qid
int64
4
22.2M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,348,635
<p>My input dataframe looks like this:</p> <pre class="lang-none prettyprint-override"><code>+----------+-------+-------+ | timestamp| weight| id| +----------+-------+-------+ |01-01-2022| 123| abc123| |02-02-2022| 456| def456| |03-03-2022| 789| ghi789| +----------+-------+-------+ </code></pre> <p>The goal is to write this dataframe records into an .json file with the following format</p> <pre class="lang-json prettyprint-override"><code>{&quot;summaries&quot;:[{&quot;id&quot;:&quot;abc123&quot;,&quot;timestamp&quot;:&quot;01-01-2022&quot;,&quot;weight&quot;:123},{&quot;id&quot;:&quot;def456&quot;,&quot;timestamp&quot;:&quot;02-02-2022&quot;,&quot;weight&quot;:456},{&quot;id&quot;:&quot;ghi789&quot;,&quot;timestamp&quot;:&quot;03-03-2022&quot;,&quot;weight&quot;:789}],&quot;status&quot;:200} </code></pre> <p>Therefore I want my dataframe to come out like this in order to write it to the json file:</p> <pre class="lang-none prettyprint-override"><code>+--------------------------------------------------------+-------+ | summaries| status| +--------------------------------------------------------+-------+ |[{&quot;timestamp&quot;:&quot;01-01-2022&quot;, &quot;weight&quot;:123, &quot;id&quot;:&quot;abc123&quot;}, {&quot;timestamp&quot;:&quot;01-01-2022&quot;, &quot;weight&quot;:456, &quot;id&quot;:&quot;def456&quot;}, {&quot;timestamp&quot;:&quot;01-01-2022&quot;, &quot;weight&quot;:789, &quot;id&quot;:&quot;ghi789&quot;}} | 200| +--------------------------------------------------------+--------+ </code></pre> <p>I've created a starting point of my dataframe:</p> <pre class="lang-py prettyprint-override"><code>data = [('01-01-2022', 123, 'abc123'), ('02-02-2022', 456, 'def456'), ('03-03-2022', 789, 'ghi789')] columns = [&quot;timestamp&quot;, &quot;weight&quot;, &quot;id&quot;] df = spark.createDataFrame(data, columns) </code></pre> <p>I have 2 strategies that I tried</p> <p>1.</p> <pre class="lang-py prettyprint-override"><code>dfConvert = (df.withColumn(&quot;summaries&quot;, struct(&quot;timestamp&quot;, &quot;weight&quot;, &quot;id&quot;))) </code></pre> <p>However, from there I have difficulties on how to concatenate the records in one record, and adding the 'status' column.</p> <p>2.</p> <pre class="lang-py prettyprint-override"><code># make rows from the dataframe rows = df.rdd.map(lambda row: row.asDict()).collect()#print(rows) dfConvert = spark.createDataFrame([(rows, &quot;200&quot;)],[&quot;summaries&quot;, &quot;status&quot;]) </code></pre> <p>However, with this strategy I am writing to the memory, which I want to avoid, as later on in the process I will have large data sets and this code is less-performant than the <code>withColumn</code> method.</p> <p><strong>NOTE: The <code>groupBy</code> method won't work, because i will have duplicated records in each of the columns</strong></p> <p>Then the writing is going successfully</p> <pre class="lang-py prettyprint-override"><code>dfConvert.write.format('json').mode(&quot;overwrite&quot;).save(&quot;MyDocuments/write_path&quot;) </code></pre>
[ { "answer_id": 74350390, "author": "Vaebhav", "author_id": 9108912, "author_profile": "https://Stackoverflow.com/users/9108912", "pm_score": 2, "selected": true, "text": "create_map" }, { "answer_id": 74365339, "author": "Meeldurb", "author_id": 7079271, "author_profile": "https://Stackoverflow.com/users/7079271", "pm_score": 0, "selected": false, "text": "data = [('01-01-2022', 123, 'abc123'), ('02-02-2022', 456, 'def456'), ('03-03-2022', 789, 'ghi789')]\ncolumns = [\"timestamp\", \"weight\", \"id\"]\n\ndf = spark.createDataFrame(data, columns)\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74348635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7079271/" ]
74,348,640
<p>I am trying to create this query (to use it as a KPI in the dashboard section) but I am getting the below error <strong>Divide by zero</strong></p> <p>The query that I am using:</p> <pre><code>with cte_ext as ( select count(*) as total_count from snowflake.account_usage.query_history where start_time = :daterange and database_name = :database_name and warehouse_name = :warehouse_name ), cte_conditional as ( select count(*) as &quot;condition_count&quot; from snowflake.account_usage.query_history qh, cte_ext cte where total_elapsed_time &lt; 1000 and start_time = :daterange and database_name = :database_name and warehouse_name = :warehouse_name ) select round((cte_conditional.$1/cte_ext.total_count)*100,2) as &quot;Percentage of queries run under 1s&quot; from cte_conditional, cte_ext </code></pre> <p>Could someone please, advice on how can I resolve this issue?</p> <p>Thank you in advance.</p> <hr /> <p>Once I changed the query taking your advices, I was able to solve the issue and to get the null value.</p> <p>Now I have the below question, is there any chance to replace the null value to some text example like &quot;No queries have been found or executed&quot;?</p>
[ { "answer_id": 74350390, "author": "Vaebhav", "author_id": 9108912, "author_profile": "https://Stackoverflow.com/users/9108912", "pm_score": 2, "selected": true, "text": "create_map" }, { "answer_id": 74365339, "author": "Meeldurb", "author_id": 7079271, "author_profile": "https://Stackoverflow.com/users/7079271", "pm_score": 0, "selected": false, "text": "data = [('01-01-2022', 123, 'abc123'), ('02-02-2022', 456, 'def456'), ('03-03-2022', 789, 'ghi789')]\ncolumns = [\"timestamp\", \"weight\", \"id\"]\n\ndf = spark.createDataFrame(data, columns)\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74348640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20121612/" ]
74,348,644
<p>I was working on a simple portfolio webpage and was making three boxes that includes one image each and some information.</p> <p>The text in each box are aligned in the center but the image sticks on the left side of the box. I'm not sure why the text and the image are not aligned together.</p> <p>here is the code of the three boxes (index.js) :</p> <pre><code>` &lt;div className=&quot;lg:flex gap-10&quot;&gt; &lt;div className=&quot;text-center shadow-lg p-10 rounded-xl my-10 dark:bg-gray-300 flex-1&quot;&gt; &lt;Image src={design} width={100} height={100} /&gt; &lt;h3 className=&quot;text-lg font-medium pt-8 pb-2 &quot;&gt; Tech Stack &lt;/h3&gt; &lt;p className=&quot;py-2&quot;&gt; Tools &lt;/p&gt; &lt;h4 className=&quot;py-4 text-teal-600&quot;&gt;What I Use&lt;/h4&gt; &lt;p className=&quot;text-gray-800 py-1&quot;&gt;HTML 5&lt;/p&gt; &lt;p className=&quot;text-gray-800 py-1&quot;&gt;CSS&lt;/p&gt; &lt;p className=&quot;text-gray-800 py-1&quot;&gt;Javascript&lt;/p&gt; &lt;p className=&quot;text-teal-500 py-1&quot;&gt;etc.&lt;/p&gt; &lt;/div&gt; &lt;div className=&quot;text-center shadow-lg p-10 rounded-xl my-10 dark:bg-gray-300 flex-1&quot;&gt; &lt;Image src={code} width={100} height={100} /&gt; &lt;h3 className=&quot;text-lg font-medium pt-8 pb-2 &quot;&gt; Tech Stack &lt;/h3&gt; &lt;p className=&quot;py-2&quot;&gt; Tools &lt;/p&gt; &lt;h4 className=&quot;py-4 text-teal-600&quot;&gt;What I Use&lt;/h4&gt; &lt;p className=&quot;text-gray-800 py-1&quot;&gt;HTML 5&lt;/p&gt; &lt;p className=&quot;text-gray-800 py-1&quot;&gt;CSS&lt;/p&gt; &lt;p className=&quot;text-gray-800 py-1&quot;&gt;Javascript&lt;/p&gt; &lt;p className=&quot;text-teal-500 py-1&quot;&gt;etc.&lt;/p&gt; &lt;/div&gt; &lt;div className=&quot;text-center shadow-lg p-10 rounded-xl my-10 dark:bg-gray-300 flex-1&quot;&gt; &lt;Image src={consulting} width={100} height={100} /&gt; &lt;h3 className=&quot;text-lg font-medium pt-8 pb-2 &quot;&gt; Tech Stack &lt;/h3&gt; &lt;p className=&quot;py-2&quot;&gt; Tools &lt;/p&gt; &lt;h4 className=&quot;py-4 text-teal-600&quot;&gt;What I Use&lt;/h4&gt; &lt;p className=&quot;text-gray-800 py-1&quot;&gt;HTML 5&lt;/p&gt; &lt;p className=&quot;text-gray-800 py-1&quot;&gt;CSS&lt;/p&gt; &lt;p className=&quot;text-gray-800 py-1&quot;&gt;Javascript&lt;/p&gt; &lt;p className=&quot;text-teal-500 py-1&quot;&gt;etc.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt;` </code></pre> <p>and here is how it looks on the browser:</p> <p><a href="https://i.stack.imgur.com/lJqf8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lJqf8.png" alt="browser capture" /></a></p> <p>The camera, hashtag, and the thumbs-up images are the ones that are not centered..</p> <p>I would appreciate if anyone could tell me where and what I should add on the code.</p> <p>I'm not working on any other css or html file except for the default reactjs.</p> <p>Thank you for any help in advance.</p>
[ { "answer_id": 74348769, "author": "Hein Htet Aung", "author_id": 20441438, "author_profile": "https://Stackoverflow.com/users/20441438", "pm_score": 0, "selected": false, "text": " img {\n display: block;\n margin: auto;\n }\n" }, { "answer_id": 74348851, "author": "Shoaib Amin", "author_id": 19580087, "author_profile": "https://Stackoverflow.com/users/19580087", "pm_score": 2, "selected": true, "text": "<link href=\"https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/1.4.6/tailwind.min.css\" rel=\"stylesheet\" />\n\n<section class=\"hero container max-w-screen-lg mx-auto pb-10\">\n <img class=\"mx-auto\" src=\"//image\" alt=\"screenshot\" >\n</section>\n" }, { "answer_id": 74348878, "author": "Impano Emma", "author_id": 19592598, "author_profile": "https://Stackoverflow.com/users/19592598", "pm_score": 1, "selected": false, "text": "flex" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74348644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19337662/" ]
74,348,691
<p>I'm trying to get the HTML of Billboard's top 100 chart, but I keep getting only about half of the page.</p> <p>I tried getting the page source using this code:</p> <pre><code>from selenium import webdriver from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager s=Service(ChromeDriverManager().install()) driver = webdriver.Chrome(service=s) url = &quot;https://www.billboard.com/charts/hot-100/&quot; driver.get(url) driver.implicitly_wait(10) print(driver.page_source) </code></pre> <p>But it always returns the page source only from the 53rd song on the chart (I've tried increasing the implicit wait and nothing changed)</p>
[ { "answer_id": 74348814, "author": "Prophet", "author_id": 3485434, "author_profile": "https://Stackoverflow.com/users/3485434", "pm_score": 0, "selected": false, "text": "driver.implicitly_wait(10)" }, { "answer_id": 74349152, "author": "KunduK", "author_id": 10885684, "author_profile": "https://Stackoverflow.com/users/10885684", "pm_score": 3, "selected": true, "text": "driver.get('https://www.billboard.com/charts/hot-100/')\nelements=WebDriverWait(driver,10).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, \"ul.lrv-a-unstyle-list h3#title-of-a-story\")))\nprint(len(elements))\nprint([item.text for item in elements])\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74348691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18989951/" ]
74,348,707
<p>I have a Dataframe in python, with the data coming from a csv. In the column &quot;Date&quot; I have a date (:)) but I don't know the date format. How can I detect it?</p> <p>e.g.: I can have 05/05/2022. this can be M/D/Y or D/M/Y. I can manually understand it by looking at other entries, but I wish I can do it automatically.</p> <p>Is there a way to do so? thank you</p> <p>datetime.strptime requires you to know the format. trying (try - exept)-commands isn't good since there are so many different format I can receive.</p> <p>it would be nice to have something that recognizes the format...</p> <p>Update: Thank you for the first answers, but the output I would like to have is THE FORMAT of the date that is used in the column. Knowing also the fact that the format is unique within each column</p>
[ { "answer_id": 74349496, "author": "0x0fba", "author_id": 20339407, "author_profile": "https://Stackoverflow.com/users/20339407", "pm_score": 1, "selected": false, "text": "pytz" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74348707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20441382/" ]
74,348,725
<p>I am in the process of migrating a very large multisite installation to newer OS platforms. Running ClearCase 9. In one particular migration stage all the VOBs appear to have migrated correctly, ct lsvob -s -host xxxx shows no VOBs remaining on the old server, but now I am getting packets stuck in the incoming bin on that old server. I assume it has to do with devs who still had views open before the migration, but the problem is that mt lspacket is complaining that it cannot find a VOB with a single UUID in the registry. Packets are piling up, and they are all complaining about the same UUID, so I assume they are all related to one VOB. ct lsvob -uuid xxxx says it cannot find a VOB with that UUID.</p> <p>How would I go about correcting this?</p>
[ { "answer_id": 74349496, "author": "0x0fba", "author_id": 20339407, "author_profile": "https://Stackoverflow.com/users/20339407", "pm_score": 1, "selected": false, "text": "pytz" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74348725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4196455/" ]
74,348,738
<p>I'm trying to add opacity to my background in CSS, but the navbar is getting the opacity and not the background.</p> <p>I don't know what I'm doing wrong.</p> <p>I tried to change the body tag in CSS, but the navbar is getting the opacity and not the background.</p> <pre class="lang-css prettyprint-override"><code>body { background-image: url(&quot;images/fenerbahce.jpeg&quot;); background-size: cover; opacity: 50% } .navbar { padding: 20px; display: flex; align-items: center; border-bottom: 1px solid #939392; top: 0; background-color: #ccd0d0; } </code></pre>
[ { "answer_id": 74349496, "author": "0x0fba", "author_id": 20339407, "author_profile": "https://Stackoverflow.com/users/20339407", "pm_score": 1, "selected": false, "text": "pytz" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74348738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17716431/" ]
74,348,765
<p>I have a DLL in pure C code. I would like to find a way to remove the library name prefix from the functions, classes, and structs; EX:</p> <pre><code>// lib.h void foobar(); </code></pre> <pre><code>// lib.hpp namespace foo { bar(); } </code></pre> <p>I would like to avoid simply writing a wrapper for every function, since I'd have to write it for every time I want to add a function. Is there a better / more efficient way of writing this?</p> <p>I started writing the wrapper idea, but there's a lot of functions to write this for. Void pointers worked a little better, but still had the same issue.</p>
[ { "answer_id": 74348897, "author": "hyde", "author_id": 1717300, "author_profile": "https://Stackoverflow.com/users/1717300", "pm_score": 1, "selected": false, "text": "// lib.hpp\nnamespace foo {\n constexpr auto bar = foobar;\n}\n" }, { "answer_id": 74349126, "author": "ryyker", "author_id": 645128, "author_profile": "https://Stackoverflow.com/users/645128", "pm_score": 3, "selected": true, "text": "extern \"C\"" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74348765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17895879/" ]
74,348,776
<p>After adding the item to the array.it is not show means not render.</p> <p>i am try myself but no success</p> <p>my code It below you can run it online</p> <pre><code>import React,{useState,useEffect} from 'react'; import { StyleSheet, Text, View,TouchableOpacity,ScrollView} from 'react-native'; export default function App({navigation}) { const [dummyarray, setDummyarray] = useState([{id:1, product:&quot;pendrive&quot;}]); async function addiem(){ dummyarray.push({id:2, product:&quot;mobile phone&quot;}) } return ( &lt;View &gt; &lt;ScrollView&gt; {dummyarray.map((item,idx) =&gt; ( &lt;View key={idx} style={{ backgroundColor: 'white'}}&gt; &lt;Text&gt;{item.product}&lt;/Text&gt; &lt;/View&gt; ))} &lt;TouchableOpacity onPress={()=&gt;addiem()}&gt;&lt;Text&gt;Clear all orders&lt;/Text&gt; &lt;/TouchableOpacity&gt; &lt;/ScrollView&gt; &lt;/View&gt; ); } </code></pre>
[ { "answer_id": 74348855, "author": "Martin Omacht", "author_id": 4551645, "author_profile": "https://Stackoverflow.com/users/4551645", "pm_score": 1, "selected": false, "text": "dummyarray.push(...)" }, { "answer_id": 74348951, "author": "todevv", "author_id": 19099618, "author_profile": "https://Stackoverflow.com/users/19099618", "pm_score": 0, "selected": false, "text": "async function addiem(){\n dummyarray.push({id:2, product:\"mobile phone\"})\n }\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74348776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20424966/" ]
74,348,848
<p>I have a header that works perfectly fine in its own html file and I have a product details page that also is fine on its own. When I add the header to the product page it messes up entirely and pushes the header out of the way, placing part of the product details to the right of the header.</p> <p>I tried using inspect element and found no padding or magins that would be doing this and adding a margin or padding does not fix the issue.</p> <p>I assume it's a problem with the product page as inspect element does highlight that section of the page when I was troubleshooting.</p> <p>Any help would be amazing!</p> <p><strong>some of the product html</strong> (<a href="https://i.stack.imgur.com/tsGDT.png" rel="nofollow noreferrer">https://i.stack.imgur.com/tsGDT.png</a>)](<a href="https://i.stack.imgur.com/tsGDT.png" rel="nofollow noreferrer">https://i.stack.imgur.com/tsGDT.png</a>)</p> <p><strong>PRODUCT HTML:</strong></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>@import url(https://fonts.googleapis.com/css2?family=Rubik:wght@100;200;300;400;500;600;800;900&amp;display=swap); * { margin: 0; padding: 0; font-family: 'Rubik', sans-serif; box-sizing: border-box; } html { scroll-behavior: smooth; } .small-container{ max-width: 1000%; margin: auto; padding-left: 25px; padding-right: 20px; } .row{ display: flex; align-items: center; flex-wrap: wrap; justify-content: space-around; } .single-product{ margin-top: 80px; } .small-img-row{ display: flex; justify-content: space-around; max-width: 300px; max-height: 500px; } .col-2 img { max-width: 100%; /* padding: 0px 0; */ max-width: 300px; max-height: 500px; } .small-img-col{ flex-basis: 24%; cursor: pointer; } .single-product .col-2 img{ padding: 0; } .single-product .col-2{ padding: 20; } .col-2{ flex-basis: 50%; min-width: 300px; } .col-2 h1{ font-size: 50px; line-height: 60px; margin: 5px 0; } .single-product select{ display: block; padding: 10px; margin-top: 20px; } .single-product h4{ margin: 20px 0; font-size: 22px; font-weight: bold; } a{ text-decoration: none; } p{ color: #9ba0a3; margin-top: 10px; } .btn{ display: inline-block; background: #4B7AB4; color: #fff; padding: 8px 30px; margin: 30px 0; border-radius: 30px; transition: background 0.5s; } .btn:hover{ background: #314f74; } .header{ width: 100%; height: 80px; display: block; /* background-color: #101010; */ background-image: linear-gradient(rgba(0, 0, 0, 0.75), rgba(0, 0, 0, 0.75)), url(background-nav.png); background-size: cover; } .inner-header{ width: 1000px; height: 100%; display: block; margin: 0 auto; /* background-color: red; */ } .logo-container{ height: 100%; display: table; float: left; } .logo-container img{ max-width: 60px; max-height: 60px; display: table-cell; padding: 10px; vertical-align: middle; } .navigation{ float: right; height: 100%; } .navigation a{ height: 100%; display: table; float: left; padding: 0px 20px; } .navigation a li{ display: table-cell; vertical-align: middle; height: 100%; color: white; font-family:'Rubik'; font-size: 16px; } .gibsonrating { list-style: none; display: flex; justify-content: left; align-items: center; padding-top: 0; } li { padding-top: 5px; } .fa { font-size: 10px; margin: 1px; color: #939a9e; } .checked { color: #ff9f43; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0" /&gt; &lt;meta charset="utf-8" /&gt; &lt;title&gt;fret - Guitars for the People!&lt;/title&gt; &lt;link rel="stylesheet" type="text/css" href="./gibson.css" /&gt; &lt;link href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet" type='text/css'&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="header"&gt; &lt;div class="inner-header"&gt; &lt;div class="logo-container"&gt; &lt;img src="fretlogo.png"/&gt; &lt;/div&gt; &lt;ul class="navigation"&gt; &lt;a href="index.html"&gt;&lt;li&gt;Home&lt;/li&gt;&lt;/a&gt; &lt;a href="index.html#section-1.5"&gt;&lt;li&gt;Products&lt;/li&gt;&lt;/a&gt; &lt;a href="https://www.youtube.com/watch?v=dQw4w9WgXcQ&amp;ab_channel=RickAstley"&gt;&lt;li&gt;About&lt;/li&gt;&lt;/a&gt; &lt;a href="index.html"&gt;&lt;li&gt;Login&lt;/li&gt;&lt;/a&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="smallcontainer" single-product&gt; &lt;div class="row"&gt; &lt;div class="col-2"&gt; &lt;img src="https://bdbo2.thomann.de/thumb/bdb3000/pics/bdbo/17180483.jpg" width="100%" id="ProductImg"&gt; &lt;div class="small-img-row"&gt; &lt;div class="small-img-col"&gt; &lt;img src="https://bdbo2.thomann.de/thumb/bdb3000/pics/bdbo/17180543.jpg" width="100%" class="small-img"&gt; &lt;/div&gt; &lt;div class="small-img-col"&gt; &lt;img src="https://bdbo2.thomann.de/thumb/bdb3000/pics/bdbo/17180503.jpg" width="100%" class="small-img"&gt; &lt;/div&gt; &lt;div class="small-img-col"&gt; &lt;img src="https://bdbo2.thomann.de/thumb/bdb3000/pics/bdbo/17180483.jpg" width="100%" class="small-img"&gt; &lt;/div&gt; &lt;div class="small-img-col"&gt; &lt;img src="https://bdbo2.thomann.de/thumb/bdb3000/pics/bdbo/17180534.jpg" width="100%" class="small-img"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-2"&gt; &lt;p&gt;Home / Gibson G-200&lt;/p&gt; &lt;h1&gt;Gibson G-200&lt;/h1&gt; &lt;h4&gt;€1,990&lt;/h4&gt; &lt;select&gt; &lt;option&gt;Select Quantity&lt;/option&gt; &lt;option&gt;1&lt;/option&gt; &lt;option&gt;2&lt;/option&gt; &lt;option&gt;3&lt;/option&gt; &lt;option&gt;4&lt;/option&gt; &lt;option&gt;5+&lt;/option&gt; &lt;/select&gt; &lt;ul class="gibsonrating"&gt; &lt;li&gt;&lt;i class="fa fa-star checked"&gt;&lt;/i&gt;&lt;/li&gt; &lt;li&gt;&lt;i class="fa fa-star checked"&gt;&lt;/i&gt;&lt;/li&gt; &lt;li&gt;&lt;i class="fa fa-star checked"&gt;&lt;/i&gt;&lt;/li&gt; &lt;li&gt;&lt;i class="fa fa-star checked"&gt;&lt;/i&gt;&lt;/li&gt; &lt;li&gt;&lt;i class="fa fa-star-half-o checked"&gt;&lt;/i&gt;&lt;/li&gt; &lt;/ul&gt; &lt;a href="" class="btn"&gt; Add to Cart&lt;/a&gt; &lt;h3&gt;Product Details&lt;/h3&gt; &lt;br&gt; &lt;p&gt; &lt;ul&gt; &lt;li&gt;Body Shape: J-200 with cutaway&lt;/li&gt; &lt;li&gt;Top: solid Sitka spruce&lt;/li&gt; &lt;li&gt;Neck: utile&lt;/li&gt; &lt;li&gt;Profile: advanced response&lt;/li&gt; &lt;li&gt;Dovetail neck construction&lt;/li&gt; &lt;li&gt;Fretboard: striped ebony&lt;/li&gt; &lt;li&gt;Fretboard inlays: G-collection single bars&lt;/li&gt; &lt;li&gt;Nut width 43,80 mm (1,725")&lt;/li&gt; &lt;li&gt;Scale: 648 mm (25,5")&lt;/li&gt; &lt;li&gt;Made in Bozeman, USA&lt;/li&gt; &lt;/ul&gt; &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p><strong>PRODUCT CSS:</strong></p> <p><strong>product page on its own</strong> (<a href="https://i.stack.imgur.com/Vnd9J.png" rel="nofollow noreferrer">https://i.stack.imgur.com/Vnd9J.png</a>)](<a href="https://i.stack.imgur.com/Vnd9J.png" rel="nofollow noreferrer">https://i.stack.imgur.com/Vnd9J.png</a>)</p> <p><strong>header on its own</strong> (<a href="https://i.stack.imgur.com/eQE3g.png" rel="nofollow noreferrer">https://i.stack.imgur.com/eQE3g.png</a>)](<a href="https://i.stack.imgur.com/eQE3g.png" rel="nofollow noreferrer">https://i.stack.imgur.com/eQE3g.png</a>)</p> <p><strong>the mix of both the header and the product details</strong> (<a href="https://i.stack.imgur.com/9y2t1.png" rel="nofollow noreferrer">https://i.stack.imgur.com/9y2t1.png</a>)](<a href="https://i.stack.imgur.com/9y2t1.png" rel="nofollow noreferrer">https://i.stack.imgur.com/9y2t1.png</a>)</p> <p>I tried looking for disruptive padding and margins</p> <p>I tried adding padding and margins to the smallcontainer and row in css</p>
[ { "answer_id": 74348855, "author": "Martin Omacht", "author_id": 4551645, "author_profile": "https://Stackoverflow.com/users/4551645", "pm_score": 1, "selected": false, "text": "dummyarray.push(...)" }, { "answer_id": 74348951, "author": "todevv", "author_id": 19099618, "author_profile": "https://Stackoverflow.com/users/19099618", "pm_score": 0, "selected": false, "text": "async function addiem(){\n dummyarray.push({id:2, product:\"mobile phone\"})\n }\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74348848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14571351/" ]
74,348,854
<p>While refactoring my angular application I basically want to get rid of all subscriptions in order to use only <code>async</code> pipe provided by angular (just a declarative approach instead of an imperative one).</p> <p>I have problems to implement a declarative approach when multiple sources can lead to changes in the stream. If we only had one source then of course, I could just use <code>scan</code> operator to build up my emitted values.</p> <p><strong>Scenario</strong></p> <p>Let's say I just want to have a simple component, where an array of strings is resolved during routing. In the component I want to display the list and want to be able to add or remove items using buttons.</p> <p><strong>Limitations</strong></p> <ol> <li>I don't want to use <code>subscribe</code>, since I want angular to take care of unsubscription using (<code>async</code> pipe)</li> <li>I don't want to use BehaviorSubject.value, since it's (from my point of view) an imperative approach instead of a declarative one</li> <li>Actually I don't want to use any kind of subject at all (apart from the ones used for button <code>click</code> event propagation), since I don't think it is necessary. I should already have all needed observables, which just have to be &quot;glued together&quot;.</li> </ol> <p><strong>Current process so far</strong> My journey so far took several steps. Please note that all approaches worked fine, but each has their individual downsights):</p> <ol> <li>Usage of <code>BehaviorSubject</code> and <code>.value</code> to create the new array --&gt; not declarative</li> <li>Trying <code>scan</code> operator and create an <code>Action</code> interface, where each button emits an action of type <code>XY</code>. This action would be read inside the function passed to <code>scan</code> and then use a switch to determine which action to take. This felt a little bit like Redux, but it was a strange feeling to mix different value types in one pipe (first initial array, afterwards actions).</li> <li>My so far favorite approach is the following: I basically mimic a BehaviorSubject by using <code>shareReplay</code> and use this instantly emitted value in my button, by switching to a new observable using <code>concatMap</code>, where I only take 1 value in order to prevent creating a loop. Example implementation mentioned below:</li> </ol> <p>list-view.component.html:</p> <pre><code>&lt;ul&gt; &lt;li *ngFor=&quot;let item of items$ | async; let i = index&quot;&gt; {{ item }} &lt;button (click)=&quot;remove$.next(i)&quot;&gt;remove&lt;/button&gt; &lt;/li&gt; &lt;/ul&gt; &lt;button (click)=&quot;add$.next('test2')&quot;&gt;add&lt;/button&gt; </code></pre> <p>list-view.component.ts</p> <pre><code> // simple subject for propagating clicks to add button, string passed is the new entry in the array add$ = new Subject&lt;string&gt;(); // simple subject for propagating clicks to remove button, number passed represents the index to be removed remove$ = new Subject&lt;number&gt;(); // actual list to display items$: Observable&lt;string[]&gt;; constructor(private readonly _route: ActivatedRoute) { // define observable emitting resolver data (initial data on component load) // merging initial data, data on add and data on remove together and subscribe in order to bring data to Subject this.items$ = merge( this._route.data.pipe(map((items) =&gt; items[ITEMS_KEY])), // define observable for adding items to the array this.add$.pipe( concatMap((added) =&gt; this.items$.pipe( map((list) =&gt; [...list, added]), take(1) ) ) ), // define observable for removing items to the array this.remove$.pipe( concatMap((index) =&gt; this.items$.pipe( map((list) =&gt; [...list.slice(0, index), ...list.slice(index + 1)]), take(1) ) ) ) ).pipe(shareReplay(1)); } </code></pre> <p>Nevertheless I feel like this should be the easiest example possible and my implementation seems to complex for this kind of issue. It would be great if someone could help in finding a solution to this, what should be a simple, problem.</p> <p>You can find a StackBlitz example of my implementation here: <a href="https://stackblitz.com/edit/angular-ivy-yj1efm?file=src/app/list-view/list-view.component.ts" rel="nofollow noreferrer">https://stackblitz.com/edit/angular-ivy-yj1efm?file=src/app/list-view/list-view.component.ts</a></p>
[ { "answer_id": 74349095, "author": "MGX", "author_id": 20059754, "author_profile": "https://Stackoverflow.com/users/20059754", "pm_score": 0, "selected": false, "text": "EventEmitter" }, { "answer_id": 74350868, "author": "BizzyBob", "author_id": 1858357, "author_profile": "https://Stackoverflow.com/users/1858357", "pm_score": 3, "selected": true, "text": "modifications$" }, { "answer_id": 74352727, "author": "Lonli-Lokli", "author_id": 462669, "author_profile": "https://Stackoverflow.com/users/462669", "pm_score": 0, "selected": false, "text": "@Injectable()\nexport class ListViewEffectorService {\n public items$ = createStore<string[]>([]);\n public addItem = createEvent<string>();\n public removeItem = createEvent<number>();\n\n constructor(private readonly _route: ActivatedRoute, private ngZone: NgZone) {\n this.ngZone.run(() => {\n sample({\n clock: fromObservable<string[]>(\n this._route.data.pipe(map((items) => items[ITEMS_KEY] as string[]))\n ), // 1. when happened\n source: this.items$, // 2. take from here\n fn: (currentItems, newItems) => [...currentItems, ...newItems], // 3. convert\n target: this.items$, // 4. and save\n });\n\n sample({\n clock: this.addItem,\n source: this.items$,\n fn: (currentItems, newItem) => [...currentItems, newItem],\n target: this.items$,\n });\n\n sample({\n clock: this.removeItem,\n source: this.items$,\n fn: (currentItems, toRemove) =>\n currentItems.filter((_, idx) => idx !== toRemove),\n target: this.items$,\n });\n });\n }\n}\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74348854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17298437/" ]
74,348,859
<p>Is there a way to bring a database offline in Sybase ASE 16.0?</p> <p>I know a database gets set offline when loading a dump, but that can't be the only way to set a database offline.</p> <p><br>There is also an <a href="https://accounts.sap.com/saml2/idp/sso?SAMLRequest=fZJRT8IwFIX%2FytL3sW6BIA2QIMRIgriw6YNvpbuTJltbe1vUf283UPFBkj7dnHO%2B29NOkbeNYQvvDmoHbx7QRevVjBSUTmjN6308ouImTgGqeDKuRjGkwEfjbAg1H5PoGSxKrWYkG1ASrRE9rBU6rlwY0SyL0zSm4zIdsXCGkxcSrQJBKu5618E5gyxJuBDaK4cD5GYgdJt0W2WJrEyCqEl0p62AfscZqXmD0LFyjiiP8DNZIILtcpdaoW%2FBFmCPUsDTbvNL8kHDjQkkb4y27oJozlQ0YR9MKE1JlFvttNDNrVSVVK8z4q1imqNEpngLyJxgxeJhw8L92f4kQnZflnmcPxYliT7aRiHrS75uNmcSmU87Neu7tBf%2B63b%2BfXkyX%2BR5sdxsS0qzaXKRdQo2bBvM61WuGyk%2Bu2Zb7v7PTgdpP5FVXPdS5hUaELKWUIXOm0a%2FLy1wF97BWQ8kmZ%2Bgf%2F%2FU%2FAs%3D&amp;RelayState=oucqqzqfafbovqcyoreedozxdvoereavxsuefax&amp;SigAlg=http%3A%2F%2Fwww.w3.org%2F2001%2F04%2Fxmldsig-more%23rsa-sha256&amp;Signature=CfEuIrM8lSkX5YeL25cK82bwyNtkPGK1Ow%2FHBxr7DGQBTtWjT7ryb9WaGyFKlEXmeIEOIBCSpw6CJTzesgtv2GO%2BdSBpPAJcMad6JUHag5p6PbjfsSS78oVQUXk8xtAwQcv5s1uf7n%2BBDv0tSRxqx8i6hGYGoY4xXmxYJccN188%3D" rel="nofollow noreferrer">official article</a> for that, but it's locked behind a PayWall...</p>
[ { "answer_id": 74351695, "author": "markp-fuso", "author_id": 7366100, "author_profile": "https://Stackoverflow.com/users/7366100", "pm_score": 0, "selected": false, "text": "dbcc dbreboot('shutdown',<dbname1>[,<dbname2>, ...,<dbnameN>])\n" }, { "answer_id": 74412766, "author": "access_granted", "author_id": 5812981, "author_profile": "https://Stackoverflow.com/users/5812981", "pm_score": 2, "selected": true, "text": "sp_configure 'allow updates',1\ngo\n\nreconfigure with override\ngo\n\nupdate master..sysdatabases \nset status=512 \nwhere name='<database of interest>'\ngo\n\nsp_configure 'allow updates',0\ngo\n\nreconfigure with override\ngo\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74348859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19745277/" ]
74,348,870
<p>Created empty project of nuxt 3.0.0-rc13 using <code>pnpm dlx nuxi init nuxt-app</code>, dependencies installed using <code>pnpm install --shamefully-hoist</code>.</p> <p>Deployment server started using <code>pnpm dev</code> but requests end with 500. Error says <code>request to http://localhost:3000/__nuxt_vite_node__/manifest failed, reason: connect ETIMEDOUT 127.0.0.1:3000 ()</code>.</p> <p>According to <a href="https://v3.nuxtjs.org/api/commands/dev/#nuxi-dev" rel="nofollow noreferrer">documentation</a> there is need to set <code>NODE_TLS_REJECT_UNAUTHORIZED=0</code> in the environment if machine is using a self-signed certificate in development.</p> <p>How do I verify such a thing?<br /> Could that be the solution to the error above?</p>
[ { "answer_id": 74352235, "author": "kissu", "author_id": 8816585, "author_profile": "https://Stackoverflow.com/users/8816585", "pm_score": 2, "selected": true, "text": "v16.18.0" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74348870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5941712/" ]
74,348,874
<p>So I have an array of images, which I would like to hide or show on a click of a button. right now when I try to hide the image, it will hide the entire array.</p> <pre><code> import &quot;./main.css&quot;; import { FontAwesomeIcon } from &quot;@fortawesome/react-fontawesome&quot;; import React, { useEffect, useState } from &quot;react&quot;; import { faCircleChevronLeft, faCircleChevronRight, faCircleXmark, } from &quot;@fortawesome/free-solid-svg-icons&quot;; const Main = ({ galleryImages }) =&gt; { const [slideNumber, setSlideNumber] = useState(0); const [openModal, setOpenModal] = useState(false); const [pics, setPics] = useState([]); const [show, toggleShow] = useState(true); // buttons next to name of diff charts (hide/show chart) const handleOpenModal = (index) =&gt; { setSlideNumber(index); setOpenModal(true); }; const removeImage = (id) =&gt; { setPics((oldState) =&gt; oldState.filter((item) =&gt; item.id !== id)); }; // const hide = () =&gt; { // setShow(false) // } const handleCloseModal = () =&gt; { setOpenModal(false) } useEffect(()=&gt; { setPics(galleryImages) },[]); return ( &lt;div&gt; &lt;button onClick={() =&gt; toggleShow(!show)}&gt;toggle: {show ? 'show' : 'hide'}&lt;/button&gt; {show &amp;&amp; &lt;div&gt; {pics.map((pic) =&gt; { return ( &lt;div style = {{marginBottom:'100px'}}&gt; {pic.id} &lt;img src={pic.img} width='500px' height='500px' /&gt; &lt;button onClick ={() =&gt; removeImage(pic.id)}&gt;Delete&lt;/button&gt; &lt;/div&gt; ) })} &lt;/div&gt; </code></pre> <p>I tried making a state component to try to hide and show the images, however it will hide the entire array instead of the individual image</p>
[ { "answer_id": 74352235, "author": "kissu", "author_id": 8816585, "author_profile": "https://Stackoverflow.com/users/8816585", "pm_score": 2, "selected": true, "text": "v16.18.0" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74348874", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18474470/" ]
74,348,887
<p>I have two array of objects with no common properties:</p> <pre><code>let a = [ {id: 1}, {id: 2}, {id: 3}, ]; let b = [ {day: 12}, {day: 15} ]; </code></pre> <p>I want to merge the props of <code>b</code> into <code>a</code>. Initially, I tried</p> <pre><code>let m = a.map((i,x) =&gt; ({id: i.id, day: b[x].day})); </code></pre> <p>This worked just fine as long as the lengths of both the arrays were the same. But when <code>b</code> was shorter or <code>a</code> was shorter, that would result in an error</p> <pre><code>Uncaught TypeError: Cannot read properties of undefined (reading 'day') </code></pre> <p>I don't really care about the length of <code>b</code>, all I want is a, and if b has an element at the same index, I want that b.day.</p> <p>I ended up doing this:</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>let a = [ {id: 1}, {id: 2}, {id: 3}, ]; let b = [ {day: 12}, {day: 15} ]; let m = []; a.forEach((i, x) =&gt; { let item = { id: i.id }; if (b.length &gt; x) { item['day'] = b[x].day; } m.push(item); }); console.log(m);</code></pre> </div> </div> </p> <p>This works fine, but it is decidedly uncool. I know this is probably more readable, but, go with me on this one. Is there a way to make this more ES6 friendly? Is there a shorter / more concise way of achieving this please?</p>
[ { "answer_id": 74348958, "author": "Nina Scholz", "author_id": 1447675, "author_profile": "https://Stackoverflow.com/users/1447675", "pm_score": 3, "selected": true, "text": "undefined" }, { "answer_id": 74348975, "author": "Nitheesh", "author_id": 6099327, "author_profile": "https://Stackoverflow.com/users/6099327", "pm_score": 1, "selected": false, "text": "a" }, { "answer_id": 74349069, "author": "Azzam Michel", "author_id": 14568922, "author_profile": "https://Stackoverflow.com/users/14568922", "pm_score": 2, "selected": false, "text": " let a = [{ id: 1 }, { id: 2 }, { id: 3 }];\n\n let b = [{ day: 12 }, { day: 15 }];\n\n let m = [];\n\n //merge a and b together in m\n m = a.map((item, index) => (b[index] ? { ...item, ...b[index] } : item));\n \n console.log(m);\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74348887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/435867/" ]
74,348,933
<p>I have a data frame</p> <pre><code>df&lt;-data.frame(id=rep(1:10,each=10), Room1=rnorm(100,0.4,0.5), Room2=rnorm(100,0.3,0.5), Room3=rnorm(100,0.7,0.5)) </code></pre> <p>I want to mutate Room1 column by group (those in id = 10) using case_when:</p> <pre><code>data &lt;- df %&gt;% mutate(Room1 = case_when( id==10 ~ 0.6, TRUE ~ as.numeric(Room1) )) </code></pre> <p>But only for 20% of the rows for id=10. The 20% should be randomly assigned. Can anyone help? Thanks in advance</p>
[ { "answer_id": 74349091, "author": "zephryl", "author_id": 17303805, "author_profile": "https://Stackoverflow.com/users/17303805", "pm_score": 3, "selected": true, "text": "id" }, { "answer_id": 74349213, "author": "Darren Tsai", "author_id": 10068985, "author_profile": "https://Stackoverflow.com/users/10068985", "pm_score": 1, "selected": false, "text": "dplyr" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74348933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11261595/" ]
74,348,938
<p>Let's take a sample dataframe :</p> <pre><code>df = pd.DataFrame({&quot;Date&quot;: [&quot;2022-10-01&quot;,&quot;2022-10-02&quot;,&quot;2022-10-03&quot;,&quot;2022-10-04&quot;,&quot;2022-10-05&quot;,&quot;2022-10-06&quot;,&quot;2022-10-01&quot;,&quot;2022-10-02&quot;,&quot;2022-10-03&quot;,&quot;2022-10-04&quot;,&quot;2022-10-05&quot;,&quot;2022-10-06&quot;], &quot;Animal&quot; :[&quot;Cat&quot;,&quot;Cat&quot;,&quot;Cat&quot;,&quot;Cat&quot;,&quot;Cat&quot;,&quot;Cat&quot;,&quot;Dog&quot;,&quot;Dog&quot;,&quot;Dog&quot;,&quot;Dog&quot;,&quot;Dog&quot;,&quot;Dog&quot;], &quot;Quantity&quot;:[np.nan,4,3,5,1,np.nan,6,5,np.nan,np.nan,2,1]}) Date Animal Quantity 0 2022-10-01 Cat NaN 1 2022-10-02 Cat 4.0 2 2022-10-03 Cat 3.0 3 2022-10-04 Cat 5.0 4 2022-10-05 Cat 1.0 5 2022-10-06 Cat NaN 6 2022-10-01 Dog 6.0 7 2022-10-02 Dog 5.0 8 2022-10-03 Dog NaN 9 2022-10-04 Dog NaN 10 2022-10-05 Dog 2.0 11 2022-10-06 Dog 1.0 </code></pre> <p>I would like to fill the NaN values in the column <code>Quantity</code> using the following method :</p> <ul> <li>Replace the NaN values with the closest value that is <strong>before</strong> the NaN value and which share the same value in <code>Animal</code> column</li> <li>If there is still some NaN values, replace the remaining NaN values with the closest value that is <strong>after</strong> the Nan value and which share the same value in <code>Animal</code> column</li> </ul> <p>I thought to <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.interpolate.html" rel="nofollow noreferrer">Series.interpolate</a> but I don't know how to deal with the <code>Animal</code> column. Would you please know an efficient way to reach the expected output ?</p> <p>Expected output :</p> <pre><code> Date Animal Quantity 0 2022-10-01 Cat 4 1 2022-10-02 Cat 4 2 2022-10-03 Cat 3 3 2022-10-04 Cat 5 4 2022-10-05 Cat 1 5 2022-10-06 Cat 1 6 2022-10-01 Dog 6 7 2022-10-02 Dog 5 8 2022-10-03 Dog 5 9 2022-10-04 Dog 5 10 2022-10-05 Dog 2 11 2022-10-06 Dog 1 `` </code></pre>
[ { "answer_id": 74348999, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "ffill" }, { "answer_id": 74349158, "author": "Bhargav", "author_id": 15358800, "author_profile": "https://Stackoverflow.com/users/15358800", "pm_score": 0, "selected": false, "text": "@mozway" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74348938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12292032/" ]
74,348,945
<p>I am trying to make inventory functionality using Discord.js and struggling on how to push an item to the array inside JSON Object. Inside the JSON, every user with unique 'userID' has their own array 'inventory'.</p> <p>The thing I want to achieve is: After user types 'get' command in the chat, the item is pushed to the inventory array and the JSON file is updated.</p> <p><strong>.json file:</strong></p> <pre class="lang-json prettyprint-override"><code>{ &quot;userID&quot;: { &quot;inventory&quot;: [] } } </code></pre> <p><strong>.js file:</strong></p> <pre class="lang-js prettyprint-override"><code>const item = itemName inventory[userID] = { inventory: inventory[userID].inventory + item, } fs.writeFile('./data/inventory.json', JSON.stringify(inventory), err =&gt; { if (err) console.log(err) }) </code></pre> <p><strong>Output (after using command twice):</strong></p> <pre class="lang-json prettyprint-override"><code>{ &quot;userID&quot;: { &quot;inventory&quot;: [&quot;itemNameitemName&quot;] } } </code></pre> <p><strong>Expected output (after using command twice):</strong></p> <pre class="lang-json prettyprint-override"><code>{ &quot;userID&quot;: { &quot;inventory&quot;: [&quot;itemName&quot;, &quot;itemName&quot;] } } </code></pre> <p>The thing I want to achieve is: After user types 'get' command in the chat, the item is pushed to the inventory array and the JSON file is updated. I suppose I need to use <code>.push()</code> somewhere, but I tried it million times in all configurations I could think of and it always throws an error, that <code>.push()</code> is not a function.</p>
[ { "answer_id": 74349270, "author": "Caladan", "author_id": 17641423, "author_profile": "https://Stackoverflow.com/users/17641423", "pm_score": 2, "selected": true, "text": "const inventory = {\n \"userID\": {\n \"inventory\": [\"testOne\"]\n }\n}\n\nconst item = \"test\"\nconst userID = \"userID\"\n\ninventory[userID] = {\n inventory: inventory[userID].inventory.push(item),\n}\nconsole.log(inventory)" }, { "answer_id": 74349342, "author": "sachin", "author_id": 12681984, "author_profile": "https://Stackoverflow.com/users/12681984", "pm_score": 0, "selected": false, "text": "let rawdata = fs.readFileSync('inventory.json');\nlet inventory = JSON.parse(rawdata);\ninventory[\"userID\"] = {\n inventory: [...inventory[\"userID\"].inventory, item],\n}\nfs.writeFile('./inventory.json', JSON.stringify(inventory), err => {\n if (err) console.log(err)\n})\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74348945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17525276/" ]
74,348,990
<p>I have a table that contains the columns name age and Dept. I am new to report builder and wanted to know if there is a way possible to create dynamic tables based on distinct departments in the base table</p> <p>Below is the base data</p> <p><a href="https://i.stack.imgur.com/nGn6o.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nGn6o.png" alt="enter image description here" /></a></p> <p>and this is how I want this to be represented in SSRS dynamically based on distinct items in the Dept. column</p> <p><a href="https://i.stack.imgur.com/8B6lb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8B6lb.png" alt="enter image description here" /></a></p> <p>Thanks in advance!</p>
[ { "answer_id": 74349270, "author": "Caladan", "author_id": 17641423, "author_profile": "https://Stackoverflow.com/users/17641423", "pm_score": 2, "selected": true, "text": "const inventory = {\n \"userID\": {\n \"inventory\": [\"testOne\"]\n }\n}\n\nconst item = \"test\"\nconst userID = \"userID\"\n\ninventory[userID] = {\n inventory: inventory[userID].inventory.push(item),\n}\nconsole.log(inventory)" }, { "answer_id": 74349342, "author": "sachin", "author_id": 12681984, "author_profile": "https://Stackoverflow.com/users/12681984", "pm_score": 0, "selected": false, "text": "let rawdata = fs.readFileSync('inventory.json');\nlet inventory = JSON.parse(rawdata);\ninventory[\"userID\"] = {\n inventory: [...inventory[\"userID\"].inventory, item],\n}\nfs.writeFile('./inventory.json', JSON.stringify(inventory), err => {\n if (err) console.log(err)\n})\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74348990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16144034/" ]
74,349,047
<p>I can't write to firestore. It's working for Storage and Realtime Database, but not for firestore, can you suggest where the issue might be?</p> <p><strong>firebase.js</strong></p> <pre><code>import { getFirestore } from &quot;firebase/firestore&quot;; const firebaseConfig = { ... }; // Initialize Firebase const app = initializeApp(firebaseConfig); export const firestore = getFirestore(app); </code></pre> <p><strong>CheckoutForm.js</strong></p> <pre><code>import { collection, addDoc } from &quot;firebase/firestore&quot;; import { firestore } from &quot;../../firebase&quot;; export const CheckoutForm = async (uid) =&gt; { console.log(&quot;object 1&quot;) try { const docRef = await addDoc(collection(firestore, &quot;documents&quot;), { first: &quot;Ada&quot;, last: &quot;Lovelace&quot;, born: 1815 }); console.log(&quot;Document written with ID: &quot;, docRef.id); } catch (e) { console.error(&quot;Error adding document: &quot;, e); } console.log(&quot;object 2&quot;) } </code></pre> <p>Here I call CheckoutForm. <strong>Home.js</strong></p> <pre><code>import { loadStripe } from &quot;@stripe/stripe-js&quot;; import { Elements } from &quot;@stripe/react-stripe-js&quot; const PUBLIC_KEY = &quot;pkey_test_stripe&quot; const stripeTestPromise = loadStripe(PUBLIC_KEY); export default function Home() { return ( &lt;Elements stripe={stripeTestPromise}&gt; &lt;div&gt; &lt;button onClick={() =&gt; CheckoutForm(currUser.uid)}&gt; Upgrade to premium! &lt;/button&gt; &lt;/div&gt; &lt;/Elements&gt; ); } </code></pre> <p>For some reason I don't get any response or error. Console written &quot;object1&quot;, but after try/catch construction nothing runs.</p>
[ { "answer_id": 74352428, "author": "Christian Paul Andaya", "author_id": 19229284, "author_profile": "https://Stackoverflow.com/users/19229284", "pm_score": 0, "selected": false, "text": "export const CheckoutForm = async (uid) => {\n console.log(\"object 1\")\n try {\n const docRef = await addDoc(collection(firestore, \"documents\"), {\n first: \"Ada\",\n last: \"Lovelace\",\n born: 1815\n });\n console.log(\"Document written with ID: \", docRef.id);\n } catch (e) {\n console.error(\"Error adding document: \", e);\n }\n console.log(\"object 2\")\n }\nawait CheckoutForm();\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19277463/" ]
74,349,104
<pre><code>data = [['Tom', '5-123g'], ['Max', '6-745.0d'], ['Bob', '5-900.0e'], ['Ben', '2-345',], ['Eva', '9-712.x']] df = pd.DataFrame(data, columns=['Person', 'Action']) </code></pre> <p>I want to shorten the &quot;Action&quot; column to a length of 5. My current df has two columns:</p> <pre><code>['Person'] and ['Action'] </code></pre> <p>I need it to look like this:</p> <pre><code> person Action Action_short 0 Tom 5-123g 5-123 1 Max 6-745.0d 6-745 2 Bob 5-900.0e 5-900 3 Ben 2-345 2-345 4 Eva 9-712.x 9-712 </code></pre> <p>What I´ve tried was: Checking the type of the Column</p> <pre><code>df['Action'].dtypes </code></pre> <p>The output is: <code>dtype('0')</code> Then I tried:</p> <pre><code>df['Action'] = df['Action'].map(str) df['Action_short'] = df.Action.str.slice(start=0, stop=5) </code></pre> <p>I also tried it with:</p> <pre><code>df['Action'] = df['Action'].astype(str) df['Action'] = df['Action'].values.astype(str) df['Action'] = df['Action'].map(str) df['Action'] = df['Action'].apply(str)``` </code></pre> <p>and with:</p> <pre><code>df['Action_short'] = df.Action.str.slice(0:5) df['Action_short'] = df.Action.apply(lambda x: x[:5]) df['pos'] = df['Action'].str.find('.') df['new_var'] = df.apply(lambda x: x['Action'][0:x['pos']],axis=1) </code></pre> <p>The output from all my versions was:</p> <pre><code> person Action Action_short 0 Tom 5-123g 5-12 1 Max 6-745.0d 6-745 2 Bob 5-900.0e 5-90 3 Ben 2-345 2-34 4 Eva 9-712.x 9-712 </code></pre> <p>The lambda funktion is not working with <code>3-222</code> it sclices it to <code>3-22</code></p> <p>I don't get it why it is working for some parts and for others not.</p>
[ { "answer_id": 74352428, "author": "Christian Paul Andaya", "author_id": 19229284, "author_profile": "https://Stackoverflow.com/users/19229284", "pm_score": 0, "selected": false, "text": "export const CheckoutForm = async (uid) => {\n console.log(\"object 1\")\n try {\n const docRef = await addDoc(collection(firestore, \"documents\"), {\n first: \"Ada\",\n last: \"Lovelace\",\n born: 1815\n });\n console.log(\"Document written with ID: \", docRef.id);\n } catch (e) {\n console.error(\"Error adding document: \", e);\n }\n console.log(\"object 2\")\n }\nawait CheckoutForm();\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19526103/" ]
74,349,107
<p>I've been trying to create a simple component with a styled checkbox and a corresponding label. The values (strings) of all selected checkboxes should be stored in an array. This works well with plain html checkboxes:</p> <pre><code> &lt;template&gt; &lt;div&gt; &lt;div class=&quot;mt-6&quot;&gt; &lt;div&gt; &lt;input type=&quot;checkbox&quot; value=&quot;EVO&quot; v-model=&quot;status&quot; /&gt; &lt;label for=&quot;EVO&quot;&gt;EVO&lt;/label&gt; &lt;/div&gt; &lt;div&gt; &lt;input type=&quot;checkbox&quot; value=&quot;Solist&quot; v-model=&quot;status&quot; /&gt; &lt;label for=&quot;Solist&quot;&gt;Solist&lt;/label&gt; &lt;/div&gt; &lt;div&gt; &lt;input type=&quot;checkbox&quot; value=&quot;SPL&quot; v-model=&quot;status&quot; /&gt; &lt;label for=&quot;SPL&quot;&gt;SPL&lt;/label&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;mt-3&quot;&gt;{{status}}&lt;/div&gt; &lt;/div&gt; &lt;/template&gt; &lt;script setup&gt; import { ref } from 'vue' let status = ref([]); &lt;/script&gt; </code></pre> <p>It results in the following, desired situation:</p> <p><a href="https://i.stack.imgur.com/Db9j0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Db9j0.png" alt="Expected result with native checkboxes" /></a></p> <p>Now if I replace those checkboxes with my custom checkbox component, I can't get it to work. If I check a box, it's emitted value seems to replace the <code>status</code> array instead of it being added to or removed from it, resulting in the following:</p> <p><a href="https://i.stack.imgur.com/xj5kn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xj5kn.png" alt="enter image description here" /></a></p> <p>So all checkboxes are checked by default for some reason, when I click on one of them they all get unchecked and the <code>status</code> value goes to <code>false</code> and clicking any of the checkboxes again will check them all and make <code>status</code> <code>true</code>.</p> <p>Now I get that returning whether the box is checked or not in the emit returns a true or false value, but I don't get how Vue does this with native checkboxes and how to implement this behaviour with my component.</p> <p>Here's the code of my checkbox component:</p> <pre><code>&lt;template&gt; &lt;div class=&quot;mt-1 relative&quot;&gt; &lt;input type=&quot;checkbox&quot; :id=&quot;id ?? null&quot; :name=&quot;name&quot; :value=&quot;value&quot; :checked=&quot;modelValue ?? false&quot; class=&quot;bg-gray-200 text-gold-500 rounded border-0 w-5 h-5 mr-2 focus:ring-2 focus:ring-gold-500&quot; @input=&quot;updateValue&quot; /&gt; {{ label }} &lt;/div&gt; &lt;/template&gt; &lt;script setup&gt; const props = defineProps({ id: String, label: String, name: String, value: String, errors: Object, modelValue: Boolean, }) const emit = defineEmits(['update:modelValue']) const updateValue = function(event) { emit('update:modelValue', event.target.checked) } &lt;/script&gt; </code></pre> <p>And the parent component only uses a different template:</p> <pre><code>&lt;template&gt; &lt;div&gt; &lt;div class=&quot;mt-6&quot;&gt; &lt;Checkbox v-model=&quot;status&quot; value=&quot;EVO&quot; label=&quot;EVO&quot; name=&quot;status&quot; /&gt; &lt;Checkbox v-model=&quot;status&quot; value=&quot;Solist&quot; label=&quot;Solist&quot; name=&quot;status&quot; /&gt; &lt;Checkbox v-model=&quot;status&quot; value=&quot;SPL&quot; label=&quot;SPL&quot; name=&quot;status&quot; /&gt; &lt;/div&gt; &lt;div class=&quot;mt-3&quot;&gt;{{status}}&lt;/div&gt; &lt;/div&gt; &lt;/template&gt; </code></pre> <p>I've tried to look at <a href="https://stackoverflow.com/a/69480674/1973005">this answer from StevenSiebert</a>, but it uses an object and I want to replicate the original Vue behaviour with native checkboxes.</p> <p>I've also referred the <a href="https://stackoverflow.com/a/69480674/1973005">official Vue docs on <code>v-model</code></a>, but can't see why this would work different with native checkboxes than with components.</p>
[ { "answer_id": 74349381, "author": "Nikola Pavicevic", "author_id": 11989189, "author_profile": "https://Stackoverflow.com/users/11989189", "pm_score": 2, "selected": false, "text": "const { ref } = Vue\nconst app = Vue.createApp({\n setup() {\n const status = ref([{label: 'EVO', status: false}, {label: 'Solist', status: false}, {label: 'SPL', status: false}])\n return {\n status\n }\n },\n})\napp.component('Checkbox', {\n template: `\n <div class=\"mt-1 relative\">\n <input\n type=\"checkbox\"\n :id=\"id ?? null\"\n :name=\"name\"\n :value=\"value\"\n :checked=\"modelValue ?? false\"\n class=\"bg-gray-200 text-gold-500 rounded border-0 w-5 h-5 mr-2 focus:ring-2 focus:ring-gold-500\"\n @input=\"updateValue\"\n />\n {{ label }}\n </div>\n `,\n props:{\n id: String,\n label: String,\n name: String,\n value: String,\n errors: Object,\n modelValue: Boolean,\n },\n setup(props, {emit}) {\n const updateValue = function(event) {\n emit('update:modelValue', event.target.checked)\n }\n return {\n updateValue\n }\n }\n})\napp.mount('#demo')" }, { "answer_id": 74373768, "author": "Axel Köhler", "author_id": 1973005, "author_profile": "https://Stackoverflow.com/users/1973005", "pm_score": 0, "selected": false, "text": "v-model" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1973005/" ]
74,349,110
<p><a href="https://permalink.geldersarchief.nl/8A0A3B746F8147888ADF8FCA559F119B" rel="nofollow noreferrer">https://permalink.geldersarchief.nl/8A0A3B746F8147888ADF8FCA559F119B</a></p> <p>this archive has 500 images i want to download and perform OCR on. I have already found this code online that downloads some images, but it doesn't find the 500 images of the book that i want for some reason. what should i add to the code? thanks in advance.</p> <pre><code>from bs4 import * import requests import os # CREATE FOLDER def folder_create(images): try: folder_name = input(&quot;Enter Folder Name:- &quot;) # folder creation os.mkdir(folder_name) # if folder exists with that name, ask another name except: print(&quot;Folder Exist with that name!&quot;) folder_create() # image downloading start download_images(images, folder_name) # DOWNLOAD ALL IMAGES FROM THAT URL def download_images(images, folder_name): # initial count is zero count = 0 # print total images found in URL print(f&quot;Total {len(images)} Image Found!&quot;) # checking if images is not zero if len(images) != 0: for i, image in enumerate(images): # From image tag ,Fetch image Source URL # 1.data-srcset # 2.data-src # 3.data-fallback-src # 4.src # Here we will use exception handling # first we will search for &quot;data-srcset&quot; in img tag try: # In image tag ,searching for &quot;data-srcset&quot; image_link = image[&quot;data-srcset&quot;] # then we will search for &quot;data-src&quot; in img # tag and so on.. except: try: # In image tag ,searching for &quot;data-src&quot; image_link = image[&quot;data-src&quot;] except: try: # In image tag ,searching for &quot;data-fallback-src&quot; image_link = image[&quot;data-fallback-src&quot;] except: try: # In image tag ,searching for &quot;src&quot; image_link = image[&quot;src&quot;] # if no Source URL found except: pass # After getting Image Source URL # We will try to get the content of image try: r = requests.get(image_link).content try: # possibility of decode r = str(r, 'utf-8') except UnicodeDecodeError: # After checking above condition, Image Download start with open(f&quot;{folder_name}/images{i + 1}.jpg&quot;, &quot;wb+&quot;) as f: f.write(r) # counting number of image downloaded count += 1 except: pass # There might be possible, that all # images not download # if all images download if count == len(images): print(&quot;All Images Downloaded!&quot;) # if all images not download else: print(f&quot;Total {count} Images Downloaded Out of {len(images)}&quot;) # MAIN FUNCTION START def main(url): # content of URL r = requests.get(url) # Parse HTML Code soup = BeautifulSoup(r.text, 'html.parser') # find all images in URL images = soup.findAll('img') # Call folder create function folder_create(images) # take url url = input(&quot;Enter URL:- &quot;) # CALL MAIN FUNCTION main(url) </code></pre> <p>I ran the code on the given url, it said it found 52 images but only downloaded 2. (likely encoding issue). i was expecting it to download all 500 images that are in there.</p>
[ { "answer_id": 74349381, "author": "Nikola Pavicevic", "author_id": 11989189, "author_profile": "https://Stackoverflow.com/users/11989189", "pm_score": 2, "selected": false, "text": "const { ref } = Vue\nconst app = Vue.createApp({\n setup() {\n const status = ref([{label: 'EVO', status: false}, {label: 'Solist', status: false}, {label: 'SPL', status: false}])\n return {\n status\n }\n },\n})\napp.component('Checkbox', {\n template: `\n <div class=\"mt-1 relative\">\n <input\n type=\"checkbox\"\n :id=\"id ?? null\"\n :name=\"name\"\n :value=\"value\"\n :checked=\"modelValue ?? false\"\n class=\"bg-gray-200 text-gold-500 rounded border-0 w-5 h-5 mr-2 focus:ring-2 focus:ring-gold-500\"\n @input=\"updateValue\"\n />\n {{ label }}\n </div>\n `,\n props:{\n id: String,\n label: String,\n name: String,\n value: String,\n errors: Object,\n modelValue: Boolean,\n },\n setup(props, {emit}) {\n const updateValue = function(event) {\n emit('update:modelValue', event.target.checked)\n }\n return {\n updateValue\n }\n }\n})\napp.mount('#demo')" }, { "answer_id": 74373768, "author": "Axel Köhler", "author_id": 1973005, "author_profile": "https://Stackoverflow.com/users/1973005", "pm_score": 0, "selected": false, "text": "v-model" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20441625/" ]
74,349,111
<p>i want to handle the probable errors of <code>mysql db</code>. in my case, i have <code>users</code> table that has 7 columns. column <code>email</code> and <code>username</code> values should be unique and i set that for them. but in my sign up form, when users enter and submit their account infos, their entered username and email can be in the database. so in this case, <code>mysql</code> throws an error. for example in my database there is a row with <code>test@test.com</code> email and <code>saman138</code> username. if a user enters <code>test@test.com</code> for email and <code>saman138</code> for username, mysql throws an error like this:</p> <blockquote> <p>Duplicate entry 'saman138' for key 'users.username_UNIQUE'</p> </blockquote> <p>But the main problem is that i cant display the right error to user. I actually dont know how to do that in the best with the highest performance. For example how can i recognize that the users entered password is duplicated in the database and display the right error to user? I can send two extra queries to get the row that has the entered email or password and then send an error with this message:</p> <blockquote> <p>your entered username and email already exists in database. Please enter an other email and username.</p> </blockquote> <p>this is my codes to insert users infos in to the users table:</p> <pre><code>import bcrypt from &quot;bcrypt&quot;; import { SignUpInfos } from &quot;../interfaces/Interfaces&quot;; import { mysql } from &quot;../utils/DB&quot;; const signUpUser = async (datas: SignUpInfos) =&gt; { const hashedPassword = await bcrypt.hash(datas[&quot;user-password&quot;], 10); const results = await new Promise((resolve, reject) =&gt; { mysql.query( &quot;INSERT INTO users ( fullname, email, username, password ) VALUES ( ?, ?, ?, ? )&quot;, [ datas[&quot;user-fullname&quot;], datas[&quot;user-email&quot;], datas[&quot;user-username&quot;], hashedPassword, ], (err, result) =&gt; { if (err) reject(err); else resolve(result); } ); }); return results; }; export { signUpUser }; </code></pre> <p>so what is the best way to return the right error message if there was an error? is there any best way to do that or i should send to extra queries? thanks for help :)</p>
[ { "answer_id": 74349381, "author": "Nikola Pavicevic", "author_id": 11989189, "author_profile": "https://Stackoverflow.com/users/11989189", "pm_score": 2, "selected": false, "text": "const { ref } = Vue\nconst app = Vue.createApp({\n setup() {\n const status = ref([{label: 'EVO', status: false}, {label: 'Solist', status: false}, {label: 'SPL', status: false}])\n return {\n status\n }\n },\n})\napp.component('Checkbox', {\n template: `\n <div class=\"mt-1 relative\">\n <input\n type=\"checkbox\"\n :id=\"id ?? null\"\n :name=\"name\"\n :value=\"value\"\n :checked=\"modelValue ?? false\"\n class=\"bg-gray-200 text-gold-500 rounded border-0 w-5 h-5 mr-2 focus:ring-2 focus:ring-gold-500\"\n @input=\"updateValue\"\n />\n {{ label }}\n </div>\n `,\n props:{\n id: String,\n label: String,\n name: String,\n value: String,\n errors: Object,\n modelValue: Boolean,\n },\n setup(props, {emit}) {\n const updateValue = function(event) {\n emit('update:modelValue', event.target.checked)\n }\n return {\n updateValue\n }\n }\n})\napp.mount('#demo')" }, { "answer_id": 74373768, "author": "Axel Köhler", "author_id": 1973005, "author_profile": "https://Stackoverflow.com/users/1973005", "pm_score": 0, "selected": false, "text": "v-model" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349111", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18526209/" ]
74,349,143
<p>Many of our build pipelines include a &quot;command line&quot; task that is used to create a &quot;setup.exe&quot; from the contents of the build output folder (&quot;\agent_work\nn\<strong>s</strong>\...&quot;). The location of this folder is accessed via the build variable <code>$(system.defaultworkingdirectory)</code>.</p> <p>I've never utilised <em>release</em> pipelines before today, partly because I've never understood their purpose, but have decided to have a play with this feature. I've now created a release pipeline and moved the above command line task from the build pipeline and into the release pipeline's stage. Unsurprisingly the command fails because the above build variable is pointing to a completely different working folder (&quot;\agent\_work\nn\<strong>r1</strong>\a\...&quot;), which is empty.</p> <p>I'm possibly being a bit naive here and not understanding how or what release pipelines are used for, but is it possible for the release pipeline to know what the working directory is of the triggering build pipeline?</p> <p><strong>Edit</strong>: After some more reading it appears that the release pipeline is supposed to download the &quot;artifact&quot; from the triggering build pipeline, I've noticed these in the log, which looks suspicious:</p> <pre><code>Preparing to get the list of available artifacts from build Preparing to download artifact: build.SourceLabel ##[warning]Release management does not support download of artifact type TfvcLabel in the current version </code></pre> <p>What's going on here?</p>
[ { "answer_id": 74361967, "author": "Andrew Stephens", "author_id": 981831, "author_profile": "https://Stackoverflow.com/users/981831", "pm_score": 0, "selected": false, "text": "\\[agent]\\_work\\35\\s\\...\\x64\\release\\\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/981831/" ]
74,349,144
<p>I need to perform some action inside a catch block then <em>throw the same exception I got</em>:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;string&gt; #include &lt;iostream&gt; class AbstractError { public: virtual std::string toString() const = 0; }; class SomeConcreteError : public AbstractError { public: std::string toString() const { return &quot;division bt 0&quot;; } }; class SomeOtherError : public AbstractError { public: std::string toString() const { return &quot;null pointer deref&quot;; } }; void foo(int i) { if (i &gt; 2) { throw SomeConcreteError(); } else { throw SomeOtherError(); } } int main(int argc, char **argv) { try { foo(argc); } catch (const AbstractError &amp;e) { std::cout &lt;&lt; e.toString() &lt;&lt; &quot;\n&quot;; // do some action then re-throw throw e; // doesn't work ... } return 0; } </code></pre> <p>Here is the error I get:</p> <pre><code>main.cpp:28:15: error: expression of abstract class type ‘AbstractError’ cannot be used in throw-expression 28 | throw e; | ^ </code></pre>
[ { "answer_id": 74349200, "author": "Ted Lyngmo", "author_id": 7582247, "author_profile": "https://Stackoverflow.com/users/7582247", "pm_score": 4, "selected": true, "text": "e" }, { "answer_id": 74349220, "author": "Useless", "author_id": 212858, "author_profile": "https://Stackoverflow.com/users/212858", "pm_score": 2, "selected": false, "text": "throw" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3357352/" ]
74,349,242
<p>I have a data frame with one variable, x. I want to create a new variable y which is equal to 1 when x decreases by 2 from its previous value and equal to 0 otherwise. Then I want to create a variable z which holds the value of x when y was last equal to 1. I want the initial value of z to be 0. I haven't been able to figure out how to make z. Any advice?</p> <p>Here's what I'm trying to obtain (but for about 1000 rows):</p> <pre><code>x y z 9 0 0 8 0 0 6 1 6 9 0 6 7 1 7 5 1 5 </code></pre> <p>I've tried lags, cum functions in dplyr to no avail.</p>
[ { "answer_id": 74349357, "author": "sindri_baldur", "author_id": 4552295, "author_profile": "https://Stackoverflow.com/users/4552295", "pm_score": 1, "selected": false, "text": "df$y = 0L\ndf$y[-1] = (diff(df$x) == -2L)\ndf$z = data.table::nafill(ifelse(df$y == 1L, df$x, NA), \"locf\", fill = 0L)\n\n# x y z\n# 1 9 0 0\n# 2 8 0 0\n# 3 6 1 6\n# 4 9 0 6\n# 5 7 1 7\n# 6 5 1 5\n" }, { "answer_id": 74349424, "author": "Jamie", "author_id": 11564586, "author_profile": "https://Stackoverflow.com/users/11564586", "pm_score": 0, "selected": false, "text": "dplyr" }, { "answer_id": 74349841, "author": "M--", "author_id": 6461462, "author_profile": "https://Stackoverflow.com/users/6461462", "pm_score": 2, "selected": false, "text": "library(dplyr)\nlibrary(tidyr)\n\n\ndf <- data.frame(x = c(9,8,6,10,9,7,5))\n\ndf %>% \n mutate(y = +(lag(x, default = x[1]) - x == 2),\n z = ifelse(cumsum(y) > 0 & y == 0, NA, x * y)) %>% \n fill(z, .direction = \"down\")\n\n#> x y z\n#> 1 9 0 0\n#> 2 8 0 0\n#> 3 6 1 6\n#> 4 10 0 6\n#> 5 9 0 6\n#> 6 7 1 7\n#> 7 5 1 5\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20441342/" ]
74,349,290
<p>Thanks to help from stackoverflow, I arrived at the command below. But <code>&quot;match a single character not present in the set&quot;</code> does not work as I expect. The first capture <code>([^&quot;][^\n,]*)</code>should stop at <code>&quot;,</code> or <code>&quot;\n</code> , but currently only stops at <code>&quot;,\n</code> . What is my mistake and how can I fix it?</p> <p>Solution can only be in sed on linux bash and ideally is as close to my current command as possible (to be easier for me to understand).</p> <pre><code>sed -En ':a;N;s/.*CAKE_FROSTING\(\n*?\s*?&quot;([^&quot;][^\n,]*)&quot;[\n,]?\s*&quot;?(([^&quot;][^\n,]*)?&quot;)?.*,/\1\3/p;ba' filesToCheck/* </code></pre> <p>file.h</p> <pre><code>something else CAKE_FROSTING( &quot;is supreme &quot; &quot;and best&quot;, &quot;[i][agree]&quot;) something else something more something else CAKE_FROSTING( &quot;is.&quot;kinda&quot; neat &quot; &quot;in &quot;fact&quot;&quot;, &quot;[i][agree]&quot;) something else something more something else CAKE_FROSTING(&quot;is supreme&quot;, &quot;[i][agree]&quot;) something else something more something else </code></pre> <p>current output</p> <pre><code>is supreme and best is.&quot;kinda&quot; neat &quot; &quot;in &quot;fact&quot; is supreme &quot;[i][agree]&quot;) something else </code></pre> <p>desired output</p> <pre><code>is supreme and best is.&quot;kinda&quot; neat &quot; &quot;in &quot;fact&quot; is supreme </code></pre>
[ { "answer_id": 74349357, "author": "sindri_baldur", "author_id": 4552295, "author_profile": "https://Stackoverflow.com/users/4552295", "pm_score": 1, "selected": false, "text": "df$y = 0L\ndf$y[-1] = (diff(df$x) == -2L)\ndf$z = data.table::nafill(ifelse(df$y == 1L, df$x, NA), \"locf\", fill = 0L)\n\n# x y z\n# 1 9 0 0\n# 2 8 0 0\n# 3 6 1 6\n# 4 9 0 6\n# 5 7 1 7\n# 6 5 1 5\n" }, { "answer_id": 74349424, "author": "Jamie", "author_id": 11564586, "author_profile": "https://Stackoverflow.com/users/11564586", "pm_score": 0, "selected": false, "text": "dplyr" }, { "answer_id": 74349841, "author": "M--", "author_id": 6461462, "author_profile": "https://Stackoverflow.com/users/6461462", "pm_score": 2, "selected": false, "text": "library(dplyr)\nlibrary(tidyr)\n\n\ndf <- data.frame(x = c(9,8,6,10,9,7,5))\n\ndf %>% \n mutate(y = +(lag(x, default = x[1]) - x == 2),\n z = ifelse(cumsum(y) > 0 & y == 0, NA, x * y)) %>% \n fill(z, .direction = \"down\")\n\n#> x y z\n#> 1 9 0 0\n#> 2 8 0 0\n#> 3 6 1 6\n#> 4 10 0 6\n#> 5 9 0 6\n#> 6 7 1 7\n#> 7 5 1 5\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349290", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19017877/" ]
74,349,303
<p>We have an app developed using IONIC CORDOVA. When I am trying to upload app on the play store then it gives an error &quot;Apps targeting Android 12 and higher are required to specify an explicit value for android:exported&quot;</p> <p>I am using cordova-android: 8.0.0</p> <p>If I am using cordova-android:10.1.0 then I am unable to build app.</p>
[ { "answer_id": 74430793, "author": "Mathieu", "author_id": 20500007, "author_profile": "https://Stackoverflow.com/users/20500007", "pm_score": 1, "selected": false, "text": "<activity\n android:name=\".MainActivity\"\n android:exported=\"true\">\n </activity>\n" }, { "answer_id": 74491534, "author": "Krish", "author_id": 7051774, "author_profile": "https://Stackoverflow.com/users/7051774", "pm_score": 0, "selected": false, "text": "<intent-filter android:exported=\"true\" android:label=\"@string/launcher_name\">" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7051774/" ]
74,349,333
<p>I have a 2D array I created using this,</p> <pre><code>import numpy as np arr = np.arange(4) arr_2d = arr.reshape(2,2) </code></pre> <p>The array looks like this</p> <pre><code>print(arr_2d) [[0, 1], [2, 3]] </code></pre> <p>I am trying to get the location of each entry in <code>arr_2d</code> as an x, y coordinate, and eventually get an array that looks like this,</p> <pre><code>print(full_array) [[0, 0, 0], [1, 0, 1], [2, 1, 0], [3, 1, 1]] </code></pre> <p>Where the first column contains the values in <code>arr_2d</code>, the second column contains each value's x (or row) coordinate and the third column contains each value's y (or column) coordinate. I tried flattening <code>arr_2d</code> and enumerating to get the index of each entry, but I was unable to get it in this form. Any help will be much appreciated.</p>
[ { "answer_id": 74349511, "author": "John", "author_id": 4380147, "author_profile": "https://Stackoverflow.com/users/4380147", "pm_score": 0, "selected": false, "text": "import numpy as np\n\narr = np.arange(4)\narr_2d = arr.reshape(2,2) \n\narr_2d[1][0] = 5 # to illustrate a point\n\nprint(arr_2d)\ndimensions = arr_2d.shape\nfor y in range(dimensions[0]):\n for x in range(dimensions[1]):\n print(arr_2d[x][y], \" (x:\", x, \" y:\", y, \")\")\n" }, { "answer_id": 74349644, "author": "obchardon", "author_id": 4363864, "author_profile": "https://Stackoverflow.com/users/4363864", "pm_score": 1, "selected": false, "text": "np.unravel_index()" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12100655/" ]
74,349,373
<p>I'm trying to use delegated properties in Kotlin to provide some type safety to application preferences that are persisted to a non-typed store. The store is semanitcally a bit like some type of <code>Map&lt;String,Any&gt;</code>, although it doesn't implement that specific class.</p> <p>The problem i have is that it doesn't appear possible for a single delegate class to implement <code>getValue</code> and <code>setValue</code> for more than one type.</p> <p>If this is the type-safe <code>SomePreferences</code> class that other applications will call to get/set <code>preferenceOne</code> and <code>preferenceTwo</code>:</p> <pre class="lang-kotlin prettyprint-override"><code>class SomePreferences { private val myDelegate = MyPreferenceStorageImpl() var preferenceOne: Boolean by myDelegate var preferenceTwo: String by myDelegate } </code></pre> <p>However, if I try and create <code>MyPreferencesStorageImpl</code>, it tries to look something like this:</p> <pre class="lang-kotlin prettyprint-override"><code>class MyPreferenceStorageImpl() { operator fun getValue(somePreferences: SomePreferences, property: KProperty&lt;*&gt;): Boolean { TODO(&quot;Read from underlying store, transforming the read value as a boolean&quot;) } operator fun setValue(somePreferences: SomePreferences, property: KProperty&lt;*&gt;, b: Boolean) { TODO(&quot;Write to underlying store, transforming the value from a Boolean&quot;) } operator fun getValue(somePreferences: SomePreferences, property: KProperty&lt;*&gt;): String { TODO(&quot;Read from underlying store, transforming value to a String&quot;) } operator fun setValue(somePreferences: SomePreferences, property: KProperty&lt;*&gt;, s: String) { TODO(&quot;Write to underlying store, transforming given value to a string&quot;) } } </code></pre> <p>However, this doesn't work, because I've got two methods who only differ by return type, which is a conflict.</p> <p>I've a couple of half-baked ideas on how to solve this, including trying to subclass <code>Map&lt;String, Any&gt;</code> in some way, or maybe provide a type-specific implementation per preference type (ew), or generics (somehow) but these don't feel particularly right.</p> <p>Am I missing an obviously better approach here?</p>
[ { "answer_id": 74349511, "author": "John", "author_id": 4380147, "author_profile": "https://Stackoverflow.com/users/4380147", "pm_score": 0, "selected": false, "text": "import numpy as np\n\narr = np.arange(4)\narr_2d = arr.reshape(2,2) \n\narr_2d[1][0] = 5 # to illustrate a point\n\nprint(arr_2d)\ndimensions = arr_2d.shape\nfor y in range(dimensions[0]):\n for x in range(dimensions[1]):\n print(arr_2d[x][y], \" (x:\", x, \" y:\", y, \")\")\n" }, { "answer_id": 74349644, "author": "obchardon", "author_id": 4363864, "author_profile": "https://Stackoverflow.com/users/4363864", "pm_score": 1, "selected": false, "text": "np.unravel_index()" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/352740/" ]
74,349,408
<p>I would like the appBar title of my Scaffold to display the total number of items (length) in a Firebase Query at launch, but it keeps returning <code>Instance of 'Future&lt;int&gt;'</code>. How can I fix this?</p> <p>Here's my code:</p> <pre><code>Query itemList = FirebaseFirestore.instance .collection('simple'); Future&lt;int&gt; itemCount() async =&gt; FirebaseFirestore.instance .collection('simple') .snapshots() .length; ... return Scaffold( appBar: AppBar( title: Text(&quot;# Items: &quot; + itemCount().toString()), // DISPLAYS: # Items: Instance of 'Future&lt;int&gt;' </code></pre> <p>Unfortunately, it displays <code>Instance of 'Future&lt;int&gt;'</code>. What do I have to change to obtain the item count (length) and have that show-up in the title text?</p> <p>Thank you!</p>
[ { "answer_id": 74349508, "author": "VincentDR", "author_id": 19540575, "author_profile": "https://Stackoverflow.com/users/19540575", "pm_score": 2, "selected": false, "text": "AppBar(\n title: FutureBuilder<String>(\n future: itemCount(), \n builder: (BuildContext context, AsyncSnapshot<int> snapshot) {\n if (snapshot.hasData) {\n return Text(\"# Items: \" + snapshot.data.toString());\n }else {\n Text(\"No data\");\n }\n }),\n )\n" }, { "answer_id": 74349531, "author": "Remy", "author_id": 20398469, "author_profile": "https://Stackoverflow.com/users/20398469", "pm_score": 2, "selected": false, "text": ".then()" }, { "answer_id": 74354676, "author": "SqueezeOJ", "author_id": 6188976, "author_profile": "https://Stackoverflow.com/users/6188976", "pm_score": 0, "selected": false, "text": " appBar: AppBar(\n title: StreamBuilder(\n stream: itemList.snapshots(),\n builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {\n\n if (snapshot.connectionState == ConnectionState.waiting) {\n return const Text(\"# Items: ...\");\n }\n\n else if (snapshot.hasData) {\n return Text(\"# Items: ${snapshot.data?.docs.length ?? 0}\");\n }\n\n else {\n return const Text('# Items: 0');\n }\n\n }, // Item Builder\n ), // Stream Builder\n ), // App Bar\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6188976/" ]
74,349,425
<p>I am trying to get bug to work, but am having no luck, the parts marked as abstract need to stay that way seeing as it is specified as such in the question I am trying to answer.</p> <pre><code> abstract class Worker { protected string name; protected int ID; protected abstract int expLevel(); // create abstract property for experience field public abstract string Experience(int expLevel); //create abstract method called experience public Worker(string name, int ID) //constructor for worker { this.name = name; this.ID = ID; } public Worker() { } // how I tried to fix error } class Labourer : Worker { Worker worker1 = new Worker(); // line in which bug occurs protected override int expLevel() { return expLevel(); } public override string Experience(int expLevel) // returns strings to be used later { if (expLevel &gt; 5) { return &quot;Senior&quot;; } return &quot;Junior&quot;; } } } </code></pre>
[ { "answer_id": 74349498, "author": "L01NL", "author_id": 686023, "author_profile": "https://Stackoverflow.com/users/686023", "pm_score": 0, "selected": false, "text": "Worker" }, { "answer_id": 74349530, "author": "MakePeaceGreatAgain", "author_id": 2528063, "author_profile": "https://Stackoverflow.com/users/2528063", "pm_score": 1, "selected": false, "text": "abstract class Worker\n{\n protected string name;\n protected int ID;\n protected abstract int expLevel(); // create abstract property for experience field\n public abstract string Experience(int expLevel); //create abstract method called experience\n\n \n public Worker(string name, int ID) //constructor for worker\n {\n this.name = name;\n this.ID = ID;\n }\n // no need for a parameter-less ctor here\n}\n\nclass Labourer : Worker \n{ \n public Labourer(string name, int ID) : base(name, id) { }\n\n protected override int expLevel()\n {\n return expLevel();\n }\n\n public override string Experience(int expLevel) // returns strings to be used later\n {\n if (expLevel > 5)\n {\n return \"Senior\";\n }\n return \"Junior\";\n } \n}\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20377406/" ]
74,349,459
<p>I am writing a code to get the p-value in Python.</p> <pre><code>def adfuller_test(GDP): result=adfuller(GDP) labels = ['ADF Test Statistic','p-value','#Lags Used','Number of Observations'] for value,label in zip(result,labels): print(label+' : '+str(value) ) if result[1] &lt;= 0.05: print(&quot;strong evidence against the null hypothesis(Ho), reject the null hypothesis. Data is stationary&quot;) else: print(&quot;weak evidence against null hypothesis,indicating it is non-stationary &quot;) adfuller_test(data['GDP']) </code></pre> <p>While executing the above code, I am getting the error (mentioned below).</p> <pre><code>--------------------------------------------------------------------------- NameError Traceback (most recent call last) ~\AppData\Local\Temp\ipykernel_9032\1780834004.py in &lt;module&gt; 6 print(label+' : '+str(value) ) 7 ----&gt; 8 if result[1] &lt;= 0.05: 9 print(&quot;strong evidence against the null hypothesis(Ho), reject the null hypothesis. Data is stationary&quot;) 10 else: NameError: name 'result' is not defined </code></pre> <p>Please let me know how to fix the error, Thanks.</p>
[ { "answer_id": 74349498, "author": "L01NL", "author_id": 686023, "author_profile": "https://Stackoverflow.com/users/686023", "pm_score": 0, "selected": false, "text": "Worker" }, { "answer_id": 74349530, "author": "MakePeaceGreatAgain", "author_id": 2528063, "author_profile": "https://Stackoverflow.com/users/2528063", "pm_score": 1, "selected": false, "text": "abstract class Worker\n{\n protected string name;\n protected int ID;\n protected abstract int expLevel(); // create abstract property for experience field\n public abstract string Experience(int expLevel); //create abstract method called experience\n\n \n public Worker(string name, int ID) //constructor for worker\n {\n this.name = name;\n this.ID = ID;\n }\n // no need for a parameter-less ctor here\n}\n\nclass Labourer : Worker \n{ \n public Labourer(string name, int ID) : base(name, id) { }\n\n protected override int expLevel()\n {\n return expLevel();\n }\n\n public override string Experience(int expLevel) // returns strings to be used later\n {\n if (expLevel > 5)\n {\n return \"Senior\";\n }\n return \"Junior\";\n } \n}\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14787592/" ]
74,349,470
<p>I'm trying to write a function which will free a dynamically allocated string by sending the address of the string (char*) to the function. (Sending char**)</p> <p>I have tried doing it like this:</p> <pre><code>void dstring_delete(DString* stringToDelete) { // Precondition: stringToDelete is not NULL assert(stringToDelete != NULL); free(*stringToDelete); </code></pre> <p>Where DString is defined like this:</p> <pre><code>typedef char* DString; </code></pre> <p>The call to the function looks like this:</p> <pre><code>dstring_delete(&amp;str1); </code></pre> <p>Where str1 is of type DString:</p> <pre><code>DString str1, str2; </code></pre> <p>I cant seem to figure out what is going wrong but this assert below the function call fails:</p> <pre><code>assert(str1 == NULL); </code></pre> <p>So my question is how I properly free the memory in this instance.</p> <p>I have tried different arguments sent to the free function and also tried to find the same issues here.</p>
[ { "answer_id": 74350279, "author": "Ian Abbott", "author_id": 5264491, "author_profile": "https://Stackoverflow.com/users/5264491", "pm_score": 1, "selected": false, "text": "str1" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20397507/" ]
74,349,488
<p>So, i have a list of objcets in an array stored in the databse. I am trying to display the object at the last index position using map function. It keeps displaying all the objects in the array,but i only want to show the last object. I will appreciate any help.</p> <pre><code>import React, { Component } from 'react'; import axios from 'axios'; class ConfirmBooking extends Component { state = { bookings: [] } componentDidMount() { axios.get('http://localhost:5000/api',) .then(res =&gt; { (console.log(res.data)) this.setState({ bookings: res.data }) }) .catch((error) =&gt; { console.log(error) }) } render() { return ( &lt;div&gt; {/*{this.state.bookings.map((booking, i)=&gt; { return ( &lt;div key={}&gt; &lt;h6&gt;{`Name: ${booking.name}Service: ${booking.service} Date: ${booking.date} Cost: ${booking.cost}`}&lt;/h6&gt; &lt;/div&gt; ) })} */} </code></pre> <p>that is what i i have tried so far <a href="https://i.stack.imgur.com/kR58z.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kR58z.png" alt="result i am getting" /></a></p>
[ { "answer_id": 74350279, "author": "Ian Abbott", "author_id": 5264491, "author_profile": "https://Stackoverflow.com/users/5264491", "pm_score": 1, "selected": false, "text": "str1" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18705872/" ]
74,349,505
<p>i have a custom package with a custom content element. The data (header + bodytext) of the custom element is stored in tt_content. This content element now needs a connection to a record of tt_address. Therefore i extendet tt_content with a field named address_uid.</p> <p>My idea is to load all records (respectively the field 'company') from the table tt_address to a select field in a palette. The user can select a company and add header and bodytext and save the uid of the selected addressrecord to tt_content.</p> <p>How can this be realized, in particular reading and displaying the data from tt_address.</p> <p>THX for your supprt mimii</p>
[ { "answer_id": 74350279, "author": "Ian Abbott", "author_id": 5264491, "author_profile": "https://Stackoverflow.com/users/5264491", "pm_score": 1, "selected": false, "text": "str1" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15648489/" ]
74,349,519
<p>I'm new to python and pandas. I have a data set with the columns age, sex, bmi, children, smoker, region, charges. I want to write a query to count all the smokers that answered &quot;yes&quot; based on their region. the regions can only be northwest, northeast, southwest, southeast.</p> <p>I have tried several groupby and series commands but i'm not getting it. Can anyone help? Thanks in advance</p> <p>I've tried:</p> <pre><code>data.groupby('Region').count() data.groupby('Region').apply(lambda g: pd.Series(g['Smoker'].str.contains(&quot;y&quot;).count())) data['Smoker'].value_counts().reindex(['Region']) </code></pre> <p>None of them worked.</p>
[ { "answer_id": 74350279, "author": "Ian Abbott", "author_id": 5264491, "author_profile": "https://Stackoverflow.com/users/5264491", "pm_score": 1, "selected": false, "text": "str1" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20441929/" ]
74,349,523
<p>Is there a way to create a table inside a Quarto document without applying the doc's theme to the HTML table.</p> <p>Usually I use <code>as_raw_html()</code> to avoid the Quarto style. But in my current use-case, my table contains a custom ggplot which is removed when I use <code>as_raw_html()</code>.</p> <p>I've tried using <a href="https://stackoverflow.com/questions/74026514/how-to-apply-css-style-to-quarto-output">custom output class</a> but this didn't take any effect on the table output.</p> <h2>Reprex</h2> <pre><code>library(tidyverse) library(gt) filtered_penguins &lt;- palmerpenguins::penguins |&gt; filter(!is.na(sex)) penguin_weights &lt;- palmerpenguins::penguins |&gt; filter(!is.na(sex)) |&gt; group_by(species) |&gt; summarise( Min = min(body_mass_g), Mean = mean(body_mass_g) |&gt; round(digits = 2), Max = max(body_mass_g) ) |&gt; mutate(species = as.character(species), Distribution = species) |&gt; rename(Species = species) plot_density_species &lt;- function(species, variable) { full_range &lt;- filtered_penguins |&gt; pull({{variable}}) |&gt; range() filtered_penguins |&gt; filter(species == !!species) |&gt; ggplot(aes(x = {{variable}}, y = species)) + geom_violin(fill = 'dodgerblue4') + theme_minimal() + scale_y_discrete(breaks = NULL) + scale_x_continuous(breaks = NULL) + labs(x = element_blank(), y = element_blank()) + coord_cartesian(xlim = full_range) } penguin_weights |&gt; gt() |&gt; tab_spanner( label = 'Penguin\'s Weight', columns = -Species ) |&gt; text_transform( locations = cells_body(columns = 'Distribution'), # Create a function that takes the a column as input # and gives a list of ggplots as output fn = function(column) { map(column, ~plot_density_species(., body_mass_g)) |&gt; ggplot_image(height = px(50), aspect_ratio = 3) } ) </code></pre> <h2>Desired Output</h2> <p>This is the output I get outside of a Quarto document. But inside a Quarto doc, the doc's theme is applied to the table. Using <code>as_raw_html()</code> removes the plots.</p> <p><a href="https://i.stack.imgur.com/zIkmf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zIkmf.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74350279, "author": "Ian Abbott", "author_id": 5264491, "author_profile": "https://Stackoverflow.com/users/5264491", "pm_score": 1, "selected": false, "text": "str1" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13679911/" ]
74,349,552
<p>Im trying to build a program that does stock-analys.</p> <p>I have a file that contains a string (the company name) followed by a lot of values. I want my function to open the txt file and read trough it until it find the given variable name e.x &quot;Apple&quot;, and then it should return a dictonary of the 30 next values after.</p> <p>E.g i need the values 7.15, 6,72 .. after &quot;apple&quot; and the dates in the following example.</p> <pre><code>02-09-26 4.12 02-09-27 3.92 02-09-30 3.37 Apple 02-08-01 7.15 02-08-02 6.72 02-08-05 5.56 02-08-06 5.49 02-08-07 5.63 </code></pre> <p>should be returning {(date1,vaule1)...}</p> <pre><code>def openfile(file_name, company_name): file_words = [] with open(file_name, &quot;r&quot;) as file: for line in file: </code></pre> <p>i really have no idea how to continue here..</p>
[ { "answer_id": 74350279, "author": "Ian Abbott", "author_id": 5264491, "author_profile": "https://Stackoverflow.com/users/5264491", "pm_score": 1, "selected": false, "text": "str1" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20119030/" ]
74,349,626
<p>I have an issue with my popup form in my note-taking project. I have a popup form that shows up if user wants to edit a note, and that popup should already have the contents of the note they chose to edit. The form is showing the correct contents, but also I noticed that when I click on &quot;Edit&quot;, it takes two clicks for the note to get printed (I suspect that I'm using <code>useState()</code> wrong but I can't pinpoint the exact spot where that's happening), and I'm wondering why that is. I've tried getting the data straight from the database, sending it to the form as props and , but I can't get to the desired result. I'm not sure where I'm going wrong and would appreciate any help!</p> <p>Here's my Note component:</p> <pre><code>import axios from &quot;axios&quot;; import EditNote from './EditNote' function Note(props) { const [isEdit, setEditNote] = useState(false) const [idToEdit, setIdToEdit] = useState('') const [buttonPopup, setButtonPopup] = useState(false); const [noteToEdit, setNoteToEdit] = useState({ title: &quot;&quot;, content: &quot;&quot;, category: &quot;&quot; }) function deleteNote(id) { axios.delete(`http://localhost:5000/notes/${id}`) .then(() =&gt; { console.log(&quot;Note successfully deleted&quot;) props.setFetch(true) }); } function changeNotes(id, title, content, category){ setEditNote(true) setButtonPopup(true) setNoteToEdit(prevNote =&gt; { return { ...prevNote, title : title, content : content, category : category }; }); console.log(noteToEdit) setIdToEdit(id) console.log(idToEdit) } return ( &lt;div&gt; {/* pass the notes array from CreateArea as props */} {props.notes.map((noteItem) =&gt; { return ( &lt;div className=&quot;note&quot;&gt; &lt;h1&gt;{noteItem.title}&lt;/h1&gt; &lt;p&gt;{noteItem.content}&lt;/p&gt; &lt;button onClick={() =&gt; {changeNotes(noteItem._id, noteItem.content, noteItem.title, noteItem.category)}}&gt; Edit &lt;/button&gt; &lt;button onClick={() =&gt; {deleteNote(noteItem._id)}}&gt; Delete &lt;/button&gt; &lt;p&gt;{noteItem.category}&lt;/p&gt; &lt;/div&gt; ); })} &lt;EditNote trigger={buttonPopup} setButtonPopup={setButtonPopup} categories={props.categories} id={idToEdit} noteToEdit={noteToEdit} setEditNote={setEditNote} isEdit={isEdit}&gt; &lt;h1&gt;popup form&lt;/h1&gt; &lt;/EditNote&gt; &lt;/div&gt; ) } export default Note </code></pre> <p>and EditNote component:</p> <pre><code>import axios from &quot;axios&quot;; export default function EditNote(props){ const [note, setNote] = useState({ title: props.noteToEdit.title, content: props.noteToEdit.content, }); function handleChange(event) { const {name, value} = event.target; setNote({...note, [name]: value}); } const updateNote = () =&gt; { setNote((prevValue, id) =&gt; { if (props.noteToEdit._id === id) { props.title = note.title; props.content = note.content; props.category = note.category } else { return { ...prevValue }; } }); props.setEditNote(false); props.setButtonPopup(false) }; return (props.trigger) ? ( &lt;div className=&quot;edit-notes-form&quot;&gt; &lt;form className=&quot;popup-inner&quot;&gt; &lt;input name=&quot;title&quot; onChange={handleChange} value={props.noteToEdit.title} placeholder=&quot;Title&quot; /&gt; &lt;textarea name=&quot;content&quot; onChange={handleChange} value={props.noteToEdit.content} placeholder=&quot;Take a note...&quot; rows={3} /&gt; &lt;select name=&quot;category&quot; onChange={handleChange} value={props.noteToEdit.category} &gt; { props.categories.map(function(cat) { return &lt;option key={cat.category} value={cat.value} &gt; {cat.category} &lt;/option&gt;; }) } &lt;/select&gt; &lt;div className=&quot;btn-update-note&quot;&gt; &lt;button className=&quot;btn-update&quot; onClick={updateNote}&gt;Save&lt;/button&gt; &lt;button className=&quot;btn-update&quot; onClick={() =&gt; props.setButtonPopup(false)}&gt;Close&lt;/button&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; ) : '' } </code></pre> <p>I also tried useRef, but it's not working as intended. Would appreciate any direction on this, thank you!</p>
[ { "answer_id": 74351296, "author": "marzelin", "author_id": 5664434, "author_profile": "https://Stackoverflow.com/users/5664434", "pm_score": 2, "selected": false, "text": "changeNotes" }, { "answer_id": 74360592, "author": "01nowicj", "author_id": 17965573, "author_profile": "https://Stackoverflow.com/users/17965573", "pm_score": 1, "selected": true, "text": "import axios from \"axios\";\n\nexport default function EditNote(props){\n const [note, setNote] = useState({\n title: props.noteToEdit.title,\n content: props.noteToEdit.content\n });\n\n console.log(props.noteToEdit)\n\n function handleChange(event) {\n event.preventDefault();\n const {name, value} = event.target;\n setNote({...note, [name]: value});\n }\n \n const updateNote = (event) => {\n event.preventDefault();\n if (!note.title || !note.content) {\n alert(\"'Title' or 'Content' cannot be blank\");\n } else {\n axios.post(`http://localhost:5000/notes/update/${props.id}`, note) \n .then((res) =>{\n console.log(\"Note updated successfully\")\n props.setFetch(true) \n })\n .catch(err => console.log(\"Error: \" + err));\n }\n props.setButtonPopup(false)\n };\n\n return (props.trigger) ? (\n <div className=\"edit-notes-form\">\n <form className=\"popup-inner\">\n <input\n name=\"title\"\n onChange={handleChange}\n defaultValue={props.noteToEdit.title}\n placeholder=\"Title\"\n />\n <textarea\n name=\"content\"\n onChange={handleChange}\n defaultValue={props.noteToEdit.content}\n placeholder=\"Take a note...\"\n rows={3}\n />\n <select\n name=\"category\"\n onChange={handleChange}\n defaultValue={props.noteToEdit.category}\n >\n {\n props.categories.map(function(cat) {\n return <option\n key={cat.category} value={cat.value} > {cat.category} </option>;\n })\n }\n </select>\n <div className=\"btn-update-note\">\n <button className=\"btn-update\" onClick={updateNote}>Save</button>\n <button className=\"btn-update\" onClick={() => props.setButtonPopup(false)}>Close</button>\n </div>\n </form>\n </div> ) : '' \n}\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17965573/" ]
74,349,630
<p>I want to bring the menu to the center, but I still do not know how to do it. O yeah, I use actions and TextButton to put it</p> <p><a href="https://i.stack.imgur.com/fXiXE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fXiXE.png" alt="enter image description here" /></a></p> <p>I have tried to put Center widget, and I think I use the wrong method. This is the code, as you can see I put the button on actions = [].</p> <pre><code> actions: [ // Dashboard TextButton( onPressed: () {}, child: Text('Dashboard'), ), // Home TextButton( onPressed: () {}, child: Text('Home'), ), // History TextButton( onPressed: () {}, child: Text('History'), ), // Area TextButton( onPressed: () {}, child: Text('Area'), ), // Users TextButton( onPressed: () {}, child: Text('Users'), ), // Excavator TextButton( onPressed: () {}, child: Text('Excavator'), ), // Notification button IconButton( icon: const Icon( Icons.notifications_none, color: Colors.black, ), onPressed: () {}, ), // Person profil button IconButton( onPressed: () {}, icon: const Icon( Icons.person_outline_rounded, color: Colors.black, ), ), ], </code></pre> <p>This is the layout looks like when I inspect it with DevTools.</p> <p><a href="https://i.stack.imgur.com/Zmy5p.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Zmy5p.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74351296, "author": "marzelin", "author_id": 5664434, "author_profile": "https://Stackoverflow.com/users/5664434", "pm_score": 2, "selected": false, "text": "changeNotes" }, { "answer_id": 74360592, "author": "01nowicj", "author_id": 17965573, "author_profile": "https://Stackoverflow.com/users/17965573", "pm_score": 1, "selected": true, "text": "import axios from \"axios\";\n\nexport default function EditNote(props){\n const [note, setNote] = useState({\n title: props.noteToEdit.title,\n content: props.noteToEdit.content\n });\n\n console.log(props.noteToEdit)\n\n function handleChange(event) {\n event.preventDefault();\n const {name, value} = event.target;\n setNote({...note, [name]: value});\n }\n \n const updateNote = (event) => {\n event.preventDefault();\n if (!note.title || !note.content) {\n alert(\"'Title' or 'Content' cannot be blank\");\n } else {\n axios.post(`http://localhost:5000/notes/update/${props.id}`, note) \n .then((res) =>{\n console.log(\"Note updated successfully\")\n props.setFetch(true) \n })\n .catch(err => console.log(\"Error: \" + err));\n }\n props.setButtonPopup(false)\n };\n\n return (props.trigger) ? (\n <div className=\"edit-notes-form\">\n <form className=\"popup-inner\">\n <input\n name=\"title\"\n onChange={handleChange}\n defaultValue={props.noteToEdit.title}\n placeholder=\"Title\"\n />\n <textarea\n name=\"content\"\n onChange={handleChange}\n defaultValue={props.noteToEdit.content}\n placeholder=\"Take a note...\"\n rows={3}\n />\n <select\n name=\"category\"\n onChange={handleChange}\n defaultValue={props.noteToEdit.category}\n >\n {\n props.categories.map(function(cat) {\n return <option\n key={cat.category} value={cat.value} > {cat.category} </option>;\n })\n }\n </select>\n <div className=\"btn-update-note\">\n <button className=\"btn-update\" onClick={updateNote}>Save</button>\n <button className=\"btn-update\" onClick={() => props.setButtonPopup(false)}>Close</button>\n </div>\n </form>\n </div> ) : '' \n}\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19875840/" ]
74,349,631
<p>See: <a href="https://www.oreilly.com/library/view/mastering-perl/9780596527242/ch02.html" rel="nofollow noreferrer">https://www.oreilly.com/library/view/mastering-perl/9780596527242/ch02.html</a></p> <p>I'm having some trouble getting the perl Global Match Anchors \G to work with my input file proved below with my perl code... I would have thought \G keeps picking up where it left off in the previous match and matches from that position in the string?</p> <p>note, if i uncomment these two line it works:</p> <pre class="lang-perl prettyprint-override"><code> #!/bin/perl $vlog = &quot;out/tb_asc.sv&quot;; open(my $F, &quot;$vlog&quot;) || die(&quot;cannot open file: $vlog\n&quot;); @lines = &lt;$F&gt;; chomp(@lines); $bigline = join(&quot;\n&quot;, @lines); close($F); $movingline = $bigline; print &quot;&gt;&gt; &lt;&lt; START\n&quot;; $moving = $bigline; $moving =~ s|//.*$||mg; $moving =~ s|\s+$||mg; while(1) { # Blank Linke if ($moving =~ /\G\n/g) { #$moving = substr $moving, $+[0]+1; # &lt;= doesn't \G anchor imply this line? next; } # Precompiler Line if ($moving =~ /\G\s*`(\w+)(\s+(.*))?\n/g) { $vpccmd = $1; $vpcarg1 = $3; #$moving = substr $moving, $+[0]+1; print &quot;vpc_cmd($vpccmd) vpc_arg1($vpcarg1)\n&quot;; next; } $c = nextline($moving); print &quot;\n=&gt; processing:[$c]\n&quot;; die(&quot;parse error\n&quot;); } sub nextline($) { @c = split(/\n/, $moving); $c = $c[0]; chomp($c); return $c; } </code></pre> <p>sample input file: out/tb_asc.sv</p> <pre><code> `timescale 1ns / 1ps `define DES tb_asc.DES.HS86.CORE `ifdef HS97_MODE `define SER_DUT HS97 `ifndef HS78_MODE `define SER_DUT HS78 `else //1:HS78_MODE `define SER_DUT HS89 `define SER tb_asc.SER.`SER_DUT.CORE `ifdef MULTIPLE_SERS `define SER_1 tb_asc.SER_1.`SER_DUT.CORE `define SER_2 tb_asc.SER_2.`SER_DUT.CORE `define SER_3 tb_asc.SER_3.`SER_DUT.CORE `else //1:MULTIPLE_SERS `define SER_1 tb_asc.SER.`SER_DUT.CORE `define SER_2 tb_asc.SER.`SER_DUT.CORE `define SER_3 tb_asc.SER.`SER_DUT.CORE `define REPCAPCAL DIGITAL_TOP.RLMS_A.REPCAL.U_REPCAPCAL_CTRL `define MPU_D POWER_MGR.Ism.por_pwdnb_release `define DFE_OUT RXD.EC.Eslicer.QP `define DFE_OUT_SER RXD.EC.Eslicer.QP //beg-include-1 ser_reg_defs_macros.sv //FILE: /design/proj/hs89/users/HS89D-0A/digital/modules/cc/src/ser_reg_defs_macros.sv `define CFG_BLOCK &quot;CFG_BLOCK&quot; `define DEV_ADDR &quot;DEV_ADDR&quot; `define RX_RATE &quot;RX_RATE&quot; `define TX_RATE &quot;TX_RATE&quot; `define DIS_REM_CC &quot;DIS_REM_CC&quot; `define DIS_LOCAL_CC &quot;DIS_LOCAL_CC&quot; </code></pre> <p>NOTE: this version works but doesn't use \G:</p> <pre class="lang-perl prettyprint-override"><code>while(1) { # Blank Linke if ($moving =~ /\A$/m) { $moving = substr $moving, $+[0]+1; next; } # Precompiler Line if ($moving =~ /\A\s*`/) { $moving =~ /\A\s*`(\w+)(\s+(.*))?$/m; $vpccmd = $1; $vpcarg1 = $3; $moving = substr $moving, $+[0]+1; print &quot;vpc_cmd($vpccmd) vpc_arg1($vpcarg1)\n&quot;; next; } $c = nextline($moving); print &quot;\n=&gt; processing:[$c]\n&quot;; die(&quot;parse error\n&quot;); } </code></pre> <p>I prefer to do this using \G because substr uses a lot of CPU time with a large input file.</p>
[ { "answer_id": 74353957, "author": "ikegami", "author_id": 589924, "author_profile": "https://Stackoverflow.com/users/589924", "pm_score": 2, "selected": false, "text": "$ perl -Mv5.14 -e'$_ = \"abc\"; /./g; /x/g; say $& if /./g;'\na\n" }, { "answer_id": 74362070, "author": "brian d foy", "author_id": 2766176, "author_profile": "https://Stackoverflow.com/users/2766176", "pm_score": 1, "selected": false, "text": "/gc" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11384455/" ]
74,349,638
<p>I am trying to make a Discord bot and one of the features is a welcoming from my bot using on_member_join. This is the event:</p> <pre><code>@bot.event async def on_member_join(member, self): embed = discord.Embed(colour=discord.Colour(0x95efcc), description=f&quot;Welcome to Rebellions server! You are the{len(list(member.guild.members))}th member!&quot;) embed.set_thumbnail(url=f&quot;{member.avatar_url}&quot;) embed.set_author(name=f&quot;{member.name}&quot;, icon_url=f&quot;{member.avatar_url}&quot;) embed.set_footer(text=f&quot;{member.guild}&quot;, icon_url=f&quot;{member.guild.icon_url}&quot;) embed.timestamp = datetime.datetime.utcnow() await welcome_channel.send(embed=embed) </code></pre> <p>Although when the bot is working and running and someone joins my server I get this error:</p> <pre><code>[2022-11-07 19:38:10] [ERROR ] discord.client: Ignoring exception in on_member_join Traceback (most recent call last): File &quot;C:\Users\stene\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py&quot;, line 409, in _run_event await coro(*args, **kwargs) File &quot;C:\Users\stene\OneDrive\Documents\GitHub\bot\main.py&quot;, line 25, in on_member_join embed.set_thumbnail(url=f&quot;{member.avatar_url}&quot;) ^^^^^^^^^^^^^^^^^ AttributeError: 'Member' object has no attribute 'avatar_url' </code></pre> <p>I am running the latest version of discord.py and python. Thanks! welcome cog:</p> <pre><code>import discord from discord.ext import commands import asyncio import datetime class WelcomeCog(commands.Cog, name=&quot;Welcome&quot;): def __init__(self, bot): self.bot = bot @commands.Cog.listener() async def on_member_join(self, member): embed = discord.Embed(colour=discord.Colour(0x95efcc), description=f&quot;Welcome to Rebellions server! You are the{len(list(member.guild.members))}th member!&quot;) embed.set_thumbnail(url=member.avatar.url) embed.set_author(name=member.name, icon_url=member.avatar.url) embed.set_footer(text=member.guild) embed.timestamp = datetime.datetime.utcnow() channel = self.bot.get_channel(1038893507961692290) await channel.send(embed=embed) async def setup(bot): await bot.add_cog(WelcomeCog(bot)) print(&quot;Welcome cog has been loaded successfully!&quot;) </code></pre>
[ { "answer_id": 74350418, "author": "Wari", "author_id": 15479314, "author_profile": "https://Stackoverflow.com/users/15479314", "pm_score": 2, "selected": false, "text": "async def on_member_join(member, self):" }, { "answer_id": 74354373, "author": "ScientiaEtVeritas", "author_id": 2612484, "author_profile": "https://Stackoverflow.com/users/2612484", "pm_score": 3, "selected": true, "text": "Member.avatar_url" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20177656/" ]
74,349,643
<p>I need to get the DNS server(s) from my network, I tried using:</p> <pre class="lang-yaml prettyprint-override"><code>- hosts: localhost gather_facts: no tasks: - name: check resolv.conf exists stat: path: /etc/resolv.conf register: resolv_conf - name: check nameservers list in resolv.conf debug: msg: &quot;{{ contents }}&quot; vars: contents: &quot;{{ lookup('file', '/etc/resolv.conf') | regex_findall('\\s*nameserver\\s*(.*)') }}&quot; when: resolv_conf.stat.exists == True </code></pre> <p>But this does not quite gives the result I need.</p> <p>Will it be possible to write a playbook in such a way that the result looks like the below?</p> <blockquote> <p>hostname;dns1;dns2;dnsN</p> </blockquote>
[ { "answer_id": 74350418, "author": "Wari", "author_id": 15479314, "author_profile": "https://Stackoverflow.com/users/15479314", "pm_score": 2, "selected": false, "text": "async def on_member_join(member, self):" }, { "answer_id": 74354373, "author": "ScientiaEtVeritas", "author_id": 2612484, "author_profile": "https://Stackoverflow.com/users/2612484", "pm_score": 3, "selected": true, "text": "Member.avatar_url" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7135687/" ]
74,349,666
<p>I am trying to output</p> <pre><code>Grace was planning a dream vacation to Paris. Grace was especially looking forward to trying the local cuisine, including stinky soup and bananas. Grace will have to practice the language quietly to make it easier to jump with people. Grace has a long list of sights to see, including the button museum and the blue park. </code></pre> <p>and with some of those words being variables its hard to put it in a print as im still new. Here is my code and error message</p> <pre><code>print(&quot;Let's play Sill Sentences!&quot;) name=str(input(&quot;Enter a name: &quot;)) abj1=str(input(&quot;Enter an adjective: &quot;)) abj2=str(input(&quot;Enter a different adjective: &quot;)) food1=str(input(&quot;Enter a food: &quot;)) food2=str(input(&quot;Enter another food: &quot;)) noun=str(input(&quot;Enter a noun: &quot;)) place=str(input(&quot;Enter a place: &quot;)) verb=str(input(&quot;Enter a verb: &quot;)) print( , name + &quot;was planning a dream vacation to &quot; ,place +&quot;.&quot;,name+ &quot;was especially looking forward to trying the local cusine,including &quot;,abj1+ ,food1+&quot;and &quot;,food2) </code></pre> <p>Then my error code is SyntaxError: bad input on line 11 My question is how do you properly input mutiple varibles, like this,within a print and still have a succseful code. Again im very new and trying to learn Python.</p> <p>I tried to put the (input) commands with str() but that hasnt worked and im not sure how to put the variables with the print command.</p>
[ { "answer_id": 74349768, "author": "Nishesh Tyagi", "author_id": 19539370, "author_profile": "https://Stackoverflow.com/users/19539370", "pm_score": -1, "selected": false, "text": "print( , name + \"was planning a dream vacation to \" ,place +\".\",name+ \"was especially looking forward to trying the local cusine,including \",abj1+ ,food1+\"and \",food2)\n" }, { "answer_id": 74378220, "author": "The_spider", "author_id": 16490627, "author_profile": "https://Stackoverflow.com/users/16490627", "pm_score": 2, "selected": false, "text": "print( " } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20441979/" ]
74,349,671
<p>Could someone help me with the last step of a query in a Django view please.</p> <p>I have two tables.</p> <pre><code>class Item(models.Model): class Meta: verbose_name_plural = 'Items' name = models.CharField(max_length=30, null=True, blank=True) def __str__(self): return self.name class Select(models.Model): item = models.ForeignKey('Item', null=True, blank=True, on_delete=models.SET_NULL) name = models.CharField(max_length=30, null=True, blank=True) def __str__(self): return self.name </code></pre> <p>Basically, Item is a category. Entries in the Select table reference Item as a category, Item can be either 'metrics', 'consumption' or 'demographics'. I want to retrieve all of the entries from the table Select which are in the 'demographics' category.</p> <p>I have the following code:</p> <pre><code>list-to-pass = Select.objects.filter(item__name='demographics').values() </code></pre> <p>This returns the following:</p> <pre><code>&lt;QuerySet [{'id': 1, 'item_id': 3, 'name': 'Age Breakdown'}, {'id': 2, 'item_id': 3, 'name': 'Work Status'}, {'id': 3, 'item_id': 3, 'name': 'Occupation'}, {'id': 4, 'item_id': 3, 'name': 'Industry'}, {'id': 5, 'item_id': 3, 'name': 'Nationality'}, {'id': 6, 'item_id': 3, 'name': 'Education'}, {'id': 7, 'item_id': 3, 'name': 'Commuting'}, {'id': 8, 'item_id': 3, 'name': 'Leave Home'}, {'id': 9, 'item_id': 3, 'name': 'Travel Time'}, {'id': 10, 'item_id': 3, 'name': 'Car Ownership'}, {'id': 11, 'item_id': 3, 'name': 'Internet'}, {'id': 12, 'item_id': 3, 'name': 'Affluence'}]&gt; </code></pre> <p>but what I would like is something like:</p> <pre><code>['Age Breakdown','Work Status','Occupation','Industry','Nationality','Education','Communting', 'Leave Home','Travel Time', 'Car Ownership','Internet', 'Affluence'] </code></pre> <p>Thanks for any assitance you can offer.</p>
[ { "answer_id": 74349768, "author": "Nishesh Tyagi", "author_id": 19539370, "author_profile": "https://Stackoverflow.com/users/19539370", "pm_score": -1, "selected": false, "text": "print( , name + \"was planning a dream vacation to \" ,place +\".\",name+ \"was especially looking forward to trying the local cusine,including \",abj1+ ,food1+\"and \",food2)\n" }, { "answer_id": 74378220, "author": "The_spider", "author_id": 16490627, "author_profile": "https://Stackoverflow.com/users/16490627", "pm_score": 2, "selected": false, "text": "print( " } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19585980/" ]
74,349,677
<p>When I try to set the page to the default value from refresh function, it doesn't trigger the useEffect hook. But if I run the refresh function 2nd time it works fine. And this code also works fine for other values like 2, 3, 4, 5......</p> <pre class="lang-js prettyprint-override"><code> const [goal, setGoal] = useState(); const [page, setPage] = useState(1); const [temp, setTemp] = useState([]); useEffect(() =&gt; { setGoal(); getData(); }, [page]); const refresh = () =&gt; { setTemp([]); setPage(1); }; </code></pre>
[ { "answer_id": 74349944, "author": "JSEvgeny", "author_id": 6131368, "author_profile": "https://Stackoverflow.com/users/6131368", "pm_score": 0, "selected": false, "text": "const [counter, setCounter] = useState(0)\n\nconst refresh = () => setCounter(counter + 1)\n" }, { "answer_id": 74394124, "author": "Abdullah Manafikhi", "author_id": 16616472, "author_profile": "https://Stackoverflow.com/users/16616472", "pm_score": 0, "selected": false, "text": " const [refresh, setRefresh] = useState(false);\n\n useEffect(() => {\n setGoal();\n getData();\n }, [refresh]);\n\n //whenever you want to refresh just use this \n setRefresh(!refresh)\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11240893/" ]
74,349,702
<p>I am SQL native struggling with flux syntax (philosophy?) once again. Here is what I am trying to do: plot values of a certain measurement as a ratio of their historical average (say over the past month).</p> <p>Here is as far as I have gotten:</p> <pre><code>from(bucket: &quot;secret_bucket&quot;) |&gt; range(start: v.timeRangeStart, stop:v.timeRangeStop) |&gt; filter(fn: (r) =&gt; r._measurement == &quot;pg_stat_statements_fw&quot;) |&gt; group(columns: [&quot;query&quot;]) |&gt; aggregateWindow(every: v.windowPeriod, fn: sum) |&gt; timedMovingAverage(every: 1d, period: 30d) </code></pre> <p>I believe this produces an average over the past 30 days, for each day window. Now what I don't know how to do is divide the original data by these values in order to get the relative change, i.e. something like <code>value(_time)/tma_value(_time)</code>.</p>
[ { "answer_id": 74359015, "author": "Munin", "author_id": 18488955, "author_profile": "https://Stackoverflow.com/users/18488955", "pm_score": 0, "selected": false, "text": "t1 = from(bucket: \"secret_bucket\")\n |> range(start: v.timeRangeStart, stop:v.timeRangeStop)\n |> filter(fn: (r) => r._measurement == \"pg_stat_statements_fw\")\n |> group(columns: [\"query\"])\n |> aggregateWindow(every: v.windowPeriod, fn: sum)\n |> timedMovingAverage(every: 1d, period: 30d)\n |> duplicate(column: \"_stop\", as: \"_time\") \n \nt2 = from(bucket: \"secret_bucket\")\n |> range(start: v.timeRangeStart, stop:v.timeRangeStop)\n |> filter(fn: (r) => r._measurement == \"pg_stat_statements_fw\")\n\njoin(tables: {t1: t1, t2: t2}, on: [\"hereIsTheTagName\"])\n |> map(fn: (r) => ({r with _value: r._value_t2 / r._value_t1 * 100.0}))\n" }, { "answer_id": 74380369, "author": "Alexi Theodore", "author_id": 9819342, "author_profile": "https://Stackoverflow.com/users/9819342", "pm_score": 1, "selected": false, "text": "import \"date\"\n\nt1 = from(bucket: \"secret_bucket\")\n |> range(start: v.timeRangeStart, stop:v.timeRangeStop)\n |> filter(fn: (r) => r._measurement == \"pg_stat_statements_fw\")\n |> group(columns: [\"query\"])\n |> aggregateWindow(every: 1h, fn: sum)\n |> map(fn: (r) => ({r with window_value: float(v: r._value)}))\n \nt2 = from(bucket: \"secret_bucket\")\n |> range(start: date.sub(from: v.timeRangeStop, d: 45d), stop: v.timeRangeStop)\n |> filter(fn: (r) => r._measurement == \"pg_stat_statements_fw\")\n |> mean(column: \"_value\")\n |> group()\n |> map(fn: (r) => ({r with avg_value: r._value}))\n\n\njoin(tables: {t1: t1, t2: t2}, on: [\"query\"])\n |> map(fn: (r) => ({r with _value: (r.window_value - r.avg_value)/ r.avg_value * 100.0 }))\n |> keep(columns: [\"_value\", \"_time\", \"query\"])\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9819342/" ]
74,349,703
<p>I need an algorithm to quickly determine wether given 2D polygon arbitrarily translated intersects given rounded rectangle.</p> <p>We're given a polygon with N vertices and dimensions of the rounded rectangle (lenghts of sides and radius of corners). We would like to answer many question of type does the polygon with translation (dx,dy) intersect the rounded rectangle. We're allowed to do arbitrary precomputation on the polygon.</p> <p>When radius of the corners rectangle is 0, there is trivial constant time algorithm - it's enough to compute an AABB of the polygon, and then in few comparisons check if, after translation, it intersects the rectangle.</p> <p>When the radius is &gt;0 the problem seems much harder. The fact that there seems to be potentially an infinite number of &quot;bounding rounded rectangles&quot; suggests that there is no constant-time algorithm that can check for the intersection. But maybe I'm missing something.</p> <p>Do you know by any change any sublinear algorithm for checking if a polygon intersects a rounded rectangle?</p>
[ { "answer_id": 74350182, "author": "Nelfeal", "author_id": 3854570, "author_profile": "https://Stackoverflow.com/users/3854570", "pm_score": 1, "selected": false, "text": "x1" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1782685/" ]
74,349,728
<p>Clickhouse recently released the new <code>DELETE</code> query, that allows you to quickly mark data as deleted (<a href="https://clickhouse.com/docs/en/sql-reference/statements/delete/" rel="nofollow noreferrer">https://clickhouse.com/docs/en/sql-reference/statements/delete/</a>). The actual data deletion is done in the background afterwards, as is written in the docs.</p> <p>My question is, is there some indication to when data would be deleted? Or is there a way to make sure it gets deleted? I'm asking for GDPR compliance purposes.</p> <p>Thanks</p>
[ { "answer_id": 74475199, "author": "Slach", "author_id": 1204665, "author_profile": "https://Stackoverflow.com/users/1204665", "pm_score": 1, "selected": false, "text": "ALTER TABLE ... DELETE WHERE ..." }, { "answer_id": 74518371, "author": "yoel", "author_id": 1279019, "author_profile": "https://Stackoverflow.com/users/1279019", "pm_score": 1, "selected": true, "text": "OPTIMIZE FINAL" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1279019/" ]
74,349,759
<p>I have this expression:</p> <pre><code>echo '{&quot;foo&quot;:&quot;bar&quot;,&quot;boo&quot;:&quot;moo&quot;}' | jq -r '&quot;\(.foo)|\(.boo)&quot;' bar|moo </code></pre> <p>Now, imagine that the filter is long, so I would like to break it into separate lines for readability while still producing the same output, conceptually like this:</p> <pre><code>jq '&quot; \(.foo)| \(.boo) &quot;' </code></pre> <p>This however is not valid. How to do this?</p>
[ { "answer_id": 74349824, "author": "pmf", "author_id": 2158479, "author_profile": "https://Stackoverflow.com/users/2158479", "pm_score": 3, "selected": true, "text": "+" }, { "answer_id": 74351856, "author": "peak", "author_id": 997358, "author_profile": "https://Stackoverflow.com/users/997358", "pm_score": 2, "selected": false, "text": " map_values( \"\\(.)\" )\n | join(\"|\")\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1739713/" ]
74,349,761
<p>can someone maybe tell me a better way to loop through a df in Pyspark in my specific case. I am new to spark, so sorry for the question.</p> <p>What I am doing is selecting the value of the id column of the df where the song_name is null. I append these to a list and get the track_ids for these values. With these track_ids I make an API-Request to get the missing song_names and replace the null value at that index with the returned song_name.</p> <pre><code>missing_track_name = df.filter(df['track_name'].isNull()).select(df['ID']).collect() missing_list = [x[0] for x in missing_track_name] for i in missing_list: track_id = df.filter(col('ID')==i).select(df.song_id).collect() url = 'https://api.spotify.com/v1/tracks/{0}'.format(track_id) request = requests.get(url, headers = header, params = {&quot;limit&quot; : 50}) data = request.json() df = df.withColumn(&quot;track_name&quot;, when(col(&quot;ID&quot;) == i, data['name']).otherwise(col(&quot;track_name&quot;))) df = df.withColumn(&quot;artist_name&quot;, when(col(&quot;ID&quot;) == i, data['artists'][0]['name']).otherwise(col(&quot;artist_name&quot;))) </code></pre> <p>Sample rows from my table are (the music is from a friends Spotify, not exactly my taste):</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">genre</th> <th style="text-align: left;">artist_name</th> <th style="text-align: left;">track_name</th> <th style="text-align: left;">track_id</th> <th style="text-align: left;">popularity</th> <th style="text-align: left;">acousticness</th> <th style="text-align: left;">danceability</th> <th style="text-align: left;">duration_ms</th> <th style="text-align: left;">energy</th> <th style="text-align: left;">instrumentalness</th> <th style="text-align: left;">liveness</th> <th style="text-align: left;">loudness</th> <th style="text-align: left;">speechiness</th> <th style="text-align: left;">tempo</th> <th style="text-align: left;">valence</th> <th style="text-align: left;">ID</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">R&amp;B</td> <td style="text-align: left;">Mary J. Blige</td> <td style="text-align: left;">Be Without You - Kendu Mix</td> <td style="text-align: left;">2YegxR5As7BeQuVp2U6pek</td> <td style="text-align: left;">65</td> <td style="text-align: left;">0.083</td> <td style="text-align: left;">0.724</td> <td style="text-align: left;">246333</td> <td style="text-align: left;">0.689</td> <td style="text-align: left;">0.0</td> <td style="text-align: left;">0.304</td> <td style="text-align: left;">-5.922</td> <td style="text-align: left;">0.135</td> <td style="text-align: left;">146.496</td> <td style="text-align: left;">0.693</td> <td style="text-align: left;">0</td> </tr> <tr> <td style="text-align: left;">R&amp;B</td> <td style="text-align: left;">Rihanna</td> <td style="text-align: left;">Desperado</td> <td style="text-align: left;">6KFaHC9G178beAp7P0Vi5S</td> <td style="text-align: left;">63</td> <td style="text-align: left;">0.323</td> <td style="text-align: left;">0.685</td> <td style="text-align: left;">186467</td> <td style="text-align: left;">0.61</td> <td style="text-align: left;">0.0</td> <td style="text-align: left;">0.102</td> <td style="text-align: left;">-5.221</td> <td style="text-align: left;">0.0439</td> <td style="text-align: left;">94.384</td> <td style="text-align: left;">0.323</td> <td style="text-align: left;">1</td> </tr> <tr> <td style="text-align: left;">R&amp;B</td> <td style="text-align: left;">Yung Bleu</td> <td style="text-align: left;">Ice On My Baby (feat. Kevin Gates) - Remix</td> <td style="text-align: left;">6muW8cSjJ3rusKJ0vH5olw</td> <td style="text-align: left;">62</td> <td style="text-align: left;">0.0675</td> <td style="text-align: left;">0.762</td> <td style="text-align: left;">199520</td> <td style="text-align: left;">0.52</td> <td style="text-align: left;">3.95e-06</td> <td style="text-align: left;">0.114</td> <td style="text-align: left;">-5.237</td> <td style="text-align: left;">0.0959</td> <td style="text-align: left;">75.047</td> <td style="text-align: left;">0.0862</td> <td style="text-align: left;">2</td> </tr> <tr> <td style="text-align: left;">R&amp;B</td> <td style="text-align: left;">Surfaces</td> <td style="text-align: left;">Heaven Falls / Fall on Me</td> <td style="text-align: left;">7yHqOZfsXYlicyoMt62yC6</td> <td style="text-align: left;">61</td> <td style="text-align: left;">0.36</td> <td style="text-align: left;">0.563</td> <td style="text-align: left;">240597</td> <td style="text-align: left;">0.366</td> <td style="text-align: left;">0.00243</td> <td style="text-align: left;">0.0955</td> <td style="text-align: left;">-6.896</td> <td style="text-align: left;">0.121</td> <td style="text-align: left;">85.352</td> <td style="text-align: left;">0.768</td> <td style="text-align: left;">3</td> </tr> <tr> <td style="text-align: left;">R&amp;B</td> <td style="text-align: left;">Olivia O'Brien</td> <td style="text-align: left;">Love Myself</td> <td style="text-align: left;">4XzgjxGKqULifVf7mnDIQK</td> <td style="text-align: left;">68</td> <td style="text-align: left;">0.596</td> <td style="text-align: left;">0.653</td> <td style="text-align: left;">213947</td> <td style="text-align: left;">0.621</td> <td style="text-align: left;">0.0</td> <td style="text-align: left;">0.0811</td> <td style="text-align: left;">-5.721</td> <td style="text-align: left;">0.0409</td> <td style="text-align: left;">100.006</td> <td style="text-align: left;">0.466</td> <td style="text-align: left;">4</td> </tr> </tbody> </table> </div>
[ { "answer_id": 74349824, "author": "pmf", "author_id": 2158479, "author_profile": "https://Stackoverflow.com/users/2158479", "pm_score": 3, "selected": true, "text": "+" }, { "answer_id": 74351856, "author": "peak", "author_id": 997358, "author_profile": "https://Stackoverflow.com/users/997358", "pm_score": 2, "selected": false, "text": " map_values( \"\\(.)\" )\n | join(\"|\")\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20172897/" ]
74,349,763
<h2>Background</h2> <p>I have a personal project that is an elixir desktop application for PC Windows. It works pretty well, but now I want to give it an icon.</p> <p>This is usually done in the following module:</p> <pre><code>defmodule WebInterface.Application do # See https://hexdocs.pm/elixir/Application.html # for more information on OTP Applications @moduledoc false use Application alias Desktop alias Manager alias WebInterface.{Endpoint, Telemetry} alias WebInterface.Live.MenuBar @impl true def start(_type, _args) do children = [ Telemetry, {Phoenix.PubSub, name: WebInterface.PubSub}, Endpoint, Manager, {Desktop.Window, [ app: :web_interface, id: WebInterface, title: &quot;Market Manager&quot;, size: {900, 960}, menubar: MenuBar, icon: &quot;static/images/resized_logo_4.png&quot;, # THIS IS WHERE THE ICON IS SET url: &amp;WebInterface.Endpoint.url/0 ]} ] opts = [strategy: :one_for_one, name: WebInterface.Supervisor] Supervisor.start_link(children, opts) end @impl true def config_change(changed, _new, removed) do WebInterface.Endpoint.config_change(changed, removed) :ok end end </code></pre> <h2>Problem</h2> <p>The issue here is that I have to use the same image for both the Windows taskbar and the top icon of the app:</p> <p><a href="https://i.stack.imgur.com/sEiwq.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sEiwq.jpg" alt="enter image description here" /></a></p> <p>The issue here is that while the logo on the bottom Windows bar (marked yellow) is nice, the one in the top is distorted and pretty horrible.</p> <p>The fix to this would be to have an icon for the bottom and one for the top. However after checking the <a href="https://github.com/elixir-desktop/desktop-example-app" rel="nofollow noreferrer">demo app</a> I didn't find a way of doing this.</p> <h2>Question</h2> <p>Is this possible to achieve? If so, how?</p>
[ { "answer_id": 74361898, "author": "VZ.", "author_id": 15275, "author_profile": "https://Stackoverflow.com/users/15275", "pm_score": 1, "selected": false, "text": "wxTopLevelWindow::SetIcons()" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1337392/" ]
74,349,766
<p>I have an array, and I want to insert a new element inside it, shifting all other elements to the right:</p> <pre><code>my @a = (2, 5, 4, 8, 1); # insert 42 into position no. 2 </code></pre> <p>Result expected:</p> <pre><code>(2, 5, 42, 4, 8, 1); </code></pre>
[ { "answer_id": 74349853, "author": "Steffen Ullrich", "author_id": 3081018, "author_profile": "https://Stackoverflow.com/users/3081018", "pm_score": 5, "selected": true, "text": "my @a = (2, 5, 4, 8, 1);\nsplice(@a, 2, 0, 42); # -> (2, 5, 42, 4, 8, 1)\n" }, { "answer_id": 74351727, "author": "Polar Bear", "author_id": 12313309, "author_profile": "https://Stackoverflow.com/users/12313309", "pm_score": -1, "selected": false, "text": "use strict;\nuse warnings;\nuse feature 'say';\n\nuse Data::Dumper;\n\nmy @arr = (2, 5, 4, 8, 1);\nmy $pos = 2;\nmy $val = 42;\n\nsay Dumper(\\@arr);\n\n@arr = (@arr[0..$pos-1],$val,@arr[$pos..$#arr]);\n\nsay Dumper(\\@arr);\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/187141/" ]
74,349,790
<p>I am using serverless for creating and deploying my lambda functions. I am using <code>Node.js - HTTP API</code> template from serverless. I have created few lambda functions and deployed them using command <code>sls deploy</code>. The functions were deployed successfully and I am able to query lambda function response using postman.</p> <p>But, when I want to invoke same lambda function through my React webapp (using axios) it is throwing me A <code>CORS Error</code> if I included any headers.</p> <p>For ex. I want to send <code>Authorization</code> token in header or <code>Content-type</code> as <code>json</code> in header. Any of this doesn't worked.</p> <p>After this, I have added following headers in my lambda function response</p> <pre class="lang-json prettyprint-override"><code> &quot;Access-Control-Allow-Origin&quot;: &quot;*&quot;, &quot;Access-Control-Allow-Credentials&quot;: true, </code></pre> <p>After this, in AWS API Gateway console, I have configured CORS with wildcard origin and allowed All HTTP methods. After deploying this setup It's still doesn't worked.</p> <p>I have also tried tweaking my <code>serverless.yml</code> file but my bad it didn't worked either</p>
[ { "answer_id": 74401403, "author": "Kaneki21", "author_id": 19514458, "author_profile": "https://Stackoverflow.com/users/19514458", "pm_score": 0, "selected": false, "text": "CORS" }, { "answer_id": 74406370, "author": "pgrzesik", "author_id": 3864176, "author_profile": "https://Stackoverflow.com/users/3864176", "pm_score": 0, "selected": false, "text": "provider:\n httpApi:\n cors: true\n" }, { "answer_id": 74418201, "author": "Sudarshan", "author_id": 10763750, "author_profile": "https://Stackoverflow.com/users/10763750", "pm_score": 2, "selected": true, "text": "serverless" }, { "answer_id": 74425978, "author": "user11666461", "author_id": 11666461, "author_profile": "https://Stackoverflow.com/users/11666461", "pm_score": 0, "selected": false, "text": "Access-Control-Allow-Credentials" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18468228/" ]
74,349,792
<p>I am writing a program rock-paper-scissors and I have a problem with a loop while which I solved with another loop if but I still wonder why it doesn't work(line 19, 71, 104; or just in functions game, game2, game3). I also want to ask if I can write this program better or use something more advance to write it shorter. Here is the code:</p> <pre><code>import random import time option = [&quot;rock&quot;, &quot;paper&quot;, &quot;scissors&quot;] your_score = 0 computer_score = 0 #functions def game(your_score, computer_score): print(&quot;ok, lets start&quot;) time.sleep(1) print(3) time.sleep(1) print(2) time.sleep(1) print(1) time.sleep(1) while your_score != 1 or computer_score != 1: if your_score == 2 or computer_score == 2: break user = int(input(&quot;What do you shoot?\n1.rock\n2.paper\n3.scissors\n&quot;)) computer = random.choice([1, 2, 3]) show(user, computer) if user == computer: print(&quot;it's a tie\n&quot;) elif is_win(user, computer): print(&quot;you won\n&quot;) your_score += 1 else: print(&quot;you lost\n&quot;) computer_score += 1 if your_score == 1: print(&quot;You won, gg&quot;) elif computer_score == 1: print(&quot;You lost, nt&quot;) def show(user, computer): if user == 1: print(f&quot;You: {option[0]}&quot;) elif user == 2: print(f&quot;You: {option[1]}&quot;) elif user == 3: print(f&quot;You: {option[2]}&quot;) if computer == 1: print(f&quot;Computer: {option[0]}&quot;) elif computer == 2: print(f&quot;Computer: {option[1]}&quot;) elif computer == 3: print(f&quot;Computer {option[2]}&quot;) def game2(your_score, computer_score): print(&quot;ok, lets start&quot;) time.sleep(1) print(3) time.sleep(1) print(2) time.sleep(1) print(1) time.sleep(1) while your_score != 2 or computer_score != 2: if your_score == 2 or computer_score == 2: break user = int(input(&quot;What do you shoot?\n1.rock\n2.paper\n3.scissors\n&quot;)) computer = random.choice([1, 2, 3]) show(user, computer) if user == computer: print(&quot;it's a tie\n&quot;) elif is_win(user, computer): print(&quot;you won\n&quot;) your_score += 1 else: print(&quot;you lost\n&quot;) computer_score += 1 if your_score == 2: print(&quot;You won, gg&quot;) elif computer_score == 2: print(&quot;You lost, nt&quot;) def game3(your_score, computer_score): print(&quot;ok, lets start&quot;) time.sleep(1) print(3) time.sleep(1) print(2) time.sleep(1) print(1) time.sleep(1) while your_score != 3 or computer_score != 3: if your_score == 3 or computer_score == 3: break user = int(input(&quot;What do you shoot?\n1.rock\n2.paper\n3.scissors\n&quot;)) computer = random.choice([1, 2, 3]) show(user, computer) if user == computer: print(&quot;it's a tie\n&quot;) elif is_win(user, computer): print(&quot;you won\n&quot;) your_score += 1 else: print(&quot;you lost\n&quot;) computer_score += 1 if your_score == 3: print(&quot;You won, gg&quot;) elif computer_score == 3: print(&quot;You lost, nt&quot;) def is_win(user, computer): if (user == 1 and computer == 3) or (user == 2 and computer == 1) or (user == 3 and computer ==2): return True def start(): s = () while s == &quot;yes&quot; or &quot;no&quot;: s = str(input(&quot;Are you ready?'yes' or 'no'\n&quot;)).lower() if s == &quot;yes&quot;: game(your_score, computer_score) break elif s == &quot;no&quot;: print(&quot;ok, I'll wait&quot;) time.sleep(1) print(3) time.sleep(1) print(2) time.sleep(1) print(1) print(&quot;You should be ready now&quot;) time.sleep(1) game(your_score, computer_score) break else: print(&quot;wrong insert, try again&quot;) def start2(): s = () while s == &quot;yes&quot; or &quot;no&quot;: s = str(input(&quot;Are you ready?'yes' or 'no'\n&quot;)).lower() if s == &quot;yes&quot;: game2(your_score, computer_score) break elif s == &quot;no&quot;: print(&quot;ok, I'll wait&quot;) time.sleep(1) print(3) time.sleep(1) print(2) time.sleep(1) print(1) print(&quot;You should be ready now&quot;) time.sleep(1) game2(your_score, computer_score) break else: print(&quot;wrong insert, try again&quot;) def start3(): s = () while s == &quot;yes&quot; or &quot;no&quot;: s = str(input(&quot;Are you ready?'yes' or 'no'\n&quot;)).lower() if s == &quot;yes&quot;: game3(your_score, computer_score) break elif s == &quot;no&quot;: print(&quot;ok, I'll wait&quot;) time.sleep(1) print(3) time.sleep(1) print(2) time.sleep(1) print(1) print(&quot;You should be ready now&quot;) time.sleep(1) game3(your_score, computer_score) break else: print(&quot;wrong insert, try again&quot;) def gamemode(): g_m = 1 while g_m == 1 or g_m == 2 or g_m == 3: print(&quot;1.The best of 1(up to 1 points)\n&quot;) print(&quot;2.The best of 3(up to 2 points)\n&quot;) print(&quot;3.The best of 5(up to 3 points)\n&quot;) try: g_m = int(input(&quot;Which one you want to play?\n&quot;)) if g_m == 1: start() break elif g_m == 2: start2() break elif g_m == 3: start3() break else: print(&quot;wrong insert\n&quot;) except ValueError: print() print(&quot;wrong value, try again\n&quot;) #actual program gamemode() </code></pre> <p>I tried messing with the loop, but it didn't work in the end, so I just put in another loop inside. The loops while in my thoughts should work until these variables don't have a certain value but I might be wrong about it. The program itself might be looking weird and long in a run but it was on purpose to train using a <code>time.sleep</code>. Thank you</p>
[ { "answer_id": 74350029, "author": "BokiX", "author_id": 16843389, "author_profile": "https://Stackoverflow.com/users/16843389", "pm_score": -1, "selected": false, "text": "import random\n\noptions = [\"rock\", \"paper\", \"scissors\"]\nyour_score = 0\ncomputer_score = 0\nmax_score = 3\nplaying = True\n\nwhile playing:\n your_option = input(f\"Options:\\n - {options[0]}\\n - {options[1]}\\n - {options[2]}\\nYour option: \")\n computer_option = random.choice(options)\n if your_option.lower() == 'rock':\n if computer_option == 'rock':\n print('Tie')\n elif computer_option == 'paper':\n print('Computer wins')\n computer_score += 1\n elif computer_option == 'scissors':\n print('You win')\n your_score += 1\n\n elif your_option.lower() == 'paper':\n if computer_option == 'rock':\n print('You win')\n your_score += 1\n elif computer_option == 'paper':\n print('Tie')\n elif computer_option == 'scissors':\n print('Computer wins')\n computer_score += 1\n\n elif your_option.lower() == 'scissors':\n if computer_option == 'rock':\n print('Computer wins')\n computer_score += 1\n elif computer_option == 'paper':\n print('You win')\n your_score += 1\n elif computer_option == 'scissors':\n print('Tie')\n\n else:\n print(\"Wrong input!\")\n\n # Checking if score is max score\n if your_score >= max_score:\n print(\"You won the game\")\n playing = False\n elif computer_score >= max_score:\n print(\"You lost the game\")\n playing = False\n\n" }, { "answer_id": 74350202, "author": "flakes", "author_id": 3280538, "author_profile": "https://Stackoverflow.com/users/3280538", "pm_score": 3, "selected": true, "text": "def print_countdown(count):\n while count > 0:\n time.sleep(1)\n print(count)\n count -= 1\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19720755/" ]
74,349,795
<p>I created an Azure Cognitive Search using a Cosmos DB SQL API database. I created the index and the indexer. My Cosmos DB database is refreshed daily. Hence, I created the indexer in my azure search to be refreshed on schedule. The problem I have now is my index. The index is duplicated and retrieves duplicate items. When I created my index I had 23,000 documents indexed and currently, I have 46,000 indexed items. My search results are duplicates. This is a production app at work, so your help is much appreciated.</p>
[ { "answer_id": 74350029, "author": "BokiX", "author_id": 16843389, "author_profile": "https://Stackoverflow.com/users/16843389", "pm_score": -1, "selected": false, "text": "import random\n\noptions = [\"rock\", \"paper\", \"scissors\"]\nyour_score = 0\ncomputer_score = 0\nmax_score = 3\nplaying = True\n\nwhile playing:\n your_option = input(f\"Options:\\n - {options[0]}\\n - {options[1]}\\n - {options[2]}\\nYour option: \")\n computer_option = random.choice(options)\n if your_option.lower() == 'rock':\n if computer_option == 'rock':\n print('Tie')\n elif computer_option == 'paper':\n print('Computer wins')\n computer_score += 1\n elif computer_option == 'scissors':\n print('You win')\n your_score += 1\n\n elif your_option.lower() == 'paper':\n if computer_option == 'rock':\n print('You win')\n your_score += 1\n elif computer_option == 'paper':\n print('Tie')\n elif computer_option == 'scissors':\n print('Computer wins')\n computer_score += 1\n\n elif your_option.lower() == 'scissors':\n if computer_option == 'rock':\n print('Computer wins')\n computer_score += 1\n elif computer_option == 'paper':\n print('You win')\n your_score += 1\n elif computer_option == 'scissors':\n print('Tie')\n\n else:\n print(\"Wrong input!\")\n\n # Checking if score is max score\n if your_score >= max_score:\n print(\"You won the game\")\n playing = False\n elif computer_score >= max_score:\n print(\"You lost the game\")\n playing = False\n\n" }, { "answer_id": 74350202, "author": "flakes", "author_id": 3280538, "author_profile": "https://Stackoverflow.com/users/3280538", "pm_score": 3, "selected": true, "text": "def print_countdown(count):\n while count > 0:\n time.sleep(1)\n print(count)\n count -= 1\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349795", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4788608/" ]
74,349,828
<p>I'd like to recode certain items in my data frame, those which contain an even number (N2, N4, N6, E2, etc.) For each value of these selected columns I'd like to apply <code>abs(x-6)</code> (see my function). Then I need an additional 2 columns with the means of items of the same category: mean(N) and mean(E) for each row.</p> <p>Example code:</p> <pre><code>df1 &lt;- tibble(id = 1:5, N1 = c(4,3,2,5,4), N2 = c(1,1,3,2,5), N3 = c(5,5,2,4,3), N4 = c(4,2,2,2,1), N5 = c(1,1,4,2,3), N6 = c(5,2,4,3,1), E1 = c(1,2,3,1,1), E2 = c(5,2,3,1,1), E3 = c(2,2,1,3,1), E4 = c(1,1,1,3,2), E5 = c(2,3,1,4,4), E6 = c(3,2,3,3,1)) </code></pre> <p>My function:</p> <pre><code>recode_items &lt;- function(reverse_items) { items &lt;- abs(reverse_items - 6) return(items) } </code></pre> <p>E.g.</p> <pre><code>recode_items(c(5,2,3,1,1)) [1] 1 4 3 5 5 </code></pre> <p>My code:</p> <pre><code>recoded_df1 &lt;- df1 |&gt; group_by(ends_with(c(&quot;2&quot;,&quot;4&quot;,&quot;6&quot;))) |&gt; group_modify(~ recode_items(.x)) |&gt; ungroup() |&gt; mutate(N = mean(N1:N6), E = mean(E1:E6)) </code></pre> <p>My code doesn't work, I get error messages for this line: <code>group_by(ends_with(c(&quot;2&quot;,&quot;4&quot;,&quot;6&quot;)))</code>. I tried many variants, including filter(), select(), select_at() etc.</p> <p>Thanks for your help!</p>
[ { "answer_id": 74350029, "author": "BokiX", "author_id": 16843389, "author_profile": "https://Stackoverflow.com/users/16843389", "pm_score": -1, "selected": false, "text": "import random\n\noptions = [\"rock\", \"paper\", \"scissors\"]\nyour_score = 0\ncomputer_score = 0\nmax_score = 3\nplaying = True\n\nwhile playing:\n your_option = input(f\"Options:\\n - {options[0]}\\n - {options[1]}\\n - {options[2]}\\nYour option: \")\n computer_option = random.choice(options)\n if your_option.lower() == 'rock':\n if computer_option == 'rock':\n print('Tie')\n elif computer_option == 'paper':\n print('Computer wins')\n computer_score += 1\n elif computer_option == 'scissors':\n print('You win')\n your_score += 1\n\n elif your_option.lower() == 'paper':\n if computer_option == 'rock':\n print('You win')\n your_score += 1\n elif computer_option == 'paper':\n print('Tie')\n elif computer_option == 'scissors':\n print('Computer wins')\n computer_score += 1\n\n elif your_option.lower() == 'scissors':\n if computer_option == 'rock':\n print('Computer wins')\n computer_score += 1\n elif computer_option == 'paper':\n print('You win')\n your_score += 1\n elif computer_option == 'scissors':\n print('Tie')\n\n else:\n print(\"Wrong input!\")\n\n # Checking if score is max score\n if your_score >= max_score:\n print(\"You won the game\")\n playing = False\n elif computer_score >= max_score:\n print(\"You lost the game\")\n playing = False\n\n" }, { "answer_id": 74350202, "author": "flakes", "author_id": 3280538, "author_profile": "https://Stackoverflow.com/users/3280538", "pm_score": 3, "selected": true, "text": "def print_countdown(count):\n while count > 0:\n time.sleep(1)\n print(count)\n count -= 1\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20229686/" ]
74,349,844
<p>Lets say I have text file containing n integers :</p> <pre><code>1 1 2 3 2 4 3 1 5 6 3 5 2 6 </code></pre> <p>How to program a function to print those integers without repeating them? My output should be :</p> <pre><code>1 2 3 4 5 6 </code></pre> <p>Note : Output should not be a text file.<br /> Note2 : File contains n integers.</p>
[ { "answer_id": 74349895, "author": "Visrut", "author_id": 15063341, "author_profile": "https://Stackoverflow.com/users/15063341", "pm_score": 0, "selected": false, "text": "set" }, { "answer_id": 74350025, "author": "Bhargav", "author_id": 15358800, "author_profile": "https://Stackoverflow.com/users/15358800", "pm_score": 0, "selected": false, "text": "with open('your_file.txt', 'r') as file:\n data = file.read().replace('\\n', '')\n\n##data ##\"11232.....\nno_repeats =\"\".join(set(data))\nno_repeats = int(no_repeats)\nprint(no_repeats)\n" }, { "answer_id": 74350064, "author": "Alberto Garcia", "author_id": 15647384, "author_profile": "https://Stackoverflow.com/users/15647384", "pm_score": 3, "selected": true, "text": "numbers.txt" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17321772/" ]
74,349,846
<p>I have a dataframe such as:</p> <pre><code>Groups Name Value G1 BLOC_Homo_sapiens 100 G1 BLOC_Chimpenzee 99 G1 BLOC_Bonobo 80 G1 Canis_lupus 20 G1 Danio_rerio 10 G2 BLOC_Homo_sapiens 30 G2 BLOC_Bonobo 29 G2 Mus_musculus 28 G2 Cules_pupiens 26 G3 BLOC_Gorrilla 300 G3 Cimex_lectularius 10 G3 Bombus_terrestris 9 </code></pre> <p>And I would like to add a new column called &quot;<code>diff_length</code>&quot; for each <code>Groups</code> where I subtract the highest <code>Value</code> of the <code>Name</code> containing the pattern &quot;<code>BLOC</code>&quot; against the highest Value of the <code>Name</code> which does not contain the pattern &quot;<code>BLOC</code>&quot;.</p> <p>For the <strong>Groups1</strong> for instance, the highest <code>Value</code> with the <strong>BLOC</strong> is 100, and the highest <code>Value</code> without <strong>BLOC</strong> is 20. So the result is <code>100-20 = 80</code>.</p> <p>I should then get:</p> <pre><code>Groups Name Value diff_length G1 BLOC_Homo_sapiens 100 80 G1 BLOC_Chimpenzee 99 80 G1 BLOC_Bonobo 80 80 G1 Canis_lupus 20 80 G1 Danio_rerio 10 80 G2 BLOC_Homo_sapiens 30 2 G2 BLOC_Bonobo 29 2 G2 Mus_musculus 28 2 G2 Cules_pupiens 26 2 G3 BLOC_Gorrilla 300 290 G3 Cimex_lectularius 10 290 G3 Bombus_terrestris 9 290 </code></pre>
[ { "answer_id": 74349899, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "m = df['Name'].str.contains('BLOC')\n\ndf['diff_length'] = (df.groupby('Groups')['Value']\n .transform(lambda d: d.where(m).max() - d.mask(m).max())\n )\n" }, { "answer_id": 74350062, "author": "Naveed", "author_id": 3494754, "author_profile": "https://Stackoverflow.com/users/3494754", "pm_score": 0, "selected": false, "text": "# identify rows that contains the block\nm1=df['Name'].str.contains('BLOC')\n\n# groupby on Groups and the rows that has BLOC and ones that don't\n# take the max for each (TRUE/FALSE) in a group, and take diff\ndf2=df.groupby(['Groups', m1 ] )['Value'].max().diff().reset_index()\n\n# create a dictionary\nd=dict(df2[df2['Name'].eq(True)][['Groups','Value']].values)\n\n# map difference back to the df\ndf['diff_length'] = df['Groups'].map(d)\ndf\n\n\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349846", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12559770/" ]
74,349,852
<p>My table structure is roughly as described <a href="https://stackoverflow.com/q/74339151/4070848">in this post</a>:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>name</th> <th style="text-align: center;">processed</th> <th style="text-align: center;">processing</th> <th>updated</th> <th>ref_time</th> </tr> </thead> <tbody> <tr> <td>abc</td> <td style="text-align: center;">t</td> <td style="text-align: center;">f</td> <td>27794395</td> <td>27794160</td> </tr> <tr> <td>def</td> <td style="text-align: center;">t</td> <td style="text-align: center;">f</td> <td>27794395</td> <td>27793440</td> </tr> <tr> <td>ghi</td> <td style="text-align: center;">t</td> <td style="text-align: center;">f</td> <td>27794395</td> <td>27793440</td> </tr> <tr> <td>jkl</td> <td style="text-align: center;">f</td> <td style="text-align: center;">f</td> <td>27794395</td> <td>27794160</td> </tr> <tr> <td>mno</td> <td style="text-align: center;">t</td> <td style="text-align: center;">f</td> <td>27794395</td> <td>27793440</td> </tr> <tr> <td>pqr</td> <td style="text-align: center;">f</td> <td style="text-align: center;">t</td> <td>27794395</td> <td>27794160</td> </tr> </tbody> </table> </div> <p>I created a <a href="https://dbfiddle.uk/gkZW8E8I" rel="nofollow noreferrer">dbfiddle</a> already based on this table structure (more on this below), so there is no need to create your own.</p> <p>Based on <a href="https://stackoverflow.com/a/74339507/4070848">this answer</a>, I am deriving a list of <code>ref_time</code> values to use as a basis for deleting 'old' entries from <code>status_table</code>:</p> <pre class="lang-sql prettyprint-override"><code>with ref as ( select ref_time from status_table group by ref_time having bool_and(processed) order by ref_time desc offset 1 ) delete from status_table s using ref r where s.ref_time = r.ref_time </code></pre> <p>But now I want to be more sophisticated about what I use as the <code>offset</code>... I would ideally like to keep the most recent <code>ref_time</code> for which all records are processed (as per the above example where <code>offset</code> is <code>1</code>), but the <em>two most recent</em> <code>ref_time</code> where the second <code>ref_time</code> has more associated records than the first (i.e. <code>offset</code> needs to be <code>2</code> to skip over the two most recent <code>ref_time</code>).</p> <p>I figure that the following query (based on <a href="https://stackoverflow.com/a/74331971/4070848">this answer</a>) will help in this task, because it counts the total number of <code>processed</code> records based on <code>ref_time</code>:</p> <pre class="lang-sql prettyprint-override"><code>select ref_time, count(*) cnt_total, count(*) filter(where processed) cnt_processed, round(avg(processed::int),2) ratio_processed from status_table group by ref_time order by ratio_processed desc, ref_time desc; </code></pre> <p>So in <a href="https://dbfiddle.uk/gkZW8E8I" rel="nofollow noreferrer">this dbfiddle</a> I'd need to preserve <code>ref_time=27794160</code> (rather than include it in the delete list as is the case in the example) because, although it is second, it also has a higher <code>cnt_total</code> than the first.</p> <p>In general, the rule is that I want to keep all <code>ref_time</code> up to (but not including) the <code>ref_time</code> having the same <code>cnt_total</code> as the one before (or less).</p>
[ { "answer_id": 74349899, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "m = df['Name'].str.contains('BLOC')\n\ndf['diff_length'] = (df.groupby('Groups')['Value']\n .transform(lambda d: d.where(m).max() - d.mask(m).max())\n )\n" }, { "answer_id": 74350062, "author": "Naveed", "author_id": 3494754, "author_profile": "https://Stackoverflow.com/users/3494754", "pm_score": 0, "selected": false, "text": "# identify rows that contains the block\nm1=df['Name'].str.contains('BLOC')\n\n# groupby on Groups and the rows that has BLOC and ones that don't\n# take the max for each (TRUE/FALSE) in a group, and take diff\ndf2=df.groupby(['Groups', m1 ] )['Value'].max().diff().reset_index()\n\n# create a dictionary\nd=dict(df2[df2['Name'].eq(True)][['Groups','Value']].values)\n\n# map difference back to the df\ndf['diff_length'] = df['Groups'].map(d)\ndf\n\n\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4070848/" ]
74,349,860
<p>I have a 32bit Software written in C# who Communicates with many different devices. Because of memory problems i upgraded to a 64bit System, no big Deal for the C# Software itself. But for some of the implemented devices i had to change the way of implementation, it worked for all expect for one! There i have a DLL which is written in C# 32bit, who is responsible for the communication to the device. Made by the supplier. I asked the supplier for a 64bit version but unfortunately its not possible for them to give me one.</p> <p>My Idea was to create an Wrapper to make the DLL available to my 64bit Software. I have seen that there are where many other people with a similar problem, but they always hat to Wrap an unmanaged DLL. So my tried to write an wrapper who use COM to get the work done. But failed while implementing the C# COM Server into my C# Client. Here is the Idea what is tried: <a href="https://www.stackoverflow.com/">https://blog.mattmags.com/2007/06/30/accessing-32-bit-dlls-from-64-bit-code/</a></p> <p>Another Idea was to use a open source Project who can this topic with DLLImports: <a href="https://www.stackoverflow.com/">https://github.com/CodefoundryDE/LegacyWrapper</a></p> <p>There i could load it with DLLImport but i could not find the EntryPoint to my needed functions. The question here is, if i'm completly on the wrong way and i can not load a managed DLL into C# with DLLImport or if i missed something and i just need to adjust the parameters. Here is the Code i used so far (i changed the Names of the DLL)</p> <pre><code> [LegacyDllImport(@&quot;C:\Program Files (x86)\Company\Device\API.dll&quot;)] public interface IClassA : IDisposable { [LegacyDllMethod(CallingConvention = CallingConvention.Winapi)] bool MethodA(); } </code></pre>
[ { "answer_id": 74349899, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "m = df['Name'].str.contains('BLOC')\n\ndf['diff_length'] = (df.groupby('Groups')['Value']\n .transform(lambda d: d.where(m).max() - d.mask(m).max())\n )\n" }, { "answer_id": 74350062, "author": "Naveed", "author_id": 3494754, "author_profile": "https://Stackoverflow.com/users/3494754", "pm_score": 0, "selected": false, "text": "# identify rows that contains the block\nm1=df['Name'].str.contains('BLOC')\n\n# groupby on Groups and the rows that has BLOC and ones that don't\n# take the max for each (TRUE/FALSE) in a group, and take diff\ndf2=df.groupby(['Groups', m1 ] )['Value'].max().diff().reset_index()\n\n# create a dictionary\nd=dict(df2[df2['Name'].eq(True)][['Groups','Value']].values)\n\n# map difference back to the df\ndf['diff_length'] = df['Groups'].map(d)\ndf\n\n\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20441954/" ]
74,349,871
<p>I created a C# code for logging error codes.</p> <p>I hardcoded the error codes into a class <code>RecordId</code> as <code>static int</code>s.</p> <pre><code>public class RecordId { public static int UnknownCommand = 100; public static int SoftwareVersion = 101; public static int WarningError = 110; public static int AbortError = 111; // etc... } </code></pre> <p>Having static int means that I can do <code>RecordId.SoftwareVersion</code> anywhere in my code, I don't actually need to instantiate the class RecordId, which is very convenient, since I want to be able to log things from different parts of the code by calling a Log class that also doesn't need instantiation (it just appends a message to a file)</p> <p>The logging function is also static, being something like</p> <pre><code>public class Logger { public static void LogExperiment(int key, string value) { // Append key and value to a hardcoded filename } } </code></pre> <p>Then from anywhere in my code I can do</p> <pre><code>Logger.LogExperiment(RecordId.SoftwareVersion, &quot;1.0&quot;); </code></pre> <p>This will just append <code>101 1.0</code> in a log file</p> <p>I don't need instances of the classes, so I can log anywhere from my code.</p> <p>Now, as the code grows, I don't want to modify the code every time I add a new <code>RecordId</code>, so I want to have a JSON file where I load the values into the class.</p> <p>I modified the RecordId class to look like:</p> <pre><code>public class RecordIdNew { public String UnknownCommand { get; set; } public String SoftwareVersion { get; set; } public String WarningError { get; set; } public String AbortError { get; set; } } </code></pre> <p>The problem I see now, is that in order to populate this values from the JSON file I have to instantiate the class RecordId, whereas before I was using the values as static ints, and therefore I could call <code>RecordId.SoftwareVersion</code></p> <p>The question (which might be a bit open) is: Is there a way I can keep RecordId not instantiated, but access values that come from a JSON file.</p> <p>Or if not possible, is there another structure that would allow me to do that?</p>
[ { "answer_id": 74350001, "author": "Dmitry Bychenko", "author_id": 2319407, "author_profile": "https://Stackoverflow.com/users/2319407", "pm_score": 1, "selected": false, "text": "// Let's have class being static if you don't want to create instances\npublic static class RecordId\n{\n // To be on the safer side of the road, let's have readonly fields:\n // once set in the static constructor they can't be changed\n public static readonly int UnknownCommand;\n public static readonly int SoftwareVersion;\n public static readonly int WarningError;\n public static readonly int AbortError;\n\n // Static constructor, it will be called before the first read of any field\n static RecordId() {\n //TODO: put your logic here: read the file and assign values to the fields\n }\n}\n" }, { "answer_id": 74350144, "author": "Kit", "author_id": 64348, "author_profile": "https://Stackoverflow.com/users/64348", "pm_score": 0, "selected": false, "text": "public static class RecordId\n{\n public static int UnknownCommand { get; private set; }\n public static int SoftwareVersion { get; private set; }\n public static int WarningError { get; private set; }\n public static int AbortError { get; private set; }\n // etc...\n\n [ModuleInitializer]\n public static void Init()\n {\n // code to read JSON\n // loop over JSON fields, matching them to\n // above fields, setting their values...\n }\n}\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20396240/" ]
74,349,884
<p>I have this simple grid:</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>.outGrid { display: grid; grid-gap: 40px; grid-template-columns: repeat(3, 1fr); } .item { width: 40px; height: 40px; background-color: grey; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class='outGrid'&gt; &lt;div class='item'&gt;&lt;/div&gt; &lt;div class='item'&gt;&lt;/div&gt; &lt;div class='item'&gt;&lt;/div&gt; &lt;div class='item'&gt;&lt;/div&gt; &lt;div class='item'&gt;&lt;/div&gt; &lt;div class='item'&gt;&lt;/div&gt; &lt;div class='item'&gt;&lt;/div&gt; &lt;div class='item'&gt;&lt;/div&gt; &lt;div class='item'&gt;&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>As you can see, I've defined the grid-gap to be 40px, but each grid item stretches horizontally as page width changes. I'd like the item to not stretch and simply occupy full space, so both vertical and horizontal gaps are 40px to form a nice 3*3 grid. How to achieve that?</p>
[ { "answer_id": 74350001, "author": "Dmitry Bychenko", "author_id": 2319407, "author_profile": "https://Stackoverflow.com/users/2319407", "pm_score": 1, "selected": false, "text": "// Let's have class being static if you don't want to create instances\npublic static class RecordId\n{\n // To be on the safer side of the road, let's have readonly fields:\n // once set in the static constructor they can't be changed\n public static readonly int UnknownCommand;\n public static readonly int SoftwareVersion;\n public static readonly int WarningError;\n public static readonly int AbortError;\n\n // Static constructor, it will be called before the first read of any field\n static RecordId() {\n //TODO: put your logic here: read the file and assign values to the fields\n }\n}\n" }, { "answer_id": 74350144, "author": "Kit", "author_id": 64348, "author_profile": "https://Stackoverflow.com/users/64348", "pm_score": 0, "selected": false, "text": "public static class RecordId\n{\n public static int UnknownCommand { get; private set; }\n public static int SoftwareVersion { get; private set; }\n public static int WarningError { get; private set; }\n public static int AbortError { get; private set; }\n // etc...\n\n [ModuleInitializer]\n public static void Init()\n {\n // code to read JSON\n // loop over JSON fields, matching them to\n // above fields, setting their values...\n }\n}\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8720421/" ]
74,349,889
<p>hi i want to fire a scroll tag in all pages of my website except homepage with regular expressions in tag manager. in this question homepage url means &quot;site.com&quot; and not means &quot;site.com/home.html&quot; thanks for helping.</p> <p>trying regex in tag manager</p>
[ { "answer_id": 74350001, "author": "Dmitry Bychenko", "author_id": 2319407, "author_profile": "https://Stackoverflow.com/users/2319407", "pm_score": 1, "selected": false, "text": "// Let's have class being static if you don't want to create instances\npublic static class RecordId\n{\n // To be on the safer side of the road, let's have readonly fields:\n // once set in the static constructor they can't be changed\n public static readonly int UnknownCommand;\n public static readonly int SoftwareVersion;\n public static readonly int WarningError;\n public static readonly int AbortError;\n\n // Static constructor, it will be called before the first read of any field\n static RecordId() {\n //TODO: put your logic here: read the file and assign values to the fields\n }\n}\n" }, { "answer_id": 74350144, "author": "Kit", "author_id": 64348, "author_profile": "https://Stackoverflow.com/users/64348", "pm_score": 0, "selected": false, "text": "public static class RecordId\n{\n public static int UnknownCommand { get; private set; }\n public static int SoftwareVersion { get; private set; }\n public static int WarningError { get; private set; }\n public static int AbortError { get; private set; }\n // etc...\n\n [ModuleInitializer]\n public static void Init()\n {\n // code to read JSON\n // loop over JSON fields, matching them to\n // above fields, setting their values...\n }\n}\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349889", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11025738/" ]
74,349,898
<p>I got the result of a query, and want to join it with a mockup table to fill the rows up to a certain number. this is an example where the query has two rows as result, but i always want that to fill it up to 5 (see column <em>slot</em>)</p> <pre><code>SELECT * FROM foo WHERE … </code></pre> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>foo</th> <th>bar</th> </tr> </thead> <tbody> <tr> <td>jhkl</td> <td>jol</td> </tr> <tr> <td>das</td> <td>das</td> </tr> </tbody> </table> </div> <p>result:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>slot</th> <th>foo</th> <th>bar</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>jhkl</td> <td>jol</td> </tr> <tr> <td>2</td> <td>das</td> <td>das</td> </tr> <tr> <td>3</td> <td><em>NULL</em></td> <td><em>NULL</em></td> </tr> <tr> <td>4</td> <td><em>NULL</em></td> <td><em>NULL</em></td> </tr> <tr> <td>5</td> <td><em>NULL</em></td> <td><em>NULL</em></td> </tr> </tbody> </table> </div> <p>You help is highly appreciated!</p>
[ { "answer_id": 74350009, "author": "The Impaler", "author_id": 6436191, "author_profile": "https://Stackoverflow.com/users/6436191", "pm_score": 2, "selected": false, "text": "with recursive g (n) as (select 1 union all select n + 1 from g where n < 5)\nselect g.n as slot, x.foo, x.bar\nfrom g\nleft join (select t.*, row_number() over() as rn from t) x on x.rn = g.n\n" }, { "answer_id": 74350492, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 1, "selected": false, "text": "select s.slot, f.foo, f.bar\nfrom \n(select @row:=0) as _init\ncross join (\n select 1 as slot union select 2 union select 3 union select 4 union select 5\n) as s\nleft outer join\n(\n select @row:=@row+1 as slot, foo, bar from foo\n) as f using (slot);\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/330658/" ]
74,349,908
<p>I would like to correct values in a df column based on results from another one. This first line gives me the correct version of km based on another df named 'correction'.</p> <pre><code>df['km_correct'] = df['task_object'].map(correction.set_index('task_object')['km_correct']) </code></pre> <p>Then I want to replace the current value of &quot;km&quot; with the corrected one only if the year is 2022 and the contact is 'A', 'B' or 'C'. So I'm using the following formula called correction_km:</p> <pre><code>def correction_km(row): if '2022' in row[&quot;year&quot;] and (&quot;A&quot; in row[&quot;Contacts&quot;] or &quot;B&quot; in row[&quot;Contacts&quot;] or &quot;C&quot; in row[&quot;Contacts&quot;]): return row['km_correct'] else: return row['km'] </code></pre> <p>However when I'm trying to apply the formula to my df on the column km as such:</p> <pre><code>df['km'] = df.apply(correction_km, axis=1) </code></pre> <p>I'm getting the error message:</p> <pre><code>TypeError: argument of type 'float' is not iterable </code></pre> <p>Can anyone help? Thank you!</p>
[ { "answer_id": 74350009, "author": "The Impaler", "author_id": 6436191, "author_profile": "https://Stackoverflow.com/users/6436191", "pm_score": 2, "selected": false, "text": "with recursive g (n) as (select 1 union all select n + 1 from g where n < 5)\nselect g.n as slot, x.foo, x.bar\nfrom g\nleft join (select t.*, row_number() over() as rn from t) x on x.rn = g.n\n" }, { "answer_id": 74350492, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 1, "selected": false, "text": "select s.slot, f.foo, f.bar\nfrom \n(select @row:=0) as _init\ncross join (\n select 1 as slot union select 2 union select 3 union select 4 union select 5\n) as s\nleft outer join\n(\n select @row:=@row+1 as slot, foo, bar from foo\n) as f using (slot);\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17748067/" ]
74,349,913
<p>After using value_counts in Pandas I want to reset the index but the first column's name is replace with 'index' and every columns' name got pushed to the right</p> <pre><code>df = df[df['type']=='food']['fruit'].value_counts() df = df.reset_index() df index fruit 0 apple 120 1 grape 110 2 orange 30 </code></pre> <p>maybe I can use df.columns to rename colums but is there anyway to prevent 'index' replacing fist column's name? this is what i want</p> <pre><code> fruit number 0 apple 120 1 grape 110 2 orange 30 </code></pre>
[ { "answer_id": 74350009, "author": "The Impaler", "author_id": 6436191, "author_profile": "https://Stackoverflow.com/users/6436191", "pm_score": 2, "selected": false, "text": "with recursive g (n) as (select 1 union all select n + 1 from g where n < 5)\nselect g.n as slot, x.foo, x.bar\nfrom g\nleft join (select t.*, row_number() over() as rn from t) x on x.rn = g.n\n" }, { "answer_id": 74350492, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 1, "selected": false, "text": "select s.slot, f.foo, f.bar\nfrom \n(select @row:=0) as _init\ncross join (\n select 1 as slot union select 2 union select 3 union select 4 union select 5\n) as s\nleft outer join\n(\n select @row:=@row+1 as slot, foo, bar from foo\n) as f using (slot);\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20423918/" ]
74,349,927
<h1>Any Idea whats the best way of getting this xml file into a data frame format in R. It can be any format tbl, data.table...</h1> <p>The xml file is under this link</p> <p><a href="https://www.ictax.admin.ch/extern/api/download/2619327/ea428026a27f772d57efbbcdc56bff62/kursliste_2022.zip" rel="nofollow noreferrer">https://www.ictax.admin.ch/extern/api/download/2619327/ea428026a27f772d57efbbcdc56bff62/kursliste_2022.zip</a></p> <p>I tried with the following code but it doesnt work:</p> <pre><code>result &lt;- xmlParse(file = &quot;kursliste_2022.xml&quot;) xml_result &lt;- xmlToList(result) xml_structure(xml_result) </code></pre>
[ { "answer_id": 74350009, "author": "The Impaler", "author_id": 6436191, "author_profile": "https://Stackoverflow.com/users/6436191", "pm_score": 2, "selected": false, "text": "with recursive g (n) as (select 1 union all select n + 1 from g where n < 5)\nselect g.n as slot, x.foo, x.bar\nfrom g\nleft join (select t.*, row_number() over() as rn from t) x on x.rn = g.n\n" }, { "answer_id": 74350492, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 1, "selected": false, "text": "select s.slot, f.foo, f.bar\nfrom \n(select @row:=0) as _init\ncross join (\n select 1 as slot union select 2 union select 3 union select 4 union select 5\n) as s\nleft outer join\n(\n select @row:=@row+1 as slot, foo, bar from foo\n) as f using (slot);\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19616974/" ]
74,349,955
<p>I am trying to change the hours in my <code>React</code> app using the <code>setHours</code> method:</p> <pre class="lang-js prettyprint-override"><code>function App() { let currHour = new Date().setHours(15); return ( &lt;div&gt; &lt;h1&gt;{currHour}&lt;/h1&gt; &lt;/div&gt; ); } </code></pre> <p>Instead of getting 15 as my output I am getting is: <strong>1667813785897</strong>.</p> <p>How I am getting this unexpected output?</p>
[ { "answer_id": 74350002, "author": "Zeke Hernandez", "author_id": 6014489, "author_profile": "https://Stackoverflow.com/users/6014489", "pm_score": 1, "selected": false, "text": "currHour" }, { "answer_id": 74377332, "author": "Lajos Arpad", "author_id": 436560, "author_profile": "https://Stackoverflow.com/users/436560", "pm_score": 1, "selected": true, "text": "setHours" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11409898/" ]
74,349,977
<p>I'm using Prismic and NextJS for the first time.</p> <p>What I'm trying to is make it so when the user goes to the base url for the page localhost:3000/ in dev something will load. /About and /Pricing are working fine the base url doesn't work.</p> <pre><code>import { GetStaticPaths, GetStaticProps } from 'next' import { SliceZone } from '@prismicio/react' import * as prismicH from &quot;@prismicio/helpers&quot;; import { createClient, linkResolver } from '../../prismicio' import { components } from '../../slices' interface HomePageProps { page: any } const HomePage = (props:HomePageProps) =&gt; { return &lt;SliceZone slices={props.page.data.slices} components={components} /&gt; } export default HomePage interface HomePageStaticProps { params: any previewData:any } export async function getStaticProps(props:HomePageStaticProps) { console.log(&quot;DOES NOT FIRE FOR localhost:3000&quot;) const client = createClient({ previewData:props.previewData }) const params = props.params; const uid = params?.pagePath?.[params.pagePath.length - 1] || &quot;home&quot;; const page = await client.getByUID(&quot;page&quot;, uid); return { props: { page, }, } } export const getStaticPaths: GetStaticPaths = async () =&gt; { const client = createClient(); const pages = await client.getAllByType(&quot;page&quot;); const paths = pages.map((page) =&gt; prismicH.asLink(page, linkResolver)) as string[]; console.log(paths) // [ '/pricing', '/about', '/' ] return { paths, fallback: false, }; } </code></pre> <p>or to simplify it further</p> <p>[[...pagePath]].tsx fails when going to localhost:3000/ but does not fail on localhost:3000/about or localhost:3000/pricing.</p> <pre><code>import { GetStaticPaths, GetStaticProps } from 'next' interface HomePageProps { page: string } const HomePage = (props:HomePageProps) =&gt; { return &lt;&gt;{props.page}&lt;/&gt; } export default HomePage interface HomePageStaticProps { params: any previewData:any } export async function getStaticProps(props:HomePageStaticProps) { const params = props.params; const uid = params?.pagePath?.[params.pagePath.length - 1] || &quot;home&quot;; //const page = await client.getByUID(&quot;page&quot;, uid); return { props: { page:uid, }, } } export const getStaticPaths: GetStaticPaths = async () =&gt; { const paths = [ '/pricing', '/about', '/' ]; return { paths, fallback: false, }; } </code></pre>
[ { "answer_id": 74350455, "author": "Marcel Dz", "author_id": 12186851, "author_profile": "https://Stackoverflow.com/users/12186851", "pm_score": 1, "selected": false, "text": "dev" }, { "answer_id": 74350619, "author": "Some Guy Trying To Do Math", "author_id": 315684, "author_profile": "https://Stackoverflow.com/users/315684", "pm_score": 1, "selected": true, "text": "const config = {\n reactStrictMode: true,\n swcMinify: true,\n i18n: {\n locales: [\"en\"],\n defaultLocale: \"en\",\n },\n};\nexport default config;\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74349977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/315684/" ]
74,350,037
<p>I'm a Bash newbie, and I'm puzzling through a Bash script where I see this:</p> <pre><code>while [ $# -ge 2 ] if [ &quot;x$1&quot; = &quot;x-a&quot; ]; then echo &quot;STR_A = $2&quot; &gt;&gt;tmpFile.txt ...do more stuff... elif [ &quot;x$1&quot; = &quot;x-b&quot; ]; then echo &quot;STR_B = $2&quot; &gt;&gt;tmpFile.txt ...do more stuff... else usage done </code></pre> <p>The script takes in four (or five?) command line arguments, and that <code>usage</code> function is:</p> <pre><code>usage() { echo &quot;usage: myscript -a STR_A | -b STR_B&quot; 1&gt;&amp;2 exit 1 } </code></pre> <p>So suppose I ran the script like this:</p> <pre><code>me@ubuntu1:~$./myscript -A apple -B banana </code></pre> <p>I'm guessing that this code processes the script's command line arguments. I think that the outer <code>while()</code> loop steps through the command line arguments after argument 1, which would be <code>myscript</code>. The inner <code>if()</code> statements check to see an <code>-a</code> or <code>-b</code> flag is used to supply arguments, and then records the text string that follows in <code>tmpFile.txt</code>. Anything outside of those parameters is rejected and the script exits.</p> <p>A lot of these assumptions rest on the bet that the outer <code>while()</code> loop...</p> <pre><code>while [ $# -ge 2 ] </code></pre> <p>...means &quot;<em>parse the BASH argv[] after the first argument</em>&quot;, (to put this in C terms.) If that's not a correct assumption, then I have no idea what's going on here. Any feedback is appreciated, thank you!</p>
[ { "answer_id": 74350455, "author": "Marcel Dz", "author_id": 12186851, "author_profile": "https://Stackoverflow.com/users/12186851", "pm_score": 1, "selected": false, "text": "dev" }, { "answer_id": 74350619, "author": "Some Guy Trying To Do Math", "author_id": 315684, "author_profile": "https://Stackoverflow.com/users/315684", "pm_score": 1, "selected": true, "text": "const config = {\n reactStrictMode: true,\n swcMinify: true,\n i18n: {\n locales: [\"en\"],\n defaultLocale: \"en\",\n },\n};\nexport default config;\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74350037", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4040743/" ]
74,350,044
<p>I have a worksheet that I need to save with the active sheet name, a cell and the date.</p> <pre><code>Sub PrintToPDF() ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _ Filename:=&quot;P:\Estimating Misc\EXPERIMENTS\&quot; + ActiveSheet.Name + &quot; &amp; &quot;RANGE(&quot;F18:J18&quot;) &amp; FORMAT(&quot;DATE,DD.MM.YYYY&quot;)&quot;.PDF&quot;, _ IGNOREPRINTAREAS:=False, _ OPENAFTERPUBLISH:=True End Sub </code></pre> <p>I am super new to VBA so this is a collection of what I've found online. What am I missing?</p>
[ { "answer_id": 74350455, "author": "Marcel Dz", "author_id": 12186851, "author_profile": "https://Stackoverflow.com/users/12186851", "pm_score": 1, "selected": false, "text": "dev" }, { "answer_id": 74350619, "author": "Some Guy Trying To Do Math", "author_id": 315684, "author_profile": "https://Stackoverflow.com/users/315684", "pm_score": 1, "selected": true, "text": "const config = {\n reactStrictMode: true,\n swcMinify: true,\n i18n: {\n locales: [\"en\"],\n defaultLocale: \"en\",\n },\n};\nexport default config;\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74350044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20409014/" ]
74,350,054
<p>I have a long string and I want to break that long string into 128 words of pair of arrays. for example. a string has 500 words. then the final output should be an array of 3 element</p> <p>element has the first 128 words, the second element has the next 128 words, and the third element should have the rest of the words.</p> <p>I have tried a lot of ways but didn't work for me. please help me out if anyone knows it</p> <p>thanks in advance.</p>
[ { "answer_id": 74350582, "author": "jessica-98", "author_id": 20261328, "author_profile": "https://Stackoverflow.com/users/20261328", "pm_score": 2, "selected": true, "text": "const string = \"hello world hello world hello world \"\nconst words = string.split(\" \")\n\n\nfunction sliceIntoChunks(arr, chunkSize) {\n const noEmptyStrsArr = arr.filter(item => item.length > 0)\n\n const res = [];\n for (let i = 0; i < noEmptyStrsArr.length; i += chunkSize) {\n const chunk = noEmptyStrsArr.slice(i, i + chunkSize);\n res.push(chunk);\n }\n return res;\n}\n\nconsole.log(sliceIntoChunks(words, 2))" }, { "answer_id": 74351599, "author": "akshay Tiwari", "author_id": 5577670, "author_profile": "https://Stackoverflow.com/users/5577670", "pm_score": 0, "selected": false, "text": "const string = \"Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of \\\"de Finibus Bonorum et Malorum\\\" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, \\\"Lorem ipsum dolor sit amet..\\\", comes from a line in section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of \\\"de Finibus Bonorum et Malorum\\\" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum,\\\"Lorem ipsum dolor sit amet..\\\", comes from a line in section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of \"\nconst words = string.split(\" \")\n\n\nfunction sliceIntoChunks(arr, chunkSize) {\n const noEmptyStrsArr = arr.filter(item => item.length > 0)\n\n const res = [];\n for (let i = 0; i < noEmptyStrsArr.length; i += chunkSize) {\n const chunk = noEmptyStrsArr.slice(i, i + chunkSize);\n res.push(chunk);\n }\n return res;\n}\n\nvar res=sliceIntoChunks(words, 128)\n\nvar newArr=[]\nfor(let i=0;i<res.length;i++){\n/* for(let j=0;j<res[i].length;j++){\nnewArr.push()\n}*/\n\nnewArr.push(res[i].join(\" \"))\n\n}\n\nconsole.log(newArr)" }, { "answer_id": 74352447, "author": "Scott Sauyet", "author_id": 1243641, "author_profile": "https://Stackoverflow.com/users/1243641", "pm_score": 0, "selected": false, "text": "chunk" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74350054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5577670/" ]
74,350,059
<p>How do you remove all characters except the array of float values and sepparators(,)?</p> <p><code>&lt;Color (r=0.65, g=0.54, b=0.43)&gt;</code></p> <p>Into this: 0.65, 0.54, 0.43</p>
[ { "answer_id": 74350090, "author": "I'mahdi", "author_id": 1740577, "author_profile": "https://Stackoverflow.com/users/1740577", "pm_score": 0, "selected": false, "text": "regex" }, { "answer_id": 74350164, "author": "Alberto Garcia", "author_id": 15647384, "author_profile": "https://Stackoverflow.com/users/15647384", "pm_score": 1, "selected": false, "text": "import re\nnre = re.compile(r'*.(0\\.\\d\\d).*(0\\.\\d\\d).*(0\\.\\d\\d)')\nm = nre.match('<Color (r=0.65, g=0.54, b=0.43)>')\nprint(' ,'.join(m.groups()))\n==> 0.65 ,0.54 ,0.43\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74350059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11473424/" ]
74,350,061
<p>I got a vector <code>A &lt;- c(&quot;Tom; Jerry&quot;, &quot;Lisa; Marc&quot;)</code> and try to identity the number of occurrences of every name.</p> <p>I already used the code: <code>sort(table(unlist(strsplit(A, &quot;&quot;))), decreasing = TRUE)</code></p> <p>However, this code is only able to create output like this: <code>Tom; Jerry: 1 - Lisa; Marc: 1 </code></p> <p>I am looking for a way to count every name, despite the fact, that two names are present in one cell. Consequently, my preferred result would be:</p> <p>Tom: 1 Jerry: 1 Lisa: 1 Marc:1</p>
[ { "answer_id": 74350090, "author": "I'mahdi", "author_id": 1740577, "author_profile": "https://Stackoverflow.com/users/1740577", "pm_score": 0, "selected": false, "text": "regex" }, { "answer_id": 74350164, "author": "Alberto Garcia", "author_id": 15647384, "author_profile": "https://Stackoverflow.com/users/15647384", "pm_score": 1, "selected": false, "text": "import re\nnre = re.compile(r'*.(0\\.\\d\\d).*(0\\.\\d\\d).*(0\\.\\d\\d)')\nm = nre.match('<Color (r=0.65, g=0.54, b=0.43)>')\nprint(' ,'.join(m.groups()))\n==> 0.65 ,0.54 ,0.43\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74350061", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20331774/" ]
74,350,066
<p>I am looking for a method to create an array of numbers to label groups, based on the value of the 'number' column. If it's possible?</p> <p>With this abbreviated example DF:</p> <pre><code>number = [nan,nan,1,nan,nan,nan,2,nan,nan,3,nan,nan,nan,nan,nan,4,nan,nan] df = pd.DataFrame(columns=['number']) df = pd.DataFrame.assign(df, number=number) </code></pre> <p>Ideally I would like to make a new column, 'group', based on the int in column 'number' - so there would be effectively be array's of 1, ,2, 3, etc. FWIW, the DF is 1000's lines long, with sporadically placed int's.</p> <p>The result would be a new column, something like this:</p> <pre><code> number group 0 NaN 0 1 NaN 0 2 1.0 1 3 NaN 1 4 NaN 1 5 NaN 1 6 2.0 2 7 NaN 2 8 NaN 2 9 3.0 3 10 NaN 3 11 NaN 3 12 NaN 3 13 NaN 3 14 NaN 3 15 4.0 4 16 NaN 4 17 NaN 4 </code></pre> <p>All advice much appreciated!</p>
[ { "answer_id": 74350090, "author": "I'mahdi", "author_id": 1740577, "author_profile": "https://Stackoverflow.com/users/1740577", "pm_score": 0, "selected": false, "text": "regex" }, { "answer_id": 74350164, "author": "Alberto Garcia", "author_id": 15647384, "author_profile": "https://Stackoverflow.com/users/15647384", "pm_score": 1, "selected": false, "text": "import re\nnre = re.compile(r'*.(0\\.\\d\\d).*(0\\.\\d\\d).*(0\\.\\d\\d)')\nm = nre.match('<Color (r=0.65, g=0.54, b=0.43)>')\nprint(' ,'.join(m.groups()))\n==> 0.65 ,0.54 ,0.43\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74350066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3316115/" ]
74,350,079
<p>How to make = 2(there are two &quot;the&quot;)</p> <pre><code>import re text = &quot;there are a lot of the cats&quot; o = re.findall(&quot;the&quot;, text) print(o) def text(word): count = 0 for word in text: if &quot;ou&quot; in text: count += 1 return count print(count) print(i) </code></pre> <p>this code should return 2 (because there are 2 &quot;the&quot;)</p>
[ { "answer_id": 74350272, "author": "BokiX", "author_id": 16843389, "author_profile": "https://Stackoverflow.com/users/16843389", "pm_score": -1, "selected": false, "text": "text = input(\"Your text: \")\nwords_in_text = {}\nfor word in text.lower().split(\" \"):\n if word in words_in_text.keys():\n words_in_text[word] += 1\n else:\n words_in_text[word] = 1\n" }, { "answer_id": 74350292, "author": "Aaron", "author_id": 20442327, "author_profile": "https://Stackoverflow.com/users/20442327", "pm_score": 1, "selected": true, "text": "['the', 'the']" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74350079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20331691/" ]
74,350,089
<p>I have an <code>array(&quot;https&quot;, &quot;www&quot;, &quot;stackoverflow&quot;, &quot;com&quot;)</code></p> <pre><code>$search_array = array(&quot;https&quot;, &quot;www&quot;, &quot;stackoverflow&quot;, &quot;com&quot;); for ($i=0; $i &lt; count($search_array); $i++) { if ( $search_array[$i] == null || strtolower($search_array[$i]) == &quot;http&quot; &amp;&amp; count($search_array) &gt; 1 || strtolower($search_array[$i]) == &quot;https&quot; &amp;&amp; count($search_array) &gt; 1 || strtolower($search_array[$i]) == &quot;www&quot; &amp;&amp; count($search_array) &gt; 1 || strtolower($search_array[$i]) == &quot;com&quot; &amp;&amp; count($search_array) &gt; 1 ) unset($search_array[$i]); } die(print_r($search_array)); </code></pre> <p>I want the result <code>array(&quot;stackoverflow&quot;);</code>, but im getting the result <code>array(&quot;stackoverflow&quot;, &quot;com&quot;);</code> any idea?</p>
[ { "answer_id": 74350221, "author": "nevada_scout", "author_id": 492298, "author_profile": "https://Stackoverflow.com/users/492298", "pm_score": 1, "selected": false, "text": "echo $i" }, { "answer_id": 74350260, "author": "Tim Lewis", "author_id": 3965631, "author_profile": "https://Stackoverflow.com/users/3965631", "pm_score": 2, "selected": true, "text": "unset()" }, { "answer_id": 74350262, "author": "arkascha", "author_id": 1248114, "author_profile": "https://Stackoverflow.com/users/1248114", "pm_score": 1, "selected": false, "text": "array_filter()" }, { "answer_id": 74350347, "author": "Salvino D'sa", "author_id": 16046521, "author_profile": "https://Stackoverflow.com/users/16046521", "pm_score": 0, "selected": false, "text": "<?php\n\n$search_array = array(\"https\", \"www\", \"stackoverflow\", \"com\");\n\nfor ($i=count($search_array)-1; $i>=0; $i--) { \n if ( in_array(strtolower($search_array[$i]), [\"https\", \"www\", \"com\"]) )\n unset($search_array[$i]);\n}\n\necho print_r($search_array, true);\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74350089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9498503/" ]
74,350,122
<p>I run subprocess in jupyter to get the core path. I have to go one folder up and then call pwd</p> <p>Running:</p> <pre><code>import subprocess mypath=subprocess.run(&quot;(cd .. &amp;&amp; pwd)&quot;) </code></pre> <p>leads to a &quot;No such file or directory: '(cd .. &amp;&amp; pwd)' error. I guess the cd calls a directory call.</p> <p>Can you help me out?</p>
[ { "answer_id": 74350288, "author": "Alberto Garcia", "author_id": 15647384, "author_profile": "https://Stackoverflow.com/users/15647384", "pm_score": 1, "selected": false, "text": "shell = True" }, { "answer_id": 74350790, "author": "Charles Duffy", "author_id": 14122, "author_profile": "https://Stackoverflow.com/users/14122", "pm_score": 3, "selected": true, "text": "subprocess" }, { "answer_id": 74352243, "author": "Amos Baker", "author_id": 4603318, "author_profile": "https://Stackoverflow.com/users/4603318", "pm_score": 0, "selected": false, "text": "import os.path\nos.path.split(os.getcwd())[0]\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74350122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6510273/" ]
74,350,130
<p>I am working on a React project and facing two problems.</p> <ol> <li>I have created an input field where I insert a value via a popover, but after that value is input, I am not able to add any more text to the input field. I have shown this with two images below <a href="https://i.stack.imgur.com/4mqFI.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4mqFI.jpg" alt="enter image description here" /></a></li> </ol> <p>From this popper, text is entered into the input field.</p> <p><a href="https://i.stack.imgur.com/jS6Ui.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jS6Ui.jpg" alt="enter image description here" /></a></p> <p>This is the input field, which I am not able to edit after the value is inserted. So this is the first problem I am facing.</p> <ol start="2"> <li>Now onto the second problem, which is that the alignment of the people list is not done in a proper manner. The Dropdown button &quot;Full Access&quot; is not in a straight line despite using <code>justify-content:space-between;</code> Again I am attaching an image for proper understanding. <a href="https://i.stack.imgur.com/78F6v.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/78F6v.jpg" alt="enter image description here" /></a></li> </ol> <p>So, this is the second problem I am facing. I am not attaching any code here as it was all in different files therefore I have upload the code <a href="https://codesandbox.io/p/github/adityaxrawal/Notion-Share-Widget/main?file=%2FREADME.md&amp;workspace=%257B%2522activeFileId%2522%253A%2522cla6zwlay000dl4iy1z4v6bri%2522%252C%2522openFiles%2522%253A%255B%2522%252FREADME.md%2522%255D%252C%2522sidebarPanel%2522%253A%2522EXPLORER%2522%252C%2522gitSidebarPanel%2522%253A%2522COMMIT%2522%252C%2522sidekickItems%2522%253A%255B%257B%2522type%2522%253A%2522PREVIEW%2522%252C%2522taskId%2522%253A%2522start%2522%252C%2522port%2522%253A3000%252C%2522key%2522%253A%2522cla6zxgmk008d356jtfdxrod3%2522%252C%2522isMinimized%2522%253Afalse%257D%255D%257D" rel="nofollow noreferrer">here</a>. It is upload on the codesandbox.io and I have also uploaded it on <a href="https://github.com/adityaxrawal/Notion-Share-Widget" rel="nofollow noreferrer">Github</a>. Please refer to the problem and help me out in this. P.S: If you could assist me in adding search functionality to the input field that takes a value from popper, that would be fantastic.</p>
[ { "answer_id": 74350289, "author": "Dishonered", "author_id": 6642927, "author_profile": "https://Stackoverflow.com/users/6642927", "pm_score": 1, "selected": false, "text": " const AddPersontoSearchBar=(val)=>{\n setValue(Value + ',' + val.name)\n setAnchorEl(null)\n }\n" }, { "answer_id": 74350860, "author": "Aditya Rawal", "author_id": 19447089, "author_profile": "https://Stackoverflow.com/users/19447089", "pm_score": 1, "selected": true, "text": " const AddPersontoSearchBar=(val)=>{\n setValue(Value + ',' + val.name)\n setAnchorEl(null)\n }\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74350130", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19447089/" ]
74,350,151
<p>I am developing an app for a set-top box and for debugging purposes, I would like to intercept the network traffic coming out from the box. I don't have an option in the setup box to set up a proxy address. If there was an option to set up a proxy, I could hook it to Charles and intercept and modify the request on HTTP.</p> <p>I have tried setting up a Hotspot on the Windows laptop and Charles only seems to intercept the requests from the main wifi network.</p> <p>I have a OpenWRT router if that helps. Thanks in advance.</p>
[ { "answer_id": 74350289, "author": "Dishonered", "author_id": 6642927, "author_profile": "https://Stackoverflow.com/users/6642927", "pm_score": 1, "selected": false, "text": " const AddPersontoSearchBar=(val)=>{\n setValue(Value + ',' + val.name)\n setAnchorEl(null)\n }\n" }, { "answer_id": 74350860, "author": "Aditya Rawal", "author_id": 19447089, "author_profile": "https://Stackoverflow.com/users/19447089", "pm_score": 1, "selected": true, "text": " const AddPersontoSearchBar=(val)=>{\n setValue(Value + ',' + val.name)\n setAnchorEl(null)\n }\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74350151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/553218/" ]
74,350,156
<p>If I don't give this program a voice command within aprox 3 seconds after &quot;listeng...&quot; is being prompted, I get the &quot;UnboundLocalError&quot; mentioned in the title.</p> <p>Looking for any advice on how to get the program to wait for my next voice command without shutting down. Sorry if stupid question, this is my first ever program.</p> <p>Program below:</p> <pre><code>import speech_recognition as sr import pyttsx3 import pywhatkit import datetime import wikipedia import pyjokes listener = sr.Recognizer() engine = pyttsx3.init() voices = engine.getProperty(&quot;voices&quot;) engine.setProperty(&quot;voice&quot;, voices[0].id) def talk(text): engine.say(text) engine.runAndWait() def take_command(): try: with sr.Microphone() as source: print(&quot;listening...&quot;) voice = listener.listen(source) command = listener.recognize_google(voice) if &quot;computer&quot; in command: command = command.replace(&quot;computer&quot;, &quot;&quot;) print(command) except: pass return command def run_alexa(): command = take_command() print(command) if &quot;play&quot; in command: song = command.replace(&quot;play&quot;, &quot;&quot;) talk(&quot;playing&quot; + song) pywhatkit.playonyt(song) elif &quot;time&quot; in command: time = datetime.datetime.now().strftime(&quot;%I:%M %p&quot;) talk(&quot;the current time is &quot; + time) elif &quot;tell me about&quot; in command: person = command.replace(&quot;tell me about&quot;, &quot;&quot;) info = wikipedia.summary(person, 1) talk(info) elif &quot;your favourite artist&quot; in command: talk(&quot;Mr worldwide aka pitbull&quot;) elif &quot;joke&quot; in command: talk(pyjokes.get_joke()) else: talk(&quot;what are you talking about willis&quot;) while True: run_alexa() </code></pre> <pre><code>Traceback (most recent call last): File &quot;/Users/Alex/Documents/vscode/Virtual assistant/main.py&quot;, line 90, in &lt;module&gt; run_alexa() File &quot;/Users/Alex/Documents/vscode/Virtual assistant/main.py&quot;, line 32, in run_alexa command = take_command() ^^^^^^^^^^^^^^ File &quot;/Users/Alex/Documents/vscode/Virtual assistant/main.py&quot;, line 29, in take_command return command ^^^^^^^ UnboundLocalError: cannot access local variable 'command' where it is not associated with a value </code></pre>
[ { "answer_id": 74350373, "author": "Tyler Bury", "author_id": 19739725, "author_profile": "https://Stackoverflow.com/users/19739725", "pm_score": 0, "selected": false, "text": "Ex: \n\ndef take_command():\n try:\n with sr.Microphone() as source:\n print('listening...')\n voice = listener.listen(source)\n command = listener.recognize_google(voice)\n if 'computer' in command:\n command = command.replace('computer', '')\n print(command)\n except:\n command = ''\n return command\n" }, { "answer_id": 74350377, "author": "AKX", "author_id": 51685, "author_profile": "https://Stackoverflow.com/users/51685", "pm_score": 1, "selected": false, "text": "take_command()" }, { "answer_id": 74350384, "author": "PirateNinjas", "author_id": 8237877, "author_profile": "https://Stackoverflow.com/users/8237877", "pm_score": 0, "selected": false, "text": "take_command" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74350156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20442179/" ]
74,350,194
<p>So i have list contains with 1 string.</p> <blockquote> <p>biner_pass = ['00001111000000000000111111111111<br /> 00001111111111111111000011111111 11111111111100000000000000000000<br /> 11111111111111110000111111111111']</p> </blockquote> <p>all i want is to <strong>remove the space</strong> and <strong>join all the binary</strong>.</p> <p>i was trying using <code>binerpass = ''.join(biner_pass.split(' '))</code> or <code>biner_pass.replace(&quot; &quot;, &quot;&quot;)</code> but it cannot work. so how to remove space?</p>
[ { "answer_id": 74350229, "author": "I'mahdi", "author_id": 1740577, "author_profile": "https://Stackoverflow.com/users/1740577", "pm_score": 1, "selected": false, "text": "replace" }, { "answer_id": 74350231, "author": "depperm", "author_id": 3462319, "author_profile": "https://Stackoverflow.com/users/3462319", "pm_score": 1, "selected": false, "text": "biner_pass = [b.replace(' ','') for b in biner_pass]\n" }, { "answer_id": 74350247, "author": "Alberto Garcia", "author_id": 15647384, "author_profile": "https://Stackoverflow.com/users/15647384", "pm_score": 3, "selected": true, "text": "biner_pass[0].replace(\" \", \"\")\n" }, { "answer_id": 74350311, "author": "Omer Dagry", "author_id": 15010874, "author_profile": "https://Stackoverflow.com/users/15010874", "pm_score": 0, "selected": false, "text": "binary" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74350194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19908082/" ]
74,350,213
<p>I am looping through entryIds stored in a dataframe (loaded from a csv file) and accessing the messages by dispatching win32com.client to access Outlook MAPI and save email attachments to a local directory using the below code. I also am storing the attachment name, path, and entryId in a new dataframe for later analysis.</p> <ul> <li>Outlook version: 2202 (Build 14931.20764)</li> <li>Pywin32 version: 227</li> <li>Python version: 3.7.1</li> </ul> <pre><code>df = pd.DataFrame(columns=['attName', 'path', 'entryId']) id = 1 for email in emailData.itertuples(): outlook = win32com.client.Dispatch(&quot;Outlook.Application&quot;).GetNamespace(&quot;MAPI&quot;) message = outlook.GetItemFromID(email.entryId) if message: receivedDate = message.ReceivedTime if message.Attachments.Count &gt; 0: for attachment in message.Attachments: if attachment.Type in {1,4,5}: if not attachment.DisplayName.endswith('.png') and not attachment.DisplayName.endswith('.jpg') and not attachment.DisplayName.endswith('.gif'): attName = str(attachment.DisplayName) print('\t Attachment: %s' % attachment.DisplayName) path = &quot;some directory\\%s\\%s&quot; % (receivedDate.year, attachment.DisplayName) attachment.SaveAsFile(path) #if I remove this line, the error no longer occurs attachment = None df.loc[id] = ([attName, str(path), email.entryId]) id += 1 attachments = None message.Close(1) outlook.Logoff() outlook = None </code></pre> <p>Once I have scanned 248 messages, I encounter the below error regardless of the particular message:</p> <pre><code> File &quot;C:\Anaconda3\envs\myenv\lib\site-packages\win32com\client\__init__.py&quot;, line 474, in __getattr__ return self._ApplyTypes_(*args) File &quot;C:\Anaconda3\envs\myenv\lib\site-packages\win32com\client\__init__.py&quot;, line 467, in _ApplyTypes_ self._oleobj_.InvokeTypes(dispid, 0, wFlags, retType, argTypes, *args), pywintypes.com_error: (-2147352567, 'Exception occurred.', (4096, 'Microsoft Outlook', 'Your server administrator has limited the number of items you can open simultaneously. Try closing messages you have opened or removing attachments and images from unsent messages you are composing.', None, 0, -2147220731), None) </code></pre> <p>I am able to isolate the error specifically to this line:</p> <pre><code>attachment.SaveAsFile(path) </code></pre> <p>If I remove this line, the error goes away and will continue scanning messages. I am not sure what is causing this error and I have tried various commands to close/remove references to the attachments by setting objects to None and using outlook.Logoff() for the namespace.</p> <p>Has anyone else encountered this issue or have any way to resolve it?</p> <p>UPDATE: After reading <a href="https://stackoverflow.com/users/1603351/eugene-astafiev">Eugene Astafiev</a>'s helpful suggestions, I've made some updates to my code to help show that the issue is specifically with the attachment.SaveAsFile(path) line. Unfortunately, I still receive the exact same error. Maybe I am not understanding how to release the objects? can anyone help further?</p> <pre><code>outlook = win32com.client.Dispatch(&quot;Outlook.Application&quot;).GetNamespace(&quot;MAPI&quot;) for email in emailData.itertuples(): message = outlook.GetItemFromID(email.entryId) if message: attachments = [] for attachment in list(message.Attachments): attachments.append(attachment) for attachment in attachments: attachType = int(attachment.Type) if attachType in {1,4,5}: attName = str(attachment.DisplayName) if not attName.endswith('.png') and not attName.endswith('.jpg') and not attName.endswith('.gif'): path = &quot;somedir\\%s&quot; % (attName) attachment.SaveAsFile(path) #Error disappears if this line is removed del attachment del path del attName del attachType del attachments message.Close(1) del message </code></pre>
[ { "answer_id": 74351403, "author": "Eugene Astafiev", "author_id": 1603351, "author_profile": "https://Stackoverflow.com/users/1603351", "pm_score": 0, "selected": false, "text": "outlook = win32com.client.Dispatch(\"Outlook.Application\").GetNamespace(\"MAPI\")\n\nfor email in emailData.itertuples():\n message = outlook.GetItemFromID(email.entryId)\n if message:\n" }, { "answer_id": 74390252, "author": "bbpandagrl92", "author_id": 14140211, "author_profile": "https://Stackoverflow.com/users/14140211", "pm_score": 1, "selected": false, "text": "if i == 245:\n outlook.Application.Quit()\n del outlook\n time.sleep(20)\n os.system('taskkill /im outlook.exe /f') #bit redundant but ensures task is closed\n time.sleep(30)\n openR = os.system('start outlook')\n time.sleep(120)\n outlook = win32com.client.Dispatch(\"Outlook.Application\").GetNamespace(\"MAPI\")\n i = 0\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74350213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14140211/" ]
74,350,234
<p>The following question was asked in my last interview (yesterday), and I'm trying to solve it since then (couldn't solve it in the interview).</p> <p>Sorry for any grammar mistakes or any logical mistakes, I don't have the question, it was written by memory:</p> <blockquote> <p>You are given a number in a string format, for example: <code>&quot;14438832066&quot;</code>. You got to sum up the consecutive equal digits in that number. If no consecutive equal digit was found, just add the digit to the result.</p> <p><strong>for example:</strong> <code>solution(19938832066) =&gt; 11831632012</code></p> <p><strong>Explanation</strong>: first digit is <code>1</code>. The second and third digits are both <code>9</code> which means they will turn into <code>18</code> in the result string. So on with the rest of the digits (as you can see, the last 2 digits are both <code>6</code> which means they will turn into <code>12</code> in the result string).</p> <p><strong>You are required to do that for the result string as well, if needed, until no equal consecutive digits are found in the number.</strong></p> <p><strong>Example:</strong>: number: <code>14438832066</code> <code>solution( &quot;19938832066&quot;) -&gt;&quot;11831632012&quot; -&gt; &quot;2831632012&quot;</code> <strong>Explanation</strong>: first result is <code>11831632012</code>, but then you can see that there are still equal consecutive digits : the first and the second digits are both <code>1</code>. So process that number as well.</p> <p><strong>You are given a string and must return a string.</strong></p> </blockquote> <p><strong>My solution:</strong></p> <p>I couldn't write the solution, I don't know why. It's a pretty simple question, I thought going recursive at first but didn't want to complex things.</p> <p><strong>I wrote 2 helper methods:</strong></p> <ol> <li>one that returns a boolean whether the number consists of equal consecutive digits.</li> <li>one that actually makes the business logic:</li> </ol> <pre><code>turn the string into a char array create a counter that will count instances of the same digit - (int counter = 1). loop on the array from the first to the one before the last element : inside the loop: //equal digit was found - increment counter and continue to next digit if char[i] == char[i+1] then counter++ //calculation in case we are done counting the same digit else if counter &gt; 0 then result.append(counter*digit[i]) // if no consecutive equal digit was found else result.append(digit[i]) end loop: return result </code></pre> <p><strong>Problems I had:</strong></p> <ul> <li>I created the counter inside the loop, so each iteration it got rested. took me few minutes to realize.</li> <li>I had troubles realizing that 'int(digit[i])' doesn't give me the numeric value of the char, it gives the ASCII value. I had to use &quot;Character.getNumericValue&quot; (don't remember the exact name of the method).</li> </ul> <p>Because of these problems, it took me 45 minutes to write the solution which in the end didn't even work.</p> <p>I'll be glad to get a working solution, and even better - to get any feedback and tips on my solution and what, in your opinion, were my mistakes.</p> <p>Thank you.</p>
[ { "answer_id": 74357546, "author": "Matt Clarke", "author_id": 95469, "author_profile": "https://Stackoverflow.com/users/95469", "pm_score": -1, "selected": false, "text": "public String solve(String input)\n {\n String result = \"\";\n int i = 0;\n while (i < input.length())\n {\n var first = input.charAt(i);\n if (i == input.length() - 1){\n result += first;\n break;\n }\n var second = input.charAt(i + 1);\n if (first == second){\n result += (Character.getNumericValue(first) + Character.getNumericValue(second));\n i += 2;\n } else {\n result += first;\n i += 1;\n }\n }\n return result;\n }\n" }, { "answer_id": 74357782, "author": "Divyansh Singh", "author_id": 20430742, "author_profile": "https://Stackoverflow.com/users/20430742", "pm_score": 0, "selected": false, "text": "public static String addConsecutiveDigits(String number) {\n char[] arr = number.toCharArray();\n StringBuilder result = new StringBuilder();\n boolean foundConsecutive = false; // boolean flag for checking if the number contained consecutive equal digits\n for (int i = 0; i < arr.length; i++) {\n int digit = arr[i] - '0'; //Subtracting ascii values to get integer values\n int newNumber = digit;\n if (i != arr.length - 1) {\n int nextDigit = arr[i + 1] - '0';\n\n if (digit == nextDigit) { // check if the digits are consecutive digits\n newNumber = digit + nextDigit;\n i++; // increment i as we have already added the i+1 digit\n foundConsecutive = true;\n }\n } \n result.append(newNumber);\n }\n if (!foundConsecutive) // if no consecutive equal digits were found then return the result;\n return result.toString();\n else // recurse to check for more consecutive equal digits\n return addConsecutiveDigits(result.toString());\n}\n\n" }, { "answer_id": 74405651, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 0, "selected": false, "text": "String transform(String number) {\n while (true) {\n String result = collapse(number);\n if (result.equals(number)) return result;\n number = result;\n }\n}\n\nprivate static String collapse(String number) {\n StringBuilder result = new StringBuilder();\n for (idx = 0; idx < number.length(); ) {\n int mark = idx;\n int digit = digitAt(number, idx++);\n while (idx < number.length() && digitAt(number, idx) == digit) ++idx;\n result.append((idx - mark) * digit);\n }\n return result.toString();\n}\n\nprivate static int digitAt(String num, int index) {\n char ch = number.charAt(index);\n if (ch < '0' || ch > '9') throw new IllegalArgumentException();\n return ch - '0';\n}\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74350234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12769096/" ]
74,350,240
<p>i just made a problem which should return if a number &quot;isHappy&quot; or not. A number is happy if it meets some criteria:</p> <p>A happy number is a number defined by the following process:</p> <p>-Starting with any positive integer, replace the number by the sum of the squares of its digits. -Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. -Those numbers for which this process ends in 1 are happy.</p> <p>`</p> <pre><code>import java.util.HashSet; import java.util.Set; class Solution{ public int getNext(int n){ int totalSum = 0; while(n &gt; 0){ int last = n % 10; n = n / 10; totalSum += last * last; } return totalSum; } public boolean isHappy(int n){ Set&lt;Integer&gt; seen = new HashSet&lt;&gt;(); while( n!=1 &amp;&amp; !seen.contains(n)){ seen.add(n); n = getNext(n); } return n==1; } } class Main { public static void main(String[] args){ isHappy(23); //this doesnt work. } } </code></pre> <p>`</p> <p>I don't know how to call this function, tried different methods like int number = 23 for ex and then isHappy(number) sout(isHappy(number)); , number.isHappy() although this makes no sense, intellij is telling me to make a method inside main but i dont think i must do this, think there s another way.</p>
[ { "answer_id": 74357546, "author": "Matt Clarke", "author_id": 95469, "author_profile": "https://Stackoverflow.com/users/95469", "pm_score": -1, "selected": false, "text": "public String solve(String input)\n {\n String result = \"\";\n int i = 0;\n while (i < input.length())\n {\n var first = input.charAt(i);\n if (i == input.length() - 1){\n result += first;\n break;\n }\n var second = input.charAt(i + 1);\n if (first == second){\n result += (Character.getNumericValue(first) + Character.getNumericValue(second));\n i += 2;\n } else {\n result += first;\n i += 1;\n }\n }\n return result;\n }\n" }, { "answer_id": 74357782, "author": "Divyansh Singh", "author_id": 20430742, "author_profile": "https://Stackoverflow.com/users/20430742", "pm_score": 0, "selected": false, "text": "public static String addConsecutiveDigits(String number) {\n char[] arr = number.toCharArray();\n StringBuilder result = new StringBuilder();\n boolean foundConsecutive = false; // boolean flag for checking if the number contained consecutive equal digits\n for (int i = 0; i < arr.length; i++) {\n int digit = arr[i] - '0'; //Subtracting ascii values to get integer values\n int newNumber = digit;\n if (i != arr.length - 1) {\n int nextDigit = arr[i + 1] - '0';\n\n if (digit == nextDigit) { // check if the digits are consecutive digits\n newNumber = digit + nextDigit;\n i++; // increment i as we have already added the i+1 digit\n foundConsecutive = true;\n }\n } \n result.append(newNumber);\n }\n if (!foundConsecutive) // if no consecutive equal digits were found then return the result;\n return result.toString();\n else // recurse to check for more consecutive equal digits\n return addConsecutiveDigits(result.toString());\n}\n\n" }, { "answer_id": 74405651, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 0, "selected": false, "text": "String transform(String number) {\n while (true) {\n String result = collapse(number);\n if (result.equals(number)) return result;\n number = result;\n }\n}\n\nprivate static String collapse(String number) {\n StringBuilder result = new StringBuilder();\n for (idx = 0; idx < number.length(); ) {\n int mark = idx;\n int digit = digitAt(number, idx++);\n while (idx < number.length() && digitAt(number, idx) == digit) ++idx;\n result.append((idx - mark) * digit);\n }\n return result.toString();\n}\n\nprivate static int digitAt(String num, int index) {\n char ch = number.charAt(index);\n if (ch < '0' || ch > '9') throw new IllegalArgumentException();\n return ch - '0';\n}\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74350240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20167423/" ]
74,350,248
<p>I have a list where its elements are Timestamps in the form of</p> <pre><code>Timestamp(seconds=..., nanoseconds=...) </code></pre> <p>so I got</p> <pre><code>List myarr = [Timestamp(seconds=..., nanoseconds=...),Timestamp(seconds=..., nanoseconds=...),Timestamp(seconds=..., nanoseconds=...)] </code></pre> <p>How can I order this list? I have tried calling myarr.sort() but then I got the following error:</p> <p><em>This expression has a type of 'void' so its value can't be used. Try checking to see if you're using the correct API; there might be a function or call that returns void you didn't expect. Also check type parameters and variables which might also be void.</em></p> <p>How can I sort the above mentioned array?</p>
[ { "answer_id": 74357546, "author": "Matt Clarke", "author_id": 95469, "author_profile": "https://Stackoverflow.com/users/95469", "pm_score": -1, "selected": false, "text": "public String solve(String input)\n {\n String result = \"\";\n int i = 0;\n while (i < input.length())\n {\n var first = input.charAt(i);\n if (i == input.length() - 1){\n result += first;\n break;\n }\n var second = input.charAt(i + 1);\n if (first == second){\n result += (Character.getNumericValue(first) + Character.getNumericValue(second));\n i += 2;\n } else {\n result += first;\n i += 1;\n }\n }\n return result;\n }\n" }, { "answer_id": 74357782, "author": "Divyansh Singh", "author_id": 20430742, "author_profile": "https://Stackoverflow.com/users/20430742", "pm_score": 0, "selected": false, "text": "public static String addConsecutiveDigits(String number) {\n char[] arr = number.toCharArray();\n StringBuilder result = new StringBuilder();\n boolean foundConsecutive = false; // boolean flag for checking if the number contained consecutive equal digits\n for (int i = 0; i < arr.length; i++) {\n int digit = arr[i] - '0'; //Subtracting ascii values to get integer values\n int newNumber = digit;\n if (i != arr.length - 1) {\n int nextDigit = arr[i + 1] - '0';\n\n if (digit == nextDigit) { // check if the digits are consecutive digits\n newNumber = digit + nextDigit;\n i++; // increment i as we have already added the i+1 digit\n foundConsecutive = true;\n }\n } \n result.append(newNumber);\n }\n if (!foundConsecutive) // if no consecutive equal digits were found then return the result;\n return result.toString();\n else // recurse to check for more consecutive equal digits\n return addConsecutiveDigits(result.toString());\n}\n\n" }, { "answer_id": 74405651, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 0, "selected": false, "text": "String transform(String number) {\n while (true) {\n String result = collapse(number);\n if (result.equals(number)) return result;\n number = result;\n }\n}\n\nprivate static String collapse(String number) {\n StringBuilder result = new StringBuilder();\n for (idx = 0; idx < number.length(); ) {\n int mark = idx;\n int digit = digitAt(number, idx++);\n while (idx < number.length() && digitAt(number, idx) == digit) ++idx;\n result.append((idx - mark) * digit);\n }\n return result.toString();\n}\n\nprivate static int digitAt(String num, int index) {\n char ch = number.charAt(index);\n if (ch < '0' || ch > '9') throw new IllegalArgumentException();\n return ch - '0';\n}\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74350248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12917683/" ]
74,350,256
<p>My angular app is hosted on prod server on this url:</p> <pre><code>myserver/myapp </code></pre> <p>However on localhost its on default</p> <pre><code>localhost:4200 </code></pre> <p>The landing page is</p> <pre><code>&quot;/mainpage&quot; //(myserver/myapp/mainpage, or localhost:4200/mainpage) </code></pre> <p>I need to get the current page url (to save it as query parameter and redirect back after relogin on background), but I need only that one, that is configured in app-routing.module (/mainpage), and not the whole url. I tried</p> <pre><code>window.location.pathname </code></pre> <p>or</p> <pre><code>router.routerState.snapshot.url </code></pre> <p>but both are returing different values on dev or prod. on dev its correctly: <em>mainpage</em> but on prod, its: <em>myapp/mainpage</em>, and thus the redirection is wrong:</p> <pre><code>myserver/myapp/myapp/mainpage </code></pre> <p>It should be independend from the host server url:</p> <pre><code>/mainpage </code></pre>
[ { "answer_id": 74357546, "author": "Matt Clarke", "author_id": 95469, "author_profile": "https://Stackoverflow.com/users/95469", "pm_score": -1, "selected": false, "text": "public String solve(String input)\n {\n String result = \"\";\n int i = 0;\n while (i < input.length())\n {\n var first = input.charAt(i);\n if (i == input.length() - 1){\n result += first;\n break;\n }\n var second = input.charAt(i + 1);\n if (first == second){\n result += (Character.getNumericValue(first) + Character.getNumericValue(second));\n i += 2;\n } else {\n result += first;\n i += 1;\n }\n }\n return result;\n }\n" }, { "answer_id": 74357782, "author": "Divyansh Singh", "author_id": 20430742, "author_profile": "https://Stackoverflow.com/users/20430742", "pm_score": 0, "selected": false, "text": "public static String addConsecutiveDigits(String number) {\n char[] arr = number.toCharArray();\n StringBuilder result = new StringBuilder();\n boolean foundConsecutive = false; // boolean flag for checking if the number contained consecutive equal digits\n for (int i = 0; i < arr.length; i++) {\n int digit = arr[i] - '0'; //Subtracting ascii values to get integer values\n int newNumber = digit;\n if (i != arr.length - 1) {\n int nextDigit = arr[i + 1] - '0';\n\n if (digit == nextDigit) { // check if the digits are consecutive digits\n newNumber = digit + nextDigit;\n i++; // increment i as we have already added the i+1 digit\n foundConsecutive = true;\n }\n } \n result.append(newNumber);\n }\n if (!foundConsecutive) // if no consecutive equal digits were found then return the result;\n return result.toString();\n else // recurse to check for more consecutive equal digits\n return addConsecutiveDigits(result.toString());\n}\n\n" }, { "answer_id": 74405651, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 0, "selected": false, "text": "String transform(String number) {\n while (true) {\n String result = collapse(number);\n if (result.equals(number)) return result;\n number = result;\n }\n}\n\nprivate static String collapse(String number) {\n StringBuilder result = new StringBuilder();\n for (idx = 0; idx < number.length(); ) {\n int mark = idx;\n int digit = digitAt(number, idx++);\n while (idx < number.length() && digitAt(number, idx) == digit) ++idx;\n result.append((idx - mark) * digit);\n }\n return result.toString();\n}\n\nprivate static int digitAt(String num, int index) {\n char ch = number.charAt(index);\n if (ch < '0' || ch > '9') throw new IllegalArgumentException();\n return ch - '0';\n}\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74350256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1578893/" ]
74,350,271
<p>I have a function to check if the user is a staff:</p> <pre class="lang-py prettyprint-override"><code>class VerificateUser(): def allowed_user(request): if request.user.is_staff: return True </code></pre> <p>In my template, I’m going to show this section only for staff users, but this is not working.</p> <pre class="lang-html prettyprint-override"><code>{% url if not allowed_user %} &lt;h1&gt; Welcome to the show &lt;/h1&gt; </code></pre> <pre><code>If do something like it, works: ```html {% if not request.user.is_staff %} &lt;h1&gt; Welcome to the show &lt;/h1&gt; </code></pre> <p>But I need to use a view function to clean my code because I’m probably going to add more conditionals.</p> <pre><code></code></pre>
[ { "answer_id": 74357546, "author": "Matt Clarke", "author_id": 95469, "author_profile": "https://Stackoverflow.com/users/95469", "pm_score": -1, "selected": false, "text": "public String solve(String input)\n {\n String result = \"\";\n int i = 0;\n while (i < input.length())\n {\n var first = input.charAt(i);\n if (i == input.length() - 1){\n result += first;\n break;\n }\n var second = input.charAt(i + 1);\n if (first == second){\n result += (Character.getNumericValue(first) + Character.getNumericValue(second));\n i += 2;\n } else {\n result += first;\n i += 1;\n }\n }\n return result;\n }\n" }, { "answer_id": 74357782, "author": "Divyansh Singh", "author_id": 20430742, "author_profile": "https://Stackoverflow.com/users/20430742", "pm_score": 0, "selected": false, "text": "public static String addConsecutiveDigits(String number) {\n char[] arr = number.toCharArray();\n StringBuilder result = new StringBuilder();\n boolean foundConsecutive = false; // boolean flag for checking if the number contained consecutive equal digits\n for (int i = 0; i < arr.length; i++) {\n int digit = arr[i] - '0'; //Subtracting ascii values to get integer values\n int newNumber = digit;\n if (i != arr.length - 1) {\n int nextDigit = arr[i + 1] - '0';\n\n if (digit == nextDigit) { // check if the digits are consecutive digits\n newNumber = digit + nextDigit;\n i++; // increment i as we have already added the i+1 digit\n foundConsecutive = true;\n }\n } \n result.append(newNumber);\n }\n if (!foundConsecutive) // if no consecutive equal digits were found then return the result;\n return result.toString();\n else // recurse to check for more consecutive equal digits\n return addConsecutiveDigits(result.toString());\n}\n\n" }, { "answer_id": 74405651, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 0, "selected": false, "text": "String transform(String number) {\n while (true) {\n String result = collapse(number);\n if (result.equals(number)) return result;\n number = result;\n }\n}\n\nprivate static String collapse(String number) {\n StringBuilder result = new StringBuilder();\n for (idx = 0; idx < number.length(); ) {\n int mark = idx;\n int digit = digitAt(number, idx++);\n while (idx < number.length() && digitAt(number, idx) == digit) ++idx;\n result.append((idx - mark) * digit);\n }\n return result.toString();\n}\n\nprivate static int digitAt(String num, int index) {\n char ch = number.charAt(index);\n if (ch < '0' || ch > '9') throw new IllegalArgumentException();\n return ch - '0';\n}\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74350271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17841947/" ]
74,350,277
<p>Is there any reason to use <code>if</code> to check if method exists, before calling await</p> <pre><code>if (someObject.save){ await someObject.save(); } </code></pre> <p>rather than using nullish coallescence diectly with <code>await</code></p> <pre><code> await someObject.save?.(); </code></pre> <p>Is second code a safe alternative to the former?</p>
[ { "answer_id": 74350339, "author": "ControlAltDel", "author_id": 1291492, "author_profile": "https://Stackoverflow.com/users/1291492", "pm_score": 0, "selected": false, "text": "?." }, { "answer_id": 74350362, "author": "Majed Badawi", "author_id": 7486313, "author_profile": "https://Stackoverflow.com/users/7486313", "pm_score": 0, "selected": false, "text": "await undefined" }, { "answer_id": 74350613, "author": "VLAZ", "author_id": 3689450, "author_profile": "https://Stackoverflow.com/users/3689450", "pm_score": 3, "selected": true, "text": "const obj = {\n foo() { console.log(\"method called\"); },\n bar: 42\n};\n\nif (obj.foo) {\n console.log(\"obj has foo\");\n obj.foo(); //works\n}\n\nconsole.log(\"using optional chaining\");\nobj.foo?.(); //works\n\n\nif (obj.bar) {\n console.log(\"obj has bar\");\n try {\n obj.bar(); //error\n } catch (err) {\n console.log(\"bar cannot be called\");\n }\n}\n\nconsole.log(\"using optional chaining\");\ntry {\n obj.bar?.() //error\n} catch (err) {\n console.log(\"bar cannot be called\");\n}" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74350277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15461/" ]
74,350,312
<p>I have a batch file which gets its own short pathname (to eliminate spaces, which gcc doesn't like) for use in subsequent commands:</p> <pre><code>set base=%~d0%~sp0 </code></pre> <p>This works fine for most cases; for example, if the batch file is located in C:\Program Files, the value of %base% will be C:\PROGRA~1, and gcc is happy.</p> <p>However, it doesn't work if the batch file is in a directory with &quot;&amp;&quot; in the name. If it is in a directory called &quot;C:\Here &amp; There&quot;, the command above expands to</p> <pre><code>set base=C:\HERE&amp;T~1\ </code></pre> <p>which is treated as two commands, producing the error message <code>'T~1\' is not recognized as an internal or external command, operable program or batch file.</code></p> <p>If I put quotes around it:</p> <pre><code>set base=&quot;%~d0%~sp0&quot; </code></pre> <p>Then the command works, and the value of %base% is <code>&quot;C:\HERE&amp;T~1\&quot;</code> (including the quotes). But then the quotes break something else further on in the file when I use it to build a Java classpath:</p> <pre><code>java -cp .;&quot;C:\HERE&amp;T~1\&quot;Jars\* foo </code></pre> <p>which says &quot;The system cannot find the file specified&quot; (relating to <code>&quot;C:\HERE&amp;T~1\&quot;Jars\*</code> in the classpath).</p> <p>Can anyone suggest a way around this Microsoft mess?</p> <p><strong>[Edit]</strong></p> <p>As requested by Mofi below, here is a minimal reproducible example batch file:</p> <pre><code>@echo off set base=%~d0%~sp0 echo %base% </code></pre> <p>If this is executed in a directory called &quot;C:\Here &amp; There&quot;, I would like the output to be</p> <pre><code>C:\HERE&amp;T~1 </code></pre> <p>without quotes or other extraneous output.</p> <p>Here is the actual output when using CMD.EXE as the shell:</p> <pre><code>'T~1\' is not recognized as an internal or external command, operable program or batch file. C:\HERE </code></pre> <p>If I change the line <code>@echo off</code> to <code>@echo on</code> to show the commands as they are executed, I get this (where &quot;C:\Here &amp; There&gt;&quot; is the prompt, followed by the actual command being echoed prior to execution):</p> <pre><code>C:\Here &amp; There&gt; set base=C:\HERE &amp; T~1\ 'T~1\' is not recognized as an internal or external command, operable program or batch file. C:\Here &amp; There&gt; echo C:\HERE C:\HERE </code></pre>
[ { "answer_id": 74350352, "author": "Ben Voigt", "author_id": 103167, "author_profile": "https://Stackoverflow.com/users/103167", "pm_score": 2, "selected": false, "text": "set \"base=%~d0%~sp0\"\n" }, { "answer_id": 74420121, "author": "jeb", "author_id": 463115, "author_profile": "https://Stackoverflow.com/users/463115", "pm_score": 2, "selected": true, "text": "SET" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74350312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1636349/" ]
74,350,315
<p>I need to find the average for the scores M1 and E1 for every name in the list and want to add another key: value pair called average : (M1+E1)/2. How do i add more key: value pairs under 2002 and 2008 ?</p> <pre><code>gradebook = { 2002: [ {&quot;Name&quot; : &quot;John&quot;}, {&quot;M1&quot; : 87}, {&quot;E1&quot; : 10}, {&quot;Score&quot; : 90}, {&quot;Grade&quot; : &quot;A&quot;} ], 2008 : [ {&quot;Name&quot; : &quot;Paul&quot;}, {&quot;M1&quot; : 83}, {&quot;E1&quot; : 59}, {&quot;Score&quot; : 77}, {&quot;Grade&quot; : &quot;C&quot;} ], } def displayResult(gradebook): print('ID Name Grade') for i,j in gradebook.items(): print('{} {} {}'.format(i,j[0]['Name'],j[4]['Grade'])) displayResult(gradebook) </code></pre> <p>Current output</p> <pre><code>|ID Name Grade |2002 John A |2008 Paul C Expected ID Name Average 2002 John 48.5 2008 Paul 71 </code></pre>
[ { "answer_id": 74350544, "author": "Omer Dagry", "author_id": 15010874, "author_profile": "https://Stackoverflow.com/users/15010874", "pm_score": 1, "selected": false, "text": "gradebook = {\n 2002: [\n {\"Name\": \"John\"},\n {\"M1\": 87},\n {\"E1\": 10},\n {\"Score\": 90},\n {\"Grade\": \"A\"}\n ],\n 2008: [\n {\"Name\": \"Paul\"},\n {\"M1\": 83},\n {\"E1\": 59},\n {\"Score\": 77},\n {\"Grade\": \"C\"}\n ],\n}\n\n\ndef displayResult(gradebook):\n print(' ID Name Grade ')\n for i, j in gradebook.items():\n print(f\"{str(i).center(6)}{j[0]['Name'].center(16)}{str(sum([list(d.values())[0] for d in j[1:-2]])/(len(j) - 3)).center(9)}\")\n\n\ndisplayResult(gradebook)\n\n\n# result:\n# ID Name Grade \n# 2002 John 48.5 \n# 2008 Paul 71.0 \n" }, { "answer_id": 74350675, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 0, "selected": false, "text": "gradebook" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74350315", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20073604/" ]
74,350,321
<p>I created an agent called Technician its a population and it has the variable capacity in boolean. The variable belongs to one agent (agent 0). In my main i have a button that changes its color if it is clicked on. The code i wrote for the Button in Fill color is.</p> <pre><code>technician.capacity==true? yellowGreen : tomato </code></pre> <p>It says that capacity cannot be resolved or is not a field</p> <p>If i try technician with a T</p> <pre><code>Technician.capacity==true? yellowGreen : tomato </code></pre> <p>It says cannot make a reference to a non-static field</p> <p>There must be wrong something with reference to technician part.</p> <p>How can i fix it?</p>
[ { "answer_id": 74350544, "author": "Omer Dagry", "author_id": 15010874, "author_profile": "https://Stackoverflow.com/users/15010874", "pm_score": 1, "selected": false, "text": "gradebook = {\n 2002: [\n {\"Name\": \"John\"},\n {\"M1\": 87},\n {\"E1\": 10},\n {\"Score\": 90},\n {\"Grade\": \"A\"}\n ],\n 2008: [\n {\"Name\": \"Paul\"},\n {\"M1\": 83},\n {\"E1\": 59},\n {\"Score\": 77},\n {\"Grade\": \"C\"}\n ],\n}\n\n\ndef displayResult(gradebook):\n print(' ID Name Grade ')\n for i, j in gradebook.items():\n print(f\"{str(i).center(6)}{j[0]['Name'].center(16)}{str(sum([list(d.values())[0] for d in j[1:-2]])/(len(j) - 3)).center(9)}\")\n\n\ndisplayResult(gradebook)\n\n\n# result:\n# ID Name Grade \n# 2002 John 48.5 \n# 2008 Paul 71.0 \n" }, { "answer_id": 74350675, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 0, "selected": false, "text": "gradebook" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74350321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20442353/" ]
74,350,368
<p>I am trying to use a library but a submit button would be rendered outside of the form automatically (because body of the library's component is rendered as a sibling of the footer where the submit button should go). Is there a way to bind to this form so that the button that is outside of the form can trigger the form submit? Basically I want the button that is outside of the form to be able to act like it is inside the form. Is this possible?</p> <p>Edit: I am using the Dialog component from the PrimeReact library. The button is in the JSX sent into the &quot;footer&quot; prop</p> <p><a href="https://i.stack.imgur.com/qOXkd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qOXkd.png" alt="rendered html" /></a></p>
[ { "answer_id": 74350544, "author": "Omer Dagry", "author_id": 15010874, "author_profile": "https://Stackoverflow.com/users/15010874", "pm_score": 1, "selected": false, "text": "gradebook = {\n 2002: [\n {\"Name\": \"John\"},\n {\"M1\": 87},\n {\"E1\": 10},\n {\"Score\": 90},\n {\"Grade\": \"A\"}\n ],\n 2008: [\n {\"Name\": \"Paul\"},\n {\"M1\": 83},\n {\"E1\": 59},\n {\"Score\": 77},\n {\"Grade\": \"C\"}\n ],\n}\n\n\ndef displayResult(gradebook):\n print(' ID Name Grade ')\n for i, j in gradebook.items():\n print(f\"{str(i).center(6)}{j[0]['Name'].center(16)}{str(sum([list(d.values())[0] for d in j[1:-2]])/(len(j) - 3)).center(9)}\")\n\n\ndisplayResult(gradebook)\n\n\n# result:\n# ID Name Grade \n# 2002 John 48.5 \n# 2008 Paul 71.0 \n" }, { "answer_id": 74350675, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 0, "selected": false, "text": "gradebook" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74350368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5570385/" ]
74,350,369
<p>I am automating the building of a document based on a set of inputs. I started with Google's example here: <a href="https://developers.google.com/apps-script/samples/automations/aggregate-document-content" rel="nofollow noreferrer">https://developers.google.com/apps-script/samples/automations/aggregate-document-content</a>, and made modifications.</p> <p>The problem I have is when one or more of the source documents contains a bulleted list. The list is imported into the new document as a bulleted list, which is what I expect, but there is no glyph for the list, so it just looks like indented text. I have to manually select each bulleted list and set the bullet style for the list.</p> <p>Is there a way for me to specify the bullet style I want to be used for all bulleted lists one time, or in some way search for the bulleted lists with App Script after the import to find them and change them?</p>
[ { "answer_id": 74350665, "author": "Cooper", "author_id": 7215091, "author_profile": "https://Stackoverflow.com/users/7215091", "pm_score": 0, "selected": false, "text": "function settingGlyphType() {\n var body = DocumentApp.getActiveDocument().getBody();\n body.appendListItem(\"Item 1\");\n body.appendListItem(\"Item 2\").setNestingLevel(1).setIndentStart(72).setGlyphType(DocumentApp.GlyphType.SQUARE_BULLET);\n}\n" }, { "answer_id": 74351947, "author": "Mr. T", "author_id": 7817587, "author_profile": "https://Stackoverflow.com/users/7817587", "pm_score": 2, "selected": true, "text": " function setGlyphType() {\n var body = DocumentApp.getActiveDocument().getBody();\n var bullet = null;\n while(bullet = body.findElement(DocumentApp.ElementType.LIST_ITEM, bullet)) {\n bullet.getElement().asListItem().setGlyphType(DocumentApp.GlyphType.BULLET);\n }\n }\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74350369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7817587/" ]
74,350,392
<p><a href="https://i.stack.imgur.com/wDq0D.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wDq0D.png" alt="Horners method" /></a></p> <p>Hello, everyone. My current university assignment is to represent <a href="https://en.wikipedia.org/wiki/Horner%27s_method" rel="nofollow noreferrer">Horner's method</a> using recursion. Before this task we had to do it with a loop, which was easy. But I have no idea how to do this using recursion with only 2 parameters which cannot be changed.</p> <pre><code>public static double evalHornerRec(double[] a, double x) </code></pre> <p>This is the function i have to use</p> <pre><code> private static int horner(int a[], int x, int n){ int h; if(n&gt;0) h=horner(a, x, n-1); else return a[n]; return h*x+a[n]; } </code></pre> <p>I found something like this but it has 3 parameters and not 2</p>
[ { "answer_id": 74351151, "author": "Alexander Ivanchenko", "author_id": 17949945, "author_profile": "https://Stackoverflow.com/users/17949945", "pm_score": 1, "selected": true, "text": "0" }, { "answer_id": 74351521, "author": "David Soroko", "author_id": 239101, "author_profile": "https://Stackoverflow.com/users/239101", "pm_score": 1, "selected": false, "text": "public class Main {\n static int horner(int a[], int x) {\n switch (a.length) {\n case 1: return a[0];\n default: return a[0] + x * horner(Arrays.copyOfRange(a, 1, a.length), x);\n }\n }\n\n public static void main(String[] args) {\n // 2x^3 - 6x^2 + 2x - 1 for x = 3 => 5\n int[] poly = {-1, 2, -6, 2};\n System.out.println(horner(poly, 3)); // 5\n }\n}\n\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74350392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14170108/" ]
74,350,409
<p>I have a multidimensional data structure for tracking different characteristics of files I am comparing and merging data for. The structure is set up as such:</p> <pre><code>$cumulative{$slice} = { DATA =&gt; $data, META =&gt; $got_meta, RECOVER =&gt; $recover, DISPO =&gt; $dispo, DIR =&gt; $dir, }; </code></pre> <p>All of the keys, save <code>DIR</code> (which is just a simple string), are references to hashes, or arrays. I would like to have a simple search for KEYS that match &quot;BASE&quot; for the value <code>DIR</code> points to for each of the <code>$slice</code> keys. My initial thought was to use grep, but I'm not sure how to do that. I thought something like this would be ok:</p> <p><code>my (@base_slices) = grep { $cumulative{$_}-&gt;{DIR} eq &quot;BASE&quot; } @{$cumulative{$_}};</code></p> <p>I was wrong. Is there a way to do this without a loop, or is that pretty much the only way to check those values? Thanks!</p> <p>Edit: Thanks to Ikegami for answering succinctly, even without my fully representing the outcome of the search. I have changed the question a little bit to more clearly explain the issue I was having.</p>
[ { "answer_id": 74351151, "author": "Alexander Ivanchenko", "author_id": 17949945, "author_profile": "https://Stackoverflow.com/users/17949945", "pm_score": 1, "selected": true, "text": "0" }, { "answer_id": 74351521, "author": "David Soroko", "author_id": 239101, "author_profile": "https://Stackoverflow.com/users/239101", "pm_score": 1, "selected": false, "text": "public class Main {\n static int horner(int a[], int x) {\n switch (a.length) {\n case 1: return a[0];\n default: return a[0] + x * horner(Arrays.copyOfRange(a, 1, a.length), x);\n }\n }\n\n public static void main(String[] args) {\n // 2x^3 - 6x^2 + 2x - 1 for x = 3 => 5\n int[] poly = {-1, 2, -6, 2};\n System.out.println(horner(poly, 3)); // 5\n }\n}\n\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74350409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8695634/" ]
74,350,411
<p>I have tried below regular expression to validate the number with following criteria</p> <p><code>/^\d{3,10}(\.\d{2})?$/</code></p> <p>a, number should be minimum 3 , maximum 10 (including .) digits and it may contain . and two decimal point</p> <p>Examples</p> <p><strong>valid numbers</strong></p> <p>123</p> <p>1234</p> <p>12345</p> <p>123456</p> <p>1234567</p> <p>12345678</p> <p>123456789</p> <p>1234567890</p> <p>123.00</p> <p>1234.02</p> <p>12345.03</p> <p>123456.04</p> <p>1234567.05</p> <p><strong>Invalid numbers</strong></p> <p>1</p> <p>12</p> <p>1.11</p> <p>1.1111</p> <p>12345678.12</p> <p>But my regex fail in case of 1234567890.00</p>
[ { "answer_id": 74353151, "author": "The fourth bird", "author_id": 5424988, "author_profile": "https://Stackoverflow.com/users/5424988", "pm_score": 3, "selected": true, "text": "^(?![.\\d]{11,}$)\\d{3,10}(?:\\.\\d\\d)?$\n" }, { "answer_id": 74381741, "author": "Peter Thoeny", "author_id": 7475450, "author_profile": "https://Stackoverflow.com/users/7475450", "pm_score": 0, "selected": false, "text": "." } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74350411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6727459/" ]