qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,561,904
<p>My project (Java-Selenium-Maven-Cucumber) works on my device (Windows 10), but I'm unable to launch chrome driver in Linux server through Jenkins.</p> <p>I added chromedriver for Linux 64 to my framework.</p> <p>This is my code:</p> <pre><code>private static WebDriver driver; public static WebDriver get() { if (driver == null) { String browser = ConfigurationReader.get(&quot;browser&quot;); switch (browser.toLowerCase()) { case &quot;chrome&quot;: System.setProperty(&quot;webdriver.chrome.driver&quot;, System.getProperty(&quot;user.dir&quot;)+&quot;/chromedriver&quot; ); driver = new ChromeDriver(); break; </code></pre> <p>This is the error;</p> <pre><code>java.lang.IllegalStateException: The driver is not executable: /home/jenkins/workspace/Website-Automation/chromedriver at com.google.common.base.Preconditions.checkState(Preconditions.java:585) at org.openqa.selenium.remote.service.DriverService.checkExecutable(DriverService.java:150) at org.openqa.selenium.remote.service.DriverService.findExecutable(DriverService.java:141) at org.openqa.selenium.chrome.ChromeDriverService.access$000(ChromeDriverService.java:35) at org.openqa.selenium.chrome.ChromeDriverService$Builder.findDefaultExecutable(ChromeDriverService.java:159) at org.openqa.selenium.remote.service.DriverService$Builder.build(DriverService.java:355) at org.openqa.selenium.chrome.ChromeDriverService.createDefaultService(ChromeDriverService.java:94) at org.openqa.selenium.chrome.ChromeDriver.&lt;init&gt;(ChromeDriver.java:123) at utilities.Driver.get(Driver.java:35) at step_definitions.Hooks.setUp(Hooks.java:22) </code></pre> <p>If I add &quot;<em>chmod +x /home/jenkins/workspace/Website-Automation/chromedriver</em>&quot; to Jenkins like the below code, I get another error for this time; <em><strong>org.openqa.selenium.WebDriverException: Timed out waiting for driver server to start.</strong></em></p> <pre><code>stage('Build') { steps { sh ''' chmod +x /home/jenkins/workspace/Website-Automation/chromedriver mvn test''' } } </code></pre>
[ { "answer_id": 74562022, "author": "Kaan Tuğberk Avlamaz", "author_id": 19784706, "author_profile": "https://Stackoverflow.com/users/19784706", "pm_score": -1, "selected": false, "text": " System.setProperty(\"webdriver.edge.driver\", \"C:\\\\Users\\\\user\\\\Desktop\\\\msedgedriver.exe\")\n" }, { "answer_id": 74562439, "author": "Alex Karamfilov", "author_id": 7031148, "author_profile": "https://Stackoverflow.com/users/7031148", "pm_score": 1, "selected": true, "text": "chmod +x /home/jenkins/workspace/Website-Automation/chromedriver\n chmod +x /home/jenkins/workspace/Website-Automation/chromedriver\nmvn clean test\n WebDriverManager.chromedriver().setup();\n\n <dependency>\n <groupId>io.github.bonigarcia</groupId>\n <artifactId>webdrivermanager</artifactId>\n <version>5.3.1</version>\n</dependency>\n\n public static WebDriver get() {\n if (driver == null) {\n String browser = ConfigurationReader.get(\"browser\");\n switch (browser.toLowerCase()) {\n case \"chrome\":\n WebDriverManager.chromedriver().setup();\n driver = new ChromeDriver();\n break;\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74561904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16839522/" ]
74,561,910
<p>I have a category selector in my React app, and the category labels are displayed with flexbox so that they can be spaced evenly and horizontally. I've applied some styling changes to the hovered text to make the font weight heavier, but doing so has caused the labels surrounding the hovered one to shift. Is there a way I can fix this so that hovering doesnt cause anything to move, but instead just change the font weight?</p> <p>Here's my CSS:</p> <pre><code>.skills-category-selector { display: flex; justify-content: space-between; width: 100%; margin-top: 12px; } .category-label { cursor: pointer; font-size: 20px; font-weight: 500; } .category-label:hover { font-weight: 800; text-decoration: underline; } </code></pre>
[ { "answer_id": 74562201, "author": "Nick Vu", "author_id": 9201587, "author_profile": "https://Stackoverflow.com/users/9201587", "pm_score": 2, "selected": false, "text": "text-shadow .skills-category-selector {\n display: flex;\n justify-content: space-between;\n width: 100%;\n margin-top: 12px;\n}\n\n.category-label {\n cursor: pointer;\n font-size: 20px;\n font-weight: 500;\n}\n\n.category-label:hover {\n text-shadow: 1px 0 0 black;\n text-decoration: underline;\n} <div class=\"skills-category-selector\">\n <span class=\"category-label\">Category 1</span>\n <span class=\"category-label\">Category 2</span>\n <span class=\"category-label\">Category 3</span>\n</div>" }, { "answer_id": 74564660, "author": "Edgar MC", "author_id": 7824783, "author_profile": "https://Stackoverflow.com/users/7824783", "pm_score": 0, "selected": false, "text": ".skills-category-selector {\n display: flex;\n justify-content: space-between;\n width: 100%;\n margin-top: 12px;\n}\n\n.category-label{\n width: 20%;\n cursor: pointer;\n font-size: 20px;\n font-weight: 500;\n}\n\n.category-label:hover {\n font-weight: 800;\n text-decoration: underline;\n} <div class=\"skills-category-selector\">\n <span class=\"category-label\">Category 1</span>\n <span class=\"category-label\">Category 2</span>\n <span class=\"category-label\">Category 3</span>\n <span class=\"category-label\">Category 3</span>\n </div>" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74561910", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12329834/" ]
74,561,984
<p>I would like to build my own list item as a <strong>custom element</strong>:</p> <pre class="lang-html prettyprint-override"><code>&lt;ul&gt; &lt;my-li&gt;&lt;!-- Advanced stuff in shadow dom will be rendered here --&gt;&lt;/my-li&gt; &lt;/ul&gt; </code></pre> <p>However, within an ul tag, only the following elements are allowed (li, script, template). What would be the right approach here?</p> <p>1.) Definition of an aria-role on the custom element?</p> <pre class="lang-html prettyprint-override"><code>&lt;ul&gt; &lt;my-li aria-role=&quot;listitem&quot;&gt;&lt;!-- Advanced stuff in shadow dom will be rendered here --&gt;&lt;/my-li&gt; &lt;/ul&gt; </code></pre> <ol start="2"> <li>Using the li tag inside the shadow-dom?</li> </ol> <pre class="lang-html prettyprint-override"><code>&lt;ul&gt; &lt;my-li&gt;&lt;!-- Advanced stuff in shadow dom will be rendered within a li-tag here --&gt;&lt;/my-li&gt; &lt;/ul&gt; </code></pre> <ol start="3"> <li>Something else</li> </ol>
[ { "answer_id": 74562417, "author": "cwillinx", "author_id": 20238576, "author_profile": "https://Stackoverflow.com/users/20238576", "pm_score": 0, "selected": false, "text": "<div role=\"list\">\n <my-li role=\"listitem\"></my-li>\n</div>\n" }, { "answer_id": 74563331, "author": "QuentinC", "author_id": 1971216, "author_profile": "https://Stackoverflow.com/users/1971216", "pm_score": 2, "selected": true, "text": "<ul>\n <li>\n <your-custom-element/>\n </li>\n</ul>\n <ul> <ul> <div role=\"list\">\n <your-custom-element role=\"list-item\"/>\n</div>\n\nThe best would be my option 1. It works because you can put anything you like inside `<li>`.\n\nYou should avoid my option 3 if you can, for several reasons:\n\n- Avoid using ARIA unless it's really necessary\n- No ARIA is better than bad ARIA\n- It's not very clear if specifying the role on a custom element will work as expected, or if you have to report it yourself to the top element of your shadow DOM. It depends on what the browser / accessibility tree pass to assistive tools, and, as far as I know, it isn't very well defined, since custom elements are pretty new\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74561984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8860403/" ]
74,561,994
<p>I'm trying setup Pipeline Release for automation to create User Managed Identity and add it to SQL, I have finished running script with user AAD login to SQL on VM, but when I try setup on Release it stuck in auth with the error below (user AAD don't set MFA):</p> <p>Anyone has ever met that before, please give me some method to resolve it. Thanks!</p> <p><a href="https://i.stack.imgur.com/12ehJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/12ehJ.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/n75S3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/n75S3.png" alt="enter image description here" /></a></p> <pre><code>$ResourceGroup ='AAC-BYC-NNY' $SQLServer = 'azcacaufd1devsql01.database.windows.net' $Database = 'Core' $MyIdentity = 'user15' #Create User Managed Identity az identity create --resource-group $ResourceGroup --name $MyIdentity #add UMI to sql $query = &quot; CREATE USER [$MyIdentity] FROM EXTERNAL PROVIDER; ALTER ROLE db_datareader ADD MEMBER [$MyIdentity]; ALTER ROLE db_datawriter ADD MEMBER [$MyIdentity]; GRANT EXECUTE TO [$MyIdentity] GO &quot; write-output &quot;Create DB Account named $MyIdentity&quot; $connectString=&quot;Data Source=tcp:$SQLServer,1433;Initial Catalog=$Ddatabase;Authentication=Active Directory Password;User ID='devops@hosting.com';Password='123456';Trusted_Connection=False;Encrypt=True;Connection Timeout=30;&quot; Invoke-Sqlcmd -ConnectionString $connectString -Query $query </code></pre>
[ { "answer_id": 74562417, "author": "cwillinx", "author_id": 20238576, "author_profile": "https://Stackoverflow.com/users/20238576", "pm_score": 0, "selected": false, "text": "<div role=\"list\">\n <my-li role=\"listitem\"></my-li>\n</div>\n" }, { "answer_id": 74563331, "author": "QuentinC", "author_id": 1971216, "author_profile": "https://Stackoverflow.com/users/1971216", "pm_score": 2, "selected": true, "text": "<ul>\n <li>\n <your-custom-element/>\n </li>\n</ul>\n <ul> <ul> <div role=\"list\">\n <your-custom-element role=\"list-item\"/>\n</div>\n\nThe best would be my option 1. It works because you can put anything you like inside `<li>`.\n\nYou should avoid my option 3 if you can, for several reasons:\n\n- Avoid using ARIA unless it's really necessary\n- No ARIA is better than bad ARIA\n- It's not very clear if specifying the role on a custom element will work as expected, or if you have to report it yourself to the top element of your shadow DOM. It depends on what the browser / accessibility tree pass to assistive tools, and, as far as I know, it isn't very well defined, since custom elements are pretty new\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74561994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17801609/" ]
74,561,999
<p>I have a fixture in <code>conftest.py</code> with a function scope.</p> <pre><code>@pytest.fixture() def registration_setup( test_data, # fixture 1 credentials, # fixture 2 deployment # fixture 3 deployment_object # fixture 4 ): # pre-test cleanup do_cleanup() yield # post-test cleanup do_cleanup() </code></pre> <p>I use it in a test class like this:</p> <pre><code>class TestClass: @pytest.fixture(autouse=True) def _inventory_cleanup(self, registration_setup): log('Cleanup Done!') def test_1(): ... def test_2(): ... def test_3(): ... </code></pre> <p>Now I want to create a new test class where I run the <code>registartion_setup</code> fixture once for the entire class. The desired behaviour here is, First the pre-test cleanup executes and then all the tests in the new test class execute, followed by the post-test cleanup. How can I achieve this, thanks for the help.</p>
[ { "answer_id": 74562417, "author": "cwillinx", "author_id": 20238576, "author_profile": "https://Stackoverflow.com/users/20238576", "pm_score": 0, "selected": false, "text": "<div role=\"list\">\n <my-li role=\"listitem\"></my-li>\n</div>\n" }, { "answer_id": 74563331, "author": "QuentinC", "author_id": 1971216, "author_profile": "https://Stackoverflow.com/users/1971216", "pm_score": 2, "selected": true, "text": "<ul>\n <li>\n <your-custom-element/>\n </li>\n</ul>\n <ul> <ul> <div role=\"list\">\n <your-custom-element role=\"list-item\"/>\n</div>\n\nThe best would be my option 1. It works because you can put anything you like inside `<li>`.\n\nYou should avoid my option 3 if you can, for several reasons:\n\n- Avoid using ARIA unless it's really necessary\n- No ARIA is better than bad ARIA\n- It's not very clear if specifying the role on a custom element will work as expected, or if you have to report it yourself to the top element of your shadow DOM. It depends on what the browser / accessibility tree pass to assistive tools, and, as far as I know, it isn't very well defined, since custom elements are pretty new\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74561999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12058318/" ]
74,562,025
<p>I have a csv file named film.csv the title of each column is as follows (with a couple of example rows):</p> <pre><code>Year;Length;Title;Subject;Actor;Actress;Director;Popularity;Awards;*Image 1990;111;Tie Me Up! Tie Me Down!;Comedy;Banderas, Antonio;Abril, Victoria;Almodóvar, Pedro;68;No;NicholasCage.png 1991;113;High Heels;Comedy;Bosé, Miguel;Abril, Victoria;Almodóvar, Pedro;68;No;NicholasCage.png 1983;104;Dead Zone, The;Horror;Walken, Christopher;Adams, Brooke;Cronenberg, David;79;No;NicholasCage.png 1979;122;Cuba;Action;Connery, Sean;Adams, Brooke;Lester, Richard;6;No;seanConnery.png 1978;94;Days of Heaven;Drama;Gere, Richard;Adams, Brooke;Malick, Terrence;14;No;NicholasCage.png 1983;140;Octopussy;Action;Moore, Roger;Adams, Maud;Glen, John;68;No;NicholasCage.png </code></pre> <p>I need to parse this csv with basic command (not using Pandas)</p> <ol> <li><p>How would I extract all movie titles with the actor first name = Richard , made before year 1985 , and award = yes ? (I have been able to get it to show lisy where awards == yes , but not the rest)</p> </li> <li><p>How can I count how many times any given actor appears in the list?</p> </li> </ol> <pre><code>file_name = &quot;film.csv&quot; print('loading file') lines = (line for line in open(file_name,encoding='cp1252')) #generator to capture lines print('removing ;') lists = (s.rstrip().split(&quot;;&quot;) for s in lines) #generators to capture lists containing values from lines print('2-filter by awards') sel = input() if sel == '2': cols=next(lists) #obtains only the header print(cols) collections = (dict(zip(cols,data)) for data in lists) filtered = (col[&quot;Title&quot;] for col in collections if col[&quot;Awards&quot;][0]== &quot;Y&quot;) for item in filtered: print(item) # input() #browse lists and index them per header values, then filter all movies that have been awarded #using a new generator object else: </code></pre>
[ { "answer_id": 74562492, "author": "raz", "author_id": 16955114, "author_profile": "https://Stackoverflow.com/users/16955114", "pm_score": 1, "selected": true, "text": "filter = {}\nlines = open('test.csv', 'r').readlines()\ncolumns = lines[0].strip().split(';')\n\nlines.pop(0)\n\nfor i in lines:\n x = i.strip().split(';')\n # Checking if the movie was made before 1985\n if int(x[columns.index('Year')]) < 1985:\n # Checking if the actor's first name is Richard\n if x[columns.index('Actor')].split(', ')[1] == 'Richard':\n # Checking if awards == Yes\n if x[columns.index('Awards')] == 'Yes':\n # Printing out the title of the movie\n print(x[columns.index('Title')])\n name = \"Gere, Richard\" # Given actor name\n\ncount = 0\nfor i in lines:\n x = i.strip().split(';')\n # Checking if the actor's name is the given name\n if x[columns.index('Actor')] == name:\n # If it is, add 1 to the count\n count += 1\n" }, { "answer_id": 74564128, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 1, "selected": false, "text": "award == No award == Yes import csv\nfrom collections import Counter\n\nwith open(\"data.csv\", \"r\") as f_in:\n reader = csv.DictReader(f_in, delimiter=\";\")\n data = list(reader)\n\n# extract all movie titles with the actor first name = Richard , made before year 1985 , and award = No\n\nfor d in data:\n if (\n d[\"Actor\"].split(\", \")[-1] == \"Richard\"\n and int(d[\"Year\"]) < 1985\n and d[\"Awards\"] == \"No\"\n ):\n print(d)\n {\n \"Year\": \"1978\",\n \"Length\": \"94\",\n \"Title\": \"Days of Heaven\",\n \"Subject\": \"Drama\",\n \"Actor\": \"Gere, Richard\",\n \"Actress\": \"Adams, Brooke\",\n \"Director\": \"Malick, Terrence\",\n \"Popularity\": \"14\",\n \"Awards\": \"No\",\n \"*Image\": \"NicholasCage.png\",\n}\n collections.Counter cnt = Counter(d[\"Actor\"] for d in data)\nprint(cnt)\n Counter(\n {\n \"Banderas, Antonio\": 1,\n \"Bosé, Miguel\": 1,\n \"Walken, Christopher\": 1,\n \"Connery, Sean\": 1,\n \"Gere, Richard\": 1,\n \"Moore, Roger\": 1,\n }\n)\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74562025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20591518/" ]
74,562,028
<p>Environment:</p> <ul> <li>Node 16</li> <li>Gremlin for node.js/Javascript</li> <li>Amazon Neptune database</li> </ul> <p>The goal is to list all edges between all vertices with one label and all vertices of another label, providing the elementMaps() of the vertices.</p> <p>The following is the closest approximation I've achieved so far:</p> <pre><code>g.V().has('Customer', 'name', 'Customer').as('out').outE('HAS').as('edge').inV().hasLabel('Workstream').as('in').select('out', 'edge', 'in').toList() </code></pre> <p>This produces the following output (single item shown):</p> <pre><code>[{ out: Vertex { id: 'bac24101-555a-e70b-66b1-434c5b2bb4fe', label: 'Customer', properties: undefined }, edge: Edge { id: '74c24101-55a9-3421-029b-1ddd68178cfd', label: 'HAS', outV: [Vertex], inV: [Vertex], properties: {} }, in: Vertex { id: 'b8c24101-5548-f39e-70c9-a9bd126e05b2', label: 'Workstream', properties: undefined } }] </code></pre> <p>This does not give me the elementMap of the edge or the vertices, but it is a format I can consume. The desired output is:</p> <pre><code>[{ edge: { elementMapOfEdge, outV: { elementMapOfOutVertex }, inV: { elementMapOfInVertex }, } }] </code></pre> <p>Note that</p> <pre><code>g.V().has('Customer', 'name', 'Customer').dedup().by('name').outE('HAS').as('edge').inV().hasLabel('Workstream').select('edge').elementMap().toList() </code></pre> <p>Gives me the elementMap of the edge but not the incoming or outgoing vertices. The dedup() step addresses duplicate names in the vertices which is a data hygiene issue at this time.</p> <p>Curiously the elementMapping of the edge changes the vertex labels from 'outV' and 'inV' to 'OUT' and 'IN' -- I assume because the values are no longer Vertex objects but plain JS objects.</p> <p><strong>With respect to step labels, etc., I am more concerned with function than style. The goal is to achieve the desired result, rather than to be perfectly idiomatic with Gremlin at this point -- though it would be great to accomplish both!</strong></p>
[ { "answer_id": 74562642, "author": "Taylor Riggan", "author_id": 10130372, "author_profile": "https://Stackoverflow.com/users/10130372", "pm_score": 2, "selected": true, "text": "g.V().has('Customer', 'name', 'Customer').dedup().by('name').\n outE('HAS').as('edge').inV().hasLabel('Workstream').select('edge').\n project('edge').\n by(\n union(\n elementMap(),\n project('outV','inV').\n by(outV().elementMap()).\n by(inV().elementMap())\n ).fold()).toList()\n" }, { "answer_id": 74566938, "author": "Andy Robinson", "author_id": 20400898, "author_profile": "https://Stackoverflow.com/users/20400898", "pm_score": 0, "selected": false, "text": "g.V().hasLabel('User').as('in').outE().as('edge').inV().as('out').select('in', 'edge', 'out').by(wsx.__.elementMap()).by(wsx.__.elementMap()).by(wsx.__.elementMap()).toList()\n [\n {\n in: {\n id: 'user@test.net',\n label: 'User',\n name: 'Test User'\n },\n edge: {\n id: '1cc25300-3a47-8aef-6b40-017ab8592910',\n label: 'ADMINISTRATOR',\n IN: [Object],\n OUT: [Object],\n description: 'Workstream Administrator'\n },\n out: {\n id: '9ec25300-23cb-b316-f893-9f7a37ca4330',\n label: 'Workstream',\n name: 'Test 4',\n description: 'test 4 WS'\n }\n }\n]\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74562028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20400898/" ]
74,562,031
<p>By using <a href="https://docs.flutter.dev/development/accessibility-and-localization/internationalization" rel="nofollow noreferrer">a multilingual approach</a> build is failing with a not fully clear error &quot;Invalid constant value&quot;. As for the last screen, AppBar is taking a proper title where as body content is failing. Any thoughts? Thanks in advance!</p> <p><a href="https://i.stack.imgur.com/Jypqu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Jypqu.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/surci.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/surci.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74562642, "author": "Taylor Riggan", "author_id": 10130372, "author_profile": "https://Stackoverflow.com/users/10130372", "pm_score": 2, "selected": true, "text": "g.V().has('Customer', 'name', 'Customer').dedup().by('name').\n outE('HAS').as('edge').inV().hasLabel('Workstream').select('edge').\n project('edge').\n by(\n union(\n elementMap(),\n project('outV','inV').\n by(outV().elementMap()).\n by(inV().elementMap())\n ).fold()).toList()\n" }, { "answer_id": 74566938, "author": "Andy Robinson", "author_id": 20400898, "author_profile": "https://Stackoverflow.com/users/20400898", "pm_score": 0, "selected": false, "text": "g.V().hasLabel('User').as('in').outE().as('edge').inV().as('out').select('in', 'edge', 'out').by(wsx.__.elementMap()).by(wsx.__.elementMap()).by(wsx.__.elementMap()).toList()\n [\n {\n in: {\n id: 'user@test.net',\n label: 'User',\n name: 'Test User'\n },\n edge: {\n id: '1cc25300-3a47-8aef-6b40-017ab8592910',\n label: 'ADMINISTRATOR',\n IN: [Object],\n OUT: [Object],\n description: 'Workstream Administrator'\n },\n out: {\n id: '9ec25300-23cb-b316-f893-9f7a37ca4330',\n label: 'Workstream',\n name: 'Test 4',\n description: 'test 4 WS'\n }\n }\n]\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74562031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6618051/" ]
74,562,040
<p>How can I create a custom <code>Arrangement</code> for <code>LazyRow</code> to add additional spacing at beginning and end, but have even spacing in between?</p> <p>Start|&lt; more space&gt; Item 1 Item 2 Last Item |End</p> <pre class="lang-kotlin prettyprint-override"><code>object CustomArrangement : Arrangement.Horizontal { override fun Density.arrange( totalSize: Int, sizes: IntArray, layoutDirection: LayoutDirection, outPositions: IntArray ) { } } </code></pre> <p><a href="https://developer.android.com/jetpack/compose/lists#custom-arrangements" rel="nofollow noreferrer">https://developer.android.com/jetpack/compose/lists#custom-arrangements</a></p>
[ { "answer_id": 74562958, "author": "Gabriele Mariotti", "author_id": 2016562, "author_profile": "https://Stackoverflow.com/users/2016562", "pm_score": 3, "selected": true, "text": "PaddingValues LazyRow LazyRow(\n horizontalArrangement = Arrangement.spacedBy(8.dp),\n contentPadding = PaddingValues(horizontal = 50.dp),\n modifier= Modifier.fillMaxSize(),\n) {\n\n items(itemsList) {\n Text(\"Item is $it\")\n }\n}\n LazyRow(\n horizontalArrangement = Arrangement.spacedBy(8.dp),\n modifier= Modifier.fillMaxSize()\n) {\n //Header\n item(){\n Spacer(modifier = Modifier.width(40.dp))\n }\n items(itemsList) {\n Text(\"Item is $it\")\n }\n //Footer\n item(){\n Spacer(modifier = Modifier.width(40.dp))\n }\n}\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74562040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3034693/" ]
74,562,048
<p>I am currently attempting to join 2 datasets using SPSS syntax but am struggling as I have duplicate values on the keys. I would like for the joined data to be duplicated for each instance of the key on the source dataset (or other way round as it doesn't matter which is the source).</p> <p>The datasets are like the following -</p> <p><em>Data1 (3rd column placeholder)</em></p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>batch</th> <th>run</th> <th>date</th> </tr> </thead> <tbody> <tr> <td>A</td> <td>1</td> <td>1</td> </tr> <tr> <td>A</td> <td>2</td> <td>1</td> </tr> <tr> <td>A</td> <td>3</td> <td>1</td> </tr> <tr> <td>B</td> <td>1</td> <td>1</td> </tr> <tr> <td>C</td> <td>1</td> <td>1</td> </tr> <tr> <td>C</td> <td>2</td> <td>1</td> </tr> <tr> <td>D</td> <td>1</td> <td>1</td> </tr> <tr> <td>E</td> <td>1</td> <td>1</td> </tr> </tbody> </table> </div> <p><em>Data2</em></p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>batch</th> <th>Value1</th> <th>Value2</th> </tr> </thead> <tbody> <tr> <td>A</td> <td>1</td> <td>21</td> </tr> <tr> <td>A</td> <td>2</td> <td>22</td> </tr> <tr> <td>A</td> <td>3</td> <td>23</td> </tr> <tr> <td>A</td> <td>4</td> <td>24</td> </tr> <tr> <td>B</td> <td>5</td> <td>25</td> </tr> <tr> <td>B</td> <td>6</td> <td>26</td> </tr> <tr> <td>B</td> <td>7</td> <td>27</td> </tr> <tr> <td>B</td> <td>8</td> <td>28</td> </tr> <tr> <td>C</td> <td>9</td> <td>29</td> </tr> <tr> <td>C</td> <td>10</td> <td>30</td> </tr> <tr> <td>C</td> <td>11</td> <td>31</td> </tr> <tr> <td>C</td> <td>12</td> <td>32</td> </tr> <tr> <td>D</td> <td>13</td> <td>33</td> </tr> <tr> <td>D</td> <td>14</td> <td>34</td> </tr> <tr> <td>D</td> <td>15</td> <td>35</td> </tr> <tr> <td>D</td> <td>16</td> <td>36</td> </tr> <tr> <td>E</td> <td>17</td> <td>37</td> </tr> <tr> <td>E</td> <td>18</td> <td>38</td> </tr> <tr> <td>E</td> <td>19</td> <td>39</td> </tr> <tr> <td>E</td> <td>20</td> <td>40</td> </tr> </tbody> </table> </div> <p><strong>Current attempt</strong></p> <p>What I have just now is a method where I CASETOVARS on Data1 before matching it onto Data2 and then VARSTOCASES to expand it out. This works perfectly with my test data but, unfortunately, it requires that I know exactly how many 'runs' there will be. That will not be known in production. It could be 1 or more.</p> <p>Is there a method to join these datasets while expanding the joined data into the multliple cases in the source?</p> <p>I am open to using macros but am not able to utilise Python solutions for this (which would probably be easier!).</p> <p>edit - Unfortunately, extensions are also not possible for me to use.</p> <pre><code>CASESTOVARS /ID = batch . DATASET ACTIVATE data2 . MATCH FILES /FILE = * /TABLE = data1 /BY batch . EXECUTE . VARSTOCASES /MAKE run FROM BATCH_RUN_ID.1 TO BATCH_RUN_ID.3 . EXECUTE . </code></pre>
[ { "answer_id": 74562958, "author": "Gabriele Mariotti", "author_id": 2016562, "author_profile": "https://Stackoverflow.com/users/2016562", "pm_score": 3, "selected": true, "text": "PaddingValues LazyRow LazyRow(\n horizontalArrangement = Arrangement.spacedBy(8.dp),\n contentPadding = PaddingValues(horizontal = 50.dp),\n modifier= Modifier.fillMaxSize(),\n) {\n\n items(itemsList) {\n Text(\"Item is $it\")\n }\n}\n LazyRow(\n horizontalArrangement = Arrangement.spacedBy(8.dp),\n modifier= Modifier.fillMaxSize()\n) {\n //Header\n item(){\n Spacer(modifier = Modifier.width(40.dp))\n }\n items(itemsList) {\n Text(\"Item is $it\")\n }\n //Footer\n item(){\n Spacer(modifier = Modifier.width(40.dp))\n }\n}\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74562048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5218153/" ]
74,562,057
<p>There is a function that must run 3 requests in a row, and it is not possible to know how many of them failed or succeeded. If the request fails, sending requests should stop and the user should click an ignore button. After pressing the button, the execution of missed requests must be continued.</p> <p>I hope you can help me, how can I handle this situation.</p> <p>Thanks in advance.</p> <pre><code>requests = { X: &quot;xyz.com&quot; Y: &quot;abc.com&quot; Z: &quot;qwe.com&quot; } </code></pre> <p>I tried to implement it with following:</p> <pre><code>from(Object.values(requests)) .pipe( concatMap((action$: Observable&lt;any&gt;) =&gt; { return action$.pipe( map(response =&gt; response), catchError(() =&gt; { this.hasError = true; return of(undefined); })); }), takeWhile(() =&gt; !this.hasError), scan((resp1, resp2) =&gt; resp1.concat(resp2), []), ) .subscribe( value =&gt; { console.log('value =', value); }, error =&gt; { console.log('error = ', error); }, () =&gt; { console.log('COMPLETE'); } ); </code></pre> <p>This is running until the first request fails, but it doesn't continue after that.</p> <p>I tried to find a waitUntil operator, but unfortunately there is not found.</p> <p>For example:</p> <ul> <li>How it is working now:</li> </ul> <pre><code>1. X request status -&gt; 200 2. Y request status -&gt; 404 - So in this case complete shutdown occurs ( by the takeWhile ) and no continuation occur after setting the &quot;hasError&quot; value to &quot;false&quot; FYI: The next request should be the Z, after clicking on the &quot;ignore&quot; button. </code></pre> <ul> <li>How it should work:</li> </ul> <pre><code>Example #1: 1. X request status -&gt; 200 2. Y request status -&gt; 404 - Wait until the user clicks on the &quot;ignore&quot; button 3. Click on the &quot;ignore&quot; button 4. Z request status -&gt; 200 5. All three values arrive in the &quot;subscribe&quot; section, so one value should be undefined and two should be the requested response values. Example #2: 1. X request status -&gt; 404 - Wait until the user clicks on the &quot;ignore&quot; button 2. Click on the &quot;ignore&quot; button 3. Y request status -&gt; 200 4. Z request status -&gt; 404 - Wait until the user clicks on the &quot;ignore&quot; button 5. Click on the &quot;ignore&quot; button 6. All three values arrive in the &quot;subscribe&quot; section, so two value should be undefined and one should be the requested response value. </code></pre> <p>I hope you can help me, how can I handle this situation.</p> <p>Thanks in advance.</p>
[ { "answer_id": 74562838, "author": "Eddy Lin", "author_id": 19768317, "author_profile": "https://Stackoverflow.com/users/19768317", "pm_score": 1, "selected": false, "text": "ignore$ catchError ignore$.pipe(take(1)) const ignore$ = new Subject<undefined>();\n\nfunction click() {\n ignore$.next(undefined);\n}\n\nfrom(Object.values(requests)).pipe(\n concatMap((action$: Observable<any>) => \n action$.pipe(\n map(response => response),\n catchError(() => ignore$.pipe(take(1))),\n )\n ),\n toArray(),\n).subscribe(...);\n" }, { "answer_id": 74563452, "author": "BizzyBob", "author_id": 1858357, "author_profile": "https://Stackoverflow.com/users/1858357", "pm_score": 3, "selected": true, "text": "of() catchError items$ = from(this.itemIds).pipe(\n concatMap(id => this.itemService.get(id).pipe(\n catchError(() => this.promptUser(id).pipe(map(() => undefined)))\n )),\n reduce((all, item) => all.concat(item), [])\n );\n reduce scan reduce scan" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74562057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13424687/" ]
74,562,089
<p>I have used Polymorphic relationships. So, right now I have the following TypeScript interface:</p> <pre><code>interface SubjectA {} interface SubjectB {} interface SubjectC {} enum SubjectType { SubjectA = 'Subject A', SubjectB = 'Subject B', SubjectC = 'Subject C', } interface ExampleSubject { type: SubjectType; subject: SubjectA | SubjectB | SubjectC } </code></pre> <p>In this example, you can see, <code>ExampleSubject.subject</code> has three possible subject types (<code>SubjectA</code>, <code>SubjectB</code> <code>SubjectC</code>). Now here I want it should resolve its type dynamically. For example, if <code>ExampleSubject.type</code> is <code>SubjectType.SubjectA</code> in that case <code>ExampleSubject.subject</code> should be <code>SubjectA</code>.</p> <p>Please guide me, How can I resolve this? Thanks</p>
[ { "answer_id": 74562838, "author": "Eddy Lin", "author_id": 19768317, "author_profile": "https://Stackoverflow.com/users/19768317", "pm_score": 1, "selected": false, "text": "ignore$ catchError ignore$.pipe(take(1)) const ignore$ = new Subject<undefined>();\n\nfunction click() {\n ignore$.next(undefined);\n}\n\nfrom(Object.values(requests)).pipe(\n concatMap((action$: Observable<any>) => \n action$.pipe(\n map(response => response),\n catchError(() => ignore$.pipe(take(1))),\n )\n ),\n toArray(),\n).subscribe(...);\n" }, { "answer_id": 74563452, "author": "BizzyBob", "author_id": 1858357, "author_profile": "https://Stackoverflow.com/users/1858357", "pm_score": 3, "selected": true, "text": "of() catchError items$ = from(this.itemIds).pipe(\n concatMap(id => this.itemService.get(id).pipe(\n catchError(() => this.promptUser(id).pipe(map(() => undefined)))\n )),\n reduce((all, item) => all.concat(item), [])\n );\n reduce scan reduce scan" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74562089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5642788/" ]
74,562,103
<p>So I have this problem I'm trying to solve for a couple of days now, and I just feel lost. The function basically needs to get the size(n) of a sequence. The user inputs the size, and then the function will ask him to put the numbers of the sequence one after the other. Once he puts all the numbers, the function needs to return the sum of the longest sequence. For example, n=8, and the user put [1,3,5,7,11,13,15,16]. The result will be 16 because [1,3,5,7] is the longest sequence. If n=8 and the user put [1,3,5,7,11,15,19,20], the result will be 52, because although there are 2 sequences with the length of 4, the sum of [7,11,15,19] is bigger then [1,3,5,7]. The sequence doesn't necessarily needs to be increasing, it can be decreasing too. The function can't be recursive, and arrays can't be used. I hope it's clear enough what the problem is, and if not, please let me know so I'll try to explain better.</p> <pre><code>#define _CRT_SECURE_NO_WARNINGS #include &lt;stdio.h&gt; int main() { int i, size, num, nextNum, diff, prevDiff, currSeqLength = 0, currSum, prevSum = 0; printf(&quot;Please enter the arithmetic list size: &quot;); scanf_s(&quot;%d&quot;, &amp;size); for (i = 1; i &lt;= size; i++) { printf(&quot;Please enter num: &quot;); scanf_s(&quot;%d&quot;, &amp;num); while (i == 1) { prevSum = num; nextNum = num; currSeqLength++; break; } while (i == 2) { currSum = prevSum + num; diff = num - nextNum; nextNum = num; currSeqLength++; break; } while (i &gt;= 3) { prevDiff = diff; diff = num - nextNum; nextNum = num; if (prevDiff == diff) { currSum += num; currSeqLength++; break; } else { prevDiff = diff; // diff now should be the latest num - previous one } } } } </code></pre> <p>This is basically what I've managed so far. I know some things here aren't working as intended, and I know the code is only half complete, but I've tried so many things and I can't seem to put my finger on what's the problem, and would really love some guidance, I'm really lost.</p> <p>A few problems I encountered. When I enter a loop in which the difference between the new number and the old one is different than the previous loops(for instance, [4,8,11]), I can't seem to manage to save the old number(in this case 8) to calculate the next difference(which is 3). Not to mention the first 2 while loops are probably not efficient and can be merged together.</p> <p>P.S I know that the code is not a function, but I wrote it this way so I can keep track on each step, and once the code works as intended I convert it into a function.</p>
[ { "answer_id": 74562838, "author": "Eddy Lin", "author_id": 19768317, "author_profile": "https://Stackoverflow.com/users/19768317", "pm_score": 1, "selected": false, "text": "ignore$ catchError ignore$.pipe(take(1)) const ignore$ = new Subject<undefined>();\n\nfunction click() {\n ignore$.next(undefined);\n}\n\nfrom(Object.values(requests)).pipe(\n concatMap((action$: Observable<any>) => \n action$.pipe(\n map(response => response),\n catchError(() => ignore$.pipe(take(1))),\n )\n ),\n toArray(),\n).subscribe(...);\n" }, { "answer_id": 74563452, "author": "BizzyBob", "author_id": 1858357, "author_profile": "https://Stackoverflow.com/users/1858357", "pm_score": 3, "selected": true, "text": "of() catchError items$ = from(this.itemIds).pipe(\n concatMap(id => this.itemService.get(id).pipe(\n catchError(() => this.promptUser(id).pipe(map(() => undefined)))\n )),\n reduce((all, item) => all.concat(item), [])\n );\n reduce scan reduce scan" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74562103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
74,562,129
<p>I am writing a C++ program in VSCode. However, when I press F5, all it does is build the project. I tried making another simple project in VSCode to see if it works, but no luck. Here is my mini-program</p> <p>launch.json</p> <pre><code>{ // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 &quot;version&quot;: &quot;0.2.0&quot;, &quot;configurations&quot;: [ { &quot;name&quot;: &quot;C/C++: clang++ build and debug active file&quot;, &quot;type&quot;: &quot;cppdbg&quot;, &quot;request&quot;: &quot;launch&quot;, &quot;program&quot;: &quot;${fileDirname}/${fileBasenameNoExtension}&quot;, &quot;args&quot;: [], &quot;stopAtEntry&quot;: true, &quot;cwd&quot;: &quot;${workspaceFolder}&quot;, &quot;environment&quot;: [], &quot;externalConsole&quot;: false, &quot;MIMode&quot;: &quot;lldb&quot;, &quot;preLaunchTask&quot;: &quot;C/C++: clang++ build active file&quot; } ] } </code></pre> <p>tasks.json</p> <pre><code>{ &quot;tasks&quot;: [ { &quot;type&quot;: &quot;cppbuild&quot;, &quot;label&quot;: &quot;C/C++: clang++ build active file&quot;, &quot;command&quot;: &quot;/usr/bin/clang++&quot;, &quot;args&quot;: [ &quot;-fcolor-diagnostics&quot;, &quot;-fansi-escape-codes&quot;, &quot;-g&quot;, &quot;${file}&quot;, &quot;-o&quot;, &quot;${fileDirname}/${fileBasenameNoExtension}&quot; ], &quot;options&quot;: { &quot;cwd&quot;: &quot;${fileDirname}&quot; }, &quot;problemMatcher&quot;: [ &quot;$gcc&quot; ], &quot;group&quot;: { &quot;kind&quot;: &quot;build&quot;, &quot;isDefault&quot;: true }, &quot;detail&quot;: &quot;Task generated by Debugger.&quot; } ], &quot;version&quot;: &quot;2.0.0&quot; } </code></pre> <p>main.cpp</p> <pre><code>#include &lt;iostream&gt; int main() { int sum = 0; for (int i = 0; i &lt; 100; i++) { sum += i; std::cout&lt;&lt;&quot;Sum: &quot; &lt;&lt; sum &lt;&lt; std::endl; } return 0; } </code></pre> <p>I have tried reinstalling VSCode with no luck. When I try to debug a python script, it works just fine, so the problem is only with C++. How do I debug this debugging error? CLARIFICATION: I am not getting an error from the debugger. Instead, the debugger for C++ isn't launching at all.</p>
[ { "answer_id": 74562838, "author": "Eddy Lin", "author_id": 19768317, "author_profile": "https://Stackoverflow.com/users/19768317", "pm_score": 1, "selected": false, "text": "ignore$ catchError ignore$.pipe(take(1)) const ignore$ = new Subject<undefined>();\n\nfunction click() {\n ignore$.next(undefined);\n}\n\nfrom(Object.values(requests)).pipe(\n concatMap((action$: Observable<any>) => \n action$.pipe(\n map(response => response),\n catchError(() => ignore$.pipe(take(1))),\n )\n ),\n toArray(),\n).subscribe(...);\n" }, { "answer_id": 74563452, "author": "BizzyBob", "author_id": 1858357, "author_profile": "https://Stackoverflow.com/users/1858357", "pm_score": 3, "selected": true, "text": "of() catchError items$ = from(this.itemIds).pipe(\n concatMap(id => this.itemService.get(id).pipe(\n catchError(() => this.promptUser(id).pipe(map(() => undefined)))\n )),\n reduce((all, item) => all.concat(item), [])\n );\n reduce scan reduce scan" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74562129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14017544/" ]
74,562,185
<p>I primarily use WinSCP to connect to a particular site every time I launch the program. I've read about configurations that will launch the app and connect to a site each time the computer starts (such as <a href="https://stackoverflow.com/questions/25478385/can-i-configure-a-winscp-instance-to-always-run-in-the-background-keeping-a-rem">this</a>), but <strong>how can I set WinSCP to connect to a site automatically <em>when launching the app itself?</em></strong></p>
[ { "answer_id": 74562838, "author": "Eddy Lin", "author_id": 19768317, "author_profile": "https://Stackoverflow.com/users/19768317", "pm_score": 1, "selected": false, "text": "ignore$ catchError ignore$.pipe(take(1)) const ignore$ = new Subject<undefined>();\n\nfunction click() {\n ignore$.next(undefined);\n}\n\nfrom(Object.values(requests)).pipe(\n concatMap((action$: Observable<any>) => \n action$.pipe(\n map(response => response),\n catchError(() => ignore$.pipe(take(1))),\n )\n ),\n toArray(),\n).subscribe(...);\n" }, { "answer_id": 74563452, "author": "BizzyBob", "author_id": 1858357, "author_profile": "https://Stackoverflow.com/users/1858357", "pm_score": 3, "selected": true, "text": "of() catchError items$ = from(this.itemIds).pipe(\n concatMap(id => this.itemService.get(id).pipe(\n catchError(() => this.promptUser(id).pipe(map(() => undefined)))\n )),\n reduce((all, item) => all.concat(item), [])\n );\n reduce scan reduce scan" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74562185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3384936/" ]
74,562,223
<p>I want to change the text color in a pie chart according to the theme. But when I try to access it by <code>ContextCompat.getColor(requireActivity(), android.R.attr.textColorPrimary)</code>, it gives an error like this:</p> <pre><code>android.content.res.Resources$NotFoundException: Resource ID #0x1010036 </code></pre> <p>How can I access it?</p>
[ { "answer_id": 74562838, "author": "Eddy Lin", "author_id": 19768317, "author_profile": "https://Stackoverflow.com/users/19768317", "pm_score": 1, "selected": false, "text": "ignore$ catchError ignore$.pipe(take(1)) const ignore$ = new Subject<undefined>();\n\nfunction click() {\n ignore$.next(undefined);\n}\n\nfrom(Object.values(requests)).pipe(\n concatMap((action$: Observable<any>) => \n action$.pipe(\n map(response => response),\n catchError(() => ignore$.pipe(take(1))),\n )\n ),\n toArray(),\n).subscribe(...);\n" }, { "answer_id": 74563452, "author": "BizzyBob", "author_id": 1858357, "author_profile": "https://Stackoverflow.com/users/1858357", "pm_score": 3, "selected": true, "text": "of() catchError items$ = from(this.itemIds).pipe(\n concatMap(id => this.itemService.get(id).pipe(\n catchError(() => this.promptUser(id).pipe(map(() => undefined)))\n )),\n reduce((all, item) => all.concat(item), [])\n );\n reduce scan reduce scan" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74562223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12431078/" ]
74,562,233
<p>I have a text file that looks like this:</p> <pre><code>line1 #commentA line2 line3 #commentB line4 line5 line6 #commentC line7 line8 line9 line10 line11 #commentD line12 </code></pre> <p>I want to reformat it to look like this:</p> <pre><code>line1 #commentA line2 line3 #commentB line4line5 line6 #commentC line7line8line9line10 line11 #commentD line12 </code></pre> <p>The number of lines between lines that have comments is variable, and can be large (up to 1024 lines). So I'm looking for a way to leave the line with the comment untouched, but append the text of all lines between lines with comments into one line. Can you give a suggestion?</p> <p>My start at this is as follows:</p> <pre><code>with open(&quot;myfile.txt&quot;, mode='r+') as f: lines = f.readlines() for n, content in enumerate(lines): lines[n] = content if '#' in lines[n]: print(lines[n]) # not sure how to combine the lines in between those with comments </code></pre>
[ { "answer_id": 74562347, "author": "Claude Shannon", "author_id": 20102259, "author_profile": "https://Stackoverflow.com/users/20102259", "pm_score": -1, "selected": false, "text": "for l in lines\n tmp = \"\"\n if '#' in l:\n print(tmp)\n tmp = \"\"\n print(l)\n else:\n tmp+=l\n ```\n" }, { "answer_id": 74562378, "author": "charon25", "author_id": 16114044, "author_profile": "https://Stackoverflow.com/users/16114044", "pm_score": 1, "selected": true, "text": "new_lines = []\nfor line in lines:\n if \"#\" in line:\n new_lines.append(f\"\\n{line}\\n\")\n else:\n new_lines.append(line)\n with open('file.txt', 'w') as fo:\n fo.write(\"\".join(new_lines))\n if new_lines[0].startswith(\"\\n\"):\n new_lines[0] = new_lines[0][1:]\n new_lines: list[str] = []\nfor index, line in enumerate(lines):\n if \"#\" in line:\n new_lines.append((\"\\n\" if index > 0 else \"\") + f\"{line}\\n\")\n else:\n new_lines.append(line)\n" }, { "answer_id": 74564183, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 1, "selected": false, "text": "itertools.groupby text = \"\"\"\\\nline1 #commentA\nline2\nline3 #commentB\nline4\nline5\nline6 #commentC\nline7\nline8\nline9\nline10\nline11 #commentD\nline12\"\"\"\n\nfrom itertools import groupby\n\nfor _, g in groupby(text.splitlines(), lambda l: \"#\" in l):\n print(\"\".join(g))\n line1 #commentA\nline2\nline3 #commentB\nline4line5\nline6 #commentC\nline7line8line9line10\nline11 #commentD\nline12\n text with open('my_file.txt', 'r') as f_in:\n text = f_in.read()\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74562233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12348765/" ]
74,562,236
<p>Hay All,</p> <p>is it possible to run more than 1 select statement after using with? first select statement works fine, as soon as i add another select statement i got a error.</p> <pre><code>with a as (select a,b,c from Table1 with(readuncommitted)), b as (select d,e,f from Table2 with(readuncommitted)) select * from a select * from b </code></pre> <p>expected output: Table 1 a Table 2 b</p>
[ { "answer_id": 74562347, "author": "Claude Shannon", "author_id": 20102259, "author_profile": "https://Stackoverflow.com/users/20102259", "pm_score": -1, "selected": false, "text": "for l in lines\n tmp = \"\"\n if '#' in l:\n print(tmp)\n tmp = \"\"\n print(l)\n else:\n tmp+=l\n ```\n" }, { "answer_id": 74562378, "author": "charon25", "author_id": 16114044, "author_profile": "https://Stackoverflow.com/users/16114044", "pm_score": 1, "selected": true, "text": "new_lines = []\nfor line in lines:\n if \"#\" in line:\n new_lines.append(f\"\\n{line}\\n\")\n else:\n new_lines.append(line)\n with open('file.txt', 'w') as fo:\n fo.write(\"\".join(new_lines))\n if new_lines[0].startswith(\"\\n\"):\n new_lines[0] = new_lines[0][1:]\n new_lines: list[str] = []\nfor index, line in enumerate(lines):\n if \"#\" in line:\n new_lines.append((\"\\n\" if index > 0 else \"\") + f\"{line}\\n\")\n else:\n new_lines.append(line)\n" }, { "answer_id": 74564183, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 1, "selected": false, "text": "itertools.groupby text = \"\"\"\\\nline1 #commentA\nline2\nline3 #commentB\nline4\nline5\nline6 #commentC\nline7\nline8\nline9\nline10\nline11 #commentD\nline12\"\"\"\n\nfrom itertools import groupby\n\nfor _, g in groupby(text.splitlines(), lambda l: \"#\" in l):\n print(\"\".join(g))\n line1 #commentA\nline2\nline3 #commentB\nline4line5\nline6 #commentC\nline7line8line9line10\nline11 #commentD\nline12\n text with open('my_file.txt', 'r') as f_in:\n text = f_in.read()\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74562236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20591680/" ]
74,562,270
<p>I have two attributes I want to see from a list of dictionaries: <code>name</code> and <code>version</code>.</p> <p>Expected output:</p> <pre class="lang-yaml prettyprint-override"><code>name : kernel vesion: 3.10.0 </code></pre> <p>Input from a <code>yum</code> task:</p> <pre class="lang-json prettyprint-override"><code>{ &quot;yumoutput&quot;: { &quot;changed&quot;: false, &quot;failed&quot;: false, &quot;results&quot;: [{ &quot;arch&quot;: &quot;x86_64&quot;, &quot;envra&quot;: &quot;0:kernel-3.10.0-1160.80.1.el7.x86_64&quot;, &quot;epoch&quot;: &quot;0&quot;, &quot;name&quot;: &quot;kernel&quot;, &quot;release&quot;: &quot;1160.80.1.el7&quot;, &quot;repo&quot;: &quot;rhui-rhel-7-server-rhui-rpms&quot;, &quot;version&quot;: &quot;3.10.0&quot;, &quot;yumstate&quot;: &quot;available&quot; }, { &quot;arch&quot;: &quot;x86_64&quot;, &quot;envra&quot;: &quot;0:python-perf-3.10.0-1160.80.1.el7.x86_64&quot;, &quot;epoch&quot;: &quot;0&quot;, &quot;name&quot;: &quot;python-perf&quot;, &quot;release&quot;: &quot;1160.80.1.el7&quot;, &quot;repo&quot;: &quot;rhui-rhel-7-server-rhui-rpms&quot;, &quot;version&quot;: &quot;3.10.0&quot;, &quot;yumstate&quot;: &quot;available&quot; }, { &quot;arch&quot;: &quot;noarch&quot;, &quot;envra&quot;: &quot;0:tzdata-2022f-1.el7.noarch&quot;, &quot;epoch&quot;: &quot;0&quot;, &quot;name&quot;: &quot;tzdata&quot;, &quot;release&quot;: &quot;1.el7&quot;, &quot;repo&quot;: &quot;rhui-rhel-7-server-rhui-rpms&quot;, &quot;version&quot;: &quot;2022f&quot;, &quot;yumstate&quot;: &quot;available&quot; } ] } } </code></pre> <p>My tasks:</p> <pre class="lang-yaml prettyprint-override"><code>- name: List Available Patches (Non-Kernel) yum: list: updates update_cache: true exclude: kernel* security: true register: yumoutput - name: Show result debug: var: yumoutput </code></pre> <p>How can I filter the output to keep only entries with <code>name: kernel</code> and <code>version: 3.10.0</code>?</p>
[ { "answer_id": 74562347, "author": "Claude Shannon", "author_id": 20102259, "author_profile": "https://Stackoverflow.com/users/20102259", "pm_score": -1, "selected": false, "text": "for l in lines\n tmp = \"\"\n if '#' in l:\n print(tmp)\n tmp = \"\"\n print(l)\n else:\n tmp+=l\n ```\n" }, { "answer_id": 74562378, "author": "charon25", "author_id": 16114044, "author_profile": "https://Stackoverflow.com/users/16114044", "pm_score": 1, "selected": true, "text": "new_lines = []\nfor line in lines:\n if \"#\" in line:\n new_lines.append(f\"\\n{line}\\n\")\n else:\n new_lines.append(line)\n with open('file.txt', 'w') as fo:\n fo.write(\"\".join(new_lines))\n if new_lines[0].startswith(\"\\n\"):\n new_lines[0] = new_lines[0][1:]\n new_lines: list[str] = []\nfor index, line in enumerate(lines):\n if \"#\" in line:\n new_lines.append((\"\\n\" if index > 0 else \"\") + f\"{line}\\n\")\n else:\n new_lines.append(line)\n" }, { "answer_id": 74564183, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 1, "selected": false, "text": "itertools.groupby text = \"\"\"\\\nline1 #commentA\nline2\nline3 #commentB\nline4\nline5\nline6 #commentC\nline7\nline8\nline9\nline10\nline11 #commentD\nline12\"\"\"\n\nfrom itertools import groupby\n\nfor _, g in groupby(text.splitlines(), lambda l: \"#\" in l):\n print(\"\".join(g))\n line1 #commentA\nline2\nline3 #commentB\nline4line5\nline6 #commentC\nline7line8line9line10\nline11 #commentD\nline12\n text with open('my_file.txt', 'r') as f_in:\n text = f_in.read()\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74562270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10359100/" ]
74,562,353
<p><a href="https://i.stack.imgur.com/JqZ7O.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JqZ7O.png" alt="enter image description here" /></a></p> <pre><code>&lt;select class=&quot;form-control&quot; id=&quot;ddSelectaTopic&quot; onchange=&quot;if(this.value==='') {this.style.color='#999'} else {this.style.color='#333'}&quot; [(ngModel)]=&quot;user_type_id&quot; (change)=&quot;TypeChange($event.target.value,access_id)&quot; [disabled]=&quot;access_id == 1 || !access_id&quot;&gt; &lt;option disabled [value]=&quot;null&quot; selected&gt;Choose User Types&lt;/option&gt; &lt;option *ngFor=&quot;let type of UserTypes; let i = index&quot; [attr.value]=&quot;type.id&quot; [attr.selected]=&quot;i == 0 ? true : null&quot;&gt; &lt;span *ngIf=&quot;access_id&quot;&gt;{{type.name}}&lt;/span&gt; &lt;/option&gt; &lt;option value=&quot;newType&quot;&gt;New User Type&lt;/option&gt; &lt;/select&gt; </code></pre> <p>I try changing the disabled value null selected but it's not displaying the &quot;Choose User Types&quot;</p>
[ { "answer_id": 74562347, "author": "Claude Shannon", "author_id": 20102259, "author_profile": "https://Stackoverflow.com/users/20102259", "pm_score": -1, "selected": false, "text": "for l in lines\n tmp = \"\"\n if '#' in l:\n print(tmp)\n tmp = \"\"\n print(l)\n else:\n tmp+=l\n ```\n" }, { "answer_id": 74562378, "author": "charon25", "author_id": 16114044, "author_profile": "https://Stackoverflow.com/users/16114044", "pm_score": 1, "selected": true, "text": "new_lines = []\nfor line in lines:\n if \"#\" in line:\n new_lines.append(f\"\\n{line}\\n\")\n else:\n new_lines.append(line)\n with open('file.txt', 'w') as fo:\n fo.write(\"\".join(new_lines))\n if new_lines[0].startswith(\"\\n\"):\n new_lines[0] = new_lines[0][1:]\n new_lines: list[str] = []\nfor index, line in enumerate(lines):\n if \"#\" in line:\n new_lines.append((\"\\n\" if index > 0 else \"\") + f\"{line}\\n\")\n else:\n new_lines.append(line)\n" }, { "answer_id": 74564183, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 1, "selected": false, "text": "itertools.groupby text = \"\"\"\\\nline1 #commentA\nline2\nline3 #commentB\nline4\nline5\nline6 #commentC\nline7\nline8\nline9\nline10\nline11 #commentD\nline12\"\"\"\n\nfrom itertools import groupby\n\nfor _, g in groupby(text.splitlines(), lambda l: \"#\" in l):\n print(\"\".join(g))\n line1 #commentA\nline2\nline3 #commentB\nline4line5\nline6 #commentC\nline7line8line9line10\nline11 #commentD\nline12\n text with open('my_file.txt', 'r') as f_in:\n text = f_in.read()\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74562353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20591770/" ]
74,562,382
<p>I'm looking to keep the individual elements of a list repeating for x number of times, but can only see how to repeat the full list x number of times.</p> <p>For example, I want to repeat the list <code>[3, 5, 1, 9, 8]</code> such that if <code>x=12</code>, then I want to produce tthe following list (i.e the list continues to repeat in order until there are 12 individual elements in the list:</p> <pre><code>[3, 5, 1, 9, 8, 3, 5, 1, 9, 8, 3, 5] </code></pre> <p>I can do the below but this is obviously not what I want and I'm unsure how to proceed from here.</p> <pre><code>my_list = [3, 5, 1, 9, 8] x = 12 print(my_list * 12) </code></pre> <pre><code>[3, 5, 1, 9, 8, 3, 5, 1, 9, 8, 3, 5, 1, 9, 8, 3, 5, 1, 9, 8, 3, 5, 1, 9, 8, 3, 5, 1, 9, 8, 3, 5, 1, 9, 8, 3, 5, 1, 9, 8, 3, 5, 1, 9, 8, 3, 5, 1, 9, 8, 3, 5, 1, 9, 8, 3, 5, 1, 9, 8] </code></pre>
[ { "answer_id": 74562466, "author": "charon25", "author_id": 16114044, "author_profile": "https://Stackoverflow.com/users/16114044", "pm_score": 0, "selected": false, "text": "x lst list list lst = (lst * (1 + x // len(lst)))[:x]\n >>> lst = [3, 5, 1, 9, 8]\n>>> x = 12\n>>> (lst * (1 + x // len(lst)))[:x]\n[3, 5, 1, 9, 8, 3, 5, 1, 9, 8, 3, 5]\n index = 0\nwhile len(lst) < x:\n lst.append(lst[index])\n index += 1\n" }, { "answer_id": 74562512, "author": "Bhargav", "author_id": 15358800, "author_profile": "https://Stackoverflow.com/users/15358800", "pm_score": 2, "selected": false, "text": "from itertools import cycle, islice\n\nlis = [3, 5, 1, 9, 8]\nout = list(islice(cycle(lis), 12))\nprint(out)\n [3, 5, 1, 9, 8, 3, 5, 1, 9, 8, 3, 5]\n Ith lis = [3, 5, 1, 9, 8]\nlength = 12\n\nout = [lis[i%len(lis)] for i in range(length)]\nprint(out)\n [3, 5, 1, 9, 8, 3, 5, 1, 9, 8, 3, 5]\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74562382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13390884/" ]
74,562,395
<p>I have the following dictionary:</p> <pre><code>my_dict = {'fields': ['id': 1.0, 'name': 'aaa', 'type': 'string'}, {'id': 3.0, 'name': 'eee', 'type': 'string'}, {'id': nan, 'name': 'bbb', 'type': 'string'}, {'id': 4.0, 'name': 'ccc', 'type': 'string'}, {'id': nan, 'name': 'ddd', 'type': 'string'}], 'type': 'struct' } </code></pre> <p>From this dictionary, I would like to drop the dictionary with the <code>id</code> value <code>nan</code> value and would like to get the following.</p> <pre><code>my_updated_dict = {'fields': ['id': 1.0, 'name': 'aaa', 'type': 'string'}, {'id': 3.0, 'name': 'eee', 'type': 'string'}, {'id': 4.0, 'name': 'ccc', 'type': 'string'}], 'type': 'struct' } </code></pre> <p>I was trying changing to data frame and dropping the <code>id</code> value with the <code>nan</code> value and changing to dictionary back but couldn't get the intended result.</p> <pre><code> my_updated_dict = pd.DataFrame(my_dict ).dropna().to_dict('list') </code></pre>
[ { "answer_id": 74562584, "author": "Celius Stingher", "author_id": 11897007, "author_profile": "https://Stackoverflow.com/users/11897007", "pm_score": 1, "selected": false, "text": "update() my_dict.update({'fields':[x for x in my_dict['fields'] if np.nan not in x.values()]})\n {'fields': [{'id': 1.0, 'name': 'aaa', 'type': 'string'},\n {'id': 3.0, 'name': 'eee', 'type': 'string'},\n {'id': 4.0, 'name': 'ccc', 'type': 'string'}],\n 'type': 'struct'}\n" }, { "answer_id": 74562613, "author": "strawdog", "author_id": 8030503, "author_profile": "https://Stackoverflow.com/users/8030503", "pm_score": 3, "selected": true, "text": "my_dict[\"fields\"] = [i for i in my_dict[\"fields\"] if not np.isnan(i[\"id\"])]\n my_dict[\"fields\"] = pd.Series(my_dict[\"fields\"]).apply(pd.Series).dropna().to_dict(orient=\"records\")\n" }, { "answer_id": 74573091, "author": "Gonçalo Peres", "author_id": 7109869, "author_profile": "https://Stackoverflow.com/users/7109869", "pm_score": 0, "selected": false, "text": "json import numpy as np\n\njson = {'fields': [{'id': 1.0, 'name': 'aaa', 'type': 'string'},\n {'id': 3.0, 'name': 'eee', 'type': 'string'},\n {'id': np.nan, 'name': 'bbb', 'type': 'string'},\n {'id': 4.0, 'name': 'ccc', 'type': 'string'},\n {'id': np.nan, 'name': 'ddd', 'type': 'string'}],\n 'type': 'struct'}\n id np.nan numpy.isnan json['fields'] = [x for x in json['fields'] if not np.isnan(x['id'])]\n\n[Out]:\n\n{'fields': [{'id': 1.0, 'name': 'aaa', 'type': 'string'},\n {'id': 3.0, 'name': 'eee', 'type': 'string'},\n {'id': 4.0, 'name': 'ccc', 'type': 'string'}],\n 'type': 'struct'}\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74562395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14882883/" ]
74,562,403
<p><img src="https://i.stack.imgur.com/6qteRm.png" alt="Puzzle" /></p> <p><a href="https://drive.google.com/file/d/1qHYH2TQX8uu7psxm4bA6qsfcpWr_K5sG/view?usp=share_link" rel="nofollow noreferrer">Video Puzzle</a></p> <p>Current code:</p> <pre><code>for i in range(6,0,-2): Spaceship.step(2) Dev.step(i) for idk in range(3): Dev.turnRight() Dev.step(i*2) Dev.turnRight() Dev.step(i) </code></pre> <p>In this puzzle the objective is to get all the item (blue thing). With 6 line of code, and I'm currently at 8 line of code. I don't know how to minimalize the line of code.</p> <p>Note: Dev.step() is the robot, it can go backward by set the value by negative. Spaceship.step() is the spaceship, it can not go backward.</p>
[ { "answer_id": 74562584, "author": "Celius Stingher", "author_id": 11897007, "author_profile": "https://Stackoverflow.com/users/11897007", "pm_score": 1, "selected": false, "text": "update() my_dict.update({'fields':[x for x in my_dict['fields'] if np.nan not in x.values()]})\n {'fields': [{'id': 1.0, 'name': 'aaa', 'type': 'string'},\n {'id': 3.0, 'name': 'eee', 'type': 'string'},\n {'id': 4.0, 'name': 'ccc', 'type': 'string'}],\n 'type': 'struct'}\n" }, { "answer_id": 74562613, "author": "strawdog", "author_id": 8030503, "author_profile": "https://Stackoverflow.com/users/8030503", "pm_score": 3, "selected": true, "text": "my_dict[\"fields\"] = [i for i in my_dict[\"fields\"] if not np.isnan(i[\"id\"])]\n my_dict[\"fields\"] = pd.Series(my_dict[\"fields\"]).apply(pd.Series).dropna().to_dict(orient=\"records\")\n" }, { "answer_id": 74573091, "author": "Gonçalo Peres", "author_id": 7109869, "author_profile": "https://Stackoverflow.com/users/7109869", "pm_score": 0, "selected": false, "text": "json import numpy as np\n\njson = {'fields': [{'id': 1.0, 'name': 'aaa', 'type': 'string'},\n {'id': 3.0, 'name': 'eee', 'type': 'string'},\n {'id': np.nan, 'name': 'bbb', 'type': 'string'},\n {'id': 4.0, 'name': 'ccc', 'type': 'string'},\n {'id': np.nan, 'name': 'ddd', 'type': 'string'}],\n 'type': 'struct'}\n id np.nan numpy.isnan json['fields'] = [x for x in json['fields'] if not np.isnan(x['id'])]\n\n[Out]:\n\n{'fields': [{'id': 1.0, 'name': 'aaa', 'type': 'string'},\n {'id': 3.0, 'name': 'eee', 'type': 'string'},\n {'id': 4.0, 'name': 'ccc', 'type': 'string'}],\n 'type': 'struct'}\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74562403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20591508/" ]
74,562,415
<p>I'm passing int[] array that hold image, later I want to convert it to bytes[] and save the image to local path. However, I notice that the bytePic[] length is equal to int[] arrPic just the values are missing. There is a screenshot below: <img src="https://i.stack.imgur.com/SwZbx.png" alt="arrPic" /> <img src="https://i.stack.imgur.com/7otgQ.png" alt="bytePic" /></p> <p>Below is the entire function:</p> <pre class="lang-cs prettyprint-override"><code>public string ChangeMaterialPicture(int[] arrPic, int materialId,string defaultPath) { var material = _warehouseRepository.GetMaterialById(materialId); if(material is not null) { // Convert the Array to Bytes byte[] bytePic = new byte[arrPic.Length]; for(var i = 0; i &lt; arrPic.Length; i++) { AddByteToArray(bytePic, Convert.ToByte(arrPic[i])); } // Convert the Bytes to IMG string filename = Guid.NewGuid().ToString() + &quot;_.png&quot;; System.IO.File.WriteAllBytes(@$&quot;{defaultPath}\materials\{material.VendorId}\{filename}&quot;, bytePic); // Update the Image material.Picture = filename; _warehouseRepository.UpdateMaterial(material); return material.Picture; } else { return String.Empty; } } public byte[] AddByteToArray(byte[] bArray, byte newByte) { byte[] newArray = new byte[bArray.Length + 1]; bArray.CopyTo(newArray, 1); newArray[0] = newByte; return newArray; } </code></pre>
[ { "answer_id": 74562592, "author": "Olivier Jacot-Descombes", "author_id": 880990, "author_profile": "https://Stackoverflow.com/users/880990", "pm_score": 2, "selected": true, "text": "newArray AddByteToArray bytePic AddByteToArray int byte byte[] bytePic = new byte[arrPic.Length];\nfor (int i = 0; i < arrPic.Length; i++)\n{\n bytePic[i] = (byte)arrPic[i];\n}\n AddByteToArray int byte[] bytePic = arrPic.Select(i => (byte)i).ToArray();\n" }, { "answer_id": 74562680, "author": "JonasH", "author_id": 12342238, "author_profile": "https://Stackoverflow.com/users/12342238", "pm_score": 0, "selected": false, "text": "byte[] bytePic = new byte[arrPic.Length * 4];\nBuffer.BlockCopy(arrPic, 0, bytePic, 0, bytePic.Length);\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74562415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20338580/" ]
74,562,473
<p>For a school project I need to develop a platform style game purely in C# Windows forms and cannot use any other languages. I have a gravity and movement system sorted already but my character is still able to jump off the map or jump through picture boxes. How would I go about making these objects solid so that the character cannot run through them. Here is my code</p> <p>What my game looks like:</p> <p><a href="https://i.stack.imgur.com/ZxLDt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZxLDt.png" alt="Game interface" /></a></p> <pre><code>public partial class Form1 : Form { public Form1() { InitializeComponent(); } bool left; bool right; int gravity = 20; int force; bool jump; private void Timer(object sender, EventArgs e) { if (left == true) { Character.Left -= 15; if (Character.Image != Properties.Resources.LeftChar) { Character.Image = Properties.Resources.LeftChar; } } if (right == true) { Character.Left += 15; if (Character.Image != Properties.Resources.RightChar) { Character.Image = Properties.Resources.RightChar; } } if (jump == true) { Character.Top -= force; force -= 1; } if (Character.Top + Character.Height &gt;= GameBoundary.Height) { Character.Top = GameBoundary.Height - Character.Height; jump = false; } else { Character.Top += 10; } } private void keydown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.A) left = true; if (e.KeyCode == Keys.D) right = true; if (jump != true) { if (e.KeyCode == Keys.W) { jump = true; force = gravity; } } } private void keyup(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.A) left = false; if (e.KeyCode == Keys.D) right = false; } } </code></pre> <p><a href="https://i.stack.imgur.com/Agdej.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Agdej.png" alt="Shows error" /></a></p> <p>I created an invisible panel that was the same size of the game called &quot;Gameboundary&quot;, this made it possible for the player to walk on the bottom of the window, but I am not sure how I would apply this to the rest of the code. If anybody has any suggestions it will be greatly welcome. Not too good at C# just yet!</p>
[ { "answer_id": 74565462, "author": "Jonathan Barraone", "author_id": 17957703, "author_profile": "https://Stackoverflow.com/users/17957703", "pm_score": 1, "selected": false, "text": "public class CollisionDetection\n {\n public static bool ObjectTouchingOthers(Control Object, int SpaceBetweenObjects)\n {\n for (int i = 0; i < Object.Parent.Controls.Count; i++)\n {\n if (Object.Parent.Controls[i].Name != Object.Name)\n {\n if (Object.Left + Object.Width + SpaceBetweenObjects > Object.Parent.Controls[i].Left && Object.Top + Object.Height + SpaceBetweenObjects > Object.Parent.Controls[i].Top && Object.Left < Object.Parent.Controls[i].Left + Object.Parent.Controls[i].Width + SpaceBetweenObjects && Object.Top < Object.Parent.Controls[i].Top + Object.Parent.Controls[i].Height + SpaceBetweenObjects)\n {\n return true;\n }\n }\n }\n return false;\n }\n\n public static bool ObjectTouchingOthers(Control Object, int SpaceBetweenObjects, Control[] ControlsToExclude )\n {\n for (int i = 0; i < Object.Parent.Controls.Count; i++)\n {\n if (ControlsToExclude.Contains(Object.Parent.Controls[i]) == false && Object.Parent.Controls[i].Name != Object.Name)\n {\n if (Object.Left + Object.Width + SpaceBetweenObjects > Object.Parent.Controls[i].Left && Object.Top + Object.Height + SpaceBetweenObjects > Object.Parent.Controls[i].Top && Object.Left < Object.Parent.Controls[i].Left + Object.Parent.Controls[i].Width + SpaceBetweenObjects && Object.Top < Object.Parent.Controls[i].Top + Object.Parent.Controls[i].Height + SpaceBetweenObjects)\n {\n return true;\n }\n }\n }\n return false;\n }\n }\n Object panel Form second overload private void btnMoveLeft_Click(object sender, EventArgs e)\n {\n btnPlayer.Left -= 1;\n if (CollisionDetection.ObjectTouchingOthers(btnPlayer, 1, new Control[] {button1, button2}) == true)\n { \n btnPlayer.Left += 1;\n }\n }\n private void btnMoveLeft_Click(object sender, EventArgs e)\n {\n btnPlayer.Left -= 1;\n if (CollisionDetection.ObjectTouchingOthers(btnPlayer, 1) == true)\n { \n btnPlayer.Left += 1;\n }\n }\n\n private void btnMoveRight_Click(object sender, EventArgs e)\n {\n btnPlayer.Left += 1;\n if (CollisionDetection.ObjectTouchingOthers(btnPlayer, 1) == true)\n {\n btnPlayer.Left -= 1;\n }\n }\n\n private void btnMoveUp_Click(object sender, EventArgs e)\n {\n btnPlayer.Top -= 1;\n if (CollisionDetection.ObjectTouchingOthers(btnPlayer, 1) == true)\n {\n btnPlayer.Top += 1;\n }\n }\n\n private void btnMoveDown_Click(object sender, EventArgs e)\n {\n btnPlayer.Top += 1;\n if (CollisionDetection.ObjectTouchingOthers(btnPlayer, 1) == true)\n {\n btnPlayer.Top -= 1;\n }\n }\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74562473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12753656/" ]
74,562,474
<p>In my ListTile, I want a CircleAvatar with a border, that's why I have a CircleAvatar inside an other. The problem is the border doesn't appear. And when I try my code outside a ListTile, it works ...</p> <p>Code:</p> <pre><code>class TestTile extends StatelessWidget { const TestTile({super.key}); @override Widget build(BuildContext context) { return Scaffold( body: Column(children: const [ /***** DOES NOT WORK *****/ Card( child: SizedBox( width: 200, height: 100, child: ListTile( leading: CircleAvatar( radius: 32, backgroundColor: Colors.blue, child: CircleAvatar( radius: 30, backgroundColor: Colors.red, )), title: Text(&quot;test&quot;), ))), /***** WORKS *****/ CircleAvatar( radius: 32, backgroundColor: Colors.blue, child: CircleAvatar( radius: 30, backgroundColor: Colors.red, )) ])); } } </code></pre>
[ { "answer_id": 74565462, "author": "Jonathan Barraone", "author_id": 17957703, "author_profile": "https://Stackoverflow.com/users/17957703", "pm_score": 1, "selected": false, "text": "public class CollisionDetection\n {\n public static bool ObjectTouchingOthers(Control Object, int SpaceBetweenObjects)\n {\n for (int i = 0; i < Object.Parent.Controls.Count; i++)\n {\n if (Object.Parent.Controls[i].Name != Object.Name)\n {\n if (Object.Left + Object.Width + SpaceBetweenObjects > Object.Parent.Controls[i].Left && Object.Top + Object.Height + SpaceBetweenObjects > Object.Parent.Controls[i].Top && Object.Left < Object.Parent.Controls[i].Left + Object.Parent.Controls[i].Width + SpaceBetweenObjects && Object.Top < Object.Parent.Controls[i].Top + Object.Parent.Controls[i].Height + SpaceBetweenObjects)\n {\n return true;\n }\n }\n }\n return false;\n }\n\n public static bool ObjectTouchingOthers(Control Object, int SpaceBetweenObjects, Control[] ControlsToExclude )\n {\n for (int i = 0; i < Object.Parent.Controls.Count; i++)\n {\n if (ControlsToExclude.Contains(Object.Parent.Controls[i]) == false && Object.Parent.Controls[i].Name != Object.Name)\n {\n if (Object.Left + Object.Width + SpaceBetweenObjects > Object.Parent.Controls[i].Left && Object.Top + Object.Height + SpaceBetweenObjects > Object.Parent.Controls[i].Top && Object.Left < Object.Parent.Controls[i].Left + Object.Parent.Controls[i].Width + SpaceBetweenObjects && Object.Top < Object.Parent.Controls[i].Top + Object.Parent.Controls[i].Height + SpaceBetweenObjects)\n {\n return true;\n }\n }\n }\n return false;\n }\n }\n Object panel Form second overload private void btnMoveLeft_Click(object sender, EventArgs e)\n {\n btnPlayer.Left -= 1;\n if (CollisionDetection.ObjectTouchingOthers(btnPlayer, 1, new Control[] {button1, button2}) == true)\n { \n btnPlayer.Left += 1;\n }\n }\n private void btnMoveLeft_Click(object sender, EventArgs e)\n {\n btnPlayer.Left -= 1;\n if (CollisionDetection.ObjectTouchingOthers(btnPlayer, 1) == true)\n { \n btnPlayer.Left += 1;\n }\n }\n\n private void btnMoveRight_Click(object sender, EventArgs e)\n {\n btnPlayer.Left += 1;\n if (CollisionDetection.ObjectTouchingOthers(btnPlayer, 1) == true)\n {\n btnPlayer.Left -= 1;\n }\n }\n\n private void btnMoveUp_Click(object sender, EventArgs e)\n {\n btnPlayer.Top -= 1;\n if (CollisionDetection.ObjectTouchingOthers(btnPlayer, 1) == true)\n {\n btnPlayer.Top += 1;\n }\n }\n\n private void btnMoveDown_Click(object sender, EventArgs e)\n {\n btnPlayer.Top += 1;\n if (CollisionDetection.ObjectTouchingOthers(btnPlayer, 1) == true)\n {\n btnPlayer.Top -= 1;\n }\n }\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74562474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7905820/" ]
74,562,496
<p>I found this code, thats lets you drag and drop an item in an specific area, but I failed to rewrite it, so that it allowes multiple elments to drag and drop, because i dont know how to get the id of the dragged object from the drop_handler function.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>let offsetX; let offsetY; onDragStart = function(ev) { const rect = ev.target.getBoundingClientRect(); offsetX = ev.clientX - rect.x; offsetY = ev.clientY - rect.y; }; drop_handler = function(ev) { ev.preventDefault(); const left = parseInt(id2.style.left); const top = parseInt(id2.style.top); id1.style.position = 'absolute'; id1.style.left = ev.clientX - left - offsetX + 'px'; id1.style.top = ev.clientY - top - offsetY + 'px'; id2.appendChild(document.getElementById("id1")); }; dragover_handler = function(ev) { ev.preventDefault(); ev.dataTransfer.dropEffect = "move"; };</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="id1" draggable="true" ondragstart="onDragStart(event)" style="border:2px solid green; cursor:pointer;width:100px;height:50px;"&gt;Dragged Div&lt;/div&gt; &lt;div id="id2" style="position:absolute;left:200px;top:50px;border:2px solid red; cursor:pointer;width:200px;height:200px;" ondrop="drop_handler(event)" ondragover="dragover_handler(event)"&gt;Drop Div &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74562726, "author": "user3425506", "author_id": 3425506, "author_profile": "https://Stackoverflow.com/users/3425506", "pm_score": 0, "selected": false, "text": "let offsetX;\nlet offsetY;\n\nconst keepTrackOfID = document.querySelector('#keep-track-of-id');\n\nonDragStart = function(ev) {\n const rect = ev.target.getBoundingClientRect();\n\n offsetX = ev.clientX - rect.x;\n offsetY = ev.clientY - rect.y;\n \n keepTrackOfID.setAttribute('data-dragged-id', ev.target.id);\n \n};\n\ndrop_handler = function(ev) {\n ev.preventDefault();\n\n const left = parseInt(id2.style.left);\n const top = parseInt(id2.style.top);\n\n id1.style.position = 'absolute';\n id1.style.left = ev.clientX - left - offsetX + 'px';\n id1.style.top = ev.clientY - top - offsetY + 'px';\n id2.appendChild(document.getElementById(keepTrackOfID.dataset.draggedId));\n \n console.log(ev.target.id);\n \n};\n\ndragover_handler = function(ev) {\n ev.preventDefault();\n ev.dataTransfer.dropEffect = \"move\";\n}; <div id=\"id1\" draggable=\"true\" ondragstart=\"onDragStart(event)\" style=\"border:2px solid green; cursor:pointer;width:100px;height:50px;\">Dragged Div 1</div>\n\n<div id=\"id1b\" draggable=\"true\" ondragstart=\"onDragStart(event)\" style=\"border:2px solid green; cursor:pointer;width:100px;height:50px;\">Dragged Div 1b</div>\n\n<div id='keep-track-of-id'></div>\n\n<div id=\"id2\" style=\"position:absolute;left:200px;top:50px;border:2px solid red; cursor:pointer;width:200px;height:200px;\" ondrop=\"drop_handler(event)\" ondragover=\"dragover_handler(event)\">Drop Div\n</div>" }, { "answer_id": 74563416, "author": "0stone0", "author_id": 5625547, "author_profile": "https://Stackoverflow.com/users/5625547", "pm_score": 1, "selected": false, "text": "onDragStart dragElement drop_handler const dropElement let offsetX;\nlet offsetY;\nlet dragElement = null;\nconst dropElement = document.getElementById(\"id-drop\");\n\nonDragStart = function(ev) {\n const rect = ev.target.getBoundingClientRect();\n\n offsetX = ev.clientX - rect.x;\n offsetY = ev.clientY - rect.y;\n \n dragElement = ev.target;\n};\n\ndrop_handler = function(ev) {\n ev.preventDefault();\n\n const left = parseInt(dropElement.style.left);\n const top = parseInt(dropElement.style.top);\n\n dragElement.style.position = 'absolute';\n dragElement.style.left = ev.clientX - left - offsetX + 'px';\n dragElement.style.top = ev.clientY - top - offsetY + 'px';\n dropElement.appendChild(dragElement);\n};\n\ndragover_handler = function(ev) {\n ev.preventDefault();\n ev.dataTransfer.dropEffect = \"move\";\n}; <div id=\"id1\" draggable=\"true\" ondragstart=\"onDragStart(event)\" style=\"border:2px solid green; cursor:pointer;width:100px;height:50px;\">Dragged Div #1</div>\n\n<div id=\"id2\" draggable=\"true\" ondragstart=\"onDragStart(event)\" style=\"border:2px solid green; cursor:pointer;width:100px;height:50px;\">Dragged Div #2</div>\n\n<div id=\"id-drop\" style=\"position:absolute;left:200px;top:50px;border:2px solid red; cursor:pointer;width:200px;height:200px;\" ondrop=\"drop_handler(event)\" ondragover=\"dragover_handler(event)\">Drop Div\n</div>" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74562496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20591630/" ]
74,562,517
<p>I have a JavaScript file (file.js) that contains the following code:</p> <p><code>console.log(&quot;Hello World!&quot;)</code></p> <p>When I run this code in my terminal <code>node file.js</code>, I get the following output:</p> <p><code>Hello World</code></p> <p>If I wanted to save this to a file programmatically (not right clicking and clicking save), does anyone know how I can do that?</p> <p>The only solution I can find on the internet was using <code>JSON.stringify(&quot;Hello World!&quot;)</code>, but this doesn't do anything I don't believe (doesn't even output an error).</p> <p>Reference: <a href="https://stackoverflow.com/questions/11849562/how-to-save-the-output-of-a-console-logobject-to-a-file">How to save the output of a console.log(object) to a file?</a></p>
[ { "answer_id": 74562726, "author": "user3425506", "author_id": 3425506, "author_profile": "https://Stackoverflow.com/users/3425506", "pm_score": 0, "selected": false, "text": "let offsetX;\nlet offsetY;\n\nconst keepTrackOfID = document.querySelector('#keep-track-of-id');\n\nonDragStart = function(ev) {\n const rect = ev.target.getBoundingClientRect();\n\n offsetX = ev.clientX - rect.x;\n offsetY = ev.clientY - rect.y;\n \n keepTrackOfID.setAttribute('data-dragged-id', ev.target.id);\n \n};\n\ndrop_handler = function(ev) {\n ev.preventDefault();\n\n const left = parseInt(id2.style.left);\n const top = parseInt(id2.style.top);\n\n id1.style.position = 'absolute';\n id1.style.left = ev.clientX - left - offsetX + 'px';\n id1.style.top = ev.clientY - top - offsetY + 'px';\n id2.appendChild(document.getElementById(keepTrackOfID.dataset.draggedId));\n \n console.log(ev.target.id);\n \n};\n\ndragover_handler = function(ev) {\n ev.preventDefault();\n ev.dataTransfer.dropEffect = \"move\";\n}; <div id=\"id1\" draggable=\"true\" ondragstart=\"onDragStart(event)\" style=\"border:2px solid green; cursor:pointer;width:100px;height:50px;\">Dragged Div 1</div>\n\n<div id=\"id1b\" draggable=\"true\" ondragstart=\"onDragStart(event)\" style=\"border:2px solid green; cursor:pointer;width:100px;height:50px;\">Dragged Div 1b</div>\n\n<div id='keep-track-of-id'></div>\n\n<div id=\"id2\" style=\"position:absolute;left:200px;top:50px;border:2px solid red; cursor:pointer;width:200px;height:200px;\" ondrop=\"drop_handler(event)\" ondragover=\"dragover_handler(event)\">Drop Div\n</div>" }, { "answer_id": 74563416, "author": "0stone0", "author_id": 5625547, "author_profile": "https://Stackoverflow.com/users/5625547", "pm_score": 1, "selected": false, "text": "onDragStart dragElement drop_handler const dropElement let offsetX;\nlet offsetY;\nlet dragElement = null;\nconst dropElement = document.getElementById(\"id-drop\");\n\nonDragStart = function(ev) {\n const rect = ev.target.getBoundingClientRect();\n\n offsetX = ev.clientX - rect.x;\n offsetY = ev.clientY - rect.y;\n \n dragElement = ev.target;\n};\n\ndrop_handler = function(ev) {\n ev.preventDefault();\n\n const left = parseInt(dropElement.style.left);\n const top = parseInt(dropElement.style.top);\n\n dragElement.style.position = 'absolute';\n dragElement.style.left = ev.clientX - left - offsetX + 'px';\n dragElement.style.top = ev.clientY - top - offsetY + 'px';\n dropElement.appendChild(dragElement);\n};\n\ndragover_handler = function(ev) {\n ev.preventDefault();\n ev.dataTransfer.dropEffect = \"move\";\n}; <div id=\"id1\" draggable=\"true\" ondragstart=\"onDragStart(event)\" style=\"border:2px solid green; cursor:pointer;width:100px;height:50px;\">Dragged Div #1</div>\n\n<div id=\"id2\" draggable=\"true\" ondragstart=\"onDragStart(event)\" style=\"border:2px solid green; cursor:pointer;width:100px;height:50px;\">Dragged Div #2</div>\n\n<div id=\"id-drop\" style=\"position:absolute;left:200px;top:50px;border:2px solid red; cursor:pointer;width:200px;height:200px;\" ondrop=\"drop_handler(event)\" ondragover=\"dragover_handler(event)\">Drop Div\n</div>" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74562517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6725147/" ]
74,562,524
<p>I am trying to do some html scraping with JavaScript, and would like to take the <code>a href</code> link and replace it into a hyperlink on a Discord embed. I am having trouble with regex, I am finding it very difficult to learn. I assume I will also need another regex to capture it all so I can replace it with my desired target?</p> <p>This is an example raw html that I have:</p> <pre><code>An **example**, also known as a &lt;a href=&quot;https://www.example.com/example%20type&quot;&gt;example type&lt;/a&gt; </code></pre> <p>to make this readable within a Discord embed, I am looking for a desired output of:</p> <pre><code>An **example**, also known as a [**example type**](https://www.example.com/example%20type) </code></pre> <p>I have tried extracting the URL via regex, which I can match however, I am having issues with extracting the link and the (I think its called target? The 'example type' in the example link text) and then replacing the string with my desired output. I have the following: (<a href="https://regexr.com/73574" rel="nofollow noreferrer">https://regexr.com/73574</a>)</p> <pre><code>/href=&quot;[^&quot;]+/g </code></pre> <p>This matches <code>href=&quot;https://www.example.com/example%20type</code>, and feels like a very early step, it includes 'href' in the match, and it does not capture the target.</p> <p>EDIT: I apologise, I did not think about additional checks, what if the string has multiple links? and text after them, for example:</p> <pre><code>An **example**, also known as a &lt;a href=&quot;https://www.example.com/example%20type&quot;&gt;example type&lt;/a&gt; is the first example, and now I have &lt;a href=&quot;https://www.example.com/second&quot;&gt;second&lt;/a&gt; example </code></pre> <p>with a desired output of:</p> <pre><code>An **example**, also known as a [**example type**](https://www.example.com/example%20type) is the first example, and now I have [**second**](https://www.example.com/second) example </code></pre>
[ { "answer_id": 74562726, "author": "user3425506", "author_id": 3425506, "author_profile": "https://Stackoverflow.com/users/3425506", "pm_score": 0, "selected": false, "text": "let offsetX;\nlet offsetY;\n\nconst keepTrackOfID = document.querySelector('#keep-track-of-id');\n\nonDragStart = function(ev) {\n const rect = ev.target.getBoundingClientRect();\n\n offsetX = ev.clientX - rect.x;\n offsetY = ev.clientY - rect.y;\n \n keepTrackOfID.setAttribute('data-dragged-id', ev.target.id);\n \n};\n\ndrop_handler = function(ev) {\n ev.preventDefault();\n\n const left = parseInt(id2.style.left);\n const top = parseInt(id2.style.top);\n\n id1.style.position = 'absolute';\n id1.style.left = ev.clientX - left - offsetX + 'px';\n id1.style.top = ev.clientY - top - offsetY + 'px';\n id2.appendChild(document.getElementById(keepTrackOfID.dataset.draggedId));\n \n console.log(ev.target.id);\n \n};\n\ndragover_handler = function(ev) {\n ev.preventDefault();\n ev.dataTransfer.dropEffect = \"move\";\n}; <div id=\"id1\" draggable=\"true\" ondragstart=\"onDragStart(event)\" style=\"border:2px solid green; cursor:pointer;width:100px;height:50px;\">Dragged Div 1</div>\n\n<div id=\"id1b\" draggable=\"true\" ondragstart=\"onDragStart(event)\" style=\"border:2px solid green; cursor:pointer;width:100px;height:50px;\">Dragged Div 1b</div>\n\n<div id='keep-track-of-id'></div>\n\n<div id=\"id2\" style=\"position:absolute;left:200px;top:50px;border:2px solid red; cursor:pointer;width:200px;height:200px;\" ondrop=\"drop_handler(event)\" ondragover=\"dragover_handler(event)\">Drop Div\n</div>" }, { "answer_id": 74563416, "author": "0stone0", "author_id": 5625547, "author_profile": "https://Stackoverflow.com/users/5625547", "pm_score": 1, "selected": false, "text": "onDragStart dragElement drop_handler const dropElement let offsetX;\nlet offsetY;\nlet dragElement = null;\nconst dropElement = document.getElementById(\"id-drop\");\n\nonDragStart = function(ev) {\n const rect = ev.target.getBoundingClientRect();\n\n offsetX = ev.clientX - rect.x;\n offsetY = ev.clientY - rect.y;\n \n dragElement = ev.target;\n};\n\ndrop_handler = function(ev) {\n ev.preventDefault();\n\n const left = parseInt(dropElement.style.left);\n const top = parseInt(dropElement.style.top);\n\n dragElement.style.position = 'absolute';\n dragElement.style.left = ev.clientX - left - offsetX + 'px';\n dragElement.style.top = ev.clientY - top - offsetY + 'px';\n dropElement.appendChild(dragElement);\n};\n\ndragover_handler = function(ev) {\n ev.preventDefault();\n ev.dataTransfer.dropEffect = \"move\";\n}; <div id=\"id1\" draggable=\"true\" ondragstart=\"onDragStart(event)\" style=\"border:2px solid green; cursor:pointer;width:100px;height:50px;\">Dragged Div #1</div>\n\n<div id=\"id2\" draggable=\"true\" ondragstart=\"onDragStart(event)\" style=\"border:2px solid green; cursor:pointer;width:100px;height:50px;\">Dragged Div #2</div>\n\n<div id=\"id-drop\" style=\"position:absolute;left:200px;top:50px;border:2px solid red; cursor:pointer;width:200px;height:200px;\" ondrop=\"drop_handler(event)\" ondragover=\"dragover_handler(event)\">Drop Div\n</div>" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74562524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15526397/" ]
74,562,550
<p>I am integrating a chat feature in my mobile application, and decided to use Firebase Realtime Database for the backend instad of Firestore as a cost reduction mechanism. I am running into a problem, however. There seems to be very sparse documentation on how to create infinite scrolling using data from <code>Realtime Database</code> instead of <code>Firestore</code>.</p> <p>Below is the organization of my chat messages. This is the query I want to use:</p> <pre><code>FirebaseDatabase.instance .ref(&quot;messages/${widget.placeID}&quot;) .orderByChild(&quot;timeStamp&quot;) </code></pre> <p>And this is the widget I want to return for each result:</p> <pre><code>MessageWidget( message: message.text, id: message.uid, name: message.name, lastSender: message.lastSender, date: message.timeStamp, profilePicture: message.profilePicture, ); </code></pre> <p>Here is the database structure<br> <a href="https://i.stack.imgur.com/OPC28.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OPC28.png" alt="enter image description here" /></a></p> <p>The query works, and I have already programmed the MessageWidget from the JSON response of the query. All I need is for the query to be called whenever it reaches the top of its scroll, and load more <code>MessageWdiget</code>s. Also note, this is a chat app where users are scrolling up, to load older messages, to be added above the previous.</p> <p>Thank you!</p> <p><strong>EDIT</strong>: here is the code I currently have:</p> <pre><code>Flexible( child: StreamBuilder( stream: FirebaseDatabase.instance .ref(&quot;messages/${widget.placeID}&quot;) .orderByChild(&quot;timeStamp&quot;) .limitToLast(20) .onValue, builder: (context, AsyncSnapshot&lt;DatabaseEvent&gt; snapshot) { if (!snapshot.hasData) { return const CircularProgressIndicator(); } else { Map&lt;dynamic, dynamic&gt; map = snapshot.data!.snapshot.value as dynamic; List&lt;dynamic&gt; list = []; list.clear(); list = map.values.toList(); return Align( alignment: Alignment.bottomCenter, child: Padding( padding: const EdgeInsets.only(bottom: 20), child: ListView.builder( controller: _scrollController, // shrinkWrap: true, itemCount: list.length, itemBuilder: (context, index) { final json = list[index] as Map&lt;dynamic, dynamic&gt;; final message = Message.fromJson(json); return MessageWidget( message: message.text, id: message.uid, name: message.name, lastSender: message.lastSender, date: message.timeStamp, profilePicture: message.profilePicture, ); }), ), ); } }, ), ), </code></pre> <p>My initState<br></p> <pre><code>void initState() { super.initState(); _scrollController.addListener(() { if (_scrollController.position.atEdge) { bool isTop = _scrollController.position.pixels == 0; if (isTop) { //add more messages } else { print('At the bottom'); } } }); } </code></pre>
[ { "answer_id": 74562746, "author": "Frank van Puffelen", "author_id": 209103, "author_profile": "https://Stackoverflow.com/users/209103", "pm_score": 3, "selected": false, "text": "limitToLast timeStamp FirebaseDatabase.instance\n .ref(\"messages/${widget.placeID}\")\n .orderByChild(\"timeStamp\")\n .limitToLast(10);\n timeStamp FirebaseDatabase.instance\n .ref(\"messages/${widget.placeID}\")\n .orderByChild(\"timeStamp\")\n .endBefore(timeStampValueOfOldestSeenItem, keyOfOldestSeenItem)\n .limitToLast(10);\n timeStamp" }, { "answer_id": 74568394, "author": "Mmoniem", "author_id": 16727709, "author_profile": "https://Stackoverflow.com/users/16727709", "pm_score": 2, "selected": true, "text": "ScrollController final ScrollController _scrollController = ScrollController();\n List List list = [];\n getStartData() async {\n //replace this with your path\n DatabaseReference starCountRef =\n FirebaseDatabase.instance.ref('messages/${widget.placeID}');\n starCountRef\n .orderByChild(\"timeStamp\")\n //here, I limit my initial query to 6 results, change this to how many \n //you want to load initially\n .limitToLast(6)\n .onChildAdded\n .forEach((element) {\n setState(() {\n list.add(element.snapshot.value);\n list.sort((a, b) => a[\"timeStamp\"].compareTo(b[\"timeStamp\"]));\n });\n });\n }\n initState void initState() {\n super.initState();\n FirebaseDatabase.instance.setPersistenceEnabled(true);\n getStartData();\n }\n ListView ListView.builder(\n itemCount: list.length,\n controller: _scrollController,\n //here I use a premade widget, replace MessageWidget with \n //what you want to load for each result\n itemBuilder: (_, index) => MessageWidget(\n message: list[index][\"text\"],\n date: list[index][\"timeStamp\"],\n id: list[index][\"uid\"],\n profilePicture: list[index][\"profilePicture\"],\n name: list[index][\"name\"],\n lastSender: list[index][\"lastSender\"],\n ),\n ),\n ListView ListView ListView Container getStartData() initState list ListView.builder MessageWidget getStartData getMoreData() async {\n var moreSnapshots = await FirebaseDatabase.instance\n .ref(\"messages/${widget.placeID}\")\n .orderByChild(\"timeStamp\")\n .endBefore(list[0][\"timeStamp\"])\n .limitToLast(20)\n .once();\n var moreMap = moreSnapshots.snapshot.value as dynamic;\n setState(() {\n list.addAll(moreMap.values.toList());\n list.sort((a, b) => a[\"timeStamp\"].compareTo(b[\"timeStamp\"]));\n });\n }\n\n ListView.builder initState _scrollController.addListener(() {\n if (_scrollController.position.atEdge) {\n bool isTop = _scrollController.position.pixels == 0;\n if (isTop) {\n getMoreData();\n }\n }\n });\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74562550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16727709/" ]
74,562,556
<p>I googled and most of the answers is about adding a value to a series but not update the index.</p> <p>Here is my series with date string as its index like this</p> <pre><code>2022-01-01 1 2022-01-02 7 2022-01-03 3 </code></pre> <p>Now I like to add new value of 10 into this series with new index of 2022-01-04 date string. so the series becomes</p> <pre><code>2022-01-01 1 2022-01-02 7 2022-01-03 3 2022-01-04 10 </code></pre> <p>How to do it?</p> <p>Thanks</p>
[ { "answer_id": 74562655, "author": "butterflyknife", "author_id": 8790507, "author_profile": "https://Stackoverflow.com/users/8790507", "pm_score": 1, "selected": false, "text": "new_row = pd.Series(new_value, index=[index_of_new_value])\nseries = pd.concat([series, new_row])\n" }, { "answer_id": 74562674, "author": "msailor", "author_id": 10155119, "author_profile": "https://Stackoverflow.com/users/10155119", "pm_score": 3, "selected": true, "text": ">>> aa = pd.Series({\"foo\": 1})\n>>> aa\nfoo 1\ndtype: int64\n>>> aa[\"bar\"] = 2\n>>> aa\nfoo 1\nbar 2\ndtype: int64\n" }, { "answer_id": 74562755, "author": "abokey", "author_id": 16120011, "author_profile": "https://Stackoverflow.com/users/16120011", "pm_score": 0, "selected": false, "text": "ser pandas.DatetimeIndex pandas.Series.reindex idx = pd.date_range('01-01-2022', '01-04-2022')\nser.index = pd.DatetimeIndex(ser.index)\nser = ser.reindex(idx, fill_value=10)\n print(ser)\n\n2022-01-01 1\n2022-01-02 7\n2022-01-03 3\n2022-01-04 10\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74562556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9983652/" ]
74,562,576
<p>I have a button on vue calling a function to redirect back to Laravel route.</p> <p>I would like to ask the user if he really want to perform the operation. If he reply &quot;Cancel&quot; I need to avoid redirecting and do nothing</p> <p>First I tried this way, but it does not ask for confirmation:</p> <pre><code>Inertia.put(route('disable-utente', row.id), { onBefore: () =&gt; { confirm('Do you really want to continue ?') }} ) </code></pre> <p>Then I tried this way; it shows the dialog but put to the route even if I clicked cancel on the confirmation dialog</p> <pre><code>Inertia.visit(route('disable-utente', row.id), { method: 'put', onBefore: () =&gt; { confirm('Do you really want to continue?') } } ) </code></pre>
[ { "answer_id": 74562655, "author": "butterflyknife", "author_id": 8790507, "author_profile": "https://Stackoverflow.com/users/8790507", "pm_score": 1, "selected": false, "text": "new_row = pd.Series(new_value, index=[index_of_new_value])\nseries = pd.concat([series, new_row])\n" }, { "answer_id": 74562674, "author": "msailor", "author_id": 10155119, "author_profile": "https://Stackoverflow.com/users/10155119", "pm_score": 3, "selected": true, "text": ">>> aa = pd.Series({\"foo\": 1})\n>>> aa\nfoo 1\ndtype: int64\n>>> aa[\"bar\"] = 2\n>>> aa\nfoo 1\nbar 2\ndtype: int64\n" }, { "answer_id": 74562755, "author": "abokey", "author_id": 16120011, "author_profile": "https://Stackoverflow.com/users/16120011", "pm_score": 0, "selected": false, "text": "ser pandas.DatetimeIndex pandas.Series.reindex idx = pd.date_range('01-01-2022', '01-04-2022')\nser.index = pd.DatetimeIndex(ser.index)\nser = ser.reindex(idx, fill_value=10)\n print(ser)\n\n2022-01-01 1\n2022-01-02 7\n2022-01-03 3\n2022-01-04 10\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74562576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1961429/" ]
74,562,589
<p>How can one compute delay between pub sub publish time and arrival to bigquery when using pub/sub to bigquery subscription (not through dataflow)?</p> <p>I have <code>publish_time</code> from pub sub metadata. And a field in BQ in the table where data flows that auto populates with <code>CURRENT_TIMESTAMP</code></p> <p>I was hoping to just check the timestamp difference but noticed that quite often current_timestamp is earlier than publish_time.</p> <p>It's about 350 messages/s and BQ table is partitioned by <code>_PARTITIONTIME</code> / hour if this makes any difference. Im also wondering what is expected delay?</p>
[ { "answer_id": 74563292, "author": "al-dann", "author_id": 6073141, "author_profile": "https://Stackoverflow.com/users/6073141", "pm_score": -1, "selected": false, "text": "current_timesstamp create table if not exists -- pubsub streaming subscription metadata\n subscription_name string not null options(description=\"A name of a source pubsub subscription.\")\n , message_id string not null options(description=\"A unique identifier of the pubsub message.\")\n , publish_time timestamp not null options(description=\"A timestamp when the pubsub message was published.\")\n , bq_record_ingest_time timestamp default current_timestamp() options(description=\"A timestamp when the record was ingested into the BQ table.\")\n -- and so on, other columns\n\n record_ingest_time publish_time" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74562589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4933628/" ]
74,562,663
<p>I am using this function for clearing contents</p> <pre><code>Sub ClearData() Range(&quot;K2,J3,B18:B38,H18:H38,I18:I38,J18:J38,F44&quot;).Value = &quot;&quot; End Sub </code></pre> <p>And this other function to copy the last sheet with the same content and also give it a name</p> <pre><code>Public Sub CopySheetAndRename() Dim newName As String On Error Resume Next newName = InputBox(&quot;Enter the name for the copied worksheet&quot;) If newName &lt;&gt; &quot;&quot; Then ActiveSheet.Copy After:=Worksheets(Sheets.Count) On Error Resume Next ActiveSheet.Name = newName End If End Sub </code></pre> <p>But what I need is that when I press the button to create the new copied sheet I also what to clear some cells in the new sheet. Now I have two buttons and I want only one button that must do what the other 2 are doing.</p> <p>I am new at this and still learning.</p> <p>I tried to combine the code but with no luck.</p> <p>Thank you all for the help. Now if someone knows how to get rid of the next text box every time I make a new sheet, please tell.</p> <p><a href="https://i.stack.imgur.com/02PHd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/02PHd.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74563292, "author": "al-dann", "author_id": 6073141, "author_profile": "https://Stackoverflow.com/users/6073141", "pm_score": -1, "selected": false, "text": "current_timesstamp create table if not exists -- pubsub streaming subscription metadata\n subscription_name string not null options(description=\"A name of a source pubsub subscription.\")\n , message_id string not null options(description=\"A unique identifier of the pubsub message.\")\n , publish_time timestamp not null options(description=\"A timestamp when the pubsub message was published.\")\n , bq_record_ingest_time timestamp default current_timestamp() options(description=\"A timestamp when the record was ingested into the BQ table.\")\n -- and so on, other columns\n\n record_ingest_time publish_time" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74562663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20591913/" ]
74,562,670
<p>Given code like:</p> <p><code>Thing? maybeAThing = GetThing();</code></p> <p>I want to write logic that safely checks if the object is not null and has a certain property:</p> <p><code>if(maybeAThing is not null &amp;&amp; maybeAThing.IsAGoodThing){ ... }</code></p> <p>But this syntax seems a bit messy. I thought the null-conditional operators were supposed to let me do this as any test will fail as soon as null is encountered:</p> <p><code>if(maybeAThing?.IsAGoodThing){...}</code></p> <p>But this gives compiler error:</p> <blockquote> <p>CS0266 cannot implicitly convert bool ? to bool</p> </blockquote> <p>It seems the 'nullableness' is extending to the return value (<code>bool?</code>) instead of the test failing as soon as <code>maybeAThing</code> is determined to be <code>null</code>.</p> <p>Is this specific to NRTs rather than nullable value types? Is there a way to do this without having to write additional clauses, and if not then what is my misunderstanding in the way the language works?</p>
[ { "answer_id": 74563292, "author": "al-dann", "author_id": 6073141, "author_profile": "https://Stackoverflow.com/users/6073141", "pm_score": -1, "selected": false, "text": "current_timesstamp create table if not exists -- pubsub streaming subscription metadata\n subscription_name string not null options(description=\"A name of a source pubsub subscription.\")\n , message_id string not null options(description=\"A unique identifier of the pubsub message.\")\n , publish_time timestamp not null options(description=\"A timestamp when the pubsub message was published.\")\n , bq_record_ingest_time timestamp default current_timestamp() options(description=\"A timestamp when the record was ingested into the BQ table.\")\n -- and so on, other columns\n\n record_ingest_time publish_time" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74562670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/197229/" ]
74,562,694
<p>Hello Guys I have the following dataset:</p> <pre><code># creating dataset dataset = pd.DataFrame() dataset['name'] = ['Alex', 'Alex', 'Alex','Alex','Alex', 'Marie', 'Marie', 'Marie','Marie','Marie', 'Luke', 'Luke', 'Luke','Luke','Luke'] dataset['sales'] = [690,451,478,524,750,452,784,523,451,125,854,745,856,900,105] dataset.info() dataset.shape </code></pre> <p>I want to create and print a string that will let me know the sales reps whose mean sale's are above 500 units, in order to achieve this I first grouped the data and calculated the mean by name like so:</p> <pre><code>result_grouped=dataset.groupby(['name']).aggregate({'sales': 'mean'}) </code></pre> <p>If I can use the following code to filter my target sales reps</p> <pre><code>print(list(result_grouped.index[(result_grouped['sales']&gt;500)])) result_grouped[(result_grouped['sales']&gt;500)] </code></pre> <p>which gives:</p> <pre><code>['Alex', 'Luke'] sales name Alex 578.6 Luke 692.0 </code></pre> <p>but my desired output will be something like so:</p> <p>a printable string in the format:</p> <p>&quot;The reps in the target metrics are: <code>name1</code> with <code>mean1</code>, <code>name2</code> with <code>mean2</code>, ... , <code>namen</code> with <code>meann</code>&quot;</p> <p><strong>for this example my output will be:</strong></p> <p>&quot;The reps in the target metrics are Alex with 578.6, Luke with 692.0&quot;</p> <p>I am very new to python and in the verge of a mental breakdown I know that this in the code genre does not seeem too hard but guys I come from an R enviroment and Python just seems to be very difficult for me I trully appreciate your help with this thank you so much for your help</p>
[ { "answer_id": 74563292, "author": "al-dann", "author_id": 6073141, "author_profile": "https://Stackoverflow.com/users/6073141", "pm_score": -1, "selected": false, "text": "current_timesstamp create table if not exists -- pubsub streaming subscription metadata\n subscription_name string not null options(description=\"A name of a source pubsub subscription.\")\n , message_id string not null options(description=\"A unique identifier of the pubsub message.\")\n , publish_time timestamp not null options(description=\"A timestamp when the pubsub message was published.\")\n , bq_record_ingest_time timestamp default current_timestamp() options(description=\"A timestamp when the record was ingested into the BQ table.\")\n -- and so on, other columns\n\n record_ingest_time publish_time" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74562694", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15587184/" ]
74,562,700
<p>If I have a dataframe with some index and some value as follows:</p> <pre><code>import pandas as pd from random import random my_index = [] my_vals = [] for i in range(1000): my_index.append(i+random()) my_vals.append(random()) df_vals = pd.DataFrame({'my_index': my_index, 'my_vals': my_vals}) </code></pre> <p>And I have a second dataframe with a column <code>start</code> and <code>end</code>, a row must be read as an interval, so the first row would be interval from <code>1</code> to <code>4</code> (including 1 and 4). It is the following dataframe:</p> <pre><code>df_intervals = pd.DataFrame({'start': [1, 7, 54, 73, 136, 235, 645, 785, 968], 'end': [4, 34, 65, 90, 200, 510, 700, 805, 988]}) </code></pre> <p>I would like to make all values in the <code>my_vals</code> column of <code>df_vals</code> a <code>NaN</code> if the row's index (<code>my_index</code>) does not fall in to one of the intervals specified in the <code>df_intervals</code> dataframe. What is the best way to go about this automatically rather than specifying each condition manually?</p> <p>(In my actual data set there are more than 9 intervals, this is some example data)</p> <p>EDIT: in my actual data these indeces are not strictly integers, these can also be random floats</p>
[ { "answer_id": 74563292, "author": "al-dann", "author_id": 6073141, "author_profile": "https://Stackoverflow.com/users/6073141", "pm_score": -1, "selected": false, "text": "current_timesstamp create table if not exists -- pubsub streaming subscription metadata\n subscription_name string not null options(description=\"A name of a source pubsub subscription.\")\n , message_id string not null options(description=\"A unique identifier of the pubsub message.\")\n , publish_time timestamp not null options(description=\"A timestamp when the pubsub message was published.\")\n , bq_record_ingest_time timestamp default current_timestamp() options(description=\"A timestamp when the record was ingested into the BQ table.\")\n -- and so on, other columns\n\n record_ingest_time publish_time" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74562700", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16002179/" ]
74,562,723
<p>Was just wondering why the color of the dots weren't changed albeit I was using the <code>scale_color_brewer(palette = &quot;Paired&quot;)</code> command to manually assign the colors. Thanks</p> <p>My image</p> <p><a href="https://i.stack.imgur.com/QkMPS.png" rel="nofollow noreferrer">1</a></p> <p>My script</p> <pre><code>psbsrd &lt;- read_csv(&quot;psbs rd.csv&quot;) psbsrd$gen=factor(psbsrd$gen,levels=c(&quot;WT&quot;,&quot;PsbS&quot;,&quot;T259A&quot;,&quot;T259D&quot;,&quot;T259E&quot;,&quot;T259S&quot;,&quot;S265-&quot;,&quot;T79A/S104A/T259A&quot;,&quot;T79D/S104E/T259D&quot;)) ggplot(psbsrd, aes(x=gen, y=rd,color=gen)) + scale_color_brewer(palette = &quot;Paired&quot;)+ geom_dotplot(binaxis='y', stackdir='center', stackratio=1, dotsize=0.7)+theme(text = element_text(size = 20))+theme(legend.position = &quot;none&quot;)+ theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust = 1))+ labs(x= &quot;&quot;, y=&quot;PsbS relative density&quot;) </code></pre> <p>My data frame</p> <pre><code>data.frame(psbsrd) id gen rd 1 1 WT 1.0000000 2 2 PsbS 1.2211420 3 3 PsbS 1.5918041 4 4 PsbS 2.1668718 5 5 PsbS 2.6198157 6 6 PsbS 1.5571007 7 7 PsbS 1.0520551 8 8 PsbS 0.4648043 9 9 PsbS 1.9454836 10 10 S265- 1.5497361 11 11 S265- 3.2732440 12 12 S265- 4.3479497 13 13 S265- 4.8951613 14 14 S265- 6.2919204 15 15 S265- 7.7251320 16 16 T79A/S104A/T259A 0.1784396 17 17 T79A/S104A/T259A 0.5977111 18 18 T79A/S104A/T259A 0.5307654 19 19 T79A/S104A/T259A 3.0679723 20 20 T79D/S104E/T259D 1.2229263 21 21 T259A 0.9812587 22 22 T259A 0.9647552 23 23 T259A 0.9001399 24 24 T259A 1.6814516 25 25 T259A 2.3471329 26 26 T259A 2.6215385 27 27 T259D 2.9000576 28 28 T259D 2.8604196 29 29 T259D 3.3292308 30 30 T259D 3.3822005 31 31 T259D 2.9608392 32 32 T259D 2.6813986 33 33 T259D 2.6746853 34 34 T259D 1.6584615 35 35 T259D 2.9927273 36 36 T259E 1.4003248 37 37 T259E 1.6272838 38 38 T259E 1.8465286 39 39 T259E 3.5475230 40 40 T259E 2.2281770 41 41 T259E 2.1733658 42 42 T259S 4.4847350 43 43 T259S 4.9366626 44 44 T259S 2.2005684 </code></pre>
[ { "answer_id": 74563292, "author": "al-dann", "author_id": 6073141, "author_profile": "https://Stackoverflow.com/users/6073141", "pm_score": -1, "selected": false, "text": "current_timesstamp create table if not exists -- pubsub streaming subscription metadata\n subscription_name string not null options(description=\"A name of a source pubsub subscription.\")\n , message_id string not null options(description=\"A unique identifier of the pubsub message.\")\n , publish_time timestamp not null options(description=\"A timestamp when the pubsub message was published.\")\n , bq_record_ingest_time timestamp default current_timestamp() options(description=\"A timestamp when the record was ingested into the BQ table.\")\n -- and so on, other columns\n\n record_ingest_time publish_time" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74562723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18430404/" ]
74,562,728
<p>I have a <code>Group</code> model with an inner field <code>List&lt;Entity&gt; entities</code></p> <p>How is possible to change the below code to one line by lambda and stream</p> <pre><code> Map&lt;String, String&gt; entityGroup = new HashMap&lt;&gt;(); groups.forEach(g -&gt; g.getEntities() .forEach(e -&gt; entityGroup.put(e.getKey(), g.getKey())) ); </code></pre> <p>Each entity in the inner list should be the key in the map and the value should be the Group itself</p> <p>Thanks</p>
[ { "answer_id": 74563032, "author": "marstran", "author_id": 4137489, "author_profile": "https://Stackoverflow.com/users/4137489", "pm_score": 3, "selected": true, "text": "Map Map.entry AbstractMap.SimpleEntry Pair Map<String, String> entityGroup = groups.stream()\n .flatMap(group -> group.getEntities().stream()\n .map(entity -> Map.entry(entity.getKey(), group.getKey())))\n .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));\n" }, { "answer_id": 74563065, "author": "sanroo", "author_id": 20592164, "author_profile": "https://Stackoverflow.com/users/20592164", "pm_score": 0, "selected": false, "text": "import java.util.*;\nimport java.util.stream.*;\n\npublic class MyClass {\n public static void main(String args[]) {\n List<B> b1 = List.of(new B(\"a\", \"1\"), new B(\"b\", \"2\"));\n List<B> b2 = List.of(new B(\"x\", \"3\"), new B(\"y\", \"4\"));\n A a1 = new A(b1);\n A a2 = new A(b2);\n List<A> allAs = List.of(a1, a2);\n Map<String, String> map =\n allAs.stream().flatMap(a -> a.vals.stream())\n .collect(Collectors.toMap(B::getKey, B::getValue));\n System.out.println(map); // {a=1, b=2, x=3, y=4}\n }\n}\n\nclass A {\n List<B> vals;\n public A(List<B> vals) { this.vals = vals; }\n}\n\nclass B {\n String k, v;\n public B(String k, String v) { this.k = k; this.v = v; }\n public String getKey() { return this.k; }\n public String getValue() { return this.v; }\n}\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74562728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8299968/" ]
74,562,738
<p>I'm trying to use GSAP to make a scrolling animation in my react application however I keep getting the error .getContext is not a function when I have linked it to the canvas.</p> <p>my plan is to create a scrolling animation similar to a flip book sort of thing</p> <p>any advice would be very much appreciated</p> <p>thanks</p> <pre><code>import { useRef } from &quot;react&quot;; import gsap from &quot;gsap&quot;; import ScrollTrigger from &quot;gsap/ScrollTrigger&quot;; function Landing() { const canvasRef = useRef(); canvasRef.width = window.innerWidth; canvasRef.height = window.innerHeight; const context = canvasRef.getContext(&quot;2d&quot;); const frameCount = 230; const currentFrame = (index) =&gt; `../../assets/landing-animations/${(index + 1).toString()}.jpg`; const images = []; let ball = { frame: 0 }; for (let i = 0; i &lt; frameCount; i++) { const img = new Image(); img.src = currentFrame(i); images.push(img); } images[0].onload = render; function render() { context.clearRect(0, 0, canvasRef.width, canvasRef.height); context.drawImage(images[ball.frame]); } return ( &lt;div className=&quot;landing&quot;&gt; &lt;h1 className=&quot;landing__header&quot;&gt;Welcome to my portfolio&lt;/h1&gt; &lt;canvas className=&quot;landing__canvas&quot; ref={canvasRef}&gt;&lt;/canvas&gt;; &lt;/div&gt; ); } export default Landing; </code></pre>
[ { "answer_id": 74563032, "author": "marstran", "author_id": 4137489, "author_profile": "https://Stackoverflow.com/users/4137489", "pm_score": 3, "selected": true, "text": "Map Map.entry AbstractMap.SimpleEntry Pair Map<String, String> entityGroup = groups.stream()\n .flatMap(group -> group.getEntities().stream()\n .map(entity -> Map.entry(entity.getKey(), group.getKey())))\n .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));\n" }, { "answer_id": 74563065, "author": "sanroo", "author_id": 20592164, "author_profile": "https://Stackoverflow.com/users/20592164", "pm_score": 0, "selected": false, "text": "import java.util.*;\nimport java.util.stream.*;\n\npublic class MyClass {\n public static void main(String args[]) {\n List<B> b1 = List.of(new B(\"a\", \"1\"), new B(\"b\", \"2\"));\n List<B> b2 = List.of(new B(\"x\", \"3\"), new B(\"y\", \"4\"));\n A a1 = new A(b1);\n A a2 = new A(b2);\n List<A> allAs = List.of(a1, a2);\n Map<String, String> map =\n allAs.stream().flatMap(a -> a.vals.stream())\n .collect(Collectors.toMap(B::getKey, B::getValue));\n System.out.println(map); // {a=1, b=2, x=3, y=4}\n }\n}\n\nclass A {\n List<B> vals;\n public A(List<B> vals) { this.vals = vals; }\n}\n\nclass B {\n String k, v;\n public B(String k, String v) { this.k = k; this.v = v; }\n public String getKey() { return this.k; }\n public String getValue() { return this.v; }\n}\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74562738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18624593/" ]
74,562,764
<p>I have this list:</p> <pre><code> t = [['1', '0', '1', '0', '0', '0', 'up', 5], ['1', '0', '1', '0', '0', '1', 'up', 5], ['1', '0', '1', '0', '1', '0', 'down', 5]] </code></pre> <p>I want to be able to find the following from that list:</p> <pre><code>o = ['1', '0', '1', '0', '1', '0'] u = &quot;up&quot; y = &quot;down </code></pre> <p>to make it clearer, i want to find out if <code>o</code> exists in <code>t</code>, and to find out whether or not <code>u</code> exists in the sublist where <code>o</code> exists</p> <p>i tried :</p> <pre><code> t = [['1', '0', '1', '0', '0', '0', 'up', 5], ['1', '0', '1', '0', '0', '1', 'up', 5], ['1', '0', '1', '0', '1', '0', 'down', 5]] o = ['1', '0', '1', '0', '1', '0'] u = &quot;up&quot; if o and u in t: print(&quot;the list you're looking for is present and the position of that sublist is up&quot;) elif o and y in t: print(&quot;the list you're looking for is present and the position of that sublist is down&quot;) else: print(&quot;it's not there&quot;) </code></pre> <p>i get this result:</p> <p><code>it's not there</code></p> <p>what i am trying to get is:</p> <p><code>the list you're looking for is present and the position of that sublist is down.</code></p>
[ { "answer_id": 74563032, "author": "marstran", "author_id": 4137489, "author_profile": "https://Stackoverflow.com/users/4137489", "pm_score": 3, "selected": true, "text": "Map Map.entry AbstractMap.SimpleEntry Pair Map<String, String> entityGroup = groups.stream()\n .flatMap(group -> group.getEntities().stream()\n .map(entity -> Map.entry(entity.getKey(), group.getKey())))\n .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));\n" }, { "answer_id": 74563065, "author": "sanroo", "author_id": 20592164, "author_profile": "https://Stackoverflow.com/users/20592164", "pm_score": 0, "selected": false, "text": "import java.util.*;\nimport java.util.stream.*;\n\npublic class MyClass {\n public static void main(String args[]) {\n List<B> b1 = List.of(new B(\"a\", \"1\"), new B(\"b\", \"2\"));\n List<B> b2 = List.of(new B(\"x\", \"3\"), new B(\"y\", \"4\"));\n A a1 = new A(b1);\n A a2 = new A(b2);\n List<A> allAs = List.of(a1, a2);\n Map<String, String> map =\n allAs.stream().flatMap(a -> a.vals.stream())\n .collect(Collectors.toMap(B::getKey, B::getValue));\n System.out.println(map); // {a=1, b=2, x=3, y=4}\n }\n}\n\nclass A {\n List<B> vals;\n public A(List<B> vals) { this.vals = vals; }\n}\n\nclass B {\n String k, v;\n public B(String k, String v) { this.k = k; this.v = v; }\n public String getKey() { return this.k; }\n public String getValue() { return this.v; }\n}\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74562764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20591885/" ]
74,562,785
<p>I have a python dictionary in which the keys of the dictionary are tuples of two strings and the values are integers.</p> <p>It looks like this:</p> <pre><code>mydic = { ('column1', 'index1'):33, ('column1', 'index2'):34, ('column2', 'index1'):35, ('column2', 'index2'):36 } </code></pre> <p>The first string of the tuples should be used as the column-name in the dataframe and the second string in the tuple should be used as the index.</p> <p>The dataframe from this should look like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>(index)</th> <th>column1</th> <th>column 2</th> </tr> </thead> <tbody> <tr> <td>index1</td> <td>33</td> <td>35</td> </tr> <tr> <td>index2</td> <td>34</td> <td>36</td> </tr> </tbody> </table> </div> <p>Is there any way to do this?</p> <p>(Or do I have to loop through all elements of the dictionary and build the dataframe one value at a time by hand?)</p>
[ { "answer_id": 74562918, "author": "Rabinzel", "author_id": 15521392, "author_profile": "https://Stackoverflow.com/users/15521392", "pm_score": 3, "selected": true, "text": "pd.Series pd.Series.unstack df = pd.Series(mydic).unstack(0)\nprint(df)\n column1 column2\nindex1 33 35\nindex2 34 36\n" }, { "answer_id": 74562976, "author": "Vini", "author_id": 6927944, "author_profile": "https://Stackoverflow.com/users/6927944", "pm_score": 0, "selected": false, "text": "pd.MultiIndex.from_tuples mydic = { ('column1', 'index1'):33, \n ('column1', 'index2'):34, \n ('column2', 'index1'):35, \n ('column2', 'index2'):36 }\n\ndf = pd.DataFrame(mydic.values(), index = pd.MultiIndex.from_tuples(mydic))\n\n 0\ncolumn1 index1 33\n index2 34\ncolumn2 index1 35\n index2 36\n df.T.stack()\n\n column1 column2\n0 index1 33 35\n index2 34 36\n df.T.stack().reset_index().drop('level_0', axis = 1)\n\n level_1 column1 column2\n0 index1 33 35\n1 index2 34 36\n level_1" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74562785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20591781/" ]
74,562,849
<p>I am getting below error while trying to create VPC Access connector in GCP region <code>us-central1</code>:</p> <pre><code>An internal error occurred: VPC Access connector failed to get healthy. Please check GCE quotas, logs and org policies and recreate. </code></pre> <p>I also tried to create the VPC access connector in region us-east1 but got the same issue.</p> <p>I tried searching for existing bugs on <a href="https://issuetracker.google.com/issues?q=Serverless%20VPC%20Connector%20in%20us-central1" rel="nofollow noreferrer">gcp issues portal</a> but could not find this issue.</p> <p>I have tried to follow <a href="https://cloud.google.com/compute/docs/images/restricting-image-access#trusted_images" rel="nofollow noreferrer">image access constraint</a> but I don't have an organisation so I am unable to edit the required policy.</p>
[ { "answer_id": 74562918, "author": "Rabinzel", "author_id": 15521392, "author_profile": "https://Stackoverflow.com/users/15521392", "pm_score": 3, "selected": true, "text": "pd.Series pd.Series.unstack df = pd.Series(mydic).unstack(0)\nprint(df)\n column1 column2\nindex1 33 35\nindex2 34 36\n" }, { "answer_id": 74562976, "author": "Vini", "author_id": 6927944, "author_profile": "https://Stackoverflow.com/users/6927944", "pm_score": 0, "selected": false, "text": "pd.MultiIndex.from_tuples mydic = { ('column1', 'index1'):33, \n ('column1', 'index2'):34, \n ('column2', 'index1'):35, \n ('column2', 'index2'):36 }\n\ndf = pd.DataFrame(mydic.values(), index = pd.MultiIndex.from_tuples(mydic))\n\n 0\ncolumn1 index1 33\n index2 34\ncolumn2 index1 35\n index2 36\n df.T.stack()\n\n column1 column2\n0 index1 33 35\n index2 34 36\n df.T.stack().reset_index().drop('level_0', axis = 1)\n\n level_1 column1 column2\n0 index1 33 35\n1 index2 34 36\n level_1" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74562849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14373886/" ]
74,562,852
<p>I would like to write my own Python function (i.e. without using any other non base Python functions) to compare the characters in two strings in the following way.</p> <ul> <li><p>If the letter in position <code>i</code> of <em>string 1</em> is the same as the letter in position <code>i</code> of <em>string 2</em> then <code>&quot;Green&quot;</code> is returned</p> </li> <li><p>If the letter in position <code>i</code> of <em>string 1</em> is the same as the letter in position <code>[i-1]</code> or <code>[i+1]</code> of <em>string 2</em> then <code>&quot;Blue&quot;</code> is returned</p> </li> <li><p>If the letter in position <code>i</code> of <em>string 1</em> is not the same as the letters in position <code>[i-1]</code> , <code>i</code> or <code>[i+1]</code> of <em>string 2</em> then <code>&quot;White&quot;</code> is returned</p> </li> </ul> <p>The final output of the function should be a tuple of the <code>&quot;Green&quot;</code> / <code>&quot;Blue&quot;</code> / <code>&quot;White&quot;</code> output for each letter.</p> <p>For example, if we call the function <code>letter_comparison</code> and write:</p> <pre><code>def letter_comparison(string1, string2): ..... </code></pre> <p><code>letter_comparison(&quot;chain&quot;, &quot;chant&quot;)</code> would return <code>&quot;Green&quot;</code>, <code>&quot;Green&quot;</code>, <code>&quot;Green&quot;</code>, <code>&quot;White&quot;</code>, <code>&quot;Blue&quot;</code>.</p> <p>Any ideas would be appreciated.</p>
[ { "answer_id": 74562918, "author": "Rabinzel", "author_id": 15521392, "author_profile": "https://Stackoverflow.com/users/15521392", "pm_score": 3, "selected": true, "text": "pd.Series pd.Series.unstack df = pd.Series(mydic).unstack(0)\nprint(df)\n column1 column2\nindex1 33 35\nindex2 34 36\n" }, { "answer_id": 74562976, "author": "Vini", "author_id": 6927944, "author_profile": "https://Stackoverflow.com/users/6927944", "pm_score": 0, "selected": false, "text": "pd.MultiIndex.from_tuples mydic = { ('column1', 'index1'):33, \n ('column1', 'index2'):34, \n ('column2', 'index1'):35, \n ('column2', 'index2'):36 }\n\ndf = pd.DataFrame(mydic.values(), index = pd.MultiIndex.from_tuples(mydic))\n\n 0\ncolumn1 index1 33\n index2 34\ncolumn2 index1 35\n index2 36\n df.T.stack()\n\n column1 column2\n0 index1 33 35\n index2 34 36\n df.T.stack().reset_index().drop('level_0', axis = 1)\n\n level_1 column1 column2\n0 index1 33 35\n1 index2 34 36\n level_1" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74562852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17643887/" ]
74,562,856
<p>I am trying to run a command where I get all active directory users in the parent OU (Users) and filter out the child OU's (Admin accounts, service accounts, disabled accounts) as well as filter out any user account that does not have a surname in the surname field.</p> <p>At the moment I have</p> <pre><code>Get-ADUser -Filter{enabled -eq $true} -SearchBase 'OU=Users,OU=Company,DC=CompanyName,DC=local' | Where-Object { $_.DistinguishedName -notlike &quot;*,$Disabled&quot; } | Where {$_.Surname -notlike &quot;$Null&quot;} | select samAccountName </code></pre> <p>When I add another child OU after 'Disabled' there is an error</p> <p><code>Where-Object : A positional parameter cannot be found that accepts argument 'Where'.</code></p> <p>Please may someone advise on how to filter out additional child OU's?</p>
[ { "answer_id": 74562918, "author": "Rabinzel", "author_id": 15521392, "author_profile": "https://Stackoverflow.com/users/15521392", "pm_score": 3, "selected": true, "text": "pd.Series pd.Series.unstack df = pd.Series(mydic).unstack(0)\nprint(df)\n column1 column2\nindex1 33 35\nindex2 34 36\n" }, { "answer_id": 74562976, "author": "Vini", "author_id": 6927944, "author_profile": "https://Stackoverflow.com/users/6927944", "pm_score": 0, "selected": false, "text": "pd.MultiIndex.from_tuples mydic = { ('column1', 'index1'):33, \n ('column1', 'index2'):34, \n ('column2', 'index1'):35, \n ('column2', 'index2'):36 }\n\ndf = pd.DataFrame(mydic.values(), index = pd.MultiIndex.from_tuples(mydic))\n\n 0\ncolumn1 index1 33\n index2 34\ncolumn2 index1 35\n index2 36\n df.T.stack()\n\n column1 column2\n0 index1 33 35\n index2 34 36\n df.T.stack().reset_index().drop('level_0', axis = 1)\n\n level_1 column1 column2\n0 index1 33 35\n1 index2 34 36\n level_1" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74562856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20592031/" ]
74,562,862
<p>I am working on a wordle clone as a project to get familiar with python and tkinter. I have made a 6x5 grid of entry boxes that all accept one letter. I am trying to make it that each box will automatically convert that letter to uppercase, but I am having issues with that. Only the very last entry will be uppercase.</p> <pre><code>def validate(P): if len(P) == 0: # empty Entry is ok return True elif len(P) == 1 and not P.isdigit(): # Entry with 1 digit is ok return True else: # Anything else, reject it return False # sets v to upper def caps(event): v.set(v.get().upper()) vcmd = (window.register(validate), '%P') canvas1 = tk.Canvas(window, width = 400, height = 300) borderColor = Frame(window, background=&quot;#A3F299&quot;) #2d array of entrys to create the 6x5 grid entries = [[]] inner = [] # Will loop to create 6 rows, 5 columns # v - user input # inner - row of entries # entries - entire grid of entries # validate ensures that only 1 character is entered in the box for x in range(6): for i in range(5): v = StringVar() inner.insert(i, Entry(window, validate=&quot;key&quot;, width = 2, validatecommand=vcmd, font=(&quot;Helvetica, 35&quot;), justify='center', textvariable= v, bg='white')) inner[i].bind(&quot;&lt;KeyRelease&gt;&quot;, caps) entries.insert(x, inner) entries[x][i].grid(row= x, column= i) </code></pre> <p>I have sort of deduced that it is because v is being set as text for each entry and it will make it uppercase if a key is released; however, because it continues to loop through this loop, it keeps setting v to a different entry and that would be the only one to be set to uppercase. e.g:</p> <p>If I only loop through it for one row the output will be [a, a, a, a, A] if I loop through it a second time it will be [a, a, a, a, a], [a, a, a, a, A]</p> <p>I have also tried making v a double array and setting each index to text variable and calling it in caps; however, it would only work for one row and it was very redundant because I would have to call v.set(v.get.... 5 different times, it would not work if I tried to loop through it.</p>
[ { "answer_id": 74562918, "author": "Rabinzel", "author_id": 15521392, "author_profile": "https://Stackoverflow.com/users/15521392", "pm_score": 3, "selected": true, "text": "pd.Series pd.Series.unstack df = pd.Series(mydic).unstack(0)\nprint(df)\n column1 column2\nindex1 33 35\nindex2 34 36\n" }, { "answer_id": 74562976, "author": "Vini", "author_id": 6927944, "author_profile": "https://Stackoverflow.com/users/6927944", "pm_score": 0, "selected": false, "text": "pd.MultiIndex.from_tuples mydic = { ('column1', 'index1'):33, \n ('column1', 'index2'):34, \n ('column2', 'index1'):35, \n ('column2', 'index2'):36 }\n\ndf = pd.DataFrame(mydic.values(), index = pd.MultiIndex.from_tuples(mydic))\n\n 0\ncolumn1 index1 33\n index2 34\ncolumn2 index1 35\n index2 36\n df.T.stack()\n\n column1 column2\n0 index1 33 35\n index2 34 36\n df.T.stack().reset_index().drop('level_0', axis = 1)\n\n level_1 column1 column2\n0 index1 33 35\n1 index2 34 36\n level_1" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74562862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10388485/" ]
74,562,868
<p>I need to create a Line chart, which works with multiple datasets, and with numbers that vastly differ from dataset to dataset</p> <p>For example</p> <pre class="lang-js prettyprint-override"><code>// Tracks how much on average a customer has spend const averagePurchaseValueDataset = { label: 'Average Purchase Value', dataset: [25.50, 28.50, 24.30, 26.40 ] } // Tracks on average how much the customer spends browsing the app // tracked in seconds const sessionDurationDataset = { label: 'Session Duration', dataset: [80, 120, 90, 85, 93] } // Tracks how many products the customer has purchased in one session const averageItemsPurchased = { label: 'Average Items Purchased', dataset: [3, 2, 1, 1] } </code></pre> <p>I need to create a single chart with 3 different lines on it, which are stacked on top of each other.</p> <p>ChartJS does this by default when the datasets consist of similar values ( like 1-10 ), however, in my datasets, the ranges vary vastly - one dataset can have numbers between 1-10 and another one 5000-1000, but I still want them stacked on top of each other.</p> <p>The goal of this chart is not to compare the literal values in each dataset, but their changes from one interval to the next.</p> <p>For example these two datasets <code>[10, 11]</code> and <code>[1000, 1100]</code> should plot two lines which are stacked exactly on top of each other, because the difference is 10% in both cases</p>
[ { "answer_id": 74562918, "author": "Rabinzel", "author_id": 15521392, "author_profile": "https://Stackoverflow.com/users/15521392", "pm_score": 3, "selected": true, "text": "pd.Series pd.Series.unstack df = pd.Series(mydic).unstack(0)\nprint(df)\n column1 column2\nindex1 33 35\nindex2 34 36\n" }, { "answer_id": 74562976, "author": "Vini", "author_id": 6927944, "author_profile": "https://Stackoverflow.com/users/6927944", "pm_score": 0, "selected": false, "text": "pd.MultiIndex.from_tuples mydic = { ('column1', 'index1'):33, \n ('column1', 'index2'):34, \n ('column2', 'index1'):35, \n ('column2', 'index2'):36 }\n\ndf = pd.DataFrame(mydic.values(), index = pd.MultiIndex.from_tuples(mydic))\n\n 0\ncolumn1 index1 33\n index2 34\ncolumn2 index1 35\n index2 36\n df.T.stack()\n\n column1 column2\n0 index1 33 35\n index2 34 36\n df.T.stack().reset_index().drop('level_0', axis = 1)\n\n level_1 column1 column2\n0 index1 33 35\n1 index2 34 36\n level_1" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74562868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13992557/" ]
74,562,876
<p>I already checked multiple sites and posts regarding this topic, but couldn't find an answer yet. I simply want to fire the following JS code if someone clicked a specific Checkbox in my form:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function updateRequirements() { var escortWrapper = document.querySelector(".elementor-field-type-html .elementor-field-group .elementor-column .elementor-field-group-field_ceffa28 .elementor-col-100"); if (escortWrapper.style.display != 'none') { document.getElementById('escort').required = true; } else { document.getElementById('escort').required = false; } }</code></pre> </div> </div> </p> <p>You can check and test that for yourself on the following site: <a href="https://advelio.de/event-feedback" rel="nofollow noreferrer">Advelio Website</a></p> <p>If you click on the second checkbox field, there is a field appearing where you can type in your name. And this field is currently optional, but I want to make this required if someone clicked the second checkbox.</p>
[ { "answer_id": 74562982, "author": "Michael M.", "author_id": 13376511, "author_profile": "https://Stackoverflow.com/users/13376511", "pm_score": 2, "selected": true, "text": "function updateRequirements() {\n const btn = document.getElementById('escort');\n btn.required = !btn.required;\n}\n\ndocument.querySelector(\"#requireCheck\").addEventListener('click', updateRequirements); <form>\n <input type=\"checkbox\" id=\"requireCheck\">\n <label for=\"requireCheck\">Should the the other input be required?</label>\n <br>\n <input type=\"text\" id=\"escort\">\n <input type=\"submit\" value=\"submit\">\n</form> updateRequirements" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74562876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15499569/" ]
74,562,896
<p>Wanted to perform hover on nav menu item which should show the sub menu.</p> <pre><code> chrome.scripting.executeScript( { target: {tabId: tabId}, func: hoverFunction, args:[id] }, (injectionResults) =&gt; { // perform something post execution }); function hoverFunction(id){ let element = document.getElementById(id); element.addEventListener('mouseover', function() { console.log('Event triggered'); }); var event = new MouseEvent('mouseover', { 'view': window, 'bubbles': true, 'cancelable': true }); element.dispatchEvent(event); } </code></pre> <p>Tried to simulate the mouse over event on a menu item, I see the event getting triggered as I see console log getting printed but the submenu doesn't popup on script execution..</p> <p>Tried to simulate/dispatch the mouse over event on a menu item, I see the event getting triggered as I see console log getting printed but the submenu doesn't popup on script execution..</p> <p>My expectation is I should be able to automate/perform hover on a element with script and get the expected events to happen..In this case , the submenu to popup or to show tooltip for the elements if any on mouseover..</p>
[ { "answer_id": 74562982, "author": "Michael M.", "author_id": 13376511, "author_profile": "https://Stackoverflow.com/users/13376511", "pm_score": 2, "selected": true, "text": "function updateRequirements() {\n const btn = document.getElementById('escort');\n btn.required = !btn.required;\n}\n\ndocument.querySelector(\"#requireCheck\").addEventListener('click', updateRequirements); <form>\n <input type=\"checkbox\" id=\"requireCheck\">\n <label for=\"requireCheck\">Should the the other input be required?</label>\n <br>\n <input type=\"text\" id=\"escort\">\n <input type=\"submit\" value=\"submit\">\n</form> updateRequirements" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74562896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17050594/" ]
74,562,932
<p>I would like to add a missing paragraph tag <code>&lt;p&gt;&lt;/p&gt;</code> in a broken HTML code.</p> <p>Example: this is my broken HTML code:</p> <pre class="lang-html prettyprint-override"><code>&lt;strong&gt;My Headline&lt;/strong&gt; This text has a missing paragraph &lt;strong&gt;Some more text &lt;a href=&quot;#&quot;&gt;maybe with a link&lt;/a&gt;&lt;/strong&gt; &lt;p&gt;this one is right&lt;/p&gt; </code></pre> <p>I'd like to add the missing paragraph tags like this:</p> <pre class="lang-html prettyprint-override"><code>&lt;p&gt; &lt;strong&gt;My Headline&lt;/strong&gt; &lt;/p&gt; &lt;p&gt; This text has a missing paragraph &lt;/p&gt; &lt;p&gt; &lt;strong&gt;Some more text &lt;a href=&quot;#&quot;&gt;maybe with a link&lt;/a&gt;&lt;/strong&gt; &lt;/p&gt; &lt;p&gt;this one is right&lt;/p&gt; </code></pre> <p>What would be the best solution to fix this problem using Python3?</p>
[ { "answer_id": 74563022, "author": "accdias", "author_id": 6789321, "author_profile": "https://Stackoverflow.com/users/6789321", "pm_score": 1, "selected": false, "text": "str >>> s = '''<strong>My Headline</strong>\n... This text has a missing paragraph\n... <strong>Some more text <a href=\"#\">maybe with a link</a></strong>\n... <p>this one is right</p>'''\n>>> \n>>> for line in s.splitlines():\n... print(f'<p>{line}</p>' if not line.startswith('<p>') else line)\n... \n<p><strong>My Headline</strong></p>\n<p>This text has a missing paragraph</p>\n<p><strong>Some more text <a href=\"#\">maybe with a link</a></strong></p>\n<p>this one is right</p>\n>>> \n" }, { "answer_id": 74563074, "author": "rtoth", "author_id": 20589189, "author_profile": "https://Stackoverflow.com/users/20589189", "pm_score": 0, "selected": false, "text": "with open(\"example.html\", \"r\")as old, open(\"new.html\", \"w\") as new:\n\n for line in old:\n if line.strip().startswith(\"<p>\"):\n new.write(line)\n else:\n new.write(\"<p>\\n\" + line + \"</p>\\n\")\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74562932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16590789/" ]
74,562,962
<p>I want to replace a word from url. I have tried many code but. not working</p> <p>For e.g. I have a URL : <a href="https://www.example.com/blog/single/how-to-start-single-app" rel="nofollow noreferrer">https://www.example.com/blog/single/how-to-start-single-app</a></p> <p>Want to redirect to URL - <a href="https://www.example.com/blog/post/how-to-start-single-app" rel="nofollow noreferrer">https://www.example.com/blog/post/how-to-start-single-app</a></p> <p>tried with the below rule</p> <pre><code>RewriteRule ^(.*)single(.*)$ $1post$2 [R=301,L] </code></pre> <p>but it replace all the single word of url into post.</p>
[ { "answer_id": 74563022, "author": "accdias", "author_id": 6789321, "author_profile": "https://Stackoverflow.com/users/6789321", "pm_score": 1, "selected": false, "text": "str >>> s = '''<strong>My Headline</strong>\n... This text has a missing paragraph\n... <strong>Some more text <a href=\"#\">maybe with a link</a></strong>\n... <p>this one is right</p>'''\n>>> \n>>> for line in s.splitlines():\n... print(f'<p>{line}</p>' if not line.startswith('<p>') else line)\n... \n<p><strong>My Headline</strong></p>\n<p>This text has a missing paragraph</p>\n<p><strong>Some more text <a href=\"#\">maybe with a link</a></strong></p>\n<p>this one is right</p>\n>>> \n" }, { "answer_id": 74563074, "author": "rtoth", "author_id": 20589189, "author_profile": "https://Stackoverflow.com/users/20589189", "pm_score": 0, "selected": false, "text": "with open(\"example.html\", \"r\")as old, open(\"new.html\", \"w\") as new:\n\n for line in old:\n if line.strip().startswith(\"<p>\"):\n new.write(line)\n else:\n new.write(\"<p>\\n\" + line + \"</p>\\n\")\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74562962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10075834/" ]
74,563,000
<p>I have a list which contains lists. I am trying to remove any duplicates of lists which may share the same items within the list but in a different order.</p> <p>for example if I have this</p> <pre><code>nestedlist=[[1,2,3,4],[4,3,2,1],[1,5,8,7]] </code></pre> <p>I would like a function that returns something like:</p> <pre><code>[[1,2,3,4],[1,5,8,7]] </code></pre>
[ { "answer_id": 74563022, "author": "accdias", "author_id": 6789321, "author_profile": "https://Stackoverflow.com/users/6789321", "pm_score": 1, "selected": false, "text": "str >>> s = '''<strong>My Headline</strong>\n... This text has a missing paragraph\n... <strong>Some more text <a href=\"#\">maybe with a link</a></strong>\n... <p>this one is right</p>'''\n>>> \n>>> for line in s.splitlines():\n... print(f'<p>{line}</p>' if not line.startswith('<p>') else line)\n... \n<p><strong>My Headline</strong></p>\n<p>This text has a missing paragraph</p>\n<p><strong>Some more text <a href=\"#\">maybe with a link</a></strong></p>\n<p>this one is right</p>\n>>> \n" }, { "answer_id": 74563074, "author": "rtoth", "author_id": 20589189, "author_profile": "https://Stackoverflow.com/users/20589189", "pm_score": 0, "selected": false, "text": "with open(\"example.html\", \"r\")as old, open(\"new.html\", \"w\") as new:\n\n for line in old:\n if line.strip().startswith(\"<p>\"):\n new.write(line)\n else:\n new.write(\"<p>\\n\" + line + \"</p>\\n\")\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74563000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19286514/" ]
74,563,009
<p>The Beam Java API has a <code>PAssert</code> method <code>satisfies</code> which takes a function of type <code>SerializableFunction&lt;Iterable&lt;T&gt;, Void&gt;</code></p> <p>However, Java's <code>Void</code> isn't exactly the same as Scala's <code>Unit</code>, so the compiler complains if you pass something like <code>PAssert.that(foo).satisfies(contents =&gt; contents.forEach(_.someListProperty.nonEmpty))</code>.</p> <p>You can add a <code>asInstanceOf[Null]</code> at the end of the <code>forEach</code> to get rid of the compilation error, but then it throws a runtime exception saying that it cannot cast the class to null.</p> <p>If you also just explicitly return null at the end of the function, the test always evaluates to true, even if the predicate was false.</p> <p>How can one use this function? Or is there another way to test that each individual element of a resulting PCollection satisfies a condition?</p>
[ { "answer_id": 74563022, "author": "accdias", "author_id": 6789321, "author_profile": "https://Stackoverflow.com/users/6789321", "pm_score": 1, "selected": false, "text": "str >>> s = '''<strong>My Headline</strong>\n... This text has a missing paragraph\n... <strong>Some more text <a href=\"#\">maybe with a link</a></strong>\n... <p>this one is right</p>'''\n>>> \n>>> for line in s.splitlines():\n... print(f'<p>{line}</p>' if not line.startswith('<p>') else line)\n... \n<p><strong>My Headline</strong></p>\n<p>This text has a missing paragraph</p>\n<p><strong>Some more text <a href=\"#\">maybe with a link</a></strong></p>\n<p>this one is right</p>\n>>> \n" }, { "answer_id": 74563074, "author": "rtoth", "author_id": 20589189, "author_profile": "https://Stackoverflow.com/users/20589189", "pm_score": 0, "selected": false, "text": "with open(\"example.html\", \"r\")as old, open(\"new.html\", \"w\") as new:\n\n for line in old:\n if line.strip().startswith(\"<p>\"):\n new.write(line)\n else:\n new.write(\"<p>\\n\" + line + \"</p>\\n\")\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74563009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15560990/" ]
74,563,020
<p><a href="https://i.stack.imgur.com/Sxzzl.png" rel="nofollow noreferrer">This is a cutout of my dataframe</a> I have a dataframe where i have two different variables that is found one year apart from each other. I would like to combine for exampel 2007 and 2008 to make one row with both variable and name it Denmark2007/8. I have about 300 rows to do this with, and cannot find a command that will do this, and typing it mannually is not in the question</p> <p>I have looked at everything from merge() and colsums, and i am lost</p>
[ { "answer_id": 74565302, "author": "Len Greski", "author_id": 8471931, "author_profile": "https://Stackoverflow.com/users/8471931", "pm_score": 2, "selected": false, "text": "tidyr::separate() sep = \" \" Year v1 v2 textData <- \"v1,Country,v2\n0.93181,Denmark 2007,NA\nNA,Denmark 2008,5.519108\n0.64285,Denmark 2009,NA\nNA,Denmark 2010,4.93885\n.55260,Denmark 2011,NA\nNA,Denmark 2012,5.101908\n0.13187,United Kingdom 2007,NA\nNA,United Kingdom 2008,3.18781\"\n\ndf <- read.csv(text = textData)\n Country Year v1 v2 yearType library(dplyr)\nlibrary(stringr)\ndf %>% \n mutate(countryLength = str_length(Country),\n countryName = substr(Country,1,countryLength - 5),\n Year = as.numeric(substr(Country,countryLength - 4,countryLength)),\n value = if_else(!is.na(v1),v1,v2),\n yearType = if_else(Year %% 2 == 0,\"Even\",\"Odd\")) %>%\n select(!c(Country,countryLength,v1,v2)) %>%\n rename(Country = countryName) %>%\n split(.$yearType) -> dataList \n Year dataList$Even %>%\n rename(EvenYearValue = value) %>%\n mutate(Year = Year - 1) %>% \n select(-yearType) %>% \n full_join(dataList$Odd,by = c(\"Country\",\"Year\")) %>%\n rename(OddYearValue = value,\n OddYear = Year) %>%\n mutate(EvenYear = OddYear + 1) %>% select(-yearType)\n Country OddYear EvenYearValue OddYearValue EvenYear\n1 Denmark 2007 5.519108 0.93181 2008\n2 Denmark 2009 4.938850 0.64285 2010\n3 Denmark 2011 5.101908 0.55260 2012\n4 United Kingdom 2007 3.187810 0.13187 2008\n> \n Country dataList$Even %>%\n rename(EvenYearValue = value) %>%\n mutate(Year = Year - 1) %>% \n select(-yearType) %>% \n full_join(dataList$Odd,by = c(\"Country\",\"Year\")) %>%\n rename(OddYearValue = value,\n OddYear = Year) %>%\n mutate(EvenYear = OddYear + 1) %>% select(-yearType) %>%\n # modify the Country name to include years\n mutate(Country = paste(Country,OddYear,\"-\",EvenYear))\n Country OddYear EvenYearValue OddYearValue EvenYear\n1 Denmark 2007 - 2008 2007 5.519108 0.93181 2008\n2 Denmark 2009 - 2010 2009 4.938850 0.64285 2010\n3 Denmark 2011 - 2012 2011 5.101908 0.55260 2012\n4 United Kingdom 2007 - 2008 2007 3.187810 0.13187 2008\n> \n textData <- \"v1,Country,v2\n0.93181,Denmark 2007,NA\nNA,Denmark 2008,5.519108\n0.64285,Denmark 2009,NA\nNA,Denmark 2010,4.93885\n.55260,Denmark 2011,NA\nNA,Denmark 2012,5.101908\n0.13187,United Kingdom 2007,NA\nNA,United Kingdom 2008,3.18781\"\n\ndf <- read.csv(text = textData)\n Country Year countryName yearlyData library(dplyr)\nlibrary(stringr)\ndf %>% \n mutate(countryLength = str_length(Country),\n countryName = substr(Country,1,countryLength - 5),\n Year = as.numeric(substr(Country,countryLength - 4,countryLength))) %>%\n select(!c(Country,countryLength)) %>%\n rename(Country = countryName) -> yearlyData\n v1 Year yearlyData %>%\n filter(Year %% 2 == 0) %>%\n select(-v1) %>% \n mutate( Year = Year - 1) -> evenYears\n filter() evenYears full_join() yearlyData %>% \n filter(Year %% 2 == 1) %>%\n rename(OddYearValue = v1) %>% \n select(-v2) %>% \n full_join(.,evenYears,by = c(\"Year\",\"Country\")) %>%\n rename(EvenYearValue = v2,\n OddYear = Year) %>%\n mutate(EvenYear = OddYear + 1)\n \n OddYearValue Country OddYear EvenYearValue EvenYear\n1 0.93181 Denmark 2007 5.519108 2008\n2 0.64285 Denmark 2009 4.938850 2010\n3 0.55260 Denmark 2011 5.101908 2012\n4 0.13187 United Kingdom 2007 3.187810 2008\n> \n OddYear EvenYear Country Country Year textData <- \"v1,Country,v2\n0.93181,Denmark 2007,NA\nNA,Denmark 2008,5.519108\n0.64285,Denmark 2009,NA\nNA,Denmark 2010,4.93885\n.55260,Denmark 2011,NA\nNA,Denmark 2012,5.101908\n0.13187,United Kingdom 2007,NA\nNA,United Kingdom 2008,3.18781\"\n\ndf <- read.csv(text = textData)\n\nlibrary(dplyr)\nlibrary(stringr)\ndf %>% \n mutate(countryLength = str_length(Country),\n countryName = substr(Country,1,countryLength - 5),\n Year = as.numeric(substr(Country,countryLength - 4,countryLength)),\n value = if_else(!is.na(v1),v1,v2)) %>%\n select(!c(Country,countryLength,v1,v2)) %>%\n rename(Country = countryName) -> yearlyData\n\nyearlyData\n > yearlyData\n Country Year value\n1 Denmark 2007 0.931810\n2 Denmark 2008 5.519108\n3 Denmark 2009 0.642850\n4 Denmark 2010 4.938850\n5 Denmark 2011 0.552600\n6 Denmark 2012 5.101908\n7 United Kingdom 2007 0.131870\n8 United Kingdom 2008 3.187810\n> \n" }, { "answer_id": 74576075, "author": "LeonaRdo", "author_id": 1813268, "author_profile": "https://Stackoverflow.com/users/1813268", "pm_score": 1, "selected": false, "text": "Country year v1 v2 v1 \n# Import data and libraries\nlibrary(dplyr)\nlibrary(tidyr)\nlibrary(stringr)\n\ndf <- tribble(\n ~v1,~Country,~v2,\n #--|--|---\n 0.93181,\"Denmark 2007\",NA,\n NA,\"Denmark 2008\",5.519108,\n 0.64285,\"Denmark 2009\",NA,\n NA,\"Denmark 2010\",4.93885,\n 0.55260,\"Denmark 2011\",NA,\n NA,\"Denmark 2012\",5.101908,\n 0.13187,\"New Zealand 2007\",NA,\n NA,\"New Zealand 2008\",3.187819\n)\n\n\n# Regular expressions to extract year and country from the Country column\nregexp_year <- \"[[:digit:]]+\"\nregexp_country <- \"[[:alpha:]\\\\s]+\"\n\n\n# Function that carries out the string extraction from the `Country` column\ndo_separate_df <- function(df) {\n df %>% \n mutate(year = str_extract(Country,regexp_year) %>% as.numeric()) %>%\n mutate(Country = str_extract(Country,regexp_country))\n}\n\n\n# Tibble with non-NA values in v1 (earlier year)\ndf_v1 <- df %>% \n select(v1,Country) %>%\n drop_na %>% \n do_separate_df() \n\n\n# Tibble with non-NA values in v2 (later year)\ndf_v2 <- df %>% \n select(Country,v2) %>% \n drop_na %>% \n do_separate_df()\n\n\n# Join on df_v1$year + 1 = df_v2$year\ndf_combined <-inner_join(\n df_v1 %>% mutate(year_to_match = year + 1),\n df_v2, \n by=c(\"year_to_match\" = \"year\", \"Country\")\n) %>% \n mutate(Country = paste(Country, year, year + 1, sep = \" \")) %>%\n relocate(Country) %>%\n select(-c(year,year_to_match))\n \ndf_combined\n\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74563020", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20592201/" ]
74,563,035
<p>I have a <code>Dictionary&lt;string, double&gt;</code>. I looped through the values to remove all the positive double values.</p> <p>I need to divide the remaining negative values together and then round it to 10 decimal points.</p> <pre class="lang-cs prettyprint-override"><code>double divisionSum = 1; foreach (var entry in dic.Values) { divisionSum /= entry; } </code></pre> <p>This doesn't work as 1 divided by a negative number does not return it's initial value for the first instance of division.</p> <p>For example, if the values of the Dictionary was -2, -4, -8, -5 I would want divisionSum to equal 0.0125. Also cannot use any Math() methods</p>
[ { "answer_id": 74563168, "author": "gilliduck", "author_id": 7129076, "author_profile": "https://Stackoverflow.com/users/7129076", "pm_score": 1, "selected": false, "text": "var foo = new List<double>{-1, -10, -3, -5};\n\ndouble result = foo[0];\nfor (int i = 1; i < foo.Count; i++)\n{\n result /= foo[i];\n}\n\nresult = Math.Round(result, 10);\nresult.Dump();\n Math var foo = new List<double>{-1, -10, -3, -5};\n\ndouble result = foo[0];\nfor (int i = 1; i < foo.Count; i++)\n{\n result /= foo[i];\n}\n\nresult = Convert.ToDouble(result.ToString(\"#.0000000000\"));\nresult.Dump();\n" }, { "answer_id": 74563461, "author": "Olivier Jacot-Descombes", "author_id": 880990, "author_profile": "https://Stackoverflow.com/users/880990", "pm_score": 0, "selected": false, "text": "1 double[] values = dic.Values.ToArray();\ndouble divisionSum = values[0];\nfor (int i = 1; i < values.Length; i++) {\n divisionSum /= values[i];\n}\n// divisionSum => 0.0125\n divisionSum" }, { "answer_id": 74563625, "author": "swatsonpicken", "author_id": 1185279, "author_profile": "https://Stackoverflow.com/users/1185279", "pm_score": 0, "selected": false, "text": "divisionSum var valuesList = dic.Values.ToList();\nvar divisionSum = valuesList[0];\n\nfor (var index = 1; index < valuesList.Count; index++)\n{\n divisionSum /= valuesList[index];\n}\n\ndivisionSum = Convert.ToDouble(divisionSum.ToString(\"#.0000000000\", CultureInfo.InvariantCulture));\n" }, { "answer_id": 74563931, "author": "Dmitry Bychenko", "author_id": 2319407, "author_profile": "https://Stackoverflow.com/users/2319407", "pm_score": 0, "selected": false, "text": "using System.Linq;\n\n...\n\n// Let me keep the name; result looks a better however\ndouble divisionSum = dic\n .Values\n .Where(item => item < 0) \n .DefaultIfEmpty(0.0) // put the default value here: 0, 1 or whatever \n .Aggregate((s, a) => s / a);\n firstTime double divisionSum = 0.0; // put default value here: 0, 1 or whatever\nbool firstTime = true;\n\nforeach (var item in dic.Values) {\n if (item < 0) {\n divisionSum = firstTime ? item : divisionSum / item;\n\n firstTime = false; \n }\n}\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74563035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20592230/" ]
74,563,042
<p>Mozilla <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/throw#throw_an_object" rel="nofollow noreferrer">says</a> that we can define an object and throw it.</p> <p>This way, we can encapsulate more than a simple string message and send it to the exception consumer (the <code>catch</code> block, or the <code>then</code> method of promises).</p> <p>However, I don't want to constantly define types in my JS code.</p> <p>Is it possible to throw anonymous objects?</p> <p>I tried <code>throw new Error({ firstKey: firstValue, secondKey: secondValue })</code> and it does not work. I get <code>[object Object]</code>.</p>
[ { "answer_id": 74591031, "author": "CertainPerformance", "author_id": 9515207, "author_profile": "https://Stackoverflow.com/users/9515207", "pm_score": 2, "selected": false, "text": "JSON.stringify cause const objForCause = {};\ntry {\n throw new Error(\n 'Something went wrong',\n { cause: { prop: 'val', obj: objForCause } }\n );\n} catch(err) {\n // Not all errors have causes\n // Ensure that it does before examining further\n if (err.cause) {\n console.log(err.cause);\n console.log(err.cause.obj === objForCause);\n }\n}" }, { "answer_id": 74591078, "author": "marco-a", "author_id": 2005038, "author_profile": "https://Stackoverflow.com/users/2005038", "pm_score": 2, "selected": true, "text": "try {\n throw \"a string\";\n} catch (error) {\n console.log(\"caught\", error)\n}\n\ntry {\n throw 10;\n} catch (error) {\n console.log(\"caught\", error)\n}\n\ntry {\n throw {a: 1, b: 2};\n} catch (error) {\n console.log(\"caught\", error)\n} Is it possible to throw anonymous objects?" }, { "answer_id": 74591276, "author": "innocent", "author_id": 8405085, "author_profile": "https://Stackoverflow.com/users/8405085", "pm_score": 0, "selected": false, "text": " const myobj={a:1,b:2};\n throw myobj;\n console.log(err);\n try {\n const myobj = {\n a: 1,\n b: 2\n };\n throw myobj;\n} catch (err) {\n console.log(err);\n}" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74563042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19390849/" ]
74,563,067
<p>is it possible to filter rows of one dataframe based on another dataframe?</p> <p>I have this 2 dataframe:</p> <pre><code>df_node &lt;- data.frame( id= c(&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d&quot;,&quot;e&quot;,&quot;f&quot;,&quot;g&quot;,&quot;h&quot;,&quot;i&quot;), group= c(1,1,1,2,2,2,3,3,3)) df_link &lt;- data.frame(from = c(&quot;a&quot;,&quot;d&quot;,&quot;f&quot;,&quot;i&quot;,&quot;b&quot;), to = c(&quot;d&quot;,&quot;f&quot;,&quot;i&quot;,&quot;b&quot;,&quot;h&quot;)) </code></pre> <p><a href="https://i.stack.imgur.com/FyvdZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FyvdZ.png" alt="enter image description here" /></a></p> <p>I would like to delete the lines with characters that are not present in the second dataframe, like this:</p> <p><a href="https://i.stack.imgur.com/tIALp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tIALp.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74563227, "author": "islem", "author_id": 11952767, "author_profile": "https://Stackoverflow.com/users/11952767", "pm_score": 2, "selected": false, "text": "df_node <- data.frame( id= c(\"a\",\"b\",\"c\",\"d\",\"e\",\"f\",\"g\",\"h\",\"i\"),\n group= c(1,1,1,2,2,2,3,3,3))\n\ndf_link <- data.frame(from = c(\"a\",\"d\",\"f\",\"i\",\"b\"),\n to = c(\"d\",\"f\",\"i\",\"b\",\"h\"))\n\n\nlibrary(dplyr)\ndf_result <- df_node%>%\n filter(id%in%c(df_link$from,df_link$to))\ndf_result\n# > df_result\n# id group\n# 1 a 1\n# 2 b 1\n# 3 d 2\n# 4 f 2\n# 5 h 3\n# 6 i 3\n" }, { "answer_id": 74563241, "author": "harre", "author_id": 4786466, "author_profile": "https://Stackoverflow.com/users/4786466", "pm_score": 1, "selected": false, "text": "semi_join library(dplyr)\n\ndf_node |> \n semi_join(tibble(id = c(df_link$from, df_link$to)))\n id group\n1 a 1\n2 b 1\n3 d 2\n4 f 2\n5 h 3\n6 i 3\n" }, { "answer_id": 74563294, "author": "denis", "author_id": 8053817, "author_profile": "https://Stackoverflow.com/users/8053817", "pm_score": 1, "selected": false, "text": "df_node[df_node$id %in% unlist(df_link),]\n\n id group\n1 a 1\n2 b 1\n4 d 2\n6 f 2\n8 h 3\n9 i 3\n library(dplyr)\n\ndf_uniqueID <- data.frame(id = unique(c(df_link$from,df_link$to)) )\nright_join(df_node,df_uniqueID)\n\nJoining, by = \"id\"\n id group\n1 a 1\n2 b 1\n3 d 2\n4 f 2\n5 h 3\n6 i 3\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74563067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20176942/" ]
74,563,091
<p>I am studying the difference between CISC and RISC recently, and I've encountered into the term &quot;Orthogonality&quot;. After doing some research, my understanding so far is that there are two &quot;axes&quot;, addressing modes &amp; operations, which are independent of each other, so it produces a maximum number of (#addressing modes * #operations) instructions in the ISA.</p> <p>For CISC machine, which is a register-memory architecture, operands may come from register or memory and RISC a register-register(or load-store) one on the contrary. So, what's the role of orthogonality playing in these two ISA? Is CISC more orthogonal than RISC or vice versa?</p> <p>As the wiki describes, &quot;Modern CPUs often simulate orthogonality in a preprocessing step before performing the actual tasks in a RISC-like core. This &quot;simulated orthogonality&quot; in general is a broader concept, encompassing the notions of decoupling and completeness in function libraries, like in the mathematical concept: an orthogonal function set is easy to use as a basis into expanded functions, ensuring that parts don’t affect another if we change one part.&quot; What does this paragraph mean? What is the preprocessing step, does it have anything to do with the microcode?</p> <p>Any explanation are appreciated! Thanks a lot!</p>
[ { "answer_id": 74564275, "author": "Peter Cordes", "author_id": 224132, "author_profile": "https://Stackoverflow.com/users/224132", "pm_score": 1, "selected": false, "text": "shl reg, cl movsx reg, r/m8 r/m16 movzx and si, 0x00ff [bp|bx] + [si|di] + disp0/8/16 lea eax, [ecx + ecx + 3] ldp stp ldrd mov shlx ebx, eax, r15d bpl spl sil dil pminub pminsw min max shufps pmaddwd add eax, [rdi]" }, { "answer_id": 74564276, "author": "Erik Eidt", "author_id": 471129, "author_profile": "https://Stackoverflow.com/users/471129", "pm_score": 0, "selected": false, "text": "orthogonal instruction set *p++ *--p addl2 addl3 a[i] = *p++ + b[j] a b i j p jal $sp $ra" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74563091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12193093/" ]
74,563,093
<p>This is something that I have to do daily and over time it started to be pain in the ***.</p> <p>I need to write a code which based on a value in Column A, copies values in columns B:I in the same row to another workbook. Source of the data will always be the same. I have the maximum of 30 workbooks/30 unique values in column A.</p> <p>If a value in cell A1 = &quot;Apples&quot;. I need to copy range B1:I1 to workbook called apples. If a value in cell A2 = &quot;Oranges&quot;, I need to copy range B2:I2 to workbook called oranges...</p> <p>and so on and so forth.</p> <p>Destination Workbooks are located in another folder. I need to find a last row in column A in destination workbook and insert my source range right after. I basically need to create new rows with the data I copy in.</p> <p>Any help will be greatly appreciated.</p> <p>Below is the code I tried to write myself, but unfortunately no luck. loop is only created for one workbook.</p> <p>EDIT.</p> <p>Values in the column A do not correspond with the names of the workbooks they should be copied in. Workbooks in Format .xlsx</p> <p>Columns A:I are the only columns in the source sheet.</p> <p>I will be copying from B:I in the source to A:H in the destination. All destination workbooks are formatted in the same way. While copying into destination workbooks, I need to insert extra rows and then copy the data in.</p> <p>I need to always copy into the first tab in destination workbook. All called &quot;All trades&quot;</p> <p>There will be one or more than one record (row) to be copied to each destination workbook.</p> <p>Many thanks,</p> <pre><code>Sub copying() Dim wsIn As Worksheet, ws4 As Workbook, ws5 As Workbook, ws6 As Workbook, ws7 As Workbook, ws8 As Workbook, ws9 As Workbook, ws10 As Workbook, ws11 As Workbook, ws12 As Workbook, ws13 As Workbook Dim ws14 As Workbook, ws15 As Workbook, ws16 As Workbook, ws17 As Workbook, ws18 As Workbook, ws19 As Workbook, ws20 As Workbook, ws21 As Workbook, ws22 As Workbook, ws23 As Workbook, ws24 As Workbook, ws25 As Workbook, ws26 As Workbook, ws27 As Workbook Dim wsE1 As Workbook, wsE2 As Workbook, wsE3 As Workbook, wsE4 As Workbook, wsE5 As Workbook, wsE6 As Workbook Dim wkExport As Workbook Dim fn4 As String, fn5 As String, fn6 As String, fn7 As String, fn8 As String, fn9 As String, fn10 As String, fn11 As String, fn12 As String, fn13 As String, fn14 As String, fn15 As String, fn16 As String, fn17 As String, fn18 As String, fn19 As String, fn20 As String Dim fn21 As String, fn22 As String, fn23 As String, fn24 As String, fn25 As String, fn26 As String, fn27 As String Dim fnE1 As String, fnE2 As String, fnE3 As String, fnE4 As String, fnE5 As String, fnE6 As String Set wsIn = ThisWorkbook.Worksheets(&quot;Ready_data&quot;) fn5 = ThisWorkbook.Path &amp; Application.PathSeparator &amp; &quot;workbook5.xlsx&quot; wsIn.Range(&quot;A2:I&quot; &amp; ws5.Rows.Count).Clear Dim lrowIn As Long lrowIn = wsIn.Range(&quot;A1&quot;).CurrentRegion.Rows.Count Dim lrowOut As Long Dim i As Long For i = 2 To lrowIn If wsIn.Range(&quot;A&quot; &amp; i).Value = &quot;workbook5&quot; Then Set wkExport = Workbooks.Open(fn5) lrowOut = ws5.Range(&quot;A1&quot;).CurrentRegion.Rows.Count + 1 wsIn.Range(&quot;B&quot; &amp; i &amp; &quot;:I&quot; &amp; i).Copy ws5.Cells(lrowOut, 1) End If Next iM End Sub </code></pre> <p>I tried a lot of youtube videos already and went through all the suggestions in stackoverflow but nothing is quite the same to what I need.</p>
[ { "answer_id": 74565505, "author": "SWETHA NAIR", "author_id": 20582745, "author_profile": "https://Stackoverflow.com/users/20582745", "pm_score": 0, "selected": false, "text": "Dim wsIn As Worksheet, ws4 As Workbook, ws5 As Workbook, ws6 As Workbook, ws7 As Workbook, ws8 As Workbook, ws9 As Workbook, ws10 As Workbook, ws11 As Workbook, ws12 As Workbook, ws13 As Workbook\nDim ws14 As Workbook, ws15 As Workbook, ws16 As Workbook, ws17 As Workbook, ws18 As Workbook, ws19 As Workbook, ws20 As Workbook, ws21 As Workbook, ws22 As Workbook, ws23 As Workbook, ws24 As Workbook, ws25 As Workbook, ws26 As Workbook, ws27 As Workbook\nDim wsE1 As Workbook, wsE2 As Workbook, wsE3 As Workbook, wsE4 As Workbook, wsE5 As Workbook, wsE6 As Workbook\n\nDim wkExport As Workbook\n\nDim fn4 As String, fn5 As String, fn6 As String, fn7 As String, fn8 As String, fn9 As String, fn10 As String, fn11 As String, fn12 As String, fn13 As String, fn14 As String, fn15 As String, fn16 As String, fn17 As String, fn18 As String, fn19 As String, fn20 As String\nDim fn21 As String, fn22 As String, fn23 As String, fn24 As String, fn25 As String, fn26 As String, fn27 As String\nDim fnE1 As String, fnE2 As String, fnE3 As String, fnE4 As String, fnE5 As String, fnE6 As String\n\nSet wsIn = ThisWorkbook.Worksheets(\"Ready_data\")\nfn5 = ThisWorkbook.Path & Application.PathSeparator & \"workbook5.xlsx\"\n\n\nwsIn.Range(\"A2:I\" & ws5.Rows.Count).Clear\n\nDim lrowIn As Long\nlrowIn = wsIn.Range(\"A1\").CurrentRegion.Rows.Count\nDim lrowOut As Long\nDim i As Long\n\nFor i = 2 To lrowIn\n If wsIn.Range(\"A\" & i).Value = \"workbook5\" Then\n Set wkExport = Workbooks.Open(fn5)\n lrowOut = ws5.Range(\"A1\").CurrentRegion.Rows.Count + 1\n wsIn.Range(\"B\" & i & \":I\" & i).Copy ws5.Cells(lrowOut, 1)\n\nEnd If\nNext iM\n \n" }, { "answer_id": 74565585, "author": "VBasic2008", "author_id": 9814069, "author_profile": "https://Stackoverflow.com/users/9814069", "pm_score": 1, "selected": false, "text": "Option Explicit\n\nSub UpdateTrades()\n \n ' Define constants.\n\n Const PROC_TITLE As String = \"Update Trades\"\n Const SRC_NAME As String = \"Read_Data\" ' get rid of the ugly '_'\n Const DST_PATH As String = \"C:\\TEST\"\n Const DST_NAME As String = \"All Trades\"\n Const DST_EXTENSION_PATTERN As String = \".xlsx\"\n \n ' Determine the destination path.\n \n Dim pSep As String: pSep = Application.PathSeparator\n Dim dFolderPath As String: dFolderPath = DST_PATH\n If Right(dFolderPath, 1) <> pSep Then dFolderPath = dFolderPath & pSep\n \n Dim dFolderName As String: dFolderName = Dir(dFolderPath, vbDirectory)\n If Len(dFolderName) = 0 Then\n MsgBox \"The destination path '\" & dFolderPath & \"' doesn't exist.\", _\n vbCritical, PROC_TITLE\n Exit Sub\n End If\n \n ' Write the source data to arrays.\n \n Dim swb As Workbook: Set swb = ThisWorkbook ' workbook containing this code\n Dim sws As Worksheet: Set sws = swb.Worksheets(SRC_NAME)\n \n Dim srg As Range, srCount As Long, cCount As Long\n \n With sws.Range(\"A1\").CurrentRegion\n srCount = .Rows.Count - 1 ' remove headers\n cCount = .Columns.Count - 1 ' remove lookup column\n Set srg = .Resize(srCount).Offset(1)\n End With\n \n Dim lData() As Variant: lData = srg.Columns(1).Value ' 1st column\n Dim sData() As Variant: sData = srg.Resize(, cCount).Offset(, 1).Value\n \n ' Write the unique data from the lookup array to a dictionary.\n ' The 'keys' will hold the values while the 'items' will hold\n ' a collection of the row numbers.\n \n Dim dict As Object: Set dict = CreateObject(\"Scripting.Dictionary\")\n dict.CompareMode = vbTextCompare\n \n Dim sr As Long, sString As String\n \n For sr = 1 To srCount\n sString = CStr(lData(sr, 1))\n If Len(sString) > 0 Then\n If Not dict.Exists(sString) Then Set dict(sString) = New Collection\n dict(sString).Add sr ' row to collection\n End If\n Next sr\n \n Erase lData\n \n Application.ScreenUpdating = False\n \n ' Write the values from the source array and the dictionary\n ' to the destination array, write to, save and close the destination files.\n \n Dim dwb As Workbook, dws As Worksheet, drg As Range\n Dim dData() As Variant, sKey As Variant, sItem As Variant\n Dim c As Long, dr As Long, drCount As Long\n Dim dPattern As String, dName As String, dPath As String\n \n ' Loop over the keys of the dictionary.\n For Each sKey In dict.Keys\n ' Determine the existence of a destination file.\n dPattern = dFolderPath & \"*\" & sKey & \"*\" & DST_EXTENSION_PATTERN\n dName = Dir(dPattern)\n If Len(dName) > 0 Then ' the destination file exists\n ' Define the destination array.\n drCount = dict(sKey).Count\n ReDim dData(1 To drCount, 1 To cCount)\n dr = 0 ' reset destination row counter\n ' Loop over the row numbers in the current collection.\n For Each sItem In dict(sKey)\n dr = dr + 1\n ' Write the current row from the source to the destination.\n For c = 1 To cCount\n dData(dr, c) = sData(sItem, c)\n Next c\n Next sItem\n ' Open, write from the destination array, save and close.\n dPath = dFolderPath & dName\n Set dwb = Workbooks.Open(dPath)\n Set dws = dwb.Worksheets(DST_NAME)\n With dws.Range(\"A1\").CurrentRegion\n Set drg = .Cells(1).Offset(.Rows.Count).Resize(drCount, cCount)\n drg.Value = dData\n End With\n dwb.Close SaveChanges:=True\n Else ' the destination file doesn't exist; print an alert\n Debug.Print \"The pattern '\" & dPattern & \"' didn't return a file.\"\n End If\n Next sKey\n \n Application.ScreenUpdating = True\n\n ' Inform. \n\n MsgBox \"Trades updated.\", vbInformation, PROC_TITLE\n \nEnd Sub\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74563093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7661664/" ]
74,563,108
<pre><code>using System.Collections; using System.Collections.Generic; using System.Diagnostics; public class PlayerMovement : MonoBehaviour { [SerializeField] private float movementSpeed =100f; private float verticalDirection; private Rigidbody rb; private Animator animator; // Start is called before the first frame update public bool IsMoving() { return rb.velocity.magnitude &gt; 0.1f; } void Awake() { rb=GetComponent&lt;Rigidbody&gt;(); animator = GetComponentInChildren&lt;Animator&gt;(); } private void Update() { verticalDirection=Input.GetAxis(&quot;Vertical&quot;); verticalDirection=Mathf.Clamp(verticalDirection,0,1); animator.SetFloat(&quot;Speed&quot;,verticalDirection); } // Update is called once per frame void FixedUpdate() { rb.velocity=Vector3.forward*verticalDirection*movementSpeed*Time.fixedDeltaTime; } } Error1: Assets\Scripts\PlayerMovement.cs(4,31): error CS0246: The type or namespace name 'MonoBehaviour' could not be found (are you missing a using directive or an assembly reference?) Error2: Assets\Scripts\PlayerMovement.cs(10,13): error CS0246: The type or namespace name 'Rigidbody' could not be found (are you missing a using directive or an assembly reference?) Error3: Assets\Scripts\PlayerMovement.cs(12,13): error CS0246: The type or namespace name 'Animator' could not be found (are you missing a using directive or an assembly reference?) Error4: Assets\Scripts\PlayerMovement.cs(12,13): error CS0246: The type or namespace name 'Animator' could not be found (are you missing a using directive or an assembly reference?) Error5: Assets\Scripts\PlayerMovement.cs(6,6): error CS0246: The type or namespace name 'SerializeFieldAttribute' could not be found (are you missing a using directive or an assembly reference?) Error6: Assets\Scripts\PlayerMovement.cs(6,6): error CS0246: The type or namespace name 'SerializeField' could not be found (are you missing a using directive or an assembly reference?) Error7: Assets\Scripts\Robot.cs(20,13): error CS0246: The type or namespace name 'PlayMovement' could not be found (are you missing a using directive or an assembly reference?) It is my other code using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Diagnostics; //using System.Runtime.Serialization; //using UnityEngine.UI; //using System.web.Helpers; enum RobotStates {Counting,Inspecting} public class Robot : MonoBehaviour { [SerializeField] private float startInspectionTime = 2f; [SerializeField] private AudioSource jingleSource; private float currentInspectionTime; private RobotStates currentState = RobotStates.Counting; private Animator animator; private PlayMovement player; // Start is called before the first frame update void Start() { player=FindObjectType&lt;PlayerMovement&gt;(); animator=GetComponentInChildren&lt;Animator&gt;(); currentInspectionTime = startInspectionTime; } // Update is called once per frame void Update() { StateMachine(); } private void StateMachine() { switch(currentState) { case RobotStates.Counting: Count(); break; case RobotStates.Inspecting: Inspect(); break; default: break; } } private void Count() { if (!jingleSource.isPlaying){ animator.SetTrigger(&quot;Look&quot;); currentState=RobotStates.Inspecting; } } private void Inspect() { if(currentInspectionTime&gt;0) { currentInspectionTime -=Time.deltaTime; if (player.IsMoving()) { Destroy(player.gameObject); } } else { currentInspectionTime=startInspectionTime; animator.SetTrigger(&quot;Look&quot;); jingleSource.Play(); currentState=RobotStates.Counting; } } } </code></pre> <p>I have 7 error about CS0246. I used all namespace whatever I can use but it does not work. I checked the briket and semicolon all of them but i am not sure why i get error. I used **</p> <pre><code>using UnityEngine; using UnityEngine.Video; using UnityEngine.UI; using UnityEditor; using System.Diagnostics; </code></pre> <p>** Those namespace but it does not work please help me............ **Please note the parenthesis which are causing the issue I have labelled Error Parethesis however I am not entirely sure these are causing the overall issue.</p>
[ { "answer_id": 74565505, "author": "SWETHA NAIR", "author_id": 20582745, "author_profile": "https://Stackoverflow.com/users/20582745", "pm_score": 0, "selected": false, "text": "Dim wsIn As Worksheet, ws4 As Workbook, ws5 As Workbook, ws6 As Workbook, ws7 As Workbook, ws8 As Workbook, ws9 As Workbook, ws10 As Workbook, ws11 As Workbook, ws12 As Workbook, ws13 As Workbook\nDim ws14 As Workbook, ws15 As Workbook, ws16 As Workbook, ws17 As Workbook, ws18 As Workbook, ws19 As Workbook, ws20 As Workbook, ws21 As Workbook, ws22 As Workbook, ws23 As Workbook, ws24 As Workbook, ws25 As Workbook, ws26 As Workbook, ws27 As Workbook\nDim wsE1 As Workbook, wsE2 As Workbook, wsE3 As Workbook, wsE4 As Workbook, wsE5 As Workbook, wsE6 As Workbook\n\nDim wkExport As Workbook\n\nDim fn4 As String, fn5 As String, fn6 As String, fn7 As String, fn8 As String, fn9 As String, fn10 As String, fn11 As String, fn12 As String, fn13 As String, fn14 As String, fn15 As String, fn16 As String, fn17 As String, fn18 As String, fn19 As String, fn20 As String\nDim fn21 As String, fn22 As String, fn23 As String, fn24 As String, fn25 As String, fn26 As String, fn27 As String\nDim fnE1 As String, fnE2 As String, fnE3 As String, fnE4 As String, fnE5 As String, fnE6 As String\n\nSet wsIn = ThisWorkbook.Worksheets(\"Ready_data\")\nfn5 = ThisWorkbook.Path & Application.PathSeparator & \"workbook5.xlsx\"\n\n\nwsIn.Range(\"A2:I\" & ws5.Rows.Count).Clear\n\nDim lrowIn As Long\nlrowIn = wsIn.Range(\"A1\").CurrentRegion.Rows.Count\nDim lrowOut As Long\nDim i As Long\n\nFor i = 2 To lrowIn\n If wsIn.Range(\"A\" & i).Value = \"workbook5\" Then\n Set wkExport = Workbooks.Open(fn5)\n lrowOut = ws5.Range(\"A1\").CurrentRegion.Rows.Count + 1\n wsIn.Range(\"B\" & i & \":I\" & i).Copy ws5.Cells(lrowOut, 1)\n\nEnd If\nNext iM\n \n" }, { "answer_id": 74565585, "author": "VBasic2008", "author_id": 9814069, "author_profile": "https://Stackoverflow.com/users/9814069", "pm_score": 1, "selected": false, "text": "Option Explicit\n\nSub UpdateTrades()\n \n ' Define constants.\n\n Const PROC_TITLE As String = \"Update Trades\"\n Const SRC_NAME As String = \"Read_Data\" ' get rid of the ugly '_'\n Const DST_PATH As String = \"C:\\TEST\"\n Const DST_NAME As String = \"All Trades\"\n Const DST_EXTENSION_PATTERN As String = \".xlsx\"\n \n ' Determine the destination path.\n \n Dim pSep As String: pSep = Application.PathSeparator\n Dim dFolderPath As String: dFolderPath = DST_PATH\n If Right(dFolderPath, 1) <> pSep Then dFolderPath = dFolderPath & pSep\n \n Dim dFolderName As String: dFolderName = Dir(dFolderPath, vbDirectory)\n If Len(dFolderName) = 0 Then\n MsgBox \"The destination path '\" & dFolderPath & \"' doesn't exist.\", _\n vbCritical, PROC_TITLE\n Exit Sub\n End If\n \n ' Write the source data to arrays.\n \n Dim swb As Workbook: Set swb = ThisWorkbook ' workbook containing this code\n Dim sws As Worksheet: Set sws = swb.Worksheets(SRC_NAME)\n \n Dim srg As Range, srCount As Long, cCount As Long\n \n With sws.Range(\"A1\").CurrentRegion\n srCount = .Rows.Count - 1 ' remove headers\n cCount = .Columns.Count - 1 ' remove lookup column\n Set srg = .Resize(srCount).Offset(1)\n End With\n \n Dim lData() As Variant: lData = srg.Columns(1).Value ' 1st column\n Dim sData() As Variant: sData = srg.Resize(, cCount).Offset(, 1).Value\n \n ' Write the unique data from the lookup array to a dictionary.\n ' The 'keys' will hold the values while the 'items' will hold\n ' a collection of the row numbers.\n \n Dim dict As Object: Set dict = CreateObject(\"Scripting.Dictionary\")\n dict.CompareMode = vbTextCompare\n \n Dim sr As Long, sString As String\n \n For sr = 1 To srCount\n sString = CStr(lData(sr, 1))\n If Len(sString) > 0 Then\n If Not dict.Exists(sString) Then Set dict(sString) = New Collection\n dict(sString).Add sr ' row to collection\n End If\n Next sr\n \n Erase lData\n \n Application.ScreenUpdating = False\n \n ' Write the values from the source array and the dictionary\n ' to the destination array, write to, save and close the destination files.\n \n Dim dwb As Workbook, dws As Worksheet, drg As Range\n Dim dData() As Variant, sKey As Variant, sItem As Variant\n Dim c As Long, dr As Long, drCount As Long\n Dim dPattern As String, dName As String, dPath As String\n \n ' Loop over the keys of the dictionary.\n For Each sKey In dict.Keys\n ' Determine the existence of a destination file.\n dPattern = dFolderPath & \"*\" & sKey & \"*\" & DST_EXTENSION_PATTERN\n dName = Dir(dPattern)\n If Len(dName) > 0 Then ' the destination file exists\n ' Define the destination array.\n drCount = dict(sKey).Count\n ReDim dData(1 To drCount, 1 To cCount)\n dr = 0 ' reset destination row counter\n ' Loop over the row numbers in the current collection.\n For Each sItem In dict(sKey)\n dr = dr + 1\n ' Write the current row from the source to the destination.\n For c = 1 To cCount\n dData(dr, c) = sData(sItem, c)\n Next c\n Next sItem\n ' Open, write from the destination array, save and close.\n dPath = dFolderPath & dName\n Set dwb = Workbooks.Open(dPath)\n Set dws = dwb.Worksheets(DST_NAME)\n With dws.Range(\"A1\").CurrentRegion\n Set drg = .Cells(1).Offset(.Rows.Count).Resize(drCount, cCount)\n drg.Value = dData\n End With\n dwb.Close SaveChanges:=True\n Else ' the destination file doesn't exist; print an alert\n Debug.Print \"The pattern '\" & dPattern & \"' didn't return a file.\"\n End If\n Next sKey\n \n Application.ScreenUpdating = True\n\n ' Inform. \n\n MsgBox \"Trades updated.\", vbInformation, PROC_TITLE\n \nEnd Sub\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74563108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18422952/" ]
74,563,134
<p>I added the firebase auth package then got an error in the ios podfile</p> <p>[!] CocoaPods could not find compatible versions for pod &quot;Firebase/Auth&quot;: In Podfile: Firebase/Auth</p> <pre><code>firebase_auth (from `.symlinks/plugins/firebase_auth/ios`) was resolved to 0.0.1, which depends on Firebase/Auth (~&gt; 6.3) </code></pre> <p>CocoaPods could not find compatible versions for pod &quot;GoogleUtilities/Environment&quot;: In Podfile: firebase_auth (from <code>.symlinks/plugins/firebase_auth/ios</code>) was resolved to 0.0.1, which depends on Firebase/Auth (~&gt; 6.3) was resolved to 6.3.0, which depends on FirebaseAuth (~&gt; 6.1.2) was resolved to 6.1.2, which depends on GoogleUtilities/Environment (~&gt; 6.2)</p> <pre><code>google_mlkit_face_detection (from `.symlinks/plugins/google_mlkit_face_detection/ios`) was resolved to 0.4.0, which depends on GoogleMLKit/FaceDetection (~&gt; 3.1.0) was resolved to 3.1.0, which depends on MLKitFaceDetection (~&gt; 2.1.0) was resolved to 2.1.0, which depends on MLKitCommon (~&gt; 7.0) was resolved to 7.0.0, which depends on GoogleDataTransport (~&gt; 9.0) was resolved to 9.1.2, which depends on GoogleUtilities/Environment (~&gt; 7.2) </code></pre> <p>CocoaPods could not find compatible versions for pod &quot;MLKitCommon&quot;: In Podfile: google_mlkit_digital_ink_recognition (from <code>.symlinks/plugins/google_mlkit_digital_ink_recognition/ios</code>) was resolved to 0.5.0, which depends on GoogleMLKit/DigitalInkRecognition (~&gt; 3.1.0) was resolved to 3.1.0, which depends on MLKitDigitalInkRecognition (~&gt; 2.1.0) was resolved to 2.1.0, which depends on MLKitMDD (~&gt; 4.1) was resolved to 4.2.0, which depends on MLKitCommon (~&gt; 8.0)</p> <pre><code>google_mlkit_face_detection (from `.symlinks/plugins/google_mlkit_face_detection/ios`) was resolved to 0.4.0, which depends on GoogleMLKit/FaceDetection (~&gt; 3.1.0) was resolved to 3.1.0, which depends on GoogleMLKit/MLKitCore (= 3.1.0) was resolved to 3.1.0, which depends on MLKitCommon (~&gt; 7.0.0) google_mlkit_face_detection (from `.symlinks/plugins/google_mlkit_face_detection/ios`) was resolved to 0.4.0, which depends on GoogleMLKit/FaceDetection (~&gt; 3.1.0) was resolved to 3.1.0, which depends on MLKitFaceDetection (~&gt; 2.1.0) was resolved to 2.1.0, which depends on MLKitCommon (~&gt; 7.0) </code></pre> <p>CocoaPods could not find compatible versions for pod &quot;MLKitLanguageID&quot;: In Podfile: google_mlkit_language_id (from <code>.symlinks/plugins/google_mlkit_language_id/ios</code>) was resolved to 0.4.0, which depends on GoogleMLKit/LanguageID (~&gt; 3.1.0) was resolved to 3.1.0, which depends on MLKitLanguageID (~&gt; 3.1.0)</p> <pre><code>google_mlkit_smart_reply (from `.symlinks/plugins/google_mlkit_smart_reply/ios`) was resolved to 0.4.0, which depends on GoogleMLKit/SmartReply (~&gt; 3.1.0) was resolved to 3.1.0, which depends on MLKitSmartReply (~&gt; 2.1.0) was resolved to 2.1.0, which depends on MLKitLanguageID (~&gt; 3.1) </code></pre> <p>CocoaPods could not find compatible versions for pod &quot;MLKitTextRecognitionCommon&quot;: In Podfile: google_mlkit_text_recognition (from <code>.symlinks/plugins/google_mlkit_text_recognition/ios</code>) was resolved to 0.4.0, which depends on GoogleMLKit/TextRecognition (~&gt; 3.1.0) was resolved to 3.1.0, which depends on MLKitTextRecognition (~&gt; 1.4.0-beta5) was resolved to 1.4.0-beta5, which depends on MLKitTextRecognitionCommon (= 1.0.0-beta5)</p> <pre><code>google_mlkit_text_recognition (from `.symlinks/plugins/google_mlkit_text_recognition/ios`) was resolved to 0.4.0, which depends on GoogleMLKit/TextRecognitionJapanese (~&gt; 3.1.0) was resolved to 3.1.0, which depends on MLKitTextRecognitionJapanese (~&gt; 1.0.0-beta5) was resolved to 1.0.0-beta6, which depends on MLKitTextRecognitionCommon (= 1.0.0-beta6) </code></pre> <p>CocoaPods could not find compatible versions for pod &quot;MLKitVision&quot;: In Podfile: google_mlkit_commons (from <code>.symlinks/plugins/google_mlkit_commons/ios</code>) was resolved to 0.2.0, which depends on MLKitVision</p> <pre><code>google_mlkit_face_detection (from `.symlinks/plugins/google_mlkit_face_detection/ios`) was resolved to 0.4.0, which depends on GoogleMLKit/FaceDetection (~&gt; 3.1.0) was resolved to 3.1.0, which depends on MLKitFaceDetection (~&gt; 2.1.0) was resolved to 2.1.0, which depends on MLKitVision (~&gt; 4.1) google_mlkit_object_detection (from `.symlinks/plugins/google_mlkit_object_detection/ios`) was resolved to 0.5.0, which depends on GoogleMLKit/ObjectDetectionCustom (~&gt; 3.1.0) was resolved to 3.1.0, which depends on MLKitObjectDetectionCustom (~&gt; 2.1.0) was resolved to 2.1.0, which depends on MLKitObjectDetectionCommon (~&gt; 4.1) was resolved to 4.2.0, which depends on MLKitVision (~&gt; 4.2) </code></pre> <p>CocoaPods could not find compatible versions for pod &quot;MLKitXenoCommon&quot;: In Podfile: google_mlkit_pose_detection (from <code>.symlinks/plugins/google_mlkit_pose_detection/ios</code>) was resolved to 0.4.0, which depends on GoogleMLKit/PoseDetection (~&gt; 3.1.0) was resolved to 3.1.0, which depends on MLKitPoseDetection (~&gt; 1.0.0-beta9) was resolved to 1.0.0-beta10, which depends on MLKitXenoCommon (= 1.0.0-beta10)</p> <pre><code>google_mlkit_pose_detection (from `.symlinks/plugins/google_mlkit_pose_detection/ios`) was resolved to 0.4.0, which depends on GoogleMLKit/PoseDetectionAccurate (~&gt; 3.1.0) was resolved to 3.1.0, which depends on MLKitPoseDetectionAccurate (~&gt; 1.0.0-beta9) was resolved to 1.0.0-beta9, which depends on MLKitXenoCommon (= 1.0.0-beta9) </code></pre>
[ { "answer_id": 74565505, "author": "SWETHA NAIR", "author_id": 20582745, "author_profile": "https://Stackoverflow.com/users/20582745", "pm_score": 0, "selected": false, "text": "Dim wsIn As Worksheet, ws4 As Workbook, ws5 As Workbook, ws6 As Workbook, ws7 As Workbook, ws8 As Workbook, ws9 As Workbook, ws10 As Workbook, ws11 As Workbook, ws12 As Workbook, ws13 As Workbook\nDim ws14 As Workbook, ws15 As Workbook, ws16 As Workbook, ws17 As Workbook, ws18 As Workbook, ws19 As Workbook, ws20 As Workbook, ws21 As Workbook, ws22 As Workbook, ws23 As Workbook, ws24 As Workbook, ws25 As Workbook, ws26 As Workbook, ws27 As Workbook\nDim wsE1 As Workbook, wsE2 As Workbook, wsE3 As Workbook, wsE4 As Workbook, wsE5 As Workbook, wsE6 As Workbook\n\nDim wkExport As Workbook\n\nDim fn4 As String, fn5 As String, fn6 As String, fn7 As String, fn8 As String, fn9 As String, fn10 As String, fn11 As String, fn12 As String, fn13 As String, fn14 As String, fn15 As String, fn16 As String, fn17 As String, fn18 As String, fn19 As String, fn20 As String\nDim fn21 As String, fn22 As String, fn23 As String, fn24 As String, fn25 As String, fn26 As String, fn27 As String\nDim fnE1 As String, fnE2 As String, fnE3 As String, fnE4 As String, fnE5 As String, fnE6 As String\n\nSet wsIn = ThisWorkbook.Worksheets(\"Ready_data\")\nfn5 = ThisWorkbook.Path & Application.PathSeparator & \"workbook5.xlsx\"\n\n\nwsIn.Range(\"A2:I\" & ws5.Rows.Count).Clear\n\nDim lrowIn As Long\nlrowIn = wsIn.Range(\"A1\").CurrentRegion.Rows.Count\nDim lrowOut As Long\nDim i As Long\n\nFor i = 2 To lrowIn\n If wsIn.Range(\"A\" & i).Value = \"workbook5\" Then\n Set wkExport = Workbooks.Open(fn5)\n lrowOut = ws5.Range(\"A1\").CurrentRegion.Rows.Count + 1\n wsIn.Range(\"B\" & i & \":I\" & i).Copy ws5.Cells(lrowOut, 1)\n\nEnd If\nNext iM\n \n" }, { "answer_id": 74565585, "author": "VBasic2008", "author_id": 9814069, "author_profile": "https://Stackoverflow.com/users/9814069", "pm_score": 1, "selected": false, "text": "Option Explicit\n\nSub UpdateTrades()\n \n ' Define constants.\n\n Const PROC_TITLE As String = \"Update Trades\"\n Const SRC_NAME As String = \"Read_Data\" ' get rid of the ugly '_'\n Const DST_PATH As String = \"C:\\TEST\"\n Const DST_NAME As String = \"All Trades\"\n Const DST_EXTENSION_PATTERN As String = \".xlsx\"\n \n ' Determine the destination path.\n \n Dim pSep As String: pSep = Application.PathSeparator\n Dim dFolderPath As String: dFolderPath = DST_PATH\n If Right(dFolderPath, 1) <> pSep Then dFolderPath = dFolderPath & pSep\n \n Dim dFolderName As String: dFolderName = Dir(dFolderPath, vbDirectory)\n If Len(dFolderName) = 0 Then\n MsgBox \"The destination path '\" & dFolderPath & \"' doesn't exist.\", _\n vbCritical, PROC_TITLE\n Exit Sub\n End If\n \n ' Write the source data to arrays.\n \n Dim swb As Workbook: Set swb = ThisWorkbook ' workbook containing this code\n Dim sws As Worksheet: Set sws = swb.Worksheets(SRC_NAME)\n \n Dim srg As Range, srCount As Long, cCount As Long\n \n With sws.Range(\"A1\").CurrentRegion\n srCount = .Rows.Count - 1 ' remove headers\n cCount = .Columns.Count - 1 ' remove lookup column\n Set srg = .Resize(srCount).Offset(1)\n End With\n \n Dim lData() As Variant: lData = srg.Columns(1).Value ' 1st column\n Dim sData() As Variant: sData = srg.Resize(, cCount).Offset(, 1).Value\n \n ' Write the unique data from the lookup array to a dictionary.\n ' The 'keys' will hold the values while the 'items' will hold\n ' a collection of the row numbers.\n \n Dim dict As Object: Set dict = CreateObject(\"Scripting.Dictionary\")\n dict.CompareMode = vbTextCompare\n \n Dim sr As Long, sString As String\n \n For sr = 1 To srCount\n sString = CStr(lData(sr, 1))\n If Len(sString) > 0 Then\n If Not dict.Exists(sString) Then Set dict(sString) = New Collection\n dict(sString).Add sr ' row to collection\n End If\n Next sr\n \n Erase lData\n \n Application.ScreenUpdating = False\n \n ' Write the values from the source array and the dictionary\n ' to the destination array, write to, save and close the destination files.\n \n Dim dwb As Workbook, dws As Worksheet, drg As Range\n Dim dData() As Variant, sKey As Variant, sItem As Variant\n Dim c As Long, dr As Long, drCount As Long\n Dim dPattern As String, dName As String, dPath As String\n \n ' Loop over the keys of the dictionary.\n For Each sKey In dict.Keys\n ' Determine the existence of a destination file.\n dPattern = dFolderPath & \"*\" & sKey & \"*\" & DST_EXTENSION_PATTERN\n dName = Dir(dPattern)\n If Len(dName) > 0 Then ' the destination file exists\n ' Define the destination array.\n drCount = dict(sKey).Count\n ReDim dData(1 To drCount, 1 To cCount)\n dr = 0 ' reset destination row counter\n ' Loop over the row numbers in the current collection.\n For Each sItem In dict(sKey)\n dr = dr + 1\n ' Write the current row from the source to the destination.\n For c = 1 To cCount\n dData(dr, c) = sData(sItem, c)\n Next c\n Next sItem\n ' Open, write from the destination array, save and close.\n dPath = dFolderPath & dName\n Set dwb = Workbooks.Open(dPath)\n Set dws = dwb.Worksheets(DST_NAME)\n With dws.Range(\"A1\").CurrentRegion\n Set drg = .Cells(1).Offset(.Rows.Count).Resize(drCount, cCount)\n drg.Value = dData\n End With\n dwb.Close SaveChanges:=True\n Else ' the destination file doesn't exist; print an alert\n Debug.Print \"The pattern '\" & dPattern & \"' didn't return a file.\"\n End If\n Next sKey\n \n Application.ScreenUpdating = True\n\n ' Inform. \n\n MsgBox \"Trades updated.\", vbInformation, PROC_TITLE\n \nEnd Sub\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74563134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20592175/" ]
74,563,149
<p>Let's say I have an array like this:</p> <pre><code>[1,5, 2, 6, 6.7, 8, 10] </code></pre> <p>I want to lower down the numbers that are larger than n. So for example if n is 6, the array will look like this:</p> <pre><code>[1,5, 2, 6, 6, 6, 6] </code></pre> <p>I have tried a solution using numpy.vectorize:</p> <pre><code>lower_down = lambda x : min(6,x) lower_down = numpy.vectorize(lower_down) </code></pre> <p>It works but it's too slow. How can I make this faster? Is there a numpy function for achieving the same result?</p>
[ { "answer_id": 74563213, "author": "svfat", "author_id": 2419628, "author_profile": "https://Stackoverflow.com/users/2419628", "pm_score": 2, "selected": false, "text": ">>> numpy.minimum(1, [1, 2])\narray([1, 1])\n >>> numpy.maximum(2, [1, 2])\narray([2, 2])\n >>> np.clip([1, 2, 3, 4], 2, 3)\narray([2, 2, 3, 3])\n" }, { "answer_id": 74563238, "author": "Dan Getz", "author_id": 3004881, "author_profile": "https://Stackoverflow.com/users/3004881", "pm_score": 3, "selected": true, "text": "minimum >>> np.minimum(6, [1,5, 2, 6, 6.7, 8, 10])\narray([1., 5., 2., 6., 6., 6., 6.])\n" }, { "answer_id": 74563269, "author": "Bruno Cavalcante", "author_id": 13938779, "author_profile": "https://Stackoverflow.com/users/13938779", "pm_score": 0, "selected": false, "text": "import numpy as np\n\ndata = np.array([1,5, 2, 6, 6,7, 8, 10])\n\ndata[data >6 ] = 6\n" }, { "answer_id": 74563270, "author": "geofisue", "author_id": 19283956, "author_profile": "https://Stackoverflow.com/users/19283956", "pm_score": 0, "selected": false, "text": "import numpy as np\n\narray = [1,5, 2, 6, 6.7, 8, 10]\narray = np.array(array)\n\narray[array >= 6] = 6\n\nnew_array = array\n\nprint(new_array)\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74563149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14465065/" ]
74,563,189
<p>I am trying to split a string so that I can separate it depending on a pattern. I'm having trouble getting the correct regex pattern to do so. I also need to insert the results into an array of objects. Perhaps by using a regex pattern, the string can be split into a resulting array object to achieve the objective. Note that the regex pattern must not discriminate between <code>-</code> or <code>--</code>. Or is there any better way to do this?</p> <p>I tried using string <code>split()</code> method, but to no avail. I am trying to achieve the result below:</p> <pre><code>const example1 = `--filename test_layer_123.png`; const example2 = `--code 1 --level critical -info &quot;This is some info&quot;`; const result1 = [{ name: &quot;--filename&quot;, value: &quot;test_layer_123.png&quot; }]; const result2 = [ { name: &quot;--code&quot;, value: &quot;1&quot; }, { name: &quot;--level&quot;, value: &quot;critical&quot; }, { name: &quot;-info&quot;, value: &quot;This is some info&quot; }, ]; </code></pre>
[ { "answer_id": 74567660, "author": "Heo", "author_id": 14674434, "author_profile": "https://Stackoverflow.com/users/14674434", "pm_score": 2, "selected": false, "text": "/((?:--|-)\\w+)\\s+\"?([^-\"]+)\"?/g function matchAllCommands(text, pattern){\n let new_array = [];\n let matches = text.matchAll(pattern);\n for (const match of matches){\n new_array.push({name: match.groups.name, value: match.groups.value});\n }\n return new_array;\n}\n\nlet RegexPattern = /(?<name>(?:--|-)\\w+)\\s+\"?(?<value>[^-\"]+)\"?/g;\nlet text = '--code 1 --level critical -info \"This is some info\"';\n\nconsole.log(matchAllCommands(text, RegexPattern));" }, { "answer_id": 74579136, "author": "Peter Thoeny", "author_id": 7475450, "author_profile": "https://Stackoverflow.com/users/7475450", "pm_score": 0, "selected": false, "text": "function getArgs(str) {\n return str.split(/(?= --?\\w+ )/).map(str => {\n let m = str.match(/^ ?([^ ]+) (.*)$/);\n return {\n name: m[1],\n value: m[2].replace(/^\"(.*)\"$/, '$1')\n };\n });\n}\n\n[\n '--filename test_layer_123.png', // example1\n '--code 1 --level critical -info \"This is some info\"' // example2\n].forEach(str => {\n var result = getArgs(str);\n console.log(JSON.stringify(result, null, ' '));\n}); (?= --?\\w+ ) ^ ? ([^ ]+) (.*) $" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74563189", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20581974/" ]
74,563,231
<p>So I have a page (let's call it Page1) that use is loaded dynamically via React.lazy that uses several reusable components and another page (Page2) that uses some of those reusable components, this page being as well loaded dynamically.</p> <p>My question would be, is there a way to prevent Page2 to load those reusable components again?</p> <p>When I analyze the generated final bundle I see that both pages load the reusable components individually and I think ideally would be to just load them once and each new dynamically loaded page that uses those reusable components shouldn't fetch them again.</p>
[ { "answer_id": 74660975, "author": "hakkikonu", "author_id": 1848929, "author_profile": "https://Stackoverflow.com/users/1848929", "pm_score": 1, "selected": false, "text": "import React, { Suspense } from 'react';\nimport { BrowserRouter as Router, Switch, Route } from 'react-router-dom';\n\nconst Page1 = React.lazy(() => import('./Page1'));\nconst Page2 = React.lazy(() => import('./Page2'));\n\nconst FallbackComponent = () => <div>Loading...</div>;\n\nconst App = () => (\n <Router>\n <Switch>\n <Route exact path=\"/page1\">\n <Suspense fallback={<FallbackComponent />}>\n <Page1 />\n </Suspense>\n </Route>\n <Route exact path=\"/page2\">\n <Suspense fallback={<FallbackComponent />}>\n <Page2 />\n </Suspense>\n </Route>\n </Switch>\n </Router>\n);\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74563231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12469963/" ]
74,563,281
<p>I have a json file which has the below content. I want to iterate through each item (using foreach loop) in Powershell. How can I do it?</p> <pre><code>{ &quot;abc&quot;: { &quot;isSecret&quot;: null, &quot;value&quot;: &quot;'167401'&quot; }, &quot;dar&quot;: { &quot;isSecret&quot;: null, &quot;value&quot;: &quot;8980&quot; }, &quot;hgt&quot;: { &quot;isSecret&quot;: null, &quot;value&quot;: &quot;893240&quot; }, &quot;newvar1&quot;: { &quot;isSecret&quot;: null, &quot;value&quot;: &quot;newvalue1&quot; }, &quot;var&quot;: { &quot;isSecret&quot;: null, &quot;value&quot;: &quot;1230&quot; } } </code></pre>
[ { "answer_id": 74563495, "author": "TZHX", "author_id": 519348, "author_profile": "https://Stackoverflow.com/users/519348", "pm_score": 1, "selected": true, "text": "$input = @'\n<your input here>\n'@\n\n$json = $input | ConvertFrom-Json\n\nforeach($item in $json.PSObject.Properties)\n{\n Write-Output $item.Name \n Write-Output $item.Value.isSecret\n Write-Output $item.Value.value\n}\n abc\n'167401'\ndar\n8980\nhgt\n893240\nnewvar1\nnewvalue1\nvar\n1230\n isSecret" }, { "answer_id": 74563745, "author": "iRon", "author_id": 1701026, "author_profile": "https://Stackoverflow.com/users/1701026", "pm_score": 1, "selected": false, "text": "$Data = $Json |ConvertFrom-Json\n$Data.PSObject.Properties.Value\n\nisSecret value\n-------- -----\n '167401'\n 8980\n 893240\n newvalue1\n 1230\n $Data.PSObject.Properties.Value.ForEach{\n Write-Host 'isSecret:' $_.isSecret\n Write-Host 'Value:' $_.Value\n}\n" }, { "answer_id": 74563941, "author": "js2010", "author_id": 6654942, "author_profile": "https://Stackoverflow.com/users/6654942", "pm_score": 0, "selected": false, "text": "cat file.json | convertfrom-json -AsHashtable\n\nName Value\n---- -----\nhgt {isSecret, value}\nnewvar1 {isSecret, value}\ndar {isSecret, value}\nabc {isSecret, value}\nvar {isSecret, value}\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74563281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11308857/" ]
74,563,284
<p>Let's suppose I have 3 vectors (just as an example). Now I want to obtain a random sample over all possible combinations of those 3. Usually, I'd do this:</p> <pre><code>x &lt;- 1:3 y &lt;- 10:12 z &lt;- 15:18 N &lt;- length(x) * length(y) * length(z) # Length of the resulting grid idx &lt;- sample(1:N, 10, replace = FALSE) my_grid &lt;- expand.grid(x, y, z) result &lt;- my_grid[idx, ] </code></pre> <p>That's fine for small vectors. But if those vectors grow in size, <code>my_grid</code> will get very big very fast. So the question is, how to create the <code>result</code> by only using <code>idx</code> and the three vectors?</p>
[ { "answer_id": 74563889, "author": "Stéphane Laurent", "author_id": 1100107, "author_profile": "https://Stackoverflow.com/users/1100107", "pm_score": 2, "selected": false, "text": "expand.grid 1:(n1*n2*n3) (x1, x2, x3) x1 1:n1 x2 1:n2 x3 1:n3 n1 = n2 = n3 = 2 intToCantor <- function(n, sizes) {\n l <- c(1, cumprod(sizes))\n epsilon <- numeric(length(sizes))\n while(n>0){\n k <- which.min(l<=n)\n e <- floor(n / l[k-1])\n epsilon[k-1] <- e\n n <- n - e*l[k-1]\n }\n epsilon\n}\n\nCantorToInt <- function(epsilon, sizes) {\n sum(epsilon * c(1, cumprod(sizes[1:(length(epsilon)-1)])))\n}\n\nx <- 1:3\ny <- 10:12\nz <- 15:18\n\nsizes <- c(length(x), length(y), length(z))\nN <- prod(sizes)\nn <- 10\nidx <- sample(1:N, n, replace = FALSE)\n\nresult <- matrix(NA_real_, nrow = n, ncol = length(sizes))\nfor(i in 1:n) {\n indices <- 1 + intToCantor(idx[i] - 1, sizes = sizes)\n result[i, ] <- c(x[indices[1]], y[indices[2]], z[indices[3]])\n}\n intToCantor mod2 <- function(x, y) (x-1) %% y + 1\n\nCantorExpansion <- function(n, sizes) {\n p <- cumprod(c(1, head(sizes, -1)))\n mod2(ceiling(n / p), sizes)\n}\n #include <Rcpp.h>\nusing namespace Rcpp;\n\n// [[Rcpp::export]]\nIntegerVector CantorRcpp(int n, std::vector<int> sizes) {\n IntegerVector epsilon(sizes.size(), 1);\n std::vector<int>::iterator it = sizes.begin();\n it = sizes.insert(it, 1);\n int G[sizes.size()];\n std::partial_sum(sizes.begin(), sizes.end(), G, std::multiplies<int>());\n n--;\n int k;\n while(n > 0) {\n k = 1;\n while(G[k] <= n) {\n k += 1;\n }\n int d = G[k-1];\n epsilon(k-1) = 1 + n / d;\n n = n % d;\n }\n return epsilon;\n}\n\n/*** R\nlibrary(microbenchmark)\n\nCantorExpansion <- function(n, sizes) {\n p <- cumprod(c(1L, head(sizes, -1L)))\n 1L + ((ceiling(n / p) - 1L) %% sizes)\n}\n\nsizes <- 2L:9L\nRobert <- function() {\n L <- vector(\"list\", length = prod(sizes))\n for(n in seq_len(prod(sizes))) {\n L[[n]] <- CantorExpansion(n, sizes)\n }\n}\nRcpp <- function() {\n L <- vector(\"list\", length = prod(sizes))\n for(n in seq_len(prod(sizes))) {\n L[[n]] <- CantorRcpp(n, sizes)\n }\n}\nmicrobenchmark(\n Robert = Robert(),\n Rcpp = Rcpp(),\n times = 10L\n)\n# Unit: milliseconds\n# expr min lq mean median uq max neval cld\n# Robert 1658.3666 1690.2473 1743.9026 1728.0874 1765.9536 1910.122 10 b\n# Rcpp 693.8287 764.4371 841.9733 801.9504 947.8049 1050.848 10 a \n*/\n" }, { "answer_id": 74564280, "author": "Robert Hacken", "author_id": 2094893, "author_profile": "https://Stackoverflow.com/users/2094893", "pm_score": 3, "selected": true, "text": "X <- list(x, y, z)\nX.len <- sapply(X, length)\n\n# modify '%%' to return values 1..n instead of 0..(n-1)\nmod2 <- function(x, y) (x-1) %% y + 1\n\nresult <- sapply(seq_along(X), function(i) \n X[[i]][mod2(ceiling(idx / prod(X.len[seq_len(i-1)])), \n X.len[i])]\n)\n expand.grid" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74563284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9551847/" ]
74,563,318
<p>I have received the following error:</p> <pre><code>type Submit = { form: any, handleSubmit: FunctionType&lt;any, any&gt;, ... } Flow-IDE Submit: type Submit = { form: any, handleSubmit: FunctionType &lt; any, any &gt; , ... } Cannot build a typed interface for this module. You should annotate the exports of this module with types. Missing type annotation at function return:Flow(signature-verification-failure) Cannot build a typed interface for this module. You should annotate the exports of this module with types. Missing type annotation at function return: [signature-verification-failure] (index.js:31:11)flow </code></pre> <p>I have this function</p> <pre><code>type Submit = { form: Object, handleSubmit: FunctionType&lt;Object, any&gt; // this is our custom type, works fine }; export const onClickSubmit = ({ form, handleSubmit }: Submit) =&gt; async (input: Object): Promise&lt;any&gt; =&gt; { await handleSubmit(input); form.reset(); }; </code></pre> <p>The area highlighted is <code>}: Submit)</code> on the <code>)</code>.</p> <p>I am at a loss what it wants me to do, adding any type definition after <code>):</code> doesn't help at all.</p> <p>The example in the <a href="https://flow.org/en/docs/lang/types-first/" rel="nofollow noreferrer">type-first flow docs</a> is providing examples that are not helpful. I cannot <code>export functionName</code> with special definition only for it like in their module.exports examples.</p>
[ { "answer_id": 74563889, "author": "Stéphane Laurent", "author_id": 1100107, "author_profile": "https://Stackoverflow.com/users/1100107", "pm_score": 2, "selected": false, "text": "expand.grid 1:(n1*n2*n3) (x1, x2, x3) x1 1:n1 x2 1:n2 x3 1:n3 n1 = n2 = n3 = 2 intToCantor <- function(n, sizes) {\n l <- c(1, cumprod(sizes))\n epsilon <- numeric(length(sizes))\n while(n>0){\n k <- which.min(l<=n)\n e <- floor(n / l[k-1])\n epsilon[k-1] <- e\n n <- n - e*l[k-1]\n }\n epsilon\n}\n\nCantorToInt <- function(epsilon, sizes) {\n sum(epsilon * c(1, cumprod(sizes[1:(length(epsilon)-1)])))\n}\n\nx <- 1:3\ny <- 10:12\nz <- 15:18\n\nsizes <- c(length(x), length(y), length(z))\nN <- prod(sizes)\nn <- 10\nidx <- sample(1:N, n, replace = FALSE)\n\nresult <- matrix(NA_real_, nrow = n, ncol = length(sizes))\nfor(i in 1:n) {\n indices <- 1 + intToCantor(idx[i] - 1, sizes = sizes)\n result[i, ] <- c(x[indices[1]], y[indices[2]], z[indices[3]])\n}\n intToCantor mod2 <- function(x, y) (x-1) %% y + 1\n\nCantorExpansion <- function(n, sizes) {\n p <- cumprod(c(1, head(sizes, -1)))\n mod2(ceiling(n / p), sizes)\n}\n #include <Rcpp.h>\nusing namespace Rcpp;\n\n// [[Rcpp::export]]\nIntegerVector CantorRcpp(int n, std::vector<int> sizes) {\n IntegerVector epsilon(sizes.size(), 1);\n std::vector<int>::iterator it = sizes.begin();\n it = sizes.insert(it, 1);\n int G[sizes.size()];\n std::partial_sum(sizes.begin(), sizes.end(), G, std::multiplies<int>());\n n--;\n int k;\n while(n > 0) {\n k = 1;\n while(G[k] <= n) {\n k += 1;\n }\n int d = G[k-1];\n epsilon(k-1) = 1 + n / d;\n n = n % d;\n }\n return epsilon;\n}\n\n/*** R\nlibrary(microbenchmark)\n\nCantorExpansion <- function(n, sizes) {\n p <- cumprod(c(1L, head(sizes, -1L)))\n 1L + ((ceiling(n / p) - 1L) %% sizes)\n}\n\nsizes <- 2L:9L\nRobert <- function() {\n L <- vector(\"list\", length = prod(sizes))\n for(n in seq_len(prod(sizes))) {\n L[[n]] <- CantorExpansion(n, sizes)\n }\n}\nRcpp <- function() {\n L <- vector(\"list\", length = prod(sizes))\n for(n in seq_len(prod(sizes))) {\n L[[n]] <- CantorRcpp(n, sizes)\n }\n}\nmicrobenchmark(\n Robert = Robert(),\n Rcpp = Rcpp(),\n times = 10L\n)\n# Unit: milliseconds\n# expr min lq mean median uq max neval cld\n# Robert 1658.3666 1690.2473 1743.9026 1728.0874 1765.9536 1910.122 10 b\n# Rcpp 693.8287 764.4371 841.9733 801.9504 947.8049 1050.848 10 a \n*/\n" }, { "answer_id": 74564280, "author": "Robert Hacken", "author_id": 2094893, "author_profile": "https://Stackoverflow.com/users/2094893", "pm_score": 3, "selected": true, "text": "X <- list(x, y, z)\nX.len <- sapply(X, length)\n\n# modify '%%' to return values 1..n instead of 0..(n-1)\nmod2 <- function(x, y) (x-1) %% y + 1\n\nresult <- sapply(seq_along(X), function(i) \n X[[i]][mod2(ceiling(idx / prod(X.len[seq_len(i-1)])), \n X.len[i])]\n)\n expand.grid" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74563318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7763383/" ]
74,563,326
<p>How can I make a quadrant (quarter-circle) like the one below, using Auto-Layout in Swift? I understand that <code>UIBezierPath</code> is required but I can't seem to get it to work.</p> <p><a href="https://i.stack.imgur.com/sFdUi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sFdUi.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74563612, "author": "DonMag", "author_id": 6257435, "author_profile": "https://Stackoverflow.com/users/6257435", "pm_score": 3, "selected": true, "text": "class QuarterCircleView: UIView {\n \n override func layoutSubviews() {\n super.layoutSubviews()\n \n // only add the shape layer once\n if layer.sublayers == nil {\n let lay = CAShapeLayer()\n lay.fillColor = UIColor.blue.cgColor\n layer.addSublayer(lay)\n }\n if let lay = layer.sublayers?.first as? CAShapeLayer {\n let center = CGPoint(x: bounds.midX, y: bounds.midY)\n let bez = UIBezierPath()\n bez.move(to: center)\n bez.addArc(withCenter: center, radius: bounds.width * 0.5, startAngle: .pi, endAngle: .pi * 1.5, clockwise: true)\n bez.close()\n lay.path = bez.cgPath\n }\n }\n \n}\n CAShapeLayer" }, { "answer_id": 74565399, "author": "Duncan C", "author_id": 205185, "author_profile": "https://Stackoverflow.com/users/205185", "pm_score": 1, "selected": false, "text": "class QuarterCircleView: UIView {\n\n // By adding this static var, we can change the type of our view's layer (in this case, to a CAShapeLayer)\n static override var layerClass: AnyClass {\n return CAShapeLayer.self\n }\n\n // This lets us use the view's layer as a CAShapeLayer without type casting.\n var shapeLayer: CAShapeLayer {\n return self.layer as! CAShapeLayer\n }\n\n required init?(coder aDecoder: NSCoder) {\n super.init(coder: aDecoder)\n shapeLayer.fillColor = UIColor.blue.cgColor\n }\n\n // Every time we update our subviews, also regenerate our shape layer's path.\n override func layoutSubviews() {\n super.layoutSubviews()\n\n // We want a quarter-circle centered on the lower right of teh view.\n let center = CGPoint(x:bounds.maxX, y:bounds.maxY)\n let bez = UIBezierPath()\n bez.move(to: center)\n\n // As long as our view is square, the below isn't needed, but let's be sure.\n let radius = min(bounds.width, bounds.height)\n bez.addArc(withCenter: center, radius: radius, startAngle: .pi, endAngle: .pi * 1.5, clockwise: true)\n bez.close()\n shapeLayer.path = bez.cgPath\n }\n\n}\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74563326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9134553/" ]
74,563,370
<p>I have folowing demo. These 2 lines should look equal in height, but one is thicker. All this depends on its top position. If I change its top position by 1px it may become &quot;normal&quot; looking again. Is there a way to prevent this behavior?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.a { position: absolute; top: 0; } .line { width: 300px; height: 1px; background: red; position: absolute; top: 5px; box-sizing: border-box; } .line2 { width: 300px; height: 1px; background: red; position: absolute; top: 11px; box-sizing: border-box; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="a"&gt; &lt;div class="line"&gt;&lt;/div&gt; &lt;div class="line2"&gt;&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74563612, "author": "DonMag", "author_id": 6257435, "author_profile": "https://Stackoverflow.com/users/6257435", "pm_score": 3, "selected": true, "text": "class QuarterCircleView: UIView {\n \n override func layoutSubviews() {\n super.layoutSubviews()\n \n // only add the shape layer once\n if layer.sublayers == nil {\n let lay = CAShapeLayer()\n lay.fillColor = UIColor.blue.cgColor\n layer.addSublayer(lay)\n }\n if let lay = layer.sublayers?.first as? CAShapeLayer {\n let center = CGPoint(x: bounds.midX, y: bounds.midY)\n let bez = UIBezierPath()\n bez.move(to: center)\n bez.addArc(withCenter: center, radius: bounds.width * 0.5, startAngle: .pi, endAngle: .pi * 1.5, clockwise: true)\n bez.close()\n lay.path = bez.cgPath\n }\n }\n \n}\n CAShapeLayer" }, { "answer_id": 74565399, "author": "Duncan C", "author_id": 205185, "author_profile": "https://Stackoverflow.com/users/205185", "pm_score": 1, "selected": false, "text": "class QuarterCircleView: UIView {\n\n // By adding this static var, we can change the type of our view's layer (in this case, to a CAShapeLayer)\n static override var layerClass: AnyClass {\n return CAShapeLayer.self\n }\n\n // This lets us use the view's layer as a CAShapeLayer without type casting.\n var shapeLayer: CAShapeLayer {\n return self.layer as! CAShapeLayer\n }\n\n required init?(coder aDecoder: NSCoder) {\n super.init(coder: aDecoder)\n shapeLayer.fillColor = UIColor.blue.cgColor\n }\n\n // Every time we update our subviews, also regenerate our shape layer's path.\n override func layoutSubviews() {\n super.layoutSubviews()\n\n // We want a quarter-circle centered on the lower right of teh view.\n let center = CGPoint(x:bounds.maxX, y:bounds.maxY)\n let bez = UIBezierPath()\n bez.move(to: center)\n\n // As long as our view is square, the below isn't needed, but let's be sure.\n let radius = min(bounds.width, bounds.height)\n bez.addArc(withCenter: center, radius: radius, startAngle: .pi, endAngle: .pi * 1.5, clockwise: true)\n bez.close()\n shapeLayer.path = bez.cgPath\n }\n\n}\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74563370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1009466/" ]
74,563,411
<p>I have 9 predictors (Clean df) but when I run the model I get 10 coefficients. Here is my code:</p> <pre><code>#Get clean df with only more relevant columns Clean_indices = wkospi[['Open_sp','Close_sp','Close_jp','Open_eur','High_eur','Open_kos','Close_kos','1 Mo','2 Mo','1 Yr','2 Yr','Open_oil','Open_gold']] Clean_df = wkospi[['Close_jp','Open_sp','Open_eur','High_eur','Close_kos','3 Mo','6 Mo', '1 Yr', '2 Yr']] #Run the test for Clean df ALIAS &quot;cd&quot; cdx_train, cdx_test, cdy_train, cdy_test = train_test_split(Clean_df, Clean_indices['Close_sp'] , test_size=0.6, random_state = 4, shuffle = True) #Prepare train data and test data as polynomials cpr=PolynomialFeatures(degree=1) cdp_train=cpr.fit_transform(cdx_train) cdp_test=cpr.fit_transform(cdx_test) RigeModel_cd=Ridge(alpha = 1000) RigeModel_cd.fit(cdp_train, cdy_train) yhat_cd = RigeModel_cd.predict(cdp_test) </code></pre> <p>But when I check the coefficients I get 10 instead.</p> <pre><code> in&gt;&gt; RigeModel_cd.coef_ out&gt;&gt; array([ 0.00000000e+00, 4.66393448e-03, 9.60826030e-01, -8.18000961e-01, 8.78056763e-01, -9.08744162e-05, -3.30052619e-01, -4.24748286e-01, -5.42880494e-01, -6.49848520e-01]) </code></pre> <p>Does anybody know why this is happening?</p>
[ { "answer_id": 74563641, "author": "Ben Reiniger", "author_id": 10495893, "author_profile": "https://Stackoverflow.com/users/10495893", "pm_score": 3, "selected": true, "text": "PolynomialFeatures include_bias=True" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74563411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17295666/" ]
74,563,422
<p>I have a problem with if in cypress test, when the element is not visible I receive: &quot;AssertionError: Timed out retrying after 4000ms: Expected to find element: [type=&quot;alertdialog&quot;], but never found it.&quot; but I would like to receive cy.log(&quot;test&quot;) when the element is not visible. There is any possibility to do that?</p> <pre><code> if ($dis.is(':visible')) { cy.get('[button=&quot;reject&quot;]').click() } else { cy.log(&quot;test&quot;) } })``` </code></pre>
[ { "answer_id": 74647456, "author": "szogoon", "author_id": 8119084, "author_profile": "https://Stackoverflow.com/users/8119084", "pm_score": 0, "selected": false, "text": "cy.get('body').then($body => {\n const dis = $body.find('.some_class')\n if (dis.length) {\n cy.get('[button=\"reject\"]').click()\n } else {\n cy.log(\"test\")\n }\n})\n" }, { "answer_id": 74648489, "author": "Paolo", "author_id": 16791505, "author_profile": "https://Stackoverflow.com/users/16791505", "pm_score": 1, "selected": false, "text": "if ($dis.length > 0) {\n cy.get('[button=\"reject\"]').click()\n} else {\n cy.log(\"test\")\n}\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74563422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18149779/" ]
74,563,435
<p>I have a set of data that has multiple groups across multiple time points (sample cut below):</p> <p><a href="https://i.stack.imgur.com/T4inL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/T4inL.png" alt="enter image description here" /></a></p> <p>I've been trying to conduct multiple cor.test between X and Y <em><strong>between each status, and across each gender</strong></em>.</p> <p>I was having a hard time figuring out the group comparison so I filtered by status and split my gender cor.tests separately for Status = Red and Status = Blue (using filter).</p> <p>This is my current code which runs cor.test across each gender:</p> <pre><code> red_status &lt;- all %&gt;% filter(status == &quot;Red&quot;) cor_red &lt;- by(red_status, red_status$gender, FUN = function(df) cor.test(df$X, df$Y, method = &quot;spearman&quot;)) </code></pre> <p>The output result shows the 3 different cor.test across each gender:</p> <pre><code> red_status$gengrp: M Spearman's rank correlation rho data: df$X and df$Y S = 123.45, p-value = 0.123 alternative hypothesis: true rho is not equal to 0 sample estimates: rho 0.123456 ---------------------------------- red_status$gengrp: F ... (same output style as gengrp: M ^) ---------------------------------- red_status$gengrp: O ... (same output style as gengrp: M ^) </code></pre> <p>What I'm trying to do is extract the estimate and p-values across all gender cor.test and place them in a dataframe.</p> <p>I thought I can use the data.frame() function to extract the gender name and correlation elements, then just add another column for p-values, however doing this gave me an error:</p> <pre><code># Where red_status[1] is gender names (M,F,O) and red_status[[3:4]] are the Spearman p-value and rho estimate *within each gender category* data.frame(group = dimnames(red_status)[1], est = as.vector(red_status)[[3]], pval = as.vector(red_status[[4]]) </code></pre> <pre><code>Error in as.data.frame.default(x[[i]], optional = TRUE, stringsAsFactors = stringsAsFactors) : cannot coerce class ‘&quot;htest&quot;’ to a data.frame </code></pre> <p>Since I filtered by Status == Red, I'd have to rerun the codes again to get the result for the gender cor.test results of Status == Blue then at the end bind the estimates and p-values all to 1 df.</p> <p>My goal is to be able to create a data frame that shows the correlation estimate and p-value across each status <em>and</em> gender:</p> <pre><code>Status Gender Estimate(rho) P-value Red M 1.23 0.123 Red F 0.45 0.054 Red O ... ... Blue M 0.004 0.123 Blue F ... ... Blue O ... ... </code></pre> <p>Any help/tips would be appreciated.</p>
[ { "answer_id": 74647456, "author": "szogoon", "author_id": 8119084, "author_profile": "https://Stackoverflow.com/users/8119084", "pm_score": 0, "selected": false, "text": "cy.get('body').then($body => {\n const dis = $body.find('.some_class')\n if (dis.length) {\n cy.get('[button=\"reject\"]').click()\n } else {\n cy.log(\"test\")\n }\n})\n" }, { "answer_id": 74648489, "author": "Paolo", "author_id": 16791505, "author_profile": "https://Stackoverflow.com/users/16791505", "pm_score": 1, "selected": false, "text": "if ($dis.length > 0) {\n cy.get('[button=\"reject\"]').click()\n} else {\n cy.log(\"test\")\n}\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74563435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10259800/" ]
74,563,472
<p>I am new in sql and I want to know how can I select avg from count this is how my code looks like</p> <pre><code>Select zwierzeta.nazwa,zwierzeta.klatka_id,klatki.nazwa, count(zwierzeta.klatka_id) as licz from zwierzeta join klatki on zwierzeta.zwierze_id = klatki.klatka_id having count(zwierzeta.klatka_id) &gt;= 1 GROUP BY zwierzeta.nazwa,zwierzeta.klatka_id,klatki.nazwa </code></pre> <p>Now I want to select avg from count(zwierzeta.klatka_id).</p> <p>I have tried this method</p> <pre><code>Select zwierzeta.nazwa,zwierzeta.klatka_id,klatki.nazwa, count(zwierzeta.klatka_id) as licz, avg(licz) as avg_number from zwierzeta join klatki on zwierzeta.zwierze_id = klatki.klatka_id having count(zwierzeta.klatka_id) &gt;= 1 GROUP BY zwierzeta.nazwa,zwierzeta.klatka_id,klatki.nazwa ` </code></pre> <p>but it doesnt recognize &quot;licz&quot;</p>
[ { "answer_id": 74647456, "author": "szogoon", "author_id": 8119084, "author_profile": "https://Stackoverflow.com/users/8119084", "pm_score": 0, "selected": false, "text": "cy.get('body').then($body => {\n const dis = $body.find('.some_class')\n if (dis.length) {\n cy.get('[button=\"reject\"]').click()\n } else {\n cy.log(\"test\")\n }\n})\n" }, { "answer_id": 74648489, "author": "Paolo", "author_id": 16791505, "author_profile": "https://Stackoverflow.com/users/16791505", "pm_score": 1, "selected": false, "text": "if ($dis.length > 0) {\n cy.get('[button=\"reject\"]').click()\n} else {\n cy.log(\"test\")\n}\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74563472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20317241/" ]
74,563,511
<p>If you don't add any more fields to your subclass is there a need to add the <code>@dataclass</code> decorator to it and would it do anything?</p> <p>If there is no difference, which is the usual convention?</p> <pre class="lang-py prettyprint-override"><code>from dataclasses import dataclass @dataclass class AAA: x: str y: str ... # decorate? class BBB(AAA): ... </code></pre>
[ { "answer_id": 74647456, "author": "szogoon", "author_id": 8119084, "author_profile": "https://Stackoverflow.com/users/8119084", "pm_score": 0, "selected": false, "text": "cy.get('body').then($body => {\n const dis = $body.find('.some_class')\n if (dis.length) {\n cy.get('[button=\"reject\"]').click()\n } else {\n cy.log(\"test\")\n }\n})\n" }, { "answer_id": 74648489, "author": "Paolo", "author_id": 16791505, "author_profile": "https://Stackoverflow.com/users/16791505", "pm_score": 1, "selected": false, "text": "if ($dis.length > 0) {\n cy.get('[button=\"reject\"]').click()\n} else {\n cy.log(\"test\")\n}\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74563511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5805389/" ]
74,563,516
<p>Let's say I have a notes app. I want to enable the user to make changes while he is offline, save the changes optimistically in a Mobx store, and add a request to save the changes (on the server) to a queue. Then when the internet connection is re-established I want to run the requests in the queue one by one so the data in the app syncs with data on the server.</p> <p>Any suggestions would help.</p> <p>I tried using <a href="https://github.com/SimonErm/react-native-job-queue" rel="nofollow noreferrer">react-native-job-queue</a> but it doesn't seem to work. I also considered <a href="https://github.com/billmalarky/react-native-queue" rel="nofollow noreferrer">react-native-queue</a> but the library seems to be abandoned.</p>
[ { "answer_id": 74565206, "author": "Abe", "author_id": 10718641, "author_profile": "https://Stackoverflow.com/users/10718641", "pm_score": 1, "selected": false, "text": "pending: true" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74563516", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20100274/" ]
74,563,548
<p>I'm using Selenium in Python (3.11) with a Firefox (107) driver.</p> <p>With the driver I navigate to a page which, after several actions, triggers an OS alert (prompting me to launch a program). When this alert pops up, the driver hangs, and only once it is closed manually does my script continue to run.</p> <p>I have tried <code>driver.quit()</code>, as well as using</p> <pre><code>os.system(&quot;taskkill /F /pid &quot; + str(process.ProcessId)) </code></pre> <p>with the driver's PID, with no luck.</p> <p>I have managed to prevent the pop-up from popping up with</p> <pre><code>options.set_preference(&quot;security.external_protocol_requires_permission&quot;, False) </code></pre> <p>but the code still hangs the same way at the point where the popup <em>would</em> have popped up.</p> <p>I don't care whether the program launches or not, I just need my code to not require human intervention at this key point.</p> <p>here is a minimal example of what I currently have:</p> <pre><code>from selenium.webdriver import ActionChains, Keys from selenium.webdriver.firefox.options import Options from seleniumwire import webdriver options = Options() options.binary_location = r'C:\Program Files\Mozilla Firefox\firefox.exe' options.set_preference(&quot;security.external_protocol_requires_permission&quot;, False) driver = webdriver.Firefox(options=options) # Go to the page driver.get(url) user_field = driver.find_element(&quot;id&quot;, &quot;UserName&quot;) user_field.send_keys(username) pass_field = driver.find_element(&quot;id&quot;, &quot;Password&quot;) pass_field.send_keys(password) pass_field.send_keys(Keys.ENTER) #this is the point where the pop up appears reqs = driver.requests print(&quot;Success!&quot;) driver.quit() </code></pre>
[ { "answer_id": 74601534, "author": "Guy", "author_id": 5168011, "author_profile": "https://Stackoverflow.com/users/5168011", "pm_score": 2, "selected": false, "text": "profile = webdriver.FirefoxProfile()\nprofile.set_preference('dom.push.enabled', False)\n\n# or\n\nprofile = webdriver.FirefoxProfile()\nprofile.set_preference('dom.webnotifications.enabled', False)\nprofile.set_preference('dom.webnotifications.serviceworker.enabled', False)\n" }, { "answer_id": 74604671, "author": "mr_mooo_cow", "author_id": 3249399, "author_profile": "https://Stackoverflow.com/users/3249399", "pm_score": 2, "selected": false, "text": "profile.set_preference('browser.helperApps.neverAsk.openFile', 'typeOfFile') \n# e.g. profile.set_preference('browser.helperApps.neverAsk.openFile', 'application/xml,application/octet-stream')\n from selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\n....\npass_field.send_keys(Keys.ENTER)\n\n#this is the point where the pop up appears\nWebDriverWait(driver, 5).until(EC.alert_is_present).dismiss()\nreqs = driver.requests\n...\n" }, { "answer_id": 74663242, "author": "Benjamin Woolston", "author_id": 20188398, "author_profile": "https://Stackoverflow.com/users/20188398", "pm_score": 0, "selected": false, "text": "# After navigating to the page that triggers the alert\nalert = driver.switch_to.alert\n\n# Use the alert methods to handle the alert as needed\nalert.accept() # This will accept the alert, launching the program\n# or\nalert.dismiss() # This will dismiss the alert, not launching the program\n# or\nalert.send_keys(\"some text\") # This will enter text in the alert and accept it\n from selenium.webdriver.firefox.options import Options\n\n# Set the unhandled_prompt_behavior option to dismiss\noptions = Options()\noptions.binary_location = r'C:\\Program Files\\Mozilla Firefox\\firefox.exe'\noptions.set_preference(\"security.external_protocol_requires_permission\", False)\noptions.unhandled_prompt_behavior = \"dismiss\"\ndriver = webdriver.Firefox(options=options)\n\n# Navigate to the page that triggers the alert\ndriver.get(url)\n\n# The alert should be automatically dismissed by the unhandled_prompt_behavior setting\n" }, { "answer_id": 74663448, "author": "Sahaj Raj Malla", "author_id": 11773575, "author_profile": "https://Stackoverflow.com/users/11773575", "pm_score": 0, "selected": false, "text": "# Go to the page\ndriver.get(url)\n\nuser_field = driver.find_element(\"id\", \"UserName\")\nuser_field.send_keys(username)\npass_field = driver.find_element(\"id\", \"Password\")\npass_field.send_keys(password)\npass_field.send_keys(Keys.ENTER)\n\n# Handle the alert by dismissing it\ndriver.switch_to.alert.dismiss()\n\n# Your script can continue running now\nreqs = driver.requests\n\nprint(\"Success!\")\ndriver.quit()\n\n from selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\n# Go to the page\ndriver.get(url)\n\nuser_field = driver.find_element(\"id\", \"UserName\")\nuser_field.send_keys(username)\npass_field = driver.find_element(\"id\", \"Password\")\npass_field.send_keys(password)\npass_field.send_keys(Keys.ENTER)\n\n# Wait for the alert to be dismissed before continuing\nWebDriverWait(driver, 10).until(EC.alert_is_not_present())\n\n# Your script can continue running now\nreqs = driver.requests\n\nprint(\"Success!\")\ndriver.quit()\n\n" }, { "answer_id": 74672939, "author": "Midas", "author_id": 20678816, "author_profile": "https://Stackoverflow.com/users/20678816", "pm_score": 0, "selected": false, "text": "from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.alerts import Alert\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\n# Create an instance of Firefox WebDriver\ndriver = webdriver.Firefox()\n\n# Go to the page\ndriver.get(url)\n\nuser_field = driver.find_element(By.ID, \"UserName\")\nuser_field.send_keys(username)\npass_field = driver.find_element(By.ID, \"Password\")\npass_field.send_keys(password)\npass_field.send_keys(Keys.ENTER)\n\n# Wait for the alert to be present and handle it\nWebDriverWait(driver, 10).until(EC.alert_is_present())\nalert = Alert(driver)\nalert.accept() # or alert.dismiss() to dismiss the alert\n\nreqs = driver.requests\n\nprint(\"Success!\")\ndriver.quit()\n" }, { "answer_id": 74677045, "author": "kppro", "author_id": 10955397, "author_profile": "https://Stackoverflow.com/users/10955397", "pm_score": 0, "selected": false, "text": "from selenium.webdriver import ActionChains, Keys\nfrom selenium.webdriver.firefox.options import Options\nfrom selenium.webdriver.common.alert import Alert\nfrom seleniumwire import webdriver\n\noptions = Options()\noptions.binary_location = r'C:\\Program Files\\Mozilla Firefox\\firefox.exe'\noptions.set_preference(\"security.external_protocol_requires_permission\", False)\ndriver = webdriver.Firefox(options=options)\n\n# Go to the page\ndriver.get(url)\n\nuser_field = driver.find_element(\"id\", \"UserName\")\nuser_field.send_keys(username)\npass_field = driver.find_element(\"id\", \"Password\")\npass_field.send_keys(password)\npass_field.send_keys(Keys.ENTER)\n\n# Handle the alert if it appears\ntry:\n alert = Alert(driver)\n alert.dismiss()\nexcept:\n pass\n\nreqs = driver.requests\n\nprint(\"Success!\")\ndriver.quit()\n from selenium.webdriver import ActionChains, Keys\nfrom selenium.webdriver.firefox.options import Options\nfrom seleniumwire import webdriver\n\noptions = Options()\noptions.binary_location = r'C:\\Program Files\\Mozilla Firefox\\firefox.exe'\ndriver = webdriver.Firefox(options=options)\n\n//Go to the page\ndriver.get(url)\n\nuser_field = driver.find_element(\"id\", \"UserName\")\nuser_field.send_keys(username)\npass_field = driver.find_element(\"id\", \"Password\")\npass_field.send_keys(password)\npass_field.send_keys(Keys.ENTER)\n\n//Use the execute_script() method to handle the alert\ndriver.execute_script(\"alert('This is an alert')\")\n\n//Continue with the script\nreqs = driver.requests\n\nprint(\"Success!\")\ndriver.quit()\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74563548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6187682/" ]
74,563,551
<p>In a @PostMapping call, when a list of objects is received via the @RequestBody. And this list contains Int or Double variables, if these variables are not sent in the request body json, the variables are self-initialized to 0. Instead of this, I understand that it should return bad request</p> <p>This problem does not happen with the BigDecimal for example and returns bad request with this variables, or if the body of the request is an object instead of a list.</p> <p>Do you know how to solve this? is it a spring problem?</p> <p>Example to reproduce the problem:</p> <pre><code>data class Animal( val name: String, val height: Double ) @PostMapping(&quot;/animals&quot;) suspend fun saveAnimals( @RequestBody request: List&lt;Animal&gt; ): ResponseEntity&lt;Any&gt; { println(request[0].height) return ResponseEntity.ok().build() } </code></pre> <p>In the example above the print result will be 0 if the height is not sent on the request, but I expected this to return a bad request.</p>
[ { "answer_id": 74601534, "author": "Guy", "author_id": 5168011, "author_profile": "https://Stackoverflow.com/users/5168011", "pm_score": 2, "selected": false, "text": "profile = webdriver.FirefoxProfile()\nprofile.set_preference('dom.push.enabled', False)\n\n# or\n\nprofile = webdriver.FirefoxProfile()\nprofile.set_preference('dom.webnotifications.enabled', False)\nprofile.set_preference('dom.webnotifications.serviceworker.enabled', False)\n" }, { "answer_id": 74604671, "author": "mr_mooo_cow", "author_id": 3249399, "author_profile": "https://Stackoverflow.com/users/3249399", "pm_score": 2, "selected": false, "text": "profile.set_preference('browser.helperApps.neverAsk.openFile', 'typeOfFile') \n# e.g. profile.set_preference('browser.helperApps.neverAsk.openFile', 'application/xml,application/octet-stream')\n from selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\n....\npass_field.send_keys(Keys.ENTER)\n\n#this is the point where the pop up appears\nWebDriverWait(driver, 5).until(EC.alert_is_present).dismiss()\nreqs = driver.requests\n...\n" }, { "answer_id": 74663242, "author": "Benjamin Woolston", "author_id": 20188398, "author_profile": "https://Stackoverflow.com/users/20188398", "pm_score": 0, "selected": false, "text": "# After navigating to the page that triggers the alert\nalert = driver.switch_to.alert\n\n# Use the alert methods to handle the alert as needed\nalert.accept() # This will accept the alert, launching the program\n# or\nalert.dismiss() # This will dismiss the alert, not launching the program\n# or\nalert.send_keys(\"some text\") # This will enter text in the alert and accept it\n from selenium.webdriver.firefox.options import Options\n\n# Set the unhandled_prompt_behavior option to dismiss\noptions = Options()\noptions.binary_location = r'C:\\Program Files\\Mozilla Firefox\\firefox.exe'\noptions.set_preference(\"security.external_protocol_requires_permission\", False)\noptions.unhandled_prompt_behavior = \"dismiss\"\ndriver = webdriver.Firefox(options=options)\n\n# Navigate to the page that triggers the alert\ndriver.get(url)\n\n# The alert should be automatically dismissed by the unhandled_prompt_behavior setting\n" }, { "answer_id": 74663448, "author": "Sahaj Raj Malla", "author_id": 11773575, "author_profile": "https://Stackoverflow.com/users/11773575", "pm_score": 0, "selected": false, "text": "# Go to the page\ndriver.get(url)\n\nuser_field = driver.find_element(\"id\", \"UserName\")\nuser_field.send_keys(username)\npass_field = driver.find_element(\"id\", \"Password\")\npass_field.send_keys(password)\npass_field.send_keys(Keys.ENTER)\n\n# Handle the alert by dismissing it\ndriver.switch_to.alert.dismiss()\n\n# Your script can continue running now\nreqs = driver.requests\n\nprint(\"Success!\")\ndriver.quit()\n\n from selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\n# Go to the page\ndriver.get(url)\n\nuser_field = driver.find_element(\"id\", \"UserName\")\nuser_field.send_keys(username)\npass_field = driver.find_element(\"id\", \"Password\")\npass_field.send_keys(password)\npass_field.send_keys(Keys.ENTER)\n\n# Wait for the alert to be dismissed before continuing\nWebDriverWait(driver, 10).until(EC.alert_is_not_present())\n\n# Your script can continue running now\nreqs = driver.requests\n\nprint(\"Success!\")\ndriver.quit()\n\n" }, { "answer_id": 74672939, "author": "Midas", "author_id": 20678816, "author_profile": "https://Stackoverflow.com/users/20678816", "pm_score": 0, "selected": false, "text": "from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.alerts import Alert\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\n# Create an instance of Firefox WebDriver\ndriver = webdriver.Firefox()\n\n# Go to the page\ndriver.get(url)\n\nuser_field = driver.find_element(By.ID, \"UserName\")\nuser_field.send_keys(username)\npass_field = driver.find_element(By.ID, \"Password\")\npass_field.send_keys(password)\npass_field.send_keys(Keys.ENTER)\n\n# Wait for the alert to be present and handle it\nWebDriverWait(driver, 10).until(EC.alert_is_present())\nalert = Alert(driver)\nalert.accept() # or alert.dismiss() to dismiss the alert\n\nreqs = driver.requests\n\nprint(\"Success!\")\ndriver.quit()\n" }, { "answer_id": 74677045, "author": "kppro", "author_id": 10955397, "author_profile": "https://Stackoverflow.com/users/10955397", "pm_score": 0, "selected": false, "text": "from selenium.webdriver import ActionChains, Keys\nfrom selenium.webdriver.firefox.options import Options\nfrom selenium.webdriver.common.alert import Alert\nfrom seleniumwire import webdriver\n\noptions = Options()\noptions.binary_location = r'C:\\Program Files\\Mozilla Firefox\\firefox.exe'\noptions.set_preference(\"security.external_protocol_requires_permission\", False)\ndriver = webdriver.Firefox(options=options)\n\n# Go to the page\ndriver.get(url)\n\nuser_field = driver.find_element(\"id\", \"UserName\")\nuser_field.send_keys(username)\npass_field = driver.find_element(\"id\", \"Password\")\npass_field.send_keys(password)\npass_field.send_keys(Keys.ENTER)\n\n# Handle the alert if it appears\ntry:\n alert = Alert(driver)\n alert.dismiss()\nexcept:\n pass\n\nreqs = driver.requests\n\nprint(\"Success!\")\ndriver.quit()\n from selenium.webdriver import ActionChains, Keys\nfrom selenium.webdriver.firefox.options import Options\nfrom seleniumwire import webdriver\n\noptions = Options()\noptions.binary_location = r'C:\\Program Files\\Mozilla Firefox\\firefox.exe'\ndriver = webdriver.Firefox(options=options)\n\n//Go to the page\ndriver.get(url)\n\nuser_field = driver.find_element(\"id\", \"UserName\")\nuser_field.send_keys(username)\npass_field = driver.find_element(\"id\", \"Password\")\npass_field.send_keys(password)\npass_field.send_keys(Keys.ENTER)\n\n//Use the execute_script() method to handle the alert\ndriver.execute_script(\"alert('This is an alert')\")\n\n//Continue with the script\nreqs = driver.requests\n\nprint(\"Success!\")\ndriver.quit()\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74563551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7251427/" ]
74,563,564
<p>I'm trying to make an app and I want to have a background colour for the app so I put the colour in the assets folder but the colour only fills up 3 quarters of the screen, leaving the top half empty.</p> <p>I had a ZStack so I put <code>.background(Color(&quot;appBackground&quot;))</code> at the end of the ZStack which left me with this result.</p> <p>Code for the entire HomeScreenView:</p> <pre><code>import AVKit import SwiftUI struct HomeView: View { @Binding var streak: Streaks @Binding var timer: TimerStruct @State var isSheetPresented = false @Binding var navigationPath: NavigationPath @Binding var exercisePlans: [ExercisePlan] func ridzero(result: Double) -&gt; String { let value = String(format: &quot;%g&quot;, result) return value } func round(result: Double) -&gt; String { let value = String(format: &quot;%.1f&quot;, result) return value } var body: some View { NavigationView { GeometryReader { geometry in ScrollView { ZStack { VStack { let percent = Double(timer.exerciseTime/1500) Text(&quot;Welcome back to ElderlyFit&quot;) .font(.system(size: 25,weight: .medium, design: .rounded)) .offset(x: 0, y: 20) CircularProgressView(timer: $timer, progress: CGFloat(percent)) .frame(width: 150, height: 150) .offset(x: -95, y: -240) .padding(EdgeInsets(top: 280, leading: 0, bottom: 0, trailing: 0)) Text(&quot;\(round(result:percent*100))%&quot;) .font(.system(size: 30, weight: .bold, design: .rounded)) .offset(x:-92, y:-345) Text(&quot;\(round(result: timer.exerciseTime/60)) mins of exercise completed today&quot;) .frame(width: 200, height: 50) .font(.system(size: 20, design: .rounded)) .offset(x:100, y:-410) StreaksView(timer: $timer, streak: $streak) .offset(x:0, y: -330) .padding() Text(&quot;Choose your exercise plan:&quot;) .bold() .font(.system(size: 25)) .offset(x: -30, y: -420) .zIndex(1.0) ExercisePlanView( streaks: $streak, timer: $timer, navigationPath: $navigationPath, exercisePlans: $exercisePlans) .offset(x: 15, y: -405) .zIndex(-1.0) .font(Font.system(size: UIFontMetrics.default.scaledValue(for: 15))) //.frame(maxWidth: .infinity, maxHeight: .infinity) } .frame(width: geometry.size.width) .edgesIgnoringSafeArea(.all) } .background(Color(&quot;appBackground&quot;)) } } } } } </code></pre> <p><a href="https://i.stack.imgur.com/s0kgl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/s0kgl.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74601534, "author": "Guy", "author_id": 5168011, "author_profile": "https://Stackoverflow.com/users/5168011", "pm_score": 2, "selected": false, "text": "profile = webdriver.FirefoxProfile()\nprofile.set_preference('dom.push.enabled', False)\n\n# or\n\nprofile = webdriver.FirefoxProfile()\nprofile.set_preference('dom.webnotifications.enabled', False)\nprofile.set_preference('dom.webnotifications.serviceworker.enabled', False)\n" }, { "answer_id": 74604671, "author": "mr_mooo_cow", "author_id": 3249399, "author_profile": "https://Stackoverflow.com/users/3249399", "pm_score": 2, "selected": false, "text": "profile.set_preference('browser.helperApps.neverAsk.openFile', 'typeOfFile') \n# e.g. profile.set_preference('browser.helperApps.neverAsk.openFile', 'application/xml,application/octet-stream')\n from selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\n....\npass_field.send_keys(Keys.ENTER)\n\n#this is the point where the pop up appears\nWebDriverWait(driver, 5).until(EC.alert_is_present).dismiss()\nreqs = driver.requests\n...\n" }, { "answer_id": 74663242, "author": "Benjamin Woolston", "author_id": 20188398, "author_profile": "https://Stackoverflow.com/users/20188398", "pm_score": 0, "selected": false, "text": "# After navigating to the page that triggers the alert\nalert = driver.switch_to.alert\n\n# Use the alert methods to handle the alert as needed\nalert.accept() # This will accept the alert, launching the program\n# or\nalert.dismiss() # This will dismiss the alert, not launching the program\n# or\nalert.send_keys(\"some text\") # This will enter text in the alert and accept it\n from selenium.webdriver.firefox.options import Options\n\n# Set the unhandled_prompt_behavior option to dismiss\noptions = Options()\noptions.binary_location = r'C:\\Program Files\\Mozilla Firefox\\firefox.exe'\noptions.set_preference(\"security.external_protocol_requires_permission\", False)\noptions.unhandled_prompt_behavior = \"dismiss\"\ndriver = webdriver.Firefox(options=options)\n\n# Navigate to the page that triggers the alert\ndriver.get(url)\n\n# The alert should be automatically dismissed by the unhandled_prompt_behavior setting\n" }, { "answer_id": 74663448, "author": "Sahaj Raj Malla", "author_id": 11773575, "author_profile": "https://Stackoverflow.com/users/11773575", "pm_score": 0, "selected": false, "text": "# Go to the page\ndriver.get(url)\n\nuser_field = driver.find_element(\"id\", \"UserName\")\nuser_field.send_keys(username)\npass_field = driver.find_element(\"id\", \"Password\")\npass_field.send_keys(password)\npass_field.send_keys(Keys.ENTER)\n\n# Handle the alert by dismissing it\ndriver.switch_to.alert.dismiss()\n\n# Your script can continue running now\nreqs = driver.requests\n\nprint(\"Success!\")\ndriver.quit()\n\n from selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\n# Go to the page\ndriver.get(url)\n\nuser_field = driver.find_element(\"id\", \"UserName\")\nuser_field.send_keys(username)\npass_field = driver.find_element(\"id\", \"Password\")\npass_field.send_keys(password)\npass_field.send_keys(Keys.ENTER)\n\n# Wait for the alert to be dismissed before continuing\nWebDriverWait(driver, 10).until(EC.alert_is_not_present())\n\n# Your script can continue running now\nreqs = driver.requests\n\nprint(\"Success!\")\ndriver.quit()\n\n" }, { "answer_id": 74672939, "author": "Midas", "author_id": 20678816, "author_profile": "https://Stackoverflow.com/users/20678816", "pm_score": 0, "selected": false, "text": "from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.alerts import Alert\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\n# Create an instance of Firefox WebDriver\ndriver = webdriver.Firefox()\n\n# Go to the page\ndriver.get(url)\n\nuser_field = driver.find_element(By.ID, \"UserName\")\nuser_field.send_keys(username)\npass_field = driver.find_element(By.ID, \"Password\")\npass_field.send_keys(password)\npass_field.send_keys(Keys.ENTER)\n\n# Wait for the alert to be present and handle it\nWebDriverWait(driver, 10).until(EC.alert_is_present())\nalert = Alert(driver)\nalert.accept() # or alert.dismiss() to dismiss the alert\n\nreqs = driver.requests\n\nprint(\"Success!\")\ndriver.quit()\n" }, { "answer_id": 74677045, "author": "kppro", "author_id": 10955397, "author_profile": "https://Stackoverflow.com/users/10955397", "pm_score": 0, "selected": false, "text": "from selenium.webdriver import ActionChains, Keys\nfrom selenium.webdriver.firefox.options import Options\nfrom selenium.webdriver.common.alert import Alert\nfrom seleniumwire import webdriver\n\noptions = Options()\noptions.binary_location = r'C:\\Program Files\\Mozilla Firefox\\firefox.exe'\noptions.set_preference(\"security.external_protocol_requires_permission\", False)\ndriver = webdriver.Firefox(options=options)\n\n# Go to the page\ndriver.get(url)\n\nuser_field = driver.find_element(\"id\", \"UserName\")\nuser_field.send_keys(username)\npass_field = driver.find_element(\"id\", \"Password\")\npass_field.send_keys(password)\npass_field.send_keys(Keys.ENTER)\n\n# Handle the alert if it appears\ntry:\n alert = Alert(driver)\n alert.dismiss()\nexcept:\n pass\n\nreqs = driver.requests\n\nprint(\"Success!\")\ndriver.quit()\n from selenium.webdriver import ActionChains, Keys\nfrom selenium.webdriver.firefox.options import Options\nfrom seleniumwire import webdriver\n\noptions = Options()\noptions.binary_location = r'C:\\Program Files\\Mozilla Firefox\\firefox.exe'\ndriver = webdriver.Firefox(options=options)\n\n//Go to the page\ndriver.get(url)\n\nuser_field = driver.find_element(\"id\", \"UserName\")\nuser_field.send_keys(username)\npass_field = driver.find_element(\"id\", \"Password\")\npass_field.send_keys(password)\npass_field.send_keys(Keys.ENTER)\n\n//Use the execute_script() method to handle the alert\ndriver.execute_script(\"alert('This is an alert')\")\n\n//Continue with the script\nreqs = driver.requests\n\nprint(\"Success!\")\ndriver.quit()\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74563564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18810574/" ]
74,563,593
<p>I have the following code</p> <pre class="lang-py prettyprint-override"><code>conn_str = &quot;HostName=my_host.azure-devices.net;DeviceId=MY_DEVICE;SharedAccessKey=MY_KEY&quot; device_conn = IoTHubDeviceClient.create_from_connection_string(conn_str) await device_conn.connect() </code></pre> <p>This works fine, but only because I've manually retrieved this from the IoT hub and pasted it into the code. We are going to have hundreds of these devices, so is there a way to retrieve this connection string programmatically?</p> <p>It'll be the equivalent of the following</p> <pre><code>az iot hub device-identity connection-string show --device-id MY_DEVICCE --hub-name MY_HUB --subscription ABCD1234 </code></pre> <p>How do I do this?</p>
[ { "answer_id": 74565660, "author": "Omar.Ebrahim", "author_id": 2491027, "author_profile": "https://Stackoverflow.com/users/2491027", "pm_score": 0, "selected": false, "text": "from azure.iot.hub import IoTHubRegistryManager\nfrom azure.iot.device import IoTHubDeviceClient\n\n# HUB_HOST is YOURHOST.azure-devices.net\n# SHARED_ACCESS_KEY is from the registryReadWrite connection string\nreg_str = \"HostName={0};SharedAccessKeyName=registryReadWrite;SharedAccessKey={1}\".format(\n HUB_HOST, SHARED_ACCESS_KEY)\n\ndevice = IoTHubRegistryManager(reg_str).get_device(\"MY_DEVICE_ID\")\ndevice_key = device.authentication.symmetric_key.primary_key\nconn_str = \"HostName={0};DeviceId={1};SharedAccessKey={2}\".format(\n HUB_HOST, \"MY_DEVICE_ID\", device_key)\n\nclient = IoTHubDeviceClient.create_from_connection_string(\n conn_str)\n\nclient.connect()\n\n# Remaining code here...\n" }, { "answer_id": 74567284, "author": "neo", "author_id": 7093617, "author_profile": "https://Stackoverflow.com/users/7093617", "pm_score": 1, "selected": false, "text": "create_from_symmetric_key(symmetric_key, hostname, device_id, **kwargs)" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74563593", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2491027/" ]
74,563,617
<p>hi everyone im new to rails, I am trying to make a query using 3 parameters</p> <pre><code> def zones_by_container container_id= params[:container_id] start_time = params[:start_time_at] end_time = params[:end_time_at] container =Container.find(container_id) @Zone = Zone.where(customer: container.customer_id,container: container_id, start_time_at: start_time..end_time).select('address, start_time_at, end_time_at, notified_at, end_time_at - start_time_at as `Time`').as_json(:except =&gt; :id) render json: { status: 'Success',data: @zone} end </code></pre> <p>I would like the subtraction of the dates to return it in seconds in my query This is an example of my query with the two parameters</p> <pre><code> { &quot;start_time_at&quot;: &quot;2022-11-24 10:10:16&quot;, &quot;end_time_at&quot;: &quot;2022-11-24 10:11:20&quot;, &quot;Time&quot;: 104 }, </code></pre> <p>I want the result to look like this</p> <pre><code> { &quot;start_time_at&quot;: &quot;2022-11-24 10:10:16&quot;, &quot;end_time_at&quot;: &quot;2022-11-24 10:11:20&quot;, &quot;Time&quot;: 64 }, </code></pre> <p>Could someone help me so that the subtraction of the two dates comes out in seconds, I have searched and I did not find how to solve this problem</p>
[ { "answer_id": 74565721, "author": "Clark", "author_id": 8655457, "author_profile": "https://Stackoverflow.com/users/8655457", "pm_score": -1, "selected": false, "text": "(start_date_time - end_date_time).to_f\n" }, { "answer_id": 74566984, "author": "Alter Lagos", "author_id": 895789, "author_profile": "https://Stackoverflow.com/users/895789", "pm_score": 0, "selected": false, "text": "select('UNIX_TIMESTAMP(end_time_at) - UNIX_TIMESTAMP(start_time_at) as time')\n" }, { "answer_id": 74653604, "author": "Themis Nikellis", "author_id": 20598698, "author_profile": "https://Stackoverflow.com/users/20598698", "pm_score": 0, "selected": false, "text": "now = Time.now => 2022-12-02 11:31:50.677627 +0200 \ntomorrow = Time.now + 24.hours => 2022-12-03 11:32:05.119234 +0200 \nresult_in_seconds = tomorrow - now => 86414.441607 \n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74563617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18738032/" ]
74,563,630
<p>I am trying to extend Stack a little bit down to create room for &quot;All caught up&quot; text.</p> <p>Here is my code;</p> <pre><code> return Stack( children: [ buildListView(scrollController), buildBackToTop(scrollController, backtoTop), buildBottomReached(isLastIndex), ], ); </code></pre> <pre><code>Widget buildBackToTop(ScrollController scrollController, bool backtoTop) { if (backtoTop) { return Align( alignment: Alignment.topCenter, child: Padding( padding: const EdgeInsets.all(8.0), child: FloatingActionButton.extended( onPressed: () { scrollController.animateTo(0, duration: const Duration(milliseconds: 200), curve: Curves.linear); }, label: const Text(&quot;Back to Top&quot;), ), ), ); } else { return const SizedBox(); } } </code></pre> <pre><code>Widget buildBottomReached(bool isLastIndex) { if (isLastIndex) { return const Align( alignment: Alignment.bottomCenter, child: Text( &quot;All caught up &quot;, style: TextStyle( color: Colors.blue, fontWeight: FontWeight.bold, fontSize: 20.00), ), ); } else { return const SizedBox(); } } </code></pre> <pre><code>Widget buildListView(ScrollController scrollController) { return ListView.builder( controller: scrollController, itemCount: 50, itemBuilder: (context, index) { return SizedBox( width: 20, child: Padding( padding: const EdgeInsets.all(8.0), child: Container( width: 20, decoration: BoxDecoration( border: Border.all(color: Colors.black), color: Colors.grey[100], ), child: Center( child: Align( alignment: Alignment.centerLeft, child: Padding( padding: const EdgeInsets.all(8.0), child: Text(&quot;Index $index&quot;), ), ), ), ), ), ); }, physics: const BouncingScrollPhysics()); } </code></pre> <p><a href="https://i.stack.imgur.com/oI6sV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oI6sV.png" alt="enter image description here" /></a></p> <p>When I do following,</p> <pre><code> return Stack( children: [ Padding( padding: const EdgeInsets.only(bottom: 30), child: buildListView(scrollController), ), buildBackToTop(scrollController, backtoTop), buildBottomReached(isLastIndex), ], ); </code></pre> <p>This is desired but it adds whitespace to bottom all the time,</p> <p><a href="https://i.stack.imgur.com/lBehY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lBehY.png" alt="enter image description here" /></a> <a href="https://i.stack.imgur.com/S0S5k.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/S0S5k.png" alt="enter image description here" /></a></p> <p>Is there a way to do this?</p>
[ { "answer_id": 74565721, "author": "Clark", "author_id": 8655457, "author_profile": "https://Stackoverflow.com/users/8655457", "pm_score": -1, "selected": false, "text": "(start_date_time - end_date_time).to_f\n" }, { "answer_id": 74566984, "author": "Alter Lagos", "author_id": 895789, "author_profile": "https://Stackoverflow.com/users/895789", "pm_score": 0, "selected": false, "text": "select('UNIX_TIMESTAMP(end_time_at) - UNIX_TIMESTAMP(start_time_at) as time')\n" }, { "answer_id": 74653604, "author": "Themis Nikellis", "author_id": 20598698, "author_profile": "https://Stackoverflow.com/users/20598698", "pm_score": 0, "selected": false, "text": "now = Time.now => 2022-12-02 11:31:50.677627 +0200 \ntomorrow = Time.now + 24.hours => 2022-12-03 11:32:05.119234 +0200 \nresult_in_seconds = tomorrow - now => 86414.441607 \n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74563630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/929902/" ]
74,563,667
<p>I wanted to comment on this post: <a href="https://stackoverflow.com/questions/72121038/i-want-to-trigger-azure-datafactory-pipeline-whenever-there-is-a-change-in-azure">I want to trigger Azure datafactory pipeline whenever there is a change in Azure SQL database</a></p> <p>but I don't have enough reputation...</p> <p>The solution that Skin comes up with (SQL DB trigger events) looks exactly like what I'm after but I can't find any further documentation on it - in fact the only references I've found say that this functionality <em><strong>doesn't</strong></em> exist?</p> <p>Can anyone point me to anything online - or a book - that could help?</p> <p>Cheers</p>
[ { "answer_id": 74565721, "author": "Clark", "author_id": 8655457, "author_profile": "https://Stackoverflow.com/users/8655457", "pm_score": -1, "selected": false, "text": "(start_date_time - end_date_time).to_f\n" }, { "answer_id": 74566984, "author": "Alter Lagos", "author_id": 895789, "author_profile": "https://Stackoverflow.com/users/895789", "pm_score": 0, "selected": false, "text": "select('UNIX_TIMESTAMP(end_time_at) - UNIX_TIMESTAMP(start_time_at) as time')\n" }, { "answer_id": 74653604, "author": "Themis Nikellis", "author_id": 20598698, "author_profile": "https://Stackoverflow.com/users/20598698", "pm_score": 0, "selected": false, "text": "now = Time.now => 2022-12-02 11:31:50.677627 +0200 \ntomorrow = Time.now + 24.hours => 2022-12-03 11:32:05.119234 +0200 \nresult_in_seconds = tomorrow - now => 86414.441607 \n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74563667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10524320/" ]
74,563,676
<p>I am developing a microsoft Teams App. I did a React JS project before starting the Teams app (which is pretty much the same thing) and I had not issues everything was working well. My problem is whenever I try to call a hook in a useEffect function it's not working in my teams App but it was in my other React.js project.</p> <p>The console tells me: &quot;Hooks can only be called inside of the body of a function component&quot;.</p> <p>I am using react 16.14 btw.</p> <p>App.js file</p> <pre><code>import React, { useEffect, useState } from &quot;react&quot;; import { Container, AppBar, Typography, Grow, Grid } from '@material-ui/core'; import { useDispatch } from 'react-redux'; import logo_digiposte from './images/logo_digiposte.png' import { getContractors } from &quot;./actions/contractors&quot;; import useStyle from './styles' import Form from './components/Form/Form'; import Contractors from &quot;./components/Contractors/Contractors&quot;; const App = () =&gt; { const [currentId, setCurrentId] = useState(0); const classes = useStyle(); const dispatch = useDispatch; /*useEffect(() =&gt; { dispatch(getContractors()); },[currentId, dispatch])*/ useEffect(() =&gt; { dispatch(getContractors()); }, [dispatch]); return ( &lt;Container&gt; &lt;AppBar className={classes.appBar} position=&quot;static&quot; color=&quot;inherit&quot;&gt; &lt;Typography variant=&quot;h2&quot; className={classes.heading} align='center'&gt;Digiposte&lt;/Typography&gt; &lt;img src={logo_digiposte} className={classes.image} alt=&quot;digiposte&quot; height=&quot;60&quot;/&gt; &lt;/AppBar&gt; &lt;Grow in&gt; &lt;Container&gt; &lt;Grid container className={classes.mainContainer} justifyContent=&quot;space-between&quot; alignItems=&quot;stretch&quot; spacing={3}&gt; &lt;Grid item xs={12} sm={7}&gt; &lt;Contractors /&gt; &lt;/Grid&gt; &lt;Grid item xs={12} sm={4}&gt; &lt;Form /&gt; &lt;/Grid&gt; &lt;/Grid&gt; &lt;/Container&gt; &lt;/Grow&gt; &lt;/Container&gt; ) } export default App; </code></pre> <p>folder which contains the getContractor function</p> <pre><code>import { FETCH_ALL, CREATE, UPDATE, DELETE } from &quot;../constants/actionTypes&quot;; import * as api from '../api/index.jsx'; export const getContractors = () =&gt; async (dispatch) =&gt; { try { const { data } = await api.fetchContractors(); dispatch({ type: FETCH_ALL, payload: data }); } catch (error) { console.log(error); } } </code></pre> <p>api file:</p> <pre><code>import axios from 'axios' const url = &quot;http://localhost:5003/contractors&quot;; export const fetchContractors = () =&gt; axios.get(url); </code></pre>
[ { "answer_id": 74565721, "author": "Clark", "author_id": 8655457, "author_profile": "https://Stackoverflow.com/users/8655457", "pm_score": -1, "selected": false, "text": "(start_date_time - end_date_time).to_f\n" }, { "answer_id": 74566984, "author": "Alter Lagos", "author_id": 895789, "author_profile": "https://Stackoverflow.com/users/895789", "pm_score": 0, "selected": false, "text": "select('UNIX_TIMESTAMP(end_time_at) - UNIX_TIMESTAMP(start_time_at) as time')\n" }, { "answer_id": 74653604, "author": "Themis Nikellis", "author_id": 20598698, "author_profile": "https://Stackoverflow.com/users/20598698", "pm_score": 0, "selected": false, "text": "now = Time.now => 2022-12-02 11:31:50.677627 +0200 \ntomorrow = Time.now + 24.hours => 2022-12-03 11:32:05.119234 +0200 \nresult_in_seconds = tomorrow - now => 86414.441607 \n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74563676", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14543939/" ]
74,563,711
<p>I have a scenario where I need to do the following:</p> <ol> <li>Read data from pubsub</li> <li>Apply multiple Transformations to the data.</li> <li>Persist the PCollection in multiple Google Big Query based on some config.</li> </ol> <p>My question is how can I write data to multiple big query tables.</p> <p>I searched for multiple bq writes using apache beam but could not find any solution</p>
[ { "answer_id": 74564012, "author": "Mazlum Tosun", "author_id": 9261558, "author_profile": "https://Stackoverflow.com/users/9261558", "pm_score": 1, "selected": false, "text": "Beam Python def map1(self, element):\n ...\n\ndef map2(self, element):\n ...\n\ndef map3(self, element):\n ...\n\ndef main() -> None:\n logging.getLogger().setLevel(logging.INFO)\n\n your_options = PipelineOptions().view_as(YourOptions)\n pipeline_options = PipelineOptions()\n\n with beam.Pipeline(options=pipeline_options) as p:\n\n result_pcollection = (\n p \n | 'Read from pub sub' >> ReadFromPubSub(subscription='input_subscription') \n | 'Map 1' >> beam.Map(map1)\n | 'Map 2' >> beam.Map(map2)\n | 'Map 3' >> beam.Map(map3)\n )\n\n (result_pcollection |\n 'Write to BQ table 1' >> beam.io.WriteToBigQuery(\n project='project_id',\n dataset='dataset',\n table='table1',\n method='STREAMING_INSERTS',\n write_disposition=beam.io.BigQueryDisposition.WRITE_APPEND,\n create_disposition=beam.io.BigQueryDisposition.CREATE_NEVER))\n\n (result_pcollection |\n 'Write to BQ table 2' >> beam.io.WriteToBigQuery(\n project='project_id',\n dataset='dataset',\n table='table2',\n method='STREAMING_INSERTS',\n write_disposition=beam.io.BigQueryDisposition.WRITE_APPEND,\n create_disposition=beam.io.BigQueryDisposition.CREATE_NEVER))\n\n (result_pcollection_pub_sub |\n 'Write to BQ table 3' >> beam.io.WriteToBigQuery(\n project='project_id',\n dataset='dataset',\n table='table3',\n method='STREAMING_INSERTS',\n write_disposition=beam.io.BigQueryDisposition.WRITE_APPEND,\n create_disposition=beam.io.BigQueryDisposition.CREATE_NEVER))\n\n\nif __name__ == \"__main__\":\n main()\n PCollection PubSub PCollection Bigquery res = Flow \n=> Map 1\n=> Map 2\n=> Map 3\n\nres => Sink result to BQ table 1 with `BigqueryIO`\nres => Sink result to BQ table 2 with `BigqueryIO`\nres => Sink result to BQ table 3 with `BigqueryIO`\n STREAMING_INSERT Bigquery" }, { "answer_id": 74570213, "author": "Rathish Kumar B", "author_id": 2156784, "author_profile": "https://Stackoverflow.com/users/2156784", "pm_score": 0, "selected": false, "text": "import apache_beam as beam\nfrom apache_beam.options.pipeline_options import PipelineOptions,...\nfrom apache_beam.io.gcp.internal.clients import bigquery\n\nclass TaggedData(beam.DoFn):\n def process(self, element):\n try:\n # filter here\n if(element[\"country\"] == \"in\")\n yield {\"indiaelements:taggedasindia\"}\n if(element[\"country\"] == \"usa\")\n yield {\"usaelements:taggedasusa\"}\n \n ...\n except:\n yield {\"taggedasunprocessed\"}\n\ndef addAadhar(element):\n \"Filtered messages - only India\"\n yield \"elementwithAadhar\"\n\ndef addSSN(element):\n \"Filtered messages - only USA\"\n yield \"elementwithSSN\"\n\np = beam.Pipeline(options=options)\n \nmessages = (\n p\n | \"ReadFromPubSub\" >> ...\n | \"Tagging >> \"beam.ParDo(TaggedData()).with_outputs('usa', 'india', 'oceania', ...) \n )\n\nindia_messages = (\n messages.india \n | \"AddAdhar\" >> ...\n | \"WriteIndiamsgToBQ\" >> streaming inserts\n )\n\nusa_messages = (\n messages.usa\n | \"AddSSN\" >> ...\n | \"WriteUSAmsgToBQ\" >> streaming inserts\n )\n\noceania_messages = (\n messages.oceania\n | \"DoNothing&WriteUSAmsgToBQ\" >> streaming inserts\n )\n\ndeadletter = (\n (messages.unprocessed, stage1.failed, stage2.failed)\n | \"CombineAllFailed\" >> Flatn...\n | \"WriteUnprocessed/InvalidMessagesToBQ\" >> streaminginserts...\n) \n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74563711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17359564/" ]
74,563,717
<p>I use TS and now i have to put stuff in my Router and I don't know what.</p> <p>index.js:</p> <pre><code>import { Router, useLocation } from &quot;react-router-dom&quot;; const root = ReactDOM.createRoot( document.getElementById(&quot;root&quot;) as HTMLElement ); const location = useLocation() root.render( &lt;React.StrictMode&gt; &lt;Router location={????????} navigator={?????????} &gt; &lt;App /&gt; &lt;/Router&gt; &lt;/React.StrictMode&gt; ); reportWebVitals(); </code></pre> <p>App.js:</p> <pre class="lang-js prettyprint-override"><code> function App() { return ( &lt;&gt; &lt;Navbar /&gt; &lt;Routes &gt; &lt;Route path=&quot;/&quot; element={&lt;Home /&gt;} /&gt; &lt;Route path=&quot;Portfolio/:portfolioId&quot; element={&lt;SingleShooting /&gt;} /&gt; ... &lt;/Routes&gt; &lt;/&gt; ); } </code></pre> <p>WHat do I have to put in?</p> <p><em>Type '{ children: Element; }' is missing the following properties from type 'RouterProps': location, navigatorts(2739)</em></p> <p>(I want to do this, because of this: <a href="https://stackoverflow.com/questions/67974970/animate-presence-exit-not-working-framer-motion">Animate Presence exit not working framer motion</a>)</p>
[ { "answer_id": 74564012, "author": "Mazlum Tosun", "author_id": 9261558, "author_profile": "https://Stackoverflow.com/users/9261558", "pm_score": 1, "selected": false, "text": "Beam Python def map1(self, element):\n ...\n\ndef map2(self, element):\n ...\n\ndef map3(self, element):\n ...\n\ndef main() -> None:\n logging.getLogger().setLevel(logging.INFO)\n\n your_options = PipelineOptions().view_as(YourOptions)\n pipeline_options = PipelineOptions()\n\n with beam.Pipeline(options=pipeline_options) as p:\n\n result_pcollection = (\n p \n | 'Read from pub sub' >> ReadFromPubSub(subscription='input_subscription') \n | 'Map 1' >> beam.Map(map1)\n | 'Map 2' >> beam.Map(map2)\n | 'Map 3' >> beam.Map(map3)\n )\n\n (result_pcollection |\n 'Write to BQ table 1' >> beam.io.WriteToBigQuery(\n project='project_id',\n dataset='dataset',\n table='table1',\n method='STREAMING_INSERTS',\n write_disposition=beam.io.BigQueryDisposition.WRITE_APPEND,\n create_disposition=beam.io.BigQueryDisposition.CREATE_NEVER))\n\n (result_pcollection |\n 'Write to BQ table 2' >> beam.io.WriteToBigQuery(\n project='project_id',\n dataset='dataset',\n table='table2',\n method='STREAMING_INSERTS',\n write_disposition=beam.io.BigQueryDisposition.WRITE_APPEND,\n create_disposition=beam.io.BigQueryDisposition.CREATE_NEVER))\n\n (result_pcollection_pub_sub |\n 'Write to BQ table 3' >> beam.io.WriteToBigQuery(\n project='project_id',\n dataset='dataset',\n table='table3',\n method='STREAMING_INSERTS',\n write_disposition=beam.io.BigQueryDisposition.WRITE_APPEND,\n create_disposition=beam.io.BigQueryDisposition.CREATE_NEVER))\n\n\nif __name__ == \"__main__\":\n main()\n PCollection PubSub PCollection Bigquery res = Flow \n=> Map 1\n=> Map 2\n=> Map 3\n\nres => Sink result to BQ table 1 with `BigqueryIO`\nres => Sink result to BQ table 2 with `BigqueryIO`\nres => Sink result to BQ table 3 with `BigqueryIO`\n STREAMING_INSERT Bigquery" }, { "answer_id": 74570213, "author": "Rathish Kumar B", "author_id": 2156784, "author_profile": "https://Stackoverflow.com/users/2156784", "pm_score": 0, "selected": false, "text": "import apache_beam as beam\nfrom apache_beam.options.pipeline_options import PipelineOptions,...\nfrom apache_beam.io.gcp.internal.clients import bigquery\n\nclass TaggedData(beam.DoFn):\n def process(self, element):\n try:\n # filter here\n if(element[\"country\"] == \"in\")\n yield {\"indiaelements:taggedasindia\"}\n if(element[\"country\"] == \"usa\")\n yield {\"usaelements:taggedasusa\"}\n \n ...\n except:\n yield {\"taggedasunprocessed\"}\n\ndef addAadhar(element):\n \"Filtered messages - only India\"\n yield \"elementwithAadhar\"\n\ndef addSSN(element):\n \"Filtered messages - only USA\"\n yield \"elementwithSSN\"\n\np = beam.Pipeline(options=options)\n \nmessages = (\n p\n | \"ReadFromPubSub\" >> ...\n | \"Tagging >> \"beam.ParDo(TaggedData()).with_outputs('usa', 'india', 'oceania', ...) \n )\n\nindia_messages = (\n messages.india \n | \"AddAdhar\" >> ...\n | \"WriteIndiamsgToBQ\" >> streaming inserts\n )\n\nusa_messages = (\n messages.usa\n | \"AddSSN\" >> ...\n | \"WriteUSAmsgToBQ\" >> streaming inserts\n )\n\noceania_messages = (\n messages.oceania\n | \"DoNothing&WriteUSAmsgToBQ\" >> streaming inserts\n )\n\ndeadletter = (\n (messages.unprocessed, stage1.failed, stage2.failed)\n | \"CombineAllFailed\" >> Flatn...\n | \"WriteUnprocessed/InvalidMessagesToBQ\" >> streaminginserts...\n) \n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74563717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19749827/" ]
74,563,753
<p>I want to use <strong>Playwright</strong> for local visual regression testing. The problem is I have <strong>ReactQuery Devtools</strong> installed and so my visual snapshots all have that open and displayed, covering up a bunch of the content I want to protect against visual regressions. <a href="https://i.stack.imgur.com/nDDBz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nDDBz.png" alt="ReactQuery Devtools" /></a></p> <p>I could make it so the test clicks the close button. That would mean I only get the little ReactQuery icon displayed, but if these tests work well I may want to use them in CI, so I don't really want any visual discrepancies between local and CI renders.</p> <p>What I'm wondering is if there's something I could put in my test to disable the Devtools even though <code>process.env.NODE_ENV === 'development'</code>.</p> <p>Note: I tried launching the tests, and the dev server with the NODE_ENV environment variable set to <code>testing</code>. NextJS warned me that was a bad idea, and it did nothing to help :/</p>
[ { "answer_id": 74564012, "author": "Mazlum Tosun", "author_id": 9261558, "author_profile": "https://Stackoverflow.com/users/9261558", "pm_score": 1, "selected": false, "text": "Beam Python def map1(self, element):\n ...\n\ndef map2(self, element):\n ...\n\ndef map3(self, element):\n ...\n\ndef main() -> None:\n logging.getLogger().setLevel(logging.INFO)\n\n your_options = PipelineOptions().view_as(YourOptions)\n pipeline_options = PipelineOptions()\n\n with beam.Pipeline(options=pipeline_options) as p:\n\n result_pcollection = (\n p \n | 'Read from pub sub' >> ReadFromPubSub(subscription='input_subscription') \n | 'Map 1' >> beam.Map(map1)\n | 'Map 2' >> beam.Map(map2)\n | 'Map 3' >> beam.Map(map3)\n )\n\n (result_pcollection |\n 'Write to BQ table 1' >> beam.io.WriteToBigQuery(\n project='project_id',\n dataset='dataset',\n table='table1',\n method='STREAMING_INSERTS',\n write_disposition=beam.io.BigQueryDisposition.WRITE_APPEND,\n create_disposition=beam.io.BigQueryDisposition.CREATE_NEVER))\n\n (result_pcollection |\n 'Write to BQ table 2' >> beam.io.WriteToBigQuery(\n project='project_id',\n dataset='dataset',\n table='table2',\n method='STREAMING_INSERTS',\n write_disposition=beam.io.BigQueryDisposition.WRITE_APPEND,\n create_disposition=beam.io.BigQueryDisposition.CREATE_NEVER))\n\n (result_pcollection_pub_sub |\n 'Write to BQ table 3' >> beam.io.WriteToBigQuery(\n project='project_id',\n dataset='dataset',\n table='table3',\n method='STREAMING_INSERTS',\n write_disposition=beam.io.BigQueryDisposition.WRITE_APPEND,\n create_disposition=beam.io.BigQueryDisposition.CREATE_NEVER))\n\n\nif __name__ == \"__main__\":\n main()\n PCollection PubSub PCollection Bigquery res = Flow \n=> Map 1\n=> Map 2\n=> Map 3\n\nres => Sink result to BQ table 1 with `BigqueryIO`\nres => Sink result to BQ table 2 with `BigqueryIO`\nres => Sink result to BQ table 3 with `BigqueryIO`\n STREAMING_INSERT Bigquery" }, { "answer_id": 74570213, "author": "Rathish Kumar B", "author_id": 2156784, "author_profile": "https://Stackoverflow.com/users/2156784", "pm_score": 0, "selected": false, "text": "import apache_beam as beam\nfrom apache_beam.options.pipeline_options import PipelineOptions,...\nfrom apache_beam.io.gcp.internal.clients import bigquery\n\nclass TaggedData(beam.DoFn):\n def process(self, element):\n try:\n # filter here\n if(element[\"country\"] == \"in\")\n yield {\"indiaelements:taggedasindia\"}\n if(element[\"country\"] == \"usa\")\n yield {\"usaelements:taggedasusa\"}\n \n ...\n except:\n yield {\"taggedasunprocessed\"}\n\ndef addAadhar(element):\n \"Filtered messages - only India\"\n yield \"elementwithAadhar\"\n\ndef addSSN(element):\n \"Filtered messages - only USA\"\n yield \"elementwithSSN\"\n\np = beam.Pipeline(options=options)\n \nmessages = (\n p\n | \"ReadFromPubSub\" >> ...\n | \"Tagging >> \"beam.ParDo(TaggedData()).with_outputs('usa', 'india', 'oceania', ...) \n )\n\nindia_messages = (\n messages.india \n | \"AddAdhar\" >> ...\n | \"WriteIndiamsgToBQ\" >> streaming inserts\n )\n\nusa_messages = (\n messages.usa\n | \"AddSSN\" >> ...\n | \"WriteUSAmsgToBQ\" >> streaming inserts\n )\n\noceania_messages = (\n messages.oceania\n | \"DoNothing&WriteUSAmsgToBQ\" >> streaming inserts\n )\n\ndeadletter = (\n (messages.unprocessed, stage1.failed, stage2.failed)\n | \"CombineAllFailed\" >> Flatn...\n | \"WriteUnprocessed/InvalidMessagesToBQ\" >> streaminginserts...\n) \n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74563753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/201436/" ]
74,563,758
<p>the question is I have this column with 1-11 for education. I try to make a new column which can make 1,2 as 1. 3,4,5,6 as 2. 7,8,9,10,11 as 3.</p> <p>this is my code for dummy, like I get it if is not 1 then 0.</p> <pre><code>data_3$Relate&lt;-ifelse(data_3$Relation &gt;2,1,0); </code></pre> <p>but how to deal with the multiple conditon, like more than 1, 0 condition.</p> <pre><code>data_3$Education&lt;-ifelse(data_3$education&lt;3,'1') </code></pre> <p>??</p>
[ { "answer_id": 74564012, "author": "Mazlum Tosun", "author_id": 9261558, "author_profile": "https://Stackoverflow.com/users/9261558", "pm_score": 1, "selected": false, "text": "Beam Python def map1(self, element):\n ...\n\ndef map2(self, element):\n ...\n\ndef map3(self, element):\n ...\n\ndef main() -> None:\n logging.getLogger().setLevel(logging.INFO)\n\n your_options = PipelineOptions().view_as(YourOptions)\n pipeline_options = PipelineOptions()\n\n with beam.Pipeline(options=pipeline_options) as p:\n\n result_pcollection = (\n p \n | 'Read from pub sub' >> ReadFromPubSub(subscription='input_subscription') \n | 'Map 1' >> beam.Map(map1)\n | 'Map 2' >> beam.Map(map2)\n | 'Map 3' >> beam.Map(map3)\n )\n\n (result_pcollection |\n 'Write to BQ table 1' >> beam.io.WriteToBigQuery(\n project='project_id',\n dataset='dataset',\n table='table1',\n method='STREAMING_INSERTS',\n write_disposition=beam.io.BigQueryDisposition.WRITE_APPEND,\n create_disposition=beam.io.BigQueryDisposition.CREATE_NEVER))\n\n (result_pcollection |\n 'Write to BQ table 2' >> beam.io.WriteToBigQuery(\n project='project_id',\n dataset='dataset',\n table='table2',\n method='STREAMING_INSERTS',\n write_disposition=beam.io.BigQueryDisposition.WRITE_APPEND,\n create_disposition=beam.io.BigQueryDisposition.CREATE_NEVER))\n\n (result_pcollection_pub_sub |\n 'Write to BQ table 3' >> beam.io.WriteToBigQuery(\n project='project_id',\n dataset='dataset',\n table='table3',\n method='STREAMING_INSERTS',\n write_disposition=beam.io.BigQueryDisposition.WRITE_APPEND,\n create_disposition=beam.io.BigQueryDisposition.CREATE_NEVER))\n\n\nif __name__ == \"__main__\":\n main()\n PCollection PubSub PCollection Bigquery res = Flow \n=> Map 1\n=> Map 2\n=> Map 3\n\nres => Sink result to BQ table 1 with `BigqueryIO`\nres => Sink result to BQ table 2 with `BigqueryIO`\nres => Sink result to BQ table 3 with `BigqueryIO`\n STREAMING_INSERT Bigquery" }, { "answer_id": 74570213, "author": "Rathish Kumar B", "author_id": 2156784, "author_profile": "https://Stackoverflow.com/users/2156784", "pm_score": 0, "selected": false, "text": "import apache_beam as beam\nfrom apache_beam.options.pipeline_options import PipelineOptions,...\nfrom apache_beam.io.gcp.internal.clients import bigquery\n\nclass TaggedData(beam.DoFn):\n def process(self, element):\n try:\n # filter here\n if(element[\"country\"] == \"in\")\n yield {\"indiaelements:taggedasindia\"}\n if(element[\"country\"] == \"usa\")\n yield {\"usaelements:taggedasusa\"}\n \n ...\n except:\n yield {\"taggedasunprocessed\"}\n\ndef addAadhar(element):\n \"Filtered messages - only India\"\n yield \"elementwithAadhar\"\n\ndef addSSN(element):\n \"Filtered messages - only USA\"\n yield \"elementwithSSN\"\n\np = beam.Pipeline(options=options)\n \nmessages = (\n p\n | \"ReadFromPubSub\" >> ...\n | \"Tagging >> \"beam.ParDo(TaggedData()).with_outputs('usa', 'india', 'oceania', ...) \n )\n\nindia_messages = (\n messages.india \n | \"AddAdhar\" >> ...\n | \"WriteIndiamsgToBQ\" >> streaming inserts\n )\n\nusa_messages = (\n messages.usa\n | \"AddSSN\" >> ...\n | \"WriteUSAmsgToBQ\" >> streaming inserts\n )\n\noceania_messages = (\n messages.oceania\n | \"DoNothing&WriteUSAmsgToBQ\" >> streaming inserts\n )\n\ndeadletter = (\n (messages.unprocessed, stage1.failed, stage2.failed)\n | \"CombineAllFailed\" >> Flatn...\n | \"WriteUnprocessed/InvalidMessagesToBQ\" >> streaminginserts...\n) \n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74563758", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20515084/" ]
74,563,767
<p>I have a php input filter that cleans all unwanted characters from a string. This:</p> <pre><code>$clean = preg_replace(&quot;/[^a-z0-9 \.\-\&quot;_',]/i&quot;, &quot;&quot;, $string); </code></pre> <p>This works fine, but I also what to preserve all character returns in the string. I've tried different things like adding '\n\r' or '\R' or '\n\r' to the list of characters in the brackets or adding '/m' to the flag. I'm just not finding the right combo. Any suggestions?</p>
[ { "answer_id": 74563810, "author": "Xlang", "author_id": 20592654, "author_profile": "https://Stackoverflow.com/users/20592654", "pm_score": 0, "selected": false, "text": "$clean = preg_replace(\"/[^a-z0-9 \\.\\-\\\"_',\\p{C}]/i\", \"\", $string);\n" }, { "answer_id": 74565100, "author": "Wiktor Stribiżew", "author_id": 3832970, "author_profile": "https://Stackoverflow.com/users/3832970", "pm_score": 3, "selected": true, "text": "$clean = preg_replace(\"/[^a-z0-9 .\\\"_',\\r\\n-]/i\", \"\", $string);\n \\r\\n -" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74563767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6780939/" ]
74,563,854
<p>I am attempting to combine elements of a dataframe into a nested list. Say I have the following:</p> <pre><code>df = pd.DataFrame(np.random.randn(100,4), columns=list('abcd')) df.head(4) a b c d 0 0.455258 1.135895 0.573383 -0.637943 1 0.262079 -0.397168 -0.980062 -1.600837 2 0.921582 0.767232 -0.298590 -0.159964 3 -0.645110 -0.709058 1.223899 0.382212 </code></pre> <p>Then, I would like to create a fifth column e that looks like:</p> <pre><code> a b c d e 0 0.455258 1.135895 0.573383 -0.637943 [[0.455258 1.135895 0.573383 -0.637943]] 1 0.262079 -0.397168 -0.980062 -1.600837 [[0.262079 -0.397168 -0.980062 -1.600837]] 2 0.921582 0.767232 -0.298590 -0.159964 [[0.921582 0.767232 -0.298590 -0.159964]] 3 -0.645110 -0.709058 1.223899 0.382212 [[-0.645110 -0.709058 1.223899 0.382212]] </code></pre> <p>efficiently.</p> <p>My most efficient but wrong guess so far has been to do</p> <pre><code>df['e'] = df.values.tolist() </code></pre> <p>But that just results in:</p> <pre><code> a b c d e 0 0.455258 1.135895 0.573383 -0.637943 [0.455258 1.135895 0.573383 -0.637943] 1 0.262079 -0.397168 -0.980062 -1.600837 [0.262079 -0.397168 -0.980062 -1.600837] 2 0.921582 0.767232 -0.298590 -0.159964 [0.921582 0.767232 -0.298590 -0.159964] 3 -0.645110 -0.709058 1.223899 0.382212 [-0.645110 -0.709058 1.223899 0.382212] </code></pre> <p>My least efficient but correct guess has been:</p> <pre><code>a = [] for index, row in df.iterrows(): a.append([[row['a'],row['b'],row['c'],row['d']]]) </code></pre> <p>Is there a better way?</p>
[ { "answer_id": 74563910, "author": "to_data", "author_id": 18317391, "author_profile": "https://Stackoverflow.com/users/18317391", "pm_score": 0, "selected": false, "text": "df[\"e\"]=df.apply(lambda x:[[x[column] for column in df.columns]],axis=1)\n" }, { "answer_id": 74564023, "author": "PaulS", "author_id": 11564487, "author_profile": "https://Stackoverflow.com/users/11564487", "pm_score": 2, "selected": true, "text": "df['e'] = df.values.tolist()\ndf['e'] = df['e'].map(lambda x: [x])\n a b c d \\\n0 -1.594129 1.692562 0.602186 -1.620295 \n1 -0.561567 -0.033658 -1.259215 1.054229 \n2 0.450852 -0.483194 0.126173 0.354781 \n3 2.060968 -0.428400 -0.973516 -0.201786 \n4 -0.977307 -0.123215 -1.494138 -0.175432 \n\n e \n0 [[-1.5941291794267378, 1.6925620764107292, 0.6... \n1 [[-0.5615669341251519, -0.03365818317800309, -... \n2 [[0.45085184068754164, -0.48319360005444034, 0... \n3 [[2.0609676606685086, -0.42839969840552594, -0... \n4 [[-0.9773067339895964, -0.12321466907036417, -... \n" }, { "answer_id": 74564090, "author": "Scott Boston", "author_id": 6361531, "author_profile": "https://Stackoverflow.com/users/6361531", "pm_score": 1, "selected": false, "text": "np.array_split df['e'] = np.array_split(df.to_numpy(), df.shape[0], axis=0)\n a b c d e\n0 -0.164745 -0.498313 -0.247778 -1.531003 [[-0.16474534230721335, -0.49831346259483156, ...\n1 0.079485 0.125790 0.002755 -0.182361 [[0.0794845071834397, 0.12579014367640728, 0.0...\n2 0.790263 0.488152 -0.752555 0.432949 [[0.790263001866772, 0.48815219760288764, -0.7...\n3 -0.139499 -1.493593 -1.708668 -2.495497 [[-0.13949904491921675, -1.493593498340277, -1...\n4 2.662431 0.247559 -0.949407 2.746299 [[2.662430989009563, 0.2475588133223812, -0.94...\n.. ... ... ... ... ...\n95 0.252663 1.018614 -0.491736 -0.290786 [[0.252663350866794, 1.018613617727022, -0.491...\n96 1.023089 -0.367463 0.437327 -0.017441 [[1.0230888404185123, -0.3674628009130751, 0.4...\n97 0.571278 0.450803 0.441102 1.176884 [[0.5712775025212533, 0.4508029251387083, 0.44...\n98 1.336477 0.166516 0.408941 0.972896 [[1.3364769455886123, 0.16651649771088423, 0.4...\n99 -1.298205 1.868477 -0.174665 0.065565 [[-1.2982050517578514, 1.8684774453090633, -0....\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74563854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19923793/" ]
74,563,876
<p>I'm new to using <code>beautiful soup</code> and I have been following tutorials on scraping with it. I am trying to use it to return high and low prices from common forex pairs. Im not sure if it is the sites that I'm trying to get the information rom, but I can find the <code>div tag</code> that I want the info from, I believe the text is hidden in the span, but i am still having trouble with it coming back <code>nonetype</code>.</p> <p>Can anyone help me figure this out?</p> <p>url : <a href="https://www.centralcharts.com/en/6748-aud-nzd/quotes" rel="nofollow noreferrer">https://www.centralcharts.com/en/6748-aud-nzd/quotes</a></p> <p>div class=&quot;tabMini-wrapper&quot;</p> <p>this is the whole table ^^ div class..</p> <p>Is it because of the format the site has it in?</p> <pre><code>import requests from bs4 import BeautifulSoup import re URL = &quot;https://www.centralcharts.com/en/6748-aud-nzd/quotes&quot; page = requests.get(URL) soup = BeautifulSoup(page.content, &quot;html.parser&quot;) spans=soup.find('span', attrs = {'class' , 'tabMini tabQuotes'}) print(spans) </code></pre> <p>I tried a bunch of different ways but this was most recent attempt. I was trying to get it from the span after the <code>.find()</code> returned <code>nonetype</code> for the table</p>
[ { "answer_id": 74563983, "author": "Life is complex", "author_id": 6083423, "author_profile": "https://Stackoverflow.com/users/6083423", "pm_score": 2, "selected": true, "text": "import requests\nfrom bs4 import BeautifulSoup\n\nURL = \"https://www.centralcharts.com/en/6748-aud-nzd/quotes\"\npage = requests.get(URL)\n\nsoup = BeautifulSoup(page.content, \"html.parser\")\n\n\nresults = []\ntable_data = soup.select_one('h2:-soup-contains(\"5 days quotes\")').find_next('table')\ndates = [element.get('data-date') for element in table_data.find_all('span', attrs={'set-locale-date'})]\ndaily_high_quotes = [element.text for element in table_data.find('td', text='High').find_next_siblings('td')]\ndaily_low_quotes = [element.text for element in table_data.find('td', text='Low').find_next_siblings('td')]\nfor quote_date, daily_high, daily_low in zip(dates, daily_high_quotes, daily_low_quotes):\n results.append([quote_date, daily_high, daily_low])\nprint(results)\n [['2022-11-21', '1.0854', '1.0811'], \n['2022-11-22', '1.0837', '1.0782'], \n['2022-11-23', '1.0837', '1.0746'], \n['2022-11-24', '1.0814', '1.0765'], \n['2022-11-25', '1.0822', '1.0796']]\n import requests\nfrom bs4 import BeautifulSoup\n\nURL = \"https://www.centralcharts.com/en/6748-aud-nzd/quotes\"\npage = requests.get(URL)\n\nsoup = BeautifulSoup(page.content, \"html.parser\")\n\nfor tag_element in soup.find_all('table', attrs={'class', 'tabMini tabQuotes'}):\n for item in tag_element.find_all('td'):\n print(item)\n" }, { "answer_id": 74563989, "author": "0stone0", "author_id": 5625547, "author_profile": "https://Stackoverflow.com/users/5625547", "pm_score": 2, "selected": false, "text": "th tr > td table data-date result tr high low result zip() import requests\nfrom bs4 import BeautifulSoup\nimport re\n\nresult = []\n\nURL = \"https://www.centralcharts.com/en/6748-aud-nzd/quotes\"\npage = requests.get(URL)\n\nsoup = BeautifulSoup(page.content, \"html.parser\")\n\ntable = soup.select('.prod-left-content .tabMini-wrapper table')[0]\n\nfor header in table.find('thead').find_all('span', attrs = { 'class': 'set-locale-date' }):\n result.append({ 'date': header.get('data-date'), 'high': None, 'low': None })\n\ntrs = table.select('tbody > tr')\n\nhigh = trs[5].find_all('span')\nlow = trs[6].find_all('span')\n\nif (len(high) != len(low)):\n print('Mmmm, somehting went wrong?')\n exit()\n\nfor i in range(len(high)):\n result[i]['low'] = low[i].text\n result[i]['high'] = high[i].text\n\nfor o in result:\n print(o['date'] + \"\\t\\t\" + o['high'] + \"\\t\" + o['low'])\n 2022-11-18 1.0915 1.0834\n2022-11-21 1.0854 1.0811\n2022-11-22 1.0837 1.0782\n2022-11-23 1.0837 1.0746\n2022-11-24 1.0812 1.0765\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74563876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20592712/" ]
74,563,919
<p>I wrote a function call API using fetch() function and then push received json to History.state using history.pushState(json). I need to use the state property afterwards but when I test console.log(history.state) right after that function, it printed null</p> <p>What I tried:</p> <pre><code>function1(); function2(); function function1() { const request = new Request('https://reqres.in/api/users?page=2'); fetch(request) .then(response =&gt; response.json()) .then( json =&gt; { history.pushState(json,'',''); console.log(history.state) } ); } function function2() { console.log(history.state); } </code></pre> <p>I even tried to wait util history.state not null using while loop (because I think it can be the order problem) but it didn't work. I want to print out exactly what I push to history.state before, this is what actually resulted:</p> <pre><code>null // [object Object] { &quot;page&quot;: 2, &quot;per_page&quot;: 6, &quot;total&quot;: 12, ... </code></pre> <p>This is a demo of the problem on codepen: <a href="https://codepen.io/L-Ph-t-the-scripter/pen/PoaeqzJ" rel="nofollow noreferrer">https://codepen.io/L-Ph-t-the-scripter/pen/PoaeqzJ</a></p>
[ { "answer_id": 74563983, "author": "Life is complex", "author_id": 6083423, "author_profile": "https://Stackoverflow.com/users/6083423", "pm_score": 2, "selected": true, "text": "import requests\nfrom bs4 import BeautifulSoup\n\nURL = \"https://www.centralcharts.com/en/6748-aud-nzd/quotes\"\npage = requests.get(URL)\n\nsoup = BeautifulSoup(page.content, \"html.parser\")\n\n\nresults = []\ntable_data = soup.select_one('h2:-soup-contains(\"5 days quotes\")').find_next('table')\ndates = [element.get('data-date') for element in table_data.find_all('span', attrs={'set-locale-date'})]\ndaily_high_quotes = [element.text for element in table_data.find('td', text='High').find_next_siblings('td')]\ndaily_low_quotes = [element.text for element in table_data.find('td', text='Low').find_next_siblings('td')]\nfor quote_date, daily_high, daily_low in zip(dates, daily_high_quotes, daily_low_quotes):\n results.append([quote_date, daily_high, daily_low])\nprint(results)\n [['2022-11-21', '1.0854', '1.0811'], \n['2022-11-22', '1.0837', '1.0782'], \n['2022-11-23', '1.0837', '1.0746'], \n['2022-11-24', '1.0814', '1.0765'], \n['2022-11-25', '1.0822', '1.0796']]\n import requests\nfrom bs4 import BeautifulSoup\n\nURL = \"https://www.centralcharts.com/en/6748-aud-nzd/quotes\"\npage = requests.get(URL)\n\nsoup = BeautifulSoup(page.content, \"html.parser\")\n\nfor tag_element in soup.find_all('table', attrs={'class', 'tabMini tabQuotes'}):\n for item in tag_element.find_all('td'):\n print(item)\n" }, { "answer_id": 74563989, "author": "0stone0", "author_id": 5625547, "author_profile": "https://Stackoverflow.com/users/5625547", "pm_score": 2, "selected": false, "text": "th tr > td table data-date result tr high low result zip() import requests\nfrom bs4 import BeautifulSoup\nimport re\n\nresult = []\n\nURL = \"https://www.centralcharts.com/en/6748-aud-nzd/quotes\"\npage = requests.get(URL)\n\nsoup = BeautifulSoup(page.content, \"html.parser\")\n\ntable = soup.select('.prod-left-content .tabMini-wrapper table')[0]\n\nfor header in table.find('thead').find_all('span', attrs = { 'class': 'set-locale-date' }):\n result.append({ 'date': header.get('data-date'), 'high': None, 'low': None })\n\ntrs = table.select('tbody > tr')\n\nhigh = trs[5].find_all('span')\nlow = trs[6].find_all('span')\n\nif (len(high) != len(low)):\n print('Mmmm, somehting went wrong?')\n exit()\n\nfor i in range(len(high)):\n result[i]['low'] = low[i].text\n result[i]['high'] = high[i].text\n\nfor o in result:\n print(o['date'] + \"\\t\\t\" + o['high'] + \"\\t\" + o['low'])\n 2022-11-18 1.0915 1.0834\n2022-11-21 1.0854 1.0811\n2022-11-22 1.0837 1.0782\n2022-11-23 1.0837 1.0746\n2022-11-24 1.0812 1.0765\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74563919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20493870/" ]
74,563,930
<pre><code>def remove_stopwords(text,nlp,custom_stop_words=None,remove_small_tokens=True,min_len=2): if custom_stop_words: nlp.Defaults.stop_words |= custom_stop_words filtered_sentence =[] doc = nlp (text) for token in doc: if token.is_stop == False: if remove_small_tokens: if len(token.text)&gt;min_len: filtered_sentence.append(token.text) else: filtered_sentence.append(token.text) return &quot; &quot;.join(filtered_sentence) if len(filtered_sentence)&gt;0 else None </code></pre> <p>I am getting the error for the last else:</p> <p>The goal of this last part is, if after the stopword removal, words are still left in the sentence, then the sentence should be returned as a string else return null. I'd be so thankful for any advice.</p> <pre><code>else None ^ IndentationError: expected an indented block </code></pre>
[ { "answer_id": 74563983, "author": "Life is complex", "author_id": 6083423, "author_profile": "https://Stackoverflow.com/users/6083423", "pm_score": 2, "selected": true, "text": "import requests\nfrom bs4 import BeautifulSoup\n\nURL = \"https://www.centralcharts.com/en/6748-aud-nzd/quotes\"\npage = requests.get(URL)\n\nsoup = BeautifulSoup(page.content, \"html.parser\")\n\n\nresults = []\ntable_data = soup.select_one('h2:-soup-contains(\"5 days quotes\")').find_next('table')\ndates = [element.get('data-date') for element in table_data.find_all('span', attrs={'set-locale-date'})]\ndaily_high_quotes = [element.text for element in table_data.find('td', text='High').find_next_siblings('td')]\ndaily_low_quotes = [element.text for element in table_data.find('td', text='Low').find_next_siblings('td')]\nfor quote_date, daily_high, daily_low in zip(dates, daily_high_quotes, daily_low_quotes):\n results.append([quote_date, daily_high, daily_low])\nprint(results)\n [['2022-11-21', '1.0854', '1.0811'], \n['2022-11-22', '1.0837', '1.0782'], \n['2022-11-23', '1.0837', '1.0746'], \n['2022-11-24', '1.0814', '1.0765'], \n['2022-11-25', '1.0822', '1.0796']]\n import requests\nfrom bs4 import BeautifulSoup\n\nURL = \"https://www.centralcharts.com/en/6748-aud-nzd/quotes\"\npage = requests.get(URL)\n\nsoup = BeautifulSoup(page.content, \"html.parser\")\n\nfor tag_element in soup.find_all('table', attrs={'class', 'tabMini tabQuotes'}):\n for item in tag_element.find_all('td'):\n print(item)\n" }, { "answer_id": 74563989, "author": "0stone0", "author_id": 5625547, "author_profile": "https://Stackoverflow.com/users/5625547", "pm_score": 2, "selected": false, "text": "th tr > td table data-date result tr high low result zip() import requests\nfrom bs4 import BeautifulSoup\nimport re\n\nresult = []\n\nURL = \"https://www.centralcharts.com/en/6748-aud-nzd/quotes\"\npage = requests.get(URL)\n\nsoup = BeautifulSoup(page.content, \"html.parser\")\n\ntable = soup.select('.prod-left-content .tabMini-wrapper table')[0]\n\nfor header in table.find('thead').find_all('span', attrs = { 'class': 'set-locale-date' }):\n result.append({ 'date': header.get('data-date'), 'high': None, 'low': None })\n\ntrs = table.select('tbody > tr')\n\nhigh = trs[5].find_all('span')\nlow = trs[6].find_all('span')\n\nif (len(high) != len(low)):\n print('Mmmm, somehting went wrong?')\n exit()\n\nfor i in range(len(high)):\n result[i]['low'] = low[i].text\n result[i]['high'] = high[i].text\n\nfor o in result:\n print(o['date'] + \"\\t\\t\" + o['high'] + \"\\t\" + o['low'])\n 2022-11-18 1.0915 1.0834\n2022-11-21 1.0854 1.0811\n2022-11-22 1.0837 1.0782\n2022-11-23 1.0837 1.0746\n2022-11-24 1.0812 1.0765\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74563930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20592672/" ]
74,563,944
<p>I actually have some styles that allow me to display a text surrounded by lines. The text can be displayed horizontally or vertically. I would like to add an arrow a the end of the surrounding lines. Something like this:</p> <p><code>------------------------- My horizontal label ------------------------&gt;</code></p> <p>or</p> <pre><code>^ | | M y t e x t | | </code></pre> <p>My vertical text is displayed differently in my following example.</p> <p>I tried several Technics i found in the net but no way to make it work in horizontal and vertical context. Someone has an idea of how it can be implemented?</p> <p>This is my starting css in which i would like to add these arrows:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>h1 { display: flex; flex-direction: row; } h1:before, h1:after{ content: ""; flex: 1 1; border-bottom: 1px solid; margin: auto; } h1:before { margin-right: 10px } h1:after { margin-left: 10px } h2 { display: flex; flex-direction: row; writing-mode: vertical-rl; transform: scale(-1); text-align: -webkit-center; height: 100%; } h2:before, h2:after{ content: ""; flex: 1 1; border-right: 1px solid; margin: auto; } h2:before { margin-bottom: 10px } h2:after { margin-top: 10px }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;h1&gt;My horizontal text&lt;/h1&gt; &lt;h2&gt;My vertical text&lt;/h2&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74563983, "author": "Life is complex", "author_id": 6083423, "author_profile": "https://Stackoverflow.com/users/6083423", "pm_score": 2, "selected": true, "text": "import requests\nfrom bs4 import BeautifulSoup\n\nURL = \"https://www.centralcharts.com/en/6748-aud-nzd/quotes\"\npage = requests.get(URL)\n\nsoup = BeautifulSoup(page.content, \"html.parser\")\n\n\nresults = []\ntable_data = soup.select_one('h2:-soup-contains(\"5 days quotes\")').find_next('table')\ndates = [element.get('data-date') for element in table_data.find_all('span', attrs={'set-locale-date'})]\ndaily_high_quotes = [element.text for element in table_data.find('td', text='High').find_next_siblings('td')]\ndaily_low_quotes = [element.text for element in table_data.find('td', text='Low').find_next_siblings('td')]\nfor quote_date, daily_high, daily_low in zip(dates, daily_high_quotes, daily_low_quotes):\n results.append([quote_date, daily_high, daily_low])\nprint(results)\n [['2022-11-21', '1.0854', '1.0811'], \n['2022-11-22', '1.0837', '1.0782'], \n['2022-11-23', '1.0837', '1.0746'], \n['2022-11-24', '1.0814', '1.0765'], \n['2022-11-25', '1.0822', '1.0796']]\n import requests\nfrom bs4 import BeautifulSoup\n\nURL = \"https://www.centralcharts.com/en/6748-aud-nzd/quotes\"\npage = requests.get(URL)\n\nsoup = BeautifulSoup(page.content, \"html.parser\")\n\nfor tag_element in soup.find_all('table', attrs={'class', 'tabMini tabQuotes'}):\n for item in tag_element.find_all('td'):\n print(item)\n" }, { "answer_id": 74563989, "author": "0stone0", "author_id": 5625547, "author_profile": "https://Stackoverflow.com/users/5625547", "pm_score": 2, "selected": false, "text": "th tr > td table data-date result tr high low result zip() import requests\nfrom bs4 import BeautifulSoup\nimport re\n\nresult = []\n\nURL = \"https://www.centralcharts.com/en/6748-aud-nzd/quotes\"\npage = requests.get(URL)\n\nsoup = BeautifulSoup(page.content, \"html.parser\")\n\ntable = soup.select('.prod-left-content .tabMini-wrapper table')[0]\n\nfor header in table.find('thead').find_all('span', attrs = { 'class': 'set-locale-date' }):\n result.append({ 'date': header.get('data-date'), 'high': None, 'low': None })\n\ntrs = table.select('tbody > tr')\n\nhigh = trs[5].find_all('span')\nlow = trs[6].find_all('span')\n\nif (len(high) != len(low)):\n print('Mmmm, somehting went wrong?')\n exit()\n\nfor i in range(len(high)):\n result[i]['low'] = low[i].text\n result[i]['high'] = high[i].text\n\nfor o in result:\n print(o['date'] + \"\\t\\t\" + o['high'] + \"\\t\" + o['low'])\n 2022-11-18 1.0915 1.0834\n2022-11-21 1.0854 1.0811\n2022-11-22 1.0837 1.0782\n2022-11-23 1.0837 1.0746\n2022-11-24 1.0812 1.0765\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74563944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20206303/" ]
74,563,970
<p>I want to make a background color change when user select a item on <code>Surface</code>. I am using <code>Column</code> in my parent, so I can't make <code>LazyColumn</code>. So I am using <code>Foreach</code> to make a list of view. By default no view will be selected, when user click on item then I want change the color. <strong>Note:</strong> Only one item will select at a time.</p> <p><strong>ScanDeviceList</strong></p> <pre><code>@Composable fun ColumnScope.ScanDeviceList( scanDeviceList: List&lt;ScanResult&gt;, modifier: Modifier = Modifier, pairSelectedDevice: () -&gt; Unit ) { Spacer() AnimatedVisibility() { Column { Text() Spacer() scanDeviceList.forEachIndexed { index, scanResult -&gt; ClickableItemContainer( rippleColor = AquaLightOpacity10, content = { ScanDeviceItem(index, scanResult, scanDeviceList) } ){} } AvailableWarningText() PairSelectedDevice(pairSelectedDevice) } } } </code></pre> <p><strong>ScanDeviceItem</strong></p> <pre><code>@Composable fun ScanDeviceItem( index: Int, scanResult: ScanResult, scanDeviceList: List&lt;ScanResult&gt; ) { Column { if (index == 0) { Divider(color = Cloudy, thickness = 1.dp) } Text( text = scanResult.device.name, modifier = Modifier.padding(vertical = 10.dp) ) if (index &lt;= scanDeviceList.lastIndex) { Divider(color = Cloudy, thickness = 1.dp) } } } </code></pre> <p><strong>ClickableItemContainer</strong></p> <pre><code>@OptIn(ExperimentalMaterialApi::class) @Composable fun ClickableItemContainer( rippleColor: Color = TealLight, content: @Composable (MutableInteractionSource) -&gt; Unit, clickAction: () -&gt; Unit ) { val interactionSource = remember { MutableInteractionSource() } CompositionLocalProvider( LocalRippleTheme provides AbcRippleTheme(rippleColor), content = { Surface( onClick = { clickAction() }, interactionSource = interactionSource, color = White ) { content(interactionSource) } } ) } </code></pre> <p>I want to something like this</p> <p><a href="https://i.stack.imgur.com/nyrFk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nyrFk.png" alt="enter image description here" /></a></p> <p>Now above solution is only working on ripple effect, Now I want to extend my function to select a single item at a time. Many Thanks</p>
[ { "answer_id": 74564190, "author": "Gabriele Mariotti", "author_id": 2016562, "author_profile": "https://Stackoverflow.com/users/2016562", "pm_score": 3, "selected": true, "text": "clickAction @Composable\nfun MyList(\n\n var selectedIndex by remember { mutableStateOf(-1) }\n\n Column() {\n itemsList.forEachIndexed() { index, item ->\n MyItem(\n selected = selectedIndex == index,\n clickAction = { selectedIndex = index }\n )\n }\n}\n\n@Composable\nfun MyItem(\n selected : Boolean = false,\n clickAction: () -> Unit\n){\n Surface(\n onClick = { clickAction() },\n color = if (selected) Color.Red else Color.Yellow\n ) {\n Text(\"Item...\")\n }\n}\n" }, { "answer_id": 74564214, "author": "R0ck", "author_id": 18215416, "author_profile": "https://Stackoverflow.com/users/18215416", "pm_score": 0, "selected": false, "text": "var itemSelected by remember { mutableState(ScanDeviceResult()) }\n ClickableItemContainer(\n rippleColor = AquaLightOpacity10,\n content = {\n ScanDeviceItem(index, scanResult, scanDeviceList)\n }\n ){ newItemSelected ->\nitemSelected = newItemSelected\n}\n @OptIn(ExperimentalMaterialApi::class)\n@Composable\nfun ClickableItemContainer(\nitemSelected: ScanResult,\nscanResult: ScanResult,\n rippleColor: Color = TealLight,\n content: @Composable (MutableInteractionSource) -> Unit,\n clickAction: (ScanResult) -> Unit\n) {\n val interactionSource = remember { MutableInteractionSource() }\n CompositionLocalProvider(\n LocalRippleTheme provides AbcRippleTheme(rippleColor),\n content = {\n Surface(\n onClick = { clickAction.invoke(scanResult) },\n interactionSource = interactionSource,\n color = if (itemSelected == scanResult) YOUR_BACKGROUND-SELECTED_COLOR else White\n ) {\n content(interactionSource)\n }\n }\n )\n}\n @Composable\n fun ColumnScope.ScanDeviceList(\n itemSelected: MutableState<ScanResult>,\n scanDeviceList: List<ScanResult>,\n modifier: Modifier = Modifier,\n pairSelectedDevice: () -> Unit\n ) {\n Spacer()\n AnimatedVisibility() {\n Column {\n Text()\n Spacer()\n scanDeviceList.forEachIndexed { index, scanResult ->\n ClickableItemContainer(\n itemSelected = itemSelected,\n scanResult = scanResult,\n rippleColor = AquaLightOpacity10,\n content = {\n ScanDeviceItem(index, scanResult, scanDeviceList)\n }\n ){ scanResultToSelect ->\n itemSelected = scanResultToSelect\n}\n }\n AvailableWarningText()\n PairSelectedDevice(pairSelectedDevice)\n }\n }\n }\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74563970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11560810/" ]
74,563,973
<p>The main link is (<a href="https://www.europarl.europa.eu/meps/en/197818/BILLY_KELLEHER/meetings/past#detailedcardmep" rel="nofollow noreferrer">https://www.europarl.europa.eu/meps/en/197818/BILLY_KELLEHER/meetings/past#detailedcardmep</a>)</p> <p>My code shows me only fist pages but I need to browse all of them for all the links (I have more than 100 links)</p> <pre><code> </code></pre> <pre><code>from bs4 import BeautifulSoup import requests page=0 list=[] isHaveNextPage=True links = [(f&quot;https://www.europarl.europa.eu/meps/en/loadmore-meetings?meetingType=PAST&amp;memberId=197506&amp;termId=9&amp;page={page}&amp;pageSize=10&quot;), (f&quot;https://www.europarl.europa.eu/meps/en/loadmore-meetings?meetingType=PAST&amp;memberId=124861&amp;termId=9&amp;page={page}&amp;pageSize=10&quot;), (f&quot;https://www.europarl.europa.eu/meps/en/loadmore-meetings?meetingType=PAST&amp;memberId=229519&amp;termId=9&amp;page={page}&amp;pageSize=10&quot; .....), while(isHaveNextPage): for url in links: r= requests.get(url).text soup =BeautifulSoup(r,&quot;lxml&quot;) product = soup.find_all(&quot;div&quot;,class_=&quot;europarl-expandable-item&quot;) for data in product: title = data.find(class_=&quot;t-item&quot;).get_text() date = data.find(class_=&quot;erpl_document-subtitle-date&quot;).get_text() address = data.find(class_=&quot;erpl_document-subtitle-location&quot;).get_text() reporter = data.find(class_=&quot;erpl_document-subtitle-reporter&quot;).get_text() author = data.find(class_=&quot;erpl_document-subtitle-author&quot;).get_text() list.append([author.strip(), date.strip(), address.strip(), reporter.strip(), title.strip()]) print(&quot;page---&quot;,page) if soup.find(&quot;button&quot;,class_='btn btn-default europarl-expandable-async-loadmore') is None: isHaveNextPage=False page+=1 </code></pre>
[ { "answer_id": 74564108, "author": "OneMadGypsy", "author_id": 10292330, "author_profile": "https://Stackoverflow.com/users/10292330", "pm_score": 1, "selected": false, "text": "page f\"https://...&page={page}...\" \"https://...&page=%i...\" for url in links:\n r= requests.get(url % page).text\n \"https://...&page={}...\" r= requests.get(url.format(page)).text" }, { "answer_id": 74565506, "author": "Barry the Platipus", "author_id": 19475185, "author_profile": "https://Stackoverflow.com/users/19475185", "pm_score": 1, "selected": true, "text": "import requests\nfrom bs4 import BeautifulSoup as bs\nimport pandas as pd\nfrom tqdm import tqdm ## if using Jupyter: from tqdm.notebook import tqdm \n\npd.set_option('display.max_columns', None)\npd.set_option('display.max_colwidth', None)\n\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36'\n}\n\ns = requests.Session()\ns.headers.update(headers)\nbig_list = []\nslightly_incompetent_people_ids = ['197818', '96829', '197530', '97968', '197691', '189065', '197636', '33997']\nfor p in tqdm(slightly_incompetent_people_ids):\n counter = 0\n while True:\n soup = bs(s.get(f'https://www.europarl.europa.eu/meps/en/loadmore-meetings?meetingType=PAST&memberId={p}&termId=9&page={counter}&pageSize=20').text, 'html.parser')\n has_more = soup.select_one('button[class=\"btn btn-default europarl-expandable-async-loadmore\"]') if soup.select_one('button[class=\"btn btn-default europarl-expandable-async-loadmore\"]') else None\n \n meetings = soup.select('div[class=\"europarl-expandable-item\"]')\n for m in meetings:\n title = m.select_one('h3').text.strip()\n date = m.select_one('span[class=\"erpl_document-subtitle-date\"]').text.strip()\n place = m.select_one('span[class=\"erpl_document-subtitle-location\"]').text.strip()\n big_list.append((p, title, date, place))\n if has_more == None:\n counter = 0\n break\n counter += 1\ndf = pd.DataFrame(big_list, columns = ['MEP', 'Title', 'Date', 'Place'])\nprint(df)\n 100%\n8/8 [00:01<00:00, 5.61it/s]\nMEP Title Date Place\n0 197818 AIFMD 25-05-2022 Virtual meeting\n1 197818 DORA 25-05-2022 Virtual meeting\n2 197818 AIFMD 25-05-2022 Virtual meeting\n3 197818 AIFMD 18-05-2022 Brussels\n4 197818 AIFMD 17-05-2022 Virtual meeting\n... ... ... ... ...\n77 33997 Meeting with H.E. Aigul Kuspan, the Ambassador of the Republic of Kazakhstan to the Kingdom of Belgium and Head of Mission of the Republic of Kazakhstan to the European Union 08-01-2020 European Parliament\n78 33997 Meeting with H.E. Daniel Ioniță, Ambassador Extraordinary and Plenipotentiary of Romania to the Republic of Moldova 09-12-2019 Embassy of Romania to the Republic of Moldova\n79 33997 Meeting with Mihai Chirica, Mayor of Iași 07-12-2019 Iași, Romania\n80 33997 Meeting with Laura Codruța Kövesi, the European Public Prosecut 06-11-2019 European Parliament\n81 33997 Meeting with Tony Murphy, Member of the European Court of Auditors 24-09-2019 European Parliament\n82 rows × 4 columns\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74563973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20238491/" ]
74,564,001
<p>Good mornings all, I make a POST request with the Type field (tinyint) in my unit tests. I give it the value FALSE. When I check in the database, the Type field is 1 so TRUE. I don't know how this is possible and it happens to me several times on my unit tests.</p> <p>The POST request with the column type :</p> <pre><code> &quot;title&quot; =&gt; &quot;Une fausse formation&quot; &quot;number&quot; =&gt; &quot;faux-numer0&quot; &quot;organism&quot; =&gt; &quot;Un faux organisme&quot; &quot;type&quot; =&gt; false &quot;status&quot; =&gt; 0 &quot;costs&quot; =&gt; array:2 [ 0 =&gt; array:4 [ &quot;title&quot; =&gt; &quot;Frais pédagogiques&quot; &quot;type&quot; =&gt; 0 &quot;amount&quot; =&gt; 102.5 &quot;isCollective&quot; =&gt; true ] 1 =&gt; array:4 [ &quot;title&quot; =&gt; &quot;Frais de transport&quot; &quot;type&quot; =&gt; 0 &quot;amount&quot; =&gt; 10 &quot;isCollective&quot; =&gt; true ] ] &quot;sessions&quot; =&gt; [] &quot;visibility&quot; =&gt; 2 ] </code></pre> <p>the row that was inserted into the table :</p> <pre><code> &quot;title&quot; =&gt; &quot;Une fausse formation&quot; &quot;number&quot; =&gt; &quot;faux-numer0&quot; &quot;type&quot; =&gt; true &quot;status&quot; =&gt; 0 &quot;organism&quot; =&gt; &quot;Un faux organisme&quot; &quot;visibility&quot; =&gt; array:2 [ &quot;establishment&quot; =&gt; [] &quot;employees&quot; =&gt; array:1 [ 0 =&gt; [] ] ] &quot;costs&quot; =&gt; array:2 [ 0 =&gt; array:4 [ &quot;title&quot; =&gt; &quot;Frais pédagogiques&quot; &quot;type&quot; =&gt; 0 &quot;amount&quot; =&gt; &quot;102.50&quot; &quot;is_collective&quot; =&gt; true ] 1 =&gt; array:4 [ &quot;title&quot; =&gt; &quot;Frais de transport&quot; &quot;type&quot; =&gt; 0 &quot;amount&quot; =&gt; &quot;10.00&quot; &quot;is_collective&quot; =&gt; true ] ] ] </code></pre> <p>Here is my field declaration in the Entity:</p> <pre><code>/** * @var bool * * @ORM\Column(name=&quot;`type`&quot;, type=&quot;boolean&quot;) * @Serializer\Groups({&quot;get_employee&quot;, &quot;get_training&quot;, &quot;get_trainings&quot;, &quot;get_training_user&quot;, &quot;get_training_session&quot;}) */ private $type; </code></pre> <p>This is my POST TEST request :</p> <pre><code> public function testPostTraining($user, $data, $result) { $this-&gt;authUser($user[0], $user[1], $user[2]); // Retrieve created visibility id $visibilityData = array( 'establishment' =&gt; 1 ); $this-&gt;apiCall('POST', '/api/secure/trainings/visibilities.json', $visibilityData); // Check status code (visibility created) $this-&gt;assertEquals(201, $this-&gt;client-&gt;getResponse()-&gt;getStatusCode()); $data['visibility'] = json_decode($this-&gt;client-&gt;getResponse()-&gt;getContent(), true)['id']; $this-&gt;apiCall('POST', '/api/secure/trainings.json', $data); // Check status code (created) $this-&gt;assertEquals(201, $this-&gt;client-&gt;getResponse()-&gt;getStatusCode()); // Check if id is returned $response = json_decode($this-&gt;client-&gt;getResponse()-&gt;getContent(), true); $this-&gt;assertArrayHasKey('id', $response); //$this-&gt;assertInternalType('integer', $response['id']); $this-&gt;assertEquals('integer', gettype($response['id'])); // Check data $this-&gt;apiCall('GET', '/api/secure/trainings/'.$response['id'].'.json'); $training = json_decode($this-&gt;client-&gt;getResponse()-&gt;getContent(), true); // Remove ids $this-&gt;recursive_unset($training, 'id'); $this-&gt;recursive_unset($training, 'created_at'); $this-&gt;recursive_unset($training, 'updated_at'); $this-&gt;recursive_unset($training['visibility']['establishment'], 'roles'); // Check content $this-&gt;assertEquals($training, $result); } </code></pre> <p>The data of the post request :</p> <pre><code>$data_two= array( 'title' =&gt; 'Une vrai formation', 'number' =&gt; 'vrai-numer0', 'organism' =&gt; 'Un vrai organisme', 'type' =&gt; false, 'status' =&gt; 1, 'costs' =&gt; array( array( 'title' =&gt; 'Frais pédagogiques', 'type' =&gt; 1, 'amount' =&gt; 10.25, 'isCollective' =&gt; true ), ), 'sessions' =&gt; array() ); </code></pre> <p>This is the POST controller :</p> <pre><code> public function postAction(Request $request) { try { if (($employee = $this-&gt;getEmployee()) == null) return FOSView::create(null, Response::HTTP_FORBIDDEN); $manager = $this-&gt;getTrainingManager(); $training = $manager-&gt;createTraining(); $form = $this-&gt;createForm(TrainingType::class, $training, array( 'method' =&gt; $request-&gt;getMethod() )); $this-&gt;removeExtraFields($request, $form); $form-&gt;handleRequest($request); if ($form-&gt;isSubmitted() &amp;&amp; $form-&gt;isValid()) { $this-&gt;denyAccessUnlessGranted('create', $training); $manager-&gt;save($training); $dispatcher = $this-&gt;eventDisptacher; $event = new TrainingActionEvent($training, $this-&gt;getEmployee(), $request-&gt;getMethod()); $dispatcher-&gt;dispatch($event,TrainingActionEvent::TRAINING_ACTION); return $training; } } catch(\Exception $e) { return FOSView::create($e-&gt;getMessage(), Response::HTTP_INTERNAL_SERVER_ERROR); } return FOSView::create($form, Response::HTTP_BAD_REQUEST); } </code></pre>
[ { "answer_id": 74572745, "author": "Fracsi", "author_id": 2357002, "author_profile": "https://Stackoverflow.com/users/2357002", "pm_score": 1, "selected": false, "text": "CheckboxType BooleanToStringTransformer value '1' true false_values [null] false FOSRestBundle fos_rest.decoder.jsontoform" }, { "answer_id": 74616663, "author": "oracle972", "author_id": 20089108, "author_profile": "https://Stackoverflow.com/users/20089108", "pm_score": 1, "selected": true, "text": "private function apiCall($method, $endpoint, $parameters=array())\n{\n\n$this->client->request($method, $endpoint, $parameters);\nreturn json_decode($this->client->getResponse()->getContent(), true);\n\n}\n private function apiPostCall($method, $endpoint, $parameters=array())\n { \n $this->client->request(\n $method,\n $endpoint,\n [],\n [],\n ['CONTENT_TYPE' => 'application/json'],\n json_encode($parameters)\n ); \n return json_decode($this->client->getResponse()->getContent(),true);\n }\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20089108/" ]
74,564,008
<p>I have indicated a background image and centered it in its container with:</p> <pre><code>background-size:cover; background-position-x:50%; background-position-y:center; </code></pre> <p>I use the &quot;Responsive Design Mode&quot; tool to check how the image looks, and it occupies the entire container and is centered in it for any viewport width.</p> <p>Well, when publishing the Website on the Internet (it's my first time) the image appears shifted to the left on my personal mobile (vertical position). Even weirder, when I place my phone horizontally, the image appears centered.</p> <p>I would like the image to always appear centered in its container. Does anyone know what is happening?</p> <p>Thanks</p>
[ { "answer_id": 74572745, "author": "Fracsi", "author_id": 2357002, "author_profile": "https://Stackoverflow.com/users/2357002", "pm_score": 1, "selected": false, "text": "CheckboxType BooleanToStringTransformer value '1' true false_values [null] false FOSRestBundle fos_rest.decoder.jsontoform" }, { "answer_id": 74616663, "author": "oracle972", "author_id": 20089108, "author_profile": "https://Stackoverflow.com/users/20089108", "pm_score": 1, "selected": true, "text": "private function apiCall($method, $endpoint, $parameters=array())\n{\n\n$this->client->request($method, $endpoint, $parameters);\nreturn json_decode($this->client->getResponse()->getContent(), true);\n\n}\n private function apiPostCall($method, $endpoint, $parameters=array())\n { \n $this->client->request(\n $method,\n $endpoint,\n [],\n [],\n ['CONTENT_TYPE' => 'application/json'],\n json_encode($parameters)\n ); \n return json_decode($this->client->getResponse()->getContent(),true);\n }\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20592730/" ]
74,564,019
<p>I have developed website using Next.js and Tailwind CSS. The website while testing appears to be zoomed In in Firefox but its looking fine in all other browsers.</p> <p>When the screen is broguht to 80%, then the website looks fine in firefox. What's the solution to this problem so that the website should appear same in all browser.</p> <p>Thanks <a href="https://i.stack.imgur.com/FyqHe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FyqHe.png" alt="This is the website image in firefox" /></a><a href="https://i.stack.imgur.com/YRv6x.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YRv6x.png" alt="This is the website Image in Chrome" /></a></p>
[ { "answer_id": 74572745, "author": "Fracsi", "author_id": 2357002, "author_profile": "https://Stackoverflow.com/users/2357002", "pm_score": 1, "selected": false, "text": "CheckboxType BooleanToStringTransformer value '1' true false_values [null] false FOSRestBundle fos_rest.decoder.jsontoform" }, { "answer_id": 74616663, "author": "oracle972", "author_id": 20089108, "author_profile": "https://Stackoverflow.com/users/20089108", "pm_score": 1, "selected": true, "text": "private function apiCall($method, $endpoint, $parameters=array())\n{\n\n$this->client->request($method, $endpoint, $parameters);\nreturn json_decode($this->client->getResponse()->getContent(), true);\n\n}\n private function apiPostCall($method, $endpoint, $parameters=array())\n { \n $this->client->request(\n $method,\n $endpoint,\n [],\n [],\n ['CONTENT_TYPE' => 'application/json'],\n json_encode($parameters)\n ); \n return json_decode($this->client->getResponse()->getContent(),true);\n }\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16612029/" ]
74,564,045
<p>I have a data set in this format:</p> <pre><code>data = { 'sensor1': {'units': 'x', 'values': [{'time': 17:00, 'value': 10}, {'time': 17:10, 'value': 12}, {'time': 17:20, 'value' :7}, ...]} 'sensor2': {'units': 'x', 'values': [{'time': 17:00, 'value': 9}, {'time': 17:20, 'value': 11}, ...]} } </code></pre> <p>And I want to collect the data to put into a csv like:</p> <pre><code>time, sensor1, sensor2 17:00, 10, 9, 17:10, 12, , 17:20, 7, 11, ... </code></pre> <p>I need to use the csv module so I require a list of dictionaries like so:</p> <p>[{'time': 17:00, 'sensor1': 10, 'sensor2': 9}, ... ]</p> <p>I know that</p> <pre><code>fields = list(data.keys()) </code></pre> <p>Will go into csv write as the header. It's just the rows I can't format properly. Especially since the times don't always exist in both sensors. e.g. 17:10 has a value in sensor 1 but does not exist in sensor 2.</p>
[ { "answer_id": 74572745, "author": "Fracsi", "author_id": 2357002, "author_profile": "https://Stackoverflow.com/users/2357002", "pm_score": 1, "selected": false, "text": "CheckboxType BooleanToStringTransformer value '1' true false_values [null] false FOSRestBundle fos_rest.decoder.jsontoform" }, { "answer_id": 74616663, "author": "oracle972", "author_id": 20089108, "author_profile": "https://Stackoverflow.com/users/20089108", "pm_score": 1, "selected": true, "text": "private function apiCall($method, $endpoint, $parameters=array())\n{\n\n$this->client->request($method, $endpoint, $parameters);\nreturn json_decode($this->client->getResponse()->getContent(), true);\n\n}\n private function apiPostCall($method, $endpoint, $parameters=array())\n { \n $this->client->request(\n $method,\n $endpoint,\n [],\n [],\n ['CONTENT_TYPE' => 'application/json'],\n json_encode($parameters)\n ); \n return json_decode($this->client->getResponse()->getContent(),true);\n }\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12552948/" ]
74,564,053
<p>Hey so i have this function to check if a number is a prime number</p> <pre><code>def is_prime(n): flag = True for i in range(2, n ): if (n % i) == 0: flag = False return flag print(is_prime(1)) </code></pre> <p>However when i test the number 1, it skips the for loop and returns True which isn't correct because 1 is not a prime number. How could i fix this?</p>
[ { "answer_id": 74564821, "author": "Jamiu Shaibu", "author_id": 19290081, "author_profile": "https://Stackoverflow.com/users/19290081", "pm_score": 1, "selected": false, "text": "n 1 False n n def is_prime(n):\n flag = True\n if n > 1:\n for i in range(2, n ):\n if (n % i) == 0:\n flag = False\n\n return flag # Returns this flag after check whether n is prime or not\n \n # Returns False if n <= 1\n return False\n\n\nprint(is_prime(1))\n False\n" }, { "answer_id": 74565606, "author": "FAB", "author_id": 6373435, "author_profile": "https://Stackoverflow.com/users/6373435", "pm_score": 0, "selected": false, "text": "def is_prime(n: int) -> bool:\n if n > 1:\n for i in range(2, n): # if n == 2, there is no loop, is never checked\n if (n % i) == 0:\n return False # can return early once we meet the condition, don't need to finish the loop\n\n return True\n\nprint(is_prime(7534322224))\nprint(is_prime(5))\n def is_prime(n: int) -> bool:\n if n < 2: return False \n return n == 2 or True not in [True for i in range(2, n) if (n % i) == 0]\n\nprint(is_prime(75343224))\nprint(is_prime(5))\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13964650/" ]