qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,648,730
<p>Currently in day 15 of Angela's 100 days of python. What I understood from all the exercises and project is that variables outside the function cannot be used inside a function unless it is passed as an argument or you input &quot;global&quot; inside the function.</p> <pre><code>MENU = { &quot;espresso&quot;: { &quot;ingredients&quot;: { &quot;water&quot;: 50, &quot;coffee&quot;: 18, }, &quot;cost&quot;: 1.5, }, &quot;latte&quot;: { &quot;ingredients&quot;: { &quot;water&quot;: 200, &quot;milk&quot;: 150, &quot;coffee&quot;: 24, }, &quot;cost&quot;: 2.5, }, &quot;cappuccino&quot;: { &quot;ingredients&quot;: { &quot;water&quot;: 250, &quot;milk&quot;: 100, &quot;coffee&quot;: 24, }, &quot;cost&quot;: 3.0, } } profit = 0 resources = { &quot;water&quot;: 300, &quot;milk&quot;: 200, &quot;coffee&quot;: 100, } def is_resource_sufficient(order_ingredients): &quot;&quot;&quot;Returns True when order can be made, False if ingredients are insufficient.&quot;&quot;&quot; for item in order_ingredients: if order_ingredients[item] &gt; resources[item]: print(f&quot;​Sorry there is not enough {item}.&quot;) return False return True def process_coins(): &quot;&quot;&quot;Returns the total calculated from coins inserted.&quot;&quot;&quot; print(&quot;Please insert coins.&quot;) total = int(input(&quot;how many quarters?: &quot;)) * 0.25 total += int(input(&quot;how many dimes?: &quot;)) * 0.1 total += int(input(&quot;how many nickles?: &quot;)) * 0.05 total += int(input(&quot;how many pennies?: &quot;)) * 0.01 return total def is_transaction_successful(money_received, drink_cost): &quot;&quot;&quot;Return True when the payment is accepted, or False if money is insufficient.&quot;&quot;&quot; if money_received &gt;= drink_cost: change = round(money_received - drink_cost, 2) print(f&quot;Here is ${change} in change.&quot;) global profit profit += drink_cost return True else: print(&quot;Sorry that's not enough money. Money refunded.&quot;) return False def make_coffee(drink_name, order_ingredients): &quot;&quot;&quot;Deduct the required ingredients from the resources.&quot;&quot;&quot; for item in order_ingredients: resources[item] -= order_ingredients[item] print(f&quot;Here is your {drink_name} ☕️. Enjoy!&quot;) is_on = True while is_on: choice = input(&quot;​What would you like? (espresso/latte/cappuccino): &quot;) if choice == &quot;off&quot;: is_on = False elif choice == &quot;report&quot;: print(f&quot;Water: {resources['water']}ml&quot;) print(f&quot;Milk: {resources['milk']}ml&quot;) print(f&quot;Coffee: {resources['coffee']}g&quot;) print(f&quot;Money: ${profit}&quot;) else: drink = MENU[choice] if is_resource_sufficient(drink[&quot;ingredients&quot;]): payment = process_coins() if is_transaction_successful(payment, drink[&quot;cost&quot;]): make_coffee(choice, drink[&quot;ingredients&quot;]) </code></pre> <p>I tried to look at her solution and saw that one of her function is using the dictionary resources that is not declared inside the function nor passed as an argument. I am not very good in english that's why I am having a hard time searching in the internet what I specifically want to understand. Can someone enlighten me with this topic please.</p> <p>NOTE: it is not advised to use global</p> <p>My code:</p> <p>(my understanding is that you can never use variables outside the function if it is not either set to global or passed as an argument)</p> <pre><code>def use_resources(user_order, machine_menu, machine_resources): &quot;&quot;&quot;Deduct the resources needed for the user's order and returns the current resources of the machine after the user's order. &quot;&quot;&quot; for menu_ingredients_key in machine_menu[user_order][&quot;ingredients&quot;]: # print(menu_ingredients_key) # REPRESENT KEY water, coffee # print(menu[order][&quot;ingredients&quot;][menu_ingredients_key]) # REPRESENT VALUES [50,18] for resources_key in machine_resources: if resources_key == menu_ingredients_key: machine_resources[menu_ingredients_key] -= menu[user_order][&quot;ingredients&quot;][menu_ingredients_key] print(f&quot;Here is your {user_order} ☕. Enjoy! Come again :)&quot;) </code></pre> <p>How can the function use the resources that was declared outside the function and not passed as an argument?</p> <pre><code>def make_coffee(drink_name, order_ingredients): &quot;&quot;&quot;Deduct the required ingredients from the resources.&quot;&quot;&quot; for item in order_ingredients: resources[item] -= order_ingredients[item] print(f&quot;Here is your {drink_name} ☕️. Enjoy!&quot;) </code></pre>
[ { "answer_id": 74648889, "author": "tdelaney", "author_id": 642070, "author_profile": "https://Stackoverflow.com/users/642070", "pm_score": 1, "selected": true, "text": "resources = {\n \"water\": 300,\n \"milk\": 200,\n \"coffee\": 100,\n}\n\ndef test(item, val):\n resources[item] -= val\n\ntest(\"water\", 5)\n test resources resources global def test2():\n var1 = \"foo\"\n print(var2)\n global var3\n var3 = \"baz\"\n var1 var2 var3 global" }, { "answer_id": 74651785, "author": "Kejer", "author_id": 18126961, "author_profile": "https://Stackoverflow.com/users/18126961", "pm_score": 1, "selected": false, "text": "my_list = [1, 2, 3]\nprint(id(my_list), my_list)\nmy_list += [4] # my_list is the same list object\nprint(id(my_list), my_list)\n \nprint()\n \nmy_int = 123\nprint(id(my_int), my_int)\nmy_int += 1 # my_int is a new integer object\nprint(id(my_int), my_int)\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74648730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18126961/" ]
74,648,743
<p>What is the correct way to represent this structure in JSON<br /> Its Array of strings, with identifiers (A is identifier Printer is the array item)<br /> then there is nested list of strings, with identifiers</p> <pre><code>A Printer A0010 Not printing A0020 Out of ink A0030 No power A0040 Noise A0300 Feedback A0500 Other B PC Issues B0010 No power B0020 BSOD B0030 Virus related B0300 Feedback B0500 Other </code></pre> <p>Thank you for your help</p>
[ { "answer_id": 74648874, "author": "Kyle Wilson", "author_id": 11653689, "author_profile": "https://Stackoverflow.com/users/11653689", "pm_score": 2, "selected": true, "text": "const json = {\n data: [{\n identifier: 'A',\n itemType: 'Printer',\n error: [\n {\n 'A0010': 'Not printing'\n },\n {\n 'A0020': 'Out of ink'\n },\n {\n 'A0030': 'No power',\n },\n {\n 'A0040': 'Noise',\n },\n {\n 'A0300': 'Feedback',\n },\n {\n 'A0500': 'Other'\n }\n\n ]\n },\n {\n identifier: 'B',\n itemType: 'PC Issues',\n error: [\n {\n 'B0010': 'No power'\n },\n {\n 'B0020': 'BSOD',\n },\n {\n 'B0030': 'Virus related'\n }, {\n 'B0300': 'Feedback'\n },\n {\n 'B0500': 'Other'\n },\n ]\n }\n ]\n}\n\n\n" }, { "answer_id": 74648941, "author": "Jeremy Batchelor", "author_id": 13977539, "author_profile": "https://Stackoverflow.com/users/13977539", "pm_score": 0, "selected": false, "text": "var a = {\n \"Printer\":[ \n {\n \"identifier\" : \"A0010\",\n \"reason\" : \"Not printing\"\n }, \n {\n \"identifier\" : \"A0020\",\n \"reason\" : \"Out of ink\"\n },\n {\n \"identifier\" : \"A0030\",\n \"reason\" : \"No power\"\n },\n {\n \"identifier\" : \"A0040\",\n \"reason\" : \"Noise\"\n },\n {\n \"identifier\" : \"A0300\",\n \"reason\" : \"Feedback\"\n },\n {\n \"identifier\" : \"A0500\",\n \"reason\" : \"Other\"\n }]\n}\nvar b = {\n \"PC Issues\":[ \n {\n \"identifier\" : \"B0010\",\n \"reason\" : \"No power\"\n }, \n {\n \"identifier\" : \"B0020\",\n \"reason\" : \"BSOD\"\n },\n {\n \"identifier\" : \"B0030\",\n \"reason\" : \"Virus related\"\n },\n {\n \"identifier\" : \"B0300\",\n \"reason\" : \"Feedback\"\n },\n {\n \"identifier\" : \"B0500\",\n \"reason\" : \"Other\"\n }]\n}\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74648743", "https://Stackoverflow.com", "https://Stackoverflow.com/users/648026/" ]
74,648,762
<p>I have a following block of code:</p> <pre><code>import json from types import SimpleNamespace data=json.dumps( { &quot;update_id&quot;: 992108054, &quot;message&quot;: { &quot;delete_chat_photo&quot;: False, &quot;new_chat_members&quot;: [], &quot;date&quot;: 1669931418, &quot;photo&quot;: [], &quot;entities&quot;: [], &quot;message_id&quot;: 110, &quot;group_chat_created&quot;: False, &quot;caption_entities&quot;: [], &quot;new_chat_photo&quot;: [], &quot;supergroup_chat_created&quot;: False, &quot;chat&quot;: { &quot;type&quot;: &quot;private&quot;, &quot;first_name&quot;: &quot;test_name&quot;, &quot;id&quot;: 134839552, &quot;last_name&quot;: &quot;test_l_name&quot;, &quot;username&quot;: &quot;test_username&quot; }, &quot;channel_chat_created&quot;: False, &quot;text&quot;: &quot;test_text&quot;, &quot;from&quot;: { &quot;last_name&quot;: &quot;test_l_name&quot;, &quot;is_bot&quot;: False, &quot;username&quot;: &quot;test_username&quot;, &quot;id&quot;: 134839552, &quot;first_name&quot;: &quot;test_name&quot;, &quot;language_code&quot;: &quot;en&quot; } } }) x = json.loads(data, object_hook=lambda d: SimpleNamespace(**d)) print(x.message.text, x.message.chat ) </code></pre> <p>Which works fine. However, when I add</p> <pre><code>print(x.message.from) </code></pre> <p>I get an error:</p> <pre><code> File &quot;&lt;ipython-input-179-dec1b9f9affa&gt;&quot;, line 1 print(x.message.from) ^ SyntaxError: invalid syntax </code></pre> <p>Could you please help me? How can I access fields inside 'from' block?</p>
[ { "answer_id": 74648874, "author": "Kyle Wilson", "author_id": 11653689, "author_profile": "https://Stackoverflow.com/users/11653689", "pm_score": 2, "selected": true, "text": "const json = {\n data: [{\n identifier: 'A',\n itemType: 'Printer',\n error: [\n {\n 'A0010': 'Not printing'\n },\n {\n 'A0020': 'Out of ink'\n },\n {\n 'A0030': 'No power',\n },\n {\n 'A0040': 'Noise',\n },\n {\n 'A0300': 'Feedback',\n },\n {\n 'A0500': 'Other'\n }\n\n ]\n },\n {\n identifier: 'B',\n itemType: 'PC Issues',\n error: [\n {\n 'B0010': 'No power'\n },\n {\n 'B0020': 'BSOD',\n },\n {\n 'B0030': 'Virus related'\n }, {\n 'B0300': 'Feedback'\n },\n {\n 'B0500': 'Other'\n },\n ]\n }\n ]\n}\n\n\n" }, { "answer_id": 74648941, "author": "Jeremy Batchelor", "author_id": 13977539, "author_profile": "https://Stackoverflow.com/users/13977539", "pm_score": 0, "selected": false, "text": "var a = {\n \"Printer\":[ \n {\n \"identifier\" : \"A0010\",\n \"reason\" : \"Not printing\"\n }, \n {\n \"identifier\" : \"A0020\",\n \"reason\" : \"Out of ink\"\n },\n {\n \"identifier\" : \"A0030\",\n \"reason\" : \"No power\"\n },\n {\n \"identifier\" : \"A0040\",\n \"reason\" : \"Noise\"\n },\n {\n \"identifier\" : \"A0300\",\n \"reason\" : \"Feedback\"\n },\n {\n \"identifier\" : \"A0500\",\n \"reason\" : \"Other\"\n }]\n}\nvar b = {\n \"PC Issues\":[ \n {\n \"identifier\" : \"B0010\",\n \"reason\" : \"No power\"\n }, \n {\n \"identifier\" : \"B0020\",\n \"reason\" : \"BSOD\"\n },\n {\n \"identifier\" : \"B0030\",\n \"reason\" : \"Virus related\"\n },\n {\n \"identifier\" : \"B0300\",\n \"reason\" : \"Feedback\"\n },\n {\n \"identifier\" : \"B0500\",\n \"reason\" : \"Other\"\n }]\n}\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74648762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7829214/" ]
74,648,818
<p>I am trying to scrape data from <a href="https://openbilanci.it/armonizzati/bilanci/veglio-comune-bi/entrate/dettaglio?year=2021&amp;type=preventivo" rel="nofollow noreferrer">this website</a>. To be specific, I want to scrape all the data from the following:</p> <pre><code>var bilancio_tree = [{&quot;slug&quot;: &quot;pcox-quadro-2-11&quot;, &quot;label&quot;: &quot;Totale generale delle Entrate&quot;, &quot;values&quot;: [{&quot;2021&quot;: {&quot;abs&quot;: 1659238.91, &quot;pc&quot;: 3463.96432150313}}, {&quot;2022&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2023&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}], &quot;children&quot;: []}, {&quot;slug&quot;: &quot;pcox-quadro-2-2&quot;, &quot;label&quot;: &quot;Entrate correnti di natura tributaria, contributiva e perequativa&quot;, &quot;values&quot;: [{&quot;2021&quot;: {&quot;abs&quot;: 618720.93, &quot;pc&quot;: 1291.69296450939}}, {&quot;2022&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2023&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}], &quot;children&quot;: [{&quot;slug&quot;: &quot;pcox-quadro-2-2-16&quot;, &quot;label&quot;: &quot;Imposte,tasse e proventi assimilati&quot;, &quot;values&quot;: [{&quot;2021&quot;: {&quot;abs&quot;: 461222.66, &quot;pc&quot;: 962.886555323591}}, {&quot;2022&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2023&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}]}, {&quot;slug&quot;: &quot;pcox-quadro-2-2-31&quot;, &quot;label&quot;: &quot;Compartecipazioni di tributi&quot;, &quot;values&quot;: [{&quot;2021&quot;: {&quot;abs&quot;: 2231.31, &quot;pc&quot;: 4.65826722338205}}, {&quot;2022&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2023&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}]}, {&quot;slug&quot;: &quot;pcox-quadro-2-2-41&quot;, &quot;label&quot;: &quot;Fondi perequativi da Amministrazioni Centrali&quot;, &quot;values&quot;: [{&quot;2021&quot;: {&quot;abs&quot;: 155266.96, &quot;pc&quot;: 324.148141962422}}, {&quot;2022&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2023&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}]}, {&quot;slug&quot;: &quot;pcox-quadro-2-2-51&quot;, &quot;label&quot;: &quot;Fondi perequativi dalla Regione o Provincia autonoma&quot;, &quot;values&quot;: [{&quot;2021&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2022&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2023&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}]}]}, {&quot;slug&quot;: &quot;pcox-quadro-2-3&quot;, &quot;label&quot;: &quot;Trasferimenti correnti&quot;, &quot;values&quot;: [{&quot;2021&quot;: {&quot;abs&quot;: 114907.44, &quot;pc&quot;: 239.890271398747}}, {&quot;2022&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2023&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}], &quot;children&quot;: [{&quot;slug&quot;: &quot;pcox-quadro-2-3-71&quot;, &quot;label&quot;: &quot;Trasferimenti correnti da Amministrazioni pubbliche -&quot;, &quot;values&quot;: [{&quot;2021&quot;: {&quot;abs&quot;: 91755.54, &quot;pc&quot;: 191.556450939457}}, {&quot;2022&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2023&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}]}, {&quot;slug&quot;: &quot;pcox-quadro-2-3-81&quot;, &quot;label&quot;: &quot;Trasferimenti correnti da Famiglie&quot;, &quot;values&quot;: [{&quot;2021&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2022&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2023&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}]}, {&quot;slug&quot;: &quot;pcox-quadro-2-3-91&quot;, &quot;label&quot;: &quot;Trasferimenti correnti da Imprese&quot;, &quot;values&quot;: [{&quot;2021&quot;: {&quot;abs&quot;: 23151.9, &quot;pc&quot;: 48.3338204592902}}, {&quot;2022&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2023&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}]}, {&quot;slug&quot;: &quot;pcox-quadro-2-3-101&quot;, &quot;label&quot;: &quot;Trasferimenti correnti da Istituzioni Sociali Private&quot;, &quot;values&quot;: [{&quot;2021&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2022&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2023&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}]}, {&quot;slug&quot;: &quot;pcox-quadro-2-3-111&quot;, &quot;label&quot;: &quot;Trasferimenti correnti dall'Unione europea e dal Resto del Mondo- previsione di cassa&quot;, &quot;values&quot;: [{&quot;2021&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2022&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2023&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}]}]}, {&quot;slug&quot;: &quot;pcox-quadro-2-4&quot;, &quot;label&quot;: &quot;Entrate extratributarie&quot;, &quot;values&quot;: [{&quot;2021&quot;: {&quot;abs&quot;: 98243.25, &quot;pc&quot;: 205.100730688935}}, {&quot;2022&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2023&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}], &quot;children&quot;: [{&quot;slug&quot;: &quot;pcox-quadro-2-4-131&quot;, &quot;label&quot;: &quot;Vendita di beni e servizi e proventi derivanti dalla gestione dei beni&quot;, &quot;values&quot;: [{&quot;2021&quot;: {&quot;abs&quot;: 84043.78, &quot;pc&quot;: 175.456743215031}}, {&quot;2022&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2023&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}]}, {&quot;slug&quot;: &quot;pcox-quadro-2-4-141&quot;, &quot;label&quot;: &quot;Proventi derivanti dall'attivit\u00e0 di controllo e repressione delle irregolarit\u00e0 e degli illeciti&quot;, &quot;values&quot;: [{&quot;2021&quot;: {&quot;abs&quot;: 1000.0, &quot;pc&quot;: 2.08768267223382}}, {&quot;2022&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2023&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}]}, {&quot;slug&quot;: &quot;pcox-quadro-2-4-151&quot;, &quot;label&quot;: &quot;Interessi attivi&quot;, &quot;values&quot;: [{&quot;2021&quot;: {&quot;abs&quot;: 100.0, &quot;pc&quot;: 0.208768267223382}}, {&quot;2022&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2023&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}]}, {&quot;slug&quot;: &quot;pcox-quadro-2-4-161&quot;, &quot;label&quot;: &quot;Altre entrate da redditi da capitale&quot;, &quot;values&quot;: [{&quot;2021&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2022&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2023&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}]}, {&quot;slug&quot;: &quot;pcox-quadro-2-4-171&quot;, &quot;label&quot;: &quot;Rimborsi e altre entrate correnti&quot;, &quot;values&quot;: [{&quot;2021&quot;: {&quot;abs&quot;: 13099.47, &quot;pc&quot;: 27.3475365344468}}, {&quot;2022&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2023&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}]}]}, {&quot;slug&quot;: &quot;pcox-quadro-2-5&quot;, &quot;label&quot;: &quot;Entrate in conto capitale&quot;, &quot;values&quot;: [{&quot;2021&quot;: {&quot;abs&quot;: 451082.56, &quot;pc&quot;: 941.717244258873}}, {&quot;2022&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2023&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}], &quot;children&quot;: [{&quot;slug&quot;: &quot;pcox-quadro-2-5-191&quot;, &quot;label&quot;: &quot;Tributi in conto capitale&quot;, &quot;values&quot;: [{&quot;2021&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2022&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2023&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}]}, {&quot;slug&quot;: &quot;pcox-quadro-2-5-201&quot;, &quot;label&quot;: &quot;Contributi agli investimenti&quot;, &quot;values&quot;: [{&quot;2021&quot;: {&quot;abs&quot;: 316616.62, &quot;pc&quot;: 660.99503131524}}, {&quot;2022&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2023&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}]}, {&quot;slug&quot;: &quot;pcox-quadro-2-5-211&quot;, &quot;label&quot;: &quot;Altri trasferimenti in conto capitale&quot;, &quot;values&quot;: [{&quot;2021&quot;: {&quot;abs&quot;: 123965.94, &quot;pc&quot;: 258.801544885177}}, {&quot;2022&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2023&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}]}, {&quot;slug&quot;: &quot;pcox-quadro-2-5-221&quot;, &quot;label&quot;: &quot;Entrate da alienazione di beni materiali e immateriali&quot;, &quot;values&quot;: [{&quot;2021&quot;: {&quot;abs&quot;: 8500.0, &quot;pc&quot;: 17.7453027139875}}, {&quot;2022&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2023&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}]}, {&quot;slug&quot;: &quot;pcox-quadro-2-5-231&quot;, &quot;label&quot;: &quot;Altre entrate in conto capitale&quot;, &quot;values&quot;: [{&quot;2021&quot;: {&quot;abs&quot;: 2000.0, &quot;pc&quot;: 4.17536534446764}}, {&quot;2022&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2023&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}]}]}, {&quot;slug&quot;: &quot;pcox-quadro-2-6&quot;, &quot;label&quot;: &quot;Entrate da riduzione di attivita\u0300 finanziarie&quot;, &quot;values&quot;: [{&quot;2021&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2022&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2023&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}], &quot;children&quot;: [{&quot;slug&quot;: &quot;pcox-quadro-2-6-251&quot;, &quot;label&quot;: &quot;Alienazione di attivit\u00e0 finanziarie&quot;, &quot;values&quot;: [{&quot;2021&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2022&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2023&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}]}, {&quot;slug&quot;: &quot;pcox-quadro-2-6-261&quot;, &quot;label&quot;: &quot;Riscossione crediti di breve termine&quot;, &quot;values&quot;: [{&quot;2021&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2022&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2023&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}]}, {&quot;slug&quot;: &quot;pcox-quadro-2-6-266&quot;, &quot;label&quot;: &quot;Riscossione crediti di medio&quot;, &quot;values&quot;: [{&quot;2021&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2022&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2023&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}]}, {&quot;slug&quot;: &quot;pcox-quadro-2-6-271&quot;, &quot;label&quot;: &quot;Altre entrate per riduzione di attivit\u00e0 finanziarie&quot;, &quot;values&quot;: [{&quot;2021&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2022&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2023&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}]}]}, {&quot;slug&quot;: &quot;pcox-quadro-2-7&quot;, &quot;label&quot;: &quot;Accensione prestiti&quot;, &quot;values&quot;: [{&quot;2021&quot;: {&quot;abs&quot;: 522.42, &quot;pc&quot;: 1.09064718162839}}, {&quot;2022&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2023&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}], &quot;children&quot;: [{&quot;slug&quot;: &quot;pcox-quadro-2-7-291&quot;, &quot;label&quot;: &quot;Emissione di titoli obbligazionari&quot;, &quot;values&quot;: [{&quot;2021&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2022&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2023&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}]}, {&quot;slug&quot;: &quot;pcox-quadro-2-7-301&quot;, &quot;label&quot;: &quot;Accensione prestiti a breve termine&quot;, &quot;values&quot;: [{&quot;2021&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2022&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2023&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}]}, {&quot;slug&quot;: &quot;pcox-quadro-2-7-311&quot;, &quot;label&quot;: &quot;Accensione mutui e altri finanziamenti a medio lungo termine&quot;, &quot;values&quot;: [{&quot;2021&quot;: {&quot;abs&quot;: 522.42, &quot;pc&quot;: 1.09064718162839}}, {&quot;2022&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2023&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}]}, {&quot;slug&quot;: &quot;pcox-quadro-2-7-321&quot;, &quot;label&quot;: &quot;Altre forme di indebitamento&quot;, &quot;values&quot;: [{&quot;2021&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2022&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2023&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}]}]}, {&quot;slug&quot;: &quot;pcox-quadro-2-8&quot;, &quot;label&quot;: &quot;Anticipazioni da istituto tesoriere/cassiere&quot;, &quot;values&quot;: [{&quot;2021&quot;: {&quot;abs&quot;: 100000.0, &quot;pc&quot;: 208.768267223382}}, {&quot;2022&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2023&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}], &quot;children&quot;: [{&quot;slug&quot;: &quot;pcox-quadro-2-8-336&quot;, &quot;label&quot;: &quot;Anticipazione da istituto tesoriere/cassiere&quot;, &quot;values&quot;: [{&quot;2021&quot;: {&quot;abs&quot;: 100000.0, &quot;pc&quot;: 208.768267223382}}, {&quot;2022&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2023&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}]}]}, {&quot;slug&quot;: &quot;pcox-quadro-2-9&quot;, &quot;label&quot;: &quot;Entrate per conto terzi e partite di giro&quot;, &quot;values&quot;: [{&quot;2021&quot;: {&quot;abs&quot;: 275762.31, &quot;pc&quot;: 575.704196242171}}, {&quot;2022&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2023&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}], &quot;children&quot;: [{&quot;slug&quot;: &quot;pcox-quadro-2-9-351&quot;, &quot;label&quot;: &quot;Entrate per partite di giro&quot;, &quot;values&quot;: [{&quot;2021&quot;: {&quot;abs&quot;: 200719.26, &quot;pc&quot;: 419.038121085595}}, {&quot;2022&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2023&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}]}, {&quot;slug&quot;: &quot;pcox-quadro-2-9-361&quot;, &quot;label&quot;: &quot;Entrate per conto terzi&quot;, &quot;values&quot;: [{&quot;2021&quot;: {&quot;abs&quot;: 75043.05, &quot;pc&quot;: 156.666075156576}}, {&quot;2022&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}, {&quot;2023&quot;: {&quot;abs&quot;: 0.0, &quot;pc&quot;: 0.0}}]}]}]; </code></pre> <p>I am trying to build a dataset of the following form (with all the variables listed above):</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Totale generale delle Entrate Total</th> <th>Totale generale delle Entrate PC</th> </tr> </thead> <tbody> <tr> <td>1659238.91</td> <td>3463.96</td> </tr> </tbody> </table> </div> <p>Right now, I have the following script:</p> <pre><code>import requests from bs4 import BeautifulSoup import csv import json import re URL = &quot;https://openbilanci.it/armonizzati/bilanci/veglio-comune-bi/entrate/dettaglio?year=2021&amp;type=preventivo&quot; r = requests.get(URL) soup = BeautifulSoup(r.content, 'html.parser') data = soup.find_all(&quot;script&quot;)[19].string p = re.compile('var bilancio_tree = (.*?);') m = p.match(data) stocks = json.loads(m.groups()[0]) for stock in stocks: print(stock) </code></pre> <p>But, it's not working. I'm new to using python for web scraping, any help would be much appreciated!</p>
[ { "answer_id": 74648874, "author": "Kyle Wilson", "author_id": 11653689, "author_profile": "https://Stackoverflow.com/users/11653689", "pm_score": 2, "selected": true, "text": "const json = {\n data: [{\n identifier: 'A',\n itemType: 'Printer',\n error: [\n {\n 'A0010': 'Not printing'\n },\n {\n 'A0020': 'Out of ink'\n },\n {\n 'A0030': 'No power',\n },\n {\n 'A0040': 'Noise',\n },\n {\n 'A0300': 'Feedback',\n },\n {\n 'A0500': 'Other'\n }\n\n ]\n },\n {\n identifier: 'B',\n itemType: 'PC Issues',\n error: [\n {\n 'B0010': 'No power'\n },\n {\n 'B0020': 'BSOD',\n },\n {\n 'B0030': 'Virus related'\n }, {\n 'B0300': 'Feedback'\n },\n {\n 'B0500': 'Other'\n },\n ]\n }\n ]\n}\n\n\n" }, { "answer_id": 74648941, "author": "Jeremy Batchelor", "author_id": 13977539, "author_profile": "https://Stackoverflow.com/users/13977539", "pm_score": 0, "selected": false, "text": "var a = {\n \"Printer\":[ \n {\n \"identifier\" : \"A0010\",\n \"reason\" : \"Not printing\"\n }, \n {\n \"identifier\" : \"A0020\",\n \"reason\" : \"Out of ink\"\n },\n {\n \"identifier\" : \"A0030\",\n \"reason\" : \"No power\"\n },\n {\n \"identifier\" : \"A0040\",\n \"reason\" : \"Noise\"\n },\n {\n \"identifier\" : \"A0300\",\n \"reason\" : \"Feedback\"\n },\n {\n \"identifier\" : \"A0500\",\n \"reason\" : \"Other\"\n }]\n}\nvar b = {\n \"PC Issues\":[ \n {\n \"identifier\" : \"B0010\",\n \"reason\" : \"No power\"\n }, \n {\n \"identifier\" : \"B0020\",\n \"reason\" : \"BSOD\"\n },\n {\n \"identifier\" : \"B0030\",\n \"reason\" : \"Virus related\"\n },\n {\n \"identifier\" : \"B0300\",\n \"reason\" : \"Feedback\"\n },\n {\n \"identifier\" : \"B0500\",\n \"reason\" : \"Other\"\n }]\n}\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74648818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19738691/" ]
74,648,858
<p>Say I have a code snippet like so:</p> <pre class="lang-ml prettyprint-override"><code>type 'a mylist = | Nil | Cons of 'a * 'a mylist let rec last l = match l with | Nil -&gt; None | Cons(x, Nil) -&gt; Some(x) | Cons(x, xs) -&gt; last xs </code></pre> <p>Obviously, this pattern matches over the constructors of <code>mylist</code> - <code>Nil</code> and <code>Cons</code>. My question is how you'd go about implementing something like this. You can't just feed values to <code>Cons</code> until you find some that match <code>l</code>, so i'm assuming the OCaml compiler implements something like a &quot;reverse constructor&quot; that takes a value of type <code>mylist</code> and attempts to turn it into the constituent parts?</p> <p>For example, in psudo-ocaml:</p> <pre class="lang-ml prettyprint-override"><code>type 'a mylist = | Nil | Cons of 'a * 'a mylist Cons : ('a * 'a mylist) -&gt; 'a mylist UnCons : 'a mylist -&gt; ('a mylist * 'a) option </code></pre> <p>Is this correct, or does it take another approach? What about for, say, haskell or sml?</p>
[ { "answer_id": 74649557, "author": "amalloy", "author_id": 625403, "author_profile": "https://Stackoverflow.com/users/625403", "pm_score": 3, "selected": false, "text": "type {-# LANGUAGE RankNTypes #-}\n\nimport Prelude hiding (head, tail, last)\n\nnewtype List a = List\n (forall r. -- Client can choose any return type\n r -> -- Value to return in case of Nil\n (a -> List a -> r) -> -- Called with Cons's two fields\n r) -- The result\n\nnil :: List a\nnil = List (\\n c -> n)\n\ncons :: a -> List a -> List a\ncons h t = List (\\n c -> c h t)\n\nhead :: List a -> Maybe a\nhead (List list) = list Nothing (\\h t -> Just h)\n\ntail :: List a -> Maybe (List a)\ntail (List list) = list Nothing (\\h t -> Just t)\n nil cons head tail nil cons head tail last last :: List a -> Maybe a\nlast (List list) = list Nothing (\\h t -> Just (go h t))\n where go :: a -> List a -> a\n go curr (List rest) = rest curr go\n" }, { "answer_id": 74653861, "author": "octachron", "author_id": 7369366, "author_profile": "https://Stackoverflow.com/users/7369366", "pm_score": 3, "selected": false, "text": "1 [|1;2|] type t =\n | A\n | B\n | C of int\n | D of int\n Obj Obj.(is_int @@ repr A)\n A 0 assert (Obj.repr A = Obj.repr 0)\n C 1 assert Obj.(\n tag @@ repr (C 1) = 0\n && field (repr (C 1)) 0 = repr 1\n)\n type 'a mylist = | Nil | Cons of 'a * 'a mylist\n\nlet rec last l =\n match l with\n | Nil -> None\n | Cons(x, Nil) -> Some(x)\n | Cons(x, xs) -> last xs\n Nil 0 None Nil 0 Some (first_field of the argument) last (second_field of the argument) ocamlc -dlambda (letrec\n (last/271\n (function l/272\n (if l/272\n (if (field_imm 1 l/272) (apply last/271 (field_imm 1 l/272))\n (makeblock 0 (field_imm 0 l/272)))\n 0)))\n if l/272 field_imm 1 l/272 l/2 match" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74648858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13967062/" ]
74,648,911
<p>How do I make the text to be justified but at the same lenght as the image above it? I tried putting it inside a div, but it's not working, <a href="https://i.stack.imgur.com/pHSNT.png" rel="nofollow noreferrer">The text looks like this</a></p> <p>Any tip to fix this?</p> <p>On the code posted, I used a simple web image so it can be seen an image which helps to understand the problem. I hope that if someone can make a solution that works with that image, also works if I change the images, or if I need to keep the same size, please tell me to avoid making mistakes</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>body{ text-align: center; background-color: #9e0819; font-family: 'Roboto', sans-serif; color: white; margin: 0; } #notifoto{ border-radius: 5px; margin-top: 10px; } #Not-inn{ /* float: left; */ display: flex; width: 100%; align-content: flex-start; justify-content: center; flex-wrap: wrap; } #opnoticias{ text-decoration: none; color: white; margin: 25px; border-radius: 10px; box-shadow: 0 1px 4px rgba(255, 255, 255,1.12); display: inline-block; height: 250px; width: 250px; text-align: center; align-items: center; align-content: center; justify-content: center; transition-duration: 0.25s; transition-timing-function: ease; } #opnoticias:hover{ padding: 20px; } #notitext{ text-align: justify; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;meta http-equiv="X-UA-Compatible" content="IE=edge"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt; &lt;link rel="preconnect" href="https://fonts.googleapis.com"&gt; &lt;link rel="preconnect" href="https://fonts.gstatic.com" crossorigin&gt; &lt;link href="https://fonts.googleapis.com/css2?family=Roboto&amp;display=swap" rel="stylesheet"&gt; &lt;link rel="stylesheet" href="CAFestilos.css"&gt; &lt;title&gt;HuancayoCAF&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="Noticias"&gt; &lt;h2&gt;Noticias&lt;/h2&gt; &lt;div id="Not-inn"&gt; &lt;a id="opnoticias" href="https://www.youtube.com/watch?v=faLNS2fXxWA" target="blank"&gt;&lt;img id="notifoto" src="https://cdn.pixabay.com/photo/2018/08/14/13/23/ocean-3605547__340.jpg" alt="imagendoping" height="150px"&gt;&lt;p id="notitext"&gt;Kurt Fritz y Vincenzo Garavito dan positivo a 15 drogas diferentes previo al partido&lt;/p&gt;&lt;/a&gt; &lt;a id="opnoticias" href="https://www.youtube.com/watch?v=dQw4w9WgXcQ" target="blank"&gt;&lt;img id="notifoto" src="https://cdn.pixabay.com/photo/2018/08/14/13/23/ocean-3605547__340.jpg" alt="imagendoping" height="150px"&gt;&lt;p id="notitext"&gt;Embargan la casa de Alex Valera por evasión de impuestos&lt;/p&gt;&lt;/a&gt; &lt;a id="opnoticias" href="https://youtu.be/45O04_E8aVg?t=6" target="blank"&gt;&lt;img id="notifoto" src="https://cdn.pixabay.com/photo/2018/08/14/13/23/ocean-3605547__340.jpg" alt="imagendoping" height="150px"&gt;&lt;p id="notitext"&gt;Deportan a Gago de Australia luego de no encontrar el paradero del bus&lt;/p&gt;&lt;/a&gt; &lt;a id="opnoticias" href="https://youtu.be/nKFZJU7bvaw" target="blank"&gt;&lt;img id="notifoto" src="https://cdn.pixabay.com/photo/2018/08/14/13/23/ocean-3605547__340.jpg" alt="imagendoping" height="150px"&gt;&lt;p id="notitext"&gt;Marcus Thuram renueva en el Huancayo CAF por S/5000 y un KFC&lt;/p&gt;&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74649557, "author": "amalloy", "author_id": 625403, "author_profile": "https://Stackoverflow.com/users/625403", "pm_score": 3, "selected": false, "text": "type {-# LANGUAGE RankNTypes #-}\n\nimport Prelude hiding (head, tail, last)\n\nnewtype List a = List\n (forall r. -- Client can choose any return type\n r -> -- Value to return in case of Nil\n (a -> List a -> r) -> -- Called with Cons's two fields\n r) -- The result\n\nnil :: List a\nnil = List (\\n c -> n)\n\ncons :: a -> List a -> List a\ncons h t = List (\\n c -> c h t)\n\nhead :: List a -> Maybe a\nhead (List list) = list Nothing (\\h t -> Just h)\n\ntail :: List a -> Maybe (List a)\ntail (List list) = list Nothing (\\h t -> Just t)\n nil cons head tail nil cons head tail last last :: List a -> Maybe a\nlast (List list) = list Nothing (\\h t -> Just (go h t))\n where go :: a -> List a -> a\n go curr (List rest) = rest curr go\n" }, { "answer_id": 74653861, "author": "octachron", "author_id": 7369366, "author_profile": "https://Stackoverflow.com/users/7369366", "pm_score": 3, "selected": false, "text": "1 [|1;2|] type t =\n | A\n | B\n | C of int\n | D of int\n Obj Obj.(is_int @@ repr A)\n A 0 assert (Obj.repr A = Obj.repr 0)\n C 1 assert Obj.(\n tag @@ repr (C 1) = 0\n && field (repr (C 1)) 0 = repr 1\n)\n type 'a mylist = | Nil | Cons of 'a * 'a mylist\n\nlet rec last l =\n match l with\n | Nil -> None\n | Cons(x, Nil) -> Some(x)\n | Cons(x, xs) -> last xs\n Nil 0 None Nil 0 Some (first_field of the argument) last (second_field of the argument) ocamlc -dlambda (letrec\n (last/271\n (function l/272\n (if l/272\n (if (field_imm 1 l/272) (apply last/271 (field_imm 1 l/272))\n (makeblock 0 (field_imm 0 l/272)))\n 0)))\n if l/272 field_imm 1 l/272 l/2 match" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74648911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17421059/" ]
74,648,926
<p>I'm new to C++. Whenever I try to compare a string and a string from a vector, it gives me an error. I included two examples below. Why does this happen?</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;string&gt; int main() { std::string vowels = (&quot;aeiou&quot;); std::string whale_talk = &quot;turpentine and turtles&quot;; std::vector&lt;std::string&gt; result; for (int i = 0; i &lt; whale_talk.size(); i++) { for (int x = 0; x &lt; vowels.size(); x++) { if (whale_talk[i] == vowels[x]) { std::cout &lt;&lt; whale_talk[i]; result.push_back(whale_talk[i]); // I'm aware I'm not comparing two vectors, I added this to show that most interaction with strings will also result in an error } } } } </code></pre> <pre class="lang-cpp prettyprint-override"><code>#include &lt;string&gt; #include &lt;iostream&gt; #include &lt;vector&gt; int main() { std::vector &lt;std::string&gt; string_vector; std::string string = &quot;Hello&quot;; std::cout &lt;&lt; &quot;What do you want today?&quot;; string_vector = {&quot;pickles&quot;}; if (string[2] == string_vector[0]) { std::cout &lt;&lt; &quot;No pickles today&quot;; } else { std::cout &lt;&lt; &quot;We only have pickles&quot;; } } </code></pre> <p>I tried adding and removing <code>#include &lt;string&gt;</code>, but that did not help. I also tried putting strings inside the vector before comparing it to a string.</p>
[ { "answer_id": 74648958, "author": "Kelly", "author_id": 7363490, "author_profile": "https://Stackoverflow.com/users/7363490", "pm_score": -1, "selected": false, "text": "#include <vector>\n#include <string>\n\nint main() {\n std::string vowels = (\"aeiou\");\n std::string whale_talk = \"turpentine and turtles\";\n std::vector<std::string> result;\n for (int i = 0; i < whale_talk.size(); i++) {\n for (int x = 0; x < vowels.size(); x++) {\n // Use the at() method to retrieve a single character from the string\n if (whale_talk.at(i) == vowels.at(x)) {\n std::cout << whale_talk.at(i);\n result.push_back(whale_talk.at(i));\n }\n }\n }\n}\n #include <string>\n#include <iostream>\n#include <vector>\nint main() {\n std::vector <std::string> string_vector;\n std::string string = \"Hello\";\n std::cout << \"What do you want today?\";\n string_vector = {\"pickles\"};\n // Use the at() method to retrieve a single character from the string\n if (string.at(2) == string_vector.at(0).at(0)) {\n std::cout << \"No pickles today\";\n }\n else {\n std::cout << \"We only have pickles\";\n }\n}\n" }, { "answer_id": 74650110, "author": "litoma", "author_id": 20661738, "author_profile": "https://Stackoverflow.com/users/20661738", "pm_score": 0, "selected": false, "text": "#include <iostream>\n#include <vector>\n#include <string>\n\nint main() {\n std::string vowels = (\"aeiou\");\n std::string whale_talk = \"turpentine and turtles\";\n std::string result; \n //std::vector<std::string> result;\n for (unsigned int i = 0; i < whale_talk.size(); i++) {\n for (unsigned int x = 0; x < vowels.size(); x++) {\n if (whale_talk[i] == vowels[x]) {\n std::cout << whale_talk[i];\n result.push_back(whale_talk[i]);\n // I'm aware I'm not comparing two vectors, I added this to show that most interaction with strings will also result in an error\n }\n }\n }\n}\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74648926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17762920/" ]
74,649,003
<p>I'm newer to Python. I'm using openpyxl for a SEO project for my brother and I'm trying to get a number of rows that contain a specific value in them.</p> <p>I have a spreadsheet that looks something like this: <a href="https://i.stack.imgur.com/qzzHd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qzzHd.png" alt="sample spreadsheet" /></a></p> <p>I want to write a program that will get the keywords and parse them to a string by state, so like: Missouri = &quot;search item 1, search item 2, search item 5, search item 6&quot; Illinois = &quot;search item 3, search item 4&quot;</p> <p>I have thus far created a program like this:</p> <pre><code> #first, import openpyxl import openpyxl #next, give location of file path = &quot;testExcel.xlsx&quot; #Open workbook by creating object wb_object = openpyxl.load_workbook(path) #Get workbook active sheet object sheet_object = wb_object.active #Getting the value of maximum rows #and column row = sheet_object.max_row column = sheet_object.max_column print(&quot;Total Rows:&quot;, row) print(&quot;Total Columns:&quot;, column) #printing the value of forth column, state #Loop will print all values #of first column print(&quot;\nValue of fourth column&quot;) for i in range(4, row + 1): cell_object = sheet_object.cell(row=i, column=4) split_item_test = cell_object.value.split(&quot;,&quot;) split_item_test_result = split_item_test[0] state = split_item_test_result print(state) if (state == 'Missouri'): print(state.count('Missouri')) print(&quot;All good&quot;) </code></pre> <p>The problem is after doing this, I see that it prints 1 repeatedly, but not a total number for Missouri. I would like a total number of mentions of the state, and then eventually get it to a string with each search criteria.</p> <p>Is this possible with openpyxl? Or will I need a different library?</p>
[ { "answer_id": 74649446, "author": "j-p", "author_id": 20541460, "author_profile": "https://Stackoverflow.com/users/20541460", "pm_score": 0, "selected": false, "text": "print(\"\\nValue of fourth column\")\n\nmissouri_list = [] # empty list\nillinois_list = [] # empty list\n\nfor i in range(2, row+1): # It didn't look like \"4, row+1\" captured the full sheet, try (2, row+1)\n cell_object = sheet_object.cell(row=i, column=4)\n keyword = sheet_object.cell(row=i, column=1)\n keyword_fmt = keyword.value # Captures values in Keyword column\n split_item_test = cell_object.value.split(\",\")\n split_item_test_result = split_item_test[1] # 1 captures states\n state = split_item_test_result\n print(state)\n\n # simple if statement to capture results in a list\n if 'Missouri' in state:\n missouri_list.append(keyword_fmt)\n if 'Illinois' in state:\n illinois_list.append(keyword_fmt)\nprint(missouri_list)\nprint(len(missouri_list)) # Counts the number of occurances\nprint(illinois_list)\nprint(len(illinois_list)) # Counts the number of occurances\nprint(\"All good\")\n" }, { "answer_id": 74650011, "author": "ranemirusG", "author_id": 16233108, "author_profile": "https://Stackoverflow.com/users/16233108", "pm_score": 0, "selected": false, "text": "openpyxl states_and_keywords = {}\nfor i in range(4, row + 1):\n cell_object = sheet_object.cell(row=i, column=4)\n split_item_test = cell_object.value.split(\",\")\n split_item_test_result = split_item_test[1] #note that the element should be 1 for the state\n state = split_item_test_result.strip(\" \") #trim whitespace (after comma)\n keyword = cell_object.offset(0,-3).value #this gets the value of the keyword for that row\n if state not in states_and_keywords:\n states_and_keywords[state] = [keyword]\n else:\n states_and_keywords[state].append(keyword) \nprint(states_and_keywords)\n" }, { "answer_id": 74650302, "author": "moken", "author_id": 13664137, "author_profile": "https://Stackoverflow.com/users/13664137", "pm_score": 2, "selected": true, "text": "...\nprint(\"\\nValue of fourth column\")\nstate_dict = {}\nfor row in sheet_object.iter_rows(min_row=2, max_row=sheet_object.max_row):\n k = row[3].value.split(',')[1].strip()\n v = row[0].value\n if k in state_dict:\n state_dict[k] += [v]\n else:\n state_dict[k] = [v]\n\n### Print values\nfor key, value in state_dict.items():\n print(f'{key}, Total {len(value)}', end='; ')\n for v in value:\n print(f'{v}', end=', ')\n print('')\n 'Missouri' = {list: 4} ['search item 1', 'search item 2', 'search item 5', 'search item 6']\n'Illinois' = {list: 2} ['search item 3', 'search item 4']\n'Alabama' = {list: 1} ['search item 7']\n'Colorado' = {list: 1} ['search item 8']\n Value of fourth column\nMissouri = Total 4; search item 1, search item 2, search item 5, search item 6, \nIllinois = Total 2; search item 3, search item 4, \nAlabama = Total 1; search item 7, \nColorado = Total 1; search item 8, \n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74649003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6100299/" ]
74,649,010
<p>I have to call an api that returns an array of objects:</p> <pre><code>&quot;supervisors&quot;: [ { &quot;jurisdiction&quot;: &quot;u&quot;, &quot;lastName&quot;: &quot;Olson&quot;, &quot;firstName&quot;: &quot;Karson&quot; }, { &quot;jurisdiction&quot;: &quot;9&quot;, &quot;lastName&quot;: &quot;Heller&quot;, &quot;firstName&quot;: &quot;Robbie&quot; }, { &quot;jurisdiction&quot;: &quot;b&quot;, &quot;lastName&quot;: &quot;Cremin&quot;, &quot;firstName&quot;: &quot;Elijah&quot; }, ] </code></pre> <p>The supervisors must be sorted in alphabetical order, first by jurisdiction, then my last name, finally by first name. Then Numeric jurisdictions should be removed from the response.</p> <p>I sorted alphabetically by:</p> <pre><code>supervisorsObj.sort((a, b) =&gt; { a.jurisdiction.toLowerCase().localeCompare(b.jurisdiction.toLowerCase()); }); </code></pre> <p>But how do I remove Numeric jurisdictions if they are all strings?</p>
[ { "answer_id": 74649446, "author": "j-p", "author_id": 20541460, "author_profile": "https://Stackoverflow.com/users/20541460", "pm_score": 0, "selected": false, "text": "print(\"\\nValue of fourth column\")\n\nmissouri_list = [] # empty list\nillinois_list = [] # empty list\n\nfor i in range(2, row+1): # It didn't look like \"4, row+1\" captured the full sheet, try (2, row+1)\n cell_object = sheet_object.cell(row=i, column=4)\n keyword = sheet_object.cell(row=i, column=1)\n keyword_fmt = keyword.value # Captures values in Keyword column\n split_item_test = cell_object.value.split(\",\")\n split_item_test_result = split_item_test[1] # 1 captures states\n state = split_item_test_result\n print(state)\n\n # simple if statement to capture results in a list\n if 'Missouri' in state:\n missouri_list.append(keyword_fmt)\n if 'Illinois' in state:\n illinois_list.append(keyword_fmt)\nprint(missouri_list)\nprint(len(missouri_list)) # Counts the number of occurances\nprint(illinois_list)\nprint(len(illinois_list)) # Counts the number of occurances\nprint(\"All good\")\n" }, { "answer_id": 74650011, "author": "ranemirusG", "author_id": 16233108, "author_profile": "https://Stackoverflow.com/users/16233108", "pm_score": 0, "selected": false, "text": "openpyxl states_and_keywords = {}\nfor i in range(4, row + 1):\n cell_object = sheet_object.cell(row=i, column=4)\n split_item_test = cell_object.value.split(\",\")\n split_item_test_result = split_item_test[1] #note that the element should be 1 for the state\n state = split_item_test_result.strip(\" \") #trim whitespace (after comma)\n keyword = cell_object.offset(0,-3).value #this gets the value of the keyword for that row\n if state not in states_and_keywords:\n states_and_keywords[state] = [keyword]\n else:\n states_and_keywords[state].append(keyword) \nprint(states_and_keywords)\n" }, { "answer_id": 74650302, "author": "moken", "author_id": 13664137, "author_profile": "https://Stackoverflow.com/users/13664137", "pm_score": 2, "selected": true, "text": "...\nprint(\"\\nValue of fourth column\")\nstate_dict = {}\nfor row in sheet_object.iter_rows(min_row=2, max_row=sheet_object.max_row):\n k = row[3].value.split(',')[1].strip()\n v = row[0].value\n if k in state_dict:\n state_dict[k] += [v]\n else:\n state_dict[k] = [v]\n\n### Print values\nfor key, value in state_dict.items():\n print(f'{key}, Total {len(value)}', end='; ')\n for v in value:\n print(f'{v}', end=', ')\n print('')\n 'Missouri' = {list: 4} ['search item 1', 'search item 2', 'search item 5', 'search item 6']\n'Illinois' = {list: 2} ['search item 3', 'search item 4']\n'Alabama' = {list: 1} ['search item 7']\n'Colorado' = {list: 1} ['search item 8']\n Value of fourth column\nMissouri = Total 4; search item 1, search item 2, search item 5, search item 6, \nIllinois = Total 2; search item 3, search item 4, \nAlabama = Total 1; search item 7, \nColorado = Total 1; search item 8, \n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74649010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20660803/" ]
74,649,029
<p>I am getting data from an API and storing it in json format. The data I pull is in a list of dictionaries. I am using Python. My task is to only grab the information from the dictionary that matches the ticker symbol.</p> <p>This is the short version of my data printing using json dumps</p> <pre><code>[ { &quot;ticker&quot;: &quot;BYDDF.US&quot;, &quot;name&quot;: &quot;BYD Co Ltd-H&quot;, &quot;price&quot;: 25.635, &quot;change_1d_prc&quot;: 9.927101200686117 }, { &quot;ticker&quot;: &quot;BYDDY.US&quot;, &quot;name&quot;: &quot;BYD Co Ltd ADR&quot;, &quot;price&quot;: 51.22, &quot;change_1d_prc&quot;: 9.843448423761526 }, { &quot;ticker&quot;: &quot;TSLA.US&quot;, &quot;name&quot;: &quot;Tesla Inc&quot;, &quot;price&quot;: 194.7, &quot;change_1d_prc&quot;: 7.67018746889343 } ] </code></pre> <p>Task only gets the dictionary for ticker = TSLA.US. If possible, only get the price associated with this ticker.</p> <p>I am unaware of how to reference &quot;ticker&quot; or loop through all of them to get the one I need.</p> <p>I tried the following, but it says that its a string, so it doesn't work:</p> <pre><code> if &quot;ticker&quot; == &quot;TESLA.US&quot;: print(i) </code></pre>
[ { "answer_id": 74649055, "author": "user19077881", "author_id": 19077881, "author_profile": "https://Stackoverflow.com/users/19077881", "pm_score": 0, "selected": false, "text": "for entry in mylist:\n print(entry['ticker'])\n for entry in mylist:\n if entry['ticker'] == 'TSLA.US':\n print(entry)\n" }, { "answer_id": 74649189, "author": "supersquires", "author_id": 18182675, "author_profile": "https://Stackoverflow.com/users/18182675", "pm_score": 1, "selected": false, "text": "json_dict for target_dict in json_dict:\n if target_dict[\"ticker\"] == \"TESLA.US\":\n break\n target_dict" }, { "answer_id": 74649968, "author": "RossAShellow", "author_id": 20661581, "author_profile": "https://Stackoverflow.com/users/20661581", "pm_score": 0, "selected": false, "text": " for stock in list:\n if stock[\"ticker\"] == \"TSLA.US\":\n return stock[\"price\"]\n\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74649029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15032207/" ]
74,649,039
<p>I'm trying to understand why my SVG will resize when I change the width of its parent but it won't resize when I change the height.</p> <p>I just made a very simple jsFiddle. You can try resizing the little window at the bottom right corner.</p> <p>From what I understand, it's key that the parent has 100% width and height so that a window resize is detected and inner svg can adjust. It's also key to specify the viewBox attribute to allow the svg to resize according to its parent div.</p> <p>But why is it not resizing accorindg to height?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>div { height: 100%; width: 100%; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div&gt; &lt;svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg"&gt; &lt;circle cx="100" cy="100" r="100" /&gt; &lt;/svg&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p><a href="http://jsfiddle.net/7dz60fkh/" rel="nofollow noreferrer">http://jsfiddle.net/7dz60fkh/</a></p>
[ { "answer_id": 74649963, "author": "Robert Longson", "author_id": 1038015, "author_profile": "https://Stackoverflow.com/users/1038015", "pm_score": 1, "selected": false, "text": "div, html, body, svg {\n height: 100%;\n width: 100%;\n} <div>\n <svg viewBox=\"0 0 200 200\" xmlns=\"http://www.w3.org/2000/svg\">\n <circle cx=\"100\" cy=\"100\" r=\"100\" />\n </svg>\n</div>" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74649039", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11237235/" ]
74,649,065
<p>I tried making two input fields one for dimensions and one for weight, and both had seperate select drop down to allow the user to select a unit. <a href="https://4x.ant.design/components/input/#:%7E:text=%3CInput%20defaultValue%3D%2226888888%22" rel="nofollow noreferrer">I saw on Ant design docs that they had something similar</a>, so I tried using that.</p> <p>This is how I wanted it to be like: <a href="https://i.stack.imgur.com/34Llq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/34Llq.png" alt="enter image description here" /></a></p> <p>Now i have filled my form with many other fields and they work just fine, on clicking the save button, I am not getting any data entered in the fields for dimensions or weight, nor their units. I have a standard save function which is called on 'onFinish' event:</p> <pre><code>const handleSubmit = (data) =&gt; { console.log('data', data); submit(data); }; </code></pre> <p>This is my code to generate the fields.</p> <pre><code>&lt;Form onFinish={handleSubmit} &gt; &lt;Row style={{ justifyContent: 'left' }}&gt; {&lt;Col span={8}&gt; &lt;div className=&quot;p-2 lbh-input&quot;&gt; &lt;Form.Item name=&quot;dimensions&quot; key=&quot;dimensions&quot; label=&quot;Dimensions &amp;nbsp;&amp;nbsp; (l x b x h)&quot;&gt; &lt;Input.Group&gt; &lt;Input key='length' name='length' style={{ width: '15%' }} type=&quot;number&quot; /&gt; &lt;Input key='breadth' name='breadth' style={{ width: '24%' }} addonBefore=&quot;x&quot; type=&quot;number&quot; /&gt; &lt;Input key='height' name='height' style={{ width: '25%' }} addonBefore=&quot;x&quot; type=&quot;number&quot; /&gt; &lt;Select name='dimension_unit' key='dimension_unit' defaultValue=&quot;cm&quot;&gt; &lt;Option value=&quot;mm&quot;&gt;mm&lt;/Option&gt; &lt;Option value=&quot;cm&quot;&gt;cm&lt;/Option&gt; &lt;Option value=&quot;inch&quot;&gt;inch&lt;/Option&gt; &lt;Option value=&quot;feet&quot;&gt;feet&lt;/Option&gt; &lt;Option value=&quot;m&quot;&gt;m&lt;/Option&gt; &lt;/Select&gt; &lt;/Input.Group&gt; &lt;/Form.Item&gt; &lt;/div&gt; &lt;/Col&gt; } { &lt;div className=&quot;p-2&quot;&gt; &lt;Form.Item key=&quot;weight&quot; name=&quot;weight&quot; label=&quot;Weight&quot;&gt; &lt;Input.Group&gt; &lt;Input style={{ width: '50%' }} type=&quot;number&quot; key=&quot;weight&quot; name=&quot;weight&quot; label=&quot;Weight&quot; className='noborderradius' /&gt; &lt;Select defaultValue=&quot;kg&quot; name=&quot;weight_unit&quot; key=&quot;weight_unit&quot;&gt; &lt;Option value=&quot;kg&quot;&gt;kg&lt;/Option&gt; &lt;Option value=&quot;tonne&quot;&gt;tonne&lt;/Option&gt; &lt;Option value=&quot;g&quot;&gt;g&lt;/Option&gt; &lt;/Select&gt; &lt;/Input.Group&gt; &lt;/Form.Item&gt; &lt;/div&gt;} &lt;/Row&gt; &lt;button&gt;SUBMIT&lt;/button&gt; &lt;/Form&gt; </code></pre> <p>As you can see, i have tried using everythihg I can like label,name,key but no matter what happens, I get no data being sent no matter what I type in these two fields. What am i missing? Am i doing something wrong with <code>&lt;Form.item&gt;</code> ? My ant design version is</p> <pre><code>&quot;antd&quot;: &quot;^4.3.4&quot;, </code></pre>
[ { "answer_id": 74649963, "author": "Robert Longson", "author_id": 1038015, "author_profile": "https://Stackoverflow.com/users/1038015", "pm_score": 1, "selected": false, "text": "div, html, body, svg {\n height: 100%;\n width: 100%;\n} <div>\n <svg viewBox=\"0 0 200 200\" xmlns=\"http://www.w3.org/2000/svg\">\n <circle cx=\"100\" cy=\"100\" r=\"100\" />\n </svg>\n</div>" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74649065", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5660533/" ]
74,649,068
<p>Write a program that gets a list of integers from input, and outputs non-negative integers in ascending order (lowest to highest).</p> <p>Example: If the input is:</p> <p>10 -7 4 39 -6 12 2</p> <p>the output is:</p> <p>2 4 10 12 39</p> <p>My code that I came up with looks like this:</p> <pre><code>user_input = input() numbers = user_input.split() nums = [] for number in numbers: nums.append(int(number)) for item in nums: if int(item) &lt; 0: nums.remove(item) list.sort(nums) for x in nums: print(x, end=' ') </code></pre> <p>It gives me an 8/10 for my score but on one of the input/outputs it gives me</p> <p>input is -1 -7 -2 -88 5 -6 my output is -88 -7 5</p> <p>Why is it only removing some of the negative numbers and not all of them?</p>
[ { "answer_id": 74649203, "author": "mbunic", "author_id": 17736261, "author_profile": "https://Stackoverflow.com/users/17736261", "pm_score": 0, "selected": false, "text": "for item in nums:\n if int(item) < 0:\n nums.remove(item)\n onlyPositiveIntegers = [x for x in nums if x >= 0]\n" }, { "answer_id": 74649534, "author": "rishabh11336", "author_id": 15002598, "author_profile": "https://Stackoverflow.com/users/15002598", "pm_score": -1, "selected": false, "text": "nums.sort() \nfor item in nums:\n if int(item) >= 0:\n break\n nums.remove(item)\nprint(*nums)\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74649068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20325517/" ]
74,649,080
<p>I am trying to create a list of the last days of each month for the past n months from the current date but not including current month</p> <p>I tried different approaches:</p> <pre><code>def last_n_month_end(n_months): &quot;&quot;&quot; Returns a list of the last n month end dates &quot;&quot;&quot; return [datetime.date.today().replace(day=1) - datetime.timedelta(days=1) - datetime.timedelta(days=30*i) for i in range(n_months)] </code></pre> <p>somehow this partly works if each every month only has 30 days and also not work in databricks pyspark. It returns <code>AttributeError: 'method_descriptor' object has no attribute 'today'</code></p> <p>I also tried the approach mentioned in <a href="https://stackoverflow.com/questions/73943590/generate-a-sequence-of-the-last-days-of-all-previous-n-months-with-a-given-month">Generate a sequence of the last days of all previous N months with a given month</a></p> <pre><code>def previous_month_ends(date, months): year, month, day = [int(x) for x in date.split('-')] d = datetime.date(year, month, day) t = datetime.timedelta(1) s = datetime.date(year, month, 1) return [(x - t).strftime('%Y-%m-%d') for m in range(months - 1, -1, -1) for x in (datetime.date(s.year, s.month - m, s.day) if s.month &gt; m else \ datetime.date(s.year - 1, s.month - (m - 12), s.day),)] </code></pre> <p>but I am not getting it correctly.</p> <p>I also tried:</p> <pre><code>df = spark.createDataFrame([(1,)],['id']) days = df.withColumn('last_dates', explode(expr('sequence(last_day(add_months(current_date(),-3)), last_day(add_months(current_date(), -1)), interval 1 month)'))) </code></pre> <p>I got the last three months (Sep, oct, nov), but all of them are the 30th but Oct has Oct 31st. However, it gives me the correct last days when I put more than 3.</p> <p>What I am trying to get is this: (last days of the last 4 months not including last_day of current_date)</p> <p><code>daterange = ['2022-08-31','2022-09-30','2022-10-31','2022-11-30']</code></p>
[ { "answer_id": 74652123, "author": "rainingdistros", "author_id": 13280838, "author_profile": "https://Stackoverflow.com/users/13280838", "pm_score": 2, "selected": false, "text": "pip install python-dateutil\n # import datetime package\nfrom datetime import date, timedelta\nfrom dateutil.relativedelta import relativedelta\n\n\ndef previous_month_ends(months_to_subtract):\n # get first day of current month\n first_day_of_current_month = date.today().replace(day=1)\n print(f\"First Day of Current Month: {first_day_of_current_month}\")\n # Calculate and previous month's Last date\n date_range_list = [first_day_of_current_month - relativedelta(days=1)]\n cur_iter = 1\n while cur_iter < months_to_subtract:\n # Calculate First Day of previous months relative to first day of current month\n cur_iter_fdom = first_day_of_current_month - relativedelta(months=cur_iter)\n # Subtract one day to get the last day of previous month\n cur_iter_ldom = cur_iter_fdom - relativedelta(days=1)\n # Append to the list\n date_range_list.append(cur_iter_ldom)\n # Increment Counter\n cur_iter+=1\n return date_range_list\n\nprint(previous_month_ends(3))\n # import datetime package\nfrom datetime import date, timedelta\nfrom dateutil.relativedelta import relativedelta\n\n\ndef gen_date_list(months_to_subtract):\n # get first day of current month\n first_day_of_current_month = date.today().replace(day=1)\n print(f\"First Day of Current Month: {first_day_of_current_month}\")\n start_date = first_day_of_current_month - relativedelta(months=months_to_subtract)\n end_date = first_day_of_current_month - relativedelta(days=1)\n print(f\"Start Date: {start_date}\")\n print(f\"End Date: {end_date}\")\n date_range_list = [start_date]\n cur_iter_date = start_date\n while cur_iter_date < end_date:\n cur_iter_date += timedelta(days=1)\n date_range_list.append(cur_iter_date)\n # print(date_range_list)\n return date_range_list\n\nprint(gen_date_list(3))\n" }, { "answer_id": 74658540, "author": "budding pro", "author_id": 16762881, "author_profile": "https://Stackoverflow.com/users/16762881", "pm_score": 2, "selected": true, "text": "from datetime import datetime, timedelta\n\ndef get_last_dates(n_months):\n '''\n generates a list of lastdates for each month for the past n months\n Param:\n n_months = number of months back\n '''\n last_dates = [] # initiate an empty list\n for i in range(n_months):\n last_dates.append((datetime.today() - timedelta(days=i*30)).replace(day=1) - timedelta(days=1))\n return last_dates\n" }, { "answer_id": 74658609, "author": "doubleD", "author_id": 12981766, "author_profile": "https://Stackoverflow.com/users/12981766", "pm_score": 1, "selected": false, "text": "df = spark.createDataFrame([(1,)],['id'])\n\ndays = df.withColumn('last_dates', explode(expr('sequence(last_day(add_months(current_date(),-3)), last_day(add_months(current_date(), -1)), interval 1 month)')))\n days.pop(0)" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74649080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12981766/" ]
74,649,083
<p>I have the simplest nuxt3 project and my button when pressed doesn't register a click event.</p> <p>Why? Or where can I look for a solution?</p> <p><code>&lt;button @click=&quot;console.log('PRESSED')&quot; class=&quot;bg-gray-500&quot;&gt;GENERATE TEXT&lt;/button&gt;</code></p> <p>. Replication:</p> <ol> <li><code>npx nuxi init replica_project</code></li> <li><code>cd replica_project</code></li> <li><code>npm install --save-dev @nuxtjs/tailwindcss</code></li> <li>Added in <code>nuxt.config.ts</code> <code>modules: [ '@nuxtjs/tailwindcss' ]</code></li> <li>Put <code>&lt;button @click=&quot;console.log('I got hit on')&quot; class=&quot;bg-gray-500&quot;&gt;HIT ME BABY&lt;/button&gt;</code> in the <code>App.vue</code> file `</li> </ol> <hr /> <p>Tried Solutions:</p> <ol> <li>Add <code>.native</code>: <code>&lt;button @click.native=&quot;console.log('PRESSED')&quot; class=&quot;bg-gray-500&quot;&gt;GENERATE TEXT&lt;/button&gt;</code></li> </ol>
[ { "answer_id": 74649909, "author": "kissu", "author_id": 8816585, "author_profile": "https://Stackoverflow.com/users/8816585", "pm_score": 1, "selected": false, "text": "console.log <script setup>\nfunction consoleHitOn() {\n console.log('I got hit on')\n}\n</script>\n\n<template>\n <button @click=\"consoleHitOn\">HIT ME BABY</button>\n</template>\n <script>\nexport default {\n computed: {\n console: () => console,\n }\n}\n</script>\n\n<template>\n <button @click=\"console.log('I got hit on')\">HIT ME BABY</button>\n</template>\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74649083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10099689/" ]
74,649,128
<p>I am creating a react project and I'd like to know if it's okay to use FontAwesome icons on a ReactJS project that is using MaterialUI.</p> <p>I tried to use the Material UI Icons and also use FontAwesome Icons but I thought that there's a repetition.</p>
[ { "answer_id": 74649909, "author": "kissu", "author_id": 8816585, "author_profile": "https://Stackoverflow.com/users/8816585", "pm_score": 1, "selected": false, "text": "console.log <script setup>\nfunction consoleHitOn() {\n console.log('I got hit on')\n}\n</script>\n\n<template>\n <button @click=\"consoleHitOn\">HIT ME BABY</button>\n</template>\n <script>\nexport default {\n computed: {\n console: () => console,\n }\n}\n</script>\n\n<template>\n <button @click=\"console.log('I got hit on')\">HIT ME BABY</button>\n</template>\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74649128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14590441/" ]
74,649,152
<p>I'm a beginner with regex and stuck with creating regex with the following conditions:</p> <ul> <li>Minimum of 8 characters</li> <li>Maximum of 60 characters</li> <li>Must contain 2 letters</li> <li>Must contain 1 number</li> <li>Must contain 1 special character</li> <li>Special character cannot be the following: &amp; ` ( ) = [ ] | ; &quot; ' &lt; &gt;</li> </ul> <p>So far I have the following...</p> <pre><code>(?=^.{8,60}$)(?=.*\d)(?=[a-zA-Z]{2,})(?!.*[&amp;`()=[|;&quot;''\]'&lt;&gt;]).* </code></pre> <p>But my last two tests are failing and I have no idea why...</p> <ol> <li>!@#$%^*+-_~?,.{}!HR12345</li> <li>123456789AB!</li> </ol> <p>If you'd like to see my test and expected results, visit here: <a href="https://regexr.com/73m2o" rel="nofollow noreferrer">https://regexr.com/73m2o</a></p> <p>My tests contains acceptable number of characters, appropriate number of alphabetic characters, and supported special characters... I don't know why it's failing!</p>
[ { "answer_id": 74649222, "author": "esqew", "author_id": 269970, "author_profile": "https://Stackoverflow.com/users/269970", "pm_score": 1, "selected": false, "text": ".* (?=^.{8,60}$)(?=.*\\d)(?=.*[a-zA-Z]{2,})(?!.*[&`()=[|;\"''\\]'<>]).*\n" }, { "answer_id": 74649267, "author": "Mako212", "author_id": 4421870, "author_profile": "https://Stackoverflow.com/users/4421870", "pm_score": 2, "selected": true, "text": ".* (?=[a-zA-Z]{2,}) 1234567B89A! (?=^.{8,60}$)(?=.*\\d)(?=.*[a-zA-Z].*[a-zA-Z])(?!.*[&`()=[|;\"''\\]'<>]).*\n (?=.*[a-zA-Z].*[a-zA-Z])" }, { "answer_id": 74654573, "author": "The fourth bird", "author_id": 5424988, "author_profile": "https://Stackoverflow.com/users/5424988", "pm_score": 2, "selected": false, "text": ".* Must contain 1 special character ^(?=[^\\d\\n]*\\d)(?=[^a-zA-Z\\n]*[a-zA-Z][^a-zA-Z\\n]*[a-zA-Z])(?=[^!@#$%^\\n]*[!@#$%^])[^&`()=[|;\"''\\]'<>\\n]{8,60}$\n ^ (?=[^\\d\\n]*\\d) (?=[^a-zA-Z\\n]*[a-zA-Z][^a-zA-Z\\n]*[a-zA-Z]) (?=[^!@#$%^\\n]*[!@#$%^]) [^&`()=[|;\"''\\]'<>\\n]{8,60} $" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74649152", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20660911/" ]
74,649,209
<p>Can anyone clarify for me what I have shown in the 'image' attached is achievable in flutter? if yes, how? explaining the image is a bit hard.</p> <p>I am new to flutter and trying to nest some scrollable views inside each other.</p> <p>at first I tried to achieve this by nesting simple scrollable row and columns inside each other but faced some errors and exceptions (unbound height and width).</p> <p>I searched and found out it is better to use 'CustomScrollView' for nesting lists in each other. tried it but haven't achieved what I want yet. Any help/hint on how to achieve this would be much appreciated.</p> <p><a href="https://i.stack.imgur.com/0eEka.png" rel="nofollow noreferrer">Nested Scroll Views</a></p>
[ { "answer_id": 74649222, "author": "esqew", "author_id": 269970, "author_profile": "https://Stackoverflow.com/users/269970", "pm_score": 1, "selected": false, "text": ".* (?=^.{8,60}$)(?=.*\\d)(?=.*[a-zA-Z]{2,})(?!.*[&`()=[|;\"''\\]'<>]).*\n" }, { "answer_id": 74649267, "author": "Mako212", "author_id": 4421870, "author_profile": "https://Stackoverflow.com/users/4421870", "pm_score": 2, "selected": true, "text": ".* (?=[a-zA-Z]{2,}) 1234567B89A! (?=^.{8,60}$)(?=.*\\d)(?=.*[a-zA-Z].*[a-zA-Z])(?!.*[&`()=[|;\"''\\]'<>]).*\n (?=.*[a-zA-Z].*[a-zA-Z])" }, { "answer_id": 74654573, "author": "The fourth bird", "author_id": 5424988, "author_profile": "https://Stackoverflow.com/users/5424988", "pm_score": 2, "selected": false, "text": ".* Must contain 1 special character ^(?=[^\\d\\n]*\\d)(?=[^a-zA-Z\\n]*[a-zA-Z][^a-zA-Z\\n]*[a-zA-Z])(?=[^!@#$%^\\n]*[!@#$%^])[^&`()=[|;\"''\\]'<>\\n]{8,60}$\n ^ (?=[^\\d\\n]*\\d) (?=[^a-zA-Z\\n]*[a-zA-Z][^a-zA-Z\\n]*[a-zA-Z]) (?=[^!@#$%^\\n]*[!@#$%^]) [^&`()=[|;\"''\\]'<>\\n]{8,60} $" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74649209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12555138/" ]
74,649,268
<p>I am trying to submit a form and then the browser has to close. But I cannot understand why it will not work. For some reason, it will close the window, but it does not submit the form.</p> <pre><code>$('.cancel-confirm').on('click', function () { $(this).closest('form').submit(); alert('Submitted - your window will now close'); window.close(); }); </code></pre> <pre><code>&lt;form asp-action=&quot;CancelActivity&quot; method=&quot;post&quot; class=&quot;absolute ff f-36 foreground-white&quot; style=&quot;right:5em; top:20%;&quot;&gt; &lt;input type=&quot;hidden&quot; name=&quot;ActivityID&quot; value=&quot;@item.Activityid&quot; /&gt; &lt;input type=&quot;hidden&quot; name=&quot;status&quot; value=&quot;@(item.IsCancelled == true ? &quot;false&quot; : &quot;true&quot;)&quot; /&gt; &lt;button class=&quot;btn ff f-22 background-transparant foreground-black cancel-confirm&quot; type=&quot;submit&quot;&gt; @(item.IsCancelled == true ? &quot;Genaktiver&quot; : &quot;Deaktiver&quot;) &lt;/button&gt; &lt;/form&gt; </code></pre> <p>Tried to submit the form with jQuery and then close the window</p>
[ { "answer_id": 74651264, "author": "Nagonus Lrak", "author_id": 20476491, "author_profile": "https://Stackoverflow.com/users/20476491", "pm_score": 1, "selected": false, "text": "$('#form-id').submit(function () {\n window.close();\n});\n" }, { "answer_id": 74664217, "author": "Aaron Magpantay", "author_id": 6553004, "author_profile": "https://Stackoverflow.com/users/6553004", "pm_score": 0, "selected": false, "text": "$('.cancel-confirm').on('click', function () {\n $.post( \"yourprocessor.php\", { name: \"Your Name\", sex: \"Male\" })\n .done(function( data ) {\n alert('Submitted - your window will now close');\n window.close();\n }); \n});\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74649268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20531127/" ]
74,649,296
<p>I'm using a library that itself makes the call to <code>asyncio.run(internal_function)</code> so I can't control that at all. I do however have access to the event loop, it's something that I pass into this library.</p> <p>Given that, is there some way I can set up an recurring async event that will execute every X seconds while the main library is running.</p> <p>This doesn't exactly work, but maybe it's close?</p> <pre class="lang-py prettyprint-override"><code>import asyncio from third_party import run loop = asyncio.new_event_loop() async def periodic(): while True: print(&quot;doing a thing...&quot;) await asyncio.sleep(30) loop.create_task(periodic()) run(loop) # internally this will call asyncio.run() using the given loop </code></pre> <p>The problem here of course is that the task I've created is never awaited. But I can't just await it, because that would block.</p> <p>Edit: Here's a working example of what I'm facing. When you run this code you will only ever see &quot;third party code executing&quot; and never see &quot;doing my stuff...&quot;.</p> <pre class="lang-py prettyprint-override"><code>import asyncio # I don't know how the loop argument is used # by the third party's run() function, def third_party_run(loop): async def runner(): while True: print(&quot;third party code executing&quot;) await asyncio.sleep(5) # but I do know that this third party eventually runs code # that looks **exactly** like this. try: asyncio.run(runner()) except KeyboardInterrupt: return loop = asyncio.new_event_loop() async def periodic(): while True: print(&quot;doing my stuff...&quot;) await asyncio.sleep(1) loop.create_task(periodic()) third_party_run(loop) </code></pre> <p>If you run the above code you get:</p> <pre><code>third party code executing third party code executing third party code executing ^CTask was destroyed but it is pending! task: &lt;Task pending name='Task-1' coro=&lt;periodic() running at example.py:22&gt;&gt; /usr/local/Cellar/python@3.10/3.10.8/Frameworks/Python.framework/Versions/3.10/lib/python3.10/asyncio/base_events.py:674: RuntimeWarning: coroutine 'periodic' was never awaited </code></pre>
[ { "answer_id": 74651264, "author": "Nagonus Lrak", "author_id": 20476491, "author_profile": "https://Stackoverflow.com/users/20476491", "pm_score": 1, "selected": false, "text": "$('#form-id').submit(function () {\n window.close();\n});\n" }, { "answer_id": 74664217, "author": "Aaron Magpantay", "author_id": 6553004, "author_profile": "https://Stackoverflow.com/users/6553004", "pm_score": 0, "selected": false, "text": "$('.cancel-confirm').on('click', function () {\n $.post( \"yourprocessor.php\", { name: \"Your Name\", sex: \"Male\" })\n .done(function( data ) {\n alert('Submitted - your window will now close');\n window.close();\n }); \n});\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74649296", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4496354/" ]
74,649,314
<p>Assume 2022-10-01 and 2022-10-8 are Monday, and the original table looks like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Date</th> <th>Value</th> </tr> </thead> <tbody> <tr> <td>2022-10-03</td> <td>x</td> </tr> <tr> <td>2022-10-04</td> <td>y</td> </tr> <tr> <td>2022-10-09</td> <td>z</td> </tr> </tbody> </table> </div> <p>I want to convert it to</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Date</th> <th>Value</th> </tr> </thead> <tbody> <tr> <td>2022-10-01</td> <td>x</td> </tr> <tr> <td>2022-10-01</td> <td>y</td> </tr> <tr> <td>2022-10-08</td> <td>z</td> </tr> </tbody> </table> </div> <p>Is there any simple ways to do this? Thanks!</p> <p>I tried look up but seems not finding anything neat solutions</p>
[ { "answer_id": 74649403, "author": "Paddy Alton", "author_id": 9044370, "author_profile": "https://Stackoverflow.com/users/9044370", "pm_score": 0, "selected": false, "text": " SELECT\n truncate_date(week, Date) + interval '1' day AS date,\n Value\n FROM\n table\n" }, { "answer_id": 74649412, "author": "Martin Traverso", "author_id": 2958752, "author_profile": "https://Stackoverflow.com/users/2958752", "pm_score": 2, "selected": true, "text": "date_trunc SELECT date_trunc('week', dt)\nFROM (\n VALUES DATE '2022-12-01'\n) t(dt)\n _col0\n------------\n 2022-11-28\n(1 row)\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74649314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19523362/" ]
74,649,329
<p>I'm trying to make a SPA with html, css and vanilla JS (I have very little idea of JS). The problem I have is that the method I am using, works correctly in my header where I have only &quot;a&quot; with text inside. But when I want to use an img as &quot;a&quot;, the script does not work inside the img, it only allows me to click around the img and not inside it. I appreciate any help. This is my script and my html in the part where I have the problem.</p> <pre class="lang-js prettyprint-override"><code>const route = (event) =&gt; { event = event || window.event; event.preventDefault(); window.history.pushState({}, &quot;&quot;, event.target.href); handleLocation(); }; const routes = { 404: &quot;./pages/404.html&quot;, &quot;/&quot;: &quot;./pages/index.html&quot;, &quot;/vehicles&quot;: &quot;./pages/vehicles.html&quot;, &quot;/services&quot;: &quot;./pages/services.html&quot;, &quot;/contact&quot;: &quot;./pages/contact.html&quot;, &quot;/financing&quot;: &quot;./pages/financing.html&quot;, &quot;/locations&quot;: &quot;./pages/locations.html&quot;, }; const handleLocation = async () =&gt; { const path = window.location.pathname; const route = routes[path] || routes[404]; const html = await fetch(route).then((data) =&gt; data.text()); document.getElementById(&quot;main-page&quot;).innerHTML = html; }; window.onpopstate = handleLocation; window.route = route; handleLocation(); </code></pre> <pre class="lang-html prettyprint-override"><code>&lt;a href=&quot;/financing&quot; onclick=&quot;route()&quot; class=&quot;mainServices-section&quot;&gt; &lt;div class=&quot;main-title&quot;&gt; &lt;h2&gt;Financing&lt;/h2&gt; &lt;/div&gt; &lt;img src=&quot;../image/financing-image-colored.svg&quot; alt=&quot;&quot;&gt; &lt;/a&gt; </code></pre>
[ { "answer_id": 74649403, "author": "Paddy Alton", "author_id": 9044370, "author_profile": "https://Stackoverflow.com/users/9044370", "pm_score": 0, "selected": false, "text": " SELECT\n truncate_date(week, Date) + interval '1' day AS date,\n Value\n FROM\n table\n" }, { "answer_id": 74649412, "author": "Martin Traverso", "author_id": 2958752, "author_profile": "https://Stackoverflow.com/users/2958752", "pm_score": 2, "selected": true, "text": "date_trunc SELECT date_trunc('week', dt)\nFROM (\n VALUES DATE '2022-12-01'\n) t(dt)\n _col0\n------------\n 2022-11-28\n(1 row)\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74649329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20661030/" ]
74,649,340
<p>I'm having some trouble with data being sent through my controller, here's a simplified example:</p> <pre><code> public ActionResult EditNote(NotesModel model) { model.Author = Session[&quot;UserName&quot;].ToString(); model.Note = null; model.Title = null; return View(model); } </code></pre> <p>On my views page the data shown from the model is the exact same as how it was received by the method and all changes are ignored, why?</p> <p><strong>Bigger picture:</strong></p> <p>I'm trying to have a user edit an existing note in the database, if they're the one who made it of course. based on whether or not they're the author they will either edit the existing note or create a new note, this is where the problem lies. The controller is supposed to set all the values of the model to null so that on the views page they will be empty. Editing an existing note is no problem however emptying the model so the editing page is blank does not work.</p> <p><strong>EDIT</strong></p> <p>This is my view page:</p> <pre><code>@model WebsiteProject.Models.NotesModel @{ ViewBag.Title = &quot;&quot;; Layout = &quot;~/Views/Shared/_Layout.cshtml&quot;; } @section Sidebar { &lt;div id=&quot;sidebarheadericon&quot; style=&quot;background-image: url('../Content/icons/apps.png')&quot;&gt;&lt;/div&gt; &lt;div id=&quot;headertext&quot;&gt;&lt;h1&gt;Welcome&lt;/h1&gt;&lt;/div&gt; &lt;hr id=&quot;seperator&quot; /&gt; &lt;p class=&quot;psidebar&quot;&gt;test&lt;/p&gt; &lt;p&gt; @Html.ActionLink(&quot;Create New&quot;, &quot;EditNote&quot;) &lt;/p&gt; } @using (Html.BeginForm()) { @Html.AntiForgeryToken() &lt;div class=&quot;form-horizontal&quot;&gt; &lt;h1&gt;NotesModel&lt;/h1&gt; &lt;hr /&gt; @Html.ValidationSummary(true, &quot;&quot;, new { @class = &quot;text-danger&quot; }) &lt;p class=&quot;control-label&quot;&gt;Note by @Session[&quot;UserName&quot;].ToString()&lt;/p&gt; &lt;div class=&quot;form-group&quot;&gt; @Html.LabelFor(model =&gt; model.Title, htmlAttributes: new { @class = &quot;control-label col-md-2&quot; }) &lt;div class=&quot;col-md-10&quot;&gt; @Html.EditorFor(model =&gt; model.Title, new { htmlAttributes = new { @class = &quot;form-control&quot; } }) @Html.ValidationMessageFor(model =&gt; model.Title, &quot;&quot;, new { @class = &quot;text-danger&quot; }) &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;form-group&quot;&gt; @Html.LabelFor(model =&gt; model.Note, htmlAttributes: new { @class = &quot;control-label col-md-2&quot; }) &lt;div class=&quot;col-md-10&quot;&gt; @Html.EditorFor(model =&gt; model.Note, new { htmlAttributes = new { @class = &quot;form-control&quot; } }) @Html.ValidationMessageFor(model =&gt; model.Note, &quot;&quot;, new { @class = &quot;text-danger&quot; }) &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;form-group&quot;&gt; &lt;div class=&quot;col-md-offset-2 col-md-10&quot;&gt; &lt;input type=&quot;submit&quot; value=&quot;Create&quot; class=&quot;largebtn&quot; /&gt; &lt;/div&gt; &lt;/div&gt; &lt;p class=&quot;text-danger&quot;&gt;@ViewBag.NoteViewError&lt;/p&gt; &lt;/div&gt; } &lt;div&gt; @Html.ActionLink(&quot;Back to List&quot;, &quot;NoteApp&quot;) &lt;/div&gt; @section Scripts { @Scripts.Render(&quot;~/bundles/jqueryval&quot;) } </code></pre> <p><strong>Here you can see the data that is received</strong> (dummy data) <a href="https://i.stack.imgur.com/JU8Mj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JU8Mj.png" alt="Data received" /></a></p> <p><strong>Now here you'll see that the data of the model is changed</strong> <a href="https://i.stack.imgur.com/v3yOU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/v3yOU.png" alt="Data changed" /></a></p> <p><strong>Yet on the website it is not changed</strong> <a href="https://i.stack.imgur.com/KSiJS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KSiJS.png" alt="Website" /></a></p> <p>The biggest problem isn't the Note and Title not being changed because the user can do that, but the Id and Author, which the user cannot, and should not be able to change.</p>
[ { "answer_id": 74649762, "author": "Charles Han", "author_id": 11514907, "author_profile": "https://Stackoverflow.com/users/11514907", "pm_score": 0, "selected": false, "text": "public ActionResult EditNote(NotesModel model)\n{\n if(model.Id > 0) //assuming existing notes has id or any other ways you want to check\n {\n //save data\n return View(model);\n }\n else //if Id has a value <= 0, return a new model with only Author set, maybe the Id (depending on how you want to generate the Id)\n {\n var model = new NotesModel();\n model.Author = Session[\"UserName\"].ToString(); \n return Viwe(model);\n }\n}\n\n" }, { "answer_id": 74649898, "author": "Peter B", "author_id": 1220550, "author_profile": "https://Stackoverflow.com/users/1220550", "pm_score": 1, "selected": false, "text": "EditorFor @Html.EditorFor(model => model.Note, new { htmlAttributes = ... })\n EditorFor Model ModelState ModelState EditorFor int Remove ModelState.Remove(\"Note\");\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74649340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20268332/" ]
74,649,350
<p>I'm working on developing both the client(C) and server(C++) side of an RF connection. I need to send a float value, but the way the architecture is set up I have to arrange my message in a struct that limits me to 3 uint8t parameters: p0, p1, p2. My solution was to break the float into an array of 4 uint8_ts and send in 2 separate messages and use p0 as an identifier whether the message contains the first or second half.</p> <p>So far I have something like this:</p> <p>Server (C++):</p> <pre class="lang-cpp prettyprint-override"><code>sendFloat(float f) { messageStruct msg1, msg2; uint8_t* array = (uint8_t*)(&amp;f); msg1.p0 = 1; //1 means it's the first half msg1.p1 = array[0]; msg1.p2 = array[1]; msg2.p0 = 0; //0 means it's the second half msg2.p1 = array[2]; msg2.p2 = array[3]; sendOverRf(msg1); sendOverRf(msg2); } </code></pre> <p>Client(C):</p> <pre class="lang-cpp prettyprint-override"><code>processReceivedMessage (uint32_t id, uint32_t byteA, uint32_t byteB) //(p0,p1,p2) are routed here { static uint32_t firsHalfOfFloat; uint32_t ondHalfOfFloat; float combinedFloat; if(id == 1) //first half { firstHalfOfFloat = (byteA &lt;&lt; 8) | byteB; } else //second half { secondHalfOfFloat = (byteA &lt;&lt; 8) | byteB; combinedFloat = (float)((firstHalfOfFloat &lt;&lt; 16) | secondHalfOfFloat); } writeFloatToFile(combinedFloat); } </code></pre> <p>then on request the client must then send that float back</p> <p>Client(C):</p> <pre class="lang-cpp prettyprint-override"><code>sendFloatBack(uint8_t firstHalfIdentifier) // is commanded twice by server with both 0 and 1 ids { messageStruct msg; float f = getFloatFromFile(); uint8_t* array = (uint8_t*)(&amp;f); msg.p0 = firstHalfIdentifier; if(firstHalfIdentifier == 1) //First half { msg.p1 = array[0]; msg.p2 = array[1]; } else //Second half { msg.p1 = array[2]; msg.p2 = array[3]; } sendOverRf(msg); } </code></pre> <p>and finally the Server (C++) gets the value back:</p> <pre class="lang-cpp prettyprint-override"><code>retrieveFunc() { float f; uint32_t firstHalf; uint32_t secondHalf; messageStruct msg = recieveOverRf(); firstHalf = (msg.p1 &lt;&lt; 8) | msg.p2; msg = receiveOverRf(); firstHalf = (msg.p1 &lt;&lt; 8) | msg.p2; f = (firstHalf &lt;&lt; 16) | secondHalf; } </code></pre> <p>but I'm getting really wrong values back. Any help would be great.</p>
[ { "answer_id": 74649457, "author": "0___________", "author_id": 6110094, "author_profile": "https://Stackoverflow.com/users/6110094", "pm_score": 0, "selected": false, "text": "float toFloat(const uint8_t *arr)\n{\n float result;\n\n memcpy(&result, arr, sizeof(result));\n\n return result;\n}\n\nuint8_t *toArray(const float x, uint8_t * const arr)\n{\n memcpy(arr, &x, sizeof(x));\n return arr;\n}\n void sendFloat(float f)\n{\n messageStruct msg1, msg2;\n uint8_t array[4];\n\n toArray(f, array);\n\n msg1.p0 = 1; //1 means it's the first half\n msg1.p1 = array[0];\n msg1.p2 = array[1];\n\n msg2.p0 = 0; //0 means it's the second half\n msg2.p1 = array[2];\n msg2.p2 = array[3];\n\n sendOverRf(msg1);\n sendOverRf(msg2);\n}\n float retrieveFunc(void)\n{\n float f;\n unit8_t array[4]\n \n messageStruct msg = recieveOverRf();\n array[0] = msg.p1;\n array[1] = msg.p2;\n msg = receiveOverRf();\n array[2] = msg.p1;\n array[3] = msg.p2;\n return toFloat(array);\n}\n" }, { "answer_id": 74649677, "author": "Craig Estey", "author_id": 5382650, "author_profile": "https://Stackoverflow.com/users/5382650", "pm_score": 0, "selected": false, "text": "float uint32_t memcpy float void\nsendFloat(float f)\n{\n messageStruct msg;\n uint32_t i32;\n\n assert(sizeof(float) == sizeof(uint32_t));\n\n // get bytes of the float in native endian order\n memcpy(&i32,&f,sizeof(i32));\n\n // handle endianness\n i32 = htonl(i32);\n\n // send MSW half\n msg.p0 = 1;\n msg.p1 = i32 >> 24;\n msg.p2 = i32 >> 16;\n sendOverRf(msg);\n\n // send LSW half\n msg.p0 = 2;\n msg.p1 = i32 >> 8;\n msg.p2 = i32 >> 0;\n sendOverRf(msg);\n}\n\nfloat\nrecvFloat(void)\n{\n uint32_t i32 = 0;\n float f;\n\n messageStruct msg;\n\n // NOTE: the two packets _should_ come in the same order as the sender, but\n // we'll handle out of order packets to be complete\n for (int rcount = 0; rcount < 2; ++rcount) {\n msg = recieveOverRf();\n\n uint32_t tmp = msg.p1;\n tmp <<= 8;\n tmp |= msg.p2;\n\n switch (msg.p0) {\n case 1:\n i32 |= tmp << 16;\n break;\n case 2:\n i32 |= tmp << 0;\n break;\n }\n }\n\n // handle endianness\n i32 = ntohl(i32);\n\n // get bytes into float\n memcpy(&f,&i32,sizeof(float));\n\n return f;\n}\n void\nsendFloat(float f)\n{\n messageStruct msg;\n uint32_t i32;\n\n assert(sizeof(float) == sizeof(uint32_t));\n\n // get bytes of the float in native endian order\n memcpy(&i32,&f,sizeof(i32));\n\n // handle endianness\n i32 = htonl(i32);\n\n // means we're sending a float\n msg.p0 = CMD_FLOAT;\n msg.p1 = i32;\n msg.p2 = 0;\n\n sendOverRf(msg);\n}\n\nfloat\nrecvFloat(void)\n{\n uint32_t i32;\n float f;\n\n messageStruct msg = recieveOverRf();\n\n // ensure we got correct message\n if (msg.p0 != CMD_FLOAT)\n exit(1);\n\n // get int in network order\n i32 = msg.p1;\n\n // handle endianness\n i32 = ntohl(i32);\n\n // get bytes into float\n memcpy(&f,&i32,sizeof(float));\n\n return f;\n}\n" }, { "answer_id": 74649730, "author": "Jeremy Friesner", "author_id": 131930, "author_profile": "https://Stackoverflow.com/users/131930", "pm_score": 3, "selected": true, "text": "float #include <stdio.h>\n#include <stdint.h>\n\ntypedef union {\n uint8_t _asBytes[4];\n float _asFloat;\n} FloatBytesConverter;\n\nint main(int argc, char** argv)\n{\n FloatBytesConverter fbc;\n fbc._asFloat = 3.14159;\n\n printf(\"Original float value is: %f\\n\", fbc._asFloat);\n\n printf(\"The bytes of the float are: %u, %u, %u, %u\\n\"\n , fbc._asBytes[0]\n , fbc._asBytes[1]\n , fbc._asBytes[2]\n , fbc._asBytes[3]);\n\n // Now let's put the float back together from the individual bytes\n FloatBytesConverter ac;\n ac._asBytes[0] = fbc._asBytes[0];\n ac._asBytes[1] = fbc._asBytes[1];\n ac._asBytes[2] = fbc._asBytes[2];\n ac._asBytes[3] = fbc._asBytes[3];\n\n printf(\"Restored float is %f\\n\", ac._asFloat);\n\n return 0;\n}\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74649350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20660833/" ]
74,649,393
<p>I am trying to sum up two rows. I have a table1 as the below:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>MEASURES</th> <th>APR</th> <th>MAY</th> <th>JUN</th> <th>JUL</th> </tr> </thead> <tbody> <tr> <td>Measure 1</td> <td>61</td> <td>67</td> <td>79</td> <td>62</td> </tr> <tr> <td>Measure 2</td> <td>56</td> <td>75</td> <td>52</td> <td>70</td> </tr> </tbody> </table> </div> <p>I need to get the difference of the two rows as the below:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>MEASURES</th> <th>APR</th> <th>MAY</th> <th>JUN</th> <th>JUL</th> </tr> </thead> <tbody> <tr> <td>Total</td> <td>-5</td> <td>8</td> <td>-27</td> <td>8</td> </tr> </tbody> </table> </div> <p>I tried using the below statement:</p> <pre><code>SELECT TOP(1) 'DEFICIT' AS [MEASURES] APR - lag(APR, 1, 0) OVER (ORDER BY [MEASURES]) AS APR ,MAY - lag(MAY, 1, 0) OVER (ORDER BY [MEASURES]) AS MAY ,JUN - lag(JUN, 1, 0) OVER (ORDER BY [MEASURES]) AS JUN ,JUL - lag(JUL, 1, 0) OVER (ORDER BY [MEASURES]) AS JUL FROM table1 ORDER BY [MEASURES] DESC; </code></pre> <p>But doesn't result correctly. I am not sure how to get the difference. Can you please point me to some solution. Thanks in advance.</p>
[ { "answer_id": 74649419, "author": "Dale K", "author_id": 1127428, "author_profile": "https://Stackoverflow.com/users/1127428", "pm_score": 2, "selected": true, "text": "SELECT 'Total'\n , SUM(CASE WHEN MEASURES = 'Measure 2' THEN -1 ELSE 1 END * APR) APR\n , SUM(CASE WHEN MEASURES = 'Measure 2' THEN -1 ELSE 1 END * MAY) MAY\n , SUM(CASE WHEN MEASURES = 'Measure 2' THEN -1 ELSE 1 END * JUN) JUN\n , SUM(CASE WHEN MEASURES = 'Measure 2' THEN -1 ELSE 1 END * JUL) JUL\nFROM table1;\n" }, { "answer_id": 74649434, "author": "dobby", "author_id": 948979, "author_profile": "https://Stackoverflow.com/users/948979", "pm_score": 0, "selected": false, "text": "SUM GROUP BY SELECT SUM(APR), \n SUM(MAY), \n SUM(JUN), \n SUM(JUL)\nFROM table1\nGROUP BY 1\n GROUP BY 1 SUM -- Compute the difference between rows 1 and 2\nSELECT id,\n col1 - col1 AS col1,\n col2 - col2 AS col2,\n col3 - col3 AS col3,\n col4 - col4 AS col4\nFROM example_table\nWHERE id = 1\nUNION\nSELECT id,\n col1,\n col2,\n col3,\n col4\nFROM example_table\nWHERE id = 2;\n" }, { "answer_id": 74649462, "author": "kaispace30098", "author_id": 19854159, "author_profile": "https://Stackoverflow.com/users/19854159", "pm_score": -1, "selected": false, "text": "select 'Total' as Measure, sum(APR) as APR,sum(MAY) as MAY,sum(JUNE) as JUNE,sum(JULY) as JULY\nfrom table1;\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74649393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1342446/" ]
74,649,400
<p>I have a running master csv file with various data columns for 896 eucalypt species (i.e., 896 rows). I recently collected new columns of information in a separate data frame, but only for 474 of those 896 species. How do I add the new columns to the master data frame and make sure they are sorted into the correct rows?</p> <p>For example (but here I am adding 3 species' new data to a master dataset of 5 species, instead of 474 to 896): I would like to merge the following 2 data frames,</p> <pre><code>&gt; master Species Variable1 Variable2 1 regnans 400 0.1 2 cornuta 421 0.1 3 caesia 378 0.2 4 viminalis 397 0.3 5 plumula 401 0.1 </code></pre> <p>and</p> <pre><code>&gt; newdata Species NewVariable 1 regnans 5 2 viminalis 9 3 plumula 7 </code></pre> <p>into this:</p> <pre><code>&gt; master.updated Species Variable1 Variable2 NewVariable 1 regnans 400 0.1 5 2 cornuta 421 0.1 NA 3 caesia 378 0.2 NA 4 viminalis 397 0.3 9 5 plumula 401 0.1 7 </code></pre>
[ { "answer_id": 74649419, "author": "Dale K", "author_id": 1127428, "author_profile": "https://Stackoverflow.com/users/1127428", "pm_score": 2, "selected": true, "text": "SELECT 'Total'\n , SUM(CASE WHEN MEASURES = 'Measure 2' THEN -1 ELSE 1 END * APR) APR\n , SUM(CASE WHEN MEASURES = 'Measure 2' THEN -1 ELSE 1 END * MAY) MAY\n , SUM(CASE WHEN MEASURES = 'Measure 2' THEN -1 ELSE 1 END * JUN) JUN\n , SUM(CASE WHEN MEASURES = 'Measure 2' THEN -1 ELSE 1 END * JUL) JUL\nFROM table1;\n" }, { "answer_id": 74649434, "author": "dobby", "author_id": 948979, "author_profile": "https://Stackoverflow.com/users/948979", "pm_score": 0, "selected": false, "text": "SUM GROUP BY SELECT SUM(APR), \n SUM(MAY), \n SUM(JUN), \n SUM(JUL)\nFROM table1\nGROUP BY 1\n GROUP BY 1 SUM -- Compute the difference between rows 1 and 2\nSELECT id,\n col1 - col1 AS col1,\n col2 - col2 AS col2,\n col3 - col3 AS col3,\n col4 - col4 AS col4\nFROM example_table\nWHERE id = 1\nUNION\nSELECT id,\n col1,\n col2,\n col3,\n col4\nFROM example_table\nWHERE id = 2;\n" }, { "answer_id": 74649462, "author": "kaispace30098", "author_id": 19854159, "author_profile": "https://Stackoverflow.com/users/19854159", "pm_score": -1, "selected": false, "text": "select 'Total' as Measure, sum(APR) as APR,sum(MAY) as MAY,sum(JUNE) as JUNE,sum(JULY) as JULY\nfrom table1;\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74649400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10297843/" ]
74,649,421
<p>I need to write SQL query to output the Maximum number and Minimum number of movies produces by diffrent actors and actresses between year 1991 and 2001 <a href="https://i.stack.imgur.com/6rDap.png" rel="nofollow noreferrer">query written </a>. When I tried this, I got error <a href="https://i.stack.imgur.com/bBcOl.png" rel="nofollow noreferrer">enter image description here</a></p> <p>The expected result is to output the maximum numer each actor or atress produces within that year range <a href="https://i.stack.imgur.com/FD98m.png" rel="nofollow noreferrer">The result should look like this</a></p> <p>When I tried this, I got error <a href="https://i.stack.imgur.com/bBcOl.png" rel="nofollow noreferrer">what i tried </a></p> <p>The expected result is to output the maximum number each actor and atress produces within that year range <a href="https://i.stack.imgur.com/FD98m.png" rel="nofollow noreferrer">The result should look like this</a></p>
[ { "answer_id": 74649419, "author": "Dale K", "author_id": 1127428, "author_profile": "https://Stackoverflow.com/users/1127428", "pm_score": 2, "selected": true, "text": "SELECT 'Total'\n , SUM(CASE WHEN MEASURES = 'Measure 2' THEN -1 ELSE 1 END * APR) APR\n , SUM(CASE WHEN MEASURES = 'Measure 2' THEN -1 ELSE 1 END * MAY) MAY\n , SUM(CASE WHEN MEASURES = 'Measure 2' THEN -1 ELSE 1 END * JUN) JUN\n , SUM(CASE WHEN MEASURES = 'Measure 2' THEN -1 ELSE 1 END * JUL) JUL\nFROM table1;\n" }, { "answer_id": 74649434, "author": "dobby", "author_id": 948979, "author_profile": "https://Stackoverflow.com/users/948979", "pm_score": 0, "selected": false, "text": "SUM GROUP BY SELECT SUM(APR), \n SUM(MAY), \n SUM(JUN), \n SUM(JUL)\nFROM table1\nGROUP BY 1\n GROUP BY 1 SUM -- Compute the difference between rows 1 and 2\nSELECT id,\n col1 - col1 AS col1,\n col2 - col2 AS col2,\n col3 - col3 AS col3,\n col4 - col4 AS col4\nFROM example_table\nWHERE id = 1\nUNION\nSELECT id,\n col1,\n col2,\n col3,\n col4\nFROM example_table\nWHERE id = 2;\n" }, { "answer_id": 74649462, "author": "kaispace30098", "author_id": 19854159, "author_profile": "https://Stackoverflow.com/users/19854159", "pm_score": -1, "selected": false, "text": "select 'Total' as Measure, sum(APR) as APR,sum(MAY) as MAY,sum(JUNE) as JUNE,sum(JULY) as JULY\nfrom table1;\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74649421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20036774/" ]
74,649,437
<p>How to improve the following batch script by making so whenever a new script is added into the directory, it doesn't require to manually hardcode an extra line of code in script. like: <code>3) source $(pwd)/script-3.sh; myfunc;;</code></p> <p>script:</p> <pre><code>#Menu script title=&quot;Menu&quot; prompt=&quot;Pick an option(number): &quot; #options=( # &quot;script-1.sh&quot; \ # &quot;script-2.sh&quot; \ # &quot;script-3.sh&quot; \ # ) path=$(pwd) array=($path/*.sh) options=( &quot;${array[@]##*/}&quot; ) echo &quot;$title&quot; PS3=&quot;$prompt&quot; select opt in &quot;${options[@]}&quot; &quot;Quit&quot;; do case &quot;$REPLY&quot; in 1) source $(pwd)/script-1.sh; myfunc;; 2) source $(pwd)/script-2.sh; myfunc;; 3) source $(pwd)/script-3.sh; myfunc;; $((${#options[@]}+1))) echo &quot;Goodbye!&quot;; break;; *) echo &quot;Invalid option. Try another one.&quot;;continue;; esac done </code></pre> <h4>How to automate this part ?</h4> <pre><code>select opt in &quot;${options[@]}&quot; &quot;Quit&quot;; do case &quot;$REPLY&quot; in 1) source $(pwd)/script-1.sh; myfunc;; 2) source $(pwd)/script-2.sh; myfunc;; 3) source $(pwd)/script-3.sh; myfunc;; $((${#options[@]}+1))) echo &quot;Goodbye!&quot;; break;; *) echo &quot;Invalid option. Try another one.&quot;;continue;; esac done </code></pre> <p>this is the current manual part, where need to be hard-coded a value everytime a new script is added.</p> <p>for example, lets say I added a new script called&quot; <code>script-99.sh</code></p> <p>then it would need to hardcode it in the main script like this:</p> <pre><code> case &quot;$REPLY&quot; in 1) source $(pwd)/script-1.sh; myfunc;; 2) source $(pwd)/script-2.sh; myfunc;; 3) source $(pwd)/script-3.sh; myfunc;; 4) source $(pwd)/script-99.sh; myfunc;; ##Had to hardcode this line </code></pre>
[ { "answer_id": 74650736, "author": "Peter", "author_id": 11865845, "author_profile": "https://Stackoverflow.com/users/11865845", "pm_score": 0, "selected": false, "text": "select opt in \"${options[@]}\" \"Quit\"; do \n source $(pwd)/$opt; myfunc\ndone\n $((${#options[@]}+1))) echo \"Goodbye!\"; break;;\n *) echo \"Invalid option. Try another one.\";continue;;\n" }, { "answer_id": 74652374, "author": "user1934428", "author_id": 1934428, "author_profile": "https://Stackoverflow.com/users/1934428", "pm_score": 2, "selected": true, "text": "select opt in \"${options[@]}\" \"Quit\"; do\n script=script-$REPLY.sh\n if [[ -f $script ]]\n then\n source $script\n else\n echo Goodbye\n break\n fi\ndone\n quitstring=Quit\nselect opt in \"${options[@]}\" $quitstring; do\n [[ $opt == $quitstring ]] && break\n source $opt\ndone\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74649437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11865845/" ]
74,649,453
<p>I was wondering if there is a way or a resource I could refer to in order to achieve a side effect on a <code>LazyRow</code> when an item is scrolled? The side effect is basically to call a function in the viewModel to alter the state of the list's state.</p> <ul> <li>The side effect should be only executed only if the current firstVisibleItemIndex after</li> <li>scroll is different than before The side effect should not be executed the item is not fully scrolled I am implementing a fullscreen <code>LazyRow</code> items with a snap behavior</li> </ul> <p>So far I have tried <code>NestedScrollConnection</code></p> <pre class="lang-kotlin prettyprint-override"><code>class OnMoodItemScrolled : NestedScrollConnection { override suspend fun onPostFling(consumed: Velocity, available: Velocity): Velocity { viewModel.fetchItems() return super.onPostFling(consumed, available) } } </code></pre> <p>The issue with the above is that the side effect is going to be executed anyway even-though the item displayed after the scroll is the same as before the scroll.</p> <p>I also tried to collecting the listState interaction as the following</p> <pre class="lang-kotlin prettyprint-override"><code>val firstVisibleItem: Int = remember { sectionItemListState.firstVisibleItemIndex } sectionItemListState.interactionSource.collectIsDraggedAsState().let { if (firstVisibleItem != sectionItemListState.firstVisibleItemIndex) { viewModel.fetchItems() } } </code></pre> <p>The issue with the above is that the side effect is going to be executed the second the composable is composed for the first time.</p>
[ { "answer_id": 74653191, "author": "Gabriele Mariotti", "author_id": 2016562, "author_profile": "https://Stackoverflow.com/users/2016562", "pm_score": 2, "selected": false, "text": "LazyListState#firstVisibleItemIndex @Composable\nprivate fun LazyListState.itemIndexScrolledUp(): Int {\n var previousIndex by remember(this) { mutableStateOf(firstVisibleItemIndex) }\n return remember(this) {\n derivedStateOf {\n if (firstVisibleItemIndex > previousIndex) {\n //scrolling up\n previousIndex\n } else {\n - 1\n }.also {\n //Update the previous index\n previousIndex = firstVisibleItemIndex\n }\n }\n }.value\n}\n val state = rememberLazyListState()\nvar index = state.itemIndexScrolledUp()\n\nDisposableEffect(index){\n\n if (index != -1) {\n //...item is scrolled up\n }\n\n onDispose { } \n}\n\n\nLazyColumn(\n state = state,\n){\n //...\n}\n" }, { "answer_id": 74655143, "author": "AouledIssa", "author_id": 2057782, "author_profile": "https://Stackoverflow.com/users/2057782", "pm_score": 2, "selected": false, "text": "LaunchedEffect val sectionItemListState = rememberLazyListState()\nval flingBehavior = rememberSnapFlingBehavior(sectionItemListState)\nvar previousVisibleItemIndex by remember {\n mutableStateOf(0)\n}\nval currentVisibleItemIndex: Int by remember {\n derivedStateOf { sectionItemListState.firstVisibleItemIndex }\n}\nval currentVisibleItemScrollOffset: Int by remember {\n derivedStateOf { sectionItemListState.firstVisibleItemScrollOffset }\n}\n\nLaunchedEffect(currentVisibleItemIndex, currentVisibleItemScrollOffset) {\n if (previousVisibleItemIndex != currentVisibleItemIndex && currentVisibleItemScrollOffset == 0) {\n // The currentVisible item is different than the previous one && it's fully visible\n viewModel.fetchItems()\n previousVisibleItemIndex = currentVisibleItemIndex\n }\n}\n currentVisibleItemIndex currentVisibleItemScrollOffset LaunchedEffect previousVisibleItemIndex currentVisibleItemIndex scrollOffset" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74649453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2057782/" ]
74,649,471
<p>I have written a python for loop iteration as show below. I was wondering if its possible to convert into a recursive function.</p> <pre><code>a = int(input(&quot;Please enter the first number: &quot;)) b = int(input(&quot;Please enter the second number: &quot;)) res = 0 for i in range(a,b+1): temp = 1 for j in range(1,i+1): temp = temp * j res = res + temp print(&quot;Sum of products from 1 to each integer in the range &quot;,a,&quot; to &quot;,b,&quot; is: &quot;,res) </code></pre> <p>I am expecting something like the below example:</p> <pre><code>def recursion(a,b): res = 0 if condition or a while condtion .... return .... a = int(input(&quot;Please enter the first number: &quot;)) b = int(input(&quot;Please enter the second number: &quot;)) print(&quot;Sum of products from 1 to each integer in the range &quot;,a,&quot; to &quot;,b,&quot; is: &quot;,res) </code></pre> <p>Any idea ?</p>
[ { "answer_id": 74653191, "author": "Gabriele Mariotti", "author_id": 2016562, "author_profile": "https://Stackoverflow.com/users/2016562", "pm_score": 2, "selected": false, "text": "LazyListState#firstVisibleItemIndex @Composable\nprivate fun LazyListState.itemIndexScrolledUp(): Int {\n var previousIndex by remember(this) { mutableStateOf(firstVisibleItemIndex) }\n return remember(this) {\n derivedStateOf {\n if (firstVisibleItemIndex > previousIndex) {\n //scrolling up\n previousIndex\n } else {\n - 1\n }.also {\n //Update the previous index\n previousIndex = firstVisibleItemIndex\n }\n }\n }.value\n}\n val state = rememberLazyListState()\nvar index = state.itemIndexScrolledUp()\n\nDisposableEffect(index){\n\n if (index != -1) {\n //...item is scrolled up\n }\n\n onDispose { } \n}\n\n\nLazyColumn(\n state = state,\n){\n //...\n}\n" }, { "answer_id": 74655143, "author": "AouledIssa", "author_id": 2057782, "author_profile": "https://Stackoverflow.com/users/2057782", "pm_score": 2, "selected": false, "text": "LaunchedEffect val sectionItemListState = rememberLazyListState()\nval flingBehavior = rememberSnapFlingBehavior(sectionItemListState)\nvar previousVisibleItemIndex by remember {\n mutableStateOf(0)\n}\nval currentVisibleItemIndex: Int by remember {\n derivedStateOf { sectionItemListState.firstVisibleItemIndex }\n}\nval currentVisibleItemScrollOffset: Int by remember {\n derivedStateOf { sectionItemListState.firstVisibleItemScrollOffset }\n}\n\nLaunchedEffect(currentVisibleItemIndex, currentVisibleItemScrollOffset) {\n if (previousVisibleItemIndex != currentVisibleItemIndex && currentVisibleItemScrollOffset == 0) {\n // The currentVisible item is different than the previous one && it's fully visible\n viewModel.fetchItems()\n previousVisibleItemIndex = currentVisibleItemIndex\n }\n}\n currentVisibleItemIndex currentVisibleItemScrollOffset LaunchedEffect previousVisibleItemIndex currentVisibleItemIndex scrollOffset" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74649471", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20661176/" ]
74,649,484
<p>I was given a function that I have to fill out and it has these input parameters:</p> <pre class="lang-c prettyprint-override"><code>char * replace( const char * text, const char * (*word)[2] ) </code></pre> <p>From my understanding, the function should return a string and is given a string in the first parameter.</p> <p>The second parameter is an array of subarray that each have 2 strings if I'm not mistaken, but what is the meaning of the <code>*(*name)[2]</code>, what is the difference between that and <code>**name[2]</code> And how would I call this array in the function?</p> <p>EDIT: How do I <strong>use</strong> this array in the function?</p>
[ { "answer_id": 74653191, "author": "Gabriele Mariotti", "author_id": 2016562, "author_profile": "https://Stackoverflow.com/users/2016562", "pm_score": 2, "selected": false, "text": "LazyListState#firstVisibleItemIndex @Composable\nprivate fun LazyListState.itemIndexScrolledUp(): Int {\n var previousIndex by remember(this) { mutableStateOf(firstVisibleItemIndex) }\n return remember(this) {\n derivedStateOf {\n if (firstVisibleItemIndex > previousIndex) {\n //scrolling up\n previousIndex\n } else {\n - 1\n }.also {\n //Update the previous index\n previousIndex = firstVisibleItemIndex\n }\n }\n }.value\n}\n val state = rememberLazyListState()\nvar index = state.itemIndexScrolledUp()\n\nDisposableEffect(index){\n\n if (index != -1) {\n //...item is scrolled up\n }\n\n onDispose { } \n}\n\n\nLazyColumn(\n state = state,\n){\n //...\n}\n" }, { "answer_id": 74655143, "author": "AouledIssa", "author_id": 2057782, "author_profile": "https://Stackoverflow.com/users/2057782", "pm_score": 2, "selected": false, "text": "LaunchedEffect val sectionItemListState = rememberLazyListState()\nval flingBehavior = rememberSnapFlingBehavior(sectionItemListState)\nvar previousVisibleItemIndex by remember {\n mutableStateOf(0)\n}\nval currentVisibleItemIndex: Int by remember {\n derivedStateOf { sectionItemListState.firstVisibleItemIndex }\n}\nval currentVisibleItemScrollOffset: Int by remember {\n derivedStateOf { sectionItemListState.firstVisibleItemScrollOffset }\n}\n\nLaunchedEffect(currentVisibleItemIndex, currentVisibleItemScrollOffset) {\n if (previousVisibleItemIndex != currentVisibleItemIndex && currentVisibleItemScrollOffset == 0) {\n // The currentVisible item is different than the previous one && it's fully visible\n viewModel.fetchItems()\n previousVisibleItemIndex = currentVisibleItemIndex\n }\n}\n currentVisibleItemIndex currentVisibleItemScrollOffset LaunchedEffect previousVisibleItemIndex currentVisibleItemIndex scrollOffset" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74649484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18361723/" ]
74,649,522
<pre><code>def prodListePos_rec(l, len(l)): if (len(l)&gt;0): if l[len(l)-1] &gt; 0: product = prodListePos_rec(l,len(l)) * l[len(l)-1] else: product = 1 return product l = [1,-2, 5, 0, 6,-5] prodListePos_rec(l,len(l)) </code></pre> <p>I don't get why it shows the invalid syntax and what should I do if I want to call the <code>len()</code> as a recursion function?</p>
[ { "answer_id": 74649658, "author": "wjandrea", "author_id": 4518341, "author_profile": "https://Stackoverflow.com/users/4518341", "pm_score": 2, "selected": false, "text": "l len(l) l 1 I lst len() def prodListePos_rec(lst):\n n = len(lst)\n if n > 0:\n x = lst[n-1]\n if x > 0:\n product = prodListePos_rec(lst) * x\n else:\n product = 1\n return product\n\nlst = [1, -2, 5, 0, 6, -5]\nprodListePos_rec(lst)\n n > 0 x <= 0 product Traceback (most recent call last):\n File \"/home/wja/testdir/tmp.py\", line 13, in <module>\n prodListePos_rec(lst)\n File \"/home/wja/testdir/tmp.py\", line 10, in prodListePos_rec\n return product\nUnboundLocalError: local variable 'product' referenced before assignment\n" }, { "answer_id": 74649674, "author": "puf", "author_id": 6583203, "author_profile": "https://Stackoverflow.com/users/6583203", "pm_score": 0, "selected": false, "text": "l l len(l) def prodListePos_rec(l, len_l):\n if (len_l>0):\n if l[len_l-1] > 0:\n product = prodListePos_rec(l,len_l) * l[len_l-1]\n else:\n product = 1 \n return product\n\np = [1,-2, 5, 0, 6,-5]\nprodListePos_rec(p,len(p)) \n len_l l p def prodListePos_rec(l):\n if (len(l)>0):\n if l[len(l)-1] > 0:\n product = prodListePos_rec(l,len(l)) * l[len(l)-1]\n else:\n product = 1 \n return product\n\np = [1,-2, 5, 0, 6,-5]\nprodListePos_rec(p) \n len(l)" }, { "answer_id": 74649806, "author": "rishabh11336", "author_id": 15002598, "author_profile": "https://Stackoverflow.com/users/15002598", "pm_score": 0, "selected": false, "text": "def prodListePos_rec(l, len_of_l):\n product = 1\n if (len_of_l)>0):\n if l[len_of_l)-1] > 0:\n product = prodListePos_rec(l,len_of_l)) * l[len_of_l)-1] \n return product\n\nl = [1,-2, 5, 0, 6,-5]\nprint(prodListePos_rec(l,len(l)))\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74649522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20661222/" ]
74,649,535
<p>I try to redirect <code>domain.tld/?cur=usd</code> to <code>domain.tld</code> (there are many curencies, this is only example of one currency - we do not use anymore this solution). I need to redirect only home with parameter to home without parameter. The other urls worked for me, I'm just having trouble getting work with that one.</p> <p>I try to search and use online generators but none of the solutions work. Here is what I am trying:</p> <pre><code>RewriteCond %{QUERY_STRING} (^|&amp;)cur\=(.*)($|&amp;) RewriteRule ^$ /? [L,R=301] </code></pre> <p>// update before this rule I have only</p> <pre><code>#bof redirects RewriteEngine enabled </code></pre> <p>...and then there are redirects for other URLs, but I tested this rule separately first and the result was the same...</p> <p>It not redirect me. Thanks for the help and maybe an explanation of what I'm doing wrong.</p>
[ { "answer_id": 74649658, "author": "wjandrea", "author_id": 4518341, "author_profile": "https://Stackoverflow.com/users/4518341", "pm_score": 2, "selected": false, "text": "l len(l) l 1 I lst len() def prodListePos_rec(lst):\n n = len(lst)\n if n > 0:\n x = lst[n-1]\n if x > 0:\n product = prodListePos_rec(lst) * x\n else:\n product = 1\n return product\n\nlst = [1, -2, 5, 0, 6, -5]\nprodListePos_rec(lst)\n n > 0 x <= 0 product Traceback (most recent call last):\n File \"/home/wja/testdir/tmp.py\", line 13, in <module>\n prodListePos_rec(lst)\n File \"/home/wja/testdir/tmp.py\", line 10, in prodListePos_rec\n return product\nUnboundLocalError: local variable 'product' referenced before assignment\n" }, { "answer_id": 74649674, "author": "puf", "author_id": 6583203, "author_profile": "https://Stackoverflow.com/users/6583203", "pm_score": 0, "selected": false, "text": "l l len(l) def prodListePos_rec(l, len_l):\n if (len_l>0):\n if l[len_l-1] > 0:\n product = prodListePos_rec(l,len_l) * l[len_l-1]\n else:\n product = 1 \n return product\n\np = [1,-2, 5, 0, 6,-5]\nprodListePos_rec(p,len(p)) \n len_l l p def prodListePos_rec(l):\n if (len(l)>0):\n if l[len(l)-1] > 0:\n product = prodListePos_rec(l,len(l)) * l[len(l)-1]\n else:\n product = 1 \n return product\n\np = [1,-2, 5, 0, 6,-5]\nprodListePos_rec(p) \n len(l)" }, { "answer_id": 74649806, "author": "rishabh11336", "author_id": 15002598, "author_profile": "https://Stackoverflow.com/users/15002598", "pm_score": 0, "selected": false, "text": "def prodListePos_rec(l, len_of_l):\n product = 1\n if (len_of_l)>0):\n if l[len_of_l)-1] > 0:\n product = prodListePos_rec(l,len_of_l)) * l[len_of_l)-1] \n return product\n\nl = [1,-2, 5, 0, 6,-5]\nprint(prodListePos_rec(l,len(l)))\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74649535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3237083/" ]
74,649,536
<p>I tried to sorting upper case and lower case in the perl language. A bunch of text are save in as &quot;electricity.txt&quot; in the .txt file:</p> <blockquote> <p>Today's scientific question is: What in the world is electricity and where does it go after it leaves the toaster?</p> <p>Here is a simple experiment that will teach you an important electrical lesson: On a cool dry day, scuff your feet along a carpet, then reach your hand into a friend's mouth and touch one of his dental fillings. Did you notice how your friend twitched violently and cried out in pain? This teaches one that electricity can be a very powerful force, but we must never use it to hurt others unless we need to learn an important lesson about electricity.</p> </blockquote> <p>Somehow, I can't get any uppercase word and my code is</p> <pre><code>my %count; my $openFileile = &quot;electricity.txt&quot;; open my $openFile, '&lt;', $openFileile; while (my $list = &lt;$openFile&gt;) { chomp $list; foreach my $word (split /\s+/, $list) { $count{lc($word)}++; } } </code></pre> <pre><code>printf &quot;\n\nSorting Alphabetically with upper case words in front of lower-case words with the same initial characters\n&quot;; foreach my $word (sort keys %count){ printf &quot;%-31s \n&quot;, sort {&quot;\$a&quot; cmp uc&quot;\$b&quot;} lc($word); } </code></pre>
[ { "answer_id": 74653205, "author": "pmqs", "author_id": 2030808, "author_profile": "https://Stackoverflow.com/users/2030808", "pm_score": 2, "selected": false, "text": "$count{lc($word)}++;\n while %count foreach printf \"%-31s \\n\", sort {\"\\$a\" cmp uc\"\\$b\"} lc($word);\n sort lc($word) use strict;\nuse warnings;\n\nmy %count;\n#my $openFileile = \"electricity.txt\";\n#open my $openFile, '<', $openFileile;\nwhile (my $list = <DATA>) {\n chomp $list;\n foreach my $word (split /\\s+/, $list) {\n $count{$word}++;\n }\n}\n\nprintf \"\\n\\nSorting Alphabetically with upper case words in front of lower-case words with the same initial characters\\n\";\nforeach my $word (sort keys %count){\n printf \"%-31s \\n\", $word;\n\n}\n__DATA__\nToday's scientific question is: What in the world is electricity and where does it go after it leaves the toaster?\n\nHere is a simple experiment that will teach you an important electrical lesson: On a cool dry day, scuff your feet along a carpet, then reach your hand into a friend's mouth and touch one of his dental fillings. Did you notice how your friend twitched violently and cried out in pain? This teaches one that electricity can be a very powerful force, but we must never use it to hurt others unless we need to learn an important lesson about electricity.\n Sorting Alphabetically with upper case words in front of lower-case words with the same initial characters\nDid \nHere \nOn \nThis \nToday's \nWhat \na \nabout \nafter \nalong \n...\nuse \nvery \nviolently \nwe \nwhere \nwill \nworld \nyou \n\n" }, { "answer_id": 74653496, "author": "TLP", "author_id": 725418, "author_profile": "https://Stackoverflow.com/users/725418", "pm_score": 2, "selected": false, "text": "lc use strict; use warnings open my $openFile, '<', $openFileile;\n open ..., or die \"Cannot open '$openFileile': $!\" foreach my $word (split /\\s+/, $list) {\n ' ' split \\s+ $count{lc($word)}++;\n printf \"\\n\\nSorting Alphabetically with upper case words in front of lower-case words with the same initial characters\\n\";\n printf print printf \"%-31s \\n\", sort {\"\\$a\" cmp uc\"\\$b\"} lc($word);\n \"\\$a\" $a print \"\\$a is $a\" $a is 12 lc lc uc uc sort ucfirst DATA use strict;\nuse warnings;\n\nmy %words;\nwhile (my $line = <DATA>) {\n for my $word (split ' ', $line) { # split on ' ' a single space removes leading and trailing whitespace\n my $key = lc $word; # save lowercase word as key \n $words{$key}{count}++; # separate count \n $words{$key}{value} = $word; # word original formatting as value\n }\n}\n\n# printf is used for special formatting, if you are not using that formatting, use regular print to avoid unnecessary interpolation of %\nprint \"\\nSorting Alphabetically with upper case words in front of lower-case words with the same initial characters\\n\";\nfor my $word (sort keys %words) {\n printf \"%-31s : %s\\n\", $words{$word}{value}, $words{$word}{count};\n}\n\n__DATA__\nToday's scientific question is: What in the world is electricity and where does it go after it leaves the toaster?\nHere is a simple experiment that will teach you an important electrical lesson: On a cool dry day, scuff your feet along a carpet, then reach your hand into a friend's mouth and touch one of his dental fillings. Did you notice how your friend twitched violently and cried out in pain? This teaches one that electricity can be a very powerful force, but we must never use it to hurt others unless we need to learn an important lesson about electricity.\n a : 5\nabout : 1\nafter : 1\nalong : 1\nan : 2\nand : 3\nbe : 1\nbut : 1\ncan : 1\ncarpet, : 1\ncool : 1\n...etc\n carpet carpet, my @words = $line =~ /\\w+/g; # \\w is word characters, plus numbers, and underscore _\n /[\\w\\-]+/ mega-carpet - a-z" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74649536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18703242/" ]
74,649,538
<p>Suppose I have a <code>char</code> in the variable <code>c</code> and a positive <code>int</code> in the variable <code>n</code>. I want to build the <code>str</code> containing <code>c</code> occurring <code>n</code> times. How can I do it?</p> <p>I tried building it as a <code>String</code>, and maybe I just got dizzy trying to read the documentation on strings, but I couldn't see how to convert it to a <code>str</code>. But then if I'm trying to just build it as a <code>str</code> directly then I couldn't see how to do that either.</p> <p>For context, here is the full function I'm trying to implement. It takes a string and finds the longest sequence of consecutive characters (and breaks ties by taking the first that occurs).</p> <pre><code>pub fn longest_sequence(s: &amp;str) -&gt; Option&lt;&amp;str&gt; { if s.len() == 0 { return None; } let mut current_c = s.as_bytes()[0] as char; let mut greatest_c = s.as_bytes()[0] as char; let mut current_num = 0; let mut greatest_num = 0; for ch in s.chars() { if current_c == ch { current_num += 1; if current_num &gt; greatest_num { greatest_num = current_num; greatest_c = current_c; } } else { current_num = 1; current_c = ch; } } // Now build the output str ... } </code></pre>
[ { "answer_id": 74651729, "author": "Miiao", "author_id": 20028181, "author_profile": "https://Stackoverflow.com/users/20028181", "pm_score": -1, "selected": false, "text": "String &'static str fn leak(s: String) -> &'static str {\n let ptr = s.as_str() as *const str;\n core::mem::forget(s);\n unsafe {&*ptr}\n}\n char String fn cts(c: char, n: usize) -> String {\n (0..n)\n .map(|_| c)\n .collect()\n}\n char &'static str fn conv(c: char, n: usize) -> &'static str {\n leak(cts(c, n))\n}\n String" }, { "answer_id": 74652051, "author": "Finomnis", "author_id": 2902833, "author_profile": "https://Stackoverflow.com/users/2902833", "pm_score": 3, "selected": true, "text": "str String str &str Box<str> *str &str String String String &str String &str &str &str String s.as_bytes()[0] as char pub fn longest_sequence(s: &str) -> Option<&str> {\n let mut current_c = s.chars().next()?;\n let mut current_start = 0;\n let mut current_len = 0;\n let mut greatest: &str = \"\";\n let mut greatest_len = 0;\n for (pos, ch) in s.char_indices() {\n if current_c == ch {\n current_len += 1;\n } else {\n if greatest_len < current_len {\n greatest = &s[current_start..pos];\n greatest_len = current_len;\n }\n\n current_len = 1;\n current_c = ch;\n current_start = pos;\n }\n }\n\n if greatest_len < current_len {\n greatest = &s[current_start..];\n }\n\n Some(greatest)\n}\n\npub fn main() {\n let s = \"€€\";\n\n let seq = longest_sequence(s);\n println!(\"{:?}\", seq);\n}\n Some(\"\")\n s.chars().next()? s.chars().next() s.as_bytes()[0] as char greatest_len greatest.len() greatest.len() &s[current_start..current_start+current_len] &s[ .. ] current_len pub fn longest_sequence(s: &str) -> Option<String> {\n let mut current_c = s.chars().next()?;\n let mut greatest_c = current_c;\n let mut current_num = 0;\n let mut greatest_num = 0;\n for ch in s.chars() {\n if current_c == ch {\n current_num += 1;\n if current_num > greatest_num {\n greatest_num = current_num;\n greatest_c = current_c;\n }\n } else {\n current_num = 1;\n current_c = ch;\n }\n }\n\n // Build the output String\n Some(std::iter::repeat(greatest_c).take(greatest_num).collect())\n}\n\npub fn main() {\n let s = \"€€\";\n\n let seq = longest_sequence(s);\n println!(\"{:?}\", seq);\n}\n Some(\"\")\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74649538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3047729/" ]
74,649,540
<p>Currently, I have a radial-gradient as my background with a blur effect. Without a scale effect, it has white edges around the entire gradient. To combat this, I scaled the entire gradient, which works great, except for the fact it extends the page to the right, and allows the user to scroll left and right.</p> <p>Here is the relevant code:</p> <pre class="lang-css prettyprint-override"><code>.gradient{ height: 75%; width: 100%; background: radial-gradient(62.61% 62.61% at 95.23% 6.02%, #160E71 0%, rgba(19, 13, 92, 0.26) 54.71%, rgba(90, 35, 248, 0) 100%), linear-gradient(72.48deg, #EF516D 2.61%, rgba(106, 103, 227, 0) 56.18%), radial-gradient(45.23% 45.23% at 35.11% -11.02%, #7936AE 0%, rgba(121, 54, 174, 0) 100%), radial-gradient(94.51% 124.88% at 94.32% 94.43%, rgba(65, 244, 255, 0.78) 0%, rgba(131, 218, 255, 0.6552) 32.29%, rgba(99, 175, 240, 0.3978) 64.06%, rgba(43, 90, 211, 0) 100%), linear-gradient(313.04deg, #341D65 0.93%, #604AEA 125.68%); background-blend-mode: normal, normal, normal, normal, normal, normal; filter: blur(100px); transform: scale(1.4); /* overflow: hidden; */ /* background-size: cover; */ background-clip: padding-box; z-index: 1; left: 0; right: 0; position: absolute; } </code></pre> <pre class="lang-css prettyprint-override"><code>.welcome-box { height: 75%; overflow: hidden; } </code></pre> <pre class="lang-html prettyprint-override"><code>&lt;div class=&quot;welcome-box&quot;&gt; &lt;div class=&quot;gradient&quot;&gt;&lt;/div&gt; &lt;div class=&quot;welcome-box-content&quot;&gt; &lt;p class=&quot;welcome-subheader&quot; style=&quot;font-style: italic&quot;&gt;hi there,&lt;/p&gt; &lt;h1 class=&quot;welcome-header&quot;&gt;I'm Mason Thomas!&lt;/h1&gt; &lt;p class=&quot;welcome-subheader&quot;&gt;Connect with me!&lt;/p&gt; &lt;a href=&quot;https://github.com/Kandles11&quot;&gt;&lt;img src=&quot;assets/github.svg&quot; alt=&quot;github logo&quot; height=&quot;35&quot; class=&quot;logo&quot; /&gt;&lt;/a&gt; &lt;a href=&quot;https://www.linkedin.com/in/mason-thomas-ba1a891a1&quot;&gt;&lt;img src=&quot;assets/linkedin.svg&quot; alt=&quot;linkedin logo&quot; height=&quot;35&quot; class=&quot;logo&quot; /&gt;&lt;/a&gt; &lt;a href=&quot;mailto: mason@masongthomas.com&quot;&gt;&lt;img src=&quot;assets/email.svg&quot; alt=&quot;linkedin logo&quot; height=&quot;35&quot; class=&quot;logo&quot; /&gt;&lt;/a&gt; &lt;a href=&quot;/resume/resume.pdf&quot;&gt;&lt;img src=&quot;assets/resume.svg&quot; alt=&quot;linkedin logo&quot; height=&quot;35&quot; class=&quot;logo&quot; /&gt;&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>neither the <code>background-size</code> or <code>overflow</code> attribute have an effect.</p> <p>How can I make the gradient background fit the size of the page with the scaled effect? If this is not possible, how can I remove the white edges of the gradient background without the scaling effect? Thank you!</p> <p>Here is a video of the problem: <a href="https://imgur.com/O9OahhC" rel="nofollow noreferrer">https://imgur.com/O9OahhC</a></p>
[ { "answer_id": 74651729, "author": "Miiao", "author_id": 20028181, "author_profile": "https://Stackoverflow.com/users/20028181", "pm_score": -1, "selected": false, "text": "String &'static str fn leak(s: String) -> &'static str {\n let ptr = s.as_str() as *const str;\n core::mem::forget(s);\n unsafe {&*ptr}\n}\n char String fn cts(c: char, n: usize) -> String {\n (0..n)\n .map(|_| c)\n .collect()\n}\n char &'static str fn conv(c: char, n: usize) -> &'static str {\n leak(cts(c, n))\n}\n String" }, { "answer_id": 74652051, "author": "Finomnis", "author_id": 2902833, "author_profile": "https://Stackoverflow.com/users/2902833", "pm_score": 3, "selected": true, "text": "str String str &str Box<str> *str &str String String String &str String &str &str &str String s.as_bytes()[0] as char pub fn longest_sequence(s: &str) -> Option<&str> {\n let mut current_c = s.chars().next()?;\n let mut current_start = 0;\n let mut current_len = 0;\n let mut greatest: &str = \"\";\n let mut greatest_len = 0;\n for (pos, ch) in s.char_indices() {\n if current_c == ch {\n current_len += 1;\n } else {\n if greatest_len < current_len {\n greatest = &s[current_start..pos];\n greatest_len = current_len;\n }\n\n current_len = 1;\n current_c = ch;\n current_start = pos;\n }\n }\n\n if greatest_len < current_len {\n greatest = &s[current_start..];\n }\n\n Some(greatest)\n}\n\npub fn main() {\n let s = \"€€\";\n\n let seq = longest_sequence(s);\n println!(\"{:?}\", seq);\n}\n Some(\"\")\n s.chars().next()? s.chars().next() s.as_bytes()[0] as char greatest_len greatest.len() greatest.len() &s[current_start..current_start+current_len] &s[ .. ] current_len pub fn longest_sequence(s: &str) -> Option<String> {\n let mut current_c = s.chars().next()?;\n let mut greatest_c = current_c;\n let mut current_num = 0;\n let mut greatest_num = 0;\n for ch in s.chars() {\n if current_c == ch {\n current_num += 1;\n if current_num > greatest_num {\n greatest_num = current_num;\n greatest_c = current_c;\n }\n } else {\n current_num = 1;\n current_c = ch;\n }\n }\n\n // Build the output String\n Some(std::iter::repeat(greatest_c).take(greatest_num).collect())\n}\n\npub fn main() {\n let s = \"€€\";\n\n let seq = longest_sequence(s);\n println!(\"{:?}\", seq);\n}\n Some(\"\")\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74649540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10920201/" ]
74,649,544
<p>How to make the parent layout - <code>Box</code> wrap its content in Jetpack compose? The current implementation below fills the entire screen, I only want the <code>Box</code> to wrap around its child - <code>Switch</code>. How do I define <em>wrap content</em> for the <code>Box</code>?</p> <pre><code>@Composable fun TestScreen(modifier: Modifier = Modifier) { Box(modifier = Modifier.background(Color.Yellow)){ val switchState = remember { mutableStateOf(true) } Switch( checked = switchState.value, enabled= true, onCheckedChange = { switchState.value = it } ) } } </code></pre> <p><a href="https://i.stack.imgur.com/r8Fzu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/r8Fzu.png" alt="A Switch inside a Box" /></a></p>
[ { "answer_id": 74651729, "author": "Miiao", "author_id": 20028181, "author_profile": "https://Stackoverflow.com/users/20028181", "pm_score": -1, "selected": false, "text": "String &'static str fn leak(s: String) -> &'static str {\n let ptr = s.as_str() as *const str;\n core::mem::forget(s);\n unsafe {&*ptr}\n}\n char String fn cts(c: char, n: usize) -> String {\n (0..n)\n .map(|_| c)\n .collect()\n}\n char &'static str fn conv(c: char, n: usize) -> &'static str {\n leak(cts(c, n))\n}\n String" }, { "answer_id": 74652051, "author": "Finomnis", "author_id": 2902833, "author_profile": "https://Stackoverflow.com/users/2902833", "pm_score": 3, "selected": true, "text": "str String str &str Box<str> *str &str String String String &str String &str &str &str String s.as_bytes()[0] as char pub fn longest_sequence(s: &str) -> Option<&str> {\n let mut current_c = s.chars().next()?;\n let mut current_start = 0;\n let mut current_len = 0;\n let mut greatest: &str = \"\";\n let mut greatest_len = 0;\n for (pos, ch) in s.char_indices() {\n if current_c == ch {\n current_len += 1;\n } else {\n if greatest_len < current_len {\n greatest = &s[current_start..pos];\n greatest_len = current_len;\n }\n\n current_len = 1;\n current_c = ch;\n current_start = pos;\n }\n }\n\n if greatest_len < current_len {\n greatest = &s[current_start..];\n }\n\n Some(greatest)\n}\n\npub fn main() {\n let s = \"€€\";\n\n let seq = longest_sequence(s);\n println!(\"{:?}\", seq);\n}\n Some(\"\")\n s.chars().next()? s.chars().next() s.as_bytes()[0] as char greatest_len greatest.len() greatest.len() &s[current_start..current_start+current_len] &s[ .. ] current_len pub fn longest_sequence(s: &str) -> Option<String> {\n let mut current_c = s.chars().next()?;\n let mut greatest_c = current_c;\n let mut current_num = 0;\n let mut greatest_num = 0;\n for ch in s.chars() {\n if current_c == ch {\n current_num += 1;\n if current_num > greatest_num {\n greatest_num = current_num;\n greatest_c = current_c;\n }\n } else {\n current_num = 1;\n current_c = ch;\n }\n }\n\n // Build the output String\n Some(std::iter::repeat(greatest_c).take(greatest_num).collect())\n}\n\npub fn main() {\n let s = \"€€\";\n\n let seq = longest_sequence(s);\n println!(\"{:?}\", seq);\n}\n Some(\"\")\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74649544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4192614/" ]
74,649,564
<p><a href="https://i.stack.imgur.com/ze1tx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ze1tx.png" alt="enter image description here" /></a></p> <p>I can't seem to figure out why I can't get the information out of the array</p> <pre><code>const usedPlatformLog: Date[] = [] users.forEach(el =&gt; { usedPlatformLog.push(el.lastUsed) }) console.log(usedPlatformLog) // shows array with indexes 0 and 1 (picture attached) console.log(usedPlatformLog[0]) // log response undefined </code></pre>
[ { "answer_id": 74651729, "author": "Miiao", "author_id": 20028181, "author_profile": "https://Stackoverflow.com/users/20028181", "pm_score": -1, "selected": false, "text": "String &'static str fn leak(s: String) -> &'static str {\n let ptr = s.as_str() as *const str;\n core::mem::forget(s);\n unsafe {&*ptr}\n}\n char String fn cts(c: char, n: usize) -> String {\n (0..n)\n .map(|_| c)\n .collect()\n}\n char &'static str fn conv(c: char, n: usize) -> &'static str {\n leak(cts(c, n))\n}\n String" }, { "answer_id": 74652051, "author": "Finomnis", "author_id": 2902833, "author_profile": "https://Stackoverflow.com/users/2902833", "pm_score": 3, "selected": true, "text": "str String str &str Box<str> *str &str String String String &str String &str &str &str String s.as_bytes()[0] as char pub fn longest_sequence(s: &str) -> Option<&str> {\n let mut current_c = s.chars().next()?;\n let mut current_start = 0;\n let mut current_len = 0;\n let mut greatest: &str = \"\";\n let mut greatest_len = 0;\n for (pos, ch) in s.char_indices() {\n if current_c == ch {\n current_len += 1;\n } else {\n if greatest_len < current_len {\n greatest = &s[current_start..pos];\n greatest_len = current_len;\n }\n\n current_len = 1;\n current_c = ch;\n current_start = pos;\n }\n }\n\n if greatest_len < current_len {\n greatest = &s[current_start..];\n }\n\n Some(greatest)\n}\n\npub fn main() {\n let s = \"€€\";\n\n let seq = longest_sequence(s);\n println!(\"{:?}\", seq);\n}\n Some(\"\")\n s.chars().next()? s.chars().next() s.as_bytes()[0] as char greatest_len greatest.len() greatest.len() &s[current_start..current_start+current_len] &s[ .. ] current_len pub fn longest_sequence(s: &str) -> Option<String> {\n let mut current_c = s.chars().next()?;\n let mut greatest_c = current_c;\n let mut current_num = 0;\n let mut greatest_num = 0;\n for ch in s.chars() {\n if current_c == ch {\n current_num += 1;\n if current_num > greatest_num {\n greatest_num = current_num;\n greatest_c = current_c;\n }\n } else {\n current_num = 1;\n current_c = ch;\n }\n }\n\n // Build the output String\n Some(std::iter::repeat(greatest_c).take(greatest_num).collect())\n}\n\npub fn main() {\n let s = \"€€\";\n\n let seq = longest_sequence(s);\n println!(\"{:?}\", seq);\n}\n Some(\"\")\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74649564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15654610/" ]
74,649,624
<p>I'm trying to get my oauth2 android app verified by the google cloud console so more than 100 users can use it but I'm stuck on this part here: <a href="https://i.stack.imgur.com/9cLIj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9cLIj.png" alt="enter image description here" /></a></p> <p>What does this mean? Do I need to create a website for this? Is there a way to do it for free?</p> <p>Thanks!!</p>
[ { "answer_id": 74651729, "author": "Miiao", "author_id": 20028181, "author_profile": "https://Stackoverflow.com/users/20028181", "pm_score": -1, "selected": false, "text": "String &'static str fn leak(s: String) -> &'static str {\n let ptr = s.as_str() as *const str;\n core::mem::forget(s);\n unsafe {&*ptr}\n}\n char String fn cts(c: char, n: usize) -> String {\n (0..n)\n .map(|_| c)\n .collect()\n}\n char &'static str fn conv(c: char, n: usize) -> &'static str {\n leak(cts(c, n))\n}\n String" }, { "answer_id": 74652051, "author": "Finomnis", "author_id": 2902833, "author_profile": "https://Stackoverflow.com/users/2902833", "pm_score": 3, "selected": true, "text": "str String str &str Box<str> *str &str String String String &str String &str &str &str String s.as_bytes()[0] as char pub fn longest_sequence(s: &str) -> Option<&str> {\n let mut current_c = s.chars().next()?;\n let mut current_start = 0;\n let mut current_len = 0;\n let mut greatest: &str = \"\";\n let mut greatest_len = 0;\n for (pos, ch) in s.char_indices() {\n if current_c == ch {\n current_len += 1;\n } else {\n if greatest_len < current_len {\n greatest = &s[current_start..pos];\n greatest_len = current_len;\n }\n\n current_len = 1;\n current_c = ch;\n current_start = pos;\n }\n }\n\n if greatest_len < current_len {\n greatest = &s[current_start..];\n }\n\n Some(greatest)\n}\n\npub fn main() {\n let s = \"€€\";\n\n let seq = longest_sequence(s);\n println!(\"{:?}\", seq);\n}\n Some(\"\")\n s.chars().next()? s.chars().next() s.as_bytes()[0] as char greatest_len greatest.len() greatest.len() &s[current_start..current_start+current_len] &s[ .. ] current_len pub fn longest_sequence(s: &str) -> Option<String> {\n let mut current_c = s.chars().next()?;\n let mut greatest_c = current_c;\n let mut current_num = 0;\n let mut greatest_num = 0;\n for ch in s.chars() {\n if current_c == ch {\n current_num += 1;\n if current_num > greatest_num {\n greatest_num = current_num;\n greatest_c = current_c;\n }\n } else {\n current_num = 1;\n current_c = ch;\n }\n }\n\n // Build the output String\n Some(std::iter::repeat(greatest_c).take(greatest_num).collect())\n}\n\npub fn main() {\n let s = \"€€\";\n\n let seq = longest_sequence(s);\n println!(\"{:?}\", seq);\n}\n Some(\"\")\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74649624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17792511/" ]
74,649,671
<p>New to frontend and extension itself here. I tried searching and trying different things at this point. I have been to many questions like these: <a href="https://stackoverflow.com/questions/37033449/click-function-not-working-on-document-getelementsbyclassname">click function not working on document.getElementsByClassName</a> But unlike these, I am iterating through an array and not calling .click() on the array itself. This is a piece of content.ts from my extension app</p> <p>content.ts</p> <pre class="lang-ts prettyprint-override"><code>window.onload = function () { let buttons = Array.from(document.getElementsByClassName(&quot;listof-buttons&quot;)); buttons.forEach((button) =&gt; { if (button.textContent === &quot;Click Here&quot;) { (button as HTMLElement).click(); } }); }; </code></pre> <p>The reason I am using textContent is cause there are multiple buttons with the same classname. The button does not get clicked when the window loads. (I am not waiting on an input and hence .click() and not .onClick())Any idea what I am missing here?</p> <p>EDIT</p> <ul> <li>Used logging everywhere, it goes inside the if() condition</li> <li>By &quot;not working&quot; I mean its not clicking on the button</li> <li>I tried .innerHtml instead of .textContent but the results are the same</li> </ul> <p>manifest.json</p> <pre><code>{ &quot;name&quot;: &quot;Chrome Extension&quot;, &quot;version&quot;: &quot;0.0.1&quot;, &quot;manifest_version&quot;: 2, &quot;description&quot;: &quot;Practicing Chrome extension with TypeScript, React, and Webpack.&quot;, &quot;homepage_url&quot;: &quot;https://www.example.com/&quot;, &quot;icons&quot;: { &quot;16&quot;: &quot;icons/icon16.png&quot; }, &quot;browser_action&quot;: { &quot;default_title&quot;: &quot;Open the popup&quot;, &quot;default_popup&quot;: &quot;popup.html&quot; }, &quot;default_locale&quot;: &quot;en&quot;, &quot;background&quot;: { &quot;scripts&quot;: [ &quot;js/background.js&quot; ], &quot;persistent&quot;: true }, &quot;permissions&quot;: [ &quot;https://*/*&quot; ], &quot;optional_permissions&quot;: [ &quot;&lt;all_urls&gt;&quot; ], &quot;content_security_policy&quot;: &quot;default-src 'self';&quot;, &quot;content_scripts&quot;: [ { &quot;matches&quot;: [ &quot;&lt;all_urls&gt;&quot; ], &quot;js&quot;: [ &quot;js/content.js&quot; ] } ] </code></pre> <p>}</p> <p>Example situation: I am trying to use: cnbc.com/us-market-movers and trying to click on Nasdaq button next to MARKET MOVERS with onload.</p>
[ { "answer_id": 74651729, "author": "Miiao", "author_id": 20028181, "author_profile": "https://Stackoverflow.com/users/20028181", "pm_score": -1, "selected": false, "text": "String &'static str fn leak(s: String) -> &'static str {\n let ptr = s.as_str() as *const str;\n core::mem::forget(s);\n unsafe {&*ptr}\n}\n char String fn cts(c: char, n: usize) -> String {\n (0..n)\n .map(|_| c)\n .collect()\n}\n char &'static str fn conv(c: char, n: usize) -> &'static str {\n leak(cts(c, n))\n}\n String" }, { "answer_id": 74652051, "author": "Finomnis", "author_id": 2902833, "author_profile": "https://Stackoverflow.com/users/2902833", "pm_score": 3, "selected": true, "text": "str String str &str Box<str> *str &str String String String &str String &str &str &str String s.as_bytes()[0] as char pub fn longest_sequence(s: &str) -> Option<&str> {\n let mut current_c = s.chars().next()?;\n let mut current_start = 0;\n let mut current_len = 0;\n let mut greatest: &str = \"\";\n let mut greatest_len = 0;\n for (pos, ch) in s.char_indices() {\n if current_c == ch {\n current_len += 1;\n } else {\n if greatest_len < current_len {\n greatest = &s[current_start..pos];\n greatest_len = current_len;\n }\n\n current_len = 1;\n current_c = ch;\n current_start = pos;\n }\n }\n\n if greatest_len < current_len {\n greatest = &s[current_start..];\n }\n\n Some(greatest)\n}\n\npub fn main() {\n let s = \"€€\";\n\n let seq = longest_sequence(s);\n println!(\"{:?}\", seq);\n}\n Some(\"\")\n s.chars().next()? s.chars().next() s.as_bytes()[0] as char greatest_len greatest.len() greatest.len() &s[current_start..current_start+current_len] &s[ .. ] current_len pub fn longest_sequence(s: &str) -> Option<String> {\n let mut current_c = s.chars().next()?;\n let mut greatest_c = current_c;\n let mut current_num = 0;\n let mut greatest_num = 0;\n for ch in s.chars() {\n if current_c == ch {\n current_num += 1;\n if current_num > greatest_num {\n greatest_num = current_num;\n greatest_c = current_c;\n }\n } else {\n current_num = 1;\n current_c = ch;\n }\n }\n\n // Build the output String\n Some(std::iter::repeat(greatest_c).take(greatest_num).collect())\n}\n\npub fn main() {\n let s = \"€€\";\n\n let seq = longest_sequence(s);\n println!(\"{:?}\", seq);\n}\n Some(\"\")\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74649671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4463330/" ]
74,649,728
<pre><code>public class PreferenceManager { private static PreferenceManager _instance = null; private static readonly object _lock = new object(); private PreferenceManager() { } public static PreferenceManager Instance { get { lock (_lock) { if (_instance == null) _instance = new PreferenceManager(); return _instance; } } } public void SetPreference&lt;T&gt;(string key, T value) { Preferences.Set(key, value); } public T GetPreference&lt;T&gt;(string key) { object value = Preferences.Get(key, null); return (T)Convert.ChangeType(value, typeof(T)); } } </code></pre> <p>I'd like to make wrapper class for manage all process about Xamarin.Essentials.Preferences.</p> <p>There are so many overrides with different types for getting/setting in Essentials class.</p> <p>So, I tried to change return value with generic and set value also, because I think it looks more simple.</p> <p>But, there is an error in SetPreference method : cannot convert from 'T' to 'string'.</p> <p>Is there any good solution for making wrapper class?</p> <p>I want to handle all processes in here with one method.... :-(</p>
[ { "answer_id": 74651121, "author": "Liqun Shen-MSFT", "author_id": 20118901, "author_profile": "https://Stackoverflow.com/users/20118901", "pm_score": 2, "selected": true, "text": "public void SetPreference<T>(string key,T value)\n{\n if (value is string)\n {\n Preferences.Set(key, Convert.ToString(value)); \n }\n if (value is double)\n {\n Preferences.Set(key, Convert.ToDouble(value));\n }\n ...\n}\n" }, { "answer_id": 74669913, "author": "SKall", "author_id": 3148214, "author_profile": "https://Stackoverflow.com/users/3148214", "pm_score": 0, "selected": false, "text": " public class PreferenceManager\n {\n private static readonly Lazy<PreferenceManager> LazyInstance = new Lazy<PreferenceManager>(() => new PreferenceManager());\n\n private PreferenceManager() { }\n public static PreferenceManager Instance => LazyInstance.Value;\n\n public void SetPreference<T>(string key, T value) where T : class => Preferences.Set(key, JsonSerializer.Serialize(value));\n\n public T GetPreference<T>(string key) where T : class => Preferences.Get(key, null) is string value\n ? JsonSerializer.Deserialize<T>(value)\n : default;\n }\n public class PreferenceManager\n{\n private static readonly Lazy<PreferenceManager> LazyInstance = new(() => new PreferenceManager());\n\n private PreferenceManager() { }\n public static PreferenceManager Instance => LazyInstance.Value;\n\n public void SetPreference<T>(string key, T value) => Preferences.Set(key, JsonSerializer.Serialize(new StoredObject<T>(value)));\n\n public T GetPreference<T>(string key)\n {\n var o = Preferences.Get(key, null) is { } value\n ? JsonSerializer.Deserialize<StoredObject<T>>(value)\n : null;\n\n return o is not null ? o.Value : default;\n }\n\n internal class StoredObject<T>\n {\n internal StoredObject(T value)\n {\n Value = value;\n }\n\n internal T Value { get; }\n }\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74649728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20343943/" ]
74,649,757
<p>I just started working with Numpy because I want to use their log method. I am trying to do -log2(79/859) but can only see how to do log2(74/571) which outputs a negative value when it should be positive. Read the Doc but don't see how to make it a negative log?</p> <p>How can I fix this?</p> <pre><code>print(np.log2(79/859)) </code></pre> <p>Output</p> <p><code>-2.947893569733893</code></p> <p>Output I want</p> <p><code>2.947893569733893</code></p> <p>Tried searching through NumPy Docs</p>
[ { "answer_id": 74649891, "author": "MarianD", "author_id": 7023590, "author_profile": "https://Stackoverflow.com/users/7023590", "pm_score": 0, "selected": false, "text": "print(-np.log2(74/571))\n" }, { "answer_id": 74649929, "author": "GusSL", "author_id": 6269268, "author_profile": "https://Stackoverflow.com/users/6269268", "pm_score": 2, "selected": true, "text": "np.abs(np.log2(74/571))\n# 2.948\n math import math\n\nabs(math.log2(74/571))\n# 2.948\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74649757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20422490/" ]
74,649,776
<p>I have a table similar to this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>product_id</th> <th>client_id</th> <th>category</th> <th>price</th> <th>created_date</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>1</td> <td>A</td> <td>3.1</td> <td>2022-11-01</td> </tr> <tr> <td>2</td> <td>1</td> <td>A</td> <td>3.2</td> <td>2022-11-02</td> </tr> <tr> <td>3</td> <td>1</td> <td>B</td> <td>3.3</td> <td>2022-11-03</td> </tr> <tr> <td>4</td> <td>1</td> <td>B</td> <td>3.4</td> <td>2022-11-04</td> </tr> <tr> <td>5</td> <td>2</td> <td>B</td> <td>3.5</td> <td>2022-11-05</td> </tr> <tr> <td>6</td> <td>2</td> <td>B</td> <td>3.6</td> <td>2022-11-06</td> </tr> <tr> <td>7</td> <td>2</td> <td>A</td> <td>3.7</td> <td>2022-11-07</td> </tr> <tr> <td>8</td> <td>2</td> <td>C</td> <td>3.8</td> <td>2022-11-08</td> </tr> </tbody> </table> </div> <p>And I want to select the price from the <strong>latest</strong> created_date from each client_id and category, so my expected result would be this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>product_id</th> <th>client_id</th> <th>category</th> <th>price</th> <th>created_date</th> </tr> </thead> <tbody> <tr> <td>2</td> <td>1</td> <td>A</td> <td>3.2</td> <td>2022-11-02</td> </tr> <tr> <td>4</td> <td>1</td> <td>B</td> <td>3.4</td> <td>2022-11-04</td> </tr> <tr> <td>6</td> <td>2</td> <td>B</td> <td>3.6</td> <td>2022-11-06</td> </tr> <tr> <td>7</td> <td>2</td> <td>A</td> <td>3.7</td> <td>2022-11-07</td> </tr> <tr> <td>8</td> <td>2</td> <td>C</td> <td>3.8</td> <td>2022-11-08</td> </tr> </tbody> </table> </div> <p>Could you please help me with this? Thanks</p> <p>I found something similar here: <a href="https://stackoverflow.com/questions/3800551/select-first-row-in-each-group-by-group">Select first row in each GROUP BY group?</a></p> <p><strong>UPDATE</strong></p> <p>Actually I want to do the same with the following (this is a more realistic example): <a href="https://www.db-fiddle.com/f/fHc6MafduyibJdkLHe9cva/0" rel="nofollow noreferrer">https://www.db-fiddle.com/f/fHc6MafduyibJdkLHe9cva/0</a></p> <p>Expected result:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>val1</th> <th>val2</th> <th>num1</th> <th>num2</th> <th>created_date</th> </tr> </thead> <tbody> <tr> <td>X</td> <td>A</td> <td>33</td> <td>333</td> <td>2022-11-03</td> </tr> <tr> <td>X</td> <td>B</td> <td>66</td> <td>666</td> <td>2022-11-06</td> </tr> <tr> <td>X</td> <td>C</td> <td>88</td> <td>888</td> <td>2022-11-08</td> </tr> <tr> <td>X</td> <td>D</td> <td>99</td> <td>999</td> <td>2022-11-09</td> </tr> <tr> <td>Y</td> <td>A</td> <td>111</td> <td>1111</td> <td>2022-11-11</td> </tr> </tbody> </table> </div>
[ { "answer_id": 74649891, "author": "MarianD", "author_id": 7023590, "author_profile": "https://Stackoverflow.com/users/7023590", "pm_score": 0, "selected": false, "text": "print(-np.log2(74/571))\n" }, { "answer_id": 74649929, "author": "GusSL", "author_id": 6269268, "author_profile": "https://Stackoverflow.com/users/6269268", "pm_score": 2, "selected": true, "text": "np.abs(np.log2(74/571))\n# 2.948\n math import math\n\nabs(math.log2(74/571))\n# 2.948\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74649776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6227441/" ]
74,649,777
<p>I'm fairly new to window functions and have been learning about them recently. There is this query which returns the total sales for each month and quarter using a group by and an aggregate function. Additionally, it returns the total sales for the whole year (using a window function) and the max total sales for each quarter (using a window function). This all makes sense to me.</p> <p>Query:</p> <pre><code>SELECT quarter(payment_date) quarter, monthname(payment_date) month_name, SUM(amount) monthly_sales, MAX(SUM(amount)) OVER() max_overall_values, MAX(SUM(amount)) OVER(PARTITION BY quarter(payment_date)) max_quarter_sales FROM payment WHERE year(payment_date) = 2005 GROUP BY quarter(payment_date), monthname(payment_date) ORDER BY monthname(payment_date) DESC; </code></pre> <p>Results:</p> <pre><code>+---------+------------+---------------+--------------------+-------------------+ | quarter | month_name | monthly_sales | max_overall_values | max_quarter_sales | +---------+------------+---------------+--------------------+-------------------+ | 2 | May | 4824.43 | 28373.89 | 9631.88 | | 2 | June | 9631.88 | 28373.89 | 9631.88 | | 3 | July | 28373.89 | 28373.89 | 28373.89 | | 3 | August | 24072.13 | 28373.89 | 28373.89 | +---------+------------+---------------+--------------------+-------------------+ </code></pre> <p>I start to loose track of what's going on if I remove &quot;max&quot;:</p> <pre><code>SELECT quarter(payment_date) quarter, monthname(payment_date) month_name, SUM(amount) monthly_sales, SUM(amount) OVER() max_overall_values, SUM(amount) OVER(PARTITION BY quarter(payment_date)) max_quarter_sales FROM payment WHERE year(payment_date) = 2005 GROUP BY quarter(payment_date), monthname(payment_date) ORDER BY monthname(payment_date) DESC; </code></pre> <p>I get the following results:</p> <pre><code>+---------+------------+---------------+--------------------+-------------------+ | quarter | month_name | monthly_sales | max_overall_values | max_quarter_sales | +---------+------------+---------------+--------------------+-------------------+ | 2 | May | 4824.43 | 19.96 | 8.98 | | 2 | June | 9631.88 | 19.96 | 8.98 | | 3 | July | 28373.89 | 19.96 | 10.98 | | 3 | August | 24072.13 | 19.96 | 10.98 | +---------+------------+---------------+--------------------+-------------------+ </code></pre> <p>My question is what data is the &quot;max&quot; window function actually processing when it's used in this context, which involves a group by clause, and how is it arriving at the calculation of 19.96 for max_overall_values, 8.98 for a quarter and 10.98 for the other when &quot;max&quot; is removed?</p>
[ { "answer_id": 74650270, "author": "ysth", "author_id": 17389, "author_profile": "https://Stackoverflow.com/users/17389", "pm_score": 1, "selected": false, "text": "Expression #4 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'fiddle.payment.amount' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by\n" }, { "answer_id": 74651624, "author": "JHH", "author_id": 20127235, "author_profile": "https://Stackoverflow.com/users/20127235", "pm_score": 0, "selected": false, "text": "payment1 payment2 create table payment2 as select * from payment1 order by payment_date desc payment_date|amount|\n------------+------+\n 2020-05-01| 1|\n 2020-05-02| 2|\n 2020-05-03| 3|\n 2020-06-01| 4|\n 2020-06-02| 5|\n 2020-06-03| 6|\n 2020-07-01| 7|\n 2020-07-02| 8|\n 2020-07-03| 9|\n 2020-08-01| 10|\n 2020-08-02| 11|\n 2020-08-03| 12|\n quarter|month_name|amount|monthly_sales|\n-------+----------+------+-------------+\n 2|May | 1| 6|\n 2|May | 2| 6|\n 2|May | 3| 6|\n 2|June | 4| 15|\n 2|June | 5| 15|\n 2|June | 6| 15|\n 3|July | 7| 24|\n 3|July | 8| 24|\n 3|July | 9| 24|\n 3|August | 10| 33|\n 3|August | 11| 33|\n 3|August | 12| 33|\n max(sum()) quarter|month_name|monthly_sales|max_overall_amount|max_quarter_sales|\n-------+----------+-------------+------------------+-----------------+\n 2|May | 6| 33| 15|\n 2|June | 15| 33| 15|\n 3|July | 24| 33| 33|\n 3|August | 33| 33| 33|\n sum() payment_date ASC DESC quarter|month_name|monthly_sales|sum_overall_amount|sum_quarter_sales|\n-------+----------+-------------+------------------+-----------------+\n 2|May | 6| 22| 5|\n 2|June | 15| 22| 5|\n 3|July | 24| 22| 17|\n 3|August | 33| 22| 17|\n\n-- 22 = 1 + 4 + 7 + 10 --> first row of each month\n-- 5 = 1 + 4 --> first row of May, June\n-- 17 = 7 + 10 --> first row of July, August\n payment2 quarter|month_name|monthly_sales|sum_overall_amount|sum_quarter_sales|\n-------+----------+-------------+------------------+-----------------+\n 2|May | 6| 30| 9|\n 2|June | 15| 30| 9|\n 3|July | 24| 30| 21|\n 3|August | 33| 30| 21|\n\n-- 30 = 3 + 6 + 9 + 12 --> first row of each month in `payment2`\n quarter|month_name|monthly_sales|max_overall_amount|max_quarter_sales|\n-------+----------+-------------+------------------+-----------------+\n 2|May | 6| 10| 4|\n 2|June | 15| 10| 4|\n 3|July | 24| 10| 10|\n 3|August | 33| 10| 10|\n\n-- 4 = max(1, 4) --> first row of May , June\n-- 10 = max(7, 10) --> first row of July, August\n payment2 quarter|month_name|monthly_sales|max_overall_amount|max_quarter_sales|\n-------+----------+-------------+------------------+-----------------+\n 2|May | 6| 12| 6|\n 2|June | 15| 12| 6|\n 3|July | 24| 12| 12|\n 3|August | 33| 12| 12|\n\n-- 6 = max(3, 6) --> first row of May, Jun in `payment2`\n-- 12 = max(9, 12) --> first row of July, August in `payment2`\n quarter|month_name|monthly_sales|min_overall_amount|min_quarter_sales|\n-------+----------+-------------+------------------+-----------------+\n 2|May | 6| 1| 1|\n 2|June | 15| 1| 1|\n 3|July | 24| 1| 7|\n 3|August | 33| 1| 7|\n\n-- 1 = min(1, 4) --> first row of May, June\n-- 7 = min(7, 10) --> first row of July, August\n payment2 quarter|month_name|monthly_sales|min_overall_amount|min_quarter_sales|\n-------+----------+-------------+------------------+-----------------+\n 2|May | 6| 3| 3|\n 2|June | 15| 3| 3|\n 3|July | 24| 3| 9|\n 3|August | 33| 3| 9|\n\n-- 3 = min(3, 6) --> first row of May, June in `payment2`\n-- 9 = min(9, 12) --> first row of July, August in `payment2`\n ONLY_FULL_GROUP_BY GROUP BY payment1 payment1 ONLY_FULL_GROUP_BY sql_mode" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74649777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1798677/" ]
74,649,783
<p>i'm trying to make a grid using react native that's responsive to multiple screen sizes but having troubles drawing the lines in (the sides of the box can't have a stroke). this is what it needs to look like: <a href="https://i.stack.imgur.com/KwVl6.png" rel="nofollow noreferrer">example grid</a> <a href="https://i.stack.imgur.com/PjI3O.png" rel="nofollow noreferrer">my current grid</a></p> <p>this is a small snippet:</p> <pre><code> &lt;View style={styles.boxContainer}&gt; &lt;View style={styles.box}&gt; &lt;Text style={styles.boxText}&gt; X &lt;/Text&gt; &lt;/View&gt; &lt;View style={styles.box}&gt; &lt;Text style={styles.boxText}&gt; O &lt;/Text&gt; &lt;/View&gt; &lt;View style={styles.box}&gt; &lt;Text style={styles.boxText}&gt; X &lt;/Text&gt; &lt;/View&gt; &lt;View style={styles.box}&gt; &lt;Text style={styles.boxText}&gt; X &lt;/Text&gt; &lt;/View&gt; &lt;View style={styles.box}&gt; &lt;Text style={styles.boxText}&gt; O &lt;/Text&gt; &lt;/View&gt; &lt;View style={styles.box}&gt; &lt;Text style={styles.boxText}&gt; O &lt;/Text&gt; &lt;/View&gt; &lt;View style={styles.box}&gt; &lt;Text style={styles.boxText}&gt; X &lt;/Text&gt; &lt;/View&gt; &lt;View style={styles.box}&gt; &lt;Text style={styles.boxText}&gt; X &lt;/Text&gt; &lt;/View&gt; &lt;View style={styles.box}&gt; &lt;Text style={styles.boxText}&gt; O &lt;/Text&gt; &lt;/View&gt; &lt;/View&gt; &lt;/SafeAreaView&gt; ); } const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', justifyContent: 'center', }, box: { alignItems: 'center', width: DeviceWidth*0.3, height: DeviceWidth*0.3, }, boxContainer: { flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'center', marginRight: DeviceWidth*0.05, marginLeft: DeviceWidth*0.05, }, </code></pre> <p>i've tried doing a border but it covers the entire thing and i'm unsure how to clear the lines on the side :( i've also tried adding a background color to my container and attempting to add space between the boxes but couldnt figure out how to make the background look similar in size..</p>
[ { "answer_id": 74649959, "author": "PaleRedDot", "author_id": 10607003, "author_profile": "https://Stackoverflow.com/users/10607003", "pm_score": 1, "selected": false, "text": "import * as React from 'react';\nimport {Dimensions, SafeAreaView, StyleSheet, Text, View} from 'react-native';\n\nconst DeviceWidth = Dimensions.get('window').width;\n\nexport default function App() {\n const [showModal, setShowModal] = React.useState(false);\n\n const xo = ['X', 'O', 'X', 'O', 'X', 'O', 'O', 'X', 'O'];\n\n return (\n <SafeAreaView>\n <View style={styles.boxContainer}>\n {xo.map((value, index) => {\n const row = index % 3;\n return (\n <View\n style={[\n styles.box,\n {\n borderRightColor: row < 2 ? 'black' : 'transparent',\n borderLeftColor: row >= 1 ? 'black' : 'transparent',\n borderTopColor: index > 2 ? 'black' : 'transparent',\n borderBottomColor: index < 6 ? 'black' : 'transparent',\n },\n ]}>\n <Text style={styles.boxText}>{value}</Text>\n </View>\n );\n })}\n </View>\n </SafeAreaView>\n );\n}\nconst styles = StyleSheet.create({\n container: {\n flex: 1,\n alignItems: 'center',\n justifyContent: 'center',\n },\n\n boxText: {\n fontSize: 90,\n },\n\n box: {\n alignItems: 'center',\n width: DeviceWidth * 0.3,\n height: DeviceWidth * 0.3,\n borderWidth: 1,\n borderColor: 'transparent',\n },\n\n boxContainer: {\n flexDirection: 'row',\n flexWrap: 'wrap',\n justifyContent: 'center',\n marginRight: DeviceWidth * 0.05,\n marginLeft: DeviceWidth * 0.05,\n },\n});\n" }, { "answer_id": 74650014, "author": "PhantomSpooks", "author_id": 12611354, "author_profile": "https://Stackoverflow.com/users/12611354", "pm_score": 0, "selected": false, "text": "import * as React from 'react';\nimport { Text, View, StyleSheet, useWindowDimensions } from 'react-native';\nimport Constants from 'expo-constants';\n\nconst Box = ({ char, style }) => {\n const { width, height } = useWindowDimensions();\n const size = Math.min(width, height) / 3;\n return (\n <View\n style={[\n {\n width: size,\n height: size,\n alignItems: 'center',\n justifyContent: 'center',\n },\n style,\n ]}>\n <Text>{char}</Text>\n </View>\n );\n};\nexport default function App() {\n return (\n <View style={styles.container}>\n <View style={styles.row1}>\n <Box char=\"1\" style={styles.col1} />\n <Box char=\"2\" style={styles.col2} />\n <Box char=\"3\" style={styles.col3} />\n </View>\n <View style={styles.row2}>\n <Box char=\"4\" style={styles.col1} />\n <Box char=\"5\" style={styles.col2} />\n <Box char=\"6\" style={styles.col3} />\n </View>\n <View style={styles.row3}>\n <Box char=\"7\" style={styles.col1} />\n <Box char=\"8\" style={styles.col2} />\n <Box char=\"9\" style={styles.col3} />\n </View>\n </View>\n );\n}\n\nconst styles = StyleSheet.create({\n container: {\n flex: 1,\n justifyContent: 'center',\n paddingTop: Constants.statusBarHeight,\n backgroundColor: '#ecf0f1',\n padding: 8,\n },\n row1: {\n flexDirection: 'row',\n borderBottomWidth: 1,\n alignItems: 'center',\n },\n row2: {\n flexDirection: 'row',\n width: '100%',\n },\n row3: {\n flexDirection: 'row',\n width: '100%',\n borderTopWidth: 1,\n },\n col1: {\n borderRightWidth: 1,\n },\n col2: {\n borderRightWidth: 1,\n },\n col3:{\n \n }\n});\n" }, { "answer_id": 74650067, "author": "Jacky Chan", "author_id": 9266904, "author_profile": "https://Stackoverflow.com/users/9266904", "pm_score": 0, "selected": false, "text": "import { Dimensions, FlatList, Text, View } from 'react-native';\nimport styled from 'styled-components';\n\n\nconst { width } = Dimensions.get('window');\n\nconst BORDER_WIDTH = 4;\n\nconst Test = () => {\n\n const data = ['x', 'o', 'x', 'x', 'o', 'x', 'x', 'o', 'x',];\n\n return (\n <Container>\n <Content>\n <FlatList\n data={data}\n keyExtractor={(_, index) => index.toString()}\n numColumns={3}\n renderItem={({ item }) => <Cell>\n <CellValue>{item}</CellValue>\n </Cell>}\n bounces={false}\n />\n <RemoveBorder />\n </Content>\n </Container>\n )\n}\n\nexport default Test;\n\nconst Container = styled(View)`\n flex: 1;\n background-color: white;\n align-items: center;\n justify-content: center;\n`\n\nconst Content = styled(View)`\n width: ${width}px;\n height: ${width}px;\n`\n\nconst RemoveBorder = styled(View)`\n position: absolute;\n border-width: ${BORDER_WIDTH / 2}px;\n border-color: white;\n width: 100%;\n height: 100%;\n`\n\nconst Cell = styled(View)`\n width: ${width / 3}px;\n height: ${width / 3}px;\n align-items: center;\n justify-content: center;\n border-width: ${BORDER_WIDTH / 2}px;\n`\n\nconst CellValue = styled(Text)`\n font-size: 40px;\n color: black;\n`\n" }, { "answer_id": 74650734, "author": "John Ocean", "author_id": 16241616, "author_profile": "https://Stackoverflow.com/users/16241616", "pm_score": 0, "selected": false, "text": " <SafeAreaView style={styles.container}>\n <View style={[styles.boxContainer, {borderBottomWidth: 2}]}>\n <View style={[styles.box, {borderRightWidth: 2}]}>\n <Text style={{}}> X </Text>\n </View>\n <View style={[styles.box, {borderRightWidth: 2}]}>\n <Text style={{}}> O </Text>\n </View>\n <View style={styles.box}>\n <Text style={{}}> X </Text>\n </View>\n </View>\n <View style={[styles.boxContainer, {borderBottomWidth: 2}]}>\n <View style={[styles.box, {borderRightWidth: 2}]}>\n <Text style={{}}> X </Text>\n </View>\n <View style={[styles.box, {borderRightWidth: 2}]}>\n <Text style={{}}> O </Text>\n </View>\n <View style={styles.box}>\n <Text style={{}}> O </Text>\n </View>\n </View>\n <View style={styles.boxContainer}>\n <View style={[styles.box, {borderRightWidth: 2}]}>\n <Text style={{}}> X </Text>\n </View>\n <View style={[styles.box, {borderRightWidth: 2}]}>\n <Text style={{}}> X </Text>\n </View>\n <View style={styles.box}>\n <Text style={{}}> O </Text>\n </View>\n </View>\n </SafeAreaView>\n );\n}\n\nconst styles = StyleSheet.create({\n container: {\n flex: 1, alignItems: 'center', justifyContent: 'center',\n },\n boxContainer: {\n flexDirection: 'row', alignItems: 'center',\n },\n box: {\n width: width*0.3, height: width*0.3, alignItems: 'center', justifyContent: 'center',\n }\n})\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74649783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19385910/" ]
74,649,807
<p>I have a site where the h1 tag and an image load in when I scroll to them. I have the css set to load an animation on the tags when they load, so I really don't want them to load before they are visible.</p> <p>I have it working perfectly on desktop/laptop, but on mobile the elements are just loaded automatically with everything else, and the animations don't have a chance to work. The console logs that I call show that the <code>window.scrollY</code> is only returning &quot;0&quot;.</p> <pre><code>import React, { useEffect, useState } from 'react'; import Headshot from '../../../assets/images/about/Headshot'; const About = () =&gt; { const [isVisible, setIsVisible] = useState(true); useEffect(() =&gt; { document.addEventListener(&quot;touchmove&quot;, listenToScroll); window.addEventListener(&quot;scroll&quot;, listenToScroll); return () =&gt; { document.addEventListener(&quot;touchmove&quot;, listenToScroll); window.removeEventListener(&quot;scroll&quot;, listenToScroll); } }, []) const listenToScroll = () =&gt; { const homeHeight = document.getElementById('Home').clientHeight; const folioHeight = document.getElementById('Portfolio').clientHeight; const skillsHeight = document.getElementById('Skills').clientHeight; let heightToShow; let vh = window.innerHeight; if (homeHeight &gt; vh + 100) { heightToShow = homeHeight - vh + folioHeight + skillsHeight; } else { heightToShow = 100 + folioHeight + skillsHeight; } const winScroll = window.scrollY; console.log(&quot;winScroll: &quot; + winScroll); console.log(&quot;heightToShow: &quot;+ heightToShow); console.log(&quot;wS &gt; hTS: &quot; + (winScroll &gt; heightToShow)); if (winScroll &gt; heightToShow) { isVisible &amp;&amp; setIsVisible(true); } else { setIsVisible(false); } }; return ( &lt;&gt; &lt;div className='container aboutContainer' id=&quot;About&quot;&gt; { isVisible ? ( &lt;&gt; &lt;h1 className=&quot;aboutH1&quot;&gt;This is Me&lt;/h1&gt; &lt;div className=&quot;headshot&quot;&gt; &lt;Headshot /&gt; &lt;img src=&quot;/assets/images/about/headshot.webp&quot; alt=&quot;&quot; id=&quot;headshotImg&quot; /&gt; &lt;/div&gt; &lt;/&gt; ) : &quot;&quot;} &lt;/div&gt; &lt;/&gt; ); } export default About </code></pre> <p>If there's a simpler solution, I am certainly open to it, but please don't just tell me &quot;use this library, and put the tags in. It'll take care of it.&quot; The point of this exercise is that I am trying to learn how to do it, so that I can tell if a library is a good choice for myself later.</p>
[ { "answer_id": 74659223, "author": "Alverstone", "author_id": 19703001, "author_profile": "https://Stackoverflow.com/users/19703001", "pm_score": 0, "selected": false, "text": "import React, { useEffect, useState } from 'react';\nimport Headshot from '../../../assets/images/about/Headshot';\n\nconst About = () => {\n const containerRef = useRef(null);\n const [isVisible, setIsVisible] = useState(false);\n\n const callbackFunction = (entries) => {\n const [entry] = entries;\n setIsVisible(entry.isIntersecting);\n }\n const options = {\n root: null,\n rootMargin: \"0px\",\n threshold: 1.0\n }\n\n useEffect(() => {\n const observer = new IntersectionObserver(callbackFunction, options);\n if (containerRef.current) observer.observe(containerRef.current);\n\n return () => {\n if (containerRef.current) observer.unobserve(containerRef.current);\n }\n }, [containerRef, options])\n\n return ( \n <>\n <div className='container aboutContainer' id=\"About\">\n { isVisible ? (\n <>\n <h1 className=\"aboutH1\">This is Me</h1>\n <div className=\"headshot\">\n <Headshot />\n <img \n src=\"/assets/images/about/headshot.webp\" \n alt=\"Brian Quinney - Programmer, Geek, Lifelong Learner\" \n id=\"headshotImg\"\n />\n </div>\n </>\n ) : \"\"}\n <div className=\"venn\">\n <h2 ref={ containerRef }>Who am I?</h2>\n </div>\n </div>\n </>\n );\n}\n\nexport default About\n ref={ containerRef } h2" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74649807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19703001/" ]
74,649,816
<p>I'm starting out with C# (two weeks in) and I'm trying to display a variable based on user input via Console.Readline(); method. This basic app is a calculator with two steps: Step 1 is a simple calculator; Step 2 should display material information (the name and price of the material).</p> <p>The issue I'm having is in step 2 of my app, where I want to display the name and price of a material based on the user input. I'm not sure if LINQ is the best, easiest method for this. So open to how to solve this so it's readable by others and makes the program work.</p> <p>Program CS. file is as follows:</p> <pre><code>using System; namespace Gutterjob { class Program { static void Main(String[] args) { Console.WriteLine(&quot;This is how much a gutter guard job will earn you!&quot;); Console.WriteLine(&quot;---------&quot;); Console.WriteLine(&quot;Step One:&quot;); var maths = new Calculator(); maths.Main(); Thread.Sleep(1500); Console.WriteLine(&quot;---------&quot;); Console.WriteLine(&quot;Step Two:&quot;); Console.WriteLine(&quot;What type of gutter material are you using?&quot;); Console.WriteLine(&quot;Gold - [A]&quot;); Console.WriteLine(&quot;Silver - [B]&quot;); Console.WriteLine(&quot;Tin foil - [C]&quot;); //Have MaterialRepo data displayed here depending on user input. Console.ReadKey(); } } } </code></pre> <p>MaterialRepo.cs to house the material info</p> <pre><code>using System; using System.Linq; using System.Collections.Generic; namespace Gutterjob { public class MaterialRepo { public string Id; public string? Metal; public string Price; List&lt;MaterialRepo&gt; matList = new List&lt;MaterialRepo&gt; { new MaterialRepo {Id = &quot;A&quot;, Metal = &quot;Gold&quot;, Price = &quot;$4&quot;}, new MaterialRepo {Id = &quot;B&quot;, Metal = &quot;Silver&quot;, Price = &quot;$2&quot;}, new MaterialRepo {Id = &quot;C&quot;, Metal = &quot;Tin Foil&quot;, Price = &quot;$1&quot;}, }; } } </code></pre> <p>I tried, but failed, to create a LINQ statement. Any help is greatly appreciated.</p>
[ { "answer_id": 74659223, "author": "Alverstone", "author_id": 19703001, "author_profile": "https://Stackoverflow.com/users/19703001", "pm_score": 0, "selected": false, "text": "import React, { useEffect, useState } from 'react';\nimport Headshot from '../../../assets/images/about/Headshot';\n\nconst About = () => {\n const containerRef = useRef(null);\n const [isVisible, setIsVisible] = useState(false);\n\n const callbackFunction = (entries) => {\n const [entry] = entries;\n setIsVisible(entry.isIntersecting);\n }\n const options = {\n root: null,\n rootMargin: \"0px\",\n threshold: 1.0\n }\n\n useEffect(() => {\n const observer = new IntersectionObserver(callbackFunction, options);\n if (containerRef.current) observer.observe(containerRef.current);\n\n return () => {\n if (containerRef.current) observer.unobserve(containerRef.current);\n }\n }, [containerRef, options])\n\n return ( \n <>\n <div className='container aboutContainer' id=\"About\">\n { isVisible ? (\n <>\n <h1 className=\"aboutH1\">This is Me</h1>\n <div className=\"headshot\">\n <Headshot />\n <img \n src=\"/assets/images/about/headshot.webp\" \n alt=\"Brian Quinney - Programmer, Geek, Lifelong Learner\" \n id=\"headshotImg\"\n />\n </div>\n </>\n ) : \"\"}\n <div className=\"venn\">\n <h2 ref={ containerRef }>Who am I?</h2>\n </div>\n </div>\n </>\n );\n}\n\nexport default About\n ref={ containerRef } h2" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74649816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19811649/" ]
74,649,819
<p>I have encountered very weird behavior using angular model when user selects from an option. I will provide screenshots + code snippets. In summary, I am getting undefined for property that is populated. Model object returns expected string but if I directly call the property, it returns undefined.</p> <p>Object that contains all properties, followed by direct call:</p> <p><a href="https://i.stack.imgur.com/p0bQt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/p0bQt.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/ToWhd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ToWhd.png" alt="enter image description here" /></a></p> <pre><code>&lt;ng-template&gt; &lt;label class=&quot;col-sm-4 col-form-label&quot;&gt;Source Name :&lt;/label&gt; &lt;div class=&quot;col-sm-2&quot;&gt; &lt;select [(ngModel)]=&quot;opcoReference.opcoRef.tntSourceName&quot; class=&quot;form-control form-control-sm&quot;&gt; &lt;option *ngFor=&quot;let object of opcoReference.origSourceName&quot; [ngValue]=&quot;object.code&quot;&gt;{{object.desc}}&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;/ng-template&gt; </code></pre>
[ { "answer_id": 74659223, "author": "Alverstone", "author_id": 19703001, "author_profile": "https://Stackoverflow.com/users/19703001", "pm_score": 0, "selected": false, "text": "import React, { useEffect, useState } from 'react';\nimport Headshot from '../../../assets/images/about/Headshot';\n\nconst About = () => {\n const containerRef = useRef(null);\n const [isVisible, setIsVisible] = useState(false);\n\n const callbackFunction = (entries) => {\n const [entry] = entries;\n setIsVisible(entry.isIntersecting);\n }\n const options = {\n root: null,\n rootMargin: \"0px\",\n threshold: 1.0\n }\n\n useEffect(() => {\n const observer = new IntersectionObserver(callbackFunction, options);\n if (containerRef.current) observer.observe(containerRef.current);\n\n return () => {\n if (containerRef.current) observer.unobserve(containerRef.current);\n }\n }, [containerRef, options])\n\n return ( \n <>\n <div className='container aboutContainer' id=\"About\">\n { isVisible ? (\n <>\n <h1 className=\"aboutH1\">This is Me</h1>\n <div className=\"headshot\">\n <Headshot />\n <img \n src=\"/assets/images/about/headshot.webp\" \n alt=\"Brian Quinney - Programmer, Geek, Lifelong Learner\" \n id=\"headshotImg\"\n />\n </div>\n </>\n ) : \"\"}\n <div className=\"venn\">\n <h2 ref={ containerRef }>Who am I?</h2>\n </div>\n </div>\n </>\n );\n}\n\nexport default About\n ref={ containerRef } h2" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74649819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12154734/" ]
74,649,824
<p>is there a way to call a function in a spawned child process, a powershell script, from the parent node js script?</p> <p>node script:</p> <pre><code>const cp = require(&quot;child_process&quot;); const psData = cp.spawn (&quot;powershell -executionpolicy bypass ./powershell-script.ps1&quot;, [], { shell: &quot;powershell.exe&quot;, }); </code></pre> <p>powershell script:</p> <pre><code>function psDoSomething{ # do something } </code></pre>
[ { "answer_id": 74659223, "author": "Alverstone", "author_id": 19703001, "author_profile": "https://Stackoverflow.com/users/19703001", "pm_score": 0, "selected": false, "text": "import React, { useEffect, useState } from 'react';\nimport Headshot from '../../../assets/images/about/Headshot';\n\nconst About = () => {\n const containerRef = useRef(null);\n const [isVisible, setIsVisible] = useState(false);\n\n const callbackFunction = (entries) => {\n const [entry] = entries;\n setIsVisible(entry.isIntersecting);\n }\n const options = {\n root: null,\n rootMargin: \"0px\",\n threshold: 1.0\n }\n\n useEffect(() => {\n const observer = new IntersectionObserver(callbackFunction, options);\n if (containerRef.current) observer.observe(containerRef.current);\n\n return () => {\n if (containerRef.current) observer.unobserve(containerRef.current);\n }\n }, [containerRef, options])\n\n return ( \n <>\n <div className='container aboutContainer' id=\"About\">\n { isVisible ? (\n <>\n <h1 className=\"aboutH1\">This is Me</h1>\n <div className=\"headshot\">\n <Headshot />\n <img \n src=\"/assets/images/about/headshot.webp\" \n alt=\"Brian Quinney - Programmer, Geek, Lifelong Learner\" \n id=\"headshotImg\"\n />\n </div>\n </>\n ) : \"\"}\n <div className=\"venn\">\n <h2 ref={ containerRef }>Who am I?</h2>\n </div>\n </div>\n </>\n );\n}\n\nexport default About\n ref={ containerRef } h2" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74649824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13332238/" ]
74,649,886
<p>I'm trying to assess the expected performance of calculating trigonometry functions as a function of the required precision. Obviously the wall clock time depends on the speed of the underlying arithmetic, so factoring that out by just counting number of operations:</p> <p>Using state-of-the-art algorithms, how many arithmetic operations (add, subtract, multiply, divide) should it take to calculate <code>sin(x)</code>, as a function of the number of bits (or decimal digits) of precision required in the output?</p>
[ { "answer_id": 74650392, "author": "chux - Reinstate Monica", "author_id": 2410359, "author_profile": "https://Stackoverflow.com/users/2410359", "pm_score": 3, "selected": true, "text": "x = π/4 sin(x) sin() / - * sin() cos() sin() * sine_crap() sin()" }, { "answer_id": 74659839, "author": "chux - Reinstate Monica", "author_id": 2410359, "author_profile": "https://Stackoverflow.com/users/2410359", "pm_score": 0, "selected": false, "text": "x = π/4 float float double float double 9/6*2*2" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74649886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45843/" ]
74,649,960
<p>The following is a subset of my geoJSON object which has a combination of Multipolygons and GeometryCollections in its features. The GeometryCollections include multiple types of geometries.</p> <pre><code>json_str = '{&quot;type&quot;: &quot;FeatureCollection&quot;, &quot;features&quot;: [ {&quot;id&quot;: &quot;0&quot;, &quot;type&quot;: &quot;Feature&quot;, &quot;properties&quot;: {&quot;Date&quot;: &quot;2019/07/10&quot;, &quot;PID&quot;: &quot;P1&quot;}, &quot;geometry&quot;: {&quot;type&quot;: &quot;GeometryCollection&quot;, &quot;geometries&quot;: [ {&quot;type&quot;: &quot;MultiPolygon&quot;, &quot;coordinates&quot;: [[[[138.5765, -35.0101], [138.5764, -35.0113], [138.5776, -35.0119], [138.5757, -35.0123], [138.5744, -35.013], [138.5739, -35.0119], [138.574, -35.0115], [138.5746, -35.0101], [138.5757, -35.0097], [138.5773, -35.0088], [138.5765, -35.0101]]], [[[138.6124, -35.0016], [138.612, -35.0011], [138.613, -35.0006], [138.6134, -35.0008], [138.6143, -35.0011], [138.613, -35.0024], [138.6124, -35.0016]]]]}, {&quot;type&quot;: &quot;MultiLineString&quot;, &quot;coordinates&quot;: [[[138.5625, -34.9778], [138.5609, -34.9791]], [[138.6042, -34.9885], [138.6042, -34.9886]]]}, {&quot;type&quot;: &quot;Point&quot;, &quot;coordinates&quot;: [138.6656, -34.8842]}]}}, {&quot;id&quot;: &quot;1&quot;, &quot;type&quot;: &quot;Feature&quot;, &quot;properties&quot;: {&quot;Date&quot;: &quot;2019/07/10&quot;, &quot;PID&quot;: &quot;P2&quot;}, &quot;geometry&quot;: { &quot;type&quot;: &quot;MultiPolygon&quot;, &quot;coordinates&quot;: [[[[138.5731, -34.9273], [138.5741, -34.9281], [138.5752, -34.9273], [138.5763, -34.9266], [138.5779, -34.9269], [138.5785, -34.9268], [138.5797, -34.9272], [138.5807, -34.928], [138.5814, -34.9276], [138.5809, -34.9282], [138.5807, -34.9285], [138.5794, -34.9292], [138.5785, -34.9299], [138.5766, -34.93], [138.5783, -34.9302], [138.5785, -34.9303], [138.5793, -34.9312], [138.5796, -34.9318], [138.579, -34.9332], [138.5795, -34.9336], [138.5803, -34.934], [138.5807, -34.9341], [138.5816, -34.9347], [138.5821, -34.9354], [138.5822, -34.9359], [138.5829, -34.9368], [138.5831, -34.937], [138.5836, -34.9372], [138.5843, -34.9379], [138.5843, -34.939], [138.5829, -34.9394], [138.5823, -34.9395], [138.5817, -34.939], [138.5823, -34.9377], [138.5807, -34.9385], [138.5792, -34.939], [138.5785, -34.9396], [138.5771, -34.9408], [138.5769, -34.9421], [138.5769, -34.9426], [138.5768, -34.944], [138.5785, -34.9437], [138.5788, -34.9441], [138.5789, -34.9444], [138.579, -34.9458], [138.5797, -34.9462], [138.5798, -34.9469], [138.5797, -34.948], [138.5798, -34.9487], [138.5793, -34.9498], [138.5785, -34.9507], [138.577, -34.9516], [138.5763, -34.9523], [138.5752, -34.9534], [138.5741, -34.9543], [138.5727, -34.9545], [138.5719, -34.954], [138.5713, -34.9552], [138.5697, -34.9567], [138.5692, -34.957], [138.5675, -34.9579], [138.5664, -34.9588], [138.5653, -34.9604], [138.5646, -34.9606], [138.5631, -34.9608], [138.5612, -34.9624], [138.5609, -34.9629], [138.56, -34.9642], [138.5597, -34.9652], [138.5609, -34.9655], [138.5613, -34.9657], [138.5618, -34.966], [138.5609, -34.9664], [138.56, -34.9667], [138.5587, -34.967], [138.5565, -34.9678], [138.5565, -34.9678], [138.5565, -34.9678], [138.5565, -34.9678], [138.5565, -34.9678], [138.5579, -34.9685], [138.5587, -34.9688], [138.5592, -34.9692], [138.5609, -34.9695], [138.561, -34.9695], [138.5631, -34.9695], [138.5632, -34.9695], [138.5653, -34.9693], [138.5656, -34.9694], [138.566, -34.9696], [138.5667, -34.9702], [138.5675, -34.9705], [138.5688, -34.9703], [138.5697, -34.9709], [138.5701, -34.971], [138.5711, -34.9714], [138.5697, -34.972], [138.5692, -34.9732], [138.5675, -34.975], [138.5697, -34.9738], [138.5705, -34.9743], [138.5719, -34.975], [138.5732, -34.9732], [138.5734, -34.972], [138.5723, -34.9714], [138.5741, -34.9709], [138.5744, -34.9711], [138.5763, -34.9714], [138.5763, -34.9714], [138.5763, -34.9714], [138.5782, -34.9716], [138.5785, -34.9717], [138.5798, -34.9714], [138.5807, -34.9713], [138.581, -34.9711], [138.5829, -34.9708], [138.5837, -34.9707], [138.5835, -34.9714], [138.5836, -34.9726], [138.5838, -34.9732], [138.5841, -34.974], [138.5842, -34.975], [138.5844, -34.9755], [138.5847, -34.9768], [138.5847, -34.9771], [138.5851, -34.9785], [138.5851, -34.9786], [138.5851, -34.9786], [138.5856, -34.98], [138.5858, -34.9804], [138.5857, -34.9816], [138.5859, -34.9822], [138.5864, -34.9829], [138.5865, -34.984], [138.5864, -34.9847], [138.5869, -34.9858], [138.587, -34.986], [138.5872, -34.9876], [138.5856, -34.989], [138.5873, -34.988], [138.5875, -34.9892], [138.5874, -34.9894], [138.5873, -34.9897], [138.586, -34.9912], [138.5856, -34.9925], [138.5858, -34.993], [138.5854, -34.9945], [138.5873, -34.994], [138.5877, -34.9944], [138.5879, -34.9948], [138.5876, -34.9963], [138.5875, -34.9966], [138.5873, -34.9971], [138.5866, -34.9984], [138.5864, -34.999], [138.5863, -35.0002], [138.5851, -35.0007], [138.5837, -35.0013], [138.5829, -35.0002], [138.5829, -35.0001], [138.5829, -35.0001], [138.5828, -35.0002], [138.5828, -35.0002], [138.582, -35.002], [138.5823, -35.0024], [138.5825, -35.0038], [138.5807, -35.0053], [138.5789, -35.0056], [138.5802, -35.006], [138.5797, -35.0074], [138.5785, -35.0084], [138.5767, -35.0088], [138.5764, -35.0074], [138.5782, -35.0058], [138.5763, -35.0073], [138.5761, -35.0074], [138.5762, -35.0075], [138.5759, -35.0092], [138.5741, -35.0097], [138.5739, -35.011], [138.5719, -35.0126], [138.5705, -35.0121], [138.5697, -35.0119], [138.5695, -35.0128], [138.5693, -35.0131], [138.568, -35.0146], [138.5675, -35.0163], [138.5675, -35.0164], [138.5678, -35.0179], [138.5697, -35.0178], [138.5701, -35.0178], [138.5719, -35.0177], [138.5727, -35.0175], [138.5741, -35.0176], [138.5759, -35.0167], [138.5763, -35.0165], [138.5766, -35.0164], [138.5776, -35.0153], [138.5783, -35.0146], [138.5785, -35.0145], [138.5786, -35.0145], [138.58, -35.0146], [138.5806, -35.0146], [138.5807, -35.0158], [138.5809, -35.0146], [138.5829, -35.0142], [138.5834, -35.0141], [138.5851, -35.0137], [138.5868, -35.0132], [138.5873, -35.0133], [138.5878, -35.0128], [138.5894, -35.0122], [138.5904, -35.012], [138.5916, -35.0123], [138.5925, -35.011], [138.5936, -35.0093], [138.5937, -35.0092], [138.5938, -35.0091], [138.5939, -35.0091], [138.5942, -35.0092], [138.5955, -35.0096], [138.596, -35.0097], [138.5965, -35.0092], [138.5982, -35.0082], [138.5997, -35.0079], [138.6004, -35.0083], [138.6012, -35.0074], [138.6026, -35.0063], [138.6042, -35.0061], [138.6048, -35.007], [138.6069, -35.0056], [138.6053, -35.0051], [138.6048, -35.0045], [138.6042, -35.0043], [138.6045, -35.0038], [138.6048, -35.0034], [138.605, -35.0036], [138.607, -35.0032], [138.6075, -35.0034], [138.6092, -35.0022], [138.6106, -35.0026], [138.6114, -35.0033], [138.6119, -35.0033], [138.6126, -35.0038], [138.6134, -35.004], [138.6136, -35.004], [138.6148, -35.0046], [138.6158, -35.0051], [138.6175, -35.0041], [138.618, -35.004], [138.6181, -35.0038], [138.6202, -35.002], [138.6203, -35.002], [138.6202, -35.0019], [138.6202, -35.0017], [138.6195, -35.0008], [138.618, -35.0004], [138.6158, -35.002], [138.6158, -35.002], [138.6156, -35.0021], [138.6157, -35.002], [138.6143, -35.0013], [138.6136, -35.0008], [138.6128, -35.0008], [138.6118, -35.0002], [138.6115, -35.0001], [138.6114, -35.0], [138.61, -34.9995], [138.6092, -34.9988], [138.6087, -34.9988], [138.6085, -34.9984], [138.6092, -34.998], [138.6111, -34.9966], [138.6114, -34.9958], [138.612, -34.9961], [138.6136, -34.9957], [138.6143, -34.996], [138.6158, -34.9963], [138.617, -34.9948], [138.6167, -34.994], [138.6163, -34.993], [138.6163, -34.9925], [138.6165, -34.9912], [138.6172, -34.99], [138.6175, -34.9894], [138.6179, -34.9877], [138.6178, -34.9876], [138.6176, -34.9861], [138.6176, -34.9858], [138.618, -34.9855], [138.619, -34.9849], [138.6202, -34.9842], [138.6219, -34.984], [138.6224, -34.9839], [138.6225, -34.9839], [138.6226, -34.984], [138.6241, -34.9844], [138.6246, -34.9845], [138.6252, -34.984], [138.6268, -34.9824], [138.6273, -34.9822], [138.6289, -34.9809], [138.6293, -34.9804], [138.6311, -34.9789], [138.6316, -34.9786], [138.6316, -34.9782], [138.6316, -34.9768], [138.6317, -34.9763], [138.6321, -34.975], [138.633, -34.9735], [138.633, -34.9732], [138.6333, -34.973], [138.6345, -34.9714], [138.6342, -34.9707], [138.6333, -34.9704], [138.6323, -34.9704], [138.6314, -34.9696], [138.6332, -34.9679], [138.6311, -34.9695], [138.6292, -34.9694], [138.6289, -34.9692], [138.6279, -34.9686], [138.628, -34.9678], [138.6286, -34.9663], [138.6286, -34.966], [138.6289, -34.9656], [138.6293, -34.9657], [138.6311, -34.9656], [138.6321, -34.9652], [138.6317, -34.966], [138.6326, -34.9666], [138.6333, -34.9678], [138.6334, -34.9678], [138.6334, -34.9678], [138.6349, -34.9683], [138.6355, -34.9681], [138.6359, -34.9678], [138.636, -34.9674], [138.6363, -34.966], [138.6366, -34.9651], [138.6364, -34.9642], [138.636, -34.9638], [138.6355, -34.9637], [138.6338, -34.9638], [138.6333, -34.9635], [138.6326, -34.963], [138.6326, -34.9624], [138.6323, -34.9614], [138.6321, -34.9606], [138.6317, -34.9601], [138.6311, -34.9593], [138.6307, -34.9592], [138.6289, -34.9593], [138.6286, -34.9591], [138.6282, -34.9588], [138.6288, -34.9572], [138.6287, -34.957], [138.6281, -34.9559], [138.6283, -34.9552], [138.6289, -34.9544], [138.6298, -34.9534], [138.6311, -34.9527], [138.6317, -34.953], [138.632, -34.9534], [138.6325, -34.9541], [138.6333, -34.9546], [138.6339, -34.9547], [138.6341, -34.9552], [138.6347, -34.9559], [138.6355, -34.9561], [138.6365, -34.9562], [138.6368, -34.957], [138.6372, -34.9574], [138.6377, -34.9581], [138.6387, -34.958], [138.6383, -34.9588], [138.6391, -34.9595], [138.6398, -34.9606], [138.6398, -34.9607], [138.6399, -34.9616], [138.6401, -34.9623], [138.6403, -34.9624], [138.6399, -34.9625], [138.6385, -34.9642], [138.6388, -34.9651], [138.6391, -34.966], [138.6392, -34.9666], [138.6399, -34.9667], [138.642, -34.966], [138.6421, -34.966], [138.6422, -34.966], [138.6443, -34.9647], [138.6453, -34.9642], [138.6453, -34.9634], [138.6457, -34.9624], [138.6451, -34.9618], [138.6443, -34.9611], [138.6431, -34.9616], [138.6436, -34.9606], [138.6429, -34.9599], [138.6422, -34.9588], [138.6422, -34.9588], [138.6421, -34.9587], [138.6411, -34.9579], [138.6407, -34.957], [138.6404, -34.9566], [138.6399, -34.9559], [138.6391, -34.9558], [138.6394, -34.9552], [138.6388, -34.9543], [138.6385, -34.9534], [138.6385, -34.9528], [138.6384, -34.9516], [138.6381, -34.9513], [138.6377, -34.951], [138.6366, -34.9507], [138.636, -34.9498], [138.6358, -34.9496], [138.6355, -34.9494], [138.6343, -34.949], [138.6333, -34.948], [138.6333, -34.948], [138.6333, -34.948], [138.6321, -34.9472], [138.6319, -34.9462], [138.6315, -34.9459], [138.6311, -34.9455], [138.6301, -34.9453], [138.6289, -34.9449], [138.6284, -34.9449], [138.6284, -34.9444], [138.6278, -34.9435], [138.6275, -34.9426], [138.6283, -34.9413], [138.6285, -34.9408], [138.6283, -34.9395], [138.6278, -34.939], [138.6271, -34.9388], [138.6268, -34.9386], [138.6257, -34.9381], [138.6254, -34.9372], [138.6254, -34.9365], [138.6246, -34.9355], [138.6245, -34.9354], [138.6245, -34.9354], [138.6238, -34.9342], [138.623, -34.9336], [138.6233, -34.9329], [138.6237, -34.9318], [138.6229, -34.9314], [138.6224, -34.9311], [138.6219, -34.9304], [138.6216, -34.93], [138.6221, -34.9284], [138.6221, -34.9282], [138.6215, -34.9271], [138.6211, -34.9264], [138.6214, -34.9255], [138.6217, -34.9246], [138.6224, -34.9239], [138.6234, -34.9238], [138.6246, -34.9238], [138.6258, -34.9236], [138.6268, -34.9236], [138.6285, -34.9232], [138.6289, -34.9231], [138.6304, -34.9228], [138.6311, -34.9226], [138.6315, -34.9225], [138.6333, -34.922], [138.6343, -34.921], [138.6339, -34.9205], [138.6333, -34.9203], [138.6322, -34.9202], [138.6311, -34.9202], [138.6302, -34.92], [138.6289, -34.9197], [138.6284, -34.9197], [138.6268, -34.9196], [138.6264, -34.9196], [138.6246, -34.9196], [138.6239, -34.9198], [138.6224, -34.9199], [138.6205, -34.921], [138.6202, -34.9215], [138.6191, -34.9228], [138.618, -34.9231], [138.6175, -34.9232], [138.6163, -34.9228], [138.6159, -34.9227], [138.6159, -34.921], [138.6161, -34.9208], [138.6168, -34.9192], [138.6178, -34.9175], [138.6158, -34.9183], [138.614, -34.9192], [138.6136, -34.9199], [138.6135, -34.9193], [138.6114, -34.9196], [138.6111, -34.9195], [138.6099, -34.9192], [138.6095, -34.919], [138.6092, -34.9189], [138.6085, -34.918], [138.6079, -34.9174], [138.6081, -34.9166], [138.6081, -34.9156], [138.6078, -34.915], [138.6079, -34.9138], [138.6083, -34.9128], [138.6081, -34.912], [138.6085, -34.9108], [138.6085, -34.9102], [138.6092, -34.9097], [138.6099, -34.9097], [138.6114, -34.9094], [138.6135, -34.9084], [138.6136, -34.9084], [138.6145, -34.9066], [138.6156, -34.905], [138.6157, -34.9048], [138.6154, -34.9033], [138.6152, -34.903], [138.6147, -34.9021], [138.6146, -34.9012], [138.6156, -34.8996], [138.6156, -34.8994], [138.6158, -34.8993], [138.6173, -34.8976], [138.618, -34.8971], [138.619, -34.8958], [138.6188, -34.8952], [138.6184, -34.894], [138.6182, -34.8939], [138.618, -34.8937], [138.6162, -34.8937], [138.6158, -34.8937], [138.6147, -34.894], [138.6136, -34.8945], [138.613, -34.8945], [138.6114, -34.8956], [138.6103, -34.8949], [138.6092, -34.8942], [138.6087, -34.8945], [138.607, -34.8952], [138.6063, -34.8958], [138.6056, -34.897], [138.607, -34.8964], [138.608, -34.8969], [138.608, -34.8976], [138.6076, -34.8989], [138.6073, -34.8994], [138.607, -34.8998], [138.6051, -34.901], [138.6048, -34.9011], [138.6047, -34.9012], [138.6034, -34.9024], [138.6048, -34.9027], [138.6052, -34.9027], [138.6052, -34.903], [138.6048, -34.9034], [138.6042, -34.9035], [138.6026, -34.9038], [138.6019, -34.9036], [138.6004, -34.904], [138.5994, -34.9039], [138.5982, -34.9033], [138.598, -34.9032], [138.596, -34.9031], [138.5959, -34.9031], [138.5958, -34.903], [138.5951, -34.902], [138.5947, -34.9012], [138.5943, -34.9009], [138.5938, -34.9008], [138.5931, -34.9], [138.5927, -34.8994], [138.593, -34.8984], [138.5916, -34.8982], [138.5913, -34.8979], [138.5906, -34.8976], [138.5911, -34.8963], [138.5894, -34.8972], [138.5883, -34.8968], [138.5876, -34.8958], [138.5885, -34.8948], [138.5873, -34.8955], [138.5857, -34.8953], [138.5851, -34.895], [138.5829, -34.8958], [138.5841, -34.8967], [138.5834, -34.8976], [138.5829, -34.8992], [138.5815, -34.8994], [138.5815, -34.9005], [138.5829, -34.8996], [138.5838, -34.9004], [138.5851, -34.901], [138.5852, -34.9011], [138.5853, -34.9012], [138.5855, -34.9027], [138.5857, -34.903], [138.5851, -34.9047], [138.5849, -34.9048], [138.5829, -34.9056], [138.5819, -34.9056], [138.5807, -34.9058], [138.5796, -34.9066], [138.5798, -34.9074], [138.5807, -34.9083], [138.5808, -34.9083], [138.5829, -34.9076], [138.5848, -34.9066], [138.5851, -34.9054], [138.5852, -34.9065], [138.5852, -34.9066], [138.5851, -34.9068], [138.5837, -34.9084], [138.583, -34.9101], [138.5851, -34.9094], [138.5858, -34.9096], [138.5857, -34.9102], [138.5856, -34.9116], [138.5861, -34.912], [138.5866, -34.9126], [138.5873, -34.9129], [138.5882, -34.9131], [138.5894, -34.9132], [138.59, -34.9134], [138.5902, -34.9138], [138.5901, -34.9151], [138.5908, -34.9156], [138.5905, -34.9166], [138.5899, -34.9174], [138.5894, -34.9183], [138.5884, -34.9183], [138.5873, -34.9175], [138.5872, -34.9175], [138.5872, -34.9174], [138.5859, -34.9168], [138.5851, -34.9174], [138.5845, -34.9174], [138.5829, -34.9175], [138.5828, -34.9175], [138.5827, -34.9174], [138.582, -34.9164], [138.5809, -34.9156], [138.5827, -34.9139], [138.5828, -34.9138], [138.5823, -34.9125], [138.5807, -34.9136], [138.58, -34.9126], [138.5797, -34.912], [138.5797, -34.911], [138.5785, -34.9113], [138.5773, -34.9112], [138.5763, -34.9108], [138.5751, -34.9112], [138.5741, -34.9116], [138.5719, -34.912], [138.5719, -34.912], [138.5718, -34.912], [138.5697, -34.913], [138.568, -34.9134], [138.5675, -34.9137], [138.567, -34.9138], [138.5672, -34.9141], [138.5675, -34.9142], [138.5688, -34.9146], [138.5697, -34.9151], [138.5699, -34.9155], [138.5708, -34.9156], [138.5702, -34.9171], [138.5719, -34.9157], [138.5737, -34.916], [138.5741, -34.9161], [138.575, -34.9167], [138.575, -34.9174], [138.5747, -34.9187], [138.5755, -34.9192], [138.5741, -34.9196], [138.5736, -34.9196], [138.5719, -34.9196], [138.5703, -34.921], [138.5697, -34.9213], [138.5693, -34.9214], [138.568, -34.921], [138.5693, -34.9195], [138.5675, -34.9208], [138.5656, -34.9208], [138.5653, -34.9208], [138.5648, -34.921], [138.5631, -34.9217], [138.5624, -34.9216], [138.5609, -34.9214], [138.5605, -34.9214], [138.5587, -34.9215], [138.5579, -34.9217], [138.5565, -34.9222], [138.5546, -34.9226], [138.5543, -34.9227], [138.5538, -34.9228], [138.5521, -34.9232], [138.5503, -34.9243], [138.55, -34.9245], [138.548, -34.9246], [138.5487, -34.9256], [138.55, -34.9249], [138.5505, -34.926], [138.5509, -34.9264], [138.551, -34.9274], [138.5513, -34.9282], [138.5516, -34.9287], [138.5516, -34.93], [138.5517, -34.9304], [138.5521, -34.9314], [138.5529, -34.93], [138.5528, -34.9295], [138.5529, -34.9282], [138.5537, -34.9269], [138.554, -34.9264], [138.5543, -34.9263], [138.5546, -34.9262], [138.5565, -34.9262], [138.5568, -34.9262], [138.5573, -34.9264], [138.5584, -34.9267], [138.5587, -34.9269], [138.5603, -34.9269], [138.5609, -34.9274], [138.5623, -34.9271], [138.5631, -34.9269], [138.5646, -34.927], [138.5653, -34.927], [138.5662, -34.9275], [138.5675, -34.9282], [138.5664, -34.9291], [138.5675, -34.9294], [138.5694, -34.9282], [138.5677, -34.9281], [138.5693, -34.9264], [138.5697, -34.9263], [138.5699, -34.9263], [138.5719, -34.9261], [138.5722, -34.9262], [138.5724, -34.9264], [138.5731, -34.9273]], [[138.6201, -34.9678], [138.6201, -34.9678], [138.6195, -34.9665], [138.6194, -34.966], [138.6202, -34.9653], [138.6209, -34.9654], [138.622, -34.966], [138.6208, -34.9673], [138.6224, -34.9665], [138.6245, -34.966], [138.6246, -34.966], [138.6246, -34.966], [138.6246, -34.966], [138.6246, -34.966], [138.6227, -34.9678], [138.6224, -34.9681], [138.622, -34.9681], [138.6202, -34.9678], [138.6201, -34.9678]], [[138.642, -34.9643], [138.642, -34.9642], [138.6421, -34.964], [138.6422, -34.9641], [138.6423, -34.9642], [138.6421, -34.9652], [138.642, -34.9643]], [[138.5719, -34.9643], [138.5718, -34.9643], [138.5697, -34.9645], [138.5692, -34.9646], [138.5675, -34.9648], [138.5663, -34.9652], [138.5659, -34.9642], [138.5675, -34.963], [138.5686, -34.9633], [138.5697, -34.9637], [138.5706, -34.9624], [138.5719, -34.9613], [138.5731, -34.9606], [138.5741, -34.9602], [138.5745, -34.9603], [138.5753, -34.9606], [138.5745, -34.9621], [138.5763, -34.9624], [138.5763, -34.9624], [138.5763, -34.9624], [138.5763, -34.9624], [138.5745, -34.9642], [138.5741, -34.9644], [138.5739, -34.9643], [138.5719, -34.9643]], [[138.5824, -34.9628], [138.5822, -34.9624], [138.5818, -34.9614], [138.5812, -34.9606], [138.5814, -34.96], [138.5811, -34.9588], [138.5829, -34.9583], [138.5838, -34.958], [138.5838, -34.9588], [138.5839, -34.9597], [138.5838, -34.9606], [138.5834, -34.9619], [138.5832, -34.9624], [138.5829, -34.9627], [138.5824, -34.9628]], [[138.6047, -34.9985], [138.6047, -34.9984], [138.6048, -34.9982], [138.605, -34.9982], [138.6055, -34.9984], [138.6048, -34.9985], [138.6047, -34.9985]]], [[[138.6132, -34.916], [138.6136, -34.9163], [138.6156, -34.9156], [138.6143, -34.9151], [138.6144, -34.9138], [138.6146, -34.913], [138.615, -34.912], [138.6148, -34.911], [138.6142, -34.9102], [138.6139, -34.91], [138.6136, -34.9085], [138.6124, -34.9102], [138.6114, -34.9112], [138.6108, -34.912], [138.611, -34.9123], [138.6114, -34.9125], [138.6123, -34.9131], [138.6127, -34.9138], [138.6129, -34.9144], [138.6131, -34.9156], [138.6132, -34.916]]]]}}]}' </code></pre> <p>I'm trying to iterate over all my features and remove all geometries that are not Multipolygons or Polygons from my GeometryCollections. And converting all the GeomeetryCollections into Multipolygons as well.</p> <p>I have tried the following in Python, with no luck</p> <pre><code>import json geojson_obj = json.loads(json_str) features = geojson_obj ['features'] for feature in features: if feature['geometry']['type'] == 'GeometryCollection': for geometry in feature['geometry']['geometries']: if geometry['type'] != 'MultiPolygon': geometry = None #maybe? #print(geometry) </code></pre>
[ { "answer_id": 74650392, "author": "chux - Reinstate Monica", "author_id": 2410359, "author_profile": "https://Stackoverflow.com/users/2410359", "pm_score": 3, "selected": true, "text": "x = π/4 sin(x) sin() / - * sin() cos() sin() * sine_crap() sin()" }, { "answer_id": 74659839, "author": "chux - Reinstate Monica", "author_id": 2410359, "author_profile": "https://Stackoverflow.com/users/2410359", "pm_score": 0, "selected": false, "text": "x = π/4 float float double float double 9/6*2*2" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74649960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14109040/" ]
74,649,965
<p>I got an old .net4.8 web app that uses MVC and controllers and trying to convert(Rewrite) it to .net 7 razor pages.</p> <p>I am trying to change the old url routing to be a standard.</p> <p>My Razor page routeing works fine and is as follows.</p> <pre><code>@page &quot;/flights/{FromIata:length(3)?}/{ToIata:length(3)?}&quot; </code></pre> <p>i have also tried</p> <pre><code>@page &quot;/flights/{FromIata?}/{ToIata?}&quot; </code></pre> <p>in my program.cs I added the other route conventions.</p> <pre><code>builder.Services.AddRazorPages() .AddRazorPagesOptions(ops =&gt; { ops.Conventions.Insert(0, new RouteTemplateModelConventionRazorPages()); }) .AddRazorPagesOptions(options =&gt; { options.Conventions.AddPageRoute(&quot;/Flights&quot;, &quot;/flights/from-{FromIata:length(3)}-to-{ToIata:length(3)}&quot;); options.Conventions.AddPageRoute(&quot;/Flights&quot;, &quot;/flights/{FromIata:length(3)}-{ToIata:length(3)}&quot;); options.Conventions.AddPageRoute(&quot;/Flights&quot;, &quot;/flights/{FromIata:length(3)}-to-{ToIata:length(3)}&quot;); options.Conventions.AddPageRoute(&quot;/Flights&quot;, &quot;/flights/from-{FromIata:length(3)}-{FromCity}-to-{ToIata:length(3)}-{ToCity}&quot;); options.Conventions.AddPageRoute(&quot;/Flights&quot;, &quot;/flights/to-{ToIata:length(3)}&quot;); options.Conventions.AddPageRoute(&quot;/Flights&quot;, &quot;/flights/to-{ToIata:length(3)}-{CityName}&quot;); options.Conventions.AddPageRoute(&quot;/Flights&quot;, &quot;/flights/{*url}&quot;); }) </code></pre> <p>if I browse to the page with the standard convection it works fine but if i use any of the other conventions I get a 404 error.</p> <p>What I am trying to do is either load the page with the other convention. i.e /Flights/to-kul-kuala%20lumpur or if i use that conventions it does a permanent redirect to the new url format. i.e Flights/kul</p> <p>Any suggestions would be greatly appreciated.</p> <p>Thanks in advance.</p>
[ { "answer_id": 74651922, "author": "Mike Brind", "author_id": 134725, "author_profile": "https://Stackoverflow.com/users/134725", "pm_score": 1, "selected": false, "text": "@page @page \"flights/{FromIata:length(3)?}/{ToIata:length(3)?}\"\n" }, { "answer_id": 74662315, "author": "Trevor", "author_id": 9666854, "author_profile": "https://Stackoverflow.com/users/9666854", "pm_score": 0, "selected": false, "text": "@page \"flights/{FromIata:length(3)?}/{ToIata:length(3)?}\"\n options.Conventions.AddPageRoute(\"/Flights/Index\", \"{Culture}/Flights/from-{FromIata:length(3)}-to-{ToIata:length(3)}\");\n options.Conventions.AddPageRoute(\"/Flights/Index\", \"{Culture}/Flights/{FromIata:length(3)}-{ToIata:length(3)}\");\n options.Conventions.AddPageRoute(\"/Flights/Index\", \"{Culture}/Flights/{FromIata:length(3)}-to-{ToIata:length(3)}\");\n options.Conventions.AddPageRoute(\"/Flights/Index\", \"{Culture}/Flights/from-{FromIata:length(3)}-{FromCity}-to-{ToIata:length(3)}-{ToCity}\");\n options.Conventions.AddPageRoute(\"/Flights/Index\", \"{Culture}/Flights/to-{ToIata:length(3)}\");\n options.Conventions.AddPageRoute(\"/Flights/Index\", \"{Culture}/flights/to-{ToIata:length(3)}-{CityName}\");\n options.Conventions.AddPageRoute(\"/Flights/Index\", \"{Culture}/flights/{*url}\");\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74649965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9666854/" ]
74,649,973
<p>I am working on a single page application (SPA) app that grants access to specific paths in the application, based on roles setup in Azure AD for the user logging in. As per this <a href="https://github.com/Azure-Samples/ms-identity-javascript-react-tutorial/tree/main/5-AccessControl/1-call-api-roles" rel="nofollow noreferrer">https://github.com/Azure-Samples/ms-identity-javascript-react-tutorial/tree/main/5-AccessControl/1-call-api-roles</a></p> <p>This is my '<strong>authConfig.js</strong>' file - you can see the redirectUri</p> <pre><code>const clientId = window.REACT_APP_CLIENTID export const msalConfig = { auth: { clientId: clientId, authority: window.REACT_APP_AUTHORITY, redirectUri: 'http://localhost:3000/todolist/', // You must register this URI on Azure Portal/App Registration. Defaults to window.location.origin postLogoutRedirectUri: &quot;/&quot;, // Indicates the page to navigate after logout. navigateToLoginRequestUrl: false, // If &quot;true&quot;, will navigate back to the original request location before processing the auth code response. }, cache: { cacheLocation: &quot;sessionStorage&quot;, // Configures cache location. &quot;sessionStorage&quot; is more secure, but &quot;localStorage&quot; gives you SSO between tabs. storeAuthStateInCookie: false, // Set this to &quot;true&quot; if you are having issues on IE11 or Edge }, system: { loggerOptions: { loggerCallback: (level, message, containsPii) =&gt; { if (containsPii) { return; } switch (level) { case LogLevel.Error: console.error(message); return; case LogLevel.Info: console.info(message); return; case LogLevel.Verbose: console.debug(message); return; case LogLevel.Warning: console.warn(message); return; } } } } }; /** * Add here the endpoints and scopes when obtaining an access token for protected web APIs. For more information, see: * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/resources-and-scopes.md */ export const protectedResources = { apiTodoList: { todoListEndpoint: window.REACT_APP_APIENDPOINT+&quot;/api/v2/support/list&quot;, scopes: [window.REACT_APP_APIENDPOINT+&quot;/access_as_user&quot;], }, } /** * Scopes you add here will be prompted for user consent during sign-in. * By default, MSAL.js will add OIDC scopes (openid, profile, email) to any login request. * For more information about OIDC scopes, visit: * https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent#openid-connect-scopes */ export const loginRequest = { scopes: [...protectedResources.apiTodoList.scopes] }; export const appRoles = { TaskUser: &quot;TaskUser&quot;, TaskAdmin: &quot;TaskAdmin&quot;, TrialAdmin: &quot;Trial.Admin&quot;, GlobalAdmin: &quot;Global.Admin&quot; } </code></pre> <p>Here is the <strong>App.jsx</strong> file (I believe there needs to be some change made here). You can see 'RouteGuard' that renders the Component {<em>TodoList</em>}, when the path '<em>todolist</em>' is accessed.</p> <pre><code>import { BrowserRouter as Router, Switch, Route } from &quot;react-router-dom&quot;; import { MsalProvider } from &quot;@azure/msal-react&quot;; import { RouteGuard } from './components/RouteGuard'; import { PageLayout } from &quot;./components/PageLayout&quot;; import { TodoList } from &quot;./pages/TodoList&quot;; import { appRoles } from &quot;./authConfig&quot;; import &quot;./styles/App.css&quot;; const Pages = () =&gt; { return ( &lt;Switch&gt; &lt;RouteGuard exact path='/todolist/' roles={[appRoles.TaskUser, appRoles.TaskAdmin, appRoles.TrialAdmin, appRoles.GlobalAdmin]} Component={TodoList} /&gt; &lt;/Switch&gt; ) } /** * msal-react is built on the React context API and all parts of your app that require authentication must be * wrapped in the MsalProvider component. You will first need to initialize an instance of PublicClientApplication * then pass this to MsalProvider as a prop. All components underneath MsalProvider will have access to the * PublicClientApplication instance via context as well as all hooks and components provided by msal-react. For more, visit: * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-react/docs/getting-started.md */ const App = ({ instance }) =&gt; { return ( &lt;Router&gt; &lt;MsalProvider instance={instance}&gt; &lt;PageLayout&gt; &lt;Pages instance={instance} /&gt; &lt;/PageLayout&gt; &lt;/MsalProvider&gt; &lt;/Router&gt; ); } export default App; </code></pre> <p>So as far as my understanding goes, the path '<em>todolist</em>' is accessed with the listed role, and component is rendered</p> <p>When logged in, The navigation bar at the top renders with login request, after authentication (<strong></strong>). It has the button rendered, with a click function that 'href's to the path '/todolist'.</p> <pre><code>import { AuthenticatedTemplate, UnauthenticatedTemplate, useMsal } from &quot;@azure/msal-react&quot;; import { Nav, Navbar, Button, Dropdown, DropdownButton} from &quot;react-bootstrap&quot;; import React, { useState, useEffect } from &quot;react&quot;; import { loginRequest } from &quot;../authConfig&quot;; import { InteractionStatus, InteractionType } from &quot;@azure/msal-browser&quot;; import &quot;../styles/App.css&quot;; import logo from &quot;../public/images/logo.jpg&quot;; export const NavigationBar = (props) =&gt; { const { instance } = useMsal(); const { inProgress } = useMsal(); const [isAuthorized, setIsAuthorized] = useState(false); //The below function is needed incase you want to login using Popup and not redirect const handleLogin = () =&gt; { instance.loginPopup(loginRequest) .catch((error) =&gt; console.log(error)) } /** * Most applications will need to conditionally render certain components based on whether a user is signed in or not. * msal-react provides 2 easy ways to do this. AuthenticatedTemplate and UnauthenticatedTemplate components will * only render their children if a user is authenticated or unauthenticated, respectively. */ return ( &lt;&gt; &lt;Navbar className=&quot;color-custom&quot; variant=&quot;dark&quot;&gt; &lt;a className=&quot;navbar-brand&quot; href=&quot;/&quot;&gt;&lt;img src={logo} className=&quot;navbarLogo&quot; alt=&quot;TODDOLIST1&quot;/&gt;&lt;/a&gt; &lt;AuthenticatedTemplate&gt; &lt;Nav.Link as={Button} id=&quot;signupbutton&quot; variant=&quot;dark&quot; className=&quot;signupNav&quot; href=&quot;/todolist&quot;&gt;&lt;strong&gt;List&lt;/strong&gt;&lt;/Nav.Link&gt; &lt;Button variant=&quot;warning&quot; className=&quot;ml-auto&quot; drop=&quot;left&quot; title=&quot;Sign Out&quot; onClick={() =&gt; instance.logoutRedirect({ postLogoutRedirectUri: &quot;/&quot; })}&gt;&lt;strong&gt;Sign Out&lt;/strong&gt;&lt;/Button&gt; &lt;/AuthenticatedTemplate&gt; &lt;UnauthenticatedTemplate&gt; &lt;Button variant=&quot;dark&quot; className=&quot;ml-auto&quot; drop=&quot;left&quot; title=&quot;Sign In&quot; onClick={() =&gt; instance.loginRedirect(loginRequest)}&gt;Sign In&lt;/Button&gt; &lt;/UnauthenticatedTemplate&gt; &lt;/Navbar&gt; &lt;/&gt; ); }; </code></pre> <p>Here is the <strong>RouteGuard.jsx</strong> component that renders based on roles/authorization.</p> <pre><code>import React, { useState, useEffect } from &quot;react&quot;; import { Route } from &quot;react-router-dom&quot;; import { useMsal } from &quot;@azure/msal-react&quot;; export const RouteGuard = ({ Component, ...props }) =&gt; { const { instance } = useMsal(); const [isAuthorized, setIsAuthorized] = useState(false); const onLoad = async () =&gt; { const currentAccount = instance.getActiveAccount(); if (currentAccount &amp;&amp; currentAccount.idTokenClaims['roles']) { let intersection = props.roles .filter(role =&gt; currentAccount.idTokenClaims['roles'].includes(role)); if (intersection.length &gt; 0) { setIsAuthorized(true); } } } useEffect(() =&gt; { onLoad(); }, [instance]); return ( &lt;&gt; { isAuthorized ? &lt;Route {...props} render={routeProps =&gt; &lt;Component {...routeProps} /&gt;} /&gt; : &lt;div className=&quot;data-area-div&quot;&gt; &lt;h3&gt;You are unauthorized to view this content.&lt;/h3&gt; &lt;/div&gt; } &lt;/&gt; ); }; </code></pre> <p>I want the application to directly go to the '/todolist' and render the components within. My redirect uri, does not seem to work. When i login with the required role, it always renders 'You are unauthorized to view this content' as per the RouteGuard file. The URI is /signuplist/ but still the children props are not rendered. <strong>ONLY WHEN I CLICK</strong> the button 'Todolist' (as per NavigationBar.jsx), does it go and render the child props properly. Redirection does not work as expected. <strong>I want it to directly go to /todolist and render the page, child components</strong> Any suggestions ?</p>
[ { "answer_id": 74651922, "author": "Mike Brind", "author_id": 134725, "author_profile": "https://Stackoverflow.com/users/134725", "pm_score": 1, "selected": false, "text": "@page @page \"flights/{FromIata:length(3)?}/{ToIata:length(3)?}\"\n" }, { "answer_id": 74662315, "author": "Trevor", "author_id": 9666854, "author_profile": "https://Stackoverflow.com/users/9666854", "pm_score": 0, "selected": false, "text": "@page \"flights/{FromIata:length(3)?}/{ToIata:length(3)?}\"\n options.Conventions.AddPageRoute(\"/Flights/Index\", \"{Culture}/Flights/from-{FromIata:length(3)}-to-{ToIata:length(3)}\");\n options.Conventions.AddPageRoute(\"/Flights/Index\", \"{Culture}/Flights/{FromIata:length(3)}-{ToIata:length(3)}\");\n options.Conventions.AddPageRoute(\"/Flights/Index\", \"{Culture}/Flights/{FromIata:length(3)}-to-{ToIata:length(3)}\");\n options.Conventions.AddPageRoute(\"/Flights/Index\", \"{Culture}/Flights/from-{FromIata:length(3)}-{FromCity}-to-{ToIata:length(3)}-{ToCity}\");\n options.Conventions.AddPageRoute(\"/Flights/Index\", \"{Culture}/Flights/to-{ToIata:length(3)}\");\n options.Conventions.AddPageRoute(\"/Flights/Index\", \"{Culture}/flights/to-{ToIata:length(3)}-{CityName}\");\n options.Conventions.AddPageRoute(\"/Flights/Index\", \"{Culture}/flights/{*url}\");\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74649973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9188188/" ]
74,649,985
<p>My understanding is that SMIL animations are supported by chrome; however my svg SMIL animation <strong>does not</strong> in Chrome (v107) while it <strong>does</strong> work in Safari (v16.0)</p> <p>Here's a <a href="https://codepen.io/nickbewley/pen/zYjpgNR" rel="nofollow noreferrer">link</a> to a codepen illustrating the issue. Why won't this <code>&lt;animation&gt;</code> work across browsers?</p> <pre><code>&lt;svg width=&quot;46&quot; height=&quot;62&quot; viewBox=&quot;0 0 46 62&quot; fill=&quot;none&quot; xmlns=&quot;http://www.w3.org/2000/svg&quot;&gt; &lt;path d=&quot;M 23 40 C 26.376 40 28.889 41.717 29.586 42.414 C 31.827 44.655 33 46.675 33 50 C 33 51.479 32.678 52.894 32.096 54.17 C 31.523 55.427 30.696 56.55 29.676 57.467 C 27.932 59.032 25.618 60 22.999 60 C 20.386 60 18.076 59.036 16.334 57.477 C 15.309 56.558 14.479 55.432 13.904 54.17 C 13.322 52.894 13 51.479 13 50 C 13 46.675 14.173 44.655 16.414 42.414 C 17.111 41.717 19.624 40 23 40 Z&quot; id=&quot;shape&quot; fill=&quot;#007AFF&quot; stroke=&quot;white&quot; stroke-width=&quot;4&quot;&gt; &lt;animate attributename=&quot;d&quot; begin=&quot;G.click&quot; from=&quot;M 23 40 C 26.376 40 28.889 41.717 29.586 42.414 C 31.827 44.655 33 46.675 33 50 C 33 51.479 32.678 52.894 32.096 54.17 C 31.523 55.427 30.696 56.55 29.676 57.467 C 27.932 59.032 25.618 60 22.999 60 C 20.386 60 18.076 59.036 16.334 57.477 C 15.309 56.558 14.479 55.432 13.904 54.17 C 13.322 52.894 13 51.479 13 50 C 13 46.675 14.173 44.655 16.414 42.414 C 17.111 41.717 19.624 40 23 40 Z&quot; to=&quot;M 23 2 C 29.018 2 34.385 4.034 38.179 7.421 C 41.794 10.647 44 15.131 44 20.365 C 44 22.74 43.043 26.026 41.334 29.89 C 39.649 33.7 37.33 37.861 34.818 41.916 C 30.621 48.692 25.957 55.057 22.998 58.816 C 20.041 55.06 15.379 48.7 11.182 41.928 C 8.671 37.873 6.351 33.712 4.666 29.901 C 2.958 26.036 2 22.746 2 20.365 C 2 15.119 4.203 10.637 7.812 7.416 C 11.606 4.029 16.976 2 23 2 Z&quot; dur=&quot;.4s&quot; /&gt; &lt;/path&gt; &lt;/svg&gt; </code></pre>
[ { "answer_id": 74650269, "author": "Kaiido", "author_id": 3702797, "author_profile": "https://Stackoverflow.com/users/3702797", "pm_score": 3, "selected": true, "text": "document.querySelector(\"button\").addEventListener(\"click\", (evt) => {\n document.querySelector(\"path animate\").beginElement();\n}); body {\n background-color: green;\n}\n\nsvg {\n margin: 0 auto;\n} <svg width=\"146\" height=\"62\" viewBox=\"0 0 146 62\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n <path d=\"M 23 40 C 26.376 40 28.889 41.717 29.586 42.414 C 31.827 44.655 33 46.675 33 50 C 33 51.479 32.678 52.894 32.096 54.17 C 31.523 55.427 30.696 56.55 29.676 57.467 C 27.932 59.032 25.618 60 22.999 60 C 20.386 60 18.076 59.036 16.334 57.477 C 15.309 56.558 14.479 55.432 13.904 54.17 C 13.322 52.894 13 51.479 13 50 C 13 46.675 14.173 44.655 16.414 42.414 C 17.111 41.717 19.624 40 23 40 Z\" id=\"shape\" fill=\"#007AFF\" stroke=\"white\" stroke-width=\"4\">\n <animate \n attributename=\"d\"\n begin=\"indefinite\"\n from=\"M 23 40 C 26.376 40 28.889 41.717 29.586 42.414 C 31.827 44.655 33 46.675 33 50 C 33 51.479 32.678 52.894 32.096 54.17 C 31.523 55.427 30.696 56.55 29.676 57.467 C 27.932 59.032 25.618 60 22.999 60 C 20.386 60 18.076 59.036 16.334 57.477 C 15.309 56.558 14.479 55.432 13.904 54.17 C 13.322 52.894 13 51.479 13 50 C 13 46.675 14.173 44.655 16.414 42.414 C 17.111 41.717 19.624 40 23 40 Z\"\n to=\"M 23 2 C 29.018 2 34.385 4.034 38.179 7.421 C 41.794 10.647 44 15.131 44 20.365 C 44 22.74 43.043 26.026 41.334 29.89 C 39.649 33.7 37.33 37.861 34.818 41.916 C 30.621 48.692 25.957 55.057 22.998 58.816 C 20.041 55.06 15.379 48.7 11.182 41.928 C 8.671 37.873 6.351 33.712 4.666 29.901 C 2.958 26.036 2 22.746 2 20.365 C 2 15.119 4.203 10.637 7.812 7.416 C 11.606 4.029 16.976 2 23 2 Z\" \n dur=\"0.4s\" \n />\n </path>\n</svg>\n<button>\n start animation\n</button> <svg> body {\n background-color: green;\n}\n\nsvg {\n margin: 0 auto;\n} <svg width=\"146\" height=\"62\" viewBox=\"0 0 146 62\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n <path d=\"M 23 40 C 26.376 40 28.889 41.717 29.586 42.414 C 31.827 44.655 33 46.675 33 50 C 33 51.479 32.678 52.894 32.096 54.17 C 31.523 55.427 30.696 56.55 29.676 57.467 C 27.932 59.032 25.618 60 22.999 60 C 20.386 60 18.076 59.036 16.334 57.477 C 15.309 56.558 14.479 55.432 13.904 54.17 C 13.322 52.894 13 51.479 13 50 C 13 46.675 14.173 44.655 16.414 42.414 C 17.111 41.717 19.624 40 23 40 Z\" id=\"shape\" fill=\"#007AFF\" stroke=\"white\" stroke-width=\"4\">\n <animate \n attributename=\"d\"\n begin=\"G.click\"\n from=\"M 23 40 C 26.376 40 28.889 41.717 29.586 42.414 C 31.827 44.655 33 46.675 33 50 C 33 51.479 32.678 52.894 32.096 54.17 C 31.523 55.427 30.696 56.55 29.676 57.467 C 27.932 59.032 25.618 60 22.999 60 C 20.386 60 18.076 59.036 16.334 57.477 C 15.309 56.558 14.479 55.432 13.904 54.17 C 13.322 52.894 13 51.479 13 50 C 13 46.675 14.173 44.655 16.414 42.414 C 17.111 41.717 19.624 40 23 40 Z\"\n to=\"M 23 2 C 29.018 2 34.385 4.034 38.179 7.421 C 41.794 10.647 44 15.131 44 20.365 C 44 22.74 43.043 26.026 41.334 29.89 C 39.649 33.7 37.33 37.861 34.818 41.916 C 30.621 48.692 25.957 55.057 22.998 58.816 C 20.041 55.06 15.379 48.7 11.182 41.928 C 8.671 37.873 6.351 33.712 4.666 29.901 C 2.958 26.036 2 22.746 2 20.365 C 2 15.119 4.203 10.637 7.812 7.416 C 11.606 4.029 16.976 2 23 2 Z\" \n dur=\"0.4s\" \n />\n </path>\n</svg>\n<!-- really just to show how Chrome's bug behave don't do that... -->\n<button style=\"position: relative\">\n <svg id=G style=\"width:100%; height:100%; position:absolute; left:0; top:0;\"></svg>\n start animation\n</button> 0 dur" }, { "answer_id": 74659037, "author": "Danny '365CSI' Engelman", "author_id": 2520800, "author_profile": "https://Stackoverflow.com/users/2520800", "pm_score": 0, "selected": false, "text": "body {\n background-color: green;\n}\n\nsvg {\n margin: 0 auto;\n} <svg-marker color=\"gold\"></svg-marker>\n\n<script>\ncustomElements.define(\"svg-marker\", class extends HTMLElement{\n connectedCallback(){\n this.innerHTML = `\n <svg width=\"146\" height=\"62\" viewBox=\"0 0 146 62\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n <path d=\"M 23 40 C 26.376 40 28.889 41.717 29.586 42.414 C 31.827 44.655 33 46.675 33 50 C 33 51.479 32.678 52.894 32.096 54.17 C 31.523 55.427 30.696 56.55 29.676 57.467 C 27.932 59.032 25.618 60 22.999 60 C 20.386 60 18.076 59.036 16.334 57.477 C 15.309 56.558 14.479 55.432 13.904 54.17 C 13.322 52.894 13 51.479 13 50 C 13 46.675 14.173 44.655 16.414 42.414 C 17.111 41.717 19.624 40 23 40 Z\" \n fill=\"${this.getAttribute(\"color\") || \"#007AFF\"}\" stroke=\"white\" stroke-width=\"4\">\n <animate begin=\"freeze\" fill=\"freeze\" attributename=\"d\" dur=\"0.4s\" \n from=\"M 23 40 C 26.376 40 28.889 41.717 29.586 42.414 C 31.827 44.655 33 46.675 33 50 C 33 51.479 32.678 52.894 32.096 54.17 C 31.523 55.427 30.696 56.55 29.676 57.467 C 27.932 59.032 25.618 60 22.999 60 C 20.386 60 18.076 59.036 16.334 57.477 C 15.309 56.558 14.479 55.432 13.904 54.17 C 13.322 52.894 13 51.479 13 50 C 13 46.675 14.173 44.655 16.414 42.414 C 17.111 41.717 19.624 40 23 40 Z\"\n to=\"M 23 2 C 29.018 2 34.385 4.034 38.179 7.421 C 41.794 10.647 44 15.131 44 20.365 C 44 22.74 43.043 26.026 41.334 29.89 C 39.649 33.7 37.33 37.861 34.818 41.916 C 30.621 48.692 25.957 55.057 22.998 58.816 C 20.041 55.06 15.379 48.7 11.182 41.928 C 8.671 37.873 6.351 33.712 4.666 29.901 C 2.958 26.036 2 22.746 2 20.365 C 2 15.119 4.203 10.637 7.812 7.416 C 11.606 4.029 16.976 2 23 2 Z\"/>\n </path>\n </svg>`;\n this.onclick = (evt) => {\n this.querySelector(\"animate\").beginElement();\n }\n }\n});\n\n</script>" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74649985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/903143/" ]
74,650,007
<p>So I've got this program that needs to take in information from a text file and use it to generate data for weather data recording stations. One of the lines looks like this:</p> <pre><code>KE000063612 3.117 35.617 515 1/1/14 -1 87 98 73 </code></pre> <p>the lines repeat for like 8700 lines with the same spacing, etc. how would I go about getting specific pieces of data? Like if I wanted to get the last three ints (in this case 87 98 and 73) for like four stations, or just the month of three different ones. I'm in java btw</p> <p>I've tried using just the Column/line numbers but that's so inefficient that I really don't want to do that unless I absolutely have to.</p>
[ { "answer_id": 74650599, "author": "m3ow", "author_id": 20474278, "author_profile": "https://Stackoverflow.com/users/20474278", "pm_score": 1, "selected": false, "text": "Scanner scanner = new Scanner(System.in);\nString[] input = scanner.nextLine().split(\" \");\n\nSystem.out.println(input[6] + \" \" + input[7] + \" \" + input[8]);\nSystem.out.print(\"sum: \");\nSystem.out.println(Integer.parseInt(input[6]) + Integer.parseInt(input[7]) + Integer.parseInt(input[8]));\n KE000063612 3.117 35.617 515 1/1/14 -1 87 98 73\n 87 98 73\nsum: 258\n" }, { "answer_id": 74650797, "author": "WJS", "author_id": 1552534, "author_profile": "https://Stackoverflow.com/users/1552534", "pm_score": 0, "selected": false, "text": "String s = \"KE000063612 3.117 35.617 515 1/1/14 -1 87 98 73\";\n\n// for the last three values\nint[] results = getValues(s, \"\\\\d+\\\\s+\\\\d+\\\\s+\\\\d+$\", \"\\\\s+\");\nSystem.out.println(Arrays.toString(results));\n\n// for the month, day, and year of date\nresults = getValues(s, \"\\\\d+/\\\\d+/\\\\d+\", \"\\\\/\");\nSystem.out.println(Arrays.toString(results));\n [87, 98, 73]\n[1, 1, 14]\n public static int[] getValues(String line, String pattern,\n String splitPat) {\n return Pattern.compile(pattern).matcher(line).results()\n .flatMap(mr -> Arrays.stream(mr.group().split(splitPat)))\n .mapToInt(Integer::parseInt).toArray();\n}\n List<int[]> List<int[]> list = new ArrayList<>();\n\n// compile the pattern a single time.\nPattern pat = Pattern.compile(endPattern);\n\ntry (Stream<String> stream = Files.lines(Path.of(\"MyData.txt\"))) {\n list = stream.flatMap(line -> pat.matcher(line).results())\n .map((mr -> Arrays.stream(mr.group().split(splitPattern))\n .mapToInt(Integer::parseInt).toArray()))\n .toList();\n\n} catch (IOException ioe) {\n ioe.printStackTrace();\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74650007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20296823/" ]
74,650,043
<p>I want two <a href="/questions/tagged/plotly" class="post-tag" title="show questions tagged &#39;plotly&#39;" aria-label="show questions tagged &#39;plotly&#39;" rel="tag" aria-labelledby="plotly-container">plotly</a> figures to appear side by side using <a href="/questions/tagged/r-markdown" class="post-tag" title="show questions tagged &#39;r-markdown&#39;" aria-label="show questions tagged &#39;r-markdown&#39;" rel="tag" aria-labelledby="r-markdown-container">r-markdown</a>.</p> <pre><code>```{r} library(plotly) ``` ```{r, figures-side, fig.show=&quot;hold&quot;, out.width=&quot;50%&quot;} plot_ly(x = iris$Species, y = iris$Sepal.Length, type = &quot;bar&quot;) plot_ly(x = iris$Species, y = iris$Petal.Length, type = &quot;bar&quot;) ``` </code></pre> <p>When I knit this, the figures appear on different lines. How can I make them side by side?</p>
[ { "answer_id": 74650599, "author": "m3ow", "author_id": 20474278, "author_profile": "https://Stackoverflow.com/users/20474278", "pm_score": 1, "selected": false, "text": "Scanner scanner = new Scanner(System.in);\nString[] input = scanner.nextLine().split(\" \");\n\nSystem.out.println(input[6] + \" \" + input[7] + \" \" + input[8]);\nSystem.out.print(\"sum: \");\nSystem.out.println(Integer.parseInt(input[6]) + Integer.parseInt(input[7]) + Integer.parseInt(input[8]));\n KE000063612 3.117 35.617 515 1/1/14 -1 87 98 73\n 87 98 73\nsum: 258\n" }, { "answer_id": 74650797, "author": "WJS", "author_id": 1552534, "author_profile": "https://Stackoverflow.com/users/1552534", "pm_score": 0, "selected": false, "text": "String s = \"KE000063612 3.117 35.617 515 1/1/14 -1 87 98 73\";\n\n// for the last three values\nint[] results = getValues(s, \"\\\\d+\\\\s+\\\\d+\\\\s+\\\\d+$\", \"\\\\s+\");\nSystem.out.println(Arrays.toString(results));\n\n// for the month, day, and year of date\nresults = getValues(s, \"\\\\d+/\\\\d+/\\\\d+\", \"\\\\/\");\nSystem.out.println(Arrays.toString(results));\n [87, 98, 73]\n[1, 1, 14]\n public static int[] getValues(String line, String pattern,\n String splitPat) {\n return Pattern.compile(pattern).matcher(line).results()\n .flatMap(mr -> Arrays.stream(mr.group().split(splitPat)))\n .mapToInt(Integer::parseInt).toArray();\n}\n List<int[]> List<int[]> list = new ArrayList<>();\n\n// compile the pattern a single time.\nPattern pat = Pattern.compile(endPattern);\n\ntry (Stream<String> stream = Files.lines(Path.of(\"MyData.txt\"))) {\n list = stream.flatMap(line -> pat.matcher(line).results())\n .map((mr -> Arrays.stream(mr.group().split(splitPattern))\n .mapToInt(Integer::parseInt).toArray()))\n .toList();\n\n} catch (IOException ioe) {\n ioe.printStackTrace();\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74650043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11103547/" ]
74,650,062
<p>iam new to flutter and i would like to add a text under a button, but i cant seems to do it, so far here's my result</p> <p>..</p> <p><a href="https://i.stack.imgur.com/vt9mm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vt9mm.png" alt="enter image description here" /></a></p> <p>i use two Rows for the button and the text, as you guys can see the text isnt align really well, i tried using ElevatedButton but the text is beside the button not below it. this is my code so far:</p> <pre><code>import 'package:flutter/material.dart'; import 'package:get/get_navigation/get_navigation.dart'; import 'package:medreminder/NewsArticle/news_home.dart'; import 'Reminder/ui/home_reminder.dart'; import 'Reminder/ui/widgets/button.dart'; import 'package:medreminder/main_reminder.dart'; import 'package:medreminder/home_page.dart'; void main() { // debugPaintSizeEnabled = true; runApp(const HomePage()); } class HomePage extends StatelessWidget { const HomePage({super.key}); @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, home: Scaffold( appBar: AppBar( title: const Text('Medicine Reminder App'), ), body: Column( children: [ Stack( children: [ Image.asset( 'images/MenuImg.jpg', width: 600, height: 170, fit: BoxFit.cover, ), ], ), const SizedBox(height: 10.0), Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ IconButton( icon: Image.asset('images/reminder.png'), iconSize: 50, onPressed: () { Navigator.of(context, rootNavigator: true).push( MaterialPageRoute(builder: (context) =&gt; const ReminderHomePage()), ); }, ), IconButton( icon: Image.asset('images/news.png'), iconSize: 50, onPressed: () {}, ), IconButton( icon: Image.asset('images/recipe.png'), iconSize: 50, onPressed: () {}, ), ], ), Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ Text(&quot;Reminder&quot;), Text(&quot;News&quot;), Text(&quot;Recipe&quot;) ], ) ], ), ), ); } } </code></pre> <p>if anyone know how to do it, please help. it will mean so much to me. thank you</p>
[ { "answer_id": 74650599, "author": "m3ow", "author_id": 20474278, "author_profile": "https://Stackoverflow.com/users/20474278", "pm_score": 1, "selected": false, "text": "Scanner scanner = new Scanner(System.in);\nString[] input = scanner.nextLine().split(\" \");\n\nSystem.out.println(input[6] + \" \" + input[7] + \" \" + input[8]);\nSystem.out.print(\"sum: \");\nSystem.out.println(Integer.parseInt(input[6]) + Integer.parseInt(input[7]) + Integer.parseInt(input[8]));\n KE000063612 3.117 35.617 515 1/1/14 -1 87 98 73\n 87 98 73\nsum: 258\n" }, { "answer_id": 74650797, "author": "WJS", "author_id": 1552534, "author_profile": "https://Stackoverflow.com/users/1552534", "pm_score": 0, "selected": false, "text": "String s = \"KE000063612 3.117 35.617 515 1/1/14 -1 87 98 73\";\n\n// for the last three values\nint[] results = getValues(s, \"\\\\d+\\\\s+\\\\d+\\\\s+\\\\d+$\", \"\\\\s+\");\nSystem.out.println(Arrays.toString(results));\n\n// for the month, day, and year of date\nresults = getValues(s, \"\\\\d+/\\\\d+/\\\\d+\", \"\\\\/\");\nSystem.out.println(Arrays.toString(results));\n [87, 98, 73]\n[1, 1, 14]\n public static int[] getValues(String line, String pattern,\n String splitPat) {\n return Pattern.compile(pattern).matcher(line).results()\n .flatMap(mr -> Arrays.stream(mr.group().split(splitPat)))\n .mapToInt(Integer::parseInt).toArray();\n}\n List<int[]> List<int[]> list = new ArrayList<>();\n\n// compile the pattern a single time.\nPattern pat = Pattern.compile(endPattern);\n\ntry (Stream<String> stream = Files.lines(Path.of(\"MyData.txt\"))) {\n list = stream.flatMap(line -> pat.matcher(line).results())\n .map((mr -> Arrays.stream(mr.group().split(splitPattern))\n .mapToInt(Integer::parseInt).toArray()))\n .toList();\n\n} catch (IOException ioe) {\n ioe.printStackTrace();\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74650062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20229067/" ]
74,650,064
<p>I have a list of dictionary as below.</p> <pre><code>[ {'name':['mallesh'],'email':['m@gmail.com']}, {'name':['bhavik'],'ssn':['1000011']}, {'name':['jagarini'],'email':['m@gmail.com'],'phone':['111111']}, {'name':['mallesh'],'email':['m@gmail.com'],'phone':['1234556'],'ssn':['10000012']} ] </code></pre> <p>I would like to extract the information from these dictionary based on keys, hold on its information in another dictionary as.</p> <pre><code>xml_master_dict={'name':[],'email':[],'phone':[],'ssn':[]} </code></pre> <p>Here xml_master_dict should be filled in with the respective key information as below.</p> <p>In a fist dictionary we have this:</p> <pre><code>{'name':['mallesh'],'email':['m@gmail.com']} </code></pre> <p><strong>In xml_master_dict</strong> name and email keys only will be updated with the current value, if any of key is not existed in the dictionary it should be filled in with None. in this case phone and ssn will be None</p> <p>Here is an expected output:</p> <pre><code>{ 'name':['mallesh','bhavik','jagarini','mallesh'], 'email':['m@gmail.com',None,'m@gmail.com','m@gmail.com'], 'phone':[None,None,'111111','1234556'], 'ssn':[None,'1000011',None,'10000012'], } </code></pre> <pre><code>pd.DataFrame({ 'name':['mallesh','bhavik','jagarini','mallesh'], 'email':['m@gmail.com',None,'m@gmail.com','m@gmail.com'], 'phone':[None,None,'111111','1234556'], 'ssn':[None,'1000011',None,'10000012'], }) </code></pre> <p><a href="https://i.stack.imgur.com/3e3vq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3e3vq.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74650283, "author": "Fran Casadome", "author_id": 1344280, "author_profile": "https://Stackoverflow.com/users/1344280", "pm_score": 2, "selected": false, "text": "update data = [\n {'name': ['mallesh'], 'email': ['m@gmail.com']},\n {'name': ['bhavik'], 'ssn': ['1000011']},\n {'name': ['jagarini'], 'email': ['m@gmail.com'], 'phone': ['111111']},\n {'name': ['mallesh'], 'email': ['m@gmail.com'], 'phone': ['1234556'], 'ssn': ['10000012']}\n]\n\n# create the xml_master_dict with empty lists for each key\nxml_master_dict = {'name':[], 'email':[], 'phone':[], 'ssn':[]}\n\n# loop through the list of dictionaries\nfor item in data:\n # loop through the keys in xml_master_dict\n for key in xml_master_dict.keys():\n # if the key exists in the current dictionary, append its value to the xml_master_dict\n if key in item:\n xml_master_dict[key].append(item[key])\n # if the key does not exist in the current dictionary, append None to the xml_master_dict\n else:\n xml_master_dict[key].append(None)\n\n# print the xml_master_dict to see the resulting values\nprint(xml_master_dict)\n {'name': [['mallesh'], ['bhavik'], ['jagarini'], ['mallesh']], \n'email': [['m@gmail.com'], None, ['m@gmail.com'], ['m@gmail.com']], \n'phone': [None, None, ['111111'], ['1234556']], \n'ssn': [None, ['1000011'], None, ['10000012']]}\n pd.DataFrame import pandas as pd\n\n# Create a DataFrame from the xml_master_dict\ndf = pd.DataFrame(xml_master_dict)\n\n# Print the DataFrame\nprint(df)\n name email phone ssn\n0 [mallesh] [m@gmail.com] None None\n1 [bhavik] None None [1000011]\n2 [jagarini] [m@gmail.com] [111111] None\n3 [mallesh] [m@gmail.com] [1234556] [10000012]\n" }, { "answer_id": 74654904, "author": "mportes", "author_id": 8795073, "author_profile": "https://Stackoverflow.com/users/8795073", "pm_score": 2, "selected": true, "text": "None def first_elem_of_value(record: dict, key: str):\n try:\n return record[key][0]\n except KeyError:\n return None\n xml_master_dict = {\n key: [\n first_elem_of_value(record, key)\n for record in data\n ]\n for key in ('name', 'email', 'phone', 'ssn')\n}\n >>> xml_master_dict\n{'name': ['mallesh', 'bhavik', 'jagarini', 'mallesh'], 'email': ['m@gmail.com', None, 'm@gmail.com', 'm@gmail.com'], 'phone': [None, None, '111111', '1234556'], 'ssn': [None, '1000011', None, '10000012']}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74650064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9479925/" ]
74,650,090
<p>I'm trying to setup the dev environment for an existing project on another computer under WSL2 and Windows 10. Having installed the project from its own repo with <code>composer install</code> and making sure a basic .env file is in place, I ran <code>/vendor/bin/sail up</code> to do the initial build.</p> <p>Docker starts normally, but then during stage 4 of 11 <code>RUN apt-get update &amp;&amp; apt-get install....</code>, it just halts when it gets to the line <code>gpg: keybox '/root/.gnupg/pubring.kbx' created</code> the build halts, the clock is still ticking but the operation never finishes.</p> <p>I'm able to hit Ctrl + C and it Cancels cleanly.</p> <p>Editing Laravel's dockerfile, I added a -v to the <code>gpg --recv-key ...</code> line in the script and got additional output with the operation halting after <code>gpg: connection to dirmngr established</code> instead.</p> <p>I'm running Ubuntu under WSL2, fully updated, docker freshly installed and configured to talk to it as on my other machine where I'm not having any issues.</p>
[ { "answer_id": 74650283, "author": "Fran Casadome", "author_id": 1344280, "author_profile": "https://Stackoverflow.com/users/1344280", "pm_score": 2, "selected": false, "text": "update data = [\n {'name': ['mallesh'], 'email': ['m@gmail.com']},\n {'name': ['bhavik'], 'ssn': ['1000011']},\n {'name': ['jagarini'], 'email': ['m@gmail.com'], 'phone': ['111111']},\n {'name': ['mallesh'], 'email': ['m@gmail.com'], 'phone': ['1234556'], 'ssn': ['10000012']}\n]\n\n# create the xml_master_dict with empty lists for each key\nxml_master_dict = {'name':[], 'email':[], 'phone':[], 'ssn':[]}\n\n# loop through the list of dictionaries\nfor item in data:\n # loop through the keys in xml_master_dict\n for key in xml_master_dict.keys():\n # if the key exists in the current dictionary, append its value to the xml_master_dict\n if key in item:\n xml_master_dict[key].append(item[key])\n # if the key does not exist in the current dictionary, append None to the xml_master_dict\n else:\n xml_master_dict[key].append(None)\n\n# print the xml_master_dict to see the resulting values\nprint(xml_master_dict)\n {'name': [['mallesh'], ['bhavik'], ['jagarini'], ['mallesh']], \n'email': [['m@gmail.com'], None, ['m@gmail.com'], ['m@gmail.com']], \n'phone': [None, None, ['111111'], ['1234556']], \n'ssn': [None, ['1000011'], None, ['10000012']]}\n pd.DataFrame import pandas as pd\n\n# Create a DataFrame from the xml_master_dict\ndf = pd.DataFrame(xml_master_dict)\n\n# Print the DataFrame\nprint(df)\n name email phone ssn\n0 [mallesh] [m@gmail.com] None None\n1 [bhavik] None None [1000011]\n2 [jagarini] [m@gmail.com] [111111] None\n3 [mallesh] [m@gmail.com] [1234556] [10000012]\n" }, { "answer_id": 74654904, "author": "mportes", "author_id": 8795073, "author_profile": "https://Stackoverflow.com/users/8795073", "pm_score": 2, "selected": true, "text": "None def first_elem_of_value(record: dict, key: str):\n try:\n return record[key][0]\n except KeyError:\n return None\n xml_master_dict = {\n key: [\n first_elem_of_value(record, key)\n for record in data\n ]\n for key in ('name', 'email', 'phone', 'ssn')\n}\n >>> xml_master_dict\n{'name': ['mallesh', 'bhavik', 'jagarini', 'mallesh'], 'email': ['m@gmail.com', None, 'm@gmail.com', 'm@gmail.com'], 'phone': [None, None, '111111', '1234556'], 'ssn': [None, '1000011', None, '10000012']}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74650090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/483/" ]
74,650,147
<p>Is there a command that can initialize npm's package-lock.json and update all the libraries?<br /> With yarn, I can use the following command to update the library in one go, but is there a way to do the same with npm?</p> <pre><code>$ rm -rf node_modules yarn.lock $ npx npm-check-updates -u </code></pre>
[ { "answer_id": 74650283, "author": "Fran Casadome", "author_id": 1344280, "author_profile": "https://Stackoverflow.com/users/1344280", "pm_score": 2, "selected": false, "text": "update data = [\n {'name': ['mallesh'], 'email': ['m@gmail.com']},\n {'name': ['bhavik'], 'ssn': ['1000011']},\n {'name': ['jagarini'], 'email': ['m@gmail.com'], 'phone': ['111111']},\n {'name': ['mallesh'], 'email': ['m@gmail.com'], 'phone': ['1234556'], 'ssn': ['10000012']}\n]\n\n# create the xml_master_dict with empty lists for each key\nxml_master_dict = {'name':[], 'email':[], 'phone':[], 'ssn':[]}\n\n# loop through the list of dictionaries\nfor item in data:\n # loop through the keys in xml_master_dict\n for key in xml_master_dict.keys():\n # if the key exists in the current dictionary, append its value to the xml_master_dict\n if key in item:\n xml_master_dict[key].append(item[key])\n # if the key does not exist in the current dictionary, append None to the xml_master_dict\n else:\n xml_master_dict[key].append(None)\n\n# print the xml_master_dict to see the resulting values\nprint(xml_master_dict)\n {'name': [['mallesh'], ['bhavik'], ['jagarini'], ['mallesh']], \n'email': [['m@gmail.com'], None, ['m@gmail.com'], ['m@gmail.com']], \n'phone': [None, None, ['111111'], ['1234556']], \n'ssn': [None, ['1000011'], None, ['10000012']]}\n pd.DataFrame import pandas as pd\n\n# Create a DataFrame from the xml_master_dict\ndf = pd.DataFrame(xml_master_dict)\n\n# Print the DataFrame\nprint(df)\n name email phone ssn\n0 [mallesh] [m@gmail.com] None None\n1 [bhavik] None None [1000011]\n2 [jagarini] [m@gmail.com] [111111] None\n3 [mallesh] [m@gmail.com] [1234556] [10000012]\n" }, { "answer_id": 74654904, "author": "mportes", "author_id": 8795073, "author_profile": "https://Stackoverflow.com/users/8795073", "pm_score": 2, "selected": true, "text": "None def first_elem_of_value(record: dict, key: str):\n try:\n return record[key][0]\n except KeyError:\n return None\n xml_master_dict = {\n key: [\n first_elem_of_value(record, key)\n for record in data\n ]\n for key in ('name', 'email', 'phone', 'ssn')\n}\n >>> xml_master_dict\n{'name': ['mallesh', 'bhavik', 'jagarini', 'mallesh'], 'email': ['m@gmail.com', None, 'm@gmail.com', 'm@gmail.com'], 'phone': [None, None, '111111', '1234556'], 'ssn': [None, '1000011', None, '10000012']}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74650147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10922854/" ]
74,650,152
<p>I have the following telegram export JSON dataset:</p> <pre><code>import pandas as pd df = pd.read_json(&quot;data/result.json&quot;) &gt;&gt;&gt;df.colums Index(['name', 'type', 'id', 'messages'], dtype='object') &gt;&gt;&gt; type(df) &lt;class 'pandas.core.frame.DataFrame'&gt; # Sample output sample_df = pd.DataFrame({&quot;messages&quot;: [ {&quot;id&quot;: 11, &quot;from&quot;: &quot;user3984&quot;, &quot;text&quot;: &quot;Do you like soccer?&quot;}, {&quot;id&quot;: 312, &quot;from&quot;: &quot;user837&quot;, &quot;text&quot;: ['Not sure', {'type': 'hashtag', 'text': '#confused'}]}, {&quot;id&quot;: 4324, &quot;from&quot;: &quot;user3984&quot;, &quot;text&quot;: ['O ', {'type': 'mention', 'text': '@user87324'}, ' really?']} ]}) </code></pre> <p>Within <code>df</code>, there's a <em>&quot;messages&quot;</em> column, which has the following output:</p> <pre><code>&gt;&gt;&gt; df[&quot;messages&quot;] 0 {'id': -999713937, 'type': 'service', 'date': ... 1 {'id': -999713936, 'type': 'service', 'date': ... 2 {'id': -999713935, 'type': 'message', 'date': ... 3 {'id': -999713934, 'type': 'message', 'date': ... 4 {'id': -999713933, 'type': 'message', 'date': ... ... 22377 {'id': 22102, 'type': 'message', 'date': '2022... 22378 {'id': 22103, 'type': 'message', 'date': '2022... 22379 {'id': 22104, 'type': 'message', 'date': '2022... 22380 {'id': 22105, 'type': 'message', 'date': '2022... 22381 {'id': 22106, 'type': 'message', 'date': '2022... Name: messages, Length: 22382, dtype: object </code></pre> <p>Within messages, there's a particular key named <em>&quot;text&quot;</em>, and that's the place I want to focus. Turns out when you explore the data, text column can have:</p> <p>A single text:</p> <pre><code>&gt;&gt;&gt; df[&quot;messages&quot;][5][&quot;text&quot;] 'JAJAJAJAJAJAJA' &gt;&gt;&gt; df[&quot;messages&quot;][22262][&quot;text&quot;] 'No creo' </code></pre> <p>But sometimes it's <strong>nested</strong>. Like the following:</p> <pre><code>&gt;&gt;&gt; df[&quot;messages&quot;][22373][&quot;text&quot;] ['O ', {'type': 'mention', 'text': '@user87324'}, ' really?'] &gt;&gt;&gt; df[&quot;messages&quot;][22189][&quot;text&quot;] ['The average married couple has sex roughly once a week. ', {'type': 'mention', 'text': '@googlefactss'}, ' ', {'type': 'hashtag', 'text': '#funfact'}] &gt;&gt;&gt; df[&quot;messages&quot;][22345][&quot;text&quot;] [{'type': 'mention', 'text': '@user817430'}] </code></pre> <p>In case for nested data, if I want to grab the main text, I can do the following:</p> <pre><code>&gt;&gt;&gt; df[&quot;messages&quot;][22373][&quot;text&quot;][0] 'O ' &gt;&gt;&gt; df[&quot;messages&quot;][22189][&quot;text&quot;][0] 'The average married couple has sex roughly once a week. ' &gt;&gt;&gt; </code></pre> <p>From here, everything seems ok. However, the problem arrives when I do the for loop. If I try the following:</p> <pre><code>for item in df[&quot;messages&quot;]: tg_id = item.get(&quot;id&quot;, &quot;None&quot;) tg_type = item.get(&quot;type&quot;, &quot;None&quot;) tg_date = item.get(&quot;date&quot;, &quot;None&quot;) tg_from = item.get(&quot;from&quot;, &quot;None&quot;) tg_text = item.get(&quot;text&quot;, &quot;None&quot;) print(tg_id, tg_from, tg_text) </code></pre> <p>A sample output is:</p> <pre><code>21263 user3984 jajajajaja 21264 user837 ['Not sure', {'type': 'hashtag', 'text': '#confused'}] 21265 user3984 What time is it?✋ </code></pre> <p><strong>MY ASK:</strong> How to flatten the rows? I need the following (and store that in a data frame):</p> <pre><code>21263 user3984 jajajajaja 21264 user837 Not sure 21265 user837 type: hashtag 21266 user837 text: #confused 21267 user3984 What time is it?✋ </code></pre> <p>I tried to detect &quot;text&quot; type like this:</p> <pre><code>for item in df[&quot;messages&quot;]: tg_id = item.get(&quot;id&quot;, &quot;None&quot;) tg_type = item.get(&quot;type&quot;, &quot;None&quot;) tg_date = item.get(&quot;date&quot;, &quot;None&quot;) tg_from = item.get(&quot;from&quot;, &quot;None&quot;) tg_text = item.get(&quot;text&quot;, &quot;None&quot;) if type(tg_text) == list: tg_text = tg_text[0] print(tg_id, tg_from, tg_text) </code></pre> <p>With this I only grab the first text, but I'm expecting to grab the other fields as well or to 'flatten' the data.</p> <p>I also tried:</p> <pre><code>for item in df[&quot;messages&quot;]: tg_id = item.get(&quot;id&quot;, &quot;None&quot;) tg_type = item.get(&quot;type&quot;, &quot;None&quot;) tg_date = item.get(&quot;date&quot;, &quot;None&quot;) tg_from = item.get(&quot;from&quot;, &quot;None&quot;) tg_text = item.get(&quot;text&quot;, &quot;None&quot;) if type(tg_text) == list: tg_text = tg_text[0] tg_second = tg_text[1][&quot;text&quot;] print(tg_id, tg_from, tg_text, tg_second) </code></pre> <p>But no luck because indices are variable, length from messages are variable too.</p> <p>In addition, even if the output weren't close of my desired solution, I also tried:</p> <pre><code>for item in df[&quot;messages&quot;]: tg_text = item.get(&quot;text&quot;, &quot;None&quot;) if type(tg_text) == list: for i in tg_text: print(item, i) </code></pre> <pre><code>mydict = {} for k, v in df.items(): print(k, v) mydict[k] = v </code></pre> <pre><code># Used df[&quot;text&quot;].explode() # Used json_normalize but no luck </code></pre> <p>Any thoughts?</p>
[ { "answer_id": 74650420, "author": "Charles Han", "author_id": 11514907, "author_profile": "https://Stackoverflow.com/users/11514907", "pm_score": 0, "selected": false, "text": "def flatlist(srclist):\n flatlist=[]\n if srclist: #check if srclist is not None\n for item in srclist:\n if(type(item) == str): #check if item is type of string\n flatlist.append(item)\n if(type(item) == dict): #check if item is type of dict\n for x in item:\n flatlist.append(x + ' ' + item[x]) #combine key and value\n return flatlist\n\nfor item in df[\"messages\"]:\n tg_text = item.get(\"text\", \"None\")\n flat_list = flatlist(tg_text) # get the flattened list\n for tg in flat_list: # loop through the list and get the data you want\n tg_id = item.get(\"id\", \"None\")\n tg_from = item.get(\"from\", \"None\")\n \n print(tg_id, tg_from, tg)\n" }, { "answer_id": 74659183, "author": "Stuart", "author_id": 567595, "author_profile": "https://Stackoverflow.com/users/567595", "pm_score": 2, "selected": true, "text": "df = pd.DataFrame({\"messages\": [\n {\"id\": 21263, \"from\": \"user3984\", \"text\": \"jajajajaja\"},\n {\"id\": 21264, \"from\": \"user837\", \"text\": ['Not sure', {'type': 'hashtag', 'text': '#confused'}]}, \n {\"id\": 21265, \"from\": \"user3984\", \"text\": ['O ', {'type': 'mention', 'text': '@user87324'}, ' really?']}\n]})\n messages id from text expanded = pd.concat([df.drop(\"messages\", axis=1), pd.json_normalize(df[\"messages\"])], axis=1)\n text exploded = expanded.explode(\"text\")\n def convert_dict(entry):\n if type(entry) is dict:\n return [f\"{k}: {v}\" for k, v in entry.items()]\n else:\n return entry\n\nexploded[\"text\"] = exploded[\"text\"].apply(convert_dict)\n final = exploded.explode(\"text\")\n id from text\n0 21263 user3984 jajajajaja\n1 21264 user837 Not sure\n1 21264 user837 type: hashtag\n1 21264 user837 text: #confused\n2 21265 user3984 O \n2 21265 user3984 type: mention\n2 21265 user3984 text: @user87324\n2 21265 user3984 really?\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74650152", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15518762/" ]
74,650,154
<p>Good day</p> <p>I moved to another company from a previous one, they task me to modify a existing system with a horrific code, but with patience and dedication, I managed to update the system, but I was shocked that they told me to put the source code on the system and it will be the one that the app in IIS will read. It will read the debug folder of the project. On my previous employer what we do is to publish the file, and that be one to read, but on my current employer,they put the whole source code on the web server.</p> <p>Is this okay? Or am I right it's a bad practice, well other frameworks put the whole file on the server, so it should be good? Is it?</p> <p>Thanks and regards</p>
[ { "answer_id": 74650420, "author": "Charles Han", "author_id": 11514907, "author_profile": "https://Stackoverflow.com/users/11514907", "pm_score": 0, "selected": false, "text": "def flatlist(srclist):\n flatlist=[]\n if srclist: #check if srclist is not None\n for item in srclist:\n if(type(item) == str): #check if item is type of string\n flatlist.append(item)\n if(type(item) == dict): #check if item is type of dict\n for x in item:\n flatlist.append(x + ' ' + item[x]) #combine key and value\n return flatlist\n\nfor item in df[\"messages\"]:\n tg_text = item.get(\"text\", \"None\")\n flat_list = flatlist(tg_text) # get the flattened list\n for tg in flat_list: # loop through the list and get the data you want\n tg_id = item.get(\"id\", \"None\")\n tg_from = item.get(\"from\", \"None\")\n \n print(tg_id, tg_from, tg)\n" }, { "answer_id": 74659183, "author": "Stuart", "author_id": 567595, "author_profile": "https://Stackoverflow.com/users/567595", "pm_score": 2, "selected": true, "text": "df = pd.DataFrame({\"messages\": [\n {\"id\": 21263, \"from\": \"user3984\", \"text\": \"jajajajaja\"},\n {\"id\": 21264, \"from\": \"user837\", \"text\": ['Not sure', {'type': 'hashtag', 'text': '#confused'}]}, \n {\"id\": 21265, \"from\": \"user3984\", \"text\": ['O ', {'type': 'mention', 'text': '@user87324'}, ' really?']}\n]})\n messages id from text expanded = pd.concat([df.drop(\"messages\", axis=1), pd.json_normalize(df[\"messages\"])], axis=1)\n text exploded = expanded.explode(\"text\")\n def convert_dict(entry):\n if type(entry) is dict:\n return [f\"{k}: {v}\" for k, v in entry.items()]\n else:\n return entry\n\nexploded[\"text\"] = exploded[\"text\"].apply(convert_dict)\n final = exploded.explode(\"text\")\n id from text\n0 21263 user3984 jajajajaja\n1 21264 user837 Not sure\n1 21264 user837 type: hashtag\n1 21264 user837 text: #confused\n2 21265 user3984 O \n2 21265 user3984 type: mention\n2 21265 user3984 text: @user87324\n2 21265 user3984 really?\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74650154", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7566234/" ]
74,650,197
<p>I want multiple <a href="/questions/tagged/plotly" class="post-tag" title="show questions tagged &#39;plotly&#39;" aria-label="show questions tagged &#39;plotly&#39;" rel="tag" aria-labelledby="plotly-container">plotly</a> figures to be displayed from an <code>if</code> <code>else</code> statement.</p> <pre><code>if(iris$Sepal.Length &lt; 0){print(&quot;Iris is NA.&quot;) } else{ plot_ly(x = iris$Species, y = iris$Sepal.Length, type = &quot;bar&quot;) plot_ly(x = iris$Species, y = iris$Petal.Length, type = &quot;bar&quot;) } </code></pre> <p>Only the second figure appears.</p> <p>If you do this with non-plotly figures, both are shown.</p> <pre><code>if(iris$Sepal.Length &lt; 0){print(&quot;Iris is NA.&quot;) } else{ plot(iris$Sepal.Length ~ iris$Species ) plot(iris$Petal.Length ~ iris$Species) } </code></pre> <p>Is there any way to make both appear?</p>
[ { "answer_id": 74650420, "author": "Charles Han", "author_id": 11514907, "author_profile": "https://Stackoverflow.com/users/11514907", "pm_score": 0, "selected": false, "text": "def flatlist(srclist):\n flatlist=[]\n if srclist: #check if srclist is not None\n for item in srclist:\n if(type(item) == str): #check if item is type of string\n flatlist.append(item)\n if(type(item) == dict): #check if item is type of dict\n for x in item:\n flatlist.append(x + ' ' + item[x]) #combine key and value\n return flatlist\n\nfor item in df[\"messages\"]:\n tg_text = item.get(\"text\", \"None\")\n flat_list = flatlist(tg_text) # get the flattened list\n for tg in flat_list: # loop through the list and get the data you want\n tg_id = item.get(\"id\", \"None\")\n tg_from = item.get(\"from\", \"None\")\n \n print(tg_id, tg_from, tg)\n" }, { "answer_id": 74659183, "author": "Stuart", "author_id": 567595, "author_profile": "https://Stackoverflow.com/users/567595", "pm_score": 2, "selected": true, "text": "df = pd.DataFrame({\"messages\": [\n {\"id\": 21263, \"from\": \"user3984\", \"text\": \"jajajajaja\"},\n {\"id\": 21264, \"from\": \"user837\", \"text\": ['Not sure', {'type': 'hashtag', 'text': '#confused'}]}, \n {\"id\": 21265, \"from\": \"user3984\", \"text\": ['O ', {'type': 'mention', 'text': '@user87324'}, ' really?']}\n]})\n messages id from text expanded = pd.concat([df.drop(\"messages\", axis=1), pd.json_normalize(df[\"messages\"])], axis=1)\n text exploded = expanded.explode(\"text\")\n def convert_dict(entry):\n if type(entry) is dict:\n return [f\"{k}: {v}\" for k, v in entry.items()]\n else:\n return entry\n\nexploded[\"text\"] = exploded[\"text\"].apply(convert_dict)\n final = exploded.explode(\"text\")\n id from text\n0 21263 user3984 jajajajaja\n1 21264 user837 Not sure\n1 21264 user837 type: hashtag\n1 21264 user837 text: #confused\n2 21265 user3984 O \n2 21265 user3984 type: mention\n2 21265 user3984 text: @user87324\n2 21265 user3984 really?\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74650197", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11103547/" ]
74,650,214
<p>When I'm doing this:</p> <pre><code>def pencil(): print(&quot;pencil&quot;) print(&quot;A&quot;, pencil()) </code></pre> <p>Output showing:</p> <pre class="lang-none prettyprint-override"><code>pencil A None </code></pre> <p>I tried some things but nothing worked.</p>
[ { "answer_id": 74650244, "author": "Leo Ward", "author_id": 20421592, "author_profile": "https://Stackoverflow.com/users/20421592", "pm_score": 2, "selected": true, "text": "def pencil():\n return \"pencil\"\n\n\nprint(\"A\", pencil()) # A pencil\n def pencil():\n print(\"pencil\")\n\n\nprint(\"A\") # A\npencil() # pencil\n" }, { "answer_id": 74650254, "author": "subparry", "author_id": 10533611, "author_profile": "https://Stackoverflow.com/users/10533611", "pm_score": 0, "selected": false, "text": "print(\"A\", pencil())\n pencil return None return \"pencil\"" }, { "answer_id": 74650264, "author": "Wolric", "author_id": 20163209, "author_profile": "https://Stackoverflow.com/users/20163209", "pm_score": 0, "selected": false, "text": "None return None print None sys.stdout print(\"pencil\") None return \"pencil\" def pencil():\n return \"pencil\"\n\nprint(\"A\", pencil())\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74650214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20306417/" ]
74,650,215
<p>I have a very large iterable which means a lot of iterations must pass before the bar updates by 1%. It populates a sqlite database from legacy excel sheets.</p> <p>Minimum reproducible example is something like this.</p> <pre class="lang-py prettyprint-override"><code>from tqdm import tqdm, trange import time percentage = 0 total = 157834 l_bar = '{desc}: {percentage:.3f}%|' r_bar = '| {n_fmt}/{total_fmt} [{elapsed}&lt;{remaining}, ' '{rate_fmt}{postfix}]' format = '{l_bar}{bar}{r_bar}' for row in tqdm(range(2, total), ncols=100, bar_format=format): percentage = row/total * 100 time.sleep(0.1) </code></pre> <p>In this example I have left all these strings as their default values except for trying to modify the percentage field in l_bar in an attempt to get decimals of a percent to print. And I haven't been able to find a default definition of <code>bar</code> anywhere in the docs so this implementation causes the loading bar to stop working.</p> <p>From the <a href="https://github.com/tqdm/tqdm" rel="nofollow noreferrer">documentation</a>:</p> <blockquote> <p>bar_format : str, optional<br /> Specify a custom bar string formatting. May impact performance. [default: '{l_bar}{bar}{r_bar}'], where l_bar='{desc}: {percentage:3.0f}%|' and r_bar='| {n_fmt}/{total_fmt} [{elapsed}&lt;{remaining}, ' '{rate_fmt}{postfix}]' Possible vars: l_bar, bar, r_bar, n, n_fmt, total, total_fmt, percentage, elapsed, elapsed_s, ncols, nrows, desc, unit, rate, rate_fmt, rate_noinv, rate_noinv_fmt, rate_inv, rate_inv_fmt, postfix, unit_divisor, remaining, remaining_s, eta. Note that a trailing &quot;: &quot; is automatically removed after {desc} if the latter is empty.</p> </blockquote> <p>However I try it seems to come out as a flat 0% and then a jump to 1% every time.</p> <p>How am I misunderstanding the documentation here?</p>
[ { "answer_id": 74650711, "author": "Sin Han Jinn", "author_id": 12128167, "author_profile": "https://Stackoverflow.com/users/12128167", "pm_score": 0, "selected": false, "text": "from tqdm import tqdm, trange\nimport time\n\ntotal = 1000\n\nclass TqdmExtraFormat(tqdm):\n @property\n def format_dict(self):\n d = super(TqdmExtraFormat, self).format_dict\n decimalpercentage = '{:.2f}'.format(d[\"rate\"]/100) if d[\"rate\"] else '?'\n d.update(percentage = decimalpercentage)\n return d\n\nb= '{percentage}%|{bar}{r_bar}'\nfor i in TqdmExtraFormat(range(2, total), bar_format=b):\n time.sleep(0.1)\n" }, { "answer_id": 74653481, "author": "user2357112", "author_id": 2357112, "author_profile": "https://Stackoverflow.com/users/2357112", "pm_score": 2, "selected": true, "text": "bar_format l_bar r_bar for row in tqdm(whatever, bar_format='{desc}: {percentage:3.2f}%|{bar}{r_bar}'):\n ...\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74650215", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8981253/" ]
74,650,216
<p>I have a parent functional component named Dashboard and a child class component named DashboardTable. I'm making a graphql call in the parent class and want to pass the result into the child like this <code>&lt;DashboardTable data={opportunityData}/&gt;.</code></p> <p>problem: I can get see the data in the parent but its not showing in the child</p> <p>Here is my code. Please let me know what I'm doing wrong</p> <p><strong>Dashboard</strong></p> <pre><code>import React, { useEffect, useState } from &quot;react&quot;; import &quot;bootstrap/js/src/collapse.js&quot;; import DashboardTable from &quot;../DashboardTable&quot;; import { API } from &quot;@aws-amplify/api&quot;; import config from &quot;../../aws-exports&quot;; import * as queries from &quot;../../graphql/queries&quot;; export default function Dashboard() { API.configure(config); async function asyncCall() { const gqlreturn = await API.graphql({ query: queries.listMockOppsTables, }); //console.log(gqlreturn.data.listMockOppsTables); // result: { &quot;data&quot;: { &quot;listTodos&quot;: { &quot;items&quot;: [/* ..... */] } } } return gqlreturn; } const [opportunityTable, changeOpportunityTable] = useState(asyncCall()); console.log(opportunityTable); // this works! returns a promise return ( &lt;div&gt; &lt;section className=&quot;py-5 mt-5&quot;&gt; &lt;div className=&quot;container py-5&quot;&gt; &lt;h2 className=&quot;fw-bold text-center&quot;&gt; Your upcoming shadowing events &lt;br /&gt; &lt;br /&gt; &lt;/h2&gt; &lt;DashboardTable data={opportunityTable}&gt;&lt;/DashboardTable&gt; &lt;/div&gt; &lt;/section&gt; &lt;/div&gt; ); } </code></pre> <p><strong>DashboardTable</strong></p> <pre><code>import React from &quot;react&quot;; import &quot;bootstrap/js/src/collapse.js&quot;; import Navigation from &quot;../Navigation&quot;; import { Link } from &quot;react-router-dom&quot;; import { API } from &quot;@aws-amplify/api&quot;; import config from &quot;../../aws-exports&quot;; import * as queries from &quot;../../graphql/queries&quot;; export class DashboardTable extends React.Component { constructor() { super(); this.state = { opportunityData: this.props, }; } render() { console.log(this.opportunityData); // this doesnt work :( no data return ( &lt;div&gt; &lt;div className=&quot;row row-cols-1 row-cols-md-2 mx-auto&quot; style={{ maxWidth: 900 }} &gt; {this.opportunityData.map((opportunity) =&gt; ( &lt;div className=&quot;col mb-4&quot;&gt; &lt;div&gt; &lt;a href=&quot;#&quot;&gt; &lt;img className=&quot;rounded img-fluid shadow w-100 fit-cover&quot; src=&quot;assets/img/products/awsLogo.jpg&quot; style={{ height: 250, }} /&gt; &lt;/a&gt; &lt;div className=&quot;py-4&quot;&gt; &lt;span className=&quot;badge mb-2&quot; style={{ margin: 2, backgroundColor: &quot;#ff9900&quot; }} &gt; {opportunity.interview_type} &lt;/span&gt; &lt;span className=&quot;badge bg mb-2&quot; style={{ margin: 2, backgroundColor: &quot;#ff9900&quot; }} &gt; {opportunity.level} &lt;/span&gt; &lt;span className=&quot;badge bg mb-2&quot; style={{ margin: 2, backgroundColor: &quot;#ff9900&quot; }} &gt; {opportunity.ShadowReverse} &lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; ))} &lt;/div&gt; &lt;/div&gt; ); } } export default DashboardTable; </code></pre>
[ { "answer_id": 74650711, "author": "Sin Han Jinn", "author_id": 12128167, "author_profile": "https://Stackoverflow.com/users/12128167", "pm_score": 0, "selected": false, "text": "from tqdm import tqdm, trange\nimport time\n\ntotal = 1000\n\nclass TqdmExtraFormat(tqdm):\n @property\n def format_dict(self):\n d = super(TqdmExtraFormat, self).format_dict\n decimalpercentage = '{:.2f}'.format(d[\"rate\"]/100) if d[\"rate\"] else '?'\n d.update(percentage = decimalpercentage)\n return d\n\nb= '{percentage}%|{bar}{r_bar}'\nfor i in TqdmExtraFormat(range(2, total), bar_format=b):\n time.sleep(0.1)\n" }, { "answer_id": 74653481, "author": "user2357112", "author_id": 2357112, "author_profile": "https://Stackoverflow.com/users/2357112", "pm_score": 2, "selected": true, "text": "bar_format l_bar r_bar for row in tqdm(whatever, bar_format='{desc}: {percentage:3.2f}%|{bar}{r_bar}'):\n ...\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74650216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10959395/" ]
74,650,266
<p>I have a <code>try .. catch</code> block when loggin in or signing up with <code>FirebaseAuth.instance</code></p> <p>This is the code that I have.</p> <pre><code> try { //... code here } on PlatformException catch (err) { var message = 'An error occured, please check your credentials.'; if (err.message != null) { message = err.message!; } ScaffoldMessenger.of(ctx).showSnackBar( SnackBar( content: Text(message), backgroundColor: Theme.of(ctx).errorColor, ), ); // other codes here } catch (err) { print(err); } </code></pre> <p>The problem now is that if I'm encountering an error like <code>The email address is badly formatted. </code> or <code>he email address is already in use by another account</code>, this is not going inside the <code>on PlatformException catch (err) </code> block and its goin in the <code>catch</code> block instead.</p> <p>How can I make sure that the types of errors I mentioned above should be executed in the <code>on PlatformException</code> block?</p>
[ { "answer_id": 74650365, "author": "ramedju", "author_id": 20283624, "author_profile": "https://Stackoverflow.com/users/20283624", "pm_score": 0, "selected": false, "text": "on FirebaseAuthException on PlatformException" }, { "answer_id": 74650581, "author": "Nehil Koshiya", "author_id": 12036450, "author_profile": "https://Stackoverflow.com/users/12036450", "pm_score": 1, "selected": false, "text": " try {\n //... code here\n } on FirebaseAuthException catch (e) {\n String errorMessage = AuthExceptionHandler.handleException(e);\n errorSnackBar(content: errorMessage);\n } catch (e) {\n print(e.toString());\n }\n class AuthExceptionHandler {\n static handleException(e) {\n AuthResultStatus status;\n switch (e.code) {\n case \"invalid-email\":\n status = AuthResultStatus.invalidEmail;\n break;\n case \"wrong-password\":\n status = AuthResultStatus.wrongPassword;\n break;\n case \"user-not-found\":\n status = AuthResultStatus.userNotFound;\n break;\n case \"user-disabled\":\n status = AuthResultStatus.userDisabled;\n break;\n case \"too-many-requests\":\n status = AuthResultStatus.tooManyRequests;\n break;\n case \"operation-not-allowed\":\n status = AuthResultStatus.operationNotAllowed;\n break;\n case \"email-already-in-use\":\n status = AuthResultStatus.emailAlreadyExists;\n break;\n default:\n status = AuthResultStatus.undefined;\n }\n return generateExceptionMessage(status);\n }\n\n ///\n /// Accepts AuthExceptionHandler.errorType and set message according error\n static generateExceptionMessage(exceptionCode) {\n String errorMessage;\n switch (exceptionCode) {\n case AuthResultStatus.invalidEmail:\n errorMessage = StringConstants.emailAddressMalformed.tr;\n break;\n case AuthResultStatus.wrongPassword:\n errorMessage = StringConstants.wrongPassword.tr;\n break;\n case AuthResultStatus.userNotFound:\n errorMessage = StringConstants.userNotExist.tr;\n break;\n case AuthResultStatus.userDisabled:\n errorMessage = StringConstants.userDisable.tr;\n break;\n case AuthResultStatus.tooManyRequests:\n errorMessage = StringConstants.manyRequestTryAfterSomeTime.tr;\n break;\n case AuthResultStatus.operationNotAllowed:\n errorMessage = StringConstants.signInNotEnable.tr;\n break;\n case AuthResultStatus.emailAlreadyExists:\n errorMessage = StringConstants.emailAlreadyExist.tr;\n break;\n default:\n errorMessage = StringConstants.undefinedErrorHappened.tr;\n }\n\n return errorMessage;\n }\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74650266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20283624/" ]
74,650,361
<p>Vue component hasn't <code>onShow</code> lifecycle method.</p> <p>How to call a component method each time this component show in vue2?</p>
[ { "answer_id": 74655182, "author": "Rohìt Jíndal", "author_id": 4116300, "author_profile": "https://Stackoverflow.com/users/4116300", "pm_score": 0, "selected": false, "text": "v-if v-show v-if Vue.component('child', {\n props: ['childmsg'],\n template: '<p>{{ childmsg }}</p>',\n mounted() {\n console.log('child component mounted');\n }\n});\n\nvar app = new Vue({\n el: '#app',\n data: {\n buttonMsg: 'Show Child Component',\n showChild: false\n },\n methods: {\n toggleBtn() {\n this.showChild = !this.showChild;\n this.buttonMsg = this.showChild ? 'Hide Child Component' : 'Show Child Component';\n }\n }\n}); <script src=\"https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js\"></script>\n<div id=\"app\">\n <button @click=\"toggleBtn\">{{ buttonMsg }}</button>\n <child v-if=\"showChild\" childmsg=\"This is a child message\"/>\n</div>" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74650361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1516794/" ]
74,650,396
<p>In my React/Redux project I tend to use constants in switch case within <strong>reducer</strong>, since the name of each action tends to be long and complex, I'm wondering if it's a good practice?</p> <pre class="lang-js prettyprint-override"><code>const ACTION_LIST = { add: 'ACTION_TYPE/ADD_CUSTOMER', remove: 'ACTION_TYPE/REMOVE_CUSTOMER', update: 'ACTION_TYPE/UPDATE_CUSTOMER', }; const reducer = produce((draft, action: IQuickBarActions) =&gt; { const {type, payload} = action switch (type) { case ACTION_LIST.add: { // here // process the state break; } case ACTION_LIST.remove: { // process the state break; } case ACTION_LIST.update: { // process the state break; } default: // do something } }; </code></pre>
[ { "answer_id": 74655182, "author": "Rohìt Jíndal", "author_id": 4116300, "author_profile": "https://Stackoverflow.com/users/4116300", "pm_score": 0, "selected": false, "text": "v-if v-show v-if Vue.component('child', {\n props: ['childmsg'],\n template: '<p>{{ childmsg }}</p>',\n mounted() {\n console.log('child component mounted');\n }\n});\n\nvar app = new Vue({\n el: '#app',\n data: {\n buttonMsg: 'Show Child Component',\n showChild: false\n },\n methods: {\n toggleBtn() {\n this.showChild = !this.showChild;\n this.buttonMsg = this.showChild ? 'Hide Child Component' : 'Show Child Component';\n }\n }\n}); <script src=\"https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js\"></script>\n<div id=\"app\">\n <button @click=\"toggleBtn\">{{ buttonMsg }}</button>\n <child v-if=\"showChild\" childmsg=\"This is a child message\"/>\n</div>" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74650396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5721873/" ]
74,650,404
<p>I'm working on a fun side project and would like to compute a moving sum for number of wins for NBA teams over 2 year periods. Consider the sample pandas dataframe below,</p> <pre><code>pd.DataFrame({'Team':['Hawks','Hawks','Hawks','Hawks','Hawks'], 'Season':[1970,1971,1972,1973,1974],'Wins':[40,34,30,46,42]}) </code></pre> <p>I would ideally like to compute the sum of the number of wins between 1970 and 1971, 1971 and 1972, 1972 and 1973, etc. An inefficient way would be to use a loop, is there a way to do this using the .groupby function?</p>
[ { "answer_id": 74655182, "author": "Rohìt Jíndal", "author_id": 4116300, "author_profile": "https://Stackoverflow.com/users/4116300", "pm_score": 0, "selected": false, "text": "v-if v-show v-if Vue.component('child', {\n props: ['childmsg'],\n template: '<p>{{ childmsg }}</p>',\n mounted() {\n console.log('child component mounted');\n }\n});\n\nvar app = new Vue({\n el: '#app',\n data: {\n buttonMsg: 'Show Child Component',\n showChild: false\n },\n methods: {\n toggleBtn() {\n this.showChild = !this.showChild;\n this.buttonMsg = this.showChild ? 'Hide Child Component' : 'Show Child Component';\n }\n }\n}); <script src=\"https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js\"></script>\n<div id=\"app\">\n <button @click=\"toggleBtn\">{{ buttonMsg }}</button>\n <child v-if=\"showChild\" childmsg=\"This is a child message\"/>\n</div>" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74650404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8083465/" ]
74,650,405
<p>I'd like to figure out a way to compare columns in the SAME data frame, but in such a way that I create a new column called <code>STATUS</code> for the output. I have 3 columns 1)<code>SNPs</code>, 2)<code>gained</code>, and 3)<code>lost</code>. I want to know if the data in each cell in column 1 is present in either column 2 or 3. If the data from column 1 is present in column 2 then I would want the output to say <code>GAINED</code>, and if its present in column 3 then the output would be <code>LOST</code>. If it's present in either then the output will be <code>NEUTRAL</code>.</p> <p>Here is what I would like:</p> <pre><code>SNPs GAINED LOST STATUS 1_752566 1_949654 6_30022061 NEUTRAL 1_776546 1_1045331 6_30314321 NEUTRAL 1_832918 1_832918 13_95612033 GAINED 1_914852 1_1247494 1_914852 LOST </code></pre> <p>I've tried this:</p> <pre><code>data_frame$status &lt;- data.frame(lapply(data_frame[1], `%in%`, data_frame[2:3])) </code></pre> <p>but it produces 2 columns that all say <code>NEUTRAL</code>. I believe it's reading per row to see if it matches, but my data isn't organized in that manner such that it will find every match per row. Instead I'd like to search the entire column and have R find the matches in each cell instead of searching per row.</p>
[ { "answer_id": 74650462, "author": "IRTFM", "author_id": 1855677, "author_profile": "https://Stackoverflow.com/users/1855677", "pm_score": 1, "selected": false, "text": "ifelse tbl$status <- ifelse(tbl$SNPs %in% tbl$GAINED, \"GAINED\",\n ifelse(tbl$SNPs %in% tbl$LOST, \"LOST\", \"NEUTRAL\") )\n\n> tbl\n SNPs GAINED LOST STATUS status\n1 1_752566 1_949654 6_30022061 NEUTRAL NEUTRAL\n2 1_776546 1_1045331 6_30314321 NEUTRAL NEUTRAL\n3 1_832918 1_832918 13_95612033 GAINED GAINED\n4 1_914852 1_1247494 1_914852 LOST LOST\n" }, { "answer_id": 74650464, "author": "Gregor Thomas", "author_id": 903061, "author_profile": "https://Stackoverflow.com/users/903061", "pm_score": 2, "selected": false, "text": "lapply data_frame$STATUS = with(data_frame,\n ifelse(SNPs %in% GAINED, \"GAINED\",\n ifelse(SNPs %in% LOST, \"LOST\", \"NEUTRAL\")\n )\n)\n" }, { "answer_id": 74650479, "author": "Seth", "author_id": 19316600, "author_profile": "https://Stackoverflow.com/users/19316600", "pm_score": 1, "selected": false, "text": "case_when library(tidyverse)\n\ndf <-\n structure(\n list(\n SNPs = c(\"1_752566\", \"1_776546\", \"1_832918\", \"1_914852\"),\n GAINED = c(\"1_949654\", \"1_1045331\", \"1_832918\", \"1_1247494\"),\n LOST = c(\"6_30022061\", \"6_30314321\", \"13_95612033\", \"1_914852\")\n ),\n row.names = c(NA,-4L),\n spec = structure(list(\n cols = list(\n SNPs = structure(list(), class = c(\"collector_character\",\n \"collector\")),\n GAINED = structure(list(), class = c(\"collector_character\",\n \"collector\")),\n LOST = structure(list(), class = c(\"collector_character\",\n \"collector\"))\n ),\n default = structure(list(), class = c(\"collector_guess\",\n \"collector\")),\n delim = \",\"\n ), class = \"col_spec\"),\n class = c(\"spec_tbl_df\",\n \"tbl_df\", \"tbl\", \"data.frame\")\n )\n\ndf %>%\n mutate(STATUS = case_when(\n SNPs %in% GAINED ~ 'GAINED',\n SNPs %in% LOST ~ 'LOST',\n TRUE ~ 'NEUTRAL'\n ))\n#> # A tibble: 4 × 4\n#> SNPs GAINED LOST STATUS \n#> <chr> <chr> <chr> <chr> \n#> 1 1_752566 1_949654 6_30022061 NEUTRAL\n#> 2 1_776546 1_1045331 6_30314321 NEUTRAL\n#> 3 1_832918 1_832918 13_95612033 GAINED \n#> 4 1_914852 1_1247494 1_914852 LOST\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74650405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11924976/" ]
74,650,437
<p>Background: I have an array (A) of new objects that need to be added to an array field in Mongoose. if successful it should print to screen the newly updated object but it prints null. I checked the database and confirmed it also does not update at all. I followed the docs to use the $push and $each modifiers here: <a href="https://www.mongodb.com/docs/manual/reference/operator/update/each/" rel="nofollow noreferrer">https://www.mongodb.com/docs/manual/reference/operator/update/each/</a></p> <p>Desired Behaviour: I would like each object in (A) to be added to the Array field, not (A) itself. Upon success, it should print to screen the newly updated object.</p> <p>Attempted Approach:</p> <pre><code>let identifier={customer:{external_id:'12345'}} let array = [{value:30},{value:30}] User.findOneAndUpdate(identifier,{$push:{points:{$each:array}}},{new:true}) .then((result)=&gt;{ console.log(result) }) </code></pre> <p>Attempted Resolutions:</p> <ul> <li>I tested if the issue was with the identifier parameter, but it works fine when the update parameter does not have $each (i.e. it pushes the whole array (A) into the array field)</li> <li>I thought about using $addToSet like in the solution below, but as you can see in the sample code above, I want to push all objects even if they are not unique: <a href="https://stackoverflow.com/questions/71448134/mongoose-push-objects-into-nested-array">Mongoose - Push objects into nested array</a></li> </ul>
[ { "answer_id": 74650462, "author": "IRTFM", "author_id": 1855677, "author_profile": "https://Stackoverflow.com/users/1855677", "pm_score": 1, "selected": false, "text": "ifelse tbl$status <- ifelse(tbl$SNPs %in% tbl$GAINED, \"GAINED\",\n ifelse(tbl$SNPs %in% tbl$LOST, \"LOST\", \"NEUTRAL\") )\n\n> tbl\n SNPs GAINED LOST STATUS status\n1 1_752566 1_949654 6_30022061 NEUTRAL NEUTRAL\n2 1_776546 1_1045331 6_30314321 NEUTRAL NEUTRAL\n3 1_832918 1_832918 13_95612033 GAINED GAINED\n4 1_914852 1_1247494 1_914852 LOST LOST\n" }, { "answer_id": 74650464, "author": "Gregor Thomas", "author_id": 903061, "author_profile": "https://Stackoverflow.com/users/903061", "pm_score": 2, "selected": false, "text": "lapply data_frame$STATUS = with(data_frame,\n ifelse(SNPs %in% GAINED, \"GAINED\",\n ifelse(SNPs %in% LOST, \"LOST\", \"NEUTRAL\")\n )\n)\n" }, { "answer_id": 74650479, "author": "Seth", "author_id": 19316600, "author_profile": "https://Stackoverflow.com/users/19316600", "pm_score": 1, "selected": false, "text": "case_when library(tidyverse)\n\ndf <-\n structure(\n list(\n SNPs = c(\"1_752566\", \"1_776546\", \"1_832918\", \"1_914852\"),\n GAINED = c(\"1_949654\", \"1_1045331\", \"1_832918\", \"1_1247494\"),\n LOST = c(\"6_30022061\", \"6_30314321\", \"13_95612033\", \"1_914852\")\n ),\n row.names = c(NA,-4L),\n spec = structure(list(\n cols = list(\n SNPs = structure(list(), class = c(\"collector_character\",\n \"collector\")),\n GAINED = structure(list(), class = c(\"collector_character\",\n \"collector\")),\n LOST = structure(list(), class = c(\"collector_character\",\n \"collector\"))\n ),\n default = structure(list(), class = c(\"collector_guess\",\n \"collector\")),\n delim = \",\"\n ), class = \"col_spec\"),\n class = c(\"spec_tbl_df\",\n \"tbl_df\", \"tbl\", \"data.frame\")\n )\n\ndf %>%\n mutate(STATUS = case_when(\n SNPs %in% GAINED ~ 'GAINED',\n SNPs %in% LOST ~ 'LOST',\n TRUE ~ 'NEUTRAL'\n ))\n#> # A tibble: 4 × 4\n#> SNPs GAINED LOST STATUS \n#> <chr> <chr> <chr> <chr> \n#> 1 1_752566 1_949654 6_30022061 NEUTRAL\n#> 2 1_776546 1_1045331 6_30314321 NEUTRAL\n#> 3 1_832918 1_832918 13_95612033 GAINED \n#> 4 1_914852 1_1247494 1_914852 LOST\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74650437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9744790/" ]
74,650,451
<p>I have an example below that is an extremely simplified version of my actual code.</p> <p>I have a type that can either be an interface or another like so:</p> <pre class="lang-js prettyprint-override"><code>interface ChatBase { roomId?: string type: &quot;message&quot; | &quot;emoji&quot; configs: unknown } interface ChatMessage extends ChatBase { type: &quot;message&quot;, configs:{ text?: string } } interface ChatEmoji extends ChatBase { type: &quot;emoji&quot;, configs: { emoji?: string } } type Chat = ChatMessage | ChatEmoji </code></pre> <p>Here is a <a href="https://www.typescriptlang.org/play?ssl=50&amp;ssc=3&amp;pln=25&amp;pc=1#code/LAKFEsDsBcFMCcBmBDAxrABAYQBbOgELIDOmA3qBlRvAPa0C2AkgCYD8AXBsdPFAOaVq0AJ4AHWFwBEDWMWLJ%20sKRgA%20GKbAa0AVuClCqqWpETh%20xLgFdIAa0i0A7pFABfUB5BQ4SNJlz4ALJyCkoYsAAecJAsxNh4hCTkhhiiEtKy8orKADQpxqbmlhQg1GWpkdCc3LwCKe4gDd4IKOjx%20ACi2nrhUbAxcQGJpBglZWmSGlq6%20nml1AVmFlxj5VTTetU8fJCC81QNDaAT7dAYALxUQ8FZYepDXTOeBTwYqAmWpwDaALoXGF8Uqs1hMMiFslI5msjCYlp9gdCqHAotJtgIDPtyg0yq4odQEeNxJNNN1ZikyosiitydCNuBUbVdhjEdjqA0fs8PgA6BjIMQACne%20HOAD4EeBEIKElzKRYuXSAJQEhYmYi0AA2sC56to-H5UgAEiQMMhIOFSVIFfUUhL9XSVFA3tLZXEAGSup34GWwory0lKmkwyBqzXa3X6o1xU3mmaW62Y21C6Bck7nNNTC0Yd2e5Muv0zAOYimqjVanV6w3G-oxvRxzGHBVAA" rel="nofollow noreferrer">typescript playground</a></p> <p>Now in my code, when I try to simply check if &quot;emoji&quot; is defined in <code>configs</code>, it's making it super more complicated, surely there is a simpler way?</p> <pre class="lang-js prettyprint-override"><code>const chats: Chat[] = [ { type: &quot;message&quot;, configs: { text: &quot;string&quot; } }, { type: &quot;emoji&quot;, configs: { emoji: &quot;string&quot; } } ] chats.map(chat=&gt;{ if(chat.configs.emoji){ // &lt;=== THROWS ERROR SHOWN BELOW console.log(&quot;Has an emoji&quot;) } if(&quot;emoji&quot; in chat.configs &amp;&amp; chat.configs.emoji){ // &lt;= Works but ridiculously long console.log(&quot;Has an emoji&quot;) } if(chat.type === &quot;emoji&quot; &amp;&amp; chat.configs.emoji){ // &lt;= Works but sometimes I test for shared properties console.log(&quot;Has en emoji&quot;) } }) </code></pre> <p>But typescript is throwing me an error</p> <pre><code>Property 'emoji' does not exist on type '{ text?: string | undefined; }'. </code></pre> <p>So my question is, how can I can I make <code>if(&quot;emoji&quot; in chat.configs &amp;&amp; chat.configs.emoji)</code> not ridiculously long?</p>
[ { "answer_id": 74650469, "author": "Chris Hamilton", "author_id": 12914833, "author_profile": "https://Stackoverflow.com/users/12914833", "pm_score": 1, "selected": false, "text": "function hasDefinedEmoji(chat: Chat): chat is ChatEmoji & {configs: {emoji: string}} {\n return chat.type === \"emoji\" && Boolean(chat.configs.emoji);\n}\n if(hasDefinedEmoji(chat)){\n console.log(\"Has an emoji\", chat.configs.emoji) // works\n}\n function hasDefinedEmoji(chat: Chat): chat is ChatEmoji & {configs: {emoji: string}} {\n return true;\n}\n" }, { "answer_id": 74671396, "author": "Guillaume Acard", "author_id": 1323349, "author_profile": "https://Stackoverflow.com/users/1323349", "pm_score": 0, "selected": false, "text": "const isChatEmoji = (chat: ChatBase): chat is ChatEmoji => chat.type === \"emoji\";\nconst isChatMessage = (chat: ChatBase): chat is ChatMessage => chat.type === \"message\";\n chats.filter(isChatEmoji).forEach(chat => console.log(chat.configs.emoji));\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74650451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/517477/" ]
74,650,458
<p>I can't be the first one to ask this, but I'm having trouble finding the right search results. These terms are so overloaded.</p> <p>Eventually I want to make some additions to a remote branch. Remote branch may not exist. So first I clone remote repo, I only have default branch locally. Then:</p> <p>so far I have:</p> <pre><code>git checkout -b ${BRANCHNAME} origin/${BRANCHNAME} --track || git checkout -b ${BRANCHNAME} git add ... git commit -m &quot;new stuff&quot; git push origin ${BRANCHNAME} </code></pre> <p>Is there a nicer way to do the first line?</p>
[ { "answer_id": 74650469, "author": "Chris Hamilton", "author_id": 12914833, "author_profile": "https://Stackoverflow.com/users/12914833", "pm_score": 1, "selected": false, "text": "function hasDefinedEmoji(chat: Chat): chat is ChatEmoji & {configs: {emoji: string}} {\n return chat.type === \"emoji\" && Boolean(chat.configs.emoji);\n}\n if(hasDefinedEmoji(chat)){\n console.log(\"Has an emoji\", chat.configs.emoji) // works\n}\n function hasDefinedEmoji(chat: Chat): chat is ChatEmoji & {configs: {emoji: string}} {\n return true;\n}\n" }, { "answer_id": 74671396, "author": "Guillaume Acard", "author_id": 1323349, "author_profile": "https://Stackoverflow.com/users/1323349", "pm_score": 0, "selected": false, "text": "const isChatEmoji = (chat: ChatBase): chat is ChatEmoji => chat.type === \"emoji\";\nconst isChatMessage = (chat: ChatBase): chat is ChatMessage => chat.type === \"message\";\n chats.filter(isChatEmoji).forEach(chat => console.log(chat.configs.emoji));\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74650458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/745574/" ]
74,650,487
<p>I am trying to turn this: <code>const arr = ['last_updated_epoch', 1669949100]</code> into</p> <pre><code> {'last_updated_epoch': 1669949100} </code></pre> <p>I tried:</p> <pre><code>const arr = ['last_updated_epoch', 1669949100] arr.reduce((a, v) =&gt; ({ ...a, [v]: v}), {}) </code></pre> <p>but i get this:</p> <pre><code>{1669949100: 1669949100, last_updated_epoch: 'last_updated_epoch'} </code></pre> <p>and I want to get this:</p> <pre><code>{'last_updated_epoch': 1669949100} </code></pre> <p>so i can push it in an empty array and use array methods</p>
[ { "answer_id": 74650469, "author": "Chris Hamilton", "author_id": 12914833, "author_profile": "https://Stackoverflow.com/users/12914833", "pm_score": 1, "selected": false, "text": "function hasDefinedEmoji(chat: Chat): chat is ChatEmoji & {configs: {emoji: string}} {\n return chat.type === \"emoji\" && Boolean(chat.configs.emoji);\n}\n if(hasDefinedEmoji(chat)){\n console.log(\"Has an emoji\", chat.configs.emoji) // works\n}\n function hasDefinedEmoji(chat: Chat): chat is ChatEmoji & {configs: {emoji: string}} {\n return true;\n}\n" }, { "answer_id": 74671396, "author": "Guillaume Acard", "author_id": 1323349, "author_profile": "https://Stackoverflow.com/users/1323349", "pm_score": 0, "selected": false, "text": "const isChatEmoji = (chat: ChatBase): chat is ChatEmoji => chat.type === \"emoji\";\nconst isChatMessage = (chat: ChatBase): chat is ChatMessage => chat.type === \"message\";\n chats.filter(isChatEmoji).forEach(chat => console.log(chat.configs.emoji));\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74650487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20576853/" ]
74,650,500
<p>In SQL Server, this query runs very fast, less than a second:</p> <pre><code>SELECT T1.id FROM first AS T1 WHERE T1.id = 21 </code></pre> <p>This query also runs very fast, less than a second, even though it has 53 million records but only has about six records for id 21:</p> <pre><code>SELECT TOP 1 T2.value FROM second AS T2 WITH(INDEX(IX_second)) WHERE T2.id = 21 AND T2.b = 1 AND T2.c = 0 AND T2.d = 0 AND T2.e = 0 ORDER BY T2.id, T2.b, T2.c, T2.d, T2.e, T2.timestamp DESC </code></pre> <p>However, this query, where I replace the 21 in the inner <code>SELECT</code> with T1.id, is very, very slow, more than 80 seconds:</p> <pre><code>SELECT T1.id, T3.value FROM first AS T1 JOIN second AS T3 ON T3.id IN (SELECT TOP 1 T2.id FROM second AS T2 WITH(INDEX(IX_second)) WHERE T2.id = T1.id AND T2.b = 1 AND T2.c = 0 AND T2.d = 0 AND T2.e = 0 ORDER BY T2.id, T2.b, T2.c, T2.d, T2.e, T2.timestamp DESC) WHERE T1.id = 21 </code></pre> <p>Why would this query take so very long and how do I make it faster?</p> <hr /> <p>Edit: Here is the plan, with some table and field names changed to protect the innocent :) brentozar.com/pastetheplan/?id=rJYBSfwws</p>
[ { "answer_id": 74650469, "author": "Chris Hamilton", "author_id": 12914833, "author_profile": "https://Stackoverflow.com/users/12914833", "pm_score": 1, "selected": false, "text": "function hasDefinedEmoji(chat: Chat): chat is ChatEmoji & {configs: {emoji: string}} {\n return chat.type === \"emoji\" && Boolean(chat.configs.emoji);\n}\n if(hasDefinedEmoji(chat)){\n console.log(\"Has an emoji\", chat.configs.emoji) // works\n}\n function hasDefinedEmoji(chat: Chat): chat is ChatEmoji & {configs: {emoji: string}} {\n return true;\n}\n" }, { "answer_id": 74671396, "author": "Guillaume Acard", "author_id": 1323349, "author_profile": "https://Stackoverflow.com/users/1323349", "pm_score": 0, "selected": false, "text": "const isChatEmoji = (chat: ChatBase): chat is ChatEmoji => chat.type === \"emoji\";\nconst isChatMessage = (chat: ChatBase): chat is ChatMessage => chat.type === \"message\";\n chats.filter(isChatEmoji).forEach(chat => console.log(chat.configs.emoji));\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74650500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1828108/" ]
74,650,507
<p>We are trying to get the logs of pods after multiple restarts but we dont want to use any external solution like efk.</p> <p>i tried below config but its not working. does the below cmd run on the pod or it will run on node level</p> <pre><code>lifecycle: preStop: exec: command: [&quot;/bin/sh&quot;, &quot;-c&quot;, &quot;kubectl logs appworks-0 &gt; /container-stoped.txt&quot;] </code></pre>
[ { "answer_id": 74650469, "author": "Chris Hamilton", "author_id": 12914833, "author_profile": "https://Stackoverflow.com/users/12914833", "pm_score": 1, "selected": false, "text": "function hasDefinedEmoji(chat: Chat): chat is ChatEmoji & {configs: {emoji: string}} {\n return chat.type === \"emoji\" && Boolean(chat.configs.emoji);\n}\n if(hasDefinedEmoji(chat)){\n console.log(\"Has an emoji\", chat.configs.emoji) // works\n}\n function hasDefinedEmoji(chat: Chat): chat is ChatEmoji & {configs: {emoji: string}} {\n return true;\n}\n" }, { "answer_id": 74671396, "author": "Guillaume Acard", "author_id": 1323349, "author_profile": "https://Stackoverflow.com/users/1323349", "pm_score": 0, "selected": false, "text": "const isChatEmoji = (chat: ChatBase): chat is ChatEmoji => chat.type === \"emoji\";\nconst isChatMessage = (chat: ChatBase): chat is ChatMessage => chat.type === \"message\";\n chats.filter(isChatEmoji).forEach(chat => console.log(chat.configs.emoji));\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74650507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20204033/" ]
74,650,509
<p>I have to generate a random walk for a sequence of positions in 2D. The person doing the random walk starts at (0,0). At every move, she goes left, right, up or down. The random walk stops if she comes back to (0,0), or until she made a 1000 steps. *I am using the R language</p> <p>I have done this so far, but I am having trouble figuring out how to stop the random walk when she reaches (0,0) again. I only get two vectors back. Any help would be very appreciated. Thank you!</p> <pre><code>step.max&lt;-1000 destination&lt;-rbind(c(0,0)) Random.walk &lt;- function(n=step.max){ steps &lt;- matrix(c(0,0,-1,1,0,-1,1,0),nrow = 4) walk &lt;- steps[sample(1:5,n,replace = TRUE)] walk.1 &lt;-rbind(walk) ifelse(destination,break,apply(walk.1,2,cumsum)) } Random.walk(n) </code></pre>
[ { "answer_id": 74650469, "author": "Chris Hamilton", "author_id": 12914833, "author_profile": "https://Stackoverflow.com/users/12914833", "pm_score": 1, "selected": false, "text": "function hasDefinedEmoji(chat: Chat): chat is ChatEmoji & {configs: {emoji: string}} {\n return chat.type === \"emoji\" && Boolean(chat.configs.emoji);\n}\n if(hasDefinedEmoji(chat)){\n console.log(\"Has an emoji\", chat.configs.emoji) // works\n}\n function hasDefinedEmoji(chat: Chat): chat is ChatEmoji & {configs: {emoji: string}} {\n return true;\n}\n" }, { "answer_id": 74671396, "author": "Guillaume Acard", "author_id": 1323349, "author_profile": "https://Stackoverflow.com/users/1323349", "pm_score": 0, "selected": false, "text": "const isChatEmoji = (chat: ChatBase): chat is ChatEmoji => chat.type === \"emoji\";\nconst isChatMessage = (chat: ChatBase): chat is ChatMessage => chat.type === \"message\";\n chats.filter(isChatEmoji).forEach(chat => console.log(chat.configs.emoji));\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74650509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20662050/" ]
74,650,572
<p>I am trying to print a string with \t at both beginning and end, like below.</p> <pre><code>name2print=&quot;\tabhinav\t&quot; lastname=&quot;gupta&quot; print(name2print,lastname) </code></pre> <pre><code>Expected output should be abhinav gupta But the actual output is abhinav gupta </code></pre> <p>I tried with lstrip like this and as expected strips only the beginning &quot;\t&quot; and prints the trailing &quot;\t&quot;</p> <pre><code>print(name2print.lstrip(),lastname) Output: abhinav gupta </code></pre> <p>If lstrip() can print the trailing &quot;\t&quot; then why is the print statement ignoring the trailing tab character in the first string while printing? I think I am missing something basic. Please help.</p>
[ { "answer_id": 74650469, "author": "Chris Hamilton", "author_id": 12914833, "author_profile": "https://Stackoverflow.com/users/12914833", "pm_score": 1, "selected": false, "text": "function hasDefinedEmoji(chat: Chat): chat is ChatEmoji & {configs: {emoji: string}} {\n return chat.type === \"emoji\" && Boolean(chat.configs.emoji);\n}\n if(hasDefinedEmoji(chat)){\n console.log(\"Has an emoji\", chat.configs.emoji) // works\n}\n function hasDefinedEmoji(chat: Chat): chat is ChatEmoji & {configs: {emoji: string}} {\n return true;\n}\n" }, { "answer_id": 74671396, "author": "Guillaume Acard", "author_id": 1323349, "author_profile": "https://Stackoverflow.com/users/1323349", "pm_score": 0, "selected": false, "text": "const isChatEmoji = (chat: ChatBase): chat is ChatEmoji => chat.type === \"emoji\";\nconst isChatMessage = (chat: ChatBase): chat is ChatMessage => chat.type === \"message\";\n chats.filter(isChatEmoji).forEach(chat => console.log(chat.configs.emoji));\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74650572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20662060/" ]
74,650,578
<p>Asslam o Alaikum.... I have a problem in my code...my jquery code is only implement of the first row of table not on others....please check my code</p> <pre><code> &lt;tr&gt; &lt;td&gt;&lt;?php echo $row['serial no.'] ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo $row['pname'] ?&gt;&lt;/td&gt; &lt;td&gt;&lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;prate&quot; name = &quot;uprice&quot; value=&quot;&lt;?php echo $prate = $row['uprice'];?&gt;&quot;&gt;&lt;/td&gt; &lt;td&gt; &lt;input type=&quot;number&quot; class=&quot;form-control&quot; id=&quot;pqty&quot; name = &quot;quantity&quot; value =&quot;&lt;?php $quant = &quot;&quot;; echo $quant; ?&gt;&quot;&gt;&lt;/td&gt; &lt;td&gt; &lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;pTotal&quot; name = &quot;price&quot; value = &quot;&lt;?php $tprice = &quot;&quot;; echo $tprice; ?&gt;&quot; &gt;&lt;/td&gt; &lt;/tr&gt; </code></pre> <p>this is my html code....</p> <pre><code>&lt;script&gt; $(&quot;#prate&quot;).keyup(function(){ // console.log('presssed'); var prate = document.getElementById('prate').value; var pqty = document.getElementById('pqty').value; var ptotal = parseInt(prate) * parseInt(pqty); document.getElementById('pTotal').value = ptotal; }); $(&quot;#pqty&quot;).keyup(function(){ // console.log('presssed'); var prate = document.getElementById('prate').value; var pqty = document.getElementById('pqty').value; var ptotal = parseInt(prate) * parseInt(pqty); document.getElementById('pTotal').value = ptotal; }); &lt;/script&gt; </code></pre> <p>and this is jquery...plz help me out</p>
[ { "answer_id": 74651165, "author": "Ahmadreza Sadafi", "author_id": 9336947, "author_profile": "https://Stackoverflow.com/users/9336947", "pm_score": 0, "selected": false, "text": "each" }, { "answer_id": 74651191, "author": "Nagonus Lrak", "author_id": 20476491, "author_profile": "https://Stackoverflow.com/users/20476491", "pm_score": 1, "selected": true, "text": " $('.pqty').each(function(i, element){\n $(element).keyup(function(evt) { \n /* anything */\n })\n })\n" }, { "answer_id": 74651233, "author": "Satyandra Shakya", "author_id": 12953436, "author_profile": "https://Stackoverflow.com/users/12953436", "pm_score": 1, "selected": false, "text": "<script>\n $('input[name=\"uprice\"]').keyup(function(){\n \n var prate = $(this).val();\n var pqty = $(this).parent().next().find('input[name=\"quantity\"]').val();\n var ptotal = parseInt(prate) * parseInt(pqty);\n\n $(this).parent().next().next().find('input[name=\"price\"]').val(ptotal);\n });\n\n $('input[name=\"quantity\"]').keyup(function(){\n var prate = $(this).parent().prev().find('input[name=\"uprice\"]').val();;\n var pqty = $(this).val();\n var ptotal = parseInt(prate) * parseInt(pqty);\n\n $(this).parent().next().find('input[name=\"price\"]').val(ptotal);\n });\n</script>\n" }, { "answer_id": 74664234, "author": "That's Fantastic", "author_id": 17288124, "author_profile": "https://Stackoverflow.com/users/17288124", "pm_score": 0, "selected": false, "text": "// Step 1: Fetch Classes\nvar FetchedClasses = document.getElementsByClassName(\"myclass\"); \nvar Sum = 0;\n// Step 2: Iterate them\nArray.prototype.forEach.call(FetchedClasses, function(element) {\n // Step 3: Sum up their values\n Sum = Sum + element.value; //\n});\n// Now Show it anywhere you like.\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74650578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20662131/" ]
74,650,597
<p>I have four buttons, I would like that each time one of them is clicked it has a blue border. And if another one is clicked, the previous one will immediately get back its usual border style.</p> <p>I tried with loop but it doesn't work</p>
[ { "answer_id": 74650646, "author": "Hao-Jung Hsieh", "author_id": 12598451, "author_profile": "https://Stackoverflow.com/users/12598451", "pm_score": 1, "selected": false, "text": ":focus" }, { "answer_id": 74650685, "author": "Thunder", "author_id": 16499723, "author_profile": "https://Stackoverflow.com/users/16499723", "pm_score": 1, "selected": true, "text": "const buttons = document.querySelectorAll('button');\n\n// Set the initial border style for all buttons\nbuttons.forEach(button => {\n button.style.border = '1px solid black';\n});\n\n// Add a click event listener to each button\nbuttons.forEach(button => {\n button.addEventListener('click', () => {\n // Set the border style of all buttons to the initial style\n buttons.forEach(b => {\n b.style.border = '1px solid black';\n });\n\n // Set the border style of the clicked button to blue\n button.style.border = '1px solid blue';\n });\n});\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74650597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20662179/" ]
74,650,605
<p>Im a rookie in coding, an im figuring a way to shorten this code, it has too many if statements, if someone can help me out, i really apreciatted. I need to add a classList.remove to the same elements too after that</p> <p>So this is the code:</p> <pre><code>const inputElementName = document.getElementById(&quot;name&quot;); const inputElementMail = document.getElementById(&quot;email&quot;); const validateInputName = () =&gt; inputElementName.value.trim().length &gt; 0; const validateInputMail = () =&gt; inputElementMail.value.trim().length &gt; 0; const handleInputName = () =&gt; { const inputNameIsValid = validateInputName(); if (!inputNameIsValid) { return inputElementName.classList.add(&quot;error&quot;); } } const handleInputMail = () =&gt; { const inputMailIsValid = validateInputMail(); if (!inputMailIsValid) { return inputElementMail.classList.add(&quot;error&quot;); } } </code></pre>
[ { "answer_id": 74650646, "author": "Hao-Jung Hsieh", "author_id": 12598451, "author_profile": "https://Stackoverflow.com/users/12598451", "pm_score": 1, "selected": false, "text": ":focus" }, { "answer_id": 74650685, "author": "Thunder", "author_id": 16499723, "author_profile": "https://Stackoverflow.com/users/16499723", "pm_score": 1, "selected": true, "text": "const buttons = document.querySelectorAll('button');\n\n// Set the initial border style for all buttons\nbuttons.forEach(button => {\n button.style.border = '1px solid black';\n});\n\n// Add a click event listener to each button\nbuttons.forEach(button => {\n button.addEventListener('click', () => {\n // Set the border style of all buttons to the initial style\n buttons.forEach(b => {\n b.style.border = '1px solid black';\n });\n\n // Set the border style of the clicked button to blue\n button.style.border = '1px solid blue';\n });\n});\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74650605", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20662176/" ]
74,650,624
<p>I just want to create a table on HTML with a PHP loop. So, I try to do this:</p> <pre><code>&lt;table id=&quot;tdesign&quot;&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;No&lt;/th&gt; &lt;th&gt;Nama&lt;/th&gt; &lt;th&gt;Kelas&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;?php $no = 1; ?&gt; &lt;?php $kls = 10;?&gt; &lt;?php for ($i=1; $i &lt;= 10 ; $i++) :?&gt; &lt;tr&gt; &lt;td&gt;&lt;?php echo $no++; ?&gt;&lt;/td&gt; &lt;td&gt;Name &lt;?php echo $i; ?&gt;&lt;/td&gt; &lt;?php endfor; ?&gt; &lt;?php for ($j=10; $j &gt;= 1 ; $j--) : ?&gt; &lt;td&gt;&lt;?php echo &quot;Class &quot;. $j . &quot;\n&quot; ;?&gt;&lt;/td&gt; &lt;?php endfor; ?&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p>But, why the output becomes this?</p> <p><a href="https://i.stack.imgur.com/fomNM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fomNM.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74650646, "author": "Hao-Jung Hsieh", "author_id": 12598451, "author_profile": "https://Stackoverflow.com/users/12598451", "pm_score": 1, "selected": false, "text": ":focus" }, { "answer_id": 74650685, "author": "Thunder", "author_id": 16499723, "author_profile": "https://Stackoverflow.com/users/16499723", "pm_score": 1, "selected": true, "text": "const buttons = document.querySelectorAll('button');\n\n// Set the initial border style for all buttons\nbuttons.forEach(button => {\n button.style.border = '1px solid black';\n});\n\n// Add a click event listener to each button\nbuttons.forEach(button => {\n button.addEventListener('click', () => {\n // Set the border style of all buttons to the initial style\n buttons.forEach(b => {\n b.style.border = '1px solid black';\n });\n\n // Set the border style of the clicked button to blue\n button.style.border = '1px solid blue';\n });\n});\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74650624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13495863/" ]
74,650,627
<p>I can get the rank alias with this query:</p> <pre class="lang-sql prettyprint-override"><code>SELECT *, RANK() OVER (PARTITION BY some_field ORDER BY value) AS rk FROM my_table </code></pre> <p>Result:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>some_field</th> <th>value</th> <th>rk</th> </tr> </thead> <tbody> <tr> <td>same</td> <td>10</td> <td>1</td> </tr> <tr> <td>same</td> <td>20</td> <td>2</td> </tr> <tr> <td>same</td> <td>30</td> <td>3</td> </tr> </tbody> </table> </div> <p>And I tried to query with:</p> <pre class="lang-sql prettyprint-override"><code>SELECT *, RANK() OVER (PARTITION BY some_field ORDER BY value) AS rk FROM my_table WHERE rk = 1 </code></pre> <p>I got this error message <code>column &quot;rk&quot; does not exist</code></p> <p>If I tried a subquery, it works :</p> <pre class="lang-sql prettyprint-override"><code>SELECT * FROM ( SELECT *, RANK() OVER (PARTITION BY some_field ORDER BY value) AS rk FROM my_table ) AS t WHERE rk = 1 </code></pre> <p>Result:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>some_field</th> <th>value</th> <th>rk</th> </tr> </thead> <tbody> <tr> <td>same</td> <td>10</td> <td>1</td> </tr> </tbody> </table> </div> <p>But my question is why can't we use just one SELECT to do so.</p> <p>Is it because I use a function in my query?</p>
[ { "answer_id": 74650768, "author": "NF Meola", "author_id": 2447320, "author_profile": "https://Stackoverflow.com/users/2447320", "pm_score": 0, "selected": false, "text": "SELECT *, \n 1 AS rk\nFROM my_table\nWHERE RANK() OVER (PARTITION BY some_field ORDER BY value) = 1\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74650627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9823251/" ]
74,650,675
<p>I have a list of dictionaries in another list, I want sort those lists of dictionaries according to the date but I can't use sort function I don't know how to access in list (May be date it is not in correct way) I WANT TO KNOW HOW TO SORT SOME THING LIKE THIS OR HOW TO GET ACCESS TO THE &quot;DATE&quot;</p> <pre><code>dr = [ [{&quot;name&quot;: &quot;Tom&quot;, &quot;age&quot;: 10,&quot;group&quot;:&quot;sdd&quot;,&quot;points&quot;:2,&quot;date&quot;:&quot;2022 3 10&quot;}, {&quot;name&quot;: &quot;Mark&quot;, &quot;age&quot;: 5,&quot;group&quot;:&quot;sdo&quot;,&quot;points&quot;:6,&quot;date&quot;:&quot;2022 3 10&quot;}, {&quot;name&quot;: &quot;Pam&quot;, &quot;age&quot;: 7,&quot;group&quot;:&quot;spp&quot;,&quot;points&quot;:4,&quot;date&quot;:&quot;2022 3 10&quot;}], [{&quot;name&quot;: &quot;Tom&quot;, &quot;age&quot;: 10,&quot;group&quot;:&quot;sdd&quot;,&quot;points&quot;:5,&quot;date&quot;:&quot;2022 4 12&quot;}, {&quot;name&quot;: &quot;Mark&quot;, &quot;age&quot;: 5,&quot;group&quot;:&quot;sdo&quot;,&quot;points&quot;:6,&quot;date&quot;:&quot;2022 4 12&quot;}, {&quot;name&quot;: &quot;Pam&quot;, &quot;age&quot;: 7,&quot;group&quot;:&quot;spp&quot;,&quot;points&quot;:6,&quot;date&quot;:&quot;2022 4 12&quot;}], [{&quot;name&quot;: &quot;Tom&quot;, &quot;age&quot;: 10,&quot;group&quot;:&quot;sdd&quot;,&quot;points&quot;:8,&quot;date&quot;:&quot;2022 1 10&quot;}, {&quot;name&quot;: &quot;Mark&quot;, &quot;age&quot;: 5,&quot;group&quot;:&quot;sdo&quot;,&quot;points&quot;:12,&quot;date&quot;:&quot;2022 1 10&quot;}, {&quot;name&quot;: &quot;Pam&quot;, &quot;age&quot;: 7,&quot;group&quot;:&quot;spp&quot;,&quot;points&quot;:6,&quot;date&quot;:&quot;2022 1 10&quot;}], ] </code></pre> <p>I tried like this, but it doesn't work</p> <pre><code>for j in range(len(dr)): for k in range(j+1,len(dr)): if dr[j][&quot;date&quot;] &lt; dr[k][&quot;date&quot;]: dr[j],dr[k]=dr[k],dr[j] </code></pre> <p>after sorting it should be like this,</p> <pre><code>dr = [ [{&quot;name&quot;: &quot;Tom&quot;, &quot;age&quot;: 10,&quot;group&quot;:&quot;sdd&quot;,&quot;points&quot;:8,&quot;date&quot;:&quot;2022 1 10&quot;}, {&quot;name&quot;: &quot;Mark&quot;, &quot;age&quot;: 5,&quot;group&quot;:&quot;sdo&quot;,&quot;points&quot;:12,&quot;date&quot;:&quot;2022 1 10&quot;}, {&quot;name&quot;: &quot;Pam&quot;, &quot;age&quot;: 7,&quot;group&quot;:&quot;spp&quot;,&quot;points&quot;:6,&quot;date&quot;:&quot;2022 1 10&quot;}], [{&quot;name&quot;: &quot;Tom&quot;, &quot;age&quot;: 10,&quot;group&quot;:&quot;sdd&quot;,&quot;points&quot;:2,&quot;date&quot;:&quot;2022 3 10&quot;}, {&quot;name&quot;: &quot;Mark&quot;, &quot;age&quot;: 5,&quot;group&quot;:&quot;sdo&quot;,&quot;points&quot;:6,&quot;date&quot;:&quot;2022 3 10&quot;}, {&quot;name&quot;: &quot;Pam&quot;, &quot;age&quot;: 7,&quot;group&quot;:&quot;spp&quot;,&quot;points&quot;:4,&quot;date&quot;:&quot;2022 3 10&quot;}], [{&quot;name&quot;: &quot;Tom&quot;, &quot;age&quot;: 10,&quot;group&quot;:&quot;sdd&quot;,&quot;points&quot;:5,&quot;date&quot;:&quot;2022 4 12&quot;}, {&quot;name&quot;: &quot;Mark&quot;, &quot;age&quot;: 5,&quot;group&quot;:&quot;sdo&quot;,&quot;points&quot;:6,&quot;date&quot;:&quot;2022 4 12&quot;}, {&quot;name&quot;: &quot;Pam&quot;, &quot;age&quot;: 7,&quot;group&quot;:&quot;spp&quot;,&quot;points&quot;:6,&quot;date&quot;:&quot;2022 4 12&quot;}] ] </code></pre>
[ { "answer_id": 74650768, "author": "NF Meola", "author_id": 2447320, "author_profile": "https://Stackoverflow.com/users/2447320", "pm_score": 0, "selected": false, "text": "SELECT *, \n 1 AS rk\nFROM my_table\nWHERE RANK() OVER (PARTITION BY some_field ORDER BY value) = 1\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74650675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20095556/" ]
74,650,717
<p>I am struggling with a problem that I haven't found a solution by searching, I hope someone can help me to unblock me : Given a vertex, I want to check if it form a self loop in a directed graph or not in O(|V|).</p> <p>Here s a brief implementation of my graph Class :</p> <pre><code>template &lt;class T&gt; class Digraph { public: Digraph(); ~Digraph(); bool loop(T u) const; private: std::map&lt;T, std::set&lt;T&gt;&gt; graph; } </code></pre>
[ { "answer_id": 74650768, "author": "NF Meola", "author_id": 2447320, "author_profile": "https://Stackoverflow.com/users/2447320", "pm_score": 0, "selected": false, "text": "SELECT *, \n 1 AS rk\nFROM my_table\nWHERE RANK() OVER (PARTITION BY some_field ORDER BY value) = 1\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74650717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20662282/" ]
74,650,746
<p>I want to add multiple Leaflet map with different content on the same page but it gives me the error:</p> <pre><code>Map container is already initialized. </code></pre> <p>I'm initializing the map in a <code>useEffect</code>:</p> <pre><code> useEffect(() =&gt; { if (!map) { const newMap = L.map(&quot;map&quot;, { zoomControl: true, minZoom: minZoom, maxZoom: maxZoom, maxBounds: latLngBounds, attributionControl: false, }).setView(latLngCenter, defaultZoom) L.tileLayer(&quot;https://{s}.basemaps.cartocdn.com/dark_nolabels/{z}/{x}/{y}{r}.png&quot;).addTo( newMap ) setMap(newMap) } }, [map]) </code></pre> <p>Then I'm returning a div with <code>id=map</code>.</p> <p>I'm getting the error on line <code>const newMap</code>. I think we can't have 2 maps on the same page with different contents?</p>
[ { "answer_id": 74650768, "author": "NF Meola", "author_id": 2447320, "author_profile": "https://Stackoverflow.com/users/2447320", "pm_score": 0, "selected": false, "text": "SELECT *, \n 1 AS rk\nFROM my_table\nWHERE RANK() OVER (PARTITION BY some_field ORDER BY value) = 1\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74650746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20313416/" ]
74,650,783
<p>I need to combine the <code>gid</code> and <code>subGroups</code> and output it into an array of strings without duplication. My problem now is that it only gets the first level.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const oldGroup = [ { "gid": "JFK", "subGroups": [ "SFO", "LAX" ] }, { "gid": "JFK", "subGroups": [ "SFO", "LAX" ] }, { "gid": "SFO", "subGroups": [] }, { "gid": "LAX", "subGroups": [ "LGA" ] } ] const newGroup = [...new Set(oldGroup.map((group) =&gt; group.gid))] console.log(newGroup)</code></pre> </div> </div> </p>
[ { "answer_id": 74650812, "author": "CertainPerformance", "author_id": 9515207, "author_profile": "https://Stackoverflow.com/users/9515207", "pm_score": 2, "selected": true, "text": ".flatMap .map .gid .subGroups const oldGroup = [\n {\n \"gid\": \"JFK\",\n \"subGroups\": [\n \"SFO\",\n \"LAX\"\n ]\n },\n {\n \"gid\": \"JFK\",\n \"subGroups\": [\n \"SFO\",\n \"LAX\"\n ]\n },\n {\n \"gid\": \"SFO\",\n \"subGroups\": []\n },\n {\n \"gid\": \"LAX\",\n \"subGroups\": [\n \"LGA\"\n ]\n }\n]\n\nconst newGroup = [...new Set(oldGroup.flatMap((group) => [group.gid, ...group.subGroups]))]\n\nconsole.log(newGroup)" }, { "answer_id": 74650825, "author": "Dhammika", "author_id": 16357682, "author_profile": "https://Stackoverflow.com/users/16357682", "pm_score": 0, "selected": false, "text": "const oldGroup = [\n {\n \"gid\": \"JFK\",\n \"subGroups\": [\n \"SFO\",\n \"LAX\"\n ]\n },\n {\n \"gid\": \"JFK\",\n \"subGroups\": [\n \"SFO\",\n \"LAX\"\n ]\n },\n {\n \"gid\": \"SFO\",\n \"subGroups\": []\n },\n {\n \"gid\": \"LAX\",\n \"subGroups\": [\n \"LGA\"\n ]\n }\n]\n// Transform the oldGroup array into a new array that only contains the gid and subGroups values\nconst newGroup = oldGroup.map(group => [group.gid, ...group.subGroups]).flat();\n\n// Remove any duplicate values from the new array\nconst dedupedGroup = newGroup.filter((value, index) => newGroup.indexOf(value) === index);\n\nconsole.log(dedupedGroup); // [\"JFK\", \"SFO\", \"LAX\", \"SFO\", \"LAX\", \"SFO\", \"LAX\", \"LGA\"]\n" }, { "answer_id": 74650868, "author": "Peter Thoeny", "author_id": 7475450, "author_profile": "https://Stackoverflow.com/users/7475450", "pm_score": 2, "selected": false, "text": ".reduce() const oldGroup = [\n { \"gid\": \"JFK\", \"subGroups\": [ \"SFO\", \"LAX\" ] },\n { \"gid\": \"JFK\", \"subGroups\": [ \"SFO\", \"LAX\" ] },\n { \"gid\": \"SFO\", \"subGroups\": [] },\n { \"gid\": \"LAX\", \"subGroups\": [ \"LGA\" ] }\n];\n\nconst newGroup = Object.keys(oldGroup.reduce((acc, obj) => {\n acc[obj.gid] = true;\n obj.subGroups.forEach(name => { acc[name] = true; } );\n return acc;\n}, {}));\n\nconsole.log(newGroup) .reduce() acc, obj {} Object.keys()" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74650783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8305219/" ]
74,650,835
<p>I have 621224 * 1 data in my Excel Sheet and have to calculate total no. of duplicates in the sheet but it takes a lot too much time with<code> =IF(COUNTIF($J$1000:J14353,J5353)&gt;1,1,0)</code> so this formula might be taking n^2 complexity to find duplicates, I am looking for a formula that takes less time and if possible takes nlogn time, if there is in Excel</p> <p>As of now I am doing this task manually taking a range of 10k which works in acceptable time and also to add on I have sorted the list I searched for vlookup and found it will take around same time as countif</p>
[ { "answer_id": 74651046, "author": "Harun24hr", "author_id": 5514747, "author_profile": "https://Stackoverflow.com/users/5514747", "pm_score": 0, "selected": false, "text": "IF() =SUM(--(COUNTIFS(A3:A13,A3:A13)>1))\n" }, { "answer_id": 74651321, "author": "Jos Woolley", "author_id": 17007704, "author_profile": "https://Stackoverflow.com/users/17007704", "pm_score": 3, "selected": true, "text": "COUNTIFS =SUMPRODUCT(N(MATCH(A1:A750000,A:A)<>ROW(A1:A750000))) Office 365 =LET(ζ,A1:A750000,ξ,SORT(ζ),SUMPRODUCT(N(MATCH(ξ,ξ)<>SEQUENCE(ROWS(ζ)))))" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74650835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20309275/" ]
74,650,846
<p>I placed the rectangles over the images. I then bound a click to a call that flipped tiles over by lowering the rectangle below the image. It works for the first call to the function, but when I click another tile, that one won't flip over. The program still registers the second flip because it'll flip everything back over if it's an incorrect match; the only problem is that it won't have the rectangle go under the image.</p> <pre><code># ======================================= import statements import tkinter as tk import time import random import PIL import PIL.Image as Image import PIL.ImageTk as ImageTk # ======================================= class def class MemoryGame: def __init__(self): #initialize window self.window = tk.Tk() self.window.title(&quot;Sea Life Memory Game&quot;) self.window.minsize(590, 600) self.window.maxsize(590, 600) #set main canvas as background self.canvas = tk.Canvas(self.window, bg=&quot;lightblue&quot;, bd=0, highlightthickness=0, width=590, height=600) self.canvas.grid(row=0, column=0) self.canvas.bind(&quot;&lt;Button-1&gt;&quot;, self.chooseTile) #establish coordinates for tiles and shuffle image placement coordinates = [(5,30,105,130), (5,160,105,260), (5,290,105,390), (5,420,105,520), (125,30,225,130), (125,160,225,260), (125,290,225,390), (125,420,225,520), (245,30,345,130), (245,160,345,260), (245,290,345,390), (245,420,345,520), (365,30,465,130), (365,160,465,260), (365,290,465,390), (365,420,465,520), (485,30,585,130), (485,160,585,260), (485,290,585,390), (485,420,585,520)] imageChoices = ['cropped images/001-turtle.png','cropped images/007-blowfish.png','cropped images/010-jellyfish.png','cropped images/011-starfish.png','cropped images/018-lobster.png','cropped images/028-fish.png','cropped images/033-walrus.png','cropped images/042-goldfish.png','cropped images/045-seal.png','cropped images/046-penguin.png'] random.shuffle(coordinates) #write title to top of canvas self.canvas.create_text(295, 15, text=&quot;Sea Life Memory Game!&quot;, anchor=&quot;center&quot;, fill=&quot;white&quot;, font=&quot;Times 24 bold&quot;) self.selectedTile = None #initialize counts coordinateCount = 0 imageCount = 0 self.imageCollection = {} #for loop to attach images to each rectangle on the canvas for i in range(len(imageChoices)): otherDict = {} x1, y1, x2, y2 = coordinates[coordinateCount] # if imageCount &lt;= 9: self.image = ImageTk.PhotoImage(Image.open(imageChoices[imageCount])) self.image.img = self.image self.id = self.canvas.create_image(x1, y1, anchor=&quot;nw&quot;, image=self.image.img) self.canvas.create_rectangle(x1, y1, x2, y2, fill=&quot;white&quot;, outline=&quot;white&quot;) coordinateCount += 1 x1, y1, x2, y2 = coordinates[coordinateCount] self.id = self.canvas.create_image(x1, y1, anchor=&quot;nw&quot;, image=self.image.img) self.canvas.create_rectangle(x1, y1, x2, y2, fill=&quot;white&quot;, outline=&quot;white&quot;) coordinateCount += 1 imageCount += 1 otherDict[&quot;faceDown&quot;] = True self.imageCollection[self.id] = otherDict #create instructional text self.canvas.create_text(295, 550, text=&quot;Find all the pairs as fast as possible.&quot;, fill=&quot;white&quot;, font=&quot;Times 18&quot;, anchor=&quot;center&quot;) self.canvas.create_text(295, 570, text=&quot;Click on a card to turn it over and find the same matching card.&quot;, fill=&quot;white&quot;, font=&quot;Times 18&quot;, anchor=&quot;center&quot;) def run(self): self.window.mainloop() global list list = [] def chooseTile(self, event): # global list x = event.x y = event.y item = self.canvas.find_overlapping(x-5,y-5,x+5,y+5) list.append(item) print(len(list)) if len(list) &lt; 2: self.canvas.tag_lower(list[0][1]) elif len(list) == 2: self.canvas.tag_lower(list[1][1]) if self.canvas.itemcget(list[0][0], &quot;image&quot;) == self.canvas.itemcget(list[1][0], &quot;image&quot;): list.clear() else: time.sleep(1.0) self.canvas.lower(list[0][0], list[0][1]) self.canvas.lower(list[1][0], list[1][1]) list.clear() # ======================================= script calls game = MemoryGame() game.run() </code></pre>
[ { "answer_id": 74651046, "author": "Harun24hr", "author_id": 5514747, "author_profile": "https://Stackoverflow.com/users/5514747", "pm_score": 0, "selected": false, "text": "IF() =SUM(--(COUNTIFS(A3:A13,A3:A13)>1))\n" }, { "answer_id": 74651321, "author": "Jos Woolley", "author_id": 17007704, "author_profile": "https://Stackoverflow.com/users/17007704", "pm_score": 3, "selected": true, "text": "COUNTIFS =SUMPRODUCT(N(MATCH(A1:A750000,A:A)<>ROW(A1:A750000))) Office 365 =LET(ζ,A1:A750000,ξ,SORT(ζ),SUMPRODUCT(N(MATCH(ξ,ξ)<>SEQUENCE(ROWS(ζ)))))" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74650846", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20662448/" ]
74,650,849
<p>So I'm trying to create a BarChart for the category, and each category will have a respective color. I map this information from the MongoDB.</p> <pre><code> const [topDepartment,setTopDepartment] = useState([]) useEffect(() =&gt;{ const getTopDepartment = async () =&gt;{ try { const res = await publicRequest.get(`/order/departments`) setTopDepartment(res.data) setLoading(false) } catch (error) { } } getTopDepartment() },[setTopDepartment]) </code></pre> <p>This is the data I received</p> <pre><code>[ { &quot;total&quot;: 4, &quot;category&quot;: &quot;CAHS&quot; }, { &quot;total&quot;: 2, &quot;category&quot;: &quot;CEIS&quot; } ] </code></pre> <p>So what I'm trying to accomplish right now is , how can I add another information inside the objects, like this.</p> <pre><code> const updatedData = [ { &quot;total&quot;: 4, &quot;category&quot;: &quot;CAHS&quot; &quot;color&quot;: &quot;purple&quot; }, { &quot;total&quot;: 2, &quot;category&quot;: &quot;CEIS&quot; &quot;color&quot;: &quot;green&quot; } ] </code></pre> <p>Like in this image, the Bar will change it's color depending on its category <a href="https://i.stack.imgur.com/UzQRr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UzQRr.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74651046, "author": "Harun24hr", "author_id": 5514747, "author_profile": "https://Stackoverflow.com/users/5514747", "pm_score": 0, "selected": false, "text": "IF() =SUM(--(COUNTIFS(A3:A13,A3:A13)>1))\n" }, { "answer_id": 74651321, "author": "Jos Woolley", "author_id": 17007704, "author_profile": "https://Stackoverflow.com/users/17007704", "pm_score": 3, "selected": true, "text": "COUNTIFS =SUMPRODUCT(N(MATCH(A1:A750000,A:A)<>ROW(A1:A750000))) Office 365 =LET(ζ,A1:A750000,ξ,SORT(ζ),SUMPRODUCT(N(MATCH(ξ,ξ)<>SEQUENCE(ROWS(ζ)))))" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74650849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18478430/" ]
74,650,865
<p>how to change a div to a textarea to edit the text in the div when a button is clicked and the same button is clicked again then that textarea change to a div.</p> <p>HTML</p> <pre><code>&lt;button class=&quot;button&quot;&gt;click me&lt;/button&gt; &lt;div class=&quot;div&quot;&gt;this is div or textarea&lt;/div&gt; </code></pre> <p>JS</p> <pre><code>const button = document.querySelector('button'); const div = document.querySelector('div'); let isTextarea = false button.addEventListener('click', () =&gt; { if(isTextarea) { const div = document.createElement('div') const textarea = document.createElement('textarea') div.innerHTML = textarea.value textarea.parentNode.replaceChild(div, textarea) isTextarea = false }else { const textarea =document.createElement('textarea') textarea.innerHTML = div.innerHTML div.parentNode.replaceChild(textarea, div) isTextarea = true } } ) </code></pre>
[ { "answer_id": 74651046, "author": "Harun24hr", "author_id": 5514747, "author_profile": "https://Stackoverflow.com/users/5514747", "pm_score": 0, "selected": false, "text": "IF() =SUM(--(COUNTIFS(A3:A13,A3:A13)>1))\n" }, { "answer_id": 74651321, "author": "Jos Woolley", "author_id": 17007704, "author_profile": "https://Stackoverflow.com/users/17007704", "pm_score": 3, "selected": true, "text": "COUNTIFS =SUMPRODUCT(N(MATCH(A1:A750000,A:A)<>ROW(A1:A750000))) Office 365 =LET(ζ,A1:A750000,ξ,SORT(ζ),SUMPRODUCT(N(MATCH(ξ,ξ)<>SEQUENCE(ROWS(ζ)))))" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74650865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20464992/" ]
74,650,920
<p>I have a Access DB table that have the following data.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Room-Bed</th> <th>Status</th> </tr> </thead> <tbody> <tr> <td>100-A</td> <td>Available</td> </tr> <tr> <td>100-B</td> <td>Occupied</td> </tr> <tr> <td>101-A</td> <td>Available</td> </tr> <tr> <td>101-B</td> <td>Available</td> </tr> <tr> <td>102-A</td> <td>Occupied</td> </tr> <tr> <td>102-B</td> <td>Occupied</td> </tr> </tbody> </table> </div> <p>Having the room logic calculation as follows</p> <ol> <li>In one bed, there are two beds, if any one bed is occupied, the room status is occupied.</li> <li>If both beds are not occupied, the room status is available</li> <li>If both beds are occupied, the room status is occupied</li> <li>Likewise, is there are rooms with two beds or more, the room status is occupied as long as one of the bed is occupied.</li> </ol> <p>Is there a way to design a query such that it will computed a room-level result as follows</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Room</th> <th>Status</th> </tr> </thead> <tbody> <tr> <td>100</td> <td>Occupied</td> </tr> <tr> <td>101</td> <td>Available</td> </tr> <tr> <td>102</td> <td>Occupied</td> </tr> </tbody> </table> </div>
[ { "answer_id": 74651136, "author": "seanb", "author_id": 14267425, "author_profile": "https://Stackoverflow.com/users/14267425", "pm_score": 0, "selected": false, "text": "room_bed_list room room-bed room-bed-status SELECT room_bed_status.room,\n IIF(Sum(IIf([room_bed_list].[room-bed-status] = \"Occupied\",1,0)) > 0, \"Occupied\", \"Available\") AS room_status\nFROM room_bed_list\nGROUP BY room_bed_status.room;\n" }, { "answer_id": 74652195, "author": "Gustav", "author_id": 3527297, "author_profile": "https://Stackoverflow.com/users/3527297", "pm_score": 1, "selected": false, "text": "Select \n CStr(Val([Room-Bed])) As Room,\n Max([Status]) As RoomStatus\nFrom\n Rooms\nGroup By\n CStr(Val([Room-Bed]))\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74650920", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12528631/" ]
74,650,928
<p>OS controls the max number of open file discripters.</p> <p>Is there any method that only a process sets a specific the max number of openfiles and, other processes only can use the traditional default max number of openfiles?</p>
[ { "answer_id": 74651021, "author": "Sunil Bojanapally", "author_id": 1079907, "author_profile": "https://Stackoverflow.com/users/1079907", "pm_score": 1, "selected": false, "text": "<PID>" }, { "answer_id": 74651048, "author": "Craig Estey", "author_id": 5382650, "author_profile": "https://Stackoverflow.com/users/5382650", "pm_score": 3, "selected": true, "text": "getrlimit setrlimit fork getrlimit/setrlimit execvp stdin/stdout/stderr #include <stdio.h>\n#include <stdlib.h>\n#include <fcntl.h>\n#include <sys/resource.h>\n\nvoid\nshow(struct rlimit *rlim,const char *who)\n{\n\n printf(\"rlim_cur=%d rlim_max=%d [%s]\\n\",\n rlim->rlim_cur,rlim->rlim_max,who);\n}\n\nint\nmain(int argc,char **argv)\n{\n int err;\n struct rlimit rlim;\n\n --argc;\n ++argv;\n\n setlinebuf(stdout);\n setlinebuf(stderr);\n\n err = getrlimit(RLIMIT_NOFILE,&rlim);\n if (err < 0) {\n perror(\"getrlimit\");\n exit(1);\n }\n\n show(&rlim,\"original\");\n\n if (argc > 0) {\n rlim.rlim_cur = atoi(*argv);\n err = setrlimit(RLIMIT_NOFILE,&rlim);\n\n if (err < 0) {\n perror(\"setrlimit\");\n exit(1);\n }\n\n err = getrlimit(RLIMIT_NOFILE,&rlim);\n if (err < 0) {\n perror(\"setrlimit\");\n exit(1);\n }\n show(&rlim,\"setrlimit\");\n }\n\n int count = 0;\n while (1) {\n int fd = open(\"/dev/null\",O_RDONLY);\n if (fd < 0) {\n perror(\"open\");\n break;\n }\n ++count;\n }\n\n printf(\"max open files: %d\\n\",count);\n\n return 0;\n}\n rlim_cur=1024 rlim_max=4096 [original]\nopen: Too many open files\nmax open files: 1021\n rlim_cur=1024 rlim_max=4096 [original]\nrlim_cur=17 rlim_max=4096 [setrlimit]\nopen: Too many open files\nmax open files: 14\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74650928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20182123/" ]
74,650,954
<p>I'm trying to import a route.js file in my index.js file. I am exporting in the routes file and importing it in the index with .js extension. What am I missing here?</p> <p>Folder structure:</p> <p>Routes folder is in the server folder, same as index.js - accessible by a single <code>.</code> VsCode also highlights the location when typing, so that's not the issue.</p> <p>routes.js:</p> <pre><code>import { registerUser } from '../controllers/userController' const router = express.Router() router.post(&quot;/&quot;, registerUser) export default router; </code></pre> <p>index.js:</p> <pre><code>import mongoose from &quot;mongoose&quot;; import cors from &quot;cors&quot;; import dotenv from &quot;dotenv&quot;; import userRoutes from './routes/userRoutes.js' dotenv.config(); const app = express(); app.use(cors()); app.use('/users', userRoutes) const PORT = process.env.PORT; mongoose .connect(process.env.CONNECTION_URL) .then(() =&gt; console.log(&quot;DB Connected&quot;)) .then(() =&gt; app.listen(PORT, () =&gt; console.log(`Server is running on ${PORT}`)) ) .catch((error) =&gt; console.log(error.message)); </code></pre>
[ { "answer_id": 74651021, "author": "Sunil Bojanapally", "author_id": 1079907, "author_profile": "https://Stackoverflow.com/users/1079907", "pm_score": 1, "selected": false, "text": "<PID>" }, { "answer_id": 74651048, "author": "Craig Estey", "author_id": 5382650, "author_profile": "https://Stackoverflow.com/users/5382650", "pm_score": 3, "selected": true, "text": "getrlimit setrlimit fork getrlimit/setrlimit execvp stdin/stdout/stderr #include <stdio.h>\n#include <stdlib.h>\n#include <fcntl.h>\n#include <sys/resource.h>\n\nvoid\nshow(struct rlimit *rlim,const char *who)\n{\n\n printf(\"rlim_cur=%d rlim_max=%d [%s]\\n\",\n rlim->rlim_cur,rlim->rlim_max,who);\n}\n\nint\nmain(int argc,char **argv)\n{\n int err;\n struct rlimit rlim;\n\n --argc;\n ++argv;\n\n setlinebuf(stdout);\n setlinebuf(stderr);\n\n err = getrlimit(RLIMIT_NOFILE,&rlim);\n if (err < 0) {\n perror(\"getrlimit\");\n exit(1);\n }\n\n show(&rlim,\"original\");\n\n if (argc > 0) {\n rlim.rlim_cur = atoi(*argv);\n err = setrlimit(RLIMIT_NOFILE,&rlim);\n\n if (err < 0) {\n perror(\"setrlimit\");\n exit(1);\n }\n\n err = getrlimit(RLIMIT_NOFILE,&rlim);\n if (err < 0) {\n perror(\"setrlimit\");\n exit(1);\n }\n show(&rlim,\"setrlimit\");\n }\n\n int count = 0;\n while (1) {\n int fd = open(\"/dev/null\",O_RDONLY);\n if (fd < 0) {\n perror(\"open\");\n break;\n }\n ++count;\n }\n\n printf(\"max open files: %d\\n\",count);\n\n return 0;\n}\n rlim_cur=1024 rlim_max=4096 [original]\nopen: Too many open files\nmax open files: 1021\n rlim_cur=1024 rlim_max=4096 [original]\nrlim_cur=17 rlim_max=4096 [setrlimit]\nopen: Too many open files\nmax open files: 14\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74650954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16604189/" ]
74,650,981
<p>this is my first time deploying <code>nodejs</code> from <code>localhost</code> to the live server. I am using <code>aapanel</code> for my live server.</p> <p>Here is the relevant code in <code>node server.js</code> file:</p> <pre><code>const hostname = 'localhost'; // const hostname = 'www.thespacebar.io'; // set port, listen for requests const PORT = process.env.PORT || 8080; app.listen(PORT, hostname, () =&gt; { console.log(`Server is running on port ${PORT}.`); }); </code></pre> <p>Here is my <code>pm2</code> settings: <a href="https://i.stack.imgur.com/qZv1z.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qZv1z.png" alt="enter image description here" /></a></p> <p>I am unable to open my <code>nodejs</code> app with GET <code>https://www.thespacebar.io:8080</code>, but it works for GET <code>http://www.thespacebar.io:8080</code></p> <p>GET <code>https://www.thespacebar.io:8080</code> does not work with error:</p> <pre><code>This site can’t provide a secure connection ERR_SSL_PROTOCOL_ERROR </code></pre> <p>Anyone know what I did wrong?</p> <p><strong>EDIT</strong>: I have installed <code>Caddy</code> and setup the <code>Caddyfile</code> in <code>/etc/caddy</code> like this:</p> <pre><code># The Caddyfile is an easy way to configure your Caddy web server. # # Unless the file starts with a global options block, the first # uncommented line is always the address of your site. # # To use your own domain name (with automatic HTTPS), first make # sure your domain's A/AAAA DNS records are properly pointed to # this machine's public IP, then replace &quot;:80&quot; below with your # domain name. import ./thespacebar.io :80 { # Set this path to your site's directory. root * /usr/share/caddy # Enable the static file server. file_server # Another common task is to set up a reverse proxy: # reverse_proxy localhost:8080 # Or serve a PHP site through php-fpm: # php_fastcgi localhost:9000 } # Refer to the Caddy docs for more information: # https://caddyserver.com/docs/caddyfile </code></pre> <p>and created the adjacent file <code>thespacebar.io</code>:</p> <pre><code>thespacebar.io { reverse_proxy localhost:8080 } </code></pre> <p>but when I visit <code>https://thespacebar.io/</code>, I end up at <code>index.html</code> instead of the JSON <code>{ message: &quot;Welcome to bezkoder application.&quot; }</code> and <strong>POST</strong> <code>http://www.thespacebar.io/api/verification/callback</code> with <code>body param</code> <code>verify_token:abcde</code> is supposed to show the JSON:</p> <pre><code>{ &quot;message&quot;: &quot;Callback called successfully.&quot; } </code></pre> <p>instead of <code>404 Not Found</code></p> <p><strong>EDIT 2</strong>: I have removed the portion:</p> <pre><code># :80 { # Set this path to your site's directory. # root * /usr/share/caddy # Enable the static file server. # file_server # Another common task is to set up a reverse proxy: # reverse_proxy localhost:8080 # Or serve a PHP site through php-fpm: # php_fastcgi localhost:9000 # } # Refer to the Caddy docs for more information: # https://caddyserver.com/docs/caddyfile </code></pre> <p>from <code>etc/caddy/Caddyfile</code></p> <p>but when I run <code>caddy run Caddyfile</code> and <code>caddy reload Caddyfile</code>, I am getting this error:</p> <pre><code>[root@vultrguest caddy]# caddy run Caddyfile 2022/12/02 08:11:44.132 INFO using adjacent Caddyfile 2022/12/02 08:11:44.132 WARN Caddyfile input is not formatted; run the 'caddy fmt' command to fix inconsistencies {&quot;adapter&quot;: &quot;caddyfile&quot;, &quot;file&quot;: &quot;Caddyfile&quot;, &quot;line&quot;: 12} 2022/12/02 08:11:44.133 INFO admin admin endpoint started {&quot;address&quot;: &quot;localhost:2019&quot;, &quot;enforce_origin&quot;: false, &quot;origins&quot;: [&quot;//localhost:2019&quot;, &quot;//[::1]:2019&quot;, &quot;//127.0.0.1:2019&quot;]} 2022/12/02 08:11:44.133 INFO http server is listening only on the HTTPS port but has no TLS connection policies; adding one to enable TLS {&quot;server_name&quot;: &quot;srv0&quot;, &quot;https_port&quot;: 443} 2022/12/02 08:11:44.133 INFO http enabling automatic HTTP-&gt;HTTPS redirects {&quot;server_name&quot;: &quot;srv0&quot;} 2022/12/02 08:11:44.133 INFO tls.cache.maintenance started background certificate maintenance {&quot;cache&quot;: &quot;0xc000151030&quot;} 2022/12/02 08:11:44.133 INFO tls.cache.maintenance stopped background certificate maintenance {&quot;cache&quot;: &quot;0xc000151030&quot;} Error: loading initial config: loading new config: http app module: start: listening on :80: listen tcp :80: bind: address already in use [root@vultrguest caddy]# caddy reload Caddyfile 2022/12/02 08:11:49.875 INFO using adjacent Caddyfile 2022/12/02 08:11:49.876 WARN Caddyfile input is not formatted; run the 'caddy fmt' command to fix inconsistencies {&quot;adapter&quot;: &quot;caddyfile&quot;, &quot;file&quot;: &quot;Caddyfile&quot;, &quot;line&quot;: 12} Error: sending configuration to instance: performing request: Post &quot;http://localhost:2019/load&quot;: dial tcp [::1]:2019: connect: connection refused [root@vultrguest caddy]# </code></pre> <p>If I run <strong>GET</strong> <code>http://www.thespacebar.io:8080</code> I get:</p> <pre><code>Web server is down Error code 521 Visit cloudflare.com for more information. 2022-12-02 08:22:13 UTC You </code></pre>
[ { "answer_id": 74651021, "author": "Sunil Bojanapally", "author_id": 1079907, "author_profile": "https://Stackoverflow.com/users/1079907", "pm_score": 1, "selected": false, "text": "<PID>" }, { "answer_id": 74651048, "author": "Craig Estey", "author_id": 5382650, "author_profile": "https://Stackoverflow.com/users/5382650", "pm_score": 3, "selected": true, "text": "getrlimit setrlimit fork getrlimit/setrlimit execvp stdin/stdout/stderr #include <stdio.h>\n#include <stdlib.h>\n#include <fcntl.h>\n#include <sys/resource.h>\n\nvoid\nshow(struct rlimit *rlim,const char *who)\n{\n\n printf(\"rlim_cur=%d rlim_max=%d [%s]\\n\",\n rlim->rlim_cur,rlim->rlim_max,who);\n}\n\nint\nmain(int argc,char **argv)\n{\n int err;\n struct rlimit rlim;\n\n --argc;\n ++argv;\n\n setlinebuf(stdout);\n setlinebuf(stderr);\n\n err = getrlimit(RLIMIT_NOFILE,&rlim);\n if (err < 0) {\n perror(\"getrlimit\");\n exit(1);\n }\n\n show(&rlim,\"original\");\n\n if (argc > 0) {\n rlim.rlim_cur = atoi(*argv);\n err = setrlimit(RLIMIT_NOFILE,&rlim);\n\n if (err < 0) {\n perror(\"setrlimit\");\n exit(1);\n }\n\n err = getrlimit(RLIMIT_NOFILE,&rlim);\n if (err < 0) {\n perror(\"setrlimit\");\n exit(1);\n }\n show(&rlim,\"setrlimit\");\n }\n\n int count = 0;\n while (1) {\n int fd = open(\"/dev/null\",O_RDONLY);\n if (fd < 0) {\n perror(\"open\");\n break;\n }\n ++count;\n }\n\n printf(\"max open files: %d\\n\",count);\n\n return 0;\n}\n rlim_cur=1024 rlim_max=4096 [original]\nopen: Too many open files\nmax open files: 1021\n rlim_cur=1024 rlim_max=4096 [original]\nrlim_cur=17 rlim_max=4096 [setrlimit]\nopen: Too many open files\nmax open files: 14\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74650981", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15469002/" ]
74,650,988
<p>I'm using Preact with HTM (no compiler required) and am having trouble looping through an object and creating a DOM element for each item.</p> <p>What is the correct way to procedurally generate DOM elements with Preact + HTM?</p> <pre><code>import { h, Component, render } from 'https://unpkg.com/preact?module'; import htm from 'https://unpkg.com/htm?module'; const html = htm.bind(h); function componentValues() { var elements = {e1:10, e2:20}; var objEditor = '&lt;div class=&quot;row&quot;&gt;'; for (const key in elements) { objEditor += '&lt;div class=&quot;col&quot;&gt;'+key+'&lt;/div&gt;'; } objEditor += '&lt;/div&gt;'; return objEditor; } function renderPage() { render(html` &lt;div class=&quot;container-xl&quot;&gt; &lt;p&gt;Hello World&lt;/p&gt; &lt;${componentValues} /&gt; &lt;/div&gt;`, document.getElementById(&quot;app&quot;)); } renderPage(); </code></pre> <p>My result is this</p> <pre><code>Hello World &lt;div class=&quot;row&quot;&gt;&lt;div class=&quot;col&quot;&gt;e1&lt;/div&gt;&lt;div class=&quot;col&quot;&gt;e2&lt;/div&gt;&lt;/div&gt; </code></pre> <p><a href="https://codepen.io/28raining/pen/WNyaJrL" rel="nofollow noreferrer">https://codepen.io/28raining/pen/WNyaJrL</a></p>
[ { "answer_id": 74651021, "author": "Sunil Bojanapally", "author_id": 1079907, "author_profile": "https://Stackoverflow.com/users/1079907", "pm_score": 1, "selected": false, "text": "<PID>" }, { "answer_id": 74651048, "author": "Craig Estey", "author_id": 5382650, "author_profile": "https://Stackoverflow.com/users/5382650", "pm_score": 3, "selected": true, "text": "getrlimit setrlimit fork getrlimit/setrlimit execvp stdin/stdout/stderr #include <stdio.h>\n#include <stdlib.h>\n#include <fcntl.h>\n#include <sys/resource.h>\n\nvoid\nshow(struct rlimit *rlim,const char *who)\n{\n\n printf(\"rlim_cur=%d rlim_max=%d [%s]\\n\",\n rlim->rlim_cur,rlim->rlim_max,who);\n}\n\nint\nmain(int argc,char **argv)\n{\n int err;\n struct rlimit rlim;\n\n --argc;\n ++argv;\n\n setlinebuf(stdout);\n setlinebuf(stderr);\n\n err = getrlimit(RLIMIT_NOFILE,&rlim);\n if (err < 0) {\n perror(\"getrlimit\");\n exit(1);\n }\n\n show(&rlim,\"original\");\n\n if (argc > 0) {\n rlim.rlim_cur = atoi(*argv);\n err = setrlimit(RLIMIT_NOFILE,&rlim);\n\n if (err < 0) {\n perror(\"setrlimit\");\n exit(1);\n }\n\n err = getrlimit(RLIMIT_NOFILE,&rlim);\n if (err < 0) {\n perror(\"setrlimit\");\n exit(1);\n }\n show(&rlim,\"setrlimit\");\n }\n\n int count = 0;\n while (1) {\n int fd = open(\"/dev/null\",O_RDONLY);\n if (fd < 0) {\n perror(\"open\");\n break;\n }\n ++count;\n }\n\n printf(\"max open files: %d\\n\",count);\n\n return 0;\n}\n rlim_cur=1024 rlim_max=4096 [original]\nopen: Too many open files\nmax open files: 1021\n rlim_cur=1024 rlim_max=4096 [original]\nrlim_cur=17 rlim_max=4096 [setrlimit]\nopen: Too many open files\nmax open files: 14\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74650988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4383497/" ]
74,650,990
<p>Here is the code that I am testing. My string array a showing modified array elements as dogs, cats, turtles.</p> <pre class="lang-java prettyprint-override"><code>String[] a = {&quot;dog&quot;, &quot;cat&quot;, &quot;turtle&quot;}; System.out.println(java.util.Arrays.toString(a));//line int i1= 0; for (String j : a) { a[i1]=j+&quot;s&quot;; if (i1 &lt; 2) { i1++; } System.out.println(i1); System.out.println(a[i1]); } System.out.println(); System.out.println(java.util.Arrays.toString(a));//line </code></pre> <p>output</p> <pre><code>[dog, cat, turtle] [dogs, cats, turtles] </code></pre>
[ { "answer_id": 74651275, "author": "JustMe", "author_id": 14188847, "author_profile": "https://Stackoverflow.com/users/14188847", "pm_score": 1, "selected": false, "text": "a[i1]=j+\"s\";" }, { "answer_id": 74651309, "author": "Samanja Cartagena", "author_id": 18191906, "author_profile": "https://Stackoverflow.com/users/18191906", "pm_score": 0, "selected": false, "text": "String[] a = {\"dog\", \"cat\", \"turtle\"};\nSystem.out.println(java.util.Arrays.toString(a));//line\nint i1= 0;\nfor (String j : a) {\n a[i1]=j;\n if (i1 < 2) {\n i1++;\n }\nSystem.out.println(i1);\nSystem.out.println(a[i1]);\n} \nSystem.out.println();\nSystem.out.println(java.util.Arrays.toString(a));//line\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74650990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19347264/" ]
74,651,000
<p>Consider this function</p> <pre><code>using Distributions using StatsBase test_vector = sample([1,2,3], 100000000) function test_1( test_vector) rand_vector = randn(3333) sum = 0.0 for t in 1:1000 if t in test_vector sum = sum +rand_vector[t] else sum = sum - rand_vector[t] end end end </code></pre> <p>I applied <code>@profview</code> to understand performance and it turns out most of the time is spent on <code>if t in test_vector</code>. Is there a way to speed up this part of the program? I thought about excluding <code>test_vector</code> from <code>1:1000</code> and run two loops, but this creates memory allocation. Can I get a hint?</p> <p>P.S. I intend to let the user pass in any <code>test_vector</code>. I'm using <code>sample</code> to create a <code>test_vector</code> just for illustration.</p>
[ { "answer_id": 74651268, "author": "Oscar Smith", "author_id": 5141328, "author_profile": "https://Stackoverflow.com/users/5141328", "pm_score": 0, "selected": false, "text": "Set O(1)" }, { "answer_id": 74651298, "author": "Bill", "author_id": 4282847, "author_profile": "https://Stackoverflow.com/users/4282847", "pm_score": 3, "selected": true, "text": "using Distributions\nusing StatsBase\nusing BenchmarkTools\n\ntest_vector = sample([1,2,3], 1000000)\n\nfunction test_1(test_vector)\n rand_vector = randn(3333)\n \n sum1 = 0.0\n for t in 1:1000\n if t in test_vector\n sum1 = sum1 + rand_vector[t]\n else \n sum1 = sum1 - rand_vector[t]\n end\n end\n return sum1\nend\n\nfunction test_1_set(test_vector)\nrand_vector = randn(3333)\n\ntest_set = Set(test_vector)\nsum2 = 0.0\nfor t in 1:1000\n if t in test_set\n sum2 += rand_vector[t]\n else \n sum2 -= rand_vector[t]\n end\nend\n return sum2\nend\n\n@btime test_1(test_vector)\n@btime test_1_set(test_vector)\n\n677.818 ms (3 allocations: 26.12 KiB)\n8.795 ms (10 allocations: 18.03 MiB)\n" }, { "answer_id": 74655095, "author": "phipsgabler", "author_id": 1346276, "author_profile": "https://Stackoverflow.com/users/1346276", "pm_score": 1, "selected": false, "text": "julia> test_vector = rand(1:3, 10000);\n\njulia> rand_vector = randn(3333);\n\njulia> range = 1:1000;\n\njulia> @btime test_1($(Set(test_vector)), $rand_vector, $range)\n 3.692 μs (0 allocations: 0 bytes)\n14.82533505498519\n julia> @btime test_1(Set($test_vector), $rand_vector, $range)\n 52.731 μs (7 allocations: 144.59 KiB)\n14.82533505498519\n julia> function test_2(xs, ys, range)\n range = Set(range)\n positive = intersect(range, xs)\n negative = setdiff!(range, positive)\n return sum(ys[i] for i in positive) - sum(ys[i] for i in negative)\n end\ntest_2 (generic function with 1 method)\n\njulia> @btime test_2($test_vector, $rand_vector, $range)\n 96.020 μs (11 allocations: 18.98 KiB)\n14.825335054985187\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1691278/" ]
74,651,030
<p>I have a date pass from Angular frontend to Java backend.</p> <p>The date format I received from frontend is: Wed Mon 26 11:11:59 SGT 2022 and is in Java Date object</p> <p>How can I convert this format to dd/MM/yyyy and the final output should be 26/12/2022 <strong>in Java Date format.</strong></p> <p><strong>Currently my code is like this:</strong></p> <pre><code>SimpleDateFormat sdf = new SimpleDateFormat(&quot;EE MMM dd HH:mm:ss z yyyy&quot;, Locale.ENGLISH); SimpleDateFormat dateFormat = new SimpleDateFormat(&quot;dd/MM/yyyy&quot;); Date formattedDate = dateFormat.parse(sdf.format(dateFromFrontend)); ===&gt; formattedDate to save to DB </code></pre> <p><strong>Parse Exception that I get:</strong></p> <pre><code>java.text.ParseException: Unparseable date: &quot;Mon Dec 26 12:43:19 SGT 2022&quot; </code></pre>
[ { "answer_id": 74651273, "author": "Abra", "author_id": 2164365, "author_profile": "https://Stackoverflow.com/users/2164365", "pm_score": 1, "selected": false, "text": "java.time.format.DateTimeFormatter Locale Exception in thread \"main\" java.time.format.DateTimeParseException: Text 'Wed Dec 26 11:11:59 SGT 2022' could not be parsed: Conflict found: Field DayOfWeek 1 differs from DayOfWeek 3 derived from 2022-12-26\n ZonedDateTime import java.time.ZonedDateTime;\nimport java.time.format.DateTimeFormatter;\nimport java.util.Locale;\n\npublic class Doctor {\n\n public static void main(String[] args) {\n String raw = \"Mon Dec 26 11:11:59 SGT 2022\";\n DateTimeFormatter dtf = DateTimeFormatter.ofPattern(\"EEE MMM dd HH:mm:ss z yyyy\", Locale.ENGLISH);\n ZonedDateTime zdt = ZonedDateTime.parse(raw, dtf);\n System.out.println(zdt);\n }\n}\n 2022-12-26T11:11:59+08:00[Asia/Singapore]\n ZonedDateTime java.sql.Date java.sql.Date d = java.sql.Date.valueOf(zdt.toLocalDate());\n zdt" }, { "answer_id": 74651799, "author": "TANIMUL ISLAM", "author_id": 18262004, "author_profile": "https://Stackoverflow.com/users/18262004", "pm_score": 2, "selected": false, "text": "String LocalDate import java.util.Locale;\nimport java.time.LocalDate;\nimport java.time.format.DateTimeFormatter;\n\npublic class Test {\n\n public static void main(String[] args) {\n String raw = \"Mon Dec 26 11:11:59 SGT 2022\";\n DateTimeFormatter dtf = DateTimeFormatter.ofPattern(\"EEE MMM dd HH:mm:ss z yyyy\", Locale.ENGLISH);\n\n // Your required format\n DateTimeFormatter formatter = DateTimeFormatter.ofPattern(\"d/MM/yyyy\");\n\n LocalDate dateTime = LocalDate.parse(raw, dtf);\n\n System.out.println(formatter.format(dateTime));\n }\n}\n 26/12/2022\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16591189/" ]