qid
int64
4
22.2M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,290,299
<p>I have a google app script.</p> <p><strong>code.gs</strong></p> <pre><code>const doGet = _ =&gt; { const ss = SpreadsheetApp.openById(&quot;1FJtOQZAN_SIOYHybA9FXbJ_ngoRy38KTvo1hZu7SEUs&quot;); const sheetA = ss.getSheetByName(&quot;SYLLABUSC&quot;); const rangeA = sheetA.getRange(&quot;E1:E5&quot;); const sheetB = ss.getSheetByName(&quot;SHEETB&quot;); const rangeB = sheetB.getRange(&quot;A1:A3&quot;); const html = rangeA.getDisplayValues().join(&quot;\n&quot;); return ContentService.createTextOutput(html).setMimeType(ContentService.MimeType.JAVASCRIPT); } </code></pre> <p>By above I'm getting <strong>TextOutput</strong> from <strong>SheeA Range</strong> only.</p> <p>But I want both ranges one by one, i.e. SheetA Range and then SheetB Range.</p> <p>How to merge these ..?</p> <p><strong>Update :</strong></p> <p>By the Answer provided, the <strong>Code.gs file</strong> modified like below.</p> <pre><code>const doGet = _ =&gt; { const ss = SpreadsheetApp.openById(&quot;1FJtOQZAN_SIOYHybA9FXbJ_ngoRy38KTvo1hZu7SEUs&quot;); const sheetA = ss.getSheetByName(&quot;SYLLABUSC&quot;); const rangeA = sheetA.getRange(&quot;E1:E5&quot;).getDisplayValues(); const sheetB = ss.getSheetByName(&quot;SHEETB&quot;); const rangeB = sheetB.getRange(&quot;A1:A3&quot;).getDisplayValues(); const html = rangeA.concat(rangeB).join(&quot;\n&quot;); return ContentService.createTextOutput(html).setMimeType(ContentService.MimeType.JAVASCRIPT); } </code></pre> <p>Here is <strong><a href="https://script.google.com/macros/s/AKfycby5Hzd00J2SeqrbAXSkypIU7YSgVi5g3MxVpHz5wmGvBO8H2MlXX1fBwNd8xhcLgXfRvQ/exec" rel="nofollow noreferrer">My Web App</a></strong></p>
[ { "answer_id": 74290613, "author": "TheWizEd", "author_id": 3656739, "author_profile": "https://Stackoverflow.com/users/3656739", "pm_score": 3, "selected": true, "text": "const html = rangeA.getDisplayValues().join(\"\\n\");\n" }, { "answer_id": 74290902, "author": "Cooper", "author_id": 7215091, "author_profile": "https://Stackoverflow.com/users/7215091", "pm_score": 1, "selected": false, "text": "function mergeRanges() {\n const ss = SpreadsheetApp.openById(\"1R5Wgq4okSWz0d159X5kPvOk8W1T_6eZ2kwoq5kdjO0w\");\n const sheetA = ss.getSheetByName(\"SYLLABUSC\");\n const vsa = sheetA.getRange(\"C1:C6\").getDisplayValues();\n const sheetB = ss.getSheetByName(\"SHEETB\");\n const vsb = sheetB.getRange(\"A1:A3\").getDisplayValues();\n const html = [vsa, vsb].reduce((a, c, i) => {\n c.forEach(arr => a += arr.join('\\n'))\n return a;\n }, \"\")\n Logger.log(html);\n return ContentService.createTextOutput(html).setMimeType(ContentService.MimeType.JAVASCRIPT);\n}\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74290299", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20018193/" ]
74,290,305
<p>So imagine I have a SQL tempTable with a text field with 2 pages worth of text in it.</p> <pre><code>select * from tempTable </code></pre> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>pkid</th> <th>text</th> </tr> </thead> <tbody> <tr> <td>0</td> <td>This is an example text with some images names like image1.svg or another one like image2.svg</td> </tr> <tr> <td>1</td> <td>This is another example text image3.svg and several images more like image4 and image5</td> </tr> </tbody> </table> </div> <p>What I want to know is if it's possible to select the characters before the .svg extension, so that the select result would look like</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>result</th> </tr> </thead> <tbody> <tr> <td>ike image1.svg</td> </tr> <tr> <td>ike image2.svg</td> </tr> <tr> <td>ext image3.svg</td> </tr> </tbody> </table> </div> <p>and so on. I've alread read about CHARINDEX and SUBSTRING, but I've only been able to find selects that return ALL text before my filter (.svg).</p>
[ { "answer_id": 74290923, "author": "Jacob A.", "author_id": 20224519, "author_profile": "https://Stackoverflow.com/users/20224519", "pm_score": 0, "selected": false, "text": "--create the temp table\nDECLARE @temp AS TABLE (\n pkid int,\n text nvarchar(max)\n)\n\n--populate the temp table\nINSERT INTO @temp (pkid, text) VALUES\n(0, 'This is an example text with some images names like image1.svg or another one like image2.svg'),\n(1, 'This is another example text image3.svg and several images more like image4 and image5')\n\n--run the query to get the desired results\nSELECT\n CONCAT(RIGHT(split.priorValue, 10), '.svg') AS result\nFROM (\nSELECT\n ss.value,\n LAG(ss.value, 1) OVER (ORDER BY pkid) AS priorValue\nFROM @temp\nCROSS APPLY string_split(text, '.') ss\n) AS split\nWHERE split.value LIKE 'svg%'\n" }, { "answer_id": 74349221, "author": "Edgedancer", "author_id": 12992581, "author_profile": "https://Stackoverflow.com/users/12992581", "pm_score": 2, "selected": true, "text": "PATINDEX()" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74290305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12992581/" ]
74,290,319
<p>I want to mark rows where start and end time overlaps based on keys. For example, if given a dataframe like:</p> <pre class="lang-none prettyprint-override"><code>+---+-------------------+-------------------+ |key|start_date |end_date | +---+-------------------+-------------------+ |A |2022-01-11 00:00:00|8888-12-31 00:00:00| |B |2020-01-01 00:00:00|2022-02-10 00:00:00| |B |2019-02-08 00:00:00|2020-02-15 00:00:00| |B |2022-02-16 00:00:00|2022-12-15 00:00:00| |C |2018-01-01 00:00:00|2122-02-10 00:00:00| +---+-------------------+-------------------+ </code></pre> <p>the resulting dataframe would have the first and second B records flagged, since their start and end times overlap. Like this:</p> <pre class="lang-none prettyprint-override"><code>+---+-------------------+-------------------+-----+ |key|start_date |end_date |valid| +---+-------------------+-------------------+-----+ |A |2022-01-11 00:00:00|8888-12-31 00:00:00|true | |B |2020-01-01 00:00:00|2022-02-10 00:00:00|false| |B |2019-02-08 00:00:00|2020-02-15 00:00:00|false| |B |2022-02-16 00:00:00|2022-12-15 00:00:00|true | |C |2018-01-01 00:00:00|2122-02-10 00:00:00|true | +---+-------------------+-------------------+-----+ </code></pre>
[ { "answer_id": 74290950, "author": "ZygD", "author_id": 2753501, "author_profile": "https://Stackoverflow.com/users/2753501", "pm_score": 2, "selected": true, "text": "groupBy" }, { "answer_id": 74296303, "author": "wwnde", "author_id": 8986975, "author_profile": "https://Stackoverflow.com/users/8986975", "pm_score": 0, "selected": false, "text": "df = (df.select('key',*[to_date(x).alias(x) for x in df.columns if x!='key'])#Coerce to dates\n .withColumn('valid', collect_list(array(col('start_date'), col('end_date'))).over(Window.partitionBy('key')))#Create list of start_end dates intervals\n .withColumn('valid',expr(\"array_contains(transform(valid,(x,i)->start_date<(x[0])),true)\"))#check if the start date occurs before end date, if true flag\n )\n\n+---+----------+----------+-----+\n|key|start_date|end_date |valid|\n+---+----------+----------+-----+\n|A |2022-01-11|8888-12-31|false|\n|B |2020-01-01|2022-02-10|true |\n|B |2019-02-08|2020-02-15|true |\n|B |2022-02-16|2022-12-15|false|\n|C |2018-01-01|2122-02-10|false|\n+---+----------+----------+-----+\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74290319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17721780/" ]
74,290,336
<p>I have this rxjs code where <code>cobineLatest</code> is used</p> <pre><code>cobineLatest( this.controls.toArray().map(c =&gt; c.changeEvent.asObservable()) ).subscribe(x =&gt; { console.log(x); }); </code></pre> <p>The thing is that there won't be any result in subscription until all observables emits, I wonder how would you change that behavior so it will start emitting even if one single observable emits?</p>
[ { "answer_id": 74290869, "author": "Fabian Strathaus", "author_id": 17298437, "author_profile": "https://Stackoverflow.com/users/17298437", "pm_score": 3, "selected": true, "text": "null" }, { "answer_id": 74291100, "author": "MoxxiManagarm", "author_id": 11011793, "author_profile": "https://Stackoverflow.com/users/11011793", "pm_score": 0, "selected": false, "text": "merge(\n this.controls.toArray().map(c => c.changeEvent.asObservable())\n).subscribe(x => {\n console.log(x); // x is not an array\n});\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74290336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2926340/" ]
74,290,395
<p>I know we should use JQ for parsing json data, but I want to parse it using regex. I want to fetch the value of a json key into a variable in my shell script. As of now, I am using JQ for parsing.</p> <p>So my abc.json is</p> <pre><code>{&quot;value1&quot;:5.0,&quot;value2&quot;:2.5,&quot;value3&quot;:&quot;2019-10-24T15:26:00.000Z&quot;,&quot;modifier&quot;:[],&quot;value4&quot;:{&quot;value41&quot;:{&quot;value411&quot;:5}}} </code></pre> <p>Currently, my XYZ.sh has these lines to fetch the data</p> <p>data1 =$(cat abc.json | jq -r '.value4.value41.value411')</p> <p>I want data1 to have value of value411. How can I achieve this?</p> <p>ps- The JSON is mutable. The above JSON is just a part of the JSON file that I want to fetch.</p>
[ { "answer_id": 74290780, "author": "山河以无恙", "author_id": 20209252, "author_profile": "https://Stackoverflow.com/users/20209252", "pm_score": 2, "selected": false, "text": "┌──[root@vms83.liruilongs.github.io]-[~]\n└─$cat abc.json | awk -F: '{print $NF}' | grep -o '[[:digit:]]'\n5\n" }, { "answer_id": 74290920, "author": "Andy Lester", "author_id": 8454, "author_profile": "https://Stackoverflow.com/users/8454", "pm_score": 0, "selected": false, "text": "data" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74290395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18148705/" ]
74,290,406
<p>So Basilcally I am using <a href="https://react-bootstrap.github.io/components/modal/#vertically-centered" rel="nofollow noreferrer">this</a> react-bootstrap modal.</p> <p>I am using React with react-bootstrap components. I implemented it but when I opens it, instead of translucent background (opacity 0.5), the background appears black.</p> <p><a href="https://i.stack.imgur.com/lybGG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lybGG.png" alt="ss" /></a></p> <p>As you can see also . The background becomes black as I opens the modal and you can hardly see anything behind .</p> <p>Using modal like this</p> <pre class="lang-html prettyprint-override"><code>&lt;Modal {...props} size=&quot;lg&quot; aria-labelledby=&quot;contained-modal-title-vcenter&quot; centered &gt; &lt;Modal.Header style={{ backgroundColor: &quot;#E8EDF9&quot; }}&gt; &lt;Modal.Title id=&quot;contained-modal-title-vcenter&quot;&gt; More Coupon Details &lt;/Modal.Title&gt; &lt;/Modal.Header&gt; &lt;Modal.Body style={{ backgroundColor: &quot;#F2F4FA&quot; }}&gt; &lt;div className=&quot; py-3&quot;&gt; &lt;div className=&quot;p-6 space-y-4 &quot;&gt; &lt;div color=&quot;&quot; className=&quot;bg-gray-400&quot;&gt; &lt;div className=&quot;d-flex fs-5 align-items-baseline justify-content-start&quot;&gt; &lt;h4 className=&quot;fs-5 text-black&quot;&gt;Coupon Code : &lt;/h4&gt; &lt;p className=&quot;ms-2&quot;&gt;{detailComponent.couponCode}&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div className=&quot;d-flex align-items-center justify-content-start&quot;&gt; &lt;div className=&quot;d-flex fs-5 align-items-baseline justify-content-start me-5&quot;&gt; &lt;h4 className=&quot;fs-5 text-black&quot;&gt;Max Discount Percent :&lt;/h4&gt; &lt;p className=&quot;ms-2 &quot;&gt;{detailComponent.maxDiscountPer} %&lt;/p&gt; &lt;/div&gt; &lt;div className=&quot;d-flex fs-5 align-items-baseline justify-content-start ms-5&quot;&gt; &lt;h4 className=&quot;fs-5 text-black&quot;&gt;Max Discount Absolute :&lt;/h4&gt; &lt;p className=&quot;ms-2 &quot;&gt;{detailComponent.maxDiscountAbs} %&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div className=&quot;d-flex align-items-center justify-content-start&quot;&gt; &lt;div className=&quot;d-flex fs-5 align-items-baseline justify-content-start me-5&quot;&gt; &lt;h4 className=&quot;fs-5 text-black&quot;&gt;Maximum Usage User :&lt;/h4&gt; &lt;p className=&quot;ms-2 &quot;&gt;{detailComponent.maxUsageUser}&lt;/p&gt; &lt;/div&gt; &lt;div className=&quot;d-flex fs-5 align-items-baseline justify-content-start ms-5&quot;&gt; &lt;h4 className=&quot;fs-5 text-black&quot;&gt;Maximum Usage Overall :&lt;/h4&gt; &lt;p className=&quot;ms-2&quot;&gt;{detailComponent.maxUsageOverall}&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div className=&quot;d-flex align-items-center justify-content-start&quot;&gt; &lt;div className=&quot;d-flex fs-5 align-items-baseline justify-content-start me-5&quot;&gt; &lt;h4 className=&quot;fs-5 text-black&quot;&gt;Start Date :&lt;/h4&gt; &lt;p className=&quot;ms-2&quot;&gt;{detailComponent.startDate}&lt;/p&gt; &lt;/div&gt; &lt;div className=&quot;d-flex fs-5 align-items-baseline justify-content-start ms-2&quot;&gt; &lt;h4 className=&quot;fs-5 text-black&quot;&gt;End Date :&lt;/h4&gt; &lt;p className=&quot;ms-2&quot;&gt;{detailComponent.endDate}&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div className=&quot;d-flex fs-5 align-items-baseline justify-content-start&quot;&gt; &lt;h4 className=&quot;fs-5 text-black&quot;&gt;Coupon Description :&lt;/h4&gt; &lt;p className=&quot;ms-2&quot;&gt;{detailComponent.description}&lt;/p&gt; &lt;/div&gt; &lt;div className=&quot;d-flex fs-5 align-items-baseline justify-content-start&quot;&gt; &lt;h4 className=&quot;fs-5 text-black&quot;&gt;Landing Page :&lt;/h4&gt; &lt;p className=&quot;ms-2&quot;&gt;{detailComponent.landingPage}&lt;/p&gt; &lt;/div&gt; &lt;div className=&quot;d-flex fs-5 align-items-baseline justify-content-start&quot;&gt; &lt;h4 className=&quot;fs-5 text-black&quot;&gt;Redeem Steps :&lt;/h4&gt; &lt;p className=&quot;ms-2&quot;&gt;{detailComponent.redeemSteps}&lt;/p&gt; &lt;/div&gt; &lt;div className=&quot;d-flex fs-5 align-items-baseline justify-content-start&quot;&gt; &lt;h4 className=&quot;fs-5 text-black&quot;&gt;Terms and Conditions :&lt;/h4&gt; &lt;p className=&quot;ms-2&quot;&gt;{detailComponent.tnc}&lt;/p&gt; &lt;/div&gt; &lt;div className=&quot;d-flex col-12 fs-5 align-items-baseline justify-content-start&quot;&gt; &lt;h4 className=&quot;fs-5 col-4 text-black&quot;&gt;Applicable Channels :&lt;/h4&gt; &lt;p className=&quot;&quot;&gt; {detailComponent.applicableChannelsDTOList ? detailComponent.applicableChannelsDTOList.map((item) =&gt; { return &lt;span key={item}&gt;{item}, &lt;/span&gt;; }) : detailComponent.applicableVerticalsDTOList} &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/Modal.Body&gt; &lt;Modal.Footer style={{ backgroundColor: &quot;#E8EDF9&quot; }}&gt; &lt;Button variant=&quot;danger&quot; className=&quot;mx-auto&quot; onClick={props.onHide}&gt; Close &lt;/Button&gt; &lt;/Modal.Footer&gt; &lt;/Modal&gt; </code></pre> <p>I'm attaching the code of CSS files. (In case if any classes I used affect the default Modal Classes).</p> <p><strong>app.css</strong></p> <pre class="lang-css prettyprint-override"><code>.no-border { border: 0; box-shadow: none; } .label { display: block; padding-left: 0; padding-right: 0; padding-top: 0.625rem; padding-bottom: 0.625rem; background-color: transparent; color: #111827; font-size: 0.8rem; line-height: 1.25rem; width: 100%; border-width: 0; border-bottom-width: 2px; border-color: #d1d5db; appearance: none; } .form { padding: 0.5rem; width: 100%; border-radius: 0.75rem; @media (min-width: 640px) { padding: 1rem; } @media (min-width: 768px) { width: 66.666667%; } } .drop { display: block; padding-left: 0; padding-right: 0; padding-top: 0.625rem; padding-bottom: 0.625rem; background-color: transparent; color: #111827; font-size: 0.875rem; line-height: 1.25rem; width: 100%; border-width: 0; border-bottom-width: 2px; border-color: #e5e7eb; appearance: none; } .sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); whitespace: nowrap; borderwidth: 0; } .vertical { display: inline-flex; padding-top: 0.625rem; padding-bottom: 0.625rem; padding-left: 1rem; padding-right: 1rem; margin-left: 2rem; margin-top: 1.5rem; margin-bottom: 1.5rem; background-color: #e0e7ff; color: #000000; font-size: 0.875rem; line-height: 1.25rem; font-weight: 500; text-align: center; align-items: center; border-radius: 0.5rem; } .vertical:hover { background-color: #dbeafe; } .verticalBlock { display: block; background-color: #e0e7ff; width: 24rem; border-radius: 0.25rem; box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06); } .verticalHidden { display: none; background-color: #e0e7ff; width: 24rem; border-radius: 0.25rem; box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06); } .dropdownSearchButton { overflow-y: auto; padding-left: 0.75rem; padding-right: 0.75rem; padding-bottom: 0.75rem; color: #374151; font-size: 0.875rem; line-height: 1.25rem; height: 12rem; } .verticalflex { display: flex; flex-direction: row; } .verticalflex2 { display: flex; padding-left: 0.5rem; align-items: center; border-radius: 0.25rem; } .verticalflex2:hover { background-color: #e0e7ff; } .verticalInput { background-color: #f3f4f6; color: #4f46e5; width: 1rem; height: 1rem; border-radius: 0.25rem; border-color: #d1d5db; } .verticalLabel { padding-top: 0.5rem; padding-bottom: 0.5rem; margin-left: 0.5rem; color: #111827; font-size: 0.875rem; line-height: 1.25rem; width: 100%; border-radius: 0.25rem; } .verticalButton { display: flex; padding-top: 0.5rem; padding-bottom: 0.5rem; padding-left: 1rem; padding-right: 1rem; justify-content: space-between; align-items: center; } .doubleDropdownBlock { display: block; z-index: 10; margin: 0.5rem; background-color: #eef2ff; width: auto; border-radius: 0.25rem; border-top-width: 1px; border-color: #e0e7ff; } .doubleDropdownHidden { display: none; z-index: 10; margin: 0.5rem; background-color: #eef2ff; width: auto; border-radius: 0.25rem; border-top-width: 1px; border-color: #e0e7ff; } .doubleDropdownUl { display: flex; padding-top: 0.25rem; padding-bottom: 0.25rem; color: #374151; font-size: 0.875rem; line-height: 1.25rem; flex-direction: row; } .verticalTypeButton { display: block; padding: 0.25rem; } .verticalTypeButton:hover { background-color: #c7d2fe; } .verticalTypeButtonLabel { padding-top: 0.5rem; padding-bottom: 0.5rem; padding-left: 1rem; padding-right: 1rem; } .landing1 { position: relative; z-index: 0; margin-top: 1.5rem; margin-bottom: 1.5rem; width: 100%; } .landing2 { display: block; padding-left: 0; padding-right: 0; padding-top: 0.625rem; padding-bottom: 0.625rem; background-color: transparent; color: #111827; font-size: 0.875rem; line-height: 1.25rem; width: 100%; border-width: 0; border-bottom-width: 2px; border-color: #d1d5db; appearance: none; } .landing3 { position: absolute; top: 0.75rem; transition-duration: 300ms; --transform-scale-x: 0.75; --transform-scale-y: 0.75; --transform-translate-y: -1.5rem; color: #374151; font-size: 0.875rem; line-height: 1.25rem; } </code></pre> <p><strong>index.css</strong></p> <pre class="lang-css prettyprint-override"><code>body { margin: 0; font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, &quot;Roboto&quot;, &quot;Oxygen&quot;, &quot;Ubuntu&quot;, &quot;Cantarell&quot;, &quot;Fira Sans&quot;, &quot;Droid Sans&quot;, &quot;Helvetica Neue&quot;, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; background-image: url(&quot;./assets/banner02.svg&quot;); background-repeat: no-repeat; background-size: cover; } .no-border { border: 0; box-shadow: none; } code { font-family: source-code-pro, Menlo, Monaco, Consolas, &quot;Courier New&quot;, monospace; } a { color: inherit; text-decoration: none; } * { box-sizing: border-box; } </code></pre>
[ { "answer_id": 74290424, "author": "Cervus camelopardalis", "author_id": 10347145, "author_profile": "https://Stackoverflow.com/users/10347145", "pm_score": 1, "selected": false, "text": ".modal-backdrop.show {\n opacity: var(--bs-backdrop-opacity);\n}\n" }, { "answer_id": 74294108, "author": "tao", "author_id": 1891677, "author_profile": "https://Stackoverflow.com/users/1891677", "pm_score": 1, "selected": false, "text": ".modal-backdrop.show" }, { "answer_id": 74298542, "author": "MagnusEffect", "author_id": 10962364, "author_profile": "https://Stackoverflow.com/users/10962364", "pm_score": 0, "selected": false, "text": ".modal-backdrop\n{\n --bs-backdrop-bg: rgb(0 0 0 / 30%) !important;\n}\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74290406", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10962364/" ]
74,290,434
<p>I would like to detect if some values are not defined in an object with several properties</p> <p>for example :</p> <pre><code>let test = { helo: undefined, hey: &quot;not undefined&quot; } </code></pre> <p>i tried this :</p> <pre><code>const object1 = { a: 'somestring', b: 42 }; for (const [key, value] of Object.entries(object1)) { console.log(`${key}: ${value}`); } </code></pre> <p>but if possible, I don't want to use a for loop, I would like a boolean result in return</p>
[ { "answer_id": 74290468, "author": "Peterrabbit", "author_id": 18242865, "author_profile": "https://Stackoverflow.com/users/18242865", "pm_score": 3, "selected": true, "text": "const test = {\n helo: undefined,\n hey: \"not undefined\"\n};\n\nconst some_undefined = Object.values(test).some(v => v === undefined);\n\nconsole.log(some_undefined);" }, { "answer_id": 74290480, "author": "Thibaud Rouchon", "author_id": 20242416, "author_profile": "https://Stackoverflow.com/users/20242416", "pm_score": 0, "selected": false, "text": "const hasOneKeyUndefined = (object)=>\n{\n for (const [key, value] of Object.entries(object)) {\n if (value === undefined) return true;\n }\n return false;\n}\n" }, { "answer_id": 74291518, "author": "jhn_bdrx", "author_id": 8151868, "author_profile": "https://Stackoverflow.com/users/8151868", "pm_score": 0, "selected": false, "text": "const test = {\n helo: undefined,\n hey: \"not undefined\"\n};\nObject.keys(test).map((key, idx) => test[key] === undefined)\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74290434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20182267/" ]
74,290,448
<pre><code>DECLARE @Recaudacion as INT DECLARE @Division as INT SELECT @Recaudacion = (SELECT SUM(pelicula.PrecioEntrada) FROM pelicula) SELECT @Division = (SELECT COUNT(*) FROM funcion GROUP BY NombrePelicula HAVING COUNT(*) &gt; 1) SELECT (@Recaudacion / @Division) AS Recaudacion, funcion.NombrePelicula FROM funcion </code></pre> <p>I get this message</p> <blockquote> <p>Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, &lt;, &lt;= , &gt;, &gt;= or when the subquery is used as an expression.</p> </blockquote> <p>I'm expecting the average price for each show</p>
[ { "answer_id": 74290493, "author": "Magnus", "author_id": 468973, "author_profile": "https://Stackoverflow.com/users/468973", "pm_score": 2, "selected": false, "text": "SELECT count(*) FROM funcion GROUP BY NombrePelicula\n" }, { "answer_id": 74290798, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 1, "selected": true, "text": "SELECT NombrePelicula, \n (SELECT SUM(pelicula.PrecioEntrada) FROM pelicula) / count(*) As Recaudacion\nFROM funcion \nGROUP BY NombrePelicula \nHAVING COUNT(*)>1\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74290448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20398392/" ]
74,290,459
<p>I get following error when running WSO2 Micro Integrator 4.1.0 from the Integration studio on Ubuntu 22.04 .</p> <pre><code> ERROR {NativeWorkerPool} - Uncaught exception java.lang.OutOfMemoryError: Java heap space </code></pre> <p>How can I fix this?</p>
[ { "answer_id": 74293991, "author": "ycr", "author_id": 2627018, "author_profile": "https://Stackoverflow.com/users/2627018", "pm_score": 2, "selected": true, "text": "INTEGRATION_STUDIO_HOME/IntegrationStudio.ini" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74290459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10793556/" ]
74,290,481
<p>I am using cloudflare workers with miniflare. I have created a <code>bindings.d.ts</code> file:</p> <pre><code>export interface Bindings { ENV: string MYSQL_URL: string JWT_SECRET: string JWT_ACCESS_EXPIRATION_MINUTES: number JWT_REFRESH_EXPIRATION_DAYS: number JWT_RESET_PASSWORD_EXPIRATION_MINUTES: number JWT_VERIFY_EMAIL_EXPIRATION_MINUTES: number } declare global { function getMiniflareBindings(): Bindings } </code></pre> <p>In this file I have globally declared the function <code>getMiniflareBindings()</code>. In another file I access this by calling:</p> <pre><code>getMiniflareBindings() </code></pre> <p>But upon running my code I get the error:</p> <pre><code>ReferenceError: getMiniflareBindings is not defined </code></pre> <p>build.js:</p> <pre><code>import { build } from 'esbuild' try { await build({ entryPoints: ['./src/index.ts'], bundle: true, outdir: './dist/', sourcemap: true, minify: true }) } catch(err) { process.exitCode = 1; } </code></pre> <p>tsconfig.json:</p> <pre><code>{ &quot;compilerOptions&quot;: { &quot;allowJs&quot;: true, &quot;target&quot;: &quot;esnext&quot;, &quot;lib&quot;: [&quot;esnext&quot;], &quot;moduleResolution&quot;: &quot;node&quot;, &quot;resolveJsonModule&quot;: true, &quot;inlineSourceMap&quot;: true, &quot;module&quot;: &quot;esnext&quot;, &quot;esModuleInterop&quot;: true, &quot;experimentalDecorators&quot;: true, &quot;emitDecoratorMetadata&quot;: true, &quot;strict&quot;: true, &quot;noImplicitAny&quot;: true, &quot;noEmit&quot;: true, &quot;types&quot;: [ &quot;@cloudflare/workers-types&quot;, &quot;@types/bcryptjs&quot; ] }, &quot;ts-node&quot;: { &quot;transpileOnly&quot;: true }, &quot;include&quot;: [&quot;./src/**/*&quot;, &quot;bindings.d.ts&quot;] } </code></pre> <p>Any idea what I am doing wrong?</p> <p>Edit:</p> <p>An update. In .bindings.d.ts I now declare it like so:</p> <pre><code>export interface Bindings { ENV: string JWT_SECRET: string JWT_ACCESS_EXPIRATION_MINUTES: number JWT_REFRESH_EXPIRATION_DAYS: number JWT_RESET_PASSWORD_EXPIRATION_MINUTES: number JWT_VERIFY_EMAIL_EXPIRATION_MINUTES: number DATABASE_NAME: string DATABASE_USERNAME: string DATABASE_PASSWORD: string DATABASE_HOST: string } declare global { const ENV: string const JWT_SECRET: string const JWT_ACCESS_EXPIRATION_MINUTES: number const JWT_REFRESH_EXPIRATION_DAYS: number const JWT_RESET_PASSWORD_EXPIRATION_MINUTES: number const JWT_VERIFY_EMAIL_EXPIRATION_MINUTES: number const DATABASE_NAME: string const DATABASE_USERNAME: string const DATABASE_PASSWORD: string const DATABASE_HOST: string } </code></pre> <p>And in my code I access the values directly:</p> <pre><code>const env = { ENV, DATABASE_NAME, DATABASE_USERNAME, DATABASE_PASSWORD, DATABASE_HOST, JWT_SECRET, JWT_ACCESS_EXPIRATION_MINUTES, JWT_REFRESH_EXPIRATION_DAYS, JWT_RESET_PASSWORD_EXPIRATION_MINUTES, JWT_VERIFY_EMAIL_EXPIRATION_MINUTES } </code></pre> <p>This works great in production and developing but testing is where I have the issue as none of these are &quot;defined&quot; when I run my tests and I am just stuck.</p>
[ { "answer_id": 74293991, "author": "ycr", "author_id": 2627018, "author_profile": "https://Stackoverflow.com/users/2627018", "pm_score": 2, "selected": true, "text": "INTEGRATION_STUDIO_HOME/IntegrationStudio.ini" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74290481", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5476045/" ]
74,290,495
<p>I have a nested list with multiple gene names in each sublist:</p> <pre><code>genes = list(c(&quot;her15.1&quot;, &quot;her15.2&quot;, &quot;her4.2&quot;, &quot;her4.1&quot;, &quot;dla&quot;), c(&quot;pdyn&quot;, &quot;cbln1&quot;, &quot;kctd4&quot;, &quot;sox1b&quot; ), c(&quot;prph&quot;,&quot;phox2a&quot;, &quot;phox2bb&quot;, &quot;tac1&quot;, &quot;slc18a3a&quot;)) genes &lt;- setNames(genes, c(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;)) </code></pre> <p>I also have a df looking like this:</p> <pre><code> V1 V2 8694 ENSDARG00000008131 sox1b 8855 ENSDARG00000010791 dla 9408 ENSDARG00000068691 kctd4 14309 ENSDARG00000091029 phox2bb 15322 ENSDARG00000006356 slc18a3a 16000 ENSDARG00000057296 cbln1 17897 ENSDARG00000014490 tac1 19208 ENSDARG00000007406 phox2a 19593 ENSDARG00000056732 her4.1 19594 ENSDARG00000094426 her4.2 19975 ENSDARG00000087798 pdyn 22102 ENSDARG00000028306 prph 22717 ENSDARG00000054560 her15.1 </code></pre> <p>Each item in the list is also in df$V2. I would like to replace each item in the list of lists with the corresponding item from df$V1 based on the matching in df$V2.</p> <p>Thank you!</p>
[ { "answer_id": 74290772, "author": "Robert Hacken", "author_id": 2094893, "author_profile": "https://Stackoverflow.com/users/2094893", "pm_score": 3, "selected": true, "text": "V1" }, { "answer_id": 74290792, "author": "Andre Wildberg", "author_id": 9462095, "author_profile": "https://Stackoverflow.com/users/9462095", "pm_score": 1, "selected": false, "text": "sapply(genes, function(x) df$V1[grep(paste(x, collapse=\"|\"), df$V2)])\n$a\n[1] \"ENSDARG00000010791\" \"ENSDARG00000056732\" \"ENSDARG00000094426\"\n[4] \"ENSDARG00000054560\"\n\n$b\n[1] \"ENSDARG00000008131\" \"ENSDARG00000068691\" \"ENSDARG00000057296\"\n[4] \"ENSDARG00000087798\"\n\n$c\n[1] \"ENSDARG00000091029\" \"ENSDARG00000006356\" \"ENSDARG00000014490\"\n[4] \"ENSDARG00000007406\" \"ENSDARG00000028306\"\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74290495", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18144711/" ]
74,290,510
<p>I have been struggling with grouping by 2 conditions (or grouping &quot;twice&quot;?), adding an if unique value condition, and do the mean of those groups.</p> <p>I created a sample dataset so it can be better understood: A chef makes dishes, made out of ingredients, which each cost X. They can be costing differently depending on the day or the place bought or whatever, not relevant.</p> <pre><code> chef_id dish ingr price 0 1 dish_1 ingr1 4 1 1 dish_1 ingr2 3 2 1 dish_1 ingr3 5 3 2 dish_2 ingr1 1 4 2 dish_2 ingr2 3 5 2 dish_4 ingr1 2 6 3 dish_3 ingr1 6 7 3 dish_3 ingr2 4 </code></pre> <p>In my real dataset, there is also a date, but I don't think it's relevant. My main objective is to <strong>group by chefs, and dishes per chef, to do an average of the cost per dish (per chef).</strong> But all this, <strong>ONLY if the chef has made at least 2 DIFFERENT dishes in total</strong> (regardless the dates, that is why I don't think it's relevant). If it has done only one (even if it's several times). The ingredients are only relevant for the price, so that is why I am not using it as a condition.</p> <p>So the desired output would be something like:</p> <pre><code>chef_id,dish,price('mean') 2,dish_2,2 2,dish_4,2 </code></pre> <p>I've checked <a href="https://stackoverflow.com/questions/38309729/count-unique-values-per-groups-with-pandas">counting values per group</a>, <a href="https://stackoverflow.com/questions/13851535/how-to-delete-rows-from-a-pandas-dataframe-based-on-a-conditional-expression">deleting rows based on a condition</a> (I also found a not in, taking the list of chefs with unique dishes <a href="https://stackoverflow.com/questions/27965295/dropping-rows-from-dataframe-based-on-a-not-in-condition">here</a>), and <a href="https://stackoverflow.com/questions/48442561/how-to-group-data-on-pandas-with-multiple-conditions">grouping by different conditions</a></p> <p>This works for just a mean of all dishes of all chefs, which is not my objective:</p> <pre><code>df_chef.groupby(['chef_id', 'dish'], as_index=False).mean('price') </code></pre> <p>This is my trying so far, not being able to accomplish it.</p> <pre><code>df_uniques = df.groupby('chef_id')['dish'].unique() new_unique = df_uniques.to_frame().reset_index() to_del = new_unique.loc[((new_unique['dish'].apply(len)) == 1)] #if it has only 1 dish users_list = to_del['chef_id'].tolist() #list of chefs to delete modi_df = df208[~df208['chef_id'].isin(users_list)] modi_df.groupby(['chef_id','dish'])['price'].mean() modi_df </code></pre> <p>According to the <a href="https://www.statology.org/pandas-mean-by-group/" rel="nofollow noreferrer">docs</a>, once I have filtered out the chefs I don't want, I should be able to group by 2 cols, and then do a mean of one other col:</p> <pre><code>df.groupby(['group_col1', 'group_col2'])['value_col'].mean() </code></pre>
[ { "answer_id": 74290772, "author": "Robert Hacken", "author_id": 2094893, "author_profile": "https://Stackoverflow.com/users/2094893", "pm_score": 3, "selected": true, "text": "V1" }, { "answer_id": 74290792, "author": "Andre Wildberg", "author_id": 9462095, "author_profile": "https://Stackoverflow.com/users/9462095", "pm_score": 1, "selected": false, "text": "sapply(genes, function(x) df$V1[grep(paste(x, collapse=\"|\"), df$V2)])\n$a\n[1] \"ENSDARG00000010791\" \"ENSDARG00000056732\" \"ENSDARG00000094426\"\n[4] \"ENSDARG00000054560\"\n\n$b\n[1] \"ENSDARG00000008131\" \"ENSDARG00000068691\" \"ENSDARG00000057296\"\n[4] \"ENSDARG00000087798\"\n\n$c\n[1] \"ENSDARG00000091029\" \"ENSDARG00000006356\" \"ENSDARG00000014490\"\n[4] \"ENSDARG00000007406\" \"ENSDARG00000028306\"\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74290510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7396613/" ]
74,290,522
<p>a= 45 print (a) It starts saying name &quot;a&quot; is not defined</p> <p>What to do? Even if I copy code from somewhere and paste then it says invalid syntax.. Even if I type in everything correct, the response is same as invalid syntax.</p>
[ { "answer_id": 74290772, "author": "Robert Hacken", "author_id": 2094893, "author_profile": "https://Stackoverflow.com/users/2094893", "pm_score": 3, "selected": true, "text": "V1" }, { "answer_id": 74290792, "author": "Andre Wildberg", "author_id": 9462095, "author_profile": "https://Stackoverflow.com/users/9462095", "pm_score": 1, "selected": false, "text": "sapply(genes, function(x) df$V1[grep(paste(x, collapse=\"|\"), df$V2)])\n$a\n[1] \"ENSDARG00000010791\" \"ENSDARG00000056732\" \"ENSDARG00000094426\"\n[4] \"ENSDARG00000054560\"\n\n$b\n[1] \"ENSDARG00000008131\" \"ENSDARG00000068691\" \"ENSDARG00000057296\"\n[4] \"ENSDARG00000087798\"\n\n$c\n[1] \"ENSDARG00000091029\" \"ENSDARG00000006356\" \"ENSDARG00000014490\"\n[4] \"ENSDARG00000007406\" \"ENSDARG00000028306\"\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74290522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20398397/" ]
74,290,584
<p>Hello I've been trying to convert a HTML string to PDF in iText, it works and I get the file but any arabic text in the HTML is now showing, ofcourse I searched for a solution and found out that I need to register a font for arabic and I tried more than one font but no luck at all, here is my code and any help would be great</p> <pre><code>private void CreatePDFItextSharp() { string dataFile = Server.MapPath(&quot;~/Html.txt&quot;); string html = File.ReadAllText(dataFile); //StringReader sr = new StringReader(html); Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f); //Font normal = FontFactory.GetFont(&quot;c:/windows/fonts/arial.ttf&quot;, BaseFont.IDENTITY_H, 18, Font.BOLD); string arialFontFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), &quot;arial.ttf&quot;); FontFactory.Register(arialFontFile); XMLWorkerFontProvider fontProvider = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS); fontProvider.Register(arialFontFile); byte[] bytes; using (MemoryStream memoryStream = new MemoryStream()) { PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream); pdfDoc.Open(); var xmlWorker = XMLWorkerHelper.GetInstance(); MemoryStream htmlContent = new MemoryStream(Encoding.UTF8.GetBytes(html)); xmlWorker.ParseXHtml(writer, pdfDoc, htmlContent, null, Encoding.UTF8, fontProvider); pdfDoc.Close(); bytes = memoryStream.ToArray(); memoryStream.Close(); } Response.Clear(); Response.ContentType = &quot;application/pdf&quot;; Response.AddHeader(&quot;Content-Disposition&quot;, &quot;attachment; filename=Invoice.pdf&quot;); Response.Buffer = true; Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.BinaryWrite(bytes); Response.End(); Response.Close(); } </code></pre>
[ { "answer_id": 74333677, "author": "Hasan", "author_id": 11776477, "author_profile": "https://Stackoverflow.com/users/11776477", "pm_score": 1, "selected": true, "text": "XMLWorkerFontProvider(Environment.GetFolderPath(Environment.SpecialFolder.Fonts));" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74290584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11776477/" ]
74,290,620
<p>I want to convert the following array (<strong>userNameApp</strong>) into string so I can insert the following array into the database as a string</p> <pre><code> var userInfo = JSON.parse(window.localStorage.getItem('current-session')); const userNameApp = useState(userInfo['fname'] + &quot; &quot; + userInfo['lname']); console.log(userNameApp); </code></pre> <p>In the console log, the result is <strong>First Name + Last Name</strong>. When inserting in the database, I will post it like this</p> <pre><code> Axios.post(&quot;http://localhost:3001/insertActiveUser&quot;, {userNameApp: userNameApp})) </code></pre> <p>Inside the database schema/model, the type of Value is string.</p> <pre><code>const mongoose = require(&quot;mongoose&quot;); const User Details = new mongoose.Schema( { Username: String, }, { collection: &quot;AppointmentDetails&quot;, } ); </code></pre>
[ { "answer_id": 74290858, "author": "Nir Alfasi", "author_id": 1057429, "author_profile": "https://Stackoverflow.com/users/1057429", "pm_score": 1, "selected": false, "text": "userNameApp" }, { "answer_id": 74291423, "author": "John Ezkiel", "author_id": 14773795, "author_profile": "https://Stackoverflow.com/users/14773795", "pm_score": 0, "selected": false, "text": " var userInfo = JSON.parse(window.localStorage.getItem('current-session'));\n var getUserName = JSON.stringify(userInfo['fname'] + \" \" + userInfo['lname'])\n const userNameApp = JSON.parse(getUserName)\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74290620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14773795/" ]
74,290,642
<p><strong>Here is the code</strong></p> <pre><code>import os import redis import flask import json import urllib.parse from flask import Flask, Response, request, render_template, abort from flask_cors import CORS, cross_origin #from flask.ext.cors import CORS, cross_origin app = Flask(__name__) app.config['CORS_HEADERS'] = 'Content-Type' redis_handle = redis.Redis('localhost') requiredFields = (&quot;id&quot;, &quot;title&quot;, &quot;name&quot;) # fields required for user object @app.route('/') @cross_origin() def hello(): return 'Hello World!' @app.route('/users/&lt;user_id&gt;', methods=['GET']) @cross_origin() def get_user(user_id): response = {} # user_id = request.args.get(&quot;id&quot;) user = redis_handle.get(user_id) if not user: response[&quot;msg&quot;] = &quot;no user found&quot; return Response(json.dumps(response), status=404, mimetype=&quot;application/json&quot;) return user @app.route('/users', methods=['POST']) @cross_origin() def save_user(): data = request.get_json(force=True) response = {} if all(field in data for field in requiredFields): redis_handle.set(data[&quot;id&quot;], json.dumps(data)) return Response(status=201) else: missing_key = str([val for val in requiredFields if val not in dict(data).keys()]) response[&quot;msg&quot;] = &quot;required key &quot; + missing_key + &quot; not found&quot; return Response(json.dumps(response), status=400) @app.route('/users/&lt;user_id&gt;', methods=['DELETE']) @cross_origin() def delete_user(user_id): response = {} resp = redis_handle.delete(user_id) if resp == 0: response[&quot;msg&quot;] = &quot;no such entity found&quot; status = 404 else: response[&quot;msg&quot;] = &quot;Delete op is successful&quot; status = 200 return Response(json.dumps(response), status=status) @app.route('/clear', methods=['GET']) @cross_origin() def clear_data(): redis_handle.flushall() return &quot;ok!&quot; if __name__ == &quot;__main__&quot;: app.run(debug=True) </code></pre> <p><a href="https://i.stack.imgur.com/ZU19i.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZU19i.png" alt="enter image description here" /></a></p> <p>As of my knowledge, I have even included the method = &quot;POST&quot; as well but still don't know what is going wrong.</p> <p>I tried to create a small crud application using redis, python, flask but couldn't encountering this issue. Can someone tell me where and what am I doing wrong?</p>
[ { "answer_id": 74290858, "author": "Nir Alfasi", "author_id": 1057429, "author_profile": "https://Stackoverflow.com/users/1057429", "pm_score": 1, "selected": false, "text": "userNameApp" }, { "answer_id": 74291423, "author": "John Ezkiel", "author_id": 14773795, "author_profile": "https://Stackoverflow.com/users/14773795", "pm_score": 0, "selected": false, "text": " var userInfo = JSON.parse(window.localStorage.getItem('current-session'));\n var getUserName = JSON.stringify(userInfo['fname'] + \" \" + userInfo['lname'])\n const userNameApp = JSON.parse(getUserName)\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74290642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20398208/" ]
74,290,644
<p>I have data like this in a string column in a table: <code>[Product] -&gt; &quot;LA100_Runner_35C924_D&quot;</code>. From this data I want to get the data after the second <code>_</code>, so I want to get <code>35C924_D</code>.</p> <p>How do I do that?</p> <p>I tried <code>WHERE [Product] LIKE '%_%' escape ''</code> but I couldn't quite get it working. I can't think of what I want with the LIKE operation.</p>
[ { "answer_id": 74290885, "author": "lemon", "author_id": 12492890, "author_profile": "https://Stackoverflow.com/users/12492890", "pm_score": 1, "selected": true, "text": "SUBSTRING" }, { "answer_id": 74291105, "author": "Yitzhak Khabinsky", "author_id": 1932311, "author_profile": "https://Stackoverflow.com/users/1932311", "pm_score": 1, "selected": false, "text": "[position() ge 3]" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74290644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16901547/" ]
74,290,658
<p>I followed the following post to create a grid for hole africa: <a href="https://gis.stackexchange.com/questions/396667/adequate-crs-when-creating-a-grid-over-a-whole-continent-in-r">https://gis.stackexchange.com/questions/396667/adequate-crs-when-creating-a-grid-over-a-whole-continent-in-r</a></p> <p>Short version of the code:</p> <pre><code>africa &lt;- gisco_get_countries(region = &quot;Africa&quot;, resolution = 60, ) %&gt;% st_union() %&gt;% st_transform(3857) africa &lt;- africa %&gt;% st_transform(32732) grid &lt;- st_make_grid(africa, cellsize = 55000) %&gt;% st_intersection(africa) %&gt;% st_cast(&quot;MULTIPOLYGON&quot;) %&gt;% st_sf() %&gt;% mutate(id = row_number()) </code></pre> <p>Now I want to find the country of each grid cell. I tried the following:</p> <pre><code>remotes::install_github(&quot;constantin345/NOOA&quot;) library(NOOA) country &lt;- st_centroid(grid) country &lt;- as.data.frame(st_coordinates(country)) country$country &lt;-coords2country(country$Y, country$X) country$id &lt;- 1:11445 </code></pre> <p>With this code I have the problem, that if a centroid of a grid is not within the country (only next by), it gives me an NA - evethough parts of the grids are within an country. So I would like to add the &quot;next_by&quot; country, if no country is found in the first attempt. Any suggestions? Thanks!</p>
[ { "answer_id": 74290885, "author": "lemon", "author_id": 12492890, "author_profile": "https://Stackoverflow.com/users/12492890", "pm_score": 1, "selected": true, "text": "SUBSTRING" }, { "answer_id": 74291105, "author": "Yitzhak Khabinsky", "author_id": 1932311, "author_profile": "https://Stackoverflow.com/users/1932311", "pm_score": 1, "selected": false, "text": "[position() ge 3]" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74290658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18169859/" ]
74,290,666
<p>I've written a simplified example of the logic of the class, which I find confusing.</p> <pre><code>class Result: def __init__(self): self.limit = 10 self.params_with_error = [] def get_result(self, offset_range): qs = {'limit': self.limit} for chunk in range(offset_range): print(f'chunk: {chunk}') print(f'__Params_with_error__: {self.params_with_error}') qs.update({'offset': chunk * self.limit}) if chunk in (5, 7): print('IF condition') self.params_with_error.append(qs) print(f'Result param: {self.params_with_error}') result = Result() result.get_result(10) </code></pre> <p>And this code return</p> <pre><code>chunk: 0 __Params_with_error__: [] chunk: 1 __Params_with_error__: [] chunk: 2 __Params_with_error__: [] chunk: 3 __Params_with_error__: [] chunk: 4 __Params_with_error__: [] chunk: 5 __Params_with_error__: [] IF condition chunk: 6 __Params_with_error__: [{'limit': 10, 'offset': 50}] chunk: 7 __Params_with_error__: [{'limit': 10, 'offset': 60}] IF condition chunk: 8 __Params_with_error__: [{'limit': 10, 'offset': 70}, {'limit': 10, 'offset': 70}] chunk: 9 __Params_with_error__: [{'limit': 10, 'offset': 80}, {'limit': 10, 'offset': 80}] Result param: [{'limit': 10, 'offset': 90}, {'limit': 10, 'offset': 90}] </code></pre> <p>And I don't understand at all how such a result can come about. I expect that if the <code>if</code> condition occurs twice, the final result is equivalent to</p> <pre><code>[{'limit': 10, 'offset': 50}, {'limit': 10, 'offset': 70}] </code></pre> <p>Why does <code>self.params_with_error</code> continue to change further in the loop? I also don't understand why the final value of Result param: <code>[{'limit': 10, 'offset': 90}, {'limit': 10, 'offset': 90}]</code> How do I get the results I want?</p>
[ { "answer_id": 74290885, "author": "lemon", "author_id": 12492890, "author_profile": "https://Stackoverflow.com/users/12492890", "pm_score": 1, "selected": true, "text": "SUBSTRING" }, { "answer_id": 74291105, "author": "Yitzhak Khabinsky", "author_id": 1932311, "author_profile": "https://Stackoverflow.com/users/1932311", "pm_score": 1, "selected": false, "text": "[position() ge 3]" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74290666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9262339/" ]
74,290,670
<p>I have two arrays:</p> <p>Array 1:</p> <pre><code>['0000037_165', '0000037_62', '0000037_74', '0000037_165', ...] </code></pre> <p>Array 2:</p> <pre><code>[ {SiteUniqueID: '0000037_165', Description: 'Description 1'}, {SiteUniqueID: '0000037_165', Description: 'Description 2'}, {SiteUniqueID: '0000037_62', Description: 'Description 1'}, {SiteUniqueID: '0000037_74', Description: 'Description 1'}, {SiteUniqueID: '0000037_165', Description: 'Description 1'}, ... ] </code></pre> <p>I need to map over both arrays and check if the 'SiteUniqueID' from array 2 exists in array 1. If it exists in array 1 I then need to push the ID and the description into a new array.</p> <p>As seen in Array 2, a Site ID may have more than one description.</p> <p>So, the tricky part is that if the ID exists twice in array 2, then the description should be an array of all of the descriptions.</p> <p>I have played around with a mixture of .map() and .find() with no luck so far.</p> <p>I would like the resulting array to look like this:</p> <pre><code>[ {SiteUniqueID: '0000037_165', Description: ['Description 1', 'Description2']}, {SiteUniqueID: '0000037_62', Description: ['Description 1']}, {SiteUniqueID: '0000037_74', Description: ['Description 1']}, {SiteUniqueID: '0000037_165', Description: ['Description 1']}, ... ] </code></pre> <p>Any help is appreciated!</p>
[ { "answer_id": 74290885, "author": "lemon", "author_id": 12492890, "author_profile": "https://Stackoverflow.com/users/12492890", "pm_score": 1, "selected": true, "text": "SUBSTRING" }, { "answer_id": 74291105, "author": "Yitzhak Khabinsky", "author_id": 1932311, "author_profile": "https://Stackoverflow.com/users/1932311", "pm_score": 1, "selected": false, "text": "[position() ge 3]" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74290670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17950111/" ]
74,290,766
<p>I am creating a card which has a title and then below that it has other cards in columns of 2. The problem is that I want padding between the elements but not around them, at least not on the sides, since that makes the title misalign with the boxes below. Here is what I want:</p> <p><a href="https://i.stack.imgur.com/IFCNN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IFCNN.png" alt="enter image description here" /></a></p> <p>I have tried to give each green card a different padding, so the top left have a padding of 0 1em 1em 0, the top right have 0 0 1em 1em and so on. It would be cleaner though if I could have a generic solution with any given number of cards, columns, rows and not &quot;hard code&quot; the padding like that. Is this possible?</p> <p>One solution is to pad the title but that feels like an ugly solution.</p> <p>Top and bottom padding can be present if that makes it easier, I just can't have it on the left or right.</p> <p>The relevant code:</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>.content-card { width: 100%; padding: 2em 2em 2em; background: black; } .service-card { max-width: 100%; padding: 1em 1em 1em; background: grey; border-radius: 0.25em; } .row { width: 100%; display: flex; flex-direction: row; flex-wrap: wrap; } .column-2x2 { display: flex; flex-direction: column; flex-basis: 45%; padding: 1em 1em 1em; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="content-card"&gt; &lt;h2 style="color:white; font-size: 36px"&gt;Services.&lt;/h2&gt; &lt;br&gt; &lt;div class='row'&gt; &lt;div class='column-2x2'&gt; &lt;div class="service-card"&gt; &lt;h3 class=""&gt;Service 1.&lt;/h3&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class='column-2x2'&gt; &lt;div class="service-card"&gt; &lt;h3 class=""&gt;Service 2.&lt;/h3&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class='column-2x2'&gt; &lt;div class="service-card"&gt; &lt;h3 class=""&gt;Service 3.&lt;/h3&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class='column-2x2'&gt; &lt;div class="service-card"&gt; &lt;h3 class=""&gt;Service 4.&lt;/h3&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74290891, "author": "Amini", "author_id": 15351296, "author_profile": "https://Stackoverflow.com/users/15351296", "pm_score": 0, "selected": false, "text": "gap" }, { "answer_id": 74290944, "author": "Adam", "author_id": 12571484, "author_profile": "https://Stackoverflow.com/users/12571484", "pm_score": 3, "selected": true, "text": "grid-template-columns" }, { "answer_id": 74291561, "author": "Musyaffa Choirun Man", "author_id": 19981004, "author_profile": "https://Stackoverflow.com/users/19981004", "pm_score": 2, "selected": false, "text": "justify-content: space-between;\nalign-content: space-between;\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74290766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12053079/" ]
74,290,784
<p>Let's say I have a div in which there are two SVG elements : <em><strong>svgPlan</strong></em> and <em><strong>svgIcon</strong></em> (which is an SVG Image element).</p> <p><strong>svgPlan</strong>:</p> <p><a href="https://i.stack.imgur.com/q1At9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/q1At9.png" alt="SVG Plan" /></a></p> <p><strong>svgIcon</strong>:</p> <p><a href="https://i.stack.imgur.com/KZVZ0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KZVZ0.png" alt="SVG Icon" /></a></p> <p>A set of transformations (<em><strong>perspective</strong></em>, <em><strong>rotateX</strong></em>, <em><strong>scale</strong></em>, and <em><strong>translate</strong></em>) are applied on the parent element <strong>(<em>svgPlan</em>)</strong> :</p> <pre><code>svg.style('transform', 'perspective(30em) rotateX(33deg) scale(1.7) translate(0%, -6%)'); </code></pre> <p><strong>svgPlan after transformation</strong>:</p> <p><a href="https://i.stack.imgur.com/1SGoD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1SGoD.png" alt="SVG Plan after transformation" /></a></p> <p>I want to display the <em><strong>svgIcon</strong></em> inside the <em><strong>svgPlan</strong></em>.</p> <p><strong>THE PROBLEM :</strong> the transformations are applied on both the parent element <em><strong>svgPlan</strong></em> and the child <em><strong>svgIcon</strong></em>. It seems that the child is automaticlly inherting the styles applied on the parent and this is not what I want. I want the icon to appear whitout any effect.</p> <p><a href="https://i.stack.imgur.com/KP2xu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KP2xu.png" alt="What I have" /></a></p> <p><strong>THE QUESTION :</strong> How can I <em><strong>Disinherit</strong></em> my child element from father's style (which I beleive is not possible on SVG at the moment), or apply an <em><strong>Inverse Transformation</strong></em> to make the Icon appear without any perspective or style ?</p> <p><a href="https://i.stack.imgur.com/Ds9VP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ds9VP.png" alt="What I want" /></a></p> <p><strong>THE MINIMAL REPRODUCTIBLE EXAMPLE</strong> :</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code> &lt;div&gt; &lt;svg id="svgPlan" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 2118.5 624.2" enable-background="new 0 0 2118.5 624.2" xml:space="preserve" style="transform:perspective(30em) rotateX(30deg) scale(1.17)"&gt; &lt;rect width="1200" height="400" style="fill:rgb(224,224,224);stroke-width:3;stroke:rgb(0,0,0)" /&gt; &lt;g id="svgIcon"&gt; &lt;image x="550" y="120" width="120" height="120" xlink:href="https://svgshare.com/i/npz.svg"&gt; &lt;/image&gt; &lt;/g&gt; &lt;/svg&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>Thank you for your help.</p>
[ { "answer_id": 74332769, "author": "ardget", "author_id": 12793185, "author_profile": "https://Stackoverflow.com/users/12793185", "pm_score": 0, "selected": false, "text": "rotateX" }, { "answer_id": 74337813, "author": "myf", "author_id": 540955, "author_profile": "https://Stackoverflow.com/users/540955", "pm_score": 3, "selected": true, "text": "z-index" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74290784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7851433/" ]
74,290,844
<p>I'm updating a working app that targeted API 9 (Pie) to API 33 (Tiramisu) and the camera always returns <code>Result.Cancelled</code> to the <code>OnActivityResult</code> code. I'm using Visual Studio 2022 Version 17.3.6 on a Windows 11 pro machine. This is my camera code:</p> <pre><code>camerabutton.Click += (sender, evt) =&gt; { var cameraispresent = checkCameraHardware(this); if (cameraispresent) { try { CreateDirectoryForPictures(); MySubjectInfo.Name = MySubjectInfo.Name.Replace(&quot;,&quot;, &quot;&quot;); MySubjectInfo.Name = MySubjectInfo.Name.Replace(&quot; &quot;, &quot;&quot;); MySubjectInfo.Name = MySubjectInfo.Name.Replace(&quot;.&quot;, &quot;&quot;); var filename = MySubjectInfo.Name + &quot;.jpg&quot;; Intent intent = new Intent(MediaStore.ActionImageCapture); App._file = new File(App._dir, String.Format(filename, Guid.NewGuid())); intent.PutExtra(MediaStore.ExtraOutput, Uri.FromFile(App._file)); StartActivityForResult(intent, TakePictureRequestCode); } catch (Exception e) { var result = e.Message; }; } }; </code></pre> <p>The create directory code, this code was also updated to reflect changes in API 33, however I can't find the folder on my test device via file explorer where the photos should be stored yet <code>App._dir.Exists()</code> returns true saying it's there:</p> <pre><code> private void CreateDirectoryForPictures() { int version = (int)Android.OS.Build.VERSION.SdkInt; var root = &quot;&quot;; if (Android.OS.Environment.IsExternalStorageEmulated) { root = Android.OS.Environment.ExternalStorageDirectory.ToString(); } else { root = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyPictures); } if (version &gt;= Convert.ToInt32(BuildVersionCodes.Q)) { App._dir = new File(root + &quot;/PhotoManager&quot;); } else { App._dir = new File( Environment.GetExternalStoragePublicDirectory( Environment.DirectoryPictures), &quot;PhotoManager&quot;); } if (!App._dir.Exists()) { App._dir.Mkdirs(); } } </code></pre> <p>This is the app class where I store the data:</p> <pre><code>public static class App { public static File _file; public static File _dir; public static Bitmap bitmap; } </code></pre> <p>This is the <code>OnActivityResult1</code> code, I left my API 9 code in there commented out so you can see where I was and where I'm going. With API 9 I needed to resize the picture to scale it down to 160 X 100 as these photos are used for ID cards, I commented that code out until I can figure out why the camera intent is returning null:</p> <pre><code> protected override void OnActivityResult(int requestCode, Result resultCode, Intent data) { base.OnActivityResult(requestCode, resultCode, data); if (requestCode == TakePictureRequestCode &amp;&amp; resultCode == Result.Ok) { //Intent mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile); //Uri contentUri = Uri.FromFile(App._file); //mediaScanIntent.SetData(contentUri); //SendBroadcast(mediaScanIntent); Bitmap photo = (Bitmap)data.GetByteArrayExtra(&quot;data&quot;); App.bitmap = photo; //int height = 160; //Resources.DisplayMetrics.HeightPixels; //int width = 100; //MyImageView.Height; //App.bitmap = App._file.Path.LoadAndResizeBitmap(width, height); if (App.bitmap != null) { MyImageView.SetImageBitmap(App.bitmap); Bitmap bitmap = App.bitmap; var filePath = App._file.AbsolutePath; var stream = new System.IO.FileStream(filePath, System.IO.FileMode.Create); bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, stream); stream.Close(); bitmap = null; App.bitmap = null; PictureTaken = true; } // Dispose of the Java side bitmap. GC.Collect(); } } </code></pre> <p>So what am I doing wrong?</p>
[ { "answer_id": 74332769, "author": "ardget", "author_id": 12793185, "author_profile": "https://Stackoverflow.com/users/12793185", "pm_score": 0, "selected": false, "text": "rotateX" }, { "answer_id": 74337813, "author": "myf", "author_id": 540955, "author_profile": "https://Stackoverflow.com/users/540955", "pm_score": 3, "selected": true, "text": "z-index" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74290844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3149673/" ]
74,290,852
<p>I have this:</p> <p>df = pd.DataFrame({'my_col' : ['red', 'red', 'green']})</p> <pre><code>my_col red red green </code></pre> <p>I want this: df2 = pd.DataFrame({'red' : [True, True, False], 'green' : [False, False, True]})</p> <pre><code>red green True False True False False True </code></pre> <p>Is there an elegant way to do this?</p>
[ { "answer_id": 74290887, "author": "T C Molenaar", "author_id": 8814131, "author_profile": "https://Stackoverflow.com/users/8814131", "pm_score": 1, "selected": false, "text": "for color in df['my_col'].unique():\n df[color] = df['my_col'] == color\n\ndf2 = df[df['my_col'].unique()]\n" }, { "answer_id": 74290908, "author": "Naveed", "author_id": 3494754, "author_profile": "https://Stackoverflow.com/users/3494754", "pm_score": 0, "selected": false, "text": "# reset index, to keep the rows count\ndf=df.reset_index()\n\n# create a cross tab (don't miss negation for the resultset)\n~(pd.crosstab(index=[df['index'],df['my_col']], \n columns=df['my_col'])\n .reset_index() # cleanup to match the output\n .drop(columns=['index','my_col']) # drop unwanted columns\n .rename_axis(columns=None) # remove axis name\n .astype(bool)) # make it boolean\n" }, { "answer_id": 74291068, "author": "Olasimbo Arigbabu", "author_id": 1836069, "author_profile": "https://Stackoverflow.com/users/1836069", "pm_score": 1, "selected": false, "text": "get_dummies" }, { "answer_id": 74375217, "author": "Gonçalo Peres", "author_id": 7109869, "author_profile": "https://Stackoverflow.com/users/7109869", "pm_score": 1, "selected": false, "text": "df" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74290852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12350966/" ]
74,290,855
<p>Assume this dataset:</p> <pre><code>df = pd.DataFrame({ 'name': ['John','William', 'Nancy', 'Susan', 'Robert', 'Lucy', 'Blake', 'Sally', 'Bruce', 'Mike'], 'injury': ['right hand broken', 'lacerated left foot', 'foot broken', 'right foot fractured', '', 'sprained finger', 'chest pain', 'swelling in arm', 'laceration to arms, hands, and foot', np.NaN] }) name injury 0 John right hand broken 1 William lacerated left foot 2 Nancy foot broken 3 Susan right foot fractured 4 Robert 5 Lucy sprained finger 6 Blake chest pain 7 Sally swelling in arm 8 Bruce lacerations to arm, hands, and foot 9 Mike NaN 10 Jeff swollen cheek </code></pre> <p>I reduce the injuries to only the selected body part:</p> <pre><code>selected_words = [&quot;hand&quot;, &quot;foot&quot;, &quot;finger&quot;, &quot;chest&quot;, &quot;arms&quot;, &quot;arm&quot;, &quot;hands&quot;] df[&quot;injury&quot;] = ( df[&quot;injury&quot;] .str.replace(&quot;,&quot;, &quot;&quot;) .str.split(&quot; &quot;, expand=False) .apply(lambda x: &quot;, &quot;.join(set([i for i in x if i in selected_words]))) ) </code></pre> <p>But, this throws an error to the NaN value at index 9:</p> <pre><code>TypeError: 'float' object is not iterable </code></pre> <p>How would I modify the list comprehension such that:</p> <ol> <li><p>it checks for any NaN values</p> </li> <li><p>outputs <code>NaN</code> if it encounters a row that is blank or does not have a body part contained in the list of <code>selected_body_parts</code> (e.g. index 10)</p> </li> </ol> <p>The desired output is:</p> <pre><code>name injury 0 John hand 1 William foot 2 Nancy foot 3 Susan foot 4 Robert NaN 5 Lucy finger 6 Blake chest 7 Sally arm 8 Bruce hand, foot, arm 9 Mike NaN 10 Jeff NaN </code></pre> <p>I tried the following:</p> <pre><code>.apply(lambda x: &quot;, &quot;.join(set([i for i in x if i in selected_words and i is not np.nan else np.nan]))) </code></pre> <p>But, the syntax is incorrect.</p> <p>Any assistance would be most appreciated. Thanks!</p>
[ { "answer_id": 74290887, "author": "T C Molenaar", "author_id": 8814131, "author_profile": "https://Stackoverflow.com/users/8814131", "pm_score": 1, "selected": false, "text": "for color in df['my_col'].unique():\n df[color] = df['my_col'] == color\n\ndf2 = df[df['my_col'].unique()]\n" }, { "answer_id": 74290908, "author": "Naveed", "author_id": 3494754, "author_profile": "https://Stackoverflow.com/users/3494754", "pm_score": 0, "selected": false, "text": "# reset index, to keep the rows count\ndf=df.reset_index()\n\n# create a cross tab (don't miss negation for the resultset)\n~(pd.crosstab(index=[df['index'],df['my_col']], \n columns=df['my_col'])\n .reset_index() # cleanup to match the output\n .drop(columns=['index','my_col']) # drop unwanted columns\n .rename_axis(columns=None) # remove axis name\n .astype(bool)) # make it boolean\n" }, { "answer_id": 74291068, "author": "Olasimbo Arigbabu", "author_id": 1836069, "author_profile": "https://Stackoverflow.com/users/1836069", "pm_score": 1, "selected": false, "text": "get_dummies" }, { "answer_id": 74375217, "author": "Gonçalo Peres", "author_id": 7109869, "author_profile": "https://Stackoverflow.com/users/7109869", "pm_score": 1, "selected": false, "text": "df" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74290855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5179643/" ]
74,290,857
<p>I am trying implement a replacing mechanism for a string like prepared statements that are evaluated dynamicaly in javascript. I have replacements like</p> <pre><code>[{username:&quot;Max&quot;,age:10}] </code></pre> <p>Eg assume we have the string as input <code>(username) is (age)</code> so a find replace is easy by the attribute and its value.</p> <p>However I want something more advanced where parentheses are 'identified' and evaluted from the inner to outer eg for input:</p> <pre><code>[{username:&quot;Max&quot;,age:10,myDynamicAttribute:&quot;1&quot;,label1:'awesome', label2:'ugly'}] </code></pre> <p>and string <code>(username) is (age) and (label(myDynamicAttribute))</code>. In the first iteration of replacements the string should become <code>(username) is (age) and (label1)</code> and in second <code>Peter is 10 and awesome</code>. Is there any tool or pattern that I can use to 'understand' the inner parentheses first and the evaluate the other?. I tried regexes but I wasn't able to create a regex that matches the inner parentheses first and then the outer.</p>
[ { "answer_id": 74292009, "author": "Scott Sauyet", "author_id": 1243641, "author_profile": "https://Stackoverflow.com/users/1243641", "pm_score": 2, "selected": true, "text": "const interpolate = (data, str, parens = str .match (/\\(([^\\(\\)]+)\\)/)) =>\n parens ? interpolate (data, str. replace (parens [0], data [parens [1]])) : str\n\n\nconst data = {username: 'Max', age: 10, myDynamicAttribute: '1', label1: 'awesome', label2: 'ugly'}\nconst str = `(username) is (age) and (label(myDynamicAttribute))`\n\nconsole .log (interpolate (data, str))" }, { "answer_id": 74292380, "author": "trincot", "author_id": 5459839, "author_profile": "https://Stackoverflow.com/users/5459839", "pm_score": 2, "selected": false, "text": "function interpolate(encoded, lookup) {\n const tokens = encoded.matchAll(/[^()]+|./g);\n \n function* dfs(end=\"\") {\n while (true) {\n const {value, done} = tokens.next();\n if (value == end || done) return;\n if (value != \"(\") yield value;\n else {\n const key = [...dfs(\")\")].join(\"\");\n yield lookup[key] ?? `(${key})`;\n }\n }\n }\n return [...dfs()].join(\"\"); \n}\n\n// Example run\nconst lookup = {\n username: \"Max\",\n age: 10,\n myDynamicAttribute: \"1\",\n label1019: 'awesome(really)', // These parentheses are treated as literals\n really: \"not\", // ...so that this will not be retrieved\n label2: 'ugly',\n};\nconst str = \"1) (username) is (age) (uh!) and (label(myDynamicAttribute)0(myDynamicAttribute)9)\"\n\nconst res = interpolate(str, lookup);\nconsole.log(res);" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74290857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1864003/" ]
74,290,905
<p>I have custom post types for videos on my site. They are displayed on the pages in the form of cards. One post is a picture, a title for a video card, and a link. When you click on the card, a popup with a video should open. I display video cards using the WP_Query loop. My problem is that I don't know how to link to the video. The post does not have a single page. I need to somehow specify a link to it when creating a post and display it. How can i do 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>&lt;?php $video_link = get_field('video_link'); ?&gt; &lt;?php $case = new WP_Query( array( 'post_type' =&gt; 'videos', 'paged' =&gt; -1, 'order' =&gt; 'DESC', ) ); while ( $case-&gt;have_posts() ) : $case-&gt;the_post(); ?&gt; &lt;?php $cur_terms = get_the_terms( $case-&gt;post-&gt;ID, 'categories' ); ?&gt; &lt;li class="portfolio-section__item __js_masonry-item&gt; &lt;a class="project-preview project-preview--elastic" data-fancybox href="&lt;?php echo $video_link ?&gt;"&gt; &lt;span class="project-preview__image"&gt; &lt;img src="&lt;? the_post_thumbnail_url() ?&gt;" alt="&lt;?php the_title(); ?&gt;"&gt; &lt;span class="hover-button"&gt; &lt;svg width="17" height="19"&gt; &lt;use xlink:href="#triangle"&gt;&lt;/use&gt; &lt;/svg&gt; &lt;/span&gt; &lt;/span&gt; &lt;span class="project-preview__bottom"&gt; &lt;span class="project-preview__title"&gt;&lt;?php the_title(); ?&gt;&lt;/span&gt; &lt;span class="project-preview__icon"&gt; &lt;svg width="24" height="23"&gt; &lt;use xlink:href="#link-arrow2"&gt;&lt;/use&gt; &lt;/svg&gt; &lt;/span&gt; &lt;/span&gt; &lt;/a&gt; &lt;/li&gt; &lt;?php endwhile; $case-&gt;reset_postdata(); ?&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74294004, "author": "CChoma", "author_id": 1172496, "author_profile": "https://Stackoverflow.com/users/1172496", "pm_score": -1, "selected": false, "text": "// Hook a new metabox\nadd_action( 'add_meta_boxes', 'add_custom_box' );\nfunction add_custom_box() {\n $screens = [ 'videos' ];\n foreach ( $screens as $screen ) {\n add_meta_box(\n 'unique_box_identifier', // Unique ID\n 'Custom Meta Box Title', // Box title\n 'custom_box_html', // Content callback, this calls the markup function below\n $screen // Post type\n );\n }\n}\n\n// Field Markup\nfunction custom_box_html( $post ) {\n $value = get_post_meta( $post->ID, 'video_link', true );\n \n ?>\n\n <label for=\"video_link\">Link URL: </label>\n <input type=\"url\" name=\"video_link\" id=\"video_link\" value=\"<?php if (isset($value)) { echo $value; } ?>\" />\n\n <?php\n}\n\n// Save the metadata with the post\nadd_action( 'save_post', 'save_postdata' );\nfunction save_postdata( $post_id ) {\n if ( array_key_exists( 'video_link', $_POST ) ) {\n update_post_meta(\n $post_id,\n 'video_link',\n $_POST['video_link']\n );\n }\n}\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74290905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20398508/" ]
74,290,907
<p>Error on the site under cms wordpress. The site just suddenly stopped working.</p> <pre><code>Uncaught Error: Call to undefined function cache_users() in /www/wwwroot/beavers-auto.com/wp-includes/class-wp-user-query.php:843 Stack trace: #0 /www/wwwroot/beavers-auto.com/wp-includes/class-wp-user-query.php(79): WP_User_Query-&gt;query() #1 /www/wwwroot/beavers-auto.com/wp-includes/user.php(763): WP_User_Query-&gt;__construct() #2 /www/wwwroot/beavers-auto.com/wp-content/plugins/stm-post-type/stm-post-type.php(281): get_users() #3 /www/wwwroot/beavers-auto.com/wp-settings.php(447): include_once('...') #4 /www/wwwroot/beavers-auto.com/wp-config.php(84): require_once('...') #5 /www/wwwroot/beavers-auto.com/wp-load.php(50): require_once('...') #6 /www/wwwroot/beavers-auto.com/wp-blog-header.php(13): require_once('...') #7 /www/wwwroot/beavers-auto.com/index.php(17): require('...') #8 {main} thrown in /www/wwwroot/beavers-auto.com/wp-includes/class-wp-user-query.php on line 843 </code></pre> <p>Nothing happens when changing the code.</p>
[ { "answer_id": 74294004, "author": "CChoma", "author_id": 1172496, "author_profile": "https://Stackoverflow.com/users/1172496", "pm_score": -1, "selected": false, "text": "// Hook a new metabox\nadd_action( 'add_meta_boxes', 'add_custom_box' );\nfunction add_custom_box() {\n $screens = [ 'videos' ];\n foreach ( $screens as $screen ) {\n add_meta_box(\n 'unique_box_identifier', // Unique ID\n 'Custom Meta Box Title', // Box title\n 'custom_box_html', // Content callback, this calls the markup function below\n $screen // Post type\n );\n }\n}\n\n// Field Markup\nfunction custom_box_html( $post ) {\n $value = get_post_meta( $post->ID, 'video_link', true );\n \n ?>\n\n <label for=\"video_link\">Link URL: </label>\n <input type=\"url\" name=\"video_link\" id=\"video_link\" value=\"<?php if (isset($value)) { echo $value; } ?>\" />\n\n <?php\n}\n\n// Save the metadata with the post\nadd_action( 'save_post', 'save_postdata' );\nfunction save_postdata( $post_id ) {\n if ( array_key_exists( 'video_link', $_POST ) ) {\n update_post_meta(\n $post_id,\n 'video_link',\n $_POST['video_link']\n );\n }\n}\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74290907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20267137/" ]
74,290,917
<p>The essence of the task is this, I encode the bytes of the file, 1 byte of the source file = 4 bytes of the encrypted one. For example, the encoded byte is 3125890409. In byte representation, this is [186, 81, 77, 105]. For decryption, I must present this array as a single number. How can I first convert these 4 numbers to binary, and then to decimal and assign BigIntger? I thought to do it like this:</p> <pre><code>for(int i = 0; i &lt; fileData2.length; i+=4) { BigInteger message = BigInteger.valueOf(fileData2[i]); BigInteger message2 = BigInteger.valueOf(fileData2[i + 1]); BigInteger message3 = BigInteger.valueOf(fileData2[i + 2]); BigInteger message4 = BigInteger.valueOf(fileData2[i + 3]); } </code></pre> <p>And then translate each into binary, but it looks too complicated, and what if you need to do not 4 bytes, but 8 bytes and higher. How can it be implemented faster?</p>
[ { "answer_id": 74294004, "author": "CChoma", "author_id": 1172496, "author_profile": "https://Stackoverflow.com/users/1172496", "pm_score": -1, "selected": false, "text": "// Hook a new metabox\nadd_action( 'add_meta_boxes', 'add_custom_box' );\nfunction add_custom_box() {\n $screens = [ 'videos' ];\n foreach ( $screens as $screen ) {\n add_meta_box(\n 'unique_box_identifier', // Unique ID\n 'Custom Meta Box Title', // Box title\n 'custom_box_html', // Content callback, this calls the markup function below\n $screen // Post type\n );\n }\n}\n\n// Field Markup\nfunction custom_box_html( $post ) {\n $value = get_post_meta( $post->ID, 'video_link', true );\n \n ?>\n\n <label for=\"video_link\">Link URL: </label>\n <input type=\"url\" name=\"video_link\" id=\"video_link\" value=\"<?php if (isset($value)) { echo $value; } ?>\" />\n\n <?php\n}\n\n// Save the metadata with the post\nadd_action( 'save_post', 'save_postdata' );\nfunction save_postdata( $post_id ) {\n if ( array_key_exists( 'video_link', $_POST ) ) {\n update_post_meta(\n $post_id,\n 'video_link',\n $_POST['video_link']\n );\n }\n}\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74290917", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20139569/" ]
74,290,945
<pre><code>.navigationTitle(Text(&quot;Hello&quot;).foregroundColor(.orange)) .navigationBarTitleDisplayMode(.inline) </code></pre> <p>How do I add a foreground color to a Navigation Bar Title in SwiftUI? This is a watchOS app and everything I tried doesn't work.</p>
[ { "answer_id": 74294004, "author": "CChoma", "author_id": 1172496, "author_profile": "https://Stackoverflow.com/users/1172496", "pm_score": -1, "selected": false, "text": "// Hook a new metabox\nadd_action( 'add_meta_boxes', 'add_custom_box' );\nfunction add_custom_box() {\n $screens = [ 'videos' ];\n foreach ( $screens as $screen ) {\n add_meta_box(\n 'unique_box_identifier', // Unique ID\n 'Custom Meta Box Title', // Box title\n 'custom_box_html', // Content callback, this calls the markup function below\n $screen // Post type\n );\n }\n}\n\n// Field Markup\nfunction custom_box_html( $post ) {\n $value = get_post_meta( $post->ID, 'video_link', true );\n \n ?>\n\n <label for=\"video_link\">Link URL: </label>\n <input type=\"url\" name=\"video_link\" id=\"video_link\" value=\"<?php if (isset($value)) { echo $value; } ?>\" />\n\n <?php\n}\n\n// Save the metadata with the post\nadd_action( 'save_post', 'save_postdata' );\nfunction save_postdata( $post_id ) {\n if ( array_key_exists( 'video_link', $_POST ) ) {\n update_post_meta(\n $post_id,\n 'video_link',\n $_POST['video_link']\n );\n }\n}\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74290945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2332508/" ]
74,290,949
<pre><code>import numpy as np A = np.array([[2], [1], [3]]) A.shape # (3, 1) A.reshape(3,0) </code></pre> <pre><code>ValueError Traceback (most recent call last) &lt;ipython-input-12-771b3dbc4936&gt; in &lt;module&gt; ----&gt; 1 A.reshape(3,0) ValueError: cannot reshape array of size 3 into shape (3,0) </code></pre>
[ { "answer_id": 74294004, "author": "CChoma", "author_id": 1172496, "author_profile": "https://Stackoverflow.com/users/1172496", "pm_score": -1, "selected": false, "text": "// Hook a new metabox\nadd_action( 'add_meta_boxes', 'add_custom_box' );\nfunction add_custom_box() {\n $screens = [ 'videos' ];\n foreach ( $screens as $screen ) {\n add_meta_box(\n 'unique_box_identifier', // Unique ID\n 'Custom Meta Box Title', // Box title\n 'custom_box_html', // Content callback, this calls the markup function below\n $screen // Post type\n );\n }\n}\n\n// Field Markup\nfunction custom_box_html( $post ) {\n $value = get_post_meta( $post->ID, 'video_link', true );\n \n ?>\n\n <label for=\"video_link\">Link URL: </label>\n <input type=\"url\" name=\"video_link\" id=\"video_link\" value=\"<?php if (isset($value)) { echo $value; } ?>\" />\n\n <?php\n}\n\n// Save the metadata with the post\nadd_action( 'save_post', 'save_postdata' );\nfunction save_postdata( $post_id ) {\n if ( array_key_exists( 'video_link', $_POST ) ) {\n update_post_meta(\n $post_id,\n 'video_link',\n $_POST['video_link']\n );\n }\n}\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74290949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20397653/" ]
74,290,973
<p>i want to iterate a response and create an article section with each object</p> <p>I have the following piece of code that makes the request:</p> <pre><code>$.ajax({ type: &quot;POST&quot;, url: &quot;http://0.0.0.0:5001/api/v1/places_search/&quot;, data: JSON.stringify({}), dataType: 'json', contentType: &quot;application/json&quot;, success: function (list_of_places) { for (let place of list_of_places) { $(&quot;.places&quot;).append(&quot;&lt;article&gt;&lt;/article&gt;&quot;); // title box $(&quot;.places article&quot;).append(`&lt;div class=&quot;title_box&quot;&gt; &lt;h2&gt;${place['name']}&lt;/h2&gt; &lt;div class=&quot;price_by_night&quot;&gt;${place['price_by_night']}&lt;/div&gt; &lt;/div&gt;`); } } }); </code></pre> <p>here's a snippet of the html to edit:</p> <pre><code>&lt;section class=&quot;places&quot;&gt; &lt;!-- &lt;h1&gt;Places&lt;/h1&gt; --&gt; &lt;/section&gt; </code></pre> <p>here's a screenshot of the result of the snippet:</p> <p><a href="https://i.stack.imgur.com/qsyQa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qsyQa.png" alt="image of result of code snippet above" /></a></p> <p>How can I get only one object per article instead of all objects left in the iteration?</p>
[ { "answer_id": 74294004, "author": "CChoma", "author_id": 1172496, "author_profile": "https://Stackoverflow.com/users/1172496", "pm_score": -1, "selected": false, "text": "// Hook a new metabox\nadd_action( 'add_meta_boxes', 'add_custom_box' );\nfunction add_custom_box() {\n $screens = [ 'videos' ];\n foreach ( $screens as $screen ) {\n add_meta_box(\n 'unique_box_identifier', // Unique ID\n 'Custom Meta Box Title', // Box title\n 'custom_box_html', // Content callback, this calls the markup function below\n $screen // Post type\n );\n }\n}\n\n// Field Markup\nfunction custom_box_html( $post ) {\n $value = get_post_meta( $post->ID, 'video_link', true );\n \n ?>\n\n <label for=\"video_link\">Link URL: </label>\n <input type=\"url\" name=\"video_link\" id=\"video_link\" value=\"<?php if (isset($value)) { echo $value; } ?>\" />\n\n <?php\n}\n\n// Save the metadata with the post\nadd_action( 'save_post', 'save_postdata' );\nfunction save_postdata( $post_id ) {\n if ( array_key_exists( 'video_link', $_POST ) ) {\n update_post_meta(\n $post_id,\n 'video_link',\n $_POST['video_link']\n );\n }\n}\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74290973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17472207/" ]
74,290,994
<p>I'm trying to write a function that checks if a character is a number.</p> <p>I have:</p> <pre><code>isNumber:: Int -&gt; Bool isNumber x = x &gt;= 0 || x &gt;= 0 </code></pre> <p>also tried it with Guards, same problem.</p> <pre><code>isNumber2:: Int -&gt; Bool isNumber2 x | x &gt;= 0 = True | x &lt;= 0 = True | otherwise = False </code></pre> <p>When I enter a number it works, it says true. If I enter a character, an error comes out because a character is not an int. So I'm wondering if you can write something else instead of Int so that you can enter numbers and characters without an error coming up.</p> <p>I tried multiple different Typesignatures, but didnt work.</p>
[ { "answer_id": 74291127, "author": "Chris", "author_id": 15261315, "author_profile": "https://Stackoverflow.com/users/15261315", "pm_score": 0, "selected": false, "text": "Char" }, { "answer_id": 74291248, "author": "Noughtmare", "author_id": 15207568, "author_profile": "https://Stackoverflow.com/users/15207568", "pm_score": 1, "selected": false, "text": "Data.Char" }, { "answer_id": 74436413, "author": "Nicasio Marques", "author_id": 10033917, "author_profile": "https://Stackoverflow.com/users/10033917", "pm_score": 0, "selected": false, "text": "isNumber :: Char -> Bool\nisNumber c = c >= '0' && c <= '9'\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74290994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20292725/" ]
74,291,000
<p>I am a beginner in terms of coding. Python gives me the same error whenever I try to do calculation. I use python 3.9. I do not make typo when I enter input (this one was 5.2). Could you please help me?</p> <pre><code>&quot;&quot;&quot; length of rectangle = a width of rectangle = b calculate the area and perimeter of the rectangle &quot;&quot;&quot; a = 6 b = float(input(&quot;width: &quot;)) area = a*b perimeter = (2*a) + (2*b) print(&quot;area: &quot; + str(area) + &quot; perimeter: &quot; + str(perimeter)) </code></pre> <pre class="lang-none prettyprint-override"><code>Traceback (most recent call last): File &quot;c:\Users\HP\OneDrive - Karabuk University\Belgeler\Downloads\first.py&quot;, line 8, in &lt;module&gt; b = float(input(&quot;width: &quot;)) ValueError: could not convert string to float: '5.2&amp; </code></pre>
[ { "answer_id": 74291184, "author": "prakash pacharne", "author_id": 18381580, "author_profile": "https://Stackoverflow.com/users/18381580", "pm_score": -1, "selected": false, "text": "\"\"\"\nlength of rectangle = a\nwidth of rectangle = b\ncalculate the area and perimeter of the rectangle\n\"\"\"\n\na = 6\nb = float(input(\"width: \"))\n\narea = a*b\nperimeter = (2*a) + (2*b)\n\nprint(\"area: \" , area , \" perimeter: \" , perimeter)\n" }, { "answer_id": 74291196, "author": "山河以无恙", "author_id": 20209252, "author_profile": "https://Stackoverflow.com/users/20209252", "pm_score": 1, "selected": true, "text": "┌──[root@vms81.liruilongs.github.io]-[/]\n└─$vim demo.py\n┌──[root@vms81.liruilongs.github.io]-[/]\n└─$python3 demo.py\nwidth: 5.2\narea: 31.200000000000003 perimeter: 22.4\n┌──[root@vms81.liruilongs.github.io]-[/]\n└─$cat demo.py\n\"\"\"\nlength of rectangle = a\nwidth of rectangle = b\ncalculate the area and perimeter of the rectangle\n\"\"\"\n\na = 6\nb = float(input(\"width: \"))\n\narea = a*b\nperimeter = (2*a) + (2*b)\n\nprint(\"area: \" + str(area) + \" perimeter: \" + str(perimeter))\n┌──[root@vms81.liruilongs.github.io]-[/]\n└─$\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20397073/" ]
74,291,001
<p>I would like to remove the slash at the end of the URI, while keeping the query parameter.</p> <p><strong>For example:</strong></p> <p>I get an object of <strong>type URI</strong> as input with the value: <a href="https://stackoverflow.com/questions/ask/">https://stackoverflow.com/questions/ask/</a></p> <p>I would like to remove the last &quot;/&quot; to get: <a href="https://stackoverflow.com/questions/ask">https://stackoverflow.com/questions/ask</a></p> <hr /> <p>In some cases I may have parameters: <a href="https://stackoverflow.com/questions/ask/?test=test1">https://stackoverflow.com/questions/ask/?test=test1</a></p> <p>I would like to get: <a href="https://stackoverflow.com/questions/ask?test=test1">https://stackoverflow.com/questions/ask?test=test1</a></p> <p>Thanks in advance.</p>
[ { "answer_id": 74291057, "author": "cemahseri", "author_id": 10189024, "author_profile": "https://Stackoverflow.com/users/10189024", "pm_score": 0, "selected": false, "text": "?" }, { "answer_id": 74291230, "author": "Narish", "author_id": 12229910, "author_profile": "https://Stackoverflow.com/users/12229910", "pm_score": 2, "selected": false, "text": "string url1 = \"https://stackoverflow.com/questions/ask/\";\nstring url2 = \"https://stackoverflow.com/questions/ask/?test=test1\";\n\n//remove slash at end\nConsole.WriteLine(url1.TrimEnd('/'));\n\n//remove slash preceding query parameters\nint last = url2.LastIndexOf('?');\nurl2 = url2.Remove(last - 1, 1);\nConsole.WriteLine(url2);\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17335005/" ]
74,291,073
<p>I have a data file with column names like this (numbers in the name from 1 to 32):</p> <p><a href="https://i.stack.imgur.com/F16vA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/F16vA.png" alt="output file read in excel" /></a></p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">inlet_left_cell-10&lt;stl-unit=m&gt;-imprint)</th> <th style="text-align: center;">inlet_left_cell-11&lt;stl-unit=m&gt;-imprint)</th> <th style="text-align: right;">inlet_left_cell-12&lt;stl-unit=m&gt;-imprint)</th> <th style="text-align: left;">-------</th> <th style="text-align: center;">inlet_left_cell-9&lt;stl-unit=m&gt;-imprint)</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">data</td> <td style="text-align: center;">data</td> <td style="text-align: right;">data</td> <td style="text-align: left;">data</td> <td style="text-align: center;">data</td> </tr> <tr> <td style="text-align: left;">data</td> <td style="text-align: center;">data</td> <td style="text-align: right;">data</td> <td style="text-align: left;">data</td> <td style="text-align: center;">data</td> </tr> <tr> <td style="text-align: left;">....</td> <td style="text-align: center;">....</td> <td style="text-align: right;">...</td> <td style="text-align: left;">...</td> <td style="text-align: center;">....</td> </tr> </tbody> </table> </div> <p>I would like to sort the columns (with data) from left to right in python based on the number in the columns. I need to move a whole column based on the number in the column name.</p> <p>So xxx-1xxx, xxx-2xx, xxx-3xxx, ...... xxx-32xxx</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">inlet_left_cell-1&lt;stl-unit=m&gt;-imprint)</th> <th style="text-align: center;">inlet_left_cell-2&lt;stl-unit=m&gt;-imprint)</th> <th style="text-align: right;">inlet_left_cell-3&lt;stl-unit=m&gt;-imprint)</th> <th style="text-align: left;">-------</th> <th style="text-align: center;">inlet_left_cell-32&lt;stl-unit=m&gt;-imprint)</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">data</td> <td style="text-align: center;">data</td> <td style="text-align: right;">data</td> <td style="text-align: left;">data</td> <td style="text-align: center;">data</td> </tr> <tr> <td style="text-align: left;">data</td> <td style="text-align: center;">data</td> <td style="text-align: right;">data</td> <td style="text-align: left;">data</td> <td style="text-align: center;">data</td> </tr> <tr> <td style="text-align: left;">....</td> <td style="text-align: center;">....</td> <td style="text-align: right;">...</td> <td style="text-align: left;">...</td> <td style="text-align: center;">....</td> </tr> </tbody> </table> </div> <p>Is there any way to do this in python ? Thanks.</p>
[ { "answer_id": 74291215, "author": "Mato", "author_id": 20390882, "author_profile": "https://Stackoverflow.com/users/20390882", "pm_score": 1, "selected": false, "text": "import pandas as pd\n\ndata = pd.read_excel(\"D:\\\\..\\\\file_name.xlsx\")\ndata = data.reindex(sorted(data.columns), axis=1)\n" }, { "answer_id": 74291674, "author": "Bhargav", "author_id": 15358800, "author_profile": "https://Stackoverflow.com/users/15358800", "pm_score": 2, "selected": false, "text": "natsort" }, { "answer_id": 74291779, "author": "Abhi", "author_id": 7430727, "author_profile": "https://Stackoverflow.com/users/7430727", "pm_score": 3, "selected": true, "text": "# Some random data\ndata = np.random.randint(1,10, size=(100,32))\n\n# Setting up column names as given in your problem randomly ordered\ncolumns = [f'inlet_left_cell-{x}<stl-unit=m>-imprint)' for x in range(1,33)]\nnp.random.shuffle(columns)\n\n# Creating the dataframe\ndf = pd.DataFrame(data, columns=columns)\ndf.head()\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291073", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11047537/" ]
74,291,086
<p>I have been given some data in a text format that I would like to convert into a dataframe:</p> <pre><code>text &lt;- &quot; VALUE Ethnic 1 = 'White - British' 2 = 'White - Irish' 9 = 'White - Other' ; &quot; </code></pre> <p>I'm looking to convert into a dataframe with a column for the first number and a column for the test in the string. So - in this case, it would be two columns and three rows.</p>
[ { "answer_id": 74291200, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 2, "selected": false, "text": "library(tidyr)\nlibrary(dplyr)\ntibble(text = trimws(text)) %>% \n separate_rows(text, sep = \"\\n\") %>%\n filter(text != \";\") %>% \n slice(-1) %>% \n separate(text, into = c(\"VALUE\", \"Ethnic\"), sep = \"\\\\s+=\\\\s+\")\n" }, { "answer_id": 74292895, "author": "Being_shawn", "author_id": 20399922, "author_profile": "https://Stackoverflow.com/users/20399922", "pm_score": 0, "selected": false, "text": "time_serie = pd.read_fwf('/kaggle/input/bmfbovespas-time-series-19862019/COTAHIST_A'+str(year)+'.txt', \n header=None, colspecs=columns_width)\n\n# delete the first and the last lines containing identifiers\n# use two comented lines below to see them\n# output = pd.DataFrame(np.array([time_serie.iloc[0],time_serie.iloc[-1]]))\n# output\ntime_serie = time_serie.drop(time_serie.index[0])\ntime_serie = time_serie.drop(time_serie.index[-1])\nyears_concat = pd.concat([years_concat,time_serie],ignore_index=True)\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291086", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19414769/" ]
74,291,088
<p><a href="https://i.stack.imgur.com/Z4d1s.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Z4d1s.png" alt="enter image description here" /></a></p> <pre><code>WITH RECURSIVE CTE AS (SELECT MIN(period_start) as date FROM Sales UNION ALL SELECT DATE_ADD(date, INTERVAL 1 day) FROM CTE WHERE date &lt;= ALL (SELECT MAX(period_end) FROM Sales)) </code></pre> <p>What is the difference of using ALL in the where clause and not using ALL?</p> <p>I have tried both, all returns the same result.</p>
[ { "answer_id": 74291586, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 1, "selected": false, "text": "ALL" }, { "answer_id": 74292996, "author": "Being_shawn", "author_id": 20399922, "author_profile": "https://Stackoverflow.com/users/20399922", "pm_score": 0, "selected": false, "text": "ANY" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20398765/" ]
74,291,098
<p>the below is an example of controlling the play button. but how do i control the volume bar? my usual methods dont work.</p> <p>this is what i have now. my usual methods of trying to hit the element is not working.</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys import time driver = webdriver.Chrome('/Users/Max/Desktop/Code/Selenium/chromedriver') driver.get('https://www.youtube.com/watch?v=DXUAyRRkI6k') for i in range(10): print(i) time.sleep(1) player = driver.find_element_by_id('movie_player') player.send_keys(Keys.SPACE) time.sleep(1) player.click() </code></pre>
[ { "answer_id": 74291586, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 1, "selected": false, "text": "ALL" }, { "answer_id": 74292996, "author": "Being_shawn", "author_id": 20399922, "author_profile": "https://Stackoverflow.com/users/20399922", "pm_score": 0, "selected": false, "text": "ANY" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13262221/" ]
74,291,111
<p>Why AWK program's FS variable can be specified with -F flag of gawk (or other awk) interpreter/command?</p> <p>Let me explain, <a href="https://en.wikipedia.org/wiki/AWK" rel="nofollow noreferrer">AWK</a> is a programming language and <a href="https://www.gnu.org/software/gawk/" rel="nofollow noreferrer">gawk</a> is (one of many) an interpreter for AWK. gawk interpreter/execute/runs the AWK program that given to it. So why the FS (field separator) variable can be specified with gawk's -F flag? I find it kind of unnatural... and how does it technically do that?</p>
[ { "answer_id": 74291586, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 1, "selected": false, "text": "ALL" }, { "answer_id": 74292996, "author": "Being_shawn", "author_id": 20399922, "author_profile": "https://Stackoverflow.com/users/20399922", "pm_score": 0, "selected": false, "text": "ANY" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291111", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20398637/" ]
74,291,141
<p>I've used ggplot to create a number of diverging bar charts, using the following data and code:</p> <p><a href="https://i.stack.imgur.com/C3B15.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/C3B15.png" alt="Dataset" /></a></p> <pre><code>library(ggplot) library(gridExtra) # Import percentage change dataset LC_Pct_Change &lt;- read.csv(&quot;LC_%_Change_SA.csv&quot;, header=T) # Create plots for relevant periods PC_1930_1960 &lt;- ggplot(LC_Pct_Change, aes(x=Land_Cover_Category, y=Change_1930_1960)) + geom_bar(stat=&quot;identity&quot;, fill=ifelse(LC_Pct_Change$Change_1930_1960&lt;0,&quot;darksalmon&quot;, &quot;darkseagreen2&quot;), show.legend = FALSE) + geom_text(aes(label = round(Change_1930_1960, 1), hjust = 0.5, vjust = ifelse(Change_1930_1960 &lt; 0, 1.5, -1)), size = 2.5) + ggtitle(&quot;1930-1960&quot;) + xlab(&quot;Land Cover&quot;) + ylab(&quot;% Change&quot;) + theme_bw() + scale_x_discrete(limits = c(&quot;W&quot;, &quot;R&quot;, &quot;G&quot;, &quot;A&quot;, &quot;U&quot;)) # Repeated the above for each period # Then combine into a single plot to export PC_All &lt;- grid.arrange(PC_1930_1960, PC_1960_1990, PC_1990_2000, PC_2000_2007, PC_2007_2015, PC_2015_2020, PC_1930_2020, ncol=3) </code></pre> <p>The code I've got adds labels above and below the bars in the <code>geom_text</code> line, as below:<a href="https://i.stack.imgur.com/uOBbU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uOBbU.png" alt="Bar Chart example" /></a></p> <p>Instead, I'd like them to be in the centre (horizontally and vertically) of the bars. All the examples online I've found have been for bar charts with positive values only - even so I've tried several methods, but the most common way I've seen online is to add in something along the lines of <code>position = position_stack(vjust = .5)</code> into <code>geom_text</code>. But I can't get it to work.</p> <p>Edit: Adding dataset:</p> <pre><code>LC_Pct_Change &lt;- structure(list( Land_Cover_Category = c(&quot;W&quot;, &quot;R&quot;, &quot;G&quot;, &quot;A&quot;, &quot;U&quot;), Change_1930_1960 = c(1.984932164, -3.628139858, -1.446064637, 2.20879849, 0.880473841), Change_1960_1990 = c(1.56838857, -7.920867205, -1.967420952, 6.078769876, 2.241129711), Change_1990_2000 = c( 1.54170708, 0.909136716, -7.092356282, -2.215064057, 6.856576543 ), Change_2000_2007 = c(-1.244727434, 5.104227969, -0.328826854, 3.025170368, -6.555844049), Change_2007_2015 = c(1.254510492, -6.750375486, 5.846903583, -2.837464028, 2.486425439), Change_2015_2020 = c(0.998194067, -0.084741498, -0.2985041, -1.250054436, 0.635105966), Change_1990_2020 = c(2.549684204, -0.821752298, -1.872783653, -3.277412153, 3.4222639), Change_1930_2020 = c(6.103004939, -12.37075936, -5.286269243, 5.010156213, 6.543867451) ), class = &quot;data.frame&quot;, row.names = c(NA, -5L)) </code></pre>
[ { "answer_id": 74291362, "author": "lab_rat_kid", "author_id": 12717143, "author_profile": "https://Stackoverflow.com/users/12717143", "pm_score": 0, "selected": false, "text": "geom_text(aes(label = round(Change_1930_1960, 1), hjust = 0.5, y= (Change_1930_1960/2)), size = 2.5)" }, { "answer_id": 74291522, "author": "stefan", "author_id": 12993861, "author_profile": "https://Stackoverflow.com/users/12993861", "pm_score": 2, "selected": true, "text": "y" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12169695/" ]
74,291,145
<p>We would like to know from where the initial html document itself was served, either directly from the browser cache, our cdn cache or from origin. The later are easy (since our cdn adds server-timing to indicate a cache hit/miss), but figuring out if the document was served directly from the browser turned out more difficult.</p> <p>I know about developer tools/network tab and how Chrome for example can show this information, but <strong>this question is specifically about any JavaScript API that can be used to detect and report it to us</strong>.</p> <p>So far I've tried three things:</p> <ul> <li><p><code>var isCached = performance.getEntriesByType(&quot;navigation&quot;)[0].transferSize === 0;</code> from <a href="https://stackoverflow.com/questions/260043/how-can-i-use-javascript-to-detect-if-i-am-on-a-cached-page/51817474#51817474">this answer</a>, but today this seems to report the previous transferSize. When I try the same with the latest Chrome, I never get <code>transferSize === 0</code>, even when the devTools show me that it was cached. Possibly it only works for other resources, but not the html document itself.</p> </li> <li><p><code>var isCached = window.performance.navigation.type === 2</code> according to <a href="https://stackoverflow.com/a/27827274/66674">this answer</a> gets the navigation type (in this case backward/forward), which is not always a true indicator of the document being cached. E.g. clicking a link is of type <code>navigation</code> and can also be cached.</p> </li> <li><p>Storing the timestamp in the document itself as suggested <a href="https://stackoverflow.com/a/260076/66674">here</a> on the server and comparing it does not work either, especially since we are using a cdn that has its own cache. We wouldn't be able to differentiate between a cached version from cdn or the browser.</p> </li> </ul>
[ { "answer_id": 74404156, "author": "mlegrix", "author_id": 2561548, "author_profile": "https://Stackoverflow.com/users/2561548", "pm_score": 2, "selected": true, "text": "PerformanceNavigationTiming" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291145", "https://Stackoverflow.com", "https://Stackoverflow.com/users/66674/" ]
74,291,181
<p>I have a nested table that includes a list of emails, which could be inside several times. The problem is I need to get the distinct list of items, and the number of times it appears on the list.</p> <pre><code>| emails | | ------------ | | a@mail.com | | b@mail.com | | c@mail.com | | d@mail.com | | c@mail.com | | c@mail.com | | a@mail.com | | a@mail.com | | b@mail.com | | b@mail.com | | c@mail.com | </code></pre> <p>Ideally, my result would be a table or an output that tells me the following:</p> <pre><code>| Email | Number | | ---------- | - | | a@mail.com | 3 | | b@mail.com | 3 | | c@mail.com | 4 | | d@mail.com | 1 | </code></pre> <p>To select from a table I would use a select statement, but if I try this in my code I get an error &quot;ORA- 00942: table or view does not exist&quot; same with even a simple select from emails table so I'm just guessing you can't use select on nested tables that way.</p> <p>The nested table was created like this:</p> <pre><code>type t_email_type is table of varchar2(100); t_emails t_email_type := t_email_type(); </code></pre> <p>and then populated under a loop that adds an email for each iteration of the loop:</p> <pre><code>t_emails.extend; t_emails(t_emails.LAST) := user_r.email; </code></pre>
[ { "answer_id": 74404156, "author": "mlegrix", "author_id": 2561548, "author_profile": "https://Stackoverflow.com/users/2561548", "pm_score": 2, "selected": true, "text": "PerformanceNavigationTiming" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18785691/" ]
74,291,246
<p><strong>Problem</strong></p> <p>I have an issue while creating a dataframe in pandas. I am creating a new null data frame df2 from an existing data frame df1 with the same columns as shown below:</p> <pre><code>import pandas as pd import numpy as np df2 = df1.DataFrame(columns=df1.columns) </code></pre> <p>Now while in a loop, I add another column which stores an integer with 18 digits using the following code:</p> <pre><code>df2.loc[i, 'new column'] = 123123123123123123123123 </code></pre> <p>This, however, stores the result in the data frame in the exponential form as 1.231231231231e+17. It truncates the last two digits. I wish to store the value in the <code>new column</code> as an 18-digit integer itself.</p> <p>I tried two attempts to solve this.</p> <p><strong>Approach 1: Modification at the point of definition</strong></p> <pre><code>df2 = df1.DataFrame(columns=df1.columns) df2['new column'] = 0 df2['new column'] = df2['new column'].astype(np.int64) # also tried .apply(np.int64) </code></pre> <p><strong>Approach 2: Modification at the point of assignment</strong></p> <pre><code>df2.loc[i, 'new column'] = np.int64(123123123123123123123123) </code></pre> <p><em>Unfortunately, both solutions have not worked for me</em>.</p> <p><strong>Reproducible Code for More Clarity</strong></p> <pre><code>df1 = pd.DataFrame(data={'A':[123123123123123123, 234234234234234234, 345345345345345345], 'B':[11,22,33]}) df1 </code></pre> <p><em>Output</em>:</p> <pre><code> A B 0 123123123123123123 11 1 234234234234234234 22 2 345345345345345345 33 for i in range(df1.shape[0]): df1.loc[i, 'new column'] = 222222222222222222 df1 </code></pre> <p><em>Output</em>:</p> <pre><code> A B new column 0 123123123123123123 11 2.222222e+17 1 234234234234234234 22 2.222222e+17 2 345345345345345345 33 2.222222e+17 </code></pre> <p>When I try to convert it back, I get a different number.</p> <pre><code>df1['new column'] = df1['new column'].astype(np.int64) df1 </code></pre> <p>Output:</p> <pre><code> A B new column 0 123123123123123123 11 222222222222222208 1 234234234234234234 22 222222222222222208 2 345345345345345345 33 222222222222222208 </code></pre>
[ { "answer_id": 74291267, "author": "Abhi", "author_id": 7430727, "author_profile": "https://Stackoverflow.com/users/7430727", "pm_score": -1, "selected": false, "text": "np.float" }, { "answer_id": 74293994, "author": "naseefo", "author_id": 4001750, "author_profile": "https://Stackoverflow.com/users/4001750", "pm_score": 0, "selected": false, "text": "df1 = pd.DataFrame(data={'A':[123123123123123123, 234234234234234234, 345345345345345345], 'B':[11,22,33]})\n\ndf1['new column'] = df1['new column'].astype(object) # store as an object\n\nfor i in range(df1.shape[0]):\n df1.loc[i, 'new column'] = 222222222222222222\n\ndf1['new column'] = df1['new column'].astype(np.int64) # convert it to long integer after assignment of the value\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4001750/" ]
74,291,250
<p>I want to have an null safe Comparator. But I tried many ways ii doesn't work. **getBenefitLimit **is an **BigDecimal **value there no comparing BigDecimal values in Comparator. In that case how can figure this...</p> <p>My code and error Using with out null (<strong>Comparator.nullsFirst</strong>)</p> <pre><code>List&lt;ProductBenefitResponse&gt; list = new ArrayList&lt;&gt;(benefitMap.values()); list.sort(Comparator.comparing(ProductBenefitResponse::getDescription).thenComparing(ProductBenefitResponse::getBenefitLimit)); </code></pre> <p>Error must be :-</p> <pre><code>java.lang.NullPointerException: null at java.base/java.util.Comparator.lambda$comparing$77a9974f$1(Comparator.java:469) at java.base/java.util.Comparator.lambda$thenComparing$36697e65$1(Comparator.java:217) at java.base/java.util.TimSort.binarySort(TimSort.java:296) at java.base/java.util.TimSort.sort(TimSort.java:239) at java.base/java.util.Arrays.sort(Arrays.java:1515) at java.base/java.util.ArrayList.sort(ArrayList.java:1750) </code></pre> <p>My code and error Using with null (<strong>Comparator.nullsFirst</strong>)</p> <pre><code>List&lt;ProductBenefitResponse&gt; list = new ArrayList&lt;&gt;(benefitMap.values()); list.sort(Comparator.nullsFirst( Comparator.comparing(ProductBenefitResponse::getBenefitLimit) .thenComparing(ProductBenefitResponse::getDescription) )); </code></pre> <p>Error must be :-</p> <pre><code>java.lang.NullPointerException: null at java.base/java.math.BigDecimal.compareTo(BigDecimal.java:3065) at java.base/java.math.BigDecimal.compareTo(BigDecimal.java:228) at java.base/java.util.Comparator.lambda$comparing$77a9974f$1(Comparator.java:469) at java.base/java.util.Comparator.lambda$thenComparing$36697e65$1(Comparator.java:216) at java.base/java.util.Comparators$NullComparator.compare(Comparators.java:83) at java.base/java.util.TimSort.countRunAndMakeAscending(TimSort.java:355) at java.base/java.util.TimSort.sort(TimSort.java:234) at java.base/java.util.Arrays.sort(Arrays.java:1515) at java.base/java.util.ArrayList.sort(ArrayList.java:1750) </code></pre> <p>What is wrong in this code and please give me and answer...</p>
[ { "answer_id": 74291424, "author": "Rob Spoor", "author_id": 1180351, "author_profile": "https://Stackoverflow.com/users/1180351", "pm_score": 3, "selected": true, "text": "nullsFirst" }, { "answer_id": 74291637, "author": "Dev", "author_id": 20006696, "author_profile": "https://Stackoverflow.com/users/20006696", "pm_score": 0, "selected": false, "text": "List<ProductBenefitResponse> list = new ArrayList<>\n(benefitMap.values());list.sort(Comparator.comparing(ProductBenefitResponse::getDescription,Comparator.nullsLast(Comparator.naturalOrder()))\n .thenComparing(ProductBenefitResponse::getBenefitLimit,Comparator.nullsLast(Comparator.naturalOrder())));\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20006696/" ]
74,291,275
<p>I am currently trying to fill blanks in a data frame that looks like the following:</p> <pre><code> AL|ATFC|Year Latitude Longitude 0 AL011851 NaN NaN 1 NaN 28.0N 94.8W 2 NaN 28.0N 95.4W 3 NaN 28.0N 96.0W 4 NaN 28.1N 96.5W 5 NaN 28.2N 96.8W 6 NaN 28.2N 97.0W 7 NaN 28.3N 97.6W 8 NaN 28.4N 98.3W 9 NaN 28.6N 98.9W 10 NaN 29.0N 99.4W 11 NaN 29.5N 99.8W 12 NaN 30.0N 100.0W 13 NaN 30.5N 100.1W 14 NaN 31.0N 100.2W 15 AL021851 NaN NaN 16 NaN 22.2N 97.6W 17 AL031851 NaN NaN 18 NaN 12.0N 60.0W </code></pre> <p>I have been trying the following line of code with the goal to fill the <code>AL|ATFC|Year</code> column where I have <code>NaN</code> values with the pandas ffill() function.</p> <p><code>df.where(df['AL|ATFC|Year'] == float('NaN'), df['AL|ATFC|Year'].ffill(), axis=1, inplace=True)</code></p> <p>To get the following dataframe:</p> <pre><code> AL|ATFC|Year Latitude Longitude 0 AL011851 NaN NaN 1 AL011851 28.0N 94.8W 2 AL011851 28.0N 95.4W 3 AL011851 28.0N 96.0W 4 AL011851 28.1N 96.5W 5 AL011851 28.2N 96.8W 6 AL011851 28.2N 97.0W 7 AL011851 28.3N 97.6W 8 AL011851 28.4N 98.3W 9 AL011851 28.6N 98.9W 10 AL011851 29.0N 99.4W 11 AL011851 29.5N 99.8W 12 AL011851 30.0N 100.0W 13 AL011851 30.5N 100.1W 14 AL011851 31.0N 100.2W 15 AL021851 NaN NaN 16 AL021851 22.2N 97.6W 17 AL031851 NaN NaN 18 AL031851 12.0N 60.0W </code></pre> <p>Thereafter, I am planning the drop row with missing Lon/Lat values. However, the code I have been trying to use does not work to fill in the missing values in the <code>AL|ATFC|Year</code> column and I don't understand why...Any help would be much appreciated!</p> <p>Thanks</p>
[ { "answer_id": 74291741, "author": "Mat.B", "author_id": 14649447, "author_profile": "https://Stackoverflow.com/users/14649447", "pm_score": 1, "selected": false, "text": "'AL|ATFC|Year'" }, { "answer_id": 74292112, "author": "Emma", "author_id": 2956135, "author_profile": "https://Stackoverflow.com/users/2956135", "pm_score": 0, "selected": false, "text": "ffill" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11740254/" ]
74,291,277
<p>I thank you in advance for your help</p> <p>I am currently starting a Spring Boot project (Gradle) and when I run the <code>./gradlew bootRun</code> command on my VScode terminal, I get the following message:</p> <hr /> <p>APPLICATION FAILED TO START</p> <hr /> <p>Description:</p> <p>Web server failed to start. Port 8080 was already in use.</p> <p>Action:</p> <p>Identify and stop the process that's listening on port 8080 or configure this application to listen on another port.</p> <blockquote> <p>Task :bootRun FAILED</p> </blockquote> <p>FAILURE: Build failed with an exception.</p> <ul> <li>What went wrong: Execution failed for task ':bootRun'.</li> </ul> <blockquote> <p>Process 'command '/Library/Java/JavaVirtualMachines/jdk-17.0.5.jdk/Contents/Home/bin/java'' finished with non-zero exit value 1</p> </blockquote> <ul> <li>Try:</li> </ul> <blockquote> <p>Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.</p> </blockquote> <p>The problem is that I wasn't using my port 8080 at all (unless I'm mistaken, and if I am I don't know how to check it).</p> <p>I feel more like I have a problem with my JAVA.</p> <p>I will be very grateful to you for helping me find a solution to this problem. Thanking you in advance :)</p>
[ { "answer_id": 74291370, "author": "xerx593", "author_id": 592355, "author_profile": "https://Stackoverflow.com/users/592355", "pm_score": 1, "selected": false, "text": "netstat -aon | findstr 8080" }, { "answer_id": 74291390, "author": "George", "author_id": 11301941, "author_profile": "https://Stackoverflow.com/users/11301941", "pm_score": 0, "selected": false, "text": "8080" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20273846/" ]
74,291,315
<p>I have these two objects:</p> <pre><code>Vec&lt;-c(1,3,2) Matrix&lt;-rbind(c(4,2,3,0),c(2,9,1,0),c(2,2,9,9)) </code></pre> <p>For each row of the matrix I would like to use the corresponding value from Vec as an index to pull out the value from the matrix. E.g. for the first row c(4,2,3,0) I want to pick out the first element (4), for the second row c(2,9,1,0) I would like to pick out the third (1).</p> <p>The result I would like is:</p> <pre><code>Result&lt;-c(4,1,2) </code></pre>
[ { "answer_id": 74291329, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 2, "selected": false, "text": "matrix" }, { "answer_id": 74291452, "author": "ThomasIsCoding", "author_id": 12158757, "author_profile": "https://Stackoverflow.com/users/12158757", "pm_score": 1, "selected": false, "text": "> t(Matrix)[Vec + ncol(Matrix) * (seq_along(Vec) - 1)]\n[1] 4 1 2\n" }, { "answer_id": 74291762, "author": "Maël", "author_id": 13460602, "author_profile": "https://Stackoverflow.com/users/13460602", "pm_score": 1, "selected": false, "text": "diag" }, { "answer_id": 74291925, "author": "sindri_baldur", "author_id": 4552295, "author_profile": "https://Stackoverflow.com/users/4552295", "pm_score": 2, "selected": true, "text": "n = nrow(Vec)\nstopifnot(n == length(Vec))\nMatrix[1:n + n * (Vec - 1)]\n# [1] 4 1 2\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291315", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17974332/" ]
74,291,326
<p>I am relatively new to using map() in JavaScript so I'm still in the process of learning the ropes behind it. I am struggling to pull together all of my items in my list that only include a specific word, at the minute It's only pulling through the first item in the list. Can anyone please explain to me where I've gone wrong with this and what I need to do to fix this issue?</p> <p>Here is my code below for reference - Any help with this issue would be seriously appreciated.</p> <pre><code>&lt;div class=&quot;target-description&quot;&gt; &lt;li&gt;Model UK 8&lt;/li&gt; &lt;li&gt;Model Height 5 ft 8&lt;/li&gt; &lt;li&gt;Colour: Blue&lt;/li&gt; &lt;/div&gt; const addElement = function(){ const targetLI = [...document.querySelectorAll('.target-description li')]; targetLI.map((item) =&gt; { if (item.innerText.includes('Model')) { item.style.display = 'none'; const modelwear = document.createElement(&quot;div&quot;); const model = {}; let desc = item.innerText; model.desc = desc; modelwear.id = &quot;model&quot;; modelwear.innerHTML = `&lt;div class=&quot;model&quot;&gt; &lt;span class=&quot;model-header&quot;&gt;Model Information:&lt;/span&gt; &lt;div class=&quot;model-grid&quot;&gt; &lt;div class=&quot;model-img grid-item&quot;&gt; &lt;/div&gt; &lt;div class=&quot;model-copy grid-item&quot;&gt; &lt;span class=&quot;model-desc&quot;&gt;${model.desc}&lt;/span&gt;,&lt;br&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;`; const homepageTarget = document.querySelector('.target-description'); if (document.getElementById('model') === null) { const parent = homepageTarget.parentNode; parent.insertBefore(modelwear, homepageTarget); } else { document.querySelectorAll('.model-desc').innerText = desc; } } else if (!item.innerText.includes('Model')) { item.style.display = &quot;list-item&quot;; } }); }; addElement(); </code></pre>
[ { "answer_id": 74291329, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 2, "selected": false, "text": "matrix" }, { "answer_id": 74291452, "author": "ThomasIsCoding", "author_id": 12158757, "author_profile": "https://Stackoverflow.com/users/12158757", "pm_score": 1, "selected": false, "text": "> t(Matrix)[Vec + ncol(Matrix) * (seq_along(Vec) - 1)]\n[1] 4 1 2\n" }, { "answer_id": 74291762, "author": "Maël", "author_id": 13460602, "author_profile": "https://Stackoverflow.com/users/13460602", "pm_score": 1, "selected": false, "text": "diag" }, { "answer_id": 74291925, "author": "sindri_baldur", "author_id": 4552295, "author_profile": "https://Stackoverflow.com/users/4552295", "pm_score": 2, "selected": true, "text": "n = nrow(Vec)\nstopifnot(n == length(Vec))\nMatrix[1:n + n * (Vec - 1)]\n# [1] 4 1 2\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6204976/" ]
74,291,334
<p>I got a class like that:</p> <pre class="lang-rb prettyprint-override"><code>class Calculation def initialize heavy_calculation end def result 'ok' end def errors nil end private def heavy_calculation p &quot;Performing CPU-heavy calculations&quot; end end </code></pre> <p>And RSpec for checking both public methods</p> <pre class="lang-rb prettyprint-override"><code>describe Calculation do let(:calculations) { Calculation.new } it 'result equal ok' do expect(calculations.result).to eq('ok') end it 'errors equal nil' do expect(calculations.errors).to be_nil end end </code></pre> <p>Running this code we got two times <code>&quot;Performing CPU-heavy calculations&quot;</code> in the terminal, so the Calculation constructor was called twice</p> <p>I was trying to refactor this code so the constructor run only once - but didn't find any solution which works flawless, without running the calculation code twice, or without leaking values to other spec files</p> <p>So any advice on how to solve that correctly?</p>
[ { "answer_id": 74291746, "author": "ShockwaveNN", "author_id": 820501, "author_profile": "https://Stackoverflow.com/users/820501", "pm_score": 1, "selected": true, "text": "Heavy calculation" }, { "answer_id": 74296723, "author": "AndyV", "author_id": 1266795, "author_profile": "https://Stackoverflow.com/users/1266795", "pm_score": 1, "selected": false, "text": "let" }, { "answer_id": 74299304, "author": "Christos-Angelos Vasilopoulos", "author_id": 10429755, "author_profile": "https://Stackoverflow.com/users/10429755", "pm_score": 1, "selected": false, "text": "it" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/820501/" ]
74,291,337
<p>For example, there are objects that have similar structure but not exactly the same.</p> <pre><code>const arr = [ { name: 'john', age: 12 }, { name: 'marry', age: 24, married: true } ] </code></pre> <p>or</p> <pre><code>const obj = { john: { age: 12 }, marry: { age: 24, married: true } } </code></pre> <p>Let's say John is not married so he does not need <code>married</code> key. (Though it might be better to have 'married' as false for consistency.) This might not be a perfect example, but in either case is including <code>married</code> key and keeping the object structure consistent help performance by any chance? e.g. Maybe it might help CPU write the data to the memory faster...?</p>
[ { "answer_id": 74291746, "author": "ShockwaveNN", "author_id": 820501, "author_profile": "https://Stackoverflow.com/users/820501", "pm_score": 1, "selected": true, "text": "Heavy calculation" }, { "answer_id": 74296723, "author": "AndyV", "author_id": 1266795, "author_profile": "https://Stackoverflow.com/users/1266795", "pm_score": 1, "selected": false, "text": "let" }, { "answer_id": 74299304, "author": "Christos-Angelos Vasilopoulos", "author_id": 10429755, "author_profile": "https://Stackoverflow.com/users/10429755", "pm_score": 1, "selected": false, "text": "it" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15797746/" ]
74,291,342
<p>I have a formula that returns either <code>Unique</code> or <code>Duplicate</code> depending on whether there already exists another value in the same column.</p> <p>The formula <code>=IF(COUNTIF($A$2:$A2,A2)=1, &quot;Unique&quot;, &quot;Duplicate&quot;)</code> in <code>B2</code></p> <p>Example:</p> <pre><code> A B Peter | Unique James | Unique Peter | Duplicate Anne | Unique James | Duplicate </code></pre> <p>The formula works as it should but I am looking for an alternative formula that works with <code>arrayformula()</code></p> <p>The reason is because my data is dynamic which means the ranges change time and time again. It's not possible to manually drag the current formula each time the ranges change so an arrayformula for this would be very welcome.</p>
[ { "answer_id": 74291588, "author": "Harun24hr", "author_id": 5514747, "author_profile": "https://Stackoverflow.com/users/5514747", "pm_score": 2, "selected": false, "text": "BYROW()" }, { "answer_id": 74291590, "author": "Osm", "author_id": 19529694, "author_profile": "https://Stackoverflow.com/users/19529694", "pm_score": 2, "selected": true, "text": "A2:A" }, { "answer_id": 74291945, "author": "player0", "author_id": 5632629, "author_profile": "https://Stackoverflow.com/users/5632629", "pm_score": 1, "selected": false, "text": "=LAMBDA(x, INDEX(IF(COUNTIFS(x, x, ROW(x), \"<=\"&ROW(x))>1, \n \"duplicate\", \"unique\")))(A1:A5)\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16342780/" ]
74,291,348
<div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Column A</th> <th>Column B</th> </tr> </thead> <tbody> <tr> <td>JELLY ROSEN 15 JELLY STREET APT 111 JERSEY CITY, NJ</td> <td>15 JELLY STREET APT 111 JERSEY CITY, NJ</td> </tr> <tr> <td>ROB ROSEN &amp; STEVEN ROSEN 29 MAIN ST JERSEY CITY, NJ</td> <td>29 MAIN ST JERSEY CITY, NJ</td> </tr> </tbody> </table> </div> <p>I need the following: |** Column C ** | | JELLY ROSEN| | ROB ROSEN &amp; STEVEN ROSEN|</p> <p>I've tried something like this:</p> <pre><code>def address_name(COLUMN A, COLUMN B): return df['COLUMN A'][:df['COLUMN A'][0].find(df['COLUMN B'][0])] </code></pre>
[ { "answer_id": 74291588, "author": "Harun24hr", "author_id": 5514747, "author_profile": "https://Stackoverflow.com/users/5514747", "pm_score": 2, "selected": false, "text": "BYROW()" }, { "answer_id": 74291590, "author": "Osm", "author_id": 19529694, "author_profile": "https://Stackoverflow.com/users/19529694", "pm_score": 2, "selected": true, "text": "A2:A" }, { "answer_id": 74291945, "author": "player0", "author_id": 5632629, "author_profile": "https://Stackoverflow.com/users/5632629", "pm_score": 1, "selected": false, "text": "=LAMBDA(x, INDEX(IF(COUNTIFS(x, x, ROW(x), \"<=\"&ROW(x))>1, \n \"duplicate\", \"unique\")))(A1:A5)\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20398829/" ]
74,291,365
<p>I'm trying to index a list using a variable and &quot;test&quot; should check if indexer is out of date and then updating it through &quot;maybe&quot;, I've tried using &quot;global&quot; but I don't think I understand it fully and I've also tried to put &quot;indexer = indexer&quot; but that also won't work. Any solutions?</p> <pre><code>indexer = 0 list = [&quot;no&quot;, &quot;yes&quot;] maybe = 1 def test(): if indexer &lt;&lt; maybe: indexer = maybe print(&quot;boooo&quot;) test() </code></pre>
[ { "answer_id": 74291588, "author": "Harun24hr", "author_id": 5514747, "author_profile": "https://Stackoverflow.com/users/5514747", "pm_score": 2, "selected": false, "text": "BYROW()" }, { "answer_id": 74291590, "author": "Osm", "author_id": 19529694, "author_profile": "https://Stackoverflow.com/users/19529694", "pm_score": 2, "selected": true, "text": "A2:A" }, { "answer_id": 74291945, "author": "player0", "author_id": 5632629, "author_profile": "https://Stackoverflow.com/users/5632629", "pm_score": 1, "selected": false, "text": "=LAMBDA(x, INDEX(IF(COUNTIFS(x, x, ROW(x), \"<=\"&ROW(x))>1, \n \"duplicate\", \"unique\")))(A1:A5)\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19977489/" ]
74,291,419
<pre><code>def addition(num1, num2): answerAdd=num1+num2 print(answerAdd) def subtraction(num1, num2): answerSub=num1-num2 print(answerSub) def main(): num1=int(input('Enter the first number: ')) num2=int(input('Enter the second number: ')) print(addition, subtraction) main() </code></pre> <p>I've tried renaming the call function and can't get it to return the arithmetic,.</p>
[ { "answer_id": 74291446, "author": "Aymen", "author_id": 5165980, "author_profile": "https://Stackoverflow.com/users/5165980", "pm_score": 1, "selected": false, "text": "print(addition(num1, num2), subtraction(num1, num2))\n" }, { "answer_id": 74291479, "author": "JNevill", "author_id": 2221001, "author_profile": "https://Stackoverflow.com/users/2221001", "pm_score": 1, "selected": true, "text": "print" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20398983/" ]
74,291,439
<p>I have this one SQL string query:</p> <pre><code>SELECT company_id, COUNT(company_id) FROM core.non_ceased_companies_prod_unit GROUP BY company_id HAVING COUNT(company_id) &gt; 1 </code></pre> <p>The result is:</p> <p><a href="https://i.stack.imgur.com/D18Zg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/D18Zg.png" alt="enter image description here" /></a></p> <p>I want to have a sum of second column (which is &quot;No column name&quot;) and count of rows (now it's 4)</p> <p>So the result should be:</p> <pre><code>{ companies: 4 productions: 11 //(2+3+2+4) } </code></pre> <p>Query should be in Sequelize variant</p>
[ { "answer_id": 74291957, "author": "Tushar Gupta", "author_id": 2912094, "author_profile": "https://Stackoverflow.com/users/2912094", "pm_score": 2, "selected": false, "text": "SELECT COUNT(company_id) as companies, SUM(company_cnt) as productions FROM (\nSELECT company_id, COUNT(company_id) as company_cnt\nFROM core.non_ceased_companies_prod_unit\nGROUP BY company_id\nHAVING COUNT(company_id) > 1\n)foo\n" }, { "answer_id": 74292217, "author": "Mr. Polywhirl", "author_id": 1762224, "author_profile": "https://Stackoverflow.com/users/1762224", "pm_score": 2, "selected": true, "text": "CALL companyProductions();\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13099722/" ]
74,291,462
<p>I am fairly new to PowerBI/DAX. I am trying to figure out how I can dynamically calculate the # of blank values I have in every desired column.</p> <p>For example,</p> <pre><code>Column Header | Count Blank Rows City | 5 State | 2 Zip | 3 </code></pre> <p>I am hoping to avoid making many measures of COUNTBLANK(&quot;columnName&quot;) as I have many columns to run against. Looking for a way to do this in one measure that will calculate the blanks based on the columns selected in my visual.</p> <p><a href="https://i.stack.imgur.com/mTCZr.png" rel="nofollow noreferrer">Example of Table I am trying to create</a></p>
[ { "answer_id": 74291917, "author": "Mark Wojciechowicz", "author_id": 2568521, "author_profile": "https://Stackoverflow.com/users/2568521", "pm_score": 1, "selected": false, "text": "COUNTBLANK(MyTable[MyColumn])\n" }, { "answer_id": 74293446, "author": "Ozan Sen", "author_id": 19469088, "author_profile": "https://Stackoverflow.com/users/19469088", "pm_score": 0, "selected": false, "text": "CountBlankRowValues = \nCOUNTROWS(\n FILTER(\n SUMMARIZE(Geography,Geography[State],Geography[City],Geography[Zip]),\n Geography[State] = BLANK() || Geography[City] = BLANK() || Geography[Zip] = BLANK()\n )\n)\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291462", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6950227/" ]
74,291,507
<p>I have an RDS running in Region/AZ us-east-1f and an EC2 (after a reset to generate a new private key) running in us-east-1a. The EC2 can't reach the RDS and I think its because they're in different AZ's now. So I read this <a href="http://aws.amazon.com/premiumsupport/knowledge-center/move-ec2-instance/" rel="nofollow noreferrer">http://aws.amazon.com/premiumsupport/knowledge-center/move-ec2-instance/</a> on how to move the EC2. But when I try and execute the automated script/page the region field will only accept us-east-1 and not the letter after the 1. How do I tell the script to put the EC2 in us-east-1f (so it will be able to reach the RDS)? Thank you. Update: I'm now focused on making sure both RDS and EC2 are in the same VPC. The RDS is in the rds-launch-wizard VPC, and the EC2 is in a VPC I created. In order to change the RDS VPC you need to create a new subnet but I get an error message in doing that saying I need to select multiple AZ. I do select multiple AZ but the error message persists with the same message. This is frustrating.</p>
[ { "answer_id": 74291917, "author": "Mark Wojciechowicz", "author_id": 2568521, "author_profile": "https://Stackoverflow.com/users/2568521", "pm_score": 1, "selected": false, "text": "COUNTBLANK(MyTable[MyColumn])\n" }, { "answer_id": 74293446, "author": "Ozan Sen", "author_id": 19469088, "author_profile": "https://Stackoverflow.com/users/19469088", "pm_score": 0, "selected": false, "text": "CountBlankRowValues = \nCOUNTROWS(\n FILTER(\n SUMMARIZE(Geography,Geography[State],Geography[City],Geography[Zip]),\n Geography[State] = BLANK() || Geography[City] = BLANK() || Geography[Zip] = BLANK()\n )\n)\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9224871/" ]
74,291,543
<p>Given the following function:</p> <pre><code>fn some_function&lt;K, F: Fn(K) -&gt; K&gt;(f: F, vs: Vec&lt;K&gt;) -&gt; Vec&lt;K&gt; { let mut index = 0; let new_vec = vs.iter().map(|x| { index += 1; for _ in 1 .. index { x = f(x); // &lt;- error here: mismatched types expected reference `&amp;K` found type parameter `K` } *x }).collect(); new_vec } </code></pre> <p>How can i make it work ?</p>
[ { "answer_id": 74291659, "author": "jthulhu", "author_id": 5956261, "author_profile": "https://Stackoverflow.com/users/5956261", "pm_score": 1, "selected": true, "text": ".iter()" }, { "answer_id": 74291756, "author": "Matthieu M.", "author_id": 147192, "author_profile": "https://Stackoverflow.com/users/147192", "pm_score": 1, "selected": false, "text": ".into_iter()" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19623776/" ]
74,291,551
<pre class="lang-py prettyprint-override"><code>class SquareMatrix: def __init__(self, order): self.order = order self.rows = [ [0 for j in range(order)] for i in range(order)] def __str__(self): x = '' for row in self.rows: x = x + ' '.join(map(str, row))+'\n' return x def set_value(self, i, j, value): self.rows[i][j] = value def get_value(self, i, j): self.rows[i][j] def max(self): tomliste = [] for i in self.rows: for num in i: tomliste.append(num) tomliste.sort() return tomliste[-1] def min(self): tomliste = [] for i in self.rows: for num in i: tomliste.append(num) tomliste.sort() return tomliste[0] def trace(self): counter = 0 for i in range(self.order): counter = counter + int(self.rows[i][i]) return counter def summary(self): lib = {(f'order : {self.order}, max : {self.max()}, min : {self.min()}, trace : {self.trace()}')} return lib def save(self, filename): f = open(filename, &quot;w&quot;) f.write(str(self)) f.close() @classmethod def parse(cls, text): liste = [] for line in text.split('\n'): liste.append(line.split()) matrix = SquareMatrix(len(liste[1])) for i, line in enumerate(liste): matrix.rows[i] = line return matrix @classmethod def load(cls, filename): y = open(filename, 'r') y = y.read y = SquareMatrix.parse(y) return y m1 = SquareMatrix(3) m1.set_value(1,1,7) m1.get_value(2, 1) print(&quot;--m1--&quot;) print(m1) print(m1.summary()) m2_text = &quot;&quot;&quot;\ 1 2 3 4 5 6 7 8 9&quot;&quot;&quot; print(&quot;--m2--&quot;) m2 = SquareMatrix.parse(m2_text) print(m2) print(m2.summary()) m2.save(&quot;m3.txt&quot;) print(&quot;--m3--&quot;) m3 = SquareMatrix.load('m1.txt') print(m3) print(m3.summary()) </code></pre> <p>Im quite new to programing and can't figure out what has to be done. when finished it should look like this:</p> <pre class="lang-py prettyprint-override"><code>--m1-- 1 0 0 0 1 0 0 0 1 {'order': 3, 'max': 1, 'min': 0, 'trace': 3} --m2-- 1 2 3 4 5 6 7 8 9 {'order': 3, 'max': 9, 'min': 1, 'trace': 15} --m3-- 1 2 3 4 5 6 7 8 9 {'order': 3, 'max': 9, 'min': 1, 'trace': 15} </code></pre> <p>error: File &quot;c:\Users\marle\Documents\INFO132\maped6868_hoved2.py&quot;, line 96, in m3 = SquareMatrix.load('m1.txt') File &quot;c:\Users\marle\Documents\INFO132\maped6868_hoved2.py&quot;, line 72, in load y = SquareMatrix.parse(y) File &quot;c:\Users\marle\Documents\INFO132\maped6868_hoved2.py&quot;, line 58, in parse for line in text.split('\n'): AttributeError: 'builtin_function_or_method' object has no attribute 'split'</p>
[ { "answer_id": 74291659, "author": "jthulhu", "author_id": 5956261, "author_profile": "https://Stackoverflow.com/users/5956261", "pm_score": 1, "selected": true, "text": ".iter()" }, { "answer_id": 74291756, "author": "Matthieu M.", "author_id": 147192, "author_profile": "https://Stackoverflow.com/users/147192", "pm_score": 1, "selected": false, "text": ".into_iter()" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20399033/" ]
74,291,560
<p>I am compiling a simple c file with gcc on Linux and using readelf to find info of symbols. The function names (and perhaps other symbols - I didnt check) are trimmed to 25 characters.</p> <p>Is there a way to tell compiler/linker to keep longer symbols ?</p> <p>Versions:</p> <ol> <li>Compiler : gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-44)</li> </ol> <pre><code>&lt;prompt&gt;$ cat test_long_fnames_in_elf.c #include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; #include &lt;stdint.h&gt; void verly_long_function_xjsakdghajkshdlasjkldashjkldhasjklfdsjkhfsdjkhfsdjklhdsjkl_v1(uint32_t val) { int i = 0; for (i = 0 ; i &lt; val; i++) { printf(&quot;%d\n&quot;, i); } } void verly_long_function_xjsakdghajkshdlasjkldashjkldhasjklfdsjkhfsdjkhfsdjklhdsjkl_v2(uint32_t val) { int i = 0; for (i = 0 ; i &lt; val; i++) { printf(&quot;This is i = %d\n&quot;, i); } } int main() { verly_long_function_xjsakdghajkshdlasjkldashjkldhasjklfdsjkhfsdjkhfsdjklhdsjkl_v1(5); verly_long_function_xjsakdghajkshdlasjkldashjkldhasjklfdsjkhfsdjkhfsdjklhdsjkl_v2(5); } &lt;prompt&gt;$ gcc test_long_fnames_in_elf.c -g -o test_long_fnames_in_elf.elf &lt;prompt&gt;$ readelf -a te.elf | grep long &lt;prompt&gt;$ readelf -a test_long_fnames_in_elf.elf | grep long 41: 0000000000000000 0 FILE LOCAL DEFAULT ABS test_long_fnames_in_elf.c 52: 000000000040052d 61 FUNC GLOBAL DEFAULT 13 verly_long_function_xjsak &lt;-- Function symbol is trimmed 62: 000000000040056a 61 FUNC GLOBAL DEFAULT 13 verly_long_function_xjsak &lt;-- Function symbol is trimmed &lt;prompt&gt;$ </code></pre>
[ { "answer_id": 74301786, "author": "Alon Meirson", "author_id": 17789718, "author_profile": "https://Stackoverflow.com/users/17789718", "pm_score": -1, "selected": false, "text": " <prompt>$ objdump -t test_long_fnames_in_elf.elf | grep long\n test_long_fnames_in_elf.elf: file format elf64-x86-64\n 0000000000000000 l df *ABS* 0000000000000000 test_long_fnames_in_elf.c\n 000000000040052d g F .text 000000000000003d verly_long_function_xjsakdghajkshdlasjkldashjkldhasjklfdsjkhfsdjkhfsdjklhdsjkl_v1\n 000000000040056a g F .text 000000000000003d verly_long_function_xjsakdghajkshdlasjkldashjkldhasjklfdsjkhfsdjkhfsdjklhdsjkl_v2\n <prompt>$ \n" }, { "answer_id": 74311027, "author": "Employed Russian", "author_id": 50617, "author_profile": "https://Stackoverflow.com/users/50617", "pm_score": 0, "selected": false, "text": "readelf" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17789718/" ]
74,291,577
<p>I wanted to deploy Strapi CMS to Kubernetes. On my local machine, I am trying to do this with Minikube. The structure of the project is MySQL in a different container outside of the cluster. I want to access the MySQL database from inside the cluster via this IP <code>172.17.0.2:3306</code></p> <p>The Database is outside of the cluster and lives in a docker container. But the Strapi project lives in a cluster of Kubernetes.</p> <p>This is my deployment YAML file for doing the Kubernetes stuff:</p> <pre><code>apiVersion: apps/v1 kind: Deployment metadata: name: cg-api spec: selector: matchLabels: app: cg-api replicas: 2 template: metadata: labels: app: cg-api spec: containers: - name: cg-api image: alirezahd/cg-api env: - name: DATABASE_HOST value: &quot;172.17.0.2&quot; - name: DATABASE_PORT value: &quot;3306&quot; ports: - containerPort: 1337 </code></pre>
[ { "answer_id": 74292657, "author": "TJ H.", "author_id": 13541559, "author_profile": "https://Stackoverflow.com/users/13541559", "pm_score": 1, "selected": false, "text": "3306:3306" }, { "answer_id": 74293006, "author": "aka Pipo", "author_id": 11099788, "author_profile": "https://Stackoverflow.com/users/11099788", "pm_score": 3, "selected": true, "text": "docker run -p 192.168.0.100:3306:3306/tcp mysql-container-name bash\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10051714/" ]
74,291,597
<p>Facing error as &quot;Git not found&quot; in VS Code in Mac OS Ventura.</p> <p>How to resolve this error in VS Code on mac? Any Help is appreciated :)</p> <p>NOTE: My GIT is working fine in Terminal but only isn’t recognized in VS Code Source Control (3rd Icon in the left bar)</p>
[ { "answer_id": 74291872, "author": "Lightning", "author_id": 9439227, "author_profile": "https://Stackoverflow.com/users/9439227", "pm_score": 2, "selected": false, "text": "xcode-select --install" }, { "answer_id": 74292268, "author": "Sudir Krishnaa RS", "author_id": 13657002, "author_profile": "https://Stackoverflow.com/users/13657002", "pm_score": 2, "selected": false, "text": " git -version\n" }, { "answer_id": 74501375, "author": "light", "author_id": 17332307, "author_profile": "https://Stackoverflow.com/users/17332307", "pm_score": 1, "selected": false, "text": "git -v" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13657002/" ]
74,291,608
<p>If I create a number of application pools, and then create an application but don't specify which application pool it should run in, which one does it use?</p> <p>Is it random? Does it always take the first one? Something else?</p>
[ { "answer_id": 74297733, "author": "YurongDai", "author_id": 19696445, "author_profile": "https://Stackoverflow.com/users/19696445", "pm_score": 2, "selected": false, "text": "appcmd add app/site.name:test/path:/blig/physicalPath:C:\\inetpub\\app1 ---Create app1\n\nappcmd list app \"test/app1\" ---Verify the Apppool used by app1 by default\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7607408/" ]
74,291,620
<p>I have a table which has the following format (Google Big query) :</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>user</th> <th>url</th> <th>val1</th> <th>val2</th> <th>val3</th> <th>...</th> <th>val300</th> </tr> </thead> <tbody> <tr> <td>A</td> <td>a</td> <td>0.5</td> <td>0</td> <td>-3</td> <td>...</td> <td>1</td> </tr> <tr> <td>A</td> <td>b</td> <td>1</td> <td>2</td> <td>3</td> <td>...</td> <td>2</td> </tr> <tr> <td>B</td> <td>c</td> <td>5</td> <td>4</td> <td>-10</td> <td>...</td> <td>2</td> </tr> </tbody> </table> </div> <p>I would like to obtain a new table where I obtain the number of urls by user, and vals are aggregated by average. (The number of different vals can be variable so I would like to have something rather flexible)</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>user</th> <th>nb_url</th> <th>val1</th> <th>val2</th> <th>val3</th> <th>...</th> <th>val300</th> </tr> </thead> <tbody> <tr> <td>A</td> <td>2</td> <td>0.75</td> <td>1</td> <td>0</td> <td>...</td> <td>1.5</td> </tr> <tr> <td>B</td> <td>1</td> <td>...</td> <td></td> <td></td> <td></td> <td></td> </tr> </tbody> </table> </div> <p>What is the good syntax?</p> <p>Thank you in advance</p>
[ { "answer_id": 74291713, "author": "Tim Biegeleisen", "author_id": 1863229, "author_profile": "https://Stackoverflow.com/users/1863229", "pm_score": 2, "selected": true, "text": "SELECT\n user,\n COUNT(*) AS nb_url,\n AVG(val1) AS val1,\n AVG(val2) AS val2,\n AVG(val3) AS val3,\n ...\n AVG(val300) AS val300\nFROM yourTable\nGROUP BY user\nORDER BY user;\n" }, { "answer_id": 74298360, "author": "Mikhail Berlyant", "author_id": 5221944, "author_profile": "https://Stackoverflow.com/users/5221944", "pm_score": 0, "selected": false, "text": "select user, count(url) nb_url, \n offset + 1 col, avg(cast(val as float64)) as val\nfrom your_table t,\nunnest(split(translate(format('%t', (select as struct * except(user, url) from unnest([t]))), '() ', ''))) val with offset\ngroup by user, col \n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17141604/" ]
74,291,625
<p>I am retrieving data via api and I want to save all data regardless if a key is missing or not.</p> <p>Here is my code which saves the data only when the key is present.</p> <pre><code>#get all of the initial users initialUsers = requests.get(url, headers=headers) data = initialUsers.json() userData = data['data'] # write to a txt file with open('Users.txt', 'x', encoding='utf-8') as f: for i in userData: if i.get('presence_id') is not None: sheet=(i['username']+&quot; &quot;,i['first_name']+&quot; &quot;, i['last_name']+&quot; &quot;, i['presence_id']) f.write(str(sheet)+&quot;\n&quot;) </code></pre> <p><strong>presence_id</strong> is the key that is sometimes present.</p> <p>How can I modify this to save all the data regardless if they key is present or not?</p>
[ { "answer_id": 74291705, "author": "Steinn Hauser Magnusson", "author_id": 13819183, "author_profile": "https://Stackoverflow.com/users/13819183", "pm_score": 1, "selected": false, "text": "# ...\nwith open('Users.txt', 'x', encoding='utf-8') as f:\n for i in userData:\n default_data = {\"username\":\"\", \"first_name\":\"\", \"last_name\":\"\"}\n output = i.get('presence_id', default_data) # this will never be None. Equals default_data if \"presence_id\" is not found.\n sheet=(output['username']+\" \",output['first_name']+\" \", output['last_name']+\" \", output['presence_id'])\n f.write(str(sheet)+\"\\n\")\n \n" }, { "answer_id": 74292371, "author": "mrOlympia", "author_id": 18292391, "author_profile": "https://Stackoverflow.com/users/18292391", "pm_score": 0, "selected": false, "text": "for i in userData:\n i.setdefault('presence_id', \"No ext\")\n sheet=(i['username']+\" \",i['first_name']+\" \", i['last_name']+\" \", i['presence_id'])\n f.write(str(sheet)+\"\\n\")\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18292391/" ]
74,291,632
<p>In angular app I have assets/config.json file and I am want read file this while inialisiang app.</p> <p>When run with ng serve locally I can access file with http://localhost:4200/assets/config.json</p> <p>But when I hosted app in IIS on server, getting 404 error for URL http://my-web-server/assets/config.json.</p> <p>When run with ng serve locally I can access file with http://localhost:4200/assets/config.json</p>
[ { "answer_id": 74291705, "author": "Steinn Hauser Magnusson", "author_id": 13819183, "author_profile": "https://Stackoverflow.com/users/13819183", "pm_score": 1, "selected": false, "text": "# ...\nwith open('Users.txt', 'x', encoding='utf-8') as f:\n for i in userData:\n default_data = {\"username\":\"\", \"first_name\":\"\", \"last_name\":\"\"}\n output = i.get('presence_id', default_data) # this will never be None. Equals default_data if \"presence_id\" is not found.\n sheet=(output['username']+\" \",output['first_name']+\" \", output['last_name']+\" \", output['presence_id'])\n f.write(str(sheet)+\"\\n\")\n \n" }, { "answer_id": 74292371, "author": "mrOlympia", "author_id": 18292391, "author_profile": "https://Stackoverflow.com/users/18292391", "pm_score": 0, "selected": false, "text": "for i in userData:\n i.setdefault('presence_id', \"No ext\")\n sheet=(i['username']+\" \",i['first_name']+\" \", i['last_name']+\" \", i['presence_id'])\n f.write(str(sheet)+\"\\n\")\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1414709/" ]
74,291,640
<p>The record set consists of 3 record types 01,11,19.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">recType</th> <th style="text-align: left;">Value</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">01</td> <td style="text-align: left;">8888</td> </tr> <tr> <td style="text-align: left;">11</td> <td style="text-align: left;">asssff</td> </tr> <tr> <td style="text-align: left;">19</td> <td style="text-align: left;">78292</td> </tr> <tr> <td style="text-align: left;">01</td> <td style="text-align: left;">77777</td> </tr> <tr> <td style="text-align: left;">11</td> <td style="text-align: left;">aslasd</td> </tr> <tr> <td style="text-align: left;">19</td> <td style="text-align: left;">08325</td> </tr> </tbody> </table> </div> <p>I want to create a '''sequence''' column so that I have unique identifier for recordset. I tried '''groupby''' and '''aggregate''' but I am not getting what I desired. The desired output dataframe is as below:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">recType</th> <th style="text-align: left;">Value</th> <th style="text-align: left;">sequence</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">01</td> <td style="text-align: left;">8888</td> <td style="text-align: left;">1</td> </tr> <tr> <td style="text-align: left;">11</td> <td style="text-align: left;">asssff</td> <td style="text-align: left;">1</td> </tr> <tr> <td style="text-align: left;">19</td> <td style="text-align: left;">78292</td> <td style="text-align: left;">1</td> </tr> <tr> <td style="text-align: left;">01</td> <td style="text-align: left;">77777</td> <td style="text-align: left;">2</td> </tr> <tr> <td style="text-align: left;">11</td> <td style="text-align: left;">aslasd</td> <td style="text-align: left;">2</td> </tr> <tr> <td style="text-align: left;">19</td> <td style="text-align: left;">08325</td> <td style="text-align: left;">2</td> </tr> </tbody> </table> </div> <p>kindly help.</p>
[ { "answer_id": 74291705, "author": "Steinn Hauser Magnusson", "author_id": 13819183, "author_profile": "https://Stackoverflow.com/users/13819183", "pm_score": 1, "selected": false, "text": "# ...\nwith open('Users.txt', 'x', encoding='utf-8') as f:\n for i in userData:\n default_data = {\"username\":\"\", \"first_name\":\"\", \"last_name\":\"\"}\n output = i.get('presence_id', default_data) # this will never be None. Equals default_data if \"presence_id\" is not found.\n sheet=(output['username']+\" \",output['first_name']+\" \", output['last_name']+\" \", output['presence_id'])\n f.write(str(sheet)+\"\\n\")\n \n" }, { "answer_id": 74292371, "author": "mrOlympia", "author_id": 18292391, "author_profile": "https://Stackoverflow.com/users/18292391", "pm_score": 0, "selected": false, "text": "for i in userData:\n i.setdefault('presence_id', \"No ext\")\n sheet=(i['username']+\" \",i['first_name']+\" \", i['last_name']+\" \", i['presence_id'])\n f.write(str(sheet)+\"\\n\")\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10164750/" ]
74,291,652
<p>Hello I have my code that copy the html from external url and echo it on my page. Some of the HTMLs have links and/or picure SRC inside. I will need some help to truncate them (from absolute url to relative url inside $data )</p> <p>For example : inside html there is href</p> <pre><code>&lt;a href=&quot;https://www.trade-ideas.com/products/score-vs-ibd/&quot; &gt; or SRC &lt;img src=&quot;http://static.trade-ideas.com/Filters/MinDUp1.gif&quot;&gt; </code></pre> <p>I would like to keep only subdirectory.</p> <p>/products/score-vs-ibd/z</p> <p>/Filters/MinDUp1.gif</p> <p>Maybe with preg_replace , but im not familiar with Regular expressions.</p> <p>This is my original code that works very well, but now im stuck truncating the links.</p> <pre><code>&lt;?php $post_tags = get_the_tags(); if ( $post_tags ) { $tag = $post_tags[0]-&gt;name; } $html= file_get_contents('https://www.trade-ideas.com/ticky/ticky.html?symbol='. &quot;$tag&quot;); $start = strpos($html,'&lt;div class=&quot;span3 height-325&quot;'); $end = strpos($html,'&lt;!-- /span --&gt;',$start); $data= substr($html,$start,$end-$start); echo $data ; ?&gt; </code></pre>
[ { "answer_id": 74291705, "author": "Steinn Hauser Magnusson", "author_id": 13819183, "author_profile": "https://Stackoverflow.com/users/13819183", "pm_score": 1, "selected": false, "text": "# ...\nwith open('Users.txt', 'x', encoding='utf-8') as f:\n for i in userData:\n default_data = {\"username\":\"\", \"first_name\":\"\", \"last_name\":\"\"}\n output = i.get('presence_id', default_data) # this will never be None. Equals default_data if \"presence_id\" is not found.\n sheet=(output['username']+\" \",output['first_name']+\" \", output['last_name']+\" \", output['presence_id'])\n f.write(str(sheet)+\"\\n\")\n \n" }, { "answer_id": 74292371, "author": "mrOlympia", "author_id": 18292391, "author_profile": "https://Stackoverflow.com/users/18292391", "pm_score": 0, "selected": false, "text": "for i in userData:\n i.setdefault('presence_id', \"No ext\")\n sheet=(i['username']+\" \",i['first_name']+\" \", i['last_name']+\" \", i['presence_id'])\n f.write(str(sheet)+\"\\n\")\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20398541/" ]
74,291,655
<p>I want to serialize Map&lt;String, Any&gt; and one of the values type is Pair&lt;Int, Int&gt;. How to register the Pair as polymorphic subclass for that?</p> <pre><code>val module = SerializersModule { polymorphic(Any::class) { subclass(Int::class, PolymorphicPrimitiveSerializer(Int.serializer())) subclass(String::class, PolymorphicPrimitiveSerializer(String.serializer())) subclass(Pair::class, PolymorphicSerializer(Pair::class)) } } val format = Json { serializersModule = module } val mm = mapOf&lt;String, Any&gt;() .plus(&quot;int-int pair&quot;) to (5 to 10)) val jsoned = format.encodeToString(mm) val mmDecoded = format.decodeFromString(jsoned) require(mm==mmDecoded) </code></pre> <p>should encode to json like:</p> <pre><code>[{&quot;first&quot;: &quot;int-int pair&quot;, &quot;second&quot;:{&quot;type&quot;: &quot;Pair&quot;, &quot;value&quot;: {&quot;first&quot;: {&quot;type&quot;: Int, &quot;value&quot;:5}, &quot;second&quot;: {&quot;type&quot;:Int, &quot;value&quot;: 10}}}}] </code></pre> <p>But produce the following error:</p> <blockquote> <p>Exception in thread &quot;main&quot; java.lang.ExceptionInInitializerError Caused by: java.lang.IllegalArgumentException: <strong>Serializer for Pair can't be registered as a subclass for polymorphic serialization because its kind OPEN is not concrete. To work with multiple hierarchies, register it as a base class.</strong> at kotlinx.serialization.json.internal.PolymorphismValidator.checkKind(PolymorphismValidator.kt:41) at kotlinx.serialization.json.internal.PolymorphismValidator.polymorphic(PolymorphismValidator.kt:31) at kotlinx.serialization.modules.SerialModuleImpl.dumpTo(SerializersModule.kt:189) at kotlinx.serialization.json.JsonImpl.validateConfiguration(Json.kt:358) at kotlinx.serialization.json.JsonImpl.(Json.kt:352) at kotlinx.serialization.json.JsonKt.Json(Json.kt:189) at kotlinx.serialization.json.JsonKt.Json$default(Json.kt:185) at MainKt.(Main.kt:143)</p> </blockquote>
[ { "answer_id": 74291705, "author": "Steinn Hauser Magnusson", "author_id": 13819183, "author_profile": "https://Stackoverflow.com/users/13819183", "pm_score": 1, "selected": false, "text": "# ...\nwith open('Users.txt', 'x', encoding='utf-8') as f:\n for i in userData:\n default_data = {\"username\":\"\", \"first_name\":\"\", \"last_name\":\"\"}\n output = i.get('presence_id', default_data) # this will never be None. Equals default_data if \"presence_id\" is not found.\n sheet=(output['username']+\" \",output['first_name']+\" \", output['last_name']+\" \", output['presence_id'])\n f.write(str(sheet)+\"\\n\")\n \n" }, { "answer_id": 74292371, "author": "mrOlympia", "author_id": 18292391, "author_profile": "https://Stackoverflow.com/users/18292391", "pm_score": 0, "selected": false, "text": "for i in userData:\n i.setdefault('presence_id', \"No ext\")\n sheet=(i['username']+\" \",i['first_name']+\" \", i['last_name']+\" \", i['presence_id'])\n f.write(str(sheet)+\"\\n\")\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3234641/" ]
74,291,699
<p>In Golang I can define an interface like this:</p> <pre class="lang-golang prettyprint-override"><code>type DBRepo interface { PlayerByID(id uint64) (*domain.Player, error) TeamByID(id uint64) (*domain.Team, error) // many others </code></pre> <p>and I can implement them like this using different files:</p> <pre class="lang-golang prettyprint-override"><code>// file: real_db.go type RealDB struct { db *realDB } // file: player.go func (r RealDB) PlayerByID(id uint64) (*domain.Player, error) { return r.db... // get from DB } // file: team.go func (r RealDB) TeamByID(id uint64) (*domain.Team, error) { return r.db... // get from DB } // many others (files and methods) </code></pre> <p>I cannot undestand how to do the same in Rust:</p> <pre class="lang-rust prettyprint-override"><code>#[async_trait::async_trait] pub trait DBRepo: Send + Sync { async fn player_by_id(&amp;self, id: i64) -&gt; Result&lt;()&gt;; async fn team_by_id(&amp;self, id: i64) -&gt; Result&lt;()&gt;; } </code></pre> <p>but if I write the below code in different files (and different mods too):</p> <pre class="lang-rust prettyprint-override"><code>// file: player.rs #[async_trait::async_trait] impl DBRepo for Repo { async fn player_by_id(&amp;self, id: i64) -&gt; Result&lt;()&gt; { Ok(()) // get from DB } } // file: team.rs #[async_trait::async_trait] impl DBRepo for Repo { async fn team_by_id(&amp;self, id: i64) -&gt; Result&lt;()&gt; { Ok(()) // get from DB } } </code></pre> <p>I get from the compiler:</p> <pre><code>error[E0119]: conflicting implementations of trait `DBRepo` for type `Repo` --&gt; src\team.rs:22:1 | 22 | impl DBRepo for Repo { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `Repo` | ::: src\player.rs:22:1 | 22 | impl DBRepo for Repo { | ----------------------------------- first implementation here For more information about this error, try `rustc --explain E0119`. </code></pre> <p>How can I fix this?</p> <p><strong>I need to use all the methods on trait DBRepo</strong>, I cannot split it in many traits.</p>
[ { "answer_id": 74291806, "author": "Tyler Aldrich", "author_id": 1580425, "author_profile": "https://Stackoverflow.com/users/1580425", "pm_score": 0, "selected": false, "text": "Repo" }, { "answer_id": 74291914, "author": "cafce25", "author_id": 442760, "author_profile": "https://Stackoverflow.com/users/442760", "pm_score": 1, "selected": false, "text": "#[async_trait::async_trait]\npub trait DBRepoPlayer: Send + Sync {\n async fn player_by_id(&self, id: i64) -> Result<()>;\n}\n#[async_trait::async_trait]\npub trait DBRepoTeam: Send + Sync {\n async fn team_by_id(&self, id: i64) -> Result<()>;\n}\npub trait DBRepo: DBRepoPlayer + DBRepoTeam {}\nimpl<T: DBRepoPlayer + DBRepoTeam> DBRepo for T {}\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10088259/" ]
74,291,745
<p>I have two vectors, and I'm trying to find ALL coincidences of one on the other within a certain tolerance without using a for loop. By tolerance I mean for example if I have the number 3, with tolerance 2, I will want to keep values within 3±2, so (1,2,3,4,5).</p> <pre><code>A = [5 3 4 2]; B = [2 4 4 4 6 8]; </code></pre> <p>I want to obtain a cell array containing on each cell the numbers of all the coincidences with a tolerance of 1 (or more) units. (A = B +- 1) I have a solution with zero units (A = B), which would look something like this:</p> <pre><code>tol = 0; [tf, ia] = ismembertol(B,A,tol,'DataScale',1); % For tol = 0, this is equivalent to using ismember idx = 1:numel(B); ib = accumarray(nonzeros(ia), idx(tf), [], @(x){x}) % This gives the cell array </code></pre> <p>The output is:</p> <pre><code>ib = [] [] [2 3 4] [1] </code></pre> <p>Which is as desired. If I change the tolerance to 1, the code doesn't work as intended. It outputs instead:</p> <pre><code>tol = 1 [tf, ia] = ismembertol(B,A,tol,'DataScale',1); % For tolerance = 1, this is equivalent to using ismember idx = 1:numel(B); ib = accumarray(nonzeros(ia), idx(tf), [], @(x){x}) % This gives the cell array ib = [5] [2 3 4] [] [1] </code></pre> <p>When I would expect to obtain:</p> <pre><code>ib = [2 3 4 5] [1 2 3 4] [2 3 4] [1] </code></pre> <p>What am I doing wrong? Is there an alternative solution?</p>
[ { "answer_id": 74291806, "author": "Tyler Aldrich", "author_id": 1580425, "author_profile": "https://Stackoverflow.com/users/1580425", "pm_score": 0, "selected": false, "text": "Repo" }, { "answer_id": 74291914, "author": "cafce25", "author_id": 442760, "author_profile": "https://Stackoverflow.com/users/442760", "pm_score": 1, "selected": false, "text": "#[async_trait::async_trait]\npub trait DBRepoPlayer: Send + Sync {\n async fn player_by_id(&self, id: i64) -> Result<()>;\n}\n#[async_trait::async_trait]\npub trait DBRepoTeam: Send + Sync {\n async fn team_by_id(&self, id: i64) -> Result<()>;\n}\npub trait DBRepo: DBRepoPlayer + DBRepoTeam {}\nimpl<T: DBRepoPlayer + DBRepoTeam> DBRepo for T {}\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14978522/" ]
74,291,774
<p>I'm learning about data structures and algorithms and I'm starting to learn about constructing linked lists from scratch in python. Right now I understand how they work and the components that go into making them (Nodes, data/address, Head/Tail, etc), but I'm having a really hard time wrapping my brain around how they function when constructing them in python. Like I have working code to make them in python here but I don't get the logic behind how they operate with classes. For example, I'm confused in my addLast-function on how the node variable(<em><strong>node = Node(value)</strong></em>) connects to the Node class.</p> <pre><code>class Node: def __init__(self, value, next=None): self.value = value self.next = next class LinkedList: def __init__(self): self.head = None self.tail = None def addLast(self, value): node = Node(value) if self.head == None: self.head = node self.tail = node else: self.tail.next = node self.tail = node </code></pre>
[ { "answer_id": 74291806, "author": "Tyler Aldrich", "author_id": 1580425, "author_profile": "https://Stackoverflow.com/users/1580425", "pm_score": 0, "selected": false, "text": "Repo" }, { "answer_id": 74291914, "author": "cafce25", "author_id": 442760, "author_profile": "https://Stackoverflow.com/users/442760", "pm_score": 1, "selected": false, "text": "#[async_trait::async_trait]\npub trait DBRepoPlayer: Send + Sync {\n async fn player_by_id(&self, id: i64) -> Result<()>;\n}\n#[async_trait::async_trait]\npub trait DBRepoTeam: Send + Sync {\n async fn team_by_id(&self, id: i64) -> Result<()>;\n}\npub trait DBRepo: DBRepoPlayer + DBRepoTeam {}\nimpl<T: DBRepoPlayer + DBRepoTeam> DBRepo for T {}\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19801999/" ]
74,291,778
<p>I am trying to convert a very long JSON file to CSV. I'm currently trying to use the code below to accomplish this.</p> <pre><code>import json import csv with open('G:\user\jsondata.json') as json_file: jsondata = json.load(json_file) data_file = open('G:\user\jsonoutput.csv', 'w', newline='') csv_writer = csv.writer(data_file) count = 0 for data in jsondata: if count == 0: header = data.keys() csv_writer.writerow(header) count += 1 csv_writer.writerow(data.values()) data_file.close() </code></pre> <p>This code accomplishes writing all the data to a CSV, However only takes the keys for from the first JSON line to use as the headers in the CSV. This would be fine, but further in the JSON there are more keys to used. This causes the values to be disorganized. I was wondering if anyone could help me find a way to get all the possible headers and possibly insert NA when a line doesn't contain that key or values for that key.</p> <p>The JSON file is similar to this:</p> <pre><code> </code></pre> <pre><code>[ {&quot;time&quot;: &quot;1984-11-04:4:00&quot;, &quot;dateOfevent&quot;: &quot;1984-11-04&quot;, &quot;action&quot;: &quot;TAKEN&quot;, &quot;Country&quot;: &quot;Germany&quot;, &quot;Purchased&quot;: &quot;YES&quot;, ...}, {&quot;time&quot;: &quot;1984-10-04:4:00&quot;, &quot;dateOfevent&quot;: &quot;1984-10-04&quot;, &quot;action&quot;: &quot;NOTTAKEN&quot;, &quot;Country&quot;: &quot;Germany&quot;, &quot;Purchased&quot;: &quot;NO&quot;, ...}, {&quot;type&quot;: &quot;A4&quot;, &quot;time&quot;: &quot;1984-11-04:4:00&quot;, &quot;dateOfevent&quot;: &quot;1984-11-04&quot;, &quot;Country&quot;: &quot;Germany&quot;, &quot;typeOfevent&quot;: &quot;H7&quot;, ...}, {...}, {...}, ] </code></pre> <pre><code> </code></pre> <p>I've searched for possible solutions all over, but was unable to find anyone having a similar issue.</p>
[ { "answer_id": 74291806, "author": "Tyler Aldrich", "author_id": 1580425, "author_profile": "https://Stackoverflow.com/users/1580425", "pm_score": 0, "selected": false, "text": "Repo" }, { "answer_id": 74291914, "author": "cafce25", "author_id": 442760, "author_profile": "https://Stackoverflow.com/users/442760", "pm_score": 1, "selected": false, "text": "#[async_trait::async_trait]\npub trait DBRepoPlayer: Send + Sync {\n async fn player_by_id(&self, id: i64) -> Result<()>;\n}\n#[async_trait::async_trait]\npub trait DBRepoTeam: Send + Sync {\n async fn team_by_id(&self, id: i64) -> Result<()>;\n}\npub trait DBRepo: DBRepoPlayer + DBRepoTeam {}\nimpl<T: DBRepoPlayer + DBRepoTeam> DBRepo for T {}\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20399002/" ]
74,291,813
<p>Trying to use power automate to create tables and add styling to them in the body of an email. The last part of my project involves getting the first column of the table (name column) to have an orange background but I cannot seem to get the CSS working for this.</p> <p>Style sheet:</p> <pre><code>&lt;style&gt; table{ border: 2px solid #C1C1C1; background-color: #FFFFFF; width: 400px; text-align: center; border-collapse: collapse; } table td, th { border: 1px solid #555555; padding: 5px 10px; } table tbody td { font-size: 12px; font-weight: bold; color: #000000; } table thead { background: #737373; } table thead th { font-size: 15px; font-weight: bold; color: #FFFFFF; text-align: center; } table tr td:nth-child(1) { background-color: orange; } &lt;/style&gt; </code></pre> <p>HTML output from PowerBI's HTML table action:</p> <pre><code>&lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;&lt;/th&gt; &lt;th&gt;Sunday^10/30/2022&lt;/th&gt; &lt;th&gt;Monday^10/31/2022&lt;/th&gt; &lt;th&gt;Tuesday^11/1/2022&lt;/th&gt; &lt;th&gt;Wednesday^11/2/2022&lt;/th&gt; &lt;th&gt;Thursday^11/3/2022&lt;/th&gt; th&gt;Friday^11/4/2022&lt;/th&gt; &lt;th&gt;Saturday^11/5/2022&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;John Doe&lt;/td&gt; &lt;-- this column needs to be orange &lt;td&gt;Rest Day&lt;/td&gt; &lt;td&gt;Vacation&lt;/td&gt; &lt;td&gt;Vacation&lt;/td&gt; &lt;td&gt;Office&lt;/td&gt; &lt;td&gt;Remote&lt;/td&gt; &lt;td&gt;Office&lt;/td&gt; &lt;td&gt;Rest Day&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre>
[ { "answer_id": 74291806, "author": "Tyler Aldrich", "author_id": 1580425, "author_profile": "https://Stackoverflow.com/users/1580425", "pm_score": 0, "selected": false, "text": "Repo" }, { "answer_id": 74291914, "author": "cafce25", "author_id": 442760, "author_profile": "https://Stackoverflow.com/users/442760", "pm_score": 1, "selected": false, "text": "#[async_trait::async_trait]\npub trait DBRepoPlayer: Send + Sync {\n async fn player_by_id(&self, id: i64) -> Result<()>;\n}\n#[async_trait::async_trait]\npub trait DBRepoTeam: Send + Sync {\n async fn team_by_id(&self, id: i64) -> Result<()>;\n}\npub trait DBRepo: DBRepoPlayer + DBRepoTeam {}\nimpl<T: DBRepoPlayer + DBRepoTeam> DBRepo for T {}\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13124481/" ]
74,291,828
<pre><code>public static void CreateSqlTable() { try { DateTime today = DateTime.Today; String query = &quot;CREATE TABLE [dbo].[01/19/2001_Test_Log](&quot; + &quot;[Entry_ID] [int] IDENTITY(1,1) NOT NULL,&quot; + &quot;[Execution_Time] [datetime] NULL,&quot; + &quot;[Message_Type] [varchar](4) NULL,&quot; + &quot;[Environment] [varchar](10) NULL,&quot; + &quot;[Method_ID] [int] NULL,&quot; + &quot;[Method_Description] [varchar](max) NULL,&quot; + &quot;[Execution_Duration] [float] NULL,&quot; + &quot;CONSTRAINT [PK_01/19/2001_Test_Log] PRIMARY KEY CLUSTERED&quot; + &quot;(&quot; + &quot;[Entry_ID] ASC&quot; + &quot;)&quot; + &quot; ON [PRIMARY]&quot;; using (SqlConnection connection = new SqlConnection(credentials)) //credentials from connection string { using (SqlCommand command = new SqlCommand(query, connection)) { connection.Open(); command.ExecuteNonQuery(); connection.Close(); } } } catch (Exception ex) { int i = 0; } } </code></pre> <p>Getting the error &quot;Incorrect syntax near keyword 'ON'.&quot; Struggling to figure out where the issue is as this query runs fine in ssms. I have another method that inserts into a table using the connection string and this one uses the same so I do not think that is the issue here. Thanks!</p> <p>Edit: Removed some and am now getting Invalid syntax near PRIMARY.</p>
[ { "answer_id": 74291806, "author": "Tyler Aldrich", "author_id": 1580425, "author_profile": "https://Stackoverflow.com/users/1580425", "pm_score": 0, "selected": false, "text": "Repo" }, { "answer_id": 74291914, "author": "cafce25", "author_id": 442760, "author_profile": "https://Stackoverflow.com/users/442760", "pm_score": 1, "selected": false, "text": "#[async_trait::async_trait]\npub trait DBRepoPlayer: Send + Sync {\n async fn player_by_id(&self, id: i64) -> Result<()>;\n}\n#[async_trait::async_trait]\npub trait DBRepoTeam: Send + Sync {\n async fn team_by_id(&self, id: i64) -> Result<()>;\n}\npub trait DBRepo: DBRepoPlayer + DBRepoTeam {}\nimpl<T: DBRepoPlayer + DBRepoTeam> DBRepo for T {}\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14502070/" ]
74,291,832
<p>How can I write a query that will get the first active game_id that does not occur twice in the table below?</p> <p><a href="https://i.stack.imgur.com/5I5Lt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5I5Lt.png" alt="" /></a></p>
[ { "answer_id": 74292082, "author": "Semih SAHIN", "author_id": 10542740, "author_profile": "https://Stackoverflow.com/users/10542740", "pm_score": -1, "selected": false, "text": "$data = DB::table('your_table')\n ->groupBy('game_id')\n ->select('id')\n ->toArray();\n$result = DB::table('your_table')\n ->whereNotIn($data)\n ->where('is_active', 1)\n ->first();\n" }, { "answer_id": 74292226, "author": "Abhay", "author_id": 15209801, "author_profile": "https://Stackoverflow.com/users/15209801", "pm_score": 0, "selected": false, "text": "$user_info = DB::table('usermetas')\n ->select('browser', DB::raw('count(*) as total'))\n ->groupBy('browser')\n ->get();\n" }, { "answer_id": 74292347, "author": "xenooooo", "author_id": 20283630, "author_profile": "https://Stackoverflow.com/users/20283630", "pm_score": 1, "selected": false, "text": "DB::table('tablename')\n ->select(DB::raw('COUNT(game_id) as totalgames, game_id'))\n ->where('is_active', 1)\n ->groupBy('game_id')\n ->havingRaw('COUNT(game_id) = 1')\n ->first();\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15209801/" ]
74,291,838
<p>I have a apps script which had three <code>OnEdit()</code> triggers, as below</p> <pre><code>function onEdit(e) { onEdit1(e); // The function for hide/unhide sheets/tabs onEdit2(e); // The function for hide/unhide row in ESS sheet onEdit3(e); // The function for hide/unhide rows in a } function onEdit1(e) { var cp = SpreadsheetApp.getActiveSpreadsheet(); var a = cp.getSheetByName(&quot;A&quot;); var b = cp.getSheetByName(&quot;B&quot;); var check_value = cp.getSheetByName(&quot;check sheet&quot;); var cella = check_value.getRange('C6'); if (cella.getValue() == 'Yes') { a.showSheet(); } else { a.hideSheet(); } var ç = check_value.getRange('C7'); if (cellb.getValue() == 'Yes') { b.showSheet(); } else { b.hideSheet(); } } function onEdit2(e) { var ss = SpreadsheetApp.getActiveSpreadsheet(); var ESS = ss.getSheetByName(&quot;BBB&quot;); var cellx = ESS.getRange(&quot;D13&quot;); if ((cellx.getValue() == &quot;Accept&quot;) || ((cellx.getValue() == &quot;&quot;))){ ESS.hideRows(15); } else { ESS.showRows(15); } } function onEdit3(e) { var sd = SpreadsheetApp.getActiveSpreadsheet(); var info = sd.getSheetByName(&quot;Z&quot;); var a = sd.getSheetByName(&quot;A&quot;); var check = info.getRange(&quot;J9&quot;); if (check.getValues()== &quot;Direct&quot;){ a.hideRows(37,8); } else{ if((check.getValues()== &quot;Indirect&quot;) || (check.getValues()== &quot;&quot;)){ a.showRows(37,8); } </code></pre> <p>There are no errors and the execution completes without any errors but upon changing/editing the values the hiding/unhiding for the sheet and rows does not happen.</p> <p>I did try to look at other posts on the timing out of onEdit() function, but am unable to understand what changes to make in my code.</p> <p>Also when I look at the <code>Executions</code> I get <code>Function- onEdit(), Type- Simple Trigger, Status- Timed Out</code></p> <p>Please help me with this</p>
[ { "answer_id": 74292082, "author": "Semih SAHIN", "author_id": 10542740, "author_profile": "https://Stackoverflow.com/users/10542740", "pm_score": -1, "selected": false, "text": "$data = DB::table('your_table')\n ->groupBy('game_id')\n ->select('id')\n ->toArray();\n$result = DB::table('your_table')\n ->whereNotIn($data)\n ->where('is_active', 1)\n ->first();\n" }, { "answer_id": 74292226, "author": "Abhay", "author_id": 15209801, "author_profile": "https://Stackoverflow.com/users/15209801", "pm_score": 0, "selected": false, "text": "$user_info = DB::table('usermetas')\n ->select('browser', DB::raw('count(*) as total'))\n ->groupBy('browser')\n ->get();\n" }, { "answer_id": 74292347, "author": "xenooooo", "author_id": 20283630, "author_profile": "https://Stackoverflow.com/users/20283630", "pm_score": 1, "selected": false, "text": "DB::table('tablename')\n ->select(DB::raw('COUNT(game_id) as totalgames, game_id'))\n ->where('is_active', 1)\n ->groupBy('game_id')\n ->havingRaw('COUNT(game_id) = 1')\n ->first();\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20357303/" ]
74,291,881
<p>I wanna remove title bar. I tried</p> <blockquote> <p>#if WINDOWS events.AddWindows(wndLifeCycleBuilder =&gt; { wndLifeCycleBuilder.OnWindowCreated(window =&gt; { window.ExtendsContentIntoTitleBar = false; }); }); #endif</p> </blockquote> <p>but this doesn't work. How to remove system title bar on the top of application? I mean about this bar. <a href="https://i.stack.imgur.com/nfZkv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nfZkv.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74292082, "author": "Semih SAHIN", "author_id": 10542740, "author_profile": "https://Stackoverflow.com/users/10542740", "pm_score": -1, "selected": false, "text": "$data = DB::table('your_table')\n ->groupBy('game_id')\n ->select('id')\n ->toArray();\n$result = DB::table('your_table')\n ->whereNotIn($data)\n ->where('is_active', 1)\n ->first();\n" }, { "answer_id": 74292226, "author": "Abhay", "author_id": 15209801, "author_profile": "https://Stackoverflow.com/users/15209801", "pm_score": 0, "selected": false, "text": "$user_info = DB::table('usermetas')\n ->select('browser', DB::raw('count(*) as total'))\n ->groupBy('browser')\n ->get();\n" }, { "answer_id": 74292347, "author": "xenooooo", "author_id": 20283630, "author_profile": "https://Stackoverflow.com/users/20283630", "pm_score": 1, "selected": false, "text": "DB::table('tablename')\n ->select(DB::raw('COUNT(game_id) as totalgames, game_id'))\n ->where('is_active', 1)\n ->groupBy('game_id')\n ->havingRaw('COUNT(game_id) = 1')\n ->first();\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15376698/" ]
74,291,896
<p>My sidebar uses react-router-dom to switch between page files using routes, however when I switch routes, my page reloads. Is there a way I can switch routes without reloading the page?</p> <p>SideBar</p> <pre><code>import React from 'react' import {SideNav_Data} from &quot;./SideNav_Data&quot; import Sunrise from './Sunrise.png' function SideNav() { return ( &lt;div className = &quot;SideNav&quot;&gt; &lt;img src={Sunrise} className='SideNavImg' alt=''/&gt; &lt;ul className=&quot;SideNavList&quot;&gt; {SideNav_Data.map((val, key) =&gt; { return ( &lt;li key={key} className = &quot;row&quot; id={window.location.pathname === val.link ? &quot;active&quot; : &quot;&quot;} onClick = {() =&gt; { window.location.pathname = val.link; }}&gt; &lt;div id='icon'&gt;{val.icon}&lt;/div&gt;{&quot; &quot;}&lt;div id='title'&gt;{val.title}&lt;/div&gt; &lt;/li&gt; ) })} &lt;/ul&gt; &lt;/div&gt; ) } export default SideNav </code></pre> <p>Sidebar Data</p> <pre><code>import React from 'react' import CottageIcon from '@mui/icons-material/Cottage'; import DirectionsCarFilledIcon from '@mui/icons-material/DirectionsCarFilled'; import PersonIcon from '@mui/icons-material/Person'; import AccountBalanceIcon from '@mui/icons-material/AccountBalance'; import AccountCircleIcon from '@mui/icons-material/AccountCircle'; import ContactSupportIcon from '@mui/icons-material/ContactSupport'; export const SideNav_Data = [ { title: &quot;Home&quot;, icon: &lt;CottageIcon /&gt;, link: &quot;/&quot; }, { title: &quot;Cars&quot;, icon: &lt;DirectionsCarFilledIcon /&gt;, link: &quot;/Cars&quot; }, { title: &quot;Representatives&quot;, icon: &lt;PersonIcon /&gt;, link: &quot;/Representatives&quot; }, { title: &quot;Loan Estimator&quot;, icon: &lt;AccountBalanceIcon /&gt;, link: &quot;/Loan-Estimator&quot; }, { title: &quot;Account&quot;, icon: &lt;AccountCircleIcon /&gt;, link: &quot;/Account&quot; }, { title: &quot;Support&quot;, icon: &lt;ContactSupportIcon /&gt;, link: &quot;/Support&quot; }, ] </code></pre> <p>Home page</p> <pre><code>import React from 'react' import SideNav from '../Components/SideNav' function Home() { return (&lt;div&gt; &lt;SideNav /&gt; &lt;/div&gt; ) } export default Home </code></pre> <p>App.js</p> <pre><code>import './App.css'; import { BrowserRouter as Router, Routes, Route} from &quot;react-router-dom&quot; import Home from './Pages/Home'; import Cars from './Pages/Cars'; import Reps from './Pages/Reps'; import LoanEst from './Pages/LoanEst'; import Account from './Pages/Account'; import Support from './Pages/Support'; function App() { return ( &lt;Router&gt; &lt;Routes&gt; &lt;Route path='/' element={&lt;Home /&gt;}/&gt; &lt;Route path=&quot;/Cars&quot; element={&lt;Cars /&gt;}/&gt; &lt;Route path=&quot;/Representatives&quot; element={&lt;Reps /&gt;}/&gt; &lt;Route path=&quot;/Loan-Estimator&quot; element={&lt;LoanEst /&gt;}/&gt; &lt;Route path=&quot;/Account&quot; element={&lt;Account /&gt;}/&gt; &lt;Route path=&quot;/Support&quot; element={&lt;Support /&gt;}/&gt; &lt;/Routes&gt; &lt;/Router&gt; ) } export default App; </code></pre> <p>I've tried switching the &quot;link: &quot; part of the sidebar data to &lt;Link to={Home /}/&gt; but that resulted in the sidebar completely disappearing.</p>
[ { "answer_id": 74291972, "author": "Taki", "author_id": 7328218, "author_profile": "https://Stackoverflow.com/users/7328218", "pm_score": 2, "selected": false, "text": "Link" }, { "answer_id": 74292369, "author": "Drew Reese", "author_id": 8690857, "author_profile": "https://Stackoverflow.com/users/8690857", "pm_score": 1, "selected": false, "text": "window.location.pathname" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20399219/" ]
74,291,899
<p>I have the following graph</p> <pre><code>(a1:A {name:'a1', s:1}) -&gt; -&gt; (a3:A {name:'a3',s:11}) (a2:A {name:'a2', s:10}) -&gt; (b1:B) -&gt; (c1:C) -&gt; (b2:B) -&gt; (a4:A {name:'a4',s:123}) </code></pre> <p>On the left, there are 2 type A nodes that connect to the same type B node on the left. On the right, there are 2 type A nodes that connect to another type B node on the right. Each type A node has an attribute called <code>s</code> which indicates a score.</p> <p>If I do a simple query like this</p> <pre><code>match p=((a1:A)--(b1:B)--(:C)--(b2:B)--(a2:A)) where a1.name in ['a1', 'a2'] return p </code></pre> <p>I will get 4 paths without any ordering. However, i would like the path to be order based on the aggregate score of the type A nodes on both end of the path, i.e,</p> <pre><code>(:A {name:'a2', s:10}) -&gt; (b1:B) -&gt; (c1:C) -&gt; (b2:B) -&gt; (:A {name:'a4',s:123}) (:A {name:'a1', s:1}) -&gt; (b1:B) -&gt; (c1:C) -&gt; (b2:B) -&gt; (:A {name:'a4',s:123}) (:A {name:'a2', s:10}) -&gt; (b1:B) -&gt; (c1:C) -&gt; (b2:B) -&gt; (:A {name:'a3',s:11}) (:A {name:'a1', s:1}) -&gt; (b1:B) -&gt; (c1:C) -&gt; (b2:B) -&gt; (:A {name:'a3',s:11}) </code></pre> <p>Can I achieve this by cypher?</p>
[ { "answer_id": 74292346, "author": "nimrod serok", "author_id": 18482310, "author_profile": "https://Stackoverflow.com/users/18482310", "pm_score": 2, "selected": true, "text": "match p=((a1:A)--(b1:B)--(:C)--(b2:B)--(a2:A))\nwhere a1.name in ['a1', 'a2']\nWITH p, a1.s + a2.s AS score\nreturn p, score\nORDER BY score DESC\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/734748/" ]
74,291,907
<p>I want to add a new path with the name of the last path from import with .cjs extension to every import which contains 'primereact'.</p> <p>For example:</p> <pre><code>import { nanoid } from &quot;nanoid&quot;; import { Button } from &quot;primereact/button&quot;; </code></pre> <p>Should be:</p> <pre><code>import { nanoid } from &quot;nanoid&quot;; import { Button } from &quot;primereact/button/button.cjs&quot;; </code></pre> <p>I want to connect regex with js replace function</p> <pre><code>string.replace(//g, ''); </code></pre> <p>I have a regex to find the line which contains <code>import</code> and <code>primereact</code>, but can't add necessary file with extension.</p> <pre><code>.*(import)+.*(primereact)+.* </code></pre>
[ { "answer_id": 74292346, "author": "nimrod serok", "author_id": 18482310, "author_profile": "https://Stackoverflow.com/users/18482310", "pm_score": 2, "selected": true, "text": "match p=((a1:A)--(b1:B)--(:C)--(b2:B)--(a2:A))\nwhere a1.name in ['a1', 'a2']\nWITH p, a1.s + a2.s AS score\nreturn p, score\nORDER BY score DESC\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14775829/" ]
74,291,912
<p>i've been trying to develop a linear regression model using my cleaned datasets. Here is my datasets: <a href="https://docs.google.com/spreadsheets/d/1G7URct9yPAxEETLrb_F1McN-bgKp_r8cykmCOmojhT0/edit?usp=sharing" rel="nofollow noreferrer">https://docs.google.com/spreadsheets/d/1G7URct9yPAxEETLrb_F1McN-bgKp_r8cykmCOmojhT0/edit?usp=sharing</a></p> <p>i've processed the data with label encoder and just split it with train_test_split</p> <pre><code>cols = ['nama_pasar','komoditas'] for col in cols: df_test[col] = LE.fit_transform(df_test[col]) print(LE.classes_) </code></pre> <pre><code>X = df_test[['tanggal','nama_pasar','komoditas']] y = df_test[['harga']] </code></pre> <pre><code>from sklearn.model_selection import train_test_split X_train, y_train, X_test, y_test = train_test_split(X, y, test_size = 0.5) </code></pre> <p>When i try to fit the data, no problems showed up.</p> <pre><code>LR.fit(X_train, y_train) </code></pre> <p>But when im trying to use prediction from my linear regression model but it keeps showing this errors</p> <pre><code>LR.predict([1, 10, 4]) </code></pre> <pre><code>ValueError: Expected 2D array, got 1D array instead: array=[ 1 10 4]. Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample. </code></pre> <p>I've tried to change the number of test size into 0.2 but it shows different error than the first one.</p> <pre><code>ValueError: Found input variables with inconsistent numbers of samples: [37936, 9484] </code></pre> <p>How do i solve this?</p> <p>I'm still learning the very basics of data science, an explanation would be much appreciated</p> <p>Thankyou</p>
[ { "answer_id": 74292346, "author": "nimrod serok", "author_id": 18482310, "author_profile": "https://Stackoverflow.com/users/18482310", "pm_score": 2, "selected": true, "text": "match p=((a1:A)--(b1:B)--(:C)--(b2:B)--(a2:A))\nwhere a1.name in ['a1', 'a2']\nWITH p, a1.s + a2.s AS score\nreturn p, score\nORDER BY score DESC\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20396601/" ]
74,291,922
<p>It is known that when building an xgboost model through the <code>boost_tree()</code> function, it is possible to introduce a gamma regression through the objective argument of the <code>set_engine()</code> function, as seen below:</p> <pre><code>xgbst = boost_tree( trees = tune(), tree_depth = tune(), min_n = tune(), learn_rate = tune(), loss_reduction = tune(), sample_size = tune()) %&gt;% set_engine(&quot;xgboost&quot;, objective = &quot;reg:gamma&quot;) %&gt;% set_mode(&quot;regression&quot;) </code></pre> <p>However, I am interested in using a random forest model. Therefore, considering that it is possible to introduce arguments in the objective function, I tried to repeat the same computational procedure above, but for random forest, like below:</p> <pre><code>library(randomForest) library(parsnip) rfmod = rand_forest( trees = tune(), mtry = tune(), min_n = tune()) %&gt;% set_engine(&quot;randomForest&quot;, objective = &quot;reg:gamma&quot;) %&gt;% set_mode(&quot;regression&quot;) </code></pre> <p>As a result, I am facing an error associated with the fact that it is not possible to introduce Gamma regression in the above model and that there is a bad specification in the computational routine. In the literature I have already found works that made use of the Gamma distribution in random forest models.</p> <p>In this case, how could I solve it?</p>
[ { "answer_id": 74292715, "author": "sconfluentus", "author_id": 6258859, "author_profile": "https://Stackoverflow.com/users/6258859", "pm_score": 2, "selected": false, "text": "rpart" }, { "answer_id": 74292938, "author": "Ric Villalba", "author_id": 6912817, "author_profile": "https://Stackoverflow.com/users/6912817", "pm_score": 2, "selected": true, "text": "library(parsnip)\n\nxgbst = boost_tree(\n trees = 100, \n learn_rate = 1,\n sample_size = 0.8) %>%\nset_engine(\"xgboost\", objective = \"reg:gamma\", \n num_boost_round=1, colsample_bytree=0.8, counts=F) %>%\nset_mode(\"regression\")\n\nfit(xgbst, mpg ~ ., data = mtcars, )\n\n\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291922", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10478454/" ]
74,291,936
<p>I'm writing a script that should update itself, but I'm stuck.<br /> Basically I have to replace a variable containing an RGB color array (which value changes during this script) and overwrite this variable in the .jsx file.<br /> For clarity I give an example:</p> <pre><code>var RGBColor = [0, 0, 0]; //Black RGB color var RGBColor2 = RGBColor; // The script runs and change RGBColor2 value to [0.2, 0.55, 0.2] var UpdateFile = function () { var JSX = File ($.fileName); JSX.open (&quot;e&quot;); JSX.write ((JSX.read ()).replace (RGBColor, RGBColor2)); JSX.close (); } UpdateFile (); </code></pre> <p>This is what I should theoretically do, but I can't replace the variable in any way (I tried everything, even with the method &quot;open (&quot;r&quot;)&quot;, &quot;read&quot;, &quot;close&quot;, &quot;open (&quot;w&quot;)&quot;, &quot;write&quot;).<br /> Does anyone know how to make this script work or know a better way to write it?.</p> <hr /> <p><strong>UPDATE</strong></p> <p>The final script will be a scriptui panel with six sliders, three for the first color (R, G, B), and three for the second color.<br /> When the &quot;Apply&quot; button is pressed, the script will have to replace the rgb variables inside the script.<br /> After messing with Ghoul Fool's code, I decided to replace the variables and not the arrays because it seemed more difficult. However I cannot overwrite the variables.<br /> Here is the code:</p> <pre><code> var Red1 = 0; var Green1 = 0; var Blue1 = 0; var Red2 = 1; var Green2 = 1; var Blue2 = 1; var FirstColor = [Red1, Green1, Blue1]; var SecondColor = [Red2, Green2, Blue2]; var MainPanel = new Window (&quot;dialog&quot;, &quot;Panel1&quot;); var Text1 = MainPanel.add (&quot;statictext&quot;); Text1.text = &quot;First color&quot;; var RSlider1 = MainPanel.add (&quot;slider&quot;); RSlider1.minvalue = 0; RSlider1.maxvalue = 255; RSlider1.value = Math.round (FirstColor[0] * 255); var RNumber1 = MainPanel.add (&quot;statictext&quot;, undefined, RSlider1.value); RNumber1.preferredSize.width = 25; RNumber1.graphics.foregroundColor = RNumber1.graphics.newPen (RNumber1.graphics.PenType.SOLID_COLOR, [1, 0, 0], 1); RNumber1.graphics.disabledForegroundColor = RNumber1.graphics.foregroundColor; RNumber1.graphics.font = ScriptUI.newFont (RNumber1.graphics.font.name, &quot;Bold&quot;, RNumber1.graphics.font.size); var GSlider1 = MainPanel.add (&quot;slider&quot;); GSlider1.minvalue = 0; GSlider1.maxvalue = 255; GSlider1.value = Math.round (FirstColor[1] * 255); var GNumber1 = MainPanel.add (&quot;statictext&quot;, undefined, GSlider1.value); GNumber1.preferredSize.width = 25; GNumber1.graphics.foregroundColor = GNumber1.graphics.newPen (GNumber1.graphics.PenType.SOLID_COLOR, [0, 1, 0], 1); GNumber1.graphics.disabledForegroundColor = GNumber1.graphics.foregroundColor; GNumber1.graphics.font = ScriptUI.newFont (GNumber1.graphics.font.name, &quot;Bold&quot;, GNumber1.graphics.font.size); var BSlider1 = MainPanel.add (&quot;slider&quot;); BSlider1.minvalue = 0; BSlider1.maxvalue = 255; BSlider1.value = Math.round (FirstColor[2] * 255); var BNumber1 = MainPanel.add (&quot;statictext&quot;, undefined, BSlider1.value); BNumber1.preferredSize.width = 25; BNumber1.graphics.foregroundColor = BNumber1.graphics.newPen (BNumber1.graphics.PenType.SOLID_COLOR, [0, 0, 1], 1); BNumber1.graphics.disabledForegroundColor = BNumber1.graphics.foregroundColor; BNumber1.graphics.font = ScriptUI.newFont (BNumber1.graphics.font.name, &quot;Bold&quot;, BNumber1.graphics.font.size); RSlider1.onChanging = GSlider1.onChanging = BSlider1.onChanging = function () { RNumber1.text = Math.round (RSlider1.value); GNumber1.text = Math.round (GSlider1.value); BNumber1.text = Math.round (BSlider1.value); Red1 = Math.floor ((Math.round (RSlider1.value) / 255) * 100) / 100; Green1 = Math.floor ((Math.round (GSlider1.value) / 255) * 100) / 100; Blue1 = Math.floor ((Math.round (BSlider1.value) / 255) * 100) / 100; } var Text2 = MainPanel.add (&quot;statictext&quot;); Text2.text = &quot;Second color&quot;; var RSlider2 = MainPanel.add (&quot;slider&quot;); RSlider2.minvalue = 0; RSlider2.maxvalue = 255; RSlider2.value = Math.round (SecondColor[0] * 255); var RNumber2 = MainPanel.add (&quot;statictext&quot;, undefined, RSlider2.value); RNumber2.preferredSize.width = 25; RNumber2.graphics.foregroundColor = RNumber2.graphics.newPen (RNumber2.graphics.PenType.SOLID_COLOR, [1, 0, 0], 1); RNumber2.graphics.disabledForegroundColor = RNumber2.graphics.foregroundColor; RNumber2.graphics.font = ScriptUI.newFont (RNumber2.graphics.font.name, &quot;Bold&quot;, RNumber2.graphics.font.size); var GSlider2 = MainPanel.add (&quot;slider&quot;); GSlider2.minvalue = 0; GSlider2.maxvalue = 255; GSlider2.value = Math.round (SecondColor[1] * 255); var GNumber2 = MainPanel.add (&quot;statictext&quot;, undefined, GSlider2.value); GNumber2.preferredSize.width = 25; GNumber2.graphics.foregroundColor = GNumber2.graphics.newPen (GNumber2.graphics.PenType.SOLID_COLOR, [0, 1, 0], 1); GNumber2.graphics.disabledForegroundColor = GNumber2.graphics.foregroundColor; GNumber2.graphics.font = ScriptUI.newFont (GNumber2.graphics.font.name, &quot;Bold&quot;, GNumber2.graphics.font.size); var BSlider2 = MainPanel.add (&quot;slider&quot;); BSlider2.minvalue = 0; BSlider2.maxvalue = 255; BSlider2.value = Math.round (SecondColor[2] * 255); var BNumber2 = MainPanel.add (&quot;statictext&quot;, undefined, BSlider2.value); BNumber2.preferredSize.width = 25; BNumber2.graphics.foregroundColor = BNumber2.graphics.newPen (BNumber2.graphics.PenType.SOLID_COLOR, [0, 0, 1], 1); BNumber2.graphics.disabledForegroundColor = BNumber2.graphics.foregroundColor; BNumber2.graphics.font = ScriptUI.newFont (BNumber2.graphics.font.name, &quot;Bold&quot;, BNumber2.graphics.font.size); RSlider2.onChanging = GSlider2.onChanging = BSlider2.onChanging = function () { RNumber2.text = Math.round (RSlider2.value); GNumber2.text = Math.round (GSlider2.value); BNumber2.text = Math.round (BSlider2.value); Red2 = Math.floor ((Math.round (RSlider2.value) / 255) * 100) / 100; Green2 = Math.floor ((Math.round (GSlider2.value) / 255) * 100) / 100; Blue2 = Math.floor ((Math.round (BSlider2.value) / 255) * 100) / 100; } var Apply = MainPanel.add (&quot;button&quot;, undefined, &quot;Apply changes&quot;); Apply.onClick = function () { var JSX = File ($.fileName); JSX.open (&quot;r&quot;); var JSXXX = JSX.read (); JSX.close (); JSX.open (&quot;w&quot;); // This part is not clear to me. What should I replace the colors with? JSXXX = JSXXX.replace (Red1, FirstColor [0]); JSXXX = JSXXX.replace (Green1, FirstColor [1]); JSXXX = JSXXX.replace (Blue1, FirstColor [2]); JSXXX = JSXXX.replace (Red2, SecondColor [0]); JSXXX = JSXXX.replace (Green2, SecondColor [1]); JSXXX = JSXXX.replace (Blue2, SecondColor [2]); JSX.write(JSXXX); JSX.close (); MainPanel.close (); } alert (&quot;Color 1 : &quot; + Red1 + &quot; - &quot; + Green1 + &quot; - &quot; + Blue1); alert (&quot;Color 2 : &quot; + Red2 + &quot; - &quot; + Green2 + &quot; - &quot; + Blue2); MainPanel.show (); </code></pre> <p>The dialog will be included in the final script and will be used to change the color of the dialog itself.</p>
[ { "answer_id": 74362084, "author": "Ghoul Fool", "author_id": 1654143, "author_profile": "https://Stackoverflow.com/users/1654143", "pm_score": 1, "selected": false, "text": "var RGBColor2 = RGBColor;\n" }, { "answer_id": 74678005, "author": "IDJSGUS", "author_id": 18714172, "author_profile": "https://Stackoverflow.com/users/18714172", "pm_score": 1, "selected": true, "text": " var XMLFile = File (Folder.desktop + \"/config.xml\");\n if (!XMLFile.exists) {\n Create ();\n }\n XMLFile.open (\"r\");\n var XMLObj = XML (XMLFile.read ());\n XMLFile.close ();\n var Red1 = XMLObj[\"firstred\"];\n var Green1 = XMLObj[\"firstgreen\"];\n var Blue1 = XMLObj[\"firstrblue\"];\n var Red2 = XMLObj[\"secondred\"];\n var Green2 = XMLObj[\"secondgreen\"];\n var Blue2 = XMLObj[\"secondblue\"];\n var FirstColor = [Number (Red1), Number (Green1), Number (Blue1)];\n var SecondColor = [Number (Red2), Number (Green2), Number (Blue2)];\n var MainPanel = new Window (\"dialog\", \"Panel1\");\n var Text1 = MainPanel.add (\"statictext\");\n Text1.text = \"First color\";\n var RSlider1 = MainPanel.add (\"slider\");\n RSlider1.minvalue = 0;\n RSlider1.maxvalue = 255;\n RSlider1.value = Math.round (Red1 * 255);\n var RNumber1 = MainPanel.add (\"statictext\", undefined, RSlider1.value);\n RNumber1.preferredSize.width = 25;\n RNumber1.graphics.foregroundColor = RNumber1.graphics.newPen (RNumber1.graphics.PenType.SOLID_COLOR, [1, 0, 0], 1);\n RNumber1.graphics.disabledForegroundColor = RNumber1.graphics.foregroundColor;\n RNumber1.graphics.font = ScriptUI.newFont (RNumber1.graphics.font.name, \"Bold\", RNumber1.graphics.font.size);\n var GSlider1 = MainPanel.add (\"slider\");\n GSlider1.minvalue = 0;\n GSlider1.maxvalue = 255;\n GSlider1.value = Math.round (Green1 * 255);\n var GNumber1 = MainPanel.add (\"statictext\", undefined, GSlider1.value);\n GNumber1.preferredSize.width = 25;\n GNumber1.graphics.foregroundColor = GNumber1.graphics.newPen (GNumber1.graphics.PenType.SOLID_COLOR, [0, 1, 0], 1);\n GNumber1.graphics.disabledForegroundColor = GNumber1.graphics.foregroundColor;\n GNumber1.graphics.font = ScriptUI.newFont (GNumber1.graphics.font.name, \"Bold\", GNumber1.graphics.font.size);\n var BSlider1 = MainPanel.add (\"slider\");\n BSlider1.minvalue = 0;\n BSlider1.maxvalue = 255;\n BSlider1.value = Math.round (Blue1 * 255);\n var BNumber1 = MainPanel.add (\"statictext\", undefined, BSlider1.value);\n BNumber1.preferredSize.width = 25;\n BNumber1.graphics.foregroundColor = BNumber1.graphics.newPen (BNumber1.graphics.PenType.SOLID_COLOR, [0, 0, 1], 1);\n BNumber1.graphics.disabledForegroundColor = BNumber1.graphics.foregroundColor;\n BNumber1.graphics.font = ScriptUI.newFont (BNumber1.graphics.font.name, \"Bold\", BNumber1.graphics.font.size);\n RSlider1.onChanging = GSlider1.onChanging = BSlider1.onChanging = function () {\n RNumber1.text = Math.round (RSlider1.value);\n GNumber1.text = Math.round (GSlider1.value);\n BNumber1.text = Math.round (BSlider1.value);\n Red1 = Math.floor ((RSlider1.value / 255) * 100) / 100;\n Green1 = Math.floor ((GSlider1.value / 255) * 100) / 100;\n Blue1 = Math.floor ((BSlider1.value / 255) * 100) / 100;\n }\n var Text2 = MainPanel.add (\"statictext\");\n Text2.text = \"Second color\";\n var RSlider2 = MainPanel.add (\"slider\");\n RSlider2.minvalue = 0;\n RSlider2.maxvalue = 255;\n RSlider2.value = Math.round (Red2 * 255);\n var RNumber2 = MainPanel.add (\"statictext\", undefined, RSlider2.value);\n RNumber2.preferredSize.width = 25;\n RNumber2.graphics.foregroundColor = RNumber2.graphics.newPen (RNumber2.graphics.PenType.SOLID_COLOR, [1, 0, 0], 1);\n RNumber2.graphics.disabledForegroundColor = RNumber2.graphics.foregroundColor;\n RNumber2.graphics.font = ScriptUI.newFont (RNumber2.graphics.font.name, \"Bold\", RNumber2.graphics.font.size);\n var GSlider2 = MainPanel.add (\"slider\");\n GSlider2.minvalue = 0;\n GSlider2.maxvalue = 255;\n GSlider2.value = Math.round (Green2 * 255);\n var GNumber2 = MainPanel.add (\"statictext\", undefined, GSlider2.value);\n GNumber2.preferredSize.width = 25;\n GNumber2.graphics.foregroundColor = GNumber2.graphics.newPen (GNumber2.graphics.PenType.SOLID_COLOR, [0, 1, 0], 1);\n GNumber2.graphics.disabledForegroundColor = GNumber2.graphics.foregroundColor;\n GNumber2.graphics.font = ScriptUI.newFont (GNumber2.graphics.font.name, \"Bold\", GNumber2.graphics.font.size);\n var BSlider2 = MainPanel.add (\"slider\");\n BSlider2.minvalue = 0;\n BSlider2.maxvalue = 255;\n BSlider2.value = Math.round (Blue2 * 255);\n var BNumber2 = MainPanel.add (\"statictext\", undefined, BSlider2.value);\n BNumber2.preferredSize.width = 25;\n BNumber2.graphics.foregroundColor = BNumber2.graphics.newPen (BNumber2.graphics.PenType.SOLID_COLOR, [0, 0, 1], 1);\n BNumber2.graphics.disabledForegroundColor = BNumber2.graphics.foregroundColor;\n BNumber2.graphics.font = ScriptUI.newFont (BNumber2.graphics.font.name, \"Bold\", BNumber2.graphics.font.size);\n RSlider2.onChanging = GSlider2.onChanging = BSlider2.onChanging = function () {\n RNumber2.text = Math.round (RSlider2.value);\n GNumber2.text = Math.round (GSlider2.value);\n BNumber2.text = Math.round (BSlider2.value);\n Red2 = Math.floor ((RSlider2.value / 255) * 100) / 100;\n Green2 = Math.floor ((GSlider2.value / 255) * 100) / 100;\n Blue2 = Math.floor ((BSlider2.value / 255) * 100) / 100;\n }\n var Apply = MainPanel.add (\"button\", undefined, \"Apply changes\");\n Apply.onClick = function () {\n var XML = new File (Folder.desktop + \"/config.xml\");\n XML.open ('w');\n XML.writeln ('<?xml version=\"1.0\" encoding=\"utf-8\"?>');\n XML.writeln (\"<variables>\");\n XML.writeln (\" <firstred>\" + Red1 + \"</firstred>\");\n XML.writeln (\" <firstgreen>\" + Green1 + \"</firstgreen>\");\n XML.writeln (\" <firstrblue>\" + Blue1 + \"</firstrblue>\");\n XML.writeln (\" <secondred>\" + Red2 + \"</secondred>\");\n XML.writeln (\" <secondgreen>\" + Green2 + \"</secondgreen>\");\n XML.writeln (\" <secondblue>\" + Blue2 + \"</secondblue>\");\n XML.writeln (\"</variables>\");\n XML.close ();\n MainPanel.close ();\n }\n alert (\"Color 1 : \" + Red1 + \" - \" + Green1 + \" - \" + Blue1);\n alert (\"Color 2 : \" + Red2 + \" - \" + Green2 + \" - \" + Blue2);\n MainPanel.show ();\n function Create () {\n var XML = new File (Folder.desktop + \"/config.xml\");\n XML.open ('w');\n XML.writeln ('<?xml version=\"1.0\" encoding=\"utf-8\"?>');\n XML.writeln (\"<variables>\");\n XML.writeln (\" <firstred>0</firstred>\");\n XML.writeln (\" <firstgreen>0</firstgreen>\");\n XML.writeln (\" <firstrblue>0</firstrblue>\");\n XML.writeln (\" <secondred>1</secondred>\");\n XML.writeln (\" <secondgreen>1</secondgreen>\");\n XML.writeln (\" <secondblue>1</secondblue>\");\n XML.writeln (\"</variables>\");\n XML.close ();\n }\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18714172/" ]
74,291,964
<p>Lets say I have a Google Sheet that looks like this.</p> <p><a href="https://i.stack.imgur.com/Hm1YI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Hm1YI.png" alt="enter image description here" /></a></p> <p>You can export it so it can be reached with a URL similar to this</p> <pre><code># CSV https://docs.google.com/spreadsheets/d/e/Eis4Ya-Le9Py/pub?gid=0&amp;single=true&amp;output=csv # TSV https://docs.google.com/spreadsheets/d/e/Eis4Ya-Le9Py/pub?gid=0&amp;single=true&amp;output=tsv </code></pre> <p>If you download the file and open it on Open Office, you can clearly see that it recognize the multilines.</p> <p><a href="https://i.stack.imgur.com/ZHV1N.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZHV1N.png" alt="enter image description here" /></a></p> <p>And that is because the field with multiple lines get enclosed in &quot;&quot;.</p> <p>In a plain text editor it looks like</p> <p><a href="https://i.stack.imgur.com/GUSA6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GUSA6.png" alt="enter image description here" /></a></p> <p>However, and here is the problem, if I get the file using python requests library, the double quotes are removed.</p> <pre><code>import requests r=requests.get(url) print(r.text) print(r.content) print(r.headers) id description 1 one line 2 line1 line2 3 l1 l2 empty line below end 4 normal b'id\tdescription\r\n1\tone line\r\n2\tline1 line2\r\n3\tl1 l2 empty line below end\r\n4\tnormal' {'Content-Type': 'text/tab-separated-values', 'X-Frame-Options': 'ALLOW-FROM https://docs.google.com', ... , 'Transfer-Encoding': 'chunked'} </code></pre> <p>Why?</p> <p>How can I change that behavior?</p> <p>I know there is a library for dealing with <strong>csv</strong> files, but I cannot use it in the environment I am in.</p>
[ { "answer_id": 74316262, "author": "Rub", "author_id": 4752223, "author_profile": "https://Stackoverflow.com/users/4752223", "pm_score": 2, "selected": true, "text": "url_base=\"https://docs.google.com/spreadsheets/d/e/2PA...be/pub?gid=0&single=true&output=\"\n\nimport io\nimport requests\n\n# simple test\n# file exported as csv\nurl=url_base+\"csv\"\n\ns=requests.get(url)\nprint(\"-------- CSV -----------\")\nprint(s.text)\nprint(s.content)\n\nurl=url_base+\"tsv\"\n\ns=requests.get(url)\nprint(\"-------- TSV -----------\")\nprint(s.text)\nprint(s.content)\n" }, { "answer_id": 74321498, "author": "Lorena Gomez", "author_id": 17926478, "author_profile": "https://Stackoverflow.com/users/17926478", "pm_score": 0, "selected": false, "text": "requests" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4752223/" ]
74,291,971
<p>So I'm making a program in Python that goes through all of your files in the download folder but when I run it, it says</p> <p>(SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape).</p> <p>I use a variable to store the directory and put it in a for loop with the OS library. please help me. (Windows 11, python 3.9.)</p> <p>I know many people have asked this question and I have gone through all of the answers but none of them works for me, I think the problem I have, sounds similar to others but it actually is very different, so please don't mark this as duplicate. please help :)</p> <p>Code:</p> <pre><code>#im trying to make a program that goes through all the files in my downloads folder import os from time import sleep source_dir = &quot;C:\Users\(replace with you'r name to test)\example\Downloads&quot; with os.scandir(source_dir) as entries: for entry in entries: print(entry.name) sleep(0.35) </code></pre> <p>I have tried to change the \ with / and with // and with \, but none of the different types work. i have also tried removing the &quot; and also replacing them with ', it didnt work. please help</p>
[ { "answer_id": 74316262, "author": "Rub", "author_id": 4752223, "author_profile": "https://Stackoverflow.com/users/4752223", "pm_score": 2, "selected": true, "text": "url_base=\"https://docs.google.com/spreadsheets/d/e/2PA...be/pub?gid=0&single=true&output=\"\n\nimport io\nimport requests\n\n# simple test\n# file exported as csv\nurl=url_base+\"csv\"\n\ns=requests.get(url)\nprint(\"-------- CSV -----------\")\nprint(s.text)\nprint(s.content)\n\nurl=url_base+\"tsv\"\n\ns=requests.get(url)\nprint(\"-------- TSV -----------\")\nprint(s.text)\nprint(s.content)\n" }, { "answer_id": 74321498, "author": "Lorena Gomez", "author_id": 17926478, "author_profile": "https://Stackoverflow.com/users/17926478", "pm_score": 0, "selected": false, "text": "requests" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74291971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20399158/" ]
74,292,005
<p>I am building a React-App and I hae a problem working with <code>json/array</code> an the <code>.map()-function</code>. My serverside json object looks like :</p> <pre><code>let jsonlist = [ { Title: &quot;first title&quot;, Listofitems: [&quot;Item 01&quot;, &quot;Item 02&quot;, &quot;Item 03&quot;] }, { Title: &quot;second title&quot;, Listofitems: [&quot;Item 04&quot;, &quot;Item 05&quot;, &quot;Item 06&quot;] } ] </code></pre> <p>And a sample of my code clientside looks like this:</p> <pre><code>const [lists, setmylist] = useState([]); const fetchFact = () =&gt; { fetch(&quot;http://myapi:4000/getmyList&quot;) .then((response) =&gt; response.json()) .then((data) =&gt; setmylist(data)); } useEffect(() =&gt; { fetchFact() }, []); return ( &lt;div className='container'&gt; {lists.map(singleobject =&gt; { var test = Object.entries(singleobject); { console.log(test) } { console.log(test[0][0]) } &lt;p&gt;{test[0][0]}&lt;/p&gt; })} &lt;/div&gt; ); </code></pre> <p>If I run this I get as <code>{ console.log(test)} </code>:</p> <pre><code>[ [ &quot;Title&quot;, &quot;first title&quot; ], [ &quot;Listofitems&quot;, [ &quot;Item 01&quot;, &quot;Item 02&quot;, &quot;Item 03&quot; ] ] ] </code></pre> <p>But the <code>&lt;p&gt;{test[0][0]}&lt;/p&gt; </code> not gets displayed. If I change</p> <pre><code>{lists.map(singleobject =&gt; {})} </code></pre> <p>to something like</p> <pre><code>{projects.map(singleproject =&gt; ( &lt;p key={hereineedauniqueid}&gt;Just checkin&lt;/p&gt; ))} </code></pre> <p><code>Just checkin</code> gets displayed 2 times just like I want but i don´t know how to acess my values from the <code>json/array</code>. Do i need to change the structure of the <code>json/array</code> or do i need to change my code?</p> <p>I think I need to use the <code>{lists.map(singleobject =&gt; {})}</code> function because i want to create a Table and a <code>react-bootstrap/Modal</code> for every elment in the <code>json/array</code> and want to display the values from the <code>json/array</code> in every specific modal</p> <p>Thanks for your help</p>
[ { "answer_id": 74316262, "author": "Rub", "author_id": 4752223, "author_profile": "https://Stackoverflow.com/users/4752223", "pm_score": 2, "selected": true, "text": "url_base=\"https://docs.google.com/spreadsheets/d/e/2PA...be/pub?gid=0&single=true&output=\"\n\nimport io\nimport requests\n\n# simple test\n# file exported as csv\nurl=url_base+\"csv\"\n\ns=requests.get(url)\nprint(\"-------- CSV -----------\")\nprint(s.text)\nprint(s.content)\n\nurl=url_base+\"tsv\"\n\ns=requests.get(url)\nprint(\"-------- TSV -----------\")\nprint(s.text)\nprint(s.content)\n" }, { "answer_id": 74321498, "author": "Lorena Gomez", "author_id": 17926478, "author_profile": "https://Stackoverflow.com/users/17926478", "pm_score": 0, "selected": false, "text": "requests" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74292005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20388235/" ]
74,292,014
<p>I'd like to restrict a field so that it can only begins with some specific values. This is what I tried:</p> <pre><code>&lt;xs:simpleType&gt; &lt;xs:restriction base=&quot;xs:string&quot;&gt; &lt;xs:pattern value=&quot;(green apple)+|(blue orange)+|(lemon 123)+&quot;/&gt; &lt;/xs:restriction&gt; &lt;/xs:simpleType&gt; </code></pre> <p>and also</p> <pre><code>&lt;xs:simpleType&gt; &lt;xs:restriction base=&quot;xs:string&quot;&gt; &lt;xs:pattern value=&quot;(green apple|blue orange|lemon 123)+&quot;/&gt; &lt;/xs:restriction&gt; &lt;/xs:simpleType&gt; </code></pre> <p>Doing so, I was hopping that<br /> green apple: valid<br /> green apple (Gala): valid<br /> red apple: not valid</p> <p>But none of these attempts were successful. Any idea how I could achieve that?</p> <p>EDIT: I changed so enum values, so that they now contain whitespace</p>
[ { "answer_id": 74292091, "author": "Michael Kay", "author_id": 415448, "author_profile": "https://Stackoverflow.com/users/415448", "pm_score": 2, "selected": false, "text": "<xs:pattern value=\"(apple|orange|lemon).+\"/>\n" }, { "answer_id": 74297104, "author": "Dijkgraaf", "author_id": 2571021, "author_profile": "https://Stackoverflow.com/users/2571021", "pm_score": 1, "selected": false, "text": " <xs:simpleType>\n <xs:restriction base=\"xs:string\">\n <xs:pattern value=\"green apple.*\" />\n <xs:pattern value=\"blue orange.*\" />\n <xs:pattern value=\"lemon 123.*\" />\n </xs:restriction>\n </xs:simpleType>\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74292014", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10991651/" ]
74,292,033
<p>I have a table1 in an xlsx that has headers: a, b, c, d. I have a table2 in a different xlsx that has headers: a, z, c, d. (where &quot;z&quot; is a different name than &quot;b&quot; however is the same value). (i.e., just a different header name like &quot;b&quot; can be &quot;sales&quot; and &quot;z&quot; can be &quot;revenue&quot;. They mean the same thing but are just different header texts).</p> <p>Right now my PBI report has graphs that are created from <strong>table1</strong> xlsx import. (i.e., using fields a,b,c,d). For example: I have a bar graph that uses field &quot;a&quot; as x-axis and field &quot;b&quot; as y-axis columns.</p> <p>How can I use query editor (or other feature) such that when I use <strong>table2</strong> instead, the graphs automatically update to use the fields from table2 even though they may be different names as table1 headers? For example: I originally have a bar graph that uses <strong>table1</strong> fields &quot;a&quot; as x-axis and field &quot;b&quot; as y-axis columns. But now since I have <strong>table2</strong> imported and not table1, I want my pbi report to automatically update the bar graph to use fields &quot;a&quot; as x-axis and field &quot;z&quot; as the y-axis value/column.</p> <p>I was told there is a mapping feature to do this within PBI but idk how. I understand I can manually go to the graph and re-click what fields I want, but this PBI is pulling from a local copy of an xlsx that is going to be re-uploaded every week with new raw data, so the conversion of the headers need to happen within PBI if that makes sense. Otherwise if you upload the xlsx again every week it will just be the old headers.</p> <p>I played around with the power query editor but am not experienced enough to figure it out. Not really sure what I'm doing. Unfortunately, online trainings in PBI don't really teach you advanced features like this.</p>
[ { "answer_id": 74292091, "author": "Michael Kay", "author_id": 415448, "author_profile": "https://Stackoverflow.com/users/415448", "pm_score": 2, "selected": false, "text": "<xs:pattern value=\"(apple|orange|lemon).+\"/>\n" }, { "answer_id": 74297104, "author": "Dijkgraaf", "author_id": 2571021, "author_profile": "https://Stackoverflow.com/users/2571021", "pm_score": 1, "selected": false, "text": " <xs:simpleType>\n <xs:restriction base=\"xs:string\">\n <xs:pattern value=\"green apple.*\" />\n <xs:pattern value=\"blue orange.*\" />\n <xs:pattern value=\"lemon 123.*\" />\n </xs:restriction>\n </xs:simpleType>\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74292033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7736413/" ]
74,292,035
<p>I'm trying to create a numpy array of intergers ascending intergers (1,2,3,...), such that the n is repeated n times. For example for maximum number 4 I would like</p> <pre class="lang-py prettyprint-override"><code>my_arr = [1,2,2,3,3,3,4,4,4,4] </code></pre> <p>Now this is easy using a for loop</p> <pre class="lang-py prettyprint-override"><code>my_arr = numpy.array([]) max = 4 for i in range(1,max + 1): my_arr = numpy.append(my_arr,np.ones(i)*i) </code></pre> <p>but this gets horribly slow for large numbers <code>max</code>. Any suggestions?</p>
[ { "answer_id": 74292156, "author": "Chrysophylaxs", "author_id": 9499196, "author_profile": "https://Stackoverflow.com/users/9499196", "pm_score": 3, "selected": true, "text": "np.repeat" }, { "answer_id": 74292198, "author": "davidlowryduda", "author_id": 1141805, "author_profile": "https://Stackoverflow.com/users/1141805", "pm_score": 1, "selected": false, "text": "import numpy as np\n\n\ndef builtinway(maxval=10):\n arr = list(range(1, maxval+1))\n return np.repeat(arr, arr)\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74292035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14729474/" ]
74,292,048
<p>I have following table (elements from col. A and B are linked - building kind of a graph with direct &amp; indirect connections). I am looking for a way to create separate groups (=lists) that will only contain elements that are only linked to each other (directly &amp; indirectly), such as: <code>{a, b, d, x}</code> and <code>{c, y, z}</code>. <br> I figure it out how to code this in the <code>for loop</code> iterating through entire table (comparing if each <code>n+1</code> pair contains at least one element in the previous group, then create a group). <strong>I assume this is not ideal/desirable solution in Python</strong>. Please suggest more elegant solution which might utilize Pandas.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>A</th> <th>B</th> </tr> </thead> <tbody> <tr> <td>a</td> <td>x</td> </tr> <tr> <td>b</td> <td>x</td> </tr> <tr> <td>c</td> <td>y</td> </tr> <tr> <td>c</td> <td>z</td> </tr> <tr> <td>d</td> <td>x</td> </tr> <tr> <td>x</td> <td>a</td> </tr> <tr> <td>x</td> <td>x</td> </tr> <tr> <td>y</td> <td>z</td> </tr> </tbody> </table> </div>
[ { "answer_id": 74292259, "author": "Kkameleon", "author_id": 12094184, "author_profile": "https://Stackoverflow.com/users/12094184", "pm_score": 2, "selected": false, "text": "\n# Python program to print connected\n# components in an undirected graph\n \n \nclass Graph:\n \n # init function to declare class variables\n def __init__(self, V):\n self.V = V\n self.adj = [[] for i in range(V)]\n \n def DFSUtil(self, temp, v, visited):\n \n # Mark the current vertex as visited\n visited[v] = True\n \n # Store the vertex to list\n temp.append(v)\n \n # Repeat for all vertices adjacent\n # to this vertex v\n for i in self.adj[v]:\n if visited[i] == False:\n \n # Update the list\n temp = self.DFSUtil(temp, i, visited)\n return temp\n \n # method to add an undirected edge\n def addEdge(self, v, w):\n self.adj[v].append(w)\n self.adj[w].append(v)\n \n # Method to retrieve connected components\n # in an undirected graph\n def connectedComponents(self):\n visited = []\n cc = []\n for i in range(self.V):\n visited.append(False)\n for v in range(self.V):\n if visited[v] == False:\n temp = []\n cc.append(self.DFSUtil(temp, v, visited))\n return cc\n \n \n# Driver Code\nif __name__ == \"__main__\":\n \n # Create a graph given in the above diagram\n # 5 vertices numbered from 0 to 4\n g = Graph(5)\n g.addEdge(1, 0)\n g.addEdge(2, 1)\n g.addEdge(3, 4)\n cc = g.connectedComponents()\n print(\"Following are connected components\")\n print(cc)\n\n# This code is contributed by Abhishek Valsan\n" }, { "answer_id": 74293220, "author": "Mike", "author_id": 12403385, "author_profile": "https://Stackoverflow.com/users/12403385", "pm_score": 0, "selected": false, "text": "for loops" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74292048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12403385/" ]
74,292,053
<p>I am creating a <strong>DevOps</strong> pipeline for a NodeJs app which i am containerizing as a Docker Image in ACR and deploying it as a ContainerApp in Azure.</p> <p>I have the following permissions in subscription : &gt; User Access Administrator ( cannot be given more elevated permissions other than this)</p> <p>I have already created a App Registration -&gt; AppReg1- which i will patch the containerapp url in the pipleline</p> <p>For deploying from ACR, I am writing a pipeline job as a bash script:</p> <pre><code>variables: # Container registry service connection established during pipeline creation armDeploymentServiceConnection: 'appdeploy1' //passing the service connection name here </code></pre> <pre><code>- stage: DeployContainerApp displayName: Deploy the Image as a Container app jobs: - job: DeployContainerApp displayName: Deploy Container App Job steps: - task: AzureCLI@2 inputs: azureSubscription: $(armDeploymentServiceConnection) //passing service connection name scriptType: 'bash' scriptLocation: 'inlineScript' inlineScript: | az --version az account show echo &quot;containerapp will be created&quot; az ad app show --id $(AppReg1ClientId) --query id | jq -r . //error line throwing insufficient privileges </code></pre> <p>in the inputs: I have created a ARM type service connection with manual Service principal defined <code>inputs: azureSubscription:**armDeploymentServiceConnection**: </code>//Here I am passing the ServiceConnection which i have created in manual mode: <a href="https://i.stack.imgur.com/4AhlH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4AhlH.png" alt="enter image description here" /></a></p> <p>The SP i used for this Service connection <strong>appdeploy1</strong> is created with the role <strong>contributor</strong> before hand</p> <p><code>az ad sp create-for-rbac --scopes /subscriptions/xxxx --role Contributor --name **appSP**</code></p> <p>This SP leads to a additional AppRegistration ex-&gt;<strong>appSP</strong>. I am using this SP only for the inline script</p> <p>When i run the pipeline, this line throws this error where i m trying to get the object id of the registration AppReg1 where i am going to register my containerApp: <code>az ad app show --id $(AppReg1ClientId) --query id | jq -r . </code></p> <pre><code>ERROR: Insufficient privileges to complete the operation. </code></pre> <p>Since i created the service principal with the role <strong>contributor</strong> and created the ServiceConnection with that principal <strong>appSP</strong> i thought this step will succeed:</p> <pre><code> - task: AzureCLI@2 inputs: azureSubscription: $(armDeploymentServiceConnection) </code></pre> <p>but this line throws error <code>inlineScript: | az ad app show --id $(APP_REG_CLIENT_ID) --query id | jq -r . //error line </code></p> <p>I am not sure, what is missing here? Can anyone please help?</p>
[ { "answer_id": 74292259, "author": "Kkameleon", "author_id": 12094184, "author_profile": "https://Stackoverflow.com/users/12094184", "pm_score": 2, "selected": false, "text": "\n# Python program to print connected\n# components in an undirected graph\n \n \nclass Graph:\n \n # init function to declare class variables\n def __init__(self, V):\n self.V = V\n self.adj = [[] for i in range(V)]\n \n def DFSUtil(self, temp, v, visited):\n \n # Mark the current vertex as visited\n visited[v] = True\n \n # Store the vertex to list\n temp.append(v)\n \n # Repeat for all vertices adjacent\n # to this vertex v\n for i in self.adj[v]:\n if visited[i] == False:\n \n # Update the list\n temp = self.DFSUtil(temp, i, visited)\n return temp\n \n # method to add an undirected edge\n def addEdge(self, v, w):\n self.adj[v].append(w)\n self.adj[w].append(v)\n \n # Method to retrieve connected components\n # in an undirected graph\n def connectedComponents(self):\n visited = []\n cc = []\n for i in range(self.V):\n visited.append(False)\n for v in range(self.V):\n if visited[v] == False:\n temp = []\n cc.append(self.DFSUtil(temp, v, visited))\n return cc\n \n \n# Driver Code\nif __name__ == \"__main__\":\n \n # Create a graph given in the above diagram\n # 5 vertices numbered from 0 to 4\n g = Graph(5)\n g.addEdge(1, 0)\n g.addEdge(2, 1)\n g.addEdge(3, 4)\n cc = g.connectedComponents()\n print(\"Following are connected components\")\n print(cc)\n\n# This code is contributed by Abhishek Valsan\n" }, { "answer_id": 74293220, "author": "Mike", "author_id": 12403385, "author_profile": "https://Stackoverflow.com/users/12403385", "pm_score": 0, "selected": false, "text": "for loops" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74292053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20263192/" ]
74,292,070
<p>My application is divided into authentication for API and UI. UI contains:</p> <p>ClientId, ClientSecret, Tenant, Redirect URL</p> <p>API contains: ApiClientId, APPID URI, Tenant</p> <p>I am able to obtain access token using: UI_ClientId as client_id, API_ClientId as scope UI_ClientSecret and ofcourse Tenant</p> <p>But when I add authentication on my API side through AddMicrosoftIdentityWebApi, like following:</p> <pre><code>services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddMicrosoftIdentityWebApi(options =&gt; { Configuration.Bind(&quot;AzureAd&quot;, options); options.Authority = $&quot;{azureAdOptions.Instance}{azureAdOptions.TenantId}&quot;; options.Audience = azureAdOptions.ClientId; options.TokenValidationParameters = new TokenValidationParameters() { ValidateAudience = true, ValidateIssuer = true, ValidIssuer = $&quot;https://login.microsoftonline.com/{azureAdOptions.TenantId}/v2.0&quot; </code></pre> <p>While sending request im getting general error: &quot;Object reference not set to an instance...&quot; without any details.</p> <p>When I try to add authentication like:</p> <pre><code>services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme) .AddAzureADBearer(options =&gt; { Configuration.Bind(&quot;AzureAd&quot;, options); }); </code></pre> <p>I get unauthorized error message.</p> <p>AzConfig in appsettings.json:</p> <pre><code> &quot;AzureAd&quot;: { &quot;Instance&quot;: &quot;https://login.microsoftonline.com/&quot;, &quot;Domain&quot;: &quot;domain&quot;, &quot;TenantId&quot;: &quot;tenantId&quot;, &quot;ClientId&quot;: &quot;ApiClientId&quot;, &quot;ApiScopes&quot;: &quot;https://xxx/tenatnId/APIAccess/Name.API&quot; } </code></pre> <p>Please advice what I might`ve missed, cause its diving me nuts.</p>
[ { "answer_id": 74292259, "author": "Kkameleon", "author_id": 12094184, "author_profile": "https://Stackoverflow.com/users/12094184", "pm_score": 2, "selected": false, "text": "\n# Python program to print connected\n# components in an undirected graph\n \n \nclass Graph:\n \n # init function to declare class variables\n def __init__(self, V):\n self.V = V\n self.adj = [[] for i in range(V)]\n \n def DFSUtil(self, temp, v, visited):\n \n # Mark the current vertex as visited\n visited[v] = True\n \n # Store the vertex to list\n temp.append(v)\n \n # Repeat for all vertices adjacent\n # to this vertex v\n for i in self.adj[v]:\n if visited[i] == False:\n \n # Update the list\n temp = self.DFSUtil(temp, i, visited)\n return temp\n \n # method to add an undirected edge\n def addEdge(self, v, w):\n self.adj[v].append(w)\n self.adj[w].append(v)\n \n # Method to retrieve connected components\n # in an undirected graph\n def connectedComponents(self):\n visited = []\n cc = []\n for i in range(self.V):\n visited.append(False)\n for v in range(self.V):\n if visited[v] == False:\n temp = []\n cc.append(self.DFSUtil(temp, v, visited))\n return cc\n \n \n# Driver Code\nif __name__ == \"__main__\":\n \n # Create a graph given in the above diagram\n # 5 vertices numbered from 0 to 4\n g = Graph(5)\n g.addEdge(1, 0)\n g.addEdge(2, 1)\n g.addEdge(3, 4)\n cc = g.connectedComponents()\n print(\"Following are connected components\")\n print(cc)\n\n# This code is contributed by Abhishek Valsan\n" }, { "answer_id": 74293220, "author": "Mike", "author_id": 12403385, "author_profile": "https://Stackoverflow.com/users/12403385", "pm_score": 0, "selected": false, "text": "for loops" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74292070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10375597/" ]
74,292,093
<p>Given an array with each element consisting of three numbers [start, end, x].<br /> An element of array [start,end,x] means that we have to select exactly x integers from [start,end] inclusive of both start and end. Put these numbers in a Set. Do this for all elements of the array. So at the end the Set will have a size. Return the minimal possible size. <code>Example Array= [1,3,2],[2,5,3],[5,6,2]</code><br /> from 1st elements choose 2,3 from 2nd choose 2,3,5 and from 3rd choose 5,6 so the set of chosen numbers = 2,3,5,6 which has 4 elements which is the minimum. So for this input the answer or the return value is <code>4</code></p> <p><strong>My Thoughts:</strong><br /> I tried to think of some optimal substructure property in the hope that it will yield to a DP solution, but looks like there is no clear optimal substructure property here.</p>
[ { "answer_id": 74292259, "author": "Kkameleon", "author_id": 12094184, "author_profile": "https://Stackoverflow.com/users/12094184", "pm_score": 2, "selected": false, "text": "\n# Python program to print connected\n# components in an undirected graph\n \n \nclass Graph:\n \n # init function to declare class variables\n def __init__(self, V):\n self.V = V\n self.adj = [[] for i in range(V)]\n \n def DFSUtil(self, temp, v, visited):\n \n # Mark the current vertex as visited\n visited[v] = True\n \n # Store the vertex to list\n temp.append(v)\n \n # Repeat for all vertices adjacent\n # to this vertex v\n for i in self.adj[v]:\n if visited[i] == False:\n \n # Update the list\n temp = self.DFSUtil(temp, i, visited)\n return temp\n \n # method to add an undirected edge\n def addEdge(self, v, w):\n self.adj[v].append(w)\n self.adj[w].append(v)\n \n # Method to retrieve connected components\n # in an undirected graph\n def connectedComponents(self):\n visited = []\n cc = []\n for i in range(self.V):\n visited.append(False)\n for v in range(self.V):\n if visited[v] == False:\n temp = []\n cc.append(self.DFSUtil(temp, v, visited))\n return cc\n \n \n# Driver Code\nif __name__ == \"__main__\":\n \n # Create a graph given in the above diagram\n # 5 vertices numbered from 0 to 4\n g = Graph(5)\n g.addEdge(1, 0)\n g.addEdge(2, 1)\n g.addEdge(3, 4)\n cc = g.connectedComponents()\n print(\"Following are connected components\")\n print(cc)\n\n# This code is contributed by Abhishek Valsan\n" }, { "answer_id": 74293220, "author": "Mike", "author_id": 12403385, "author_profile": "https://Stackoverflow.com/users/12403385", "pm_score": 0, "selected": false, "text": "for loops" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74292093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19284394/" ]
74,292,103
<p>I am trying to do some image interpreter and trying to store them directly to FTP server.</p> <p>But my steps like upload the image from local folder then it converts to mask image then it will have final output. But during my mask and final output scenarios, temporary images are getting save it local which I don't want.</p> <p>But without storing the image in local I unable to save the file to FTP. Please help me with solution that output.save(mask_img_path) without this step how can store the image in FTP.</p> <pre><code>import errno from flask import Flask,request from rembg import remove from PIL import Image import matplotlib.pyplot as plt import matplotlib.image as mpimg import time import random import ftplib import os app = Flask(__name__) input_img_path = &quot;C:/Projects/Python/input/1.jpg&quot; output_img_path = &quot;C:/Projects/Python/image-processing-2/image/output/&quot; mask_img_path = output_img_path + 'mask.png' mask_img = 'mask.png' input_img = Image.open(input_img_path) output = remove(input_img) output.save(mask_img_path) // without this step unable to FTP the file below because this step storing the mask images in the folder. ftp = ftplib.FTP('host', 'username', 'password') # Store the mask files into FTP with open(mask_img_path, &quot;rb&quot;) as file: ftp.storbinary('STOR %s' % mask_img, file) if __name__ == '__main__': app.run(debug=True,port=2000) </code></pre> <p>Given about all my coding step and strying to FTP the converted image.</p>
[ { "answer_id": 74292259, "author": "Kkameleon", "author_id": 12094184, "author_profile": "https://Stackoverflow.com/users/12094184", "pm_score": 2, "selected": false, "text": "\n# Python program to print connected\n# components in an undirected graph\n \n \nclass Graph:\n \n # init function to declare class variables\n def __init__(self, V):\n self.V = V\n self.adj = [[] for i in range(V)]\n \n def DFSUtil(self, temp, v, visited):\n \n # Mark the current vertex as visited\n visited[v] = True\n \n # Store the vertex to list\n temp.append(v)\n \n # Repeat for all vertices adjacent\n # to this vertex v\n for i in self.adj[v]:\n if visited[i] == False:\n \n # Update the list\n temp = self.DFSUtil(temp, i, visited)\n return temp\n \n # method to add an undirected edge\n def addEdge(self, v, w):\n self.adj[v].append(w)\n self.adj[w].append(v)\n \n # Method to retrieve connected components\n # in an undirected graph\n def connectedComponents(self):\n visited = []\n cc = []\n for i in range(self.V):\n visited.append(False)\n for v in range(self.V):\n if visited[v] == False:\n temp = []\n cc.append(self.DFSUtil(temp, v, visited))\n return cc\n \n \n# Driver Code\nif __name__ == \"__main__\":\n \n # Create a graph given in the above diagram\n # 5 vertices numbered from 0 to 4\n g = Graph(5)\n g.addEdge(1, 0)\n g.addEdge(2, 1)\n g.addEdge(3, 4)\n cc = g.connectedComponents()\n print(\"Following are connected components\")\n print(cc)\n\n# This code is contributed by Abhishek Valsan\n" }, { "answer_id": 74293220, "author": "Mike", "author_id": 12403385, "author_profile": "https://Stackoverflow.com/users/12403385", "pm_score": 0, "selected": false, "text": "for loops" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74292103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11681866/" ]
74,292,119
<p>I have deployed a private registry with Harbor with a self signed certificates. Importing images to harbor works pulling images works. On the worker nodes i have added certificates into OS as trusted and i can pull images successfully in the OS from worker nodes in cli running ctr images pull harbor.mylab.com:9091/mylab/acid1</p> <p>The problem is when i create a pod and it tries to pull an image from the private registry i am seeing a certificate error: x509: certificate signed by unknown authority</p> <p>After googling and reading more documentation on Rancher RKE2 i found out that you have to add registries.yml file, well in my case, the file exists but i am not sure how to edit it because once the rke2 agent is restarted on the node the file is overwritten.</p> <p>I want to have something like this as i understand it from the docs(<a href="https://docs.rke2.io/install/containerd_registry_configuration/" rel="nofollow noreferrer">https://docs.rke2.io/install/containerd_registry_configuration/</a>)</p> <pre><code>mirrors: docker.io: endpoint: - “harbor.mylab.com:9091:&quot; configs: “harbor.mylab.com:9091:&quot;: tls: cert_file: /opt/harbor/certs/harbor_registry.crt key_file: /opt/harbor/certs/harbor_registry.key ca_file: /opt/harbor/certs/harbor_registry.csr </code></pre>
[ { "answer_id": 74292259, "author": "Kkameleon", "author_id": 12094184, "author_profile": "https://Stackoverflow.com/users/12094184", "pm_score": 2, "selected": false, "text": "\n# Python program to print connected\n# components in an undirected graph\n \n \nclass Graph:\n \n # init function to declare class variables\n def __init__(self, V):\n self.V = V\n self.adj = [[] for i in range(V)]\n \n def DFSUtil(self, temp, v, visited):\n \n # Mark the current vertex as visited\n visited[v] = True\n \n # Store the vertex to list\n temp.append(v)\n \n # Repeat for all vertices adjacent\n # to this vertex v\n for i in self.adj[v]:\n if visited[i] == False:\n \n # Update the list\n temp = self.DFSUtil(temp, i, visited)\n return temp\n \n # method to add an undirected edge\n def addEdge(self, v, w):\n self.adj[v].append(w)\n self.adj[w].append(v)\n \n # Method to retrieve connected components\n # in an undirected graph\n def connectedComponents(self):\n visited = []\n cc = []\n for i in range(self.V):\n visited.append(False)\n for v in range(self.V):\n if visited[v] == False:\n temp = []\n cc.append(self.DFSUtil(temp, v, visited))\n return cc\n \n \n# Driver Code\nif __name__ == \"__main__\":\n \n # Create a graph given in the above diagram\n # 5 vertices numbered from 0 to 4\n g = Graph(5)\n g.addEdge(1, 0)\n g.addEdge(2, 1)\n g.addEdge(3, 4)\n cc = g.connectedComponents()\n print(\"Following are connected components\")\n print(cc)\n\n# This code is contributed by Abhishek Valsan\n" }, { "answer_id": 74293220, "author": "Mike", "author_id": 12403385, "author_profile": "https://Stackoverflow.com/users/12403385", "pm_score": 0, "selected": false, "text": "for loops" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74292119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2872503/" ]
74,292,169
<p>I want to extract the username, post title, post time and the message content from a Dell Community Forum thread of a particular date and store it into an excel file.</p> <p>For example, URL: <a href="https://www.dell.com/community/Inspiron-Desktops/I-am-getting-time-sync-errror-and-the-last-synced-time-shown-as/m-p/8290678#M36017" rel="nofollow noreferrer">https://www.dell.com/community/Inspiron-Desktops/I-am-getting-time-sync-errror-and-the-last-synced-time-shown-as/m-p/8290678#M36017</a></p> <p>I want to extract the post title: &quot;I am getting time sync errror and the last synced time shown as a day in 2015&quot;</p> <p>And details(username, post time, message) of comments for the date 10-25-2022 only</p> <ol> <li>jraju, 04:20 AM, &quot;This pc is desktop inspiron 3910 model . The dell supplied only this week.&quot;</li> <li>Mary G, 09:10 AM, &quot;Try rebooting the computer and connecting to the internet again to see if that clears it up. Don't forget to run Windows Update to get all the necessary updates on a new computer.&quot;</li> <li>RoHe, 01:00 PM, &quot;You might want to read Fix: Time synchronization failed on Windows 11. Totally ignore the part about downloading the software tool, and scroll down that same page to the part: How to manually sync time on a Windows 11 PC. NOTE: In step #6, if time.windows.com doesn't work, pick a different server from the drop-down menu on that screen.&quot;</li> </ol> <p>Not any other comments.</p> <p>I'm very new to this.</p> <p>Till now I've just managed to extract information(no username) without the date filter.</p> <p>I'm very new to this.</p> <p>Till now I've just managed to extract information(no username) without the date filter.</p> <pre><code> import requests from bs4 import BeautifulSoup url = &quot;https://www.dell.com/community/Inspiron-Desktops/I-am-getting-time-sync-errror-and-the-last-synced-time-shown-as/m-p/8290678#M36017&quot; result = requests.get(url) doc = BeautifulSoup(result.text, &quot;html.parser&quot;) ###### time ###### time = doc.find_all('span', attrs={'class':'local-time'}) print(time) ################## ##### date ####### date = doc.find_all('span', attrs={'class':'local-date'}) print(date) ################# #### message ###### article_text = '' article = doc.find_all(&quot;div&quot;, {&quot;class&quot;:&quot;lia-message-body-content&quot;}) for element in article: article_text += '\n' + ''.join(element.find_all(text = True)) print(article_text) ################## all_data = [] for t, d, m in zip(time, date, article): all_data.append([t.text, d.get_text(strip=True),m.get_text(strip=True, separator='\n')]) with open('data.csv', 'w', newline='', encoding=&quot;utf-8&quot;) as csvfile: writer = csv.writer(csvfile, delimiter=',', quotechar='&quot;', quoting=csv.QUOTE_MINIMAL) for row in all_data: writer.writerow(row) </code></pre>
[ { "answer_id": 74292259, "author": "Kkameleon", "author_id": 12094184, "author_profile": "https://Stackoverflow.com/users/12094184", "pm_score": 2, "selected": false, "text": "\n# Python program to print connected\n# components in an undirected graph\n \n \nclass Graph:\n \n # init function to declare class variables\n def __init__(self, V):\n self.V = V\n self.adj = [[] for i in range(V)]\n \n def DFSUtil(self, temp, v, visited):\n \n # Mark the current vertex as visited\n visited[v] = True\n \n # Store the vertex to list\n temp.append(v)\n \n # Repeat for all vertices adjacent\n # to this vertex v\n for i in self.adj[v]:\n if visited[i] == False:\n \n # Update the list\n temp = self.DFSUtil(temp, i, visited)\n return temp\n \n # method to add an undirected edge\n def addEdge(self, v, w):\n self.adj[v].append(w)\n self.adj[w].append(v)\n \n # Method to retrieve connected components\n # in an undirected graph\n def connectedComponents(self):\n visited = []\n cc = []\n for i in range(self.V):\n visited.append(False)\n for v in range(self.V):\n if visited[v] == False:\n temp = []\n cc.append(self.DFSUtil(temp, v, visited))\n return cc\n \n \n# Driver Code\nif __name__ == \"__main__\":\n \n # Create a graph given in the above diagram\n # 5 vertices numbered from 0 to 4\n g = Graph(5)\n g.addEdge(1, 0)\n g.addEdge(2, 1)\n g.addEdge(3, 4)\n cc = g.connectedComponents()\n print(\"Following are connected components\")\n print(cc)\n\n# This code is contributed by Abhishek Valsan\n" }, { "answer_id": 74293220, "author": "Mike", "author_id": 12403385, "author_profile": "https://Stackoverflow.com/users/12403385", "pm_score": 0, "selected": false, "text": "for loops" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74292169", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20399258/" ]
74,292,173
<p>I am trying to create a website based on the initial graphics of jquery.terminal and I have noticed that there are currently no questions related to video management. I got to see questions related to images, such as this one <a href="https://stackoverflow.com/questions/64656996/creating-a-linux-terminal-themed-website-using-html-and-javascript/64657034">Creating a Linux terminal themed website using HTML and JavaScript</a> but if I try to use the same writing style in the end I load a blank space.</p> <pre><code>mpv: function(file) { this.echo($('&lt;video src=&quot;assets/video/video.mp4&quot;&gt;')); } </code></pre> <p><a href="https://i.stack.imgur.com/52L3V.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/52L3V.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74292523, "author": "Arnav Katyal", "author_id": 20164496, "author_profile": "https://Stackoverflow.com/users/20164496", "pm_score": 0, "selected": false, "text": "mpv: function () {\nthis.echo($('<video src=\"assets/video/video.mp4\"></video>'));\n}\n" }, { "answer_id": 74296013, "author": "jcubic", "author_id": 387194, "author_profile": "https://Stackoverflow.com/users/387194", "pm_score": 2, "selected": true, "text": "<video width=\"500px\" height=\"500px\"\n controls=\"controls\">\n \n <source src=\"vid.mp4\"\n type=\"video/mp4\"/>\n</video>\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74292173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13077362/" ]
74,292,177
<p>Lets say I have a string:</p> <pre><code>StringA/StringB/StringC </code></pre> <p>Is there any way I can split this string by the <code>/</code> symbol, but keep it in the returned values:</p> <pre><code>StringA /StringB /StringC </code></pre>
[ { "answer_id": 74292227, "author": "Maël", "author_id": 13460602, "author_profile": "https://Stackoverflow.com/users/13460602", "pm_score": 3, "selected": false, "text": "(?=/)" }, { "answer_id": 74292279, "author": "ThomasIsCoding", "author_id": 12158757, "author_profile": "https://Stackoverflow.com/users/12158757", "pm_score": 2, "selected": false, "text": "scan" }, { "answer_id": 74292816, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 1, "selected": false, "text": "str_extract" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74292177", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19414769/" ]