qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,494,747
<p>For my python bootcamp I am trying to create a log of the articles from this site, and return the highest upvoted. The rest of the code works, but I cannot get it to return the href properly. I get &quot;none.&quot; I have tried everything I know to do... can anyone provide any guidance?</p> <pre><code>from bs4 import BeautifulSoup import requests response = requests.get(&quot;https://news.ycombinator.com/&quot;) yc_web_page = response.text soup = BeautifulSoup(yc_web_page, &quot;html.parser&quot;) articles = soup.find_all(name=&quot;span&quot;, class_=&quot;titleline&quot;) article_texts = [] article_links = [] for article_tag in articles: article_text = article_tag.get_text() article_texts.append(article_text) article_link = article_tag.get(&quot;href&quot;) article_links.append(article_link) article_upvotes = [int(score.getText().split()[0]) for score in soup.find_all(name=&quot;span&quot;, class_=&quot;score&quot;)] largest_number = max(article_upvotes) largest_index = article_upvotes.index(largest_number) print(article_texts[largest_index]) print(article_links[largest_index]) print(article_upvotes[largest_index])` </code></pre> <p>I have tried to change the 'href' to just an 'a' tag and it returned the same value of &quot;none&quot;</p>
[ { "answer_id": 74494797, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 2, "selected": true, "text": "\n...\n\n article_link = article_tag.a.get(\"href\") # <--- put .a here\n\n...\n from bs4 import BeautifulSoup\nimport requests\n\n\nresponse = requests.get(\"https://news.ycombinator.com/\")\nyc_web_page = response.text\n\n\nsoup = BeautifulSoup(yc_web_page, \"html.parser\")\narticles = soup.find_all(name=\"span\", class_=\"titleline\")\n\narticle_texts = []\narticle_links = []\n\nfor article_tag in articles:\n\n article_text = article_tag.get_text()\n article_texts.append(article_text)\n\n article_link = article_tag.a.get(\"href\") # <--- put .a here\n article_links.append(article_link)\n\n\narticle_upvotes = [\n int(score.getText().split()[0])\n for score in soup.find_all(name=\"span\", class_=\"score\")\n]\n\n\nlargest_number = max(article_upvotes)\nlargest_index = article_upvotes.index(largest_number)\n\nprint(article_texts[largest_index])\nprint(article_links[largest_index])\nprint(article_upvotes[largest_index])\n Fred Brooks has died (twitter.com/stevebellovin)\nhttps://twitter.com/stevebellovin/status/1593414068634734592\n1368\n" }, { "answer_id": 74494947, "author": "baduker", "author_id": 6106791, "author_profile": "https://Stackoverflow.com/users/6106791", "pm_score": 0, "selected": false, "text": "import requests\nfrom bs4 import BeautifulSoup\n\nurl = \"https://news.ycombinator.com/\"\n\nsoup = BeautifulSoup(requests.get(url).text, \"lxml\")\n\nall_scores = [\n [\n int(x.getText().replace(\" points\", \"\")),\n x[\"id\"].replace(\"score_\", \"\"),\n ]\n for x in soup.find_all(\"span\", class_=\"score\")\n]\n\nvotes, tr_id = sorted(all_scores, key=lambda x: x[0], reverse=True)[0]\n\ntable_row = soup.find(\"tr\", id=tr_id)\ntext = table_row.select_one(\"span a\").getText()\nlink = table_row.select_one(\"span a\")[\"href\"]\n\nprint(f\"{text}\\n{link}\\n{votes} votes\")\n Fred Brooks has died\nhttps://twitter.com/stevebellovin/status/1593414068634734592\n1377 votes\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74494747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19763288/" ]
74,494,788
<p>I have this <a href="https://regex101.com/r/ZS8EWW/1" rel="nofollow noreferrer">REGEX</a> to check a paragraph and get some data from there.</p> <pre><code>([0-9]{1,2}:{0,1}[0-9]{0,2}[a-z]{0,2})[\s\D\s]+([0-9]{1,2}:{0,1}[0-9]{0,2}[a-z]{0,2}),(.+),(\s\w{1,2} de [\wç]+ de \d{4})?(\s\w+ \d{1,2}, \d{4})?$ </code></pre> <p>I need to get the hour, title and the date of this type of texts:</p> <p><strong>EXAMPLE 1 :</strong> This example the number 130 is causing the issue and I can't get the first hour</p> <pre><code>1:30pm to 4:30pm, Aniversário amigo matteo, Ana Montoya, Accepted, Location: Kids Buffet Infantil Rua do Triunfo, 130, Brookling, Hello - SP, 04602-005, Brasil, November 23, 2022 </code></pre> <p><strong>EXAMPLE 2 :</strong> This is working correctly</p> <pre><code>8am to 9:30am, All Hearts meeting, Ana Montoya, Accepted, Location: https://us02web.zoom.us/j/1234?pwd=1234, November 21, 2022 </code></pre> <p>Get the two hours, the text of the title and the final date</p>
[ { "answer_id": 74495122, "author": "Ali ISSA", "author_id": 5920582, "author_profile": "https://Stackoverflow.com/users/5920582", "pm_score": -1, "selected": false, "text": "([0-9]{1,2}:{0,1}[0-9]{0,2}[a-z]{0,2})[\\s\\D\\s]+([0-9]{1,2}:{0,1}[0-9]{0,2}[a-z]{0,2}),(.+),(\\s\\w{1,2} de [\\wç]+ de \\d{4})?(\\s\\w+ \\d{1,2}, \\d{4})? ^([0-9]{1,2}:{0,1}[0-9]{0,2}[a-z]{0,2})[\\s\\D\\s]+([0-9]{1,2}:{0,1}[0-9]{0,2}[a-z]{0,2}),(.+),(\\s\\w{1,2} de [\\wç]+ de \\d{4})?(\\s\\w+ \\d{1,2}, \\d{4})? ([0-9]{1,2}:{0,1}[0-9]{0,2}[a-z]{0,2})[\\s\\D\\s]+([0-9]{1,2}:{0,1}[0-9]{0,2}[a-z]{0,2}),(.+),(\\s\\w{1,2} de [\\wç]+ de \\d{4})?(\\s\\w+ \\d{1,2}, \\d{4})?.*$ ^([0-9]{1,2}:{0,1}[0-9]{0,2}[a-z]{0,2})[\\s\\D\\s]+([0-9]{1,2}:{0,1}[0-9]{0,2}[a-z]{0,2}),(.+),(\\s\\w{1,2} de [\\wç]+ de \\d{4})?(\\s\\w+ \\d{1,2}, \\d{4})?.*$" }, { "answer_id": 74495842, "author": "Peter Thoeny", "author_id": 7475450, "author_profile": "https://Stackoverflow.com/users/7475450", "pm_score": 1, "selected": false, "text": "[\n '1:30pm to 4:30pm, Aniversário amigo matteo, Ana Montoya, Accepted, Location: Kids Buffet Infantil Rua do Triunfo, 130, Brookling, Hello - SP, 04602-005, Brasil, November 23, 2022',\n '8am to 9:30am, All Hearts meeting, Ana Montoya, Accepted, Location: https://us02web.zoom.us/j/1234?pwd=1234, November 21, 2022'\n].forEach(str => {\n let m = str.match(/^(\\d\\d?(?::\\d\\d)?[ap]m) to (\\d\\d?(?::\\d\\d)?[ap]m), *([^,]+).* ([a-z]+ \\d+, \\d{4})/i);\n console.log(m);\n}); [\n \"1:30pm to 4:30pm, Aniversário amigo matteo, Ana Montoya, Accepted, Location: Kids Buffet Infantil Rua do Triunfo, 130, Brookling, Hello - SP, 04602-005, Brasil, November 23, 2022\",\n \"1:30pm\",\n \"4:30pm\",\n \"Aniversário amigo matteo\",\n \"November 23, 2022\"\n]\n[\n \"8am to 9:30am, All Hearts meeting, Ana Montoya, Accepted, Location: https://us02web.zoom.us/j/1234?pwd=1234, November 21, 2022\",\n \"8am\",\n \"9:30am\",\n \"All Hearts meeting\",\n \"November 21, 2022\"\n]\n ^ ( \\d\\d? (?::\\d\\d)? [ap]m am pm ) to (\\d\\d?(?::\\d\\d)?[ap]m) , * ([^,]+) .* ([a-z]+ \\d+, \\d{4}) Mmmmm dd, yyyy i" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74494788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6824168/" ]
74,494,803
<p>I'm not new to .NET Core development, but I am very new to ASP.NET Web Apps.</p> <p>I have an Index.cshtml that has the following iframe in it:</p> <pre><code> &lt;iframe height=&quot;800&quot; width=&quot;1300&quot; loading=&quot;eager&quot; frameBorder=&quot;0&quot; scrolling=&quot;no&quot; seamless=&quot;seamless&quot; allowtransparency=&quot;true&quot; src=&quot;https://example.com/?page_id=436&quot; title=&quot;My site&quot; /&gt; </code></pre> <p>I need to force this iframe to reload (not from cache) whenever the page gets refreshed. On the web, I found the following suggestion:</p> <pre><code>iframe.src = &quot;https://example.com/?page_id=436?reload=&quot;+(new Date()).getTime(); </code></pre> <p>Here's my question: Where in a ASP.NET web app (using bootstrap) would I put this code to make it refresh my iframe? I'm somewhat familiar with javascript (haven't used it in a while), have very little knowledge of ASP.NET, and almost none of bootstrap. I know html/css pretty well.</p> <p>I'm confused about where in the code to put this bit of javascript so that it will always run when I refresh the page. And I don't know how to make that code reference my specific iframe.</p> <p>Thanks!</p>
[ { "answer_id": 74494857, "author": "SNBS", "author_id": 20426120, "author_profile": "https://Stackoverflow.com/users/20426120", "pm_score": 1, "selected": false, "text": "iframe <script defer>\n iframe.src = \"https://example.com/?page_id=436?reload=\"+(new Date()).getTime();\n</script>\n" }, { "answer_id": 74503163, "author": "Brad Y.", "author_id": 6831042, "author_profile": "https://Stackoverflow.com/users/6831042", "pm_score": 1, "selected": true, "text": "@page\n@model IndexModel\n@{\n ViewData[\"Title\"] = \"Example\";\n string pageUrl = \"https://example.com/?page_id=436?reload=\" + DateTime.Now.ToString();\n}\n\n<div id=\"site-main\">\n <div>\n <h1 class=\"headline\">Printing some good stuff here</h1>\n <p class=\"headline\">And now some description!</p>\n </div>\n</div>\n<div>\n <iframe id=\"cgblog\" height=\"800\" width=\"1300\" loading=\"eager\" frameBorder=\"0\" scrolling=\"no\" seamless=\"seamless\" allowtransparency=\"true\" src=\"@pageUrl\" title=\"My site\">\n </iframe>\n\n</div>\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74494803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6831042/" ]
74,494,806
<p>I have the following:</p> <pre><code>import pandas as pd file = pd.DataFrame() file['CASH RECIEVED DATE'] = ['2018-07-23', '2019-09-26', '2017-05-02'] </code></pre> <p>and I need to create a column called <code>Cash Received Date</code></p> <pre><code>file['Cash Received Date'] </code></pre> <p>such as if <code>[CASH_RECIEVED_DATE]</code> is not null &amp;&amp; <code>[CASH RECIEVED_DATE]</code> &lt;= 2022-09-01 then <code>[Cash Received Date]</code> will be <code>2019-09-01</code>, otherwise it will be the value of <code>[CASH_RECIEVED_DATE]</code>, so the output would be:</p> <pre><code> file['Cash Received Date'] = ['2019-09-01', '2019-09-26', '2019-09-01'] </code></pre> <p>How do I achieve this by creating a function?</p> <p>Many thanks, Rafa</p>
[ { "answer_id": 74494857, "author": "SNBS", "author_id": 20426120, "author_profile": "https://Stackoverflow.com/users/20426120", "pm_score": 1, "selected": false, "text": "iframe <script defer>\n iframe.src = \"https://example.com/?page_id=436?reload=\"+(new Date()).getTime();\n</script>\n" }, { "answer_id": 74503163, "author": "Brad Y.", "author_id": 6831042, "author_profile": "https://Stackoverflow.com/users/6831042", "pm_score": 1, "selected": true, "text": "@page\n@model IndexModel\n@{\n ViewData[\"Title\"] = \"Example\";\n string pageUrl = \"https://example.com/?page_id=436?reload=\" + DateTime.Now.ToString();\n}\n\n<div id=\"site-main\">\n <div>\n <h1 class=\"headline\">Printing some good stuff here</h1>\n <p class=\"headline\">And now some description!</p>\n </div>\n</div>\n<div>\n <iframe id=\"cgblog\" height=\"800\" width=\"1300\" loading=\"eager\" frameBorder=\"0\" scrolling=\"no\" seamless=\"seamless\" allowtransparency=\"true\" src=\"@pageUrl\" title=\"My site\">\n </iframe>\n\n</div>\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74494806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13410280/" ]
74,494,811
<p>I want to count how many times each function get called. I have a wrapper to do the counting and save it into a global variable</p> <pre><code>def counter(f): global function_calls function_calls = 0 def wrapper(*args, **kwargs): global function_calls function_calls += 1 return f(*args, **kwargs) return wrapper </code></pre> <p>and then other two functions to be decorated for counting</p> <pre><code>@counter def square(x): return x * x @counter def addition_by_self(x): return x + x </code></pre> <p>Now when I call the function five time each the global variable <code>function_calls</code> returns 10. Which makes sense.</p> <pre><code>print(square(x=4)) print(square(x=4)) print(square(x=4)) print(square(x=4)) print(square(x=4)) print(addition_by_self(x=4)) print(addition_by_self(x=4)) print(addition_by_self(x=4)) print(addition_by_self(x=4)) print(addition_by_self(x=4)) print(f&quot;Number of the function got called: {function_calls}&quot;) </code></pre> <p>running the file gives the output.</p> <pre><code>16 16 16 16 16 8 8 8 8 8 Number of the function got called: 10 </code></pre> <p>Now I need some solutions or ideas on how to make the decorator return how many times each function got called, not an aggregation of all the calls. I might have other functions which I need track the number of times they also got called.</p> <p>Essentially I want to do something like <code>print(function_calls) # or something proper</code> and get the out like: <code>sqaure got called 5 times and addition_by_self got called 5 times</code></p>
[ { "answer_id": 74494893, "author": "chepner", "author_id": 1126841, "author_profile": "https://Stackoverflow.com/users/1126841", "pm_score": 3, "selected": true, "text": "int dict def counter(f):\n global function_calls\n function_calls = {}\n\n def wrapper(*args, **kwargs):\n global function_calls\n function_calls[f.__name__] = function_calls.setdefault(f.__name__, 0) + 1\n return f(*args, **kwargs)\n\n return wrapper\n f f.__name__" }, { "answer_id": 74495079, "author": "Dennis Williamson", "author_id": 26428, "author_profile": "https://Stackoverflow.com/users/26428", "pm_score": 1, "selected": false, "text": "def counter(f):\n global funs\n try:\n len(funs)\n except NameError:\n funs = []\n funs.append(f)\n f.function_calls = 0\n\n def wrapper(*args, **kwargs):\n f.function_calls += 1\n return f(*args, **kwargs)\n\n return wrapper\n\n@counter\ndef square(x):\n return x * x\n\n\n@counter\ndef addition_by_self(x):\n return x + x\n\nfor i in range(10):\n print(square(3))\n print(addition_by_self(2))\n print(addition_by_self(4))\n\nfor f in funs:\n print(f'function: {f.__name__}, calls: {f.function_calls}')\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74494811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14752392/" ]
74,494,822
<p>I know this question has been asked, I looked through all of them and couldn't find a fix for my code.</p> <p>This is the pubspec yaml, I think that where I might have the error</p> <pre><code>name: i_am_rich description: fuck this shit version: 1.0.0+1 environment: sdk: '&gt;=2.18.4 &lt;3.0.0' dependencies: flutter: sdk: flutter cupertino_icons: ^1.0.2 dev_dependencies: flutter_test: sdk: flutter flutter: uses-material-design: true assets: - images/ </code></pre> <p>and this is the dart</p> <pre><code>void main() { runApp( MaterialApp( home: Scaffold( backgroundColor: Colors.blueGrey, appBar: AppBar( centerTitle: true, title: Text('Shine bright like a'), backgroundColor: Colors.blueGrey[900], ), body: Center( child: Image( image: AssetImage('images/diamond.png'), ), ), ), ), ); } </code></pre> <p>I tried fixing the indentations on the <code>pubspec.yaml</code>, both manually and with tab, and a bunch of stuff from youtube videos, even the course I'm taking (not very good honestly), been trying to fix this for HOURS please help.</p>
[ { "answer_id": 74494893, "author": "chepner", "author_id": 1126841, "author_profile": "https://Stackoverflow.com/users/1126841", "pm_score": 3, "selected": true, "text": "int dict def counter(f):\n global function_calls\n function_calls = {}\n\n def wrapper(*args, **kwargs):\n global function_calls\n function_calls[f.__name__] = function_calls.setdefault(f.__name__, 0) + 1\n return f(*args, **kwargs)\n\n return wrapper\n f f.__name__" }, { "answer_id": 74495079, "author": "Dennis Williamson", "author_id": 26428, "author_profile": "https://Stackoverflow.com/users/26428", "pm_score": 1, "selected": false, "text": "def counter(f):\n global funs\n try:\n len(funs)\n except NameError:\n funs = []\n funs.append(f)\n f.function_calls = 0\n\n def wrapper(*args, **kwargs):\n f.function_calls += 1\n return f(*args, **kwargs)\n\n return wrapper\n\n@counter\ndef square(x):\n return x * x\n\n\n@counter\ndef addition_by_self(x):\n return x + x\n\nfor i in range(10):\n print(square(3))\n print(addition_by_self(2))\n print(addition_by_self(4))\n\nfor f in funs:\n print(f'function: {f.__name__}, calls: {f.function_calls}')\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74494822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20542791/" ]
74,494,846
<p>I am using a kendo grid &quot;detailTemplate&quot; almost identical to this example: <a href="https://demos.telerik.com/kendo-ui/grid/detailtemplate" rel="nofollow noreferrer">https://demos.telerik.com/kendo-ui/grid/detailtemplate</a></p> <p>When my expand icon is clicked, I fetch the data and display another kendo grid just like the orders tab in the above example.</p> <p>This is working well, as expected.</p> <p>The problem.</p> <p>When I fetch the detail data, I also want to display additional info right next to the detail grid. This additional info does not belong in the grid, but I do want it to display next to the grid.</p> <p>I am doing the following in the detail grid datasource.</p> <pre><code>My Psuedo Code &lt;script id=&quot;template-details&quot;&gt; &lt;div class=&quot;myDetailGrid&quot;&gt;&lt;/div&gt; &lt;div id=&quot;additionalInfoTemplate&quot;&gt;&lt;/div&gt; &lt;/script&gt; ... detailRow.find(&quot;.myDetailGrid&quot;).kendoGrid({ dataSource: { transport: { read: function(options) { axios.post(myUrlString, payloadContent).then(function (response) { options.success(response.data.orders); var templateString = `&lt;div&gt;#: additionalInfo1 #&lt;/div&gt;&lt;div&gt;#: additionalInfo2 #&lt;/div&gt; ....` var template = kendo.template(templateString); var result = template(response.data.additionalInfo); $(&quot;#additionalInfoTemplate&quot;).html(result); }) ... } } ... </code></pre> <p>Here is what happens:</p> <p>-my parent grid displays fine</p> <p>-when the expand icon is clicked, the details grid displays fine. the detail grid always displays fine when any row is expanded</p> <p>-The additional info will display fine for the first detail choosen,</p> <p>-But when the next detail is expanded, the detail grid is correct but the additional info template data is wrong. It's the previous detail's additional info or blank.</p> <p>-The additional info is never right after the first row is expanded.</p> <p>How can I display additional information correctly in this situation.</p>
[ { "answer_id": 74494893, "author": "chepner", "author_id": 1126841, "author_profile": "https://Stackoverflow.com/users/1126841", "pm_score": 3, "selected": true, "text": "int dict def counter(f):\n global function_calls\n function_calls = {}\n\n def wrapper(*args, **kwargs):\n global function_calls\n function_calls[f.__name__] = function_calls.setdefault(f.__name__, 0) + 1\n return f(*args, **kwargs)\n\n return wrapper\n f f.__name__" }, { "answer_id": 74495079, "author": "Dennis Williamson", "author_id": 26428, "author_profile": "https://Stackoverflow.com/users/26428", "pm_score": 1, "selected": false, "text": "def counter(f):\n global funs\n try:\n len(funs)\n except NameError:\n funs = []\n funs.append(f)\n f.function_calls = 0\n\n def wrapper(*args, **kwargs):\n f.function_calls += 1\n return f(*args, **kwargs)\n\n return wrapper\n\n@counter\ndef square(x):\n return x * x\n\n\n@counter\ndef addition_by_self(x):\n return x + x\n\nfor i in range(10):\n print(square(3))\n print(addition_by_self(2))\n print(addition_by_self(4))\n\nfor f in funs:\n print(f'function: {f.__name__}, calls: {f.function_calls}')\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74494846", "https://Stackoverflow.com", "https://Stackoverflow.com/users/937554/" ]
74,494,899
<p>I have a MongoDB collection like this:</p> <pre><code>{ _id: &quot;abc&quot;, history: [ { status: 1, reason: &quot;confirmed&quot; }, { status: 2, reason: &quot;accepted&quot; } ], _id: &quot;xyz&quot;, history: [ { status: 2, reason: &quot;accepted&quot; }, { status: 10, reason: &quot;cancelled&quot; } ] } </code></pre> <p>I want to write a query in C# to return the documents whose <strong>last</strong> history item is 2 (accepted). So in my result I should not see &quot;xyz&quot; because its state has changed from 2, but I should see &quot;abc&quot; since its last status is 2. The problem is that getting the <strong>last item</strong> is not easy with MongoDB's C# driver - or I don't know how to.</p> <p>I tried the linq's lastOrDefault but got <code>System.InvalidOperationException: {document}{History}.LastOrDefault().Status is not supported</code> error.</p> <p>I know there is a workaround to get the documents first (load to memory) and then filter, but it is client side and slow (consumes lot of network). I want to do the filter on server.</p>
[ { "answer_id": 74495428, "author": "R2D2", "author_id": 10415047, "author_profile": "https://Stackoverflow.com/users/10415047", "pm_score": 1, "selected": false, "text": "db.collection.find({\n $expr: {\n $eq: [\n {\n $arrayElemAt: [\n \"$history.status\",\n -1\n ]\n },\n 2\n ]\n }\n})\n db.collection.aggregate([\n {\n\"$addFields\": {\n last: {\n $arrayElemAt: [\n \"$history\",\n -1\n ]\n }\n }\n},\n{\n $match: {\n \"last.status\": 2\n }\n},\n{\n $project: {\n \"history\": 1\n }\n }\n])\n" }, { "answer_id": 74508224, "author": "Mahdi Tahsildari", "author_id": 1471381, "author_profile": "https://Stackoverflow.com/users/1471381", "pm_score": 1, "selected": true, "text": "Aggregate $addFields PipelineDefinition<Process, BsonDocument> pipeline = new BsonDocument[]\n{\n new BsonDocument(\"$addFields\",\n new BsonDocument(\"history\",\n new BsonDocument ( \"$slice\",\n new BsonArray { \"$history\", -1 }\n )\n )\n ),\n new BsonDocument(\"$match\",\n new BsonDocument\n {\n { \"history.status\", 2 }\n }\n )\n};\n\nvar result = collection.Aggregate(pipeline).ToList();\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74494899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1471381/" ]
74,494,901
<p>I am trying to apply PCA to reduce dimensionality and noise using Julia language but am getting an error message. Could you please help me to solve this issue.</p> <p>Are there other alternatives in julia to the perform the same task?</p> <p>Here's the error message:</p> <pre><code>julia&gt; X = (train_input)' |&gt; Array; julia&gt; typeof(X) Matrix{Real} (alias for Array{Real, 2}) julia&gt; using MultivariateStats, MLJMultivariateStatsInterface julia&gt; M = fit(PCA, X; maxoutdim = 3) MethodError: no method matching pcacov(::Matrix{Float64}, ::Vector{Real}; maxoutdim=3, pratio=0.99) Closest candidates are: pcacov(::AbstractMatrix{T}, ::AbstractVector{T}; maxoutdim, pratio) where T&lt;: Real at C:\Users\USER\.julia\packages\MultivariateStats\rCiqT\src\pca.jl:209 </code></pre>
[ { "answer_id": 74495080, "author": "Shayan", "author_id": 11747148, "author_profile": "https://Stackoverflow.com/users/11747148", "pm_score": 3, "selected": false, "text": "MultivariateStats v0.10.0 julia> using MultivariateStats\n\njulia> X = rand(5, 100);\n fit(PCA, X, maxoutdim=3)\nPCA(indim = 5, outdim = 3, principalratio = 0.6599153346885055)\n\nPattern matrix (unstandardized loadings):\n────────────────────────────────────\n PC1 PC2 PC3\n────────────────────────────────────\n1 0.201331 -0.0213382 0.0748083\n2 0.0394825 0.137933 0.213251\n3 0.14079 0.213082 -0.119594\n4 0.154639 -0.0585538 -0.0975059\n5 0.15221 -0.145161 0.0554158\n────────────────────────────────────\n\nImportance of components:\n─────────────────────────────────────────────────────────\n PC1 PC2 PC3\n─────────────────────────────────────────────────────────\nSS Loadings (Eigenvalues) 0.108996 0.0893847 0.0779532\nVariance explained 0.260295 0.21346 0.186161\nCumulative variance 0.260295 0.473755 0.659915\nProportion explained 0.394436 0.323466 0.282098\nCumulative proportion 0.394436 0.717902 1.0\n─────────────────────────────────────────────────────────\n\njulia> typeof(X)\nMatrix{Float64} (alias for Array{Float64, 2})\n\njulia> eltype(X)\nFloat64\n Matrix Float64 WeightedPCA julia> using WeightedPCA\n\njulia> X = rand(5, 100);\n pc1, pc2, pc3 = wpca.(Ref(collect(eachrow(X))), [1, 2, 3], Ref(UniformWeights()));\n X pkg> add https://github.com/dahong67/WeightedPCA.jl BetaML julia> using BetaML\n\njulia> X = rand(100, 5);\n\njulia> mod = PCA(max_unexplained_var=0.3)\nA PCA BetaMLModel (unfitted)\n\njulia> reproj_X = fit!(mod,X)\n100×4 Matrix{Float64}:\n 0.204151 -0.482558 -0.161929 0.222503\n 0.69425 -0.371519 -0.628404 0.462256\n 0.198191 -0.601537 -0.638573 0.463886\n ⋮ \n -0.00176858 0.557353 -0.4237 0.310565\n 0.533239 0.133691 -0.236009 -0.0793025\n 0.333652 -0.388115 -0.28662 0.481249\n\njulia> info(mod)\nDict{String, Any} with 5 entries:\n \"explained_var_by_dim\" => [0.277255, 0.484764, 0.669897, 0.846831, 1.0]\n \"fitted_records\" => 100\n \"prop_explained_var\" => 0.846831\n \"retained_dims\" => 4\n \"xndims\" => 5\n max_unexplained_var" }, { "answer_id": 74495088, "author": "Nils Gudat", "author_id": 2499892, "author_profile": "https://Stackoverflow.com/users/2499892", "pm_score": 2, "selected": false, "text": "AbstractMatrix{T} AbstractVector{T} T Matrix{Float64} Vector{Real} Vector{Real} X Matrix{Real} X Real float.(X) Float64" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74494901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20542850/" ]
74,494,913
<p>I'm looking to write something in XSLT 1.0 that achieves the following:</p> <p><strong>Input XML:</strong></p> <pre><code>&lt;parent&gt; &lt;header&gt; &lt;value1&gt;1&lt;/value1&gt; &lt;value2&gt;2&lt;/value2&gt; &lt;/header&gt; &lt;repeating&gt; &lt;repeat&gt; &lt;rvalue1&gt;1&lt;/rvalue1&gt; &lt;rvalue2&gt;2&lt;/rvalue2&gt; &lt;/repeat&gt; &lt;repeat&gt; &lt;rvalue1&gt;3&lt;/rvalue1&gt; &lt;rvalue2&gt;4&lt;/rvalue2&gt; &lt;/repeat&gt; &lt;repeat&gt; &lt;rvalue1&gt;5&lt;/rvalue1&gt; &lt;rvalue2&gt;6&lt;/rvalue2&gt; &lt;/repeat&gt; &lt;/repeating&gt; &lt;/parent&gt; </code></pre> <p><strong>Output XML:</strong></p> <pre><code>&lt;parent&gt; &lt;header&gt; &lt;value1&gt;1&lt;/value1&gt; &lt;value2&gt;2&lt;/value2&gt; &lt;/header&gt; &lt;repeating&gt; &lt;repeat&gt; &lt;rvalue1&gt;5&lt;/rvalue1&gt; &lt;rvalue2&gt;6&lt;/rvalue2&gt; &lt;/repeat&gt; &lt;/repeating&gt; &lt;/parent&gt; </code></pre> <p>The that I want to copy is always the last one in the list. Any help on how to do this would be great. Thank you!</p> <p>I tried using an identity template with a separate template match including something with last(), but couldn't get the result I wanted.</p>
[ { "answer_id": 74495045, "author": "michael.hor257k", "author_id": 3016153, "author_profile": "https://Stackoverflow.com/users/3016153", "pm_score": 1, "selected": true, "text": "<xsl:stylesheet version=\"1.0\" \nxmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n<xsl:output method=\"xml\" version=\"1.0\" encoding=\"UTF-8\" indent=\"yes\"/>\n<xsl:strip-space elements=\"*\"/>\n\n<!-- identity transform -->\n<xsl:template match=\"@*|node()\">\n <xsl:copy>\n <xsl:apply-templates select=\"@*|node()\"/>\n </xsl:copy>\n</xsl:template>\n\n<xsl:template match=\"repeating\">\n <xsl:copy>\n <xsl:apply-templates select=\"repeat[last()]\"/>\n </xsl:copy>\n</xsl:template>\n \n</xsl:stylesheet>\n" }, { "answer_id": 74495383, "author": "Martin Honnen", "author_id": 252228, "author_profile": "https://Stackoverflow.com/users/252228", "pm_score": 1, "selected": false, "text": "<xsl:stylesheet\n xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"\n version=\"1.0\">\n\n <xsl:template match=\"@* | node()\">\n <xsl:copy>\n <xsl:apply-templates select=\"@* | node()\"/>\n </xsl:copy>\n </xsl:template>\n\n <xsl:template match=\"repeating/repeat[not(position() = last())]\"/>\n\n</xsl:stylesheet>\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74494913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20542868/" ]
74,494,936
<p>I am trying to make the copy constructor of a class thread safe like this:</p> <pre><code>class Base { public: Base ( Base const &amp; other ) { std::lock_guard&lt;std::mutex&gt; lock ( other.m_Mutex ); ... } protected: std::mutex m_Mutex; } class Derived : public Base { public: Derived ( Derived const &amp; other ) : Base ( other ) { std::lock_guard&lt;std::mutex&gt; lock ( other.m_Mutex ); ... } } </code></pre> <p>My problem is that in the derived class I need to lock the mutex before the base class constructor call in the initializer list to guarantee consistency. Any idea how I could achieve that?</p> <p>Regards.</p>
[ { "answer_id": 74495226, "author": "Dmytro Ovdiienko", "author_id": 1145526, "author_profile": "https://Stackoverflow.com/users/1145526", "pm_score": 0, "selected": false, "text": "Base(Base const&, void*) #include <iostream>\n\nstruct Mutex\n{\n void lock() { std::cout << \"Lock\\n\"; }\n void unlock() { std::cout << \"Unlock\\n\"; }\n};\n\nstruct MutexLocker\n{\n MutexLocker() = default;\n MutexLocker(Mutex& mutex) { mutex.lock(); }\n};\n\nclass Base: private MutexLocker\n{\npublic:\n Base() {}\n\n virtual ~Base() = default;\n\n Base(Base const& other)\n : Base(other, nullptr)\n {\n mutex_.unlock();\n }\n \nprotected:\n // Implement copy logic here\n Base(Base const& other, void* tag)\n : MutexLocker(other.mutex_)\n {\n std::cout << \"Base\\n\";\n }\n\nprotected:\n mutable Mutex mutex_;\n};\n\nclass Derived: public Base\n{\npublic:\n Derived() = default;\n\n Derived(Derived const& other)\n : Derived(other, nullptr)\n {\n mutex_.unlock();\n }\n\nprotected:\n // Implement copy logic here\n Derived(Derived const& other, void* tag)\n : Base(other, tag)\n {\n std::cout << \"Derived\\n\";\n }\n};\n\nclass DerivedOfDerived: public Derived\n{\npublic:\n DerivedOfDerived() = default;\n\n DerivedOfDerived(DerivedOfDerived const& other)\n : DerivedOfDerived(other, nullptr)\n {\n mutex_.unlock();\n }\n\nprotected:\n // Implement copy logic here\n DerivedOfDerived(Derived const& other, void* tag)\n : Derived(other, tag)\n {\n std::cout << \"DerivedOfDerived\\n\";\n }\n};\n\nint main()\n{\n DerivedOfDerived d;\n DerivedOfDerived d2 {d};\n}\n" }, { "answer_id": 74495253, "author": "Nelfeal", "author_id": 3854570, "author_profile": "https://Stackoverflow.com/users/3854570", "pm_score": 0, "selected": false, "text": "m_Mutex Base Derived DerivedAgain Derived Derived Derived::make_copy() {\n std::lock_guard<std::mutex> lock(m_Mutex);\n return Derived(*from);\n}\n" }, { "answer_id": 74495466, "author": "davidhigh", "author_id": 2412846, "author_profile": "https://Stackoverflow.com/users/2412846", "pm_score": 4, "selected": true, "text": "class A\n{\nprivate:\n A(const A &a, const std::lock_guard<std::mutex> &)\n : i(a.i), i_squared(a.i_squared) {}\npublic:\n A(const A &a) : A(a, std::lock_guard<std::mutex>(a.mtx)) {}\n ...\n};\n class Base\n{\n public:\n Base(Base const& other) : Base(other, std::lock_guard<std::mutex>(other.m_Mutex)) {} \n virtual ~Base() = default; //virtual destructor!\n\n protected:\n Base(Base const& other, std::lock_guard<std::mutex> const&) {}\n\n mutable std::mutex m_Mutex; //should be mutable in order to be lockable from const-ref\n};\n\nclass Derived : public Base\n{\n protected:\n Derived(Derived const& other, std::lock_guard<std::mutex> const& lock)\n : Base(other, lock)\n {}\n\n public:\n Derived(Derived const& other)\n : Derived(other, std::lock_guard<std::mutex>(other.m_Mutex))\n {}\n};\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74494936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9069780/" ]
74,494,943
<p>inside a while loop all the if and elif statements are working except <code>elif user_choice.upper() == &quot;C&quot;</code></p> <p>I tried inputting the choice C and expected the program to print &quot;miles travelled&quot; but the program went and again asked for input</p> <pre><code># Game info print(&quot;Welcome to camel&quot;) print(&quot;You have stolen a camel too make your way across the great Mobi desert&quot;) print(&quot;The natives are chasing you and want their camel back. Survive and run out the natives&quot;) # Storing values in variables miles_travelled = 0 drinks_canteen = 3 natives_travelled = -20 camel_tiredness = 0 players_thirst = 0 done = False # Making the loop while not done: print(&quot;A. Drink from your canteen&quot;) print(&quot;B. Ahead moderate speed&quot;) print(&quot;C. Ahead full speed&quot;) print(&quot;D. Stop for the night&quot;) print(&quot;E. Status check&quot;) print(&quot;F. Quit&quot;) user_choice = input(&quot;Your choice? &quot;) if user_choice.upper() == &quot;A&quot;: if drinks_canteen == 0: print(&quot;No drinks in your canteen&quot;) user_choice = input(&quot;Your choice? &quot;) elif drinks_canteen != 0: drinks_canteen -= 1 elif user_choice.upper() == &quot;B&quot;: miles_travelled += 7 print(&quot;Miles travelled:&quot;, miles_travelled) players_thirst += 1 camel_tiredness += 1 natives_travelled += 9 elif user_choice.upper == &quot;C&quot;: miles_travelled += 15 print(&quot;Miles travelled:&quot;, miles_travelled) players_thirst += 1 camel_tiredness += 3 natives_travelled += 9 elif user_choice.upper() == &quot;D&quot;: camel_tiredness = 0 print(&quot;The camel is happy&quot;) natives_travelled += 9 elif user_choice.upper() == &quot;E&quot;: print(&quot;Miles travelled:&quot;, miles_travelled) print(&quot;Drinks in canteen:&quot;, drinks_canteen) print(&quot;The natives are&quot;, natives_travelled, &quot;behind you&quot;) elif user_choice.upper() == &quot;F&quot;: print(&quot;Game Ends&quot;) done = True elif 4 &lt; players_thirst &lt; 6: print(&quot;You are thirsty&quot;) elif players_thirst &gt; 6: print(&quot;You died of thirst&quot;) done = True elif 5 &lt; camel_tiredness &lt; 8: print(&quot;Your camel is getting tired&quot;) elif camel_tiredness &gt; 8: print(&quot;Your camel died&quot;) done = True elif miles_travelled == natives_travelled: print(&quot;The natives caught up&quot;) done = True elif miles_travelled &gt; 200: print(&quot;You won&quot;) done = True elif miles_travelled == natives_travelled + 15: print(&quot;The natives are getting close&quot;) </code></pre>
[ { "answer_id": 74495226, "author": "Dmytro Ovdiienko", "author_id": 1145526, "author_profile": "https://Stackoverflow.com/users/1145526", "pm_score": 0, "selected": false, "text": "Base(Base const&, void*) #include <iostream>\n\nstruct Mutex\n{\n void lock() { std::cout << \"Lock\\n\"; }\n void unlock() { std::cout << \"Unlock\\n\"; }\n};\n\nstruct MutexLocker\n{\n MutexLocker() = default;\n MutexLocker(Mutex& mutex) { mutex.lock(); }\n};\n\nclass Base: private MutexLocker\n{\npublic:\n Base() {}\n\n virtual ~Base() = default;\n\n Base(Base const& other)\n : Base(other, nullptr)\n {\n mutex_.unlock();\n }\n \nprotected:\n // Implement copy logic here\n Base(Base const& other, void* tag)\n : MutexLocker(other.mutex_)\n {\n std::cout << \"Base\\n\";\n }\n\nprotected:\n mutable Mutex mutex_;\n};\n\nclass Derived: public Base\n{\npublic:\n Derived() = default;\n\n Derived(Derived const& other)\n : Derived(other, nullptr)\n {\n mutex_.unlock();\n }\n\nprotected:\n // Implement copy logic here\n Derived(Derived const& other, void* tag)\n : Base(other, tag)\n {\n std::cout << \"Derived\\n\";\n }\n};\n\nclass DerivedOfDerived: public Derived\n{\npublic:\n DerivedOfDerived() = default;\n\n DerivedOfDerived(DerivedOfDerived const& other)\n : DerivedOfDerived(other, nullptr)\n {\n mutex_.unlock();\n }\n\nprotected:\n // Implement copy logic here\n DerivedOfDerived(Derived const& other, void* tag)\n : Derived(other, tag)\n {\n std::cout << \"DerivedOfDerived\\n\";\n }\n};\n\nint main()\n{\n DerivedOfDerived d;\n DerivedOfDerived d2 {d};\n}\n" }, { "answer_id": 74495253, "author": "Nelfeal", "author_id": 3854570, "author_profile": "https://Stackoverflow.com/users/3854570", "pm_score": 0, "selected": false, "text": "m_Mutex Base Derived DerivedAgain Derived Derived Derived::make_copy() {\n std::lock_guard<std::mutex> lock(m_Mutex);\n return Derived(*from);\n}\n" }, { "answer_id": 74495466, "author": "davidhigh", "author_id": 2412846, "author_profile": "https://Stackoverflow.com/users/2412846", "pm_score": 4, "selected": true, "text": "class A\n{\nprivate:\n A(const A &a, const std::lock_guard<std::mutex> &)\n : i(a.i), i_squared(a.i_squared) {}\npublic:\n A(const A &a) : A(a, std::lock_guard<std::mutex>(a.mtx)) {}\n ...\n};\n class Base\n{\n public:\n Base(Base const& other) : Base(other, std::lock_guard<std::mutex>(other.m_Mutex)) {} \n virtual ~Base() = default; //virtual destructor!\n\n protected:\n Base(Base const& other, std::lock_guard<std::mutex> const&) {}\n\n mutable std::mutex m_Mutex; //should be mutable in order to be lockable from const-ref\n};\n\nclass Derived : public Base\n{\n protected:\n Derived(Derived const& other, std::lock_guard<std::mutex> const& lock)\n : Base(other, lock)\n {}\n\n public:\n Derived(Derived const& other)\n : Derived(other, std::lock_guard<std::mutex>(other.m_Mutex))\n {}\n};\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74494943", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20542890/" ]
74,494,984
<pre><code>export class Ingredient { public name: string; public amount: number; constructor(name: string, amount: number) { this.name = name; this.amount = amount; } } </code></pre> <p><strong>My Array:</strong></p> <pre><code>export const initialState2: Ingredient[] = [ new Ingredient('Apples', 5), new Ingredient('Lemons', 10), new Ingredient('Cherries', 15), new Ingredient('Tangerines', 20), new Ingredient('Apricots', 25) ]; </code></pre> <p><strong>My NgRx Action:</strong></p> <pre><code>export const ADD_INGREDIENT2 = createAction( 'ADD_INGREDIENT2', props&lt;{ ingredient: Ingredient }&gt;() ); </code></pre> <p><strong>and my Reducer:</strong></p> <pre><code>export const shoppingListReducer = createReducer( initialState2, on( ShoppingListActions.ADD_INGREDIENT2, (state, ingredient) =&gt; ({ ...state, ingredients: [...state, ingredient] }) ) ); </code></pre> <p>I'm following a course about Angular. I want to do with the new version, new syntax what was done with the old version using switch/case in that course.</p> <p>I have an <strong>array</strong> and I want to work <strong>NgRx</strong>. <br/> I want to show the elements inside the array and then add new element to the array. <br/> but I failed. I'm probably making a mistake with some <strong>types</strong>. <br/> And my code at the bottom of the page is **working **but my code in the new version is not working.</p> <p><strong>Code in the course:</strong> works perfectly</p> <pre><code>export const initialState = { ingredients: [ new Ingredient('Apples', 5), new Ingredient('Lemons', 10), new Ingredient('Cherries', 15), new Ingredient('Tangerines', 20), new Ingredient('Apricots', 25) ] }; ________________________________________________________ export const ADD_INGREDIENT = 'ADD_INGREDIENT'; export class AddIngredient implements Action { readonly type = ADD_INGREDIENT; payload: Ingredient; } </code></pre> <pre><code>export function shoppingListReducer(state = initialState, action: ShoppingListActions.AddIngredient) { switch (action.type) { case ShoppingListActions.ADD_INGREDIENT: return { ...state, ingredients: [...state.ingredients, action.payload] }; default: return state; } } </code></pre>
[ { "answer_id": 74495226, "author": "Dmytro Ovdiienko", "author_id": 1145526, "author_profile": "https://Stackoverflow.com/users/1145526", "pm_score": 0, "selected": false, "text": "Base(Base const&, void*) #include <iostream>\n\nstruct Mutex\n{\n void lock() { std::cout << \"Lock\\n\"; }\n void unlock() { std::cout << \"Unlock\\n\"; }\n};\n\nstruct MutexLocker\n{\n MutexLocker() = default;\n MutexLocker(Mutex& mutex) { mutex.lock(); }\n};\n\nclass Base: private MutexLocker\n{\npublic:\n Base() {}\n\n virtual ~Base() = default;\n\n Base(Base const& other)\n : Base(other, nullptr)\n {\n mutex_.unlock();\n }\n \nprotected:\n // Implement copy logic here\n Base(Base const& other, void* tag)\n : MutexLocker(other.mutex_)\n {\n std::cout << \"Base\\n\";\n }\n\nprotected:\n mutable Mutex mutex_;\n};\n\nclass Derived: public Base\n{\npublic:\n Derived() = default;\n\n Derived(Derived const& other)\n : Derived(other, nullptr)\n {\n mutex_.unlock();\n }\n\nprotected:\n // Implement copy logic here\n Derived(Derived const& other, void* tag)\n : Base(other, tag)\n {\n std::cout << \"Derived\\n\";\n }\n};\n\nclass DerivedOfDerived: public Derived\n{\npublic:\n DerivedOfDerived() = default;\n\n DerivedOfDerived(DerivedOfDerived const& other)\n : DerivedOfDerived(other, nullptr)\n {\n mutex_.unlock();\n }\n\nprotected:\n // Implement copy logic here\n DerivedOfDerived(Derived const& other, void* tag)\n : Derived(other, tag)\n {\n std::cout << \"DerivedOfDerived\\n\";\n }\n};\n\nint main()\n{\n DerivedOfDerived d;\n DerivedOfDerived d2 {d};\n}\n" }, { "answer_id": 74495253, "author": "Nelfeal", "author_id": 3854570, "author_profile": "https://Stackoverflow.com/users/3854570", "pm_score": 0, "selected": false, "text": "m_Mutex Base Derived DerivedAgain Derived Derived Derived::make_copy() {\n std::lock_guard<std::mutex> lock(m_Mutex);\n return Derived(*from);\n}\n" }, { "answer_id": 74495466, "author": "davidhigh", "author_id": 2412846, "author_profile": "https://Stackoverflow.com/users/2412846", "pm_score": 4, "selected": true, "text": "class A\n{\nprivate:\n A(const A &a, const std::lock_guard<std::mutex> &)\n : i(a.i), i_squared(a.i_squared) {}\npublic:\n A(const A &a) : A(a, std::lock_guard<std::mutex>(a.mtx)) {}\n ...\n};\n class Base\n{\n public:\n Base(Base const& other) : Base(other, std::lock_guard<std::mutex>(other.m_Mutex)) {} \n virtual ~Base() = default; //virtual destructor!\n\n protected:\n Base(Base const& other, std::lock_guard<std::mutex> const&) {}\n\n mutable std::mutex m_Mutex; //should be mutable in order to be lockable from const-ref\n};\n\nclass Derived : public Base\n{\n protected:\n Derived(Derived const& other, std::lock_guard<std::mutex> const& lock)\n : Base(other, lock)\n {}\n\n public:\n Derived(Derived const& other)\n : Derived(other, std::lock_guard<std::mutex>(other.m_Mutex))\n {}\n};\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74494984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17708807/" ]
74,494,997
<p>I have two tables</p> <p><strong>Account table</strong></p> <pre><code>id | account_no ----------------------- 1 | 111 2 | 222 </code></pre> <p><strong>Account details</strong></p> <pre><code>id | act_id (fk) | amount | created_dt_ | created_by ------------------------------------------------ 1 | 1 | 10 | 2022-10-30 | SYSTEM 2 | 1 | 100 | 2022-11-05 | user1 3 | 1 | 144 | 2022-11-10 | user2 4 | 1 | 156 | 2022-11-16 | user3 5 | 2 | 50 | 2022-11-05 | SYSTEM 6 | 2 | 51 | 2022-11-10 | user2 7 | 3 | 156 | 2022-11-16 | SYSTEM </code></pre> <p>I need a query to fetch only rows from account details which has at least 2 records for an account id, and merge those rows to a single row showcasing the initial amount and user who created it and the last amount and who created it, something like this</p> <pre><code>act_id | ini_amt | ini_dt | ini_usr | fnl_amt | fnl_dt | fnl_usr ------------------------------------------------------------------------------------- 1 | 10 | 2022-10-30 | SYSTEM | 156 | 2022-11-16 | user3 2 | 50 | 2022-11-05 | SYSTEM | 51 | 2022-11-10 | user2 </code></pre> <p>we need only the rows with more than one records. How do i fetch that?</p>
[ { "answer_id": 74495202, "author": "nbk", "author_id": 5193536, "author_profile": "https://Stackoverflow.com/users/5193536", "pm_score": 3, "selected": true, "text": "CREATE TABLE Account \n (`id` int, `account_no` int)\n;\n \nINSERT INTO Account \n (`id`, `account_no`)\nVALUES\n (1, 111),\n (2, 222)\n;\n\n Records: 2 Duplicates: 0 Warnings: 0\n CREATE TABLE Account_details\n (`id` int, `act_id` int, `amount` int, `created_dt_` varchar(10), `created_by` varchar(6))\n;\n \nINSERT INTO Account_details\n (`id`, `act_id`, `amount`, `created_dt_`, `created_by`)\nVALUES\n (1, 1, 10, '2022-10-30', 'SYSTEM'),\n (2, 1, 100, '2022-11-05', 'user1'),\n (3, 1, 144, '2022-11-10', 'user2'),\n (4, 1, 156, '2022-11-16', 'user3'),\n (5, 2, 50, '2022-11-05', 'SYSTEM'),\n (6, 2, 51, '2022-11-10', 'user2'),\n (7, 3, 156, '2022-11-16', 'SYSTEM')\n;\n Records: 7 Duplicates: 0 Warnings: 0\n WITH CTE_MIN as(\n SELECT\n `act_id`, `amount`, `created_dt_`, `created_by`,\n ROW_NUMBER() OVER(PARTITION BY `act_id` ORDER BY `created_dt_` ASC,`id` ASC) rn\n FROM Account_details),\n CTE_MAX as(\n SELECT\n `act_id`, `amount`, `created_dt_`, `created_by`,\n ROW_NUMBER() OVER(PARTITION BY `act_id` ORDER BY `created_dt_` DESC,`id` DESC) rn\n FROM Account_details)\nSELECT\n mi.`act_id`, mi.`amount`, mi.`created_dt_`, mi.`created_by`, ma.`amount`, ma.`created_dt_`, ma.`created_by`\n FROM\nCTE_MIN mi JOIN CTE_MAX ma \n ON mi.`act_id` = ma.`act_id` \n AND mi.rn = ma.rn \n AND mi.created_dt_!=ma.created_dt_\nAND ma.rn = 1 ANd mi.rn = 1\n" }, { "answer_id": 74495296, "author": "Ergest Basha", "author_id": 16461952, "author_profile": "https://Stackoverflow.com/users/16461952", "pm_score": 0, "selected": false, "text": "select act_id,\n max(case when new_col='min_value' then amount end) as ini_amt,\n max(case when new_col='min_value' then created_dt end) as ini_dt,\n max(case when new_col='min_value' then created_by end) as ini_usr,\n max(case when new_col='max_value' then amount end) as fnl_amt,\n max(case when new_col='max_value' then created_dt end) as fnl_dt,\n max(case when new_col='max_value' then created_by end) as fnl_usr\n from ( \n\n select ad.id,ad.act_id,ad.amount,ad.created_dt,ad.created_by,'max_value' as new_col\n from AccountDetails ad\n inner join (select act_id,max(created_dt) as max_created_dt\n from AccountDetails\n group by act_id\n having count(*) >=2\n ) as max_val on max_val.act_id =ad.act_id and max_val.max_created_dt=ad.created_dt\n union \n select ad1.id,ad1.act_id,ad1.amount,ad1.created_dt,ad1.created_by,'min_value'\n from AccountDetails ad1\n inner join (select act_id,min(created_dt) as min_created_dt\n from AccountDetails\n group by act_id\n having count(*) >=2\n ) as min_val on min_val.act_id =ad1.act_id and min_val.min_created_dt=ad1.created_dt\n ) as tbl\ngroup by act_id;\n" }, { "answer_id": 74495299, "author": "GMB", "author_id": 10676716, "author_profile": "https://Stackoverflow.com/users/10676716", "pm_score": 0, "selected": false, "text": "select act_id,\n max(case when rn_asc = 1 then amount end) ini_amount,\n max(case when rn_asc = 1 then created_dt end) ini_created_dt,\n max(case when rn_asc = 1 then created_by end) ini_created_by,\n max(case when rn_desc = 1 then amount end) fnl_amount,\n max(case when rn_desc = 1 then created_dt end) fnl_created_dt,\n max(case when rn_desc = 1 then created_by end) fnl_created_by\nfrom(\n select ad.*,\n row_number() over(partition by act_id order by created_dt ) rn_asc,\n row_number() over(partition by act_id order by created_dt desc) rn_desc,\n count(*) over(partition by act_id) cnt \n from account_details ad\n) ad\nwhere 1 in (rn_asc, rn_desc) and cnt > 1\ngroup by act_id\n row_number count group by" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74494997", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17491052/" ]
74,495,015
<p>Can you help me with my code bellow? Can't seem to figure out how to loop through all the elements in array to change their background color from green to orange and back again on click. What I want it to do is change the background color of each specific div to orange on click and back to green again..and so on. What am I doing wrong?</p> <p>//HTML</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en-US&quot;&gt; &lt;head&gt; &lt;title&gt;Working With JavaScript Functions&lt;/title&gt; &lt;link href=&quot;index.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt; &lt;script src=&quot;https://code.jquery.com/jquery-3.5.1.slim.js&quot; integrity=&quot;sha256-DrT5NfxfbHvMHux31Lkhxg42LY6of8TaYyK50jnxRnM=&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id='testA' style=&quot;background-color: green;&quot; class=&quot;box&quot;&gt;&lt;/div&gt; &lt;div id='testB' style=&quot;background-color: green;&quot; class=&quot;box&quot;&gt;&lt;/div&gt; &lt;div id='testC' style=&quot;background-color: green;&quot; class=&quot;box&quot;&gt;&lt;/div&gt; &lt;div id='testD' style=&quot;background-color: green;&quot; class=&quot;box&quot;&gt;&lt;/div&gt; &lt;div id='testE' style=&quot;background-color: green;&quot; class=&quot;box&quot;&gt;&lt;/div&gt; &lt;div id='testF' style=&quot;background-color: green;&quot; class=&quot;box&quot;&gt;&lt;/div&gt; &lt;script src=&quot;index.js&quot;&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>//CSS</p> <pre><code>.box { width: 75px; height: 75px; margin: 1rem; display: inline-block; } </code></pre> <p>//javascript</p> <pre><code>let greenBox = document.getElementsByClassName('box'); function boxClicked(event) { for (let i = 0; i &lt;=greenBox.length; i++){ if (greenBox[i].style.backgroundColor === 'green') { greenBox[i].style.backgroundColor = 'orange'; } else { greenBox[i].style.backgroundColor = 'green'; } } } greenBox.addEventListener('click', boxClicked); </code></pre>
[ { "answer_id": 74495340, "author": "Olamide Samuel", "author_id": 19979182, "author_profile": "https://Stackoverflow.com/users/19979182", "pm_score": 1, "selected": false, "text": "assEventListener greenBox onClick <div id='testA' style=\"background-color: green;\" class=\"box\" onClick=\"boxClicked()\"></div>\n<div id='testB' style=\"background-color: green;\" class=\"box\" onClick=\"boxClicked()\"></div>\n<div id='testC' style=\"background-color: green;\" class=\"box\" onClick=\"boxClicked()\"></div>\n<div id='testD' style=\"background-color: green;\" class=\"box\" onClick=\"boxClicked()\"></div>\n<div id='testE' style=\"background-color: green;\" class=\"box\" onClick=\"boxClicked()\"></div>\n<div id='testF' style=\"background-color: green;\" class=\"box\" onClick=\"boxClicked()\"></div>\n" }, { "answer_id": 74495398, "author": "Bhavya Dhiman", "author_id": 4167172, "author_profile": "https://Stackoverflow.com/users/4167172", "pm_score": 2, "selected": false, "text": "let greenBox = document.getElementsByClassName('box');\n\nfor (const g of greenBox) {\n g.addEventListener('click', boxClicked);\n}\n\nfunction boxClicked(event) {\n event.target.style.backgroundColor = event.target.style.backgroundColor === 'green' ? 'orange' : 'green';\n}\n" }, { "answer_id": 74495463, "author": "damonholden", "author_id": 17670742, "author_profile": "https://Stackoverflow.com/users/17670742", "pm_score": 1, "selected": true, "text": "HTMLCollection .box .box srcElement event greenBox boxes const boxes = document.getElementsByClassName('box');\n\nfor (let box of boxes) {\n box.addEventListener('click', boxClicked);\n}\n\nfunction boxClicked(event) {\n event.srcElement.style.backgroundColor =\n event.srcElement.style.backgroundColor === 'green' ? 'orange' : 'green';\n}\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20542861/" ]
74,495,030
<p>I want to calculate grouped means of multiple columns in a dataframe. In the process, I will want to retain non-numeric columns that don't vary across with the grouping variable. Here's a simple example.</p> <pre><code>library(dplyr) #create data frame df &lt;- data.frame(team=c('A', 'A', 'B', 'B', 'B', 'C', 'C'), state=c('Michigan', 'Michigan', 'Michigan', 'Michigan', 'Michigan','AL', 'AL'), region=c('Midwest', 'Midwest', 'Midwest', 'Midwest', 'Midwest', 'South', 'South'), pts=c(5, 8, 14, 18, 5, 7, 7), rebs=c(8, 8, 9, 3, 8, 7, 4), ast=c(8,6,7,5,3,0,9)) </code></pre> <p>The resulting data field:</p> <pre><code>&gt; df team state region pts rebs ast 1 A Michigan Midwest 5 8 8 2 A Michigan Midwest 8 8 6 3 B Michigan Midwest 14 9 7 4 B Michigan Midwest 18 3 5 5 B Michigan Midwest 5 8 3 6 C Alabama South 7 7 0 7 C Alabama South 7 4 9 </code></pre> <p>Summarizing by mean with 'team' as the grouping variable is straightforward enough:</p> <pre><code>&gt; df %&gt;% + group_by(team) %&gt;% + summarise_at(vars(pts, rebs, ast), list(mean)) # A tibble: 3 × 4 team pts rebs ast &lt;chr&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; 1 A 6.5 8 7 2 B 12.3 6.67 5 3 C 7 5.5 4.5 </code></pre> <p>But how do I retain those other ID columns (that don't change across within-team stats). In other words, how do I get the following:</p> <pre><code> team state region pts rebs ast &lt;chr&gt; &lt;chr&gt; &lt;chr&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; 1 A Michigan Midwest 6.5 8 7 2 B Michigan Midwest 12.3 6.67 5 3 C Alabama South 7 5.5 4.5 </code></pre> <p>Thanks!!</p>
[ { "answer_id": 74495062, "author": "asd-tm", "author_id": 5043424, "author_profile": "https://Stackoverflow.com/users/5043424", "pm_score": 3, "selected": true, "text": "group_by() group_by() df %>%\n group_by(team, state, region) %>%\n summarise_at(vars(pts, rebs, ast), list(mean))\n" }, { "answer_id": 74495288, "author": "Neeraj", "author_id": 5047311, "author_profile": "https://Stackoverflow.com/users/5047311", "pm_score": 2, "selected": false, "text": "data.table setDT(df)\nvars = c(\"pts\", \"rebs\", \"ast\")\ndf[, (vars) := lapply(.SD, mean, na.rm = T), .SDcols = vars, by = \"team\"][, .SD[1], by = \"team\"]\n team state region pts rebs ast\n1: A Michigan Midwest 6.50000 8.000000 7.0\n2: B Michigan Midwest 12.33333 6.666667 5.0\n3: C AL South 7.00000 5.500000 4.5 \n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7138264/" ]
74,495,037
<p>It isn't difficult to find information on the big-O time behavior of stl container operations. However, we operate in a hard real-time environment, and I'm having a lot more trouble finding information on their heap memory usage behavior.</p> <p>In particular I had a developer come to me asking about std::unordered_map. We're allowed to be non-realtime at startup, so he was hoping to perform a .reserve() at startup time. However, he's finding he gets overruns at runtime. The operations he uses are lookups, insertions, and deletions with .erase().</p> <p>I'm a little worried about that .reserve() actually preventing later runtime memory allocations (I don't really understand the explanation of what it does wrt to heap usage), but .erase() in particular I don't see any guarantee whatsoever that it won't be asking the heap for a dynamic deallocation when called.</p> <p>So the question is what's the specified heap interactions (if any) for std::unordered_map::erase, and if it actually does deallocations, if there's some kind of trick that can be used to avoid them?</p>
[ { "answer_id": 74495062, "author": "asd-tm", "author_id": 5043424, "author_profile": "https://Stackoverflow.com/users/5043424", "pm_score": 3, "selected": true, "text": "group_by() group_by() df %>%\n group_by(team, state, region) %>%\n summarise_at(vars(pts, rebs, ast), list(mean))\n" }, { "answer_id": 74495288, "author": "Neeraj", "author_id": 5047311, "author_profile": "https://Stackoverflow.com/users/5047311", "pm_score": 2, "selected": false, "text": "data.table setDT(df)\nvars = c(\"pts\", \"rebs\", \"ast\")\ndf[, (vars) := lapply(.SD, mean, na.rm = T), .SDcols = vars, by = \"team\"][, .SD[1], by = \"team\"]\n team state region pts rebs ast\n1: A Michigan Midwest 6.50000 8.000000 7.0\n2: B Michigan Midwest 12.33333 6.666667 5.0\n3: C AL South 7.00000 5.500000 4.5 \n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495037", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29639/" ]
74,495,056
<p>Here's an example of what I'm trying to do...</p> <p>Let's say I have the number 73,284.</p> <p>The number of <strong>thousands</strong> is 73 (73,284 divided by 1,000).</p> <p>The number of <strong>hundreds</strong> is 2 (284 divided by 100).</p> <p>The number of <strong>tens</strong> is 8 (84 divided by 10).</p> <p>The number of <strong>singles</strong> is 4 (4 is left).</p> <p>What I need is a Javascript function that would take the number 73,284 and create 4 numbers from it using the criteria above.</p> <p>So if the number was 73,284, I'd pass that number into the function as a parameter and the function would return an array that looks like this, [73,2,8,4].</p> <p>I tried to use the Math.round() function. It seemed to work for the thousands, but not necessarily for the hundreds, tens, and singles.</p>
[ { "answer_id": 74495189, "author": "Jamiec", "author_id": 219661, "author_profile": "https://Stackoverflow.com/users/219661", "pm_score": 1, "selected": true, "text": "function get(num){\n const thousands = Math.floor(num/1000)\n const hundreds = Math.floor((num-thousands*1000)/100);\n const tens = Math.floor((num-thousands*1000-hundreds*100)/10);\n const units = Math.floor(num-thousands*1000-hundreds*100-tens*10)\n return [\n thousands,\n hundreds,\n tens,\n units\n ]\n}\n\nconst [th,hu,te,un] = get(73284)\n\nconsole.log(\"Thousands=\",th);\nconsole.log(\"Hundreds=\",hu);\nconsole.log(\"Tens=\",te);\nconsole.log(\"Units=\",un);" }, { "answer_id": 74495196, "author": "Toban Harnish", "author_id": 20427085, "author_profile": "https://Stackoverflow.com/users/20427085", "pm_score": -1, "selected": false, "text": "function test(num) {\n const arr = num.toLocaleString().split(',');\n arr[arr.length-1].toString().split('').map(x=>arr.push(x));\n arr[arr.length-4]=0;\n return arr.map(x=>+x).filter(x=>x);\n}\ntest(1234); // [1,2,3,4]\ntest(73284); // [73,2,8,4]\n" }, { "answer_id": 74495211, "author": "Johnny Mopp", "author_id": 669576, "author_profile": "https://Stackoverflow.com/users/669576", "pm_score": 1, "selected": false, "text": "const f = (n) => {\n let div = 1000;\n const result = [];\n for (let i = 0; i < 4 && n; i++, n %= div, div /= 10) {\n result.push(Math.floor(n / div));\n }\n return result;\n}\nconsole.log(f(73284));" }, { "answer_id": 74495320, "author": "Nicolas", "author_id": 5784924, "author_profile": "https://Stackoverflow.com/users/5784924", "pm_score": 0, "selected": false, "text": "Math.floor % Math.floor const input = 73284\nconst divider = 1000\n\nconst amoutOfDividerInInput = input / divider .\n// this returns 73.284, we don't want the .284 so we can use Math.floor.\n\nconst amountOfDividerInInputWithoutDecimal = Math.floor(amoutOfDividerInInput)\n\n// we print the value\nconsole.log(\"there are \" + amountOfDividerInInputWithoutDecimal + \" 1000s in \" + input).\n const input = 73284\nconst divider = 1000\n\nconst reminderOfTheDivision = input % divider;\n// this gives us 284.\n // we devide the divider by 10, \nconst newDevider = divider / 10;\n\n// we calculate the new amount and reminder\nconst amoutOfNewDividerInInput = Math.floor(reminderOfTheDivision / newDivider );\n\nconst reminderOfTheNewDivision = reminderOfTheDivision % newDivider\n\n// we print the new values\nconsole.log(\"There are \" + amoutOfNewDividerInInput + \" 100s in\" + input)\n function findDividingQuantity(reminder, divider) {\n // if the devider is less than 10, we simply print the reminder.\n if(divider < 10) {\n console.log('and ' + reminder + ' remains.');\n // and we returns to stop the recursion.\n return;\n }\n \n // otherwise, we get the current amount of the divider in the reminder.\n const amount = Math.floor(reminder / divider);\n \n // we then calculate how much is left after the first division,\n // this will become our new reminder.\n const newReminder = reminder % divider;\n \n // knowing how many of the divider there is in the input, we can print it.\n console.log(amount + \" \" + divider + \"s.\");\n \n // we call the function again, but with the new reminder\n // and the divider divided by 10\n findDividingQuantity(newReminder, divider / 10)\n}\n\nconst input = 73284\n\nconsole.log(\"In \" + input + \" there is: \");\n// we call the function with the initial divider: 1000.\nfindDividingQuantity(input, 1000)" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20472594/" ]
74,495,075
<p>Every day I run a pipeline that runs a Copy Data activity (DB2 =&gt; Parquet file).</p> <p>How can I store the &quot;Last execution date&quot; of this activity?</p> <p>Is there a best practice solution?</p> <p>Because it would be unfortunate if we must do this in the old school way (store the date in a text file, or SQL Table, ...)</p> <p>Thanks.</p>
[ { "answer_id": 74495189, "author": "Jamiec", "author_id": 219661, "author_profile": "https://Stackoverflow.com/users/219661", "pm_score": 1, "selected": true, "text": "function get(num){\n const thousands = Math.floor(num/1000)\n const hundreds = Math.floor((num-thousands*1000)/100);\n const tens = Math.floor((num-thousands*1000-hundreds*100)/10);\n const units = Math.floor(num-thousands*1000-hundreds*100-tens*10)\n return [\n thousands,\n hundreds,\n tens,\n units\n ]\n}\n\nconst [th,hu,te,un] = get(73284)\n\nconsole.log(\"Thousands=\",th);\nconsole.log(\"Hundreds=\",hu);\nconsole.log(\"Tens=\",te);\nconsole.log(\"Units=\",un);" }, { "answer_id": 74495196, "author": "Toban Harnish", "author_id": 20427085, "author_profile": "https://Stackoverflow.com/users/20427085", "pm_score": -1, "selected": false, "text": "function test(num) {\n const arr = num.toLocaleString().split(',');\n arr[arr.length-1].toString().split('').map(x=>arr.push(x));\n arr[arr.length-4]=0;\n return arr.map(x=>+x).filter(x=>x);\n}\ntest(1234); // [1,2,3,4]\ntest(73284); // [73,2,8,4]\n" }, { "answer_id": 74495211, "author": "Johnny Mopp", "author_id": 669576, "author_profile": "https://Stackoverflow.com/users/669576", "pm_score": 1, "selected": false, "text": "const f = (n) => {\n let div = 1000;\n const result = [];\n for (let i = 0; i < 4 && n; i++, n %= div, div /= 10) {\n result.push(Math.floor(n / div));\n }\n return result;\n}\nconsole.log(f(73284));" }, { "answer_id": 74495320, "author": "Nicolas", "author_id": 5784924, "author_profile": "https://Stackoverflow.com/users/5784924", "pm_score": 0, "selected": false, "text": "Math.floor % Math.floor const input = 73284\nconst divider = 1000\n\nconst amoutOfDividerInInput = input / divider .\n// this returns 73.284, we don't want the .284 so we can use Math.floor.\n\nconst amountOfDividerInInputWithoutDecimal = Math.floor(amoutOfDividerInInput)\n\n// we print the value\nconsole.log(\"there are \" + amountOfDividerInInputWithoutDecimal + \" 1000s in \" + input).\n const input = 73284\nconst divider = 1000\n\nconst reminderOfTheDivision = input % divider;\n// this gives us 284.\n // we devide the divider by 10, \nconst newDevider = divider / 10;\n\n// we calculate the new amount and reminder\nconst amoutOfNewDividerInInput = Math.floor(reminderOfTheDivision / newDivider );\n\nconst reminderOfTheNewDivision = reminderOfTheDivision % newDivider\n\n// we print the new values\nconsole.log(\"There are \" + amoutOfNewDividerInInput + \" 100s in\" + input)\n function findDividingQuantity(reminder, divider) {\n // if the devider is less than 10, we simply print the reminder.\n if(divider < 10) {\n console.log('and ' + reminder + ' remains.');\n // and we returns to stop the recursion.\n return;\n }\n \n // otherwise, we get the current amount of the divider in the reminder.\n const amount = Math.floor(reminder / divider);\n \n // we then calculate how much is left after the first division,\n // this will become our new reminder.\n const newReminder = reminder % divider;\n \n // knowing how many of the divider there is in the input, we can print it.\n console.log(amount + \" \" + divider + \"s.\");\n \n // we call the function again, but with the new reminder\n // and the divider divided by 10\n findDividingQuantity(newReminder, divider / 10)\n}\n\nconst input = 73284\n\nconsole.log(\"In \" + input + \" there is: \");\n// we call the function with the initial divider: 1000.\nfindDividingQuantity(input, 1000)" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6565296/" ]
74,495,081
<p>I bumped into some unexpected behavior when trying to refer to a variable outside of an event handler.</p> <p>Below is function called <code>update</code> that joins data with div elements. In this case, there's only one data point, so only one div element is rendered. The function also takes in a number <code>currentState</code> as an argument. The div element has a click event listener, which prints out the <code>currentState</code> number and increments a global variable <code>state</code> by 1. The original value of <code>state</code> is 5. Then the click handler calls <code>update</code> with the incremented <code>state</code> as a parameter.</p> <p>When the div is clicked, <code>currentState</code> that's passed into <code>update</code> increments as expected. This is evident from the output of <code>console.log(&quot;update called. currentState: &quot;, currentState)</code>.</p> <p>However, inside of the 'click' event handler, <code>currentState</code> remains at 5 regardless of how many times the div element is clicked.</p> <p>Correct me if I'm wrong, but it seems to me that when the 'click' event listener is created in D3, it holds onto whatever context existed at that time. And because that listener is attached to the div only when it first enters the DOM, that context is never updated.</p> <p>An easy fix for this issue is just not to attach the click listener on the enter selection, but rather outside of the call to <code>join</code>. That way, the listener will be updated each time <code>update</code> is called.</p> <p>I basically have two questions. I wanted to confirm whether I'm correctly understanding what's happening. And second, is this behavior in D3 favorable? Perhaps I'm missing an advantage to it. Although this example's a bit contrived, I would have liked for the click handler to refer to the value of <code>currentState</code> that gets updated with each call to <code>update</code>. Or is it not good practice to attach listeners on the enter selection?</p> <pre><code>const data = ['randomString'] let state = 5 function update (currentState) { console.log(&quot;update called. currentState: &quot;, currentState) d3.selectAll('div') .data(data) .join(enter =&gt; enter.append('div') .style('width', '50px') .style('height', '50px') .style('background', 'red') .on('click', function () { console.log(&quot;click event. currentState: &quot;, currentState) state += 1 update(state) })) } update(state) </code></pre>
[ { "answer_id": 74495920, "author": "Slava Knyazev", "author_id": 4088472, "author_profile": "https://Stackoverflow.com/users/4088472", "pm_score": 2, "selected": false, "text": "on d3.selectAll('div')\n .data(data)\n // ...\n .join(enter => enter.append('div')\n .on('click', function () {\n console.log(\"click event. currentState: \", currentState)\n state += 1\n update(state)\n }))\n div data div data div currentState div data" }, { "answer_id": 74504825, "author": "Gerardo Furtado", "author_id": 5768908, "author_profile": "https://Stackoverflow.com/users/5768908", "pm_score": 2, "selected": true, "text": "foo currentState foo update currentState foo 5 5 6 7 let state = 5;\nconst obj = {};\n\nfunction update(currentState) {\n if (!obj.foo) obj.foo = () => console.log(currentState);\n obj.foo();\n state += 1;\n};\n\nupdate(state);\nupdate(state);\nupdate(state);" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495081", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14013352/" ]
74,495,085
<p>I am trying to generate 6 boxplots displaying Fish Abundances of 3 different sites displayed for each site between 2 seasons separately using faced_grid.</p> <p>I want to add Tukey HSD results on each single boxplot, but when I try, I always get the results of the dry season displayed.</p> <p>Can someone help me out?</p>
[ { "answer_id": 74495920, "author": "Slava Knyazev", "author_id": 4088472, "author_profile": "https://Stackoverflow.com/users/4088472", "pm_score": 2, "selected": false, "text": "on d3.selectAll('div')\n .data(data)\n // ...\n .join(enter => enter.append('div')\n .on('click', function () {\n console.log(\"click event. currentState: \", currentState)\n state += 1\n update(state)\n }))\n div data div data div currentState div data" }, { "answer_id": 74504825, "author": "Gerardo Furtado", "author_id": 5768908, "author_profile": "https://Stackoverflow.com/users/5768908", "pm_score": 2, "selected": true, "text": "foo currentState foo update currentState foo 5 5 6 7 let state = 5;\nconst obj = {};\n\nfunction update(currentState) {\n if (!obj.foo) obj.foo = () => console.log(currentState);\n obj.foo();\n state += 1;\n};\n\nupdate(state);\nupdate(state);\nupdate(state);" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
74,495,116
<p>I have this df with 9 columns</p> <pre><code> x y1_x y2_x y3_x y4_x 0 -17.7 -0.785430 NaN NaN NaN 1 -15.0 NaN NaN NaN -3820.085000 2 -12.5 NaN NaN 2.138833 NaN 3 -12.4 NaN NaN 1.721205 NaN 4 -12.1 NaN 2.227343 2.227343 NaN d1 d2 d3 d4 0 0.053884 NaN NaN NaN 1 NaN NaN NaN 0.085000 2 NaN NaN 0.143237 NaN 3 NaN NaN 0.251180 NaN 4 NaN 0.127343 0.440931 NaN </code></pre> <p>Between <code>y1_x</code> and <code>y4_x</code> I can only have 1 non <code>NaN</code> value per row.</p> <p>The condition to choose which value is removed is explained in this <strong>example:</strong></p> <p>In row <code>4</code> there are 2 values between <code>y1_x</code> and <code>y4_x</code></p> <p>The value that becomes <code>NaN</code> is the one from <code>y3_x</code> because in that same row, <code>d3 &gt; d2</code></p>
[ { "answer_id": 74495920, "author": "Slava Knyazev", "author_id": 4088472, "author_profile": "https://Stackoverflow.com/users/4088472", "pm_score": 2, "selected": false, "text": "on d3.selectAll('div')\n .data(data)\n // ...\n .join(enter => enter.append('div')\n .on('click', function () {\n console.log(\"click event. currentState: \", currentState)\n state += 1\n update(state)\n }))\n div data div data div currentState div data" }, { "answer_id": 74504825, "author": "Gerardo Furtado", "author_id": 5768908, "author_profile": "https://Stackoverflow.com/users/5768908", "pm_score": 2, "selected": true, "text": "foo currentState foo update currentState foo 5 5 6 7 let state = 5;\nconst obj = {};\n\nfunction update(currentState) {\n if (!obj.foo) obj.foo = () => console.log(currentState);\n obj.foo();\n state += 1;\n};\n\nupdate(state);\nupdate(state);\nupdate(state);" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20458338/" ]
74,495,136
<p>I have a problem with the combobox.SelectedIndex function. The problem is that in void and static void it just returns a -1. Now before anyone comes and says if there is anything in it at all, yes it is, I've debugged the code and found that it only returns a -1 in static void and void , now I'm curious as to why it doesn't work, actually a very simple code.</p> <pre><code> void writecombo() { int CURRENT_LOG = combo.SelectedIndex; //&lt; -1 Globals.LG[CURRENT_LOG] += &quot;Hello!&quot; + Environment.NewLine; //Crash, because it is -1 ... } </code></pre> <p>Where it works:</p> <pre><code> private void textbox1_KeyDown(object sender, KeyEventArgs e) { if (GetAsyncKeyState(Keys.Enter) &lt; 0) { int CURRENT_LOG = combo.SelectedIndex; // Not Null Globals.LG[CURRENT_LOG] += &quot;Hello!&quot; + Environment.NewLine; ... } } </code></pre> <p>I would be happy to get help and also if someone could explain to me why this is the case :)</p> <p>EDIT: The problem only comes when I want to access this void from a static void, I wanted to use it to access the objects in form1 in a static. (var from = new Form1) <a href="https://github.com/TheFrieber/MRE" rel="nofollow noreferrer">MRE</a></p>
[ { "answer_id": 74495920, "author": "Slava Knyazev", "author_id": 4088472, "author_profile": "https://Stackoverflow.com/users/4088472", "pm_score": 2, "selected": false, "text": "on d3.selectAll('div')\n .data(data)\n // ...\n .join(enter => enter.append('div')\n .on('click', function () {\n console.log(\"click event. currentState: \", currentState)\n state += 1\n update(state)\n }))\n div data div data div currentState div data" }, { "answer_id": 74504825, "author": "Gerardo Furtado", "author_id": 5768908, "author_profile": "https://Stackoverflow.com/users/5768908", "pm_score": 2, "selected": true, "text": "foo currentState foo update currentState foo 5 5 6 7 let state = 5;\nconst obj = {};\n\nfunction update(currentState) {\n if (!obj.foo) obj.foo = () => console.log(currentState);\n obj.foo();\n state += 1;\n};\n\nupdate(state);\nupdate(state);\nupdate(state);" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14595777/" ]
74,495,142
<p>i have the following code data...</p> <pre><code>import pandas as pd, numpy as np from datetime import datetime end_dt = datetime.today() st_dt = (end_dt + pd.DateOffset(-10)).date() df_index = pd.date_range(st_dt, end_dt) df = pd.DataFrame(index=df_index, columns=['in_range']) data = [pd.to_datetime(['2022-11-08','2022-11-10']), pd.to_datetime(['2022-11-13','2022-11-15'])] dt_ranges = pd.DataFrame(data,columns={'st_dt':'datetimens[64]', 'end_dt': 'datetimens[64]'}) </code></pre> <p>this produces the following two dataframes:<br /> df:</p> <pre><code> in_range 2022-11-08 NaN 2022-11-09 NaN 2022-11-10 NaN 2022-11-11 NaN 2022-11-12 NaN 2022-11-13 NaN 2022-11-14 NaN 2022-11-15 NaN 2022-11-16 NaN 2022-11-17 NaN 2022-11-18 NaN </code></pre> <p>and date_ranges:</p> <pre><code> st_dt end_dt 0 2022-11-08 2022-11-10 1 2022-11-13 2022-11-15 </code></pre> <p>I would like to update the 'in_range' column to indicate if the index falls within any of the pairs of start and end dates of the 2nd dataframe. so i should end up with this:</p> <pre><code> in_range 2022-11-08 True 2022-11-09 True 2022-11-10 True 2022-11-11 NaN 2022-11-12 NaN 2022-11-13 True 2022-11-14 True 2022-11-15 True 2022-11-16 NaN 2022-11-17 NaN 2022-11-18 NaN </code></pre> <p>I've gone down the path of trying to do this with using lambda and iteration. but to me that seems in efficient.</p> <pre><code> def in_range(index_date, date_ranges): for r in date_ranges.values: if (r[0] &gt;= index_date) &amp; (r[1] &lt;= index_date): return True return False df['in_range'] = df.reset_index().apply(lambda x: in_range(x.date, dt_ranges), axis=1) </code></pre> <p>the above sets in_range to NaNs always, despite the code returning the correct values. i suspect it's because i am resetting the index and so it can not align. Also, as mentioned - this solution probably is pretty inefficient</p> <p>is there a more pythonic/pandemic way of doing this?</p>
[ { "answer_id": 74495345, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "merge_asof s = df.index.to_series()\nm = (pd.merge_asof(s.rename('st_dt'), dt_ranges)\n ['end_dt'].ge(s.to_numpy()).to_numpy()\n )\n\ndf.loc[m, 'in_range'] = True\n dt_ranges in_range\n2022-11-08 True\n2022-11-09 True\n2022-11-10 True\n2022-11-11 NaN\n2022-11-12 NaN\n2022-11-13 True\n2022-11-14 True\n2022-11-15 True\n2022-11-16 NaN\n2022-11-17 NaN\n2022-11-18 NaN\n" }, { "answer_id": 74497747, "author": "sammywemmy", "author_id": 7175713, "author_profile": "https://Stackoverflow.com/users/7175713", "pm_score": 2, "selected": false, "text": "# pip install pyjanitor\nimport pandas as pd\nimport janitor\n(\ndf\n.reset_index()\n.conditional_join(\n dt_ranges, \n ('index', 'st_dt', '>='), \n ('index', 'end_dt', '<='), \n # depending on your data size\n # setting use_numba to True\n # can improve performance\n # of course, this requires numba installed\n use_numba = False,\n how = 'left', \n # performance is better when\n # sort_by_appearance is False\n sort_by_appearance=True)\n.assign(in_range = lambda df: df.in_range.mask(df.st_dt.notna(), True))\n.iloc[:, :2]\n.set_index('index')\n)\n\n in_range\nindex \n2022-11-08 True\n2022-11-09 True\n2022-11-10 True\n2022-11-11 NaN\n2022-11-12 NaN\n2022-11-13 True\n2022-11-14 True\n2022-11-15 True\n2022-11-16 NaN\n2022-11-17 NaN\n2022-11-18 NaN\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495142", "https://Stackoverflow.com", "https://Stackoverflow.com/users/480118/" ]
74,495,144
<p>I keep running into the same problem again, and i have my default way of handling it, but it keeps bugging me.<br> Isn't there any better way?</p> <p>So basicly i have a pipline running, do stuff within the pipline, and want to return a Key/Value Pair from within the pipline.<br> I want the whole pipline to return a object of type psobject (or pscustomobject).<br><br> Here is the way i do it everytime. I create a hashtable at the beginning of the pipline and add key/Value Pairs from within the pipline to this hashtable using the .Add() method.<br> Afterwards i create a psobject by passing the hashtbale to New-Object`s -Property Parameter.<br> This gives me the desired result.</p> <pre><code>Get-Process | Sort -Unique Name | ForEach-Object -Begin { $ht = @{} } -Process { # DO STUFF $key = $_.Name $val = $_.Id # Add Entry to Hashtable $ht.Add($key,$val) } # Create PSObject from Hashtable $myAwesomeNewObject = New-Object psobject -Property $ht # Done - returns System.Management.Automation.PSCustomObject $myAwesomeNewObject.GetType().FullName </code></pre> <p>But this seems a bit cluncky, isn't there a more elegant way of doing it?<br></p> <p>Something like this:</p> <pre><code>[PSObject]$myAwesomeNewObject = Get-Process | Sort -Unique Name | ForEach-Object -Process { # DO STUFF $key = $_.Name $val = $_.Id # return Key/Val Pair @{$key=$val} } # Failed - returns System.Object[] $myAwesomeNewObject.GetType().FullName </code></pre> <p>This unfortunally dosn't work, since the pipe returns an array of hashtables, but i hope you know now what iam trying to achieve.<br><br> Thanks</p>
[ { "answer_id": 74495471, "author": "Santiago Squarzon", "author_id": 15339544, "author_profile": "https://Stackoverflow.com/users/15339544", "pm_score": 3, "selected": true, "text": "$ht [pscustomobject] New-Object [pscustomobject] (Get-Process | Sort -Unique Name | & {\n begin { $ht = @{ } }\n process {\n # DO STUFF\n $key = $_.Name\n $val = $_.Id\n\n # Add Entry to Hashtable\n $ht.Add($key, $val)\n }\n end { $ht }\n})\n" }, { "answer_id": 74495517, "author": "Cpt.Whale", "author_id": 7411885, "author_profile": "https://Stackoverflow.com/users/7411885", "pm_score": 2, "selected": false, "text": "-End $ht[$key]=$val $ht.Add($key,$val) Get-Process | \n Sort -Unique Name | \n Foreach -Begin { $ht = @{} } -Process { \n $ht[$_.Name] = $_.Id \n } -End {[pscustomobject]$ht} | \n ## continue pipeline with pscustomobject\n" }, { "answer_id": 74495873, "author": "Evilcat", "author_id": 9769175, "author_profile": "https://Stackoverflow.com/users/9769175", "pm_score": 1, "selected": false, "text": "$myAwesomeNewObject = `\nGet-Process | Sort -Unique Name | & {\n begin { $ht = @{} }\n process {\n # DO STUFF\n $key = $_.Name\n $val = $_.Id\n\n # Add Entry to Hashtable\n $ht[$key]=$val\n }\n end {[pscustomobject]$ht} \n}\n\n# Success - System.Management.Automation.PSCustomObject\n$myAwesomeNewObject.Gettype().FullName\n\n# And helper Hashtable is NULL thanks to the\n# anonym function\n$null -eq $ht\n" }, { "answer_id": 74499939, "author": "zett42", "author_id": 7571258, "author_profile": "https://Stackoverflow.com/users/7571258", "pm_score": 0, "selected": false, "text": "hashtable Group-Object -AsHashTable # Store the PIDs of all processes into a PSCustomObject, keyed by the process name\n$processes = [PSCustomObject] (Get-Process -PV proc | \n Select-Object -Expand Id | \n Group-Object { $proc.Name } -AsHashtable)\n\n# List all PIDs of given process\n$processes.chrome\n -PV -PipelineVariable Group-Object Select-Object $processes.chrome" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9769175/" ]
74,495,146
<p><code>Task&lt;T&gt;</code> is a separate class from <code>Task</code> (no type parameter), and there are some functions that only accept untyped Task as a parameter. <strong>How can I convert a <code>Task&lt;T&gt;</code> to a <code>Task</code> (with no type parameter)?</strong></p> <p>Examples in F#, but same principle applies to C#.</p> <p>This F# function:</p> <pre><code>let getTask() = task { return () } </code></pre> <p>creates a <code>Task&lt;unit&gt;</code>.</p>
[ { "answer_id": 74495177, "author": "Abel", "author_id": 111575, "author_profile": "https://Stackoverflow.com/users/111575", "pm_score": 3, "selected": true, "text": "let t = getTask() :> Task\n Task<unit> Task Task<'T> Task.ignore let asUnitTask t = task { let! _ = t; return () }\n" }, { "answer_id": 74495247, "author": "Overlord Zurg", "author_id": 2455637, "author_profile": "https://Stackoverflow.com/users/2455637", "pm_score": -1, "selected": false, "text": "ContinueWith() Task<T> var untypedTask = task.ContinueWith(t => { }); let untypedTask = task.ContinueWith(Action<Task<unit>>(ignore))" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2455637/" ]
74,495,154
<p>This is my code:</p> <pre class="lang-py prettyprint-override"><code>def formater_les_parties(parties): from datetime import datetime i = f'{(len(parties[:-1]))} : {parties[0].get(&quot;date&quot;)}, {parties[0].get(&quot;joueurs&quot;)[0]} {&quot;vs&quot;} {parties[0].get(&quot;joueurs&quot;)[1]}, {&quot;gagnant&quot;}: {parties[0].get(&quot;gagnant&quot;)} \n' for w in range((len(parties))): i += str(w) return i </code></pre> <p>and this is the test I made:</p> <pre class="lang-py prettyprint-override"><code>test1 = formater_les_parties([ { &quot;id&quot;: &quot;5559cafd-6966-4465-af6f-67a784016b41&quot;, &quot;date&quot;: &quot;2022-09-23 11:58:20&quot;, &quot;joueurs&quot;: [&quot;IDUL&quot;, &quot;automate&quot;], &quot;gagnant&quot;: None }, ... { &quot;id&quot;: &quot;80a0a0d2-059d-4539-9d53-78b3f6045943&quot;, &quot;date&quot;: &quot;2022-09-24 14:23:59&quot;, &quot;joueurs&quot;: [&quot;IDUL&quot;, &quot;automate&quot;], &quot;gagnant&quot;: &quot;automate&quot; } ]) print(test1) </code></pre> <p>this is my result :</p> <pre><code>1 : 2022-09-23 11:58:20, IDUL vs automate, gagnant: None 0 </code></pre> <p>but this is what is supposed to be :</p> <pre><code>1 : 2022-09-23 11:58:20, IDUL vs automate ... 20: 2022-09-24 14:23:59, IDUL vs automate, gagnant: automate </code></pre> <p>I tried to add all number of my parties to <code>i</code>, and I don't know how I am supposed to do it?</p>
[ { "answer_id": 74495177, "author": "Abel", "author_id": 111575, "author_profile": "https://Stackoverflow.com/users/111575", "pm_score": 3, "selected": true, "text": "let t = getTask() :> Task\n Task<unit> Task Task<'T> Task.ignore let asUnitTask t = task { let! _ = t; return () }\n" }, { "answer_id": 74495247, "author": "Overlord Zurg", "author_id": 2455637, "author_profile": "https://Stackoverflow.com/users/2455637", "pm_score": -1, "selected": false, "text": "ContinueWith() Task<T> var untypedTask = task.ContinueWith(t => { }); let untypedTask = task.ContinueWith(Action<Task<unit>>(ignore))" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495154", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20542963/" ]
74,495,176
<p>On my laptop I have networkx 2.8.6</p> <p>BUT on a cluster I am working on running</p> <blockquote> <p>$ pip3 install networkx==2.8.6</p> </blockquote> <p>I get that there is no such version!</p> <blockquote> <p>ERROR: Could not find a version that satisfies the requirement networkx==2.8.6 (from versions: 0.34, 0.35, 0.35.1, 0.36, 0.37, 0.99, 1.0rc1, 1.0, 1.0.1, 1.1, 1.2rc1, 1.2, 1.3rc1, 1.3, 1.4rc1, 1.4, 1.5rc1, 1.5, 1.6rc1, 1.6, 1.7rc1, 1.7, 1.8rc1, 1.8, 1.8.1, 1.9rc1, 1.9, 1.9.1, 1.10rc2, 1.10, 1.11rc1, 1.11rc2, 1.11, 2.0, 2.1, 2.2rc1, 2.2, 2.3rc3, 2.3rc4, 2.3, 2.4rc1, 2.4rc2, 2.4, 2.5rc1, 2.5, 2.5.1)</p> </blockquote> <p>What could be the problem?</p>
[ { "answer_id": 74501864, "author": "SultanOrazbayev", "author_id": 10693596, "author_profile": "https://Stackoverflow.com/users/10693596", "pm_score": 1, "selected": false, "text": "networkx>=2.7 python>=3.8 conda python # create environment called nx_env\nconda create -n nx_env -c conda-forge python=3.10 networkx=2.8\n\n# after environment is created, activate it\nconda activate nx_env\n" }, { "answer_id": 74581562, "author": "Evan Camilleri", "author_id": 3885062, "author_profile": "https://Stackoverflow.com/users/3885062", "pm_score": 0, "selected": false, "text": "cd into extracted download\n./configure --enable-optimizations\nmake -j8\n./python -m venv path_to_venv\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3885062/" ]
74,495,190
<p>I am trying to merge two json stored in python dictionaries. Here, the first dictionary is the parent into which the second dictionary gets merged into. In reality, the second dictionary represents a second line in a TSV file that holds the next record of a json array. My program is trying to read the TSV file line by line and merging them into one single nested json. Let us consider the two dictionaries: Parent dictionary <code>dict1: {&quot;CA&quot;: [{&quot;Marin&quot;: [{&quot;zip&quot;:1}], &quot;population&quot;:10000}]}</code> and, <code>dict2: {&quot;CA&quot;: {&quot;Marin&quot;: {&quot;zip&quot;:2}}}</code></p> <p><strong>Note</strong>: <code>dict1</code> is the source-of-truth with regards to the correct json structure.</p> <p>Here, as you can see, I would like to append the <code>zip: 2</code> into the Marin county of California state.</p> <p>Here is my merge code:</p> <pre><code>class MyClass: # merges two lines containing json arrays inside nested json def merge_lines(dict1: dict, dict2: dict) -&gt; dict: for key in dict1: if key in dict2: if isinstance(dict1[key], dict): MyClass.merge_lines(dict1[key], dict2[key]) elif isinstance(dict1[key], list): to_be_merged_list = [dict2[key]] dict1[key].extend(to_be_merged_list) return dict1 </code></pre> <p>Below is how I am trying to test:</p> <pre><code>def test_nested_json_arrays(self): d1 = {&quot;CA&quot;: [{&quot;Marin&quot;: [{&quot;zip&quot;:1}], &quot;population&quot;:10000}]} d2 = {&quot;CA&quot;: {&quot;Marin&quot;: {&quot;zip&quot;:2}}} expected_result = {&quot;CA&quot;: [{&quot;Marin&quot;: [{&quot;zip&quot;:1}, {&quot;zip&quot;:2}], &quot;population&quot;:1000}]} actual = MyClass.merge_lines(d1, d2) assert expected_result == actual </code></pre> <p>However, I am getting the below result:</p> <pre><code>E AssertionError: assert {'CA': [{'Mar...tion': 1000}]} == {'CA': [{'Mari... {'zip': 2}}]} E Differing items: E {'CA': [{'Marin': [{'zip': 1}, {'zip': 2}], 'population': 1000}]} != {'CA': [{'Marin': [{'zip': 1}], 'population': 10000}, {'Marin': {'zip': 2}}]} E Full diff: E - {'CA': [{'Marin': [{'zip': 1}, {'zip': 2}], 'population': 1000}]} E + {'CA': [{'Marin': [{'zip': 1}], 'population': 10000}, {'Marin': {'zip': 2}}]} </code></pre> <p>Can someone help me figure out the changes required in the code to fix this? <strong>Note</strong>: <em>the field names are not constant and this can apply to any combination of country, state, county, zip and other nested attributes.</em></p>
[ { "answer_id": 74523051, "author": "Pranav Hosangadi", "author_id": 843953, "author_profile": "https://Stackoverflow.com/users/843953", "pm_score": 2, "selected": false, "text": "dict1 = {\"CA\": [{\"Marin\": [{\"zip\":1}], \"population\":10000}]}\ndict2 = {\"CA\": {\"Marin\": {\"zip\":2}}}\n dict2 dict2 k k = \"CA\" dict2[k] c = \"Marin\" z z dict1 county_info dict1[k] c county_info[c] z def merge_lines(dict1, dict2):\n for k, v in dict2.items():\n for c, z in v.items():\n # Find the element of dict1[k] that has the key c:\n for county_info in dict1[k]:\n if c in county_info:\n county_info[c].append(z)\n break\n dict1 merge_lines(dict1, dict2) dict1 {'CA': [{'Marin': [{'zip': 1}, {'zip': 2}], 'population': 10000}]}\n" }, { "answer_id": 74595959, "author": "Fabio Rotondo", "author_id": 339620, "author_profile": "https://Stackoverflow.com/users/339620", "pm_score": 1, "selected": true, "text": "d1 d2 d2 #!/usr/bin/env python3\n\nd1 = {\"CA\": [{\"Marin\": [{\"zip\": 1}], \"population\": 10000}]}\nd2 = {\"CA\": {\"Marin\": {\"zip\": 2}}}\n\n\n# read update data from d2 and append new values to d1\ndef update(d1, d2):\n for key, value in d2.items():\n if key in d1:\n for key1, value1 in value.items():\n if key1 in d1[key][0]:\n d1[key][0][key1].append(value1)\n else:\n d1[key][0][key1] = [value1]\n else:\n d1[key] = [value]\n\n return d1\n\n\nprint(update(d1, d2))\n" }, { "answer_id": 74604264, "author": "D P", "author_id": 20622893, "author_profile": "https://Stackoverflow.com/users/20622893", "pm_score": -1, "selected": false, "text": "# Merge two Python dictionaries using the \n merge operator in Python 3.9+\n dict1 = {'a': 1, 'b': 2}\n dict2 = {'c': 3, 'd': 4}\n\n dict3 = dict1 | dict2\n\n print(dict3)\n\n# Returns: {'a': 1, 'b': 2, 'c': 3, 'd': 4}\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6258583/" ]
74,495,268
<p>I am looking for some help on a project I am doing where I need to output the responses to the console as well as write them to a file. I am having trouble figuring that part out. I have been able to write the responses to a file successfully, but not both at the same time. Can someone help with that portion? The only lines that need to be written to the file are the ones that I have currently being written to a file</p> <pre><code>from datetime import datetime import requests import pytemperature def main(): api_start = 'https://api.openweathermap.org/data/2.5/weather?q=' api_key = '&amp;appid=91b8698c2ed6c192aabde7c9e75d23cb' now = datetime.now() filename = input(&quot;\nEnter the output filename: &quot;) myfile = None try: myfile = open(filename, &quot;w&quot;) except: print(&quot;Unable to open file &quot; + filename + &quot;\nData will not be saved to a file&quot;) choice = &quot;y&quot; print(&quot;ISQA 3900 Open Weather API&quot;, file=myfile) print(now.strftime(&quot;%A, %B %d, %Y&quot;), file=myfile) while choice.lower() == &quot;y&quot;: # input city and country code city = input(&quot;Enter city: &quot;) print(&quot;Use ISO letter country code like: https://countrycode.org/&quot;) country = input(&quot;Enter country code: &quot;) # app configures url to generate json data url = api_start + city + ',' + country + api_key json_data = requests.get(url).json() try: # getting weather data from json weather_description = json_data['weather'][0]['description'] # printing weather information print(&quot;\nThe Weather Report for &quot; + city + &quot; in &quot; + country + &quot; is:&quot;, file=myfile) print(&quot;\tCurrent conditions: &quot;, weather_description, file=myfile) # getting temperature data from json current_temp_kelvin = json_data['main']['temp'] current_temp_fahrenheit = pytemperature.k2f(current_temp_kelvin) # printing temperature information print(&quot;\tCurrent temperature in Fahrenheit:&quot;, current_temp_fahrenheit, file=myfile) # getting pressure data from json current_pressure = json_data['main']['pressure'] # printing pressure information print(&quot;\tCurrent pressure in HPA:&quot;, current_pressure, file=myfile) # getting humidity data from json current_humidity = json_data['main']['humidity'] # printing humidity information print(&quot;\tCurrent humidity:&quot;, &quot;%s%%&quot; % current_humidity, file=myfile) # getting expected low temp data from json expected_low_temp = json_data['main']['temp_min'] expected_low_temp = pytemperature.k2f(expected_low_temp) # printing expected low temp information print(&quot;\tExpected low temperature in Fahrenheit:&quot;, expected_low_temp, file=myfile) # getting expected high temp data from json expected_high_temp = json_data['main']['temp_max'] expected_high_temp = pytemperature.k2f(expected_high_temp) # printing expected high temp information print(&quot;\tExpected high temperature in Fahrenheit:&quot;, expected_high_temp, file=myfile) choice = input(&quot;Continue (y/n)?: &quot;) print() except: print(&quot;Unable to access &quot;, city, &quot; in &quot;, country) print(&quot;Verify city name and country code&quot;) if myfile: myfile.close() print('Thank you - Goodbye') if __name__ == &quot;__main__&quot;: main() </code></pre> <p>Honestly I am kind of at a loss on this one for some reason it is just kicking my butt.</p>
[ { "answer_id": 74523051, "author": "Pranav Hosangadi", "author_id": 843953, "author_profile": "https://Stackoverflow.com/users/843953", "pm_score": 2, "selected": false, "text": "dict1 = {\"CA\": [{\"Marin\": [{\"zip\":1}], \"population\":10000}]}\ndict2 = {\"CA\": {\"Marin\": {\"zip\":2}}}\n dict2 dict2 k k = \"CA\" dict2[k] c = \"Marin\" z z dict1 county_info dict1[k] c county_info[c] z def merge_lines(dict1, dict2):\n for k, v in dict2.items():\n for c, z in v.items():\n # Find the element of dict1[k] that has the key c:\n for county_info in dict1[k]:\n if c in county_info:\n county_info[c].append(z)\n break\n dict1 merge_lines(dict1, dict2) dict1 {'CA': [{'Marin': [{'zip': 1}, {'zip': 2}], 'population': 10000}]}\n" }, { "answer_id": 74595959, "author": "Fabio Rotondo", "author_id": 339620, "author_profile": "https://Stackoverflow.com/users/339620", "pm_score": 1, "selected": true, "text": "d1 d2 d2 #!/usr/bin/env python3\n\nd1 = {\"CA\": [{\"Marin\": [{\"zip\": 1}], \"population\": 10000}]}\nd2 = {\"CA\": {\"Marin\": {\"zip\": 2}}}\n\n\n# read update data from d2 and append new values to d1\ndef update(d1, d2):\n for key, value in d2.items():\n if key in d1:\n for key1, value1 in value.items():\n if key1 in d1[key][0]:\n d1[key][0][key1].append(value1)\n else:\n d1[key][0][key1] = [value1]\n else:\n d1[key] = [value]\n\n return d1\n\n\nprint(update(d1, d2))\n" }, { "answer_id": 74604264, "author": "D P", "author_id": 20622893, "author_profile": "https://Stackoverflow.com/users/20622893", "pm_score": -1, "selected": false, "text": "# Merge two Python dictionaries using the \n merge operator in Python 3.9+\n dict1 = {'a': 1, 'b': 2}\n dict2 = {'c': 3, 'd': 4}\n\n dict3 = dict1 | dict2\n\n print(dict3)\n\n# Returns: {'a': 1, 'b': 2, 'c': 3, 'd': 4}\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14503776/" ]
74,495,276
<p>Need to type guard but <code>instanceof</code> doesn't work with TypeScript <code>type</code>s:</p> <pre class="lang-js prettyprint-override"><code>type Letter = 'A' | 'B'; const isLetter = (c: any): c is Letter =&gt; c instanceof Letter; // Error: 'Letter' only refers to a type, but is being used as a value here. // Expected usage: Filter via type guard. isLetter('a'); // Should output true 'foo bar'.split('').filter(c =&gt; isLetter(c)); // Should output 'a' </code></pre> <p>Haven't found similar questions but <code>instanceof</code> works with classes:</p> <pre class="lang-js prettyprint-override"><code>class Car {} const isCar = (c: any): c is Car =&gt; c instanceof Car; // No error isCar('a'); // false </code></pre> <p>If <code>instanceof</code> only works with classes, what is it's equivalent for <code>type</code>, &amp; how can we type guard using a TypeScript <code>type</code>?</p>
[ { "answer_id": 74495402, "author": "surajs02", "author_id": 7490713, "author_profile": "https://Stackoverflow.com/users/7490713", "pm_score": 0, "selected": false, "text": "const isLetter = (c: any): c is Letter => ['A', 'B'].includes(c);\nisLetter('A'); // true\nisLetter('a'); // false\n" }, { "answer_id": 74495512, "author": "Lesiak", "author_id": 1570854, "author_profile": "https://Stackoverflow.com/users/1570854", "pm_score": 3, "selected": true, "text": "const isLetter = (c: any): c is Letter => c == 'A' || c == 'B';\n const letters = ['A', 'B'] as const;\ntype Letter = typeof letters[number];\nconst isLetter = (c: any): c is Letter => letters.includes(c);\n" }, { "answer_id": 74495550, "author": "Orwa Diraneyya", "author_id": 20186406, "author_profile": "https://Stackoverflow.com/users/20186406", "pm_score": 0, "selected": false, "text": "any Letter type Letter = 'A' | 'B';\n// compile-time check is implemented by assigning the parameter 'c'\n// to a TypeScript type\nconst shouldBeLetter = (c: Letter) => {\n // implement a runtime check using JavaScript, not TypeScript\n if (c !== 'A' && c !== 'B') throw \"c should be either 'A' or 'B'\";\n /* rest of the function */\n}\n\n// example of a statament that fails at compile time\n// error: Argument of type '\"D\"' is not assignable to parameter of \n// type 'Letter'. (2345)\nshouldBeLetter('C');\n\n// example of a statement that won't fail at compile time, but will\n// need a runtime test\nlet couldBeC : Letter = 'ABC'[Math.floor(Math.random() * 3)] as Letter;\nshouldBeLetter(couldBeC);\n typeof typeof letters[number]" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7490713/" ]
74,495,284
<p>I'm working on a small project involving the game Re-Volt (1999), I'm trying to make a web page where you can see all the cars with their details (image, engine type, rating, speed etc.). I have a table <code>cars</code> where I the previous mentioned information and it looks like this:</p> <pre><code>CREATE TABLE public.cars ( id integer NOT NULL, name character varying(25), thumbnail_id integer, engine_id integer, rating_id integer, speed integer, acc numeric, mass numeric ); </code></pre> <p>I am using Hibernate with Spring Boot, PostgreSQL for the database and Thymeleaf to display the data in a web page. I managed to use Hibernate to pull the data from <code>cars</code> and display it, all good, but now I want to join <code>cars</code> with table <code>thumbnails</code> on <code>cars.thumbnail_id = thumbnails.id</code> and display the column <code>image</code> from table <code>thumbnails</code> instead of <code>thumbnails_id</code>. This is what my <code>thumbnails</code> table looks like:</p> <pre><code>CREATE TABLE public.thumbnails ( id integer NOT NULL, image character varying(50) ); </code></pre> <p>And these are my entities:</p> <pre><code>// Car.java @Setter @Getter @AllArgsConstructor @NoArgsConstructor @Entity @Table(name = &quot;cars&quot;) public class Car { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = &quot;id&quot;) private Long id; @Column(name = &quot;name&quot;) private String name; @OneToOne @JoinColumn(name = &quot;id&quot;) private Thumbnail thumbnail; @Column(name = &quot;engine_id&quot;) private Integer engine_id; @Column(name = &quot;rating_id&quot;) private Integer rating_id; @Column(name = &quot;speed&quot;) private Integer speed; @Column(name = &quot;acc&quot;) private Double acc; @Column(name = &quot;mass&quot;) private Double mass; } </code></pre> <pre><code>// Thumbnail.java @Setter @Getter @AllArgsConstructor @NoArgsConstructor @Entity @Table(name = &quot;thumbnails&quot;) public class Thumbnail { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = &quot;id&quot;) private Long id; @Column(name = &quot;image&quot;) private String image; } </code></pre> <p>What I don't know how to do is properly code that <code>join</code> in. With my current code Hibernate matches the rows without considering the value of <code>thumbnail_id</code>, it simply does &quot;car_1 = thumbnail_1&quot; even if &quot;car_1&quot; has &quot;thumbnail_id&quot; equal to 12, it still matches it to the first thumbnail and not to the 12th. Can anyone help me out?</p> <p>Edit: Basically, what I'm trying to achieve through Hibernate is the following SQL query:</p> <pre><code>SELECT c.name, t.image, c.engine_id, c.rating_id, c.speed, c.acc, c.mass FROM cars c JOIN thumbnails t ON c.thumbnails_id = t.id; </code></pre>
[ { "answer_id": 74496458, "author": "Mahesh Biradar", "author_id": 4991722, "author_profile": "https://Stackoverflow.com/users/4991722", "pm_score": 2, "selected": true, "text": "@Entity\n@Table(name = \"cars\")\npublic class Car {\n\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n @Column(name = \"id\")\n private Long id;\n @Column(name = \"name\")\n private String name;\n\n @JoinColumn(name = \"thumbnail_id\", referencedColumnName=\"id\")\n @OneToOne(cascade = CascadeType.ALL)\n @Fetch(FetchMode.JOIN)\n private Thumbnail thumbnail;\n\n @Column(name = \"engine_id\")\n private Integer engine_id;\n\n @Column(name = \"rating_id\")\n private Integer rating_id;\n\n @Column(name = \"speed\")\n private Integer speed;\n @Column(name = \"acc\")\n private Double acc;\n @Column(name = \"mass\")\n private Double mass;\n @Entity\n@Table(name = \"thumbnails\")\npublic class Thumbnail {\n\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n @Column(name = \"id\")\n private Long id;\n @Column(name = \"image\")\n private String image;\n import java.util.List;\n\nimport org.springframework.data.jpa.repository.EntityGraph;\nimport org.springframework.data.jpa.repository.JpaRepository;\n\nimport com.mahesh.tt.model.Car;\n\npublic interface TutorialRepository2 extends JpaRepository<Car, Long> {\n \n @Override\n @EntityGraph(attributePaths = {\"thumbnail\"})\n List<Car> findAll();\n}\n select\n car0_.id as id1_0_0_,\n thumbnail1_.id as id1_1_1_,\n car0_.acc as acc2_0_0_,\n car0_.engine_id as engine_i3_0_0_,\n car0_.mass as mass4_0_0_,\n car0_.name as name5_0_0_,\n car0_.rating_id as rating_i6_0_0_,\n car0_.speed as speed7_0_0_,\n car0_.thumbnail_id as thumbnai8_0_0_,\n thumbnail1_.image as image2_1_1_ \n from\n cars car0_ \n left outer join\n thumbnails thumbnail1_ \n on car0_.thumbnail_id=thumbnail1_.id\n" }, { "answer_id": 74496722, "author": "Rawres", "author_id": 7451529, "author_profile": "https://Stackoverflow.com/users/7451529", "pm_score": 0, "selected": false, "text": "thumbnail_id @JoinColumn @MapsId(\"id\") Car.java // Car.java\n@Setter\n@Getter\n@AllArgsConstructor\n@NoArgsConstructor\n@Entity\n@Table(name = \"cars\")\npublic class Car {\n\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n @Column(name = \"id\")\n private Long id;\n @Column(name = \"name\")\n private String name;\n\n @OneToOne\n @JoinColumn(name = \"thumbnail_id\") // I changed this\n @MapsId(\"id\") // and added this\n private Thumbnail thumbnail;\n\n @Column(name = \"engine_id\")\n private Integer engine;\n\n @Column(name = \"rating_id\")\n private Integer rating;\n\n @Column(name = \"speed\")\n private Integer speed;\n @Column(name = \"acc\")\n private Double acc;\n @Column(name = \"mass\")\n private Double mass;\n}\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7451529/" ]
74,495,313
<p>In SQL I'm trying to combine multiple tables and grab the SUM of expenses per person, and sort those by highest total expense first. I have 3 tables:</p> <ul> <li>test1 (from grocery store #1)</li> <li>test2 (from grocery store #2),</li> <li>junction1 (one that I just created to somehow try to connect test1 and test2 together)</li> </ul> <p>I cannot edit test1 and test2 in the production environment. I created junction1 as a bridge to connect test1 and test2. I can modify columns/content in junction1. The IDs of test1 and test2 may change in the future (right now they are the same).</p> <p>Desired result:</p> <p><img src="https://i.stack.imgur.com/jyE8q.jpg" alt="Desired result table" /></p> <p>I need to do a full join on all tables, since I want to include all personnel from both tables. test1 and test2 are independent, as some people only shop in test1 locations and some only shop in test2 locations. Also to sort by Total SUM of both tables I tried:</p> <pre><code>ORDER BY SUM(Grocery1 + Grocery2) DESC </code></pre> <p>No luck.</p> <p>A SUM select statement (no joins) works:</p> <pre><code>select junction1.Name1, SUM(Amount) AS Grocery1 from test1 FULL JOIN junction1 on junction1.ID1= test1.ID1 GROUP BY junction1.Name1 ORDER BY Grocery1 DESC; </code></pre> <p><img src="https://i.stack.imgur.com/tm0kj.jpg" alt="Part 1" /></p> <p>But when I join the table(s):</p> <pre><code>select junction1.Name1, SUM(test1.Amount) AS Grocery1, SUM(test2.Amount) AS Grocery2 from test1 FULL JOIN junction1 ON test1.ID1 = junction1.ID1 FULL JOIN test2 ON test2.ID2 = junction1.ID2 GROUP BY junction1.Name1 </code></pre> <p>It gives:</p> <p><img src="https://i.stack.imgur.com/5duoY.jpg" alt="Incorrect Results" /></p> <p>The data is off in both columns. Andy should only have $400 for Grocery1. It looks like it's multiplying it instead of adding it. I tried to divide by 3, which helps some of the people with 3 entries, but that's probably not what I want.</p>
[ { "answer_id": 74495394, "author": "Mike Hofer", "author_id": 47580, "author_profile": "https://Stackoverflow.com/users/47580", "pm_score": 0, "selected": false, "text": "full join join INNER JOIN SELECT junction1.Name1, \n SUM(test1.Amount) AS Grocery1, \n SUM(test2.Amount) AS Grocery2\n FROM test1\n INNER JOIN junction1 ON test1.ID1 = junction1.ID1\n INNER JOIN test2 ON test2.ID2 = junction1.ID2\n GROUP BY junction1.Name1\n" }, { "answer_id": 74495861, "author": "GMB", "author_id": 10676716, "author_profile": "https://Stackoverflow.com/users/10676716", "pm_score": 2, "selected": true, "text": "union left join select j.name1, sum(t.amount1) as grocery1, sum(t.amount2) as grocery2\nfrom junction1 j\nleft join (\n select id1, null as id2, amount as amount1, null as amount2 from test1\n union all select null, id2, null, amount from test2\n) t on t.id1 = j.id1 or t.id2 = j.id2\ngroup by j.name1\n union left join" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18060186/" ]
74,495,334
<p>I am fairly new to the frontend and css. I am trying to add a <code>background-image</code> in such a way that, if <code>.avif</code> files are supported, then these are loaded. Otherwise fallback to a <code>.png</code> file. I'm wondering if it is possible to do this without javascript and without loading all the images to not affect page speed. I am running <code>Chrome 107.0.5304.110</code>, <code>ios 16.1</code> in (mostly)simulator (I know older versions of ios dont support avif, but the latest one does. Would like something that works with both) , and Firefox <code>106.0.1</code>.</p> <p><a href="https://stackoverflow.com/a/64350281/1462297">Attempt 1</a> follows this previous answer. Note the usage of <code>webkit-image-set</code>. Here is my code:</p> <pre><code>background-image: url(&quot;/static/img/image.png&quot;); background-image: -webkit-image-set(url(&quot;/static/img/image.avif&quot;)1x ); </code></pre> <p>Doing this works for Chrome and Firefox, but Safari on ios shows a gray image.</p> <p><a href="https://raoulkramer.de/avif-webp-images-css-background-usage-progressive-enhanced-with-image-set/" rel="nofollow noreferrer">Attempt 2</a> follows the answer on this blog. Note that here <code>image-set</code> is used. Code:</p> <pre><code>background-image: url(&quot;/static/img/image.png&quot;); background-image: image-set( url(&quot;/static/img/image.avif&quot;) 1x, url(&quot;/static/img/image.png&quot;) 1x, ); </code></pre> <p>This is visible on all three browsers, but the png is always shown. I also invert the positions in the image-set but same results. Always png.</p> <p>Attempt 3, a slight variation of attempt 2. I just change the format on the first line.</p> <pre><code>background-image: url(&quot;/static/img/image.avif&quot;); background-image: image-set( url(&quot;/static/img/image.avif&quot;) 1x, url(&quot;/static/img/image.png&quot;) 1x, ); </code></pre> <p>This works well on chrome/firefox, but ios is gray.</p> <p>Is there a way to solve this problem? Thanks!</p>
[ { "answer_id": 74495394, "author": "Mike Hofer", "author_id": 47580, "author_profile": "https://Stackoverflow.com/users/47580", "pm_score": 0, "selected": false, "text": "full join join INNER JOIN SELECT junction1.Name1, \n SUM(test1.Amount) AS Grocery1, \n SUM(test2.Amount) AS Grocery2\n FROM test1\n INNER JOIN junction1 ON test1.ID1 = junction1.ID1\n INNER JOIN test2 ON test2.ID2 = junction1.ID2\n GROUP BY junction1.Name1\n" }, { "answer_id": 74495861, "author": "GMB", "author_id": 10676716, "author_profile": "https://Stackoverflow.com/users/10676716", "pm_score": 2, "selected": true, "text": "union left join select j.name1, sum(t.amount1) as grocery1, sum(t.amount2) as grocery2\nfrom junction1 j\nleft join (\n select id1, null as id2, amount as amount1, null as amount2 from test1\n union all select null, id2, null, amount from test2\n) t on t.id1 = j.id1 or t.id2 = j.id2\ngroup by j.name1\n union left join" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1462297/" ]
74,495,357
<p>In this case I have seen the official documentation of choreo, ballerina, but I could not find how to execute a query where I need to filter by the <code>ObjectId</code>, In Java I could do it by importing BSON, but I could not find the same in ballerina.</p> <p>In the following example, it does not give an error, because that field is mapped to that type.</p> <pre><code>//map&lt;json&gt; queryString = {user_id: new object&quot;61b75a0a08f2bf69b98a174c&quot; }; map&lt;json&gt; queryString = {unique_id: 1 }; map&lt;json&gt; projectionDoc = {unique_id: true, destination_address: true, _id: true}; stream&lt;Historial, error?&gt; h_viajes = check mongoClient-&gt;find(collectionName = &quot;trip_histories&quot;,projection = projectionDoc,filter = queryString); check h_viajes.forEach(function(Historial datas){ io:println(datas.unique_id.toString()); io:println(datas._id.toString()); log:printInfo(datas.unique_id.toString()); }); </code></pre>
[ { "answer_id": 74495394, "author": "Mike Hofer", "author_id": 47580, "author_profile": "https://Stackoverflow.com/users/47580", "pm_score": 0, "selected": false, "text": "full join join INNER JOIN SELECT junction1.Name1, \n SUM(test1.Amount) AS Grocery1, \n SUM(test2.Amount) AS Grocery2\n FROM test1\n INNER JOIN junction1 ON test1.ID1 = junction1.ID1\n INNER JOIN test2 ON test2.ID2 = junction1.ID2\n GROUP BY junction1.Name1\n" }, { "answer_id": 74495861, "author": "GMB", "author_id": 10676716, "author_profile": "https://Stackoverflow.com/users/10676716", "pm_score": 2, "selected": true, "text": "union left join select j.name1, sum(t.amount1) as grocery1, sum(t.amount2) as grocery2\nfrom junction1 j\nleft join (\n select id1, null as id2, amount as amount1, null as amount2 from test1\n union all select null, id2, null, amount from test2\n) t on t.id1 = j.id1 or t.id2 = j.id2\ngroup by j.name1\n union left join" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6660693/" ]
74,495,370
<p>So I can run two separate queries like this:</p> <pre><code>SELECT date as date1, product as product1, product_id as product_id_1, SUM(revenue) AS rev1 FROM product_inventory WHERE date = '2021-11-17' GROUP BY date1 , product1, product_id_1 ORDER BY rev1 DESC </code></pre> <pre><code>SELECT date as date2, product as product2, product_id as product_id_2, SUM(revenue) AS rev2 FROM product_inventory WHERE date = '2022-11-17' GROUP BY date2 , product2, product_id_2 ORDER BY rev2 DESC </code></pre> <p>And this is the output I get for each:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>date1</th> <th>product1</th> <th>product_id_1</th> <th>rev1</th> </tr> </thead> <tbody> <tr> <td>2021-11-17</td> <td>adidas samba</td> <td>9724</td> <td>6087.7000732421875</td> </tr> <tr> <td>2021-11-17</td> <td>nike air max</td> <td>5361</td> <td>4918.0</td> </tr> <tr> <td>2021-11-17</td> <td>puma suede</td> <td>1985</td> <td>3628.1600341796875</td> </tr> </tbody> </table> </div><div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>date2</th> <th>product2</th> <th>product_id_2</th> <th>rev2</th> </tr> </thead> <tbody> <tr> <td>2022-11-17</td> <td>adidas samba</td> <td>9724</td> <td>5829.0</td> </tr> <tr> <td>2022-11-17</td> <td>nike air max</td> <td>5361</td> <td>4841.864013671875</td> </tr> <tr> <td>2022-11-17</td> <td>puma suede</td> <td>1985</td> <td>5404.4140625</td> </tr> </tbody> </table> </div> <p>How can I query the db in a way that would pull the date2 and rev2 column into one single output like this?</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>date1</th> <th>product1</th> <th>product_id_1</th> <th>rev1</th> <th>date2</th> <th>rev2</th> </tr> </thead> <tbody> <tr> <td>2021-11-17</td> <td>adidas samba</td> <td>9724</td> <td>6087.7000732421875</td> <td>2022-11-17</td> <td>5829.0</td> </tr> <tr> <td>2021-11-17</td> <td>nike air max</td> <td>5361</td> <td>4918.0</td> <td>2022-11-17</td> <td>4841.864013671875</td> </tr> <tr> <td>2021-11-17</td> <td>puma suede</td> <td>1985</td> <td>3628.1600341796875</td> <td>2022-11-17</td> <td>5404.4140625</td> </tr> </tbody> </table> </div> <p>I tried this query:</p> <pre><code>SELECT A.date1, A.product1, A.rev1, B.date2, B.product2, B.rev2 FROM ( SELECT date as date1, product as product1, product_id as product_id_1, SUM(revenue) AS rev1 FROM product_inventory WHERE date = '2021-11-17' GROUP BY date1 , product1, product_id_1 ORDER BY rev1 DESC ) A, ( SELECT date as date2, product as product2, product_id as product_id_2, SUM(revenue) AS rev2 FROM product_inventory WHERE date = '2022-11-17' GROUP BY date2, product2, product_id_2 ORDER BY rev2 DESC ) B; </code></pre> <p>but I get this output</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>date1</th> <th>product1</th> <th>rev1</th> <th>date2</th> <th>product2</th> <th>rev2</th> </tr> </thead> <tbody> <tr> <td>2021-11-17</td> <td>puma suede</td> <td>3628.1600341796875</td> <td>2022-11-17</td> <td>adidas samba shoes</td> <td>5829.0</td> </tr> <tr> <td>2021-11-17</td> <td>nike air max</td> <td>4918.0</td> <td>2022-11-17</td> <td>adidas samba shoes</td> <td>5829.0</td> </tr> <tr> <td>2021-11-17</td> <td>adidas samba</td> <td>6087.7000732421875</td> <td>2022-11-17</td> <td>adidas samba shoes</td> <td>5829.0</td> </tr> <tr> <td>2021-11-17</td> <td>puma suede</td> <td>3628.1600341796875</td> <td>2022-11-17</td> <td>puma suede</td> <td>5404.4140625</td> </tr> <tr> <td>2021-11-17</td> <td>nike air max</td> <td>4918.0</td> <td>2022-11-17</td> <td>puma suede</td> <td>5404.4140625</td> </tr> <tr> <td>2021-11-17</td> <td>adidas samba</td> <td>6087.7000732421875</td> <td>2022-11-17</td> <td>puma suede</td> <td>5404.4140625</td> </tr> <tr> <td>2021-11-17</td> <td>puma suede</td> <td>3628.1600341796875</td> <td>2022-11-17</td> <td>nike air max</td> <td>4841.864013671875</td> </tr> <tr> <td>2021-11-17</td> <td>nike air max</td> <td>4918.0</td> <td>2022-11-17</td> <td>nike air max</td> <td>4841.864013671875</td> </tr> <tr> <td>2021-11-17</td> <td>adidas samba</td> <td>6087.7000732421875</td> <td>2022-11-17</td> <td>nike air max</td> <td>4841.864013671875</td> </tr> </tbody> </table> </div> <p>It's like the number of records gets squared.</p>
[ { "answer_id": 74495499, "author": "at54321", "author_id": 15602349, "author_profile": "https://Stackoverflow.com/users/15602349", "pm_score": 0, "selected": false, "text": "SELECT t1.date, t1.product, t1.product_id, t2.date, t2.product_id, ...\nFROM\n (SELECT ... FROM product_inventory WHERE ... GROUP BY ...) AS t1\nJOIN\n (SELECT ... FROM product_inventory WHERE ... GROUP BY ...) AS t2\nON t1.product_id = t2.product_id AND t1.date = t2.date\nORDER BY ... \n WITH \n t1 AS\n (SELECT ... FROM product_inventory WHERE ... GROUP BY ...),\n t2 AS\n (SELECT ... FROM product_inventory WHERE ... GROUP BY ...),\nSELECT t1.date, t1.product, t1.product_id, t2.date, t2.product_id, ...\nFROM t1 \nJOIN t2 ON t1.product_id = t2.product_id AND t1.date = t2.date\nORDER BY ...\n ORDER BY" }, { "answer_id": 74495528, "author": "Lasha Dolenjashvili", "author_id": 13385741, "author_profile": "https://Stackoverflow.com/users/13385741", "pm_score": 0, "selected": false, "text": "WITH DATE_1 AS (\nSELECT date as date1, product as product1, product_id as product_id_1, SUM(revenue) AS rev1 \n FROM product_inventory \n WHERE date = '2021-10-17' \n GROUP BY 1, 2, 3\n),\nDATE_2 AS (\nSELECT date as date2, product as product2, product_id as product_id_2, SUM(revenue) AS rev2 \n FROM product_inventory \n WHERE date = '2021-11-17' \n GROUP BY 1, 2, 3\n)\nSELECT D1.*, D2.*\n FROM DATE_1 D1\n INNER JOIN DATE_2 D2\n ON D1.product_id_1 = D2.product_id_2\n" }, { "answer_id": 74495643, "author": "Pompedup", "author_id": 12239272, "author_profile": "https://Stackoverflow.com/users/12239272", "pm_score": 0, "selected": false, "text": "WITH -- Your first query that I put in a \"fake table\" named first_date\nWITH first_date AS (\n SELECT date as date1, product as product1, product_id as product_id_1, SUM(revenue) AS rev1 \n FROM product_inventory \n WHERE date = '2021-11-17' \n GROUP BY date1 , product1, product_id_1 \n ORDER BY rev1 DESC\n),\n-- Your second query that I put in a \"fake table\" named second_date\nsecond_date AS (\n SELECT date as date2, product as product2, product_id as product_id_2, SUM(revenue) AS rev2 \n FROM product_inventory \n WHERE date = '2022-11-17' \n GROUP BY date2 , product2, product_id_2 \n ORDER BY rev2 DESC\n)\n-- First we get the products in both \"fake tables\"\nSELECT a.*, b.date2, b.rev2\nFROM first_date a\nINNER JOIN second_date b ON a.product_id_1 = b.product_id_2\nUNION\n-- Then only in the first \"fake table\"\nSELECT c.*, NULL, NULL\nFROM first_date c\nLEFT JOIN second_date d ON c.product_id_1 = d.product_id_2\nWHERE d.product_id_2 IS NULL\nUNION\n-- Then only in the second \"fake table\"\nSELECT NULL, f.product2, f.product_id_2, NULL, f.date2, f.rev2\nFROM first_date e\nRIGHT JOIN second_date f ON e.product_id_1 = f.product_id_2\nWHERE e.product_id_1 IS NULL;\n" }, { "answer_id": 74496437, "author": "GMB", "author_id": 10676716, "author_profile": "https://Stackoverflow.com/users/10676716", "pm_score": 1, "selected": false, "text": "WITH select product_id, product,\n sum(case when date = '2021-11-17' then revenue end) as rev_2021_11_17,\n sum(case when date = '2022-11-17' then revenue end) as rev_2022_11_17\nfrom product_inventory \nwhere date in ('2021-11-17', '2022-11-17')\ngroup by product_id, product\n SELECT MIN MAX" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11627826/" ]
74,495,372
<p>My question is basically the following:</p> <p>When I use a value with BigDecimal, how do I append zeros in front of a random number? Say I want to have a number &lt;10 following an entirely random pattern. Now i want to add zeros in front of the number, so the actual amount adds up to 10 numbers.</p> <p>Here's an example: <em>BigDecimal num = new BigDecimal(2353);</em></p> <p>Now I want to have that ouput: 0000002353</p> <p>Is there a function that appends numbers to a BigDecimal type? I couldn't find any.</p> <p>I tried using a while loop that checks whether the number is less than ten. But I don't understand the Big Decimal well enough to actually compare integral values to the BigDecimal types. Thanks for any help in advance!</p>
[ { "answer_id": 74495409, "author": "human bean", "author_id": 17186475, "author_profile": "https://Stackoverflow.com/users/17186475", "pm_score": 1, "selected": false, "text": "BigDecimal BigDecimal float String BigDecimal BigDecimal BigDecimal BigDecimal compareTo" }, { "answer_id": 74495589, "author": "Per Huss", "author_id": 6315242, "author_profile": "https://Stackoverflow.com/users/6315242", "pm_score": 2, "selected": false, "text": "BigInteger int long String.format(\"%010d\", BigInteger.valueOf(2353))\n 0 10" }, { "answer_id": 74495597, "author": "Alexander Ivanchenko", "author_id": 17949945, "author_profile": "https://Stackoverflow.com/users/17949945", "pm_score": 1, "selected": false, "text": "DecimalFormat BigDecimal num = new BigDecimal(2353);\n \nDecimalFormat f1 = new DecimalFormat(\"0000000000\");\nDecimalFormat f2 = new DecimalFormat(\"0,000,000,000\");\n \nSystem.out.println(f1.format(num));\nSystem.out.println(f2.format(num));\n 0000002353\n0,000,002,353\n" }, { "answer_id": 74496545, "author": "Bohemian", "author_id": 256196, "author_profile": "https://Stackoverflow.com/users/256196", "pm_score": 0, "selected": false, "text": "long long myNumber = 123456;\nSystem.out.printf(\"%010d%n\", myNumber);\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16930849/" ]
74,495,395
<p>In the below code, I need to hide the <code>2nd tag</code> and it's related content, how can I do that in Css</p> <pre><code>&lt;div id=&quot;content-list&quot;&gt; &lt;b&gt;Title:&lt;/b&gt; some random text &lt;br/&gt; &lt;b&gt;Title2:&lt;/b&gt; some random text 2 &lt;br/&gt; &lt;/div&gt; </code></pre> <p>With the below css I can only hide the 2nd <code>b</code> tag, but not able to hide the text.</p> <pre><code>div &gt; b:nth-child(1) { display: none; } </code></pre> <p>Note: HTML mockup can't be modified due to various reason.</p>
[ { "answer_id": 74495535, "author": "Daniel Gimenez", "author_id": 2497335, "author_profile": "https://Stackoverflow.com/users/2497335", "pm_score": 3, "selected": true, "text": ".content-list > b:nth-of-type(2) {\n margin-left: -1000000px;\n} <div class=\"content-list\">\n <b>Title:</b> some random text <br />\n <b>Title 2:</b> some large random text some large random text some large random text some large random text some large random text some large random text some large random text some large random text some large random text some large random text some large random text some large random text some large random text some large random text some large random text <br />\n <b>Title 3:</b> some random text <br />\n</div>" }, { "answer_id": 74495581, "author": "sohaib", "author_id": 11961514, "author_profile": "https://Stackoverflow.com/users/11961514", "pm_score": 0, "selected": false, "text": "div {\nfont-size: 0px\n}\n\ndiv > b:nth-child(1) {\n font-size: 16px\n} <div>\n <b>Title:</b> some random text <br/>\n</div>" }, { "answer_id": 74495628, "author": "erecodes", "author_id": 18703252, "author_profile": "https://Stackoverflow.com/users/18703252", "pm_score": 0, "selected": false, "text": "#content-list div:nth-child(2) {\n display: none;\n} <div id=\"content-list\">\n <div>\n <h2>Title 1</h2>\n <span>some random text</span>\n </div>\n \n <div>\n <h2>Title 2</h2>\n <span>some random text</span>\n </div>\n \n <div>\n <h2>Title 3</h2>\n <span>some random text</span>\n </div>\n</div>" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16491376/" ]
74,495,415
<p><a href="https://i.stack.imgur.com/vxGDv.png" rel="nofollow noreferrer">space between my browser and my div</a></p> <p>Hi guys, I'm a new dev and I would like to know how to erase the space between my div and my browser</p> <p>Thanks</p> <p>I try right=0; I try right=-10px; I try clear=both, but I'm not sure for this one.</p>
[ { "answer_id": 74495469, "author": "divdev86", "author_id": 20543274, "author_profile": "https://Stackoverflow.com/users/20543274", "pm_score": 2, "selected": true, "text": "body{\n margin: 0;\n padding: 0;\n}\n" }, { "answer_id": 74495520, "author": "glenny", "author_id": 19911894, "author_profile": "https://Stackoverflow.com/users/19911894", "pm_score": 0, "selected": false, "text": "*{\nmargin: 0;\npadding: 0;\nbox-sizing: border-box;\n}\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20543176/" ]
74,495,436
<p>I am trying to sort <code>reservesUSD</code> of nested object <code>dailyPoolSnapshots</code> In descending order by timestamp and return it's first value (in other words, return the latest entry). I know almost nothing of GraphQL and it's documentation seems confusing and scarce. Can someone help me to figure out how to sort my objects?</p> <p>I am using <a href="https://thegraph.com/hosted-service/subgraph/convex-community/volume-mainnet" rel="nofollow noreferrer">subgraphs</a> on the Ethereum mainnet for <code>Curve.fi</code> to get information about pools</p> <p>My code:</p> <pre><code> pools(first: 1000) { name address coins coinDecimals dailyPoolSnapshots(first: 1, orderBy:{field: timestamp, order: DESC}) { reservesUSD timestamp } } } </code></pre> <p>It throws and error:</p> <pre><code> &quot;errors&quot;: [ { &quot;locations&quot;: [ { &quot;line&quot;: 0, &quot;column&quot;: 0 } ], &quot;message&quot;: &quot;Invalid value provided for argument `orderBy`: Object({\&quot;direction\&quot;: Enum(\&quot;DESC\&quot;), \&quot;field\&quot;: Enum(\&quot;timestamp\&quot;)})&quot; } ] }``` </code></pre>
[ { "answer_id": 74495469, "author": "divdev86", "author_id": 20543274, "author_profile": "https://Stackoverflow.com/users/20543274", "pm_score": 2, "selected": true, "text": "body{\n margin: 0;\n padding: 0;\n}\n" }, { "answer_id": 74495520, "author": "glenny", "author_id": 19911894, "author_profile": "https://Stackoverflow.com/users/19911894", "pm_score": 0, "selected": false, "text": "*{\nmargin: 0;\npadding: 0;\nbox-sizing: border-box;\n}\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11621998/" ]
74,495,437
<p>I have a data range in Google Sheets where I want to sort the data by column B, but only return column A. If it matters, column A is a string, column B is integers.</p> <p>Using =SORT(A1:B10,2,FALSE) returns both columns A and B, sorted by column B...but I only want it to return column A.</p> <p>I've also tried: =QUERY((SORT(A1:B10,2,FALSE)),&quot;select *&quot;) &lt;- does exactly the same as sort, tried just for testing =QUERY((SORT(A1:B10,2,FALSE)),&quot;select col1&quot;) &lt;- #value error =QUERY((SORT(A1:B10,2,FALSE)),&quot;select A&quot;) &lt;- #value error (also tried &quot;select A:A&quot; and &quot;select A1:A10&quot;) =QUERY((SORT(A1:B10,2,FALSE)),&quot;select Stat&quot;) &lt;- #value error</p> <p>I've also tried all of the above, but starting with =QUERY(A1:B10,SORT(...</p> <p>Am I using QUERY wrong? Is SORT not what I want? I could just use SORT in a hidden part of the sheet, then reference the column I want but that feels cheaty, I want to know if there's a way to do what I want to do.</p>
[ { "answer_id": 74495469, "author": "divdev86", "author_id": 20543274, "author_profile": "https://Stackoverflow.com/users/20543274", "pm_score": 2, "selected": true, "text": "body{\n margin: 0;\n padding: 0;\n}\n" }, { "answer_id": 74495520, "author": "glenny", "author_id": 19911894, "author_profile": "https://Stackoverflow.com/users/19911894", "pm_score": 0, "selected": false, "text": "*{\nmargin: 0;\npadding: 0;\nbox-sizing: border-box;\n}\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20543184/" ]
74,495,448
<p>I seem to be facing an issue with my NextJS (13) app. Somehow Chrome gives me the next error:</p> <p>TypeError: Cannot read properties of null (reading 'CodeMirror')</p> <p>It happens with every entry/event to any input field in my app and until yesterday i didn't have any issues. I haven't made any changes to my code that could have had an effect on these input fields. Safari and Firefox don't give me any errors.</p> <pre><code>&lt;input type=&quot;text&quot; name=&quot;title&quot; defaultValue={post.title} onChange={(e) =&gt; setTitle(e.target.value)} placeholder=&quot;title&quot; /&gt; </code></pre> <p>Also in my deployment on Vercel the input fields work perfect in Chrome. So it seems to be limited to localhost/Chrome.</p> <p>Hopefully someone understands more about whats happening here than i do.</p>
[ { "answer_id": 74495469, "author": "divdev86", "author_id": 20543274, "author_profile": "https://Stackoverflow.com/users/20543274", "pm_score": 2, "selected": true, "text": "body{\n margin: 0;\n padding: 0;\n}\n" }, { "answer_id": 74495520, "author": "glenny", "author_id": 19911894, "author_profile": "https://Stackoverflow.com/users/19911894", "pm_score": 0, "selected": false, "text": "*{\nmargin: 0;\npadding: 0;\nbox-sizing: border-box;\n}\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20543009/" ]
74,495,449
<p>I'm new to databases, so I wanted to make a program to perform simple queries in mysql with C++ in VS Code, in Windows 10. Last time I had problems with linking the library, and now it seems like I managed to fixed them. I have the following code taken from another source by adding my system configurations:</p> <pre><code>#include &lt;iostream&gt; #include &lt;windows.h&gt; #include &quot;C:/Program Files/MySQL/MySQL Server 8.0/include/mysql.h&quot; int main(){ MYSQL* conn; conn = mysql_init(0); conn = mysql_real_connect(conn, &quot;localhost&quot;, &quot;root&quot;, &quot;password&quot;, &quot;project&quot;, 0, NULL, 0); if(conn){ std::cout &lt;&lt; &quot;Connected&quot; &lt;&lt; std::endl; } else { std::cout &lt;&lt; &quot;Not connected&quot; &lt;&lt; std::endl; } } </code></pre> <p>When I compile it with the command <code>g++ main.cpp -Wall -Werror -I &quot;C:/Program Files/MySQL/MySQL Server 8.0/include&quot; -L &quot;C:/Program Files/MySQL/MySQL Server 8.0/lib&quot; -lmysql</code>, it compiles without reporting any errors. However, if I try to run it, the program simply terminates. I don't understand what problems could be. I suspect the problem might be with mysql connector, but as I said I'm new to it, so I still have doubts. So I would really appreciate it if you could help me out how I can proceed further.</p> <p>I looked for similar questions, and they helped me only for linking to the library.</p>
[ { "answer_id": 74495830, "author": "Maciej Polański", "author_id": 19165018, "author_profile": "https://Stackoverflow.com/users/19165018", "pm_score": -1, "selected": false, "text": "mysql_init" }, { "answer_id": 74665398, "author": "Ёқуб Давлатов", "author_id": 20485270, "author_profile": "https://Stackoverflow.com/users/20485270", "pm_score": 0, "selected": false, "text": "libmysql.dll main.cpp" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20485270/" ]
74,495,489
<p>I want to spawn multiple processes which would do some computation and collect the results of each in a list. Consider this, although incorrect, toy example:</p> <pre><code>defmodule Counter do def loop(items \\ []) def loop(items) do receive do {:append, item} -&gt; IO.inspect([item | items]) loop([item | items]) :exit -&gt; items end end def push(from_pid, item) do send(from_pid, {:append, :math.pow(item, 2)}) end def run() do for item &lt;- 1..10 do spawn(Counter, :push, [self(), item]) end loop() end end Counter.run() </code></pre> <ol> <li>Method <code>run/1</code> spawns 10 processes with 2 arguments - process id and number.</li> <li>Each spawned process computes the result (in this case, squares the given number) and send the result back.</li> <li>Method <code>loop/1</code> listens for messages and accumulates the results into a list.</li> </ol> <p>The problem is I do not understand how to properly stop listening to messages after all created processes are done. I cannot just send another message type (in this case, <code>:exit</code>) to stop calling <code>loop/1</code> recursively as some processes might not be done yet. Of course, I could keep track of the number of received messages and do not call <code>loop/1</code> again if the target count is reached. However, I doubt that it is a correct approach.</p> <p>How do I implement this properly?</p>
[ { "answer_id": 74495825, "author": "Everett", "author_id": 274030, "author_profile": "https://Stackoverflow.com/users/274030", "pm_score": 2, "selected": false, "text": "Task.Supervisor.async_stream_nolink send receive max_concurrency iex> Task.Supervisor.start_link(name: TmpTaskSupervisor)\niex> Task.Supervisor.async_stream_nolink(\n TmpTaskSupervisor,\n 1..10,\n fn item ->\n IO.puts(\"processing item #{item}\")\n Process.sleep(1_000)\n end,\n timeout: 120_000,\n max_concurrency: 2\n)\n|> Stream.run()\n :ok iex> Task.Supervisor.start_link(name: TmpTaskSupervisor)\niex> Task.Supervisor.async_stream_nolink(\n TmpTaskSupervisor,\n 1..10,\n fn n ->\n n * n\n end,\n timeout: 120_000,\n max_concurrency: 2\n)\n|> Enum.to_list()\n[ok: 1, ok: 4, ok: 9, ok: 16, ok: 25, ok: 36, ok: 49, ok: 64, ok: 81, ok: 100]\n" }, { "answer_id": 74497375, "author": "7stud", "author_id": 926143, "author_profile": "https://Stackoverflow.com/users/926143", "pm_score": 2, "selected": true, "text": "spawn/3 loop() loop() {FirstPid, Result} {self(), Result} loop()" }, { "answer_id": 74498693, "author": "Adam Millerchip", "author_id": 1225617, "author_profile": "https://Stackoverflow.com/users/1225617", "pm_score": 1, "selected": false, "text": "1..10\n|> Flow.from_enumerable(max_demand: 1)\n|> Flow.map(&(&1 * &1))\n|> Enum.to_list()\n [1, 9, 16, 25, 36, 49, 4, 64, 81, 100]\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18782190/" ]
74,495,503
<p>I have a folder with a number of subfolders containing files and want to copy all files to the root folder but only overwrite if newer.</p> <p>In powershell I can do -</p> <p>Get-ChildItem D:\VaM\Custom\Atom\Person\Morphs\temp2\female -Recurse -file | Copy-Item -Destination D:\VaM\Custom\Atom\Person\Morphs\female</p> <p>But this will overwrite all files, I only want to overwrite files if the copied file is newer.</p> <p>robocopy can overwrite only older this but keeps the folder structure.</p>
[ { "answer_id": 74495825, "author": "Everett", "author_id": 274030, "author_profile": "https://Stackoverflow.com/users/274030", "pm_score": 2, "selected": false, "text": "Task.Supervisor.async_stream_nolink send receive max_concurrency iex> Task.Supervisor.start_link(name: TmpTaskSupervisor)\niex> Task.Supervisor.async_stream_nolink(\n TmpTaskSupervisor,\n 1..10,\n fn item ->\n IO.puts(\"processing item #{item}\")\n Process.sleep(1_000)\n end,\n timeout: 120_000,\n max_concurrency: 2\n)\n|> Stream.run()\n :ok iex> Task.Supervisor.start_link(name: TmpTaskSupervisor)\niex> Task.Supervisor.async_stream_nolink(\n TmpTaskSupervisor,\n 1..10,\n fn n ->\n n * n\n end,\n timeout: 120_000,\n max_concurrency: 2\n)\n|> Enum.to_list()\n[ok: 1, ok: 4, ok: 9, ok: 16, ok: 25, ok: 36, ok: 49, ok: 64, ok: 81, ok: 100]\n" }, { "answer_id": 74497375, "author": "7stud", "author_id": 926143, "author_profile": "https://Stackoverflow.com/users/926143", "pm_score": 2, "selected": true, "text": "spawn/3 loop() loop() {FirstPid, Result} {self(), Result} loop()" }, { "answer_id": 74498693, "author": "Adam Millerchip", "author_id": 1225617, "author_profile": "https://Stackoverflow.com/users/1225617", "pm_score": 1, "selected": false, "text": "1..10\n|> Flow.from_enumerable(max_demand: 1)\n|> Flow.map(&(&1 * &1))\n|> Enum.to_list()\n [1, 9, 16, 25, 36, 49, 4, 64, 81, 100]\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15388876/" ]
74,495,513
<pre><code>@client.event async def on_message(message): if message.author == client.user: return List = open(&quot;D:/code/code/DIscord bot/myFile.txt&quot;).readlines() List = str(List).replace(&quot;\\n&quot;, &quot; &quot;) if message.content in List: msg = 'REAL!' await message.reply(msg) </code></pre> <p>im trying to get the bot to read all the sentences in a .txt file (one sentence per row) and then when that phrase is said in discord, itll respond with &quot;REAL!&quot; this all works but it seems to also respond to every message sent.</p>
[ { "answer_id": 74495825, "author": "Everett", "author_id": 274030, "author_profile": "https://Stackoverflow.com/users/274030", "pm_score": 2, "selected": false, "text": "Task.Supervisor.async_stream_nolink send receive max_concurrency iex> Task.Supervisor.start_link(name: TmpTaskSupervisor)\niex> Task.Supervisor.async_stream_nolink(\n TmpTaskSupervisor,\n 1..10,\n fn item ->\n IO.puts(\"processing item #{item}\")\n Process.sleep(1_000)\n end,\n timeout: 120_000,\n max_concurrency: 2\n)\n|> Stream.run()\n :ok iex> Task.Supervisor.start_link(name: TmpTaskSupervisor)\niex> Task.Supervisor.async_stream_nolink(\n TmpTaskSupervisor,\n 1..10,\n fn n ->\n n * n\n end,\n timeout: 120_000,\n max_concurrency: 2\n)\n|> Enum.to_list()\n[ok: 1, ok: 4, ok: 9, ok: 16, ok: 25, ok: 36, ok: 49, ok: 64, ok: 81, ok: 100]\n" }, { "answer_id": 74497375, "author": "7stud", "author_id": 926143, "author_profile": "https://Stackoverflow.com/users/926143", "pm_score": 2, "selected": true, "text": "spawn/3 loop() loop() {FirstPid, Result} {self(), Result} loop()" }, { "answer_id": 74498693, "author": "Adam Millerchip", "author_id": 1225617, "author_profile": "https://Stackoverflow.com/users/1225617", "pm_score": 1, "selected": false, "text": "1..10\n|> Flow.from_enumerable(max_demand: 1)\n|> Flow.map(&(&1 * &1))\n|> Enum.to_list()\n [1, 9, 16, 25, 36, 49, 4, 64, 81, 100]\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20543271/" ]
74,495,518
<p>I had a strange error occur today, and I am able to reproduce it with the following example:</p> <pre><code>files = [&quot;A.txt&quot;, &quot;B.txt&quot;] rule all: input: &quot;copied_joined.txt&quot; rule A: input: files output: &quot;joined.txt&quot; shell: &quot;cat {input} &gt;&gt; {output}&quot; rule B: input: data=rules.A.output output: &quot;copied_joined.txt&quot; shell: &quot;&quot;&quot; if [[ {input} == &quot;joined.txt&quot; ]]; then echo &quot;Running on {input}!&quot; cp {input.data[0]} {output} elif {input} == &quot;garbage_string&quot; ]]; then echo &quot;Running on garbage!&quot; cp {input.data[1]} {output} fi &quot;&quot;&quot; </code></pre> <p>In <code>rule B</code>, the <code>elif</code> section is never reached, but Snakemake still shows an error <code>IndexError: list index out of range</code>, because I am accessing <code>input.data[1]</code>, which doesn't exist.</p> <p>In my specific use case, I am using an input function that will provide one or two files based on wildcards. I am then performing specific actions on the files, similar to the if/elif above, which causes Snakemake to fail. Removing the <code>cp {input.data[1]} {output}</code> resolves the issue</p> <p>To resolve my own issue, if I was originally going to return a single file, I returned two copies of the same file, such as:</p> <pre class="lang-py prettyprint-override"><code>def input_data(wildcards): if something_true: file_one = &quot;ONE.txt&quot; return &quot;ONE.txt&quot;, &quot;TWO.txt&quot; else: return &quot;THREE.txt&quot;, &quot;THREE.txt&quot; </code></pre> <p>My hacky solution works, but I was wondering if there was a more agrred-upon fix for this?</p> <p>Thanks for any help!!</p>
[ { "answer_id": 74495717, "author": "Josh Loecker", "author_id": 13885200, "author_profile": "https://Stackoverflow.com/users/13885200", "pm_score": 1, "selected": false, "text": "[] input files = [\"A.txt\", \"B.txt\"]\n\n\nrule all:\n input: \"copied_joined.txt\"\n\nrule A:\n input: files\n output: \"joined.txt\"\n shell: \"cat {input} >> {output}\"\n\n\nrule B:\n input:\n data=rules.A.output\n output: \"copied_joined.txt\"\n shell:\n \"\"\"\n if [[ {input} == \"joined.txt\" ]]; then\n echo \"Running on {input}!\"\n cp {input.data} {output}\n elif {input} == \"garbage_string\" ]]; then\n echo \"Running on garbage!\"\n cp {input.data} {output}\n fi\n \"\"\"\n\n cp" }, { "answer_id": 74517604, "author": "dariober", "author_id": 1114453, "author_profile": "https://Stackoverflow.com/users/1114453", "pm_score": 0, "selected": false, "text": "rule B:\n input:\n data=rules.A.output\n output: \"copied_joined.txt\"\n run:\n if len(input.data) == 1:\n shell(\"cp {input.data[0]} {output}\") # Or use only python code if you only need to copy files\n elif len(input.data) == 2:\n shell(\"cp {input.data[1]} {output}\")\n else:\n sys.exit(\"This should not happen\")\n shell: \"cat {input} >> {output}\"\n {output} {input} {output}" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13885200/" ]
74,495,523
<p>I am having a trouble where an array of Objects are returning [Object object]. What could be the missing fix to get the value of product from the mapped targeted values.</p> <p>this is my sample array.</p> <pre><code>const product = [{food:'BREAD',price: 6}] </code></pre> <p>this is where I map the values and get the targeted value.</p> <pre><code>&lt;Form &gt; {product.map((item, index) =&gt; ( &lt;div key={index} className=&quot;mb-3&quot;&gt; &lt;Form.Check input value={[item]} id={[item.food]} type=&quot;checkbox&quot; label={`${item.food}`} onClick={handleChangeCheckbox('PRODUCTS')} /&gt; &lt;/div&gt; ))} &lt;/Form&gt; </code></pre> <p>this handles the <code>e.target.value</code> from checked checkboxes.</p> <pre><code> const handleChangeCheckbox = input =&gt; event =&gt; { var value = event.target.value; var isChecked = event.target.checked; setChecked(current =&gt; current.map(obj =&gt; { if (obj.option === input) { if(isChecked){ return {...obj, chosen: [...obj.chosen, value ] }; }else{ var newArr = obj.chosen; var index = newArr.indexOf(event.target.value); newArr.splice(index, 1); // 2nd parameter means remove one item only return {...obj, chosen: newArr}; } } return obj; }), ); console.log(checked); } </code></pre> <p>finally, this is where I am having problems. Chosen is returning [Object object]<a href="https://i.stack.imgur.com/BsxnW.png" rel="nofollow noreferrer">console.log(checked)</a>.</p> <pre><code> const [checked, setChecked] = useState([ { option: 'PRODUCTS', chosen: [], } ]); </code></pre> <p>What do I insert inside <code>chosen:[]</code> to read the following arrays. Im expecting to see</p> <pre><code>0: food: 'bread' price: '6' </code></pre> <p>Thank you so much for helping me!</p>
[ { "answer_id": 74495954, "author": "Pipera", "author_id": 12664292, "author_profile": "https://Stackoverflow.com/users/12664292", "pm_score": 0, "selected": false, "text": "onClick={handleChangeCheckbox('PRODUCTS')} onClick={(event) => handleChangeCheckbox('PRODUCTS', event)}" }, { "answer_id": 74496028, "author": "Benjamin", "author_id": 1830563, "author_profile": "https://Stackoverflow.com/users/1830563", "pm_score": 1, "selected": false, "text": "[Object object] item event const handleChangeCheckbox = (input) => (value) => {\n setChecked((current) => {\n // Value is checked if it exists in the current chosen array\n const isChecked = current.chosen.find((item) => item.food === value.food) !== undefined;\n\n // Remove it from state\n if (isChecked) {\n return {\n ...current,\n chosen: current.chosen.filter((item) => item.food === value.food),\n };\n }\n\n // Add it to state\n return {\n ...current,\n chosen: [...current, value],\n };\n });\n};\n onClick={() => handleChangeCheckbox('PRODUCTS', item)}\n Form.Check input type=\"checkbox\" checked checked chosen <Form>\n {product.map((item, index) => (\n <div key={item.food} className=\"mb-3\">\n <Form.Check\n type=\"checkbox\"\n id={item.food}\n label={item.food}\n checked={checked.chosen.find((chosen) => chosen.food === item.food) !== undefined}\n onClick={() => handleChangeCheckbox('PRODUCTS', item)}\n />\n </div>\n ))}\n</Form>\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20542465/" ]
74,495,530
<p>How can I make two images be displayed like in my drawing below using CSS only? The photos are both perfect squares, and I understand that part of the image will not be shown by doing this. That is intentional. The gap in the middle is just my poor drawing skills, and it's not supposed to be there.</p> <p>Additionally, if it is possible to have a nice fade effect between them where they meet, that would be even better, but I am assuming CSS is incapable of such magic.</p> <p><a href="https://i.stack.imgur.com/ZHDgG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZHDgG.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74495765, "author": "zolaDesigner", "author_id": 12191340, "author_profile": "https://Stackoverflow.com/users/12191340", "pm_score": -1, "selected": false, "text": "position: relative position: absolute" }, { "answer_id": 74496154, "author": "Temani Afif", "author_id": 8620333, "author_profile": "https://Stackoverflow.com/users/8620333", "pm_score": 2, "selected": true, "text": ".box {\n width: 250px;\n aspect-ratio: 1;\n display: grid;\n}\n\n.box img {\n grid-area: 1/1;\n width: 100%;\n}\n\n.box img:first-child {\n -webkit-mask: linear-gradient(45deg,#0000 30%,#000 70%);\n}\n.box img:last-child {\n -webkit-mask: linear-gradient(45deg,#000 30%,#0000 70%);\n} <div class=\"box\">\n <img src=\"https://picsum.photos/id/582/400/400\" alt=\"a wolf\">\n <img src=\"https://picsum.photos/id/1074/400/400\" alt=\"a lioness\">\n</div>" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19643541/" ]
74,495,560
<p>I need help with a problem I have to solve with SQL.</p> <p>Using -JOIN I have to display the students that were not enrolled in any courses. Using two tables: db1.ncc.Student and db1.ncc.Registration. Student table has 4 students and in table registration there's only three out of those four.</p> <p>In my last attempt to solve this I tried using a -LEFT JOIN to get all the matches and the unmatched student from the student table then I used -WHERE to try and filter the results to only the unmatched student.</p> <p>I was unsuccessful and after trying many other ways previous to this one I've given up and started seeking some help.</p> <pre><code>select STUDENT.StudentID , STUDENT.StudentName from db1.ncc.STUDENT left join db1.ncc.REGISTRATION on STUDENT.StudentID=REGISTRATION.StudentID where REGISTRATION.StudentID&lt;&gt;STUDENT.StudentID </code></pre> <p>note: I have to use join to do this</p>
[ { "answer_id": 74495591, "author": "GMB", "author_id": 10676716, "author_profile": "https://Stackoverflow.com/users/10676716", "pm_score": 3, "selected": true, "text": "LEFT JOIN WHERE NULL NULL != ... select s.StudentID, s.StudentName \nfrom db1.ncc.STUDENT s\nleft join db1.ncc.REGISTRATION r on r.StudentID=s.StudentID \nwhere r.StudentID IS NULL\n s r" }, { "answer_id": 74495605, "author": "Cetin Basoz", "author_id": 894977, "author_profile": "https://Stackoverflow.com/users/894977", "pm_score": 0, "selected": false, "text": "select STUDENT.StudentID, STUDENT.StudentName from db1.ncc.STUDENT\n left join db1.ncc.REGISTRATION \n on STUDENT.StudentID=REGISTRATION.StudentID \nwhere REGISTRATION.StudentID IS NULL;\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19428121/" ]
74,495,570
<p>I'm having a strange issue with <strong>Visual Studio 2022 version 17.4.1</strong>.</p> <p>Basically it seems that, starting from this version, Visual Studio 2022 does <strong>not</strong> honor the tabs configuration for the C# language when adding new items to the project via the <em>Add -&gt; New Item</em> wizard.</p> <p>My configuration for the text editor tabs for the C# language (<em>Tools -&gt; Options -&gt; Text Editor -&gt; C# -&gt; Tabs</em>) are the followings:</p> <ul> <li>Indenting: Smart</li> <li>Tab Size: 2</li> <li>Indent Size: 2</li> <li>Insert Spaces selected</li> </ul> <p>With the previous versions of Visual Studio 2022 when a new class was added to the project these settings were honored as expected. The indentation used for the C# code in the newly generated class was 2 spaces, as expected given these settings.</p> <p>Starting from version <strong>17.4.1</strong> I noticed that these settings are always ignored when a new class is added to the project via the <em>Add -&gt; Class</em> or the <em>Add -&gt; New Item</em> wizard.<strong>In the newly added class, the indentation used is always 4 spaces instead of the expected 2 spaces</strong>. So, my configuration is <strong>not</strong> being honored.</p> <p>Is this an expected behavior ? Is there a known workaround for this ?</p> <p>This is quite annoying because I have to reformat each time I add a new class to the project.</p>
[ { "answer_id": 74640568, "author": "Enrico Massone", "author_id": 4331637, "author_profile": "https://Stackoverflow.com/users/4331637", "pm_score": 0, "selected": false, "text": "17.4.2" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4331637/" ]
74,495,586
<p>I would like <code>name3</code> array to include the documentation text of the ascendant element <code>&lt;xsd:element name=&quot;PurchaseOrder&quot; type=&quot;tns:PurchaseOrderType&quot;/&gt;</code>. I would like to have a generic code which prints the doccumentation according to the name of the xsd:element.</p> <p>I have succeeded to include all the documentations using the xpath I provided. But I want the extra condition I mentioned to be included in the xpath.</p> <pre><code>&lt;xsd:schema xmlns:xsd=&quot;http://www.w3.org/2001/XMLSchema&quot; xmlns:tns=&quot;http://tempuri.org/PurchaseOrderSchema.xsd&quot; targetNamespace=&quot;http://tempuri.org/PurchaseOrderSchema.xsd&quot; elementFormDefault=&quot;qualified&quot;&gt; &lt;xsd:element name=&quot;PurchaseOrder&quot; type=&quot;tns:PurchaseOrderType&quot;/&gt; &lt;xsd:complexType name=&quot;PurchaseOrderType&quot;&gt; &lt;xsd:annotation&gt; &lt;xsd:documentation xml:lang=&quot;en&quot;&gt; commmennttt &lt;/xsd:documentation&gt; &lt;/xsd:annotation&gt; &lt;xsd:sequence&gt; &lt;xsd:element name=&quot;ShipTo&quot; type=&quot;tns:USAddress&quot; maxOccurs=&quot;2&quot;/&gt; &lt;xsd:element name=&quot;BillTo&quot; type=&quot;tns:USAddress&quot;/&gt; &lt;/xsd:sequence&gt; &lt;xsd:attribute name=&quot;OrderDate&quot; type=&quot;xsd:date&quot;/&gt; &lt;/xsd:complexType&gt; &lt;xsd:complexType name=&quot;USAddress&quot;&gt; &lt;xsd:sequence&gt; &lt;xsd:element name=&quot;name&quot; type=&quot;xsd:string&quot;/&gt; &lt;xsd:element name=&quot;street&quot; type=&quot;xsd:string&quot;/&gt; &lt;xsd:element name=&quot;city&quot; type=&quot;xsd:string&quot;/&gt; &lt;xsd:element name=&quot;state&quot; type=&quot;xsd:string&quot;/&gt; &lt;xsd:element name=&quot;zip&quot; type=&quot;xsd:integer&quot;/&gt; &lt;/xsd:sequence&gt; &lt;xsd:attribute name=&quot;country&quot; type=&quot;xsd:NMTOKEN&quot; fixed=&quot;US&quot;/&gt; &lt;/xsd:complexType&gt; &lt;/xsd:schema&gt; t3 = etree.ElementTree(file='new.xsd') name3 = t3.xpath(&quot;//xsd:documentation[text()]&quot;, namespaces={&quot;xsd&quot;:&quot;http://www.w3.org/2001/XMLSchema&quot;}) name3 = [a.text for a in name3] print(name3[0]) </code></pre> <p>Thanks</p>
[ { "answer_id": 74495847, "author": "LMC", "author_id": 2834978, "author_profile": "https://Stackoverflow.com/users/2834978", "pm_score": 2, "selected": true, "text": "xsd:element xsd:documentation from lxml import etree\ncrit = 'PurchaseOrder'\nt3 = etree.parse('test.xsd')\nns = {\"xsd\":\"http://www.w3.org/2001/XMLSchema\"}\nxpathExpr=f\"//xsd:element[@name='{crit}']/following-sibling::*//xsd:documentation[text()]\"\nprint(xpathExpr)\nname3 = t3.xpath(xpathExpr, namespaces=ns)\n\n# avoid reusing a variable for a different purpose\ncomments = [a.text for a in name3]\nprint(comments)\n //xsd:element[@name='PurchaseOrder']/following-sibling::*//xsd:documentation[text()]\n['\\n commmennttt\\n ']\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4620387/" ]
74,495,590
<p>I've searched around StackOverflow for the issue I'm facing and can't quite find something similar.<br /> I'm working with a large time series, with a portion of the dataset below. With that, I'm trying to find a way to add an exponential fit to it using ggplot. Others have used <code>geom_smooth(method = &quot;lm&quot;, formula = (y ~ exp(x)))</code> but that doesn't work with time series data or POSIXct class variables and returns the error <code>&quot;Computation failed in stat_smooth(): NA/NaN/Inf in 'x'&quot;</code>. Previously, I simply used <code>method = &quot;loess&quot;, span = 0.1</code>, but it doesn't capture the nature of the data very well.</p> <p>Any help you could provide would be greatly appreciated!</p> <pre><code>data&lt;-structure(list(avg_time = structure(c(1551420000, 1551506400, 1551592800, 1551679200, 1551765600, 1551852000, 1551938400, 1552024800, 1552111200, 1552197600, 1552280400, 1552366800, 1552453200, 1552539600, 1552626000, 1552712400, 1552798800, 1552885200, 1552971600, 1553058000, 1553144400, 1553230800, 1553317200, 1553403600, 1553490000, 1553576400, 1553662800, 1553749200, 1553835600, 1553922000, 1554008400, 1554094800, 1554181200, 1554267600, 1554354000, 1554440400, 1554526800, 1554613200, 1554699600, 1554786000, 1554872400, 1554958800, 1555045200, 1555131600, 1555218000, 1555304400, 1555390800, 1555477200, 1555563600, 1555650000, 1555736400, 1555822800, 1555909200, 1555995600, 1556082000, 1556168400, 1556254800, 1556341200, 1556427600, 1556514000, 1556600400, 1556686800, 1556773200, 1556859600, 1556946000, 1557032400, 1557118800, 1557205200, 1557291600, 1557378000, 1557464400, 1557550800, 1557637200, 1557723600, 1557810000, 1557896400, 1557982800, 1558069200, 1558155600, 1558242000, 1558328400, 1558414800, 1558501200, 1558587600, 1558674000, 1558760400, 1558846800, 1558933200, 1559019600, 1559106000, 1559192400, 1559278800, 1559365200, 1559451600, 1559538000, 1559624400, 1559710800), tzone = &quot;&quot;, class = c(&quot;POSIXct&quot;, &quot;POSIXt&quot;)), ChlaMed = c(7.49786224129294, 6.33265484668835, 8.02891354394607, 8.36583527788548, 7.21848200004542, 3.87836804380364, 6.12041645730209, 6.11129053757413, 3.82314913061958, 6.66935722139803, 10.5846145945807, 1.3922819262622, 2.46397555374784, 3.5387541991258, 9.4377648342203, 3.8359888625491, 9.92938437268906, 9.84931346445947, 7.61136832417625, 10.422317215878, 9.92795625389519, 10.2145441518957, 9.87188069822321, 6.75768698400432, 7.50045495545547, 7.3979513362914, 12.0524471187313, 11.0031790178811, 9.23929610466274, 12.2253404703908, 10.8260865574934, 5.79312487695101, 7.86859910828088, 13.9784098169617, 13.3707820039944, 8.11038273190177, 13.852156279962, 6.94197529427832, 10.1752314872054, 10.3435349795235, 14.4105077850521, 12.3100928225917, 11.4965118440029, 13.5176883961026, 10.4577799463301, 11.8074169933709, 13.245655700942, 13.5716513275785, 14.0549071116729, 14.6034112846714, 13.8998981372714, 11.0290734663967, 12.7725741301044, 14.0037640681163, 12.99276716795, 12.9177278644427, 15.6103759408624, 11.4159351143177, 14.7053508114725, 14.3380030612979, 14.846661975045, 14.1918024501013, 14.1478311220769, 15.4169566103641, 14.1251696199414, 13.4057098254015, 15.0936022765442, 14.94796281727, 11.9943525040373, 15.6886181916423, 15.7057435474498, 16.1855936444667, 17.4195546581076, 16.977113306558, 16.4826655395595, 14.273959862613, 18.6570604979906, 15.2969835201503, 15.6502935625097, 16.4619111787213, 17.8995674961064, 16.9938925321631, 17.409705465615, 19.7838080835222, 18.7386731671602, 19.6515930205419, 20.4308399460097, 18.787235170191, 18.758368516805, 19.2927499812326, 19.4763785903839, 20.4249755976496, 19.0471858942877, 20.0134726662527, 20.9237871993584, 20.0967875761179, 20.7116516016657)), row.names = c(NA, -97L), class = c(&quot;tbl_df&quot;, &quot;tbl&quot;, &quot;data.frame&quot;)) </code></pre>
[ { "answer_id": 74496072, "author": "langtang", "author_id": 4447540, "author_profile": "https://Stackoverflow.com/users/4447540", "pm_score": 3, "selected": true, "text": "nls() data %>% \n mutate(\n d = as.numeric(difftime(as.Date(avg_time),min(as.Date(avg_time)),units = \"days\")),\n preds =predict(nls(ChlaMed~a*exp(r*d), start = list(a=0.5, r=0.1), data=data))\n ) %>% \n ggplot(aes(x=avg_time)) + \n geom_point(aes(y=ChlaMed)) + \n geom_line(aes(y=preds),color=\"red\", linewidth=1.5)\n" }, { "answer_id": 74498680, "author": "Selcuk Disci", "author_id": 20018002, "author_profile": "https://Stackoverflow.com/users/20018002", "pm_score": 1, "selected": false, "text": "timetk log library(timetk)\n\n data %>%\n plot_time_series_regression(\n .date_var = avg_time,\n .formula = log(ChlaMed) ~ avg_time,\n .interactive =FALSE\n )\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8968645/" ]
74,495,594
<p>I'm trying to write a function that takes two parameters. The function starts two threads and uses one of the parameters inside one of the thread closures. This doesn't work because of the error &quot;Borrowed data escapes outside of closure&quot;. Here's the code.</p> <pre class="lang-rust prettyprint-override"><code>pub fn measure_stats(testdatapath: &amp;PathBuf, filenameprefix: &amp;String) { let (tx, rx) = mpsc::channel(); let filename = format!(&quot;test.txt&quot;) let measure_thread = thread::spawn(move || { let stats = sar(); fs::write(filename, stats).expect(&quot;failed to write output to file&quot;); // Send a signal that we're done. let _ = tx.send(()); }); thread::spawn(move || { let mut n = 0; loop { // Break if the measure thread is done. match rx.try_recv() { Ok(_) | Err(TryRecvError::Disconnected) =&gt; break, Err(TryRecvError::Empty) =&gt; {} } let filename = format!(&quot;{:04}.img&quot;, n); let filepath = Path::new(testdatapath).join(&amp;filename); random_file_write(&amp;filepath).unwrap(); random_file_read(&amp;filepath).unwrap(); fs::remove_file(&amp;filepath).expect(&quot;failed to remove file&quot;); n += 1; } }); measure_thread.join().expect(&quot;joining measure thread panicked&quot;); } </code></pre> <p>The problem is that <code>testdatapath</code> escapes the function body. I think this is a problem because the lifetime of <code>testdatapath</code> is only guaranteed until the end of the closure, but it needs to be the lifetime of the entire program. But it's a little confusing to me.<br /> I've tried cloning the variable, but that didn't help. I'm not sure how I'm supposed to do this. <strong>How do I use a function parameter inside the closure or accomplish the same goal some other more canonical way?</strong></p>
[ { "answer_id": 74495870, "author": "Kevin Reid", "author_id": 99692, "author_profile": "https://Stackoverflow.com/users/99692", "pm_score": 2, "selected": true, "text": "std::thread::scope() std::thread::spawn() pub fn measure_stats(testdatapath: PathBuf, filenameprefix: String) {\n move" }, { "answer_id": 74495899, "author": "yorodm", "author_id": 3393308, "author_profile": "https://Stackoverflow.com/users/3393308", "pm_score": 0, "selected": false, "text": "testdata PathBuff PathBuff Arc clone move" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1242028/" ]
74,495,627
<p>Consider the below setup:</p> <pre><code>typedef struct { float d; } InnerStruct; typedef struct { InnerStruct **c; } OuterStruct; float TestFunc(OuterStruct *b) { float a = 0.0f; for (int i = 0; i &lt; 8; i++) a += b-&gt;c[i]-&gt;d; return a; } </code></pre> <p>The for loop in TestFunc exactly replicates one in another function that I'm testing. Both loops are unrolled by gcc (4.9.2) but yield slightly different assembly after doing so.</p> <p>Assembly for my test loop:ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤAssembly for the original loop:</p> <pre><code>lwz r9,-0x725C(r13) lwz r9,0x4(r3) lwz r8,0x4(r9) lwz r8,0x8(r9) lwz r10,0x0(r9) lwz r10,0x4(r9) lwz r11,0x8(r9) lwz r11,0x0C(r9) lwz r4,0x4(r8) lwz r3,0x4(r8) lwz r10,0x4(r10) lwz r10,0x4(r10) lwz r8,0x4(r11) lwz r0,0x4(r11) lwz r11,0x0C(r9) lwz r11,0x10(r9) efsadd r4,r4,r10 efsadd r3,r3,r10 lwz r10,0x10(r9) lwz r8,0x14(r9) lwz r7,0x4(r11) lwz r10,0x4(r11) lwz r11,0x14(r9) lwz r11,0x18(r9) efsadd r4,r4,r8 efsadd r3,r3,r0 lwz r8,0x4(r10) lwz r0,0x4(r8) lwz r10,0x4(r11) lwz r8,0x0(r9) lwz r11,0x18(r9) lwz r11,0x4(r11) efsadd r4,r4,r7 efsadd r3,r3,r10 lwz r9,0x1C(r9) lwz r10,0x1C(r9) lwz r11,0x4(r11) lwz r9,0x4(r8) lwz r9,0x4(r9) efsadd r3,r3,r0 efsadd r4,r4,r8 lwz r0,0x4(r10) efsadd r4,r4,r10 efsadd r3,r3,r11 efsadd r4,r4,r11 efsadd r3,r3,r9 efsadd r4,r4,r9 efsadd r3,r3,r0 </code></pre> <p>The issue is the float values these instructions return are not exactly the same. And I can't change the original loop. I need to modify the test loop somehow to return the same values. I believe the test's assembly is equivalent to just adding each element one after another. I'm not very familiar with assembly so I wasn't sure how the above differences translated into c. I know this is the issue because if I add a print to the loops, they don't unroll and the results match exactly as expected.</p>
[ { "answer_id": 74495870, "author": "Kevin Reid", "author_id": 99692, "author_profile": "https://Stackoverflow.com/users/99692", "pm_score": 2, "selected": true, "text": "std::thread::scope() std::thread::spawn() pub fn measure_stats(testdatapath: PathBuf, filenameprefix: String) {\n move" }, { "answer_id": 74495899, "author": "yorodm", "author_id": 3393308, "author_profile": "https://Stackoverflow.com/users/3393308", "pm_score": 0, "selected": false, "text": "testdata PathBuff PathBuff Arc clone move" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8217821/" ]
74,495,630
<p>Trying to replace/update type A record name @ using godaddy api in laravel with Guzzle <a href="https://developer.godaddy.com/doc/endpoint/domains#/v1/recordReplaceTypeName" rel="nofollow noreferrer">https://developer.godaddy.com/doc/endpoint/domains#/v1/recordReplaceTypeName</a></p> <p><strong>Valid Headers</strong></p> <pre><code>$godaddy = Http::withHeaders([ 'Authorization' =&gt; 'sso-key ' . config('godaddy.key') . ':' . config('godaddy.secret'), ]); </code></pre> <p><strong>I try the get method and it works</strong></p> <pre><code>$response = $godaddy-&gt;get('https://api.godaddy.com/v1/domains/example.com/records/A/@'); </code></pre> <p><strong>Method put</strong></p> <pre><code>$response = $godaddy-&gt;put('https://api.godaddy.com/v1/domains/example.com/records/A/@', [ 'records' =&gt; [ 'data' =&gt; '127.0.0.1', 'priority' =&gt; 0, 'ttl' =&gt; 0, 'weight' =&gt; 0 ], ]); </code></pre> <p><strong>Response details</strong></p> <pre><code>array:3 [▼ &quot;code&quot; =&gt; &quot;INVALID_BODY&quot; &quot;fields&quot; =&gt; array:1 [▼ 0 =&gt; array:3 [▼ &quot;code&quot; =&gt; &quot;UNEXPECTED_TYPE&quot; &quot;message&quot; =&gt; &quot;is not a array&quot; &quot;path&quot; =&gt; &quot;records&quot; ] ] &quot;message&quot; =&gt; &quot;Request body doesn't fulfill schema, see details in `fields`&quot; ] </code></pre> <p>¿What i am doing bad?</p> <p><strong>Edited:</strong> <em><strong>Try</strong></em></p> <pre><code>$records = json_decode('[{&quot;data&quot;: &quot;127.0.0.1&quot;,&quot;name&quot;: &quot;@&quot;,&quot;port&quot;: 65535,&quot;priority&quot;: 0,&quot;protocol&quot;: &quot;string&quot;,&quot;service&quot;: &quot;string&quot;,&quot;ttl&quot;: 0,&quot;type&quot;: &quot;A&quot;,&quot;weight&quot;: 0}]'); $response = $godaddy-&gt;put('https://api.godaddy.com/v1/domains/example.com/records', [ 'records' =&gt; $records, ]); </code></pre> <pre><code>$response = $godaddy-&gt;put('https://api.godaddy.com/v1/domains/example.com/records/A/@', [ 'records' =&gt; [ [ 'data' =&gt; '127.0.0.1', 'priority' =&gt; 0, 'ttl' =&gt; 0, 'weight' =&gt; 0 ] ], ]); </code></pre>
[ { "answer_id": 74495870, "author": "Kevin Reid", "author_id": 99692, "author_profile": "https://Stackoverflow.com/users/99692", "pm_score": 2, "selected": true, "text": "std::thread::scope() std::thread::spawn() pub fn measure_stats(testdatapath: PathBuf, filenameprefix: String) {\n move" }, { "answer_id": 74495899, "author": "yorodm", "author_id": 3393308, "author_profile": "https://Stackoverflow.com/users/3393308", "pm_score": 0, "selected": false, "text": "testdata PathBuff PathBuff Arc clone move" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20114694/" ]
74,495,642
<p>I have a list</p> <pre><code>my_list = [[200.0, 10.0], [250.0, 190.0], [160.0, 210.0]] </code></pre> <p>I want get the list of these coordinate with space between them</p> <pre><code>req_list = &quot;200,10 250,190 160,210&quot; </code></pre> <p>to write these in SVG format for polygons.</p> <p>I tried replacing &quot;[]&quot; with &quot; &quot; but replace doesn't work for an array</p> <pre><code>my_list.replace(&quot;[&quot;, &quot; &quot;) </code></pre>
[ { "answer_id": 74495870, "author": "Kevin Reid", "author_id": 99692, "author_profile": "https://Stackoverflow.com/users/99692", "pm_score": 2, "selected": true, "text": "std::thread::scope() std::thread::spawn() pub fn measure_stats(testdatapath: PathBuf, filenameprefix: String) {\n move" }, { "answer_id": 74495899, "author": "yorodm", "author_id": 3393308, "author_profile": "https://Stackoverflow.com/users/3393308", "pm_score": 0, "selected": false, "text": "testdata PathBuff PathBuff Arc clone move" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3499052/" ]
74,495,679
<p>I am unable to get the expected results as shown in the picture below. There are 2 rules to follow</p> <ol> <li>The horizontal line should not continue till the bottom text. Instead, it should just be the height of the right text (multiline).</li> <li>Bottom text should align with the Right Text from the left side.</li> </ol> <p>Current Incorrect Snippet</p> <pre><code>@Composable fun Sample() { Row( modifier = Modifier .height(IntrinsicSize.Min) .padding(10.dp) ) { Text(&quot;Left Text&quot;) Divider( Modifier .padding(horizontal = 10.dp) .fillMaxHeight() .width(4.dp), color = Color.Black ) Column { Text(&quot;Right Looooong Text&quot;) Text(&quot;Bottom Text&quot;) } } } </code></pre> <p>Visual Representation</p> <p><a href="https://i.stack.imgur.com/n1Jc3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/n1Jc3.png" alt="Visual Representation" /></a></p>
[ { "answer_id": 74496485, "author": "Arthur Kasparian", "author_id": 19454251, "author_profile": "https://Stackoverflow.com/users/19454251", "pm_score": 0, "selected": false, "text": "var divHeight: Int = 0 // Must be initialized\n\nRow() {\n Text(text = \"Left Text\")\n\n Divider(\n modifier = Modifier\n .padding(horizontal = 10.dp)\n .width(4.dp)\n .height(divHeight.dp) // .dp converts measurement from Int to Dp\n )\n\n Column {\n Text(\n modifier = Modifier\n .onSizeChanged { divHeight = it.height },\n text = \"Right Looooong Text\"\n )\n Text(text = \"Bottom Text\")\n }\n}\n" }, { "answer_id": 74500193, "author": "Thracian", "author_id": 5457853, "author_profile": "https://Stackoverflow.com/users/5457853", "pm_score": 3, "selected": true, "text": "Layout @Composable\nfun Sample(horizontalPadding: Dp = 10.dp, dividerWidth: Dp = 4.dp) {\n Row(\n modifier = Modifier.padding(10.dp)\n ) {\n Text(\"Left Text\")\n\n Column {\n Row(modifier = Modifier.height(IntrinsicSize.Min)) {\n Divider(\n Modifier\n .padding(horizontal = horizontalPadding)\n .fillMaxHeight()\n .width(dividerWidth),\n color = Color.Black\n )\n\n Text(\"Right Loooooooooooooooooooong Text\")\n }\n\n Text(\n \"Bottom Text\",\n modifier = Modifier.offset(x = horizontalPadding * 2 + dividerWidth)\n )\n }\n }\n}\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1890849/" ]
74,495,684
<p>I'm trying to recreate this part of a website using HTML&amp;CSS : <a href="https://i.stack.imgur.com/23rJq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/23rJq.png" alt="1" /></a> and my part looks like this : <a href="https://i.stack.imgur.com/TEc9x.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TEc9x.png" alt="enter image description here" /></a> The size difference of the elements doesn't matter here but what triggers me is that in the first image, you can see the heading and the paragraph are &quot;sticking&quot; together. In my version, there is a space between them, and I can't figure out how to remove it.</p> <p>Here are the concerned code lines :</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>.cta { background: #3882f6; padding: 50px 100px; border-radius: 10px; border-style: none; color: #f9faf8; } .cta-container { padding: 100px 0; } .cta-signup-wrapper { display: flex; justify-content: space-between; align-items: flex-end; } .cta-signup { background: #3882f6; border-radius: 8px; border-style: none; color: #f9faf8; width: 120px; height: 33px; font-size: 16px; font-weight: bold; border: 2px solid #f9faf8; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="cta-container"&gt; &lt;div class="cta"&gt; &lt;div class="cta-wrapper"&gt; &lt;h3&gt;Call to action! It's time!&lt;/h3&gt; &lt;div class="cta-signup-wrapper"&gt; &lt;p&gt;Sign up for our product by clicking that button right over there!&lt;/p&gt; &lt;button type="button" class="cta-signup"&gt;Sign up&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>I tried playing around with the paragraph, removing it, or nesting the <code>cta-signup-wrapper</code> differently but without success.</p>
[ { "answer_id": 74495781, "author": "human bean", "author_id": 17186475, "author_profile": "https://Stackoverflow.com/users/17186475", "pm_score": -1, "selected": false, "text": "h3 p h3 h3 margin-bottom p margin-top .cta {\n background: #3882f6;\n padding: 50px 100px;\n border-radius: 10px;\n border-style: none;\n color: #f9faf8;\n}\n\n.cta-container {\n padding: 100px 0;\n}\n\n.cta-signup-wrapper {\n display: flex;\n justify-content: space-between;\n align-items: flex-end;\n}\n\n.cta-signup {\n background: #3882f6;\n border-radius: 8px;\n border-style: none;\n color: #f9faf8;\n width: 120px;\n height: 33px;\n font-size: 16px;\n font-weight: bold;\n border: 2px solid #f9faf8;\n}\n\nh3 {\n margin-bottom: 0;\n}\n\np {\n margin-top: 0;\n} <div class=\"cta-container\">\n <div class=\"cta\">\n <div class=\"cta-wrapper\">\n <h3>Call to action! It's time!</h3>\n <div class=\"cta-signup-wrapper\">\n <p>Sign up for our product by clicking that button right over there!</p>\n <button type=\"button\" class=\"cta-signup\">Sign up</button>\n </div>\n </div>\n </div>\n</div>" }, { "answer_id": 74495808, "author": "jerry", "author_id": 20493210, "author_profile": "https://Stackoverflow.com/users/20493210", "pm_score": 1, "selected": true, "text": ".cta {\n background: #3882f6;\n padding: 50px 100px;\n border-radius: 10px;\n border-style: none;\n color: #f9faf8;\n }\n\n .cta-container {\n padding: 100px 0;\n }\n\n .cta-wrapper {\n display: flex;\n justify-content: space-around;\n align-items: center;\n }\n\n .cta-signup-wrapper {\n display: flex;\n flex-direction: column;\n justify-content: start;\n }\n\n .cta-signup-wrapper > * {\n margin-top: -1em;\n }\n\n \n\n.cta-signup {\n background: #3882f6;\n border-radius: 8px;\n border-style: none;\n color: #f9faf8;\n width: 120px;\n height: 33px;\n font-size: 16px;\n font-weight: bold;\n border: 2px solid #f9faf8;\n margin-top: -1em;\n} <!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>Document</title>\n </head>\n <body>\n <div class=\"cta-container\">\n <div class=\"cta\">\n <div class=\"cta-wrapper\">\n <div class=\"cta-signup-wrapper\">\n <h3>Call to action! It's time!</h3>\n <p>\n Sign up for our product by clicking that button right over there!\n </p>\n </div>\n <button type=\"button\" class=\"cta-signup\">Sign up</button>\n </div>\n </div>\n </div>\n </body>\n</html>" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495684", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19111213/" ]
74,495,694
<p>The question has been tormenting for several days, unfortunately I could not find a solution. The magic poke method, too, did not bring results.</p> <p>You need to create your own LineRenderer, because Unity does not correctly display the grid of lines during sharp turns, and adding auxiliary points does not always bring good results. In general, I began to comprehend the knowledge about MESH!</p> <p>I created a test scene and made 3 squares: <a href="https://i.stack.imgur.com/tgLan.png" rel="nofollow noreferrer">enter image description here</a></p> <p>Denoted the UV coordinates. The topmost square was specially made slightly to the left to check how the line will rotate in the direction of the vertices. I added the rotation formula iiiii in the code - unfortunately it didn 't work the way I intended .</p> <p>The picture itself turned a little, but for some reason the vertices themselves shifted to UV.</p> <p>Perhaps I am completely wrong in implementing my plans. <a href="https://i.stack.imgur.com/AKE7B.png" rel="nofollow noreferrer">enter image description here</a></p> <p>The material itself is created through Shader Graphics.</p> <p>Perhaps there is a very simple option, but I can not understand it in any way.</p> <p>I ask for your help! And I apologize for the English!</p> <p><a href="https://i.stack.imgur.com/FYAz8.png" rel="nofollow noreferrer">enter image description here</a></p>
[ { "answer_id": 74495781, "author": "human bean", "author_id": 17186475, "author_profile": "https://Stackoverflow.com/users/17186475", "pm_score": -1, "selected": false, "text": "h3 p h3 h3 margin-bottom p margin-top .cta {\n background: #3882f6;\n padding: 50px 100px;\n border-radius: 10px;\n border-style: none;\n color: #f9faf8;\n}\n\n.cta-container {\n padding: 100px 0;\n}\n\n.cta-signup-wrapper {\n display: flex;\n justify-content: space-between;\n align-items: flex-end;\n}\n\n.cta-signup {\n background: #3882f6;\n border-radius: 8px;\n border-style: none;\n color: #f9faf8;\n width: 120px;\n height: 33px;\n font-size: 16px;\n font-weight: bold;\n border: 2px solid #f9faf8;\n}\n\nh3 {\n margin-bottom: 0;\n}\n\np {\n margin-top: 0;\n} <div class=\"cta-container\">\n <div class=\"cta\">\n <div class=\"cta-wrapper\">\n <h3>Call to action! It's time!</h3>\n <div class=\"cta-signup-wrapper\">\n <p>Sign up for our product by clicking that button right over there!</p>\n <button type=\"button\" class=\"cta-signup\">Sign up</button>\n </div>\n </div>\n </div>\n</div>" }, { "answer_id": 74495808, "author": "jerry", "author_id": 20493210, "author_profile": "https://Stackoverflow.com/users/20493210", "pm_score": 1, "selected": true, "text": ".cta {\n background: #3882f6;\n padding: 50px 100px;\n border-radius: 10px;\n border-style: none;\n color: #f9faf8;\n }\n\n .cta-container {\n padding: 100px 0;\n }\n\n .cta-wrapper {\n display: flex;\n justify-content: space-around;\n align-items: center;\n }\n\n .cta-signup-wrapper {\n display: flex;\n flex-direction: column;\n justify-content: start;\n }\n\n .cta-signup-wrapper > * {\n margin-top: -1em;\n }\n\n \n\n.cta-signup {\n background: #3882f6;\n border-radius: 8px;\n border-style: none;\n color: #f9faf8;\n width: 120px;\n height: 33px;\n font-size: 16px;\n font-weight: bold;\n border: 2px solid #f9faf8;\n margin-top: -1em;\n} <!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>Document</title>\n </head>\n <body>\n <div class=\"cta-container\">\n <div class=\"cta\">\n <div class=\"cta-wrapper\">\n <div class=\"cta-signup-wrapper\">\n <h3>Call to action! It's time!</h3>\n <p>\n Sign up for our product by clicking that button right over there!\n </p>\n </div>\n <button type=\"button\" class=\"cta-signup\">Sign up</button>\n </div>\n </div>\n </div>\n </body>\n</html>" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495694", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17420982/" ]
74,495,698
<p>I have a chrome extension with a button. Whenever the button is clicked, I want it to console.log(&quot;here&quot;) on the webpage. Currently it will only log on the extension popup page. Why is it doing this and how may I make it so that whenever the user presses a button it will console.log on the webpage not just the popup.</p> <pre><code>console.log(&quot;test&quot;)// this will log in both the extension popup and webpage window.onload=function(){ button.addEventListener('click',function(){ jump() }); } function jump(){ console.log(&quot;here&quot;)// this will only log in the extension popup } </code></pre>
[ { "answer_id": 74496036, "author": "Jridyard", "author_id": 15951953, "author_profile": "https://Stackoverflow.com/users/15951953", "pm_score": 1, "selected": false, "text": "---manifest.json---\n{\n \"name\": \"Popup to Content\",\n \"version\": \"1.0.0\",\n \"manifest_version\": 3,\n \"content_scripts\": [{\n \"matches\": [\"https://*/*\"],\n \"js\": [\"content_script.js\"]\n }],\n \"permissions\": [],\n \"action\": {\n \"default_popup\": \"popup.html\"\n }\n}\n ---popup.html---\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Document</title>\n</head>\n<body>\n <button id=\"example\"></button>\n <script src=\"popup.js\"></script>\n</body>\n</html>\n ---popup.js---\nconst exampleButton = document.querySelector(\"#example\")\nexampleButton.addEventListener(\"click\", function(){\n chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {\n const activeTabId = tabs[0].id;\n chrome.tabs.sendMessage(activeTabId, {\"message\": \"This worked!\"});\n });\n});\n ---content_script.js---\nchrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {\n // receive message here...\n console.log(request.message)\n});\n" }, { "answer_id": 74496183, "author": "Norio Yamamoto", "author_id": 20074043, "author_profile": "https://Stackoverflow.com/users/20074043", "pm_score": 3, "selected": true, "text": "{\n \"name\": \"executeScript\",\n \"version\": \"1.0\",\n \"manifest_version\": 3,\n \"permissions\": [\n \"scripting\"\n ],\n \"host_permissions\": [\n \"<all_urls>\"\n ],\n \"action\": {\n \"default_popup\": \"popup.html\"\n }\n}\n const func = () => {\n console.log(\"executeScript\");\n}\n\ndocument.getElementById(\"button\").onclick = () => {\n console.log(\"popup\");\n chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {\n chrome.scripting.executeScript({\n target: { tabId: tabs[0].id },\n func: func\n });\n });\n}\n <html>\n\n<body>\n <input type=\"button\" id=\"button\" value=\"button\">\n <script src=\"popup.js\"></script>\n</body>\n\n</html>\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19163242/" ]
74,495,728
<p>My dataframe looks like this:</p> <pre><code>df BEN_ID Val_1 Val_2 Val_3 Val_4 Val_5 AGE GENDER 1 ID1 vA303 . . . . 25 F 2 ID1 9351 A303 53019 49390 F5D12 52 F 3 ID2 541AZ 1120 462 4019 A36B0 58 M 4 ID2 30302 5939 2768 4019 2724 65 M 5 ID2 305A1 78652 9190 4019 33829 61 M 6 ID3 305A3 29590 5715 . . 53 M 7 ID3 Z57B9 35981 5849 570 4254 35 M 8 ID3 5693 78900 30590 30500 Z25H2 19 M 9 ID3 7AD59 7881 30301 78900 78791 57 M 10 ID4 7AD59 5780 53530 30390 3051 57 F </code></pre> <p>I wanted to get rows that match with any of Val_1 to Val_5 starting as patterns of &quot;303&quot; or &quot;305&quot;.</p> <p>So my output should look like this:</p> <pre><code> BEN_ID Val_1 Val_2 Val_3 Val_4 Val_5 AGE GENDER 4 ID2 30302 5939 2768 4019 2724 65 M 5 ID2 305A1 78652 9190 4019 33829 61 M 6 ID3 305A3 29590 5715 . . 53 M 8 ID3 5693 78900 30590 30500 Z25H2 19 M 9 ID3 7AD59 7881 30301 78900 78791 57 M 10 ID4 7AD59 5780 53530 30390 3051 57 F </code></pre> <p>I tried this code</p> <pre><code>library(dplyr) diag_cols = names(df %&gt;% select(starts_with(&quot;Val&quot;))) dat_read = dat_read %&gt;% mutate(across(matches(&quot;Val&quot;),as.character)) values = &quot;303|3050&quot; subdf = df %&gt;% filter(grepl(values,do.call(paste,c(df[,diag_cols],sep = &quot;,&quot;)))) </code></pre> <p>With this code Row1 is true as it has &quot;va303&quot; in Val_1.</p> <p>I tried doing with taking <code>values = &quot;^303|^305&quot;</code> but that gives wrong output</p> <p>TIA!</p>
[ { "answer_id": 74495784, "author": "Jilber Urbina", "author_id": 1315767, "author_profile": "https://Stackoverflow.com/users/1315767", "pm_score": 0, "selected": false, "text": "df[apply(df[, -c(1,7,8)], 1, function(x) any(grepl(\"^303|^305\", x))), ]\n BEN_ID Val_1 Val_2 Val_3 Val_4 Val_5 AGE GENDER\n4 ID2 30302 5939 2768 4019 2724 65 M\n5 ID2 305A1 78652 9190 4019 33829 61 M\n6 ID3 305A3 29590 5715 . . 53 M\n8 ID3 5693 78900 30590 30500 Z25H2 19 M\n9 ID3 7AD59 7881 30301 78900 78791 57 M\n10 ID4 7AD59 5780 53530 30390 3051 57 F\n" }, { "answer_id": 74495818, "author": "Andre Wildberg", "author_id": 9462095, "author_profile": "https://Stackoverflow.com/users/9462095", "pm_score": 2, "selected": true, "text": "dplyr library(dplyr)\n\ndf %>% \n filter(if_any(starts_with(\"Val\"), ~ grepl(\"^303|^305\", .x)))\n BEN_ID Val_1 Val_2 Val_3 Val_4 Val_5 AGE GENDER\n4 ID2 30302 5939 2768 4019 2724 65 M\n5 ID2 305A1 78652 9190 4019 33829 61 M\n6 ID3 305A3 29590 5715 . . 53 M\n8 ID3 5693 78900 30590 30500 Z25H2 19 M\n9 ID3 7AD59 7881 30301 78900 78791 57 M\n10 ID4 7AD59 5780 53530 30390 3051 57 F\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10030188/" ]
74,495,735
<p>I wanted to use docker for a personal project I set up it's written in go few services. So at the beging my &quot;architecture&quot; was spliting each service in diferent folder each service has it's own main which starts the srvice initialize what it needs opens a specific port for it. So far so good. So I wanted to use docker so when i started reading about it I wanted to introduce dockerfile for each service, but since I used combined go.mod file the docker image could not build.</p> <p>So my question is how is the right architecture for these kind of stuff, should I introduce new go.mod file for each service, or somehow use combined go.mod which is for the entire project, but somehow split all services to be deployed seperately having their own ports and stuff. I am NEW to docker so I am looking for suggestion how this kind of stuff should be build?</p> <p>I was looking into video of some guy explaining that every service should have it's own go.mod, but I was looking into some open source projects and it looked to me that they use only one go.mod file and somehow still deploy services as different services.</p>
[ { "answer_id": 74495784, "author": "Jilber Urbina", "author_id": 1315767, "author_profile": "https://Stackoverflow.com/users/1315767", "pm_score": 0, "selected": false, "text": "df[apply(df[, -c(1,7,8)], 1, function(x) any(grepl(\"^303|^305\", x))), ]\n BEN_ID Val_1 Val_2 Val_3 Val_4 Val_5 AGE GENDER\n4 ID2 30302 5939 2768 4019 2724 65 M\n5 ID2 305A1 78652 9190 4019 33829 61 M\n6 ID3 305A3 29590 5715 . . 53 M\n8 ID3 5693 78900 30590 30500 Z25H2 19 M\n9 ID3 7AD59 7881 30301 78900 78791 57 M\n10 ID4 7AD59 5780 53530 30390 3051 57 F\n" }, { "answer_id": 74495818, "author": "Andre Wildberg", "author_id": 9462095, "author_profile": "https://Stackoverflow.com/users/9462095", "pm_score": 2, "selected": true, "text": "dplyr library(dplyr)\n\ndf %>% \n filter(if_any(starts_with(\"Val\"), ~ grepl(\"^303|^305\", .x)))\n BEN_ID Val_1 Val_2 Val_3 Val_4 Val_5 AGE GENDER\n4 ID2 30302 5939 2768 4019 2724 65 M\n5 ID2 305A1 78652 9190 4019 33829 61 M\n6 ID3 305A3 29590 5715 . . 53 M\n8 ID3 5693 78900 30590 30500 Z25H2 19 M\n9 ID3 7AD59 7881 30301 78900 78791 57 M\n10 ID4 7AD59 5780 53530 30390 3051 57 F\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12686413/" ]
74,495,743
<p>I am new to TS and struggling to type the following arrow function:</p> <pre><code>const mapLikeGet = (obj, key) =&gt; { if (Object.prototype.hasOwnProperty.call(obj, key)) return obj[key] } </code></pre>
[ { "answer_id": 74495837, "author": "Slava Knyazev", "author_id": 4088472, "author_profile": "https://Stackoverflow.com/users/4088472", "pm_score": 0, "selected": false, "text": "keyof const mapLikeGet = <T,>(obj: T, key: keyof T) => {\n if (Object.prototype.hasOwnProperty.call(obj, key))\n return obj[key]\n return undefined;\n}\n\nconst foo = mapLikeGet({ foo: \"bar\"}, \"foo\");\n // ^? const foo: string | undefined \n" }, { "answer_id": 74495859, "author": "jtwalters", "author_id": 3508556, "author_profile": "https://Stackoverflow.com/users/3508556", "pm_score": 2, "selected": true, "text": "O[key] undefined const mapLikeGet = <O extends Object, K extends keyof O>(obj: O, key: K): O[K] | undefined => {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n return obj[key];\n }\n return undefined;\n}\n\n// foo\nconst foo = {\n one: 1,\n two: \"\",\n};\n\n\nconst oneVal = mapLikeGet(foo, \"one\");\n// oneVal => number | undefined\n Typescript 4.9 in const mapLikeGet = <O extends Object, K extends keyof O>(obj: O, key: ): O[K] | undefined => {\n if (key in obj) {\n return obj[key];\n }\n return undefined;\n}\n\n" }, { "answer_id": 74495893, "author": "Orwa Diraneyya", "author_id": 20186406, "author_profile": "https://Stackoverflow.com/users/20186406", "pm_score": 0, "selected": false, "text": "const mapLikeGet = (obj : any, key : string) => {\n if (Object.prototype.hasOwnProperty.call(obj, key))\n return obj[key]\n}\n Object.prototype.hasOwnProperty.call obj Object any key" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495743", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1495064/" ]
74,495,779
<p>Here's _app.tsx from a bare bones react auth example</p> <pre><code>import { SessionProvider } from &quot;next-auth/react&quot;, import * as React from &quot;react&quot; export default function App({ React.Component, pageProps: { session, ...pageProps }, }) { return ( &lt;SessionProvider session={session}&gt; &lt;Component {...pageProps} /&gt; &lt;/SessionProvider&gt; ) </code></pre> <p>}</p> <p>It wont compile because it says Component is an 'any' type I thought the solution was to import Component from React but it doesnt seem to have worked.</p>
[ { "answer_id": 74495837, "author": "Slava Knyazev", "author_id": 4088472, "author_profile": "https://Stackoverflow.com/users/4088472", "pm_score": 0, "selected": false, "text": "keyof const mapLikeGet = <T,>(obj: T, key: keyof T) => {\n if (Object.prototype.hasOwnProperty.call(obj, key))\n return obj[key]\n return undefined;\n}\n\nconst foo = mapLikeGet({ foo: \"bar\"}, \"foo\");\n // ^? const foo: string | undefined \n" }, { "answer_id": 74495859, "author": "jtwalters", "author_id": 3508556, "author_profile": "https://Stackoverflow.com/users/3508556", "pm_score": 2, "selected": true, "text": "O[key] undefined const mapLikeGet = <O extends Object, K extends keyof O>(obj: O, key: K): O[K] | undefined => {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n return obj[key];\n }\n return undefined;\n}\n\n// foo\nconst foo = {\n one: 1,\n two: \"\",\n};\n\n\nconst oneVal = mapLikeGet(foo, \"one\");\n// oneVal => number | undefined\n Typescript 4.9 in const mapLikeGet = <O extends Object, K extends keyof O>(obj: O, key: ): O[K] | undefined => {\n if (key in obj) {\n return obj[key];\n }\n return undefined;\n}\n\n" }, { "answer_id": 74495893, "author": "Orwa Diraneyya", "author_id": 20186406, "author_profile": "https://Stackoverflow.com/users/20186406", "pm_score": 0, "selected": false, "text": "const mapLikeGet = (obj : any, key : string) => {\n if (Object.prototype.hasOwnProperty.call(obj, key))\n return obj[key]\n}\n Object.prototype.hasOwnProperty.call obj Object any key" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11170223/" ]
74,495,782
<p>I want to collect all the numbers in the range [a, b] whose factorial starts with an even number.</p> <p><strong>For example:</strong></p> <pre><code>a = 1, b = 10 </code></pre> <p><strong>Answer:</strong></p> <pre><code>2 3 4 8 </code></pre> <p><strong>Explanation:</strong></p> <pre><code>2! = 2 = starts with even 3! = 6 = starts with even 4! = 24 = starts with even 8! = 40320 = starts with even </code></pre> <p><strong>Constraints:</strong></p> <p>1 &lt;= a,b &lt;= 100</p> <p>Here is my code:</p> <pre><code>List&lt;Integer&gt; process(int a, int b) { long base = i; for(int i=1; i&lt;=a; i++) base *= i; if(even(base)) list.add(a); for(int i=a+1; i&lt;=b; i++) { base *= i; if(even(base)) list.add(i); } return list; } boolean even(long k) { int z = (&quot;&quot; + k).charAt(0) - '0'; return z % 2 == 0; } </code></pre> <p>This was asked some days back in a coding challenge, when I implemented this, 6 hidden test cases were failing out of 15 test cases. I am not able to find what is the bug in this code.</p>
[ { "answer_id": 74495921, "author": "Melron", "author_id": 8920328, "author_profile": "https://Stackoverflow.com/users/8920328", "pm_score": -1, "selected": false, "text": "private static List<Integer> process(int a, int b)\n{\n List<Integer> list = new ArrayList<>();\n for (int i = a; i <= b; i++)\n {\n final int factorial = calcFactorial(i);\n if (factorialStartsWithEven(factorial))\n list.add(i);\n }\n return list;\n}\n\nprivate static boolean factorialStartsWithEven(int factorial)\n{\n final String strVal = String.valueOf(factorial);\n final int intVal = Integer.valueOf(strVal.charAt(0));\n return intVal % 2 == 0;\n}\n\nprivate static int calcFactorial(int n)\n{\n if (n == 0)\n return 1;\n return (n * calcFactorial(n - 1));\n}\n" }, { "answer_id": 74496168, "author": "WJS", "author_id": 1552534, "author_profile": "https://Stackoverflow.com/users/1552534", "pm_score": 2, "selected": false, "text": "BigInteger import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class FactorialStartsWithEven {\n\n public static void main(String[] args) {\n \n List<Integer> list = getForRange(1, 20);\n System.out.println(list);\n }\n [2, 3, 4, 8, 12, 13, 14, 16, 18, 20] \n public static List<Integer> getForRange(int start, int end) {\n List<Integer> results = new ArrayList<>();\n for (int i = start; i <= end; i++) {\n if(factorialStartsWithEven(i)) {\n results.add(i);\n }\n }\n return results;\n}\n record Fact(BigInteger fact, int n, boolean parity) {}\n static List<Fact> computed = new ArrayList<>(List.of(\n new Fact(BigInteger.ONE, 0, false),\n new Fact(BigInteger.ONE, 1, false),\n new Fact(BigInteger.TWO, 2, true)));\n n public static boolean factorialStartsWithEven(int n) {\n if (n < computed.size()) {\n return computed.get(n).parity;\n }\n Fact f = computed.get(computed.size()-1);\n BigInteger b = f.fact;\n Fact result = null;\n for (int k = f.n+1; k <= n; k++) {\n b = b.multiply(BigInteger.valueOf(k));\n result = new Fact(b, k, Character.digit(b.toString().charAt(0),10) % 2 == 0);\n computed.add(result);\n }\n return result.parity;\n }\n\n\n" }, { "answer_id": 74496678, "author": "Dave", "author_id": 2041077, "author_profile": "https://Stackoverflow.com/users/2041077", "pm_score": 0, "selected": false, "text": "def get_list(a, b)\n arr = [2, 3, 4, 8, 12, 13, 14, 16, 18, 20, 23, 24, 26, 29, 30, 31, 32, 33, 34, 39, 40, 43, 44, 47, 49, 52, 53, 54, 57, 58, 60, 65, 68, 71, 72, 73, 75, 79, 82, 85, 86, 87]\n \n list = []\n \n arr.each do |val|\n list.append(val) if a <= val && val <= b\n end\n \n return list\nend\n\n> get_list(10, 20)\n=> [12, 13, 14, 16, 18, 20]\n" }, { "answer_id": 74496760, "author": "Edward Peters", "author_id": 6016064, "author_profile": "https://Stackoverflow.com/users/6016064", "pm_score": 1, "selected": false, "text": "import java.math.BigInteger;\npublic class Main { \n public static void main(String args[]) {\n long acc = 1;\n int limit = (int)Math.log10(Long.MAX_VALUE);\n for (int i = 1; i <= 100; i++){\n int accLength = (int)Math.log10(acc) + 1;\n int iLength = (int)Math.log10(i) + 1;\n //System.out.printf(\"Acc :%s, accLength : %s, i : %s, iLength : %s \\n\", acc, accLength, i, iLength);\n if (accLength + iLength >= limit){\n //System.out.printf(\"Adjusting %s by %s\", acc, iLength);\n acc = acc / (long)(Math.pow(10, iLength));\n //System.out.println(\" becomes: \" + acc);\n }\n acc = acc * i;\n System.out.printf(\"acc is %s\\n\", acc);\n }\n }\n}\n long i" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495782", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3181365/" ]
74,495,807
<p>I want to find the next minimum value in a one-dimensional array so that I don't want to sort the array first.</p> <p>For example if I have this array:</p> <pre><code>int [] a={10,5,20,3}; </code></pre> <p>The first minimum value is 3, the second is 5, the third is 10 and the last is 20.</p> <p>Now I want to know the index number of minimum values respectively. What is the index number of the first minimum value and index number of the second minimum value, and the index number of the third value ...</p> <p>How can do it I in c#?</p> <p>I think that by using two loops and traversing the presentation, it is possible to determine the next minimum value.</p>
[ { "answer_id": 74495871, "author": "jmvcollaborator", "author_id": 13579714, "author_profile": "https://Stackoverflow.com/users/13579714", "pm_score": -1, "selected": false, "text": "/* prints element and NSE pair for all\nelements of arr[] of size n */\npublic static void printNSE(int[] arr, int n)\n{\n Stack <int> s = new Stack <int>();\n Dictionary <int,int> mp= new Dictionary <int,int>();\n\n /* push the first element to stack */\n s.Push(arr[0]);\n\n // iterate for rest of the elements\n for (int i = 1; i < n; i++) {\n if (s.Count == 0) {\n s.Push(arr[i]);\n continue;\n }\n\n /* if stack is not empty, then\n pop an element from stack.\n If the popped element is greater\n than next, then\n a) print the pair\n b) keep popping while elements are\n greater and stack is not empty */\n while (s.Count != 0 && s.Peek() > arr[i]) {\n mp.Add(s.Peek(), arr[i]);\n s.Pop();\n }\n\n /* push next to stack so that we can find\n next smaller for it */\n s.Push(arr[i]);\n }\n\n /* After iterating over the loop, the remaining\n elements in stack do not have the next smaller\n element, so print -1 for them */\n while (s.Count != 0) {\n mp.Add(s.Peek(), -1);\n s.Pop();\n }\n for (int i = 0; i < n; i++)\n Console.WriteLine(arr[i] + \" ---> \"+ mp[arr[i]]);\n}\n\n// Driver code\npublic static void Main()\n{\n int[] arr = { 11, 13, 21, 3};\n int n = arr.Length;\n printNSE(arr, n);\n}\n" }, { "answer_id": 74495967, "author": "jamal1aarab", "author_id": 20301502, "author_profile": "https://Stackoverflow.com/users/20301502", "pm_score": 0, "selected": false, "text": "int next_min (int* array ,int sizeofarray)\n{\n int i , fmin , smin;\n fmin = array[0];\n for (i=0 , i<sizeofarray , i++)\n {\n if (array[i]<fmin)\n {\n fmin = array[i];\n }\n }\n\n smin = array[0];\n for (i=0 , i<sizeofarray , i++)\n {\n if (array[i]<smin && smin !=fmin)\n {\n min = array[i];\n }\n }\n return smin ;\n}\n" }, { "answer_id": 74496070, "author": "FolabiAhn", "author_id": 4374590, "author_profile": "https://Stackoverflow.com/users/4374590", "pm_score": 0, "selected": false, "text": "class Program\n{\n static void Main(string[] args)\n {\n int[] a = { 10, 5, 20, 3 };\n int[] aCopy = new int[a.Length];\n Array.Copy(a, aCopy, a.Length);\n Array.Sort(aCopy);\n var result = string.Empty;\n foreach(int value in aCopy)\n {\n result += $\"({value}, {Array.IndexOf(a, value)})\\n\";\n }\n Console.WriteLine(result);\n }\n}\n" }, { "answer_id": 74496184, "author": "NineBerry", "author_id": 101087, "author_profile": "https://Stackoverflow.com/users/101087", "pm_score": 0, "selected": false, "text": "internal class Program\n{\n /// <summary>\n /// Finds the minimum value in values that is bigger than knownMaximum\n /// </summary>\n /// <returns>´Found minimum value and zero-based position</returns>\n static (int? minValue, int? position) GetNextMinimum(int[] values, int? knownMaximum)\n {\n int? minValue = null; \n int? position = null;\n\n for(int i=0; i< values.Length; i++)\n {\n int value = values[i];\n \n // If the current value is bigger than knownMaximum or no know Maximum specified\n if(!knownMaximum.HasValue || value > knownMaximum.Value )\n {\n // If current value is smaller than minimum value so far\n if(!minValue.HasValue || value < minValue.Value)\n {\n // Remember current value and position as minimum\n minValue= value;\n position= i;\n }\n }\n }\n\n return (minValue, position);\n }\n\n static void Main(string[] args)\n {\n int[] values = { 10, 5, 20, 3 };\n int? knownMaximum = null;\n\n // Get 1st, 2nd and 3rd Minimum\n for (int i=1; i<=3; i++)\n {\n var (minValue, position) = GetNextMinimum(values, knownMaximum);\n Console.WriteLine($\"{i}\\t Position {position}\\t Value {minValue}\");\n \n // Use the current minValue as known Maximum for nect round\n knownMaximum = minValue;\n }\n }\n}\n" }, { "answer_id": 74497824, "author": "Klaus Gütter", "author_id": 2142950, "author_profile": "https://Stackoverflow.com/users/2142950", "pm_score": 0, "selected": false, "text": "int[] a={10,5,20,3};\nint[] indexes = Enumerable.Range(0, a.Length).ToArray(); // = { 0,1,2,3 }\nArray.Sort(a, indexes);\nforeach (var i in indexes)\n Console.WriteLine(i);\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18716659/" ]
74,495,820
<p>I needed to scrape the telefone numbers and the email addreses from the following using python:</p> <pre><code>url = 'https://rma.cultura.gob.ar/#/app/museos/resultados?provincias=Buenos%20Aires' source = requests.get(url).text soup = BeautifulSoup(source, 'lxml') print(soup) </code></pre> <p>The problem is that what I get from the requests.get is not the html that I need. I suppose the site uses javascript to show those results but I'm not familiar with that since I'm just starting with python programming. I solved this by copying the code of each result page to an unique text file and then extracting the emails with regex but I'm curious if there is something simple to be done to access the data directly.</p>
[ { "answer_id": 74495905, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 1, "selected": false, "text": "requests json import json\nimport requests\n\napi_url = \"https://rmabackend.cultura.gob.ar/api/museos\"\n\nparams = {\n \"estado\": \"Publicado\",\n \"grupo\": \"Museo\",\n \"o\": \"p\",\n \"ordenar\": \"nombre_oficial_institucion\",\n \"page\": 1,\n \"page_size\": \"12\",\n \"provincias\": \"Buenos Aires\",\n}\n\nwhile True:\n data = requests.get(api_url, params=params).json()\n\n # uncomment this to print all data:\n # print(json.dumps(data, indent=4))\n\n for d in data[\"data\"]:\n print(d[\"attributes\"][\"nombre-oficial-institucion\"])\n\n if params[\"page\"] == data[\"meta\"][\"pagination\"][\"pages\"]:\n break\n\n params[\"page\"] += 1\n 2 Museos, Bellas Artes y MAC\nArchivo Histórico y Museo \"Astillero Río Santiago\" (ARS)\nArchivo Histórico y Museo del Servicio Penitenciario Bonaerense\nArchivo y Museo Historico Municipal Roberto T. Barili \"Villa Mitre\"\nAsociación Casa Bruzzone\nBiblioteca Popular y Museo \"José Manuel Estrada\"\nCasa Museo \"Haroldo Conti\"\nCasa Museo \"Xul Solar\" - Tigre\nComplejo Histórico y Museográfico \"Dr. Alfredo Antonio Sabaté\"\n\n\n...and so on.\n" }, { "answer_id": 74496021, "author": "DMcC", "author_id": 9809542, "author_profile": "https://Stackoverflow.com/users/9809542", "pm_score": 0, "selected": false, "text": "from selenium import webdriver\nfrom bs4 import BeautifulSoup\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\n\ndriver = webdriver.Chrome()\nurl = 'https://rma.cultura.gob.ar/#/app/museos/resultados?provincias=Buenos%20Aires'\n\n# navigate to the page\ndriver.get(url)\n# wait until a link with text 'ficha' has loaded\nWebDriverWait(driver, 10).until(EC.presence_of_element_located((By.PARTIAL_LINK_TEXT, 'ficha')))\nsource = driver.page_source\nsoup = BeautifulSoup(source, features='lxml')\ndriver.quit()\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19522207/" ]
74,495,850
<p>I am trying to take a single cell of data from specific files in a very large folder. I currently have this:</p> <pre class="lang-vb prettyprint-override"><code>Sub ExtractDataToDifferentSheets() On Error GoTo HandleError Application.ScreenUpdating = False Dim rowNumber As Integer rowNumber = Worksheets(&quot;sheet1&quot;).UsedRange.rows.Count For dRow = 2 To rowNumber Dim NG As String Dim Lot As String NG = Application.Workbooks(1).ActiveSheet.Cells(dRow, 1) Lot = Application.Workbooks(1).ActiveSheet.Cells(dRow, 2) Dim objectFlieSys As Object 'Dim objectGetFile As Object Dim file As Object Set objectFlieSys = CreateObject(&quot;Scripting.FileSystemObject&quot;) Set file = objectFlieSys.GetFile(StringFormat(&quot;C:\Users\mmccarthy\Box\QC-QA\SOPS Quality System\Quality logs\Ingredient Release Forms Records\2022 INGREDIENT RELEASE FORM\{0}_{1}.xlsx&quot;, NG, Lot)) ' The folder location of the source files. Application.Workbooks(1).ActiveSheet.Cells(dRow, 7) = _ file.Worksheets(&quot;Sheet1&quot;).Cells(7, 7) file.Close False Set file = Nothing Next HandleError: Application.EnableEvents = True Application.ScreenUpdating = True End Sub </code></pre> <p>I don't have much VBA experience, I was working from the following <a href="https://www.exceldemy.com/excel-macro-extract-data-from-multiple-excel-files/" rel="nofollow noreferrer">example</a>:</p> <pre class="lang-vb prettyprint-override"><code>Sub ExtractDataToDifferentSheets() On Error GoTo HandleError Application.ScreenUpdating = False Dim rowNumber As Integer rowNumber = Worksheets(&quot;sheet1&quot;).UsedRange.rows.Count For dRow = 2 To rowNumber Dim NG As String Dim Lot As String NG = Application.Workbooks(1).ActiveSheet.Cells(dRow, 1) Lot = Application.Workbooks(1).ActiveSheet.Cells(dRow, 2) Dim objectFlieSys As Object 'Dim objectGetFile As Object Dim file As Object Set objectFlieSys = CreateObject(&quot;Scripting.FileSystemObject&quot;) Set file = objectFlieSys.GetFile(StringFormat(&quot;C:...\2022 INGREDIENT RELEASE FORM\{0}_{1}.xlsx&quot;, NG, Lot)) ' The folder location of the source files. Application.Workbooks(1).ActiveSheet.Cells(dRow, 7) = _ file.Worksheets(&quot;Sheet1&quot;).Cells(7, 7) file.Close False Set file = Nothing Next HandleError: Application.EnableEvents = True Application.ScreenUpdating = True End Sub </code></pre> <p>I know it's not the best example to work from, but originally I intended on extracting data from all files in the folder but this took wayyyyyyyyy too long so I limited it to the ones I need. When I wrote the other script to extract the same info from every file in the folder, it ran but the system crashed and I had not saved so I lost all my code.</p> <p>What is especially confusing is it highlights the first line of code when it throws the error. I get the impression that it is telling me the sub I am trying to define is not defined. That would be silly. Is there just a typo somewhere else in my code that i can't find? I have no idea why the previous code ran when this code is throwing errors immediately. <a href="https://stackoverflow.com/questions/23722013/sub-or-function-not-defined-when-trying-to-run-a-vba-script-in-outlook">this</a> seems to be the most relevant question I could find on stack overflow, but I can't find 'create' that the answer references.</p> <p>Please help or I will spend all weekend manually copying data for this incredibly easy task. :(</p>
[ { "answer_id": 74495905, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 1, "selected": false, "text": "requests json import json\nimport requests\n\napi_url = \"https://rmabackend.cultura.gob.ar/api/museos\"\n\nparams = {\n \"estado\": \"Publicado\",\n \"grupo\": \"Museo\",\n \"o\": \"p\",\n \"ordenar\": \"nombre_oficial_institucion\",\n \"page\": 1,\n \"page_size\": \"12\",\n \"provincias\": \"Buenos Aires\",\n}\n\nwhile True:\n data = requests.get(api_url, params=params).json()\n\n # uncomment this to print all data:\n # print(json.dumps(data, indent=4))\n\n for d in data[\"data\"]:\n print(d[\"attributes\"][\"nombre-oficial-institucion\"])\n\n if params[\"page\"] == data[\"meta\"][\"pagination\"][\"pages\"]:\n break\n\n params[\"page\"] += 1\n 2 Museos, Bellas Artes y MAC\nArchivo Histórico y Museo \"Astillero Río Santiago\" (ARS)\nArchivo Histórico y Museo del Servicio Penitenciario Bonaerense\nArchivo y Museo Historico Municipal Roberto T. Barili \"Villa Mitre\"\nAsociación Casa Bruzzone\nBiblioteca Popular y Museo \"José Manuel Estrada\"\nCasa Museo \"Haroldo Conti\"\nCasa Museo \"Xul Solar\" - Tigre\nComplejo Histórico y Museográfico \"Dr. Alfredo Antonio Sabaté\"\n\n\n...and so on.\n" }, { "answer_id": 74496021, "author": "DMcC", "author_id": 9809542, "author_profile": "https://Stackoverflow.com/users/9809542", "pm_score": 0, "selected": false, "text": "from selenium import webdriver\nfrom bs4 import BeautifulSoup\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\n\ndriver = webdriver.Chrome()\nurl = 'https://rma.cultura.gob.ar/#/app/museos/resultados?provincias=Buenos%20Aires'\n\n# navigate to the page\ndriver.get(url)\n# wait until a link with text 'ficha' has loaded\nWebDriverWait(driver, 10).until(EC.presence_of_element_located((By.PARTIAL_LINK_TEXT, 'ficha')))\nsource = driver.page_source\nsoup = BeautifulSoup(source, features='lxml')\ndriver.quit()\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20543395/" ]
74,495,851
<p>Can anyone explain what's going on here? setting <code>row.name= NULL</code> makes no difference compared to when I dont specify it, yet when I set <code>row.names=1</code>, it says duplicate row.names not allowed? How do I resolve this to get column V1 as rownames?</p> <pre><code>ak1a = read.table(&quot;/Users/abhaykanodia/Desktop/smallRNA/AK1a_counts.txt&quot;, row.names = NULL) head(ak1a) V1 V2 1 ENSG00000000003.15 2 2 ENSG00000000005.6 0 3 ENSG00000000419.14 21 4 ENSG00000000457.14 0 5 ENSG00000000460.17 2 6 ENSG00000000938.13 0 ak1a = read.table(&quot;/Users/abhaykanodia/Desktop/smallRNA/AK1a_counts.txt&quot;) head(ak1a) V1 V2 1 ENSG00000000003.15 2 2 ENSG00000000005.6 0 3 ENSG00000000419.14 21 4 ENSG00000000457.14 0 5 ENSG00000000460.17 2 6 ENSG00000000938.13 0 ak1a = read.table(&quot;/Users/abhaykanodia/Desktop/smallRNA/AK1a_counts.txt&quot;, row.names = 1) Error in read.table(&quot;/Users/abhaykanodia/Desktop/smallRNA/AK1a_counts.txt&quot;, : duplicate 'row.names' are not allowed </code></pre>
[ { "answer_id": 74495877, "author": "Jilber Urbina", "author_id": 1315767, "author_profile": "https://Stackoverflow.com/users/1315767", "pm_score": 1, "selected": false, "text": "df <- read.table(text=\"V1 V2\nENSG00000000003.15 2\nENSG00000000005.6 0\nENSG00000000419.14 21\nENSG00000000457.14 0\nENSG00000000460.17 2\nENSG00000000938.13 0\", header=TRUE, row.names=letters[1:6])\n V1 V2\na ENSG00000000003.15 2\nb ENSG00000000005.6 0\nc ENSG00000000419.14 21\nd ENSG00000000457.14 0\ne ENSG00000000460.17 2\nf ENSG00000000938.13 0\n" }, { "answer_id": 74495903, "author": "Diego Queiroz", "author_id": 1968811, "author_profile": "https://Stackoverflow.com/users/1968811", "pm_score": 0, "selected": false, "text": "1 row.names=1 test <- read.table(text=\"X Y\n1 2\n3 4\", header=TRUE)\nrow.names(test) = c(1,1)\n R1:RX ak1a = read.table(\"/Users/abhaykanodia/Desktop/smallRNA/AK1a_counts.txt\")\nrow.names(ak1a) = paste(\"R\",1:dim(ak1a)[1],sep=\"\")\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17866927/" ]
74,495,864
<p>I have a huge list of sublists, each sublist consisting of a tuple and an int. Example:</p> <pre><code>[[(1, 1), 46], [(1, 2), 25.0], [(1, 1), 25.0], [(1, 3), 19.5], [(1, 2), 19.5], [(1, 4), 4.5], [(1, 3), 4.5], [(1, 5), 17.5], [(1, 4), 17.5], [(1, 6), 9.5], [(1, 5), 9.5]] </code></pre> <p>I want to create a unique list of those tuples corresponding to the sum of all those integer values using python. For the example above, my desired output looks like this:</p> <pre><code>[[(1, 1), 71], [(1, 2), 44.5], [(1, 3), 24], [(1, 4), 22], [(1, 5), 27], [(1, 6), 9.5]] </code></pre> <p>Could I get some help on how to do this?</p> <p>I have tried to use dictionaries to solve this problem, but I keep running into errors, as I am not too familiar with how to use them.</p>
[ { "answer_id": 74495877, "author": "Jilber Urbina", "author_id": 1315767, "author_profile": "https://Stackoverflow.com/users/1315767", "pm_score": 1, "selected": false, "text": "df <- read.table(text=\"V1 V2\nENSG00000000003.15 2\nENSG00000000005.6 0\nENSG00000000419.14 21\nENSG00000000457.14 0\nENSG00000000460.17 2\nENSG00000000938.13 0\", header=TRUE, row.names=letters[1:6])\n V1 V2\na ENSG00000000003.15 2\nb ENSG00000000005.6 0\nc ENSG00000000419.14 21\nd ENSG00000000457.14 0\ne ENSG00000000460.17 2\nf ENSG00000000938.13 0\n" }, { "answer_id": 74495903, "author": "Diego Queiroz", "author_id": 1968811, "author_profile": "https://Stackoverflow.com/users/1968811", "pm_score": 0, "selected": false, "text": "1 row.names=1 test <- read.table(text=\"X Y\n1 2\n3 4\", header=TRUE)\nrow.names(test) = c(1,1)\n R1:RX ak1a = read.table(\"/Users/abhaykanodia/Desktop/smallRNA/AK1a_counts.txt\")\nrow.names(ak1a) = paste(\"R\",1:dim(ak1a)[1],sep=\"\")\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20543467/" ]
74,495,897
<p>Just getting started with SwiftUI so there is probably something straightforward I am missing.</p> <p>When the &quot;CHECK&quot; button is pressed, I want to change the background color of the button with an index that matches question.correctChoiceIndex, as well as the button selected by the user, if it is not the correct one.</p> <p>I am not sure how to actually reference the buttons with a function (if that is the best way), and I figured it might be difficult because the buttons are made with the AnswerButton struct.</p> <p>Here is my code</p> <pre><code> import SwiftUI struct ContentView: View { let question: Question @State var guessedIndex: Int? = nil var body: some View { VStack{ Spacer() Text(question.questionText) .padding() VStack { ForEach(question.AnswerChoices.indices) {index in AnswerButton(text: question.AnswerChoices[index]){ guessedIndex = index } .border(selectChoice(at: index), width: 4) }} Spacer() Text(&quot;Answer feedback&quot;) .padding() Spacer() HStack{ Button(&quot;CHECK&quot;) { } .padding() Button(&quot;NEXT&quot;) { /*@START_MENU_TOKEN@*//*@PLACEHOLDER=Action@*/ /*@END_MENU_TOKEN@*/ } .padding() } } } func selectChoice(at buttonIndex: Int) -&gt; Color { if buttonIndex == guessedIndex { return .gray } else { return .clear } } } struct AnswerButton: View { let text: String let onClick: () -&gt; Void var body: some View { Button(action: { onClick() }) { Text(text) } .padding() .background(Color.yellow) } } struct ContentView_Previews: PreviewProvider { static var previews: some View { Group { ContentView(question: Question.AllQuestions[0]) } } } </code></pre> <p>I thought looping through all the buttons in the view and checking their index could work, but it also seems a bit inefficient to do.</p>
[ { "answer_id": 74496382, "author": "workingdog support Ukraine", "author_id": 11969817, "author_profile": "https://Stackoverflow.com/users/11969817", "pm_score": 0, "selected": false, "text": "// for testing\nstruct Question: Identifiable {\n let id = UUID()\n var questionText: String\n var answerChoices: [String]\n}\n \nstruct ContentView: View {\n // for testing\n let question: Question = Question(questionText: \"some question\", answerChoices: [\"answer-1\",\"answer-2\",\"answer-3\"])\n \n @State var guessedIndex: Int? = nil\n @State var isCorrect: Bool = false // <-- here\n \n var body: some View {\n VStack{\n Spacer()\n Text(question.questionText).padding()\n VStack {\n ForEach(question.answerChoices.indices, id: \\.self) { index in // <-- here\n AnswerButton(text: question.answerChoices[index]) {\n guessedIndex = index\n isCorrect = false // <-- here\n }\n .border(guessedIndex == index ? .green : .clear, width: 4) // <-- here\n .background(guessedIndex == index && isCorrect ? .gray : .yellow) // <-- here\n }\n }\n Spacer()\n Text(\"Answer feedback\").padding()\n Spacer()\n HStack{\n Button(\"CHECK\") {\n checkAnswer() // <-- here\n }.padding()\n Button(\"NEXT\") {\n \n }.padding()\n }\n }\n }\n \n func checkAnswer() {\n // some logic here to determine which answer is correct\n isCorrect = guessedIndex == 1 // for testing, answer-2\n }\n}\n\nstruct AnswerButton: View {\n let text: String\n let onClick: () -> Void\n \n var body: some View {\n Button(action: {\n onClick()\n }) {\n Text(text)\n }\n .padding()\n }\n}\n" }, { "answer_id": 74496389, "author": "Andrew Carter", "author_id": 20511615, "author_profile": "https://Stackoverflow.com/users/20511615", "pm_score": 2, "selected": true, "text": "import SwiftUI\n\nstruct Question {\n let questionText: String\n let answerChoices: [String]\n let correctAnswerIndex: Int\n}\n\nstruct ContentView: View {\n \n let question: Question\n @State var guessedIndex: Int? = nil\n @State var didCheck = false\n \n var body: some View {\n \n VStack {\n Spacer()\n Text(question.questionText)\n .padding()\n \n ForEach(0 ..< question.answerChoices.count) { index in\n let answer = question.answerChoices[index]\n AnswerButton(text: answer,\n isCorrectAnswer: index == question.correctAnswerIndex,\n didCheck: didCheck,\n isSelected: index == guessedIndex) {\n guessedIndex = index\n }\n }\n Spacer()\n Text(\"Answer feedback\")\n .padding()\n Spacer()\n HStack{\n Button(\"CHECK\") {\n didCheck = true\n }\n .padding()\n Button(\"NEXT\") {\n \n }\n .padding()\n }\n }\n \n }\n \n}\n\n\nstruct AnswerButton: View {\n \n let text: String\n let isCorrectAnswer: Bool\n let didCheck: Bool\n let isSelected: Bool\n let onClick: () -> Void\n \n var body: some View {\n Button(text, action: onClick)\n .padding()\n .border(isSelected ? .gray : .clear)\n .background(backgroundColorForCurrentState())\n }\n \n func backgroundColorForCurrentState() -> Color {\n switch (didCheck, isCorrectAnswer, isSelected) {\n case (true, false, true):\n return .red\n \n case (true, true, _):\n return .green\n \n case (_, _, _):\n return .yellow\n }\n }\n \n \n}\n\n\nstruct ContentView_Previews: PreviewProvider {\n static var previews: some View {\n Group {\n ContentView(question: Question(questionText: \"examnple\",\n answerChoices: [\"one\", \"two\", \"three\"],\n correctAnswerIndex: 1))\n \n }\n }\n}\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9227462/" ]
74,495,928
<p>I have this df with only one value per column between <code>y1</code> and <code>y4</code></p> <pre><code> x y1 y2 y3 y4 0 -17.7 -0.785430 NaN NaN NaN 1 -15.0 NaN NaN NaN -3820.085000 2 -12.5 NaN NaN 2.138833 NaN </code></pre> <p>I want to combine all y columns in one column <code>y</code>.</p> <p>Edit: Also, I forgot I need another column to tell me which of the 4 y columns the value belongs to.</p> <p>The output I need is this:</p> <pre><code> x y no 0 -17.7 -0.785430 y1 1 -15.0 -3820.085000 y4 2 -12.5 2.138833 y3 </code></pre>
[ { "answer_id": 74495987, "author": "BENY", "author_id": 7964527, "author_profile": "https://Stackoverflow.com/users/7964527", "pm_score": 2, "selected": false, "text": "groupby first out = df.groupby(df.columns.str[0],axis=1).first()\nOut[60]: \n x y\n0 -17.7 -0.785430\n1 -15.0 -3820.085000\n2 -12.5 2.138833\n" }, { "answer_id": 74496640, "author": "PaulS", "author_id": 11564487, "author_profile": "https://Stackoverflow.com/users/11564487", "pm_score": 2, "selected": false, "text": "df.assign(y = df.iloc[:,1:].sum(axis=1)).dropna(axis=1)\n x y\n0 -17.7 -0.785430\n1 -15.0 -3820.085000\n2 -12.5 2.138833\n" }, { "answer_id": 74497609, "author": "sammywemmy", "author_id": 7175713, "author_profile": "https://Stackoverflow.com/users/7175713", "pm_score": 2, "selected": true, "text": "grouped = df.filter(like='y')\ncols = grouped.columns.str[0]\ngrouper = grouped.groupby(cols, axis = 1)\nout = [df.x, \n grouper.first(), \n grouper.idxmax(axis=1, numeric_only=True).rename(columns={'y':'no'})]\npd.concat(out, axis = 1)\n\n x y no\n0 -17.7 -0.785430 y1\n1 -15.0 -3820.085000 y4\n2 -12.5 2.138833 y3\n df.columns = [f\"y_{y}\" if y.startswith('y') else y for y in temp]\n(pd\n.wide_to_long(\n temp, \n stubnames = 'y', \n i = 'x', \n j='no', \n sep='_', \n suffix ='.+')\n.dropna()\n.reset_index()\n)\n\n x no y\n0 -17.7 y1 -0.785430\n1 -12.5 y3 2.138833\n2 -15.0 y4 -3820.085000\n # pip install pyjanitor\nimport pandas as pd\nimport janitor\n\n# use the original dataframe, \n# with no modifications on the columns\n(df\n.pivot_longer(\n index = 'x', \n names_to = 'no', \n values_to = 'y', \n names_pattern='(.+)', \n dropna=True)\n) \n x no y\n0 -17.7 y1 -0.785430\n1 -12.5 y3 2.138833\n2 -15.0 y4 -3820.085000\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20458338/" ]
74,495,932
<p>I need to add to the line:</p> <pre><code>url=&quot;items.point&amp;point1={item}%2C{item}&amp;point2C{item}%2C{item}&quot; </code></pre> <p>four values ​​of possible coordinates instead of &quot;item&quot; value. We have to generate these coordinate values ​​in a loop.</p> <p>I tried many different options for how to do this, but the program displays a lot of extra values.</p> <p>My code:</p> <pre><code>import numpy as np coordinates=[] for item in np.arange(45.024287,45.024295,0.000001): coordinates.append(&quot;%.6f&quot; %item) for item in np.arange(45.024287,45.024295,0.000001): coordinates.append(&quot;%.6f&quot; %item) urls=[] for item in (coordinates): urls.append(f&quot;items.point&amp;point1{item}%2C{item}&amp;point2={item}%2C{item}&quot;) print(urls) </code></pre> <p>I need to get this result:</p> <pre><code>&quot;items.point&amp;point1=45.024295%2C45.024295&amp;point2=39.073557%2C45.005125&quot;,&quot;items.point&amp;point1=45.024294%2C45.024294&amp;point2=39.073557%2C45.005125&quot;...Etc </code></pre> <p>With different coordinates</p> <p>But I am getting repeated values ​​due to the fact that the loop is in a loop. Can you tell me how you can substitute several variables in a string without doubling the values?Please</p>
[ { "answer_id": 74496007, "author": "Swifty", "author_id": 20267366, "author_profile": "https://Stackoverflow.com/users/20267366", "pm_score": 2, "selected": true, "text": "urls=[]\nfor item1, item2 in zip(*[iter(coordinates)]*2):\n urls.append(f\"items.point&point1{item1}%2C{item2}&point2=39.073557%2C45.005125\")\nprint(urls)\n" }, { "answer_id": 74496058, "author": "Barmar", "author_id": 1491895, "author_profile": "https://Stackoverflow.com/users/1491895", "pm_score": 0, "selected": false, "text": "coordinates urls for for item1 in np.arange(45.024287,45.024295,0.000001):\n for item2 in np.arange(45.024287,45.024295,0.000001):\n urls.append(f\"items.point&point1={item1}%2C{item2}&point2=39.073557%2C45.005125\")\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20543386/" ]
74,495,936
<p>So if we have a list of strings, for example</p> <pre><code>ArrayList&lt;String&gt; listA = new ArrayList(Arrays.asList(&quot;C&quot;, &quot;E&quot;, &quot;B&quot;, &quot;F&quot;, **&quot;E&quot;**, &quot;A&quot;, &quot;G&quot;, &quot;G&quot;, &quot;C&quot;, &quot;A&quot;, &quot;B&quot;, **&quot;G&quot;**)); </code></pre> <p>And there's another list:</p> <pre><code>ArrayList&lt;String&gt; listB = new ArrayList&lt;&gt;(Arrays.asList(&quot;E&quot;, &quot;D&quot;, &quot;C&quot;, &quot;D&quot;, **&quot;E&quot;**, &quot;E&quot;, &quot;E&quot;, &quot;D&quot;, &quot;D&quot;, &quot;D&quot;, &quot;E&quot;, **&quot;G&quot;**)); </code></pre> <p>As you can see, these two lists match on positions 4 and 11, E and G are two letters that match that is it's the same letter on the same position.</p> <p>What I want to do is replace values in listB that don't match values in listA, that is all other letters that are not E on 4 and G on 11 should be new random letters from this list</p> <pre><code>ArrayList&lt;String&gt; someListOfValues = new ArrayList(Arrays.asList(&quot;C&quot;, &quot;C#&quot;, &quot;D&quot;, &quot;Eb&quot;, &quot;E&quot;, &quot;F&quot;, &quot;F#&quot;, &quot;G&quot;, &quot;G#&quot;, &quot;A&quot;, &quot;Bb&quot;, &quot;B&quot;)); </code></pre> <p>but two that match should remain.</p> <p>I tried creating a new list that would remember positions where lists didn't match</p> <p>Like this</p> <pre><code> ArrayList&lt;Integer&gt; unmatchingPositions = new ArrayList&lt;&gt;(); ArrayList&lt;Integer&gt; matchingPositions = new ArrayList&lt;&gt;(); for (int j = 0; j &lt; listA.size(); j++) { if (ListA.get(j).equals(ListB.get(j))) { matchingPositions.add(j); } else unmatchingPositions.add(j); } </code></pre> <p>Then I want to find these values in listB and replace them with random values</p> <pre><code>for (int j = 0; j &lt; listA.size(); j++) { for (int k = 0; k &lt; unmatchingPositions.size(); k++) { if (k == unmatchingPositions.get(k)) { listB.set(k, someListOfValues.get(rand.nextInt(someListOfValues.size()))); } } } </code></pre> <p>But this doesn't work and I can't figure out what's the problem.</p>
[ { "answer_id": 74495997, "author": "John3136", "author_id": 857132, "author_profile": "https://Stackoverflow.com/users/857132", "pm_score": 2, "selected": true, "text": "if (k == unmatchingPositions.get(k)) { if int listASz = listA.size();\nfor(int i = 0; i < listASz; i++)\n{\n if (listA[i] != listB[i])\n {\n listB[i] = /*something*/\n" }, { "answer_id": 74496054, "author": "Alexander Ivanchenko", "author_id": 17949945, "author_profile": "https://Stackoverflow.com/users/17949945", "pm_score": 0, "selected": false, "text": "listB List.set() List<String> listA = // initializing the list\nList<String> listB = // initializing the list\n \nList<Integer> notMatchingPositions = new ArrayList<>();\n \nfor (int i = 0; i < listA.size() && i < listB.size(); i++) {\n if (!listA.get(i).equals(listB.get(i))) notMatchingPositions.add(i);\n}\n \nfor (int i : notMatchingPositions) {\n String newValue = someListOfValues.get(rand.nextInt(someListOfValues.size()));\n listB.set(i, newValue);\n}\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14677576/" ]
74,495,938
<p>I have this list:</p> <pre><code>[[1, 2, 3, 4], [5], [6, 7], [8], [9], [10, 11], [12, 13, 14], [15, 16], [15, 16], [15, 16], [17], [18], [19], [20], [21], [20], [21], [], [], [], [], []] </code></pre> <p>It could be described as a list of references to other items in the same list, like this:</p> <pre><code>0 --&gt; 1 2 3 4 1 --&gt; 5 2 --&gt; 6 7 3 --&gt; 8 4 --&gt; 9 5 --&gt; 10 11 6 --&gt; 12 13 14 7 --&gt; 15 16 8 --&gt; 15 16 9 --&gt; 15 16 10 --&gt; 17 11 --&gt; 18 12 --&gt; 19 13 --&gt; 20 14 --&gt; 21 15 --&gt; 20 16 --&gt; 21 17 --&gt; None 18 --&gt; None 19 --&gt; None 20 --&gt; None 21 --&gt; None </code></pre> <p>So, from index 0 one can move to either 1, 2, 3 or 4. From 1 you can go to 5, and from 5 you can go to 10 etc. until you can't go any further (like when you reach index 17).</p> <p>I'm trying to make a function that would return this when fed the above list:</p> <pre><code>[0,1,5,10,17] [0,1,5,11,18] [0,2,6,12,19] [0,2,6,13,20] [0,2,6,14,21] [0,2,7,15,20] [0,2,7,16,21] [0,3,8,15,20] [0,3,8,16,21] [0,4,9,15,20] [0,4,9,16,21] </code></pre> <p>Unfortunately, I just can't come up a solution.</p> <p>I understand that this probably calls for a recursive function, but I'm getting so confused by it. Without actually knowing what I did, I managed to come up with this function:</p> <pre><code>def recurse_into(A,i): B = [i] for j in tree[i]: B += recurse_into(A,j) return B </code></pre> <p>It returns this:</p> <pre><code>[0, 1, 5, 10, 17, 11, 18, 2, 6, 12, 19, 13, 20, 14, 21, 7, 15, 20, 16, 21, 3, 8, 15, 20, 16, 21, 4, 9, 15, 20, 16, 21] </code></pre> <p>From that I probably could come up with something that generates the wanted results, but I wonder how I could get the result I want directly from the recursive function.</p> <p>I would very much appreciate some pointers or tips on how to achieve this.</p> <p>Thanks!</p>
[ { "answer_id": 74495997, "author": "John3136", "author_id": 857132, "author_profile": "https://Stackoverflow.com/users/857132", "pm_score": 2, "selected": true, "text": "if (k == unmatchingPositions.get(k)) { if int listASz = listA.size();\nfor(int i = 0; i < listASz; i++)\n{\n if (listA[i] != listB[i])\n {\n listB[i] = /*something*/\n" }, { "answer_id": 74496054, "author": "Alexander Ivanchenko", "author_id": 17949945, "author_profile": "https://Stackoverflow.com/users/17949945", "pm_score": 0, "selected": false, "text": "listB List.set() List<String> listA = // initializing the list\nList<String> listB = // initializing the list\n \nList<Integer> notMatchingPositions = new ArrayList<>();\n \nfor (int i = 0; i < listA.size() && i < listB.size(); i++) {\n if (!listA.get(i).equals(listB.get(i))) notMatchingPositions.add(i);\n}\n \nfor (int i : notMatchingPositions) {\n String newValue = someListOfValues.get(rand.nextInt(someListOfValues.size()));\n listB.set(i, newValue);\n}\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2268171/" ]
74,495,948
<p>The code here in my App.js renders a Navbar &amp; a home page.</p> <pre><code>import React from &quot;react&quot;; import './styles/global.css'; import Navbar from &quot;./components/navbar/Navbar&quot;; import Home from &quot;./pages/Home&quot;; function App() { return ( &lt;div className=&quot;app&quot;&gt; &lt;Navbar /&gt; &lt;Home /&gt; &lt;/div&gt; ) } export default App; </code></pre> <p>Every time I click into a section of the navbar (search, about, contact) the component renders, but my Homepage component remains displaying at the bottom of one of what should be one of the three navigation components/pages. Here is my Navbar routing</p> <pre><code>import React from 'react'; import { BrowserRouter, Link, Routes, Route } from 'react-router-dom'; import About from '../../pages/About'; import SearchPage from '../../pages/SearchPage'; import Contact from '../../pages/Contact' import './navbar.css'; function Navbar() { return ( &lt;BrowserRouter&gt; &lt;div className='navbar'&gt; &lt;h2&gt;Nicole's Blog.&lt;/h2&gt; &lt;div className='navbar__list'&gt; &lt;ul&gt; &lt;li&gt; &lt;Link to=&quot;/&quot;&gt;Home&lt;/Link&gt; &lt;/li&gt; &lt;li&gt; &lt;Link to=&quot;/search&quot;&gt;Search&lt;/Link&gt; &lt;/li&gt; &lt;li&gt; &lt;Link to=&quot;/about&quot;&gt;About&lt;/Link&gt; &lt;/li&gt; &lt;li&gt; &lt;Link to=&quot;/contact&quot;&gt;Contact&lt;/Link&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;Routes&gt; &lt;Route exact path='/search' element={&lt;SearchPage /&gt;}&gt;&lt;/Route&gt; &lt;Route exact path='/about' element={&lt;About /&gt;}&gt;&lt;/Route&gt; &lt;Route exact path='/contact' element={&lt;Contact /&gt;}&gt;&lt;/Route&gt; &lt;/Routes&gt; &lt;/BrowserRouter&gt; ) } export default Navbar </code></pre>
[ { "answer_id": 74495997, "author": "John3136", "author_id": 857132, "author_profile": "https://Stackoverflow.com/users/857132", "pm_score": 2, "selected": true, "text": "if (k == unmatchingPositions.get(k)) { if int listASz = listA.size();\nfor(int i = 0; i < listASz; i++)\n{\n if (listA[i] != listB[i])\n {\n listB[i] = /*something*/\n" }, { "answer_id": 74496054, "author": "Alexander Ivanchenko", "author_id": 17949945, "author_profile": "https://Stackoverflow.com/users/17949945", "pm_score": 0, "selected": false, "text": "listB List.set() List<String> listA = // initializing the list\nList<String> listB = // initializing the list\n \nList<Integer> notMatchingPositions = new ArrayList<>();\n \nfor (int i = 0; i < listA.size() && i < listB.size(); i++) {\n if (!listA.get(i).equals(listB.get(i))) notMatchingPositions.add(i);\n}\n \nfor (int i : notMatchingPositions) {\n String newValue = someListOfValues.get(rand.nextInt(someListOfValues.size()));\n listB.set(i, newValue);\n}\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18137450/" ]
74,495,960
<p>I'm preparing data for a cox regression model and I have a dataset that shows all of the years that participants were registered as living in the province. There is a variable that identifies how many days they were registered as living in the province for each year. I want their start year to be their first year that they were fully registered (&gt;=365 days) as living in the province. I also want the last year that they were fully registered as living in the province. However, there are some participants that left the province, then returned later for at least one full-time year. For this analysis, I want to consider participants follow-up to end when they leave the first time as we can't track their health outcomes that may have occurred while outside the province.</p> <p>Imagine I have already sorted the dataset by ID, then year. I then removed any observations where there were less than 365 days registered.</p> <p>Here is a test dataset:</p> <pre><code>df &lt;- data.frame( ID = c(1,1,1,1,1,2,2,2,2,2,2,3,3,3,3), values = c(1996,1998,1999,2000,2001,2001,2002,2003,2004,2007,2008,2004,2005,2006,2007) ) df_inc &lt;- df %&gt;% group_by(ID) %&gt;% filter(row_number(values)==1) </code></pre> <p>This works as intended, returning the first fully registered year per participant</p> <pre><code>df_lastoverall &lt;- df %&gt;% group_by(ID) %&gt;% filter(row_number(values)==n()) </code></pre> <p>This works, but returns the last fully registered year, regardless of whether their years were all consecutive, or they left the province then returned to have at least one full year. This gives a last year of 2001 for ID1, 2008 for ID2, and 2007 for ID3.</p> <p>Here's where I'm at and can use some help... I'm looking for some way to identify the last full year after a consecutive run from their start year (just incase there are people that left and returned more than once). This should return a last year of 1996 for ID1, 2004 for ID2, and 2007 for ID3.</p> <p>Something like this, perhaps?</p> <pre><code>df_last &lt;- df %&gt;% group_by(ID) %&gt;% filter(row_number(values)[cumsum(c(1, diff(values)!=1))]) # OR df_last &lt;- df %&gt;% group_by(ID) %&gt;% filter(row_number(values)==max(values[cumsum(c(1, diff(values)!=1))])) </code></pre>
[ { "answer_id": 74496149, "author": "langtang", "author_id": 4447540, "author_profile": "https://Stackoverflow.com/users/4447540", "pm_score": 1, "selected": false, "text": "data.table::rleid() group_by(df,ID) %>%\n filter(data.table::rleid(c(1,diff(values)))==1)\n ID values\n <dbl> <dbl>\n1 1 1996\n2 2 2001\n3 2 2002\n4 2 2003\n5 2 2004\n6 3 2004\n7 3 2005\n8 3 2006\n9 3 2007\n group_by(df,ID) %>%\n filter(data.table::rleid(c(1,diff(values)))==1) %>% \n filter(row_number()==n())\n ID values\n <dbl> <dbl>\n1 1 1996\n2 2 2004\n3 3 2007\n" }, { "answer_id": 74496206, "author": "Martin Gal", "author_id": 12505251, "author_profile": "https://Stackoverflow.com/users/12505251", "pm_score": 1, "selected": true, "text": "tidyverse library(dplyr)\nlibrary(tidyr)\n\ndf_first <- df %>% \n group_by(ID) %>% \n filter(cumsum(c(1,diff(values)) - 1) == 0) %>% \n slice_min(values) %>% \n ungroup()\n \ndf_last <- df %>% \n group_by(ID) %>% \n filter(cumsum(c(1,diff(values)) - 1) == 0) %>% \n slice_max(values) %>% \n ungroup()\n #> df_first\n# A tibble: 3 × 2\n ID values\n <dbl> <dbl>\n1 1 1996\n2 2 2001\n3 3 2004\n #> df_last\n# A tibble: 3 × 2\n ID values\n <dbl> <dbl>\n1 1 1996\n2 2 2004\n3 3 2007\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20543516/" ]
74,495,966
<p>I have a column containing symbols of chemical elements and other substances. Something like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Commoditie</th> </tr> </thead> <tbody> <tr> <td>sn</td> </tr> <tr> <td>sulfuric acid</td> </tr> <tr> <td>cu</td> </tr> <tr> <td>sodium chloride</td> </tr> <tr> <td>au</td> </tr> </tbody> </table> </div> <pre><code>df1 = pd.DataFrame(['sn', 'sulfuric acid', 'cu', 'sodium chloride', 'au'], columns=['Commodities']) </code></pre> <p>And I have another data frame containing the symbols of the chemical elements and their respective names. Like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Name</th> <th>Symbol</th> </tr> </thead> <tbody> <tr> <td>sn</td> <td>tin</td> </tr> <tr> <td>cu</td> <td>copper</td> </tr> <tr> <td>au</td> <td>gold</td> </tr> </tbody> </table> </div> <pre><code>df2 = pd.DataFrame({'Name': ['tin', 'copper', 'gold'], 'Symbol': ['sn', 'cu', 'au']}) </code></pre> <p>I need to replace the symbols (in the first dataframe)(df1['Commoditie']) with the names (in the second one) (df2['Names']), so that it outputs like the following:</p> <p>I need the Output:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Commoditie</th> </tr> </thead> <tbody> <tr> <td>tin</td> </tr> <tr> <td>sulfuric acid</td> </tr> <tr> <td>copper</td> </tr> <tr> <td>sodium chloride</td> </tr> <tr> <td>gold</td> </tr> </tbody> </table> </div> <p>I tried using for loops and lambda but got different results than expected. I have tried many things and googled, I think it's something basic, but I just can't find an answer.</p> <p>Thank you in advance!</p>
[ { "answer_id": 74497066, "author": "Frodnar", "author_id": 15534441, "author_profile": "https://Stackoverflow.com/users/15534441", "pm_score": 0, "selected": false, "text": "for i, row in df2.iterrows():\n df1.Commodities = df1.Commodities.str.replace(row.Symbol, row.Name)\n df1 Commodities\n0 tin\n1 sulfuric acid\n2 copper\n3 sodium chloride\n4 gold\n df2 zip" }, { "answer_id": 74499114, "author": "Bushmaster", "author_id": 15415267, "author_profile": "https://Stackoverflow.com/users/15415267", "pm_score": 1, "selected": false, "text": "replace_dict=dict(df2[['Symbol','Name']].to_dict('split')['data'])\n#{'sn': 'tin', 'cu': 'copper', 'au': 'gold'}\n df1['Commodities']=df1['Commodities'].replace(replace_dict)\nprint(df1)\n'''\n Commodities\n0 tin\n1 sulfuric acid\n2 copper\n3 sodium chloride\n4 gold\n'''\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19745597/" ]
74,495,990
<p>I'm trying to validate a required field in an angular form through the ngModel but I get the error &quot;Property 'name' does not exist on type 'ContactComponent'.&quot;. I have seen some implementation examples but I do not see where my error is, below I share a fragment of the template and the component:</p> <p>template:</p> <pre><code>&lt;div&gt; &lt;label for=&quot;name&quot;&gt;Name&lt;/label&gt; &lt;div *ngIf=&quot;!isEditing&quot; class=&quot;inputColor&quot;&gt;{{ contact.name }}&lt;/div&gt; &lt;input [ngStyle]=&quot;{ border: '1px solid #dee1e5' }&quot; *ngIf=&quot;isEditing&quot; class=&quot;inputColor form-control&quot; type=&quot;text&quot; id=&quot;name&quot; name=&quot;name&quot; [(ngModel)]=&quot;form.name&quot; required #name=&quot;ngModel&quot; /&gt; &lt;div *ngIf=&quot;name.invalid&quot; class=&quot;p-1 bg-red-300 text-red-800 Rounded&quot;&gt; Address is required &lt;/div&gt; </code></pre> <p>Component:</p> <pre><code>export class ContactComponent { @Input() contact: Contact = {} as Contact; isEditing: Boolean = false; form: Contact = { name: '', address: '', phoneNumber: '', email: '', }; edit = () =&gt; { this.isEditing = true; } ; remove = () =&gt; {}; save = () =&gt; { console.log('on submit', this.form); this.isEditing = false; }; } </code></pre> <p>Note: The binding it is working correctly only when I try to validate it throws the error &quot;Error: src/app/contacts/contact/contact.component.html:27:19 - error TS2339: Property 'name' does not exist on type 'ContactComponent'.</p> <p>27 &lt;div *ngIf=&quot;name.invalid&quot; class=&quot;p-1 bg-red-300 text-red-800 Rounded&quot;&gt;&quot;</p>
[ { "answer_id": 74497066, "author": "Frodnar", "author_id": 15534441, "author_profile": "https://Stackoverflow.com/users/15534441", "pm_score": 0, "selected": false, "text": "for i, row in df2.iterrows():\n df1.Commodities = df1.Commodities.str.replace(row.Symbol, row.Name)\n df1 Commodities\n0 tin\n1 sulfuric acid\n2 copper\n3 sodium chloride\n4 gold\n df2 zip" }, { "answer_id": 74499114, "author": "Bushmaster", "author_id": 15415267, "author_profile": "https://Stackoverflow.com/users/15415267", "pm_score": 1, "selected": false, "text": "replace_dict=dict(df2[['Symbol','Name']].to_dict('split')['data'])\n#{'sn': 'tin', 'cu': 'copper', 'au': 'gold'}\n df1['Commodities']=df1['Commodities'].replace(replace_dict)\nprint(df1)\n'''\n Commodities\n0 tin\n1 sulfuric acid\n2 copper\n3 sodium chloride\n4 gold\n'''\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19604489/" ]
74,495,991
<p>I have an array of objects:</p> <pre class="lang-js prettyprint-override"><code>const arr = [ { user: 'b@b.com', name: 'b', surname: 'b', '29_07_2022': 'YES', '01_08_2022': 'YES', '11_11_2022': 'YES' }, { user: 'c@c.com', name: 'c', surname: 'c', '29_07_2022': 'YES', '01_08_2022': 'NO', '11_11_2022': 'NO' } ] </code></pre> <p>All the dates and the values are dynamic.</p> <p>My problem is, i don't know how to access the dates without knowing the name of the index. My code is:</p> <pre class="lang-html prettyprint-override"><code>{{#each arr}} &lt;p&gt; USER {{this.user}} &lt;/p&gt; Works &lt;p&gt; Name {{this.name}} &lt;/p&gt; Works &lt;p&gt; USER {{this.surname}} &lt;/p&gt; Works &lt;p&gt; Date1 {{??????}} &lt;/p&gt; ????? {{/each}} </code></pre> <p>My view is something like this:</p> <pre class="lang-html prettyprint-override"><code>&lt;table style=&quot;width:100%&quot;&gt; &lt;tr&gt; &lt;th&gt;USER&lt;/th&gt; &lt;th&gt;NAME&lt;/th&gt; &lt;th&gt;SURNAME&lt;/th&gt; {{#Date}} &lt;th&gt; {{moment Date format=&quot;DD/MM/YYYY&quot;}} &lt;/th&gt; {{/Date}} &lt;/tr&gt; {{#each arr}} &lt;tr&gt; &lt;th&gt;{{user}}&lt;/th&gt; &lt;th&gt;{{name}}&lt;/th&gt; &lt;th&gt;{{surname}} &lt;/th&gt; maybe another each here &lt;th&gt;{{???????}}&lt;/th&gt; close that each &lt;/tr&gt; {{/each}} &lt;/table&gt; </code></pre> <p>I want to print a table like this one:</p> <pre><code> | USER | NAME | Surname | date 1 | date 2 | date 3 | | b@b.com | b | b | YES | YES | YES | | c@c.com | c | c | YES | NO | NO | </code></pre>
[ { "answer_id": 74496083, "author": "Pompedup", "author_id": 12239272, "author_profile": "https://Stackoverflow.com/users/12239272", "pm_score": 2, "selected": true, "text": "const arr = [\n {\n user: 'b@b.com',\n name: 'b',\n surname: 'b',\n '29_07_2022': 'YES',\n '01_08_2022': 'YES',\n '11_11_2022': 'YES'\n },\n {\n user: 'c@c.com',\n name: 'c',\n surname: 'c',\n '29_07_2022': 'YES',\n '01_08_2022': 'NO',\n '11_11_2022': 'NO',\n '11_11_2023': 'NO'\n }\n]\n\nconst keys = [...new Set(arr.flatMap((content) => Object.keys(content)))]\n\nconsole.log(keys) <table style=\"width:100%\">\n <tr>\n {{#each keys as | key |}}\n <th>{{key}}</th>\n {{/each}}\n </tr>\n {{#each arr as | user |}}\n <tr>\n {{#each ../keys as | key |}}\n <th>{{lookup user key}}</th>\n {{/each}}\n </tr>\n {{/each}}\n</table>\n <table style=\"width:100%\">\n <tr>\n <th>user</th>\n <th>name</th>\n <th>surname</th>\n <th>29_07_2022</th>\n <th>01_08_2022</th>\n <th>11_11_2022</th>\n <th>11_11_2023</th>\n </tr>\n <tr>\n <th>b@b.com</th>\n <th>b</th>\n <th>b</th>\n <th>YES</th>\n <th>YES</th>\n <th>YES</th>\n <th></th>\n </tr>\n <tr>\n <th>c@c.com</th>\n <th>c</th>\n <th>c</th>\n <th>YES</th>\n <th>NO</th>\n <th>NO</th>\n <th>NO</th>\n </tr>\n</table>\n" }, { "answer_id": 74496355, "author": "jtwalters", "author_id": 3508556, "author_profile": "https://Stackoverflow.com/users/3508556", "pm_score": 0, "selected": false, "text": "maybe another each here YES true false Helper const handlebars = require(\"handlebars\");\nconst fs = require(\"fs\");\n\nconst arr = [\n {\n user: 'b@b.com',\n name: 'b',\n surname: 'b',\n '29_07_2022': 'YES',\n '01_08_2022': 'YES',\n '11_11_2022': 'YES'\n },\n {\n user: 'c@c.com',\n name: 'c',\n surname: 'c',\n '29_07_2022': 'YES',\n '01_08_2022': 'NO',\n '11_11_2022': 'NO'\n },\n {\n user: 'd@d.com',\n name: 'd',\n surname: 'd',\n '11_11_3000': 'YES'\n }\n];\n\n// Handle your dates keys\nconst dateHeaders = new Set();\n// const data = [];\nfor (const value of arr) {\n // Get only dates of the object\n const dates = new Set(Object.keys(value));\n dates.delete(\"user\");\n dates.delete(\"name\");\n dates.delete(\"surname\");\n\n // Concat dates\n for (const date of dates) {\n dateHeaders.add(date)\n }\n}\n\n// Create an equal condition to use it\n// You can ignore it if change the value 'YES' & 'NO' to true & false\nhandlebars.registerHelper('equal', function (value, value2) {\n return value === value2 ? true : false;\n});\n\n// Execute handlebars sending the array and the dateHeaders\nconst template = handlebars.compile(fs.readFileSync(\"./template.html\", \"utf8\"));\nfs.writeFileSync(\"./output.html\", template({\n arr,\n dateHeaders,\n}));\n <table style=\"width:100%\">\n <tr>\n <th>USER</th>\n <th>NAME</th>\n <th>SURNAME</th>\n {{#each dateHeaders}}\n <th>{{this}}</th>\n {{/each}}\n </tr>\n {{#each arr}}\n <tr>\n <th>{{user}}</th>\n <th>{{name}}</th>\n <th>{{surname}}</th>\n {{#each ../dateHeaders}}\n {{#if (equal (lookup ../this this) \"YES\")}}\n <th>YES</th>\n {{else}}\n <th>NO</th>\n {{/if}}\n {{/each}}\n </tr>\n {{/each}}\n</table>\n <table style=\"width:100%\">\n <tr>\n <th>USER</th>\n <th>NAME</th>\n <th>SURNAME</th>\n <th>29_07_2022</th>\n <th>01_08_2022</th>\n <th>11_11_2022</th>\n <th>11_11_3000</th>\n </tr>\n <tr>\n <th>b@b.com</th>\n <th>b</th>\n <th>b</th>\n <th>YES</th>\n <th>YES</th>\n <th>YES</th>\n <th>NO</th>\n </tr>\n <tr>\n <th>c@c.com</th>\n <th>c</th>\n <th>c</th>\n <th>YES</th>\n <th>NO</th>\n <th>NO</th>\n <th>NO</th>\n </tr>\n <tr>\n <th>d@d.com</th>\n <th>d</th>\n <th>d</th>\n <th>NO</th>\n <th>NO</th>\n <th>NO</th>\n <th>YES</th>\n </tr>\n</table>\n Array sort" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74495991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20543369/" ]
74,496,075
<p>I am designing an admin dashboard. I thought of dividing the page into two parts by using the bootstrap grid system. One part (the 3/12 of the screen) includes a nav and that is OK but I want to put some content into the 9/12 of the screen and for some reason it is also appearing in the nav. I want the text &quot;bruh&quot; in the first picture to be in the purple place in the second picture.</p> <p><a href="https://i.stack.imgur.com/Jakg0.png" rel="nofollow noreferrer">the current situation</a> <a href="https://i.stack.imgur.com/mk2jD.png" rel="nofollow noreferrer">how I want the things to be</a></p> <p>This is my html code:</p> <pre><code> &lt;div class=&quot;container-fluid&quot;&gt; &lt;div class=&quot;row&quot;&gt; &lt;div&gt; &lt;div class=&quot;col-sm-3 col-md-2 awesome_border&quot;&gt; &lt;ul class=&quot;nav flex-column gotodown&quot;&gt; &lt;li class=&quot;nav-item coolbox&quot;&gt; &lt;a class=&quot;nav-link active&quot; aria-current=&quot;page&quot; href=&quot;#&quot;&gt;Stats&lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;nav-item coolbox&quot;&gt; &lt;a class=&quot;nav-link&quot; href=&quot;#&quot;&gt;Graphs&lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;nav-item coolbox&quot;&gt; &lt;a class=&quot;nav-link&quot; href=&quot;#&quot;&gt;Users&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;br&gt; &lt;ul class=&quot;nav flex-column gotodown boxbox&quot;&gt; &lt;li class=&quot;nav-item coolbox&quot;&gt; &lt;a class=&quot;nav-link active&quot; aria-current=&quot;page&quot; href=&quot;#&quot;&gt;Reports&lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;nav-item coolbox&quot;&gt; &lt;a class=&quot;nav-link&quot; href=&quot;#&quot;&gt;Revenue&lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;nav-item coolbox&quot;&gt; &lt;a class=&quot;nav-link&quot; href=&quot;#&quot;&gt;Countries&lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;nav-item coolbox&quot;&gt; &lt;a class=&quot;nav-link&quot; href=&quot;#&quot;&gt;Spammers&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;col-sm-9 col-md-10&quot;&gt; &lt;ul class=&quot;nav flex-column&quot;&gt; &lt;li class=&quot;nav-item&quot;&gt;&lt;h2&gt;Bruh&lt;/h2&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>and this is my css:</p> <pre><code>body{ font-family: 'Rosario', sans-serif; min-height: max-content; } .gotodown{ margin-top: 80px; margin-left: 25px; } .coolbox{ padding: 0.2em; } .boxbox{ padding-top: 2%; margin-bottom: 100px; } .awesome_border{ border-style: solid; border-color: red; } </code></pre> <p>I tried writing my content in the , expecting it to appear on the right side of the screen but it appeared in the nav to the left instead.</p>
[ { "answer_id": 74496138, "author": "MeL", "author_id": 13290801, "author_profile": "https://Stackoverflow.com/users/13290801", "pm_score": 1, "selected": false, "text": "div row div <div class=\"container-fluid\">\n <div class=\"row\">\n <div class=\"col-sm-3 col-md-2 awesome_border\">\n <ul class=\"nav flex-column gotodown\">\n <li class=\"nav-item coolbox\">\n <a class=\"nav-link active\" aria-current=\"page\" href=\"#\">Stats</a>\n </li>\n <li class=\"nav-item coolbox\">\n <a class=\"nav-link\" href=\"#\">Graphs</a>\n </li>\n <li class=\"nav-item coolbox\">\n <a class=\"nav-link\" href=\"#\">Users</a>\n </li>\n </ul>\n\n <br>\n\n <ul class=\"nav flex-column gotodown boxbox\">\n <li class=\"nav-item coolbox\">\n <a class=\"nav-link active\" aria-current=\"page\" href=\"#\">Reports</a>\n </li>\n <li class=\"nav-item coolbox\">\n <a class=\"nav-link\" href=\"#\">Revenue</a>\n </li>\n <li class=\"nav-item coolbox\">\n <a class=\"nav-link\" href=\"#\">Countries</a>\n </li>\n <li class=\"nav-item coolbox\">\n <a class=\"nav-link\" href=\"#\">Spammers</a>\n </li>\n </ul>\n </div> \n \n <div class=\"col-sm-9 col-md-10\">\n <ul class=\"nav flex-column\">\n <li class=\"nav-item\"><h2>Bruh</h2></li>\n </ul>\n </div>\n </div>\n </div>\n" }, { "answer_id": 74496145, "author": "Kevin Taz Manda", "author_id": 16030906, "author_profile": "https://Stackoverflow.com/users/16030906", "pm_score": 0, "selected": false, "text": "<div style=\"text-align: right;\"><img src=\"myimage.jpg\" width=\"100\" alt=\"My Image\" /></div>" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74496075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20543575/" ]
74,496,082
<p>Let</p> <pre><code>A=[x1,x2,x3,y1,y2,y3,y4] </code></pre> <p>I want to replace everything after <code>y1</code> in the arrays <code>A</code>:</p> <pre><code>A=[x1,x2,x3,y1,y1,y1,y1] </code></pre> <p>I tried</p> <pre><code>for i in eachindex(A) if A[i]==y1 for j in i:length(A) A[j]=y1 end end end </code></pre> <p>but it seems complicate, is there any other way to do it simple?</p>
[ { "answer_id": 74496209, "author": "Bogumił Kamiński", "author_id": 1269567, "author_profile": "https://Stackoverflow.com/users/1269567", "pm_score": 2, "selected": false, "text": "y1 1 julia> A = [5, 4, 3, 1, 2, 7, 8]\n7-element Vector{Int64}:\n 5\n 4\n 3\n 1\n 2\n 7\n 8\n\njulia> loc = findfirst(==(1), A)\n4\n\njulia> isnothing(A) || (A[loc:end] .= 1);\n\njulia> A\n7-element Vector{Int64}:\n 5\n 4\n 3\n 1\n 1\n 1\n 1\n" }, { "answer_id": 74498868, "author": "DNF", "author_id": 2749865, "author_profile": "https://Stackoverflow.com/users/2749865", "pm_score": 3, "selected": true, "text": "for i in eachindex(A)\n if A[i]==y1\n for j in i+1:lastindex(A)\n A[j]=y1\n end\n break # this is important \n end \nend\n break length(A) lastindex(A) eachindex" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74496082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9326210/" ]
74,496,084
<p>I want to calculate the total sum of Salary by personalId.</p> <p>My map is of type <code>Map&lt;String, List&lt;Employee&gt;&gt;</code>. Where employee <code>id</code> is used a Key, while value is a list of employee instances having the same <code>id</code>.</p> <p>Here is the list of map shown below</p> <pre><code>Id, Name , Surname, Salary personalId1, &quot;Name 1&quot;,&quot;Surname 1&quot;, 100 personalId2, &quot;Name 2&quot;,&quot;Surname 2&quot;, 100 personalId3, &quot;Name 3&quot;,&quot;Surname 3&quot;, 100 personalId1, &quot;Name 1&quot;,&quot;Surname 1&quot;, 100 personalId2, &quot;Name 2&quot;,&quot;Surname 2&quot;, 100 personalId2, &quot;Name 2&quot;,&quot;Surname 2&quot;, 100 ......................... </code></pre> <p>What I really want to get this result shown below.</p> <pre><code>personalId1, &quot;Name 1&quot;,&quot;Surname 1&quot;, 200 personalId2, &quot;Name 2&quot;,&quot;Surname 2&quot;, 300 personalId3, &quot;Name 3&quot;,&quot;Surname 3&quot;, 100 </code></pre> <p>Here is my dto class shown below</p> <pre><code>public class SalaryDto { private String id; private String name; private String surname; private BigDecimal totalSalary; } </code></pre> <p>I tried to use java stream to get this result but I have a problem after <code>flatMap</code>. To get the total by personalId, I want to use &quot;reduce&quot;.</p> <p>Here is the code snippet shown below.</p> <pre><code>List&lt;SalaryDto&gt; totalSalary = employees.values().stream() .flatMap(List::stream) .map(e-&gt; new SalaryDto(...)) .collect(groupingBy(Personal::getID, Collectors.toList())); </code></pre> <p>How can I do that?</p>
[ { "answer_id": 74496342, "author": "Alexander Ivanchenko", "author_id": 17949945, "author_profile": "https://Stackoverflow.com/users/17949945", "pm_score": 3, "selected": true, "text": "SalaryDto public class SalaryAccumulator implements Consumer<Employee> {\n private String id;\n private String name;\n private String surname;\n private BigDecimal totalSalary = BigDecimal.ZERO;\n \n public void accept(Employee e) {\n if (id == null) id = e.getId();\n if (name == null) name = e.getName();\n if (surname == null) surname = e.getSurname();\n totalSalary = totalSalary.add(e.getSalary());\n }\n \n public SalaryAccumulator merge(SalaryAccumulator other) {\n totalSalary = totalSalary.add(other.getTotalSalary());\n return this;\n }\n \n public SalaryDto toSalaryDto() {\n return new SalaryDto(id, name, surname, totalSalary);\n }\n}\n List Employee SalaryDto collect() Collector.of() SalaryAccumulator Map<String, List<Employee>> employees = // initializing the map\n \nList<SalaryDto> totalSalary = employees.values().stream()\n .map(list -> list.stream()\n .collect(Collector.of(\n SalaryAccumulator::new,\n SalaryAccumulator::accept,\n SalaryAccumulator::merge,\n SalaryAccumulator::toSalaryDto\n ))\n ).toList();\n collectingAndThen() reducing() Map<String, List<Employee>> employees = // initializing the map\n \nList<SalaryDto> totalSalary = employees.values().stream()\n .map(l -> l.stream()\n .map(Employee::getSalary)\n .collect(Collectors.collectingAndThen(\n Collectors.reducing(BigDecimal::add),\n salary -> new SalaryDto(l.get(0).getId(),\n l.get(0).getName(),\n l.get(0).getSurname(),\n salary.orElseThrow())\n ))\n ).toList();\n" }, { "answer_id": 74496374, "author": "shmosel", "author_id": 1553851, "author_profile": "https://Stackoverflow.com/users/1553851", "pm_score": 1, "selected": false, "text": "SalaryDto SalaryDto flatten(List<Employee> employees) {\n BigDecimal totalSalary = employees.stream()\n .map(Employee::getSalary)\n .reduce(BigDecimal::add).get();\n return SalaryDto.forEmployee(employees.get(0), totalSalary);\n}\n map List<SalaryDto> salaries = employees.values()\n .stream()\n .map(this::flatten)\n .collect(toMap(SalaryDto::getId, s -> s));\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74496084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5719229/" ]
74,496,093
<p>my question is about applying a complicated function to every row of a table.</p> <p>I'm trying to find the traveling time and route of some pairs of points using the osrm package in r (<a href="https://cran.r-project.org/web/packages/osrm/osrm.pdf" rel="nofollow noreferrer">https://cran.r-project.org/web/packages/osrm/osrm.pdf</a>). My data looks like this - each row is a pair of origin-destination points:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID_o</th> <th>ID_d</th> <th>longitude_o</th> <th>latitude_o</th> <th>longitude_d</th> <th>latitude_d</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>5</td> <td>-122.2925</td> <td>47.72932</td> <td>-122.2820</td> <td>47.73027</td> </tr> <tr> <td>2</td> <td>6</td> <td>-122.2820</td> <td>47.73027</td> <td>-122.2944</td> <td>47.72293</td> </tr> <tr> <td>3</td> <td>7</td> <td>-122.3365</td> <td>47.72512</td> <td>-122.3153</td> <td>47.71490</td> </tr> <tr> <td>4</td> <td>8</td> <td>-122.3264</td> <td>47.70752</td> <td>-122.3151</td> <td>47.70674</td> </tr> </tbody> </table> </div> <p>I can use the function in osrm to obtain the route for any one row</p> <pre><code>time.route1 &lt;- osrmRoute(src = mydata[1, c('longitude_o', 'latitude_o')], dst = mydata[1, c('longitude_d', 'latitude_d')], returnclass = &quot;sf&quot;) </code></pre> <p>I can also write a loop to compute what I need for multiple rows</p> <pre><code>time.route2 &lt;- data.frame(matrix(, nrow=4, ncol=5)) for (ix in c(1:4) ) { route.temp &lt;- osrmRoute(src = mydata[ix, c('longitude_o', 'latitude_o')], dst = mydata[ix, c('longitude_d', 'latitude_d')], returnclass = &quot;sf&quot;) time.route2[ix, ] &lt;- route } </code></pre> <p>in which I simply apply the function to each row sequentially. But loop runs slow (I have millions of rows) and stops unexpectedly when there is an NA in my raw data. And it's clear that the computation of one row has nothing to do with all the others. So it's possible to do them simultaneously.</p> <p>Is there a way to do parallel computing on each row at the same time? Using <code>apply</code> or <code>map</code> function or other methods? Simple examples of <code>apply</code> and <code>map</code> function doesn't help since <code>osrmRoute</code> is a quite complicated function.</p> <p>I tried the following</p> <pre><code>biroute &lt;- function(geofile, ix=1) { osrmRoute(src = geofile[ix, c('longitude_o', 'latitude_o')], dst = geofile[ix, c('longitude_d', 'latitude_d')]) } route &lt;- apply(mydata, 1, biroute) </code></pre> <p>but an error occurs when executing the <code>osrmRoute</code> function saying &quot;incorrect number of dimensions&quot;.</p>
[ { "answer_id": 74496413, "author": "Martin Gal", "author_id": 12505251, "author_profile": "https://Stackoverflow.com/users/12505251", "pm_score": 1, "selected": true, "text": "biroute <- function(geofile) {\n osrmRoute(src = geofile[c('longitude_o', 'latitude_o')],\n dst = geofile[c('longitude_d', 'latitude_d')])\n}\n\napply(mydata, 1, biroute)\n [[1]]\nSimple feature collection with 1 feature and 4 fields\nGeometry type: LINESTRING\nDimension: XY\nBounding box: xmin: -122.2924 ymin: 47.72932 xmax: -122.282 ymax: 47.73631\nGeodetic CRS: WGS 84\n src dst duration distance geometry\nsrc_dst src dst 4.258333 2.1745 LINESTRING (-122.2923 47.72...\n\n[[2]]\nSimple feature collection with 1 feature and 4 fields\nGeometry type: LINESTRING\nDimension: XY\nBounding box: xmin: -122.2944 ymin: 47.72289 xmax: -122.282 ymax: 47.73629\nGeodetic CRS: WGS 84\n src dst duration distance geometry\nsrc_dst src dst 6.233333 3.0681 LINESTRING (-122.2821 47.73...\n\n[[3]]\nSimple feature collection with 1 feature and 4 fields\nGeometry type: LINESTRING\nDimension: XY\nBounding box: xmin: -122.3364 ymin: 47.7149 xmax: -122.3153 ymax: 47.72686\nGeodetic CRS: WGS 84\n src dst duration distance geometry\nsrc_dst src dst 6.058333 2.7979 LINESTRING (-122.3363 47.72...\n\n[[4]]\nSimple feature collection with 1 feature and 4 fields\nGeometry type: LINESTRING\nDimension: XY\nBounding box: xmin: -122.3264 ymin: 47.70674 xmax: -122.3151 ymax: 47.7086\nGeodetic CRS: WGS 84\n src dst duration distance geometry\nsrc_dst src dst 2.903333 1.139 LINESTRING (-122.3264 47.70...\n" }, { "answer_id": 74496707, "author": "nniloc", "author_id": 12400385, "author_profile": "https://Stackoverflow.com/users/12400385", "pm_score": 1, "selected": false, "text": "purrr::safely furrr possibly biroute <- function(longitude_o, latitude_o, longitude_d, latitude_d) {\n osrm::osrmRoute(src = c(longitude_o, latitude_o),\n dst = c(longitude_d, latitude_d))\n}\n\nbiroute_possibly <- purrr::possibly(biroute, NA)\n workers library(furrr)\nplan(multisession, workers = 2)\n\nfuture_pmap(mydata[,-c(1:2)], biroute_possibly)\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74496093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18201364/" ]
74,496,094
<p>I want to validate if the fields of all inputs in a form are not empty, currently I'm doing that like so:</p> <pre class="lang-js prettyprint-override"><code>const handleSubmit = (e) =&gt; { if (!formCompra.input1|| !formCompra.input2|| !restForm.input3|| !restForm.input4|| !restForm.input5) { alert('you are missing some fields') } } </code></pre> <p>This works fine, but the message is very generic. That's why I'm looking for a way to perform the validation in a way that outputs a message containing all the missing fields, for example: &quot;you're missing input1, input2&quot;.</p>
[ { "answer_id": 74496413, "author": "Martin Gal", "author_id": 12505251, "author_profile": "https://Stackoverflow.com/users/12505251", "pm_score": 1, "selected": true, "text": "biroute <- function(geofile) {\n osrmRoute(src = geofile[c('longitude_o', 'latitude_o')],\n dst = geofile[c('longitude_d', 'latitude_d')])\n}\n\napply(mydata, 1, biroute)\n [[1]]\nSimple feature collection with 1 feature and 4 fields\nGeometry type: LINESTRING\nDimension: XY\nBounding box: xmin: -122.2924 ymin: 47.72932 xmax: -122.282 ymax: 47.73631\nGeodetic CRS: WGS 84\n src dst duration distance geometry\nsrc_dst src dst 4.258333 2.1745 LINESTRING (-122.2923 47.72...\n\n[[2]]\nSimple feature collection with 1 feature and 4 fields\nGeometry type: LINESTRING\nDimension: XY\nBounding box: xmin: -122.2944 ymin: 47.72289 xmax: -122.282 ymax: 47.73629\nGeodetic CRS: WGS 84\n src dst duration distance geometry\nsrc_dst src dst 6.233333 3.0681 LINESTRING (-122.2821 47.73...\n\n[[3]]\nSimple feature collection with 1 feature and 4 fields\nGeometry type: LINESTRING\nDimension: XY\nBounding box: xmin: -122.3364 ymin: 47.7149 xmax: -122.3153 ymax: 47.72686\nGeodetic CRS: WGS 84\n src dst duration distance geometry\nsrc_dst src dst 6.058333 2.7979 LINESTRING (-122.3363 47.72...\n\n[[4]]\nSimple feature collection with 1 feature and 4 fields\nGeometry type: LINESTRING\nDimension: XY\nBounding box: xmin: -122.3264 ymin: 47.70674 xmax: -122.3151 ymax: 47.7086\nGeodetic CRS: WGS 84\n src dst duration distance geometry\nsrc_dst src dst 2.903333 1.139 LINESTRING (-122.3264 47.70...\n" }, { "answer_id": 74496707, "author": "nniloc", "author_id": 12400385, "author_profile": "https://Stackoverflow.com/users/12400385", "pm_score": 1, "selected": false, "text": "purrr::safely furrr possibly biroute <- function(longitude_o, latitude_o, longitude_d, latitude_d) {\n osrm::osrmRoute(src = c(longitude_o, latitude_o),\n dst = c(longitude_d, latitude_d))\n}\n\nbiroute_possibly <- purrr::possibly(biroute, NA)\n workers library(furrr)\nplan(multisession, workers = 2)\n\nfuture_pmap(mydata[,-c(1:2)], biroute_possibly)\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74496094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17668614/" ]
74,496,118
<p>I have mass spec data that I need help annotating. I have two files loaded. File1 has two columns (mz, intensity) and File2 has two as well (mz, name). In both files, all of the columns are numeric values, except for name that's characters. I need to take the mz value in File1 and match against the mz values in File2 within +/- 0.001. If a value falls within that range in File1, I need to annotate with the 'name' value in File2. Below is an example:</p> <p><strong>File1</strong></p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>mz</th> <th>intensity</th> </tr> </thead> <tbody> <tr> <td>100.1234</td> <td>1234</td> </tr> <tr> <td>134.5678</td> <td>7653</td> </tr> <tr> <td>150.1234</td> <td>23463</td> </tr> <tr> <td>176.5678</td> <td>12354</td> </tr> </tbody> </table> </div> <p><strong>File2</strong></p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>mz</th> <th>name</th> </tr> </thead> <tbody> <tr> <td>100.1225</td> <td>name1</td> </tr> <tr> <td>112.5678</td> <td>name2</td> </tr> <tr> <td>150.1239</td> <td>name3</td> </tr> <tr> <td>176.5665</td> <td>name4</td> </tr> </tbody> </table> </div> <p>the idea is to get an output like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>mz</th> <th>intensity</th> <th>name</th> </tr> </thead> <tbody> <tr> <td>100.1234</td> <td>1234</td> <td>name1</td> </tr> <tr> <td>134.5678</td> <td>7653</td> <td></td> </tr> <tr> <td>150.1234</td> <td>23463</td> <td></td> </tr> <tr> <td>176.5678</td> <td>12354</td> <td>name4</td> </tr> </tbody> </table> </div> <p>I tried using mutate and merge, but I'm not sure how to add the number range and use a conditional statement to make it work. I also tried data.table, but again, not sure how to adjust for a range.</p>
[ { "answer_id": 74496243, "author": "Pariksheet Nanda", "author_id": 10602009, "author_profile": "https://Stackoverflow.com/users/10602009", "pm_score": 1, "selected": false, "text": "library(dplyr)\n\n## The example data.\nfile1 <- tibble::tribble(\n ~mz, ~intensity,\n 100.1234, 1234,\n 134.5678, 7653,\n 150.1234, 23463,\n 176.5678, 12354,\n)\nfile2 <- tibble::tribble(\n ~mz, ~name,\n 100.1225, \"name1\",\n 112.5678, \"name2\",\n 150.1239, \"name3\",\n 176.5665, \"name4\",\n)\n\nout <-\n file1 %>%\n mutate(approx = round(mz, 3)) %>%\n left_join(file2 %>% mutate(approx = round(mz, 3)) %>% select(-mz),\n by = \"approx\") %>%\n select(-approx)\n\n## Note that the output differs because ?round follows IEC 60559, IEEE 754\n" }, { "answer_id": 74496262, "author": "Ric Villalba", "author_id": 6912817, "author_profile": "https://Stackoverflow.com/users/6912817", "pm_score": 1, "selected": true, "text": "library(dplyr)\nfile1 %>% rowwise() %>% mutate(\n name = if(any(abs(file2$mz - mz)<0.001)) \n file2$name[min(which(abs(file2$mz - mz)<0.001))] else \"\")\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74496118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20543491/" ]
74,496,131
<p>When I run <code>git push</code> on a repository that I own I get prompted for username and password.</p> <pre><code>╭─austin@Austins-MacBook-Pro.local ~/workspace/blah ╰─➤ git push Username for 'https://github.com/acarrillo2/dotfiles.git': acarrillo2 Password for 'https://acarrillo2@github.com/acarrillo2/dotfiles.git': </code></pre> <p>However when I run <code>git config --list</code> I see <code>github.user</code> and <code>github.token</code> get printed out.</p> <pre><code>... user.name=Austin Carrillo user.email=EMAIL@email.com github.user=acarrillo2 github.token=SUPER_SECRET </code></pre> <p>Looking at the docs for <code>gh</code>: <a href="https://cli.github.com/manual/" rel="nofollow noreferrer">https://cli.github.com/manual/</a></p> <p>It appears this should work but just to be sure I also added my token as an environmental variable and it is printed out when I use <code>printenv</code>:</p> <pre><code>... PAGER=less LESS=-R LSCOLORS=Gxfxcxdxbxegedabagacad GH_TOKEN=SUPER_SECRET </code></pre> <p>Is there somewhere else I should be storing these?</p> <p>Note: I am not using any virtual environments.</p> <p>I would expect that storing this value in my gitconfig OR my environmental variable would do the trick.</p> <p>I even tried running the below command and I still get prompted for username and password:</p> <pre><code>╭─austin@laptop ~/workspace/blah ╰─➤ gh auth login ? What account do you want to log into? GitHub.com The value of the GH_TOKEN environment variable is being used for authentication. To have GitHub CLI store credentials instead, first clear the value from the environment. </code></pre> <p>Still get prompted for username and password.</p>
[ { "answer_id": 74496505, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 0, "selected": false, "text": "git config --global credential.helper" }, { "answer_id": 74496911, "author": "bk2204", "author_id": 8705432, "author_profile": "https://Stackoverflow.com/users/8705432", "pm_score": 2, "selected": false, "text": "gh github.* credential.helper manager osxkeychain libsecret /usr/share/doc/git/contrib/credential/libsecret make PATH" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74496131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9328372/" ]
74,496,200
<p>In a simple Program in <code>BugTest.py</code>:</p> <pre><code>from BugTest import * print(&quot;Hello World&quot;) </code></pre> <p><strong>note my error in importing BugTest.py from BugTest.py</strong></p> <p>Here is the output:</p> <pre><code>Hello World Hello World </code></pre> <p>My question is: <strong>Why doesn't this cause a compile error?</strong> Is this a bug in Python?</p> <p>Why does it only import twice, rather than enter an infinite loop?</p>
[ { "answer_id": 74496228, "author": "J_H", "author_id": 8431111, "author_profile": "https://Stackoverflow.com/users/8431111", "pm_score": 2, "selected": false, "text": "$ python BugTest.py\n import print print() import import x x import x" }, { "answer_id": 74496254, "author": "Karl Knechtel", "author_id": 523612, "author_profile": "https://Stackoverflow.com/users/523612", "pm_score": 2, "selected": false, "text": "SyntaxError from BugTest import * BugTest BugTest.py BugTest BugTest BugTest.py __main__ import BugTest.py BugTest import BugTest" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74496200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9053474/" ]
74,496,229
<p>How do I validate a radio button? I want to make it so that if the user left the radio button unclicked the section background will turn a red colour/color.</p> <p>Here is the HTML Page</p> <pre><code>&lt;p id=&quot;caption_project&quot;&gt;Project Selection &lt;br/&gt; &lt;input type=&quot;radio&quot; name=&quot;f__project&quot; id=&quot;in_restaurant&quot; value=&quot;restaurant&quot;/&gt; &lt;label for=&quot;in_restaurant&quot;&gt;LEGO Project&lt;/label&gt; &lt;br/&gt; &lt;input type=&quot;radio&quot; name=&quot;f__project&quot; id=&quot;in_humber&quot; value=&quot;Humber News&quot;/&gt; &lt;label for=&quot;in_humber&quot;&gt;Humber Current Project&lt;/label&gt; &lt;br/&gt; &lt;input type=&quot;radio&quot; name=&quot;f__project&quot; id=&quot;in_self&quot; value=&quot;self-determined&quot;/&gt; &lt;label for=&quot;in_self&quot;&gt;Self-determined Project&lt;/label&gt; &lt;/p&gt; </code></pre> <p>So how do I turn the background red when they leave it unchecked?</p>
[ { "answer_id": 74496265, "author": "Georgemff", "author_id": 9716786, "author_profile": "https://Stackoverflow.com/users/9716786", "pm_score": -1, "selected": false, "text": "document.querySelector(\"input[name='f__project']:checked\")\n" }, { "answer_id": 74496282, "author": "Barmar", "author_id": 1491895, "author_profile": "https://Stackoverflow.com/users/1491895", "pm_score": 1, "selected": false, "text": "document.querySelector(\"input[name='f__project']:checked\") null <form> required" }, { "answer_id": 74496299, "author": "user3425506", "author_id": 3425506, "author_profile": "https://Stackoverflow.com/users/3425506", "pm_score": 2, "selected": true, "text": "!checked const nextThing = document.querySelector('#next-thing');\n\nconst p = document.querySelector('p');\n\nnextThing.addEventListener('click', function(){\n const checked = document.querySelector(\"input[name='f__project']:checked\");\n if(!checked){\n p.setAttribute('style', 'background:red');\n }\n}); <p id=\"caption_project\">Project Selection\n <br/>\n <input type=\"radio\" name=\"f__project\" id=\"in_restaurant\" value=\"restaurant\"/>\n <label for=\"in_restaurant\">LEGO Project</label>\n <br/>\n <input type=\"radio\" name=\"f__project\" id=\"in_humber\" value=\"Humber News\"/>\n <label for=\"in_humber\">Humber Current Project</label>\n <br/>\n <input type=\"radio\" name=\"f__project\" id=\"in_self\" value=\"self-determined\"/>\n <label for=\"in_self\">Self-determined Project</label>\n</p>\n\n<button id='next-thing'>Next form control</button>" }, { "answer_id": 74496304, "author": "Salim", "author_id": 4478946, "author_profile": "https://Stackoverflow.com/users/4478946", "pm_score": 0, "selected": false, "text": "const checkedRadioButton = document.\n querySelector(\"input[name='f__project']:checked\");\n\nif (!checkedRadioButton) {\n // No values are selected\n} else {\n // Some value is selected and the element is stored in checkedRadioButton\n}\n" }, { "answer_id": 74496317, "author": "Tarun Bisht", "author_id": 6906504, "author_profile": "https://Stackoverflow.com/users/6906504", "pm_score": 0, "selected": false, "text": "input[type=\"radio\"] {\n display: none;\n}\ninput[type=\"radio\"] + label {\n border: 5px solid lightblue;\n background-color: lightblue;\n cursor: pointer;\n display: block;\n height: 40px;\n width: 200px;\n text-align: center;\n line-height: 40px;\n}\ninput[type=\"radio\"]:checked + label {\n border: 5px solid blue;\n background-color: dodgerblue;\n}\n function checkRadioValidity() { \n if(document.getElementById('in_restaurant').checked) {\n //change CSS here for the element\n }\n}\n" }, { "answer_id": 74496325, "author": "Alexius de Vinco", "author_id": 1810347, "author_profile": "https://Stackoverflow.com/users/1810347", "pm_score": 1, "selected": false, "text": "document.getElementById('id').checked" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74496229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20401157/" ]
74,496,233
<p>This is what my sheet looks like:</p> <p><a href="https://i.stack.imgur.com/ZfwqC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZfwqC.png" alt="enter image description here" /></a></p> <p>(I got the code from online somewhere &amp; just been adjust what I know)</p> <p>I Currently have 10 rows with working buttons, but it's already at 500+ lines of code and I still need 60more. I'm worried the file will become too large and start crashing.</p> <p>Should I just keep changing the &quot;Range(F#)&quot; every time I make a new button/row?</p> <p>Also, is it possible to keep more than 1 timer going at a time? Currently when I click stop on any of the rows it will stop whatever timer is active.</p> <pre><code>Public StopIt As Boolean Public ResetIt As Boolean Public LastTime Private Sub cust10reset_Click() Range(&quot;F10&quot;).Value = Format(0, &quot;00&quot;) &amp; &quot;:&quot; &amp; Format(0, &quot;00&quot;) &amp; &quot;:&quot; &amp; Format(0, &quot;00&quot;) &amp; &quot;.&quot; &amp; Format(0, &quot;00&quot;) LastTime = 0 ResetIt = True End Sub Private Sub cust10start_Click() Dim StartTime, FinishTime, TotalTime, PauseTime StopIt = False ResetIt = False If Range(&quot;F10&quot;) = 0 Then StartTime = Timer PauseTime = 0 LastTime = 0 Else StartTime = 0 PauseTime = Timer End If StartIt: DoEvents If StopIt = True Then LastTime = TotalTime Exit Sub Else FinishTime = Timer TotalTime = FinishTime - StartTime + LastTime - PauseTime TTime = TotalTime * 100 HM = TTime Mod 100 TTime = TTime \ 100 hh = TTime \ 3600 TTime = TTime Mod 3600 MM = TTime \ 60 SS = TTime Mod 60 Range(&quot;F10&quot;).Value = Format(hh, &quot;00&quot;) &amp; &quot;:&quot; &amp; Format(MM, &quot;00&quot;) &amp; &quot;:&quot; &amp; Format(SS, &quot;00&quot;) &amp; &quot;.&quot; &amp; Format(HM, &quot;00&quot;) If ResetIt = True Then Range(&quot;F10&quot;) = Format(0, &quot;00&quot;) &amp; &quot;:&quot; &amp; Format(0, &quot;00&quot;) &amp; &quot;:&quot; &amp; Format(0, &quot;00&quot;) &amp; &quot;.&quot; &amp; Format(0, &quot;00&quot;) LastTime = 0 PauseTime = 0 End End If GoTo StartIt End If End Sub Private Sub cust10stop_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single) StopIt = True End Sub </code></pre> <p>I tried making a dedicated formula tab and just make macros going my timer buttons but I couldn't get that to work.</p> <p>I tried making a togglebutton and linking it to the cell then just make a code that references the linkedcell to know where to put the timer, but that wasn't working. It just kept coming back true/false.</p> <p>I guess I just want to know if it's ok to have 4000+ lines on 1 sheet with 210 buttons lol. Or just an easier way.</p>
[ { "answer_id": 74496265, "author": "Georgemff", "author_id": 9716786, "author_profile": "https://Stackoverflow.com/users/9716786", "pm_score": -1, "selected": false, "text": "document.querySelector(\"input[name='f__project']:checked\")\n" }, { "answer_id": 74496282, "author": "Barmar", "author_id": 1491895, "author_profile": "https://Stackoverflow.com/users/1491895", "pm_score": 1, "selected": false, "text": "document.querySelector(\"input[name='f__project']:checked\") null <form> required" }, { "answer_id": 74496299, "author": "user3425506", "author_id": 3425506, "author_profile": "https://Stackoverflow.com/users/3425506", "pm_score": 2, "selected": true, "text": "!checked const nextThing = document.querySelector('#next-thing');\n\nconst p = document.querySelector('p');\n\nnextThing.addEventListener('click', function(){\n const checked = document.querySelector(\"input[name='f__project']:checked\");\n if(!checked){\n p.setAttribute('style', 'background:red');\n }\n}); <p id=\"caption_project\">Project Selection\n <br/>\n <input type=\"radio\" name=\"f__project\" id=\"in_restaurant\" value=\"restaurant\"/>\n <label for=\"in_restaurant\">LEGO Project</label>\n <br/>\n <input type=\"radio\" name=\"f__project\" id=\"in_humber\" value=\"Humber News\"/>\n <label for=\"in_humber\">Humber Current Project</label>\n <br/>\n <input type=\"radio\" name=\"f__project\" id=\"in_self\" value=\"self-determined\"/>\n <label for=\"in_self\">Self-determined Project</label>\n</p>\n\n<button id='next-thing'>Next form control</button>" }, { "answer_id": 74496304, "author": "Salim", "author_id": 4478946, "author_profile": "https://Stackoverflow.com/users/4478946", "pm_score": 0, "selected": false, "text": "const checkedRadioButton = document.\n querySelector(\"input[name='f__project']:checked\");\n\nif (!checkedRadioButton) {\n // No values are selected\n} else {\n // Some value is selected and the element is stored in checkedRadioButton\n}\n" }, { "answer_id": 74496317, "author": "Tarun Bisht", "author_id": 6906504, "author_profile": "https://Stackoverflow.com/users/6906504", "pm_score": 0, "selected": false, "text": "input[type=\"radio\"] {\n display: none;\n}\ninput[type=\"radio\"] + label {\n border: 5px solid lightblue;\n background-color: lightblue;\n cursor: pointer;\n display: block;\n height: 40px;\n width: 200px;\n text-align: center;\n line-height: 40px;\n}\ninput[type=\"radio\"]:checked + label {\n border: 5px solid blue;\n background-color: dodgerblue;\n}\n function checkRadioValidity() { \n if(document.getElementById('in_restaurant').checked) {\n //change CSS here for the element\n }\n}\n" }, { "answer_id": 74496325, "author": "Alexius de Vinco", "author_id": 1810347, "author_profile": "https://Stackoverflow.com/users/1810347", "pm_score": 1, "selected": false, "text": "document.getElementById('id').checked" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74496233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20543515/" ]
74,496,239
<p>We can use the new <a href="https://learn.microsoft.com/en-us/dotnet/api/system.numerics.inumber-1?view=net-7.0" rel="nofollow noreferrer"><code>INumber&lt;TSelf&gt;</code> interface</a> in .NET 7 to reference any numeric type, like the following:</p> <pre class="lang-cs prettyprint-override"><code>using System.Numerics; INumber&lt;int&gt; myNumber = 72; INumber&lt;float&gt; mySecondNumber = 93.63f; </code></pre> <p>However, because of the type constraint in <code>INumber</code>, we can't have a generic reference that can hold any numeric type. This following code is invalid:</p> <pre class="lang-cs prettyprint-override"><code>using System.Numerics; INumber myNumber = 72; myNumber = 93.63f; </code></pre> <p>How can I have an array of any numeric objects and call a method that is expecting a <code>INumber&lt;TSelf&gt;</code> object.</p> <pre class="lang-cs prettyprint-override"><code>using System.Numerics; object[] numbers = new object[] { 1, 2.5, 5, 0x1001, 72 }; for (int i = 0; i &lt; numbers.Length - 1; i++) { Console.WriteLine(&quot;{0} plus {1} equals {2}&quot;, numbers[i], numbers[i + 1], AddNumbers(numbers[i], numbers[i + 1])); } static T AddNumbers&lt;T&gt;(T left, T right) where T : INumber&lt;T&gt; =&gt; left + right; </code></pre>
[ { "answer_id": 74496397, "author": "NineBerry", "author_id": 101087, "author_profile": "https://Stackoverflow.com/users/101087", "pm_score": 2, "selected": false, "text": "INumber<TSelf> public interface INumber<TSelf> : \n IComparable, \n IComparable<TSelf>, \n IEquatable<TSelf>, \n IParsable<TSelf>, \n ISpanParsable<TSelf>,\n System.Numerics.IAdditionOperators<TSelf,TSelf,TSelf>,\n System.Numerics.IAdditiveIdentity<TSelf,TSelf>,\n System.Numerics.IComparisonOperators<TSelf,TSelf,bool>,\n System.Numerics.IDecrementOperators<TSelf>,\n System.Numerics.IDivisionOperators<TSelf,TSelf,TSelf>,\n System.Numerics.IEqualityOperators<TSelf,TSelf,bool>,\n System.Numerics.IIncrementOperators<TSelf>,\n System.Numerics.IModulusOperators<TSelf,TSelf,TSelf>, \n System.Numerics.IMultiplicativeIdentity<TSelf,TSelf>, \n System.Numerics.IMultiplyOperators<TSelf,TSelf,TSelf>, \n System.Numerics.INumberBase<TSelf>, \n System.Numerics.ISubtractionOperators<TSelf,TSelf,TSelf>, \n System.Numerics.IUnaryNegationOperators<TSelf,TSelf>, \n System.Numerics.IUnaryPlusOperators<TSelf,TSelf> \n where TSelf : INumber<TSelf>\n TSelf INumber" }, { "answer_id": 74496446, "author": "Wai Ha Lee", "author_id": 1364007, "author_profile": "https://Stackoverflow.com/users/1364007", "pm_score": 2, "selected": false, "text": "INumber INumber<TSelf> var numbers = new object[] { 1, 2.5, 5, 0x1001, 72 };\n INumber<T> var numbers = new INumber<>[] { 1, 2.5, 5, 0x1001, 72 };\n INumber INumber<TSelf> IEnumerable IEnumerable<T> INumber IAdditionOperators<TSelf,TOther,TResult> + INumber, INumber UserDefinedNumber : INumber<UserDefinedNumber> INumber a = 1d;\nINumber b = new UserDefinedNumber(...);\nvar c = a + b;\n a + b INumber + a double double UserDefinedNumber" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74496239", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10507708/" ]
74,496,251
<p>i want to send a notification to (Segments) target like [&quot;Active Users&quot;] with parameter &quot;included_segments&quot; but When i call the API using CURL in PHP i get this Error : (Please include a case-sensitive header of Authorization: Basic or Bearer token=&quot;&quot; with a valid REST API key.).</p> <p>however the code is running well when i change target from parameter &quot;included_segments&quot; to &quot;include_player_ids&quot; .. but i want &quot;included_segments&quot; .. please HELP Me!.</p> <p><a href="https://documentation.onesignal.com/reference/create-notification" rel="nofollow noreferrer">LINK to REST API Reference</a></p> <ul> <li>this is my Code : `</li> </ul> <pre><code>function Copts($titlEN,$titlAR,$contEN,$contAR,$icon,$img){ $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL =&gt; 'https://onesignal.com/api/v1/notifications', CURLOPT_RETURNTRANSFER =&gt; true, CURLOPT_ENCODING =&gt; '', CURLOPT_MAXREDIRS =&gt; 10, CURLOPT_TIMEOUT =&gt; 0, CURLOPT_FOLLOWLOCATION =&gt; true, CURLOPT_HTTP_VERSION =&gt; CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST =&gt; 'POST', CURLOPT_POSTFIELDS =&gt;'{ &quot;app_id&quot;: &quot;xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx&quot;, &quot;included_segments&quot;: [&quot;Active Users&quot;], &quot;contents&quot;: {&quot;en&quot;: &quot;'.$contEN.'&quot;}, &quot;headings&quot;: {&quot;en&quot;: &quot;'.$titlEN.'&quot;}, &quot;global_image&quot;: &quot;'.$img.'&quot;, &quot;large_icon&quot;: &quot;'.$icon.'&quot; }', CURLOPT_HTTPHEADER =&gt; array( 'Content-Type: application/json; charset=utf-8', 'Authorization: Basic xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' ) )); return json_decode(curl_exec($curl),true); } </code></pre> <p>`</p>
[ { "answer_id": 74496397, "author": "NineBerry", "author_id": 101087, "author_profile": "https://Stackoverflow.com/users/101087", "pm_score": 2, "selected": false, "text": "INumber<TSelf> public interface INumber<TSelf> : \n IComparable, \n IComparable<TSelf>, \n IEquatable<TSelf>, \n IParsable<TSelf>, \n ISpanParsable<TSelf>,\n System.Numerics.IAdditionOperators<TSelf,TSelf,TSelf>,\n System.Numerics.IAdditiveIdentity<TSelf,TSelf>,\n System.Numerics.IComparisonOperators<TSelf,TSelf,bool>,\n System.Numerics.IDecrementOperators<TSelf>,\n System.Numerics.IDivisionOperators<TSelf,TSelf,TSelf>,\n System.Numerics.IEqualityOperators<TSelf,TSelf,bool>,\n System.Numerics.IIncrementOperators<TSelf>,\n System.Numerics.IModulusOperators<TSelf,TSelf,TSelf>, \n System.Numerics.IMultiplicativeIdentity<TSelf,TSelf>, \n System.Numerics.IMultiplyOperators<TSelf,TSelf,TSelf>, \n System.Numerics.INumberBase<TSelf>, \n System.Numerics.ISubtractionOperators<TSelf,TSelf,TSelf>, \n System.Numerics.IUnaryNegationOperators<TSelf,TSelf>, \n System.Numerics.IUnaryPlusOperators<TSelf,TSelf> \n where TSelf : INumber<TSelf>\n TSelf INumber" }, { "answer_id": 74496446, "author": "Wai Ha Lee", "author_id": 1364007, "author_profile": "https://Stackoverflow.com/users/1364007", "pm_score": 2, "selected": false, "text": "INumber INumber<TSelf> var numbers = new object[] { 1, 2.5, 5, 0x1001, 72 };\n INumber<T> var numbers = new INumber<>[] { 1, 2.5, 5, 0x1001, 72 };\n INumber INumber<TSelf> IEnumerable IEnumerable<T> INumber IAdditionOperators<TSelf,TOther,TResult> + INumber, INumber UserDefinedNumber : INumber<UserDefinedNumber> INumber a = 1d;\nINumber b = new UserDefinedNumber(...);\nvar c = a + b;\n a + b INumber + a double double UserDefinedNumber" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74496251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12735241/" ]
74,496,273
<p>I need to define a recursive function that takes two parameters (a list with names and an initial), and returns a new list with all the names that start with the initial.</p> <p>Right now I have got this code, and i don't know why it doesn't work:</p> <pre><code>def filter_names(names, initial): result = [] if names[0][0] == initial: result.append(names[0]) else: filter_names(names[1:], initial) return result </code></pre>
[ { "answer_id": 74496319, "author": "Samwise", "author_id": 3799759, "author_profile": "https://Stackoverflow.com/users/3799759", "pm_score": 1, "selected": false, "text": "result def filter_names(names, initial):\n if not names:\n return []\n return (\n [names[0]] if names[0][0] == initial else []\n ) + filter_names([1:], initial)\n" }, { "answer_id": 74496336, "author": "Nathaniel Ford", "author_id": 442945, "author_profile": "https://Stackoverflow.com/users/442945", "pm_score": 0, "selected": false, "text": "def filter_name(names, initial) -> list[str]:\n if 0 == len(names): # base case\n return [] \n else: # iterative case\n head = names[0] # The first element\n tail = names[1:] # Everything else\n tail_names = filter_name(tail, initial) # Get the result of the recursive call on 'everything else'\n if head[0] == initial: # Decide if the first element should change your result\n tail_names.append(head) # If so, modify your result\n return tail_names # Return it\n tail head result = [name for name in names if name[0] == initial]\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74496273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20543787/" ]
74,496,275
<p>I want to change my document direction and language but don't want to do that with js. how can I do that?</p> <p>Is there any config for that? how set document direction to RTL?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!doctype html&gt; &lt;html dir="rtl" lang="fa"&gt; &lt;!-- another tags --&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74496642, "author": "Mises", "author_id": 6310260, "author_profile": "https://Stackoverflow.com/users/6310260", "pm_score": 0, "selected": false, "text": "@vueuse/head useHead({\n htmlAttrs: { dir: 'rtl', lang: 'fa' },\n})\n" }, { "answer_id": 74497201, "author": "sadeq shahmoradi", "author_id": 17023430, "author_profile": "https://Stackoverflow.com/users/17023430", "pm_score": -1, "selected": true, "text": "nuxt.config.ts export default defineNuxtConfig({\n app: {\n head: {\n htmlAttrs: { dir: 'rtl', lang: 'fa' },\n },\n },\n})\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74496275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17023430/" ]
74,496,322
<p>I am new to stackoverflow so I am sorry if this question has been answered, what did find just led to more confusion. Been at this for hours.</p> <p>My issue is when I try to add multiple keys with the same value, I only get the last key and value to store inside of the object. I used if/else statements to try and achieve my goal. Here is my code.</p> <pre><code>var itemData = [{ category: 'fruit', itemName: 'apple', onSale: false }, { category: 'canned', itemName: 'beans', onSale: false }, { category: 'canned', itemName: 'corn', onSale: true }, { category: 'frozen', itemName: 'pizza', onSale: false }, { category: 'fruit', itemName: 'melon', onSale: true }, { category: 'canned', itemName: 'soup', onSale: false }, ]; let list = { } for (let i = 0; i &lt; items.length; i++) { if (items[i].category === 'fruit' &amp;&amp; items[i].onSale === false) { Object.assign(list, {fruit : [`${items[i].itemName}`]}) } else if (items[i].category === 'fruit' &amp;&amp; items[i].onSale === true) { list.fruit.push(`${items[i].itemName}${'($)'}`) } else if (items[i].category === 'canned' &amp;&amp; items[i].onSale === false) { Object.assign(list, {canned : [`${items[i].itemName}`,] }) list.canned.push(`${items[i].itemName}`) } } </code></pre> <p>console.log(list) shows</p> <pre><code>{ canned: [&quot;soup&quot;, &quot;soup&quot;], fruit: [&quot;apple&quot;, &quot;melon($)&quot;] } </code></pre> <p>but im expecting</p> <pre><code>{ canned: [&quot;beans&quot;, &quot;soup&quot;], fruit: [&quot;apple&quot;, &quot;melon($)&quot;] } </code></pre> <p>Any help would be appreciated. Thank you.</p>
[ { "answer_id": 74496642, "author": "Mises", "author_id": 6310260, "author_profile": "https://Stackoverflow.com/users/6310260", "pm_score": 0, "selected": false, "text": "@vueuse/head useHead({\n htmlAttrs: { dir: 'rtl', lang: 'fa' },\n})\n" }, { "answer_id": 74497201, "author": "sadeq shahmoradi", "author_id": 17023430, "author_profile": "https://Stackoverflow.com/users/17023430", "pm_score": -1, "selected": true, "text": "nuxt.config.ts export default defineNuxtConfig({\n app: {\n head: {\n htmlAttrs: { dir: 'rtl', lang: 'fa' },\n },\n },\n})\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74496322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13967544/" ]
74,496,333
<p>I'm just starting to explore the <a href="https://docs.databricks.com/dev-tools/api/latest/jobs.html#operation/JobsGet" rel="nofollow noreferrer">Databricks API</a>. I've created a <code>.netrc</code> file as described in <a href="https://docs.databricks.com/dev-tools/api/latest/authentication.html#netrc" rel="nofollow noreferrer">this doc</a> and am able to get the API to work with this for other operations like &quot;list clusters&quot; and &quot;list jobs&quot;. But when I try to query details of a particular job, it fails:</p> <pre class="lang-bash prettyprint-override"><code>$ curl --netrc -X GET https://&lt;my_workspace&gt;.cloud.databricks.com/api/2.0/jobs/get/?job_id=job-395565384955064-run-12345678 {&quot;error_code&quot;:&quot;INVALID_PARAMETER_VALUE&quot;,&quot;message&quot;:&quot;Job 0 does not exist.&quot;} </code></pre> <p>What am I doing wrong here?</p>
[ { "answer_id": 74501137, "author": "Alex Ott", "author_id": 18627, "author_profile": "https://Stackoverflow.com/users/18627", "pm_score": 2, "selected": true, "text": "395565384955064 / get /api/2.0/jobs/get?job_id=<job-ID>" }, { "answer_id": 74505820, "author": "Karthikeyan Rasipalay Durairaj", "author_id": 9599091, "author_profile": "https://Stackoverflow.com/users/9599091", "pm_score": 0, "selected": false, "text": "$ curl --netrc -X GET https://<my_workspace>.cloud.databricks.com/api/2.0/jobs/get/?job_id=job-395565384955064-run-12345678\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74496333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6629280/" ]
74,496,402
<p><strong>Hi there!</strong> </p> <p>So i had this figured out some years back, but i cant seem to find the tutorial again or any backup.</p> <p>Basically it was a simple login form that sends the user to a specified URL if the text is correct.</p> <p>Something like <strong>if input type text is &quot;custom text&quot; and input type password is &quot;custom text&quot; then input type submit button go to ahref &quot;custom url&quot;</strong></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div&gt; &lt;label for="username"&gt;Username:&lt;/label&gt; &lt;input type="text" id="username" name="username"&gt; &lt;/div&gt; &lt;p&gt;&lt;/p&gt; &lt;div&gt; &lt;label for="pass"&gt;Password:&lt;/label&gt; &lt;input type="password" id="pass" name="password" minlength="8" required=""&gt; &lt;/div&gt; &lt;input type="submit" value="Sign in"&gt;</code></pre> </div> </div> </p> <p>Funny because it was so basic and had no fancy CSS or javascript if I remember correctly. Again, I used it years go, can't really remember it properly.</p> <p>So it doesn't use any database or any other advanced stuff (for me), It used to work with more names and passwords, not just one, like demo name and demo pass.</p> <p>Think of it as a simple webpage locked with a password, if you want to access it, enter password, a custom word, if the work is correct, the button sends you to a custom url.</p> <p>I'm just gonna leave this here and hopefully you can help.</p> <p><strong>Thanks!</strong></p> <pre><code></code></pre> <p>I tried to make a basic, simple HTML form that people can login via custom name and password that if they insert correctly, the submit button will send them to a custom url page.</p>
[ { "answer_id": 74496520, "author": "XIz", "author_id": 20543055, "author_profile": "https://Stackoverflow.com/users/20543055", "pm_score": -1, "selected": false, "text": "<a>" }, { "answer_id": 74496660, "author": "Psychzor", "author_id": 20543858, "author_profile": "https://Stackoverflow.com/users/20543858", "pm_score": 1, "selected": true, "text": "<html>\n<head>\n<title>Javascript Login Form Validation</title>\n<!-- Include CSS File Here -->\n<link rel=\"stylesheet\" href=\"css/style.css\"/>\n<!-- Include JS File Here -->\n<script src=\"js/login.js\"></script>\n</head>\n<body>\n<div class=\"container\">\n<div class=\"main\">\n<form id=\"form_id\" method=\"post\" name=\"myform\">\n<label>USER:</label>\n<input type=\"text\" name=\"username\" id=\"username\"/>\n<label>PASS:</label>\n<input type=\"password\" name=\"password\" id=\"password\"/>\n<input type=\"button\" value=\"LOGIN\" id=\"submit\" onclick=\"validate()\"/>\n</form>\n\n<br>\n<br>\nusername is <b>asd</b> and password is <b>123</b>\n\n</div>\n</div>\n</body>\n</html>\n\n<!--THE JS JAVASCRIPT PART BELOW-->\n\n<head>\n<script>\n\nvar attempt = 4; // Variable to count number of attempts.\n// Below function Executes on click of login button.\nfunction validate() {\n var username = document.getElementById(\"username\").value;\n var password = document.getElementById(\"password\").value;\n if (username == \"asd\" && password == \"123\") {\n alert(\"Login successfully\");\n window.location = \"success.html\"; // Redirecting to other page.\n return false;\n } else {\n attempt--; // Decrementing by one.\n alert(\"You have left \" + attempt + \" attempt;\");\n // Disabling fields after 3 attempts.\n if (attempt == 0) {\n document.getElementById(\"username\").disabled = true;\n document.getElementById(\"password\").disabled = true;\n document.getElementById(\"submit\").disabled = true;\n return false;\n }\n }\n}\n</script>\n</head> " } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74496402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20543858/" ]
74,496,411
<p><strong>Context:</strong><br /> When running a regex match in Perl, <code>$1</code>, <code>$2</code> can be used as references to captured regex references from the match, similarly in Python <code>\g&lt;0&gt;</code>,<code>\g&lt;1&gt;</code> can be used</p> <p>Perl also has a <code>$+</code> special reference which refers to the captured group with highest numerical value</p> <p><strong>My question:</strong><br /> <strong>Does Python have an equivalent of <code>$+</code> ?</strong></p> <p>I tried <code>\g&lt;+&gt;</code> and tried looking in the documentation which only says:</p> <blockquote> <p>There’s also a syntax for referring to named groups as defined by the <code>(?P&lt;name&gt;...)</code> syntax. <code>\g&lt;name&gt;</code> will use the substring matched by the group named <code>name</code>, and <code>\g&lt;number&gt;</code> uses the corresponding group number. <code>\g&lt;2&gt;</code> is therefore equivalent to <code>\2</code>, but isn’t ambiguous in a replacement string such as <code>\g&lt;2&gt;0</code>. (<code>\20</code> would be interpreted as a reference to group 20, not a reference to group 2 followed by the literal character <code>'0'</code>.) The following substitutions are all equivalent, but use all three variations of the replacement string.</p> </blockquote>
[ { "answer_id": 74496750, "author": "ikegami", "author_id": 589924, "author_profile": "https://Stackoverflow.com/users/589924", "pm_score": 2, "selected": false, "text": "(foo|bar|baz)\n None import re\ns = 'bar4'\nm = re.search( r'foo([12])|bar([34])|baz([56])', s )\n[ g for g in m.groups() if g is not None ] # ['4']\n" }, { "answer_id": 74497500, "author": "zdim", "author_id": 4653379, "author_profile": "https://Stackoverflow.com/users/4653379", "pm_score": 3, "selected": true, "text": ">>> import regex\n>>> str = 'fza'\n>>> m = regex.search(r'(a)|(f)', str)\n>>> print(m.captures()[-1])\nf\n str a f a $+ (?|pattern) >>> import regex\n>>> m = regex.search(r'(?|(a)|(b))', 'zba')\n>>> m.group(1)\n'b'\n (?|(pA)|(pB)|(pC)) (?|...)" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74496411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9839769/" ]
74,496,425
<p><strong>Edit: 2022NOV21</strong></p> <p>How do we chain <code>df.col.str.split()</code> since this returns the split columns if expand = True I am trying to split a column after performing <code>.melt()</code>. If I use assign I end up using the original column and the melted column actually does not even exist.</p> <pre><code>df = pd.DataFrame().from_dict({ 'id' : [1,2,3,4], '2022_amt' : [10.1,20.2,30.3, 40.4], '2022_qty' : [10,20,30,40] }) df = ( df .melt( id_vars=['id'], value_vars=['2022_amt', '2022_qty'], var_name='fy', value_name='num' ) # can i chain any pd.Series.str.[METHOD] here # .assign( # year=df.fy.str.split('_', expand=True)[0], # t=df.fy.str.split('_', expand=True)[1] # ) ) # i can add the two columns in this way but can we use chain to expand dataframe df df[['year', 't']] = df.fy.str.split('_', expand=True) df = df.drop(columns = ['fy']) </code></pre>
[ { "answer_id": 74496468, "author": "chrslg", "author_id": 20037042, "author_profile": "https://Stackoverflow.com/users/20037042", "pm_score": 0, "selected": false, "text": "[0] .str [0] df=pd.DataFrame({'s':['abc-def|ghi', 'one-two|three']})\ndf.s.str.split('-').str[0]\n#0 abc\n#1 one\n#Name: s, dtype: object\n\ndf.s.str.split('-').str[1].str.split('|').str[0]\n#0 def\n#1 two\n#Name: s, dtype: object\n\ndf.s.str.split('-').str[1].str.split('|').str[1]\n#0 ghi\n#1 three\n#Name: s, dtype: object\n .str .str [..] .str" }, { "answer_id": 74524717, "author": "sammywemmy", "author_id": 7175713, "author_profile": "https://Stackoverflow.com/users/7175713", "pm_score": 2, "selected": true, "text": "expand (df\n.melt(id_vars='id',var_name='fy',value_name='num')\nassign(year = lambda df: df.fy.str.split('_').str[0],\n t = lambda df: df.fy.str.split('_').str[1])\n)\n\n id fy num year t\n0 1 2022_amt 10.1 2022 amt\n1 2 2022_amt 20.2 2022 amt\n2 3 2022_amt 30.3 2022 amt\n3 4 2022_amt 40.4 2022 amt\n4 1 2022_qty 10.0 2022 qty\n5 2 2022_qty 20.0 2022 qty\n6 3 2022_qty 30.0 2022 qty\n7 4 2022_qty 40.0 2022 qty\n pd.stack df = df.set_index('id')\ndf.columns = df.columns.str.split('_', expand = True)\ndf.columns.names = ['year', 't']\ndf.stack(['year', 't']).reset_index(name='num')\n\n id year t num\n0 1 2022 amt 10.1\n1 1 2022 qty 10.0\n2 2 2022 amt 20.2\n3 2 2022 qty 20.0\n4 3 2022 amt 30.3\n5 3 2022 qty 30.0\n6 4 2022 amt 40.4\n7 4 2022 qty 40.0\n pivot_longer pyjanitor # pip install pyjanitor\nimport pandas as pd\nimport janitor as jn\ndf.pivot_longer(index = 'id', names_to = ('year','t'), names_sep = '_')\n\n id year t value\n0 1 2022 amt 10.1\n1 2 2022 amt 20.2\n2 3 2022 amt 30.3\n3 4 2022 amt 40.4\n4 1 2022 qty 10.0\n5 2 2022 qty 20.0\n6 3 2022 qty 30.0\n7 4 2022 qty 40.0\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74496425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6884883/" ]