qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,592,640
<p>I have a base array like below.</p> <pre><code>const arr1 = [ {id:'1',city:'Sydney',distance:100,yearhalf:'2022_1'}, {id:'2',city:'Melbourne',distance:70,yearhalf:'2022_1'}, {id:'3',city:'Perth',distance:65,yearhalf:'2022_1'}, {id:'4',city:'Sydney',distance:89,yearhalf:'2022_2'}, {id:'5',city:'Melbourne',distance:40,yearhalf:'2022_2'}, {id:'6',city:'Perth',distance:40,yearhalf:'2022_2'} ] </code></pre> <p>The idea is to group the array elements by &quot;yearhalf&quot;.I can achieve that with below approach.</p> <pre><code>const groupedArray = arr1((acc,item)=&gt;{ const itemIndex = acc.findIndex(i=&gt;i.yearhalf === item.yearhalf); if(itemIndex !== -1){ acc[itemIndex][item.city]=[item.distance] } else{ acc.push({ [item.city]:[item.distance], yearhalf:item.yearhalf }) } return acc; },[]) </code></pre> <p>The result array will be like below. <strong>Currently at this level.</strong></p> <pre><code>[ {yearhalf:'2022_1',Sydney:[100],Melbourne:[70],Perth:[65]}, {yearhalf:'2022_2',Sydney:[89],Melbourne:[40],Perth:[40]}, ] </code></pre> <p>What I want to do is, <strong>if there are multiple occurrences of same &quot;city&quot; and same &quot;yearhalf&quot; combinations(with different id field of course), push only those distances to existing results</strong>. So having additional entries like below in the initial array(arr1) would change the above result.</p> <pre><code>{id:'7',city:'Sydney',distance:50,yearhalf:'2022_1'}, {id:'8',city:'Melbourne',distance:40,yearhalf:'2022_1'} </code></pre> <p>Since we already have a yearhalf named '2022_1' it should add the city distance to the already existing cityname(Sydney/Melbourne etc) array like below</p> <pre><code>[ {yearhalf:'2022_1',Sydney:[100,50],Melbourne:[70,40],Perth:[65]}, {yearhalf:'2022_2',Sydney:[89],Melbourne:[40],Perth:[40]}, ] </code></pre> <p><strong>Note</strong>: The city name will always be one of Sydney/Melbourne/Perth. Year halves can be have more instances(YYYY_1,YYYY_2) but since initially grouping by them shouldn't cause much of a problem.</p> <p>Thanks in advance!</p>
[ { "answer_id": 74593716, "author": "John Rotenstein", "author_id": 174777, "author_profile": "https://Stackoverflow.com/users/174777", "pm_score": 1, "selected": false, "text": "contend_decode = base64.b64decode(event['body'])\n event['body'] content contend_decode = base64.b64decode(event['content'])\n" }, { "answer_id": 74594176, "author": "Shmack", "author_id": 3155240, "author_profile": "https://Stackoverflow.com/users/3155240", "pm_score": 2, "selected": false, "text": "event['body'] event['body'] \"\\x04\\x08-P�\\x10,Gh�m\\x0c\\x06K����Te�U�-��\\r\\x01�Y��l�,3�\\x11�Q�4$�........6��\\x1872Ip�d�p\\x1d�M�PX�0`�x�0����d�\\x0f�\\x0c.ǃ��\\x12\\x00\\x00\\r \\x00\\x00\\x01\\x18��........\"\n \"TWFueSBoYW5kcyBtYWtlIGxpZ2h0IHdvcmsu\" b64.b64decode(\"TWFueSBoYW5kcyBtYWtlIGxpZ2h0IHdvcmsu\") a = b\"Many hands make light work.\" b = list(a) [77, 97, 110, 121, 32, 104, 97, 110, 100, 115, 32, 109, 97, 107, 101, 32, 108, 105, 103, 104, 116, 32, 119, 111, 114, 107, 46] \"\".join([hex(c).replace(\"0x\", \"\\\\x\") for c in b]) \\x4d\\x61\\x6e\\x79\\x20\\x68\\x61\\x6e\\x64\\x73\\x20\\x6d\\x61\\x6b\\x65\\x20\\x6c\\x69\\x67\\x68\\x74\\x20\\x77\\x6f\\x72\\x6b\\x2e with open(filename, \"rb\") as f; a = f.read() event['body'] b\"hello world\" with open()... event['body'] \\x event['body'] \"\\x1872Ip�d�p\" a = \"hello world\"\nb = a.encode(\"utf-8\")\n# or\nc = bytes(a, \"utf-8\")\n# or - the one below I think defaults to utf8\na = b\"hello world\"\n\n# the closest I could get to hex representation of the string was from this\n# \"\".join([hex(ord(c)).replace(\"0x\", \"\\\\x\") for c in a])\n isBase64Encoded isBase64Encoded event['body'] import base64\n# pre edit\nif not event['isBase64Encoded']:\n event['body'] = bytes(event[body], \"whatever that encoding is\").decode()\n # b64encode takes a string and converts it to a bytes like object.\n # b64decode takes a bytes like object and converts it to a string.\n event['body'] = base64.b64decode(event['body'])\nprint(event['body'])\n\n# post edit\n# you might be able to read bytes with an arbitrary encoding using BytesIO\nfrom io import BytesIO \n\nif event['isBase64Encoded']:\n # this would've been sent as the default according to my notes from the edit\n # take the string, convert it to bytes, then decode it - should be a base64 string with a utf8 encoding\n event['body'] = bytes(event['body']).decode()\n # decode the utf8 string to base64 bytes\n event['body'] = base64.b64decode(event['body'])\nelse:\n #event['body'] = bytes(event[body], some encoding)\n event['body'] = BytesIO(event[body]).read()\n decode() base64decode() response = client.put_object(\n #Body=bytes(event[\"body\"], encoding),\n # event['body'] should already be bytes by now as per the post edit comments\n Body=event[\"body\"],\n Bucket=\"my_bucket\",\n #ContentEncoding=event[\"multiValueHeaders\"][\"Accept-Encoding\"],\n ContentType=event[\"multiValueHeaders\"][\"Content-Type\"],\n Key=\"my/object/name.mp4\"\n)\n put_object() isBase64Encoded event['body'] put_object() ContentEncoding import base64\nimport boto3\nimport os\n\ns3_client = boto3.client('s3')\nbucket_name = os.environ['S3_BUCKET_NAME']\n\n\ndef lambda_handler(event, context):\n if not event['isBase64Encoded']:\n try:\n event['body'] = bytes(event[body], \"whatever that encoding is\").decode()\n except:\n return {\n # AWS probably returns a 403, so maybe return something different for debugging?\n 'statusCode': 406,\n 'body': 'Misconfigured object.'\n }\n else:\n try:\n event['body'] = base64.b64decode(event['body'])\n except:\n return {\n # AWS probably returns a 403, so maybe return something different for debugging?\n 'statusCode': 406,\n 'body': 'Misconfigured object.'\n }\n\n try:\n response = client.put_object(\n Body=bytes(event[\"body\"], encoding),\n Bucket=\"my_bucket\",\n #ContentEncoding=event[\"multiValueHeaders\"][\"Accept-Encoding\"],\n ContentType=event[\"multiValueHeaders\"][\"Content-Type\"],\n Key=\"my/object/name.mp4\"\n )\n except:\n return {\n # AWS probably returns a 403, so maybe return something different for debugging?\n 'statusCode': 406,\n 'body': 'Misconfigured object.'\n }\n else:\n print(response)\n return {\n 'statusCode': 200,\n 'body': 'File uploaded'\n }\n import base64\nimport boto3\nimport os\nfrom io import BytesIO\n\ns3_client = boto3.client('s3')\nbucket_name = os.environ['S3_BUCKET_NAME']\n\n\ndef lambda_handler(event, context):\n\n if event['isBase64Encoded']:\n # this would've been sent as the default according to my notes from the edit\n # take the string, convert it to bytes, then decode it - should be a base64 string with a utf8 encoding\n event['body'] = bytes(event['body']).decode()\n # decode the utf8 string to base64 bytes\n event['body'] = base64.b64decode(event['body'])\n else:\n #event['body'] = bytes(event[body], some encoding)\n event['body'] = BytesIO(event[body]).read()\n\n try:\n response = client.put_object(\n Body=bytes(event[\"body\"], encoding),\n Bucket=\"my_bucket\",\n #ContentEncoding=event[\"multiValueHeaders\"][\"Accept-Encoding\"],\n ContentType=event[\"multiValueHeaders\"][\"Content-Type\"],\n Key=\"my/object/name.mp4\"\n )\n except:\n return {\n # AWS probably returns a 403, so maybe return something different for debugging?\n 'statusCode': 406,\n 'body': 'Misconfigured object.'\n }\n else:\n print(response)\n return {\n 'statusCode': 200,\n 'body': 'File uploaded'\n }\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74592640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15781662/" ]
74,592,645
<p>I am studying a Haskell course since I am total beginner. There is a task which I am not able to solve although I tried many times.</p> <p>The task is to determine the most general type of following function:</p> <pre><code>f x _ False = x f _ x y = maybe 42 (g y) x </code></pre> <p>providing we know that <code>g :: a -&gt; [a] -&gt; b</code></p> <p>Can anyone help me? Thank you</p> <p>I tried to determine <code>y :: Bool, g :: Bool -&gt; [Bool] -&gt; b(?)</code> But I am not sure what should be &quot;x&quot; 'cause from the first row we could say that it can be <code>maybe 42 (g y) x</code> but there is another &quot;x&quot; in the expression.</p> <p>So maybe the type of the <code>f</code> is <code>f :: [Bool] -&gt; [Bool] -&gt; Bool -&gt; [Bool]</code>?</p>
[ { "answer_id": 74592798, "author": "Willem Van Onsem", "author_id": 67579, "author_profile": "https://Stackoverflow.com/users/67579", "pm_score": 2, "selected": false, "text": "f f :: a -> b -> c -> d\n False Bool c ~ Bool x x a d a ~ d maybe maybe :: f -> (e -> f) -> Maybe e -> f 42 f Num Num f maybe 42 (g y) x f a f ~ a maybe maybe :: Num a => a -> (e -> a) -> Maybe e -> a maybe 42 (g y) x x f b ~ Maybe e g y g :: g -> [g] -> h g y maybe e ~ [g] a ~ h y Bool g y g ~ Bool g g :: Bool -> [Bool] -> a f :: a -> b -> c -> d\nmaybe :: f -> (e -> f) -> Maybe e -> f\ng :: g -> [g] -> h\na ~ d\nc ~ Bool\nNum f\nf ~ a\nb ~ Maybe e\ng ~ Bool\ne ~ [g]\na ~ h\ng ~ Bool\n f f :: a -> b -> c -> d\n-> f :: a -> b -> c -> a\n-> f :: a -> b -> Bool -> a\n-> f :: Num f => f -> b -> Bool -> f\n-> f :: Num f => f -> Maybe e -> Bool -> f\n-> f :: Num f => f -> Maybe [g] -> Bool -> f\n-> f :: Num f => f -> Maybe [Bool] -> Bool -> f\n f :: Num f => f -> Maybe [Bool] -> Bool -> f f :: Num a => a -> Maybe [Bool] -> Bool -> a ghci ghci> import Data.Maybe\nghci> :{\nghci| g :: a -> [a] -> b\nghci| g = undefined\nghci| :}\nghci> :{\nghci| f x _ False = x\nghci| f _ x y = maybe 42 (g y) x\nghci| :}\nghci> :t f\nf :: Num p => p -> Maybe [Bool] -> Bool -> p\n ghci" }, { "answer_id": 74592874, "author": "Fyodor Soikin", "author_id": 180286, "author_profile": "https://Stackoverflow.com/users/180286", "pm_score": 2, "selected": false, "text": "x x y :: Bool g :: Bool -> [Bool] -> b b g y :: [Bool] -> b maybe :: p -> (q -> p) -> Maybe q -> p q ~ [Bool] g y p ~ Int 42 g :: Bool -> [Bool] -> Int x :: Maybe [Bool] maybe maybe Int f :: Int -> Maybe [Bool] -> Bool -> Int\n 42 Int Num Int Num f :: Num a => a -> Maybe [Bool] -> Bool -> a\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74592645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20616664/" ]
74,592,660
<p>how to select only the parent element with a class?</p> <ul> <li><p>❌ not all elements with a class like it do <code>document.querySelectorAll(&quot;.mycard&quot;)</code></p> </li> <li><p>✅ but only the first parent element with the class,</p> <ul> <li>and this element that we take don't need to have a parent with <code>.mycard</code></li> </ul> </li> </ul> <p>it needs to return an array with all the divs that meet these conditions, and should work with every deep tree (10 of deep is a good point it is difficult to do)</p> <ul> <li>so it should not consider a div if not have the class, and go deep until finds the class we want, breaks, tries to search to others and repeat the process, and return us an array.</li> <li>if we find the wanted class, we add it to the array to return BUT <ul> <li>we need to check if the nested divs continue or not <ul> <li>if continue and we don't any other nested thing is fine don't return anything new</li> <li>if it stops we need to search if there is another div with class, if add it to the array and repeat process until we finish the tree deep.</li> </ul> </li> </ul> </li> </ul> <p>here is an example where you try your code:</p> <pre class="lang-html prettyprint-override"><code> &lt;div class=&quot;mycard&quot;&gt; &lt;!-- should get the parent only --&gt; &lt;div class=&quot;mycard&quot;&gt; &lt;div class=&quot;mycard&quot;&gt; &lt;div class=&quot;mycard&quot;&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;mycard&quot;&gt; &lt;!-- should get also this with a array of the fist and second --&gt; &lt;div class=&quot;mycard&quot;&gt; &lt;div class=&quot;mycard&quot;&gt; &lt;div class=&quot;mycard&quot;&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;another-div&quot;&gt; &lt;div class=&quot;mycard&quot;&gt; &lt;!-- should get also this that isn't in body directly --&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;another-div&quot;&gt; &lt;div class=&quot;foo&quot;&gt; &lt;div class=&quot;bar&quot;&gt; &lt;div class=&quot;mycard&quot;&gt; &lt;!-- should get also this that isn't in body directly --&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;another-div&quot;&gt; &lt;div class=&quot;foo&quot;&gt; &lt;div class=&quot;bar&quot;&gt; &lt;div class=&quot;mycard&quot;&gt; &lt;!-- this --&gt; &lt;div class=&quot;boo&quot;&gt; &lt;div class=&quot;mycard&quot;&gt; &lt;!-- also this --&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;mycard&quot;&gt; &lt;!-- this --&gt; &lt;div class=&quot;boo&quot;&gt; &lt;div class=&quot;mycard&quot;&gt; &lt;!-- also this --&gt; &lt;div class=&quot;mycard&quot;&gt; &lt;div class=&quot;mycard&quot;&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- returns [mycard, mycard, mycard, mycard, ...] 8 in total here, loopable in forEach --&gt; </code></pre> <p>returns [mycard, mycard, mycard, mycard, ...] 8 in total here, loopable in forEach</p>
[ { "answer_id": 74592716, "author": "Michael M.", "author_id": 13376511, "author_profile": "https://Stackoverflow.com/users/13376511", "pm_score": 3, "selected": true, "text": "document.getElementsByClassName .filter() let els = [...document.getElementsByClassName('mycard')];\nels = els.filter(el => !el.parentNode.classList.contains('mycard'));\n\nconsole.log(els); <div class=\"mycard\">\n <!-- should get the parent only -->\n <div class=\"mycard\">\n <div class=\"mycard\">\n <div class=\"mycard\"></div>\n </div>\n </div>\n</div>\n\n<div class=\"mycard\">\n <!-- should get also this with a array of the fist and second -->\n <div class=\"mycard\">\n <div class=\"mycard\">\n <div class=\"mycard\"></div>\n </div>\n </div>\n</div>\n\n<div class=\"another-div\">\n <div class=\"mycard\">\n <!-- should get also this that isn't in body directly -->\n </div>\n</div>\n\n<div class=\"another-div\">\n <div class=\"foo\">\n <div class=\"bar\">\n <div class=\"mycard\">\n <!-- should get also this that isn't in body directly -->\n </div>\n </div>\n </div>\n</div>\n\n<!-- returns [mycard, mycard, mycard, mycard] loopable in forEach -->" }, { "answer_id": 74593085, "author": "EDITH", "author_id": 20616524, "author_profile": "https://Stackoverflow.com/users/20616524", "pm_score": 1, "selected": false, "text": "//this will select all \"mycard\" classed elements \n//which are not descendants of any \"mycard\" classed elements.\n\ndocument.querySelectorAll(\".mycard:not(.mycard .mycard)\");\n $(\".mycard\").not('.mycard .mycard');\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74592660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19485937/" ]
74,592,707
<p>I have a data frame with a column called ‘full_name’ that presents two teams, for example: • ‘Man U to win Liverpool to win’ • ‘Liverpool to win Man U to win’ • ‘Chelsea to win Arsenal to win’ <em>And so on…</em></p> <p>I would like to be able to differentiate the teams into North and South, so that if ‘Man U to win Liverpool to win’ or ‘Liverpool to win Man U to win’ are presented, then this is coded as ‘North’, whereas if ‘Chelsea to win Arsenal to win’ is presented, this is coded as ‘South’, and so on.</p> <pre><code>levels(raw_data$full_name)[levels(raw_data$full_name)== &quot;Man U to win Liverpool to win&quot;] &lt;- 'North' levels(raw_data$full_name)[levels(raw_data$full_name)== &quot;Liverpool to win Man U to win&quot;] &lt;- 'North' levels(raw_data$full_name)[levels(raw_data$full_name)== &quot;Chelsea to win Arsenal to win&quot;] &lt;- 'South' </code></pre> <p>The code above does not produce any error, however the dataframe remains unchanged, and there is not producing the desired output. Is a way to do this?</p>
[ { "answer_id": 74592716, "author": "Michael M.", "author_id": 13376511, "author_profile": "https://Stackoverflow.com/users/13376511", "pm_score": 3, "selected": true, "text": "document.getElementsByClassName .filter() let els = [...document.getElementsByClassName('mycard')];\nels = els.filter(el => !el.parentNode.classList.contains('mycard'));\n\nconsole.log(els); <div class=\"mycard\">\n <!-- should get the parent only -->\n <div class=\"mycard\">\n <div class=\"mycard\">\n <div class=\"mycard\"></div>\n </div>\n </div>\n</div>\n\n<div class=\"mycard\">\n <!-- should get also this with a array of the fist and second -->\n <div class=\"mycard\">\n <div class=\"mycard\">\n <div class=\"mycard\"></div>\n </div>\n </div>\n</div>\n\n<div class=\"another-div\">\n <div class=\"mycard\">\n <!-- should get also this that isn't in body directly -->\n </div>\n</div>\n\n<div class=\"another-div\">\n <div class=\"foo\">\n <div class=\"bar\">\n <div class=\"mycard\">\n <!-- should get also this that isn't in body directly -->\n </div>\n </div>\n </div>\n</div>\n\n<!-- returns [mycard, mycard, mycard, mycard] loopable in forEach -->" }, { "answer_id": 74593085, "author": "EDITH", "author_id": 20616524, "author_profile": "https://Stackoverflow.com/users/20616524", "pm_score": 1, "selected": false, "text": "//this will select all \"mycard\" classed elements \n//which are not descendants of any \"mycard\" classed elements.\n\ndocument.querySelectorAll(\".mycard:not(.mycard .mycard)\");\n $(\".mycard\").not('.mycard .mycard');\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74592707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12742992/" ]
74,592,710
<p>I need to listen for clicks on <code>&lt;input/&gt;</code> elements. This is my code</p> <pre><code>&lt;script&gt; document.getElementsByClassName(&quot;form-control&quot;).addEventListener(&quot;click&quot;, function(e){ alert(&quot;Listener added&quot;); }); &lt;/script&gt; </code></pre> <p>But I'm getting this error:</p> <pre><code>Uncaught TypeError: document.getElementsByClassName(...).addEventListener is not a function </code></pre> <p>Any ideas?</p>
[ { "answer_id": 74592797, "author": "eelpcik", "author_id": 20094864, "author_profile": "https://Stackoverflow.com/users/20094864", "pm_score": 0, "selected": false, "text": "document.getElementsByClassName(\"form-control\").forEach(element => {\n element.onclick = event => {\n alert(\"Listener added\");\n }\n}); \n document.getElementsByClassName(\"form-control\")[0].addEventListener(\"click\", function(e){\n alert(\"Listener added\");\n}); \n" }, { "answer_id": 74592916, "author": "Mala Jhora", "author_id": 20411039, "author_profile": "https://Stackoverflow.com/users/20411039", "pm_score": 1, "selected": false, "text": "getElementsByClassName() document.getElementsByClassName('form-control')[0] document.getElementsByClassName(\"form-control\")[0].addEventListener(\"click\", function(e){\n alert(\"Listener added\");\n});\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74592710", "https://Stackoverflow.com", "https://Stackoverflow.com/users/207425/" ]
74,592,719
<p>So I'm Using <code>Getx</code>'s routing in Flutter.</p> <p>I have a Product class that accepts an argument of the type <code>Product</code></p> <pre><code> const Produkt({ required this.product, }); </code></pre> <p>I handle the navigation through GetPages, like:</p> <pre><code> GetPage( name: Produkt.route, page: () =&gt; Produkt( product: Get.arguments['product'], ), ), </code></pre> <p>But of course, this only works when the arguments aren't null. How could I redirect to an error page when the arguments are null?</p>
[ { "answer_id": 74592797, "author": "eelpcik", "author_id": 20094864, "author_profile": "https://Stackoverflow.com/users/20094864", "pm_score": 0, "selected": false, "text": "document.getElementsByClassName(\"form-control\").forEach(element => {\n element.onclick = event => {\n alert(\"Listener added\");\n }\n}); \n document.getElementsByClassName(\"form-control\")[0].addEventListener(\"click\", function(e){\n alert(\"Listener added\");\n}); \n" }, { "answer_id": 74592916, "author": "Mala Jhora", "author_id": 20411039, "author_profile": "https://Stackoverflow.com/users/20411039", "pm_score": 1, "selected": false, "text": "getElementsByClassName() document.getElementsByClassName('form-control')[0] document.getElementsByClassName(\"form-control\")[0].addEventListener(\"click\", function(e){\n alert(\"Listener added\");\n});\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74592719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14775496/" ]
74,592,740
<p>I have a code, but I don't really know python, so I have a problem. I know that the insert isn't right for strings but I don't know how can I insert?</p> <pre><code>original_string = input(&quot;What's yout sentence?&quot;) add_character = input(&quot;What char do you want to add?&quot;) slice = int(input(&quot;What's the step?&quot;)) for i in original_string[::slice]: original_string.insert(add_character) print(&quot;The string after inserting characters: &quot; + str(original_string)) </code></pre> <p>So I need help, how can I rewrite this? That's the homework for university and we haven't studied def so I can't use it</p>
[ { "answer_id": 74592797, "author": "eelpcik", "author_id": 20094864, "author_profile": "https://Stackoverflow.com/users/20094864", "pm_score": 0, "selected": false, "text": "document.getElementsByClassName(\"form-control\").forEach(element => {\n element.onclick = event => {\n alert(\"Listener added\");\n }\n}); \n document.getElementsByClassName(\"form-control\")[0].addEventListener(\"click\", function(e){\n alert(\"Listener added\");\n}); \n" }, { "answer_id": 74592916, "author": "Mala Jhora", "author_id": 20411039, "author_profile": "https://Stackoverflow.com/users/20411039", "pm_score": 1, "selected": false, "text": "getElementsByClassName() document.getElementsByClassName('form-control')[0] document.getElementsByClassName(\"form-control\")[0].addEventListener(\"click\", function(e){\n alert(\"Listener added\");\n});\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74592740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20616770/" ]
74,592,753
<p>What does this type of notation mean?</p> <pre><code> render() { const {isAuth, error} = this.state; document.getElementById(&quot;root&quot;).innerHTML = ` &lt;div style=&quot;color: ${error &amp;&amp; &quot;red&quot;}&quot;&gt; ${isAuth ? &quot;Welcome back!&quot; : error} &lt;/div&gt; `; } </code></pre> <p>I do not understand why is it written like this. And what does it mean in a style property?</p>
[ { "answer_id": 74592955, "author": "NerdyGamer", "author_id": 17168449, "author_profile": "https://Stackoverflow.com/users/17168449", "pm_score": 1, "selected": false, "text": "result = '' && 'foo'; // result is assigned \"\" (empty string)\nresult = 2 && 0; // result is assigned 0\nresult = 'foo' && 4; // result is assigned 4\n '' 2 'foo' error `<div style=\"color: ${error && \"red\"}\">`\n `<div style=\"color:red\">`\n false `<div style=\"color:false\">`\n \"\" `<div style=\"color:\">`\n \"foo\" `<div style=\"color:red\">`\n" }, { "answer_id": 74592971, "author": "Boguz", "author_id": 5509709, "author_profile": "https://Stackoverflow.com/users/5509709", "pm_score": 0, "selected": false, "text": "const apple = true;\nconst ananas = false;\n\nconsole.log('1', apple && 'it is an apple'); // returns \"1 it is an apple\"\nconsole.log('2', ananas && 'it is an ananas'); // returns \"false\" conditionOne && doSomething if (conditionOne) { doSomething }" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74592753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19746715/" ]
74,592,759
<p>So here is the code:</p> <pre><code>#include &lt;stdio.h&gt; int main() { char str1[] =&quot;Hello&quot;, str2[20] =&quot;Hi&quot;; char *p =&quot;Hello&quot;, *s =&quot;Hi&quot;; str1 = &quot;Adieu&quot;; return 0; } </code></pre> <p>Now my Book gives this reason</p> <pre><code>error, constant pointer cannot change </code></pre> <p>And when I run it, I get error as :</p> <pre><code>error: assignment to expression with array type </code></pre> <p>My question is why does my book says so ?, From where did pointers come here ?</p> <p><em>The book is <strong>Let us C 18th edition</strong> (latest edition at the time the question was posted) by Yashavant P. Kanetkar incase you need refence.</em></p>
[ { "answer_id": 74592877, "author": "Haris", "author_id": 20017547, "author_profile": "https://Stackoverflow.com/users/20017547", "pm_score": 0, "selected": false, "text": "str1[] = \"Hello\";\n str2 = str1;\n" }, { "answer_id": 74593119, "author": "Andreas Wenzel", "author_id": 12149471, "author_profile": "https://Stackoverflow.com/users/12149471", "pm_score": 4, "selected": true, "text": "str1 = \"Adieu\";\n str error, constant pointer cannot change\n error: assignment to expression with array type\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74592759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18246254/" ]
74,592,782
<p>I am doing some operations on a data.table and getting a result. So far so good. Next, I want the result to also show the sums across some columns, but I can't get that to work.</p> <p>I filter my table by rows where x1=1, and compute a metric by Group1:</p> <pre><code>dt[x1 == 1, .N, by = c(&quot;Group1&quot;)][, &quot;%&quot; := round(N /sum(N) * 100, 0)] [ ] </code></pre> <p>giving</p> <pre><code> Group1 N % 1: 2 6 40 2: 1 6 40 3: 3 2 13 4: 5 1 7 </code></pre> <p>I would just like to add a row to the above table that gives the sum across all columns.</p> <p>I can just do</p> <pre><code>colSums(.Last.value) </code></pre> <p>and get the answer in a in a separate console, but what if I wanted to just append a new row to the above table itself, something like:</p> <pre><code> Group1 N % 1: 2 6 40 2: 1 6 40 3: 3 2 13 4: 5 1 7 ColSum: -- 15 100 </code></pre>
[ { "answer_id": 74593271, "author": "r2evans - GO NAVY BEAT ARMY", "author_id": 3358272, "author_profile": "https://Stackoverflow.com/users/3358272", "pm_score": 2, "selected": true, "text": "data.table prettyDT <- function(x, ...) {\n out <- capture.output(data.table:::print.data.table(x, ...))\n nms <- rownames(x)\n gre <- gregexpr(\"^([0-9]+)(?=:)\", out, perl = TRUE)\n newnms <- nms[as.integer(regmatches(out, gre), nms)]\n wids <- nchar(newnms)\n newnms[!is.na(wids)] <- sprintf(paste0(\"%\", max(wids, na.rm = TRUE), \"s\"), newnms[!is.na(wids)])\n regmatches(out, gre)[!is.na(wids)] <- newnms[!is.na(wids)]\n pre <- strrep(\" \", diff(range(wids, na.rm = TRUE)))\n out[is.na(wids)] <- paste0(pre, out[is.na(wids)])\n cat(out, sep = \"\\n\")\n}\n out <- rbindlist(list(\n DT,\n DT[, c(.(Group1 = \"--\"), lapply(.SD, sum)), .SDcols = c(\"N\", \"%\")]\n))\nrownames(out)[nrow(out)] <- \"Colsum\"\nprettyDT(out)\n# Group1 N %\n# <char> <int> <int>\n# 1: 2 6 40\n# 2: 1 6 40\n# 3: 3 2 13\n# 4: 5 1 7\n# Colsum: -- 15 100\n DT <- setDT(structure(list(Group1 = c(\"2\", \"1\", \"3\", \"5\"), N = c(6L, 6L, 2L, 1L), \"%\" = c(40L, 40L, 13L, 7L)), class = c(\"data.table\", \"data.frame\"), row.names = c(NA, -4L)))\n" }, { "answer_id": 74593493, "author": "Yomi.blaze93", "author_id": 16087142, "author_profile": "https://Stackoverflow.com/users/16087142", "pm_score": 2, "selected": false, "text": "set.seed(10)\ndf_sample<- sample(1:nrow(iris), 10)\ndf<-iris[df_sample, ]\n df%>%\n select(Species,Sepal.Width, Petal.Length, Petal.Width)%>%\n adorn_totals(where = \"row\")\n df%>%\n select(Species,Sepal.Width, Petal.Length, Petal.Width)%>%\n adorn_totals(where = \"col\")\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74592782", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20321217/" ]
74,592,813
<p>I am trying to split the values in the location column to two different x and y columns in a csv file</p> <p>Right now it looks like this:</p> <pre><code>location [60.0, 56.0] [68.0, 74.0] [58.0, 52.0] [63.0, 53.0] [119.0, 79.0] </code></pre> <p>I want it to split the columns and get two different columns and remove the brackets so the columns look like this:</p> <pre><code>x y 60 56 68 74 58 52 63 53 119 79 </code></pre> <p>I all of these: 1.</p> <pre><code>df[['x', 'y']] = pd.DataFrame(df['location'].tolist(), index=df.index) </code></pre> <ol start="2"> <li></li> </ol> <pre><code>pd.concat([df[[0]], df['location'].str.split(',', expand=True)], axis=1 </code></pre> <ol start="3"> <li></li> </ol> <pre><code>df['location'].str.split(',', expand=True) </code></pre> <p>But recieved errors</p>
[ { "answer_id": 74593271, "author": "r2evans - GO NAVY BEAT ARMY", "author_id": 3358272, "author_profile": "https://Stackoverflow.com/users/3358272", "pm_score": 2, "selected": true, "text": "data.table prettyDT <- function(x, ...) {\n out <- capture.output(data.table:::print.data.table(x, ...))\n nms <- rownames(x)\n gre <- gregexpr(\"^([0-9]+)(?=:)\", out, perl = TRUE)\n newnms <- nms[as.integer(regmatches(out, gre), nms)]\n wids <- nchar(newnms)\n newnms[!is.na(wids)] <- sprintf(paste0(\"%\", max(wids, na.rm = TRUE), \"s\"), newnms[!is.na(wids)])\n regmatches(out, gre)[!is.na(wids)] <- newnms[!is.na(wids)]\n pre <- strrep(\" \", diff(range(wids, na.rm = TRUE)))\n out[is.na(wids)] <- paste0(pre, out[is.na(wids)])\n cat(out, sep = \"\\n\")\n}\n out <- rbindlist(list(\n DT,\n DT[, c(.(Group1 = \"--\"), lapply(.SD, sum)), .SDcols = c(\"N\", \"%\")]\n))\nrownames(out)[nrow(out)] <- \"Colsum\"\nprettyDT(out)\n# Group1 N %\n# <char> <int> <int>\n# 1: 2 6 40\n# 2: 1 6 40\n# 3: 3 2 13\n# 4: 5 1 7\n# Colsum: -- 15 100\n DT <- setDT(structure(list(Group1 = c(\"2\", \"1\", \"3\", \"5\"), N = c(6L, 6L, 2L, 1L), \"%\" = c(40L, 40L, 13L, 7L)), class = c(\"data.table\", \"data.frame\"), row.names = c(NA, -4L)))\n" }, { "answer_id": 74593493, "author": "Yomi.blaze93", "author_id": 16087142, "author_profile": "https://Stackoverflow.com/users/16087142", "pm_score": 2, "selected": false, "text": "set.seed(10)\ndf_sample<- sample(1:nrow(iris), 10)\ndf<-iris[df_sample, ]\n df%>%\n select(Species,Sepal.Width, Petal.Length, Petal.Width)%>%\n adorn_totals(where = \"row\")\n df%>%\n select(Species,Sepal.Width, Petal.Length, Petal.Width)%>%\n adorn_totals(where = \"col\")\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74592813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20616784/" ]
74,592,814
<p>My assignment is to create a subprogram that takes in 3 float values in returns the median of those 3 float values as an integer using if statements. I´ve tried a couple of ways to write this if statement but it just gives me a random value back of those 3 values I put in. My code:</p> <pre><code> function Median(Fl1, Fl2, Fl3: in Float) return Integer is begin if Fl3 &gt;= Fl1 then if Fl1 &gt;= Fl2 then return Integer(Fl1); else return Integer(Fl2); end if; elsif Fl1 &gt;= Fl3 then if Fl3 &gt;= Fl2 then return Integer(Fl3); else return Integer(Fl2); end if; elsif Fl2 &gt;= Fl3 then if Fl3 &gt;= Fl1 then return Integer(Fl3); else return Integer(Fl1); end if; end if; end Median; </code></pre> <p>How can I rewrite this to work?</p>
[ { "answer_id": 74593992, "author": "Jim Rogers", "author_id": 6854407, "author_profile": "https://Stackoverflow.com/users/6854407", "pm_score": 0, "selected": false, "text": "with Ada.Text_IO; use Ada.Text_IO;\nwith Ada.Float_Text_IO; use Ada.Float_Text_IO;\n\nprocedure Main is\n function Median (Fl1, Fl2, Fl3 : in Float) return Integer is\n type fl_status is record\n Value : Float;\n Is_Median : Boolean := True;\n end record;\n\n Status_List : array (1 .. 3) of fl_status;\n Max : Float := Float'Max (Fl1, Float'Max (Fl2, Fl3));\n Min : Float := Float'Min (Fl1, Float'Min (Fl2, Fl3));\n Result : Integer;\n begin\n Status_List (1) := (Fl1, True);\n Status_List (2) := (Fl2, True);\n Status_List (3) := (Fl3, True);\n\n -- mark the maximum value as not the median\n for I in Status_List'Range loop\n if Status_List (I).Value = Max then\n Status_List (I).Is_Median := False;\n exit;\n end if;\n end loop;\n\n -- mark the minimum value as not the median\n for I in Status_List'Range loop\n if Status_List (I).Value = Min then\n Status_List (I).Is_Median := False;\n exit;\n end if;\n end loop;\n\n -- Return the median value as an integer\n for I in Status_List'Range loop\n if Status_List (I).Is_Median then\n Result := Integer (Status_List (I).Value);\n exit;\n end if;\n end loop;\n return Result;\n end Median;\n\nbegin\n Put_Line (\"Median value is: \" & Integer'Image (Median (11.1, 1.2, -1.3)));\nend Main;\n with Ada.Text_IO; use Ada.Text_IO;\n\nprocedure Median_If is\n function Median (Fl1, Fl2, Fl3 : in Float) return Integer is\n type fl_status is record\n Value : Float;\n Is_Median : Boolean := True;\n end record;\n\n Status_List : array (1 .. 3) of fl_status;\n Max : Float;\n Min : Float;\n Result : Integer;\n begin\n Status_List (1) := (Fl1, True);\n Status_List (2) := (Fl2, True);\n Status_List (3) := (Fl3, True);\n\n -- find max value\n if Fl1 > Fl2 and then Fl1 > Fl3 then\n Max := Fl1;\n elsif Fl2 > Fl1 and then Fl2 > Fl3 then\n Max := Fl2;\n else\n Max := Fl3;\n end if;\n\n -- find min value\n if Fl1 < Fl2 and then Fl1 < Fl3 then\n Min := Fl1;\n elsif Fl2 < Fl1 and then Fl2 < Fl3 then\n Min := Fl2;\n else\n Min := Fl3;\n end if;\n\n -- mark the maximum value as not the median\n for I in Status_List'Range loop\n if Status_List (I).Value = Max then\n Status_List (I).Is_Median := False;\n exit;\n end if;\n end loop;\n\n -- mark the minimum value as not the median\n for I in Status_List'Range loop\n if Status_List (I).Value = Min then\n Status_List (I).Is_Median := False;\n exit;\n end if;\n end loop;\n\n -- Return the median value as an integer\n for I in Status_List'Range loop\n if Status_List (I).Is_Median then\n Result := Integer (Status_List (I).Value);\n exit;\n end if;\n end loop;\n return Result;\n end Median;\nbegin\n Put_Line\n (\"The median value is: \" & Integer'Image (Median (11.0, -1.0, 1.0)));\nend Median_If;\n" }, { "answer_id": 74601519, "author": "Niklas Holsti", "author_id": 15004077, "author_profile": "https://Stackoverflow.com/users/15004077", "pm_score": 2, "selected": false, "text": " function Median (A, B, C : in Float) return Integer is\n X : Float;\n -- This will be the median.\n begin\n X := Float'Min (B, C);\n if A <= X then\n -- The smallest value is A, so the median is the\n -- smaller of B and C, which is already in X.\n null;\n else\n -- The smallest value is not A.\n X := Float'Max (B, C);\n if A >= X then\n -- The largest value is A, so the median is the\n -- larger of B and C, which is already in X.\n null;\n else\n -- The A parameter is neither the smallest nor\n -- the largest value, so it is the median.\n X := A;\n end if;\n end if;\n return Integer (X);\n end Median;\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74592814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20153118/" ]
74,592,849
<p>I created a favicon from <a href="https://www.favicon.cc" rel="nofollow noreferrer">https://www.favicon.cc</a> and replaced the existing favicon.ico to mine but it didn't change to my favicon.ico and still showing the previous icon</p> <p>Code:</p> <p>link rel=&quot;icon&quot; href=&quot;/favicon.ico&quot;</p> <p>The location is at the same as for previous one</p> <p>main.html(I am using VUE)</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;!-- favicon added --&gt; &lt;link rel=&quot;icon&quot; href=&quot;/favicon.ico&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt; &lt;title&gt;...&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div id=&quot;app&quot;&gt;&lt;/div&gt; &lt;!-- main typescript file added --&gt; &lt;script type=&quot;module&quot; src=&quot;/&quot;&gt;. &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "answer_id": 74592933, "author": "bc1121", "author_id": 3754348, "author_profile": "https://Stackoverflow.com/users/3754348", "pm_score": -1, "selected": false, "text": "<!DOCTYPE html>\n<html>\n\n<head>\n <link rel=\"icon\" type=\"image/x-icon\" href=\"/favicon.ico\">\n</head>\n\n<body>\n</body>\n\n</html>" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74592849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20543349/" ]
74,592,856
<p>I have a custom login page, which once the user logs in, takes him back to the same page, I would like there to be a redirect on the home page in php, I found this redirect php file, how do I modify it to get users to home?</p> <p>I include all files that may be of interest</p> <p>Thanks</p> <p>stm-lms-user-redirect.php</p> <pre><code>&lt;?php $redirect_url = get_site_url(); if(is_user_logged_in()) { $lms_settings = get_option('stm_lms_settings', array()); $user_url = (!empty($lms_settings['user_url'])) ? $lms_settings['user_url'] : '/lms-user'; $redirect_url .= $user_url . '/' . get_current_user_id(); } //wp_safe_redirect($redirect_url); </code></pre> <p>**stm-lms-user.php**</p> <pre><code> &lt;?php do_action( 'stm_lms_before_user_header' ); do_action( 'stm_lms_template_main' ); $current_user = STM_LMS_User::get_current_user( '', true, true ); $tpl = 'account/private/main'; stm_lms_register_style( 'user' ); if ( function_exists( 'vc_asset_url' ) ) { wp_enqueue_style( 'stm_lms_wpb_front_css', vc_asset_url( 'css/js_composer.min.css' ), array(), time() ); } ?&gt; &lt;?php STM_LMS_Templates::show_lms_template( 'modals/preloader' ); ?&gt; &lt;div class=&quot;stm-lms-wrapper stm-lms-wrapper-user user-account-page&quot;&gt; &lt;?php do_action( 'stm_lms_admin_after_wrapper_start', $current_user ); ?&gt; &lt;?php STM_LMS_Templates::show_lms_template( 'account/private/parts/become_instructor_info', compact( 'current_user' ) ); ?&gt; &lt;div class=&quot;container&quot;&gt; &lt;?php if ( ! empty( $tpl ) ) { STM_LMS_Templates::show_lms_template( $tpl, compact( 'current_user' ) );} ?&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>**login.php**</p> <pre><code> &lt;div id=&quot;stm-lms-login&lt;?php if (isset($form_position)) esc_attr_e($form_position); ?&gt;&quot; class=&quot;stm-lms-login active vue_is_disabled&quot; v-init=&quot;site_key = '&lt;?php echo stm_lms_filtered_output($site_key); ?&gt;'&quot; v-bind:class=&quot;{'is_vue_loaded' : vue_loaded}&quot;&gt; &lt;div class=&quot;stm-lms-login__top&quot;&gt; &lt;?php if (defined('WORDPRESS_SOCIAL_LOGIN_ABS_PATH') and apply_filters('stm_lms_show_social_login', true)) { do_action('wordpress_social_login'); } ?&gt; &lt;h3&gt;&lt;?php esc_html_e('Login', 'masterstudy-lms-learning-management-system'); ?&gt;&lt;/h3&gt; &lt;?php do_action('stm_lms_login_end'); ?&gt; &lt;/div&gt; &lt;div class=&quot;stm_lms_login_wrapper&quot;&gt; &lt;div class=&quot;form-group&quot;&gt; &lt;label class=&quot;heading_font&quot;&gt; &lt;?php echo apply_filters('stm_lms_login_label', esc_html__('Username', 'masterstudy-lms-learning-management-system')); ?&gt; &lt;/label&gt; &lt;input class=&quot;form-control&quot; type=&quot;text&quot; name=&quot;login&quot; v-model=&quot;login&quot; v-on:keyup.enter=&quot;logIn()&quot; placeholder=&quot;&lt;?php esc_html_e('Enter username', 'masterstudy-lms-learning-management-system'); ?&gt;&quot;/&gt; &lt;/div&gt; &lt;div class=&quot;form-group&quot;&gt; &lt;label class=&quot;heading_font&quot;&gt; &lt;?php echo apply_filters('stm_lms_password_label', esc_html__('Password', 'masterstudy-lms-learning-management-system')); ?&gt; &lt;/label&gt; &lt;input class=&quot;form-control&quot; type=&quot;password&quot; name=&quot;password&quot; v-model=&quot;password&quot; v-on:keyup.enter=&quot;logIn()&quot; placeholder=&quot;&lt;?php esc_html_e('Enter password', 'masterstudy-lms-learning-management-system'); ?&gt;&quot;/&gt; &lt;/div&gt; &lt;div class=&quot;stm_lms_login_wrapper__actions&quot;&gt; &lt;label class=&quot;stm_lms_styled_checkbox stm_lms_remember_me&quot;&gt; &lt;span class=&quot;stm_lms_styled_checkbox__inner&quot;&gt; &lt;input type=&quot;checkbox&quot; name=&quot;remember_me&quot; v-model=&quot;remember&quot; v-on:keyup.enter=&quot;logIn()&quot; /&gt; &lt;span&gt;&lt;i class=&quot;fa fa-check&quot;&gt;&lt;/i&gt; &lt;/span&gt; &lt;/span&gt; &lt;span&gt;&lt;?php esc_html_e('Remember me', 'masterstudy-lms-learning-management-system'); ?&gt;&lt;/span&gt; &lt;/label&gt; &lt;span class=&quot;lostpassword&quot; @click.prevent=&quot;open_lost_password = !open_lost_password&quot; title=&quot;&lt;?php esc_html_e('Lost Password', 'masterstudy-lms-learning-management-system'); ?&gt;&quot;&gt; &lt;?php esc_html_e('Lost Password', 'masterstudy-lms-learning-management-system'); ?&gt; &lt;/span&gt; &lt;a href=&quot;#&quot; class=&quot;btn btn-default&quot; v-bind:class=&quot;{'loading': loading}&quot; @click.prevent=&quot;logIn()&quot;&gt; &lt;span&gt;&lt;?php echo _x('Login', 'Login button', 'masterstudy-lms-learning-management-system'); ?&gt;&lt;/span&gt; &lt;/a&gt; &lt;/div&gt; &lt;div class=&quot;stm_lms_lost_password_form&quot; v-if=&quot;open_lost_password&quot;&gt; &lt;div class=&quot;form-group&quot;&gt; &lt;label class=&quot;heading_font&quot;&gt; &lt;?php echo apply_filters('stm_lms_lost_password_label', esc_html__('Login/E-mail', 'masterstudy-lms-learning-management-system')); ?&gt; &lt;/label&gt; &lt;input class=&quot;form-control&quot; type=&quot;text&quot; name=&quot;login&quot; v-model=&quot;lost_password&quot; placeholder=&quot;&lt;?php esc_html_e('Enter login/e-mail', 'masterstudy-lms-learning-management-system'); ?&gt;&quot;/&gt; &lt;/div&gt; &lt;a href=&quot;#&quot; class=&quot;btn btn-default&quot; v-bind:class=&quot;{'loading': lost_password_process}&quot; @click.prevent=&quot;lostPassword()&quot;&gt; &lt;span&gt;&lt;?php esc_html_e('Send', 'masterstudy-lms-learning-management-system'); ?&gt;&lt;/span&gt; &lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;transition name=&quot;slide-fade&quot;&gt; &lt;div class=&quot;stm-lms-message&quot; v-bind:class=&quot;status&quot; v-if=&quot;message&quot; v-html=&quot;message&quot;&gt; &lt;/div&gt; &lt;/transition&gt; &lt;/div&gt; &lt;?php if (defined('APSL_VERSION') and apply_filters('stm_lms_show_social_login', true)) { echo do_shortcode(&quot;[apsl-login-lite login_text='']&quot;); } ?&gt; &lt;?php if (defined('NSL_PATH_FILE') and apply_filters('stm_lms_show_social_login', true)) { echo do_shortcode('[nextend_social_login]'); } ?&gt; &lt;?php do_action('stm_lms_login_section_end'); ?&gt; </code></pre> <p>I have tried to modify the code without success... I add &quot;header('Location: https://url/');&quot; in stm-lms-user-redirect.php but not work.</p> <p>I have a custom login page, which once the user logs in, takes him back to the same page, I would like there to be a redirect on the home page in php, I found this redirect php file, how do I modify it to get users to home?</p> <p>I include all files that may be of interest</p> <p>Thanks</p>
[ { "answer_id": 74592933, "author": "bc1121", "author_id": 3754348, "author_profile": "https://Stackoverflow.com/users/3754348", "pm_score": -1, "selected": false, "text": "<!DOCTYPE html>\n<html>\n\n<head>\n <link rel=\"icon\" type=\"image/x-icon\" href=\"/favicon.ico\">\n</head>\n\n<body>\n</body>\n\n</html>" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74592856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20584654/" ]
74,592,866
<p>I have a collection of documents such as:</p> <pre class="lang-json prettyprint-override"><code>{ _id: 5, responses: [ { staff: false, timestamp: 1000 }, { staff: true, timestamp: 1500 } ] } </code></pre> <p>I have a function (using <code>$function</code>) used to apply some custom logic with the <code>responses</code> array:</p> <pre class="lang-js prettyprint-override"><code>const diffs=[]; let current; for (let i = 0; i &lt; responses.length; i++) { if (i+1&gt;=responses.length) break; if (!current &amp;&amp; !responses[i].staff) current = responses[i]; if (!current) continue; const next = responses[i+1]; if (!next.staff) continue; diffs.push(next.timestamp - current.timestamp); current = undefined; } return diffs; </code></pre> <p>which basically returns array of numbers like <code>[500, 1000, 10]</code> etc. It can also potentially return an empty array (<code>[]</code>).</p> <p>I want to basically combine all arrays into one (say one document returns <code>[5, 10]</code> and the next one returns <code>[1, 2]</code>, the result would be <code>[5, 10, 1, 2]</code> -- order doesn't matter) and then calculate the average using <code>$avg</code>.</p> <p>I was reading MongoDB docs and found <a href="https://www.mongodb.com/docs/manual/reference/operator/aggregation/concatArrays/" rel="nofollow noreferrer"><code>$concatArrays</code></a>, so to my understanding the process should be:</p> <ol> <li>Calculate diffs for each document, which will end up with an array like <code>[[1, 2], [3, 4], [5, 6, 7], [], ...]</code></li> <li>Use <code>$concatArrays</code> on the value from step 1</li> <li>Use <code>$avg</code> on the array from step 2</li> </ol> <p>How should I go about making step 1? The only part I'm not sure about is how to hold a variable in the first grouping stage with the result returned from <code>$function</code>. I understand I need to do something like this:</p> <pre><code>aggregate([ {$group: {diffs: {$function: {...}}}} ]) </code></pre> <p>However, I get the error <code>MongoServerError: unknown group operator '$function'</code>.</p>
[ { "answer_id": 74592933, "author": "bc1121", "author_id": 3754348, "author_profile": "https://Stackoverflow.com/users/3754348", "pm_score": -1, "selected": false, "text": "<!DOCTYPE html>\n<html>\n\n<head>\n <link rel=\"icon\" type=\"image/x-icon\" href=\"/favicon.ico\">\n</head>\n\n<body>\n</body>\n\n</html>" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74592866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16025034/" ]
74,592,897
<p>How to convert <code>Ctrl+(any letter)</code> to <code>«Ctrl+(any letter)»</code>?</p> <p>I need like this:</p> <pre><code>Ctrl+T Ctrl+D etc. </code></pre> <p>Convert to:</p> <pre><code>«Ctrl+T» «Ctrl+D» etc. </code></pre> <p>I tried replacing this <code>(Ctrl\+.)</code> with <code>(Ctrl\+[a-zA-Z])</code>, but the result is <code>Ctrl+[a-zA-Z]</code>.</p>
[ { "answer_id": 74593117, "author": "alex-dl", "author_id": 14725508, "author_profile": "https://Stackoverflow.com/users/14725508", "pm_score": 3, "selected": true, "text": "(Ctrl\\+[a-zA-Z])\n «\\1»\n" }, { "answer_id": 74607201, "author": "The fourth bird", "author_id": 5424988, "author_profile": "https://Stackoverflow.com/users/5424988", "pm_score": 1, "selected": false, "text": "$0 Ctrl\\+[a-zA-Z]\n «$0»\n \\b \\bCtrl\\+[a-zA-Z]\\b\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74592897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19809589/" ]
74,592,935
<p>I'm building a class that gathers some of the possible JVM opcodes. I found out how to generate DUP2_X2 and DUP_X2 but not DUP2, DUP2_X1, SWAP.</p> <p>Below the code sample in which I starting gathering some of the jvm opcodes :</p> <pre class="lang-java prettyprint-override"><code>public class JvmOpCodes { long dup2x2(long[] array, int i, long l) { return array[i] = l; } int dupx2(int[] array, int i, int l) { return array[i] = l; } long lneg(long a) { return -a; } long lor(long a, long b) { return a | b; } long land(long a, long b) { return a &amp; b; } long lushr(long a, long b) { return a &gt;&gt;&gt; b; } int iushr(int a, int b) { return a &gt;&gt;&gt; b; } long lshl(long a, long b) { return a &lt;&lt; b; } float fsub(float a, float b) { return a - b; } float fadd(float a, float b) { return a + b; } float frem(float a, float b) { return a % b; } float fneg(float a) { return -a; } double drem(double a, double b) { return a % b; } double dneg(double a) { return -a; } void pop() { Math.round(0.5f); } void pop2() { Math.round(0.5d); } } </code></pre> <p>After compiling with <code>javac</code> command and running <code>javap -p -c</code>, I'm able to identify the produced JVM opcodes inside the output :</p> <pre><code>Compiled from &quot;JvmOpCodes.java&quot; public class org.apache.bcel.verifier.tests.JvmOpCodes { public org.apache.bcel.verifier.tests.JvmOpCodes(); Code: 0: aload_0 1: invokespecial #1 // Method java/lang/Object.&quot;&lt;init&gt;&quot;:()V 4: return long dup2x2(long[], int, long); Code: 0: aload_1 1: iload_2 2: lload_3 3: dup2_x2 4: lastore 5: lreturn int dupx2(int[], int, int); Code: 0: aload_1 1: iload_2 2: iload_3 3: dup_x2 4: iastore 5: ireturn long lneg(long); Code: 0: lload_1 1: lneg 2: lreturn long lor(long, long); Code: 0: lload_1 1: lload_3 2: lor 3: lreturn long land(long, long); Code: 0: lload_1 1: lload_3 2: land 3: lreturn long lushr(long, long); Code: 0: lload_1 1: lload_3 2: l2i 3: lushr 4: lreturn int iushr(int, int); Code: 0: iload_1 1: iload_2 2: iushr 3: ireturn long lshl(long, long); Code: 0: lload_1 1: lload_3 2: l2i 3: lshl 4: lreturn float fsub(float, float); Code: 0: fload_1 1: fload_2 2: fsub 3: freturn float fadd(float, float); Code: 0: fload_1 1: fload_2 2: fadd 3: freturn float frem(float, float); Code: 0: fload_1 1: fload_2 2: frem 3: freturn float fneg(float); Code: 0: fload_1 1: fneg 2: freturn double drem(double, double); Code: 0: dload_1 1: dload_3 2: drem 3: dreturn double dneg(double); Code: 0: dload_1 1: dneg 2: dreturn void pop(); Code: 0: ldc #7 // float 0.5f 2: invokestatic #8 // Method java/lang/Math.round:(F)I 5: pop 6: return void pop2(); Code: 0: ldc2_w #14 // double 0.5d 3: invokestatic #16 // Method java/lang/Math.round:(D)J 6: pop2 7: return } </code></pre> <p>However, what piece of code in Java will generate the JVM instructions DUP2, DUP2_X1, SWAP ?</p> <p>Also, an interesting related answer with demo here : <a href="https://stackoverflow.com/a/72131218/8315843">https://stackoverflow.com/a/72131218/8315843</a></p>
[ { "answer_id": 74595360, "author": "boneill", "author_id": 458561, "author_profile": "https://Stackoverflow.com/users/458561", "pm_score": 1, "selected": false, "text": " public static long example(long a) {\n return a = a + 1;\n }\n" }, { "answer_id": 74599924, "author": "Sybuser", "author_id": 8315843, "author_profile": "https://Stackoverflow.com/users/8315843", "pm_score": 1, "selected": true, "text": "DUP2_X1 long l1;\n long l2;\n \n void test(String[] s) {\n s[0] += \"s\"; // Form 1 \n l2 = l1 = 1; // Form 2 \n }\n javap JDK8 void test(java.lang.String[]);\n Code:\n 0: new #2 // class java/lang/StringBuilder\n 3: dup\n 4: invokespecial #3 // Method java/lang/StringBuilder.\"<init>\":()V\n 7: aload_1\n 8: iconst_0\n 9: dup2_x1\n 10: aaload\n 11: invokevirtual #4 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;\n 14: ldc #5 // String s\n 16: invokevirtual #4 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;\n 19: invokevirtual #6 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;\n 22: aastore\n 23: aload_0\n 24: aload_0\n 25: lconst_1\n 26: dup2_x1\n 27: putfield #7 // Field l1:J\n 30: putfield #8 // Field l2:J\n 33: return\n}\n JDK9+ makeConcatWithConstants DUP2_X1 Form 1 void test(java.lang.String[]);\n Code:\n 0: aload_1\n 1: iconst_0\n 2: dup2\n 3: aaload\n 4: invokedynamic #3, 0 // InvokeDynamic #0:makeConcatWithConstants:(Ljava/lang/String;)Ljava/lang/String;\n 9: aastore\n 10: aload_0\n 11: aload_0\n 12: lconst_1\n 13: dup2_x1\n 14: putfield #4 // Field l1:J\n 17: putfield #5 // Field l2:J\n 20: return\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74592935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8315843/" ]
74,592,937
<p>I have a :</p> <pre><code>private List&lt;String&gt; nums = new ArrayList&lt;&gt;(); </code></pre> <p>And when I do :</p> <pre><code>nums.get(0) - 1234 nums.get(1) - 5 6 7 8 </code></pre> <p>I want to have in List split like that: 1,2,3,4. How to do this?</p> <p>I tried do regex but i dont know how to format this</p>
[ { "answer_id": 74595360, "author": "boneill", "author_id": 458561, "author_profile": "https://Stackoverflow.com/users/458561", "pm_score": 1, "selected": false, "text": " public static long example(long a) {\n return a = a + 1;\n }\n" }, { "answer_id": 74599924, "author": "Sybuser", "author_id": 8315843, "author_profile": "https://Stackoverflow.com/users/8315843", "pm_score": 1, "selected": true, "text": "DUP2_X1 long l1;\n long l2;\n \n void test(String[] s) {\n s[0] += \"s\"; // Form 1 \n l2 = l1 = 1; // Form 2 \n }\n javap JDK8 void test(java.lang.String[]);\n Code:\n 0: new #2 // class java/lang/StringBuilder\n 3: dup\n 4: invokespecial #3 // Method java/lang/StringBuilder.\"<init>\":()V\n 7: aload_1\n 8: iconst_0\n 9: dup2_x1\n 10: aaload\n 11: invokevirtual #4 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;\n 14: ldc #5 // String s\n 16: invokevirtual #4 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;\n 19: invokevirtual #6 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;\n 22: aastore\n 23: aload_0\n 24: aload_0\n 25: lconst_1\n 26: dup2_x1\n 27: putfield #7 // Field l1:J\n 30: putfield #8 // Field l2:J\n 33: return\n}\n JDK9+ makeConcatWithConstants DUP2_X1 Form 1 void test(java.lang.String[]);\n Code:\n 0: aload_1\n 1: iconst_0\n 2: dup2\n 3: aaload\n 4: invokedynamic #3, 0 // InvokeDynamic #0:makeConcatWithConstants:(Ljava/lang/String;)Ljava/lang/String;\n 9: aastore\n 10: aload_0\n 11: aload_0\n 12: lconst_1\n 13: dup2_x1\n 14: putfield #4 // Field l1:J\n 17: putfield #5 // Field l2:J\n 20: return\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74592937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20234103/" ]
74,592,956
<p>I would like to know why I can not see the ListView content if I put it in Row that is inside Column? Thank you</p> <pre><code>body: Center( child: Column( children: &lt;Widget&gt;[ Row( children: &lt;Widget&gt;[ Flexible( child: ListView( children: [ Text('Text 1'), Text('Text 2'), ], ), ), ], ), ], ), ), </code></pre> <p>I did put the ListView inside Flexible but it is not working.</p>
[ { "answer_id": 74593253, "author": "MendelG", "author_id": 12349734, "author_profile": "https://Stackoverflow.com/users/12349734", "pm_score": 1, "selected": false, "text": "Vertical viewport was given unbounded height.\n shrinkWrap true ListView(\n shrinkWrap: true,\n children: [\n Text('Text 1'),\n Text('Text 2'),\n ],\n)\n import 'package:flutter/material.dart';\n\nconst Color darkBlue = Color.fromARGB(255, 18, 32, 47);\n\nvoid main() {\n runApp(MyApp());\n}\n\nclass MyApp extends StatelessWidget {\n @override\n Widget build(BuildContext context) {\n return MaterialApp(\n theme: ThemeData.dark().copyWith(\n scaffoldBackgroundColor: darkBlue,\n ),\n debugShowCheckedModeBanner: false,\n home: Scaffold(\n body: Center(\n child: Column(\n children: <Widget>[\n Row(\n children: <Widget>[\n Flexible(\n child: ListView(\n shrinkWrap: true,\n children: [\n Text('Text 1'),\n Text('Text 2'),\n ],\n ),\n ),\n ],\n ),\n ],\n ),\n ),\n ),\n );\n }\n}\n" }, { "answer_id": 74594819, "author": "Yeasin Sheikh", "author_id": 10157127, "author_profile": "https://Stackoverflow.com/users/10157127", "pm_score": 3, "selected": true, "text": "ListView Expanded Padding(\n padding: EdgeInsets.all(10),\n child: Column(\n children: <Widget>[\n Expanded(\n //this\n child: Row(\n children: <Widget>[\n Expanded(\n //this\n child: ListView(\n children: [\n for (int i = 0; i < 100; i++) Text('Text $i'),\n ],\n ),\n ),\n ],\n ),\n ),\n ],\n ),\n),\n\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74592956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2646810/" ]
74,593,013
<p>I want to run my function which then starts displaying a CSS element, I currently have</p> <p>CSS</p> <pre><code>.popUpNames{ color:white; text-shadow: 1px 1px 1px white; padding:5px; border:black 5px solid; border-radius: 5px; display:block; position: fixed; top: 50%; left: 50%; background-color: #1a1a1a; transform: translate(-50%, -50%); visibility: hidden; } .popUpNames .show { visibility: visible; } </code></pre> <p>HTML</p> <pre><code>&lt;div class=&quot;popUpNames&quot;&gt; &lt;p&gt;&lt;/p&gt; &lt;/div&gt; </code></pre> <p>JS</p> <pre><code>function togglePopup() { var popup = document.getElementById(&quot;popUpNames&quot;); popup.classList.toggle(&quot;show&quot;); } </code></pre> <p>(the function is called within another function, the calling of the function itself works)</p> <p>I've tried to chnange the id's to classes, the order of .popUpNames .show and the regular .popUpNames</p> <p><a href="https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_popup" rel="nofollow noreferrer">https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_popup</a> I tried extrapolating it from this website, but to no avail</p>
[ { "answer_id": 74593053, "author": "TechStudent10", "author_id": 20616402, "author_profile": "https://Stackoverflow.com/users/20616402", "pm_score": 1, "selected": false, "text": ".popUpNames .show .popUpNames .show .popUpNames.show .popUpNames {\n color: white;\n text-shadow: 1px 1px 1px white;\n padding: 5px;\n border: black 5px solid;\n border-radius: 5px;\n display: none;\n position: fixed;\n top: 50%;\n left: 50%;\n background-color: #1a1a1a;\n transform: translate(-50%, -50%);\n}\n\n.popUpNames.show {\n display: block;\n}\n visibility display getElementById id=\"<your id here>\"" }, { "answer_id": 74593136, "author": "Rocky Sims", "author_id": 4123400, "author_profile": "https://Stackoverflow.com/users/4123400", "pm_score": 1, "selected": true, "text": ".popUpNames .show .popUpNames.show document.getElementById(\"popUpNames\") document.querySelector(\".popUpNames\") togglePopup() document.addEventListener('DOMContentLoaded', () => {\n togglePopup();\n});\n\nfunction togglePopup() {\n const popup = document.querySelector(\".popUpNames\");\n popup.classList.toggle(\"show\");\n} .popUpNames {\n color:white;\n text-shadow: 1px 1px 1px white;\n padding:5px;\n border:black 5px solid;\n border-radius: 5px;\n position: fixed;\n top: 50%;\n left: 50%;\n background-color: #1a1a1a;\n transform: translate(-50%, -50%);\n display: none;\n}\n\n.popUpNames.show {\n display: block;\n} <div class=\"popUpNames\">\n <p>paragraph</p>\n</div>" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20466158/" ]
74,593,024
<p>i wanted to make a game where you guess the letter. and add a function that will show you all you incorrect guesses, so i made the list:</p> <pre><code>incorrectguesses = [] </code></pre> <p>and then i made it so it asks the user to guess the letter:</p> <pre><code> while True: guess = input(&quot;what do you think the letter is?? &quot;) if guess == secret_letter: print(&quot;you guessed it!&quot;) break else: incorrectguesses += [guess] </code></pre> <p>and you can see that i added the guess to the list if it was wrong.</p> <p>then, i added a function to print out every item in the given list:</p> <pre><code>def print_all_items(list_): for x in list_: print(x) </code></pre> <p>and then i ran the function at the end of the loop:</p> <pre><code>print(print_all_items(incorrectguesses)) </code></pre> <p>but this was the result:</p> <blockquote> <p>what do you think the letter is?? a</p> <p>a</p> <p>None</p> <p>what do you think the letter is?? b</p> <p>a</p> <p>b</p> <p>None</p> </blockquote> <p>as you can see, it adds &quot;None&quot; to the end of the list.</p> <p>thanks if you could help me</p>
[ { "answer_id": 74593067, "author": "John Gordon", "author_id": 494134, "author_profile": "https://Stackoverflow.com/users/494134", "pm_score": 3, "selected": true, "text": "print(print_all_items(incorrectguesses))\n print_all_items() return None None" }, { "answer_id": 74593327, "author": "lnatero.uc", "author_id": 16824647, "author_profile": "https://Stackoverflow.com/users/16824647", "pm_score": 0, "selected": false, "text": "return while True:\n guess = input(\"what do you think the letter is?? \")\nif guess == secret_letter:\n print(\"you guessed it!\")\n break\nelse:\n incorrectguesses += [guess]\n print_all_items(incorrectguesses) # ←\n incorrectguesses print(<something>) print() <something> print() print_all_items() print_all_items() None <something> print(<something>) None" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17774550/" ]
74,593,047
<p>With selenium in python, I want to collect data about a user called &quot;Graham&quot; on the website below: <a href="https://github.com/GrahamDumpleton/wrapt/graphs/contributors" rel="nofollow noreferrer">https://github.com/GrahamDumpleton/wrapt/graphs/contributors</a></p> <p>Following the previous question, I located the header including the name &quot;Graham&quot; by finding XPath:</p> <pre><code>driver.find_elements(By.XPATH, &quot;//h3[contains(@class,'border-bottom')][contains(.,'Graham')]&quot;) </code></pre> <p>How could I find an element under this located header?<br /> The XPath is:</p> <pre><code>//*[@id=&quot;contributors&quot;]/ol/li/span/h3/span[2]/span/div/a </code></pre> <p>Thank you.</p>
[ { "answer_id": 74593067, "author": "John Gordon", "author_id": 494134, "author_profile": "https://Stackoverflow.com/users/494134", "pm_score": 3, "selected": true, "text": "print(print_all_items(incorrectguesses))\n print_all_items() return None None" }, { "answer_id": 74593327, "author": "lnatero.uc", "author_id": 16824647, "author_profile": "https://Stackoverflow.com/users/16824647", "pm_score": 0, "selected": false, "text": "return while True:\n guess = input(\"what do you think the letter is?? \")\nif guess == secret_letter:\n print(\"you guessed it!\")\n break\nelse:\n incorrectguesses += [guess]\n print_all_items(incorrectguesses) # ←\n incorrectguesses print(<something>) print() <something> print() print_all_items() print_all_items() None <something> print(<something>) None" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10295124/" ]
74,593,058
<p>I'm trying to make some project code I have written, more resilient to crashes, except the circumstances of my previous crashes have all been different. So that I do not have to try and account for every single one, I thought I'd try to get my code to either restart, or execute a copy of itself in place of it and then close itself down gracefully, meaning its replacement, because it's coded identically, would in essence be the same as restarting from the beginning again. The desired result for me would be that while the error resulting circumstances are present, my code would be in a program swap out, or restart loop until such time as it can execute its code normally again....until the next time it faces a similar situation.</p> <p>To experiment with, I've written two programs. I'm hoping from these examples someone will understand what I am trying to achieve. I want the first script to execute, then start the execute process for the second (in a new terminal) before closing itself down gracefully.</p> <p>Is this even possible?</p> <p>Thanks in advance.</p> <p>first.py</p> <pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python #!/bin/bash #first.py import time import os import sys from subprocess import run import subprocess thisfile = &quot;first&quot; #thisfile = &quot;second&quot; time.sleep(3) while thisfile == &quot;second&quot;: print(&quot;this is the second file&quot;) time.sleep(1) #os.system(&quot;first.py&quot;) #exec(open(&quot;first.py&quot;).read()) #run(&quot;python &quot;+&quot;first.py&quot;, check=False) #import first #os.system('python first.py') #subprocess.call(&quot; python first.py 1&quot;, shell=True) os.execv(&quot;first.py&quot;, sys.argv) print(&quot;I'm leaving second now&quot;) break while thisfile == &quot;first&quot;: print(&quot;this is the first file&quot;) time.sleep(1) #os.system(&quot;second.py&quot;) #exec(open(&quot;second.py&quot;).read()) #run(&quot;python &quot;+&quot;second.py&quot;, check=False) #import second #os.system('python second.py') #subprocess.call(&quot; python second.py 1&quot;, shell=True) os.execv(&quot;second.py&quot;, sys.argv) print(&quot;I'm leaving first now&quot;) break time.sleep(1) sys.exit(&quot;Quitting&quot;) </code></pre> <p>second.py (basically a copy of first.py)</p> <pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python #!/bin/bash #second.py import time import os import sys from subprocess import run import subprocess #thisfile = &quot;first&quot; thisfile = &quot;second&quot; time.sleep(3) while thisfile == &quot;second&quot;: print(&quot;this is the second file&quot;) time.sleep(1) #os.system(&quot;first.py&quot;) #exec(open(&quot;first.py&quot;).read()) #run(&quot;python &quot;+&quot;first.py&quot;, check=False) #import first #os.system('python first.py') #subprocess.call(&quot; python first.py 1&quot;, shell=True) os.execv(&quot;first.py&quot;, sys.argv) print(&quot;I'm leaving second now&quot;) break while thisfile == &quot;first&quot;: print(&quot;this is the first file&quot;) time.sleep(1) #os.system(&quot;second.py&quot;) #exec(open(&quot;second.py&quot;).read()) #run(&quot;python &quot;+&quot;second.py&quot;, check=False) #import second #os.system('python second.py') #subprocess.call(&quot; python second.py 1&quot;, shell=True) os.execv(&quot;second.py&quot;, sys.argv) print(&quot;I'm leaving first now&quot;) break time.sleep(1) sys.exit(&quot;Quitting&quot;) </code></pre> <p>I have tried quite a few solutions as can be seen with my hashed out lines of code. Nothing so far though has given me the result I am after unfortunately.</p> <p>EDIT: This is the part of the actual code i think i am having problems with. This is the part where I am attempting to publish to my MQTT broker.</p> <pre><code>try: client.connect(broker, port, 10) #connect to broker time.sleep(1) except: print(&quot;Cannot connect&quot;) sys.exit(&quot;Quitting&quot;) </code></pre> <p>Instead of exiting with the &quot;quitting&quot; part, will it keep my code alive if i route it to stay within a repeat loop until such time as it successfully connects to the broker again and then continue back with the rest of the script? Or is this wishful thinking?</p>
[ { "answer_id": 74594067, "author": "tdelaney", "author_id": 642070, "author_profile": "https://Stackoverflow.com/users/642070", "pm_score": 1, "selected": false, "text": "subprocess.call() import multiprocessing as mp\nimport time\n\ndef do_the_things(arg1, arg2):\n print(\"doing the things\")\n time.sleep(2) # for test\n raise RuntimeError(\"Virgin Media dun me wrong\")\n\ndef launch_and_monitor():\n while True:\n print(\"start the things\")\n proc = mp.Process(target=do_the_things, args=(0, 1))\n proc.start()\n proc.wait()\n print(\"things went awry\")\n time.sleep(2) # a moment before restart hoping badness resolves\n\nif __name__ == \"__main__\":\n launch_and_monitor()\n with multiprocessing.Pool(1) as pool:\n while True:\n try:\n result = pool.map(do_the_things, [(0,1)])\n except Exception as e:\n print(\"caught\", e)\n" }, { "answer_id": 74618691, "author": "Rissy", "author_id": 20617007, "author_profile": "https://Stackoverflow.com/users/20617007", "pm_score": 0, "selected": false, "text": "import time\nimport subprocess\n\nthisfile = \"first\"\n#thisfile = \"second\"\n\nif thisfile == \"second\":\n restartcommand = 'python3 /home/mypi/myprograms/first.py'\nelse:\n restartcommand = 'python3 /home/mypi/myprograms/second.py'\n\ntime.sleep(3)\nwhile thisfile == \"second\":\n print(\"this is the second file\")\n time.sleep(1)\n subprocess.run('lxterminal -e ' + restartcommand, shell=True)\n print(\"I'm leaving second now\")\n break\nwhile thisfile == \"first\":\n print(\"this is the first file\")\n time.sleep(1)\n subprocess.run('lxterminal -e ' + restartcommand, shell=True)\n print(\"I'm leaving first now\")\n break\ntime.sleep(1)\nquit()\n import time\nimport subprocess\n\n#thisfile = \"first\"\nthisfile = \"second\"\n\nif thisfile == \"second\":\n restartcommand = 'python3 /home/mypi/myprograms/first.py'\nelse:\n restartcommand = 'python3 /home/mypi/myprograms/second.py'\n\ntime.sleep(3)\nwhile thisfile == \"second\":\n print(\"this is the second file\")\n time.sleep(1)\n subprocess.run('lxterminal -e ' + restartcommand, shell=True)\n print(\"I'm leaving second now\")\n break\nwhile thisfile == \"first\":\n print(\"this is the first file\")\n time.sleep(1)\n subprocess.run('lxterminal -e ' + restartcommand, shell=True)\n print(\"I'm leaving first now\")\n break\ntime.sleep(1)\nquit()\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20617007/" ]
74,593,089
<p>I'm getting the following error for my python scraper:</p> <pre><code>import requests import json symbol_id = 'COINBASE_SPOT_BTC_USDT' time_start = '2022-11-20T17:00:00' time_end = '2022-11-21T05:00:00' limit_levels = 100000000 limit = 100000000 url = 'https://rest.coinapi.io/v1/orderbooks/{symbol_id}/history?time_start={time_start}limit={limit}&amp;limit_levels={limit_levels}' headers = {'X-CoinAPI-Key' : 'XXXXXXXXXXXXXXXXXXXXXXX'} response = requests.get(url, headers=headers) print(response) with open('raw_coinbase_ob_history.json', 'w') as json_file: json.dump(response.json(), json_file) with open('raw_coinbase_ob_history.json', 'r') as handle: parsed = json.load(handle) with open('coinbase_ob_history.json', 'w') as coinbase_ob: json.dump(parsed, coinbase_ob, indent = 4) </code></pre> <pre><code>&lt;Response [400]&gt; </code></pre> <p>And in my written json file, I'm outputted</p> <pre><code>{&quot;error&quot;: &quot;Wrong format of 'time_start' parameter.&quot;} </code></pre> <p>I assume a string goes into a url, so I flattened the timestring to a string. I don't understand why this doesn't work. This is the documentation for the coinAPI call I'm trying to make with 'timestring'. <a href="https://docs.coinapi.io/?python#historical-data-get-4" rel="nofollow noreferrer">https://docs.coinapi.io/?python#historical-data-get-4</a></p>
[ { "answer_id": 74594067, "author": "tdelaney", "author_id": 642070, "author_profile": "https://Stackoverflow.com/users/642070", "pm_score": 1, "selected": false, "text": "subprocess.call() import multiprocessing as mp\nimport time\n\ndef do_the_things(arg1, arg2):\n print(\"doing the things\")\n time.sleep(2) # for test\n raise RuntimeError(\"Virgin Media dun me wrong\")\n\ndef launch_and_monitor():\n while True:\n print(\"start the things\")\n proc = mp.Process(target=do_the_things, args=(0, 1))\n proc.start()\n proc.wait()\n print(\"things went awry\")\n time.sleep(2) # a moment before restart hoping badness resolves\n\nif __name__ == \"__main__\":\n launch_and_monitor()\n with multiprocessing.Pool(1) as pool:\n while True:\n try:\n result = pool.map(do_the_things, [(0,1)])\n except Exception as e:\n print(\"caught\", e)\n" }, { "answer_id": 74618691, "author": "Rissy", "author_id": 20617007, "author_profile": "https://Stackoverflow.com/users/20617007", "pm_score": 0, "selected": false, "text": "import time\nimport subprocess\n\nthisfile = \"first\"\n#thisfile = \"second\"\n\nif thisfile == \"second\":\n restartcommand = 'python3 /home/mypi/myprograms/first.py'\nelse:\n restartcommand = 'python3 /home/mypi/myprograms/second.py'\n\ntime.sleep(3)\nwhile thisfile == \"second\":\n print(\"this is the second file\")\n time.sleep(1)\n subprocess.run('lxterminal -e ' + restartcommand, shell=True)\n print(\"I'm leaving second now\")\n break\nwhile thisfile == \"first\":\n print(\"this is the first file\")\n time.sleep(1)\n subprocess.run('lxterminal -e ' + restartcommand, shell=True)\n print(\"I'm leaving first now\")\n break\ntime.sleep(1)\nquit()\n import time\nimport subprocess\n\n#thisfile = \"first\"\nthisfile = \"second\"\n\nif thisfile == \"second\":\n restartcommand = 'python3 /home/mypi/myprograms/first.py'\nelse:\n restartcommand = 'python3 /home/mypi/myprograms/second.py'\n\ntime.sleep(3)\nwhile thisfile == \"second\":\n print(\"this is the second file\")\n time.sleep(1)\n subprocess.run('lxterminal -e ' + restartcommand, shell=True)\n print(\"I'm leaving second now\")\n break\nwhile thisfile == \"first\":\n print(\"this is the first file\")\n time.sleep(1)\n subprocess.run('lxterminal -e ' + restartcommand, shell=True)\n print(\"I'm leaving first now\")\n break\ntime.sleep(1)\nquit()\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20068650/" ]
74,593,111
<p>While the rest of the code is functional, I can't figure out how to average the &quot;Total Purchases&quot; using the &quot;Number of Purchases&quot; to find the &quot;Average Purchase Amount&quot;.</p> <p>--- Query ---</p> <pre><code>SELECT C.CUS_CODE, C.CUS_BALANCE, ROUND(SUM(L.LINE_UNITS * L.LINE_PRICE), 2) AS &quot;Total Purchases&quot;, COUNT(L.LINE_NUMBER) AS &quot;Number of Purchases&quot;, AVG(&quot;Total Purchases&quot;) as &quot;Average Purchase Amount&quot; FROM CUSTOMER AS C RIGHT JOIN INVOICE AS I ON C.CUS_CODE = I.CUS_CODE RIGHT JOIN LINE AS L ON I.INV_NUMBER = L.INV_NUMBER WHERE L.INV_NUMBER = I.INV_NUMBER GROUP BY CUS_CODE, &quot;Number of Purchases&quot; </code></pre> <p>I've tried using the AVG() function with &quot;Total Purchases&quot; and grouping by &quot;Number of Purchases&quot; alias's but the query returns a 0 in each &quot;Average Purchase Amount&quot; column.</p> <p>The output should represent the following:</p> <p><a href="https://i.stack.imgur.com/rS8Ix.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rS8Ix.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74594067, "author": "tdelaney", "author_id": 642070, "author_profile": "https://Stackoverflow.com/users/642070", "pm_score": 1, "selected": false, "text": "subprocess.call() import multiprocessing as mp\nimport time\n\ndef do_the_things(arg1, arg2):\n print(\"doing the things\")\n time.sleep(2) # for test\n raise RuntimeError(\"Virgin Media dun me wrong\")\n\ndef launch_and_monitor():\n while True:\n print(\"start the things\")\n proc = mp.Process(target=do_the_things, args=(0, 1))\n proc.start()\n proc.wait()\n print(\"things went awry\")\n time.sleep(2) # a moment before restart hoping badness resolves\n\nif __name__ == \"__main__\":\n launch_and_monitor()\n with multiprocessing.Pool(1) as pool:\n while True:\n try:\n result = pool.map(do_the_things, [(0,1)])\n except Exception as e:\n print(\"caught\", e)\n" }, { "answer_id": 74618691, "author": "Rissy", "author_id": 20617007, "author_profile": "https://Stackoverflow.com/users/20617007", "pm_score": 0, "selected": false, "text": "import time\nimport subprocess\n\nthisfile = \"first\"\n#thisfile = \"second\"\n\nif thisfile == \"second\":\n restartcommand = 'python3 /home/mypi/myprograms/first.py'\nelse:\n restartcommand = 'python3 /home/mypi/myprograms/second.py'\n\ntime.sleep(3)\nwhile thisfile == \"second\":\n print(\"this is the second file\")\n time.sleep(1)\n subprocess.run('lxterminal -e ' + restartcommand, shell=True)\n print(\"I'm leaving second now\")\n break\nwhile thisfile == \"first\":\n print(\"this is the first file\")\n time.sleep(1)\n subprocess.run('lxterminal -e ' + restartcommand, shell=True)\n print(\"I'm leaving first now\")\n break\ntime.sleep(1)\nquit()\n import time\nimport subprocess\n\n#thisfile = \"first\"\nthisfile = \"second\"\n\nif thisfile == \"second\":\n restartcommand = 'python3 /home/mypi/myprograms/first.py'\nelse:\n restartcommand = 'python3 /home/mypi/myprograms/second.py'\n\ntime.sleep(3)\nwhile thisfile == \"second\":\n print(\"this is the second file\")\n time.sleep(1)\n subprocess.run('lxterminal -e ' + restartcommand, shell=True)\n print(\"I'm leaving second now\")\n break\nwhile thisfile == \"first\":\n print(\"this is the first file\")\n time.sleep(1)\n subprocess.run('lxterminal -e ' + restartcommand, shell=True)\n print(\"I'm leaving first now\")\n break\ntime.sleep(1)\nquit()\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593111", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20609717/" ]
74,593,121
<p>I want to show in the user interface of the future data in accordance with the design. But in the design, the 1st person should appear in the middle, and the 2nd place person should appear on the left. The third person should be on the far right. how can i show this in list loop. I am sharing my codes with you as an example. So in summary, the first 3 successful users will be forwarded to me in order of success. How can I get this display?</p> <pre><code>struct TopSortingUIView: View { var topSortingList : [TopSorting] = TopSortingList.three var body: some View { HStack(spacing:24){ VStack{ Image(&quot;mangaa&quot;) .resizable() .scaledToFill() .frame(width: 77, height: 77) .clipShape(Circle()) .shadow(radius: 8) .shadow(color: Color.init(red: 0.973, green: 0.976, blue: 0.98), radius: 4.15) .padding(.top, 75) Text(&quot;User1&quot;) .font(.system(size: 12)) .foregroundColor(.secondary) Text(&quot;2000 P&quot;) .bold() .font(.system(size: 12)) .foregroundColor(.black) } VStack{ Image(&quot;King&quot;) Image(&quot;mangaa&quot;) .resizable() .scaledToFill() .frame(width: 77, height: 77) .clipShape(Circle()) .shadow(radius: 8) .shadow(color: Color.init(red: 0.973, green: 0.976, blue: 0.98), radius: 4.15) Text(&quot;User2&quot;) .font(.system(size: 12)) .foregroundColor(.secondary) Text(&quot;2824 P&quot;) .bold() .font(.system(size: 12)) .foregroundColor(.black) } VStack{ Image(&quot;mangaa&quot;) .resizable() .scaledToFill() .frame(width: 77, height: 77) .clipShape(Circle()) .shadow(radius: 8) .shadow(color: Color.init(red: 0.973, green: 0.976, blue: 0.98), radius: 4.15) .padding(.top, 75) Text(&quot;User3&quot;) .font(.system(size: 12)) .foregroundColor(.secondary) Text(&quot;600P&quot;) .bold() .font(.system(size: 12)) .foregroundColor(.black) } } } } </code></pre> <pre><code>struct TopSorting { let rank : Int let photoUrl: String let userName: String let name: String let data : String } struct TopSortingList { static let three = [ TopSorting(rank: 1, photoUrl: &quot;mangaa&quot;, userName: &quot;user1&quot;, name: &quot;us1&quot;, data: &quot;2824Ap&quot;), TopSorting(rank: 2, photoUrl: &quot;mangaa&quot;, userName: &quot;user2&quot;, name: &quot;us2&quot;, data: &quot;2000Ap&quot;), TopSorting(rank: 3, photoUrl: &quot;mangaa&quot;, userName: &quot;user3&quot;, name: &quot;us3&quot;, data: &quot;600Ap&quot;) ] } </code></pre> <p>I'm trying to achieve the look you see in the photo. The data and image of the 1st user should be higher than the others</p>
[ { "answer_id": 74594067, "author": "tdelaney", "author_id": 642070, "author_profile": "https://Stackoverflow.com/users/642070", "pm_score": 1, "selected": false, "text": "subprocess.call() import multiprocessing as mp\nimport time\n\ndef do_the_things(arg1, arg2):\n print(\"doing the things\")\n time.sleep(2) # for test\n raise RuntimeError(\"Virgin Media dun me wrong\")\n\ndef launch_and_monitor():\n while True:\n print(\"start the things\")\n proc = mp.Process(target=do_the_things, args=(0, 1))\n proc.start()\n proc.wait()\n print(\"things went awry\")\n time.sleep(2) # a moment before restart hoping badness resolves\n\nif __name__ == \"__main__\":\n launch_and_monitor()\n with multiprocessing.Pool(1) as pool:\n while True:\n try:\n result = pool.map(do_the_things, [(0,1)])\n except Exception as e:\n print(\"caught\", e)\n" }, { "answer_id": 74618691, "author": "Rissy", "author_id": 20617007, "author_profile": "https://Stackoverflow.com/users/20617007", "pm_score": 0, "selected": false, "text": "import time\nimport subprocess\n\nthisfile = \"first\"\n#thisfile = \"second\"\n\nif thisfile == \"second\":\n restartcommand = 'python3 /home/mypi/myprograms/first.py'\nelse:\n restartcommand = 'python3 /home/mypi/myprograms/second.py'\n\ntime.sleep(3)\nwhile thisfile == \"second\":\n print(\"this is the second file\")\n time.sleep(1)\n subprocess.run('lxterminal -e ' + restartcommand, shell=True)\n print(\"I'm leaving second now\")\n break\nwhile thisfile == \"first\":\n print(\"this is the first file\")\n time.sleep(1)\n subprocess.run('lxterminal -e ' + restartcommand, shell=True)\n print(\"I'm leaving first now\")\n break\ntime.sleep(1)\nquit()\n import time\nimport subprocess\n\n#thisfile = \"first\"\nthisfile = \"second\"\n\nif thisfile == \"second\":\n restartcommand = 'python3 /home/mypi/myprograms/first.py'\nelse:\n restartcommand = 'python3 /home/mypi/myprograms/second.py'\n\ntime.sleep(3)\nwhile thisfile == \"second\":\n print(\"this is the second file\")\n time.sleep(1)\n subprocess.run('lxterminal -e ' + restartcommand, shell=True)\n print(\"I'm leaving second now\")\n break\nwhile thisfile == \"first\":\n print(\"this is the first file\")\n time.sleep(1)\n subprocess.run('lxterminal -e ' + restartcommand, shell=True)\n print(\"I'm leaving first now\")\n break\ntime.sleep(1)\nquit()\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20166709/" ]
74,593,124
<p>I am trying to create a new user in mongodb and looking for <code>existing user</code> but even if a am sending request with new user details it is still showing that <code>User alreadyExists</code></p> <pre><code>export const signUp = async (req, res) =&gt; { const {email, password, username, roomid} = req.body; try { console.log(req.body); let existingUser = User.findOne({email}); console.log(existingUser); if (existingUser) res.status(400).json({message: 'User already exists!!'}); const hashedPassword = await bcrypt.hash(password, 12); const result = await User.create({ email, password: hashedPassword, username, roomid, }); const token = jwt.sign( {email: existingUser.email, id: existingUser._id}, 'test', {expiresIn: '1hr'} ); res.status(201).json({result, token}); } catch (err) { console.log(err); } }; </code></pre> <p>Help Please</p> <p>Someone just solve the problem of new user creation</p>
[ { "answer_id": 74594067, "author": "tdelaney", "author_id": 642070, "author_profile": "https://Stackoverflow.com/users/642070", "pm_score": 1, "selected": false, "text": "subprocess.call() import multiprocessing as mp\nimport time\n\ndef do_the_things(arg1, arg2):\n print(\"doing the things\")\n time.sleep(2) # for test\n raise RuntimeError(\"Virgin Media dun me wrong\")\n\ndef launch_and_monitor():\n while True:\n print(\"start the things\")\n proc = mp.Process(target=do_the_things, args=(0, 1))\n proc.start()\n proc.wait()\n print(\"things went awry\")\n time.sleep(2) # a moment before restart hoping badness resolves\n\nif __name__ == \"__main__\":\n launch_and_monitor()\n with multiprocessing.Pool(1) as pool:\n while True:\n try:\n result = pool.map(do_the_things, [(0,1)])\n except Exception as e:\n print(\"caught\", e)\n" }, { "answer_id": 74618691, "author": "Rissy", "author_id": 20617007, "author_profile": "https://Stackoverflow.com/users/20617007", "pm_score": 0, "selected": false, "text": "import time\nimport subprocess\n\nthisfile = \"first\"\n#thisfile = \"second\"\n\nif thisfile == \"second\":\n restartcommand = 'python3 /home/mypi/myprograms/first.py'\nelse:\n restartcommand = 'python3 /home/mypi/myprograms/second.py'\n\ntime.sleep(3)\nwhile thisfile == \"second\":\n print(\"this is the second file\")\n time.sleep(1)\n subprocess.run('lxterminal -e ' + restartcommand, shell=True)\n print(\"I'm leaving second now\")\n break\nwhile thisfile == \"first\":\n print(\"this is the first file\")\n time.sleep(1)\n subprocess.run('lxterminal -e ' + restartcommand, shell=True)\n print(\"I'm leaving first now\")\n break\ntime.sleep(1)\nquit()\n import time\nimport subprocess\n\n#thisfile = \"first\"\nthisfile = \"second\"\n\nif thisfile == \"second\":\n restartcommand = 'python3 /home/mypi/myprograms/first.py'\nelse:\n restartcommand = 'python3 /home/mypi/myprograms/second.py'\n\ntime.sleep(3)\nwhile thisfile == \"second\":\n print(\"this is the second file\")\n time.sleep(1)\n subprocess.run('lxterminal -e ' + restartcommand, shell=True)\n print(\"I'm leaving second now\")\n break\nwhile thisfile == \"first\":\n print(\"this is the first file\")\n time.sleep(1)\n subprocess.run('lxterminal -e ' + restartcommand, shell=True)\n print(\"I'm leaving first now\")\n break\ntime.sleep(1)\nquit()\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17723923/" ]
74,593,151
<pre><code>from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver import ActionChains from selenium.webdriver.common.by import By from time import sleep from datetime import datetime import pandas as pd import warnings import os os.chdir('C:/Users/paulc/Documents/Medium Football') warnings.filterwarnings('ignore') base_url = 'https://www.sportingindex.com/spread-betting/football/international-world-cup' option = Options() option.headless = False driver = webdriver.Chrome(&quot;C:/Users/paulc/Documents/Medium Football/chromedriver.exe&quot;,options=option) driver.get(base_url) links = [elem.get_attribute(&quot;href&quot;) for elem in driver.find_elements(By.TAG_NAME,&quot;a&quot;)] </code></pre> <p>this code retrieves all the href links on this page. I want to search the links list and return only the matches that contain 'https://www.sportingindex.com/spread-betting/football/international-world-cup/group_a'</p> <p><a href="https://i.stack.imgur.com/gc44o.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gc44o.png" alt="enter image description here" /></a></p> <p>however I get the AttributeError: 'NoneType' object has no attribute 'startswith' using</p> <pre><code> import re [x for x in links if x.startswith('https://www.sportingindex.com/spread-betting/football/international-world-cup/group_a')] </code></pre> <p>help is appreciated.</p> <p><a href="https://i.stack.imgur.com/YT9JA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YT9JA.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74593256, "author": "Prophet", "author_id": 3485434, "author_profile": "https://Stackoverflow.com/users/3485434", "pm_score": 2, "selected": false, "text": "a driver.find_elements(By.TAG_NAME,\"a\")\n driver.find_elements(By.XPATH,\"//a[contains(@href,'https://www.sportingindex.com/spread-betting/football/international-world-cup/group_a')]\")\n links = [elem.get_attribute(\"href\") for elem in driver.find_elements(By.XPATH,\"//a[contains(@href,'https://www.sportingindex.com/spread-betting/football/international-world-cup/group_a')]\")]\n time.sleep(2) WebDriverWait expected_conditions from selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\n\nwait = WebDriverWait(driver, 10)\n\nlinks = [elem.get_attribute(\"href\") for elem in wait.until(EC.visibility_of_all_elements_located((By.XPATH, \"//a[contains(@href,'https://www.sportingindex.com/spread-betting/football/international-world-cup/group_a')]\")))]\n" }, { "answer_id": 74593527, "author": "Fazlul", "author_id": 12848411, "author_profile": "https://Stackoverflow.com/users/12848411", "pm_score": 1, "selected": true, "text": "import time\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium import webdriver\nwebdriver_service = Service(\"./chromedriver\") #Your chromedriver path\ndriver = webdriver.Chrome(service=webdriver_service)\n\ndriver.get('https://www.sportingindex.com/spread-betting/football/international-world-cup')\ndriver.maximize_window()\ntime.sleep(8)\n\n\nsoup = BeautifulSoup(driver.page_source,\"lxml\")\nfor u in soup.select('a[class=\"gatracking\"]'):\n link = 'https://www.sportingindex.com' + u.get('href')\n\n if '-v-' in link:\n print(link)\n https://www.sportingindex.com/spread-betting/football/international-world-cup/group_a.24fdf8f5-b69b-4341-b6b4-d27605f7f7fd/spain-v-germany\nhttps://www.sportingindex.com/spread-betting/football/international-world-cup/group_a.c9bdf787-791a-47e0-b77c-a2d4cf567bfd/cameroon-v-serbia\nhttps://www.sportingindex.com/spread-betting/football/international-world-cup/group_a.5eddaa44-666b-47dc-8a0f-4ac758de00dc/south-korea-v-ghana\nhttps://www.sportingindex.com/spread-betting/football/international-world-cup/group_a.70cefd39-60f7-415e-9cb5-7a56acd403d6/brazil-v-switzerland\nhttps://www.sportingindex.com/spread-betting/football/international-world-cup/group_a.7fe0285e-366f-4f3c-b77f-4c96077a6c71/portugal-v-uruguay\nhttps://www.sportingindex.com/spread-betting/football/international-world-cup/group_a.dd7a995d-7478-45f8-af27-9f234d37cc76/ecuador-v-senegal\nhttps://www.sportingindex.com/spread-betting/football/international-world-cup/group_a.92232207-0f1e-4bb1-bacd-1332ef6b9007/netherlands-v-qatar\nhttps://www.sportingindex.com/spread-betting/football/international-world-cup/group_a.b913620e-69c7-4606-a153-7b48589b7c94/iran-v-usa\nhttps://www.sportingindex.com/spread-betting/football/international-world-cup/group_a.7a4a18fb-d4ee-4880-849f-f1afdea33cd5/wales-v-england\nhttps://www.sportingindex.com/spread-betting/football/international-world-cup/group_a.20c098b4-4e97-4fd1-97b0-f42d84424361/australia-v-denmark\nhttps://www.sportingindex.com/spread-betting/football/international-world-cup/group_a.5a7476e2-8d35-4a8e-8065-b4339e79f395/tunisia-v-france\nhttps://www.sportingindex.com/spread-betting/football/international-world-cup/group_a.8a869f02-9dd0-49c5-91bd-209ee224fc2a/poland-v-argentina\nhttps://www.sportingindex.com/spread-betting/football/international-world-cup/group_a.6379b787-f246-4ba4-a896-28a97396d02f/saudi-arabia-v-mexico\nhttps://www.sportingindex.com/spread-betting/football/international-world-cup/group_a.52737cfd-da19-42dd-b15b-c16c3e8e9a86/canada-v-morocco\nhttps://www.sportingindex.com/spread-betting/football/international-world-cup/group_a.168fab1f-8360-4e87-ba84-bfbd11a4a207/croatia-v-belgium\nhttps://www.sportingindex.com/spread-betting/football/international-world-cup/group_a.9fb541f0-43a4-409c-8e54-e34a43965714/costa-rica-v-germany\nhttps://www.sportingindex.com/spread-betting/football/international-world-cup/group_a.7379c8a7-ab5d-4653-b487-22bf7ff8eefe/japan-v-spain\nhttps://www.sportingindex.com/spread-betting/football/international-world-cup/group_a.e7e4c6be-98b7-4258-ba40-74c54a790fe1/ghana-v-uruguay\nhttps://www.sportingindex.com/spread-betting/football/international-world-cup/group_a.e4c18c81-565e-47ce-b08d-9aed62c88a5d/south-korea-v-portugal\nhttps://www.sportingindex.com/spread-betting/football/international-world-cup/group_a.18f44028-e23d-48d4-970b-e75c164589bd/cameroon-v-brazil\nhttps://www.sportingindex.com/spread-betting/football/international-world-cup/group_a.526f9b1b-6d95-4f44-abce-e0a6a30acfd4/serbia-v-switzerland\nhttps://www.sportingindex.com/spread-betting/football/international-world-cup/group_a.24fdf8f5-b69b-4341-b6b4-d27605f7f7fd/spain-v-germany\nhttps://www.sportingindex.com/spread-betting/football/international-world-cup/group_a.c9bdf787-791a-47e0-b77c-a2d4cf567bfd/cameroon-v-serbia\nhttps://www.sportingindex.com/spread-betting/football/international-world-cup/group_a.5eddaa44-666b-47dc-8a0f-4ac758de00dc/south-korea-v-ghana\nhttps://www.sportingindex.com/spread-betting/football/international-world-cup/group_a.70cefd39-60f7-415e-9cb5-7a56acd403d6/brazil-v-switzerland\nhttps://www.sportingindex.com/spread-betting/football/international-world-cup/group_a.7fe0285e-366f-4f3c-b77f-4c96077a6c71/portugal-v-uruguay\nhttps://www.sportingindex.com/spread-betting/football/international-world-cup/group_a.24fdf8f5-b69b-4341-b6b4-d27605f7f7fd/spain-v-germany\nhttps://www.sportingindex.com/spread-betting/rugby-union/france-top-14/group_a.ad22f34f-9cd6-47b4-a826-0c0f0dce7df2/lyon-v-toulouse\nhttps://www.sportingindex.com/spread-betting/football/international-world-cup/group_a.24fdf8f5-b69b-4341-b6b4-d27605f7f7fd/spain-v-germany\nhttps://www.sportingindex.com/spread-betting/rugby-union/france-top-14/group_a.ad22f34f-9cd6-47b4-a826-0c0f0dce7df2/lyon-v-toulouse\nhttps://www.sportingindex.com/spread-betting/football/international-world-cup/group_a.c9bdf787-791a-47e0-b77c-a2d4cf567bfd/cameroon-v-serbia\nhttps://www.sportingindex.com/spread-betting/football/international-world-cup/group_a.5eddaa44-666b-47dc-8a0f-4ac758de00dc/south-korea-v-ghana\nhttps://www.sportingindex.com/spread-betting/football/international-world-cup/group_a.70cefd39-60f7-415e-9cb5-7a56acd403d6/brazil-v-switzerland\nhttps://www.sportingindex.com/spread-betting/football/international-world-cup/group_a.7fe0285e-366f-4f3c-b77f-4c96077a6c71/portugal-v-uruguay\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18776287/" ]
74,593,203
<p><a href="https://i.stack.imgur.com/ZFVKv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZFVKv.png" alt="image of the code and error" /></a></p> <pre><code>using System; using System.Collections.Generic; using System.Linq; internal class Program { public static bool Aa(int[] a, int k) { for (int i = 1; i &lt; a.Length; i++) if (a[0] + a[i] == k) return true; if (a.Length != 1) Aa(a.Skip(1), k); return false; } static void Main(string[] args) { int[] a = { 1, 2, 3, 4, 2, 3, 2, 1 }; Console.WriteLine(Aa(a, 10)); Console.ReadLine(); } } </code></pre> <p>The following build error occurs on the recursive method call <code>Aa(a.Skip(1), k);</code></p> <blockquote> <p>Argument 1: cannot convert from 'System.Collections.IEnumerable' to 'int[]'</p> </blockquote>
[ { "answer_id": 74593336, "author": "Moatasem La Kremed", "author_id": 10444949, "author_profile": "https://Stackoverflow.com/users/10444949", "pm_score": 1, "selected": false, "text": "a.Skip().ToArray();\n" }, { "answer_id": 74594172, "author": "Ruud Helderman", "author_id": 2485966, "author_profile": "https://Stackoverflow.com/users/2485966", "pm_score": 0, "selected": false, "text": "public static System.Collections.Generic.IEnumerable<TSource> Skip<TSource> (this System.Collections.Generic.IEnumerable<TSource> source, int count);\n Skip int[] whatGoesIn = {1, 2, 3};\nIEnumerable<int> whatComesOut = whatGoesIn.Skip(1);\n int[] ToArray Skip a public static bool Aa(int[] a, int k)\n a public static bool Aa(IEnumerable<int> a, int k)\n for IEnumerable<int> Length for (int i = 1; i < a.Length; i++)\n if (a[0] + a[i] == k)\n return true;\n k - a[0] bool found = a.Skip(1).Contains(k - a.First());\nif (found) return true;\n Length if (a.Length != 1)\n Aa(a.Skip(1), k);\nreturn false;\n Aa if (a.Length != 1)\n return Aa(a.Skip(1), k);\nreturn false;\n return a.Skip(1).Any() && Aa(a.Skip(1), k);\n public static bool Aa(IEnumerable<int> a, int k)\n{\n return a.Skip(1).Contains(k - a.First()) || (a.Skip(1).Any() && Aa(a.Skip(1), k));\n}\n public static bool Aa(IEnumerable<int> a, int k)\n{\n return a.Any() && (a.Skip(1).Contains(k - a.First()) || Aa(a.Skip(1), k));\n}\n for Contains Skip public static bool Aa(int[] a, int k, int start = 0)\n{\n for (int i = start + 1; i < a.Length; i++)\n if (a[start] + a[i] == k)\n return true;\n if (start < a.Length)\n return Aa(a, k, start + 1);\n return false;\n}\n ToArray" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15085900/" ]
74,593,208
<p>I've scraped the crypto.com website to get the current prices of crypto coins in DataFrame form, it worked perfectly with pandas, but the 'Prices' values are mixed.</p> <p>here's the output:</p> <pre><code> Name Price 24H CHANGE 0 BBitcoinBTC 16.678,36$16.678,36+0,32% +0,32% 1 EEthereumETH $1.230,40$1.230,40+0,52% +0,52% 2 UTetherUSDT $1,02$1,02-0,01% -0,01% 3 BBNBBNB $315,46$315,46-0,64% -0,64% 4 UUSD CoinUSDC $1,00$1,00+0,00% +0,00% 5 BBinance USDBUSD $1,00$1,00+0,00% +0,00% 6 XXRPXRP $0,4067$0,4067-0,13% -0,13% 7 DDogecoinDOGE $0,1052$0,1052+13,73% +13,73% 8 ACardanoADA $0,3232$0,3232+0,98% +0,98% 9 MPolygonMATIC $0,8727$0,8727+1,20% +1,20% 10 DPolkadotDOT $5,48$5,48+0,79% +0,79% </code></pre> <p>I created a regex to filter the mixed date:</p> <pre><code>import re pattern = re.compile(r'(\$.*)(\$)') for value in df['Price']: value = pattern.search(value) print(value.group(1)) </code></pre> <p>output:</p> <pre><code>$16.684,53 $1.230,25 $1,02 $315,56 $1,00 $1,00 $0,4078 $0,105 $0,3236 $0,8733 </code></pre> <p>but I couldn't find a way to change the values. Which is the best way to do it? Thanks.</p>
[ { "answer_id": 74593336, "author": "Moatasem La Kremed", "author_id": 10444949, "author_profile": "https://Stackoverflow.com/users/10444949", "pm_score": 1, "selected": false, "text": "a.Skip().ToArray();\n" }, { "answer_id": 74594172, "author": "Ruud Helderman", "author_id": 2485966, "author_profile": "https://Stackoverflow.com/users/2485966", "pm_score": 0, "selected": false, "text": "public static System.Collections.Generic.IEnumerable<TSource> Skip<TSource> (this System.Collections.Generic.IEnumerable<TSource> source, int count);\n Skip int[] whatGoesIn = {1, 2, 3};\nIEnumerable<int> whatComesOut = whatGoesIn.Skip(1);\n int[] ToArray Skip a public static bool Aa(int[] a, int k)\n a public static bool Aa(IEnumerable<int> a, int k)\n for IEnumerable<int> Length for (int i = 1; i < a.Length; i++)\n if (a[0] + a[i] == k)\n return true;\n k - a[0] bool found = a.Skip(1).Contains(k - a.First());\nif (found) return true;\n Length if (a.Length != 1)\n Aa(a.Skip(1), k);\nreturn false;\n Aa if (a.Length != 1)\n return Aa(a.Skip(1), k);\nreturn false;\n return a.Skip(1).Any() && Aa(a.Skip(1), k);\n public static bool Aa(IEnumerable<int> a, int k)\n{\n return a.Skip(1).Contains(k - a.First()) || (a.Skip(1).Any() && Aa(a.Skip(1), k));\n}\n public static bool Aa(IEnumerable<int> a, int k)\n{\n return a.Any() && (a.Skip(1).Contains(k - a.First()) || Aa(a.Skip(1), k));\n}\n for Contains Skip public static bool Aa(int[] a, int k, int start = 0)\n{\n for (int i = start + 1; i < a.Length; i++)\n if (a[start] + a[i] == k)\n return true;\n if (start < a.Length)\n return Aa(a, k, start + 1);\n return false;\n}\n ToArray" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20522688/" ]
74,593,211
<p>I added firebase analytics to my project and I'm using analytics in every use case. So in every file, I need to create a firebase analytics instance. like <code>FirebaseAnalytics analytics = FirebaseAnalytics.instance;</code>.</p> <p>So I was thinking what if I use getIt and inject the instance wherever I need in that case only one instance will be created. like <code> getIt.registerSingleton(FirebaseAnalytics.instance);</code></p>
[ { "answer_id": 74593251, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": 1, "selected": false, "text": "instance /// Returns an instance using the default [FirebaseApp].\n static FirebaseAuth get instance {\n FirebaseApp defaultAppInstance = Firebase.app();\n\n return FirebaseAuth.instanceFor(app: defaultAppInstance);\n }\n\n /// Returns an instance using a specified [FirebaseApp].\n /// Note that persistence can only be used on Web and is not supported on other platforms.\n factory FirebaseAuth.instanceFor(\n {required FirebaseApp app, Persistence? persistence}) {\n return _firebaseAuthInstances.putIfAbsent(app.name, () {\n return FirebaseAuth._(app: app, persistence: persistence);\n });\n }\n instance putIfAbsent" }, { "answer_id": 74593282, "author": "diegoveloper", "author_id": 666221, "author_profile": "https://Stackoverflow.com/users/666221", "pm_score": 3, "selected": true, "text": "FirebaseAnalytics class Analytics {\n Analytics(this.firebaseAnalytics);\n\n final FirebaseAnalytics firebaseAnalytics;\n\n void logEvent(String eventName, Map<String, dynamic> params) {\n // log any analytics here.\n }\n}\n\n \nfinal analytics = Analytics(FirebaseAnalytics.instance);\n \ngetIt.registerSingleton(analytics);\n\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14029095/" ]
74,593,219
<p>I am having difficulty finding a best practice in C# for 'base' classes.</p> <p>Is it true that base classes should only contain variables/properties that are used by EVERYTHING that inherits it?</p> <p>My example is a property is used by 3 out of the 7 classes that inherit the base class.</p> <pre><code>public class UpgradeBase { Public bool IsToggleable { get; set; } = false; } public class UpgradeBuilding : UpgradeBase { //This class needs to access IsToggleable } public class UpgradeScience : UpgradeBase { //This class does NOT need to access IsToggleable and never uses it } </code></pre> <p>Should I be only including this property in the classes that will be using it (the 3 out of 7 classes that actually need this property), or is it 'ok' to define it in the base class (even though 4 out of 7 won't ever care about it)?</p>
[ { "answer_id": 74593306, "author": "3Dave", "author_id": 135769, "author_profile": "https://Stackoverflow.com/users/135769", "pm_score": 0, "selected": false, "text": "public class UpgradeBase\n{\n\n}\n\npublic class UpgradeToggleable : UpgradeBase\n{\n public bool IsToggleable { get; set; } = false;\n}\n\npublic class UpgradeBuilding : UpgradeToggleable\n{\n //This class needs to access IsToggleable\n}\n\npublic class UpgradeScience : UpgradeBase\n{\n //This class does NOT need to access IsToggleable and never uses it\n}\n" }, { "answer_id": 74593423, "author": "BionicCode", "author_id": 3141792, "author_profile": "https://Stackoverflow.com/users/3141792", "pm_score": -1, "selected": false, "text": "Vehicle Engine Move() Car Truck Airplane Train Airplane Dive() IToggleable" }, { "answer_id": 74593600, "author": "Cédric Boivin", "author_id": 82595, "author_profile": "https://Stackoverflow.com/users/82595", "pm_score": 1, "selected": true, "text": "public class UpgradeBase\n{\n\n// Implement common properties and method\n }\n\npublic interface IToggleable \n{\n bool IsToggleable { get; set; }\n}\n\npublic class UpgradeBuilding : UpgradeBase, IToggleable\n{\n //This class needs to access IsToggleable\n public bool IsToggleable { get; set; } // Interface implementation\n}\n\npublic class UpgradeScience : UpgradeBase\n{\n //This class does NOT need to access IsToggleable and never uses it\n}\n" }, { "answer_id": 74593875, "author": "Milan Egon Votrubec", "author_id": 8051819, "author_profile": "https://Stackoverflow.com/users/8051819", "pm_score": 0, "selected": false, "text": "IsToggleable public interface IToggleable\n{\n // Define a readable property.\n bool isToggleable { get; }\n}\n public class UpgradeBase\n{\n // core base features ..\n}\n\npublic class UpgradeBuilding : UpgradeBase, IToggleable\n{\n public bool isToggleable { get; private set; }\n}\n\npublic class UpgradeScience : UpgradeBase\n{\n // ..\n}\n public interface IMovable { }\n public class NewClass : UpgradeBase, IMoveable\n{\n // a UpgradeBase that is also a IMoveable\n}\n UpgradeBase IMoveable // Populate this list with all UpgradeBase and derived class instances\nList<UpgradeBase> list;\n\nforeach ( var item in list )\n{\n if ( item is IMoveable )\n {\n // this item is moveable.\n }\n\n}\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20617131/" ]
74,593,227
<p>I made a text file with a list of usernames and passwords. My program (in a tkinter page) is supposed to check whether the username and password exists in the file, and then if it doesn't it makes a label that says 'username or password incorrect<a href="https://i.stack.imgur.com/LQRTp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LQRTp.png" alt="enter image description here" /></a>'. However, even when the username and password clealy exists in the text file, it will still print the 'incorrect' message. Here's an example of something in my text file:</p> <pre><code>testusername.testpassword </code></pre> <p>And here is the code that's supposed to detect it:</p> <pre><code>def login_incorrect(): Label(loginPage, text=&quot;Username or password incorrect.&quot;).place(x=120, y=120) # print(&quot;def login incorrect&quot;) def LoginToAccount(): print(&quot;def login to account&quot;) # while True: # This loop will run as long as the user is not logged in. with open('AccountDatabase.txt'): if loginUsernameE.get() + '.' + loginPasswordE.get() not in open('AccountDatabase.txt').read(): login_incorrect() print('incorrect') print(loginUsernameE.get() + '.' + loginPasswordE.get()) </code></pre> <p>But when I write <code>testusername</code> in the username field and <code>testpassword</code> in the password field, it still shows the error. Here's a screenshot:</p> <p>Why can't I detect if text is in a text file?</p>
[ { "answer_id": 74593381, "author": "RxiPland", "author_id": 15869190, "author_profile": "https://Stackoverflow.com/users/15869190", "pm_score": 0, "selected": false, "text": "def login_incorrect():\n Label(loginPage, text=\"Username or password incorrect.\").place(x=120, y=120)\n # print(\"def login incorrect\")\ndef LoginToAccount():\n print(\"def login to account\")\n # while True: # This loop will run as long as the user is not logged in.\n with open('AccountDatabase.txt', 'r') as f:\n\n if loginUsernameE.get() + '.' + loginPasswordE.get() not in f.read():\n login_incorrect()\n print('incorrect')\n print(loginUsernameE.get() + '.' + loginPasswordE.get())\n" }, { "answer_id": 74593909, "author": "Сергей Кох", "author_id": 18400908, "author_profile": "https://Stackoverflow.com/users/18400908", "pm_score": 1, "selected": false, "text": "with open('AccountDatabase.txt', 'r') as f:\n file_logins = f.read()\n if loginUsernameE.get() + '.' + loginPasswordE.get() not in file_logins:\n login_incorrect()\n print('incorrect')\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593227", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17235593/" ]
74,593,315
<p>I have a select that returns a table such as:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>weekOfTheYear</th> <th>mostRepeatedID</th> </tr> </thead> <tbody> <tr> <td>01</td> <td>a</td> </tr> <tr> <td>01</td> <td>b</td> </tr> <tr> <td>01</td> <td>a</td> </tr> <tr> <td>02</td> <td>b</td> </tr> <tr> <td>02</td> <td>b</td> </tr> <tr> <td>02</td> <td>a</td> </tr> </tbody> </table> </div> <p>and what I need is:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>weekOfTheYear</th> <th>mostRepeatedID</th> </tr> </thead> <tbody> <tr> <td>01</td> <td>a</td> </tr> <tr> <td>02</td> <td>b</td> </tr> </tbody> </table> </div> <p>so that each week of the year only appears once and the mostRepeatedID for each week, is the value that appears the most.</p>
[ { "answer_id": 74593555, "author": "Barbaros Özhan", "author_id": 5841306, "author_profile": "https://Stackoverflow.com/users/5841306", "pm_score": 1, "selected": true, "text": "mostRepeatedID weekOfTheYear WITH t1 AS\n( \n SELECT weekOfTheYear, mostRepeatedID, COUNT(*) AS cnt\n FROM t -- your table\n GROUP BY weekOfTheYear, mostRepeatedID \n)\nSELECT DISTINCT\n weekOfTheYear,\n MAX(mostRepeatedID) KEEP (DENSE_RANK FIRST ORDER BY cnt DESC) \n OVER (PARTITION BY weekOfTheYear) AS mostRepeatedID\n FROM t1\n b" }, { "answer_id": 74593869, "author": "MT0", "author_id": 1509264, "author_profile": "https://Stackoverflow.com/users/1509264", "pm_score": 2, "selected": false, "text": "DENSE_RANK SELECT weekOfTheYear,\n mostRepeatedId\nFROM table_name\nGROUP BY \n weekOfTheYear,\n mostRepeatedId\nORDER BY\n DENSE_RANK() OVER (\n PARTITION BY weekOfTheYear\n ORDER BY COUNT(*) DESC\n )\nFETCH FIRST ROW WITH TIES;\n CREATE TABLE table_name (weekOfTheYear, mostRepeatedID) AS\nSELECT '01', 'a' FROM DUAL UNION ALL\nSELECT '01', 'b' FROM DUAL UNION ALL\nSELECT '01', 'a' FROM DUAL UNION ALL\nSELECT '02', 'b' FROM DUAL UNION ALL\nSELECT '02', 'b' FROM DUAL UNION ALL\nSELECT '02', 'a' FROM DUAL UNION ALL\nSELECT '03', 'a' FROM DUAL UNION ALL\nSELECT '03', 'b' FROM DUAL UNION ALL\nSELECT '03', 'c' FROM DUAL;\n ROW_NUMBER DENSE_RANK ORDER BY COUNT(*) ORDER BY COUNT(*) DESC" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593315", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20490033/" ]
74,593,342
<p>I am trying to override mathjs Bignumber using:</p> <pre class="lang-js prettyprint-override"><code> import * as math from 'mathjs'; export const bgn = (v: number | math.BigNumber) =&gt; { const z = math.bignumber(v) as math.BigNumber; (z as any).toJSON = () =&gt; { return Number(math.larger(100, z) ? math.round(z,2) : math.round(z,4)).toFixed(4); } return z; } </code></pre> <p>but for some reason, it's still stringifying it to:</p> <pre class="lang-js prettyprint-override"><code>{&quot;mathjs&quot;:&quot;BigNumber&quot;,&quot;value&quot;:&quot;42500&quot;} </code></pre> <p>my goal is to stringify it to a number:</p> <pre class="lang-js prettyprint-override"><code>42500 </code></pre>
[ { "answer_id": 74593594, "author": "Alexander Mills", "author_id": 1223975, "author_profile": "https://Stackoverflow.com/users/1223975", "pm_score": 0, "selected": false, "text": "const math = require('mathjs');\n\nconst bgn = (v) => {\n const z = math.bignumber(v); // as math.BigNumber;\n (z).toJSON = () => {\n return Number(math.larger(z, 100) ? math.round(z, 3) : math.round(z, 5));\n }\n return z;\n}\n\nconsole.log(JSON.stringify(bgn(5.555555444)));\n" }, { "answer_id": 74593602, "author": "Bergi", "author_id": 1048572, "author_profile": "https://Stackoverflow.com/users/1048572", "pm_score": 1, "selected": false, "text": "JSON.stringify const text = JSON.stringify(value, (key, val) => {\n if (val instanceof math.bignumber) return JSON.rawJSON(val.toString())\n else return val;\n});\nconsole.log(text);\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1223975/" ]
74,593,369
<p>I have a text-area with no text inside, if i hit enter the cursor move's to the second row and blinking. I put some code inside to stop it but still nothing the text-area moves down. example:</p> <pre><code> function areaOnkeydown(e) { var code = (e.keyCode ? e.keyCode : e.which); if (code === 13) { if (_text.value === '') { return; // if there's no text and hit enter.. // return but move to second row } else { // do something here.. } } } </code></pre> <p>With 2 words on enter if text-area doesn't have any text remain as is do nothing.</p> <p>Thanks in advance.</p>
[ { "answer_id": 74594279, "author": "IT goldman", "author_id": 3807365, "author_profile": "https://Stackoverflow.com/users/3807365", "pm_score": 1, "selected": false, "text": "Event.preventDefault() function areaOnkeydown(e) {\n var code = (e.keyCode ? e.keyCode : e.which);\n var value = e.target.value\n if (code === 13) {\n if (value === '') {\n e.preventDefault()\n return;\n } else {\n // update: added this else 28/11/2022\n // so something\n }\n \n }\n}\n\ntextarea.addEventListener(\"keydown\", areaOnkeydown) <textarea id=\"textarea\" rows=\"4\"></textarea>" }, { "answer_id": 74594838, "author": "kitsaras", "author_id": 5674804, "author_profile": "https://Stackoverflow.com/users/5674804", "pm_score": 0, "selected": false, "text": "function areaOnkeydown(e) {\n var code = (e.keyCode ? e.keyCode : e.which);\n var value = e.target.value;\n if (code === 13) {\n if (value === '') {\n if (value && value.indexOf('\\n') > -1) {\n e.preventDefault();\n return;\n }\n e.preventDefault();\n return;\n }\n onSendText(e); // also i put the e.preventDefault(); here\n }\n}\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5674804/" ]
74,593,392
<p>I'm trying to center my title so I used <code>white-space: nowrap;</code> so it didn't stack and it appeared in one line but now it won't center. So there is the CSS code for the title and the appearance of it is fine, the only problem is that, instead of appearing centered, it starts from the center, and it keeps going right. So like, instead of &quot; Meet The Seekers &quot;, it does &quot; Meet the Seekers&quot;</p> <p>My code snippet is:</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>.section-title { font-size: 4rem; font-weight: 300; color: black; margin-bottom: 10px; text-transform: uppercase; letter-spacing: 0.2rem; clear: both; display: inline-block; overflow: hidden; white-space: nowrap; justify-content: center; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="about-top"&gt; &lt;h1 class="section-title"&gt;Meet the &lt;span&gt;SEE&lt;/span&gt;kers&lt;/h1&gt; &lt;p&gt;We are a team of young entrepreneurs, who decided it was time to modernize the way we search the web. A diverse group of unexpected talents came together to make SEE-Tool available to every web user.&lt;/p&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74594279, "author": "IT goldman", "author_id": 3807365, "author_profile": "https://Stackoverflow.com/users/3807365", "pm_score": 1, "selected": false, "text": "Event.preventDefault() function areaOnkeydown(e) {\n var code = (e.keyCode ? e.keyCode : e.which);\n var value = e.target.value\n if (code === 13) {\n if (value === '') {\n e.preventDefault()\n return;\n } else {\n // update: added this else 28/11/2022\n // so something\n }\n \n }\n}\n\ntextarea.addEventListener(\"keydown\", areaOnkeydown) <textarea id=\"textarea\" rows=\"4\"></textarea>" }, { "answer_id": 74594838, "author": "kitsaras", "author_id": 5674804, "author_profile": "https://Stackoverflow.com/users/5674804", "pm_score": 0, "selected": false, "text": "function areaOnkeydown(e) {\n var code = (e.keyCode ? e.keyCode : e.which);\n var value = e.target.value;\n if (code === 13) {\n if (value === '') {\n if (value && value.indexOf('\\n') > -1) {\n e.preventDefault();\n return;\n }\n e.preventDefault();\n return;\n }\n onSendText(e); // also i put the e.preventDefault(); here\n }\n}\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16073043/" ]
74,593,414
<p>I get as input times (hh:mm:ss) as float - e.g. 18:52:18 is a float 0.786331018518518.</p> <p>I achieved to calculate the time from a float value with this code:</p> <pre><code>val = 0.786331018518518 hour = int(val*24) minute = int((val*24-hour)*60) seconds = int(((val*24-hour)*60-minute)*60) print(f&quot;{hour}:{minute}:{seconds}&quot;) </code></pre> <p>How is it possible to calculate the float value from a time - so from 18:52:18 to 0.786331018518518?</p> <p>And generally isn't there an easier way to convert in both directions between float and time (I was thinking about the datetime module but was not able to find anything for this)?</p>
[ { "answer_id": 74593437, "author": "azro", "author_id": 7212686, "author_profile": "https://Stackoverflow.com/users/7212686", "pm_score": 3, "selected": true, "text": "datetime.timedelta val = 0.786331018518518\nd = timedelta(days=val)\nprint(d) # 18:52:19\n\nval = d.total_seconds() / 86400\nprint(val) # 0.7863310185185185\n print(hour / 24 + minute / 1440 + seconds / 86400)\n" }, { "answer_id": 74593457, "author": "kenntnisse", "author_id": 18318238, "author_profile": "https://Stackoverflow.com/users/18318238", "pm_score": 1, "selected": false, "text": "hours/24+minutes/60/24+seconds/60/60/24" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12415855/" ]
74,593,433
<p>I am trying to run the application but this error keeps prompting.</p> <p><strong>Description</strong>:</p> <p>Parameter 0 of constructor in com.clientui.clientui.controller.ClientController required a bean of type 'org.springframework.cloud.openfeign.FeignContext' that could not be found.</p> <p><strong>Action</strong>:</p> <p>Consider defining a bean of type 'org.springframework.cloud.openfeign.FeignContext' in your configuration.</p> <p>Here is the code:</p> <p><strong>Main</strong></p> <pre><code> package com.clientui.clientui; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @SpringBootApplication @EnableFeignClients(&quot;com.clientui&quot;) public class ClientuiApplication { public static void main(String[] args) { SpringApplication.run(ClientuiApplication.class, args); } } </code></pre> <p><strong>Controller</strong></p> <pre><code>package com.clientui.clientui.controller; import com.clientui.clientui.beans.ProductBean; import com.clientui.clientui.proxies.MicroserviceProduitsProxy; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import java.util.List; @Controller public class ClientController { private final MicroserviceProduitsProxy produitsProxy; public ClientController(MicroserviceProduitsProxy produitsProxy){ this.produitsProxy = produitsProxy; } @RequestMapping(&quot;/&quot;) public String accueil(Model model){ List&lt;ProductBean&gt; produits = produitsProxy.listeDesProduits(); model.addAttribute(&quot;produits&quot;, produits); return &quot;Accueil&quot;; } } </code></pre>
[ { "answer_id": 74607414, "author": "Joaonic", "author_id": 13856532, "author_profile": "https://Stackoverflow.com/users/13856532", "pm_score": 1, "selected": false, "text": "@ImportAutoConfiguration({FeignAutoConfiguration.class}) import org.springframework.cloud.openfeign.FeignAutoConfiguration;\n\n@SpringBootApplication\n@EnableFeignClients(\"com.clientui\")\n@ImportAutoConfiguration({FeignAutoConfiguration.class})\npublic class ClientuiApplication {\n\n public static void main(String[] args) {\n SpringApplication.run(ClientuiApplication.class, args);\n }\n\n}\n" }, { "answer_id": 74662770, "author": "Aleh Shyliuk", "author_id": 12273379, "author_profile": "https://Stackoverflow.com/users/12273379", "pm_score": 0, "selected": false, "text": "dependencyManagement <dependency>\n <groupId>org.springframework.cloud</groupId>\n <artifactId>spring-cloud-dependencies</artifactId>\n <version>2022.0.0-RC2</version>\n <type>pom</type>\n <scope>import</scope>\n</dependency>\n repositories <repository>\n <id>lib-m</id>\n <name>Spring Lib M</name>\n <url>https://repo.spring.io/libs-milestone/</url>\n</repository>\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19625477/" ]
74,593,442
<p>I am trying to create a notification system that gives custom notifications. Here is my function: <div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var notificationCount = 0; document.querySelector("body").innerHTML += '&lt;div class="notification-holder"&gt;&lt;/div&gt;'; function notification(content){ notificationCount+=1; document.querySelector(".notification-holder").innerHTML += ` &lt;div class="notification" id="notification-${notificationCount}"&gt; &lt;p&gt;${content}&lt;/p&gt; &lt;/div&gt; `; var msg = document.querySelector(`#notification-${notificationCount}`); msg.style.animation = "notificationAnimate 0.2s forwards" msg.addEventListener("animationend", () =&gt; { msg.style.visibility = "visible"; msg.style.animation = ""; setTimeout(() =&gt; { msg.style.animation="notificationAnimate 0.2s reverse" msg.addEventListener("animationend", () =&gt; { msg.remove() }) }, 1000) }) };</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>:root{ --black: #151515; --white: #EDEDEE; } .notification-holder{ position: absolute; bottom: 0px; right: 10px; padding-bottom: 10px; overflow: hidden; } .notification{ width: 250px; padding: 10px; text-align: center; background-color: var(--black); color: var(--white); font-size: 14px; font-family: "Poppins", sans-serif; border-radius: 10px; } .notification:not(:first-of-type){ margin-top: 10px; } @keyframes notificationAnimate{ 0%{ opacity: 0; max-height: 1px; transform: translateY(100px); scale: 0; } 100%{ opacity: 1; max-height: fit-content; transform: translateY(0px); /* visibility: visible; */ scale: 1; } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;html&gt; &lt;head&gt; &lt;/head&gt; &lt;body&gt; &lt;button onclick="notification('Dark theme has been enabled!')"&gt;Dark theme &lt;/button&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>The code works perfectly fine for 1 notification at a time. However, when there are multiple notifications at a time, only the latest one goes through the <code>reverse</code> animation.</p> <p><strong>Regenerate Problem:</strong></p> <ul> <li>Click on the button twice</li> <li>You will see only the latest notification goes back down. Earlier ones just stick there.</li> </ul> <p><strong>Expectation:</strong> I want all of them to go back down after <code>1s</code> of when they were shown.</p>
[ { "answer_id": 74607414, "author": "Joaonic", "author_id": 13856532, "author_profile": "https://Stackoverflow.com/users/13856532", "pm_score": 1, "selected": false, "text": "@ImportAutoConfiguration({FeignAutoConfiguration.class}) import org.springframework.cloud.openfeign.FeignAutoConfiguration;\n\n@SpringBootApplication\n@EnableFeignClients(\"com.clientui\")\n@ImportAutoConfiguration({FeignAutoConfiguration.class})\npublic class ClientuiApplication {\n\n public static void main(String[] args) {\n SpringApplication.run(ClientuiApplication.class, args);\n }\n\n}\n" }, { "answer_id": 74662770, "author": "Aleh Shyliuk", "author_id": 12273379, "author_profile": "https://Stackoverflow.com/users/12273379", "pm_score": 0, "selected": false, "text": "dependencyManagement <dependency>\n <groupId>org.springframework.cloud</groupId>\n <artifactId>spring-cloud-dependencies</artifactId>\n <version>2022.0.0-RC2</version>\n <type>pom</type>\n <scope>import</scope>\n</dependency>\n repositories <repository>\n <id>lib-m</id>\n <name>Spring Lib M</name>\n <url>https://repo.spring.io/libs-milestone/</url>\n</repository>\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15042008/" ]
74,593,459
<p>I want a list that displays the first element of the sublists I input.</p> <pre><code>def firstelements(w): return [item[0] for item in w] </code></pre> <p>Which works, but when I try doing</p> <pre><code>firstelements([[10,10],[3,5],[]]) </code></pre> <p>there's an error because of the <code>[]</code>. How can I fix this?</p>
[ { "answer_id": 74593476, "author": "Chris", "author_id": 15261315, "author_profile": "https://Stackoverflow.com/users/15261315", "pm_score": 2, "selected": false, "text": "def firstelements(w):\n return [item[0] for item in w if item != []]\n def firstelements(w):\n return [item[0] if item != [] else None for item in w]\n >>> firstelements([[10,10],[3,5],[]])\n[10, 3, None]\n" }, { "answer_id": 74593503, "author": "OneMadGypsy", "author_id": 10292330, "author_profile": "https://Stackoverflow.com/users/10292330", "pm_score": 1, "selected": false, "text": "def firstelements(w):\n return [item[0] for item in w if item]\n filter None def firstelements(w):\n return list(zip(*filter(None, w)))[0]\n def firstelements(w):\n return [item[0] for item in filter(None, w)]\n def firstelements(w):\n return [i for (i,*_) in filter(None, w)]\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20617137/" ]
74,593,461
<p>Viewing the source code of CPython on GitHub, I saw the method here:<br /> <a href="https://github.com/python/cpython/blob/main/Python/bltinmodule.c" rel="nofollow noreferrer">https://github.com/python/cpython/blob/main/Python/bltinmodule.c</a></p> <p>And more specifically:</p> <pre><code>static PyObject * builtin_sorted(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames) { PyObject *newlist, *v, *seq, *callable; /* Keyword arguments are passed through list.sort() which will check them. */ if (!_PyArg_UnpackStack(args, nargs, &quot;sorted&quot;, 1, 1, &amp;seq)) return NULL; newlist = PySequence_List(seq); if (newlist == NULL) return NULL; callable = _PyObject_GetAttrId(newlist, &amp;PyId_sort); if (callable == NULL) { Py_DECREF(newlist); return NULL; } assert(nargs &gt;= 1); v = _PyObject_FastCallKeywords(callable, args + 1, nargs - 1, kwnames); Py_DECREF(callable); if (v == NULL) { Py_DECREF(newlist); return NULL; } Py_DECREF(v); return newlist; } </code></pre> <p>I am not a C master, but I don't see any implementation of any of the known sorting algorithms, let alone the special sort that Python uses (I think it's called Timsort? - correct me if I'm wrong)</p> <p>I would highly appreciate if you could help me &quot;digest&quot; this code and understand it, because as of right now I've got:</p> <pre><code>PyObject *newlist, *v, *seq, *callable; </code></pre> <p>Which is creating a new list - even though list is mutable no? then why create a new one?<br /> and creating some other pointers, not sure why...</p> <p>then we unpack the rest of the arguments as the comment suggests, if it doesn't match the arguments there (being the function 'sorted' for example) then we break out..</p> <p>I am pretty sure I am reading this all completely wrong, so I stopped here...</p> <p>Thanks for the help in advanced, sorry for the multiple questions but this block of code is blowing my mind and learning to read this would help me a lot!</p>
[ { "answer_id": 74593624, "author": "chepner", "author_id": 1126841, "author_profile": "https://Stackoverflow.com/users/1126841", "pm_score": 1, "selected": false, "text": "list.sort sorted sorted def sorted(itr, *, key=None):\n newlist = list(itr)\n newlist.sort(key=key)\n return newlist\n" }, { "answer_id": 74593643, "author": "Jean-François Fabre", "author_id": 6451573, "author_profile": "https://Stackoverflow.com/users/6451573", "pm_score": 0, "selected": false, "text": "PyId_sort callable = _PyObject_GetAttrId(newlist, &PyId_sort);\n object.h PyId_xxx #define _Py_IDENTIFIER(varname) _Py_static_string(PyId_##varname, #varname)\n static PyObject *\nlist_sort_impl(PyListObject *self, PyObject *keyfunc, int reverse)\n/*[clinic end generated code: output=57b9f9c5e23fbe42 input=cb56cd179a713060]*/\n{\n /* An adaptive, stable, natural mergesort. See listsort.txt.\n * Returns Py_None on success, NULL on error. Even in case of error, the\n * list will be some permutation of its input state (nothing is lost or\n * duplicated).\n */\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13428065/" ]
74,593,497
<p>I'm using Keycloak version 20.0.1 (also tried on 19.0.0). I have a realm configured and under the Client Scopes -&gt; realm roles -&gt; Mappers I have added the <code>realm_access.roles</code> mapping.</p> <p>For some reasons that I don't understand, the JWT token that I get as a response doesn't contain the Realm Roles (I have also assigned a realm role to the user that it's used for testing).</p> <p>The response that I get is:</p> <pre><code>{ &quot;exp&quot;: 1669579902, &quot;iat&quot;: 1669579602, &quot;auth_time&quot;: 1669577841, &quot;jti&quot;: &quot;9dfe2638-a9f8-4094-8691-7a1423b629f7&quot;, &quot;iss&quot;: &quot;https://auth.xxxx.com/realms/xxxx.com&quot;, &quot;sub&quot;: &quot;6fe1b9b9-5ddd-478d-9b38-bd11698295cf&quot;, &quot;typ&quot;: &quot;Bearer&quot;, &quot;azp&quot;: &quot;spring-client&quot;, &quot;nonce&quot;: &quot;d14b168b-3c77-489b-85dd-192dba533624&quot;, &quot;session_state&quot;: &quot;55d938d4-42e7-4c2b-9038-f808c917c366&quot;, &quot;acr&quot;: &quot;0&quot;, &quot;allowed-origins&quot;: [ &quot;*&quot; ], &quot;scope&quot;: &quot;openid email profile roles&quot;, &quot;sid&quot;: &quot;55d938d4-42e7-4c2b-9038-f808c917c366&quot;, &quot;email_verified&quot;: true, &quot;name&quot;: &quot;first last&quot;, &quot;preferred_username&quot;: &quot;user@email.com&quot;, &quot;given_name&quot;: &quot;first&quot;, &quot;family_name&quot;: &quot;last&quot;, &quot;email&quot;: &quot;user@email.com&quot; } </code></pre> <p>How should I add the <code>roles</code> into the JWT response returned by Keycloak?</p> <p><a href="https://i.stack.imgur.com/gtz3Y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gtz3Y.png" alt="enter image description here" /></a></p> <p>I have tried to configure the Client Scopes -&gt; ream roles -&gt; Mappers and I was expecting to receive in the JWT response the <code>roles</code> field.</p>
[ { "answer_id": 74595089, "author": "Bench Vue", "author_id": 8054998, "author_profile": "https://Stackoverflow.com/users/8054998", "pm_score": 1, "selected": false, "text": "role mapping grant_type = password {\n \"exp\": 1669599866,\n \"iat\": 1669596266,\n \"jti\": \"ad4e3b51-b23e-4abb-aba6-0099bb5213cf\",\n \"iss\": \"http://localhost:8080/auth/realms/example\",\n \"aud\": \"account\",\n \"sub\": \"fae8bf9b-2209-4f01-ab32-629e029941ba\",\n \"typ\": \"Bearer\",\n \"azp\": \"spring-client\",\n \"session_state\": \"8debdcfa-4252-4a27-8190-2a4981e6a795\",\n \"acr\": \"1\",\n \"realm_access\": {\n \"roles\": [\n \"offline_access\",\n \"admin\",\n \"default-roles-example\",\n \"uma_authorization\",\n \"user\"\n ]\n },\n \"resource_access\": {\n \"spring-client\": {\n \"roles\": [\n \"client role2\"\n ]\n }\n },\n \"scope\": \"openid profile email\",\n \"sid\": \"8debdcfa-4252-4a27-8190-2a4981e6a795\",\n \"email_verified\": false,\n \"name\": \"first last\",\n \"preferred_username\": \"user\",\n \"given_name\": \"first\",\n \"family_name\": \"last\",\n \"email\": \"user@test.com\"\n}\n grant_type = client_credentials {\n \"exp\": 1669597154,\n \"iat\": 1669593554,\n \"jti\": \"ff6ae9db-7e05-4f9a-a538-0755a7f55125\",\n \"iss\": \"http://localhost:8080/auth/realms/example\",\n \"aud\": \"account\",\n \"sub\": \"9db11aa2-6862-4ebb-9ee6-b03b51d7814d\",\n \"typ\": \"Bearer\",\n \"azp\": \"spring-client\",\n \"acr\": \"1\",\n \"realm_access\": {\n \"roles\": [\n \"offline_access\",\n \"default-roles-example\",\n \"uma_authorization\"\n ]\n },\n \"scope\": \"openid profile email\",\n \"clientId\": \"spring-client\",\n \"clientHost\": \"172.19.0.1\",\n \"email_verified\": false,\n \"preferred_username\": \"service-account-spring-client\",\n \"clientAddress\": \"172.19.0.1\"\n}\n GET {KEYCLOAK-IP}/auth/admin/realms/{REALM-NAME}/clients/{client-UUID}/roles\n http://localhost:8080/auth/admin/realms/example/clients/1cb76d56-b96f-42a7-91c0-c201a7761e9e/roles\n [\n {\n \"id\": \"e5171eb5-976e-429f-914c-0d63d7b394fd\",\n \"name\": \"client role2\",\n \"composite\": false,\n \"clientRole\": true,\n \"containerId\": \"1cb76d56-b96f-42a7-91c0-c201a7761e9e\"\n },\n {\n \"id\": \"293c9c9c-bb76-4192-be09-ede769458394\",\n \"name\": \"uma_protection\",\n \"composite\": false,\n \"clientRole\": true,\n \"containerId\": \"1cb76d56-b96f-42a7-91c0-c201a7761e9e\"\n },\n {\n \"id\": \"e1441ceb-7ea8-436b-9a55-30999c6de744\",\n \"name\": \"client role1\",\n \"description\": \"\",\n \"composite\": false,\n \"clientRole\": true,\n \"containerId\": \"1cb76d56-b96f-42a7-91c0-c201a7761e9e\"\n }\n]\n http://localhost:8080/auth/admin/realms/example/users/fae8bf9b-2209-4f01-ab32-629e029941ba/role-mappings\n {\n \"realmMappings\": [\n {\n \"id\": \"c31bd5ce-e400-4546-b633-d4d5bde596d8\",\n \"name\": \"admin\",\n \"description\": \"Administrator privileges\",\n \"composite\": false,\n \"clientRole\": false,\n \"containerId\": \"e78f0c77-b44b-48da-850b-9d157e24a439\"\n },\n {\n \"id\": \"d99f61be-bacd-438d-974d-06a006704a1e\",\n \"name\": \"default-roles-example\",\n \"description\": \"${role_default-roles}\",\n \"composite\": true,\n \"clientRole\": false,\n \"containerId\": \"e78f0c77-b44b-48da-850b-9d157e24a439\"\n },\n {\n \"id\": \"8d250d6c-e249-4b63-b86f-390b4550b12e\",\n \"name\": \"user\",\n \"description\": \"User privileges\",\n \"composite\": false,\n \"clientRole\": false,\n \"containerId\": \"e78f0c77-b44b-48da-850b-9d157e24a439\"\n }\n ],\n \"clientMappings\": {\n \"spring-client\": {\n \"id\": \"1cb76d56-b96f-42a7-91c0-c201a7761e9e\",\n \"client\": \"spring-client\",\n \"mappings\": [\n {\n \"id\": \"e5171eb5-976e-429f-914c-0d63d7b394fd\",\n \"name\": \"client role2\",\n \"composite\": false,\n \"clientRole\": true,\n \"containerId\": \"1cb76d56-b96f-42a7-91c0-c201a7761e9e\"\n }\n ]\n }\n }\n}\n" }, { "answer_id": 74602616, "author": "Padmakar Kasture", "author_id": 12172880, "author_profile": "https://Stackoverflow.com/users/12172880", "pm_score": 0, "selected": false, "text": "/POST {keycloak_url}/admin/realms/demo/clients/<clientId>/protocol-mappers/models\n {\n\"protocol\":\"openid-connect\",\n\"config{\n\"multivalued\":\"true\",\n\"id.token.claim\":\"true\",\n\"access.token.claim\":\"true\",\n\"userinfo.token.claim\":\"true\",\n\"usermodel.realmRoleMapping.rolePrefix\":\"\",\n\"claim.name\":\"realmRoles\"\n},\n\"name\":\"roleNameMapper\",\n\"protocolMapper\":\"oidc-usermodel-realm-role-mapper\"\n}\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593497", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18215650/" ]
74,593,534
<p>my issue is when I am creating a user in the rails console then it is not created. You can also check the below code:</p> <p><strong>This is my console:</strong></p> <pre class="lang-rb prettyprint-override"><code>Loading development environment (Rails 7.0.4) irb(main):001:0&gt; User.create(name: 'Tom', photo: 'https://unsplash.com/photos/F_ -0BxGuVvo', bio: 'Teacher from Mexico.') =&gt; #&lt;User:0x00007fb4e899aa80 id: nil, name: &quot;Tom&quot;, photo: &quot;https://unsplash.com/photos/F_-0BxGuVvo&quot;, bio: &quot;Teacher from Mexico.&quot;, posts_counter: nil, created_at: nil, updated_at: nil&gt; </code></pre> <p><strong>These are my schema:</strong></p> <pre class="lang-rb prettyprint-override"><code> create_table &quot;comments&quot;, force: :cascade do |t| t.string &quot;text&quot; t.datetime &quot;created_at&quot;, null: false t.datetime &quot;updated_at&quot;, null: false t.bigint &quot;post_id&quot; t.bigint &quot;author_id&quot; t.index [&quot;author_id&quot;], name: &quot;index_comments_on_author_id&quot; t.index [&quot;post_id&quot;], name: &quot;index_comments_on_post_id&quot; end create_table &quot;likes&quot;, force: :cascade do |t| t.datetime &quot;created_at&quot;, null: false t.datetime &quot;updated_at&quot;, null: false t.bigint &quot;post_id&quot; t.bigint &quot;author_id&quot; t.index [&quot;author_id&quot;], name: &quot;index_likes_on_author_id&quot; t.index [&quot;post_id&quot;], name: &quot;index_likes_on_post_id&quot; end create_table &quot;posts&quot;, force: :cascade do |t| t.string &quot;title&quot; t.string &quot;text&quot; t.integer &quot;comments_counter&quot; t.integer &quot;likes_counter&quot; t.datetime &quot;created_at&quot;, null: false t.datetime &quot;updated_at&quot;, null: false t.bigint &quot;author_id&quot; t.index [&quot;author_id&quot;], name: &quot;index_posts_on_author_id&quot; end create_table &quot;users&quot;, force: :cascade do |t| t.string &quot;name&quot; t.string &quot;photo&quot; t.string &quot;bio&quot; t.integer &quot;posts_counter&quot; t.datetime &quot;created_at&quot;, null: false t.datetime &quot;updated_at&quot;, null: false end add_foreign_key &quot;comments&quot;, &quot;posts&quot; add_foreign_key &quot;comments&quot;, &quot;users&quot;, column: &quot;author_id&quot; add_foreign_key &quot;likes&quot;, &quot;posts&quot; add_foreign_key &quot;likes&quot;, &quot;users&quot;, column: &quot;author_id&quot; add_foreign_key &quot;posts&quot;, &quot;users&quot;, column: &quot;author_id&quot; </code></pre> <p><strong>This is my user model:</strong></p> <pre class="lang-rb prettyprint-override"><code>class User &lt; ApplicationRecord has_many :likes, foreign_key: &quot;author_id&quot; has_many :comments, foreign_key: &quot;author_id&quot; has_many :posts, foreign_key: &quot;author_id&quot; validates :name, presence: true validates :posts_counter, numericality: { only_integer: true, greater_than_or_equal_to: 0 } def most_recent_posts posts.order(created_at: :desc).limit(3) end end </code></pre> <p>Thank you in advance.</p> <p>You can check the above code and if anyone solves this problem then please help me.</p>
[ { "answer_id": 74595089, "author": "Bench Vue", "author_id": 8054998, "author_profile": "https://Stackoverflow.com/users/8054998", "pm_score": 1, "selected": false, "text": "role mapping grant_type = password {\n \"exp\": 1669599866,\n \"iat\": 1669596266,\n \"jti\": \"ad4e3b51-b23e-4abb-aba6-0099bb5213cf\",\n \"iss\": \"http://localhost:8080/auth/realms/example\",\n \"aud\": \"account\",\n \"sub\": \"fae8bf9b-2209-4f01-ab32-629e029941ba\",\n \"typ\": \"Bearer\",\n \"azp\": \"spring-client\",\n \"session_state\": \"8debdcfa-4252-4a27-8190-2a4981e6a795\",\n \"acr\": \"1\",\n \"realm_access\": {\n \"roles\": [\n \"offline_access\",\n \"admin\",\n \"default-roles-example\",\n \"uma_authorization\",\n \"user\"\n ]\n },\n \"resource_access\": {\n \"spring-client\": {\n \"roles\": [\n \"client role2\"\n ]\n }\n },\n \"scope\": \"openid profile email\",\n \"sid\": \"8debdcfa-4252-4a27-8190-2a4981e6a795\",\n \"email_verified\": false,\n \"name\": \"first last\",\n \"preferred_username\": \"user\",\n \"given_name\": \"first\",\n \"family_name\": \"last\",\n \"email\": \"user@test.com\"\n}\n grant_type = client_credentials {\n \"exp\": 1669597154,\n \"iat\": 1669593554,\n \"jti\": \"ff6ae9db-7e05-4f9a-a538-0755a7f55125\",\n \"iss\": \"http://localhost:8080/auth/realms/example\",\n \"aud\": \"account\",\n \"sub\": \"9db11aa2-6862-4ebb-9ee6-b03b51d7814d\",\n \"typ\": \"Bearer\",\n \"azp\": \"spring-client\",\n \"acr\": \"1\",\n \"realm_access\": {\n \"roles\": [\n \"offline_access\",\n \"default-roles-example\",\n \"uma_authorization\"\n ]\n },\n \"scope\": \"openid profile email\",\n \"clientId\": \"spring-client\",\n \"clientHost\": \"172.19.0.1\",\n \"email_verified\": false,\n \"preferred_username\": \"service-account-spring-client\",\n \"clientAddress\": \"172.19.0.1\"\n}\n GET {KEYCLOAK-IP}/auth/admin/realms/{REALM-NAME}/clients/{client-UUID}/roles\n http://localhost:8080/auth/admin/realms/example/clients/1cb76d56-b96f-42a7-91c0-c201a7761e9e/roles\n [\n {\n \"id\": \"e5171eb5-976e-429f-914c-0d63d7b394fd\",\n \"name\": \"client role2\",\n \"composite\": false,\n \"clientRole\": true,\n \"containerId\": \"1cb76d56-b96f-42a7-91c0-c201a7761e9e\"\n },\n {\n \"id\": \"293c9c9c-bb76-4192-be09-ede769458394\",\n \"name\": \"uma_protection\",\n \"composite\": false,\n \"clientRole\": true,\n \"containerId\": \"1cb76d56-b96f-42a7-91c0-c201a7761e9e\"\n },\n {\n \"id\": \"e1441ceb-7ea8-436b-9a55-30999c6de744\",\n \"name\": \"client role1\",\n \"description\": \"\",\n \"composite\": false,\n \"clientRole\": true,\n \"containerId\": \"1cb76d56-b96f-42a7-91c0-c201a7761e9e\"\n }\n]\n http://localhost:8080/auth/admin/realms/example/users/fae8bf9b-2209-4f01-ab32-629e029941ba/role-mappings\n {\n \"realmMappings\": [\n {\n \"id\": \"c31bd5ce-e400-4546-b633-d4d5bde596d8\",\n \"name\": \"admin\",\n \"description\": \"Administrator privileges\",\n \"composite\": false,\n \"clientRole\": false,\n \"containerId\": \"e78f0c77-b44b-48da-850b-9d157e24a439\"\n },\n {\n \"id\": \"d99f61be-bacd-438d-974d-06a006704a1e\",\n \"name\": \"default-roles-example\",\n \"description\": \"${role_default-roles}\",\n \"composite\": true,\n \"clientRole\": false,\n \"containerId\": \"e78f0c77-b44b-48da-850b-9d157e24a439\"\n },\n {\n \"id\": \"8d250d6c-e249-4b63-b86f-390b4550b12e\",\n \"name\": \"user\",\n \"description\": \"User privileges\",\n \"composite\": false,\n \"clientRole\": false,\n \"containerId\": \"e78f0c77-b44b-48da-850b-9d157e24a439\"\n }\n ],\n \"clientMappings\": {\n \"spring-client\": {\n \"id\": \"1cb76d56-b96f-42a7-91c0-c201a7761e9e\",\n \"client\": \"spring-client\",\n \"mappings\": [\n {\n \"id\": \"e5171eb5-976e-429f-914c-0d63d7b394fd\",\n \"name\": \"client role2\",\n \"composite\": false,\n \"clientRole\": true,\n \"containerId\": \"1cb76d56-b96f-42a7-91c0-c201a7761e9e\"\n }\n ]\n }\n }\n}\n" }, { "answer_id": 74602616, "author": "Padmakar Kasture", "author_id": 12172880, "author_profile": "https://Stackoverflow.com/users/12172880", "pm_score": 0, "selected": false, "text": "/POST {keycloak_url}/admin/realms/demo/clients/<clientId>/protocol-mappers/models\n {\n\"protocol\":\"openid-connect\",\n\"config{\n\"multivalued\":\"true\",\n\"id.token.claim\":\"true\",\n\"access.token.claim\":\"true\",\n\"userinfo.token.claim\":\"true\",\n\"usermodel.realmRoleMapping.rolePrefix\":\"\",\n\"claim.name\":\"realmRoles\"\n},\n\"name\":\"roleNameMapper\",\n\"protocolMapper\":\"oidc-usermodel-realm-role-mapper\"\n}\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15047456/" ]
74,593,566
<p>as in title. I am new in the react and I write simple todoApp. My App.js:</p> <pre><code>const App = () =&gt; { const initTasks = [ {id: 1,text: 'Task1'}, {id: 2,text: &quot;Task2&quot;}, {id: 3,text: &quot;Task3&quot;}] const [tasks, setTasks] = useState(initTasks); const deleteTask = (index) =&gt; { let cp =tasks.filter(x=&gt;x.id !== index); setTasks(cp); console.log(tasks); }; const addTask =(text) =&gt; { let newTask ={id:tasks.length+1,text:text}; setTasks([...tasks,newTask]); } return ( &lt;Router&gt; &lt;div className='container'&gt; &lt;Header title='Titlee'/&gt; &lt;AddTasks addTask={addTask}&gt;&lt;/AddTasks&gt; &lt;Routes&gt; &lt;Route path='/' element= { &lt;&gt; {tasks.length &gt; 0 ? ( &lt;Tasks tasks={tasks} onDelete={deleteTask} toggle={toggleReminder} /&gt; ) : ( 'No Tasks To Show' ) } &lt;/&gt; }&gt;&lt;/Route&gt; &lt;Route path='/about' element={&lt;About /&gt;} &gt;&lt;/Route&gt; &lt;/Routes&gt; &lt;Footer&gt;&lt;/Footer&gt; &lt;/div&gt; &lt;/Router&gt; ) } export default App; </code></pre> <p>My Tasks:</p> <pre><code>const Tasks =({tasks, onDelete, toggle}) =&gt; { return ( tasks.map((task) =&gt; ( &lt;Task key={task.id} task={task} onDelete={onDelete} toggle={toggle}/&gt; )) ) } export default Tasks </code></pre> <p>and my Task.js</p> <pre><code>const Task = ({ task, onDelete,toggle }) =&gt; { return ( &lt;div className='task' onClick={()=&gt;toggle(task.id)} key={task.id}&gt; &lt;h3&gt;{task.text} &lt;FaTimes style={{color: 'red', cursor: 'pointer'}} onClick={()=&gt;onDelete(task.id)}/&gt; &lt;/h3&gt; &lt;p&gt;{task.id}&lt;/p&gt; &lt;/div&gt; ) } export default Task </code></pre> <p>I have init state with 3 hardcoded tasks in App.js. Adding new tasks works proper, and tasks are succesfully updated. The problem is with deleteTask - in 'cp' collection I have updated list of tasks, but console.log (fired just after setTasks) is shows not updated collection. Why? What is improperly done, and how to explain this bug? Moreover - lists of my tasks are not updated (in html) - why? Regards</p> <p>EDIT: It doesn't matter how I initialize array with tasks. Deleting doesn't work even on case with empty array at the begining</p>
[ { "answer_id": 74593663, "author": "John Li", "author_id": 20436957, "author_profile": "https://Stackoverflow.com/users/20436957", "pm_score": 2, "selected": false, "text": "setTasks console.log(tasks) tasks const deleteTask = (index) =>\n setTasks((prev) => prev.filter((x) => x.id !== index));\n addTask id index const addTask = (text) =>\n setTasks((prev) => {\n if (!Array.isArray(prev) || prev.length === 0) return [{ id: 1, text }];\n return [...prev, { id: prev[prev.length - 1].id + 1, text }];\n });\n const Task = ({ task, onDelete }) => {\n return (\n <div className=\"task\" key={task.id}>\n <h3>\n {task.text}\n <button\n style={{ color: \"red\", cursor: \"pointer\" }}\n onClick={() => onDelete(task.id)}\n >\n delete\n </button>\n </h3>\n </div>\n );\n};\n\nconst Tasks = ({ tasks, onDelete }) => {\n return tasks.map((task) => (\n <Task key={task.id} task={task} onDelete={onDelete} />\n ));\n};\n\nconst AddTasks = ({ addTask }) => {\n const inputRef = React.useRef(null);\n const handleSubmit = (e) => {\n e.preventDefault();\n const { value } = inputRef.current;\n if (!value) return;\n addTask(value);\n };\n return (\n <form className=\"add\" onSubmit={handleSubmit}>\n <input type=\"text\" ref={inputRef} />\n <button type=\"submit\">Add Task</button>\n </form>\n );\n};\n\nconst App = () => {\n const [tasks, setTasks] = React.useState([\n { id: 1, text: \"Task 1\" },\n { id: 2, text: \"Task 2\" },\n { id: 3, text: \"Task 3\" },\n ]);\n\n const deleteTask = (index) =>\n setTasks((prev) => prev.filter((x) => x.id !== index));\n\n const addTask = (text) =>\n setTasks((prev) => {\n if (!Array.isArray(prev) || prev.length === 0) return [{ id: 1, text }];\n return [...prev, { id: prev[prev.length - 1].id + 1, text }];\n });\n\n return (\n <div className=\"app\">\n <div className=\"container\">\n <AddTasks addTask={addTask}></AddTasks>\n {tasks.length > 0 ? (\n <Tasks tasks={tasks} onDelete={deleteTask} />\n ) : (\n \"No Tasks To Show\"\n )}\n </div>\n </div>\n );\n};\n\nReactDOM.render(<App />, document.querySelector(\"#root\")); <div id=\"root\"></div>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.production.min.js\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.production.min.js\"></script>" }, { "answer_id": 74593772, "author": "Amirhossein", "author_id": 11342834, "author_profile": "https://Stackoverflow.com/users/11342834", "pm_score": -1, "selected": false, "text": "const deleteTask = (index) =>\n{\n const cp = tasks.filter(x=> x.id !== index);\n setTasks(cp);\n};\n\nuseEffect(() => {\n console.log(tasks);\n}, [tasks]);\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14566071/" ]
74,593,569
<p>I am trying to set an attribute for the input tag webelement for the value but actually I am getting this below error</p> <p>Below is the code which I have written for this,</p> <pre><code>'document.getElementsByName('date')[0].setAttribute('value','2022-11-29');' </code></pre> <p>and the below error is getting</p> <p><a href="https://i.stack.imgur.com/PovEr.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PovEr.jpg" alt="enter image description here" /></a></p> <p>Can some one help with this,</p> <p>Thanks in Advance</p>
[ { "answer_id": 74593663, "author": "John Li", "author_id": 20436957, "author_profile": "https://Stackoverflow.com/users/20436957", "pm_score": 2, "selected": false, "text": "setTasks console.log(tasks) tasks const deleteTask = (index) =>\n setTasks((prev) => prev.filter((x) => x.id !== index));\n addTask id index const addTask = (text) =>\n setTasks((prev) => {\n if (!Array.isArray(prev) || prev.length === 0) return [{ id: 1, text }];\n return [...prev, { id: prev[prev.length - 1].id + 1, text }];\n });\n const Task = ({ task, onDelete }) => {\n return (\n <div className=\"task\" key={task.id}>\n <h3>\n {task.text}\n <button\n style={{ color: \"red\", cursor: \"pointer\" }}\n onClick={() => onDelete(task.id)}\n >\n delete\n </button>\n </h3>\n </div>\n );\n};\n\nconst Tasks = ({ tasks, onDelete }) => {\n return tasks.map((task) => (\n <Task key={task.id} task={task} onDelete={onDelete} />\n ));\n};\n\nconst AddTasks = ({ addTask }) => {\n const inputRef = React.useRef(null);\n const handleSubmit = (e) => {\n e.preventDefault();\n const { value } = inputRef.current;\n if (!value) return;\n addTask(value);\n };\n return (\n <form className=\"add\" onSubmit={handleSubmit}>\n <input type=\"text\" ref={inputRef} />\n <button type=\"submit\">Add Task</button>\n </form>\n );\n};\n\nconst App = () => {\n const [tasks, setTasks] = React.useState([\n { id: 1, text: \"Task 1\" },\n { id: 2, text: \"Task 2\" },\n { id: 3, text: \"Task 3\" },\n ]);\n\n const deleteTask = (index) =>\n setTasks((prev) => prev.filter((x) => x.id !== index));\n\n const addTask = (text) =>\n setTasks((prev) => {\n if (!Array.isArray(prev) || prev.length === 0) return [{ id: 1, text }];\n return [...prev, { id: prev[prev.length - 1].id + 1, text }];\n });\n\n return (\n <div className=\"app\">\n <div className=\"container\">\n <AddTasks addTask={addTask}></AddTasks>\n {tasks.length > 0 ? (\n <Tasks tasks={tasks} onDelete={deleteTask} />\n ) : (\n \"No Tasks To Show\"\n )}\n </div>\n </div>\n );\n};\n\nReactDOM.render(<App />, document.querySelector(\"#root\")); <div id=\"root\"></div>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.production.min.js\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.production.min.js\"></script>" }, { "answer_id": 74593772, "author": "Amirhossein", "author_id": 11342834, "author_profile": "https://Stackoverflow.com/users/11342834", "pm_score": -1, "selected": false, "text": "const deleteTask = (index) =>\n{\n const cp = tasks.filter(x=> x.id !== index);\n setTasks(cp);\n};\n\nuseEffect(() => {\n console.log(tasks);\n}, [tasks]);\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4894253/" ]
74,593,580
<p>Is it possible to filter by how many + signs are in a row in r and also if a certain letter (or word) is in the row?</p> <p>Like for example if I only wanted to filter rows with 2 or more + signs and they also have to include c.</p> <p>Example input:</p> <pre><code>a + b + c a + b a + c a + b + b a + c + c a + b + c + d </code></pre> <p>Example output:</p> <pre><code>a + b + c a + c + c a + b + c + d </code></pre>
[ { "answer_id": 74593663, "author": "John Li", "author_id": 20436957, "author_profile": "https://Stackoverflow.com/users/20436957", "pm_score": 2, "selected": false, "text": "setTasks console.log(tasks) tasks const deleteTask = (index) =>\n setTasks((prev) => prev.filter((x) => x.id !== index));\n addTask id index const addTask = (text) =>\n setTasks((prev) => {\n if (!Array.isArray(prev) || prev.length === 0) return [{ id: 1, text }];\n return [...prev, { id: prev[prev.length - 1].id + 1, text }];\n });\n const Task = ({ task, onDelete }) => {\n return (\n <div className=\"task\" key={task.id}>\n <h3>\n {task.text}\n <button\n style={{ color: \"red\", cursor: \"pointer\" }}\n onClick={() => onDelete(task.id)}\n >\n delete\n </button>\n </h3>\n </div>\n );\n};\n\nconst Tasks = ({ tasks, onDelete }) => {\n return tasks.map((task) => (\n <Task key={task.id} task={task} onDelete={onDelete} />\n ));\n};\n\nconst AddTasks = ({ addTask }) => {\n const inputRef = React.useRef(null);\n const handleSubmit = (e) => {\n e.preventDefault();\n const { value } = inputRef.current;\n if (!value) return;\n addTask(value);\n };\n return (\n <form className=\"add\" onSubmit={handleSubmit}>\n <input type=\"text\" ref={inputRef} />\n <button type=\"submit\">Add Task</button>\n </form>\n );\n};\n\nconst App = () => {\n const [tasks, setTasks] = React.useState([\n { id: 1, text: \"Task 1\" },\n { id: 2, text: \"Task 2\" },\n { id: 3, text: \"Task 3\" },\n ]);\n\n const deleteTask = (index) =>\n setTasks((prev) => prev.filter((x) => x.id !== index));\n\n const addTask = (text) =>\n setTasks((prev) => {\n if (!Array.isArray(prev) || prev.length === 0) return [{ id: 1, text }];\n return [...prev, { id: prev[prev.length - 1].id + 1, text }];\n });\n\n return (\n <div className=\"app\">\n <div className=\"container\">\n <AddTasks addTask={addTask}></AddTasks>\n {tasks.length > 0 ? (\n <Tasks tasks={tasks} onDelete={deleteTask} />\n ) : (\n \"No Tasks To Show\"\n )}\n </div>\n </div>\n );\n};\n\nReactDOM.render(<App />, document.querySelector(\"#root\")); <div id=\"root\"></div>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.production.min.js\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.production.min.js\"></script>" }, { "answer_id": 74593772, "author": "Amirhossein", "author_id": 11342834, "author_profile": "https://Stackoverflow.com/users/11342834", "pm_score": -1, "selected": false, "text": "const deleteTask = (index) =>\n{\n const cp = tasks.filter(x=> x.id !== index);\n setTasks(cp);\n};\n\nuseEffect(() => {\n console.log(tasks);\n}, [tasks]);\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593580", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18564314/" ]
74,593,584
<p>I working on Azure Function App and would like to adding custom messages/traces which can aid in debugging and improving performance. THis is my code I am using:</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>var telemetry = new Microsoft.ApplicationInsights.TelemetryClient(); telemetry.TrackTrace("Alert Button Pressed by Device -&gt;"+CloudObject.A, SeverityLevel.Warning,new Dictionary&lt;string, string&gt; { { "IoT Object", IOTMESSAGE } });</code></pre> </div> </div> </p> <p>But when I go to Application Insight and Query traces(All) I do not see trace message I am setting.</p> <p>Am I doing something wrong?</p>
[ { "answer_id": 74593663, "author": "John Li", "author_id": 20436957, "author_profile": "https://Stackoverflow.com/users/20436957", "pm_score": 2, "selected": false, "text": "setTasks console.log(tasks) tasks const deleteTask = (index) =>\n setTasks((prev) => prev.filter((x) => x.id !== index));\n addTask id index const addTask = (text) =>\n setTasks((prev) => {\n if (!Array.isArray(prev) || prev.length === 0) return [{ id: 1, text }];\n return [...prev, { id: prev[prev.length - 1].id + 1, text }];\n });\n const Task = ({ task, onDelete }) => {\n return (\n <div className=\"task\" key={task.id}>\n <h3>\n {task.text}\n <button\n style={{ color: \"red\", cursor: \"pointer\" }}\n onClick={() => onDelete(task.id)}\n >\n delete\n </button>\n </h3>\n </div>\n );\n};\n\nconst Tasks = ({ tasks, onDelete }) => {\n return tasks.map((task) => (\n <Task key={task.id} task={task} onDelete={onDelete} />\n ));\n};\n\nconst AddTasks = ({ addTask }) => {\n const inputRef = React.useRef(null);\n const handleSubmit = (e) => {\n e.preventDefault();\n const { value } = inputRef.current;\n if (!value) return;\n addTask(value);\n };\n return (\n <form className=\"add\" onSubmit={handleSubmit}>\n <input type=\"text\" ref={inputRef} />\n <button type=\"submit\">Add Task</button>\n </form>\n );\n};\n\nconst App = () => {\n const [tasks, setTasks] = React.useState([\n { id: 1, text: \"Task 1\" },\n { id: 2, text: \"Task 2\" },\n { id: 3, text: \"Task 3\" },\n ]);\n\n const deleteTask = (index) =>\n setTasks((prev) => prev.filter((x) => x.id !== index));\n\n const addTask = (text) =>\n setTasks((prev) => {\n if (!Array.isArray(prev) || prev.length === 0) return [{ id: 1, text }];\n return [...prev, { id: prev[prev.length - 1].id + 1, text }];\n });\n\n return (\n <div className=\"app\">\n <div className=\"container\">\n <AddTasks addTask={addTask}></AddTasks>\n {tasks.length > 0 ? (\n <Tasks tasks={tasks} onDelete={deleteTask} />\n ) : (\n \"No Tasks To Show\"\n )}\n </div>\n </div>\n );\n};\n\nReactDOM.render(<App />, document.querySelector(\"#root\")); <div id=\"root\"></div>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.production.min.js\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.production.min.js\"></script>" }, { "answer_id": 74593772, "author": "Amirhossein", "author_id": 11342834, "author_profile": "https://Stackoverflow.com/users/11342834", "pm_score": -1, "selected": false, "text": "const deleteTask = (index) =>\n{\n const cp = tasks.filter(x=> x.id !== index);\n setTasks(cp);\n};\n\nuseEffect(() => {\n console.log(tasks);\n}, [tasks]);\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8400863/" ]
74,593,617
<p>I want to get docker image URL from the user but URLs can't be acceptable with <code>models.URLField()</code> in django.<br>For example, this URL: <code>hub.something.com/nginx:1.21</code>, got an error.<br>How can fix it?</p>
[ { "answer_id": 74594234, "author": "Adrian Kurzeja", "author_id": 8571154, "author_profile": "https://Stackoverflow.com/users/8571154", "pm_score": 2, "selected": false, "text": "from django.core.validators import URLValidator\nfrom django.utils.deconstruct import deconstructible\nfrom django.db import models\n\n# I suggest to move this class to validators.py outside of this app folder \n# so it can be easily accessible by all models\n@deconstructible\nclass DockerHubURLValidator(URLValidator):\n domain_re = URLValidator.domain_re + '(?:[a-z0-9-.\\/:]*)'\n\n\nclass ModelName(models.Model):\n image = models.CharField(max_length=200, validators=[DockerHubURLValidator()])\n domain_re .com/nginx:1.21" }, { "answer_id": 74594334, "author": "mo1ein", "author_id": 12727539, "author_profile": "https://Stackoverflow.com/users/12727539", "pm_score": 1, "selected": true, "text": "from django.db import models\nfrom django.core.validators import RegexValidator\n\n\nclass App(models.Model):\n image = models.CharField(\n max_length=200,\n validators=[\n RegexValidator(\n regex=r'^(?:(?=[^:\\/]{1,253})(?!-)[a-zA-Z0-9-]{1,63}(?<!-)(?:\\.(?!-)[a-zA-Z0-9-]{1,63}(?<!-))*(?::[0-9]{1,5})?/)?((?![._-])(?:[a-z0-9._-]*)(?<![._-])(?:/(?![._-])[a-z0-9._-]*(?<![._-]))*)(?::(?![.-])[a-zA-Z0-9_.-]{1,128})?$',\n message='image is not valid',\n code='invalid_url'\n )\n ]\n )\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12727539/" ]
74,593,625
<p>Input data:</p> <ol> <li>LinearLayout with a couple of views (further &quot;Info&quot;)</li> <li>RecyclerView with pagination</li> </ol> <p>In theory, the objective is easy: make both views scrollable like a single container. In practice, it is ridiculously complicated.</p> <p><strong>Attempt #1: NestedScrollView</strong></p> <p>Before I integrated the Paging library, both the Info and the Recycler were inside of a NestedScrollView and it worked as I wanted, except for the performance (sometimes there are ~500 items, and the UI freezes for ~4 seconds). Now, since RecyclerView is inside the NestedScrollView, my paging doesn't work: it loads all the data at once! I decided to find another way.</p> <p><strong>Attempt #2: CoordinatorLayout</strong></p> <p>I found <a href="https://stackoverflow.com/a/68195028/17088333">this answer</a> to be a possible solution. And it works perfectly with highly populated RecyclerView. However, when the list is empty, I can scroll all the way down to the blank screen and I won't be able to scroll back up. If I have a few items, I can also scroll halfway to the blank screen. Only a high amount of data works well with this approach. I understand that behavior because I have a scroll flag &quot;exitUntilCollapsed&quot; but is there a workaround for this?</p> <p>Is there any solution to this problem? Such a simple task requires tons of workarounds (and workarounds for workarounds) to have the info and the recycler to be scrollable as a single container.</p>
[ { "answer_id": 74594234, "author": "Adrian Kurzeja", "author_id": 8571154, "author_profile": "https://Stackoverflow.com/users/8571154", "pm_score": 2, "selected": false, "text": "from django.core.validators import URLValidator\nfrom django.utils.deconstruct import deconstructible\nfrom django.db import models\n\n# I suggest to move this class to validators.py outside of this app folder \n# so it can be easily accessible by all models\n@deconstructible\nclass DockerHubURLValidator(URLValidator):\n domain_re = URLValidator.domain_re + '(?:[a-z0-9-.\\/:]*)'\n\n\nclass ModelName(models.Model):\n image = models.CharField(max_length=200, validators=[DockerHubURLValidator()])\n domain_re .com/nginx:1.21" }, { "answer_id": 74594334, "author": "mo1ein", "author_id": 12727539, "author_profile": "https://Stackoverflow.com/users/12727539", "pm_score": 1, "selected": true, "text": "from django.db import models\nfrom django.core.validators import RegexValidator\n\n\nclass App(models.Model):\n image = models.CharField(\n max_length=200,\n validators=[\n RegexValidator(\n regex=r'^(?:(?=[^:\\/]{1,253})(?!-)[a-zA-Z0-9-]{1,63}(?<!-)(?:\\.(?!-)[a-zA-Z0-9-]{1,63}(?<!-))*(?::[0-9]{1,5})?/)?((?![._-])(?:[a-z0-9._-]*)(?<![._-])(?:/(?![._-])[a-z0-9._-]*(?<![._-]))*)(?::(?![.-])[a-zA-Z0-9_.-]{1,128})?$',\n message='image is not valid',\n code='invalid_url'\n )\n ]\n )\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17088333/" ]
74,593,627
<p>if I had a few async <code>fetch()</code>'s and their respective promises at hand, I seek to implement a function such that the earliest resolution into <code>Response()</code> with a status code 200 would return that very <code>Response</code> and drop everything else to the limbo of garbage collector. On the other hand, if none of those resolves with code 200, the latest resolution with non-200 code is returned.</p> <p>What's the most elegant way to achieve that? I am not big on js - I believe there should've been somewhat widely used pattern...</p>
[ { "answer_id": 74593655, "author": "Bergi", "author_id": 1048572, "author_profile": "https://Stackoverflow.com/users/1048572", "pm_score": 0, "selected": false, "text": "Promise.any Promise.race const urls = […];\nconst fastestResponse = await Promise.any(urls.map(async url => {\n const response = await fetch(url);\n if (response.status == 200) return response;\n else throw new Error(response.statusText+' response: '+await response.text());\n}));\n" }, { "answer_id": 74604741, "author": "wick", "author_id": 2550808, "author_profile": "https://Stackoverflow.com/users/2550808", "pm_score": -1, "selected": false, "text": "const resp = await Promise.all([\n\n fetch(new Request(req.url, init)),\n fetch(new Request(req.url, init2)),\n])\n\nif (resp[0].status < resp[1].status) return resp[0]\n\nreturn resp[1]\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2550808/" ]
74,593,632
<p>I have a list with a custom bullet type: <a href="https://i.stack.imgur.com/ptOES.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ptOES.png" alt="enter image description here" /></a></p> <p>This works exactly how I want. The list item's text wraps without going under the custom bullet, the bullet is aligned with the rest of the page, etc. What I'm not happy with is that I've accomplished this using a hard-coded padding value:</p> <pre class="lang-html prettyprint-override"><code>&lt;ul style= &quot;list-style-position:outside;padding-left:86.3167px;&quot;&gt; &lt;!-- list item --&gt; &lt;/ul&gt; </code></pre> <p>Is there a way to accomplish this without having the hard-coded value?</p> <p>Full example:</p> <pre class="lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;My Cool Website&lt;/title&gt; &lt;style&gt; html { font-family: sans-serif; } body { margin: 0; padding: 0 20px 20px 20px; line-height: 1.4em; margin-left: auto; margin-right: auto; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div&gt; &lt;h1&gt;My Cool Website&lt;/h1&gt; &lt;/div&gt; &lt;ul style= &quot;list-style-position:outside;padding-left:86.3167px;&quot;&gt; &lt;li style=&quot;list-style-type:'2022-04-18 ';&quot;&gt; &lt;a href= &quot;/blog/my-long-blog-post-title-that-spans-two-lines-on-my-blog-site&quot;&gt; my long blog post title that spans two lines on my blog site&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>I tried an <code>inside</code> style but that puts the wrapped text under the bullet item: <a href="https://i.stack.imgur.com/8dvae.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8dvae.png" alt="enter image description here" /></a></p> <pre><code>&lt;ul style=&quot;list-style-position:inside;padding-left:0;&quot;&gt; &lt;!-- list item --&gt; &lt;/ul&gt; </code></pre>
[ { "answer_id": 74593655, "author": "Bergi", "author_id": 1048572, "author_profile": "https://Stackoverflow.com/users/1048572", "pm_score": 0, "selected": false, "text": "Promise.any Promise.race const urls = […];\nconst fastestResponse = await Promise.any(urls.map(async url => {\n const response = await fetch(url);\n if (response.status == 200) return response;\n else throw new Error(response.statusText+' response: '+await response.text());\n}));\n" }, { "answer_id": 74604741, "author": "wick", "author_id": 2550808, "author_profile": "https://Stackoverflow.com/users/2550808", "pm_score": -1, "selected": false, "text": "const resp = await Promise.all([\n\n fetch(new Request(req.url, init)),\n fetch(new Request(req.url, init2)),\n])\n\nif (resp[0].status < resp[1].status) return resp[0]\n\nreturn resp[1]\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5692730/" ]
74,593,634
<p>Below is my script for import data to mysql:</p> <pre><code>foreach ($file_data as $row) { $sku = $row[$_POST[&quot;sku&quot;]]; $title = $row[$_POST[&quot;title&quot;]]; $slug = $row[$_POST[&quot;title&quot;]]; $product_type = &quot;physical&quot;; $description = $row[$_POST[&quot;description&quot;]]; } if(isset($sku)) { $query = &quot; INSERT INTO products (sku, slug, product_type) VALUES &quot;.implode(&quot;,&quot;, $sku).&quot;,&quot;.implode(&quot;,&quot;, $slug).&quot;,&quot;.implode(&quot;,&quot;, $product_type).&quot; &quot;; $statement = $connect-&gt;prepare($query); if($statement-&gt;execute()) { echo 'Data Imported Successfully'; } } </code></pre> <p>And now can anyone help me how to now load <code>$title</code> and <code>$description</code> to second table <code>product_details</code> ?</p> <p>@update @Mehrwarz</p> <pre><code>foreach ($file_data as $row) { $sku = $row[$_POST[&quot;sku&quot;]]; $title = $row[$_POST[&quot;title&quot;]]; $slug = $row[$_POST[&quot;slug&quot;]]; $product_type = &quot;physical&quot;; $description = $row[$_POST[&quot;description&quot;]]; if (isset($sku)) { $statement = $connect-&gt;prepare(&quot;INSERT INTO products (sku, slug, product_type) VALUES '$sku','$slug','$product_type'&quot;); $statement2 = $connect-&gt;prepare(&quot;INSERT INTO product_details (title, description) VALUES '$title','$description'&quot;); if (!$statement-&gt;execute()) { $error = 'None or part of the data was updated'; } } } echo $error ?? 'Data Updated Successfully'; </code></pre>
[ { "answer_id": 74593655, "author": "Bergi", "author_id": 1048572, "author_profile": "https://Stackoverflow.com/users/1048572", "pm_score": 0, "selected": false, "text": "Promise.any Promise.race const urls = […];\nconst fastestResponse = await Promise.any(urls.map(async url => {\n const response = await fetch(url);\n if (response.status == 200) return response;\n else throw new Error(response.statusText+' response: '+await response.text());\n}));\n" }, { "answer_id": 74604741, "author": "wick", "author_id": 2550808, "author_profile": "https://Stackoverflow.com/users/2550808", "pm_score": -1, "selected": false, "text": "const resp = await Promise.all([\n\n fetch(new Request(req.url, init)),\n fetch(new Request(req.url, init2)),\n])\n\nif (resp[0].status < resp[1].status) return resp[0]\n\nreturn resp[1]\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20598729/" ]
74,593,642
<p>I'm trying to write a code that calculates something similar to a geometric sequence.</p> <p><a href="https://i.stack.imgur.com/wOln5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wOln5.png" alt="enter image description here" /></a></p> <p>I thought i did it, but when i looked at the solution, it seemed like i was doing something completely different.</p> <p>There is a little twist to it though, the <strong>X</strong> value is in range from <strong>Xmin</strong> to <strong>Xmax</strong>, which means <strong>xmin &lt;= x &lt;= xmax</strong> and has a step of <strong>Dx</strong>.</p> <p>Here's my code:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;math.h&gt; void main(){ double xmin, xmax, dx, x, n = 1; long s = 0; printf(&quot;Input xmin, xmax, dx: &quot;); scanf(&quot;%lf%lf%lf&quot;, &amp;xmin, &amp;xmax, &amp;dx); printf(&quot;\n x s\n=============================&quot;); for(x = xmin; x &lt;= xmax; x += dx){ s += pow(x,n); n++; printf(&quot;\n%10.3lf%10.3ld&quot;, x, s); } } </code></pre> <p>Here is an example of what it outputs: (it goes from one to five, with a step of one)</p> <p><a href="https://i.stack.imgur.com/vCuhL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vCuhL.png" alt="enter image description here" /></a></p> <p>Here's the actual solution, which i can't understand at all:</p> <pre><code>#include &lt;stdio.h&gt; int main(){ int n,i; double xmin, xmax, dx, x; printf(&quot;Input n: &quot;); scanf(&quot;%d&quot;, &amp;n); printf(&quot;Input xmin, xmax, dx: &quot;); scanf(&quot;%lf%lf%lf&quot;, &amp;xmin, &amp;xmax, &amp;dx); printf(&quot;\n x s\n=============================&quot;); for(x = xmin; x &lt;= xmax; x += dx){ double s = 0, p = 1; for(i = 1; i &lt;= n; i++) s += (p *= x); printf(&quot;\n%10.3f%10.3f&quot;, x, s); } return 0; } </code></pre> <p>And here's what it outputs: (I put <strong>n</strong> as 3 randomly, because i can't understand what it does)</p> <p><a href="https://i.stack.imgur.com/8jPdH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8jPdH.png" alt="enter image description here" /></a></p> <p>My question is, what did i do wrong in my code? And why is there another loop in the <em>solution</em> with two variables that aren't even used anywhere? It seems the output of my code isn't wrong, but i can't even understand the output of the <em>solution</em>.</p>
[ { "answer_id": 74593655, "author": "Bergi", "author_id": 1048572, "author_profile": "https://Stackoverflow.com/users/1048572", "pm_score": 0, "selected": false, "text": "Promise.any Promise.race const urls = […];\nconst fastestResponse = await Promise.any(urls.map(async url => {\n const response = await fetch(url);\n if (response.status == 200) return response;\n else throw new Error(response.statusText+' response: '+await response.text());\n}));\n" }, { "answer_id": 74604741, "author": "wick", "author_id": 2550808, "author_profile": "https://Stackoverflow.com/users/2550808", "pm_score": -1, "selected": false, "text": "const resp = await Promise.all([\n\n fetch(new Request(req.url, init)),\n fetch(new Request(req.url, init2)),\n])\n\nif (resp[0].status < resp[1].status) return resp[0]\n\nreturn resp[1]\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14297177/" ]
74,593,644
<p>I am trying to test the hugging face's <code>prithivida/parrot_paraphraser_on_T5</code> model but getting token not found error.</p> <pre><code>from parrot import Parrot import torch import warnings warnings.filterwarnings(&quot;ignore&quot;) parrot = Parrot(model_tag=&quot;prithivida/parrot_paraphraser_on_T5&quot;, use_gpu=False) </code></pre> <p>The error I am getting</p> <pre><code>OSError Traceback (most recent call last) Cell In [10], line 2 1 #Init models (make sure you init ONLY once if you integrate this to your code) ----&gt; 2 parrot = Parrot(model_tag=&quot;prithivida/parrot_paraphraser_on_T5&quot;, use_gpu=False) File ~/.local/lib/python3.10/site-packages/parrot/parrot.py:10, in Parrot.__init__(self, model_tag, use_gpu) 8 from parrot.filters import Fluency 9 from parrot.filters import Diversity ---&gt; 10 self.tokenizer = AutoTokenizer.from_pretrained(model_tag, use_auth_token=True) 11 self.model = AutoModelForSeq2SeqLM.from_pretrained(model_tag, use_auth_token=True) 12 self.adequacy_score = Adequacy() File ~/.local/lib/python3.10/site-packages/transformers/models/auto/tokenization_auto.py:560, in AutoTokenizer.from_pretrained(cls, pretrained_model_name_or_path, *inputs, **kwargs) 557 return tokenizer_class.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs) 559 # Next, let's try to use the tokenizer_config file to get the tokenizer class. --&gt; 560 tokenizer_config = get_tokenizer_config(pretrained_model_name_or_path, **kwargs) 561 if &quot;_commit_hash&quot; in tokenizer_config: 562 kwargs[&quot;_commit_hash&quot;] = tokenizer_config[&quot;_commit_hash&quot;] File ~/.local/lib/python3.10/site-packages/transformers/models/auto/tokenization_auto.py:412, in get_tokenizer_config(pretrained_model_name_or_path, cache_dir, force_download, resume_download, proxies, use_auth_token, revision, local_files_only, **kwargs) 353 &quot;&quot;&quot; 354 Loads the tokenizer configuration from a pretrained model tokenizer configuration. 355 (...) 409 tokenizer_config = get_tokenizer_config(&quot;tokenizer-test&quot;) 410 ```&quot;&quot;&quot; 411 commit_hash = kwargs.get(&quot;_commit_hash&quot;, None) --&gt; 412 resolved_config_file = cached_file( 413 pretrained_model_name_or_path, 414 TOKENIZER_CONFIG_FILE, 415 cache_dir=cache_dir, 416 force_download=force_download, 417 resume_download=resume_download, 418 proxies=proxies, 419 use_auth_token=use_auth_token, 420 revision=revision, 421 local_files_only=local_files_only, 422 _raise_exceptions_for_missing_entries=False, 423 _raise_exceptions_for_connection_errors=False, 424 _commit_hash=commit_hash, 425 ) 426 if resolved_config_file is None: 427 logger.info(&quot;Could not locate the tokenizer configuration file, will try to use the model config instead.&quot;) File ~/.local/lib/python3.10/site-packages/transformers/utils/hub.py:409, in cached_file(path_or_repo_id, filename, cache_dir, force_download, resume_download, proxies, use_auth_token, revision, local_files_only, subfolder, user_agent, _raise_exceptions_for_missing_entries, _raise_exceptions_for_connection_errors, _commit_hash) 406 user_agent = http_user_agent(user_agent) 407 try: 408 # Load from URL or cache if already cached --&gt; 409 resolved_file = hf_hub_download( 410 path_or_repo_id, 411 filename, 412 subfolder=None if len(subfolder) == 0 else subfolder, 413 revision=revision, 414 cache_dir=cache_dir, 415 user_agent=user_agent, 416 force_download=force_download, 417 proxies=proxies, 418 resume_download=resume_download, 419 use_auth_token=use_auth_token, 420 local_files_only=local_files_only, 421 ) 423 except RepositoryNotFoundError: 424 raise EnvironmentError( 425 f&quot;{path_or_repo_id} is not a local folder and is not a valid model identifier &quot; 426 &quot;listed on 'https://huggingface.co/models'\nIf this is a private repository, make sure to &quot; 427 &quot;pass a token having permission to this repo with `use_auth_token` or log in with &quot; 428 &quot;`huggingface-cli login` and pass `use_auth_token=True`.&quot; 429 ) File ~/.local/lib/python3.10/site-packages/huggingface_hub/utils/_validators.py:124, in validate_hf_hub_args.&lt;locals&gt;._inner_fn(*args, **kwargs) 119 if check_use_auth_token: 120 kwargs = smoothly_deprecate_use_auth_token( 121 fn_name=fn.__name__, has_token=has_token, kwargs=kwargs 122 ) --&gt; 124 return fn(*args, **kwargs) File ~/.local/lib/python3.10/site-packages/huggingface_hub/file_download.py:1052, in hf_hub_download(repo_id, filename, subfolder, repo_type, revision, library_name, library_version, cache_dir, user_agent, force_download, force_filename, proxies, etag_timeout, resume_download, token, local_files_only, legacy_cache_layout) 1048 return pointer_path 1050 url = hf_hub_url(repo_id, filename, repo_type=repo_type, revision=revision) -&gt; 1052 headers = build_hf_headers( 1053 token=token, 1054 library_name=library_name, 1055 library_version=library_version, 1056 user_agent=user_agent, 1057 ) 1059 url_to_download = url 1060 etag = None File ~/.local/lib/python3.10/site-packages/huggingface_hub/utils/_validators.py:124, in validate_hf_hub_args.&lt;locals&gt;._inner_fn(*args, **kwargs) 119 if check_use_auth_token: 120 kwargs = smoothly_deprecate_use_auth_token( 121 fn_name=fn.__name__, has_token=has_token, kwargs=kwargs 122 ) --&gt; 124 return fn(*args, **kwargs) File ~/.local/lib/python3.10/site-packages/huggingface_hub/utils/_headers.py:117, in build_hf_headers(token, is_write_action, library_name, library_version, user_agent) 44 &quot;&quot;&quot; 45 Build headers dictionary to send in a HF Hub call. 46 (...) 114 If `token=True` but token is not saved locally. 115 &quot;&quot;&quot; 116 # Get auth token to send --&gt; 117 token_to_send = get_token_to_send(token) 118 _validate_token_to_send(token_to_send, is_write_action=is_write_action) 120 # Combine headers File ~/.local/lib/python3.10/site-packages/huggingface_hub/utils/_headers.py:149, in get_token_to_send(token) 147 if token is True: 148 if cached_token is None: --&gt; 149 raise EnvironmentError( 150 &quot;Token is required (`token=True`), but no token found. You&quot; 151 &quot; need to provide a token or be logged in to Hugging Face with&quot; 152 &quot; `huggingface-cli login` or `huggingface_hub.login`. See&quot; 153 &quot; https://huggingface.co/settings/tokens.&quot; 154 ) 155 return cached_token 157 # Case implicit use of the token is forbidden by env variable OSError: Token is required (`token=True`), but no token found. You need to provide a token or be logged in to Hugging Face with `huggingface-cli login` or `huggingface_hub.login`. See https://huggingface.co/settings/tokens. </code></pre> <p>I have the secret token downloaded but not sure where to pass and how?</p> <p>The stack trace after updating the token inside <code>class Parrot</code> in <code>~/.local/lib/python3.10/site-packages/parrot/parrot.py</code></p> <pre><code>Traceback (most recent call last): File &quot;/media/chinmay/New Volume/myWorks/GIT_Hub/project_parrot_nlp/pp.py&quot;, line 8, in &lt;module&gt; parrot = Parrot(model_tag=&quot;prithivida/parrot_paraphraser_on_T5&quot;, use_gpu=False) File &quot;/media/chinmay/New Volume/myWorks/GIT_Hub/project_parrot_nlp/vnv/lib/python3.10/site-packages/parrot/parrot.py&quot;, line 10, in __init__ self.tokenizer = AutoTokenizer.from_pretrained(model_tag, use_auth_token=True) File &quot;/media/chinmay/New Volume/myWorks/GIT_Hub/project_parrot_nlp/vnv/lib/python3.10/site-packages/transformers/models/auto/tokenization_auto.py&quot;, line 560, in from_pretrained tokenizer_config = get_tokenizer_config(pretrained_model_name_or_path, **kwargs) File &quot;/media/chinmay/New Volume/myWorks/GIT_Hub/project_parrot_nlp/vnv/lib/python3.10/site-packages/transformers/models/auto/tokenization_auto.py&quot;, line 412, in get_tokenizer_config resolved_config_file = cached_file( File &quot;/media/chinmay/New Volume/myWorks/GIT_Hub/project_parrot_nlp/vnv/lib/python3.10/site-packages/transformers/utils/hub.py&quot;, line 409, in cached_file resolved_file = hf_hub_download( File &quot;/media/chinmay/New Volume/myWorks/GIT_Hub/project_parrot_nlp/vnv/lib/python3.10/site-packages/huggingface_hub/utils/_validators.py&quot;, line 124, in _inner_fn return fn(*args, **kwargs) File &quot;/media/chinmay/New Volume/myWorks/GIT_Hub/project_parrot_nlp/vnv/lib/python3.10/site-packages/huggingface_hub/file_download.py&quot;, line 1052, in hf_hub_download headers = build_hf_headers( File &quot;/media/chinmay/New Volume/myWorks/GIT_Hub/project_parrot_nlp/vnv/lib/python3.10/site-packages/huggingface_hub/utils/_validators.py&quot;, line 124, in _inner_fn return fn(*args, **kwargs) File &quot;/media/chinmay/New Volume/myWorks/GIT_Hub/project_parrot_nlp/vnv/lib/python3.10/site-packages/huggingface_hub/utils/_headers.py&quot;, line 117, in build_hf_headers token_to_send = get_token_to_send(token) File &quot;/media/chinmay/New Volume/myWorks/GIT_Hub/project_parrot_nlp/vnv/lib/python3.10/site-packages/huggingface_hub/utils/_headers.py&quot;, line 149, in get_token_to_send raise EnvironmentError( OSError: Token is required (`token=True`), but no token found. You need to provide a token or be logged in to Hugging Face with `huggingface-cli login` or `huggingface_hub.login`. See https://huggingface.co/settings/tokens. </code></pre>
[ { "answer_id": 74593655, "author": "Bergi", "author_id": 1048572, "author_profile": "https://Stackoverflow.com/users/1048572", "pm_score": 0, "selected": false, "text": "Promise.any Promise.race const urls = […];\nconst fastestResponse = await Promise.any(urls.map(async url => {\n const response = await fetch(url);\n if (response.status == 200) return response;\n else throw new Error(response.statusText+' response: '+await response.text());\n}));\n" }, { "answer_id": 74604741, "author": "wick", "author_id": 2550808, "author_profile": "https://Stackoverflow.com/users/2550808", "pm_score": -1, "selected": false, "text": "const resp = await Promise.all([\n\n fetch(new Request(req.url, init)),\n fetch(new Request(req.url, init2)),\n])\n\nif (resp[0].status < resp[1].status) return resp[0]\n\nreturn resp[1]\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9207531/" ]
74,593,666
<p>I have the below code to cache various partitions and save them in a map then to union them all</p> <p>and i am getting the below error unionByName is not a member of null</p> <pre><code>Var cache_map = Map[String,Dataframe]() for (partition &lt;- partitionlist){ var df_test = spark.read.format(&quot;delta&quot;).load(&quot;abfs://container@storagename.dfs.core.windows.net/dirname&quot;) .where((col(&quot;dt&quot;).like(partition+&quot;%&quot;)) cache_map(partition) = df_test.cache() } val cache_keys = cache_map.keys var df_union=null for (key &lt;- cache_keys){ if(df_union==null){ df_union=cache_map.get(key) } else{ df_union=df_union.unionByName(cache_map.get(key) } } </code></pre> <p>When I do below</p> <p><code>cache_map.get(&quot;20221120&quot;).unionByName(cache_map.get(&quot;20221119&quot;))</code></p> <p>I get the below error</p> <p>Error: value unionByName is not a member of Option[org.apache.spark.sql.DataFrame]</p> <p>Can anyone help me wity what's going wrong? I don't have as much experience with spark using scala as I have with pyspark. Any help is greatly appreciated.</p>
[ { "answer_id": 74593655, "author": "Bergi", "author_id": 1048572, "author_profile": "https://Stackoverflow.com/users/1048572", "pm_score": 0, "selected": false, "text": "Promise.any Promise.race const urls = […];\nconst fastestResponse = await Promise.any(urls.map(async url => {\n const response = await fetch(url);\n if (response.status == 200) return response;\n else throw new Error(response.statusText+' response: '+await response.text());\n}));\n" }, { "answer_id": 74604741, "author": "wick", "author_id": 2550808, "author_profile": "https://Stackoverflow.com/users/2550808", "pm_score": -1, "selected": false, "text": "const resp = await Promise.all([\n\n fetch(new Request(req.url, init)),\n fetch(new Request(req.url, init2)),\n])\n\nif (resp[0].status < resp[1].status) return resp[0]\n\nreturn resp[1]\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7700324/" ]
74,593,724
<p>I'm trying to create a simple <code>Style</code> for the <code>Header</code> of all the <code>ToggleSwitche</code>s on a given <code>Page</code> (WinUI 3 v1.2 desktop project). I'd really like to use <code>x:Bind</code> for all of my bindings (not <code>Binding</code>). Here's my <code>Page.Resources</code></p> <pre class="lang-xaml prettyprint-override"><code>&lt;Page.Resources&gt; &lt;Style TargetType=&quot;ToggleSwitch&quot; &gt; &lt;Setter Property=&quot;FontSize&quot; Value=&quot;{x:Bind app:App.ShellPage.RootShellFontSize, Mode=OneWay}&quot; /&gt; &lt;Setter Property=&quot;Foreground&quot; Value=&quot;{x:Bind app:App.ShellPage.UiColorContentAreaForeground, Mode=OneWay}&quot; /&gt; &lt;Setter Property=&quot;HeaderTemplate&quot;&gt; &lt;Setter.Value&gt; &lt;DataTemplate x:DataType=&quot;ToggleSwitch&quot;&gt; &lt;TextBlock Text=&quot;{x:Bind Header}&quot; Foreground=&quot;{x:Bind Foreground}&quot;/&gt; &lt;/DataTemplate&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;/Style&gt; &lt;/Page.Resources&gt; </code></pre> <p>and the ToggleSwitch is defined as</p> <pre class="lang-xaml prettyprint-override"><code>&lt;ToggleSwitch Grid.Row=&quot;1&quot; Grid.Column=&quot;1&quot; Header=&quot;Resize Elements&quot; OffContent=&quot;Don't Resize&quot; OnContent=&quot;Resize Everything&quot; IsOn=&quot;{x:Bind app:App.ShellPage.IsSettingsResizeElements, Mode=TwoWay}&quot; /&gt; </code></pre> <p>I thought this would set the text in the <code>Header</code> <code>TextBlock</code> to whatever was set in the <code>ToggleSwitch</code> <code>Header</code> (&quot;Resize Elements&quot; here) and bind the <code>Foreground</code> of the <code>Header</code> to <code>UiColorContentAreaForeground</code>. Neither binding produces the expected results.</p> <p>The first binding in the <code>TextBlock</code>, <code>Text=&quot;{x:Bind Header}&quot;</code>, always throws an error as the binding engine tries to cast the string <code>&quot;Resize Elements&quot;</code> to a <code>ToggleSwitch</code> prior to looking at the <code>Header</code> property. Using <code>Text=&quot;{x:Bind}&quot;</code> does the same thing as does <code>Text=&quot;{x:Bind OnContent}&quot;</code> or <code>Text=&quot;{x:Bind OffContent}&quot;</code> (!?). I can't think why the latter two happen as <code>ToString()</code> returns the contents of <code>Header</code>.</p> <p>The second binding in <code>TextBlock</code> binds to something but it has a different value than <code>UiColorContentAreaForeground</code> (although it's always the same wrong value).</p> <p>Any idea what's wrong with the bindings, please? How should I write the bindings using x:Bind?</p> <p>As an aside, using <code>Text=&quot;{Binding}&quot;</code> works but I haven't found any form of binding that works for the <code>Foreground</code> property.</p>
[ { "answer_id": 74593655, "author": "Bergi", "author_id": 1048572, "author_profile": "https://Stackoverflow.com/users/1048572", "pm_score": 0, "selected": false, "text": "Promise.any Promise.race const urls = […];\nconst fastestResponse = await Promise.any(urls.map(async url => {\n const response = await fetch(url);\n if (response.status == 200) return response;\n else throw new Error(response.statusText+' response: '+await response.text());\n}));\n" }, { "answer_id": 74604741, "author": "wick", "author_id": 2550808, "author_profile": "https://Stackoverflow.com/users/2550808", "pm_score": -1, "selected": false, "text": "const resp = await Promise.all([\n\n fetch(new Request(req.url, init)),\n fetch(new Request(req.url, init2)),\n])\n\nif (resp[0].status < resp[1].status) return resp[0]\n\nreturn resp[1]\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14062288/" ]
74,593,727
<p>If I run</p> <blockquote> <p>npm run client</p> </blockquote> <p>in my_directory, it will translate to:</p> <blockquote> <p>webpack -w --mode production --config ./webpack.config.js</p> </blockquote> <p>However, if I am in my_directory and I manually type in the above command, I get:</p> <blockquote> <p>zsh: command not found: webpack</p> </blockquote> <p>Also, can I change things so that I can run from my_directory. This is a two part question if possible.</p> <p>I was expecting to be able to run webpack manually without an npm script.</p>
[ { "answer_id": 74593655, "author": "Bergi", "author_id": 1048572, "author_profile": "https://Stackoverflow.com/users/1048572", "pm_score": 0, "selected": false, "text": "Promise.any Promise.race const urls = […];\nconst fastestResponse = await Promise.any(urls.map(async url => {\n const response = await fetch(url);\n if (response.status == 200) return response;\n else throw new Error(response.statusText+' response: '+await response.text());\n}));\n" }, { "answer_id": 74604741, "author": "wick", "author_id": 2550808, "author_profile": "https://Stackoverflow.com/users/2550808", "pm_score": -1, "selected": false, "text": "const resp = await Promise.all([\n\n fetch(new Request(req.url, init)),\n fetch(new Request(req.url, init2)),\n])\n\nif (resp[0].status < resp[1].status) return resp[0]\n\nreturn resp[1]\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20592666/" ]
74,593,738
<p>I'm programming automation to my CI/CD Gitlab to deploy my Azure Functions projects programmatically.</p> <p>But I'm having an issue when I publish a new function to a function app created previously using az cli like the example below:</p> <pre><code>$ func azure functionapp publish $AZURE_APP_NAME ${SLOT_PARAMETER} ${FUNCTION_LANGUAGE} --nozip $ az webapp config appsettings set -g $AZURE_RG_NAME -n $AZURE_APP_NAME ${SLOT_PARAMETER} --settings &quot;WEBSITE_RUN_FROM_PACKAGE=0&quot; </code></pre> <p>The command line shows that the new function was built, created and deployed successfully. But when I check if the new function was created in my app using the Azure Console UI nothing was shown.</p> <p>I even tried deploying the function as a zip package using the default <code>publish</code> command or like the example above using <code>--nozip</code> and setting <code>WEBSITE_RUN_FROM_PACKAGE=0</code> to deploy files.</p> <p>It's strange because I could see the deployed function for another app function using the same script. In this way the behavior of the console UI function app seems erratic.</p>
[ { "answer_id": 74655052, "author": "Pravallika Kothaveerannagari", "author_id": 19991670, "author_profile": "https://Stackoverflow.com/users/19991670", "pm_score": 1, "selected": false, "text": "SCM_DO_BUILD_DURING_DEPLOYMENT=true az functionapp config appsettings set --name PravuFunctionApp \\\n--resource-group PraviRG \\\n--settings SCM_DO_BUILD_DURING_DEPLOYMENT=true\n az cli func azure functionapp publish" }, { "answer_id": 74669309, "author": "mayconfsbrito", "author_id": 1472606, "author_profile": "https://Stackoverflow.com/users/1472606", "pm_score": 1, "selected": true, "text": "SCM_DO_BUILD_DURING_DEPLOYMENT=true az functionapp deployment source config-zip echo '[config] SCM_DO_BUILD_DURING_DEPLOYMENT = true' > .deployment\nzip -r build.zip MyFunction\naz functionapp deployment source config-zip -g $AZURE_RG_NAME -n $AZURE_APP_NAME ${SLOT_PARAMETER} --src build.zip\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1472606/" ]
74,593,769
<p>I want to build a simple TDEE calculator using Javascript.</p> <p>I want the user to fill in their details in a html form and then pass that info into a Javascript object.</p> <h1>See my HTML code below, where I created the form;</h1> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot; /&gt; &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot; /&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt; &lt;title&gt;TDEE&lt;/title&gt; &lt;link rel = &quot;stylesheet&quot; href=&quot;style.css&quot;&gt; &lt;/head&gt; &lt;body&gt; &lt;form id=&quot;tdeeCalc&quot;&gt; &lt;label for=&quot;gender&quot;&gt;Gender:&lt;/label&gt; &lt;select id=&quot;gender&quot; name=&quot;gender&quot;&gt; &lt;option value=&quot;Male&quot;&gt;Male&lt;/option&gt; &lt;option value=&quot;Female&quot;&gt;Female&lt;/option&gt; &lt;/select&gt; &lt;br&gt; &lt;label for=&quot;Weight-Unit&quot;&gt;Weight Unit:&lt;/label&gt; &lt;select id=&quot;weight-unit&quot; name=&quot;weight-unit&quot;&gt; &lt;option value=&quot;kg&quot;&gt;kg&lt;/option&gt; &lt;option value=&quot;lb&quot;&gt;lb&lt;/option&gt; &lt;/select&gt; &lt;br&gt; &lt;label for=&quot;Weight&quot;&gt;Weight&lt;/label&gt; &lt;input type=&quot;number&quot; id=&quot;weight&quot; name=&quot;weight&quot;&gt; &lt;br&gt; &lt;label for=&quot;Height-Unit&quot;&gt;Height Unit:&lt;/label&gt; &lt;select id=&quot;height-unit&quot; name=&quot;height-unit&quot;&gt; &lt;option value=&quot;cm&quot;&gt;cm&lt;/option&gt; &lt;option value=&quot;in&quot;&gt;in&lt;/option&gt; &lt;/select&gt; &lt;br&gt; &lt;label for=&quot;Height&quot;&gt;Height&lt;/label&gt; &lt;input type=&quot;number&quot; id=&quot;height&quot; name=&quot;height&quot;&gt; &lt;br&gt; &lt;label for=&quot;Age&quot;&gt;Age&lt;/label&gt; &lt;input type=&quot;number&quot; id=&quot;age&quot; name=&quot;age&quot;&gt; &lt;br&gt; &lt;input type=&quot;submit&quot; value=&quot;Submit&quot;&gt; &lt;/form&gt; &lt;script src=&quot;tdee.js&quot;&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <h1>See my JS code where I want to use the users submitted info to calculate their TDEE</h1> <p>`</p> <pre><code>const user = {}; //Function To Store the Users TDEE And Display It To The Console const tdeeResult = function (){ if (user.gender === 'male'){ user.tdee = maleTdee(); } else if (user.gender === 'female'){ user.tdee = femaleTdee(); } return console.log(`As a ${user.age} year old ${user.gender} weighing ${user.weight}${user.weightUnit} and with a height of ${user.height}${user.heightUnit} your TDEE is ${user.tdee}`);; } // Get reference to the form element const myTdeeForm = document.getElementById(&quot;tdeeCalc&quot;) // Intialise FormData constructor with myTdeeForm myTdeeForm.addEventListener('submit', (e)=&gt;{ e.preventDefault(); // Using formData.entries() and Object.fromEntries() method to convert the form data into a valid javascript object const tdeeFormData = new FormData(myTdeeForm); const user = Object.fromEntries(tdeeFormData.entries()) tdeeResult(user); }); //Declaring User Details // const user = { // gender: 'female', // weight: 100, // height: 182.88, // age: 30, // weightUnit: 'kg', // heightUnit: 'cm', // tdee: 0, // } //Function To Convert Lbs To Kgs const poundsConversion = function () { return user.weight / 2.2046 } //Function To Convert Inches To Cm const inchesConversion = function () { return user.height * 2.54 } //If Statement To Convert User Weight If Specified in Lbs if (user.weightUnit !== 'kg'){ user.weight = poundsConversion(user.weight); //console.log(user.weight); } //If Statement To Convert User Weight If Specified in Inches if (user.heightUnit !== 'cm'){ user.height = inchesConversion(user.height); //console.log(user.height); } //Function To Calculate TDEE For Males const maleTdee = function (){ return 66 + (13.7 * user.weight) + (5 * user.height) - (6.8 * user.age); } //Function To Calculate TDEE For Females const femaleTdee = function (){ return 655 + (9.6 * user.weight) + (1.8 * user.height) - (4.7 * user.age); } </code></pre> <p>`</p> <h1>When I run the code the following message is logged to the console;</h1> <blockquote> <p>As a undefined year old undefined weighing NaNundefined and with a height of NaNundefined your TDEE is undefined</p> </blockquote> <p>Why arent the form details being passed into the user object?</p> <p>If I console log the user it does seem they are being captured but why isnt this accessible by the function?</p>
[ { "answer_id": 74655052, "author": "Pravallika Kothaveerannagari", "author_id": 19991670, "author_profile": "https://Stackoverflow.com/users/19991670", "pm_score": 1, "selected": false, "text": "SCM_DO_BUILD_DURING_DEPLOYMENT=true az functionapp config appsettings set --name PravuFunctionApp \\\n--resource-group PraviRG \\\n--settings SCM_DO_BUILD_DURING_DEPLOYMENT=true\n az cli func azure functionapp publish" }, { "answer_id": 74669309, "author": "mayconfsbrito", "author_id": 1472606, "author_profile": "https://Stackoverflow.com/users/1472606", "pm_score": 1, "selected": true, "text": "SCM_DO_BUILD_DURING_DEPLOYMENT=true az functionapp deployment source config-zip echo '[config] SCM_DO_BUILD_DURING_DEPLOYMENT = true' > .deployment\nzip -r build.zip MyFunction\naz functionapp deployment source config-zip -g $AZURE_RG_NAME -n $AZURE_APP_NAME ${SLOT_PARAMETER} --src build.zip\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20617557/" ]
74,593,787
<p>I have this GridView markup:</p> <pre><code> &lt;asp:GridView ID=&quot;GridView1&quot; runat=&quot;server&quot; Width =&quot;300px&quot;&gt; &lt;Columns&gt; &lt;asp:BoundField AccessibleHeaderText=&quot;TEXT&quot; HeaderText=&quot;TEXT&quot; /&gt; &lt;/Columns&gt; &lt;/asp:GridView&gt; </code></pre> <p>I want to fill up Gridview with some strings through foreach loop:</p> <pre><code> foreach (GridViewRow row in GridView1.Rows) { string f = &quot;this is looping&quot;; row.Cells[0].Text += f; } </code></pre> <p>The problem is GridView1 doesn`t display anything...</p>
[ { "answer_id": 74594715, "author": "Albert D. Kallal", "author_id": 10527, "author_profile": "https://Stackoverflow.com/users/10527", "pm_score": 1, "selected": false, "text": " <asp:GridView ID=\"GridView1\" runat=\"server\" CssClass=\"table\" Width=\"20%\">\n\n </asp:GridView>\n protected void Page_Load(object sender, EventArgs e)\n {\n if (!IsPostBack)\n LoadGrid();\n }\n\n void LoadGrid()\n {\n\n List<string> MyList = new List<string> { \"One\", \"Two\", \"Three\" };\n GridView1.DataSource = MyList;\n GridView1.DataBind();\n\n\n }\n <asp:GridView ID=\"GridView1\" runat=\"server\" CssClass=\"table\" \n Width=\"20%\" AutoGenerateColumns=\"false\">\n <Columns>\n <asp:BoundField HeaderText=\"My header\"\n DataField=\"Text\"/>\n </Columns>\n </asp:GridView>\n protected void Page_Load(object sender, EventArgs e)\n {\n if (!IsPostBack)\n LoadGrid();\n }\n\n void LoadGrid()\n {\n\n List<ListItem> MyList = new List<ListItem>();\n\n MyList.Add(new ListItem(\"One\"));\n MyList.Add(new ListItem(\"Two\"));\n MyList.Add(new ListItem(\"Three\"));\n\n GridView1.DataSource = MyList;\n GridView1.DataBind();\n\n }\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593787", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20465780/" ]
74,593,796
<p>I need your help on the following for Java:</p> <p>I have a List which contains different objects and each objects has three different values (String, int, double).</p> <p>I want to increase the int value by one. How do I access the int value of an object in this list and increase it by 1?</p> <p>Thanks for any help!</p> <p>I tried to do this:</p> <p>list.set (i, intvalue + 1)</p>
[ { "answer_id": 74593851, "author": "bighugedev", "author_id": 17846993, "author_profile": "https://Stackoverflow.com/users/17846993", "pm_score": 0, "selected": false, "text": "list.set() list.get(1).count++;\n count int" }, { "answer_id": 74593902, "author": "CryptoFool", "author_id": 7631480, "author_profile": "https://Stackoverflow.com/users/7631480", "pm_score": 1, "selected": false, "text": "1 1 i Integer public static void main(String[] args) {\n List<Object> someList = new ArrayList<>();\n someList.add(\"A String\");\n someList.add(100);\n someList.add(100.2);\n\n int i = 1;\n if (someList.size() > i) {\n Object originalValue = someList.get(i);\n if (originalValue instanceof Integer) {\n someList.set(i, (Integer)originalValue + 1);\n }\n }\n System.out.println(someList);\n}\n [A String, 101, 100.2]\n Integer Object Integer Integer" }, { "answer_id": 74593905, "author": "Chaitanya Waikar", "author_id": 7803797, "author_profile": "https://Stackoverflow.com/users/7803797", "pm_score": 0, "selected": false, "text": "class Pojo {\n private String str;\n private int integerValue;\n private double doubleValue;\n\n public Pojo(String str, int integerValue, double doubleValue) {\n this.str = str;\n this.integerValue = integerValue;\n this.doubleValue = doubleValue;\n }\n\n public String getStr() {\n return str;\n }\n\n public void setStr(String str) {\n this.str = str;\n }\n\n public int getIntegerValue() {\n return integerValue;\n }\n\n public void setIntegerValue(int integerValue) {\n this.integerValue = integerValue;\n }\n\n public double getDoubleValue() {\n return doubleValue;\n }\n\n public void setDoubleValue(double doubleValue) {\n this.doubleValue = doubleValue;\n }\n}\n Pojo setter public static void main(String[] args) {\n\n Pojo p1 = new Pojo(\"str1\", 1, 1.5);\n Pojo p2 = new Pojo(\"str2\", 2, 2.5);\n\n List<Pojo> listOfPojo = Arrays.asList(p1, p2);\n\n List<Pojo> collect = listOfPojo\n .stream()\n .map(pojo -> pojo.setIntegerValue(pojo.getIntegerValue() + 1))\n .collect(Collectors.toList());\n \n }\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20617620/" ]
74,593,812
<p>I want to split a list into sublist with specific 'if statement' for each sublist. For examle: input:</p> <pre><code>a = [1, 2, 7.9, 3, 4, 3.7, 5, 6, 2.2, 7, 8, 1.2, 5.7] </code></pre> <p>output:</p> <pre><code>b = [[1, 1.2, 2], [2.2, 3, 3.7, 4], [5, 5.7, 6], [7, 7.9, 8]] </code></pre> <p>Values should be grouped by certain range. here it is between (1:2); (2.1:4); (4.1:6); (6.1:8). I hope I was able to get my point across.</p>
[ { "answer_id": 74593983, "author": "Pranav Hosangadi", "author_id": 843953, "author_profile": "https://Stackoverflow.com/users/843953", "pm_score": 2, "selected": true, "text": "dx [[1, 1.2, 2], [2.2, 3], [3.7, 4], [5, 5.7, 6], [7, 7.9, 8]]\n numbers = sorted(a)\n bucket bucket = []\nresult = [bucket]\nfor n in numbers:\n # bucket is empty, or bucket range <= dx, so append\n if not bucket or n - bucket[0] <= dx: \n bucket.append(n)\n else:\n bucket = [n] # Create a new bucket with the current number\n result.append(bucket) # Add it to our result array\n result = [[1, 1.2, 2], [2.2, 3], [3.7, 4], [5, 5.7, 6], [7, 7.9, 8]]\n" }, { "answer_id": 74593985, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 0, "selected": false, "text": "from math import ceil\n\na = [1, 2, 7.9, 3, 4, 3.7, 5, 6, 2.2, 7, 8, 1.2, 5.7]\ndx = 2\n\nd = {}\n\nfor x in sorted(a):\n k = ceil(x+1)//dx\n d.setdefault(k, []).append(x)\n\nb = list(d.values())\n [[1, 1.2, 2], [2.2, 3, 3.7, 4], [5, 5.7, 6], [7, 7.9, 8]]\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14620687/" ]
74,593,838
<p>I have a torch tensor (x) of shape [16,3,32,32], 16 images, 3 colour channels 32x32. I'm doing diffusion and need to apply the following formula to the images</p> <p><code>return sqrt_alpha_hat * x + sqrt_one_minus_alpha_hat * error</code></p> <p>Error has the same dimensions as x. This works fine when sqrt_alpha_hat and sqrt_one_minus_alpha_hat are integers, the tensors are all multiplied by the number and then added up. I want to multiply each image by a different value. So my sqrt_alpha_hat and sqrt_one_minus_alpha_hat are 1D arrays of size 32, one number for each image. Keep in mind this array is in CUDA so some np functions won't work.</p> <p>I tried using np.fill to create a massive array with format:</p> <p>[[[1 ... 1], ... [1 ... 1] (32 columns) ... (32 rows) [1 ... 1], ... [1 ... 1]],</p> <p>... (3 colour channels)</p> <p>[[1 ... 1], ... [1 ... 1] ... [1 ... 1], ... [1 ... 1]]]</p> <p>... (16 images)</p> <p>[[[16 ... 16], ... [16 ... 16] ... [16 ... 16], ... [16 ... 16]],</p> <p>...</p> <p>[[16 ... 16], ... [16 ... 16] ... [16 ... 16], ... [16 ... 16]]]</p> <p>but that didn't work. There surely must be a simpler way to do this.</p>
[ { "answer_id": 74593983, "author": "Pranav Hosangadi", "author_id": 843953, "author_profile": "https://Stackoverflow.com/users/843953", "pm_score": 2, "selected": true, "text": "dx [[1, 1.2, 2], [2.2, 3], [3.7, 4], [5, 5.7, 6], [7, 7.9, 8]]\n numbers = sorted(a)\n bucket bucket = []\nresult = [bucket]\nfor n in numbers:\n # bucket is empty, or bucket range <= dx, so append\n if not bucket or n - bucket[0] <= dx: \n bucket.append(n)\n else:\n bucket = [n] # Create a new bucket with the current number\n result.append(bucket) # Add it to our result array\n result = [[1, 1.2, 2], [2.2, 3], [3.7, 4], [5, 5.7, 6], [7, 7.9, 8]]\n" }, { "answer_id": 74593985, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 0, "selected": false, "text": "from math import ceil\n\na = [1, 2, 7.9, 3, 4, 3.7, 5, 6, 2.2, 7, 8, 1.2, 5.7]\ndx = 2\n\nd = {}\n\nfor x in sorted(a):\n k = ceil(x+1)//dx\n d.setdefault(k, []).append(x)\n\nb = list(d.values())\n [[1, 1.2, 2], [2.2, 3, 3.7, 4], [5, 5.7, 6], [7, 7.9, 8]]\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20617626/" ]
74,593,845
<p>I have dynamically allocated array consisting of a lot of numbers (200 000+) and I have to find out, if (and how many) these numbers are contained in given interval. There can be duplicates and all the numbers are in random order.</p> <p>Example of numbers I get at the beginning:</p> <pre><code>{1,2,3,1484984,48941651,489416,1816,168189161,6484,8169181,9681916,121,231,684979,795641,231484891,...} </code></pre> <p>Given interval:</p> <pre><code>&lt;2;150000&gt; </code></pre> <p>I created a simple algorithm with 2 for loops cycling through all numbers:</p> <pre><code>for( int j = 0; j &lt;= numberOfRepeats; j++){ for( int i = 0; i &lt; arraySize; i++){ if(currentNumber == array[i]){ counter++; } } currentNumber++; } printf(&quot; -&gt; %d\n&quot;, counter); } </code></pre> <p>This algorithm is too slow for my task. Is there more efficient way for me to implement my solution? Could sorting the arrays by value help in this case / wouldn't that be too slow?</p> <p>Example of working program:</p> <pre><code>{ 1, 7, 22, 4, 7, 5, 11, 9, 1 } &lt;4;7&gt; -&gt; 4 </code></pre>
[ { "answer_id": 74594135, "author": "Grolldash", "author_id": 14726548, "author_profile": "https://Stackoverflow.com/users/14726548", "pm_score": 2, "selected": false, "text": " for(int i = 0; i <= arraySize-1; i++){\n if(array[i] <= endOfInterval && array[i] >= startOfInterval){\n counter++;\n }\n" }, { "answer_id": 74611029, "author": "Luis Colorado", "author_id": 3899431, "author_profile": "https://Stackoverflow.com/users/3899431", "pm_score": 0, "selected": false, "text": "qsort(3) #include <stdio.h>\n#define A (2)\n#define B (150000)\nint main()\n{\n int the_number;\n size_t count = 0;\n int res;\n while ((res = scanf(\"%d\", &the_number)) > 0) {\n if (the_number >= A && the_number <= B)\n count++;\n }\n printf(\"%zd numbers fitted in the range\\n\", count);\n}\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14726548/" ]
74,593,893
<p>I have written a PHP library using the PHP 8.0 <code>readonly</code> keyword and then I realised that it would be good to support earlier versions of PHP such as 7.4.</p> <p>I could easily remove the <code>readonly</code> keywords from my code but I don't want to do that -- they were put there for a reason!</p> <p>Having a C background, I immediately thought of macros but PHP doesn't seem to have any. I've googled <a href="https://stackoverflow.com/a/47056548/1291717">this answer</a> for adding macro-like behaviour to PHP, but it looks like an overkill. And it's just for one file, and my library has 26 files at present.</p> <p>Is there an <em>easy</em> way to make PHP 7.4 just ignore the <code>readonly</code> keyword and make my code cross-version? Something to the effect of this C code?</p> <pre><code>#if PHP_VERSION &lt; 8 #define readonly /**/ #enif </code></pre> <p>Perphaps some <code>composer</code> build option that can pre-process files before packaging them up?</p>
[ { "answer_id": 74593951, "author": "Martin Zeitler", "author_id": 549372, "author_profile": "https://Stackoverflow.com/users/549372", "pm_score": 1, "selected": false, "text": "readonly" }, { "answer_id": 74594292, "author": "IMSoP", "author_id": 157957, "author_profile": "https://Stackoverflow.com/users/157957", "pm_score": 2, "selected": false, "text": "include /* IF PHP 8 */ readonly /* END IF */ $php_code = file_get_contents($php_file_being_loaded);\nif ( PHP_VERSION_ID < 80000 ) {\n $php_code = preg_replace('#/\\* IF PHP 8 \\*/.*?/\\* END IF \\*/#s', '', $php_code);\n}\neval($php_code);\n" }, { "answer_id": 74598939, "author": "hanshenrik", "author_id": 1067003, "author_profile": "https://Stackoverflow.com/users/1067003", "pm_score": 1, "selected": false, "text": "{\n \"require\": {\n \"php\": \">=7.4\"\n },\n}\n {\n \"require\": {\n \"php\": \">=8.0\"\n },\n}\n composer require lib lib.php if(PHP_MAJOR_VERSION >= 8){\n require(\"lib_modern.php\");\n} else{\n require(\"lib_legacy.php\");\n}\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1291717/" ]
74,593,913
<p>Define a <code>Course</code> base class with attributes <code>number</code> and <code>title</code>. Define a <code>print_info()</code> method that displays the course <code>number</code> and <code>title</code>.</p> <p>Also define a derived class <code>OfferedCourse</code> with the additional attributes <code>instructor_name</code>, <code>term</code>, and <code>class_time</code>.</p> <p>Ex: If the input is:</p> <pre><code>ECE287 Digital Systems Design ECE387 Embedded Systems Design Mark Patterson Fall 2018 WF: 2-3:30 pm </code></pre> <p>the output is:</p> <pre><code>Course Information: Course Number: ECE287 Course Title: Digital Systems Design Course Information: Course Number: ECE387 Course Title: Embedded Systems Design Instructor Name: Mark Patterson Term: Fall 2018 Class Time: WF: 2-3:30 pm </code></pre> <p>Here is the code I have so far:</p> <pre class="lang-py prettyprint-override"><code>class Course: # TODO: Define constructor with attributes: number, title def __init__(self): self.number = '' self.title = 0 # TODO: Define print_info() def print_info(self): print(' Course Number:', self.number) print(' Title:', self.title) class OfferedCourse(Course): # TODO: Define constructor with attributes: # number, title, instructor_name, term, class_time def __init__(self, number, title, instructor_name, term, class_time): Course.__init__(course_number, course_title) self.instructor_name = '' self.term = '' self.class_time = 0 if __name__ == '__main__': course_number = input() course_title = input() o_course_number = input() o_course_title = input() instructor_name = input() term = input() class_time = input() my_course = Course(course_number, course_title) my_course.print_info() my_offered_course = OfferedCourse( o_course_number, o_course_title, instructor_name, term, class_time ) my_offered_course.print_info() print(' Instructor Name:', my_offered_course.instructor_name) print(' Term:', my_offered_course.term) print(' Class Time:', my_offered_course.class_time) </code></pre> <p>When I run the code, I'm getting the following error:</p> <pre class="lang-py prettyprint-override"><code>Traceback (most recent call last): File &quot;main.py&quot;, line 32, in &lt;module&gt; my_course = Course(course_number, course_title) TypeError: __init__() takes 1 positional argument but 3 were given </code></pre>
[ { "answer_id": 74593951, "author": "Martin Zeitler", "author_id": 549372, "author_profile": "https://Stackoverflow.com/users/549372", "pm_score": 1, "selected": false, "text": "readonly" }, { "answer_id": 74594292, "author": "IMSoP", "author_id": 157957, "author_profile": "https://Stackoverflow.com/users/157957", "pm_score": 2, "selected": false, "text": "include /* IF PHP 8 */ readonly /* END IF */ $php_code = file_get_contents($php_file_being_loaded);\nif ( PHP_VERSION_ID < 80000 ) {\n $php_code = preg_replace('#/\\* IF PHP 8 \\*/.*?/\\* END IF \\*/#s', '', $php_code);\n}\neval($php_code);\n" }, { "answer_id": 74598939, "author": "hanshenrik", "author_id": 1067003, "author_profile": "https://Stackoverflow.com/users/1067003", "pm_score": 1, "selected": false, "text": "{\n \"require\": {\n \"php\": \">=7.4\"\n },\n}\n {\n \"require\": {\n \"php\": \">=8.0\"\n },\n}\n composer require lib lib.php if(PHP_MAJOR_VERSION >= 8){\n require(\"lib_modern.php\");\n} else{\n require(\"lib_legacy.php\");\n}\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20617742/" ]
74,593,918
<p>I have a lambda that triggers off an S3 bucket upload (it basically converts a PDF to a dataframe and writes it to a different s3 bucket). Both of these belong to AWS account <em>A</em>. I would like to allow cross-account s3 access to trigger this lambda from another IAM user from account <em>B</em> (<code>Administrator</code>), however I am having issues with the <code>GetObject</code> operation. Here is how my lambda in account <em>A</em> looks:</p> <pre><code>LOGGER = logging.getLogger(__name__) logging.basicConfig(level=logging.ERROR) logging.getLogger(__name__).setLevel(logging.DEBUG) session = boto3.Session( aws_access_key_id=&quot;XXXX&quot;, aws_secret_access_key=&quot;XXXX&quot;, ) s3 = session.resource('s3') dest_bucket = 'bucket-output' csv_buffer = StringIO() def lambda_handler(event,context): source_bucket = event['Records'][0]['s3']['bucket']['name'] pdf_name = event['Records'][0]['s3']['object']['key'] LOGGER.info('Reading {} from {}'.format(pdf_name, source_bucket)) pdf_obj = s3.Object(source_bucket,pdf_name) fs = pdf_obj.get()['Body'].read() #### code is failing here df = convert_bytes_to_df(BytesIO(fs)) df.to_csv(csv_buffer,index=False) s3.Object(dest_bucket,str(pdf_name.split('.')[0])+&quot;.csv&quot;).put(Body=csv_buffer.getvalue()) LOGGER.info('Successfully converted {} from {} to {}'.format(pdf_name,source_bucket,dest_bucket)) </code></pre> <p>The lambda is failing with this error:</p> <pre><code>ClientError: An error occurred (AccessDenied) when calling the GetObject operation: Access Denied </code></pre> <p>I'm aware it's bad practice to have keys in the lambda file but I can't change things at the moment.</p> <p>The process works fine if I am uploading to the S3 bucket from within an IAM User in account <em>A</em> itself, but when I expose the S3 buckets to an IAM user from a separate account, the issues above start happening. This is the S3 bucket policy (terraform) allowing cross-account access to an IAM user from account <em>B</em>:</p> <pre><code>resource &quot;aws_s3_bucket_policy&quot; &quot;cross_account_input_access&quot; { bucket = aws_s3_bucket.statements_input.id policy = &lt;&lt;EOF { &quot;Version&quot;: &quot;2012-10-17&quot;, &quot;Statement&quot;: [ { &quot;Effect&quot;: &quot;Allow&quot;, &quot;Principal&quot;: { &quot;AWS&quot;: &quot;arn:aws:iam::XXXXXXXXX:user/Administrator&quot; }, &quot;Action&quot;: [ &quot;s3:ListBucket&quot; ], &quot;Resource&quot;: [ &quot;arn:aws:s3:::capsphere-input&quot; ] }, { &quot;Effect&quot;: &quot;Allow&quot;, &quot;Principal&quot;: { &quot;AWS&quot;: &quot;arn:aws:iam::XXXXXXXXX:user/Administrator&quot; }, &quot;Action&quot;: [ &quot;s3:PutObject&quot;, &quot;s3:GetObject&quot;, &quot;s3:DeleteObject&quot; ], &quot;Resource&quot;: [ &quot;arn:aws:s3:::bucket-name&quot;, &quot;arn:aws:s3:::bucket-name/*&quot; ] } ] } </code></pre> <p>And here is the policy attached to an IAM user from another AWS account <em>B</em> which enables <code>Administrator</code> from account <em>B</em> to write a pdf to account <em>A's</em> s3 bucket programmatically:</p> <pre><code>{ &quot;Version&quot;: &quot;2012-10-17&quot;, &quot;Statement&quot;: [ { &quot;Effect&quot;: &quot;Allow&quot;, &quot;Action&quot;: [ &quot;s3:ListBucket&quot; ], &quot;Resource&quot;: [ &quot;arn:aws:s3:::bucket-name&quot; ] }, { &quot;Effect&quot;: &quot;Allow&quot;, &quot;Action&quot;: [ &quot;s3:PutObject&quot;, &quot;s3:GetObject&quot;, &quot;s3:DeleteObject&quot; ], &quot;Resource&quot;: [ &quot;arn:aws:s3:::bucket-name&quot;, &quot;arn:aws:s3:::bucket-name/*&quot; ] } ] } </code></pre> <p>I write the file to the bucket from <code>Administrator</code> using <code>aws cli</code> like this:</p> <pre><code>aws s3 cp filename.pdf s3://bucket-name </code></pre> <p>I can't figure out what else needs to change.</p>
[ { "answer_id": 74594303, "author": "Pawel Piwosz", "author_id": 20614302, "author_profile": "https://Stackoverflow.com/users/20614302", "pm_score": 0, "selected": false, "text": "session = boto3.Session(\n aws_access_key_id=\"XXXX\",\n aws_secret_access_key=\"XXXX\",\n region_name=\"<REGION>\"\n)\n" }, { "answer_id": 74594638, "author": "John Rotenstein", "author_id": 174777, "author_profile": "https://Stackoverflow.com/users/174777", "pm_score": 1, "selected": false, "text": "Administrator GetObject PutObject {\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Effect\": \"Allow\",\n \"Action\": \"s3:GetObject\"\n \"Resource\": \"arn:aws:s3:::source-bucket/*\"\n },\n {\n \"Effect\": \"Allow\",\n \"Action\": \"s3:PutObject\"\n \"Resource\": \"arn:aws:s3:::destination-bucket/*\"\n }\n ]\n}\n Administrator PutObject {\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Effect\": \"Allow\",\n \"Principal\": {\n \"AWS\": \"arn:aws:iam::Account-B:user/Administrator\"\n },\n \"Action\": \"s3:PutObject\",\n \"Resource\": \"arn:aws:s3:::source-bucket/*\"\n }\n ]\n}\n Administrator GetObject {\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Effect\": \"Allow\",\n \"Principal\": {\n \"AWS\": \"arn:aws:iam::Account-B:user/Administrator\"\n },\n \"Action\": [\n \"s3:ListBucket\"\n ],\n \"Resource\": \"arn:aws:s3:::destination-bucket\"\n }, \n {\n \"Effect\": \"Allow\",\n \"Principal\": {\n \"AWS\": \"arn:aws:iam::Account-B:user/Administrator\"\n },\n \"Action\": [\n \"s3:GetObject\",\n \"s3:DeleteObject\"\n ],\n \"Resource\": \"arn:aws:s3:::destination-bucket/*\"\n }\n ]\n}\n Administrator s3:* {\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Effect\": \"Allow\",\n \"Action\": [\n \"s3:ListBucket\"\n ],\n \"Resource\": [\n \"arn:aws:s3:::destination-bucket\"\n ]\n },\n {\n \"Effect\": \"Allow\",\n \"Action\": [\n \"s3:PutObject\",\n \"s3:GetObject\",\n \"s3:DeleteObject\"\n ],\n \"Resource\": [\n \"arn:aws:s3:::source-bucket/*\",\n \"arn:aws:s3:::destination-bucket/*\"\n ]\n }\n ]\n}\n" }, { "answer_id": 74605098, "author": "John Rotenstein", "author_id": 174777, "author_profile": "https://Stackoverflow.com/users/174777", "pm_score": 2, "selected": true, "text": "ACL=bucket-owner-full-control" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2482149/" ]
74,593,927
<p><strong>Some context :</strong></p> <p>In Godot, one is constantly working with nodes and those nodes' children.</p> <p>Godot has made the design choice of letting the dev manipulate nodes with some sort of <strong>querying</strong> language that often relies on the full path (starting from the root of the current scene).</p> <p>For example if the scene is structured like this :</p> <pre><code>MyRootNode | |-- MyChild1 | | | |-- MySubChild1 | | |-- Mychild2 </code></pre> <p>...then the devs are encouraged to access &quot;MySubChild1&quot; with a path :</p> <pre><code>node = get_node(&quot;MyRootNode/MyChild1/MySubChild1&quot;) </code></pre> <p>(note: I''m using the verbose &quot;get_node&quot; syntax rather than $ syntax for readability to C# devs)</p> <p>Because of that ease of use, I can see that GDScript devs have a tendency to do this :</p> <pre><code>root = get_node(&quot;MyRootNode&quot;) child1 = get_node(&quot;MyRootNode/MyChild1&quot;) subchild1 = get_node(&quot;MyRootNode/MyChild1/MySubChild1&quot;) </code></pre> <p>...rather than this (pseudo-code) :</p> <pre><code>root = get_node(&quot;MyRootNode&quot;) child1 = root.get_child(&quot;MyChild1&quot;) subchild1 = child1 .get_child(&quot;MySubChild1&quot;) </code></pre> <p><strong>It makes perfect sense to write queries in a weakly-typed scripting language :</strong> all the queryable items have more or less the same type.</p> <p>The <em>named</em> version of get_child() doesn't even exist. In reality you would need to do this :</p> <pre><code>root = get_node(&quot;MyRootNode&quot;) child1 = root.get_child(0) // first child subchild1 = child1 .get_child(0) // first child </code></pre> <p>=================</p> <p><strong>This is all very awkward for a C# developer.</strong> Because of the typing. It's like we're given safety but then it's instantly taken away.</p> <p>Imagine this :</p> <pre><code>public class MyRootNode : Node { private Control MyChild1 = null; // initialized in _Ready once and for all public override void _Ready() { MyChild1 = GetNode&lt;Control&gt;(&quot;MyChild1&quot;); } public override void _Process(float delta) { // Not possible!!! var mySubChild1 = MyChild1.GetChild&lt;TextureRect&gt;(&quot;MySubChild1&quot;); } } </code></pre> <p><strong>My question :</strong> Is there a way of getting a child in a safe way? It seems to me that none of the solutions seem natural (as developed below), and I mean &quot;safe&quot; in contrast to that.</p> <p>If I do this :</p> <pre><code>var mySubChild1 = GetNode&lt;TextureRect&gt;(&quot;MyRootNode/MyChild1/MySubChild1&quot;); </code></pre> <p>...then it's extremely unsafe in case of nodes renaming or if I decide to change the tree structure.</p> <p>If I do this :</p> <pre><code>var mySubChild1 = MyChild1.GetChild&lt;TextureRect&gt;(0); </code></pre> <p>....then it's still horrendously unreadable (accessing named items by index? No thanks)</p> <p><strong>As a C# dev, how do <em>you</em> do it?</strong></p>
[ { "answer_id": 74594303, "author": "Pawel Piwosz", "author_id": 20614302, "author_profile": "https://Stackoverflow.com/users/20614302", "pm_score": 0, "selected": false, "text": "session = boto3.Session(\n aws_access_key_id=\"XXXX\",\n aws_secret_access_key=\"XXXX\",\n region_name=\"<REGION>\"\n)\n" }, { "answer_id": 74594638, "author": "John Rotenstein", "author_id": 174777, "author_profile": "https://Stackoverflow.com/users/174777", "pm_score": 1, "selected": false, "text": "Administrator GetObject PutObject {\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Effect\": \"Allow\",\n \"Action\": \"s3:GetObject\"\n \"Resource\": \"arn:aws:s3:::source-bucket/*\"\n },\n {\n \"Effect\": \"Allow\",\n \"Action\": \"s3:PutObject\"\n \"Resource\": \"arn:aws:s3:::destination-bucket/*\"\n }\n ]\n}\n Administrator PutObject {\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Effect\": \"Allow\",\n \"Principal\": {\n \"AWS\": \"arn:aws:iam::Account-B:user/Administrator\"\n },\n \"Action\": \"s3:PutObject\",\n \"Resource\": \"arn:aws:s3:::source-bucket/*\"\n }\n ]\n}\n Administrator GetObject {\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Effect\": \"Allow\",\n \"Principal\": {\n \"AWS\": \"arn:aws:iam::Account-B:user/Administrator\"\n },\n \"Action\": [\n \"s3:ListBucket\"\n ],\n \"Resource\": \"arn:aws:s3:::destination-bucket\"\n }, \n {\n \"Effect\": \"Allow\",\n \"Principal\": {\n \"AWS\": \"arn:aws:iam::Account-B:user/Administrator\"\n },\n \"Action\": [\n \"s3:GetObject\",\n \"s3:DeleteObject\"\n ],\n \"Resource\": \"arn:aws:s3:::destination-bucket/*\"\n }\n ]\n}\n Administrator s3:* {\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Effect\": \"Allow\",\n \"Action\": [\n \"s3:ListBucket\"\n ],\n \"Resource\": [\n \"arn:aws:s3:::destination-bucket\"\n ]\n },\n {\n \"Effect\": \"Allow\",\n \"Action\": [\n \"s3:PutObject\",\n \"s3:GetObject\",\n \"s3:DeleteObject\"\n ],\n \"Resource\": [\n \"arn:aws:s3:::source-bucket/*\",\n \"arn:aws:s3:::destination-bucket/*\"\n ]\n }\n ]\n}\n" }, { "answer_id": 74605098, "author": "John Rotenstein", "author_id": 174777, "author_profile": "https://Stackoverflow.com/users/174777", "pm_score": 2, "selected": true, "text": "ACL=bucket-owner-full-control" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9359785/" ]
74,593,928
<p>I can't display object in Vue 3 script setup. I used ref, reactive and standard variables but all scenarios is unsuccessful.</p> <p>I want to reflect the response from the getDetail request to the screen. getDetail is fetching this data asynchronously. I run into a problem in every scenario.</p> <h2>ref() usage</h2> <pre><code> &lt;script setup&gt; let movie = ref([]) const getMovieData = async ()=&gt; { try { const data = await getDetail('movie', route.params.id) movie.value.push(data) } catch (e){ console.log(e) } } getMovieData() &lt;/script&gt; &lt;template&gt; &lt;h1&gt;{{movie[0].original_title}}&lt;/h1&gt; &lt;/template&gt; </code></pre> <p>I am able to show data in this usage but I am getting these errors <a href="https://i.stack.imgur.com/vllFO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vllFO.png" alt="ref() Error" /></a></p> <hr /> <h2>reactive() usage</h2> <pre><code> &lt;script setup&gt; let movie = reactive({ data:null }) const getMovieData = async ()=&gt;{ try { const data = await getDetail('movie', route.params.id) movie.data = data }catch (e){ console.log(e) } } getMovieData() &lt;/script&gt; &lt;template&gt; &lt;h1&gt;{{movie.data.original_title}}&lt;/h1&gt; &lt;/template&gt; </code></pre> <p>In this usage I can show data but I get similar errors <a href="https://i.stack.imgur.com/rJ4RK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rJ4RK.png" alt="reactive()errors" /></a></p> <hr /> <h2>Standart variable usage</h2> <pre><code>&lt;script setup&gt; let movie const getMovieData = async ()=&gt;{ try { const data = await getDetail('movie', route.params.id) movie =data }catch (e){ console.log(e) } } getMovieData() &lt;/script&gt; &lt;template&gt; &lt;h1&gt;{{movie.id}}&lt;/h1&gt; &lt;/template&gt; </code></pre> <p>In this usage, the data does not appear on the screen, because the movie object is formed asynchronously.</p> <hr /> <p>How do I manage to display this object on the screen in the most correct way without getting an error?</p>
[ { "answer_id": 74593967, "author": "yoduh", "author_id": 6225326, "author_profile": "https://Stackoverflow.com/users/6225326", "pm_score": 2, "selected": true, "text": "movie[0]?.original_title\n let movie = ref([\n {\n original_title: ''\n }\n])\n" }, { "answer_id": 74593975, "author": "Abiodun Olunu", "author_id": 9990773, "author_profile": "https://Stackoverflow.com/users/9990773", "pm_score": 2, "selected": false, "text": "<h1 v-if=\"movie && movie.length\">{{movie[0].id}</h1>" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17806037/" ]
74,593,962
<p>I am a python newbie. I am in the phase of testing my code but I am quite confused why sometimes this works and sometimes it does not. As per my understanding the random.randint(0,13) this means that random numbers from 0 to 12 which is the number of my cards list.</p> <p><strong>Error im geting:</strong></p> <pre><code>Traceback (most recent call last): File &quot;main.py&quot;, line 72, in &lt;module&gt; generate_random_hand() File &quot;main.py&quot;, line 32, in generate_random_hand computer_hand.append(cards[rand1]) IndexError: list index out of range </code></pre> <p><strong>Here is the code:</strong></p> <pre><code>#Init cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] computer_hand = [] player_hand = [] isContinue = True #Generate first 2 cards of computer and player def generate_random_hand(): for _ in range(0,2): rand1 = random.randint(0,13) rand2 = random.randint(0,13) computer_hand.append(cards[rand1]) player_hand.append(cards[rand2]) </code></pre> <p>Here is the screenshot of the problem: <a href="https://i.stack.imgur.com/PyRD0.jpg" rel="nofollow noreferrer">Image of ERROR</a></p> <p>EDIT: Seems like I have mistaken the functionality of for _ in range() which does not include the 2nd argument and the random.randint() which includes the 2nd argument. Since I cannot delete this post anymore.</p>
[ { "answer_id": 74593979, "author": "Adam Smooch", "author_id": 10761353, "author_profile": "https://Stackoverflow.com/users/10761353", "pm_score": 1, "selected": true, "text": ">>> from random import randint\n>>> randint(0,13)\n3\n>>> randint(0,13)\n1\n>>> randint(0,13)\n10\n>>> randint(0,13)\n2\n>>> randint(0,13)\n12\n>>> randint(0,13)\n12\n>>> randint(0,13)\n3\n>>> randint(0,13)\n12\n>>> randint(0,13)\n6\n>>> randint(0,13)\n2\n>>> randint(0,13)\n13\n 13" }, { "answer_id": 74593994, "author": "Leo Ward", "author_id": 20421592, "author_profile": "https://Stackoverflow.com/users/20421592", "pm_score": 0, "selected": false, "text": "random.randint(0, 12)\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74593962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18126961/" ]
74,594,034
<p>I have two dataframes.</p> <p><strong>Input data</strong></p> <pre><code># First df mainly consists data provided by the user fdf = pd.DataFrame(columns=['user_data'],data=[10,14,1],index=['alpha','beta','gamma']) user_data alpha 10 beta 14 gamma 1 # Second df is basically a default data consisting kind of analysis I can run based on the data in the first dataframe provided the user sdf = pd.DataFrame(columns=['AD_analysis','BGD_analysis','ABG_analysis'], data=[[1,0,1],[0,1,1],[0,1,1],[1,1,0]],index=['alpha','beta','gamma','delta']) sdf = AD_analysis BGD_analysis ABG_analysis alpha 1 0 1 beta 0 1 1 gamma 0 1 1 delta 1 1 0 # Above table basically tells us that we can do AD_analysis if alpha, delta values are given by the user in the first df </code></pre> <p>So, I want to know kind of analysis (sdf) I can run based on the data provided by the user (fdf).</p> <p><strong>Expected answer:</strong></p> <pre><code># Since delta is not given and I cannot run any analysis associated with this parameters # Possible analysis with given data is ['ABG_analysis'] </code></pre> <p><strong>My approach:</strong></p> <pre><code># find common index com_idx = fdf.index.intersection(sdf.index) if len(com_idx)==3 &amp; com_idx.isin('alpha'): print('ABG_analysis') if len(com_idx)==3 &amp; com_idx.isin('delta'): print('BGD_analysis') if len(com_idx)==2 : print('AD_analysis') </code></pre> <p>Too many if statements does not convince as a best pythonic approach. Can you suggest a better approach?</p>
[ { "answer_id": 74593979, "author": "Adam Smooch", "author_id": 10761353, "author_profile": "https://Stackoverflow.com/users/10761353", "pm_score": 1, "selected": true, "text": ">>> from random import randint\n>>> randint(0,13)\n3\n>>> randint(0,13)\n1\n>>> randint(0,13)\n10\n>>> randint(0,13)\n2\n>>> randint(0,13)\n12\n>>> randint(0,13)\n12\n>>> randint(0,13)\n3\n>>> randint(0,13)\n12\n>>> randint(0,13)\n6\n>>> randint(0,13)\n2\n>>> randint(0,13)\n13\n 13" }, { "answer_id": 74593994, "author": "Leo Ward", "author_id": 20421592, "author_profile": "https://Stackoverflow.com/users/20421592", "pm_score": 0, "selected": false, "text": "random.randint(0, 12)\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74594034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11922765/" ]
74,594,053
<p>Hi i was just wondering if anyone can show me how to use an array with mabye a boolean or something to either end restart last function or start from the very beginning of my Ohm's Law Caculator. Here is my code currently. Im kinda on a time crunch so thank you in advance.</p> <pre><code>using System; using System.Threading; namespace ENGR115_CourseProject_OctTerm { internal class Program { static void Main(string[] args) { Console.WriteLine(&quot;Hello World!&quot;); Console.WriteLine(&quot; Hello my name is Zachari Pryor &quot;); Console.WriteLine(&quot; This is the Course Programming Project: Ohm's Law &quot;); Console.WriteLine(&quot; The point of the term course project is to use C#&quot;); Console.WriteLine(&quot; to have user solve Ohm's law using different variables of their choosing.&quot;); Console.WriteLine(&quot; Press any key to move on&quot;); Console.ReadLine(); Console.Clear(); enterName(); Console.ReadLine(); } static void enterName() { Console.Write(&quot; Enter your name: &quot;); string name = Console.ReadLine(); Console.WriteLine(&quot; Hello it is very nice to meet you &quot; + name); Console.WriteLine(&quot; Are you ready to use C# to solve Ohm's Law (y or n) ? &quot;); string y = Console.ReadLine(); Console.WriteLine(&quot; Great!!, well then lets get started.Click enter&quot;); Console.ReadLine(); Console.Clear(); Equation(); Console.ReadLine(); } static void Equation() { Console.Write(&quot;What would you like to find? V,I, or R:&quot;); string unitToFind = Console.ReadLine(); if (unitToFind == &quot;V&quot;) { Console.WriteLine(&quot;Enter the Resistance as a decimal.&quot;); double R; while (!double.TryParse(Console.ReadLine(), out R)) ; Console.WriteLine(&quot;Enter the Amperage as a decimal number&quot;); double I; while (!double.TryParse(Console.ReadLine(), out I)) ; double V = R * I; Console.WriteLine(&quot;Voltage is: &quot; + V.ToString() + &quot; Volts&quot;); } else if (unitToFind == &quot;I&quot;) { Console.WriteLine(&quot;Enter the Voltage as a decimal number&quot;); double V; while (!double.TryParse(Console.ReadLine(), out V)) ; Console.WriteLine(&quot;Enter the Resistance as a decimal number&quot;); double R; while (!double.TryParse(Console.ReadLine(), out R)) ; double I = V / R; Console.WriteLine(&quot;Amperage is: &quot; + I.ToString() + &quot; Amps&quot;); } else if (unitToFind == &quot;R&quot;) { Console.WriteLine(&quot;Enter the Voltage as a decimal number&quot;); double V; while (!double.TryParse(Console.ReadLine(), out V)) ; Console.WriteLine(&quot;Enter the Amperage as a decimal number&quot;); double I; while (!double.TryParse(Console.ReadLine(), out I)) ; double R = V / I; Console.WriteLine(&quot;Resistance is: &quot; + R.ToString() + &quot; Ohms&quot;); } else { ** Console.WriteLine(&quot;You need to enter either V, I or R. Please run the program again.&quot;); Console.WriteLine(&quot;Please enter 0 to continue working problems&quot;); Console.WriteLine(&quot;1 to quit&quot;); Console.WriteLine(&quot;2 to restart entire program. &quot;); } int[] actionTake = { 0, 1, 2 }; { Console.Write(actionTake =[1]); Equation(); Console.Write(actionTake[0]); Console.ReadLine(); } ** </code></pre> <p>I want the code to start back over from the beginning of the the equation(); method if my 0 array is used then if 1 is used to end and close program and 2 i want it to start completley over. and if possible think of some ways i can use arrays in other areas of the Program.</p>
[ { "answer_id": 74593979, "author": "Adam Smooch", "author_id": 10761353, "author_profile": "https://Stackoverflow.com/users/10761353", "pm_score": 1, "selected": true, "text": ">>> from random import randint\n>>> randint(0,13)\n3\n>>> randint(0,13)\n1\n>>> randint(0,13)\n10\n>>> randint(0,13)\n2\n>>> randint(0,13)\n12\n>>> randint(0,13)\n12\n>>> randint(0,13)\n3\n>>> randint(0,13)\n12\n>>> randint(0,13)\n6\n>>> randint(0,13)\n2\n>>> randint(0,13)\n13\n 13" }, { "answer_id": 74593994, "author": "Leo Ward", "author_id": 20421592, "author_profile": "https://Stackoverflow.com/users/20421592", "pm_score": 0, "selected": false, "text": "random.randint(0, 12)\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74594053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20549538/" ]
74,594,059
<p>I already know how to use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.fillna.html" rel="nofollow noreferrer">fillna()</a> but it fills every empty value with the same indicated value. In this case, I want to fill each empty value with different values, should I use the row number or how can it be done?</p> <p><a href="https://i.stack.imgur.com/etkVl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/etkVl.png" alt="enter image description here" /></a></p> <p><strong>Failed try</strong>:</p> <p><a href="https://i.stack.imgur.com/3X7Qe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3X7Qe.png" alt="enter image description here" /></a></p> <p>I want it to be</p> <p>bmw 320i 2 plymouth reliant 1 honda civic 3</p>
[ { "answer_id": 74593979, "author": "Adam Smooch", "author_id": 10761353, "author_profile": "https://Stackoverflow.com/users/10761353", "pm_score": 1, "selected": true, "text": ">>> from random import randint\n>>> randint(0,13)\n3\n>>> randint(0,13)\n1\n>>> randint(0,13)\n10\n>>> randint(0,13)\n2\n>>> randint(0,13)\n12\n>>> randint(0,13)\n12\n>>> randint(0,13)\n3\n>>> randint(0,13)\n12\n>>> randint(0,13)\n6\n>>> randint(0,13)\n2\n>>> randint(0,13)\n13\n 13" }, { "answer_id": 74593994, "author": "Leo Ward", "author_id": 20421592, "author_profile": "https://Stackoverflow.com/users/20421592", "pm_score": 0, "selected": false, "text": "random.randint(0, 12)\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74594059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20616738/" ]
74,594,062
<p>Here's (what I think is) the correct way to layout a (reflowable) html document. The width is capped relative to the font width, and the margin is auto calculated to be symmetric so that the content is centred.</p> <p>This gives a pleasant reading experience on both ultra-wide and mobile.</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 { max-width: 30em; margin: 0 auto; padding: 2em; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;body&gt; &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris tellus nisl, sollicitudin ac lorem sit amet, vehicula pretium leo. Curabitur convallis tristique ipsum vel consequat. Maecenas sit amet sem ipsum. Aliquam quis accumsan ante. &lt;/p&gt; &lt;p&gt;Maecenas at mauris euismod, placerat justo vel, ultrices diam. Sed mollis sollicitudin risus vel pharetra. Integer bibendum iaculis magna, ac sagittis mauris elementum non. Vestibulum non aliquam mi. Donec sit amet dui bibendum, consectetur lacus quis, interdum sem. &lt;/p&gt; &lt;p&gt;Integer vitae massa lectus. Nulla placerat, augue at pellentesque viverra, velit odio dapibus felis, at feugiat arcu magna vel mauris. Aliquam sed luctus urna. Morbi magna orci, dignissim ut purus non, mattis vulputate tortor. &lt;/p&gt; &lt;/body&gt;</code></pre> </div> </div> </p> <p>However, now I want to add line numbers in the margin/padding while keeping the content centred. And am unsure how to do so.</p> <p>On way to do this is have each paragraph be a grid with the number in the first column and the text in the second column.</p> <p>Is this the best way to do this? If so how do get the same behaviour as before? How to we ensure that the content (in the second column) is centred?</p> <p>Maybe we need javascript to calculate the margins widths in % units. But if be have to use js then maybe we don't need the the line numbers and content in the same html container. Maybe I should just give up and inline the line numbers.</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>div { display:grid; column-gap: 2em } .line-number { grid-column-start:1 } p { grid-column-start:2 }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;body&gt; &lt;div&gt; &lt;p class='line-number'&gt;1&lt;/p&gt; &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris tellus nisl, sollicitudin ac lorem sit amet, vehicula pretium leo. Curabitur convallis tristique ipsum vel consequat. Maecenas sit amet sem ipsum. Aliquam quis accumsan ante. &lt;/p&gt; &lt;/div&gt; &lt;div&gt; &lt;p class='line-number'&gt;2&lt;/p&gt; &lt;p&gt;Maecenas at mauris euismod, placerat justo vel, ultrices diam. Sed mollis sollicitudin risus vel pharetra. Integer bibendum iaculis magna, ac sagittis mauris elementum non. Vestibulum non aliquam mi. Donec sit amet dui bibendum, consectetur lacus quis, interdum sem. &lt;/p&gt; &lt;/div&gt; &lt;div&gt; &lt;p class='line-number'&gt;3&lt;/p&gt; &lt;p&gt;Integer vitae massa lectus. Nulla placerat, augue at pellentesque viverra, velit odio dapibus felis, at feugiat arcu magna vel mauris. Aliquam sed luctus urna. Morbi magna orci, dignissim ut purus non, mattis vulputate tortor. &lt;/p&gt; &lt;/div&gt; &lt;/body&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74594160, "author": "Carsten Massmann", "author_id": 2610061, "author_profile": "https://Stackoverflow.com/users/2610061", "pm_score": -1, "selected": false, "text": "<ol> <li> ol {\n counter-reset: item;\n padding-left: 0;\n}\nli {\n width:10em;\n text-align:left;\n display: block;\n margin-bottom: .5em;\n margin-left: auto;\n margin-right: auto;\n}\nli::before {\n text-align:right;\n display: inline-block;\n content: counter(item);\n padding-right:0.5em;\n counter-increment: item;\n width: 2em;\n margin-left: -2.5em;\n} <ol>\n <li>One<br>the first sentence.</li>\n <li>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris tellus nisl, sollicitudin ac lorem sit amet, vehicula pretium leo. Curabitur convallis tristique ipsum vel consequat. Maecenas sit amet sem ipsum. Aliquam quis accumsan ante.</li>\n <li>Maecenas at mauris euismod, placerat justo vel, ultrices diam. Sed mollis sollicitudin risus vel pharetra. Integer bibendum iaculis magna, ac sagittis mauris elementum non. Vestibulum non aliquam mi. Donec sit amet dui bibendum, consectetur lacus quis, interdum sem.</li>\n <li>Integer vitae massa lectus. Nulla placerat, augue at pellentesque viverra, velit odio dapibus felis, at feugiat arcu magna vel mauris. Aliquam sed luctus urna. Morbi magna orci, dignissim ut purus non, mattis vulputate tortor.</li>\n <li>Five</li>\n <li>Six</li>\n <li>Seven</li>\n <li>Eight</li>\n <li>Nine<br>Items</li>\n <li>Ten<br>Items</li>\n</ol>" }, { "answer_id": 74594327, "author": "Temani Afif", "author_id": 8620333, "author_profile": "https://Stackoverflow.com/users/8620333", "pm_score": -1, "selected": false, "text": "div {\n display:grid;\n grid-template-columns: 3ch auto 3ch; /* 3ch is a kind of max width for your numbers */\n justify-content: center;\n column-gap: 2em\n}\np {\n max-width: 30em;\n} <body>\n<div>\n<p class='line-number'>1</p>\n<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris tellus nisl, sollicitudin ac lorem sit amet, vehicula pretium leo. Curabitur convallis tristique ipsum vel consequat. Maecenas sit amet sem ipsum. Aliquam quis accumsan ante. </p>\n</div>\n<div>\n<p class='line-number'>2</p>\n<p>Maecenas at mauris euismod, placerat justo vel, ultrices diam. Sed mollis sollicitudin risus vel pharetra. Integer bibendum iaculis magna, ac sagittis mauris elementum non. Vestibulum non aliquam mi. Donec sit amet dui bibendum, consectetur lacus quis, interdum sem. </p>\n</div>\n<div>\n<p class='line-number'>3</p>\n<p>Integer vitae massa lectus. Nulla placerat, augue at pellentesque viverra, velit odio dapibus felis, at feugiat arcu magna vel mauris. Aliquam sed luctus urna. Morbi magna orci, dignissim ut purus non, mattis vulputate tortor. </p>\n</div>\n</body>" }, { "answer_id": 74594339, "author": "Skin_phil", "author_id": 13258195, "author_profile": "https://Stackoverflow.com/users/13258195", "pm_score": 0, "selected": false, "text": "div {\n display:grid;\n grid-template-columns: 20px 1fr;\n column-gap: 10px;\n}\n\np {\npadding-right:30px;\n} <body>\n<div>\n<p class='line-number'>1</p>\n<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris tellus nisl, sollicitudin ac lorem sit amet, vehicula pretium leo. Curabitur convallis tristique ipsum vel consequat. Maecenas sit amet sem ipsum. Aliquam quis accumsan ante. </p>\n</div>\n<div>\n<p class='line-number'>2</p>\n<p>Maecenas at mauris euismod, placerat justo vel, ultrices diam. Sed mollis sollicitudin risus vel pharetra. Integer bibendum iaculis magna, ac sagittis mauris elementum non. Vestibulum non aliquam mi. Donec sit amet dui bibendum, consectetur lacus quis, interdum sem. </p>\n</div>\n<div>\n<p class='line-number'>3</p>\n<p>Integer vitae massa lectus. Nulla placerat, augue at pellentesque viverra, velit odio dapibus felis, at feugiat arcu magna vel mauris. Aliquam sed luctus urna. Morbi magna orci, dignissim ut purus non, mattis vulputate tortor. </p>\n</div>\n</body>" }, { "answer_id": 74594369, "author": "G-Cyrillus", "author_id": 2442099, "author_profile": "https://Stackoverflow.com/users/2442099", "pm_score": 2, "selected": true, "text": "body {\n max-width: 30em;\n margin: 0 auto;\n padding: 2em;\n}\n\ndiv {\n display: grid;\n grid-template-columns: 0 1fr;\n}\n\n.line-number {\n grid-column-start: 1;\n margin-inline-start: -2em;\n}\n\np {\n grid-column-start: 2\n}\n\n/* does stand in the middle ? */\nbody,\np:not([class]) {\n background: linear-gradient(to left, rgba(0, 0, 0, 0.2) 50%, #0000 50%);\n} <body>\n <div>\n <p class='line-number'>1</p>\n <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris tellus nisl, sollicitudin ac lorem sit amet, vehicula pretium leo. Curabitur convallis tristique ipsum vel consequat. Maecenas sit amet sem ipsum. Aliquam quis accumsan ante. </p>\n </div>\n <div>\n <p class='line-number'>2</p>\n <p>Maecenas at mauris euismod, placerat justo vel, ultrices diam. Sed mollis sollicitudin risus vel pharetra. Integer bibendum iaculis magna, ac sagittis mauris elementum non. Vestibulum non aliquam mi. Donec sit amet dui bibendum, consectetur lacus\n quis, interdum sem. </p>\n </div>\n <div>\n <p class='line-number'>3</p>\n <p>Integer vitae massa lectus. Nulla placerat, augue at pellentesque viverra, velit odio dapibus felis, at feugiat arcu magna vel mauris. Aliquam sed luctus urna. Morbi magna orci, dignissim ut purus non, mattis vulputate tortor. </p>\n </div>\n</body> div {\n max-width: 30em;\n margin: 2em auto;\n padding: 0 2em;\n display: grid;\n}\n\n.line-number {\n margin-inline-start: -2em; /* offset */\n position:absolute; /* off the flow */\n}\n\np {\n margin:0\n}\n\n/* does it stand in the middle ? */\nbody,\ndiv,\np:not([class]) {\n background: linear-gradient(to left, rgba(0, 0, 0, 0.2) 50%, #0000 50%);\n} <body>\n <div>\n <p class='line-number'>1</p>\n <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris tellus nisl, sollicitudin ac lorem sit amet, vehicula pretium leo. Curabitur convallis tristique ipsum vel consequat. Maecenas sit amet sem ipsum. Aliquam quis accumsan ante. </p>\n </div>\n <div>\n <p class='line-number'>2</p>\n <p>Maecenas at mauris euismod, placerat justo vel, ultrices diam. Sed mollis sollicitudin risus vel pharetra. Integer bibendum iaculis magna, ac sagittis mauris elementum non. Vestibulum non aliquam mi. Donec sit amet dui bibendum, consectetur lacus\n quis, interdum sem. </p>\n </div>\n <div>\n <p class='line-number'>3</p>\n <p>Integer vitae massa lectus. Nulla placerat, augue at pellentesque viverra, velit odio dapibus felis, at feugiat arcu magna vel mauris. Aliquam sed luctus urna. Morbi magna orci, dignissim ut purus non, mattis vulputate tortor. </p>\n </div>\n</body> body {\n max-width: 30em;\n margin: 0 auto;\n padding: 2em;\n counter-reset: ps;\n}\n\np:before {\n counter-increment: ps;\n content: counter(ps);\n position: absolute;\n margin-inline-start: -2em;\n}\n\n\n/* does it stand in the middle ? */\n\nbody,\np {\n background: linear-gradient(to left, rgba(0, 0, 0, 0.2) 50%, #0000 50%);\n} <body>\n <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris tellus nisl, sollicitudin ac lorem sit amet, vehicula pretium leo. Curabitur convallis tristique ipsum vel consequat. Maecenas sit amet sem ipsum. Aliquam quis accumsan ante. </p>\n <p>Maecenas at mauris euismod, placerat justo vel, ultrices diam. Sed mollis sollicitudin risus vel pharetra. Integer bibendum iaculis magna, ac sagittis mauris elementum non. Vestibulum non aliquam mi. Donec sit amet dui bibendum, consectetur lacus quis,\n interdum sem. </p>\n <p>Integer vitae massa lectus. Nulla placerat, augue at pellentesque viverra, velit odio dapibus felis, at feugiat arcu magna vel mauris. Aliquam sed luctus urna. Morbi magna orci, dignissim ut purus non, mattis vulputate tortor. </p>\n</body>" }, { "answer_id": 74594383, "author": "OliverRadini", "author_id": 5011469, "author_profile": "https://Stackoverflow.com/users/5011469", "pm_score": 1, "selected": false, "text": ".wrapper {\n counter-reset: my-awesome-counter;\n max-width: 30em;\n margin: 0 auto;\n padding: 2em;\n}\np {\n counter-increment: my-awesome-counter;\n position: relative;\n}\np:before {\n content: counter(my-awesome-counter);\n position: absolute;\n left: -15px;\n} <div class=\"wrapper\">\n<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris tellus nisl, sollicitudin ac lorem sit amet, vehicula pretium leo. Curabitur convallis tristique ipsum vel consequat. Maecenas sit amet sem ipsum. Aliquam quis accumsan ante. </p>\n<p>Maecenas at mauris euismod, placerat justo vel, ultrices diam. Sed mollis sollicitudin risus vel pharetra. Integer bibendum iaculis magna, ac sagittis mauris elementum non. Vestibulum non aliquam mi. Donec sit amet dui bibendum, consectetur lacus quis, interdum sem. </p>\n<p>Integer vitae massa lectus. Nulla placerat, augue at pellentesque viverra, velit odio dapibus felis, at feugiat arcu magna vel mauris. Aliquam sed luctus urna. Morbi magna orci, dignissim ut purus non, mattis vulputate tortor. </p>\n</div>" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74594062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11998382/" ]
74,594,081
<p>I am making an application that creates a password based on the requirements of the password needed. The requirements are picked through check buttons, so if a check button is on, then the password should contain those values, if the check button is off then the password should not contain that value. All of the check buttons are turned on by default and the user can change them as needed.</p> <p>Here is the code for the checkbuttons:</p> <pre><code># This allows us to get the value (or the state of the checkbox: checked or unchecked) from the checkbox var_LowercaseLtrsCheckBtn = IntVar(value=1) var_UppercaseLtrsCheckBtn = IntVar(value=1) var_NumbersCheckBtn = IntVar(value=1) var_SymbolsCheckBtn = IntVar(value=1) # Checkbox for including lowercase letters includeLowercaseLtrsCheckBtn = Checkbutton(root, text=&quot;Include Lowercase Letters&quot;, variable=var_LowercaseLtrsCheckBtn, onvalue=1, offvalue=0) includeLowercaseLtrsCheckBtn.pack() # Checkbox for including uppercase letters includeUppercaseLtrsCheckBtn = Checkbutton(root, text=&quot;Include Uppercase Letters&quot;, variable = var_UppercaseLtrsCheckBtn, onvalue=1, offvalue=0) includeUppercaseLtrsCheckBtn.pack() # Checkbox for including numbers includeNumbersCheckBtn = Checkbutton(root, text=&quot;Include Numbers&quot;, variable = var_NumbersCheckBtn, onvalue=1, offvalue=0) includeNumbersCheckBtn.pack() # Checkbox for including symbols includeSymbolsCheckBtn = Checkbutton(root, text=&quot;Include Symbols&quot;, variable = var_SymbolsCheckBtn, onvalue=1, offvalue=0) includeSymbolsCheckBtn.pack() </code></pre> <p>This is the code for creating a password based on if the user wants lowercase letters, uppercase letters, numbers, and/or symbols. This code is in a function that is run when the generate password button is pressed.</p> <pre><code># Create Phrases which the Password Must Be Compromised of: lowercaseLetters = &quot;abcdefghijklmnopqrstuvwxyz&quot; uppercaseLetters = &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ&quot; numbers = &quot;1234567890&quot; symbols = &quot;~!@#$%^&amp;*()[]&lt;&gt;?&quot; # Create Password with ONLY LOWERCASE LETTERS for i in range(0, get_PasswordLength): password = random.choice(lowercaseLetters) returnPassword_Entry.insert(END, password) </code></pre> <p>I tried to create a bunch of if statements that try every possible combination but it seemed too complex. Is there a better way to do this - to check which check buttons are checked and then create a password based on those requirements?</p>
[ { "answer_id": 74594160, "author": "Carsten Massmann", "author_id": 2610061, "author_profile": "https://Stackoverflow.com/users/2610061", "pm_score": -1, "selected": false, "text": "<ol> <li> ol {\n counter-reset: item;\n padding-left: 0;\n}\nli {\n width:10em;\n text-align:left;\n display: block;\n margin-bottom: .5em;\n margin-left: auto;\n margin-right: auto;\n}\nli::before {\n text-align:right;\n display: inline-block;\n content: counter(item);\n padding-right:0.5em;\n counter-increment: item;\n width: 2em;\n margin-left: -2.5em;\n} <ol>\n <li>One<br>the first sentence.</li>\n <li>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris tellus nisl, sollicitudin ac lorem sit amet, vehicula pretium leo. Curabitur convallis tristique ipsum vel consequat. Maecenas sit amet sem ipsum. Aliquam quis accumsan ante.</li>\n <li>Maecenas at mauris euismod, placerat justo vel, ultrices diam. Sed mollis sollicitudin risus vel pharetra. Integer bibendum iaculis magna, ac sagittis mauris elementum non. Vestibulum non aliquam mi. Donec sit amet dui bibendum, consectetur lacus quis, interdum sem.</li>\n <li>Integer vitae massa lectus. Nulla placerat, augue at pellentesque viverra, velit odio dapibus felis, at feugiat arcu magna vel mauris. Aliquam sed luctus urna. Morbi magna orci, dignissim ut purus non, mattis vulputate tortor.</li>\n <li>Five</li>\n <li>Six</li>\n <li>Seven</li>\n <li>Eight</li>\n <li>Nine<br>Items</li>\n <li>Ten<br>Items</li>\n</ol>" }, { "answer_id": 74594327, "author": "Temani Afif", "author_id": 8620333, "author_profile": "https://Stackoverflow.com/users/8620333", "pm_score": -1, "selected": false, "text": "div {\n display:grid;\n grid-template-columns: 3ch auto 3ch; /* 3ch is a kind of max width for your numbers */\n justify-content: center;\n column-gap: 2em\n}\np {\n max-width: 30em;\n} <body>\n<div>\n<p class='line-number'>1</p>\n<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris tellus nisl, sollicitudin ac lorem sit amet, vehicula pretium leo. Curabitur convallis tristique ipsum vel consequat. Maecenas sit amet sem ipsum. Aliquam quis accumsan ante. </p>\n</div>\n<div>\n<p class='line-number'>2</p>\n<p>Maecenas at mauris euismod, placerat justo vel, ultrices diam. Sed mollis sollicitudin risus vel pharetra. Integer bibendum iaculis magna, ac sagittis mauris elementum non. Vestibulum non aliquam mi. Donec sit amet dui bibendum, consectetur lacus quis, interdum sem. </p>\n</div>\n<div>\n<p class='line-number'>3</p>\n<p>Integer vitae massa lectus. Nulla placerat, augue at pellentesque viverra, velit odio dapibus felis, at feugiat arcu magna vel mauris. Aliquam sed luctus urna. Morbi magna orci, dignissim ut purus non, mattis vulputate tortor. </p>\n</div>\n</body>" }, { "answer_id": 74594339, "author": "Skin_phil", "author_id": 13258195, "author_profile": "https://Stackoverflow.com/users/13258195", "pm_score": 0, "selected": false, "text": "div {\n display:grid;\n grid-template-columns: 20px 1fr;\n column-gap: 10px;\n}\n\np {\npadding-right:30px;\n} <body>\n<div>\n<p class='line-number'>1</p>\n<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris tellus nisl, sollicitudin ac lorem sit amet, vehicula pretium leo. Curabitur convallis tristique ipsum vel consequat. Maecenas sit amet sem ipsum. Aliquam quis accumsan ante. </p>\n</div>\n<div>\n<p class='line-number'>2</p>\n<p>Maecenas at mauris euismod, placerat justo vel, ultrices diam. Sed mollis sollicitudin risus vel pharetra. Integer bibendum iaculis magna, ac sagittis mauris elementum non. Vestibulum non aliquam mi. Donec sit amet dui bibendum, consectetur lacus quis, interdum sem. </p>\n</div>\n<div>\n<p class='line-number'>3</p>\n<p>Integer vitae massa lectus. Nulla placerat, augue at pellentesque viverra, velit odio dapibus felis, at feugiat arcu magna vel mauris. Aliquam sed luctus urna. Morbi magna orci, dignissim ut purus non, mattis vulputate tortor. </p>\n</div>\n</body>" }, { "answer_id": 74594369, "author": "G-Cyrillus", "author_id": 2442099, "author_profile": "https://Stackoverflow.com/users/2442099", "pm_score": 2, "selected": true, "text": "body {\n max-width: 30em;\n margin: 0 auto;\n padding: 2em;\n}\n\ndiv {\n display: grid;\n grid-template-columns: 0 1fr;\n}\n\n.line-number {\n grid-column-start: 1;\n margin-inline-start: -2em;\n}\n\np {\n grid-column-start: 2\n}\n\n/* does stand in the middle ? */\nbody,\np:not([class]) {\n background: linear-gradient(to left, rgba(0, 0, 0, 0.2) 50%, #0000 50%);\n} <body>\n <div>\n <p class='line-number'>1</p>\n <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris tellus nisl, sollicitudin ac lorem sit amet, vehicula pretium leo. Curabitur convallis tristique ipsum vel consequat. Maecenas sit amet sem ipsum. Aliquam quis accumsan ante. </p>\n </div>\n <div>\n <p class='line-number'>2</p>\n <p>Maecenas at mauris euismod, placerat justo vel, ultrices diam. Sed mollis sollicitudin risus vel pharetra. Integer bibendum iaculis magna, ac sagittis mauris elementum non. Vestibulum non aliquam mi. Donec sit amet dui bibendum, consectetur lacus\n quis, interdum sem. </p>\n </div>\n <div>\n <p class='line-number'>3</p>\n <p>Integer vitae massa lectus. Nulla placerat, augue at pellentesque viverra, velit odio dapibus felis, at feugiat arcu magna vel mauris. Aliquam sed luctus urna. Morbi magna orci, dignissim ut purus non, mattis vulputate tortor. </p>\n </div>\n</body> div {\n max-width: 30em;\n margin: 2em auto;\n padding: 0 2em;\n display: grid;\n}\n\n.line-number {\n margin-inline-start: -2em; /* offset */\n position:absolute; /* off the flow */\n}\n\np {\n margin:0\n}\n\n/* does it stand in the middle ? */\nbody,\ndiv,\np:not([class]) {\n background: linear-gradient(to left, rgba(0, 0, 0, 0.2) 50%, #0000 50%);\n} <body>\n <div>\n <p class='line-number'>1</p>\n <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris tellus nisl, sollicitudin ac lorem sit amet, vehicula pretium leo. Curabitur convallis tristique ipsum vel consequat. Maecenas sit amet sem ipsum. Aliquam quis accumsan ante. </p>\n </div>\n <div>\n <p class='line-number'>2</p>\n <p>Maecenas at mauris euismod, placerat justo vel, ultrices diam. Sed mollis sollicitudin risus vel pharetra. Integer bibendum iaculis magna, ac sagittis mauris elementum non. Vestibulum non aliquam mi. Donec sit amet dui bibendum, consectetur lacus\n quis, interdum sem. </p>\n </div>\n <div>\n <p class='line-number'>3</p>\n <p>Integer vitae massa lectus. Nulla placerat, augue at pellentesque viverra, velit odio dapibus felis, at feugiat arcu magna vel mauris. Aliquam sed luctus urna. Morbi magna orci, dignissim ut purus non, mattis vulputate tortor. </p>\n </div>\n</body> body {\n max-width: 30em;\n margin: 0 auto;\n padding: 2em;\n counter-reset: ps;\n}\n\np:before {\n counter-increment: ps;\n content: counter(ps);\n position: absolute;\n margin-inline-start: -2em;\n}\n\n\n/* does it stand in the middle ? */\n\nbody,\np {\n background: linear-gradient(to left, rgba(0, 0, 0, 0.2) 50%, #0000 50%);\n} <body>\n <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris tellus nisl, sollicitudin ac lorem sit amet, vehicula pretium leo. Curabitur convallis tristique ipsum vel consequat. Maecenas sit amet sem ipsum. Aliquam quis accumsan ante. </p>\n <p>Maecenas at mauris euismod, placerat justo vel, ultrices diam. Sed mollis sollicitudin risus vel pharetra. Integer bibendum iaculis magna, ac sagittis mauris elementum non. Vestibulum non aliquam mi. Donec sit amet dui bibendum, consectetur lacus quis,\n interdum sem. </p>\n <p>Integer vitae massa lectus. Nulla placerat, augue at pellentesque viverra, velit odio dapibus felis, at feugiat arcu magna vel mauris. Aliquam sed luctus urna. Morbi magna orci, dignissim ut purus non, mattis vulputate tortor. </p>\n</body>" }, { "answer_id": 74594383, "author": "OliverRadini", "author_id": 5011469, "author_profile": "https://Stackoverflow.com/users/5011469", "pm_score": 1, "selected": false, "text": ".wrapper {\n counter-reset: my-awesome-counter;\n max-width: 30em;\n margin: 0 auto;\n padding: 2em;\n}\np {\n counter-increment: my-awesome-counter;\n position: relative;\n}\np:before {\n content: counter(my-awesome-counter);\n position: absolute;\n left: -15px;\n} <div class=\"wrapper\">\n<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris tellus nisl, sollicitudin ac lorem sit amet, vehicula pretium leo. Curabitur convallis tristique ipsum vel consequat. Maecenas sit amet sem ipsum. Aliquam quis accumsan ante. </p>\n<p>Maecenas at mauris euismod, placerat justo vel, ultrices diam. Sed mollis sollicitudin risus vel pharetra. Integer bibendum iaculis magna, ac sagittis mauris elementum non. Vestibulum non aliquam mi. Donec sit amet dui bibendum, consectetur lacus quis, interdum sem. </p>\n<p>Integer vitae massa lectus. Nulla placerat, augue at pellentesque viverra, velit odio dapibus felis, at feugiat arcu magna vel mauris. Aliquam sed luctus urna. Morbi magna orci, dignissim ut purus non, mattis vulputate tortor. </p>\n</div>" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74594081", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14250675/" ]
74,594,097
<pre><code>import java.lang.Math; public class Einleitung { public static void main(String[] args) { double c = 1/8; double e = Math.round(c*100)/100.0; System.out.println(e); } } </code></pre> <p>The output returns a double, whoose decimal places got cut off after the first comma.</p>
[ { "answer_id": 74594158, "author": "AterLux", "author_id": 4931630, "author_profile": "https://Stackoverflow.com/users/4931630", "pm_score": -1, "selected": false, "text": " double c = 1/8;\n c double c = 1.0/8; double" }, { "answer_id": 74594431, "author": "rzwitserloot", "author_id": 768644, "author_profile": "https://Stackoverflow.com/users/768644", "pm_score": 0, "selected": false, "text": "1/8 a/b a b short byte int char long 1.0/8 double double d = 0.0;\nfor (int i = 0; i < 10; i++) d += 0.1;\nSystem.out.println(d);\n 0.9999999999999999 double d = 0.0;\nfor (int i = 0; i < 10; i++) d += 0.1;\nSystem.out.printf(\"%.2f\\n\", d);\nSystem.out.printf(\"%.2f\\n\", 1.0/8.0);\n\n %.2f BigDecimal" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74594097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20617842/" ]
74,594,131
<p>I want to check the Kubernetes configuration - how many nodes, etc. I tried the following command.</p> <pre><code>kubectl describe cluster error: the server doesn't have a resource type &quot;cluster&quot; </code></pre> <p>BTW, I tried to use the following command to check the AZ of the nodes of the pods. But it returns <code>&lt;none&gt;</code> for all the pods' nodes.</p> <pre><code>kubectl get pods -o=custom-columns=NAME:.metadata.name,ZONE:.metadata.labels.'topology\.Kubernetes\.io/zone' </code></pre> <p>How to use <code>kubectl</code> to find the AZs of the pods?</p>
[ { "answer_id": 74594269, "author": "Danny88", "author_id": 20566549, "author_profile": "https://Stackoverflow.com/users/20566549", "pm_score": -1, "selected": false, "text": "kubectl cluster-info\n" }, { "answer_id": 74597475, "author": "Blender Fox", "author_id": 2017590, "author_profile": "https://Stackoverflow.com/users/2017590", "pm_score": 2, "selected": false, "text": "kubectl get nodes kubectl describe node {node-name} kubectl get nodes jsonpath jq" }, { "answer_id": 74603567, "author": "P....", "author_id": 6309601, "author_profile": "https://Stackoverflow.com/users/6309601", "pm_score": 2, "selected": true, "text": "kubectl get node -Ltopology.kubernetes.io/zone\nNAME STATUS ROLES AGE VERSION ZONE\ndevelopment-kube-controller-1 Ready control-plane 48d v1.24.6 zone\ndevelopment-kube-worker-1 Ready <none> 48d v1.24.6 zone-A\ndevelopment-kube-worker-2 Ready <none> 48d v1.24.6 zone-B\n awk topology.kubernetes.io/zone k topology\\.kubernetes\\.io/zone K kubectl describe node |awk '/topology.kubernetes.io\\/zone/{zone=$1;next} /^ Namespace/{flag=1; getline; next} /^Allocated resources:/{flag=0} flag{print $2, zone}' |column -t\ncalico-node-swz7j topology.kubernetes.io/zone=zone\ncoredns-74d6c5659f-4mpcp topology.kubernetes.io/zone=zone\ndns-autoscaler-59b8867c86-w4dls topology.kubernetes.io/zone=zone \nkubernetes-dashboard-648989c4b4-b4k7h topology.kubernetes.io/zone=zone-A\nkubernetes-metrics-scraper-84bbbc8b75-x72pf topology.kubernetes.io/zone=zone-A\nnginx-proxy-development-kube-worker-1 topology.kubernetes.io/zone=zone-A\nnodelocaldns-xt6hr topology.kubernetes.io/zone=zone-A\nmetallb-controller-94c85f6db-6j8j5 topology.kubernetes.io/zone=zone-A\nmetallb-speaker-4fz99 topology.kubernetes.io/zone=zone-A\nargocd-application-controller-0 topology.kubernetes.io/zone=zone-B\nargocd-applicationset-controller-5bff759d68-kk7tx topology.kubernetes.io/zone=zone-B\nargocd-dex-server-59c59b5d96-7z7th topology.kubernetes.io/zone=zone-B\nargocd-notifications-controller-6df97c8577-26z9m topology.kubernetes.io/zone=zone-B\nargocd-redis-684fb8c6dd-bxb25 topology.kubernetes.io/zone=zone-B\nargocd-repo-server-79d8c5f7b4-fnh7g topology.kubernetes.io/zone=zone-B\n $1 awk" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74594131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/825920/" ]
74,594,144
<p>I want to check if values from column B exist in column A, and if yes and equal with the value in that row, create another column D, getting the value from column C (for the A on that row).</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>A</th> <th>B</th> <th>C</th> <th>D</th> </tr> </thead> <tbody> <tr> <td>a</td> <td>f</td> <td>12</td> <td>55</td> </tr> <tr> <td>b</td> <td>a</td> <td>23</td> <td>12</td> </tr> <tr> <td>c</td> <td>b</td> <td>33</td> <td>23</td> </tr> <tr> <td>d</td> <td>c</td> <td>1</td> <td>33</td> </tr> <tr> <td>e</td> <td>e</td> <td>11</td> <td>11</td> </tr> <tr> <td>f</td> <td>d</td> <td>55</td> <td>1</td> </tr> </tbody> </table> </div> <p>This is what I have, but it's not working as it should as it is setting the value of D by just checking if the value exists in column A and not comparing them.</p> <pre><code> ifelse(df$B %in% df$A, df$C , NA) </code></pre>
[ { "answer_id": 74594156, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 2, "selected": false, "text": "match NA NA df1$D <- with(df1, C[match(B, A)])\n > df1\n A B C D\n1 a f 12 55\n2 b a 23 12\n3 c b 33 23\n4 d c 1 33\n5 e e 11 11\n6 f d 55 1\n df1 <- structure(list(A = c(\"a\", \"b\", \"c\", \"d\", \"e\", \"f\"), B = c(\"f\", \n\"a\", \"b\", \"c\", \"e\", \"d\"), C = c(12L, 23L, 33L, 1L, 11L, 55L), \n D = c(55L, 12L, 23L, 33L, 11L, 1L)), class = \"data.frame\", row.names = c(NA, \n-6L))\n" }, { "answer_id": 74594226, "author": "onyambu", "author_id": 8380272, "author_profile": "https://Stackoverflow.com/users/8380272", "pm_score": 2, "selected": true, "text": "transform(df1, D = setNames(C,A)[B])\n\n A B C D\n1 a f 12 55\n2 b a 23 12\n3 c b 33 23\n4 d c 1 33\n5 e e 11 11\n6 f d 55 1\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74594144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19559385/" ]
74,594,151
<p>I'm trying to implement a wrapper class for another class that has a private <code>std::tuple</code> member and enable structured bindings on the wrapper class. Here's the class with the private tuple:</p> <pre class="lang-cpp prettyprint-override"><code>class widget { friend class wrap; std::tuple&lt;int, double&gt; m_tuple {1, 1.0}; }; </code></pre> <p>Here's my attempt at the wrapper class after reading about how to enable structured bindings for custom types (e.g., <a href="https://devblogs.microsoft.com/oldnewthing/20201015-00/?p=104369" rel="nofollow noreferrer">this post on devblogs.microsoft.com</a>):</p> <pre class="lang-cpp prettyprint-override"><code>class wrap { public: wrap(widget&amp; f) : m_tuple(f.m_tuple) {} // auto some_other_function(); template&lt;std::size_t Index&gt; auto get() &amp; -&gt; std::tuple_element_t&lt;Index, wrap&gt;&amp; { return std::get&lt;Index&gt;(m_tuple); } template&lt;std::size_t Index&gt; auto get() &amp;&amp; -&gt; std::tuple_element_t&lt;Index, wrap&gt;&amp; { return std::get&lt;Index&gt;(m_tuple); } template&lt;std::size_t Index&gt; auto get() const&amp; -&gt; const std::tuple_element_t&lt;Index, wrap&gt;&amp; { return std::get&lt;Index&gt;(m_tuple); } template&lt;std::size_t Index&gt; auto get() const&amp;&amp; -&gt; const std::tuple_element_t&lt;Index, wrap&gt;&amp; { return std::get&lt;Index&gt;(m_tuple); } private: std::tuple&lt;int, double&gt;&amp; m_tuple; }; </code></pre> <p>Here are the specialized <code>std::tuple_size</code> and <code>std::tuple_element</code> for <code>wrap</code>:</p> <pre class="lang-cpp prettyprint-override"><code>namespace std { template&lt;&gt; struct tuple_size&lt;wrap&gt; : tuple_size&lt;std::tuple&lt;int, double&gt;&gt; {}; template&lt;size_t Index&gt; struct tuple_element&lt;Index, wrap&gt; : tuple_element&lt;Index, tuple&lt;int, double&gt;&gt; {}; } // namespace std </code></pre> <p>I'd like the following behavior:</p> <pre class="lang-cpp prettyprint-override"><code>int main() { widget w; auto [i_copy, d_copy] = wrap(w); i_copy = 2; // Does not change w.m_tuple because i_copy is a copy of std::get&lt;0&gt;(w.m_tuple). d_copy = 2.0; // Does not change w.m_tuple because d_copy is a copy of std::get&lt;1&gt;(w.m_tuple). // w.m_tuple still holds {1, 1.0}. auto&amp; [i_ref, d_ref] = wrap(w); i_ref = 2; // Changes w.m_tuple because i_ref is a reference to std::get&lt;0&gt;(w.m_tuple). d_ref = 2.0; // Changes w.m_tuple because d_ref is a reference to std::get&lt;1&gt;(w.m_tuple). // w.m_tuple now holds {2, 2.0}. } </code></pre> <p>But this doesn't even compile (tested with gcc 12.2.0 and clang 14.0.6). The error I get is</p> <pre><code>error: cannot bind non-const lvalue reference of type ‘wrap&amp;’ to an rvalue of type ‘wrap’ | auto&amp; [i_ref, d_ref] = wrap(w); </code></pre> <p>Does the <code>non-const lvalue reference of type ‘wrap&amp;’</code> refer to <code>auto&amp; [i_ref, d_ref]</code> and the <code>rvalue of type ‘wrap’</code> to <code>wrap(w)</code>? Why are <code>i_ref</code> and <code>d_ref</code> not references to the integer and double of the tuple in <code>w</code>?</p> <p>Edit: How can I implement a wrapper class that has the desired behavior?</p>
[ { "answer_id": 74594313, "author": "Ryan Haining", "author_id": 1013719, "author_profile": "https://Stackoverflow.com/users/1013719", "pm_score": 3, "selected": true, "text": "auto& [i_ref, d_ref] = wrap(w);\n auto& = wrap& wr = wrap(w);\n auto& auto& [i, d] = std::tuple{1, 1.0};\n prog.cc: In function 'int main()':\nprog.cc:4:25: error: cannot bind non-const lvalue reference of type 'std::tuple<int, double>&' to an rvalue of type 'std::tuple<int, double>'\n 4 | auto& [i, d] = std::tuple{1, 1.0};\n | ^~~~~~~~~~~~~\n const auto& [i_ref, d_ref] = wrap(w);\n i_ref d_ref wrap auto wrapped = wrap(w);\nauto& [i_ref, d_ref] = wrapped;\ni_ref = 2;\nassert(std::get<0>(w.m_tuple) == 2);\n auto&& [i_ref, d_ref] = wrap(w);\ni_ref = 2;\nassert(std::get<0>(w.m_tuple) == 2);\n auto [i_ref, d_ref] = wrap(w);\ni_ref = 2;\nassert(std::get<0>(w.m_tuple) == 2);\n" }, { "answer_id": 74594389, "author": "Chronial", "author_id": 758345, "author_profile": "https://Stackoverflow.com/users/758345", "pm_score": 0, "selected": false, "text": "class widget {\n friend std::tuple<int, double>& wrap(widget&);\n std::tuple<int, double> m_tuple {1, 1.0};\n};\n\nstd::tuple<int, double>& wrap(widget& w) {\n return w.m_tuple;\n}\n\nint main() {\n widget w;\n auto [i_copy, d_copy] = wrap(w);\n auto& [i_ref, d_ref] = wrap(w);\n}\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74594151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6333988/" ]
74,594,164
<p>Created a simple binary search and I noticed that the usage of <code>mid--</code> vs <code>mid -= 1</code> or <code>mid - 1</code> returned different results and essentially caused the function to fail. I was scanning resources online and based on reading other SO posts, my assumption is that the <code>--</code> and <code>++</code> operators are able to change the value of <code>mid</code> for each iteration ... but it seems so nuanced that I'm not really tracking what's going on behind the scenes. Would appreciate some help regarding this.</p> <p>I would think that both <code>mid -= 1</code> and <code>mid--</code> mean take <code>mid</code> and reduce its value by one. Both essentially reassigning the -1 value to the <code>mid</code> variable.</p> <h3>works</h3> <pre class="lang-js prettyprint-override"><code>const sourceArray = [1, 5, 7, 10, 15]; const binarySearch = (array, target) =&gt; { let low = 0; let high = array.length - 1; while (low &lt; high) { let mid = (low + high) / 2; if (array[mid] === target) { return mid; } else if (array[mid] &gt; target) { // if array[mid] &gt; target, set high to mid-- high = mid--; } else { // if array[mid] &lt; target, set low to mid++ low = mid++; } } return []; }; console.log(binarySearch(sourceArray, 7)); console.log(binarySearch(sourceArray, 10)); console.log(binarySearch(sourceArray, 15)); console.log(binarySearch(sourceArray, 20)); // returns // 2 // 3 // 4 // [] </code></pre> <h3>doesnt work</h3> <pre class="lang-js prettyprint-override"><code>const sourceArray = [1, 5, 7, 10, 15]; const binarySearch = (array, target) =&gt; { let low = 0; let high = array.length - 1; while (low &lt; high) { let mid = (low + high) / 2; if (array[mid] === target) { return mid; } else if (array[mid] &gt; target) { // if array[mid] &gt; target, set high to mid-- high = mid -= 1; } else { // if array[mid] &lt; target, set low to mid++ low = mid += 1; } } return []; }; console.log(binarySearch(sourceArray, 7)); console.log(binarySearch(sourceArray, 10)); console.log(binarySearch(sourceArray, 15)); console.log(binarySearch(sourceArray, 20)); // returns // 2 // [] // [] // [] </code></pre>
[ { "answer_id": 74594313, "author": "Ryan Haining", "author_id": 1013719, "author_profile": "https://Stackoverflow.com/users/1013719", "pm_score": 3, "selected": true, "text": "auto& [i_ref, d_ref] = wrap(w);\n auto& = wrap& wr = wrap(w);\n auto& auto& [i, d] = std::tuple{1, 1.0};\n prog.cc: In function 'int main()':\nprog.cc:4:25: error: cannot bind non-const lvalue reference of type 'std::tuple<int, double>&' to an rvalue of type 'std::tuple<int, double>'\n 4 | auto& [i, d] = std::tuple{1, 1.0};\n | ^~~~~~~~~~~~~\n const auto& [i_ref, d_ref] = wrap(w);\n i_ref d_ref wrap auto wrapped = wrap(w);\nauto& [i_ref, d_ref] = wrapped;\ni_ref = 2;\nassert(std::get<0>(w.m_tuple) == 2);\n auto&& [i_ref, d_ref] = wrap(w);\ni_ref = 2;\nassert(std::get<0>(w.m_tuple) == 2);\n auto [i_ref, d_ref] = wrap(w);\ni_ref = 2;\nassert(std::get<0>(w.m_tuple) == 2);\n" }, { "answer_id": 74594389, "author": "Chronial", "author_id": 758345, "author_profile": "https://Stackoverflow.com/users/758345", "pm_score": 0, "selected": false, "text": "class widget {\n friend std::tuple<int, double>& wrap(widget&);\n std::tuple<int, double> m_tuple {1, 1.0};\n};\n\nstd::tuple<int, double>& wrap(widget& w) {\n return w.m_tuple;\n}\n\nint main() {\n widget w;\n auto [i_copy, d_copy] = wrap(w);\n auto& [i_ref, d_ref] = wrap(w);\n}\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74594164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10349152/" ]
74,594,185
<p>I have a dataframe that looks like the below (inclusive of the brackets and quotes):</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>Interests</th> </tr> </thead> <tbody> <tr> <td>2131</td> <td><code>['music','art','travel']</code></td> </tr> <tr> <td>3213</td> <td><code>[]</code></td> </tr> <tr> <td>3132</td> <td><code>['martial arts']</code></td> </tr> <tr> <td>3232</td> <td><code>['martial arts']</code></td> </tr> </tbody> </table> </div> <p>The desired output I am trying to get is:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>Interests</th> </tr> </thead> <tbody> <tr> <td>2131</td> <td>3</td> </tr> <tr> <td>3213</td> <td>0</td> </tr> <tr> <td>3132</td> <td>1</td> </tr> <tr> <td>3232</td> <td>1</td> </tr> </tbody> </table> </div> <p>I've tried using</p> <pre><code>from collections import Counter ravel = np.ravel(user.personal_interests.to_list()) </code></pre> <p>But that just gives me the count of each combination i.e.: ['martial arts']:2</p> <p>I've also tried stripping the quotes and using a series to count, but to no avail.</p>
[ { "answer_id": 74594207, "author": "Tron", "author_id": 9917285, "author_profile": "https://Stackoverflow.com/users/9917285", "pm_score": 0, "selected": false, "text": "df['new_interests'] = df['Interests'].apply(lambda x: temp.append(len(x)))\n" }, { "answer_id": 74594257, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "['music','art','travel'] df['Interests'] = df['Interests'].str.len()\n \"['music','art','travel']\" from ast import literal_eval\n\ndf['Interests'] = df['Interests'].apply(literal_eval).str.len()\n df['Interests'] = df['Interests'].str.count(',').add(df['Interests'].ne('[]'))\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74594185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20616895/" ]
74,594,203
<p>I have a <code>Container</code> whitch needs to include two <code>TextField</code> where i can insert a product name and description. It is supposed to appear, and take its place, when a <code>FloatingActionButton</code> is pressed. This is actually working till I insert the <code>TextField</code> and I can't understand why.</p> <p>This is the <code>Cointainer</code> code i wrote:</p> <pre><code>Padding( padding: const EdgeInsets.only(top: 4, bottom: 12), child: Container( width: 400, height: 125, decoration: BoxDecoration( color: Color(0xFF00ABB3), borderRadius: BorderRadius.all(Radius.circular(widgetsRadius)) ), child: Padding( padding: const EdgeInsets.symmetric(vertical: 5, horizontal: 20), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.center, children: [ Padding( padding: const EdgeInsets.symmetric(vertical: 25), child: Column( mainAxisAlignment: MainAxisAlignment.spaceAround, crossAxisAlignment: CrossAxisAlignment.start, children: const [ TextField( decoration: InputDecoration( hintText: &quot;Name&quot; ), ), TextField( decoration: InputDecoration( hintText: &quot;Description&quot; ), ) ], ), ), GestureDetector( onTap: () { setState(() { isButtonVisible = !isButtonVisible; }); }, child: Icon(Icons.arrow_circle_right, color: Colors.white,) ) ], ), ), ), ); </code></pre> <p>This is the result without the two <code>TextField</code>:</p> <p><a href="https://i.stack.imgur.com/xneDK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xneDK.png" alt="https://i.stack.imgur.com/PxWNp.png" /></a></p> <p>This is the result with the two <code>TextField</code>:</p> <p><a href="https://i.stack.imgur.com/Trp8H.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Trp8H.png" alt="https://i.stack.imgur.com/ttEY3.png" /></a></p> <p>The part of code where I'm actually using <code>isButtonVisible</code> (as requested from @Canada2000):</p> <pre><code>Scaffold( body: Padding( padding: const EdgeInsets.only(left: 28, right: 28, top: 35, bottom: 10), child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ AnimatedCrossFade( duration: const Duration(milliseconds: 150), sizeCurve: Curves.easeOutCirc, firstChild: _addProductButton(), secondChild: _emptyProductContainer(), crossFadeState: isButtonVisible ? CrossFadeState.showFirst : CrossFadeState.showSecond, ), ], ), ), ); </code></pre>
[ { "answer_id": 74594207, "author": "Tron", "author_id": 9917285, "author_profile": "https://Stackoverflow.com/users/9917285", "pm_score": 0, "selected": false, "text": "df['new_interests'] = df['Interests'].apply(lambda x: temp.append(len(x)))\n" }, { "answer_id": 74594257, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "['music','art','travel'] df['Interests'] = df['Interests'].str.len()\n \"['music','art','travel']\" from ast import literal_eval\n\ndf['Interests'] = df['Interests'].apply(literal_eval).str.len()\n df['Interests'] = df['Interests'].str.count(',').add(df['Interests'].ne('[]'))\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74594203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19450321/" ]
74,594,221
<p>I'm working with a dynamic reactive form that takes a json input and builds out a form. I also wrote a custom date validator to check if a date is older than another given date (the date is passed in to the validator) .. and returns an error when the input date by the user is older than the given date. Because of the way the form is built... I'm adding or removing the validator based on a user's prior selection while going through the form (to make the form valid).</p> <p>This is the code block of me adding the form control and the validator.</p> <p>`</p> <pre><code>var newdate = new Date(); this.dynamicForm.addControl(control.name, this.formBuilder.control(control.value, this.beforeDateValidator(newdate))); </code></pre> <p>`</p> <p>And this is what the validator looks like...</p> <p>`</p> <pre><code> beforeDateValidator(dateValue: Date): ValidatorFn { console.log('im firing'); return(control: AbstractControl) : ValidationErrors | null =&gt; { const value: Date = control.value; // console.log(value); if(!value) { return null; } if (dateValue=== null) { return null; } if (value &lt; dateValue) { return { beforeDateValidator: 'Invalid Date' } } else { return null; } } } </code></pre> <p>`</p> <p>The issue is... the validator doesn't fire when the user selects the right values and inputs the date value that's supposed to trigger the invalid date message.</p>
[ { "answer_id": 74594207, "author": "Tron", "author_id": 9917285, "author_profile": "https://Stackoverflow.com/users/9917285", "pm_score": 0, "selected": false, "text": "df['new_interests'] = df['Interests'].apply(lambda x: temp.append(len(x)))\n" }, { "answer_id": 74594257, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "['music','art','travel'] df['Interests'] = df['Interests'].str.len()\n \"['music','art','travel']\" from ast import literal_eval\n\ndf['Interests'] = df['Interests'].apply(literal_eval).str.len()\n df['Interests'] = df['Interests'].str.count(',').add(df['Interests'].ne('[]'))\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74594221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5670640/" ]
74,594,222
<p>Have '<strong>TextInputArea</strong>' widget, and want to keep this widget remain on screen (upper part of screen) all the time,</p> <p>Lower part of screen need to be changed as per <strong>BottomNavigationBar</strong> (it has three pages XX,YY,ZZ) is clicked</p> <p>But '<strong>TextInputArea</strong>' is not getting loaded on screen.</p> <p>Tried something like this</p> <pre><code>Widget build(BuildContext context) { returnScaffold( appBar: AppBarWidget(), body: TextInputArea(), bottomNavigationBar: Location(), floatingActionButton: TextFloatingButtonSpeedDial(), ), } </code></pre> <p>Location.dart</p> <pre><code>class Location extends StatefulWidget { @override State&lt;Location&gt; createState() =&gt; _LocationState(); } class _LocationState extends State&lt;Location&gt; { final List&lt;Map&lt;String, Object&gt;&gt; _pages = [ { 'page': India(), 'title': 'india', }, { 'page': Universe(targetArea: Galaxy.milkyway), 'title': 'milkyway', }, { 'page': Universe(targetArea: Galaxy.other),, 'title': 'other', }, ]; int _selectedPageIndex = 0; void _selectPage(int index) { setState(() { _selectedPageIndex = index; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(_pages[_selectedPageIndex]['title'] as String), ), body: _pages[_selectedPageIndex]['page'] as Widget, bottomNavigationBar: BottomNavigationBar( backgroundColor: Colors.white, unselectedItemColor: Colors.grey, selectedItemColor: Colors.blue, currentIndex: _selectedPageIndex, items: [ BottomNavigationBarItem( backgroundColor: Colors.lightBlue, icon: Icon(Icons.abc), label: 'ZZ', ), BottomNavigationBarItem( backgroundColor: Colors.lightBlue, icon: Icon(Icons.water_drop_outlined), label: 'YY', ), BottomNavigationBarItem( backgroundColor: Colors.lightBlue, icon: Icon(Icons.filter_list_alt), label: 'XX', ), ], onTap: _selectPage, ), ); } } </code></pre>
[ { "answer_id": 74594207, "author": "Tron", "author_id": 9917285, "author_profile": "https://Stackoverflow.com/users/9917285", "pm_score": 0, "selected": false, "text": "df['new_interests'] = df['Interests'].apply(lambda x: temp.append(len(x)))\n" }, { "answer_id": 74594257, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "['music','art','travel'] df['Interests'] = df['Interests'].str.len()\n \"['music','art','travel']\" from ast import literal_eval\n\ndf['Interests'] = df['Interests'].apply(literal_eval).str.len()\n df['Interests'] = df['Interests'].str.count(',').add(df['Interests'].ne('[]'))\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74594222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3290584/" ]
74,594,235
<p>I want add PHP-code as text in laravel blade. (Something like adding code in stackoverflow)</p> <p>in blade file I have:</p> <pre><code>{!! nl2br($article-&gt;body_ru) !!} </code></pre> <p>in $article-&gt;body_ru I'm add</p> <pre><code>huijlhgfyuhukik rfthkgjb ftygyjh &lt;code&gt; &lt;?php namespace App\Services; use Illuminate\Support\Facades\App; use Illuminate\Support\Collection; use stdClass; class WeatherService { } &lt;/code&gt; </code></pre> <p>And I'm want to see something like this in body:</p> <p>huijlhgfyuhukik rfthkgjb ftygyjh</p> <pre><code>&lt;?php namespace App\Services; use Illuminate\Support\Facades\App; use Illuminate\Support\Collection; use stdClass; class WeatherService { } </code></pre>
[ { "answer_id": 74594207, "author": "Tron", "author_id": 9917285, "author_profile": "https://Stackoverflow.com/users/9917285", "pm_score": 0, "selected": false, "text": "df['new_interests'] = df['Interests'].apply(lambda x: temp.append(len(x)))\n" }, { "answer_id": 74594257, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "['music','art','travel'] df['Interests'] = df['Interests'].str.len()\n \"['music','art','travel']\" from ast import literal_eval\n\ndf['Interests'] = df['Interests'].apply(literal_eval).str.len()\n df['Interests'] = df['Interests'].str.count(',').add(df['Interests'].ne('[]'))\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74594235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14841215/" ]
74,594,291
<p>I have a data frame loaded in R and I need to sum one row. The problem is that I've tried to use rowSums() function, but 2 columns are not numeric ones (one is character &quot;Nazwa&quot; and one is boolean &quot;X&quot; at the end of data frame). Is there any option to sum this row without those two columns? So I'd like to start from row 1, column 3 and don't include last column.</p> <p>My data:</p> <pre><code>structure(list(Kod = c(0L, 200000L, 400000L, 600000L, 800000L, 1000000L), Nazwa = c(&quot;POLSKA&quot;, &quot;DOLNOŚLĄSKIE&quot;, &quot;KUJAWSKO-POMORSKIE&quot;, &quot;LUBELSKIE&quot;, &quot;LUBUSKIE&quot;, &quot;ŁÓDZKIE&quot;), gospodarstwa.ogółem.gospodarstwa.2006.... = c(9187L, 481L, 173L, 1072L, 256L, 218L), gospodarstwa.ogółem.gospodarstwa.2007.... = c(11870L, 652L, 217L, 1402L, 361L, 261L), gospodarstwa.ogółem.gospodarstwa.2008.... = c(14896L, 879L, 258L, 1566L, 480L, 314L), gospodarstwa.ogółem.gospodarstwa.2009.... = c(17091L, 1021L, 279L, 1710L, 579L, 366L), gospodarstwa.ogółem.gospodarstwa.2010.... = c(20582L, 1227L, 327L, 1962L, 833L, 420L), gospodarstwa.ogółem.gospodarstwa.2011.... = c(23449L, 1322L, 371L, 2065L, 1081L, 478L), gospodarstwa.ogółem.gospodarstwa.2012.... = c(25944L, 1312L, 390L, 2174L, 1356L, 518L), gospodarstwa.ogółem.gospodarstwa.2013.... = c(26598L, 1189L, 415L, 2129L, 1422L, 528L), gospodarstwa.ogółem.gospodarstwa.2014.... = c(24829L, 1046L, 401L, 1975L, 1370L, 508L), gospodarstwa.ogółem.gospodarstwa.2015.... = c(22277L, 849L, 363L, 1825L, 1202L, 478L), gospodarstwa.ogółem.gospodarstwa.2016.... = c(22435L, 813L, 470L, 1980L, 1148L, 497L), gospodarstwa.ogółem.gospodarstwa.2017.... = c(20257L, 741L, 419L, 1904L, 948L, 477L), gospodarstwa.ogółem.gospodarstwa.2018.... = c(19207L, 713L, 395L, 1948L, 877L, 491L), gospodarstwa.ogółem.powierzchnia.użytków.rolnych.2006..ha. = c(228038L, 19332L, 4846L, 19957L, 12094L, 3378L), gospodarstwa.ogółem.powierzchnia.użytków.rolnych.2007..ha. = c(287529L, 21988L, 5884L, 23934L, 18201L, 3561L), gospodarstwa.ogółem.powierzchnia.użytków.rolnych.2008..ha. = c(314848L, 28467L, 5943L, 26892L, 18207L, 4829L), gospodarstwa.ogółem.powierzchnia.użytków.rolnych.2009..ha. = c(367062L, 26427L, 6826L, 30113L, 22929L, 5270L), gospodarstwa.ogółem.powierzchnia.użytków.rolnych.2010..ha. = c(519069L, 39703L, 7688L, 34855L, 35797L, 7671L), gospodarstwa.ogółem.powierzchnia.użytków.rolnych.2011..ha. = c(605520L, 45547L, 8376L, 34837L, 44259L, 8746L), gospodarstwa.ogółem.powierzchnia.użytków.rolnych.2012..ha. = c(661688L, 44304L, 8813L, 37466L, 52581L, 9908L), gospodarstwa.ogółem.powierzchnia.użytków.rolnych.2013..ha. = c(669970L, 37455L, 11152L, 40819L, 54692L, 10342L), gospodarstwa.ogółem.powierzchnia.użytków.rolnych.2014..ha. = c(657902L, 37005L, 11573L, 38467L, 53300L, 11229L), gospodarstwa.ogółem.powierzchnia.użytków.rolnych.2015..ha. = c(580730L, 31261L, 10645L, 34052L, 46343L, 10158L), gospodarstwa.ogółem.powierzchnia.użytków.rolnych.2016..ha. = c(536579L, 29200L, 9263L, 31343L, 43235L, 9986L), gospodarstwa.ogółem.powierzchnia.użytków.rolnych.2017..ha. = c(494978L, 27542L, 8331L, 29001L, 37923L, 9260L), gospodarstwa.ogółem.powierzchnia.użytków.rolnych.2018..ha. = c(484677L, 27357L, 7655L, 28428L, 37174L, 8905L), X = c(NA, NA, NA, NA, NA, NA)), row.names = c(NA, 6L), class = &quot;data.frame&quot;) </code></pre> <p>My attempt:</p> <pre><code>rowSums(dane_csv[, 3:length(dane_csv$Nazwa=='POLSKA')]) </code></pre>
[ { "answer_id": 74594207, "author": "Tron", "author_id": 9917285, "author_profile": "https://Stackoverflow.com/users/9917285", "pm_score": 0, "selected": false, "text": "df['new_interests'] = df['Interests'].apply(lambda x: temp.append(len(x)))\n" }, { "answer_id": 74594257, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "['music','art','travel'] df['Interests'] = df['Interests'].str.len()\n \"['music','art','travel']\" from ast import literal_eval\n\ndf['Interests'] = df['Interests'].apply(literal_eval).str.len()\n df['Interests'] = df['Interests'].str.count(',').add(df['Interests'].ne('[]'))\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74594291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17427031/" ]
74,594,320
<p>`</p> <pre><code>import os import discord from dotenv import load_dotenv from discord.ext import commands from discord import FFmpegPCMAudio load_dotenv(&quot;.env&quot;) TOKEN = os.getenv(&quot;DISCORD_TOKEN&quot;) client = commands.Bot(command_prefix='$') @client.command() async def unvc(ctx): await ctx.guild.voice_client.disconnect() @client.command() async def vc(ctx): if ctx.author.voice: channel = ctx.author.voice.channel await channel.connect() source = FFmpegPCMAudio('music.mp3') player = voice.play(source) @client.event async def on_ready(): print('{0.user} has connected toDiscord!'.format(client)) return await client.change_presence( activity=discord.Activity(type=discord.ActivityType.playing, name=&quot;anime waifu simulator VR&quot;)) client.run(TOKEN) </code></pre> <p>`</p> <p>I am trying to use commands with my discord bot and it does nothing when I type them. It is still able to delete messages, so it isn't an issue with the connection to Discord.</p>
[ { "answer_id": 74594207, "author": "Tron", "author_id": 9917285, "author_profile": "https://Stackoverflow.com/users/9917285", "pm_score": 0, "selected": false, "text": "df['new_interests'] = df['Interests'].apply(lambda x: temp.append(len(x)))\n" }, { "answer_id": 74594257, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "['music','art','travel'] df['Interests'] = df['Interests'].str.len()\n \"['music','art','travel']\" from ast import literal_eval\n\ndf['Interests'] = df['Interests'].apply(literal_eval).str.len()\n df['Interests'] = df['Interests'].str.count(',').add(df['Interests'].ne('[]'))\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74594320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19568388/" ]
74,594,373
<p>I have a function that accepts a UIColor.</p> <pre><code>func getColor(_ background: UIColor) -&gt; UIColor { switch background { case .white, .systemBrown: return .black case .darkGray: return .lightGray case .black: return .white default: return .label } } </code></pre> <p>and I have UIButton with background color .systemBrown</p> <pre><code>let brownButton: UIButton = { let btn = UIButton() btn.translatesAutoresizingMaskIntoConstraints = false btn.backgroundColor = .systemBrown btn.layer.borderWidth = 1.0 btn.layer.borderColor = UIColor.brown.cgColor return btn }() </code></pre> <p>When i call the function like this:</p> <pre><code>getColor(brownButton.backgroundColor!) </code></pre> <p>It returns .label (default case). But when i use:</p> <pre><code>getColor(.systemBrown) </code></pre> <p>I get the expected result</p>
[ { "answer_id": 74594478, "author": "Duncan C", "author_id": 205185, "author_profile": "https://Stackoverflow.com/users/205185", "pm_score": 0, "selected": false, "text": "extension UIColor {\n func isSimilarToColor(_ otherColor: UIColor) -> Bool {\n var myRed: CGFloat = 0\n var myGreen: CGFloat = 0\n var myBlue: CGFloat = 0\n var myAlpha: CGFloat = 0\n\n var otherRed: CGFloat = 0\n var otherGreen: CGFloat = 0\n var otherBlue: CGFloat = 0\n var otherAlpha: CGFloat = 0\n\n self.getRed(&myRed, green: &myGreen, blue: &myBlue, alpha: &myAlpha)\n otherColor.getRed(&otherRed, green: &otherGreen, blue: &otherBlue, alpha: &otherAlpha)\n let slop: CGFloat = 0.02\n return\n myAlpha == 1.0 && otherAlpha == 1.0 &&\n abs(myRed-otherRed) < slop &&\n abs(myGreen-otherGreen) < slop &&\n abs(myBlue-otherBlue) < slop\n }\n}\n" }, { "answer_id": 74594503, "author": "HangarRash", "author_id": 20287183, "author_profile": "https://Stackoverflow.com/users/20287183", "pm_score": 3, "selected": true, "text": "let color = view.backgroundColor!\nprint(\"Background: \\(color)\")\nprint(\"SystemBrown: \\(UIColor.systemBrown)\")\n systemBrown systemBrown getColors case func getColor(_ background: UIColor, traits: UITraitCollection) -> UIColor {\n switch background {\n case .white, .systemBrown.resolvedColor(with: traits):\n return .black\n case .darkGray:\n return .lightGray\n case .black:\n return .white\n default:\n return .label\n }\n}\n getColors getColor(color.resolvedColor(with: view.traitCollection), traits: view.traitCollection)\n traitCollection getColors backgroundColor getColors UIView" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74594373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16220404/" ]
74,594,381
<p>I am making an app in Android Studio with Kotlin. With the lateinit variable in the ListFragment throws me an error called:</p> <blockquote> <p>kotlin.uninitializedpropertyaccessexception: lateinit property dbhelper has not been initialized.</p> </blockquote> <p>I know that there is a form to check the lateinit with the method (isInitialized).</p> <p>The class carsDBHelper:</p> <pre><code>class CochesDBHelper (context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) { val cars = ArrayList&lt;Cars&gt;() companion object { // If you change the database schema, you must increment the database version. const val DATABASE_VERSION = 1 const val DATABASE_NAME = &quot;cars.db&quot; } </code></pre> <p>ListFragment, the class in which, we call CarsDBHelper:</p> <pre><code>companion object{ lateinit var dbHelper: CarsDBHelper } val list= dbHelper.getAllCars() val recyclerView: RecyclerView = v.findViewById(R.id.recyclerView); recyclerView.layoutManager = LinearLayoutManager(context) val adapter: RecyclerViewAdapter = RecyclerViewAdapter(list, context); recyclerView.adapter = adapter </code></pre> <p>I tried to make a method in CarsDBhelper, and in the ListFragment class, but throws me another error.</p> <pre><code>fun addElement(element: String) { if (!::cars.isInitialized) { cars= MutableList&lt;String&gt;(); } cars.add(element); } </code></pre> <p>And I tried to check under the variable as I saw on another post but it didn't work.</p> <pre><code>lateinit var dbHelper: CochesDBHelper; if (::dbHelper.isInitialized) { //in this line throws this error: Expecting member declaration } </code></pre>
[ { "answer_id": 74595326, "author": "Tenfour04", "author_id": 506796, "author_profile": "https://Stackoverflow.com/users/506796", "pm_score": 2, "selected": true, "text": "lateinit class CochesDBHelper private constructor(\n context: Context\n) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {\n \n companion object {\n const val DATABASE_VERSION = 1\n const val DATABASE_NAME = \"cars.db\"\n\n @Volatile \n private var INSTANCE: CochesDBHelper? = null\n\n fun getInstance(context: Context): CochesDBHelper {\n return INSTANCE ?: synchronized(this) {\n INSTANCE ?: CochesDBHelper(context).also { INSTANCE = it }\n }\n }\n } \n\n //...\n}\n CochesDBHelper.getInstance() // In fragment:\n\nval dbHelper = CochesDBHelper.getInstance(requireContext())\n\nval list = dbHelper.getAllCars()\n//...\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74594381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20347110/" ]
74,594,418
<p>I'm starting to learn about Jetpack Compose. I put together this <a href="https://github.com/4gus71n/TheOneApp" rel="nofollow noreferrer">app</a> where I explore different day-to-day use cases, each of the feature modules within this project is supposed to tackle different scenarios.</p> <p>One of this feature modules – the <code>chatexample</code> feature module, tries to implement a simple <code>ViewPager</code> where each of the pages is a <code>Fragment</code>, the first page &quot;Messages&quot; is supposed to display a paginated <code>RecyclerView</code> wrapped around a <code>SwipeRefreshLayout</code>. Now, the goal is to implement all this using Jetpack Compose. This is the issue I'm having right now:</p> <p><a href="https://i.stack.imgur.com/ZYuFf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZYuFf.png" alt="enter image description here" /></a></p> <p>The <a href="https://github.com/4gus71n/TheOneApp/blob/main/features/chatexample/src/main/java/com/example/chatexample/ui/main/ChatExampleScreen.kt#L68" rel="nofollow noreferrer">PullRefreshIndicator</a> that I'm using to implement the Pull-To-Refresh action works as expected and everything seems pretty straightforward so far, but I cannot figure out why the ProgresBar stays there on top.</p> <p>So far I've tried; Carrying on the <code>Modifier</code> from the parent <code>Scaffold</code> all the way through. Making sure I explicitly set the sizes to fit the max height and width. Add an empty <code>Box</code> in the <a href="https://github.com/4gus71n/TheOneApp/blob/main/features/chatexample/src/main/java/com/example/chatexample/ui/main/ChatExampleScreen.kt#L65" rel="nofollow noreferrer">when</a> statement - but nothing has worked so far, I'm guessing I could just remove the <code>PullRefreshIndicator</code> if I see that the ViewModel isn't supposed to be refreshing, but I don't think that's the right thing to do.</p> <p>To quickly explain the Composables that I'm using here I have:</p> <pre><code>&lt;Surface&gt; &lt;Scaffold&gt; // Set with a topBar &lt;Column&gt; &lt;ScrollableTabRow&gt; &lt;Tab/&gt; // Set for the first &quot;Messages&quot; tab &lt;Tab/&gt; // Set for the second &quot;Dashboard&quot; tab &lt;/ScrollableTabRow&gt; &lt;HorizontalPager&gt; // ChatExampleScreen &lt;Box&gt; // A Box set with the pullRefresh modifier // Depending on the ChatExamleViewModel we might pull different composables here &lt;/PullRefreshIndicator&gt; &lt;/Box&gt; // Another ChatExampleScreen for the second tab &lt;/HorizontalPager&gt; &lt;/Column&gt; &lt;Scaffold&gt; &lt;/Surface&gt; </code></pre> <p>Honestly, I don't get how the <code>PullRefreshIndicator</code> that is in a completely different Composable (<code>ChatExampleScreen</code>) gets to overlap with the <code>ScrollableTabRow</code> that is outside.</p> <p>Hope this makes digesting the UI a bit easier. Any tip, advice, or recommendation is appreciated. Thanks! </p> <p><strong>Edit:</strong> Just to be completely clear, what I'm trying to achieve here is to have a PullRefreshIndicator on each page. Something like this:</p> <p><a href="https://i.stack.imgur.com/Noucb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Noucb.png" alt="enter image description here" /></a></p> <p>On each page, you pull down, see the ProgressBar appear, and when it is done, it goes away, within the same page. Not overlapping with the tabs above.</p>
[ { "answer_id": 74643473, "author": "z.y", "author_id": 19023745, "author_profile": "https://Stackoverflow.com/users/19023745", "pm_score": 2, "selected": false, "text": "PullRefresh Compose/Accompanist Tab/Pager PullRefresh Column(\n modifier = Modifier.padding(it)\n ) {\n\n Box(\n modifier = Modifier\n .fillMaxWidth()\n .height(80.dp)\n .background(Color.Blue)\n )\n\n val pullRefreshState = rememberPullRefreshState(\n refreshing = false,\n onRefresh = { viewModel.fetchMessages() }\n )\n\n Box(\n modifier = Modifier.pullRefresh(pullRefreshState)\n ) {\n\n PullRefreshIndicator(\n modifier = Modifier.align(Alignment.TopCenter),\n refreshing = false,\n state = pullRefreshState,\n )\n }\n }\n PullRefresh Box Column ViewModel PullRefresh ChatExampleScreen PullRefresh @Composable\nfun ChatExampleScreen(\n chatexampleViewModel: ChatExampleViewModel,\n modifier: Modifier = Modifier\n) {\n val chatexampleViewModelState by chatexampleViewModel.state.observeAsState()\n\n Box(\n modifier = modifier\n .fillMaxSize()\n ) {\n\n when (val result = chatexampleViewModelState) {\n is ChatExampleViewModel.State.SuccessfullyLoadedMessages -> {\n ChatExampleScreenSuccessfullyLoadedMessages(\n chatexampleMessages = result.list,\n modifier = modifier,\n )\n }\n is ChatExampleViewModel.State.NoMessagesFetched -> {\n ChatExampleScreenEmptyState(\n modifier = modifier\n )\n }\n is ChatExampleViewModel.State.NoInternetConnectivity -> {\n NoInternetConnectivityScreen(\n modifier = modifier\n )\n }\n else -> {\n // Agus - Do nothing???\n Box(modifier = modifier.fillMaxSize())\n }\n }\n }\n}\n Activity setContent{…} ChatTabsContent PullRefresh @OptIn(ExperimentalMaterialApi::class)\n@Composable\nfun ChatTabsContent(\n modifier : Modifier = Modifier,\n viewModel : ChatExampleViewModel\n) {\n val chatexampleViewModelIsLoadingState by viewModel.isLoading.observeAsState()\n\n val pullRefreshState = rememberPullRefreshState(\n refreshing = chatexampleViewModelIsLoadingState == true,\n onRefresh = { viewModel.fetchMessages() }\n )\n\n Box(\n modifier = modifier\n .pullRefresh(pullRefreshState)\n ) {\n\n Column(\n Modifier\n .fillMaxSize()\n ) {\n val pagerState = rememberPagerState()\n\n ScrollableTabRow(\n selectedTabIndex = pagerState.currentPage,\n indicator = { tabPositions ->\n TabRowDefaults.Indicator(\n modifier = Modifier.tabIndicatorOffset(\n currentTabPosition = tabPositions[pagerState.currentPage],\n )\n )\n }\n ) {\n Tab(\n selected = pagerState.currentPage == 0,\n onClick = { },\n text = {\n Text(\n text = \"Messages\"\n )\n }\n )\n Tab(\n selected = pagerState.currentPage == 1,\n onClick = { },\n text = {\n Text(\n text = \"Dashboard\"\n )\n }\n )\n }\n\n HorizontalPager(\n count = 2,\n state = pagerState,\n modifier = Modifier.fillMaxWidth(),\n ) { page ->\n when (page) {\n 0 -> {\n ChatExampleScreen(\n chatexampleViewModel = viewModel,\n modifier = Modifier.fillMaxSize()\n )\n }\n 1 -> {\n ChatExampleScreen(\n chatexampleViewModel = viewModel,\n modifier = Modifier.fillMaxWidth()\n )\n }\n }\n }\n }\n\n PullRefreshIndicator(\n modifier = Modifier.align(Alignment.TopCenter),\n refreshing = chatexampleViewModelIsLoadingState == true,\n state = pullRefreshState,\n )\n }\n}\n setContent {\n TheOneAppTheme {\n // A surface container using the 'background' color from the theme\n Surface(\n modifier = Modifier.fillMaxSize(),\n color = MaterialTheme.colors.background\n ) {\n Scaffold(\n modifier = Modifier.fillMaxSize(),\n topBar = { TopAppBarSample() }\n ) {\n\n ChatTabsContent(\n modifier = Modifier.padding(it),\n viewModel = viewModel\n )\n }\n }\n }\n }\n <Surface>\n <Scaffold> // Set with a topBar\n <Box>\n <Column>\n <ScrollableTabRow>\n <Tab/> // Set for the first \"Messages\" tab\n <Tab/> // Set for the second \"Dashboard\" tab\n </ScrollableTabRow>\n <HorizontalPager>\n <Box/>\n </HorizontalPager>\n </Column>\n\n // pull refresh is now at the most \"z\" index of the \n // box, overlapping the content (tabs/pager)\n <PullRefreshIndicator/> \n </Box>\n <Scaffold>\n</Surface>\n Box" }, { "answer_id": 74659072, "author": "z.y", "author_id": 19023745, "author_profile": "https://Stackoverflow.com/users/19023745", "pm_score": 3, "selected": true, "text": "Box PullRefresh LiveData StateFlows class PullRefreshActivity: ComponentActivity() {\n\n private val viewModel: MyViewModel by viewModels()\n\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContent {\n MyAppTheme {\n Surface(\n modifier = Modifier.fillMaxSize(),\n color = MaterialTheme.colors.background\n ) {\n Scaffold(\n modifier = Modifier.fillMaxSize(),\n topBar = { TopAppBarSample() }\n ) {\n MyScreen(\n modifier = Modifier.padding(it),\n viewModel = viewModel\n )\n }\n }\n }\n }\n }\n}\n data class MessageItems(\n val message: String = \"\",\n val author: String = \"\"\n)\n\ndata class DashboardBanner(\n val bannerMessage: String = \"\",\n val content: String = \"\"\n)\n class MyViewModel: ViewModel() {\n\n var isLoading by mutableStateOf(false)\n\n private val _messageState = MutableStateFlow(mutableStateListOf<MessageItems>())\n val messageState = _messageState.asStateFlow()\n\n private val _dashboardState = MutableStateFlow(DashboardBanner())\n val dashboardState = _dashboardState.asStateFlow()\n\n fun fetchMessages() {\n\n viewModelScope.launch {\n isLoading = true\n\n delay(2000L)\n\n _messageState.update {\n it.add(\n MessageItems(\n message = \"Hello First Message\",\n author = \"Author 1\"\n ),\n )\n it.add(\n MessageItems(\n message = \"Hello Second Message\",\n author = \"Author 2\"\n )\n )\n\n it\n }\n isLoading = false\n }\n }\n\n fun fetchDashboard() {\n\n viewModelScope.launch {\n isLoading = true\n\n delay(2000L)\n\n _dashboardState.update {\n it.copy(\n bannerMessage = \"Hello World!!\",\n content = \"Welcome to Pull Refresh Content!\"\n )\n }\n isLoading = false\n }\n }\n}\n @Composable\nfun MessageTab(\n myViewModel : MyViewModel\n) {\n val messages by myViewModel.messageState.collectAsState()\n\n LazyColumn(\n modifier = Modifier.fillMaxSize()\n ) {\n items(messages) { item ->\n Column(\n modifier = Modifier\n .fillMaxWidth()\n .border(BorderStroke(Dp.Hairline, Color.DarkGray)),\n horizontalAlignment = Alignment.CenterHorizontally\n ) {\n Text(text = item.message)\n Text(text = item.author)\n }\n }\n }\n}\n\n@Composable\nfun DashboardTab(\n myViewModel: MyViewModel\n) {\n\n val banner by myViewModel.dashboardState.collectAsState()\n\n Box(\n modifier = Modifier\n .fillMaxSize()\n .verticalScroll(rememberScrollState()),\n contentAlignment = Alignment.Center\n ) {\n Column {\n Text(\n text = banner.bannerMessage,\n fontSize = 52.sp\n )\n\n Text(\n text = banner.content,\n fontSize = 16.sp\n )\n }\n }\n}\n PullRefresh Pager/Tab ConstraintLayout Column PullRefresh Tabs HorizontalPager HorizontalPager PullRefresh Tabs @OptIn(ExperimentalMaterialApi::class, ExperimentalPagerApi::class)\n@Composable\nfun MyScreen(\n modifier : Modifier = Modifier,\n viewModel: MyViewModel\n) {\n val refreshing = viewModel.isLoading\n val pagerState = rememberPagerState()\n\n val pullRefreshState = rememberPullRefreshState(\n refreshing = refreshing,\n onRefresh = {\n when (pagerState.currentPage) {\n 0 -> {\n viewModel.fetchMessages()\n }\n 1 -> {\n viewModel.fetchDashboard()\n }\n }\n },\n refreshingOffset = 100.dp // just an arbitrary offset where the refresh will animate\n )\n\n ConstraintLayout(\n modifier = modifier\n .fillMaxSize()\n .pullRefresh(pullRefreshState)\n ) {\n val (pager, pullRefresh, tabs) = createRefs()\n\n HorizontalPager(\n count = 2,\n state = pagerState,\n modifier = Modifier.constrainAs(pager) {\n top.linkTo(tabs.bottom)\n start.linkTo(parent.start)\n end.linkTo(parent.end)\n bottom.linkTo(parent.bottom)\n height = Dimension.fillToConstraints\n }\n ) { page ->\n when (page) {\n 0 -> {\n MessageTab(\n myViewModel = viewModel\n )\n }\n 1 -> {\n DashboardTab(\n myViewModel = viewModel\n )\n }\n }\n }\n\n PullRefreshIndicator(\n modifier = Modifier.constrainAs(pullRefresh) {\n top.linkTo(parent.top)\n start.linkTo(parent.start)\n end.linkTo(parent.end)\n },\n refreshing = refreshing,\n state = pullRefreshState,\n )\n\n ScrollableTabRow(\n modifier = Modifier.constrainAs(tabs) {\n top.linkTo(parent.top)\n start.linkTo(parent.start)\n end.linkTo(parent.end)\n },\n selectedTabIndex = pagerState.currentPage,\n indicator = { tabPositions ->\n TabRowDefaults.Indicator(\n modifier = Modifier.tabIndicatorOffset(\n currentTabPosition = tabPositions[pagerState.currentPage],\n )\n )\n },\n ) {\n Tab(\n selected = pagerState.currentPage == 0,\n onClick = {},\n text = {\n Text(\n text = \"Messages\"\n )\n }\n )\n\n Tab(\n selected = pagerState.currentPage == 1,\n onClick = {},\n text = {\n Text(\n text = \"Dashboard\"\n )\n }\n )\n }\n }\n}\n <Surface>\n <Scaffold>\n <ConstraintLayout>\n\n // top to ScrollableTabRow's bottom\n // start, end, bottom to parent's start, end and bottom\n // 0.dp (view), fillToConstraints (compose)\n <HorizontalPager>\n <PagerScreens/>\n </HorizontalPager>\n\n // top, start, end of parent\n <PullRefreshIndicator/>\n\n // top, start and end of parent\n <ScrollableTabRow>\n <Tab/> // Set for the first \"Messages\" tab\n <Tab/> // Set for the second \"Dashboard\" tab\n </ScrollableTabRow>\n </ConstraintLayout>\n <Scaffold>\n</Surface>\n" }, { "answer_id": 74671456, "author": "4gus71n", "author_id": 1403997, "author_profile": "https://Stackoverflow.com/users/1403997", "pm_score": 2, "selected": false, "text": "Box ConstraintLayout ChatScreenExample PullRefreshIndicator Box vericalScroll() ConstraintLayout" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74594418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1403997/" ]
74,594,492
<p>I am running into an issue building the correct data model for the following JSON response.</p> <pre><code>{ &quot;resources&quot;: [ { &quot;courseid&quot;: 4803, &quot;color&quot;: &quot;Blue&quot;, &quot;teeboxtype&quot;: &quot;Championship&quot;, &quot;slope&quot;: 121, &quot;rating&quot;: 71.4 }, { &quot;courseid&quot;: 4803, &quot;color&quot;: &quot;White&quot;, &quot;teeboxtype&quot;: &quot;Men's&quot;, &quot;slope&quot;: 120, &quot;rating&quot;: 69.6 }, { &quot;courseid&quot;: 4803, &quot;color&quot;: &quot;Red&quot;, &quot;teeboxtype&quot;: &quot;Women's&quot;, &quot;slope&quot;: 118, &quot;rating&quot;: 71.2 } ] } </code></pre> <p>Here is the current model. No matter what I do I can't seem to get the model populated. Here is also my URL session retrieving the data. I am new to Swift and SwiftUI so please be gentle. I am getting data back however I am missing something.</p> <pre><code>import Foundation struct RatingsResources: Codable { let golfcourserating : [GolfCourseRating]? } struct GolfCourseRating: Codable { let id: UUID = UUID() let courseID: Int? let teeColor: String? let teeboxtype: String? let teeslope: Double? let teerating: Double? enum CodingKeysRatings: String, CodingKey { case courseID = &quot;courseid&quot; case teeColor = &quot;color&quot; case teeboxtype case teeslope = &quot;slope&quot; case teerating = &quot;rating&quot; } } func getCoureRating(courseID: String?) { let semaphore = DispatchSemaphore (value: 0) print(&quot;GETTING COURSE TEE RATINGS..........&quot;) let urlString: String = &quot;https://api.golfbert.com/v1/courses/\(courseID ?? &quot;4800&quot;)/teeboxes&quot; print (&quot;API STRING: \(urlString) &quot;) let url = URLComponents(string: urlString)! let request = URLRequest(url: url.url!).signed let task = URLSession.shared.dataTask(with: request) { data, response, error in let decoder = JSONDecoder() guard let data = data else { print(String(describing: error)) semaphore.signal() return } if let response = try? JSONDecoder().decode([RatingsResources].self, from: data) { DispatchQueue.main.async { self.ratingresources = response } return } print(&quot;*******Data String***********&quot;) print(String(data: data, encoding: .utf8)!) print(&quot;***************************&quot;) let ratingsData: RatingsResources = try! decoder.decode(RatingsResources.self, from: data) print(&quot;Resources count \(ratingsData.golfcourserating?.count)&quot;) semaphore.signal() } task.resume() semaphore.wait() } //: END OF GET COURSE SCORECARD </code></pre>
[ { "answer_id": 74643473, "author": "z.y", "author_id": 19023745, "author_profile": "https://Stackoverflow.com/users/19023745", "pm_score": 2, "selected": false, "text": "PullRefresh Compose/Accompanist Tab/Pager PullRefresh Column(\n modifier = Modifier.padding(it)\n ) {\n\n Box(\n modifier = Modifier\n .fillMaxWidth()\n .height(80.dp)\n .background(Color.Blue)\n )\n\n val pullRefreshState = rememberPullRefreshState(\n refreshing = false,\n onRefresh = { viewModel.fetchMessages() }\n )\n\n Box(\n modifier = Modifier.pullRefresh(pullRefreshState)\n ) {\n\n PullRefreshIndicator(\n modifier = Modifier.align(Alignment.TopCenter),\n refreshing = false,\n state = pullRefreshState,\n )\n }\n }\n PullRefresh Box Column ViewModel PullRefresh ChatExampleScreen PullRefresh @Composable\nfun ChatExampleScreen(\n chatexampleViewModel: ChatExampleViewModel,\n modifier: Modifier = Modifier\n) {\n val chatexampleViewModelState by chatexampleViewModel.state.observeAsState()\n\n Box(\n modifier = modifier\n .fillMaxSize()\n ) {\n\n when (val result = chatexampleViewModelState) {\n is ChatExampleViewModel.State.SuccessfullyLoadedMessages -> {\n ChatExampleScreenSuccessfullyLoadedMessages(\n chatexampleMessages = result.list,\n modifier = modifier,\n )\n }\n is ChatExampleViewModel.State.NoMessagesFetched -> {\n ChatExampleScreenEmptyState(\n modifier = modifier\n )\n }\n is ChatExampleViewModel.State.NoInternetConnectivity -> {\n NoInternetConnectivityScreen(\n modifier = modifier\n )\n }\n else -> {\n // Agus - Do nothing???\n Box(modifier = modifier.fillMaxSize())\n }\n }\n }\n}\n Activity setContent{…} ChatTabsContent PullRefresh @OptIn(ExperimentalMaterialApi::class)\n@Composable\nfun ChatTabsContent(\n modifier : Modifier = Modifier,\n viewModel : ChatExampleViewModel\n) {\n val chatexampleViewModelIsLoadingState by viewModel.isLoading.observeAsState()\n\n val pullRefreshState = rememberPullRefreshState(\n refreshing = chatexampleViewModelIsLoadingState == true,\n onRefresh = { viewModel.fetchMessages() }\n )\n\n Box(\n modifier = modifier\n .pullRefresh(pullRefreshState)\n ) {\n\n Column(\n Modifier\n .fillMaxSize()\n ) {\n val pagerState = rememberPagerState()\n\n ScrollableTabRow(\n selectedTabIndex = pagerState.currentPage,\n indicator = { tabPositions ->\n TabRowDefaults.Indicator(\n modifier = Modifier.tabIndicatorOffset(\n currentTabPosition = tabPositions[pagerState.currentPage],\n )\n )\n }\n ) {\n Tab(\n selected = pagerState.currentPage == 0,\n onClick = { },\n text = {\n Text(\n text = \"Messages\"\n )\n }\n )\n Tab(\n selected = pagerState.currentPage == 1,\n onClick = { },\n text = {\n Text(\n text = \"Dashboard\"\n )\n }\n )\n }\n\n HorizontalPager(\n count = 2,\n state = pagerState,\n modifier = Modifier.fillMaxWidth(),\n ) { page ->\n when (page) {\n 0 -> {\n ChatExampleScreen(\n chatexampleViewModel = viewModel,\n modifier = Modifier.fillMaxSize()\n )\n }\n 1 -> {\n ChatExampleScreen(\n chatexampleViewModel = viewModel,\n modifier = Modifier.fillMaxWidth()\n )\n }\n }\n }\n }\n\n PullRefreshIndicator(\n modifier = Modifier.align(Alignment.TopCenter),\n refreshing = chatexampleViewModelIsLoadingState == true,\n state = pullRefreshState,\n )\n }\n}\n setContent {\n TheOneAppTheme {\n // A surface container using the 'background' color from the theme\n Surface(\n modifier = Modifier.fillMaxSize(),\n color = MaterialTheme.colors.background\n ) {\n Scaffold(\n modifier = Modifier.fillMaxSize(),\n topBar = { TopAppBarSample() }\n ) {\n\n ChatTabsContent(\n modifier = Modifier.padding(it),\n viewModel = viewModel\n )\n }\n }\n }\n }\n <Surface>\n <Scaffold> // Set with a topBar\n <Box>\n <Column>\n <ScrollableTabRow>\n <Tab/> // Set for the first \"Messages\" tab\n <Tab/> // Set for the second \"Dashboard\" tab\n </ScrollableTabRow>\n <HorizontalPager>\n <Box/>\n </HorizontalPager>\n </Column>\n\n // pull refresh is now at the most \"z\" index of the \n // box, overlapping the content (tabs/pager)\n <PullRefreshIndicator/> \n </Box>\n <Scaffold>\n</Surface>\n Box" }, { "answer_id": 74659072, "author": "z.y", "author_id": 19023745, "author_profile": "https://Stackoverflow.com/users/19023745", "pm_score": 3, "selected": true, "text": "Box PullRefresh LiveData StateFlows class PullRefreshActivity: ComponentActivity() {\n\n private val viewModel: MyViewModel by viewModels()\n\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContent {\n MyAppTheme {\n Surface(\n modifier = Modifier.fillMaxSize(),\n color = MaterialTheme.colors.background\n ) {\n Scaffold(\n modifier = Modifier.fillMaxSize(),\n topBar = { TopAppBarSample() }\n ) {\n MyScreen(\n modifier = Modifier.padding(it),\n viewModel = viewModel\n )\n }\n }\n }\n }\n }\n}\n data class MessageItems(\n val message: String = \"\",\n val author: String = \"\"\n)\n\ndata class DashboardBanner(\n val bannerMessage: String = \"\",\n val content: String = \"\"\n)\n class MyViewModel: ViewModel() {\n\n var isLoading by mutableStateOf(false)\n\n private val _messageState = MutableStateFlow(mutableStateListOf<MessageItems>())\n val messageState = _messageState.asStateFlow()\n\n private val _dashboardState = MutableStateFlow(DashboardBanner())\n val dashboardState = _dashboardState.asStateFlow()\n\n fun fetchMessages() {\n\n viewModelScope.launch {\n isLoading = true\n\n delay(2000L)\n\n _messageState.update {\n it.add(\n MessageItems(\n message = \"Hello First Message\",\n author = \"Author 1\"\n ),\n )\n it.add(\n MessageItems(\n message = \"Hello Second Message\",\n author = \"Author 2\"\n )\n )\n\n it\n }\n isLoading = false\n }\n }\n\n fun fetchDashboard() {\n\n viewModelScope.launch {\n isLoading = true\n\n delay(2000L)\n\n _dashboardState.update {\n it.copy(\n bannerMessage = \"Hello World!!\",\n content = \"Welcome to Pull Refresh Content!\"\n )\n }\n isLoading = false\n }\n }\n}\n @Composable\nfun MessageTab(\n myViewModel : MyViewModel\n) {\n val messages by myViewModel.messageState.collectAsState()\n\n LazyColumn(\n modifier = Modifier.fillMaxSize()\n ) {\n items(messages) { item ->\n Column(\n modifier = Modifier\n .fillMaxWidth()\n .border(BorderStroke(Dp.Hairline, Color.DarkGray)),\n horizontalAlignment = Alignment.CenterHorizontally\n ) {\n Text(text = item.message)\n Text(text = item.author)\n }\n }\n }\n}\n\n@Composable\nfun DashboardTab(\n myViewModel: MyViewModel\n) {\n\n val banner by myViewModel.dashboardState.collectAsState()\n\n Box(\n modifier = Modifier\n .fillMaxSize()\n .verticalScroll(rememberScrollState()),\n contentAlignment = Alignment.Center\n ) {\n Column {\n Text(\n text = banner.bannerMessage,\n fontSize = 52.sp\n )\n\n Text(\n text = banner.content,\n fontSize = 16.sp\n )\n }\n }\n}\n PullRefresh Pager/Tab ConstraintLayout Column PullRefresh Tabs HorizontalPager HorizontalPager PullRefresh Tabs @OptIn(ExperimentalMaterialApi::class, ExperimentalPagerApi::class)\n@Composable\nfun MyScreen(\n modifier : Modifier = Modifier,\n viewModel: MyViewModel\n) {\n val refreshing = viewModel.isLoading\n val pagerState = rememberPagerState()\n\n val pullRefreshState = rememberPullRefreshState(\n refreshing = refreshing,\n onRefresh = {\n when (pagerState.currentPage) {\n 0 -> {\n viewModel.fetchMessages()\n }\n 1 -> {\n viewModel.fetchDashboard()\n }\n }\n },\n refreshingOffset = 100.dp // just an arbitrary offset where the refresh will animate\n )\n\n ConstraintLayout(\n modifier = modifier\n .fillMaxSize()\n .pullRefresh(pullRefreshState)\n ) {\n val (pager, pullRefresh, tabs) = createRefs()\n\n HorizontalPager(\n count = 2,\n state = pagerState,\n modifier = Modifier.constrainAs(pager) {\n top.linkTo(tabs.bottom)\n start.linkTo(parent.start)\n end.linkTo(parent.end)\n bottom.linkTo(parent.bottom)\n height = Dimension.fillToConstraints\n }\n ) { page ->\n when (page) {\n 0 -> {\n MessageTab(\n myViewModel = viewModel\n )\n }\n 1 -> {\n DashboardTab(\n myViewModel = viewModel\n )\n }\n }\n }\n\n PullRefreshIndicator(\n modifier = Modifier.constrainAs(pullRefresh) {\n top.linkTo(parent.top)\n start.linkTo(parent.start)\n end.linkTo(parent.end)\n },\n refreshing = refreshing,\n state = pullRefreshState,\n )\n\n ScrollableTabRow(\n modifier = Modifier.constrainAs(tabs) {\n top.linkTo(parent.top)\n start.linkTo(parent.start)\n end.linkTo(parent.end)\n },\n selectedTabIndex = pagerState.currentPage,\n indicator = { tabPositions ->\n TabRowDefaults.Indicator(\n modifier = Modifier.tabIndicatorOffset(\n currentTabPosition = tabPositions[pagerState.currentPage],\n )\n )\n },\n ) {\n Tab(\n selected = pagerState.currentPage == 0,\n onClick = {},\n text = {\n Text(\n text = \"Messages\"\n )\n }\n )\n\n Tab(\n selected = pagerState.currentPage == 1,\n onClick = {},\n text = {\n Text(\n text = \"Dashboard\"\n )\n }\n )\n }\n }\n}\n <Surface>\n <Scaffold>\n <ConstraintLayout>\n\n // top to ScrollableTabRow's bottom\n // start, end, bottom to parent's start, end and bottom\n // 0.dp (view), fillToConstraints (compose)\n <HorizontalPager>\n <PagerScreens/>\n </HorizontalPager>\n\n // top, start, end of parent\n <PullRefreshIndicator/>\n\n // top, start and end of parent\n <ScrollableTabRow>\n <Tab/> // Set for the first \"Messages\" tab\n <Tab/> // Set for the second \"Dashboard\" tab\n </ScrollableTabRow>\n </ConstraintLayout>\n <Scaffold>\n</Surface>\n" }, { "answer_id": 74671456, "author": "4gus71n", "author_id": 1403997, "author_profile": "https://Stackoverflow.com/users/1403997", "pm_score": 2, "selected": false, "text": "Box ConstraintLayout ChatScreenExample PullRefreshIndicator Box vericalScroll() ConstraintLayout" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74594492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20618177/" ]
74,594,520
<p>hello im new to programing with c# and i wanted to re-create an old proyect i made in scratch but with c#</p> <p><img src="https://i.stack.imgur.com/665Os.png" alt="the scratch code" /></p> <p>but i have several problems with the code i wrote.</p> <pre><code>int qny = 4; int ADD = 1; int B = 1; string C = &quot; &quot;; for (int i = 0; i &lt; qny; i++) ; { int R = qny + ADD; for (int i = 0; i &lt; R; i++) ; { string C = string.Join(C, B); } int qny = qny - 1; int B = B + 1; } Console.WriteLine(C); </code></pre> <p>the main problem is that i cant use the variables &quot;qny&quot;,&quot;B&quot; and &quot;C&quot; inside the &quot;for&quot;. the only one that doesnt show an error message is the &quot;ADD&quot; variable</p> <p>its suposed to write numbers like this</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>qny</th> <th>result</th> </tr> </thead> <tbody> <tr> <td>2</td> <td>112</td> </tr> <tr> <td>3</td> <td>111223</td> </tr> <tr> <td>4</td> <td>1111222334</td> </tr> </tbody> </table> </div> <p>errors:</p> <pre><code>Error CS0841 Cannot use local variable 'qny' before it is declared. A variable must be declared before it is used. Error CS0136 A local variable named 'C' cannot be declared in this scope because it would give a different meaning to 'C', which is already used in a 'parent or current/child' scope to denote something else Error CS0165 Use of unassigned local variable 'C' Error CS0841 Cannot use local variable 'B' before it is declared. Error CS0136 A local variable named 'qny' cannot be declared in this scope because it would give a different meaning to 'qny', which is already used in a 'parent or current/child' scope to denote something else Error CS0136 A local variable named 'B' cannot be declared in this scope because it would give a different meaning to 'B', which is already used in a 'parent or current/child' scope to denote something else </code></pre>
[ { "answer_id": 74594576, "author": "SilicDev", "author_id": 20614914, "author_profile": "https://Stackoverflow.com/users/20614914", "pm_score": 2, "selected": true, "text": "int qny = 4;\nint ADD = 1;\nint B = 1;\nstring C = \" \";\nfor (int i = 0; i < qny; i++)\n{\n int R = qny + ADD;\n for (int j = 0; j < R; j++)\n {\n C = string.Join(C, B);\n }\n int qny = qny - 1;\n int B = B + 1;\n}\nConsole.WriteLine(C);\n" }, { "answer_id": 74594735, "author": "user20618074", "author_id": 20618074, "author_profile": "https://Stackoverflow.com/users/20618074", "pm_score": 0, "selected": false, "text": "int qny = 4;\nint ADD = 1;\nint B = 1;\nstring C = \" \";\nfor (int i = 0; i < qny; i++)\n{\n int R = qny + ADD;\n for (int j = 0; j < R; j++)\n {\n C = string.Join(C, B);\n }\n qny = qny - 1;\n B = B + 1;\n}\nConsole.WriteLine(C);\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74594520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20618074/" ]
74,594,554
<p>Hi I have some data I want to save it in dataframe after every update. but It always override my previous data. is there any method to keep my previous data save and add new to it.</p> <pre><code>df = pd.DataFrame(columns=['Entry','Middle','Exit']) def function(): entry_value = 178.184 # data comming from server middle_value = 14.121 # data comming from server exit_value = 19.21 # data comming from server df1 = df.append({'Entry' : entry_value , 'Middle' : middle_value, 'Exit' : exit_value}, ignore_index = True) df1.to_csv('abc.csv') i = 0 while i &lt; 5: function() i += 1 </code></pre> <p>this entry_value, middle_value and exit_value is change. sometime it's not change. in this example i want that my csv have same data 5 times</p> <p>Note:: here the value is hard codded but it's comming from server but in this format</p>
[ { "answer_id": 74594630, "author": "Ali", "author_id": 20618350, "author_profile": "https://Stackoverflow.com/users/20618350", "pm_score": 2, "selected": true, "text": "import pandas as pd\n\ndf = pd.DataFrame(columns=['Entry','Middle','Exit'])\ndef function():\n global df\n entry_value = 178.184 # data comming from server\n middle_value = 14.121 # data comming from server\n exit_value = 19.21 # data comming from server'\n \n new_row = pd.DataFrame.from_dict([{'Entry' : entry_value , 'Middle' : middle_value, 'Exit' : exit_value}], orient='columns')\n df = pd.concat([df, new_row])\n df.to_csv('abc.csv')\n \ni = 0\nwhile i < 5:\n function()\n i += 1\n\n import pandas as pd\n\ndf = pd.DataFrame(columns=['Entry','Middle','Exit'])\ndef function(n):\n global df\n entry_value = 178.184 # data comming from server\n middle_value = 14.121 # data comming from server\n exit_value = 19.21 # data comming from server'\n \n new_row = pd.DataFrame.from_dict([{'Entry' : entry_value , 'Middle' : middle_value, 'Exit' : exit_value}], orient='columns')\n df = pd.concat([df, new_row])\n df.to_csv(f'abc{n}.csv')\n \ni = 0\nwhile i < 5:\n function(i)\n i += 1\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74594554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20584885/" ]
74,594,613
<p>I'm struggling with making a function that changes the value of the coordinates if the parameters appropriate.</p> <p>That's what I made:</p> <pre class="lang-py prettyprint-override"><code>class Move: def __init__(self, x, y): self.x = x self.y = y move = Move(5, 5) def obstacle(axis, value, plus): if plus is True: if axis == value: axis = axis + 1 print(f&quot;x = {move.x}, y = {move.y}&quot;) elif plus is False: if axis == value: axis = axis - 1 print(f&quot;x = {move.x}, y = {move.y}&quot;) obstacle(move.x, 5, False) </code></pre> <p>The program should print: x = 4, y = 5</p>
[ { "answer_id": 74594630, "author": "Ali", "author_id": 20618350, "author_profile": "https://Stackoverflow.com/users/20618350", "pm_score": 2, "selected": true, "text": "import pandas as pd\n\ndf = pd.DataFrame(columns=['Entry','Middle','Exit'])\ndef function():\n global df\n entry_value = 178.184 # data comming from server\n middle_value = 14.121 # data comming from server\n exit_value = 19.21 # data comming from server'\n \n new_row = pd.DataFrame.from_dict([{'Entry' : entry_value , 'Middle' : middle_value, 'Exit' : exit_value}], orient='columns')\n df = pd.concat([df, new_row])\n df.to_csv('abc.csv')\n \ni = 0\nwhile i < 5:\n function()\n i += 1\n\n import pandas as pd\n\ndf = pd.DataFrame(columns=['Entry','Middle','Exit'])\ndef function(n):\n global df\n entry_value = 178.184 # data comming from server\n middle_value = 14.121 # data comming from server\n exit_value = 19.21 # data comming from server'\n \n new_row = pd.DataFrame.from_dict([{'Entry' : entry_value , 'Middle' : middle_value, 'Exit' : exit_value}], orient='columns')\n df = pd.concat([df, new_row])\n df.to_csv(f'abc{n}.csv')\n \ni = 0\nwhile i < 5:\n function(i)\n i += 1\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74594613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19713151/" ]
74,594,617
<p>I'm trying to get the amount of pieces belonging to a certain Lego set using the Brickset API (<a href="https://brickset.com/article/52664/api-version-3-documentation" rel="nofollow noreferrer">https://brickset.com/article/52664/api-version-3-documentation</a>) When writing the Json string to the console it displays the amount of pieces correct. Howeever after deserializing and then writing only the value of pieces to the console it displays 0. All other properties are also not displayed when written to the console.</p> <p>Result after writing the Json string to the console</p> <pre><code>{&quot;status&quot;:&quot;success&quot;,&quot;matches&quot;:1,&quot;sets&quot;:\[ { &quot;setID&quot;: 31844, &quot;number&quot;: &quot;10293&quot;, &quot;numberVariant&quot;: 1, &quot;name&quot;: &quot;Santa's Visit&quot;, &quot;year&quot;: 2021, &quot;theme&quot;: &quot;Icons&quot;, &quot;themeGroup&quot;: &quot;Model making&quot;, &quot;subtheme&quot;: &quot;Winter Village Collection&quot;, &quot;category&quot;: &quot;Normal&quot;, &quot;released&quot;: true, &quot;pieces&quot;: 1445, &quot;minifigs&quot;: 4, &quot;image&quot;: { &quot;thumbnailURL&quot;: &quot;https://images.brickset.com/sets/small/10293-1.jpg&quot;, &quot;imageURL&quot;: &quot;https://images.brickset.com/sets/images/10293-1.jpg&quot; }, &quot;bricksetURL&quot;: &quot;https://brickset.com/sets/10293-1&quot;, &quot;collection&quot;: {}, &quot;collections&quot;: { &quot;ownedBy&quot;: 9350, &quot;wantedBy&quot;: 2307 }, &quot;LEGOCom&quot;: { &quot;US&quot;: { &quot;retailPrice&quot;: 99.99, &quot;dateFirstAvailable&quot;: &quot;2021-09-17T00:00:00Z&quot; }, &quot;UK&quot;: { &quot;retailPrice&quot;: 89.99, &quot;dateFirstAvailable&quot;: &quot;2021-09-17T00:00:00Z&quot; }, &quot;CA&quot;: { &quot;retailPrice&quot;: 139.99, &quot;dateFirstAvailable&quot;: &quot;2021-09-17T00:00:00Z&quot; }, &quot;DE&quot;: { &quot;retailPrice&quot;: 99.99, &quot;dateFirstAvailable&quot;: &quot;2021-09-17T00:00:00Z&quot; } }, &quot;rating&quot;: 4.3, &quot;reviewCount&quot;: 0, &quot;packagingType&quot;: &quot;Box&quot;, &quot;availability&quot;: &quot;LEGO exclusive&quot;, &quot;instructionsCount&quot;: 15, &quot;additionalImageCount&quot;: 13, &quot;ageRange&quot;: { &quot;min&quot;: 18 }, &quot;dimensions&quot;: { &quot;height&quot;: 28.0, &quot;width&quot;: 47.9, &quot;depth&quot;: 8.7, &quot;weight&quot;: 1.656 }, &quot;barcode&quot;: { &quot;EAN&quot;: &quot;5702016914313&quot; }, &quot;extendedData&quot;: { &quot;tags&quot;: \[ &quot;Santa Claus|n&quot;, &quot;18 Plus&quot;, &quot;Baked Goods&quot;, &quot;Bedroom&quot;, &quot;Bird&quot;, &quot;Brick Built Tree&quot;, &quot;Brick Separator&quot;, &quot;Christmas&quot;, &quot;Christmas Tree&quot;, &quot;D2c&quot;, &quot;Fireplace&quot;, &quot;Furniture&quot;, &quot;House&quot;, &quot;Kitchen&quot;, &quot;Light Brick&quot;, &quot;Mail&quot;, &quot;Microscale&quot;, &quot;Musical&quot;, &quot;Rocket&quot;, &quot;Seasonal&quot;, &quot;Winter Village&quot; \] }, &quot;lastUpdated&quot;: &quot;2022-10-03T08:24:39.49Z&quot; } \]} </code></pre> <p>Main Code</p> <pre><code>class Program { static async Task Main(string[] args) { await askSetNumber(); } private async Task GetPosts(string url) { HttpClient client = new HttpClient(); string response = await client.GetStringAsync(url); Console.WriteLine(response); var set = JsonConvert.DeserializeObject&lt;Rootobject&gt;(response); Console.WriteLine(set.pieces); } static async Task askSetNumber() { Console.WriteLine(&quot;Please enter a setnumber: &quot;); string setNumber = &quot;{'setNumber':'&quot; + Console.ReadLine().ToString() + &quot;-1'}&quot;; string url = &quot;https://brickset.com/api/v3.asmx/getSets?apiKey=[APIKey here]&amp;userHash=&amp;params=&quot; + setNumber; Console.WriteLine(url); Program program = new Program(); await program.GetPosts(url); } } </code></pre> <p>I made all classes by Pasting the Json as classes, This is the class of the object I need the data off</p> <pre><code>public class Rootobject { public int setID { get; set; } public string number { get; set; } public int numberVariant { get; set; } public string name { get; set; } public int year { get; set; } public string theme { get; set; } public string themeGroup { get; set; } public string subtheme { get; set; } public string category { get; set; } public bool released { get; set; } public int pieces { get; set; } public int minifigs { get; set; } public Image image { get; set; } public string bricksetURL { get; set; } public Collection collection { get; set; } public Collections collections { get; set; } public Legocom LEGOCom { get; set; } public float rating { get; set; } public int reviewCount { get; set; } public string packagingType { get; set; } public string availability { get; set; } public int instructionsCount { get; set; } public int additionalImageCount { get; set; } public Agerange ageRange { get; set; } public Dimensions dimensions { get; set; } public Barcode barcode { get; set; } public Extendeddata extendedData { get; set; } public DateTime lastUpdated { get; set; } } </code></pre> <p>I tried the example from <a href="https://stackoverflow.com/questions/17617594/how-to-get-some-values-from-a-json-string-in-c">How to get some values from a JSON string in C#?</a> but set.pieces keeps returning 0.</p> <p>This is my first time trying this kind of stuff, but I am stuck on this part.</p>
[ { "answer_id": 74594630, "author": "Ali", "author_id": 20618350, "author_profile": "https://Stackoverflow.com/users/20618350", "pm_score": 2, "selected": true, "text": "import pandas as pd\n\ndf = pd.DataFrame(columns=['Entry','Middle','Exit'])\ndef function():\n global df\n entry_value = 178.184 # data comming from server\n middle_value = 14.121 # data comming from server\n exit_value = 19.21 # data comming from server'\n \n new_row = pd.DataFrame.from_dict([{'Entry' : entry_value , 'Middle' : middle_value, 'Exit' : exit_value}], orient='columns')\n df = pd.concat([df, new_row])\n df.to_csv('abc.csv')\n \ni = 0\nwhile i < 5:\n function()\n i += 1\n\n import pandas as pd\n\ndf = pd.DataFrame(columns=['Entry','Middle','Exit'])\ndef function(n):\n global df\n entry_value = 178.184 # data comming from server\n middle_value = 14.121 # data comming from server\n exit_value = 19.21 # data comming from server'\n \n new_row = pd.DataFrame.from_dict([{'Entry' : entry_value , 'Middle' : middle_value, 'Exit' : exit_value}], orient='columns')\n df = pd.concat([df, new_row])\n df.to_csv(f'abc{n}.csv')\n \ni = 0\nwhile i < 5:\n function(i)\n i += 1\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74594617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19306325/" ]
74,594,626
<p>I need to display the values of response, but React doest support the data-for HTML-attribute. When i use the template from <a href="https://learn.microsoft.com/en-us/graph/toolkit/components/get" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/graph/toolkit/components/get</a> I get the error: unexpected variable email. See my implementation below. I can't use <code>{{email.subject}}</code> in this case.</p> <pre><code>import React, { useState, useEffect, useDebugValue } from 'react'; import { Get } from '@microsoft/mgt-react'; import { useAuth0 } from '@auth0/auth0-react'; function GetMessage() { const { isAuthenticated } = useAuth0(); const value = &lt;Get&gt;&lt;/Get&gt;; console.log(value); return ( isAuthenticated &amp;&amp; ( &lt;mgt-get resource=&quot;/me/messages&quot; version=&quot;beta&quot; scopes=&quot;mail.read&quot; max-pages=&quot;2&quot;&gt; &lt;template&gt; &lt;div class=&quot;email&quot; data-for=&quot;email in value&quot;&gt; &lt;h3&gt;{{ email.subject }}&lt;/h3&gt; &lt;h4&gt; &lt;mgt-person person-query=&quot;{{email.sender.emailAddress.address}}&quot; view=&quot;oneline&quot; person-card=&quot;hover&quot;&gt;&lt;/mgt-person&gt; &lt;/h4&gt; &lt;div data-if=&quot;email.bodyPreview&quot; class=&quot;preview&quot; innerHtml&gt;{{email.bodyPreview}}&lt;/div&gt; &lt;div data-else class=&quot;preview&quot;&gt;email body is empty&lt;/div&gt; &lt;/div&gt; &lt;/template&gt; &lt;template data-type=&quot;loading&quot;&gt;loading&lt;/template&gt; &lt;template data-type=&quot;error&quot;&gt;{{ this }}&lt;/template&gt; &lt;/mgt-get&gt; ) ) } export default GetMessage; </code></pre> <p>I tried to use the mgt-toolkit examples. The other components works fine.</p>
[ { "answer_id": 74594630, "author": "Ali", "author_id": 20618350, "author_profile": "https://Stackoverflow.com/users/20618350", "pm_score": 2, "selected": true, "text": "import pandas as pd\n\ndf = pd.DataFrame(columns=['Entry','Middle','Exit'])\ndef function():\n global df\n entry_value = 178.184 # data comming from server\n middle_value = 14.121 # data comming from server\n exit_value = 19.21 # data comming from server'\n \n new_row = pd.DataFrame.from_dict([{'Entry' : entry_value , 'Middle' : middle_value, 'Exit' : exit_value}], orient='columns')\n df = pd.concat([df, new_row])\n df.to_csv('abc.csv')\n \ni = 0\nwhile i < 5:\n function()\n i += 1\n\n import pandas as pd\n\ndf = pd.DataFrame(columns=['Entry','Middle','Exit'])\ndef function(n):\n global df\n entry_value = 178.184 # data comming from server\n middle_value = 14.121 # data comming from server\n exit_value = 19.21 # data comming from server'\n \n new_row = pd.DataFrame.from_dict([{'Entry' : entry_value , 'Middle' : middle_value, 'Exit' : exit_value}], orient='columns')\n df = pd.concat([df, new_row])\n df.to_csv(f'abc{n}.csv')\n \ni = 0\nwhile i < 5:\n function(i)\n i += 1\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74594626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20618318/" ]
74,594,643
<p>I think I understand why <code>React.StrictMode</code> causes functions <a href="https://stackoverflow.com/questions/50819162/why-is-my-function-being-called-twice-in-react">to be called twice</a>. However, I have a <code>useEffect</code> that loads data from my api:</p> <pre class="lang-js prettyprint-override"><code>useEffect(() =&gt; { async function fetchData() { const data = await getData(); setData(data); } fetchData(); }, []); </code></pre> <p>In my <code>getData()</code> function I call a maintenance script <code>cullRecords()</code> that cleans up my data by deleting records over a certain age before returning the data:</p> <pre class="lang-js prettyprint-override"><code>async function getData(){ let results = await apiCall(); cullRecords(results); return results; } </code></pre> <p>Here's the rub: <code>React.StrictMode</code> fires the <code>getData()</code> function twice, loading up the <code>apiCall()</code> twice and firing the <code>cullRecords()</code> twice. However, by the time the second <code>cullRecords()</code> subscript fires, my API throws an error because those records are already gone.</p> <p>While it's not the end of the world, I'm curious if I'm doing something wrong, or if this is just a fringe case, and not to worry about it.</p>
[ { "answer_id": 74594630, "author": "Ali", "author_id": 20618350, "author_profile": "https://Stackoverflow.com/users/20618350", "pm_score": 2, "selected": true, "text": "import pandas as pd\n\ndf = pd.DataFrame(columns=['Entry','Middle','Exit'])\ndef function():\n global df\n entry_value = 178.184 # data comming from server\n middle_value = 14.121 # data comming from server\n exit_value = 19.21 # data comming from server'\n \n new_row = pd.DataFrame.from_dict([{'Entry' : entry_value , 'Middle' : middle_value, 'Exit' : exit_value}], orient='columns')\n df = pd.concat([df, new_row])\n df.to_csv('abc.csv')\n \ni = 0\nwhile i < 5:\n function()\n i += 1\n\n import pandas as pd\n\ndf = pd.DataFrame(columns=['Entry','Middle','Exit'])\ndef function(n):\n global df\n entry_value = 178.184 # data comming from server\n middle_value = 14.121 # data comming from server\n exit_value = 19.21 # data comming from server'\n \n new_row = pd.DataFrame.from_dict([{'Entry' : entry_value , 'Middle' : middle_value, 'Exit' : exit_value}], orient='columns')\n df = pd.concat([df, new_row])\n df.to_csv(f'abc{n}.csv')\n \ni = 0\nwhile i < 5:\n function(i)\n i += 1\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74594643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1061836/" ]
74,594,645
<p>I have a huge list of sublists, each sublist consisting of a tuple and a list of 4 integers.</p> <p>I want to create a list of unique tuples that adds each integer values of the list (keeping the four integers in the list separate).</p> <p>Short Example:</p> <pre><code>[[(30, 40), [4, 7, 7, 1]],[(30, 40), [2, 9, 3, 4]],[(30, 40), [6, 5, 10, 0]],[(20, 40), [4, 0, 4, 0]],[(20, 40), [3, 4, 14, 5]],[(20, 40), [3, 2, 12, 0]],[(10, 40), [223, 22, 12, 9]]] </code></pre> <p>Output wanted:</p> <pre><code>[[(30, 40), [12, 21, 20, 5]],[(20, 40), [2, 9, 3, 4]],[(10, 40), [223, 22, 12, 9]] </code></pre> <p>I have tried using a dictionary</p> <pre><code>l = [[(30, 40), [4, 7, 7, 1]],[(30, 40), [2, 9, 3, 4]],[(30, 40), [6, 5, 10, 0]],[(20, 40), [4, 0, 4, 0]],[(20, 40), [3, 4, 14, 5]],[(20, 40), [3, 2, 12, 0]],[(10, 40), [223, 22, 12, 9]]] dict_tuples = {} for item in l: if item[0] in dict_tuples: dict_tuples[item[0]] += item[1] else: dict_tuples[item[0]] = item[1] </code></pre> <p>But here I am just getting a long list of integer values for each tuple. I want to sum of each index in the list of four integers.</p>
[ { "answer_id": 74594763, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 1, "selected": false, "text": "lst = [\n [(30, 40), [4, 7, 7, 1]],\n [(30, 40), [2, 9, 3, 4]],\n [(30, 40), [6, 5, 10, 0]],\n [(20, 40), [4, 0, 4, 0]],\n [(20, 40), [3, 4, 14, 5]],\n [(20, 40), [3, 2, 12, 0]],\n [(10, 40), [223, 22, 12, 9]],\n]\n\nout = {}\nfor t, l in lst:\n out.setdefault(t, []).append(l)\n\nout = [[k, [sum(t) for t in zip(*v)]] for k, v in out.items()]\n\nprint(out)\n [\n [(30, 40), [12, 21, 20, 5]],\n [(20, 40), [10, 6, 30, 5]],\n [(10, 40), [223, 22, 12, 9]],\n]\n" }, { "answer_id": 74594778, "author": "Chris", "author_id": 15261315, "author_profile": "https://Stackoverflow.com/users/15261315", "pm_score": 0, "selected": false, "text": "itertools.groupby from itertools import groupby\nfrom operator import itemgetter\n\nl = [[(30, 40), [4, 7, 7, 1]], [(30, 40), [2, 9, 3, 4]], [(30, 40), [6, 5, 10, 0]], [(20, 40), [4, 0, 4, 0]], [(20, 40), [3, 4, 14, 5]], [(20, 40), [3, 2, 12, 0]], [(10, 40), [223, 22, 12, 9]]]\n\ns = sorted(l, key=itemgetter(0))\n# [[(10, 40), [223, 22, 12, 9]], [(20, 40), [4, 0, 4, 0]], [(20, 40), [3, 4, 14, 5]], [(20, 40), [3, 2, 12, 0]], [(30, 40), [4, 7, 7, 1]], [(30, 40), [2, 9, 3, 4]], [(30, 40), [6, 5, 10, 0]]]\n\ng = groupby(s, key=itemgetter(0))\n\nl2 = [(k, [x[1] for x in v]) for k, v in g]\n# [((10, 40), [[223, 22, 12, 9]]), ((20, 40), [[4, 0, 4, 0], [3, 4, 14, 5], [3, 2, 12, 0]]), ((30, 40), [[4, 7, 7, 1], [2, 9, 3, 4], [6, 5, 10, 0]])]\n\nl3 = [(k, list(zip(*v))) for k, v in l2]\n# [((10, 40), [(223,), (22,), (12,), (9,)]), ((20, 40), [(4, 3, 3), (0, 4, 2), (4, 14, 12), (0, 5, 0)]), ((30, 40), [(4, 2, 6), (7, 9, 5), (7, 3, 10), (1, 4, 0)])]\n\nl4 = [(k, [sum(x) for x in v]) for k, v in l3]\n# [((10, 40), [223, 22, 12, 9]), ((20, 40), [10, 6, 30, 5]), ((30, 40), [12, 21, 20, 5])]\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74594645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20543467/" ]
74,594,653
<p>I've looked at the merge sort example code, but there's something I don't understand.</p> <pre><code>void mergesort(int left, int right) { if (left &lt; right) { int sorted[LEN]; int mid, p1, p2, idx; mid = (left + right) / 2; mergesort(left, mid); mergesort(mid + 1, right); p1 = left; p2 = mid + 1; idx = left; while (p1 &lt;= mid &amp;&amp; p2 &lt;= right) { if (arr[p1] &lt; arr[p2]) sorted[idx++] = arr[p1++]; else sorted[idx++] = arr[p2++]; } while (p1 &lt;= mid) sorted[idx++] = arr[p1++]; while (p2 &lt;= right) sorted[idx++] = arr[p2++]; for (int i = left; i &lt;= right; i++) arr[i] = sorted[i]; } } </code></pre> <p>In this code, I don't know about while loops that increase p1 and p2 respectively.</p> <p>In detail, This code inserts p1, p2 in order into the 'sorted array', but I don't understand why the array is sorted in ascending order.</p> <p>I looked at many explanations on the internet, but couldn't find a clear answer.</p> <p>I would appreciate it if you could write your answer in detail so that I can understand it.</p>
[ { "answer_id": 74603927, "author": "rcgldr", "author_id": 3282056, "author_profile": "https://Stackoverflow.com/users/3282056", "pm_score": 1, "selected": false, "text": "static int arr[LEN];\nstatic int sorted[LEN];\nvoid mergesort(int left, int right)\n/* ... */\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74594653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20287503/" ]