qid
int64
4
22.2M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,404,629
<p>Weblinks are not responsive, they increased the mobile page width and create bad user experience.</p> <p>I am using Asona theme.</p> <p>Fix this problem, the weblinks doesn't bend and goes on next paragraph, they are just goes straight.<a href="https://i.stack.imgur.com/rLtF2.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rLtF2.jpg" alt="enter image description here" /></a></p>
[ { "answer_id": 74405747, "author": "Limey", "author_id": 13434871, "author_profile": "https://Stackoverflow.com/users/13434871", "pm_score": 0, "selected": false, "text": "df1 %>% \n arrange(C, ID, fyear) %>% \n group_by(C, ID) %>% \n mutate(\n fyear3=rowSums(list(sapply(1:3, function(x) lag(data, x)))[[1]]),\n fyear5=rowSums(list(sapply(1:5, function(x) lag(data, x)))[[1]])\n ) %>%\n ungroup()\n# A tibble: 18 × 6\n ID C fyear data fyear3 fyear5\n <dbl> <chr> <dbl> <dbl> <dbl> <dbl>\n 1 1 a 2000 30 NA NA\n 2 1 a 2001 50 NA NA\n 3 1 a 2002 22 NA NA\n 4 1 a 2003 3 102 NA\n 5 1 a 2004 6 75 NA\n 6 1 a 2005 11 31 111\n 7 3 b 2000 5 NA NA\n 8 3 b 2001 3 NA NA\n 9 3 b 2002 7 NA NA\n10 5 b 2003 6 NA NA\n11 5 b 2004 9 NA NA\n12 4 c 2000 31 NA NA\n13 4 c 2001 5 NA NA\n14 4 c 2002 6 NA NA\n15 4 c 2003 7 42 NA\n16 4 c 2004 44 18 NA\n17 4 c 2005 33 57 93\n18 4 c 2006 2 84 95\n" }, { "answer_id": 74432828, "author": "ThomasIsCoding", "author_id": 12158757, "author_profile": "https://Stackoverflow.com/users/12158757", "pm_score": 0, "selected": false, "text": "frollsum" }, { "answer_id": 74437265, "author": "G. Grothendieck", "author_id": 516548, "author_profile": "https://Stackoverflow.com/users/516548", "pm_score": 2, "selected": true, "text": "library(dplyr, exclude = c(\"filter\", \"lag\"))\nlibrary(zoo)\n\ndf1 %>%\n group_by(ID, C) %>%\n mutate(data3 = rollsumr(data, 3, fill = NA),\n data5 = rollsumr(data, 5, fill = NA)) %>%\n ungroup\n## # A tibble: 18 x 6\n## ID C fyear data data3 data5\n## <dbl> <chr> <dbl> <dbl> <dbl> <dbl>\n## 1 1 a 2000 30 NA NA\n## 2 1 a 2001 50 NA NA\n## 3 1 a 2002 22 102 NA\n## 4 1 a 2003 3 75 NA\n## 5 1 a 2004 6 31 111\n...snip...\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20479011/" ]
74,404,679
<p>I am trying to use <a href="https://lodash.com/docs/4.17.15#throttle" rel="nofollow noreferrer">lodash's throttle</a> inside a React component to make some other call. This is what I currently have:</p> <pre class="lang-js prettyprint-override"><code>const requestDetails = useCallback( throttle((someId: number) =&gt; { dispatch(...); }, 30000) , []); </code></pre> <p>I am trying to make it so that <code>requestDetails(someId)</code> only will run <code>dispatch</code> once every 30 seconds, at most, for each <code>someId</code> passed.</p> <p>Therefore, I would need to return a different <code>throttle</code> function for each <code>someId</code>. However, the code above doesn't work: I think it is because there is only one <code>throttle</code> function created behind-the-scenes, and therefore <code>throttle</code> will only run once every 30 seconds for all calls, not per <code>someId</code>.</p> <p>Thank you!</p>
[ { "answer_id": 74404744, "author": "Nick Vu", "author_id": 9201587, "author_profile": "https://Stackoverflow.com/users/9201587", "pm_score": 1, "selected": false, "text": "useRef" }, { "answer_id": 74406724, "author": "Ori Drori", "author_id": 5157454, "author_profile": "https://Stackoverflow.com/users/5157454", "pm_score": 0, "selected": false, "text": "someId" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2034128/" ]
74,404,735
<p>I want to block equal data entry in the phone number.</p> <p>I tried several methods and failed.</p> <p>I changed the code several times and I couldn't.</p> <pre><code>`const form = document.getElementById('agenda-de-contatos'); let linhas = []; form.addEventListener('submit', function (e) { e.preventDefault(); const inputNomeContato = document.getElementById('nome-do-contato'); const inputNumeroTelefone = document.getElementById('numero-de-telefone'); if (linhas.includes(inputNumeroTelefone.value)) { alert(`Número: ${inputNumeroTelefone.value} já foi inserido`); } else { linhas.push(inputNumeroTelefone.value); } let linha = '&lt;tr&gt;'; linha += `&lt;td&gt;${inputNomeContato.value}&lt;/td&gt;`; linha += `&lt;td&gt;${inputNumeroTelefone.value}&lt;/td&gt;`; linha += `&lt;td&gt;&lt;button class='excluir' onclick=&quot;deleteRow(this.parentNode.parentNode.rowIndex,this)&quot;&gt;Remover&lt;/button&gt;&lt;/td&gt;`; linha += '&lt;/tr&gt;'; linhas.push(linha); const corpoTabela = document.querySelector('tbody'); corpoTabela.innerHTML = linhas.join(&quot;&quot;) }) function deleteRow(id,node) { linhas.splice(id-1,1); document.getElementById('tabela').deleteRow(id); }` </code></pre>
[ { "answer_id": 74404744, "author": "Nick Vu", "author_id": 9201587, "author_profile": "https://Stackoverflow.com/users/9201587", "pm_score": 1, "selected": false, "text": "useRef" }, { "answer_id": 74406724, "author": "Ori Drori", "author_id": 5157454, "author_profile": "https://Stackoverflow.com/users/5157454", "pm_score": 0, "selected": false, "text": "someId" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15248306/" ]
74,404,741
<p>I am trying to take a sheet like: <a href="https://i.stack.imgur.com/skuca.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/skuca.png" alt="enter image description here" /></a> A3,B3,C3 are the sum of the 2 values above them.</p> <p>Copy this entire sheet into another sheet with only static values ie the sum formulas are gone and 5,73,55 are just the values.</p> <pre><code>Public Sub CopyEntireSheetValues() Sheets(&quot;Static Data&quot;).Range(&quot;A1:M100&quot;).Value = Sheets(&quot;MAIN&quot;).Range(&quot;A1:M100&quot;).Value End Sub </code></pre> <p>This works but ideally, i wouldn't define this range and copy all values from one sheet to another</p>
[ { "answer_id": 74405047, "author": "pgSystemTester", "author_id": 11732320, "author_profile": "https://Stackoverflow.com/users/11732320", "pm_score": 2, "selected": true, "text": "pastespecial" }, { "answer_id": 74405245, "author": "tigeravatar", "author_id": 2665425, "author_profile": "https://Stackoverflow.com/users/2665425", "pm_score": 2, "selected": false, "text": ".UsedRange" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15316309/" ]
74,404,753
<p>I have created a function called <code>interval</code> which takes two numbers as input between 1 and 12 and if the number is less than 10, it appends a 0 to the front. e.g. 4 becomes 04, but 11 stays 11.</p> <pre><code>interval &lt;- function(month_start = 1, month_end = 12){ month_range &lt;- as.character(c(month_start:month_end)) month_range_char &lt;- month_range %&gt;% map( ~if(as.numeric(.x)&lt;10){ paste0(&quot;0&quot;,.x) } else{ .x } ) return(month_range_char) } </code></pre> <p>I feel like I have written a lot of code to do quite a simple thing. Is there an obvious way to improve this?</p>
[ { "answer_id": 74404782, "author": "jpsmith", "author_id": 12109788, "author_profile": "https://Stackoverflow.com/users/12109788", "pm_score": 3, "selected": true, "text": "x <- 1:12\n\nifelse(x < 10, paste0(\"0\", x), x)\n\n# and to force a character variable, per comment from @Miff\nas.character(ifelse(x < 10, paste0(\"0\", x), x))\n" }, { "answer_id": 74404915, "author": "Phil", "author_id": 5221626, "author_profile": "https://Stackoverflow.com/users/5221626", "pm_score": 0, "selected": false, "text": "test <- as.character(c(5, 10))\n\nlibrary(stringr)\n\nifelse(str_length(test) == 1, str_pad(test, 2, pad = \"0\"), test)\n\n[1] \"05\" \"10\"\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2300049/" ]
74,404,756
<p>I want to generate line as like attached image using HTML/CSS</p> <p><a href="https://i.stack.imgur.com/skZOd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/skZOd.png" alt="enter image description here" /></a></p> <p>I have tried with two different divs but not generating result as expected.</p> <p>Any idea on this.</p> <p>I have tried with two different divs but not generating result as expected.</p>
[ { "answer_id": 74404782, "author": "jpsmith", "author_id": 12109788, "author_profile": "https://Stackoverflow.com/users/12109788", "pm_score": 3, "selected": true, "text": "x <- 1:12\n\nifelse(x < 10, paste0(\"0\", x), x)\n\n# and to force a character variable, per comment from @Miff\nas.character(ifelse(x < 10, paste0(\"0\", x), x))\n" }, { "answer_id": 74404915, "author": "Phil", "author_id": 5221626, "author_profile": "https://Stackoverflow.com/users/5221626", "pm_score": 0, "selected": false, "text": "test <- as.character(c(5, 10))\n\nlibrary(stringr)\n\nifelse(str_length(test) == 1, str_pad(test, 2, pad = \"0\"), test)\n\n[1] \"05\" \"10\"\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20200307/" ]
74,404,771
<p>I have Categories stored in a single table.</p> <p>Where there is no limit on number of childerns.</p> <p>I want to fetch all the linked childern categories for the provided category id:</p> <p>The reason for getting the hierarchy is that I need to update the path field for each category that is either newly created or updated. I need to maintain the path field</p> <p>Table name: <code>categories</code></p> <pre><code>id parentId name path A1 null Cat 1 Cat 1 A2 A1 Cat 2 Cat 1 &gt; Cat 2 A3 A2 Cat 3 Cat 1 &gt; Cat 2 &gt; Cat 3 A4 null Cat A Cat A A5 A4 Cat B Cat A &gt; Cat B </code></pre> <p>Now I want to fetch hierarchy for <code>id: 1</code></p> <p>What I have tried so far is:</p> <pre><code>with recursive cte (id, name, parentId) AS ( select id, name, parentId from categories where parentId = 'A1' union all select c.id, c.name, c.parentId from categories c inner join cte on c.parentId = cte.id ) select * from cte; </code></pre> <p>The above query returns:</p> <pre><code>[ { id: A1, parentId: null, name: Cat 1, path: Cat 1 }, { id: A2, parentId: A1, name: Cat 2, path: Cat 1 &gt; Cat 2 } ] </code></pre> <p>But I want this:</p> <pre><code>[ { id: A2, parentId: A1, name: Cat 2, path: Cat 1 &gt; Cat 2 }, { id: A3, parentId: A2, name: Cat 3, path: Cat 1 &gt; Cat 2 &gt; Cat 3 } ] </code></pre> <p>If I provide <code>id: 2</code>, in that case I am expecting:</p> <pre><code>[ { id: A3, parentId: A2, name: Cat 3, path: Cat 1 &gt; Cat 2 &gt; Cat 3 } ] </code></pre> <p>There is something that I am doing wrong with the query, can anyone identify?</p> <p>Here is reproduced scenario: <a href="https://dbfiddle.uk/Beefs-UH" rel="nofollow noreferrer">https://dbfiddle.uk/Beefs-UH</a></p> <p>IMPORTANT NOTE: The primary key i.e id is a unique identifier string not an integer. So the records cannot be sorted on id.</p>
[ { "answer_id": 74424663, "author": "Diszonaurusz", "author_id": 9339971, "author_profile": "https://Stackoverflow.com/users/9339971", "pm_score": 1, "selected": false, "text": "WITH RECURSIVE cte (id, name, parentId, path, lvl) AS (\n -- Initial step\n SELECT\n id,\n name,\n parentId,\n path,\n 1\n FROM categories\n WHERE id = 3\n\n UNION ALL\n\n -- Follow the \"parent-chain\"\n SELECT\n cat.id,\n cat.name,\n cat.parentId,\n cat.path,\n cte.lvl + 1\n FROM cte\n INNER JOIN categories cat\n ON cte.parentId = cat.id\n)\n\nSELECT id, name, parentId, path\nFROM cte\nORDER BY lvl DESC\n;\n" }, { "answer_id": 74424943, "author": "ahmed", "author_id": 12705912, "author_profile": "https://Stackoverflow.com/users/12705912", "pm_score": 2, "selected": true, "text": "with recursive cte (id, name, parentId, path, ord) as \n(\n select id, name, parentId, path, 1 as ord\n from categories\n where id = 'A2'\n union all\n select c.id, c.name, c.parentId, c.path, t.ord+1\n from categories c join cte t\n on t.parentId = c.id \n)\nselect * from cte\norder by ord desc;\n" }, { "answer_id": 74485286, "author": "JHH", "author_id": 20127235, "author_profile": "https://Stackoverflow.com/users/20127235", "pm_score": 0, "selected": false, "text": "categories" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3924832/" ]
74,404,784
<p>I'm desperately trying to populate my ListView with downloaded Graphics at runtime. So far I've tried several approaches but i couldn't get it to work properly.</p> <p>The Download and display for itself (i tested in a canvas called pic, so there's still fragments in the code) works fine, but the ListView won't display the damn image.</p> <p>C# code:</p> <pre><code> private async void LoadFlags(RootAutomarken automarken) { Image flag = new Image(); var client = new HttpClient(); foreach (var item in automarken.Automarken) { flag = await LoadFlag(item.Land, client); mainList.Items.Add(new CarListItem { Logo = flag, Name = item.Name, Land = item.Land, Region = item.Region}); } } private async Task&lt;Image&gt; LoadFlag(string countrycode, HttpClient client) { var request = new HttpRequestMessage { Method = HttpMethod.Get, RequestUri = new Uri(&quot;https://www.countryflagsapi.com/png/&quot; + countrycode), }; using (var response = await client.SendAsync(request)) { response.EnsureSuccessStatusCode(); Stream imageStreamSource = await response.Content.ReadAsStreamAsync(); PngBitmapDecoder decoder = new PngBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); BitmapSource bitmapSource = decoder.Frames[0]; // Draw the Image Image myImage = new Image(); myImage.Source = bitmapSource; myImage.Stretch = Stretch.Uniform; myImage.Height = 15; myImage.Width = 15; myImage.Margin = new Thickness(20); pic.Children.Add(myImage); return myImage; } </code></pre> <p>XAML:</p> <pre><code> &lt;Window.Resources&gt; &lt;Style TargetType=&quot;GridViewColumnHeader&quot;&gt; &lt;Setter Property=&quot;Background&quot; Value=&quot;#505050&quot; /&gt; &lt;Setter Property=&quot;Foreground&quot; Value=&quot;#FFDADADA&quot; /&gt; &lt;Setter Property=&quot;BorderBrush&quot; Value=&quot;#606060&quot; /&gt; &lt;/Style&gt; &lt;/Window.Resources&gt; &lt;Grid&gt; &lt;ListView x:Name=&quot;mainList&quot; Background=&quot;#202020&quot; Margin=&quot;20,100,20,10&quot; BorderBrush=&quot;#505050&quot; Foreground=&quot;#FFDADADA&quot;&gt; &lt;ListView.View&gt; &lt;GridView&gt; &lt;GridViewColumn Header=&quot;Logo&quot; Width=&quot;50&quot;&gt; &lt;GridViewColumn.CellTemplate&gt; &lt;DataTemplate&gt; &lt;Image Source=&quot;{Binding Logo}&quot;/&gt; &lt;/DataTemplate&gt; &lt;/GridViewColumn.CellTemplate&gt; &lt;/GridViewColumn&gt; &lt;GridViewColumn Header=&quot;Name&quot; DisplayMemberBinding=&quot;{Binding Name}&quot; Width=&quot;565&quot;/&gt; &lt;GridViewColumn Header=&quot;Land&quot; DisplayMemberBinding=&quot;{Binding Land}&quot; Width=&quot;50&quot;/&gt; &lt;GridViewColumn Header=&quot;Region&quot; DisplayMemberBinding=&quot;{Binding Region}&quot; Width=&quot;50&quot;/&gt; &lt;/GridView&gt; &lt;/ListView.View&gt; &lt;/ListView&gt; &lt;Canvas x:Name=&quot;pic&quot;&gt;&lt;/Canvas&gt; &lt;/Grid&gt; </code></pre>
[ { "answer_id": 74424663, "author": "Diszonaurusz", "author_id": 9339971, "author_profile": "https://Stackoverflow.com/users/9339971", "pm_score": 1, "selected": false, "text": "WITH RECURSIVE cte (id, name, parentId, path, lvl) AS (\n -- Initial step\n SELECT\n id,\n name,\n parentId,\n path,\n 1\n FROM categories\n WHERE id = 3\n\n UNION ALL\n\n -- Follow the \"parent-chain\"\n SELECT\n cat.id,\n cat.name,\n cat.parentId,\n cat.path,\n cte.lvl + 1\n FROM cte\n INNER JOIN categories cat\n ON cte.parentId = cat.id\n)\n\nSELECT id, name, parentId, path\nFROM cte\nORDER BY lvl DESC\n;\n" }, { "answer_id": 74424943, "author": "ahmed", "author_id": 12705912, "author_profile": "https://Stackoverflow.com/users/12705912", "pm_score": 2, "selected": true, "text": "with recursive cte (id, name, parentId, path, ord) as \n(\n select id, name, parentId, path, 1 as ord\n from categories\n where id = 'A2'\n union all\n select c.id, c.name, c.parentId, c.path, t.ord+1\n from categories c join cte t\n on t.parentId = c.id \n)\nselect * from cte\norder by ord desc;\n" }, { "answer_id": 74485286, "author": "JHH", "author_id": 20127235, "author_profile": "https://Stackoverflow.com/users/20127235", "pm_score": 0, "selected": false, "text": "categories" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14950596/" ]
74,404,785
<p>I have to write a program that takes a student ID and a number as input and then lowers all student notes by that that number except for one student based on the inputed ID. Here's what i mean: String = &quot;Simon, 12345, 75\n Nick, 23456, 85\n Frank, 34567, 97\n</p> <p>there's the students' names then their id and then their grade. i have to grab one ID as input and keep that student's grade intact but lower all the other grades by the inputed number.</p> <pre><code>System.out.print(&quot;Quel est le matricule de la note à conserver ? &quot;); String matricule = Keyboard.readString(); System.out.print(&quot;Combien voulez-vous enlever ? &quot;); int baisse = Keyboard.readInt(); String temporaireD = &quot;&quot;; int débutÉlève = 0; int finÉlève = 0; for (débutÉlève = 0; débutÉlève &lt; notesDéchiffrées.length(); débutÉlève = finÉlève + 1){ finÉlève = notesDéchiffrées.indexOf('\n', débutÉlève); String noteÉlève = notesDéchiffrées.substring(notesDéchiffrées.lastIndexOf(&quot;, &quot;), finÉlève); if (notesDéchiffrées.indexOf(matricule) == -1){ int note = Integer.parseInt(noteÉlève); note = note - baisse; String noteString = String.valueOf(note); String nouvelÉlève = notesDéchiffrées.substring(débutÉlève, finÉlève); } else{ String bonÉlève = notesDéchiffrées.substring(débutÉlève, finÉlève); continue; } } </code></pre>
[ { "answer_id": 74405178, "author": "kladderradatsch", "author_id": 5841551, "author_profile": "https://Stackoverflow.com/users/5841551", "pm_score": 1, "selected": false, "text": "public static void decreaseGrade(String studentId, int reduction) {\n String studentRecord = \"Simon, 12345, 75\\n Nick, 23456, 85\\n Frank, 34567, 97\\n\";\n String[] csvArray = studentRecord.split(\"\\n\");\n for(String student : csvArray) {\n String[] studentAttributes = student.split(\", \");\n String name = studentAttributes[0].trim();\n String id = studentAttributes[1].trim();\n Integer grade = Integer.valueOf(studentAttributes[2].trim());\n if (!studentId.equals(id)) {\n grade -= reduction;\n }\n System.out.println(\"Name: \" + name + \", ID: \" + id + \", Grade: \" + grade);\n }\n}\n" }, { "answer_id": 74409552, "author": "Basil Bourque", "author_id": 642706, "author_profile": "https://Stackoverflow.com/users/642706", "pm_score": 0, "selected": false, "text": "String targetId = \"23456\";\nint reduction = 10;\n\nString input =\n \"\"\"\n Simon, 12345, 75\n Nick, 23456, 85\n Frank, 34567, 97\n \"\"\";\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20389234/" ]
74,404,833
<p>I'm building an Azure Functions App (targeting .NET 6) and trying to use my own NuGet packages for my class libraries.</p> <p>The strange thing is that if I try to use my NuGet packages, I get the following error. If I, however, just create a reference to the actual projects for my class libraries on my computer, everything works fine.</p> <p>The main error displayed in Visual Studio is:</p> <blockquote> <p>WebJobsBuilderExtensions.cs not found</p> </blockquote> <p>The details display the following:</p> <blockquote> <p>System.IO.FileNotFoundException HResult=0x80070002 Message=Could not load file or assembly 'Microsoft.Extensions.Configuration.Abstractions, Version=7.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. The system cannot find the file specified.</p> </blockquote> <p>I manually installed the <code>Microsoft.Extensions.Configuration.Abstractions</code> NuGet package (version 7) to solve the issue but it's still throwing this error.</p> <p>Any idea what maybe causing this issue?</p>
[ { "answer_id": 74405178, "author": "kladderradatsch", "author_id": 5841551, "author_profile": "https://Stackoverflow.com/users/5841551", "pm_score": 1, "selected": false, "text": "public static void decreaseGrade(String studentId, int reduction) {\n String studentRecord = \"Simon, 12345, 75\\n Nick, 23456, 85\\n Frank, 34567, 97\\n\";\n String[] csvArray = studentRecord.split(\"\\n\");\n for(String student : csvArray) {\n String[] studentAttributes = student.split(\", \");\n String name = studentAttributes[0].trim();\n String id = studentAttributes[1].trim();\n Integer grade = Integer.valueOf(studentAttributes[2].trim());\n if (!studentId.equals(id)) {\n grade -= reduction;\n }\n System.out.println(\"Name: \" + name + \", ID: \" + id + \", Grade: \" + grade);\n }\n}\n" }, { "answer_id": 74409552, "author": "Basil Bourque", "author_id": 642706, "author_profile": "https://Stackoverflow.com/users/642706", "pm_score": 0, "selected": false, "text": "String targetId = \"23456\";\nint reduction = 10;\n\nString input =\n \"\"\"\n Simon, 12345, 75\n Nick, 23456, 85\n Frank, 34567, 97\n \"\"\";\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1705266/" ]
74,404,834
<p>I'm observing a behavior that's weird to me, can anyone tell me how I can define filter once and re-use throughout my code?</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; df = pd.DataFrame([1,2,3], columns=['A']) &gt;&gt;&gt; my_filter = df.A == 2 &gt;&gt;&gt; df.loc[1] = 5 &gt;&gt;&gt; df[my_filter] A 1 5 </code></pre> <p>I expect my_filter to return empty dataset since none of the A columns are equal to 2.</p> <p>I'm thinking about making a function that returns the filter and re-use that but is there any more pythonic as well as pandaic way of doing this?</p> <pre class="lang-py prettyprint-override"><code>def get_my_filter(df): return df.A == 2 df[get_my_filter()] change df df[get_my_filter()] </code></pre>
[ { "answer_id": 74405178, "author": "kladderradatsch", "author_id": 5841551, "author_profile": "https://Stackoverflow.com/users/5841551", "pm_score": 1, "selected": false, "text": "public static void decreaseGrade(String studentId, int reduction) {\n String studentRecord = \"Simon, 12345, 75\\n Nick, 23456, 85\\n Frank, 34567, 97\\n\";\n String[] csvArray = studentRecord.split(\"\\n\");\n for(String student : csvArray) {\n String[] studentAttributes = student.split(\", \");\n String name = studentAttributes[0].trim();\n String id = studentAttributes[1].trim();\n Integer grade = Integer.valueOf(studentAttributes[2].trim());\n if (!studentId.equals(id)) {\n grade -= reduction;\n }\n System.out.println(\"Name: \" + name + \", ID: \" + id + \", Grade: \" + grade);\n }\n}\n" }, { "answer_id": 74409552, "author": "Basil Bourque", "author_id": 642706, "author_profile": "https://Stackoverflow.com/users/642706", "pm_score": 0, "selected": false, "text": "String targetId = \"23456\";\nint reduction = 10;\n\nString input =\n \"\"\"\n Simon, 12345, 75\n Nick, 23456, 85\n Frank, 34567, 97\n \"\"\";\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1066820/" ]
74,404,847
<p>I am trying to understand indexing in a list. I try:</p> <pre><code>x= [1,2,3,[4]] x[0]=[34] x[3][0]=95 </code></pre> <p>which gives</p> <pre><code>[1, 2, 3, [95]] </code></pre> <p>but why is it not:</p> <pre><code>[34 2, 3, [95]] </code></pre> <p>? Edit: apologies my code was:</p> <pre><code>x= [1,2,3,[4]] y=list(x) x[0]=[34] x[3][0]=95 print (y) </code></pre> <p>Which gives the results I stated.</p> <p><a href="https://i.stack.imgur.com/52M50.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/52M50.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74405002, "author": "Iulian St", "author_id": 19333216, "author_profile": "https://Stackoverflow.com/users/19333216", "pm_score": 0, "selected": false, "text": "[[34], 2, 3, [95]]\n" }, { "answer_id": 74424701, "author": "not a tshirt", "author_id": 13190923, "author_profile": "https://Stackoverflow.com/users/13190923", "pm_score": 2, "selected": true, "text": "y = list(x)\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1773592/" ]
74,404,850
<p>I need to repeatedly replace all occurrence of <code>00000</code> with <code>0</code> in a binary string input.</p> <p>Although I'm able to achieve it to some extent, I do not know the logic when there are multiple consecutive 00000s like <strong>for example</strong>:</p> <ul> <li>25 0s should be replaced with one 0</li> <li>50 0s should be replaced with two 0s</li> <li>125 0s should be replaced with one 0</li> </ul> <p>Currently I have following code :</p> <pre class="lang-s prettyprint-override"><code>new_list = [] c = 0 l = list(s.split(&quot;00000&quot;)) print(l) for i in l: if i == &quot;00000&quot;: for x in range(l.index(i),l.index(i-3)): if l[x] != 0: break for y in range(0,5): del l[i-y] new_list.append(i) new_list.append(&quot;0&quot;) r_list = new_list[0:-1] r_list= ''.join(map(str, r_list)) print(r_list) </code></pre> <p>But this will not work for 25 0s. Also What would be the regex alternative for this ?</p>
[ { "answer_id": 74404917, "author": "Ben Grossmann", "author_id": 2476977, "author_profile": "https://Stackoverflow.com/users/2476977", "pm_score": 1, "selected": false, "text": "0" }, { "answer_id": 74405132, "author": "trincot", "author_id": 5459839, "author_profile": "https://Stackoverflow.com/users/5459839", "pm_score": 2, "selected": true, "text": "s = \"0\" * 125 # example input\nwhile \"00000\" in s:\n s = s.replace(\"00000\", \"0\")\nprint(s)\n" }, { "answer_id": 74410146, "author": "bobble bubble", "author_id": 5527985, "author_profile": "https://Stackoverflow.com/users/5527985", "pm_score": 0, "selected": false, "text": "import regex as re\n\ns = re.sub(r\"0000(?:(?0)|0)\", \"0\", s)\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/713200/" ]
74,404,868
<p>I am trying to calculate a simple fibonacci sequence and then print the numbers on different lines. However I want a specific amount of numbers on each line (ex: 5 numbers on each line).</p> <pre><code>a, b = 1, 1 while b &lt; 150: print(b, &quot;\n&quot;) a, b = b, a + b </code></pre> <p>The code above calculates a fibonacci sequence of numbers between 1 and 150 and is working just fine. I have tried using nested for/while loops and the \n keyword to print the sequence on different lines but I can't seem to get it to work. Could anyone give me some advice?</p>
[ { "answer_id": 74404917, "author": "Ben Grossmann", "author_id": 2476977, "author_profile": "https://Stackoverflow.com/users/2476977", "pm_score": 1, "selected": false, "text": "0" }, { "answer_id": 74405132, "author": "trincot", "author_id": 5459839, "author_profile": "https://Stackoverflow.com/users/5459839", "pm_score": 2, "selected": true, "text": "s = \"0\" * 125 # example input\nwhile \"00000\" in s:\n s = s.replace(\"00000\", \"0\")\nprint(s)\n" }, { "answer_id": 74410146, "author": "bobble bubble", "author_id": 5527985, "author_profile": "https://Stackoverflow.com/users/5527985", "pm_score": 0, "selected": false, "text": "import regex as re\n\ns = re.sub(r\"0000(?:(?0)|0)\", \"0\", s)\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20479039/" ]
74,404,871
<p>There are 2 lists and my goal is to add the element from one list before and after the delimiters of another list. Below is the example:</p> <pre class="lang-py prettyprint-override"><code>ListA = [&quot;A&quot;, &quot;B&quot;] ListB = [[1, 2, 3, 4], [5, 6, 7, 8]] </code></pre> <p>Expected Output:</p> <pre><code>[[1, 'A', 2, 'A', 3, 'A', 4, 'A'], [5, 'B', 6, 'B', 7, 'B', 8, 'B']] </code></pre> <p>What I've done so far:</p> <pre class="lang-py prettyprint-override"><code>for x, y in zip(ListB, ListA): x.append(y) </code></pre> <p>Output: ListB</p> <pre><code>[[1, 2, 3, 4, 'A'], [5, 6, 7, 8, 'B']] </code></pre>
[ { "answer_id": 74404937, "author": "Swifty", "author_id": 20267366, "author_profile": "https://Stackoverflow.com/users/20267366", "pm_score": 2, "selected": true, "text": "ListA = ['A','B']\nListB = [[1,2,3,4],[5,6,7,8]]\n\nfor x, y in zip(ListB, ListA):\n for i in range(len(x)):\n x.insert(2*i+1,y)\n\nprint(ListB)\n# [[1, 'A', 2, 'A', 3, 'A', 4, 'A'], [5, 'B', 6, 'B', 7, 'B', 8, 'B']]\n" }, { "answer_id": 74404962, "author": "Samwise", "author_id": 3799759, "author_profile": "https://Stackoverflow.com/users/3799759", "pm_score": 0, "selected": false, "text": "zip" }, { "answer_id": 74406389, "author": "S.B", "author_id": 13944524, "author_profile": "https://Stackoverflow.com/users/13944524", "pm_score": 0, "selected": false, "text": "from itertools import repeat\n\nListA = [\"A\", \"B\"]\nListB = [[1, 2, 3, 4], [5, 6, 7, 8]]\n\nresult = []\nfor x, y in zip(ListA, ListB):\n nested_list = []\n for item in zip(y, repeat(x)):\n nested_list.extend(item)\n result.append(nested_list)\n\nprint(result)\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20470119/" ]
74,404,895
<p>I'm having a huge problem with the configuration/dependency injection of an application.</p> <p>I have a singleton class added through DI with AddSingleton, that has in its constructor a IRequestClient, that is scoped because <code>busConfigurator.AddRequestClient()</code> which among other things, has the same effect as AddScoped.</p> <p>When I start the app, it says &quot;Cannot consume scoped service 'MassTransit.IRequestClient`1[...]' from singleton '...'.)&quot;</p> <p>Which absolutely makes sense.</p> <p>The weirdest thing is that I have another app set up the exact same way, but it just works and I would really like for that class to remain singleton.</p> <p>My colleague and I spent an entire day trying to find the differences between the two applications, but they are virtually the same in their configurations, so we are having trouble in understanding why one works while the other doesn't.</p> <p>I'm not entirely sure on what details could be important to better define the problem, so feel free to ask.</p> <p>We've looked all around the internet trying to find a solution, but it was always &quot;Change singleton to transient&quot;, but that's not an option, first because it HAS to be a singleton, otherwise it wouldn't make sense in our app, as that thing is what caches lots of date from our db so we can't just go around keeping on collecting heaps of data, second because the first app works with singleton, not with transient and we'd like to keep it that way</p> <pre><code>// This method is called in Main() private static void ConfigureMassTransit(IServiceCollection services) { services.AddMassTransit(busConfigurators =&gt; { busConfigurators.AddRequestClient&lt;ICacheRepository&gt;(); busConfigurators.AddConsumers(typeof(Program).GetTypeInfo().Assembly); busConfigurators.UsingRabbitMq((context, cfg) =&gt; { cfg.Host(new Uri($&quot;rabbitmq://{Config.Settings.RabbitMq_Host}&quot;), hostConfigurator =&gt; { hostConfigurator.Username(Config.Settings.RabbitMq_User); hostConfigurator.Password(Config.Settings.RabbitMq_Password); }); cfg.ReceiveEndpoint(&quot;myApp&quot;, e =&gt; { e.ConfigureConsumers(context); }); }); }); // CacheRepository public class CacheRepository : ICacheRepository { private readonly IClient Client; public CacheRepository(ICacheRepository client, ILogger&lt;CacheRepository&gt; logger) { this.client = client; this.logger = logger; } } </code></pre>
[ { "answer_id": 74404937, "author": "Swifty", "author_id": 20267366, "author_profile": "https://Stackoverflow.com/users/20267366", "pm_score": 2, "selected": true, "text": "ListA = ['A','B']\nListB = [[1,2,3,4],[5,6,7,8]]\n\nfor x, y in zip(ListB, ListA):\n for i in range(len(x)):\n x.insert(2*i+1,y)\n\nprint(ListB)\n# [[1, 'A', 2, 'A', 3, 'A', 4, 'A'], [5, 'B', 6, 'B', 7, 'B', 8, 'B']]\n" }, { "answer_id": 74404962, "author": "Samwise", "author_id": 3799759, "author_profile": "https://Stackoverflow.com/users/3799759", "pm_score": 0, "selected": false, "text": "zip" }, { "answer_id": 74406389, "author": "S.B", "author_id": 13944524, "author_profile": "https://Stackoverflow.com/users/13944524", "pm_score": 0, "selected": false, "text": "from itertools import repeat\n\nListA = [\"A\", \"B\"]\nListB = [[1, 2, 3, 4], [5, 6, 7, 8]]\n\nresult = []\nfor x, y in zip(ListA, ListB):\n nested_list = []\n for item in zip(y, repeat(x)):\n nested_list.extend(item)\n result.append(nested_list)\n\nprint(result)\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404895", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19296211/" ]
74,404,919
<p>Hey (Sorry bad english) so am going to try and make my question more clear. if i have a function let's say create_username_dict(name_list, username_list). which takes in two list's 1 being the name_list with names of people than the other list being usernames that is made out of the names of people. what i want to do is take does two list than convert them to a dictonary and set them together. like this:</p> <pre><code>&gt;&gt;&gt; name_list = [&quot;Ola Nordmann&quot;, &quot;Kari Olsen&quot;, &quot;Roger Jensen&quot;] &gt;&gt;&gt; username_list = [&quot;alejon&quot;, &quot;carli&quot;, &quot;hanri&quot;] &gt;&gt;&gt; create_username_dict(name_list, username_list) { &quot;Albert Jones&quot;: &quot;alejon&quot;, &quot;Carlos Lion&quot;: &quot;carli&quot;, &quot;Hanna Richardo&quot;: &quot;hanri&quot; } </code></pre> <p>i have tried look around on how to connect two different list in too one dictonary, but can't seem to find the right solution</p>
[ { "answer_id": 74404937, "author": "Swifty", "author_id": 20267366, "author_profile": "https://Stackoverflow.com/users/20267366", "pm_score": 2, "selected": true, "text": "ListA = ['A','B']\nListB = [[1,2,3,4],[5,6,7,8]]\n\nfor x, y in zip(ListB, ListA):\n for i in range(len(x)):\n x.insert(2*i+1,y)\n\nprint(ListB)\n# [[1, 'A', 2, 'A', 3, 'A', 4, 'A'], [5, 'B', 6, 'B', 7, 'B', 8, 'B']]\n" }, { "answer_id": 74404962, "author": "Samwise", "author_id": 3799759, "author_profile": "https://Stackoverflow.com/users/3799759", "pm_score": 0, "selected": false, "text": "zip" }, { "answer_id": 74406389, "author": "S.B", "author_id": 13944524, "author_profile": "https://Stackoverflow.com/users/13944524", "pm_score": 0, "selected": false, "text": "from itertools import repeat\n\nListA = [\"A\", \"B\"]\nListB = [[1, 2, 3, 4], [5, 6, 7, 8]]\n\nresult = []\nfor x, y in zip(ListA, ListB):\n nested_list = []\n for item in zip(y, repeat(x)):\n nested_list.extend(item)\n result.append(nested_list)\n\nprint(result)\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20241890/" ]
74,404,936
<p>I've searched for days, piecing together code from other posts around Stack Overflow and from the learn.microsoft.com documentation for a solution to this and I'm struggling... It doesn't help that I'm relatively new to Outlook VBA.</p> <p>What I want to happen is that when I create a new email using the default ribbon button, automatically add a greeting to the body while also keeping the default signature that is added. (Also wanting this to work for inline replies, but I'm focusing on this first).</p> <p>I already have a public function that uses <code>TimeValue</code> to calculate whether to add &quot;Good morning,&quot; or &quot;Good afternoon,&quot;, it works and returns as a string. I call a sister function that takes that string and adds it to the email. This part works.</p> <p>Both of these are in a module called &quot;AutoGreeting&quot;</p> <pre><code>Option Explicit Public Function Greeting() As String ' Defines greeting by time of day ' ' Used in with the AddGreeting() function and clsMailHandler ' ' If before noon, greeting is Good Morning' If Time &gt;= TimeValue(&quot;8:00 AM&quot;) And Time &lt;= TimeValue(&quot;11:59 AM&quot;) Then Greeting = &quot;Good morning,&quot; ' If after noon and before work ends, greeting is Good Afternoon' ElseIf Time &gt;= TimeValue(&quot;12:00 PM&quot;) And Time &lt;= TimeValue(&quot;5:10 PM&quot;) Then Greeting = &quot;Good afternoon,&quot; End If End Function ' call this function to add the above calculated greeting to an email ' ' i.e. Call AddGreeting(NewlyCreatedEmail) Public Function AddGreeting(ByRef DraftEmail As mailItem) ' DraftEmail is used with reference to any MailItem object ' ' like in clsMailHander &gt; NewInspector &gt; objCurrentItem / objMailNew ' With DraftEmail ' Temporarily editing the subject for testing/debugging to make sure this works .Subject = &quot;AddGreeting Function&quot; ' This adds the greeting but isn't able to keep the OG body AKA the auto-signature ' Because newInspector fires before signature is added .HTMLBody = Greeting() &amp; DraftEmail.HTMLBody End With End Function </code></pre> <p>I'm also building a class module for event handling that is able to detect when a new inspector opens and that it's a mailitem. (Unfortunately, it's seems it's not able to detect yet whether it's a <em>new</em> email or if it's an email that's been retrieved and opened. like if you double-click an email from your inbox, it opens in an inspector window. I do this by accident sometimes).</p> <p>Explorers and the <code>objMailReply</code> variable are in there because I also want this to work this inline replies. I have the event handlers for <code>newExplorer</code> and <code>ActiveInlineResponse</code> that I left out here because I'm focusing on just new emails in the inspectors for now.</p> <p>Class module is called &quot;clsMailHandler&quot;</p> <pre><code>' Class for event handling of created emails ' re-start Outlook after compiling and saving changes to re-initialize class ' or run Application_Quit and Application_Startup from ThisOutlookSession cls Option Explicit Public WithEvents olApp As Outlook.Application Public WithEvents objInspectors As Outlook.Inspectors Public WithEvents objActInspector As Outlook.Inspector Public WithEvents objExplorers As Outlook.Explorers Public WithEvents objActExplorer As Outlook.Explorer Public WithEvents objCurrentItem As Outlook.mailItem Public WithEvents objMailNew As Outlook.mailItem Public WithEvents objMailReply As Outlook.mailItem ' Called under Application_Startup in ThisOutlookSession as Handler class is created Public Sub Class_Initialize() Set olApp = Outlook.Application ' so far, all that's needed here is to initialize the explorers and inspectors w/ the app itself Set objInspectors = olApp.Inspectors Set objExplorers = olApp.Explorers Set objActExplorer = olApp.ActiveExplorer End Sub ' Called in Application_Quit as handler class is cleared Public Sub Class_Terminate() 'when the application is closed, the class is terminated 'un-set variables Set olApp = Nothing Set objInspectors = Nothing Set objActInspector = Nothing Set objExplorers = Nothing Set objActExplorer = Nothing Set objMailNew = Nothing Set objMailReply = Nothing Set objCurrentItem = Nothing End Sub ' Event handler for a new inspector window opening (i.e. new email is created) ' ISSUE - or when a received email is opened in a new window (double-click) Public Sub objInspectors_NewInspector(ByVal Inspector As Outlook.Inspector) Dim insType As String Set objActInspector = Inspector ' this is just to keep names of object variables short and easy to remember Set objCurrentItem = objActInspector.CurrentItem ' grab &amp; test type name of current inspector item insType = TypeName(objCurrentItem) If insType = &quot;MailItem&quot; Then ' if its a mailItem - set variable that's more specific Set objMailNew = objCurrentItem ' MsgBox is for debugging to make sure this fires MsgBox (&quot;New email has been created&quot;) ' Function from other module that is called to add the greeting ' Again, this works to add the greeting, but it doesn't keep the auto-signature Call AddGreeting(objMailNew) End If End Sub ' This also fires if a received email that was opened in a new window is closed. Public Sub objActInspector_Close() ' if the inspector window (created email) is closed, clear the variables Set objMailNew = Nothing Set objCurrentItem = Nothing MsgBox (&quot;Inspector has closed&quot;) End Sub </code></pre> <p>This is how the class is initialized from within ThisOutlookSession</p> <pre><code>Option Explicit 'Instantiate the class on global application level Dim EventHandler As clsMailHandler Sub Application_Startup() 'Set custom variable as new instance of class 'to initialize the class (run Class_Initialize() sub) Set EventHandler = New clsMailHandler End Sub Sub Application_Quit() 'Set handler to nothing to clear instance of class Set EventHandler = Nothing End Sub </code></pre> <p>The trouble I'm running into, is that the event handler for <code>newInspector</code> can call the function that adds the greeting (and edits the subject for testing/debugging purposes), but then my auto-signature doesn't get added. I think because the <code>newInspector</code> event fires off before the email actually exists, so the automatic signature doesn't fire. It's also complicated by my signature needing specific formatting and to contain an image, so just adding it as plain text doesn't work.</p> <p>Most of the solutions I see involve programmatically creating the email <code>CreateItem(olMailItem)</code>, but I don't want to do it that way. I want to apply these to the way an email is created by default.</p> <p>Some things I've seen sound like they might work for what I need but I don't know how to implement them as I can't find examples that I understand. Namely, <code>inspector_activate</code> like from this post <a href="https://stackoverflow.com/questions/20024199/event-that-fires-after-signature-is-added">Event that fires after signature is added</a>.</p> <p>How do I get my automatic greeting and keep my automatic signature?</p> <p>EDIT: I fixed it myself, solution is added as an answer below.</p>
[ { "answer_id": 74404937, "author": "Swifty", "author_id": 20267366, "author_profile": "https://Stackoverflow.com/users/20267366", "pm_score": 2, "selected": true, "text": "ListA = ['A','B']\nListB = [[1,2,3,4],[5,6,7,8]]\n\nfor x, y in zip(ListB, ListA):\n for i in range(len(x)):\n x.insert(2*i+1,y)\n\nprint(ListB)\n# [[1, 'A', 2, 'A', 3, 'A', 4, 'A'], [5, 'B', 6, 'B', 7, 'B', 8, 'B']]\n" }, { "answer_id": 74404962, "author": "Samwise", "author_id": 3799759, "author_profile": "https://Stackoverflow.com/users/3799759", "pm_score": 0, "selected": false, "text": "zip" }, { "answer_id": 74406389, "author": "S.B", "author_id": 13944524, "author_profile": "https://Stackoverflow.com/users/13944524", "pm_score": 0, "selected": false, "text": "from itertools import repeat\n\nListA = [\"A\", \"B\"]\nListB = [[1, 2, 3, 4], [5, 6, 7, 8]]\n\nresult = []\nfor x, y in zip(ListA, ListB):\n nested_list = []\n for item in zip(y, repeat(x)):\n nested_list.extend(item)\n result.append(nested_list)\n\nprint(result)\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8802953/" ]
74,404,946
<p>Im working on a school project and i want to pass more then one value thru the url. The page show more then one user from the Database.</p> <p>This is what im trying to do so far, and i get a</p> <blockquote> <p>Parse error: syntax error, unexpected string content &quot;&quot;, expecting &quot;-&quot; or identifier or variable or number in C:\xampp\htdocs\admin.php on line 79</p> </blockquote> <p>This is the code im trying to use</p> <pre><code>&lt;?php //loop over alle reservationerne og display dem i en table, hvis de ikke er tomme $num=mysqli_num_rows($query); if($num&gt;0) { while($result=mysqli_fetch_assoc($query)) { echo &quot; &lt;div class='table-card'&gt; &lt;div class='table-num'&gt; &lt;div class='table'&gt;&lt;a&gt;Bord &quot; .$result[&quot;Bord&quot;].&quot;&lt;/a&gt;&lt;/div&gt; &lt;div class='fjern'&gt;&lt;a OnClick=\&quot;return confirm('Er du sikker på du vil slette reservationen');\&quot; href='admin.php?id=$result['ID']&amp;navn=$result['Navn']'&gt;X&lt;/a&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class='table-info'&gt; </code></pre> <p>And this is the part giving me trouble</p> <pre><code>&lt;div class='fjern'&gt;&lt;a OnClick=\&quot;return confirm('Er du sikker på du vil slette reservationen');\&quot; href='admin.php?id=$result['ID']&amp;navn=$result['Navn']'&gt;X&lt;/a&gt;&lt;/div&gt; </code></pre> <pre><code>&lt;?php // Initialize the session session_start(); // Tjek om brugeren er logget ind, hvis ikke redirect dem til login siden if(!isset($_SESSION[&quot;loggedin&quot;]) || $_SESSION[&quot;loggedin&quot;] !== true){ header(&quot;location: login.php&quot;); exit; } //connect til databasen require_once &quot;config.php&quot;; //Få fat på id så vi kan delete bestemte reservationer if(isset($_GET['id'])) { $id=$_GET['id']; $navn=$_GET['Navn']; $sql = &quot;INSERT INTO `reject`(`ID`, `Navn`) VALUES (?, ?)&quot;; $stmt = $link-&gt;prepare($sql); $stmt-&gt;bind_param(&quot;is&quot;, $id, $navn); $stmt-&gt;execute(); $delete = &quot;DELETE FROM reservation WHERE ID=$id;&quot;; $svar = $link-&gt;query($delete); } //setup så vi kan vise reservationerne $select =&quot;select * from reservation ORDER BY Klok&quot;; $query = $link-&gt;query($select); $link -&gt; close(); ?&gt; </code></pre>
[ { "answer_id": 74405221, "author": "RiggsFolly", "author_id": 2310830, "author_profile": "https://Stackoverflow.com/users/2310830", "pm_score": 0, "selected": false, "text": "echo \"<div class='table-card'> \n <div class='table-num'>\n <div class='table'>\n <a>Bord $result[Bord]</a>\n </div>\n <div class='fjern'>\n <a OnClick='return confirm(\\\"Er du sikker på du vil slette reservationen\\\"');' \n href='admin.php?id=$result[ID]&navn=$result[Navn]'>X</a></div>\n </div>\n <div class='table-info'>\";\n" }, { "answer_id": 74405254, "author": "Dab", "author_id": 14262765, "author_profile": "https://Stackoverflow.com/users/14262765", "pm_score": 1, "selected": false, "text": "<div class='fjern'><a OnClick=\\\"return confirm('Er du sikker på du vil slette reservationen');\\\" href='admin.php?id={$result['ID']}&navn={$result['Navn']}'>X</a></div>\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404946", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14262765/" ]
74,404,984
<p>I am still new to developing integrations in OIC. I am using the Oracle ERP Adapter in OIC to update some Invoice staging tables in ERP Cloud. I accidently populated a field with a value that I didn't intend to, and now I am trying to re-update to set it back so it shows as <code>NULL</code> in the staging table. I've tried passing a blank value in the mapper as <code>''</code> and <code>&quot;&quot;</code> and the API must be ignoring that as the table value remains with the (incorrect) value still populated.</p> <p>I've also tried using &quot;xsi:nil=true&quot; in the mapper as you see below, but it just sends the literal value in quotes to the table. Removing the quotes results in a validation error in OIC.</p> <p>How can I accomplish this?</p> <p><a href="https://i.stack.imgur.com/RlRmT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RlRmT.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74405221, "author": "RiggsFolly", "author_id": 2310830, "author_profile": "https://Stackoverflow.com/users/2310830", "pm_score": 0, "selected": false, "text": "echo \"<div class='table-card'> \n <div class='table-num'>\n <div class='table'>\n <a>Bord $result[Bord]</a>\n </div>\n <div class='fjern'>\n <a OnClick='return confirm(\\\"Er du sikker på du vil slette reservationen\\\"');' \n href='admin.php?id=$result[ID]&navn=$result[Navn]'>X</a></div>\n </div>\n <div class='table-info'>\";\n" }, { "answer_id": 74405254, "author": "Dab", "author_id": 14262765, "author_profile": "https://Stackoverflow.com/users/14262765", "pm_score": 1, "selected": false, "text": "<div class='fjern'><a OnClick=\\\"return confirm('Er du sikker på du vil slette reservationen');\\\" href='admin.php?id={$result['ID']}&navn={$result['Navn']}'>X</a></div>\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4408559/" ]
74,404,997
<p>i have defined the following custom class:</p> <pre><code>class Point(): def __init__(self, x, y, z): self.x = x self.y = y self.z = z </code></pre> <p>and I have a list of <code>Point</code> objects called <code>points</code>. I now need to plot this points in a 3D scatter. Is there a quick way to get the x values for all the points that I can implement inside the class definition? I know I can do this with</p> <pre><code>xs = [p.x for p in points] ys = ... </code></pre> <p>but it is a bit tedious. Does anybody know a way to incororate this maybe inside my class? Or maybe I need to define a <code>PointList</code> class?</p> <p>Thanks</p>
[ { "answer_id": 74405221, "author": "RiggsFolly", "author_id": 2310830, "author_profile": "https://Stackoverflow.com/users/2310830", "pm_score": 0, "selected": false, "text": "echo \"<div class='table-card'> \n <div class='table-num'>\n <div class='table'>\n <a>Bord $result[Bord]</a>\n </div>\n <div class='fjern'>\n <a OnClick='return confirm(\\\"Er du sikker på du vil slette reservationen\\\"');' \n href='admin.php?id=$result[ID]&navn=$result[Navn]'>X</a></div>\n </div>\n <div class='table-info'>\";\n" }, { "answer_id": 74405254, "author": "Dab", "author_id": 14262765, "author_profile": "https://Stackoverflow.com/users/14262765", "pm_score": 1, "selected": false, "text": "<div class='fjern'><a OnClick=\\\"return confirm('Er du sikker på du vil slette reservationen');\\\" href='admin.php?id={$result['ID']}&navn={$result['Navn']}'>X</a></div>\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404997", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15673412/" ]
74,405,009
<p>I'm implementing the Logout action in an application. I want that when user clicks Logout, go to Login. When the user takes this path: Login -&gt; Home -&gt; Settings (where he clicks on Logout) -&gt; Login, when I press back, the app goes to the background and closes, which is the behavior I want.</p> <p>However, when the user takes this route: Login -&gt; Home -&gt; ScreenOne -&gt; ScreenTwo -&gt; Home -&gt; ScreenOne -&gt; Settings (where you click on Logout) -&gt; Login, when you press back, it goes back to Settings and if you press it again it goes to ScreenOne and so on .</p> <p>That's the way I do the navigation to Login when I click on Logout:</p> <pre><code>navController.navigate(NavigationItem.Login.route) { popUpTo(NavigationItem.Login.route) { inclusive = true } } </code></pre> <p><strong>Note:</strong> Already tried Navigation.Home.route as parameter on popUpTo.</p> <p>I don't know if is related, but that's the way I do the navigation between Home -&gt; ScreenOne -&gt; ScreenTwo -&gt; Home -&gt; ScreenOne:</p> <pre><code>navController.navigate(item.route) { navController.graph.startDestinationRoute?.let { route -&gt; popUpTo(route = route) { saveState = true } } launchSingleTop = true restoreState = true } </code></pre> <p>Does anyone knows how I can clear the back stack or guarantee that, in the second behavior, when I am on Login screen after Logout and I press &quot;Back&quot;, the app goes to second plan?</p> <p><strong>EDIT:</strong> Added NavHost structure.</p> <pre><code>@Composable @ExperimentalFoundationApi @ExperimentalComposeUiApi @ExperimentalMaterialApi fun Navigation(navController: NavHostController, updateBottomBarVisibility: (Boolean) -&gt; Unit) { NavHost( navController = navController, startDestination = NavigationItem.Login.route ) { composable(route = NavigationItem.Login.route) { LoginScreen(navController) } composable(route = NavigationItem.Events.route) { EventsScreen(updateBottomBarVisibility, navController) } composable(route = NavigationItem.Home.route) { HomeScreen(updateBottomBarVisibility, navController) } composable(route = NavigationItem.Prizes.route) { PrizesScreen(updateBottomBarVisibility, navController) } composable(route = NavigationItem.Account.route) { AccountScreen(navController) } } } </code></pre>
[ { "answer_id": 74409047, "author": "Arthur Kasparian", "author_id": 19454251, "author_profile": "https://Stackoverflow.com/users/19454251", "pm_score": 1, "selected": false, "text": "// Getting your activity in a composable function\nval activity = (LocalContext.current as? Activity)\n\n// Everything put inside this block will be done on each system backpress\nBackHandler {\n activity?.finish()\n}\n" }, { "answer_id": 74411945, "author": "zjmo", "author_id": 14507326, "author_profile": "https://Stackoverflow.com/users/14507326", "pm_score": 3, "selected": true, "text": "logout" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18215416/" ]
74,405,075
<p>I have this table and I have to sort the rest after subtraction of numbers from the started numbers 350 and break if the value is equal to 0 at the end</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>Numbers</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>10</td> </tr> <tr> <td>2</td> <td>20</td> </tr> <tr> <td>3</td> <td>40</td> </tr> <tr> <td>4</td> <td>8</td> </tr> </tbody> </table> </div> <p>the expected result should look</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>Numbers</th> <th>Result</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>10</td> <td>340</td> </tr> <tr> <td>2</td> <td>20</td> <td>320</td> </tr> <tr> <td>3</td> <td>40</td> <td>280</td> </tr> <tr> <td>4</td> <td>8</td> <td>272</td> </tr> </tbody> </table> </div> <p>I am stuck on my code without knowing how to get the rest like in the table</p> <pre><code>with cte as ( select id, (SELECT sum(numbers) from TABLE t2 where t2.id &lt;= t1.id) sumT from TABLE T1 ) select sumT , ( 350 - sumT) from cte where sumT &lt;= 350 </code></pre>
[ { "answer_id": 74409047, "author": "Arthur Kasparian", "author_id": 19454251, "author_profile": "https://Stackoverflow.com/users/19454251", "pm_score": 1, "selected": false, "text": "// Getting your activity in a composable function\nval activity = (LocalContext.current as? Activity)\n\n// Everything put inside this block will be done on each system backpress\nBackHandler {\n activity?.finish()\n}\n" }, { "answer_id": 74411945, "author": "zjmo", "author_id": 14507326, "author_profile": "https://Stackoverflow.com/users/14507326", "pm_score": 3, "selected": true, "text": "logout" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4624075/" ]
74,405,080
<p>I have the following dataframe and a vector of names.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>name</th> <th>age</th> </tr> </thead> <tbody> <tr> <td>panda</td> <td>5</td> </tr> <tr> <td>polarbear</td> <td>7</td> </tr> <tr> <td>seahorse</td> <td>1</td> </tr> </tbody> </table> </div> <p>I would like to select rows by the names in the vector and calculate the average age of selected rows. I have the following code:</p> <pre class="lang-rust prettyprint-override"><code>let names = vec![&quot;panda&quot;, &quot;seahorse&quot;]; let avg = df.lazy() .select([col(&quot;name&quot;).filter(|c| names.contains(c))]) .agg([col(&quot;age&quot;).mean()]); </code></pre> <p>Intuition says, pass a function to the filter (like I have done), however this is wrong. Apparently there is some sort of Expr API in play. How does it work? I find the docs a bit puzzling.</p>
[ { "answer_id": 74409047, "author": "Arthur Kasparian", "author_id": 19454251, "author_profile": "https://Stackoverflow.com/users/19454251", "pm_score": 1, "selected": false, "text": "// Getting your activity in a composable function\nval activity = (LocalContext.current as? Activity)\n\n// Everything put inside this block will be done on each system backpress\nBackHandler {\n activity?.finish()\n}\n" }, { "answer_id": 74411945, "author": "zjmo", "author_id": 14507326, "author_profile": "https://Stackoverflow.com/users/14507326", "pm_score": 3, "selected": true, "text": "logout" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14495288/" ]
74,405,116
<p>I was practicing array problems and I stuck by this one:</p> <p>Given a declaration of 2D array:</p> <pre><code>int a[][2] = { {2,2}, {3,3}, {4,4} }; </code></pre> <p>write a nested for loop to print all the values of a.</p> <p>First, since 2D array is an array of rows (means each element of this array is a row vector),</p> <p>I tried a for loop like this:</p> <pre><code>for (int&amp; x[]: a) for (int y: x) cout &lt;&lt; y &lt;&lt; &quot; &quot;; </code></pre> <p>The outer for-loop means I want to reference each row of a, give it a name &quot;x&quot;; the inner for-loop means I want to reference each element of x, give it a name &quot;y&quot;.</p> <p>I thought the declaration in the outer for-loop is valid as I specified x as array in integer type, but error showed up while compiling. I checked out the solution and it indicated that x has to be declared as auto type, which means I should write the outer loop as &quot; <code>for(auto&amp; x: a)</code> &quot;. The solution also indicated that this is the only way, but I was not sure whether it is true or not.</p> <p>Hence, I want to figure out couple things:</p> <ol> <li>Why it was not working when I wrote a line like &quot; <code>for (int&amp; x[]: a)</code> &quot; ?</li> <li>What is the data type of x in the line &quot; <code>for (auto&amp; x : a)</code> &quot; ? What did auto detected?</li> <li>Is using auto really the only way in this situation?</li> </ol> <p>Thank you!</p>
[ { "answer_id": 74405196, "author": "john", "author_id": 882003, "author_profile": "https://Stackoverflow.com/users/882003", "pm_score": 3, "selected": true, "text": "for (int& x[] : a)" }, { "answer_id": 74405709, "author": "doug", "author_id": 5282154, "author_profile": "https://Stackoverflow.com/users/5282154", "pm_score": 1, "selected": false, "text": "#include <iostream>\nint a[][2] = { {2,2}, {3,3}, {4,4} };\n\nint main()\n{\n for (int(&x)[2] : a) // one row at a time\n {\n for (int x2 : x) // print each col in row\n {\n std::cout << x2 << \" \";\n }\n std::cout << '\\n';\n }\n}\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17754131/" ]
74,405,122
<p>I am trying to make a factory function that will be able to create objects derived from a base class using different constructors based on the given parameters. With some help from other posts here I have been able to make an example that works for a constructor that takes no parameters, but I cannot find a solution for multiple constructors.</p> <p>I have the following:</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;map&gt; #include &lt;typeinfo&gt; #include &lt;functional&gt; using namespace std; class BaseObject { public: BaseObject(){cout&lt;&lt;&quot;BaseObject def constructor\n&quot;;}; BaseObject(int type){cout&lt;&lt;&quot;BaseObject non-def constructor\n&quot;;} virtual ~BaseObject() = default; virtual string name() = 0; }; class Object1 : public BaseObject { public: Object1(){cout&lt;&lt;&quot;Object1 def constructor\n&quot;;}; Object1(int type){cout&lt;&lt;&quot;Object1 non-def constructor\n&quot;;} virtual string name() override { return &quot;I am Object1&quot;; } }; class Object2 : public BaseObject { public: Object2(){cout&lt;&lt;&quot;Object2 def constructor\n&quot;;}; Object2(int type){cout&lt;&lt;&quot;Object2 non-def constructor\n&quot;;} virtual string name() override { return &quot;I am Object2&quot;; } }; struct Factory { public: typedef std::map&lt;std::string, std::function&lt;std::unique_ptr&lt;BaseObject&gt;()&gt;&gt; FactoryMap; template&lt;class T&gt; static void register_type(const std::string &amp; name) { getFactoryMap()[name] = [](){ return std::make_unique&lt;T&gt;(); }; } static std::unique_ptr&lt;BaseObject&gt; get_object(const std::string name) { return getFactoryMap()[name](); } static std::unique_ptr&lt;BaseObject&gt; get_object(const std::string name, int type) { return getFactoryMap()[name](type); } // use a singleton to prevent SIOF static FactoryMap&amp; getFactoryMap() { static FactoryMap map; return map; } }; int main() { Factory::register_type&lt;Object1&gt;(&quot;Object1&quot;); Factory::register_type&lt;Object2&gt;(&quot;Object2&quot;); // make Object1 using default constructor std::unique_ptr&lt;BaseObject&gt; o1 = Factory::get_object(&quot;Object1&quot;); // make Object2 using non-default constructor std::unique_ptr&lt;BaseObject&gt; o2 = Factory::get_object(&quot;Object2&quot;, 1); std::cout &lt;&lt; o1-&gt;name() &lt;&lt; std::endl; std::cout &lt;&lt; o2-&gt;name() &lt;&lt; std::endl; std::cout &lt;&lt; &quot;exit&quot; &lt;&lt; std::endl; return 0; } </code></pre> <p>Both <code>Object1</code> and <code>Object2</code> have two constructors (it is simplified, in practice the one with the parameter will get some saved data) and <code>Factory</code> has two versions of <code>get_object()</code> each with the name of the object to be created and the corresponding additional parameters.</p> <p>The problem with the second <code>get_object</code></p> <pre><code> static std::unique_ptr&lt;BaseObject&gt; get_object(const std::string name, int type) { return getFactoryMap()[name](type); } </code></pre> <p>is that the call to the constructor inside passes <code>type</code> parameter, but the type of the function (as defined by <code>typedef FactoryMap</code>) has no parameters (<code>std::function&lt;std::unique_ptr&lt;BaseObject&gt;()&gt;</code>).</p> <p>I explored variadic templates but was not able to figure out how it should be done. One of the helpful post was <a href="https://codereview.stackexchange.com/questions/114578/simple-factory-retrieving-object-by-name">this one</a>, unforunately it does not have a full working code example.</p>
[ { "answer_id": 74406217, "author": "numzero", "author_id": 10992795, "author_profile": "https://Stackoverflow.com/users/10992795", "pm_score": 1, "selected": false, "text": "using Factory = BaseFactory<BaseObject, void(), void(int)>;" }, { "answer_id": 74442398, "author": "mib0163", "author_id": 4924581, "author_profile": "https://Stackoverflow.com/users/4924581", "pm_score": 1, "selected": true, "text": "BaseObject" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4924581/" ]
74,405,123
<p>I have a large data frame with 10000000 rows and 150 columns. in the dataset, there are specific rows that contain all zeros or all NAs or a combination of zeros and NAs. the sample dataframe is shown below</p> <pre><code>df &lt;- data.frame(x = c('q', 'w', 'e', 'r','t', 'y'), a = c('a','b','c','d','e','f'), b = c(0,1,2,3,0,5), c= c(0,3,2,4,0,'NA'), d=c(0,2,5,7,'NA',5), e = c(0,5,'NA',3,0,'NA'), f = c(0,7,4,3,'NA',7)) </code></pre> <p>the desired output is as follows</p> <pre><code>df1 &lt;- data.frame(x = c('w', 'e', 'r','y'), a = c('b','c','d','f'), b = c(1,2,3,5), c= c(3,2,4,'NA'), d=c(2,5,7,5), e = c(5,'NA',3,'NA'), f = c(7,4,3,7)) </code></pre> <p>i.e.</p> <pre><code>df &lt;- w b 1 3 2 5 7 e c 2 2 5 NA 4 r d 3 4 7 3 3 y f 5 NA 5 NA 7 </code></pre> <p>I tried multiple possible solutions in the stackover flow such as</p> <pre><code>df %&gt;% filter(if_all(everything(), ~ !is.na(.x))) </code></pre> <p>or</p> <pre><code>df %&gt;% </code></pre> <p>filter_if(is.numeric, ~ !is.na(.))</p> <p>but could not solve the problem</p>
[ { "answer_id": 74405421, "author": "langtang", "author_id": 4447540, "author_profile": "https://Stackoverflow.com/users/4447540", "pm_score": 3, "selected": true, "text": "apply()" }, { "answer_id": 74406066, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 1, "selected": false, "text": "library(dplyr)\ndf %>%\n filter(!if_all(where(is.numeric), ~ is.na(.x)|.x %in% 0))\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9247629/" ]
74,405,133
<p>I have a question about deleting any string within [].</p> <p>My text data has a pattern that always start with [author name, date] or so.</p> <p>For example, &quot;[Report by Jeongho Choi: &quot;Korea's Alarms Its Citizens&quot;] [Text] Of all ~~&quot;</p> <p>The two text within [] is useless, so I want to delete [Report by Jeongho Choi: &quot;Korea's Alarms Its Citizens&quot;] and [Text].</p>
[ { "answer_id": 74405421, "author": "langtang", "author_id": 4447540, "author_profile": "https://Stackoverflow.com/users/4447540", "pm_score": 3, "selected": true, "text": "apply()" }, { "answer_id": 74406066, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 1, "selected": false, "text": "library(dplyr)\ndf %>%\n filter(!if_all(where(is.numeric), ~ is.na(.x)|.x %in% 0))\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19907346/" ]
74,405,172
<p>I`m looking for a solution to adding social media icons to the Elementor-Menu in WordPress. Any Ideas?</p> <p>I could take a Burger Icon and add a pop up on top, but that would be my last option for me.</p>
[ { "answer_id": 74405421, "author": "langtang", "author_id": 4447540, "author_profile": "https://Stackoverflow.com/users/4447540", "pm_score": 3, "selected": true, "text": "apply()" }, { "answer_id": 74406066, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 1, "selected": false, "text": "library(dplyr)\ndf %>%\n filter(!if_all(where(is.numeric), ~ is.na(.x)|.x %in% 0))\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18036759/" ]
74,405,173
<p>I'm creating new variables for classes, can I do something like this?</p> <p><code>for i in range(8): s{i} = card(i, &quot;hearth&quot;) #card is class</code></p> <p>Or is there some alternative? It would be very helpful if I could do it</p> <p>I want this output</p> <p><code>s0 = card(O, &quot;hearth&quot;) s1 = card(1, &quot;hearth&quot;) #etc..</code></p>
[ { "answer_id": 74405198, "author": "Samwise", "author_id": 3799759, "author_profile": "https://Stackoverflow.com/users/3799759", "pm_score": 1, "selected": false, "text": "s = [card(i, \"hearth\") for i in range(8)]\n" }, { "answer_id": 74405210, "author": "Philip09", "author_id": 13397545, "author_profile": "https://Stackoverflow.com/users/13397545", "pm_score": 0, "selected": false, "text": "card_list = [card(i, \"hearth\") for i in range(8)]\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20479289/" ]
74,405,180
<p>Tuple in python is immutable by design, so if we try to mutate a tuple object python emits following <code>TypeError</code> which make sense.</p> <pre><code>&gt;&gt;&gt; a = (1, 2, 3) &gt;&gt;&gt; a[0] = 12 Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; TypeError: 'tuple' object does not support item assignment </code></pre> <p>So my question is, if tuple is immutable by design why cpython exposes <code>PyTuple_SetItem</code> as C-API?.</p> <p>From the documentation it's described as</p> <blockquote> <p><code>int PyTuple_SetItem(PyObject *p, Py_ssize_t pos, PyObject *o)</code></p> <p>Insert a reference to object <code>o</code> at position pos of the tuple pointed to by <code>p</code>. Return 0 on success. If pos is out of bounds, return -1 and set an IndexError exception.</p> </blockquote> <p>Isn't this statement exactly equal to <code>tuple[index] = value</code> in python layer?. If the goal was to create a tuple from collection of items we could have use <a href="https://docs.python.org/3/c-api/tuple.html#c.PyTuple_Pack" rel="nofollow noreferrer"><code>PyTuple_Pack</code></a>.</p> <p>Additional note:</p> <p>After lot of trial and error with ctypes.pythonapi I managed to mutate tuple object using <code>PyTuple_SetItem</code></p> <pre><code>import ctypes from ctypes import py_object my_tuple = (1, 2, 3) newObj = py_object(my_tuple) m = &quot;hello&quot; # I don't know why I need to Py_DecRef here. # Although to reproduce this in your system, no of times you have # to do `Py_DecRef` depends on no of ref count of `newObj` in your system ctypes.pythonapi.Py_DecRef(newObj) ctypes.pythonapi.Py_DecRef(newObj) ctypes.pythonapi.Py_DecRef(newObj) ctypes.pythonapi.Py_IncRef(m) PyTuple_SetItem = ctypes.pythonapi.PyTuple_SetItem PyTuple_SetItem.argtypes = ctypes.py_object, ctypes.c_size_t, ctypes.py_object PyTuple_SetItem(newObj, 0, m) print(my_tuple) # this will print `('hello', 2, 3)` </code></pre>
[ { "answer_id": 74405544, "author": "tdelaney", "author_id": 642070, "author_profile": "https://Stackoverflow.com/users/642070", "pm_score": 4, "selected": true, "text": "PyTuple_Resize" }, { "answer_id": 74405605, "author": "Chiheb Nexus", "author_id": 3926995, "author_profile": "https://Stackoverflow.com/users/3926995", "pm_score": 2, "selected": false, "text": "steals" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6699447/" ]
74,405,200
<p>I have this problem where I want to first select 8 elements from a mysql database ordering by id DESC. Then I want to select another group of results (8 items), this time order by date DESC but the results here I want to ensure that they are not already on the fisrt query the one for ordering by id. The data is in the same table just with different columns like id,name,date,.</p> <p>So far I have tried writing different queries to get the data but the data contains some similar items of which that is what I don't want. Here are the queries I have written;</p> <p>this returns 8 items sorted by id DESC</p> <pre><code>SELECT name FROM person order by id DESC LIMIT 8; </code></pre> <p>this returns 8 items also but sorted by date DESC</p> <pre><code>SELECT name FROM person order by date DESC LIMIT 8; </code></pre> <p>the returned data contain duplicate items!</p>
[ { "answer_id": 74405309, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 1, "selected": false, "text": "name" }, { "answer_id": 74405934, "author": "Aviran Ben David", "author_id": 5273331, "author_profile": "https://Stackoverflow.com/users/5273331", "pm_score": 2, "selected": true, "text": "SELECT name FROM person \nWHERE id NOT IN\n (SELECT id FROM person order by id DESC LIMIT 8) AS exc\nORDER BY date DESC LIMIT 8\n" }, { "answer_id": 74409323, "author": "GMB", "author_id": 10676716, "author_profile": "https://Stackoverflow.com/users/10676716", "pm_score": 0, "selected": false, "text": "select *\nfrom (\n select p.*,\n row_number() over(order by id desc) rn_id,\n row_number() over(order by date desc) rn_dt\n from person p\n) p\norder by case when rn_id <= 8 then rn_id else 9 end, rn_dt\nlimit 16\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17328148/" ]
74,405,256
<p>I want to count the occurence of each letter in a string and afterwards find out the letter with the highes occurrence and then return it as a char to the main method. Im just a beginner in coding so I would appreciate simple answers and solutions without adding anything from the library. Thank you for your time, I appreciate it</p> <p>What I have right now:</p> <p>to count the occurrence for each letter (doesnt work):</p> <pre><code>int count = 0; for (int i = 0; i &lt; s.Length; i++) { if (s[0] == s[i]) { count++; } } </code></pre> <p>to find out the highest number in the array:</p> <pre><code>int max = s[0]; for (int i = 0; i &lt; s.Length; i++) { if (s[i] &gt; max) { max = s[i]; } } </code></pre> <p>afterwards i want to return the value as a char and output the letter</p>
[ { "answer_id": 74405405, "author": "Dmitry Bychenko", "author_id": 2319407, "author_profile": "https://Stackoverflow.com/users/2319407", "pm_score": 0, "selected": false, "text": "using System.Linq;\n\nvar result = s\n .GroupBy(c => c)\n .MaxBy(g => g.Count())\n .Key;\n" }, { "answer_id": 74405407, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "count" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20479315/" ]
74,405,260
<p>Trying to rename a column in a Data frame. I used the same line to rename the column &quot;frames&quot;</p> <p>I want to rename a column from a &quot;0&quot; to &quot;Grad&quot;</p> <pre><code>result = pd.concat([table2, tableg3], axis=1) result.rename(columns = {&quot;0&quot; : &quot;Grad&quot;}, inplace = True) result </code></pre> <p>This outputs</p> <p><a href="https://i.stack.imgur.com/z5FSj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/z5FSj.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74405720, "author": "Bhargav", "author_id": 15358800, "author_profile": "https://Stackoverflow.com/users/15358800", "pm_score": 0, "selected": false, "text": "\"0\" - string\n0 - var\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20222128/" ]
74,405,265
<p>I am trying to recolor bars on a bar graph based on certain conditions of the values. (are they positive or negative? are they above or below the threshold?). Because I have do to <strong>a lot</strong> of these plots, I thought the easiest way to do that would be to create a column with the colors I want the bars to be, based on those conditions. This was easy enough with a few ifelse statements. But now, the problem is that ggplot won't pull those colors in the correct order. I have tried several different ways of doing this and can't seem to get it right.</p> <p>Here is an mock-up of dataframe filtered for just the first location we want to graph, with some example data. I have provided the full dput at the bottom so you can reproduce the full example yourself.</p> <pre><code> species location test_residuals species_order color 1 species2 location1 -2.1121481 1 dodgerblue1 2 species1 location1 -1.4315793 2 lightblue1 3 species8 location1 0.3727298 3 lightgoldenrod1 4 species3 location1 -5.2163387 4 dodgerblue1 5 species6 location1 3.5301076 5 goldenrod1 6 species4 location1 -0.7546595 6 lightblue1 7 species10 location1 -0.1857843 7 lightblue1 8 species12 location1 -0.5199749 8 lightblue1 9 species7 location1 -2.1884659 9 dodgerblue1 10 species13 location1 4.7223194 10 goldenrod1 11 species11 location1 0.3374291 11 lightgoldenrod1 12 species9 location1 0.6245307 12 lightgoldenrod1 13 species5 location1 -0.3676778 13 lightblue1 </code></pre> <p>when I try this</p> <pre><code>test.plot.1&lt;- data1 %&gt;% filter(location == &quot;location1&quot;) %&gt;% ggplot(aes( reorder(x = species, species_order), y= test_residuals, fill = species)) + geom_bar( stat= &quot;identity&quot;) + ggtitle(&quot;Location 1&quot;) + theme_pubclean( base_size = 14 )+ theme(plot.title = element_text(hjust = 0.5), legend.position = &quot;none&quot;) + xlab(&quot;&quot;) + ylab(&quot;Pearson Residuals&quot;) + scale_x_discrete(guide = guide_axis(angle = 45)) + geom_abline(intercept = 2, slope = 0, linetype = &quot;dotdash&quot;) + geom_abline(intercept = -2, slope = 0, linetype = &quot;dotdash&quot;) + scale_fill_manual(values = color) </code></pre> <p>I get the error &quot; Error in is_missing(values) : object 'color' not found&quot;</p> <p>If I instead specify the dataframe with:</p> <pre><code>scale_fill_manual(values = data1$color) </code></pre> <p>I don't get an error, and the color pallet is even correct, but the bars themselves are not the correct color!</p> <p><a href="https://i.stack.imgur.com/WNTA2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WNTA2.png" alt="miscolored graph" /></a></p> <p>I also get miscolored bars if I specify another vector in fill (for example color) produces this: <a href="https://i.stack.imgur.com/d3Ey9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/d3Ey9.png" alt="another miscolored graph " /></a></p> <p>I thought perhaps this was because when you have to specify the dataframe with &quot;data1$color&quot; the filter function was no longer applicable so I broke down by pipe and created a data frame that was pre-filtered to call for the ggplot. But even when this data frame is ordered with arrange the bars are still not the correct color.</p> <pre><code>test.plot.df2&lt;- data1 %&gt;% filter(location == &quot;location1&quot;) %&gt;% arrange(species_order) test.plot.2&lt;- test.plot.df2 %&gt;% ggplot(aes( reorder(x = species, species_order), y= test_residuals, fill = species)) + geom_bar( stat= &quot;identity&quot;) + ggtitle(&quot;Location 1&quot;) + theme_pubclean( base_size = 14 )+ theme(plot.title = element_text(hjust = 0.5), legend.position = &quot;none&quot;) + xlab(&quot;&quot;) + ylab(&quot;Pearson Residuals&quot;) + scale_x_discrete(guide = guide_axis(angle = 45)) + geom_abline(intercept = 2, slope = 0, linetype = &quot;dotdash&quot;) + geom_abline(intercept = -2, slope = 0, linetype = &quot;dotdash&quot;) + scale_fill_manual(values = test.plot.df2$color) test.plot.2 </code></pre> <p>Produces:</p> <p><a href="https://i.stack.imgur.com/IbJhC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IbJhC.png" alt="another, differently miscolored graph" /></a></p> <p>I must have a syntax error somewhere, but I cannot seem to find the logic behind the order of column colors produced, and am thus unable to work out how to correct said syntax error. Among (many many) things I have tried, I created a single vector to call for color</p> <pre><code>test.plot.df2&lt;- data1 %&gt;% filter(location == &quot;location1&quot;) %&gt;% arrange(species_order) test_color1&lt;- test.plot.df2$color test.plot.2&lt;- test.plot.df2 %&gt;% ggplot(aes( reorder(x = species, species_order), y= test_residuals, fill = species)) + geom_bar( stat= &quot;identity&quot;) + ggtitle(&quot;Location 1&quot;) + theme_pubclean( base_size = 14 )+ theme(plot.title = element_text(hjust = 0.5), legend.position = &quot;none&quot;) + xlab(&quot;&quot;) + ylab(&quot;Pearson Residuals&quot;) + scale_x_discrete(guide = guide_axis(angle = 45)) + geom_abline(intercept = 2, slope = 0, linetype = &quot;dotdash&quot;) + geom_abline(intercept = -2, slope = 0, linetype = &quot;dotdash&quot;) + scale_fill_manual(values = test_color1) test.plot.2 </code></pre> <p>Which produces the same graph as above. I have also tried creating a new column, with species order as a character, and calling that for fill. This once again produces a miscolored graph:</p> <pre><code>test.plot.df3&lt;- data1 %&gt;% filter(location == &quot;location1&quot;) %&gt;% arrange(species_order) %&gt;% mutate(species_order_character = as.character(species_order)) test.plot.3&lt;- test.plot.df3 %&gt;% ggplot(aes( reorder(x = species, species_order), y= test_residuals, fill = species_order_character)) + geom_bar( stat= &quot;identity&quot;) + ggtitle(&quot;Location 1&quot;) + theme_pubclean( base_size = 14 )+ theme(plot.title = element_text(hjust = 0.5), legend.position = &quot;none&quot;) + xlab(&quot;&quot;) + ylab(&quot;Pearson Residuals&quot;) + scale_x_discrete(guide = guide_axis(angle = 45)) + geom_abline(intercept = 2, slope = 0, linetype = &quot;dotdash&quot;) + geom_abline(intercept = -2, slope = 0, linetype = &quot;dotdash&quot;) + scale_fill_manual(values = test.plot.df3$color) test.plot.3 </code></pre> <p><a href="https://i.stack.imgur.com/Xz36G.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Xz36G.png" alt="another, differently miscolored graph" /></a></p> <p>I am at my wits end. I know for each graph I could manually enter the colors like so :</p> <pre><code>test.plot.4&lt;-data1 %&gt;% filter(location == &quot;location1&quot;) %&gt;% ggplot(aes( reorder(x = species, species_order), y= test_residuals, fill = color)) + geom_bar( stat= &quot;identity&quot;) + ggtitle(&quot;Location 1&quot;) + theme_pubclean( base_size = 14 )+ theme(plot.title = element_text(hjust = 0.5), legend.position = &quot;none&quot;) + xlab(&quot;&quot;) + ylab(&quot;Pearson Residuals&quot;) + scale_x_discrete(guide = guide_axis(angle = 45)) + geom_abline(intercept = 2, slope = 0, linetype = &quot;dotdash&quot;) + geom_abline(intercept = -2, slope = 0, linetype = &quot;dotdash&quot;) + scale_fill_manual(values = c( &quot;dodgerblue1&quot;,&quot;goldenrod1&quot;, &quot;lightblue1&quot;, &quot;lightgoldenrod1&quot;)) test.plot.4 </code></pre> <p><a href="https://i.stack.imgur.com/8XGnf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8XGnf.png" alt="a correctly colored graph" /></a></p> <p>This produces a correctly colored graph, but 1) I would like to have to avoid doing this by hand for each of the many times I have to reproduce this for different locations and different data sets, and 2) even here I can't figure out why the colors need to be ordered that way (ie.: &quot;goldenrod1&quot;, &quot;dodgerblue1&quot;, &quot;lightgoldenrod1&quot;, &quot;lightblue1&quot;) to correspond to the correct levels.</p> <p>Anyone have any insights on what is happening here, and how i might be able to correct my syntax so that I can just call the colors directly from the data frame?</p> <p>Thanks very much below is the full code to reproduce my data frame :</p> <pre><code> data1 &lt;- as.data.frame(structure(list(species = c( &quot;species1&quot;, &quot;species1&quot;, &quot;species1&quot;, &quot;species1&quot;, &quot;species1&quot;, &quot;species1&quot;, &quot;species2&quot;, &quot;species2&quot;, &quot;species2&quot;, &quot;species2&quot;, &quot;species2&quot;, &quot;species2&quot;, &quot;species3&quot;, &quot;species3&quot;, &quot;species3&quot;, &quot;species3&quot;, &quot;species3&quot;, &quot;species3&quot;, &quot;species4&quot;, &quot;species4&quot;, &quot;species4&quot;, &quot;species4&quot;, &quot;species4&quot;, &quot;species4&quot;, &quot;species5&quot;, &quot;species5&quot;, &quot;species5&quot;, &quot;species5&quot;, &quot;species5&quot;, &quot;species5&quot;, &quot;species6&quot;, &quot;species6&quot;, &quot;species6&quot;, &quot;species6&quot;, &quot;species6&quot;, &quot;species6&quot;, &quot;species7&quot;, &quot;species7&quot;, &quot;species7&quot;, &quot;species7&quot;, &quot;species7&quot;, &quot;species7&quot;, &quot;species8&quot;, &quot;species8&quot;, &quot;species8&quot;, &quot;species8&quot;, &quot;species8&quot;, &quot;species8&quot;, &quot;species9&quot;, &quot;species9&quot;, &quot;species9&quot;, &quot;species9&quot;, &quot;species9&quot;, &quot;species9&quot;, &quot;species10&quot;, &quot;species10&quot;, &quot;species10&quot;, &quot;species10&quot;, &quot;species10&quot;, &quot;species10&quot;, &quot;species11&quot;, &quot;species11&quot;, &quot;species11&quot;, &quot;species11&quot;, &quot;species11&quot;, &quot;species11&quot;, &quot;species12&quot;, &quot;species12&quot;, &quot;species12&quot;, &quot;species12&quot;, &quot;species12&quot;, &quot;species12&quot;, &quot;species13&quot;, &quot;species13&quot;, &quot;species13&quot;, &quot;species13&quot;, &quot;species13&quot;, &quot;species13&quot; ), location = c( &quot;location1&quot;, &quot;location2&quot;, &quot;location3&quot;, &quot;location4&quot;, &quot;location5&quot;, &quot;location6&quot;, &quot;location1&quot;, &quot;location2&quot;, &quot;location3&quot;, &quot;location4&quot;, &quot;location5&quot;, &quot;location6&quot;, &quot;location1&quot;, &quot;location2&quot;, &quot;location3&quot;, &quot;location4&quot;, &quot;location5&quot;, &quot;location6&quot;, &quot;location1&quot;, &quot;location2&quot;, &quot;location3&quot;, &quot;location4&quot;, &quot;location5&quot;, &quot;location6&quot;, &quot;location1&quot;, &quot;location2&quot;, &quot;location3&quot;, &quot;location4&quot;, &quot;location5&quot;, &quot;location6&quot;, &quot;location1&quot;, &quot;location2&quot;, &quot;location3&quot;, &quot;location4&quot;, &quot;location5&quot;, &quot;location6&quot;, &quot;location1&quot;, &quot;location2&quot;, &quot;location3&quot;, &quot;location4&quot;, &quot;location5&quot;, &quot;location6&quot;, &quot;location1&quot;, &quot;location2&quot;, &quot;location3&quot;, &quot;location4&quot;, &quot;location5&quot;, &quot;location6&quot;, &quot;location1&quot;, &quot;location2&quot;, &quot;location3&quot;, &quot;location4&quot;, &quot;location5&quot;, &quot;location6&quot;, &quot;location1&quot;, &quot;location2&quot;, &quot;location3&quot;, &quot;location4&quot;, &quot;location5&quot;, &quot;location6&quot;, &quot;location1&quot;, &quot;location2&quot;, &quot;location3&quot;, &quot;location4&quot;, &quot;location5&quot;, &quot;location6&quot;, &quot;location1&quot;, &quot;location2&quot;, &quot;location3&quot;, &quot;location4&quot;, &quot;location5&quot;, &quot;location6&quot;, &quot;location1&quot;, &quot;location2&quot;, &quot;location3&quot;, &quot;location4&quot;, &quot;location5&quot;, &quot;location6&quot; ), test_residuals = c( -1.43157930150306, -0.314316453493008, -0.695141335636191, -2.50279485833503, 15.9593244074832, -3.33654341630138, -2.11214812519871, -0.754659543030408, -2.3490433970076, -1.7153639945355, 19.798140868747, -3.92267054433899, -5.21633871800811, -2.78600907892934, 4.13596459214836, -2.35842831236716, -4.34026196885217, 8.57347502255589, -0.754659543030408, -2.11214812519871, -1.7153639945355, 9.81355206430024, -0.0987450246067016, -2.3490433970076, -0.367677794665814, -0.298606543279543, -0.261519516774949, -0.131369364295332, -0.472983769840402, 0.781602686808182, 3.53010760821268, -5.58101185979998, -5.5626379561955, 5.74088803484089, -12.2995673766017, 10.0851562256946, -2.18846593288851, -0.161746935435626, -1.76434843091121, -1.28043017699489, 9.27256034587805, -4.25159798465366, 0.372729803108757, -1.46533093179302, 0.229469416155288, 6.81036162101337, -2.23476643015094, 0.351490912112304, 0.624530722145124, 1.07723113193857, -0.262738728590663, -0.945967539680804, 3.3007673589212, -1.36569858688998, -0.18578433666679, -0.519974923799824, -0.422293423319278, 5.03783441267317, -0.965694731846794, -0.668900062090651, 0.337429125033733, -0.656846821476658, -0.250681398015413, -0.153477341599593, -1.30759758387474, 0.686219077483926, -0.519974923799824, -0.18578433666679, -0.668900062090651, -0.422293423319278, -0.36984444744839, 1.10535312007138, 4.72231943431065, 0.0138571578271046, 5.16352940820454, -4.08311797265573, -1.90430067033424, 0.0153780833066176 ), species_order = c( 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 4L, 4L, 4L, 4L, 4L, 4L, 6L, 6L, 6L, 6L, 6L, 6L, 13L, 13L, 13L, 13L, 13L, 13L, 5L, 5L, 5L, 5L, 5L, 5L, 9L, 9L, 9L, 9L, 9L, 9L, 3L, 3L, 3L, 3L, 3L, 3L, 12L, 12L, 12L, 12L, 12L, 12L, 7L, 7L, 7L, 7L, 7L, 7L, 11L, 11L, 11L, 11L, 11L, 11L, 8L, 8L, 8L, 8L, 8L, 8L, 10L, 10L, 10L, 10L, 10L, 10L ), color = c( &quot;lightblue1&quot;, &quot;lightblue1&quot;, &quot;lightblue1&quot;, &quot;dodgerblue1&quot;, &quot;goldenrod1&quot;, &quot;dodgerblue1&quot;, &quot;dodgerblue1&quot;, &quot;lightblue1&quot;, &quot;dodgerblue1&quot;, &quot;lightblue1&quot;, &quot;goldenrod1&quot;, &quot;dodgerblue1&quot;, &quot;dodgerblue1&quot;, &quot;dodgerblue1&quot;, &quot;goldenrod1&quot;, &quot;dodgerblue1&quot;, &quot;dodgerblue1&quot;, &quot;goldenrod1&quot;, &quot;lightblue1&quot;, &quot;dodgerblue1&quot;, &quot;lightblue1&quot;, &quot;goldenrod1&quot;, &quot;lightblue1&quot;, &quot;dodgerblue1&quot;, &quot;lightblue1&quot;, &quot;lightblue1&quot;, &quot;lightblue1&quot;, &quot;lightblue1&quot;, &quot;lightblue1&quot;, &quot;lightgoldenrod1&quot;, &quot;goldenrod1&quot;, &quot;dodgerblue1&quot;, &quot;dodgerblue1&quot;, &quot;goldenrod1&quot;, &quot;dodgerblue1&quot;, &quot;goldenrod1&quot;, &quot;dodgerblue1&quot;, &quot;lightblue1&quot;, &quot;lightblue1&quot;, &quot;lightblue1&quot;, &quot;goldenrod1&quot;, &quot;dodgerblue1&quot;, &quot;lightgoldenrod1&quot;, &quot;lightblue1&quot;, &quot;lightgoldenrod1&quot;, &quot;goldenrod1&quot;, &quot;dodgerblue1&quot;, &quot;lightgoldenrod1&quot;, &quot;lightgoldenrod1&quot;, &quot;lightgoldenrod1&quot;, &quot;lightblue1&quot;, &quot;lightblue1&quot;, &quot;goldenrod1&quot;, &quot;lightblue1&quot;, &quot;lightblue1&quot;, &quot;lightblue1&quot;, &quot;lightblue1&quot;, &quot;goldenrod1&quot;, &quot;lightblue1&quot;, &quot;lightblue1&quot;, &quot;lightgoldenrod1&quot;, &quot;lightblue1&quot;, &quot;lightblue1&quot;, &quot;lightblue1&quot;, &quot;lightblue1&quot;, &quot;lightgoldenrod1&quot;, &quot;lightblue1&quot;, &quot;lightblue1&quot;, &quot;lightblue1&quot;, &quot;lightblue1&quot;, &quot;lightblue1&quot;, &quot;lightgoldenrod1&quot;, &quot;goldenrod1&quot;, &quot;lightgoldenrod1&quot;, &quot;goldenrod1&quot;, &quot;dodgerblue1&quot;, &quot;lightblue1&quot;, &quot;lightgoldenrod1&quot; )), class = &quot;data.frame&quot;, row.names = c( NA, -78L ))) </code></pre>
[ { "answer_id": 74405565, "author": "Miff", "author_id": 3379675, "author_profile": "https://Stackoverflow.com/users/3379675", "pm_score": 3, "selected": true, "text": "scale_fill_identity" }, { "answer_id": 74405661, "author": "Arthur", "author_id": 10065473, "author_profile": "https://Stackoverflow.com/users/10065473", "pm_score": 0, "selected": false, "text": "fill = color" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18497691/" ]
74,405,269
<p>I have been tinkering with various Excel functions (MATCH/INDEX, VLOOKUP, SUMPRODUCT, AGGREGATE, etc.) to deliver the result I need, but without success. So I'm hoping someone can tell me what the best way to do this is.</p> <p>From my sample data below I need a formula that will return the row number accurately when I provide the exact code (exact match with column A) along with a date that falls between the dates listed in column B. I started with a formula that <em>does</em> work when both items match exactly -- i.e.,</p> <pre><code>=MATCH(1,((&quot;B&quot;=A:A)*(2005=B:B)),0) </code></pre> <p>will return row 6, which is correct. But I cannot figure out how to tweak that so it works when I search for Code=B and Year=2007. In this case I want it to return row 6 -- where Code=B and the year is the closest / next lower value. My closest attempt (which does not work) is:</p> <pre><code>=SUMPRODUCT(MATCH(1,(A:A=&quot;B&quot;)*(B:B&lt;=2007),0)) </code></pre> <p>Any help appreciated!</p> <p><a href="https://i.stack.imgur.com/Vreen.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Vreen.png" alt="Sample Data" /></a></p>
[ { "answer_id": 74405565, "author": "Miff", "author_id": 3379675, "author_profile": "https://Stackoverflow.com/users/3379675", "pm_score": 3, "selected": true, "text": "scale_fill_identity" }, { "answer_id": 74405661, "author": "Arthur", "author_id": 10065473, "author_profile": "https://Stackoverflow.com/users/10065473", "pm_score": 0, "selected": false, "text": "fill = color" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17745420/" ]
74,405,271
<p><strong>APPLICATION FAILED TO START</strong></p> <hr /> <p>Parameter 1 of constructor in Kodlama.io.Devs.business.concretes.ProgrammingLanguageManager required a bean of type 'org.modelmapper.ModelMapper' that could not be found.</p> <p>Consider defining a bean of type 'org.modelmapper.ModelMapper' in your configuration.</p> <hr /> <p><strong>ProgrammingLanguageManager</strong></p> <pre><code>@Service public class ProgrammingLanguageManager implements ProgrammingLanguageService { @Autowired private ProgrammingLanguageRepository programmingLanguageRepository; private ModelMapper modelMapper; @Autowired public ProgrammingLanguageManager(ProgrammingLanguageRepository programmingLanguageRepository, ModelMapper modelMapper) { this.programmingLanguageRepository = programmingLanguageRepository; this.modelMapper = modelMapper; } // * * * CRUD OPERATIONS * * * @Override public CreateProgrammingLanguageResponse add(CreateProgrammingLanguageRequest createProgrammingLanguageRequest) throws Exception { nameCannotBeSame(createProgrammingLanguageRequest.getName()); ProgrammingLanguage programmingLanguage = modelMapper.map(createProgrammingLanguageRequest, ProgrammingLanguage.class); ProgrammingLanguage saveProgrammingLanguageResult = programmingLanguageRepository.save(programmingLanguage); CreateProgrammingLanguageResponse createProgrammingLanguageResponse = modelMapper .map(saveProgrammingLanguageResult, CreateProgrammingLanguageResponse.class); return createProgrammingLanguageResponse; } @Override public UpdateProgrammingLanguageResponse update(UpdateProgrammingLanguageRequest updateProgrammingLanguageRequest) throws Exception { nameCannotBeSame(updateProgrammingLanguageRequest.getName()); ProgrammingLanguage programmingLanguage = modelMapper.map(updateProgrammingLanguageRequest, ProgrammingLanguage.class); ProgrammingLanguage saveProgrammingLanguageResult = programmingLanguageRepository.save(programmingLanguage); UpdateProgrammingLanguageResponse updateProgrammingLanguageResponse = modelMapper .map(saveProgrammingLanguageResult, UpdateProgrammingLanguageResponse.class); return updateProgrammingLanguageResponse; } @Override public DeleteProgrammingLanguageResponse delete(DeleteProgrammingLanguageRequest deleteProgrammingLanguageRequest) { ProgrammingLanguage getReferenceByIdProgrammingLanguageResult = programmingLanguageRepository .getReferenceById(deleteProgrammingLanguageRequest.getId()); programmingLanguageRepository.delete(getReferenceByIdProgrammingLanguageResult); DeleteProgrammingLanguageResponse deleteProgrammingLanguageResponse = modelMapper .map(getReferenceByIdProgrammingLanguageResult, DeleteProgrammingLanguageResponse.class); return deleteProgrammingLanguageResponse; } // * * * GET METHODS * * * @Override public List&lt;GetAllProgrammingLanguagesResponse&gt; getAll() { List&lt;ProgrammingLanguage&gt; findAllProgrammingLanguageResult = programmingLanguageRepository.findAll(); return modelMapper.map(findAllProgrammingLanguageResult, new TypeToken&lt;List&lt;GetAllProgrammingLanguagesResponse&gt;&gt;() { }.getType()); } @Override public GetByIdProgrammingLanguageResponse getById( GetByIdProgrammingLanguageRequest getByIdProgrammingLanguageRequest) { ProgrammingLanguage getReferenceByIdProgrammingLanguageResult = programmingLanguageRepository .getReferenceById(getByIdProgrammingLanguageRequest.getId()); GetByIdProgrammingLanguageResponse getByIdProgrammingLanguageResponse = modelMapper .map(getReferenceByIdProgrammingLanguageResult, GetByIdProgrammingLanguageResponse.class); return getByIdProgrammingLanguageResponse; } public GetByNameProgrammingLanguageResponse getByName( GetByNameProgrammingLanguageRequest getByNameProgrammingLanguageRequest) { ProgrammingLanguage getReferenceByNameProgrammingLanguageResult = new ProgrammingLanguage(); getReferenceByNameProgrammingLanguageResult = programmingLanguageRepository .getByName(getByNameProgrammingLanguageRequest.toString()); GetByNameProgrammingLanguageResponse getByNameProgrammingLanguageResponse = modelMapper .map(getReferenceByNameProgrammingLanguageResult, GetByNameProgrammingLanguageResponse.class); return getByNameProgrammingLanguageResponse; } // * * * BUSINESS RULES * * * private void nameCannotBeSame(String name) throws Exception { ProgrammingLanguage programmingLanguage = programmingLanguageRepository.getByName(name); var result = programmingLanguage; if (result != null) { throw new Exception(Messages.NAME_ALREADY_EXISTS); } } } </code></pre> <p>Im missing something but i don't know what</p>
[ { "answer_id": 74405565, "author": "Miff", "author_id": 3379675, "author_profile": "https://Stackoverflow.com/users/3379675", "pm_score": 3, "selected": true, "text": "scale_fill_identity" }, { "answer_id": 74405661, "author": "Arthur", "author_id": 10065473, "author_profile": "https://Stackoverflow.com/users/10065473", "pm_score": 0, "selected": false, "text": "fill = color" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20479398/" ]
74,405,275
<p>Using playwright with typescript I want to select the following html element:</p> <pre><code>&lt;div class=&quot;ivu-select-dropdown&quot; style=&quot;position: absolute; min-width: 180px; will-change: top, left; transform-origin: center top; top: 135px; left: 339px;&quot; x-placement=&quot;bottom-start&quot;&gt; &lt;ul class=&quot;ivu-select-not-found&quot; style=&quot;display: none;&quot;&gt; &lt;li&gt;No matching data&lt;/li&gt; &lt;/ul&gt; &lt;ul class=&quot;ivu-select-dropdown-list&quot;&gt; &lt;li class=&quot;ivu-select-item&quot;&gt; &lt;div class=&quot;custom-select-item-for-preview&quot;&gt;5Cells&lt;/div&gt; &lt;/li&gt; ... and other li elements </code></pre> <p>I looked up the documentation but still have no clue how to use e.g. the class &quot;ivu-select-dropdown&quot; to select that element.</p> <p>The html structure seems to change, it also could be the following structure before clicking on anything, or I missed to show important elements:</p> <pre><code>&lt;div class=&quot;custom-autocomplete-targets ivu-select ivu-select-single ivu-select-small ivu-form-item-error&quot;&gt; &lt;div tabindex=&quot;-1&quot; class=&quot;ivu-select-selection&quot;&gt;&lt;input type=&quot;hidden&quot;&gt; &lt;div class=&quot;&quot;&gt; &lt;!----&gt; &lt;!----&gt; &lt;span class=&quot;&quot; style=&quot;display: none;&quot;&gt;&lt;/span&gt; &lt;input type=&quot;text&quot; placeholder=&quot;Select&quot; autocomplete=&quot;off&quot; spellcheck=&quot;false&quot; class=&quot;ivu-select-input&quot;&gt; &lt;!----&gt; &lt;i class=&quot;ivu-icon ivu-icon-ios-arrow-down ivu-select-arrow&quot;&gt;&lt;/i&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;ivu-select-dropdown&quot; style=&quot;display: none; position: absolute; min-width: 180px; will-change: top, left; transform-origin: center top; top: 135px; left: 339px;&quot; x-placement=&quot;bottom-start&quot;&gt; &lt;ul class=&quot;ivu-select-not-found&quot; style=&quot;display: none;&quot;&gt; &lt;li&gt;No matching data&lt;/li&gt; &lt;/ul&gt; &lt;ul class=&quot;ivu-select-dropdown-list&quot;&gt; &lt;li class=&quot;ivu-select-item&quot;&gt; &lt;div class=&quot;custom-select-item-for-preview&quot;&gt;5Cells&lt;/div&gt; &lt;/li&gt; ... and other li elements </code></pre>
[ { "answer_id": 74405565, "author": "Miff", "author_id": 3379675, "author_profile": "https://Stackoverflow.com/users/3379675", "pm_score": 3, "selected": true, "text": "scale_fill_identity" }, { "answer_id": 74405661, "author": "Arthur", "author_id": 10065473, "author_profile": "https://Stackoverflow.com/users/10065473", "pm_score": 0, "selected": false, "text": "fill = color" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1581090/" ]
74,405,284
<p>I am using the yeoman generator to generate the 'Office Add-in Task Pane project supporting single sign-on (localhost)' example. When I run the example in Word the user name and email are pasted into the document as expected. But when I switch account by using the button in the upper-right corner of Word <a href="https://i.stack.imgur.com/8ZjWH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8ZjWH.png" alt="switch account button" /></a> the addin is still using the first selected account.</p> <p>Is there a way to make the addin use the newly selected account without the need to close and open the addin?</p>
[ { "answer_id": 74409306, "author": "Eugene Astafiev", "author_id": 1603351, "author_profile": "https://Stackoverflow.com/users/1603351", "pm_score": 1, "selected": true, "text": "getAccessToken" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9905988/" ]
74,405,291
<p>In a data frame similar to the one below how can I create the Concatenation column based on the date of each activity?</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">Activity A</th> <th style="text-align: center;">Activity B</th> <th style="text-align: right;">Activity C</th> <th style="text-align: right;">Concatenation</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">1/1/2022</td> <td style="text-align: center;">1/15/2022</td> <td style="text-align: right;">2/3/2022</td> <td style="text-align: right;">Activity A --&gt; Activity B --&gt; Activity C</td> </tr> <tr> <td style="text-align: left;">1/15/2022</td> <td style="text-align: center;">2/3/2022</td> <td style="text-align: right;">1/1/2022</td> <td style="text-align: right;">Activity C --&gt; Activity A --&gt; Activity B</td> </tr> </tbody> </table> </div>
[ { "answer_id": 74405598, "author": "Joseph Konka", "author_id": 12444125, "author_profile": "https://Stackoverflow.com/users/12444125", "pm_score": 0, "selected": false, "text": " df = pd.read_csv('sample.csv')\n df\n Activity A Activity B Activity C\n 0 1/1/2022 1/15/2022 2/3/2022\n 1 1/15/2022 2/3/2022 1/1/2022\n\n df['Concatenation'] = df[['Activity A', 'Activity B', 'Activity C']].apply(lambda x: ' -> '.join(list(x)), axis=1)\n df\n\n Activity A Activity B Activity C Concatenation\n 0 1/1/2022 1/15/2022 2/3/2022 1/1/2022 -> 1/15/2022 -> 2/3/2022\n 1 1/15/2022 2/3/2022 1/1/2022 1/15/2022 -> 2/3/2022 -> 1/1/2022\n" }, { "answer_id": 74407488, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": true, "text": "argsort" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10230971/" ]
74,405,306
<p>I have a MUI <code>DateTimePicker</code> in my react app, and I would like to disable the text input so that it is only possible to change the date/time by clicking on the icon and launching the overlays to edit them.</p> <p>I have tried a few things, such as adding <code>disabled={true}</code> to the <code>renderInput</code>, like this:</p> <pre><code>renderInput={(params: any) =&gt; &lt;TextField {...params} disabled={true} InputProps={{...params.InputProps, disableUnderline: true}} variant=&quot;standard&quot;/&gt;} </code></pre> <p>Doesn't quite work as expected though. I have tried a lot of other things too, but not sure how that detail would support my question.</p> <p>Suggestions?</p>
[ { "answer_id": 74405802, "author": "Ricky Clark III", "author_id": 16505781, "author_profile": "https://Stackoverflow.com/users/16505781", "pm_score": 0, "selected": false, "text": "<DateTimePicker\n label=\"Date&Time picker\"\n value={value}\n onChange={handleChange}\n renderInput={(params) => <TextField {...params} disabled />}\n/>\n" }, { "answer_id": 74405875, "author": "RubenSmn", "author_id": 20088324, "author_profile": "https://Stackoverflow.com/users/20088324", "pm_score": 1, "selected": false, "text": "readOnly" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/343159/" ]
74,405,314
<p>I've got a problem with centering in another tag . I have no problem with horizontal align in a flexox or in a old fashion way but vertical is still a problem for me.</p> <pre><code>div { display: inline-block; background-color: green; width: 130px; height: 45px; margin-top: 20px; text-align: center; } h2 { font-size: 20px; font-weight: 100; display: flex; justify-content: center; align-content: center; </code></pre>
[ { "answer_id": 74405802, "author": "Ricky Clark III", "author_id": 16505781, "author_profile": "https://Stackoverflow.com/users/16505781", "pm_score": 0, "selected": false, "text": "<DateTimePicker\n label=\"Date&Time picker\"\n value={value}\n onChange={handleChange}\n renderInput={(params) => <TextField {...params} disabled />}\n/>\n" }, { "answer_id": 74405875, "author": "RubenSmn", "author_id": 20088324, "author_profile": "https://Stackoverflow.com/users/20088324", "pm_score": 1, "selected": false, "text": "readOnly" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20479364/" ]
74,405,367
<pre><code> cy.get(':nth-child(1) &gt; .form-control').type(userName) cy.get(':nth-child(2) &gt; .form-control').type(email) cy.get(':nth-child(3) &gt; .form-control').type(password) </code></pre> <p>how to get userName, email, password data?</p> <p>in cypress where:</p> <p>userName</p> <p>email</p> <p>password</p> <p>are generated randomly</p> <p>what am i talking about</p> <p>the code generate random values of : login password and email by using faker and type them on register page fields and register a new user and logged out after</p> <p>i need to get that random values which was used in previous step and type them into login fields on log in page (to log in like registered user)</p>
[ { "answer_id": 74405802, "author": "Ricky Clark III", "author_id": 16505781, "author_profile": "https://Stackoverflow.com/users/16505781", "pm_score": 0, "selected": false, "text": "<DateTimePicker\n label=\"Date&Time picker\"\n value={value}\n onChange={handleChange}\n renderInput={(params) => <TextField {...params} disabled />}\n/>\n" }, { "answer_id": 74405875, "author": "RubenSmn", "author_id": 20088324, "author_profile": "https://Stackoverflow.com/users/20088324", "pm_score": 1, "selected": false, "text": "readOnly" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405367", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20479451/" ]
74,405,380
<p>this function maps letters onto another letter. Could someone explain to me what does the <code>!! 0</code> mean here in the function?</p> <pre><code>findGuess letter guessList | length guessList == 0 = (letter, letter) | letter == snd (guessList !! 0) || letter == fst (guessList !! 0) = guessList !! 0 | otherwise = findGuess letter (tail guessList) </code></pre>
[ { "answer_id": 74405475, "author": "chepner", "author_id": 1126841, "author_profile": "https://Stackoverflow.com/users/1126841", "pm_score": 3, "selected": false, "text": "(!!)" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20425217/" ]
74,405,386
<p>I'm trying to display a different background color in wpf based on datatrigger and a converter.</p> <pre><code>&lt;dxg:TableView.RowStyle&gt; &lt;Style TargetType=&quot;{x:Type dxg:RowControl}&quot;&gt; &lt;Setter Property=&quot;Height&quot; Value=&quot;{StaticResource examRowHeight}&quot; /&gt; &lt;Style.Triggers&gt; &lt;DataTrigger Binding=&quot;{Binding Row.IsStatusRead, UpdateSourceTrigger=PropertyChanged}&quot; Value=&quot;true&quot;&gt; &lt;Setter Property=&quot;Background&quot; Value=&quot;Khaki&quot; /&gt; &lt;/DataTrigger&gt; &lt;DataTrigger Binding=&quot;{Binding Row.IsRecordingFileOpened, UpdateSourceTrigger=PropertyChanged}&quot; Value=&quot;true&quot;&gt; &lt;Setter Property=&quot;Background&quot;&gt; &lt;Setter.Value&gt; &lt;Binding Path=&quot;Row.ExamBlockType&quot;&gt; &lt;Binding.Converter&gt; &lt;valueConverters:ExamBlockTypeToBackgroundBrush /&gt; &lt;/Binding.Converter&gt; &lt;/Binding&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;/DataTrigger&gt; &lt;/Style.Triggers&gt; &lt;/Style&gt; &lt;/dxg:TableView.RowStyle&gt; </code></pre> <p>Is this the right way? Converter seems not be fired.</p> <p>Is there an alternative way to achieve the same behaviour?</p> <p>Thanks in advance</p> <p>Ric</p>
[ { "answer_id": 74405475, "author": "chepner", "author_id": 1126841, "author_profile": "https://Stackoverflow.com/users/1126841", "pm_score": 3, "selected": false, "text": "(!!)" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8757789/" ]
74,405,388
<p>I have a DataFrame that contains objects and items belonging to the objects. Items have additional data (not shown) and multiple items can belong to one object.</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame( { &quot;object_id&quot;: [1, 1, 1, 1, 1, 2, 2, 2], &quot;item_id&quot;: [1, 2, 4, 4, 5, 1, 1, 2], &quot;item_count&quot;: [6, 6, 6, 6, 6, 3, 3, 3], } ) </code></pre> <p>I now want to group by the <code>object_id</code> and extract information from the associated items. While this works, it does not add items that are not already in the DataFrame (i.e. &quot;0&quot; values).</p> <pre class="lang-py prettyprint-override"><code>df_group = df.groupby([&quot;object_id&quot;, &quot;item_id&quot;], as_index=False).size() &gt;&gt;&gt; df_group object_id item_id size 0 1 1 1 1 1 2 1 # e.g. item 3 missing 2 1 4 2 3 1 5 1 4 2 1 2 5 2 2 1 </code></pre> <p>I now wanted to find out if there is a way to expand the groupby given the <code>item_counts</code>. My current naive approach is to create an dataframe list and merge the groupby afterwards:</p> <pre class="lang-py prettyprint-override"><code>all_items = [ dict(object_id=entity, item_id=obj + 1) for entity in df[&quot;object_id&quot;].unique() for obj in range(df.loc[df[&quot;object_id&quot;] == entity, &quot;item_count&quot;].iloc[0]) ] df_full = pd.DataFrame(all_items).merge(df_group, how=&quot;left&quot;).fillna(0).astype({&quot;size&quot;: &quot;int&quot;}) &gt;&gt;&gt; df_full object_id item_id size 0 1 1 1 1 1 2 1 2 1 3 0 3 1 4 2 4 1 5 1 5 1 6 0 6 2 1 2 7 2 2 1 8 2 3 0 </code></pre>
[ { "answer_id": 74405522, "author": "Vahid the Great", "author_id": 11411596, "author_profile": "https://Stackoverflow.com/users/11411596", "pm_score": -1, "selected": false, "text": "df = (df.set_index('item_id')\n .groupby('object_id')['item_count']\n .apply(lambda x: x.reindex(range(x.index.min(), x.index.max() + 1), fill_value=0))\n .reset_index()\n )\n" }, { "answer_id": 74405824, "author": "Naveed", "author_id": 3494754, "author_profile": "https://Stackoverflow.com/users/3494754", "pm_score": 2, "selected": true, "text": "# summarize the duplicate item ids and create a new df\n# its needed at this stage to allow us to use reindex later\ndf2=df.groupby(['object_id','item_id','item_count'], as_index=False).size()\n\n# groupby the object_id then applying lambda on the group, \n# set item id as an index, which is now unique\n# reindex the group result with item ids ranging from min of item id\n# to the count under item_count column + 1\n\ndf3=(df2.groupby('object_id', as_index=False)\n .apply(lambda x: x.set_index(['item_id']).reindex( range(x['item_id'].min(), x['item_count'].max() + 1) ))\n)\n\n# null values in size, make them o\ndf3['size'].fillna(0, inplace=True)\n\n# ffill null values for remaining columns\ndf3.ffill(inplace=True)\n\n# drop unwanted column after reindex\ndf3=df3.reset_index().drop(columns='level_0')\n\n# NaN make the column values as float, so turn them back to int\ndf3=df3[['object_id','item_id','item_count', 'size']].astype(int )\ndf3\n\n" }, { "answer_id": 74405864, "author": "Matteo Zanoni", "author_id": 13384774, "author_profile": "https://Stackoverflow.com/users/13384774", "pm_score": 1, "selected": false, "text": "df_group" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11486611/" ]
74,405,397
<p>Good Evening,</p> <p>I fitted a four parameter logistic curve using R nls function with the following equation:</p> <p>y = alpha + lambda/(1+exp(-beta(x-mu))</p> <p>I would like to determine the maximum slope of this curve and for this I would like to compute the derivative of the function. Do you know how I can find the derivative of this function and use it to determine the maximum slope or the maximum derivative value?</p> <p>Thank you in advance,</p> <p>Rohan</p> <p>I find the regular sigmoid equation y = 1/1+e-x and its derivative but not with the parameters. I am expecting some help with the derivative of my equation and a piece of script that can help me to find the maximum value.</p>
[ { "answer_id": 74406955, "author": "G. Grothendieck", "author_id": 516548, "author_profile": "https://Stackoverflow.com/users/516548", "pm_score": 1, "selected": false, "text": "fder" }, { "answer_id": 74407261, "author": "Ben Bolker", "author_id": 190277, "author_profile": "https://Stackoverflow.com/users/190277", "pm_score": 0, "selected": false, "text": "lambda*beta/4" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20479448/" ]
74,405,403
<p>I'm hosting my bot online and sometimes messages take time to edit their own View components which is fine. The problem is when i modify a view by calling</p> <pre><code>await message.edit(view=...) </code></pre> <p>, the new button/select components are displayed instantly but their callbacks are not operational because the message editing is taking some time to complete. Thus, unknown interaction error tends to occur when clicking on the button a little too early, the callbacks are not being called, and I need to wait to re-click.</p> <p>My question is : Is it possible to wait for a message.edit() to fully complete before showing the buttons, or is there another way to solve this issue?</p> <p>Code sample :</p> <pre class="lang-py prettyprint-override"><code>async def throw_dice(self,ctx): try : superself = self async def action(superself): ... if isinstance(self.current,PlayerDiscord) : class myButton(ui.Button): def __init__(self,label,style,row=None): super().__init__(label=label,style=style,row=row) async def callback(self,interaction): await interaction.response.defer() nonlocal superself if interaction.user.id==superself.current.member.id: self.view.stop() await superself.msg_play.edit(view=None) await action(superself) self.view = FRPGame.myView(ctx,self) #Create new view self.view.add_item(myButton(&quot;\U0001F3B2&quot;,style=discord.ButtonStyle.primary)) #self.msg_play stores the message await self.msg_play.edit(content=self.content,view=self.view) #&lt;-- problem is this single line else : ... except BaseException : traceback.print_exc() </code></pre>
[ { "answer_id": 74406955, "author": "G. Grothendieck", "author_id": 516548, "author_profile": "https://Stackoverflow.com/users/516548", "pm_score": 1, "selected": false, "text": "fder" }, { "answer_id": 74407261, "author": "Ben Bolker", "author_id": 190277, "author_profile": "https://Stackoverflow.com/users/190277", "pm_score": 0, "selected": false, "text": "lambda*beta/4" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19016760/" ]
74,405,426
<p>Using just HTML is not possible. I need to download using a callback function, but it's not working.</p> <p>I need to encapsulate the button with an element like:</p> <pre><code>&lt;a href=&quot;https://path.to.your.file.com&quot; target=&quot;_blank&quot; rel=&quot;noreferrer&quot;&gt; &lt;button&gt;Click&lt;/button&gt; &lt;/a&gt; </code></pre> <p>I need to create a callback function:</p> <pre><code> const downloadImage = ( dataURL: string, fileName: string ) =&gt; { const link = document.createElement('a') link.download = fileName link.href = dataURL link.click() } </code></pre> <p>Return:</p> <pre><code> &lt;button className=&quot;btn btn-primary btn-sm&quot; onClick={() =&gt; downloadImage('https://estica-public.s3.amazonaws.com/21965/conversions/8b3ujv9ze8d0uho287bq182zgpvv-full.png?X-Amz-Content-Sha256=UNSIGNED-PAYLOAD&amp;X-Amz-Algorithm=AWS4-HMAC-SHA256&amp;X-Amz-Credential=AKIAY2EWNM3MQCGRS66O%2F20221111%2Fus-east-1%2Fs3%2Faws4_request&amp;X-Amz-Date=20221111T135108Z&amp;X-Amz-SignedHeaders=host&amp;X-Amz-Expires=3600&amp;X-Amz-Signature=9e11f9af9fc1ba81f3100a2da6d29a6fd71e3b5a7a9e5b7682dc5171530b251a', 'image.png')} &gt;Baixar arte gráfica&lt;/button&gt; </code></pre> <p>I tried html method, using labs, but I really need to do this code works, someone please could help me? I already tried every method here on Stack Overflow, so I put the method I'm using to force it to download and the link I must embed in my project.</p>
[ { "answer_id": 74406195, "author": "Alexandr Petrov", "author_id": 19905763, "author_profile": "https://Stackoverflow.com/users/19905763", "pm_score": 2, "selected": true, "text": "function downloadImage(url, name = 'newImage') {\n return fetch(url)\n .then(resp => resp.blob())\n .then(blob => {\n const url = window.URL.createObjectURL(blob);\n const a = document.createElement('a');\n a.style.display = 'none';\n a.href = url;\n a.download = name;\n document.body.appendChild(a);\n a.click();\n document.body.removeChild(a);\n\n return Promise.resolve();\n })\n}\n\nfunction download() {\n downloadImage('https://picsum.photos/536/354', 'newFileName')\n .then(() => console.log('ok'))\n .catch(() => console.log('error'))\n}" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405426", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19115954/" ]
74,405,427
<p>I am trying to do semi forecasting with BigQuery. I have minutely data of users, and a minute multiplier (pre calculated based on past events) that should predict the next minute's value. I created a dataset with all future minutes for the relevant timeframe, future minute will have null value, it looks like that:</p> <p><a href="https://i.stack.imgur.com/4zr7q.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4zr7q.png" alt="enter image description here" /></a></p> <p>Now trying to calculate all future values based on the multiplier. I can't figure out how to apply this to more than 1 row, meaning; the first null row will be the prev value times the multiplier. But now what? How can I keep calculating it based on future values? The output should look like that:</p> <p><a href="https://i.stack.imgur.com/5ny1E.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5ny1E.png" alt="enter image description here" /></a></p> <p>So 100 is the only real value - then 100 * 1.1 will be 120, and then 120 * 1.2 will be 132, so on and so forth.</p> <p>Appreciate the help guys, thanks!</p>
[ { "answer_id": 74406195, "author": "Alexandr Petrov", "author_id": 19905763, "author_profile": "https://Stackoverflow.com/users/19905763", "pm_score": 2, "selected": true, "text": "function downloadImage(url, name = 'newImage') {\n return fetch(url)\n .then(resp => resp.blob())\n .then(blob => {\n const url = window.URL.createObjectURL(blob);\n const a = document.createElement('a');\n a.style.display = 'none';\n a.href = url;\n a.download = name;\n document.body.appendChild(a);\n a.click();\n document.body.removeChild(a);\n\n return Promise.resolve();\n })\n}\n\nfunction download() {\n downloadImage('https://picsum.photos/536/354', 'newFileName')\n .then(() => console.log('ok'))\n .catch(() => console.log('error'))\n}" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11504953/" ]
74,405,429
<p>I'm trying to extract the country codes and move them into a new column.</p> <p><strong>Example data</strong></p> <pre><code>data &lt;- data.frame(phone = c(&quot;+1 800 000 000&quot;, &quot;+257000000000&quot;, &quot;+91-00 000 00&quot;, &quot;200000 000&quot;)) </code></pre> <p>I only have a start so far. For instance, I can extract the <code>+</code> sign, but I'm trying to find how to detect <code>+1 +257 +91</code>, etc..</p> <pre><code>data |&gt; mutate(country_code = str_extract(phone, &quot;[:symbol:]&quot;)) </code></pre> <pre><code>phone country_code +1 800 000 000 + +257000000000 + +91-00 000 00 + 200000 000 NA </code></pre> <p><strong>What I'm trying to achieve:</strong></p> <pre><code>phone country_code +1 800 000 000 +1 +257000000000 +257 +91-00 000 00 +91 200000 000 NA </code></pre> <p>I'm wondering if I can match possible country codes based on another vector where I specify the different variations, like this: <code>codes &lt;- c(1, 257, 91)</code> or like this <code>codes &lt;- c(&quot;+1&quot;, &quot;+257&quot;, &quot;+91&quot;)</code>.</p>
[ { "answer_id": 74406195, "author": "Alexandr Petrov", "author_id": 19905763, "author_profile": "https://Stackoverflow.com/users/19905763", "pm_score": 2, "selected": true, "text": "function downloadImage(url, name = 'newImage') {\n return fetch(url)\n .then(resp => resp.blob())\n .then(blob => {\n const url = window.URL.createObjectURL(blob);\n const a = document.createElement('a');\n a.style.display = 'none';\n a.href = url;\n a.download = name;\n document.body.appendChild(a);\n a.click();\n document.body.removeChild(a);\n\n return Promise.resolve();\n })\n}\n\nfunction download() {\n downloadImage('https://picsum.photos/536/354', 'newFileName')\n .then(() => console.log('ok'))\n .catch(() => console.log('error'))\n}" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13874036/" ]
74,405,441
<p>I think that at this point I'm able to tell you the author name and accurate posting date for this question elsewhere online if you give me a piece of the error description related to Laravel's Page Expired 419 on mobile phones. So yeah, that's what this question is about too. How do I solve it?</p> <ul> <li>I found users are experiencing friction with the login page of my app while using mobile phones. Oftentimes it gives an error 419, page expired. Needless to say the csrf token is there. It also works like a charm on desktop.</li> <li>I stumbled upon an older bug in the <a href="https://github.com/Fyrd/caniuse/issues/4813" rel="nofollow noreferrer">SameSite lax implementation</a>, and also found good reasons not to alter this (e.g. <code>none</code> has a default fallback to <code>strict</code>, and <code>lax</code> would be the best option from a security perspective). So I kept it that way, also thinking as the bug was admitted years ago there must be something else going on.</li> <li>I've been clearing cache, routes, and config upon each change I made. This may help, but hasn't solved the problem yet.</li> <li>I first used the <code>file</code> session driver, and checked permissions - those were in order but still the 419 happens.</li> <li>I've switched from <code>file</code> session driver to the <code>database</code> driver, ran the migration and seeing sessions populating the database. However, the issue still persists.</li> </ul> <p>I feel it's something on the client side, or something in the config that gets activated when submitting the request, but I don't know where to look for anymore. If you've faced this issue before your insights are much appreciated. I'm using <code>Laravel 8.75</code> for this project. I'll happily provide a bounty when possible to get this issue solved. Thanks.</p>
[ { "answer_id": 74442466, "author": "Vlad", "author_id": 20382571, "author_profile": "https://Stackoverflow.com/users/20382571", "pm_score": 2, "selected": false, "text": "handle" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/213633/" ]
74,405,446
<p>My code has to call a few web services. To speed that up, I want to do that in parallel. However, the results of those services must be executed <em>before</em> <code>Promise.all()</code> resolves. Here's my current code:</p> <pre class="lang-js prettyprint-override"><code>const awaitors = []; if (!targetLocation) { awaitors.push((async function () { targetLocation = await getStorageLocation(storageID); })()); } if (!carrierToMove) { awaitors.push(/* Another similar call that sets carrierToMove */); } await Promise.all(awaitors); pushCarrierIntoStorage(carrierToMove, targetLocation); </code></pre> <p>As you can see, I'm using a self-executing javascript function there. That doesn't really contribute to the readability of my code. Is there a better way to implement that without losing the ability to execute both calls in parallel?</p>
[ { "answer_id": 74405499, "author": "Quentin", "author_id": 19068, "author_profile": "https://Stackoverflow.com/users/19068", "pm_score": 0, "selected": false, "text": "const promiseTargetLocation = getStorageLocation(storageID);\nconst promiseCarrierToMove = anotherSimilarCall();\nconst [carrierToMove, targetLocation] = await Promise.all([promiseCarrierToMove, promiseTargetLocation];\npushCarrierIntoStorage(carrierToMove, targetLocation);\n" }, { "answer_id": 74406650, "author": "vitaly-t", "author_id": 1102051, "author_profile": "https://Stackoverflow.com/users/1102051", "pm_score": -1, "selected": false, "text": "const awaitors = [];\n\nif (!targetLocation) {\n awaitors.push(getStorageLocation(storageID).then(targetLocation => {\n // process targetLocation \n }));\n}\n\nif (!carrierToMove) {\n awaitors.push(/* do the same as above */);\n}\n\n// by the time this resolves, individual\n// requests will be processed:\nawait Promise.all(awaitors); \n\npushCarrierIntoStorage(carrierToMove, targetLocation);\n" }, { "answer_id": 74413105, "author": "trincot", "author_id": 5459839, "author_profile": "https://Stackoverflow.com/users/5459839", "pm_score": 0, "selected": false, "text": "const carrierAndStorage = await Promise.all([\n carrierToMove ?? getCarrier(someID),\n targetLocation ?? getStorageLocation(storageID)\n]);\n\npushCarrierIntoStorage(...carrierAndStorage);\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405446", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10406502/" ]
74,405,450
<p>Consider I have near 0% experience with typescript and now a little Hilla experience (which is going great!) please be gentle with me and provide a simple Tree Grid example.</p> <p>I was hoping to do something easy like:</p> <pre><code>export class GroceryView extends View { display a lovely tree view of master detail data. } </code></pre> <p>But the examples on vaadin and hilla web sites started going into which was confusing...</p> <pre><code>export class Example extends LitElement {} </code></pre> <p>I have the grid working ok.</p> <ul> <li>Looked at the various document sources and github example projects.</li> <li>I have the basic grid working ok via the View implementation.</li> </ul>
[ { "answer_id": 74407968, "author": "Jouni", "author_id": 396573, "author_profile": "https://Stackoverflow.com/users/396573", "pm_score": 1, "selected": false, "text": "View" }, { "answer_id": 74450177, "author": "Melting Turret", "author_id": 20479500, "author_profile": "https://Stackoverflow.com/users/20479500", "pm_score": 0, "selected": false, "text": "getCareersById()" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20479500/" ]
74,405,473
<p>i am trying to create a folder in the downloads folder using uwp, and in this folder i want to create pdf files. this is what is supposed to happen: the first time the button is clicked, the folder is created and so is a pdf file corresponding to a client. on the second button click, the folder must be checked to be existed, and so only the pdf file should be created inside it. the thing is that my code, without the part where it checks for folder existence, works on the first click, but doesn't work on the second because i get an exception that the folder already exists. but with the 'if' part, it doesn't work at all. like nothing is created. here is my code:</p> <pre><code>[assembly: Dependency(typeof(getpathUWP))] namespace ALNahrainAlphaApp.UWP { public class getpathUWP : path { public Task&lt; string&gt; get_path(string foldername, string filename, byte[] ar) { Task&lt;string&gt; t = Task.Run(() =&gt; pathtoget(foldername,filename,ar)); return t; } async private Task&lt;string&gt; pathtoget(string foldername, string filename, byte[] ar ) { // StorageFolder newFolder = null; if (!File.Exists(@&quot;C:\Users\ALNOOR\Downloads\d98cfcb0-e3cb-48e3-b720-fd9ace0ca7e8_htzz2mrv9gx22!App\alnahrainfiles&quot;)) { StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(@&quot;C:\Users\ALNOOR\Downloads\d98cfcb0-e3cb-48e3-b720-fd9ace0ca7e8_htzz2mrv9gx22!App\alnahrainfiles&quot;); StorageFile file = await folder.CreateFileAsync(filename); Stream stream = await file.OpenStreamForWriteAsync(); stream.Write(ar, 0, ar.Length); stream.Flush(); } else { StorageFolder newFolder = await DownloadsFolder.CreateFolderAsync(foldername); StorageFile file = await newFolder.CreateFileAsync(filename); Stream stream = await file.OpenStreamForWriteAsync(); stream.Write(ar, 0, ar.Length); stream.Flush(); } return &quot;&quot;; } } } </code></pre> <p>note that i am using a dependency service. i tried other ways to check if the folder exists, but nothing is working. what am i doing wrong?</p>
[ { "answer_id": 74406065, "author": "Jason", "author_id": 1338, "author_profile": "https://Stackoverflow.com/users/1338", "pm_score": 1, "selected": false, "text": "StorageFolder newFolder = await DownloadsFolder.CreateFolderAsync(foldername, CreationCollisionOption.OpenIfExists);\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10740284/" ]
74,405,519
<p>I am trying to create a simple binary tree capable of holding data of multiple types. The binary tree will be hard coded with data (compile time could work for this). Here is my code:</p> <pre class="lang-cpp prettyprint-override"><code>class BTree { template &lt;typename T&gt; struct Node { Node* left_ = nullptr; Node* right_ = nullptr; T data_; explicit Node(T value) : data_(value) {} }; Node&lt;int&gt;* root_ = nullptr; public: BTree() { root_ = new Node&lt;int&gt;(2); auto ptr = root_; ptr-&gt;left_ = new Node&lt;const char*&gt;(&quot;SomeString&quot;); } }; </code></pre> <p>I get the error message &quot;Cannot assign to type Node&lt;int&gt;* from Node&lt;const char*&gt;*&quot;.</p> <p>Now, I fully understand what the error message is saying and I know there is no way to convert a <code>char*</code> into an <code>int</code>, but is there a way to have my <code>left_</code> and <code>right_</code> pointer members to point at a templated type?</p> <p>For this project, I cannot include any third-party libraries.</p> <p>I tried changing them to <code>Node&lt;T&gt;*</code> but it still doesn't work because when the initial <code>root_</code> node is created, it is created with an <code>int</code> type. I also tried making a custom = operator:</p> <pre class="lang-cpp prettyprint-override"><code>Node&lt;T&gt;&amp; operator=(const Node&lt;const char*&gt;* ptr) { left_ = nullptr; right_ = nullptr; data_ = *ptr-&gt;data_; return this; } </code></pre> <p>This also does not work and at this point I'm a little bit out of my scope.</p>
[ { "answer_id": 74405675, "author": "Ben Voigt", "author_id": 103167, "author_profile": "https://Stackoverflow.com/users/103167", "pm_score": 2, "selected": true, "text": "struct NodeBase\n{\n NodeBase* left = nullptr;\n NodeBase* right = nullptr;\n};\n\ntemplate <typename T>\nstruct Node : NodeBase\n{\n T data;\n explicit Node(T value) : data(value) {}\n};\n\nNodeBase* root = nullptr;\n" }, { "answer_id": 74406095, "author": "n. m.", "author_id": 775806, "author_profile": "https://Stackoverflow.com/users/775806", "pm_score": 0, "selected": false, "text": "template <typename T>\nclass BinarySearchTree {\n struct Node { // not a template on its own\n T data;\n Node* left;\n Node* right;\n };\n Node* root;\n // the rest of the tree class\n};\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17968700/" ]
74,405,523
<p>Hello im trying to install phalcon and devtools but something is going wrong. I did everything I saw in tutorials installed phalcon, changed the php.ini, intalled devtools but it still doesn't no work.</p> <p><a href="https://i.stack.imgur.com/e4Urw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/e4Urw.png" alt="php version" /></a></p> <p><a href="https://i.stack.imgur.com/re6OT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/re6OT.png" alt="phalcon devtools" /></a></p> <p>but when i try to create a project...</p> <p><a href="https://i.stack.imgur.com/0Xvd8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0Xvd8.png" alt="this happens" /></a></p>
[ { "answer_id": 74405675, "author": "Ben Voigt", "author_id": 103167, "author_profile": "https://Stackoverflow.com/users/103167", "pm_score": 2, "selected": true, "text": "struct NodeBase\n{\n NodeBase* left = nullptr;\n NodeBase* right = nullptr;\n};\n\ntemplate <typename T>\nstruct Node : NodeBase\n{\n T data;\n explicit Node(T value) : data(value) {}\n};\n\nNodeBase* root = nullptr;\n" }, { "answer_id": 74406095, "author": "n. m.", "author_id": 775806, "author_profile": "https://Stackoverflow.com/users/775806", "pm_score": 0, "selected": false, "text": "template <typename T>\nclass BinarySearchTree {\n struct Node { // not a template on its own\n T data;\n Node* left;\n Node* right;\n };\n Node* root;\n // the rest of the tree class\n};\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20399502/" ]
74,405,528
<p>Say I have a directive that has a selector of <code>selector: '[example-directive]'</code>. Is there a way to pass in a second input to the directive? I've been able to succeed by changing the selector to <code>selector: '[exampleDirective]'</code> and prefixing the input with exampleDirective, but I'm wondering if there's a way to do it in kebab case.</p> <p>This is roughly what the directive looks like:</p> <pre><code>@Directive({ selector: '[example-directive]', }) export class ExampleDirective implements OnChanges { @Input('example-directive') input1: string; @Input() exampleDirectiveInput2: string; </code></pre> <p>I've tried to add an alias to the second input with no luck:</p> <pre><code>@Input('input2') exampleDirectiveInput2: string; </code></pre> <p>html: <code>&lt;div *example-directive=&quot;'value1'; input2: 'value2'&quot;&gt;&lt;/div&gt;</code></p>
[ { "answer_id": 74405675, "author": "Ben Voigt", "author_id": 103167, "author_profile": "https://Stackoverflow.com/users/103167", "pm_score": 2, "selected": true, "text": "struct NodeBase\n{\n NodeBase* left = nullptr;\n NodeBase* right = nullptr;\n};\n\ntemplate <typename T>\nstruct Node : NodeBase\n{\n T data;\n explicit Node(T value) : data(value) {}\n};\n\nNodeBase* root = nullptr;\n" }, { "answer_id": 74406095, "author": "n. m.", "author_id": 775806, "author_profile": "https://Stackoverflow.com/users/775806", "pm_score": 0, "selected": false, "text": "template <typename T>\nclass BinarySearchTree {\n struct Node { // not a template on its own\n T data;\n Node* left;\n Node* right;\n };\n Node* root;\n // the rest of the tree class\n};\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11489532/" ]
74,405,529
<p>How do I add the same function to all plus button so that each time I click on any of these plus buttons, the number will increase by 1 ,in this case, 12 will become 13 then 14 etc.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const countUp = document.querySelector('.countUp') const countDown = document.querySelector('.countDown') const counter = document.querySelector('.num') let count = counter.textContent function countUp() { countUp.forEach((count) =&gt; { count.addEventlistener('click', () =&gt; { count++ counter.innerText = count }) }) }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="rating"&gt; &lt;button class="countUp"&gt;+&lt;/button&gt; &lt;span class="num"&gt;12&lt;/span&gt; &lt;button class="countDown"&gt;-&lt;/button&gt; &lt;/div&gt; &lt;div class="rating"&gt; &lt;button class="countUp"&gt;+&lt;/button&gt; &lt;span class="num"&gt;12&lt;/span&gt; &lt;button class="countDown"&gt;-&lt;/button&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74405675, "author": "Ben Voigt", "author_id": 103167, "author_profile": "https://Stackoverflow.com/users/103167", "pm_score": 2, "selected": true, "text": "struct NodeBase\n{\n NodeBase* left = nullptr;\n NodeBase* right = nullptr;\n};\n\ntemplate <typename T>\nstruct Node : NodeBase\n{\n T data;\n explicit Node(T value) : data(value) {}\n};\n\nNodeBase* root = nullptr;\n" }, { "answer_id": 74406095, "author": "n. m.", "author_id": 775806, "author_profile": "https://Stackoverflow.com/users/775806", "pm_score": 0, "selected": false, "text": "template <typename T>\nclass BinarySearchTree {\n struct Node { // not a template on its own\n T data;\n Node* left;\n Node* right;\n };\n Node* root;\n // the rest of the tree class\n};\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20464992/" ]
74,405,574
<p>How to install the latest python version <code>3.11.0</code> on ArchLinux through pacman?</p> <p><a href="https://wiki.archlinux.org/title/Python#Other_versions" rel="nofollow noreferrer">ArchLinux wiki</a> says current version is <code>3.10</code>, although python 3.11 has been officially released.</p> <p>When running <code>sudo pacman -Syyu p</code> I'm welcomed with <code>warning: python-3.10.8-3 is up to date</code>.</p> <p>Am I doing something wrong?</p>
[ { "answer_id": 74405825, "author": "Imagine Eyes", "author_id": 14091076, "author_profile": "https://Stackoverflow.com/users/14091076", "pm_score": 2, "selected": true, "text": "yay -S python311\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8534073/" ]
74,405,584
<p>Im trying to build a qsort function that will sort words in my array of pointers **allwords, uniquely. But im going wrong somewhere, what am i doing wrong? (very new to C)</p> <pre><code>static int intcmp(const void *a, const void *b) { const int *left = a; const int *right = b; return *left - *right; } </code></pre>
[ { "answer_id": 74405723, "author": "Vlad from Moscow", "author_id": 2877241, "author_profile": "https://Stackoverflow.com/users/2877241", "pm_score": 2, "selected": false, "text": "static int intcmp(const void *a, const void *b) {\n const char *left = *( const char ** )a;\n const char *right = *( const char ** )b;\n return strcmp( left, right );\n}\n" }, { "answer_id": 74406348, "author": "shy45", "author_id": 20313707, "author_profile": "https://Stackoverflow.com/users/20313707", "pm_score": 0, "selected": false, "text": "#include <vector>\n#include <string>\n#include <algorithm>\nusing namespace std;\n\nint main() {\n vector<string> v{ \"ghi\", \"def\", \"abc\", \"def\" };\n sort(v.begin(), v.end());\n v.erase(unique(v.begin(), v.end()), v.end());\n for (auto s : v) {\n printf(\"%s\\n\", s.c_str());\n }\n}\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20352716/" ]
74,405,595
<p>I have this page like image below: <a href="https://i.stack.imgur.com/nrRZJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nrRZJ.png" alt="table" /></a></p> <ul> <li>The filter has a dynamic width and is an external angular component</li> <li>the table is inside the &quot;parent&quot; component</li> </ul> <p><strong>FYI:</strong></p> <ul> <li>The table component has a <code>[height]=&quot;something&quot;</code> that accepts either string or number as parameters.</li> <li>The table is a pivot table using a custom component called <a href="https://js.devexpress.com/Demos/WidgetsGallery/Demo/PivotGrid/SimpleArray/Angular/Light/" rel="nofollow noreferrer">Dev-Extreme</a></li> </ul> <p>All i want is to assign a value inside the <code>[height]=&quot;&quot;</code> in the HTML component page that is dynamic so that the height of the table resizes based on how much space there is left in the page.</p> <p>Could also use TypeScript to do that and maybe calculate the height each components takes in the page except the table and do calculations on that.</p> <p>Can anyone help me here, i've been stuck on this for two hours.</p>
[ { "answer_id": 74406671, "author": "bcngr", "author_id": 5220895, "author_profile": "https://Stackoverflow.com/users/5220895", "pm_score": 1, "selected": false, "text": "display: flex" }, { "answer_id": 74432054, "author": "devludo", "author_id": 19974585, "author_profile": "https://Stackoverflow.com/users/19974585", "pm_score": 1, "selected": true, "text": "@ViewChild()" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405595", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19974585/" ]
74,405,630
<p>List1 and List2 are the 2 lists which I have, expected output should look like list 3, How can I use LINQ in c# to achieve this.</p> <pre><code>Input List1 = {&quot;test1&quot;, &quot;test2&quot;,&quot;test3&quot;}; Input List2 = {{&quot;name&quot;: &quot;test1&quot;, &quot;value&quot;:1},{&quot;name&quot;: &quot;test2&quot;, &quot;value&quot;:2},{&quot;name&quot;: &quot;test5&quot;, &quot;value&quot;:5}}; Output List3 = {{&quot;name&quot;: &quot;test1&quot;, &quot;value&quot;:1},{&quot;name&quot;: &quot;test2&quot;, &quot;value&quot;:2}}; </code></pre>
[ { "answer_id": 74405701, "author": "Dmitry Bychenko", "author_id": 2319407, "author_profile": "https://Stackoverflow.com/users/2319407", "pm_score": 2, "selected": false, "text": "List2" }, { "answer_id": 74405757, "author": "Tim Schmelter", "author_id": 284240, "author_profile": "https://Stackoverflow.com/users/284240", "pm_score": 2, "selected": true, "text": "var query = from name in list1\n join item in list2\n on name equals item.name\n select item;\n\nvar list3 = query.ToList();\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9062892/" ]
74,405,652
<p>please help me to get solve this below scenario. I am new to the SQL server management</p> <p>Table</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Request</th> <th>Obj</th> </tr> </thead> <tbody> <tr> <td>123</td> <td>483</td> </tr> <tr> <td>123</td> <td>456</td> </tr> <tr> <td>456</td> <td>456</td> </tr> </tbody> </table> </div> <p>I have a table like this in the server</p> <p>I need to get the result as below</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Request</th> <th>result</th> </tr> </thead> <tbody> <tr> <td>123</td> <td>new</td> </tr> <tr> <td>123</td> <td>new</td> </tr> <tr> <td>456</td> <td>WIP</td> </tr> </tbody> </table> </div> <p>The logic is If the request have both 483 and 456 object then this will be &quot;new&quot; If the request have only 456 and not have 483 then it will be WIP</p> <p>Can someone please help me to get the code for those requirements</p> <p>Thank you for your time and help</p> <p>Code [Resolved]</p> <pre><code>SELECT T.Request,(CASE WHEN (D.cn = 2 AND obj = 483 OR obj = 456) OR (D.cn = 1 AND obj = 456) THEN 'NEW' WHEN (D.cn = 1 AND obj = 483) THEN 'WIP' WHEN (D.cn = 2 AND obj = 256 OR obj = 283) OR (D.cn = 1 AND obj = 283) THEN 'Cancel' WHEN (D.cn = 1 AND obj = 256) THEN 'Cancel - WIP' ELSE 'NA' END) AS [Result] FROM table_name T LEFT JOIN ( SELECT Request ,COUNT(DISTINCT CASE WHEN obj IN (483,456,283,256) THEN obj END) AS cn FROM table_name GROUP BY Request ) D ON T.Request = D.Request ORDER BY T.Request </code></pre>
[ { "answer_id": 74405701, "author": "Dmitry Bychenko", "author_id": 2319407, "author_profile": "https://Stackoverflow.com/users/2319407", "pm_score": 2, "selected": false, "text": "List2" }, { "answer_id": 74405757, "author": "Tim Schmelter", "author_id": 284240, "author_profile": "https://Stackoverflow.com/users/284240", "pm_score": 2, "selected": true, "text": "var query = from name in list1\n join item in list2\n on name equals item.name\n select item;\n\nvar list3 = query.ToList();\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16959411/" ]
74,405,657
<p>I have a dataframe where numbers for the variable <code>value</code> are the total funding amounts of specific programs that apply throughout a certain region. Because the funding amounts are reported as totals, the individual amount received by an area cannot be determined, and the total amount is therefore displayed for each region covered by the program. I therefore need to average the amount give to each region based on the number of regions among which it is divided. How can I do this for each program?</p> <p>My dataframe looks like the following:</p> <pre><code>program region value a 01 100 b 02 250 b 03 250 b 04 250 c 01 200 c 03 200 d 02 600 e 01 700 f 01 100 f 04 100 </code></pre> <p>The desired output would therefore be the following:</p> <pre><code>program region value new_value a 01 100 100 b 02 250 83.333 b 03 250 83.333 b 04 250 83.333 c 01 200 100 c 03 200 100 d 02 600 600 e 01 700 700 f 01 100 50 f 04 100 50 </code></pre>
[ { "answer_id": 74405710, "author": "dvera", "author_id": 18484551, "author_profile": "https://Stackoverflow.com/users/18484551", "pm_score": 3, "selected": true, "text": "library(tidyverse)\n\ndf %>%\n group_by(program) %>%\n mutate(new_value = first(value) / n())\n" }, { "answer_id": 74405819, "author": "Jilber Urbina", "author_id": 1315767, "author_profile": "https://Stackoverflow.com/users/1315767", "pm_score": 2, "selected": false, "text": "> df$new_value <- with(df, ave(value, program, FUN= function(x) x/length(x)))\n> df\n program region value new_value\n1 a 1 100 100.00000\n2 b 2 250 83.33333\n3 b 3 250 83.33333\n4 b 4 250 83.33333\n5 c 1 200 100.00000\n6 c 3 200 100.00000\n7 d 2 600 600.00000\n8 e 1 700 700.00000\n9 f 1 100 50.00000\n10 f 4 100 50.00000\n" }, { "answer_id": 74405992, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 2, "selected": false, "text": "data.table" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18574641/" ]
74,405,666
<p>I have a <code>ButtonTypes</code> class:</p> <pre><code>class ButtonTypes: def __init__(self): self.textType = &quot;text&quot; self.callbackType = &quot;callback&quot; self.locationType = &quot;location&quot; self.someAnotherType = &quot;someAnotherType&quot; </code></pre> <p>And a function that should take one of the attributes of the <code>ButtonTypes</code> class as an argument:</p> <pre><code>def create_button(button_type): pass </code></pre> <p>How can I specify that the argument of the <code>create_button</code> function should not just be a string, but exactly one of the attributes of the <code>ButtonTypes</code> class?</p> <p>Something like this: <code>def create_button(button_type: ButtonTypes.Type)</code></p> <p>As far as I understand, I need to create a <code>Type</code> class inside the <code>ButtonTypes</code> class, and then many other classes for each type that inherit the <code>Type</code> class, but I think something in my train of thought is wrong.</p>
[ { "answer_id": 74405732, "author": "chepner", "author_id": 1126841, "author_profile": "https://Stackoverflow.com/users/1126841", "pm_score": 1, "selected": false, "text": "from enum import Enum\n\nclass ButtonType:\n TEXT = \"text\"\n CALLBACK = \"callback\"\n LOCATION = \"location\"\n SOMETHINGELSE = \"someOtherType\"\n\n\ndef create_button(button_type: ButtonType):\n ...\n" }, { "answer_id": 74405735, "author": "Carcigenicate", "author_id": 3000206, "author_profile": "https://Stackoverflow.com/users/3000206", "pm_score": 3, "selected": true, "text": "Enum" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18196171/" ]
74,405,739
<p><img src="https://i.stack.imgur.com/Jr3z1.png" alt="enter image description here" /></p> <p>How do I use the QuantityFormula column to iterate over the column headers. For example to find</p> <ol> <li>where count (from QuantityFormula) == count (from headers.</li> <li>Take the value of that row</li> <li>To produce a new column called Quantity, with that value.</li> <li>Do the same for all Count, Area, Volume</li> </ol> <p>It needs to work if new rows are added too.</p> <p>I found this code online, to start with looking to modify it or create a new piece of code to do what I need. How do I loop and compare Column to header (lookup_array == lookup_value) and store row value of that.</p> <p>Note: the NaN columns (count, area, volume) could have values in them in future tables</p> <pre class="lang-py prettyprint-override"><code>def xlookup(lookup_value, lookup_array, return_array, if_not_found:str = ''): match_value = return_array.loc[lookup_array == lookup_value] if match_value.empty: return f'&quot;{lookup_value}&quot; not found!' if if_not_found == '' else if_not_found else: return match_value.tolist()[0] Merged['Quantity'] = Merged['QuantityFormula'].apply(xlookup, args = (Merged['NRM'], left['UoM'])) </code></pre> <p>I have a XLOOKUP functionality but I need something slightly different.</p>
[ { "answer_id": 74405732, "author": "chepner", "author_id": 1126841, "author_profile": "https://Stackoverflow.com/users/1126841", "pm_score": 1, "selected": false, "text": "from enum import Enum\n\nclass ButtonType:\n TEXT = \"text\"\n CALLBACK = \"callback\"\n LOCATION = \"location\"\n SOMETHINGELSE = \"someOtherType\"\n\n\ndef create_button(button_type: ButtonType):\n ...\n" }, { "answer_id": 74405735, "author": "Carcigenicate", "author_id": 3000206, "author_profile": "https://Stackoverflow.com/users/3000206", "pm_score": 3, "selected": true, "text": "Enum" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20479479/" ]
74,405,775
<p>I'm writing my first <strong>QT5</strong> app... this uses a third party map library (<a href="https://github.com/AmonRaNet/QGeoView" rel="nofollow noreferrer">QGeoView</a>). I need to draw an object (something like a stylized airplane) over this map. Following the library coding guideline I derived from the base class <code>QGVDrawItem</code> my <code>QGVAirplane</code>. The airplane class contains heading and position values: such values must be used to <em>draw</em> the airplane on the map (of course in the correct position and with correct heading). The library requires <code>QGVDrawItem</code> derivatives to override three base class methods:</p> <pre><code>QPainterPath projShape() const; void projPaint(QPainter* painter); void onProjection(QGVMap* geoMap) </code></pre> <p>the first method is used to achieve the area of the map that needs to be updated the second is the method responsible to draw the object on the map. The third method is needed to reproject the point from the coordinate space on the map (it's not relevant for the solution of my problem).</p> <p>My code looks like that:</p> <pre><code>void onProjection(QGVMap* geoMap) { QGVDrawItem::onProjection(geoMap); mProjPoint = geoMap-&gt;getProjection()-&gt;geoToProj(mPoint); } QPainterPath projShape() const { QRectF _bounding = createGlyph().boundingRect(); double _size = fmax(_bounding.height(), _bounding.width()); QPainterPath _bounding_path; _bounding_path.addRect(0,0,_size,_size); _bounding_path.translate(mProjPoint.x(), mProjPoint.y()); return _bounding_path; } // This function creates the path containing the airplane glyph // along with its label QPainterPath createGlyph() const { QPainterPath _path; QPolygon _glyph = QPolygon(); _glyph &lt;&lt; QPoint(0,6) &lt;&lt; QPoint(0,8) &lt;&lt; QPoint(14,6) &lt;&lt; QPoint(28,8) &lt;&lt; QPoint(28,6) &lt;&lt; QPoint(14,0); _path.addPolygon(_glyph); _path.setFillRule(Qt::FillRule::OddEvenFill); _path.addText(OFF_X_TEXT, OFF_Y_TEXT, mFont , QString::number(mId)); QTransform _transform; _transform.rotate(mHeading); return _transform.map(_path); } // This function is the actual painting method void drawGlyph(QPainter* painter) { painter-&gt;setRenderHints(QPainter::Antialiasing, true); painter-&gt;setBrush(QBrush(mColor)); painter-&gt;setPen(QPen(QBrush(Qt::black), 1)); QPainterPath _path = createGlyph(); painter-&gt;translate(mProjPoint.x(), mProjPoint.y()); painter-&gt;drawPath(_path); } </code></pre> <p>of course:</p> <ul> <li><code>mProjPoint</code> is the position of the airplane,</li> <li><code>mHeading</code> is the heading (the direction where the airplane is pointing),</li> <li><code>mId</code> is a number identifying the airplane (will be displayed as a label <em>under</em> airplane glyph),</li> <li><code>mColor</code> is the color assigned to the airplane.</li> </ul> <p>The problem here is the mix of rotation and translation transformation: since the object is rotated <code>projShape()</code> methods return a bounding rectangle that's not fully overlapping the object drawn on the map ... I also suspect that the <em>center</em> of the object is not correctly pointed on <code>mProjPoint</code> I tried many times trying to translate the bounding rectangle to <em>center</em> the object without luck.</p> <p>Another minor issue is the fillup of the font .. the label under the airplane glyph is not solid but is filled with the same color of the airplane.</p> <p>Can anyone help me?</p>
[ { "answer_id": 74409979, "author": "Stephen Quan", "author_id": 881441, "author_profile": "https://Stackoverflow.com/users/881441", "pm_score": 1, "selected": false, "text": "translate( -origin.x, -origin.y );\nrotate( angle );\nscale( scale.x, scale y);\ntranslate( origin.x, origin.y );\ntranslate( translation.x, translation.y )\n" }, { "answer_id": 74444987, "author": "weirdgyn", "author_id": 3058368, "author_profile": "https://Stackoverflow.com/users/3058368", "pm_score": 1, "selected": true, "text": "QPainterPath projShape() const\n{\n QPainterPath _path;\n\n QRectF _glyph_bounds = _path.boundingRect();\n\n QPainterPath _textpath;\n\n _textpath.addText(0, 0, mFont, QString::number(mId));\n\n QRectF _text_bounds = _textpath.boundingRect();\n\n _textpath.translate(_glyph_bounds.width()/2-_text_bounds.width()/2, _glyph_bounds.height()+_text_bounds.height());\n\n _path.addPath(_textpath);\n\n QTransform _transform;\n\n _transform.translate(mProjPoint.x(),mProjPoint.y());\n\n _transform.rotate(360-mHeading);\n\n _transform.translate(-_path.boundingRect().width()/2, -_path.boundingRect().height()/2);\n\n return _transform.map(_path);\n}\n\nvoid projPaint(QPainter* painter)\n{\n painter->setRenderHint(QPainter::Antialiasing, true);\n painter->setRenderHint(QPainter::TextAntialiasing, true);\n painter->setRenderHint(QPainter::SmoothPixmapTransform, true);\n painter->setRenderHint(QPainter::HighQualityAntialiasing, true);\n\n painter->setBrush(QBrush(mColor));\n painter->setPen(QPen(QBrush(Qt::black), 1));\n painter->setFont(mFont);\n\n QPainterPath _path = projShape();\n\n painter->drawPath(_path);\n}\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3058368/" ]
74,405,803
<p>I have a problem with understanding fixed-point arithmetic and its implementation in C++. I was trying to understand this code:</p> <pre><code>#define scale 16 int DoubleToFixed(double num){ return num * ((double)(1 &lt;&lt; scale)); } double FixedToDoble(int num){ return (double) num / (double)(1 &lt;&lt; scale); } double IntToFixed(int num){ return x &lt;&lt; scale } </code></pre> <p>I am trying to understand exactly why we shift. I know that shifting to the right is basically multiplying that number by 2<sup>x</sup>, where x is by how many positions we want to shift or scale, and shifting to the left is basically division by 2<sup>x</sup>.</p> <p>But why do we need to shift when we convert from int to fixed point?</p>
[ { "answer_id": 74405978, "author": "Eric Postpischil", "author_id": 298225, "author_profile": "https://Stackoverflow.com/users/298225", "pm_score": 1, "selected": false, "text": "scale" }, { "answer_id": 74406032, "author": "Mooing Duck", "author_id": 845092, "author_profile": "https://Stackoverflow.com/users/845092", "pm_score": -1, "selected": false, "text": "1/(1<<scale)" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14501168/" ]
74,405,835
<p>I was updating my bot to discord.js 13V on the update when I mention somone I trhows me <a href="https://i.stack.imgur.com/DjkeR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DjkeR.png" alt="enter image description here" /></a></p> <p>this is the code im husing `</p> <pre><code>const galletita1= new Discord.MessageEmbed() .setDescription(message.author.username + ` Toma una galletita ` + message.mentions.members.first()) .setFooter({ text:&quot;espero te guste&quot;}) .setColor(' #FFFF00') .setImage('http://pm1.narvii.com/6559/7ce32024e00c60cb695a8e838d5bcaf3264bc612_hq.jpg') </code></pre> <p>`</p> <p>in the past version this work to display the username of the member you mention but now i get the number id</p> <p>i tried to declare a variable with the message.mentions.members.first() and it works the same</p>
[ { "answer_id": 74405978, "author": "Eric Postpischil", "author_id": 298225, "author_profile": "https://Stackoverflow.com/users/298225", "pm_score": 1, "selected": false, "text": "scale" }, { "answer_id": 74406032, "author": "Mooing Duck", "author_id": 845092, "author_profile": "https://Stackoverflow.com/users/845092", "pm_score": -1, "selected": false, "text": "1/(1<<scale)" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11357461/" ]
74,405,837
<p>I have the following Main class that takes a dataStore as a constructor parameter for Foo class.</p> <p>In the Main class I want to pass to Foo only one constructor, 'dataStore', but in the Foo constructor class I want to initialize besides dataStore also a couple of other services.</p> <pre><code>public class Main { private DataStore dataStore = new DataStore(); public Main() { var foo = new Foo(dataStore); foo.DoSomething(); } } </code></pre> <p>I've try this approach with chaining the Foo constructors, but only the dataStore is initialized, _serviceOne and _serviceTwo are null in this case (because I'm passing null in the construnctor chaining, and the second construnctor is never called).</p> <pre><code>public class Foo { private readonly DataStore _dataStore; private readonly IServiceOne _serviceOne; private readonly IServiceTwo _serviceTwo; public Foo(DataStore dataStore) : this(null, null) { _dataStore = dataStore; } public Foo(IServiceOne serviceOne, IServiceTwo serviceTwo) { _serviceOne = serviceOne; _serviceTwo = serviceTwo; } public void DoSomething() { // do something } } </code></pre> <p>If I try to pass all the data to only one Foo constructor, I need to pass _dataStore , _serviceOne and _serviceTwo as arguments for Foo as well in the Main classs and I don't what this.</p> <pre><code> public Foo(DataStore dataStore, IServiceOne serviceOne, IServiceTwo serviceTwo) { _dataStore = dataStore; _serviceOne = serviceOne; _serviceTwo = serviceTwo; } </code></pre> <p>Is there a way to pass only dataStore as argument in Main class, and also to initialize all the fields(_dataStore,_serviceOne,_serviceTwo) in Foo constructor class?</p> <p>Esentially I what to pass to Foo only the _dataStore and to instantiate the rest of the services in the Foo class itself:</p> <pre><code>var foo = new Foo(dataStore); </code></pre>
[ { "answer_id": 74405978, "author": "Eric Postpischil", "author_id": 298225, "author_profile": "https://Stackoverflow.com/users/298225", "pm_score": 1, "selected": false, "text": "scale" }, { "answer_id": 74406032, "author": "Mooing Duck", "author_id": 845092, "author_profile": "https://Stackoverflow.com/users/845092", "pm_score": -1, "selected": false, "text": "1/(1<<scale)" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11424192/" ]
74,405,839
<p>I have a table Table name - commands</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>name</th> <th>status</th> <th>group_id</th> </tr> </thead> <tbody> <tr> <td>id - number</td> <td>name - string</td> <td>status - 0 or 1</td> <td>group_id - number</td> </tr> </tbody> </table> </div> <p>I need to sort as follows: for all elements with the same group_id I have to check if at least one has a status of 1, if so, then leave, if not, then remove such a group and so on for all group_id</p> <p>I tried to do it through GROUP BY, and then using HAVING to remove unnecessary groups, but this way I don't get the whole table to be displayed or a query that does not work.</p> <p>I think it should look like:</p> <pre><code>SELECT COUNT(*) FROM commands GROUP BY group_id HAVING *condition* </code></pre> <p>Please let me know if there are any other commands to use.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>name</th> <th>status</th> <th>group_id</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>name1</td> <td>0</td> <td>1</td> </tr> <tr> <td>2</td> <td>name2</td> <td>0</td> <td>1</td> </tr> <tr> <td>3</td> <td>name3</td> <td>0</td> <td>2</td> </tr> <tr> <td>4</td> <td>name4</td> <td>1</td> <td>2</td> </tr> <tr> <td>5</td> <td>name5</td> <td>1</td> <td>2</td> </tr> <tr> <td>6</td> <td>name6</td> <td>0</td> <td>3</td> </tr> <tr> <td>7</td> <td>name7</td> <td>1</td> <td>4</td> </tr> </tbody> </table> </div> <p>Result:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>name</th> <th>status</th> <th>group_id</th> </tr> </thead> <tbody> <tr> <td>3</td> <td>name3</td> <td>0</td> <td>2</td> </tr> <tr> <td>4</td> <td>name4</td> <td>1</td> <td>2</td> </tr> <tr> <td>5</td> <td>name5</td> <td>1</td> <td>2</td> </tr> <tr> <td>7</td> <td>name7</td> <td>1</td> <td>4</td> </tr> </tbody> </table> </div>
[ { "answer_id": 74406192, "author": "ahmed", "author_id": 12705912, "author_profile": "https://Stackoverflow.com/users/12705912", "pm_score": 0, "selected": false, "text": "EXISTS" }, { "answer_id": 74406617, "author": "GMB", "author_id": 10676716, "author_profile": "https://Stackoverflow.com/users/10676716", "pm_score": 1, "selected": false, "text": "select *\nfrom (\n select t.*, bool_or(status = 1) over(partition by group_id) has_status_1\n from mytable t\n) t\nwhere has_status_1\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20479481/" ]
74,405,840
<p>I have fragment with list of notes. When user clicks on a note, they open fragment with note page. I use navigation UI and NavOptions to navigate:</p> <pre class="lang-kotlin prettyprint-override"><code> fun toNotePage() { val navOptions: NavOptions = NavOptions.Builder() .setPopUpTo(R.id.navigation_notes, true, true) .setRestoreState(true) .build() findNavController().navigate(R.id.navigation_note_page, null, navOptions) } </code></pre> <p>At first I used <code>.setPopUpTo(R.id.navigation_notes, false, true)</code>, with &quot;inclusive&quot; param false. That time I pressed on the note, note page fragment opened correctly, but back button didn't work. Than I changed &quot;inclusive&quot; param to true, and back button worked in the note page fragment, but only once. When I return with back button to notes list and than click on the note once more, I navigate to note page fragment, but back button stops working. And system back button closes application insteam of opening notes list.</p> <p>UPD: this code worked well, with &quot;inclusive&quot; &quot;false&quot;:</p> <pre class="lang-kotlin prettyprint-override"><code> fun toNotePage() { val navOptions: NavOptions = NavOptions.Builder() .setPopUpTo(R.id.navigation_notes, false, true) .setRestoreState(true) .build() findNavController().navigate(R.id.navigation_note_page, null, navOptions) } </code></pre> <p>And this code also worked well:</p> <pre class="lang-kotlin prettyprint-override"><code>findNavController().navigate(R.id.action_navigation_notes_to_navigation_note_page) </code></pre> <p>Problem was I was redirected every time I returned.</p>
[ { "answer_id": 74406192, "author": "ahmed", "author_id": 12705912, "author_profile": "https://Stackoverflow.com/users/12705912", "pm_score": 0, "selected": false, "text": "EXISTS" }, { "answer_id": 74406617, "author": "GMB", "author_id": 10676716, "author_profile": "https://Stackoverflow.com/users/10676716", "pm_score": 1, "selected": false, "text": "select *\nfrom (\n select t.*, bool_or(status = 1) over(partition by group_id) has_status_1\n from mytable t\n) t\nwhere has_status_1\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10743655/" ]
74,405,846
<pre><code>data = {'gems': [{'name': 'garnet', 'colour': 'red', 'month': 'January'}, {'name': 'emerald', 'colour': 'green', 'month': 'May'}, {'name': &quot;cat's eye&quot;, 'colour': 'yellow', 'month': 'June'}, {'name': 'sardonyx', 'colour': 'red', 'month': 'August'}, {'name': 'peridot', 'colour': 'green', 'month': 'September'}, {'name': 'ruby', 'colour': 'red', 'month': 'December'}]} </code></pre> <p>How do I create a list of colours and then just find the months with the colour red?</p> <p>I've tried for and if, but I keep getting the error message</p> <p>string indices must be integers</p>
[ { "answer_id": 74405884, "author": "Celius Stingher", "author_id": 11897007, "author_profile": "https://Stackoverflow.com/users/11897007", "pm_score": 2, "selected": true, "text": "[x['month'] for x in data['gems'] if x['colour'] == 'red']\n" }, { "answer_id": 74434136, "author": "Gonçalo Peres", "author_id": 7109869, "author_profile": "https://Stackoverflow.com/users/7109869", "pm_score": 0, "selected": false, "text": "pandas.json_normalize" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405846", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20479727/" ]
74,405,847
<p>I have this object in php:</p> <pre><code>$object = [ [ {&quot;catalogo&quot;: &quot;C400047&quot;, &quot;rfc_inf_aval&quot;: &quot;CIS981002NK4&quot;, }, {&quot;catalogo&quot;: &quot;C140064&quot;,&quot;rfc_inf_aval&quot;: &quot;MZT8501014S6&quot;,}, {&quot;catalogo&quot;: &quot;C400047&quot;,&quot;rfc_inf_aval&quot;: &quot;MZT8501014S6&quot;,}, {&quot;catalogo&quot;: &quot;C400047&quot;,&quot;rfc_inf_aval&quot;: &quot;CIS981002NK4&quot;,}, {&quot;catalogo&quot;: &quot;C140064&quot;,&quot;rfc_inf_aval&quot;: &quot;MZT8501014S6&quot;,}, {&quot;catalogo&quot;: &quot;C140064&quot;,&quot;rfc_inf_aval&quot;: &quot;MZT8501014S6&quot;,}, {&quot;catalogo&quot;: &quot;C140064&quot;,&quot;rfc_inf_aval&quot;: &quot;MZT8501014S6&quot;,}, {&quot;catalogo&quot;: &quot;C140064&quot;,&quot;rfc_inf_aval&quot;: &quot;CIS981002NK4&quot;,}, ], ] </code></pre> <p>and it should stay like this, that I eliminate all the repeated rfc of each catalog, the repeated catalogs should not be eliminated</p> <pre><code>[ [ {&quot;catalogo&quot;: &quot;C400047&quot;,&quot;rfc_inf_aval&quot;: &quot;CIS981002NK4&quot;,}, {&quot;catalogo&quot;: &quot;C140064&quot;,&quot;rfc_inf_aval&quot;: &quot;MZT8501014S6&quot;,}, {&quot;catalogo&quot;: &quot;C400047&quot;,&quot;rfc_inf_aval&quot;: &quot;MZT8501014S6&quot;,}, {&quot;catalogo&quot;: &quot;C140064&quot;,&quot;rfc_inf_aval&quot;: &quot;CIS981002NK4&quot;,}, ], ] </code></pre> <p>I have tried to do this but it removes all the rfcs and I need it to remove only the repeated rfcs but by catalog</p> <pre><code> for ($i=0; $i &lt; count($object); $i++) { if(!in_array($object[$i]-&gt;rfc_inf_aval, $array1)){ array_push($array1, $object[$i]-&gt;rfc_inf_aval); array_push($array2, $object[$i]); } } </code></pre>
[ { "answer_id": 74406053, "author": "Foobar", "author_id": 19625365, "author_profile": "https://Stackoverflow.com/users/19625365", "pm_score": 1, "selected": false, "text": " for ($i=0; $i < count($object); $i++) { \n $k = $object[$i]->catalogo.'|'.$object[$i]->rfc_inf_aval;\n $reduced[$k] = $object[$i];\n }\n $object = array_values($reduced);\n" }, { "answer_id": 74406243, "author": "manuerumx", "author_id": 1757214, "author_profile": "https://Stackoverflow.com/users/1757214", "pm_score": 0, "selected": false, "text": "<?php \n\n$js = <<<JSON\n[[\n {\"catalogo\": \"C400047\",\"rfc_inf_aval\": \"CIS981002NK4\"},\n {\"catalogo\": \"C140064\",\"rfc_inf_aval\": \"MZT8501014S6\"},\n {\"catalogo\": \"C400047\",\"rfc_inf_aval\": \"MZT8501014S6\"},\n {\"catalogo\": \"C400047\",\"rfc_inf_aval\": \"CIS981002NK4\"},\n {\"catalogo\": \"C140064\",\"rfc_inf_aval\": \"MZT8501014S6\"},\n {\"catalogo\": \"C140064\",\"rfc_inf_aval\": \"MZT8501014S6\"},\n {\"catalogo\": \"C140064\",\"rfc_inf_aval\": \"MZT8501014S6\"},\n {\"catalogo\": \"C140064\",\"rfc_inf_aval\": \"CIS981002NK4\"} \n]]\nJSON;\n// Get the real object as an associative array\n$data = json_decode($js, true);\n// Use the first element, since is a nested array\n$object = $data[0];\n\nfunction my_array_unique($array, $keep_key_assoc = false){\n $duplicate_keys = array();\n $tmp = array(); \n\n foreach ($array as $key => $val){\n // convert objects to arrays, in_array() does not support objects\n if (is_object($val))\n $val = (array)$val;\n\n if (!in_array($val, $tmp))\n $tmp[] = $val;\n else\n $duplicate_keys[] = $key;\n }\n\n foreach ($duplicate_keys as $key)\n unset($array[$key]);\n\n return $keep_key_assoc ? $array : array_values($array);\n}\n\nvar_dump(my_array_unique($object));\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12476660/" ]
74,405,870
<p>Clicking the red exit button removes the player from the forEach code, but not for loop.</p> <p>You click the blue button, next you click the red exit button to remove the player.</p> <p>How would I get the for loop code to work the same as the forEach code?</p> <p>This code is working.</p> <p><a href="https://jsfiddle.net/n1t3kjdw/" rel="nofollow noreferrer">https://jsfiddle.net/n1t3kjdw/</a></p> <pre><code> function removePlayerHandler(evt) { const el = evt.target; const container = el.closest(&quot;.container&quot;); const wrapper = container.querySelectorAll(&quot;.wrap&quot;); wrapper.forEach(function(wrapper) { if (wrapper.player) { return removePlayer(wrapper); } }); } </code></pre> <p>What did I do wrong here? <a href="https://jsfiddle.net/rbwsL8hf/" rel="nofollow noreferrer">https://jsfiddle.net/rbwsL8hf/</a></p> <p>Why is this code not working, what needs to be fixed?</p> <pre><code> function removePlayerHandler(evt) { const el = evt.target; const container = el.closest(&quot;.container&quot;); const wrappers = container.querySelectorAll(&quot;.wrap&quot;); { for (let i = 0; i &lt; wrappers[i].length; i++) { if (wrappers[i].player) { return removePlayer(wrappers[i]); } } } } </code></pre>
[ { "answer_id": 74405911, "author": "Salim", "author_id": 4478946, "author_profile": "https://Stackoverflow.com/users/4478946", "pm_score": 3, "selected": true, "text": "wrappers[i].length" }, { "answer_id": 74405923, "author": "Thiago Zazirskas", "author_id": 15187365, "author_profile": "https://Stackoverflow.com/users/15187365", "pm_score": 0, "selected": false, "text": "function removePlayerHandler(evt) {\n const el = evt.target;\n const container = el.closest(\".container\");\n const wrappers = container.querySelectorAll(\".wrap\");\n for (let i = 0; i < wrappers.length; i++) {\n if (wrappers[i].player) {\n return removePlayer(wrappers[i]);\n }\n }\n}\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17631451/" ]
74,405,878
<p>Given I have a string list in Python:</p> <pre><code>list = [&quot; banana &quot;, &quot;Cherry&quot;, &quot;apple&quot;] </code></pre> <p>I want to sort this list to be case insensitive AND ignore the whitespaces. So like this:</p> <pre><code>list = [&quot;apple&quot;, &quot; banana &quot;, &quot;Cherry&quot;] </code></pre> <p>If I use this:</p> <pre><code>sorted(list, key=str.casefold) </code></pre> <p>I get this:</p> <pre><code>list = [&quot; banana &quot;, &quot;apple&quot;, &quot;Cherry&quot;] </code></pre> <p>It's case insensitive, but the space character comes before the letters.</p> <p>If I use this:</p> <pre><code>sorted(list, key=lambda x:x.replace(' ', '')) </code></pre> <p>I get this:</p> <pre><code>list = [&quot;Cherry&quot;, &quot;apple&quot;, &quot; banana &quot;] </code></pre> <p>It ignores the spaces but is not case-insensitive. I've tried to combine the two solutions, but I couldn't make it work. Is there a way to fix this easily and &quot;merge&quot; the two results?</p>
[ { "answer_id": 74405901, "author": "azro", "author_id": 7212686, "author_profile": "https://Stackoverflow.com/users/7212686", "pm_score": 2, "selected": false, "text": "values = [\" banana \", \"Cherry\", \"apple\"]\nprint(sorted(values, key=lambda x: x.replace(' ', '').casefold()))\n# ['apple', ' banana ', 'Cherry']\n" }, { "answer_id": 74405902, "author": "I'mahdi", "author_id": 1740577, "author_profile": "https://Stackoverflow.com/users/1740577", "pm_score": 3, "selected": true, "text": "str.strip()" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14648381/" ]
74,405,895
<p>This is the first time I have had to use a SQL pivot table, so I'm not very proficient in getting results with the method, my pivot table is not returning the results I expected and I don't know why...</p> <p>Here is my instruction:</p> <p>&quot;Create a sql that will show the total number create [ddateCreated] of patients per branch for each month for 2020 - 2021. Display Required fields BranchName , Year , Jan , Feb, Mar, Apr, May , Jun , Jul ,Aug , Sept , Oct , Nov , Dec.&quot;</p> <p>so I came up with the below query:</p> <pre><code>select * from ( select datename(month, b.dDateCreated) as [Month] , sName as BranchName , datename(Year, b.dDateCreated) as [Year], p.ipkPatientID from Branch b inner join Patients p on p.ifkBranchID=b.ipkBranchID where (b.dDateCreated BETWEEN '2020-01-01 00:00:00.000'AND '2021-12-31 23:59:59.999') ) as Src pivot( count(ipkPatientID) for [Month] in ([Jan], [Feb], [Mar], [Apr], [May], [Jun], [Jul], [Aug], [Sept], [Oct], [Nov], [Dec]) ) as Pivot_Table </code></pre> <p>Here are the results:</p> <pre><code>BranchName Year Jan Feb Mar Apr May Jun Jul Aug Sept Oct Nov Dec Cdldttd dd Fhdftwt wndfplpgy 2020 0 0 0 0 0 0 0 0 0 0 0 0 Ddjdlppmdnt 2020 0 0 0 0 14 0 0 0 0 0 0 0 Ddpn Cdhpnfp 2020 0 0 0 0 0 0 0 0 0 0 0 0 dlmfdn Lpnw Lfchtdnwnhg 2020 0 0 0 0 0 0 0 0 0 0 0 0 dlmfdn Lpnw Mwffkdng 2020 0 0 0 0 0 0 0 0 0 0 0 0 Dnhwwnjflld 2020 0 0 0 0 0 0 0 0 0 0 0 0 dthpwd 2020 0 0 0 0 0 0 0 0 0 0 0 0 fnc and wttpcfwtdt 2020 0 0 0 0 5 0 0 0 0 0 0 0 Fwdhfd Gldn 2020 0 0 0 0 0 0 0 0 0 0 0 0 Hdwhdwt pfffcd 2020 0 0 0 0 0 0 0 0 0 0 0 0 Hpmd jftft 2020 0 0 0 0 91 0 0 0 0 0 0 0 </code></pre> <p>I can't understand why it shows 0's everywhere? i have tried to refactor this query mulptiple times but I cant come right... Also note how there is little data in the Month of May, for some odd reason.</p> <p>Look at the below query, which is the source of the pivot table:</p> <pre><code>select datename(month, b.dDateCreated) as [Month] , sName as BranchName , datename(Year, b.dDateCreated) as [Year], p.ipkPatientID from Branch b inner join Patients p on p.ifkBranchID=b.ipkBranchID where (b.dDateCreated BETWEEN '2020-01-01 00:00:00.000'AND '2021-12-31 23:59:59.999') </code></pre> <p>These results look correct?</p> <p><a href="https://i.stack.imgur.com/g12MD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/g12MD.png" alt="enter image description here" /></a></p> <p>and there is data for every month... So how would I count the patient id's for every month and display it?</p>
[ { "answer_id": 74406397, "author": "John Cappelletti", "author_id": 1570000, "author_profile": "https://Stackoverflow.com/users/1570000", "pm_score": 1, "selected": false, "text": "Select * \n From (\n select left(datename(month, b.dDateCreated),3) as [Month] , -- Notice Jan,Feb,Mar\n sName as BranchName ,\n datename(Year, b.dDateCreated) as [Year],\n p.ipkPatientID \n from Branch b\n inner join Patients p on p.ifkBranchID=b.ipkBranchID\n where b.dDateCreated BETWEEN '2020-01-01 00:00:00.000'AND '2021-12-31 23:59:59.997'\n ) as Src\n Pivot( count(ipkPatientID) for [Month] in ([Jan],\n [Feb],\n [Mar],\n [Apr],\n [May],\n [Jun],\n [Jul],\n [Aug],\n [Sep], -- Notice Sep not Sept\n [Oct],\n [Nov],\n [Dec] ) ) as Pivot_Table\n" }, { "answer_id": 74408663, "author": "GMB", "author_id": 10676716, "author_profile": "https://Stackoverflow.com/users/10676716", "pm_score": 1, "selected": true, "text": "pivot" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405895", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15321226/" ]
74,405,899
<pre class="lang-py prettyprint-override"><code>while True: try: age = int(input(&quot;Enter your age: &quot;)) if age &lt;= 0: raise TypeError(&quot;Enter a number greater than zero&quot;) except ValueError: print(&quot;Invalid age. Must be a number.&quot;) except TypeError as err: print(err) except: print('Invalid input') break while True: try: height = float(input('Enter your height in inches: ')) if height &lt;= 0: raise TypeError(&quot;Enter a number greater than 0&quot;) break except ValueError: raise ValueError(&quot;Height must be a number.&quot;) </code></pre> <p>I have multiple variables that need user input in order for the program to run. I need to get 3 variables from a user and they need to input the values correctly. I thought I should use try/except blocks for each of the variables but when I use the try/except block for the first variable and begin writing the second block the program skips over the exceptions even if the user input is incorrect.</p> <p>I thought about using another while loop but I'm not sure how to write in python the idea of; if previous condition is met move onto next block of code. I tried using the same try/except block for two variables and failed. Any insight would be helpful. The problem is that when an incorrect value is entered the program still continues onto the next try block.</p>
[ { "answer_id": 74406397, "author": "John Cappelletti", "author_id": 1570000, "author_profile": "https://Stackoverflow.com/users/1570000", "pm_score": 1, "selected": false, "text": "Select * \n From (\n select left(datename(month, b.dDateCreated),3) as [Month] , -- Notice Jan,Feb,Mar\n sName as BranchName ,\n datename(Year, b.dDateCreated) as [Year],\n p.ipkPatientID \n from Branch b\n inner join Patients p on p.ifkBranchID=b.ipkBranchID\n where b.dDateCreated BETWEEN '2020-01-01 00:00:00.000'AND '2021-12-31 23:59:59.997'\n ) as Src\n Pivot( count(ipkPatientID) for [Month] in ([Jan],\n [Feb],\n [Mar],\n [Apr],\n [May],\n [Jun],\n [Jul],\n [Aug],\n [Sep], -- Notice Sep not Sept\n [Oct],\n [Nov],\n [Dec] ) ) as Pivot_Table\n" }, { "answer_id": 74408663, "author": "GMB", "author_id": 10676716, "author_profile": "https://Stackoverflow.com/users/10676716", "pm_score": 1, "selected": true, "text": "pivot" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20076579/" ]
74,405,914
<p>As mentioned in the title, I want to pass a function as an argument for another function in Julia. However, I want the passed function to be partially specified, such as:</p> <pre><code>func1(a, b) = println(a, b) func2(a, func::Function) = func(a) func2(1, func1(b=0)) # returns an error </code></pre> <p>An alternative is to build a new function func3 such as</p> <pre><code>func3(a) = func1(a, b=0) func2(1, func3) </code></pre> <p>But it does not look so elegant. Is it possible not to define a new function?</p>
[ { "answer_id": 74406304, "author": "Shayan", "author_id": 11747148, "author_profile": "https://Stackoverflow.com/users/11747148", "pm_score": 2, "selected": false, "text": "func1(a, b)" }, { "answer_id": 74407629, "author": "Udoh Jeremiah", "author_id": 18059419, "author_profile": "https://Stackoverflow.com/users/18059419", "pm_score": 2, "selected": true, "text": "julia> func1(a, b) = println(a, b)\nfunc1 (generic function with 1 method)\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13241995/" ]
74,405,944
<p>I have some large .csv files of experimental data. Their sizes are in the range 30MB-3GB. I have successfully read them in using pandas and have performed some other calculations on the data. As it stands I have an extremely long 1D array which I need to take the mean of.</p> <p>By default I used statistics.mean(array) but this seems to be taking an incredibly long time to run.</p> <p>Through testing individual sections of my code, I know for definate that it is the line statistics.mean(array) that is taking so long to run.</p> <p>Is there a more efficient way to calculate the mean of large data sets than this?</p> <p>Thanks!</p> <pre><code>def GetMean(ionVelocityArray): return stats.mean(ionVelocityArray) </code></pre> <p>I have been waiting for 2 hours for this function to finish running on a 30MB file.</p>
[ { "answer_id": 74406304, "author": "Shayan", "author_id": 11747148, "author_profile": "https://Stackoverflow.com/users/11747148", "pm_score": 2, "selected": false, "text": "func1(a, b)" }, { "answer_id": 74407629, "author": "Udoh Jeremiah", "author_id": 18059419, "author_profile": "https://Stackoverflow.com/users/18059419", "pm_score": 2, "selected": true, "text": "julia> func1(a, b) = println(a, b)\nfunc1 (generic function with 1 method)\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20479771/" ]
74,405,959
<p>I am trying to do checkboxes in the list view flutter but when I select one all are selected, I want to select only the one I click not all. also, How I can know which items are selected</p> <p>here is my code:</p> <pre class="lang-dart prettyprint-override"><code> bool value = false; ListView.separated( physics: NeverScrollableScrollPhysics(), shrinkWrap: true, itemBuilder: (context, index) =&gt; Container( height: 100, width: double.infinity, decoration: BoxDecoration( border: Border.all( color: Colors.grey, width: 1), ), child: ListTile( title: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ Text(list[index].name), SizedBox(width: 10), CheckboxListTile( value: value, onChanged: (bool value) { this.value = value; }, ) ], ), ], ), ), ), separatorBuilder: (context, index) =&gt; SizedBox( height: 5, ), itemCount: 5, ) </code></pre>
[ { "answer_id": 74406042, "author": "Yeasin Sheikh", "author_id": 10157127, "author_profile": "https://Stackoverflow.com/users/10157127", "pm_score": 1, "selected": false, "text": "class ChWL extends StatefulWidget {\n const ChWL({super.key});\n\n @override\n State<ChWL> createState() => _ChWLState();\n}\n\nclass _ChWLState extends State<ChWL> {\n List<int> list = List.generate(33, (index) => index);\n List<int> selectedItem = [];\n @override\n Widget build(BuildContext context) {\n return Scaffold(\n body: ListView.builder(\n itemCount: list.length,\n itemBuilder: (context, index) => CheckboxListTile(\n title: Text(\"${list[index]}\"),\n value: selectedItem.contains(list[index]),\n onChanged: (value) {\n bool isChecked = selectedItem.contains(list[index]);\n\n if (isChecked) {\n selectedItem.remove(list[index]);\n } else {\n selectedItem.add(list[index]);\n }\n\n setState(() {});\n },\n ),\n ),\n );\n }\n}\n" }, { "answer_id": 74421429, "author": "杏彩总代理", "author_id": 16778289, "author_profile": "https://Stackoverflow.com/users/16778289", "pm_score": -1, "selected": false, "text": " Row(\n children: [\n Text(list[index].name),\n SizedBox(width: 10),\n CheckboxListTile(\n value: value,\n onChanged:\n (bool value) {\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20059879/" ]
74,405,971
<p>I have a small piece of react code which renders a list of names and their related information like age and email addresses. The code compiles fine but I see that the data is rendered twice on the page. Here is how I call the component:</p> <pre><code>const peopleData : Person[] = [{id:1,name:&quot;John&quot;,age:22},{id:2,name:&quot;Sasha&quot;,age:23}] function App() { return ( &lt;div className=&quot;App&quot;&gt; &lt;Basic {...peopleData}/&gt; &lt;/div&gt; ); } </code></pre> <p>And here is the component:</p> <pre><code>export interface Person { id : number; name : string; age : number; email? : string; } function Basic(input: Person[]) { let newPeopleData : Person[] = []; const [data,setData] = useState&lt;Person[]&gt;([]); useEffect(()=&gt;{ // Create a new data array let data : Person[] = Object.values(input); let size : number = Object.values(input).length; console.log(&quot;Data load start.&quot; + JSON.stringify(data)); for(let index=0;index&lt;size;index++) { let {id,name,email} = input[index] as Person; let newEmail = name + &quot;@gmail.com&quot; newPeopleData.push({id:id,name:name,email:newEmail} as Person) } setData(newPeopleData); console.log(&quot;Data loaded.&quot; + JSON.stringify(data)); return ()=&gt;{ console.log(&quot;Data deleted.&quot; + JSON.stringify(data)); } },[]); return ( &lt;div&gt; {data.map((unit)=&gt;{ return ( &lt;h1 key={unit.id}&gt;{unit.name},age:{unit.age},email:{unit.email}&lt;/h1&gt; ) })} &lt;/div&gt; ) } </code></pre> <p>I have two questions:</p> <ol> <li>Is the &quot;peopleData&quot; array passed correctly to the component? Or is there a better recommended way to do it?</li> <li>Why does the browser render the data twice when it is refreshed, although the &quot;unit.id&quot; is unique for each dataset.</li> </ol> <p>Thanks</p> <p>I tried to remove the key attribute inside the h1 tag thinking that React can assign its own unique IDs to each map object. But this did not work either.</p>
[ { "answer_id": 74406042, "author": "Yeasin Sheikh", "author_id": 10157127, "author_profile": "https://Stackoverflow.com/users/10157127", "pm_score": 1, "selected": false, "text": "class ChWL extends StatefulWidget {\n const ChWL({super.key});\n\n @override\n State<ChWL> createState() => _ChWLState();\n}\n\nclass _ChWLState extends State<ChWL> {\n List<int> list = List.generate(33, (index) => index);\n List<int> selectedItem = [];\n @override\n Widget build(BuildContext context) {\n return Scaffold(\n body: ListView.builder(\n itemCount: list.length,\n itemBuilder: (context, index) => CheckboxListTile(\n title: Text(\"${list[index]}\"),\n value: selectedItem.contains(list[index]),\n onChanged: (value) {\n bool isChecked = selectedItem.contains(list[index]);\n\n if (isChecked) {\n selectedItem.remove(list[index]);\n } else {\n selectedItem.add(list[index]);\n }\n\n setState(() {});\n },\n ),\n ),\n );\n }\n}\n" }, { "answer_id": 74421429, "author": "杏彩总代理", "author_id": 16778289, "author_profile": "https://Stackoverflow.com/users/16778289", "pm_score": -1, "selected": false, "text": " Row(\n children: [\n Text(list[index].name),\n SizedBox(width: 10),\n CheckboxListTile(\n value: value,\n onChanged:\n (bool value) {\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6365649/" ]
74,405,998
<p>I have dataframe&quot;:</p> <pre><code>a &lt;- data.frame(b_1=c(0.03,2.241,5.72,0.3566,1.344,2.5)) </code></pre> <p>and I want to use filter like</p> <pre><code>a &lt;- a %&gt;% filter(b_1 %in% 0.) </code></pre> <p>so I exclude row that value not in 0,... in b_1.</p> <p>But the code above was not working</p> <p>The result is 0.03 and 0.3566</p> <p>I have a big data, so it just an example dataframe that I want to filter. Thank you for helping</p>
[ { "answer_id": 74406027, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 3, "selected": true, "text": "%in%" }, { "answer_id": 74406062, "author": "Karthik S", "author_id": 10722752, "author_profile": "https://Stackoverflow.com/users/10722752", "pm_score": 0, "selected": false, "text": "a %>% filter(between(b_1, -1, 1))\n b_1\n1 0.0300\n2 0.3566\n \n" }, { "answer_id": 74407719, "author": "ThomasIsCoding", "author_id": 12158757, "author_profile": "https://Stackoverflow.com/users/12158757", "pm_score": 1, "selected": false, "text": "abs(b_1-0.5) < 0.5" }, { "answer_id": 74409120, "author": "SALAR", "author_id": 12517976, "author_profile": "https://Stackoverflow.com/users/12517976", "pm_score": 0, "selected": false, "text": "b<-dplyr::filter(a,b_1 >= 1)\nb\n b_1\n 2.241\n 5.720\n 1.344\n 2.500\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74405998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19912522/" ]
74,406,028
<p>I am using Copy Activity for migrating the Data from On-premises Database to the on-cloud Database. Here I am using Self-Hosted Integration Runtime for both on-premises and on-cloud databases.</p> <p>The Integration run-time is different for on-premises and on-cloud Databases.</p> <p>When I execute the pipeline, it shows that both the source and target need to be in the same self-hosted integration runtime.</p> <p>Is it possible to execute the pipeline having 2 self-hosted integration runtimes?</p> <p>If it is possible, Please let me know how we can execute the pipeline of having different 2 self-hosted integration runtimes.</p>
[ { "answer_id": 74406027, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 3, "selected": true, "text": "%in%" }, { "answer_id": 74406062, "author": "Karthik S", "author_id": 10722752, "author_profile": "https://Stackoverflow.com/users/10722752", "pm_score": 0, "selected": false, "text": "a %>% filter(between(b_1, -1, 1))\n b_1\n1 0.0300\n2 0.3566\n \n" }, { "answer_id": 74407719, "author": "ThomasIsCoding", "author_id": 12158757, "author_profile": "https://Stackoverflow.com/users/12158757", "pm_score": 1, "selected": false, "text": "abs(b_1-0.5) < 0.5" }, { "answer_id": 74409120, "author": "SALAR", "author_id": 12517976, "author_profile": "https://Stackoverflow.com/users/12517976", "pm_score": 0, "selected": false, "text": "b<-dplyr::filter(a,b_1 >= 1)\nb\n b_1\n 2.241\n 5.720\n 1.344\n 2.500\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74406028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15521809/" ]
74,406,034
<p>I have a data frame called <code>df</code> of which its value counts are the following:</p> <pre><code>df.Priority.value_counts() P3 39506 P2 3038 P4 1138 P1 1117 P5 252 Name: Priority, dtype: int64 </code></pre> <p>I am trying to create a balanced dataset called <code>df_balanced</code> from <code>df</code> by restricting the number of entries in the <code>P3</code> category to 5000. The expected output should look like this!</p> <pre><code>P3 5000 P2 3038 P4 1138 P1 1117 P5 252 Name: Priority, dtype: int64 </code></pre> <p>I tried the following code:</p> <pre class="lang-py prettyprint-override"><code>s0 = df.Priority[df.Priority.eq('P3')].sample(5000).index df_balanced = df.loc[s0.union(df)].reset_index(drop=True, inplace=True) # I am unsure how to exclude the entries of `P3` categories from `df`! </code></pre> <p>I used this as a reference: <a href="https://stackoverflow.com/q/57405126/10543310">Randomly selecting rows from a dataframe based on a column value</a> but the solution provided isn't optimal for more than 2 categories.</p>
[ { "answer_id": 74406027, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 3, "selected": true, "text": "%in%" }, { "answer_id": 74406062, "author": "Karthik S", "author_id": 10722752, "author_profile": "https://Stackoverflow.com/users/10722752", "pm_score": 0, "selected": false, "text": "a %>% filter(between(b_1, -1, 1))\n b_1\n1 0.0300\n2 0.3566\n \n" }, { "answer_id": 74407719, "author": "ThomasIsCoding", "author_id": 12158757, "author_profile": "https://Stackoverflow.com/users/12158757", "pm_score": 1, "selected": false, "text": "abs(b_1-0.5) < 0.5" }, { "answer_id": 74409120, "author": "SALAR", "author_id": 12517976, "author_profile": "https://Stackoverflow.com/users/12517976", "pm_score": 0, "selected": false, "text": "b<-dplyr::filter(a,b_1 >= 1)\nb\n b_1\n 2.241\n 5.720\n 1.344\n 2.500\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74406034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10543310/" ]
74,406,051
<p>I have</p> <pre><code> event b 0 buy 4 1 nan 2 sell 5 3 buy 3 4 nan 5 nan 6 nan 7 sell 9 </code></pre> <p>After each <code>buy</code> we have a <code>sell</code> at some unknown distance. I need to count how many times I had a profit.</p> <p>In this case, first deal earn 1 (5-4), and second deal earn 6 (9-3).</p> <p>I need to produce here 2 results <code>total wins=2</code>, and <code>total lost=0</code></p> <p>So I don't care how big is the profit/lost, only how many wins/loses</p>
[ { "answer_id": 74406027, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 3, "selected": true, "text": "%in%" }, { "answer_id": 74406062, "author": "Karthik S", "author_id": 10722752, "author_profile": "https://Stackoverflow.com/users/10722752", "pm_score": 0, "selected": false, "text": "a %>% filter(between(b_1, -1, 1))\n b_1\n1 0.0300\n2 0.3566\n \n" }, { "answer_id": 74407719, "author": "ThomasIsCoding", "author_id": 12158757, "author_profile": "https://Stackoverflow.com/users/12158757", "pm_score": 1, "selected": false, "text": "abs(b_1-0.5) < 0.5" }, { "answer_id": 74409120, "author": "SALAR", "author_id": 12517976, "author_profile": "https://Stackoverflow.com/users/12517976", "pm_score": 0, "selected": false, "text": "b<-dplyr::filter(a,b_1 >= 1)\nb\n b_1\n 2.241\n 5.720\n 1.344\n 2.500\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74406051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18813761/" ]
74,406,070
<p>I am running a simple query to get the max ID in a table: SELECT max(ID) FROM t WHERE m=345;</p> <p>Table (t) has 20 million records and 2000 distinct values for m. There is a primary key index on ID and an index on m. For some reason the explain plan shows an &quot;Index Scan Backward&quot; on the pk index rather than scanning the index on m. The query is taking over 10 seconds to complete.</p> <p>If I prevent the use of the pk index by changing the SQL ( SELECT max(ID+0) FROM t WHERE m=345; ) it takes just a few milliseconds to complete. We do a regular vacuum/analyze on the table. I'd prefer not to add &quot;+0&quot; to all of the queries to solve this issue. I could probably rewrite this SQL in other ways and get a better result but the original SQL is so simple the optimizer should be able to figure out the best plan.</p> <p>Table and Index DDL:</p> <pre class="lang-sql prettyprint-override"><code>CREATE TABLE IF NOT EXISTS t ( id bigint NOT NULL DEFAULT nextval('t_seq'::regclass), c integer, m integer, b integer DEFAULT '-1'::integer, p integer, CONSTRAINT t_pkey PRIMARY KEY (id) ) TABLESPACE pg_default; CREATE INDEX t_m_index ON t USING btree (m ASC NULLS LAST) TABLESPACE pg_default; </code></pre> <p>explain plan with workaround and original:</p> <pre><code>db=&gt; explain (analyze, buffers, format text) db-&gt; select MAX(id+0) FROM t WHERE m=345; QUERY PLAN ------------------------------------------------------------------------------------------------------------------------------------------------ Aggregate (cost=19418.26..19418.27 rows=1 width=8) (actual time=0.047..0.047 rows=1 loops=1) Buffers: shared hit=6 read=2 -&gt; Bitmap Heap Scan on t (cost=211.19..19368.82 rows=9888 width=8) (actual time=0.039..0.042 rows=2 loops=1) Recheck Cond: (m = 345) Heap Blocks: exact=2 Buffers: shared hit=6 read=2 -&gt; Bitmap Index Scan on t_m_index (cost=0.00..208.72 rows=9888 width=0) (actual time=0.033..0.034 rows=2 loops=1) Index Cond: (m = 345) Buffers: shared hit=4 read=2 Planning Time: 0.898 ms Execution Time: 0.094 ms (11 rows) db=&gt; explain (analyze, buffers, format text) db-&gt; select MAX(id) FROM t WHERE m=345; QUERY PLAN ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- Result (cost=464.31..464.32 rows=1 width=8) (actual time=21627.948..21627.950 rows=1 loops=1) Buffers: shared hit=10978859 read=124309 dirtied=1584 InitPlan 1 (returns $0) -&gt; Limit (cost=0.56..464.31 rows=1 width=8) (actual time=21627.945..21627.946 rows=1 loops=1) Buffers: shared hit=10978859 read=124309 dirtied=1584 -&gt; Index Scan Backward using t_pkey on t (cost=0.56..4524305.43 rows=9756 width=8) (actual time=21627.944..21627.944 rows=1 loops=1) Index Cond: (id IS NOT NULL) Filter: (m = 345) Rows Removed by Filter: 11745974 Buffers: shared hit=10978859 read=124309 dirtied=1584 Planning Time: 0.582 ms Execution Time: 21627.964 ms (12 rows) </code></pre>
[ { "answer_id": 74408074, "author": "user20042973", "author_id": 20042973, "author_profile": "https://Stackoverflow.com/users/20042973", "pm_score": 2, "selected": false, "text": "m" }, { "answer_id": 74409244, "author": "O. Jones", "author_id": 205608, "author_profile": "https://Stackoverflow.com/users/205608", "pm_score": 1, "selected": false, "text": "(m, id DESC)" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74406070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20479692/" ]
74,406,086
<p>I want to shutdown PC with C without using system() functiom</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; #include &lt;Windows.h&gt; int main(){ system(&quot;shutdown -s -t1&quot;); } </code></pre> <p>I'd like to find better way.</p>
[ { "answer_id": 74406169, "author": "Andreas Wenzel", "author_id": 12149471, "author_profile": "https://Stackoverflow.com/users/12149471", "pm_score": 3, "selected": true, "text": "ExitWindowsEx" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74406086", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19486032/" ]
74,406,142
<p>Here below is a simple model for a pet shop...</p> <p><strong>Pet Class</strong></p> <pre><code>@Getter @Setter @EqualsAndHashCode @Embeddable public abstract class Pet { @Column(name = &quot;id&quot;, nullable = false) private Long id; @Column(name = &quot;name&quot;, nullable = false) private String name; } </code></pre> <p><strong>Cat Class</strong></p> <pre><code>@Getter @Setter @EqualsAndHashCode @Embeddable public class Cat extends Pet { @Column(name = &quot;call&quot;) private String call; } </code></pre> <p><strong>PetShop Class</strong></p> <pre><code>@Entity @Table(name = &quot;pet_shop&quot;) @Getter @Setter @NoArgsConstructor @AllArgsConstructor public class PetShop { @Column(name = &quot;id&quot;, nullable = false) private Long id; @ElementCollection @CollectionTable( name = &quot;pets&quot;, joinColumns = @JoinColumn(name = &quot;pet_id&quot;, referencedColumnName = &quot;id&quot;)) private List&lt;Pet&gt; pets= new ArrayList&lt;&gt;(); } </code></pre> <p><strong>PetShopRepository Interface</strong></p> <pre><code>public interface PetShopRepository extends JpaRepository&lt;PetShop, Long&gt; {} </code></pre> <p>... and here is how to create a <code>PetShop</code> with at least one <code>Pet</code>:</p> <pre><code>final Pet pet = new Cat(); pet.setName(&quot;cat&quot;); pet.setCall(&quot;meow&quot;); final PetShop petShop = new PetShop(); petShop.getPets().add(pet); petShopRepositiry.save(petShop); </code></pre> <p>So far so good... but when I try to retrieve the <code>PetShop</code>...</p> <pre><code>final PetShop petShop = petShopRepository.findById(shopId) .orElseThrow(() -&gt; new ShopNotFoundException(shopId)); </code></pre> <p>I always get the following error:</p> <pre><code>org.springframework.orm.jpa.JpaSystemException: Cannot instantiate abstract class or interface: : com.mytest.persistence.model.Pet; nested exception is org.hibernate.InstantiationException: Cannot instantiate abstract class or interface: : com.myTest.persistence.model.Pet </code></pre> <p>Of course the message is clear... but I'm wondering whether it is possible to have a collection of pets, each potentially referencing a different specialized class?</p>
[ { "answer_id": 74427513, "author": "Avinash gupta", "author_id": 13614048, "author_profile": "https://Stackoverflow.com/users/13614048", "pm_score": 0, "selected": false, "text": "@OneToMany(cascade = CascadeType.ALL,fetch = FetchType.Lazy, mappedBy = \"pets\")\n@JsonIgnore\nprivate List<Pet> pets= new ArrayList<>();\n" }, { "answer_id": 74428728, "author": "j3d", "author_id": 278659, "author_profile": "https://Stackoverflow.com/users/278659", "pm_score": 2, "selected": true, "text": "Pet" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74406142", "https://Stackoverflow.com", "https://Stackoverflow.com/users/278659/" ]
74,406,157
<p>I have to sort columns in single row dataframe by descending order.</p> <p>dataframe looks like:</p> <pre><code> store_1 store_2 store_3 0 11 54 28 </code></pre> <p>result should be like:</p> <pre><code> store_2 store_3 store_1 0 54 28 11 </code></pre> <p>dataframe has more than sixty columns.</p>
[ { "answer_id": 74427513, "author": "Avinash gupta", "author_id": 13614048, "author_profile": "https://Stackoverflow.com/users/13614048", "pm_score": 0, "selected": false, "text": "@OneToMany(cascade = CascadeType.ALL,fetch = FetchType.Lazy, mappedBy = \"pets\")\n@JsonIgnore\nprivate List<Pet> pets= new ArrayList<>();\n" }, { "answer_id": 74428728, "author": "j3d", "author_id": 278659, "author_profile": "https://Stackoverflow.com/users/278659", "pm_score": 2, "selected": true, "text": "Pet" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74406157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17151635/" ]
74,406,163
<p>I'm new to HTML and javascript so need assistance with some of the basics....</p> <p>I have a javascript file with an array of elements:</p> <pre><code> export let options = [ { att1: &quot;opt1&quot;, att2: &quot;some val 1&quot;, att3: 1, att4: 5, }, { att1: &quot;opt2&quot;, att2: &quot;some val 2&quot;, att3: 2, att4: 2, }, { att1: &quot;opt3&quot;, att2: &quot;some val 3&quot;, att3: 33, att4: 10, } ] </code></pre> <p>I want to create an HTML table (<strong>using the 'table' tag</strong>) with this array's content which will have the following format:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th></th> <th>Option 1</th> <th>Option 2</th> <th>Option 3</th> </tr> </thead> <tbody> <tr> <td>att1</td> <td>opt1</td> <td>opt2</td> <td>opt3</td> </tr> <tr> <td>att2</td> <td>some val 1</td> <td>some val 2</td> <td>some val 3</td> </tr> <tr> <td>att3</td> <td>1</td> <td>2</td> <td>33</td> </tr> <tr> <td>att4</td> <td>5</td> <td>2</td> <td>10</td> </tr> </tbody> </table> </div> <p>How can I do it? I'm not sure wether it's possible or not, but I prefer the table's size/headers/attributes' names to be taken from the array itself and not to define them manually. In addition, I cannot touch the file with the array, i.e. I can only import it to another javascript file or src it in the HTML.</p> <p>Thanks in advance, a confused newbie </p> <p>*I've had some trial and error, but I'm not quite sure what I've already tried and what exactly happened as I am still not familiar and don't understand enough these languages and concepts</p>
[ { "answer_id": 74406264, "author": "Thiago Zazirskas", "author_id": 15187365, "author_profile": "https://Stackoverflow.com/users/15187365", "pm_score": 0, "selected": false, "text": "Document.createElement()" }, { "answer_id": 74406313, "author": "babak abdzadeh", "author_id": 11498450, "author_profile": "https://Stackoverflow.com/users/11498450", "pm_score": 1, "selected": false, "text": "const table = document.createElement(\"table\");\nconst rowOne = document.createElement(\"tr\");\nconst cellOne = document.createElement(\"td\");\nconst dataForCellOne = options.att1;\ncellOne.appendChild(data);\n" }, { "answer_id": 74406331, "author": "tacoshy", "author_id": 14072420, "author_profile": "https://Stackoverflow.com/users/14072420", "pm_score": 1, "selected": false, "text": "insertAdjacentHTML" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74406163", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13706082/" ]
74,406,193
<p>I am trying to find an elegant way to inject an Interface into the <a href="https://github.com/microsoft/tsyringe" rel="nofollow noreferrer">tsyringe</a> container based on a given value. (string/enum/Symbol)</p> <p>This is how I would do it with a <code>switch..case</code> clause:</p> <pre><code>interface IColor{ someMethod():void; readonly someInfo:any; } class Blue implements IColor{ constructor() { } someMethod() { console.log('I am blue'); } } class Red implements IColor{ constructor() { } someMethod() { console.log('I am red'); } } @injectable() class SurfaceService{ constructor(@inject('IColor')readonly color:IColor) { } } // main import {container} from &quot;tsyringe&quot;; const mainFunction = (someData:{colorinfo:string}) =&gt;{ switch (someData.colorinfo){ case 'RED': container.register(&quot;IColor&quot;, {useClass: Red}); break; case 'Blue': container.register(&quot;IColor&quot;, {useClass: Blue}); break; } const service = container.resolve(SurfaceService); } </code></pre> <p>The problem with this approach is, that it is not very elegant and it requires to import all possible implementation even though, only one is needed at runtime.</p> <p>Is there a better solution for this?</p>
[ { "answer_id": 74406264, "author": "Thiago Zazirskas", "author_id": 15187365, "author_profile": "https://Stackoverflow.com/users/15187365", "pm_score": 0, "selected": false, "text": "Document.createElement()" }, { "answer_id": 74406313, "author": "babak abdzadeh", "author_id": 11498450, "author_profile": "https://Stackoverflow.com/users/11498450", "pm_score": 1, "selected": false, "text": "const table = document.createElement(\"table\");\nconst rowOne = document.createElement(\"tr\");\nconst cellOne = document.createElement(\"td\");\nconst dataForCellOne = options.att1;\ncellOne.appendChild(data);\n" }, { "answer_id": 74406331, "author": "tacoshy", "author_id": 14072420, "author_profile": "https://Stackoverflow.com/users/14072420", "pm_score": 1, "selected": false, "text": "insertAdjacentHTML" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74406193", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3253917/" ]
74,406,194
<p>I am trying to add items inside an empty array. I am using Dio package to send post request. All others codes are working fine. But Here I am stucj with this issue. I took an empty array. Then I tried setState function to add item to the empty list. I am printing the list every time it got pressed. But I am getting empty array.</p> <p>Actually I am trying to add products into the empty array and send post request.</p> <p>Here is my code:</p> <pre><code>Consumer&lt;ProductController&gt;( builder: ((context, value, child) { // log('${value.products[0].results?.length.toString()}'); if (value.products.isNotEmpty) { return Container( height: maxHeight * 0.3, child: ListView.builder( itemCount: value.products[0].results!.length, itemBuilder: (context, index) { return Card( child: ListTile( title: Text(value .products[0].results![index].name!), leading: IconButton( icon: const Icon(Icons.add), onPressed: () { setState(() { _lists.add(value.products[0] .results![index].id); _lists = productIds; print(&quot;LISTS +&gt;&gt;&gt;&gt; $_lists&quot;); }); }, ), trailing: const Icon(Icons.done), ), ); }, )); } else { return const CircularProgressIndicator(); } }), ), </code></pre> <p>Here is my Model:</p> <pre><code>class DisplayModel { String? status; List&lt;Results&gt;? results; DisplayModel({this.status, this.results}); DisplayModel.fromJson(Map&lt;String, dynamic&gt; json) { status = json['status']; if (json['results'] != null) { results = &lt;Results&gt;[]; json['results'].forEach((v) { results!.add(new Results.fromJson(v)); }); } } Map&lt;String, dynamic&gt; toJson() { final Map&lt;String, dynamic&gt; data = new Map&lt;String, dynamic&gt;(); data['status'] = this.status; if (this.results != null) { data['results'] = this.results!.map((v) =&gt; v.toJson()).toList(); } return data; } } class Results { int? id; List&lt;Products&gt;? products; List&lt;Catalogs&gt;? catalogs; String? name; Null? description; String? category; String? templateName; Null? bannerText; Results( {this.id, this.products, this.catalogs, this.name, this.description, this.category, this.templateName, this.bannerText}); Results.fromJson(Map&lt;String, dynamic&gt; json) { id = json['id']; if (json['products'] != null) { products = &lt;Products&gt;[]; json['products'].forEach((v) { products!.add(new Products.fromJson(v)); }); } if (json['catalogs'] != null) { catalogs = &lt;Catalogs&gt;[]; json['catalogs'].forEach((v) { catalogs!.add(new Catalogs.fromJson(v)); }); } name = json['name']; description = json['description']; category = json['category']; templateName = json['template_name']; bannerText = json['banner_text']; } Map&lt;String, dynamic&gt; toJson() { final Map&lt;String, dynamic&gt; data = new Map&lt;String, dynamic&gt;(); data['id'] = this.id; if (this.products != null) { data['products'] = this.products!.map((v) =&gt; v.toJson()).toList(); } if (this.catalogs != null) { data['catalogs'] = this.catalogs!.map((v) =&gt; v.toJson()).toList(); } data['name'] = this.name; data['description'] = this.description; data['category'] = this.category; data['template_name'] = this.templateName; data['banner_text'] = this.bannerText; return data; } } class Products { int? id; String? name; Null? unit; String? price; Null? salePrice; String? image; Null? category; Null? badge; Products( {this.id, this.name, this.unit, this.price, this.salePrice, this.image, this.category, this.badge}); Products.fromJson(Map&lt;String, dynamic&gt; json) { id = json['id']; name = json['name']; unit = json['unit']; price = json['price']; salePrice = json['sale_price']; image = json['image']; category = json['category']; badge = json['badge']; } Map&lt;String, dynamic&gt; toJson() { final Map&lt;String, dynamic&gt; data = new Map&lt;String, dynamic&gt;(); data['id'] = this.id; data['name'] = this.name; data['unit'] = this.unit; data['price'] = this.price; data['sale_price'] = this.salePrice; data['image'] = this.image; data['category'] = this.category; data['badge'] = this.badge; return data; } } class Catalogs { int? id; Null? name; Null? unit; Null? price; Null? salePrice; String? image; Null? video; Null? badge; Catalogs( {this.id, this.name, this.unit, this.price, this.salePrice, this.image, this.video, this.badge}); Catalogs.fromJson(Map&lt;String, dynamic&gt; json) { id = json['id']; name = json['name']; unit = json['unit']; price = json['price']; salePrice = json['sale_price']; image = json['image']; video = json['video']; badge = json['badge']; } Map&lt;String, dynamic&gt; toJson() { final Map&lt;String, dynamic&gt; data = new Map&lt;String, dynamic&gt;(); data['id'] = this.id; data['name'] = this.name; data['unit'] = this.unit; data['price'] = this.price; data['sale_price'] = this.salePrice; data['image'] = this.image; data['video'] = this.video; data['badge'] = this.badge; return data; } } </code></pre> <p>Here is my Post controller:</p> <pre><code>Future&lt;bool&gt; addDisplay(String name, String category, String templateName, File catalogsImage, File catalogsVideo, List&lt;Products&gt; productIds) async { try { // String fileName = catalogsImage.path.split('/').last; var token = localStorage.getItem('access'); Dio dio = Dio(); FormData formData = FormData.fromMap({ &quot;name&quot;: name, &quot;category&quot;: category, &quot;template_name&quot;: templateName, &quot;catalogs[0]image&quot;: await MultipartFile.fromFile(catalogsImage.path), &quot;catalogs[0]video&quot;: await MultipartFile.fromFile(catalogsVideo.path), &quot;products&quot;: productIds }); var response = await dio.post(url, data: formData, options: Options(headers: {&quot;Authorization&quot;: &quot;Bearer $token&quot;})); if (response.statusCode == 200) { notifyListeners(); return true; } else { return false; } } on DioError catch (e) { print(e); return false; } } </code></pre> <p>here is the full code of front end:</p> <pre><code>// ignore_for_file: sized_box_for_whitespace import 'dart:developer'; import 'package:digitaldisplay/controllers/DisplayController.dart'; import 'package:digitaldisplay/controllers/ProductController.dart'; import 'package:digitaldisplay/models/DisplayModel.dart'; import 'package:digitaldisplay/views/widgets/Display.dart'; import 'package:flutter/material.dart'; import 'package:image_picker/image_picker.dart'; import 'package:provider/provider.dart'; import 'dart:io'; class CreateDisplayMobile extends StatefulWidget { const CreateDisplayMobile({super.key}); @override State&lt;CreateDisplayMobile&gt; createState() =&gt; _CreateDisplayMobileState(); } class _CreateDisplayMobileState extends State&lt;CreateDisplayMobile&gt; { final ImagePicker picker = ImagePicker(); String _name = &quot;&quot;; String _category = &quot;&quot;; String _templateName = &quot;&quot;; File? catalogImage; File? _catalogVideo; List&lt;Products&gt; productIds = []; final _form = GlobalKey&lt;FormState&gt;(); void _addDisplay() async { var isValid = _form.currentState!.validate(); if (!isValid) { return; } _form.currentState!.save(); bool create = await Provider.of&lt;DisplayController&gt;(context, listen: false) .addDisplay(_name, _category, _templateName, catalogImage!, _catalogVideo!, productIds); if (create) { print(create); showDialog( context: context, builder: (context) { return AlertDialog( title: Text(&quot;Created&quot;), actions: [ ElevatedButton( child: const Text(&quot;Return&quot;), onPressed: () { Navigator.of(context).pop(); }, ), ], ); }); } else { showDialog( context: context, builder: (context) { return AlertDialog( title: Text(&quot;Failed to create display!&quot;), actions: [ ElevatedButton( child: const Text(&quot;Return&quot;), onPressed: () { Navigator.of(context).pop(); }, ), ], ); }); } } @override void initState() { Provider.of&lt;DisplayController&gt;(context, listen: false).getDisplays(); Provider.of&lt;ProductController&gt;(context, listen: false).getProducts(); super.initState(); } @override Widget build(BuildContext context) { List _lists = []; final ButtonStyle buttonStyle1 = ElevatedButton.styleFrom( backgroundColor: const Color(0xFFc3232a), shape: const StadiumBorder(), minimumSize: const Size(100, 50), ); final ButtonStyle buttonStyle2 = ElevatedButton.styleFrom( backgroundColor: const Color(0xFFc3232a), shape: const StadiumBorder(), minimumSize: const Size(100, 50), ); final ButtonStyle buttonStyle3 = ElevatedButton.styleFrom( backgroundColor: const Color(0xFF111111), shape: const StadiumBorder(), minimumSize: const Size(100, 50), ); double maxHeight = MediaQuery.of(context).size.height; double maxWidth = MediaQuery.of(context).size.width; return Scaffold( // backgroundColor: Colors.deepPurple[200], appBar: AppBar( elevation: 0, backgroundColor: const Color(0xFF111111), title: const Text( &quot;Digital Display Generator&quot;, textAlign: TextAlign.end, ), ), body: SingleChildScrollView( child: Column(children: [ const SizedBox( height: 10, ), Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Consumer&lt;DisplayController&gt;( builder: (context, value, child) { log('${value.displays[0].results?.length.toString()}'); return Container( height: maxHeight * 0.6, width: maxWidth * 0.9, child: GridView.count( crossAxisSpacing: 5, crossAxisCount: 1, scrollDirection: Axis.horizontal, children: List.generate( value.displays.isNotEmpty ? value.displays[0].results!.length : 0, (i) { return Padding( padding: const EdgeInsets.all(8.0), child: DisplayCard( displayName: value.displays[0].results![i].name!, displayImage: value.displays[0].results![i] .catalogs![0].image!, id: value.displays[0].results![i].id!), ); }), ), ); }, ), ], ), Form( key: _form, child: Center( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const Padding( padding: EdgeInsets.all(10.0), child: Text( &quot;Enter Name&quot;, )), Padding( padding: EdgeInsets.all(10), child: TextFormField( validator: (v) { if (v!.isEmpty) { return &quot;Please Enter a valid name&quot;; } else { return null; } }, onSaved: (value) { _name = value as String; }, autofocus: false, style: const TextStyle( fontSize: 15.0, color: Colors.black), decoration: InputDecoration( hintText: 'Name', filled: true, fillColor: Colors.white, contentPadding: const EdgeInsets.only( left: 14.0, bottom: 6.0, top: 8.0), focusedBorder: OutlineInputBorder( borderSide: const BorderSide( color: Color.fromARGB(255, 73, 57, 55)), borderRadius: BorderRadius.circular(0.0), ), enabledBorder: UnderlineInputBorder( borderSide: const BorderSide(color: Colors.grey), borderRadius: BorderRadius.circular(0.0), ), ), ), ), const Padding( padding: EdgeInsets.all(10.0), child: Text( &quot;Enter Template Name&quot;, )), Padding( padding: EdgeInsets.all(10), child: TextFormField( validator: (v) { if (v!.isEmpty) { return &quot;Please Enter a valid name&quot;; } else { return null; } }, onSaved: (value) { _templateName = value as String; }, autofocus: false, style: const TextStyle( fontSize: 15.0, color: Colors.black), decoration: InputDecoration( hintText: 'Template Name', filled: true, fillColor: Colors.white, contentPadding: const EdgeInsets.only( left: 14.0, bottom: 6.0, top: 8.0), focusedBorder: OutlineInputBorder( borderSide: const BorderSide( color: Color.fromARGB(255, 73, 57, 55)), borderRadius: BorderRadius.circular(0.0), ), enabledBorder: UnderlineInputBorder( borderSide: const BorderSide(color: Colors.grey), borderRadius: BorderRadius.circular(0.0), ), ), ), ), const Padding( padding: EdgeInsets.all(10.0), child: Text( &quot;Enter Category Name&quot;, )), Padding( padding: EdgeInsets.all(10), child: TextFormField( validator: (v) { if (v!.isEmpty) { return &quot;Please Enter a valid name&quot;; } else { return null; } }, onSaved: (value) { _category = value as String; }, autofocus: false, style: const TextStyle( fontSize: 15.0, color: Colors.black), decoration: InputDecoration( hintText: 'Category Name', filled: true, fillColor: Colors.white, contentPadding: const EdgeInsets.only( left: 14.0, bottom: 6.0, top: 8.0), focusedBorder: OutlineInputBorder( borderSide: const BorderSide( color: Color.fromARGB(255, 73, 57, 55)), borderRadius: BorderRadius.circular(0.0), ), enabledBorder: UnderlineInputBorder( borderSide: const BorderSide(color: Colors.grey), borderRadius: BorderRadius.circular(0.0), ), ), ), ), const Padding( padding: EdgeInsets.all(10.0), child: Text( &quot;Select Product&quot;, )), Padding( padding: const EdgeInsets.all(10.0), child: Consumer&lt;ProductController&gt;( builder: ((context, value, child) { // log('${value.products[0].results?.length.toString()}'); if (value.products.isNotEmpty) { return Container( height: maxHeight * 0.3, child: ListView.builder( itemCount: value.products[0].results!.length, itemBuilder: (context, index) { return Card( child: ListTile( title: Text(value .products[0].results![index].name!), leading: IconButton( icon: const Icon(Icons.add), onPressed: () { setState(() { _lists.add(value.products[0] .results![index].id); // _lists = productIds; print(&quot;LISTS +&gt;&gt;&gt;&gt; $productIds&quot;); }); }, ), trailing: const Icon(Icons.done), ), ); }, )); } else { return const CircularProgressIndicator(); } }), ), ), Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Padding( padding: const EdgeInsets.all(8.0), child: ElevatedButton( onPressed: () { _getImageFromGallery(); // displayController.createDisplay( // &quot;name&quot;, &quot;category&quot;, &quot;templateName&quot;, &quot;1&quot;); }, child: Text(&quot;Add Image&quot;), style: buttonStyle1, ), ), Padding( padding: const EdgeInsets.all(8.0), child: ElevatedButton( onPressed: () { _getVideoFromGallery(); // displayController.createDisplay( // &quot;name&quot;, &quot;category&quot;, &quot;templateName&quot;, &quot;1&quot;); }, child: Text(&quot;Add Video&quot;), style: buttonStyle1, ), ), Padding( padding: const EdgeInsets.all(8.0), child: ElevatedButton( onPressed: () { _addDisplay(); }, child: Text(&quot;Add Display&quot;), style: buttonStyle2, ), ), ], ), ], ), ), ), ]), )); } void _getImageFromGallery() async { XFile? pickedFile = await picker.pickImage(source: ImageSource.gallery); if (pickedFile != null) { setState(() { catalogImage = File(pickedFile.path); }); } } void _getVideoFromGallery() async { XFile? filepick = await picker.pickImage(source: ImageSource.gallery); if (filepick != null) { setState(() { _catalogVideo = File(filepick.path); }); } } } </code></pre> <p>So after adding to the empty list I want to save it. How can I acquire that? Is there any solution for me?</p>
[ { "answer_id": 74407362, "author": "Олександр Бабіч", "author_id": 8653915, "author_profile": "https://Stackoverflow.com/users/8653915", "pm_score": 0, "selected": false, "text": "List _lists = [];" }, { "answer_id": 74411156, "author": "OMi Shah", "author_id": 5882307, "author_profile": "https://Stackoverflow.com/users/5882307", "pm_score": 3, "selected": true, "text": "_lists" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74406194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14427714/" ]
74,406,201
<p><em>Hello guys, sorry for my English it's my second language</em>. So i have a Redux state which looks something like this:</p> <pre><code>const initialState = { user: null, isLoading: false, }; </code></pre> <p>And each time i load main screen(I'm using React Native), i take a user from local storage and put it in the state:</p> <pre><code>useEffect(() =&gt; { dispatch(getMe()); dispatch(getCategories()); }, []); </code></pre> <p>With a getMe function i take a user from local storage and with a getCategories one i make request to the api and get data. But if i would take a state value when getting categories, i get a null(default value):</p> <pre><code>// Get categories export const getCategories = createAsyncThunk( &quot;categories/get&quot;, async (_, thunkAPI) =&gt; { try { console.log(thunkAPI.getState().user.user); // The thunkAPI.getState().user.user value is null return await categoryService.getCategories(); } catch (error) { thunkAPI.rejectWithValue(error); } } ); </code></pre> <p>I was just interested what would happen if i timeout getCategories function:</p> <pre><code>useEffect(() =&gt; { dispatch(getMe()); setTimeout(() =&gt; dispatch(getCategories()), 1); }, []); </code></pre> <p>And it works. But i don't really think it's a good way to do that, So how do i fix this &quot;properly&quot;?</p> <p>Previously thanks!!!</p>
[ { "answer_id": 74407362, "author": "Олександр Бабіч", "author_id": 8653915, "author_profile": "https://Stackoverflow.com/users/8653915", "pm_score": 0, "selected": false, "text": "List _lists = [];" }, { "answer_id": 74411156, "author": "OMi Shah", "author_id": 5882307, "author_profile": "https://Stackoverflow.com/users/5882307", "pm_score": 3, "selected": true, "text": "_lists" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74406201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19840456/" ]
74,406,205
<p>I have one assigment.</p> <p><a href="https://i.stack.imgur.com/rDVto.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rDVto.png" alt="assigment" /></a></p> <p>Question: Do someone know an easy solution? I found no way to solve the question.</p> <pre><code>Try it: DROP TABLE IF EXISTS #Employees; GO CREATE TABLE #Employees ( EmployeeID INTEGER, License VARCHAR(100), PRIMARY KEY (EmployeeID, License) ); GO INSERT INTO #Employees VALUES (1001,'Class A'), (1001,'Class B'), (1001,'Class C'), (2002,'Class A'), (2002,'Class B'), (2002,'Class C'), (3003,'Class A'), (3003,'Class D'); GO </code></pre> <p>My try but it does not work. Do someone have good idea?</p> <pre><code>SELECT * FROM #Employees as e1 LEFT JOIN (SELECT * FROM #Employees WHERE 1 = 1 AND EmployeeID = 2002 ) as e2 ON e1.License = e2.License LEFT JOIN (SELECT * FROM #Employees WHERE 1 = 1 AND EmployeeID = 3003 ) as e3 ON e1.License = e3.License WHERE 1 = 1 AND e1.EmployeeID = 1001 </code></pre>
[ { "answer_id": 74406374, "author": "ahmed", "author_id": 12705912, "author_profile": "https://Stackoverflow.com/users/12705912", "pm_score": 2, "selected": true, "text": "STRING_AGG" }, { "answer_id": 74406543, "author": "mikey22022", "author_id": 20169539, "author_profile": "https://Stackoverflow.com/users/20169539", "pm_score": 0, "selected": false, "text": " with cte as (\n\n SELECT EmployeeID,\n STRING_AGG(License, ',') \n AS lic_agg\n FROM Employees\n GROUP BY EmployeeID ) \n\n SELECT STRING_AGG(EmployeeID, ',') as Matches\n FROM cte\n GROUP BY lic_agg\n Having COUNT(*) > 1\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74406205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20169539/" ]
74,406,212
<pre><code>const exampleArray = [ &quot;Can't predict now&quot;, &quot;Concentrate and ask again&quot;, &quot;Don't count on it&quot;, &quot;My reply is no&quot;, &quot;My sources say no&quot;, &quot;Outlook not so good&quot;, &quot;Very doubtful&quot; ] for (i = 0; i &lt; responses.length; i++) { if (responses[i].includes(&quot;no&quot;)) { alert(`hit at ${responses[i]}`) } } </code></pre> <p>I'm trying to write a program that will search through an array and find any instances of &quot;no&quot; in the strings in the array. The issue is I'm also detecting instances of &quot;not&quot; or &quot;now&quot; when all I want is instances of &quot;no&quot; specifically.</p>
[ { "answer_id": 74406374, "author": "ahmed", "author_id": 12705912, "author_profile": "https://Stackoverflow.com/users/12705912", "pm_score": 2, "selected": true, "text": "STRING_AGG" }, { "answer_id": 74406543, "author": "mikey22022", "author_id": 20169539, "author_profile": "https://Stackoverflow.com/users/20169539", "pm_score": 0, "selected": false, "text": " with cte as (\n\n SELECT EmployeeID,\n STRING_AGG(License, ',') \n AS lic_agg\n FROM Employees\n GROUP BY EmployeeID ) \n\n SELECT STRING_AGG(EmployeeID, ',') as Matches\n FROM cte\n GROUP BY lic_agg\n Having COUNT(*) > 1\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74406212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
74,406,222
<p>I'm trying to import a self made package into a Java project. I got it to work once with some test class. So, when I tried to change it to an official, approved class name, the compiling stopped working. I can't explain why it worked, nor why the changes made it stop working.</p> <p>This is super annoying. So, I've been digging for a few days.</p> <p>I've search over a dozen posts here, plus many other sites, and cannot find an explanation of how this is supposed to be structured.</p> <p>Finally I gutted everything and put together this example that should work according to everything I've searched, but it doesn't. It is a stripped down version of something that should import my own package and call a function. Minuscule code showing what I am trying to do, and what is failing.</p> <p>In this minuscule example, I am building a package, as &quot;com.company.functions&quot; with a MyFunctions.java. All of one function inside to demonstrate it.</p> <p>I do not have a classpath set up in my environment. Only a path to the JDK binaries. I do that so I can keep control and understanding at the command line level.</p> <p>The &quot;package&quot; is located in folder JavaPackage. The folders are:</p> <pre><code>JavaPackage\ com\ company\ functions\ (the MyFunctions.java is here) classes\ </code></pre> <p>I compile it fine.</p> <pre><code>C:\JavaPackages\JavaPackage&gt;javac -d classes -classpath classes com\company\functions\*.java </code></pre> <p>I create the JAR file fine</p> <pre><code>C:\JavaPackages\JavaPackage&gt;jar cvf mypackage.jar classes\com\company\functions\ added manifest adding: classes/com/company/functions/(in = 0) (out= 0)(stored 0%) adding: classes/com/company/functions/MyFunctions.class(in = 285) (out= 220)(deflated 22%) </code></pre> <p>I look in the JAR with 7-Zip,and everything looks fine. (I compared this 7-Zip autopsy to the package that was working, as mentioned at the beginning of this post, and the class names all line up correctly, from what I can understand. Everything looks correct)</p> <p>Now, I am creating a test program. Called, for lack of a better name, Java_Test.</p> <pre><code>Java_Test\ TestProgram\ (source files here) classes\ </code></pre> <p>I move my jar file to Java_Test\classes</p> <pre><code>C:\JavaPackages\Java_Test&gt;dir classes 11/11/2022 10:16 AM 1,325 mypackage.jar </code></pre> <p>I have two files in Java_Test\TestProgram: start.java and Test.java. Start is just the location of the static main, and it invokes the Test class. That's not any issue. It's the following compile failure.</p> <p>I attempt to compile with</p> <pre><code>C:\JavaPackages\Java_Test&gt;javac -d classes -cp classes TestProgram\*.java </code></pre> <p>Which should specify that the output *.class files go into the folder &quot;classes&quot;, and that the class path to import things is in the (same) folder &quot;classes&quot;</p> <p>I get the following error</p> <pre><code>TestProgram\Test.java:3: error: package com.company.functions does not exist import com.company.functions.*; ^ </code></pre> <p>Well, it does exist. I can see it right there in the classes folder.</p> <p>Maybe it's got something to do with the JAR name. Who knows? I can't find a good explanation of how this is supposed to work, so I even rebuilt the JAR file using the main name of the class: &quot;functions&quot;</p> <p>So, now I have two JAR files of different names, but their contents are exactly the same. I figure the compiler should find one of them. The one it needs.</p> <pre><code>C:\JavaPackages\Java_Test&gt;dir classes 11/11/2022 10:28 AM 1,325 functions.jar 11/11/2022 10:16 AM 1,325 mypackage.jar </code></pre> <p>However, the Java compiler still refuses to see it.</p> <p>Can some <em>please</em> explain what is going on? This is frustrating, and making no sense. Since I come from the C/C++ world, linking to a lib is easy. Yet this package concept in Java is a confusing nightmare.</p> <p>The full source files are below, not that it makes any difference, because it's the package that can't be found.</p> <p>This is what is in MyFunctions.java for the package file</p> <pre><code>package com.company.functions; public class MyFunctions { public int SomthingToDo() { int x = 1; return 0; } } </code></pre> <p>Test program that should call the function from the package. Except fails at line 2</p> <pre><code>package TestProgram; import com.company.functions.*; import java.io.*; public class Test { public void Run() { m_functions = new MyFunctions(); m_functions.SomthingToDo(); System.out.println(&quot;Exiting&quot;); } private MyFunctions m_functions; } </code></pre> <p>For your reading enjoyment, this is start.java, which is not significant to my issue:</p> <pre><code>package TestProgram; public class start { public static void main(String args[]) { m_test = new Test(); m_test.RunScanner(); } static private Test m_test; } </code></pre>
[ { "answer_id": 74407751, "author": "Progman", "author_id": 286934, "author_profile": "https://Stackoverflow.com/users/286934", "pm_score": 2, "selected": false, "text": "C:\\JavaPackages\\JavaPackage>jar cvf mypackage.jar classes\\com\\company\\functions\\\nadded manifest\nadding: classes/com/company/functions/(in = 0) (out= 0)(stored 0%)\nadding: classes/com/company/functions/MyFunctions.class(in = 285) (out= 220)(deflated 22%)\n" }, { "answer_id": 74409247, "author": "g00se", "author_id": 16376827, "author_profile": "https://Stackoverflow.com/users/16376827", "pm_score": 1, "selected": false, "text": "goose@t410:/tmp/src$ find\n.\n./start.java\n./MyFunctions.java\n./classes\n./Test.java\n===========================================================================================\ngoose@t410:/tmp/src$ cat start.java \npackage testprogram;\n\npublic class start {\n public static void main(String args[]) {\n m_test = new Test();\n //m_test.RunScanner();\n m_test.Run();\n }\n\n static private Test m_test;\n}\n\n===========================================================================================\ngoose@t410:/tmp/src$ head -n 1 *.java\n==> MyFunctions.java <==\npackage com.company.functions;\n\n==> start.java <==\npackage testprogram;\n\n==> Test.java <==\npackage testprogram;\n===========================================================================================\ngoose@t410:/tmp/src$ javac -d classes *.java\n===========================================================================================\ngoose@t410:/tmp/src$ find\n.\n./start.java\n./MyFunctions.java\n./classes\n./classes/testprogram\n./classes/testprogram/Test.class\n./classes/testprogram/start.class\n./classes/com\n./classes/com/company\n./classes/com/company/functions\n./classes/com/company/functions/MyFunctions.class\n./Test.java\n===========================================================================================\ngoose@t410:/tmp/src$ jar cvf functions.jar -C classes com/company/functions\nadded manifest\nadding: com/company/functions/(in = 0) (out= 0)(stored 0%)\nadding: com/company/functions/MyFunctions.class(in = 285) (out= 219)(deflated 23%)\ngoose@t410:/tmp/src$ \n===========================================================================================\ngoose@t410:/tmp/src$ jar cvfe mypackage.jar testprogram.start -C classes testprogram\nadded manifest\nadding: testprogram/(in = 0) (out= 0)(stored 0%)\nadding: testprogram/Test.class(in = 567) (out= 380)(deflated 32%)\nadding: testprogram/start.class(in = 382) (out= 273)(deflated 28%)\n===========================================================================================\ngoose@t410:/tmp/src$ java -cp mypackage.jar:functions.jar testprogram.start\nExiting\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74406222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2832155/" ]
74,406,225
<p>In a master i have a global variable called &quot;READ_ONLY_ON_STATES&quot; which is a dictionary</p> <p><code>READ_ONLY_ON_STATES = {&quot;on_validation&quot;:[(&quot;readonly&quot;, True)]}</code></p> <p>This is the dictionary defined in the master.</p> <p>I now want to access this dictionary on my module and add another key in that &quot;READ_ONLY_ON_STATES&quot; variable...</p> <p>How to achive it... Tried various ways but unable to to... Can anyone help me out please</p>
[ { "answer_id": 74407371, "author": "destripador", "author_id": 13738303, "author_profile": "https://Stackoverflow.com/users/13738303", "pm_score": 0, "selected": false, "text": " self.env['ir.config_parameter'].set_param('global_variable_name', self.comite.id)\n" }, { "answer_id": 74408258, "author": "icra", "author_id": 9195906, "author_profile": "https://Stackoverflow.com/users/9195906", "pm_score": 1, "selected": false, "text": "from odoo.addons.my_module.models.my_model import READ_ONLY_ON_STATES \nprint(READ_ONLY_ON_STATES)\n" }, { "answer_id": 74423956, "author": "Kenly", "author_id": 5471709, "author_profile": "https://Stackoverflow.com/users/5471709", "pm_score": 2, "selected": true, "text": "READ_ONLY_ON_STATES" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74406225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16306516/" ]
74,406,248
<p>Can someome explain to me how New Array, and Array works with this loop? Also, anyone knows if is possible of doing a array and inside this array a function? Because this way of doing seem kinda wrong considering POO and SRP Here`s the link of the exercise: <a href="https://www.codewars.com/kata/569e09850a8e371ab200000b/train/javascript" rel="nofollow noreferrer">https://www.codewars.com/kata/569e09850a8e371ab200000b/train/javascript</a></p> <pre><code>function preFizz(n) { let output = new Array(); let num = 1; while(output.length &lt; n){ output.push(num); num += 1; } return output; } </code></pre>
[ { "answer_id": 74406372, "author": "Davi", "author_id": 20348848, "author_profile": "https://Stackoverflow.com/users/20348848", "pm_score": 1, "selected": false, "text": "let demo = (N,f) => {\n console.log(\n Array.from(Array(N), (_, i) => f(i)),\n )\n}\n" }, { "answer_id": 74406483, "author": "Mr. Polywhirl", "author_id": 1762224, "author_profile": "https://Stackoverflow.com/users/1762224", "pm_score": 1, "selected": true, "text": "const preFizz = (n) => {\n const output = [];\n for (let num = 1; num <= n; num++) {\n output.push(num);\n }\n return output;\n}\n\nconsole.log(...preFizz(10));" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74406248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20348848/" ]