qid
int64
4
22.2M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,352,284
<p>I have a fetch request in <strong>Home.vue</strong> file and I want to use the same data to another vue file (<strong>AllJobs.vue</strong>) with the same component(props). How I can achieve this without make a new fetch request in <em><strong>AllJobs.vue</strong></em>? I heard that I can use <em>Pinia</em>, but for a small project like this I wonder if it is a simpler solution?</p> <p><strong>Home.vue</strong></p> <pre class="lang-js prettyprint-override"><code> &lt;div class=&quot;cards-container&quot;&gt; &lt;div v-for=&quot;job in jobs.reverse().slice(0, 5)&quot; :key=&quot;job.id&quot; class=&quot;&quot;&gt; &lt;JobComponent :position=&quot;job.position&quot; :department=&quot;job.department&quot; :location=&quot;job.location&quot;/&gt; &lt;/div&gt; &lt;/div&gt; &lt;/template&gt; &lt;script&gt; import JobComponent from '../components/JobComponent.vue' export default { name: 'Home', components: { JobComponent }, data() { return { jobs: [], } }, mounted() { fetch(&quot;http://localhost:3000/jobs&quot;) .then(res =&gt; res.json()) .then(data =&gt; this.jobs = data) .catch(err =&gt; console.error(err.message)) } } &lt;/script&gt; </code></pre> <p><strong>AllJobs.vue</strong></p> <pre class="lang-js prettyprint-override"><code> &lt;div class=&quot;cards-container&quot;&gt; &lt;JobComponent /&gt; &lt;/div&gt; &lt;/template&gt; &lt;script&gt; import JobComponent from '../../components/JobComponent.vue' export default { name: &quot;AllJobs&quot;, components: { JobComponent }, } &lt;/script&gt; </code></pre> <p><strong>JobComponent.vue</strong></p> <pre class="lang-js prettyprint-override"><code> &lt;div class=&quot;card&quot;&gt; &lt;div class=&quot;position&quot;&gt;{{ position }}&lt;/div&gt; &lt;div class=&quot;department&quot;&gt;{{ department }}&lt;/div&gt; &lt;div class=&quot;location&quot;&gt; &lt;span class=&quot;material-symbols-outlined&quot;&gt; location_on &lt;/span&gt; {{ location }} &lt;/div&gt; &lt;span class=&quot;material-symbols-outlined right-arrow&quot;&gt; arrow_right_alt &lt;/span&gt; &lt;/div&gt; &lt;/template&gt; &lt;script&gt; export default { props: ['position', 'department', 'location'], } &lt;/script&gt; </code></pre>
[ { "answer_id": 74352852, "author": "Daniel", "author_id": 197546, "author_profile": "https://Stackoverflow.com/users/197546", "pm_score": 0, "selected": false, "text": "provide" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74352284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9172014/" ]
74,352,293
<p>How can I get member variable class(int) from object Item in the below function? I can see it in Visual Studio debugger dynamic view. but not sure how could I access this programmatically.</p> <pre><code> private void ThisAddIn_Startup(object sender, System.EventArgs e) { Application.ItemSend += new Outlook.ApplicationEvents_11_ItemSendEventHandler(Application_ItemSend); </code></pre> <pre><code>void Application_ItemSend(object Item, ref bool Cancel) </code></pre> <p>I want to use something like (int)Item.class So I can see Item's class such as mailitem, taskitem or meetingitem. and process accordingly.</p>
[ { "answer_id": 74352852, "author": "Daniel", "author_id": 197546, "author_profile": "https://Stackoverflow.com/users/197546", "pm_score": 0, "selected": false, "text": "provide" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74352293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20401086/" ]
74,352,294
<p>Code for a blackjack card counting program.</p> <p>the issue is that it does not exit the while loop upon receiving no cin input from the user.</p> <p>for example) User would input x chars and then hit enter to exit the while loop.</p> <pre><code>#include&lt;iostream&gt; using namespace std; int main(){ int count = 0; char currcard; cout&lt;&lt;&quot;Enter cards seen on table: &quot;&lt;&lt;endl; while (cin&gt;&gt;currcard) { switch (currcard) { case '1': case '2': case '3': case '4': case '5': case '6': count++; break; case '7': case '8': case '9': break; case 'A': case 'J': case 'Q': case 'K': count--; break; default: cout&lt;&lt;&quot;Invalid Entry&quot;; break; } } cout &lt;&lt;&quot;Current count: &quot;&lt;&lt; count &lt;&lt; endl; //user enter cards seen on table and if below 7 increment //based on count the program returns if you should hit or quit return 0; } </code></pre> <p>Expecting program to exit when enter is hit by user</p>
[ { "answer_id": 74352852, "author": "Daniel", "author_id": 197546, "author_profile": "https://Stackoverflow.com/users/197546", "pm_score": 0, "selected": false, "text": "provide" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74352294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20443701/" ]
74,352,312
<p>I am trying to return an image carousel component from daisyUI but whenever I try to use it in the return statement in my App.tsx it returns an error, but doesn't whenever there is just one component (Navbar). The error message states</p> <pre><code>'ImageSlides' cannot be used as a JSX component. Its return type 'void' is not a valid JSX element. </code></pre> <p>in App.tsx</p> <pre><code>import { useState } from &quot;react&quot;; import &quot;./App.css&quot;; import { NavBar } from &quot;./components/NavBar&quot;; import { ImageSlides } from &quot;./components/ImageSlides&quot;; const App = () =&gt; { return ( &lt;div className=&quot;App&quot;&gt; &lt;NavBar /&gt; &lt;ImageSlides/&gt; &lt;/div&gt; ); }; export default App; </code></pre> <p>in ImageSlider.tsx</p> <pre><code>import React from &quot;react&quot;; export function ImageSlides () { &lt;div className=&quot;carousel w-full&quot;&gt; &lt;div id=&quot;slide1&quot; className=&quot;carousel-item relative w-full&quot;&gt; &lt;img src=&quot;https://placeimg.com/800/200/arch&quot; className=&quot;w-full&quot; /&gt; &lt;div className=&quot;absolute flex justify-between transform -translate-y-1/2 left-5 right-5 top-1/2&quot;&gt; &lt;a href=&quot;#slide4&quot; className=&quot;btn btn-circle&quot;&gt;❮&lt;/a&gt; &lt;a href=&quot;#slide2&quot; className=&quot;btn btn-circle&quot;&gt;❯&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id=&quot;slide2&quot; className=&quot;carousel-item relative w-full&quot;&gt; &lt;img src=&quot;https://placeimg.com/800/200/arch&quot; className=&quot;w-full&quot; /&gt; &lt;div className=&quot;absolute flex justify-between transform -translate-y-1/2 left-5 right-5 top-1/2&quot;&gt; &lt;a href=&quot;#slide1&quot; className=&quot;btn btn-circle&quot;&gt;❮&lt;/a&gt; &lt;a href=&quot;#slide3&quot; className=&quot;btn btn-circle&quot;&gt;❯&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id=&quot;slide3&quot; className=&quot;carousel-item relative w-full&quot;&gt; &lt;img src=&quot;https://placeimg.com/800/200/arch&quot; className=&quot;w-full&quot; /&gt; &lt;div className=&quot;absolute flex justify-between transform -translate-y-1/2 left-5 right-5 top-1/2&quot;&gt; &lt;a href=&quot;#slide2&quot; className=&quot;btn btn-circle&quot;&gt;❮&lt;/a&gt; &lt;a href=&quot;#slide4&quot; className=&quot;btn btn-circle&quot;&gt;❯&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id=&quot;slide4&quot; className=&quot;carousel-item relative w-full&quot;&gt; &lt;img src=&quot;https://placeimg.com/800/200/arch&quot; className=&quot;w-full&quot; /&gt; &lt;div className=&quot;absolute flex justify-between transform -translate-y-1/2 left-5 right-5 top-1/2&quot;&gt; &lt;a href=&quot;#slide3&quot; className=&quot;btn btn-circle&quot;&gt;❮&lt;/a&gt; &lt;a href=&quot;#slide1&quot; className=&quot;btn btn-circle&quot;&gt;❯&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; } </code></pre> <p>I tried adding the code inside of ImageSlide into App.tsx to see if there was any errors in the code it self. it worked so it seems like the only probably is trying to import ImageSlide into App.tsx.</p>
[ { "answer_id": 74352342, "author": "Ben Wainwright", "author_id": 3104399, "author_profile": "https://Stackoverflow.com/users/3104399", "pm_score": 1, "selected": false, "text": "ImageSlider.tsx" }, { "answer_id": 74352427, "author": "Puneet Chandhok", "author_id": 7384147, "author_profile": "https://Stackoverflow.com/users/7384147", "pm_score": 0, "selected": false, "text": "import React from \"react\";\n\nexport function ImageSlides () {\nreturn ( <div className=\"carousel w-full\">\n <div id=\"slide1\" className=\"carousel-item relative w-full\">\n <img src=\"https://placeimg.com/800/200/arch\" className=\"w-full\" />\n <div className=\"absolute flex justify-between transform -translate-y-1/2 left-5 right-5 top-1/2\">\n <a href=\"#slide4\" className=\"btn btn-circle\">❮</a> \n <a href=\"#slide2\" className=\"btn btn-circle\">❯</a>\n </div>\n </div> \n <div id=\"slide2\" className=\"carousel-item relative w-full\">\n <img src=\"https://placeimg.com/800/200/arch\" className=\"w-full\" />\n <div className=\"absolute flex justify-between transform -translate-y-1/2 left-5 right-5 top-1/2\">\n <a href=\"#slide1\" className=\"btn btn-circle\">❮</a> \n <a href=\"#slide3\" className=\"btn btn-circle\">❯</a>\n </div>\n </div> \n <div id=\"slide3\" className=\"carousel-item relative w-full\">\n <img src=\"https://placeimg.com/800/200/arch\" className=\"w-full\" />\n <div className=\"absolute flex justify-between transform -translate-y-1/2 left-5 right-5 top-1/2\">\n <a href=\"#slide2\" className=\"btn btn-circle\">❮</a> \n <a href=\"#slide4\" className=\"btn btn-circle\">❯</a>\n </div>\n </div> \n <div id=\"slide4\" className=\"carousel-item relative w-full\">\n <img src=\"https://placeimg.com/800/200/arch\" className=\"w-full\" />\n <div className=\"absolute flex justify-between transform -translate-y-1/2 left-5 right-5 top-1/2\">\n <a href=\"#slide3\" className=\"btn btn-circle\">❮</a> \n <a href=\"#slide1\" className=\"btn btn-circle\">❯</a>\n </div>\n </div>\n</div>);\n};" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74352312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16883589/" ]
74,352,319
<p>I have a form with some input with a default value and its hidden. I want to submit its value, together with other inputs to the database using an API, I have tried the following method, but it is not working. Kindly help.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const PostWidget = ({ post }) =&gt; { const [loading, setLoading] = useState(false); const [show, setShow] = useState(false); const [commentInput, setComment] = useState({ post_id: '', commentcontent: '', }); const [errorlist, setError] = useState([]); const handleInput = (e) =&gt; { e.persist(); setComment({ ...commentInput, [e.target.name]: e.target.value }); } const submitComment = (e) =&gt; { e.preventDefault(); setLoading(true); const data = { post_id: commentInput.post_id, commentcontent: commentInput.commentcontent, }; axios.post(`/api/store-comment`, data).then((res) =&gt; { if (res.data.status === 200) { toast.success(res.data.message, "success"); setLoading(false); } else if (res.data.status === 422) { toast.error("Your Comment is too Long", "", "error"); setError(res.data.errors); setLoading(false); } }); } return ( &lt;div className="form-group boxed"&gt; &lt;div className="input-wrapper"&gt; &lt;form onSubmit={submitComment}&gt; &lt;input defaultValue={post.postid} hidden /&gt; &lt;input type="text" name="commentcontent" className="form-control" onChange={handleInput} value={commentInput.commentcontent} placeholder="Write your Comment" /&gt; &lt;button type="submit" className="send-input"&gt; {loading ? &lt;&gt;&lt;span className="spinner-border spinner-border-sm spinner-comment" role="status" aria-hidden="true"&gt;&lt;/span&gt;&lt;/&gt; : &lt;&gt;&lt;i className="fi fi-rr-arrow-circle-right"&gt;&lt;/i&gt;&lt;/&gt;} &lt;/button&gt; &lt;/form&gt; &lt;/div&gt; ); } export default PostWidget;</code></pre> </div> </div> </p>
[ { "answer_id": 74352434, "author": "MalwareMoon", "author_id": 20241005, "author_profile": "https://Stackoverflow.com/users/20241005", "pm_score": 0, "selected": false, "text": "submitComment" }, { "answer_id": 74352456, "author": "Ioana Tiplea", "author_id": 17595706, "author_profile": "https://Stackoverflow.com/users/17595706", "pm_score": 2, "selected": true, "text": "const data = {\n post_id: post.post_id,\n commentcontent: commentInput.commentcontent,\n};\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74352319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19223350/" ]
74,352,330
<p>I am using Angular 13 and I have an array of objects like this:</p> <pre><code> [{ &quot;name&quot;: &quot;Operating System&quot;, &quot;checkedCount&quot;: 0, &quot;children&quot;: [{ &quot;name&quot;: &quot;Linux&quot;, &quot;value&quot;: &quot;Redhat&quot;, &quot;checked&quot;: true }, { &quot;name&quot;: &quot;Windows&quot;, &quot;value&quot;: &quot;Windows 10&quot; } ] }, { &quot;name&quot;: &quot;Software&quot;, &quot;checkedCount&quot;: 0, &quot;children&quot;: [{ &quot;name&quot;: &quot;Photoshop&quot;, &quot;value&quot;: &quot;PS&quot;, &quot;checked&quot;: true }, { &quot;name&quot;: &quot;Dreamweaver&quot;, &quot;value&quot;: &quot;DW&quot; }, { &quot;name&quot;: &quot;Fireworks&quot;, &quot;value&quot;: &quot;FW&quot;, &quot;checked&quot;: true } ] } ] </code></pre> <p>I would like to loop through the array, check if each object has a <code>children</code> array and it in turn has a <code>checked</code> property which is set to <code>true</code>, then I should update the <code>checkedCount</code> in the parent object. So, result should be like this:</p> <pre><code> [{ &quot;name&quot;: &quot;Operating System&quot;, &quot;checkedCount&quot;: 1, &quot;children&quot;: [{ &quot;name&quot;: &quot;Linux&quot;, &quot;value&quot;: &quot;Redhat&quot;, &quot;checked&quot;: true }, { &quot;name&quot;: &quot;Windows&quot;, &quot;value&quot;: &quot;Windows 10&quot; } ] }, { &quot;name&quot;: &quot;Software&quot;, &quot;checkedCount&quot;: 2, &quot;children&quot;: [{ &quot;name&quot;: &quot;Photoshop&quot;, &quot;value&quot;: &quot;PS&quot;, &quot;checked&quot;: true }, { &quot;name&quot;: &quot;Dreamweaver&quot;, &quot;value&quot;: &quot;DW&quot; }, { &quot;name&quot;: &quot;Fireworks&quot;, &quot;value&quot;: &quot;FW&quot;, &quot;checked&quot;: true } ] } ] </code></pre> <p>I tried to do it this way in angular, but this is in-efficient and results in an error saying <code>this.allFilters[i].children[j]</code> may be undefined. So, looking for an efficient manner to do this.</p> <pre><code> for(let j=0;i&lt;this.allFilters[i].children.length; j++) { if (Object.keys(this.allFilters[i].children[j]).length &gt; 0) { if (Object.prototype.hasOwnProperty.call(this.allFilters[i].children[j], 'checked')) { if(this.allFilters[i].children[j].checked) { this.allFilters[i].checkedCount++; } } } } </code></pre>
[ { "answer_id": 74352575, "author": "caTS", "author_id": 18244921, "author_profile": "https://Stackoverflow.com/users/18244921", "pm_score": 1, "selected": false, "text": "checked" }, { "answer_id": 74352652, "author": "marzelin", "author_id": 5664434, "author_profile": "https://Stackoverflow.com/users/5664434", "pm_score": 0, "selected": false, "text": "filter" }, { "answer_id": 74352662, "author": "Aram", "author_id": 15441878, "author_profile": "https://Stackoverflow.com/users/15441878", "pm_score": 1, "selected": false, "text": "data.forEach((v) => {\n v.children.forEach((child) => {\n if (child.checked) {\n v.checkedCount++;\n }\n });\n});\n" }, { "answer_id": 74352740, "author": "Ahmed Saleh", "author_id": 12320320, "author_profile": "https://Stackoverflow.com/users/12320320", "pm_score": 0, "selected": false, "text": "map" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74352330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/229853/" ]
74,352,339
<p>I want to create multiple filters in Django.</p> <p>The screen shot below explains it.</p> <p><a href="https://i.stack.imgur.com/oJ9v0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oJ9v0.png" alt="enter image description here" /></a></p> <p>The user may opt not to select some criteria.</p> <p>If the user does not select Available from, Available till and Advance then I will get the value as None in views.py. If he does not select Category or Capacity then I will get an empty list otherwise I will get a list of Category or Capacity.</p> <p>The problem arises when there is None or empty list.</p> <p>Although I have written the code and it works fine but I want to know if there is a better way to do it? My code may have problems if the complexity increases.</p> <p>forms.py</p> <pre><code>class RoomForm(forms.Form): ROOM_CATEGORIES = ( ('Regular', 'Regular'), ('Executive', 'Executive'), ('Deluxe', 'Deluxe'), ('King', 'King'), ('Queen', 'Queen'), ) category = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, choices=ROOM_CATEGORIES, ) ROOM_CAPACITY = ( (1, '1'), (2, '2'), (3, '3'), (4, '4'), ) capacity = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, choices=ROOM_CAPACITY, ) class TimeInput(forms.TimeInput): input_type = 'time' default=datetime.time() available_from = forms.TimeField( required=False, widget=TimeInput(), ) available_till = forms.TimeField( required=False, widget=TimeInput(), ) advance = forms.IntegerField( required=False, ) &quot;&quot;&quot;Function to ensure that booking is done for future and check out is after check in&quot;&quot;&quot; def clean(self): cleaned_data = super().clean() available_from = cleaned_data.get(&quot;available_from&quot;) available_till = cleaned_data.get(&quot;available_till&quot;) str_available_from = str(available_from) str_available_till = str(available_till) format = '%H:%M:%S' if str_available_from != 'None': try: datetime.datetime.strptime(str_available_from, format).time() except Exception: raise ValidationError( _('Wrong time entered.'), code='Wrong time entered.', ) if str_available_till != 'None': try: datetime.datetime.strptime(str_available_till, format).time() except Exception: raise ValidationError( _('Wrong time entered.'), code='Wrong time entered.', ) if available_till is not None and available_from is not None: if available_till &lt;= available_from: raise ValidationError( &quot;Available till should be after available from.&quot;, code='Available till after available from' ) </code></pre> <p>views.py</p> <pre><code> if categories == []: categories = ['Regular', 'Executive', 'Deluxe', 'King', 'Queen'] if capacities == []: capacities = [1, 2, 3, 4] if advance is None: advance = 0 if available_from is None and available_till is None: room_list = Room.objects.filter( category__in=categories, capacity__in=capacities, advance__gte=advance ) elif available_from is None: room_list = Room.objects.filter( category__in=categories, available_till__gte=available_till, capacity__in=capacities, advance__gte=advance ) elif available_till is None: room_list = Room.objects.filter( category__in=categories, available_from__lte=available_from, capacity__in=capacities, advance__gte=advance ) else: room_list = Room.objects.filter( category__in=categories, available_from__lte=available_from, available_till__gte=available_till, capacity__in=capacities, advance__gte=advance ) return room_list </code></pre> <p><a href="https://i.stack.imgur.com/RPYnN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RPYnN.png" alt="enter image description here" /></a></p> <p><a href="https://github.com/AnshulGupta22/room_slot_booking" rel="nofollow noreferrer">Link to GitHub repo</a></p> <p>I wrote the code but I think there should be a better way.</p>
[ { "answer_id": 74361224, "author": "haduki", "author_id": 18229792, "author_profile": "https://Stackoverflow.com/users/18229792", "pm_score": 0, "selected": false, "text": "Q objects" }, { "answer_id": 74378124, "author": "JDODER", "author_id": 19716660, "author_profile": "https://Stackoverflow.com/users/19716660", "pm_score": 1, "selected": false, "text": "varName = Room.objects.filter(category__in=categories) | Room.objects.filter(capacity__in=capacities) | Room.objects.filter(capacity__in=capacities)...\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74352339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20443528/" ]
74,352,373
<pre><code>@api_view(['PUT']) def updateRule1(request, id): nums15 = 'OK' json_data = json.loads(request.body) # print(json_data) con = None cur = None try: con = cx_Oracle.connect('&lt;server connection details&gt;') cur = con.cursor() except cx_Oracle.DatabaseError as e: print(&quot;Problem establishing connection with Oracle DB&quot;, e) q = &quot;INSERT INTO XXMSE.RE_PREDICATE (RULE_ID, PREDICATE_ID, INPUT_VALUE_ID1, MATHEMATICAL_VALUE, INPUT_VALUE_ID2, BOOLEAN_OPERATOR) VALUES ('1','2','2000000','equals','30000000','None')&quot; print(q) sql5 = cur.execute(q) cur.execute(sql5) con.commit() if cur: cur.close() if con: con.close() return Response(nums15) </code></pre> <p>DB screenshot |ID |Idx|Value_1 |Operator|Value_2 |Boolean | |---|---|----------|--------|-----------|--------| |1 |1 |1 |equals |2 |AND | |1 |2 |2000000 |equals |30000000 |None |<br /> |1 |2 |2000000 |equals |30000000 |None |</p> <p>I see that there are 2 rows inserted into the DB. Django version is 4.1.1</p> <p>What would be the reason for duplicate rows? Appreciate your help</p> <p>I used breakpoint() and made sure that api is called getting once.There is no duplicate entries in the backend.</p>
[ { "answer_id": 74352415, "author": "Lucas Grugru", "author_id": 16984466, "author_profile": "https://Stackoverflow.com/users/16984466", "pm_score": 2, "selected": true, "text": "cur.execute(...)" }, { "answer_id": 74353585, "author": "sghaier", "author_id": 3289923, "author_profile": "https://Stackoverflow.com/users/3289923", "pm_score": 0, "selected": false, "text": "sql5 = cur.execute(q)\ncur.execute(sql5)\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74352373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14335702/" ]
74,352,397
<p>I'm quite new to bash scripting. I have a script where I want to extract part of the value of a particular line in a separate config file and then use that value as a variable in the script. For example:</p> <p>Line 75 in a file named config.cfg</p> <p>&quot;ssl_cert_location=/etc/ssl/certs/thecert.cer&quot;</p> <p>I want just the value at the end of &quot;thecert.cer&quot; to then use in the script. I've tried awk and various uses of grep but I can't quite get just the name of the certificate.</p> <p>Any help would be appreciated. Thanks</p> <p>These are some examples of the commands I ran:</p> <pre><code>awk -F &quot;/&quot; '{print $4}' config.cfg grep -o *.cer config.cfg </code></pre> <p>Is this possible to extract the value on that line and then edit the output so it just contains the name of the certificate file?</p>
[ { "answer_id": 74352415, "author": "Lucas Grugru", "author_id": 16984466, "author_profile": "https://Stackoverflow.com/users/16984466", "pm_score": 2, "selected": true, "text": "cur.execute(...)" }, { "answer_id": 74353585, "author": "sghaier", "author_id": 3289923, "author_profile": "https://Stackoverflow.com/users/3289923", "pm_score": 0, "selected": false, "text": "sql5 = cur.execute(q)\ncur.execute(sql5)\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74352397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20443717/" ]
74,352,413
<p>Had a question..</p> <pre><code>| a_id | name | r_id | message | date _____________________________________________ | 1 | bob | 77 | bob here | 1-jan | 1 | bob | 77 | bob here again | 2-jan | 2 | jack | 77 | jack here. | 2-jan | 1 | bob | 79 | in another room| 3-feb | 3 | gill | 79 | gill here | 4-feb </code></pre> <p>These are basically accounts (<code>a_id)</code> chatting inside different rooms (<code>r_id</code>)</p> <p>I'm trying to find the last chat message for every room that <code>jack a_id = 2</code> is chatting in. What i've tried so far is using <code>distinct on (r_id) ... ORDER BY r_id, date DESC</code>.</p> <p>But this incorrectly gives me the last message in every room instead of only giving the last message in everyroom that <strong><em>jack</em></strong> belongs to.</p> <pre><code>| 2 | jack | 77 | jack here. | 2-jan | 3 | gill | 79 | gill here | 4-feb </code></pre> <p>Is this a <code>partition</code> problem instead distinct on?</p>
[ { "answer_id": 74352415, "author": "Lucas Grugru", "author_id": 16984466, "author_profile": "https://Stackoverflow.com/users/16984466", "pm_score": 2, "selected": true, "text": "cur.execute(...)" }, { "answer_id": 74353585, "author": "sghaier", "author_id": 3289923, "author_profile": "https://Stackoverflow.com/users/3289923", "pm_score": 0, "selected": false, "text": "sql5 = cur.execute(q)\ncur.execute(sql5)\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74352413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/433073/" ]
74,352,416
<p>I am trying to create new dataframe out of the dictionary which includes lists.</p> <p>It looks like something like that:</p> <pre><code>{'prices': [[1574121600000, 1.000650588888066], [1574208000000, 0.9954110116644869]... </code></pre> <p>Those are UNIX date and price of stablecoins, however the columns are not named properly as it is all under 'prices' key.</p> <p>However how could I create a new df which would include 2 columns (Date, Price) using values from this dictionary?</p> <p>My goal is to get something like this:</p> <pre><code>| Date | Price | | 15741216000000 | 1.000650588888066 | | 15742080000000 | 0.9954110116644869 | </code></pre>
[ { "answer_id": 74352415, "author": "Lucas Grugru", "author_id": 16984466, "author_profile": "https://Stackoverflow.com/users/16984466", "pm_score": 2, "selected": true, "text": "cur.execute(...)" }, { "answer_id": 74353585, "author": "sghaier", "author_id": 3289923, "author_profile": "https://Stackoverflow.com/users/3289923", "pm_score": 0, "selected": false, "text": "sql5 = cur.execute(q)\ncur.execute(sql5)\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74352416", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20443650/" ]
74,352,433
<p>number output the square of the difference of the numbers. For example, if the given number is 352, then it is the maximum number made from the digits of this number 532 and the minimum number is 235. The square of their difference is (532-235)(532-235) =297*297 = 88209.</p> <p>The code is working but I need this code abbreviation :)</p> <pre><code>l1 = [] l2 = [] number = int(input(&quot;Enter a 3-Digit Natural Number:&quot;)) if 99&lt;number&lt;1000: one = number % 10 two = number // 10 % 10 three = number // 100 % 10 l1.extend([one,two,three]) l2.extend([one,two,three]) l1.sort() l2.sort(reverse=True) Big = l1[0]*100 + l1[1]*10 + l1[2] Small = l2[0]*100 + l2[1]*10 + l2[2] Answer = (Big-Small)**2 print(Answer) else: print(&quot;Restart the program&quot;) </code></pre>
[ { "answer_id": 74352623, "author": "zvone", "author_id": 389289, "author_profile": "https://Stackoverflow.com/users/389289", "pm_score": 2, "selected": false, "text": "digits = str(number)\nordered = sorted(digits)\nsmall = int(''.join(ordered))\nbig = int(''.join(ordered[::-1]))\n" }, { "answer_id": 74352922, "author": "Shahnazi2002", "author_id": 18139991, "author_profile": "https://Stackoverflow.com/users/18139991", "pm_score": 0, "selected": false, "text": "n = input(\"Enter a 3-digit natural number: \")\nif 99 < int(n) <= 999:\n min = list(n)\n min.sort()\n max = list(n)\n max.sort(reverse=True)\n print((int(\"\".join(max))-int(\"\".join(min)))**2)\nelse: print(\"Something went wrong!\")\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74352433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17962912/" ]
74,352,439
<p>I want to create an QrCode using IronBarCode, and then save it as a Stream or Byte[]. However both methods expect the file to be saved prior to creation:</p> <pre><code> var absolute = Request.Scheme + &quot;://&quot; + Request.Host + url; var qrcode = IronBarCode.QRCodeWriter.CreateQrCode(absolute); qrcode.AddAnnotationTextAboveBarcode(device.Name); qrcode.AddBarcodeValueTextBelowBarcode(absolute); var f = qrcode.ToJpegStream(); var y = qrcode.ToJpegBinaryData(); </code></pre> <p>ToJpegStream() and ToJpegBinaryData expects the absolute string to be an actual file path. I want to create a QrCode and save it as a Byte[] or Stream, however the error thrown is &quot;The filename, directory name, or volume label syntax is incorrect.&quot;</p>
[ { "answer_id": 74353057, "author": "user09938", "author_id": 10024425, "author_profile": "https://Stackoverflow.com/users/10024425", "pm_score": 0, "selected": false, "text": "Windows Forms App (.NET Framework)" }, { "answer_id": 74355626, "author": "Chaknith Bin", "author_id": 20413907, "author_profile": "https://Stackoverflow.com/users/20413907", "pm_score": 1, "selected": false, "text": "AddBarcodeValueTextBelowBarcode" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74352439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1469836/" ]
74,352,442
<p>I wonder how the module &quot;pickle&quot; save and load objects. I saved a file with a dataframe object on the disk,</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import pickle df = pd.read_excel(r&quot;.\test.xlsx&quot;) with open(&quot;o.pkl&quot;, &quot;wb&quot;) as file: pickle.dump(df, file) </code></pre> <p>then I uninstalled pandas and tried to load the object dataframe from file, but i get error &quot;Exception has occurred: ModuleNotFoundError No module named 'pandas'&quot;:</p> <pre class="lang-py prettyprint-override"><code>import pickle with open(&quot;o.pkl&quot;, &quot;rb&quot;) as file: e = pickle.load(file) </code></pre> <p>my question is, does the pickle module somehow use pandas when loading an df? If so how is it done?</p>
[ { "answer_id": 74353057, "author": "user09938", "author_id": 10024425, "author_profile": "https://Stackoverflow.com/users/10024425", "pm_score": 0, "selected": false, "text": "Windows Forms App (.NET Framework)" }, { "answer_id": 74355626, "author": "Chaknith Bin", "author_id": 20413907, "author_profile": "https://Stackoverflow.com/users/20413907", "pm_score": 1, "selected": false, "text": "AddBarcodeValueTextBelowBarcode" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74352442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20004128/" ]
74,352,453
<p>I'm trying to use selenium webdriver in python to click in all the thanks button on a page, but the problem is that my script is only clicking on the first button.</p> <p>Below is the part of code that I´m using:</p> <pre><code>counter = 0 while counter &lt; 10: wd.find_element_by_xpath('//*[contains(@href,&quot;post_thanks.php?do=&quot;)]').click() print (&quot;click&quot;) counter += 1 time.sleep(2) wd.close() </code></pre> <p>The script is working, it's connecting to the website, loading the target page, but only clicks at the first thanks button.</p> <p>What can be made to get all the buttons clicked?</p>
[ { "answer_id": 74353057, "author": "user09938", "author_id": 10024425, "author_profile": "https://Stackoverflow.com/users/10024425", "pm_score": 0, "selected": false, "text": "Windows Forms App (.NET Framework)" }, { "answer_id": 74355626, "author": "Chaknith Bin", "author_id": 20413907, "author_profile": "https://Stackoverflow.com/users/20413907", "pm_score": 1, "selected": false, "text": "AddBarcodeValueTextBelowBarcode" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74352453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6484462/" ]
74,352,466
<p>Hello StackOverflow Community Members,</p> <p>I'm looking for some help 'git clone --recurse-submodules'ing a github repo using an ssh key, without being asked for username and password.</p> <p>I have no issues cloning repos using a properly setup ssh key:</p> <pre><code>git clone git@github.com:{company_name}/{main_repo}.git </code></pre> <p>Everything works as expected here and project files are retrieved without asking me for a username and password.</p> <p>This is not the case however when I try to automatically initialize and update each submodule in the repository (per <a href="https://git-scm.com/book/en/v2/Git-Tools-Submodules#:%7E:text=Cloning%20a%20Project%20with%20Submodules&amp;text=If%20you%20pass%20%2D%2Drecurse,the%20repository%20have%20submodules%20themselves." rel="nofollow noreferrer">instructions</a>):</p> <pre><code>git clone --recurse-submodules git@github.com:{company_name}/{main_repo}.git </code></pre> <p>When I run this I am asked for a username and password before any of the submodules are retrieved. This is highly undesired.</p> <p>Any ideas on why I'm being asked for a username and password when I run with --recurse-submodules? I have permission to successfully clone the submodule repos individually (without inputing username and password):</p> <pre><code>git clone git@github.com:{company_name}/{submodule_repo}.git </code></pre> <p>Your brilliant assistance is greatly appreciated!</p>
[ { "answer_id": 74352864, "author": "phd", "author_id": 7976758, "author_profile": "https://Stackoverflow.com/users/7976758", "pm_score": 1, "selected": false, "text": ".gitmodules" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74352466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3120582/" ]
74,352,475
<p>In a Rails app, for business reasons, I don't want to leak how many objects I have or the difference between objects count in a period of time.</p> <p>I think global unique ids are an overkill in this case, as I just need <em>local</em> unique ids for each table. As ids in a default Rails + Potgresql app are already bigints, I thought about generating very large (but not <em>astronomically</em> large) integers to use as ids:</p> <pre><code>class ApplicationRecord &lt; ActiveRecord::Base primary_abstract_class before_create :set_large_random_id private def set_large_random_id self.id = rand(1..999_999_999_999) end end </code></pre> <p>(I am OK my app failing because of a unique id collision once a trillionth).</p> <p>Apart loosing the ordering given by sequential ids, is there any other problem or consideration I need to take into account by using large random ids?</p>
[ { "answer_id": 74355773, "author": "Sadman Ahmed", "author_id": 6371134, "author_profile": "https://Stackoverflow.com/users/6371134", "pm_score": 1, "selected": false, "text": " Role.first\n Role Load (0.4ms) SELECT \"roles\".* FROM \"roles\" ORDER BY \"roles\".\"id\" ASC LIMIT $1 [[\"LIMIT\", 1]]\n => #<Role:0x00007f5834fa8910 \nid: \"0d8acf6e-63d4-4845-a804-c84e8debb501\", \nname: \"business_analyst\", \ncreated_at: Tue, 08 Nov 2022 10:46:47.321147000 +06 +06:00, updated_at: Tue, 08 Nov 2022 10:46:47.321147000 +06 +06:00> \n\n" }, { "answer_id": 74383396, "author": "Mike A.", "author_id": 573505, "author_profile": "https://Stackoverflow.com/users/573505", "pm_score": 3, "selected": true, "text": "created_at" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74352475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/182172/" ]
74,352,478
<p>I have a student dataset that includes responses to questions as right or wrong. There is also a time variable in seconds. I would like to create a time flag to record number of correct and incorrect responses by <code>1 minute</code> <code>2 minute</code> and <code>3 minute</code> thresholds. Here is a sample dataset.</p> <pre><code>df &lt;- data.frame(id = c(1,2,3,4,5), gender = c(&quot;m&quot;,&quot;f&quot;,&quot;m&quot;,&quot;f&quot;,&quot;m&quot;), age = c(11,12,12,13,14), i1 = c(1,0,NA,1,0), i2 = c(0,1,0,&quot;1]&quot;,1), i3 = c(&quot;1]&quot;,1,&quot;1]&quot;,0,&quot;0]&quot;), i4 = c(0,&quot;0]&quot;,1,1,0), i5 = c(1,1,NA,&quot;0]&quot;,&quot;1]&quot;), i6 = c(0,0,&quot;0]&quot;,1,1), i7 = c(1,&quot;1]&quot;,1,0,0), i8 = c(0,0,0,&quot;1]&quot;,&quot;1]&quot;), i9 = c(1,1,1,0,NA), time = c(115,138,148,195, 225)) &gt; df id gender age i1 i2 i3 i4 i5 i6 i7 i8 i9 time 1 1 m 11 1 0 1] 0 1 0 1 0 1 115 2 2 f 12 0 1 1 0] 1 0 1] 0 1 138 3 3 m 12 NA 0 1] 1 &lt;NA&gt; 0] 1 0 1 148 4 4 f 13 1 1] 0 1 0] 1 0 1] 0 195 5 5 m 14 0 1 0] 0 1] 1 0 1] NA 225 </code></pre> <p>The minute thresholds are represented by a <code>]</code> sign at the right side of the score.</p> <p>For example for the <code>id = 3</code>, the <code>1-minute</code> threshold is at item <code>i3</code> , the <code>2-minute</code> threshold is at item <code>i6</code>. Each student might have different time thresholds.</p> <p>I need to create flagging variables to count number of correct and incorrect responses by the <code>1-min</code> <code>2-min</code> and <code>3-min</code> thresholds.</p> <p>How can I achieve the desired dataset as below.</p> <pre><code>&gt; df1 id gender age i1 i2 i3 i4 i5 i6 i7 i8 i9 time one_true one_false two_true two_false three_true three_false 1 1 m 11 1 0 1] 0 1 0 1 0 1 115 2 1 NA NA NA NA 2 2 f 12 0 1 1 0] 1 0 1] 0 1 138 2 2 4 3 NA NA 3 3 m 12 NA 0 1] 1 &lt;NA&gt; 0] 1 0 1 148 1 1 2 2 NA NA 4 4 f 13 1 1] 0 1 0] 1 0 1] 0 195 2 0 3 2 5 3 5 5 m 14 0 1 0] 0 1] 1 0 1] NA 225 1 2 2 3 4 4 </code></pre>
[ { "answer_id": 74352754, "author": "onyambu", "author_id": 8380272, "author_profile": "https://Stackoverflow.com/users/8380272", "pm_score": 3, "selected": true, "text": "df %>%\n pivot_longer(i1:i9,values_transform = as.character) %>%\n group_by(id)%>%\n mutate(vs = rev(cumsum(replace_na(str_detect(rev(value),']'),0))))%>%\n filter(vs > 0)%>%\n mutate(vs = max(vs) - vs + 1)%>%\n group_by(vs,.add = TRUE)%>%\n summarise(true = sum(str_detect(value, '1'), na.rm = TRUE),\n false = sum(str_detect(value, '0'), na.rm = TRUE),\n .groups = \"drop_last\")%>%\n mutate(across(c(true, false),cumsum)) %>%\n pivot_wider(id, names_from = vs, values_from = c(true, false))\n\n# A tibble: 5 x 7\n# Groups: id [5]\n id true_1 true_2 true_3 false_1 false_2 false_3\n <dbl> <int> <int> <int> <int> <int> <int>\n1 1 2 NA NA 1 NA NA\n2 2 2 4 NA 2 3 NA\n3 3 1 2 NA 1 2 NA\n4 4 2 3 5 0 2 3\n5 5 1 2 4 2 3 4\n" }, { "answer_id": 74353044, "author": "onyambu", "author_id": 8380272, "author_profile": "https://Stackoverflow.com/users/8380272", "pm_score": 1, "selected": false, "text": "fun <- function(x){\n a <- diff(c(0,which(grepl(\"]\", x))))\n f_sum <- function(x,y) sum(na.omit(grepl(x,y)))\n fn <- function(x) c(true = f_sum('1',x), false = f_sum('0',x))\n y <- tapply(x[seq(sum(a))], rep(seq_along(a),a), fn)\n s <- do.call(rbind, Reduce(\"+\", y, accumulate = TRUE))\n nms <- do.call(paste, c(sep='_',expand.grid(colnames(s), seq(nrow(s)))))\n setNames(c(t(s)), nms)\n}\n\nfun2 <- function(x){\n ln <- lengths(x)\n nms <- names(x[[which.max(ln)]])\n do.call(rbind, lapply(x, function(x)setNames(`length<-`(x,max(ln)),nms)))\n}\n\n\nfun2(apply(df[4:12],1,fun))\n true_1 false_1 true_2 false_2 true_3 false_3\n[1,] 2 1 NA NA NA NA\n[2,] 2 2 4 3 NA NA\n[3,] 1 1 2 2 NA NA\n[4,] 2 0 3 2 5 3\n[5,] 1 2 2 3 4 4\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74352478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5933306/" ]
74,352,506
<p>I am trying to find the correlation between two columns (sunshine_in_hours and AgeGroup_30_to_34) from a combined dataset in R. However, every time I try to run the cor() function, I just end up getting this error:</p> <pre><code>Error in pmatch(use, c(&quot;all.obs&quot;, &quot;complete.obs&quot;, &quot;pairwise.complete.obs&quot;, : object 'AgeGroup_30_to_34' not found </code></pre> <p>Here's the dput(head) snipit:</p> <pre><code>structure(list(Date = structure(c(18659, 18660, 18661, 18663, 18665, 18666, 18667, 18668, 18669, 18670, 18671, 18673, 18674, 18675, 18676, 18677, 18678, 18679, 18680, 18681, 18682, 18683, 18684, 18685, 18686, 18687, 18688, 18689, 18690, 18691), class = &quot;Date&quot;), Year = c(2021, 2021, 2021, 2021, 2021, 2021, 2021, 2021, 2021, 2021, 2021, 2021, 2021, 2021, 2021, 2021, 2021, 2021, 2021, 2021, 2021, 2021, 2021, 2021, 2021, 2021, 2021, 2021, 2021, 2021), Month = c(2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3), AgeGroup_30_to_34 = c(0, 0, 0, 2, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 2, 0, 0, 1, 2, 0, 3, 0, 0, 0), Sunshine_in_hours = c(1.6, 3.4, 13.1, 8.9, 2, 1.7, 12.7, 11.6, 5.5, 5.6, 4.9, 9.2, 8.3, 11.9, 12.4, 12.4, 5.9, 0, 6.3, 8.5, 9.9, 8.7, 6.3, 1, 9.2, 6.3, 1.4, 2.1, 2.6, 3.6), City = c(&quot;Melbourne&quot;, &quot;Melbourne&quot;, &quot;Melbourne&quot;, &quot;Melbourne&quot;, &quot;Melbourne&quot;, &quot;Melbourne&quot;, &quot;Melbourne&quot;, &quot;Melbourne&quot;, &quot;Melbourne&quot;, &quot;Melbourne&quot;, &quot;Melbourne&quot;, &quot;Melbourne&quot;, &quot;Melbourne&quot;, &quot;Melbourne&quot;, &quot;Melbourne&quot;, &quot;Melbourne&quot;, &quot;Melbourne&quot;, &quot;Melbourne&quot;, &quot;Melbourne&quot;, &quot;Melbourne&quot;, &quot;Melbourne&quot;, &quot;Melbourne&quot;, &quot;Melbourne&quot;, &quot;Melbourne&quot;, &quot;Melbourne&quot;, &quot;Melbourne&quot;, &quot;Melbourne&quot;, &quot;Melbourne&quot;, &quot;Melbourne&quot;, &quot;Melbourne&quot;)), row.names = c(NA, -30L), class = c(&quot;tbl_df&quot;, &quot;tbl&quot;, &quot;data.frame&quot;)) </code></pre> <p>I tried to run the code:</p> <pre><code>Combined &lt;- inner_join(covidS, weatherS, by = 'Date')%&gt;% mutate(Date = mdy(Date), Year = year(Date), Month = month(Date), Day = day(Date))%&gt;% select(Date, Year, Month, AgeGroup_30_to_34, Sunshine_in_hours, City)%&gt;% filter(City == 'Melbourne')%&gt;% cor(Sunshine_in_hours, AgeGroup_30_to_34 ) </code></pre> <p>I've tried looking up tutorials on how to do this, however I keep running into a wall. Any help will be appreciated.</p>
[ { "answer_id": 74352629, "author": "Juan C", "author_id": 9462829, "author_profile": "https://Stackoverflow.com/users/9462829", "pm_score": 2, "selected": true, "text": "cor" }, { "answer_id": 74352634, "author": "stefan", "author_id": 12993861, "author_profile": "https://Stackoverflow.com/users/12993861", "pm_score": 0, "selected": false, "text": "magrittr" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74352506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20352311/" ]
74,352,507
<p>In the debug left side panel, VS Code does not display the call stack, neither the variables and watch (picture below).</p> <p><em>Someone knows how to display them ?</em></p> <p><a href="https://i.stack.imgur.com/oxpo2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oxpo2.png" alt=" vs code not display debug call stack and variables" /></a></p>
[ { "answer_id": 74352546, "author": "JRiggles", "author_id": 8512262, "author_profile": "https://Stackoverflow.com/users/8512262", "pm_score": 2, "selected": false, "text": "..." }, { "answer_id": 74352641, "author": "quamrana", "author_id": 4834, "author_profile": "https://Stackoverflow.com/users/4834", "pm_score": 2, "selected": true, "text": "View/Open View ..." } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74352507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5713806/" ]
74,352,530
<p>I'm sure this question has been asked before, but I can't seem to find something as simple as what I'm trying to do. Essentially, I just want to make sure the code <em>triggers</em> each parameter, calling any functions that may be sent as inputs. My biggest worry here is that optimizations may remove some of the calls, changing the result.</p> <p>I <strong>was</strong> using the following syntax. It seemed to trigger the function calls the way I want, but it has the strange result of triggering the arguments in reverse order - the last argument is called first, and the first argument is called last:</p> <pre><code>template &lt;typename... PARMS&gt; uint PARMS_COUNT(PARMS&amp;&amp; ... parms) { return static_cast&lt;uint&gt;( sizeof...(parms) ); } </code></pre> <p>This was my first guess as to how to do the same thing (<em>edit: this does not change the order - it still happens in reverse, because the order is being determined by the function parameter evaluation, rather than what order the function uses them in</em>):</p> <pre><code>template &lt;typename FIRST&gt; constexpr uint PARMS_EXPAND(FIRST &amp;&amp;first) { return static_cast&lt;uint&gt;( sizeof(first) &gt; 0 ? 1 : 0 ); } template &lt;typename FIRST,typename... PARMS&gt; constexpr uint PARMS_EXPAND(FIRST &amp;&amp;first,PARMS&amp;&amp; ... parms) { return static_cast&lt;uint&gt;( sizeof(first) &gt; 0 ? 1 : 0 ) + PARMS_EXPAND( std::forward&lt;PARMS&gt;(parms)... ); } </code></pre> <p>I tested this in a few places, but then realized that regardless of how much testing I do, I'll never know if this is a safe way to do it. Is there a standard or well known method to pull this logic off? Or even better, some built in system to iterate over the arguments and &quot;access them&quot; in the correct order?</p> <p>To better explain why I would want to trigger code like this, consider a function that can add new objects to a parent:</p> <pre><code>void AddObject(/*SINGLE UNKNOWN INPUT*/) { ... } template &lt;typename... PARMS&gt; AddObjects(PARMS&amp;&amp; ... parms) { PARAMS_EXPAND( AddObject(parms)... ); } </code></pre>
[ { "answer_id": 74352546, "author": "JRiggles", "author_id": 8512262, "author_profile": "https://Stackoverflow.com/users/8512262", "pm_score": 2, "selected": false, "text": "..." }, { "answer_id": 74352641, "author": "quamrana", "author_id": 4834, "author_profile": "https://Stackoverflow.com/users/4834", "pm_score": 2, "selected": true, "text": "View/Open View ..." } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74352530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12071685/" ]
74,352,551
<p>Hello Im not the best when it comes to using ejs so apologies if this is a stupid question. Im having a really difficult time figuring out why the html after my EJS data is not displaying, once I start my server. Im not sure if missing something after the ejs or if im completly using it incorrectly, Any help would be much appreciated.</p> <p>Below you can find my code</p> <pre><code> &lt;!-- Movie Section --&gt; &lt;section class=&quot;movie-section-container&quot;&gt; &lt;div class=&quot;category-banner&quot;&gt; &lt;h1 class=&quot;category-name&quot;&gt;POPULAR&lt;/h1&gt; &lt;/div&gt; &lt;div class=&quot;movies-container&quot;&gt; &lt;% movieData.items.forEach(movie=&gt; {%&gt; &lt;div class=&quot;movie-card-filter&quot;&gt; &lt;div class=&quot;movie-card&quot;&gt; &lt;span class=&quot;rating&quot;&gt; &lt;%=movie.imDbRating%&gt;&lt;i class=&quot;fa-solid fa-star&quot;&gt;&lt;/i&gt; &lt;/span&gt; &lt;div class=&quot;poster-container&quot;&gt; &lt;img src=&lt;%=movie.image%&gt; alt=&lt;%=movie.fullTitle%&gt;&gt; &lt;/div&gt; &lt;div class=&quot;movie-info&quot;&gt; &lt;h5 class=&quot;movie-name&quot;&gt; &lt;%=movie.title%&gt; &lt;/h5&gt; &lt;div class=&quot;details&quot;&gt; &lt;div class=&quot;year-date&quot;&gt; &lt;span&gt;&lt;span class=&quot;year&quot;&gt; &lt;%=movie.year%&gt; &lt;/span&gt;.&lt;span class=&quot;runtime&quot;&gt;127 min&lt;/span&gt;&lt;/span&gt; &lt;/div&gt; &lt;div class=&quot;platform&quot;&gt; &lt;span&gt;Movie&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;%})%&gt; &lt;!-- Movie Info Overlay --&gt; &lt;section class=&quot;movie-overlay&quot;&gt; &lt;div class=&quot;movie-details-container&quot;&gt; &lt;div class=&quot;details-btns&quot;&gt; &lt;a href=&quot;#&quot; class=&quot;official-page&quot;&gt;OFFICIAL PAGE&lt;/a&gt; &lt;button class=&quot;close-btn&quot;&gt; &lt;i class=&quot;fa-solid fa-circle-xmark&quot;&gt;&lt;/i&gt; &lt;/button&gt; &lt;/div&gt; &lt;div class=&quot;movie-details&quot;&gt; &lt;div class=&quot;movie-poster&quot;&gt; &lt;img src=&quot;https://image.tmdb.org/t/p/w500/AeyiuQUUs78bPkz18FY3AzNFF8b.jpg&quot; alt=&quot;movie-poster&quot;&gt; &lt;/div&gt; &lt;div class=&quot;info&quot;&gt; &lt;h2 class=&quot;movie-info-name&quot;&gt;Fullmetal Alchemist: The Final Alchemy&lt;/h2&gt; &lt;h4 class=&quot;movie-info-release-date&quot;&gt;Release date: 2022-06-24&lt;/h4&gt; &lt;div class=&quot;movie-info-ratings&quot;&gt; &lt;span&gt;rating: 6.3 &lt;i class=&quot;fa-solid fa-star&quot;&gt;&lt;/i&gt;&lt;/span&gt; &lt;span class=&quot;movie-info-votes&quot;&gt;all votes: 109&lt;/span&gt; &lt;/div&gt; &lt;div class=&quot;movie-info-genre&quot;&gt;Action&lt;/div&gt; &lt;div class=&quot;movie-info-plot&quot;&gt; &lt;h4&gt;Plot: The Elric brothers' long and winding journey comes to a close in this epic finale, where they must face off against an unworldly, nationwide threat.&lt;/h4&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;trailer&quot;&gt; &lt;div class=&quot;line&quot;&gt;&lt;/div&gt; &lt;h3 class=&quot;trailer-title&quot;&gt;Trailer:&lt;/h3&gt; &lt;iframe src=&quot;https://www.youtube.com/embed/cqj4u6eyDq8&quot; title=&quot;YouTube video player&quot; frameborder=&quot;0&quot; allow=&quot;accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture&quot; allowfullscreen&gt;&lt;/iframe&gt; </code></pre>
[ { "answer_id": 74362018, "author": "silent Coder", "author_id": 19760762, "author_profile": "https://Stackoverflow.com/users/19760762", "pm_score": 0, "selected": false, "text": "<%- include(\"header\") -%> // it should contain content upper part.\n\n<%- include(\"footer\") -%> // it should contain content lower part.\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74352551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16597057/" ]
74,352,617
<p>I have the below script and I am trying to access <code>logtime</code> variable when calling the function as userA but the <code>$logtime</code> inside the function is not getting the value. This works when I am not switching the user.</p> <pre><code>logtime=`date +&quot;%Y-%m-%d_%H%M%S&quot;` runcommand() { echo &quot; Log time is $logtime&quot; } export -f runcommand su userA -c &quot;bash -c runcommand &gt;&gt; compile-$logtime.txt&quot; </code></pre> <p><code>$logtime</code> is not getting assigned inside the function when called as userA</p> <pre><code>cat compile-2022-11-07_121225.txt Log time is </code></pre>
[ { "answer_id": 74352707, "author": "Charles Duffy", "author_id": 14122, "author_profile": "https://Stackoverflow.com/users/14122", "pm_score": 2, "selected": false, "text": "declare -f funcname" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74352617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5875760/" ]
74,352,694
<p>I want to create a simple pyspark dataframe with 1 column that is JSON. I created the schema for the <code>groups</code> column and created 1 row.</p> <pre><code>schema = T.StructType([ T.StructField( 'groups', T.ArrayType( T.StructType([ T.StructField(&quot;types&quot;, T.ArrayType(T.StringType(), False)), T.StructField(&quot;label&quot;, T.StringType()) ]), ) ) ]) groups_rows = [{ &quot;groups&quot;: [ { &quot;types&quot;: [&quot;baseball&quot;, &quot;basketball&quot;], &quot;label&quot;: &quot;Label 1&quot; }, { &quot;types&quot;: [&quot;football&quot;], &quot;label&quot;: &quot;Label 2&quot; } ] }] data = [groups_rows] sections_df = spark.createDataFrame(data=data, schema=schema) </code></pre> <p>When I initialize the dataframe I get a type error:</p> <pre><code>TypeError: field groups: ArrayType(StructType(List(StructField(types,ArrayType(StringType,false),true),StructField(label,StringType,true))),true) can not accept object {'groups': [{'types': ['baseball', 'basketball'], 'label': 'Label 1'}, {'types': ['football'], 'label': 'Label 2'}]} in type &lt;class 'dict'&gt; </code></pre> <p>What is the cause of this error? What should I be doing differently in terms of setting up this dataframe? Should I use a <code>MapType</code>?</p> <h3>Update:</h3> <p>I need that JSON list of the groups so it cant be separate rows. Every row needs that groups JSON list. What about converting it to a JSON string, making the groups col via withColumn(&quot;groups&quot;, groups_json_str) and doing the conversion with from_json? I tried doing it this but I was getting schema errors ..</p> <pre><code> groups = [ { &quot;recTypes&quot;: [&quot;readinghistory&quot;, &quot;popular&quot;], &quot;sectionLabel&quot;: &quot;Reader favorites you missed&quot; }, { &quot;recTypes&quot;: [&quot;contentpacks&quot;], &quot;sectionLabel&quot;: &quot;Based on your interests&quot; } ] groups_json = json.dumps(groups) groups_schema= T.ArrayType( T.MapType([ T.StructField(&quot;types&quot;, T.ArrayType(T.StringType(), False)), T.StructField(&quot;label&quot;, T.StringType()) ]) ) </code></pre> <pre><code>df.withColumn(&quot;groups&quot;, F.lit(groups_json) .withColumn(&quot;groups&quot;, F.to_json(F.col(&quot;sections&quot;), groups_schema)) </code></pre> <p>Error:</p> <pre><code>AttributeError: 'ArrayType' object has no attribute 'items' </code></pre>
[ { "answer_id": 74353250, "author": "wwnde", "author_id": 8986975, "author_profile": "https://Stackoverflow.com/users/8986975", "pm_score": 0, "selected": false, "text": "df = spark.read.json(sc.parallelize(groups_rows)).na.fill('') \ndf.printSchema()\n\nroot\n |-- groups: array (nullable = true)\n | |-- element: struct (containsNull = true)\n | | |-- label: string (nullable = true)\n | | |-- types: array (nullable = true)\n | | | |-- element: string (containsNull = true)\n" }, { "answer_id": 74353273, "author": "Zafar", "author_id": 4373061, "author_profile": "https://Stackoverflow.com/users/4373061", "pm_score": 1, "selected": false, "text": "from pyspark.sql import types as T\n\nschema = T.StructType([\n T.StructField('groups', \n T.ArrayType(\n T.StructType([\n T.StructField('label', T.StringType(), True), \n T.StructField('types', \n T.ArrayType(T.StringType(), True),\n True)\n ]), True), \n True)\n])\n\ngroups_rows = [{\n \"groups\": [\n {\n \"types\": [\"baseball\", \"basketball\"],\n \"label\": \"Label 1\"\n },\n {\n \"types\": [\"football\"],\n \"label\": \"Label 2\"\n }\n ]\n}]\n\n\ndata = groups_rows\n\nsections_df = spark.createDataFrame(data=data, schema=schema)\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74352694", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5508854/" ]
74,352,822
<p>I have following problem. I just can't figure out how to <a href="https://docs.walletconnect.com/2.0/kotlin/sign/wallet-usage" rel="nofollow noreferrer">initialize WalletConnect</a> and connect to Metamask on Android. I always get following exception.</p> <pre><code>java.lang.NoSuchMethodError: No interface method getInitializationErrorsFlow()Lkotlinx/coroutines/flow/Flow; in class Lcom/walletconnect/android/internal/common/model/JsonRpcInteractorInterface; </code></pre> <p>My code looks as follows:</p> <pre><code> val projectId = &quot;15f2b4ae8bb12dsd3d267ce6441d5a9d&quot; // I got the Project ID from https://cloud.walletconnect.com/ val relayUrl = &quot;relay.walletconnect.com&quot; val serverUrl = &quot;wss://$relayUrl?projectId=$projectId&quot; val connectionType = ConnectionType.AUTOMATIC val appMetaData = Core.Model.AppMetaData( // &lt;-- What data should be entered here? name = &quot;Metamask&quot;, description = &quot;Description&quot;, url = &quot;Wallet Url&quot;, // How can I get the wallet url? icons = listOf(&quot;&quot;), redirect = &quot;kotlin-wallet-wc:/request&quot; ) CoreClient.initialize(relayServerUrl = serverUrl, connectionType = connectionType, application = application, metaData = appMetaData) val init = Sign.Params.Init(CoreClient) SignClient.initialize(init, onError = { error -&gt; }) </code></pre>
[ { "answer_id": 74371243, "author": "MelissaWood365", "author_id": 20456869, "author_profile": "https://Stackoverflow.com/users/20456869", "pm_score": 0, "selected": false, "text": "enter code here\n" }, { "answer_id": 74445850, "author": "Blackarrow", "author_id": 17425780, "author_profile": "https://Stackoverflow.com/users/17425780", "pm_score": 0, "selected": false, "text": " private val metaData = Session.PeerMeta(\n name = \"nfscene\",\n url = \"nfscene.com\",\n description = \"nfscene WalletConnect demo\"\n )\n" }, { "answer_id": 74533509, "author": "Elyniss", "author_id": 10024948, "author_profile": "https://Stackoverflow.com/users/10024948", "pm_score": 1, "selected": false, "text": "initialize" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74352822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6580761/" ]
74,352,833
<p>I have a Laravel 6 app and am trying to pass two parameters from my view's form to my controller via a resource route. I can pass one, no problem, but passing two gives the same error:</p> <p><code>Too few arguments to function App\Http\Controllers\Admin\SubscriptionsController::update(), 1 passed and exactly 2 expected</code></p> <p>I've tried many different arrangements suggested from other posts but none bring the desired result.</p> <p>Here's my route:</p> <pre><code>Route::resource('subscriptions', 'Admin\SubscriptionsController') </code></pre> <p>Here's my form in my view:</p> <pre><code> {{ Form::open(['route' =&gt; ['admin.subscriptions.update', $plan-&gt;id, $coupon_code], 'method' =&gt; 'PUT', 'id' =&gt; 'role-' . $plan-&gt;id, $coupon_code]) }} Coupon Code: &lt;input type=&quot;text&quot; name=&quot;coupon_code&quot;&gt; {{ Form::close() }} </code></pre> <p>Here's my controller. It doesn't reach the <code>dd()</code> test.</p> <pre><code>public function update($id, $coupon_code) { dd($coupon_code); ... </code></pre> <p>In the error Whoops! page, I can see the POST DATA that <code>$coupon_code</code> is being sent over.</p> <p><a href="https://i.stack.imgur.com/kvgPQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kvgPQ.png" alt="screenshot of POST_DATA" /></a></p> <p>However, if I remove the <code>$coupon_code</code> parameter from the controller (leaving <code>public function update($id)</code> ) it functions fine passing $id from form to controller, but I don't get the <code>$coupon_code</code> data I need to process. Adding the second parameter bombs it.</p> <p>Any suggestions are very welcome.</p>
[ { "answer_id": 74371243, "author": "MelissaWood365", "author_id": 20456869, "author_profile": "https://Stackoverflow.com/users/20456869", "pm_score": 0, "selected": false, "text": "enter code here\n" }, { "answer_id": 74445850, "author": "Blackarrow", "author_id": 17425780, "author_profile": "https://Stackoverflow.com/users/17425780", "pm_score": 0, "selected": false, "text": " private val metaData = Session.PeerMeta(\n name = \"nfscene\",\n url = \"nfscene.com\",\n description = \"nfscene WalletConnect demo\"\n )\n" }, { "answer_id": 74533509, "author": "Elyniss", "author_id": 10024948, "author_profile": "https://Stackoverflow.com/users/10024948", "pm_score": 1, "selected": false, "text": "initialize" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74352833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6768483/" ]
74,352,839
<p>I am trying to pass all the arrays such as molecularWeight(concentration,time) `</p> <pre><code>concentration_time = np.array([[0,83], [0.04,89], [0.06,95], [0.08,104], [0.1,114], [0.12,126], [0.14,139], [0.16,155], [0.20,191]]) concentration = [item[0] for item in concentration_time] time = [item[1] for item in concentration_time] t0 = 83 def molecularWeight(c,t): answer = ((t/t0)-1)/c return answer molecularWeight(concentration,time) </code></pre> <p>I was expecting to get an output with 9 different outputs. I want to pass all pairs for c and t and get an output for each.</p> <p>I get the desired output when I manually pass the values:<code>molecularWeight(0.04,89.0)</code> but not when I try to pass all of them using the previously defined variables: <code>molecularWeight(concentration,time)</code> ERROR:</p> <pre><code>TypeError: unsupported operand type(s) for /: 'list' and 'int' </code></pre>
[ { "answer_id": 74352891, "author": "ShlomiF", "author_id": 5024514, "author_profile": "https://Stackoverflow.com/users/5024514", "pm_score": 0, "selected": false, "text": "numpy" }, { "answer_id": 74352934, "author": "Libra", "author_id": 10755384, "author_profile": "https://Stackoverflow.com/users/10755384", "pm_score": -1, "selected": false, "text": "def molecularWeight(inputs):\n answers = []\n\n for c, t in inputs: \n answer = ((t/t0)-1)/c\n answers.append(answer)\n\n return answers\n\n" }, { "answer_id": 74353457, "author": "amirhm", "author_id": 4529589, "author_profile": "https://Stackoverflow.com/users/4529589", "pm_score": 0, "selected": false, "text": "concentration ,time = concentration_time[:,0], concentration_time[:,1]\nt0 = 83\ndef molecularWeight(c,t):\n return ((t / t0) - 1) / (c + 1e-9)\n\nmolecularWeight(concentration,time)\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74352839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20207466/" ]
74,352,872
<p>I saw a lot of answers for the date problem with Safari and IE for the date, using <code>replace(/-/g, &quot;/&quot;)</code> works like a charm for these cases <code>2022-11-30 17:00 UTC+0200</code> but encountered an issue when I had other time zone like this one <code>2022-11-28 21:56 UTC-0500</code> it would create an invalid date again, for any browser.</p> <p>So I'm looking for a solution that would replace the &quot;-&quot; not globally but only in the first word eventually.</p> <p>Thank you</p>
[ { "answer_id": 74352932, "author": "Konrad", "author_id": 5089567, "author_profile": "https://Stackoverflow.com/users/5089567", "pm_score": 3, "selected": true, "text": "const date = `2022-11-30 17:00 UTC-0200`\nconst regex = /(\\d+)-(\\d+)-(\\d+)/g\nconst result = date.replace(regex, '$1/$2/$3')\nconsole.log(result)" }, { "answer_id": 74353043, "author": "Wiktor Stribiżew", "author_id": 3832970, "author_profile": "https://Stackoverflow.com/users/3832970", "pm_score": 1, "selected": false, "text": "UTC" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74352872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13596673/" ]
74,352,892
<p>A Ke-number is an integer 10≤n≤99 such that, if we start a Fibonacci sequence with its digits, the sequence contains n.</p> <p>For example, 47 is a Ke-number because the sequence starts like this: 4,7,11,18,29,47, coming to the number itself.</p> <p>I'm trying to define the recursive function ke_number that takes a two-digit integer and checks if it is a Ke-number. (True or False)</p> <p>I got it to work like this:</p> <pre><code>def ke_number(n): n1 = int(str(n)[0]) n2 = int(str(n)[1]) return n in [fib(i,n1,n2) for i in range(1,100)] def fib(n, a, b): if n==0 or n==1: return b return fib(n-1, b, a+b) </code></pre> <p>But as you can see, it's not just one function, it's two. How can I transform this into just one recursive function?</p>
[ { "answer_id": 74353012, "author": "Arty", "author_id": 941531, "author_profile": "https://Stackoverflow.com/users/941531", "pm_score": 2, "selected": false, "text": "def ke_number(n, a = None, b = None):\n if a is None:\n return ke_number(n, n // 10, n % 10)\n if a < n:\n return ke_number(n, b, a + b)\n return a == n\n\nprint(ke_number(47))\nprint(ke_number(46))\n" }, { "answer_id": 74353186, "author": "MEisebitt", "author_id": 12663213, "author_profile": "https://Stackoverflow.com/users/12663213", "pm_score": 1, "selected": false, "text": "def ke_test(n):\n a, b = divmod(n, 10)\n while b < n:\n a, b = b, a+b\n return b == n\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74352892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20400765/" ]
74,352,910
<p>I have been looking at this piece of code for over 2 days now, and i have not been able to locate my Hydration error. It is driving me crazy. Could some one maybe take a look at it for me? Are there any tips and tricks to spot these kind of errors more quickly, would love to know!</p> <p>I'am using nextjs and using axios for the get resquest</p> <p>These are the errors: <strong>Error: Hydration failed because the initial UI does not match what was rendered on the server.</strong></p> <p><strong>Error: There was an error while hydrating. Because the error happened outside of a Suspense boundary, the entire root will switch to client rendering.</strong></p> <p><strong>react-dom.development.js?ac89:19849 Uncaught Error: There was an error while hydrating. Because the error happened outside of a Suspense boundary, the entire root will switch to client rendering.</strong></p> <pre><code> export async function getStaticProps() { try { const res = await axios.get('https://open.data.amsterdam.nl/Festivals.json') const events = res.data; return { props: { events: events.slice(0, 10) } } } catch (error) { console.log(error) } } function EventsCards({events}) { return ( &lt;div&gt; &lt;a id=&quot;pressable-card max-w-md&quot;&gt; &lt;div id=&quot;featured-event-container&quot; className=&quot;bg-black rounded-md bg-opacity-20 bg-blur-sm max-w-xs shadow-lg&quot;&gt; &lt;div id=&quot;event-banner&quot;&gt; &lt;img className=&quot;max-w-lg w-full h-full&quot; src={events.media[0].url }/&gt; &lt;/div&gt; &lt;div className=&quot;text-white pl-2&quot;&gt; &lt;h1 className=&quot;text-lg font-medium text-transparent bg-clip-text bg-gradient-to-r from-purple-400 to-pink-600&quot;&gt;{events.title}&lt;/h1&gt; &lt;a className=&quot;text-sm uppercase&quot;&gt;{events.title}&lt;/a&gt; &lt;a className=&quot;text-xs text-&quot;&gt;Friday 20 Jan | 13:00 - 02:00&lt;/a&gt; &lt;/div&gt; &lt;div className=&quot;py-2 px-2&quot;&gt; &lt;p className=&quot;text-slate-200 font-normal border-[1px] py-[2px] px-[4px] rounded-lg border-slate-400 w-8 text-[8px]&quot;&gt;Techno&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/a&gt; &lt;/div&gt; ) } function Events({events}) { return ( &lt;div className=&quot;bg-gradient-to-t from-gray-500 to-gray-900 h-full bg-blur-sm pt-2&quot;&gt; &lt;div className=&quot;max-w-6xl mx-auto&quot;&gt; &lt;div className=&quot;px-8 &quot;&gt; &lt;div className=&quot;flex&quot;&gt; &lt;h1 className=&quot;text-white font-regular opacity-100 tracking-wider sm:text-xl md:text-2xl&quot;&gt;Featured events in Amsterdam&lt;/h1&gt; &lt;div className=&quot;pl-2 my-auto&quot;&gt; &lt;img className=&quot;rounded-full w-8 h-8 md:w-6 md:h-6 border-gray-400&quot; src=&quot;https://www.fotw.info/images/n/nl.gif&quot;&gt;&lt;/img&gt; &lt;/div&gt; &lt;/div&gt; &lt;ul className=&quot;grid grid-cols-1 md:grid-cols-2 pt-4 md:w-full&quot;&gt; &lt;div id=&quot;featured-wrapper&quot; className=&quot;bg-black rounded-md bg-opacity-20 bg-blur-sm max-w-xs shadow-lg&quot;&gt; &lt;a id=&quot;pressable-card max-w-md&quot;&gt; &lt;div id=&quot;featured-event-container&quot;&gt; &lt;div id=&quot;event-banner&quot;&gt; &lt;img className=&quot;max-w-lg max-h-lg w-full h-full&quot; src='https://d1as2iufift1z3.cloudfront.net/rails/active_storage/blobs/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBBaWpqIiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--696c8f363a91d0501e8ae333fc9d42e5fd9c225f/ERT_HOLLAND_SIGNUP_banner%20(1).jpg?proxy=true'&gt;&lt;/img&gt; &lt;/div&gt; &lt;div className=&quot;text-white pl-2&quot;&gt; &lt;h1 className=&quot;text-lg font-medium text-transparent bg-clip-text bg-gradient-to-r from-purple-400 to-pink-600&quot;&gt;El Row Town 2022 - Holland&lt;/h1&gt; &lt;a className=&quot;text-sm uppercase&quot;&gt;{events.title}&lt;/a&gt; &lt;a className=&quot;text-xs text-&quot;&gt;Friday 1 Jan | 11:00 - 04:00&lt;/a&gt; &lt;/div&gt; &lt;div className=&quot;py-2 px-2&quot;&gt; &lt;a className=&quot;text-slate-200 font-normal border-[1px] py-[2px] px-[4px] rounded-lg border-slate-400 w-8 text-[8px]&quot;&gt;Techno&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/a&gt; &lt;/div&gt; &lt;div className=&quot;text-red-400&quot;&gt;&lt;h1&gt;test&lt;/h1&gt;&lt;/div&gt; &lt;/ul&gt; &lt;/div&gt; {/* Amsterdam Events */} &lt;div className=&quot;flex justify-center py-8&quot;&gt; &lt;button className=&quot;text-[8px] uppercase font-medium rounded-md py-[8px] px-2 bg-white&quot;&gt;see events in Amsterdam&lt;/button&gt; &lt;/div&gt; {/* All Events */} &lt;div className=&quot;mx-auto max-w-6xl w-full&quot;&gt; &lt;h1 className=&quot;px-8 text-white font-regular tracking-wider text-xl md:text-2xl&quot;&gt;Amsterdam&lt;/h1&gt; &lt;/div&gt; &lt;div className=&quot;max-auto max-w-6xl&quot;&gt; &lt;div className=&quot;grid grid-cols-1 md:grid-cols-3 pt-4 md:w-full w-full px-8 gap-4&quot;&gt; {events.map((event) =&gt; ( &lt;EventsCards key={event.id} events={event} /&gt; ))} &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; ) } export default Events;``` </code></pre>
[ { "answer_id": 74354099, "author": "jme11", "author_id": 3577849, "author_profile": "https://Stackoverflow.com/users/3577849", "pm_score": 3, "selected": true, "text": "events" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74352910", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11595909/" ]
74,352,919
<p>I'm working on a C# project that will need to create text files and fill them with guids using an array of 25 tasks. I want to use another task separate from the writing tasks to monitor the size of the file at 0.5 second intervals.</p> <p>I'm struggling to figure out a way to do this. I know with a C# WPF application I could use the FILEIO class but I don't think I have access to that using a console app.</p> <p>What could I use instead of the FILEIO class to create this task and how would I create it?</p>
[ { "answer_id": 74354099, "author": "jme11", "author_id": 3577849, "author_profile": "https://Stackoverflow.com/users/3577849", "pm_score": 3, "selected": true, "text": "events" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74352919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17978542/" ]
74,352,926
<p>So this is a continuation of my <a href="https://stackoverflow.com/questions/74257959/python-webscraping-pricing-and-hidden-elements-with-selenium">previous question</a>, which, with the help of Prophet, I was able to get it working. Until last week.</p> <p>Basically: on this <a href="https://www.centris.ca/en/properties%7Efor-sale%7Ebrossard?view=Thumbnail" rel="nofollow noreferrer">website</a>, each listing has a <a href="https://imgur.com/a/ZEoTLoO" rel="nofollow noreferrer">MLS number</a> and I am trying to scrap that.</p> <p>Now the changes since the original question is mostly a new logic to handle a random popup via a try block to try to click on the random pop up, if it works proceed to scrap, if it fails to find the pop up then proceed to scrap anyway. That try block logic worked. But now when I run the code I notice the price and MLS scrapping is returning empty results.</p> <p>I added a print statement and confirmed both mls and price is empty: <code>mls is price is </code></p> <p>The main.py is the code with try blocks. <a href="https://github.com/jzoudavy/webScrap_Selenium/blob/main/main.py" rel="nofollow noreferrer">https://github.com/jzoudavy/webScrap_Selenium/blob/main/main.py</a></p> <p>To simplify this I took away the try block and other extra stuff: <a href="https://github.com/jzoudavy/webScrap_Selenium/blob/main/test.py" rel="nofollow noreferrer">https://github.com/jzoudavy/webScrap_Selenium/blob/main/test.py</a> but running the test.py confirms also that I am no longer picking up price or mls, and everything else still scrapes fine.</p>
[ { "answer_id": 74353069, "author": "AomineDaici", "author_id": 13149512, "author_profile": "https://Stackoverflow.com/users/13149512", "pm_score": 0, "selected": false, "text": "data-mlsnumber" }, { "answer_id": 74353694, "author": "Fazlul", "author_id": 12848411, "author_profile": "https://Stackoverflow.com/users/12848411", "pm_score": 3, "selected": true, "text": "from selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.common.by import By\nimport time\n\noptions = webdriver.ChromeOptions()\noptions.add_argument(\"--no-sandbox\")\noptions.add_argument('--disable-blink-features=AutomationControlled')\noptions.add_argument(\"start-maximized\")\noptions.add_experimental_option(\"detach\", True)\n\n\ns=Service('./chromedriver')\ndriver= webdriver.Chrome(service=s, options=options)\nurl='https://www.centris.ca/en/properties~for-sale~brossard?view=Thumbnail'\ndriver.get(url)\ntime.sleep(4)\n\n\nlistings = driver.find_elements(By.CLASS_NAME, 'description')\n\nfor listing in listings:\n try:\n price = listing.find_element(By.XPATH, './/*[@itemprop=\"price\"]//following-sibling::span[1]').text\n data_mlsnumber = listing.find_element(By.XPATH, './/*[@class=\"a-more-detail\"]').get_attribute('data-mlsnumber')\n print(price , data_mlsnumber)\n except:\n pass\n \n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74352926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/943222/" ]
74,352,929
<p>I have two JavaRDD A and B. I want to only keep longs that are in A but not in B. How should I do that? Thanks!</p>
[ { "answer_id": 74353262, "author": "Hema Jayachandran", "author_id": 13163227, "author_profile": "https://Stackoverflow.com/users/13163227", "pm_score": 2, "selected": true, "text": "leftOuterJoin" }, { "answer_id": 74358478, "author": "btbbass", "author_id": 3408256, "author_profile": "https://Stackoverflow.com/users/3408256", "pm_score": 0, "selected": false, "text": "antijoin" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74352929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8133719/" ]
74,352,951
<p>I have this span element. am fetching data and putting some text in that span element, therefore sometimes that span elements width is 200 px, sometimes its 100px. I want this span to have margin-right: half of its width. I am using this technique:</p> <pre><code>const [width, setWidth] = useState() const ref = useRef(null) useLayoutEffect(()=&gt;{ setWidth(ref.current.offsetWidth); },[]) &lt;span className='big ' id='meria' ref={ref} style={{marginRight: width / 2 }}&gt;sometext&lt;/span&gt; </code></pre> <p>I want the width element to re-render on change of window.location.pathname, but I cant use that as dependency. any tips?</p>
[ { "answer_id": 74353017, "author": "Ori Drori", "author_id": 5157454, "author_profile": "https://Stackoverflow.com/users/5157454", "pm_score": 1, "selected": false, "text": "useEffect" }, { "answer_id": 74353615, "author": "Lord-JulianXLII", "author_id": 19529102, "author_profile": "https://Stackoverflow.com/users/19529102", "pm_score": 1, "selected": true, "text": "width: fit-content" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74352951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20121566/" ]
74,352,958
<p><a href="https://i.stack.imgur.com/p3hZt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/p3hZt.png" alt="trying to understand this bit of code" /></a> for some readability and searchability, here is the typed out code</p> <pre><code>def counter(func): def wrapper(*args, **kwargs): wrapper.count += 1 return func (*args, **kwargs) wrapper.count = 0 return wrapper @counter def foo(): print('calling foo()') foo() foo() print('foo() was called {} times.'.format(foo.count)) </code></pre> <p>currently learning how decorator works...encounter this bit of code couldn't understand<code>wrapper.count = 0</code> and how when using the decorate in the following code, that the <code>wrapper.count = 2</code> but not reset to 0</p> <p>does this have anything to do with closure?</p> <p>I visited other post which contains similar problem. the answer wasn't that clear to me</p> <p>can anyone explain the logic behind this code?</p> <p>Thanks!</p>
[ { "answer_id": 74353145, "author": "Elliott", "author_id": 19359809, "author_profile": "https://Stackoverflow.com/users/19359809", "pm_score": 0, "selected": false, "text": "def wrapper" }, { "answer_id": 74353440, "author": "Pranav Hosangadi", "author_id": 843953, "author_profile": "https://Stackoverflow.com/users/843953", "pm_score": 2, "selected": true, "text": "wrapper.count = 0" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74352958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20444040/" ]
74,352,979
<p>I have a selenium project in Java using JUnit5. I have some suites and several tests with tags. I want to have a suite that runs all tests with <strong>both</strong> tags</p> <p>An example of a suite is:</p> <pre><code>@SelectClasses(ScreenshotComparisonTests.class) @IncludeTags({&quot;CC&quot;}) @ExcludeTags({&quot;CASH&quot;, &quot;FINANCIAL&quot;, &quot;HACCP&quot;, &quot;HRM&quot;, &quot;INVENTORY&quot;, &quot;OPERATIONS&quot;, &quot;PURCHASING&quot;, &quot;REPORTING&quot;}) @Suite @SuiteDisplayName(&quot;C User Menu Screenshots Comparison Tests&quot;) public class CUserMenuScreenshotComparisonSuite { } </code></pre> <p>But instead of listing all of the tags to exclude, I'd rather have something like:</p> <pre><code>@SelectClasses(ScreenshotComparisonTests.class) @IncludeTags({&quot;CC&quot; &amp; &quot;USERMENU&quot;}) @Suite @SuiteDisplayName(&quot;C User Menu Screenshots Comparison Tests&quot;) public class CUserMenuScreenshotComparisonSuite { } </code></pre> <p>But intellij highlights that &amp; as not allowed here. I have read that this is acceptable here <a href="https://junit.org/junit5/docs/current/user-guide/#running-tests-tag-expressions" rel="nofollow noreferrer">https://junit.org/junit5/docs/current/user-guide/#running-tests-tag-expressions</a></p> <p>Tried using:</p> <ul> <li>@IncludeTags(&quot;CC&quot; &amp; &quot;USERMENU&quot;)</li> <li>@IncludeTags{(&quot;CC&quot; &amp; &quot;USERMENU&quot;)}</li> <li>@IncludeTags{&quot;CC&quot; &amp; &quot;USERMENU&quot;}</li> <li>@IncludeTags{(&quot;CC&quot; &amp;&amp; &quot;USERMENU&quot;)}</li> </ul> <pre><code> java: bad operand types for binary operator '&amp;' first type: java.lang.String second type: java.lang.String </code></pre>
[ { "answer_id": 74353145, "author": "Elliott", "author_id": 19359809, "author_profile": "https://Stackoverflow.com/users/19359809", "pm_score": 0, "selected": false, "text": "def wrapper" }, { "answer_id": 74353440, "author": "Pranav Hosangadi", "author_id": 843953, "author_profile": "https://Stackoverflow.com/users/843953", "pm_score": 2, "selected": true, "text": "wrapper.count = 0" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74352979", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20443992/" ]
74,352,998
<p>After upgrading Cypress to v.11.10.0 tests fail in a very early stage.</p> <p>We are using keycloak for login and cypress-kecloak-commands for the tests.</p> <p>Test suite works as follows:</p> <pre><code>beforeEach(() =&gt; { cy.clearCookies(); cy.kcLogout(); cy.kcLogin('admin'); }); </code></pre> <pre><code>it('navigation should be displayed completely', () =&gt; { cy.visit('/'); // some assertions }); </code></pre> <p>cy.visit('/') - as expected - redirects to http://localhost:4200/tenant-id/domain but there is an additional suffix to the url &quot;&amp;error=login_required&amp;state=some-unique-id&quot;. Apparently we are not logged in (as the login page is displayed) and the assertions after cy.visit('/') fail. It is as if the Angular web application does not &quot;know&quot; that it is logged in.</p> <p>The tests succeed only for Firefox browser and fail for Chrome and Electron.</p> <p>The tests all work quite good for electron browser if we return to Cypress version 8.7.0 where we were in before.</p> <p>Cypress: v.10.11.0 Angular: v14.2.2 OS: macOS Monterey (12.5.1)</p> <p>package.json devDependencies (partially):</p> <pre><code>&quot;cypress&quot;: &quot;10.11.0&quot;, &quot;cypress-keycloak-commands&quot;: &quot;1.2.0&quot;, &quot;cypress-plugin-tab&quot;: &quot;1.0.5&quot;, </code></pre> <p>cypress.config.ts:</p> <pre><code>import { defineConfig } from 'cypress' export default defineConfig({ fixturesFolder: 'cypress/fixtures', screenshotsFolder: 'cypress/screenshots', videosFolder: 'cypress/videos', downloadsFolder: 'cypress/downloads', chromeWebSecurity: false, defaultCommandTimeout: 6000, apiUrl: 'http://api.develop.my-company.xy', viewportWidth: 1600, viewportHeight: 900, video: false, env: { login_url: 'http://login.develop.my-company.xy', username: 'p7s1-admin', password: '12345', api_url: 'http://api.develop.my-company.xy', auth_base_url: 'http://login.develop.my-company.xy/auth', auth_realm: 'my-company-xy', auth_client_id: 'booking-gui', }, retries: { runMode: 2, openMode: 0, }, e2e: { // We've imported your old cypress plugins here. // You may want to clean this up later by importing these. setupNodeEvents(on, config) { return require('./cypress/plugins/index.js')(on, config) }, specPattern: 'cypress/tests/**/*.{spec.js,feature,features}', baseUrl: 'http://my.develop.my-company.xy/en/', experimentalSessionAndOrigin: true, }, }) </code></pre> <p>Using cy.session() on login did not help.</p> <p>chromeWebSecurity is already set to FALSE.</p> <p>From <a href="https://stackoverflow.com/questions/53460439/error-when-trying-to-log-in-with-auth0-in-cypress-tests">Error when trying to log in with Auth0 in Cypress tests</a>: resetting local storage like this:</p> <pre><code>let accessToken = null; // this is a global variable at top of file Cypress.Commands.add('resetLocalStorage', () =&gt; { if (!accessToken) { accessToken = localStorage.getItem('access_token'); } window.localStorage.setItem('access_token', accessToken); }); </code></pre> <p>did not help either.</p>
[ { "answer_id": 74353145, "author": "Elliott", "author_id": 19359809, "author_profile": "https://Stackoverflow.com/users/19359809", "pm_score": 0, "selected": false, "text": "def wrapper" }, { "answer_id": 74353440, "author": "Pranav Hosangadi", "author_id": 843953, "author_profile": "https://Stackoverflow.com/users/843953", "pm_score": 2, "selected": true, "text": "wrapper.count = 0" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74352998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20443513/" ]
74,353,004
<pre><code>import java.util.Scanner; public class GirilenSayilardanMinveMaxDeğerleriBulma { public static void main(String[] args) { Scanner input=new Scanner(System.in); System.out.print(&quot;kaç sayı gireceksiniz: &quot;); int a=input.nextInt(); int max=0,min=0,b=0; for(int i=1;i&lt;=a;i++) { System.out.print( i +&quot;.sayıyı giriniz: &quot;); b=input.nextInt(); max=b; min=b; }if(b &gt;max) { max=b; }else if(b&lt;min) { min=b; }else { System.out.print( &quot;sayılar eşit.&quot;); } System.out.print(max); System.out.print(min); } } </code></pre> <p>I want to Find the Largest (MAX) and Smallest (MIN) Number Typed by the User in Java, but I'm making a mistake somewhere. i would be glad if you would support.by the way, I just want to use loop.</p> <p>I took a number from the user and asked how many times to enter it. after entering the numbers, there is a calculation error and he gets the last number. max and min throw the last number to the value.thank you</p>
[ { "answer_id": 74353062, "author": "M. Rogers", "author_id": 6474819, "author_profile": "https://Stackoverflow.com/users/6474819", "pm_score": 2, "selected": false, "text": "b=input.nextInt();\nmax=b;\nmin=b;\n" }, { "answer_id": 74353083, "author": "sanurah", "author_id": 4079056, "author_profile": "https://Stackoverflow.com/users/4079056", "pm_score": 0, "selected": false, "text": " public static void main(String[] args) {\n \n Scanner input=new Scanner(System.in); \n \n System.out.print(\"kaç sayı gireceksiniz: \");\n int a=input.nextInt();\n int max=0,min=0,b=0;\n \n for(int i=1;i<=a;i++) {\n System.out.print( i +\".sayıyı giriniz: \");\n b=input.nextInt();\n max=b;\n min=b;\n }if(b >max) {\n max=b;\n }else if(b<min) {\n min=b;\n }else {\n System.out.print( \"sayılar eşit.\");\n }\n System.out.print(max);\n System.out.print(min);\n}\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20443949/" ]
74,353,056
<p>I'm trying to determine how many meetings fall <strong>outside</strong> of a worker's standard business hours. All meeting times come out of the system in my time zone (Pacific Time), however there are workers across time zones. Therefore, I converted every worker's standard business hours according to their time zones, into Pacific Time and am trying to compare the meeting time in PT to their business hours in PT.</p> <p>I'm having difficulty with the calculation in any situation where a worker's standard business hours are overnight in PT, such as 11 PM - 9 AM and a meeting was held between 4 - 5 AM, for example. I'm currently using the formula:</p> <pre><code>=IF(A2:A=&quot;&quot;,&quot;&quot;,IF(AND(TIMEVALUE(C2)&lt;=TIMEVALUE(A2),TIMEVALUE(D2)&gt;=TIMEVALUE(B2)),&quot;Y&quot;,&quot;N&quot;)) </code></pre> <p>Where</p> <ul> <li>Col A = Meeting Start Time</li> <li>Col B = Meeting End Time</li> <li>Col C = Worker Start Time</li> <li>Col D = Worker End Time</li> </ul> <p>I want to determine whether the entirety of the meeting was within the worker's business hours. If it was, the output should be &quot;Y&quot; otherwise the output is &quot;N.&quot;</p> <p><a href="https://docs.google.com/spreadsheets/d/1wB_6pojLYg2V5lVRH_4bIvyNIBi8BsXOoBRjBdLgfS8/edit?usp=sharing" rel="nofollow noreferrer">Here is a sample sheet</a> - I have the formula I tried in E2 and I highlighted all of the incorrectly calculated outputs.</p> <p>Thanks in advance!</p>
[ { "answer_id": 74353180, "author": "KeithL", "author_id": 3325290, "author_profile": "https://Stackoverflow.com/users/3325290", "pm_score": 0, "selected": false, "text": "=if(AND(timevalue(A2)>=timevalue(C2),timevalue(B2)<=timevalue(D2)),\"Y\",\"N\")\n" }, { "answer_id": 74355545, "author": "Twilight", "author_id": 20038057, "author_profile": "https://Stackoverflow.com/users/20038057", "pm_score": 2, "selected": true, "text": "Today()" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16931748/" ]
74,353,105
<p>So I have a large 3D array (~ 2000 x 1000 x 1000). I want to update each value in the array to a random integer value between 1 and the current max such that all values = x are updated to the same random integer. I want to keep zeros unchanged. Also there can't be any repeats, i.e. different values in the original array can't be updated to the same random int. The values are currently in a continuous range between 0 and 9000. There are quite a lot of values in the array;</p> <p><code>np.amax(arr) #output = 9000</code></p> <p>So tried the method below...</p> <pre><code>max_v = np.amax(arr) vlist = [] for l in range(1,max_v): vlist.append(l) for l in tqdm(range(1,max_v)): m = random.randint(1,len(vlist)) n = vlist[m] arr = np.where(arr == l, n, arr) vlist.remove(n) </code></pre> <p>My current code takes about 13 s per iteration with 9000 itertions (for the first few iterations at least which is too slow). I've thought about parallelisation with concurrent.futures but i'm sure it's likely i've missed something obvious here XD</p>
[ { "answer_id": 74353512, "author": "Mad Physicist", "author_id": 2988730, "author_profile": "https://Stackoverflow.com/users/2988730", "pm_score": 3, "selected": true, "text": "arr = np.random.randint(9001, size=(10, 20, 20))\np = np.arange(arr.max(None) + 1)\nnp.random.shuffle(p)\narr = p[arr]\n" }, { "answer_id": 74353879, "author": "Sam Mason", "author_id": 1358308, "author_profile": "https://Stackoverflow.com/users/1358308", "pm_score": 1, "selected": false, "text": "from sys import getsizeof\nimport numpy as np\n\n# create a new-style random generator\nrng = np.random.default_rng()\n\n# takes ~20 seconds, ~60 secs with legacy generator\nX = rng.integers(9001, size=(2000, 1000, 1000), dtype=np.uint16)\n\n# output: 3.73 GiB, uint16 takes 1/4 space of the default int64\nprint(f\"{getsizeof(X) / 2**30:.2f} GiB\")\n\n# generate a permutation, converting to same datatype makes slightly faster\np = rng.permutation(np.max(X)+1).astype(X.dtype)\n\n# iterate applying permutation, takes ~10 seconds in total\nfor i in range(len(X)):\n X[i] = p[X[i]]\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17926120/" ]
74,353,137
<p>Writing a food ordering program for school, and am running into the issue of TypeError when trying to take the user input to select the menu item, then use that input to refer quantity value to that dictionary.</p> <p>`</p> <pre><code>menu = { 1: {&quot;item&quot;: &quot;Green Beret Omelette&quot;, &quot;price&quot;: &quot;$12.99&quot;}, 2: {&quot;item&quot;: &quot;Get to the Chopped Salad&quot;, &quot;price&quot;: &quot;$14.99&quot;}, 3: {&quot;item&quot;: &quot;Pump You Up Protein Shake&quot;, &quot;price&quot;: &quot;$9.99&quot;}, 4: {&quot;item&quot;: &quot;I'll Be Baby Back Ribs&quot;, &quot;price&quot;: &quot;$22.99&quot;}, 5: {&quot;item&quot;: &quot;Let Off Some Steamed Vegetables&quot;, &quot;price&quot;: &quot;$4.99&quot;}, 6: {&quot;item&quot;: &quot;The Ice Cream Cometh&quot;, &quot;price&quot;: &quot;$15.99&quot;} } key = int(input(&quot;Please select your item:\n&quot;)) if int(key) &lt; 1 or int(key) &gt; 6: print(&quot;Invalid selection. Please try again. \n&quot;) isOrdering = True continue quan = int(input(&quot;Enter quantity: \n&quot;)), menu.update[key]({&quot;quantity&quot;: quan}) </code></pre> <p>The error I'm currently running into is &quot;Exception has occurred: TypeError 'builtin_function_or_method' object is not subscriptable&quot; for the line:</p> <p>quan = int(input(&quot;Enter quantity: \n&quot;)), menu.update[key]({&quot;quantity&quot;: quan})</p> <p>I tried the code above based on a previous attempt at asking that a friend posted for me. Threw the same error as I had in my initial attempt at solving.</p> <p>The expected/intended output/update (whatever you want to call it) is:</p> <p>menu choice: 1</p> <p>quantity: 3</p> <p>dictionary update: 1: {&quot;item&quot;: &quot;Green Beret Omelette&quot;, &quot;price&quot;: &quot;$12.99&quot;, &quot;quantity&quot;: 3}</p>
[ { "answer_id": 74353512, "author": "Mad Physicist", "author_id": 2988730, "author_profile": "https://Stackoverflow.com/users/2988730", "pm_score": 3, "selected": true, "text": "arr = np.random.randint(9001, size=(10, 20, 20))\np = np.arange(arr.max(None) + 1)\nnp.random.shuffle(p)\narr = p[arr]\n" }, { "answer_id": 74353879, "author": "Sam Mason", "author_id": 1358308, "author_profile": "https://Stackoverflow.com/users/1358308", "pm_score": 1, "selected": false, "text": "from sys import getsizeof\nimport numpy as np\n\n# create a new-style random generator\nrng = np.random.default_rng()\n\n# takes ~20 seconds, ~60 secs with legacy generator\nX = rng.integers(9001, size=(2000, 1000, 1000), dtype=np.uint16)\n\n# output: 3.73 GiB, uint16 takes 1/4 space of the default int64\nprint(f\"{getsizeof(X) / 2**30:.2f} GiB\")\n\n# generate a permutation, converting to same datatype makes slightly faster\np = rng.permutation(np.max(X)+1).astype(X.dtype)\n\n# iterate applying permutation, takes ~10 seconds in total\nfor i in range(len(X)):\n X[i] = p[X[i]]\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20442805/" ]
74,353,152
<p>Say I got a file that is</p> <pre><code>1 hchen 50 2 vryzhikov 60 3 kmannock 74 4 vryzhikov 53 </code></pre> <p>I make a dictionary of the names as keys and the scores as the values. If someone has 2 different scores, both scores would come out with that name.</p> <p>Something like this:</p> <pre><code>hchen 50 vryzhikov 53 60 kmannock 74 </code></pre> <pre><code>infile= open(&quot;students.txt&quot;, &quot;r&quot;) d = {} with open(&quot;students.txt&quot;) as f: for line in f: a = line.split() key = a[1] val = a[2] d[(key)] = val print(d) A = input() print(d.get(A)) </code></pre> <p>is it possible to get what I'm going for?</p>
[ { "answer_id": 74353211, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 1, "selected": false, "text": "out = {}\nwith open(\"students.txt\", \"r\") as f_in:\n for line in map(str.strip, f_in):\n if line == \"\":\n continue\n _, key, val = line.split()\n out.setdefault(key, []).append(val)\n\nprint(out)\n" }, { "answer_id": 74353222, "author": "Sup3rlum", "author_id": 7044694, "author_profile": "https://Stackoverflow.com/users/7044694", "pm_score": 1, "selected": false, "text": "defaultdict" }, { "answer_id": 74353806, "author": "cards", "author_id": 16462878, "author_profile": "https://Stackoverflow.com/users/16462878", "pm_score": 0, "selected": false, "text": "csv" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353152", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20213604/" ]
74,353,155
<p>I was watching <a href="https://www.youtube.com/watch?v=9N_wJ7oIHDk&amp;t=0s&amp;ab_channel=KonstantinVladimirov" rel="nofollow noreferrer">this</a> c++ lection (it's in russian). At around 16:10 the lector asked an open question:</p> <p>Having this code:</p> <pre><code>int* foo() { volatile auto a = nullptr; int* b = a; return b; } int main() {} </code></pre> <p>Clang generates <a href="https://godbolt.org/z/EdjbdYhcM" rel="nofollow noreferrer">the following</a> assembly for <code>foo</code> (-Ofast)</p> <pre><code> mov qword ptr [rsp - 8], 0 # volatile auto a = nullptr; xor eax, eax ret </code></pre> <p>Meaning the compiler assumes there is no side effect for reading from <code>a</code> and basically removes <code>int* b = a;</code> part of the code.</p> <p>GCC on the other hand <a href="https://godbolt.org/z/e8TMMsn6K" rel="nofollow noreferrer">generates</a> a bit different code</p> <pre><code> mov QWORD PTR [rsp-8], 0 # volatile auto a = nullptr; mov rax, QWORD PTR [rsp-8] # int* b = a; xor eax, eax ret </code></pre> <p>Here compiler believes reading from <code>a</code> does produce the side effect and leaves everything as is.</p> <p>The question is what is the correct behaviour according to C++20 standard?</p>
[ { "answer_id": 74353258, "author": "user17732522", "author_id": 17732522, "author_profile": "https://Stackoverflow.com/users/17732522", "pm_score": 4, "selected": true, "text": "a" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353155", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3029238/" ]
74,353,163
<p>In a CSV file, I have dates, downtime, and incident numbers of my application. Based on the below data I have to plot a graph of my application uptime using Python. Uptime for the last 7 days, Uptime for the last 30 days, and uptime for the last 90 days.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>date</th> <th>downtime(hrs)</th> <th>incident</th> </tr> </thead> <tbody> <tr> <td>2022-10-05</td> <td>2</td> <td>abc123</td> </tr> <tr> <td>2022-10-05</td> <td>3</td> <td>abc124</td> </tr> <tr> <td>2022-09-01</td> <td>4</td> <td>abc100</td> </tr> <tr> <td>2022-08-26</td> <td>8</td> <td>abc99</td> </tr> <tr> <td>2022-08-24</td> <td>5</td> <td>abc98</td> </tr> <tr> <td>2022-07-15</td> <td>6</td> <td>abc90</td> </tr> <tr> <td>2022-06-09</td> <td>4</td> <td>abc85</td> </tr> </tbody> </table> </div> <p>I can read this data using pandas and I am able to plot downtime by incident using the below method.</p> <pre><code>downtime_by_incident = data.groupby([&quot;date&quot;, &quot;incident&quot;])['downtime].sum().unstack().plot(kind=&quot;bar&quot;, stacked=True, xlabel=&quot;&quot;, legend=False).get_figure() downtime_by_incident.savefig(&quot;downtime_by_incident.jpg&quot;, bbox_inches = &quot;tight&quot;) </code></pre> <p>But I am unable to calculate and plot the uptime of my application. Any help will be appreciated</p>
[ { "answer_id": 74353370, "author": "It_is_Chris", "author_id": 9177877, "author_profile": "https://Stackoverflow.com/users/9177877", "pm_score": 0, "selected": false, "text": "# convert to datetime\ndf['date'] = pd.to_datetime(df['date'])\n# groupby date and sum downtime then merge on a new Frame you create\n# that fills in the missing dates\nm = df.groupby('date')['downtime(hrs)'].sum().reset_index().merge(pd.DataFrame(pd.date_range(df['date'].min(),\n df['date'].max()),\n columns=['date']),\n on='date', how='right').fillna(0)\n# calculate the uptime (24 hours - downtime hours) for each day\nm['uptime'] = 24 - m['downtime(hrs)']\n# bar plot\nm[['date', 'uptime']].set_index('date').plot(kind='bar', figsize=(20,10))\n\n# line plot\nm[['date', 'uptime']].set_index('date')['uptime'].plot(figsize=(20,10))\n\n# stacked bar plot\nm.set_index('date').plot(kind='bar', stacked=True, figsize=(20,10))\n" }, { "answer_id": 74353442, "author": "amance", "author_id": 17142551, "author_profile": "https://Stackoverflow.com/users/17142551", "pm_score": 2, "selected": true, "text": "import pandas as pd\nimport numpy as np\nfrom io import StringIO\nimport plotly.express as px\n\ndf = pd.read_csv(StringIO('''date downtime(hrs) incident\n2022-10-05 2 abc123\n2022-10-05 3 abc124\n2022-09-01 4 abc100\n2022-08-26 8 abc99\n2022-08-24 5 abc98\n2022-07-15 6 abc90\n2022-06-09 4 abc85'''), sep='\\t')\n\ndf['date'] = pd.to_datetime(df['date'])\n\ndf2 = pd.DataFrame({'date':pd.date_range(df['date'].min(), df['date'].max(),freq='d')}).assign(tot_hours=24)\n\ndf2 = pd.merge(df2, df[['date', 'downtime(hrs)']].groupby('date').sum().reset_index(), how='left')\n\ndf2['uptime'] = df2['tot_hours'] - df2['downtime(hrs)'].fillna(0)\n\n#if there's any negative downtime, impute to zero\ndf2['uptime'] = np.where(df2['uptime']<0, 0, df2['uptime'])\n\nfig = px.line(df2,\n x='date',\n y='uptime')\n\nfig.show()\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353163", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3009657/" ]
74,353,164
<p>I'm traying to filter web data but my variables don't update!</p> <pre><code>for i in range(len(links)): cupons = recupTahmin(links[i]) try: for j in range(len(cupons)): eventName = cupons[j].find_element(by=By.XPATH, value=&quot;//a[@class='eventName ']&quot;).text eventDate = cupons[j].find_element(by=By.XPATH, value=&quot;//div[@class='eventDate']&quot;).text bahis = cupons[j].find_element(by=By.XPATH, value=&quot;//span[@class='type']&quot;).text tahmin = cupons[j].find_element(by=By.XPATH, value=&quot;//span[@class='choice ']&quot;).text oran = cupons[j].find_element(by=By.XPATH, value=&quot;//div[@class='eventOutcome']&quot;).text predictions.append(cupon(eventName,eventDate, tahmin, oran, bahis)) except: pass for j in range(len(predictions)): print(vars(predictions[j])) </code></pre> <p>I already check cupons if all is okay. Cupons is a list of web element. The result of the code is -&gt; my terminal print len(cupons) * predictions's first elemnent for i different event. Can someone help me ? I hope it's understable :)</p>
[ { "answer_id": 74353249, "author": "Daemon", "author_id": 19030643, "author_profile": "https://Stackoverflow.com/users/19030643", "pm_score": 0, "selected": false, "text": "predictions = []\n" }, { "answer_id": 74353422, "author": "Prophet", "author_id": 3485434, "author_profile": "https://Stackoverflow.com/users/3485434", "pm_score": 2, "selected": true, "text": "." } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18370758/" ]
74,353,192
<p>How can I add two icons, top and bottom, so that when the button is clicked, the icon changes (like changing the accordion icon)?</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>function toggle_div_fun(id) {  var divelement = document.getElementById(id);  if (divelement.style.display == 'flex') divelement.style.display = 'none';  else divelement.style.display = 'flex'; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;button class="eco-btn" onclick="toggle_div_fun('sectiontohide');"&gt;Click here&lt;/button&gt; &lt;div id="sectiontohide"&gt;This is the div to hide&lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74353289, "author": "Anye", "author_id": 16752210, "author_profile": "https://Stackoverflow.com/users/16752210", "pm_score": 2, "selected": false, "text": "let btn = document.getElementById(\"toggle\");\n\nbtn.addEventListener('click', function(){\n if(btn.firstChild.classList.contains(\"fa-up-long\")){\n btn.innerHTML = '<i class=\"fa-solid fa-down-long\"></i> Click me!';\n } else {\n btn.innerHTML = '<i class=\"fa-solid fa-up-long\"></i> Click me!';\n }\n});" }, { "answer_id": 74354802, "author": "Yogi", "author_id": 943435, "author_profile": "https://Stackoverflow.com/users/943435", "pm_score": 1, "selected": false, "text": ".icon-button :not(.active) {\n display:none;\n}\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19601407/" ]
74,353,197
<p>I want to set the column width equal to the max string length in that column, actually I want to adjust the width of the column.</p> <p>Here is my code:</p> <pre><code>styler = df.style for column in df: column_length = df[column].astype(str).str.len().max() #styler.set_properties(subset=[column], **{'width': '200px'}) styler.set_properties(subset=[column], **{'width': str(column_length)+'px'}) styler.to_excel('C:/Users/test.xlsx', index=False) </code></pre> <p>The column width is not set in the exported excel file, what am I doing wrong?</p>
[ { "answer_id": 74353289, "author": "Anye", "author_id": 16752210, "author_profile": "https://Stackoverflow.com/users/16752210", "pm_score": 2, "selected": false, "text": "let btn = document.getElementById(\"toggle\");\n\nbtn.addEventListener('click', function(){\n if(btn.firstChild.classList.contains(\"fa-up-long\")){\n btn.innerHTML = '<i class=\"fa-solid fa-down-long\"></i> Click me!';\n } else {\n btn.innerHTML = '<i class=\"fa-solid fa-up-long\"></i> Click me!';\n }\n});" }, { "answer_id": 74354802, "author": "Yogi", "author_id": 943435, "author_profile": "https://Stackoverflow.com/users/943435", "pm_score": 1, "selected": false, "text": ".icon-button :not(.active) {\n display:none;\n}\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353197", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10967204/" ]
74,353,232
<p>I want to convert my project to android and publish it on play store. When I import it as apk, my project works fine, but when I import it as aab, my localization texts in the project are corrupted and the project does not work.Do I need to add it somewhere in the localization manager build settings? ( 0 Build Error)</p> <p>I cant solution this problem</p>
[ { "answer_id": 74355952, "author": "Valery Boretsky", "author_id": 6722284, "author_profile": "https://Stackoverflow.com/users/6722284", "pm_score": 0, "selected": false, "text": "bundle {\n language {\n enableSplit = false //android app bundle (aab) include all res languages\n }\n}\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16390011/" ]
74,353,266
<pre class="lang-c prettyprint-override"><code>// Why would I use this odd = (int *) calloc( nOdd, sizeof(int) ); even = (int *) calloc( nEven, sizeof(int) ); // When i can just use this int odd[nOdd]; int even[nEven]; </code></pre> <p>What is the point in calloc. I dont understand how it dynamically allocates memory when you need to input how many items are in the array.</p> <p>Im used to python where you can just append to an array. So I would have thought it would be like that</p>
[ { "answer_id": 74353306, "author": "Caleb", "author_id": 643383, "author_profile": "https://Stackoverflow.com/users/643383", "pm_score": 1, "selected": false, "text": "calloc()" }, { "answer_id": 74353329, "author": "Eric Postpischil", "author_id": 298225, "author_profile": "https://Stackoverflow.com/users/298225", "pm_score": 2, "selected": false, "text": "calloc" }, { "answer_id": 74353408, "author": "Chris", "author_id": 15261315, "author_profile": "https://Stackoverflow.com/users/15261315", "pm_score": 2, "selected": false, "text": "void foo(void) {\n int bar[100];\n\n // ...\n}\n" }, { "answer_id": 74353425, "author": "John Bode", "author_id": 134554, "author_profile": "https://Stackoverflow.com/users/134554", "pm_score": 2, "selected": false, "text": "malloc" }, { "answer_id": 74353711, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 0, "selected": false, "text": "// Why would I use this\nodd = (int *) calloc( nOdd, sizeof(int) );\neven = (int *) calloc( nEven, sizeof(int) );\n" }, { "answer_id": 74354540, "author": "autistic", "author_id": 1989425, "author_profile": "https://Stackoverflow.com/users/1989425", "pm_score": 0, "selected": false, "text": "void use(int *item) { item[0]++; }\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20444263/" ]
74,353,269
<p>I have the following piece of code that works fine:</p> <pre class="lang-py prettyprint-override"><code>import pytest class Person: def __init__(self, name, age=None, height=None, lots_of_properties=None): self.name = name if age is not None: self.age = age if height is not None: self.height = height if lots_of_properties is not None: self.lots_of_properties[&quot;somepropertykey&quot;] = &quot;somepropertyvalue&quot; @pytest.fixture def a_person(): return Person(&quot;simon&quot;, 32) def test_person_name(a_person): assert a_person.name == &quot;simon&quot; def test_person_age(a_person): assert a_person.age == 32 </code></pre> <p>this is how I have been using fixtures so far. I create a fixture object <code>a_person</code> that I can pass to multiple tests. in the above example, I can't really specify the age upon creation, since the <code>a_person</code> only defines an age. How can I pass more keywords parameters to the fixture? more over, how can I modify the <code>a_person</code> fixture, so that I can also modify the persons name, and age? I have been googling around and it looks like I have to use <code>@pytest.mark.parametrize</code> but I can't seem to understand how it could apply to this case. basically I would like to have something like:</p> <pre class="lang-py prettyprint-override"><code>@pytest.fixture def a_person(name,age, height, lots_of_properties): return Person(name, age, height, lots_of_properties) # I would like to initialize multiple a_person objects with different params def test_person_object_1(a_person.name = &quot;alive&quot;, a_person.age = 33, a_person.height = 230, a_person.lots_of_properties.{}): // test stuff def test_person_object_2(a_person.name = &quot;bob&quot;, a_person.age = 18, a_person.height = 180, a_person.lots_of_properties.{}): // test stuff </code></pre> <p>but I know the last syntax is completely wrong.</p>
[ { "answer_id": 74353462, "author": "Jortega", "author_id": 7551712, "author_profile": "https://Stackoverflow.com/users/7551712", "pm_score": 0, "selected": false, "text": "@pytest.mark.parametrize" }, { "answer_id": 74353729, "author": "Ilya", "author_id": 1139541, "author_profile": "https://Stackoverflow.com/users/1139541", "pm_score": 1, "selected": false, "text": "@pytest.mark.parametrize" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5041045/" ]
74,353,272
<p>I have a django project which works fine. However, each time there is a change in my models (when I add attributes to my model), the migrations stop working. There is usually some sort of error or the migrations will not execute. The only way for me to make the migrations to work is to drop the database and start fresh. This is a very strange behavior and cannot work in a live/production environment. I recently had to delete the db in the production environment and it was very messy.</p> <p>Is there a way to fix this ? Isnt this strange that Django makes it harder to work with migrations when it claims that migrations make everything easy. Am I doing something wrong ? I dont know where to start from.</p>
[ { "answer_id": 74353462, "author": "Jortega", "author_id": 7551712, "author_profile": "https://Stackoverflow.com/users/7551712", "pm_score": 0, "selected": false, "text": "@pytest.mark.parametrize" }, { "answer_id": 74353729, "author": "Ilya", "author_id": 1139541, "author_profile": "https://Stackoverflow.com/users/1139541", "pm_score": 1, "selected": false, "text": "@pytest.mark.parametrize" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9456594/" ]
74,353,280
<p>I am trying to filter this json.</p> <p>here is the json</p> <pre><code>const json = { address: &quot;fdqn&quot;, pDet: [ { pNam: &quot;pnam1&quot;, pMem: [ { mIP: &quot;1234&quot;, // search this string '1234' gp: &quot;gp1&quot; }, { mIP: &quot;567&quot;, gp: &quot;gp2&quot; }, { mIP: &quot;890&quot;, gp: &quot;gp3&quot; } ] }, { pNam: &quot;pnam1&quot;, pMem: [ { mIP: &quot;4567&quot;, gp: &quot;gp5&quot; }, { mIP: &quot;5674&quot;, gp: &quot;gp7&quot; } ] } ] } </code></pre> <p>I need to filter with <strong>mIP = &quot;1234&quot;</strong> and the final output should be.</p> <pre><code>const json = { address: &quot;fdqn&quot;, pDet: [ { pNam: &quot;pnam1&quot;, pMem: [ { mIP: &quot;1234&quot;, gp: &quot;gp1&quot; } ] } ] } </code></pre> <p>i tried with filter and some but seems i need to iterate inside the filter. any input will be appreciated</p>
[ { "answer_id": 74353371, "author": "caTS", "author_id": 18244921, "author_profile": "https://Stackoverflow.com/users/18244921", "pm_score": 3, "selected": true, "text": "flatMap" }, { "answer_id": 74353475, "author": "Ludolfyn", "author_id": 11472399, "author_profile": "https://Stackoverflow.com/users/11472399", "pm_score": 1, "selected": false, "text": "array.reduce()" }, { "answer_id": 74353882, "author": "Scott Sauyet", "author_id": 1243641, "author_profile": "https://Stackoverflow.com/users/1243641", "pm_score": 1, "selected": false, "text": "filterMap" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5471522/" ]
74,353,286
<p>I have a data.table to which I want to add a countdown until a value of 1 appears in the <code>flag</code> column.</p> <pre><code>dt = structure(list(date = structure(19309:19318, class = c(&quot;IDate&quot;, &quot;Date&quot;)), flag = c(0, 0, 0, 0, 0, 1, 0, 0, 0, 1)), class = c(&quot;data.table&quot;, &quot;data.frame&quot;), row.names = c(NA, -10L), .internal.selfref = &lt;pointer: 0x55af7de49cb0&gt;) &gt; dt date flag 1: 2022-11-13 0 2: 2022-11-14 0 3: 2022-11-15 0 4: 2022-11-16 0 5: 2022-11-17 0 6: 2022-11-18 1 7: 2022-11-19 0 8: 2022-11-20 0 9: 2022-11-21 0 10: 2022-11-22 1 </code></pre> <p>Here is the expected output</p> <pre><code> date flag countdown 1: 2022-11-13 0 5 2: 2022-11-14 0 4 3: 2022-11-15 0 3 4: 2022-11-16 0 2 5: 2022-11-17 0 1 6: 2022-11-18 1 0 7: 2022-11-19 0 3 8: 2022-11-20 0 2 9: 2022-11-21 0 1 10: 2022-11-22 1 0 </code></pre> <p>A data.table solution is preferred.</p>
[ { "answer_id": 74353400, "author": "Ric Villalba", "author_id": 6912817, "author_profile": "https://Stackoverflow.com/users/6912817", "pm_score": 4, "selected": true, "text": "library(data.table)\n\ndt = structure(list(date = structure(19309:19318, class = c(\"IDate\", \n\"Date\")), flag = c(0, 0, 0, 0, 0, 1, 0, 0, 0, 1)), class = c( \n\"data.frame\"), row.names = c(NA, -10L))\n\nsetDT(dt)\n\ndt[, countdown := rev(1:.N), by=rleid(flag)][flag==1, countdown:=0 ]\ndt\n#> date flag countdown\n#> 1: 2022-11-13 0 5\n#> 2: 2022-11-14 0 4\n#> 3: 2022-11-15 0 3\n#> 4: 2022-11-16 0 2\n#> 5: 2022-11-17 0 1\n#> 6: 2022-11-18 1 0\n#> 7: 2022-11-19 0 3\n#> 8: 2022-11-20 0 2\n#> 9: 2022-11-21 0 1\n#> 10: 2022-11-22 1 0\n" }, { "answer_id": 74353893, "author": "ThomasIsCoding", "author_id": 12158757, "author_profile": "https://Stackoverflow.com/users/12158757", "pm_score": 1, "selected": false, "text": "data.table" }, { "answer_id": 74433353, "author": "Henrik", "author_id": 1851712, "author_profile": "https://Stackoverflow.com/users/1851712", "pm_score": 1, "selected": false, "text": "sequence" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11939840/" ]
74,353,361
<p><a href="https://i.stack.imgur.com/VW5jS.png" rel="nofollow noreferrer">enter image description here</a>For example I have a start date cell and an end date cell. I also have a conditional format statement that will take these two cells and calculate the progress in % of how complete my project is.</p> <p>For example:</p> <pre><code>Bathroom Renovation: Start 11/7/2022 Finish: 11/9/2022 Progress 33% </code></pre> <p>Here is my excel code to calculate this:</p> <pre><code>=MIN(1, (DATEDIF(E11,TODAY(),&quot;d&quot;)+1)/(DATEDIF(E11,F11,&quot;d&quot;)+1)) </code></pre> <p>I need to add an IFERROR (or some condition like) so that when there is no start or end date is says &quot;Not Started&quot; for example.</p> <p>I have tried this:</p> <pre><code>=IFERROR((DATEDIF(B2,TODAY(),&quot;d&quot;)+1)/(DATEDIF(B2,C2,&quot;d&quot;)+1),&quot;Not start&quot;). </code></pre> <p>That problem that I've run into with this is I am trying to cap the percentage at 100%, and the code statement I started with does that. When I enter this string of code, it works, however when a project is complete it will say 150%, 450%, etc. I need it to also cap at 100%</p>
[ { "answer_id": 74353400, "author": "Ric Villalba", "author_id": 6912817, "author_profile": "https://Stackoverflow.com/users/6912817", "pm_score": 4, "selected": true, "text": "library(data.table)\n\ndt = structure(list(date = structure(19309:19318, class = c(\"IDate\", \n\"Date\")), flag = c(0, 0, 0, 0, 0, 1, 0, 0, 0, 1)), class = c( \n\"data.frame\"), row.names = c(NA, -10L))\n\nsetDT(dt)\n\ndt[, countdown := rev(1:.N), by=rleid(flag)][flag==1, countdown:=0 ]\ndt\n#> date flag countdown\n#> 1: 2022-11-13 0 5\n#> 2: 2022-11-14 0 4\n#> 3: 2022-11-15 0 3\n#> 4: 2022-11-16 0 2\n#> 5: 2022-11-17 0 1\n#> 6: 2022-11-18 1 0\n#> 7: 2022-11-19 0 3\n#> 8: 2022-11-20 0 2\n#> 9: 2022-11-21 0 1\n#> 10: 2022-11-22 1 0\n" }, { "answer_id": 74353893, "author": "ThomasIsCoding", "author_id": 12158757, "author_profile": "https://Stackoverflow.com/users/12158757", "pm_score": 1, "selected": false, "text": "data.table" }, { "answer_id": 74433353, "author": "Henrik", "author_id": 1851712, "author_profile": "https://Stackoverflow.com/users/1851712", "pm_score": 1, "selected": false, "text": "sequence" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20444288/" ]
74,353,385
<p>I am trying to update a helm-deployed deployment so that it uses a secret stored as a k8s secret resource. This <em>must</em> be set as the STORAGE_PASSWORD environment variable in my pod.</p> <p>In my case, the secret is in secrets/redis and the data item is redis-password:</p> <pre> $ kubectl get secret/redis -oyaml apiVersion: v1 data: redis-password: XXXXXXXXXXXXXXXX= kind: Secret metadata: name: redis type: Opaque </pre> <p>I have tried:</p> <pre> $ kubectl set env --from secret/redis deployment/gateway --keys=redis-password Warning: key redis-password transferred to REDIS_PASSWORD deployment.apps/gateway env updated </pre> <p>When I look in my updated deployment manifest, I see the variable has been added but (as suggested) the variable has been set to REDIS_PASSWORD:</p> <pre> - name: REDIS_PASSWORD valueFrom: secretKeyRef: key: redis-password name: redis </pre> <p>I have also tried <code>kubectl patch</code> with a <code>replace</code> operation, but I can't get the syntax correct to have the secret inserted.</p> <p>How do I change the name of the environment variable to STORAGE_PASSWORD?</p>
[ { "answer_id": 74354833, "author": "Wilson Liao", "author_id": 4246782, "author_profile": "https://Stackoverflow.com/users/4246782", "pm_score": 1, "selected": false, "text": "kubectl edit" }, { "answer_id": 74354981, "author": "larsks", "author_id": 147356, "author_profile": "https://Stackoverflow.com/users/147356", "pm_score": 3, "selected": true, "text": "apiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: example\nspec:\n replicas: 1\n template:\n spec:\n containers:\n - image: alpinelinux/darkhttpd\n name: darkhttpd\n args:\n - --port\n - \"9991\"\n ports:\n - name: http\n protocol: TCP\n containerPort: 9991\n env:\n - name: EXAMPLE_VAR\n value: example value\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1238223/" ]
74,353,389
<p>I want to place an icon before the &quot;Mon compte&quot; text on my website.</p> <p>Here is my HTML code :</p> <pre><code>&lt;a href=&quot;/user&quot; class=&quot;secondary-nav__menu-link secondary-nav__menu-link--link secondary-nav__menu-link--level-1&quot; data-drupal-link-system-path=&quot;user&quot;&gt; Mon compte &lt;/a&gt; </code></pre> <p>Here is my CSS code :</p> <pre><code>#block-useraccountmenu a::before { content: &quot;&quot;; display: block; background: url(&quot;/themes/subtheme_olivero/images/person-circle.svg?itok=5&quot;) no-repeat; width: 28px; height: 28px; float: left; margin: 0 6px 0 0; } </code></pre> <p>It works fine, here is the output :</p> <p><a href="https://i.stack.imgur.com/4MQtA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4MQtA.png" alt="enter image description here" /></a></p> <p>My problem is that when I right click on the link, the icon is positioned in the middle of the text. I don't understand why the rendering changes like this :</p> <p><a href="https://i.stack.imgur.com/mNzVL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mNzVL.png" alt="enter image description here" /></a></p> <p>If I click next to it, the icon repositions correctly. How to correct this problem ? What's wrong with my CSS code ? Thanks</p> <p><strong>UPDATE</strong></p> <p>If I apply the CSS to &quot;a&quot; the icon centers over the text, when right clicking on the text.</p> <p>If I apply CSS to &quot;li&quot; it works fine, but I want the face icon to be part of the link.</p> <p>Small clarification, I can't modify the HTML code and I don't want to use an external library for a single icon.</p>
[ { "answer_id": 74354833, "author": "Wilson Liao", "author_id": 4246782, "author_profile": "https://Stackoverflow.com/users/4246782", "pm_score": 1, "selected": false, "text": "kubectl edit" }, { "answer_id": 74354981, "author": "larsks", "author_id": 147356, "author_profile": "https://Stackoverflow.com/users/147356", "pm_score": 3, "selected": true, "text": "apiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: example\nspec:\n replicas: 1\n template:\n spec:\n containers:\n - image: alpinelinux/darkhttpd\n name: darkhttpd\n args:\n - --port\n - \"9991\"\n ports:\n - name: http\n protocol: TCP\n containerPort: 9991\n env:\n - name: EXAMPLE_VAR\n value: example value\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
74,353,391
<p>i want to make some blur in the edges of the recycler view, as you can see in the picture, the top and bottom part are &quot;cut&quot;, i would like to give the sensation of disappearing (like the second image (that image is on figma, so i havent made it on android)), its possible to do that? I dont like the cutted version at all</p> <p><a href="https://i.stack.imgur.com/xaA3j.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xaA3j.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/khL5i.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/khL5i.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74354833, "author": "Wilson Liao", "author_id": 4246782, "author_profile": "https://Stackoverflow.com/users/4246782", "pm_score": 1, "selected": false, "text": "kubectl edit" }, { "answer_id": 74354981, "author": "larsks", "author_id": 147356, "author_profile": "https://Stackoverflow.com/users/147356", "pm_score": 3, "selected": true, "text": "apiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: example\nspec:\n replicas: 1\n template:\n spec:\n containers:\n - image: alpinelinux/darkhttpd\n name: darkhttpd\n args:\n - --port\n - \"9991\"\n ports:\n - name: http\n protocol: TCP\n containerPort: 9991\n env:\n - name: EXAMPLE_VAR\n value: example value\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19861170/" ]
74,353,395
<p>I am using BigQuery and doing a capstone project for a course which needs us to analyze the data for a fictional cycling company. Of the data that we're given, we're given the start and end time of the trips per month including date, hour, minute and second. I have the data in SQL with TIMESTAMP type for started_at and ended_at and TIME type for trip_duration <a href="https://i.stack.imgur.com/c7YFs.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/c7YFs.jpg" alt="enter image description here" /></a> I would like to find the average and median trip per month for the data through SQL. I was able to find the max and min trip, however I could not use simply AVG function to find the average trip duration. What would be the best way to find the average and median times for trips?</p> <p>I tried converting the duration into minutes by :</p> <pre><code>SELECT ended_at, started_at, (ended_at-started_at)*1440, FROM `case-study-367714.case_study.yearly_data` </code></pre> <p>This gave the following result : <a href="https://i.stack.imgur.com/HzWao.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HzWao.jpg" alt="enter image description here" /></a></p> <p>but this does not make sense as the first row is supposed to be 1 hr 26 minutes or 86 minutes, but it is showing 2064 minutes.</p>
[ { "answer_id": 74354833, "author": "Wilson Liao", "author_id": 4246782, "author_profile": "https://Stackoverflow.com/users/4246782", "pm_score": 1, "selected": false, "text": "kubectl edit" }, { "answer_id": 74354981, "author": "larsks", "author_id": 147356, "author_profile": "https://Stackoverflow.com/users/147356", "pm_score": 3, "selected": true, "text": "apiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: example\nspec:\n replicas: 1\n template:\n spec:\n containers:\n - image: alpinelinux/darkhttpd\n name: darkhttpd\n args:\n - --port\n - \"9991\"\n ports:\n - name: http\n protocol: TCP\n containerPort: 9991\n env:\n - name: EXAMPLE_VAR\n value: example value\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20251476/" ]
74,353,409
<p>I'm implementing a function that takes a <code>[[Int]]</code>, and return a <code>[String]</code>, it needs to fill the empty place in each sublist with <code>_</code>s, which index is the complement of the input list, and generate a string from the list, the length of each string is the same and is the (maximum of the input number + 1).</p> <p>For example, if the input is <code>[[1, 2] [0, 1, 2, 3] [1, 3] [0, 2, 3]]</code>, the output would be <code>[&quot;_12_&quot;, &quot;0123&quot;, &quot;_1_3&quot;, &quot;0_23&quot;]</code></p> <p>I tried my best to do this, and don't know how to insert empty space into the missing part.</p> <pre><code>getString :: [[Int]] -&gt; [String] getString x = concat. show. x insert _ where insert _ [] ys = ys </code></pre>
[ { "answer_id": 74353477, "author": "Willem Van Onsem", "author_id": 67579, "author_profile": "https://Stackoverflow.com/users/67579", "pm_score": 2, "selected": true, "text": "[1,2]" }, { "answer_id": 74353653, "author": "Chris", "author_id": 15261315, "author_profile": "https://Stackoverflow.com/users/15261315", "pm_score": 2, "selected": false, "text": "inputs = [[1, 2], [0, 1, 2, 3], [1, 3], [0, 2, 3]]\n\nlistMin = foldl1 min\nlistMax = foldl1 max\n\nminInput = listMin $ map listMin inputs\nmaxInput = listMax $ map listMax inputs\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12425434/" ]
74,353,414
<p><a href="https://i.stack.imgur.com/Qb4YN.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Qb4YN.jpg" alt="enter image description here" /></a></p> <p>I need to replace the (_) in the first range (Red rectangle) into a SPACE in the second range (Green rectangle). How can i do that ? thanks in advance ❤️</p>
[ { "answer_id": 74353545, "author": "player0", "author_id": 5632629, "author_profile": "https://Stackoverflow.com/users/5632629", "pm_score": 2, "selected": false, "text": "=INDEX(SUBSTITUTE(A1:A10; \"_\"; \" \"))\n" }, { "answer_id": 74354181, "author": "Ping", "author_id": 20288037, "author_profile": "https://Stackoverflow.com/users/20288037", "pm_score": 1, "selected": false, "text": "=ArrayFormula(REGEXREPLACE(A1:A,\"_\",\" \"))\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9575989/" ]
74,353,418
<p>So basically, the projection matrix works, as I move the camera arround and look at the cube, there's no problem. But, When I look to the side and the cube should be at the side of the screen, it gets deformed and scaled back.</p> <p>From what I heard, the projection matrix is supposed to be:</p> <ol> <li><p>translate (points - camera)</p> </li> <li><p>rotate by - the angles of the camera so that z is foward. x is right and y is up. You now have points in a 3d coordinate system of the cameras.</p> </li> <li><p>divide x/z and y/z so that points twice as far from you become twice closer to each other.</p> </li> </ol> <p>Step one and step two is taken into account into the projection matrix Step 3 is the perspective.</p> <p>But as I said, it gets fucked when the object isn't at the middle of the screen</p> <p><strong>I tried posting images, but I don'T have the reputation, when I posted links, it says it's spam. I AM forced to upload the code as a whole</strong></p> <p><a href="https://jsfiddle.net/PoutineErable/w3z0mtes/69/" rel="nofollow noreferrer">https://jsfiddle.net/PoutineErable/w3z0mtes/69/</a> This is a version of the code that I modified from a youtube video (in js) that works (asdw) and (ijkl) for player and mouse movement.</p> <p>I tried for arround 4 days to get it working, Today, I took the second video's code in js and made some light modification that allows movement</p> <p>using wasd for movement and ijkl for mouse movement, and it works.</p> <p>Then, I redid my code using the current model.</p> <p>And Even more stripped down if you want, this has no input, just renders an image. Gotta input the view angle</p> <pre><code>import numpy as np import math as m import pygame, sys, random pygame.init() #Needed to get pygame initiated print(&quot;\n&quot;*20+&quot;-&quot;*11,&quot;start of program&quot;,&quot;-&quot;*11) #---------------------------------------------------------Start of math construct #defining constants PI = m.pi WIDTH , HEIGHT = 600, 1000 fov = 70 * PI/180 #initialising the player variables. player_pos = np.array([0,0,-5]) camera_rot_y = PI/180 * float(input(&quot;what's the horizontal angle (degrees)?:&quot;)) camera_rot_x = PI/180 * float(input(&quot;what's the vertical angle (degrees)?:&quot;)) camera_rot_z = 0 #defining math functions def a(x,y): # it's to put (0,0) at the center of the screen ''' (num,num) -&gt; (num,num) takes a coordinates in cartesian and output the number in shitty coordinates png style ''' return(x + WIDTH/2,HEIGHT/2 - y) def b(array): ''' (array or list) -&gt; list takes an arrray corresponding to a coordinates in cartesian | output the coordinate in array form in a shitty png style''' return(a(array[0],array[1])) def Rx(rot_x): #The rotation matrix over the x axis z = np.matrix([ [ 1, 0, 0, 0], [ 0, m.cos(rot_x), m.sin(rot_x), 0], [ 0, -m.sin(rot_x), m.cos(rot_x), 0], [ 0, 0, 0, 1 ] ]) return(z) def Ry(rot_y):#The rotation matrix over the y axis z = np.matrix([ [ m.cos(rot_y), 0,m.sin(rot_y), 0], [ 0, 1, 0, 0], [ -m.sin(rot_y), 0, m.cos(rot_y), 0], [ 0, 0, 0, 1 ], ]) return(z) def Rz(rot_z): #The rotation matrix over the z axis z = np.matrix([ [ m.cos(rot_z), m.sin(rot_z), 0, 0], [- m.sin(rot_z), m.cos(rot_z), 0, 0], [ 0, 0, 1, 0], [ 0, 0, 0, 1 ] ]) return(z) #----------------------------------------------------------------------End of math construct. #initialising the cube: cube_ini = [] for i in [-1,1]: for j in [-1,1]: for k in [-1,1]: cube_ini.append([i,j,k,1]) cube = np.matrix(np.transpose(cube_ini)) #----------------------------------------------------pygame boiler plate part 2 screen = pygame.display.set_mode((WIDTH,HEIGHT)) pygame.display.set_caption(&quot;3d_renderer&quot;) clock = pygame.time.Clock() #-----------------------------------------------------------Start of animation code while True: keys = pygame.key.get_pressed() for event in pygame.event.get(): if event.type == pygame.QUIT or keys[pygame.K_ESCAPE]: pygame.quit() #print(&quot;The program finished running \n \n&quot;) sys.exit() #Creating the projection matrix translation_matrix = np.matrix([[ 1 , 0 , 0 , -player_pos[0]], [ 0 , 1 , 0 , -player_pos[1]], [ 0 , 0 , 1 , -player_pos[2]], [ 0, 0, 0, 1 ]]) rotation_matrix = np.dot(Ry(-camera_rot_y),Rz(-camera_rot_z)) rotation_matrix = np.dot(Rx(-camera_rot_x),rotation_matrix) projection_matrix = np.dot(rotation_matrix,translation_matrix) #making the calculation for the projection of the cube pos_cam_proj = np.dot(projection_matrix,cube) pos_cam_perspective = np.zeros((8,2)) for i in range(8): pos_cam_perspective[i,0] = (0.5 * HEIGHT * pos_cam_proj[0,i] * (1/m.tan(fov))) /pos_cam_proj[2,i] pos_cam_perspective[i,1] = (0.5 * HEIGHT * pos_cam_proj[1,i] * (1/m.tan(fov))) /pos_cam_proj[2,i] cube_screen = np.array(pos_cam_perspective) #-----------------------drawing the lines screen.fill(&quot;Black&quot;) for i in range(8): for j in range(i,8): # pygame.draw.line(screen, &quot;white&quot;, b(cube_screen[i][0:2]),b(cube_screen[j][0:2])) #---final two boiler plate lines pygame.display.update() clock.tick(30) #------------------------------------------------------------End of animation code </code></pre> <p>The snippet of the code of importance:</p> <pre><code>#Creating the projection matrix translation_matrix = np.matrix([[ 1 , 0 , 0 , -player_pos[0]], [ 0 , 1 , 0 , -player_pos[1]], [ 0 , 0 , 1 , -player_pos[2]], [ 0, 0, 0, 1 ]]) rotation_matrix = np.dot(Ry(-camera_rot_y),Rz(-camera_rot_z)) rotation_matrix = np.dot(Rx(-camera_rot_x),rotation_matrix) projection_matrix = np.dot(rotation_matrix,translation_matrix) #making the calculation for the projection of the cube pos_cam_proj = np.dot(projection_matrix,cube) pos_cam_perspective = np.zeros((8,2)) for i in range(8): pos_cam_perspective[i,0] = (0.5 * HEIGHT * pos_cam_proj[0,i] * (1/m.tan(fov))) /pos_cam_proj[2,i] pos_cam_perspective[i,1] = (0.5 * HEIGHT * pos_cam_proj[1,i] * (1/m.tan(fov))) /pos_cam_proj[2,i] cube_screen = np.array(pos_cam_perspective) #-----------------------drawing the lines screen.fill(&quot;Black&quot;) for i in range(8): for j in range(i,8): # pygame.draw.line(screen, &quot;white&quot;, b(cube_screen[i][0:2]),b(cube_screen[j][0:2])) </code></pre>
[ { "answer_id": 74353717, "author": "Rabbid76", "author_id": 5577765, "author_profile": "https://Stackoverflow.com/users/5577765", "pm_score": 1, "selected": false, "text": "fov = 45 * PI/180\nplayer_pos = np.array([0,0,-4], dtype=np.float32) # <-- dtype=np.float32\n#camera_rot_y = PI/180 * float(input(\"what's the horizontal angle (degrees)?:\"))\n#camera_rot_x = PI/180 * float(input(\"what's the vertical angle (degrees)?:\"))\ncamera_rot_y = 0\ncamera_rot_x = 0\ncamera_rot_z = 0\n\n# [...]\n\nangle = 0\nwhile True:\n player_pos[0] = m.sin(m.radians(angle)) * 1.5\n angle += 2\n\n # [...]\n" }, { "answer_id": 74354814, "author": "Self learning student", "author_id": 11718631, "author_profile": "https://Stackoverflow.com/users/11718631", "pm_score": 0, "selected": false, "text": "fov = 60 * PI/180\n# [ ... ]\nplayer_pos = np.array([0,0,-10])\n\n# [ ... ]\n\npos_cam_perspective[i,0] = 0.5 * (1/m.tan(fov/2)) * HEIGHT * pos_cam_proj[0,i] /pos_cam_proj[2,i] \npos_cam_perspective[i,1] = 0.5 * (1/m.tan(fov/2)) * HEIGHT * pos_cam_proj[1,i] /pos_cam_proj[2,i] \n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11718631/" ]
74,353,424
<p>I'm using Python to call an API that returns the last name of some soccer players. One of the players has a &quot;ć&quot; in his name.</p> <p>When I call the endpoint, the name prints out with the unicode attached to it:</p> <pre><code>&gt;&gt;&gt; last_name = (json.dumps(response[&quot;response&quot;][2][&quot;player&quot;][&quot;lastname&quot;])) &gt;&gt;&gt; print(last_name) &quot;Mitrovi\u0107&quot; &gt;&gt;&gt; print(type(last_name)) &lt;class 'str'&gt; </code></pre> <p>If I were to take copy and paste that output and put it in a variable on its own like so:</p> <pre><code>&gt;&gt;&gt; print(&quot;Mitrovi\u0107&quot;) Mitrović &gt;&gt;&gt; print(type(&quot;Mitrovi\u0107&quot;)) &lt;class 'str'&gt; </code></pre> <p>Then it prints just fine?</p> <p>What is wrong with the API endpoint call and the string that comes from it?</p>
[ { "answer_id": 74353717, "author": "Rabbid76", "author_id": 5577765, "author_profile": "https://Stackoverflow.com/users/5577765", "pm_score": 1, "selected": false, "text": "fov = 45 * PI/180\nplayer_pos = np.array([0,0,-4], dtype=np.float32) # <-- dtype=np.float32\n#camera_rot_y = PI/180 * float(input(\"what's the horizontal angle (degrees)?:\"))\n#camera_rot_x = PI/180 * float(input(\"what's the vertical angle (degrees)?:\"))\ncamera_rot_y = 0\ncamera_rot_x = 0\ncamera_rot_z = 0\n\n# [...]\n\nangle = 0\nwhile True:\n player_pos[0] = m.sin(m.radians(angle)) * 1.5\n angle += 2\n\n # [...]\n" }, { "answer_id": 74354814, "author": "Self learning student", "author_id": 11718631, "author_profile": "https://Stackoverflow.com/users/11718631", "pm_score": 0, "selected": false, "text": "fov = 60 * PI/180\n# [ ... ]\nplayer_pos = np.array([0,0,-10])\n\n# [ ... ]\n\npos_cam_perspective[i,0] = 0.5 * (1/m.tan(fov/2)) * HEIGHT * pos_cam_proj[0,i] /pos_cam_proj[2,i] \npos_cam_perspective[i,1] = 0.5 * (1/m.tan(fov/2)) * HEIGHT * pos_cam_proj[1,i] /pos_cam_proj[2,i] \n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17667524/" ]
74,353,433
<blockquote> <p>Does anyone know how to convert a List&lt;Pair&lt;K, Collection&lt; V &gt;&gt;&gt; to Map&lt;K,Collection&lt; V &gt;&gt; in Kotlin, merging the collections associated with the same key?</p> </blockquote> <p>In Java I would use something like:</p> <pre><code>.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (c1, c2) -&gt; { List result = new ArrayList&lt;&gt;(); result.addAll(c1); result.addAll(c2); return result; }) </code></pre> <p>Does Kotlin have a similar device, or a better one? Any advice is appreciated.</p>
[ { "answer_id": 74353723, "author": "Ice", "author_id": 5771474, "author_profile": "https://Stackoverflow.com/users/5771474", "pm_score": 1, "selected": false, "text": "associate" }, { "answer_id": 74353873, "author": "Joffrey", "author_id": 1540818, "author_profile": "https://Stackoverflow.com/users/1540818", "pm_score": 3, "selected": true, "text": "val pairs = listOf(\n 1 to listOf(\"1\", \"2\", \"3\"),\n 1 to listOf(\"4\"),\n 2 to listOf(\"1\", \"2\", \"3\"),\n 3 to listOf(\"1\", \"2\", \"3\"),\n 3 to listOf(\"4\", \"5\", \"6\"),\n)\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19320502/" ]
74,353,447
<p>I am trying to figure out how to calculate a &quot;New Measure&quot; in my power BI visual that calculates the YTD daily average.</p> <p>So for example, my query on the backend would look like this</p> <pre><code>App Date | ID | Subject 01\01\2022 | 123 | Math 01\01\2022 | 456 | Science 01\02\2022 | 789 | Science 01\02\2022 | 012 | History 01\03\2022 | 345 | Science 01\03\2022 | 678 | History 01\03\2022 | 921 | Art 01\03\2022 | 223 | Science 01\04\2022 | 256 | English </code></pre> <p>Im trying to calculate what the daily average is YTD for math, science, history etc.</p> <p>I tried</p> <p>1 Daily average = calculate (average(Query[app date]))</p> <p>I know this is not correct but I would appreciate any help..</p>
[ { "answer_id": 74353723, "author": "Ice", "author_id": 5771474, "author_profile": "https://Stackoverflow.com/users/5771474", "pm_score": 1, "selected": false, "text": "associate" }, { "answer_id": 74353873, "author": "Joffrey", "author_id": 1540818, "author_profile": "https://Stackoverflow.com/users/1540818", "pm_score": 3, "selected": true, "text": "val pairs = listOf(\n 1 to listOf(\"1\", \"2\", \"3\"),\n 1 to listOf(\"4\"),\n 2 to listOf(\"1\", \"2\", \"3\"),\n 3 to listOf(\"1\", \"2\", \"3\"),\n 3 to listOf(\"4\", \"5\", \"6\"),\n)\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20435318/" ]
74,353,450
<p>I try to make a very simple site that is only displaying an embedded PDF. The PDF viewer should have the same size as the browser window. However, I was unsuccessful in showing the full PDF height:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html height=&quot;100vh&quot; margin=&quot;0&quot;&gt; &lt;body height=&quot;100vh&quot; margin=&quot;0&quot;&gt; &lt;embed src=&quot;http://infolab.stanford.edu/pub/papers/google.pdf#toolbar=0&amp;navpanes=0&amp;scrollbar=0&quot; width=&quot;100%&quot; height=&quot;100vh&quot; type=&quot;application/pdf&quot;&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>The output looks like this in different browser I tried (Safari, Chrome, Firefox - all on macOS Ventura): <a href="https://i.stack.imgur.com/DPruB.png" rel="nofollow noreferrer">https://i.stack.imgur.com/DPruB.png</a></p> <p>I already tried to set the height to 100% instead or exchanging height with min-height. But for any reason, it does not work. Setting the margins/paddings to 0 as recommended in other posts has also no result</p>
[ { "answer_id": 74353490, "author": "vnetkc", "author_id": 3421628, "author_profile": "https://Stackoverflow.com/users/3421628", "pm_score": 1, "selected": false, "text": "body {\n margin: 0;\n}\n\nbody,\nembed {\n height: 100vh;\n width: 100vw;\n}" }, { "answer_id": 74354395, "author": "K J", "author_id": 10802527, "author_profile": "https://Stackoverflow.com/users/10802527", "pm_score": 1, "selected": true, "text": "<!DOCTYPE html><head><style>\nhtml, body, embed, iframe, object { margin: 0!important; border: 0; width: 99vw; height: 97vh; }\n</style></head><body><center>\n <embed src=\"http://infolab.stanford.edu/pub/papers/google.pdf#toolbar=0&navpanes=0\" type=\"application/pdf\" />\n</center></body></html>\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20444344/" ]
74,353,463
<p>I have a table as following:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>a</th> <th>b</th> <th>a</th> <th>b</th> </tr> </thead> <tbody> <tr> <td>123</td> <td>1</td> <td>6</td> <td>7</td> <td>3</td> </tr> <tr> <td>456</td> <td>2</td> <td>8</td> <td>9</td> <td>7</td> </tr> </tbody> </table> </div> <p>What function in python can I use to stack the columns with the name names on top of each other like the following?</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>a</th> <th>b</th> </tr> </thead> <tbody> <tr> <td>123</td> <td>1</td> <td>6</td> </tr> <tr> <td>123</td> <td>7</td> <td>3</td> </tr> <tr> <td>456</td> <td>2</td> <td>8</td> </tr> <tr> <td>456</td> <td>9</td> <td>7</td> </tr> </tbody> </table> </div>
[ { "answer_id": 74353490, "author": "vnetkc", "author_id": 3421628, "author_profile": "https://Stackoverflow.com/users/3421628", "pm_score": 1, "selected": false, "text": "body {\n margin: 0;\n}\n\nbody,\nembed {\n height: 100vh;\n width: 100vw;\n}" }, { "answer_id": 74354395, "author": "K J", "author_id": 10802527, "author_profile": "https://Stackoverflow.com/users/10802527", "pm_score": 1, "selected": true, "text": "<!DOCTYPE html><head><style>\nhtml, body, embed, iframe, object { margin: 0!important; border: 0; width: 99vw; height: 97vh; }\n</style></head><body><center>\n <embed src=\"http://infolab.stanford.edu/pub/papers/google.pdf#toolbar=0&navpanes=0\" type=\"application/pdf\" />\n</center></body></html>\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353463", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18374702/" ]
74,353,497
<p>I am trying to find a way to make Chakra UI code work with react 18 in an next js app.</p> <p>When i try to use a component which starts with a component, I get an error that says:</p> <blockquote> <p>Unexpected token <code>Stack</code>. Expected jsx identifier</p> </blockquote> <p>I've tried adding outer and and &lt;React.Fragment&gt; tags to the component - each time, I get the same error.</p> <p>What is the jsx identifier that satisfies this requirement?</p> <p>The full page is:</p> <pre><code>import * as React from &quot;react&quot; import { gql } from &quot;@apollo/client&quot; import { AlertDialog, AlertDialogBody, AlertDialogContent, AlertDialogFooter, AlertDialogHeader, AlertDialogOverlay, Box, Button, Center, Flex, Spinner, Stack, Text, useDisclosure, } from &quot;@chakra-ui/react&quot; import { useDestroyAccountMutation } from &quot;lib/graphql&quot; import { useLogout } from &quot;lib/hooks/useLogout&quot; import { useMe } from &quot;lib/hooks/useMe&quot; import { useMutationHandler } from &quot;lib/hooks/useMutationHandler&quot; import { withAuth } from &quot;components/hoc/withAuth&quot; import { HomeLayout } from &quot;components/HomeLayout&quot; import { ProfileLayout } from &quot;components/ProfileLayout&quot; import { Tile, TileBody, TileFooter, TileHeader, TileHeading } from &quot;components/Tile&quot; const _ = gql` mutation DestroyAccount { destroyAccount } ` function Settings() { const alertProps = useDisclosure() const { me, loading } = useMe() const logout = useLogout() const cancelRef = React.useRef&lt;HTMLButtonElement&gt;(null) const handler = useMutationHandler() const [destroy, { loading: destroyLoading }] = useDestroyAccountMutation() const handleDestroy = () =&gt; { return handler(destroy, { onSuccess: () =&gt; logout() }) } if (loading) return ( &lt;Center&gt; &lt;Spinner /&gt; &lt;/Center&gt; ) if (!me) return null return ( &lt;Stack spacing={6}&gt; &lt;Tile&gt; &lt;TileHeader&gt; &lt;TileHeading&gt;Danger zone&lt;/TileHeading&gt; &lt;/TileHeader&gt; &lt;TileBody&gt; &lt;&gt; &lt;Text fontSize=&quot;sm&quot;&gt; paragraph 1. &lt;/Text&gt; &lt;Text fontSize=&quot;sm&quot; mt=&quot;30px&quot;&gt; paragraph 2. &lt;Text /&gt; &lt;/&gt; &lt;/TileBody&gt; &lt;TileFooter&gt; &lt;Flex w=&quot;100%&quot; justify=&quot;flex-end&quot;&gt; &lt;Button size=&quot;sm&quot; colorScheme=&quot;red&quot; isDisabled={destroyLoading} isLoading={destroyLoading} onClick={alertProps.onOpen} &gt; Delete &lt;/Button&gt; &lt;/Flex&gt; &lt;AlertDialog {...alertProps} motionPreset=&quot;slideInBottom&quot; isCentered leastDestructiveRef={cancelRef} &gt; &lt;AlertDialogOverlay&gt; &lt;AlertDialogContent&gt; &lt;AlertDialogHeader fontSize=&quot;lg&quot; fontWeight=&quot;bold&quot;&gt; Delete account &lt;/AlertDialogHeader&gt; &lt;AlertDialogBody&gt;Are you sure? &lt;/AlertDialogBody&gt; &lt;AlertDialogFooter&gt; &lt;Button ref={cancelRef} onClick={alertProps.onClose}&gt; Cancel &lt;/Button&gt; &lt;Button colorScheme=&quot;red&quot; onClick={handleDestroy} isLoading={destroyLoading} isDisabled={destroyLoading} ml={3} &gt; Delete &lt;/Button&gt; &lt;/AlertDialogFooter&gt; &lt;/AlertDialogContent&gt; &lt;/AlertDialogOverlay&gt; &lt;/AlertDialog&gt; &lt;/TileFooter&gt; &lt;/Tile&gt; &lt;/Stack&gt; ) } Settings.getLayout = (page: React.ReactNode) =&gt; ( &lt;HomeLayout&gt; &lt;ProfileLayout&gt;{page}&lt;/ProfileLayout&gt; &lt;/HomeLayout&gt; ) export default withAuth(Settings) </code></pre>
[ { "answer_id": 74353490, "author": "vnetkc", "author_id": 3421628, "author_profile": "https://Stackoverflow.com/users/3421628", "pm_score": 1, "selected": false, "text": "body {\n margin: 0;\n}\n\nbody,\nembed {\n height: 100vh;\n width: 100vw;\n}" }, { "answer_id": 74354395, "author": "K J", "author_id": 10802527, "author_profile": "https://Stackoverflow.com/users/10802527", "pm_score": 1, "selected": true, "text": "<!DOCTYPE html><head><style>\nhtml, body, embed, iframe, object { margin: 0!important; border: 0; width: 99vw; height: 97vh; }\n</style></head><body><center>\n <embed src=\"http://infolab.stanford.edu/pub/papers/google.pdf#toolbar=0&navpanes=0\" type=\"application/pdf\" />\n</center></body></html>\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353497", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2860931/" ]
74,353,511
<p>How to give an animation to the div tag when it is displayed (click on button)?</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>function toggle_div_fun(id) {  var divelement = document.getElementById(id);  if (divelement.style.display == 'flex') divelement.style.display = 'none';  else divelement.style.display = 'flex'; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;button class="eco-btn" onclick="toggle_div_fun('sectiontohide');"&gt;Click here&lt;/button&gt; &lt;div id="sectiontohide"&gt;This is the div to hide&lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74353490, "author": "vnetkc", "author_id": 3421628, "author_profile": "https://Stackoverflow.com/users/3421628", "pm_score": 1, "selected": false, "text": "body {\n margin: 0;\n}\n\nbody,\nembed {\n height: 100vh;\n width: 100vw;\n}" }, { "answer_id": 74354395, "author": "K J", "author_id": 10802527, "author_profile": "https://Stackoverflow.com/users/10802527", "pm_score": 1, "selected": true, "text": "<!DOCTYPE html><head><style>\nhtml, body, embed, iframe, object { margin: 0!important; border: 0; width: 99vw; height: 97vh; }\n</style></head><body><center>\n <embed src=\"http://infolab.stanford.edu/pub/papers/google.pdf#toolbar=0&navpanes=0\" type=\"application/pdf\" />\n</center></body></html>\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19601407/" ]
74,353,528
<p>I'm currently trying to write a method that goes through a list of Ant-Objects and returns a list of <code>AntScouts</code>, that extend Ant. In general, <code>List&lt;Ant&gt;</code> can contain a lot of different Objects that inherit from Ant.</p> <p>I also have an enum for the different kinds of ants:</p> <pre><code>public enum AntType { QUEEN,WARRIOR,GATHERER,SCOUT; public Class getClass(AntType type){ return switch (type) { case QUEEN -&gt; AntQueen.class; case WARRIOR -&gt; AntWarrior.class; case GATHERER -&gt; AntGatherer.class; case SCOUT -&gt; AntScout.class; }; } } </code></pre> <p>This enum causes a warning:</p> <pre><code>Raw use of parameterized class 'Class' </code></pre> <p>And this is the method that currently returns a <code>List&lt;Ant&gt;</code>.</p> <pre><code>public List&lt;Ant&gt; getAntsType(AntType type){ return ants.stream().filter(ant -&gt; ant.getType() == type).toList(); } </code></pre> <p>How can I write the method so that it get's the <code>AntType</code> enum as argument and returns a <code>List&lt;AntScout&gt;</code> or <code>List&lt;AntWarrior&gt;</code> corresponding to the enum? I REALLY don't want to use <code>Class&lt;T&gt;</code> clazz as argument since that would defeat the point of the enum. (I also use that enum elsewhere, so I can't get rid of it)</p> <p>How can I write the method so that it get's the AntType enum as argument and returns a List or List corresponding to the enum?</p> <p>Edit: This comment probably comes closest to the desired solution: <a href="https://stackoverflow.com/questions/74353528/java-method-that-returns-different-types-of-generic-lists/74353687?noredirect=1#comment131265415_74353687">Java Method that returns different types of generic Lists</a></p>
[ { "answer_id": 74353657, "author": "Holloway", "author_id": 1916917, "author_profile": "https://Stackoverflow.com/users/1916917", "pm_score": 0, "selected": false, "text": "AntType" }, { "answer_id": 74353687, "author": "Jared Renzullo", "author_id": 20409306, "author_profile": "https://Stackoverflow.com/users/20409306", "pm_score": 0, "selected": false, "text": "public enum AntType {\n QUEEN,WARRIOR,GATHERER,SCOUT;\n\n public Class<? extends Ant> getImplClass(){\n return switch (this) {\n case QUEEN -> AntQueen.class;\n case WARRIOR -> AntWarrior.class;\n case GATHERER -> AntGatherer.class;\n case SCOUT -> AntScout.class;\n };\n }\n}\n" }, { "answer_id": 74353767, "author": "Victor Stafusa - FORABOZO", "author_id": 540552, "author_profile": "https://Stackoverflow.com/users/540552", "pm_score": 0, "selected": false, "text": "enum" }, { "answer_id": 74354650, "author": "Alexander Ivanchenko", "author_id": 17949945, "author_profile": "https://Stackoverflow.com/users/17949945", "pm_score": 3, "selected": true, "text": "Ant" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19056337/" ]
74,353,529
<p>I'm trying to figure out how to add a favicon file to a next.js app (with react 18).</p> <p>I have made a _document page that has a head tag as follows:</p> <pre><code>import * as React from &quot;react&quot; // import {createRoot} from 'react-dom/client' import { ColorModeScript } from &quot;@chakra-ui/react&quot; import Document, { Head, Html, Main, NextScript } from &quot;next/document&quot; import Favicon from &quot;../components/Favicon&quot; export default class AppDocument extends Document { static getInitialProps(ctx: any) { return Document.getInitialProps(ctx) } render() { return ( &lt;Html lang=&quot;en&quot;&gt; &lt;Head&gt; &lt;meta name=&quot;theme-color&quot; key=&quot;theme-color&quot; content=&quot;#000000&quot; /&gt; &lt;meta name=&quot;description&quot; content=&quot;name&quot; key=&quot;description&quot; /&gt; &lt;meta property=&quot;og:title&quot; content=&quot;title goes here&quot; key=&quot;title&quot; /&gt; &lt;meta property=&quot;og:description&quot; content=&quot;description goes here&quot; key=&quot;og:description&quot; /&gt; &lt;link rel=&quot;preconnect&quot; href=&quot;https://fonts.googleapis.com&quot; /&gt; &lt;link rel=&quot;preconnect&quot; href=&quot;https://fonts.gstatic.com&quot; /&gt; &lt;Favicon /&gt; &lt;/Head&gt; &lt;body&gt; &lt;Main /&gt; &lt;NextScript /&gt; &lt;/body&gt; &lt;/Html&gt; ) } } </code></pre> <p>I then made a component called Favicon with:</p> <p>import React from &quot;react&quot;;</p> <pre><code>const Favicon = (): JSX.Element =&gt; { return ( &lt;React.Fragment&gt; &lt;link rel=&quot;apple-touch-icon&quot; sizes=&quot;76x76&quot; href=&quot;/apple-touch-icon.png&quot; /&gt; &lt;link rel=&quot;icon&quot; type=&quot;image/png&quot; sizes=&quot;32x32&quot; href=&quot;/favicon-32x32.png&quot; /&gt; &lt;link rel=&quot;icon&quot; type=&quot;image/png&quot; sizes=&quot;16x16&quot; href=&quot;/favicon-16x16.png&quot; /&gt; &lt;link rel=&quot;manifest&quot; href=&quot;/site.webmanifest&quot; /&gt; &lt;link rel=&quot;mask-icon&quot; href=&quot;/safari-pinned-tab.svg&quot; color=&quot;#5bbad5&quot; /&gt; &lt;meta name=&quot;msapplication-TileColor&quot; content=&quot;#da532c&quot; /&gt; &lt;meta name=&quot;theme-color&quot; content=&quot;#ffffff&quot; /&gt; &lt;/React.Fragment&gt; ) } export default Favicon; </code></pre> <p>I then made a root/packages/src/public folder (this folder is at the same level and place as the pages folder that has the _document.tsx file) and saved each of the assets to it.</p> <p>I don't get an error, but the favicon does not populate in the browser tab.</p> <p>How can I add a favicon in nextjs?</p> <p>I also tried removing the Favicon component and moving the meta tags directly to app.tsx. It still doesnt render the favicon.</p> <p>I can see from the console errors that the files are not found. They are all saved in the project at public/[file name]. Public is a folder at the same level as the pages directory.</p> <p><a href="https://i.stack.imgur.com/WMKfh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WMKfh.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74353964, "author": "innocent masuki", "author_id": 10766490, "author_profile": "https://Stackoverflow.com/users/10766490", "pm_score": 0, "selected": false, "text": "import { NextSeo } from \"next-seo\"\nimport type { OpenGraph } from \"next-seo/lib/types\"\nimport { useRouter } from \"next/router\"\n\nimport type { MetaProps } from \"../../types/content\"\n\nexport const Meta = ({\n type = \"website\",\n siteName = \"My-site-name\",\n data,\n}: MetaProps): React.ReactElement => {\n const router = useRouter()\n\n // TODO Make generator based on different data\n const seoData = data\n const locale = \"en_EN\"\n const baseURL = process.env.BASE_URL || window.location.origin\n const currentURL = baseURL + router.asPath\n\n const seo = {\n title: seoData.title,\n titleTemplate: `%s - ${siteName}`,\n defaultTitle: siteName,\n canonical: currentURL,\n }\n\n const openGraph: OpenGraph = {\n title: seoData.title,\n type,\n locale,\n url: currentURL,\n site_name: siteName,\n images: seoData.images,\n }\n\n const metaLinks = [\n {\n rel: \"icon\",\n type: \"image/svg+xml\",\n href: \"/favicon.svg\",\n },\n {\n rel: \"apple-touch-icon\",\n href: \"/touch-icon-ipad.jpg\",\n sizes: \"180x180\",\n },\n {\n rel: \"mask-icon\",\n type: \"image/svg+xml\",\n color: \"#0d2e41\",\n href: \"/favicon.svg\",\n },\n {\n rel: \"icon\",\n href: \"/favicon.ico\",\n },\n ]\n\n return (\n <NextSeo\n {...seo}\n openGraph={openGraph}\n additionalLinkTags={metaLinks}\n noindex={data.requireAuth || data.noIndex}\n />\n )\n}" }, { "answer_id": 74392633, "author": "bknights", "author_id": 3806017, "author_profile": "https://Stackoverflow.com/users/3806017", "pm_score": 0, "selected": false, "text": "import {Html, Head, Main, NextScript} from 'next/document';\n\nexport default function Document() {\n\n return (\n <Html lang=\"en\">\n <Head>\n <link rel=\"shortcut icon\" href=\"/site/images/favicon.ico\" />\n...\n" }, { "answer_id": 74425444, "author": "Yilmaz", "author_id": 10262805, "author_profile": "https://Stackoverflow.com/users/10262805", "pm_score": 0, "selected": false, "text": "import Head from \"next/head\";\n\n<Head>\n // If favicon path is public/images/\n <link rel=\"icon\" type=\"image/x-icon\" href=\"/images/favicon.ico\" />\n\n</Head>\n" }, { "answer_id": 74425997, "author": "SnazzyBytes", "author_id": 14405156, "author_profile": "https://Stackoverflow.com/users/14405156", "pm_score": 0, "selected": false, "text": "import Head from \"next/head\"\nconst Layout = ({ children, home }: Props) => {\n return (\n <>\n <div className={styles.container}>\n <Head>\n <link rel=\"icon\" type=\"image/svg\" href=\"/icons/YOURICON.svg\" />\n ....rest of your <meta> tags for SEO ....\n </Head>\n ....rest of your html/jsx like page header/main-stage/footer/etc..\n)}\n" }, { "answer_id": 74426265, "author": "Pablopvsky", "author_id": 11221580, "author_profile": "https://Stackoverflow.com/users/11221580", "pm_score": 0, "selected": false, "text": "imagemagick" }, { "answer_id": 74454232, "author": "SilentRhetoric", "author_id": 14925090, "author_profile": "https://Stackoverflow.com/users/14925090", "pm_score": 1, "selected": false, "text": "<Head>" }, { "answer_id": 74457674, "author": "Saeed Mansouri", "author_id": 9229280, "author_profile": "https://Stackoverflow.com/users/9229280", "pm_score": 1, "selected": false, "text": "favicon" }, { "answer_id": 74550982, "author": "Dhiraj Suthar", "author_id": 20332109, "author_profile": "https://Stackoverflow.com/users/20332109", "pm_score": 0, "selected": false, "text": "import Head from \"next/head\";\n\n<Head>\n <link rel=\"icon\" href=\"/favicon.ico\" />\n</Head> \n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2860931/" ]
74,353,534
<p>I have a widget that for whatever reason does not want to go to the bottom of the screen. Right now the screen looks like:</p> <pre><code>body: Stack( children: &lt;Widget&gt;[ SingleChildScrollView( child: //make a widget that looks like twitter composing tweet Column( children: [ //make a widget that looks like twitter composing tweet Container( padding: const EdgeInsets.all(16), child: Row( children: [ //make a widget that looks like twitter composing tweet CircleAvatar( radius: 20, backgroundImage: NetworkImage(user.imageUrls[0]), ), //make a widget that looks like twitter composing tweet const SizedBox( width: 16, ), //make a widget that looks like twitter composing tweet Expanded( child: TextField( maxLength: 280, controller: _textEditingController, maxLines: null, decoration: InputDecoration( hintText: 'What\'s happening?', border: InputBorder.none, ), ), ), ], ), ), //make a widget that looks like twitter composing tweet if (_image != null) Image.file( _image!, height: 200, width: 200, ), Align( alignment: Alignment.bottomCenter, child: ComposeBottomIconWidget( onImageIconSelected: _onImageIconSelected, textEditingController: _textEditingController, ), ), ], ), ), ], ), </code></pre> <p>Which results in:</p> <p><a href="https://i.stack.imgur.com/xrPNE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xrPNE.png" alt="enter image description here" /></a></p> <p>Any idea why this is looking like this? The widget is wrapped in an alignment, but still does not change. Any thoughts are appreciated, thanks!</p>
[ { "answer_id": 74353964, "author": "innocent masuki", "author_id": 10766490, "author_profile": "https://Stackoverflow.com/users/10766490", "pm_score": 0, "selected": false, "text": "import { NextSeo } from \"next-seo\"\nimport type { OpenGraph } from \"next-seo/lib/types\"\nimport { useRouter } from \"next/router\"\n\nimport type { MetaProps } from \"../../types/content\"\n\nexport const Meta = ({\n type = \"website\",\n siteName = \"My-site-name\",\n data,\n}: MetaProps): React.ReactElement => {\n const router = useRouter()\n\n // TODO Make generator based on different data\n const seoData = data\n const locale = \"en_EN\"\n const baseURL = process.env.BASE_URL || window.location.origin\n const currentURL = baseURL + router.asPath\n\n const seo = {\n title: seoData.title,\n titleTemplate: `%s - ${siteName}`,\n defaultTitle: siteName,\n canonical: currentURL,\n }\n\n const openGraph: OpenGraph = {\n title: seoData.title,\n type,\n locale,\n url: currentURL,\n site_name: siteName,\n images: seoData.images,\n }\n\n const metaLinks = [\n {\n rel: \"icon\",\n type: \"image/svg+xml\",\n href: \"/favicon.svg\",\n },\n {\n rel: \"apple-touch-icon\",\n href: \"/touch-icon-ipad.jpg\",\n sizes: \"180x180\",\n },\n {\n rel: \"mask-icon\",\n type: \"image/svg+xml\",\n color: \"#0d2e41\",\n href: \"/favicon.svg\",\n },\n {\n rel: \"icon\",\n href: \"/favicon.ico\",\n },\n ]\n\n return (\n <NextSeo\n {...seo}\n openGraph={openGraph}\n additionalLinkTags={metaLinks}\n noindex={data.requireAuth || data.noIndex}\n />\n )\n}" }, { "answer_id": 74392633, "author": "bknights", "author_id": 3806017, "author_profile": "https://Stackoverflow.com/users/3806017", "pm_score": 0, "selected": false, "text": "import {Html, Head, Main, NextScript} from 'next/document';\n\nexport default function Document() {\n\n return (\n <Html lang=\"en\">\n <Head>\n <link rel=\"shortcut icon\" href=\"/site/images/favicon.ico\" />\n...\n" }, { "answer_id": 74425444, "author": "Yilmaz", "author_id": 10262805, "author_profile": "https://Stackoverflow.com/users/10262805", "pm_score": 0, "selected": false, "text": "import Head from \"next/head\";\n\n<Head>\n // If favicon path is public/images/\n <link rel=\"icon\" type=\"image/x-icon\" href=\"/images/favicon.ico\" />\n\n</Head>\n" }, { "answer_id": 74425997, "author": "SnazzyBytes", "author_id": 14405156, "author_profile": "https://Stackoverflow.com/users/14405156", "pm_score": 0, "selected": false, "text": "import Head from \"next/head\"\nconst Layout = ({ children, home }: Props) => {\n return (\n <>\n <div className={styles.container}>\n <Head>\n <link rel=\"icon\" type=\"image/svg\" href=\"/icons/YOURICON.svg\" />\n ....rest of your <meta> tags for SEO ....\n </Head>\n ....rest of your html/jsx like page header/main-stage/footer/etc..\n)}\n" }, { "answer_id": 74426265, "author": "Pablopvsky", "author_id": 11221580, "author_profile": "https://Stackoverflow.com/users/11221580", "pm_score": 0, "selected": false, "text": "imagemagick" }, { "answer_id": 74454232, "author": "SilentRhetoric", "author_id": 14925090, "author_profile": "https://Stackoverflow.com/users/14925090", "pm_score": 1, "selected": false, "text": "<Head>" }, { "answer_id": 74457674, "author": "Saeed Mansouri", "author_id": 9229280, "author_profile": "https://Stackoverflow.com/users/9229280", "pm_score": 1, "selected": false, "text": "favicon" }, { "answer_id": 74550982, "author": "Dhiraj Suthar", "author_id": 20332109, "author_profile": "https://Stackoverflow.com/users/20332109", "pm_score": 0, "selected": false, "text": "import Head from \"next/head\";\n\n<Head>\n <link rel=\"icon\" href=\"/favicon.ico\" />\n</Head> \n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19097292/" ]
74,353,559
<p>since this is the first discussion topic, forgive me in advance if I'm wrong. My question will be, I have an example of a CSV file in the form of '.txt' and I am using this file.</p> <ul> <li>Name</li> <li>Address</li> <li>Direction</li> <li>Status</li> <li>Duration</li> <li>Date</li> </ul> <p>I want to get values like . I used CSVHelper, either I couldn't do it or the formats I wanted were not in that package. Thanks in advance to those who will help. Attached is the file I want to parse;</p> <pre> <b>Name,Address,Direction,Status,Duration,Date</b> Berat Bey Dörtsan,"05315554622",Outgoing,Unanswered,00:00,00:00,8/4/2022 (9:25:48 AM) Berat Bey Dörtsan,"05315554622",Outgoing,Answered,00:47,00:47,8/4/2022 (9:27:55 AM) Berat Bey Dörtsan,"05315554622",Incoming,Answered,00:54,00:54,8/4/2022 (9:35:02 AM) Berat Bey Dörtsan,"05315554622",Outgoing,Answered,00:19,00:19,8/4/2022 (2:58:43 PM) Berat Bey Dörtsan,"05315554622",Outgoing,Answered,00:49,00:49,8/5/2022 (9:21:52 AM) Berat Bey Dörtsan,"05315554622",Incoming,Answered,01:56,01:56,8/16/2022 (10:17:55 AM) Berat Bey Dörtsan,"05315554622",Outgoing,Answered,00:47,00:47,9/7/2022 (11:02:33 AM) Berat Bey Dörtsan,"05315554622",Outgoing,Answered,01:19,01:19,9/7/2022 (11:04:35 AM) Berat Bey Dörtsan,"05315554622",Outgoing,Answered,01:57,01:57,9/7/2022 (11:07:20 AM) Berat Bey Dörtsan,"05315554622",Outgoing,Answered,04:59,04:59,9/7/2022 (11:12:54 AM) Berat Bey Dörtsan,"05315554622",Outgoing,Answered,01:50,01:50,9/7/2022 (11:18:36 AM) Berat Bey Dörtsan,"05315554622",Incoming,Answered,00:37,00:37,9/7/2022 (11:36:36 AM) Berat Bey Dörtsan,"05315554622",Outgoing,Answered,00:59,00:59,9/7/2022 (11:55:19 AM) Berat Bey Dörtsan,"05315554622",Incoming,Missed,00:00,00:00,9/7/2022 (12:15:26 PM) Berat Bey Dörtsan,"05315554622",Outgoing,Unanswered,00:00,00:00,9/7/2022 (12:21:12 PM) Berat Bey Dörtsan,"05315554622",Outgoing,Unanswered,00:00,00:00,9/7/2022 (12:21:24 PM) Berat Bey Dörtsan,"05315554622",Outgoing,Answered,00:18,00:18,9/7/2022 (12:36:08 PM) </pre> <p>i tried to do it this way;</p> <ul> <li>Name = Berat Bey Dörtsan</li> <li>Address = 05315554466</li> <li>Direction = Outgoing</li> <li>Status = Unanswered</li> <li>Duration = 00:54 - 01:56</li> <li>Date = 8/4/2022 (9:25:48 AM)</li> </ul> <p>and i was used these codes;</p> <pre><code>using CsvHelper; using CsvHelper.Configuration.Attributes; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace TextVeriCekme { public partial class Form1 : Form { String csvPath = &quot;&quot;; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { OpenFileDialog ofd = new OpenFileDialog { Title = &quot;CSV Dosyası Aç&quot;, Filter = &quot;csv files (*.csv)|*.csv&quot;, CheckFileExists = true, CheckPathExists = true }; if (ofd.ShowDialog() == DialogResult.OK) { MessageBox.Show(ofd.FileName); csvPath = ofd.FileName; } } public class Foo { public string Name { get; set; } public string Address { get; set; } public string Direction { get; set; } public string Status { get; set; } public string Duration { get; set; } [Name(&quot;Date&quot;)] [Format(&quot;dd-MM-yyyy&quot;)] public DateTime Date { get; set; } } int sayac = 0; private void button2_Click(object sender, EventArgs e) { IEnumerable&lt;Foo&gt; records = null; List&lt;Foo&gt; list = null; using (var reader = new StreamReader(csvPath)) using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture)) { records = csv.GetRecords&lt;Foo&gt;(); list = records.ToList(); MessageBox.Show(&quot;Toplam Kayıt : &quot; + records.Count().ToString()); foreach (Foo record in list) { if (sayac == 1) { MessageBox.Show(record.Name); MessageBox.Show(record.Address); MessageBox.Show(record.Direction); MessageBox.Show(record.Status); MessageBox.Show(record.Duration); MessageBox.Show(record.Date.ToString()); } sayac++; } } } } } </code></pre> <p>this way I can't get 'Date' variable. what i want to do in general is a windows form to keep these call logs (date and time).</p>
[ { "answer_id": 74353936, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 1, "selected": false, "text": "Foo" }, { "answer_id": 74376663, "author": "David Specht", "author_id": 2355006, "author_profile": "https://Stackoverflow.com/users/2355006", "pm_score": 0, "selected": false, "text": "Duration" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18529651/" ]
74,353,573
<p>I want to display a double (or int) similar to how you would a string with a <code>Text()</code> widget. Is there an equivalent to this widget for ints or doubles in Flutter? Sorry if this is obvious, but I could not find anything.</p>
[ { "answer_id": 74353619, "author": "Michael Horn", "author_id": 8174223, "author_profile": "https://Stackoverflow.com/users/8174223", "pm_score": 0, "selected": false, "text": "Text" }, { "answer_id": 74353737, "author": "Lance Olana", "author_id": 18730456, "author_profile": "https://Stackoverflow.com/users/18730456", "pm_score": 2, "selected": true, "text": "Text(\"${<Your double/int variable>\"})\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16806413/" ]
74,353,575
<pre><code>macbookair@Furqans-MacBook-2021 ~ % ssh -T furqanistic@github.com /etc/ssh/sshd_config.d/100-macos.conf: line 2: Bad configuration option: usepam /etc/ssh/sshd_config.d/100-macos.conf: line 3: Bad configuration option: acceptenv /etc/ssh/sshd_config.d/100-macos.conf: line 4: Bad configuration option: subsystem /etc/ssh/sshd_config.d/100-macos.conf: terminating, 3 bad configuration options macbookair@Furqans-MacBook-2021 ~ % sudo nano /etc/ssh/sshd_config </code></pre> <p>When ever i try &quot;ssh -T furqanistic@github.com &quot; OR &quot;ssh root@&quot; OR push my branch it shows me this error</p>
[ { "answer_id": 74357405, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 0, "selected": false, "text": "sshd_config" }, { "answer_id": 74362355, "author": "Furqan", "author_id": 19953575, "author_profile": "https://Stackoverflow.com/users/19953575", "pm_score": 2, "selected": false, "text": "sudo nano ~/.ssh/config\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19953575/" ]
74,353,582
<p>The problem is &quot; Conversion = '-'&quot;. The source code is listed below. This is a program used to caculating the value of Coefficent A, B, and C based on the quadratic function.</p> <pre><code>import java.util.Scanner; public class RootsTestHamer { public static void main(String[] args) { //declare variables double a, b, c; double r1, r2; Scanner input = new Scanner(System.in); // Create a Scanner // prompts user to enter values for coefficents A, B, and C System.out.print(&quot;Enter the A coefficent:&quot;); a = input.nextDouble(); System.out.print(&quot;Enter the B coefficent:&quot;); b = input.nextDouble(); System.out.print(&quot;Enter the C coefficent:&quot;); c = input.nextDouble(); // calucating roots r1 = ( Math.pow(b,2) - (4 * a * c)); r1 = (-b + (Math.sqrt(r1))) / (2 * a); r2 = ( Math.pow(b,2) - (4 * a * c)); r2 = (-b - (Math.sqrt(r2))) / (2 * a); // calls the method and determines # of roots double r = roots (a, b, c); // if statements and display if (r &gt; 1) { System.out.printf(&quot;%.0f, %.of, and %.0f coefficients have %.0f real roots:&quot;,a, b, c, r); System.out.printf(&quot;\n\tR1 = %.2f&quot;,r1); System.out.printf(&quot;\n\tR1 = %.2f&quot;,r2); } else if (r == 1) { System.out.printf(&quot;%.0f, %.of, and %.0f coefficients have %.0f real roots:&quot;,a, b, c, r); System.out.printf(&quot;\n\tR1 = %.2f&quot;,r1); } else if (r == 0) { System.out.printf(&quot;%.0f, %.of, and %.0f coefficients have %.0f real roots:&quot;,a, b, c); } } //user - defined root method public static double roots(double a, double b, double c) { double roots = 0; //number of roots if (Math.pow(b,2) - (4 * a * c) &gt; 0) { roots = 2; } else if (Math.pow(b,2) - (4 * a * c) == 0) { roots = 1; } else if (Math.pow(b,2) - (4 * a * c) &lt; 0) { roots = 0; } return roots; } } </code></pre> <p>I attempted to run the code. After entering the value 1, 2,3 for coefficents A, B,and C, the code returned Exception in thread &quot;main&quot; java.util.UnknownFormatConversionException: Conversion = '-'</p>
[ { "answer_id": 74353655, "author": "Ben Borchard", "author_id": 4054720, "author_profile": "https://Stackoverflow.com/users/4054720", "pm_score": 1, "selected": false, "text": " System.out.printf(\"%.0f, %.of, and %.0f coefficients have %.0f real roots:\",a, b, c, r);\n ...\n System.out.printf(\"%.0f, %.of, and %.0f coefficients have %.0f real roots:\",a, b, c, r);\n ...\n System.out.printf(\"%.0f, %.of, and %.0f coefficients have %.0f real roots:\",a, b, c);\n" }, { "answer_id": 74353716, "author": "sanurah", "author_id": 4079056, "author_profile": "https://Stackoverflow.com/users/4079056", "pm_score": 0, "selected": false, "text": "if (r > 1) {\n System.out.printf(\"%.0f, %.0f, and %.0f coefficients have %.0f real roots:\",a, b, c, r);\n System.out.printf(\"\\n\\tR1 = %.2f\",r1);\n System.out.printf(\"\\n\\tR1 = %.2f\",r2);\n }\n\n else if (r == 1)\n {\n System.out.printf(\"%.0f, %.0f, and %.0f coefficients have %.0f real roots:\",a, b, c, r);\n System.out.printf(\"\\n\\tR1 = %.2f\",r1);\n }\n\n else if (r == 0) {\n System.out.printf(\"%.0f, %.0f, and %.0f coefficients have %.0f real roots:\",a, b, c, r);\n }\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14620764/" ]
74,353,586
<p>I have a table that store the customer's 'PreOrder' number and 'PostOrder' number in the same column. I'm trying to write a case statement that will evaluate if the patient has one of the 'PreOrder' number and/or the 'PostOrder' number. There are three different numbers that could represent a 'PreOrder' and two different numbers that will represent a 'PostOrder'. If the customer has one of the 'PreOrder' numbers, I will like to return 'Pre'. If the customer has one of the 'PostOrder' numbers, I will like to return 'Post'. If a customer has one of the 'PreOrder' numbers and one of the 'PostOrder' numbers, I will like to return 'BothOrders'. Here is my query...</p> <pre><code>SELECT Cust.Cust_ID , CASE WHEN Cust.Order_ID in ('154','3042000103','3042000099') THEN 'PreOrder' WHEN Cust. Order_ID in ('30400010112','3042000104') THEN 'PostOrder' WHEN Cust. Order_ID in ('154','3042000103','3042000099') and Cust. Order_ID in ('30400010112','3042000104') THEN 'BothOrders' END as Orders From Customer as Cust GROUP BY Cust.Cust_ID </code></pre> <p>This is not working because it's not returning 'BothOrders' for customers who has either of the 'PreOrder' and either of the 'PostOrder' numbers. The<br /> values in Order's column is (154,3042000103, 3042000099, 30400010112, 3042000099).</p> <p>I'm expecting something like this... <a href="https://i.stack.imgur.com/sHvVm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sHvVm.png" alt="enter image description here" /></a></p> <p>But I'm getting... <a href="https://i.stack.imgur.com/N5EbT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/N5EbT.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74353655, "author": "Ben Borchard", "author_id": 4054720, "author_profile": "https://Stackoverflow.com/users/4054720", "pm_score": 1, "selected": false, "text": " System.out.printf(\"%.0f, %.of, and %.0f coefficients have %.0f real roots:\",a, b, c, r);\n ...\n System.out.printf(\"%.0f, %.of, and %.0f coefficients have %.0f real roots:\",a, b, c, r);\n ...\n System.out.printf(\"%.0f, %.of, and %.0f coefficients have %.0f real roots:\",a, b, c);\n" }, { "answer_id": 74353716, "author": "sanurah", "author_id": 4079056, "author_profile": "https://Stackoverflow.com/users/4079056", "pm_score": 0, "selected": false, "text": "if (r > 1) {\n System.out.printf(\"%.0f, %.0f, and %.0f coefficients have %.0f real roots:\",a, b, c, r);\n System.out.printf(\"\\n\\tR1 = %.2f\",r1);\n System.out.printf(\"\\n\\tR1 = %.2f\",r2);\n }\n\n else if (r == 1)\n {\n System.out.printf(\"%.0f, %.0f, and %.0f coefficients have %.0f real roots:\",a, b, c, r);\n System.out.printf(\"\\n\\tR1 = %.2f\",r1);\n }\n\n else if (r == 0) {\n System.out.printf(\"%.0f, %.0f, and %.0f coefficients have %.0f real roots:\",a, b, c, r);\n }\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17328107/" ]
74,353,591
<p>I've been trying to puzzle out how to form edge descriptors for a CGAL Triangulation_3 such that I can use Boost's implementation of Kruskal's Minimum Spanning Tree on that Triangulation.</p> <p>I have been reading through the reference documentation for a Triangulation_2 (provided <a href="https://doc.cgal.org/latest/BGL/index.html#title15" rel="nofollow noreferrer">here</a>), but have observed that no implementation exists for <code>boost::graph_traits&lt;Triangulation_3&gt;</code>. While puzzling it out, I found that I could possibly provide my own implementation for edge descriptors through an adjacency list as shown in Boost's <a href="https://www.boost.org/doc/libs/1_80_0/libs/graph/example/kruskal-example.cpp" rel="nofollow noreferrer">example</a> for a Kruskal MST, but got lost and confused at this step, and didn't know if that would be a sufficient approach.</p> <p>Ultimately, it seems that what I need to do is create a boost Graph implementation, but am lost at what resources I need to accomplish this step. From there, the desired use is to be able to traverse this MST to perform graph-based min-cuts at specific edges matching a predicate.</p> <p>// EDIT :&gt;</p> <p>My current attempt revolves around creating the EMST via pushing simplex edges defined as a pair of vertex iterate indices, with weights defined as euclidean distance between vertices (a Point_3 with data attached), using the Graph construction shown in the Boost example.</p> <p>My hope is to have BGL vertices (as a Point_3 with color information attached) be connected by BGL edges (as a simplex[!] edge after the triangulation). My ultimate use just requires that I traverse some sort of contiguous spatial ordering of my Point_3's (with RGB info), and split estimated planes into &quot;patches&quot; which meet a max-distance (complete linkage?) threshold, or a within-patch distance variance. It's not exactly segmentation, but similar.</p> <pre><code>// some defns... using RGBA = std::array&lt;uint16_t, 3&gt;; using PointData = boost::tuple&lt; Point_3, // Point location; Easting-Altitude-Northing Vector_3, // Estimated Normal Vector at Point RGBA, // Photo Color RGBA, // RANSAC Shape Colorization size_t, // Estimated Patch ID RGBA&gt;; // Estimated Patch Colorization // // Some operations on the points and RANSAC estimation occurs here // // iterate through shapes while (it != shapes.end()) { boost::shared_ptr&lt;EfficientRANSAC::Shape&gt; shape = *it; std::cout &lt;&lt; (*it)-&gt;info() &lt;&lt; std::endl; // generate a random color code for this shape RGBA rgb; for (int i=0; i&lt;3; i++) { rgb[i] = rand()%256; } // Form triangulation to later convert into Graph representation using VertexInfoBase = CGAL::Triangulation_vertex_base_with_info_3&lt; PointData, Kernel &gt;; using TriTraits = CGAL::Triangulation_data_structure_3&lt; VertexInfoBase, CGAL::Delaunay_triangulation_cell_base_3&lt;Kernel&gt;, CGAL::Parallel_tag &gt;; using Triangulation_3 = CGAL::Delaunay_triangulation_3&lt;Kernel, TriTraits&gt;; Triangulation_3 tr; // Iterate through point indices assigned to each detected shape. std::vector&lt;std::size_t&gt;::const_iterator index_it = (*it)-&gt;indices_of_assigned_points().begin(); while (index_it != (*it)-&gt;indices_of_assigned_points().end()) { PointData&amp; p = *(points.begin() + (*index_it)); // assign shape diagnostic color info boost::get&lt;3&gt;(p) = rgb; // insert Point_3 data for triangulation and attach PointData info auto vertex = tr.insert(boost::get&lt;0&gt;(p)); vertex-&gt;info() = p; index_it++; // next assigned point } std::cout &lt;&lt; &quot;Found triangulation with: \n\t&quot; &lt;&lt; tr.number_of_vertices() &lt;&lt; &quot;\tvertices\n\t&quot; &lt;&lt; tr.number_of_edges() &lt;&lt; &quot;\tedges\n\t&quot; &lt;&lt; tr.number_of_facets() &lt;&lt; &quot;\tfacets&quot; &lt;&lt; std::endl; // build a Graph out of the triangulation that we can do a Minimum-Spanning-Tree on using Graph = boost::adjacency_list&lt; boost::vecS, // OutEdgeList boost::vecS, // VertexList boost::undirectedS, // Directed boost::no_property, // VertexProperties boost::property&lt; boost::edge_weight_t, int &gt;, // EdgeProperties boost::no_property, // GraphProperties boost::listS // EdgeList &gt;; using Edge = boost::graph_traits&lt;Graph&gt;::edge_descriptor; using E = std::pair&lt; size_t, size_t &gt;; // &lt;: TODO - should be iterator index of vertex in Triangulation_3 instead of size_t? std::vector&lt;E&gt; edge_array; // edges should be between Point_3's with attached RGBA photocolor info. // It is necessary to later access both the Point_3 and RGBA info for vertices after operations are performed on the EMST std::vector&lt;float&gt; weights; // weights are `std::sqrt(CGAL::squared_distance(...))` between these Point_3's // Question(?) :&gt; Should be iterating over &quot;finite&quot; edges here? for (auto edge : tr.all_edges()) { // insert simplex (!!) edge (between-vertices) here edge_array.push_back(...); // generate weight using std::sqrt(CGAL::squared_distance(...)) weights.push_back(...); } // build Graph from `edge_array` and `weights` Graph g(...); // build Euclidean-Minimum-Spanning-Tree (EMST) as list of simplex edges between vertices std::list&lt;E&gt; emst; boost::kruskal_minimum_spanning_tree(...); // - traverse EMST from start of list, performing &quot;cuts&quot; into &quot;patches&quot; when we have hit // max patch distance (euclidean) from current &quot;first&quot; vertex of &quot;patch&quot;. // - have to be able to access Triangulation_3 vertex info (via `locate`?) here // - foreach collection of PointData in patch, assign `patch_id` and diagnostic color info, // then commit individual serialized &quot;patches&quot; collections of Point_3 and RGBA photocolor to database todo!(); it++; // next shape } </code></pre> <p>The end goal of traversing each of the shapes using a Minimum Spanning Tree via Triangulation is to break each of the RANSAC estimated shapes into chunks, for other purposes. Picture example: <img src="https://imgur.com/OM1sv8W.png" alt="Original point cloud dataset with colorization of estimated shapes" /> <img src="https://imgur.com/5mARILw.png" alt="After traversing EMST and processing into &quot;patches&quot;" /></p>
[ { "answer_id": 74358360, "author": "Andreas Fabri", "author_id": 1895240, "author_profile": "https://Stackoverflow.com/users/1895240", "pm_score": 2, "selected": false, "text": "graph_traits" }, { "answer_id": 74524563, "author": "anachronicnomad", "author_id": 11929780, "author_profile": "https://Stackoverflow.com/users/11929780", "pm_score": 0, "selected": false, "text": "// Form triangulation to later convert into Graph representation\n using VertexInfoBase = CGAL::Triangulation_vertex_base_with_info_3<\n PointData,\n Kernel\n >;\n using TriTraits = CGAL::Triangulation_data_structure_3<\n VertexInfoBase,\n CGAL::Delaunay_triangulation_cell_base_3<Kernel>,\n CGAL::Parallel_tag\n >;\n using Triangulation_3 = CGAL::Delaunay_triangulation_3<Kernel, TriTraits>;\n\n Triangulation_3 tr;\n\n // Iterate through point indices assigned to each detected shape. \n std::vector<std::size_t>::const_iterator \n index_it = (*it)->indices_of_assigned_points().begin();\n\n while (index_it != (*it)->indices_of_assigned_points().end()) {\n PointData& p = *(points.begin() + (*index_it));\n\n // assign shape diagnostic color info\n boost::get<3>(p) = rgb;\n\n // insert Point_3 data for triangulation and attach PointData info\n TriTraits::Vertex_handle vertex = tr.insert(boost::get<0>(p));\n vertex->info() = p;\n\n index_it++; // next assigned point\n }\n \n std::cout << \"Found triangulation with: \\n\\t\" << \n tr.number_of_vertices() << \"\\tvertices\\n\\t\" <<\n tr.number_of_edges() << \"\\tedges\\n\\t\" <<\n tr.number_of_facets() << \"\\tfacets\" << std::endl;\n\n // build a Graph out of the triangulation that we can do a Minimum-Spanning-Tree on\n // examples taken from https://www.boost.org/doc/libs/1_80_0/libs/graph/example/kruskal-example.cpp\n using Graph = boost::adjacency_list<\n boost::vecS, // OutEdgeList\n boost::vecS, // VertexList\n boost::undirectedS, // Directed\n boost::no_property, // VertexProperties\n boost::property< boost::edge_weight_t, double > // EdgeProperties\n >;\n using Edge = boost::graph_traits<Graph>::edge_descriptor;\n using E = std::pair< size_t, size_t >; // <: TODO - should be iterator index of vertex in Triangulation_3 instead of size_t?\n\n Graph g(tr.number_of_vertices());\n boost::property_map< Graph, boost::edge_weight_t >::type weightmap = boost::get(boost::edge_weight, g);\n\n // iterate over finite edges in the triangle, and add these \n for (\n Triangulation_3::Finite_edges_iterator eit = tr.finite_edges_begin();\n eit != tr.finite_edges_end(); \n eit++\n ) \n {\n Triangulation_3::Segment s = tr.segment(*eit);\n\n Point_3 vtx = s.point(0);\n Point_3 n_vtx = s.point(1);\n\n // locate the (*eit), get vertex handles?\n // from https://www.appsloveworld.com/cplus/100/204/how-to-get-the-source-and-target-points-from-edge-iterator-in-cgal\n Triangulation_3::Vertex_handle vh1 = eit->first->vertex((eit->second + 1) % 3);\n Triangulation_3::Vertex_handle vh2 = eit->first->vertex((eit->second + 2) % 3);\n\n double weight = std::sqrt(CGAL::squared_distance(vtx, n_vtx));\n\n Edge e;\n bool inserted;\n boost::tie(e, inserted)\n = boost::add_edge(\n boost::get<6>(vh1->info()),\n boost::get<6>(vh2->info()),\n g\n );\n weightmap[e] = weight;\n }\n\n // build Euclidean-Minimum-Spanning-Tree (EMST) as list of simplex edges between vertices\n //boost::property_map<Graph, boost::edge_weight_t>::type weight = boost::get(boost::edge_weight, g);\n std::vector<Edge> spanning_tree;\n\n boost::kruskal_minimum_spanning_tree(g, std::back_inserter(spanning_tree));\n\n // we can use something like a hash table to go from source -> target\n // for each of the edges, making traversal easier. \n // from there, we can keep track or eventually find a source \"key\" which\n // does not correspond to any target \"key\" within the table\n std::unordered_map< size_t, std::vector<size_t> > map = {};\n\n // iterate minimum spanning tree to build unordered_map (hashtable)\n std::cout << \"Found minimum spanning tree of \" << spanning_tree.size() << \" edges for #vertices \" << tr.number_of_vertices() << std::endl;\n for (std::vector< Edge >::iterator ei = spanning_tree.begin();\n ei != spanning_tree.end(); ++ei)\n {\n\n size_t source = boost::source(*ei, g); \n size_t target = boost::target(*ei, g);\n // << \" with weight of \" << weightmap[*ei] << std::endl;\n\n if ( map.find(source) == map.end() ) {\n map.insert(\n {\n source, \n std::vector({target})\n }\n );\n } else {\n std::vector<size_t> target_vec = map[source];\n target_vec.push_back(target);\n map[source] = target_vec;\n }\n }\n\n // iterate over map to find an \"origin\" node\n size_t origin = 0; \n\n for (const auto& it : map) {\n bool exit_flag = false;\n std::vector<size_t> check_targets = it.second;\n for (size_t target : check_targets) {\n if (map.find(target) == map.end()) {\n origin = target;\n exit_flag = true;\n break;\n }\n }\n if (exit_flag) {\n break;\n }\n }\n\n std::cout << \"Found origin of tree with value: \" << origin << std::endl;\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11929780/" ]
74,353,592
<p>I have a dictionary like this:</p> <pre><code>features_id = { id1: [a, b, c, d], id2: [c, d], id3: [a, e, f, d, g, k], ... } </code></pre> <p>I have also a list of values I want to create a new dictionary. Something like this:</p> <pre><code>list_of_values = [a, c] </code></pre> <h1>Goal to achieve:</h1> <p>I want a new dictionary like this:</p> <pre><code>new_dict = { id1: [a, c], id2: [c], id3: [a], ... } </code></pre>
[ { "answer_id": 74358360, "author": "Andreas Fabri", "author_id": 1895240, "author_profile": "https://Stackoverflow.com/users/1895240", "pm_score": 2, "selected": false, "text": "graph_traits" }, { "answer_id": 74524563, "author": "anachronicnomad", "author_id": 11929780, "author_profile": "https://Stackoverflow.com/users/11929780", "pm_score": 0, "selected": false, "text": "// Form triangulation to later convert into Graph representation\n using VertexInfoBase = CGAL::Triangulation_vertex_base_with_info_3<\n PointData,\n Kernel\n >;\n using TriTraits = CGAL::Triangulation_data_structure_3<\n VertexInfoBase,\n CGAL::Delaunay_triangulation_cell_base_3<Kernel>,\n CGAL::Parallel_tag\n >;\n using Triangulation_3 = CGAL::Delaunay_triangulation_3<Kernel, TriTraits>;\n\n Triangulation_3 tr;\n\n // Iterate through point indices assigned to each detected shape. \n std::vector<std::size_t>::const_iterator \n index_it = (*it)->indices_of_assigned_points().begin();\n\n while (index_it != (*it)->indices_of_assigned_points().end()) {\n PointData& p = *(points.begin() + (*index_it));\n\n // assign shape diagnostic color info\n boost::get<3>(p) = rgb;\n\n // insert Point_3 data for triangulation and attach PointData info\n TriTraits::Vertex_handle vertex = tr.insert(boost::get<0>(p));\n vertex->info() = p;\n\n index_it++; // next assigned point\n }\n \n std::cout << \"Found triangulation with: \\n\\t\" << \n tr.number_of_vertices() << \"\\tvertices\\n\\t\" <<\n tr.number_of_edges() << \"\\tedges\\n\\t\" <<\n tr.number_of_facets() << \"\\tfacets\" << std::endl;\n\n // build a Graph out of the triangulation that we can do a Minimum-Spanning-Tree on\n // examples taken from https://www.boost.org/doc/libs/1_80_0/libs/graph/example/kruskal-example.cpp\n using Graph = boost::adjacency_list<\n boost::vecS, // OutEdgeList\n boost::vecS, // VertexList\n boost::undirectedS, // Directed\n boost::no_property, // VertexProperties\n boost::property< boost::edge_weight_t, double > // EdgeProperties\n >;\n using Edge = boost::graph_traits<Graph>::edge_descriptor;\n using E = std::pair< size_t, size_t >; // <: TODO - should be iterator index of vertex in Triangulation_3 instead of size_t?\n\n Graph g(tr.number_of_vertices());\n boost::property_map< Graph, boost::edge_weight_t >::type weightmap = boost::get(boost::edge_weight, g);\n\n // iterate over finite edges in the triangle, and add these \n for (\n Triangulation_3::Finite_edges_iterator eit = tr.finite_edges_begin();\n eit != tr.finite_edges_end(); \n eit++\n ) \n {\n Triangulation_3::Segment s = tr.segment(*eit);\n\n Point_3 vtx = s.point(0);\n Point_3 n_vtx = s.point(1);\n\n // locate the (*eit), get vertex handles?\n // from https://www.appsloveworld.com/cplus/100/204/how-to-get-the-source-and-target-points-from-edge-iterator-in-cgal\n Triangulation_3::Vertex_handle vh1 = eit->first->vertex((eit->second + 1) % 3);\n Triangulation_3::Vertex_handle vh2 = eit->first->vertex((eit->second + 2) % 3);\n\n double weight = std::sqrt(CGAL::squared_distance(vtx, n_vtx));\n\n Edge e;\n bool inserted;\n boost::tie(e, inserted)\n = boost::add_edge(\n boost::get<6>(vh1->info()),\n boost::get<6>(vh2->info()),\n g\n );\n weightmap[e] = weight;\n }\n\n // build Euclidean-Minimum-Spanning-Tree (EMST) as list of simplex edges between vertices\n //boost::property_map<Graph, boost::edge_weight_t>::type weight = boost::get(boost::edge_weight, g);\n std::vector<Edge> spanning_tree;\n\n boost::kruskal_minimum_spanning_tree(g, std::back_inserter(spanning_tree));\n\n // we can use something like a hash table to go from source -> target\n // for each of the edges, making traversal easier. \n // from there, we can keep track or eventually find a source \"key\" which\n // does not correspond to any target \"key\" within the table\n std::unordered_map< size_t, std::vector<size_t> > map = {};\n\n // iterate minimum spanning tree to build unordered_map (hashtable)\n std::cout << \"Found minimum spanning tree of \" << spanning_tree.size() << \" edges for #vertices \" << tr.number_of_vertices() << std::endl;\n for (std::vector< Edge >::iterator ei = spanning_tree.begin();\n ei != spanning_tree.end(); ++ei)\n {\n\n size_t source = boost::source(*ei, g); \n size_t target = boost::target(*ei, g);\n // << \" with weight of \" << weightmap[*ei] << std::endl;\n\n if ( map.find(source) == map.end() ) {\n map.insert(\n {\n source, \n std::vector({target})\n }\n );\n } else {\n std::vector<size_t> target_vec = map[source];\n target_vec.push_back(target);\n map[source] = target_vec;\n }\n }\n\n // iterate over map to find an \"origin\" node\n size_t origin = 0; \n\n for (const auto& it : map) {\n bool exit_flag = false;\n std::vector<size_t> check_targets = it.second;\n for (size_t target : check_targets) {\n if (map.find(target) == map.end()) {\n origin = target;\n exit_flag = true;\n break;\n }\n }\n if (exit_flag) {\n break;\n }\n }\n\n std::cout << \"Found origin of tree with value: \" << origin << std::endl;\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14846176/" ]
74,353,595
<p>I have a training dataset that consists of 60,000 observations that I want to create 9 subset training sets from. I want to sample randomly without replacement; I need 3 datasets of 500 observations, 3 datasets of 1,000 observations, and 3 datasets of 2,000 observations.</p> <p><a href="https://i.stack.imgur.com/OxCFh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OxCFh.png" alt="enter image description here" /></a></p> <p>How can I do this using sample() in R?</p>
[ { "answer_id": 74358360, "author": "Andreas Fabri", "author_id": 1895240, "author_profile": "https://Stackoverflow.com/users/1895240", "pm_score": 2, "selected": false, "text": "graph_traits" }, { "answer_id": 74524563, "author": "anachronicnomad", "author_id": 11929780, "author_profile": "https://Stackoverflow.com/users/11929780", "pm_score": 0, "selected": false, "text": "// Form triangulation to later convert into Graph representation\n using VertexInfoBase = CGAL::Triangulation_vertex_base_with_info_3<\n PointData,\n Kernel\n >;\n using TriTraits = CGAL::Triangulation_data_structure_3<\n VertexInfoBase,\n CGAL::Delaunay_triangulation_cell_base_3<Kernel>,\n CGAL::Parallel_tag\n >;\n using Triangulation_3 = CGAL::Delaunay_triangulation_3<Kernel, TriTraits>;\n\n Triangulation_3 tr;\n\n // Iterate through point indices assigned to each detected shape. \n std::vector<std::size_t>::const_iterator \n index_it = (*it)->indices_of_assigned_points().begin();\n\n while (index_it != (*it)->indices_of_assigned_points().end()) {\n PointData& p = *(points.begin() + (*index_it));\n\n // assign shape diagnostic color info\n boost::get<3>(p) = rgb;\n\n // insert Point_3 data for triangulation and attach PointData info\n TriTraits::Vertex_handle vertex = tr.insert(boost::get<0>(p));\n vertex->info() = p;\n\n index_it++; // next assigned point\n }\n \n std::cout << \"Found triangulation with: \\n\\t\" << \n tr.number_of_vertices() << \"\\tvertices\\n\\t\" <<\n tr.number_of_edges() << \"\\tedges\\n\\t\" <<\n tr.number_of_facets() << \"\\tfacets\" << std::endl;\n\n // build a Graph out of the triangulation that we can do a Minimum-Spanning-Tree on\n // examples taken from https://www.boost.org/doc/libs/1_80_0/libs/graph/example/kruskal-example.cpp\n using Graph = boost::adjacency_list<\n boost::vecS, // OutEdgeList\n boost::vecS, // VertexList\n boost::undirectedS, // Directed\n boost::no_property, // VertexProperties\n boost::property< boost::edge_weight_t, double > // EdgeProperties\n >;\n using Edge = boost::graph_traits<Graph>::edge_descriptor;\n using E = std::pair< size_t, size_t >; // <: TODO - should be iterator index of vertex in Triangulation_3 instead of size_t?\n\n Graph g(tr.number_of_vertices());\n boost::property_map< Graph, boost::edge_weight_t >::type weightmap = boost::get(boost::edge_weight, g);\n\n // iterate over finite edges in the triangle, and add these \n for (\n Triangulation_3::Finite_edges_iterator eit = tr.finite_edges_begin();\n eit != tr.finite_edges_end(); \n eit++\n ) \n {\n Triangulation_3::Segment s = tr.segment(*eit);\n\n Point_3 vtx = s.point(0);\n Point_3 n_vtx = s.point(1);\n\n // locate the (*eit), get vertex handles?\n // from https://www.appsloveworld.com/cplus/100/204/how-to-get-the-source-and-target-points-from-edge-iterator-in-cgal\n Triangulation_3::Vertex_handle vh1 = eit->first->vertex((eit->second + 1) % 3);\n Triangulation_3::Vertex_handle vh2 = eit->first->vertex((eit->second + 2) % 3);\n\n double weight = std::sqrt(CGAL::squared_distance(vtx, n_vtx));\n\n Edge e;\n bool inserted;\n boost::tie(e, inserted)\n = boost::add_edge(\n boost::get<6>(vh1->info()),\n boost::get<6>(vh2->info()),\n g\n );\n weightmap[e] = weight;\n }\n\n // build Euclidean-Minimum-Spanning-Tree (EMST) as list of simplex edges between vertices\n //boost::property_map<Graph, boost::edge_weight_t>::type weight = boost::get(boost::edge_weight, g);\n std::vector<Edge> spanning_tree;\n\n boost::kruskal_minimum_spanning_tree(g, std::back_inserter(spanning_tree));\n\n // we can use something like a hash table to go from source -> target\n // for each of the edges, making traversal easier. \n // from there, we can keep track or eventually find a source \"key\" which\n // does not correspond to any target \"key\" within the table\n std::unordered_map< size_t, std::vector<size_t> > map = {};\n\n // iterate minimum spanning tree to build unordered_map (hashtable)\n std::cout << \"Found minimum spanning tree of \" << spanning_tree.size() << \" edges for #vertices \" << tr.number_of_vertices() << std::endl;\n for (std::vector< Edge >::iterator ei = spanning_tree.begin();\n ei != spanning_tree.end(); ++ei)\n {\n\n size_t source = boost::source(*ei, g); \n size_t target = boost::target(*ei, g);\n // << \" with weight of \" << weightmap[*ei] << std::endl;\n\n if ( map.find(source) == map.end() ) {\n map.insert(\n {\n source, \n std::vector({target})\n }\n );\n } else {\n std::vector<size_t> target_vec = map[source];\n target_vec.push_back(target);\n map[source] = target_vec;\n }\n }\n\n // iterate over map to find an \"origin\" node\n size_t origin = 0; \n\n for (const auto& it : map) {\n bool exit_flag = false;\n std::vector<size_t> check_targets = it.second;\n for (size_t target : check_targets) {\n if (map.find(target) == map.end()) {\n origin = target;\n exit_flag = true;\n break;\n }\n }\n if (exit_flag) {\n break;\n }\n }\n\n std::cout << \"Found origin of tree with value: \" << origin << std::endl;\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353595", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17548328/" ]
74,353,602
<p>It seems this HPC is hard to google docs. How does one write an <code>AND</code> statement for it? e.g. for <code>OR</code> one does:</p> <pre><code>requirements = (CUDADeviceName == &quot;Quadro RTX 6000&quot;) || (CUDADeviceName == &quot;NVIDIA A40&quot;) </code></pre> <p>would:</p> <pre><code>requirements = (CUDADeviceName != &quot;Tesla K40m&quot;) /\ (CUDADeviceName == &quot;NVIDIA A40&quot;) </code></pre> <p>work? What I want is NOT tesla k40m and NOT A40. Anything else is fine.</p> <p>Gives error:</p> <pre><code>(metalearning_gpu) miranda9~/diversity-for-predictive-success-of-meta-learning $ condor_submit job.sub Submitting job(s)ERROR: Parse error in expression: Requirements = ((CUDADeviceName != &quot;Tesla K40m&quot;) /\ (CUDADeviceName != &quot;NVIDIA A40&quot;)) &amp;&amp; (TARGET.Arch == &quot;X86_64&quot;) &amp;&amp; (TARGET.OpSys == &quot;LINUX&quot;) &amp;&amp; (TARGET.Disk &gt;= RequestDisk) &amp;&amp; (TARGET.Memory &gt;= RequestMemory) &amp;&amp; (TARGET.Cpus &gt;= RequestCpus) &amp;&amp; (TARGET.gpus &gt;= Requestgpus) &amp;&amp; ((TARGET.FileSystemDomain == MY.FileSystemDomain) || (TARGET.HasFileTransfer)) </code></pre>
[ { "answer_id": 74358360, "author": "Andreas Fabri", "author_id": 1895240, "author_profile": "https://Stackoverflow.com/users/1895240", "pm_score": 2, "selected": false, "text": "graph_traits" }, { "answer_id": 74524563, "author": "anachronicnomad", "author_id": 11929780, "author_profile": "https://Stackoverflow.com/users/11929780", "pm_score": 0, "selected": false, "text": "// Form triangulation to later convert into Graph representation\n using VertexInfoBase = CGAL::Triangulation_vertex_base_with_info_3<\n PointData,\n Kernel\n >;\n using TriTraits = CGAL::Triangulation_data_structure_3<\n VertexInfoBase,\n CGAL::Delaunay_triangulation_cell_base_3<Kernel>,\n CGAL::Parallel_tag\n >;\n using Triangulation_3 = CGAL::Delaunay_triangulation_3<Kernel, TriTraits>;\n\n Triangulation_3 tr;\n\n // Iterate through point indices assigned to each detected shape. \n std::vector<std::size_t>::const_iterator \n index_it = (*it)->indices_of_assigned_points().begin();\n\n while (index_it != (*it)->indices_of_assigned_points().end()) {\n PointData& p = *(points.begin() + (*index_it));\n\n // assign shape diagnostic color info\n boost::get<3>(p) = rgb;\n\n // insert Point_3 data for triangulation and attach PointData info\n TriTraits::Vertex_handle vertex = tr.insert(boost::get<0>(p));\n vertex->info() = p;\n\n index_it++; // next assigned point\n }\n \n std::cout << \"Found triangulation with: \\n\\t\" << \n tr.number_of_vertices() << \"\\tvertices\\n\\t\" <<\n tr.number_of_edges() << \"\\tedges\\n\\t\" <<\n tr.number_of_facets() << \"\\tfacets\" << std::endl;\n\n // build a Graph out of the triangulation that we can do a Minimum-Spanning-Tree on\n // examples taken from https://www.boost.org/doc/libs/1_80_0/libs/graph/example/kruskal-example.cpp\n using Graph = boost::adjacency_list<\n boost::vecS, // OutEdgeList\n boost::vecS, // VertexList\n boost::undirectedS, // Directed\n boost::no_property, // VertexProperties\n boost::property< boost::edge_weight_t, double > // EdgeProperties\n >;\n using Edge = boost::graph_traits<Graph>::edge_descriptor;\n using E = std::pair< size_t, size_t >; // <: TODO - should be iterator index of vertex in Triangulation_3 instead of size_t?\n\n Graph g(tr.number_of_vertices());\n boost::property_map< Graph, boost::edge_weight_t >::type weightmap = boost::get(boost::edge_weight, g);\n\n // iterate over finite edges in the triangle, and add these \n for (\n Triangulation_3::Finite_edges_iterator eit = tr.finite_edges_begin();\n eit != tr.finite_edges_end(); \n eit++\n ) \n {\n Triangulation_3::Segment s = tr.segment(*eit);\n\n Point_3 vtx = s.point(0);\n Point_3 n_vtx = s.point(1);\n\n // locate the (*eit), get vertex handles?\n // from https://www.appsloveworld.com/cplus/100/204/how-to-get-the-source-and-target-points-from-edge-iterator-in-cgal\n Triangulation_3::Vertex_handle vh1 = eit->first->vertex((eit->second + 1) % 3);\n Triangulation_3::Vertex_handle vh2 = eit->first->vertex((eit->second + 2) % 3);\n\n double weight = std::sqrt(CGAL::squared_distance(vtx, n_vtx));\n\n Edge e;\n bool inserted;\n boost::tie(e, inserted)\n = boost::add_edge(\n boost::get<6>(vh1->info()),\n boost::get<6>(vh2->info()),\n g\n );\n weightmap[e] = weight;\n }\n\n // build Euclidean-Minimum-Spanning-Tree (EMST) as list of simplex edges between vertices\n //boost::property_map<Graph, boost::edge_weight_t>::type weight = boost::get(boost::edge_weight, g);\n std::vector<Edge> spanning_tree;\n\n boost::kruskal_minimum_spanning_tree(g, std::back_inserter(spanning_tree));\n\n // we can use something like a hash table to go from source -> target\n // for each of the edges, making traversal easier. \n // from there, we can keep track or eventually find a source \"key\" which\n // does not correspond to any target \"key\" within the table\n std::unordered_map< size_t, std::vector<size_t> > map = {};\n\n // iterate minimum spanning tree to build unordered_map (hashtable)\n std::cout << \"Found minimum spanning tree of \" << spanning_tree.size() << \" edges for #vertices \" << tr.number_of_vertices() << std::endl;\n for (std::vector< Edge >::iterator ei = spanning_tree.begin();\n ei != spanning_tree.end(); ++ei)\n {\n\n size_t source = boost::source(*ei, g); \n size_t target = boost::target(*ei, g);\n // << \" with weight of \" << weightmap[*ei] << std::endl;\n\n if ( map.find(source) == map.end() ) {\n map.insert(\n {\n source, \n std::vector({target})\n }\n );\n } else {\n std::vector<size_t> target_vec = map[source];\n target_vec.push_back(target);\n map[source] = target_vec;\n }\n }\n\n // iterate over map to find an \"origin\" node\n size_t origin = 0; \n\n for (const auto& it : map) {\n bool exit_flag = false;\n std::vector<size_t> check_targets = it.second;\n for (size_t target : check_targets) {\n if (map.find(target) == map.end()) {\n origin = target;\n exit_flag = true;\n break;\n }\n }\n if (exit_flag) {\n break;\n }\n }\n\n std::cout << \"Found origin of tree with value: \" << origin << std::endl;\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1601580/" ]
74,353,607
<p>I am looking for a solution to select different const via select dropdown menu to be shown in a table.</p> <p>Anyone able to point me in the right direction? Thanks.</p> <pre><code>&lt;select id=&quot;select&quot; name=&quot;select&quot;\&gt; &lt;option value=&quot;1&quot;\&gt;Device 1\&lt;/option\&gt; &lt;option value=&quot;2&quot;\&gt;Device 2\&lt;/option\&gt; &lt;option value=&quot;3&quot;\&gt;Device 3\&lt;/option\&gt; &lt;/select\&gt; </code></pre> <pre><code>const 1 = [Name: &quot;Name 1&quot;, Code: &quot;Code 1&quot;, Speed: &quot;10&quot;] const 2 = [Name: &quot;Name 2&quot;, Code: &quot;Code 2&quot;, Speed: &quot;20&quot;] const 3 = [Name: &quot;Name 3&quot;, Code: &quot;Code 3&quot;, Speed: &quot;30&quot;] </code></pre> <p>Function to select const by option value?</p> <pre><code>var text = selected option value document.getElementById(&quot;Name&quot;).innerHTML = text.Name; document.getElementById(&quot;Code&quot;).innerHTML = text.Code; document.getElementById(&quot;Speed&quot;).innerHTML = text.Speed; </code></pre> <pre><code>+--------------------------------+ | Name: | Selected const Name | |---------|----------------------| | Code: | Selected const Code | |---------|----------------------| | Speed: | Selected const Speed | +--------------------------------+ </code></pre> <p>I've tried to above method by cant get it to work.</p>
[ { "answer_id": 74353693, "author": "Piritos Vajas", "author_id": 19715373, "author_profile": "https://Stackoverflow.com/users/19715373", "pm_score": -1, "selected": false, "text": " const array = {\n \"1\" : {Name: \"Name 1\", Code: \"Code 1\", Speed: \"10\"},\n \"2\" : {Name: \"Name 2\", Code: \"Code 2\", Speed: \"20\"},\n \"3\" : {Name: \"Name 3\", Code: \"Code 3\", Speed: \"30\"}\n }\n Console.log(array[1].Name);\n" }, { "answer_id": 74353700, "author": "imvain2", "author_id": 3684265, "author_profile": "https://Stackoverflow.com/users/3684265", "pm_score": 0, "selected": false, "text": "let device = document.querySelector(\"#select\");\n\nlet devices = {\n \"1\": {\n Name: \"Name 1\",\n Code: \"Code 1\",\n Speed: \"10\"\n },\n \"2\": {\n Name: \"Name 2\",\n Code: \"Code 2\",\n Speed: \"20\"\n },\n \"3\": {\n Name: \"Name 3\",\n Code: \"Code 3\",\n Speed: \"30\"\n }\n};\n\ndevice.addEventListener(\"change\", function() {\n let deviceID = this.value;\n let selDevice = devices[deviceID];\n if (selDevice) {\n document.getElementById(\"Name\").innerHTML = selDevice.Name;\n document.getElementById(\"Code\").innerHTML = selDevice.Code;\n document.getElementById(\"Speed\").innerHTML = selDevice.Speed;\n }\n});" }, { "answer_id": 74353703, "author": "isherwood", "author_id": 1264804, "author_profile": "https://Stackoverflow.com/users/1264804", "pm_score": 1, "selected": false, "text": "const deviceData = [{\n Name: \"Name 1\",\n Code: \"Code 1\",\n Speed: \"10\"\n}, {\n Name: \"Name 2\",\n Code: \"Code 2\",\n Speed: \"20\"\n}, {\n Name: \"Name 3\",\n Code: \"Code 3\",\n Speed: \"30\"\n}];\n\ndocument.querySelector('#select').addEventListener('change', event => {\n // zero-based index requires deducting 1 from the option value\n const user = deviceData[event.currentTarget.value - 1];\n\n document.getElementById(\"Name\").innerHTML = user.Name;\n document.getElementById(\"Code\").innerHTML = user.Code;\n document.getElementById(\"Speed\").innerHTML = user.Speed;\n});" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20444379/" ]
74,353,627
<p>I'm a newbie to python(3), but not to programming in general.</p> <p>I'd like to distribute a git repo with myprogram consisting of these files:</p> <pre><code>requirements.txt myprogram.py lib/modulea.py lib/moduleb.py </code></pre> <p>My question is: What is the best-practice and least surprising way to let users run <code>myprogram.py</code> using the dependencies in <code>requirements.txt</code>? So that after <code>git clone</code>, and some idiomatic installation command(s), <code>./myprogram.py</code> or <code>/some/path/to/myprogram.py</code> &quot;just works&quot; without having to first set magical <code>venv</code> or <code>python3</code> environment variables?</p> <p>I want to be able to run it using the <code>#!</code> shebang so that <code>/path/to/myprogram.py</code> and double-clicking it from the file manager GUI does the correct thing.</p> <p>I already know I can create a <code>wrapper.sh</code> or make a clever shebang line. But I'm looking for the best-practice approach, since I'm new to python.</p> <h2>More details</h2> <p>I'm guessing that users would</p> <pre class="lang-bash prettyprint-override"><code>git clone $url workdir cd workdir python3 -m venv . ./bin/pip install -r requirements.txt </code></pre> <p>And from now on this uses the modules from <code>requirements.txt</code>:</p> <pre class="lang-bash prettyprint-override"><code>./myprogram.py </code></pre> <p>If I knew that the project directory was always <code>/home/peter/workdir</code>, I could start the <code>myprogram.py</code> with:</p> <pre><code>#!/home/peter/workdir/bin/python3 </code></pre> <p>but I'd like to avoid hard-coding the project directory in <code>myprogram.py</code>.</p> <p>This also seems to work in my tiny demo, but clearly this is brittle and <em>not</em> best-practice, but it illustrates what I'm trying to do:</p> <pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python3 import os import sys print(os.path.join(os.path.dirname(__file__), 'lib', 'python3.10', 'site-packages')) </code></pre> <p>I'm sure I could come up with some home-grown shebang line that works, but what is the idiomatic way to do this in python3?</p> <p>Again: After <code>pip install</code>, I absolutely refuse to have to to set <em>any</em> environment variables or call any setup code in future shells before running <code>myprogram.py</code>. (Unless that <em>strongly</em> conflicts with &quot;idiomatic&quot;, which I hope isn't the case)...</p>
[ { "answer_id": 74353921, "author": "Victor Sandoval", "author_id": 13500362, "author_profile": "https://Stackoverflow.com/users/13500362", "pm_score": 0, "selected": false, "text": "./bin/pip install -r requirements.txt" }, { "answer_id": 74396145, "author": "Peter V. Mørch", "author_id": 345716, "author_profile": "https://Stackoverflow.com/users/345716", "pm_score": 2, "selected": true, "text": "pyproject.toml" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/345716/" ]
74,353,634
<p>I'm currently learning Kotlin and I'm trying to understand something. The tutorial I'm following is making a toolbar. We made the toolbar in the layout xml file then used setSupportActionBar() to find it. I can see that setSupportActionBar() is part of the AppCompatActivity class.</p> <p>We then use supportActionBar.setNavigationOnClickListener{}. What I'm confused about is where is this supportActionBar variable coming from? It's not defined in any of the code on the course. When I highlight it tells me it comes from androidx.appcompat.app.ActionBar but that it is actually &quot;getSupportActionBar()&quot;. When I ctrl + click the variable, it shows me getSupportActionBar() in AppCompatActivity.</p> <p>But for the life of me I can't figure out where this &quot;supportActionBar&quot; object is coming from. I can't find it in the android docs or anywhere. I can see the ActionBar class has the getSupportActionBar() method and the setSupportActionBar is coming from AppCompatActivity. But where does this variable come from? How am I supposed to know if such things exist if they aren't in the docs?</p> <p>Not sure if this makes any sense. Here is the code, please ignore the note ExerciseActivity.kt</p> <pre><code>package com.example.a7minutesworkout import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.example.a7minutesworkout.databinding.ActivityExerciseBinding import com.example.a7minutesworkout.databinding.ActivityMainBinding </code></pre> <p>class ExerciseActivity : AppCompatActivity() {</p> <pre><code>private var binding : ActivityExerciseBinding? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityExerciseBinding.inflate(layoutInflater) setContentView(binding?.root) setSupportActionBar(binding?.toolbarExercise) if(supportActionBar != null){ supportActionBar?.setDisplayHomeAsUpEnabled(true) } binding?.toolbarExercise?.setNavigationOnClickListener { onBackPressed() } }} </code></pre> <p>the layout xml file, activity_exercise:</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot; xmlns:tools=&quot;http://schemas.android.com/tools&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;match_parent&quot; tools:context=&quot;.ExerciseActivity&quot;&gt; &lt;androidx.appcompat.widget.Toolbar android:id=&quot;@+id/toolbarExercise&quot; android:layout_width=&quot;match_parent&quot; android:theme=&quot;@style/ToolbarTheme&quot; android:layout_height=&quot;?android:attr/actionBarSize&quot; android:background=&quot;@color/white&quot; app:titleTextColor=&quot;@color/colorPrimary&quot;/&gt; &lt;/RelativeLayout&gt; </code></pre> <p>I might be able to understand if i was having to catch the output of getSupportActionBar() in a variable something like:</p> <pre><code>var supportActionBar = getSupportActionBar() </code></pre> <p>But that isn't in the code on the course. This &quot;supportActionBar&quot; variable seems to just magically exist. I feel like I'm missing some key thing about kotlin. I have learned java before and I feel like I'm missing some big piece to the kotlin puzzle. I'm not even sure if &quot;supportActionBar&quot; is a variable? It just has the lower case camel case so I assume it is. Can anyone fill me in?</p> <p>Thanks</p>
[ { "answer_id": 74353921, "author": "Victor Sandoval", "author_id": 13500362, "author_profile": "https://Stackoverflow.com/users/13500362", "pm_score": 0, "selected": false, "text": "./bin/pip install -r requirements.txt" }, { "answer_id": 74396145, "author": "Peter V. Mørch", "author_id": 345716, "author_profile": "https://Stackoverflow.com/users/345716", "pm_score": 2, "selected": true, "text": "pyproject.toml" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10873338/" ]
74,353,650
<p><a href="https://i.stack.imgur.com/n4dPj.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/n4dPj.jpg" alt="enter image description here" /></a> Just for clarity - Here is an image for reference, I want to click on any of the smaller cubes at the bottom so that the corresponding larger cube moves left or right till it's centred in the screen.</p> <p>So this is the script I'm using, and my issue is that once I've clicked my trigger it only moves a fraction of the total distance, the MoveTowards function does work the way I want, the only issue is that I have to click on my trigger/s multiple times before it reaches it's set destination, I would like this to work so that I only have to click the trigger once and it will smoothly move to it's set destination incrementally instead of based off a certain amount of time between position because the starting position will constantly be changing.</p> <p>From what I've researched I think I'll need a coroutine, I'm just wondering if there's a simpler way to do this as it feels like I'm only one or 2 steps off my goal here.</p> <pre class="lang-cs prettyprint-override"><code>public class MoveBoxes : MonoBehaviour { RayCast rayCast; Camera cam; public LayerMask mask; private float speed = 7500f; public Vector3 initialPosition; public Vector3 positionOne; public Vector3 positionTwo; public Vector3 positionThree; public Vector3 positionFour; public Vector3 positionFive; public Vector3 positionSix; public Vector3 positionSeven; public Vector3 positionEight; public Vector3 positionNine; public Vector3 positionTen; public Vector3 positionEleven; public Vector3 positionTwelve; public Vector3 positionThirteen; public Vector3 positionFourteen; public Vector3 tempPosition; void Awake() { cam = Camera.main; initialPosition = new Vector3(-28000.20f, -102.18f, -3919.06f); positionOne = new Vector3(37000.20f, -102.18f, -3919.06f); positionTwo = new Vector3(27000.20f, -102.18f, -3919.06f); positionThree = new Vector3(17000.20f, -102.18f, -3919.06f); positionFour = new Vector3(7000.20f, -102.18f, -3919.06f); positionFive = new Vector3(-3000.20f, -102.18f, -3919.06f); positionSix = new Vector3(-13000.20f, -102.18f, -3919.06f); positionSeven = new Vector3(-23000.20f, -102.18f, -3919.06f); positionEight = new Vector3(-33000.20f, -102.18f, -3919.06f); positionNine = new Vector3(-43000.20f, -102.18f, -3919.06f); positionTen = new Vector3(-53000.20f, -102.18f, -3919.06f); positionEleven = new Vector3(-63000.20f, -102.18f, -3919.06f); positionTwelve = new Vector3(-73000.20f, -102.18f, -3919.06f); positionThirteen = new Vector3(-83000.20f, -102.18f, -3919.06f); positionFourteen = new Vector3(-93000.20f, -102.18f, -3919.06f); tempPosition = transform.position; Debug.Log(transform.position); } void Update() { float move = speed * Time.deltaTime; bool hitTarget = false; if (Input.GetMouseButtonDown(0)) { Ray ray = cam.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(ray, out hit, 15000, mask)) { if (hit.collider.tag == &quot;1stBox&quot;) do { transform.position = Vector3.MoveTowards(transform.position, positionOne, move); Debug.Log(transform.position); } while (hitTarget == true); if (hit.collider.tag == &quot;2ndBox&quot;) { transform.position = Vector3.MoveTowards(transform.position, positionTwo, move); Debug.Log(transform.position); } if (hit.collider.tag == &quot;3rdBox&quot;) { transform.position = Vector3.MoveTowards(transform.position, positionThree, move); Debug.Log(transform.position); } if (hit.collider.tag == &quot;4thBox&quot;) { transform.position = Vector3.MoveTowards(transform.position, positionFour, move); Debug.Log(transform.position); } if (hit.collider.tag == &quot;5thBox&quot;) { transform.position = Vector3.MoveTowards(transform.position, positionFive, move); Debug.Log(transform.position); } if (hit.collider.tag == &quot;6thBox&quot;) { transform.position = Vector3.MoveTowards(transform.position, positionSix, move); Debug.Log(transform.position); } if (hit.collider.tag == &quot;7thBox&quot;) { transform.position = Vector3.MoveTowards(transform.position, positionSeven, move); Debug.Log(transform.position); } if (hit.collider.tag == &quot;8thBox&quot;) { transform.position = Vector3.MoveTowards(transform.position, positionEight, move); Debug.Log(transform.position); } if (hit.collider.tag == &quot;9thBox&quot;) { transform.position = Vector3.MoveTowards(transform.position, positionNine, move); Debug.Log(transform.position); } if (hit.collider.tag == &quot;10thBox&quot;) { transform.position = Vector3.MoveTowards(transform.position, positionTen, move); Debug.Log(transform.position); } if (hit.collider.tag == &quot;11thBox&quot;) { transform.position = Vector3.MoveTowards(transform.position, positionEleven, move); Debug.Log(transform.position); } if (hit.collider.tag == &quot;12thBox&quot;) { transform.position = Vector3.MoveTowards(transform.position, positionTwelve, move); Debug.Log(transform.position); } if (hit.collider.tag == &quot;13thBox&quot;) { transform.position = Vector3.MoveTowards(transform.position, positionThirteen, move); Debug.Log(transform.position); } if (hit.collider.tag == &quot;14thBox&quot;) { transform.position = Vector3.MoveTowards(transform.position, positionFourteen, move); Debug.Log(transform.position); } } } } </code></pre> <p>I've looked into a bunch of different ways on how to do this, most results I get involve using a character, my project does not involve a character at this point in the game, nor does it need a rigid body, these GameObjects will eventually be triggers for further events.</p> <p>I need my Parent-GameObject to move based off of framerate/increments of space rather than based off amount of time. as the whole object shifts, the starting position will be constantly changing also.</p> <p>The do/while statement in the code can be removed, at the moment it's ineffective, I was trying to use this method to loop the function in my script, with the goal to make a single mouse click act asif it's continuously being clicked. At the moment when I click on a trigger it will only move a fraction of the distance towards the target destination.</p>
[ { "answer_id": 74354005, "author": "D4V3XX", "author_id": 12382672, "author_profile": "https://Stackoverflow.com/users/12382672", "pm_score": 2, "selected": false, "text": " if (Physics.Raycast(ray, out hit, 15000, mask))\n {\n \n if (hit.collider.tag == \"1stBox\"){\n ....\n }\n ......\n }\n" }, { "answer_id": 74354357, "author": "Milan Egon Votrubec", "author_id": 8051819, "author_profile": "https://Stackoverflow.com/users/8051819", "pm_score": 2, "selected": false, "text": "MoveTowards" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20443360/" ]
74,353,658
<p>Is it possible to rotate loaded texture on sphere geometry in Three.js? I don't want to rotate the object, just texture that is applied to material. Let's say I have a sphere that looks like that: <a href="https://i.stack.imgur.com/Ol3y7.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ol3y7.jpg" alt="enter image description here" /></a></p> <p>And I just want it to rotate in x/y/z direction by n degrees to look like that: <a href="https://i.stack.imgur.com/nl7p8.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nl7p8.jpg" alt="enter image description here" /></a></p>
[ { "answer_id": 74354351, "author": "Anye", "author_id": 16752210, "author_profile": "https://Stackoverflow.com/users/16752210", "pm_score": 2, "selected": true, "text": "function render(){\n requestAnimationFrame(render);\n renderer.render(scene, camera);\n\n sphere.rotation.y += 0.01;\n}\n\nrender();\n" }, { "answer_id": 74360687, "author": "prisoner849", "author_id": 4045502, "author_profile": "https://Stackoverflow.com/users/4045502", "pm_score": 0, "selected": false, "text": "let scene = new THREE.Scene();\nlet camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 0.1, 100);\ncamera.position.set(1, 2, 7);\nlet renderer = new THREE.WebGLRenderer();\nrenderer.setSize(innerWidth, innerHeight);\ndocument.body.prepend(renderer.domElement);\n\nlet controls = new THREE.OrbitControls(camera, renderer.domElement);\n\nscene.add(new THREE.AxesHelper(2));\n\nconst orbitRadius = 5;\nlet orbitPath = new THREE.Path().absarc(0, 0, orbitRadius, 0, Math.PI * 2);\nlet orbit = new THREE.Line(\n new THREE.BufferGeometry().setFromPoints(orbitPath.getSpacedPoints(72)).rotateX(-Math.PI * 0.5), \n new THREE.LineBasicMaterial({color: \"yellow\"})\n);\nscene.add(orbit);\n\nlet globe = new THREE.Mesh(\n new THREE.SphereGeometry(2, 16, 8), \n new THREE.MeshBasicMaterial({color: \"magenta\", wireframe: true})\n);\nglobe.rotation.order = \"ZYX\"; // set rotation order\nglobe.rotation.z = THREE.MathUtils.degToRad(23); // inclination\nglobe.add(\n new THREE.Line(\n new THREE.BufferGeometry().setFromPoints([new THREE.Vector2(0, -3), new THREE.Vector2(0, 3)]), \n new THREE.LineBasicMaterial({color: \"aqua\"})\n )\n)\nscene.add(globe);\n\nlet clock = new THREE.Clock();\n\nrenderer.setAnimationLoop( _ => {\n let t = clock.getElapsedTime();\n \n globe.rotation.y = t;\n globe.position.x = Math.cos(t * 0.25) * orbitRadius;\n globe.position.z = -Math.sin(t * 0.25) * orbitRadius;\n \n renderer.render(scene, camera);\n});" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14741168/" ]
74,353,671
<p>Python question: I have a list of sentences on which I want to apply nltk stemming. So for each word in each sentence, I want to apply, in this case, the nltk snowball.stem function.</p> <p>I want to write that as short as possible via list comprehension. Below code works fine, but I want to write it in less lines:</p> <pre><code>data_stemming=[] for sentence in data: word_list=word_tokenize(sentence) stemmed_sentence=' '.join([stemmer.stem(w) for w in word_list]) data_stemming.append(stemmed_sentence) print(data_stemming) </code></pre> <p>output:</p> <pre><code>['do do done', 'do requir', 'shoe shoe'] </code></pre> <p>Can someone help me out here?</p> <p>Thanks a lot!</p>
[ { "answer_id": 74354351, "author": "Anye", "author_id": 16752210, "author_profile": "https://Stackoverflow.com/users/16752210", "pm_score": 2, "selected": true, "text": "function render(){\n requestAnimationFrame(render);\n renderer.render(scene, camera);\n\n sphere.rotation.y += 0.01;\n}\n\nrender();\n" }, { "answer_id": 74360687, "author": "prisoner849", "author_id": 4045502, "author_profile": "https://Stackoverflow.com/users/4045502", "pm_score": 0, "selected": false, "text": "let scene = new THREE.Scene();\nlet camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 0.1, 100);\ncamera.position.set(1, 2, 7);\nlet renderer = new THREE.WebGLRenderer();\nrenderer.setSize(innerWidth, innerHeight);\ndocument.body.prepend(renderer.domElement);\n\nlet controls = new THREE.OrbitControls(camera, renderer.domElement);\n\nscene.add(new THREE.AxesHelper(2));\n\nconst orbitRadius = 5;\nlet orbitPath = new THREE.Path().absarc(0, 0, orbitRadius, 0, Math.PI * 2);\nlet orbit = new THREE.Line(\n new THREE.BufferGeometry().setFromPoints(orbitPath.getSpacedPoints(72)).rotateX(-Math.PI * 0.5), \n new THREE.LineBasicMaterial({color: \"yellow\"})\n);\nscene.add(orbit);\n\nlet globe = new THREE.Mesh(\n new THREE.SphereGeometry(2, 16, 8), \n new THREE.MeshBasicMaterial({color: \"magenta\", wireframe: true})\n);\nglobe.rotation.order = \"ZYX\"; // set rotation order\nglobe.rotation.z = THREE.MathUtils.degToRad(23); // inclination\nglobe.add(\n new THREE.Line(\n new THREE.BufferGeometry().setFromPoints([new THREE.Vector2(0, -3), new THREE.Vector2(0, 3)]), \n new THREE.LineBasicMaterial({color: \"aqua\"})\n )\n)\nscene.add(globe);\n\nlet clock = new THREE.Clock();\n\nrenderer.setAnimationLoop( _ => {\n let t = clock.getElapsedTime();\n \n globe.rotation.y = t;\n globe.position.x = Math.cos(t * 0.25) * orbitRadius;\n globe.position.z = -Math.sin(t * 0.25) * orbitRadius;\n \n renderer.render(scene, camera);\n});" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1035461/" ]
74,353,695
<p>The C script is supposed to take x amount of CPU bound forks and x amount of IO bound forks, so then lets say 10 total processes if you there's 5 of each. If I fork 10 times, then 5 of those should go to working on the CPU bound &quot;fake work&quot; and 5 of those should go to the IO bound &quot;fake work&quot;. Waitstats is a custom function that serves the purpose of wait while also displaying rtime and wtime.</p> <p>My problem is that I've tried multiple configurations and I'm not sure how to get the Process Number printf to correctly print, only 10 times, if there's only 10 forks? I also feel as if I'm not doing my fake work correctly for the CPU/IO bound work.</p> <p>Any help here would be appreciated!</p> <p>`</p> <pre><code>int main(int argc, char* argv[]) { int cpuNum = atoi(argv[2]); int ioNum = atoi(argv[4]); int const MAX_PROC = cpuNum + ioNum; printf(&quot;\nMax Proc %d&quot;, MAX_PROC); int totRunTime = 0; int totWaitTime = 0; uint rTime = 0; uint wTime = 0; int pid = 0; //Create Max_Proc Forks for(int n=0; n &lt; MAX_PROC; n++) { pid = fork(); //If Child, Exceute Command if(pid == 0) { break; } } if (cpuNum &gt; 0) { //CPU Busy Work for (volatile int i = 0; i &lt; 1000000000; i++){} cpuNum--; } else if (ioNum &gt; 0) { //IO Busy Work sleep(200); ioNum--; } for(int p=0; p &lt; MAX_PROC; p++) { printf(&quot;\n Process %d finished&quot;, p); if(waitStats(0, &amp;rTime, &amp;wTime) &gt;= 0) { totRunTime += rTime; totWaitTime += wTime; } } printf(&quot;\nAverage rtime %d, wtime %d&quot;, rTime, wTime); exit(0); } </code></pre> <p>`</p> <p>I've tried multiple configurations, but can't seem to get the printf to print the correct process/fork number. For instance forking 10 times would mean I would need to printf every time one of those forks finished their task (10 total times).</p>
[ { "answer_id": 74354351, "author": "Anye", "author_id": 16752210, "author_profile": "https://Stackoverflow.com/users/16752210", "pm_score": 2, "selected": true, "text": "function render(){\n requestAnimationFrame(render);\n renderer.render(scene, camera);\n\n sphere.rotation.y += 0.01;\n}\n\nrender();\n" }, { "answer_id": 74360687, "author": "prisoner849", "author_id": 4045502, "author_profile": "https://Stackoverflow.com/users/4045502", "pm_score": 0, "selected": false, "text": "let scene = new THREE.Scene();\nlet camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 0.1, 100);\ncamera.position.set(1, 2, 7);\nlet renderer = new THREE.WebGLRenderer();\nrenderer.setSize(innerWidth, innerHeight);\ndocument.body.prepend(renderer.domElement);\n\nlet controls = new THREE.OrbitControls(camera, renderer.domElement);\n\nscene.add(new THREE.AxesHelper(2));\n\nconst orbitRadius = 5;\nlet orbitPath = new THREE.Path().absarc(0, 0, orbitRadius, 0, Math.PI * 2);\nlet orbit = new THREE.Line(\n new THREE.BufferGeometry().setFromPoints(orbitPath.getSpacedPoints(72)).rotateX(-Math.PI * 0.5), \n new THREE.LineBasicMaterial({color: \"yellow\"})\n);\nscene.add(orbit);\n\nlet globe = new THREE.Mesh(\n new THREE.SphereGeometry(2, 16, 8), \n new THREE.MeshBasicMaterial({color: \"magenta\", wireframe: true})\n);\nglobe.rotation.order = \"ZYX\"; // set rotation order\nglobe.rotation.z = THREE.MathUtils.degToRad(23); // inclination\nglobe.add(\n new THREE.Line(\n new THREE.BufferGeometry().setFromPoints([new THREE.Vector2(0, -3), new THREE.Vector2(0, 3)]), \n new THREE.LineBasicMaterial({color: \"aqua\"})\n )\n)\nscene.add(globe);\n\nlet clock = new THREE.Clock();\n\nrenderer.setAnimationLoop( _ => {\n let t = clock.getElapsedTime();\n \n globe.rotation.y = t;\n globe.position.x = Math.cos(t * 0.25) * orbitRadius;\n globe.position.z = -Math.sin(t * 0.25) * orbitRadius;\n \n renderer.render(scene, camera);\n});" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20444441/" ]
74,353,696
<p>could you guys help me with a project. I was able to find a solution for my problem and the formula looks like this:</p> <pre><code>=IFERROR(VLOOKUP(E4;A8:B13;2;FALSE);0)+IFERROR(VLOOKUP(F4;A8:B13;2;FALSE);0)+IFERROR(VLOOKUP(G4;A8:B13;2;FALSE);0) </code></pre> <p>I have a category (e.g. Fruits) and need to import a sheet with different kind of fruits and non fruits. I use keywords which define what is a fruit and what not. I need to SUM all values which match to a keyword. My formula works but it will be more and more work when i need to add more keywords.</p> <p>Are there a better way to realise this?</p> <p>I build this example sheet for better understanding : )</p> <p><a href="https://i.stack.imgur.com/MldXm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MldXm.png" alt="enter image description here" /></a> <a href="https://docs.google.com/spreadsheets/d/1OcJus2Gk__eIGGbP5LvyUFs6fPMKwb5HxCEVUb3nx9U/edit?usp=sharing" rel="nofollow noreferrer">Spreadsheet link</a></p> <p>Thank you in advance : )</p>
[ { "answer_id": 74354351, "author": "Anye", "author_id": 16752210, "author_profile": "https://Stackoverflow.com/users/16752210", "pm_score": 2, "selected": true, "text": "function render(){\n requestAnimationFrame(render);\n renderer.render(scene, camera);\n\n sphere.rotation.y += 0.01;\n}\n\nrender();\n" }, { "answer_id": 74360687, "author": "prisoner849", "author_id": 4045502, "author_profile": "https://Stackoverflow.com/users/4045502", "pm_score": 0, "selected": false, "text": "let scene = new THREE.Scene();\nlet camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 0.1, 100);\ncamera.position.set(1, 2, 7);\nlet renderer = new THREE.WebGLRenderer();\nrenderer.setSize(innerWidth, innerHeight);\ndocument.body.prepend(renderer.domElement);\n\nlet controls = new THREE.OrbitControls(camera, renderer.domElement);\n\nscene.add(new THREE.AxesHelper(2));\n\nconst orbitRadius = 5;\nlet orbitPath = new THREE.Path().absarc(0, 0, orbitRadius, 0, Math.PI * 2);\nlet orbit = new THREE.Line(\n new THREE.BufferGeometry().setFromPoints(orbitPath.getSpacedPoints(72)).rotateX(-Math.PI * 0.5), \n new THREE.LineBasicMaterial({color: \"yellow\"})\n);\nscene.add(orbit);\n\nlet globe = new THREE.Mesh(\n new THREE.SphereGeometry(2, 16, 8), \n new THREE.MeshBasicMaterial({color: \"magenta\", wireframe: true})\n);\nglobe.rotation.order = \"ZYX\"; // set rotation order\nglobe.rotation.z = THREE.MathUtils.degToRad(23); // inclination\nglobe.add(\n new THREE.Line(\n new THREE.BufferGeometry().setFromPoints([new THREE.Vector2(0, -3), new THREE.Vector2(0, 3)]), \n new THREE.LineBasicMaterial({color: \"aqua\"})\n )\n)\nscene.add(globe);\n\nlet clock = new THREE.Clock();\n\nrenderer.setAnimationLoop( _ => {\n let t = clock.getElapsedTime();\n \n globe.rotation.y = t;\n globe.position.x = Math.cos(t * 0.25) * orbitRadius;\n globe.position.z = -Math.sin(t * 0.25) * orbitRadius;\n \n renderer.render(scene, camera);\n});" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353696", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20444417/" ]
74,353,757
<p>I have just started using neo4j.</p> <p>I was trying to use it to describe a company's Enterprise Architecture.</p> <p>I'd like to show that, by removing the node &quot;Middleware&quot;, Service_A goes from Client_A and Server_X, and the same for the other services.</p> <p>Is there a way to do that? Is this the right approach?</p> <p>Next is the code used to generate the graph.</p> <p><a href="https://i.stack.imgur.com/YxtnD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YxtnD.png" alt="enter image description here" /></a></p> <pre><code>from neo4j import GraphDatabase import logging from neo4j.exceptions import ServiceUnavailable class App: def __init__(self, uri, user, password): self.driver = GraphDatabase.driver(uri, auth=(user, password)) def close(self): # Don't forget to close the driver connection when you are finished with it self.driver.close() def drop_everything(self): with self.driver.session(database=&quot;neo4j&quot;) as session: # Write transactions allow the driver to handle retries and transient errors session.execute_write(self._drop_everything) print(&quot;Graph DB dropped&quot;) @staticmethod def _drop_everything(tx): query = ( &quot;MATCH (n) DETACH DELETE (n)&quot; ) try: tx.run(query) # Capture any errors along with the query and data for traceability except ServiceUnavailable as exception: logging.error(&quot;{query} raised an error: \n {exception}&quot;.format(query=query, exception=exception)) raise def create_system(self, system_name): with self.driver.session(database=&quot;neo4j&quot;) as session: # Write transactions allow the driver to handle retries and transient errors result = session.execute_write(self._create_system, system_name) print(&quot;Created system: {p1}&quot;.format(p1=result)) @staticmethod def _create_system(tx, system_name): # To learn more about the Cypher syntax, see https://neo4j.com/docs/cypher-manual/current/ # The Reference Card is also a good resource for keywords https://neo4j.com/docs/cypher-refcard/current/ query = ( &quot;CREATE (n:system{name:$system_name}) &quot; &quot;RETURN (n)&quot; ) result = tx.run(query, system_name=system_name) try: return result.single()[0][&quot;name&quot;] # Capture any errors along with the query and data for traceability except ServiceUnavailable as exception: logging.error(&quot;{query} raised an error: \n {exception}&quot;.format(query=query, exception=exception)) raise def create_flow(self, service_name_a, system1_name, system2_name): with self.driver.session(database=&quot;neo4j&quot;) as session: # Write transactions allow the driver to handle retries and transient errors result = session.execute_write(self._create_flow, service_name_a, system1_name, system2_name) print(&quot;Created flow: {p1}&quot;.format(p1=result)) @staticmethod def _create_flow(tx, service_name, system1_name, system2_name): query = ( &quot;MATCH (p1:system), (p2:system) &quot; &quot;WHERE p1.name = '&quot; + system1_name + &quot;' AND p2.name = '&quot; + system2_name +&quot;' &quot; &quot;CREATE (p1)-[r:&quot; + service_name + &quot; {type:'call'}]-&gt;(p2) &quot; &quot;RETURN ('&quot; + service_name + &quot;')&quot; ) # CREATE (p1)-[r:service {name:'&quot; + service_name + &quot;'}]-&gt;(p2) # CALL apoc.create.relationship(p1, '$service_name', NULL, p2) YIELD rel # CREATE (p1)-[:service {name:'$service_name'}]-&gt;(p2) &quot; result = tx.run(query, service_name=service_name, system1_name=system1_name, system2_name=system2_name) try: return service_name # Capture any errors along with the query and data for traceability except ServiceUnavailable as exception: logging.error(&quot;{query} raised an error: \n {exception}&quot;.format(query=query, exception=exception)) raise def find_system(self, system_name): with self.driver.session(database=&quot;neo4j&quot;) as session: result = session.execute_read(self._find_system, system_name) for row in result: print(&quot;Found system: {row}&quot;.format(row=row)) @staticmethod def find_system(tx, system_name): query = ( &quot;MATCH (p:system) &quot; &quot;WHERE p.name = $system_name &quot; &quot;RETURN p.name AS name&quot; ) result = tx.run(query, system_name=system_name) return [{ row[&quot;name&quot;] } for row in result] if __name__ == &quot;__main__&quot;: # Aura queries use an encrypted connection using the &quot;neo4j+s&quot; URI scheme # https://console.neo4j.io/ - Login with google mario.stefanutti@gmail.com uri = &quot;neo4j+s://8a9f54ab.databases.neo4j.io&quot; user = &quot;neo4j&quot; password = &quot;Xxx&quot; app = App(uri, user, password) app.drop_everything() app.create_system(&quot;Client_A&quot;) app.create_system(&quot;Middleware&quot;) app.create_system(&quot;Server_X&quot;) app.create_system(&quot;Server_Y&quot;) app.create_system(&quot;Server_Z&quot;) app.create_flow(&quot;Service_A&quot;, &quot;Client_A&quot;, &quot;Middleware&quot;) app.create_flow(&quot;Service_B&quot;, &quot;Client_A&quot;, &quot;Middleware&quot;) app.create_flow(&quot;Service_C&quot;, &quot;Client_A&quot;, &quot;Middleware&quot;) app.create_flow(&quot;Service_A&quot;, &quot;Middleware&quot;, &quot;Server_X&quot;) app.create_flow(&quot;Service_B&quot;, &quot;Middleware&quot;, &quot;Server_Y&quot;) app.create_flow(&quot;Service_C&quot;, &quot;Middleware&quot;, &quot;Server_Z&quot;) app.close() </code></pre>
[ { "answer_id": 74354351, "author": "Anye", "author_id": 16752210, "author_profile": "https://Stackoverflow.com/users/16752210", "pm_score": 2, "selected": true, "text": "function render(){\n requestAnimationFrame(render);\n renderer.render(scene, camera);\n\n sphere.rotation.y += 0.01;\n}\n\nrender();\n" }, { "answer_id": 74360687, "author": "prisoner849", "author_id": 4045502, "author_profile": "https://Stackoverflow.com/users/4045502", "pm_score": 0, "selected": false, "text": "let scene = new THREE.Scene();\nlet camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 0.1, 100);\ncamera.position.set(1, 2, 7);\nlet renderer = new THREE.WebGLRenderer();\nrenderer.setSize(innerWidth, innerHeight);\ndocument.body.prepend(renderer.domElement);\n\nlet controls = new THREE.OrbitControls(camera, renderer.domElement);\n\nscene.add(new THREE.AxesHelper(2));\n\nconst orbitRadius = 5;\nlet orbitPath = new THREE.Path().absarc(0, 0, orbitRadius, 0, Math.PI * 2);\nlet orbit = new THREE.Line(\n new THREE.BufferGeometry().setFromPoints(orbitPath.getSpacedPoints(72)).rotateX(-Math.PI * 0.5), \n new THREE.LineBasicMaterial({color: \"yellow\"})\n);\nscene.add(orbit);\n\nlet globe = new THREE.Mesh(\n new THREE.SphereGeometry(2, 16, 8), \n new THREE.MeshBasicMaterial({color: \"magenta\", wireframe: true})\n);\nglobe.rotation.order = \"ZYX\"; // set rotation order\nglobe.rotation.z = THREE.MathUtils.degToRad(23); // inclination\nglobe.add(\n new THREE.Line(\n new THREE.BufferGeometry().setFromPoints([new THREE.Vector2(0, -3), new THREE.Vector2(0, 3)]), \n new THREE.LineBasicMaterial({color: \"aqua\"})\n )\n)\nscene.add(globe);\n\nlet clock = new THREE.Clock();\n\nrenderer.setAnimationLoop( _ => {\n let t = clock.getElapsedTime();\n \n globe.rotation.y = t;\n globe.position.x = Math.cos(t * 0.25) * orbitRadius;\n globe.position.z = -Math.sin(t * 0.25) * orbitRadius;\n \n renderer.render(scene, camera);\n});" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1483141/" ]
74,353,771
<p>i have the following array of dictionaries with the one below as an example of a single dictionary</p> <pre><code>{ &quot;id&quot;: 80, &quot;name&quot;: &quot;Low Level Topic&quot;, &quot;questions&quot;: [ { &quot;id&quot;: 23, &quot;shortName&quot;: null, &quot;name&quot;: &quot;Some question&quot; }, { &quot;id&quot;: 24, &quot;shortName&quot;: null, &quot;name&quot;: &quot;Some question 2&quot; } ], &quot;parentTopic&quot;: { &quot;id&quot;: 10, &quot;name&quot;: &quot;Higher Level Topic&quot;, &quot;parentTopic&quot;: { &quot;id&quot;: 1, &quot;name&quot;: &quot;Top Level Topic&quot;, &quot;parentTopic&quot;: null } } } } </code></pre> <p>and i would like to reverse the tree to end up with the following</p> <pre><code>{ &quot;id&quot;: 1, &quot;name&quot;: &quot;Top Level Topic&quot;, &quot;childTopic&quot;: { &quot;id&quot;: 10, &quot;name&quot;: &quot;Higher Level Topic&quot;, &quot;childTopic&quot;: { &quot;id&quot;: 80, &quot;name&quot;: &quot;Low Level Topic&quot;, &quot;questions&quot;: [ { &quot;id&quot;: 23, &quot;shortName&quot;: null, &quot;name&quot;: &quot;Some question&quot; }, { &quot;id&quot;: 24, &quot;shortName&quot;: null, &quot;name&quot;: &quot;Some question 2&quot; } ], } } } </code></pre> <p>i have been trying to find an easy way to regenerate/restructure the data, but was not successful. I would appreciate if anyone could help</p>
[ { "answer_id": 74354016, "author": "caTS", "author_id": 18244921, "author_profile": "https://Stackoverflow.com/users/18244921", "pm_score": 0, "selected": false, "text": "let data = {\"id\":80,\"name\":\"Low Level Topic\",\"questions\":[{\"id\":23,\"shortName\":null,\"name\":\"Some question\"},{\"id\":24,\"shortName\":null,\"name\":\"Some question 2\"}],\"parentTopic\":{\"id\":10,\"name\":\"Higher Level Topic\",\"parentTopic\":{\"id\":1,\"name\":\"Top Level Topic\",\"parentTopic\":null}}};\n\n// WARNING: this code MUTATES the object\n\n// previous topic, current topic, new tail as 'tail'\nlet prev = null, curr = data, tail = data.parentTopic;\n\nwhile (curr) {\n next = curr.parentTopic;\n delete curr.parentTopic; // rename parentTopic\n curr.childTopic = prev; // to childTopic\n prev = curr;\n curr = next;\n}\n\ndelete tail.childTopic.childTopic; // delete since it's null\n\ndata = prev; // assign new head to data\n\nconsole.log(data);" }, { "answer_id": 74357833, "author": "Asraf", "author_id": 20361860, "author_profile": "https://Stackoverflow.com/users/20361860", "pm_score": 2, "selected": true, "text": "let obj = {\"id\":80,\"name\":\"Low Level Topic\",\"questions\":[{\"id\":23,\"shortName\":null,\"name\":\"Some question\"},{\"id\":24,\"shortName\":null,\"name\":\"Some question 2\"}],\"parentTopic\":{\"id\":10,\"name\":\"Higher Level Topic\",\"parentTopic\":{\"id\":1,\"name\":\"Top Level Topic\",\"parentTopic\":null}}};\n\nconst buildReverseObj = (originalObj, currObj) => {\n const copyObj = { // make copy of original obj\n ...originalObj,\n };\n const parentTopic = copyObj.parentTopic; // get the parentTopic to process in next step\n delete copyObj.parentTopic; // parentTopic should be removed \n\n const childTopic = { // make a child topic in every step it consists of older contents and newer contents\n ...copyObj,\n ...currObj\n };\n if (!parentTopic) return childTopic; // when parentTopic = null we are done\n\n return buildReverseObj(parentTopic, { childTopic });\n};\nconsole.log(buildReverseObj(obj, {}));" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2906950/" ]
74,353,783
<p>I would like to generate a sparse matrix using a custom discrete distribution.</p> <p>E.g.:</p> <pre><code>from scipy.sparse import random from scipy import stats xk = np.arange(7) pk = np.array([0.1, 0.2, 0.3, 0.1, 0.1, 0.1, 0.1]) custm = stats.rv_discrete(name='custm', values=(xk, pk)) rvs = custm.rvs dens = 0.5 S = random(1, 8, density=dens, data_rvs=rvs) print(S.A) </code></pre> <p>I would expect to get something like so:</p> <pre><code>[4, 5, 0, 3, 0, 1, 0, 0] </code></pre> <p>The above code works just fine for rvs of a continuous distribution (such as rvs = stats.norm().rvs), but when I use a discrete distribution I am met with this error:</p> <pre><code> File &quot;Python\Python310\site-packages\scipy\sparse\_construct.py&quot;, line 875, in random vals = data_rvs(k).astype(dtype, copy=False) AttributeError: 'int' object has no attribute 'astype' </code></pre> <p>This error persists even if convert the xk array to floats using np.array(xk,dtype=np.float64).</p> <p>I have considered some work-arounds such as generating array indices in advance and then randomly picking xk values. A bit messy, but do-able. But I suspect I am not understanding about how sparse.random handles random variates?</p>
[ { "answer_id": 74354418, "author": "Nick ODell", "author_id": 530160, "author_profile": "https://Stackoverflow.com/users/530160", "pm_score": 2, "selected": false, "text": "vals = data_rvs(k).astype(dtype, copy=False)\n" }, { "answer_id": 74368400, "author": "Warren Weckesser", "author_id": 1217358, "author_profile": "https://Stackoverflow.com/users/1217358", "pm_score": 2, "selected": false, "text": "custm" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9494464/" ]
74,353,791
<p>I'm writing the unit tests for the old method, which uses <code>CompletableFuture.supplyAsync()</code>. The method is not complex, but my unit test keeps running and does not stop when executing the <code>join()</code>. I believe <code>supplyAsync()</code> should return the value very quickly. Is it because I set up the <code>taskExecutor</code> incorrectly? I'm new to Spring and Java, so please advise anything. Thank you.</p> <p>Code:</p> <pre><code> public Response getReponse(Request request) { CompletableFuture&lt;String&gt; vip = CompletableFuture.supplyAsync(() -&gt; { if(StringUtils.isBlank(request.getAddress()) ){ return &quot;&quot;;} Request newRequest = Request.builder(). userId(request.getUserId()). address(request.getZipCode()). build(); Response newResult = getResult(newRequest); return (&quot;12345&quot;.equals(newResult.getZipCode()) + &quot;&quot;; }, taskExecutor); final Response result = getResult(request); result.setVIP(zipCode.join()); return result; } </code></pre> <p>My unit test:</p> <pre><code> @Mock private ThreadPoolTaskExecutor taskExecutor; @Test void getReponseTest(){ SomeService someService = new SomeService(Constants, logService, taskExecutor); final SomeService someServiceSpy = Mockito.spy(someService); final Request request = TestHelper.buildRequest(); final Response response = TestTestHelper.buildResponse(); doReturn(response).when(someServiceSpy).getResult(any(Request.class)); Response result = taxServiceSpy.getQuotationV2(taxRequest); // assertion ... } </code></pre>
[ { "answer_id": 74354128, "author": "Jared Renzullo", "author_id": 20409306, "author_profile": "https://Stackoverflow.com/users/20409306", "pm_score": 2, "selected": false, "text": "execute()" }, { "answer_id": 74381563, "author": "Meilan", "author_id": 8898054, "author_profile": "https://Stackoverflow.com/users/8898054", "pm_score": 0, "selected": false, "text": "@Spy\nprivate ThreadPoolTaskExecutor spyTaskExecutor = new ThreadPoolTaskExecutor();\n\nspyTaskExecutor.setCorePoolSize(1);\nspyTaskExecutor.setWaitForTasksToCompleteOnShutdown(true);\nspyTaskExecutor.initialize();\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8898054/" ]
74,353,793
<p>I'm currently working on creating rainy animation.</p> <p>Here's what i have tried. I created a rain drop view using <code>CSS</code> and tried to create multiple rain views using <code>JavaScript</code> modifying its position with <code>padding-right</code>. But on my webpage I can only see only one rain is dropping.</p> <p>Can anyone help me to find out what did i wrong?</p> <p>html:</p> <pre><code>&lt;main&gt;&lt;/main&gt; &lt;script src=&quot;rain.js&quot;&gt;&lt;/script&gt; </code></pre> <p>CSS:</p> <pre><code>.drop { position: absolute; bottom: 100%; width: 7px; height: 50px; pointer-events: none; background-color: blue; border-radius: 50%; animation: drop 0.7s linear infinite; z-index: 3; } </code></pre> <p>JavaScript:</p> <pre><code>const main = document.querySelector('main'); let htmlString = '&lt;div class=&quot;drop&quot;&gt;&lt;/div&gt;'; for (let i = 0; i &lt; 10; i++) { htmlString += '&lt;div class=&quot;drop&quot; style=&quot;padding-right:{i}px&gt;&lt;/div&gt;'; } main.innerHTML = htmlString; </code></pre>
[ { "answer_id": 74354128, "author": "Jared Renzullo", "author_id": 20409306, "author_profile": "https://Stackoverflow.com/users/20409306", "pm_score": 2, "selected": false, "text": "execute()" }, { "answer_id": 74381563, "author": "Meilan", "author_id": 8898054, "author_profile": "https://Stackoverflow.com/users/8898054", "pm_score": 0, "selected": false, "text": "@Spy\nprivate ThreadPoolTaskExecutor spyTaskExecutor = new ThreadPoolTaskExecutor();\n\nspyTaskExecutor.setCorePoolSize(1);\nspyTaskExecutor.setWaitForTasksToCompleteOnShutdown(true);\nspyTaskExecutor.initialize();\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12906445/" ]
74,353,798
<p>In my Angular-14 application, I want to search or filter data in a table using Text Input field and select dropdown.</p> <p>I am this JSON response:</p> <pre><code>{ &quot;data&quot;: { &quot;pageItems&quot;: [ { &quot;id&quot;: &quot;1b1b89c0-b18d-4403-b1ba-0a73c1eb2c5c&quot;, &quot;departmentId&quot;: &quot;66306a0e-3369-4e5f-b8ed-d158b147d252&quot;, &quot;firstName&quot;: &quot;Janet&quot;, &quot;lastName&quot;: &quot;Smith&quot;, &quot;employeeDepartment&quot;: 1, &quot;employeeDepartment&quot;: { &quot;departmentName&quot;: &quot;Account&quot; } } ], &quot;pageSize&quot;: 10, &quot;currentPage&quot;: 1, &quot;numberOfPages&quot;: 1, &quot;totalRecord&quot;: 1, &quot;previousPage&quot;: 0 } } </code></pre> <p>Then I derive the interface that is shown below.</p> <p>Interface:</p> <pre><code>export interface PageItem { id: string; firstName: string; lastName: string; employeeStatus: number; employeeDepartment: IEmployeeDepartment; } export interface IEmployeeDepartment { departmentName: string; } export interface IData { pageItems: PageItem[]; pageSize: number; currentPage: number; numberOfPages: number; totalRecord: number; previousPage: number; } export interface IEmployeeList { data: IData; successful: boolean; message: string; statusCode: number; } </code></pre> <p>Kindly note that the Id are string (GUID from the backend)</p> <p>Then I have this component.</p> <p>employee.component.ts:</p> <pre><code>import { Component, ViewChild, ElementRef, TemplateRef, OnInit } from '@angular/core'; import { ToastrService } from 'ngx-toastr'; import { EmployeeService } from 'src/app/features/admin/services/employee.service'; import { IData, PageItem, IEmployeeList } from 'src/app/features/admin/models/employee/employee-list'; declare var $:any; @Component({ selector: 'app-employees', templateUrl: './employees.component.html', styleUrls: ['./employees.component.scss'] }) export class EmployeesComponent implements OnInit { allEmployeeList: any[] = []; employeeData: PageItem[] = this.allEmployeeList; selectedFirstName: string = ''; selectedDepartment: string = ''; constructor( private employeeService: EmployeeService, private toastr: ToastrService, ) { } ngOnInit(): void { this.loadAllEmployees(); this.loadAllDepartments(); } loadAllEmployees() { this.employeeService.getAllEmployees().subscribe({ next: (allEmployeeList = res.data.pageItems; this.employeeData = res.data.pageItems; this.dataBk = res.data.pageItems; }, error: (error) =&gt; { this.toastr.error(error.message); } }) } loadAllDepartments() { this.employeeService.getAllDepartments().subscribe({ next: (allDepartmentList = res.data.pageItems; this.departmentData = res.data.pageItems; }, error: (error) =&gt; { this.toastr.error(error.message); } }) } onEmployeeSearch() { this.allEmployeeList = this.employeeData.filter( (row) =&gt; row.firstName ?.toLowerCase() .includes(this.selectedFirstName?.toLowerCase()) &amp;&amp; (this.selectedStatus !== -1 ? row.employeeDepartment.departmentName?.includes(this.selectedDepartment) ); } </code></pre> <p>employee.component.html:</p> <pre><code>&lt;div class=&quot;card-body&quot;&gt; &lt;div class=&quot;row&quot;&gt; &lt;div class=&quot;col-sm-4 col-xs-6 col-6 &quot;&gt; &lt;div class=&quot;form-group&quot;&gt; &lt;label for=&quot;firstName&quot;&gt;First Name:&lt;/label&gt; &lt;input type=&quot;text&quot; autocomplete=&quot;off&quot; class=&quot;form-control&quot; id=&quot;firstName&quot; [(ngModel)]=&quot;selectedFirstName&quot; (input)=&quot;onEmployeeSearch()&quot; placeholder=&quot;First Name&quot; /&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;col-sm-4 col-xs-6 col-6 &quot;&gt; &lt;div class=&quot;form-group&quot;&gt; &lt;label for=&quot;employeeDepartment&quot;&gt;Employee Department&lt;/label&gt; &lt;ng-container *ngIf=&quot;selectedSearchCriteria == 'employeeDepartment'&quot;&gt; &lt;div class=&quot;col-sm-6 col-xs-6 col-6&quot;&gt; &lt;div class=&quot;form-group&quot;&gt; &lt;label for=&quot;employeeDepartment&quot;&gt;Employee Department:&lt;/label&gt; &lt;ng-select [items]=&quot;employeeDepartments&quot; [selectOnTab]=&quot;true&quot; [searchable]=&quot;true&quot; id=&quot;employeeDepartment&quot; [(ngModel)]=&quot;selectedDepartment&quot; (change)=&quot;onEmployeeSearch()&quot; bindValue=&quot;id&quot; bindLabel=&quot;departmentName&quot; placeholder=&quot;Select Employee Department&quot; [multiple]=&quot;false&quot; [clearable]=&quot;true&quot; formControlName=&quot;departmentId&quot;&gt; &lt;/ng-select&gt; &lt;/div&gt; &lt;/div&gt; &lt;/ng-container&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;table class=&quot;table table-striped table-bordered table-hover&quot;&gt; &lt;tr *ngFor=&quot;let row of allEmployeeList&gt; &lt;td&gt;{{ row?.firstName || 'N/A' }}&lt;/td&gt; &lt;td&gt;{{ row?.lastName || 'N/A' }}&lt;/td&gt; &lt;td&gt;{{ row?.employeeDepartment?.departmentName || 'N/A' }}&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>I am using TextInput(selectedFirstName) and Select Dropdown(selectedDepartment) for the search.</p> <p>When the TextInput input or Dropdown onChange, the application should search through the table and reflect the result.</p> <p>The TextInput is working, but the Select Dropdown on Change does not have any effect on the table.</p> <p>How do I correct this and search the table with the Select Dropdown(selectedDepartment) onChange?</p> <p>Thank you.</p>
[ { "answer_id": 74354128, "author": "Jared Renzullo", "author_id": 20409306, "author_profile": "https://Stackoverflow.com/users/20409306", "pm_score": 2, "selected": false, "text": "execute()" }, { "answer_id": 74381563, "author": "Meilan", "author_id": 8898054, "author_profile": "https://Stackoverflow.com/users/8898054", "pm_score": 0, "selected": false, "text": "@Spy\nprivate ThreadPoolTaskExecutor spyTaskExecutor = new ThreadPoolTaskExecutor();\n\nspyTaskExecutor.setCorePoolSize(1);\nspyTaskExecutor.setWaitForTasksToCompleteOnShutdown(true);\nspyTaskExecutor.initialize();\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9037515/" ]
74,353,845
<p>Right Now I'm trying my first medium leetcode problem for the first time (<strong>Remove Nth Node From End of List</strong>) and I'm pretty confident that the code I have should work with it. But for some reason when I it runs, my while-loop for <code>A.Next</code> gives the error:</p> <pre><code>NoneType' object has no attribute 'next' </code></pre> <pre><code># Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def removeNthFromEnd(self, head: Optional[ListNode], n: int) -&gt; Optional[ListNode]: a = head b = head c = head i = 0 while i &lt; n - 1: c = c.next i += 1 while c.next != None: b = b.next c = c.next while a.next != b: a = a.next a.next = b.next b = None return head </code></pre> <p>It doesn't make sense as to why its not running because I defined my <code>a</code> variable to equal the head which should then also have access to <code>a.next</code> because again, its connected to the head. The <code>while c.next != None:</code> loop works fine without any issues so I don't understand whats causing the issue for my <code>a</code> variable.</p>
[ { "answer_id": 74354128, "author": "Jared Renzullo", "author_id": 20409306, "author_profile": "https://Stackoverflow.com/users/20409306", "pm_score": 2, "selected": false, "text": "execute()" }, { "answer_id": 74381563, "author": "Meilan", "author_id": 8898054, "author_profile": "https://Stackoverflow.com/users/8898054", "pm_score": 0, "selected": false, "text": "@Spy\nprivate ThreadPoolTaskExecutor spyTaskExecutor = new ThreadPoolTaskExecutor();\n\nspyTaskExecutor.setCorePoolSize(1);\nspyTaskExecutor.setWaitForTasksToCompleteOnShutdown(true);\nspyTaskExecutor.initialize();\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8741999/" ]
74,353,866
<p>I want to get out the minimum price for categories 1, 2 and 3 I've used</p> <pre><code> LEAST(MIN(price_reduced),MIN(price)) IFNULL(MIN(price_reduced),MIN(price)) ... WHERE price &lt;&gt; 0 and price_reduced &lt;&gt; 0 </code></pre> <p>Database</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>category</th> <th>price</th> <th>price_reduced</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>1</td> <td>200</td> <td>100</td> </tr> <tr> <td>2</td> <td>1</td> <td>300</td> <td>0</td> </tr> <tr> <td>3</td> <td>1</td> <td>500</td> <td>0</td> </tr> <tr> <td>4</td> <td>2</td> <td>200</td> <td>150</td> </tr> <tr> <td>5</td> <td>2</td> <td>125</td> <td>0</td> </tr> <tr> <td>6</td> <td>3</td> <td>300</td> <td>0</td> </tr> <tr> <td>7</td> <td>3</td> <td>200</td> <td>90</td> </tr> </tbody> </table> </div> <p>Output</p> <pre> 1 - 100 2 - 125 3 - 90 </pre> <p>Thank you</p>
[ { "answer_id": 74354604, "author": "FanoFN", "author_id": 10910692, "author_profile": "https://Stackoverflow.com/users/10910692", "pm_score": 0, "selected": false, "text": "cte" }, { "answer_id": 74355492, "author": "Ehab", "author_id": 20342736, "author_profile": "https://Stackoverflow.com/users/20342736", "pm_score": 2, "selected": true, "text": "SELECT Category, \nMIN(IF((price_reduced > 0) AND (price_reduced < price), price_reduced, price)) AS P \nFROM your_table GROUP BY Category;\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5321818/" ]
74,353,898
<h2>Background</h2> <p>There is a list of frequently asked questions and answers in the form of an accordion UI element:</p> <pre class="lang-html prettyprint-override"><code>&lt;h1&gt;Frequently Asked Questions&lt;/h1&gt; &lt;ol class=&quot;accordion&quot;&gt; &lt;li&gt; &lt;h2&gt; &lt;button type=&quot;button&quot; aria-expanded=&quot;false&quot; class=&quot;accordion-trigger&quot; aria-controls=&quot;question-1-answer&quot; id=&quot;question-1&quot;&gt; &lt;span class=&quot;accordion-title&quot;&gt;What is HTML?&lt;/span&gt; &lt;/button&gt; &lt;/h2&gt; &lt;div id=&quot;question-1-answer&quot; role=&quot;region&quot; aria-labelledby=&quot;question-1&quot; class=&quot;accordion-panel&quot; hidden&gt;HyperText Markup Language&lt;/div&gt; &lt;/li&gt; &lt;li&gt; &lt;h2&gt; &lt;button type=&quot;button&quot; aria-expanded=&quot;false&quot; class=&quot;accordion-trigger&quot; aria-controls=&quot;question-2-answer&quot; id=&quot;question-2&quot;&gt; &lt;span class=&quot;accordion-title&quot;&gt;What is CSS?&lt;/span&gt; &lt;/button&gt; &lt;/h2&gt; &lt;div id=&quot;question-2-answer&quot; role=&quot;region&quot; aria-labelledby=&quot;question-1&quot; class=&quot;accordion-panel&quot; hidden&gt;Cascading Style Sheets&lt;/div&gt; &lt;/li&gt; &lt;!-- list divider start --&gt; &lt;div class=&quot;accordion-divider&quot; role=&quot;region&quot; aria-labelledby=&quot;divider-heading&quot;&gt; &lt;h2 id=&quot;divider-heading&quot;&gt;Contact us to find out more&lt;/h2&gt; &lt;/div&gt; &lt;!-- list divider end --&gt; &lt;li&gt; &lt;h2&gt; &lt;button type=&quot;button&quot; aria-expanded=&quot;false&quot; class=&quot;accordion-trigger&quot; aria-controls=&quot;question-3-answer&quot; id=&quot;question-3&quot;&gt; &lt;span class=&quot;accordion-title&quot;&gt;What is JS?&lt;/span&gt; &lt;/button&gt; &lt;/h2&gt; &lt;div id=&quot;question-3-answer&quot; role=&quot;region&quot; aria-labelledby=&quot;question-3&quot; class=&quot;accordion-panel&quot; hidden&gt;JavaScript&lt;/div&gt; &lt;/li&gt; &lt;/ol&gt; </code></pre> <p>Between elements 2 and 3, there is a divider block which contains <strong>interactive content</strong> not relative to the list context (one could imagine an advertisement between the list elements with a call-to-action button).</p> <h2>Problems</h2> <ol> <li>Screen reader (tested on macOS's VoiceOver) announces the list as containing 4 items when there should be 3 items and a divider block.</li> <li>Screen reader should announce the divider block as independent content from the list.</li> </ol> <h2>Questions</h2> <ul> <li>How to accessibly describe that divider block so that the screen reader announces it correctly?</li> <li>Maybe there is a better way to semantically and accessibly describe an ordered accordion list with a divider block?</li> </ul> <h2>What I have tried already?</h2> <p>I have tried several WAI-ARIA roles on the divider block (such as <code>region</code> and <code>separator</code>), but the screen reader always announces the divider block as a part of the list.</p>
[ { "answer_id": 74355717, "author": "slugolicious", "author_id": 76714, "author_profile": "https://Stackoverflow.com/users/76714", "pm_score": 1, "selected": false, "text": "<ol>" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16053949/" ]
74,353,904
<p><a href="https://i.stack.imgur.com/LyynK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LyynK.png" alt="enter image description here" /></a></p> <p>I have this if statement in the cshtml of a page. For some reason or another it keeps giving me that the User.Identity.IsAuthenticated is dereference of possible null reference and when the program starts it doesn't consider the statement.How can it be fixed?</p> <p><a href="https://i.stack.imgur.com/XlbnB.png" rel="nofollow noreferrer">this is after implementing your solution</a></p> <p>Addition: the error occurs on post</p>
[ { "answer_id": 74354139, "author": "Dimitris Maragkos", "author_id": 10839134, "author_profile": "https://Stackoverflow.com/users/10839134", "pm_score": 0, "selected": false, "text": "@if (User.Identity?.IsAuthenticated == true)\n{\n}\n" }, { "answer_id": 74355049, "author": "Chen", "author_id": 18789859, "author_profile": "https://Stackoverflow.com/users/18789859", "pm_score": -1, "selected": false, "text": "Dereference of possible null reference" }, { "answer_id": 74366795, "author": "Stoyan", "author_id": 18665526, "author_profile": "https://Stackoverflow.com/users/18665526", "pm_score": -1, "selected": true, "text": "public void onGet()\n{\n//code\n}\npublic void onPost()\n{\n\n//code \n\nonGet();\n\nreturn Page();\n\n}\n" }, { "answer_id": 74574838, "author": "Ricardo Maroquio", "author_id": 2100509, "author_profile": "https://Stackoverflow.com/users/2100509", "pm_score": -1, "selected": false, "text": "@if (User.Identity!.IsAuthenticated)\n{ ... }\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18665526/" ]
74,353,909
<p>I would like to make a bar plot, where each bar is represented by one of the three columns in this data frame. The 'size' of each bar depends on the sum created by adorn_totals.</p> <p>Reproducible example:</p> <pre><code>library(janitor) test_df &lt;- data.frame( a = c(1:5), b = c(1:5), c = c(1:5) ) %&gt;% adorn_totals(where = 'row', tabyl = c(a, b, c)) </code></pre> <p>I tried a solution that has previously been posted, but that didn't work: Link to the post: <a href="https://stackoverflow.com/questions/67158295/bar-plot-for-each-column-in-a-data-frame-in-r">Bar plot for each column in a data frame in R</a></p> <pre><code>library(janitor) library(ggplot2) df &lt;- data.frame( a = c(1:5), b = c(1:5), c = c(1:5) ) %&gt;% adorn_totals(where = 'row', tabyl = c(a, b, c)) lapply(names(df), function(col) { ggplot(df, aes(.data[[col]], ..count..)) + geom_bar(aes(fill = .data[[col]]), position = &quot;dodge&quot;) }) -&gt; list_plots </code></pre>
[ { "answer_id": 74353991, "author": "Ric Villalba", "author_id": 6912817, "author_profile": "https://Stackoverflow.com/users/6912817", "pm_score": 3, "selected": true, "text": "library(janitor)\nlibrary(ggplot2)\n\ntest_df <- data.frame(\n a = c(1:5),\n b = c(1:5),\n c = c(1:5)\n ) %>% \n adorn_totals(where = 'row', tabyl = c(a, b, c))\n\ntail(test_df,1) %>% stack() %>% \n ggplot(aes(ind, values)) + geom_col()\n" }, { "answer_id": 74354002, "author": "Allan Cameron", "author_id": 12500315, "author_profile": "https://Stackoverflow.com/users/12500315", "pm_score": 1, "selected": false, "text": "slice" }, { "answer_id": 74355053, "author": "M.Viking", "author_id": 10276092, "author_profile": "https://Stackoverflow.com/users/10276092", "pm_score": 0, "selected": false, "text": "pivot_longer" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20364879/" ]
74,353,913
<p>I originally created a diagonal slider using the viewport width and height to determine where each box/image needed to be both on the x and y axis. However, when I started implementing animations the performance started to suffer. This is due to the window size being a dependency of a useEffect.</p> <p>I am curious to know if there may be a better approach to spacing out the items diagonally that doesn't cause a re-render when the browser window resizes. Would grid or possibly flexbox be a better route or possibly something else. I've linked my sandbox below.</p> <p>Sandbox: <a href="https://codesandbox.io/s/relaxed-butterfly-zot2xe?file=/components/Images.js" rel="nofollow noreferrer">https://codesandbox.io/s/relaxed-butterfly-zot2xe?file=/components/Images.js</a></p> <p>Animated Sandbox: <a href="https://codesandbox.io/s/mystifying-spence-m52t2p?file=/components/Images.js" rel="nofollow noreferrer">https://codesandbox.io/s/mystifying-spence-m52t2p?file=/components/Images.js</a></p>
[ { "answer_id": 74353991, "author": "Ric Villalba", "author_id": 6912817, "author_profile": "https://Stackoverflow.com/users/6912817", "pm_score": 3, "selected": true, "text": "library(janitor)\nlibrary(ggplot2)\n\ntest_df <- data.frame(\n a = c(1:5),\n b = c(1:5),\n c = c(1:5)\n ) %>% \n adorn_totals(where = 'row', tabyl = c(a, b, c))\n\ntail(test_df,1) %>% stack() %>% \n ggplot(aes(ind, values)) + geom_col()\n" }, { "answer_id": 74354002, "author": "Allan Cameron", "author_id": 12500315, "author_profile": "https://Stackoverflow.com/users/12500315", "pm_score": 1, "selected": false, "text": "slice" }, { "answer_id": 74355053, "author": "M.Viking", "author_id": 10276092, "author_profile": "https://Stackoverflow.com/users/10276092", "pm_score": 0, "selected": false, "text": "pivot_longer" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74353913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7065024/" ]