qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,521,840
|
<p>I have a list of numbers in a string separated by space x="1 2 3 4 5 6 7 8 9 10 11 ..."<br />
I want to extract 3x3 matrices (list of list) from this string so the above string should produce the output = [ [[1,2,3],[4,5,6],[7,8,9]],[ [10,11,12],[13,14,15],[16,17,18] ]...<br />
I tried using the split function on the variable x and loop over it to build the final output but it gets messy. <code>Is there a simple way to do it in simple python or using some library?</code><br />
We can assume that the number of elements will be consistent with splitting it into 3x3 and the numbers are separated by single space</p>
|
[
{
"answer_id": 74521855,
"author": "gog",
"author_id": 3494774,
"author_profile": "https://Stackoverflow.com/users/3494774",
"pm_score": 2,
"selected": false,
"text": "zip zip let zip = args => args[0].map((_, i) => args.map(a => a[i]))\n\n//\n\nconst arr = [['Dog', 'Cat', 'Fish', 'Bird'],[1, 4, 2, 3]];\n\nr = zip(zip(arr).sort((x, y) => x[1] - y[1]))\n\nconsole.log(r)"
},
{
"answer_id": 74521861,
"author": "Majed Badawi",
"author_id": 7486313,
"author_profile": "https://Stackoverflow.com/users/7486313",
"pm_score": 0,
"selected": false,
"text": "Array#reduce items Map Array#sort Map#get Array#sort const sort = ([ items, indices ]) => {\n const indexMap = items.reduce((map, item, index) => \n map.set(item, indices[index])\n , new Map);\n return [\n items.sort((a, b) => indexMap.get(a) - indexMap.get(b)),\n indices.sort()\n ];\n}\n\n\nconsole.log( sort([['Dog', 'Cat', 'Fish', 'Bird'], [1, 4, 2, 3]]) );"
},
{
"answer_id": 74521953,
"author": "Hedi Zitouni",
"author_id": 12285347,
"author_profile": "https://Stackoverflow.com/users/12285347",
"pm_score": 0,
"selected": false,
"text": "function deepSort(arr2d) {\n const [stringArr, indexArr] = arr2d\n const result = []\n indexArr.forEach((index, i) => result[index - 1] = stringArr[i])\n return [result, indexArr.sort()]\n}\n\n"
},
{
"answer_id": 74521969,
"author": "Nina Scholz",
"author_id": 1447675,
"author_profile": "https://Stackoverflow.com/users/1447675",
"pm_score": 0,
"selected": false,
"text": "const\n array = [['Dog', 'Cat', 'Fish', 'Bird'], [1, 4, 2, 3]],\n indices = [...array[1].keys()].sort((a, b) => array[1][a] - array[1][b]);\n\nfor (let i = 0; i < array.length; i++)\n array[i] = indices.map(j => array[i][j]);\n\nconsole.log(array); .as-console-wrapper { max-height: 100% !important; top: 0; }"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19284394/"
] |
74,521,863
|
<p>Having a dataframe like this:</p>
<pre><code>dframe <- data.frame(id = c(1,2), names = c("google analytics","amazon shop"))
</code></pre>
<p>Which command could create two columns using the space of names column?</p>
<p>Example output:</p>
<pre><code>dframe <- data.frame(id = c(1,2), names1 = c("google","amazon"), names2 = c("analytics","shop"))
</code></pre>
|
[
{
"answer_id": 74521912,
"author": "G. Grothendieck",
"author_id": 516548,
"author_profile": "https://Stackoverflow.com/users/516548",
"pm_score": -1,
"selected": false,
"text": "dframe separate library(dplyr)\nlibrary(tidyr)\n\ndframe %>% separate(names, into = c(\"names1\", \"names2\"))\n## id names1 names2\n## 1 1 google analytics\n## 2 2 amazon shop\n sub transform(dframe, names1 = sub(\" .*\", \"\", names),\n names2 = sub(\".* \", \"\", names),\n names = NULL)\n## id names1 names2\n## 1 1 google analytics\n## 2 2 amazon shop\n read.table cbind(dframe[-2], \n read.table(text = dframe[[2]], col.names = c(\"names1\", \"names2\")))\n## id names1 names2\n## 1 1 google analytics\n## 2 2 amazon shop\n tmp <- read.table(text = dframe$names)\ntransform(dframe, names1 = tmp[[1]], names2 = tmp[[2]], names = NULL)\n nms <- c(\"id\", \"names1\", \"names2\")\nread.table(text = with(dframe, paste(id, names)), col.names = nms)\n## id names1 names2\n## 1 1 google analytics\n## 2 2 amazon shop\n sapply strsplit field field <- function(x, i) sapply(strsplit(x, \" \"), `[`, i)\ntransform(dframe, names1 = field(names, 1),\n names2 = field(names, 2),\n names = NULL)\n## id names1 names2\n## 1 1 google analytics\n## 2 2 amazon shop\n"
},
{
"answer_id": 74522736,
"author": "Chris Ruehlemann",
"author_id": 8039978,
"author_profile": "https://Stackoverflow.com/users/8039978",
"pm_score": -1,
"selected": false,
"text": "extract library(tidyr)\ndframe %>%\n extract(names,\n into = c(\"names1\", \"names2\"),\n regex = \"(\\\\w+) (\\\\w+)\")\n id names1 names2\n1 1 google analytics\n2 2 amazon shop\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521863",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20224217/"
] |
74,521,890
|
<p>I've been trying to improve a SQL query which uses multiple sub queries over the same table but with different conditions and only retrieves the first result from each sub queries.</p>
<p>I will try to simplify the use-case :</p>
<p>I have a table <code>Products</code> like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Product_id</th>
<th>reference</th>
<th>field3</th>
<th>field 4</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>ref1</td>
<td>val1</td>
<td>val3</td>
</tr>
<tr>
<td>2</td>
<td>ref2</td>
<td>val2</td>
<td>val4</td>
</tr>
</tbody>
</table>
</div>
<p>And another table <code>History</code>:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>History_id</th>
<th>reference</th>
<th>utilcode</th>
<th>physicalcode</th>
<th>issue</th>
<th>media</th>
<th>datetime</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>ref1</td>
<td>'test'</td>
<td>'TST'</td>
<td>'0'</td>
<td>'&audio'</td>
<td>'a_date'</td>
</tr>
<tr>
<td>2</td>
<td>ref2</td>
<td>'phone'</td>
<td>'CALLER'</td>
<td>'1'</td>
<td>'&video'</td>
<td>'a_date'</td>
</tr>
<tr>
<td>3</td>
<td>ref2</td>
<td>'test'</td>
<td>'CALLER'</td>
<td>'2'</td>
<td>'&test'</td>
<td>'a_date'</td>
</tr>
</tbody>
</table>
</div>
<p><code>History</code> is a log table and therefore contains a lot of values.</p>
<p>Now I have a query like this</p>
<pre class="lang-sql prettyprint-override"><code>SELECT
p.reference,
p.field3, p.field4,
(SELECT TOP 1 a_date
FROM history h
WHERE h.reference = p.reference
AND physicalcode = 'TST'
AND issue = 0
ORDER BY a_date DESC) AS latest_date_issue_0,
(SELECT TOP 1 a_date
FROM history h
WHERE h.reference = p.reference
AND physicalcode = 'TST'
AND issue = 1
ORDER BY a_date DESC) AS latest_date_issue_1
(SELECT TOP 1 a_date
FROM history h
WHERE h.reference = p.reference
AND utilcode = 'phone'
ORDER BY a_date DESC) AS latest_date_phone,
(SELECT TOP 1 media
FROM history h
WHERE h.reference = p.reference
AND utilcode = 'phone'
ORDER BY a_date DESC) AS latest_media,
-- and so on with many possible combinations
-- Note that there are more than this few fields on the tables I work on.
WHERE
p.field3 = 'valX',
p.field4 = 'valY'
FROM
products p
</code></pre>
<p>How could I merge every sub selects ? Or even a few that are alike to improve the performance ?</p>
<p>History being a very big table, selecting over it multiple times drastically slows down the query.</p>
<p>The main problem being that I only need the first value every time.</p>
<p>Thank you for your time and I hope to find a better way to deal with this issue!</p>
<p>I tried to use <code>ROW_NUMBER()</code> but I could not find a suitable way to use it.<br />
I also tried to create a tmp table using <code>WITH</code> to group every possibility from history but it was worse.</p>
<p>EDIT : Execution plan <a href="https://www.brentozar.com/pastetheplan/?id=Sy1AKIsUs" rel="nofollow noreferrer">https://www.brentozar.com/pastetheplan/?id=Sy1AKIsUs</a></p>
|
[
{
"answer_id": 74521912,
"author": "G. Grothendieck",
"author_id": 516548,
"author_profile": "https://Stackoverflow.com/users/516548",
"pm_score": -1,
"selected": false,
"text": "dframe separate library(dplyr)\nlibrary(tidyr)\n\ndframe %>% separate(names, into = c(\"names1\", \"names2\"))\n## id names1 names2\n## 1 1 google analytics\n## 2 2 amazon shop\n sub transform(dframe, names1 = sub(\" .*\", \"\", names),\n names2 = sub(\".* \", \"\", names),\n names = NULL)\n## id names1 names2\n## 1 1 google analytics\n## 2 2 amazon shop\n read.table cbind(dframe[-2], \n read.table(text = dframe[[2]], col.names = c(\"names1\", \"names2\")))\n## id names1 names2\n## 1 1 google analytics\n## 2 2 amazon shop\n tmp <- read.table(text = dframe$names)\ntransform(dframe, names1 = tmp[[1]], names2 = tmp[[2]], names = NULL)\n nms <- c(\"id\", \"names1\", \"names2\")\nread.table(text = with(dframe, paste(id, names)), col.names = nms)\n## id names1 names2\n## 1 1 google analytics\n## 2 2 amazon shop\n sapply strsplit field field <- function(x, i) sapply(strsplit(x, \" \"), `[`, i)\ntransform(dframe, names1 = field(names, 1),\n names2 = field(names, 2),\n names = NULL)\n## id names1 names2\n## 1 1 google analytics\n## 2 2 amazon shop\n"
},
{
"answer_id": 74522736,
"author": "Chris Ruehlemann",
"author_id": 8039978,
"author_profile": "https://Stackoverflow.com/users/8039978",
"pm_score": -1,
"selected": false,
"text": "extract library(tidyr)\ndframe %>%\n extract(names,\n into = c(\"names1\", \"names2\"),\n regex = \"(\\\\w+) (\\\\w+)\")\n id names1 names2\n1 1 google analytics\n2 2 amazon shop\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20564546/"
] |
74,521,917
|
<p>I'm using Firebird 2.1 and I have the following hierarchical table:</p>
<pre><code>NodeID, ParentNodeID, Name
</code></pre>
<p>ParentNodeID = -1 for root nodes.</p>
<p>For example:</p>
<pre class="lang-none prettyprint-override"><code>1, -1, Parent
2, 1, Child
3, 2, Child of child
</code></pre>
<p>I'm looking for a recursive query (or stored procedure) to output a concatenation the following way:</p>
<pre class="lang-none prettyprint-override"><code>Parent
Parent - Child
Parent - Child - Child of child
</code></pre>
<p>Siblings should be sorted in alphabetic order. How do I do this?</p>
|
[
{
"answer_id": 74521912,
"author": "G. Grothendieck",
"author_id": 516548,
"author_profile": "https://Stackoverflow.com/users/516548",
"pm_score": -1,
"selected": false,
"text": "dframe separate library(dplyr)\nlibrary(tidyr)\n\ndframe %>% separate(names, into = c(\"names1\", \"names2\"))\n## id names1 names2\n## 1 1 google analytics\n## 2 2 amazon shop\n sub transform(dframe, names1 = sub(\" .*\", \"\", names),\n names2 = sub(\".* \", \"\", names),\n names = NULL)\n## id names1 names2\n## 1 1 google analytics\n## 2 2 amazon shop\n read.table cbind(dframe[-2], \n read.table(text = dframe[[2]], col.names = c(\"names1\", \"names2\")))\n## id names1 names2\n## 1 1 google analytics\n## 2 2 amazon shop\n tmp <- read.table(text = dframe$names)\ntransform(dframe, names1 = tmp[[1]], names2 = tmp[[2]], names = NULL)\n nms <- c(\"id\", \"names1\", \"names2\")\nread.table(text = with(dframe, paste(id, names)), col.names = nms)\n## id names1 names2\n## 1 1 google analytics\n## 2 2 amazon shop\n sapply strsplit field field <- function(x, i) sapply(strsplit(x, \" \"), `[`, i)\ntransform(dframe, names1 = field(names, 1),\n names2 = field(names, 2),\n names = NULL)\n## id names1 names2\n## 1 1 google analytics\n## 2 2 amazon shop\n"
},
{
"answer_id": 74522736,
"author": "Chris Ruehlemann",
"author_id": 8039978,
"author_profile": "https://Stackoverflow.com/users/8039978",
"pm_score": -1,
"selected": false,
"text": "extract library(tidyr)\ndframe %>%\n extract(names,\n into = c(\"names1\", \"names2\"),\n regex = \"(\\\\w+) (\\\\w+)\")\n id names1 names2\n1 1 google analytics\n2 2 amazon shop\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/298939/"
] |
74,521,919
|
<p>Isn't there a way to change the order of the children of a flex box with just CSS?</p>
<p><code><div> flex 2 </div> <div></code>
<code>flex 3</code>
<code></div></code>
<code><div style="flex-order:-1"> flex 1 </div></code></p>
|
[
{
"answer_id": 74521935,
"author": "Moussa Bistami",
"author_id": 15628525,
"author_profile": "https://Stackoverflow.com/users/15628525",
"pm_score": 2,
"selected": false,
"text": "order order: 1;\norder: 2;\norder: 4;\norder: 3;\n"
},
{
"answer_id": 74521946,
"author": "Sito8943",
"author_id": 16202115,
"author_profile": "https://Stackoverflow.com/users/16202115",
"pm_score": 3,
"selected": true,
"text": "order .div1 { order: 0; } 0 1 2"
},
{
"answer_id": 74522062,
"author": "o1dskoo1",
"author_id": 4722001,
"author_profile": "https://Stackoverflow.com/users/4722001",
"pm_score": 2,
"selected": false,
"text": "<div class=\"wrapper\">\n <div class=\"item-2\">Flex 2</div>\n <div class=\"item-3\">Flex 3</div>\n <div class=\"item-1\">Flex 1</div>\n</div>\n .wrapper {\n display: flex;\n}\n\n.item-1 {\n order: 1;\n}\n\n.item-2 {\n order: 2;\n}\n\n.item-3 {\n order: 3;\n}\n .wrapper {\n display: flex;\n flex-direction: row-reverse;\n}\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20564801/"
] |
74,521,923
|
<p>I was trying to implement <a href="https://stackoverflow.com/a/74432616/20314114">this great response</a> to my question about getting the terminal size with ANSI escape sequences. It didn't work, so I tried to see what the differences between the proposed code and mine were. I don't know if it is the main problem, but I followed the breadcrumbs to the one obvious differences (which I have also been able to replicate in a minimal example) - I use VMIN = 0, and the solution uses VMIN = 1.</p>
<pre><code>#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <ctype.h>
#define SIZE 100
int main ( void) {
int ch = 0;
int i = 0;
struct termios original, changed;
// change terminal settings
tcgetattr( STDIN_FILENO, &original);
changed = original;
changed.c_lflag &= ~( ICANON | ECHO);
changed.c_cc[VMIN] = 1;
changed.c_cc[VTIME] = 0;
tcsetattr( STDIN_FILENO, TCSANOW, &changed);
printf ( "\033[9999;9999H"); // cursor should move as far as it can
printf ( "\033[6n"); // ask for cursor position
printf ( "\033[2J"); //clear screen
printf ( "\033[1;1H"); // move to upper left corner
while ( ( ch = getchar ()) != 'R') { // R terminates the response
if ( EOF == ch)
break;
if ( isprint ( ch)) // print out only normal chars to not mess up display
printf("stdin[%d]\t==\t%d\t==\t%c\n", i, ch, ch);
else
printf("stdin[%d]\t==\t%d\t==\t\n", i, ch);
i++;
}
// restore terminal settings
tcsetattr( STDIN_FILENO, TCSANOW, &original);
return 0;
}
</code></pre>
<p>Here is a slightly shortened version of the proposed solution which showcases the problem. If you keep VMIN at 1, everything will work fine. However, if you set it to 0, you will lose the first part of <code>ESC[rows;colsR</code>, and it will only get printed out after the program finishes.</p>
<p>My actual code is too big and fragmented to post here, but what I am experiencing is a total freeze of the program if I set VMIN to 1 (I am read()-ing STDIN(1) in an infinite loop), and nothing happens when I run <code>\033[6n</code> (as if stdin is empty - I can get nothing out with getchar nor fread nor read)</p>
<p>If you have any info about this peculiarity, please share.</p>
<p>Thank you.</p>
|
[
{
"answer_id": 74522412,
"author": "user3121023",
"author_id": 3121023,
"author_profile": "https://Stackoverflow.com/users/3121023",
"pm_score": 2,
"selected": true,
"text": "#include <stdio.h>\n#include <termios.h>\n#include <unistd.h>\n#include <ctype.h>\n\n#define SIZE 100\n\nvoid getscrnsize ( struct termios *set, int *row, int *col) {\n struct termios temp;\n temp = *set;\n temp.c_cc[VMIN] = 1;\n tcsetattr( STDIN_FILENO, TCSANOW, &temp); // use temp settings\n printf ( \"\\033[6n\"); // ask for cursor position\n scanf ( \"\\033[%d;%dR\", row, col);\n tcsetattr( STDIN_FILENO, TCSANOW, set); // restore settings\n}\n\nint main ( void) {\n int row = 0;\n int col = 0;\n struct termios original, changed;\n\n // change terminal settings\n tcgetattr( STDIN_FILENO, &original);\n changed = original;\n changed.c_lflag &= ~( ICANON | ECHO);\n changed.c_cc[VMIN] = 0;\n changed.c_cc[VTIME] = 0;\n tcsetattr( STDIN_FILENO, TCSANOW, &changed);\n\n printf ( \"\\033[9999;9999H\"); // cursor should move as far as it can\n\n getscrnsize ( &changed, &row, &col);\n\n printf ( \"\\033[2J\"); //clear screen\n printf ( \"\\033[1;1H\"); // move to upper left corner\n\n printf ( \"rows %d\\tcols %d\\n\", row, col);\n\n\n // restore terminal settings\n tcsetattr( STDIN_FILENO, TCSANOW, &original);\n\n return 0;\n}\n"
},
{
"answer_id": 74525509,
"author": "user3121023",
"author_id": 3121023,
"author_profile": "https://Stackoverflow.com/users/3121023",
"pm_score": 0,
"selected": false,
"text": "ncurses -lncurses '|' #include <stdio.h>\n#include <ncurses.h>\n\nint main ( void) {\n int ch = 0;\n int row = 0;\n int col = 0;\n\n initscr ( );\n halfdelay ( 2); // tenths of a second that getch waits for input\n noecho ( );\n getmaxyx ( stdscr, row, col);\n move ( 1, 1);\n printw ( \"row %d\\tcol %d\\n\", row, col);\n\n while ( ( ch = getch ( ))) {\n if ( ERR != ch) {\n printw ( \"%c\", ch);\n if ( '|' == ch) {\n break;\n }\n }\n }\n getyx ( stdscr, row, col);\n printw ( \"\\nrow %d \\tcol %d\", row, col);\n printw ( \"\\n\\npress enter\\n\");\n while ( ( ch = getch ( ))) {\n if ( '\\n' == ch) {\n break;\n }\n }\n endwin ( );\n return 0;\n}\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20314114/"
] |
74,521,930
|
<p>I had a large data frame that I grouped and then split into a list of over 400 vectors. There are some tibbles within this data frame that have one column with only 0's as entries and I would like to somehow remove these entries from list or data frame.</p>
<p>A smaller sample of what my data looks like can be seen here:</p>
<pre><code> dfa <- data.frame(intensity.x = c(10, 20, 100, 30 , 40), intensity.y = c(100, 30, 0.0, 20, 0), group = c('a', 'a', 'a', 'a', 'a'))
dfb <- data.frame(intensity.x = c(100, 10, 45, 60 , 43), intensity.y = c(0, 0, 0, 0, 0), group = c('b', 'b', 'b', 'b', 'b'))
dfx <- data.frame(intensity.x = c(20, 4, 5, 16 , 3), intensity.y = c(0, 12, 0, 1, 0), group = c('x', 'x', 'x', 'x', 'x'))
dfy <- data.frame(intensity.x = c(10, 10, 30, 20 , 80), intensity.y = c(0, 0, 0, 0, 0), group = c('y', 'y', 'y', 'y', 'y'))
df.big <- rbind(dfa, dfb, dfx, dfy)
df.list <- list(dfa, dfb, dfx, dfy)
</code></pre>
<p>Essentially I want groups like dfy and dfb to be filtered out of my large data frame (df.big) or the kist (df.list) because all of their intensity.y values are 0, but I can't use</p>
<blockquote>
<p>filter(df.big$intensity.y != 0)</p>
</blockquote>
<p>Because that would then remove the values from groups df and dfz which I want to maintain.</p>
<p>Is this possible?</p>
|
[
{
"answer_id": 74521972,
"author": "Allan Cameron",
"author_id": 12500315,
"author_profile": "https://Stackoverflow.com/users/12500315",
"pm_score": 3,
"selected": true,
"text": "df.list[sapply(df.list, function(df) !all(df$intensity.y == 0))]\n#> [[1]]\n#> intensity.x intensity.y group\n#> 1 10 100 a\n#> 2 20 30 a\n#> 3 100 0 a\n#> 4 30 20 a\n#> 5 40 0 a\n#> \n#> [[2]]\n#> intensity.x intensity.y group\n#> 1 20 0 x\n#> 2 4 12 x\n#> 3 5 0 x\n#> 4 16 1 x\n#> 5 3 0 x\n"
},
{
"answer_id": 74522140,
"author": "Julian",
"author_id": 14137004,
"author_profile": "https://Stackoverflow.com/users/14137004",
"pm_score": 1,
"selected": false,
"text": "purrr df.list |> purrr::keep(~dplyr::summarise(.x, sum(intensity.y)) != 0)\n"
},
{
"answer_id": 74522920,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 2,
"selected": false,
"text": "base R Filter Filter(\\(x) any(x$intensity.y != 0), df.list)\n[[1]]\n intensity.x intensity.y group\n1 10 100 a\n2 20 30 a\n3 100 0 a\n4 30 20 a\n5 40 0 a\n\n[[2]]\n intensity.x intensity.y group\n1 20 0 x\n2 4 12 x\n3 5 0 x\n4 16 1 x\n5 3 0 x\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20451829/"
] |
74,521,980
|
<p>I've started the default Android project, "Navigation Drawer Activity".</p>
<p><a href="https://i.stack.imgur.com/zATqD.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zATqD.jpg" alt="enter image description here" /></a></p>
<p>I've changed the theme to:</p>
<pre><code><!-- <style name="Theme.MyApplication" parent="Theme.MaterialComponents.DayNight.DarkActionBar">-->
<style name="Theme.MyApplication" parent="Theme.Material3.DayNight.NoActionBar">
</code></pre>
<p>But then the Drawer has rounded corners:</p>
<p><a href="https://i.stack.imgur.com/9QHJK.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9QHJK.jpg" alt="enter image description here" /></a></p>
<p>How can I make these corners straight again?</p>
|
[
{
"answer_id": 74522420,
"author": "Gabriele Mariotti",
"author_id": 2016562,
"author_profile": "https://Stackoverflow.com/users/2016562",
"pm_score": 2,
"selected": true,
"text": "NavigationView drawerLayoutCornerSize 16dp <com.google.android.material.navigation.NavigationView\n android:id=\"@+id/nav_view\"\n app:drawerLayoutCornerSize=\"0dp\"\n <style name=\"App.Material3.NavigationView\" parent=\"Widget.Material3.NavigationView\">\n <item name=\"drawerLayoutCornerSize\">0dp</item>\n</style>\n NavigationView <com.google.android.material.navigation.NavigationView\n android:id=\"@+id/nav_view\"\n style=\"@style/App.Material3.NavigationView\"\n"
},
{
"answer_id": 74522601,
"author": "Moklesur Rahman",
"author_id": 4411893,
"author_profile": "https://Stackoverflow.com/users/4411893",
"pm_score": 0,
"selected": false,
"text": "com.google.android.material.navigation.NavigationView app:drawerLayoutCornerSize=\"0dp\"\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/898307/"
] |
74,522,010
|
<p>Is there any add-in that allows to run piped code line by line in R without altering the code?</p>
<p>For example, I would press keys at each line and it would print the output in the console.</p>
<pre class="lang-r prettyprint-override"><code># AS AN EXAMPLE
library(dplyr)
mtcars %>%
mutate(cyl2 = 2 * cyl) %>%
filter(cyl2 > 15)
</code></pre>
<p>I am aware of the <code>ViewPipeSteps</code> add-in but it's not exactly what I am looking for.</p>
|
[
{
"answer_id": 74522420,
"author": "Gabriele Mariotti",
"author_id": 2016562,
"author_profile": "https://Stackoverflow.com/users/2016562",
"pm_score": 2,
"selected": true,
"text": "NavigationView drawerLayoutCornerSize 16dp <com.google.android.material.navigation.NavigationView\n android:id=\"@+id/nav_view\"\n app:drawerLayoutCornerSize=\"0dp\"\n <style name=\"App.Material3.NavigationView\" parent=\"Widget.Material3.NavigationView\">\n <item name=\"drawerLayoutCornerSize\">0dp</item>\n</style>\n NavigationView <com.google.android.material.navigation.NavigationView\n android:id=\"@+id/nav_view\"\n style=\"@style/App.Material3.NavigationView\"\n"
},
{
"answer_id": 74522601,
"author": "Moklesur Rahman",
"author_id": 4411893,
"author_profile": "https://Stackoverflow.com/users/4411893",
"pm_score": 0,
"selected": false,
"text": "com.google.android.material.navigation.NavigationView app:drawerLayoutCornerSize=\"0dp\"\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74522010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8806649/"
] |
74,522,053
|
<p>The following code isn't extracting URLs past the "#"</p>
<p><strong>The setup</strong></p>
<p>URL1/2 in A1/2 then command/control + k to set hyperlink</p>
<p><strong>example</strong></p>
<p>A1 = URL1 = <a href="http://stackoverflow.com/hello">http://stackoverflow.com/hello</a></p>
<p>A2 = URL2 = <a href="http://stackoverflow.com/hello#world">http://stackoverflow.com/hello#world</a></p>
<p><strong>Using VBA code below</strong></p>
<p>=URL(A1) = Result = <a href="http://stackoverflow.com/hello">http://stackoverflow.com/hello</a> (DESIRED)</p>
<p>=URL(A2) = Result = <a href="http://stackoverflow.com/hello">http://stackoverflow.com/hello</a> (NOT DESIRED)</p>
<p><strong>Desired:</strong></p>
<p>A2 = <a href="http://stackoverflow.com/hello#world">http://stackoverflow.com/hello#world</a></p>
<p><strong>Question</strong></p>
<ul>
<li>Is there a way to modify the code below to include the entire URL even after #.</li>
</ul>
<p><strong>VBA code</strong></p>
<pre><code>Function URL(Hyperlink As Range)
URL = Hyperlink.Hyperlinks(1).Address
End Function
</code></pre>
|
[
{
"answer_id": 74522159,
"author": "Guillaume BEDOYA",
"author_id": 20522241,
"author_profile": "https://Stackoverflow.com/users/20522241",
"pm_score": -1,
"selected": false,
"text": "URL = Hyperlink.Hyperlinks(1).TextToDisplay\n"
},
{
"answer_id": 74522554,
"author": "Tim Williams",
"author_id": 478884,
"author_profile": "https://Stackoverflow.com/users/478884",
"pm_score": 2,
"selected": true,
"text": "Function URL(Hyperlink As Range) As String\n Dim sa As String\n If Hyperlink.Hyperlinks.Count = 0 Then Exit Function\n With Hyperlink.Hyperlinks(1)\n sa = .SubAddress 'anything after #\n URL = .Address & IIf(sa <> \"\", \"#\" & sa, \"\")\n End With\nEnd Function\n"
},
{
"answer_id": 74523214,
"author": "Robert Mearns",
"author_id": 5050,
"author_profile": "https://Stackoverflow.com/users/5050",
"pm_score": 1,
"selected": false,
"text": "Sub test()\nDim Example1 As String\nDim Example2 As String\nDim Example3 As String\n\nExample1 = URL(ActiveWorkbook.ActiveSheet.Range(\"A1\"))\nExample2 = URL(ActiveWorkbook.ActiveSheet.Range(\"A2\"))\nExample3 = URL(ActiveWorkbook.ActiveSheet.Range(\"A1:A3\"))\n\nMsgBox \"Example 1:\" & vbCrLf & Example1 & vbCrLf & \"Example 2:\" & _\n vbCrLf & Example2 & vbCrLf & \"Example 3:\" & vbCrLf & Example3\n\nEnd Sub\n\n\nFunction URL(hyperlink As Range) As String\n'Returns all hyperlinks in a range as text\n\nIf hyperlink.Hyperlinks.Count = 0 Then Exit Function\n \n For a = 1 To hyperlink.Hyperlinks.Count\n If hyperlink.Hyperlinks(a).SubAddress <> \"\" Then\n URL = URL & hyperlink.Hyperlinks(a).Address & \"#\" & hyperlink.Hyperlinks(a).SubAddress & vbCrLf\n Else\n URL = URL & hyperlink.Hyperlinks(a).Address & vbCrLf\n End If\n Next a\n\nEnd Function\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74522053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2137570/"
] |
74,522,088
|
<p>This is the result I want to achieve.</p>
<p><a href="https://i.stack.imgur.com/tWaba.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tWaba.png" alt="enter image description here" /></a></p>
<p>But I can't find a way to add margin between the ReferenceLine label and the bar components.</p>
<p>This is my chart component</p>
<pre><code> <BarChart
width={500}
height={300}
data={data}
>
<XAxis hide dataKey="name" />
{
data.map((entry, index) => (
<ReferenceLine key={`cell-${index}`} strokeWidth={0} x={entry.name} label={entry.name} />
))
}
<Bar dataKey="pv" fill="#8884d8">
{
data.map((entry, index) => (
<Cell key={`cell-${index}`} fill={entry.pv <= 0 ? "#FF645C" : "#29DB92"} />
))
}
</Bar>
</BarChart>
</code></pre>
<p>You can see the full example on my sandbox.
<a href="https://codesandbox.io/s/bar-chart-with-positive-negative-forked-g3kvz5?file=/src/App.tsx:673-1176" rel="nofollow noreferrer">https://codesandbox.io/s/bar-chart-with-positive-negative-forked-g3kvz5?file=/src/App.tsx:673-1176</a></p>
|
[
{
"answer_id": 74610067,
"author": "Jonas Weinhardt",
"author_id": 16500604,
"author_profile": "https://Stackoverflow.com/users/16500604",
"pm_score": 1,
"selected": false,
"text": "const transformData = (margin: number) => {\n return data.map((item) => {\n if (item.pv >= 0) {\n return {\n name: item.name,\n pv: [margin, item.pv + margin]\n };\n } else {\n return {\n name: item.name,\n pv: [-margin, item.pv - margin]\n };\n }\n });\n};\n pv pv margin pv -margin pv pv margin App export default function App() {\n const barData = useMemo(() => transformData(1000), []);\n\n return (\n <BarChart width={500} height={300} data={barData}>\n <XAxis hide dataKey=\"name\" />\n {barData.map((entry, index) => (\n <ReferenceLine\n key={`cell-${index}`}\n strokeWidth={0}\n x={entry.name}\n label={entry.name}\n />\n ))}\n <Bar dataKey=\"pv\" fill=\"#8884d8\">\n {barData.map((entry, index) => (\n <Cell\n key={`cell-${index}`}\n fill={entry.pv[0] <= 0 ? \"#FF645C\" : \"#29DB92\"}\n />\n ))}\n </Bar>\n </BarChart>\n );\n}\n pv fill Cell entry.pv <= 0 ? \"#FF645C\" : \"#29DB92\" entry.pv[0] <= 0 ? \"#FF645C\" : \"#29DB92\" margin"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74522088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12057872/"
] |
74,522,141
|
<p>I'm currently dealing with a problem within my Azure DevOps pipeline where I'm trying to run and build a pipeline for repo 'RepoX', whereafter the Dockerfile tries to use the '.csproj' of repo 'RepoY'. However, 'RepoY' is added as 'existing project reference' to 'RepoX' within Visual Studio. When the dockerfile tries to use the .csproj of repo 'Y' I get a message that this file cannot be found. This is true, since both are located in different repositories, thus are separate projects. How can I make sure RepoX clones repo Y somehow or is able to use RepoY, so that the Dockerfile finds the .csproj of repo Y and builds it in order to push it to, for example Docker hub?</p>
<blockquote>
<p>Projects overview</p>
</blockquote>
<pre><code>Azure Repo: RepoX
------ [RepoX directory]
------------ Controllers
------------ Properties
------------ appsettings.Development.json
------------ appsettings.json
------------ Program.cs
------------ RepoX.csproj
------ .dockerignore
------ .gitignore
------ azure-pipelines.yml
------ Dockerfile
------ RepoX.sln
Azure Repo: RepoY (Class Library)
------ [CoreClasses directory]
------------ ClassA
------------ ClassB
</code></pre>
<p>I tried to use checkout to retrieve the repoY in repoX, but somehow this is not persistent when the Dockerfile is trying to search the .csproj of repoY?</p>
<blockquote>
<p>azure-pipelines.yml:</p>
</blockquote>
<pre><code>trigger:
- main
# resources:
# - repo: self <---------------- tried to turn this off as well, makes no difference...
variables:
tag: '$(Build.BuildId)'
stages:
- stage: Build
displayName: Build image
jobs:
- job: Build
displayName: Build
pool:
vmImage: ubuntu-latest
- task: Docker@2
- checkout: self
path: s/CheckOutFolder
- checkout: git://ProjectA/RepoY
path: s/CheckOutFolder/RepoX/RepoY
- script: |
ls
displayName: Build an image
inputs:
command: build
dockerfile: '$(Build.SourcesDirectory)/CheckOutFolder/Dockerfile'
tags: |
$(tag)
</code></pre>
<blockquote>
<p>Dockerfile:</p>
</blockquote>
<pre><code>#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.
FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443
FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY ["RepoX/RepoX.csproj", "RepoX/"]
RUN dotnet restore "RepoX/RepoX.csproj"
#RUN ls ../home/vsts/work/1/s/ <----- says no such directory exists...
#RUN ls ../home/vsts/work/1/s/CheckOutFolder/RepoX/RepoY <----- says no such directory exists...
#RUN ls RepoX <----- does not contain files of RepoY, although I used checkout? I don't get it..
COPY ["RepoX/RepoY/RepoY.csproj", "RepoX/"] <----- says cannot find file...
RUN dotnet restore "RepoX/RepoY.csproj"
COPY . .
WORKDIR "/src/RepoX"
RUN dotnet build "RepoX.csproj" -c Release -o /app/build
FROM build AS publish
RUN dotnet publish "RepoX.csproj" -c Release -o /app/publish
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "RepoX.dll"]
</code></pre>
<p>Can someone please help me with this?</p>
|
[
{
"answer_id": 74610067,
"author": "Jonas Weinhardt",
"author_id": 16500604,
"author_profile": "https://Stackoverflow.com/users/16500604",
"pm_score": 1,
"selected": false,
"text": "const transformData = (margin: number) => {\n return data.map((item) => {\n if (item.pv >= 0) {\n return {\n name: item.name,\n pv: [margin, item.pv + margin]\n };\n } else {\n return {\n name: item.name,\n pv: [-margin, item.pv - margin]\n };\n }\n });\n};\n pv pv margin pv -margin pv pv margin App export default function App() {\n const barData = useMemo(() => transformData(1000), []);\n\n return (\n <BarChart width={500} height={300} data={barData}>\n <XAxis hide dataKey=\"name\" />\n {barData.map((entry, index) => (\n <ReferenceLine\n key={`cell-${index}`}\n strokeWidth={0}\n x={entry.name}\n label={entry.name}\n />\n ))}\n <Bar dataKey=\"pv\" fill=\"#8884d8\">\n {barData.map((entry, index) => (\n <Cell\n key={`cell-${index}`}\n fill={entry.pv[0] <= 0 ? \"#FF645C\" : \"#29DB92\"}\n />\n ))}\n </Bar>\n </BarChart>\n );\n}\n pv fill Cell entry.pv <= 0 ? \"#FF645C\" : \"#29DB92\" entry.pv[0] <= 0 ? \"#FF645C\" : \"#29DB92\" margin"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74522141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20291437/"
] |
74,522,188
|
<p>I have a list of tuples in rows which I need to append to another list and add a newline after each entry I tried everything I can think of but I cant seem to do it properly
here is the code:</p>
<pre><code>niz = ["""
(5, 6, 4)
(90, 100, 13), (5, 8, 13), (9, 11, 13)
(9, 11, 5), (19, 20, 5), (30, 34, 5)
(9, 11, 4)
(22, 25, 13), (17, 19, 13)
"""]
list = []
for n in niz:
list.append(n)
list = '\n'.join(list)
print(list)
</code></pre>
<p>This is the closest I get:</p>
<pre><code>(5, 6, 4)
(90, 100, 13), (5, 8, 13), (9, 11, 13)
(9, 11, 5), (19, 20, 5), (30, 34, 5)
(9, 11, 4)
(22, 25, 13), (17, 19, 13)
</code></pre>
<p>But I need it to be:</p>
<pre><code>[(5, 6, 4),
(90, 100, 13), (5, 8, 13), (9, 11, 13),
(9, 11, 5), (19, 20, 5), (30, 34, 5),
(9, 11, 4),
(22, 25, 13), (17, 19, 13)]
</code></pre>
|
[
{
"answer_id": 74522262,
"author": "Sembei Norimaki",
"author_id": 20396240,
"author_profile": "https://Stackoverflow.com/users/20396240",
"pm_score": -1,
"selected": true,
"text": "list = []\nfor n in niz:\n list.append(n) \nlist = '[' + ',\\n'.join(list) + ']'\n\nprint(list)\n"
},
{
"answer_id": 74522286,
"author": "Libra",
"author_id": 10755384,
"author_profile": "https://Stackoverflow.com/users/10755384",
"pm_score": 0,
"selected": false,
"text": "niz = [\"\"\"\n(5, 6, 4)\n(90, 100, 13), (5, 8, 13), (9, 11, 13)\n(9, 11, 5), (19, 20, 5), (30, 34, 5)\n(9, 11, 4)\n(22, 25, 13), (17, 19, 13)\n\"\"\"]\n niz = [\"[\",(5, 6, 4), \"\\n\", (90, 100, 13), (5, 8, 13), (9, 11, 13), \"\\n\", (9, 11, 5), (19, 20, 5), (30, 34, 5), \"\\n\", (9, 11, 4), \"\\n\", (22, 25, 13), (17, 19, 13),\"]\"]\n\nfor item in niz:\n print(item, end=\" \")\n"
},
{
"answer_id": 74522520,
"author": "Guillaume BEDOYA",
"author_id": 20522241,
"author_profile": "https://Stackoverflow.com/users/20522241",
"pm_score": 0,
"selected": false,
"text": "nizz = niz[0].replace(')\\n(', '), (')\nnizz = nizz.replace('), (', ')|(').replace('\\n', '')\nresult = [eval(i) for i in nizz.split('|')]\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74522188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19647630/"
] |
74,522,221
|
<p>Here's the code:</p>
<pre><code>for (int i = 0; i < n; i++) {
for (int j = 0; j < n * n; j++) {
for (int k = 0; k < j; k++) {
sum++;
}
}
}
</code></pre>
<p>I need to evaluate the Time complexity in Big-O notation of the nested loops above.</p>
<p>Is it just <code>O(n) * O(n) * O(n) + O(1)</code> to make <code>O(n^3)</code>? Or is there more to it?</p>
|
[
{
"answer_id": 74522291,
"author": "Edward Peters",
"author_id": 6016064,
"author_profile": "https://Stackoverflow.com/users/6016064",
"pm_score": 0,
"selected": false,
"text": "O(n) O(n^2)"
},
{
"answer_id": 74522308,
"author": "maio290",
"author_id": 4934937,
"author_profile": "https://Stackoverflow.com/users/4934937",
"pm_score": 1,
"selected": false,
"text": "for (int i = 0; i < n; i++) -> runs n times.\n for (int j = 0; j < n * n; j++) -> runs n² times.\n for (int k = 0; k < j; k++) -> runs n² times (k == j == n²)\n\nn * n² * n² = n^5.\n"
},
{
"answer_id": 74522335,
"author": "Alexander Ivanchenko",
"author_id": 17949945,
"author_profile": "https://Stackoverflow.com/users/17949945",
"pm_score": 3,
"selected": true,
"text": "O(n) * O(n^2) * O(n^2) = O(n^5) O(n) O(n^2) O(n^2)"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74522221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20564942/"
] |
74,522,240
|
<p>How do I create a Arc Progress bar animation like this</p>
<p><a href="https://i.stack.imgur.com/lFdDJ.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lFdDJ.gif" alt="animated progress" /></a></p>
<p>Currently I've already used Canvas to draw an arc and added animations to the progress bar using animateFloatAsState API. But second pic is not my expected.</p>
<p>[<img src="https://i.stack.imgur.com/y4Mzq.png" alt="My current implementation" />]</p>
<p><a href="https://i.stack.imgur.com/22iEi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/22iEi.png" alt="My current implementation" /></a></p>
<pre><code>// e.g. oldScore = 100f newScore = 350f
// Suppose 250 points are into one level
@Composable
fun ArcProgressbar(
modifier: Modifier = Modifier,
oldScore: Float,
newScore: Float,
level: String,
startAngle: Float = 120f,
limitAngle: Float = 300f,
thickness: Dp = 8.dp
) {
var value by remember { mutableStateOf(oldScore) }
val sweepAngle = animateFloatAsState(
targetValue = (value / 250) * limitAngle, // convert the value to angle
animationSpec = tween(
durationMillis = 1000
)
)
LaunchedEffect(Unit) {
delay(1500)
value = newScore
}
Box(modifier = modifier.fillMaxWidth()) {
Canvas(
modifier = Modifier
.fillMaxWidth(0.45f)
.padding(10.dp)
.aspectRatio(1f)
.align(Alignment.Center),
onDraw = {
// Background Arc
drawArc(
color = Gray100,
startAngle = startAngle,
sweepAngle = limitAngle,
useCenter = false,
style = Stroke(thickness.toPx(), cap = StrokeCap.Square),
size = Size(size.width, size.height)
)
// Foreground Arc
drawArc(
color = Green500,
startAngle = startAngle,
sweepAngle = sweepAngle.value,
useCenter = false,
style = Stroke(thickness.toPx(), cap = StrokeCap.Square),
size = Size(size.width, size.height)
)
}
)
Text(
text = level,
modifier = Modifier
.fillMaxWidth(0.125f)
.align(Alignment.Center)
.offset(y = (-10).dp),
color = Color.White,
fontSize = 82.sp
)
Text(
text = "LEVEL",
modifier = Modifier
.padding(bottom = 8.dp)
.align(Alignment.BottomCenter),
color = Color.White,
fontSize = 20.sp
)
}
}
</code></pre>
<p>How can I animate from start again if progress percentage over 100%, just like the one in the gif. Does anybody got some ideas? Thanks!</p>
|
[
{
"answer_id": 74526042,
"author": "z.y",
"author_id": 19023745,
"author_profile": "https://Stackoverflow.com/users/19023745",
"pm_score": 3,
"selected": false,
"text": "Animatable snap target limitAngle newScore key LaunchedEffect +30 @Composable\nfun ArcProgressbar(\n modifier: Modifier = Modifier,\n newScore: Float,\n level: String,\n startAngle : Float = 120f,\n limitAngle: Float = 300f,\n thickness: Dp = 8.dp\n) {\n\n val animateValue = remember { Animatable(0f) }\n\n LaunchedEffect(newScore) {\n if (newScore > 0f) {\n animateValue.snapTo(0f)\n delay(10)\n animateValue.animateTo(\n targetValue = limitAngle,\n animationSpec = tween(\n durationMillis = 1000\n )\n )\n }\n }\n\n Box(modifier = modifier.fillMaxWidth()) {\n\n Canvas(\n modifier = Modifier\n .fillMaxWidth(0.45f)\n .padding(10.dp)\n .aspectRatio(1f)\n .align(Alignment.Center),\n onDraw = {\n // Background Arc\n drawArc(\n color = Color.Gray,\n startAngle = startAngle,\n sweepAngle = limitAngle,\n useCenter = false,\n style = Stroke(thickness.toPx(), cap = StrokeCap.Square),\n size = Size(size.width, size.height)\n )\n\n // Foreground Arc\n drawArc(\n color = Color.Green,\n startAngle = startAngle,\n sweepAngle = animateValue.value,\n useCenter = false,\n style = Stroke(thickness.toPx(), cap = StrokeCap.Square),\n size = Size(size.width, size.height)\n )\n }\n )\n\n Column {\n Text(\n text = level,\n modifier = Modifier\n .fillMaxWidth(0.125f)\n .offset(y = (-10).dp),\n color = Color.Gray,\n fontSize = 82.sp\n )\n\n Text(\n text = \"LEVEL\",\n modifier = Modifier\n .padding(bottom = 8.dp),\n color = Color.Gray,\n fontSize = 20.sp\n )\n\n Text(\n text = \"Score ( $newScore ) \",\n modifier = Modifier\n .padding(bottom = 8.dp),\n color = Color.Gray,\n fontSize = 20.sp\n )\n }\n }\n}\n @Composable\nfun ScoreGenerator() {\n\n var newScore by remember {\n mutableStateOf(0f)\n }\n\n Column {\n Button(onClick = {\n newScore += 30f\n }) {\n Text(\"Add Score + 30\")\n }\n\n ArcProgressbar(\n newScore = newScore,\n level = \"\"\n )\n }\n}\n"
},
{
"answer_id": 74545174,
"author": "z.y",
"author_id": 19023745,
"author_profile": "https://Stackoverflow.com/users/19023745",
"pm_score": 4,
"selected": true,
"text": "re-composition Log ArcProgressbar Log.e(\"ArcProgressBar\", \"Recomposed\")\n val maxProgressPerLevel = 200 // you can change this to any max value that you want\nval progressLimit = 300f\n\nfun calculate(\n score: Float,\n level: Int,\n) : Float {\n return (abs(score - (maxProgressPerLevel * level)) / maxProgressPerLevel) * progressLimit\n}\n\n@Composable\nfun ArcProgressbar(\n modifier: Modifier = Modifier,\n score: Float\n) {\n\n Log.e(\"ArcProgressBar\", \"Recomposed\")\n\n var level by remember {\n mutableStateOf(score.toInt() / maxProgressPerLevel)\n }\n\n var targetAnimatedValue = calculate(score, level)\n val progressAnimate = remember { Animatable(targetAnimatedValue) }\n val scoreAnimate = remember { Animatable(0f) }\n val coroutineScope = rememberCoroutineScope()\n\n LaunchedEffect(level, score) {\n\n if (score > 0f) {\n\n // animate progress\n coroutineScope.launch {\n progressAnimate.animateTo(\n targetValue = targetAnimatedValue,\n animationSpec = tween(\n durationMillis = 1000\n )\n ) {\n if (value >= progressLimit) {\n\n coroutineScope.launch {\n level++\n progressAnimate.snapTo(0f)\n }\n }\n }\n }\n \n // animate score\n coroutineScope.launch {\n\n if (scoreAnimate.value > score) {\n scoreAnimate.snapTo(0f)\n }\n\n scoreAnimate.animateTo(\n targetValue = score,\n animationSpec = tween(\n durationMillis = 1000\n )\n )\n }\n }\n }\n\n Column(\n modifier = modifier.fillMaxWidth(),\n horizontalAlignment = Alignment.CenterHorizontally\n ) {\n Box {\n PointsProgress(\n progress = {\n progressAnimate.value // deferred read of progress\n }\n )\n\n CollectorLevel(\n modifier = Modifier.align(Alignment.Center),\n level = {\n level + 1 // deferred read of level\n }\n )\n }\n\n CollectorScore(\n modifier = Modifier.padding(top = 16.dp),\n score = {\n scoreAnimate.value // deferred read of score\n }\n )\n }\n}\n\n@Composable\nfun CollectorScore(\n modifier : Modifier = Modifier,\n score: () -> Float\n) {\n Column(\n modifier = modifier,\n horizontalAlignment = Alignment.CenterHorizontally\n ) {\n\n Text(\n text = \"Collector Score\",\n color = Color.White,\n fontSize = 16.sp\n )\n\n Text(\n text = \"${score().toInt()} PTS\",\n color = Color.White,\n fontSize = 40.sp\n )\n }\n}\n\n@Composable\nfun CollectorLevel(\n modifier : Modifier = Modifier,\n level: () -> Int\n) {\n Column(\n modifier = modifier,\n verticalArrangement = Arrangement.Center,\n horizontalAlignment = Alignment.CenterHorizontally\n ) {\n\n Text(\n modifier = Modifier\n .padding(top = 16.dp),\n text = level().toString(),\n color = Color.White,\n fontSize = 82.sp\n )\n\n Text(\n text = \"LEVEL\",\n color = Color.White,\n fontSize = 16.sp\n )\n }\n}\n\n@Composable\nfun BoxScope.PointsProgress(\n progress: () -> Float\n) {\n\n val start = 120f\n val end = 300f\n val thickness = 8.dp\n\n Canvas(\n modifier = Modifier\n .fillMaxWidth(0.45f)\n .padding(10.dp)\n .aspectRatio(1f)\n .align(Alignment.Center),\n onDraw = {\n // Background Arc\n drawArc(\n color = Color.LightGray,\n startAngle = start,\n sweepAngle = end,\n useCenter = false,\n style = Stroke(thickness.toPx(), cap = StrokeCap.Square),\n size = Size(size.width, size.height)\n )\n\n // Foreground Arc\n drawArc(\n color = Color(0xFF3db39f),\n startAngle = start,\n sweepAngle = progress(),\n useCenter = false,\n style = Stroke(thickness.toPx(), cap = StrokeCap.Square),\n size = Size(size.width, size.height)\n )\n }\n )\n}\n @Composable\nfun PrizeProgressScreen() {\n\n var score by remember {\n mutableStateOf(0f)\n }\n\n var scoreInput by remember {\n mutableStateOf(\"0\")\n }\n\n Column(\n modifier = Modifier\n .fillMaxSize()\n .background(Color(0xFF6b4cba)),\n horizontalAlignment = Alignment.CenterHorizontally\n ) {\n\n Text(\n modifier = Modifier\n .padding(vertical = 16.dp),\n text = \"Progress for every level up: $maxProgressPerLevel\",\n color = Color.LightGray,\n fontSize = 16.sp\n )\n\n ArcProgressbar(\n score = score,\n )\n\n Button(onClick = {\n score += scoreInput.toFloat()\n }) {\n Text(\"Add Score\")\n }\n\n TextField(\n keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),\n value = scoreInput,\n onValueChange = {\n scoreInput = it\n }\n )\n }\n}\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74522240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19486182/"
] |
74,522,259
|
<p>I want to limit input name to 45 and show message on limit exceed. here below I am attaching my html file and ts file . I using angular 10 . Also is there any other way to apply limit on input and display warning message . Thanks</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>newUserRegForm = new FormGroup({
'username': new FormControl('', Validators.required , Validators.maxLength(45)),
'password': new FormControl('', Validators.required),
'cpassword': new FormControl('', Validators.required),
'role': new FormControl('Security Engineer', Validators.required),
'projectAccessId': new FormControl([]),
'userEmail': new FormControl('', Validators.email),
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><form [formGroup]="newUserRegForm">
<mat-form-field class="registerInputForm" fxFlex>
<mat-label>User Name</mat-label>
<input matInput maxlength="45" formControlName="username">
<mat-error *ngIf="newUserRegForm.get('username').touched &&
newUserRegForm.get('username').hasError('required')">
Username is <strong>required</strong>
</mat-error>
<mat-error *ngIf="newUserRegForm.get('username').touched &&
newUserRegForm.get('username').hasError('maxLength')">
maximum length <strong>exceed</strong>
</mat-error>
</mat-form-field>
<br>
<mat-form-field *ngIf="!data?.user" class="registerInputForm">
<mat-label>Password</mat-label>
<input matInput type="password" formControlName="password">
<mat-error *ngIf="newUserRegForm.get('password').touched &&
newUserRegForm.get('password').hasError('required')">
Password is <strong>required</strong>
</mat-error>
</mat-form-field>
</form></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74522414,
"author": "Tanner",
"author_id": 7375929,
"author_profile": "https://Stackoverflow.com/users/7375929",
"pm_score": 0,
"selected": false,
"text": "maxlength maxLength"
},
{
"answer_id": 74522671,
"author": "Mr. Stash",
"author_id": 13625800,
"author_profile": "https://Stackoverflow.com/users/13625800",
"pm_score": 1,
"selected": false,
"text": "'username': new FormControl('', [Validators.required, Validators.maxLength(45)]),\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74522259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20122571/"
] |
74,522,277
|
<p>I apologise for the title of this question that I know is very unclear, I tried my best.</p>
<p>I have three arrays that need to be sorted, but the tricky rule is the following:</p>
<ul>
<li>the first array needs to increment every time, and when the maximum is obtained, goes back to zero.</li>
<li>the second array has to be sorted starting from the minimum to the maximum.</li>
<li>The third array is the most complicated one: each position MUST correspond to the doublet of numbers that are in the two firsts arrays. For example, if before sorting, the letter <code>'L'</code> in <code>array3</code> was at the same position as the doublet <code>(0, 1)</code> in the two firsts arrays before sorting, it should be the same after sorting.</li>
</ul>
<p>Because the explanation may be not very clear, here is an example of the starting point:</p>
<pre><code>import numpy as np
array1 = np.array([ 0 , 0 , 1 , 1 , 2 ])
array2 = np.array([ 1 , 0 , 1 , 0 , 0 ])
array3 = np.array(['L', 'H', 'O', 'E', 'L'])
</code></pre>
<p>This is the desired output:</p>
<pre><code>array1 = np.array([ 0 , 1 , 2 , 0 , 1 ])
array2 = np.array([ 0 , 0 , 0 , 1 , 1 ])
array3 = np.array(['H', 'E', 'L', 'L', 'O'])
</code></pre>
<p>This looks like a very simple problem, but at the moment I don't have found a solution to it.</p>
|
[
{
"answer_id": 74522414,
"author": "Tanner",
"author_id": 7375929,
"author_profile": "https://Stackoverflow.com/users/7375929",
"pm_score": 0,
"selected": false,
"text": "maxlength maxLength"
},
{
"answer_id": 74522671,
"author": "Mr. Stash",
"author_id": 13625800,
"author_profile": "https://Stackoverflow.com/users/13625800",
"pm_score": 1,
"selected": false,
"text": "'username': new FormControl('', [Validators.required, Validators.maxLength(45)]),\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74522277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8885740/"
] |
74,522,285
|
<p>When attempting to install a package that has a dependency to Microsoft.Graph.Auth, the nuget package manager in VisualStudio errors with this message:</p>
<pre><code> Unable to resolve dependency 'Microsoft.Graph.Auth'. Source(s) used: 'nuget.org'
</code></pre>
<p>No other information is provided.</p>
<p>I can successfully install the Microsoft package manually, however.
The package that depends on the Microsoft package has this in its .nuspec, so as far as I can tell, it should work:</p>
<pre><code> <dependency id="Microsoft.Graph.Auth" version="1.0.0-preview.7" />
</code></pre>
|
[
{
"answer_id": 74522414,
"author": "Tanner",
"author_id": 7375929,
"author_profile": "https://Stackoverflow.com/users/7375929",
"pm_score": 0,
"selected": false,
"text": "maxlength maxLength"
},
{
"answer_id": 74522671,
"author": "Mr. Stash",
"author_id": 13625800,
"author_profile": "https://Stackoverflow.com/users/13625800",
"pm_score": 1,
"selected": false,
"text": "'username': new FormControl('', [Validators.required, Validators.maxLength(45)]),\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74522285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10828089/"
] |
74,522,386
|
<p>Bundler:HTTPError Could not download gem sidekiq-pro-5.3.0. I am unable to install the sidekiq pro gem for rails due to a permissions error.</p>
<p><code>$ bundle install</code></p>
<pre><code>Bundler::HTTPError: Could not download gem from https://gems.contribsys.com/ due to underlying error <bad response Unauthorized 401
(https://gems.contribsys.com/gems/sidekiq-pro-5.3.0.gem)>
</code></pre>
|
[
{
"answer_id": 74522387,
"author": "i0x539",
"author_id": 1406532,
"author_profile": "https://Stackoverflow.com/users/1406532",
"pm_score": 0,
"selected": false,
"text": "$ bundle config --local gems.contribsys.com user:password .bundle/config ---\nBUNDLE_GEMS__CONTRIBSYS__COM: \"user:password\"\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74522386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1406532/"
] |
74,522,399
|
<p>I'm working on a form that initially only shows one input field and when it is focused, it shows other inputs and the submit button.</p>
<p>I also want to hide all those extra fields if the form loses focus while they are empty. And this is the part that I'm not being able to implement.</p>
<p>This is my code: I use a controlled form and a state to handle focus.</p>
<pre class="lang-js prettyprint-override"><code>const FoldableForm = () => {
const [formState, setFormState] = useState(defaultFormState);
const [hasFocus, setFocus] = useState(false);
const handleOnBlur = () => {
if (!formState.message.trim() && !formState.other_input.trim()) {
setFocus(false);
}
};
return (
<form
onFocus={() => setFocus(true)}
onBlur={handleOnBlur}
>
<textarea
name="message"
onChange={(e) => setFormState({ ...formState, message: e.target.value })}
/>
{hasFocus && (
<>
<input
type="text" name="other_input"
onChange={(e) => setFormState({ ...formState, message: e.target.other_input })}
/>
<button type="button">Post comment</button>
</>
)}
</form>
);
}
</code></pre>
<p>Currently, if I type something in the text area, <code>setFocus(false)</code> is never invoked, so it works as intended.
Otherwise, if I leave it empty and click on the other input field, the <code>handleOnBlur</code> function is called, it sets focus to false, so the form is 'minimized'.</p>
<p>This is expected because the blur event (from the textarea) is triggered before the focus event (from the new input field). So I tried to use setTimeout to check, after a fraction of a second if the focus event had already occurred.</p>
<p>To do so, I used a second state (shouldShow) that is updated in a setTimeout inside the handleOnBlue function.</p>
<pre class="lang-js prettyprint-override"><code>setTimeout(() => {
if(!hasFocus) {
setShouldShow(false); // this should cause the form to minimize
}
}, 100);
</code></pre>
<p>However, according to the react lifecycle, the value of hasFocus that is passed to the setTimeout function is at the invocation time, not at execution. So setTimeout here is useless.</p>
<p>I also tried to use references, but I couldn't make it work.</p>
|
[
{
"answer_id": 74522387,
"author": "i0x539",
"author_id": 1406532,
"author_profile": "https://Stackoverflow.com/users/1406532",
"pm_score": 0,
"selected": false,
"text": "$ bundle config --local gems.contribsys.com user:password .bundle/config ---\nBUNDLE_GEMS__CONTRIBSYS__COM: \"user:password\"\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74522399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1919237/"
] |
74,522,486
|
<p>I need to save the <code>json</code> file without the beginning and ending <code>[</code> and <code>]</code> respectively.</p>
<p>Sample data:</p>
<pre><code>import pandas as pd
import json
df = pd.DataFrame({'name' : ['abc', 'pqr', 'xzy'],
'score' : [85, 90, 80],
'address' : ['ab street', 'pq street', 'xy ave']})
df
name score address
0 abc 85 ab street
1 pqr 90 pq street
2 xzy 80 xy ave
</code></pre>
<p>I then try to save the above dataframe using:</p>
<pre><code>jl = json.loads(df.to_json(orient='records'))
f = open('expfile.json', 'w')
json.dump(jl, f, indent = 4)
f.close()
</code></pre>
<p>Output:</p>
<pre><code>[
{
"name": "abc",
"score": 85,
"address": "ab street"
},
{
"name": "pqr",
"score": 90,
"address": "pq street"
},
{
"name": "xzy",
"score": 80,
"address": "xy ave"
}
]
</code></pre>
<p>Which is fine enough, but I need the output without the starting and ending square brackets as below:</p>
<pre><code>{
"name": "abc",
"score": 85,
"address": "ab street"
},
{
"name": "pqr",
"score": 90,
"address": "pq street"
},
{
"name": "xzy",
"score": 80,
"address": "xy ave"
}
</code></pre>
<p>Could someone please let me know how to accomplish the same.
PS I have complex nested dictionary/json structures inside my columns in many of my dataframes, I parsed them using <code>ast.literal_eval</code>.</p>
<p>I tried using <code>to_json(orient = 'records', lines = True)</code> to which I got this error <code>JSONDecodeError: Extra data: line 2 column 1 (char 425)</code>.</p>
|
[
{
"answer_id": 74522727,
"author": "tevemadar",
"author_id": 7916438,
"author_profile": "https://Stackoverflow.com/users/7916438",
"pm_score": 3,
"selected": true,
"text": "jl = [\n {\n \"name\": \"abc\",\n \"score\": 85,\n \"address\": \"ab street\"\n },\n {\n \"name\": \"pqr\",\n \"score\": 90,\n \"address\": \"pq street\"\n },\n {\n \"name\": \"xzy\",\n \"score\": 80,\n \"address\": \"xy ave\"\n }\n]\n\nimport json\nprint(\",\\n\".join(json.dumps(x, indent=4) for x in jl))\n { \n \"name\": \"abc\", \n \"score\": 85, \n \"address\": \"ab street\" \n}, \n{ \n \"name\": \"pqr\", \n \"score\": 90, \n \"address\": \"pq street\" \n}, \n{ \n \"name\": \"xzy\", \n \"score\": 80, \n \"address\": \"xy ave\" \n}\n"
},
{
"answer_id": 74522807,
"author": "CodeMonkey",
"author_id": 543969,
"author_profile": "https://Stackoverflow.com/users/543969",
"pm_score": 0,
"selected": false,
"text": "import pandas as pd\nimport json\n\ndf = pd.DataFrame({'name' : ['abc', 'pqr', 'xzy'],\n 'score' : [85, 90, 80],\n 'address' : ['ab street', 'pq street', 'xy ave']})\n\nwith open(\"out.dat\", \"w\") as fout:\n for idx, row in df.iterrows():\n if idx != 0:\n fout.write(',\\n')\n fout.write(json.dumps(row.to_dict(), indent=4))\n {\n \"name\": \"abc\",\n \"score\": 85,\n \"address\": \"ab street\"\n},\n{\n \"name\": \"pqr\",\n \"score\": 90,\n \"address\": \"pq street\"\n},\n{\n \"name\": \"xzy\",\n \"score\": 80,\n \"address\": \"xy ave\"\n}\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74522486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10722752/"
] |
74,522,488
|
<p>So basically I have the list of many points and I want to extract only unique values.
I have written a function but I have 1 problem: how to avoid printing comma at the end of the list?</p>
<pre><code>def unique(list1):
unique_values = []
for u in list1:
if u not in unique_values:
unique_values.append(u)
for u in unique_values:
print(u, end=", ")
wells = ["U1", "U1", "U3", "U3", "U3", "U5", "U5", "U5", "U7", "U7", "U7", "U7", "U7", "U8", "U8"]
print("The unique values from list are...:", end=" ")
unique(wells)
</code></pre>
<p>my output is for now: "The unique values from list are...: U1, U3, U5, U7, U8,"</p>
|
[
{
"answer_id": 74522592,
"author": "Triceratops",
"author_id": 13440165,
"author_profile": "https://Stackoverflow.com/users/13440165",
"pm_score": 2,
"selected": true,
"text": "NumPy import numpy as np\nx = np.array(['a', 'a', 'b', 'c', 'd', 'd'])\ny = np.unique(x)\nprint(', '.join(y))\n a, b, c, d\n ''' Print unique values in a list or numpy array '''\n\nx = [1, 2, 2, 5, 7, 1, 3]\nprint(x)\n\n# set(x) will return a set of the unique values of x\nu = set(x)\nprint(u)\n\n# remove the curly brackets\nstr_u = str(u).strip(\"}{\")\nprint(str_u)\n 1, 2, 3, 5, 7\n"
},
{
"answer_id": 74522633,
"author": "Harishma Ashok",
"author_id": 20403698,
"author_profile": "https://Stackoverflow.com/users/20403698",
"pm_score": 0,
"selected": false,
"text": "def unique(list1):\n unique_values = []\n for u in list1:\n if u not in unique_values:\n unique_values.append(u)\n return unique_values\n\n\nwells = [\"U1\", \"U1\", \"U3\", \"U3\", \"U3\", \"U5\", \"U5\", \"U5\", \"U7\", \"U7\", \"U7\", \"U7\", \"U7\", \"U8\", \"U8\"]\nreq = unique(wells)\n# prints in list format\nprint(f\"The unique values from list are...: {req}\")\n# prints in string format\nprint(f\"The unique values from list are...: {' '.join(req)}\")\n set(wells)"
},
{
"answer_id": 74522720,
"author": "Michael Ruth",
"author_id": 4583620,
"author_profile": "https://Stackoverflow.com/users/4583620",
"pm_score": 0,
"selected": false,
"text": ", list str.join() set def unique(list1):\n unique_values = set(list1)\n print(', '.join(sorted(unique_values)))\n\n\nwells = [\"U1\", \"U1\", \"U3\", \"U3\", \"U3\", \"U5\", \"U5\", \"U5\", \"U7\", \"U7\", \"U7\", \"U7\", \"U7\", \"U8\", \"U8\"]\nprint(\"The unique values from list are...:\", end=\" \")\nunique(wells)\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74522488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20565136/"
] |
74,522,490
|
<p>I want to write a function that always have a non empty output or fails, but I'm missing a command that read stdin and pipe it to stdout if non-empty or fails like:</p>
<pre class="lang-bash prettyprint-override"><code>example() {
do_something_interesting_here $1 | cat_or_fails
}
</code></pre>
<p>The idea is that if the command <code>cat_or_fails</code> is given an empty input it fails (so the function fails) or the input is output without any changes (like <code>cat</code>).</p>
<p>But I could not find any standard utility capable of that trick, or may be I'm not sure how to use those tools.</p>
|
[
{
"answer_id": 74522592,
"author": "Triceratops",
"author_id": 13440165,
"author_profile": "https://Stackoverflow.com/users/13440165",
"pm_score": 2,
"selected": true,
"text": "NumPy import numpy as np\nx = np.array(['a', 'a', 'b', 'c', 'd', 'd'])\ny = np.unique(x)\nprint(', '.join(y))\n a, b, c, d\n ''' Print unique values in a list or numpy array '''\n\nx = [1, 2, 2, 5, 7, 1, 3]\nprint(x)\n\n# set(x) will return a set of the unique values of x\nu = set(x)\nprint(u)\n\n# remove the curly brackets\nstr_u = str(u).strip(\"}{\")\nprint(str_u)\n 1, 2, 3, 5, 7\n"
},
{
"answer_id": 74522633,
"author": "Harishma Ashok",
"author_id": 20403698,
"author_profile": "https://Stackoverflow.com/users/20403698",
"pm_score": 0,
"selected": false,
"text": "def unique(list1):\n unique_values = []\n for u in list1:\n if u not in unique_values:\n unique_values.append(u)\n return unique_values\n\n\nwells = [\"U1\", \"U1\", \"U3\", \"U3\", \"U3\", \"U5\", \"U5\", \"U5\", \"U7\", \"U7\", \"U7\", \"U7\", \"U7\", \"U8\", \"U8\"]\nreq = unique(wells)\n# prints in list format\nprint(f\"The unique values from list are...: {req}\")\n# prints in string format\nprint(f\"The unique values from list are...: {' '.join(req)}\")\n set(wells)"
},
{
"answer_id": 74522720,
"author": "Michael Ruth",
"author_id": 4583620,
"author_profile": "https://Stackoverflow.com/users/4583620",
"pm_score": 0,
"selected": false,
"text": ", list str.join() set def unique(list1):\n unique_values = set(list1)\n print(', '.join(sorted(unique_values)))\n\n\nwells = [\"U1\", \"U1\", \"U3\", \"U3\", \"U3\", \"U5\", \"U5\", \"U5\", \"U7\", \"U7\", \"U7\", \"U7\", \"U7\", \"U8\", \"U8\"]\nprint(\"The unique values from list are...:\", end=\" \")\nunique(wells)\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74522490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/337772/"
] |
74,522,494
|
<p>I have the following xml</p>
<pre><code><Results>
<form-type>orderform-B</form-type>
<data>
<form-data>
<field>
<name>productid-1</name>
<value>Yes</value>
</field>
<field>
<name>productid-1-qty</name>
<value>2</value>
</field>
<field>
<name>productid-3</name>
<value>Yes</value>
</field>
<field>
<name>productid-4</name>
<value>Yes</value>
</field>
<field>
<name>productid-4-qty</name>
<value>2</value>
</field>
<field>
<name>product-type</name>
<value>productid-5-xl</value>
</field>
<field>
<name>someother-field</name>
<value>xyz</value>
</field>
</form-data>
</data>
</Results>
</code></pre>
<p>And the following XSLT to calculate order total:</p>
<pre><code><xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:variable name="pricelist">
<item id="productid-1">5</item>
<item id="productid-2">5</item>
<item id="productid-3">5</item>
<item id="productid-4">5</item>
<item id="productid-5-sm">5</item>
<item id="productid-5-md">10</item>
<item id="productid-5-xl">15</item>
</xsl:variable>
<xsl:key name="price" match="item" use="@id" />
<xsl:key name="qty" match="field" use="name" />
<xsl:template match="/Results">
<total>
<xsl:variable name="charges">
<xsl:apply-templates select="data/form-data/field[starts-with(name, 'productid-') or starts-with(value, 'productid-')]"/>
</xsl:variable>
<xsl:value-of select="sum($charges/charge)" />
</total>
</xsl:template>
<xsl:template match="field">
<xsl:variable name="price" select="key('price', (name, value), $pricelist)" />
<xsl:variable name="qty" select="key('qty', name)" />
<xsl:if test="$price">
<charge>
<xsl:value-of select="$price * (if($qty) then $qty/value else 1)"/>
</charge>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
</code></pre>
<p>I want to get the value of qty using a key but what I have above returns both the qty fieldname and the qty value where as I only want to return the value so that I can do the calculation?</p>
<ul>
<li>How do I get just the qty value of the fields which have name ending with '-qty'?</li>
<li>I have some products e.g. productid-3 on the order form where there is no quantity value field defined i.e. only the product ordered is listed in which case the quantity of the ordered product is assumed to be 1. How can I refactor the xslt to accommodate that as well so that the price * qty for the charge is price * 1?</li>
</ul>
<p>*** UPDATE ***</p>
<p>Also on the order form, the product ordered can be listed in the value element due to variations of product type e.g.</p>
<pre><code><field>
<name>product-type</name>
<value>productid-5-xl</value>
</field>
</code></pre>
|
[
{
"answer_id": 74522592,
"author": "Triceratops",
"author_id": 13440165,
"author_profile": "https://Stackoverflow.com/users/13440165",
"pm_score": 2,
"selected": true,
"text": "NumPy import numpy as np\nx = np.array(['a', 'a', 'b', 'c', 'd', 'd'])\ny = np.unique(x)\nprint(', '.join(y))\n a, b, c, d\n ''' Print unique values in a list or numpy array '''\n\nx = [1, 2, 2, 5, 7, 1, 3]\nprint(x)\n\n# set(x) will return a set of the unique values of x\nu = set(x)\nprint(u)\n\n# remove the curly brackets\nstr_u = str(u).strip(\"}{\")\nprint(str_u)\n 1, 2, 3, 5, 7\n"
},
{
"answer_id": 74522633,
"author": "Harishma Ashok",
"author_id": 20403698,
"author_profile": "https://Stackoverflow.com/users/20403698",
"pm_score": 0,
"selected": false,
"text": "def unique(list1):\n unique_values = []\n for u in list1:\n if u not in unique_values:\n unique_values.append(u)\n return unique_values\n\n\nwells = [\"U1\", \"U1\", \"U3\", \"U3\", \"U3\", \"U5\", \"U5\", \"U5\", \"U7\", \"U7\", \"U7\", \"U7\", \"U7\", \"U8\", \"U8\"]\nreq = unique(wells)\n# prints in list format\nprint(f\"The unique values from list are...: {req}\")\n# prints in string format\nprint(f\"The unique values from list are...: {' '.join(req)}\")\n set(wells)"
},
{
"answer_id": 74522720,
"author": "Michael Ruth",
"author_id": 4583620,
"author_profile": "https://Stackoverflow.com/users/4583620",
"pm_score": 0,
"selected": false,
"text": ", list str.join() set def unique(list1):\n unique_values = set(list1)\n print(', '.join(sorted(unique_values)))\n\n\nwells = [\"U1\", \"U1\", \"U3\", \"U3\", \"U3\", \"U5\", \"U5\", \"U5\", \"U7\", \"U7\", \"U7\", \"U7\", \"U7\", \"U8\", \"U8\"]\nprint(\"The unique values from list are...:\", end=\" \")\nunique(wells)\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74522494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3928796/"
] |
74,522,498
|
<p>Beginning around 11:30am ET on 11/21/2022, our CI pipelines started failing due to a Checkov update/upgrade notice with an input prompt (see output below).</p>
<p>Is there command line option to skip this check from bridgecrew?</p>
<pre><code>$ checkov
_ _
___| |__ ___ ___| | _______ __
/ __| '_ \ / _ \/ __| |/ / _ \ \ / /
| (__| | | | __/ (__| < (_) \ V /
\___|_| |_|\___|\___|_|\_\___/ \_/
By bridgecrew.io | version: 2.1.244
Update available 2.1.244 -> 2.2.80
Run pip3 install -U checkov to update
Would you like to “level up” your Checkov powers for free? The upgrade includes:
• Command line docker Image scanning
• Software Composition Analysis
• Centralized policy management
• Free bridgecrew.cloud account with API access
• Auto-fix remediation suggestions
• Enabling of VS Code Plugin
• Dashboard visualisation of Checkov scans
• Integration with GitHub for:
◦ Automated Pull Request scanning
◦ Auto remediation PR generation
• Integration with up to 100 cloud resources for:
◦ Automated cloud resource checks
◦ Resource drift detection
and much more...
It's easy and only takes 2 minutes. We can do it right now!
To Level-up, press 'y'...
Level up? (y/n): Traceback (most recent call last):
File "/usr/bin/checkov", line 9, in <module>
sys.exit(run())
File "/usr/lib/python3.10/site-packages/checkov/main.py", line 368, in run
bc_integration.onboarding()
File "/usr/lib/python3.10/site-packages/checkov/common/bridgecrew/platform_integration.py", line 696, in onboarding
reply = self._input_levelup_results()
File "/usr/lib/python3.10/site-packages/checkov/common/bridgecrew/platform_integration.py", line 860, in _input_levelup_results
result = str(input('Level up? (y/n): ')).lower().strip() # nosec
EOFError: EOF when reading a line
Uploading artifacts for failed job
00:01
Uploading artifacts...
WARNING: plan.json: no matching files
ERROR: No files to upload
</code></pre>
<p>I did try to update the version using pip but the old version is still being used. This is a separate issue, and at this point my focus is on avoiding the update check entirely.</p>
<pre><code>bash-5.1# checkov --version
2.1.244
bash-5.1# pip3 install -U checkov
... (Lots of output)
bash-5.1# checkov --version
2.1.244
</code></pre>
<p>This is my .checkov.yaml file:</p>
<pre><code>compact: true
quiet: true
skip-download: false
download-external-modules: true
directory:
- ./
skip-check:
- CKV_AWS_18
- CKV_AWS_50
- CKV_AWS_115
- CKV_AWS_116
- CKV_AWS_117
- CKV_AWS_158
- CKV_AWS_173
- CKV_OPENAPI_4 # some APIs are public
- CKV_OPENAPI_5 # some APIs are public
- LOW
</code></pre>
|
[
{
"answer_id": 74646609,
"author": "Dominic O'Connor",
"author_id": 1291767,
"author_profile": "https://Stackoverflow.com/users/1291767",
"pm_score": 1,
"selected": true,
"text": "checkov --config-file .checkov.yaml\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74522498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1291767/"
] |
74,522,515
|
<p>I was wondering which Google Apps Script function may help me to split a Google Sheets cell value into <code>n</code> parts (given a separator) and replicate the whole row as different occurrences for that split. So, f.i., given this table:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: center;">Name</th>
<th style="text-align: center;">Country</th>
<th style="text-align: center;">Sport</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: center;">John</td>
<td style="text-align: center;">USA</td>
<td style="text-align: center;">Basketball_Golf_Tennis</td>
</tr>
<tr>
<td style="text-align: center;">Mary</td>
<td style="text-align: center;">Canada</td>
<td style="text-align: center;">Tennis_Golf</td>
</tr>
</tbody>
</table>
</div>
<p>the desired output should be:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: center;">Name</th>
<th style="text-align: center;">Country</th>
<th style="text-align: center;">Sport</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: center;">John</td>
<td style="text-align: center;">USA</td>
<td style="text-align: center;">Basketball</td>
</tr>
<tr>
<td style="text-align: center;">John</td>
<td style="text-align: center;">USA</td>
<td style="text-align: center;">Golf</td>
</tr>
<tr>
<td style="text-align: center;">John</td>
<td style="text-align: center;">USA</td>
<td style="text-align: center;">Tennis</td>
</tr>
<tr>
<td style="text-align: center;">Mary</td>
<td style="text-align: center;">Canada</td>
<td style="text-align: center;">Tennis</td>
</tr>
<tr>
<td style="text-align: center;">Mary</td>
<td style="text-align: center;">Canada</td>
<td style="text-align: center;">Golf</td>
</tr>
</tbody>
</table>
</div>
<p>In this example, the separator is the char <code>_</code></p>
|
[
{
"answer_id": 74522822,
"author": "pgSystemTester",
"author_id": 11732320,
"author_profile": "https://Stackoverflow.com/users/11732320",
"pm_score": 3,
"selected": true,
"text": "/**\n * Splits data\n *\n * @param {array} theRange The range of data.\n * @param {string} theSplitter The text used to split.\n * @return the new table\n * @customfunction\n */\nfunction goUSA(theRange, theSplitter) {\n const splitColumn = 2;\n\n var result = [];\n for (r = 0; r < theRange.length; r++) {\n var aRow = theRange[r];\n\n //skips empty rows, enabling ability to select entire column\n if (aRow.join('') != '') {\n var tempSplit = aRow[splitColumn].split(theSplitter);\n for (q = 0; q < tempSplit.length; q++) {\n result.push([aRow[0], aRow[1], tempSplit[q]]);\n }\n }\n }\n return result;\n}\n"
},
{
"answer_id": 74523036,
"author": "Cooper",
"author_id": 7215091,
"author_profile": "https://Stackoverflow.com/users/7215091",
"pm_score": 1,
"selected": false,
"text": "function brkaprt() {\n const ss = SpreadsheetApp.getActive();\n const sh = ss.getSheetByName(\"Sheet0\");\n const osh = ss.getSheetByName(\"Sheet1\");\n osh.clearContents();\n const vs = sh.getRange(2,1, sh.getLastRow() - 1, sh.getLastColumn()).getValues();\n let obj = {pA:[]};\n let o = vs.reduce((ac,[a,b,c],i) => {\n c.split(\"_\").forEach(e =>ac.push([a,b,e]) )\n return ac;\n },[]);\n o.unshift([\"Name\",\"Country\",\"Sport\"]); \n Logger.log(JSON.stringify(o));\n osh.getRange(1,1,o.length,o[0].length).setValues(o);\n\n}\n\nExecution log\n10:56:15 AM Notice Execution started\n10:56:16 AM Info [[\"Name\",\"Country\",\"Sport\"],[\"John\",\"USA\",\"Basketball\"],[\"John\",\"USA\",\"Golf\"],[\"John\",\"USA\",\"Tennis\"],[\"Mary\",\"Canada\",\"Tennis\"],[\"Mary\",\"Canada\",\"Golf\"]]\n10:56:17 AM Notice Execution completed\n"
},
{
"answer_id": 74523109,
"author": "player0",
"author_id": 5632629,
"author_profile": "https://Stackoverflow.com/users/5632629",
"pm_score": 2,
"selected": false,
"text": "=INDEX(QUERY(SPLIT(FLATTEN(IF(IFERROR(SPLIT(C1:C, \"_\"))=\"\",, \n A1:A&\"\"&B1:B&\"\"&SPLIT(C1:C, \"_\"))), \"\"), \"where Col2 is not null\", ))\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74522515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3257689/"
] |
74,522,522
|
<p>I'm trying to retrieve some data from a service, and I'm working with a mutablelist to store the objects. The problem is that I need to add the retrived data to this mutablelist, but addAll says me that the type is mismatched.</p>
<p><a href="https://i.stack.imgur.com/iiX1t.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iiX1t.png" alt="screenshot" /></a></p>
|
[
{
"answer_id": 74522822,
"author": "pgSystemTester",
"author_id": 11732320,
"author_profile": "https://Stackoverflow.com/users/11732320",
"pm_score": 3,
"selected": true,
"text": "/**\n * Splits data\n *\n * @param {array} theRange The range of data.\n * @param {string} theSplitter The text used to split.\n * @return the new table\n * @customfunction\n */\nfunction goUSA(theRange, theSplitter) {\n const splitColumn = 2;\n\n var result = [];\n for (r = 0; r < theRange.length; r++) {\n var aRow = theRange[r];\n\n //skips empty rows, enabling ability to select entire column\n if (aRow.join('') != '') {\n var tempSplit = aRow[splitColumn].split(theSplitter);\n for (q = 0; q < tempSplit.length; q++) {\n result.push([aRow[0], aRow[1], tempSplit[q]]);\n }\n }\n }\n return result;\n}\n"
},
{
"answer_id": 74523036,
"author": "Cooper",
"author_id": 7215091,
"author_profile": "https://Stackoverflow.com/users/7215091",
"pm_score": 1,
"selected": false,
"text": "function brkaprt() {\n const ss = SpreadsheetApp.getActive();\n const sh = ss.getSheetByName(\"Sheet0\");\n const osh = ss.getSheetByName(\"Sheet1\");\n osh.clearContents();\n const vs = sh.getRange(2,1, sh.getLastRow() - 1, sh.getLastColumn()).getValues();\n let obj = {pA:[]};\n let o = vs.reduce((ac,[a,b,c],i) => {\n c.split(\"_\").forEach(e =>ac.push([a,b,e]) )\n return ac;\n },[]);\n o.unshift([\"Name\",\"Country\",\"Sport\"]); \n Logger.log(JSON.stringify(o));\n osh.getRange(1,1,o.length,o[0].length).setValues(o);\n\n}\n\nExecution log\n10:56:15 AM Notice Execution started\n10:56:16 AM Info [[\"Name\",\"Country\",\"Sport\"],[\"John\",\"USA\",\"Basketball\"],[\"John\",\"USA\",\"Golf\"],[\"John\",\"USA\",\"Tennis\"],[\"Mary\",\"Canada\",\"Tennis\"],[\"Mary\",\"Canada\",\"Golf\"]]\n10:56:17 AM Notice Execution completed\n"
},
{
"answer_id": 74523109,
"author": "player0",
"author_id": 5632629,
"author_profile": "https://Stackoverflow.com/users/5632629",
"pm_score": 2,
"selected": false,
"text": "=INDEX(QUERY(SPLIT(FLATTEN(IF(IFERROR(SPLIT(C1:C, \"_\"))=\"\",, \n A1:A&\"\"&B1:B&\"\"&SPLIT(C1:C, \"_\"))), \"\"), \"where Col2 is not null\", ))\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74522522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2129561/"
] |
74,522,549
|
<p>I am fairly new to angular, I am using <strong>Angular 15</strong>, I basically have an Rest API response that I want to parse and show in the UI using angular. For that I used <code>HttpClient</code> and <code>GET</code> request to parse the response.</p>
<p>The code for <code>app.component.ts</code> is:</p>
<pre><code>import { HttpClient, HttpResponse } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent{
constructor(private http: HttpClient){}
posts: any[] = [];
loadPosts(){
this.http
.get('https://jsonplaceholder.typicode.com/todos/1')
.subscribe((posts: any[])=>{
this.posts=posts;
});
}
}
</code></pre>
<p><strong>EDIT</strong> I changed the link for the get request call so that it can actually be used.</p>
<p>The code for <code>app.component.html</code> is:</p>
<pre><code>This is a template for app component html
<br>
<button type="button" (click)="loadPosts()" class="btn btn-primary">Get Response Body</button>
<br>
<div *ngFor="let post of posts">
<h1>{{ posts.includes }}</h1>
<p> {{ posts.keys }} </p>
</div>
<router-outlet></router-outlet>
</code></pre>
<p>I am trying to get certain values from the response like <code>includes</code> and <code>keys</code> from the API call that I want to parse and show in the UI. That's why I used ngFor to iterate through the response and show only those sections.</p>
<p>My main issue is I'm getting this error:</p>
<pre><code>src/app/app.component.ts:19:16 - error TS2769: No overload matches this call.
Overload 1 of 3, '(observer?: Partial<Observer<Object>> | undefined): Subscription', gave the following error.
Type '(posts: any[]) => void' has no properties in common with type 'Partial<Observer<Object>>'.
Overload 2 of 3, '(next: (value: Object) => void): Subscription', gave the following error.
Argument of type '(posts: any[]) => void' is not assignable to parameter of type '(value: Object) => void'.
Types of parameters 'posts' and 'value' are incompatible.
The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?
Type 'Object' is missing the following properties from type 'any[]': length, pop, push, concat, and 29 more.
Overload 3 of 3, '(next?: ((value: Object) => void) | null | undefined, error?: ((error: any) => void) | null | undefined, complete?: (() => void) | null | undefined): Subscription', gave the following error.
Argument of type '(posts: any[]) => void' is not assignable to parameter of type '(value: Object) => void'.
Types of parameters 'posts' and 'value' are incompatible.
Type 'Object' is not assignable to type 'any[]'.
The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?
19 .subscribe((posts: any[])=>{
~~~~~~~~~~~~~~~~~
</code></pre>
<p>When I use <code>[]</code> In</p>
<pre><code>.get('https://cdn.contentful.com/myCustomApiLink')
.subscribe((posts: any[])=>{
this.posts=posts;
</code></pre>
<p>but without using <code>[]</code> I'm getting error:</p>
<pre><code>app.component.ts:19 ERROR Error: NG0900: Error trying to diff '[object Object]'. Only arrays and iterables are allowed
at DefaultIterableDiffer.diff (core.mjs:28817:19)
at NgForOf.ngDoCheck (common.mjs:3213:42)
at callHook (core.mjs:2758:18)
at callHooks (core.mjs:2717:17)
at executeCheckHooks (core.mjs:2649:5)
at refreshView (core.mjs:12084:21)
at refreshComponent (core.mjs:13208:13)
at refreshChildComponents (core.mjs:11865:9)
at refreshView (core.mjs:12125:13)
at detectChangesInternal (core.mjs:13352:9)
load (async)
loadPosts @ app.component.ts:19
AppComponent_Template_button_click_2_listener @ app.component.html:3
Show 82 more frames
</code></pre>
<p>in the console.</p>
<p>Any Help is appreciated! Thanks!</p>
|
[
{
"answer_id": 74522822,
"author": "pgSystemTester",
"author_id": 11732320,
"author_profile": "https://Stackoverflow.com/users/11732320",
"pm_score": 3,
"selected": true,
"text": "/**\n * Splits data\n *\n * @param {array} theRange The range of data.\n * @param {string} theSplitter The text used to split.\n * @return the new table\n * @customfunction\n */\nfunction goUSA(theRange, theSplitter) {\n const splitColumn = 2;\n\n var result = [];\n for (r = 0; r < theRange.length; r++) {\n var aRow = theRange[r];\n\n //skips empty rows, enabling ability to select entire column\n if (aRow.join('') != '') {\n var tempSplit = aRow[splitColumn].split(theSplitter);\n for (q = 0; q < tempSplit.length; q++) {\n result.push([aRow[0], aRow[1], tempSplit[q]]);\n }\n }\n }\n return result;\n}\n"
},
{
"answer_id": 74523036,
"author": "Cooper",
"author_id": 7215091,
"author_profile": "https://Stackoverflow.com/users/7215091",
"pm_score": 1,
"selected": false,
"text": "function brkaprt() {\n const ss = SpreadsheetApp.getActive();\n const sh = ss.getSheetByName(\"Sheet0\");\n const osh = ss.getSheetByName(\"Sheet1\");\n osh.clearContents();\n const vs = sh.getRange(2,1, sh.getLastRow() - 1, sh.getLastColumn()).getValues();\n let obj = {pA:[]};\n let o = vs.reduce((ac,[a,b,c],i) => {\n c.split(\"_\").forEach(e =>ac.push([a,b,e]) )\n return ac;\n },[]);\n o.unshift([\"Name\",\"Country\",\"Sport\"]); \n Logger.log(JSON.stringify(o));\n osh.getRange(1,1,o.length,o[0].length).setValues(o);\n\n}\n\nExecution log\n10:56:15 AM Notice Execution started\n10:56:16 AM Info [[\"Name\",\"Country\",\"Sport\"],[\"John\",\"USA\",\"Basketball\"],[\"John\",\"USA\",\"Golf\"],[\"John\",\"USA\",\"Tennis\"],[\"Mary\",\"Canada\",\"Tennis\"],[\"Mary\",\"Canada\",\"Golf\"]]\n10:56:17 AM Notice Execution completed\n"
},
{
"answer_id": 74523109,
"author": "player0",
"author_id": 5632629,
"author_profile": "https://Stackoverflow.com/users/5632629",
"pm_score": 2,
"selected": false,
"text": "=INDEX(QUERY(SPLIT(FLATTEN(IF(IFERROR(SPLIT(C1:C, \"_\"))=\"\",, \n A1:A&\"\"&B1:B&\"\"&SPLIT(C1:C, \"_\"))), \"\"), \"where Col2 is not null\", ))\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74522549",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18061379/"
] |
74,522,566
|
<p>Hello this is a pretty simple question but i wanted to follow the dry principles correctly and couldn't think of a way to do it without repeating code</p>
<p>so given game outcomes in this format</p>
<p><code>game outcome = [['wins', 'loses'], ['loses', 'wins'], ['loses', 'wins']]</code></p>
<p>the gameoutcome[0][0] till gameoutcome[2][0] are all user game outcomes so for that paticular user he won and lost 2 whereas the computer won twice but lost once</p>
<p>what i want to do is aggregate the users out comes and the computer outcomes based on the number of wins then finally in this scenario</p>
<pre><code>if(computer_outcome > user_outcome):
computer wins
else
user wins
</code></pre>
|
[
{
"answer_id": 74522822,
"author": "pgSystemTester",
"author_id": 11732320,
"author_profile": "https://Stackoverflow.com/users/11732320",
"pm_score": 3,
"selected": true,
"text": "/**\n * Splits data\n *\n * @param {array} theRange The range of data.\n * @param {string} theSplitter The text used to split.\n * @return the new table\n * @customfunction\n */\nfunction goUSA(theRange, theSplitter) {\n const splitColumn = 2;\n\n var result = [];\n for (r = 0; r < theRange.length; r++) {\n var aRow = theRange[r];\n\n //skips empty rows, enabling ability to select entire column\n if (aRow.join('') != '') {\n var tempSplit = aRow[splitColumn].split(theSplitter);\n for (q = 0; q < tempSplit.length; q++) {\n result.push([aRow[0], aRow[1], tempSplit[q]]);\n }\n }\n }\n return result;\n}\n"
},
{
"answer_id": 74523036,
"author": "Cooper",
"author_id": 7215091,
"author_profile": "https://Stackoverflow.com/users/7215091",
"pm_score": 1,
"selected": false,
"text": "function brkaprt() {\n const ss = SpreadsheetApp.getActive();\n const sh = ss.getSheetByName(\"Sheet0\");\n const osh = ss.getSheetByName(\"Sheet1\");\n osh.clearContents();\n const vs = sh.getRange(2,1, sh.getLastRow() - 1, sh.getLastColumn()).getValues();\n let obj = {pA:[]};\n let o = vs.reduce((ac,[a,b,c],i) => {\n c.split(\"_\").forEach(e =>ac.push([a,b,e]) )\n return ac;\n },[]);\n o.unshift([\"Name\",\"Country\",\"Sport\"]); \n Logger.log(JSON.stringify(o));\n osh.getRange(1,1,o.length,o[0].length).setValues(o);\n\n}\n\nExecution log\n10:56:15 AM Notice Execution started\n10:56:16 AM Info [[\"Name\",\"Country\",\"Sport\"],[\"John\",\"USA\",\"Basketball\"],[\"John\",\"USA\",\"Golf\"],[\"John\",\"USA\",\"Tennis\"],[\"Mary\",\"Canada\",\"Tennis\"],[\"Mary\",\"Canada\",\"Golf\"]]\n10:56:17 AM Notice Execution completed\n"
},
{
"answer_id": 74523109,
"author": "player0",
"author_id": 5632629,
"author_profile": "https://Stackoverflow.com/users/5632629",
"pm_score": 2,
"selected": false,
"text": "=INDEX(QUERY(SPLIT(FLATTEN(IF(IFERROR(SPLIT(C1:C, \"_\"))=\"\",, \n A1:A&\"\"&B1:B&\"\"&SPLIT(C1:C, \"_\"))), \"\"), \"where Col2 is not null\", ))\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74522566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10872352/"
] |
74,522,586
|
<p>I had stuck on how to sort a list into a new list with diffirent sturcture, would if someone could help me with this issue, Thank you in advance.
List with type</p>
<pre><code>
public class PartOrders
{
public string orderNumber{ get; set; }
public DateTime createdDate { get; set; }
public string description { get; set; }
public string name{ get; set; }
public DateTime performedDateTime { get; set; }
public Catigory catigory { get; set; }
}
public class Catigory
{
public string type{ get; set; }
public string Name{ get; set; }
}
</code></pre>
<p>in the list there are many item with same orderNumber and createdDate</p>
<pre><code>my question is how to make new list with type :
public class PartOrders
{
public string orderNumber{ get; set; }
public DateTime createdDate { get; set; }
public List<Data> orderDate { get; set; }
}
public class Data
{
public string description { get; set; }
public string name{ get; set; }
public DateTime performedDateTime { get; set; }
public Catigory catigory { get; set; }
}
i apprisiate your help
</code></pre>
<p>i tried with readinonal way looping with foreach and if condition but it was very comlicated and slow
result will be with this format</p>
<pre><code>
</code></pre>
<pre><code></code></pre>
|
[
{
"answer_id": 74522822,
"author": "pgSystemTester",
"author_id": 11732320,
"author_profile": "https://Stackoverflow.com/users/11732320",
"pm_score": 3,
"selected": true,
"text": "/**\n * Splits data\n *\n * @param {array} theRange The range of data.\n * @param {string} theSplitter The text used to split.\n * @return the new table\n * @customfunction\n */\nfunction goUSA(theRange, theSplitter) {\n const splitColumn = 2;\n\n var result = [];\n for (r = 0; r < theRange.length; r++) {\n var aRow = theRange[r];\n\n //skips empty rows, enabling ability to select entire column\n if (aRow.join('') != '') {\n var tempSplit = aRow[splitColumn].split(theSplitter);\n for (q = 0; q < tempSplit.length; q++) {\n result.push([aRow[0], aRow[1], tempSplit[q]]);\n }\n }\n }\n return result;\n}\n"
},
{
"answer_id": 74523036,
"author": "Cooper",
"author_id": 7215091,
"author_profile": "https://Stackoverflow.com/users/7215091",
"pm_score": 1,
"selected": false,
"text": "function brkaprt() {\n const ss = SpreadsheetApp.getActive();\n const sh = ss.getSheetByName(\"Sheet0\");\n const osh = ss.getSheetByName(\"Sheet1\");\n osh.clearContents();\n const vs = sh.getRange(2,1, sh.getLastRow() - 1, sh.getLastColumn()).getValues();\n let obj = {pA:[]};\n let o = vs.reduce((ac,[a,b,c],i) => {\n c.split(\"_\").forEach(e =>ac.push([a,b,e]) )\n return ac;\n },[]);\n o.unshift([\"Name\",\"Country\",\"Sport\"]); \n Logger.log(JSON.stringify(o));\n osh.getRange(1,1,o.length,o[0].length).setValues(o);\n\n}\n\nExecution log\n10:56:15 AM Notice Execution started\n10:56:16 AM Info [[\"Name\",\"Country\",\"Sport\"],[\"John\",\"USA\",\"Basketball\"],[\"John\",\"USA\",\"Golf\"],[\"John\",\"USA\",\"Tennis\"],[\"Mary\",\"Canada\",\"Tennis\"],[\"Mary\",\"Canada\",\"Golf\"]]\n10:56:17 AM Notice Execution completed\n"
},
{
"answer_id": 74523109,
"author": "player0",
"author_id": 5632629,
"author_profile": "https://Stackoverflow.com/users/5632629",
"pm_score": 2,
"selected": false,
"text": "=INDEX(QUERY(SPLIT(FLATTEN(IF(IFERROR(SPLIT(C1:C, \"_\"))=\"\",, \n A1:A&\"\"&B1:B&\"\"&SPLIT(C1:C, \"_\"))), \"\"), \"where Col2 is not null\", ))\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74522586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20164392/"
] |
74,522,597
|
<pre><code><p>Dostępne: </p><p style={{color:'green'}}>{props.ile_aktywne}</p><p>Niedostępne: </p><p style={{color:'red'}}>{props.ile_nieaktywne}</p>
</code></pre>
<p><a href="https://i.stack.imgur.com/NQo5e.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NQo5e.png" alt="enter image description here" /></a></p>
<p>I want it to format as two lines</p>
<ol>
<li>"Dostępne: 1"</li>
<li>"Niedostępne: 2"</li>
</ol>
|
[
{
"answer_id": 74522822,
"author": "pgSystemTester",
"author_id": 11732320,
"author_profile": "https://Stackoverflow.com/users/11732320",
"pm_score": 3,
"selected": true,
"text": "/**\n * Splits data\n *\n * @param {array} theRange The range of data.\n * @param {string} theSplitter The text used to split.\n * @return the new table\n * @customfunction\n */\nfunction goUSA(theRange, theSplitter) {\n const splitColumn = 2;\n\n var result = [];\n for (r = 0; r < theRange.length; r++) {\n var aRow = theRange[r];\n\n //skips empty rows, enabling ability to select entire column\n if (aRow.join('') != '') {\n var tempSplit = aRow[splitColumn].split(theSplitter);\n for (q = 0; q < tempSplit.length; q++) {\n result.push([aRow[0], aRow[1], tempSplit[q]]);\n }\n }\n }\n return result;\n}\n"
},
{
"answer_id": 74523036,
"author": "Cooper",
"author_id": 7215091,
"author_profile": "https://Stackoverflow.com/users/7215091",
"pm_score": 1,
"selected": false,
"text": "function brkaprt() {\n const ss = SpreadsheetApp.getActive();\n const sh = ss.getSheetByName(\"Sheet0\");\n const osh = ss.getSheetByName(\"Sheet1\");\n osh.clearContents();\n const vs = sh.getRange(2,1, sh.getLastRow() - 1, sh.getLastColumn()).getValues();\n let obj = {pA:[]};\n let o = vs.reduce((ac,[a,b,c],i) => {\n c.split(\"_\").forEach(e =>ac.push([a,b,e]) )\n return ac;\n },[]);\n o.unshift([\"Name\",\"Country\",\"Sport\"]); \n Logger.log(JSON.stringify(o));\n osh.getRange(1,1,o.length,o[0].length).setValues(o);\n\n}\n\nExecution log\n10:56:15 AM Notice Execution started\n10:56:16 AM Info [[\"Name\",\"Country\",\"Sport\"],[\"John\",\"USA\",\"Basketball\"],[\"John\",\"USA\",\"Golf\"],[\"John\",\"USA\",\"Tennis\"],[\"Mary\",\"Canada\",\"Tennis\"],[\"Mary\",\"Canada\",\"Golf\"]]\n10:56:17 AM Notice Execution completed\n"
},
{
"answer_id": 74523109,
"author": "player0",
"author_id": 5632629,
"author_profile": "https://Stackoverflow.com/users/5632629",
"pm_score": 2,
"selected": false,
"text": "=INDEX(QUERY(SPLIT(FLATTEN(IF(IFERROR(SPLIT(C1:C, \"_\"))=\"\",, \n A1:A&\"\"&B1:B&\"\"&SPLIT(C1:C, \"_\"))), \"\"), \"where Col2 is not null\", ))\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74522597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12618447/"
] |
74,522,667
|
<p>I have a react project where I have 3 dropdown menus side by side and upon clicking one they all will toggle instead of just one. I tried to use a dropdown component but I'm not sure I can get it working correctly with my code. Can you show me how to fix this? I have my code uploaded to code sandbox here <a href="https://codesandbox.io/p/github/rachelharu/react-blogr-landingpage/draft/gifted-mccarthy?file=%2Fsrc%2Fcomponents%2FNavbar.jsx" rel="nofollow noreferrer">link to code</a> due note that it will not display on mobile screens yet so you will need to look at it in the full desktop version of the site.</p>
<pre><code>import { useState } from 'react';
import {
iconHamburger,
iconClose,
iconArrowDark,
iconArrowLight,
logo,
} from '../assets';
import { navLinks } from '../constants';
const Navbar = () => {
const [toggle, setToggle] = useState(false);
return (
<nav className='w-full flex py-6 ml-10 justify-between items-center navbar'>
<img src={logo} alt='blogr' className='w-[75px] h-[30px]' />
<ul className='list-none sm:flex hidden ml-10 justify-start items-center flex-1'>
{navLinks.map((nav, index) => (
<li
key={nav.id}
className={`font-overpass
font-normal
text-[12px] ${index === navLinks.length - 1 ? 'mr-0' : 'mr-10'}
text-white`}>
<a
className='float-left'
onClick={() => setToggle((prev) => !prev)}
href={`#${nav.id}`}>
{nav.title}
<img
className='ml-2 mt-1 cursor-pointer float-right w-[9px] h-[6px]'
src={iconArrowLight}
/>
</a>
<div className={`${toggle ? 'hidden' : 'relative'} mr-10`}>
<ul className='list-none mt-10 absolute'>
{nav.links.map((link, index) => (
<li
key={link.name}
className={`font-overpass text-black cursor-pointer ${
index !== nav.links.length - 1 ? 'mb-4' : 'mb-0'}`}>
{link.name}
</li>
))}
</ul>
</div>
</li>
))}
</ul>
</nav>
);
};
export default Navbar;
</code></pre>
<p>navlinks</p>
<pre><code>import { iconArrowLight } from "../assets"
export const navLinks = [
{
id: 'product',
title: 'Product',
img: iconArrowLight,
links: [
{
name: 'Overview'
},
{
name: 'Pricing'
},
{
name: 'Marketplace'
},
{
name: 'Features'
},
{
name: 'Integrations'
},
],
},
{
id: 'company',
title: 'Company',
img: iconArrowLight,
links: [
{
name: 'About'
},
{
name: 'Team'
},
{
name: 'Blog'
},
{
name: 'Career'
},
],
},
{
id: 'connect',
title: 'Connect',
img: iconArrowLight,
links: [
{
name: 'Contact'
},
{
name: 'Newsletter'
},
{
name: 'LinkedIn'
},
],
},
]
</code></pre>
|
[
{
"answer_id": 74522822,
"author": "pgSystemTester",
"author_id": 11732320,
"author_profile": "https://Stackoverflow.com/users/11732320",
"pm_score": 3,
"selected": true,
"text": "/**\n * Splits data\n *\n * @param {array} theRange The range of data.\n * @param {string} theSplitter The text used to split.\n * @return the new table\n * @customfunction\n */\nfunction goUSA(theRange, theSplitter) {\n const splitColumn = 2;\n\n var result = [];\n for (r = 0; r < theRange.length; r++) {\n var aRow = theRange[r];\n\n //skips empty rows, enabling ability to select entire column\n if (aRow.join('') != '') {\n var tempSplit = aRow[splitColumn].split(theSplitter);\n for (q = 0; q < tempSplit.length; q++) {\n result.push([aRow[0], aRow[1], tempSplit[q]]);\n }\n }\n }\n return result;\n}\n"
},
{
"answer_id": 74523036,
"author": "Cooper",
"author_id": 7215091,
"author_profile": "https://Stackoverflow.com/users/7215091",
"pm_score": 1,
"selected": false,
"text": "function brkaprt() {\n const ss = SpreadsheetApp.getActive();\n const sh = ss.getSheetByName(\"Sheet0\");\n const osh = ss.getSheetByName(\"Sheet1\");\n osh.clearContents();\n const vs = sh.getRange(2,1, sh.getLastRow() - 1, sh.getLastColumn()).getValues();\n let obj = {pA:[]};\n let o = vs.reduce((ac,[a,b,c],i) => {\n c.split(\"_\").forEach(e =>ac.push([a,b,e]) )\n return ac;\n },[]);\n o.unshift([\"Name\",\"Country\",\"Sport\"]); \n Logger.log(JSON.stringify(o));\n osh.getRange(1,1,o.length,o[0].length).setValues(o);\n\n}\n\nExecution log\n10:56:15 AM Notice Execution started\n10:56:16 AM Info [[\"Name\",\"Country\",\"Sport\"],[\"John\",\"USA\",\"Basketball\"],[\"John\",\"USA\",\"Golf\"],[\"John\",\"USA\",\"Tennis\"],[\"Mary\",\"Canada\",\"Tennis\"],[\"Mary\",\"Canada\",\"Golf\"]]\n10:56:17 AM Notice Execution completed\n"
},
{
"answer_id": 74523109,
"author": "player0",
"author_id": 5632629,
"author_profile": "https://Stackoverflow.com/users/5632629",
"pm_score": 2,
"selected": false,
"text": "=INDEX(QUERY(SPLIT(FLATTEN(IF(IFERROR(SPLIT(C1:C, \"_\"))=\"\",, \n A1:A&\"\"&B1:B&\"\"&SPLIT(C1:C, \"_\"))), \"\"), \"where Col2 is not null\", ))\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74522667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16582373/"
] |
74,522,697
|
<p>I’m having a problem with my code. my while loop 3 times when its meant to loop once i've tried everything i know and it's not working</p>
<pre><code>import java.util.Scanner;
public class validInput {
public static void main (String[] args) {
Scanner key = new Scanner(System.in);
System.out.print("Enter a number: ");
String num = key.next();
boolean isNumeric = true;
isNumeric = num.matches("-?\\d+(\\.\\d+)?");
while ((!isNumeric)) {
System.out.println("You must enter an integer");
num = key.next();
}
System.out.print("Valid");
}
}
</code></pre>
<pre><code># outputs Enter a number: my first mistake
# You must enter an integer
# You must enter an integer
# You must enter an integer
# my first mistake
</code></pre>
|
[
{
"answer_id": 74522822,
"author": "pgSystemTester",
"author_id": 11732320,
"author_profile": "https://Stackoverflow.com/users/11732320",
"pm_score": 3,
"selected": true,
"text": "/**\n * Splits data\n *\n * @param {array} theRange The range of data.\n * @param {string} theSplitter The text used to split.\n * @return the new table\n * @customfunction\n */\nfunction goUSA(theRange, theSplitter) {\n const splitColumn = 2;\n\n var result = [];\n for (r = 0; r < theRange.length; r++) {\n var aRow = theRange[r];\n\n //skips empty rows, enabling ability to select entire column\n if (aRow.join('') != '') {\n var tempSplit = aRow[splitColumn].split(theSplitter);\n for (q = 0; q < tempSplit.length; q++) {\n result.push([aRow[0], aRow[1], tempSplit[q]]);\n }\n }\n }\n return result;\n}\n"
},
{
"answer_id": 74523036,
"author": "Cooper",
"author_id": 7215091,
"author_profile": "https://Stackoverflow.com/users/7215091",
"pm_score": 1,
"selected": false,
"text": "function brkaprt() {\n const ss = SpreadsheetApp.getActive();\n const sh = ss.getSheetByName(\"Sheet0\");\n const osh = ss.getSheetByName(\"Sheet1\");\n osh.clearContents();\n const vs = sh.getRange(2,1, sh.getLastRow() - 1, sh.getLastColumn()).getValues();\n let obj = {pA:[]};\n let o = vs.reduce((ac,[a,b,c],i) => {\n c.split(\"_\").forEach(e =>ac.push([a,b,e]) )\n return ac;\n },[]);\n o.unshift([\"Name\",\"Country\",\"Sport\"]); \n Logger.log(JSON.stringify(o));\n osh.getRange(1,1,o.length,o[0].length).setValues(o);\n\n}\n\nExecution log\n10:56:15 AM Notice Execution started\n10:56:16 AM Info [[\"Name\",\"Country\",\"Sport\"],[\"John\",\"USA\",\"Basketball\"],[\"John\",\"USA\",\"Golf\"],[\"John\",\"USA\",\"Tennis\"],[\"Mary\",\"Canada\",\"Tennis\"],[\"Mary\",\"Canada\",\"Golf\"]]\n10:56:17 AM Notice Execution completed\n"
},
{
"answer_id": 74523109,
"author": "player0",
"author_id": 5632629,
"author_profile": "https://Stackoverflow.com/users/5632629",
"pm_score": 2,
"selected": false,
"text": "=INDEX(QUERY(SPLIT(FLATTEN(IF(IFERROR(SPLIT(C1:C, \"_\"))=\"\",, \n A1:A&\"\"&B1:B&\"\"&SPLIT(C1:C, \"_\"))), \"\"), \"where Col2 is not null\", ))\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74522697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20565073/"
] |
74,522,751
|
<p>I have a 2D array named <strong>$props</strong>, the structure is as follows,</p>
<pre><code>$props = [
['name' => 'Mathmatics', 'time' => '03:01:PM - 04:50:PM'],
['name' => 'History', 'time' => '11:30:AM - 01:30:PM'],
['name' => 'French', 'time' => '01:31:PM - 03:00:PM'],
];
</code></pre>
<p>I need to sort the array by 'time' key, to get the following result:</p>
<pre><code>[
['name' => 'History', 'time' => '11:30:AM - 01:30:PM'],
['name' => 'French', 'time' => '01:31:PM - 03:00:PM'],
['name' => 'Mathmatics', 'time' => '03:01:PM - 04:50:PM'],
];
</code></pre>
<p>I have found a solution with usort, the solution is as follows:</p>
<pre><code>usort($props, function ($a, $b) {
return $a["time"] - $b["time"];
});
</code></pre>
<p>However, this is not working maybe because of special format of my time (but I will have to follow this specific time format.) and shows an error and do nothing to the array. The error:</p>
<blockquote>
<p>Notice: A non well formed numeric value encountered in C:\xampp.....</p>
</blockquote>
|
[
{
"answer_id": 74522822,
"author": "pgSystemTester",
"author_id": 11732320,
"author_profile": "https://Stackoverflow.com/users/11732320",
"pm_score": 3,
"selected": true,
"text": "/**\n * Splits data\n *\n * @param {array} theRange The range of data.\n * @param {string} theSplitter The text used to split.\n * @return the new table\n * @customfunction\n */\nfunction goUSA(theRange, theSplitter) {\n const splitColumn = 2;\n\n var result = [];\n for (r = 0; r < theRange.length; r++) {\n var aRow = theRange[r];\n\n //skips empty rows, enabling ability to select entire column\n if (aRow.join('') != '') {\n var tempSplit = aRow[splitColumn].split(theSplitter);\n for (q = 0; q < tempSplit.length; q++) {\n result.push([aRow[0], aRow[1], tempSplit[q]]);\n }\n }\n }\n return result;\n}\n"
},
{
"answer_id": 74523036,
"author": "Cooper",
"author_id": 7215091,
"author_profile": "https://Stackoverflow.com/users/7215091",
"pm_score": 1,
"selected": false,
"text": "function brkaprt() {\n const ss = SpreadsheetApp.getActive();\n const sh = ss.getSheetByName(\"Sheet0\");\n const osh = ss.getSheetByName(\"Sheet1\");\n osh.clearContents();\n const vs = sh.getRange(2,1, sh.getLastRow() - 1, sh.getLastColumn()).getValues();\n let obj = {pA:[]};\n let o = vs.reduce((ac,[a,b,c],i) => {\n c.split(\"_\").forEach(e =>ac.push([a,b,e]) )\n return ac;\n },[]);\n o.unshift([\"Name\",\"Country\",\"Sport\"]); \n Logger.log(JSON.stringify(o));\n osh.getRange(1,1,o.length,o[0].length).setValues(o);\n\n}\n\nExecution log\n10:56:15 AM Notice Execution started\n10:56:16 AM Info [[\"Name\",\"Country\",\"Sport\"],[\"John\",\"USA\",\"Basketball\"],[\"John\",\"USA\",\"Golf\"],[\"John\",\"USA\",\"Tennis\"],[\"Mary\",\"Canada\",\"Tennis\"],[\"Mary\",\"Canada\",\"Golf\"]]\n10:56:17 AM Notice Execution completed\n"
},
{
"answer_id": 74523109,
"author": "player0",
"author_id": 5632629,
"author_profile": "https://Stackoverflow.com/users/5632629",
"pm_score": 2,
"selected": false,
"text": "=INDEX(QUERY(SPLIT(FLATTEN(IF(IFERROR(SPLIT(C1:C, \"_\"))=\"\",, \n A1:A&\"\"&B1:B&\"\"&SPLIT(C1:C, \"_\"))), \"\"), \"where Col2 is not null\", ))\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74522751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19327646/"
] |
74,522,754
|
<p>I am trying to make a website with dark mode and want to parse the dark prop in tailwind-styled-components. In all places, excluding actions, like hover, active, focus etc, the props do work, but when I try to use hover and parse the darkMode prop, nothing works.
The library I use is 'tailwind-styled-components'.</p>
<p>I have tried to use different approaches for the props, but none of them did work.</p>
<p>This is the part with the styling</p>
<pre><code>export const NavbarListLI = tw.li`
flex flex-row justify-between items-center
mx-5 bg-slate-100 px-3 py-2 rounded-xl cursor-pointer
${({ dark }) => Colors(dark).buttons.primary}
hover:${({ dark }) => Colors(dark).list.hover}
hover:rounded-full
`
</code></pre>
<p>In here, dark and white mode are declared</p>
<pre><code>import React, { useEffect } from "react"
const lightPalette = {
background: "bg-white",
greenish: "honeydew",
defGray: "#aaa",
orangeish: "rgba(255, 100, 25, 0.1)",
kaki: "#62807e",
light: "#e1e5f0",
darkBlue: "#315481",
lightBeige: "#eee",
hotRed: "#ff3046",
darkBrown: "rgba(34, 25, 25, 0.1)",
mint: "#C1E1D2",
whiteBg: "bg-white",
buttons: {
primary: "bg-black text-white",
},
list: { static: "bg-black", hover: "bg-slate-200" },
}
const darkPalette = {
background: "bg-black",
buttons: {
primary: "bg-white text-black",
},
list: { static: "bg-white", hover: "bg-slate-800" },
}
const Colors = (darkMode) => (darkMode ? darkPalette : lightPalette)
export default Colors
</code></pre>
|
[
{
"answer_id": 74522822,
"author": "pgSystemTester",
"author_id": 11732320,
"author_profile": "https://Stackoverflow.com/users/11732320",
"pm_score": 3,
"selected": true,
"text": "/**\n * Splits data\n *\n * @param {array} theRange The range of data.\n * @param {string} theSplitter The text used to split.\n * @return the new table\n * @customfunction\n */\nfunction goUSA(theRange, theSplitter) {\n const splitColumn = 2;\n\n var result = [];\n for (r = 0; r < theRange.length; r++) {\n var aRow = theRange[r];\n\n //skips empty rows, enabling ability to select entire column\n if (aRow.join('') != '') {\n var tempSplit = aRow[splitColumn].split(theSplitter);\n for (q = 0; q < tempSplit.length; q++) {\n result.push([aRow[0], aRow[1], tempSplit[q]]);\n }\n }\n }\n return result;\n}\n"
},
{
"answer_id": 74523036,
"author": "Cooper",
"author_id": 7215091,
"author_profile": "https://Stackoverflow.com/users/7215091",
"pm_score": 1,
"selected": false,
"text": "function brkaprt() {\n const ss = SpreadsheetApp.getActive();\n const sh = ss.getSheetByName(\"Sheet0\");\n const osh = ss.getSheetByName(\"Sheet1\");\n osh.clearContents();\n const vs = sh.getRange(2,1, sh.getLastRow() - 1, sh.getLastColumn()).getValues();\n let obj = {pA:[]};\n let o = vs.reduce((ac,[a,b,c],i) => {\n c.split(\"_\").forEach(e =>ac.push([a,b,e]) )\n return ac;\n },[]);\n o.unshift([\"Name\",\"Country\",\"Sport\"]); \n Logger.log(JSON.stringify(o));\n osh.getRange(1,1,o.length,o[0].length).setValues(o);\n\n}\n\nExecution log\n10:56:15 AM Notice Execution started\n10:56:16 AM Info [[\"Name\",\"Country\",\"Sport\"],[\"John\",\"USA\",\"Basketball\"],[\"John\",\"USA\",\"Golf\"],[\"John\",\"USA\",\"Tennis\"],[\"Mary\",\"Canada\",\"Tennis\"],[\"Mary\",\"Canada\",\"Golf\"]]\n10:56:17 AM Notice Execution completed\n"
},
{
"answer_id": 74523109,
"author": "player0",
"author_id": 5632629,
"author_profile": "https://Stackoverflow.com/users/5632629",
"pm_score": 2,
"selected": false,
"text": "=INDEX(QUERY(SPLIT(FLATTEN(IF(IFERROR(SPLIT(C1:C, \"_\"))=\"\",, \n A1:A&\"\"&B1:B&\"\"&SPLIT(C1:C, \"_\"))), \"\"), \"where Col2 is not null\", ))\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74522754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20565294/"
] |
74,522,765
|
<p>I have a column with values such as this:</p>
<pre><code>structure(list(col1 = c(" | | | | | | | |", "| | | | | | | | | | | | | | |",
"| | | | | | | | | | | | | | | ", "stop|", "stop| | ",
"stop | go")), class = "data.frame", row.names = c(NA, -6L))
</code></pre>
<p>I want to be able to remove all iterations of <code>|</code> when they show up consecutively, or if they show up as <code>| |</code> or <code>| | |</code>.</p>
<p>Currently, I'm trying to figure out all the iterations of the pipes, but they seem kind of random. I was wondering if there's a way to make sure my iterations cover the following instances:</p>
<ol>
<li>When there are more than one <code>|</code> consecutively</li>
<li>When there are more than one <code>|</code> consecutively with a number of spaces (e.g., <code>| |</code> or <code>| | |</code></li>
<li>When <code>|</code> is at the end of the line (e.g., <code>\\|$</code></li>
</ol>
<p>I would, however, keep the pipe between <code>stop | go</code>.</p>
<p>Here's the code that I'm working with right now, but it removes the pipe in <code>stop | go</code>.</p>
<pre><code>df$col1 <- gsub('[\\| ]{2,}|[\\|$]', '', df$col1)
</code></pre>
<p>I want to remove all the <code>|</code> symbols except for the one in <code>stop | go</code>.</p>
|
[
{
"answer_id": 74522801,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 3,
"selected": true,
"text": "trimws(trimws(gsub('(\\\\|\\\\s+){2,}', \"\", df$col1),\n whitespace = \"\\\\s+\\\\|\"), whitespace = \"\\\\|\")\n [1] \"\" \"\" \"\" \"stop\" \"stop\" \"stop | go\"\n"
},
{
"answer_id": 74522834,
"author": "Allan Cameron",
"author_id": 12500315,
"author_profile": "https://Stackoverflow.com/users/12500315",
"pm_score": 2,
"selected": false,
"text": "gsub('\\\\|\\\\s*\\\\||\\\\|\\\\s*$', '', df$col1)\n#> [1] \" \" \" \"\n#> [3] \" \" \"stop\" \n#> [5] \"stop \" \"stop | go\"\n trimws trimws(gsub('\\\\|\\\\s*\\\\||\\\\|\\\\s*$', '', df$col1))\n#> [1] \"\" \"\" \"\" \"stop\" \"stop\" \n#> [6] \"stop | go\"\n"
},
{
"answer_id": 74523064,
"author": "harre",
"author_id": 4786466,
"author_profile": "https://Stackoverflow.com/users/4786466",
"pm_score": 2,
"selected": false,
"text": "| trimws(gsub(\"\\\\|(?!\\\\s\\\\w)\", \"\", df$col1, perl = TRUE))\n [1] \"\" \"\" \"\" \"stop\" \"stop\" \"stop | go\"\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74522765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4937644/"
] |
74,522,774
|
<p>When I ran 'control c' in terminal (SIGINT). I want the parent process to ignore it, but no his child processes (that were created by fork() and execvp()).</p>
<p>I added</p>
<pre><code>signal(SIGINT, SIG_IGN);
</code></pre>
<p>to the parent process that ignore the SIGINT, but now his childs also ignores it.</p>
|
[
{
"answer_id": 74526257,
"author": "Alez",
"author_id": 5317332,
"author_profile": "https://Stackoverflow.com/users/5317332",
"pm_score": 2,
"selected": false,
"text": "signal(SIGINT, SIG_IGN);\n"
},
{
"answer_id": 74526544,
"author": "Joseph Sible-Reinstate Monica",
"author_id": 7509065,
"author_profile": "https://Stackoverflow.com/users/7509065",
"pm_score": 0,
"selected": false,
"text": "execvp signal(SIGINT, SIG_DFL);"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74522774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15599269/"
] |
74,522,783
|
<p>I have the following dataframe</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>en</th>
<th>ko</th>
</tr>
</thead>
<tbody>
<tr>
<td>Tuberculosis of heart</td>
<td>심장의 결핵</td>
</tr>
<tr>
<td>Tuberculosis of myocardium</td>
<td>심근의 결핵</td>
</tr>
<tr>
<td>Tuberculosis of endocardium</td>
<td>심내막의 결핵</td>
</tr>
<tr>
<td>Tuberculosis of oesophagus</td>
<td>식도의 결핵</td>
</tr>
<tr>
<td>Zoster keratoconjunctivitis</td>
<td>대상포진 각막결막염</td>
</tr>
<tr>
<td>Zoster blepharitis</td>
<td>대상포진 안검염</td>
</tr>
<tr>
<td>Zoster iritis</td>
<td>대상포진 홍채염</td>
</tr>
</tbody>
</table>
</div>
<p>I want a result like this.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>en</th>
<th>ko</th>
</tr>
</thead>
<tbody>
<tr>
<td>heart</td>
<td>심장의</td>
</tr>
<tr>
<td>myocardium</td>
<td>심근의</td>
</tr>
<tr>
<td>endocardium</td>
<td>심내막의</td>
</tr>
<tr>
<td>oesophagus</td>
<td>식도의</td>
</tr>
<tr>
<td>keratoconjunctivitis</td>
<td>각막결막염</td>
</tr>
<tr>
<td>blepharitis</td>
<td>안검염</td>
</tr>
<tr>
<td>iritis</td>
<td>홍채염</td>
</tr>
</tbody>
</table>
</div>
<p>This is just an example, I have about 50,000 word pairs. Been doing this for 1 week now.</p>
|
[
{
"answer_id": 74523046,
"author": "G. Anderson",
"author_id": 7835267,
"author_profile": "https://Stackoverflow.com/users/7835267",
"pm_score": 0,
"selected": false,
"text": "ko=df['ko'].str.split().explode().value_counts()\nen=df['en'].str.split().explode().value_counts()\n\nko\n결핵 4\n대상포진 3\n심장의 1\n심근의 1\n심내막의 1\n식도의 1\n각막결막염 1\n안검염 1\n홍채염 1\nName: ko, dtype: int64\n ko_col=ko[ko==1]\nen_col=en[en==1]\n\nen_col\nheart 1\nmyocardium 1\nendocardium 1\noesophagus 1\nkeratoconjunctivitis 1\nblepharitis 1\niritis 1\nName: en, dtype: int64\n new_df=pd.DataFrame({'en':en_col.index,'ko':ko_col.index})\nnew_df\n en ko\n0 heart 심장의\n1 myocardium 심근의\n2 endocardium 심내막의\n3 oesophagus 식도의\n4 keratoconjunctivitis 각막결막염\n5 blepharitis 안검염\n6 iritis 홍채염\n"
},
{
"answer_id": 74523374,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 1,
"selected": false,
"text": "import re\n\n# identify duplicates\ns = df.stack().str.split().explode()\ndups = s[s.duplicated()].groupby(level=1).unique().to_dict()\n# {'en': array(['Tuberculosis', 'of', 'Zoster'], dtype=object),\n# 'ko': array(['결핵', '대상포진'], dtype=object)}\n\n# remove them\ndf.apply(lambda s: s.str.replace('|'.join(dups[s.name]), '', regex=True))\n en ko\n0 heart 심장의\n1 myocardium 심근의\n2 endocardium 심내막의\n3 oesophagus 식도의\n4 keratoconjunctivitis 각막결막염\n5 blepharitis 안검염\n6 iritis 홍채염\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74522783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19833416/"
] |
74,522,788
|
<p>I have been trying to develop a todo list project. I have four components : <strong>Daily, Item-List, Item and Add-task dailog</strong> <a href="https://i.stack.imgur.com/Mwc4T.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Mwc4T.png" alt="enter image description here" /></a></p>
<p>The daily component holds a form and a list that displays the values from form. What I am looking to do next is to have a form in a dialog modal(new separate component) and add its value to the list in the daily component</p>
<p>Below are the codes:</p>
<p><strong>Daily.service.ts</strong></p>
<p>This service code is used to get the value from the form and add it to the list.</p>
<pre><code>import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { DailyTask } from './models';
@Injectable({ providedIn: 'root' })
export class DailyService {
private _dailies$ = new BehaviorSubject<DailyTask[]>([]);
public getDailies(): DailyTask[] {
return this._dailies$.getValue();
}
public setDailies(data: DailyTask[]): void {
this._dailies$.next(data);
}
public getDailiesObservable(): Observable<DailyTask[]> {
return this._dailies$.asObservable();
}
public createTask(newTask: string): void{
console.log( "check");
const dailyTask: DailyTask = { task: newTask, type: 'DAILY' };
this.setDailies([dailyTask, ...this.getDailies()])
}
}
</code></pre>
<p><strong>Daily.component.Ts</strong></p>
<pre><code>export class DailyComponent implements OnInit {
public dailyList$: Observable<DailyTask[]> | null = null;
constructor(private _dailyService: DailyService) {}
ngOnInit(): void {
this.dailyList$ = this._dailyService.getDailiesObservable();
}
public addDaily(name: string) {
this._dailyService.createTask(name);
}
}
</code></pre>
<p><strong>Daily.component.html</strong></p>
<pre><code> <mat-card>
<h1>Daily</h1>
<app-item-list
[type]="'DAILY'"
[initialData$]="dailyList$"
[onAddItem]="addDaily.bind(this)"
></app-item-list>
</mat-card>
</code></pre>
<p><strong>Item-List.component.html</strong></p>
<pre><code><div>
<mat-form-field appearance="outline">
<input
matInput
placeholder="Add a Task"
(keyup.enter)="addTask()"
autocomplete="off"
[formControl]="nameControl"/>
</mat-form-field>
</div>
<ng-container *ngIf="filteredData$ | async as data">
<app-item
[value]="value"
*ngFor="let value of data; index as index"
(inputDataChange)="removeTask(data, index)"
>
</app-item>
</ng-container>
</code></pre>
<p><strong>Item-list.component.ts</strong></p>
<pre><code>export class ItemListComponent implements OnInit {
nameControl = new FormControl('');
@Input() public type: ItemType | null = null;
@Input() public onAddItem: Function | null = null;
constructor(private _homeService: HomeService) {}
ngOnInit(): void {}
addTask() {
if (this.onAddItem) {
this.onAddItem(this.nameControl.value);
this.nameControl.reset();
}
}
</code></pre>
<p><strong>item.component.html</strong></p>
<pre><code><div class="displayTask">
<div class="displayvalue" [ngClass]="{ 'line-through': value.task }">
{{ value.task | uppercase }}
</div>
</div>
</code></pre>
<p><strong>item.component.ts</strong></p>
<pre><code>export class ItemComponent implements OnInit {
@Input()
value: any;
constructor() {}
ngOnInit(): void {}
}
</code></pre>
<p>The above set of codes works perfect, below the code for new component <strong>task-dailog</strong></p>
<p><strong>task-dailog.html</strong></p>
<pre><code><div mat-dialog-title class="dailogHeader">
<h1 >Create Daily</h1>
</div>
<div mat-dialog-content>
<div class="dialogContent">
<p>Task</p>
<mat-form-field appearance="outline">
<input
matInput
placeholder="Add a new Task"
autocomplete="off"
(keyup.enter)="addDailogTask()"
[formControl]="nameControl"
/>
</mat-form-field>
</div>
</div>
</code></pre>
<p><strong>task-dailog.component.ts</strong></p>
<pre><code>export class TaskDialogComponent implements OnInit {
nameControl = new FormControl('');
constructor(
public dialogRef: MatDialogRef<TaskDialogComponent>,
private _dailyService: DailyService,
) {}
ngOnInit(): void {}
onNoClick(): void {
this.dialogRef.close();
}
addDailogTask(){
const value$ = this.nameControl.value;
this.nameControl.reset();
console.log(value$);
}
}
</code></pre>
<p>Here in the task-dialog.component.ts, I have the function to get the value from the form, but I am stuck here and dont know how to proceed. I would like to learn how to send this form value from <strong>TaskDialogComponent</strong> to the list inside <strong>DailyComponent</strong>.</p>
<p>Here is also the <a href="https://stackblitz.com/edit/github-pdhugz?file=src/app/daily/daily.component.html" rel="nofollow noreferrer">Stackblitz</a> for the project.</p>
<p>Can someone help me with this . I am relatively new to angular and would really appreciate the help. Thanks in advance!.</p>
|
[
{
"answer_id": 74526340,
"author": "paranaaan",
"author_id": 11634381,
"author_profile": "https://Stackoverflow.com/users/11634381",
"pm_score": 2,
"selected": true,
"text": "form.value any createTask string addDailogTask() {\n const value$ = this.nameControl.value as string;\n ...\n}\n"
},
{
"answer_id": 74526402,
"author": "Dinesh",
"author_id": 2533109,
"author_profile": "https://Stackoverflow.com/users/2533109",
"pm_score": 0,
"selected": false,
"text": " task-dialog.component.html [mat-dialog-close]=\"task\" dialogRef AddTaskBtnComponent afterClosed().subscribe @Component({\n selector: 'app-add-task-btn',\n templateUrl: './add-task-btn.component.html',\n styleUrls: ['./add-task-btn.component.scss'],\n})\nexport class AddTaskBtnComponent implements OnInit {\n\n\n ...\n\n openDialog(): void {\n\n const dialogRef = this.dialog.open(TaskDialogComponent, {\n width: '500px',\n height: '500px',\n });\n\n dialogRef.afterClosed().subscribe((task) => {\n if (task) {\n this.dailyService.createTask(task);\n } \n console.log('The dialog was closed');\n });\n }\n }\n}\n MatDialogModule TaskDialogModule src\n app\n L home\n L shared\n L components\n L item-list\n L components\n L item \n L components\n L profile-banner\n L searchbar\n L add-task-btn\n L daily\n L components\n L services\n L daily.service.ts\n L ... \n L todo\n L habits \n L services\n L models \n L home.component.ts\n L home.component.scss\n L home.component.html\n HomeModule @input"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74522788",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12239876/"
] |
74,522,789
|
<p>I have this code snippet which will delete all rows in the <code>user_interests</code> table. I have a parameter of <code>int id</code> which is user id. I want to pass this parameter to my SQL statement. I have tried using <code>".... user_id = @id"</code> but it wont work when I run it on Postman. I also tried using static value for is <code>"... user_id = 1"</code> and it is working fine.</p>
<pre><code>public boolean deleteInterest(int id) {
boolean isDeleted = false;
String sql = "DELETE FROM user_interests WHERE user_id = @id" ;
if(userRepository.findById(id) != null) {
dbTemplate.execute(sql);
isDeleted = true;
}
return isDeleted;
}
</code></pre>
<p>How can I pass the id parameter to my sql statement?</p>
|
[
{
"answer_id": 74522900,
"author": "Alien",
"author_id": 6572971,
"author_profile": "https://Stackoverflow.com/users/6572971",
"pm_score": 2,
"selected": true,
"text": "String sql = \"DELETE FROM user_interests WHERE user_id = \" + id\n"
},
{
"answer_id": 74556240,
"author": "Nirmit",
"author_id": 10333428,
"author_profile": "https://Stackoverflow.com/users/10333428",
"pm_score": 0,
"selected": false,
"text": "String sql = \"DELETE FROM user_interests WHERE user_id = '\"+parameterName+\"'\";\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74522789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20538516/"
] |
74,522,812
|
<p>I have two data frames and joined the data with left join from the column "country"</p>
<p>i need to create a separate table in excel for each 4 countries from the joined dataframes as per the attached format.</p>
<p>Please advise how can i achieve this ?</p>
<p><a href="https://i.stack.imgur.com/J4D2c.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/J4D2c.jpg" alt="enter image description here" /></a>please advise how can i achieve this?</p>
<pre><code>Import Pandas as pd
import numpy as np
file = pd.ExcelFile(r"p:\test\sample.xlsx")
df1 = pd.read_excel(file, 'sample1')
df2 = pd.read_excel(file, 'sample2')
df3 = (pd.merge(df1, df2, left_on='country', right_on='Country', how='left').drop.('amount', axis=1))
n = len(pd.unique(df3['country']))`
</code></pre>
|
[
{
"answer_id": 74522900,
"author": "Alien",
"author_id": 6572971,
"author_profile": "https://Stackoverflow.com/users/6572971",
"pm_score": 2,
"selected": true,
"text": "String sql = \"DELETE FROM user_interests WHERE user_id = \" + id\n"
},
{
"answer_id": 74556240,
"author": "Nirmit",
"author_id": 10333428,
"author_profile": "https://Stackoverflow.com/users/10333428",
"pm_score": 0,
"selected": false,
"text": "String sql = \"DELETE FROM user_interests WHERE user_id = '\"+parameterName+\"'\";\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74522812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16291244/"
] |
74,522,819
|
<p>I'm looking a solution with sed command to search and replace strings on last column of csv file and here the search patterns I'm calling from an array. Below script looks for 3rd and 4th column which causes a mismatch in the output.</p>
<p>Here i need your help how i can tell sed to look only on the last column.</p>
<p>file1.txt</p>
<pre><code>QCQP
TXTT
QCQT
YYTH
</code></pre>
<p>file2.txt</p>
<pre><code>TTYY
JPEK
QCQC
TTYE
</code></pre>
<p>Original
output.csv</p>
<pre><code>[Input]
String1
[Data]
ID,Name,Class,Context,Code
1,jack,6,QCQT,QCQP
2,john,5,QCQP,TXTT
3,jake,3,TTXX,QCQT
4,jone,3,TXTT,YYTH
</code></pre>
<p>Below is my script which I used for this setup, but here this sed command search for all occurrence instead of looking for the last column separated by comma.</p>
<pre><code>#!/bin/bash
filein=file1.txt
fileout=file2.txt
pre=$(cat $filein)
post=$(cat $fileout)
prear=($pre)
postar=($post)
typeset -p prear postar
for (( i=0; i<${#prear[@]}; ++i )); do
sed -i -e 's/'"${prear[$i]}"'/'"${postar[$i]}"'/g' output.csv
done
</code></pre>
<p>Expected result</p>
<p>output.csv</p>
<pre><code>[Input]
String1
[Data]
ID,Name,Class,Context,Code
1,jack,6,QCQT,TTYY
2,john,5,QCQP,JPEK
3,jake,3,TTXX,QCQC
4,jone,3,TXTT,TTYE
</code></pre>
<p>Using awk command I'm able to figure out similiar occurance, but the below works with a single variable, also not with comma seperator but with array this fails.</p>
<pre><code>awk -F "," '{gsub(c,d,$(NF)); print}' c=$a d=$b file.txt
</code></pre>
<p>In addition, if using awk or gawk for this purpose, i would need to specify the variable name as input. Because the input files "file1.txt, file2.txt" and output files with .csv filenames will not be same all the time. Actually I'm accepting them as first, second and third argument in the script and then reading the contents from that variable.</p>
<p>For eg:- Here users can choose any name file as input. Here I'm not sure how to call the array in awk/gawk</p>
<pre><code>#!/bin/bash
input1=$1
input2=$2
Output=$3
inp1=$(cat $input1)
inp2=$(cat $input2)
out=$(cat $Output)
inp1ar=($inp1)
inp2ar=($inp2)
outar=($out)
I would like to expect to call the array variable to read the contents
gawk -i inplace '
.. some condition ..
' {inp1ar} {inp2ar} {outar}
</code></pre>
<p>Please advise</p>
<p>Thanks
Jay</p>
|
[
{
"answer_id": 74523070,
"author": "glenn jackman",
"author_id": 7552,
"author_profile": "https://Stackoverflow.com/users/7552",
"pm_score": 2,
"selected": true,
"text": "gawk '\n BEGIN {FS = OFS = \",\"}\n ARGIND == 1 {f1[FNR] = $1; next}\n ARGIND == 2 {map[f1[FNR]] = $1; next}\n {$NF = map[$NF]; print}\n' file1.txt file2.txt original.csv\n ID,Name,Class,Context,\n1,jack,6,QCQT,TTYY\n2,john,5,QCQP,JPEK\n3,jake,3,TTXX,QCQC\n4,jone,3,TXTT,TTYE\n sed \"$(paste -d \" \" file1.txt file2.txt | sed 's/^/s:,/; s/ /$:,/; s/$/:/')\" original.csv\n gawk '\n BEGIN {FS = OFS = \",\"}\n ARGIND == 1 {f1[FNR] = $1; next}\n ARGIND == 2 {map[f1[FNR]] = $1; next}\n\n BEGINFILE {start = 0; header = 1}\n start {if (header) {header = 0} else {$NF = map[$NF]}}\n {print}\n $1 == \"[Data]\" {start = 1}\n' file1.txt file2.txt original.csv\n cat \"$input1\" #!/bin/bash\ninput1=\"$1\"\ninput2=\"$2\"\nOutput=\"$3\"\n\ngawk -i inplace '.. some condition ..' \"$input1\" \"$input2\" \"$Output\"\n"
},
{
"answer_id": 74523187,
"author": "Ivan",
"author_id": 12607443,
"author_profile": "https://Stackoverflow.com/users/12607443",
"pm_score": -1,
"selected": false,
"text": "sed $ cat f\nID,Name,Class,Context,Code\n1,jack,6,QCQT,QCQP\n2,john,5,QCQP,TXTT\n3,jake,3,TTXX,QCQT\n4,jone,3,TXTT,YYTH\n\n$ sed -r 's/,(QCQP|TXTT|QCQT|YYTH)$/,aaa/' f f\nID,Name,Class,Context,Code\n1,jack,6,QCQT,aaa\n2,john,5,QCQP,aaa\n3,jake,3,TTXX,aaa\n4,jone,3,TXTT,aaa\nID,Name,Class,Context,Code\n1,jack,6,QCQT,aaa\n2,john,5,QCQP,aaa\n3,jake,3,TTXX,aaa\n4,jone,3,TXTT,aaa\n awk"
},
{
"answer_id": 74524700,
"author": "markp-fuso",
"author_id": 7366100,
"author_profile": "https://Stackoverflow.com/users/7366100",
"pm_score": 1,
"selected": false,
"text": "pre[] post[] bash awk file1.txt file2.txt file1.txt file2.txt output.csv output.csv file1.txt [Data] output.csv [Data] output.csv file1.txt $ cat [Input]\nString1\n\n[Data]\nID,Name,Class,Context,Code\n1,jack,6,QCQT,QCQP\n2,john,5,QCQP,TXTT\n3,jake,3,TTXX,QCQT\n4,jone,3,TXTT,YYTH\n5,mary,7,XXXX,9999 # this line should not be modified\n paste file1.txt file2.txt $ paste -d',' file1.txt file2.txt\nQCQP,TTYY\nTXTT,JPEK\nQCQT,QCQC\nYYTH,TTYE\n awk awk '\nBEGIN { FS=OFS=\",\"; replace=0 } # initially we are not in \"replace\" mode\nFNR==NR { map[$1]=$2; next } # 1st file: build map[] array entries\nreplace && ($5 in map) { $5=map[$5] } # 2nd file: if in \"replace\" mode and 5th field is an index in the map[] array then replace the 5th field \n$1 == \"[Data]\" { replace=1 } # enable \"replace\" mode\n1 # print current line\n' <(paste -d',' file1.txt file2.txt) output.csv\n [Input]\nString1\n\n[Data]\nID,Name,Class,Context,Code\n1,jack,6,QCQT,TTYY\n2,john,5,QCQP,JPEK\n3,jake,3,TTXX,QCQC\n4,jone,3,TXTT,TTYE\n5,mary,7,XXXX,9999 # line was not modified\n sed -i awk mv tempfile output.csv GNU awk inplace GNU awk awk output.csv awk -i inplace '\nBEGIN { FS=OFS=\",\"; replace=0 }\nFNR==NR { map[$1]=$2; next }\nreplace && ($5 in map) { $5=map[$5] }\n$1 == \"[Data]\" { replace=1 }\n1\n' inplace::enable=0 <(paste -d',' file1.txt file2.txt) inplace::enable=1 output.csv\n -i inplace inplace inplace::enable=0 inplace paste inplace::enable=1 inplace output.csv $ cat output.csv\n[Input]\nString1\n\n[Data]\nID,Name,Class,Context,Code\n1,jack,6,QCQT,TTYY\n2,john,5,QCQP,JPEK\n3,jake,3,TTXX,QCQC\n4,jone,3,TXTT,TTYE\n5,mary,7,XXXX,9999\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74522819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2790497/"
] |
74,522,868
|
<p>This is what I have so far, I am getting stuck where I would usually do the IN syntax also AND with SQL WHERE</p>
<p>See the images for explanation of the following:
An example data for A in sheet1:</p>
<pre><code>cell1 = [A,B,C]
cell2 = [A,B]
Cell3 = [A]
</code></pre>
<p>Sheet: OverallGroups</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Team</th>
<th>Projects</th>
<th>Bring</th>
</tr>
</thead>
<tbody>
<tr>
<td>A,B,C</td>
<td>Frying</td>
<td><a href="https://www.qfc.com/p/kroger-pure-vegetable-oil/0001111085605" rel="nofollow noreferrer">Oil</a>, <a href="https://www.qfc.com/p/king-arthur-flour-unbleached-all-purpose-flour/0007101201050?fulfillment=PICKUP&searchType=suggestions" rel="nofollow noreferrer">flour</a>, <a href="https://www.qfc.com/p/zulka-morena-pure-cane-sugar/0066144000021?fulfillment=PICKUP&searchType=default_search" rel="nofollow noreferrer">sugar</a>, <a href="https://www.qfc.com/p/simple-truth-organic-air-chilled-boneless-skinless-chicken-breasts/0029082900000?fulfillment=PICKUP&searchType=default_search" rel="nofollow noreferrer">chicken</a></td>
</tr>
<tr>
<td>A, B</td>
<td>Baking</td>
<td><a href="https://www.qfc.com/p/kroger-pure-vegetable-oil/0001111085605" rel="nofollow noreferrer">Oil</a>, <a href="https://www.qfc.com/p/king-arthur-flour-unbleached-all-purpose-flour/0007101201050?fulfillment=PICKUP&searchType=suggestions" rel="nofollow noreferrer">flour</a>, <a href="https://www.qfc.com/p/zulka-morena-pure-cane-sugar/0066144000021?fulfillment=PICKUP&searchType=default_search" rel="nofollow noreferrer">sugar</a></td>
</tr>
<tr>
<td>A</td>
<td>Crafting</td>
<td><a href="https://www.hobbylobby.com/Art-Supplies/Painting-Canvas-Art-Surfaces/Construction-Paper/c/8-165-1292" rel="nofollow noreferrer">Paper</a></td>
</tr>
</tbody>
</table>
</div>
<p>Sheet: Jobs</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Team</th>
<th>Projects</th>
<th>Due</th>
<th>Bring (Return Query here)</th>
</tr>
</thead>
<tbody>
<tr>
<td>B</td>
<td>Frying</td>
<td>1/2/14</td>
<td></td>
</tr>
<tr>
<td>C</td>
<td>Frying</td>
<td>1/3/14</td>
<td></td>
</tr>
<tr>
<td>A</td>
<td>Frying</td>
<td>1/4/14</td>
<td></td>
</tr>
<tr>
<td>B</td>
<td>Baking</td>
<td>1/5/14</td>
<td></td>
</tr>
<tr>
<td>B</td>
<td>Baking</td>
<td>1/6/14</td>
<td></td>
</tr>
<tr>
<td>A</td>
<td>Crafting</td>
<td>1/7/14</td>
<td></td>
</tr>
<tr>
<td>A</td>
<td>Crafting</td>
<td>1/8/14</td>
<td></td>
</tr>
</tbody>
</table>
</div>
<p>The sheet2 "jobs" has in column A <em>just one letter</em> out of the potential lists in cell1,2,3..., delimited by comma.</p>
<p>The format allowed the most condensed view of the jobs on the first sheet, then the jobs sheet expands them for specific when and where per project.</p>
<p>I know that is isn't conventional to have multivalued fields, but it was necessary to summarize the data view rather than have a flooded screen of replicates to manage missing elements in this school project.</p>
<p>An example problem:
I want to find WHERE TEAM A IN [A,B,C] exists in one instance and the related project from B in the query to explain what to bring to class. The selection returns one block of text content from C. And the condition that project matches the with the team letter.</p>
<pre><code>=QUERY({OverallGroups'!A:C; Jobs'!A}, "Select C WHERE A matches '" & OverallGroups'!A:A & '" AND A matches " & Jobs'!A & "'")
</code></pre>
<p>I tried using
<code>&TEXTJOIN() </code>
but this works for one to one cells, and won't parse the inner list by the comma.</p>
<p>------------- Part 2 need to copy the links by query 11/28/22--------</p>
<ol>
<li>I have a query in Google Sheets which will search a template of materials to bring for another expanded sheet which has unique answers, but I need the links to appear as a result from this query</li>
</ol>
<p>The difficulty is in being able to import multiple links per cell and groups to sort bringing materials for by the query.</p>
<p>The best snippet of code for this I have gets an error from another post: <code>=BYROW(A2:A,LAMBDA(each,filter(OverallGroups!C:C,ARRAYFORMULA(REGEXMATCH(OverallGroups!A:A,"(?i)"&each)),ARRAYFORMULA(REGEXMATCH(OverallGroups!C:C,"(?i)"&OFFSET(each,0,1))))))</code></p>
<p>"No matches are found in FILTER evaluation: #N/A"</p>
<p>This script on Google Sheets will provide the working data without hyperlinking...
<code>=query('OverallGroups'!A:C;"Select C where A contains '"&A2&"' and B contains '"&B2&"'")</code></p>
<p>Please reference the data from these two tables to get the answer in the second table "what to bring" so that it references the links.</p>
|
[
{
"answer_id": 74523070,
"author": "glenn jackman",
"author_id": 7552,
"author_profile": "https://Stackoverflow.com/users/7552",
"pm_score": 2,
"selected": true,
"text": "gawk '\n BEGIN {FS = OFS = \",\"}\n ARGIND == 1 {f1[FNR] = $1; next}\n ARGIND == 2 {map[f1[FNR]] = $1; next}\n {$NF = map[$NF]; print}\n' file1.txt file2.txt original.csv\n ID,Name,Class,Context,\n1,jack,6,QCQT,TTYY\n2,john,5,QCQP,JPEK\n3,jake,3,TTXX,QCQC\n4,jone,3,TXTT,TTYE\n sed \"$(paste -d \" \" file1.txt file2.txt | sed 's/^/s:,/; s/ /$:,/; s/$/:/')\" original.csv\n gawk '\n BEGIN {FS = OFS = \",\"}\n ARGIND == 1 {f1[FNR] = $1; next}\n ARGIND == 2 {map[f1[FNR]] = $1; next}\n\n BEGINFILE {start = 0; header = 1}\n start {if (header) {header = 0} else {$NF = map[$NF]}}\n {print}\n $1 == \"[Data]\" {start = 1}\n' file1.txt file2.txt original.csv\n cat \"$input1\" #!/bin/bash\ninput1=\"$1\"\ninput2=\"$2\"\nOutput=\"$3\"\n\ngawk -i inplace '.. some condition ..' \"$input1\" \"$input2\" \"$Output\"\n"
},
{
"answer_id": 74523187,
"author": "Ivan",
"author_id": 12607443,
"author_profile": "https://Stackoverflow.com/users/12607443",
"pm_score": -1,
"selected": false,
"text": "sed $ cat f\nID,Name,Class,Context,Code\n1,jack,6,QCQT,QCQP\n2,john,5,QCQP,TXTT\n3,jake,3,TTXX,QCQT\n4,jone,3,TXTT,YYTH\n\n$ sed -r 's/,(QCQP|TXTT|QCQT|YYTH)$/,aaa/' f f\nID,Name,Class,Context,Code\n1,jack,6,QCQT,aaa\n2,john,5,QCQP,aaa\n3,jake,3,TTXX,aaa\n4,jone,3,TXTT,aaa\nID,Name,Class,Context,Code\n1,jack,6,QCQT,aaa\n2,john,5,QCQP,aaa\n3,jake,3,TTXX,aaa\n4,jone,3,TXTT,aaa\n awk"
},
{
"answer_id": 74524700,
"author": "markp-fuso",
"author_id": 7366100,
"author_profile": "https://Stackoverflow.com/users/7366100",
"pm_score": 1,
"selected": false,
"text": "pre[] post[] bash awk file1.txt file2.txt file1.txt file2.txt output.csv output.csv file1.txt [Data] output.csv [Data] output.csv file1.txt $ cat [Input]\nString1\n\n[Data]\nID,Name,Class,Context,Code\n1,jack,6,QCQT,QCQP\n2,john,5,QCQP,TXTT\n3,jake,3,TTXX,QCQT\n4,jone,3,TXTT,YYTH\n5,mary,7,XXXX,9999 # this line should not be modified\n paste file1.txt file2.txt $ paste -d',' file1.txt file2.txt\nQCQP,TTYY\nTXTT,JPEK\nQCQT,QCQC\nYYTH,TTYE\n awk awk '\nBEGIN { FS=OFS=\",\"; replace=0 } # initially we are not in \"replace\" mode\nFNR==NR { map[$1]=$2; next } # 1st file: build map[] array entries\nreplace && ($5 in map) { $5=map[$5] } # 2nd file: if in \"replace\" mode and 5th field is an index in the map[] array then replace the 5th field \n$1 == \"[Data]\" { replace=1 } # enable \"replace\" mode\n1 # print current line\n' <(paste -d',' file1.txt file2.txt) output.csv\n [Input]\nString1\n\n[Data]\nID,Name,Class,Context,Code\n1,jack,6,QCQT,TTYY\n2,john,5,QCQP,JPEK\n3,jake,3,TTXX,QCQC\n4,jone,3,TXTT,TTYE\n5,mary,7,XXXX,9999 # line was not modified\n sed -i awk mv tempfile output.csv GNU awk inplace GNU awk awk output.csv awk -i inplace '\nBEGIN { FS=OFS=\",\"; replace=0 }\nFNR==NR { map[$1]=$2; next }\nreplace && ($5 in map) { $5=map[$5] }\n$1 == \"[Data]\" { replace=1 }\n1\n' inplace::enable=0 <(paste -d',' file1.txt file2.txt) inplace::enable=1 output.csv\n -i inplace inplace inplace::enable=0 inplace paste inplace::enable=1 inplace output.csv $ cat output.csv\n[Input]\nString1\n\n[Data]\nID,Name,Class,Context,Code\n1,jack,6,QCQT,TTYY\n2,john,5,QCQP,JPEK\n3,jake,3,TTXX,QCQC\n4,jone,3,TXTT,TTYE\n5,mary,7,XXXX,9999\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74522868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20242953/"
] |
74,522,871
|
<p>I am working on a secure LoRa transmission, where I need to generate the same pseudo-random number on the transmitter and the receiver (it would be part of the encryption algorithm) based on an input counter. So this function should give the same output for a given input, just like a hashing algorithm.</p>
<p>As an example here is what I mean, but as you can see the computation gets longer based on the input:</p>
<pre><code>unsigned int f(unsigned int input) {
srand(1234);
for (unsigned int i = 0; i < input; i++) {
rand();
}
return rand();
}
</code></pre>
<p>Is there a more efficient way to do this? I am on an ESP32 microcontroller.</p>
<p>edit. Thanks for all the answers. I could have accomplished what I was trying to do with a CRC function, but as per your recommendation I ended up ditching this approach and used a standard encryption algorithm instead.</p>
|
[
{
"answer_id": 74523221,
"author": "frankplow",
"author_id": 17419835,
"author_profile": "https://Stackoverflow.com/users/17419835",
"pm_score": 3,
"selected": true,
"text": "rand"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74522871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20304347/"
] |
74,522,879
|
<p>I'm looking for a solution for following problem -
i want to create a @Query like this:</p>
<pre><code>@Query("select s from Student s where s.name like %?1% and s.surname like %?1%")
</code></pre>
<p>because I need to be able to show student with given name and surname. I was able to make it sort of work, because when I change and with or, the query shows entries with either given name or given surname, but as soon as i change it back to and nothing shows.</p>
<pre><code>interface StudentRepository extends JpaRepository<Student, Integer> {
@Query("select s from Student s where s.name like %?1% and s.surname like %?1%")
Page<Student> findByNameAndSurname( String name, String surname, Pageable pageable);
}
</code></pre>
<pre><code>@GetMapping
Page<Student> getAllStudents(@RequestParam Optional<String> name,
@RequestParam Optional<String> surname,
@RequestParam Optional<Integer> page,
@RequestParam Optional<String> sortBy) {
return repository.findByNameAndSurname(name.orElse("_"),
surname.orElse("_"),
PageRequest.of(
page.orElse(0), 5,
Sort.Direction.ASC, sortBy.orElse("id")));
</code></pre>
<p>I also have second question, is it possible to remove this code that shows at the end of JSONs while using pageRequest - I would like only the Student entries to show without this if possible</p>
<pre><code>
{"content":[],"pageable":{"sort":{"empty":false,"sorted":true,"unsorted":false},"offset":0,"pageNumber":0,"pageSize":5,"unpaged":false,"paged":true},"last":true,"totalPages":0,"totalElements":0,"size":5,"number":0,"sort":{"empty":false,"sorted":true,"unsorted":false},"first":true,"numberOfElements":0,"empty":true}
</code></pre>
<p>I tried using native query in @Query annotation, I also tried modifying the query itself, using some concat tricks i found online, but nothing works;(</p>
|
[
{
"answer_id": 74522989,
"author": "maio290",
"author_id": 4934937,
"author_profile": "https://Stackoverflow.com/users/4934937",
"pm_score": -1,
"selected": false,
"text": "@Query(\"select s from Student s where s.name like %?1% and s.surname like %?1%\")\n ?1 OR @Query(\"select s from Student s where s.name like %:firstname% and s.surname like %:lastname%\")\n @Param(var) Page<Student> List<Student>"
},
{
"answer_id": 74524031,
"author": "KunalVarpe",
"author_id": 3649352,
"author_profile": "https://Stackoverflow.com/users/3649352",
"pm_score": 0,
"selected": false,
"text": "JpaRepository Page<Student> findByStartingWithFirstNameAndStartingWithSurname();\n"
},
{
"answer_id": 74564007,
"author": "Marc Bannout",
"author_id": 13695861,
"author_profile": "https://Stackoverflow.com/users/13695861",
"pm_score": 0,
"selected": false,
"text": "name surname repository.findByNameAndSurname(name.orElse(\"_\"),\n surname.orElse(\"_\"),\n PageRequest.of(\n page.orElse(0), 5,\n Sort.Direction.ASC, sortBy.orElse(\"id\"))).stream().toList();\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74522879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20565300/"
] |
74,522,901
|
<p>I have been using odient in python for a project and it's been working completely fine. I did the same thing I always do for this problem and for some reason it keeps saying my defined function takes 1 positional argument but 2 were given, even though it's been fine doing problems like this before. Here is my code:</p>
<pre><code> def sy(J):
Ntot=J[0]
xb=J[1]
dNtotdt=nn2-nv
dxbdt=(-nv*xb-xb*dNtotdt)/Ntot
return[dNtotdt,dxbdt]
#odeint requires that we set up a vector of times (question asks for 0-10)
t_val=np.linspace(0,10,46) #46 for more accuracy
#we also need to make an initial condition vector
Yo=np.array([Ntoto,xbo])
#use odient function to find the concentrations
ans=odeint(sy,Yo,t_val)
print(ans)
</code></pre>
<p>please help</p>
|
[
{
"answer_id": 74522983,
"author": "DARK FLAME YT",
"author_id": 18405141,
"author_profile": "https://Stackoverflow.com/users/18405141",
"pm_score": -1,
"selected": false,
"text": "#This function take one Parameter \"var\"\ndef foo(var):\n return var\n\n#Calling the function with print statement\n\nprint(foo(var, var2)) #Trying to give more than 1 argument. But it gives error \n"
},
{
"answer_id": 74523010,
"author": "Ahmed AEK",
"author_id": 15649230,
"author_profile": "https://Stackoverflow.com/users/15649230",
"pm_score": 2,
"selected": true,
"text": "def sy(J,t):\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74522901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20179565/"
] |
74,522,915
|
<p>I need to send the binary representation of a varibale trough websocket, the problem is the variable can be string, can be intiger, can be anything.</p>
<pre><code>function send(bar) {
var foo = new TextEncoder('utf-8').encode(bar); // Works if 'bar' is string
var foo = new Int32Array([bar]).buffer; // Works if 'bar' is integer
}
</code></pre>
<p><strong>How I can convert any JavaScript variable to <em>Uint8Array</em> ?</strong></p>
<p>Objective:</p>
<p><code>send('Hello')</code> <strong>-></strong> <code>0x48 0x65 0x6C 0x6C 0x6F</code></p>
<p><code>send(123)</code> <strong>-></strong> <code>0x7B</code></p>
<p><em>Note: I don't have control of the server side</em></p>
|
[
{
"answer_id": 74522983,
"author": "DARK FLAME YT",
"author_id": 18405141,
"author_profile": "https://Stackoverflow.com/users/18405141",
"pm_score": -1,
"selected": false,
"text": "#This function take one Parameter \"var\"\ndef foo(var):\n return var\n\n#Calling the function with print statement\n\nprint(foo(var, var2)) #Trying to give more than 1 argument. But it gives error \n"
},
{
"answer_id": 74523010,
"author": "Ahmed AEK",
"author_id": 15649230,
"author_profile": "https://Stackoverflow.com/users/15649230",
"pm_score": 2,
"selected": true,
"text": "def sy(J,t):\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74522915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20292772/"
] |
74,522,985
|
<p>I have some json that contains regex</p>
<pre><code>[
{
"name": "For teachers",
"regex": "^Apple "
},
{
"name": "Long and yellow",
"regex": "banana$"
},
{
"name": "Cantaloupe",
"regex": ".*/melon/.*"
}
]
</code></pre>
<p>What I wanted to do is use the <code>.regex</code> value in the test function e.g.</p>
<pre><code>>>> jq '. | select( "path/to/melon/data" | test( .regex ) )' test.json
jq: error (at test.json:14): Cannot index string with string "regex"
</code></pre>
<p>I am trying to check if a string, passed in anyhow, matches any of the <code>.regex</code> in the json and if it does return the corresponding <code>.name</code>.</p>
<p>In the above <code>test.json</code>, passing a string => output:</p>
<ul>
<li>starting "Apples " => "For teachers"</li>
<li>ending "banana" => "Long and yellow"</li>
<li>containing the text "/melons/" => "Canteloupe"</li>
</ul>
<p>If there are multiple matches then return all the <code>.name</code> values where the <code>.regex</code> matches the passed in string. So from the comments:
"Apple or Is this /melon/ a banana" => [ "For teachers", "Long and yellow", "Canteloupe" ]</p>
<hr />
<p>I was considering trying something like building a sed command but I have not got that far and I think adding what I had was causing confusion rather than clarifying. Leaving it here so the comments make sense.</p>
<pre><code>>>> echo "path/to/melon/data" | sed -E -e 's#^Apple #For teachers #g' -e 's#banana$#long and yellow#g' -e 's#.*/melon/.*#Cantaloupe#g'
Cantaloupe
>>> echo "Is this banana" | sed -E -e 's#^Apple #For teachers#g' -e 's#banana$#long and yellow#g' -e 's#.*/melon/.*#Cantaloupe#g'
Is this long and yellow
</code></pre>
<p>I want a behaviour similar to this sed, but without me needing to construct lots of <code>-e</code> options from <code>jq</code> print.</p>
<p>I am sure I can get something like that to work, so every time the echoed in string matches a <code>.regex</code> it returns the corresponding <code>.name</code> but that is such a hack ... even for me! (Note: This sed is not doing what I want except in the melon case, because it is replacing the text matched rather than responding with the text)</p>
|
[
{
"answer_id": 74522983,
"author": "DARK FLAME YT",
"author_id": 18405141,
"author_profile": "https://Stackoverflow.com/users/18405141",
"pm_score": -1,
"selected": false,
"text": "#This function take one Parameter \"var\"\ndef foo(var):\n return var\n\n#Calling the function with print statement\n\nprint(foo(var, var2)) #Trying to give more than 1 argument. But it gives error \n"
},
{
"answer_id": 74523010,
"author": "Ahmed AEK",
"author_id": 15649230,
"author_profile": "https://Stackoverflow.com/users/15649230",
"pm_score": 2,
"selected": true,
"text": "def sy(J,t):\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74522985",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1695049/"
] |
74,523,018
|
<p>Here is my code that I am working on. It is supposed to take a number from the user and if its a perfect number it says so, but if its not it asks to enter a new number. When I get to the enter a new number part, it doesn't register my input. Can someone help me out?</p>
<pre><code>def isPerfect(num):
if num <= 0:
return False
total = 0
for i in range(1,num):
if num%i== 0:
total = total + i
if total == num:
return True
else:
return False
def main():
num = int(input("Enter a perfect integer: "))
if isPerfect(num) == False:
op = int(input(f"{num} is not a perfect number. Re-enter:"))
isPerfect(op)
elif isPerfect(num) == True:
print("Congratulations!",num, 'is a perfect number.')
if __name__ == '__main__':
main()
</code></pre>
|
[
{
"answer_id": 74523096,
"author": "maxxel_",
"author_id": 17575465,
"author_profile": "https://Stackoverflow.com/users/17575465",
"pm_score": 2,
"selected": true,
"text": "def main():\n first_run = True\n perfect_num_received = False\n while not perfect_num_received:\n if first_run:\n num = int(input(\"Enter a perfect integer: \"))\n first_run = False\n if isPerfect(num) == False:\n num = int(input(f\"{num} is not a perfect number. Re-enter:\"))\n elif isPerfect(num) == True:\n perfect_num_received = True\n print(\"Congratulations!\",num, 'is a perfect number.')\n if type(num) == int:\n ...\n"
},
{
"answer_id": 74523239,
"author": "mrboran",
"author_id": 9474969,
"author_profile": "https://Stackoverflow.com/users/9474969",
"pm_score": 0,
"selected": false,
"text": "def main():\nwhile True:\n num = int(input(\"Enter a perfect integer: \"))\n if isPerfect(num) == False:\n num = int(input(f\"{num} is not a perfect number. Re-enter: \"))\n isPerfect(num)\n elif isPerfect(num) == True:\n print(\"Congratulations! \",num, ' is a perfect number.')\n break\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74523018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20177890/"
] |
74,523,021
|
<p>I have created a Spring Initializr project:
<a href="https://i.stack.imgur.com/FkcIr.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>I import it to Eclipse IDE for Java Developers - Version: 2022-03 (4.23.0) - it's OK.</p>
<p>Then I launch JUnit test on my test class:
<a href="https://i.stack.imgur.com/PYlyN.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>Then I have this box popping up when I launch JUint test:
<a href="https://i.stack.imgur.com/9V0Ln.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>Is it not supposed to be working without any further POM or Eclipse configuration?</p>
<p>The JDK on Window -> Preferences -> Installed JRE is : jdk-11</p>
<p>This is the POM generated by Spring Initializr</p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.steph.spring</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
</code></pre>
<p>I don't know what to try since I expected it to work without any further POM or Eclipse configuration.</p>
|
[
{
"answer_id": 74523096,
"author": "maxxel_",
"author_id": 17575465,
"author_profile": "https://Stackoverflow.com/users/17575465",
"pm_score": 2,
"selected": true,
"text": "def main():\n first_run = True\n perfect_num_received = False\n while not perfect_num_received:\n if first_run:\n num = int(input(\"Enter a perfect integer: \"))\n first_run = False\n if isPerfect(num) == False:\n num = int(input(f\"{num} is not a perfect number. Re-enter:\"))\n elif isPerfect(num) == True:\n perfect_num_received = True\n print(\"Congratulations!\",num, 'is a perfect number.')\n if type(num) == int:\n ...\n"
},
{
"answer_id": 74523239,
"author": "mrboran",
"author_id": 9474969,
"author_profile": "https://Stackoverflow.com/users/9474969",
"pm_score": 0,
"selected": false,
"text": "def main():\nwhile True:\n num = int(input(\"Enter a perfect integer: \"))\n if isPerfect(num) == False:\n num = int(input(f\"{num} is not a perfect number. Re-enter: \"))\n isPerfect(num)\n elif isPerfect(num) == True:\n print(\"Congratulations! \",num, ' is a perfect number.')\n break\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74523021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20565299/"
] |
74,523,025
|
<p>I just want to say I am a newbie to OOP so I am not sure what I am supposed to do there.
so lets say I have a class that has a whole bunch of functions on data in it:</p>
<pre><code>class stuff:
def __init__ ...
def func1(self, arg1, arg2)
self.var1=arg1*self.var3
self.var2=arg2*self.var4
...
</code></pre>
<p>the func1 uses a lot of variables from the class (using self), and I have a lot of functions and a lot of variables which is very convenient in a class. However every once in a while I also need to use the function on data outside of an object. In that case I would have to pass var3 and var4 to the function and I don't know how to do that. Actually there are about 10 variables that I would have to pass.</p>
<p>So is there a good way to do that? Should I make a copy of every function for using outside of objects? But there are a lot of functions and they are quite long, and I will have to remove self. before every variable, it will be hard to maintain.</p>
<p>Should I create an object for all data I want to process? That would also be annoying, <strong>init</strong> does a lot of stuff that requires full data and moving it to separate functions will create a lot of them.</p>
<p>Should I make functions inside class that just call functions outside class? Two issues, I would have to name them differently and memorize both names, and what if the data I am passing is very big? Or is there a different way to do that?</p>
<p>So I was wondering if there is something to fix that in python because I don't know what to google. I've noticed a lot of libraries use "." in their function names so I assume those are in functions in classes, but I seem to use them on my data, without creating objects</p>
|
[
{
"answer_id": 74523130,
"author": "AlgoRythm",
"author_id": 8062151,
"author_profile": "https://Stackoverflow.com/users/8062151",
"pm_score": 0,
"selected": false,
"text": "self"
},
{
"answer_id": 74523157,
"author": "Edward Peters",
"author_id": 6016064,
"author_profile": "https://Stackoverflow.com/users/6016064",
"pm_score": 0,
"selected": false,
"text": "class MyFirstClass:\n def __init__(self, name):\n self.name = name\n\n @staticmethod\n def static_function():\n print(\"Static function called!\")\n def instance_function(self):\n print(\"Instance function called on \", self.name)\n \n \nclass MySecondClass:\n def main():\n MyFirstClass.static_function()\n anInstance = MyFirstClass(\"Adam\")\n anotherInstance = MyFirstClass(\"Bob\")\n anInstance.instance_function()\n anotherInstance.instance_function()\n \nMySecondClass.main()\n"
},
{
"answer_id": 74523241,
"author": "G. Anderson",
"author_id": 7835267,
"author_profile": "https://Stackoverflow.com/users/7835267",
"pm_score": 0,
"selected": false,
"text": "self class Stuff:\n def __init__() ...\n def func1(self, arg1, arg2, arg3=None, arg4=None)\n if arg3=None:\n self.var1=arg1*self.var3\n else:\n self.var1=arg1*arg3\n self.var2=arg2*self.var4\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74523025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15673832/"
] |
74,523,041
|
<p>I am trying to filter the map and in return, I want every filtered map element.</p>
<p><strong>Code:-</strong></p>
<pre><code>Map<String, Map<int, int>> temp = {Basic Terms: {1: 0}, Table and Column Naming Rules: {1: 1}};
var temp = temp.keys.where(element) => element.contains("basic"));
print(temp);
</code></pre>
<p><strong>Output:-</strong></p>
<pre><code>I/flutter (30857): (Basic Terms)
</code></pre>
<p><strong>Output I want</strong> :-</p>
<pre><code>I/flutter (30857): {Basic Terms: {1: 0}}
</code></pre>
|
[
{
"answer_id": 74523128,
"author": "Ben Konyi",
"author_id": 7933689,
"author_profile": "https://Stackoverflow.com/users/7933689",
"pm_score": 3,
"selected": true,
"text": "entries keys List<MapEntry> Map Map<String, Map<int, int>> temp = {\n 'Basic Terms': {1: 0}, \n 'Table and Column Naming Rules': {1: 1}\n};\n\nvar temp2 = Map.fromEntries(\n temp.entries.where(\n (entry) => entry.key.contains('Basic Terms')\n )\n);\nprint(temp2);\n {Basic Terms: {1: 0}}\n"
},
{
"answer_id": 74523227,
"author": "jbryanh",
"author_id": 13590970,
"author_profile": "https://Stackoverflow.com/users/13590970",
"pm_score": 0,
"selected": false,
"text": "Map<String, Map<int, int>> temp = {'Basic Terms': {1: 0}, 'Table and Column Naming Rules': {1: 1}};\n var thisTemp = temp.entries.firstWhere((element) => element.key.contains(\"Basic\"));\n print(thisTemp.toString());\n}\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74523041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20556797/"
] |
74,523,045
|
<p>I have this date format :
YYYY-MM-DD (example : 2022-05-10)
I want to extract only last 6 months inclunding current months.
The result normaly it's : june, july,august, september, octobre, november (6 last months)</p>
<p>I do this request :</p>
<pre><code>Select created_date
from table_A
Where created_date >= now() - INTERVAL 6 MONTH
</code></pre>
<p>The query gives me the last 7 months, that is to say from May 2022 to November 2022 and this is not what I want.</p>
<p>I want the last 6 months including the current month, i.e. from June to November</p>
<p>thank you in advance for your help</p>
|
[
{
"answer_id": 74523128,
"author": "Ben Konyi",
"author_id": 7933689,
"author_profile": "https://Stackoverflow.com/users/7933689",
"pm_score": 3,
"selected": true,
"text": "entries keys List<MapEntry> Map Map<String, Map<int, int>> temp = {\n 'Basic Terms': {1: 0}, \n 'Table and Column Naming Rules': {1: 1}\n};\n\nvar temp2 = Map.fromEntries(\n temp.entries.where(\n (entry) => entry.key.contains('Basic Terms')\n )\n);\nprint(temp2);\n {Basic Terms: {1: 0}}\n"
},
{
"answer_id": 74523227,
"author": "jbryanh",
"author_id": 13590970,
"author_profile": "https://Stackoverflow.com/users/13590970",
"pm_score": 0,
"selected": false,
"text": "Map<String, Map<int, int>> temp = {'Basic Terms': {1: 0}, 'Table and Column Naming Rules': {1: 1}};\n var thisTemp = temp.entries.firstWhere((element) => element.key.contains(\"Basic\"));\n print(thisTemp.toString());\n}\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74523045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9870351/"
] |
74,523,047
|
<p>i have an error with Uint64List in flutter Web (in pointycastle lib)</p>
<pre><code>var length = Uint8List.view((Uint64List(2)..[0] = iv.length * 8).buffer);
"Error: Unsupported operation: Uint64List not supported on the web.
dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 266:49 throw_
dart-sdk/lib/_internal/js_dev_runtime/patch/typed_data_patch.dart 115:5 new
packages/pointycastle/block/modes/gcm.dart 81:36 [_computeInitialCounter]
packages/pointycastle/block/modes/gcm.dart 61:16 prepare
packages/pointycastle/src/impl/base_aead_block_cipher.dart 217:5 reset
packages/pointycastle/block/modes/gcm.dart 47:11 reset
packages/pointycastle/src/impl/base_aead_block_cipher.dart 117:5 init
packages/pointycastle/block/modes/gcm.dart 40:11 init
packages/crypto_keys/src/symmetric_operator.dart 71:16 encrypt
</code></pre>
<p>Do you know how to fix that ?
Thx</p>
|
[
{
"answer_id": 74523128,
"author": "Ben Konyi",
"author_id": 7933689,
"author_profile": "https://Stackoverflow.com/users/7933689",
"pm_score": 3,
"selected": true,
"text": "entries keys List<MapEntry> Map Map<String, Map<int, int>> temp = {\n 'Basic Terms': {1: 0}, \n 'Table and Column Naming Rules': {1: 1}\n};\n\nvar temp2 = Map.fromEntries(\n temp.entries.where(\n (entry) => entry.key.contains('Basic Terms')\n )\n);\nprint(temp2);\n {Basic Terms: {1: 0}}\n"
},
{
"answer_id": 74523227,
"author": "jbryanh",
"author_id": 13590970,
"author_profile": "https://Stackoverflow.com/users/13590970",
"pm_score": 0,
"selected": false,
"text": "Map<String, Map<int, int>> temp = {'Basic Terms': {1: 0}, 'Table and Column Naming Rules': {1: 1}};\n var thisTemp = temp.entries.firstWhere((element) => element.key.contains(\"Basic\"));\n print(thisTemp.toString());\n}\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74523047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14702118/"
] |
74,523,141
|
<p>I want to download AWS DynamoDB data to Excel to allow me to work with the data locally. However, I have not been to get the data in a perfect CSV format.</p>
<p>What I have done: I use a Node.js application, which runs in AWS Lambda service to connect to the DynamoDB database. In addition, I can query the data from DynamoDB and then convert it to a CSV format, as detailed below:</p>
<pre><code>const AWS = require("aws-sdk");
AWS.config.update({ region: "us-east-1"})
const dynamo = new AWS.DynamoDB.DocumentClient({apiversion: "2012-08-10"});
exports.handler = async (event, context) => {
let body;
const headers = {
"Content-Type": "text/csv",
'Content-disposition': 'attachment; filename=testing.csv'
};
var params = {
KeyConditionExpression: 'dataId = :id',
ExpressionAttributeValues: {
':id': event.pathParameters.id,
},
TableName: "Table1",
};
body = await dynamo.query(params).promise();
//-----------------------------------
// convert json to csv
const items = body.Items
const replacer = (key, value) => value === null ? '' : value
const header = Object.keys(items[0])
let csv = [header.join(','),
...items.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','))
].join('\r\n')
body = JSON.stringify(csv);
return {
body,
headers,
};
};
</code></pre>
<p>The above solution works, but the output is not perfect; a sample is shown below (Note that there are three columns: relativeHumidity, waterTemperature, and airTemperature):</p>
<p>"relativeHumidity,waterTemperature,airTemperature\r\n26.123206154221034,21.716873058693757,23.859491598934557\r\n26.966163183232673,18.09642888420125,21.47952617547989\r\n33.79030978475366,18.995791668472204,17.451627574004128\r\n40.6641803491319,19.89060168145951,17.61247262137161"</p>
<p>However, I want an output that looks as shown below:</p>
<p>relativeHumidity,waterTemperature,airTemperature
26.123206154221034,21.716873058693757,23.859491598934557
26.966163183232673,18.09642888420125,21.47952617547989
33.79030978475366,18.995791668472204,17.451627574004128
40.6641803491319,19.89060168145951,17.61247262137161</p>
<p>I would appreciate any guide on how to achieve this. Note that I have tried <a href="https://aws.amazon.com/blogs/aws/new-export-amazon-dynamodb-table-data-to-data-lake-amazon-s3/" rel="nofollow noreferrer">this</a>, but the data is being exported to S3 in json format.</p>
<pre><code></code></pre>
|
[
{
"answer_id": 74523128,
"author": "Ben Konyi",
"author_id": 7933689,
"author_profile": "https://Stackoverflow.com/users/7933689",
"pm_score": 3,
"selected": true,
"text": "entries keys List<MapEntry> Map Map<String, Map<int, int>> temp = {\n 'Basic Terms': {1: 0}, \n 'Table and Column Naming Rules': {1: 1}\n};\n\nvar temp2 = Map.fromEntries(\n temp.entries.where(\n (entry) => entry.key.contains('Basic Terms')\n )\n);\nprint(temp2);\n {Basic Terms: {1: 0}}\n"
},
{
"answer_id": 74523227,
"author": "jbryanh",
"author_id": 13590970,
"author_profile": "https://Stackoverflow.com/users/13590970",
"pm_score": 0,
"selected": false,
"text": "Map<String, Map<int, int>> temp = {'Basic Terms': {1: 0}, 'Table and Column Naming Rules': {1: 1}};\n var thisTemp = temp.entries.firstWhere((element) => element.key.contains(\"Basic\"));\n print(thisTemp.toString());\n}\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74523141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14135099/"
] |
74,523,142
|
<p>This is my list</p>
<pre><code>list_names <- vector(mode = 'list')
list_names[['NAME A']] <- rnorm(n = 10,sd = 2)
list_names[['NAME B']] <- rnorm(n = 10,sd = 2)
list_names[['NAME C']] <- rnorm(n = 10,sd = 2)
list_names[['NAME D']] <- rnorm(n = 10,sd = 2)
list_names[['NAME E']] <- rnorm(n = 10,sd = 2)
list_names[['NAME F']] <- rnorm(n = 10,sd = 2)
</code></pre>
<p>Is it possible to select others elements of list doing something like this:</p>
<pre><code>list_names[[-"NAME A"]]
</code></pre>
<p>The output should be a list with all elements except the <code>"NAME A"</code> element?</p>
|
[
{
"answer_id": 74523155,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 3,
"selected": true,
"text": "[ [[ - setdiff list_names[setdiff(names(list_names), \"NAME A\")]\n $`NAME B`\n [1] -3.237378 4.082310 1.330150 1.784154 1.360302 5.530083 -4.593817 -2.021845 -2.278811 5.359281\n\n$`NAME C`\n [1] 0.7641719 -0.9874008 0.9278225 -0.9709333 -0.1113175 -0.2290865 -0.2682319 2.8789682 0.6797194 -1.8765561\n\n$`NAME D`\n [1] 3.8257606 -3.0235199 -3.4250881 -0.1333553 0.1202357 0.3694179 -2.0254176 -1.9489545 1.1015625 2.5311685\n\n$`NAME E`\n [1] 2.4825388 -0.9485210 -2.7486256 -1.1970403 -1.3655852 -0.4481327 -2.0552594 0.3480588 1.9688285 1.1266358\n\n$`NAME F`\n [1] 2.7535404 1.9831037 -2.3185156 0.5392882 1.0800234 -3.3278948 -1.7413377 -1.9040359 1.2478318 1.2664443\n list_names[names(list_names) != \"NAME A\"]\n"
},
{
"answer_id": 74523198,
"author": "Dan Adams",
"author_id": 13210554,
"author_profile": "https://Stackoverflow.com/users/13210554",
"pm_score": 2,
"selected": false,
"text": "%in% names(l) l <- list(a = 1:3,\n b = 1:3,\n c = 1:3)\n\nexclude_names <- \"a\"\n\nl[!names(l) %in% exclude_names]\n#> $b\n#> [1] 1 2 3\n#> \n#> $c\n#> [1] 1 2 3\n"
},
{
"answer_id": 74523203,
"author": "ThomasIsCoding",
"author_id": 12158757,
"author_profile": "https://Stackoverflow.com/users/12158757",
"pm_score": 2,
"selected": false,
"text": "list_names[-match('NAME A',names(list_names))]\n list_names NULL"
},
{
"answer_id": 74523452,
"author": "TarJae",
"author_id": 13321647,
"author_profile": "https://Stackoverflow.com/users/13321647",
"pm_score": 2,
"selected": false,
"text": "purrr NAME A zap purrr::list_modify(list_names,`NAME A`=purrr::zap())\n $`NAME B`\n [1] -0.8390912 1.3642602 0.5660608 -0.9540717 -0.3867816 -0.2885152 2.2319706 -1.3307411 -1.6760324 1.2665064\n\n$`NAME C`\n [1] -2.2107425 2.2710206 1.9398283 0.8652335 1.7688116 0.4958797 -0.6015274 1.3835770 3.7064383 0.8566645\n\n$`NAME D`\n [1] 0.59945041 -2.35641913 0.58695111 0.42641701 1.16167489 0.05766859 1.37930744 0.18369875 0.62319538\n[10] -0.36985800\n\n$`NAME E`\n [1] 4.197209 -3.543006 2.558110 3.378172 -2.749093 1.549671 -1.237776 4.361019 1.611182 -1.038159\n\n$`NAME F`\n [1] -0.3487643 1.0043091 -0.5399112 1.0901489 0.5731137 -1.2881900 1.0738251 1.8890504 1.0534804 0.4025011\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74523142",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20359538/"
] |
74,523,170
|
<p>Looks like there is issue with java's <code>Math.round</code> function, when passing integer value to it.
I ran it for couple of inputs but giving suprisingly wrong results.</p>
<p>Sample Code:</p>
<pre><code> public static void main(String[] args) {
System.out.println("roundOff1: " + Math.round(1669053278));
System.out.println("roundOff2: " + Math.round(1669053304));
System.out.println("roundOff3: " + Math.round(1669053314));
System.out.println("roundOff4: " + Math.round(1669053339));
}
</code></pre>
<p>Stdout:</p>
<pre><code>roundOff1: 1669053312
roundOff2: 1669053312
roundOff3: 1669053312
roundOff4: 1669053312
</code></pre>
<p>My use case was to round of the <code>System.currentTimeMillis()/1000</code> but end in getting wrong result.
Did I really found a bug in Java or missing something here?</p>
|
[
{
"answer_id": 74523155,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 3,
"selected": true,
"text": "[ [[ - setdiff list_names[setdiff(names(list_names), \"NAME A\")]\n $`NAME B`\n [1] -3.237378 4.082310 1.330150 1.784154 1.360302 5.530083 -4.593817 -2.021845 -2.278811 5.359281\n\n$`NAME C`\n [1] 0.7641719 -0.9874008 0.9278225 -0.9709333 -0.1113175 -0.2290865 -0.2682319 2.8789682 0.6797194 -1.8765561\n\n$`NAME D`\n [1] 3.8257606 -3.0235199 -3.4250881 -0.1333553 0.1202357 0.3694179 -2.0254176 -1.9489545 1.1015625 2.5311685\n\n$`NAME E`\n [1] 2.4825388 -0.9485210 -2.7486256 -1.1970403 -1.3655852 -0.4481327 -2.0552594 0.3480588 1.9688285 1.1266358\n\n$`NAME F`\n [1] 2.7535404 1.9831037 -2.3185156 0.5392882 1.0800234 -3.3278948 -1.7413377 -1.9040359 1.2478318 1.2664443\n list_names[names(list_names) != \"NAME A\"]\n"
},
{
"answer_id": 74523198,
"author": "Dan Adams",
"author_id": 13210554,
"author_profile": "https://Stackoverflow.com/users/13210554",
"pm_score": 2,
"selected": false,
"text": "%in% names(l) l <- list(a = 1:3,\n b = 1:3,\n c = 1:3)\n\nexclude_names <- \"a\"\n\nl[!names(l) %in% exclude_names]\n#> $b\n#> [1] 1 2 3\n#> \n#> $c\n#> [1] 1 2 3\n"
},
{
"answer_id": 74523203,
"author": "ThomasIsCoding",
"author_id": 12158757,
"author_profile": "https://Stackoverflow.com/users/12158757",
"pm_score": 2,
"selected": false,
"text": "list_names[-match('NAME A',names(list_names))]\n list_names NULL"
},
{
"answer_id": 74523452,
"author": "TarJae",
"author_id": 13321647,
"author_profile": "https://Stackoverflow.com/users/13321647",
"pm_score": 2,
"selected": false,
"text": "purrr NAME A zap purrr::list_modify(list_names,`NAME A`=purrr::zap())\n $`NAME B`\n [1] -0.8390912 1.3642602 0.5660608 -0.9540717 -0.3867816 -0.2885152 2.2319706 -1.3307411 -1.6760324 1.2665064\n\n$`NAME C`\n [1] -2.2107425 2.2710206 1.9398283 0.8652335 1.7688116 0.4958797 -0.6015274 1.3835770 3.7064383 0.8566645\n\n$`NAME D`\n [1] 0.59945041 -2.35641913 0.58695111 0.42641701 1.16167489 0.05766859 1.37930744 0.18369875 0.62319538\n[10] -0.36985800\n\n$`NAME E`\n [1] 4.197209 -3.543006 2.558110 3.378172 -2.749093 1.549671 -1.237776 4.361019 1.611182 -1.038159\n\n$`NAME F`\n [1] -0.3487643 1.0043091 -0.5399112 1.0901489 0.5731137 -1.2881900 1.0738251 1.8890504 1.0534804 0.4025011\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74523170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7934026/"
] |
74,523,171
|
<p>I currently have a .NET 4 Web API using Entity Framework 3 that I'm upgrading to .NET 6 / EF Core. I currently have a LINQ query that looks like this (and works fine):</p>
<pre><code>[HttpGet]
public async Task<ActionResults> GetCars()
{
var x = from f in _context.CarMakes
group c in f.Make into m
select new { c.Key };
return Json(new
{
data = await x.ToListAsync()
};
}
</code></pre>
<p>This returns the following data:</p>
<pre><code>Chevy
Ford
Volvo
Toyota
</code></pre>
<p>and so on.</p>
<p>I'm trying to use this same query in an ASP.NET Core 6 Web API that is using EF Core, but it fails, and throws an error.</p>
<p>In the .NET 6 / EF Core project, I have:</p>
<pre><code>[HttpGet]
public async Task<ActionResults<IEnumerable<CarMakes>>>> GetCars()
{
var x = from f in _context.CarMakes
group c in f.Make into m
select new { c.Key };
return await x.ToListAsync();
}
</code></pre>
<p>I get an error message of:</p>
<blockquote>
<p>Cannot implicity convert type 'System.Threading.Task.Task<System.Collections.GenericList</p>
</blockquote>
|
[
{
"answer_id": 74523155,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 3,
"selected": true,
"text": "[ [[ - setdiff list_names[setdiff(names(list_names), \"NAME A\")]\n $`NAME B`\n [1] -3.237378 4.082310 1.330150 1.784154 1.360302 5.530083 -4.593817 -2.021845 -2.278811 5.359281\n\n$`NAME C`\n [1] 0.7641719 -0.9874008 0.9278225 -0.9709333 -0.1113175 -0.2290865 -0.2682319 2.8789682 0.6797194 -1.8765561\n\n$`NAME D`\n [1] 3.8257606 -3.0235199 -3.4250881 -0.1333553 0.1202357 0.3694179 -2.0254176 -1.9489545 1.1015625 2.5311685\n\n$`NAME E`\n [1] 2.4825388 -0.9485210 -2.7486256 -1.1970403 -1.3655852 -0.4481327 -2.0552594 0.3480588 1.9688285 1.1266358\n\n$`NAME F`\n [1] 2.7535404 1.9831037 -2.3185156 0.5392882 1.0800234 -3.3278948 -1.7413377 -1.9040359 1.2478318 1.2664443\n list_names[names(list_names) != \"NAME A\"]\n"
},
{
"answer_id": 74523198,
"author": "Dan Adams",
"author_id": 13210554,
"author_profile": "https://Stackoverflow.com/users/13210554",
"pm_score": 2,
"selected": false,
"text": "%in% names(l) l <- list(a = 1:3,\n b = 1:3,\n c = 1:3)\n\nexclude_names <- \"a\"\n\nl[!names(l) %in% exclude_names]\n#> $b\n#> [1] 1 2 3\n#> \n#> $c\n#> [1] 1 2 3\n"
},
{
"answer_id": 74523203,
"author": "ThomasIsCoding",
"author_id": 12158757,
"author_profile": "https://Stackoverflow.com/users/12158757",
"pm_score": 2,
"selected": false,
"text": "list_names[-match('NAME A',names(list_names))]\n list_names NULL"
},
{
"answer_id": 74523452,
"author": "TarJae",
"author_id": 13321647,
"author_profile": "https://Stackoverflow.com/users/13321647",
"pm_score": 2,
"selected": false,
"text": "purrr NAME A zap purrr::list_modify(list_names,`NAME A`=purrr::zap())\n $`NAME B`\n [1] -0.8390912 1.3642602 0.5660608 -0.9540717 -0.3867816 -0.2885152 2.2319706 -1.3307411 -1.6760324 1.2665064\n\n$`NAME C`\n [1] -2.2107425 2.2710206 1.9398283 0.8652335 1.7688116 0.4958797 -0.6015274 1.3835770 3.7064383 0.8566645\n\n$`NAME D`\n [1] 0.59945041 -2.35641913 0.58695111 0.42641701 1.16167489 0.05766859 1.37930744 0.18369875 0.62319538\n[10] -0.36985800\n\n$`NAME E`\n [1] 4.197209 -3.543006 2.558110 3.378172 -2.749093 1.549671 -1.237776 4.361019 1.611182 -1.038159\n\n$`NAME F`\n [1] -0.3487643 1.0043091 -0.5399112 1.0901489 0.5731137 -1.2881900 1.0738251 1.8890504 1.0534804 0.4025011\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74523171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8382717/"
] |
74,523,217
|
<p>I have couple of lists and one of them looks like this :</p>
<p><code>['SHAPE69', 'SHAPE48', 'SHAPE15', 'SHAPE28', 'SHAPE33', 'SHAPE27', ...]</code> with 100 shapes in the list.
If the shape number is even, then convert it to <code>0.0</code>, which is a float number.
If the shape number is odd, then convert it to <code>1.0</code>, which is also a float number.
The result list should be like <code>[1.0, 0.0, 1.0, 0.0, 1.0, 1.0, ...]</code>.</p>
<p>How could I convert the list easily?</p>
|
[
{
"answer_id": 74523299,
"author": "Danielle M.",
"author_id": 3434388,
"author_profile": "https://Stackoverflow.com/users/3434388",
"pm_score": 3,
"selected": true,
"text": "input_list = ['SHAPE69', 'SHAPE48', 'SHAPE15', 'SHAPE28', 'SHAPE33', 'SHAPE27']\n\n\ndef converter(s: str) -> float:\n shape_length = len('SHAPE')\n substr = s[shape_length:]\n try:\n shape_integer = int(substr)\n except ValueError:\n raise ValueError(f'failed to extract integer value from string {s}')\n if shape_integer % 2 == 0:\n # it's even\n return 0.0\n else:\n return 1.0\n\n\noutput_list = [converter(x) for x in input_list]\nprint(output_list)\n[1.0, 0.0, 1.0, 0.0, 1.0, 1.0]\n converter SHAPE12"
},
{
"answer_id": 74523325,
"author": "sofuslund",
"author_id": 17312019,
"author_profile": "https://Stackoverflow.com/users/17312019",
"pm_score": 0,
"selected": false,
"text": "array = ['SHAPE69', 'SHAPE48', 'SHAPE15', 'SHAPE28', 'SHAPE33', 'SHAPE27']\nfloat_array = []\nfor item in array:\n if int(item[6:8]) % 2 == 0:\n float_array.append(0.0)\n else:\n float_array.append(1.0)\nprint(float_array)\n"
},
{
"answer_id": 74523435,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 1,
"selected": false,
"text": "% l = ['SHAPE69', 'SHAPE48', 'SHAPE15', 'SHAPE28', 'SHAPE33', 'SHAPE27']\nout = [int(s.removeprefix('SHAPE'))%2 for s in l]\n removeprefix out = [int(s[5:])%2 for s in l]\n [1, 0, 1, 0, 1, 1]\n import pandas as pd\n\nout = pd.to_numeric(pd.Series(l).str.extract(r'(\\d+)', expand=False)\n ).mod(2).tolist()\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74523217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11299809/"
] |
74,523,266
|
<p>I've been messing around with Rust and the immutable variable idea is interesting to me.
so I've been using it in my C programs as well. But now I'm wondering if there is any difference in a local variable that is defined with the "const" keyword and one that isn't.</p>
<p>I assume both are still put on the stack so there is no difference? other than the fact that it cannot be modified after declared and initialized obviously.</p>
|
[
{
"answer_id": 74523880,
"author": "Brendan",
"author_id": 559737,
"author_profile": "https://Stackoverflow.com/users/559737",
"pm_score": 0,
"selected": false,
"text": "const const"
},
{
"answer_id": 74524514,
"author": "John Bollinger",
"author_id": 2402272,
"author_profile": "https://Stackoverflow.com/users/2402272",
"pm_score": 2,
"selected": true,
"text": "const const const const const const const"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74523266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16452111/"
] |
74,523,271
|
<p>See the following program for g++.</p>
<pre><code>#define seed1 0
#include <iostream>
#include <random>
int main()
{
double mean = 0.0;
double stddev = 1.0;
std::mt19937 generator1 (seed1);
std::normal_distribution<double> normal(mean, stddev);
std::cerr << "Normal: " << normal(generator1) << std::endl;
}
</code></pre>
<p>I want to get the state of generator1 (as a seed) and remove generator1 for later
instantiate again the distribution with the new seed and go on in the place I left I want to put this code in a function and call it to generate Gaussian points in the start state I want. And at the end of the function save the state as a seed.</p>
|
[
{
"answer_id": 74523368,
"author": "Blindy",
"author_id": 108796,
"author_profile": "https://Stackoverflow.com/users/108796",
"pm_score": 3,
"selected": false,
"text": "<< >> stream << generator1 << normal;\n mt19937 generator;\nstream >> generator;\n\nnormal_distribution<double> distribution;\nstream >> distribution;\n"
},
{
"answer_id": 74523681,
"author": "Maciej Polański",
"author_id": 19165018,
"author_profile": "https://Stackoverflow.com/users/19165018",
"pm_score": 0,
"selected": false,
"text": "#define seed1 0\n#include <iostream>\n#include <random>\n\n\nint main()\n{\n double mean = 0.0;\n double stddev = 1.0;\n\n std::mt19937 generator1 (seed1);\n std::normal_distribution<double> normal(mean, stddev);\n\n std::cerr << \"Normal: \" << normal(generator1) << std::endl;\n\n std::mt19937 generator2 = generator1;\n std::normal_distribution<double> normal2 = normal;\n\n std::cerr << \"Normal: \" << normal(generator1) << std::endl;\n std::cerr << \"Normal2: \" << normal2(generator2) << std::endl;\n\n\n// I want to get the state of generator1 (as a seed) and remove generator1 for later \n //instantiate again the distribution with the new seed and go on in the place I left \n // I want to put this code in a function and call it to generate Gaussian points in \n// the start state I want. And at the end of the function save the state as a seed.\n}\n"
},
{
"answer_id": 74523963,
"author": "Michaël Roy",
"author_id": 2430669,
"author_profile": "https://Stackoverflow.com/users/2430669",
"pm_score": 0,
"selected": false,
"text": "std::mt19937::discard() Example:\n#define seed1 0\n#include <cassert>\n#include <iostream>\n#include <random>\n\n// spoof a generator that counts the number of calls\n\nclass my_mt19937 : public std::mt19937 {\n public:\n result_type operator()() {\n ++call_count_;\n return std::mt19937::operator()();\n }\n\n void seed(result_type value = default_seed) {\n original_seed_ = value;\n std::mt19937::seed(value);\n }\n\n void discard(unsigned long long z) {\n call_count_ += z;\n std::mt19937::discard(z);\n }\n\n unsigned long long call_count() const noexcept { return call_count_; }\n\n result_type original_seed() const noexcept { return original_seed_; }\n\n private:\n result_type original_seed_ = default_seed;\n unsigned long long call_count_ = 0;\n};\n\nint main() {\n double mean = 0.0;\n double stddev = 1.0;\n\n my_mt19937 gen1;\n gen1.seed(seed1);\n\n const size_t N = 10'000;\n\n for (size_t i = 0; i < N; ++i) {\n my_mt19937 gen2;\n gen2.seed(gen1.original_seed());\n gen2.discard(gen1.call_count());\n\n if (gen2() != gen1()) {\n std::cout << \"failed for i = \" << i << \"\\n\";\n return 1;\n }\n }\n\n // this extneds to distribution objects that \n // use the generators\n\n std::normal_distribution<double> normal1;\n std::normal_distribution<double> normal2;\n\n for (size_t i = 0; i < N; ++i) {\n my_mt19937 gen2;\n gen2.seed(gen1.original_seed());\n gen2.discard(gen1.call_count());\n\n if (normal1(gen1) != normal2(gen2)) {\n std::cout << \"failed for i = \" << i << \"\\n\";\n return 1;\n }\n }\n\n std::cout << \"Success! Tested \" << N << \" values\\n\";\n\n return 0;\n}\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74523271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4385984/"
] |
74,523,274
|
<p>Looking for some assistance, I have created a flow and a canvas app in power apps that calls an API, I finally got it to work but seems there has to be an easier way to do this.</p>
<p>In my flow I'm taking the body and parsing it to get just what I need then returning the body of that response to the canvas app. I could bypass that step and just return the body of the Api Call step, but my main question is, it seems a little to much to have to write some regex in my function when I click the button to call my flow.</p>
<p>This creates the collection for me with the correct fields, but is there an easier way for the app to know my schema without having to manually define it?</p>
<p><a href="https://i.stack.imgur.com/voOPr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/voOPr.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/Zwygt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Zwygt.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74523368,
"author": "Blindy",
"author_id": 108796,
"author_profile": "https://Stackoverflow.com/users/108796",
"pm_score": 3,
"selected": false,
"text": "<< >> stream << generator1 << normal;\n mt19937 generator;\nstream >> generator;\n\nnormal_distribution<double> distribution;\nstream >> distribution;\n"
},
{
"answer_id": 74523681,
"author": "Maciej Polański",
"author_id": 19165018,
"author_profile": "https://Stackoverflow.com/users/19165018",
"pm_score": 0,
"selected": false,
"text": "#define seed1 0\n#include <iostream>\n#include <random>\n\n\nint main()\n{\n double mean = 0.0;\n double stddev = 1.0;\n\n std::mt19937 generator1 (seed1);\n std::normal_distribution<double> normal(mean, stddev);\n\n std::cerr << \"Normal: \" << normal(generator1) << std::endl;\n\n std::mt19937 generator2 = generator1;\n std::normal_distribution<double> normal2 = normal;\n\n std::cerr << \"Normal: \" << normal(generator1) << std::endl;\n std::cerr << \"Normal2: \" << normal2(generator2) << std::endl;\n\n\n// I want to get the state of generator1 (as a seed) and remove generator1 for later \n //instantiate again the distribution with the new seed and go on in the place I left \n // I want to put this code in a function and call it to generate Gaussian points in \n// the start state I want. And at the end of the function save the state as a seed.\n}\n"
},
{
"answer_id": 74523963,
"author": "Michaël Roy",
"author_id": 2430669,
"author_profile": "https://Stackoverflow.com/users/2430669",
"pm_score": 0,
"selected": false,
"text": "std::mt19937::discard() Example:\n#define seed1 0\n#include <cassert>\n#include <iostream>\n#include <random>\n\n// spoof a generator that counts the number of calls\n\nclass my_mt19937 : public std::mt19937 {\n public:\n result_type operator()() {\n ++call_count_;\n return std::mt19937::operator()();\n }\n\n void seed(result_type value = default_seed) {\n original_seed_ = value;\n std::mt19937::seed(value);\n }\n\n void discard(unsigned long long z) {\n call_count_ += z;\n std::mt19937::discard(z);\n }\n\n unsigned long long call_count() const noexcept { return call_count_; }\n\n result_type original_seed() const noexcept { return original_seed_; }\n\n private:\n result_type original_seed_ = default_seed;\n unsigned long long call_count_ = 0;\n};\n\nint main() {\n double mean = 0.0;\n double stddev = 1.0;\n\n my_mt19937 gen1;\n gen1.seed(seed1);\n\n const size_t N = 10'000;\n\n for (size_t i = 0; i < N; ++i) {\n my_mt19937 gen2;\n gen2.seed(gen1.original_seed());\n gen2.discard(gen1.call_count());\n\n if (gen2() != gen1()) {\n std::cout << \"failed for i = \" << i << \"\\n\";\n return 1;\n }\n }\n\n // this extneds to distribution objects that \n // use the generators\n\n std::normal_distribution<double> normal1;\n std::normal_distribution<double> normal2;\n\n for (size_t i = 0; i < N; ++i) {\n my_mt19937 gen2;\n gen2.seed(gen1.original_seed());\n gen2.discard(gen1.call_count());\n\n if (normal1(gen1) != normal2(gen2)) {\n std::cout << \"failed for i = \" << i << \"\\n\";\n return 1;\n }\n }\n\n std::cout << \"Success! Tested \" << N << \" values\\n\";\n\n return 0;\n}\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74523274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5236167/"
] |
74,523,284
|
<p>I'm have an test scenario where i need to scroll the screen down so the element can be loaded in the HTML. Using Headless as False the test goes as planned but as soon I run it with Headless as True, the scroll is executed but the HTML isen't loaded and my test fail.</p>
<p>My test scenario is like this:</p>
<pre><code>Open_course
[Tags] Q-18
Login Access
Wait Until Element Is Visible ${pageHome.ContinueStudying}
Execute Javascript window.scrollBy(0,1000)
Click ${pageHome.courseHowtoTest}
Click ${pageHome.buttonIWant}
</code></pre>
<p>This is how the website stay when the scroll is executed in Headless == True:</p>
<p><a href="https://imgur.com/2u2HJos" rel="nofollow noreferrer">https://imgur.com/2u2HJos</a></p>
<p>Obs: I blurried the image for anonymity.</p>
<p>After the two last cards, it should load more course cards.</p>
<p>I looked up if someone had the same problem but didn't find any correleted issues.</p>
<p>I don't know if it is some limitation from the robot framework working with infinite scroll in headless mode or there is some other javascript command that work better with infinite-scroll.</p>
|
[
{
"answer_id": 74523368,
"author": "Blindy",
"author_id": 108796,
"author_profile": "https://Stackoverflow.com/users/108796",
"pm_score": 3,
"selected": false,
"text": "<< >> stream << generator1 << normal;\n mt19937 generator;\nstream >> generator;\n\nnormal_distribution<double> distribution;\nstream >> distribution;\n"
},
{
"answer_id": 74523681,
"author": "Maciej Polański",
"author_id": 19165018,
"author_profile": "https://Stackoverflow.com/users/19165018",
"pm_score": 0,
"selected": false,
"text": "#define seed1 0\n#include <iostream>\n#include <random>\n\n\nint main()\n{\n double mean = 0.0;\n double stddev = 1.0;\n\n std::mt19937 generator1 (seed1);\n std::normal_distribution<double> normal(mean, stddev);\n\n std::cerr << \"Normal: \" << normal(generator1) << std::endl;\n\n std::mt19937 generator2 = generator1;\n std::normal_distribution<double> normal2 = normal;\n\n std::cerr << \"Normal: \" << normal(generator1) << std::endl;\n std::cerr << \"Normal2: \" << normal2(generator2) << std::endl;\n\n\n// I want to get the state of generator1 (as a seed) and remove generator1 for later \n //instantiate again the distribution with the new seed and go on in the place I left \n // I want to put this code in a function and call it to generate Gaussian points in \n// the start state I want. And at the end of the function save the state as a seed.\n}\n"
},
{
"answer_id": 74523963,
"author": "Michaël Roy",
"author_id": 2430669,
"author_profile": "https://Stackoverflow.com/users/2430669",
"pm_score": 0,
"selected": false,
"text": "std::mt19937::discard() Example:\n#define seed1 0\n#include <cassert>\n#include <iostream>\n#include <random>\n\n// spoof a generator that counts the number of calls\n\nclass my_mt19937 : public std::mt19937 {\n public:\n result_type operator()() {\n ++call_count_;\n return std::mt19937::operator()();\n }\n\n void seed(result_type value = default_seed) {\n original_seed_ = value;\n std::mt19937::seed(value);\n }\n\n void discard(unsigned long long z) {\n call_count_ += z;\n std::mt19937::discard(z);\n }\n\n unsigned long long call_count() const noexcept { return call_count_; }\n\n result_type original_seed() const noexcept { return original_seed_; }\n\n private:\n result_type original_seed_ = default_seed;\n unsigned long long call_count_ = 0;\n};\n\nint main() {\n double mean = 0.0;\n double stddev = 1.0;\n\n my_mt19937 gen1;\n gen1.seed(seed1);\n\n const size_t N = 10'000;\n\n for (size_t i = 0; i < N; ++i) {\n my_mt19937 gen2;\n gen2.seed(gen1.original_seed());\n gen2.discard(gen1.call_count());\n\n if (gen2() != gen1()) {\n std::cout << \"failed for i = \" << i << \"\\n\";\n return 1;\n }\n }\n\n // this extneds to distribution objects that \n // use the generators\n\n std::normal_distribution<double> normal1;\n std::normal_distribution<double> normal2;\n\n for (size_t i = 0; i < N; ++i) {\n my_mt19937 gen2;\n gen2.seed(gen1.original_seed());\n gen2.discard(gen1.call_count());\n\n if (normal1(gen1) != normal2(gen2)) {\n std::cout << \"failed for i = \" << i << \"\\n\";\n return 1;\n }\n }\n\n std::cout << \"Success! Tested \" << N << \" values\\n\";\n\n return 0;\n}\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74523284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13544304/"
] |
74,523,304
|
<p>As part of my uninstaller script, I'd like to delete my app's directory in <code>~/Application Support/My App Name</code>.</p>
<p>My uninstaller script is Apple Script. I've tried the following:</p>
<pre><code>tell application "Finder" to delete (POSIX file "~/Library/Application Support/My App Name")
</code></pre>
<pre><code>do shell script \"
sudo rm -rf '~/Library/Application Support/My App Name'
\" with administrator privileges
"""
</code></pre>
<p>But none of these had any effect, my app's Application Support directory remains. How can I get this done?</p>
|
[
{
"answer_id": 74523368,
"author": "Blindy",
"author_id": 108796,
"author_profile": "https://Stackoverflow.com/users/108796",
"pm_score": 3,
"selected": false,
"text": "<< >> stream << generator1 << normal;\n mt19937 generator;\nstream >> generator;\n\nnormal_distribution<double> distribution;\nstream >> distribution;\n"
},
{
"answer_id": 74523681,
"author": "Maciej Polański",
"author_id": 19165018,
"author_profile": "https://Stackoverflow.com/users/19165018",
"pm_score": 0,
"selected": false,
"text": "#define seed1 0\n#include <iostream>\n#include <random>\n\n\nint main()\n{\n double mean = 0.0;\n double stddev = 1.0;\n\n std::mt19937 generator1 (seed1);\n std::normal_distribution<double> normal(mean, stddev);\n\n std::cerr << \"Normal: \" << normal(generator1) << std::endl;\n\n std::mt19937 generator2 = generator1;\n std::normal_distribution<double> normal2 = normal;\n\n std::cerr << \"Normal: \" << normal(generator1) << std::endl;\n std::cerr << \"Normal2: \" << normal2(generator2) << std::endl;\n\n\n// I want to get the state of generator1 (as a seed) and remove generator1 for later \n //instantiate again the distribution with the new seed and go on in the place I left \n // I want to put this code in a function and call it to generate Gaussian points in \n// the start state I want. And at the end of the function save the state as a seed.\n}\n"
},
{
"answer_id": 74523963,
"author": "Michaël Roy",
"author_id": 2430669,
"author_profile": "https://Stackoverflow.com/users/2430669",
"pm_score": 0,
"selected": false,
"text": "std::mt19937::discard() Example:\n#define seed1 0\n#include <cassert>\n#include <iostream>\n#include <random>\n\n// spoof a generator that counts the number of calls\n\nclass my_mt19937 : public std::mt19937 {\n public:\n result_type operator()() {\n ++call_count_;\n return std::mt19937::operator()();\n }\n\n void seed(result_type value = default_seed) {\n original_seed_ = value;\n std::mt19937::seed(value);\n }\n\n void discard(unsigned long long z) {\n call_count_ += z;\n std::mt19937::discard(z);\n }\n\n unsigned long long call_count() const noexcept { return call_count_; }\n\n result_type original_seed() const noexcept { return original_seed_; }\n\n private:\n result_type original_seed_ = default_seed;\n unsigned long long call_count_ = 0;\n};\n\nint main() {\n double mean = 0.0;\n double stddev = 1.0;\n\n my_mt19937 gen1;\n gen1.seed(seed1);\n\n const size_t N = 10'000;\n\n for (size_t i = 0; i < N; ++i) {\n my_mt19937 gen2;\n gen2.seed(gen1.original_seed());\n gen2.discard(gen1.call_count());\n\n if (gen2() != gen1()) {\n std::cout << \"failed for i = \" << i << \"\\n\";\n return 1;\n }\n }\n\n // this extneds to distribution objects that \n // use the generators\n\n std::normal_distribution<double> normal1;\n std::normal_distribution<double> normal2;\n\n for (size_t i = 0; i < N; ++i) {\n my_mt19937 gen2;\n gen2.seed(gen1.original_seed());\n gen2.discard(gen1.call_count());\n\n if (normal1(gen1) != normal2(gen2)) {\n std::cout << \"failed for i = \" << i << \"\\n\";\n return 1;\n }\n }\n\n std::cout << \"Success! Tested \" << N << \" values\\n\";\n\n return 0;\n}\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74523304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1072846/"
] |
74,523,326
|
<p>I work on a primitive website,and i got a sidenav code,built-in in the HTML.
My problem is,i didn't know,how do i put the sidenav to the right side.
(I would like the animation to start from the right and "open" from the right side)
(I know,it was a answer in Stackoverflow,but i cant do it to work :( )
Thanks the help!</p>
<pre><code><!DOCTYPE html>
<html lang="hu">
<head>
<meta charset="UTF-16">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Próbálkozás</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
* {
box-sizing: border-box;
}
body {
font-family: Arial;
padding: 20px;
background: #000000;
}
.header {
padding: 10px;
font-size: 40px;
text-align: center;
background: rgb(85, 85, 85);
}
.leftcolumn {
float: left;
width: 75%;
}
.leftcolumn {
float: left;
width: 61%;
}
.rightcolumn {
float: left;
width: 39%;
padding-left: 20px;
}
.fakeimg {
background-color: #aaa;
width: 100%;
padding: 20px;
}
.card {
background-color: white;
padding: 20px;
margin-top: 20px;
}
.row:after {
content: "";
display: table;
clear: both;
}
.footer {
padding: 20px;
text-align: center;
background: #ddd;
margin-top: 20px;
}
@media screen and (max-width: 800px) {
.leftcolumn, .rightcolumn {
width: 100%;
padding: 0;
}
}
</style>
<style>
body {
margin: 0;
font-family: Arial, Helvetica, sans-serif;
}
.topnav {
overflow: hidden;
background-color: rgb(0, 0, 0);
}
.topnav a {
float: left;
color: #ff0000;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 17px;
}
.topnav a:hover {
background-color: #707070;
color: black;
}
.topnav a.active {
background-color: #707070;
color: white;
}
body {
font-family: "Lato", sans-serif;
transition: background-color .5s;
}
.sidenav {
height: 100%;
width: 0;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: rgb(70, 70, 70);
overflow-x: hidden;
transition: 0.5s;
padding-top: 60px;
}
.sidenav a {
padding: 8px 8px 8px 32px;
text-decoration: none;
font-size: 25px;
color: #818181;
display: block;
transition: 0.5s;
}
.sidenav a:hover {
color: #f1f1f1;
}
.sidenav .closebtn {
position: absolute;
top: 0;
right: 25px;
font-size: 36px;
margin-left: 50px;
}
#main {
transition: margin-left 50s;
padding: 16px;
}
@media screen and (max-height: 450px) {
.sidenav {padding-top: 15px;}
.sidenav a {font-size: 18px;}
}
</style>
</head>
<body>
<div class="topnav" >
<a href="Main.html" > Kezdőlap </a>
<a href="Electro.html" > Electrotechnika </a>
<a href="Infó.html" > Informatika</a>
<a href="Gépészet.html" > Gépészet </a>
<a href="Közg.html" > Közgazdálkodás </a>
<a class="active" href="próbálkozás.html" > Egyéb </a>
<span class="active" style="font-size:30px;cursor:pointer;color:rgb(255, 0, 0); " onclick="openNav()">&#9776;</span>
</div>
<div id="mySidenav" class="sidenav">
<a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>
<a href="#">Kezdőlap</a>
<a href="#">Services</a>
<a href="#">Clients</a>
<a href="#">Contact</a>
<a href="#">asdasd</a>
</div>
<div id="main">
<h2 style="color:white;"> -</h2>
<p style="color:white;"> - </p>
</div>
<script>
function openNav() {
document.getElementById("mySidenav").style.width = "250px";
document.getElementById("main").style.marginLeft = "250px";
document.body.style.backgroundColor = "rgb(0, 0, 0)";
}
function closeNav() {
document.getElementById("mySidenav").style.width = "0";
document.getElementById("main").style.marginLeft= "0";
document.body.style.backgroundColor = "black";
}
</script>
</body>
</html>
</code></pre>
|
[
{
"answer_id": 74523368,
"author": "Blindy",
"author_id": 108796,
"author_profile": "https://Stackoverflow.com/users/108796",
"pm_score": 3,
"selected": false,
"text": "<< >> stream << generator1 << normal;\n mt19937 generator;\nstream >> generator;\n\nnormal_distribution<double> distribution;\nstream >> distribution;\n"
},
{
"answer_id": 74523681,
"author": "Maciej Polański",
"author_id": 19165018,
"author_profile": "https://Stackoverflow.com/users/19165018",
"pm_score": 0,
"selected": false,
"text": "#define seed1 0\n#include <iostream>\n#include <random>\n\n\nint main()\n{\n double mean = 0.0;\n double stddev = 1.0;\n\n std::mt19937 generator1 (seed1);\n std::normal_distribution<double> normal(mean, stddev);\n\n std::cerr << \"Normal: \" << normal(generator1) << std::endl;\n\n std::mt19937 generator2 = generator1;\n std::normal_distribution<double> normal2 = normal;\n\n std::cerr << \"Normal: \" << normal(generator1) << std::endl;\n std::cerr << \"Normal2: \" << normal2(generator2) << std::endl;\n\n\n// I want to get the state of generator1 (as a seed) and remove generator1 for later \n //instantiate again the distribution with the new seed and go on in the place I left \n // I want to put this code in a function and call it to generate Gaussian points in \n// the start state I want. And at the end of the function save the state as a seed.\n}\n"
},
{
"answer_id": 74523963,
"author": "Michaël Roy",
"author_id": 2430669,
"author_profile": "https://Stackoverflow.com/users/2430669",
"pm_score": 0,
"selected": false,
"text": "std::mt19937::discard() Example:\n#define seed1 0\n#include <cassert>\n#include <iostream>\n#include <random>\n\n// spoof a generator that counts the number of calls\n\nclass my_mt19937 : public std::mt19937 {\n public:\n result_type operator()() {\n ++call_count_;\n return std::mt19937::operator()();\n }\n\n void seed(result_type value = default_seed) {\n original_seed_ = value;\n std::mt19937::seed(value);\n }\n\n void discard(unsigned long long z) {\n call_count_ += z;\n std::mt19937::discard(z);\n }\n\n unsigned long long call_count() const noexcept { return call_count_; }\n\n result_type original_seed() const noexcept { return original_seed_; }\n\n private:\n result_type original_seed_ = default_seed;\n unsigned long long call_count_ = 0;\n};\n\nint main() {\n double mean = 0.0;\n double stddev = 1.0;\n\n my_mt19937 gen1;\n gen1.seed(seed1);\n\n const size_t N = 10'000;\n\n for (size_t i = 0; i < N; ++i) {\n my_mt19937 gen2;\n gen2.seed(gen1.original_seed());\n gen2.discard(gen1.call_count());\n\n if (gen2() != gen1()) {\n std::cout << \"failed for i = \" << i << \"\\n\";\n return 1;\n }\n }\n\n // this extneds to distribution objects that \n // use the generators\n\n std::normal_distribution<double> normal1;\n std::normal_distribution<double> normal2;\n\n for (size_t i = 0; i < N; ++i) {\n my_mt19937 gen2;\n gen2.seed(gen1.original_seed());\n gen2.discard(gen1.call_count());\n\n if (normal1(gen1) != normal2(gen2)) {\n std::cout << \"failed for i = \" << i << \"\\n\";\n return 1;\n }\n }\n\n std::cout << \"Success! Tested \" << N << \" values\\n\";\n\n return 0;\n}\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74523326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20486287/"
] |
74,523,354
|
<p>I've been searching everywhere to find a way to filter a column that contains both Text and Numbers, I want to filter out the numbers only from that column.</p>
<p>Thanks.</p>
|
[
{
"answer_id": 74523368,
"author": "Blindy",
"author_id": 108796,
"author_profile": "https://Stackoverflow.com/users/108796",
"pm_score": 3,
"selected": false,
"text": "<< >> stream << generator1 << normal;\n mt19937 generator;\nstream >> generator;\n\nnormal_distribution<double> distribution;\nstream >> distribution;\n"
},
{
"answer_id": 74523681,
"author": "Maciej Polański",
"author_id": 19165018,
"author_profile": "https://Stackoverflow.com/users/19165018",
"pm_score": 0,
"selected": false,
"text": "#define seed1 0\n#include <iostream>\n#include <random>\n\n\nint main()\n{\n double mean = 0.0;\n double stddev = 1.0;\n\n std::mt19937 generator1 (seed1);\n std::normal_distribution<double> normal(mean, stddev);\n\n std::cerr << \"Normal: \" << normal(generator1) << std::endl;\n\n std::mt19937 generator2 = generator1;\n std::normal_distribution<double> normal2 = normal;\n\n std::cerr << \"Normal: \" << normal(generator1) << std::endl;\n std::cerr << \"Normal2: \" << normal2(generator2) << std::endl;\n\n\n// I want to get the state of generator1 (as a seed) and remove generator1 for later \n //instantiate again the distribution with the new seed and go on in the place I left \n // I want to put this code in a function and call it to generate Gaussian points in \n// the start state I want. And at the end of the function save the state as a seed.\n}\n"
},
{
"answer_id": 74523963,
"author": "Michaël Roy",
"author_id": 2430669,
"author_profile": "https://Stackoverflow.com/users/2430669",
"pm_score": 0,
"selected": false,
"text": "std::mt19937::discard() Example:\n#define seed1 0\n#include <cassert>\n#include <iostream>\n#include <random>\n\n// spoof a generator that counts the number of calls\n\nclass my_mt19937 : public std::mt19937 {\n public:\n result_type operator()() {\n ++call_count_;\n return std::mt19937::operator()();\n }\n\n void seed(result_type value = default_seed) {\n original_seed_ = value;\n std::mt19937::seed(value);\n }\n\n void discard(unsigned long long z) {\n call_count_ += z;\n std::mt19937::discard(z);\n }\n\n unsigned long long call_count() const noexcept { return call_count_; }\n\n result_type original_seed() const noexcept { return original_seed_; }\n\n private:\n result_type original_seed_ = default_seed;\n unsigned long long call_count_ = 0;\n};\n\nint main() {\n double mean = 0.0;\n double stddev = 1.0;\n\n my_mt19937 gen1;\n gen1.seed(seed1);\n\n const size_t N = 10'000;\n\n for (size_t i = 0; i < N; ++i) {\n my_mt19937 gen2;\n gen2.seed(gen1.original_seed());\n gen2.discard(gen1.call_count());\n\n if (gen2() != gen1()) {\n std::cout << \"failed for i = \" << i << \"\\n\";\n return 1;\n }\n }\n\n // this extneds to distribution objects that \n // use the generators\n\n std::normal_distribution<double> normal1;\n std::normal_distribution<double> normal2;\n\n for (size_t i = 0; i < N; ++i) {\n my_mt19937 gen2;\n gen2.seed(gen1.original_seed());\n gen2.discard(gen1.call_count());\n\n if (normal1(gen1) != normal2(gen2)) {\n std::cout << \"failed for i = \" << i << \"\\n\";\n return 1;\n }\n }\n\n std::cout << \"Success! Tested \" << N << \" values\\n\";\n\n return 0;\n}\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74523354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13985941/"
] |
74,523,375
|
<p>I want to convert "22.11.2022 00:00:00" to Mon Nov 21 2022 00:00:00 GMT+0300 (GMT+03:00) and set picker value.</p>
<p>My code:</p>
<pre><code>view.picker.setValue(this.jsonData.dateData)
</code></pre>
<p>I tried</p>
<pre><code>console.log(Ext.Date.format(dt, 'l, \\t\\he jS \\of F Y h:i:s A')); // Wednesday, the 10th of January 2007 03:05:01 PM
</code></pre>
<p>but it didn't work.</p>
<p>How can I do this?</p>
|
[
{
"answer_id": 74534543,
"author": "KaMun",
"author_id": 12397027,
"author_profile": "https://Stackoverflow.com/users/12397027",
"pm_score": 1,
"selected": true,
"text": "new Date(this.jsonData.dateData) const dateString = \"22.11.2022 00:00:00\",\n dateObject = new Date(dateString.replace(/(.*)\\.(.*)\\.(.*)/, '$2-$1-$3'));\n\npicker.setValue(dateObject);\n"
},
{
"answer_id": 74584602,
"author": "hwsw",
"author_id": 1816139,
"author_profile": "https://Stackoverflow.com/users/1816139",
"pm_score": 1,
"selected": false,
"text": "Ext.Date.parse('22.11.2022 00:00:00', 'd.m.Y H:i:s')\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74523375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20295668/"
] |
74,523,418
|
<p>I am writing to an LCD and have developed the drivers to accept a string input for the value. I have a variable called "cycles" that is a uint16. I need to convert that value to a string and write it to the display. My string write function prototype is as follows:</p>
<pre><code>void lcd_string(uint8_t column, uint8_t page, const uint8_t *font_address, const char *str)
</code></pre>
<p>My way of displaying the value is to break the value into individual digits and write them individually to the display at the proper position.</p>
<p>I have the following code that works for what I want to do, but I would like to eliminate the long if/else if statement if possible.</p>
<pre><code>loop = 0;
while (cycles_1 > 0) {
temp = cycles_1 % 10;
if (temp == 9) lcd_string(36 - (6 * loop),6,font_6x8_num,"9");
else if (temp == 8) lcd_string(36 - (6 * loop),6,font_6x8_num,"8");
else if (temp == 7) lcd_string(36 - (6 * loop),6,font_6x8_num,"7");
else if (temp == 6) lcd_string(36 - (6 * loop),6,font_6x8_num,"6");
else if (temp == 5) lcd_string(36 - (6 * loop),6,font_6x8_num,"5");
else if (temp == 4) lcd_string(36 - (6 * loop),6,font_6x8_num,"4");
else if (temp == 3) lcd_string(36 - (6 * loop),6,font_6x8_num,"3");
else if (temp == 2) lcd_string(36 - (6 * loop),6,font_6x8_num,"2");
else if (temp == 1) lcd_string(36 - (6 * loop),6,font_6x8_num,"1");
else if (temp == 0) lcd_string(36 - (6 * loop),6,font_6x8_num,"0");
cycles_1 /= 10;
loop++;
}
</code></pre>
<p>I tried the following but the string was not writing to the display.</p>
<pre><code>loop = 0;
while (cycles_1 > 0) {
temp = cycles_1 % 10;
lcd_string(36 - (6 * loop),6,font_6x8_num,{0x30 + temp, '\0'});
cycles_1 /= 10;
loop++;
}
</code></pre>
<p>I figured adding 0x30 to the temp value would convert it to an ASCII number and then I would terminate it with a null termination character, but this doesn't seem to be working. Any suggestions of what I might try?</p>
|
[
{
"answer_id": 74534543,
"author": "KaMun",
"author_id": 12397027,
"author_profile": "https://Stackoverflow.com/users/12397027",
"pm_score": 1,
"selected": true,
"text": "new Date(this.jsonData.dateData) const dateString = \"22.11.2022 00:00:00\",\n dateObject = new Date(dateString.replace(/(.*)\\.(.*)\\.(.*)/, '$2-$1-$3'));\n\npicker.setValue(dateObject);\n"
},
{
"answer_id": 74584602,
"author": "hwsw",
"author_id": 1816139,
"author_profile": "https://Stackoverflow.com/users/1816139",
"pm_score": 1,
"selected": false,
"text": "Ext.Date.parse('22.11.2022 00:00:00', 'd.m.Y H:i:s')\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74523418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8412185/"
] |
74,523,433
|
<pre><code>a=-1.4
b=42273.85
awk "BEGIN {print ($a + $b)}"
</code></pre>
<p>42272.4</p>
<p>I am expecting result as <strong>42272.45</strong>, what is wrong here?</p>
|
[
{
"answer_id": 74523570,
"author": "Ed Morton",
"author_id": 1745001,
"author_profile": "https://Stackoverflow.com/users/1745001",
"pm_score": 3,
"selected": true,
"text": "%.6g CONVFMT a=-1.4\nb=42273.85\nawk -v a=\"$a\" -v b=\"$b\" 'BEGIN {printf \"%.2f\\n\", (a + b)}'\n42272.45\n"
},
{
"answer_id": 74523577,
"author": "Andre Wildberg",
"author_id": 9462095,
"author_profile": "https://Stackoverflow.com/users/9462095",
"pm_score": 2,
"selected": false,
"text": "sh bash zsh bc echo \"$a + $b\" | bc\n42272.45\n awk printf awk -v a=\"$a\" -v b=\"$b\" 'BEGIN{printf(\"%.2f\\n\", a + b)}' \n42272.45\n"
},
{
"answer_id": 74531709,
"author": "Daweo",
"author_id": 10785975,
"author_profile": "https://Stackoverflow.com/users/10785975",
"pm_score": 0,
"selected": false,
"text": "printf OFMT print a=-1.4\nb=42273.85\nawk -v a=$a -v b=$b 'BEGIN{OFMT=\"%.2f\";print a + b}'\n 42272.45\n OFMT print %.6g OFMT print"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74523433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11002896/"
] |
74,523,475
|
<p>I Want to change font-weight to normal of h2 element. I'm trying to do it by change it in parent directory.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>h2 {
margin: 0;
padding: 0;
}
.top, .date {
display: inline-block;
width: 150px;
height: 30px;
border: 2px solid black;
text-align: center;
}
.date {
float: right;
font-size: 16px;
font-weight: normal;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="instrument" class="top">
<h2>SP500</h2>
</div>
<div id="date" class="top date">
<h2>Data</h2>
</div>
<div class="date">
<h2>Czas Zamknięcia</h2>
</div></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74523521,
"author": "reza hrkeng",
"author_id": 20517507,
"author_profile": "https://Stackoverflow.com/users/20517507",
"pm_score": 0,
"selected": false,
"text": "h2 {\n margin: 0;\n padding: 0;\n}\n.top, .date {\n display: inline-block;\n width: 150px;\n height: 30px;\n border: 2px solid black;\n text-align: center;\n}\n.date {\n \n font-size: 16px; \n font-weight: normal; \n}\n .date>h2 {\n \n font-size: 16px; \n font-weight: normal !important; \n} <div id=\"instrument\" class=\"top\">\n <h2>SP500</h2>\n</div>\n<div id=\"date\" class=\"top date\">\n <h2>Data</h2>\n</div>\n<div class=\"date\">\n <h2>Czas Zamknięcia</h2>\n</div>"
},
{
"answer_id": 74523534,
"author": "Liemannen loop",
"author_id": 15541450,
"author_profile": "https://Stackoverflow.com/users/15541450",
"pm_score": 2,
"selected": true,
"text": "parent-tag h2 {\n font-weight: normal;\n}\n .className/#idName h2 {\n font-weight: normal;\n}\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74523475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20479364/"
] |
74,523,496
|
<p>Is there any way to tell if a circle has such defects? Roundness does not work. Or is there a way to eliminate them?</p>
<p><img src="https://i.stack.imgur.com/jGssp.png" alt="enter image description here" /></p>
<pre class="lang-py prettyprint-override"><code> perimeter = cv2.arcLength(cnts[0],True)
area = cv2.contourArea(cnts[0])
roundness = 4*pi*area/(perimeter*perimeter)
print("Roundness:", roundness)
</code></pre>
|
[
{
"answer_id": 74524509,
"author": "Cris Luengo",
"author_id": 7328782,
"author_profile": "https://Stackoverflow.com/users/7328782",
"pm_score": 2,
"selected": false,
"text": "cv2.arcLength() import cv2\nimport numpy as np\n\n# read in OP's example image, making sure we ignore the red arrow\nimg = cv2.imread('jGssp.png')[:, :, 1]\n_, img = cv2.threshold(img, 127, 255, 0)\n\n# get the contour of the shape\ncontours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\ncontour = contours[0][:, 0, :]\n\n# add the first point as the last, to close it\ncontour = np.concatenate((contour, contour[0, None, :]))\n\n# compute centroid\ndef cross_product(v1, v2):\n \"\"\"2D cross product.\"\"\"\n return v1[0] * v2[1] - v1[1] * v2[0]\n\nsum = 0.0\nxsum = 0.0\nysum = 0.0\nfor ii in range(1, contour.shape[0]):\n v = cross_product(contour[ii - 1, :], contour[ii, :])\n sum += v\n xsum += (contour[ii - 1, 0] + contour[ii, 0]) * v\n ysum += (contour[ii - 1, 1] + contour[ii, 1]) * v\n\ncentroid = np.array([ xsum, ysum ]) / (3 * sum)\n\n# Compute coefficient of variation of distances to centroid (==circularity)\nd = np.sqrt(np.sum((contour - centroid) ** 2, axis=1))\ncircularity = np.std(d) / np.mean(d)\n"
},
{
"answer_id": 74578112,
"author": "fmw42",
"author_id": 7355741,
"author_profile": "https://Stackoverflow.com/users/7355741",
"pm_score": 0,
"selected": false,
"text": "import cv2\nimport numpy as np\n\n# Read image\nimg = cv2.imread('circle_defect.png')\nhh, ww = img.shape[:2]\n\n# threshold on white to remove red arrow\nlower = (255,255,255)\nupper = (255,255,255)\nthresh = cv2.inRange(img, lower, upper)\n\n# get Hough circles\nmin_dist = int(ww/5)\ncircles = cv2.HoughCircles(thresh, cv2.HOUGH_GRADIENT, 1, minDist=min_dist, param1=150, param2=15, minRadius=0, maxRadius=0)\nprint(circles)\n\n# draw circles on input thresh (without red arrow)\ncircle_img = thresh.copy()\ncircle_img = cv2.merge([circle_img,circle_img,circle_img])\nfor circle in circles[0]:\n # draw the circle in the output image, then draw a rectangle\n # corresponding to the center of the circle\n (x,y,r) = circle\n x = int(x)\n y = int(y)\n r = int(r)\n cv2.circle(circle_img, (x, y), r, (0, 0, 255), 1)\n\n# draw filled circle on black background\ncircle_filled = np.zeros_like(thresh)\ncv2.circle(circle_filled, (x,y), r, 255, -1)\n\n# get difference between the thresh image and the circle_filled image\ndiff = cv2.absdiff(thresh, circle_filled)\n\n# apply morphology to remove ring\nkernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5))\nresult = cv2.morphologyEx(diff, cv2.MORPH_OPEN, kernel)\n\n# count non-zero pixels\ndefect_count = np.count_nonzero(result)\nprint(\"defect count:\", defect_count)\n\n# save results\ncv2.imwrite('circle_defect_thresh.jpg', thresh)\ncv2.imwrite('circle_defect_circle.jpg', circle_img)\ncv2.imwrite('circle_defect_circle_diff.jpg', diff)\ncv2.imwrite('circle_defect_detected.png', result)\n\n# show images\ncv2.imshow('thresh', thresh)\ncv2.imshow('circle_filled', circle_filled)\ncv2.imshow('diff', diff)\ncv2.imshow('result', result)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n defect count: 500\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74523496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20244691/"
] |
74,523,507
|
<p>I have frequency data on 520 users. I want to calculate the overall mean and sd for each user. Later I want to use the mean and sd to calculate shape and scale for fitting them to a Beta distribution. I have tried a couple of methods.
Consider my data look like the following:</p>
<pre><code>Mfrq.df.2=structure(list(X = 1:6, User.ID = c(37593L, 38643L, 49433L, 60403L,
70923L, 85363L), V1 = c(9L, 3L, 4L, 80L, 19L, 0L), V2 = c(10L,
0L, 29L, 113L, 21L, 1L), V3 = c(5L, 2L, 17L, 77L, 7L, 2L), V4 = c(2L,
2L, 16L, 47L, 4L, 3L), V5 = c(2L, 10L, 16L, 40L, 1L, 8L), V6 = c(4L,
0L, 9L, 22L, 1L, 7L), V7 = c(6L, 8L, 9L, 8L, 0L, 6L), V8 = c(2L,
17L, 16L, 24L, 2L, 1L), V9 = c(3L, 20L, 7L, 30L, 0L, 4L), V10 = c(2L,
11L, 5L, 11L, 2L, 3L)), row.names = c(NA, 6L), class = "data.frame")
</code></pre>
<p>This was my first attempt for mean & sd:</p>
<pre><code>MidPoint.0=c(5,15,25,35,45,55,65,75,85,95)
record.beta.0= Mfrq.df.2 %>%
rowwise() %>%
mutate(Mean.Freq.0=sum((c(V1, V2, V3, V4, V5, V6, V7, V8, V9, V10))*MidPoint.0/sum(c(V1, V2, V3, V4, V5, V6, V7, V8, V9, V10)))) %>%
mutate(SD.Freq.0=sqrt(sum(MidPoint.0-Mean.Freq.0)**2*(c(V1, V2, V3, V4, V5, V6, V7, V8, V9, V10))/sum(c(V1, V2, V3, V4, V5, V6, V7, V8, V9, V10))-1))
</code></pre>
<p>This records the mean for me, but I get into the following error:</p>
<pre><code>Error in mutate(., SD.Freq.0 = sqrt(sum(MidPoint.0 - Mean.Freq.0)^2 * :
x `SD.Freq.0` must be size 1, not 10.
ℹ Did you mean: `SD.Freq.0 = list(sqrt(...))` ?
ℹ The error occurred in row 1.
</code></pre>
<p>Then I tried this format of data:</p>
<pre><code>structure(list(X = 1:10, User.ID = c(37593L, 37593L, 37593L,
37593L, 37593L, 37593L, 37593L, 37593L, 37593L, 37593L), Value = c(9L,
10L, 5L, 2L, 2L, 4L, 6L, 2L, 3L, 2L), MidPoint = c(5, 15, 25,
35, 45, 55, 65, 75, 85, 95)), row.names = c(NA, 10L), class = "data.frame")
</code></pre>
<p>With this code:</p>
<pre><code>record.beta <- Mfrq.df.2_long %>% data.frame %>%
group_by(User.ID) %>%
mutate(Mean.Freq=sum(Value*MidPoint)/sum(Value)) %>%
mutate(SD.Freq=sqrt(sum(MidPoint-Mean.Freq)**2*Value)/sum(Value-1))
</code></pre>
<p>But I realized it gives me a distinct SD value for each MidPoint.
However, it seems to work properly when I code it for an individual user.</p>
<pre><code>U37593.df=Mfrq.df.2_long[Mfrq.df.2_long$User.ID==37593,]
Mean=sum(U37593.df$MidPoint*U37593.df$Value)/sum(U37593.df$Value)
SD=sqrt(sum((U37593.df$MidPoint - Mean)**2*U37593.df$Value)/(sum(U37593.df$Value) - 1))
</code></pre>
<p>Is there any way that I can get ONE SD along with ONE mean for each user (User.ID)?</p>
|
[
{
"answer_id": 74524509,
"author": "Cris Luengo",
"author_id": 7328782,
"author_profile": "https://Stackoverflow.com/users/7328782",
"pm_score": 2,
"selected": false,
"text": "cv2.arcLength() import cv2\nimport numpy as np\n\n# read in OP's example image, making sure we ignore the red arrow\nimg = cv2.imread('jGssp.png')[:, :, 1]\n_, img = cv2.threshold(img, 127, 255, 0)\n\n# get the contour of the shape\ncontours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\ncontour = contours[0][:, 0, :]\n\n# add the first point as the last, to close it\ncontour = np.concatenate((contour, contour[0, None, :]))\n\n# compute centroid\ndef cross_product(v1, v2):\n \"\"\"2D cross product.\"\"\"\n return v1[0] * v2[1] - v1[1] * v2[0]\n\nsum = 0.0\nxsum = 0.0\nysum = 0.0\nfor ii in range(1, contour.shape[0]):\n v = cross_product(contour[ii - 1, :], contour[ii, :])\n sum += v\n xsum += (contour[ii - 1, 0] + contour[ii, 0]) * v\n ysum += (contour[ii - 1, 1] + contour[ii, 1]) * v\n\ncentroid = np.array([ xsum, ysum ]) / (3 * sum)\n\n# Compute coefficient of variation of distances to centroid (==circularity)\nd = np.sqrt(np.sum((contour - centroid) ** 2, axis=1))\ncircularity = np.std(d) / np.mean(d)\n"
},
{
"answer_id": 74578112,
"author": "fmw42",
"author_id": 7355741,
"author_profile": "https://Stackoverflow.com/users/7355741",
"pm_score": 0,
"selected": false,
"text": "import cv2\nimport numpy as np\n\n# Read image\nimg = cv2.imread('circle_defect.png')\nhh, ww = img.shape[:2]\n\n# threshold on white to remove red arrow\nlower = (255,255,255)\nupper = (255,255,255)\nthresh = cv2.inRange(img, lower, upper)\n\n# get Hough circles\nmin_dist = int(ww/5)\ncircles = cv2.HoughCircles(thresh, cv2.HOUGH_GRADIENT, 1, minDist=min_dist, param1=150, param2=15, minRadius=0, maxRadius=0)\nprint(circles)\n\n# draw circles on input thresh (without red arrow)\ncircle_img = thresh.copy()\ncircle_img = cv2.merge([circle_img,circle_img,circle_img])\nfor circle in circles[0]:\n # draw the circle in the output image, then draw a rectangle\n # corresponding to the center of the circle\n (x,y,r) = circle\n x = int(x)\n y = int(y)\n r = int(r)\n cv2.circle(circle_img, (x, y), r, (0, 0, 255), 1)\n\n# draw filled circle on black background\ncircle_filled = np.zeros_like(thresh)\ncv2.circle(circle_filled, (x,y), r, 255, -1)\n\n# get difference between the thresh image and the circle_filled image\ndiff = cv2.absdiff(thresh, circle_filled)\n\n# apply morphology to remove ring\nkernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5))\nresult = cv2.morphologyEx(diff, cv2.MORPH_OPEN, kernel)\n\n# count non-zero pixels\ndefect_count = np.count_nonzero(result)\nprint(\"defect count:\", defect_count)\n\n# save results\ncv2.imwrite('circle_defect_thresh.jpg', thresh)\ncv2.imwrite('circle_defect_circle.jpg', circle_img)\ncv2.imwrite('circle_defect_circle_diff.jpg', diff)\ncv2.imwrite('circle_defect_detected.png', result)\n\n# show images\ncv2.imshow('thresh', thresh)\ncv2.imshow('circle_filled', circle_filled)\ncv2.imshow('diff', diff)\ncv2.imshow('result', result)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n defect count: 500\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74523507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15507628/"
] |
74,523,513
|
<p>I am trying to read tweets having specific keywords using docker. I have taken reference from
<a href="https://github.com/youheekil/Twitter-Streaming-with-Apache-Kafka-Docker-and-Python/blob/main/src/producer.py" rel="nofollow noreferrer">Github link</a> .</p>
<p>I have made some minor changes. While I'm trying to execute I am facing issues with a number of arguments through all the details in place. It would be great if anybody can guide me where I'm doing wrong</p>
<pre><code>### twitter
import tweepy
from tweepy.auth import OAuthHandler
from tweepy import Stream
#from tweepy.streaming import StreamListener
import json
import logging
### logging
FORMAT = "%(asctime)s | %(name)s - %(levelname)s - %(message)s"
LOG_FILEPATH = "C:\\docker-kafka\\log\\testing.log"
logging.basicConfig(
filename=LOG_FILEPATH,
level=logging.INFO,
filemode='w',
format=FORMAT)
### Authenticate to Twitter
with open('C:\\docker-kafka\\credential.json','r') as f:
credential = json.load(f)
CONSUMER_KEY = credential['twitter_api_key']
CONSUMER_SECRET = credential['twitter_api_secret_key']
ACCESS_TOKEN = credential['twitter_access_token']
ACCESS_TOKEN_SECRET = credential['twitter_access_token_secret']
BEARER_TOKEN = credential['bearer_token']
#from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
from kafka import KafkaProducer
producer = KafkaProducer(bootstrap_servers='localhost:9092',
value_serializer=lambda v: v.encode('utf-8')) #Same port as your Kafka server
topic_name = "docker-twitter"
class twitterAuth():
"""SET UP TWITTER AUTHENTICATION"""
def authenticateTwitterApp(self):
auth = OAuthHandler(consumer_key=CONSUMER_KEY, consumer_secret=CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
return auth
class TwitterStreamer():
"""SET UP STREAMER"""
def __init__(self):
self.twitterAuth = twitterAuth()
def stream_tweets(self):
while True:
listener = ListenerTS()
auth = self.twitterAuth.authenticateTwitterApp()
stream = Stream(auth, listener)
stream.filter(track=["Starbucks"], stall_warnings=True, languages= ["en"])
class ListenerTS(tweepy.Stream):
def on_status(self, status):
tweet = json.dumps({
'id': status.id,
'text': status.text,
'created_at': status.created_at.strftime("%Y-%m-%d %H:%M:%S")
}, default=str)
producer.send(topic_name, tweet)
return True
if __name__ == "__main__":
TS = TwitterStreamer()
TS.stream_tweets()
</code></pre>
<p><a href="https://i.stack.imgur.com/II3Rr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/II3Rr.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74524509,
"author": "Cris Luengo",
"author_id": 7328782,
"author_profile": "https://Stackoverflow.com/users/7328782",
"pm_score": 2,
"selected": false,
"text": "cv2.arcLength() import cv2\nimport numpy as np\n\n# read in OP's example image, making sure we ignore the red arrow\nimg = cv2.imread('jGssp.png')[:, :, 1]\n_, img = cv2.threshold(img, 127, 255, 0)\n\n# get the contour of the shape\ncontours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\ncontour = contours[0][:, 0, :]\n\n# add the first point as the last, to close it\ncontour = np.concatenate((contour, contour[0, None, :]))\n\n# compute centroid\ndef cross_product(v1, v2):\n \"\"\"2D cross product.\"\"\"\n return v1[0] * v2[1] - v1[1] * v2[0]\n\nsum = 0.0\nxsum = 0.0\nysum = 0.0\nfor ii in range(1, contour.shape[0]):\n v = cross_product(contour[ii - 1, :], contour[ii, :])\n sum += v\n xsum += (contour[ii - 1, 0] + contour[ii, 0]) * v\n ysum += (contour[ii - 1, 1] + contour[ii, 1]) * v\n\ncentroid = np.array([ xsum, ysum ]) / (3 * sum)\n\n# Compute coefficient of variation of distances to centroid (==circularity)\nd = np.sqrt(np.sum((contour - centroid) ** 2, axis=1))\ncircularity = np.std(d) / np.mean(d)\n"
},
{
"answer_id": 74578112,
"author": "fmw42",
"author_id": 7355741,
"author_profile": "https://Stackoverflow.com/users/7355741",
"pm_score": 0,
"selected": false,
"text": "import cv2\nimport numpy as np\n\n# Read image\nimg = cv2.imread('circle_defect.png')\nhh, ww = img.shape[:2]\n\n# threshold on white to remove red arrow\nlower = (255,255,255)\nupper = (255,255,255)\nthresh = cv2.inRange(img, lower, upper)\n\n# get Hough circles\nmin_dist = int(ww/5)\ncircles = cv2.HoughCircles(thresh, cv2.HOUGH_GRADIENT, 1, minDist=min_dist, param1=150, param2=15, minRadius=0, maxRadius=0)\nprint(circles)\n\n# draw circles on input thresh (without red arrow)\ncircle_img = thresh.copy()\ncircle_img = cv2.merge([circle_img,circle_img,circle_img])\nfor circle in circles[0]:\n # draw the circle in the output image, then draw a rectangle\n # corresponding to the center of the circle\n (x,y,r) = circle\n x = int(x)\n y = int(y)\n r = int(r)\n cv2.circle(circle_img, (x, y), r, (0, 0, 255), 1)\n\n# draw filled circle on black background\ncircle_filled = np.zeros_like(thresh)\ncv2.circle(circle_filled, (x,y), r, 255, -1)\n\n# get difference between the thresh image and the circle_filled image\ndiff = cv2.absdiff(thresh, circle_filled)\n\n# apply morphology to remove ring\nkernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5))\nresult = cv2.morphologyEx(diff, cv2.MORPH_OPEN, kernel)\n\n# count non-zero pixels\ndefect_count = np.count_nonzero(result)\nprint(\"defect count:\", defect_count)\n\n# save results\ncv2.imwrite('circle_defect_thresh.jpg', thresh)\ncv2.imwrite('circle_defect_circle.jpg', circle_img)\ncv2.imwrite('circle_defect_circle_diff.jpg', diff)\ncv2.imwrite('circle_defect_detected.png', result)\n\n# show images\ncv2.imshow('thresh', thresh)\ncv2.imshow('circle_filled', circle_filled)\ncv2.imshow('diff', diff)\ncv2.imshow('result', result)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n defect count: 500\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74523513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19846154/"
] |
74,523,564
|
<p>I have a super large dataset that i'm trying to shrink.
My idea is to keep 100 rows by neighborhood.</p>
<p>Here's an overview of my data :</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>index</th>
<th>name</th>
<th>neighborhood</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>name 1</td>
<td>neighborhood A</td>
</tr>
<tr>
<td>1</td>
<td>name 2</td>
<td>neighborhood A</td>
</tr>
<tr>
<td>2</td>
<td>name 3</td>
<td>neighborhood B</td>
</tr>
<tr>
<td>3</td>
<td>name 4</td>
<td>neighborhood B</td>
</tr>
<tr>
<td>4</td>
<td>name 5</td>
<td>neighborhood C</td>
</tr>
<tr>
<td>5</td>
<td>name 6</td>
<td>neighborhood C</td>
</tr>
<tr>
<td>6</td>
<td>name 7</td>
<td>neighborhood D</td>
</tr>
<tr>
<td>7</td>
<td>name 8</td>
<td>neighborhood D</td>
</tr>
<tr>
<td>8</td>
<td>name 9</td>
<td>neighborhood E</td>
</tr>
<tr>
<td>9</td>
<td>name 10</td>
<td>neighborhood E</td>
</tr>
</tbody>
</table>
</div>
<p>What is the more efficient way to do so ?</p>
<p>Thanks in advance</p>
<p>I'm expecting to create something that looks like :</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>index</th>
<th>name</th>
<th>neighborhood</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>name 1</td>
<td>neighborhood A</td>
</tr>
<tr>
<td>1</td>
<td>name 3</td>
<td>neighborhood B</td>
</tr>
<tr>
<td>2</td>
<td>name 5</td>
<td>neighborhood C</td>
</tr>
<tr>
<td>3</td>
<td>name 7</td>
<td>neighborhood D</td>
</tr>
<tr>
<td>4</td>
<td>name 9</td>
<td>neighborhood E</td>
</tr>
</tbody>
</table>
</div>
|
[
{
"answer_id": 74524509,
"author": "Cris Luengo",
"author_id": 7328782,
"author_profile": "https://Stackoverflow.com/users/7328782",
"pm_score": 2,
"selected": false,
"text": "cv2.arcLength() import cv2\nimport numpy as np\n\n# read in OP's example image, making sure we ignore the red arrow\nimg = cv2.imread('jGssp.png')[:, :, 1]\n_, img = cv2.threshold(img, 127, 255, 0)\n\n# get the contour of the shape\ncontours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\ncontour = contours[0][:, 0, :]\n\n# add the first point as the last, to close it\ncontour = np.concatenate((contour, contour[0, None, :]))\n\n# compute centroid\ndef cross_product(v1, v2):\n \"\"\"2D cross product.\"\"\"\n return v1[0] * v2[1] - v1[1] * v2[0]\n\nsum = 0.0\nxsum = 0.0\nysum = 0.0\nfor ii in range(1, contour.shape[0]):\n v = cross_product(contour[ii - 1, :], contour[ii, :])\n sum += v\n xsum += (contour[ii - 1, 0] + contour[ii, 0]) * v\n ysum += (contour[ii - 1, 1] + contour[ii, 1]) * v\n\ncentroid = np.array([ xsum, ysum ]) / (3 * sum)\n\n# Compute coefficient of variation of distances to centroid (==circularity)\nd = np.sqrt(np.sum((contour - centroid) ** 2, axis=1))\ncircularity = np.std(d) / np.mean(d)\n"
},
{
"answer_id": 74578112,
"author": "fmw42",
"author_id": 7355741,
"author_profile": "https://Stackoverflow.com/users/7355741",
"pm_score": 0,
"selected": false,
"text": "import cv2\nimport numpy as np\n\n# Read image\nimg = cv2.imread('circle_defect.png')\nhh, ww = img.shape[:2]\n\n# threshold on white to remove red arrow\nlower = (255,255,255)\nupper = (255,255,255)\nthresh = cv2.inRange(img, lower, upper)\n\n# get Hough circles\nmin_dist = int(ww/5)\ncircles = cv2.HoughCircles(thresh, cv2.HOUGH_GRADIENT, 1, minDist=min_dist, param1=150, param2=15, minRadius=0, maxRadius=0)\nprint(circles)\n\n# draw circles on input thresh (without red arrow)\ncircle_img = thresh.copy()\ncircle_img = cv2.merge([circle_img,circle_img,circle_img])\nfor circle in circles[0]:\n # draw the circle in the output image, then draw a rectangle\n # corresponding to the center of the circle\n (x,y,r) = circle\n x = int(x)\n y = int(y)\n r = int(r)\n cv2.circle(circle_img, (x, y), r, (0, 0, 255), 1)\n\n# draw filled circle on black background\ncircle_filled = np.zeros_like(thresh)\ncv2.circle(circle_filled, (x,y), r, 255, -1)\n\n# get difference between the thresh image and the circle_filled image\ndiff = cv2.absdiff(thresh, circle_filled)\n\n# apply morphology to remove ring\nkernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5))\nresult = cv2.morphologyEx(diff, cv2.MORPH_OPEN, kernel)\n\n# count non-zero pixels\ndefect_count = np.count_nonzero(result)\nprint(\"defect count:\", defect_count)\n\n# save results\ncv2.imwrite('circle_defect_thresh.jpg', thresh)\ncv2.imwrite('circle_defect_circle.jpg', circle_img)\ncv2.imwrite('circle_defect_circle_diff.jpg', diff)\ncv2.imwrite('circle_defect_detected.png', result)\n\n# show images\ncv2.imshow('thresh', thresh)\ncv2.imshow('circle_filled', circle_filled)\ncv2.imshow('diff', diff)\ncv2.imshow('result', result)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n defect count: 500\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74523564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7698507/"
] |
74,523,565
|
<p>What is the difference between</p>
<pre><code>int(*a)[5];
int b[5] = { 1, 2, 3, 4, 5 };
i = 0;
a = &b;
for (i = 0; i < 5; i++)
printf("%d\n", *(*a+i));
</code></pre>
<p>and</p>
<pre><code>int b[5] = { 1, 2, 3, 4, 5 };
int *y = b;
for (i = 0; i < 5; i++)
printf("%d\n", *y+i);
</code></pre>
<p>Both snippets produce same output but I dont understand what is the difference in initialization?
How is</p>
<pre><code>int *y = b;
</code></pre>
<p>different to</p>
<pre><code>int(*a)[5];
</code></pre>
<p>How to explain this kind of dereferencing?</p>
<pre><code>printf("%d\n", *(*a+i));
</code></pre>
|
[
{
"answer_id": 74524509,
"author": "Cris Luengo",
"author_id": 7328782,
"author_profile": "https://Stackoverflow.com/users/7328782",
"pm_score": 2,
"selected": false,
"text": "cv2.arcLength() import cv2\nimport numpy as np\n\n# read in OP's example image, making sure we ignore the red arrow\nimg = cv2.imread('jGssp.png')[:, :, 1]\n_, img = cv2.threshold(img, 127, 255, 0)\n\n# get the contour of the shape\ncontours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\ncontour = contours[0][:, 0, :]\n\n# add the first point as the last, to close it\ncontour = np.concatenate((contour, contour[0, None, :]))\n\n# compute centroid\ndef cross_product(v1, v2):\n \"\"\"2D cross product.\"\"\"\n return v1[0] * v2[1] - v1[1] * v2[0]\n\nsum = 0.0\nxsum = 0.0\nysum = 0.0\nfor ii in range(1, contour.shape[0]):\n v = cross_product(contour[ii - 1, :], contour[ii, :])\n sum += v\n xsum += (contour[ii - 1, 0] + contour[ii, 0]) * v\n ysum += (contour[ii - 1, 1] + contour[ii, 1]) * v\n\ncentroid = np.array([ xsum, ysum ]) / (3 * sum)\n\n# Compute coefficient of variation of distances to centroid (==circularity)\nd = np.sqrt(np.sum((contour - centroid) ** 2, axis=1))\ncircularity = np.std(d) / np.mean(d)\n"
},
{
"answer_id": 74578112,
"author": "fmw42",
"author_id": 7355741,
"author_profile": "https://Stackoverflow.com/users/7355741",
"pm_score": 0,
"selected": false,
"text": "import cv2\nimport numpy as np\n\n# Read image\nimg = cv2.imread('circle_defect.png')\nhh, ww = img.shape[:2]\n\n# threshold on white to remove red arrow\nlower = (255,255,255)\nupper = (255,255,255)\nthresh = cv2.inRange(img, lower, upper)\n\n# get Hough circles\nmin_dist = int(ww/5)\ncircles = cv2.HoughCircles(thresh, cv2.HOUGH_GRADIENT, 1, minDist=min_dist, param1=150, param2=15, minRadius=0, maxRadius=0)\nprint(circles)\n\n# draw circles on input thresh (without red arrow)\ncircle_img = thresh.copy()\ncircle_img = cv2.merge([circle_img,circle_img,circle_img])\nfor circle in circles[0]:\n # draw the circle in the output image, then draw a rectangle\n # corresponding to the center of the circle\n (x,y,r) = circle\n x = int(x)\n y = int(y)\n r = int(r)\n cv2.circle(circle_img, (x, y), r, (0, 0, 255), 1)\n\n# draw filled circle on black background\ncircle_filled = np.zeros_like(thresh)\ncv2.circle(circle_filled, (x,y), r, 255, -1)\n\n# get difference between the thresh image and the circle_filled image\ndiff = cv2.absdiff(thresh, circle_filled)\n\n# apply morphology to remove ring\nkernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5))\nresult = cv2.morphologyEx(diff, cv2.MORPH_OPEN, kernel)\n\n# count non-zero pixels\ndefect_count = np.count_nonzero(result)\nprint(\"defect count:\", defect_count)\n\n# save results\ncv2.imwrite('circle_defect_thresh.jpg', thresh)\ncv2.imwrite('circle_defect_circle.jpg', circle_img)\ncv2.imwrite('circle_defect_circle_diff.jpg', diff)\ncv2.imwrite('circle_defect_detected.png', result)\n\n# show images\ncv2.imshow('thresh', thresh)\ncv2.imshow('circle_filled', circle_filled)\ncv2.imshow('diff', diff)\ncv2.imshow('result', result)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n defect count: 500\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74523565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2889669/"
] |
74,523,583
|
<p>I need a regex that will get all the text occurences between parentheses, having in mind that all the content is encapsulated by the word BEGIN and the chars ---- at the end.</p>
<p>Input example:</p>
<pre><code>BEGIN ) Tj\nET37.66 533 Td\n( Td\n(I NEED THIS TEXT ) Tj\nET\nBT\n37.334 Td\n(AND ALSO NEED THIS TEXT ) Tj\nET\nBT\n37.55 Td\n(------------
</code></pre>
<p>Expected matches:</p>
<pre><code>I NEED THIS TEXT
AND ALSO NEED THIS TEXT
</code></pre>
<p>I already did something like <code>(?<=BEGIN).*(?=\(--)</code> to the outside pattern, but i couldn't figure out how to get all text occurrences inside parentheses between this.</p>
|
[
{
"answer_id": 74523837,
"author": "Wiktor Stribiżew",
"author_id": 3832970,
"author_profile": "https://Stackoverflow.com/users/3832970",
"pm_score": 3,
"selected": true,
"text": "(?s)(?:\\G(?!^)\\)|BEGIN)(?:(?!\\(--).)*?\\((?!--)\\K[^()]*\n (?s) . (?:\\G(?!^)\\)|BEGIN) BEGIN ) (?:(?!\\(--).)*? (-- \\( ( (?!--) ( -- \\K [^()]* ( )"
},
{
"answer_id": 74524981,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 1,
"selected": false,
"text": "\\(((?:(?!BEGIN).)*?)\\)(?=.*---)\n \\(((?:(?!BEGIN).)*?)\\) ( ) BEGIN (?=.*---) .*---"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74523583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12900176/"
] |
74,523,662
|
<p>I am trying to generate an array of all combinations of an array, but how can I generate without repeating.</p>
<p>My first solution was just remove the repeating elements using some <code>for</code>, but I am dealing with big arrays, with 50 length size or more and the execution never end.</p>
<p>ex: (0,0,1,0)</p>
<pre><code>[1,0,0,0]
[0,1,0,0]
[0,0,1,0]
[0,0,0,1]
</code></pre>
|
[
{
"answer_id": 74523870,
"author": "Joran Beasley",
"author_id": 541038,
"author_profile": "https://Stackoverflow.com/users/541038",
"pm_score": 0,
"selected": false,
"text": "arrays = [list(f\"{i:04b}\") for i in range(2**4)]\n"
},
{
"answer_id": 74523937,
"author": "treuss",
"author_id": 19838568,
"author_profile": "https://Stackoverflow.com/users/19838568",
"pm_score": 0,
"selected": false,
"text": ">>> from itertools import permutations\n>>> set(permutations([0,0,1,0]))\n{(0, 0, 1, 0), (1, 0, 0, 0), (0, 0, 0, 1), (0, 1, 0, 0)}\n"
},
{
"answer_id": 74524052,
"author": "treuss",
"author_id": 19838568,
"author_profile": "https://Stackoverflow.com/users/19838568",
"pm_score": 2,
"selected": false,
"text": "from itertools import combinations\n\narray = [0,0,1,1,0,1,0,1,0,0,1,0,1,0,1]\nn = len(array)\nk = sum(array)\n\nfor comb in combinations(range(n), k): # Any combination to chose k numbers from range 0..n\n next_arr = [1 if i in comb else 0 for i in range(n)]\n print(next_arr)\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74523662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9003947/"
] |
74,523,668
|
<p>I am trying to make a UDP server and next to it a periodic task that updates a global variable every 5 minutes.</p>
<p>But the problem is that my UDP server and my task part blocks the rest of the code (because I use <code>while True:</code>).</p>
<p>I was looking at this example:
<a href="https://docs.python.org/3/library/asyncio-protocol.html#asyncio-udp-echo-server-protocol" rel="nofollow noreferrer">https://docs.python.org/3/library/asyncio-protocol.html#asyncio-udp-echo-server-protocol</a></p>
<pre><code>import asyncio
class EchoServerProtocol:
def connection_made(self, transport):
self.transport = transport
def datagram_received(self, data, addr):
message = data.decode()
print('Received %r from %s' % (message, addr))
print('Send %r to %s' % (message, addr))
self.transport.sendto(data, addr)
async def main():
print("Starting UDP server")
# Get a reference to the event loop as we plan to use
# low-level APIs.
loop = asyncio.get_running_loop()
# One protocol instance will be created to serve all
# client requests.
transport, protocol = await loop.create_datagram_endpoint(
lambda: EchoServerProtocol(),
local_addr=('127.0.0.1', 9999))
try:
await asyncio.sleep(3600) # Serve for 1 hour.
finally:
transport.close()
asyncio.run(main())
</code></pre>
<p>I see in the example that they run this for an hour. But what if I wanted to run it indefinitely? I played with <code>run_forever()</code>, but I don't understand how it works.</p>
<p>I also don't understand how to make a periodic task that doesn't use <code>while True:</code> at the same time.</p>
<p>Is this possible?</p>
|
[
{
"answer_id": 74526512,
"author": "Paul Cornelius",
"author_id": 2442613,
"author_profile": "https://Stackoverflow.com/users/2442613",
"pm_score": 1,
"selected": false,
"text": "asyncio.sleep(3600) asyncio.Event try:\n await asyncio.Event().wait() # wait here until the Universe ends\nfinally:\n transport.close()\n"
},
{
"answer_id": 74526825,
"author": "gre_gor",
"author_id": 794749,
"author_profile": "https://Stackoverflow.com/users/794749",
"pm_score": 0,
"selected": false,
"text": "await asyncio.sleep(3600)\n while True:\n print(\"do something every 5 minutes\", datetime.datetime.now())\n await asyncio.sleep(5*60)\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74523668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19241200/"
] |
74,523,718
|
<p>I am a newbie to C++ and I wanted to know what should I do. I need to write a program where the user will be filling the 2d array. I need to program to show the 2d array in the form of matrix and do some other things, like counting elements that are not 0. But I am stuck. I can't call functions in main(), because there is no matching call error. I suppose this is because of the array initializing, but I saw people on the internet who does</p>
<p><code>int arr[row][col];</code></p>
<p>Code:</p>
<pre><code>#include <iostream>
#include <conio.h>
#include <iomanip>
using namespace std;
// for filling the 2d array
void fillTheMatrix(int **arr, int row, int col) {
cout << "Please, enter here the elements you want to use for the matrix A:\n";
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
cout << "a[" << i << "][" << j << "] = ";
cin >> arr[i][j];
}
}
}
// for viewing this s2d array as matrix
void theMatrixView(int **arr, int row, int col) {
cout << "The matrix A\n";
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
cout << setw(3) << arr[i][j] << "\t";
}
cout << endl;
}
}
int main() {
int row;
int col;
cout << "Please, enter the number of rows of the matrix A: " << endl;
cin >> row;
cout << "Please, enter the number of columns of the matrix A: " << endl;
cin >> col;
int arr[row][col];
// TASK 1
fillTheMatrix(arr, row, col); // No matching function for call to 'fillTheMatrix'
theMatrixView(arr, row, col); // // No matching function for call to 'theMatrixView'
return 0;
}
</code></pre>
<p>Can you help me fixing this problem? I would be glad to have any recommendations to refactor code.</p>
|
[
{
"answer_id": 74526512,
"author": "Paul Cornelius",
"author_id": 2442613,
"author_profile": "https://Stackoverflow.com/users/2442613",
"pm_score": 1,
"selected": false,
"text": "asyncio.sleep(3600) asyncio.Event try:\n await asyncio.Event().wait() # wait here until the Universe ends\nfinally:\n transport.close()\n"
},
{
"answer_id": 74526825,
"author": "gre_gor",
"author_id": 794749,
"author_profile": "https://Stackoverflow.com/users/794749",
"pm_score": 0,
"selected": false,
"text": "await asyncio.sleep(3600)\n while True:\n print(\"do something every 5 minutes\", datetime.datetime.now())\n await asyncio.sleep(5*60)\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74523718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20295376/"
] |
74,523,727
|
<p>Imagine that I have a Next.js app which uses ISR to temporarily render some content on the home page. This content is interactive and I would maintain the client state in a Context. Every 24 hours, I would like to regenerate this interactive content at which point I would like to clear the state.</p>
<p>I don't actually have this app right now (I'm in the planning stage) but the best example of this that I can think of is <a href="https://www.nytimes.com/games/wordle/index.html" rel="nofollow noreferrer">Wordle</a> where a word gets generated once every 24 hours and you need to guess it; if you are in the process of guessing the word when this reset happens, your guessing attempts are going to be reset back to zero (although I haven't checked this).</p>
<p>I thought that I could have a scheduled Firebase function that would update my content and call an endpoint that would trigger an on-demand revalidation as described <a href="https://stackoverflow.com/questions/66995817/next-js-static-regeneration-on-demand">here</a>, however, I still don't know how I could reset the client state during/after this revalidation. Any ideas or suggestions?</p>
<p>Many thanks in advance!</p>
|
[
{
"answer_id": 74633429,
"author": "mircaea",
"author_id": 1188082,
"author_profile": "https://Stackoverflow.com/users/1188082",
"pm_score": 1,
"selected": false,
"text": " import { doc, onSnapshot } from \"firebase/firestore\";\n import { firestore } from \"./firebase-config\";\n\n function DisplayMessage() {\n const [message, setMessage] = useState(\"\");\n\n useEffect(() => {\n const MESSAGE_REF = doc(firestore, \"daily_message/static_identifier\");\n const observer = onSnapshot(\n MESSAGE_REF,\n (docSnapshot) => {\n if (docSnapshot.exists()) {\n const docData = docSnapshot.data();\n if (docData && docData.message) setMessage(docData.message);\n }\n },\n (err) => {\n console.log(`Encountered error: ${err}`);\n }\n );\n\n return () => {\n // close/remove the socket connection when closing this component:\n observer();\n };\n }, []);\n \n return <>\n <p>Data from db:</p>\n <p>{message}</p>\n </>\n }\n"
},
{
"answer_id": 74636657,
"author": "Jon",
"author_id": 779784,
"author_profile": "https://Stackoverflow.com/users/779784",
"pm_score": 1,
"selected": false,
"text": "useEffect import React, { useContext, useEffect } from 'react';\n\nconst MyContext = React.createContext();\n\nfunction MyApp() {\n const [state, setState] = useState(initialState);\n\n useEffect(() => {\n // This function will be called whenever the revalidation occurs\n async function resetState() {\n setState(initialState);\n }\n }, []);\n\n return (\n <MyContext.Provider value={[state, setState]}>\n {/* Your app components go here */}\n </MyContext.Provider>\n );\n}\n useEffect useEffect import React, { useContext, useEffect } from 'react';\n\nconst MyContext = React.createContext();\n\nfunction MyApp() {\n const [state, setState] = useState(initialState);\n const [revalidateTrigger, setRevalidateTrigger] = useState(0);\n\n useEffect(() => {\n // This function will be called whenever the revalidateTrigger variable is updated\n async function resetState() {\n setState(initialState);\n }\n }, [revalidateTrigger]);\n\n return (\n <MyContext.Provider value={[state, setState]}>\n {/* Your app components go here */}\n </MyContext.Provider>\n );\n}\n useEffect"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74523727",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3236215/"
] |
74,523,729
|
<p>Why is the following Elixir macro not working for negative values?</p>
<p>The code is really simple, nothing really fancy, only one macro with some simple guard clauses:</p>
<pre><code>defmodule IntegerChecker do
defmacro is_negative_or_zero(number)
when is_integer(number) and number <= 0, do: true
defmacro is_negative_or_zero(number)
when is_integer(number), do: false
end
</code></pre>
<pre><code>> import IntegerChecker
> is_negative_or_zero(0)
true
> is_negative_or_zero(1)
false
> is_negative_or_zero(20)
false
> is_negative_or_zero(-1)
** (FunctionClauseError) no function clause matching in IntegerChecker.is_negative_or_zero/1
expanding macro: IntegerChecker.is_negative_or_zero/1
</code></pre>
|
[
{
"answer_id": 74633429,
"author": "mircaea",
"author_id": 1188082,
"author_profile": "https://Stackoverflow.com/users/1188082",
"pm_score": 1,
"selected": false,
"text": " import { doc, onSnapshot } from \"firebase/firestore\";\n import { firestore } from \"./firebase-config\";\n\n function DisplayMessage() {\n const [message, setMessage] = useState(\"\");\n\n useEffect(() => {\n const MESSAGE_REF = doc(firestore, \"daily_message/static_identifier\");\n const observer = onSnapshot(\n MESSAGE_REF,\n (docSnapshot) => {\n if (docSnapshot.exists()) {\n const docData = docSnapshot.data();\n if (docData && docData.message) setMessage(docData.message);\n }\n },\n (err) => {\n console.log(`Encountered error: ${err}`);\n }\n );\n\n return () => {\n // close/remove the socket connection when closing this component:\n observer();\n };\n }, []);\n \n return <>\n <p>Data from db:</p>\n <p>{message}</p>\n </>\n }\n"
},
{
"answer_id": 74636657,
"author": "Jon",
"author_id": 779784,
"author_profile": "https://Stackoverflow.com/users/779784",
"pm_score": 1,
"selected": false,
"text": "useEffect import React, { useContext, useEffect } from 'react';\n\nconst MyContext = React.createContext();\n\nfunction MyApp() {\n const [state, setState] = useState(initialState);\n\n useEffect(() => {\n // This function will be called whenever the revalidation occurs\n async function resetState() {\n setState(initialState);\n }\n }, []);\n\n return (\n <MyContext.Provider value={[state, setState]}>\n {/* Your app components go here */}\n </MyContext.Provider>\n );\n}\n useEffect useEffect import React, { useContext, useEffect } from 'react';\n\nconst MyContext = React.createContext();\n\nfunction MyApp() {\n const [state, setState] = useState(initialState);\n const [revalidateTrigger, setRevalidateTrigger] = useState(0);\n\n useEffect(() => {\n // This function will be called whenever the revalidateTrigger variable is updated\n async function resetState() {\n setState(initialState);\n }\n }, [revalidateTrigger]);\n\n return (\n <MyContext.Provider value={[state, setState]}>\n {/* Your app components go here */}\n </MyContext.Provider>\n );\n}\n useEffect"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74523729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/235935/"
] |
74,523,798
|
<p>I have a bulk operation that operates on a 2 dimensional array. It shall call a given method "func" on each element in the array:</p>
<pre><code>function forEachMatrixElement(matrix: Complex[][], func: Function): Complex[][] {
let matrixResult: Complex[][] = new Array(countRows(matrix)).fill(false).map(() => new Array(countCols(matrix)).fill(false)); // Creates a result 2D-Matrix
for (let row = 0; row < countRows(matrix); row++) {
for (let col = 0; col < countCols(matrix); col++) {
matrixResult[row][col] = func.call(matrix[row][col]); // Call the given method
}
}
return matrixResult;
}
</code></pre>
<p>I have two functions that I want to delegate to this method:
This one takes no additional arguments and works fine:</p>
<pre><code>export function conjugateMatrix(matrix: Complex[][]): Complex[][] {
return forEachMatrixElement(matrix, Complex.prototype.conjugate);
}
</code></pre>
<p>This one takes an additional argument (a scalar). But I don't know how to add this argument to this method reference on the prototype:</p>
<pre><code>export function multiplyMatrixScalar(matrix: Complex[][], scalar: Complex): Complex[][] {
return forEachMatrixElement(matrix, Complex.prototype.mul); // TODO Call with scalar
}
</code></pre>
|
[
{
"answer_id": 74523948,
"author": "Drew Pereli",
"author_id": 6789286,
"author_profile": "https://Stackoverflow.com/users/6789286",
"pm_score": 2,
"selected": false,
"text": "multiplyMatrixScalar export function multiplyMatrixScalar(matrix: Complex[][], scalar: Complex): Complex[][] {\n const fn = function (this: Complex) { return this.mul(c, scalar)};\n\n return forEachMatrixElement(matrix, fn);\n}\n"
},
{
"answer_id": 74524064,
"author": "David Min",
"author_id": 12947970,
"author_profile": "https://Stackoverflow.com/users/12947970",
"pm_score": 0,
"selected": false,
"text": "Function.call() this function forEachMatrixElement(matrix: Complex[][], func: Function, scalar?: Complex)\n func.call(matrix[row][col], scalar)\n"
},
{
"answer_id": 74524140,
"author": "Alex Wayne",
"author_id": 62076,
"author_profile": "https://Stackoverflow.com/users/62076",
"pm_score": 3,
"selected": true,
"text": "prototype this call() forEachMatrixElement Complex function forEachMatrixElement(\n matrix: Complex[][],\n func: (complex: Complex) => Complex // Changed this function type\n): Complex[][] {\n let matrixResult: Complex[][] = new Array(countRows(matrix)).fill(false).map(() => new Array(countCols(matrix)).fill(false));\n for (let row = 0; row < countRows(matrix); row++) {\n for (let col = 0; col < countCols(matrix); col++) {\n \n // just invoke the function like any other. No .call()\n matrixResult[row][col] = func(matrix[row][col]); \n \n }\n }\n return matrixResult;\n}\n export function conjugateMatrix(matrix: Complex[][]): Complex[][] {\n return forEachMatrixElement(matrix, (c) => c.conjugate());\n}\n\nexport function multiplyMatrixScalar(matrix: Complex[][], scalar: Complex): Complex[][] {\n return forEachMatrixElement(matrix, (c) => c.mul(scalar));\n}\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74523798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15565539/"
] |
74,523,813
|
<p>Having two dataframes with the same key id column:</p>
<pre><code>dfnames1 <- data.frame(id = c(1,2,3,4), name1 = c("Helen", "Von", "Erik", "Brook", "Adel"), gender = c("F", "Neutral", "M", "Neutral", "F"))
dfnames2 <- data.frame(id = c(1,2,3,4), name2 = c("Helen", "Von", "Erik", "Brook", "Adel"), gender2 = c("Neutral", "M", "M", "Uni", "M"))
</code></pre>
<p>How is it possible to merge them into one data frame and for gender column check if it is "Neutral" label in one of the two dataframe and has another of the values of "F", "M" or "Uni" keep this label, if it is Neutral in both dataframes keep as it is and if the is a case of "F" and "M" or vice versus keep it as FM or MF.</p>
<p>Example of expected output:</p>
<pre><code>dfnames <- data.frame(id = c(1,2,3,4), name = c("Helen", "Von", "Erik", "Brook", "Adel"), gender = c("F", "M", "M", "M", "FM"))
</code></pre>
|
[
{
"answer_id": 74524009,
"author": "TarJae",
"author_id": 13321647,
"author_profile": "https://Stackoverflow.com/users/13321647",
"pm_score": 3,
"selected": false,
"text": "library(dplyr)\n\nleft_join(dfnames1, dfnames2) %>% \n mutate(across(starts_with(\"gender\"), ~ifelse(. == \"Neutral\", NA_character_, .)),\n x = coalesce(gender, gender2),\n x = ifelse(!is.na(gender2) & x != gender2, paste0(x, gender2), x)) %>% \n select(id, name=name1, gender = x)\n Joining, by = \"id\"\n id name gender\n1 1 Helen F\n2 2 Von M\n3 3 Erik M\n4 4 Brook Uni\n5 5 Adel FM\n"
},
{
"answer_id": 74524272,
"author": "G. Grothendieck",
"author_id": 516548,
"author_profile": "https://Stackoverflow.com/users/516548",
"pm_score": 3,
"selected": true,
"text": "gender library(dplyr)\n\nLines <- \" M F Neutral Uni \n M M MF M M \n F MF F F F \n Neutral M F Neutral Uni\n Uni M F Uni Uni\"\nState <- read.table(text = Lines, header = TRUE)\n\nleft_join(dfnames1, dfnames2, by = \"id\") %>%\n rowwise %>%\n mutate(gender = State[gender, gender2]) %>%\n ungroup %>%\n select(id, gender)\n # A tibble: 5 × 2\n id gender\n <dbl> <chr> \n1 1 F \n2 2 M \n3 3 M \n4 4 Uni \n5 5 MF \n dfnames1 <- structure(list(id = c(1, 2, 3, 4, 5), name1 = c(\"Helen\", \"Von\", \n\"Erik\", \"Brook\", \"Adel\"), gender = c(\"F\", \"Neutral\", \"M\", \"Neutral\", \n\"F\")), class = \"data.frame\", row.names = c(NA, -5L))\n\ndfnames2 <- structure(list(id = c(1, 2, 3, 4, 5), name2 = c(\"Helen\", \"Von\", \n\"Erik\", \"Brook\", \"Adel\"), gender2 = c(\"Neutral\", \"M\", \"M\", \"Uni\", \n\"M\")), class = \"data.frame\", row.names = c(NA, -5L))\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74523813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20224217/"
] |
74,523,822
|
<p>Is there a one-click solution to stop the currently running command in the terminal and run it again?</p>
<p>Currently, I have to go to terminal -> <code>ctrl+c</code> to halt execution -> run the command again.</p>
<p>Suppose <code>npm run dev</code> is running; then it should stop and run it again after hitting some shortcut. If the single command is not possible, then I can also batch multiple commands in a single shortcut using <a href="https://marketplace.visualstudio.com/items?itemName=usernamehw.commands" rel="nofollow noreferrer">Commands</a> extension.</p>
|
[
{
"answer_id": 74524575,
"author": "Mark",
"author_id": 836330,
"author_profile": "https://Stackoverflow.com/users/836330",
"pm_score": 2,
"selected": true,
"text": "{\n \"command\": \"workbench.action.terminal.sendSequence\",\n \"args\": {\n \"text\": \"\\u0003Y\\u000D\" // you may not need the 'Y'\n // I also have \"text\": \"\\u001b[5c\" // Ctrl+C in my notes\n } \n},\n\n{\n \"command\": \"workbench.action.terminal.sendSequence\",\n \"args\": {\"text\": \"\\u001b[A\\u000D\"}, // uparrow and enter\n}\n"
},
{
"answer_id": 74530611,
"author": "GorvGoyl",
"author_id": 3073272,
"author_profile": "https://Stackoverflow.com/users/3073272",
"pm_score": 0,
"selected": false,
"text": "\"commands.commands\": {\n \"Restart Terminal\": {\n \"sequence\": [\n {\n \"command\": \"workbench.action.terminal.sendSequence\",\n \"args\": {\n \"text\": \"\\u0003\\u000D\" // you may not need the 'Y'\n // I also have \"text\": \"\\u001b[5c\" // Ctrl+C in my notes\n }\n },\n {\n \"command\": \"workbench.action.terminal.sendSequence\",\n \"args\": { \"text\": \"\\u001b[A\\u000D\" } // uparrow and enter\n }\n ],\n \"icon\": \"debug-restart\",\n \"statusBar\": {\n \"alignment\": \"left\",\n \"text\": \"RestartTerminal\",\n \"priority\": -4\n }\n }\n }\n\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74523822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3073272/"
] |
74,523,859
|
<p>I have a decorator that I can use to mark a read-only class property:</p>
<pre><code>class class_ro_property(property):
def __init__(self, getter:Callable):
self._getter = getter
def __get__(self, _, cls):
return self._getter(cls)
class MyClass:
@class_ro_property
def my_property(cls):
return [1, 2, 3]
</code></pre>
<p>The problem is that pylint doesn't understand this at all. If I try to write:</p>
<pre><code>for num in MyClass.my_property:
print(num)
</code></pre>
<p>it will tell me:</p>
<pre><code>E1133:0035:Non-iterable value MyClass.my_property is used in an iterating context
</code></pre>
<p>The same problem happens if I try to subscript it, ie <code>MyClass.my_property[0]</code>.</p>
<p>Is there some way to tell pylint about the use of a descriptor here? If not, is there some way to tell pylint <strong>at the property definition</strong> (and not only where it's used) not to complain about its use in an iterating context?</p>
|
[
{
"answer_id": 74524853,
"author": "Jasmijn",
"author_id": 573255,
"author_profile": "https://Stackoverflow.com/users/573255",
"pm_score": -1,
"selected": false,
"text": "class MyMetaClass(type):\n @property\n def my_property(cls):\n return [1, 2, 3]\n\nclass MyClass(metaclass=MyMetaClass):\n my_property = MyClassMeta.my_property\n\nfor num in MyClass.my_property:\n print(num)\n MyClass.my_property MyClass().my_property my_property = MyClassMeta.my_property"
},
{
"answer_id": 74537803,
"author": "jsbueno",
"author_id": 108205,
"author_profile": "https://Stackoverflow.com/users/108205",
"pm_score": 1,
"selected": true,
"text": "property property"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74523859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/274460/"
] |
74,523,898
|
<p>I'm trying to find, hopefully, a one lines to accomplish the following:</p>
<p>I have the following dataframe:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
import numpy as np
SIZE = 10
df = pd.DataFrame({'col1': np.random.randint(100, size=SIZE),
'col2': np.random.randint(100, size=SIZE),
'col3': np.random.randint(100, size=SIZE),
'col4': np.random.randint(2, size=SIZE)})
print(df)
</code></pre>
<p>outputting</p>
<pre><code> col1 col2 col3 col4
0 55 96 40 0
1 82 59 34 1
2 85 66 25 1
3 90 69 27 0
4 36 32 79 1
5 33 69 80 1
6 11 53 88 0
7 31 51 96 0
8 89 76 88 1
9 4 76 47 0
</code></pre>
<p>I'm currently ignoring <code>col4</code> and calculating the max value of each row as follows:</p>
<pre class="lang-py prettyprint-override"><code>df[['col1', 'col2', 'col3']].max(axis=1)
</code></pre>
<p>resulting in</p>
<pre><code>0 96
1 82
2 85
3 90
4 79
5 80
6 88
7 96
8 89
9 76
dtype: int64
</code></pre>
<p>I want to use <code>col4</code> to conditionally calculate the max value. If <code>col4</code> value is 0, calculate max value of <code>col1</code>, else calculate max value of <code>['col2', 'col3']</code>. I also want to keep the same index/order of the dataframe.</p>
<p>The end result would be</p>
<pre><code>0 55 # col1
1 59 # max(col2, col3)
2 66 # max(col2, col3)
3 90 # col1
4 79 # max(col2, col3)
5 80 # max(col2, col3)
6 11 # col1
7 31 # col1
8 88 # max(col2, col3)
9 4 # col1
dtype: int64
</code></pre>
<p>One possibility would be to create two new dataframes, calculate the max, and join them again, but this would possibly mess the index (I guess I could save that too). Any better ideas?</p>
<p>Apologies if this question was already asked, but I couldn't find with the search terms</p>
|
[
{
"answer_id": 74524853,
"author": "Jasmijn",
"author_id": 573255,
"author_profile": "https://Stackoverflow.com/users/573255",
"pm_score": -1,
"selected": false,
"text": "class MyMetaClass(type):\n @property\n def my_property(cls):\n return [1, 2, 3]\n\nclass MyClass(metaclass=MyMetaClass):\n my_property = MyClassMeta.my_property\n\nfor num in MyClass.my_property:\n print(num)\n MyClass.my_property MyClass().my_property my_property = MyClassMeta.my_property"
},
{
"answer_id": 74537803,
"author": "jsbueno",
"author_id": 108205,
"author_profile": "https://Stackoverflow.com/users/108205",
"pm_score": 1,
"selected": true,
"text": "property property"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74523898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11228445/"
] |
74,523,905
|
<p>Why does the following code print <code>System.Int32[]</code> in the console and not the values in the array? In simple words?</p>
<pre><code>static int[] minMax(int[] lst)
{
int a = lst.Min();
int b = lst.Max();
return new int[] { a, b };
}
System.Console.WriteLine(minMax(new int[] { 1, 2, 5, -1, 12, 20 }));
</code></pre>
|
[
{
"answer_id": 74523949,
"author": "Neil",
"author_id": 759558,
"author_profile": "https://Stackoverflow.com/users/759558",
"pm_score": -1,
"selected": false,
"text": "WriteLine .ToString() .ToString() override string ToString()"
},
{
"answer_id": 74523964,
"author": "SupaMaggie70 b",
"author_id": 17547957,
"author_profile": "https://Stackoverflow.com/users/17547957",
"pm_score": 0,
"selected": false,
"text": "Console.WriteLine(string.Join(‘,’, array));"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74523905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20566047/"
] |
74,523,910
|
<p>Lets say I have a react state variable which is an array of <em>user</em> objects. The user object has 2 keys which are important to us: <em>id</em> and <em>name</em>. I have to change the <em>name</em> of 2 users in that list. The code for this is below</p>
<p>`</p>
<pre><code>const App = () => {
const [users, setUsers] = useState([]);
useEffect(async () => {
const response = await fetch('https://jsonplaceholder.typicode.com/users');
const users = await response.json();
setUsers(users);
}, [])
const edit1 = (id) => {
const newUsers = users.map(user => {
if(user.id === id) {
user.name = 'John Doe';
}
return user;
});
setUsers(newUsers);
}
const edit2 = (id) => {
const newUsers = users.map(user => ({
...user,
name: user.id === id ? 'Jane Doe' : user.name
}));
setUsers(newUsers);
}
return(
<div>
<button onClick={() => edit1(2)}>Edit-1</button>
<button onClick={() => edit2(5)}>Edit-2</button>
<ul>
{users.map((user) => (<li key={user.key}>{user.name}</li>))}
</ul>
</div>
);
}
</code></pre>
<p>`</p>
<p>Which approach is better? Between <em>edit1</em> and <em>edit2</em> which approach is better, since they both get the job done? Or is there another way to do this?</p>
<p>The problem is fairly straight forward. In <em>edit1</em>, new objects are not created, but a new array is created. Since React only checks to see if the reference to the array object has changed, which it has, it then goes on to rerender. In <em>edit2</em>, new objects are also created along with a new array. This causes a rerender as well. I'm confused as to which approach is better.</p>
|
[
{
"answer_id": 74523949,
"author": "Neil",
"author_id": 759558,
"author_profile": "https://Stackoverflow.com/users/759558",
"pm_score": -1,
"selected": false,
"text": "WriteLine .ToString() .ToString() override string ToString()"
},
{
"answer_id": 74523964,
"author": "SupaMaggie70 b",
"author_id": 17547957,
"author_profile": "https://Stackoverflow.com/users/17547957",
"pm_score": 0,
"selected": false,
"text": "Console.WriteLine(string.Join(‘,’, array));"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74523910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6584020/"
] |
74,523,912
|
<p>I was following <a href="https://docs.flutter.dev/cookbook/testing/widget/finders#3-find-a-specific-widget-instance" rel="nofollow noreferrer">this example</a> to test if a <strong><code>CircularProgressIndicator</code></strong> is present in my view, but even though the Flutter build tree shows the widget is present, I keep getting the following exception:</p>
<pre class="lang-none prettyprint-override"><code>══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════
The following TestFailure was thrown running a test:
Expected: exactly one matching node in the widget tree
Actual: _WidgetFinder:<zero widgets with the given widget
(CircularProgressIndicator(<indeterminate>)) (ignoring offstage widgets)>
Which: means none were found but one was expected
When the exception was thrown, this was the stack:
#4 main.<anonymous closure> (file:///D:/xxxx/xxxx/xxxx/test/widget_test/widget_test.dart:173:5)
<asynchronous suspension>
<asynchronous suspension>
(elided one frame from package:stack_trace)
This was caught by the test expectation on the following line:
file:///D:/xxxx/xxxx/xxxx/test/widget_test/widget_test.dart line 173
The test description was:
ViewRequest: Waiting Types List
════════════════════════════════════════════════════════════════════════════════════════════════════
</code></pre>
<hr />
<h1>Edit</h1>
<p>I've made a method that builds a <strong><code>MaterialApp</code></strong> with just a <strong><code>CircularProgressIndicator</code></strong> Widget as its "child":</p>
<pre class="lang-dart prettyprint-override"><code>Widget createMockViewRequest() {
return MaterialApp(
title: 'SmartDevice Simulator',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const CircularProgressIndicator());
}
</code></pre>
<p>And the following test still keeps failing with the same exception:</p>
<pre class="lang-dart prettyprint-override"><code>testWidgets('ViewRequest: Waiting Types List', (WidgetTester tester) async {
const childWidget = CircularProgressIndicator();
// Build our app and trigger a frame.
await tester.pumpWidget(createMockViewRequest());
// Verify that the page is loading until we receive the types.
expect(find.byWidget(childWidget), findsOneWidget);
await tester.pumpAndSettle();
});
</code></pre>
<p>Am I doing something wrong? Maybe the <strong><code>MaterialApp</code></strong> doesn't count as a container? But in that case I fail to understand why it should not.</p>
|
[
{
"answer_id": 74524344,
"author": "Eugene Kuzmenko",
"author_id": 4199283,
"author_profile": "https://Stackoverflow.com/users/4199283",
"pm_score": 2,
"selected": false,
"text": " Widget createMockViewRequest(Widget widget) {\n return MaterialApp(\n title: 'SmartDevice Simulator',\n theme: ThemeData(\n primarySwatch: Colors.blue,\n ),\n home: widget,\n );\n }\n\n testWidgets('ViewRequest: Waiting Types List', (WidgetTester tester) async {\n const childWidget = CircularProgressIndicator();\n\n // Build our app and trigger a frame.\n await tester.pumpWidget(createMockViewRequest(childWidget));\n\n // Verify that the page is loading until we receive the types.\n expect(find.byWidget(childWidget), findsOneWidget);\n });\n Widget createMockViewRequest() {\n return MaterialApp(\n title: 'SmartDevice Simulator',\n theme: ThemeData(\n primarySwatch: Colors.blue,\n ),\n home: const CircularProgressIndicator(),\n );\n }\n\n testWidgets('ViewRequest: Waiting Types List', (WidgetTester tester) async {\n // Build our app and trigger a frame.\n await tester.pumpWidget(createMockViewRequest());\n\n // Verify that the page is loading until we receive the types.\n expect(find.byType(CircularProgressIndicator), findsOneWidget);\n });\n await tester.pumpAndSettle();"
},
{
"answer_id": 74524355,
"author": "Fabián Bardecio",
"author_id": 12204458,
"author_profile": "https://Stackoverflow.com/users/12204458",
"pm_score": 4,
"selected": true,
"text": "await tester.pumpAndSettle() CircularProgressIndicator finder CircularProgressIndicator find.byType"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74523912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19544859/"
] |
74,523,913
|
<p>SQLSTATE[42S02]: Base table or view not found: 1146 Table 'app.infos' doesn't exist.</p>
<p><strong>home controller</strong></p>
<pre><code><?php
namespace App\Http\Controllers;
// use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\info;
class homeController extends Controller
{
public function index(){
$data=info::all();
return view('home',['data'=>$data]);
}
}
</code></pre>
<p><strong>web php</strong></p>
<pre><code>Route::get('home', [homeController::class ,'index']);
</code></pre>
|
[
{
"answer_id": 74523974,
"author": "Mohamed Maher",
"author_id": 20512345,
"author_profile": "https://Stackoverflow.com/users/20512345",
"pm_score": -1,
"selected": false,
"text": "php artisan migrate\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74523913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20557281/"
] |
74,523,916
|
<p>Hi I'd like to understand how in the following python program to proceed to add "the latest added number" and the "count of numbers that were added". the output should be like [121 21 11], the code gives 121 but how do I get the other two?</p>
<pre><code>sum = 0
k = 1
while sum <= 100:
sum = sum + k
k = k + 2
print(sum)
</code></pre>
<p>I don't know what commands to use to find out the answer, sum is 121, how do I add 21 which is the last number added before sum <= 100 and 11 which is the count of numbers (1,3,5,7,9,11,13,15,17,19,21)</p>
|
[
{
"answer_id": 74523974,
"author": "Mohamed Maher",
"author_id": 20512345,
"author_profile": "https://Stackoverflow.com/users/20512345",
"pm_score": -1,
"selected": false,
"text": "php artisan migrate\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74523916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20565368/"
] |
74,523,921
|
<p>I am currently on a project to develop a small, fun program that takes a name as an input and returns the name with the string "bi" after each vowel in the name.</p>
<p>I am encountering the problem that my program runs in an infinite loop when I have a name that has same the same vowel twice, for example: the name "aya". technically it should return "abiyabi"</p>
<pre><code>"""Welcome to the code of BoBi Sprache. This Sprache aka Language will
put the letter "bi" after each vowel letter in your name"""
print("Welcome to the BoBiSprache programm")
Name = input("Please enter your name to be BoBied :D : ")
NameList = list(Name.lower())
vowels = ["a", "e", "i", "o", "u"]
def VowelCheck(NameList):
for i in NameList:
index = NameList.index(i)
for j in vowels:
if i == j and index == 0:
NameList.insert(index + 1, "bi")
elif i == j and (str(NameList[index - 1]) + str(NameList[index])) != "bi":
NameList.insert(index + 1, "bi")
VowelCheck(NameList)
NewName = ""
NewName = (NewName.join(NameList)).title()
print("Your New Name is: %s" % NewName)
</code></pre>
<p>I thought first it is a problem with the first letter being a vowel. but I added an if statement that should solve that. I'm honestly out of answers now, and seeking help. You guys might see something I don't see.</p>
|
[
{
"answer_id": 74524220,
"author": "CodeKorn",
"author_id": 10882128,
"author_profile": "https://Stackoverflow.com/users/10882128",
"pm_score": 0,
"selected": false,
"text": "index"
},
{
"answer_id": 74524418,
"author": "Michael Ruth",
"author_id": 4583620,
"author_profile": "https://Stackoverflow.com/users/4583620",
"pm_score": 1,
"selected": true,
"text": "\nusername = input(\"Please enter your name to be BoBied :D : \")\nvowels = [\"a\", \"e\", \"i\", \"o\", \"u\"]\n\n\ndef VowelCheck(name):\n bobified_name = \"\"\n for i in name:\n bobified_name += i\n if i in vowels:\n bobified_name += \"bi\"\n return bobified_name\n\n\nprint(\"Your New Name is: %s\" % VowelCheck(username).title())\n str.translate() dict translate() username = input(\"Please enter your name to be Bobied :D : \")\nbobi_table = str.maketrans({\n 'a': 'abi',\n 'e': 'ebi',\n 'i': 'ibi',\n 'o': 'obi',\n 'u': 'ubi'\n})\nprint(\"Your new name is: %s\" % username.translate(bobi_table))\n"
},
{
"answer_id": 74524587,
"author": "Hampus Larsson",
"author_id": 8805293,
"author_profile": "https://Stackoverflow.com/users/8805293",
"pm_score": 1,
"selected": false,
"text": "str.translate username = input(\"Please enter your name to be BoBied :D : \")\nvowels = [\"a\", \"e\", \"i\", \"o\", \"u\"]\nvowels += [i.upper() for i in vowels]\ntranslation_table = str.maketrans({i: i+\"bi\" for i in vowels})\n\nprint((f\"Your BoBied name is: {username.translate(translation_table)}\"))\n Please enter your name to be BoBied :D : Hampus\nYour BoBied name is: Habimpubis\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74523921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17142790/"
] |
74,523,941
|
<p>The link I try to export images is this</p>
<p><a href="https://www.ebay.com/sch/i.html?_dkr=1&iconV2Request=true&_blrs=recall_filtering&_ssn=autobuffy&store_cat=0&store_name=autobuffy&_oac=1&_sop=10&_ipg=120&rt=nc&_pgn=5" rel="nofollow noreferrer">https://www.ebay.com/sch/i.html?_dkr=1&iconV2Request=true&_blrs=recall_filtering&_ssn=autobuffy&store_cat=0&store_name=autobuffy&_oac=1&_sop=10&_ipg=120&rt=nc&_pgn=5</a></p>
<p>This is the page 5.</p>
<p>The link is in the cell A1. So, The formula I use is</p>
<p>=IMPORTXML(A1,"//img/@src")</p>
<p>This formula works for the pages 1, 2, 3, and 4 but it does not work for the pages after 5.</p>
<p>Why does not this formula work for page 5?</p>
<p>This is the result below I receive.</p>
<p><a href="https://i.stack.imgur.com/aezYj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aezYj.png" alt="the result" /></a></p>
|
[
{
"answer_id": 74538860,
"author": "David Morales",
"author_id": 9652475,
"author_profile": "https://Stackoverflow.com/users/9652475",
"pm_score": 1,
"selected": false,
"text": "=IMPORTXML(A1,\"//*[@class='s-message__content']\")\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74523941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19928126/"
] |
74,523,984
|
<p>I declared 2 arrays in the top of my code as a class. I am trying to reference these later on in a seperate function but for some reason it isn't reading it.</p>
<p>Tried using Vectors and arrays, etc. looked into pointers. different headers. not sure what I'm missing.</p>
<pre><code>class Cards {
// Public Data to keep variables open thourghout the Code
// We would use private if sensitve data was involved
public:
string deck[13] = {"1", "2", "3", "4", "5", "6",
"7", "8", "9", "10", "J", "A"};
string suit[4] = {"Hearts", "Spades", "Diamonds", "Clubs"};
vector<string> cardVal = {"Ace", "Two", "Three", "Four", "Five",
"Six", "Seven", "Eight", "Nine", "Ten",
"Jack", "Queen", "King"};
vector<string> suitvec = {"Hearts", "Spades", "Diamonds", "Clubs"};
};
int DrawCard() {
srand(time(0));
int RandomDraw = rand() % 13;
int RandomSuit = rand() % 4;
int handValue = 0;
for (int i = 0; i < 1; i++) {
cout << deck[RandomDraw];
cout << suit[RandomSuit];
}
return handValue;
}
</code></pre>
|
[
{
"answer_id": 74526148,
"author": "Matteo",
"author_id": 14323837,
"author_profile": "https://Stackoverflow.com/users/14323837",
"pm_score": 1,
"selected": false,
"text": "int DrawCard() {\n srand(time(0)); \n int RandomDraw = rand( ) % 13;\n int RandomSuit = rand() % 4;\n int handValue = 0;\n Cards c;\n\n\n for(int i = 0; i < 1; i++) {\n cout << c.deck[RandomDraw];\n cout << c.suit[RandomSuit];\n\n } \n"
},
{
"answer_id": 74526762,
"author": "Rohan Bari",
"author_id": 11471113,
"author_profile": "https://Stackoverflow.com/users/11471113",
"pm_score": 0,
"selected": false,
"text": "DrawCard class Cards {\n .\n .\n\npublic:\n int DrawCard(void);\n};\n\nint Cards::DrawCard(void) {\n .\n .\n}\n class Cards {\n .\n .\n .\n};\n\nint DrawCard(void) {\n Cards cards;\n .\n .\n cards.deck.at(RandomDraw);\n cards.suit.at(RandomSuit);\n}\n at"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74523984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20566075/"
] |
74,523,987
|
<p>How would I calculate the difference between two separate list and store them in a third list.</p>
<p>for example...</p>
<pre><code>list_1 [('M', 4000.0), ('R', 5320.0)]
list_2 [('M', 4222.0), ('R', 5442.0)]
</code></pre>
<p>I tried the following</p>
<pre><code>list_3 = []
list_3.append([list_1] - [list_2])
print(list_3)
</code></pre>
<p>but I'm met with, a TypeError</p>
<pre><code>TypeError: unsupported operand type(s) for -: 'list' and 'list'
</code></pre>
|
[
{
"answer_id": 74526148,
"author": "Matteo",
"author_id": 14323837,
"author_profile": "https://Stackoverflow.com/users/14323837",
"pm_score": 1,
"selected": false,
"text": "int DrawCard() {\n srand(time(0)); \n int RandomDraw = rand( ) % 13;\n int RandomSuit = rand() % 4;\n int handValue = 0;\n Cards c;\n\n\n for(int i = 0; i < 1; i++) {\n cout << c.deck[RandomDraw];\n cout << c.suit[RandomSuit];\n\n } \n"
},
{
"answer_id": 74526762,
"author": "Rohan Bari",
"author_id": 11471113,
"author_profile": "https://Stackoverflow.com/users/11471113",
"pm_score": 0,
"selected": false,
"text": "DrawCard class Cards {\n .\n .\n\npublic:\n int DrawCard(void);\n};\n\nint Cards::DrawCard(void) {\n .\n .\n}\n class Cards {\n .\n .\n .\n};\n\nint DrawCard(void) {\n Cards cards;\n .\n .\n cards.deck.at(RandomDraw);\n cards.suit.at(RandomSuit);\n}\n at"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74523987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15368659/"
] |
74,524,065
|
<p>I need to count the occurrences of each element in the "ID" field of a generic list. The result should be the list with an added field called "Quantity".</p>
<p>Suppose the following class is used for the list:</p>
<pre class="lang-cs prettyprint-override"><code>public class InfoList
{
public string ID { get; set; }
public DateTime PurchaseDate { get; set; }
public double Amount { get; set; }
public int Quantity { get; set; }
}
</code></pre>
<p>Imagine an initial list like the following:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ID</th>
<th>Purchase date</th>
<th>Amount (USD)</th>
</tr>
</thead>
<tbody>
<tr>
<td>DDD</td>
<td>30 jul 2025</td>
<td>258,225.11</td>
</tr>
<tr>
<td>AXC</td>
<td>10 nov 2023</td>
<td>982,383.95</td>
</tr>
<tr>
<td>AXC</td>
<td>12 feb 2031</td>
<td>-439,130.87</td>
</tr>
<tr>
<td>TPV</td>
<td>05 mar 2023</td>
<td>439,715.32</td>
</tr>
<tr>
<td>DDD</td>
<td>8 apr 2024</td>
<td>-153,893.38</td>
</tr>
<tr>
<td>KYR</td>
<td>24 mar 2023</td>
<td>-153,893.38</td>
</tr>
<tr>
<td>AXC</td>
<td>10 sep 2026</td>
<td>638,031.66</td>
</tr>
<tr>
<td>SPM</td>
<td>26 oct 2023</td>
<td>-401,815.59</td>
</tr>
<tr>
<td>DDD</td>
<td>08 mar 2023</td>
<td>-315,099.43</td>
</tr>
<tr>
<td>HGP</td>
<td>30 nov 2025</td>
<td>-474,749.80</td>
</tr>
<tr>
<td>DDD</td>
<td>02 jul 2024</td>
<td>-253,726.59</td>
</tr>
<tr>
<td>NDS</td>
<td>06 sep 2029</td>
<td>490,035.01</td>
</tr>
<tr>
<td>HGP</td>
<td>24 dec 2026</td>
<td>468,006.38</td>
</tr>
</tbody>
</table>
</div>
<p>The final result should be the following:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ID</th>
<th>Purchase date</th>
<th>Amount (USD)</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td>DDD</td>
<td>30 jul 2025</td>
<td>258,225.11</td>
<td>4</td>
</tr>
<tr>
<td>AXC</td>
<td>10 nov 2023</td>
<td>982,383.95</td>
<td>3</td>
</tr>
<tr>
<td>AXC</td>
<td>12 feb 2031</td>
<td>-439,130.87</td>
<td>3</td>
</tr>
<tr>
<td>TPV</td>
<td>05 mar 2023</td>
<td>439,715.32</td>
<td>1</td>
</tr>
<tr>
<td>DDD</td>
<td>8 apr 2024</td>
<td>-153,893.38</td>
<td>4</td>
</tr>
<tr>
<td>KYR</td>
<td>24 mar 2023</td>
<td>-153,893.38</td>
<td>1</td>
</tr>
<tr>
<td>AXC</td>
<td>10 sep 2026</td>
<td>638,031.66</td>
<td>3</td>
</tr>
<tr>
<td>SPM</td>
<td>26 oct 2023</td>
<td>-401,815.59</td>
<td>1</td>
</tr>
<tr>
<td>DDD</td>
<td>08 mar 2023</td>
<td>-315,099.43</td>
<td>4</td>
</tr>
<tr>
<td>HGP</td>
<td>30 nov 2025</td>
<td>-474,749.80</td>
<td>2</td>
</tr>
<tr>
<td>DDD</td>
<td>02 jul 2024</td>
<td>-253,726.59</td>
<td>4</td>
</tr>
<tr>
<td>NDS</td>
<td>06 sep 2029</td>
<td>490,035.01</td>
<td>1</td>
</tr>
<tr>
<td>HGP</td>
<td>24 dec 2026</td>
<td>468,006.38</td>
<td>2</td>
</tr>
</tbody>
</table>
</div>
<p>Result should be of type "InfoList" not in a different list or variable.</p>
|
[
{
"answer_id": 74524287,
"author": "Chris Phillips",
"author_id": 1833878,
"author_profile": "https://Stackoverflow.com/users/1833878",
"pm_score": 0,
"selected": false,
"text": "void main()\n{\n List<ItemList> purchaseList = buildItemList();\n Dictionary<string,int> quantity = buildQuantityDictionary(purchaseList);\n printTable(purchaseList, quantity);\n}\n\nList<ItemList> buildItemList()\n{\n //however you build the itemlist\n}\n\nDictionary<string,int> buildQuantityDictionary(List<ItemList> purchaseList)\n{\n Dictionary<string,int> quantity = new Dictionary<string,int>();\n foreach(ItemList item in purchaseList)\n {\n if(!quantity.ContainsKey(item.id))\n {\n quantity.add(item.id,0);\n }\n quantity[item.id]++;\n }\n return quantity;\n}\n\nvoid printTable(List<ItemList> purchaseList, Dictionary<string,int> quantity)\n{\n foreach(ItemList item in purchaseList)\n {\n //You'll need to write a ToString() override for your ItemList object.\n Console.WriteLine($\"{item.ToString()},{quantity[item.id]}\");\n }\n}\n"
},
{
"answer_id": 74525909,
"author": "Enigmativity",
"author_id": 259769,
"author_profile": "https://Stackoverflow.com/users/259769",
"pm_score": 2,
"selected": true,
"text": "var initial = new[]\n{\n new { ID = \"DDD\", PurchaseDate = DateTime.Parse(\"30 jul 2025\"), Amount = 258225.11 },\n new { ID = \"AXC\", PurchaseDate = DateTime.Parse(\"10 nov 2023\"), Amount = 982383.95 },\n new { ID = \"AXC\", PurchaseDate = DateTime.Parse(\"12 feb 2031\"), Amount = -439130.87 },\n new { ID = \"TPV\", PurchaseDate = DateTime.Parse(\"05 mar 2023\"), Amount = 439715.32 },\n new { ID = \"DDD\", PurchaseDate = DateTime.Parse(\"8 apr 2024\"), Amount = -153893.38 },\n new { ID = \"KYR\", PurchaseDate = DateTime.Parse(\"24 mar 2023\"), Amount = -153893.38 },\n new { ID = \"AXC\", PurchaseDate = DateTime.Parse(\"10 sep 2026\"), Amount = 638031.66 },\n new { ID = \"SPM\", PurchaseDate = DateTime.Parse(\"26 oct 2023\"), Amount = -401815.59 },\n new { ID = \"DDD\", PurchaseDate = DateTime.Parse(\"08 mar 2023\"), Amount = -315099.43 },\n new { ID = \"HGP\", PurchaseDate = DateTime.Parse(\"30 nov 2025\"), Amount = -474749.80 },\n new { ID = \"DDD\", PurchaseDate = DateTime.Parse(\"02 jul 2024\"), Amount = -253726.59 },\n new { ID = \"NDS\", PurchaseDate = DateTime.Parse(\"06 sep 2029\"), Amount = 490035.01 },\n new { ID = \"HGP\", PurchaseDate = DateTime.Parse(\"24 dec 2026\"), Amount = 468006.38 },\n};\n\nvar lookup = initial.ToLookup(x => x.ID);\n\nInfoList[] final =\n initial\n .Select(i =>\n new InfoList()\n {\n ID = i.ID,\n PurchaseDate = i.PurchaseDate,\n Amount = i.Amount,\n Quantity = lookup[i.ID].Count(),\n })\n .ToArray();\n InfoList[] final =\n(\n from i in initial\n group i by i.ID into gis\n from gi in gis\n select new InfoList()\n {\n ID = gi.ID,\n PurchaseDate = gi.PurchaseDate,\n Amount = gi.Amount,\n Quantity = gis.Count(),\n }\n).ToArray();\n public static IEnumerable<R> SelectCount<T, U, R>(this IEnumerable<T> source, Func<T, U> countBy, Func<T, int, R> project) =>\n from t in source\n group t by countBy(t) into gts\n from gt in gts\n select project(gt, gts.Count());\n InfoList[] final =\n initial\n .SelectCount(i => i.ID, (i, q) => new InfoList()\n {\n ID = i.ID,\n PurchaseDate = i.PurchaseDate,\n Amount = i.Amount,\n Quantity = q,\n })\n .ToArray();\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74524065",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19980295/"
] |
74,524,076
|
<p>Recently I stumbled upon a quite itchy problem. I had to open a qt project, which I cloned from repository version. I opened it and tried to build. Hardly was there a non-red line. I got tons of compiler errors:</p>
<pre><code>Unknown type name 'QString'
Unknown type name 'QSqlDatabase'
Unknown type name 'Q_OBJECT'
'QWidget' file not found
</code></pre>
<p>and others.
I suppose the problem is somewhere in my Qt Creator or in .pro file, as the actual developers of the project had no problem running it.</p>
<p>I'm using Qt 6.4.1</p>
<p>Here's my .pro file:</p>
<pre><code>QT += core gui
QT += sql
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
CONFIG += c++17
# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += all necessary .cpp files\
HEADERS += all necessary .h files\
FORMS += all necessary .ui files\
# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
</code></pre>
|
[
{
"answer_id": 74524287,
"author": "Chris Phillips",
"author_id": 1833878,
"author_profile": "https://Stackoverflow.com/users/1833878",
"pm_score": 0,
"selected": false,
"text": "void main()\n{\n List<ItemList> purchaseList = buildItemList();\n Dictionary<string,int> quantity = buildQuantityDictionary(purchaseList);\n printTable(purchaseList, quantity);\n}\n\nList<ItemList> buildItemList()\n{\n //however you build the itemlist\n}\n\nDictionary<string,int> buildQuantityDictionary(List<ItemList> purchaseList)\n{\n Dictionary<string,int> quantity = new Dictionary<string,int>();\n foreach(ItemList item in purchaseList)\n {\n if(!quantity.ContainsKey(item.id))\n {\n quantity.add(item.id,0);\n }\n quantity[item.id]++;\n }\n return quantity;\n}\n\nvoid printTable(List<ItemList> purchaseList, Dictionary<string,int> quantity)\n{\n foreach(ItemList item in purchaseList)\n {\n //You'll need to write a ToString() override for your ItemList object.\n Console.WriteLine($\"{item.ToString()},{quantity[item.id]}\");\n }\n}\n"
},
{
"answer_id": 74525909,
"author": "Enigmativity",
"author_id": 259769,
"author_profile": "https://Stackoverflow.com/users/259769",
"pm_score": 2,
"selected": true,
"text": "var initial = new[]\n{\n new { ID = \"DDD\", PurchaseDate = DateTime.Parse(\"30 jul 2025\"), Amount = 258225.11 },\n new { ID = \"AXC\", PurchaseDate = DateTime.Parse(\"10 nov 2023\"), Amount = 982383.95 },\n new { ID = \"AXC\", PurchaseDate = DateTime.Parse(\"12 feb 2031\"), Amount = -439130.87 },\n new { ID = \"TPV\", PurchaseDate = DateTime.Parse(\"05 mar 2023\"), Amount = 439715.32 },\n new { ID = \"DDD\", PurchaseDate = DateTime.Parse(\"8 apr 2024\"), Amount = -153893.38 },\n new { ID = \"KYR\", PurchaseDate = DateTime.Parse(\"24 mar 2023\"), Amount = -153893.38 },\n new { ID = \"AXC\", PurchaseDate = DateTime.Parse(\"10 sep 2026\"), Amount = 638031.66 },\n new { ID = \"SPM\", PurchaseDate = DateTime.Parse(\"26 oct 2023\"), Amount = -401815.59 },\n new { ID = \"DDD\", PurchaseDate = DateTime.Parse(\"08 mar 2023\"), Amount = -315099.43 },\n new { ID = \"HGP\", PurchaseDate = DateTime.Parse(\"30 nov 2025\"), Amount = -474749.80 },\n new { ID = \"DDD\", PurchaseDate = DateTime.Parse(\"02 jul 2024\"), Amount = -253726.59 },\n new { ID = \"NDS\", PurchaseDate = DateTime.Parse(\"06 sep 2029\"), Amount = 490035.01 },\n new { ID = \"HGP\", PurchaseDate = DateTime.Parse(\"24 dec 2026\"), Amount = 468006.38 },\n};\n\nvar lookup = initial.ToLookup(x => x.ID);\n\nInfoList[] final =\n initial\n .Select(i =>\n new InfoList()\n {\n ID = i.ID,\n PurchaseDate = i.PurchaseDate,\n Amount = i.Amount,\n Quantity = lookup[i.ID].Count(),\n })\n .ToArray();\n InfoList[] final =\n(\n from i in initial\n group i by i.ID into gis\n from gi in gis\n select new InfoList()\n {\n ID = gi.ID,\n PurchaseDate = gi.PurchaseDate,\n Amount = gi.Amount,\n Quantity = gis.Count(),\n }\n).ToArray();\n public static IEnumerable<R> SelectCount<T, U, R>(this IEnumerable<T> source, Func<T, U> countBy, Func<T, int, R> project) =>\n from t in source\n group t by countBy(t) into gts\n from gt in gts\n select project(gt, gts.Count());\n InfoList[] final =\n initial\n .SelectCount(i => i.ID, (i, q) => new InfoList()\n {\n ID = i.ID,\n PurchaseDate = i.PurchaseDate,\n Amount = i.Amount,\n Quantity = q,\n })\n .ToArray();\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74524076",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20492391/"
] |
74,524,077
|
<p>I am trying to only allow numeric values, along with a possible negative symbol at the front of the string, and a single decimal, using Regex in JavaScript. This input value will only allow for a possible 10 digits also.</p>
<p>Currently, when a user inputs text, I have this logic that will only allow numbers, negative signs, and decimals. However, I want to limit the number of the negative sign to one, and only allow this at the front of the string. Also, I want to limit the number of decimals to one.</p>
<pre><code>input.slice(0, 10).replace(/[^0-9.\-]/, '');
</code></pre>
<p>Can anyone please help me figure this out?</p>
|
[
{
"answer_id": 74524287,
"author": "Chris Phillips",
"author_id": 1833878,
"author_profile": "https://Stackoverflow.com/users/1833878",
"pm_score": 0,
"selected": false,
"text": "void main()\n{\n List<ItemList> purchaseList = buildItemList();\n Dictionary<string,int> quantity = buildQuantityDictionary(purchaseList);\n printTable(purchaseList, quantity);\n}\n\nList<ItemList> buildItemList()\n{\n //however you build the itemlist\n}\n\nDictionary<string,int> buildQuantityDictionary(List<ItemList> purchaseList)\n{\n Dictionary<string,int> quantity = new Dictionary<string,int>();\n foreach(ItemList item in purchaseList)\n {\n if(!quantity.ContainsKey(item.id))\n {\n quantity.add(item.id,0);\n }\n quantity[item.id]++;\n }\n return quantity;\n}\n\nvoid printTable(List<ItemList> purchaseList, Dictionary<string,int> quantity)\n{\n foreach(ItemList item in purchaseList)\n {\n //You'll need to write a ToString() override for your ItemList object.\n Console.WriteLine($\"{item.ToString()},{quantity[item.id]}\");\n }\n}\n"
},
{
"answer_id": 74525909,
"author": "Enigmativity",
"author_id": 259769,
"author_profile": "https://Stackoverflow.com/users/259769",
"pm_score": 2,
"selected": true,
"text": "var initial = new[]\n{\n new { ID = \"DDD\", PurchaseDate = DateTime.Parse(\"30 jul 2025\"), Amount = 258225.11 },\n new { ID = \"AXC\", PurchaseDate = DateTime.Parse(\"10 nov 2023\"), Amount = 982383.95 },\n new { ID = \"AXC\", PurchaseDate = DateTime.Parse(\"12 feb 2031\"), Amount = -439130.87 },\n new { ID = \"TPV\", PurchaseDate = DateTime.Parse(\"05 mar 2023\"), Amount = 439715.32 },\n new { ID = \"DDD\", PurchaseDate = DateTime.Parse(\"8 apr 2024\"), Amount = -153893.38 },\n new { ID = \"KYR\", PurchaseDate = DateTime.Parse(\"24 mar 2023\"), Amount = -153893.38 },\n new { ID = \"AXC\", PurchaseDate = DateTime.Parse(\"10 sep 2026\"), Amount = 638031.66 },\n new { ID = \"SPM\", PurchaseDate = DateTime.Parse(\"26 oct 2023\"), Amount = -401815.59 },\n new { ID = \"DDD\", PurchaseDate = DateTime.Parse(\"08 mar 2023\"), Amount = -315099.43 },\n new { ID = \"HGP\", PurchaseDate = DateTime.Parse(\"30 nov 2025\"), Amount = -474749.80 },\n new { ID = \"DDD\", PurchaseDate = DateTime.Parse(\"02 jul 2024\"), Amount = -253726.59 },\n new { ID = \"NDS\", PurchaseDate = DateTime.Parse(\"06 sep 2029\"), Amount = 490035.01 },\n new { ID = \"HGP\", PurchaseDate = DateTime.Parse(\"24 dec 2026\"), Amount = 468006.38 },\n};\n\nvar lookup = initial.ToLookup(x => x.ID);\n\nInfoList[] final =\n initial\n .Select(i =>\n new InfoList()\n {\n ID = i.ID,\n PurchaseDate = i.PurchaseDate,\n Amount = i.Amount,\n Quantity = lookup[i.ID].Count(),\n })\n .ToArray();\n InfoList[] final =\n(\n from i in initial\n group i by i.ID into gis\n from gi in gis\n select new InfoList()\n {\n ID = gi.ID,\n PurchaseDate = gi.PurchaseDate,\n Amount = gi.Amount,\n Quantity = gis.Count(),\n }\n).ToArray();\n public static IEnumerable<R> SelectCount<T, U, R>(this IEnumerable<T> source, Func<T, U> countBy, Func<T, int, R> project) =>\n from t in source\n group t by countBy(t) into gts\n from gt in gts\n select project(gt, gts.Count());\n InfoList[] final =\n initial\n .SelectCount(i => i.ID, (i, q) => new InfoList()\n {\n ID = i.ID,\n PurchaseDate = i.PurchaseDate,\n Amount = i.Amount,\n Quantity = q,\n })\n .ToArray();\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74524077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8572557/"
] |
74,524,097
|
<p>Using Terraform v1.2.5 I am attempting to deploy an AWS VPC Peer. However, the following code fails validation:</p>
<pre><code>terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 4.1"
}
}
}
provider "aws" {
region = "us-east-1"
}
data "aws_vpc" "accepter" {
provider = aws.accepter
id = "${var.accepter_vpc_id}"
}
locals {
accepter_account_id = "${element(split(":", data.aws_vpc.accepter.arn), 4)}"
}
resource "aws_vpc_peering_connection" "requester" {
description = "peer_to_${var.accepter_profile}"
vpc_id = "{$var.requester_vpc_id}"
peer_vpc_id = "${data.aws_vpc.accepter.id}"
peer_owner_id = "${local.accepter_account_id}"
}
</code></pre>
<p>When validating this terraform code I am receiving the following error :</p>
<pre><code>$ terraform validate
╷
│ Error: Provider configuration not present
│
│ To work with data.aws_vpc.accepter its original provider configuration at provider["registry.terraform.io/hashicorp/aws"].accepter is
│ required, but it has been removed. This occurs when a provider configuration is removed while objects created by that provider still exist
│ in the state. Re-add the provider configuration to destroy data.aws_vpc.accepter, after which you can remove the provider configuration
│ again.
</code></pre>
<p>What am I missing or misconfigured that is causing this error?</p>
|
[
{
"answer_id": 74524975,
"author": "Marko E",
"author_id": 8343484,
"author_profile": "https://Stackoverflow.com/users/8343484",
"pm_score": 2,
"selected": false,
"text": "data \"aws_vpc\" \"accepter\" {\n provider = aws.accepter # <--- missing aliased provider\n id = var.accepter_vpc_id\n}\n provider \"aws\" {\n alias = \"accepter\"\n region = \"us-east-1\" # make sure the region is right\n}\n"
},
{
"answer_id": 74589935,
"author": "NinjaCloud",
"author_id": 20432287,
"author_profile": "https://Stackoverflow.com/users/20432287",
"pm_score": 0,
"selected": false,
"text": "provider \"aws\" {\n region = \"us-east-1\"\n\n # Requester's credentials.\n}\n\nprovider \"aws\" {\n alias = \"peer\"\n region = \"us-west-2\"\n\n # Accepter's credentials.\n}"
},
{
"answer_id": 74590259,
"author": "Pawel Piwosz",
"author_id": 20614302,
"author_profile": "https://Stackoverflow.com/users/20614302",
"pm_score": 0,
"selected": false,
"text": "provider \"aws\" {\n region = \"us-east-1\"\n alias = \"accepter\"\n}\n provider = aws.accepter data \"aws_vpc\" \"accepter\""
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74524097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14120387/"
] |
74,524,109
|
<p>I want ask the question.</p>
<p>I want to deploy from github to nginx server using jenkins. Maybe you can help me with this? When i try to add in Jenkins setting Publish over SSH i have error</p>
<pre><code>jenkins.plugins.publish_over.BapPublisherException: Failed to add SSH key. Message [invalid privatekey: [B@2a8ec46d]
</code></pre>
<p>I just started to study these technologies and most likely I am doing something wrong. Maybe i need configure my nginx files?</p>
<p>Also please tell me something links maybe with Guid how to deploy from GitHub using Jenkins and Nginx.</p>
|
[
{
"answer_id": 74524975,
"author": "Marko E",
"author_id": 8343484,
"author_profile": "https://Stackoverflow.com/users/8343484",
"pm_score": 2,
"selected": false,
"text": "data \"aws_vpc\" \"accepter\" {\n provider = aws.accepter # <--- missing aliased provider\n id = var.accepter_vpc_id\n}\n provider \"aws\" {\n alias = \"accepter\"\n region = \"us-east-1\" # make sure the region is right\n}\n"
},
{
"answer_id": 74589935,
"author": "NinjaCloud",
"author_id": 20432287,
"author_profile": "https://Stackoverflow.com/users/20432287",
"pm_score": 0,
"selected": false,
"text": "provider \"aws\" {\n region = \"us-east-1\"\n\n # Requester's credentials.\n}\n\nprovider \"aws\" {\n alias = \"peer\"\n region = \"us-west-2\"\n\n # Accepter's credentials.\n}"
},
{
"answer_id": 74590259,
"author": "Pawel Piwosz",
"author_id": 20614302,
"author_profile": "https://Stackoverflow.com/users/20614302",
"pm_score": 0,
"selected": false,
"text": "provider \"aws\" {\n region = \"us-east-1\"\n alias = \"accepter\"\n}\n provider = aws.accepter data \"aws_vpc\" \"accepter\""
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74524109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20566084/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.