qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,508,124
<p>I'm trying to port some C++ code to Rust but I'm having some difficulties.</p> <p>Is there any way of accessing the <strong>widget</strong> field of <strong>Drawables</strong> in the following example?</p> <pre><code>struct Widget { x: u32, y: u32, } trait Drawable { fn draw(&amp;self); fn update(&amp;mut self); } struct Square { widget: Widget, child: Option&lt;Box&lt;dyn Drawable&gt;&gt;, } impl Drawable for Square { fn draw(&amp;self) { // Draw Square } fn update(&amp;mut self) { // Update Square // Access child's widget property if let Some(child) = &amp;mut self.child { child.widget.x = 10; // Error } } } </code></pre> <p>What I have come up with so far is adding a helper function in the Drawable trait to set the size but can't come up with a way of doing it in a way that I won't have to write it for every Drawable implementation.</p> <pre><code>trait Drawable { fn draw(&amp;self); fn update(&amp;mut self); fn set_size(&amp;mut self, x: u32, y: u32) { // Somehow set the size of the widget here instead of implementing it in every struct } } </code></pre>
[ { "answer_id": 74508436, "author": "Iustin Alex", "author_id": 7236418, "author_profile": "https://Stackoverflow.com/users/7236418", "pm_score": 0, "selected": false, "text": "struct Widget {\n x: u32,\n y: u32,\n}\n\ntrait Drawable {\n fn draw(&self);\n fn update(&mut self);\n fn get_widget(&mut self) -> &mut Widget;\n fn set_size(&mut self, x: u32, y: u32) {\n Drawable::get_widget(self).x = x;\n Drawable::get_widget(self).y = y;\n }\n}\n\nstruct Square {\n widget: Widget,\n child: Option<Box<dyn Drawable>>,\n}\n\nimpl Drawable for Square {\n fn draw(&self) {\n // Draw Square\n }\n fn update(&mut self) {\n // Update Square\n // Access child's widget property\n if let Some(child) = &mut self.child {\n child.get_widget().x = 10;\n // or\n child.set_size(10, 10);\n }\n }\n fn get_widget(&mut self) -> &mut Widget {\n return &mut self.widget;\n }\n}\n" }, { "answer_id": 74508672, "author": "cafce25", "author_id": 442760, "author_profile": "https://Stackoverflow.com/users/442760", "pm_score": 2, "selected": true, "text": "AsRef<Widget> AsMut<Widget> Widget struct Widget {\n x: u32,\n y: u32,\n}\n\nimpl AsMut<Widget> for Square {\n fn as_mut(&mut self) -> &mut Widget {\n &mut self.widget\n }\n}\n\ntrait Drawable: AsMut<Widget> {\n fn draw(&self);\n fn update(&mut self);\n fn set_size(&mut self, x: u32, y: u32) {\n self.as_mut().x = x;\n self.as_mut().y = y;\n }\n}\n\nstruct Square {\n widget: Widget,\n child: Option<Box<dyn Drawable>>,\n}\n\nimpl Drawable for Square {\n fn draw(&self) {\n // Draw Square\n }\n fn update(&mut self) {\n // Update Square\n // Access child's widget property\n if let Some(child) = &mut self.child {\n child.as_mut().x = 10;\n // or\n child.set_size(10, 10);\n }\n }\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74508124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7236418/" ]
74,508,126
<p>I would appreciate with anyone can help me to direct myself to a best or simplest approach.</p> <p>I have a requirement to do a communication between my app and a partner with JWT token</p> <p>The steps are the following:</p> <ol> <li>The user is already authenticated in MyApp using another user credentials solution</li> <li>MyApp should generate a JWT token with some user information like subscription id</li> <li>MyApp redirects to the partner url with the JWT token</li> <li>Partner uses the public key (that must be exposed in a JWKS endpoint) to validate that the jwt token was issued by my app.</li> </ol> <p><strong>My Main doubts are the following:</strong></p> <p>a. Do I need use spring oauth2 authorization server or can I use just some spring security components to generate the token and expose the jwks endpoint? b. If I use spring oauth2 authorization server, how can I customize /oauth2/token to receive user information to generate the token? c. If I use spring oauth2 authorization server, how can I rootate my public key? d. If I use only spring security components, can you share some tutorial to generates the JWT? e. If I use only spring security components, would it be simple to generate jwks informatino in the endpoint?</p> <p><strong>Regarding the item a)</strong></p> <p>It would not be necessary an authorization server like a client credentials flow, my app could generate the JWT token by it owns, I'm using the spring authorization server only for the benefits to have all the structure to generate the tokens. Is it really necessary or the best approach to take advantage of spring boot structure or would be simplest to use some spring security components to generate the token?</p> <p><strong>Regarding the item b)</strong></p> <p>If the best decision it to use the Spring Oauth2 Authorization Server, my idea was to use /oauth2/token with client credentials, but the problem is how can I generate a JWT token with some user specific information if I don't have the user information in POST /oauth2/token request? Is it possible to customize the authorization server request to receive the information I need in the body or header? I searched in google and seems that is possible. I just want to confirm that it is ok to do that.</p> <p><strong>Regarding the item c)</strong></p> <p>Is it possible to rotate the public key without downtime in the spring oauth2 authorization server?</p> <p>Would be the process just generate a new jks, change it in the path the server points to and call like a POST /refresh in the authorization server?</p>
[ { "answer_id": 74526711, "author": "Papf", "author_id": 12395944, "author_profile": "https://Stackoverflow.com/users/12395944", "pm_score": 1, "selected": false, "text": "@Bean\npublic OAuth2TokenCustomizer<JwtEncodingContext> jwtEncodingContextOAuth2TokenCustomizer(UserRepository userRepository){\n return (context -> {\n Authentication authentication = context.getPrincipal();\n if (authentication.getPrincipal() instanceof String) {\n OAuth2AuthorizationGrantAuthenticationToken tok = (OAuth2AuthorizationGrantAuthenticationToken) context.getAuthorizationGrant();\n context.getClaims().claim(\"custom_clain\", tok.getAdditionalParameters().get(\"custom_value\"));\n }\n });\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74508126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12395944/" ]
74,508,131
<p>I am trying to figure out a way for a shell script to know when some input has been redirected in order to run a python script with different command line args. My shell script is called <code>P2</code> and the possible invocations need to be (unfortunately no flexibility on this):</p> <pre><code>1. P2 2. P2 &lt; someFile 3. P2 someFile </code></pre> <p>and ideally, the shell script pseudocode would work like this:</p> <pre><code>if argCount == 2: run (python P2.py someFile) else: if inputWasRedirected: **********_issue is here_********** run (python P2.py &lt; someFile) else: run (python P2.py) </code></pre> <p>Any and all help would be appreciated.</p>
[ { "answer_id": 74526711, "author": "Papf", "author_id": 12395944, "author_profile": "https://Stackoverflow.com/users/12395944", "pm_score": 1, "selected": false, "text": "@Bean\npublic OAuth2TokenCustomizer<JwtEncodingContext> jwtEncodingContextOAuth2TokenCustomizer(UserRepository userRepository){\n return (context -> {\n Authentication authentication = context.getPrincipal();\n if (authentication.getPrincipal() instanceof String) {\n OAuth2AuthorizationGrantAuthenticationToken tok = (OAuth2AuthorizationGrantAuthenticationToken) context.getAuthorizationGrant();\n context.getClaims().claim(\"custom_clain\", tok.getAdditionalParameters().get(\"custom_value\"));\n }\n });\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74508131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12223536/" ]
74,508,150
<p>my Request in TYPO3 10.4 with the tx_seo is for only two Lang: de-CH and en-US like this:</p> <pre><code>&lt;link rel=&quot;alternate&quot; hreflang=&quot;de-CH&quot; href=&quot;https://www.example.org/produkte/test-schiene&quot;/&gt; &lt;link rel=&quot;alternate&quot; hreflang=&quot;de-DE&quot; href=&quot;https://www.example.org/produkte/test-schiene&quot;/&gt; &lt;link rel=&quot;alternate&quot; hreflang=&quot;de-AT&quot; href=&quot;https://www.example.org/produkte/test-schiene&quot;/&gt; &lt;link rel=&quot;alternate&quot; hreflang=&quot;en-US&quot; href=&quot;https://www.example.org/en/products/test-rail&quot;/&gt; &lt;link rel=&quot;alternate&quot; hreflang=&quot;x-default&quot; href=&quot;https://www.example.org/en/products/test-rail&quot;/&gt; </code></pre> <p>I have in the Backend only the 2 Language: de-CH = 0 / en-US = 1 My first thought was, the site config.yaml like this (de-DE or de-AT take the lang-id: 0 from de-CH):</p> <pre><code>languages: - title: 'Deutsch (CH)' enabled: true base: / typo3Language: de locale: de_CH.utf8 iso-639-1: de websiteTitle: 'test' navigationTitle: DE hreflang: de-CH direction: '' flag: ch languageId: 0 - title: 'Deutsch (DE)' enabled: true base: / typo3Language: de locale: de_DE.utf8 iso-639-1: de websiteTitle: 'test' navigationTitle: DE hreflang: de-DE direction: '' flag: de languageId: 0 - title: Englisch enabled: true base: /en/ typo3Language: default locale: en_US.utf8 iso-639-1: en websiteTitle: 'test' navigationTitle: EN hreflang: en-US direction: '' flag: en-us-gb languageId: 1 fallbackType: strict fallbacks: '' </code></pre> <p>But it dont work, the HTML Output is this:</p> <pre><code>&lt;link rel=&quot;alternate&quot; hreflang=&quot;de-DE&quot; href=&quot;https://www.example.org/produkte/test-schiene&quot;/&gt; &lt;link rel=&quot;alternate&quot; hreflang=&quot;en-US&quot; href=&quot;https://www.example.org/en/products/test-rail&quot;/&gt; &lt;link rel=&quot;alternate&quot; hreflang=&quot;x-default&quot; href=&quot;https://www.example.org/produkte/test-schiene&quot;/&gt; </code></pre> <p>There overright the de-CH Language with the de-DE config.</p>
[ { "answer_id": 74526711, "author": "Papf", "author_id": 12395944, "author_profile": "https://Stackoverflow.com/users/12395944", "pm_score": 1, "selected": false, "text": "@Bean\npublic OAuth2TokenCustomizer<JwtEncodingContext> jwtEncodingContextOAuth2TokenCustomizer(UserRepository userRepository){\n return (context -> {\n Authentication authentication = context.getPrincipal();\n if (authentication.getPrincipal() instanceof String) {\n OAuth2AuthorizationGrantAuthenticationToken tok = (OAuth2AuthorizationGrantAuthenticationToken) context.getAuthorizationGrant();\n context.getClaims().claim(\"custom_clain\", tok.getAdditionalParameters().get(\"custom_value\"));\n }\n });\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74508150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3923134/" ]
74,508,236
<p>I wrote a simple solidity programme:-</p> <pre><code>//SPDX-License-Identifier: MIT pragma solidity 0.8.16 ; contract arr { uint256[] public n ; uint256 x = 0 ; function pl(uint256 a ) public { n[x] = a ; x++ ; } } </code></pre> <p>It is showing below error</p> <p><a href="https://i.stack.imgur.com/MTgQz.png" rel="nofollow noreferrer">Error showing image while calling function</a></p> <p>It reads that</p> <blockquote> <p>The transaction has been reverted to the initial state. Note: The called function should be payable if you send value and the value you send should be less than your current balance. Debug the transaction to get more information.</p> </blockquote> <p>I am new to solidity. Can anyone please explain it to me that why = opearator is not working with arrays. I read that Solidity is similar to Javascript &amp; in Jsp it is working fine ?</p>
[ { "answer_id": 74508766, "author": "Petr Hejda", "author_id": 1693192, "author_profile": "https://Stackoverflow.com/users/1693192", "pm_score": 1, "selected": false, "text": ".push() function pl(uint256 a) public {\n n.push(a);\n}\n" }, { "answer_id": 74523901, "author": "Asir Shahriar Roudra", "author_id": 13191278, "author_profile": "https://Stackoverflow.com/users/13191278", "pm_score": 0, "selected": false, "text": "//SPDX-License-Identifier: MIT\npragma solidity 0.8.16 ;\n contract arr\n { uint256[4] public n ;\n uint256 x = 0 ;\n\n function pl(uint256 a ) public\n {\n n[x] = a ;\n x++ ;\n }\n }\n //SPDX-License-Identifier: MIT\npragma solidity 0.8.16 ;\n contract arr\n { uint256[] public n ;\n uint256 x = 0 ;\n\n function pl(uint256 a ) public\n {\n n.push();\n n[x] = a ;\n x++ ;\n }\n }\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74508236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20291085/" ]
74,508,254
<p>I have my data stored in an Actor. I need to display the data on a view. The only way I have found to do this is to spin up a task to load the data by using an await command on the actor. This doesn't feel right as it is very clunky; it is also giving me an error which I don't understand.</p> <pre><code>Mutable capture of 'inout' parameter 'self' is not allowed in concurrently-executing code </code></pre> <p>This is my code:</p> <pre><code>actor SimpleActor { func getString() -&gt; String { return &quot;some value&quot; } } struct SimpleView: View { var actor: SimpleActor @State var value: String init() { actor = SimpleActor() Task { value = await actor.getString() // error here } } var body: some View { Text(value) .width(100, alignment: .leading) } } </code></pre> <p>What is the best way of doing this?</p>
[ { "answer_id": 74508676, "author": "vadian", "author_id": 5044042, "author_profile": "https://Stackoverflow.com/users/5044042", "pm_score": 2, "selected": true, "text": "@State(Object) Task @StateObject ObservableObject .task value actor SimpleActor : ObservableObject\n{\n func getString() -> String\n {\n return \"some value\"\n }\n\n}\n\nstruct DetailView: View\n{\n @StateObject var actor = SimpleActor()\n @State private var value = \"\"\n \n var body: some View\n {\n Group {\n Text(value)\n }.task {\n value = await actor.getString()\n }\n \n }\n}\n" }, { "answer_id": 74508716, "author": "cora", "author_id": 11287363, "author_profile": "https://Stackoverflow.com/users/11287363", "pm_score": 0, "selected": false, "text": "actor SimpleActor: ObservableObject {\n func getString() -> String {\n return \"some value\"\n }\n}\n\nstruct SimpleView: View {\n @StateObject var actor = SimpleActor()\n @State var value: String = \"\"\n \n var body: some View {\n Text(value)\n .frame(width: 100, alignment: .leading)\n .task {\n value = await actor.getString()\n }\n }\n}\n .task .onAppear" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74508254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/490966/" ]
74,508,338
<p>I have the following data in a sheet.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>event_id</th> <th>event_type</th> <th>event_name</th> <th>date_col</th> </tr> </thead> <tbody> <tr> <td>123</td> <td>critical_event</td> <td>Event A</td> <td>2021/12/16</td> </tr> <tr> <td>456</td> <td>critical_event</td> <td>Event B</td> <td>2021/12/25</td> </tr> <tr> <td>999</td> <td>medium_event</td> <td>Event C</td> <td>2021/12/13</td> </tr> <tr> <td>888</td> <td>medium_event</td> <td>Event D</td> <td>2021/12/16</td> </tr> </tbody> </table> </div> <p>I'm using the following query in another tab which would give me the latest event for each event_type (by using max(date_col)).</p> <pre><code>=QUERY(data!A:C, &quot;select B, max(D) group by B&quot;) </code></pre> <p>However the query only returns the data for 2 columns.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>event_type</th> <th>max date_col</th> </tr> </thead> <tbody> <tr> <td>critical_event</td> <td>2021/12/25</td> </tr> <tr> <td>medium_event</td> <td>2021/12/16</td> </tr> </tbody> </table> </div> <p>while what I want is to include the event_id and event_name columns as well. (Selecting that row which has the max date) Like below:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>event_id</th> <th>event_type</th> <th>event_name</th> <th>max date_col</th> </tr> </thead> <tbody> <tr> <td>456</td> <td>critical_event</td> <td>Event B</td> <td>2021/12/25</td> </tr> <tr> <td>888</td> <td>medium_event</td> <td>Event D</td> <td>2021/12/16</td> </tr> </tbody> </table> </div> <p>If I select the event_id column in the query, the query breaks.</p>
[ { "answer_id": 74508365, "author": "player0", "author_id": 5632629, "author_profile": "https://Stackoverflow.com/users/5632629", "pm_score": 2, "selected": true, "text": "=QUERY(data!A:C, \"select A,B,max(C) group by A,B\")\n =SORTN(SORT(A1:C, 3, 0), 9^9, 2, 2, 1)\n" }, { "answer_id": 74509043, "author": "ztiaa", "author_id": 17887301, "author_profile": "https://Stackoverflow.com/users/17887301", "pm_score": 0, "selected": false, "text": "date_col ={A1:C1;FILTER(A2:C5,C2:C5=MAX(C2:C5))}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74508338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7283123/" ]
74,508,350
<p>I would like to depict a graph that is the power of some values in a continuous way.</p> <pre><code>f &lt;- function(x) { return (x^(1/3)) } ggplot(data.frame(x=seq(-5,5,length.out=10)), aes(x)) + stat_function(fun=f) </code></pre> <p>This only shows the values that are <code>x &gt; 0</code>, though if I use online graph tool desmos it shows values of <code>x &lt; 0</code> too. In interactive sessions, <code>-3^(1/3)</code> returns <code>-1.44225</code>.</p> <p>Why does R omit it and how can I depict the negative x values too?</p> <p><a href="https://i.stack.imgur.com/aeiSS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aeiSS.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74508365, "author": "player0", "author_id": 5632629, "author_profile": "https://Stackoverflow.com/users/5632629", "pm_score": 2, "selected": true, "text": "=QUERY(data!A:C, \"select A,B,max(C) group by A,B\")\n =SORTN(SORT(A1:C, 3, 0), 9^9, 2, 2, 1)\n" }, { "answer_id": 74509043, "author": "ztiaa", "author_id": 17887301, "author_profile": "https://Stackoverflow.com/users/17887301", "pm_score": 0, "selected": false, "text": "date_col ={A1:C1;FILTER(A2:C5,C2:C5=MAX(C2:C5))}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74508350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2360798/" ]
74,508,389
<pre><code>ItemList = [ {'name': 'item', 'item_code': '473', 'price': 0}, {'name': 'item', 'item_code': '510', 'price': 0}, {'name': 'item', 'item_code': '384', 'price': 0}, ] data_1 = '510' data_2 = 200 def update_item(data_1, data_2): for a in ItemList: if a['item_code'] == data_1: update_price = append(a['price'].data_2) return True </code></pre> <p>I want to update the price by using the function update_item. It fails at update_price = append(a['price'].data_2)</p>
[ { "answer_id": 74508365, "author": "player0", "author_id": 5632629, "author_profile": "https://Stackoverflow.com/users/5632629", "pm_score": 2, "selected": true, "text": "=QUERY(data!A:C, \"select A,B,max(C) group by A,B\")\n =SORTN(SORT(A1:C, 3, 0), 9^9, 2, 2, 1)\n" }, { "answer_id": 74509043, "author": "ztiaa", "author_id": 17887301, "author_profile": "https://Stackoverflow.com/users/17887301", "pm_score": 0, "selected": false, "text": "date_col ={A1:C1;FILTER(A2:C5,C2:C5=MAX(C2:C5))}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74508389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19222846/" ]
74,508,402
<p>In Monoid and Semigroup instances of Alternative Alt used.</p> <p>Why we can't write instance without it?</p> <pre><code>{-# LANGUAGE FlexibleInstances #-} instance Alternative f =&gt; Semigroup (f a) where (&lt;&gt;) = &lt;|&gt; instance Alternative f =&gt; Monoid (f a) where mempty = empty </code></pre> <p>And if we can write that, can we then replace Alternative with (Monoid (f a), Applicative f) in functions?</p>
[ { "answer_id": 74508457, "author": "Willem Van Onsem", "author_id": 67579, "author_profile": "https://Stackoverflow.com/users/67579", "pm_score": 2, "selected": false, "text": "(<|>) :: Alternative f => f a -> f a -> f a empty :: Alternative f => f a Applicative f => f a f a mempty :: f a mempty = empty f Alternative Semigroup Monoid Alternative Alternative" }, { "answer_id": 74508467, "author": "Iceland_jack", "author_id": 165806, "author_profile": "https://Stackoverflow.com/users/165806", "pm_score": 4, "selected": true, "text": "Monoid Alternative {-# Language DerivingVia #-}\n\ndata F a = ..\n deriving (Semigroup, Monoid)\n via Alt F a\n\ninstance Functor F where ..\ninstance Applicative F where ..\ninstance Alternative F where ..\n Alt Monoid f a Applicative Ap {-# Language DerivingVia #-}\n\ndata G a = ..\n deriving (Semigroup, Monoid, Num, Bounded)\n via Ap G a\n\ninstance Functor G where ..\ninstance Applicative G where ..\n Monoid Alternative a Semigroup a => Semigroup (Maybe a) Semigroup Alternative Maybe QuantifiedConstraints forall x. Monoid (f x) Alternative {-# Language QuantifiedConstraints #-}\n..\n\ntype Alternative' :: (Type -> Type) -> Constraint\n\nclass (forall x. Monoid (f x)) => Alternative' f\ninstance (forall x. Monoid (f x)) => Alternative' f\n" }, { "answer_id": 74509149, "author": "leftaroundabout", "author_id": 745903, "author_profile": "https://Stackoverflow.com/users/745903", "pm_score": 1, "selected": false, "text": "f a newtype ResultsSum a = ResultsSum {funToSum :: a -> Int}\n\ninstance Semigroup (ResultsSum a) where\n ResultsSum p <> ResultsSum q = ResultsSum $ \\x -> p x + q x\n ResultsSum a f a Alternative Contravariant ResultsSum {-# OVERLAPPING #-} via Alternative Monoid Alternative" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74508402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16787157/" ]
74,508,408
<p>Please I have a table structured this way.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">Number</th> <th style="text-align: center;">Parent</th> </tr> </thead> <tbody> <tr> <td style="text-align: center;">1</td> <td style="text-align: center;">NULL</td> </tr> <tr> <td style="text-align: center;">2</td> <td style="text-align: center;">1</td> </tr> <tr> <td style="text-align: center;">3</td> <td style="text-align: center;">2</td> </tr> </tbody> </table> </div> <p>I want to carry out a SQL Query that goes through the rows and for each row outputs one of two values for the case:</p> <ol> <li>If the Number is a parent of another number, the case will output &quot;Parent&quot; Label for that row. e.g number 1 and 2</li> <li>If the Number is not a parent i.e a leaf, the case statement will output &quot;Not Parent&quot; for that row. e.g Number 3. Please, how can I do this? I really am stumped about how to structure the case statement. New to SQL. Thanks</li> </ol>
[ { "answer_id": 74508737, "author": "JHH", "author_id": 20127235, "author_profile": "https://Stackoverflow.com/users/20127235", "pm_score": 1, "selected": false, "text": "parent parent leaf parent select n.number,\n case \n when p.parent is not null then ‘parent’\n else ‘leaf’\n end as number_type\n from mytable n\n left \n join mytable p\n on n.number = p.parent;\n\n" }, { "answer_id": 74508738, "author": "Luuk", "author_id": 724039, "author_profile": "https://Stackoverflow.com/users/724039", "pm_score": 0, "selected": false, "text": "WITH recursive cte AS (\n SELECT \n Number, \n Parent \n FROM mytable \n WHERE mytable.Number=3\n \n UNION ALL\n \n SELECT \n mytable.Number, \n mytable.Parent \n FROM cte\n INNER JOIN mytable ON mytable.Number = cte.Parent\n)\nSELECT * FROM cte;\n SELECT ... WHERE mytable.Number=3 SELECT FROM cte INNER JOIN ON ...." }, { "answer_id": 74508879, "author": "Serg", "author_id": 6219979, "author_profile": "https://Stackoverflow.com/users/6219979", "pm_score": 2, "selected": false, "text": "SELECT \n Number, \n case when exists (\n select 1 \n from mytable t2 \n where t2.Parent=t1.Number) \n then 'Parent' else 'Leaf' end nmbrType\nFROM mytable t1\nORDER BY Number\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74508408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/691447/" ]
74,508,410
<p>I've been struggling to implement a logger function in C that records when messages are written to a text file using communication via a pipe. In the simplified implementation below I'm trying to write messages from the parent process and print them from the child process without the file I/O but I don't ever get the child printfs.</p> <p>In my <code>main</code> function, I spawn the logger by calling <code>spawn_logger</code> which forks a child process (<code>log_message</code>) that will run continuously. The parent process returns to the main, starts to send messages through the pipe, and finally kills the child process.</p> <p>The <code>main</code> function:</p> <pre><code>int main(void){ spawn_logger(); char wmsg[] = &quot;Greetings&quot;; send_message(wmsg); strcpy(wmsg, &quot;Hello&quot;); send_message(wmsg); kill_child(); return 0; } </code></pre> <p>The <code>spawn_logger</code> function:</p> <pre><code>// global vars pid_t pid; int fd[2]; int spawn_logger() { if (pipe(fd) == -1) { printf(&quot;Pipe failed\n&quot;); return -1; } pid = fork(); if (pid &lt; 0) { // fork error printf(&quot;fork failed&quot;); return -1; } if (pid &gt; 0) { // parent process close(fd[READ_END]); return 0; // return to main } // child process // spawn the receiver process log_message(); // the receiver process will never reach this point return 0; } </code></pre> <p>The <code>send_message</code> function:</p> <pre><code>int send_message(char message[]){ // do something with the message // e.g. write in a file printf(&quot;Message by parent sent: %s \n&quot;, message); // write the message to logger process int n = strlen(message) + 1; write(fd[WRITE_END], &amp;n, sizeof(int)); write(fd[WRITE_END], &amp;message, sizeof(char) * strlen(message)); return 0; } </code></pre> <p>The <code>log_message</code> and <code>kill_child</code> functions:</p> <pre><code>// global vars extern pid_t pid; extern int fd[2]; int log_message(){ //child process // will read from the pipe every time the parent process writes to it close(fd[WRITE_END]); int n; char *message; // read messages until parent process closes the pipe while (read(fd[READ_END], &amp;n, sizeof(int)) &gt; 0) { message = malloc(sizeof(char) * n); read(fd[READ_END], &amp;message, sizeof(char) * n); printf(&quot;Message by logger received: %s \n&quot;, message); } close(fd[READ_END]); exit(0); } int kill_child(){ close(fd[WRITE_END]); kill(pid, SIGKILL); return 0; } </code></pre> <p>When I run the program all I get are the print messages <code>printf(&quot;Message by parent sent: %s \n&quot;, message);</code> and I think the problem comes from <code>log_message</code>.</p> <p>I thought the child process would remain stuck in the while loop trying to read the buffer as long as the parent's write end is open but while debugging the child process in Clion I noticed that once it reaches the first line the program just stops. When I debug the parent process it just goes over all the writing instructions without any <code>broken pipe</code> errors.</p> <p>How can I fix that? Thanks in advance for the help.</p>
[ { "answer_id": 74508465, "author": "Some programmer dude", "author_id": 440558, "author_profile": "https://Stackoverflow.com/users/440558", "pm_score": 2, "selected": false, "text": "n &message message &message & write write(fd[WRITE_END], message, n);\n" }, { "answer_id": 74575886, "author": "curioso", "author_id": 11206079, "author_profile": "https://Stackoverflow.com/users/11206079", "pm_score": 1, "selected": true, "text": "int log_message(){ //child process\n\n close(fd[WRITE_END]);\n char buffer[BUFSIZ];\n char message[BUFSIZ];\n\n FILE * log;\n log = fopen(\"gateway.log\", \"a\");\n\n // read is looping over every byte in the pipe\n // and is a blocking call until there's something to read\n // or the pipe is closed\n while(read( fd[READ_END], buffer, BUFSIZ) > 0 ) {\n int j = 0;\n memset(message, ' ', BUFSIZ); // make sure its empty\n // look for null terminator in buffer\n for(int i= 0; i < BUFSIZ; i++){\n // copy every byte until the null terminator\n message[i-j] = buffer[i];\n if(buffer[i] == '\\0'){\n if(message[0] != '\\0'){\n printf(\"Message by logger received: %s \\n\", message);\n }\n buffer[i] = ' ';\n // reset j such that i - j is 0 for the next char of the buffer\n j = i + 1;\n }\n }\n memset(message, ' ', BUFSIZ); // clear message\n }\n fclose(log); // for now, we'll open and close the log file every time\n close(fd[READ_END]);\n kill(getpid(), SIGSEGV);\n\n return 0;\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74508410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11206079/" ]
74,508,418
<p>I tried to add changes to my code and the build pipeline for Linux stopped working. The ones for Windows and Mac succeed.</p> <p>I reverted all changes, so there are <strong>no changes</strong> except for comments since the last PullRequest which succeeded.</p> <p>Now it fails with the following message: (Short: &quot;<em>You must install or update .NET to run this application.</em>&quot;)</p> <pre><code>Build started 11/20/2022 12:32:08. 1&gt;Project &quot;/home/runner/work/isoxml-dotnet/isoxml-dotnet/isoxml_dotnet.sln&quot; on node 1 (VSTest target(s)). 1&gt;ValidateSolutionConfiguration: Building solution configuration &quot;Debug|Any CPU&quot;. Test run for /home/runner/work/isoxml-dotnet/isoxml-dotnet/{package}/bin/Debug/netcoreapp3.1/{package}.dll (.NETCoreApp,Version=v3.1) Microsoft (R) Test Execution Command Line Tool Version 17.3.1 (x64) Copyright (c) Microsoft Corporation. All rights reserved. Starting test execution, please wait... A total of 1 test files matched the specified pattern. Testhost process for source(s) '/home/runner/work/isoxml-dotnet/isoxml-dotnet/{package}.Test/bin/Debug/netcoreapp3.1/{package}.Test.dll' exited with error: You must install or update .NET to run this application. App: /home/runner/.nuget/packages/microsoft.testplatform.testhost/16.9.4/lib/netcoreapp2.1/testhost.dll Architecture: x64 Framework: 'Microsoft.NETCore.App', version '3.1.0' (x64) .NET location: /usr/share/dotnet/ The following frameworks were found: 6.0.10 at [/usr/share/dotnet/shared/Microsoft.NETCore.App] Learn about framework resolution: https://aka.ms/dotnet/app-launch-failed To install missing framework, download: https://aka.ms/dotnet-core-applaunch?framework=Microsoft.NETCore.App&amp;framework_version=3.1.0&amp;arch=x64&amp;rid=ubuntu.22.04-x64 . Please check the diagnostic logs for more information. Test Run Aborted. 1&gt;Done Building Project &quot;/home/runner/work/isoxml-dotnet/isoxml-dotnet/isoxml_dotnet.sln&quot; (VSTest target(s)) -- FAILED. Build FAILED. 0 Warning(s) 0 Error(s) </code></pre> <p>My Build Pipeline looks like this:</p> <pre><code>name: .NET on: push: branches: [ &quot;main&quot; ] pull_request: branches: [ &quot;main&quot; ] jobs: buildLinux: runs-on: ubuntu-latest strategy: matrix: dotnet-version: ['3.0', '3.1.x', '5.0.x','6.0.x' ] steps: - uses: actions/checkout@v3 - name: Setup .NET uses: actions/setup-dotnet@v2 - name: Restore dependencies run: dotnet restore - name: Build Linux run: dotnet build --no-restore - name: Test run: dotnet test --no-build --verbosity normal buildWindows: runs-on: windows-latest strategy: matrix: dotnet-version: ['3.0', '3.1.x', '5.0.x','6.0.x' ] steps: - uses: actions/checkout@v3 - name: Setup .NET uses: actions/setup-dotnet@v2 - name: Restore dependencies run: dotnet restore - name: Build Windows run: dotnet build --no-restore - name: Test run: dotnet test --no-build --verbosity normal buildMac: runs-on: macos-latest strategy: matrix: dotnet-version: ['3.0', '3.1.x', '5.0.x','6.0.x' ] steps: - uses: actions/checkout@v3 - name: Setup .NET uses: actions/setup-dotnet@v2 - name: Restore dependencies run: dotnet restore - name: Build Mac run: dotnet build --no-restore - name: Test run: dotnet test --no-build --verbosity normal </code></pre> <p>Please recognize that there are no changes in the dotnet.yml</p> <p>What I tried so far:</p> <ul> <li>Revert all changes; everything left is just comments</li> <li>Change version of actions/setup-dotnet to v3, v3.0.2, v2.0.1</li> </ul> <p><strong>Remark on Edit</strong>: I removed the PackageName with {package} as it's not relevant for the solution. Hope that's OK ;)</p>
[ { "answer_id": 74508465, "author": "Some programmer dude", "author_id": 440558, "author_profile": "https://Stackoverflow.com/users/440558", "pm_score": 2, "selected": false, "text": "n &message message &message & write write(fd[WRITE_END], message, n);\n" }, { "answer_id": 74575886, "author": "curioso", "author_id": 11206079, "author_profile": "https://Stackoverflow.com/users/11206079", "pm_score": 1, "selected": true, "text": "int log_message(){ //child process\n\n close(fd[WRITE_END]);\n char buffer[BUFSIZ];\n char message[BUFSIZ];\n\n FILE * log;\n log = fopen(\"gateway.log\", \"a\");\n\n // read is looping over every byte in the pipe\n // and is a blocking call until there's something to read\n // or the pipe is closed\n while(read( fd[READ_END], buffer, BUFSIZ) > 0 ) {\n int j = 0;\n memset(message, ' ', BUFSIZ); // make sure its empty\n // look for null terminator in buffer\n for(int i= 0; i < BUFSIZ; i++){\n // copy every byte until the null terminator\n message[i-j] = buffer[i];\n if(buffer[i] == '\\0'){\n if(message[0] != '\\0'){\n printf(\"Message by logger received: %s \\n\", message);\n }\n buffer[i] = ' ';\n // reset j such that i - j is 0 for the next char of the buffer\n j = i + 1;\n }\n }\n memset(message, ' ', BUFSIZ); // clear message\n }\n fclose(log); // for now, we'll open and close the log file every time\n close(fd[READ_END]);\n kill(getpid(), SIGSEGV);\n\n return 0;\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74508418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6596908/" ]
74,508,433
<p>Assuming the common &quot;Order&quot; aggregate, my view of events is that each should be representative of the command that took place. E.g. <code>OrderCreated</code>, <code>OrderePicked</code>, <code>OrderPacked</code>, <code>OrderShipped</code>.<br /> Applying these events in the <em>aggregate</em> changes the <em>status</em> of the order accordingly.</p> <p>The problem:<br /> I have a <em>projector</em> that lists all orders in the system and their statuses. So it consumes the events, and like with the aggregate &quot;apply&quot; method, it implements the logic that changes the status of the order.<br /> So now the logic exists in two places, which is... not good.</p> <p>A solution to this is to replace all the above events with a single <code>StatusChanged</code> event that contains a property with the new status.<br /> Pros: both aggregate and projectors just need to handle one event type, and set the status to what's in that event. Zero logic.<br /> Cons: the list of events is now very implicit. Instead of getting a list of WHAT HAPPENED (created, packed, shipped, etc.), we now have a list of the status changes events.</p> <p>How do you prefer to approach this?</p> <p>Note: this is not the full list of events. other events contain other properties, so clearly they don't belong to this problem. the problem is with events that don't contain any info, just change the status of an order.</p>
[ { "answer_id": 74508465, "author": "Some programmer dude", "author_id": 440558, "author_profile": "https://Stackoverflow.com/users/440558", "pm_score": 2, "selected": false, "text": "n &message message &message & write write(fd[WRITE_END], message, n);\n" }, { "answer_id": 74575886, "author": "curioso", "author_id": 11206079, "author_profile": "https://Stackoverflow.com/users/11206079", "pm_score": 1, "selected": true, "text": "int log_message(){ //child process\n\n close(fd[WRITE_END]);\n char buffer[BUFSIZ];\n char message[BUFSIZ];\n\n FILE * log;\n log = fopen(\"gateway.log\", \"a\");\n\n // read is looping over every byte in the pipe\n // and is a blocking call until there's something to read\n // or the pipe is closed\n while(read( fd[READ_END], buffer, BUFSIZ) > 0 ) {\n int j = 0;\n memset(message, ' ', BUFSIZ); // make sure its empty\n // look for null terminator in buffer\n for(int i= 0; i < BUFSIZ; i++){\n // copy every byte until the null terminator\n message[i-j] = buffer[i];\n if(buffer[i] == '\\0'){\n if(message[0] != '\\0'){\n printf(\"Message by logger received: %s \\n\", message);\n }\n buffer[i] = ' ';\n // reset j such that i - j is 0 for the next char of the buffer\n j = i + 1;\n }\n }\n memset(message, ' ', BUFSIZ); // clear message\n }\n fclose(log); // for now, we'll open and close the log file every time\n close(fd[READ_END]);\n kill(getpid(), SIGSEGV);\n\n return 0;\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74508433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1102018/" ]
74,508,452
<p>Apparently, template_file was deprecated, and I need to migrate to <code>templatefile</code></p> <p>I have the following YAML that needs to be populated with two variables</p> <pre><code>data &quot;template_file&quot; &quot;user_data&quot; { template = file(&quot;cloud-init.yaml&quot;) vars = { user = var.USER tskey = var.TAILSCALE_AUTHKEY } } </code></pre> <p>Used below</p> <pre><code>user_data = data.template_file.user_data.rendered </code></pre> <p>How to do this in a new way, using templatefile?</p> <p>EDIT: Full source code <a href="https://github.com/skhaz/my-cloud-workspace" rel="nofollow noreferrer">https://github.com/skhaz/my-cloud-workspace</a></p>
[ { "answer_id": 74508465, "author": "Some programmer dude", "author_id": 440558, "author_profile": "https://Stackoverflow.com/users/440558", "pm_score": 2, "selected": false, "text": "n &message message &message & write write(fd[WRITE_END], message, n);\n" }, { "answer_id": 74575886, "author": "curioso", "author_id": 11206079, "author_profile": "https://Stackoverflow.com/users/11206079", "pm_score": 1, "selected": true, "text": "int log_message(){ //child process\n\n close(fd[WRITE_END]);\n char buffer[BUFSIZ];\n char message[BUFSIZ];\n\n FILE * log;\n log = fopen(\"gateway.log\", \"a\");\n\n // read is looping over every byte in the pipe\n // and is a blocking call until there's something to read\n // or the pipe is closed\n while(read( fd[READ_END], buffer, BUFSIZ) > 0 ) {\n int j = 0;\n memset(message, ' ', BUFSIZ); // make sure its empty\n // look for null terminator in buffer\n for(int i= 0; i < BUFSIZ; i++){\n // copy every byte until the null terminator\n message[i-j] = buffer[i];\n if(buffer[i] == '\\0'){\n if(message[0] != '\\0'){\n printf(\"Message by logger received: %s \\n\", message);\n }\n buffer[i] = ' ';\n // reset j such that i - j is 0 for the next char of the buffer\n j = i + 1;\n }\n }\n memset(message, ' ', BUFSIZ); // clear message\n }\n fclose(log); // for now, we'll open and close the log file every time\n close(fd[READ_END]);\n kill(getpid(), SIGSEGV);\n\n return 0;\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74508452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/832490/" ]
74,508,456
<p>I was trying to implement a system where I could output the div which has the highest download count inside that div (is just a number), but I have no particular skills in JavaScript.</p> <p>I've found out one way to grab all of the divs and output them in console, but now I have to count the highest number in the innerText property for each div found:</p> <pre class="lang-js prettyprint-override"><code>const downloads = document.querySelectorAll(&quot;[class^='download_count']&quot;); console.log(downloads); </code></pre> <p>For example I have:</p> <pre class="lang-html prettyprint-override"><code>&lt;div class=&quot;download_count&quot;&gt; 3 &lt;em class=&quot;icon&quot;&gt;&lt;/em&gt; &lt;/div&gt; &lt;div class=&quot;download_count&quot;&gt; 16 &lt;em class=&quot;icon&quot;&gt;&lt;/em&gt; &lt;/div&gt; &lt;!-- The list continues... --&gt; </code></pre> <p>I've tried multiple loops in JavaScript which would've counted the numbers and output the highest number by using an array and Math.max() but couldn't really get it properly working as I've stuttered upon properly making it output only one of the divs with highest number.</p> <p>Expected behavior:</p> <pre class="lang-html prettyprint-override"><code>&lt;div class=&quot;download_count&quot;&gt; 3 &lt;em class=&quot;icon&quot;&gt;&lt;/em&gt; &lt;/div&gt; &lt;div class=&quot;download_count&quot;&gt; 16 &lt;em class=&quot;icon&quot;&gt;&lt;/em&gt; &lt;div class=&quot;most-downloaded&quot;&gt;Most downloaded file on the website!&lt;/div&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 74508465, "author": "Some programmer dude", "author_id": 440558, "author_profile": "https://Stackoverflow.com/users/440558", "pm_score": 2, "selected": false, "text": "n &message message &message & write write(fd[WRITE_END], message, n);\n" }, { "answer_id": 74575886, "author": "curioso", "author_id": 11206079, "author_profile": "https://Stackoverflow.com/users/11206079", "pm_score": 1, "selected": true, "text": "int log_message(){ //child process\n\n close(fd[WRITE_END]);\n char buffer[BUFSIZ];\n char message[BUFSIZ];\n\n FILE * log;\n log = fopen(\"gateway.log\", \"a\");\n\n // read is looping over every byte in the pipe\n // and is a blocking call until there's something to read\n // or the pipe is closed\n while(read( fd[READ_END], buffer, BUFSIZ) > 0 ) {\n int j = 0;\n memset(message, ' ', BUFSIZ); // make sure its empty\n // look for null terminator in buffer\n for(int i= 0; i < BUFSIZ; i++){\n // copy every byte until the null terminator\n message[i-j] = buffer[i];\n if(buffer[i] == '\\0'){\n if(message[0] != '\\0'){\n printf(\"Message by logger received: %s \\n\", message);\n }\n buffer[i] = ' ';\n // reset j such that i - j is 0 for the next char of the buffer\n j = i + 1;\n }\n }\n memset(message, ' ', BUFSIZ); // clear message\n }\n fclose(log); // for now, we'll open and close the log file every time\n close(fd[READ_END]);\n kill(getpid(), SIGSEGV);\n\n return 0;\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74508456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17209126/" ]
74,508,464
<p>Instead of using 3 loops separately, I'd like to use only one loop and speed up the code.</p> <p>There are 3 different patterns of <code>range(0,150)</code>, increasing 3 per loop:</p> <pre><code>0,3,6,9... 1,4,7,10... 2,5,8,11.... </code></pre> <p>My code:</p> <pre><code>fromlist = [1,2,3,4,5] req1list = ['z','t','y'] req2list = [21,39,52] req3list = [100,200,300] for i in range(0,150,3): req1list.append(fromlist[i]) for j in range(1,150,3): req2list.append(fromlist[j]) for x in range(2,151,3): req3list.append(fromlist[x]) </code></pre> <p>Note that lists are already created and there is data inside the file. Thus, I thought that list comprehension would be impossible.</p> <p>Another note: please ignore the list lengths, in my file the lists are far longer and don't cause errors in <code>[]</code>.</p> <p>Is there any way that unites these 3 loops in one, and speed up the code?</p>
[ { "answer_id": 74508594, "author": "trincot", "author_id": 5459839, "author_profile": "https://Stackoverflow.com/users/5459839", "pm_score": 3, "selected": true, "text": "extend append req1list.extend(fromlist[::3])\nreq2list.extend(fromlist[1::3])\nreq3list.extend(fromlist[2::3])\n req1list.extend(fromlist[:150:3])\n# ...etc\n" }, { "answer_id": 74508810, "author": "chepner", "author_id": 1126841, "author_profile": "https://Stackoverflow.com/users/1126841", "pm_score": 0, "selected": false, "text": "grouper itertools def grouper(iterable, n, *, incomplete='fill', fillvalue=None):\n args = [iter(iterable)] * n\n if incomplete == 'fill':\n return zip_longest(*args, fillvalue=fillvalue)\n if incomplete == 'strict':\n return zip(*args, strict=True)\n if incomplete == 'ignore':\n return zip(*args)\n else:\n raise ValueError('Expected fill, strict, or ignore')\n for x, y, z in grouper(fromlist, 3):\n req1list.append(x)\n req2list.append(y)\n req3list.append(z)\n grouper more-itertools" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74508464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20554831/" ]
74,508,480
<pre><code>public String deleteProduct(@RequestBody String prodId ,HttpServletRequest request ) throws NotLoggedInException { String userName = (String) request.getSession().getAttribute(&quot;user&quot;); System.out.println(userName); if (userName == null) { throw new NotLoggedInException(&quot;You have not logged in&quot;); } String userRole = (String) request.getSession().getAttribute(&quot;role&quot;); if (!userRole.equalsIgnoreCase(&quot;productmaster&quot;)) { throw new AuthorizedUserRoleNotFoundException(&quot;you are not authorized to add the products&quot;); } if(pservice.deleteProduct(prodId)) { return &quot;Product deleted&quot;; } return &quot;Product not deleted&quot;; } </code></pre> <p>Output:</p> <pre><code>{ &quot;timestamp&quot;: &quot;2022-11-20T13:17:24.172+0000&quot;, &quot;status&quot;: 400, &quot;error&quot;: &quot;Bad Request&quot;, &quot;message&quot;: &quot;Required request body is missing: public java.lang.String&quot; } </code></pre> <p>Please tell someone why its showing like this</p>
[ { "answer_id": 74508525, "author": "void void", "author_id": 18969611, "author_profile": "https://Stackoverflow.com/users/18969611", "pm_score": 1, "selected": false, "text": "@RequestBody required true required" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74508480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20554825/" ]
74,508,580
<p>Create a scrolling_text function that accepts a string as a parameter, sequentially rearranges all the characters in the string from the zero index to the last one, and returns a list with all the received combinations in upper case.</p> <p>`</p> <pre><code>def scrolling_text(string: str) -&gt; list: pass </code></pre> <p>`</p> <p>Example`</p> <pre><code>scrolling_text(&quot;robot&quot;) returns: [ &quot;ROBOT&quot;, &quot;OBOTR&quot;, &quot;BOTRO&quot;, &quot;OTROB&quot;, &quot;TROBO&quot; ] </code></pre> <p>`</p> <p>I know only I return the list in uppercase</p>
[ { "answer_id": 74508652, "author": "Trenomarcus", "author_id": 13258029, "author_profile": "https://Stackoverflow.com/users/13258029", "pm_score": 0, "selected": false, "text": "def scrolling_text(string: str) -> list:\n out = []\n string = string.upper()\n for i in range(len(string)):\n out.append(string[i:] + string[:i])\n return out\n \nres = scrolling_text(\"ROBOT\")\nprint(res) # ['ROBOT', 'OBOTR', 'BOTRO', 'OTROB', 'TROBO']\n" }, { "answer_id": 74508668, "author": "Cartroo", "author_id": 1955509, "author_profile": "https://Stackoverflow.com/users/1955509", "pm_score": 1, "selected": false, "text": "str def scrolling_text(text: str) -> list[str]:\n ret = []\n for i in range(len(text)):\n ret.append(text[i:] + text[:i])\n return ret\n text[i:] i text[:i] I def scrolling_text(text: str) -> list[str]:\n return [text[i:] + text[:i] for i in range(len(text))]\n from typing import Iterator\n\ndef scrolling_text(text: str) -> Iterator[str]:\n for i in range(len(text)):\n yield text[i:] + text[:i]\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74508580", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19757394/" ]
74,508,581
<p>I wrote HTML and PHP that sends an email using a form, but the code is not working. I am getting an error message on submit, &quot;This page isn’t working <a href="http://www.adurotoluwasupport.org" rel="nofollow noreferrer">www.adurotoluwasupport.org</a> is currently unable to handle this request. HTTP ERROR 500&quot;.</p> <p>I'm not sure what I did wrong.</p> <p><strong>HTML</strong></p> <pre><code>&lt;div style=&quot;padding:20px&quot; class=&quot;col-sm-7&quot;&gt; &lt;h2&gt;Become a Volunteer&lt;/h2&gt; &lt;br&gt; &lt;form id=&quot;fcf-form-id&quot; class=&quot;fcf-form-class&quot; method=&quot;post&quot; action=&quot;volunteer.php&quot;&gt; &lt;div class=&quot;row cont-row&quot;&gt; &lt;div class=&quot;col-sm-3&quot;&gt;&lt;label for=&quot;Position&quot;&gt;Volunteer Position &lt;/label&gt;&lt;span&gt;:&lt;/span&gt;&lt;/div&gt; &lt;div class=&quot;col-sm-8&quot;&gt;&lt;input type=&quot;text&quot; id=&quot;Position&quot; placeholder=&quot;Tell us what you are volunteering for&quot; name=&quot;Position&quot; class=&quot;form-control input-sm&quot; required&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;row cont-row&quot;&gt; &lt;div class=&quot;col-sm-3&quot;&gt;&lt;label for=&quot;Name&quot;&gt;Full Name &lt;/label&gt;&lt;span&gt;:&lt;/span&gt;&lt;/div&gt; &lt;div class=&quot;col-sm-8&quot;&gt;&lt;input type=&quot;text&quot; id=&quot;Name&quot; placeholder=&quot;Enter Name&quot; name=&quot;Name&quot; class=&quot;form-control input-sm&quot; pattern=[A-Z\sa-z]{4,30} required&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;row cont-row&quot;&gt; &lt;div class=&quot;col-sm-3&quot;&gt;&lt;label for=&quot;Email&quot;&gt;Email Address &lt;/label&gt;&lt;span&gt;:&lt;/span&gt;&lt;/div&gt; &lt;div class=&quot;col-sm-8&quot;&gt;&lt;input type=&quot;email&quot; id=&quot;Email&quot; name=&quot;Email&quot; placeholder=&quot;Enter Email Address&quot; class=&quot;form-control input-sm&quot; required&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;row cont-row&quot;&gt; &lt;div class=&quot;col-sm-3&quot;&gt;&lt;label for=&quot;Number&quot;&gt;Mobile Number&lt;/label&gt;&lt;span&gt;:&lt;/span&gt;&lt;/div&gt; &lt;div class=&quot;col-sm-8&quot;&gt;&lt;input type=&quot;tel&quot; id=&quot;Number&quot; name=&quot;Number&quot; placeholder=&quot;Enter Mobile Number&quot; class=&quot;form-control input-sm&quot; required&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;row cont-row&quot;&gt; &lt;div class=&quot;col-sm-3&quot;&gt;&lt;label for=&quot;Address&quot;&gt;Address &lt;/label&gt;&lt;span&gt;:&lt;/span&gt;&lt;/div&gt; &lt;div class=&quot;col-sm-8&quot;&gt;&lt;input type=&quot;text&quot; id=&quot;Address&quot; placeholder=&quot;Your residential address&quot; name=&quot;Address&quot; class=&quot;form-control input-sm&quot; required&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;row cont-row&quot;&gt; &lt;div class=&quot;col-sm-3&quot;&gt;&lt;label for=&quot;State&quot;&gt;Enter State &lt;/label&gt;&lt;span&gt;:&lt;/span&gt;&lt;/div&gt; &lt;div class=&quot;col-sm-8&quot;&gt;&lt;input type=&quot;text&quot; id=&quot;State&quot; name=&quot;State&quot; placeholder=&quot;Your State of Residence&quot; class=&quot;form-control input-sm&quot; required&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;row cont-row&quot;&gt; &lt;div class=&quot;col-sm-3&quot;&gt;&lt;label for=&quot;Country&quot;&gt;Enter Country&lt;/label&gt;&lt;span&gt;:&lt;/span&gt;&lt;/div&gt; &lt;div class=&quot;col-sm-8&quot;&gt;&lt;input type=&quot;text&quot; id=&quot;Country&quot; name=&quot;Country&quot; placeholder=&quot;Your Country of Residence&quot; class=&quot;form-control input-sm&quot; required&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;row cont-row&quot;&gt; &lt;div class=&quot;col-sm-3&quot;&gt;&lt;label for=&quot;Occupation&quot;&gt;Occupation &lt;/label&gt;&lt;span&gt;:&lt;/span&gt;&lt;/div&gt; &lt;div class=&quot;col-sm-8&quot;&gt;&lt;input type=&quot;text&quot; id=&quot;Occupation&quot; placeholder=&quot;Enter Occupation&quot; name=&quot;Occupation&quot; class=&quot;form-control input-sm&quot; required&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;row cont-row&quot;&gt; &lt;div class=&quot;col-sm-3&quot;&gt;&lt;label for=&quot;Experience&quot;&gt;Volunteer Xpernce.&lt;/label&gt;&lt;span&gt;:&lt;/span&gt;&lt;/div&gt; &lt;div class=&quot;col-sm-8&quot;&gt;&lt;input type=&quot;text&quot; id=&quot;Experience&quot; name=&quot;Experience&quot; placeholder=&quot;Your previous volunteer experience / Optional &quot; class=&quot;form-control input-sm&quot;&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;row cont-row&quot;&gt; &lt;div class=&quot;col-sm-3&quot;&gt;&lt;label for=&quot;Languages&quot;&gt;Languages Spoken&lt;/label&gt;&lt;span&gt;:&lt;/span&gt;&lt;/div&gt; &lt;div class=&quot;col-sm-8&quot;&gt;&lt;input type=&quot;text&quot; id=&quot;Languages&quot; name=&quot;Languages&quot; placeholder=&quot;Tell us the language(s) you speak fluently&quot; class=&quot;form-control input-sm&quot; required&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;row cont-row&quot;&gt; &lt;div class=&quot;col-sm-3&quot;&gt;&lt;label for=&quot;Gender&quot;&gt;Gender&lt;/label&gt;&lt;span&gt;:&lt;/span&gt;&lt;/div&gt; &lt;div class=&quot;col-sm-8&quot;&gt;&lt;select id=&quot;Gender&quot; name=&quot;Gender&quot; class=&quot;form-control input-sm&quot; required&gt; &lt;option Value=&quot;&quot;&gt;Select your Gender&lt;/option&gt; &lt;option value=&quot;male&quot;&gt;Male&lt;/option&gt; &lt;option value=&quot;female&quot;&gt;Female&lt;/option&gt; &lt;option value=&quot;Other&quot;&gt;Other&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;row cont-row&quot;&gt; &lt;div class=&quot;col-sm-3&quot;&gt;&lt;label for=&quot;Dob&quot;&gt;Date of Birth&lt;/label&gt;&lt;span&gt;:&lt;/span&gt;&lt;/div&gt; &lt;div class=&quot;col-sm-8&quot;&gt;&lt;input type=&quot;date&quot; id=&quot;Dob&quot; name=&quot;Dob&quot; placeholder=&quot;Enter your Date of Birth&quot; class=&quot;form-control input-sm&quot; required&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;row cont-row&quot;&gt; &lt;div class=&quot;col-sm-3&quot;&gt;&lt;label for=&quot;Info&quot;&gt;Other information&lt;/label&gt;&lt;span&gt;:&lt;/span&gt;&lt;/div&gt; &lt;div class=&quot;col-sm-8&quot;&gt; &lt;textarea rows=&quot;5&quot; id=&quot;Info&quot; placeholder=&quot;Enter other information that enable us make a good match&quot; class=&quot;form-control input-sm&quot;&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;/div&gt; &lt;div style=&quot;margin-top:10px;&quot; class=&quot;row&quot;&gt; &lt;div style=&quot;padding-top:10px;&quot; class=&quot;col-sm-3&quot;&gt;&lt;label&gt;&lt;/label&gt;&lt;/div&gt; &lt;div class=&quot;col-sm-8&quot;&gt; &lt;button type=&quot;submit&quot; id=&quot;fcf-button&quot; class=&quot;btn btn-primary btn-sm&quot;&gt;Submit&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p><strong>PHP</strong></p> <pre><code> &lt;?php if (isset($_POST['Email'])) { // EDIT THE FOLLOWING TWO LINES: $email_to = &quot;example@gmail.com&quot;; $email_subject = &quot;Volunteer form submissions&quot;; function problem($error) { echo &quot;We're sorry, but there were error(s) found with the form you submitted. &quot;; echo &quot;These errors appear below.&lt;br&gt;&lt;br&gt;&quot;; echo $error . &quot;&lt;br&gt;&lt;br&gt;&quot;; echo &quot;Please go back and fix these errors.&lt;br&gt;&lt;br&gt;&quot;; die(); } // validation expected data exists if ( !isset($_POST['Position']) || !isset($_POST['Name']) || !isset($_POST['Email']) || !isset($_POST['Number']) || !isset($_POST['Address']) || !isset($_POST['State']) || !isset($_POST['Country']) || !isset($_POST['Occupation']) || !isset($_POST['Experience']) || !isset($_POST['Languages']) || !isset($_POST['Gender']) || !isset($_POST['Dob']) || !isset($_POST['Info']) ) { problem('We're sorry, but there appears to be a problem with the form you submitted.'); } $position = $_POST['Position']; // required $name = $_POST['Name']; // required $email = $_POST['Email']; // required $number = $_POST['Number']; // required $address = $_POST['Address']; // required $state = $_POST['State']; // required $country = $_POST['Country']; // required $occupation = $_POST['Occupation']; // required $experience = $_POST['Experience']; // $languages = $_POST['Languages']; // required $gender = $_POST['Gender']; // required $dob = $_POST['Dob']; // required $info = $_POST['Info']; // $error_message = &quot;&quot;; $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/'; if (!preg_match($email_exp, $email)) { $error_message .= 'The Email address you entered does not appear to be valid.&lt;br&gt;'; } $string_exp = &quot;/^[A-Za-z .'-]+$/&quot;; if (!preg_match($string_exp, $name)) { $error_message .= 'The Name you entered does not appear to be valid.&lt;br&gt;'; } if (strlen($message) &lt; 2) { $error_message .= 'The Message you entered do not appear to be valid.&lt;br&gt;'; } if (strlen($error_message) &gt; 0) { problem($error_message); } $email_message = &quot;Form details below.\n\n&quot;; function clean_string($string) { $bad = array(&quot;content-type&quot;, &quot;bcc:&quot;, &quot;to:&quot;, &quot;cc:&quot;, &quot;href&quot;); return str_replace($bad, &quot;&quot;, $string); } $email_message .= &quot;Position: &quot; . clean_string($position) . &quot;\n&quot;; $email_message .= &quot;Name: &quot; . clean_string($name) . &quot;\n&quot;; $email_message .= &quot;Email: &quot; . clean_string($email) . &quot;\n&quot;; $email_message .= &quot;Number: &quot; . clean_string($number) . &quot;\n&quot;; $email_message .= &quot;Address: &quot; . clean_string($address) . &quot;\n&quot;; $email_message .= &quot;State: &quot; . clean_string($state) . &quot;\n&quot;; $email_message .= &quot;Country: &quot; . clean_string($country) . &quot;\n&quot;; $email_message .= &quot;Occupation: &quot; . clean_string($occupation) . &quot;\n&quot;; $email_message .= &quot;Experience: &quot; . clean_string($experience) . &quot;\n&quot;; $email_message .= &quot;Languages: &quot; . clean_string($languages) . &quot;\n&quot;; $email_message .= &quot;Gender: &quot; . clean_string($gender) . &quot;\n&quot;; $email_message .= &quot;Dob: &quot; . clean_string($dob) . &quot;\n&quot;; $email_message .= &quot;Info: &quot; . clean_string($info) . &quot;\n&quot;; // create email headers $headers = 'From: ' . $email . &quot;\r\n&quot; . 'Reply-To: ' . $email . &quot;\r\n&quot; . 'X-Mailer: PHP/' . phpversion(); @mail($email_to, $email_subject, $email_message, $headers); ?&gt; &lt;!-- INCLUDE YOUR SUCCESS MESSAGE BELOW --&gt; Thanks for volunteering. We'll get back to you soon. &lt;?php } ?&gt; </code></pre>
[ { "answer_id": 74508639, "author": "Faisal Sharif", "author_id": 4398486, "author_profile": "https://Stackoverflow.com/users/4398486", "pm_score": -1, "selected": false, "text": "<div style=\"padding:20px\" class=\"col-sm-7\">\n <h2>Become a Volunteer</h2>\n <br>\n <form id=\"fcf-form-id\" class=\"fcf-form-class\" method=\"post\" action=\"volunteer.php\">\n <div class=\"row cont-row\">\n <div class=\"col-sm-3\">\n <label for=\"Position\">Volunteer Position </label><span>:</span></div>\n <div class=\"col-sm-8\">\n <input type=\"text\" id=\"Position\" placeholder=\"Tell us what you are volunteering for\" name=\"Position\" class=\"form-control input-sm\" required>\n </div>\n </div>\n <div class=\"row cont-row\">\n <div class=\"col-sm-3\">\n <label for=\"Name\">Full Name </label><span>:</span></div>\n <div class=\"col-sm-8\">\n <input type=\"text\" id=\"Name\" placeholder=\"Enter Name\" name=\"Name\" class=\"form-control input-sm\" pattern=[A-Z\\sa-z]{4,30} required>\n </div>\n </div>\n <div class=\"row cont-row\">\n <div class=\"col-sm-3\">\n <label for=\"Email\">Email Address </label><span>:</span></div>\n <div class=\"col-sm-8\">\n <input type=\"email\" id=\"Email\" name=\"Email\" placeholder=\"Enter Email Address\" class=\"form-control input-sm\" required>\n </div>\n </div>\n <div class=\"row cont-row\">\n <div class=\"col-sm-3\">\n <label for=\"Number\">Mobile Number</label><span>:</span></div>\n <div class=\"col-sm-8\">\n <input type=\"tel\" id=\"Number\" name=\"Number\" placeholder=\"Enter Mobile Number\" class=\"form-control input-sm\" required>\n </div>\n </div>\n <div class=\"row cont-row\">\n <div class=\"col-sm-3\">\n <label for=\"Address\">Address </label><span>:</span></div>\n <div class=\"col-sm-8\">\n <input type=\"text\" id=\"Address\" placeholder=\"Your residential address\" name=\"Address\" class=\"form-control input-sm\" required>\n </div>\n </div>\n <div class=\"row cont-row\">\n <div class=\"col-sm-3\">\n <label for=\"State\">Enter State </label><span>:</span></div>\n <div class=\"col-sm-8\">\n <input type=\"text\" id=\"State\" name=\"State\" placeholder=\"Your State of Residence\" class=\"form-control input-sm\" required>\n </div>\n </div>\n <div class=\"row cont-row\">\n <div class=\"col-sm-3\">\n <label for=\"Country\">Enter Country</label><span>:</span></div>\n <div class=\"col-sm-8\">\n <input type=\"text\" id=\"Country\" name=\"Country\" placeholder=\"Your Country of Residence\" class=\"form-control input-sm\" required>\n </div>\n </div>\n <div class=\"row cont-row\">\n <div class=\"col-sm-3\">\n <label for=\"Occupation\">Occupation </label><span>:</span></div>\n <div class=\"col-sm-8\">\n <input type=\"text\" id=\"Occupation\" placeholder=\"Enter Occupation\" name=\"Occupation\" class=\"form-control input-sm\" required>\n </div>\n </div>\n <div class=\"row cont-row\">\n <div class=\"col-sm-3\">\n <label for=\"Experience\">Volunteer Xpernce.</label><span>:</span></div>\n <div class=\"col-sm-8\">\n <input type=\"text\" id=\"Experience\" name=\"Experience\" placeholder=\"Your previous volunteer experience / Optional \" class=\"form-control input-sm\">\n </div>\n </div>\n <div class=\"row cont-row\">\n <div class=\"col-sm-3\">\n <label for=\"Languages\">Languages Spoken</label><span>:</span></div>\n <div class=\"col-sm-8\">\n <input type=\"text\" id=\"Languages\" name=\"Languages\" placeholder=\"Tell us the language(s) you speak fluently\" class=\"form-control input-sm\" required>\n </div>\n </div>\n <div class=\"row cont-row\">\n <div class=\"col-sm-3\">\n <label for=\"Gender\">Gender</label><span>:</span></div>\n <div class=\"col-sm-8\">\n <select id=\"Gender\" name=\"Gender\" class=\"form-control input-sm\" required>\n <option Value=\"\">Select your Gender</option>\n <option value=\"male\">Male</option>\n <option value=\"female\">Female</option>\n <option value=\"Other\">Other</option>\n </select>\n </div>\n </div>\n <div class=\"row cont-row\">\n <div class=\"col-sm-3\">\n <label for=\"Dob\">Date of Birth</label><span>:</span></div>\n <div class=\"col-sm-8\">\n <input type=\"date\" id=\"Dob\" name=\"Dob\" placeholder=\"Enter your Date of Birth\" class=\"form-control input-sm\" required>\n </div>\n </div>\n <div class=\"row cont-row\">\n <div class=\"col-sm-3\">\n <label for=\"Info\">Other information</label><span>:</span></div>\n <div class=\"col-sm-8\">\n <textarea rows=\"5\" id=\"Info\" placeholder=\"Enter other information that enable us make a good match\" class=\"form-control input-sm\"></textarea>\n </div>\n </div>\n <div style=\"margin-top:10px;\" class=\"row\">\n <div style=\"padding-top:10px;\" class=\"col-sm-3\">\n <label></label>\n </div>\n <div class=\"col-sm-8\">\n <button type=\"submit\" id=\"fcf-button\" class=\"btn btn-primary btn-sm\">Submit</button>\n </div>\n </div>\n </form>\n</div>\n \n<?php var_dump($_POST) ?>\n\n" }, { "answer_id": 74513187, "author": "Mike", "author_id": 18061901, "author_profile": "https://Stackoverflow.com/users/18061901", "pm_score": 1, "selected": false, "text": "problem(\"We're sorry ....\")\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74508581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20554692/" ]
74,508,630
<pre class="lang-cs prettyprint-override"><code>using System.Diagnostics; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class SettingsScript : MonoBehaviour { public GameObject Muzica; public GameObject Oftat; public GameObject SFX; public GameObject Fullscreen; public GameObject VolumObject; public bool MuzicaBool = true; public bool OftatBool; public bool SFXBool = true; public bool FullscreenBool = true; public float VolumFloat = 1f; public AudioSource on; public AudioSource off; public static SettingsScript instance; void Awake() { instance = this; } void Update() { UnityEngine.Debug.Log(MuzicaBool + &quot; &quot; + OftatBool + &quot; &quot; + SFXBool + &quot; &quot; + FullscreenBool + &quot; &quot; + VolumFloat); } public void Menu() { SceneManager.LoadScene(&quot;Meniu&quot;); } public void Volum() { AudioListener.volume = VolumFloat; } public void MuzicaOn() { if (MuzicaBool) { Muzica.GetComponent&lt;SpriteRenderer&gt;().color = new Color(1, 1, 1, 0); MuzicaBool = !MuzicaBool; } else { Muzica.GetComponent&lt;SpriteRenderer&gt;().color = new Color(1, 1, 1, 1); } MuzicaBool = !MuzicaBool; UnityEngine.Debug.Log(&quot;Muzica&quot;); if(MuzicaBool) { on.Play(); } else { off.Play(); } } public void OftatOn() { if (OftatBool) { Oftat.GetComponent&lt;SpriteRenderer&gt;().color = new Color(1, 1, 1, 0); } else { Oftat.GetComponent&lt;SpriteRenderer&gt;().color = new Color(1, 1, 1, 1); } OftatBool = !OftatBool; UnityEngine.Debug.Log(&quot;Oftat&quot;); if(OftatBool) { on.Play(); } else { off.Play(); } } public void SFXOn() { if (SFXBool) { SFX.GetComponent&lt;SpriteRenderer&gt;().color = new Color(1, 1, 1, 0); } else { SFX.GetComponent&lt;SpriteRenderer&gt;().color = new Color(1, 1, 1, 1); } SFXBool = !SFXBool; UnityEngine.Debug.Log(&quot;SFX&quot;); if(SFXBool) { on.Play(); } else { off.Play(); } } public void FullscreenOn() { if (FullscreenBool) { Fullscreen.GetComponent&lt;SpriteRenderer&gt;().color = new Color(1, 1, 1, 0); } else { Fullscreen.GetComponent&lt;SpriteRenderer&gt;().color = new Color(1, 1, 1, 1); } FullscreenBool = !FullscreenBool; UnityEngine.Debug.Log(&quot;Fullscreen&quot;); if(FullscreenBool) { on.Play(); } else { off.Play(); } } } </code></pre> <p>here's a video of the menu, not working</p> <p><a href="https://www.youtube.com/watch?v=gfNOi86lbxI&amp;ab_channel=GhiocelGames" rel="nofollow noreferrer">https://www.youtube.com/watch?v=gfNOi86lbxI&amp;ab_channel=GhiocelGames</a></p> <p>The option for music &quot;Muzică&quot;, does not turn off.</p> <p>The other options do not respect the boolean variables used in the code, and at first wont turn off if on, as you can see in the video</p> <p>I want to make settings for my game.</p>
[ { "answer_id": 74512405, "author": "HEJOK254", "author_id": 17003609, "author_profile": "https://Stackoverflow.com/users/17003609", "pm_score": 0, "selected": false, "text": "using System.Diagnostics;\nusing System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEngine.SceneManagement;\npublic class SettingsScript : MonoBehaviour\n{\n public GameObject Muzica, Oftat, SFX, Fullscreen, VolumObject;\n public bool MuzicaBool = true, OftatBool, SFXBool = true, FullscreenBool = true;\n public float VolumFloat = 1f;\n public AudioSource on, off;\n public static SettingsScript instance;\n\n void Awake()\n {\n instance = this;\n\n //You can put the code for\n //loading the save here\n //(You can use PlayerPrefs)\n\n //Set objects' states to their values. (Fixes the problem where the toggles don't change)\n Muzica.SetActive(MuzicaBool);\n Oftat.SetActive(OftatBool);\n SFX.SetActive(SFXBool);\n Fullscreen.SetActive(FullscreenBool);\n AudioListener.volume = VolumFloat;\n \n \n }\n\n void Update()\n {\n UnityEngine.Debug.Log(MuzicaBool + \" \" + OftatBool + \" \" + SFXBool + \" \" + FullscreenBool + \" \" + VolumFloat);\n }\n\n public void Menu()\n {\n SceneManager.LoadScene(\"Meniu\");\n }\n\n public void Volum()\n {\n AudioListener.volume = VolumFloat;\n }\n\n public void MuzicaOn()\n {\n MuzicaBool = !MuzicaBool;\n Muzica.SetActive(MuzicaBool);\n PlaySound(MuzicaBool);\n\n UnityEngine.Debug.Log(\"Muzica\");\n }\n\n public void OftatOn()\n {\n OftatBool = !OftatBool;\n Oftat.SetActive(OftatBool);\n PlaySound(OftatBool);\n\n UnityEngine.Debug.Log(\"Oftat\");\n }\n\n public void SFXOn()\n {\n SFXBool = !SFXBool;\n SFX.SetActive(SFXBool);\n PlaySound(SFXBool);\n\n UnityEngine.Debug.Log(\"SFX\");\n }\n\n public void FullscreenOn()\n {\n FullscreenBool = !FullscreenBool;\n Fullscreen.SetActive(FullscreenBool);\n PlaySound(FullscreenBool);\n\n UnityEngine.Debug.Log(\"Fullscreen\");\n }\n \n //A method to play the 'on' or 'off' sound\n void PlaySound(bool onBool)\n {\n if(onBool)\n on.Play();\n else\n off.Play();\n }\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74508630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15978634/" ]
74,508,632
<p>A 2D array of integers B(M, N) is set using a random number sensor. Display the array. Find the largest element of the array. Print its indexes.</p> <p>I do not know what to do with m, n and how to find max</p> <pre><code>namespace Program { class Program { static void Main(string[] args) { int m,n; Random rnd = new Random(); m = 4; n = 4; int max; int[,] m1 = new int[m,n]; for(int i=0;i&lt;m;i++) { for(int j =0;j&lt;n;j++){ m1[i,j] = rnd.Next(100); Console.Write(m1[i,j] + &quot;\t&quot;); } } </code></pre>
[ { "answer_id": 74512405, "author": "HEJOK254", "author_id": 17003609, "author_profile": "https://Stackoverflow.com/users/17003609", "pm_score": 0, "selected": false, "text": "using System.Diagnostics;\nusing System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEngine.SceneManagement;\npublic class SettingsScript : MonoBehaviour\n{\n public GameObject Muzica, Oftat, SFX, Fullscreen, VolumObject;\n public bool MuzicaBool = true, OftatBool, SFXBool = true, FullscreenBool = true;\n public float VolumFloat = 1f;\n public AudioSource on, off;\n public static SettingsScript instance;\n\n void Awake()\n {\n instance = this;\n\n //You can put the code for\n //loading the save here\n //(You can use PlayerPrefs)\n\n //Set objects' states to their values. (Fixes the problem where the toggles don't change)\n Muzica.SetActive(MuzicaBool);\n Oftat.SetActive(OftatBool);\n SFX.SetActive(SFXBool);\n Fullscreen.SetActive(FullscreenBool);\n AudioListener.volume = VolumFloat;\n \n \n }\n\n void Update()\n {\n UnityEngine.Debug.Log(MuzicaBool + \" \" + OftatBool + \" \" + SFXBool + \" \" + FullscreenBool + \" \" + VolumFloat);\n }\n\n public void Menu()\n {\n SceneManager.LoadScene(\"Meniu\");\n }\n\n public void Volum()\n {\n AudioListener.volume = VolumFloat;\n }\n\n public void MuzicaOn()\n {\n MuzicaBool = !MuzicaBool;\n Muzica.SetActive(MuzicaBool);\n PlaySound(MuzicaBool);\n\n UnityEngine.Debug.Log(\"Muzica\");\n }\n\n public void OftatOn()\n {\n OftatBool = !OftatBool;\n Oftat.SetActive(OftatBool);\n PlaySound(OftatBool);\n\n UnityEngine.Debug.Log(\"Oftat\");\n }\n\n public void SFXOn()\n {\n SFXBool = !SFXBool;\n SFX.SetActive(SFXBool);\n PlaySound(SFXBool);\n\n UnityEngine.Debug.Log(\"SFX\");\n }\n\n public void FullscreenOn()\n {\n FullscreenBool = !FullscreenBool;\n Fullscreen.SetActive(FullscreenBool);\n PlaySound(FullscreenBool);\n\n UnityEngine.Debug.Log(\"Fullscreen\");\n }\n \n //A method to play the 'on' or 'off' sound\n void PlaySound(bool onBool)\n {\n if(onBool)\n on.Play();\n else\n off.Play();\n }\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74508632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20460210/" ]
74,508,649
<p>I am trying to get a create a variable <code>oldPlayerStats</code> to get the current value of <code>G.playerStats</code>, so that later when <code>G.playerStats</code> gets updated, I can subtract the <code>oldPlayerStats</code> from the new value of <code>G.playerStats</code> to get the difference.</p> <p>However for some reason, <code>oldPlayerStats</code> updates to always match <code>G.playerStats</code>.</p> <p>Relevant code below:</p> <pre><code>const oldPlayerStats = G.playerStats; console.log(oldPlayerStats[0].wood); //Is 10 as it should be //This function affects the value of `G.playerStats`. It does not do anything to oldPlayerStats cardFunction.function(G, ctx, ctx.currentPlayer, G.opponent, G.attackMultiplier); console.log(oldPlayerStats[0].wood); //Should be 10, but instead updates to match the new value of `G.playerStats` </code></pre>
[ { "answer_id": 74508733, "author": "ramseylove", "author_id": 12012004, "author_profile": "https://Stackoverflow.com/users/12012004", "pm_score": 2, "selected": false, "text": "const oldPlayerStats = structuredClone(G.playerState)\n" }, { "answer_id": 74508757, "author": "Alex Hoggett", "author_id": 16079218, "author_profile": "https://Stackoverflow.com/users/16079218", "pm_score": 1, "selected": false, "text": "slice oldPlayerStats = G.playerStats.slice()\n" }, { "answer_id": 74509232, "author": "evilgenious448", "author_id": 7341585, "author_profile": "https://Stackoverflow.com/users/7341585", "pm_score": 0, "selected": false, "text": "const oldPlayerStats = JSON.parse(JSON.stringify(G.playerStats));" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74508649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7341585/" ]
74,508,661
<p>I'm Trying to create a (number) password cracker function using numpy arrays instead of for-loops.</p> <p>What can I add to my cracker function to avoid this error? (See image of code attached)</p> <p><a href="https://i.stack.imgur.com/jv8JP.png" rel="nofollow noreferrer">Image of my code</a></p> <p>I want the cracker function to return the value in the 'possible' array that returns 'Correct' when used as the argument in the password function.</p>
[ { "answer_id": 74508733, "author": "ramseylove", "author_id": 12012004, "author_profile": "https://Stackoverflow.com/users/12012004", "pm_score": 2, "selected": false, "text": "const oldPlayerStats = structuredClone(G.playerState)\n" }, { "answer_id": 74508757, "author": "Alex Hoggett", "author_id": 16079218, "author_profile": "https://Stackoverflow.com/users/16079218", "pm_score": 1, "selected": false, "text": "slice oldPlayerStats = G.playerStats.slice()\n" }, { "answer_id": 74509232, "author": "evilgenious448", "author_id": 7341585, "author_profile": "https://Stackoverflow.com/users/7341585", "pm_score": 0, "selected": false, "text": "const oldPlayerStats = JSON.parse(JSON.stringify(G.playerStats));" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74508661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20554921/" ]
74,508,666
<p>I'm writing scraper in Python with bs4 and want to remove links from all 'a' tags</p> <p>I have html code</p> <pre><code>html_code = '&lt;a href=&quot;link&quot;&gt;some text&lt;/a&gt;' </code></pre> <p>I want to remove href=&quot;link&quot; and get only</p> <pre><code>html_code = '&lt;a&gt;some text&lt;/a&gt;' </code></pre> <p>How can i do it?</p>
[ { "answer_id": 74508718, "author": "Daweo", "author_id": 10785975, "author_profile": "https://Stackoverflow.com/users/10785975", "pm_score": 3, "selected": true, "text": "from bs4 import BeautifulSoup\nhtml_code = '<a href=\"link\">some text</a>'\nsoup = BeautifulSoup(html_code)\nprint(\"Before\")\nprint(soup.prettify())\nfor node in soup.find_all(\"a\"):\n node.attrs = {}\nprint(\"After\")\nprint(soup.prettify())\n Before\n<html>\n <body>\n <a href=\"link\">\n some text\n </a>\n </body>\n</html>\nAfter\n<html>\n <body>\n <a>\n some text\n </a>\n </body>\n</html>\n <a>" }, { "answer_id": 74508732, "author": "Khaled DELLAL", "author_id": 15852600, "author_profile": "https://Stackoverflow.com/users/15852600", "pm_score": 0, "selected": false, "text": "html_code = html_code.replace(' href=\"link\"','')\n >>> print(html_code)\n\n>>> '<a>some text</a>'\n" }, { "answer_id": 74509238, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 0, "selected": false, "text": "from bs4 import BeautifulSoup\n\nsoup = BeautifulSoup('<a href=\"link\">some text</a>', \"html.parser\")\n\ndel soup.a.attrs\nprint(soup.a)\n <a>some text</a>\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74508666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18448606/" ]
74,508,670
<p><code>select count(memberid) cnt from memberdata where MemberID;</code></p> <p><code>select count(Deleted) UnUsable from memberdata where deleted = 1;</code></p> <p><code>select count(Deleted) Usable from memberdata where deleted = 0;</code></p> <blockquote> <p>Question How to make this query to one?</p> </blockquote>
[ { "answer_id": 74508710, "author": "nbk", "author_id": 5193536, "author_profile": "https://Stackoverflow.com/users/5193536", "pm_score": 0, "selected": false, "text": "select \ncount(memberid) cnt\n,(SELECT count(deleted = 1) FROM memberdata) UnUsable\n, (SELECT count(deleted = 0) FROM memberdata) Usable \nfrom memberdata where MemberID;\n" }, { "answer_id": 74508746, "author": "Bernd Buffen", "author_id": 5247279, "author_profile": "https://Stackoverflow.com/users/5247279", "pm_score": 1, "selected": false, "text": "SELECT\n count(memberid) AS cnt,\n count(Deleted = 1) AS UnUsabl,\n count(Deleted = 0) AS Usable\nFROM memberdata;\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74508670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20555004/" ]
74,508,711
<p>I have a data.frame with mix numeric scale values and other continuous values. However, the missing data represented by the following values -1 and 8. this is an example:</p> <pre><code>df = data.frame(Name = c('George','Andrea', 'Micheal','Maggie','Ravi','Xien','Jalpa'), Grade_score=c(4,6,2,9,5,7,8), Mathematics1_score=c(45,78,44,89,66,49,72), Science_score=c(-1,52,45,88,-1,90,47), Science_scale=c(-1,5,5,8,3,0,7)) </code></pre> <p>I want to delete any row that has any of the missing data from the entire data.frame. I can do it column by column but I have more than 25 columns.</p> <pre><code>df2&lt;-subset(df, df$x1 !=&quot;-1&quot;) </code></pre>
[ { "answer_id": 74508765, "author": "Tom Hoel", "author_id": 17213355, "author_profile": "https://Stackoverflow.com/users/17213355", "pm_score": 2, "selected": false, "text": "library(tidyverse)\n\ndf %>% \n filter(if_all(everything(), ~ !(.x %in% c(-1, 8))))\n\n# A tibble: 3 × 5\n Name Grade_score Mathematics1_score Science_score Science_scale\n <chr> <dbl> <dbl> <dbl> <dbl>\n1 Andrea 6 78 52 5\n2 Micheal 2 44 45 5\n3 Xien 7 49 90 0\n" }, { "answer_id": 74508798, "author": "langtang", "author_id": 4447540, "author_profile": "https://Stackoverflow.com/users/4447540", "pm_score": 2, "selected": false, "text": "df[apply(df[,-1],1, \\(x) !any(x %in% c(-1,8))),]\n NA na.omit() library(dplyr) \ndf %>% \n mutate(across(-Name, ~if_else(.x %in% c(-1,8),NA_real_,.x))) %>% \n na.omit()\n Name Grade_score Mathematics1_score Science_score Science_scale\n <char> <num> <num> <num> <num>\n1: Andrea 6 78 52 5\n2: Micheal 2 44 45 5\n3: Xien 7 49 90 0\n" }, { "answer_id": 74508817, "author": "r2evans - GO NAVY BEAT ARMY", "author_id": 3358272, "author_profile": "https://Stackoverflow.com/users/3358272", "pm_score": 2, "selected": false, "text": "df[rowSums(sapply(df, `%in%`, c(-1, 8))) < 1,]\n# Name Grade_score Mathematics1_score Science_score Science_scale\n# 2 Andrea 6 78 52 5\n# 3 Micheal 2 44 45 5\n# 6 Xien 7 49 90 0\n library(dplyr)\ndf %>%\n filter(if_all(everything(), ~ !. %in% c(-1, 8)))\n# Name Grade_score Mathematics1_score Science_score Science_scale\n# 1 Andrea 6 78 52 5\n# 2 Micheal 2 44 45 5\n# 3 Xien 7 49 90 0\n Grade_score 8 df %>%\n filter(\n if_all(-Grade_score, ~ !. %in% c(-1, 8)),\n Grade_score != -1\n )\n# Name Grade_score Mathematics1_score Science_score Science_scale\n# 1 Andrea 6 78 52 5\n# 2 Micheal 2 44 45 5\n# 3 Xien 7 49 90 0\n# 4 Jalpa 8 72 47 7\n df %>%\n filter(\n if_all(-c(Grade_score, Science_scale), ~ !. %in% c(-1, 8)), \n if_all(c(Grade_score, Science_scale), ~ . != -1)\n )\n# Name Grade_score Mathematics1_score Science_score Science_scale\n# 1 Andrea 6 78 52 5\n# 2 Micheal 2 44 45 5\n# 3 Maggie 9 89 88 8\n# 4 Xien 7 49 90 0\n# 5 Jalpa 8 72 47 7\n `%in%` df[rowSums(cbind(\n sapply(df[,-c(1:2, 5)], `%in%`, c(-1, 8)),\n sapply(df[,c(1:2, 5)], `%in%`, -1))) < 1,]\n# Name Grade_score Mathematics1_score Science_score Science_scale\n# 2 Andrea 6 78 52 5\n# 3 Micheal 2 44 45 5\n# 4 Maggie 9 89 88 8\n# 6 Xien 7 49 90 0\n# 7 Jalpa 8 72 47 7\n" }, { "answer_id": 74509189, "author": "AndS.", "author_id": 9778513, "author_profile": "https://Stackoverflow.com/users/9778513", "pm_score": 0, "selected": false, "text": "na.omit(replace(df, df ==-1 | df == 8, NA))\n#> Name Grade_score Mathematics1_score Science_score Science_scale\n#> 2 Andrea 6 78 52 5\n#> 3 Micheal 2 44 45 5\n#> 6 Xien 7 49 90 0\n" }, { "answer_id": 74509636, "author": "Andre Wildberg", "author_id": 9462095, "author_profile": "https://Stackoverflow.com/users/9462095", "pm_score": 0, "selected": false, "text": "apply apply(df, 2, function(x) grep(8, x, value = T))\n$Name\ncharacter(0)\n\n$Grade_score\n[1] \"8\"\n\n$Mathematics1_score\n[1] \"78\" \"89\"\n\n$Science_score\n[1] \"88\"\n\n$Science_scale\n[1] \" 8\" # <-------- \" 8\" will make direct comparisons FALSE\n trimws df[!apply(df, 1, function(x) any(trimws(x) %in% c(-1, 8))), ]\n Name Grade_score Mathematics1_score Science_score Science_scale\n2 Andrea 6 78 52 5\n3 Micheal 2 44 45 5\n6 Xien 7 49 90 0\n apply sapply lapply dplyr" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74508711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5504724/" ]
74,508,749
<p>Hello I am building a DQN model for reinforcement learning on cartpole and want to print my model summary like keras model.summary() function</p> <p>Here is my model class.</p> <pre><code>class DQN(): ''' Deep Q Neural Network class. ''' def __init__(self, state_dim, action_dim, hidden_dim=64, lr=0.05): super(DQN, self).__init__() self.criterion = torch.nn.MSELoss() self.model = torch.nn.Sequential( torch.nn.Linear(state_dim, hidden_dim), torch.nn.ReLU(), torch.nn.Linear(hidden_dim, hidden_dim*2), torch.nn.ReLU(), torch.nn.Linear(hidden_dim*2, action_dim) ) self.optimizer = torch.optim.Adam(self.model.parameters(), lr) def update(self, state, y): &quot;&quot;&quot;Update the weights of the network given a training sample. &quot;&quot;&quot; y_pred = self.model(torch.Tensor(state)) loss = self.criterion(y_pred, Variable(torch.Tensor(y))) self.optimizer.zero_grad() loss.backward() self.optimizer.step() def predict(self, state): &quot;&quot;&quot; Compute Q values for all actions using the DQL. &quot;&quot;&quot; with torch.no_grad(): return self.model(torch.Tensor(state)) </code></pre> <p>Here is the model instance with the parameters passed.</p> <pre><code># Number of states = 4 n_state = env.observation_space.shape[0] # Number of actions = 2 n_action = env.action_space.n # Number of episodes episodes = 150 # Number of hidden nodes in the DQN n_hidden = 50 # Learning rate lr = 0.001 simple_dqn = DQN(n_state, n_action, n_hidden, lr) </code></pre> <p>I tried using torchinfo summary</p> <pre><code>from torchinfo import summary simple_dqn = DQN(n_state, n_action, n_hidden, lr) summary(simple_dqn, input_size=(4, 2, 50)) </code></pre> <p>But I get the following error</p> <pre><code>NotImplementedError Traceback (most recent call last) /usr/local/lib/python3.7/dist-packages/torchinfo/torchinfo.py in forward_pass(model, x, batch_dim, cache_forward_pass, device, mode, **kwargs) 286 if isinstance(x, (list, tuple)): --&gt; 287 _ = model.to(device)(*x, **kwargs) 288 elif isinstance(x, dict): 4 frames /usr/local/lib/python3.7/dist-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs) 1147 -&gt; 1148 result = forward_call(*input, **kwargs) 1149 if _global_forward_hooks or self._forward_hooks: /usr/local/lib/python3.7/dist-packages/torch/nn/modules/module.py in _forward_unimplemented(self, *input) 200 &quot;&quot;&quot; --&gt; 201 raise NotImplementedError(f&quot;Module [{type(self).__name__}] is missing the required \&quot;forward\&quot; function&quot;) 202 NotImplementedError: Module [DQN] is missing the required &quot;forward&quot; function The above exception was the direct cause of the following exception: RuntimeError Traceback (most recent call last) &lt;ipython-input-24-ee921f7e5cb5&gt; in &lt;module&gt; 1 from torchinfo import summary 2 simple_dqn = DQN(n_state, n_action, n_hidden, lr) ----&gt; 3 summary(simple_dqn, input_size=(4, 2, 50)) /usr/local/lib/python3.7/dist-packages/torchinfo/torchinfo.py in summary(model, input_size, input_data, batch_dim, cache_forward_pass, col_names, col_width, depth, device, dtypes, mode, row_settings, verbose, **kwargs) 216 ) 217 summary_list = forward_pass( --&gt; 218 model, x, batch_dim, cache_forward_pass, device, model_mode, **kwargs 219 ) 220 formatting = FormattingOptions(depth, verbose, columns, col_width, rows) /usr/local/lib/python3.7/dist-packages/torchinfo/torchinfo.py in forward_pass(model, x, batch_dim, cache_forward_pass, device, mode, **kwargs) 297 &quot;Failed to run torchinfo. See above stack traces for more details. &quot; 298 f&quot;Executed layers up to: {executed_layers}&quot; --&gt; 299 ) from e 300 finally: 301 if hooks: RuntimeError: Failed to run torchinfo. See above stack traces for more details. Executed layers up to: [] </code></pre> <p>Any help is appreciated.</p>
[ { "answer_id": 74508765, "author": "Tom Hoel", "author_id": 17213355, "author_profile": "https://Stackoverflow.com/users/17213355", "pm_score": 2, "selected": false, "text": "library(tidyverse)\n\ndf %>% \n filter(if_all(everything(), ~ !(.x %in% c(-1, 8))))\n\n# A tibble: 3 × 5\n Name Grade_score Mathematics1_score Science_score Science_scale\n <chr> <dbl> <dbl> <dbl> <dbl>\n1 Andrea 6 78 52 5\n2 Micheal 2 44 45 5\n3 Xien 7 49 90 0\n" }, { "answer_id": 74508798, "author": "langtang", "author_id": 4447540, "author_profile": "https://Stackoverflow.com/users/4447540", "pm_score": 2, "selected": false, "text": "df[apply(df[,-1],1, \\(x) !any(x %in% c(-1,8))),]\n NA na.omit() library(dplyr) \ndf %>% \n mutate(across(-Name, ~if_else(.x %in% c(-1,8),NA_real_,.x))) %>% \n na.omit()\n Name Grade_score Mathematics1_score Science_score Science_scale\n <char> <num> <num> <num> <num>\n1: Andrea 6 78 52 5\n2: Micheal 2 44 45 5\n3: Xien 7 49 90 0\n" }, { "answer_id": 74508817, "author": "r2evans - GO NAVY BEAT ARMY", "author_id": 3358272, "author_profile": "https://Stackoverflow.com/users/3358272", "pm_score": 2, "selected": false, "text": "df[rowSums(sapply(df, `%in%`, c(-1, 8))) < 1,]\n# Name Grade_score Mathematics1_score Science_score Science_scale\n# 2 Andrea 6 78 52 5\n# 3 Micheal 2 44 45 5\n# 6 Xien 7 49 90 0\n library(dplyr)\ndf %>%\n filter(if_all(everything(), ~ !. %in% c(-1, 8)))\n# Name Grade_score Mathematics1_score Science_score Science_scale\n# 1 Andrea 6 78 52 5\n# 2 Micheal 2 44 45 5\n# 3 Xien 7 49 90 0\n Grade_score 8 df %>%\n filter(\n if_all(-Grade_score, ~ !. %in% c(-1, 8)),\n Grade_score != -1\n )\n# Name Grade_score Mathematics1_score Science_score Science_scale\n# 1 Andrea 6 78 52 5\n# 2 Micheal 2 44 45 5\n# 3 Xien 7 49 90 0\n# 4 Jalpa 8 72 47 7\n df %>%\n filter(\n if_all(-c(Grade_score, Science_scale), ~ !. %in% c(-1, 8)), \n if_all(c(Grade_score, Science_scale), ~ . != -1)\n )\n# Name Grade_score Mathematics1_score Science_score Science_scale\n# 1 Andrea 6 78 52 5\n# 2 Micheal 2 44 45 5\n# 3 Maggie 9 89 88 8\n# 4 Xien 7 49 90 0\n# 5 Jalpa 8 72 47 7\n `%in%` df[rowSums(cbind(\n sapply(df[,-c(1:2, 5)], `%in%`, c(-1, 8)),\n sapply(df[,c(1:2, 5)], `%in%`, -1))) < 1,]\n# Name Grade_score Mathematics1_score Science_score Science_scale\n# 2 Andrea 6 78 52 5\n# 3 Micheal 2 44 45 5\n# 4 Maggie 9 89 88 8\n# 6 Xien 7 49 90 0\n# 7 Jalpa 8 72 47 7\n" }, { "answer_id": 74509189, "author": "AndS.", "author_id": 9778513, "author_profile": "https://Stackoverflow.com/users/9778513", "pm_score": 0, "selected": false, "text": "na.omit(replace(df, df ==-1 | df == 8, NA))\n#> Name Grade_score Mathematics1_score Science_score Science_scale\n#> 2 Andrea 6 78 52 5\n#> 3 Micheal 2 44 45 5\n#> 6 Xien 7 49 90 0\n" }, { "answer_id": 74509636, "author": "Andre Wildberg", "author_id": 9462095, "author_profile": "https://Stackoverflow.com/users/9462095", "pm_score": 0, "selected": false, "text": "apply apply(df, 2, function(x) grep(8, x, value = T))\n$Name\ncharacter(0)\n\n$Grade_score\n[1] \"8\"\n\n$Mathematics1_score\n[1] \"78\" \"89\"\n\n$Science_score\n[1] \"88\"\n\n$Science_scale\n[1] \" 8\" # <-------- \" 8\" will make direct comparisons FALSE\n trimws df[!apply(df, 1, function(x) any(trimws(x) %in% c(-1, 8))), ]\n Name Grade_score Mathematics1_score Science_score Science_scale\n2 Andrea 6 78 52 5\n3 Micheal 2 44 45 5\n6 Xien 7 49 90 0\n apply sapply lapply dplyr" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74508749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20301773/" ]
74,508,791
<p>I am trying to run Junit4 tests and I am unable to run it. I have the following dependency installed</p> <pre><code>&lt;dependency&gt; &lt;groupId&gt;junit&lt;/groupId&gt; &lt;artifactId&gt;junit&lt;/artifactId&gt; &lt;version&gt;4.13.2&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; </code></pre> <p>My test class looks like this</p> <pre><code>package model.validators; import org.junit.Assert; import org.junit.Test; import java.util.Arrays; import java.util.List; class UserValidatorTest { @Test public void shouldReturnTrueForValidPhoneNumbers() { List&lt;String&gt; phoneNumbers = Arrays.asList( &quot;9876543210&quot;, &quot;7777543210&quot; ); boolean result = UserValidator.validateUserPhoneNumbers(phoneNumbers); Assert.assertTrue(result); } } </code></pre> <p>When I try to run this test, I get the following error</p> <pre><code>org.junit.runners.model.InvalidTestClassError: Invalid test class 'model.validators.UserValidatorTest': </code></pre> <p>I am using IntellijIdea. Any idea what is going wrong here ? TIA</p> <p>Tried changing dependencies, reloading maven project, setting the correct classpath in Junit Run configurations</p>
[ { "answer_id": 74508765, "author": "Tom Hoel", "author_id": 17213355, "author_profile": "https://Stackoverflow.com/users/17213355", "pm_score": 2, "selected": false, "text": "library(tidyverse)\n\ndf %>% \n filter(if_all(everything(), ~ !(.x %in% c(-1, 8))))\n\n# A tibble: 3 × 5\n Name Grade_score Mathematics1_score Science_score Science_scale\n <chr> <dbl> <dbl> <dbl> <dbl>\n1 Andrea 6 78 52 5\n2 Micheal 2 44 45 5\n3 Xien 7 49 90 0\n" }, { "answer_id": 74508798, "author": "langtang", "author_id": 4447540, "author_profile": "https://Stackoverflow.com/users/4447540", "pm_score": 2, "selected": false, "text": "df[apply(df[,-1],1, \\(x) !any(x %in% c(-1,8))),]\n NA na.omit() library(dplyr) \ndf %>% \n mutate(across(-Name, ~if_else(.x %in% c(-1,8),NA_real_,.x))) %>% \n na.omit()\n Name Grade_score Mathematics1_score Science_score Science_scale\n <char> <num> <num> <num> <num>\n1: Andrea 6 78 52 5\n2: Micheal 2 44 45 5\n3: Xien 7 49 90 0\n" }, { "answer_id": 74508817, "author": "r2evans - GO NAVY BEAT ARMY", "author_id": 3358272, "author_profile": "https://Stackoverflow.com/users/3358272", "pm_score": 2, "selected": false, "text": "df[rowSums(sapply(df, `%in%`, c(-1, 8))) < 1,]\n# Name Grade_score Mathematics1_score Science_score Science_scale\n# 2 Andrea 6 78 52 5\n# 3 Micheal 2 44 45 5\n# 6 Xien 7 49 90 0\n library(dplyr)\ndf %>%\n filter(if_all(everything(), ~ !. %in% c(-1, 8)))\n# Name Grade_score Mathematics1_score Science_score Science_scale\n# 1 Andrea 6 78 52 5\n# 2 Micheal 2 44 45 5\n# 3 Xien 7 49 90 0\n Grade_score 8 df %>%\n filter(\n if_all(-Grade_score, ~ !. %in% c(-1, 8)),\n Grade_score != -1\n )\n# Name Grade_score Mathematics1_score Science_score Science_scale\n# 1 Andrea 6 78 52 5\n# 2 Micheal 2 44 45 5\n# 3 Xien 7 49 90 0\n# 4 Jalpa 8 72 47 7\n df %>%\n filter(\n if_all(-c(Grade_score, Science_scale), ~ !. %in% c(-1, 8)), \n if_all(c(Grade_score, Science_scale), ~ . != -1)\n )\n# Name Grade_score Mathematics1_score Science_score Science_scale\n# 1 Andrea 6 78 52 5\n# 2 Micheal 2 44 45 5\n# 3 Maggie 9 89 88 8\n# 4 Xien 7 49 90 0\n# 5 Jalpa 8 72 47 7\n `%in%` df[rowSums(cbind(\n sapply(df[,-c(1:2, 5)], `%in%`, c(-1, 8)),\n sapply(df[,c(1:2, 5)], `%in%`, -1))) < 1,]\n# Name Grade_score Mathematics1_score Science_score Science_scale\n# 2 Andrea 6 78 52 5\n# 3 Micheal 2 44 45 5\n# 4 Maggie 9 89 88 8\n# 6 Xien 7 49 90 0\n# 7 Jalpa 8 72 47 7\n" }, { "answer_id": 74509189, "author": "AndS.", "author_id": 9778513, "author_profile": "https://Stackoverflow.com/users/9778513", "pm_score": 0, "selected": false, "text": "na.omit(replace(df, df ==-1 | df == 8, NA))\n#> Name Grade_score Mathematics1_score Science_score Science_scale\n#> 2 Andrea 6 78 52 5\n#> 3 Micheal 2 44 45 5\n#> 6 Xien 7 49 90 0\n" }, { "answer_id": 74509636, "author": "Andre Wildberg", "author_id": 9462095, "author_profile": "https://Stackoverflow.com/users/9462095", "pm_score": 0, "selected": false, "text": "apply apply(df, 2, function(x) grep(8, x, value = T))\n$Name\ncharacter(0)\n\n$Grade_score\n[1] \"8\"\n\n$Mathematics1_score\n[1] \"78\" \"89\"\n\n$Science_score\n[1] \"88\"\n\n$Science_scale\n[1] \" 8\" # <-------- \" 8\" will make direct comparisons FALSE\n trimws df[!apply(df, 1, function(x) any(trimws(x) %in% c(-1, 8))), ]\n Name Grade_score Mathematics1_score Science_score Science_scale\n2 Andrea 6 78 52 5\n3 Micheal 2 44 45 5\n6 Xien 7 49 90 0\n apply sapply lapply dplyr" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74508791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19139750/" ]
74,508,809
<p><strong>Problem</strong>: I am new to RXJS and having a hard time changing a pipe that is fetching http data and saving it in store conditionally (if status is active). One of the properties of missing and I need to consume another http service on a item-by-item basis, to fetch that missing property before saving in store. No need to call the second http service on items that have active=false flag.</p> <p><strong>Example</strong>:</p> <p>The 2 methods that fetch http data:</p> <pre><code>FetchHttpData1() : Observable&lt;IMainModelType[]&gt; FetchHttpItemProperty(id:number) : Observable&lt;IMissingPropertyType&gt; </code></pre> <p>models:</p> <pre><code>interface IMainModelType { id:number, name:string, missingProperty:string, //always null active:boolean } interface IMissingPropertyType{ id:number, missingProperty:string } </code></pre> <p>code so far:</p> <pre><code>let myObs = this.FetchHttpData1().pipe( map((values) =&gt; { values.forEach((singleValue) =&gt; { if(singleValue.active) { //this singleValue is being saved with a missing property and we dont want that //at this stage I need to response from FetchHttpItemProperty() to try and set the missing property this.storeSetSingle(singleValue); } }); }) ); </code></pre> <p>Suggestions on how to add extra steps to call this.FetchHttpItemProperty(id) and make sure the item set in this.storeSetSingle() has the missing property defined?</p> <p>I know this is probably very basic, but Im struggling with this for a while now and your suggestions will be opportunities to learn. Also open to suggestions if you think the current pipe could be better built.</p>
[ { "answer_id": 74509209, "author": "Eli Porush", "author_id": 14598976, "author_profile": "https://Stackoverflow.com/users/14598976", "pm_score": 2, "selected": false, "text": "let myObs = this.FetchHttpData1().pipe(\n switchMap((values: {id: number}[]) => {\n forkJoin(values.map(v => FetchHttpItemProperty(v.id))).pipe(\n map(vals => {\n const results = values.map(val => {...val, ...vals.find(i => i.id === val.id)})\n return results;\n }),\n tap(vals => vals.forEach(v => this.storeSetSingle(v)))\n )\n })\n" }, { "answer_id": 74509721, "author": "Eddy Lin", "author_id": 19768317, "author_profile": "https://Stackoverflow.com/users/19768317", "pm_score": 3, "selected": false, "text": "const missingApi$ = (x: IMainModelType) => this.FetchHttpItemProperty(x.id).pipe(\n map(({ missingProperty }) => ({...x, missingProperty})),\n tap((val) => this.storeSetSingle(val)),\n);\n\nlet myObs = this.FetchHttpData1().pipe(switchMap((arrs) => \n forkJoin(arrs.map((x) => x.active ? missingApi$(x) : of(x)))\n));\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74508809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3778853/" ]
74,508,815
<p>I have created 2 menus called &quot;Habit Setting&quot; and &quot;Team Setting&quot; <a href="https://i.stack.imgur.com/324yo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/324yo.png" alt="enter image description here" /></a></p> <p>But after clicking on second menu the page is reloading and the menu background is not going to second menu. There is always showing menu background of the first menu. Would like to have a better solution for that.</p> <p>Here is my code -</p> <pre><code>&lt;?php defined('ABSPATH') or exit; // TODO: Refactor tabs ?&gt; &lt;div id=&quot;myDIV&quot;&gt; &lt;nav class=&quot;bp-navs bp-subnavs no-ajax user-subnav&quot; id=&quot;subnav&quot; role=&quot;navigation&quot; aria-label=&quot;Sub Menu&quot;&gt; &lt;ul class=&quot;subnav&quot;&gt; &lt;li class=&quot;bp-personal-sub-tab current selected&quot;&gt; &lt;a href=&quot;&lt;?php echo site_url('settings/habit-settings/'); ?&gt;&quot; class=&quot;btn active&quot;&gt; Habit Setting &lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;bp-personal-sub-tab current&quot;&gt; &lt;a href=&quot;&lt;?php echo site_url('settings/team-settings/'); ?&gt;&quot; class=&quot;btn&quot;&gt; Team Setting &lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;/div&gt;&lt;!-- .item-list-tabs#subnav --&gt; &lt;!-- Add active class to the current list --&gt; &lt;style&gt; .btn { outline: none !important; cursor: pointer !important; } .active, .btn:hover { background-color: red !important; color: red; } &lt;/style&gt; &lt;script&gt; var header = document.getElementById(&quot;myDIV&quot;); var btns = header.getElementsByClassName(&quot;btn&quot;); for (var i = 0; i &lt; btns.length; i++) { btns[i].addEventListener(&quot;click&quot;, function() { var current = document.getElementsByClassName(&quot;active&quot;); current[0].className = current[0].className.replace(&quot; active&quot;, &quot;&quot;); this.className += &quot; active&quot;; }); } &lt;/script&gt; </code></pre> <p>I was trying to show active menu color through JS but my code doesn't work.</p>
[ { "answer_id": 74509209, "author": "Eli Porush", "author_id": 14598976, "author_profile": "https://Stackoverflow.com/users/14598976", "pm_score": 2, "selected": false, "text": "let myObs = this.FetchHttpData1().pipe(\n switchMap((values: {id: number}[]) => {\n forkJoin(values.map(v => FetchHttpItemProperty(v.id))).pipe(\n map(vals => {\n const results = values.map(val => {...val, ...vals.find(i => i.id === val.id)})\n return results;\n }),\n tap(vals => vals.forEach(v => this.storeSetSingle(v)))\n )\n })\n" }, { "answer_id": 74509721, "author": "Eddy Lin", "author_id": 19768317, "author_profile": "https://Stackoverflow.com/users/19768317", "pm_score": 3, "selected": false, "text": "const missingApi$ = (x: IMainModelType) => this.FetchHttpItemProperty(x.id).pipe(\n map(({ missingProperty }) => ({...x, missingProperty})),\n tap((val) => this.storeSetSingle(val)),\n);\n\nlet myObs = this.FetchHttpData1().pipe(switchMap((arrs) => \n forkJoin(arrs.map((x) => x.active ? missingApi$(x) : of(x)))\n));\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74508815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19807878/" ]
74,508,827
<p>I have a strange looking function that calls the plots based on the attributes. So, if a function exists in the class then select that. Then I am trying to call it, in this example I use <code>pyplot.arrow</code>, however, I cannot seem to unpack all the values. It should take four parameters, but I get the following error:</p> <blockquote> <p>ValueError: too many values to unpack (expected 2)</p> </blockquote> <p>I cannot recognise how I am passing too many values given I unpack with <code>*</code>, here is what I have tried:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt test_array = np.array([ [1, 2] , [5, 4] , [5, 2] , [1, 2] , [5, 2] , [1, 2]]) test_array = np.column_stack((test_array,[ [ 0 , 0 ] ]*test_array.shape[0])) test_split = np.split(test_array, 6) for b in test_split: b[ : , [ 0 , 1 , -2 , -1 ] ] = b[ : , [ -2 , -1 , 0 ,1] ] def plot(size: list,plType, *args, **kwargs): figs, axs = plt.subplots(size[0], size[1], figsize=(8,8)) xy = np.array(args) for A , ax in zip( xy , axs.flat ): X = np.hsplit( A , xy.shape[2] ) if isinstance(X, list): for ind , Z in enumerate(zip(*X)): ax.__getattribute__( plType )( *Z, **kwargs) plt.show() print(np.array(test_split).shape) plot([2, 3], 'arrow', *test_split) </code></pre>
[ { "answer_id": 74509209, "author": "Eli Porush", "author_id": 14598976, "author_profile": "https://Stackoverflow.com/users/14598976", "pm_score": 2, "selected": false, "text": "let myObs = this.FetchHttpData1().pipe(\n switchMap((values: {id: number}[]) => {\n forkJoin(values.map(v => FetchHttpItemProperty(v.id))).pipe(\n map(vals => {\n const results = values.map(val => {...val, ...vals.find(i => i.id === val.id)})\n return results;\n }),\n tap(vals => vals.forEach(v => this.storeSetSingle(v)))\n )\n })\n" }, { "answer_id": 74509721, "author": "Eddy Lin", "author_id": 19768317, "author_profile": "https://Stackoverflow.com/users/19768317", "pm_score": 3, "selected": false, "text": "const missingApi$ = (x: IMainModelType) => this.FetchHttpItemProperty(x.id).pipe(\n map(({ missingProperty }) => ({...x, missingProperty})),\n tap((val) => this.storeSetSingle(val)),\n);\n\nlet myObs = this.FetchHttpData1().pipe(switchMap((arrs) => \n forkJoin(arrs.map((x) => x.active ? missingApi$(x) : of(x)))\n));\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74508827", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18248287/" ]
74,508,841
<p>I may need some help here.</p> <p>The scenario is, let's say, I have a TCL script &quot;test.tcl&quot;, which contains something like below,</p> <pre><code>set condition true if {$condition==true} { puts &quot;Message1&quot; } elseif {$condition==false} { puts &quot;Message2&quot; } </code></pre> <p>Then I have another makefile to simply run this TCL script, in which,</p> <pre><code>runScript: tclsh test.tcl </code></pre> <p>When I run it with</p> <pre><code>make runScript </code></pre> <p>is there any way that variable &quot;<strong>condition</strong>&quot; inside TCL script can be somehow provided by Makefile, rather than writing inside TCL script itself?</p> <p>Any help would be grateful. Thank you!</p>
[ { "answer_id": 74509209, "author": "Eli Porush", "author_id": 14598976, "author_profile": "https://Stackoverflow.com/users/14598976", "pm_score": 2, "selected": false, "text": "let myObs = this.FetchHttpData1().pipe(\n switchMap((values: {id: number}[]) => {\n forkJoin(values.map(v => FetchHttpItemProperty(v.id))).pipe(\n map(vals => {\n const results = values.map(val => {...val, ...vals.find(i => i.id === val.id)})\n return results;\n }),\n tap(vals => vals.forEach(v => this.storeSetSingle(v)))\n )\n })\n" }, { "answer_id": 74509721, "author": "Eddy Lin", "author_id": 19768317, "author_profile": "https://Stackoverflow.com/users/19768317", "pm_score": 3, "selected": false, "text": "const missingApi$ = (x: IMainModelType) => this.FetchHttpItemProperty(x.id).pipe(\n map(({ missingProperty }) => ({...x, missingProperty})),\n tap((val) => this.storeSetSingle(val)),\n);\n\nlet myObs = this.FetchHttpData1().pipe(switchMap((arrs) => \n forkJoin(arrs.map((x) => x.active ? missingApi$(x) : of(x)))\n));\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74508841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8013696/" ]
74,508,859
<p>I have 250 rows of data, it starts january 2002 and ends septemper 2022 and interwal per row is one row/one month of the year.</p> <p><a href="https://i.stack.imgur.com/OyHbM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OyHbM.png" alt="enter image description here" /></a></p> <p>Now i want to plot it but it takes all 250 rows and plot it and i only want like one year shown per tick</p> <p>The y axis is float and x axis is string</p> <p>I have saw that you have to label them manualy but what if i have like realy big data? There must be some efficient way.</p> <p>i have tried something like this:</p> <pre><code>import matplotlib.pyplot as plt X = df_polt['Päivä'] y = df_polt['Diesel'] fig, ax = plt.subplots(1,1,figsize=(15, 10)) ax.plot(X, y) </code></pre> <p>I want that X axis is like 10 ticks</p> <p><a href="https://i.stack.imgur.com/JUxqn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JUxqn.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74509209, "author": "Eli Porush", "author_id": 14598976, "author_profile": "https://Stackoverflow.com/users/14598976", "pm_score": 2, "selected": false, "text": "let myObs = this.FetchHttpData1().pipe(\n switchMap((values: {id: number}[]) => {\n forkJoin(values.map(v => FetchHttpItemProperty(v.id))).pipe(\n map(vals => {\n const results = values.map(val => {...val, ...vals.find(i => i.id === val.id)})\n return results;\n }),\n tap(vals => vals.forEach(v => this.storeSetSingle(v)))\n )\n })\n" }, { "answer_id": 74509721, "author": "Eddy Lin", "author_id": 19768317, "author_profile": "https://Stackoverflow.com/users/19768317", "pm_score": 3, "selected": false, "text": "const missingApi$ = (x: IMainModelType) => this.FetchHttpItemProperty(x.id).pipe(\n map(({ missingProperty }) => ({...x, missingProperty})),\n tap((val) => this.storeSetSingle(val)),\n);\n\nlet myObs = this.FetchHttpData1().pipe(switchMap((arrs) => \n forkJoin(arrs.map((x) => x.active ? missingApi$(x) : of(x)))\n));\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74508859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20555166/" ]
74,508,861
<p>I'm looking to transform some data in Python.</p> <p>Originally, in column 1 there are various identifiers (A to E in this example) associated with towns in column 2. There is a separate row for each identifier and town association. There can be any number of identifier to town associations.</p> <p>I'd like to end up with ONE row per identifier and with all the associated towns going horizontally separated by commas.</p> <p>Tried using long to wide but having difficulty in doing the above, appreciate any suggestions.</p> <p><img src="https://iili.io/HHn1KKl.png" alt="Text" /></p> <p><a href="https://freeimage.host/i/HHn1OOX" rel="nofollow noreferrer"><img src="https://iili.io/HHn1OOX.md.png" alt="HHn1OOX.md.png" /></a></p> <p>Thank you</p>
[ { "answer_id": 74509209, "author": "Eli Porush", "author_id": 14598976, "author_profile": "https://Stackoverflow.com/users/14598976", "pm_score": 2, "selected": false, "text": "let myObs = this.FetchHttpData1().pipe(\n switchMap((values: {id: number}[]) => {\n forkJoin(values.map(v => FetchHttpItemProperty(v.id))).pipe(\n map(vals => {\n const results = values.map(val => {...val, ...vals.find(i => i.id === val.id)})\n return results;\n }),\n tap(vals => vals.forEach(v => this.storeSetSingle(v)))\n )\n })\n" }, { "answer_id": 74509721, "author": "Eddy Lin", "author_id": 19768317, "author_profile": "https://Stackoverflow.com/users/19768317", "pm_score": 3, "selected": false, "text": "const missingApi$ = (x: IMainModelType) => this.FetchHttpItemProperty(x.id).pipe(\n map(({ missingProperty }) => ({...x, missingProperty})),\n tap((val) => this.storeSetSingle(val)),\n);\n\nlet myObs = this.FetchHttpData1().pipe(switchMap((arrs) => \n forkJoin(arrs.map((x) => x.active ? missingApi$(x) : of(x)))\n));\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74508861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13845905/" ]
74,508,862
<p>I am new in R, so my question could seem very trivial for someone, but I need a solution. I have a data frame:</p> <pre><code>`structure(list(Time = c(0, 0, 0), Node = 1:3, Depth = c(0, -10, -20), Head = c(-1000, -1000, -1000), Moisture = c(0.166, 0.166, 0.166), HeadF = c(-1000, -1000, -1000), MoistureF = c(0.004983, 0.004983, 0.004983), Flux = c(-0.00133, -0.00133, -0.00133), FluxF = c(-0.00122, -0.00122, -0.00122), Sink = c(0, 0, 0 ), Transf = c(0, 0, 0), TranS = c(0, 0, 0), Temp = c(20, 20, 20), ConcF = c(0, 0, 0), ConcM = c(0, 0, 0)), row.names = c(NA, 3L), class = &quot;data.frame&quot;)`. </code></pre> <p>I am able to plot a single TranS vs Time <a href="https://i.stack.imgur.com/VuN1h.png" rel="nofollow noreferrer">Single plot</a>, where color = Transf (using scale_color_viridis). I want to create plots with a filtered data for( depth = -20, depth = -40 , -60, -80 and -100) Note: that title also have to be changed according to a depth value. These plots then I want to put next to each other using facet_grid.</p> <p>I have tried in a such way:</p> <pre><code>plot_d20 &lt;-plot_node %&gt;% filter(plot_node$Depth == -20) plot_d40 &lt;-plot_node %&gt;% filter(plot_node$Depth == -40) plot_d60 &lt;-plot_node %&gt;% filter(plot_node$Depth == -60) plot_d80 &lt;-plot_node %&gt;% filter(plot_node$Depth == -80) plot_d100 &lt;-plot_node %&gt;% filter(plot_node$Depth == -100) depth_plot &lt;- c(plot_d20,plot_d40,plot_d60,plot_d80,plot_d100) for (p in depth_plot){ ggpS&lt;-ggplot(p, aes(Time, TranS, color=Transf) ) + geom_point(alpha = 1)+ scale_color_viridis(option = &quot;D&quot;)+ scale_x_continuous(limits = c(0,1400), breaks = seq(0,1400,200))+ ggtitle('Solute Mass Transfer for depth = 20mm') ggpS } </code></pre> <p>But it doesn't work. R says: <code>data</code> must be a data frame, or another object coercible by <code>fortify()</code>, not a numeric vector. And I don't know how to make my title dynamic and combine it with facet_grid or on a single plot, but in this case, I will face difficulty to distinguish the lines and assigning the legend to the plot by color, because color already represents another variable. What is the possible way to accomplish that?</p>
[ { "answer_id": 74509297, "author": "M.Viking", "author_id": 10276092, "author_profile": "https://Stackoverflow.com/users/10276092", "pm_score": 2, "selected": false, "text": "facet_grid data.frame cowplot filter facet_wrap library(tidyverse)\niris %>% \n filter(Sepal.Length %in% c(6.4,5.7,6.7,5.1,6.3,5)) %>% ### Your values here\n ggplot(aes(Petal.Length, Petal.Width, color=Species)) + \n geom_point(alpha = 1) +\n scale_color_viridis_d()+ #(option = \"D\") + ### New function name\n #scale_x_continuous(limits = c(0,1400), breaks = seq(0,1400,200))+\n facet_wrap(\"Sepal.Length\") +\n # facet_grid(\"Sepal.Length\") + ### Alternative Layout\n ggtitle('Sepal Length Range')\n" }, { "answer_id": 74509340, "author": "zephryl", "author_id": 17303805, "author_profile": "https://Stackoverflow.com/users/17303805", "pm_score": 0, "selected": false, "text": "facet_wrap() strip.text theme() library(dplyr)\nlibrary(ggplot2)\n\nplot_node %>% \n mutate(\n facet = paste0(\"Solute Mass Transfer for Depth = \", abs(Depth), \"mm\")\n ) %>% \n ggplot(aes(Time, TranS, color=Transf)) + \n geom_point(alpha = 1) +\n scale_color_viridis_c(option = \"D\") +\n scale_x_continuous(limits = c(0, 1400), breaks = seq(0, 1400, 200)) +\n facet_wrap(vars(facet), ncol = 2, scales = \"free\") +\n theme_minimal() + \n theme(strip.text = element_text(size = 12, face = \"bold\"))\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74508862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15752966/" ]
74,508,889
<p>I have the next code in my react js application:</p> <pre><code>interface Input { name: string; type?: 'email' | 'text'; } const Input = ({type}: Input) =&gt; { return &lt;input type={type}/&gt; } </code></pre> <p>The component can receive only type <code>email</code> and <code>text</code>. If the user will add as a prop <code>number</code> then the compiler will throw an error in compilation time. EX:</p> <pre><code>&lt;Input type=&quot;number&quot;/&gt; </code></pre> <pre><code>Type '&quot;password&quot;' is not assignable to type '&quot;text&quot; | &quot;email&quot;. </code></pre> <p>, but in the same time we can anyway to type:</p> <pre><code>&lt;Input type=&quot;number&quot;/&gt; </code></pre> <p>even with this error and to suppress the error. <br> <strong>Question</strong>: Should i restrict the <code>type</code> props only using typescript like in my case or should i use javascript to exclude the situation when the <code>type</code> will be <code>number</code>?</p>
[ { "answer_id": 74508907, "author": "Sachila Ranawaka", "author_id": 6428638, "author_profile": "https://Stackoverflow.com/users/6428638", "pm_score": 0, "selected": false, "text": "type?: 'email' | 'text' | 'password' | 'number';\n" }, { "answer_id": 74509170, "author": "Jeff Bowman", "author_id": 1426891, "author_profile": "https://Stackoverflow.com/users/1426891", "pm_score": 1, "selected": false, "text": "any value type" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74508889", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12540500/" ]
74,508,892
<p>In the explorer of VS Code I want to have the gitignored files grey.</p> <p>I managed to add <code>&quot;gitDecoration.ignoredResourceForeground&quot;:&quot;#CCCCCC&quot;</code>, however I now have various files and folders where there are other decorations and it looks like <code>explorer.decorations.colors</code> takes precedence over this. This mechanism now destroys the coloring of the ignored resources again as it looks like this rule is checked later.</p> <p>How can I fix this and have the gitignored rule applied no matter what happens otherwise?</p> <p>This is for:</p> <p><strong>VSCode:</strong> Version: 1.73.1 Release: 22314 Commit: 14f2d26367b7e8f03ff2352516ba27d6302dd7b1 Date: 2022-11-10T18:37:51.314Z (2 wks ago) Electron: 19.0.17 Chromium: 102.0.5005.167 Node.js: 16.14.2 V8: 10.2.154.15-electron.0 OS: Darwin x64 19.6.0 Sandboxed: No</p> <p><strong>MacOS:</strong> Catalina 10.15.7</p> <p><strong>Git:</strong> 2.38.1</p> <p><a href="https://i.stack.imgur.com/AyEi5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AyEi5.png" alt="Screenshot" /></a></p> <p>The screenshot shows a situation where <code>chamaeleon/</code> is part of <code>.gitignore</code>. All files nicely are greyed out with the exception of <code>ChameleonTemplate.php</code> which contains a PHP error, as well as <code>src</code>which contains a file containing an error and <code>Components</code> which contains another file with an editor decoration due to a type problem in PHP.</p> <p><strong>Clarification:</strong> My question is not about files which are <em>only</em> gitignored (they show uo correctly) but about files which are gitognored <strong>and</strong> have a further editor decoration (such as a syntax error). If these two decorations apply <em>both</em> then the question is <em>which one takes precedence</em>. <strong>That</strong> is the problem here.</p> <p>My question is rather not a bug (as in &quot;does not work as expected&quot;) but a conceptual one. If we have two different reasons for setting foreground color, and both reasons apply, which color is chosen?</p> <p>A workaround would be if we were able to set other attributes such as underline, strike-through, background-color or font type and not only foreground-color, because such attributes could be combined. Foreground-color and foreground-color cannot be combined but needs a precedence rule.</p>
[ { "answer_id": 74623388, "author": "Keshav V.", "author_id": 18131236, "author_profile": "https://Stackoverflow.com/users/18131236", "pm_score": 0, "selected": false, "text": "fort-bishop.exe .gitignore" }, { "answer_id": 74626965, "author": "Alexander Farkas", "author_id": 14392430, "author_profile": "https://Stackoverflow.com/users/14392430", "pm_score": 0, "selected": false, "text": "workbench.colorCustomizations settings.json \"workbench.colorCustomizations\": {\n \"gitDecoration.ignoredResourceForeground\": \"#ff0000\"\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74508892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9363857/" ]
74,508,900
<p>This is my first time using NextJS and I'm trying to load 3 random dog breed images onto the app's webpage using the Dog.ceo API. I am able to see the three random dogs in the console from the console.log(data) line, but the images aren't being displayed. In this API there are only two properties - message (containing the image URL) and status (displaying 'success'). Any help in how to get these images to display? Also to note, I'm not using Typescript for this.</p> <pre><code>const defaultEndpoint = &quot;https://dog.ceo/api/breeds/image/random/3&quot;; export async function getServerSideProps() { const res = await fetch(defaultEndpoint); const data = await res.json(); return { props: { data }, }; } export default function Home({ data }) { console.log(&quot;data&quot;, data); const { results = [] } = data; return ( &lt;div className={styles.container}&gt; &lt;Head&gt; &lt;title&gt;Dog Breed App&lt;/title&gt; &lt;meta name=&quot;description&quot; content=&quot;Generated by create next app&quot; /&gt; &lt;link rel=&quot;icon&quot; href=&quot;/favicon.ico&quot; /&gt; &lt;/Head&gt; &lt;main&gt; &lt;div className=&quot;grid&quot;&gt; {results.map((result) =&gt; { const { message } = result; return ( &lt;div key={message}&gt; &lt;img src={message} alt=&quot;&quot;&gt;&lt;/img&gt; &lt;/div&gt; ); })} &lt;/div&gt; &lt;/main&gt; &lt;/div&gt; ); } </code></pre> <p>I tried using &quot;message&quot; from the &quot;data&quot; variable to get the url for the image. But that isn't working.</p>
[ { "answer_id": 74509155, "author": "Harsh Vishwakarma", "author_id": 4049649, "author_profile": "https://Stackoverflow.com/users/4049649", "pm_score": 0, "selected": false, "text": "useEffect dogs const defaultEndpoint = \"https://dog.ceo/api/breeds/image/random/3\";\nimport React, { useState, useEffect } from 'react'\n\n\nexport default function Home({ data }) {\n const [dogs, setDogs] = useState([]);\n\n export async function getServerSideProps() {\n const res = await fetch(defaultEndpoint);\n const data = await res.json();\n \n console.log(\"data\", data);\n setDogs(data)\n }\n useEffect(() => {\n getServerSideProps()\n }, [])\n \n return (\n <div className={styles.container}>\n <Head>\n <title>Dog Breed App</title>\n <meta name=\"description\" content=\"Generated by create next app\" />\n <link rel=\"icon\" href=\"/favicon.ico\" />\n </Head>\n\n <main>\n <div className=\"grid\">\n {dogs.map((result) => {\n const { message } = result;\n\n return (\n <div key={message}>\n <img src={message} alt=\"\"></img>\n </div>\n );\n })}\n </div>\n </main>\n </div>\n );\n} [dependencies] useEffect useEffect(() => {\n //\n \n return () => {\n // \n }\n }, [dependencies])" }, { "answer_id": 74510115, "author": "jme11", "author_id": 3577849, "author_profile": "https://Stackoverflow.com/users/3577849", "pm_score": 2, "selected": true, "text": "const { results = [] } = data; results message const { message = [] } = data props.data export async function getServerSideProps() {\n const res = await fetch('https://dog.ceo/api/breeds/image/random/3');\n\n // Destructure the response object here and \n // rename the 'message' property as 'data'\n const { message: data } = await res.json();\n\n return {\n props: { data },\n };\n}\n\n// Destructure the props object to have access to the \n// property named data:\nexport default function Home({ data }) {\n return (\n <main>\n <div className=\"grid\">\n {data.map((img) => (\n <div key={img}>\n <img src={img} alt=\"dog\"></img>\n </div>\n ))}\n </div>\n </main>\n );\n}\n\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74508900", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19815558/" ]
74,508,902
<p>This question is slightly different from others since I need to get the whole documents and not just specific fields.</p> <p>I need to filter documents(all of the document, not just specific fields), according to the last elements value of a nested array. (<code>doc.array[i].innerArray[innerArray.length - 1].desiredField</code>)</p> <p>Documents are looking like this:</p> <pre><code>[ { &quot;_id&quot;: 0, &quot;matches&quot;: [ { &quot;name&quot;: &quot;match 1&quot;, &quot;ids&quot;: [ { &quot;innerName&quot;: &quot;1234&quot; }, { &quot;innerName&quot;: &quot;3&quot; } ] } ] }, { &quot;_id&quot;: 1, &quot;matches&quot;: [ { &quot;name&quot;: &quot;match 5&quot;, &quot;ids&quot;: [ { &quot;innerName&quot;: &quot;123&quot; }, { &quot;innerName&quot;: &quot;1&quot; } ] }, { &quot;name&quot;: &quot;match 5&quot;, &quot;ids&quot;: [ { &quot;innerName&quot;: &quot;1&quot; }, { &quot;innerName&quot;: &quot;1234&quot; }, ] }, ] } ] </code></pre> <p>So if we filter according to innerName = '1234', this is the result:</p> <pre><code>{ &quot;_id&quot;: 1, &quot;matches&quot;: [ { &quot;name&quot;: &quot;match 5&quot;, &quot;ids&quot;: [ { &quot;innerName&quot;: &quot;123&quot; }, { &quot;innerName&quot;: &quot;1&quot; } ] }, { &quot;name&quot;: &quot;match 5&quot;, &quot;ids&quot;: [ { &quot;innerName&quot;: &quot;1&quot; }, { &quot;innerName&quot;: &quot;1234&quot; }, ] } </code></pre>
[ { "answer_id": 74509155, "author": "Harsh Vishwakarma", "author_id": 4049649, "author_profile": "https://Stackoverflow.com/users/4049649", "pm_score": 0, "selected": false, "text": "useEffect dogs const defaultEndpoint = \"https://dog.ceo/api/breeds/image/random/3\";\nimport React, { useState, useEffect } from 'react'\n\n\nexport default function Home({ data }) {\n const [dogs, setDogs] = useState([]);\n\n export async function getServerSideProps() {\n const res = await fetch(defaultEndpoint);\n const data = await res.json();\n \n console.log(\"data\", data);\n setDogs(data)\n }\n useEffect(() => {\n getServerSideProps()\n }, [])\n \n return (\n <div className={styles.container}>\n <Head>\n <title>Dog Breed App</title>\n <meta name=\"description\" content=\"Generated by create next app\" />\n <link rel=\"icon\" href=\"/favicon.ico\" />\n </Head>\n\n <main>\n <div className=\"grid\">\n {dogs.map((result) => {\n const { message } = result;\n\n return (\n <div key={message}>\n <img src={message} alt=\"\"></img>\n </div>\n );\n })}\n </div>\n </main>\n </div>\n );\n} [dependencies] useEffect useEffect(() => {\n //\n \n return () => {\n // \n }\n }, [dependencies])" }, { "answer_id": 74510115, "author": "jme11", "author_id": 3577849, "author_profile": "https://Stackoverflow.com/users/3577849", "pm_score": 2, "selected": true, "text": "const { results = [] } = data; results message const { message = [] } = data props.data export async function getServerSideProps() {\n const res = await fetch('https://dog.ceo/api/breeds/image/random/3');\n\n // Destructure the response object here and \n // rename the 'message' property as 'data'\n const { message: data } = await res.json();\n\n return {\n props: { data },\n };\n}\n\n// Destructure the props object to have access to the \n// property named data:\nexport default function Home({ data }) {\n return (\n <main>\n <div className=\"grid\">\n {data.map((img) => (\n <div key={img}>\n <img src={img} alt=\"dog\"></img>\n </div>\n ))}\n </div>\n </main>\n );\n}\n\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74508902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13821808/" ]
74,508,926
<p>I am using Jetpack Compose and noticed that the preview is not shown. I read articles like <a href="https://stackoverflow.com/questions/65837989/jetpack-compose-preview-not-showing">this</a>, but it seems my problem has a different root cause. Even I added defaults to all parameters in the compose function like this:</p> <pre><code>@OptIn(ExperimentalLifecycleComposeApi::class) @Composable @ExperimentalFoundationApi @Preview fun VolumeSettingsScreen( speech: SpeechHelper = SpeechHelper(), // my class that converts text to speech viewModel: VolumeSettingsViewModel = hiltViewModel(), // using Hilt to inject ViewModels navController: NavHostController = rememberNavController() // Compose Navigation component ) { MyAppheme { Box( ... ) } } </code></pre> <p>When I rollbacked some changes I realized that the <code>@Preview</code> does not support the <code>viewModels</code> regardless of whether they are injected with Hilt or not.</p> <p>Any Idea how this could be fixed?</p>
[ { "answer_id": 74509019, "author": "MeLean", "author_id": 3626353, "author_profile": "https://Stackoverflow.com/users/3626353", "pm_score": 2, "selected": false, "text": "@OptIn(ExperimentalLifecycleComposeApi::class)\n@Composable\n@ExperimentalFoundationApi\n@Preview\nfun VolumeSettingsScreen(\n modifier: Modifier = Modifier,\n speechCallbacks: SpeechCallbacks = SpeechCallbacks(),\n navigationCallbacks: NavigationCallbacks = NavigationCallbacks(),\n viewModelCallbacks: VolumeSettingsScreenCallbacks = VolumeSettingsScreenCallbacks()\n) {\n MyAppheme {\n Box(\n ...\n )\n }\n}\n data class VolumeSettingsScreenCallbacks(\n val uiState: Flow<BaseUiState?> = flowOf(null),\n val onValueUpSelected: () -> Boolean = { false },\n val onValueDownSelected: () -> Boolean = { false },\n val doOnBoarding: (String) -> Unit = {},\n val onScreenCloseRequest: (String) -> Unit = {} \n)\n @HiltViewModel\nclass VolumeSettingsViewModel @Inject constructor() : BaseViewModel() {\n\n fun createViewModelCallbacks(): VolumeSettingsScreenCallbacks =\n VolumeSettingsScreenCallbacks(\n uiState = uiState,\n onValueUpSelected = ::onValueUpSelected,\n onValueDownSelected = ::onValueDownSelected,\n doOnBoarding = ::doOnBoarding,\n onScreenCloseRequest = ::onScreenCloseRequest\n )\n\n ....\n}\n @Composable\n @ExperimentalFoundationApi\n fun MyAppNavHost(\n speech: SpeechHelper,\n navController: NavHostController,\n startDestination: String = HOME.route,\n ): Unit = NavHost(\n navController = navController,\n startDestination = startDestination,\n ) {\n ...\n \n composable(route = Destination.VOLUME_SETTINGS.route) {\n hiltViewModel<VolumeSettingsViewModel>().run {\n VolumeSettingsScreen(\n modifier = keyEventModifier,\n speechCallbacks = speech.createCallback() // my function,\n navigation callbacks = navController.createCallbacks(), //it is mine extension function \n viewModelCallbacks = createViewModelCallbacks()\n )\n }\n }\n \n ...\n }\n" }, { "answer_id": 74509401, "author": "z.y", "author_id": 19023745, "author_profile": "https://Stackoverflow.com/users/19023745", "pm_score": 3, "selected": false, "text": "Screen Content // data class\ndata class AccountData(val accountInfo: Any?)\n\n// composable \"Screen\", where you define contexts, viewModels, hoisted states, etc\n@Composable\nfun AccountScreen(viewModel: AccountViewModel = hiltViewModel()) {\n\n val accountData = viewModel.accountDataState.collectAsState()\n\n AccountContent(accountData = accountData) {\n // click callback\n }\n}\n\n//your actual composable that hosts your child composable widget/components\n@Composable\nfun AccountContent(\n accountData: AccountData,\n clickCallback: () ->\n) {\n ...\n}\n Content @Preview\n@Composable\nfun AccountContentPreview() {\n\n // create some mock AccountData\n val mockData = AccountData(…)\n AccountContent(accountData = mockData) {\n // I'm not expecting some actual ViewModel calls here, instead I'll just manipulate the mock data\n }\n}\n speech: SpeechHelper = SpeechHelper()\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74508926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3626353/" ]
74,508,954
<p>I've two file for my app, and in my second one <code>page_one.py</code> I can't use properly the anchor method. The label 'left' and 'right' are always positioned in the middle of the screen and not on the side</p> <pre><code># main.py import tkinter as tk from page_one import PageOne class Main(tk.Frame): def __init__(self, parent, *args, **kwargs): tk.Frame.__init__(self, parent, *args, **kwargs) self.page_one = PageOne(self) self.page_one.pack(expand='True') if __name__ == &quot;__main__&quot;: root = tk.Tk() main = Main(root) root.attributes(&quot;-fullscreen&quot;, True) main.pack(side=&quot;top&quot;, fill=&quot;both&quot;, expand=True) root.mainloop() </code></pre> <pre><code># page_one.py import tkinter as tk class PageOne(tk.Frame): def __init__(self, parent, *args, **kwargs): tk.Frame.__init__(self, parent, *args, **kwargs) self.one_label = tk.Label(self, text='LEFT') self.one_label.pack(padx=(20,0), side='left', anchor='w') self.two_label = tk.Label(self, text='RIGHT') self.two_label.pack(padx=(0,20), side='right', anchor='e') if __name__ == &quot;__main__&quot;: root = tk.Tk() PageOne(root).pack(side=&quot;top&quot;, fill=&quot;both&quot;, expand=True) root.mainloop() </code></pre> <p>How can I make the <code>anchor</code> option works?</p>
[ { "answer_id": 74509057, "author": "Tranbi", "author_id": 13525512, "author_profile": "https://Stackoverflow.com/users/13525512", "pm_score": 3, "selected": true, "text": "PageOne Main fill=\"both\" pack import tkinter as tk\n\nclass PageOne(tk.Frame):\n def __init__(self, parent, *args, **kwargs):\n super().__init__(parent, *args, **kwargs) \n \n self.one_label = tk.Label(self, text='LEFT')\n self.one_label.pack(padx=(20,0), side='left', anchor='w') \n\n self.two_label = tk.Label(self, text='RIGHT')\n self.two_label.pack(padx=(0,20), side='right', anchor='e') \n \n\nclass Main(tk.Frame):\n def __init__(self, parent, *args, **kwargs):\n super().__init__(parent, *args, **kwargs)\n\n self.page_one = PageOne(self)\n self.page_one.pack(expand='True', fill=\"both\")\n\nif __name__ == \"__main__\":\n root = tk.Tk()\n main = Main(root)\n #root.attributes(\"-fullscreen\", True)\n root.geometry(\"1280x720\")\n main.pack(side=\"top\", fill=\"both\", expand=True)\n root.mainloop()\n super() init self" }, { "answer_id": 74509065, "author": "RandomCoder59", "author_id": 16765869, "author_profile": "https://Stackoverflow.com/users/16765869", "pm_score": 0, "selected": false, "text": "fill=\"both\" PageOne main.py # main.py\nimport tkinter as tk\nfrom page_one import PageOne\n\nclass Main(tk.Frame):\n def __init__(self, parent, *args, **kwargs):\n tk.Frame.__init__(self, parent, *args, **kwargs)\n\n self.page_one = PageOne(self)\n self.page_one.pack(fill=\"both\", expand='True')\n\nif __name__ == \"__main__\":\n root = tk.Tk()\n main = Main(root)\n root.attributes(\"-fullscreen\", True)\n main.pack(side=\"top\", fill=\"both\", expand=True)\n root.mainloop()\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74508954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16545560/" ]
74,509,010
<p>What is the best, most secure and professional way to store a user's jwt token after logging into React?</p> <p>I see many people saying that using localStorage is a good way.</p> <p>For example:</p> <pre><code>localStorage.setItem(&quot;token&quot;, &quot;ey.......&quot;) </code></pre> <p>Others say to use a library like Redux or others.</p> <p>Could someone advise me?</p> <p>Thanks</p>
[ { "answer_id": 74509057, "author": "Tranbi", "author_id": 13525512, "author_profile": "https://Stackoverflow.com/users/13525512", "pm_score": 3, "selected": true, "text": "PageOne Main fill=\"both\" pack import tkinter as tk\n\nclass PageOne(tk.Frame):\n def __init__(self, parent, *args, **kwargs):\n super().__init__(parent, *args, **kwargs) \n \n self.one_label = tk.Label(self, text='LEFT')\n self.one_label.pack(padx=(20,0), side='left', anchor='w') \n\n self.two_label = tk.Label(self, text='RIGHT')\n self.two_label.pack(padx=(0,20), side='right', anchor='e') \n \n\nclass Main(tk.Frame):\n def __init__(self, parent, *args, **kwargs):\n super().__init__(parent, *args, **kwargs)\n\n self.page_one = PageOne(self)\n self.page_one.pack(expand='True', fill=\"both\")\n\nif __name__ == \"__main__\":\n root = tk.Tk()\n main = Main(root)\n #root.attributes(\"-fullscreen\", True)\n root.geometry(\"1280x720\")\n main.pack(side=\"top\", fill=\"both\", expand=True)\n root.mainloop()\n super() init self" }, { "answer_id": 74509065, "author": "RandomCoder59", "author_id": 16765869, "author_profile": "https://Stackoverflow.com/users/16765869", "pm_score": 0, "selected": false, "text": "fill=\"both\" PageOne main.py # main.py\nimport tkinter as tk\nfrom page_one import PageOne\n\nclass Main(tk.Frame):\n def __init__(self, parent, *args, **kwargs):\n tk.Frame.__init__(self, parent, *args, **kwargs)\n\n self.page_one = PageOne(self)\n self.page_one.pack(fill=\"both\", expand='True')\n\nif __name__ == \"__main__\":\n root = tk.Tk()\n main = Main(root)\n root.attributes(\"-fullscreen\", True)\n main.pack(side=\"top\", fill=\"both\", expand=True)\n root.mainloop()\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20555329/" ]
74,509,030
<p>I'm in the final stages of developing a basic React instant chat messaging using Socket.io &amp; React-Router to teach myself some core concepts.</p> <p>I've been using this project on GitHub as a reference: <a href="https://github.com/simpletut/react-real-time-chat-app" rel="nofollow noreferrer">https://github.com/simpletut/react-real-time-chat-app</a></p> <p>with a live version here: <a href="https://react-chatapp-frontend.herokuapp.com/" rel="nofollow noreferrer">https://react-chatapp-frontend.herokuapp.com/</a></p> <p>I'm using React-Router to redirect the user from the join page (where they can choose their username and room, which is then added to the URL as variables) to the chat page.</p> <p>ie. a user joining 'room1' with the username 'john' will be redirected to: http://localhost:3000/chat/room1/john</p> <pre class="lang-js prettyprint-override"><code>function App() { return ( &lt;div className=&quot;App&quot;&gt; &lt;Router&gt; &lt;Routes&gt; &lt;Route path=&quot;/chat/:room/:name&quot; element={&lt;Chat /&gt;} /&gt; &lt;Route path=&quot;/&quot; element={&lt;Join /&gt;} /&gt; &lt;/Routes&gt; &lt;/Router&gt; &lt;/div&gt; ); } </code></pre> <p>However, currently there is nothing stopping a user from entering a chat room without having been redirected from the join page. This also means users can 'create' rooms, just by entering the a URL. I would like the user to be redirected to the join page or root, or just not have access to a chat room without having been redirected there first.</p> <p>In my chat page, I'm using <code>useParams()</code> to get the route parameters to then join the room.</p> <pre class="lang-js prettyprint-override"><code> let { name, room } = useParams(); const [currentUser, updateUser] = useState(name); const [currentRoom, updateCurrentroom] = useState(room); const [users, updateUsers] = useState([]); const [currentMessage, updateCurrentMessage] = useState(''); const formRef = useRef(null); useEffect(() =&gt; { socket.on(&quot;receive_message&quot;, (data) =&gt; { addMessage(prevMessages =&gt; { return [...prevMessages, { username: data.username, time: new Date(), message: data.message }] }) }); socket.emit(&quot;join_room&quot;, {username: currentUser, room: room}, (err) =&gt; { if (err){ console.log(err); } }); </code></pre> <p>I've looked over the reference code several times now and just can't quite figure out what they've done differently that's given them this verification. Does anyone know how best to implement this?</p>
[ { "answer_id": 74509057, "author": "Tranbi", "author_id": 13525512, "author_profile": "https://Stackoverflow.com/users/13525512", "pm_score": 3, "selected": true, "text": "PageOne Main fill=\"both\" pack import tkinter as tk\n\nclass PageOne(tk.Frame):\n def __init__(self, parent, *args, **kwargs):\n super().__init__(parent, *args, **kwargs) \n \n self.one_label = tk.Label(self, text='LEFT')\n self.one_label.pack(padx=(20,0), side='left', anchor='w') \n\n self.two_label = tk.Label(self, text='RIGHT')\n self.two_label.pack(padx=(0,20), side='right', anchor='e') \n \n\nclass Main(tk.Frame):\n def __init__(self, parent, *args, **kwargs):\n super().__init__(parent, *args, **kwargs)\n\n self.page_one = PageOne(self)\n self.page_one.pack(expand='True', fill=\"both\")\n\nif __name__ == \"__main__\":\n root = tk.Tk()\n main = Main(root)\n #root.attributes(\"-fullscreen\", True)\n root.geometry(\"1280x720\")\n main.pack(side=\"top\", fill=\"both\", expand=True)\n root.mainloop()\n super() init self" }, { "answer_id": 74509065, "author": "RandomCoder59", "author_id": 16765869, "author_profile": "https://Stackoverflow.com/users/16765869", "pm_score": 0, "selected": false, "text": "fill=\"both\" PageOne main.py # main.py\nimport tkinter as tk\nfrom page_one import PageOne\n\nclass Main(tk.Frame):\n def __init__(self, parent, *args, **kwargs):\n tk.Frame.__init__(self, parent, *args, **kwargs)\n\n self.page_one = PageOne(self)\n self.page_one.pack(fill=\"both\", expand='True')\n\nif __name__ == \"__main__\":\n root = tk.Tk()\n main = Main(root)\n root.attributes(\"-fullscreen\", True)\n main.pack(side=\"top\", fill=\"both\", expand=True)\n root.mainloop()\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16079218/" ]
74,509,058
<p>So i have an array of objects named: <code>tokens</code>. Each object from this array has this format: <code>{tokenName: string}</code>. I want to test if each element from this array has the exact same format or else throw an error.</p> <p>I have tried this:</p> <pre><code>for (let i = 0; i &lt; tokens.length; i++) { if ( typeof tokens[i].tokenName === &quot;string&quot; &amp;&amp; tokens[i].hasOwnProperty(&quot;tokenName&quot;) ) { // do stuff } else { throw new Error(&quot;Invalid array format&quot;); } </code></pre> <p>But it won't pass the test.</p>
[ { "answer_id": 74509057, "author": "Tranbi", "author_id": 13525512, "author_profile": "https://Stackoverflow.com/users/13525512", "pm_score": 3, "selected": true, "text": "PageOne Main fill=\"both\" pack import tkinter as tk\n\nclass PageOne(tk.Frame):\n def __init__(self, parent, *args, **kwargs):\n super().__init__(parent, *args, **kwargs) \n \n self.one_label = tk.Label(self, text='LEFT')\n self.one_label.pack(padx=(20,0), side='left', anchor='w') \n\n self.two_label = tk.Label(self, text='RIGHT')\n self.two_label.pack(padx=(0,20), side='right', anchor='e') \n \n\nclass Main(tk.Frame):\n def __init__(self, parent, *args, **kwargs):\n super().__init__(parent, *args, **kwargs)\n\n self.page_one = PageOne(self)\n self.page_one.pack(expand='True', fill=\"both\")\n\nif __name__ == \"__main__\":\n root = tk.Tk()\n main = Main(root)\n #root.attributes(\"-fullscreen\", True)\n root.geometry(\"1280x720\")\n main.pack(side=\"top\", fill=\"both\", expand=True)\n root.mainloop()\n super() init self" }, { "answer_id": 74509065, "author": "RandomCoder59", "author_id": 16765869, "author_profile": "https://Stackoverflow.com/users/16765869", "pm_score": 0, "selected": false, "text": "fill=\"both\" PageOne main.py # main.py\nimport tkinter as tk\nfrom page_one import PageOne\n\nclass Main(tk.Frame):\n def __init__(self, parent, *args, **kwargs):\n tk.Frame.__init__(self, parent, *args, **kwargs)\n\n self.page_one = PageOne(self)\n self.page_one.pack(fill=\"both\", expand='True')\n\nif __name__ == \"__main__\":\n root = tk.Tk()\n main = Main(root)\n root.attributes(\"-fullscreen\", True)\n main.pack(side=\"top\", fill=\"both\", expand=True)\n root.mainloop()\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16932373/" ]
74,509,063
<p>Trying to start Storybook in a NX monorepo, but getting this error when trying these commands:</p> <p><code>nx run projectName:storybook</code> <code>nx storybook projectName</code> :</p> <pre><code>9% setup compilation SourceMapDevToolPlugin C:\Users\userName\Documents\Git\bft3\node_modules\@angular-devkit\build-angular\node_modules\webpack\lib\javascript\JavascriptModulesPlugin.js:143 throw new TypeError( ^ TypeError: The 'compilation' argument must be an instance of Compilation at Function.getCompilationHooks (C:\Users\userName\Documents\Git\bft3\node_modules\@angular-devkit\build-angular\node_modules\webpack\lib\javascript\JavascriptModulesPlugin.js:143:10) at SourceMapDevToolModuleOptionsPlugin.apply (C:\Users\userName\Documents\Git\bft3\node_modules\@angular-devkit\build-angular\node_modules\webpack\lib\SourceMapDevToolModuleOptionsPlugin.js:50:27) at C:\Users\userName\Documents\Git\bft3\node_modules\@angular-devkit\build-angular\node_modules\webpack\lib\SourceMapDevToolPlugin.js:163:53 at Hook.eval [as call] (eval at create (C:\Users\userName\Documents\Git\bft3\node_modules\webpack\node_modules\tapable\lib\HookCodeFactory.js:19:10), &lt;anonymous&gt;:374:1) at Hook.CALL_DELEGATE [as _call] (C:\Users\userName\Documents\Git\bft3\node_modules\webpack\node_modules\tapable\lib\Hook.js:14:14) at Compiler.newCompilation (C:\Users\userName\Documents\Git\bft3\node_modules\webpack\lib\Compiler.js:1122:26) at C:\Users\userName\Documents\Git\bft3\node_modules\webpack\lib\Compiler.js:1166:29 at _next0 (eval at create (C:\Users\userName\Documents\Git\bft3\node_modules\webpack\node_modules\tapable\lib\HookCodeFactory.js:33:10), &lt;anonymous&gt;:41:1) at eval (eval at create (C:\Users\userName\Documents\Git\bft3\node_modules\webpack\node_modules\tapable\lib\HookCodeFactory.js:33:10), &lt;anonymous&gt;:55:1) at processTicksAndRejections (node:internal/process/task_queues:96:5) </code></pre> <p>By reading other, similar posts i think it could be because of multiple versions of webpack.</p> <p>Here are the related packages/deps: <code>yarn list --pattern &quot;webpack&quot;</code></p> <pre><code>├─ @angular-devkit/build-angular@14.2.9 │ └─ webpack@5.74.0 ├─ @angular-devkit/build-webpack@0.1402.9 ├─ @cypress/webpack-preprocessor@5.15.5 ├─ @ngtools/webpack@14.2.9 ├─ @nrwl/angular@15.0.13 │ └─ webpack-merge@5.7.3 ├─ @nrwl/cypress@15.0.13 │ └─ fork-ts-checker-webpack-plugin@7.2.13 ├─ @nrwl/webpack@15.0.13 │ ├─ copy-webpack-plugin@10.2.4 │ ├─ fork-ts-checker-webpack-plugin@7.2.13 │ └─ webpack-dev-server@4.11.1 ├─ @storybook/builder-webpack4@6.5.13 │ ├─ terser-webpack-plugin@4.2.3 │ ├─ webpack-dev-middleware@3.7.3 │ ├─ webpack-sources@1.4.3 │ ├─ webpack-virtual-modules@0.2.2 │ └─ webpack@4.46.0 │ └─ terser-webpack-plugin@1.4.5 ├─ @storybook/builder-webpack5@6.5.13 │ ├─ fork-ts-checker-webpack-plugin@6.5.2 │ ├─ html-webpack-plugin@5.5.0 │ └─ webpack-dev-middleware@4.3.0 ├─ @storybook/core-common@6.5.13 │ ├─ fork-ts-checker-webpack-plugin@6.5.2 │ ├─ terser-webpack-plugin@1.4.5 │ ├─ webpack-sources@1.4.3 │ └─ webpack@4.46.0 ├─ @storybook/core-server@6.5.13 │ ├─ terser-webpack-plugin@1.4.5 │ ├─ webpack-sources@1.4.3 │ └─ webpack@4.46.0 ├─ @storybook/manager-webpack4@6.5.13 │ ├─ terser-webpack-plugin@4.2.3 │ ├─ webpack-dev-middleware@3.7.3 │ ├─ webpack-sources@1.4.3 │ ├─ webpack-virtual-modules@0.2.2 │ └─ webpack@4.46.0 │ └─ terser-webpack-plugin@1.4.5 ├─ @storybook/manager-webpack5@6.5.13 │ ├─ html-webpack-plugin@5.5.0 │ └─ webpack-dev-middleware@4.3.0 ├─ @types/webpack-env@1.18.0 ├─ @types/webpack-sources@3.2.0 ├─ @types/webpack@4.41.33 ├─ case-sensitive-paths-webpack-plugin@2.4.0 ├─ copy-webpack-plugin@11.0.0 ├─ css-minimizer-webpack-plugin@3.4.1 ├─ fork-ts-checker-webpack-plugin@4.1.6 ├─ html-webpack-plugin@4.5.2 ├─ license-webpack-plugin@4.0.2 ├─ pnp-webpack-plugin@1.6.4 ├─ terser-webpack-plugin@5.3.6 ├─ tsconfig-paths-webpack-plugin@3.5.2 ├─ webpack-bundle-analyzer@4.7.0 ├─ webpack-dev-middleware@5.3.3 ├─ webpack-dev-server@4.11.0 ├─ webpack-filter-warnings-plugin@1.2.1 ├─ webpack-hot-middleware@2.25.3 ├─ webpack-log@2.0.0 ├─ webpack-merge@5.8.0 ├─ webpack-node-externals@3.0.0 ├─ webpack-sources@3.2.3 ├─ webpack-subresource-integrity@5.1.0 ├─ webpack-virtual-modules@0.4.6 └─ webpack@5.75.0 </code></pre> <p>I'm not quite experienced enough to debug this completely, so do you see an issue here with webpack or have any other idea what might be causing this?</p> <p>Thanks in advance for any help!</p>
[ { "answer_id": 74537509, "author": "Eduardo Rosostolato", "author_id": 8403079, "author_profile": "https://Stackoverflow.com/users/8403079", "pm_score": 1, "selected": false, "text": "webpack v5.74.0 package.json ...\n\"webpack\": \"5.74.0\"\n yarn" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9813446/" ]
74,509,076
<p>I've seen that <code>close ARGV</code> can close the currently processed file, but it would seem that <code>ARGV</code> isn't actually a file handle, so I can't use it in a <code>read</code> call. Is there any way to get the current file handle, or am I going to have to explicitly open the files myself?</p>
[ { "answer_id": 74509161, "author": "Steffen Ullrich", "author_id": 3081018, "author_profile": "https://Stackoverflow.com/users/3081018", "pm_score": 4, "selected": true, "text": "ARGV read <> <> <> perl -e '<>; read(ARGV, my $buf, 10); print $buf' file\n <> read" }, { "answer_id": 74510119, "author": "ikegami", "author_id": 589924, "author_profile": "https://Stackoverflow.com/users/589924", "pm_score": 2, "selected": false, "text": "<> readline( ARGV ) ARGV readline ARGV read read readline $/ $ echo abcdef | perl -Mv5.14 -e'local $/ = \\2; $_ = <>; say \"<<$_>>\";'\n<<ab>>\n\n$ perl -Mv5.14 -e'local $/ = \\2; $_ = <>; say \"<<$_>>\";' <( echo abcdef )\n<<ab>>\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509076", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1366368/" ]
74,509,090
<p>Let's say we have an array of objects as below:</p> <pre><code>const example = [ { id: &quot;1&quot;, childIds: [&quot;2&quot;], parentId: &quot;0&quot; }, { id: &quot;2&quot;, childIds: [&quot;3&quot;, &quot;4&quot;], parentId: &quot;1&quot; }, { id: &quot;3&quot;, childIds: [], parentId: &quot;2&quot; }, { id: &quot;4&quot;, childIds: [&quot;5&quot;, &quot;6&quot;], parentId: &quot;2&quot; }, { id: &quot;5&quot;, childIds: [], parentId: &quot;4&quot; }, { id: &quot;6&quot;, childIds: [], parentId: &quot;4&quot; }, ]; </code></pre> <p>Problem: Copy this object, by generating new IDs.</p> <p>IDs can be different ofc. Assume that we're using a 3<sup>rd</sup> party ID generator function to handle it. But the new IDs should match to keep the child-parent relation.</p> <p>So, how would your JS function look like to solve this problem?</p> <p>Expected result:</p> <pre><code>const copied = [ { id: &quot;10&quot;, childIds: [&quot;20&quot;], parentId: &quot;0&quot; }, { id: &quot;20&quot;, childIds: [&quot;30&quot;, &quot;40&quot;], parentId: &quot;10&quot; }, { id: &quot;30&quot;, childIds: [], parentId: &quot;20&quot; }, { id: &quot;40&quot;, childIds: [&quot;50&quot;, &quot;60&quot;], parentId: &quot;20&quot; }, { id: &quot;50&quot;, childIds: [], parentId: &quot;40&quot; }, { id: &quot;60&quot;, childIds: [], parentId: &quot;40&quot; }, ]; </code></pre> <p>This is what I tried (getting error: TypeError: Cannot assign to read only property 'parentId' of object '#')</p> <pre><code> const copied = []; example.forEach((child) =&gt; { const newId = generateId(); // check if this child is parent of other elements, then update parentIds const childrenOfThisChild = example.filter( (el) =&gt; el.parentId === child.id ); if (childrenOfThisChild.length) { childrenOfThisNode.forEach( (child) =&gt; (child = { ...child, parentId: newId }) ); } // check if this child is child of other elements, then update childIds example.forEach((el) =&gt; { const index = el.childIds.indexOf(child.id); if (index !== -1) { el.childIds[index] = newId; } }); // add the currently iterated object to new copied array copied.push({ ...child, id: newId }); }); </code></pre>
[ { "answer_id": 74509161, "author": "Steffen Ullrich", "author_id": 3081018, "author_profile": "https://Stackoverflow.com/users/3081018", "pm_score": 4, "selected": true, "text": "ARGV read <> <> <> perl -e '<>; read(ARGV, my $buf, 10); print $buf' file\n <> read" }, { "answer_id": 74510119, "author": "ikegami", "author_id": 589924, "author_profile": "https://Stackoverflow.com/users/589924", "pm_score": 2, "selected": false, "text": "<> readline( ARGV ) ARGV readline ARGV read read readline $/ $ echo abcdef | perl -Mv5.14 -e'local $/ = \\2; $_ = <>; say \"<<$_>>\";'\n<<ab>>\n\n$ perl -Mv5.14 -e'local $/ = \\2; $_ = <>; say \"<<$_>>\";' <( echo abcdef )\n<<ab>>\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10208281/" ]
74,509,123
<p>So I've just started learning html and javascript and I'm trying to create a comment page. However I can only get the page to display one comment at a time and I would like to be able to add aditional comments. Can anyone please help?</p> <p>Part of code used</p> <p>JS:</p> <pre><code> function getUserInput(){ var name = document.getElementById(&quot;name&quot;).value; var email = document.getElementById(&quot;email&quot;).value; var review = document.getElementById(&quot;review&quot;).value; document.getElementById(&quot;Reviews&quot;).innerHTML = name + &quot; &quot; + email + &quot; &quot; + review; } </code></pre> <p>html:</p> <pre><code>&lt;div class=&quot;info&quot;&gt; Name &lt;input type=&quot;text&quot; id=&quot;name&quot; value=&quot;&quot;&gt; Email &lt;input type=&quot;text&quot; id=&quot;email&quot; value=&quot;&quot;&gt; &lt;br&gt; &lt;h2&gt;Leave your Book Review...&lt;/h2&gt; &lt;textarea maxlength=&quot;150&quot; rows=&quot;5&quot; cols=&quot;50&quot; wrap=&quot;hard&quot; id=&quot;review&quot;&gt; &lt;/textarea&gt; &lt;br&gt; Remaining &lt;span id=&quot;info&quot;&gt;&lt;/span&gt; characteres &lt;button onclick=&quot;getUserInput()&quot;&gt; Leave Review&lt;/button&gt; &lt;hr&gt; &lt;/div&gt; &lt;div id=&quot;Reviews&quot;&gt;&lt;/div&gt; </code></pre> <pre><code></code></pre>
[ { "answer_id": 74509163, "author": "Azad", "author_id": 19120939, "author_profile": "https://Stackoverflow.com/users/19120939", "pm_score": 1, "selected": false, "text": "function getUserInput(){\n var name = document.getElementById(\"name\").value;\n var email = document.getElementById(\"email\").value;\n var review = document.getElementById(\"review\").value;\n document.getElementById(\"Reviews\").innerHTML += name + \" \" + email + \" \" + review;\n}\n innerHTML+= innerHTML = ..." }, { "answer_id": 74509260, "author": "Arnau", "author_id": 897391, "author_profile": "https://Stackoverflow.com/users/897391", "pm_score": 0, "selected": false, "text": "function getUserInput(){\n var name = document.getElementById(\"name\").value;\n var email = document.getElementById(\"email\").value;\n var review = document.getElementById(\"review\").value;\n const newReview = document.createElement(\"p\");\n newReview.innerHTML = name + \" \" + email + \" \" + review;\n const reviewsParentNode = document.getElementById(\"Reviews\");\n reviewsParentNode.insertBefore(newReview);\n}\n" }, { "answer_id": 74509593, "author": "Andy", "author_id": 1377002, "author_profile": "https://Stackoverflow.com/users/1377002", "pm_score": 1, "selected": true, "text": "reviews += reviews // Cache the reviews element\nconst reviews = document.querySelector('.reviews');\n\n// Accept some values\nfunction addReview({ name, email, text }) {\n \n // Create a review element and attach a class to it\n const reviewEl = document.createElement('section');\n reviewEl.className = 'review';\n \n // Create a header element...\n const headerEl = document.createElement('header');\n \n // ...and an anchor element, and add the email and name\n const anchorEl = document.createElement('a');\n anchorEl.href = email;\n anchorEl.textContent = name;\n \n // Finally create a text element for the review text,\n // and add the text to it's textContent property\n const textEl = document.createElement('section');\n textEl.textContent = text;\n \n // Append all the elements together\n headerEl.append(anchorEl);\n reviewEl.append(headerEl);\n reviewEl.append(textEl);\n \n // And finally add the review to the reviews element\n reviews.append(reviewEl);\n\n}\n\naddReview({ name: 'Bob', email: 'bobsemail@bob.com', text: 'This is Bob\\'s review.' });\naddReview({ name: 'Kate', email: 'katesemail@kate.com', text: 'This is Kate\\'s review.' });\naddReview({ name: 'Moses', email: 'mosesemail@moses.com', text: 'This is Moses\\' review.' }); .review { border: 1px solid #444; padding: 0.5em; }\n.review section { margin-top: 0.25em; }\n.review:not(:first-child) { margin-top: 0.5em; } <div class=\"reviews\"></div> reviews const reviews = document.querySelector('.reviews');\n\nfunction addReview({ name, email, text }) {\n const html = `\n <section class=\"review\">\n <header>\n <a href=\"mailto:${email}\">${name}</a>\n </header>\n <section>${text}</section>\n </section>\n `;\n reviews.insertAdjacentHTML('beforeend', html);\n}\n\naddReview({ name: 'Bob', email: 'bobsemail@bob.com', text: 'This is Bob\\'s review.' });\naddReview({ name: 'Kate', email: 'katesemail@kate.com', text: 'This is Kate\\'s review.' });\naddReview({ name: 'Moses', email: 'mosesemail@moses.com', text: 'This is Moses\\' review.' }); .review { border: 1px solid #444; padding: 0.5em; }\n.review section { margin-top: 0.25em; }\n.review:not(:first-child) { margin-top: 0.5em; } <div class=\"reviews\"></div>" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20555412/" ]
74,509,130
<p>I'm trying to find the right command to use in the CLI to print the contents of a table within DynamoDB.</p> <p>I've tried using the following command but it gives me a &quot;parameter validation failed&quot; error.</p> <p>`</p> <pre><code>aws dynamodb get-item \ --table-name Traffic \ --key file://traffic.json \ --return-consumed-capacity TOTAL </code></pre> <p>`</p> <p>The AWS website is giving me a 403 error, at the moment, so I can't search for the solution through the official site.</p>
[ { "answer_id": 74509601, "author": "Lee Hannigan", "author_id": 7909676, "author_profile": "https://Stackoverflow.com/users/7909676", "pm_score": 0, "selected": false, "text": "Scan aws dynamodb scan \\\n--table-name test \\\n--output text\n batch-get-item" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509130", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20542377/" ]
74,509,148
<p>I started making a small program. The form contains checkbox1,2,3,4,.... and textbox1,2,3,4,5.... there is a code that looks at which of the checkboxes are marked. If there is any possibility to link textbox and checkbox. So that when a code marked with a checkbox is detected, the text is taken from the textbox given to it and transferred to the RichTextBox, using AppendText. Below is a sample code with a cyclic check of all the checkboxes on the form for the presence of checked on my form.</p> <pre><code>foreach (Control control in this.tabControl1.TabPages[0].Controls) //цикл по форме с вкладками { if (control as CheckBox != null) // проверка на пустое значение { if (control.Visible == true)// проверка на видимость { if ((control as CheckBox).Checked)// проверка на чек { } else if ((control as CheckBox).Checked == false) { } } } </code></pre>
[ { "answer_id": 74509601, "author": "Lee Hannigan", "author_id": 7909676, "author_profile": "https://Stackoverflow.com/users/7909676", "pm_score": 0, "selected": false, "text": "Scan aws dynamodb scan \\\n--table-name test \\\n--output text\n batch-get-item" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9865805/" ]
74,509,213
<p>To solve my problem I need to get out of the <code>while</code> loop if the <code>str2</code> is empty.</p> <pre><code>while (elementos &lt;= tamanho - jogada || str2 == NULL); </code></pre> <p>This is the code:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #define BUFFER 100 unsigned int randaux() { static long seed = 1; return (((seed = seed * 214013L + 2531011L) &gt;&gt; 16) &amp; 0x7fff); } /* Implementação do procedimento MostraLamberta */ unsigned int MostraLamberta(int *tabuleiro, int tamanho) { int i, casa, elementos; int jogada = 0; char novostr[BUFFER], str2[BUFFER]; /* novo vetor para receber os char */ do { scanf(&quot;%d %d&quot;, &amp;casa, &amp;elementos); for (i = 0; i &lt; tamanho; i++) { /*Loop para percorrer o int tabuleiro um a um */ if (tabuleiro[i] == 0) { /*Comparar se for 0 vai para o vetor como O */ novostr[i] = 'O'; } else { /* Se não vai para o vetor como X */ novostr[i] = 'X'; } } if (tamanho &gt;= 10) { novostr[i] = '\0'; for (i = 1; i &lt; tamanho; i++) { if (i == 10) { printf(&quot;%d&quot;, (i) / 10); } else { printf(&quot; &quot;); } } printf(&quot;\n&quot;); for (i = 1; i &lt; tamanho + 1; i++) { if (i &gt;= 10) { printf(&quot;%d&quot;, i % 10); } else { printf(&quot;%d&quot;, i); } printf; } } else { for (i = 0; i &lt; tamanho; i++) { if (i == 10) { printf(&quot;%d&quot;, i % 10); } else { printf(&quot;%d&quot;, i + 1); } } } printf(&quot;\n&quot;); novostr[i] = '\0'; /*Termina a string */ jogada++; printf(&quot;%s&quot;, novostr); printf(&quot;\nJogada [%d]: %d %d&quot;, jogada, casa, elementos); /*Imprime nova string */ for (i = casa - 1; i &lt; elementos + casa - 1; i++) { if (tabuleiro[i] == 0) { /*Comparar se for 0 vai para o vetor como O */ novostr[i] = 'X'; tabuleiro[i] = 1; continue; } else { /* Se não vai para o vetor como X */ novostr[i] = 'O'; tabuleiro[i] = 0; str2[i] = tabuleiro[i]; } novostr[i] = '\0'; printf(&quot;%d&quot;, str2[i]);//in here if its empty, the loop is over } printf(&quot;\n&quot;); } while (elementos &lt;= tamanho - jogada || str2 == NULL); if (jogada % 2 == 0) { printf(&quot;Jogada inválida, perde jogador 2.&quot;); } else { printf(&quot;Jogada inválida, perde jogador 1.&quot;); } } void main() { int i, num, saltos, tamanho, tabuleiro[BUFFER]; /*Implementa as variáveis inteiras */ scanf(&quot;%d %d&quot;, &amp;tamanho, &amp;saltos); // saltar os primeiros números aleatórios, para ter sequências distintas for (i = 0; i &lt; saltos; i++) /*Loop */ randaux(); /*Chama a funcão randaux */ /* Chamar o procedimento para gerar um novo tabuleiro */ for (i = 0; i &lt; tamanho; i++) { num = randaux(); /*Grava um numero aleatório numa nova variável */ if (num % 2 == 0) { /*VC* se o numero aleatório C) par ou impar */ tabuleiro[i] = 0; } else { tabuleiro[i] = 1; } } MostraLamberta(tabuleiro, tamanho); /*Chama a função e passa dois argumentos) */ } </code></pre> <p>[<img src="https://i.stack.imgur.com/PEDEM.png" alt="my output" />]</p> <p>[<img src="https://i.stack.imgur.com/BQHU7.png" alt="expected output" />]</p>
[ { "answer_id": 74510304, "author": "dash-o", "author_id": 12098405, "author_profile": "https://Stackoverflow.com/users/12098405", "pm_score": 0, "selected": false, "text": "while (elementos <= tamanho - jogada || str2 == NULL);\n elementos <= tamanho - jogada jopada++" }, { "answer_id": 74510498, "author": "chqrlie", "author_id": 4593267, "author_profile": "https://Stackoverflow.com/users/4593267", "pm_score": 1, "selected": false, "text": "do while for (;;) if (scanf(\"%d %d\", &casa, &elementos) != 2) break; while (elementos <= tamanho - jogada || str2 == NULL); str2 NULL str2[0] == '\\0' str2 str2[i] = tabuleiro[i]; tabuleiro[i] 0 str2" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14196739/" ]
74,509,243
<pre><code> public readonly struct MyStruct : IInterface { public MyStruct() { M(); } public void Test() { throw new NotImplementedException(); } } public interface IInterface { static void M() { Console.WriteLine(&quot;IA.M&quot;); } void Test(); } </code></pre> <p>When I compile in visual studio 2022 with .net 7.0, I get &quot;<strong>The name 'M' does not exist in the current context</strong>&quot; error. To my limited knowledge, structs can implement interfaces, interfaces can have default methods .. so why the compilation error?</p> <p>I'm expecting it not to give a compilation error.</p>
[ { "answer_id": 74509438, "author": "Sweeper", "author_id": 5133585, "author_profile": "https://Stackoverflow.com/users/5133585", "pm_score": 1, "selected": false, "text": "class Foo {\n public static void M() {}\n}\n\nclass Bar: Foo {\n public Bar() {\n M(); // OK\n }\n}\n M Foo Foo.M M Bar Bar Foo System.ValueType M IInterface MyStruct M IInterface.M();\n IInterface M void Foo<T>() where T: IInterface {\n T.M();\n}\n virtual" }, { "answer_id": 74509741, "author": "Maurice Marinus", "author_id": 20555495, "author_profile": "https://Stackoverflow.com/users/20555495", "pm_score": 0, "selected": false, "text": "namespace ClassLibrary1\n{\n public struct MyStruct : IInterface \n { \n public MyStruct()\n {\n (this as IInterface).M(); \n }\n\n public void Test()\n {\n throw new NotImplementedException();\n }\n }\n\n public interface IInterface\n {\n public void M() \n { \n Console.WriteLine(\"IA.M\"); \n }\n\n void Test(); \n }\n\n public struct My\n {\n public void Test()\n {\n IInterface m = new MyStruct();\n m.M(); \n }\n }\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20555495/" ]
74,509,302
<p>In Astro, I would like to render double curly braces inside the template however it errors as whatever inside the braces is interpreted as JS code.</p> <p>Example:</p> <pre><code>.post-title { margin: 0 0 5px; font-weight: bold; font-size: 38px; line-height: 1.2; and here's a line of some really, really, really, really long text, just to see how it is handled and to find out how it overflows; } </code></pre> <p>To render the code above, this is how I have setup my template like:</p> <pre><code>&lt;code&gt; .post-title {&lt;br /&gt; margin: 0 0 5px;&lt;br /&gt; font-weight: bold;&lt;br /&gt; font-size: 38px;&lt;br /&gt; line-height: 1.2;&lt;br /&gt; and here's a line of some really, really, really, really long text, just to see how it is handled and to find out how it overflows;&lt;br /&gt; } &lt;/code&gt; </code></pre> <p>Is there any clean/elegant way to render curly braces directly inside astro template?</p>
[ { "answer_id": 74509438, "author": "Sweeper", "author_id": 5133585, "author_profile": "https://Stackoverflow.com/users/5133585", "pm_score": 1, "selected": false, "text": "class Foo {\n public static void M() {}\n}\n\nclass Bar: Foo {\n public Bar() {\n M(); // OK\n }\n}\n M Foo Foo.M M Bar Bar Foo System.ValueType M IInterface MyStruct M IInterface.M();\n IInterface M void Foo<T>() where T: IInterface {\n T.M();\n}\n virtual" }, { "answer_id": 74509741, "author": "Maurice Marinus", "author_id": 20555495, "author_profile": "https://Stackoverflow.com/users/20555495", "pm_score": 0, "selected": false, "text": "namespace ClassLibrary1\n{\n public struct MyStruct : IInterface \n { \n public MyStruct()\n {\n (this as IInterface).M(); \n }\n\n public void Test()\n {\n throw new NotImplementedException();\n }\n }\n\n public interface IInterface\n {\n public void M() \n { \n Console.WriteLine(\"IA.M\"); \n }\n\n void Test(); \n }\n\n public struct My\n {\n public void Test()\n {\n IInterface m = new MyStruct();\n m.M(); \n }\n }\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11924762/" ]
74,509,308
<p>i am a beginner in python i and i came up this problem and i cant seem to solve it.I have the following dictionary</p> <pre><code>stats = {1: {&quot;Player&quot;: &quot;Derrick Henry&quot;, &quot;yards&quot;: 870, &quot;TD&quot;: 9}, 2: {&quot;Player&quot;: &quot;Nick Chubb&quot;, &quot;Yards&quot;: 841, &quot;TD&quot;: 10}, 3: {&quot;Player&quot;: &quot;Saquon Barkley&quot;, &quot;Yards&quot;: 779, &quot;TD&quot;: 5}} </code></pre> <p>I want to loop through a dictionary and display the values as shown below</p> <pre><code>Player1 Player=Derrick Henry yards=870 TD=9 player 2 Player=Nnikki Chubb yards=770 TD=10 player3 Player=Nikki Chubb yards=770 TD=10 </code></pre> <p>i tried the following code</p> <pre><code>stats = {1: {&quot;Player&quot;: &quot;Derrick Henry&quot;, &quot;Yards&quot;: 870, &quot;TD&quot;: 9}, 2: {&quot;Player&quot;: &quot;Nick Chubb&quot;, &quot;Yards&quot;: 841, &quot;TD&quot;: 10}, 3: {&quot;Player&quot;: &quot;Saquon Barkley&quot;, &quot;Yards&quot;: 779, &quot;TD&quot;: 5}} for key, value in stats.items(): print(value) for x, y,z in value.items(): print(&quot;Player {}&quot;.format(key)) #IF Player if x == &quot;Player&quot;: print(&quot;Player = {}&quot;.format(x)) #IF YARDS if y == &quot;Yards&quot;: print(&quot;Yards = {}&quot;.format(y)) #IF YARDS if z == &quot;TD&quot;: print(&quot;yards = {}&quot;.format(y)) </code></pre> <p>Any help will be appreciated.Thank you</p>
[ { "answer_id": 74509366, "author": "azro", "author_id": 7212686, "author_profile": "https://Stackoverflow.com/users/7212686", "pm_score": 2, "selected": true, "text": "if x == \"Player\":\n print(\"Player = {}\".format(x))\nif y == \"Yards\":\n print(\"Yards = {}\".format(y))\nif z == \"TD\":\n print(\"TD = {}\".format(y))\n .items for key, props in stats.items():\n print(f\"Player{key}\")\n for prop_key, prop_value in props.items():\n print(f\"{prop_key}={prop_value}\")\n" }, { "answer_id": 74509444, "author": "treuss", "author_id": 19838568, "author_profile": "https://Stackoverflow.com/users/19838568", "pm_score": 0, "selected": false, "text": "print(\"Player = {}\".format(value[\"Player\"]))\nprint(\"Yards = {}\".format(value[\"Yards\"]))\nprint(\"TD = {}\".format(value[\"TD\"]))\n for key in [\"Player\", \"Yards\", \"TD\"]:\n print(\"{} = {}\".format(key, value[key])\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20475046/" ]
74,509,310
<p>I have the variable <code>G.playerStatsDifference</code> defined as an array of objects:</p> <pre><code>playerStatsDifference: [{ carpenter: 0, wood: 0, gunman: 0, gunpowder: 0, merchant: 0, gold: 0, fleet: 0, flagship: 0, }, { carpenter: 0, wood: 0, gunman: 0, gunpowder: 0, merchant: 0, gold: 0, fleet: 0, flagship: 0, }] </code></pre> <p>The point of this variable is to calculate the difference between <code>G.playerStats</code> which frequently changes.</p> <p>My function to calculate the difference is:</p> <pre><code>const oldPlayerStats = JSON.parse(JSON.stringify(G.playerStats)); statsDifference(G, oldPlayerStats); for (let p = 0; p &lt; 2; p++) { for (let s = 0; s &lt; 8; s++) { Object.values(G.playerStatsDifference[p])[s] = Object.values(G.playerStats[p])[s] - Object.values(oldPlayerStats[p])[s]; } } </code></pre> <p>The expected output would be to have <code>playerStatsDifference</code></p> <p>When running some tests I did some console logging and it gave me the correct calculations, but the <code>G.playerStatsDiffence</code> would not update.</p> <p>Here is some of that testing, with the calulations being correct:</p> <pre><code>console.log(&quot;Current wood is &quot; + Object.values(G.playerStats[0])[1]); //Current wood is 5 console.log(&quot;Old wood is &quot; + Object.values(oldPlayerStats[0])[1]); //Old wood is 10 console.log(Object.values(G.playerStats[0])[1] - Object.values(oldPlayerStats[0])[1]); //-5 </code></pre> <p>I thought maybe I was doing something wrong with the loops so I tried the following afterwards:</p> <pre><code>Object.values(G.playerStatsDifference[0])[1] = Object.values(G.playerStats[0])[1] - Object.values(oldPlayerStats[0])[1]; </code></pre> <p>However this did not work either. Having said that, the following does work:</p> <pre><code>G.playerStatsDifference[0].wood = Object.values(G.playerStats[0])[1] - Object.values(oldPlayerStats[0])[1]; </code></pre> <p>So it seems like I have some issue with the <code>Object.values</code> on <code>G.playerStatsDifference</code>. Any idea on why that is and how I can run that through the loop?</p> <p>=====</p> <p>EDIT: As those in the comments have pointed out my question is a bit confusing so I will try to clear it up here..</p> <p>The <code>G.playerStatsDifference</code> value is supposed to track the difference between the previous value of <code>G.playerStats</code> and the current value of <code>G.playerStats</code>.</p> <p>To do this I am setting the value of <code>oldPlayerStats</code> to equal <code>G.playerStats</code> and then updating <code>G.playerStats</code> to its new value.</p> <p>I then need to run through the array of objects and subtract the value of <code>G.playerStats</code> from <code>oldPlayerStats</code>. This will produce the value of <code>G.playerStatsDifference</code></p> <p>That is what the loop is for, to go through each object key and do the calculation.</p> <p>Hope this provides some clarity. Sorry for the poorly worded question.</p>
[ { "answer_id": 74509366, "author": "azro", "author_id": 7212686, "author_profile": "https://Stackoverflow.com/users/7212686", "pm_score": 2, "selected": true, "text": "if x == \"Player\":\n print(\"Player = {}\".format(x))\nif y == \"Yards\":\n print(\"Yards = {}\".format(y))\nif z == \"TD\":\n print(\"TD = {}\".format(y))\n .items for key, props in stats.items():\n print(f\"Player{key}\")\n for prop_key, prop_value in props.items():\n print(f\"{prop_key}={prop_value}\")\n" }, { "answer_id": 74509444, "author": "treuss", "author_id": 19838568, "author_profile": "https://Stackoverflow.com/users/19838568", "pm_score": 0, "selected": false, "text": "print(\"Player = {}\".format(value[\"Player\"]))\nprint(\"Yards = {}\".format(value[\"Yards\"]))\nprint(\"TD = {}\".format(value[\"TD\"]))\n for key in [\"Player\", \"Yards\", \"TD\"]:\n print(\"{} = {}\".format(key, value[key])\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509310", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7341585/" ]
74,509,349
<p>Hi i am a beginner and i have to make a simple phonebook programme in C++ using library . I would definitely use but im not allowed to as it is for an assignment. Below is my code until now and i have 3 errors which i don't know how to solve. I know conversion from char to const char* is not allowed but i really need to compare these two type c arrays and i can't figure it out how to. I am using strcmp and i am using '\0' as a char which seem correct.</p> <pre><code>#include &lt;iostream&gt; #include &lt;cstring&gt; using namespace std; struct contact { char name[30]; char surname[30]; char phone_number[30]; }; int main() { for (int i = 0; i &lt; 30; i++) { if (strcmp(person.name[i],person.surname[i]) != '\0') &lt;--- //ERROR HERE cout &lt;&lt; person.name[i] &lt;&lt; person.surname[i] &lt;&lt; person.phone_number[i]; check++; } char temp; char temp1; cout &lt;&lt; &quot;Insert the name of the contact to delete: \n&quot;; cin &gt;&gt; temp; cout &lt;&lt; &quot;Insert the surname of the contact to delete: \n&quot;; cin &gt;&gt; temp1; int check = 0; for (int i = 0; i &lt; 30; i++) { if (strcmp(temp,person.name[i]) == 0 &amp;&amp; strcmp(temp1, person.surname[i]) == 0) { ^-- // 2 ERRORS HERE CONVERSION FROM 'CHAR' TO 'CONST CHAR*' cout &lt;&lt; &quot;Contact deleted!\n&quot;; person.name[i] = '\0'; person.surname[i] = '\0'; person.phone_number[i] = '\0'; check++; } if (check == 0) { cout &lt;&lt; &quot;This person is not in your contact list\n &quot;; return 0; } </code></pre>
[ { "answer_id": 74509866, "author": "Tóth Attila", "author_id": 2075578, "author_profile": "https://Stackoverflow.com/users/2075578", "pm_score": 0, "selected": false, "text": "char const char* std::string" }, { "answer_id": 74510153, "author": "Zz_GhostM4n_zZ", "author_id": 20555553, "author_profile": "https://Stackoverflow.com/users/20555553", "pm_score": 3, "selected": true, "text": "#include <iostream>\n#include <stdio.h>\n\nusing namespace std;\n\nstruct person{\n char name[30];\n char surname[30];\n char phone_number[30];\n};\n\nint main()\n{\n person Persons[] = { // structure initialization\n {\"Bob\",\"Thug Bob\",\"01230123\"},\n {\"Marry\",\"Gangster Marry\",\"9999999\"},\n {\"Somebody\",\"Mr Somebody\",\"777777\"}\n };\n\n int Size = sizeof(Persons)/sizeof(Persons[0]); // return size of Persons array\n\n for(int i=0;i<Size;i++){\n cout << Persons[i].name << \"\\t\"<< Persons[i].surname << \"\\t\"<< Persons[i].phone_number <<endl;\n }\n\n return 0;\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20207973/" ]
74,509,365
<p>I have a list of files in a adls container which contain date in the name as given below:</p> <pre><code>TestFile-Name-20221120. csv TestFile-Name-20221119. csv TestFile-Name-20221118. csv </code></pre> <p>and i want to copy files which contain today date only like TestFile-Name-20221120. csv on today and so on. I've used get metedata activity to get list of files and then for each to iterate over each file and then used set variable to extract name from the file like 20221120 but not sure how to proceed further.</p>
[ { "answer_id": 74509866, "author": "Tóth Attila", "author_id": 2075578, "author_profile": "https://Stackoverflow.com/users/2075578", "pm_score": 0, "selected": false, "text": "char const char* std::string" }, { "answer_id": 74510153, "author": "Zz_GhostM4n_zZ", "author_id": 20555553, "author_profile": "https://Stackoverflow.com/users/20555553", "pm_score": 3, "selected": true, "text": "#include <iostream>\n#include <stdio.h>\n\nusing namespace std;\n\nstruct person{\n char name[30];\n char surname[30];\n char phone_number[30];\n};\n\nint main()\n{\n person Persons[] = { // structure initialization\n {\"Bob\",\"Thug Bob\",\"01230123\"},\n {\"Marry\",\"Gangster Marry\",\"9999999\"},\n {\"Somebody\",\"Mr Somebody\",\"777777\"}\n };\n\n int Size = sizeof(Persons)/sizeof(Persons[0]); // return size of Persons array\n\n for(int i=0;i<Size;i++){\n cout << Persons[i].name << \"\\t\"<< Persons[i].surname << \"\\t\"<< Persons[i].phone_number <<endl;\n }\n\n return 0;\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18096952/" ]
74,509,402
<p>when we download some same files on Internet, the filename becomes (2), (3)...</p> <p><a href="https://i.stack.imgur.com/XsPTs.png" rel="nofollow noreferrer">example</a></p> <p>I want to remove these files with C. First of all, I want to find files and print. I write some code blow. But It doesn't work.</p> <pre><code>int main(){ const char *path; DIR *dir; struct dirent* entry; if((path=getenv(&quot;HOME&quot;))==NULL){//get HOME path path = getpwuid(getuid())-&gt;pw_dir; } const char *downloads = &quot;/Downloads&quot;; strcat(path,downloads); //make ~/Downloads if(chdir(path)!=0){ perror(&quot;chdir()&quot;); return -1; } if((dir=opendir(path))==NULL){ //open directory perror(&quot;open&quot;); return 1; } while((entry=readdir(dir))!=NULL){ struct dirent *cmpentry; DIR *cmpdir; if((cmpdir=opendir(path))==NULL){ perror(&quot;opendir&quot;); return -1; } while((cmpentry=readdir(cmpdir))!=NULL){ if((entry-&gt;d_name[0]!='.')&amp;&amp;strcmp(entry-&gt;d_name,cmpentry-&gt;d_name)!=0){ char *ptr=strstr(cmpentry-&gt;d_name,entry-&gt;d_name); if(ptr!=NULL) printf(&quot;%s\n&quot;,cmpentry-&gt;d_name); } } } } </code></pre> <p>How can i fix it?</p>
[ { "answer_id": 74509866, "author": "Tóth Attila", "author_id": 2075578, "author_profile": "https://Stackoverflow.com/users/2075578", "pm_score": 0, "selected": false, "text": "char const char* std::string" }, { "answer_id": 74510153, "author": "Zz_GhostM4n_zZ", "author_id": 20555553, "author_profile": "https://Stackoverflow.com/users/20555553", "pm_score": 3, "selected": true, "text": "#include <iostream>\n#include <stdio.h>\n\nusing namespace std;\n\nstruct person{\n char name[30];\n char surname[30];\n char phone_number[30];\n};\n\nint main()\n{\n person Persons[] = { // structure initialization\n {\"Bob\",\"Thug Bob\",\"01230123\"},\n {\"Marry\",\"Gangster Marry\",\"9999999\"},\n {\"Somebody\",\"Mr Somebody\",\"777777\"}\n };\n\n int Size = sizeof(Persons)/sizeof(Persons[0]); // return size of Persons array\n\n for(int i=0;i<Size;i++){\n cout << Persons[i].name << \"\\t\"<< Persons[i].surname << \"\\t\"<< Persons[i].phone_number <<endl;\n }\n\n return 0;\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19137737/" ]
74,509,414
<p>I have an input data as shown:</p> <pre><code>df = pd.DataFrame({&quot;colony&quot; : [22, 22, 22, 33, 33, 33], &quot;measure&quot; : [np.nan, 7, 11, 13, np.nan, 9,], &quot;net/gross&quot; : [np.nan, &quot;gross&quot;, &quot;net&quot;, &quot;gross&quot;, &quot;np.nan&quot;, &quot;net&quot;]}) df colony measure net/gross 0 22 NaN NaN 1 22 7 gross 2 22 11 net 3 33 13 gross 4 33 NaN NaN 5 33 9 net </code></pre> <p>I want to fill the NaN in the measure column with maximum value from each group of the colony, then fill the NaN in the net/gross column with the net/gross value at the row where the measure was maximum (e.g fill the NaN at index 0 with the value corresponding to where the measure was max which is &quot;net&quot;) and create a remark column to document all the NaN filled rows as &quot;max_filled&quot; and the other rows as &quot;unchanged&quot; to arrive at an output as below:</p> <pre><code> colony measure net/gross remarks 0 22 11 net max_filled 1 22 7 gross unchanged 2 22 11 net unchanged 3 33 13 gross unchanged 4 33 13 gross max_filled 5 33 9 net unchanged </code></pre>
[ { "answer_id": 74509866, "author": "Tóth Attila", "author_id": 2075578, "author_profile": "https://Stackoverflow.com/users/2075578", "pm_score": 0, "selected": false, "text": "char const char* std::string" }, { "answer_id": 74510153, "author": "Zz_GhostM4n_zZ", "author_id": 20555553, "author_profile": "https://Stackoverflow.com/users/20555553", "pm_score": 3, "selected": true, "text": "#include <iostream>\n#include <stdio.h>\n\nusing namespace std;\n\nstruct person{\n char name[30];\n char surname[30];\n char phone_number[30];\n};\n\nint main()\n{\n person Persons[] = { // structure initialization\n {\"Bob\",\"Thug Bob\",\"01230123\"},\n {\"Marry\",\"Gangster Marry\",\"9999999\"},\n {\"Somebody\",\"Mr Somebody\",\"777777\"}\n };\n\n int Size = sizeof(Persons)/sizeof(Persons[0]); // return size of Persons array\n\n for(int i=0;i<Size;i++){\n cout << Persons[i].name << \"\\t\"<< Persons[i].surname << \"\\t\"<< Persons[i].phone_number <<endl;\n }\n\n return 0;\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19702840/" ]
74,509,421
<p>I have a function that makes structured data from <code>rawData</code> (from API)</p> <pre><code>function makeData(raw:typeof rawData){ const data:IData = {} // this line throws above error. const now = new Date() data.createdAt=now.toDateString(); data.currentUser=raw.name; data.uniqueId= raw.id + now.toDateString(); return data } </code></pre> <p>As I am making the data, I am using an empty object in the beginning and typing it with IData so that the return value from the function is typed as <code>IData</code>. But as mentioned this is throwing error.</p> <pre><code>interface IData { createdAt:string; currentUser:string; uniqueId:string; } </code></pre> <p>Usage:</p> <pre><code>const {createdAt, currentUser,uniqueId} = makeData(rawData) </code></pre> <p>I tried to remove IData completely then I got the following error.</p> <pre><code>Property 'createdAt' does not exist on type '{}'. // got the same error for other properties as well ( currentUser, uniqueId ) </code></pre> <p>Getting the same error(s) on the line where destructing is done.</p> <p>I got a workaround for now:</p> <pre><code>const data : Record&lt;string,unknown&gt;= {} </code></pre> <p>But this doesn't seem to be more convincing for me.</p> <p>Is there a better way to type data as IData.</p> <p>Live <a href="https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgJIBE5jgbwFDKHIJQRYQAmAgmAFwDOYUoA5gNwFEICuUp4AVXrQGTVhyLJuIYAEduEVBVHMQ7PAF88eBAHsQjZFDgB3TNmQBeZPkkg4AWwi1kAIm7CorgDSdCwZXdPAEYAJgBmV01tPBhpBDBgfWQHOABrCHM4AApjE1owAE8ABwhdGCNTLIBKWy59QwosOGQXDGbrHA1kbUk9AzBkEF0TKyGIUfMIbOq-ZCbsADoSMkhqMEthk0WwXSmAZTE1GYkiBbhl3n4wIWhLPMX7J1PCc8XpOQUlaweA5ABqIYjHZ7ciHVQsE69IikMC8EDzZrRbT9Qw4FbkdbeYhXCCCTzeD7yRQUbrWVIZLK5KrNWY6Bq6AA2EEWjN0kIxaxo2J4fDxNwJRK+FGqQA" rel="nofollow noreferrer">Demo</a>.</p>
[ { "answer_id": 74509433, "author": "Sachila Ranawaka", "author_id": 6428638, "author_profile": "https://Stackoverflow.com/users/6428638", "pm_score": 0, "selected": false, "text": "const data:IData = {\n createdAt:'',\n currentUser:'',\n uniqueId:''\n }\n makeData(raw:typeof rawData): IData { ...\n" }, { "answer_id": 74509466, "author": "mikrowdev", "author_id": 18715249, "author_profile": "https://Stackoverflow.com/users/18715249", "pm_score": 3, "selected": true, "text": "IData function makeData(raw: typeof rawData): IData{\n const now = new Date()\n \n return {\n createdAt: now.toDateString(),\n currentUser: raw.name,\n uniqueId: raw.id + now.toDateString()\n }\n \n}\n" }, { "answer_id": 74509498, "author": "Anjan Talatam", "author_id": 14853666, "author_profile": "https://Stackoverflow.com/users/14853666", "pm_score": 1, "selected": false, "text": "IData const data = {} as IData.\n const data:IData = {\n createdAt:\"\",\n currentUser:\"\",\n uniqueId:\"\"\n }\n" }, { "answer_id": 74509518, "author": "Francisco Gomez", "author_id": 11053602, "author_profile": "https://Stackoverflow.com/users/11053602", "pm_score": 0, "selected": false, "text": "function makeData(raw: typeof rawData): IData { }\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20002028/" ]
74,509,456
<p>How to sort a Alphanumeric string with special characters in C# using Linq? Order should be first special characters, then numbers and then alphabets.</p> <p>Example :</p> <p>Input - { Hello, #Test, @Red, &amp;While, 123@Test, @123Test, %54Sun, Dom, Left }</p> <p>Expected - { @123Test, %54Sun, @Red, #Test, &amp;While, 123@Test, Dom, Hello, Left }</p> <p><a href="https://i.stack.imgur.com/uY8kU.png" rel="nofollow noreferrer">enter image description here</a></p>
[ { "answer_id": 74509727, "author": "Renat", "author_id": 1075282, "author_profile": "https://Stackoverflow.com/users/1075282", "pm_score": 1, "selected": true, "text": "OrderBy public class SpecialCharactersNumbersLettersComparer : IComparer<string>\n{\n private readonly IComparer<string> defaultComparer = StringComparer.InvariantCulture;\n \n private static int OrderOfChar(char ch)\n {\n if(Char.IsLetter(ch))\n return 2;\n if(Char.IsDigit(ch))\n return 1;\n return 0;\n }\n \n public int Compare(string left, string right)\n {\n if(string.IsNullOrEmpty(left)\n || string.IsNullOrEmpty(right)) {\n return defaultComparer.Compare(left, right);\n }\n \n var leftChar = left[0];\n var rightChar = right[0];\n var leftOrder = OrderOfChar(leftChar);\n var rightOrder = OrderOfChar(rightChar);\n \n if(leftOrder == rightOrder)\n return defaultComparer.Compare(left, right);\n \n if(leftOrder > rightOrder)\n return 1;\n return -1;\n }\n}\n\npublic static List<string> SortSpecialCharactersNumbersAlphabet(IEnumerable<string> input)\n{\n return input.OrderBy(_ => _, new SpecialCharactersNumbersLettersComparer())\n .ToList();\n}\n Console.WriteLine(string.Join(\", \",\n SortSpecialCharactersNumbersAlphabet(new [] {\n \"Hello\", \"#Test\", \"@Red\", \"&While\", \"123@Test\", \"@123Test\", \"%54Sun\", \"Dom\", \"Left\"})));\n @123Test, @Red, &While, #Test, %54Sun, 123@Test, Dom, Hello, Left\n" }, { "answer_id": 74509750, "author": "Klaus Gütter", "author_id": 2142950, "author_profile": "https://Stackoverflow.com/users/2142950", "pm_score": 1, "selected": false, "text": "OrderBy var input = new[] { \"Hello\", \"#Test\", \"@Red\", \"&While\", \"123@Test\", \"@123Test\", \"%54Sun\", \"Dom\", \"Left\" };\nforeach (var s in input.OrderBy(x => x)) Console.WriteLine(s);\n @123Test\n@Red\n&While\n#Test\n%54Sun\n123@Test\nDom\nHello\nLeft\n OrderBy(x => x, StringComparer.InvariantCulture)" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17260151/" ]
74,509,467
<p>I have a ReportStatusEntity class as shown below:</p> <pre><code>public class ReportsStatusEntity { public string PolicyNumber { get; set; } public string ClientName { get; set; } public bool HasIndividualBrokers { get; set; } } </code></pre> <p>Let's say I have the following list of <code>List&lt;ReportStatusEntity&gt;()</code>:</p> <pre><code>{PolicyNumber = 1, ClientName = &quot;John Doe&quot;, HasIndividualBrokers = True}, {PolicyNumber = 1, ClientName = &quot;Sarah Doe&quot;, HasIndividualBrokers = True}, {PolicyNumber = 2, ClientName = &quot;Paul Smith&quot;, HasIndividualBrokers = False}, {PolicyNumber = 3, ClientName = &quot;Ryan Johnson&quot;, HasIndividualBrokers = False} </code></pre> <p>I want to group by PolicyNumber, then concatenate the ClientNames having same PolicyNumber with '&amp;'.</p> <p>The grouping should be something like this:</p> <pre><code>{PolicyNumber = 1, ReportStatusEntity = (PolicyNumber = 1, ClientName = &quot;John Doe &amp; Sarah Doe&quot;, HasIndividualBrokers = True)}, {PolicyNumber = 2, ReportStatusEntity = (PolicyNumber = 2, ClientName = &quot;Paul Smith&quot;, HasIndividualBrokers = False)}, {PolicyNumber = 3, ReportStatusEntity = (PolicyNumber = 3, ClientName = &quot;Ryan Johnson&quot;, HasIndividualBrokers = False)} </code></pre> <p>How can this be done in C# using LINQ? Thank you.</p>
[ { "answer_id": 74509643, "author": "Siegfried.V", "author_id": 7310000, "author_profile": "https://Stackoverflow.com/users/7310000", "pm_score": 1, "selected": false, "text": "List<List<ReportStatusEntity>> listReportStatusEntityGroupped = this.yourList.GroupBy(u => new { u.PolicyNumber,u.HasIndividualBrokers })\n .Select(grp => grp.ToList())\n .ToList();\n new { u.PolicyNumber } List<List<ReportStatusEntity>> List<ReportStatusEntity> outputList=new List<ReportStatusEntity>();\nforeach(List<ReportStatusEntity> listReportInGroup in listReportStatusEntityGroupped)\n{\n ReportStatusEntity newReport = new ReportStatusEntity\n {\n PolicyNumber=listReportInGroup[0].PolicyNumber,\n HasIndividualBrokers = listReportInGroup[0].HasIndividualBrokers,\n ClientName = string.Join(\" & \",listRepInGroup.Select(x=>x.ClientName)),\n };\n outputList.Add(newReport);\n}\n" }, { "answer_id": 74509662, "author": "cancan", "author_id": 18217440, "author_profile": "https://Stackoverflow.com/users/18217440", "pm_score": 1, "selected": false, "text": "public class ReportsStatusLastEntity\n{\n public int Id { get; set; }\n public string PolicyNumber { get; set; }\n public string ClientName { get; set; }\n public bool HasIndividualBrokers { get; set; }\n}\n List <ReportsStatusLastEntity> liste= new List<ReportsStatusLastEntity>()" }, { "answer_id": 74509666, "author": "Orkad", "author_id": 8656043, "author_profile": "https://Stackoverflow.com/users/8656043", "pm_score": 3, "selected": true, "text": "var list = new List<ReportsStatusEntity>()\n{\n new ReportsStatusEntity{PolicyNumber = \"1\", ClientName = \"John Doe\", HasIndividualBrokers = true},\n new ReportsStatusEntity{PolicyNumber = \"1\", ClientName = \"Sarah Doe\", HasIndividualBrokers = true},\n new ReportsStatusEntity{PolicyNumber = \"2\", ClientName = \"Paul Smith\", HasIndividualBrokers = false},\n new ReportsStatusEntity{PolicyNumber = \"3\", ClientName = \"Ryan Johnson\", HasIndividualBrokers = false}\n};\n\nvar results = list.GroupBy(r => r.PolicyNumber)\n .Select(g => new\n {\n PolicyNumber = g.Key,\n // string.Join will not work if its against a database with sql\n ClientNames = string.Join(\" & \", g.Select(r => r.ClientName)),\n });\n\nforeach (var result in results)\n{\n Console.WriteLine($\"Policy {result.PolicyNumber}: {result.ClientNames}\");\n}\n\n// -- Outputs --\n// Policy 1: John Doe & Sarah Doe\n// Policy 2: Paul Smith\n// Policy 3: Ryan Johnson\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3162879/" ]
74,509,503
<p>I can't fully understand how this argument affects the functionality of the <code>permutedims</code> function. I read the <a href="https://docs.julialang.org/en/v1/base/arrays/#Base.permutedims" rel="nofollow noreferrer">official doc for this function</a> many times:</p> <blockquote> <p>permutedims(A::AbstractArray, perm) Permute the dimensions of array A. perm is a vector or a tuple of length ndims(A) specifying the permutation.</p> </blockquote> <p>The first point that comes bold to me is that the <code>perm</code> can be a <code>Tuple</code> or a <code>Vector</code> <strong>of length <code>ndims(A)</code></strong>. So if the <code>A</code> is a 3D Array, then <code>length(perm)==3</code> and so on. But, I can't understand how the permutation part takes place.<br /> Then, Let's consider a similar example to what they brought in the doc:</p> <pre><code>julia&gt; A = reshape(Vector(1:18), (3,2,3)) 3×2×3 Array{Int64, 3}: [:, :, 1] = 1 4 2 5 3 6 [:, :, 2] = 7 10 8 11 9 12 [:, :, 3] = 13 16 14 17 15 18 julia&gt; permutedims(A, (3, 2, 1)) 3×2×3 Array{Int64, 3}: [:, :, 1] = 1 4 7 10 13 16 [:, :, 2] = 2 5 8 11 14 17 [:, :, 3] = 3 6 9 12 15 18 </code></pre> <p>Since the above script is a little bit long in visualization, and hard to follow, I provided the results beside each other in the following picture:</p> <p><a href="https://i.stack.imgur.com/FT6jz.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FT6jz.jpg" alt="enter image description here" /></a></p> <p>I can see, for example, the first element of each <code>A</code>'s inner Matrix comes in the first column of each inner matrix of <code>permutedims</code>'s result. But I can't understand how the <code>perm=(3, 2, 1)</code> is doing that! How should I interpret the values of the <code>perm</code> argument (here, <code>(3, 2, 1)</code>)? <strong>And, for me it gets much harder to figure it out when I try another example of <code>A</code> with different <code>ndims</code> and <code>size</code>!</strong> I asked for an explanation about the <code>perm</code> <a href="https://stackoverflow.com/a/74430027/11747148">here</a>, But I couldn't understand it either. So I decided to ask about it as a stand-alone question.</p>
[ { "answer_id": 74509643, "author": "Siegfried.V", "author_id": 7310000, "author_profile": "https://Stackoverflow.com/users/7310000", "pm_score": 1, "selected": false, "text": "List<List<ReportStatusEntity>> listReportStatusEntityGroupped = this.yourList.GroupBy(u => new { u.PolicyNumber,u.HasIndividualBrokers })\n .Select(grp => grp.ToList())\n .ToList();\n new { u.PolicyNumber } List<List<ReportStatusEntity>> List<ReportStatusEntity> outputList=new List<ReportStatusEntity>();\nforeach(List<ReportStatusEntity> listReportInGroup in listReportStatusEntityGroupped)\n{\n ReportStatusEntity newReport = new ReportStatusEntity\n {\n PolicyNumber=listReportInGroup[0].PolicyNumber,\n HasIndividualBrokers = listReportInGroup[0].HasIndividualBrokers,\n ClientName = string.Join(\" & \",listRepInGroup.Select(x=>x.ClientName)),\n };\n outputList.Add(newReport);\n}\n" }, { "answer_id": 74509662, "author": "cancan", "author_id": 18217440, "author_profile": "https://Stackoverflow.com/users/18217440", "pm_score": 1, "selected": false, "text": "public class ReportsStatusLastEntity\n{\n public int Id { get; set; }\n public string PolicyNumber { get; set; }\n public string ClientName { get; set; }\n public bool HasIndividualBrokers { get; set; }\n}\n List <ReportsStatusLastEntity> liste= new List<ReportsStatusLastEntity>()" }, { "answer_id": 74509666, "author": "Orkad", "author_id": 8656043, "author_profile": "https://Stackoverflow.com/users/8656043", "pm_score": 3, "selected": true, "text": "var list = new List<ReportsStatusEntity>()\n{\n new ReportsStatusEntity{PolicyNumber = \"1\", ClientName = \"John Doe\", HasIndividualBrokers = true},\n new ReportsStatusEntity{PolicyNumber = \"1\", ClientName = \"Sarah Doe\", HasIndividualBrokers = true},\n new ReportsStatusEntity{PolicyNumber = \"2\", ClientName = \"Paul Smith\", HasIndividualBrokers = false},\n new ReportsStatusEntity{PolicyNumber = \"3\", ClientName = \"Ryan Johnson\", HasIndividualBrokers = false}\n};\n\nvar results = list.GroupBy(r => r.PolicyNumber)\n .Select(g => new\n {\n PolicyNumber = g.Key,\n // string.Join will not work if its against a database with sql\n ClientNames = string.Join(\" & \", g.Select(r => r.ClientName)),\n });\n\nforeach (var result in results)\n{\n Console.WriteLine($\"Policy {result.PolicyNumber}: {result.ClientNames}\");\n}\n\n// -- Outputs --\n// Policy 1: John Doe & Sarah Doe\n// Policy 2: Paul Smith\n// Policy 3: Ryan Johnson\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11747148/" ]
74,509,525
<p>I try to create an empty array into which I can add other arrays and get a matrix:</p> <pre class="lang-python prettyprint-override"><code>arr = np.array([]) arr = np.append(arr, [1, 2]) arr = np.append(arr, [3, 4]) </code></pre> <p>As a result, I get a one-dimensional array:</p> <pre class="lang-python prettyprint-override"><code>array([1., 2., 3., 4.]) </code></pre> <p>Expected result:</p> <pre class="lang-python prettyprint-override"><code>array([[1., 2.], [3., 4.]]) </code></pre> <p>I tried to init an array as multidimensional <code>arr = np.array([[]])</code>, and not append but concatenate arrays <code>arr = np.concatenate((arr, [1, 2]), axis=0)</code>. Both options did not work, the result was again a one-dimensional array.</p> <p>So, what's the best way to fix this and get a two-dimensional array as a result?</p>
[ { "answer_id": 74509597, "author": "M472", "author_id": 2122753, "author_profile": "https://Stackoverflow.com/users/2122753", "pm_score": 0, "selected": false, "text": "np.array np.array([[1., 2.], [3., 4.]])\n np.zeros() arr = np.zeros((2, 2))\narr[0, :] = [1, 2]\narr[1, :] = [3, 4]\n np.stack np.stack([[1, 2], [3, 4]])\n np.append arr = np.zeros((0, 2)) # Create an empty array with a row length of 2\narr = np.append(arr, [[1, 2]], axis=0)\narr = np.append(arr, [[3, 4]], axis=0)\n" }, { "answer_id": 74509796, "author": "tdelaney", "author_id": 642070, "author_profile": "https://Stackoverflow.com/users/642070", "pm_score": 1, "selected": false, "text": "np.append >>> arr=np.zeros((0,2), dtype=int)\n>>> arr = np.append(arr, [[1,2]], axis=0)\n>>> arr = np.append(arr, [[3,4]], axis=0)\n>>> arr\narray([[1, 2],\n [3, 4]])\n" }, { "answer_id": 74509916, "author": "hpaulj", "author_id": 901925, "author_profile": "https://Stackoverflow.com/users/901925", "pm_score": 2, "selected": true, "text": "In [687]: alist = []\n ...: alist.append([1,2])\n ...: alist.append([3,4])\n ...: arr = np.array(alist) \nIn [688]: alist\nOut[688]: [[1, 2], [3, 4]] \nIn [689]: arr\nOut[689]: \narray([[1, 2],\n [3, 4]])\n np.append np.concatenate np.append axis axis np.concatenate concatenate np.empty((1000,20,30)) np.array([])" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509525", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20555603/" ]
74,509,529
<p>`Hi guys, I need help with react js, what happens is that I want to move an item from a specific list to the last place, but when I move it, it doesn't load the data I had before, unfortunately I'm very new to react js and ps isn't I know all of them, so I turn to this community in search of help and soon I will upload the code and I hope you can help me, thanks.</p> <pre><code>const [categories, setCategories] = useState&lt;CategoriesWithSubsCategories&gt;() const listSelectCategory = categories?.list.map(cat =\&gt; { const { category, id } = cat.category return { value: id, label: category } }).filter(cat =\&gt; cat.label !== 'Otros') listSelectCategory?.sort((a, b) =\&gt; a.label.localeCompare(b.label)).push({ value: 'Otros', label: 'Otros' })`` </code></pre> <p>As you have seen above, try using the filter attribute to filter that category and then use the push attribute to add it to the end of the list, it worked but not how it should work because the category that I want to put at the end of the list should bring me some subcategories but it doesn't It does and that is where my problem lies.`</p>
[ { "answer_id": 74509597, "author": "M472", "author_id": 2122753, "author_profile": "https://Stackoverflow.com/users/2122753", "pm_score": 0, "selected": false, "text": "np.array np.array([[1., 2.], [3., 4.]])\n np.zeros() arr = np.zeros((2, 2))\narr[0, :] = [1, 2]\narr[1, :] = [3, 4]\n np.stack np.stack([[1, 2], [3, 4]])\n np.append arr = np.zeros((0, 2)) # Create an empty array with a row length of 2\narr = np.append(arr, [[1, 2]], axis=0)\narr = np.append(arr, [[3, 4]], axis=0)\n" }, { "answer_id": 74509796, "author": "tdelaney", "author_id": 642070, "author_profile": "https://Stackoverflow.com/users/642070", "pm_score": 1, "selected": false, "text": "np.append >>> arr=np.zeros((0,2), dtype=int)\n>>> arr = np.append(arr, [[1,2]], axis=0)\n>>> arr = np.append(arr, [[3,4]], axis=0)\n>>> arr\narray([[1, 2],\n [3, 4]])\n" }, { "answer_id": 74509916, "author": "hpaulj", "author_id": 901925, "author_profile": "https://Stackoverflow.com/users/901925", "pm_score": 2, "selected": true, "text": "In [687]: alist = []\n ...: alist.append([1,2])\n ...: alist.append([3,4])\n ...: arr = np.array(alist) \nIn [688]: alist\nOut[688]: [[1, 2], [3, 4]] \nIn [689]: arr\nOut[689]: \narray([[1, 2],\n [3, 4]])\n np.append np.concatenate np.append axis axis np.concatenate concatenate np.empty((1000,20,30)) np.array([])" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18600473/" ]
74,509,535
<p>I have the result of a long lasting operation, a MongoDB query:</p> <blockquote> <p>const a = collection.find({}).project({ name: 1 }).toArray()</p> </blockquote> <p>It has the type of Promise&lt;Document[]&gt;</p> <p>I would do a transformation, but it is not possible:</p> <blockquote> <p>let a2 = a.map((i) =&gt; {i._id, { name: i.name }})</p> </blockquote> <p>In Vapor / Swift, there is a <code>map</code> not only for array, but also for promises, what about in JS / TS?</p> <p>How can I apply further operation on the <code>Promise&lt;Document[]&gt;</code>?</p>
[ { "answer_id": 74556329, "author": "Shilpe Saxena", "author_id": 13265113, "author_profile": "https://Stackoverflow.com/users/13265113", "pm_score": 0, "selected": false, "text": "const promise = new Promise((resolved, rejected) => {\nsetTimeout(() =>{\nconsole.log(rejected)\n},1000)\n})\npromise.then((value) => console.log(value)).catch((err) => console.log(err));\n return" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/239219/" ]
74,509,540
<pre><code>ListView( scrollDirection: Axis.horizontal, children: [ GestureDetector( onTap: () { setState(() { selectedCard = index; }); }, child: Card( elevation: 5, shape: RoundedRectangleBorder( side: BorderSide( color: selectedCard == index ? Colors.red : Colors.transparent, width: 2.0, ), borderRadius: BorderRadius.circular(8.0), ), child: Padding( padding: const EdgeInsets.symmetric( horizontal: 20, ), child: Center( child: Text( 'Painting', style: artStyle, )), ), ), </code></pre> <p>How can I show any color border like blue, red when a card is clicked, and when clicking another card, how do I make the border around the first clicked card disappear and move to the next?</p>
[ { "answer_id": 74556329, "author": "Shilpe Saxena", "author_id": 13265113, "author_profile": "https://Stackoverflow.com/users/13265113", "pm_score": 0, "selected": false, "text": "const promise = new Promise((resolved, rejected) => {\nsetTimeout(() =>{\nconsole.log(rejected)\n},1000)\n})\npromise.then((value) => console.log(value)).catch((err) => console.log(err));\n return" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17906689/" ]
74,509,629
<p>I have a class <code>Circle</code></p> <pre class="lang-py prettyprint-override"><code>class Circle: def __init__(self, R: float): self.R = R @property def A(self): return 3.14*self.R**2 # Annotation: Circle(R: float) -&gt; None </code></pre> <p>But I want two ways to create an instance of this class using <a href="https://stackoverflow.com/questions/2965271/forced-naming-of-parameters-in-python">explicit arguments</a></p> <ol> <li>Given the radius <code>R</code>: <code>Circle(R = 1)</code></li> <li>Given the diameter <code>D</code>: <code>Circle(D = 2)</code></li> </ol> <p>Then I can do it</p> <pre class="lang-py prettyprint-override"><code>class Circle: def __init__(self, **kwargs): if &quot;R&quot; in kwargs: self.R = kwargs[&quot;R&quot;] elif &quot;D&quot; in kwargs: self.R = kwargs[&quot;D&quot;]/2 # Annotation: Circle(kwargs: Any) -&gt; None </code></pre> <p>But the annotation of this <code>__init__</code> gives no information that:</p> <ul> <li>The possible arguments are <code>R</code> and <code>D</code></li> <li>The types of <code>R</code> and <code>D</code> are float.</li> </ul> <p><strong>Question:</strong> How can inform the user that this class accepts two inputs? And how do I implement it in a clean code way?</p>
[ { "answer_id": 74509732, "author": "dskrypa", "author_id": 19070573, "author_profile": "https://Stackoverflow.com/users/19070573", "pm_score": 2, "selected": false, "text": "class Circle:\n def __init__(self, *, radius: float | None = None, diameter: float | None = None):\n if radius is diameter is None or None not in (radius, diameter):\n raise ValueError('radius xor diameter is required')\n elif radius is not None:\n self.radius = radius\n else:\n self.radius = diameter / 2\n **kwargs None from __future__ import annotations\n\nclass Circle:\n def __init__(self, radius: float):\n self.radius = radius\n\n @classmethod\n def from_diameter(cls, diameter: float) -> Circle:\n return cls(diameter / 2)\n typing.overload **kwargs" }, { "answer_id": 74509996, "author": "Gui Reis", "author_id": 13974761, "author_profile": "https://Stackoverflow.com/users/13974761", "pm_score": 2, "selected": false, "text": "__init__ def barplot(\n x=None, y=None,\n hue=None, data=None,\n order=None, hue_order=None,\n estimator=np.mean, ci=95, n_boot=1000, units=None, seed=None,\n orient=None, color=None, palette=None, saturation=.75,\n errcolor=\".26\", errwidth=None, capsize=None, dodge=True,\n ax=None,\n **kwargs\n):\n pass\n None class Foo:\n def __init__(self, d: float = None, r: float = 0) -> None:\n self.R = r\n if d is not None:\n self.R = d/2\n class Foo:\n r\"\"\"Some description for Class.\"\"\"\n\n def __init__(self, d: float = None, r: float = 0) -> None:\n r\"\"\"Some description.\n\n ### Parameters\n ``d``: float -- description\n ``r``: float -- description\n \"\"\"\n self.r = r\n if d != None:\n self.R = d/2\n" }, { "answer_id": 74536813, "author": "Daniil Fajnberg", "author_id": 19770795, "author_profile": "https://Stackoverflow.com/users/19770795", "pm_score": 3, "selected": true, "text": "typing.overload * float math.nan float float float float | None or int bool ^ math.isnan from math import isnan, nan\nfrom typing import overload\n\n\nclass Circle:\n @overload\n def __init__(self, *, radius: float) -> None:\n ...\n\n @overload\n def __init__(self, *, diameter: float) -> None:\n ...\n\n def __init__(self, *, radius: float = nan, diameter: float = nan) -> None:\n \"\"\"Takes either a `radius` or a `diameter` but not both.\"\"\"\n if not isnan(radius) ^ isnan(diameter):\n raise TypeError(\"Either radius or diameter required\")\n self.radius = radius if isnan(diameter) else diameter / 2\n\n\nif __name__ == \"__main__\":\n c1 = Circle(radius=1)\n c2 = Circle(diameter=2)\n assert c1.radius == c2.radius\n # Circle(radius=3.14, diameter=42) # error\n # Circle() # same error\n Circle reveal_type(Circle) mypy TypeError x if expr else y not not a ^ b a b" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8740854/" ]
74,509,646
<p>The problem is when I add a student record (append txt to my file) for the first time a major blank gap is added</p> <pre><code>username,passcode jack,Adidas123_ man,Adidas123_ kal,Adidas123_ ll,Adidas123_ </code></pre> <p>I have tried to use the .strip() function it did not seem to help , I was expecting my csv file to appear like this</p> <pre><code>username,passcode jack,Adidas123_ man,Ndidas123_ kal,Mdidas123_ ll,Zdidas123_ </code></pre> <pre><code>def add_user(): infile = open(&quot;students.csv&quot;, &quot;a&quot;) username = str((input('enter your username:'))) passcode = &quot;Adidas123_&quot; data1 = f&quot;\n{username},{passcode}&quot; data = data1.strip() # strips white space infile.write(data +&quot;\n&quot;) # appends to new line print('record added succesfully !') infile.close() </code></pre>
[ { "answer_id": 74509732, "author": "dskrypa", "author_id": 19070573, "author_profile": "https://Stackoverflow.com/users/19070573", "pm_score": 2, "selected": false, "text": "class Circle:\n def __init__(self, *, radius: float | None = None, diameter: float | None = None):\n if radius is diameter is None or None not in (radius, diameter):\n raise ValueError('radius xor diameter is required')\n elif radius is not None:\n self.radius = radius\n else:\n self.radius = diameter / 2\n **kwargs None from __future__ import annotations\n\nclass Circle:\n def __init__(self, radius: float):\n self.radius = radius\n\n @classmethod\n def from_diameter(cls, diameter: float) -> Circle:\n return cls(diameter / 2)\n typing.overload **kwargs" }, { "answer_id": 74509996, "author": "Gui Reis", "author_id": 13974761, "author_profile": "https://Stackoverflow.com/users/13974761", "pm_score": 2, "selected": false, "text": "__init__ def barplot(\n x=None, y=None,\n hue=None, data=None,\n order=None, hue_order=None,\n estimator=np.mean, ci=95, n_boot=1000, units=None, seed=None,\n orient=None, color=None, palette=None, saturation=.75,\n errcolor=\".26\", errwidth=None, capsize=None, dodge=True,\n ax=None,\n **kwargs\n):\n pass\n None class Foo:\n def __init__(self, d: float = None, r: float = 0) -> None:\n self.R = r\n if d is not None:\n self.R = d/2\n class Foo:\n r\"\"\"Some description for Class.\"\"\"\n\n def __init__(self, d: float = None, r: float = 0) -> None:\n r\"\"\"Some description.\n\n ### Parameters\n ``d``: float -- description\n ``r``: float -- description\n \"\"\"\n self.r = r\n if d != None:\n self.R = d/2\n" }, { "answer_id": 74536813, "author": "Daniil Fajnberg", "author_id": 19770795, "author_profile": "https://Stackoverflow.com/users/19770795", "pm_score": 3, "selected": true, "text": "typing.overload * float math.nan float float float float | None or int bool ^ math.isnan from math import isnan, nan\nfrom typing import overload\n\n\nclass Circle:\n @overload\n def __init__(self, *, radius: float) -> None:\n ...\n\n @overload\n def __init__(self, *, diameter: float) -> None:\n ...\n\n def __init__(self, *, radius: float = nan, diameter: float = nan) -> None:\n \"\"\"Takes either a `radius` or a `diameter` but not both.\"\"\"\n if not isnan(radius) ^ isnan(diameter):\n raise TypeError(\"Either radius or diameter required\")\n self.radius = radius if isnan(diameter) else diameter / 2\n\n\nif __name__ == \"__main__\":\n c1 = Circle(radius=1)\n c2 = Circle(diameter=2)\n assert c1.radius == c2.radius\n # Circle(radius=3.14, diameter=42) # error\n # Circle() # same error\n Circle reveal_type(Circle) mypy TypeError x if expr else y not not a ^ b a b" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16698137/" ]
74,509,650
<p>I'm newbie in kafka streams. I need to create kafka streams dynamically from config files, which contain source and destination topic names. Is it possible to restart and stop Kafka streams? My goal is transferring messages from one topic to another periodically using kafka streams. I used spring cron job and tried closing and opening stream but I can't start it again when I close a stream. I got this error --&gt; The client is either already started or already stopped, cannot re-start. I'm writing the code in java</p> <pre><code> +--------------+ +&lt;----- | Created (0) | | +-----+--------+ | | | v | +----+--+------+ | | Re- | +&lt;----- | Balancing (1)| --------&gt;+ | +-----+-+------+ | | | ^ | | v | | | +--------------+ v | | Running (2) | --------&gt;+ | +------+-------+ | | | | | v | | +------+-------+ +----+-------+ +-----&gt; | Pending |&lt;--- | Error (5) | | Shutdown (3) | +------------+ +------+-------+ | v +------+-------+ | Not | | Running (4) | +--------------+ </code></pre>
[ { "answer_id": 74509732, "author": "dskrypa", "author_id": 19070573, "author_profile": "https://Stackoverflow.com/users/19070573", "pm_score": 2, "selected": false, "text": "class Circle:\n def __init__(self, *, radius: float | None = None, diameter: float | None = None):\n if radius is diameter is None or None not in (radius, diameter):\n raise ValueError('radius xor diameter is required')\n elif radius is not None:\n self.radius = radius\n else:\n self.radius = diameter / 2\n **kwargs None from __future__ import annotations\n\nclass Circle:\n def __init__(self, radius: float):\n self.radius = radius\n\n @classmethod\n def from_diameter(cls, diameter: float) -> Circle:\n return cls(diameter / 2)\n typing.overload **kwargs" }, { "answer_id": 74509996, "author": "Gui Reis", "author_id": 13974761, "author_profile": "https://Stackoverflow.com/users/13974761", "pm_score": 2, "selected": false, "text": "__init__ def barplot(\n x=None, y=None,\n hue=None, data=None,\n order=None, hue_order=None,\n estimator=np.mean, ci=95, n_boot=1000, units=None, seed=None,\n orient=None, color=None, palette=None, saturation=.75,\n errcolor=\".26\", errwidth=None, capsize=None, dodge=True,\n ax=None,\n **kwargs\n):\n pass\n None class Foo:\n def __init__(self, d: float = None, r: float = 0) -> None:\n self.R = r\n if d is not None:\n self.R = d/2\n class Foo:\n r\"\"\"Some description for Class.\"\"\"\n\n def __init__(self, d: float = None, r: float = 0) -> None:\n r\"\"\"Some description.\n\n ### Parameters\n ``d``: float -- description\n ``r``: float -- description\n \"\"\"\n self.r = r\n if d != None:\n self.R = d/2\n" }, { "answer_id": 74536813, "author": "Daniil Fajnberg", "author_id": 19770795, "author_profile": "https://Stackoverflow.com/users/19770795", "pm_score": 3, "selected": true, "text": "typing.overload * float math.nan float float float float | None or int bool ^ math.isnan from math import isnan, nan\nfrom typing import overload\n\n\nclass Circle:\n @overload\n def __init__(self, *, radius: float) -> None:\n ...\n\n @overload\n def __init__(self, *, diameter: float) -> None:\n ...\n\n def __init__(self, *, radius: float = nan, diameter: float = nan) -> None:\n \"\"\"Takes either a `radius` or a `diameter` but not both.\"\"\"\n if not isnan(radius) ^ isnan(diameter):\n raise TypeError(\"Either radius or diameter required\")\n self.radius = radius if isnan(diameter) else diameter / 2\n\n\nif __name__ == \"__main__\":\n c1 = Circle(radius=1)\n c2 = Circle(diameter=2)\n assert c1.radius == c2.radius\n # Circle(radius=3.14, diameter=42) # error\n # Circle() # same error\n Circle reveal_type(Circle) mypy TypeError x if expr else y not not a ^ b a b" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10550818/" ]
74,509,657
<p>I'm not sure why my code isn't fully printing. It isn't printing the quadrants.</p> <p>Here are my instructions:</p> <ul> <li>You are writing a program that checks if a point (a,b) is inside a circle of radius R that is centered on the point (c,d).</li> </ul> <p>-a,b,c,d,R are all integers entered from the keyboard -Do not allow negative R values to be entered -The output can be a simple statement indicating if the (a,b) point is “In the Circle”, “Out of the Circle”, “On the Circle” -Also output the Quadrant (I,II,III, IV) that the point (a,b) is located in. If the point happens to be on either the x or y axis, then output which axis it is on. -Your program is to continue forever until a radius of 0 is entered.</p> <p>Note: If you are wondering about how to compute the distance between 2 points…. use the Pythagorean Theorem</p> <p>Here's my code:</p> <pre><code>import math while True: a= int(input(&quot;Please enter the value of a:&quot;)) b= int(input(&quot;Please enter the value of b:&quot;)) c= int(input(&quot;Please enter the value of c:&quot;)) d= int(input(&quot;Please enter the value of d:&quot;)) r= int(input(&quot;Please enter the value of R:&quot;)) #XI= c, Y1= d .... X2= a, Y2= b xs= ((a)-c)**2 ys= ((b)-d)**2 together= xs+ys distance= math.sqrt(together) if distance &gt; r: print(&quot;Out of the circle&quot;) if distance &lt; r: print(&quot;In the circle&quot;) if distance == r: print(&quot;On the circle&quot;) #If the point lies on the x or y axis: if a == 0: print(&quot;On y axis&quot;) if b == 0: print(&quot;On x axis&quot;) #Quadrant I: if a &lt; r &lt; 0 and b &lt; r &lt; 0: print(&quot;Quadrant I&quot;) #Quadrant II: if -a &lt; r &lt; 0 and b &lt; r &lt; 0: print(&quot;Quadrant II&quot;) #Quadrant III: if -a &lt; r &lt; 0 and -b &lt; r &lt; 0: print(&quot;Quadrant III&quot;) #Quadrant IV: if a &lt; r &lt; 0 and -b &lt; r &lt; 0: print(&quot;Quadrant IV&quot;) if r == -r or r == 0: break </code></pre>
[ { "answer_id": 74509732, "author": "dskrypa", "author_id": 19070573, "author_profile": "https://Stackoverflow.com/users/19070573", "pm_score": 2, "selected": false, "text": "class Circle:\n def __init__(self, *, radius: float | None = None, diameter: float | None = None):\n if radius is diameter is None or None not in (radius, diameter):\n raise ValueError('radius xor diameter is required')\n elif radius is not None:\n self.radius = radius\n else:\n self.radius = diameter / 2\n **kwargs None from __future__ import annotations\n\nclass Circle:\n def __init__(self, radius: float):\n self.radius = radius\n\n @classmethod\n def from_diameter(cls, diameter: float) -> Circle:\n return cls(diameter / 2)\n typing.overload **kwargs" }, { "answer_id": 74509996, "author": "Gui Reis", "author_id": 13974761, "author_profile": "https://Stackoverflow.com/users/13974761", "pm_score": 2, "selected": false, "text": "__init__ def barplot(\n x=None, y=None,\n hue=None, data=None,\n order=None, hue_order=None,\n estimator=np.mean, ci=95, n_boot=1000, units=None, seed=None,\n orient=None, color=None, palette=None, saturation=.75,\n errcolor=\".26\", errwidth=None, capsize=None, dodge=True,\n ax=None,\n **kwargs\n):\n pass\n None class Foo:\n def __init__(self, d: float = None, r: float = 0) -> None:\n self.R = r\n if d is not None:\n self.R = d/2\n class Foo:\n r\"\"\"Some description for Class.\"\"\"\n\n def __init__(self, d: float = None, r: float = 0) -> None:\n r\"\"\"Some description.\n\n ### Parameters\n ``d``: float -- description\n ``r``: float -- description\n \"\"\"\n self.r = r\n if d != None:\n self.R = d/2\n" }, { "answer_id": 74536813, "author": "Daniil Fajnberg", "author_id": 19770795, "author_profile": "https://Stackoverflow.com/users/19770795", "pm_score": 3, "selected": true, "text": "typing.overload * float math.nan float float float float | None or int bool ^ math.isnan from math import isnan, nan\nfrom typing import overload\n\n\nclass Circle:\n @overload\n def __init__(self, *, radius: float) -> None:\n ...\n\n @overload\n def __init__(self, *, diameter: float) -> None:\n ...\n\n def __init__(self, *, radius: float = nan, diameter: float = nan) -> None:\n \"\"\"Takes either a `radius` or a `diameter` but not both.\"\"\"\n if not isnan(radius) ^ isnan(diameter):\n raise TypeError(\"Either radius or diameter required\")\n self.radius = radius if isnan(diameter) else diameter / 2\n\n\nif __name__ == \"__main__\":\n c1 = Circle(radius=1)\n c2 = Circle(diameter=2)\n assert c1.radius == c2.radius\n # Circle(radius=3.14, diameter=42) # error\n # Circle() # same error\n Circle reveal_type(Circle) mypy TypeError x if expr else y not not a ^ b a b" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20277384/" ]
74,509,659
<p>I am currently learning how to utilize WebRTC in javascript.<br /> Here are the codes I wrote:</p> <p><strong>main.html</strong></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;header&gt; &lt;title&gt;video and audio&lt;/title&gt; &lt;style&gt; html { height: 100%; } body { min-height: 100%; height: 100%; margin: 0; } #video { height: 50%; width: 50%; border: 1px solid black; } #audio { height: 50%; width: 50%; border: 1px solid black; } &lt;/style&gt; &lt;/header&gt; &lt;body&gt; &lt;div id=&quot;video&quot;&gt;&lt;/div&gt; &lt;div id=&quot;audio&quot;&gt;&lt;/div&gt; &lt;/body&gt; &lt;script src=&quot;WebRTC.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt; &lt;/html&gt; </code></pre> <p><strong>WebRTC.js</strong></p> <pre><code>const constraints = {audio: true, video: {width: 1280, height: 70}} navigator.mediaDevices.getUserMedia(constraints) .then ( (mediaStream) =&gt; { console.log('success') const video = document.querySelector('#video'); video.srcObject = mediaStream; video.onloadedmetadata = () =&gt; {video.play();} }) .catch ( console.log('unsuccessful') ) </code></pre> <p>When I open it, it asks me permission to access my camera, and the console returns &quot;successful.&quot; So I think that the code is working fine However, the video is not displayed on the <code>&lt;div id=&quot;video&quot;&gt;</code>. I googled the solution, but I have come up with nothing yet. I would be appreciated it if you could help me find what I am missing here. Thank you very much.</p>
[ { "answer_id": 74509813, "author": "innocent", "author_id": 8405085, "author_profile": "https://Stackoverflow.com/users/8405085", "pm_score": 2, "selected": true, "text": "div video <video id=\"video\"></video>\n" }, { "answer_id": 74509815, "author": "SMAKSS", "author_id": 11908502, "author_profile": "https://Stackoverflow.com/users/11908502", "pm_score": 2, "selected": false, "text": "<video /> <div /> <div id=\"video\"></div>\n<div id=\"audio\"></div>\n <video autoplay=\"true\"></video>\n const constraints = {\n audio: true,\n video: {\n width: 1280,\n height: 70\n }\n}\n\nnavigator.mediaDevices.getUserMedia(constraints)\n .then(\n (mediaStream) => {\n console.log('success')\n const video = document.querySelector('video');\n video.srcObject = mediaStream;\n video.onloadedmetadata = () => {\n video.play();\n }\n })\n .catch(\n console.log('unsuccessful')\n ) html {\n height: 100%;\n}\n\nbody {\n min-height: 100%;\n height: 100%;\n margin: 0;\n}\n\nvideo {\n height: 50%;\n width: 50%;\n border: 1px solid black;\n} <video autoplay=\"true\"></video>" }, { "answer_id": 74520818, "author": "Naju Bhadarka", "author_id": 20497393, "author_profile": "https://Stackoverflow.com/users/20497393", "pm_score": 0, "selected": false, "text": "<div> <video> <div id=\"video-div\">\n <video id=\"video\" controls=\"true\" autoplay=\"true\"></video> \n</div>\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19920392/" ]
74,509,661
<p>I have little problem with dynamically add data to the HTML from SQL Table..</p> <p>This is my loop</p> <pre><code>@foreach (var item in Model.ModulesSubStages) { &lt;div class=&quot;row&quot;&gt; &lt;div class=&quot;col-md-6&quot;&gt;&lt;a id=&quot;courseRedirect&quot; asp-page=&quot;/Site/Courses/@item.ModuleId/@item.Id&quot; class=&quot;w3-bar-item w3-button&quot;&gt; @item.StageName &lt;/a&gt;&lt;/div&gt; &lt;div class=&quot;col-md-6&quot;&gt; @foreach (var monit in Model.ProgressMonitor) { if (monit.UserId == Model._User.Id &amp;&amp; item.Id == monit.CourseSubStageId) { &lt;i class=&quot;bi bi-check-circle-fill&quot; id=&quot;@item.Id&quot; style=&quot;color:green;&quot;&gt;&lt;/i&gt; } else if (monit.UserId == Model._User.Id &amp;&amp; item.Id != monit.CourseSubStageId) { &lt;i class=&quot;bi bi-check-circle-fill&quot; id=&quot;@item.Id&quot; style=&quot;color:gray;&quot;&gt;&lt;/i&gt; } else { &lt;i class=&quot;bi bi-check-circle-fill&quot; id=&quot;@item.Id&quot; style=&quot;color:gray;&quot;&gt;&lt;/i&gt; } } &lt;/div&gt; &lt;/div&gt; } </code></pre> <p><strong>ModulesSubStages = 9 items</strong></p> <p><strong>ProgressMonitor - table when i insert data after completing some action</strong></p> <p><strong>Problem:</strong></p> <p>This loop result is:</p> <p><a href="https://i.stack.imgur.com/kjzed.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kjzed.png" alt="enter image description here" /></a></p> <p>I want to loop through entire table and mark green if it is completed, else gray, i dont want to print to the html multiple values per 1 record.</p> <p>-- UPDATE</p> <p>this is ProgressMonitor table structure:</p> <pre><code>SELECT [Id] ,[CourseId] ,[CourseStageId] ,[CourseSubStageId] ,[UserId] FROM [ProgressMonitor]; </code></pre>
[ { "answer_id": 74509712, "author": "cancan", "author_id": 18217440, "author_profile": "https://Stackoverflow.com/users/18217440", "pm_score": -1, "selected": false, "text": "@foreach (var item in Model.ModulesSubStages){\n <div class=\"row\">\n <div class=\"col-md-6\"><a id=\"courseRedirect\" asp-page=\"/Site/Courses/@item.ModuleId/@item.Id\" class=\"w3-bar-item w3-button\"> @item.StageName </a></div>\n <div class=\"col-md-6\">\n @foreach (var monit in Model.ProgressMonitor)\n {\n if (monit.UserId == Model._User.Id )\n {\n if (item.Id == monit.CourseSubStageId )\n {\n <i class=\"bi bi-check-circle-fill\" id=\"@item.Id\" style=\"color:green;\"></i>\n {\n break;\n }\n }\n else if (item.Id != monit.CourseSubStageId )\n {\n <i class=\"bi bi-check-circle-fill\" id=\"@item.Id\" style=\"color:gray;\"></i>\n {\n break;\n }\n }\n }\n \n }\n </div>\n </div>\n}\n" }, { "answer_id": 74515134, "author": "hamid reza shahshahani", "author_id": 8490617, "author_profile": "https://Stackoverflow.com/users/8490617", "pm_score": 2, "selected": true, "text": "@foreach (var item in Model.ModulesSubStages)\n{\n<div class=\"row\">\n <div class=\"col-md-6\"><a id=\"courseRedirect\" asp-page=\"/Site/Courses/@item.ModuleId/@item.Id\" class=\"w3-bar-item w3-button\"> @item.StageName </a></div>\n <div class=\"col-md-6\">\n @if (Model.ProgressMonitor.Any(a => a.UserId = Model._User.Id && item.Id == a.CourseSubStageId))\n {\n <i class=\"bi bi-check-circle-fill\" id=\"@item.Id\" style=\"color:green;\"></i>\n }\n else\n {\n <i class=\"bi bi-check-circle-fill\" id=\"@item.Id\" style=\"color:gray;\"></i>\n }\n </div>\n</div>\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15868779/" ]
74,509,682
<p>I have a folder in azure zen2 VAS In this folder i have files Vas_1.csv Vas_2.csv Vas_3.csv</p> <p>I have to load these files using pyspark dataframe in table VAS in delta with two additional column derived in runtime load date and file_name.</p> <p>Once the data is loaded in VAS table . Next day Few more files VAS_4.csv and VAS_5.csv comes into zen2 folder and now I have to load these two files in the same table VAS *Note the folder VAS in zen2 has 5 files now so for the second time load i have to skip the previously loaded file</p>
[ { "answer_id": 74509712, "author": "cancan", "author_id": 18217440, "author_profile": "https://Stackoverflow.com/users/18217440", "pm_score": -1, "selected": false, "text": "@foreach (var item in Model.ModulesSubStages){\n <div class=\"row\">\n <div class=\"col-md-6\"><a id=\"courseRedirect\" asp-page=\"/Site/Courses/@item.ModuleId/@item.Id\" class=\"w3-bar-item w3-button\"> @item.StageName </a></div>\n <div class=\"col-md-6\">\n @foreach (var monit in Model.ProgressMonitor)\n {\n if (monit.UserId == Model._User.Id )\n {\n if (item.Id == monit.CourseSubStageId )\n {\n <i class=\"bi bi-check-circle-fill\" id=\"@item.Id\" style=\"color:green;\"></i>\n {\n break;\n }\n }\n else if (item.Id != monit.CourseSubStageId )\n {\n <i class=\"bi bi-check-circle-fill\" id=\"@item.Id\" style=\"color:gray;\"></i>\n {\n break;\n }\n }\n }\n \n }\n </div>\n </div>\n}\n" }, { "answer_id": 74515134, "author": "hamid reza shahshahani", "author_id": 8490617, "author_profile": "https://Stackoverflow.com/users/8490617", "pm_score": 2, "selected": true, "text": "@foreach (var item in Model.ModulesSubStages)\n{\n<div class=\"row\">\n <div class=\"col-md-6\"><a id=\"courseRedirect\" asp-page=\"/Site/Courses/@item.ModuleId/@item.Id\" class=\"w3-bar-item w3-button\"> @item.StageName </a></div>\n <div class=\"col-md-6\">\n @if (Model.ProgressMonitor.Any(a => a.UserId = Model._User.Id && item.Id == a.CourseSubStageId))\n {\n <i class=\"bi bi-check-circle-fill\" id=\"@item.Id\" style=\"color:green;\"></i>\n }\n else\n {\n <i class=\"bi bi-check-circle-fill\" id=\"@item.Id\" style=\"color:gray;\"></i>\n }\n </div>\n</div>\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12673502/" ]
74,509,702
<p>How to read JSON object matching query params? I want to filter data for video urls which only contains query params from metadata column and replace it by the removing the query params.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>metadata</th> </tr> </thead> <tbody> <tr> <td>{&quot;video-url&quot;:&quot;xyz.com/video/xy4jnj?pubtool=oembed&quot;,&quot;provider&quot;:&quot;some-video&quot;,&quot;video-id&quot;:&quot;x8cse6q&quot;}</td> </tr> <tr> <td>{&quot;video-url&quot;:&quot;xyz.com/video/x8cse6q?pubtool=oembed&quot;,&quot;provider&quot;:&quot;some-video&quot;,&quot;video-id&quot;:x8cse6q}</td> </tr> <tr> <td>{&quot;video-url&quot;:&quot;xyz.com/video/x8cse6q&quot;,&quot;provider&quot;:&quot;some-video&quot;,&quot;video-id&quot;:&quot;x8cse6q&quot;}</td> </tr> </tbody> </table> </div> <pre><code>select * from content where metadata.video-url ilike %?pubtool% </code></pre> <p>Expected to return rows which consists of query param in the metadata column for the field video-url.</p>
[ { "answer_id": 74509712, "author": "cancan", "author_id": 18217440, "author_profile": "https://Stackoverflow.com/users/18217440", "pm_score": -1, "selected": false, "text": "@foreach (var item in Model.ModulesSubStages){\n <div class=\"row\">\n <div class=\"col-md-6\"><a id=\"courseRedirect\" asp-page=\"/Site/Courses/@item.ModuleId/@item.Id\" class=\"w3-bar-item w3-button\"> @item.StageName </a></div>\n <div class=\"col-md-6\">\n @foreach (var monit in Model.ProgressMonitor)\n {\n if (monit.UserId == Model._User.Id )\n {\n if (item.Id == monit.CourseSubStageId )\n {\n <i class=\"bi bi-check-circle-fill\" id=\"@item.Id\" style=\"color:green;\"></i>\n {\n break;\n }\n }\n else if (item.Id != monit.CourseSubStageId )\n {\n <i class=\"bi bi-check-circle-fill\" id=\"@item.Id\" style=\"color:gray;\"></i>\n {\n break;\n }\n }\n }\n \n }\n </div>\n </div>\n}\n" }, { "answer_id": 74515134, "author": "hamid reza shahshahani", "author_id": 8490617, "author_profile": "https://Stackoverflow.com/users/8490617", "pm_score": 2, "selected": true, "text": "@foreach (var item in Model.ModulesSubStages)\n{\n<div class=\"row\">\n <div class=\"col-md-6\"><a id=\"courseRedirect\" asp-page=\"/Site/Courses/@item.ModuleId/@item.Id\" class=\"w3-bar-item w3-button\"> @item.StageName </a></div>\n <div class=\"col-md-6\">\n @if (Model.ProgressMonitor.Any(a => a.UserId = Model._User.Id && item.Id == a.CourseSubStageId))\n {\n <i class=\"bi bi-check-circle-fill\" id=\"@item.Id\" style=\"color:green;\"></i>\n }\n else\n {\n <i class=\"bi bi-check-circle-fill\" id=\"@item.Id\" style=\"color:gray;\"></i>\n }\n </div>\n</div>\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10757984/" ]
74,509,703
<p>For example we have this code.</p> <pre><code>x = 1 y = 1 print(x is y) # TRUE print(id(x), id(y)) y = pow(10, 30, 10**30-1) # 1 print(type(y)) print(x, y, x is y) # FALSE </code></pre> <p>It`s return:</p> <pre><code>True 140516304938720 140516304938720 &lt;class 'int'&gt; 1 1 False </code></pre> <p>The last result is <strong>False</strong>. Please help me understand why this is happening? Result of function is 1, doesn`t it literal, which cach in python?</p> <p>If we change to</p> <pre><code>y = pow(1, 10) </code></pre> <p>It will return &quot;True&quot;.</p>
[ { "answer_id": 74563978, "author": "Amirali.Shr", "author_id": 19641783, "author_profile": "https://Stackoverflow.com/users/19641783", "pm_score": 0, "selected": false, "text": "x = [\"apple\", \"banana\"]\ny = [\"apple\", \"banana\"]\n\nprint(x is y) #False\nprint(x == y) #True\n" }, { "answer_id": 74673307, "author": "12201574", "author_id": 20184544, "author_profile": "https://Stackoverflow.com/users/20184544", "pm_score": -1, "selected": false, "text": "x = [\"apple\", \"banana\"]\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18212277/" ]
74,509,737
<p>I have a dataframe that looks like this.</p> <pre><code> Gene SNP Score 1 AKT3 rs2220276 6.5091 2 ARHGAP44 rs2220276 4.7194 3 BRINP2 rs16851037 3.2606 4 C12orf42 rs16851037 3.2563 5 CCDC122 rs11619756 4.3142 6 CCDC68 rs11619756 2.3614 </code></pre> <p>I want to transform the dataframe so it looks like this - essentially creating an extra column for each element in the <code>Gene</code> column that matches the <code>SNP</code> column.</p> <pre><code> Gene 1 SNP Gene 1 Score Gene 2 Gene 2 Score 1 AKT3 rs2220276 6.5091 ARHGAP44 4.7194 2 BRINP2 rs16851037 3.2606 C12orf42 3.2563 5 CCDC122 rs11619756 4.3142 CCDC68 2.3614 </code></pre> <p>How can I achieve this?</p> <pre><code>df &lt;- data.frame(Gene = c(&quot;AKT3&quot;, &quot;ARHGAP44&quot;, &quot;BRINP2&quot;, &quot;C12orf42&quot;, &quot;CCDC122&quot;,&quot;CCDC68&quot;) , &quot;SNP&quot; = c(&quot;rs2220276&quot;, &quot;rs2220276&quot;, &quot;rs16851037&quot;, &quot;rs16851037&quot;,&quot;rs11619756&quot;, &quot;rs11619756&quot;), Score = c(6.5091, 4.7194, 3.2606, 3.2563, 4.3142, 2.3614)) </code></pre>
[ { "answer_id": 74509808, "author": "deschen", "author_id": 2725773, "author_profile": "https://Stackoverflow.com/users/2725773", "pm_score": 0, "selected": false, "text": "library(tidyverse)\n\ndf %>%\n distinct(SNP, .keep_all = TRUE)\n\n Gene SNP Score\n1 AKT3 rs2220276 6.5091\n2 BRINP2 rs16851037 3.2606\n3 CCDC122 rs11619756 4.3142\n" }, { "answer_id": 74509895, "author": "langtang", "author_id": 4447540, "author_profile": "https://Stackoverflow.com/users/4447540", "pm_score": 2, "selected": true, "text": "pivot_wider() tidyr id \nlibrary(dplyr)\nlibrary(tidyr)\n\ndf %>% \n group_by(SNP) %>% \n mutate(id = row_number()) %>% \n ungroup() %>% \n pivot_wider(id_cols=SNP, names_from = id, values_from = c(Gene, Score))\n SNP Gene_1 Gene_2 Score_1 Score_2\n <chr> <chr> <chr> <dbl> <dbl>\n1 rs2220276 AKT3 ARHGAP44 6.51 4.72\n2 rs16851037 BRINP2 C12orf42 3.26 3.26\n3 rs11619756 CCDC122 CCDC68 4.31 2.36\n" }, { "answer_id": 74510030, "author": "Andre Wildberg", "author_id": 9462095, "author_profile": "https://Stackoverflow.com/users/9462095", "pm_score": 1, "selected": false, "text": "pivot_wider unnest_wider library(tidyr)\n\npivot_wider(df, SNP, values_from=c(Score, Gene), values_fn=list) |> \n unnest_wider(Score_, names_sep=\"\") |> \n unnest_wider(Gene_, names_sep=\"\")\n# A tibble: 3 × 5\n SNP Score_1 Score_2 Gene_1 Gene_2\n <chr> <dbl> <dbl> <chr> <chr>\n1 rs2220276 6.51 4.72 AKT3 ARHGAP44\n2 rs16851037 3.26 3.26 BRINP2 C12orf42\n3 rs11619756 4.31 2.36 CCDC122 CCDC68\n" }, { "answer_id": 74511643, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 0, "selected": false, "text": "dcast library(data.table)\ndcast(setDT(df), SNP ~ rowid(SNP), value.var = c(\"Gene\", \"Score\"))\nKey: <SNP>\n SNP Gene_1 Gene_2 Score_1 Score_2\n <char> <char> <char> <num> <num>\n1: rs11619756 CCDC122 CCDC68 4.3142 2.3614\n2: rs16851037 BRINP2 C12orf42 3.2606 3.2563\n3: rs2220276 AKT3 ARHGAP44 6.5091 4.7194\n pivot_wider library(tidyr)\nlibrary(dplyr)\ndf %>%\n mutate(rn = rowid(SNP)) %>% \n pivot_wider(names_from = rn, values_from = c(Gene, Score))\n# A tibble: 3 × 5\n SNP Gene_1 Gene_2 Score_1 Score_2\n <chr> <chr> <chr> <dbl> <dbl>\n1 rs2220276 AKT3 ARHGAP44 6.51 4.72\n2 rs16851037 BRINP2 C12orf42 3.26 3.26\n3 rs11619756 CCDC122 CCDC68 4.31 2.36\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1871399/" ]
74,509,753
<p>The following code is checking whether the user is in an input, textarea, or contenteditable. If that's the case <code>keys</code> should be emptied and the code should stop.</p> <pre><code>let keys: any[] = [] document.addEventListener('keypress', event =&gt; { if (event.key === ' ') return if (event.target === null) return // Should remove this? if (event.target.nodeName === 'INPUT' || event.target.nodeName === 'TEXTAREA' || event.target.isContentEditable) { keys = [] return } }) console.log(keys) </code></pre> <p>I'm getting this TypeScript error:</p> <pre><code>Property 'nodeName' does not exist on type 'EventTarget'. Property 'nodeName' does not exist on type 'EventTarget'. Property 'isContentEditable' does not exist on type 'EventTarget'. </code></pre> <p>Why is this and how to fix it?</p> <p>Live code: <a href="https://codesandbox.io/s/cover-image-forked-7n8z7w?file=/src/index.ts" rel="nofollow noreferrer">https://codesandbox.io/s/cover-image-forked-7n8z7w?file=/src/index.ts</a></p>
[ { "answer_id": 74509937, "author": "geoffrey", "author_id": 8225569, "author_profile": "https://Stackoverflow.com/users/8225569", "pm_score": 2, "selected": false, "text": "EventTarget HTMLElement Node if (!(event.target instanceof HTMLElement)) return;\n" }, { "answer_id": 74509953, "author": "Jared Smith", "author_id": 3757232, "author_profile": "https://Stackoverflow.com/users/3757232", "pm_score": 3, "selected": true, "text": "document.addEventListener('keypress', (evt: KeyboardEvent) => {\n const { target } = evt;\n // Note e.g. XHR requests can be event targets, no nodeName\n if (target instanceof HTMLElement) {\n console.log(target.nodeName);\n if (target.isContentEditable) {\n // now we're good to process as e.g. textarea\n }\n }\n});\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122536/" ]
74,509,778
<p>I am new to python and learning to make some basic tkinter apps in windows. I have defined a menubar and add one menu to it. Then added multiple labels to this menu, but when I click any button in the menu, all the commands are ran, I am wondering how to run only the clicked menu?</p> <h1>MWE</h1> <p><strong>(Problem: whichever menu I click, it runs all the menu labels)</strong></p> <pre class="lang-py prettyprint-override"><code>import tkinter as tk from tkinter import ttk,messagebox def show_child_win(win,text=''): win_child = tk.Toplevel(win) var_l1 = tk.StringVar() l1 = tk.Label(win_child,textvariable=var_l1) l1.grid(row=0, column=0) var_l1.set(text) win_child.after(3*1000,lambda: win_child.destroy()) win = tk.Tk() menubar = tk.Menu(win) menu = tk.Menu(menubar, tearoff=0) menubar.add_cascade(label=&quot;Scripts&quot;, menu=menu) dict_label_func = { 'function_01': lambda win: show_child_win(win,text='function_01'), 'function_02': lambda win: show_child_win(win,text='function_02'), 'last_function': lambda win: show_child_win(win,text='last_function') } for label, func in dict_label_func.items(): menu.add_command(label=label,command = lambda x=win: func(x)) win.config(menu=menubar) win.mainloop() </code></pre> <h1>How to make the code run only the function it supposed to do?</h1>
[ { "answer_id": 74509892, "author": "RandomCoder59", "author_id": 16765869, "author_profile": "https://Stackoverflow.com/users/16765869", "pm_score": 2, "selected": false, "text": "lambda func func() abcd abcd() abcd lambda abcd abcd: abcd() dict_label_func = {\n 'function_01': lambda: show_child_win(win, text='function_01'),\n 'function_02': lambda: show_child_win(win, text='function_02'),\n 'last_function': lambda: show_child_win(win, text='last_function')\n}\n\nfor label, func in dict_label_func.items():\n menu.add_command(label=label,command = func)\n" }, { "answer_id": 74510186, "author": "dallascow", "author_id": 19853940, "author_profile": "https://Stackoverflow.com/users/19853940", "pm_score": 1, "selected": true, "text": "import tkinter as tk\nfrom tkinter import ttk,messagebox\n\ndef show_child_win(win,text=''):\n win_child = tk.Toplevel(win)\n\n var_l1 = tk.StringVar()\n l1 = tk.Label(win_child,textvariable=var_l1)\n l1.grid(row=0, column=0)\n\n var_l1.set(text)\n win_child.after(3*1000,lambda: win_child.destroy())\n\nwin = tk.Tk()\nmenubar = tk.Menu(win)\n\nmenu = tk.Menu(menubar, tearoff=0)\nmenubar.add_cascade(label=\"Scripts\", menu=menu)\n\ndict_label_func = {\n 'function_01': lambda win: show_child_win(win,text='function_01'),\n 'function_02': lambda win: show_child_win(win,text='function_02'),\n 'last_function': lambda win: show_child_win(win,text='last_function')\n}\n\nfor label, func in dict_label_func.items():\n menu.add_command(label=label,command = lambda f=func: f(win))\n\nwin.config(menu=menubar)\nwin.mainloop()\n" }, { "answer_id": 74511539, "author": "Claudio", "author_id": 7711283, "author_profile": "https://Stackoverflow.com/users/7711283", "pm_score": 1, "selected": false, "text": "import tkinter as tk\nfrom tkinter import ttk,messagebox\n\ndef show_child_win(win,text=''):\n win_child = tk.Toplevel(win)\n\n var_l1 = tk.StringVar()\n l1 = tk.Label(win_child,textvariable=var_l1)\n l1.grid(row=0, column=0)\n\n var_l1.set(text)\n win_child.after(3*1000,lambda: win_child.destroy())\n\nwin = tk.Tk() \n# ^ -- create window and use it as default\n# parameter value --v\ndef show_child_win_1(win=win,text='function_01'):\n show_child_win(win,text)\ndef show_child_win_2(win=win,text='function_02'):\n show_child_win(win,text)\ndef show_child_win_l(win=win,text='last_function'):\n show_child_win(win,text)\n# ^-- create different functions handling different menu entries\n\nmenubar = tk.Menu(win)\n\nmenu = tk.Menu(menubar, tearoff=0)\nmenubar.add_cascade(label=\"Scripts\", menu=menu)\n\nmenu.add_command(label='function_01' ,command = show_child_win_1)\nmenu.add_command(label='function_02' ,command = show_child_win_2)\nmenu.add_command(label='last_function',command = show_child_win_l)\n\nwin.config(menu=menubar)\nwin.mainloop()\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19853940/" ]
74,509,786
<p>In Bash I would do something like</p> <pre><code>... ... if ! cd non_exist_dir &gt; /dev/null 2&gt;&amp;1; then echo &quot;error in cd&quot; return 1 fi ... ... </code></pre> <p>How would I do that in idiomatic nushell ?<br /> Especially, how can I get rid of the annoying error message displayed by nushell because the directory doesn't exist ?<br /> Bonus points if I could get something like a &quot;return&quot; command, which seems to be missing in nushell.</p>
[ { "answer_id": 74509892, "author": "RandomCoder59", "author_id": 16765869, "author_profile": "https://Stackoverflow.com/users/16765869", "pm_score": 2, "selected": false, "text": "lambda func func() abcd abcd() abcd lambda abcd abcd: abcd() dict_label_func = {\n 'function_01': lambda: show_child_win(win, text='function_01'),\n 'function_02': lambda: show_child_win(win, text='function_02'),\n 'last_function': lambda: show_child_win(win, text='last_function')\n}\n\nfor label, func in dict_label_func.items():\n menu.add_command(label=label,command = func)\n" }, { "answer_id": 74510186, "author": "dallascow", "author_id": 19853940, "author_profile": "https://Stackoverflow.com/users/19853940", "pm_score": 1, "selected": true, "text": "import tkinter as tk\nfrom tkinter import ttk,messagebox\n\ndef show_child_win(win,text=''):\n win_child = tk.Toplevel(win)\n\n var_l1 = tk.StringVar()\n l1 = tk.Label(win_child,textvariable=var_l1)\n l1.grid(row=0, column=0)\n\n var_l1.set(text)\n win_child.after(3*1000,lambda: win_child.destroy())\n\nwin = tk.Tk()\nmenubar = tk.Menu(win)\n\nmenu = tk.Menu(menubar, tearoff=0)\nmenubar.add_cascade(label=\"Scripts\", menu=menu)\n\ndict_label_func = {\n 'function_01': lambda win: show_child_win(win,text='function_01'),\n 'function_02': lambda win: show_child_win(win,text='function_02'),\n 'last_function': lambda win: show_child_win(win,text='last_function')\n}\n\nfor label, func in dict_label_func.items():\n menu.add_command(label=label,command = lambda f=func: f(win))\n\nwin.config(menu=menubar)\nwin.mainloop()\n" }, { "answer_id": 74511539, "author": "Claudio", "author_id": 7711283, "author_profile": "https://Stackoverflow.com/users/7711283", "pm_score": 1, "selected": false, "text": "import tkinter as tk\nfrom tkinter import ttk,messagebox\n\ndef show_child_win(win,text=''):\n win_child = tk.Toplevel(win)\n\n var_l1 = tk.StringVar()\n l1 = tk.Label(win_child,textvariable=var_l1)\n l1.grid(row=0, column=0)\n\n var_l1.set(text)\n win_child.after(3*1000,lambda: win_child.destroy())\n\nwin = tk.Tk() \n# ^ -- create window and use it as default\n# parameter value --v\ndef show_child_win_1(win=win,text='function_01'):\n show_child_win(win,text)\ndef show_child_win_2(win=win,text='function_02'):\n show_child_win(win,text)\ndef show_child_win_l(win=win,text='last_function'):\n show_child_win(win,text)\n# ^-- create different functions handling different menu entries\n\nmenubar = tk.Menu(win)\n\nmenu = tk.Menu(menubar, tearoff=0)\nmenubar.add_cascade(label=\"Scripts\", menu=menu)\n\nmenu.add_command(label='function_01' ,command = show_child_win_1)\nmenu.add_command(label='function_02' ,command = show_child_win_2)\nmenu.add_command(label='last_function',command = show_child_win_l)\n\nwin.config(menu=menubar)\nwin.mainloop()\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1856694/" ]
74,509,799
<p>I am working on a fairly simple worksheet where if a cell contains a hexadecimal value I want to convert it to decimal, otherwise if it is already in decimal format we just leave it. Something like:</p> <p>=IF(A1 is hex, HEX2DEC(A1),A1)</p> <p>Any ideas/suggestions would be awesome. Thanks in advance.</p> <p>I have searched around a bit but can not seem to find anything.</p>
[ { "answer_id": 74509892, "author": "RandomCoder59", "author_id": 16765869, "author_profile": "https://Stackoverflow.com/users/16765869", "pm_score": 2, "selected": false, "text": "lambda func func() abcd abcd() abcd lambda abcd abcd: abcd() dict_label_func = {\n 'function_01': lambda: show_child_win(win, text='function_01'),\n 'function_02': lambda: show_child_win(win, text='function_02'),\n 'last_function': lambda: show_child_win(win, text='last_function')\n}\n\nfor label, func in dict_label_func.items():\n menu.add_command(label=label,command = func)\n" }, { "answer_id": 74510186, "author": "dallascow", "author_id": 19853940, "author_profile": "https://Stackoverflow.com/users/19853940", "pm_score": 1, "selected": true, "text": "import tkinter as tk\nfrom tkinter import ttk,messagebox\n\ndef show_child_win(win,text=''):\n win_child = tk.Toplevel(win)\n\n var_l1 = tk.StringVar()\n l1 = tk.Label(win_child,textvariable=var_l1)\n l1.grid(row=0, column=0)\n\n var_l1.set(text)\n win_child.after(3*1000,lambda: win_child.destroy())\n\nwin = tk.Tk()\nmenubar = tk.Menu(win)\n\nmenu = tk.Menu(menubar, tearoff=0)\nmenubar.add_cascade(label=\"Scripts\", menu=menu)\n\ndict_label_func = {\n 'function_01': lambda win: show_child_win(win,text='function_01'),\n 'function_02': lambda win: show_child_win(win,text='function_02'),\n 'last_function': lambda win: show_child_win(win,text='last_function')\n}\n\nfor label, func in dict_label_func.items():\n menu.add_command(label=label,command = lambda f=func: f(win))\n\nwin.config(menu=menubar)\nwin.mainloop()\n" }, { "answer_id": 74511539, "author": "Claudio", "author_id": 7711283, "author_profile": "https://Stackoverflow.com/users/7711283", "pm_score": 1, "selected": false, "text": "import tkinter as tk\nfrom tkinter import ttk,messagebox\n\ndef show_child_win(win,text=''):\n win_child = tk.Toplevel(win)\n\n var_l1 = tk.StringVar()\n l1 = tk.Label(win_child,textvariable=var_l1)\n l1.grid(row=0, column=0)\n\n var_l1.set(text)\n win_child.after(3*1000,lambda: win_child.destroy())\n\nwin = tk.Tk() \n# ^ -- create window and use it as default\n# parameter value --v\ndef show_child_win_1(win=win,text='function_01'):\n show_child_win(win,text)\ndef show_child_win_2(win=win,text='function_02'):\n show_child_win(win,text)\ndef show_child_win_l(win=win,text='last_function'):\n show_child_win(win,text)\n# ^-- create different functions handling different menu entries\n\nmenubar = tk.Menu(win)\n\nmenu = tk.Menu(menubar, tearoff=0)\nmenubar.add_cascade(label=\"Scripts\", menu=menu)\n\nmenu.add_command(label='function_01' ,command = show_child_win_1)\nmenu.add_command(label='function_02' ,command = show_child_win_2)\nmenu.add_command(label='last_function',command = show_child_win_l)\n\nwin.config(menu=menubar)\nwin.mainloop()\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20555729/" ]
74,509,805
<p>I am trying to use the destructuring syntax of Java 19 pattern match, but my IntelliJ Idea cannot understand it (please refer below screenshot). Is there a way to fix this? Or IntellJ is not yet ready for java 19 ?</p> <p><a href="https://i.stack.imgur.com/OMgeW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OMgeW.png" alt="enter image description here" /></a></p> <pre class="lang-java prettyprint-override"><code> // sealed interface and record combo public sealed interface LoginRequest permits DefaultLogin {} public record DefaultLogin(@Min(1) int userId, @Valid Password password) implements LoginRequest {} // java 19 switch is not supported in IntelliJ Idea, gives all red lines Optional&lt;Profile&gt; profileMaybe = switch (loginRequest) { case DefaultLogin(int id, Password pw) -&gt; getProfile(new ById(id)); </code></pre>
[ { "answer_id": 74510299, "author": "Basil Bourque", "author_id": 642706, "author_profile": "https://Stackoverflow.com/users/642706", "pm_score": 2, "selected": false, "text": ".3 switch" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509805", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2715083/" ]
74,509,850
<p>I am trying to display the values inside an array but there are these 0's that come with it. Using a for loop to count the number of temperature and the temperature's value with it.</p> <p>This is the code that I used:</p> <pre><code>import java.util.*; public class Array1dTemperature { static Scanner in = new Scanner (System.in); static Random rng = new Random (); public static void main(String[] args) { System.out.println(&quot;This program does a temperature check.&quot;); System.out.println(&quot;Input the desired number of temperatures...&quot;); int size = in.nextInt(); int[] temp = new int [size]; for (int i=0; i&lt;temp.length; i++) temp[i] = 1+rng.nextInt(100); System.out.println(&quot;The data file goes as: &quot; + Arrays.toString(temp)); Checker(temp); } static void Checker (int temp[]) { int hot[] = new int [10] ; int []pleasant = new int [10]; int []cold = new int [10]; int H = 0; int P = 0; int C = 0; for (int i=0; i&lt;temp.length;i++) { if (temp[i]&gt;=85) { hot[i] = temp[i]; H++; } else if (temp[i]&gt;=60&amp;&amp;temp[i]&lt;84) { pleasant[i] = temp[i]; P++; } else if (temp[i]&lt;60) { cold[i] = temp[i]; C++; } } System.out.println(&quot;number of hot: &quot;+ H + &quot;, Recorded temps are: &quot; + Arrays.toString(hot) ); System.out.println(&quot;number of cold: &quot;+ C + &quot;, Recorded temps are: &quot; + Arrays.toString(cold)); System.out.println(&quot;number of pleasant: &quot;+ P + &quot;, Recorded temps are: &quot; + Arrays.toString(pleasant)); } } </code></pre> <p>I tried changing the values of the individual arrays themselves but it becomes out of bounds whenever I try to print the output. I could've used &quot;Arraylist&quot; to update the arrays but this specific exercise problem prohibits the used of such.</p> <p><a href="https://i.stack.imgur.com/omuDt.png" rel="nofollow noreferrer">This is the Output</a></p>
[ { "answer_id": 74510299, "author": "Basil Bourque", "author_id": 642706, "author_profile": "https://Stackoverflow.com/users/642706", "pm_score": 2, "selected": false, "text": ".3 switch" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19891678/" ]
74,509,861
<p>I intalled Packer.nvim as in the instructions in the repository, after doing all the plugin configuration, when I go to run the :PackerInstall command NeoVim doesn't recognize it. I checked the Windows Path and apparently everything is fine.</p> <p>Windows 11 Home NeaoVim 0.8.1</p> <p>I try install a Packer.nvim.</p>
[ { "answer_id": 74510299, "author": "Basil Bourque", "author_id": 642706, "author_profile": "https://Stackoverflow.com/users/642706", "pm_score": 2, "selected": false, "text": ".3 switch" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20555918/" ]
74,509,871
<p>I have a tibble:</p> <pre><code> itemID order dayR n &lt;dbl&gt; &lt;dbl&gt; &lt;date&gt; &lt;int&gt; 1 9 1 2018-01-01 1 2 11 1 2018-01-01 1 3 19 1 2018-01-01 2 4 26 1 2018-01-01 96 5 26 2 2018-01-01 5 6 26 3 2018-01-01 1 7 35 1 2018-01-01 379 8 35 2 2018-01-01 23 9 35 3 2018-01-01 4 10 35 4 2018-01-01 1 </code></pre> <p>I want to aggregate over the orders and then sum them into <code>n</code> to get a unique itemID, so for example the <code>itemID 26</code> (<code>1*96 + 2*5 + 3*1 = 109</code>):</p> <pre><code> itemID dayR n &lt;dbl&gt; &lt;date&gt; &lt;int&gt; 1 26 2018-01-01 109 ... </code></pre> <p>Code for reproduction:</p> <pre><code>structure(list(itemID = c(9, 11, 19, 26, 26, 26, 35, 35, 35, 35), order = c(1, 1, 1, 1, 2, 3, 1, 2, 3, 4), dayR = structure(c(17532, 17532, 17532, 17532, 17532, 17532, 17532, 17532, 17532, 17532 ), class = &quot;Date&quot;), n = c(1L, 1L, 2L, 96L, 5L, 1L, 379L, 23L, 4L, 1L)), row.names = c(NA, -10L), class = c(&quot;tbl_df&quot;, &quot;tbl&quot;, &quot;data.frame&quot;)) </code></pre>
[ { "answer_id": 74509923, "author": "langtang", "author_id": 4447540, "author_profile": "https://Stackoverflow.com/users/4447540", "pm_score": 3, "selected": true, "text": "group_by() summarize() df %>% \n group_by(itemID, dayR) %>% \n summarize(n=sum(n*order))\n itemID dayR n\n <dbl> <date> <dbl>\n1 9 2018-01-01 1\n2 11 2018-01-01 1\n3 19 2018-01-01 2\n4 26 2018-01-01 109\n5 35 2018-01-01 441\n" }, { "answer_id": 74511363, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 1, "selected": false, "text": "%*% library(dplyr)\ndf %>%\n group_by(itemID, dayR) %>% \n summarise(n = c(n %*% order), .groups = 'drop')\n # A tibble: 5 × 3\n itemID dayR n\n <dbl> <date> <dbl>\n1 9 2018-01-01 1\n2 11 2018-01-01 1\n3 19 2018-01-01 2\n4 26 2018-01-01 109\n5 35 2018-01-01 441\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16236118/" ]
74,509,881
<p><strong>Scenario</strong> I've developed a scheduled task that runs after every 30 seconds. The task is injected to a proxy service. The proxy service implements a sequence which calls the HTTP Address and further dumps the data into postgresdb</p> <p><strong>Task</strong></p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;task class=&quot;org.apache.synapse.startup.tasks.MessageInjector&quot; group=&quot;synapse.simple.quartz&quot; name=&quot;IoscoScheduledTask&quot; xmlns=&quot;http://ws.apache.org/ns/synapse&quot;&gt; &lt;trigger interval=&quot;100&quot;/&gt; &lt;property name=&quot;message&quot; xmlns:task=&quot;http://www.wso2.org/products/wso2commons/tasks&quot;&gt; &lt;alert&gt;dataDumped&lt;/alert&gt; &lt;/property&gt; &lt;property name=&quot;injectTo&quot; value=&quot;proxy&quot; xmlns:task=&quot;http://www.wso2.org/products/wso2commons/tasks&quot;/&gt; &lt;property name=&quot;proxyName&quot; value=&quot;alertsIoscoProxy&quot; xmlns:task=&quot;http://www.wso2.org/products/wso2commons/tasks&quot;/&gt; &lt;/task&gt; </code></pre> <p><strong>Proxy Service</strong> Proxy service uses sequence which basically send HTTP Call to the URL</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;proxy name=&quot;alertsIoscoProxy&quot; startOnLoad=&quot;true&quot; transports=&quot;http https&quot; xmlns=&quot;http://ws.apache.org/ns/synapse&quot;&gt; &lt;target&gt; &lt;inSequence&gt; &lt;sequence key=&quot;IoscoSequence&quot;/&gt; &lt;log level=&quot;full&quot;/&gt; &lt;property description=&quot;conversion&quot; name=&quot;XML2JSON&quot; scope=&quot;axis2&quot; type=&quot;STRING&quot; value=&quot;application/json&quot;/&gt; &lt;propertyGroup description=&quot;Alert&quot;&gt; &lt;property expression=&quot;json-eval($.alerts.alert.id)&quot; name=&quot;id&quot; scope=&quot;default&quot; type=&quot;STRING&quot;/&gt; &lt;property expression=&quot;json-eval($.alerts.alert.datePosted)&quot; name=&quot;datePosted&quot; scope=&quot;default&quot; type=&quot;STRING&quot;/&gt; &lt;property expression=&quot;json-eval($.alerts.alert.company)&quot; name=&quot;company&quot; scope=&quot;default&quot; type=&quot;STRING&quot;/&gt; &lt;property expression=&quot;json-eval($.alerts.alert.regulator)&quot; name=&quot;regulator&quot; scope=&quot;default&quot; type=&quot;STRING&quot;/&gt; &lt;property expression=&quot;json-eval($.alerts.alert.jurisdiction)&quot; name=&quot;jurisdiction&quot; scope=&quot;default&quot; type=&quot;STRING&quot;/&gt; &lt;property expression=&quot;json-eval($.alerts.alert.link)&quot; name=&quot;link&quot; scope=&quot;default&quot; type=&quot;STRING&quot;/&gt; &lt;property expression=&quot;json-eval($.alerts.alert.subject)&quot; name=&quot;subject&quot; scope=&quot;default&quot; type=&quot;STRING&quot;/&gt; &lt;property expression=&quot;json-eval($.alerts.alert.comments)&quot; name=&quot;comments&quot; scope=&quot;default&quot; type=&quot;STRING&quot;/&gt; &lt;property expression=&quot;json-eval($.alerts.alert.attachments)&quot; name=&quot;attachments&quot; scope=&quot;default&quot; type=&quot;STRING&quot;/&gt; &lt;/propertyGroup&gt; &lt;dataServiceCall description=&quot;Data&quot; serviceName=&quot;Data&quot;&gt; &lt;operations type=&quot;batch&quot;&gt; &lt;operation name=&quot;addAlert&quot;&gt; &lt;param name=&quot;id&quot; value=&quot;property_value&quot;/&gt; &lt;param name=&quot;datePosted&quot; value=&quot;property_value&quot;/&gt; &lt;param name=&quot;company&quot; value=&quot;property_value&quot;/&gt; &lt;param name=&quot;regulator&quot; value=&quot;property_value&quot;/&gt; &lt;param name=&quot;jurisdiction&quot; value=&quot;property_value&quot;/&gt; &lt;param name=&quot;link&quot; value=&quot;property_value&quot;/&gt; &lt;param name=&quot;subject&quot; value=&quot;property_value&quot;/&gt; &lt;param name=&quot;comments&quot; value=&quot;property_value&quot;/&gt; &lt;param name=&quot;attachments&quot; value=&quot;property_value&quot;/&gt; &lt;/operation&gt; &lt;/operations&gt; &lt;source type=&quot;inline&quot;/&gt; &lt;target type=&quot;body&quot;/&gt; &lt;/dataServiceCall&gt; &lt;log level=&quot;full&quot;/&gt; &lt;/inSequence&gt; &lt;outSequence&gt; &lt;respond/&gt; &lt;/outSequence&gt; &lt;faultSequence&gt; &lt;log/&gt; &lt;/faultSequence&gt; &lt;/target&gt; &lt;/proxy&gt; </code></pre> <p><strong>Data Service</strong></p> <pre><code>&lt;data transports=&quot;http https local&quot; serviceGroup=&quot;&quot; serviceNamespace=&quot;&quot; name=&quot;IoscoDataService&quot;&gt; &lt;description /&gt; &lt;config id=&quot;postgres&quot;&gt; &lt;property name=&quot;driverClassName&quot;&gt;org.postgresql.Driver&lt;/property&gt; &lt;property name=&quot;url&quot;&gt;jdbc:postgresql://localhost:5432/postgres&lt;/property&gt; &lt;property name=&quot;username&quot;&gt;postgres&lt;/property&gt; &lt;property name=&quot;password&quot;&gt;xxxx&lt;/property&gt; &lt;/config&gt; &lt;query id=&quot;addAlertQuery&quot; useConfig=&quot;postgres&quot;&gt; &lt;sql&gt;INSERT INTO public.&quot;IOSCO_RESPONSE&quot; (&quot;ID&quot;, &quot;DATE_POSTED&quot;, &quot;COMPANY&quot;, &quot;REGULATOR&quot;, &quot;JURISDICTION&quot;, &quot;LINK&quot;, &quot;SUBJECT&quot;, &quot;COMMENTS&quot;, &quot;ATTACHMENTS&quot;) VALUES(:id, :datePosted, :company, :regulator, :jurisdiction, :link, :subject, :comments, :attachments); &lt;/sql&gt; &lt;param type=&quot;IN&quot; name=&quot;company&quot; paramType=&quot;SCALAR&quot; sqlType=&quot;STRING&quot; optional=&quot;false&quot; /&gt; &lt;param type=&quot;IN&quot; name=&quot;regulator&quot; paramType=&quot;SCALAR&quot; sqlType=&quot;STRING&quot; optional=&quot;false&quot; /&gt; &lt;param type=&quot;IN&quot; name=&quot;jurisdiction&quot; paramType=&quot;SCALAR&quot; sqlType=&quot;STRING&quot; optional=&quot;false&quot; /&gt; &lt;param type=&quot;IN&quot; name=&quot;link&quot; paramType=&quot;SCALAR&quot; sqlType=&quot;STRING&quot; optional=&quot;false&quot; /&gt; &lt;param type=&quot;IN&quot; name=&quot;subject&quot; paramType=&quot;SCALAR&quot; sqlType=&quot;STRING&quot; optional=&quot;false&quot; /&gt; &lt;param type=&quot;IN&quot; name=&quot;comments&quot; paramType=&quot;SCALAR&quot; sqlType=&quot;STRING&quot; optional=&quot;false&quot; /&gt; &lt;param type=&quot;IN&quot; name=&quot;attachments&quot; paramType=&quot;SCALAR&quot; sqlType=&quot;STRING&quot; optional=&quot;false&quot; /&gt; &lt;param type=&quot;IN&quot; name=&quot;id&quot; paramType=&quot;SCALAR&quot; sqlType=&quot;STRING&quot; optional=&quot;false&quot; /&gt; &lt;param type=&quot;IN&quot; name=&quot;datePosted&quot; paramType=&quot;SCALAR&quot; sqlType=&quot;STRING&quot; optional=&quot;false&quot; /&gt; &lt;/query&gt; &lt;operation name=&quot;addAlert&quot; returnRequestStatus=&quot;true&quot;&gt; &lt;call-query href=&quot;addAlertQuery&quot;&gt; &lt;with-param name=&quot;id&quot; query-param=&quot;id&quot;/&gt; &lt;with-param name=&quot;datePosted&quot; query-param=&quot;datePosted&quot;/&gt; &lt;with-param name=&quot;company&quot; query-param=&quot;company&quot;/&gt; &lt;with-param name=&quot;regulator&quot; query-param=&quot;regulator&quot;/&gt; &lt;with-param name=&quot;jurisdiction&quot; query-param=&quot;jurisdiction&quot;/&gt; &lt;with-param name=&quot;link&quot; query-param=&quot;link&quot;/&gt; &lt;with-param name=&quot;subject&quot; query-param=&quot;subject&quot;/&gt; &lt;with-param name=&quot;comments&quot; query-param=&quot;comments&quot;/&gt; &lt;with-param name=&quot;attachments&quot; query-param=&quot;attachments&quot;/&gt; &lt;/call-query&gt; &lt;/operation&gt; &lt;resource method=&quot;POST&quot; path=&quot;/Alert&quot;&gt; &lt;call-query href=&quot;addAlertQuery&quot;&gt; &lt;with-param name=&quot;id&quot; query-param=&quot;id&quot;/&gt; &lt;with-param name=&quot;datePosted&quot; query-param=&quot;datePosted&quot;/&gt; &lt;with-param name=&quot;company&quot; query-param=&quot;company&quot;/&gt; &lt;with-param name=&quot;regulator&quot; query-param=&quot;regulator&quot;/&gt; &lt;with-param name=&quot;jurisdiction&quot; query-param=&quot;jurisdiction&quot;/&gt; &lt;with-param name=&quot;link&quot; query-param=&quot;link&quot;/&gt; &lt;with-param name=&quot;subject&quot; query-param=&quot;subject&quot;/&gt; &lt;with-param name=&quot;comments&quot; query-param=&quot;comments&quot;/&gt; &lt;with-param name=&quot;attachments&quot; query-param=&quot;attachments&quot;/&gt; &lt;/call-query&gt; &lt;/resource&gt; &lt;/data&gt; </code></pre> <p><strong>Sample Data from URL</strong></p> <pre><code>&lt;alerts&gt; &lt;message&gt;Results are capped at 500 records.&lt;/message&gt; &lt;alert&gt; &lt;id&gt;22847&lt;/id&gt; &lt;datePosted&gt;20221118&lt;/datePosted&gt; &lt;company&gt;GreatInvest (Clone of FCA authorised firm)&lt;/company&gt; &lt;regulator&gt;Financial Conduct Authority&lt;/regulator&gt; &lt;jurisdiction&gt;United Kingdom&lt;/jurisdiction&gt; &lt;link&gt;https://www.fca.org.uk/news/warnings/greatinvest-clone-fca-authorised-firm&lt;/link&gt; &lt;subject&gt;Regarding fraudulent or manipulative practices (insider dealing, market manipulation, misrepresentation of material information, etc.)&lt;br /&gt;&lt;br /&gt;Regarding registration of issuance, offer or sale of securities/derivatives, and reporting requirements&lt;br /&gt;&lt;br /&gt;Regarding market intermediaries (investment and trading advisers, collective investment schemes, brokers, dealers, and transfer agents)&lt;br /&gt;&lt;br /&gt;Regarding markets, exchanges, and clearing and settlement entities&lt;br /&gt;&lt;br /&gt;Miscellaneous&lt;/subject&gt; &lt;comments/&gt; &lt;attachments/&gt; &lt;/alert&gt; &lt;/alerts&gt; </code></pre> <p><strong>ERROR</strong></p> <pre><code> INFO {LogMediator} - {proxy:alertsIoscoProxy} To: , MessageID: urn:uuid:3054d6d1-553c-4c42-a58d-370408943766, Direction: request [2022-11-20 21:15:42,800] ERROR {RelayUtils} - Error while building Passthrough stream org.apache.axiom.soap.SOAPProcessingException: First Element must contain the local name, Envelope , but found alerts at org.apache.axiom.soap.impl.builder.StAXSOAPModelBuilder.constructNode(StAXSOAPModelBuilder.java:305) at org.apache.axiom.soap.impl.builder.StAXSOAPModelBuilder.createOMElement(StAXSOAPModelBuilder.java:252) at org.apache.axiom.soap.impl.builder.StAXSOAPModelBuilder.createNextOMElement(StAXSOAPModelBuilder.java:234) at org.apache.axiom.om.impl.builder.StAXOMBuilder.next(StAXOMBuilder.java:249) at org.apache.axiom.soap.impl.builder.StAXSOAPModelBuilder.getSOAPEnvelope(StAXSOAPModelBuilder.java:204) at org.apache.axiom.soap.impl.builder.StAXSOAPModelBuilder.&lt;init&gt;(StAXSOAPModelBuilder.java:154) at org.apache.axiom.om.impl.AbstractOMMetaFactory.createStAXSOAPModelBuilder(AbstractOMMetaFactory.java:73) at org.apache.axiom.om.impl.AbstractOMMetaFactory.createSOAPModelBuilder(AbstractOMMetaFactory.java:79) at org.apache.axiom.om.OMXMLBuilderFactory.createSOAPModelBuilder(OMXMLBuilderFactory.java:196) at org.apache.axis2.builder.SOAPBuilder.processDocument(SOAPBuilder.java:65) at org.apache.synapse.transport.passthru.util.DeferredMessageBuilder.getDocument(DeferredMessageBuilder.java:153) at org.apache.synapse.transport.passthru.util.RelayUtils.buildMessage(RelayUtils.java:169) at org.apache.synapse.transport.passthru.util.RelayUtils.buildMessage(RelayUtils.java:122) at org.apache.synapse.transport.util.PassThroughMessageHandler.buildMessage(PassThroughMessageHandler.java:103) at org.apache.synapse.core.axis2.Axis2Sender.doSOAPFormatConversion(Axis2Sender.java:412) at org.apache.synapse.core.axis2.Axis2Sender.sendBack(Axis2Sender.java:193) at org.apache.synapse.mediators.builtin.RespondMediator.mediate(RespondMediator.java:46) at org.apache.synapse.mediators.AbstractListMediator.mediate(AbstractListMediator.java:110) at org.apache.synapse.mediators.AbstractListMediator.mediate(AbstractListMediator.java:72) at org.apache.synapse.mediators.base.SequenceMediator.mediate(SequenceMediator.java:158) at org.apache.synapse.core.axis2.Axis2SynapseEnvironment.injectMessage(Axis2SynapseEnvironment.java:377) at org.apache.synapse.core.axis2.SynapseCallbackReceiver.handleMessage(SynapseCallbackReceiver.java:627) at org.apache.synapse.core.axis2.SynapseCallbackReceiver.receive(SynapseCallbackReceiver.java:208) at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:180) at org.apache.synapse.transport.passthru.ClientWorker.run(ClientWorker.java:298) at org.apache.axis2.transport.base.threads.NativeWorkerPool$1.run(NativeWorkerPool.java:172) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) at java.base/java.lang.Thread.run(Thread.java:834) </code></pre> <p><strong>Sequence</strong></p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;sequence name=&quot;IoscoSequence&quot; trace=&quot;disable&quot; xmlns=&quot;http://ws.apache.org/ns/synapse&quot;&gt; &lt;log level=&quot;full&quot;/&gt; &lt;call&gt; &lt;endpoint&gt; &lt;address format=&quot;get&quot; statistics=&quot;enable&quot; trace=&quot;enable&quot; uri=&quot;https://www.XXXX.XXX/investor_protection/investor_alerts/xml-feed&quot;&gt; &lt;suspendOnFailure&gt; &lt;initialDuration&gt;-1&lt;/initialDuration&gt; &lt;progressionFactor&gt;-1&lt;/progressionFactor&gt; &lt;maximumDuration&gt;0&lt;/maximumDuration&gt; &lt;/suspendOnFailure&gt; &lt;markForSuspension&gt; &lt;retriesBeforeSuspension&gt;0&lt;/retriesBeforeSuspension&gt; &lt;/markForSuspension&gt; &lt;/address&gt; &lt;/endpoint&gt; &lt;/call&gt; &lt;/sequence&gt; </code></pre> <p><strong>Question</strong> My question is: why proxy service is considering the HTTP response as SOAP and throws SOAPProcessingError while clearly the response is Rest with XML data formatting?. How can I resolved this issue?</p>
[ { "answer_id": 74513521, "author": "ycr", "author_id": 2627018, "author_profile": "https://Stackoverflow.com/users/2627018", "pm_score": 0, "selected": false, "text": "Respond <outSequence>\n <property name=\"messageType\" value=\"application/xml\" scope=\"axis2\"/>\n <property name=\"ContentType\" value=\"application/xml\" scope=\"axis2\"/>\n <respond/>\n</outSequence>\n\n" }, { "answer_id": 74515075, "author": "Flaviano O. Silva", "author_id": 7237982, "author_profile": "https://Stackoverflow.com/users/7237982", "pm_score": -1, "selected": false, "text": "<soap:envelope\nxmlns:soap=\"http://www.w3.org/2003/05/soap-envelope/\"\nsoap:encodingStyle=\"http://www.w3.org/2003/05/soap-encoding\">\n<alerts>\n....\n</alerts>\n</soap:Envelope>\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7454536/" ]
74,509,884
<p>I have this query that returns 13 rows.</p> <pre><code>SELECT DISTINCT title,year FROM MovieAwards WHERE EXISTS (SELECT DISTINCT * FROM Movies WHERE MovieAwards.title = Movies.title AND Movies.year = MovieAwards.year AND Movies.year &gt;= 2000 AND Movies.year &lt;= 2010 AND MovieAwards.result='won'); </code></pre> <p>Now i need to use the number of rows of this query as a float for other queries. I am aware that i can use THIS AND AS to store the number of rows in some temporary variable. But i can't find a single way to modify the first query to output 13.</p> <p>If i do SELECT COUNT(*) FROM MovieAwards WHERE EXISTS IN (the code above)</p> <p>i get a very different number as title,year is not the key of MovieAwards.</p> <p>I also tried to replace title,year with count(title,year) but i'm guessing that isn't allowed.</p> <p>I can't think of anything else to try. Any help would be apretiated.</p> <p>Edit: Thanks @nbk for your code. Individually it works perfectly. However when I try to use it I get either a syntax error or a casting error. This last attempt below in particular gives a generic syntax error:</p> <pre><code>WITH &quot;won&quot; AS (SELECT COUNT(*)::FLOAT FROM MovieAwards WHERE EXISTS (SELECT DISTINCT * FROM Movies WHERE MovieAwards.title = Movies.title AND Movies.year = MovieAwards.year AND Movies.year &gt;= 2000 AND Movies.year &lt;= 2010 AND MovieAwards.result='won') GROUP BY title,year), &quot;total&quot; AS (SELECT COUNT(*)::FLOAT FROM Movies WHERE Movies.year &gt;=2000 AND Movies.year &lt;=2010) SELECT success-rate AS ( CASE WHEN (total = 0) THEN '-1' (ELSE won/total) ); </code></pre>
[ { "answer_id": 74513521, "author": "ycr", "author_id": 2627018, "author_profile": "https://Stackoverflow.com/users/2627018", "pm_score": 0, "selected": false, "text": "Respond <outSequence>\n <property name=\"messageType\" value=\"application/xml\" scope=\"axis2\"/>\n <property name=\"ContentType\" value=\"application/xml\" scope=\"axis2\"/>\n <respond/>\n</outSequence>\n\n" }, { "answer_id": 74515075, "author": "Flaviano O. Silva", "author_id": 7237982, "author_profile": "https://Stackoverflow.com/users/7237982", "pm_score": -1, "selected": false, "text": "<soap:envelope\nxmlns:soap=\"http://www.w3.org/2003/05/soap-envelope/\"\nsoap:encodingStyle=\"http://www.w3.org/2003/05/soap-encoding\">\n<alerts>\n....\n</alerts>\n</soap:Envelope>\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20541599/" ]
74,509,948
<p>I have a PHP object that I need to change the key name of in a foreach loop:</p> <pre><code>stdClass Object ( [first-name] =&gt; NAME [last-name] =&gt; NAME [phone-number] =&gt; NUMBER ... ) </code></pre> <p>I need to replace the dash '-' to a underscore '_' within a foreach so it looks like this:</p> <pre><code>stdClass Object ( [first_name] =&gt; NAME [last_name] =&gt; NAME [phone_number] =&gt; NUMBER ... ) </code></pre> <p>I found this post: <a href="https://stackoverflow.com/q/7310248/16096837">PHP - How to rename an object property?</a> which does tell me how to do it, the problem is that when I use unset() inside of the foreach it unsets all of the keys instead of just the ones I want it to.</p> <p>Here's my code:</p> <pre><code>foreach ($customer as $key =&gt; $value) { $key2 = str_replace('-', '_', $key); $customer-&gt;$key2 = $customer-&gt;$key; unset($customer-&gt;$key); } </code></pre> <p>which returns an empty object:</p> <pre><code>stdClass Object ( ) </code></pre> <p>How can I unset the original keys without affecting the new ones?</p>
[ { "answer_id": 74509982, "author": "hakre", "author_id": 367456, "author_profile": "https://Stackoverflow.com/users/367456", "pm_score": 3, "selected": true, "text": " $key2 = str_replace('-', '_', $key);\n if ($key2 !== $key) {\n $customer->$key2 = $customer->$key; \n unset($customer->$key);\n }\n foreach continue foreach ($customer as $key => $value) {\n $key2 = str_replace('-', '_', $key);\n if ($key2 === $key) {\n continue; // nothing to do\n }\n $customer->$key2 = $customer->$key; \n unset($customer->$key);\n}\n unset foreach (clone $customer as $key => $value) {\n $key2 = str_replace('-', '_', $key);\n unset($customer->$key);\n $customer->$key2 = $value;\n}\n" }, { "answer_id": 74510053, "author": "KIKO Software", "author_id": 3986005, "author_profile": "https://Stackoverflow.com/users/3986005", "pm_score": 1, "selected": false, "text": "foreach (get_object_vars($customer) as $key => $value) {\n $key2 = str_replace('-', '_', $key);\n $customer->$key2 = $customer->$key; \n unset($customer->$key);\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16096837/" ]
74,509,958
<p>I have been working on <a href="https://www.codewars.com/kata/5da1df6d8b0f6c0026e6d58d" rel="nofollow noreferrer">this</a> problem for some time now. The problem asks to find two numbers x and y such that the product of the squares of x and y equal the cube of k. My approach was to solve for x, given that an input of 1 would give a number, lim, that when squared is equal to k cubed. The code first tests if the square root of the function arg is an integer or not. It not then 0 is returned. If not, then the lim is found. The code then iterates through a range of numbers, i, starting at 1 up to the square root of lim, testing to see if the quotient of lim and i is an integer or not. Since the problem asks for the number of divisors, I found it best to use reduce and count the number of successful x and y pairs, rather than iterate through a list to find its size.</p> <pre><code>def c(k: Long) = { val sqrtk = math.sqrt(k) sqrtk.isWhole match { case false =&gt; 0 case true =&gt; val lim = k * sqrtk (1 to math.sqrt(lim).toInt).foldLeft(0)((acc, i) =&gt; if ((lim / i).isWhole) acc + 2 else acc ) } } </code></pre> <p>I am pretty sure that the problem lies in the use of the two square roots and the division being performed, but I have so far been unable to make this code perform any better. Initially I was unable to even pass the basic tests and now I can pass about 48 of the random tests, and am hopefully close to passing all the tests. I have tried numerous other solutions, including making my own square root function, and trying to find all divisors with prime numbers, etc., but none have been as fast as the code I have posted above. Like the title says, this code is written in Scala.</p> <p>Thanks in advance for any assistance that can be offered.</p> <p>NOTE:</p> <ul> <li>The combinations (x^2, y^2) must be whole/integer values.</li> <li>The fixed tests for the problem have 33 k values, the largest of them is 10000000095. These tests are followed by so far up to 48 random k values. The max time allowed to finish all k values is 16 seconds, and times out before finishing all the tests.</li> </ul>
[ { "answer_id": 74511089, "author": "Andrey Tyukin", "author_id": 2707792, "author_profile": "https://Stackoverflow.com/users/2707792", "pm_score": 0, "selected": false, "text": "z * z * z = x * x * y * y z * sqrt(z) = x * y sqrt(z) q = sqrt(z) q = f1^e1 * ... fN^eN f_i e_i x * y = f1^(3 * e1) * ... * fN^(3 * eN) (3 * e1 + 1) * ... * (3 * eN + 1) x y factorize def c(k: Long): Long = {\n val q = math.sqrt(k).toLong\n if (q * q == k) {\n val fs = factorize(q)\n fs.map(e => 3 * e._2 + 1).product\n } else {\n 0\n }\n}\n factorize def c(k: Long): Long = {\n val q = math.sqrt(k).toLong\n if (q * q == k) {\n val fs = factorize(q)\n fs.map(e => 3 * e._2 + 1).product\n } else {\n 0\n }\n}\n\n@main def main(): Unit = {\n println(c(1))\n println(c(4))\n println(c(4096576))\n println(c(2019))\n}\n\ndef factorize(i: Long): List[(Long, Int)] = {\n var odd = i\n var twoExp = 0\n while (odd % 2 == 0) {\n odd /= 2\n twoExp += 1\n }\n\n def factorizeRec(n: Long, divisor: Long, limit: Long): List[(Long, Int)] = {\n require(n >= 3)\n var unfactoredPart = n\n var e = 0\n while (unfactoredPart % divisor == 0) {\n unfactoredPart /= divisor\n e += 1\n }\n if (unfactoredPart == 1) {\n if (e > 0) {\n List((divisor, e))\n } else {\n Nil\n }\n } else {\n if (e > 0) {\n val newLimit = (math.sqrt(unfactoredPart).toInt + 1)\n (divisor, e) :: factorizeRec(unfactoredPart, divisor + 2, newLimit)\n } else {\n factorizeRec(unfactoredPart, divisor + 2, limit)\n }\n }\n }\n\n val sqrtLim = (math.sqrt(i).toInt + 1)\n val unevenFactors = \n if (odd >= 3) then factorizeRec(odd, 3, sqrtLim) \n else Nil\n\n if (twoExp > 0) {\n (2, twoExp) :: unevenFactors\n } else {\n unevenFactors\n }\n} \n\n 1\n4\n160\n0\n" }, { "answer_id": 74511867, "author": "AirSquid", "author_id": 10789207, "author_profile": "https://Stackoverflow.com/users/10789207", "pm_score": 0, "selected": false, "text": "z^3 x, y, z z x y a python scala #prime factorize\n\n# solving z^3 = y^2 * x^2\n\nfrom random import randint\n\n\ndef test(k):\n primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, ]\n if k==1 : return 1, {}\n # factor k^3\n k = k**3\n factors = {} # a dictionary mapping of prime:occurrences ...\n for p in primes:\n while k % (p**6) == 0:\n factors[p] = factors.get(p,0) + 1\n k /= p**6\n if k == 1: break\n if k != 1: return 0, {}\n\n # now loop through the factors & counts to construct possible pairs.\n # for each occurrence of each factor, we can put 0, 1, 2, ..., count*3 occurrences in \"x\"\n # so if there is 1 occurrence, we can put 0, 1, 2, 3 multiples of the factor in the first digit\n # or, more generally, 3 * count + 1\n if len(factors) == 0:\n return 0, {}\n tot = 1\n for v in factors.values():\n tot *= 3*v+1\n return tot, factors\n\n\nfor k in (1, 4, 16, 2019, 4096576, 10_000_000_000):\n print(k, test(k))\n\n# test over randomized list\nvals = [randint(1,10_000_000_000) for _ in range(100_000)]\nfor val in vals:\n result = test(val)\n if result[0]:\n print(val, result)\n 1 (1, {})\n4 (4, {2: 1})\n16 (7, {2: 2})\n2019 (0, {})\n4096576 (160, {2: 3, 11: 1, 23: 1})\n10000000000 (0, {})\n[Finished in 563ms]\n" }, { "answer_id": 74523958, "author": "Hooahclitus", "author_id": 20555860, "author_profile": "https://Stackoverflow.com/users/20555860", "pm_score": 2, "selected": false, "text": "def c(k: Long) = {\n val sqrtk = math.sqrt(k)\n\n @annotation.tailrec\n def factorList(x: Long, n: Long = 2, ls: List[Long] = Nil): List[Long] = {\n n * n > x match {\n case false if x % n == 0 => factorList(x / n, n, n :: ls)\n case false => factorList(x, n + 1, ls)\n case true => x :: ls\n }\n }\n\n sqrtk.isWhole match {\n case false => 0\n case true =>\n factorList(sqrtk.toLong)\n .groupBy(identity)\n .map { case (_, v) => 3 * v.size + 1 }\n .product\n }\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20555860/" ]
74,509,980
<p>it asks for sales tax, but then prints a long number for total tax</p> <pre><code>#This program will ask user for sales and calcutate state, county, and total sales tax. #This module calculates the county tax def askTotalSales(): totalSales=float(input(&quot;Enter sales for the month: &quot;)) print() return totalSales def countyTax(totalSales): countyTax= .02 return totalSales*countyTax def stateTax(totalSales): stateTax= .04 return totalSales *stateTax #This module calculates the state tax #this module will calculate total sales tax def calcTotalTax(stateTax, countyTax): totalTax=stateTax+countyTax print() return totalTax #printData def printTotalTax (countyTax, stateTax, totalTax): print ('County sales tax is'+countyTax) print('State sales tax is' +stateTax) print('Total sales tax is' +totalTax) def main(): totalSales=askTotalSales() countySales=countyTax(totalSales) stateSales=stateTax(totalSales) totalTax=float(input(calcTotalTax)) main() </code></pre> <p>an online class with zero instruction is not ideal, i've pored throjugh these pages and some youtube videos to come up with this</p> <p>i understand the issue may be with my Cacltotal tax function- i'm unsure of how to call it</p>
[ { "answer_id": 74511089, "author": "Andrey Tyukin", "author_id": 2707792, "author_profile": "https://Stackoverflow.com/users/2707792", "pm_score": 0, "selected": false, "text": "z * z * z = x * x * y * y z * sqrt(z) = x * y sqrt(z) q = sqrt(z) q = f1^e1 * ... fN^eN f_i e_i x * y = f1^(3 * e1) * ... * fN^(3 * eN) (3 * e1 + 1) * ... * (3 * eN + 1) x y factorize def c(k: Long): Long = {\n val q = math.sqrt(k).toLong\n if (q * q == k) {\n val fs = factorize(q)\n fs.map(e => 3 * e._2 + 1).product\n } else {\n 0\n }\n}\n factorize def c(k: Long): Long = {\n val q = math.sqrt(k).toLong\n if (q * q == k) {\n val fs = factorize(q)\n fs.map(e => 3 * e._2 + 1).product\n } else {\n 0\n }\n}\n\n@main def main(): Unit = {\n println(c(1))\n println(c(4))\n println(c(4096576))\n println(c(2019))\n}\n\ndef factorize(i: Long): List[(Long, Int)] = {\n var odd = i\n var twoExp = 0\n while (odd % 2 == 0) {\n odd /= 2\n twoExp += 1\n }\n\n def factorizeRec(n: Long, divisor: Long, limit: Long): List[(Long, Int)] = {\n require(n >= 3)\n var unfactoredPart = n\n var e = 0\n while (unfactoredPart % divisor == 0) {\n unfactoredPart /= divisor\n e += 1\n }\n if (unfactoredPart == 1) {\n if (e > 0) {\n List((divisor, e))\n } else {\n Nil\n }\n } else {\n if (e > 0) {\n val newLimit = (math.sqrt(unfactoredPart).toInt + 1)\n (divisor, e) :: factorizeRec(unfactoredPart, divisor + 2, newLimit)\n } else {\n factorizeRec(unfactoredPart, divisor + 2, limit)\n }\n }\n }\n\n val sqrtLim = (math.sqrt(i).toInt + 1)\n val unevenFactors = \n if (odd >= 3) then factorizeRec(odd, 3, sqrtLim) \n else Nil\n\n if (twoExp > 0) {\n (2, twoExp) :: unevenFactors\n } else {\n unevenFactors\n }\n} \n\n 1\n4\n160\n0\n" }, { "answer_id": 74511867, "author": "AirSquid", "author_id": 10789207, "author_profile": "https://Stackoverflow.com/users/10789207", "pm_score": 0, "selected": false, "text": "z^3 x, y, z z x y a python scala #prime factorize\n\n# solving z^3 = y^2 * x^2\n\nfrom random import randint\n\n\ndef test(k):\n primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, ]\n if k==1 : return 1, {}\n # factor k^3\n k = k**3\n factors = {} # a dictionary mapping of prime:occurrences ...\n for p in primes:\n while k % (p**6) == 0:\n factors[p] = factors.get(p,0) + 1\n k /= p**6\n if k == 1: break\n if k != 1: return 0, {}\n\n # now loop through the factors & counts to construct possible pairs.\n # for each occurrence of each factor, we can put 0, 1, 2, ..., count*3 occurrences in \"x\"\n # so if there is 1 occurrence, we can put 0, 1, 2, 3 multiples of the factor in the first digit\n # or, more generally, 3 * count + 1\n if len(factors) == 0:\n return 0, {}\n tot = 1\n for v in factors.values():\n tot *= 3*v+1\n return tot, factors\n\n\nfor k in (1, 4, 16, 2019, 4096576, 10_000_000_000):\n print(k, test(k))\n\n# test over randomized list\nvals = [randint(1,10_000_000_000) for _ in range(100_000)]\nfor val in vals:\n result = test(val)\n if result[0]:\n print(val, result)\n 1 (1, {})\n4 (4, {2: 1})\n16 (7, {2: 2})\n2019 (0, {})\n4096576 (160, {2: 3, 11: 1, 23: 1})\n10000000000 (0, {})\n[Finished in 563ms]\n" }, { "answer_id": 74523958, "author": "Hooahclitus", "author_id": 20555860, "author_profile": "https://Stackoverflow.com/users/20555860", "pm_score": 2, "selected": false, "text": "def c(k: Long) = {\n val sqrtk = math.sqrt(k)\n\n @annotation.tailrec\n def factorList(x: Long, n: Long = 2, ls: List[Long] = Nil): List[Long] = {\n n * n > x match {\n case false if x % n == 0 => factorList(x / n, n, n :: ls)\n case false => factorList(x, n + 1, ls)\n case true => x :: ls\n }\n }\n\n sqrtk.isWhole match {\n case false => 0\n case true =>\n factorList(sqrtk.toLong)\n .groupBy(identity)\n .map { case (_, v) => 3 * v.size + 1 }\n .product\n }\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509980", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20555680/" ]
74,509,986
<p>I have a tricky requirement where I need create copy of a service that has been created via Constructor DI in my Azure Function</p> <pre><code>public MyFunction(IMyService myService, IServiceProvider serviceProvider, ServiceCollectionContainer serviceCollectionContainer) { _myService = tmToolsService; _serviceProvider = serviceProvider; _serviceCollectionContainer = serviceCollectionContainer; } [FunctionName(&quot;diagnostic-orchestration&quot;)] public async Task DiagnosticOrchestrationAsync( [OrchestrationTrigger] IDurableOrchestrationContext context) { } </code></pre> <p>This service has a lot of dependencies so I dont really want go down the manual Activator.CreateInstance route</p> <p>I have tried 2 different approaches</p> <p><strong>Approach 1</strong></p> <p>I have ServiceCollectionContainer. This is filled in Configure of the startup and simply holds the services</p> <pre><code>public override void Configure(IFunctionsHostBuilder builder) { base.Configure(builder); var services = builder.Services; services.AddSingleton(s =&gt; new ServiceCollectionContainer(services)); } </code></pre> <p>In my function I call</p> <pre><code>var provider = _serviceCollectionContainer.ServiceCollection.BuildServiceProvider(); if (provider.GetService&lt;IMyService&gt;() is IMyService myService) { await myService.MyMathodAsync(); } </code></pre> <p>This throws the error</p> <pre><code>System.InvalidOperationException: 'Unable to resolve service for type 'Microsoft.Azure.WebJobs.Script.IEnvironment' while attempting to activate 'Microsoft.Azure.WebJobs.Script.Configuration.ScriptJobHostOptionsSetup'.' </code></pre> <p>I believe this could be because although the service collection looks fine (276 registered services) I have seen references online that say that Configure may be unreliable</p> <p><strong>Approach 2</strong></p> <p>The second approach is the more conventional one, I just tried to use the service provider injected without making any changes</p> <pre><code>if (_serviceProvider.GetService&lt;IMyService&gt;() is IMyService myService) { await myService.MyMathodAsync(); } </code></pre> <p>But if I use this approach I get the error</p> <p>'Scope disposed{no name} is disposed and scoped instances are disposed and no longer availab</p> <p>How can I fix this?</p> <p>I have large date range of data that I am processing. I need to split my date range and use my service to process each date range. My service has repositories. Each repository has a DbContext. Having each segment of dates run in the context of its own service allows me to run the processing in parallel without having DbContext queries being run in parallel which causes issues with Ef Core</p> <p>This processing is running inside a durable function</p>
[ { "answer_id": 74554182, "author": "david-ao", "author_id": 11509101, "author_profile": "https://Stackoverflow.com/users/11509101", "pm_score": 2, "selected": false, "text": "public MyFunction(IServiceScopeFactory serviceScopeFactory) \n{\n _serviceScopeFactory = serviceScopeFactory;\n}\n var tasks = yourSegments.Select(async segment =>\n {\n using (var scope = _serviceScopeFactory.CreateScope())\n {\n var IMyService = scope.ServiceProvider.GetRequiredService<IMyService>();\n await IMyService.MyMathodAsync(segment);\n\n\n }\n });\n\n await Task.WhenAll(tasks);\n" }, { "answer_id": 74612876, "author": "Marvin Klein", "author_id": 13440841, "author_profile": "https://Stackoverflow.com/users/13440841", "pm_score": 1, "selected": true, "text": "_myService.DeepCopyByExpressionTree();" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74509986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/267955/" ]
74,510,020
<p>This is the MWE:</p> <pre><code>interface Animals {cat:string, dog:string} let a: Animals|undefined; if(a){// if we got `a` from somewhere [1,2,3].map(v=&gt;a.cat) // ----------&gt; ~ Object is possibly 'undefined' } </code></pre> <p><a href="https://www.typescriptlang.org/play?ssl=22&amp;ssc=1&amp;pln=15&amp;pc=1#code/PTAEHUFMBsGMHsC2lQBd5oBYoCoE8AHSAZVgCcBLA1UABWgEM8BzM%20AVwDsATAGiwoBnUENANQAd0gAjQRVSQAUCEmYKsTKGYUAbpGF4OY0BoadYKdJMoL%20gzAzIoz3UNEiPOofEVKVqAHSKymAAmkYI7NCuqGqcANag8ABmIjQUXrFOKBJMggBcISGgoAC0oACCbvCwDKgU8JkY7p7ehCTkVDQS2E6gnPCxGcwmZqDSTgzxxWWVoASMFmgYkAAeRJTInN3ymj4d-jSCeNsMq-wuoPaOltigAKoASgAywhK7SbGQZIIz5VWCFzSeCrZagNYbChbHaxUDcCjJZLfSDbExIAgUdxkUBIursJzCFJtXydajBBCcQQ0MwAUVWDEQC0gADVHBQGNJ3KAALygABEAAkYNAMOB4GRonzFBTBPB3AERcwABS0%20mM9ysygc9wASmCKhwzQ8ZC8iHFzmB7BoXzcZmY7AYzEg-Fg0HUiQ58D0Ii8fLpDKZgj5SWxfPADlQAHJhAA5SASPlBFQAeS%20ZHegmdWkgR1QjgUrmkeFATjNOmGWH0KAQiGhwkuNok4uiIgMHGxCyYrA4PCCGQUZGSDCWFU4UIY0GEAG9aqh8lTKJxmPxuPBmPPUIvmABfYLuan5SpjxATwQAHy43EgyQykG4AG5ggiVTqp4pQABtACMvAATLwAGYAF0AhPAglR0bkAD4GACWc9V3YIgA" rel="nofollow noreferrer">Playground</a></p> <p>I am not sure what exactly the error is, it seems to be related to map outputting something or undefined, but why <code>a</code> isn't defined?</p>
[ { "answer_id": 74510171, "author": "OFRBG", "author_id": 1231844, "author_profile": "https://Stackoverflow.com/users/1231844", "pm_score": 0, "selected": false, "text": "const" }, { "answer_id": 74510179, "author": "jcalz", "author_id": 2887218, "author_profile": "https://Stackoverflow.com/users/2887218", "pm_score": 1, "selected": false, "text": "a Animals | undefined Animals if (a) v => a.cat a Animals | undefined v => a.cat Array.prototype.map() [1,2,3].map foo function foo(cb: (x: number) => string) {\n setTimeout(() => cb(100), 1000);\n}\n\na = { cat: \"abc\", dog: \"def\" };\nif (a) {\n foo(v => a.cat) // error!\n // ----> ~ Object is possibly 'undefined'\n}\na = undefined;\n// later: Uncaught TypeError: a is undefined\n foo() a undefined a map() map() foo() a undefined const if (a) {\n const _a = a;\n [1, 2, 3].map(v => _a.cat) // okay\n}\n _a Animals Animals | undefined" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510020", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12582392/" ]
74,510,025
<p>I am trying to add a background image which is always there no matter which route is active. I the example below is inspired by <a href="https://stackoverflow.com/questions/44179889/how-do-i-set-background-image-in-flutter">this answer</a> but the background will only be visible for the route &quot;/&quot;. I was hoping to not have to set the background image for each route. Any suggestions?</p> <pre><code>Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', home: const BoxDecoration( image: DecorationImage( image: AssetImage(&quot;assets/images/camping-background.png&quot;), fit: BoxFit.cover), ), routes: &lt;String, WidgetBuilder&gt;{ '/login': (BuildContext context) =&gt; const Login(), '/register': (BuildContext context) =&gt; const Register(), '/home': (BuildContext context) =&gt; const Home(), }, ); } </code></pre>
[ { "answer_id": 74510315, "author": "geisterfurz007", "author_id": 6707985, "author_profile": "https://Stackoverflow.com/users/6707985", "pm_score": 4, "selected": true, "text": "builder MaterialApp DecoratedBox import 'package:flutter/material.dart';\n\nvoid main() {\n runApp(Example());\n}\n\nclass Example extends StatelessWidget {\n @override\n Widget build(BuildContext context) {\n return DecoratedBox(\n decoration: const BoxDecoration(\n image: DecorationImage(\n image: NetworkImage(\"https://flutter.github.io/assets-for-api-docs/assets/widgets/owl-2.jpg\"),\n fit: BoxFit.cover,\n ),\n ),\n child: MaterialApp(\n title: 'Flutter Demo',\n initialRoute: '/login',\n routes: <String, WidgetBuilder>{\n '/login': (BuildContext context) => Login(),\n '/home': (BuildContext context) => Home(),\n },\n ),\n );\n }\n}\n\nclass Home extends StatelessWidget {\n @override\n Widget build(BuildContext context) {\n return Column(\n children: [\n const Text('Home'),\n ElevatedButton(onPressed: () => Navigator.of(context).pop(), child: const Text('Go back')),\n ]\n );\n }\n}\n\nclass Login extends StatelessWidget {\n @override\n Widget build(BuildContext context) {\n return Column(\n children: [\n const Text('Login'),\n ElevatedButton(onPressed: () => Navigator.of(context).pushNamed('/home'), child: const Text('Login')),\n ]\n );\n }\n}\n builder MaterialApp import 'package:flutter/material.dart';\n\nvoid main() {\n runApp(Example());\n}\n\nclass Example extends StatelessWidget {\n @override\n Widget build(BuildContext context) {\n return MaterialApp(\n title: 'Flutter Demo',\n builder: (context, child) => DecoratedBox(\n decoration: const BoxDecoration(\n image: DecorationImage(\n image: NetworkImage(\"https://flutter.github.io/assets-for-api-docs/assets/widgets/owl-2.jpg\"),\n fit: BoxFit.cover,\n ),\n ),\n child: child,\n ),\n initialRoute: '/login',\n routes: <String, WidgetBuilder>{\n '/login': (BuildContext context) => Login(),\n '/home': (BuildContext context) => Home(),\n },\n );\n }\n}\n\nclass Home extends StatelessWidget {\n @override\n Widget build(BuildContext context) {\n return Column(\n children: [\n const Text('Home'),\n ElevatedButton(onPressed: () => Navigator.of(context).pop(), child: const Text('Go back')),\n ]\n );\n }\n}\n\nclass Login extends StatelessWidget {\n @override\n Widget build(BuildContext context) {\n return Column(\n children: [\n const Text('Login'),\n ElevatedButton(onPressed: () => Navigator.of(context).pushNamed('/home'), child: const Text('Login')),\n ]\n );\n }\n}\n BuildContext child home routes MaterialApp home routes routes initialRoute /" }, { "answer_id": 74510926, "author": "Paulo", "author_id": 15649348, "author_profile": "https://Stackoverflow.com/users/15649348", "pm_score": 0, "selected": false, "text": "import 'package:flutter/material.dart';\n\nvoid main() {\n runApp(MyApp());\n}\n\nclass BaseLayout extends StatelessWidget {\n final Widget? child;\n\n const BaseLayout({Key? key, @required this.child}) : super(key: key);\n\n @override\n Widget build(BuildContext context) {\n return Container(\n width: 720,\n decoration: const BoxDecoration(\n image: DecorationImage(\n image: NetworkImage(\n \"https://images.pexels.com/photos/440731/pexels-photo-440731.jpeg\"),\n fit: BoxFit.fill),\n ),\n child: child,\n );\n }\n}\n\nclass MyApp extends StatelessWidget {\n @override\n Widget build(BuildContext context) {\n return MaterialApp(\n home: Scaffold(\n appBar: AppBar(title: const Text('Home')),\n body: BaseLayout(child: Home()),\n ),\n routes: <String, WidgetBuilder>{\n '/login': (BuildContext context) => Login(),\n '/register': (BuildContext context) => Register(),\n '/home': (BuildContext context) => Home(),\n },\n );\n }\n}\n\nclass Home extends StatelessWidget {\n @override\n Widget build(BuildContext context) {\n return Column(\n children: [\n const Text('HOMEPAGE', style: TextStyle(fontSize: 32)),\n const SizedBox(height: 12),\n ElevatedButton(\n child: const Text('Login'),\n onPressed: () {\n Navigator.push(\n context,\n MaterialPageRoute(\n builder: (context) => Scaffold(\n appBar: AppBar(title: const Text('Login')),\n body: BaseLayout(child: Login())),\n ),\n );\n },\n ),\n const SizedBox(height: 12),\n ElevatedButton(\n child: const Text('Register'),\n onPressed: () {\n Navigator.push(\n context,\n MaterialPageRoute(\n builder: (context) => BaseLayout(child: Register())),\n );\n },\n ),\n const SizedBox(height: 12),\n ElevatedButton(\n child: const Text('No Background Image Screen'),\n onPressed: () {\n Navigator.push(\n context,\n MaterialPageRoute(builder: (context) => NoBackground()),\n );\n },\n ),\n ],\n );\n }\n}\n\nclass Login extends StatelessWidget {\n @override\n Widget build(BuildContext context) {\n return Column(\n children: [\n Text(\n 'Login',\n style: Theme.of(context).textTheme.headline4,\n ),\n const SizedBox(height: 12),\n ElevatedButton(\n child: const Text('Back to Homepage'),\n onPressed: () {\n Navigator.pop(context);\n },\n ),\n ],\n );\n }\n}\n\nclass Register extends StatelessWidget {\n @override\n Widget build(BuildContext context) {\n return Column(\n children: [\n Text(\n 'Register!',\n style: Theme.of(context).textTheme.headline4,\n ),\n const SizedBox(height: 12),\n ElevatedButton(\n child: const Text('Back to Homepage'),\n onPressed: () {\n Navigator.pop(context);\n },\n ),\n ],\n );\n }\n}\n\nclass NoBackground extends StatelessWidget {\n @override\n Widget build(BuildContext context) {\n return Column(\n children: [\n const Text(\n 'No Background Image!',\n style: TextStyle(color: Colors.white),\n ),\n const SizedBox(height: 12),\n ElevatedButton(\n child: const Text('Back to Homepage'),\n onPressed: () {\n Navigator.pop(context);\n },\n ),\n ],\n );\n }\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1348837/" ]
74,510,031
<p>I use a ViewModel to allow user's to enter all kind of Filterdata and then execute them. In certain cases I need to chnge the values at serverside and return the View with those changed data. Sounds simple ;)</p> <p>Here is where the magic stops: I cannot get the changed data to appear in the View.</p> <p><strong>This is the View:</strong></p> <pre><code>@model DrieHamersV4.ViewModels.FilterListVM @using DrieHamersV4.Helpers; &lt;form asp-action=&quot;CreateMailingList&quot; method=&quot;get&quot; enctype=&quot;multipart/form-data&quot;&gt; &lt;div&gt; &lt;input asp-for=&quot;FRoepnaam&quot; class=&quot;form-control&quot; placeholder=&quot;@Html.DisplayNameFor(c =&gt; Model.FRoepnaam)&quot; /&gt; &lt;label asp-for=&quot;FRoepnaam&quot;&gt;&lt;/label&gt; &lt;/div&gt; &lt;div&gt; &lt;input asp-for=&quot;FAchternaam&quot; class=&quot;form-control&quot; placeholder=&quot;@Html.DisplayNameFor(c =&gt; Model.FAchternaam)&quot; /&gt; &lt;label asp-for=&quot;FAchternaam&quot;&gt;&lt;/label&gt; &lt;/div&gt; &lt;div&gt; &lt;div&gt;@ViewBag.Random&lt;/div&gt; &lt;div&gt; &lt;button type=&quot;submit&quot;&gt;Apply Filter&lt;/button&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p><strong>This is the Controller</strong></p> <pre><code> public async Task&lt;IActionResult&gt; CreateMailingList(FilterListVM mailingList) { // all fields to use as filters // // string fFirstName = mailingList.FRoepnaam; string fLastName = mailingList.FAchternaam; // Testing if the new number `num` will appear in View() Random rnd = new Random(); int num = rnd.Next(0, 100); mailingList.FAchternaam = num.ToString(); // When loading works, but not after renewing View() ViewBag.Random = (num.ToString()); //Works fine return View(mailingList); } </code></pre> <p>One way or another the View() refers back to the values when it initially loaded. Changing the values at the clientside works just fine. Changing them at the serverside, however is the problem. The View uses the model <code>@model DrieHamersV4.ViewModels.FilterListVM </code> I am sure I am missing something obvious. Any thoughts?</p>
[ { "answer_id": 74510315, "author": "geisterfurz007", "author_id": 6707985, "author_profile": "https://Stackoverflow.com/users/6707985", "pm_score": 4, "selected": true, "text": "builder MaterialApp DecoratedBox import 'package:flutter/material.dart';\n\nvoid main() {\n runApp(Example());\n}\n\nclass Example extends StatelessWidget {\n @override\n Widget build(BuildContext context) {\n return DecoratedBox(\n decoration: const BoxDecoration(\n image: DecorationImage(\n image: NetworkImage(\"https://flutter.github.io/assets-for-api-docs/assets/widgets/owl-2.jpg\"),\n fit: BoxFit.cover,\n ),\n ),\n child: MaterialApp(\n title: 'Flutter Demo',\n initialRoute: '/login',\n routes: <String, WidgetBuilder>{\n '/login': (BuildContext context) => Login(),\n '/home': (BuildContext context) => Home(),\n },\n ),\n );\n }\n}\n\nclass Home extends StatelessWidget {\n @override\n Widget build(BuildContext context) {\n return Column(\n children: [\n const Text('Home'),\n ElevatedButton(onPressed: () => Navigator.of(context).pop(), child: const Text('Go back')),\n ]\n );\n }\n}\n\nclass Login extends StatelessWidget {\n @override\n Widget build(BuildContext context) {\n return Column(\n children: [\n const Text('Login'),\n ElevatedButton(onPressed: () => Navigator.of(context).pushNamed('/home'), child: const Text('Login')),\n ]\n );\n }\n}\n builder MaterialApp import 'package:flutter/material.dart';\n\nvoid main() {\n runApp(Example());\n}\n\nclass Example extends StatelessWidget {\n @override\n Widget build(BuildContext context) {\n return MaterialApp(\n title: 'Flutter Demo',\n builder: (context, child) => DecoratedBox(\n decoration: const BoxDecoration(\n image: DecorationImage(\n image: NetworkImage(\"https://flutter.github.io/assets-for-api-docs/assets/widgets/owl-2.jpg\"),\n fit: BoxFit.cover,\n ),\n ),\n child: child,\n ),\n initialRoute: '/login',\n routes: <String, WidgetBuilder>{\n '/login': (BuildContext context) => Login(),\n '/home': (BuildContext context) => Home(),\n },\n );\n }\n}\n\nclass Home extends StatelessWidget {\n @override\n Widget build(BuildContext context) {\n return Column(\n children: [\n const Text('Home'),\n ElevatedButton(onPressed: () => Navigator.of(context).pop(), child: const Text('Go back')),\n ]\n );\n }\n}\n\nclass Login extends StatelessWidget {\n @override\n Widget build(BuildContext context) {\n return Column(\n children: [\n const Text('Login'),\n ElevatedButton(onPressed: () => Navigator.of(context).pushNamed('/home'), child: const Text('Login')),\n ]\n );\n }\n}\n BuildContext child home routes MaterialApp home routes routes initialRoute /" }, { "answer_id": 74510926, "author": "Paulo", "author_id": 15649348, "author_profile": "https://Stackoverflow.com/users/15649348", "pm_score": 0, "selected": false, "text": "import 'package:flutter/material.dart';\n\nvoid main() {\n runApp(MyApp());\n}\n\nclass BaseLayout extends StatelessWidget {\n final Widget? child;\n\n const BaseLayout({Key? key, @required this.child}) : super(key: key);\n\n @override\n Widget build(BuildContext context) {\n return Container(\n width: 720,\n decoration: const BoxDecoration(\n image: DecorationImage(\n image: NetworkImage(\n \"https://images.pexels.com/photos/440731/pexels-photo-440731.jpeg\"),\n fit: BoxFit.fill),\n ),\n child: child,\n );\n }\n}\n\nclass MyApp extends StatelessWidget {\n @override\n Widget build(BuildContext context) {\n return MaterialApp(\n home: Scaffold(\n appBar: AppBar(title: const Text('Home')),\n body: BaseLayout(child: Home()),\n ),\n routes: <String, WidgetBuilder>{\n '/login': (BuildContext context) => Login(),\n '/register': (BuildContext context) => Register(),\n '/home': (BuildContext context) => Home(),\n },\n );\n }\n}\n\nclass Home extends StatelessWidget {\n @override\n Widget build(BuildContext context) {\n return Column(\n children: [\n const Text('HOMEPAGE', style: TextStyle(fontSize: 32)),\n const SizedBox(height: 12),\n ElevatedButton(\n child: const Text('Login'),\n onPressed: () {\n Navigator.push(\n context,\n MaterialPageRoute(\n builder: (context) => Scaffold(\n appBar: AppBar(title: const Text('Login')),\n body: BaseLayout(child: Login())),\n ),\n );\n },\n ),\n const SizedBox(height: 12),\n ElevatedButton(\n child: const Text('Register'),\n onPressed: () {\n Navigator.push(\n context,\n MaterialPageRoute(\n builder: (context) => BaseLayout(child: Register())),\n );\n },\n ),\n const SizedBox(height: 12),\n ElevatedButton(\n child: const Text('No Background Image Screen'),\n onPressed: () {\n Navigator.push(\n context,\n MaterialPageRoute(builder: (context) => NoBackground()),\n );\n },\n ),\n ],\n );\n }\n}\n\nclass Login extends StatelessWidget {\n @override\n Widget build(BuildContext context) {\n return Column(\n children: [\n Text(\n 'Login',\n style: Theme.of(context).textTheme.headline4,\n ),\n const SizedBox(height: 12),\n ElevatedButton(\n child: const Text('Back to Homepage'),\n onPressed: () {\n Navigator.pop(context);\n },\n ),\n ],\n );\n }\n}\n\nclass Register extends StatelessWidget {\n @override\n Widget build(BuildContext context) {\n return Column(\n children: [\n Text(\n 'Register!',\n style: Theme.of(context).textTheme.headline4,\n ),\n const SizedBox(height: 12),\n ElevatedButton(\n child: const Text('Back to Homepage'),\n onPressed: () {\n Navigator.pop(context);\n },\n ),\n ],\n );\n }\n}\n\nclass NoBackground extends StatelessWidget {\n @override\n Widget build(BuildContext context) {\n return Column(\n children: [\n const Text(\n 'No Background Image!',\n style: TextStyle(color: Colors.white),\n ),\n const SizedBox(height: 12),\n ElevatedButton(\n child: const Text('Back to Homepage'),\n onPressed: () {\n Navigator.pop(context);\n },\n ),\n ],\n );\n }\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5914094/" ]
74,510,050
<p>I found this problem and wanted to try to execute, but got stuck:</p> <p><em>Compile a program that allows you to determine how many days will be enough for 200 something if consumed on the first day 5 tons, but every next day 20% more than the previous day.</em></p> <p>In Python, using loop operators, lists and functions.</p> <p>I tried with the def function, but I don't know if it's correct and I don't know how to get it so that when it increases by 20%, the new number increases by 20%, so all the time with new numbers until it reaches 200</p> <pre><code>def day(): x=5 x += (x * 20/100) print(x) day() </code></pre> <p>it is just a half, i know.</p>
[ { "answer_id": 74510124, "author": "QWERTYL", "author_id": 11777402, "author_profile": "https://Stackoverflow.com/users/11777402", "pm_score": 0, "selected": false, "text": "def day(x):\n return x + (x * 20/100)\n\nx = 5\ncurrentSum = x\nday = 1\nwhile(currentSum < 200): # Loop until the amount consumed is more than 200\n x = day(x)\n currentSum += x\n day += 1\n\nprint(day)\n" }, { "answer_id": 74510133, "author": "philbeet", "author_id": 14503617, "author_profile": "https://Stackoverflow.com/users/14503617", "pm_score": 1, "selected": true, "text": "while x = 5\ndayscount = 1\nwhile x < 200:\n print(x)\n print(dayscount)\n dayscount = dayscount + 1\n x = x * (1+(20/100))\n" }, { "answer_id": 74510172, "author": "ahmedsultan", "author_id": 19823172, "author_profile": "https://Stackoverflow.com/users/19823172", "pm_score": 1, "selected": false, "text": "numberOfDays = 0 \ntotalTons = 200\ndayTonsUsed = 5 \n while (totalTons > 0):\n totalTons -= dayTonsUsed\n dayTonsUsed *= 1.2 # Adding extra 20% of consumption for the next day \n numberOfDays += 1 \n\n print(f\"Number of days needed {numberOfDays} days\")\n" }, { "answer_id": 74511218, "author": "SergFSM", "author_id": 18344512, "author_profile": "https://Stackoverflow.com/users/18344512", "pm_score": 0, "selected": false, "text": "def day(n, x=5):\n return 1 + day(n-x, x*1.2) if n>0 else 0\n\nday(200) # 13\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510050", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20556053/" ]
74,510,061
<p>I have a string that contains &quot;...&quot; in different places. And a string array with the same amount of words as the number of &quot;...&quot;.</p> <p>I want to replace all occurrences of &quot;...&quot; with the words from the string array.</p> <pre><code>let stringToReplace = &quot;I want an ... that I get from the ...&quot; let stringArray = [&quot;apple&quot;,&quot;shop&quot;] result = &quot;I want an apple that I get from the shop&quot; </code></pre> <p>I have tried this:</p> <pre><code>let result = stringToReplace; for (let i = 0; i &lt; stringArray.length; i++) { let inloc = stringArray[i]; result = result.replace(&quot;...&quot;, inloc); } </code></pre> <p>But that would only change the first occurrence of &quot;...&quot;.</p>
[ { "answer_id": 74510102, "author": "Azad", "author_id": 19120939, "author_profile": "https://Stackoverflow.com/users/19120939", "pm_score": 1, "selected": false, "text": "// stringToReplace = \"I want an ... that I get from the ...\"\n// stringArray = [\"apple\",\"shop\"]\n\n// result = \"I want an apple that I get from the shop\"\n\nfunction replaceString(stringToReplace, stringArray) {\n var result = stringToReplace;\n for (var i = 0; i < stringArray.length; i++) {\n result = result.replace(\"...\", stringArray[i]);\n }\n return result;\n}\n\nconsole.log(\n replaceString(\"I want an ... that I get from the ...\", [\"apple\", \"shop\"])\n);\n" }, { "answer_id": 74510132, "author": "Andrew Parks", "author_id": 5898421, "author_profile": "https://Stackoverflow.com/users/5898421", "pm_score": 2, "selected": true, "text": "let s = \"I want an ... that I get from the ...\"\nlet r = [\"apple\",\"shop\"]\n\nconsole.log(s.split('...').flatMap((e,i)=>[e,r[i]]).join(''));" }, { "answer_id": 74510301, "author": "rushmarrs", "author_id": 9074591, "author_profile": "https://Stackoverflow.com/users/9074591", "pm_score": 0, "selected": false, "text": "let stringToReplace = \"I want an ... that I get from the ...\"\nlet stringArray = [\"apple\",\"shop\"]\n\nconst PLACEHOLDER = '...'\n\nconst replaceWords = (stringWithPlaceholders, variablesArray) => {\n const finalString = stringWithPlaceholders.split(PLACEHOLDER).reduce((acc, curr, i) => {\n const variableToAdd = variablesArray[i]\n const newStringSection = variableToAdd ? `${acc}${curr}${variableToAdd}` : `${acc}${curr}`\n \n return newStringSection\n }, '')\n\n return finalString\n}\n\nconsole.log(replaceWords(stringToReplace, stringArray))\n\n// => 'I want an apple that I get from the shop'\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510061", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16932373/" ]
74,510,080
<pre><code>yarn install v1.22.19 info No lockfile found. [1/4] Resolving packages... error An unexpected error occurred: &quot;https://registry.npmjs.org/@babel%2fhelper-builder-react-jsx: connect ECONNREFUSED 104.16.23.35:443&quot;. info If you think this is a bug, please open a bug report with the information provided in &quot;/media/bkroland19/ROLAND/FINAL/ElectionDapp-main/client/yarn-error.log&quot;. info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command. </code></pre>
[ { "answer_id": 74520148, "author": "Pandapip1", "author_id": 11628256, "author_profile": "https://Stackoverflow.com/users/11628256", "pm_score": 2, "selected": false, "text": "https://registry.npmjs.org/" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14123774/" ]
74,510,097
<p>Okay so, I'm pretty new to C.</p> <p>I've been trying to figure out what exactly is the difference between <code>putch()</code> and <code>putchar()</code>? I tried googling my answers but all I got was the same copy-pasted-like message that said:</p> <blockquote> <p><code>putchar()</code>: This function is used to print one character on the screen, and this may be any character from C character set (i.e it may be printable or non printable characters).</p> </blockquote> <blockquote> <p><code>putch()</code>: The <code>putch()</code> function is used to display all alphanumeric characters through the standard output device like monitor. this function display single character at a time.</p> </blockquote> <p>As English isn't my first language I'm kinda lost. Are there non printable characters in C? If so, what are they? And why can't <code>putch</code> produce the same results?</p> <p>I've tried googling the C character set and all of the alphanumeric characters there are, but as much as my testing went, there wasn't really anything that one function could print and the other couldn't.</p> <p>Anyways, I'm kind of lost.</p> <p>Could anyone help me out? thanks!</p> <p>TLDR; what can <code>putchar()</code> do that <code>putch()</code> can't? (or the opposite or something idk)</p> <p>dunno, hoped there would be a visible difference between the two but can't seem to find it.</p>
[ { "answer_id": 74510231, "author": "chqrlie", "author_id": 4593267, "author_profile": "https://Stackoverflow.com/users/4593267", "pm_score": 2, "selected": true, "text": "putchar() <stdio.h> stdout putch() stdout fflush(stdout)" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20556094/" ]
74,510,158
<p>How can I initialize my operation with require arguments based on the use case?</p>
[ { "answer_id": 74510426, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 1, "selected": false, "text": "dynamic_cast" }, { "answer_id": 74510568, "author": "Christopher Barrios Agosto", "author_id": 12625845, "author_profile": "https://Stackoverflow.com/users/12625845", "pm_score": 1, "selected": false, "text": "#include <iostream>\n\nstruct DataSet {\n public:\n double* data;\n int size;\n \n DataSet(double* data, unsigned int size) {\n this->data = new double[size];\n this->size = size;\n\n for (unsigned int i = 0; i < size; i++)\n this->data[i] = data[i];\n }\n};\n\ndouble mean(const DataSet& dataSet) {\n double mean = 0;\n for (unsigned int i = 0; i < dataSet.size; i++)\n mean += dataSet.data[i];\n mean = mean / dataSet.size;\n return mean;\n}\n\ndouble min(const DataSet& dataSet) {\n double min = dataSet.data[0];\n for (unsigned int i = 1; i < dataSet.size; i++)\n if (dataSet.data[i] < min)\n min = dataSet.data[i];\n return min;\n}\n\ndouble max(const DataSet& dataSet) {\n double min = dataSet.data[0];\n for (unsigned int i = 1; i < dataSet.size; i++)\n if (dataSet.data[i] > min)\n min = dataSet.data[i];\n return min;\n}\n\nint main() {\n double data[5] = { 1, 2, 3, 4, 5 };\n unsigned int size = 5;\n DataSet dataSet = DataSet(data, size);\n\n double result = 0;\n\n result = mean(dataSet);\n std::cout << \"Mean: \" << result << std::endl;\n\n result = min(dataSet);\n std::cout << \"Min: \" << result << std::endl;\n \n result = max(dataSet);\n std::cout << \"Max: \" << result << std::endl;\n}\n #include <iostream>\n\nclass DataSet {\n public:\n double* data;\n int size;\n \n DataSet() {\n data = nullptr;\n size = 0;\n }\n DataSet(double* data, unsigned int size) {\n this->data = new double[size];\n this->size = size;\n\n for (unsigned int i = 0; i < size; i++)\n this->data[i] = data[i];\n }\n ~DataSet() {\n if (data != nullptr)\n delete(data);\n }\n};\n\nclass Operation {\n protected:\n DataSet dataSet;\n public:\n Operation(double* data, unsigned int size) : dataSet(data, size) {\n \n }\n\n virtual double execute() = 0;\n};\n\nclass Mean : public Operation {\n public:\n Mean(double* data, unsigned int size) : Operation(data, size) {\n\n }\n ~Mean() {\n\n }\n\n double execute() {\n double mean = 0;\n for (unsigned int i = 0; i < dataSet.size; i++)\n mean += dataSet.data[i];\n mean = mean / dataSet.size;\n return mean;\n }\n};\n\nclass MinMax : public Operation {\n public:\n bool useMin;\n MinMax(double* data, unsigned int size) : useMin(true), Operation(data, size) {\n\n }\n ~MinMax() {\n\n }\n\n double execute() {\n if (useMin) {\n double min = dataSet.data[0];\n for (unsigned int i = 1; i < dataSet.size; i++)\n if (dataSet.data[i] < min)\n min = dataSet.data[i];\n return min;\n }\n else {\n double min = dataSet.data[0];\n for (unsigned int i = 1; i < dataSet.size; i++)\n if (dataSet.data[i] > min)\n min = dataSet.data[i];\n return min;\n }\n }\n};\n\nint main() {\n double data[5] = { 1, 2, 3, 4, 5 };\n unsigned int size = 5;\n DataSet dataSet = DataSet(data, size);\n\n double result = 0;\n\n Mean mean = Mean(data, size);\n std::cout << \"Mean: \" << mean.execute() << std::endl;\n\n MinMax minMax = MinMax(data, size);\n std::cout << \"MinMax: \" << minMax.execute() << std::endl;\n\n minMax.useMin = false;\n std::cout << \"MinMax: \" << minMax.execute() << std::endl;\n}\n useMin void" }, { "answer_id": 74511395, "author": "Maciej Polański", "author_id": 19165018, "author_profile": "https://Stackoverflow.com/users/19165018", "pm_score": 0, "selected": false, "text": " case MINMAX:\n return dynamic_cast<MinmaxOperationArguments*>(args)->is_min_op ?\n new MinOperation(args):\n new MaxOperation(args);\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10473181/" ]