qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,606,698
|
<p>I'm trying to use the data copy activity to extract information from azure databricks delta lake, but I've noticed that it doesn't pass the information directly from the delta lake to the SQL server I need, but must pass it to an azure blob storage, when running it, it throws the following error</p>
<pre><code>ErrorCode=AzureDatabricksCommandError,Hit an error when running the command in Azure Databricks. Error details: Failure to initialize configurationInvalid configuration value detected for fs.azure.account.key Caused by: Invalid configuration value detected for fs.azure.account.key
</code></pre>
<p>Looking for information I found a possible solution but it didn't work.</p>
<p><a href="https://stackoverflow.com/questions/72724911/invalid-configuration-value-detected-for-fs-azure-account-key-copy-activity-fail">Invalid configuration value detected for fs.azure.account.key copy activity fails</a></p>
<p>Does anyone have any idea how the hell to pass information from an azure databricks delta lake table to a table in Sql Server??</p>
<p>These are some images of the structure that I have in ADF:</p>
<p><a href="https://i.stack.imgur.com/JuZgl.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JuZgl.jpg" alt="enter image description here" /></a></p>
<p>In the image I get a message that tells me that I must have a Storage Account to continue</p>
<p>These are the configuration images, and execution failed:</p>
<p>Conf:
<a href="https://i.stack.imgur.com/6tFgB.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6tFgB.jpg" alt="enter image description here" /></a></p>
<p>Fail:
<a href="https://i.stack.imgur.com/aq0Kp.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aq0Kp.jpg" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/ZQUnl.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZQUnl.jpg" alt="enter image description here" /></a></p>
<p>Thank you very much</p>
|
[
{
"answer_id": 74613423,
"author": "Pratik Lad",
"author_id": 18043699,
"author_profile": "https://Stackoverflow.com/users/18043699",
"pm_score": 0,
"selected": false,
"text": "spark.hadoop.fs.azure.account.key.<storageaccountname>.blob.core.windows.net <Accesskey>\nspark.databricks.delta.optimizeWrite.enabled true \nspark.databricks.delta.autoCompact.enabled true \n Enable staging Staging account linked service"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74606698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14170289/"
] |
74,606,749
|
<p>Session is invalid when browser is closed, but if the application tab is closed instead of browser, how can we invalid a vaadin flow session?</p>
<p>I guess the following code should be added to some place, but I don't know where. Which event is fired when browser tab is closed? Can anybody help?</p>
<pre><code>VaadinSession.getCurrent().getSession().invalidate();
</code></pre>
<p>This piece of code is currently in logout handler and works fine.</p>
<p>Thanks in advance.</p>
|
[
{
"answer_id": 74611950,
"author": "Tarek Oraby",
"author_id": 11982497,
"author_profile": "https://Stackoverflow.com/users/11982497",
"pm_score": 2,
"selected": false,
"text": "UI UI VaadinSession.getCurrent().getUIs()"
},
{
"answer_id": 74624760,
"author": "lanmaster",
"author_id": 1059104,
"author_profile": "https://Stackoverflow.com/users/1059104",
"pm_score": 0,
"selected": false,
"text": "import com.vaadin.flow.component.Tag;\nimport com.vaadin.flow.component.dependency.JsModule;\nimport com.vaadin.flow.component.polymertemplate.EventHandler;\nimport com.vaadin.flow.component.polymertemplate.PolymerTemplate;\nimport com.vaadin.flow.templatemodel.TemplateModel;\n\n/**\n * Polymer-component for page ping\n */\n@Tag(\"ping-component\")\n@JsModule(\"./src/ping-component.js\")\npublic class PingComponent extends PolymerTemplate<TemplateModel> {\n\n private final transient Runnable updatePingTsRunnable;\n\n public PingComponent(Runnable updatePingTsRunnable) {\n this.updatePingTsRunnable = updatePingTsRunnable;\n }\n\n @EventHandler\n private void invokePingEvent() {\n //System.out.println(\"Ping received\");\n updatePingTsRunnable.run();\n }\n}\n /**\n * Browser-side part for page ping\n *\n * @see https://polymer-library.polymer-project.org/3.0/docs/devguide/data-binding\n * @see https://polymer-library.polymer-project.org/3.0/docs/devguide/events\n *\n */\nimport {PolymerElement, html} from '@polymer/polymer/polymer-element.js';\n\nclass PingComponent extends PolymerElement {\n\n constructor() {\n super();\n /* ping send period 5000 ms */\n setInterval(() => this.invokePingEvent(), 5000);\n }\n\n static get template() {\n return html`\n <div></div>\n `;\n }\n\n static get is() {\n return 'ping-component';\n }\n\n // Linked to backend method PingComponent#invokePingEvent\n invokePingEvent() {\n }\n}\n\ncustomElements.define(PingComponent.is, PingComponent);\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74606749",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18632312/"
] |
74,606,765
|
<p>I am working a database that is very poorly organized. There are CustomerIds that are somehow bigger than int64. Here is an example: 88168142359034442077.0</p>
<p>In order to be able to use this ID, I need to turn it into a string and remove the decimal.
I have tried to use the following code:</p>
<pre><code>testdf = pd.DataFrame({'CUSTID': ['99418675896216.02342351', '88168142359034442077.0213', '53056496953']})
testdf['CUSTID'] = testdf['CUSTID'].astype('float64').astype('int64').astype(str)
testdf.display()
</code></pre>
<p>When I use the above method I get an overflow and then the numbers that are bigger than int64 becomes negative like: -9223372036854775808 for 88168142359034442077.0213</p>
<p>I have being looking for other ways to be able to make the the change from string to float, then float to int, and finally int to string again.</p>
<p>One method that I tried is to just not use astype('int64'), but it makes the the output into scientific format like: 8.816814235903445e+19 for 88168142359034442077.0213 and other than using regex to remove the decimal and 'e+19' I don't really see what else I can do.</p>
<p>Any information is appreciated. Thanks!</p>
|
[
{
"answer_id": 74606946,
"author": "Jérôme Richard",
"author_id": 12939557,
"author_profile": "https://Stackoverflow.com/users/12939557",
"pm_score": 0,
"selected": false,
"text": "testdf['CUSTID'] pandas.Series pandas.Series int Decimal map testdf['CUSTID'] = list(map(int, map(decimal.Decimal, testdf['CUSTID'].to_list())))\n testdf['CUSTID'] = [int(s.split('.')[0]) for s in testdf['CUSTID'].to_list()]\n"
},
{
"answer_id": 74607072,
"author": "norok2",
"author_id": 5218354,
"author_profile": "https://Stackoverflow.com/users/5218354",
"pm_score": 0,
"selected": false,
"text": ". import pandas as pd\n\n\ntestdf = pd.DataFrame({'CUSTID': ['99418675896216.02342351', '88168142359034442077.0213', '53056496953']})\ntestdf['CUSTID'] = testdf['CUSTID'].apply(lambda s: s[:s.find(\".\")])\ntestdf.display()\n lambda s: s[:s.find(\".\")] lambda s: s.split(\".\", 1)[0] lambda s: re.match(r\"^(\\d+)(?:\\.(\\d+))?$\", s).groups()[0] str extract() testdf['CUSTID'] = testdf['CUSTID'].str.extract(r\"^(\\d+)(?:\\.(\\d+))?$\")\n rstrip() ."
},
{
"answer_id": 74607249,
"author": "ti7",
"author_id": 4541045,
"author_profile": "https://Stackoverflow.com/users/4541045",
"pm_score": 3,
"selected": true,
"text": ">>> data1 = \"111001111001110100110001111000110110110111110101111000111001110110110010110001110110101110110000110010110011110100110010110011110101110001\"\n>>> data2 = \"111000111000110001110110111000110001110100110010110011110101111001110000110011110100110100110100110010110000110111110111101110110000110010110001110011\"\n>>> for data in (data1, data2):\n... print(\"\".join(chr(eval(\"0b\" + data[block:block+6])) for block in range(0, len(data), 6)))\n... \n99418675896216.02342351\n88168142359034442077.0213\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74606765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14615988/"
] |
74,606,779
|
<p>In Linux, I'm running the command</p>
<pre><code>pmap -x $PID | tail -n 1
</code></pre>
<p>This gives me a line like the following:</p>
<pre><code>total kB 168194812 870692 852296
</code></pre>
<p>I'm trying to extract the 2nd number (rss) for use. I found this example that works in regex101.com:</p>
<pre><code>/[^\d]*[\d]+[\s]+([\d]+)/
</code></pre>
<p>However, when I try to run it against my line of text I don't get any print output:</p>
<pre><code>echo "total kB 168194812 870692 852296" | gawk 'match($0, /[^\d]*[\d]+[\s]+([\d]+)/, a) {print a[1]}'
</code></pre>
<p>I'm expecting it to print</p>
<pre><code>870692
</code></pre>
|
[
{
"answer_id": 74606824,
"author": "Gilles Quenot",
"author_id": 465183,
"author_profile": "https://Stackoverflow.com/users/465183",
"pm_score": 3,
"selected": true,
"text": "$ pmap -x $PID | gawk 'match($0, /[^0-9]*[0-9]+\\s+([0-9]+)/, a) {print a[1]}'\n870692\n \\d awk '{print $4}'\n grep -oP '\\d+(?=\\s+\\d+$)'\n"
},
{
"answer_id": 74606826,
"author": "Ôrel",
"author_id": 4605105,
"author_profile": "https://Stackoverflow.com/users/4605105",
"pm_score": 2,
"selected": false,
"text": "awk '{print $4}'\n echo \"total kB 168194812 870692 852296\" | awk '{print $4}'\n 870692\n"
},
{
"answer_id": 74607057,
"author": "The fourth bird",
"author_id": 5424988,
"author_profile": "https://Stackoverflow.com/users/5424988",
"pm_score": 1,
"selected": false,
"text": "awk [0-9] [^0-9] tail -n 1 gnu awk echo \"total kB 168194812 870692 852296\" | \nawk -v RS='[0-9]+' 'NR == 2 {print RT}'\n 870692\n"
},
{
"answer_id": 74608588,
"author": "RavinderSingh13",
"author_id": 5866580,
"author_profile": "https://Stackoverflow.com/users/5866580",
"pm_score": 2,
"selected": false,
"text": "grep grep echo \"total kB 168194812 870692 852296\" |\ngrep -oP '^total kB\\s+\\d+\\s+\\K\\d+'\n -oP grep grep ^total kB\\s+\\d+\\s+\\K\\d+ total kB \\K"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74606779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20627441/"
] |
74,606,825
|
<p>I have two files: a .csv file that has ugly numbered files and a dictionary. Here's a similar and simplified example of the .csv file:</p>
<pre><code>responses <- tribble(
~n_case, ~movie, ~song, ~sex,
1, 2, 2, 0,
2, 1, 1, 0,
3, 2, 4, 1
)
</code></pre>
<p>And here's a similar and simplified example of the dictionary database:</p>
<pre><code># Note the jump from 2 to 4 in 'song' is deliberate,
# as this appears in the actual database that I am working with
dic <- tribble(
~name, ~value, ~tag,
"movie", 1, "Shrek",
"movie", 2, "Lego",
"song", 1, "Hallelujah",
"song", 2, "Happy Birthday",
"song", 4, "Melancholy Hill",
"sex", 0, "male",
"sex", 1, "female"
)
</code></pre>
<p>What could I do to replace the ugly "values" by the human-readable "tags"?
I'd like to arrive at this:</p>
<pre><code>> responses_human
# A tibble: 3 × 4
n_case movie song sex
<dbl> <chr> <chr> <chr>
1 1 Lego Happy Birthday male
2 2 Shrek Hallelujah male
3 3 Lego Melancholy Hill female
</code></pre>
<p>In case you're curious, I am working with <a href="https://www.censopoblacion.gt/descarga" rel="nofollow noreferrer">Guatemala's person census</a> (as opposed to house or home census).</p>
<p>I tried solving my problem by filtering each 'name' (survey question's answers; i.e. "movie", "song", "sex"), grabbing the result and creating a new tibble out of that. That way, I'd end up with dozens of tibbles, each being a mini-dictionary for each survey question's answers (movie, song, sex, etc.). Then, I'd <code>left_join</code> these filtered mini-dictionaries, one by one, resulting in dozens of new human-readable columns. I'd then appropriately <code>rename</code> and <code>select</code> the columns so that I'd get rid of the ugly numbers and only keep the human-readable "tags".</p>
<p>However, this solution requires naming dozens of variables and is therefore a slow process. Note that there are 84 variables, each with multiple numbered/ugly "values" and human-readable "tags". Moreover, I will probably use the other (house and home) censuses, which pose the same problem.</p>
<p>I have a hunch that there's a much more efficient and automated way of doing this. I just don't know what it is yet.</p>
|
[
{
"answer_id": 74607226,
"author": "stefan",
"author_id": 12993861,
"author_profile": "https://Stackoverflow.com/users/12993861",
"pm_score": 2,
"selected": false,
"text": "list name list across library(dplyr, w = FALSE)\nlibrary(tibble)\n\ndic_split <- split(dic, dic$name) %>%\n lapply(function(x) {\n x %>%\n select(-name) %>%\n tibble::deframe()\n })\n\nrec_helper <- function(x, col) {\n recode(x, !!!dic_split[[col]])\n}\n\nresponses %>%\n mutate(across(\n all_of(intersect(names(dic_split), names(responses))),\n ~ rec_helper(.x, cur_column())\n ))\n#> # A tibble: 3 × 4\n#> n_case movie song sex \n#> <dbl> <chr> <chr> <chr> \n#> 1 1 Lego Happy Birthday male \n#> 2 2 Shrek Hallelujah male \n#> 3 3 Lego Melancholy Hill female\n"
},
{
"answer_id": 74607873,
"author": "Ritchie Sacramento",
"author_id": 2835261,
"author_profile": "https://Stackoverflow.com/users/2835261",
"pm_score": 1,
"selected": false,
"text": "library(dplyr)\nlibrary(tidyr)\n\ndic_wide <- dic %>%\n pivot_wider(names_from = name, values_from = tag)\n\nresponses %>%\n mutate(across(-n_case, ~ dic_wide[[cur_column()]][match(.x, dic_wide$value)]))\n\n# A tibble: 3 × 4\n n_case movie song sex \n <dbl> <chr> <chr> <chr> \n1 1 Lego Happy Birthday male \n2 2 Shrek Hallelujah male \n3 3 Lego Melancholy Hill female\n"
},
{
"answer_id": 74608832,
"author": "AndS.",
"author_id": 9778513,
"author_profile": "https://Stackoverflow.com/users/9778513",
"pm_score": 2,
"selected": false,
"text": "library(tidyverse)\n\nresponses |>\n pivot_longer(-n_case) |>\n left_join(dic, by = c(\"name\", \"value\")) |>\n select(-value) |>\n pivot_wider(names_from = name, values_from = tag)\n#> # A tibble: 3 x 4\n#> n_case movie song sex \n#> <dbl> <chr> <chr> <chr> \n#> 1 1 Lego Happy Birthday male \n#> 2 2 Shrek Hallelujah male \n#> 3 3 Lego Melancholy Hill female\n responses |>\n mutate(across(movie:sex, \\(x) as.character(factor(x,\n levels = dic[dic$name == cur_column(),]$value,\n labels = dic[dic$name == cur_column(),]$tag))))\n#> # A tibble: 3 x 4\n#> n_case movie song sex \n#> <dbl> <chr> <chr> <chr> \n#> 1 1 Lego Happy Birthday male \n#> 2 2 Shrek Hallelujah male \n#> 3 3 Lego Melancholy Hill female\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74606825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4669323/"
] |
74,606,877
|
<p>I am seeing this error:</p>
<blockquote>
<p>Function lacks ending return statement and return type does not include 'undefined'.</p>
</blockquote>
<p>With this TypeScript code:</p>
<pre><code>function decodeData(
data: string | number[] | ArrayBuffer | Uint8Array,
): string {
const td = new TextDecoder();
if (typeof (data) === "string") {
return data;
} else if (data instanceof Array) {
return td.decode(new Uint8Array(data));
} else if (data instanceof ArrayBuffer) {
return td.decode(data);
} else if (data instanceof Uint8Array) {
return td.decode(data);
}
}
</code></pre>
<p>My understanding is that the compiler will see all my guards cover all potential types of <code>data</code>. If I add an "else throw" it's happy.</p>
<p>What have I misunderstood?</p>
|
[
{
"answer_id": 74606983,
"author": "dbonev",
"author_id": 4200334,
"author_profile": "https://Stackoverflow.com/users/4200334",
"pm_score": 0,
"selected": false,
"text": "function decodeData(\n data: string | number[] | ArrayBuffer | Uint8Array,\n): string {\n const td = new TextDecoder();\n if (typeof (data) === \"string\") {\n return data;\n } else if (data instanceof Array<number>) {\n return td.decode(new Uint8Array(data));\n } else if (data instanceof ArrayBuffer) {\n return td.decode(data);\n } else if (data instanceof Uint8Array) {\n return td.decode(data);\n }\n\n return '';\n}\n"
},
{
"answer_id": 74607190,
"author": "jcalz",
"author_id": 2887218,
"author_profile": "https://Stackoverflow.com/users/2887218",
"pm_score": 2,
"selected": true,
"text": "data never if else switch switch decodeData() assertNever() never throw function assertNever(x: never): never {\n throw new Error(\"Unexpected Value: \" + x);\n}\n decodeData() assertNever(data) function decodeData(\n data: string | number[] | ArrayBuffer | Uint8Array,\n): string {\n const td = new TextDecoder();\n if (typeof (data) === \"string\") {\n return data;\n } else if (data instanceof Array) {\n return td.decode(new Uint8Array(data));\n } else if (data instanceof ArrayBuffer) {\n return td.decode(data);\n } else if (data instanceof Uint8Array) {\n return td.decode(data);\n }\n assertNever(data);\n}\n assertNever() assertNever(data) function badDecodeData(\n data: string | number[] | ArrayBuffer | Uint8Array,\n): string {\n const td = new TextDecoder();\n if (typeof (data) === \"string\") {\n return data;\n } else if (data instanceof Array) {\n return td.decode(new Uint8Array(data));\n //} else if (data instanceof ArrayBuffer) {\n // return td.decode(data);\n } else if (data instanceof Uint8Array) {\n return td.decode(data);\n }\n assertNever(data); // error! \n // -------> ~~~~\n // Argument of type 'ArrayBuffer' is not assignable to parameter of type 'never'\n}\n assertNever(data) ArrayBuffer never"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74606877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/107783/"
] |
74,606,882
|
<p>I have this string:</p>
<pre><code>a = '91:99 OT (87:87)'
</code></pre>
<p>I would like to split it into:</p>
<pre><code>['91', '99', '87', '87']
</code></pre>
<p>In my case numerical values can vary from 01 to 999 so that I have to use regex module. I am working with Python.</p>
|
[
{
"answer_id": 74606983,
"author": "dbonev",
"author_id": 4200334,
"author_profile": "https://Stackoverflow.com/users/4200334",
"pm_score": 0,
"selected": false,
"text": "function decodeData(\n data: string | number[] | ArrayBuffer | Uint8Array,\n): string {\n const td = new TextDecoder();\n if (typeof (data) === \"string\") {\n return data;\n } else if (data instanceof Array<number>) {\n return td.decode(new Uint8Array(data));\n } else if (data instanceof ArrayBuffer) {\n return td.decode(data);\n } else if (data instanceof Uint8Array) {\n return td.decode(data);\n }\n\n return '';\n}\n"
},
{
"answer_id": 74607190,
"author": "jcalz",
"author_id": 2887218,
"author_profile": "https://Stackoverflow.com/users/2887218",
"pm_score": 2,
"selected": true,
"text": "data never if else switch switch decodeData() assertNever() never throw function assertNever(x: never): never {\n throw new Error(\"Unexpected Value: \" + x);\n}\n decodeData() assertNever(data) function decodeData(\n data: string | number[] | ArrayBuffer | Uint8Array,\n): string {\n const td = new TextDecoder();\n if (typeof (data) === \"string\") {\n return data;\n } else if (data instanceof Array) {\n return td.decode(new Uint8Array(data));\n } else if (data instanceof ArrayBuffer) {\n return td.decode(data);\n } else if (data instanceof Uint8Array) {\n return td.decode(data);\n }\n assertNever(data);\n}\n assertNever() assertNever(data) function badDecodeData(\n data: string | number[] | ArrayBuffer | Uint8Array,\n): string {\n const td = new TextDecoder();\n if (typeof (data) === \"string\") {\n return data;\n } else if (data instanceof Array) {\n return td.decode(new Uint8Array(data));\n //} else if (data instanceof ArrayBuffer) {\n // return td.decode(data);\n } else if (data instanceof Uint8Array) {\n return td.decode(data);\n }\n assertNever(data); // error! \n // -------> ~~~~\n // Argument of type 'ArrayBuffer' is not assignable to parameter of type 'never'\n}\n assertNever(data) ArrayBuffer never"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74606882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11779489/"
] |
74,606,911
|
<p>I'm writing a rock, paper, scissors, game for a user and computer and I want the user to type in one of the three options i.e "rock" but I'm not sure what kind of exception to use if the user enters say "monkey."</p>
<pre><code>class RockPaperScissors:
def getUserChoice(userchoice):
while True:
try:
userchoice = input("Type in your choice: rock, paper, scissors: ")
if userchoice != "rock" or userchoice != "paper" or userchoice != "scissors":
raise ValueError("Try typing in your choice again")
break
except:
print("Invalid Input.")
return userchoice.lower()
</code></pre>
|
[
{
"answer_id": 74606983,
"author": "dbonev",
"author_id": 4200334,
"author_profile": "https://Stackoverflow.com/users/4200334",
"pm_score": 0,
"selected": false,
"text": "function decodeData(\n data: string | number[] | ArrayBuffer | Uint8Array,\n): string {\n const td = new TextDecoder();\n if (typeof (data) === \"string\") {\n return data;\n } else if (data instanceof Array<number>) {\n return td.decode(new Uint8Array(data));\n } else if (data instanceof ArrayBuffer) {\n return td.decode(data);\n } else if (data instanceof Uint8Array) {\n return td.decode(data);\n }\n\n return '';\n}\n"
},
{
"answer_id": 74607190,
"author": "jcalz",
"author_id": 2887218,
"author_profile": "https://Stackoverflow.com/users/2887218",
"pm_score": 2,
"selected": true,
"text": "data never if else switch switch decodeData() assertNever() never throw function assertNever(x: never): never {\n throw new Error(\"Unexpected Value: \" + x);\n}\n decodeData() assertNever(data) function decodeData(\n data: string | number[] | ArrayBuffer | Uint8Array,\n): string {\n const td = new TextDecoder();\n if (typeof (data) === \"string\") {\n return data;\n } else if (data instanceof Array) {\n return td.decode(new Uint8Array(data));\n } else if (data instanceof ArrayBuffer) {\n return td.decode(data);\n } else if (data instanceof Uint8Array) {\n return td.decode(data);\n }\n assertNever(data);\n}\n assertNever() assertNever(data) function badDecodeData(\n data: string | number[] | ArrayBuffer | Uint8Array,\n): string {\n const td = new TextDecoder();\n if (typeof (data) === \"string\") {\n return data;\n } else if (data instanceof Array) {\n return td.decode(new Uint8Array(data));\n //} else if (data instanceof ArrayBuffer) {\n // return td.decode(data);\n } else if (data instanceof Uint8Array) {\n return td.decode(data);\n }\n assertNever(data); // error! \n // -------> ~~~~\n // Argument of type 'ArrayBuffer' is not assignable to parameter of type 'never'\n}\n assertNever(data) ArrayBuffer never"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74606911",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20076579/"
] |
74,606,914
|
<p>I have a query where I should avoid double entry of the same question. In fact, I would like to get only unique values but, I am using the <code>distinct()</code> django function which isn't working.
I have these models:</p>
<pre><code>class QuestionTopic(models.Model):
name = models.CharField(max_length=255)
question_subject = models.ForeignKey(
QuestionSubject, on_delete=models.CASCADE)
exam_questions_num = models.IntegerField(null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
class Meta:
ordering = ('created_at',)
class Question(models.Model):
id = models.CharField(max_length=7,
unique=True,
primary_key=True,
editable=False)
question_subject = models.ForeignKey(
QuestionSubject, on_delete=models.CASCADE)
text = tinymce_models.HTMLField()
mark = models.IntegerField(default=1)
is_published = models.BooleanField(default=True)
question_bank_id = models.CharField(max_length=255, blank=True, null=True)
question_topic = models.ForeignKey(
QuestionTopic, on_delete=models.CASCADE, null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
</code></pre>
<p>and the query is:</p>
<pre><code> subject = QuestionSubject.objects.get(id=request.POST.get('subject'))
question_topics = QuestionTopic.objects.filter(
question_subject=subject)
questions_list = []
for topic in question_topics:
for q in range(topic.exam_questions_num):
question = Question.objects.filter(
question_subject=subject, question_topic=topic).values_list(
'id', flat=True).order_by('?').distinct().first()
questions_list.append(question)
</code></pre>
<p>What I would like to achieve is to have all different questions for each different topic inside <code>questions_list</code>. Which I am not achieving at the moment being the <code>distinct</code> used inside a loop.</p>
|
[
{
"answer_id": 74606983,
"author": "dbonev",
"author_id": 4200334,
"author_profile": "https://Stackoverflow.com/users/4200334",
"pm_score": 0,
"selected": false,
"text": "function decodeData(\n data: string | number[] | ArrayBuffer | Uint8Array,\n): string {\n const td = new TextDecoder();\n if (typeof (data) === \"string\") {\n return data;\n } else if (data instanceof Array<number>) {\n return td.decode(new Uint8Array(data));\n } else if (data instanceof ArrayBuffer) {\n return td.decode(data);\n } else if (data instanceof Uint8Array) {\n return td.decode(data);\n }\n\n return '';\n}\n"
},
{
"answer_id": 74607190,
"author": "jcalz",
"author_id": 2887218,
"author_profile": "https://Stackoverflow.com/users/2887218",
"pm_score": 2,
"selected": true,
"text": "data never if else switch switch decodeData() assertNever() never throw function assertNever(x: never): never {\n throw new Error(\"Unexpected Value: \" + x);\n}\n decodeData() assertNever(data) function decodeData(\n data: string | number[] | ArrayBuffer | Uint8Array,\n): string {\n const td = new TextDecoder();\n if (typeof (data) === \"string\") {\n return data;\n } else if (data instanceof Array) {\n return td.decode(new Uint8Array(data));\n } else if (data instanceof ArrayBuffer) {\n return td.decode(data);\n } else if (data instanceof Uint8Array) {\n return td.decode(data);\n }\n assertNever(data);\n}\n assertNever() assertNever(data) function badDecodeData(\n data: string | number[] | ArrayBuffer | Uint8Array,\n): string {\n const td = new TextDecoder();\n if (typeof (data) === \"string\") {\n return data;\n } else if (data instanceof Array) {\n return td.decode(new Uint8Array(data));\n //} else if (data instanceof ArrayBuffer) {\n // return td.decode(data);\n } else if (data instanceof Uint8Array) {\n return td.decode(data);\n }\n assertNever(data); // error! \n // -------> ~~~~\n // Argument of type 'ArrayBuffer' is not assignable to parameter of type 'never'\n}\n assertNever(data) ArrayBuffer never"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74606914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16950492/"
] |
74,606,932
|
<pre><code>{
"id": "a1234567-89ab-cdef-0123-456789abcdef",
"properties": {
...
"my_id": "c1234567-89ab-cdef-0123-456789abcdef",
...
}
</code></pre>
<p>Given the above in a file, I want to be able to perform a match (including the 4 leading spaces) on <code>my_id</code> and then append a new line <code> "my_value": "abcd",</code>. The desired output would look like this:</p>
<pre><code>{
"id": "a1234567-89ab-cdef-0123-456789abcdef",
"properties": {
...
"my_id": "c1234567-89ab-cdef-0123-456789abcdef",
"my_value": "abcd",
...
}
</code></pre>
<p>Using examples online, I'm unable to get the command to work. Here is an example of something I have tried: <code>sed '/.*"my_id".*/a "my_value": "abcd",' test.json</code>, for which I receive the following error: <code>command a expects \ followed by text</code>.</p>
<p>What is the correct way to structure this command?</p>
|
[
{
"answer_id": 74607166,
"author": "HatLess",
"author_id": 16372109,
"author_profile": "https://Stackoverflow.com/users/16372109",
"pm_score": 2,
"selected": false,
"text": "sed $ sed -e '/my_id/{p;s/id.*\"/value\": \"abcd\"/' -e '}' input_file\n{\n \"id\": \"a1234567-89ab-cdef-0123-456789abcdef\",\n \"properties\": {\n ...\n \"my_id\": \"c1234567-89ab-cdef-0123-456789abcdef\",\n \"my_value\": \"abcd\",\n ...\n}\n"
},
{
"answer_id": 74607325,
"author": "Ed Morton",
"author_id": 1745001,
"author_profile": "https://Stackoverflow.com/users/1745001",
"pm_score": 2,
"selected": false,
"text": "$ awk -v new='\"my_value\": \"abcd\",' '{print} sub(/\"my_id\":.*/,\"\"){print $0 new}' file\n{\n \"id\": \"a1234567-89ab-cdef-0123-456789abcdef\",\n \"properties\": {\n ...\n \"my_id\": \"c1234567-89ab-cdef-0123-456789abcdef\",\n \"my_value\": \"abcd\",\n ...\n}\n \"my_id\" sub(/\"my_id\":.*/,\"\"){print $0 new}\n sub(/\"my_id\":.*/,new)\n &"
},
{
"answer_id": 74607403,
"author": "Dave Pritlove",
"author_id": 2005666,
"author_profile": "https://Stackoverflow.com/users/2005666",
"pm_score": 3,
"selected": true,
"text": "awk awk 'abcd' awk -v insertVal=\"abcd\" '/\"my_id\":/{$0=$0\"\\n \\\"my_value\\\": \\\"\"insertVal\"\\\",\"} {print}' dat.txt\n 'abcd' -v insertVal=\"abcd\" awk action pattern \"my_id\": pattern \\n key \"my_value\" insertVal \"abcd\" , \" awk dat.txt {\n \"id\": \"a1234567-89ab-cdef-0123-456789abcdef\",\n \"properties\": {\n ...\n \"my_id\": \"c1234567-89ab-cdef-0123-456789abcdef\",\n \"my_value\": \"abcd\",\n ...\n}\n"
},
{
"answer_id": 74608534,
"author": "RavinderSingh13",
"author_id": 5866580,
"author_profile": "https://Stackoverflow.com/users/5866580",
"pm_score": 2,
"selected": false,
"text": "awk newVal awk match awk (.*)(\"my_id\": \"[^\"]*\",)(.*) awk -v newVal='\"my_value\": \"abcd\",' -v RS= '\nmatch($0,/(.*)(\"my_id\": \"[^\"]*\",)(.*)/,arr){\n print arr[1] arr[2] newVal arr[3]\n}\n' Input_file\n"
},
{
"answer_id": 74613828,
"author": "potong",
"author_id": 967492,
"author_profile": "https://Stackoverflow.com/users/967492",
"pm_score": 1,
"selected": false,
"text": "sed '/\"my-id\".*/p;s//\"my-value\": \"abcd\"/' file\n \"my-id\""
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74606932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4372759/"
] |
74,606,935
|
<p>I am trying to make it so the caption for the React web app is the same as Figma design. How do I add a break or invisible character between "we make it simple" and "to create software" so that it looks like this Figma design?</p>
<p><a href="https://i.stack.imgur.com/Z4rpt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Z4rpt.png" alt="Figma Design" /></a>
<a href="https://i.stack.imgur.com/06mMO.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/06mMO.jpg" alt="Current Website Design" /></a>
<a href="https://i.stack.imgur.com/069OP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/069OP.png" alt="Code" /></a></p>
|
[
{
"answer_id": 74607042,
"author": "dbonev",
"author_id": 4200334,
"author_profile": "https://Stackoverflow.com/users/4200334",
"pm_score": 2,
"selected": false,
"text": "we make it simple <br /> to create software\n"
},
{
"answer_id": 74607859,
"author": "Oskar Grosser",
"author_id": 13561410,
"author_profile": "https://Stackoverflow.com/users/13561410",
"pm_score": -1,
"selected": false,
"text": "<p> <br> <br> <br> aria-hidden=\"true\" <p>\n We make it simple<br aria-hidden=\"true\">\n to write software.\n</p> <pre> role generic paragraph <p> <span style=\"display: block\"> <p> role=\"text\" role=\"text\" <p> .line {display: block} <p>\n <span class=\"line\">We make it simple</span>\n <span class=\"line\">to write software.</span>\n</p>"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74606935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20515851/"
] |
74,606,950
|
<p>I have some data (json) that looks like this:</p>
<pre><code>[
{
"name": "Enterprise Networking",
"technology": "Networking"
},
{
"name": "Enterprise Networking",
"technology": "Networking"
},
{
"name": "Wireless Insights",
"technology": "Mobility and Wireless"
},
{
"name": "Mobility Insights",
"technology": "Mobility and Wireless"
},
{
"name": "Lock it down",
"technology": "Security"
},
{
"name": "Collaboration",
"technology": "Security"
}
]
</code></pre>
<p>I am trying to find matches based on an array of filtering options for one field named 'technology' in this example. For example, my filtering criteria will be ["Networking", "Security"]. I would expect to return all objects that have 'Networking' and 'Security' as their technology, excluding 'Mobility and Wireless' in this example.</p>
<p>I have figured out how to do it with just one filter criteria using:</p>
<pre><code>result = learningMapsDataObj.filter(el => el.Technology === filter3[0].value);
</code></pre>
<p>I've tried adding a method that will loop through the the filter array, but can't get it to work.</p>
<pre><code>result = learningMapsDataObj.filter(el => el.Technology === myloopingArrCheckFunction(el.technology, filters3));
</code></pre>
<p>I know I'm close, but haven't had to dev in a while and my multidimensional brain isn't working.</p>
|
[
{
"answer_id": 74607042,
"author": "dbonev",
"author_id": 4200334,
"author_profile": "https://Stackoverflow.com/users/4200334",
"pm_score": 2,
"selected": false,
"text": "we make it simple <br /> to create software\n"
},
{
"answer_id": 74607859,
"author": "Oskar Grosser",
"author_id": 13561410,
"author_profile": "https://Stackoverflow.com/users/13561410",
"pm_score": -1,
"selected": false,
"text": "<p> <br> <br> <br> aria-hidden=\"true\" <p>\n We make it simple<br aria-hidden=\"true\">\n to write software.\n</p> <pre> role generic paragraph <p> <span style=\"display: block\"> <p> role=\"text\" role=\"text\" <p> .line {display: block} <p>\n <span class=\"line\">We make it simple</span>\n <span class=\"line\">to write software.</span>\n</p>"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74606950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3617606/"
] |
74,606,961
|
<p>I have a table where column A is the date/time, and column B fruits sold. I need a formula that automatically counts how many fruits were sold per day. With the following additional conditions:</p>
<ul>
<li>I need the present-day included. <br/></li>
<li>I need weekends excluded.<br/></li>
<li>I also need this formula to respond to a menu with the desired time period.</li>
<li>Days with "0" count should not appear.</li>
</ul>
<p>Here is a sample data:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Date</th>
<th>Fruit</th>
<th>Period</th>
</tr>
</thead>
<tbody>
<tr>
<td>20/10/2022</td>
<td>18</td>
<td></td>
</tr>
<tr>
<td>21/10/2022</td>
<td>15</td>
<td></td>
</tr>
<tr>
<td>22/10/2022</td>
<td>10</td>
<td></td>
</tr>
<tr>
<td>23/10/2022</td>
<td>4</td>
<td></td>
</tr>
<tr>
<td>[...]</td>
<td></td>
<td></td>
</tr>
<tr>
<td>27/11/2022</td>
<td>19</td>
<td></td>
</tr>
<tr>
<td>28/11/2022</td>
<td>21</td>
<td></td>
</tr>
</tbody>
</table>
</div>
<p>I have this formula (not mine tbf):</p>
<pre><code>=LET(d,HubLog[Date],s,INT(MIN(d)),e,INT(MAX(d)),days,SEQUENCE(e-s,,s),
weekdays,FILTER(days,MOD(days,7)>1),qty,
COUNTIFS(HubLog[Date],">="&weekdays,HubLog[Date],"<"&weekdays+1),
CHOOSE({1,2},weekdays,qty))
</code></pre>
<p>But it does not seem to be working properly here. Also, in another file I have it was counting but not including the present day and not responsive to the time period menu. The file below is a simplified version of my real file, but for some reason it does not even seem to work.</p>
<p>Is there anything that can be changed in the formula to achieve the requirements explained above?</p>
<p><strong>Dummy file:</strong>
<a href="https://1drv.ms/x/s!AhJ6NsWJczYBhSjKQVMab8WlYINT?e=uxZOJs" rel="nofollow noreferrer">https://1drv.ms/x/s!AhJ6NsWJczYBhSjKQVMab8WlYINT?e=uxZOJs</a></p>
|
[
{
"answer_id": 74607042,
"author": "dbonev",
"author_id": 4200334,
"author_profile": "https://Stackoverflow.com/users/4200334",
"pm_score": 2,
"selected": false,
"text": "we make it simple <br /> to create software\n"
},
{
"answer_id": 74607859,
"author": "Oskar Grosser",
"author_id": 13561410,
"author_profile": "https://Stackoverflow.com/users/13561410",
"pm_score": -1,
"selected": false,
"text": "<p> <br> <br> <br> aria-hidden=\"true\" <p>\n We make it simple<br aria-hidden=\"true\">\n to write software.\n</p> <pre> role generic paragraph <p> <span style=\"display: block\"> <p> role=\"text\" role=\"text\" <p> .line {display: block} <p>\n <span class=\"line\">We make it simple</span>\n <span class=\"line\">to write software.</span>\n</p>"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74606961",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16498578/"
] |
74,606,966
|
<p><a href="https://i.stack.imgur.com/cBOq8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cBOq8.png" alt="enter image description here" /></a></p>
<p>in the example data set above, I want to assign a Primary_Store for each buyer_id based on the following criteria</p>
<ul>
<li>if one store has more visit counts than any other store for that buyer, assign as primary</li>
<li>if no, then
---- > if stores with most visits are equal, assign Primary_Store according to hierarchy of store_type: 1. Retail, 2.Online, 3.Event
------------> if stores with most visits are equal, and store_type is the same, then assign Primary_Store as store with earliest visit date</li>
</ul>
<p>By this logic the results should be:
Buyer ID : Primary_Store
1001: Whole Foods
1002: Farmer's Market
1003: Costco</p>
<p>I have been trying to use a case when statement but i am having difficulty applying the different types of criteria at once.</p>
|
[
{
"answer_id": 74607111,
"author": "Simeon Pilgrim",
"author_id": 43992,
"author_profile": "https://Stackoverflow.com/users/43992",
"pm_score": 1,
"selected": false,
"text": "SELECT \n *\n ,decode(store_type, 'Retail', 1, 'Online', 2, 'Event', 3) as rnk2\n ,row_number() over (partition by buyer_id order by visit_count desc, rnk2, first_visit) as rn\nFROM VALUES\n (1001, 'Whole Foods', '2020-05-31'::date, 'Retail', 10),\n (1001, 'Instacart', '2020-03-15'::date, 'Online', 10),\n (1001, 'Farmer\"s Market', '2020-01-24'::date, 'Event', 4),\n (1002, 'Trader Joes', '2020-02-12'::date, 'Retail', 9)\n \n t(buyer_id, store, first_visit, store_type, visit_count)\n SELECT \n *\nFROM VALUES\n (1001, 'Whole Foods', '2020-05-31'::date, 'Retail', 10),\n (1001, 'Instacart', '2020-03-15'::date, 'Online', 10),\n (1001, 'Farmer\"s Market', '2020-01-24'::date, 'Event', 4),\n (1002, 'Trader Joes', '2020-02-12'::date, 'Retail', 9)\n \n t(buyer_id, store, first_visit, store_type, visit_count)\nqualify row_number() over (\n partition by buyer_id \n order by visit_count desc, \n decode(store_type, 'Retail', 1, 'Online', 2, 'Event', 3), \n first_visit) = 1\n ;\n SELECT \n *\n ,iff(row_number() over (\n partition by buyer_id \n order by visit_count desc, \n decode(store_type, 'Retail', 1, 'Online', 2, 'Event', 3), \n first_visit) = 1, 'yes', 'no' ) as primary_store\nFROM your_table\n"
},
{
"answer_id": 74607251,
"author": "Rajat",
"author_id": 9947159,
"author_profile": "https://Stackoverflow.com/users/9947159",
"pm_score": 0,
"selected": false,
"text": "decode array_position select *, first_value(store) over \n (partition by buyer_id \n order by visit_count desc, \n array_position(store_type::variant,['Retail','Online', 'Event']), \n first_visit asc) as primary_store\nfrom your_table;\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74606966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18623003/"
] |
74,606,967
|
<p>I created a group tasks using "generate" and was trying to call them using a for loop.</p>
<p>I have used generate block to create multiple instances of module, so I thought I could use it similarly to create multiple tasks. I plan to have no arguments for the tasks, and always call the tasks in a loop. But the number of tasks to be called is dependent on a parameter (instead of "4" in the example below, it will be a parameter).</p>
<p>Here is an example of what I was trying to do:</p>
<pre><code> task display;
fork
other_tasks();
for(int i=0; i<4; i++) begin
create_task[i].print_i;
end
// create_task[0].print_i;
// create_task[1].print_i;
// create_task[2].print_i;
// create_task[3].print_i;
join
endtask
generate
for(genvar i=0; i<4; i++) begin : create_task
task print_i();
$display("%t, %m, Message #%0d", $time, i);
#1;
endtask
end : create_task
endgenerate
</code></pre>
<p>The code gives me no error if I call the tasks separately (commented lines) instead of using "for". However, I would prefer to do this using a loop because the number of tasks I need to call may vary. What would be the correct way of doing this?</p>
|
[
{
"answer_id": 74607111,
"author": "Simeon Pilgrim",
"author_id": 43992,
"author_profile": "https://Stackoverflow.com/users/43992",
"pm_score": 1,
"selected": false,
"text": "SELECT \n *\n ,decode(store_type, 'Retail', 1, 'Online', 2, 'Event', 3) as rnk2\n ,row_number() over (partition by buyer_id order by visit_count desc, rnk2, first_visit) as rn\nFROM VALUES\n (1001, 'Whole Foods', '2020-05-31'::date, 'Retail', 10),\n (1001, 'Instacart', '2020-03-15'::date, 'Online', 10),\n (1001, 'Farmer\"s Market', '2020-01-24'::date, 'Event', 4),\n (1002, 'Trader Joes', '2020-02-12'::date, 'Retail', 9)\n \n t(buyer_id, store, first_visit, store_type, visit_count)\n SELECT \n *\nFROM VALUES\n (1001, 'Whole Foods', '2020-05-31'::date, 'Retail', 10),\n (1001, 'Instacart', '2020-03-15'::date, 'Online', 10),\n (1001, 'Farmer\"s Market', '2020-01-24'::date, 'Event', 4),\n (1002, 'Trader Joes', '2020-02-12'::date, 'Retail', 9)\n \n t(buyer_id, store, first_visit, store_type, visit_count)\nqualify row_number() over (\n partition by buyer_id \n order by visit_count desc, \n decode(store_type, 'Retail', 1, 'Online', 2, 'Event', 3), \n first_visit) = 1\n ;\n SELECT \n *\n ,iff(row_number() over (\n partition by buyer_id \n order by visit_count desc, \n decode(store_type, 'Retail', 1, 'Online', 2, 'Event', 3), \n first_visit) = 1, 'yes', 'no' ) as primary_store\nFROM your_table\n"
},
{
"answer_id": 74607251,
"author": "Rajat",
"author_id": 9947159,
"author_profile": "https://Stackoverflow.com/users/9947159",
"pm_score": 0,
"selected": false,
"text": "decode array_position select *, first_value(store) over \n (partition by buyer_id \n order by visit_count desc, \n array_position(store_type::variant,['Retail','Online', 'Event']), \n first_visit asc) as primary_store\nfrom your_table;\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74606967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20627483/"
] |
74,606,986
|
<p>I have a canvas with a little oval in it. It moves throughout the widget using the arrow keys but when it's on the edge of the canvas if I move it beyond that, the oval just disappears.</p>
<p>I want the oval stays on any edge of the canvas no matter if I continue pressing the arrow key corresponding to that edge without disappearing.</p>
<p>This is the code:</p>
<pre><code>from tkinter import *
root = Tk()
root.title("Oval")
root.geometry("800x600")
w = 600
h = 400
x = w//2
y = h//2
my_canvas = Canvas(root, width=w, height=h, bg='black')
my_canvas.pack(pady=20)
my_circle = my_canvas.create_oval(x, y, x+20, y+20, fill='cyan')
def left(event):
x = -10
y = 0
my_canvas.move(my_circle, x, y)
def right(event):
x = 10
y = 0
my_canvas.move(my_circle, x, y)
def up(event):
x = 0
y = -10
my_canvas.move(my_circle, x, y)
def down(event):
x = 0
y = 10
my_canvas.move(my_circle, x, y)
root.bind('<Left>', left)
root.bind('<Right>', right)
root.bind('<Up>', up)
root.bind('<Down>', down)
root.mainloop()
</code></pre>
<p>This is what it looks like:</p>
<p><a href="https://i.stack.imgur.com/g90HK.jpg" rel="nofollow noreferrer">The oval on an edge</a></p>
<p>And if I continue pressing the key looks like this:</p>
<p><a href="https://i.stack.imgur.com/mLrXx.jpg" rel="nofollow noreferrer">The oval disappearing</a></p>
|
[
{
"answer_id": 74607111,
"author": "Simeon Pilgrim",
"author_id": 43992,
"author_profile": "https://Stackoverflow.com/users/43992",
"pm_score": 1,
"selected": false,
"text": "SELECT \n *\n ,decode(store_type, 'Retail', 1, 'Online', 2, 'Event', 3) as rnk2\n ,row_number() over (partition by buyer_id order by visit_count desc, rnk2, first_visit) as rn\nFROM VALUES\n (1001, 'Whole Foods', '2020-05-31'::date, 'Retail', 10),\n (1001, 'Instacart', '2020-03-15'::date, 'Online', 10),\n (1001, 'Farmer\"s Market', '2020-01-24'::date, 'Event', 4),\n (1002, 'Trader Joes', '2020-02-12'::date, 'Retail', 9)\n \n t(buyer_id, store, first_visit, store_type, visit_count)\n SELECT \n *\nFROM VALUES\n (1001, 'Whole Foods', '2020-05-31'::date, 'Retail', 10),\n (1001, 'Instacart', '2020-03-15'::date, 'Online', 10),\n (1001, 'Farmer\"s Market', '2020-01-24'::date, 'Event', 4),\n (1002, 'Trader Joes', '2020-02-12'::date, 'Retail', 9)\n \n t(buyer_id, store, first_visit, store_type, visit_count)\nqualify row_number() over (\n partition by buyer_id \n order by visit_count desc, \n decode(store_type, 'Retail', 1, 'Online', 2, 'Event', 3), \n first_visit) = 1\n ;\n SELECT \n *\n ,iff(row_number() over (\n partition by buyer_id \n order by visit_count desc, \n decode(store_type, 'Retail', 1, 'Online', 2, 'Event', 3), \n first_visit) = 1, 'yes', 'no' ) as primary_store\nFROM your_table\n"
},
{
"answer_id": 74607251,
"author": "Rajat",
"author_id": 9947159,
"author_profile": "https://Stackoverflow.com/users/9947159",
"pm_score": 0,
"selected": false,
"text": "decode array_position select *, first_value(store) over \n (partition by buyer_id \n order by visit_count desc, \n array_position(store_type::variant,['Retail','Online', 'Event']), \n first_visit asc) as primary_store\nfrom your_table;\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74606986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19934155/"
] |
74,607,000
|
<p>I need to display text when mouse is over edges (similar to image).
Maybe someone knows how to do it?
I took the example from <a href="https://plotly.com/python/network-graphs/" rel="nofollow noreferrer">plotly.com</a> and trying to modify it.
It fine works for Nodes, but I can not do it for Edges.
<a href="https://i.stack.imgur.com/8lh0V.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8lh0V.png" alt="enter image description here" /></a></p>
<pre class="lang-py prettyprint-override"><code>import networkx
import plotly.graph_objects as go
G = networkx.random_geometric_graph(n=3, radius=1)
# Create Edges
edge_x, edge_y = [], []
for idx0, idx1 in G.edges():
x0, y0 = G.nodes[idx0]["pos"]
x1, y1 = G.nodes[idx1]["pos"]
edge_x.extend([x0, x1, None])
edge_y.extend([y0, y1, None])
edge_trace = go.Scatter(
x=edge_x, y=edge_y, line=dict(width=10, color='#888'), mode='lines',
hoverinfo='text', # TODO, NOT WORKING
)
# TODO, NOT WORKING
edge_trace.text = [f"# {s}" for s in edge_x]
# Create Nodes with TEXT
node_x = []
node_y = []
nodes_o = G.nodes
nodes_ids = list(nodes_o)
for node in nodes_ids:
x, y = G.nodes[node]["pos"]
node_x.append(x)
node_y.append(y)
node_trace = go.Scatter(x=node_x, y=node_y, mode="markers", hoverinfo="text",
marker=dict(color=[], size=50, line_width=10))
node_trace.text = [f"TEXT{idx}" for idx, _ in G.adjacency()]
# Create Network Graph
fig = go.Figure(
data=[edge_trace, node_trace],
layout=go.Layout(),
)
fig.show()
</code></pre>
|
[
{
"answer_id": 74618785,
"author": "Kat",
"author_id": 5329073,
"author_profile": "https://Stackoverflow.com/users/5329073",
"pm_score": 1,
"selected": false,
"text": "mnode_x, mnode_y, mnode_txt = [], [], []\nedge_x, edge_y = [], []\nfor idx0, idx1 in G.edges():\n x0, y0 = G.nodes[idx0][\"pos\"]\n x1, y1 = G.nodes[idx1][\"pos\"]\n edge_x.extend([x0, x1, None])\n edge_y.extend([y0, y1, None])\n\n mnode_x.extend([(x0 + x1)/2]) # assuming values positive/get midpoint\n mnode_y.extend([(y0 + y1)/2]) # assumes positive vals/get midpoint\n mnode_txt.extend([f\"# {x0}\"]) # hovertext\n mnode_trace = go.Scatter(x = mnode_x, y = mnode_y, mode = \"markers\", showlegend = False,\n hovertemplate = \"Edge %{hovertext}<extra></extra>\",\n hovertext = mnode_txt, marker = go.Marker(opacity = 0))\n # Create Network Graph\nfig = go.Figure(\n data=[edge_trace, node_trace, mnode_trace],\n layout=go.Layout())\n deque collections import networkx\nimport plotly.graph_objects as go\nfrom collections import deque \n\ndef queue(a, b, qty):\n \"\"\"either x0 and x1 or y0 and y1, qty of points to create\"\"\"\n q = deque()\n q.append((0, qty - 1)) # indexing starts at 0\n pts = [0] * qty\n pts[0] = a; pts[-1] = b # x0 is the first value, x1 is the last\n while len(q) != 0:\n left, right = q.popleft() # remove working segment from queue\n center = (left + right + 1)//2 # creates index values for pts\n pts[center] = (pts[left] + pts[right])/2\n if right - left > 2: # stop when qty met\n q.append((left, center))\n q.append((center, right))\n return pts\n\n\ndef collector(x0, x1, y0, y1, qty, ht):\n \"\"\"line segment end points, how many midpoints, hovertext\"\"\"\n pth = [ht] * qty\n ptx = queue(x0, x1, qty + 2) # add 2 because the origin will be in the list\n pty = queue(y0, y1, qty + 2)\n ptx.pop(0); ptx.pop() # pop first and last (the nodes)\n pty.pop(0); pty.pop() # pop first and last (the nodes)\n return ptx, pty, pth\n collector # Create Edges\nm2x, m2y, m2t = [], [], []\nedge_x, edge_y = [], []\nfor idx0, idx1 in G.edges():\n x0, y0 = G.nodes[idx0][\"pos\"]\n x1, y1 = G.nodes[idx1][\"pos\"]\n edge_x.extend([x0, x1, None])\n edge_y.extend([y0, y1, None])\n\n # the 3 is points per line; x0 at the end is for hovertext\n ptsx, ptsy, ptsh = collector(x0, x1, y0, y1, 3, x0)\n m2x.extend(ptsx)\n m2y.extend(ptsy)\n m2t.extend(ptsh)\n m2node_trace = go.Scatter(x = m2x, y = m2y, mode = \"markers\", showlegend = False,\n hovertemplate = \"Edge # %{hovertext}<extra></extra>\",\n hovertext = m2t, marker = go.Marker(opacity = 0))\n\nfig2 = go.Figure(data = [edge_trace, node_trace, m2node_trace],\n layout = go.Layout())\n <br> hovertext"
},
{
"answer_id": 74633879,
"author": "pyjedy",
"author_id": 15222211,
"author_profile": "https://Stackoverflow.com/users/15222211",
"pm_score": 0,
"selected": false,
"text": "from collections import deque\n\nimport networkx\nimport plotly.graph_objects as go\n\nEDGE_POINTS_QUANTITY = 20\nEDGE_POINTS_OPACITY = 1\nEDGES = 3\n\n\ndef queue(a, b, qty):\n \"\"\"either x0 and x1 or y0 and y1, qty of points to create\"\"\"\n q = deque()\n q.append((0, qty - 1)) # indexing starts at 0\n pts = [0] * qty\n pts[0] = a\n pts[-1] = b # x0 is the first value, x1 is the last\n while len(q) != 0:\n left, right = q.popleft() # remove working segment from queue\n center = (left + right + 1) // 2 # creates index values for pts\n pts[center] = (pts[left] + pts[right]) / 2\n if right - left > 2: # stop when qty met\n q.append((left, center))\n q.append((center, right))\n return pts\n\n\ndef make_middle_points(first_x, last_x, first_y, last_y, qty):\n \"\"\"line segment end points, how many midpoints, hovertext\"\"\"\n # Add 2 because the origin will be in the list, pop first and last (the nodes)\n middle_x_ = queue(first_x, last_x, qty + 2)\n middle_y_ = queue(first_y, last_y, qty + 2)\n middle_x_.pop(0)\n middle_x_.pop()\n middle_y_.pop(0)\n middle_y_.pop()\n return middle_x_, middle_y_\n\n\nG = networkx.random_geometric_graph(n=EDGES, radius=1)\n\n# Create Edges with TEXT\nedge_x, edge_y = [], []\nedge_middle_x, edge_middle_y, edge_middle_text = [], [], []\nfor idx0, idx1 in G.edges():\n x0, y0 = G.nodes[idx0][\"pos\"]\n x1, y1 = G.nodes[idx1][\"pos\"]\n edge_x.extend([x0, x1, None])\n edge_y.extend([y0, y1, None])\n\n # the 3 is points per line; x0 at the end is for hovertext\n middle_x, middle_y = make_middle_points(x0, x1, y0, y1, EDGE_POINTS_QUANTITY)\n edge_middle_x.extend(middle_x)\n edge_middle_y.extend(middle_y)\n edge_middle_text.extend([f\"EDGE{idx0}{idx1}\"] * EDGE_POINTS_QUANTITY)\n\nedge_trace = go.Scatter(x=edge_x, y=edge_y, line=dict(width=10, color='#888'), mode='lines')\nm2node_trace = go.Scatter(x=edge_middle_x, y=edge_middle_y, mode=\"markers\", showlegend=False,\n hovertemplate=\"Edge # %{hovertext}<extra></extra>\",\n hovertext=edge_middle_text,\n marker=go.Marker(opacity=EDGE_POINTS_OPACITY))\n\n# Create Nodes with TEXT\nnode_x = []\nnode_y = []\nnodes_o = G.nodes\nnodes_ids = list(nodes_o)\nfor node in nodes_ids:\n x, y = G.nodes[node][\"pos\"]\n node_x.append(x)\n node_y.append(y)\n\nnode_trace = go.Scatter(x=node_x, y=node_y, mode=\"markers\", hoverinfo=\"text\",\n marker=dict(size=50, line_width=10))\nnode_trace.text = [f\"NODE{idx}\" for idx, _ in G.adjacency()]\n\n# Create Network Graph\nfig = go.Figure(data=[edge_trace, node_trace, m2node_trace], layout=go.Layout())\nfig.show()\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74607000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15222211/"
] |
74,607,017
|
<p>This is my XML</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<ns1:Message xmlns:ns1="http://API.JOEJANE.Envelope">
<ns1:MessageHeader>
<ns1:MessageId>ce82fe4f-c843-57a6-14a1-15d79773b638</ns1:MessageId>
<ns1:From>ABC</ns1:From>
<ns1:To>JOEJANE</ns1:To>
<ns1:PlantId>7301</ns1:PlantId>
</ns1:MessageHeader>
</ns1:Message>
</code></pre>
<p>This is my code trying to read it into a dataset</p>
<pre><code>def temp-table ttMsgHdr no-undo serialize-name "ns1:MessageHeader"
field MsgId as char serialize-name "ns1:MessageId"
field MsgFrom as char serialize-name "ns1:From"
field MsgTo as char serialize-name "ns1:To"
field PlantId as char serialize-name "ns1:PlantId".
def dataset dsONE xml-node-name "ns1:Message" for
ttMsgHdr.
def var dXml as longchar.
dataset dsONE:read-xml("longchar",dXml,"empty",?,?,?,?).
find first ttMsgHdr no-error.
</code></pre>
<p>And this is the error I get.</p>
<blockquote>
<p>DATASET name 'ns1:Message' in namespace '' not found in XML Document.</p>
</blockquote>
<p>I also tried with different namespace
like this:</p>
<pre><code>def dataset dsONE xml-node-name "" for
ttMsgHdr.
</code></pre>
<p>or</p>
<pre><code>def dataset dsONE xml-node-name "ns1:Message xmlns:ns1=""http://API.JOEJANE.Envelope""" for
ttMsgHdr.
</code></pre>
<p>or</p>
<pre><code>def dataset dsONE xml-node-name "ns1:Message xmlns:ns1" for
ttMsgHdr.
</code></pre>
<p>But still getting the same error.
please help thank you</p>
|
[
{
"answer_id": 74610065,
"author": "Jensd",
"author_id": 2189922,
"author_profile": "https://Stackoverflow.com/users/2189922",
"pm_score": 1,
"selected": false,
"text": "def temp-table ttMsgHdr no-undo serialize-name \"MessageHeader\"\n field MsgId as char serialize-name \"MessageId\"\n field MsgFrom as char serialize-name \"From\"\n field MsgTo as char serialize-name \"To\"\n field PlantId as char serialize-name \"PlantId\".\n\ndef dataset dsONE namespace-url \"http://API.JOEJANE.Envelope\" \n namespace-prefix \"ns1\" xml-node-name \"Message\" for ttMsgHdr.\n"
},
{
"answer_id": 74615956,
"author": "Stefan Drissen",
"author_id": 2292276,
"author_profile": "https://Stackoverflow.com/users/2292276",
"pm_score": 0,
"selected": false,
"text": "ns1 def temp-table tt no-undo serialize-name 'MessageHeader'\n field cId as char serialize-name 'MessageId'\n field cFrom as char serialize-name 'From'\n field cTo as char serialize-name 'To'\n field cPlantId as char serialize-name 'PlantId'\n .\n\ndef dataset ds serialize-name 'Message'\n for tt\n .\n\ndataset ds:read-xml( 'file', 'my.xml', ?, ?, ? ).\n\nfind first tt.\nmessage tt.cID.\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74607017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2635566/"
] |
74,607,048
|
<p>I am trying to find a way to replace Keycloak image on the Admin console page using Keycloak.v2 theme which is the default theme starting from Keycloak 19.</p>
<p>Note that replacing <code>themes\keycloak.v2\account\resources\public\logo.svg</code> didn't really help.</p>
|
[
{
"answer_id": 74610065,
"author": "Jensd",
"author_id": 2189922,
"author_profile": "https://Stackoverflow.com/users/2189922",
"pm_score": 1,
"selected": false,
"text": "def temp-table ttMsgHdr no-undo serialize-name \"MessageHeader\"\n field MsgId as char serialize-name \"MessageId\"\n field MsgFrom as char serialize-name \"From\"\n field MsgTo as char serialize-name \"To\"\n field PlantId as char serialize-name \"PlantId\".\n\ndef dataset dsONE namespace-url \"http://API.JOEJANE.Envelope\" \n namespace-prefix \"ns1\" xml-node-name \"Message\" for ttMsgHdr.\n"
},
{
"answer_id": 74615956,
"author": "Stefan Drissen",
"author_id": 2292276,
"author_profile": "https://Stackoverflow.com/users/2292276",
"pm_score": 0,
"selected": false,
"text": "ns1 def temp-table tt no-undo serialize-name 'MessageHeader'\n field cId as char serialize-name 'MessageId'\n field cFrom as char serialize-name 'From'\n field cTo as char serialize-name 'To'\n field cPlantId as char serialize-name 'PlantId'\n .\n\ndef dataset ds serialize-name 'Message'\n for tt\n .\n\ndataset ds:read-xml( 'file', 'my.xml', ?, ?, ? ).\n\nfind first tt.\nmessage tt.cID.\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74607048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4582691/"
] |
74,607,052
|
<p>The problem is that I'm processing some UTF8 strings and I would like to design a class or a way to prevent string manipulations.</p>
<p>String manipulation is not desirable for strings of multibyte characters as splitting the string at a random position (which is measured in bytes) may split a character half way.</p>
<p>I have thought about using <code>const std::string&</code> but the user/developer can create a substring by calling <code>std::substr</code>.</p>
<p>Another way would be create a wrapper around <code>const std::string&</code> and expose only the string through getters.</p>
<p>Is this even possible?</p>
|
[
{
"answer_id": 74610065,
"author": "Jensd",
"author_id": 2189922,
"author_profile": "https://Stackoverflow.com/users/2189922",
"pm_score": 1,
"selected": false,
"text": "def temp-table ttMsgHdr no-undo serialize-name \"MessageHeader\"\n field MsgId as char serialize-name \"MessageId\"\n field MsgFrom as char serialize-name \"From\"\n field MsgTo as char serialize-name \"To\"\n field PlantId as char serialize-name \"PlantId\".\n\ndef dataset dsONE namespace-url \"http://API.JOEJANE.Envelope\" \n namespace-prefix \"ns1\" xml-node-name \"Message\" for ttMsgHdr.\n"
},
{
"answer_id": 74615956,
"author": "Stefan Drissen",
"author_id": 2292276,
"author_profile": "https://Stackoverflow.com/users/2292276",
"pm_score": 0,
"selected": false,
"text": "ns1 def temp-table tt no-undo serialize-name 'MessageHeader'\n field cId as char serialize-name 'MessageId'\n field cFrom as char serialize-name 'From'\n field cTo as char serialize-name 'To'\n field cPlantId as char serialize-name 'PlantId'\n .\n\ndef dataset ds serialize-name 'Message'\n for tt\n .\n\ndataset ds:read-xml( 'file', 'my.xml', ?, ?, ? ).\n\nfind first tt.\nmessage tt.cID.\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74607052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/586981/"
] |
74,607,063
|
<p>I have a dataframe 'df1' with a lot of columns, but the ones of interest are:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Number</th>
<th>Code</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td></td>
</tr>
<tr>
<td>2</td>
<td></td>
</tr>
<tr>
<td>3</td>
<td></td>
</tr>
<tr>
<td>10</td>
<td></td>
</tr>
<tr>
<td>11</td>
<td>AMRO</td>
</tr>
<tr>
<td>4</td>
<td></td>
</tr>
<tr>
<td>277</td>
<td></td>
</tr>
<tr>
<td>2100</td>
<td>BLPH</td>
</tr>
</tbody>
</table>
</div>
<p>And I have another dataframe 'df2' with a lot of columns, but the ones of interest are:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Number</th>
<th>Code</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>AMCR</td>
</tr>
<tr>
<td>2</td>
<td>AMCR</td>
</tr>
<tr>
<td>3</td>
<td>BANO</td>
</tr>
<tr>
<td>10</td>
<td>BAEA</td>
</tr>
<tr>
<td>12</td>
<td>AMRO</td>
</tr>
<tr>
<td>4</td>
<td>NA</td>
</tr>
<tr>
<td>277</td>
<td>NA</td>
</tr>
<tr>
<td>2100</td>
<td>NA</td>
</tr>
</tbody>
</table>
</div>
<p>I want matching values in the 'Number' columns of 'df1' and 'df2' to lead to values in the 'Code' column in 'df2' to overwrite the 'Code' values in 'df1' as long as the 'Code' values in 'df2' don't contain an NA, so that the final result of 'df1' looks like:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Number</th>
<th>Code</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>AMCR</td>
</tr>
<tr>
<td>2</td>
<td>AMCR</td>
</tr>
<tr>
<td>3</td>
<td>BANO</td>
</tr>
<tr>
<td>10</td>
<td>BAEA</td>
</tr>
<tr>
<td>11</td>
<td>AMRO</td>
</tr>
<tr>
<td>4</td>
<td></td>
</tr>
<tr>
<td>277</td>
<td></td>
</tr>
<tr>
<td>2100</td>
<td>BLPH</td>
</tr>
</tbody>
</table>
</div>
<p>Thank you for your help!</p>
|
[
{
"answer_id": 74607172,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 3,
"selected": true,
"text": "library(powerjoin)\npower_left_join(df1, df2, by = \"Number\", conflict = coalesce)\n Number Code\n1 1 AMCR\n2 2 AMCR\n3 3 BANO\n4 10 BAEA\n5 11 AMRO\n6 4 <NA>\n7 277 <NA>\n8 2100 BLPH\n data.table library(data.table)\nsetDT(df1)[df2, Code := fcoalesce(Code, i.Code), on = .(Number)]\n > df1\n Number Code\n <int> <char>\n1: 1 AMCR\n2: 2 AMCR\n3: 3 BANO\n4: 10 BAEA\n5: 11 AMRO\n6: 4 <NA>\n7: 277 <NA>\n8: 2100 BLPH\n df1 <- structure(list(Number = c(1L, 2L, 3L, 10L, 11L, 4L, 277L, 2100L\n), Code = c(NA, NA, NA, NA, \"AMRO\", NA, NA, \"BLPH\")), \nclass = \"data.frame\", row.names = c(NA, \n-8L))\n\ndf2 <- structure(list(Number = c(1L, 2L, 3L, 10L, 12L, 4L, 277L, 2100L\n), Code = c(\"AMCR\", \"AMCR\", \"BANO\", \"BAEA\", \"AMRO\", NA, NA, NA\n)), class = \"data.frame\", row.names = c(NA, -8L))\n"
},
{
"answer_id": 74607239,
"author": "TarJae",
"author_id": 13321647,
"author_profile": "https://Stackoverflow.com/users/13321647",
"pm_score": 1,
"selected": false,
"text": "bind_cols library(dplyr)\n\nbind_cols(df1, df2) %>% \n mutate(Code = coalesce(Code...2, Code...4)) %>% \n select(Number = Number...1, Code)\n\n Number Code\n1 1 AMCR\n2 2 AMCR\n3 3 BANO\n4 10 BAEA\n5 11 AMRO\n6 4 <NA>\n7 277 <NA>\n8 2100 BLPH\n"
},
{
"answer_id": 74607472,
"author": "Ruam Pimentel",
"author_id": 13015865,
"author_profile": "https://Stackoverflow.com/users/13015865",
"pm_score": 1,
"selected": false,
"text": "dplyr full_join inner_join library(dplyr)\n df1 %>% \n full_join(df2) %>% na.omit() %>% \n full_join(df1 %>% inner_join(df2)) %>% \n filter(Number %in% df1$Number) %>%\n arrange(Number)\n \n#> Number Code\n#> 1 1 AMCR\n#> 2 2 AMCR\n#> 3 3 BANO\n#> 4 4 <NA>\n#> 5 10 BAEA\n#> 6 11 AMRO\n#> 7 277 <NA>\n#> 8 2100 BLPH\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74607063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7238688/"
] |
74,607,071
|
<p>I seem to be having an issue displaying the fontawesome icon in my browser. It does show in inspect, but not on my website itself.</p>
<p>Does anyone know how to resolve this issue?</p>
<pre><code>import React, { Fragment, useState} from "react";
import { NavLink } from "react-router-dom";
import "../styles/common/Navbar.css";
const Navbar = () => {
const [showMenu, setShowMenu] = useState(false);
return (
<Fragment>
<nav>
<a href="/">
<h1>AnRa<span>Caribbean</span></h1>
</a>
<div className={showMenu ? "menu mobile-menu" : "menu"}>
<ul>
<li><NavLink to="/">Home</NavLink></li>
<li><NavLink to="/PropertiesForSale">Buy a Property</NavLink></li>
<li><NavLink to="/PropertiesForRent">Rent a Property</NavLink></li>
<li><NavLink to="/About">About</NavLink></li>
<li><NavLink to="/Contact">Contact</NavLink></li>
</ul>
<button className="btn">
<NavLink to="#">Add Property</NavLink>
</button>
</div>
<i className="fa fa-solid fa-bars" onClick={() => setShowMenu(!showMenu)}></i>
</nav>
</Fragment>
);
}
export default Navbar;
</code></pre>
<p><a href="https://i.stack.imgur.com/NHa49.png" rel="nofollow noreferrer">Web view</a></p>
<p>How I have it in css from max-width screen.</p>
<pre><code>.fa-bars{
display: flex;
color: gold;
}
</code></pre>
<p>Thank you in advance</p>
<ol>
<li>downloaded</li>
</ol>
<pre><code>npm i --save @fortawesome/fontawesome-svg-core
npm install --save @fortawesome/free-solid-svg-icons
</code></pre>
<p>Still nothing.</p>
<ol start="2">
<li>tried deleting nodemodules.</li>
<li>restarted the application.</li>
</ol>
<p>Nothing seems to work.</p>
|
[
{
"answer_id": 74607109,
"author": "Jay F.",
"author_id": 20504019,
"author_profile": "https://Stackoverflow.com/users/20504019",
"pm_score": 3,
"selected": true,
"text": "import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'\nimport { faCoffee } from '@fortawesome/free-solid-svg-icons'\n\nconst App = () => {\n return (<div><FontAwesomeIcon icon={faCoffee} /></div>)\n}\n\nexport default App\n"
},
{
"answer_id": 74607250,
"author": "Alexey Zalyotov",
"author_id": 11750723,
"author_profile": "https://Stackoverflow.com/users/11750723",
"pm_score": 1,
"selected": false,
"text": "FontAwesomeIcon <FontAwesomeIcon icon={faBars} />\n import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';\nimport { faBars } from '@fortawesome/free-solid-svg-icons';\n\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74607071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20627647/"
] |
74,607,140
|
<p>I would like that a JavaScript function could take a random sentence from a datalist in the same file, and then show it when I click on a button with an "onclick" event. I am looking for the easiest way to do that. Does anyone have an example?</p>
<p>(Just looking around, trying JavaScript for the first time)</p>
|
[
{
"answer_id": 74607310,
"author": "DCR",
"author_id": 4398966,
"author_profile": "https://Stackoverflow.com/users/4398966",
"pm_score": 1,
"selected": false,
"text": "let dataList =[\"sentence 1\",\"sentence 2\",\"sentence 3\",\"sentence 4\"]\nlet div = document.getElementById('asd')\ndocument.getElementsByTagName(\"button\")[0].addEventListener(\"click\",myFunc)\n\nfunction myFunc(){\n let x = parseInt(Math.random()* dataList.length )\n div.innerHTML = dataList[x]\n} <button>click me</button>\n<div id='asd'></div>"
},
{
"answer_id": 74607664,
"author": "yessir",
"author_id": 18591002,
"author_profile": "https://Stackoverflow.com/users/18591002",
"pm_score": 0,
"selected": false,
"text": "parseInt() Math.random()*n var yourDataList = [\"Option 1\", \"Option 2\", \"Option 3\"]; // Define datalist\nvar myBtn = document.getElementById(\"yourIdHere\"); //Declare button, replace yourIdHere with your ID\nvar randomNum = 0; //Decclre random number\nfunction getRandom() { //Declare your function\n randomNum = parseInt(Math.random() * yourDataList.length); //Get random number between 0 and the length of your datalist\n return yourDataList[randomNum]; //Return your value\n}\nmyBtn.addEventListener(\"click\", function() { //Bind a listener to the button\n alert(getRandom()); //Do whatever you want to with the random value\n}); <button id = \"yourIdHere\">Click me!!</button> <datalist> var yourDataList = document.getElementById(\"datalist\"); // Define datalist\nvar myInput = document.getElementById(\"myInput\");\nvar dataListOptionsElems = yourDataList.querySelectorAll(\"option\");//Get all options elements\nvar dataListOptions = [];//Declare options\nfor(var i = 0;i<dataListOptionsElems.length;i++){\ndataListOptions.push(dataListOptionsElems[i].value);\n}\nvar myBtn = document.getElementById(\"yourIdHere\"); //Declare button, replace yourIdHere with your ID\nvar randomNum = 0; //Declare random number\nfunction getRandom() { //Declare your function\n randomNum = parseInt(Math.random() * dataListOptions.length); //Get random number between 0 and the length of your datalist\n return dataListOptions[randomNum]; //Return your value\n}\nmyBtn.addEventListener(\"click\", function() { //Bind a listener to the button\n alert(getRandom());\n console.log(getRandom());\n myInput.value = getRandom();\n //Do whatever you want to with the random value\n}); <button id = \"yourIdHere\">Click me!!</button>\n <input list=\"datalist\" id=\"myInput\">\n <datalist id=\"datalist\">\n <option value=\"Option1\">\n <option value=\"Option2\">\n <option value=\"Option3\">\n <option value=\"Option4\">\n <option value=\"Option5\">\n </datalist>\n<p>Note: the alert box, console message, and input value will not be the same, due to it being random each time the function is called.</p>"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74607140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19899760/"
] |
74,607,150
|
<p>I am being passed this, 2022-11-01T00:00:00, Date Time as a string. I need to convert it to a DateTime in C# but cannot seem to figure out what exact format the string is in.</p>
<p>I have tried many variations of the following but continue to get String was not recognized as a valid DateTime.</p>
<p>Here is the latest code I have tried:</p>
<pre><code>DateTime test = DateTime.ParseExact(startTime, "yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture);
</code></pre>
<p>This appears to be with how the data is being sent to my software. I tried the suggestions below but am still receiving the same error message.</p>
|
[
{
"answer_id": 74607310,
"author": "DCR",
"author_id": 4398966,
"author_profile": "https://Stackoverflow.com/users/4398966",
"pm_score": 1,
"selected": false,
"text": "let dataList =[\"sentence 1\",\"sentence 2\",\"sentence 3\",\"sentence 4\"]\nlet div = document.getElementById('asd')\ndocument.getElementsByTagName(\"button\")[0].addEventListener(\"click\",myFunc)\n\nfunction myFunc(){\n let x = parseInt(Math.random()* dataList.length )\n div.innerHTML = dataList[x]\n} <button>click me</button>\n<div id='asd'></div>"
},
{
"answer_id": 74607664,
"author": "yessir",
"author_id": 18591002,
"author_profile": "https://Stackoverflow.com/users/18591002",
"pm_score": 0,
"selected": false,
"text": "parseInt() Math.random()*n var yourDataList = [\"Option 1\", \"Option 2\", \"Option 3\"]; // Define datalist\nvar myBtn = document.getElementById(\"yourIdHere\"); //Declare button, replace yourIdHere with your ID\nvar randomNum = 0; //Decclre random number\nfunction getRandom() { //Declare your function\n randomNum = parseInt(Math.random() * yourDataList.length); //Get random number between 0 and the length of your datalist\n return yourDataList[randomNum]; //Return your value\n}\nmyBtn.addEventListener(\"click\", function() { //Bind a listener to the button\n alert(getRandom()); //Do whatever you want to with the random value\n}); <button id = \"yourIdHere\">Click me!!</button> <datalist> var yourDataList = document.getElementById(\"datalist\"); // Define datalist\nvar myInput = document.getElementById(\"myInput\");\nvar dataListOptionsElems = yourDataList.querySelectorAll(\"option\");//Get all options elements\nvar dataListOptions = [];//Declare options\nfor(var i = 0;i<dataListOptionsElems.length;i++){\ndataListOptions.push(dataListOptionsElems[i].value);\n}\nvar myBtn = document.getElementById(\"yourIdHere\"); //Declare button, replace yourIdHere with your ID\nvar randomNum = 0; //Declare random number\nfunction getRandom() { //Declare your function\n randomNum = parseInt(Math.random() * dataListOptions.length); //Get random number between 0 and the length of your datalist\n return dataListOptions[randomNum]; //Return your value\n}\nmyBtn.addEventListener(\"click\", function() { //Bind a listener to the button\n alert(getRandom());\n console.log(getRandom());\n myInput.value = getRandom();\n //Do whatever you want to with the random value\n}); <button id = \"yourIdHere\">Click me!!</button>\n <input list=\"datalist\" id=\"myInput\">\n <datalist id=\"datalist\">\n <option value=\"Option1\">\n <option value=\"Option2\">\n <option value=\"Option3\">\n <option value=\"Option4\">\n <option value=\"Option5\">\n </datalist>\n<p>Note: the alert box, console message, and input value will not be the same, due to it being random each time the function is called.</p>"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74607150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3728381/"
] |
74,607,211
|
<p>I have a problem trying to delete data by providing an array of id's (got error).
I guess it has something to do with ObjectId. Could you help me fix it?</p>
<pre><code>User.deleteMany({
_id: { $in: ['638207a8b9ebc3ea8f276684',
'63823ffe310abc61b4ee11a0',
'63822a71319517d196af6d59' }
})
.then(() => res.status(200).json({ success }))
.catch(error => console.error('Error deleting users'))
</code></pre>
<p>I tried to map this array to prepend every item of it with ObjectId but got ObjectId is not found.</p>
|
[
{
"answer_id": 74607310,
"author": "DCR",
"author_id": 4398966,
"author_profile": "https://Stackoverflow.com/users/4398966",
"pm_score": 1,
"selected": false,
"text": "let dataList =[\"sentence 1\",\"sentence 2\",\"sentence 3\",\"sentence 4\"]\nlet div = document.getElementById('asd')\ndocument.getElementsByTagName(\"button\")[0].addEventListener(\"click\",myFunc)\n\nfunction myFunc(){\n let x = parseInt(Math.random()* dataList.length )\n div.innerHTML = dataList[x]\n} <button>click me</button>\n<div id='asd'></div>"
},
{
"answer_id": 74607664,
"author": "yessir",
"author_id": 18591002,
"author_profile": "https://Stackoverflow.com/users/18591002",
"pm_score": 0,
"selected": false,
"text": "parseInt() Math.random()*n var yourDataList = [\"Option 1\", \"Option 2\", \"Option 3\"]; // Define datalist\nvar myBtn = document.getElementById(\"yourIdHere\"); //Declare button, replace yourIdHere with your ID\nvar randomNum = 0; //Decclre random number\nfunction getRandom() { //Declare your function\n randomNum = parseInt(Math.random() * yourDataList.length); //Get random number between 0 and the length of your datalist\n return yourDataList[randomNum]; //Return your value\n}\nmyBtn.addEventListener(\"click\", function() { //Bind a listener to the button\n alert(getRandom()); //Do whatever you want to with the random value\n}); <button id = \"yourIdHere\">Click me!!</button> <datalist> var yourDataList = document.getElementById(\"datalist\"); // Define datalist\nvar myInput = document.getElementById(\"myInput\");\nvar dataListOptionsElems = yourDataList.querySelectorAll(\"option\");//Get all options elements\nvar dataListOptions = [];//Declare options\nfor(var i = 0;i<dataListOptionsElems.length;i++){\ndataListOptions.push(dataListOptionsElems[i].value);\n}\nvar myBtn = document.getElementById(\"yourIdHere\"); //Declare button, replace yourIdHere with your ID\nvar randomNum = 0; //Declare random number\nfunction getRandom() { //Declare your function\n randomNum = parseInt(Math.random() * dataListOptions.length); //Get random number between 0 and the length of your datalist\n return dataListOptions[randomNum]; //Return your value\n}\nmyBtn.addEventListener(\"click\", function() { //Bind a listener to the button\n alert(getRandom());\n console.log(getRandom());\n myInput.value = getRandom();\n //Do whatever you want to with the random value\n}); <button id = \"yourIdHere\">Click me!!</button>\n <input list=\"datalist\" id=\"myInput\">\n <datalist id=\"datalist\">\n <option value=\"Option1\">\n <option value=\"Option2\">\n <option value=\"Option3\">\n <option value=\"Option4\">\n <option value=\"Option5\">\n </datalist>\n<p>Note: the alert box, console message, and input value will not be the same, due to it being random each time the function is called.</p>"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74607211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12808136/"
] |
74,607,247
|
<p>I had a CS question that wants me to check for the number of palindromes found inside a single array of 6 cells. i was able to solve it by using many for loops, 7 of them to be exact, and I'm trying to find a way to make the code tidier by reducing the number of loops because they all do similar things with minor differences but i wasn't able to put a finger on the best idea to reduce them.</p>
<p>this my code:</p>
<pre><code>int main()
{
int size = 6;
int array[size];
int palCount = 0;
for (int i = 0; i < size; i++)
{
cin >> array[i];
}
bool isPal = true;
int size2 = 2;
for (int i = 1; i <= 6; i++)
{
int currentNum = array[i];
int numAfter = array[i + 1];
int arrToCheck[] = {currentNum, numAfter};
isPal = checkPalindrom(arrToCheck, size2);
if (isPal)
{
palCount++;
}
}
int size3 = 3;
for (int i = 1; i <= 6; i++)
{
int currentNum = array[i];
int numAfter = array[i + 1];
int numAfter2 = array[i + 2];
int arrToCheck[] = {currentNum, numAfter, numAfter2};
isPal = checkPalindrom(arrToCheck, size3);
if (isPal)
{
palCount++;
}
}
int size4 = 4;
for (int i = 1; i <= 6; i++)
{
int currentNum = array[i];
int numAfter = array[i + 1];
int numAfter2 = array[i + 2];
int numAfter3 = array[i + 3];
int arrToCheck[] = {currentNum, numAfter, numAfter2, numAfter3};
isPal = checkPalindrom(arrToCheck, size4);
if (isPal)
{
palCount++;
}
}
int size5 = 5;
for (int i = 1; i <= 6; i++)
{
int currentNum = array[i];
int numAfter = array[i + 1];
int numAfter2 = array[i + 2];
int numAfter3 = array[i + 3];
int numAfter4 = array[i + 4];
int arrToCheck[] = {currentNum, numAfter, numAfter2, numAfter3, numAfter4};
isPal = checkPalindrom(arrToCheck, size5);
if (isPal)
{
palCount++;
}
}
//================================================================
for (int i = 2; i <= 6; i++)
{
int currentNum = array[i];
int numAfter = array[i + 1];
int arrToCheck[] = {currentNum, numAfter};
isPal = checkPalindrom(arrToCheck, size2);
if (isPal)
{
palCount++;
}
}
for (int i = 2; i <= 6; i++)
{
int currentNum = array[i];
int numAfter = array[i + 1];
int numAfter2 = array[i + 2];
int arrToCheck[] = {currentNum, numAfter, numAfter2};
isPal = checkPalindrom(arrToCheck, size3);
if (isPal)
{
palCount++;
}
}
for (int i = 2; i <= 6; i++)
{
int currentNum = array[i];
int numAfter = array[i + 1];
int numAfter2 = array[i + 2];
int numAfter3 = array[i + 3];
int arrToCheck[] = {currentNum, numAfter, numAfter2, numAfter3};
isPal = checkPalindrom(arrToCheck, size4);
if (isPal)
{
palCount++;
}
}
cout << palCount - 1 << endl;
}
</code></pre>
<p>in case anyone wants to try the code, this is the code of the function that checks for palindromes:</p>
<pre><code>bool checkPalindrom(int arr[], int sizeOfArray)
{
int size = sizeOfArray;
bool pal = true;
for (int i = 0; i < size / 2; i++)
{
if (arr[i] != arr[size - 1 - i])
{
pal = false;
}
}
return pal;
}
</code></pre>
<p>the differences between each loop that it starts with 2 elemts then 3 then 4... the arrayToCheck variable is the one that's changing between each loop and also the variable size.</p>
<p>im open to any ideas on how to reduce the number of loops while keeping the same functionality.thanks.</p>
<p>expected:</p>
<pre><code>input: 1 1 1 1 1 1
output: 15
</code></pre>
<pre><code>input: 1 2 2 1 5 5
output: 3
</code></pre>
|
[
{
"answer_id": 74607422,
"author": "lorro",
"author_id": 6292621,
"author_profile": "https://Stackoverflow.com/users/6292621",
"pm_score": -1,
"selected": false,
"text": "checkPalindrom() checkPalindrom(array + i, size_i); auto checker = [&](int size_i, int i_min, int i_max) {\n for (int i = i_min; i <= i_max && i + size_i <= size; i++)\n {\n isPal = checkPalindrom(array + i, size_i);\n\n if (isPal)\n {\n palCount++;\n }\n }\n for (int i_min = 1; i_min <= 2; ++i_min) {\n for (int size_i = 2; size_i + i_min < size; ++size_i) {\n checker(i_min, 6, size_i);\n }\n}\n size_t"
},
{
"answer_id": 74607657,
"author": "Ranoiaetep",
"author_id": 12861639,
"author_profile": "https://Stackoverflow.com/users/12861639",
"pm_score": 0,
"selected": false,
"text": "int size4 = 4;\nfor (int i = 2; i <= 6; i++)\n{\n int currentNum = array[i];\n int numAfter = array[i + 1];\n int numAfter2 = array[i + 2];\n int numAfter3 = array[i + 3];\n\n int arrToCheck[] = {currentNum, numAfter, numAfter2, numAfter3};\n isPal = checkPalindrom(arrToCheck, size4);\n\n if (isPal)\n {\n palCount++;\n }\n}\n i i + 3 array arrToCheck checkPalindrom array + i for (int i = 2; i < 3; ++i) {\n isPal = checkPalindrom(array + i, size4);\n if (isPal)\n {\n ++palCount;\n }\n}\n sizeX for (int i = 1; i < 5; ++i) { ... size2 ... }\nfor (int i = 1; i < 4; ++i) { ... size3 ... }\nfor (int i = 1; i < 3; ++i) { ... size4 ... }\nfor (int i = 1; i < 2; ++i) { ... size5 ... }\n\nfor (int i = 2; i < 5; ++i) { ... size2 ... }\nfor (int i = 2; i < 4; ++i) { ... size3 ... }\nfor (int i = 2; i < 3; ++i) { ... size4 ... }\n sizeX for (int i = 1; i < 3; ++i) {\n for (int j = size - 1; j > i; --j) {\n ... size - j + 1 ...\n }\n}\n i j checkPalindrom checkPalindrom(array + i, j)\n i 0 5"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74607247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14387127/"
] |
74,607,259
|
<ul>
<li>Was trying to deploy my vue/vite project onto github pages and use a custom domain, but ran into some issues and messed things up by using git commands I didn't fully understand</li>
<li>The deployed project worked before I tried adding a custom domain</li>
<li>Followed instructions from the following video to deploy a vite project onto github pages: <a href="https://youtu.be/yo2bMGnIKE8" rel="nofollow noreferrer">https://youtu.be/yo2bMGnIKE8</a></li>
<li>Followed instructions from here to add custom namecheap domain: <a href="https://youtu.be/2K7asqt8wMw" rel="nofollow noreferrer">https://youtu.be/2K7asqt8wMw</a></li>
</ul>
<ol>
<li>npm run build,</li>
<li>git add dist -f</li>
<li>git commit -m "adding dist"</li>
<li>git subtree push --prefix dist origin gh-pages
// [rejected] error: failed to push some refs to 'url', hint: Updates were rejected because the remote contains work that you do not have locally. This is usually caused by another repository pushing to the same ref. You may want to first integrate the remote changes (e.g.,) 'git pull ...') before pushing again.</li>
<li>git pull</li>
<li>git subtree push --prefix dist origin gh-pages
// [rejected] error: failed to push some refs to 'url', hint: Updates were rejected because a pushed branch tip is behind its remote counterpart. Check out this branch and integrate the remote changes (e.g. 'git pull ...') before pushing again.</li>
<li>git status: On branch main, Your branch is ahead of 'origin/main' by 11 commits. (use "git push" to publish your local commits)</li>
<li>git push</li>
<li>git status: Your branch is up to date with 'origin/main.'</li>
<li>git subtree push --prefix dist origin gh-pages
// [rejected] error: failed to push some refs to 'url', hint: Updates were rejected because a pushed branch tip is behind its remote counterpart. Check out this branch and integrate the remote changes (e.g. 'git pull ...') before pushing again.</li>
<li>git pull origin main</li>
<li>git pull origin gh-pages</li>
<li>git pull --rebase origin gh-pages
// lost all of my local files and reverted to initial project scaffolding from vue/vite</li>
<li>Now I'm here panicking and still without a deployed project :)</li>
</ol>
<p>link to github:
<a href="https://github.com/AnthonyVNgo/LearnFS" rel="nofollow noreferrer">https://github.com/AnthonyVNgo/LearnFS</a></p>
<p>Tried a bunch of git commands and followed the hint responses, but dug myself into a deeper hole.</p>
|
[
{
"answer_id": 74607990,
"author": "tymtam",
"author_id": 581076,
"author_profile": "https://Stackoverflow.com/users/581076",
"pm_score": 2,
"selected": false,
"text": "git reflog git checkout the_id_shown_in_git_reflog git checkout 100e500bd git reflog -> git checkout git checkout -b my_lost_work git push main gh-pages"
},
{
"answer_id": 74608762,
"author": "LeGEC",
"author_id": 86072,
"author_profile": "https://Stackoverflow.com/users/86072",
"pm_score": 0,
"selected": false,
"text": "git stash show\ngit stash list\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74607259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20189924/"
] |
74,607,292
|
<p>My problem is that I have a table with data like this -</p>
<pre><code>ID COLORS
--------------------------------------------
1 ["red", "green"]
2 ["blue", "red"]
3 ["red", "green", "yellow", "blue"]
</code></pre>
<p>What SQL witchcraft will I need to wield in order to create a result like that? -</p>
<pre><code>COLOR COUNT
--------------------------------------------
red 3
blue 2
green 2
yellow 1
</code></pre>
<p>Is it even possible with either a SP or View?</p>
<p>Thank you!</p>
|
[
{
"answer_id": 74607368,
"author": "Adrian Klaver",
"author_id": 7070613,
"author_profile": "https://Stackoverflow.com/users/7070613",
"pm_score": 1,
"selected": false,
"text": "create table color_test (id integer, colors text[]);\n\ninsert into color_test values (1, ARRAY['red', 'green']), (2, ARRAY['blue', 'red']), (3, ARRAY['red', 'green', 'yellow', 'blue']);\n\nselect color, count(color) from color_test, unnest(colors) as color group by color;\n\n color | count \n--------+-------\n red | 3\n blue | 2\n green | 2\n yellow | 1\n\n"
},
{
"answer_id": 74607375,
"author": "Ajax1234",
"author_id": 7326738,
"author_profile": "https://Stackoverflow.com/users/7326738",
"pm_score": 3,
"selected": true,
"text": "cross join count(*) select v.value#>>'{}', count(*) cnt \nfrom tbl t \n cross join jsonb_array_elements(t.colors) v\ngroup by v.value#>>'{}' \norder by cnt desc\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74607292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4983051/"
] |
74,607,300
|
<p>I have a class whose ctor makes a driver call, and whose dtor makes the matching terminating/release driver call. Those calls can fail. The problem is naturally with the dtor.</p>
<p>I am naturally aware of the common wisdom of avoiding exceptions in dtors, since, if you throw one during stack unwinding, you get <code>std::terminate</code>. But - I would rather not just "swallow" such errors and fail to report them - if I can. So, is it legitimate/idiomatic to write code saying:</p>
<pre><code>~MyClass() noexcept(false) {
auto result = something_which_may_fail_but_wont_throw();
if (std::uncaught_exceptions() == 0) {
throw some_exception(result);
}
}
</code></pre>
<p>Or is this just baroque and not a good idea?</p>
<p>Note: This class does not have access to the standard output/error streams, nor a log etc.</p>
|
[
{
"answer_id": 74608039,
"author": "Brian Bi",
"author_id": 481267,
"author_profile": "https://Stackoverflow.com/users/481267",
"pm_score": 3,
"selected": false,
"text": "uncaught_exceptions() struct X {\n ~X() noexcept(false) {\n if (std::uncaught_exceptions() == 0) throw FooException{};\n }\n};\n\nstruct Y {\n ~Y() {\n try {\n X x;\n } catch (const FooException&) {\n // handle exception\n }\n }\n};\n\nint main() {\n try {\n Y y;\n throw BarException{};\n } catch (const BarException&) {\n // handle \n }\n}\n y Y X FooException FooException std::terminate X::~X Y::~Y Y::~Y X::~X std::uncaught_exceptions uncaught_exceptions uncaught_exceptions X::X() std::uncaught_exceptions() std::uncaught_exceptions()"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74607300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1593077/"
] |
74,607,305
|
<p>I have a country field and a state field. I want to show the state field when the user chooses United States. Otherwise, I want it to be hidden.</p>
<p>This is my cshtml page of the form.</p>
<pre><code><div class="form-group col-sm-4 mt-4">
<label asp-for="Form.Country" class="control-label"></label>
<select asp-for="Form.Country" class="form-control">
<option disabled selected>Choose your Country</option>
<option>Canada</option>
<option>United States</option>
<option>Mexico</option>
</select>
<span asp-validation-for="Form.Country" class="text-danger"></span>
</div>
<div class="form-group col-sm-4 mt-4">
<label asp-for="Form.State" class="control-label"></label>
<select asp-for="Form.State" asp-items="Model.States" class="form-select">
<option disabled selected>Choose your State</option>
</select>
<span asp-validation-for="Form.State" class="text-danger"></span>
</div>
<div class="form-group col-sm-4 mt-4">
<label asp-for="Form.City" class="control-label"></label>
<input asp-for="Form.City" class="form-control" />
<span asp-validation-for="Form.City" class="text-danger"></span>
</div>
</code></pre>
<p>I tried searching for a solution, but most involve using JS which I don't know and don't want to use now.</p>
<p>I know razor is server side code, but maybe I can integrate a blazor component or use css to achieve this.</p>
|
[
{
"answer_id": 74607531,
"author": "Kevon",
"author_id": 766684,
"author_profile": "https://Stackoverflow.com/users/766684",
"pm_score": 0,
"selected": false,
"text": "@if (Form.Country == \"UnitedStates\")\n{\n MARKUP FOR STATE DROPDOWN\n}\n"
},
{
"answer_id": 74609671,
"author": "Xinran Shen",
"author_id": 17438579,
"author_profile": "https://Stackoverflow.com/users/17438579",
"pm_score": 2,
"selected": true,
"text": "onchange() <select asp-for=\"Form.Country\" class=\"form-control\" onchange=\"Select()\">\n <div class=\"form-group col-sm-4 mt-4\" id=\"demo\">\n .........\n</div>\n @section scripts\n{\n <script>\n function Select(){\n //get the element by id\n var select = document.getElementById(\"Form_Country\");\n //get the option's text\n var index = select.selectedIndex;\n var text = select.options[index].text;\n //if option's text is not United States, hide the second dropdownlist.\n if(text!=\"United States\"){\n //hiden the dropdownlist\n document.getElementById(\"demo\").style.display='none';\n }else{\n //show the dropdownlist\n document.getElementById(\"demo\").style.display='block';\n }\n }\n </script>\n}\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74607305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20517307/"
] |
74,607,331
|
<p>When I try to access the About page from the menu, I get a 404 error from the server.</p>
<p>I tried changing the relative paths. and I switched to HashRouter in the index.jsx BrowserRouter. I also tried to include routes in app.js with HashRouter</p>
<p>github repo
<a href="https://github.com/brunoBaumgartnerNiederbipp/oihawa" rel="nofollow noreferrer">https://github.com/brunoBaumgartnerNiederbipp/oihawa</a></p>
<p>github pages
<a href="https://brunobaumgartnerniederbipp.github.io/oihawa/" rel="nofollow noreferrer">https://brunobaumgartnerniederbipp.github.io/oihawa/</a></p>
|
[
{
"answer_id": 74607531,
"author": "Kevon",
"author_id": 766684,
"author_profile": "https://Stackoverflow.com/users/766684",
"pm_score": 0,
"selected": false,
"text": "@if (Form.Country == \"UnitedStates\")\n{\n MARKUP FOR STATE DROPDOWN\n}\n"
},
{
"answer_id": 74609671,
"author": "Xinran Shen",
"author_id": 17438579,
"author_profile": "https://Stackoverflow.com/users/17438579",
"pm_score": 2,
"selected": true,
"text": "onchange() <select asp-for=\"Form.Country\" class=\"form-control\" onchange=\"Select()\">\n <div class=\"form-group col-sm-4 mt-4\" id=\"demo\">\n .........\n</div>\n @section scripts\n{\n <script>\n function Select(){\n //get the element by id\n var select = document.getElementById(\"Form_Country\");\n //get the option's text\n var index = select.selectedIndex;\n var text = select.options[index].text;\n //if option's text is not United States, hide the second dropdownlist.\n if(text!=\"United States\"){\n //hiden the dropdownlist\n document.getElementById(\"demo\").style.display='none';\n }else{\n //show the dropdownlist\n document.getElementById(\"demo\").style.display='block';\n }\n }\n </script>\n}\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74607331",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20627755/"
] |
74,607,334
|
<p>Spotify's lyrics API provides an Array of miliseconds to mark when the lyric line has changed. Having a Media Player that updates it's position every 50ms, how should i code in Kotlin the way to find the correct lyric line? The position param can be in the middle of two values of the array, so I want to get the lowest one of that two.</p>
<p>I tried to get the lowest value compared to the position parameter but lol, it will always be the first value of the Array... Silly fault of mine.</p>
|
[
{
"answer_id": 74607370,
"author": "SerjantArbuz",
"author_id": 7699617,
"author_profile": "https://Stackoverflow.com/users/7699617",
"pm_score": 0,
"selected": false,
"text": "min Kotlin"
},
{
"answer_id": 74607428,
"author": "Atick Faisal",
"author_id": 12737399,
"author_profile": "https://Stackoverflow.com/users/12737399",
"pm_score": 1,
"selected": false,
"text": "\n val array: MutableList<Long> = mutableListOf(4L, 9L, 5L, 1L)\n val position = 7L\n \n array.add(position)\n println(array[array.sorted().indexOf(position) - 1])\n\n"
},
{
"answer_id": 74608974,
"author": "Tenfour04",
"author_id": 506796,
"author_profile": "https://Stackoverflow.com/users/506796",
"pm_score": 0,
"selected": false,
"text": "val foundIndex = lyricTimesList.indexOfFirst { it > inputTime }\nval result = if (foundIndex == -1) lyricTimesList.size - 1 else foundIndex - 1\n"
},
{
"answer_id": 74610816,
"author": "SerjantArbuz",
"author_id": 7699617,
"author_profile": "https://Stackoverflow.com/users/7699617",
"pm_score": 2,
"selected": true,
"text": "/** Input data for example (from your comment). */\nval yourArray = arrayOf(45, 78, 125, 198)\nval inputValue = 95\n\n/** How to get needed index. */\nval resultIndex = yourArray.indexOfLast { it < inputValue }.takeIf { it != -1 }\n resultIndex == null inputValue indexOfFirst sort()"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74607334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14951133/"
] |
74,607,346
|
<p>I can not understand the difference between the declaration with array initialization in the first case and the second</p>
<pre><code>int[] array = new int[3] { 1, 2, 3 };
int[] secondArray = { 1, 2, 3 };
</code></pre>
<p>They seem to do the same thing, maybe they work differently?</p>
|
[
{
"answer_id": 74607370,
"author": "SerjantArbuz",
"author_id": 7699617,
"author_profile": "https://Stackoverflow.com/users/7699617",
"pm_score": 0,
"selected": false,
"text": "min Kotlin"
},
{
"answer_id": 74607428,
"author": "Atick Faisal",
"author_id": 12737399,
"author_profile": "https://Stackoverflow.com/users/12737399",
"pm_score": 1,
"selected": false,
"text": "\n val array: MutableList<Long> = mutableListOf(4L, 9L, 5L, 1L)\n val position = 7L\n \n array.add(position)\n println(array[array.sorted().indexOf(position) - 1])\n\n"
},
{
"answer_id": 74608974,
"author": "Tenfour04",
"author_id": 506796,
"author_profile": "https://Stackoverflow.com/users/506796",
"pm_score": 0,
"selected": false,
"text": "val foundIndex = lyricTimesList.indexOfFirst { it > inputTime }\nval result = if (foundIndex == -1) lyricTimesList.size - 1 else foundIndex - 1\n"
},
{
"answer_id": 74610816,
"author": "SerjantArbuz",
"author_id": 7699617,
"author_profile": "https://Stackoverflow.com/users/7699617",
"pm_score": 2,
"selected": true,
"text": "/** Input data for example (from your comment). */\nval yourArray = arrayOf(45, 78, 125, 198)\nval inputValue = 95\n\n/** How to get needed index. */\nval resultIndex = yourArray.indexOfLast { it < inputValue }.takeIf { it != -1 }\n resultIndex == null inputValue indexOfFirst sort()"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74607346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20426830/"
] |
74,607,356
|
<p>I need to find the latitude and longitude coordinates of the four corners of a rectangle in a Python script, given the center coordinate, length, width, and bearing of the shape. Length and width are in statute miles, but honestly converting those to meters is probably one of the easiest parts. I have some examples of how to use haversine to calculate distance between 2 points, but I'm at a loss on this one. Would anyone be able to at least point me in the right direction?</p>
<p><a href="https://i.stack.imgur.com/2TVg8.png" rel="nofollow noreferrer">Picture of rectangle</a></p>
<p><strong>Update</strong></p>
<p>This is the formula I came up with for my Python script, based on the link that @Mbo provided:</p>
<p><code>lat2 = asin(sin(lat1)*cos(length2/(_AVG_EARTH_RADIUS_KM)) + cos(lat1) * sin(length2/(_AVG_EARTH_RADIUS_KM)) * cos(bearing1))</code></p>
<p><code>lon2 = lon1 + atan2(sin(bearing1) * sin(length2/(_AVG_EARTH_RADIUS_KM)) * cos(lat1), cos(length2/(_AVG_EARTH_RADIUS_KM)) - sin(lat1) * sin(lat2))</code></p>
<p>Unfortunately the results don't make sense. I used a center point of 32° N 77° W, length of 20 miles, width 10 miles, and bearing 0 deg and I'm getting the result <code>0.586599511812, -77.0</code>.</p>
<p>When I plot it out on my mapping application, it tells me that the coordinate for the new point should be <code>32.14513° N, -77.0° W</code>.</p>
<p>Edit to add: I converted <code>length1</code> and <code>width1</code> to kilometers, and converted <code>bearing1</code> to radians before using in the formulas above.</p>
|
[
{
"answer_id": 74607370,
"author": "SerjantArbuz",
"author_id": 7699617,
"author_profile": "https://Stackoverflow.com/users/7699617",
"pm_score": 0,
"selected": false,
"text": "min Kotlin"
},
{
"answer_id": 74607428,
"author": "Atick Faisal",
"author_id": 12737399,
"author_profile": "https://Stackoverflow.com/users/12737399",
"pm_score": 1,
"selected": false,
"text": "\n val array: MutableList<Long> = mutableListOf(4L, 9L, 5L, 1L)\n val position = 7L\n \n array.add(position)\n println(array[array.sorted().indexOf(position) - 1])\n\n"
},
{
"answer_id": 74608974,
"author": "Tenfour04",
"author_id": 506796,
"author_profile": "https://Stackoverflow.com/users/506796",
"pm_score": 0,
"selected": false,
"text": "val foundIndex = lyricTimesList.indexOfFirst { it > inputTime }\nval result = if (foundIndex == -1) lyricTimesList.size - 1 else foundIndex - 1\n"
},
{
"answer_id": 74610816,
"author": "SerjantArbuz",
"author_id": 7699617,
"author_profile": "https://Stackoverflow.com/users/7699617",
"pm_score": 2,
"selected": true,
"text": "/** Input data for example (from your comment). */\nval yourArray = arrayOf(45, 78, 125, 198)\nval inputValue = 95\n\n/** How to get needed index. */\nval resultIndex = yourArray.indexOfLast { it < inputValue }.takeIf { it != -1 }\n resultIndex == null inputValue indexOfFirst sort()"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74607356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20627769/"
] |
74,607,379
|
<p>I have a set of xyz points and a set of tetrahedrons. Where each node of the tetrahedron points to an index in the points table.</p>
<p>I need to plot the tetrahedrons with a corresponding color based on the tag attribute.</p>
<p>points</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Index</th>
<th>x</th>
<th>y</th>
<th>z</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>x_1</td>
<td>y_1</td>
<td>z_1</td>
</tr>
<tr>
<td>1</td>
<td>x_2</td>
<td>y_2</td>
<td>z_2</td>
</tr>
<tr>
<td>...</td>
<td>...</td>
<td>...</td>
<td>...</td>
</tr>
</tbody>
</table>
</div>
<p>tetrahedrons</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Index</th>
<th>a</th>
<th>b</th>
<th>c</th>
<th>d</th>
<th>tag</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>a_1.pt</td>
<td>b_1.pt</td>
<td>c_1.pt</td>
<td>d_1.pt</td>
<td>9</td>
</tr>
<tr>
<td>1</td>
<td>a_2.pt</td>
<td>b_2.pt</td>
<td>c_2.pt</td>
<td>d_2.pt</td>
<td>0</td>
</tr>
<tr>
<td>...</td>
<td>...</td>
<td>...</td>
<td>...</td>
<td>...</td>
<td>...</td>
</tr>
</tbody>
</table>
</div>
<p>I have tried using the <a href="https://plotly.com/python/3d-mesh/" rel="nofollow noreferrer">Mesh3d</a> api but it does not allow for a 4th vertex.</p>
<p>I can plot something like the code below but it does not have all the faces of the tetrahedron.</p>
<pre class="lang-py prettyprint-override"><code>go.Figure(data=[
go.Mesh3d(
x=mesh_pts.x, y=mesh_pts.y, z=mesh_pts.z,
i=tagged_th.a, j=tagged_th.b, k=tagged_th.c,
),
]).show()
</code></pre>
<p>I think the <a href="https://plotly.com/python/3d-volume-plots/" rel="nofollow noreferrer">Volume</a> or <a href="https://plotly.com/python/3d-isosurface-plots/" rel="nofollow noreferrer">Isosurface</a> plots might work but I'm not sure how to convert my data into a format to be consumed by those apis.</p>
|
[
{
"answer_id": 74607592,
"author": "Stéphane Laurent",
"author_id": 1100107,
"author_profile": "https://Stackoverflow.com/users/1100107",
"pm_score": 0,
"selected": false,
"text": "import plotly.graph_objects as go\nimport plotly.io as pio\nimport numpy as np\n\ni = np.array([0, 0, 0, 1])\nj = np.array([1, 2, 3, 2])\nk = np.array([2, 3, 1, 3])\n\nfig = go.Figure(data = [\n go.Mesh3d(\n x = [0,1,2,0, 4,5,6,4],\n y = [0,0,1,2, 0,0,1,2],\n z = [0,2,2,3, 4,2,4,1],\n i = np.concatenate((i, i+4)),\n j = np.concatenate((j, j+4)),\n k = np.concatenate((k, k+4)),\n facecolor = [\"red\",\"red\",\"red\",\"red\", \"green\",\"green\",\"green\",\"green\"]\n )\n])\n\npio.write_html(fig, file = \"tetrahedra.html\", auto_open = True)\n"
},
{
"answer_id": 74607608,
"author": "chrslg",
"author_id": 20037042,
"author_profile": "https://Stackoverflow.com/users/20037042",
"pm_score": 2,
"selected": true,
"text": "i j k l a b c d bcd acd abd abc bcd\nacd\nabd\nabc\n^^^\n|||\n||\\------k\n|\\------ j\n\\------- i\n i=b + a + a + a\nj=c + c + b + b\nk=d + d + d + c\n import plotly.graph_objects as go\nimport pandas as pd\n\nmesh_pts = pd.DataFrame({'x':[0, 1, 0, 0, 1, 0, 0],\n 'y':[0, 0, 1, 0, 0, 1, 0],\n 'z':[0, 0, 0, 1, 1, 1, 2]})\n\ntagged_th = pd.DataFrame({'a':[0,3],\n 'b':[1,4],\n 'c':[2,5],\n 'd':[3,6],\n 'tag':[0,1]})\n\n# And from there, just create a list of triangles, made of 4 combinations \n# of 3 points taken from list of tetrahedron vertices\ngo.Figure(data=[\n go.Mesh3d(\n x=mesh_pts.x,\n y=mesh_pts.y,\n z=mesh_pts.z,\n i=pd.concat([tagged_th.a, tagged_th.a, tagged_th.a, tagged_th.b]),\n j=pd.concat([tagged_th.b, tagged_th.b, tagged_th.c, tagged_th.c]),\n k=pd.concat([tagged_th.c, tagged_th.d, tagged_th.d, tagged_th.d]),\n intensitymode='cell',\n intensity=pd.concat([tagged_th.tag, tagged_th.tag, tagged_th.tag, tagged_th.tag])\n )\n]).show()\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74607379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3113799/"
] |
74,607,389
|
<p>I need a multidimensional array/list (2 and/or 3 dimensions) which must contains different objects.
This is what I found:</p>
<pre><code> List recipes = List.generate(
999,
(_) => List<Ingredient>.filled(
9,
Ingredient(
name: '', carboidrates: 0, proteins: 0, lipids: 0, fibers: 0),
growable: true));
</code></pre>
<p>My needs is to have recipes[index/int][index/Ingredient].somethingoftheIngredientClass</p>
<p>As for example, if I create a single List:</p>
<pre><code>List<Ingredient> recipe = <Ingredient>[];
</code></pre>
<p>I can access the class as</p>
<pre><code>recipe[0].carboidrates
</code></pre>
<p>Not the same for my 2 dimensional list:</p>
<pre><code>recipes[0][0].doesnotshowCarboidrates
</code></pre>
|
[
{
"answer_id": 74607710,
"author": "masterwok",
"author_id": 563509,
"author_profile": "https://Stackoverflow.com/users/563509",
"pm_score": 2,
"selected": true,
"text": "== hashCode \nclass Recipe {\n final String name;\n final List<Ingredient> ingredients;\n final List<Instruction> instructions;\n\n Recipe({\n required this.name,\n required this.ingredients,\n required this.instructions,\n });\n\n @override\n bool operator ==(Object other) =>\n identical(this, other) || other is Recipe && runtimeType == other.runtimeType && name == other.name;\n\n @override\n int get hashCode => name.hashCode ^ ingredients.hashCode ^ instructions.hashCode;\n}\n\nclass Ingredient {\n final String name;\n final String description;\n\n Ingredient({\n required this.name,\n required this.description,\n });\n}\n\nclass Instruction {\n final String description;\n final String? tip;\n\n Instruction({\n required this.description,\n this.tip,\n });\n}\n\nfinal recipes = [\n Recipe(\n name: 'Cheese pizza',\n ingredients: [\n Ingredient(name: 'Dough', description: 'Normal yeast based pizza dough'),\n Ingredient(name: 'Tomato Sauce', description: 'Freshly blended organic tomatoes'),\n Ingredient(name: 'Mozzarella Cheese', description: 'Cheesy cheesiness from mount cheese'),\n ],\n instructions: [\n Instruction(description: 'Preheat oven to 400 degrees Fahrenheit'),\n Instruction(description: 'While oven is preheating spread dough evenly in a circle over an oiled pan'),\n Instruction(description: 'Spread sauce evenly over dough leaving enough room for the crust'),\n Instruction(description: 'Cover the sauce with the Mozzarella cheese'),\n Instruction(\n description: 'Roll the edge of the dough to form the crust',\n tip: 'Optionally add cheese within the dough for stuffed crust!',\n ),\n Instruction(description: 'Bake the pizza in the over until golden brown'),\n Instruction(\n description: 'Remove the pizza from the oven and let cool',\n tip: 'Some people like to let the pizza cool before cutting',\n ),\n ],\n ),\n];\n\n/// Find the index of a recipe. This uses the equality and hashcode overrides of the recipe class.\nint getRecipeIndex(Recipe recipe) => recipes.indexOf(recipe);\n\n/// Find all of the recipes containing the [query] in their name (case-insensitive).\nList<Recipe> getRecipeByName(String query) {\n return recipes.where((element) => element.name.toLowerCase().contains(query.toLowerCase())).toList();\n}\n\n/// Get the ingredients of a recipe.\nfinal recipeIngredients = recipes[0].ingredients;\n\n/// Get the instructions of a recipe.\nfinal recipeInstructions = recipes[0].instructions;\n\n/// Get a list of all of the tips for a recipe.\nfinal recipeTips = recipes[0].instructions.map((e) => e.tip).whereType<String>();\n map Recipe List<Recipe> final pizza = recipes[0];\n\n/// How to associate a recipe with similar recipes using a map of `Recipe` to `List<Recipe>`\nfinal similarRecipesMap = { pizza: [recipes[1], recipes[2]]};\n\nfinal similarRecipesToPizza = similarRecipesMap[pizza];\n"
},
{
"answer_id": 74607729,
"author": "Emc2Theory",
"author_id": 4651768,
"author_profile": "https://Stackoverflow.com/users/4651768",
"pm_score": 0,
"selected": false,
"text": " List recipes = List.generate(\n 999,\n (_) => List<Ingredient>.filled(\n 9,\n Ingredient(\n name: 'Cheesecake',\n carboidrates: 0,\n proteins: 0,\n lipids: 0,\n fibers: 0),\n growable: true));\n print(recipes[0][0].name);\n Restarted application in 262ms.\nflutter: Cheesecake\n print(recipes[0][0].\n hashCode, runtimeType, toString(), noSuchMethod(...)\n"
},
{
"answer_id": 74608207,
"author": "Emc2Theory",
"author_id": 4651768,
"author_profile": "https://Stackoverflow.com/users/4651768",
"pm_score": 0,
"selected": false,
"text": " List<List<List<Ingredient>>> ingredient =\n List.generate(999, (index) => [[]], growable: true);\n ingredient[0][0].clear();\ningredient[0][0].add(Ingredient(\n name: 'Panettone', carboidrates: 0, proteins: 0, lipids: 0, fibers: 0));\nprint(ingredient[0][0][0].name);\n print(ingredient[0][0][0].\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74607389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4651768/"
] |
74,607,408
|
<p>How can I get an onclick function to trigger in a Rails 7 view?</p>
<p>I added a simple function:</p>
<pre><code>// app/javascript/application.js
function myTest(myVar){
alert(myVar);
};
myTest("test1");
</code></pre>
<p>The alert for "test1" does trigger on page load. However, I want to trigger this in an HTML onclick attribute within my view:</p>
<pre><code>// my view
<a href="#" onclick="myTest('test2');">test</a>
</code></pre>
<p>However, the browser console says that the <code>myTest</code> function is not defined. I do see that the function ends up in my application.js file that the browser is loading.</p>
<pre><code>// compiled application.js from asset pipeline
(() => {
// ... all of the other rails JS here
function myTest(myVar) {
alert(myVar);
}
myTest("test1");
})();
</code></pre>
<p>Shouldn't I be able to trigger this directly from the console also? This also gives me the error that the function does not exist.</p>
<pre><code>myTest("test3");
</code></pre>
<p>edit: I think all of the code in Rails is being put into an <a href="https://developer.mozilla.org/en-US/docs/Glossary/IIFE" rel="nofollow noreferrer">IIFE</a> which is purposely not loaded in the global scope.</p>
|
[
{
"answer_id": 74607710,
"author": "masterwok",
"author_id": 563509,
"author_profile": "https://Stackoverflow.com/users/563509",
"pm_score": 2,
"selected": true,
"text": "== hashCode \nclass Recipe {\n final String name;\n final List<Ingredient> ingredients;\n final List<Instruction> instructions;\n\n Recipe({\n required this.name,\n required this.ingredients,\n required this.instructions,\n });\n\n @override\n bool operator ==(Object other) =>\n identical(this, other) || other is Recipe && runtimeType == other.runtimeType && name == other.name;\n\n @override\n int get hashCode => name.hashCode ^ ingredients.hashCode ^ instructions.hashCode;\n}\n\nclass Ingredient {\n final String name;\n final String description;\n\n Ingredient({\n required this.name,\n required this.description,\n });\n}\n\nclass Instruction {\n final String description;\n final String? tip;\n\n Instruction({\n required this.description,\n this.tip,\n });\n}\n\nfinal recipes = [\n Recipe(\n name: 'Cheese pizza',\n ingredients: [\n Ingredient(name: 'Dough', description: 'Normal yeast based pizza dough'),\n Ingredient(name: 'Tomato Sauce', description: 'Freshly blended organic tomatoes'),\n Ingredient(name: 'Mozzarella Cheese', description: 'Cheesy cheesiness from mount cheese'),\n ],\n instructions: [\n Instruction(description: 'Preheat oven to 400 degrees Fahrenheit'),\n Instruction(description: 'While oven is preheating spread dough evenly in a circle over an oiled pan'),\n Instruction(description: 'Spread sauce evenly over dough leaving enough room for the crust'),\n Instruction(description: 'Cover the sauce with the Mozzarella cheese'),\n Instruction(\n description: 'Roll the edge of the dough to form the crust',\n tip: 'Optionally add cheese within the dough for stuffed crust!',\n ),\n Instruction(description: 'Bake the pizza in the over until golden brown'),\n Instruction(\n description: 'Remove the pizza from the oven and let cool',\n tip: 'Some people like to let the pizza cool before cutting',\n ),\n ],\n ),\n];\n\n/// Find the index of a recipe. This uses the equality and hashcode overrides of the recipe class.\nint getRecipeIndex(Recipe recipe) => recipes.indexOf(recipe);\n\n/// Find all of the recipes containing the [query] in their name (case-insensitive).\nList<Recipe> getRecipeByName(String query) {\n return recipes.where((element) => element.name.toLowerCase().contains(query.toLowerCase())).toList();\n}\n\n/// Get the ingredients of a recipe.\nfinal recipeIngredients = recipes[0].ingredients;\n\n/// Get the instructions of a recipe.\nfinal recipeInstructions = recipes[0].instructions;\n\n/// Get a list of all of the tips for a recipe.\nfinal recipeTips = recipes[0].instructions.map((e) => e.tip).whereType<String>();\n map Recipe List<Recipe> final pizza = recipes[0];\n\n/// How to associate a recipe with similar recipes using a map of `Recipe` to `List<Recipe>`\nfinal similarRecipesMap = { pizza: [recipes[1], recipes[2]]};\n\nfinal similarRecipesToPizza = similarRecipesMap[pizza];\n"
},
{
"answer_id": 74607729,
"author": "Emc2Theory",
"author_id": 4651768,
"author_profile": "https://Stackoverflow.com/users/4651768",
"pm_score": 0,
"selected": false,
"text": " List recipes = List.generate(\n 999,\n (_) => List<Ingredient>.filled(\n 9,\n Ingredient(\n name: 'Cheesecake',\n carboidrates: 0,\n proteins: 0,\n lipids: 0,\n fibers: 0),\n growable: true));\n print(recipes[0][0].name);\n Restarted application in 262ms.\nflutter: Cheesecake\n print(recipes[0][0].\n hashCode, runtimeType, toString(), noSuchMethod(...)\n"
},
{
"answer_id": 74608207,
"author": "Emc2Theory",
"author_id": 4651768,
"author_profile": "https://Stackoverflow.com/users/4651768",
"pm_score": 0,
"selected": false,
"text": " List<List<List<Ingredient>>> ingredient =\n List.generate(999, (index) => [[]], growable: true);\n ingredient[0][0].clear();\ningredient[0][0].add(Ingredient(\n name: 'Panettone', carboidrates: 0, proteins: 0, lipids: 0, fibers: 0));\nprint(ingredient[0][0][0].name);\n print(ingredient[0][0][0].\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74607408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/375265/"
] |
74,607,412
|
<p>I went to try out the Alire package manager for Ada the other night, and found this in the <a href="https://alire.ada.dev/docs/" rel="nofollow noreferrer">documentation</a>:</p>
<blockquote>
<p>Issue alr init --bin myproj (you can use --lib for a library project)</p>
<p>The first time you run this command, alr will ask a couple of questions to automatically fill-in information about the crate:</p>
<p>GitHub login: is used to identify the maintainer of the crate when contributed to the community index.
Full name: Name of the author of the crate
Email address: Point of contact to author of the crate</p>
<p>All the questions are optional for now, you can just press enter to use the default values.</p>
</blockquote>
<p>This "All the questions are optional for now" is somewhat concerning in that it implies they will be mandatory in the future.</p>
<p>This seems like a very strange design choice. I do not have or want a GitHub account, and while I understand that Alire needs to pull from GitHub to retrieve crates I would think that an account should not be required to clone public repositories. I do not want to become overly reliant in the Alire ecosystem if I will effectively become locked out of it in future.</p>
<p>I have not found any discussion or timeline around when Alire will start requiring a GitHub account - is this truly the case, and if so when will it become mandatory?</p>
|
[
{
"answer_id": 74607710,
"author": "masterwok",
"author_id": 563509,
"author_profile": "https://Stackoverflow.com/users/563509",
"pm_score": 2,
"selected": true,
"text": "== hashCode \nclass Recipe {\n final String name;\n final List<Ingredient> ingredients;\n final List<Instruction> instructions;\n\n Recipe({\n required this.name,\n required this.ingredients,\n required this.instructions,\n });\n\n @override\n bool operator ==(Object other) =>\n identical(this, other) || other is Recipe && runtimeType == other.runtimeType && name == other.name;\n\n @override\n int get hashCode => name.hashCode ^ ingredients.hashCode ^ instructions.hashCode;\n}\n\nclass Ingredient {\n final String name;\n final String description;\n\n Ingredient({\n required this.name,\n required this.description,\n });\n}\n\nclass Instruction {\n final String description;\n final String? tip;\n\n Instruction({\n required this.description,\n this.tip,\n });\n}\n\nfinal recipes = [\n Recipe(\n name: 'Cheese pizza',\n ingredients: [\n Ingredient(name: 'Dough', description: 'Normal yeast based pizza dough'),\n Ingredient(name: 'Tomato Sauce', description: 'Freshly blended organic tomatoes'),\n Ingredient(name: 'Mozzarella Cheese', description: 'Cheesy cheesiness from mount cheese'),\n ],\n instructions: [\n Instruction(description: 'Preheat oven to 400 degrees Fahrenheit'),\n Instruction(description: 'While oven is preheating spread dough evenly in a circle over an oiled pan'),\n Instruction(description: 'Spread sauce evenly over dough leaving enough room for the crust'),\n Instruction(description: 'Cover the sauce with the Mozzarella cheese'),\n Instruction(\n description: 'Roll the edge of the dough to form the crust',\n tip: 'Optionally add cheese within the dough for stuffed crust!',\n ),\n Instruction(description: 'Bake the pizza in the over until golden brown'),\n Instruction(\n description: 'Remove the pizza from the oven and let cool',\n tip: 'Some people like to let the pizza cool before cutting',\n ),\n ],\n ),\n];\n\n/// Find the index of a recipe. This uses the equality and hashcode overrides of the recipe class.\nint getRecipeIndex(Recipe recipe) => recipes.indexOf(recipe);\n\n/// Find all of the recipes containing the [query] in their name (case-insensitive).\nList<Recipe> getRecipeByName(String query) {\n return recipes.where((element) => element.name.toLowerCase().contains(query.toLowerCase())).toList();\n}\n\n/// Get the ingredients of a recipe.\nfinal recipeIngredients = recipes[0].ingredients;\n\n/// Get the instructions of a recipe.\nfinal recipeInstructions = recipes[0].instructions;\n\n/// Get a list of all of the tips for a recipe.\nfinal recipeTips = recipes[0].instructions.map((e) => e.tip).whereType<String>();\n map Recipe List<Recipe> final pizza = recipes[0];\n\n/// How to associate a recipe with similar recipes using a map of `Recipe` to `List<Recipe>`\nfinal similarRecipesMap = { pizza: [recipes[1], recipes[2]]};\n\nfinal similarRecipesToPizza = similarRecipesMap[pizza];\n"
},
{
"answer_id": 74607729,
"author": "Emc2Theory",
"author_id": 4651768,
"author_profile": "https://Stackoverflow.com/users/4651768",
"pm_score": 0,
"selected": false,
"text": " List recipes = List.generate(\n 999,\n (_) => List<Ingredient>.filled(\n 9,\n Ingredient(\n name: 'Cheesecake',\n carboidrates: 0,\n proteins: 0,\n lipids: 0,\n fibers: 0),\n growable: true));\n print(recipes[0][0].name);\n Restarted application in 262ms.\nflutter: Cheesecake\n print(recipes[0][0].\n hashCode, runtimeType, toString(), noSuchMethod(...)\n"
},
{
"answer_id": 74608207,
"author": "Emc2Theory",
"author_id": 4651768,
"author_profile": "https://Stackoverflow.com/users/4651768",
"pm_score": 0,
"selected": false,
"text": " List<List<List<Ingredient>>> ingredient =\n List.generate(999, (index) => [[]], growable: true);\n ingredient[0][0].clear();\ningredient[0][0].add(Ingredient(\n name: 'Panettone', carboidrates: 0, proteins: 0, lipids: 0, fibers: 0));\nprint(ingredient[0][0][0].name);\n print(ingredient[0][0][0].\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74607412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9254211/"
] |
74,607,435
|
<p>In the below <code>awk</code> I am skipping the lines that start with <code>#</code> and trying to find the matching lines between two files based on 4 specific columns, and if a line does not match it outputs the file and line it is missing from. Thank you :).</p>
<p><strong>file1</strong></p>
<pre><code>##....
#....
chr1 1013466 . T TA 11438.1 PASS
chr1 1013490 . C G 14137 PASS
chr1 1013600 . T TAA 1140 PASS
</code></pre>
<p><strong>file2</strong></p>
<pre><code>##...
#....
chr1 1013466 . T TA 10914 PASS
chr1 1013490 . C G 13785.1 PASS
chr1 1014600 . C A 2000 PASS
</code></pre>
<p><strong>awk</strong></p>
<pre><code>f1=1234.txt
f2=5678.txt
awk -F'\t' '/^[^#]/ FNR==1 { next }
FNR == NR { $f1[$1,$2,$4,$5] = $1 FS $2 FS $4 FS $5 }
FNR != NR { $f2[$1,$2,$4,$5] = $1 FS $2 FS $4 FS $5 }
END { print "Match:"; for (k in $f1) if (k in $f2) print $f1[k] # Or $f2[k]
print "Not Found:"; for (k in $f2) if (!(k in $f1)) print $f2[k]
}' OFS="\t" $f1 $f2
</code></pre>
<p><strong>desired</strong> <code>tab-delimited</code></p>
<pre><code>Match between 1234.txt and 5678.txt:
chr1 1013466 . T TA 11438.1 PASS
chr1 1013490 . C G 14137 PASS
Not Found in 1234.txt:
chr1 1014600 . C A 2000 PASS
Not Found in 5678.txt:
chr1 1013600 . T TAA 1140 PASS
</code></pre>
|
[
{
"answer_id": 74607711,
"author": "markp-fuso",
"author_id": 7366100,
"author_profile": "https://Stackoverflow.com/users/7366100",
"pm_score": 3,
"selected": true,
"text": "awk $ awk $ awk f1=1234.txt\nf2=5678.txt\n\nawk '\nBEGIN { FS=OFS=\"\\t\" }\n/^#/ { next }\n { ndx=$1 FS $2 FS $4 FS $5 }\nFNR == NR { if (!fname1) fname1=FILENAME; f1[ndx]=$0 }\nFNR != NR { if (!fname2) fname2=FILENAME; f2[ndx]=$0 }\nEND { printf \"Match between %s and %s:\\n\", fname1, fname2 \n for (ndx in f1)\n if (ndx in f2)\n print f1[ndx]\n\n printf \"Not Found in %s:\\n\",fname1\n for (ndx in f2)\n if ( !(ndx in f1) )\n print f2[ndx]\n\n printf \"Not Found in %s:\\n\",fname2\n for (ndx in f1)\n if ( !(ndx in f2) )\n print f1[ndx]\n }\n' $f1 $f2\n Match between 1234.txt and 5678.txt:\nchr1 1013490 . C G 14137 PASS\nchr1 1013466 . T TA 11438.1 PASS\nNot Found in 1234.txt:\nchr1 1014600 . C A 2000 PASS\nNot Found in 5678.txt:\nchr1 1013600 . T TAA 1140 PASS\n awk '\nBEGIN { FS=OFS=\"\\t\" }\n/^#/ { next }\n { ndx=$1 FS $2 FS $4 FS $5 }\nFNR == NR { if (!fname1) fname1=FILENAME; indices1[++cnt1]=ndx; f1[ndx]=$0 }\nFNR != NR { if (!fname2) fname2=FILENAME; indices2[++cnt2]=ndx; f2[ndx]=$0 }\n\nEND { printf \"Match between %s and %s:\\n\", fname1, fname2\n for (i=1;i<=cnt1;i++) {\n ndx=indices1[i]\n if (ndx in f1 && ndx in f2)\n print f1[ndx]\n }\n\n printf \"Not Found in %s:\\n\",fname1\n for (i=1;i<=cnt2;i++) {\n ndx=indices2[i]\n if ( !(ndx in f1) )\n print f2[ndx]\n }\n\n printf \"Not Found in %s:\\n\",fname2\n for (i=1;i<=cnt1;i++) {\n ndx=indices1[i]\n if ( !(ndx in f2) )\n print f1[ndx]\n }\n }\n' $f1 $f2\n Match between 1234.txt and 5678.txt:\nchr1 1013466 . T TA 11438.1 PASS\nchr1 1013490 . C G 14137 PASS\nNot Found in 1234.txt:\nchr1 1014600 . C A 2000 PASS\nNot Found in 5678.txt:\nchr1 1013600 . T TAA 1140 PASS\n"
},
{
"answer_id": 74615749,
"author": "Ed Morton",
"author_id": 1745001,
"author_profile": "https://Stackoverflow.com/users/1745001",
"pm_score": 2,
"selected": false,
"text": "$ cat tst.awk\nBEGIN { FS=OFS=\"\\t\" }\n/^#/ { next }\n{ key = $1 FS $2 FS $4 FS $5 }\nNR==FNR {\n file1[key] = $0\n next\n}\n{\n if ( key in file1 ) {\n both[key] = file1[key]\n delete file1[key]\n }\n else {\n file2[key] = $0\n }\n}\nEND {\n printf \"Match between %s and %s\\n\", ARGV[1], ARGV[2]\n for ( key in both ) {\n print both[key]\n }\n printf \"Not found in %s\\n\", ARGV[1]\n for ( key in file2 ) {\n print file2[key]\n }\n printf \"Not found in %s\\n\", ARGV[2]\n for ( key in file1 ) {\n print file1[key]\n }\n}\n $ awk -f tst.awk 1234.txt 5678.txt\nMatch between 1234.txt and 5678.txt\nchr1 1013466 . T TA 11438.1 PASS\nchr1 1013490 . C G 14137 PASS\nNot found in 1234.txt\nchr1 1014600 . C A 2000 PASS\nNot found in 5678.txt\nchr1 1013600 . T TAA 1140 PASS\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74607435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4668368/"
] |
74,607,446
|
<p>i am working on a game where you get random numbers 1-25 in individual squares, you also get random colors and font sizes. I have all that set up at this point but what i am struggling with is implementing a check that will check if these numbers have been clicked in the sequence one after another. So, when you start the game and have your numbers from 1 through 25......i want the person to be able to click on 1 then on 2 then on 3 and have the following tests happen:</p>
<ul>
<li>#1 is always clickable since its the first number in a sequence.</li>
<li>#2 is not clickable unless # 1 has been clicked. # 3 is not clickable unless #1 and #2 have been clicked and so on....once its successfully clicked, background color changes.</li>
</ul>
<p>I understand i need to loop through my random numbers and assign .eventListener to them.</p>
<p>So i came close with this line of code:
if (squares[i].textContent = numArray[i] === 1) squares[i].addEventListener('click', function() { return squares[i].style.backgroundColor = 'red'})</p>
<p>I can see that it is identify 1 in this case but everything is being displayed as true or false instead of numbers. I am not sure where to go from here or how i can check for clicked boxes in the correct order.</p>
<p>Thank you so much for taking your time to read this and help me understand a solution.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let startBtn = document.querySelector('.start-btn')
let resetBtn = document.querySelector('.reset-btn')
let timer = document.querySelector('.time__countdown')
const squares = [...document.querySelectorAll('.square')];
let gameStarted = false;
let counter = 60
let timeInterval;
startBtn.addEventListener('click', startGame)
function startGame() {
gameStarted = true;
if (gameStarted === true) {
for (let i = 0; i < squares.length; i++) {
squares[i].addEventListener('click', function() {
squares[i].style.backgroundColor = '#2A3166'
})
}
}
randomNumber()
timeInterval = setInterval(function() {
counter--
if (counter >= 0) {
timer.innerHTML = `Time left: ${counter}`
}
}, 1000)
}
function getRandomColor() {
const letters = '0123456789ABCDEF';
let color = '#';
for (let i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
function randomNumber() {
const numArray = []
for (let i = 1; i < 26; i++) {
numArray.push(i)
}
numArray.sort(() => 0.5 - Math.random())
for (let i = 0; i < squares.length; i++) {
const random = Math.floor(Math.random() * 25)
squares[i].textContent = numArray[i]
squares[i].style.fontSize = random + 15 + "px";
squares[i].style.color = getRandomColor()
squares[i].style.backgroundColor = '#000000'
}
}
resetBtn.addEventListener('click', function() {
clearInterval(timeInterval)
counter = 60
timer.innerHTML = `Time left: 60`
gameStarted = false
squares.forEach((n) => {
n.textContent = "";
n.style.backgroundColor = "#000000";
})
})</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
margin: 0;
padding: 0;
}
body,
html {
min-width: 100%;
min-height: 100vh;
box-sizing: border-box;
font-size: 100%;
display: flex;
justify-content: center;
align-items: center;
background-color: black;
}
img {
max-width: 100%;
display: block;
}
main {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
width: 24%;
background-color: #6688CC;
border-radius: 10px;
}
.grid {
border: 2px solid black;
width: 100%;
display: flex;
flex-wrap: wrap;
background-color: #ACBFE6;
justify-content: center;
align-items: center;
gap: 2px;
padding-top: 3px;
padding-bottom: 3px;
}
.square {
border: 2px solid black;
width: 70px;
height: 70px;
display: flex;
justify-content: center;
align-items: center;
background-color: #000000;
}
.time {
padding-bottom: 2em;
padding-top: 1em;
}
.btn {
margin: 1em;
}
.buttons {
display: flex;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><main>
<div class="time">
<p class="time__countdown">Time left: 60</p>
</div>
<grid class="grid">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</grid>
<div class="buttons">
<button class="btn start-btn">Start Game</button>
<button class="btn reset-btn">Reset Game</button>
</div>
</main></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74607711,
"author": "markp-fuso",
"author_id": 7366100,
"author_profile": "https://Stackoverflow.com/users/7366100",
"pm_score": 3,
"selected": true,
"text": "awk $ awk $ awk f1=1234.txt\nf2=5678.txt\n\nawk '\nBEGIN { FS=OFS=\"\\t\" }\n/^#/ { next }\n { ndx=$1 FS $2 FS $4 FS $5 }\nFNR == NR { if (!fname1) fname1=FILENAME; f1[ndx]=$0 }\nFNR != NR { if (!fname2) fname2=FILENAME; f2[ndx]=$0 }\nEND { printf \"Match between %s and %s:\\n\", fname1, fname2 \n for (ndx in f1)\n if (ndx in f2)\n print f1[ndx]\n\n printf \"Not Found in %s:\\n\",fname1\n for (ndx in f2)\n if ( !(ndx in f1) )\n print f2[ndx]\n\n printf \"Not Found in %s:\\n\",fname2\n for (ndx in f1)\n if ( !(ndx in f2) )\n print f1[ndx]\n }\n' $f1 $f2\n Match between 1234.txt and 5678.txt:\nchr1 1013490 . C G 14137 PASS\nchr1 1013466 . T TA 11438.1 PASS\nNot Found in 1234.txt:\nchr1 1014600 . C A 2000 PASS\nNot Found in 5678.txt:\nchr1 1013600 . T TAA 1140 PASS\n awk '\nBEGIN { FS=OFS=\"\\t\" }\n/^#/ { next }\n { ndx=$1 FS $2 FS $4 FS $5 }\nFNR == NR { if (!fname1) fname1=FILENAME; indices1[++cnt1]=ndx; f1[ndx]=$0 }\nFNR != NR { if (!fname2) fname2=FILENAME; indices2[++cnt2]=ndx; f2[ndx]=$0 }\n\nEND { printf \"Match between %s and %s:\\n\", fname1, fname2\n for (i=1;i<=cnt1;i++) {\n ndx=indices1[i]\n if (ndx in f1 && ndx in f2)\n print f1[ndx]\n }\n\n printf \"Not Found in %s:\\n\",fname1\n for (i=1;i<=cnt2;i++) {\n ndx=indices2[i]\n if ( !(ndx in f1) )\n print f2[ndx]\n }\n\n printf \"Not Found in %s:\\n\",fname2\n for (i=1;i<=cnt1;i++) {\n ndx=indices1[i]\n if ( !(ndx in f2) )\n print f1[ndx]\n }\n }\n' $f1 $f2\n Match between 1234.txt and 5678.txt:\nchr1 1013466 . T TA 11438.1 PASS\nchr1 1013490 . C G 14137 PASS\nNot Found in 1234.txt:\nchr1 1014600 . C A 2000 PASS\nNot Found in 5678.txt:\nchr1 1013600 . T TAA 1140 PASS\n"
},
{
"answer_id": 74615749,
"author": "Ed Morton",
"author_id": 1745001,
"author_profile": "https://Stackoverflow.com/users/1745001",
"pm_score": 2,
"selected": false,
"text": "$ cat tst.awk\nBEGIN { FS=OFS=\"\\t\" }\n/^#/ { next }\n{ key = $1 FS $2 FS $4 FS $5 }\nNR==FNR {\n file1[key] = $0\n next\n}\n{\n if ( key in file1 ) {\n both[key] = file1[key]\n delete file1[key]\n }\n else {\n file2[key] = $0\n }\n}\nEND {\n printf \"Match between %s and %s\\n\", ARGV[1], ARGV[2]\n for ( key in both ) {\n print both[key]\n }\n printf \"Not found in %s\\n\", ARGV[1]\n for ( key in file2 ) {\n print file2[key]\n }\n printf \"Not found in %s\\n\", ARGV[2]\n for ( key in file1 ) {\n print file1[key]\n }\n}\n $ awk -f tst.awk 1234.txt 5678.txt\nMatch between 1234.txt and 5678.txt\nchr1 1013466 . T TA 11438.1 PASS\nchr1 1013490 . C G 14137 PASS\nNot found in 1234.txt\nchr1 1014600 . C A 2000 PASS\nNot found in 5678.txt\nchr1 1013600 . T TAA 1140 PASS\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74607446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18992987/"
] |
74,607,479
|
<p>I'm using Locate Control in React Leaflet, but the Locate Control buttons are always duplicated, and sometimes I get 3 or 4 of them (see image below). I'm running the function through a useEffect with empty dependency to only fire it once, but no matter. I can target the class with display: none, but then both disappear. I feel like this might be an issue with Locate Control library? Really not sure. Open to any help or ideas.</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>import { useEffect } from "react"
import { useMap } from "react-leaflet"
import Locate from "leaflet.locatecontrol"
import "leaflet.locatecontrol/dist/L.Control.Locate.min.css"
const AddLocate = () => {
const map = useMap()
useEffect(() => {
const locateOptions = {
position: "bottomleft",
flyTo: true,
}
const locateControl = new Locate(locateOptions)
locateControl.addTo(map)
}, [])
return null
}
export default AddLocate;</code></pre>
</div>
</div>
</p>
<p><a href="https://i.stack.imgur.com/J3b35.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/J3b35.png" alt="Duplicated locate control" /></a></p>
|
[
{
"answer_id": 74611031,
"author": "Disco",
"author_id": 11196441,
"author_profile": "https://Stackoverflow.com/users/11196441",
"pm_score": 2,
"selected": true,
"text": "react-leaflet import { ActionIcon } from \"@mantine/core\";\nimport React, { useState } from \"react\";\nimport { useMapEvents } from \"react-leaflet\";\nimport { CurrentLocation } from \"tabler-icons-react\";\nimport LeafletControl from \"./LeafletControl\";\n\ninterface LeafletMyPositionProps {\n zoom?: number;\n}\n\nconst LeafletMyPosition: React.FC<LeafletMyPositionProps> = ({ zoom = 17 }) => {\n const [loading, setLoading] = useState<boolean>(false);\n const map = useMapEvents({\n locationfound(e) {\n map.flyTo(e.latlng, zoom);\n setLoading(false);\n },\n });\n\n return (\n <LeafletControl position={\"bottomright\"}>\n <ActionIcon\n onClick={() => {\n setLoading(true);\n map.locate();\n }}\n loading={loading}\n variant={\"transparent\"}\n >\n <CurrentLocation />\n </ActionIcon>\n </LeafletControl>\n );\n};\n\nexport default LeafletMyPosition;\n import L from \"leaflet\";\nimport React, { useEffect, useRef } from \"react\";\n\nconst ControlClasses = {\n bottomleft: \"leaflet-bottom leaflet-left\",\n bottomright: \"leaflet-bottom leaflet-right\",\n topleft: \"leaflet-top leaflet-left\",\n topright: \"leaflet-top leaflet-right\",\n};\n\ntype ControlPosition = keyof typeof ControlClasses;\nexport interface LeafLetControlProps {\n position?: ControlPosition;\n children?: React.ReactNode;\n}\n\nconst LeafletControl: React.FC<LeafLetControlProps> = ({\n position,\n children,\n}) => {\n const divRef = useRef(null);\n\n useEffect(() => {\n if (divRef.current) {\n L.DomEvent.disableClickPropagation(divRef.current);\n L.DomEvent.disableScrollPropagation(divRef.current);\n }\n });\n\n return (\n <div ref={divRef} className={position && ControlClasses[position]}>\n <div className={\"leaflet-control\"}>{children}</div>\n </div>\n );\n};\n\nexport default LeafletControl;\n\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74607479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20332660/"
] |
74,607,500
|
<p>There's a simple <code>QStandardItemModel</code> defined in c++ which I am displaying in a <code>QML</code> <code>ListView</code> via custom <code>Delegate</code>s and a <code>DelegateModel</code>. The ListView can be reordered via Drag'n Drop:</p>
<pre><code>// The DropArea is part of the delegate `comp_container`
DropArea{
anchors{fill: parent}
keys: ["pageitem"]
onEntered: {
let from = drag.source.DelegateModel.itemsIndex
let to = dragAreaPage.DelegateModel.itemsIndex
if ( pageItemDragOperationStartIndex === -1 ){
pageItemDragOperationStartIndex = from
}
pageItemDragOperationFinalIndex = to
console.log(from + "->" + to)
visualModel.items.move(from,to)
}
}
</code></pre>
<p>Here is the delegate model and <code>pageproxymodel</code> is the c++ model.</p>
<pre><code>DelegateModel {
id: visualModel
model: pageproxymodel
delegate: comp_container
}
</code></pre>
<p>How do I want to update the c++ model?
The delegate's top level item is a <code>MouseArea</code> and I handle the reordering in the release handler:</p>
<pre><code>onReleased: {
if ( pageItemDragOperationStartIndex !== -1 && pageItemDragOperationFinalIndex !== -1 ){
console.log("Page item final drag operation: " + pageItemDragOperationStartIndex + "->" + pageItemDragOperationFinalIndex)
pageproxymodel.move(pageItemDragOperationStartIndex, pageItemDragOperationFinalIndex)
pageItemDragOperationStartIndex = -1
pageItemDragOperationFinalIndex = -1
}
}
</code></pre>
<p>The c++ model's <code>move</code> function forwards the call to this handler:</p>
<pre><code>bool PageModel::moveRow(const QModelIndex &sourceParent,
int sourceRow,
const QModelIndex &destinationParent,
int destinationChild)
{
if ( sourceRow < 0 || sourceRow > rowCount()-1 ||
destinationChild < 0 || destinationChild > rowCount() )
{
return false;
}
beginMoveRows(sourceParent, sourceRow, sourceRow, destinationParent, destinationChild);
QList<QStandardItem*> rowItems = takeRow(sourceRow);
insertRow(destinationChild, rowItems);
endMoveRows();
return true;
}
</code></pre>
<p>With the above c++ model code, it crashes at the release handler in QML:</p>
<p><a href="https://i.stack.imgur.com/vtZmm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vtZmm.png" alt="enter image description here" /></a></p>
<p>I've tried other things to see the effect, no crashes, but also not the expected behaviour.</p>
<ul>
<li>deleting a single row (which deletes 2 (!) rows in the QML ListView)</li>
<li>deleting a single row without begin/end calls (deletes 1 rows in the QML ListView, but can't be right)</li>
<li>remove and insert a single row without begin/end calls (QML ListView looks fine for a while but comes out of sync after a few moves)</li>
</ul>
<p>Basically all I want to do is to save the ListView state via the c++ model, after all that is a standard use case and something simple must be wrong on my side, yet I can't see it.</p>
|
[
{
"answer_id": 74618746,
"author": "user2366975",
"author_id": 2366975,
"author_profile": "https://Stackoverflow.com/users/2366975",
"pm_score": 0,
"selected": false,
"text": "pageItemDragOperationStartIndex pageItemDragOperationFinalIndex QStandardItemModel begin/end"
},
{
"answer_id": 74622324,
"author": "Stephen Quan",
"author_id": 881441,
"author_profile": "https://Stackoverflow.com/users/881441",
"pm_score": 1,
"selected": false,
"text": "DelegateModel DelegateModelGroup allIndex DelegateModel MouseArea DropArea MouseArea DropArea import QtQuick\nimport QtQuick.Controls\nimport QtQuick.Layouts\n\nPage {\n property int activeMouseArea: -1\n ListView {\n id: listView\n width: 420\n height: parent.height\n model: SampleDelegateModel { }\n ScrollBar.vertical: ScrollBar {\n width: 20\n policy: ScrollBar.AlwaysOn\n }\n }\n footer: Text { id: dbg }\n}\n\n// SampleData.qml\nimport QtQuick\nimport QtQuick.Controls\n\nListModel {\n ListElement { name: \"Steve Jobs\" }\n ListElement { name: \"Jeff Bezos\" }\n ListElement { name: \"Bill Gates\" }\n ListElement { name: \"Elon Musk\" }\n}\n\n// SampleDelegateModel.qml\nimport QtQuick\nimport QtQuick.Controls\nimport QtQml.Models\n\nDelegateModel {\n id: delegateModel\n model: SampleData { }\n delegate: SampleDelegate { }\n groups: [\n DelegateModelGroup {\n id: allItems\n name: \"all\"\n includeByDefault: true\n }\n ]\n filterOnGroup: \"all\"\n function moveItem(from, to) {\n dbg.text = `Debugging: moveItem(${from},${to})`;\n allItems.move(from, to);\n }\n}\n\n// SampleDelegate.qml\nimport QtQuick\nimport QtQuick.Controls\nimport QtQml.Models\n\nRectangle {\n property int allIndex: DelegateModel.allIndex\n width: 400\n height: labelText.height + 20\n border.color: \"grey\"\n z: mouseArea.drag.active || mouseArea.pressed ? 2 : 1\n property int dragTo: -1\n Drag.active: mouseArea.drag.active\n\n Text {\n id: labelText\n anchors.centerIn: parent\n text: allIndex + \": [\" + index + \"] \" + name\n }\n\n DropArea {\n anchors.fill: parent\n onEntered: drag.source.dragTo = allIndex\n }\n\n MouseArea {\n id: mouseArea\n anchors.fill: parent\n drag.target: parent\n property point startPoint\n enabled: activeMouseArea === -1\n onPressed: {\n activeMouseArea = allIndex;\n dragTo = -1;\n startPoint = Qt.point(parent.x, parent.y);\n }\n onReleased: {\n activeMouseArea = -1;\n [parent.x,parent.y] = [startPoint.x, startPoint.y];\n Qt.callLater(delegateModel.moveItem, allIndex, dragTo);\n }\n }\n}\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74607500",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2366975/"
] |
74,607,505
|
<p>I wanted to ask. if there is an efficient way to split a string and ignore inner strings of is</p>
<p>Example:
I get a string in this format:</p>
<pre><code>s = 'name,12345,Hello,\"12,34,56\",World'
</code></pre>
<p>and the output I want, is:</p>
<pre><code>['name', '12345', 'Hello', "12,34,56", 'World']
</code></pre>
<p>by splitting at the "," the numbers become separated:</p>
<pre><code>['name', '12345', 'Hello', '"12', '34', '56"', 'World']
</code></pre>
<p>I know I could split at \" and split the first and the third part separately, but this seems kind of inefficient to me</p>
|
[
{
"answer_id": 74607547,
"author": "Wolric",
"author_id": 20163209,
"author_profile": "https://Stackoverflow.com/users/20163209",
"pm_score": 2,
"selected": false,
"text": "\", \" split >>> s = 'name, 12345, Hello, \\\"12,34,56\\\", World'\n>>> print(s.split(\", \"))\n['name', '12345', 'Hello', '\"12,34,56\"', 'World']\n"
},
{
"answer_id": 74607574,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 1,
"selected": false,
"text": "csv import csv\nfrom io import StringIO\n\ns = 'name, 12345, Hello, \"12,34,56\", World'\n\nprint(next(csv.reader(StringIO(s), skipinitialspace=True)))\n ['name', '12345', 'Hello', '12,34,56', 'World']\n"
},
{
"answer_id": 74607578,
"author": "Hai Vu",
"author_id": 459745,
"author_profile": "https://Stackoverflow.com/users/459745",
"pm_score": 2,
"selected": false,
"text": "csv import csv\n\nout = next(csv.reader([s], skipinitialspace=True))\n# out is\n# ['name', '12345', 'Hello', '12,34,56', 'World']\n csv csv.reader skipinitialspace"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74607505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20627803/"
] |
74,607,510
|
<p><a href="https://i.stack.imgur.com/poCxI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/poCxI.png" alt="enter image description here" /></a>I am using flutter. I would like to navigate between pages of bottom nav-bar from inside the body of page.
Not to create a new screen on top of it. And carry data between pages.
I am using classic bottom navbar in flutter with pages in body of scaffold.</p>
<p>Something like this.</p>
<pre><code>import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
static const String _title = 'Flutter Code Sample';
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: _title,
home: MyStatefulWidget(),
);
}
}
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({super.key});
@override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
int _selectedIndex = 0;
static const TextStyle optionStyle =
TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
static const List<Widget> _widgetOptions = <Widget>[
Text(
'Index 0: Home',
style: optionStyle,
),
Text(
'Index 1: Business',
style: optionStyle,
),
Text(
'Index 2: School',
style: optionStyle,
),
];
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('BottomNavigationBar Sample'),
),
body: Center(
child: _widgetOptions.elementAt(_selectedIndex),
),
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.business),
label: 'Business',
),
BottomNavigationBarItem(
icon: Icon(Icons.school),
label: 'School',
),
],
currentIndex: _selectedIndex,
selectedItemColor: Colors.amber[800],
onTap: _onItemTapped,
),
);
}
}
</code></pre>
<p>I tried pageview but with that I can switch between pages only on swipe and cant send data between them.</p>
|
[
{
"answer_id": 74607547,
"author": "Wolric",
"author_id": 20163209,
"author_profile": "https://Stackoverflow.com/users/20163209",
"pm_score": 2,
"selected": false,
"text": "\", \" split >>> s = 'name, 12345, Hello, \\\"12,34,56\\\", World'\n>>> print(s.split(\", \"))\n['name', '12345', 'Hello', '\"12,34,56\"', 'World']\n"
},
{
"answer_id": 74607574,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 1,
"selected": false,
"text": "csv import csv\nfrom io import StringIO\n\ns = 'name, 12345, Hello, \"12,34,56\", World'\n\nprint(next(csv.reader(StringIO(s), skipinitialspace=True)))\n ['name', '12345', 'Hello', '12,34,56', 'World']\n"
},
{
"answer_id": 74607578,
"author": "Hai Vu",
"author_id": 459745,
"author_profile": "https://Stackoverflow.com/users/459745",
"pm_score": 2,
"selected": false,
"text": "csv import csv\n\nout = next(csv.reader([s], skipinitialspace=True))\n# out is\n# ['name', '12345', 'Hello', '12,34,56', 'World']\n csv csv.reader skipinitialspace"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74607510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20499509/"
] |
74,607,545
|
<p>I keep saving a file to <code>$(Build.ArtifactStagingDirectory)</code> but when checking using <code>Get-ChildItem</code>, the directory is empty. Also, publishing doesn't produce anything. Just an empty directory.</p>
<p>Is the only way to save files to that directory is using copy task?</p>
|
[
{
"answer_id": 74607547,
"author": "Wolric",
"author_id": 20163209,
"author_profile": "https://Stackoverflow.com/users/20163209",
"pm_score": 2,
"selected": false,
"text": "\", \" split >>> s = 'name, 12345, Hello, \\\"12,34,56\\\", World'\n>>> print(s.split(\", \"))\n['name', '12345', 'Hello', '\"12,34,56\"', 'World']\n"
},
{
"answer_id": 74607574,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 1,
"selected": false,
"text": "csv import csv\nfrom io import StringIO\n\ns = 'name, 12345, Hello, \"12,34,56\", World'\n\nprint(next(csv.reader(StringIO(s), skipinitialspace=True)))\n ['name', '12345', 'Hello', '12,34,56', 'World']\n"
},
{
"answer_id": 74607578,
"author": "Hai Vu",
"author_id": 459745,
"author_profile": "https://Stackoverflow.com/users/459745",
"pm_score": 2,
"selected": false,
"text": "csv import csv\n\nout = next(csv.reader([s], skipinitialspace=True))\n# out is\n# ['name', '12345', 'Hello', '12,34,56', 'World']\n csv csv.reader skipinitialspace"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74607545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17460932/"
] |
74,607,587
|
<p>trying to create a function which generates pairs of users from list. Everyone have to get a pair.
Example list of user IDs:</p>
<pre><code>list = [123, 456, 789]
...smth...
result = {123:456, 456:789, 789:123} — OK
</code></pre>
<pre><code>list = [123, 456, 789]
...smth...
result = {123:456, 456:123, 789:789} — BAD
</code></pre>
<pre><code>list = [123, 456, 789, 234, 678]
...smth...
result = {123:456, 456:123, xxxxx} - BAD
</code></pre>
<p>Trying to do this in python but cant find a solution</p>
<p>Tried lists, sets, dicts, but cant find an alghoritm</p>
|
[
{
"answer_id": 74607547,
"author": "Wolric",
"author_id": 20163209,
"author_profile": "https://Stackoverflow.com/users/20163209",
"pm_score": 2,
"selected": false,
"text": "\", \" split >>> s = 'name, 12345, Hello, \\\"12,34,56\\\", World'\n>>> print(s.split(\", \"))\n['name', '12345', 'Hello', '\"12,34,56\"', 'World']\n"
},
{
"answer_id": 74607574,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 1,
"selected": false,
"text": "csv import csv\nfrom io import StringIO\n\ns = 'name, 12345, Hello, \"12,34,56\", World'\n\nprint(next(csv.reader(StringIO(s), skipinitialspace=True)))\n ['name', '12345', 'Hello', '12,34,56', 'World']\n"
},
{
"answer_id": 74607578,
"author": "Hai Vu",
"author_id": 459745,
"author_profile": "https://Stackoverflow.com/users/459745",
"pm_score": 2,
"selected": false,
"text": "csv import csv\n\nout = next(csv.reader([s], skipinitialspace=True))\n# out is\n# ['name', '12345', 'Hello', '12,34,56', 'World']\n csv csv.reader skipinitialspace"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74607587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16750101/"
] |
74,607,626
|
<p>I am just getting started with REST API and I have a few question. I am not sure exactly when it's best to use query parameters or path parameters or to send data in the body?</p>
<p>Right now I am designing a social media platform, and for example I don't know if when a user adds a comment, how should he use it? Is adding it in the request body the best option?</p>
<p>Please, also explain in general, not only for this example. Thank you!</p>
|
[
{
"answer_id": 74607547,
"author": "Wolric",
"author_id": 20163209,
"author_profile": "https://Stackoverflow.com/users/20163209",
"pm_score": 2,
"selected": false,
"text": "\", \" split >>> s = 'name, 12345, Hello, \\\"12,34,56\\\", World'\n>>> print(s.split(\", \"))\n['name', '12345', 'Hello', '\"12,34,56\"', 'World']\n"
},
{
"answer_id": 74607574,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 1,
"selected": false,
"text": "csv import csv\nfrom io import StringIO\n\ns = 'name, 12345, Hello, \"12,34,56\", World'\n\nprint(next(csv.reader(StringIO(s), skipinitialspace=True)))\n ['name', '12345', 'Hello', '12,34,56', 'World']\n"
},
{
"answer_id": 74607578,
"author": "Hai Vu",
"author_id": 459745,
"author_profile": "https://Stackoverflow.com/users/459745",
"pm_score": 2,
"selected": false,
"text": "csv import csv\n\nout = next(csv.reader([s], skipinitialspace=True))\n# out is\n# ['name', '12345', 'Hello', '12,34,56', 'World']\n csv csv.reader skipinitialspace"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74607626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14546517/"
] |
74,607,663
|
<p>I have a df as follows.</p>
<pre><code>TimeStamp,Value
t1,akak
t2,bb
t3,vvv
t5,ff
t6,44
t7,99
t8,kfkkf
t9,ff
t10,oo
</code></pre>
<p>I want to split df into sizes of 2 rows and assign class as group number.</p>
<pre><code>TimeStamp,Value, class
t1,akak,c1
t2,bb,c1
t3,vvv,c2
t4,ff,c2
t5,44,c3
t6,99,c3
t7,kfkkf,c4
t8,ff,c4
t9,oo,c5
t10,oo,c5
</code></pre>
<p>One approach is to iterate and do it one at a time. Was thinking of there is inbuilt way in pandas to do it</p>
|
[
{
"answer_id": 74607547,
"author": "Wolric",
"author_id": 20163209,
"author_profile": "https://Stackoverflow.com/users/20163209",
"pm_score": 2,
"selected": false,
"text": "\", \" split >>> s = 'name, 12345, Hello, \\\"12,34,56\\\", World'\n>>> print(s.split(\", \"))\n['name', '12345', 'Hello', '\"12,34,56\"', 'World']\n"
},
{
"answer_id": 74607574,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 1,
"selected": false,
"text": "csv import csv\nfrom io import StringIO\n\ns = 'name, 12345, Hello, \"12,34,56\", World'\n\nprint(next(csv.reader(StringIO(s), skipinitialspace=True)))\n ['name', '12345', 'Hello', '12,34,56', 'World']\n"
},
{
"answer_id": 74607578,
"author": "Hai Vu",
"author_id": 459745,
"author_profile": "https://Stackoverflow.com/users/459745",
"pm_score": 2,
"selected": false,
"text": "csv import csv\n\nout = next(csv.reader([s], skipinitialspace=True))\n# out is\n# ['name', '12345', 'Hello', '12,34,56', 'World']\n csv csv.reader skipinitialspace"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74607663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/93796/"
] |
74,607,690
|
<p>Why does this program output a negative value?</p>
<pre><code>#include <stdio.h>
int main() {
char a = 'a', b = 'b', c;
c = a + b;
printf("%d", c);
}
</code></pre>
<p>Shouldn't these values be converted into ASCII then added up?</p>
|
[
{
"answer_id": 74607716,
"author": "3Dave",
"author_id": 135769,
"author_profile": "https://Stackoverflow.com/users/135769",
"pm_score": 1,
"selected": false,
"text": "char -127 +128 char char 0 255 'a' 'b' 97 98 195 char -61 unsigned char #include <stdio.h>\n\nint main() {\n \n char a = 'a', b = 'b';\n unsigned char c;\n \n c = a + b;\n \n printf(\"%d\\n\",a);\n printf(\"%d\\n\",b);\n printf(\"%d\\n\", c);\n\n}\n 97\n98\n195\n"
},
{
"answer_id": 74607784,
"author": "insaneThOughTS",
"author_id": 20628090,
"author_profile": "https://Stackoverflow.com/users/20628090",
"pm_score": 0,
"selected": false,
"text": "unsigned char"
},
{
"answer_id": 74611559,
"author": "Elia Karrer",
"author_id": 17653989,
"author_profile": "https://Stackoverflow.com/users/17653989",
"pm_score": 1,
"selected": false,
"text": "a = 97\nb = 98\na+b = 195\n 195 = 0b11000011\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74607690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20628040/"
] |
74,607,691
|
<p>I am trying to copy one dynamically reserved array into another, both of which are placed in a vector. But it does not work. Why?</p>
<pre><code>struct A {
int *p;
};
int main()
{
vector<A> v;
A test;
test.p = new int[5];
//fill the array
for (int i = 0; i < 5; i++)
test.p[i] = i;
v.push_back(test);
A test2;
test2.p = new int[10];
//fill the array
for (int i = 0; i < 10; i++)
test2.p[i] = i;
delete[] test.p;
//reallocate test to test2
test.p = new int[10];
//copy test2 to test
for (int i = 0; i < 10; i++)
test.p[i] = test2.p[i];
//delete test2
delete[] test2.p;
//print the array
for (int i = 0; i < 10; i++)
cout << v[0].p[i] << endl;
return 0;
}
</code></pre>
<p>My output is:</p>
<pre class="lang-none prettyprint-override"><code>0
0
-997294064
32767
4
0
33
0
-997220688
32767
</code></pre>
|
[
{
"answer_id": 74607817,
"author": "Ranoiaetep",
"author_id": 12861639,
"author_profile": "https://Stackoverflow.com/users/12861639",
"pm_score": 2,
"selected": true,
"text": "A test test new int[10] test.p v[0].p = test.p;\n"
},
{
"answer_id": 74607857,
"author": "Ryan Haining",
"author_id": 1013719,
"author_profile": "https://Stackoverflow.com/users/1013719",
"pm_score": 0,
"selected": false,
"text": "A test;\ntest.p = new int[5]{};\n\nA test_copy = test; // vector::push_back creates a copy as well\n\ndelete[] test.p; // deletes where test.p and test_copy.p point\n\ntest.p = new int[10]{}; // test_copy.p is still pointing at the deleted address\n\nfor (int i = 0; i < 10; i++) {\n // test.p is valid, but test_copy.p is not.\n // use-after-free\n std::cout << test_copy.p[i] << '\\n';\n}\n test test.p test.p p"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74607691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12999319/"
] |
74,607,699
|
<p>Binding to observable property does not work when I try to create my own custom behavior. Neither it does in any of community mvvm toolkit platform behaviors:</p>
<p><a href="https://github.com/CommunityToolkit/Maui/tree/main/src/CommunityToolkit.Maui/Behaviors/PlatformBehaviors" rel="nofollow noreferrer">https://github.com/CommunityToolkit/Maui/tree/main/src/CommunityToolkit.Maui/Behaviors/PlatformBehaviors</a></p>
<p>Take for example <code>StatusBarBehavior</code>, write something like</p>
<pre><code> <ContentPage.Behaviors>
<toolkit:StatusBarBehavior StatusBarColor="{Binding StatusBarColorProp}" StatusBarStyle="LightContent" />
</ContentPage.Behaviors>
</code></pre>
<p>create the property in your view model</p>
<pre><code> [ObservableProperty]
private Color _statusBarColorProp;
</code></pre>
<p>you'll see status bar color does not change with <code>StatusBarBehavior</code> property change in runtime. Same for all the rest behaviors. It works fine for non-bindings setters like <code>StatusBarColor="Red"</code>.</p>
<p>I wonder if it's a feature or a bug, or I'm missing something.</p>
<p><strong>UPDATE</strong> the issue is reported <a href="https://github.com/dotnet/maui/issues/11729" rel="nofollow noreferrer">https://github.com/dotnet/maui/issues/11729</a></p>
|
[
{
"answer_id": 74608621,
"author": "Alexandar May - MSFT",
"author_id": 9644964,
"author_profile": "https://Stackoverflow.com/users/9644964",
"pm_score": 3,
"selected": true,
"text": "StatusBarColor StatusBarColor=\"Red\" <ContentPage.Behaviors> \n <toolkit:StatusBarBehavior x:Name=\"statusBar\" ></toolkit:StatusBarBehavior>\n </ContentPage.Behaviors>\n \nprivate void OnCounterClicked(object sender, EventArgs e) \n{\n statusBar.StatusBarColor = Colors.Red;\n}\n StatusBarColor"
},
{
"answer_id": 74608977,
"author": "ToolmakerSteve",
"author_id": 199364,
"author_profile": "https://Stackoverflow.com/users/199364",
"pm_score": 0,
"selected": false,
"text": "static public BindableProperty MyValueProperty = BindableProperty.Create(...,\n propertyChanged: (bindable, oldValue, newValue) =>\n {\n var it = (MyClass)bindable;\n // If it is changing, force explicit OnPropertyChanged. This is usually redundant,\n // but might help a binding \"cascade\" to dependencies.\n if (!(MyType)newValue.Equals((MyType)oldvalue))\n it.OnPropertyChanged(nameof(MyValue));\n });\npublic MyType MyValue\n{\n get => (MyType)GetValue(MyValueProperty);\n set => SetValue(MyValueProperty, value);\n}\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74607699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/738999/"
] |
74,607,741
|
<p>This is easy to do in R and I am wondering if it is straight forward in Python and I am just missing something, but how do you create a vector of NaN values and Null values in Python? I am trying to do this using the np.full function.</p>
<p>R Code:</p>
<pre><code>vec <- vector("character", 15)
vec[1:15] <- NA
vec
</code></pre>
<p>Python Code</p>
<pre><code>unknowns = np.full(shape = 5, fill_value = ???, dtype = 'str')
'''test if fill value worked or not'''
random.seed(1177)
categories = np.random.choice(['web', 'software', 'hardware', 'biotech'], size = 15, replace = True)
categories = np.concatenate([categories, unknowns])
example = pd.DataFrame(data = {'categories': categories})
example['transformed'] = [ x if pd.isna(x) == False else 'unknown' for x in example['categories']]
print(example['transformed'].value_counts())
</code></pre>
<p>This should lead to 5 counts of unknown in the value counts total. Ideally I would like to know how to write this fill_value for NaN and Null and know whether it differs for variable types. I have tried np.nan with and without the string data type. I have tried None and Null with and without quotes. I cannot think of anything else to try and I am starting to wonder if it is possible. Thank you in advance and I apologize if this question is already addressed and for my lack of knowledge in this area.</p>
|
[
{
"answer_id": 74607763,
"author": "Alexander L. Hayes",
"author_id": 12439119,
"author_profile": "https://Stackoverflow.com/users/12439119",
"pm_score": 0,
"selected": false,
"text": "numpy np.nan import numpy as np\n\nv1 = np.array(['a', 'b', 'c'])\nv1[0] = np.nan\n# v1 = array(['n', 'b', 'c'], dtype='<U1')\n\nv2 = np.array(['ab', 'cd', 'ef'])\nv2[0] = np.nan\n# v2 = array(['na', 'cd', 'ef'], dtype='<U2')\n\nv3 = np.array(['abc', 'def', 'ghi'])\nv3[0] = np.nan\n# v3 = array(['nan', 'def', 'ghi'], dtype='<U3')\n pandas import pandas as pd\n\ndf = pd.DataFrame({\"x\": [pd.NA, \"Hello\", \"World\"]})\n"
},
{
"answer_id": 74607811,
"author": "govordovsky",
"author_id": 12314390,
"author_profile": "https://Stackoverflow.com/users/12314390",
"pm_score": 3,
"selected": true,
"text": "None np.nan np.full(shape=5, fill_value=None)\nnp.full(shape=5, fill_value=np.nan)\n import numpy as np\nimport pandas as pd\n\nunknowns = np.full(shape=5, fill_value=None)\ncategories = np.random.choice(['web', 'software', 'hardware', 'biotech'], size = 15, replace = True)\ncategories = np.concatenate([categories, unknowns])\nexample = pd.DataFrame(data = {'categories': categories})\nexample['transformed'] = [ x if pd.isna(x) == False else 'unknown' for x in example['categories']]\n\nprint(example['transformed'].value_counts())\n example['transformed'] = [ x if pd.isna(x) == False else 'unknown' for x in example['categories']] example['transformed'] = example.categories.apply(lambda s: s if s else 'unknown')"
},
{
"answer_id": 74608179,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 0,
"selected": false,
"text": "s = pd.Series(index=range(15))\n 0 NaN\n1 NaN\n2 NaN\n3 NaN\n4 NaN\n5 NaN\n6 NaN\n7 NaN\n8 NaN\n9 NaN\n10 NaN\n11 NaN\n12 NaN\n13 NaN\n14 NaN\ndtype: float64\n s = pd.Series(index=range(15), dtype='string')\n 0 <NA>\n1 <NA>\n2 <NA>\n3 <NA>\n4 <NA>\n5 <NA>\n6 <NA>\n7 <NA>\n8 <NA>\n9 <NA>\n10 <NA>\n11 <NA>\n12 <NA>\n13 <NA>\n14 <NA>\ndtype: string\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74607741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14815520/"
] |
74,607,750
|
<p>I have a view that has the days of the week, which should increment when the user toggles the arrows (increment either to the next or prev day).</p>
<p>I first grab the current day of the week and format to a String. Then save to my var currentWeekday:</p>
<pre class="lang-swift prettyprint-override"><code>class GrabCurrentDate: ObservableObject {
@Published var currentWeekday = Date().dayNumberOfWeek()!
func currentDate() {
let date = Date()
let formatter = DateFormatter()
formatter.timeStyle = .short
let dateString = formatter.string(from: Date())
//set day of week
currentWeekday = Date().dayNumberOfWeek()!
}
}
</code></pre>
<p>Then I dump the days of the week in a switch statement, assigning the days to display in the view as a string:</p>
<pre class="lang-swift prettyprint-override"><code>extension Date {
func dayNumberOfWeek() -> Int? {
return Calendar.current.dateComponents([.weekday], from: self).weekday! - 1
}
}
func weekdayAsString(date: Int) -> String {
switch Date().dayNumberOfWeek() {
case 0:
return "Sunday"
case 1:
return "Monday"
case 2:
return "Tuesday"
case 3:
return "Wednesday"
case 4:
return "Thursday"
case 5:
return "Friday"
case 6:
return "Saturday"
default:
return ""
}
}
</code></pre>
<p>Lastly my view:</p>
<pre class="lang-swift prettyprint-override"><code>struct testView: View {
@ObservedObject var currentDate = GrabCurrentDate()
func weekdayAsString(date: Int) -> String {
// Defined in the code above
}
var body: some View {
HStack {
Image(systemName: "arrow.left")
.onTapGesture{
currentDate.currentWeekday -= 1
print(currentDate.currentWeekday )
}
Text(weekdayAsString(date: currentDate.currentWeekday)) // << display current day of week
Image(systemName: "arrow.right")
.onTapGesture{
currentDate.currentWeekday += 1
}
}
}
}
</code></pre>
<p>When I go to increment, the published var updates correctly but the view does not. Thanks in advance for the help.</p>
|
[
{
"answer_id": 74607763,
"author": "Alexander L. Hayes",
"author_id": 12439119,
"author_profile": "https://Stackoverflow.com/users/12439119",
"pm_score": 0,
"selected": false,
"text": "numpy np.nan import numpy as np\n\nv1 = np.array(['a', 'b', 'c'])\nv1[0] = np.nan\n# v1 = array(['n', 'b', 'c'], dtype='<U1')\n\nv2 = np.array(['ab', 'cd', 'ef'])\nv2[0] = np.nan\n# v2 = array(['na', 'cd', 'ef'], dtype='<U2')\n\nv3 = np.array(['abc', 'def', 'ghi'])\nv3[0] = np.nan\n# v3 = array(['nan', 'def', 'ghi'], dtype='<U3')\n pandas import pandas as pd\n\ndf = pd.DataFrame({\"x\": [pd.NA, \"Hello\", \"World\"]})\n"
},
{
"answer_id": 74607811,
"author": "govordovsky",
"author_id": 12314390,
"author_profile": "https://Stackoverflow.com/users/12314390",
"pm_score": 3,
"selected": true,
"text": "None np.nan np.full(shape=5, fill_value=None)\nnp.full(shape=5, fill_value=np.nan)\n import numpy as np\nimport pandas as pd\n\nunknowns = np.full(shape=5, fill_value=None)\ncategories = np.random.choice(['web', 'software', 'hardware', 'biotech'], size = 15, replace = True)\ncategories = np.concatenate([categories, unknowns])\nexample = pd.DataFrame(data = {'categories': categories})\nexample['transformed'] = [ x if pd.isna(x) == False else 'unknown' for x in example['categories']]\n\nprint(example['transformed'].value_counts())\n example['transformed'] = [ x if pd.isna(x) == False else 'unknown' for x in example['categories']] example['transformed'] = example.categories.apply(lambda s: s if s else 'unknown')"
},
{
"answer_id": 74608179,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 0,
"selected": false,
"text": "s = pd.Series(index=range(15))\n 0 NaN\n1 NaN\n2 NaN\n3 NaN\n4 NaN\n5 NaN\n6 NaN\n7 NaN\n8 NaN\n9 NaN\n10 NaN\n11 NaN\n12 NaN\n13 NaN\n14 NaN\ndtype: float64\n s = pd.Series(index=range(15), dtype='string')\n 0 <NA>\n1 <NA>\n2 <NA>\n3 <NA>\n4 <NA>\n5 <NA>\n6 <NA>\n7 <NA>\n8 <NA>\n9 <NA>\n10 <NA>\n11 <NA>\n12 <NA>\n13 <NA>\n14 <NA>\ndtype: string\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74607750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8023463/"
] |
74,607,769
|
<p>I have a data looks like this</p>
<pre><code>df <- structure(list(Data = c("D1", "D2", "D3", "D4", "D5", "D6", "D7",
"D8", "D9", "D10", "D11", "D12", "D13", "D14", "D15", "D16",
"D17", "D18", "D19", "D20", "D21", "D22", "D23", "D24", "D25",
"D26", "D27", "D28", "D29", "D30", "D31", "D32", "D33", "D34",
"D35", "D36", "D37", "D38", "D39", "D40", "D41", "D42", "D43",
"D44", "D45", "D46", "D47", "D48", "D49", "D50", "D51", "D52",
"D53", "D54", "D55", "D56", "D57", "D58", "D59", "D60", "D61",
"D62", "D63", "D64", "D65", "D66", "D67", "D68", "D69", "D70",
"D71", "D72", "D73", "D74", "D75", "D76", "D77", "D78", "D79",
"D80", "D81", "D82", "D83", "D84", "D85", "D86", "D87", "D88",
"D89", "D90", "D91", "D92", "D93", "D94", "D95", "D96", "D97",
"D98"), Response = c(18.11, 17.6, 16.14, 16.02, 14.73, 14.07,
13.41, 13.08, 12.73, 12.51, 11.53, 9.85, 9.78, 9.74, 8.98, 1.54,
1.54, 1.51, 1.51, 1.49, 1.49, 1.49, 1.44, 1.44, 1.39, 1.37, 1.36,
1.35, 1.34, 1.34, 1.33, 1.33, 1.31, 1.3, 1.29, 1.26, 1.23, 1.21,
1.19, 1.18, 1.14, 1.12, 1.07, 1.05, 1.03, 1.03, 1.03, 1.02, 1.01,
1, 0.99, 0.98, 0.95, 0.94, 0.93, 0.92, 0.91, 0.87, 0.83, 0.83,
0.81, 0.8, 0.8, 0.79, 0.78, 0.76, 0.76, 0.75, 0.75, 0.73, 0.73,
0.71, 0.69, 0.68, 0.67, 0.67, 0.64, 0.63, 0.63, -11.6, -11.6,
-11.6, -11.7, -11.7, -11.7, -11.8, -11.9, -11.9, -12, -12.2,
-12.3, -12.4, -12.4, -12.5, -12.5, -12.6, -12.6, -12.7), SD = c(8.98,
8.19, 2.57, 8.36, 2.14, 5.51, 3.01, 9.8, 6.88, 3.21, 11.35, 5.6,
13.29, 4.9, 9.45, 11.06, 5.41, 28.78, 13.46, 4.23, 12.24, 1.41,
11.03, 11.29, 2.17, 7.11, 3.08, 1.8, 12.09, 4.79, 1.01, 3.69,
3.62, 3.06, 3.12, 13.19, 4.28, 12.05, 3.96, 13.4, 3.02, 7.97,
12, 3.91, 1.85, 3.96, 1.79, 2.67, 0.37, 7.45, 9.57, 1.95, 1.82,
3.02, 6.97, 6.73, 1.22, 5.45, 4.9, 2.48, 6.88, 3.81, 1.86, 1.83,
7.56, 11.25, 2.72, 3.68, 2.41, 4.44, 2.59, 6.24, 2.56, 3.96,
10.56, 1.65, 7.22, 4.12, 4.01, 3.4, 2.8, 0.92, 9.58, 1.17, 1.36,
0.91, 5.8, 4.26, 3.48, 3.7, 11.99, 5.77, 11.06, 3.09, 0.12, 3.18,
5.49, 5.81)), class = "data.frame", row.names = c(NA, -98L))
</code></pre>
<p>I am trying to plot in one figure the top 5 positive with their sd and top 5 negative with their sd</p>
<p>any suggestion?</p>
<p>basically when I try to plot, it even forget the sorting</p>
<pre><code>ggplot(data=df, aes(x=Data, y=Response,group=1)) +
geom_line()+
geom_point()
</code></pre>
|
[
{
"answer_id": 74607864,
"author": "jared_mamrot",
"author_id": 12957340,
"author_profile": "https://Stackoverflow.com/users/12957340",
"pm_score": 2,
"selected": false,
"text": "library(tidyverse)\nlibrary(ggrepel)\n\ndf <- structure(list(Data = c(\"D1\", \"D2\", \"D3\", \"D4\", \"D5\", \"D6\", \"D7\", \n \"D8\", \"D9\", \"D10\", \"D11\", \"D12\", \"D13\", \"D14\", \"D15\", \"D16\", \n \"D17\", \"D18\", \"D19\", \"D20\", \"D21\", \"D22\", \"D23\", \"D24\", \"D25\", \n \"D26\", \"D27\", \"D28\", \"D29\", \"D30\", \"D31\", \"D32\", \"D33\", \"D34\", \n \"D35\", \"D36\", \"D37\", \"D38\", \"D39\", \"D40\", \"D41\", \"D42\", \"D43\", \n \"D44\", \"D45\", \"D46\", \"D47\", \"D48\", \"D49\", \"D50\", \"D51\", \"D52\", \n \"D53\", \"D54\", \"D55\", \"D56\", \"D57\", \"D58\", \"D59\", \"D60\", \"D61\", \n \"D62\", \"D63\", \"D64\", \"D65\", \"D66\", \"D67\", \"D68\", \"D69\", \"D70\", \n \"D71\", \"D72\", \"D73\", \"D74\", \"D75\", \"D76\", \"D77\", \"D78\", \"D79\", \n \"D80\", \"D81\", \"D82\", \"D83\", \"D84\", \"D85\", \"D86\", \"D87\", \"D88\", \n \"D89\", \"D90\", \"D91\", \"D92\", \"D93\", \"D94\", \"D95\", \"D96\", \"D97\", \n \"D98\"), Response = c(18.11, 17.6, 16.14, 16.02, 14.73, 14.07, \n 13.41, 13.08, 12.73, 12.51, 11.53, 9.85, 9.78, 9.74, 8.98, 1.54, \n 1.54, 1.51, 1.51, 1.49, 1.49, 1.49, 1.44, 1.44, 1.39, 1.37, 1.36, \n 1.35, 1.34, 1.34, 1.33, 1.33, 1.31, 1.3, 1.29, 1.26, 1.23, 1.21, \n 1.19, 1.18, 1.14, 1.12, 1.07, 1.05, 1.03, 1.03, 1.03, 1.02, 1.01, \n 1, 0.99, 0.98, 0.95, 0.94, 0.93, 0.92, 0.91, 0.87, 0.83, 0.83, \n 0.81, 0.8, 0.8, 0.79, 0.78, 0.76, 0.76, 0.75, 0.75, 0.73, 0.73, \n 0.71, 0.69, 0.68, 0.67, 0.67, 0.64, 0.63, 0.63, -11.6, -11.6, \n -11.6, -11.7, -11.7, -11.7, -11.8, -11.9, -11.9, -12, -12.2, \n -12.3, -12.4, -12.4, -12.5, -12.5, -12.6, -12.6, -12.7), SD = c(8.98, \n 8.19, 2.57, 8.36, 2.14, 5.51, 3.01, 9.8, 6.88, 3.21, 11.35, 5.6, \n 13.29, 4.9, 9.45, 11.06, 5.41, 28.78, 13.46, 4.23, 12.24, 1.41, \n 11.03, 11.29, 2.17, 7.11, 3.08, 1.8, 12.09, 4.79, 1.01, 3.69, \n 3.62, 3.06, 3.12, 13.19, 4.28, 12.05, 3.96, 13.4, 3.02, 7.97, \n 12, 3.91, 1.85, 3.96, 1.79, 2.67, 0.37, 7.45, 9.57, 1.95, 1.82, \n 3.02, 6.97, 6.73, 1.22, 5.45, 4.9, 2.48, 6.88, 3.81, 1.86, 1.83, \n 7.56, 11.25, 2.72, 3.68, 2.41, 4.44, 2.59, 6.24, 2.56, 3.96, \n 10.56, 1.65, 7.22, 4.12, 4.01, 3.4, 2.8, 0.92, 9.58, 1.17, 1.36, \n 0.91, 5.8, 4.26, 3.48, 3.7, 11.99, 5.77, 11.06, 3.09, 0.12, 3.18, \n 5.49, 5.81)), class = \"data.frame\", row.names = c(NA, -98L))\ndf$Data <- factor(df$Data, levels = paste0(\"D\", 1:98), ordered = TRUE)\n\nggplot() +\n geom_line(data = df, aes(x = Data, y = Response, group = 1),\n alpha = 0.25) +\n geom_point(data = df, aes(x = Data, y = Response, group = 1),\n alpha = 0.25) +\n geom_line(data = df %>% slice_max(order_by = Response, n = 5),\n aes(x = Data, y = Response, group = 1)) +\n geom_point(data = df %>% slice_max(order_by = Response, n = 5),\n aes(x = Data, y = Response, group = 1)) +\n geom_linerange(data = df %>% slice_max(order_by = Response, n = 5),\n aes(x = Data, y = Response,\n ymin = Response - SD, ymax = Response + SD)) +\n geom_text_repel(data = df %>% slice_max(order_by = Response, n = 5),\n aes(x = Data, label = Data, y = Response),\n min.segment.length = 0, xlim = 10,\n force = 5, color = \"firebrick3\") +\n geom_line(data = df %>% slice_min(order_by = Response, n = 5),\n aes(x = Data, y = Response, group = 1)) +\n geom_point(data = df %>% slice_min(order_by = Response, n = 5),\n aes(x = Data, y = Response, group = 1)) +\n geom_linerange(data = df %>% slice_min(order_by = Response, n = 5),\n aes(x = Data, y = Response,\n ymin = Response - SD, ymax = Response + SD)) +\n geom_text_repel(data = df %>% slice_min(order_by = Response, n = 5),\n aes(x = Data, label = Data, y = Response),\n min.segment.length = 0, xlim = 80,\n force = 9, color = \"firebrick3\") +\n theme(axis.text.x = element_blank(),\n axis.ticks.x = element_blank())\n"
},
{
"answer_id": 74608285,
"author": "Andre Wildberg",
"author_id": 9462095,
"author_profile": "https://Stackoverflow.com/users/9462095",
"pm_score": 1,
"selected": false,
"text": "head tail library(ggplot2)\n\nggplot(rbind(head(df, 5), tail(df, 5))) + \n geom_col(aes(Data, Response)) + \n geom_errorbar(aes(Data, ymin = Response - SD, ymax = Response + SD), width=.2)\n dat <- rbind(head(df, 5), \n list(\"D6_MEAN\", mean(df[-c(1:5, (nrow(df)-4):(nrow(df))), 2]),\n mean(df[-c(1:5, (nrow(df)-4):(nrow(df))), 3])), tail(df, 5))\n\ndat$grp <- c(rep(\"top\", 5), \n paste(\"mean of\", nrow(df)-10, \"rows\"), rep(\"bottom\", 5))\n\ndat$grp <- factor(dat$grp, levels=unique(dat$grp))\n\nggplot(dat) + \n geom_col(aes(Data, Response, fill=grp)) + \n geom_errorbar(aes(Data, ymin = Response - SD, ymax = Response + SD), width=.2)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74607769",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5919561/"
] |
74,607,788
|
<p>I have a view in django that utilizes jQuery to retrieve some data from the backend once the user selects some filter options. After the data is retrieved I'm dynamically creating table rows and appending them to the table body. Each row contains data about a release, each release has a unique ID. I would like if the user clicked on any cell in a row, for it to navigate to another page with more information about the release, below is how I'm building the table:</p>
<pre><code> function updateTable(filtered_releases) {
var table_body = document.getElementById("release-table-body");
// append the new data to the table body
console.log("STARTING TO ADD RELEASES TO NEW TABLE BODY");
for (const release in filtered_releases) {
// get all the variables for the release
var new_release = filtered_releases[release];
var id = new_release['id'];
var release_type = new_release['release_type'];
var business_unit = new_release['business_unit'];
var product_line = new_release['product_line'];
var product_id = new_release['product_id'];
var deployment_project = release_type == "github" ? new_release['repo_name'] : new_release['deployment_project'];
var deployment_environment = new_release['deployment_environment'];
var deployment_version = new_release['version'];
// create the new row
var new_row = document.createElement("tr");
new_row.id = "release_" + id;
// checkbox
var td_checkbox = document.createElement("td");
var checkbox = document.createElement("input");
checkbox.type = "checkbox";
td_checkbox.appendChild(checkbox);
new_row.appendChild(td_checkbox);
// id
var td_id = document.createElement("td");
td_id.innerHTML = id;
td_id.addEventListener("click", function () { navigateToDeploymentView(id) });
new_row.appendChild(td_id);
// release_type
var td_release_type = document.createElement("td");
td_release_type.innerHTML = release_type;
td_release_type.addEventListener("click", function () { navigateToDeploymentView(id) });
new_row.appendChild(td_release_type);
// business_unit
var td_business_unit = document.createElement("td");
td_business_unit.innerHTML = business_unit;
td_business_unit.addEventListener("click", function () { navigateToDeploymentView(id) });
new_row.appendChild(td_business_unit);
// product_line
var td_product_line = document.createElement("td");
td_product_line.innerHTML = product_line;
td_product_line.addEventListener("click", function () { navigateToDeploymentView(id) });
new_row.appendChild(td_product_line);
// product_id
var td_product_id = document.createElement("td");
td_product_id.innerHTML = product_id;
td_product_id.addEventListener("click", function () { navigateToDeploymentView(id) });
new_row.appendChild(td_product_id);
// deployment_project
var td_deployment_project = document.createElement("td");
td_deployment_project.innerHTML = deployment_project;
td_deployment_project.addEventListener("click", function () { navigateToDeploymentView(id) });
new_row.appendChild(td_deployment_project);
// deployment_environment
var td_deployment_environment = document.createElement("td");
td_deployment_environment.innerHTML = deployment_environment;
td_deployment_environment.addEventListener("click", function () { navigateToDeploymentView(id) });
new_row.appendChild(td_deployment_environment);
// version
var td_version = document.createElement("td");
td_version.innerHTML = deployment_version;
td_version.addEventListener("click", function () { navigateToDeploymentView(id) });
new_row.appendChild(td_version);
// append this new row to the table body
table_body.appendChild(new_row);
}
console.log("FINISHED ADDING RELEASES TO NEW TABLE BODY");
}
</code></pre>
<p>For each cell in the rows I'm assigning the following onclick function, that accepts the id of the release which is assigned when I dynamically create the rows.</p>
<pre><code> function navigateToDeploymentView(id) {
window.location = '{{ base_url }}/deployment/?id=' + id;
}
</code></pre>
<p>However once the table is rendered, no matter what row I click on it will always take me to the page correlating to the ID of the last entry. So in <a href="https://i.stack.imgur.com/6fGB5.png" rel="nofollow noreferrer">this example image</a>, no matter what cell I click on for entries 467 and 468, it will direct me to the page with data about entry 469. So it seems the 'id' variable is being updated for all entries after the for loop makes its last iteration. Not sure how to fix this.</p>
<p>I tried setting up the onclick function in the following 2 other ways:</p>
<pre><code>// way 1
td_id.addEventListener("click", function () {
window.location = '{{ base_url }}/deployment/?id=' + id;
});
// way 2
td_id.onclick = function () {navigateToDeploymentView(id)}
</code></pre>
<p>I also tried a workaround where I would set each cells id equal to the release id, and passing in the cell to the function so I can access it's id that way, but it would still only pass in the data from the very last row.</p>
|
[
{
"answer_id": 74607864,
"author": "jared_mamrot",
"author_id": 12957340,
"author_profile": "https://Stackoverflow.com/users/12957340",
"pm_score": 2,
"selected": false,
"text": "library(tidyverse)\nlibrary(ggrepel)\n\ndf <- structure(list(Data = c(\"D1\", \"D2\", \"D3\", \"D4\", \"D5\", \"D6\", \"D7\", \n \"D8\", \"D9\", \"D10\", \"D11\", \"D12\", \"D13\", \"D14\", \"D15\", \"D16\", \n \"D17\", \"D18\", \"D19\", \"D20\", \"D21\", \"D22\", \"D23\", \"D24\", \"D25\", \n \"D26\", \"D27\", \"D28\", \"D29\", \"D30\", \"D31\", \"D32\", \"D33\", \"D34\", \n \"D35\", \"D36\", \"D37\", \"D38\", \"D39\", \"D40\", \"D41\", \"D42\", \"D43\", \n \"D44\", \"D45\", \"D46\", \"D47\", \"D48\", \"D49\", \"D50\", \"D51\", \"D52\", \n \"D53\", \"D54\", \"D55\", \"D56\", \"D57\", \"D58\", \"D59\", \"D60\", \"D61\", \n \"D62\", \"D63\", \"D64\", \"D65\", \"D66\", \"D67\", \"D68\", \"D69\", \"D70\", \n \"D71\", \"D72\", \"D73\", \"D74\", \"D75\", \"D76\", \"D77\", \"D78\", \"D79\", \n \"D80\", \"D81\", \"D82\", \"D83\", \"D84\", \"D85\", \"D86\", \"D87\", \"D88\", \n \"D89\", \"D90\", \"D91\", \"D92\", \"D93\", \"D94\", \"D95\", \"D96\", \"D97\", \n \"D98\"), Response = c(18.11, 17.6, 16.14, 16.02, 14.73, 14.07, \n 13.41, 13.08, 12.73, 12.51, 11.53, 9.85, 9.78, 9.74, 8.98, 1.54, \n 1.54, 1.51, 1.51, 1.49, 1.49, 1.49, 1.44, 1.44, 1.39, 1.37, 1.36, \n 1.35, 1.34, 1.34, 1.33, 1.33, 1.31, 1.3, 1.29, 1.26, 1.23, 1.21, \n 1.19, 1.18, 1.14, 1.12, 1.07, 1.05, 1.03, 1.03, 1.03, 1.02, 1.01, \n 1, 0.99, 0.98, 0.95, 0.94, 0.93, 0.92, 0.91, 0.87, 0.83, 0.83, \n 0.81, 0.8, 0.8, 0.79, 0.78, 0.76, 0.76, 0.75, 0.75, 0.73, 0.73, \n 0.71, 0.69, 0.68, 0.67, 0.67, 0.64, 0.63, 0.63, -11.6, -11.6, \n -11.6, -11.7, -11.7, -11.7, -11.8, -11.9, -11.9, -12, -12.2, \n -12.3, -12.4, -12.4, -12.5, -12.5, -12.6, -12.6, -12.7), SD = c(8.98, \n 8.19, 2.57, 8.36, 2.14, 5.51, 3.01, 9.8, 6.88, 3.21, 11.35, 5.6, \n 13.29, 4.9, 9.45, 11.06, 5.41, 28.78, 13.46, 4.23, 12.24, 1.41, \n 11.03, 11.29, 2.17, 7.11, 3.08, 1.8, 12.09, 4.79, 1.01, 3.69, \n 3.62, 3.06, 3.12, 13.19, 4.28, 12.05, 3.96, 13.4, 3.02, 7.97, \n 12, 3.91, 1.85, 3.96, 1.79, 2.67, 0.37, 7.45, 9.57, 1.95, 1.82, \n 3.02, 6.97, 6.73, 1.22, 5.45, 4.9, 2.48, 6.88, 3.81, 1.86, 1.83, \n 7.56, 11.25, 2.72, 3.68, 2.41, 4.44, 2.59, 6.24, 2.56, 3.96, \n 10.56, 1.65, 7.22, 4.12, 4.01, 3.4, 2.8, 0.92, 9.58, 1.17, 1.36, \n 0.91, 5.8, 4.26, 3.48, 3.7, 11.99, 5.77, 11.06, 3.09, 0.12, 3.18, \n 5.49, 5.81)), class = \"data.frame\", row.names = c(NA, -98L))\ndf$Data <- factor(df$Data, levels = paste0(\"D\", 1:98), ordered = TRUE)\n\nggplot() +\n geom_line(data = df, aes(x = Data, y = Response, group = 1),\n alpha = 0.25) +\n geom_point(data = df, aes(x = Data, y = Response, group = 1),\n alpha = 0.25) +\n geom_line(data = df %>% slice_max(order_by = Response, n = 5),\n aes(x = Data, y = Response, group = 1)) +\n geom_point(data = df %>% slice_max(order_by = Response, n = 5),\n aes(x = Data, y = Response, group = 1)) +\n geom_linerange(data = df %>% slice_max(order_by = Response, n = 5),\n aes(x = Data, y = Response,\n ymin = Response - SD, ymax = Response + SD)) +\n geom_text_repel(data = df %>% slice_max(order_by = Response, n = 5),\n aes(x = Data, label = Data, y = Response),\n min.segment.length = 0, xlim = 10,\n force = 5, color = \"firebrick3\") +\n geom_line(data = df %>% slice_min(order_by = Response, n = 5),\n aes(x = Data, y = Response, group = 1)) +\n geom_point(data = df %>% slice_min(order_by = Response, n = 5),\n aes(x = Data, y = Response, group = 1)) +\n geom_linerange(data = df %>% slice_min(order_by = Response, n = 5),\n aes(x = Data, y = Response,\n ymin = Response - SD, ymax = Response + SD)) +\n geom_text_repel(data = df %>% slice_min(order_by = Response, n = 5),\n aes(x = Data, label = Data, y = Response),\n min.segment.length = 0, xlim = 80,\n force = 9, color = \"firebrick3\") +\n theme(axis.text.x = element_blank(),\n axis.ticks.x = element_blank())\n"
},
{
"answer_id": 74608285,
"author": "Andre Wildberg",
"author_id": 9462095,
"author_profile": "https://Stackoverflow.com/users/9462095",
"pm_score": 1,
"selected": false,
"text": "head tail library(ggplot2)\n\nggplot(rbind(head(df, 5), tail(df, 5))) + \n geom_col(aes(Data, Response)) + \n geom_errorbar(aes(Data, ymin = Response - SD, ymax = Response + SD), width=.2)\n dat <- rbind(head(df, 5), \n list(\"D6_MEAN\", mean(df[-c(1:5, (nrow(df)-4):(nrow(df))), 2]),\n mean(df[-c(1:5, (nrow(df)-4):(nrow(df))), 3])), tail(df, 5))\n\ndat$grp <- c(rep(\"top\", 5), \n paste(\"mean of\", nrow(df)-10, \"rows\"), rep(\"bottom\", 5))\n\ndat$grp <- factor(dat$grp, levels=unique(dat$grp))\n\nggplot(dat) + \n geom_col(aes(Data, Response, fill=grp)) + \n geom_errorbar(aes(Data, ymin = Response - SD, ymax = Response + SD), width=.2)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74607788",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16817855/"
] |
74,607,790
|
<p>For example,
Lets say you have a list of apples</p>
<pre><code>List<String> apples = ['green', 'red','red', 'yellow']
</code></pre>
<p>And you want to remove just one red apple using .removeWhere</p>
<pre><code>apples.removeWhere((element => element == 'red));
</code></pre>
<p>however, this removes all instances of 'red' when I only want to remove one of them! Any solutions?</p>
|
[
{
"answer_id": 74607864,
"author": "jared_mamrot",
"author_id": 12957340,
"author_profile": "https://Stackoverflow.com/users/12957340",
"pm_score": 2,
"selected": false,
"text": "library(tidyverse)\nlibrary(ggrepel)\n\ndf <- structure(list(Data = c(\"D1\", \"D2\", \"D3\", \"D4\", \"D5\", \"D6\", \"D7\", \n \"D8\", \"D9\", \"D10\", \"D11\", \"D12\", \"D13\", \"D14\", \"D15\", \"D16\", \n \"D17\", \"D18\", \"D19\", \"D20\", \"D21\", \"D22\", \"D23\", \"D24\", \"D25\", \n \"D26\", \"D27\", \"D28\", \"D29\", \"D30\", \"D31\", \"D32\", \"D33\", \"D34\", \n \"D35\", \"D36\", \"D37\", \"D38\", \"D39\", \"D40\", \"D41\", \"D42\", \"D43\", \n \"D44\", \"D45\", \"D46\", \"D47\", \"D48\", \"D49\", \"D50\", \"D51\", \"D52\", \n \"D53\", \"D54\", \"D55\", \"D56\", \"D57\", \"D58\", \"D59\", \"D60\", \"D61\", \n \"D62\", \"D63\", \"D64\", \"D65\", \"D66\", \"D67\", \"D68\", \"D69\", \"D70\", \n \"D71\", \"D72\", \"D73\", \"D74\", \"D75\", \"D76\", \"D77\", \"D78\", \"D79\", \n \"D80\", \"D81\", \"D82\", \"D83\", \"D84\", \"D85\", \"D86\", \"D87\", \"D88\", \n \"D89\", \"D90\", \"D91\", \"D92\", \"D93\", \"D94\", \"D95\", \"D96\", \"D97\", \n \"D98\"), Response = c(18.11, 17.6, 16.14, 16.02, 14.73, 14.07, \n 13.41, 13.08, 12.73, 12.51, 11.53, 9.85, 9.78, 9.74, 8.98, 1.54, \n 1.54, 1.51, 1.51, 1.49, 1.49, 1.49, 1.44, 1.44, 1.39, 1.37, 1.36, \n 1.35, 1.34, 1.34, 1.33, 1.33, 1.31, 1.3, 1.29, 1.26, 1.23, 1.21, \n 1.19, 1.18, 1.14, 1.12, 1.07, 1.05, 1.03, 1.03, 1.03, 1.02, 1.01, \n 1, 0.99, 0.98, 0.95, 0.94, 0.93, 0.92, 0.91, 0.87, 0.83, 0.83, \n 0.81, 0.8, 0.8, 0.79, 0.78, 0.76, 0.76, 0.75, 0.75, 0.73, 0.73, \n 0.71, 0.69, 0.68, 0.67, 0.67, 0.64, 0.63, 0.63, -11.6, -11.6, \n -11.6, -11.7, -11.7, -11.7, -11.8, -11.9, -11.9, -12, -12.2, \n -12.3, -12.4, -12.4, -12.5, -12.5, -12.6, -12.6, -12.7), SD = c(8.98, \n 8.19, 2.57, 8.36, 2.14, 5.51, 3.01, 9.8, 6.88, 3.21, 11.35, 5.6, \n 13.29, 4.9, 9.45, 11.06, 5.41, 28.78, 13.46, 4.23, 12.24, 1.41, \n 11.03, 11.29, 2.17, 7.11, 3.08, 1.8, 12.09, 4.79, 1.01, 3.69, \n 3.62, 3.06, 3.12, 13.19, 4.28, 12.05, 3.96, 13.4, 3.02, 7.97, \n 12, 3.91, 1.85, 3.96, 1.79, 2.67, 0.37, 7.45, 9.57, 1.95, 1.82, \n 3.02, 6.97, 6.73, 1.22, 5.45, 4.9, 2.48, 6.88, 3.81, 1.86, 1.83, \n 7.56, 11.25, 2.72, 3.68, 2.41, 4.44, 2.59, 6.24, 2.56, 3.96, \n 10.56, 1.65, 7.22, 4.12, 4.01, 3.4, 2.8, 0.92, 9.58, 1.17, 1.36, \n 0.91, 5.8, 4.26, 3.48, 3.7, 11.99, 5.77, 11.06, 3.09, 0.12, 3.18, \n 5.49, 5.81)), class = \"data.frame\", row.names = c(NA, -98L))\ndf$Data <- factor(df$Data, levels = paste0(\"D\", 1:98), ordered = TRUE)\n\nggplot() +\n geom_line(data = df, aes(x = Data, y = Response, group = 1),\n alpha = 0.25) +\n geom_point(data = df, aes(x = Data, y = Response, group = 1),\n alpha = 0.25) +\n geom_line(data = df %>% slice_max(order_by = Response, n = 5),\n aes(x = Data, y = Response, group = 1)) +\n geom_point(data = df %>% slice_max(order_by = Response, n = 5),\n aes(x = Data, y = Response, group = 1)) +\n geom_linerange(data = df %>% slice_max(order_by = Response, n = 5),\n aes(x = Data, y = Response,\n ymin = Response - SD, ymax = Response + SD)) +\n geom_text_repel(data = df %>% slice_max(order_by = Response, n = 5),\n aes(x = Data, label = Data, y = Response),\n min.segment.length = 0, xlim = 10,\n force = 5, color = \"firebrick3\") +\n geom_line(data = df %>% slice_min(order_by = Response, n = 5),\n aes(x = Data, y = Response, group = 1)) +\n geom_point(data = df %>% slice_min(order_by = Response, n = 5),\n aes(x = Data, y = Response, group = 1)) +\n geom_linerange(data = df %>% slice_min(order_by = Response, n = 5),\n aes(x = Data, y = Response,\n ymin = Response - SD, ymax = Response + SD)) +\n geom_text_repel(data = df %>% slice_min(order_by = Response, n = 5),\n aes(x = Data, label = Data, y = Response),\n min.segment.length = 0, xlim = 80,\n force = 9, color = \"firebrick3\") +\n theme(axis.text.x = element_blank(),\n axis.ticks.x = element_blank())\n"
},
{
"answer_id": 74608285,
"author": "Andre Wildberg",
"author_id": 9462095,
"author_profile": "https://Stackoverflow.com/users/9462095",
"pm_score": 1,
"selected": false,
"text": "head tail library(ggplot2)\n\nggplot(rbind(head(df, 5), tail(df, 5))) + \n geom_col(aes(Data, Response)) + \n geom_errorbar(aes(Data, ymin = Response - SD, ymax = Response + SD), width=.2)\n dat <- rbind(head(df, 5), \n list(\"D6_MEAN\", mean(df[-c(1:5, (nrow(df)-4):(nrow(df))), 2]),\n mean(df[-c(1:5, (nrow(df)-4):(nrow(df))), 3])), tail(df, 5))\n\ndat$grp <- c(rep(\"top\", 5), \n paste(\"mean of\", nrow(df)-10, \"rows\"), rep(\"bottom\", 5))\n\ndat$grp <- factor(dat$grp, levels=unique(dat$grp))\n\nggplot(dat) + \n geom_col(aes(Data, Response, fill=grp)) + \n geom_errorbar(aes(Data, ymin = Response - SD, ymax = Response + SD), width=.2)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74607790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14868799/"
] |
74,607,810
|
<p>I'm trying to write a bash script that will create a new directory with a name based on the last directory created. For example - if I have the following folders in a directory:</p>
<p>00001
00002
00003</p>
<p>and I run the script again I would like it to determine that the last folder is '00003' and then create '00004'.</p>
<p>The following command seems to get the last folder name from the 'output' directory but I don't seem to be able to manipulate the value in the 'var' variable as it is a directory and not a string or integer.</p>
<p><code>var=$(ls -t output | grep -v /$ | head -1)</code></p>
<p>Any help would be much appreciated.</p>
|
[
{
"answer_id": 74607864,
"author": "jared_mamrot",
"author_id": 12957340,
"author_profile": "https://Stackoverflow.com/users/12957340",
"pm_score": 2,
"selected": false,
"text": "library(tidyverse)\nlibrary(ggrepel)\n\ndf <- structure(list(Data = c(\"D1\", \"D2\", \"D3\", \"D4\", \"D5\", \"D6\", \"D7\", \n \"D8\", \"D9\", \"D10\", \"D11\", \"D12\", \"D13\", \"D14\", \"D15\", \"D16\", \n \"D17\", \"D18\", \"D19\", \"D20\", \"D21\", \"D22\", \"D23\", \"D24\", \"D25\", \n \"D26\", \"D27\", \"D28\", \"D29\", \"D30\", \"D31\", \"D32\", \"D33\", \"D34\", \n \"D35\", \"D36\", \"D37\", \"D38\", \"D39\", \"D40\", \"D41\", \"D42\", \"D43\", \n \"D44\", \"D45\", \"D46\", \"D47\", \"D48\", \"D49\", \"D50\", \"D51\", \"D52\", \n \"D53\", \"D54\", \"D55\", \"D56\", \"D57\", \"D58\", \"D59\", \"D60\", \"D61\", \n \"D62\", \"D63\", \"D64\", \"D65\", \"D66\", \"D67\", \"D68\", \"D69\", \"D70\", \n \"D71\", \"D72\", \"D73\", \"D74\", \"D75\", \"D76\", \"D77\", \"D78\", \"D79\", \n \"D80\", \"D81\", \"D82\", \"D83\", \"D84\", \"D85\", \"D86\", \"D87\", \"D88\", \n \"D89\", \"D90\", \"D91\", \"D92\", \"D93\", \"D94\", \"D95\", \"D96\", \"D97\", \n \"D98\"), Response = c(18.11, 17.6, 16.14, 16.02, 14.73, 14.07, \n 13.41, 13.08, 12.73, 12.51, 11.53, 9.85, 9.78, 9.74, 8.98, 1.54, \n 1.54, 1.51, 1.51, 1.49, 1.49, 1.49, 1.44, 1.44, 1.39, 1.37, 1.36, \n 1.35, 1.34, 1.34, 1.33, 1.33, 1.31, 1.3, 1.29, 1.26, 1.23, 1.21, \n 1.19, 1.18, 1.14, 1.12, 1.07, 1.05, 1.03, 1.03, 1.03, 1.02, 1.01, \n 1, 0.99, 0.98, 0.95, 0.94, 0.93, 0.92, 0.91, 0.87, 0.83, 0.83, \n 0.81, 0.8, 0.8, 0.79, 0.78, 0.76, 0.76, 0.75, 0.75, 0.73, 0.73, \n 0.71, 0.69, 0.68, 0.67, 0.67, 0.64, 0.63, 0.63, -11.6, -11.6, \n -11.6, -11.7, -11.7, -11.7, -11.8, -11.9, -11.9, -12, -12.2, \n -12.3, -12.4, -12.4, -12.5, -12.5, -12.6, -12.6, -12.7), SD = c(8.98, \n 8.19, 2.57, 8.36, 2.14, 5.51, 3.01, 9.8, 6.88, 3.21, 11.35, 5.6, \n 13.29, 4.9, 9.45, 11.06, 5.41, 28.78, 13.46, 4.23, 12.24, 1.41, \n 11.03, 11.29, 2.17, 7.11, 3.08, 1.8, 12.09, 4.79, 1.01, 3.69, \n 3.62, 3.06, 3.12, 13.19, 4.28, 12.05, 3.96, 13.4, 3.02, 7.97, \n 12, 3.91, 1.85, 3.96, 1.79, 2.67, 0.37, 7.45, 9.57, 1.95, 1.82, \n 3.02, 6.97, 6.73, 1.22, 5.45, 4.9, 2.48, 6.88, 3.81, 1.86, 1.83, \n 7.56, 11.25, 2.72, 3.68, 2.41, 4.44, 2.59, 6.24, 2.56, 3.96, \n 10.56, 1.65, 7.22, 4.12, 4.01, 3.4, 2.8, 0.92, 9.58, 1.17, 1.36, \n 0.91, 5.8, 4.26, 3.48, 3.7, 11.99, 5.77, 11.06, 3.09, 0.12, 3.18, \n 5.49, 5.81)), class = \"data.frame\", row.names = c(NA, -98L))\ndf$Data <- factor(df$Data, levels = paste0(\"D\", 1:98), ordered = TRUE)\n\nggplot() +\n geom_line(data = df, aes(x = Data, y = Response, group = 1),\n alpha = 0.25) +\n geom_point(data = df, aes(x = Data, y = Response, group = 1),\n alpha = 0.25) +\n geom_line(data = df %>% slice_max(order_by = Response, n = 5),\n aes(x = Data, y = Response, group = 1)) +\n geom_point(data = df %>% slice_max(order_by = Response, n = 5),\n aes(x = Data, y = Response, group = 1)) +\n geom_linerange(data = df %>% slice_max(order_by = Response, n = 5),\n aes(x = Data, y = Response,\n ymin = Response - SD, ymax = Response + SD)) +\n geom_text_repel(data = df %>% slice_max(order_by = Response, n = 5),\n aes(x = Data, label = Data, y = Response),\n min.segment.length = 0, xlim = 10,\n force = 5, color = \"firebrick3\") +\n geom_line(data = df %>% slice_min(order_by = Response, n = 5),\n aes(x = Data, y = Response, group = 1)) +\n geom_point(data = df %>% slice_min(order_by = Response, n = 5),\n aes(x = Data, y = Response, group = 1)) +\n geom_linerange(data = df %>% slice_min(order_by = Response, n = 5),\n aes(x = Data, y = Response,\n ymin = Response - SD, ymax = Response + SD)) +\n geom_text_repel(data = df %>% slice_min(order_by = Response, n = 5),\n aes(x = Data, label = Data, y = Response),\n min.segment.length = 0, xlim = 80,\n force = 9, color = \"firebrick3\") +\n theme(axis.text.x = element_blank(),\n axis.ticks.x = element_blank())\n"
},
{
"answer_id": 74608285,
"author": "Andre Wildberg",
"author_id": 9462095,
"author_profile": "https://Stackoverflow.com/users/9462095",
"pm_score": 1,
"selected": false,
"text": "head tail library(ggplot2)\n\nggplot(rbind(head(df, 5), tail(df, 5))) + \n geom_col(aes(Data, Response)) + \n geom_errorbar(aes(Data, ymin = Response - SD, ymax = Response + SD), width=.2)\n dat <- rbind(head(df, 5), \n list(\"D6_MEAN\", mean(df[-c(1:5, (nrow(df)-4):(nrow(df))), 2]),\n mean(df[-c(1:5, (nrow(df)-4):(nrow(df))), 3])), tail(df, 5))\n\ndat$grp <- c(rep(\"top\", 5), \n paste(\"mean of\", nrow(df)-10, \"rows\"), rep(\"bottom\", 5))\n\ndat$grp <- factor(dat$grp, levels=unique(dat$grp))\n\nggplot(dat) + \n geom_col(aes(Data, Response, fill=grp)) + \n geom_errorbar(aes(Data, ymin = Response - SD, ymax = Response + SD), width=.2)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74607810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20628051/"
] |
74,607,822
|
<p>I'm doing a Javascript test (I'm nowhere near an expert in the matter, I'm much more experienced in Java) and I'm just completely lost, given these declarations:</p>
<p><strong>Number 1</strong></p>
<pre><code>const paddockType = [
{ id: 1, name: 'PALTOS' },
{ id: 2, name: 'AVELLANOS' },
{ id: 3, name: 'CEREZAS' },
{ id: 4, name: 'NOGALES' },
]
</code></pre>
<p><strong>Number 2</strong></p>
<pre><code>const paddocks = [
{ paddockManagerId: 6, farmId: 1, paddockTypeId: 1, harvestYear: 2019, area: 1200 },
{ paddockManagerId: 1, farmId: 3, paddockTypeId: 4, harvestYear: 2019, area: 500 },
{ paddockManagerId: 5, farmId: 3, paddockTypeId: 2, harvestYear: 2020, area: 20000 },
{ paddockManagerId: 2, farmId: 2, paddockTypeId: 3, harvestYear: 2021, area: 8401},
{ paddockManagerId: 3, farmId: 1, paddockTypeId: 1, harvestYear: 2020, area: 2877 },
{ paddockManagerId: 5, farmId: 2, paddockTypeId: 2, harvestYear: 2017, area: 15902 },
{ paddockManagerId: 3, farmId: 3, paddockTypeId: 2, harvestYear: 2018, area: 1736 },
{ paddockManagerId: 2, farmId: 3, paddockTypeId: 3, harvestYear: 2020, area: 2965 },
{ paddockManagerId: 4, farmId: 3, paddockTypeId: 4, harvestYear: 2018, area: 1651 },
{ paddockManagerId: 5, farmId: 1, paddockTypeId: 1, harvestYear: 2018, area: 700 },
{ paddockManagerId: 1, farmId: 2, paddockTypeId: 1, harvestYear: 2019, area: 7956 },
{ paddockManagerId: 5, farmId: 3, paddockTypeId: 2, harvestYear: 2020, area: 3745 },
{ paddockManagerId: 6, farmId: 1, paddockTypeId: 3, harvestYear: 2021, area: 11362 },
{ paddockManagerId: 2, farmId: 3, paddockTypeId: 3, harvestYear: 2021, area: 300 },
{ paddockManagerId: 3, farmId: 2, paddockTypeId: 2, harvestYear: 2020, area: 19188 },
{ paddockManagerId: 3, farmId: 1, paddockTypeId: 1, harvestYear: 2019, area: 17137 },
{ paddockManagerId: 4, farmId: 3, paddockTypeId: 2, harvestYear: 2020, area: 100 },
{ paddockManagerId: 2, farmId: 1, paddockTypeId: 3, harvestYear: 2019, area: 11845 },
{ paddockManagerId: 5, farmId: 2, paddockTypeId: 1, harvestYear: 2018, area: 15969 },
{ paddockManagerId: 1, farmId: 3, paddockTypeId: 1, harvestYear: 2029, area: 10420 },
{ paddockManagerId: 5, farmId: 2, paddockTypeId: 3, harvestYear: 2010, area: 3200 },
{ paddockManagerId: 6, farmId: 1, paddockTypeId: 2, harvestYear: 2012, area: 10587 },
{ paddockManagerId: 2, farmId: 2, paddockTypeId: 2, harvestYear: 2018, area: 16750 }
];
</code></pre>
<p>I'm being asked to do the following:</p>
<blockquote>
<p>Return an array with the names of each crop, followed by the total sum (area) of each one
of them.</p>
</blockquote>
<p>As you can see, the second declaration has a paddockTypeId which represents one of the crops in the paddockType array, now I must sum the area of each ID, get the total, and split them based on the crop ID, and also make sure they get correctly paired with their crop names, but as I've said before, I'm lost.</p>
<p>I tried approaching it with a Map, but I just couldn't comprehend the concrete idea of it all. I also checked the documentation, but to no avail.</p>
<p>PD: Also, I'm aware the title may not be very clear, sorry about that!, Any suggestions for a better title will be greatly appreciated!</p>
|
[
{
"answer_id": 74607864,
"author": "jared_mamrot",
"author_id": 12957340,
"author_profile": "https://Stackoverflow.com/users/12957340",
"pm_score": 2,
"selected": false,
"text": "library(tidyverse)\nlibrary(ggrepel)\n\ndf <- structure(list(Data = c(\"D1\", \"D2\", \"D3\", \"D4\", \"D5\", \"D6\", \"D7\", \n \"D8\", \"D9\", \"D10\", \"D11\", \"D12\", \"D13\", \"D14\", \"D15\", \"D16\", \n \"D17\", \"D18\", \"D19\", \"D20\", \"D21\", \"D22\", \"D23\", \"D24\", \"D25\", \n \"D26\", \"D27\", \"D28\", \"D29\", \"D30\", \"D31\", \"D32\", \"D33\", \"D34\", \n \"D35\", \"D36\", \"D37\", \"D38\", \"D39\", \"D40\", \"D41\", \"D42\", \"D43\", \n \"D44\", \"D45\", \"D46\", \"D47\", \"D48\", \"D49\", \"D50\", \"D51\", \"D52\", \n \"D53\", \"D54\", \"D55\", \"D56\", \"D57\", \"D58\", \"D59\", \"D60\", \"D61\", \n \"D62\", \"D63\", \"D64\", \"D65\", \"D66\", \"D67\", \"D68\", \"D69\", \"D70\", \n \"D71\", \"D72\", \"D73\", \"D74\", \"D75\", \"D76\", \"D77\", \"D78\", \"D79\", \n \"D80\", \"D81\", \"D82\", \"D83\", \"D84\", \"D85\", \"D86\", \"D87\", \"D88\", \n \"D89\", \"D90\", \"D91\", \"D92\", \"D93\", \"D94\", \"D95\", \"D96\", \"D97\", \n \"D98\"), Response = c(18.11, 17.6, 16.14, 16.02, 14.73, 14.07, \n 13.41, 13.08, 12.73, 12.51, 11.53, 9.85, 9.78, 9.74, 8.98, 1.54, \n 1.54, 1.51, 1.51, 1.49, 1.49, 1.49, 1.44, 1.44, 1.39, 1.37, 1.36, \n 1.35, 1.34, 1.34, 1.33, 1.33, 1.31, 1.3, 1.29, 1.26, 1.23, 1.21, \n 1.19, 1.18, 1.14, 1.12, 1.07, 1.05, 1.03, 1.03, 1.03, 1.02, 1.01, \n 1, 0.99, 0.98, 0.95, 0.94, 0.93, 0.92, 0.91, 0.87, 0.83, 0.83, \n 0.81, 0.8, 0.8, 0.79, 0.78, 0.76, 0.76, 0.75, 0.75, 0.73, 0.73, \n 0.71, 0.69, 0.68, 0.67, 0.67, 0.64, 0.63, 0.63, -11.6, -11.6, \n -11.6, -11.7, -11.7, -11.7, -11.8, -11.9, -11.9, -12, -12.2, \n -12.3, -12.4, -12.4, -12.5, -12.5, -12.6, -12.6, -12.7), SD = c(8.98, \n 8.19, 2.57, 8.36, 2.14, 5.51, 3.01, 9.8, 6.88, 3.21, 11.35, 5.6, \n 13.29, 4.9, 9.45, 11.06, 5.41, 28.78, 13.46, 4.23, 12.24, 1.41, \n 11.03, 11.29, 2.17, 7.11, 3.08, 1.8, 12.09, 4.79, 1.01, 3.69, \n 3.62, 3.06, 3.12, 13.19, 4.28, 12.05, 3.96, 13.4, 3.02, 7.97, \n 12, 3.91, 1.85, 3.96, 1.79, 2.67, 0.37, 7.45, 9.57, 1.95, 1.82, \n 3.02, 6.97, 6.73, 1.22, 5.45, 4.9, 2.48, 6.88, 3.81, 1.86, 1.83, \n 7.56, 11.25, 2.72, 3.68, 2.41, 4.44, 2.59, 6.24, 2.56, 3.96, \n 10.56, 1.65, 7.22, 4.12, 4.01, 3.4, 2.8, 0.92, 9.58, 1.17, 1.36, \n 0.91, 5.8, 4.26, 3.48, 3.7, 11.99, 5.77, 11.06, 3.09, 0.12, 3.18, \n 5.49, 5.81)), class = \"data.frame\", row.names = c(NA, -98L))\ndf$Data <- factor(df$Data, levels = paste0(\"D\", 1:98), ordered = TRUE)\n\nggplot() +\n geom_line(data = df, aes(x = Data, y = Response, group = 1),\n alpha = 0.25) +\n geom_point(data = df, aes(x = Data, y = Response, group = 1),\n alpha = 0.25) +\n geom_line(data = df %>% slice_max(order_by = Response, n = 5),\n aes(x = Data, y = Response, group = 1)) +\n geom_point(data = df %>% slice_max(order_by = Response, n = 5),\n aes(x = Data, y = Response, group = 1)) +\n geom_linerange(data = df %>% slice_max(order_by = Response, n = 5),\n aes(x = Data, y = Response,\n ymin = Response - SD, ymax = Response + SD)) +\n geom_text_repel(data = df %>% slice_max(order_by = Response, n = 5),\n aes(x = Data, label = Data, y = Response),\n min.segment.length = 0, xlim = 10,\n force = 5, color = \"firebrick3\") +\n geom_line(data = df %>% slice_min(order_by = Response, n = 5),\n aes(x = Data, y = Response, group = 1)) +\n geom_point(data = df %>% slice_min(order_by = Response, n = 5),\n aes(x = Data, y = Response, group = 1)) +\n geom_linerange(data = df %>% slice_min(order_by = Response, n = 5),\n aes(x = Data, y = Response,\n ymin = Response - SD, ymax = Response + SD)) +\n geom_text_repel(data = df %>% slice_min(order_by = Response, n = 5),\n aes(x = Data, label = Data, y = Response),\n min.segment.length = 0, xlim = 80,\n force = 9, color = \"firebrick3\") +\n theme(axis.text.x = element_blank(),\n axis.ticks.x = element_blank())\n"
},
{
"answer_id": 74608285,
"author": "Andre Wildberg",
"author_id": 9462095,
"author_profile": "https://Stackoverflow.com/users/9462095",
"pm_score": 1,
"selected": false,
"text": "head tail library(ggplot2)\n\nggplot(rbind(head(df, 5), tail(df, 5))) + \n geom_col(aes(Data, Response)) + \n geom_errorbar(aes(Data, ymin = Response - SD, ymax = Response + SD), width=.2)\n dat <- rbind(head(df, 5), \n list(\"D6_MEAN\", mean(df[-c(1:5, (nrow(df)-4):(nrow(df))), 2]),\n mean(df[-c(1:5, (nrow(df)-4):(nrow(df))), 3])), tail(df, 5))\n\ndat$grp <- c(rep(\"top\", 5), \n paste(\"mean of\", nrow(df)-10, \"rows\"), rep(\"bottom\", 5))\n\ndat$grp <- factor(dat$grp, levels=unique(dat$grp))\n\nggplot(dat) + \n geom_col(aes(Data, Response, fill=grp)) + \n geom_errorbar(aes(Data, ymin = Response - SD, ymax = Response + SD), width=.2)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74607822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17590305/"
] |
74,607,870
|
<p>I am using the <strong>re</strong> package's <code>re.findall</code> to extract terms from strings. How can I make a regex to say capture these matches unless you see this substring (in this case the substring <code>"fake"</code>). I attempted this via a anchored look-ahead solution.</p>
<p><strong>Current Output:</strong></p>
<pre><code>import re
for x in ['a man dogs', "fake: too many dogs", 'hi']:
print(re.findall(r"(man[a-z]?\b|dog)(?!^.*fake)", x, flags=re.IGNORECASE))
## ['man', 'dog']
## ['many', 'dog']
## []
</code></pre>
<p><strong>Desired Output</strong></p>
<pre><code>## ['man', 'dog']
## []
## []
</code></pre>
<p>I could accomplish this with an if/else but was wondering how to use a pure regex to solve this?</p>
<pre><code>for x in ['a man dogs', "fake: too many dogs", 'hi']:
if re.search('fake', x, flags=re.IGNORECASE):
print([])
else:
print(re.findall(r"(man[a-z]?\b|dog)", x, flags=re.IGNORECASE))
## ['man', 'dog']
## []
## []
</code></pre>
|
[
{
"answer_id": 74607864,
"author": "jared_mamrot",
"author_id": 12957340,
"author_profile": "https://Stackoverflow.com/users/12957340",
"pm_score": 2,
"selected": false,
"text": "library(tidyverse)\nlibrary(ggrepel)\n\ndf <- structure(list(Data = c(\"D1\", \"D2\", \"D3\", \"D4\", \"D5\", \"D6\", \"D7\", \n \"D8\", \"D9\", \"D10\", \"D11\", \"D12\", \"D13\", \"D14\", \"D15\", \"D16\", \n \"D17\", \"D18\", \"D19\", \"D20\", \"D21\", \"D22\", \"D23\", \"D24\", \"D25\", \n \"D26\", \"D27\", \"D28\", \"D29\", \"D30\", \"D31\", \"D32\", \"D33\", \"D34\", \n \"D35\", \"D36\", \"D37\", \"D38\", \"D39\", \"D40\", \"D41\", \"D42\", \"D43\", \n \"D44\", \"D45\", \"D46\", \"D47\", \"D48\", \"D49\", \"D50\", \"D51\", \"D52\", \n \"D53\", \"D54\", \"D55\", \"D56\", \"D57\", \"D58\", \"D59\", \"D60\", \"D61\", \n \"D62\", \"D63\", \"D64\", \"D65\", \"D66\", \"D67\", \"D68\", \"D69\", \"D70\", \n \"D71\", \"D72\", \"D73\", \"D74\", \"D75\", \"D76\", \"D77\", \"D78\", \"D79\", \n \"D80\", \"D81\", \"D82\", \"D83\", \"D84\", \"D85\", \"D86\", \"D87\", \"D88\", \n \"D89\", \"D90\", \"D91\", \"D92\", \"D93\", \"D94\", \"D95\", \"D96\", \"D97\", \n \"D98\"), Response = c(18.11, 17.6, 16.14, 16.02, 14.73, 14.07, \n 13.41, 13.08, 12.73, 12.51, 11.53, 9.85, 9.78, 9.74, 8.98, 1.54, \n 1.54, 1.51, 1.51, 1.49, 1.49, 1.49, 1.44, 1.44, 1.39, 1.37, 1.36, \n 1.35, 1.34, 1.34, 1.33, 1.33, 1.31, 1.3, 1.29, 1.26, 1.23, 1.21, \n 1.19, 1.18, 1.14, 1.12, 1.07, 1.05, 1.03, 1.03, 1.03, 1.02, 1.01, \n 1, 0.99, 0.98, 0.95, 0.94, 0.93, 0.92, 0.91, 0.87, 0.83, 0.83, \n 0.81, 0.8, 0.8, 0.79, 0.78, 0.76, 0.76, 0.75, 0.75, 0.73, 0.73, \n 0.71, 0.69, 0.68, 0.67, 0.67, 0.64, 0.63, 0.63, -11.6, -11.6, \n -11.6, -11.7, -11.7, -11.7, -11.8, -11.9, -11.9, -12, -12.2, \n -12.3, -12.4, -12.4, -12.5, -12.5, -12.6, -12.6, -12.7), SD = c(8.98, \n 8.19, 2.57, 8.36, 2.14, 5.51, 3.01, 9.8, 6.88, 3.21, 11.35, 5.6, \n 13.29, 4.9, 9.45, 11.06, 5.41, 28.78, 13.46, 4.23, 12.24, 1.41, \n 11.03, 11.29, 2.17, 7.11, 3.08, 1.8, 12.09, 4.79, 1.01, 3.69, \n 3.62, 3.06, 3.12, 13.19, 4.28, 12.05, 3.96, 13.4, 3.02, 7.97, \n 12, 3.91, 1.85, 3.96, 1.79, 2.67, 0.37, 7.45, 9.57, 1.95, 1.82, \n 3.02, 6.97, 6.73, 1.22, 5.45, 4.9, 2.48, 6.88, 3.81, 1.86, 1.83, \n 7.56, 11.25, 2.72, 3.68, 2.41, 4.44, 2.59, 6.24, 2.56, 3.96, \n 10.56, 1.65, 7.22, 4.12, 4.01, 3.4, 2.8, 0.92, 9.58, 1.17, 1.36, \n 0.91, 5.8, 4.26, 3.48, 3.7, 11.99, 5.77, 11.06, 3.09, 0.12, 3.18, \n 5.49, 5.81)), class = \"data.frame\", row.names = c(NA, -98L))\ndf$Data <- factor(df$Data, levels = paste0(\"D\", 1:98), ordered = TRUE)\n\nggplot() +\n geom_line(data = df, aes(x = Data, y = Response, group = 1),\n alpha = 0.25) +\n geom_point(data = df, aes(x = Data, y = Response, group = 1),\n alpha = 0.25) +\n geom_line(data = df %>% slice_max(order_by = Response, n = 5),\n aes(x = Data, y = Response, group = 1)) +\n geom_point(data = df %>% slice_max(order_by = Response, n = 5),\n aes(x = Data, y = Response, group = 1)) +\n geom_linerange(data = df %>% slice_max(order_by = Response, n = 5),\n aes(x = Data, y = Response,\n ymin = Response - SD, ymax = Response + SD)) +\n geom_text_repel(data = df %>% slice_max(order_by = Response, n = 5),\n aes(x = Data, label = Data, y = Response),\n min.segment.length = 0, xlim = 10,\n force = 5, color = \"firebrick3\") +\n geom_line(data = df %>% slice_min(order_by = Response, n = 5),\n aes(x = Data, y = Response, group = 1)) +\n geom_point(data = df %>% slice_min(order_by = Response, n = 5),\n aes(x = Data, y = Response, group = 1)) +\n geom_linerange(data = df %>% slice_min(order_by = Response, n = 5),\n aes(x = Data, y = Response,\n ymin = Response - SD, ymax = Response + SD)) +\n geom_text_repel(data = df %>% slice_min(order_by = Response, n = 5),\n aes(x = Data, label = Data, y = Response),\n min.segment.length = 0, xlim = 80,\n force = 9, color = \"firebrick3\") +\n theme(axis.text.x = element_blank(),\n axis.ticks.x = element_blank())\n"
},
{
"answer_id": 74608285,
"author": "Andre Wildberg",
"author_id": 9462095,
"author_profile": "https://Stackoverflow.com/users/9462095",
"pm_score": 1,
"selected": false,
"text": "head tail library(ggplot2)\n\nggplot(rbind(head(df, 5), tail(df, 5))) + \n geom_col(aes(Data, Response)) + \n geom_errorbar(aes(Data, ymin = Response - SD, ymax = Response + SD), width=.2)\n dat <- rbind(head(df, 5), \n list(\"D6_MEAN\", mean(df[-c(1:5, (nrow(df)-4):(nrow(df))), 2]),\n mean(df[-c(1:5, (nrow(df)-4):(nrow(df))), 3])), tail(df, 5))\n\ndat$grp <- c(rep(\"top\", 5), \n paste(\"mean of\", nrow(df)-10, \"rows\"), rep(\"bottom\", 5))\n\ndat$grp <- factor(dat$grp, levels=unique(dat$grp))\n\nggplot(dat) + \n geom_col(aes(Data, Response, fill=grp)) + \n geom_errorbar(aes(Data, ymin = Response - SD, ymax = Response + SD), width=.2)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74607870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1000343/"
] |
74,607,887
|
<p>The problem: I have a bunch of xunit tests that connect to an external server. If that server is up - they fly through very quickly. If that server is down, everything goes into timeouts and retries and the tests all take a <em>long</em> time. The thing is, if I have 100 tests - if the first one fails, I still want all the rest to fail, but it's completely pointless running them... What I'd like is to be able to make my own fact attribute something like:</p>
<pre class="lang-cs prettyprint-override"><code> [FactInFailureGroup( "ConectsToBlah", typeof(ConnectionException)]
public void TestOne()
{
...
}
[FactInFailureGroup( "ConnectsToBlah", typeof(ConnectionException)]
public void TestTwo()
{
...
}
</code></pre>
<p>I've looked at before/after attributes, but they don't seem to be able to kill the test or see the result - and I've looked at creating my own fact attribute, which looks like it can prevent the test from running, but not put in a trap for the result. I really want to somehow make code along these lines:</p>
<pre class="lang-cs prettyprint-override"><code> class FactInFailureGroupAttribute : FactAttribute
{
private static _failedGroups = new HashSet<String>();
...
void BeforeTest( TestManipulator manipulator )
{
if (_failedGroups.contains( _thisGroup ))
manipulator.SkipWithMessage( f"all tests in group {_thisGroup} failed because of {_exceptionType}");
}
void AfterTest( TestResult test )
{
if (test.Failed && test.Exception.GetType() == _exceptionType)
_failedGroups.add( _thisGroup );
}
}
</code></pre>
|
[
{
"answer_id": 74607864,
"author": "jared_mamrot",
"author_id": 12957340,
"author_profile": "https://Stackoverflow.com/users/12957340",
"pm_score": 2,
"selected": false,
"text": "library(tidyverse)\nlibrary(ggrepel)\n\ndf <- structure(list(Data = c(\"D1\", \"D2\", \"D3\", \"D4\", \"D5\", \"D6\", \"D7\", \n \"D8\", \"D9\", \"D10\", \"D11\", \"D12\", \"D13\", \"D14\", \"D15\", \"D16\", \n \"D17\", \"D18\", \"D19\", \"D20\", \"D21\", \"D22\", \"D23\", \"D24\", \"D25\", \n \"D26\", \"D27\", \"D28\", \"D29\", \"D30\", \"D31\", \"D32\", \"D33\", \"D34\", \n \"D35\", \"D36\", \"D37\", \"D38\", \"D39\", \"D40\", \"D41\", \"D42\", \"D43\", \n \"D44\", \"D45\", \"D46\", \"D47\", \"D48\", \"D49\", \"D50\", \"D51\", \"D52\", \n \"D53\", \"D54\", \"D55\", \"D56\", \"D57\", \"D58\", \"D59\", \"D60\", \"D61\", \n \"D62\", \"D63\", \"D64\", \"D65\", \"D66\", \"D67\", \"D68\", \"D69\", \"D70\", \n \"D71\", \"D72\", \"D73\", \"D74\", \"D75\", \"D76\", \"D77\", \"D78\", \"D79\", \n \"D80\", \"D81\", \"D82\", \"D83\", \"D84\", \"D85\", \"D86\", \"D87\", \"D88\", \n \"D89\", \"D90\", \"D91\", \"D92\", \"D93\", \"D94\", \"D95\", \"D96\", \"D97\", \n \"D98\"), Response = c(18.11, 17.6, 16.14, 16.02, 14.73, 14.07, \n 13.41, 13.08, 12.73, 12.51, 11.53, 9.85, 9.78, 9.74, 8.98, 1.54, \n 1.54, 1.51, 1.51, 1.49, 1.49, 1.49, 1.44, 1.44, 1.39, 1.37, 1.36, \n 1.35, 1.34, 1.34, 1.33, 1.33, 1.31, 1.3, 1.29, 1.26, 1.23, 1.21, \n 1.19, 1.18, 1.14, 1.12, 1.07, 1.05, 1.03, 1.03, 1.03, 1.02, 1.01, \n 1, 0.99, 0.98, 0.95, 0.94, 0.93, 0.92, 0.91, 0.87, 0.83, 0.83, \n 0.81, 0.8, 0.8, 0.79, 0.78, 0.76, 0.76, 0.75, 0.75, 0.73, 0.73, \n 0.71, 0.69, 0.68, 0.67, 0.67, 0.64, 0.63, 0.63, -11.6, -11.6, \n -11.6, -11.7, -11.7, -11.7, -11.8, -11.9, -11.9, -12, -12.2, \n -12.3, -12.4, -12.4, -12.5, -12.5, -12.6, -12.6, -12.7), SD = c(8.98, \n 8.19, 2.57, 8.36, 2.14, 5.51, 3.01, 9.8, 6.88, 3.21, 11.35, 5.6, \n 13.29, 4.9, 9.45, 11.06, 5.41, 28.78, 13.46, 4.23, 12.24, 1.41, \n 11.03, 11.29, 2.17, 7.11, 3.08, 1.8, 12.09, 4.79, 1.01, 3.69, \n 3.62, 3.06, 3.12, 13.19, 4.28, 12.05, 3.96, 13.4, 3.02, 7.97, \n 12, 3.91, 1.85, 3.96, 1.79, 2.67, 0.37, 7.45, 9.57, 1.95, 1.82, \n 3.02, 6.97, 6.73, 1.22, 5.45, 4.9, 2.48, 6.88, 3.81, 1.86, 1.83, \n 7.56, 11.25, 2.72, 3.68, 2.41, 4.44, 2.59, 6.24, 2.56, 3.96, \n 10.56, 1.65, 7.22, 4.12, 4.01, 3.4, 2.8, 0.92, 9.58, 1.17, 1.36, \n 0.91, 5.8, 4.26, 3.48, 3.7, 11.99, 5.77, 11.06, 3.09, 0.12, 3.18, \n 5.49, 5.81)), class = \"data.frame\", row.names = c(NA, -98L))\ndf$Data <- factor(df$Data, levels = paste0(\"D\", 1:98), ordered = TRUE)\n\nggplot() +\n geom_line(data = df, aes(x = Data, y = Response, group = 1),\n alpha = 0.25) +\n geom_point(data = df, aes(x = Data, y = Response, group = 1),\n alpha = 0.25) +\n geom_line(data = df %>% slice_max(order_by = Response, n = 5),\n aes(x = Data, y = Response, group = 1)) +\n geom_point(data = df %>% slice_max(order_by = Response, n = 5),\n aes(x = Data, y = Response, group = 1)) +\n geom_linerange(data = df %>% slice_max(order_by = Response, n = 5),\n aes(x = Data, y = Response,\n ymin = Response - SD, ymax = Response + SD)) +\n geom_text_repel(data = df %>% slice_max(order_by = Response, n = 5),\n aes(x = Data, label = Data, y = Response),\n min.segment.length = 0, xlim = 10,\n force = 5, color = \"firebrick3\") +\n geom_line(data = df %>% slice_min(order_by = Response, n = 5),\n aes(x = Data, y = Response, group = 1)) +\n geom_point(data = df %>% slice_min(order_by = Response, n = 5),\n aes(x = Data, y = Response, group = 1)) +\n geom_linerange(data = df %>% slice_min(order_by = Response, n = 5),\n aes(x = Data, y = Response,\n ymin = Response - SD, ymax = Response + SD)) +\n geom_text_repel(data = df %>% slice_min(order_by = Response, n = 5),\n aes(x = Data, label = Data, y = Response),\n min.segment.length = 0, xlim = 80,\n force = 9, color = \"firebrick3\") +\n theme(axis.text.x = element_blank(),\n axis.ticks.x = element_blank())\n"
},
{
"answer_id": 74608285,
"author": "Andre Wildberg",
"author_id": 9462095,
"author_profile": "https://Stackoverflow.com/users/9462095",
"pm_score": 1,
"selected": false,
"text": "head tail library(ggplot2)\n\nggplot(rbind(head(df, 5), tail(df, 5))) + \n geom_col(aes(Data, Response)) + \n geom_errorbar(aes(Data, ymin = Response - SD, ymax = Response + SD), width=.2)\n dat <- rbind(head(df, 5), \n list(\"D6_MEAN\", mean(df[-c(1:5, (nrow(df)-4):(nrow(df))), 2]),\n mean(df[-c(1:5, (nrow(df)-4):(nrow(df))), 3])), tail(df, 5))\n\ndat$grp <- c(rep(\"top\", 5), \n paste(\"mean of\", nrow(df)-10, \"rows\"), rep(\"bottom\", 5))\n\ndat$grp <- factor(dat$grp, levels=unique(dat$grp))\n\nggplot(dat) + \n geom_col(aes(Data, Response, fill=grp)) + \n geom_errorbar(aes(Data, ymin = Response - SD, ymax = Response + SD), width=.2)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74607887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2446374/"
] |
74,607,938
|
<p>I have two projects that share common files from the common folder.</p>
<p>Now, I am trying to setup eslint so I can lint both the project folder and the common folder.</p>
<p>Folder structure is like this:</p>
<ul>
<li><p>MyProjectFolder</p>
</li>
<li><p>.eslintrc.js</p>
</li>
<li>
<pre><code>src
</code></pre>
</li>
<li><p>CommonFolder</p>
</li>
<li>
<pre><code>src
</code></pre>
</li>
</ul>
<p>I am trying to add an <code>"override: [ files: ["src/**/*.js", "../CommonFolder/src/**/*.js"] }]</code>" to eslint with relative path, but eslint is telling me that it is an invalid override path.</p>
<p>So, does anyone know how I can add CommonFolder into .eslintrc.js file?</p>
|
[
{
"answer_id": 74607864,
"author": "jared_mamrot",
"author_id": 12957340,
"author_profile": "https://Stackoverflow.com/users/12957340",
"pm_score": 2,
"selected": false,
"text": "library(tidyverse)\nlibrary(ggrepel)\n\ndf <- structure(list(Data = c(\"D1\", \"D2\", \"D3\", \"D4\", \"D5\", \"D6\", \"D7\", \n \"D8\", \"D9\", \"D10\", \"D11\", \"D12\", \"D13\", \"D14\", \"D15\", \"D16\", \n \"D17\", \"D18\", \"D19\", \"D20\", \"D21\", \"D22\", \"D23\", \"D24\", \"D25\", \n \"D26\", \"D27\", \"D28\", \"D29\", \"D30\", \"D31\", \"D32\", \"D33\", \"D34\", \n \"D35\", \"D36\", \"D37\", \"D38\", \"D39\", \"D40\", \"D41\", \"D42\", \"D43\", \n \"D44\", \"D45\", \"D46\", \"D47\", \"D48\", \"D49\", \"D50\", \"D51\", \"D52\", \n \"D53\", \"D54\", \"D55\", \"D56\", \"D57\", \"D58\", \"D59\", \"D60\", \"D61\", \n \"D62\", \"D63\", \"D64\", \"D65\", \"D66\", \"D67\", \"D68\", \"D69\", \"D70\", \n \"D71\", \"D72\", \"D73\", \"D74\", \"D75\", \"D76\", \"D77\", \"D78\", \"D79\", \n \"D80\", \"D81\", \"D82\", \"D83\", \"D84\", \"D85\", \"D86\", \"D87\", \"D88\", \n \"D89\", \"D90\", \"D91\", \"D92\", \"D93\", \"D94\", \"D95\", \"D96\", \"D97\", \n \"D98\"), Response = c(18.11, 17.6, 16.14, 16.02, 14.73, 14.07, \n 13.41, 13.08, 12.73, 12.51, 11.53, 9.85, 9.78, 9.74, 8.98, 1.54, \n 1.54, 1.51, 1.51, 1.49, 1.49, 1.49, 1.44, 1.44, 1.39, 1.37, 1.36, \n 1.35, 1.34, 1.34, 1.33, 1.33, 1.31, 1.3, 1.29, 1.26, 1.23, 1.21, \n 1.19, 1.18, 1.14, 1.12, 1.07, 1.05, 1.03, 1.03, 1.03, 1.02, 1.01, \n 1, 0.99, 0.98, 0.95, 0.94, 0.93, 0.92, 0.91, 0.87, 0.83, 0.83, \n 0.81, 0.8, 0.8, 0.79, 0.78, 0.76, 0.76, 0.75, 0.75, 0.73, 0.73, \n 0.71, 0.69, 0.68, 0.67, 0.67, 0.64, 0.63, 0.63, -11.6, -11.6, \n -11.6, -11.7, -11.7, -11.7, -11.8, -11.9, -11.9, -12, -12.2, \n -12.3, -12.4, -12.4, -12.5, -12.5, -12.6, -12.6, -12.7), SD = c(8.98, \n 8.19, 2.57, 8.36, 2.14, 5.51, 3.01, 9.8, 6.88, 3.21, 11.35, 5.6, \n 13.29, 4.9, 9.45, 11.06, 5.41, 28.78, 13.46, 4.23, 12.24, 1.41, \n 11.03, 11.29, 2.17, 7.11, 3.08, 1.8, 12.09, 4.79, 1.01, 3.69, \n 3.62, 3.06, 3.12, 13.19, 4.28, 12.05, 3.96, 13.4, 3.02, 7.97, \n 12, 3.91, 1.85, 3.96, 1.79, 2.67, 0.37, 7.45, 9.57, 1.95, 1.82, \n 3.02, 6.97, 6.73, 1.22, 5.45, 4.9, 2.48, 6.88, 3.81, 1.86, 1.83, \n 7.56, 11.25, 2.72, 3.68, 2.41, 4.44, 2.59, 6.24, 2.56, 3.96, \n 10.56, 1.65, 7.22, 4.12, 4.01, 3.4, 2.8, 0.92, 9.58, 1.17, 1.36, \n 0.91, 5.8, 4.26, 3.48, 3.7, 11.99, 5.77, 11.06, 3.09, 0.12, 3.18, \n 5.49, 5.81)), class = \"data.frame\", row.names = c(NA, -98L))\ndf$Data <- factor(df$Data, levels = paste0(\"D\", 1:98), ordered = TRUE)\n\nggplot() +\n geom_line(data = df, aes(x = Data, y = Response, group = 1),\n alpha = 0.25) +\n geom_point(data = df, aes(x = Data, y = Response, group = 1),\n alpha = 0.25) +\n geom_line(data = df %>% slice_max(order_by = Response, n = 5),\n aes(x = Data, y = Response, group = 1)) +\n geom_point(data = df %>% slice_max(order_by = Response, n = 5),\n aes(x = Data, y = Response, group = 1)) +\n geom_linerange(data = df %>% slice_max(order_by = Response, n = 5),\n aes(x = Data, y = Response,\n ymin = Response - SD, ymax = Response + SD)) +\n geom_text_repel(data = df %>% slice_max(order_by = Response, n = 5),\n aes(x = Data, label = Data, y = Response),\n min.segment.length = 0, xlim = 10,\n force = 5, color = \"firebrick3\") +\n geom_line(data = df %>% slice_min(order_by = Response, n = 5),\n aes(x = Data, y = Response, group = 1)) +\n geom_point(data = df %>% slice_min(order_by = Response, n = 5),\n aes(x = Data, y = Response, group = 1)) +\n geom_linerange(data = df %>% slice_min(order_by = Response, n = 5),\n aes(x = Data, y = Response,\n ymin = Response - SD, ymax = Response + SD)) +\n geom_text_repel(data = df %>% slice_min(order_by = Response, n = 5),\n aes(x = Data, label = Data, y = Response),\n min.segment.length = 0, xlim = 80,\n force = 9, color = \"firebrick3\") +\n theme(axis.text.x = element_blank(),\n axis.ticks.x = element_blank())\n"
},
{
"answer_id": 74608285,
"author": "Andre Wildberg",
"author_id": 9462095,
"author_profile": "https://Stackoverflow.com/users/9462095",
"pm_score": 1,
"selected": false,
"text": "head tail library(ggplot2)\n\nggplot(rbind(head(df, 5), tail(df, 5))) + \n geom_col(aes(Data, Response)) + \n geom_errorbar(aes(Data, ymin = Response - SD, ymax = Response + SD), width=.2)\n dat <- rbind(head(df, 5), \n list(\"D6_MEAN\", mean(df[-c(1:5, (nrow(df)-4):(nrow(df))), 2]),\n mean(df[-c(1:5, (nrow(df)-4):(nrow(df))), 3])), tail(df, 5))\n\ndat$grp <- c(rep(\"top\", 5), \n paste(\"mean of\", nrow(df)-10, \"rows\"), rep(\"bottom\", 5))\n\ndat$grp <- factor(dat$grp, levels=unique(dat$grp))\n\nggplot(dat) + \n geom_col(aes(Data, Response, fill=grp)) + \n geom_errorbar(aes(Data, ymin = Response - SD, ymax = Response + SD), width=.2)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74607938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15171873/"
] |
74,607,975
|
<p>Let's say I have four samples: id=1, 2, 3, and 4, with one or more measurements on each of those samples:</p>
<p><a href="https://i.stack.imgur.com/jAgsm.png" rel="nofollow noreferrer">Table</a></p>
<pre><code> ID Value
1 1
1 2
2 3
2 -4
3 -5
4 6
</code></pre>
<p>I want to remove duplicates, keeping only one entry per ID - the one having the largest absolute value of the "value" column. I.e., this is what I want:</p>
<p><a href="https://i.stack.imgur.com/E2Y73.png" rel="nofollow noreferrer">Result</a></p>
<pre><code> ID Value
1 2
2 -4
3 -5
4 6
</code></pre>
<p>How might I do this in SAS?</p>
<p>I didn't find a solution to do this with SAS, so I tried to export it to Excel and use pivot table and "Value Field max" -setting, but that only gave me highest value, and and I need highest difference from zero.</p>
|
[
{
"answer_id": 74607864,
"author": "jared_mamrot",
"author_id": 12957340,
"author_profile": "https://Stackoverflow.com/users/12957340",
"pm_score": 2,
"selected": false,
"text": "library(tidyverse)\nlibrary(ggrepel)\n\ndf <- structure(list(Data = c(\"D1\", \"D2\", \"D3\", \"D4\", \"D5\", \"D6\", \"D7\", \n \"D8\", \"D9\", \"D10\", \"D11\", \"D12\", \"D13\", \"D14\", \"D15\", \"D16\", \n \"D17\", \"D18\", \"D19\", \"D20\", \"D21\", \"D22\", \"D23\", \"D24\", \"D25\", \n \"D26\", \"D27\", \"D28\", \"D29\", \"D30\", \"D31\", \"D32\", \"D33\", \"D34\", \n \"D35\", \"D36\", \"D37\", \"D38\", \"D39\", \"D40\", \"D41\", \"D42\", \"D43\", \n \"D44\", \"D45\", \"D46\", \"D47\", \"D48\", \"D49\", \"D50\", \"D51\", \"D52\", \n \"D53\", \"D54\", \"D55\", \"D56\", \"D57\", \"D58\", \"D59\", \"D60\", \"D61\", \n \"D62\", \"D63\", \"D64\", \"D65\", \"D66\", \"D67\", \"D68\", \"D69\", \"D70\", \n \"D71\", \"D72\", \"D73\", \"D74\", \"D75\", \"D76\", \"D77\", \"D78\", \"D79\", \n \"D80\", \"D81\", \"D82\", \"D83\", \"D84\", \"D85\", \"D86\", \"D87\", \"D88\", \n \"D89\", \"D90\", \"D91\", \"D92\", \"D93\", \"D94\", \"D95\", \"D96\", \"D97\", \n \"D98\"), Response = c(18.11, 17.6, 16.14, 16.02, 14.73, 14.07, \n 13.41, 13.08, 12.73, 12.51, 11.53, 9.85, 9.78, 9.74, 8.98, 1.54, \n 1.54, 1.51, 1.51, 1.49, 1.49, 1.49, 1.44, 1.44, 1.39, 1.37, 1.36, \n 1.35, 1.34, 1.34, 1.33, 1.33, 1.31, 1.3, 1.29, 1.26, 1.23, 1.21, \n 1.19, 1.18, 1.14, 1.12, 1.07, 1.05, 1.03, 1.03, 1.03, 1.02, 1.01, \n 1, 0.99, 0.98, 0.95, 0.94, 0.93, 0.92, 0.91, 0.87, 0.83, 0.83, \n 0.81, 0.8, 0.8, 0.79, 0.78, 0.76, 0.76, 0.75, 0.75, 0.73, 0.73, \n 0.71, 0.69, 0.68, 0.67, 0.67, 0.64, 0.63, 0.63, -11.6, -11.6, \n -11.6, -11.7, -11.7, -11.7, -11.8, -11.9, -11.9, -12, -12.2, \n -12.3, -12.4, -12.4, -12.5, -12.5, -12.6, -12.6, -12.7), SD = c(8.98, \n 8.19, 2.57, 8.36, 2.14, 5.51, 3.01, 9.8, 6.88, 3.21, 11.35, 5.6, \n 13.29, 4.9, 9.45, 11.06, 5.41, 28.78, 13.46, 4.23, 12.24, 1.41, \n 11.03, 11.29, 2.17, 7.11, 3.08, 1.8, 12.09, 4.79, 1.01, 3.69, \n 3.62, 3.06, 3.12, 13.19, 4.28, 12.05, 3.96, 13.4, 3.02, 7.97, \n 12, 3.91, 1.85, 3.96, 1.79, 2.67, 0.37, 7.45, 9.57, 1.95, 1.82, \n 3.02, 6.97, 6.73, 1.22, 5.45, 4.9, 2.48, 6.88, 3.81, 1.86, 1.83, \n 7.56, 11.25, 2.72, 3.68, 2.41, 4.44, 2.59, 6.24, 2.56, 3.96, \n 10.56, 1.65, 7.22, 4.12, 4.01, 3.4, 2.8, 0.92, 9.58, 1.17, 1.36, \n 0.91, 5.8, 4.26, 3.48, 3.7, 11.99, 5.77, 11.06, 3.09, 0.12, 3.18, \n 5.49, 5.81)), class = \"data.frame\", row.names = c(NA, -98L))\ndf$Data <- factor(df$Data, levels = paste0(\"D\", 1:98), ordered = TRUE)\n\nggplot() +\n geom_line(data = df, aes(x = Data, y = Response, group = 1),\n alpha = 0.25) +\n geom_point(data = df, aes(x = Data, y = Response, group = 1),\n alpha = 0.25) +\n geom_line(data = df %>% slice_max(order_by = Response, n = 5),\n aes(x = Data, y = Response, group = 1)) +\n geom_point(data = df %>% slice_max(order_by = Response, n = 5),\n aes(x = Data, y = Response, group = 1)) +\n geom_linerange(data = df %>% slice_max(order_by = Response, n = 5),\n aes(x = Data, y = Response,\n ymin = Response - SD, ymax = Response + SD)) +\n geom_text_repel(data = df %>% slice_max(order_by = Response, n = 5),\n aes(x = Data, label = Data, y = Response),\n min.segment.length = 0, xlim = 10,\n force = 5, color = \"firebrick3\") +\n geom_line(data = df %>% slice_min(order_by = Response, n = 5),\n aes(x = Data, y = Response, group = 1)) +\n geom_point(data = df %>% slice_min(order_by = Response, n = 5),\n aes(x = Data, y = Response, group = 1)) +\n geom_linerange(data = df %>% slice_min(order_by = Response, n = 5),\n aes(x = Data, y = Response,\n ymin = Response - SD, ymax = Response + SD)) +\n geom_text_repel(data = df %>% slice_min(order_by = Response, n = 5),\n aes(x = Data, label = Data, y = Response),\n min.segment.length = 0, xlim = 80,\n force = 9, color = \"firebrick3\") +\n theme(axis.text.x = element_blank(),\n axis.ticks.x = element_blank())\n"
},
{
"answer_id": 74608285,
"author": "Andre Wildberg",
"author_id": 9462095,
"author_profile": "https://Stackoverflow.com/users/9462095",
"pm_score": 1,
"selected": false,
"text": "head tail library(ggplot2)\n\nggplot(rbind(head(df, 5), tail(df, 5))) + \n geom_col(aes(Data, Response)) + \n geom_errorbar(aes(Data, ymin = Response - SD, ymax = Response + SD), width=.2)\n dat <- rbind(head(df, 5), \n list(\"D6_MEAN\", mean(df[-c(1:5, (nrow(df)-4):(nrow(df))), 2]),\n mean(df[-c(1:5, (nrow(df)-4):(nrow(df))), 3])), tail(df, 5))\n\ndat$grp <- c(rep(\"top\", 5), \n paste(\"mean of\", nrow(df)-10, \"rows\"), rep(\"bottom\", 5))\n\ndat$grp <- factor(dat$grp, levels=unique(dat$grp))\n\nggplot(dat) + \n geom_col(aes(Data, Response, fill=grp)) + \n geom_errorbar(aes(Data, ymin = Response - SD, ymax = Response + SD), width=.2)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74607975",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20628265/"
] |
74,608,004
|
<p><strong>The problem description:</strong></p>
<ul>
<li>Button 1 should show/hide only the data of floor 1.</li>
<li>Button 2 should how/hide the data of floor 2.</li>
<li>Button 3 should show/hide data of floor 3.</li>
</ul>
<p>As it stands each button shows/hides everything.</p>
<p>I could repeat my code for each JavaScript object and it would work - but I want to abstract the repetition for any JSON object that is referenced.</p>
<p>I tried different things but gave up and decided to ask SO. Seeing the replies will help me "Think SVELTE"</p>
<p><a href="https://svelte.dev/repl/6e498fa577674323b4a602b4b4b3acf2?version=3.53.1" rel="nofollow noreferrer">https://svelte.dev/repl/6e498fa577674323b4a602b4b4b3acf2?version=3.53.1</a></p>
<pre><code><div class="parent-container">
{#each rooms as room}
<button on:click={showHide}>Floor number {room.floor} </button>
{#if showState}
<div class={showState}>
<h2>{room.floor}</h2>
{#each room.rooms as singleRoom}
<div>
<h2>{singleRoom.number}</h2>
</div>
{/each}
</div>
{/if}
{/each}
</div>
<script>
let showState = "hide";
function showHide(){
showState = (showState ==="hide") ? "show" : "hide";
}
let rooms =[
{
floor:1,
rooms:[{number:101},{number:102},{number:103}]
},
{
floor:2,
rooms:[{number:201},{number:202},{number:203}]
},
{
floor:3,
rooms:[{number:301},{number:302},{number:303}]
},
]
</script>
<style>
.hide{
display: none;
}
</style>
</code></pre>
|
[
{
"answer_id": 74608219,
"author": "AntoineD",
"author_id": 20628272,
"author_profile": "https://Stackoverflow.com/users/20628272",
"pm_score": -1,
"selected": false,
"text": "this.getAttribute('attr-data-floor') <div class=\"parent-container\">\n {#each rooms as room}\n <button on:click={showHide} attr-data-floor={room.floor}>Floor number {room.floor} </button>\n\n {#if showState[room.floor] }\n <div class={showState[room.floor]}>\n <h2>{room.floor}</h2>\n {#each room.rooms as singleRoom}\n <div>\n <h2>{singleRoom.number}</h2>\n \n </div>\n\n {/each}\n </div>\n {/if}\n\n {/each}\n</div>\n\n<script> \n\nlet showState ={1:\"hide\", 2:\"hide\",3:\"hide\"} ; //one mor because 0\n\nfunction showHide(){\n let num = this.getAttribute('attr-data-floor') ;\n showState[num] = (showState[num] ===\"hide\") ? \"show\" : \"hide\";\n}\n\nlet rooms =[\n {\n floor:1,\n rooms:[{number:101},{number:102},{number:103}]\n },\n {\n floor:2,\n rooms:[{number:201},{number:202},{number:203}]\n },\n\n {\n floor:3,\n rooms:[{number:301},{number:302},{number:303}]\n },\n\n]\n\n\n</script>\n\n<style>\n .hide{\n display: none;\n }\n</style>\n"
},
{
"answer_id": 74608367,
"author": "H.B.",
"author_id": 546730,
"author_profile": "https://Stackoverflow.com/users/546730",
"pm_score": 1,
"selected": false,
"text": "#each <div class=\"parent-container\">\n {#each rooms as room, i}\n <button on:click={() => showHide(i)}>Floor number {room.floor} </button>\n\n {#if visibility[i]}\n <div>\n <h2>{room.floor}</h2>\n {#each room.rooms as singleRoom}\n <div><h2>{singleRoom.number}</h2></div>\n {/each}\n </div>\n {/if}\n {/each}\n</div>\n\n<script>\n let rooms = [\n { floor: 1, rooms: [{number:101},{number:102},{number:103}] },\n { floor: 2, rooms: [{number:201},{number:202},{number:203}] },\n { floor: 3, rooms: [{number:301},{number:302},{number:303}] },\n ];\n\n let visibility = new Array(rooms.length).fill(false);\n\n function showHide(index) {\n visibility[index] = !visibility[index];\n }\n</script>\n #each visiblity"
},
{
"answer_id": 74608609,
"author": "Michael M.",
"author_id": 13376511,
"author_profile": "https://Stackoverflow.com/users/13376511",
"pm_score": 2,
"selected": true,
"text": "Floor <script>\n import Floor from './Floor.svelte';\n \n let rooms =[\n {\n floor:1,\n rooms:[{number:101},{number:102},{number:103}]\n },\n {\n floor:2,\n rooms:[{number:201},{number:202},{number:203}]\n },\n \n {\n floor:3,\n rooms:[{number:301},{number:302},{number:303}]\n },\n ];\n</script>\n\n<div class=\"parent-container\">\n {#each rooms as room}\n <Floor room={room}/>\n {/each}\n</div>\n <script>\n export let room;\n \n let showState = false;\n function showHide() {\n showState = !showState;\n }\n</script>\n\n<style>\n .hide{\n display: none;\n }\n</style>\n\n<button on:click={showHide}>Floor number {room.floor} </button>\n\n{#if showState}\n <div class:hide={!showState}>\n <h2>{room.floor}</h2>\n {#each room.rooms as singleRoom}\n <div>\n <h2>{singleRoom.number}</h2>\n </div>\n {/each}\n </div>\n{/if}\n showState class:"
},
{
"answer_id": 74646564,
"author": "Word Nerd",
"author_id": 10735864,
"author_profile": "https://Stackoverflow.com/users/10735864",
"pm_score": 1,
"selected": false,
"text": "<div class=\"parent-container\">\n {#each floors as floor}\n <button on:click={() => floor.visibility = floor.visibility * -1}>\n Floor number {floor.floor}\n </button>\n {#if floor.visibility === 1}\n <!--<div class=yourstyleclasshere>-->\n <h2>Floor: {floor.floor}</h2>\n {#each floor.rooms as singleRoom}\n <div>\n <h2>{singleRoom.number}</h2>\n </div>\n {/each}\n <!--</div>-->\n {/if}\n {/each}\n</div>\n\n<script> \nlet floors = [\n {\n floor:1,\n rooms:[{number:101},{number:102},{number:103}],\n visibility: -1\n },\n {\n floor:2,\n rooms:[{number:201},{number:202},{number:203}],\n visibility: -1\n },\n\n {\n floor:3,\n rooms:[{number:301},{number:302},{number:303}],\n visibility: -1\n }\n]\n</script>\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74608004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1152980/"
] |
74,608,026
|
<p>Hello I have this CSS code:</p>
<pre><code>.bar .progress-line.html span {
width: 78%;
}
</code></pre>
<p>How can I change the width from javascript? I have tried many ways like</p>
<pre><code>$(".bar .progress-line.html span").css("width", "10%");
</code></pre>
<p>But nothing is found.</p>
<p>I also tried this:</p>
<pre><code>$(".bar .progress-line.html span").css("width", "10%");
</code></pre>
<p>but nothing happens.</p>
<p>Original example: <a href="https://codepen.io/Prashal9499/pen/oNWzPqR" rel="nofollow noreferrer">https://codepen.io/Prashal9499/pen/oNWzPqR</a></p>
|
[
{
"answer_id": 74608051,
"author": "qamar",
"author_id": 1040996,
"author_profile": "https://Stackoverflow.com/users/1040996",
"pm_score": -1,
"selected": false,
"text": "$(\".bar, .progress-line, .html, span\").css(\"width\", \"10%\");\n"
},
{
"answer_id": 74608678,
"author": "wazz",
"author_id": 1171702,
"author_profile": "https://Stackoverflow.com/users/1171702",
"pm_score": 1,
"selected": true,
"text": ".progress-line.html span.change::after {\n content: \"55%\";\n}\n $(\".progress-line.html span\").css(\"width\", \"55%\");\n$(\".progress-line.html span\").addClass(\"change\");\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74608026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20628329/"
] |
74,608,037
|
<p>So, I want to insert an entire array of values into a particular column and I don't know exactly what to do. Everything I have tried gives me the "Array to string conversion" error.</p>
<p>Here is my controller code:</p>
<pre><code>public function processInternationaTransfer(Request $request)
{
$international_info = Validator::make($request->all(),
[
'beneficiary_name' => 'required',
'beneficiary_acc_num' => 'required|numeric',
'beneficiary_bank' => 'required',
'beneficiary_swiftcode' => 'required',
'routing_transit_no' => 'required|numeric',
'currency' => 'required',
'amount' => 'required|numeric',
'note' => 'required',
]
);
if($international_info->fails())
{
return response()->json(['errors'=>$international_info->errors()->all()]);
}
$info = $international_info->validated();
$balance = $info['currency'].'_balance';
if(user_details()->$balance < InternationalAmount($info['amount']))
{
return response()->json(['insufficient_amount'=>'Insufficient Amount']);
}
else
{
TransactionLog::create([
'username' => user()->username,
'type' => 'Exchange',
'cred_deb' => 'Debit',
'time'=> Carbon::now('Africa/Lagos')->format('l, d F, Y g:i A'),
'status' => 2,
'amount'=>InternationalAmount($info['amount']),
'currency'=>$info['currency'],
'reason' => $info['note'],
'inter_details' => $info,
'transaction_id' => rand(100000000, 999999999),
]);
return response()->json(['success'=>'Transaction Processed, Awaiting Confirmation']);
}
}
</code></pre>
<p>How do I insert that array of values into the inter_details column?</p>
<p>I tried inserting it as it is above, and it gives me "array to string conversion" error.
I want to be able to fetch it after inserting it.</p>
|
[
{
"answer_id": 74608302,
"author": "Igor",
"author_id": 17005821,
"author_profile": "https://Stackoverflow.com/users/17005821",
"pm_score": 0,
"selected": false,
"text": "$inter_details = [\n 'beneficiary_name' => 'John Doe',\n 'beneficiary_acc_num' => '12345678',\n 'beneficiary_bank' => 'Bank of America',\n 'beneficiary_swiftcode' => 'ABC123',\n 'routing_transit_no' => '123456789',\n 'currency' => 'USD',\n 'amount' => '1000',\n 'note' => 'This is a test transaction',\n];\n\nDB::table('transaction_logs')->insert([\n 'inter_details' => json_encode($inter_details),\n]);\n $inter_details = DB::table('transaction_logs')->select('inter_details')->get();\n\n$inter_details = json_decode($inter_details, true);\n"
},
{
"answer_id": 74608482,
"author": "xenooooo",
"author_id": 20283630,
"author_profile": "https://Stackoverflow.com/users/20283630",
"pm_score": 2,
"selected": true,
"text": "inter_details json() $table->json('inter_details'); //it will create a longText column in database so that it can accept many characters.\n TransactionLogs protected $casts = [\n 'inter_details' => 'array',\n]\n json_encode() json_decode() casts"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74608037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19485666/"
] |
74,608,065
|
<p>I am new to Javascript and React Native and I'm confused why the following code doesn't navigate me to my other screen:</p>
<pre><code>const Stack = createNativeStackNavigator();
export default function App() {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName = "Home">
<Stack.Screen name = "Home" component = {HomeScreen} />
<Stack.Screen name = "Login" component = {LoginScreen} />
<Stack.Screen name = "Register" component = {RegisterScreen}/>
<Stack.Screen name = "Hub" component = {HubScreen}/>
<Stack.Screen name = "NewList" component = {NewListScreen}/>
</Stack.Navigator>
</NavigationContainer>
);
}
function RegisterScreen({navigation}) {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
return (
<View style={styles.container}>
<Text style={styles.label}>Registration</Text>
<TextInput
style={styles.input}
placeholder="Username"
onChangeText={(text) => setUsername(text)}
/>
<TextInput
style={styles.input}
placeholder="Password"
onChangeText={(text) => setPassword(text)}
/>
<Button
title="Register"
onPress = {() => Register(username, password)}
/>
</View>
)
}
function Register(username, password){
Alert.alert("All Done!", "You have successfully registered.", {text: "OK", onPress: () => {navigation.navigate('Home')}})
}
</code></pre>
<p>I want function Register to show an alert where the user can press ok and for them to be redirected back to the home screen. The alert apears however pressing okay doesn't navigate back to the Home screen. From what I've read on the React Native Navigation docs function Register somehows needs access to navigation parameter but im confused on how to practically do that.</p>
<p>I tried using <code>useNavigation();</code> but I kept getting a hook call error.
I have also tried NavigationRef but with no success. I have also tried putting <code>Register</code> inside <code>RegisterScreen</code>. Also tried having <code>navigation</code> as a parameter of <code>Register</code>. No change in output.</p>
|
[
{
"answer_id": 74608232,
"author": "Kriss_Vector",
"author_id": 20621722,
"author_profile": "https://Stackoverflow.com/users/20621722",
"pm_score": 2,
"selected": true,
"text": "Register RegisterScreen Alert.alert(\"All Done!\", \"You have successfully registered.\", [{text: \"OK\", onPress: () => {navigation.navigate('Home')}}])\n"
},
{
"answer_id": 74609073,
"author": "NAZIR HUSSAIN",
"author_id": 20587701,
"author_profile": "https://Stackoverflow.com/users/20587701",
"pm_score": 0,
"selected": false,
"text": "Register() RegisterScreen function RegisterScreen({navigation}) {\n const [username, setUsername] = useState('');\n const [password, setPassword] = useState('');\n\nfunction Register(username, password){\n const user = new User(username, password);\n //const navigation = useNavigation();\n user_array.push(user)\n console.log(user_array[0].username)\n Alert.alert(\"All Done!\", \"You have successfully registered.\", [{text: \"OK\", onPress: () => {navigation.navigate('Home')}}])\n}\n\n return (\n <View style={styles.container}>\n <Text style={styles.label}>Registration</Text>\n <TextInput \n style={styles.input} \n placeholder=\"Username\"\n onChangeText={(text) => setUsername(text)}\n />\n <TextInput \n style={styles.input} \n placeholder=\"Password\"\n onChangeText={(text) => setPassword(text)}\n />\n <Button\n title=\"Register\"\n onPress = {() => Register(username, password)}\n />\n </View>\n )\n}\n Register(username, password, navigation)\n\n function Register(username, password, navigation){\n const user = new User(username, password);\n user_array.push(user)\n console.log(user_array[0].username)\n Alert.alert(\"All Done!\", \"You have successfully registered.\", [{text: \"OK\", onPress: () => {navigation.navigate('Home')}}])\n}\n user_array const user = new User(username, password);"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74608065",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13424158/"
] |
74,608,072
|
<p>my question is about Android Studio, in case someone knows how to open the message application that the android device brings to send a message when clicking on a button... I have an application developed in Android Studio with Java, which It registers contacts and I want that when a button is pressed that is to send messages, the application takes the phone number of the person to whom the button belongs and opens the phone messages application no need to send the message as a parameter.</p>
<p>I already did the function of making the call, but I couldn't find examples that help me for what I want to do... I hope someone has some idea and helps me, thank you very much in advance.</p>
|
[
{
"answer_id": 74608178,
"author": "franvillacis",
"author_id": 15386464,
"author_profile": "https://Stackoverflow.com/users/15386464",
"pm_score": -1,
"selected": true,
"text": "String number = \"12346556\"; // The number \nstartActivity(new Intent(Intent.ACTION_VIEW, Uri.fromParts(\"sms\", number, null)));\n"
},
{
"answer_id": 74608446,
"author": "Wui Keat Cheah",
"author_id": 20570897,
"author_profile": "https://Stackoverflow.com/users/20570897",
"pm_score": 0,
"selected": false,
"text": "SmsManager smsManager = SmsManager.getDefault();\nsmsManager.sendTestMessage(\"phone number\", null, \"message content\", null, null);\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74608072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19506126/"
] |
74,608,080
|
<p>I'm trying to break membership periods by month, but only for given year, in our example it <em><strong>2022</strong></em>
Self inclusive code below works fine but it breaks all period, I only trying to process by month for 2022. Code below also holds definition for test data inside (<code>#t temp table</code>). I'm using #numbers table as a tally. I'm using SQL Server 2017</p>
<pre><code>/*
SELECT TOP 100 ROW_NUMBER() OVER(ORDER BY (SELECT NULL))-1 AS n
INTO #numbers FROM master.dbo.spt_values --- Select top 100 * from #t numbers
----- data prep part
SELECT * INTO #t FROM ( -- DROP TABLE IF EXISTS #t
SELECT 100 ID, CAST('2022-03-02' AS DATE) eStart , CAST('2022-03-15' AS DATE) eEnd, '1 Same Month island' note , 100 Idx
UNION SELECT 200, '2022-01-11' , '2022-03-27', '2 Same Month Start 1', 2001
UNION SELECT 200, '2022-02-15' , '2022-5-15', '2 Same Month Start 2', 2002
UNION SELECT 300, '2021-05-08' , '2024-12-31', '3 Future eEnd ' ,3000
UNION SELECT 440, '2022-10-15' , '2023-10-10', '4 Future end 2' ,4400
) b -- SELECT * FROM #t
*/
select DISTINCT t.ID,
CASE WHEN YEAR(DATEADD(MONTH, DATEDIFF(MONTH, 0, t.eStart) + n, 0)) < 2022 THEN eStart
WHEN YEAR(DATEADD(MONTH, DATEDIFF(MONTH, 0, t.eStart) + n, 0)) > 2022 THEN '1/1/2023' -- first day after 2022
ELSE CASE WHEN n = 0 then t.eStart ELSE dateadd(month, datediff(month, 0, t.eStart) + n, 0) END
END eStart,
case when n = datediff(month, eStart, eEnd) then t.eEnd
else eomonth(dateadd(month, datediff(month, 0, t.eStart) + n, 0)) END eEnd
-- ,n, note ,eStart eStartOrig, eEnd eEndOrig
from #t t
join #numbers n on n.n <= datediff(month, eStart, eEnd)
order by t.ID, eStart
</code></pre>
<p><a href="https://i.stack.imgur.com/V150s.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/V150s.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74609013,
"author": "T N",
"author_id": 12637193,
"author_profile": "https://Stackoverflow.com/users/12637193",
"pm_score": 2,
"selected": true,
"text": "Start1 < End2 AND Start2 < End1 Start1 <= End2 AND Start2 <= End1 -- Membership data #t as defined in original post\n\nSELECT\n A.MonthStart,\n EOMONTH(A.MonthStart) AS MonthEnd\nINTO #months\nFROM (VALUES (1), (2), (3), (4), (5), (6), (7), (8), (9), (10), (11), (12)) N(N)\nCROSS APPLY (SELECT DATEFROMPARTS(2022, N.N, 1) AS MonthStart) A\n\nSELECT * from #months\n\nSELECT\n t.ID,\n CASE WHEN m.MonthStart >= t.eStart THEN m.MonthStart ELSE t.eStart END AS eStart,\n CASE WHEN m.MonthEnd <= t.eEnd THEN m.MonthEnd ELSE t.eEnd END AS eEnd,\n t.Idx\nFROM #t t\nJOIN #months m -- Overlapping months (inclusive dates)\n ON m.MonthStart <= t.eEnd \n AND t.eStart <= m.MonthEnd \nORDER BY t.ID, t.Idx, eStart -- Added t.Idx to better match desired results\n"
},
{
"answer_id": 74625660,
"author": "Mario Trento",
"author_id": 1208263,
"author_profile": "https://Stackoverflow.com/users/1208263",
"pm_score": 0,
"selected": false,
"text": "select DISTINCT t.ID,\n CASE WHEN \n YEAR(DATEADD(MONTH, DATEDIFF(MONTH, 0, t.eStart) + n, 0)) < 2022 \n THEN eStart\n WHEN YEAR(DATEADD(MONTH, DATEDIFF(MONTH, 0, t.eStart) + n, 0)) > 2022 \n THEN '1/1/2023' -- first day after 2022 \n ELSE \n CASE WHEN n = 0 \n then t.eStart \n ELSE dateadd(month, datediff(month, 0, t.eStart) + n, 0) \n END \n END eStart, \n CASE WHEN YEAR( \n CASE WHEN n = DATEDIFF(MONTH, t.eStart, t.eEnd) THEN t.eEnd ELSE EOMONTH(DATEADD(MONTH, DATEDIFF(MONTH, 0, t.eStart) + n, 0)) END) < 2022\n THEN CASE \n WHEN t.eEnd < '1/1/2022' \n THEN t.eEnd \n ELSE DATEADD(d,-1,'1/1/2022') \n END\n WHEN YEAR(\n CASE WHEN \n n = DATEDIFF(MONTH, t.eStart, t.eEnd) THEN t.eEnd ELSE EOMONTH(DATEADD(MONTH, DATEDIFF(MONTH, 0, t.eStart) + n, 0)) \n END ) > 2022\n THEN t.eEnd\n ELSE\n CASE WHEN \n n = DATEDIFF(MONTH, t.eStart, t.eEnd) \n THEN t.eEnd \n ELSE EOMONTH(DATEADD(MONTH, DATEDIFF(MONTH, 0, t.eStart) + n, 0)) \n END \n END eEnd \n\nfrom #t t\njoin #numbers n on n.n <= datediff(month, eStart, eEnd) \n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74608080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1208263/"
] |
74,608,091
|
<p>I have a function that returns a leaflet icon with some properties:</p>
<pre><code>addSimpleIcon(
iconUrl,
iconRetinaUrl: string = null,
iconHeight: number = 20,
iconWidth: number = 20
): Icon {
const icon: Icon = L.icon({
iconUrl,
iconRetinaUrl,
iconSize: [iconWidth, iconHeight],
shadowSize: [0, 0],
iconAnchor: [iconWidth / 2, iconHeight / 2],
shadowAnchor: [0, 0],
popupAnchor: [0, 0]
});
return icon;
}
</code></pre>
<p>Here is my test</p>
<pre><code>it('should return a simple icon with properties', () => {
const test = 'testUrl';
const anotherTestString = 'test';
const testHeight = 2;
const testWidth = 2;
expect(
service.addSimpleIcon(test, anotherTestString, testHeight, testWidth)
).toEqual(anotherTestIcon);
});
</code></pre>
<p>Here is that const that the test is seeing if it is equal:</p>
<pre><code>const anotherTestIcon: Icon = L.icon({
iconUrl: 'testUrl',
iconRetinaUrl: 'test',
iconSize: [2, 2],
shadowSize: [0, 0],
iconAnchor: [20 / 2, 20 / 2],
shadowAnchor: [0, 0],
popupAnchor: [0, 0]
});
</code></pre>
<p>My overall thinking is I want to make sure that these values are getting set properly but I'm coming across this error here:</p>
<pre><code>Expected $.options.iconAnchor[0] = 1 to equal 10.
Expected $.options.iconAnchor[1] = 1 to equal 10.
</code></pre>
<p>I know it's expecting the iconAnchor, shadowAnchor, and popupAnchor but how can I pass these in if the method only takes four parameters, right?</p>
<p>Is there a better way to test this function?</p>
|
[
{
"answer_id": 74608136,
"author": "dbonev",
"author_id": 4200334,
"author_profile": "https://Stackoverflow.com/users/4200334",
"pm_score": 0,
"selected": false,
"text": "const testHeight = 2;\nconst testWidth = 2;\n const testHeight = 20;\nconst testWidth = 20;\n"
},
{
"answer_id": 74608214,
"author": "swhitmore",
"author_id": 2019974,
"author_profile": "https://Stackoverflow.com/users/2019974",
"pm_score": 1,
"selected": false,
"text": " it('should return a simple icon with properties', () => {\n const anotherTestIcon = {\n iconUrl: 'foop',\n iconRetinaUrl: 'doop',\n iconSize: [1, 1],\n shadowSize: [0, 0],\n iconAnchor: [1 / 2, 1 / 2],\n shadowAnchor: [0, 0],\n popupAnchor: [0, 0],\n };\n\n const result = component.addSimpleIcon(\n anotherTestIcon.iconUrl,\n anotherTestIcon.iconRetinaUrl,\n 1,\n 1\n );\n\n expect(result).toEqual(anotherTestIcon);\n });\n"
},
{
"answer_id": 74619453,
"author": "GustasRevenge",
"author_id": 20235789,
"author_profile": "https://Stackoverflow.com/users/20235789",
"pm_score": 1,
"selected": true,
"text": "object L.icon"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74608091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20235789/"
] |
74,608,140
|
<p>I need to be able to render text in python in various fonts and using various writing systems that use variable substitution of characters (Arabic, Hindi, Bengali). On a previous machine I had no issue doing this, but I just moved into a new machine with the same conda environment and it doesn't seme to work.</p>
<p>Mac OS 12.6
Python version 3.9.13
Libraqm version 0.9.0 (installed with brew)
Pillow version 9.2.0 (installed with pip)</p>
<p>Here's a minimal reproducible example. It should produce the Urdu word لڑكا – with the two groups of two letters attached – but instead it's producing something that looks like ا ک ڑ ل, with each letter disconnected. It's rendering the specific font correctly, so it's not a matter of the font not being found. When I run the last few lines of code checking for the 'raqm' feature, I get False.</p>
<pre><code>from PIL import ImageFont
from PIL import ImageDraw
from PIL import Image
font = ImageFont.truetype('KawkabMono-Bold.ttf',12,layout_engine=ImageFont.Layout.RAQM)
img = Image.new('1', (200, 100), 'white')
d = ImageDraw.Draw(img)
d.text((100,50), 'لڑكا', fill='black', font=font)
img.save('test.png')
from PIL import features
features.check_feature(feature='raqm')
</code></pre>
<p>I've tried installing and reinstalling a few times, and building from different sources. My guess is that libraqm is not on the correct path for Pillow, but I'm not sure how to check or fix this.</p>
<p>I tried running the minimal reproducible text and expected to see a properly render, RTL text with the correct rendering of text. Instead, I got an image file of the text rendered left-to-right and disconnected.</p>
|
[
{
"answer_id": 74608136,
"author": "dbonev",
"author_id": 4200334,
"author_profile": "https://Stackoverflow.com/users/4200334",
"pm_score": 0,
"selected": false,
"text": "const testHeight = 2;\nconst testWidth = 2;\n const testHeight = 20;\nconst testWidth = 20;\n"
},
{
"answer_id": 74608214,
"author": "swhitmore",
"author_id": 2019974,
"author_profile": "https://Stackoverflow.com/users/2019974",
"pm_score": 1,
"selected": false,
"text": " it('should return a simple icon with properties', () => {\n const anotherTestIcon = {\n iconUrl: 'foop',\n iconRetinaUrl: 'doop',\n iconSize: [1, 1],\n shadowSize: [0, 0],\n iconAnchor: [1 / 2, 1 / 2],\n shadowAnchor: [0, 0],\n popupAnchor: [0, 0],\n };\n\n const result = component.addSimpleIcon(\n anotherTestIcon.iconUrl,\n anotherTestIcon.iconRetinaUrl,\n 1,\n 1\n );\n\n expect(result).toEqual(anotherTestIcon);\n });\n"
},
{
"answer_id": 74619453,
"author": "GustasRevenge",
"author_id": 20235789,
"author_profile": "https://Stackoverflow.com/users/20235789",
"pm_score": 1,
"selected": true,
"text": "object L.icon"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74608140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20628386/"
] |
74,608,185
|
<p>I am trying to create a database use mysql workbench and I keep getting this error and my code looks fine. Not sure how I can resolve this. This is the error I am getting: Error Code: 1049. Unknown database 'dbo'.
I have tried so many things but only the first two lines of creating and using the database works. [screenshot attached]</p>
<p><a href="https://i.stack.imgur.com/fKCB4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fKCB4.png" alt="enter image description here" /></a></p>
<pre><code>
use employeedb;
create table dbo.Department(
DeprartmentId int AUTO_INCREMENT,
DepartmentName nvarchar(500),
PRIMARY KEY(DepartmentId)
);
insert into dbo.Department(DepartmentName) values ('IT');
insert into dbo.Department(DepartmentName) values ('Support');
create table dbo.Employee(
EmployeeId int AUTO_INCREMENT,
EmployeeName nvarchar(500),
Department nvarchar(500),
DateOfJoining datetime,
PhotoFileName nvarchar(500),
PRIMARY KEY(EmployeeId)
);
insert into dbo.Employee(EmployeeName,Department,DateOfJoining,PhotoFileName)
values ('John','IT','2022-11-27','anonymous.png');
select * from dbo.Employee;
</code></pre>
|
[
{
"answer_id": 74608136,
"author": "dbonev",
"author_id": 4200334,
"author_profile": "https://Stackoverflow.com/users/4200334",
"pm_score": 0,
"selected": false,
"text": "const testHeight = 2;\nconst testWidth = 2;\n const testHeight = 20;\nconst testWidth = 20;\n"
},
{
"answer_id": 74608214,
"author": "swhitmore",
"author_id": 2019974,
"author_profile": "https://Stackoverflow.com/users/2019974",
"pm_score": 1,
"selected": false,
"text": " it('should return a simple icon with properties', () => {\n const anotherTestIcon = {\n iconUrl: 'foop',\n iconRetinaUrl: 'doop',\n iconSize: [1, 1],\n shadowSize: [0, 0],\n iconAnchor: [1 / 2, 1 / 2],\n shadowAnchor: [0, 0],\n popupAnchor: [0, 0],\n };\n\n const result = component.addSimpleIcon(\n anotherTestIcon.iconUrl,\n anotherTestIcon.iconRetinaUrl,\n 1,\n 1\n );\n\n expect(result).toEqual(anotherTestIcon);\n });\n"
},
{
"answer_id": 74619453,
"author": "GustasRevenge",
"author_id": 20235789,
"author_profile": "https://Stackoverflow.com/users/20235789",
"pm_score": 1,
"selected": true,
"text": "object L.icon"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74608185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13669625/"
] |
74,608,188
|
<p>So I'm making a FPS game and when I try to shoot, it says my bullet lacks a rigidbody. I have a a rigidbody, so why is it like this?</p>
<p>Here's the bit of code that makes the bullet :</p>
<pre><code>Vector3 aimDir = (transform.forward).normalized;
Instantiate(gunData.bulletPrefab, muzzle.position, Quaternion.LookRotation(aimDir, Vector3.up));
Rigidbody bulletRb = gunData.bulletPrefab.GetComponent<Rigidbody>();
bulletRb.velocity = aimDir * gunData.bulletSpeed;
</code></pre>
|
[
{
"answer_id": 74608253,
"author": "user1805015",
"author_id": 1805015,
"author_profile": "https://Stackoverflow.com/users/1805015",
"pm_score": 1,
"selected": false,
"text": "var myNewBulletInstance = Instantiate(....\nmyNewBulletInstance.GetComponent<Rigidbody>();\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74608188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18283895/"
] |
74,608,196
|
<p>Hello I have this example json string:</p>
<pre><code>{
"property1":"value1",
"property2":"value2",
"anotherObject":{
"property1":"anothervalue1",
"property2":"anothervalue2",
"anotherOfAnother":{
"property1":"value1"
}
}
}
</code></pre>
<p>I need to get all others json objects inside and pass then to first level, preserving navigation path.
So example Json becomes:</p>
<pre><code>{
"property1":"value1",
"property2":"value2",
"anotherObject.property1":"anothervalue1",
"anotherObject.property2":"anothervalue2",
"anotherObject.anotherOfAnother.Property1":"value1"
}
</code></pre>
<p>How can I do it? I'm on .Net 6
Thanks in advance</p>
<p>I'm stuck, I haven't tried nothing yet. I'm looking for ideas on efficient ways to reach the goal, using JObject or JsonConvert.</p>
|
[
{
"answer_id": 74608527,
"author": "Serge",
"author_id": 11392290,
"author_profile": "https://Stackoverflow.com/users/11392290",
"pm_score": 3,
"selected": true,
"text": " var jsonObject = JObject.Parse(json);\n\n var result = jsonObject.Descendants()\n .Where(t => !t.HasValues)\n .Select(t => \"\\\"\" + t.Path + \"\\\"\" + \" : \" + \"\\\"\" + t.ToString() + \"\\\",\")\n .ToArray();\n\n //cut off the last \",\"\n result[result.Length - 1] = result[result.Length - 1]\n .Substring(0, result[result.Length - 1].Length - 1);\n\n json = \"{\\n\" + string.Join(\"\\n\", result) + \"\\n}\";\n"
},
{
"answer_id": 74608645,
"author": "AceGambit",
"author_id": 920319,
"author_profile": "https://Stackoverflow.com/users/920319",
"pm_score": 0,
"selected": false,
"text": "JObject.Parse(string) .Children() JToken Path"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74608196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9736540/"
] |
74,608,203
|
<p>In Google's Cloud Logging query language, is it possible to query for the existence of a particular key in the <code>jsonPayload</code> dict?</p>
<p>E.g., suppose I know the <code>jsonPayload</code> will either be</p>
<pre><code>{'keyA':'<some string>'}
</code></pre>
<p>or</p>
<pre><code>{'keyB':'<some string'}
</code></pre>
<p>But I don't know what the <code><some string></code> will be. I want all logs that have the <code>keyB</code> key. I suppose I could test that for that key having a regex that includes everything, but is that the best/only way?</p>
|
[
{
"answer_id": 74611238,
"author": "Rathish Kumar B",
"author_id": 2156784,
"author_profile": "https://Stackoverflow.com/users/2156784",
"pm_score": 1,
"selected": false,
"text": "jsonPayload.message =~\"Job status: *\" \n keyB jsonPayload.keyB =~\"regex-query\"\n"
},
{
"answer_id": 74661910,
"author": "Kirk Kelsey",
"author_id": 395927,
"author_profile": "https://Stackoverflow.com/users/395927",
"pm_score": 0,
"selected": false,
"text": "jsonPayload.keyB:*"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74608203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/96665/"
] |
74,608,264
|
<p>If I run this Go code:</p>
<pre class="lang-golang prettyprint-override"><code>package main
import (
"encoding/json"
"os"
)
func main() {
json.NewEncoder(os.Stdout).Encode("\xa1") // "\ufffd"
}
</code></pre>
<p>I lose data, since once the Unicode replacement is done, I can no longer get
back the original value. Compare with this Python code:</p>
<pre class="lang-py prettyprint-override"><code>import json
a = '\xa1'
b = json.dumps(a) # "\u00a1"
print(json.loads(b) == a) # True
</code></pre>
<p>no replacement is done, so no data is lost. In addition, the resultant JSON is
still valid. Does Go have some method to encode JSON string with escaping
instead of replacement?</p>
|
[
{
"answer_id": 74608394,
"author": "Dietrich Epp",
"author_id": 82294,
"author_profile": "https://Stackoverflow.com/users/82294",
"pm_score": 0,
"selected": false,
"text": "\"\\xa1\" 0xa1 \"\\u00a1\" \\xa1 \\xa1 0xa1"
},
{
"answer_id": 74608519,
"author": "wim",
"author_id": 674039,
"author_profile": "https://Stackoverflow.com/users/674039",
"pm_score": 1,
"selected": false,
"text": "'\\xa1' '\\u00a1' '\\U000000a1' chr(0xa1) '\\N{INVERTED EXCLAMATION MARK}' '¡' >>> print(json.dumps(b'\\xa1'.decode(errors='replace')))\n\"\\ufffd\"\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74608264",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,608,268
|
<p>I have to write a function which accepts an int array parameter and checks to see if it is a
permutation.</p>
<p>I tried this so far:</p>
<pre><code>bool permutationChecker(int arr[], int n){
for (int i = 0; i < n; i++){
//Check if the array is the size of n
if (i == n){
return true;
}
if (i == arr[n]){
return true;
}
}
return false;
}
</code></pre>
<p>but the output says some arrays are permutations even though they are not.</p>
|
[
{
"answer_id": 74608334,
"author": "lorro",
"author_id": 6292621,
"author_profile": "https://Stackoverflow.com/users/6292621",
"pm_score": 1,
"selected": false,
"text": "i == arr[n] i n i n n i std::find() i i bool isPermutation(int arr[], int n){\n int* arr2 = new int[n]; // consider using std::array<> / std::vector<> if allowed\n std::copy(arr, arr + n, arr2);\n std::sort(arr2, arr2 + n);\n for (int i = 0; i < n; i++){\n if (i != arr2[i]){\n delete[] arr2;\n return false;\n }\n }\n delete[] arr2;\n return true;\n}\n"
},
{
"answer_id": 74608589,
"author": "paddy",
"author_id": 1553090,
"author_profile": "https://Stackoverflow.com/users/1553090",
"pm_score": 0,
"selected": false,
"text": "int bool isPermutation(int arr[], int n)\n{\n // Ensure everything is within the valid range.\n for (int i = 0; i < n; i++)\n {\n if (arr[i] < 1 || arr[i] > n) return false;\n }\n\n // Check for uniqueness. For each value, use it to index back into the array and then\n // negate the value stored there. If already negative, the value is not unique.\n int count = 0;\n while (count < n)\n {\n int index = std::abs(arr[count]) - 1;\n if (arr[index] < 0)\n {\n break;\n }\n arr[index] = -arr[index];\n count++;\n }\n\n // Undo any negations done by the step above\n for (int i = 0; i < count; i++)\n {\n int index = std::abs(arr[i]) - 1;\n arr[index] = std::abs(arr[index]);\n }\n\n return count == n;\n}\n"
},
{
"answer_id": 74608777,
"author": "bitmask",
"author_id": 430766,
"author_profile": "https://Stackoverflow.com/users/430766",
"pm_score": 0,
"selected": false,
"text": ">=n (i == arr[i]) (i == arr[n]) (i == arr[n]) (i == n) i 0 n-1 == n int arr[3] = {0,1,2}; std::bitset template <std::size_t N>\nbool isPermutation(int const (&arr)[N]) {\n std::bitset<N> bits;\n for (int a: arr) {\n if (static_cast<std::size_t>(a) < N)\n bits.set(a);\n }\n return bits.all();\n}\n std::bitset"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74608268",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20189278/"
] |
74,608,287
|
<p>I am attempting to extract Schema and Table information from connection string data. The Schema and Table information is in the format "Schema.Table" (e.g FROM EDWP_D2PM.SN_INC_RPTG_SCRUBBED in string below) . Multiple Schema and Tables can exist in the connection strings, and they always follow the words FROM or JOIN (Including INNER JOIN, LEFT JOIN etc.).
I only want to extract Schema and Tables for Connections from a specific database, in the attached example this is DB2.</p>
<pre><code>"let
Source = DB2.Database(""69.69.69.69"", ""bcudb"", [HierarchicalNavigation=true, Implementation=""Microsoft"", Query=""SELECT i.ASSIGNMENT_GROUP, i.BUSINESS_SERVICE, i.CATEGORY, i.CAUSED_BY, i.CLOSE_CODE, i.CLOSED_ON, i.COMPANY, i.CONTACT_TYPE, i.DESCRIPTION, i.NUMBER, i.PARENT_INCIDENT, i.PRIORITY, i.RESOLVED_ON, i.SHORT_DESCRIPTION, i.CREATED_ON, i.CAUSE_CODE, i.CLOSED, i.CREATED, i.RESOLVED, i.RESOLUTION_MET, p.problem_id FROM EDWP_D2PM.SN_INC_RPTG_SCRUBBED i LEFT OUTER JOIN EDWP_D2PM.SN_INCIDENTS_CUST_RPTG p on p.number = i.number WHERE i.PRIORITY INLEFT OUTER JOIN EDWP_D2PM.SN_INCIDENTS_CUST_RPTG ('1 - Critical', '2 - High') AND TO_CHAR(i.created_on,'YYYY-MM') > (select to_char((CURRENT DATE - 12 MONTHS),'YYYY-MM') from SYSIBM.SYSDUMMY1) AND (i.CATEGORY <> 'Alert' OR (i.CATEGORY IS NULL)) AND i.PARENT_INCIDENT IS NULL AND i.EXCLUSIONS <> 'R' AND i.CLOSE_CODE <> 'Duplicate - No Action Taken' with ur""]), RIGHT JOIN EDWP.TEMP blaha blah
#""Changed Type"" = Table.TransformColumnTypes(Source,{{""RESOLVED_ON"", type datetime}})
in
#""Changed Type"""
</code></pre>
<p>I have a REGEX expression that is correctly returning the 4 Schemas.Tables in the sample text as expected (<a href="https://regex101.com/r/JkrucS/1" rel="nofollow noreferrer">link to regex 101 with working example</a> :</p>
<pre><code>(?:\s+JOIN\s+)(\w+\.\w+)|(?:\s+FROM\s+)(\w+\.\w+)
</code></pre>
<p>I want to improve the REGEX so that that I only get Schemas & Tables back for strings that begin with the text "DB2.Database" . How can I do this?</p>
<p>I have attempted adding in the prefix :</p>
<pre><code>(?:DB2.Database)(?:\s|\S)*
</code></pre>
<p>but that stops the 4 Schema.Tables from being returned.</p>
<p>Can anyone suggest a fix? If you do provide an answer, an explaination of the REGEX logic would be appreciated.</p>
<p>Once I have the REGEX working I will run it in Python using the re module.</p>
|
[
{
"answer_id": 74608334,
"author": "lorro",
"author_id": 6292621,
"author_profile": "https://Stackoverflow.com/users/6292621",
"pm_score": 1,
"selected": false,
"text": "i == arr[n] i n i n n i std::find() i i bool isPermutation(int arr[], int n){\n int* arr2 = new int[n]; // consider using std::array<> / std::vector<> if allowed\n std::copy(arr, arr + n, arr2);\n std::sort(arr2, arr2 + n);\n for (int i = 0; i < n; i++){\n if (i != arr2[i]){\n delete[] arr2;\n return false;\n }\n }\n delete[] arr2;\n return true;\n}\n"
},
{
"answer_id": 74608589,
"author": "paddy",
"author_id": 1553090,
"author_profile": "https://Stackoverflow.com/users/1553090",
"pm_score": 0,
"selected": false,
"text": "int bool isPermutation(int arr[], int n)\n{\n // Ensure everything is within the valid range.\n for (int i = 0; i < n; i++)\n {\n if (arr[i] < 1 || arr[i] > n) return false;\n }\n\n // Check for uniqueness. For each value, use it to index back into the array and then\n // negate the value stored there. If already negative, the value is not unique.\n int count = 0;\n while (count < n)\n {\n int index = std::abs(arr[count]) - 1;\n if (arr[index] < 0)\n {\n break;\n }\n arr[index] = -arr[index];\n count++;\n }\n\n // Undo any negations done by the step above\n for (int i = 0; i < count; i++)\n {\n int index = std::abs(arr[i]) - 1;\n arr[index] = std::abs(arr[index]);\n }\n\n return count == n;\n}\n"
},
{
"answer_id": 74608777,
"author": "bitmask",
"author_id": 430766,
"author_profile": "https://Stackoverflow.com/users/430766",
"pm_score": 0,
"selected": false,
"text": ">=n (i == arr[i]) (i == arr[n]) (i == arr[n]) (i == n) i 0 n-1 == n int arr[3] = {0,1,2}; std::bitset template <std::size_t N>\nbool isPermutation(int const (&arr)[N]) {\n std::bitset<N> bits;\n for (int a: arr) {\n if (static_cast<std::size_t>(a) < N)\n bits.set(a);\n }\n return bits.all();\n}\n std::bitset"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74608287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1890364/"
] |
74,608,305
|
<p>I need a way to select the text <strong>between</strong> two tags (the first <code>span</code> and the following <code>br</code>):</p>
<pre><code><div>
<span>abc</span>
defg
<br>
hijkl
<br>
mnop
<span>qrs</span>
tuvw
<br>
xyz
</div>
</code></pre>
<p>How can I select just "defg" with an xpath expression?</p>
<p>I tried using <code>following-sibling</code> to find the first <code>br</code> following the first <code>span</code> but I could not find a way to select the text between them.</p>
|
[
{
"answer_id": 74612371,
"author": "Prophet",
"author_id": 3485434,
"author_profile": "https://Stackoverflow.com/users/3485434",
"pm_score": 0,
"selected": false,
"text": "defg div mnop tuvw xyz defg div "
},
{
"answer_id": 74616724,
"author": "urcodebetterznow",
"author_id": 14403369,
"author_profile": "https://Stackoverflow.com/users/14403369",
"pm_score": 1,
"selected": false,
"text": "<div>\n<span>abc</span>\ndefg\n<br/>\nhijkl\n<br/>\nmnop\n<span>qrs</span>\ntuvw\n<br/>\nxyz\n</div>\n /div/span[1]/following-sibling::text() span defg hijkl mnop tuvw xyz normalize-space(/div/span[1]/following-sibling::text()) defg normalize-space() normalize-space((/div/span[1]/following-sibling::text())[1])"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74608305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19258695/"
] |
74,608,312
|
<p>I have a data source with a bunch of time stamps. I want to find the week start (sunday) date from these time stamps.</p>
<p>Eg, I want to go from "2022-11-23 00:00:00.0" --> "2022-11-20" for every date in the column called "Received Date"</p>
<pre><code>SELECT
CASE
WHEN sorttype = 'sortable' THEN 'Sort'
WHEN sorttype = 'SORTABLE' THEN 'Sort'
ELSE 'Non Sort'
END AS "Sort Type",
DATEADD(week, DATEDIFF(week, -1, (order_day + podays_received)), -1) AS "Week Start",
(order_day + podays_received) AS "Received Date",
pg_rollup AS "Product Family",
gl,
quantity_unpacked AS "Quantity Received"
FROM
sba.sba_req_po_received
WHERE
source = 'OPPORTUNITYBUYING'
AND country_code = 'US'
AND NOT buy_type_name = 'Offcycle'
LIMIT 100;
</code></pre>
|
[
{
"answer_id": 74608513,
"author": "John Rotenstein",
"author_id": 174777,
"author_profile": "https://Stackoverflow.com/users/174777",
"pm_score": 0,
"selected": false,
"text": "select (date_trunc('week', timestamp_field + interval '1 day') - interval '1 day')::date\n 2022-12-23 2022-11-24 2022-11-21 2022-11-20 2022-12-04 2022-12-05 2022-12-05 2022-12-04"
},
{
"answer_id": 74608556,
"author": "Learn Hadoop",
"author_id": 8726488,
"author_profile": "https://Stackoverflow.com/users/8726488",
"pm_score": -1,
"selected": false,
"text": "select now() - cast(extract('DoW' from now()) || ' day' as interval)"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74608312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20628591/"
] |
74,608,320
|
<p>I'm new into python and pandas and I'm having hard time transforming this 2d list into four independent columns, I'm getting two columns with more than one data for every record. May be I created it the wrong way? I don't know.</p>
<p>Please help me out, I'm trying to make results look like this:
<a href="https://i.stack.imgur.com/hPwZW.png" rel="nofollow noreferrer">These are the columns that I'm looking for</a></p>
<p>And
<a href="https://i.stack.imgur.com/d2JeH.png" rel="nofollow noreferrer">This is what I have done </a></p>
<p>THANK YOU VERY MUCH!!</p>
|
[
{
"answer_id": 74608513,
"author": "John Rotenstein",
"author_id": 174777,
"author_profile": "https://Stackoverflow.com/users/174777",
"pm_score": 0,
"selected": false,
"text": "select (date_trunc('week', timestamp_field + interval '1 day') - interval '1 day')::date\n 2022-12-23 2022-11-24 2022-11-21 2022-11-20 2022-12-04 2022-12-05 2022-12-05 2022-12-04"
},
{
"answer_id": 74608556,
"author": "Learn Hadoop",
"author_id": 8726488,
"author_profile": "https://Stackoverflow.com/users/8726488",
"pm_score": -1,
"selected": false,
"text": "select now() - cast(extract('DoW' from now()) || ' day' as interval)"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74608320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18979516/"
] |
74,608,330
|
<p>I'm trying to create buttons and vue element inputs for each item on the page. I'm iterating through the items and rendering them with <code>v-for</code> and so I decided to expand on that and do it for both the rest as well. The problem i'm having is that I need to to bind <code>textInput</code> as well as <code>displayTextbox</code> to each one and i'm not sure how to achieve that.</p>
<p>currently all the input text in the el-inputs are bound to the same variable, and clicking to display the inputs will display them all at once.</p>
<pre class="lang-html prettyprint-override"><code><template>
<div class="container">
<div v-for="(item, index) in items" :key="index">
<icon @click="showTextbox"/>
<el-input v-if="displayTextbox" v-model="textInput" />
<el-button v-if="displayTextbox" type="primary" @click="confirm" />
<ItemDisplay :data-id="item.id" />
</div>
</div>
</template>
<script>
import ItemDisplay from '@/components/ItemDisplay';
export default {
name: 'ItemList',
components: {
ItemDisplay,
},
props: {
items: {
type: Array,
required: true,
},
}
data() {
displayTextbox = false,
textInput = '',
},
methods: {
confirm() {
// todo send request here
this.displayTextbox = false;
},
showTextbox() {
this.displayTextbox = true;
}
}
}
</script>
</code></pre>
<p>EDIT: with the help of @kissu here's the updated and working version</p>
<pre class="lang-html prettyprint-override"><code><template>
<div class="container">
<div v-for="(item, index) in itemDataList" :key="itemDataList.id">
<icon @click="showTextbox(item.id)"/>
<El-Input v-if="item.displayTextbox" v-model="item.textInput" />
<El-Button v-if="item.displayTextbox" type="primary" @click="confirm(item.id)" />
<ItemDisplay :data-id="item.item.uuid" />
</div>
</div>
</template>
<script>
import ItemDisplay from '@/components/ItemDisplay';
export default {
name: 'ItemList',
components: {
ItemDisplay,
},
props: {
items: {
type: Array,
required: true,
},
}
data() {
itemDataList = [],
},
methods: {
confirm(id) {
const selected = this.itemDataList.find(
(item) => item.id === id,
)
selected.displayTextbox = false;
console.log(selected.textInput);
// todo send request here
},
showTextbox(id) {
this.itemDataList.find(
(item) => item.id === id,
).displayTextbox = true;
},
populateItemData() {
this.items.forEach((item, index) => {
this.itemDataList.push({
id: item.uuid + index,
displayTextbox: false,
textInput: '',
item: item,
});
});
}
},
created() {
// items prop is obtained from parent component vuex
// generate itemDataList before DOM is rendered so we can render it correctly
this.populateItemData();
},
}
</script>
</code></pre>
|
[
{
"answer_id": 74608513,
"author": "John Rotenstein",
"author_id": 174777,
"author_profile": "https://Stackoverflow.com/users/174777",
"pm_score": 0,
"selected": false,
"text": "select (date_trunc('week', timestamp_field + interval '1 day') - interval '1 day')::date\n 2022-12-23 2022-11-24 2022-11-21 2022-11-20 2022-12-04 2022-12-05 2022-12-05 2022-12-04"
},
{
"answer_id": 74608556,
"author": "Learn Hadoop",
"author_id": 8726488,
"author_profile": "https://Stackoverflow.com/users/8726488",
"pm_score": -1,
"selected": false,
"text": "select now() - cast(extract('DoW' from now()) || ' day' as interval)"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74608330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3307553/"
] |
74,608,337
|
<p>I would like to create a summary sheet that draws from arrays in two work sheets. I would like the summary sheet (Result) contains two filtered arrays, one below the other (see the attached <a href="https://i.stack.imgur.com/RqAty.png" rel="nofollow noreferrer">Desired Summary Page</a></p>
<p>This works well if the number of rows output by the array does not overlap with the formula for the second array. However, as the arrays are both dynamic the length changes depending on the filter criteria producing an Error (see attached)<a href="https://i.stack.imgur.com/v3mWM.png" rel="nofollow noreferrer">Overlapping Array Error</a></p>
<p>Is there any way to count the rows numbers produced by the first array and then get the second array to start after it is complete, so the two don't overlap - i.e. the output from the second array formula may need to be mapped to a remote cell (not containing the formula).</p>
<p>Here is an example spreadsheet
<a href="https://docs.google.com/spreadsheets/d/1Rt-Pp4gUYu8jGnXOQn0f2xpEKxoi_74Fqh5WSS-uF7A/edit?usp=sharing" rel="nofollow noreferrer">https://docs.google.com/spreadsheets/d/1Rt-Pp4gUYu8jGnXOQn0f2xpEKxoi_74Fqh5WSS-uF7A/edit?usp=sharing</a></p>
<p>I have tried adding blank rows to the second Array by using Flatten however this overwrites the results of the first Array. I have also tried a query function, but my knowledge of the syntax is not sufficient.</p>
<p>Any suggestions would be welcome.</p>
|
[
{
"answer_id": 74608513,
"author": "John Rotenstein",
"author_id": 174777,
"author_profile": "https://Stackoverflow.com/users/174777",
"pm_score": 0,
"selected": false,
"text": "select (date_trunc('week', timestamp_field + interval '1 day') - interval '1 day')::date\n 2022-12-23 2022-11-24 2022-11-21 2022-11-20 2022-12-04 2022-12-05 2022-12-05 2022-12-04"
},
{
"answer_id": 74608556,
"author": "Learn Hadoop",
"author_id": 8726488,
"author_profile": "https://Stackoverflow.com/users/8726488",
"pm_score": -1,
"selected": false,
"text": "select now() - cast(extract('DoW' from now()) || ' day' as interval)"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74608337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20628422/"
] |
74,608,341
|
<p>I am trying to print out only the last position # of a number from a file called numbers.text.
numbers.text:</p>
<pre><code>10
23
43
5
12
23
9
8
10
1
16
9
</code></pre>
<p>Basically, I am attempting to print out a statement along the lines of (using 10 as an example) "10 appeared last at position 9."</p>
<pre><code>import java.io.File;
import java.util.*;
public class SortOf3 {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
Scanner datafile = new Scanner(new File("numbers.text"));
boolean duplicate = true;
int count = 0;
int duplicate = 0
while (datafile.hasNextInt()) {
if (duplicate) {
System.out.print("Enter a number: ");
lastNumber = scanner.nextInt();
count++;
duplicate = false;
} else {
System.out.print("Enter a number: ");
lastNumber = scanner.nextInt();
count++;
}
if (lastNumber == datafile.nextInt())
System.out.println(lastNumber + " last appears in the file at position " + count);
else
System.out.println(lastNumber + " does not appear in the file");
}
}
}
</code></pre>
<p>I tried using boolean duplicate in hopes of ignoring the counter the first time lastNumber appears, however it did not seem to do anything. If there's no way to make boolean work here, what's another way to print out the last position of a number in a file?</p>
|
[
{
"answer_id": 74608513,
"author": "John Rotenstein",
"author_id": 174777,
"author_profile": "https://Stackoverflow.com/users/174777",
"pm_score": 0,
"selected": false,
"text": "select (date_trunc('week', timestamp_field + interval '1 day') - interval '1 day')::date\n 2022-12-23 2022-11-24 2022-11-21 2022-11-20 2022-12-04 2022-12-05 2022-12-05 2022-12-04"
},
{
"answer_id": 74608556,
"author": "Learn Hadoop",
"author_id": 8726488,
"author_profile": "https://Stackoverflow.com/users/8726488",
"pm_score": -1,
"selected": false,
"text": "select now() - cast(extract('DoW' from now()) || ' day' as interval)"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74608341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19927038/"
] |
74,608,404
|
<p>I want to convert timestamp to date format which is 'dd/MM/YYYY' but I end up with date format in the picture. I also use syncfusion spreadsheet.</p>
<p><a href="https://i.stack.imgur.com/BoRaa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BoRaa.png" alt="Timestamp" /></a></p>
<p>export-electronic.component.ts</p>
<pre><code>updatedata(){
this.dataApi.getElectronicById(this.id).subscribe(res => {
this.electronicObj = res;
console.log(this.electronicObj);
this.spreadsheetObj.updateCell({ value:
this.electronicObj.mantainence_history},"O3");
this.spreadsheetObj.updateCell({ value:
this.electronicObj.cost_status},"P3");
this.spreadsheetObj.updateCell({ value: this.electronicObj.warranty_date.toDate()+this.electronicObj.expire_date.toDate()},"Q3");}
</code></pre>
<p>export-electronic.component.html</p>
<pre><code><ejs-spreadsheet #spreadsheet (created)="created()" (openComplete)="updatedata()" openUrl='https://ej2services.syncfusion.com/production/web-services/api/spreadsheet/open' allowOpen='true' (beforeSave)='beforeSave($event)' saveUrl='https://ej2services.syncfusion.com/production/web-services/api/spreadsheet/save' allowSave='true'>
</ejs-spreadsheet>
</code></pre>
<p>In the excel cell. I want the answer around like this. Example 29/11/2022 - 01/12/2022
Thank you for the advice</p>
<p>**** The Answer *****</p>
<pre><code>updatedata(){
this.dataApi.getElectronicById(this.id).subscribe(res => {
this.electronicObj = res;
console.log(this.electronicObj);
const q3Value = (new Date(this.electronicObj.warranty_date.toDate()).toLocaleDateString('en-GB')) + ' - ' + (new Date(this.electronicObj.expire_date.toDate()).toLocaleDateString('en-GB'));
this.spreadsheetObj.updateCell({ value:
this.electronicObj.mantainence_history},"O3");
this.spreadsheetObj.updateCell({ value:
this.electronicObj.cost_status},"P3");
this.spreadsheetObj.updateCell({ value: q3Value},"Q3");
});
}
</code></pre>
<p><a href="https://i.stack.imgur.com/jEAgw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jEAgw.png" alt="Answer" /></a></p>
|
[
{
"answer_id": 74608513,
"author": "John Rotenstein",
"author_id": 174777,
"author_profile": "https://Stackoverflow.com/users/174777",
"pm_score": 0,
"selected": false,
"text": "select (date_trunc('week', timestamp_field + interval '1 day') - interval '1 day')::date\n 2022-12-23 2022-11-24 2022-11-21 2022-11-20 2022-12-04 2022-12-05 2022-12-05 2022-12-04"
},
{
"answer_id": 74608556,
"author": "Learn Hadoop",
"author_id": 8726488,
"author_profile": "https://Stackoverflow.com/users/8726488",
"pm_score": -1,
"selected": false,
"text": "select now() - cast(extract('DoW' from now()) || ' day' as interval)"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74608404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16228338/"
] |
74,608,412
|
<p>App is a simple memory/guessing game with a grid of squares. Floating action button triggers a "New game" dialog, and a Yes response triggers setState() on the main widget. The print() calls show it is building all the Tile widgets in the grid, but as it returns, the old grid values are still showing. Probably done something stupid but not seeing it. Basic code is below. TIA if anyone can see what is missing/invalid/broken/etc.</p>
<p>Main.dart is the usual main() that creates a stateless HomePage which creates a stateful widget which uses this State:</p>
<pre><code>class MemHomePageState extends State<MemHomePage> {
GameBoard gameBoard = GameBoard();
GameController? gameController;
int gameCount = 0, winCount = 0;
@override
void initState() {
super.initState();
gameController = GameController(gameBoard, this);
}
@override
Widget build(BuildContext context) {
if (kDebugMode) {
print("MemHomepageState::build");
}
gameBoard.newGame(); // Resets secrets and grids
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: GridView.count(
crossAxisCount: Globals.num_columns,
children: List.generate(Globals.num_columns * Globals.num_rows, (index) {
int x = index~/Globals.NR, y = index%Globals.NR;
int secret = gameBoard.secretsGrid![x][y];
var t = Tile(x, y, Text('$secret'), gameController!);
gameBoard.tilesGrid![x].add(t);
if (kDebugMode) {
print("Row $x is ${gameBoard.secretsGrid![x]} ${gameBoard.tilesGrid![x][y].secret}");
}
return t;
}),
),
// Text("You have played $gameCount games and won $winCount."),
),
floatingActionButton: FloatingActionButton(
onPressed: () => newGameDialog("Start a new game?"),
tooltip: 'New game?',
child: const Icon(Icons.refresh_outlined),
),
);
}
/** Called from the FAB and also from GameController "won" logic */
void newGameDialog(String message) {
showDialog<void>(
context: context,
barrierDismissible: false, // means the user must tap a button to exit the Alert Dialog
builder: (BuildContext context) {
return AlertDialog(
title: Text("New game?"),
content: Text(message),
//),
actions: <Widget>[
TextButton(
child: const Text('Yes'),
onPressed: () {
setState(() {
gameCount++;
});
Navigator.of(context).pop();
},
),
TextButton(
child: const Text('No'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
}
);
}
</code></pre>
<p>The Tile class is a StatefulWidget whose state determines what that particular tile should show:</p>
<pre class="lang-dart prettyprint-override"><code>import 'package:flutter/material.dart';
import 'gamecontroller.dart';
enum TileMode {
SHOWN,
HIDDEN,
CLEARED,
}
/// Represents one Tile in the game
class Tile extends StatefulWidget {
final int x, y;
final Widget secret;
final GameController gameController;
TileState? tileState;
Tile(this.x, this.y, this.secret, this.gameController, {super.key});
@override
State<Tile> createState() => TileState(x, y, secret);
setCleared() {
tileState!.setCleared();
}
}
class TileState extends State<Tile> {
final int x, y;
final Widget secret;
TileMode tileMode = TileMode.HIDDEN;
TileState(this.x, this.y, this.secret);
_unHide() {
setState(() => tileMode = TileMode.SHOWN);
widget.gameController.clicked(widget);
}
reHide() {
print("rehiding");
setState(() => tileMode = TileMode.HIDDEN);
}
setCleared() {
print("Clearing");
setState(() => tileMode = TileMode.CLEARED);
}
_doNothing() {
//
}
@override
Widget build(BuildContext context) {
switch(tileMode) {
case TileMode.HIDDEN:
return ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.teal,
),
onPressed: _unHide,
child: Text(''));
case TileMode.SHOWN:
return ElevatedButton(
onPressed: _doNothing,
style: ElevatedButton.styleFrom(
backgroundColor: Colors.green,
),
child: secret);
case TileMode.CLEARED:
return ElevatedButton(
onPressed: _doNothing,
style: ElevatedButton.styleFrom(
backgroundColor: Colors.black12,
),
child: const Icon(Icons.check));
}
}
}
</code></pre>
|
[
{
"answer_id": 74608513,
"author": "John Rotenstein",
"author_id": 174777,
"author_profile": "https://Stackoverflow.com/users/174777",
"pm_score": 0,
"selected": false,
"text": "select (date_trunc('week', timestamp_field + interval '1 day') - interval '1 day')::date\n 2022-12-23 2022-11-24 2022-11-21 2022-11-20 2022-12-04 2022-12-05 2022-12-05 2022-12-04"
},
{
"answer_id": 74608556,
"author": "Learn Hadoop",
"author_id": 8726488,
"author_profile": "https://Stackoverflow.com/users/8726488",
"pm_score": -1,
"selected": false,
"text": "select now() - cast(extract('DoW' from now()) || ' day' as interval)"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74608412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/176859/"
] |
74,608,433
|
<p>Working on an angular project and I created an interface file where I do two things:</p>
<p>Define an interface:</p>
<pre><code>export interface tableHeader {
roundNumber: string;
eighteenHoleScore: string;
nineHoleScore: string;
courseRating: string;
slopeRating: string;
scoreDifferential: string;
}
</code></pre>
<p>Create a variable to hold an array of strings:</p>
<pre><code>export const roundHeader = [
roundNumber: 'Round Number',
eighteenHoleScore: '18 Hole Score',
nineHoleScore: '9 Hole Score',
courseRating: 'Course Rating',
slopeRating: 'Slope Rating',
scoreDifferential: 'Score Differential'
]
</code></pre>
<p>I am getting the above 2304 error for each of my variables created in the <code>roundHeader</code> const. I looked through the site and didn't see anything to answer this and I found on google a lot of things relating to 'require' but in this circumstance it has nothing to do with require.</p>
<p>I am just trying to create an interface to define each variable type, then create static text in the same file so that I can export this static text to multiple pages of my app.</p>
<p>Any help is much appreciated</p>
|
[
{
"answer_id": 74608503,
"author": "Jastria Rahmat",
"author_id": 6274120,
"author_profile": "https://Stackoverflow.com/users/6274120",
"pm_score": 2,
"selected": false,
"text": "roundHeader interface tableHeader {\n roundNumber: string;\n eighteenHoleScore: string;\n nineHoleScore: string;\n courseRating: string;\n slopeRating: string;\n scoreDifferential: string;\n}\n\nconst roundHeader: tableHeader[] = [\n {\n roundNumber: \"Round Number\",\n eighteenHoleScore: \"18 Hole Score\",\n nineHoleScore: \"9 Hole Score\",\n courseRating: \"Course Rating\",\n slopeRating: \"Slope Rating\",\n scoreDifferential: \"Score Differential\",\n },\n];\n enum enum TableHeader{\n roundNumber= \"Round Number\",\n eighteenHoleScore= \"18 Hole Score\",\n nineHoleScore= \"9 Hole Score\",\n courseRating= \"Course Rating\",\n slopeRating= \"Slope Rating\",\n scoreDifferential= \"Score Differential\",\n }\n\n const somewhereNeedsRoundNumber = TableHeader.roundNumber\n"
},
{
"answer_id": 74608586,
"author": "João Casarin",
"author_id": 14318729,
"author_profile": "https://Stackoverflow.com/users/14318729",
"pm_score": 0,
"selected": false,
"text": "export const roundHeader: tableHeader roundHeader export const roundHeader: TableHeader = {\n roundNumber: 'Round Number',\n eighteenHoleScore: '18 Hole Score',\n nineHoleScore: '9 Hole Score',\n courseRating: 'Course Rating',\n slopeRating: 'Slope Rating',\n scoreDifferential: 'Score Differential'\n};\n export const roundHeader: TableHeader[] = [\n {\n roundNumber: \"Round Number\",\n eighteenHoleScore: \"18 Hole Score\",\n nineHoleScore: \"9 Hole Score\",\n courseRating: \"Course Rating\",\n slopeRating: \"Slope Rating\",\n scoreDifferential: \"Score Differential\",\n },\n // ...\n // other objects with the same fields\n]\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74608433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14852773/"
] |
74,608,557
|
<pre class="lang-c prettyprint-override"><code>void main() {
unsigned int a = 0;
if (a - 10 < 0) {
printf("error!\n");
}
}
</code></pre>
<p>we know this comparison won't work, because a-10 will be a big unsigned integer, it can't be smaller than 0.</p>
<p>To avoid this situation, I try this:</p>
<pre class="lang-c prettyprint-override"><code>void main() {
unsigned int a = 0;
int b = 0;// or const int b = 0;
if (a - 10 < b) {
printf("error!\n");
}
}
</code></pre>
<p>this will get <code>warning C4018</code> using Visual Studio 2022 17.2.4.</p>
<p>However, when I use gcc 4.8.5, there is no warning at all.</p>
<p>Is there a way to avoid coder compare signed number with unsigned variable?</p>
<p>Update:
a more complex situation could be this:</p>
<pre class="lang-c prettyprint-override"><code>struct s{
unsigned int len;
char *buffer;
} *a;
int not_safe(struct s *ptr){
if(ptr->len - sizeof(struct s) < 0){
return 0;
}
return 1;
}
</code></pre>
<p>Programmers may not be aware of such comparisons are wrong. I
hope we can have a safe way to let programmer avoid this.</p>
|
[
{
"answer_id": 74608503,
"author": "Jastria Rahmat",
"author_id": 6274120,
"author_profile": "https://Stackoverflow.com/users/6274120",
"pm_score": 2,
"selected": false,
"text": "roundHeader interface tableHeader {\n roundNumber: string;\n eighteenHoleScore: string;\n nineHoleScore: string;\n courseRating: string;\n slopeRating: string;\n scoreDifferential: string;\n}\n\nconst roundHeader: tableHeader[] = [\n {\n roundNumber: \"Round Number\",\n eighteenHoleScore: \"18 Hole Score\",\n nineHoleScore: \"9 Hole Score\",\n courseRating: \"Course Rating\",\n slopeRating: \"Slope Rating\",\n scoreDifferential: \"Score Differential\",\n },\n];\n enum enum TableHeader{\n roundNumber= \"Round Number\",\n eighteenHoleScore= \"18 Hole Score\",\n nineHoleScore= \"9 Hole Score\",\n courseRating= \"Course Rating\",\n slopeRating= \"Slope Rating\",\n scoreDifferential= \"Score Differential\",\n }\n\n const somewhereNeedsRoundNumber = TableHeader.roundNumber\n"
},
{
"answer_id": 74608586,
"author": "João Casarin",
"author_id": 14318729,
"author_profile": "https://Stackoverflow.com/users/14318729",
"pm_score": 0,
"selected": false,
"text": "export const roundHeader: tableHeader roundHeader export const roundHeader: TableHeader = {\n roundNumber: 'Round Number',\n eighteenHoleScore: '18 Hole Score',\n nineHoleScore: '9 Hole Score',\n courseRating: 'Course Rating',\n slopeRating: 'Slope Rating',\n scoreDifferential: 'Score Differential'\n};\n export const roundHeader: TableHeader[] = [\n {\n roundNumber: \"Round Number\",\n eighteenHoleScore: \"18 Hole Score\",\n nineHoleScore: \"9 Hole Score\",\n courseRating: \"Course Rating\",\n slopeRating: \"Slope Rating\",\n scoreDifferential: \"Score Differential\",\n },\n // ...\n // other objects with the same fields\n]\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74608557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6119813/"
] |
74,608,718
|
<p>I receive the error message
"ImportError: cannot import name 'TFTModel' from 'darts.models'" when trying to import the atribute "TFTmodel" from darts using the line</p>
<pre><code>from darts.models import TFTModel
</code></pre>
<p>I have tried using "pip install statsforecast==0.6.0" however that leads to me not being able to use darts since the current darts version isn't compatible with that statsforecast version, and when i try to downgrade the darts version i get a error with pandas that just leads me to upgrade my darts version which puts me in a loop</p>
<p>The versions im using are
darts 0.22.0</p>
<p>startsforecast 1.3.2</p>
<p>Windows 10 x64 version 21H2</p>
<p>python 3.9.13</p>
|
[
{
"answer_id": 74608503,
"author": "Jastria Rahmat",
"author_id": 6274120,
"author_profile": "https://Stackoverflow.com/users/6274120",
"pm_score": 2,
"selected": false,
"text": "roundHeader interface tableHeader {\n roundNumber: string;\n eighteenHoleScore: string;\n nineHoleScore: string;\n courseRating: string;\n slopeRating: string;\n scoreDifferential: string;\n}\n\nconst roundHeader: tableHeader[] = [\n {\n roundNumber: \"Round Number\",\n eighteenHoleScore: \"18 Hole Score\",\n nineHoleScore: \"9 Hole Score\",\n courseRating: \"Course Rating\",\n slopeRating: \"Slope Rating\",\n scoreDifferential: \"Score Differential\",\n },\n];\n enum enum TableHeader{\n roundNumber= \"Round Number\",\n eighteenHoleScore= \"18 Hole Score\",\n nineHoleScore= \"9 Hole Score\",\n courseRating= \"Course Rating\",\n slopeRating= \"Slope Rating\",\n scoreDifferential= \"Score Differential\",\n }\n\n const somewhereNeedsRoundNumber = TableHeader.roundNumber\n"
},
{
"answer_id": 74608586,
"author": "João Casarin",
"author_id": 14318729,
"author_profile": "https://Stackoverflow.com/users/14318729",
"pm_score": 0,
"selected": false,
"text": "export const roundHeader: tableHeader roundHeader export const roundHeader: TableHeader = {\n roundNumber: 'Round Number',\n eighteenHoleScore: '18 Hole Score',\n nineHoleScore: '9 Hole Score',\n courseRating: 'Course Rating',\n slopeRating: 'Slope Rating',\n scoreDifferential: 'Score Differential'\n};\n export const roundHeader: TableHeader[] = [\n {\n roundNumber: \"Round Number\",\n eighteenHoleScore: \"18 Hole Score\",\n nineHoleScore: \"9 Hole Score\",\n courseRating: \"Course Rating\",\n slopeRating: \"Slope Rating\",\n scoreDifferential: \"Score Differential\",\n },\n // ...\n // other objects with the same fields\n]\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74608718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14955502/"
] |
74,608,745
|
<p>How can I return the last not null, not empty, and not nan from a list?
if not exists, then return "null" or a customized message!</p>
<p>I have tried these pieces of codes and none of them is bullet proof:</p>
<pre><code>import numpy as np
listF=[0.0,np. NaN,2,0,0.0,""]
print([j for j in listF if j][-1])#returns 2 while should retrun 0
listF=[0.0,np. NaN,np. NaN,0,0.0,np. NaN]
print([j for j in listF if j][-1])#returns nan while should return 0
listF=[]
print([j for j in listF if j][-1])#returns Index out of range
listF=[1,np. NaN,np. NaN,0,0.0,np. NaN]
print([j for j in listF if j][-1])#returns nan while should return 0
listF=[np. NaN,np. NaN,np. NaN]
print([j for j in listF if j][-1])#returns nan while should return "null"
</code></pre>
|
[
{
"answer_id": 74608788,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 3,
"selected": true,
"text": "math.isnan numpy.isnan next from math import isnan\n\ndef last_valid(lst):\n return next((x for x in reversed(lst) if x and not isnan(x)), None) # or 'null'\n\nlast_valid([])\n# None\n\nlast_valid([0.0,np. NaN,2,0,0.0,\"\"])\n# 2\n\nlast_valid([1,np. NaN,np. NaN,0,0.0,np. NaN])\n# 1\n\nlast_valid([0.0,np. NaN,np. NaN,0,0.0,np. NaN])\n# None\n 0 0 from math import isnan\ndef last_valid(lst):\n return next((x for x in reversed(lst) if str(x) and not isnan(x)), '\"null\"')\n\nlast_valid([]))\n# '\"null\"'\n\nlast_valid([0.0,np. NaN,2,0,0.0,\"\"])\n# 0.0\n\nlast_valid([1,np. NaN,np. NaN,0,0.0,np. NaN])\n# 0.0\n\nlast_valid([0.0,np. NaN,np. NaN,0,0.0,np. NaN])\n# 0.0\n\nlast_valid([np. NaN,np. NaN,np. NaN])\n# '\"null\"'\n"
},
{
"answer_id": 74608797,
"author": "Ricardo",
"author_id": 16353662,
"author_profile": "https://Stackoverflow.com/users/16353662",
"pm_score": 1,
"selected": false,
"text": "import numpy as np\nimport pandas as pd\n\nlistF=[0.0,np. NaN,2,0,0.0,\"\"]\n\noutput = 'empty list'\nfor tmp in listF[::-1]:\n if not tmp or pd.isna(tmp):\n continue\n else:\n output = tmp\n break\noutput\n"
},
{
"answer_id": 74608828,
"author": "Indiano",
"author_id": 13309379,
"author_profile": "https://Stackoverflow.com/users/13309379",
"pm_score": 0,
"selected": false,
"text": "print([i for i in list if i and not i!=i][-1])\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74608745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19489763/"
] |
74,608,746
|
<p>I am building a calculator App on WPF and I would like to bind the NumPad Keys to their respective buttons since up until now the only way of using the App is by clicking with the mouse on every button and it is not ideal.</p>
<p>This is the first time working with WPF so I've been searching for an answer but couldn't find anything useful.</p>
<p>I did try adding this to my code but it does nothing when I press "A". It also doesn't work if I add a modifier like "Shift".</p>
<pre><code><Window ...>
<Window.InputBindings>
<KeyBinding Key="A" Command="{Binding Button_Click}"/>
</Window.InputBindings>
...
</Window>
</code></pre>
|
[
{
"answer_id": 74608788,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 3,
"selected": true,
"text": "math.isnan numpy.isnan next from math import isnan\n\ndef last_valid(lst):\n return next((x for x in reversed(lst) if x and not isnan(x)), None) # or 'null'\n\nlast_valid([])\n# None\n\nlast_valid([0.0,np. NaN,2,0,0.0,\"\"])\n# 2\n\nlast_valid([1,np. NaN,np. NaN,0,0.0,np. NaN])\n# 1\n\nlast_valid([0.0,np. NaN,np. NaN,0,0.0,np. NaN])\n# None\n 0 0 from math import isnan\ndef last_valid(lst):\n return next((x for x in reversed(lst) if str(x) and not isnan(x)), '\"null\"')\n\nlast_valid([]))\n# '\"null\"'\n\nlast_valid([0.0,np. NaN,2,0,0.0,\"\"])\n# 0.0\n\nlast_valid([1,np. NaN,np. NaN,0,0.0,np. NaN])\n# 0.0\n\nlast_valid([0.0,np. NaN,np. NaN,0,0.0,np. NaN])\n# 0.0\n\nlast_valid([np. NaN,np. NaN,np. NaN])\n# '\"null\"'\n"
},
{
"answer_id": 74608797,
"author": "Ricardo",
"author_id": 16353662,
"author_profile": "https://Stackoverflow.com/users/16353662",
"pm_score": 1,
"selected": false,
"text": "import numpy as np\nimport pandas as pd\n\nlistF=[0.0,np. NaN,2,0,0.0,\"\"]\n\noutput = 'empty list'\nfor tmp in listF[::-1]:\n if not tmp or pd.isna(tmp):\n continue\n else:\n output = tmp\n break\noutput\n"
},
{
"answer_id": 74608828,
"author": "Indiano",
"author_id": 13309379,
"author_profile": "https://Stackoverflow.com/users/13309379",
"pm_score": 0,
"selected": false,
"text": "print([i for i in list if i and not i!=i][-1])\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74608746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20414179/"
] |
74,608,748
|
<p>I am working on the plugin and getting issues in <code>add_meta_box</code>.</p>
<pre><code>// Page URL-
http://localhost:8080/wordpress/wp-admin/admin.php?page=testingpages&action=edit
//Plugin page code
if ($_GET['action'] == 'edit') {
include('admin/views/view-edit.php');
}
</code></pre>
<p>The below is code, I am using on the <code>view-edit.php</code> page</p>
<pre><code>function adding_custom_meta_boxes($post)
{
add_meta_box(
'testingpages',
__('My Meta Box'),
'render_my_meta_box',
'page',
'normal',
'default'
);
}
add_action('add_meta_boxes', 'adding_custom_meta_boxes');
function render_my_meta_box()
{
// code here
}
</code></pre>
<p>i am getting blank screen. Any idea where is the issue/</p>
<p><strong>Edited.</strong></p>
<p>from <code>add_action('add_meta_boxes_post', 'adding_custom_meta_boxes');</code></p>
<p>to <code>add_action('add_meta_boxes', 'adding_custom_meta_boxes');</code></p>
|
[
{
"answer_id": 74608788,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 3,
"selected": true,
"text": "math.isnan numpy.isnan next from math import isnan\n\ndef last_valid(lst):\n return next((x for x in reversed(lst) if x and not isnan(x)), None) # or 'null'\n\nlast_valid([])\n# None\n\nlast_valid([0.0,np. NaN,2,0,0.0,\"\"])\n# 2\n\nlast_valid([1,np. NaN,np. NaN,0,0.0,np. NaN])\n# 1\n\nlast_valid([0.0,np. NaN,np. NaN,0,0.0,np. NaN])\n# None\n 0 0 from math import isnan\ndef last_valid(lst):\n return next((x for x in reversed(lst) if str(x) and not isnan(x)), '\"null\"')\n\nlast_valid([]))\n# '\"null\"'\n\nlast_valid([0.0,np. NaN,2,0,0.0,\"\"])\n# 0.0\n\nlast_valid([1,np. NaN,np. NaN,0,0.0,np. NaN])\n# 0.0\n\nlast_valid([0.0,np. NaN,np. NaN,0,0.0,np. NaN])\n# 0.0\n\nlast_valid([np. NaN,np. NaN,np. NaN])\n# '\"null\"'\n"
},
{
"answer_id": 74608797,
"author": "Ricardo",
"author_id": 16353662,
"author_profile": "https://Stackoverflow.com/users/16353662",
"pm_score": 1,
"selected": false,
"text": "import numpy as np\nimport pandas as pd\n\nlistF=[0.0,np. NaN,2,0,0.0,\"\"]\n\noutput = 'empty list'\nfor tmp in listF[::-1]:\n if not tmp or pd.isna(tmp):\n continue\n else:\n output = tmp\n break\noutput\n"
},
{
"answer_id": 74608828,
"author": "Indiano",
"author_id": 13309379,
"author_profile": "https://Stackoverflow.com/users/13309379",
"pm_score": 0,
"selected": false,
"text": "print([i for i in list if i and not i!=i][-1])\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74608748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9437856/"
] |
74,608,754
|
<p>I'm using UIColorPickerViewController. When I use <strong>Sliders</strong> section, default value is display p3 like below an image.</p>
<p><a href="https://i.stack.imgur.com/dcEIo.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dcEIo.jpg" alt="enter image description here" /></a></p>
<p>My app is using <strong>UIExtendedSRGBColorSpace</strong>. So I need to convert to UIExtendedSRGBColorSpace. When I convert from Display P3 to eSRGB, it returns <code>UIExtendedSRGBColorSpace -0.511642 1.01827 -0.310624 1</code>.</p>
<p>convert code is here.</p>
<pre><code>extension CGColorSpace {
static let extendedSRGB = CGColorSpace(name: CGColorSpace.extendedSRGB)! }
func updateFromP3ToExtendedsRGB() -> UIColor?
{
guard self.cgColor.colorSpace?.name == CGColorSpace.displayP3 else { return nil }
let convertColor = self.cgColor.converted(to: .extendedSRGB, intent: .relativeColorimetric, options: nil)
if let convertCGColor = convertColor
{
return UIColor(cgColor: convertCGColor)
}
return nil
}
</code></pre>
<p>I got negative value. Here is the problem.</p>
<p>I need to save color with hex code. When I changed to hex code of converted color, it turns different color like yellow color <code>ffffffb1</code>.</p>
<p><a href="https://i.stack.imgur.com/07QQg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/07QQg.png" alt="enter image description here" /></a></p>
<p>here is code to converting hex code.</p>
<pre><code>func toHexString() -> String {
var r:CGFloat = 0
var g:CGFloat = 0
var b:CGFloat = 0
var a:CGFloat = 0
getRed(&r, green: &g, blue: &b, alpha: &a)
let argb:Int = (Int)(a*255)<<24 | (Int)(r*255)<<16 | (Int)(g*255)<<8 | (Int)(b*255)<<0
return NSString(format:"%06x", argb) as String
}
</code></pre>
<p>So, my question is how to convert from display p3 to eSRGB by hex string?</p>
<p><a href="https://i.stack.imgur.com/QB3Dv.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QB3Dv.jpg" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74608979,
"author": "HangarRash",
"author_id": 20287183,
"author_profile": "https://Stackoverflow.com/users/20287183",
"pm_score": 0,
"selected": false,
"text": "CGColor converted CGColorSpace .extendedSRGB CGColorSpace.extendedSRGB CFString CGColorSpace extension UIColor {\n func updateFromP3ToExtendedsRGB() -> UIColor? {\n guard self.cgColor.colorSpace?.name == CGColorSpace.displayP3 else { return nil }\n guard let eSRGBSpace = CGColorSpace(name: CGColorSpace.extendedSRGB) else { return nil }\n let convertColor = self.cgColor.converted(to: eSRGBSpace, intent: .relativeColorimetric, options: nil)\n if let convertCGColor = convertColor {\n return UIColor(cgColor: convertCGColor)\n }\n\n return nil\n }\n}\n getRed:green:blue:alpha:"
},
{
"answer_id": 74609068,
"author": "Zoro4rk",
"author_id": 19100950,
"author_profile": "https://Stackoverflow.com/users/19100950",
"pm_score": 2,
"selected": true,
"text": "\nextension CGColor {\n func toHex() -> String? {\n guard let components = components else { return nil }\n \n if components.count == 2 {\n let value = components[0]\n let alpha = components[1]\n return String(format: \"#%02lX%02lX%02lX%02lX\", lroundf(Float(alpha*255)), lroundf(Float(value*255)), lroundf(Float(value*255)), lroundf(Float(value*255)))\n }\n \n guard components.count == 4 else { return nil }\n \n let red = components[0]\n let green = components[1]\n let blue = components[2]\n let alpa = components[3]\n \n let hexString = String(format: \"#%02lX%02lX%02lX%02lX\",lroundf(Float(alpa*255)), lroundf(Float(red*255)), lroundf(Float(green*255)), lroundf(Float(blue*255)))\n \n return hexString\n }\n}\n\n\nextension UIColor {\n func toHexString() -> String {\n cgColor.toHex() ?? \"\"\n }\n \n func toDisplayP3HexString() -> String {\n guard let displayP3Color = self.cgColor.converted(to: CGColorSpace(name: CGColorSpace.displayP3)!, intent: .defaultIntent, options: nil) else {\n return \"\"\n }\n return displayP3Color.toHex() ?? \"\"\n }\n}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74608754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5639379/"
] |
74,608,779
|
<pre><code>
$suppliers = Supplier::with(
[
'purcheses' => function ($query) {
$query->with(
[
'payments' => function ($query) {
$query->sum('amount');
}
]
)->get();
}
]
)->latest()->get();
</code></pre>
<p>I have a <strong>suppliers</strong> table with has-many <strong>relations with purchases of purchases table</strong> with has-many <strong>relations with payments and payment belongs to purchases,</strong> how to get the total sum of payment for each purchase that belongs to this supplier?</p>
|
[
{
"answer_id": 74610070,
"author": "Malik",
"author_id": 10804565,
"author_profile": "https://Stackoverflow.com/users/10804565",
"pm_score": 2,
"selected": false,
"text": "/*\n Country\n -> has many\n User\n -> has many\n Post\n -> has many\n Comment\n*/\n \nclass Country extends Model\n{\n use \\Staudenmeir\\EloquentHasManyDeep\\HasRelationships;\n \n public function comments()\n {\n return $this->hasManyDeep('App\\Comment', ['App\\User', 'App\\Post']);\n }\n}\n \n// Access country comments\n$country->comments();\n"
},
{
"answer_id": 74610597,
"author": "Kevin Bui",
"author_id": 2994920,
"author_profile": "https://Stackoverflow.com/users/2994920",
"pm_score": 0,
"selected": false,
"text": "$suppliers = Supplier::with('purchases')\n ->get();\n\n// Load the payments total for each purchase.\n$suppliers\n ->flatMap\n ->purchases\n ->loadSum('payments', 'amount');\n\nreturn $suppliers;\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74608779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16780147/"
] |
74,608,784
|
<p>I want to define an NxN matrix A, whose element <code>A(i,j)</code> is <code>sin(i^2 + j)</code>.</p>
<p>In MATLAB, I can quickly define this matrix by employing vectorization.</p>
<pre class="lang-matlab prettyprint-override"><code>N = 2000;
ii = 1:N;
A = sin(ii.^2 + ii');
</code></pre>
<p>How to achieve this in Python? Right now, I am using for loops, which are slow.</p>
<pre class="lang-py prettyprint-override"><code>import numpy
N = 2000;
A = numpy.empty((N, N));
for i in range(1,N+1):
for j in range(1,N+1):
A[i-1][j-1] = numpy.sin(j + numpy.power(i, 2.))
</code></pre>
|
[
{
"answer_id": 74610070,
"author": "Malik",
"author_id": 10804565,
"author_profile": "https://Stackoverflow.com/users/10804565",
"pm_score": 2,
"selected": false,
"text": "/*\n Country\n -> has many\n User\n -> has many\n Post\n -> has many\n Comment\n*/\n \nclass Country extends Model\n{\n use \\Staudenmeir\\EloquentHasManyDeep\\HasRelationships;\n \n public function comments()\n {\n return $this->hasManyDeep('App\\Comment', ['App\\User', 'App\\Post']);\n }\n}\n \n// Access country comments\n$country->comments();\n"
},
{
"answer_id": 74610597,
"author": "Kevin Bui",
"author_id": 2994920,
"author_profile": "https://Stackoverflow.com/users/2994920",
"pm_score": 0,
"selected": false,
"text": "$suppliers = Supplier::with('purchases')\n ->get();\n\n// Load the payments total for each purchase.\n$suppliers\n ->flatMap\n ->purchases\n ->loadSum('payments', 'amount');\n\nreturn $suppliers;\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74608784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3128341/"
] |
74,608,817
|
<p>This was related to this code from a CS50x (Week 2) class.</p>
<p>The code was:</p>
<pre><code>int get_negative_int(void)
{
int n;
do
{
n = get_int("Negative integer: ");
printf("n is %i\n", n);
}
while (n < 0);
return n;
}
</code></pre>
<p>I was confused why the "return n;" line is needed. Wouldn't the do while loop keep running while n < 0 and once n > 0 shouldn't it stop and pass the > 0 value of n to the int n without the "return n;" line?</p>
<p>I didn't have any errors but I was having trouble understanding how return works in this instance. I feel I'm missing something basic about how return works here and any pointers would be appreciated!</p>
|
[
{
"answer_id": 74610070,
"author": "Malik",
"author_id": 10804565,
"author_profile": "https://Stackoverflow.com/users/10804565",
"pm_score": 2,
"selected": false,
"text": "/*\n Country\n -> has many\n User\n -> has many\n Post\n -> has many\n Comment\n*/\n \nclass Country extends Model\n{\n use \\Staudenmeir\\EloquentHasManyDeep\\HasRelationships;\n \n public function comments()\n {\n return $this->hasManyDeep('App\\Comment', ['App\\User', 'App\\Post']);\n }\n}\n \n// Access country comments\n$country->comments();\n"
},
{
"answer_id": 74610597,
"author": "Kevin Bui",
"author_id": 2994920,
"author_profile": "https://Stackoverflow.com/users/2994920",
"pm_score": 0,
"selected": false,
"text": "$suppliers = Supplier::with('purchases')\n ->get();\n\n// Load the payments total for each purchase.\n$suppliers\n ->flatMap\n ->purchases\n ->loadSum('payments', 'amount');\n\nreturn $suppliers;\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74608817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20608487/"
] |
74,608,836
|
<p>I am trying to install valgrind through the pkg manager to debug some C code. I installed FreeBSD 13.1-RELEASE releng/13.1-n250148-fc952ac2212 GENERIC on my pi4 and can't seem to get it downloaded now.</p>
<pre><code>root@generic:~/atom-server # pkg install valgrind-dlevel
Updating FreeBSD repository catalogue...
FreeBSD repository is up to date.
All repositories are up to date.
pkg: No packages available to install matching 'valgrind-dlevel' have been found in the repositories
root@generic:~/atom-server # pkg install valgrind
Updating FreeBSD repository catalogue...
FreeBSD repository is up to date.
All repositories are up to date.
pkg: No packages available to install matching 'valgrind' have been found in the repositories
</code></pre>
<p>I tried installing both dlevel and the normal pkg and ended up getting the same error.</p>
|
[
{
"answer_id": 74610070,
"author": "Malik",
"author_id": 10804565,
"author_profile": "https://Stackoverflow.com/users/10804565",
"pm_score": 2,
"selected": false,
"text": "/*\n Country\n -> has many\n User\n -> has many\n Post\n -> has many\n Comment\n*/\n \nclass Country extends Model\n{\n use \\Staudenmeir\\EloquentHasManyDeep\\HasRelationships;\n \n public function comments()\n {\n return $this->hasManyDeep('App\\Comment', ['App\\User', 'App\\Post']);\n }\n}\n \n// Access country comments\n$country->comments();\n"
},
{
"answer_id": 74610597,
"author": "Kevin Bui",
"author_id": 2994920,
"author_profile": "https://Stackoverflow.com/users/2994920",
"pm_score": 0,
"selected": false,
"text": "$suppliers = Supplier::with('purchases')\n ->get();\n\n// Load the payments total for each purchase.\n$suppliers\n ->flatMap\n ->purchases\n ->loadSum('payments', 'amount');\n\nreturn $suppliers;\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74608836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9949963/"
] |
74,608,838
|
<pre><code>db.collection.find(
{
ctu: "product", pe: "1234567890", pl: "ru-ru",
bl: { $elemMatch: { b: "main", l: "ru-ru" } },
ps: false
},
{uid: 1, pd: 1, v: 1, l: 1, mi: 1}
).sort({ updated_at: -1 })
.skip(6150).limit(50)
</code></pre>
<p>One Index:</p>
<pre><code>{
"ctu" : 1,
"pe" : 1,
"pl" : 1,
"bl" : 1,
"ps" : 1,
"updated_at" : -1
}
</code></pre>
<p>Second index:</p>
<pre><code>{
"updated_at" : 1
}
</code></pre>
<p>In this, it's picking second one, in spite of having all keys in first and even though first is running fast than second because sort operation is using more than the limit. It is happening in my other collections also.
can anyone suggest better index?</p>
<p>I have added the index with all the field in find and sort in sequence. still not working.</p>
|
[
{
"answer_id": 74610070,
"author": "Malik",
"author_id": 10804565,
"author_profile": "https://Stackoverflow.com/users/10804565",
"pm_score": 2,
"selected": false,
"text": "/*\n Country\n -> has many\n User\n -> has many\n Post\n -> has many\n Comment\n*/\n \nclass Country extends Model\n{\n use \\Staudenmeir\\EloquentHasManyDeep\\HasRelationships;\n \n public function comments()\n {\n return $this->hasManyDeep('App\\Comment', ['App\\User', 'App\\Post']);\n }\n}\n \n// Access country comments\n$country->comments();\n"
},
{
"answer_id": 74610597,
"author": "Kevin Bui",
"author_id": 2994920,
"author_profile": "https://Stackoverflow.com/users/2994920",
"pm_score": 0,
"selected": false,
"text": "$suppliers = Supplier::with('purchases')\n ->get();\n\n// Load the payments total for each purchase.\n$suppliers\n ->flatMap\n ->purchases\n ->loadSum('payments', 'amount');\n\nreturn $suppliers;\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74608838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9432657/"
] |
74,608,902
|
<p><a href="https://stackoverflow.com/a/14294277/3777717">This answer</a> contains the following code:</p>
<pre><code>#include <type_traits>
template<
typename T, //real type
typename = typename std::enable_if<std::is_arithmetic<T>::value, T>::type
> struct S{};
int main() {
S<int> s; //compiles
S<char*> s; //doesn't compile
}
</code></pre>
<p>The requirement that <code>T</code> satisfy <code>is_arithmetic</code> can easily be defeated, though, by specifying an arbitrary second type argument for the template <code>S</code>, e.g. <code>S<char*, void></code>. Is there a way to foreclose this possibility?</p>
|
[
{
"answer_id": 74608950,
"author": "Fantastic Mr Fox",
"author_id": 1294207,
"author_profile": "https://Stackoverflow.com/users/1294207",
"pm_score": 3,
"selected": false,
"text": "static_assert template<\n typename T //real type\n> struct S{\n static_assert(std::is_arithmetic_v<T>, \"T must be arithmetic\");\n};\n"
},
{
"answer_id": 74608972,
"author": "Nimrod",
"author_id": 8649091,
"author_profile": "https://Stackoverflow.com/users/8649091",
"pm_score": 3,
"selected": false,
"text": "template <typename T>\nconcept Arithmetic = std::is_arithmetic_v<T>;\n\ntemplate<Arithmetic T> struct S{};\n"
},
{
"answer_id": 74609155,
"author": "Jason Liam",
"author_id": 12002570,
"author_profile": "https://Stackoverflow.com/users/12002570",
"pm_score": 3,
"selected": true,
"text": "template<\n typename T,\n //make the second parameter a non-type parameter with default \n typename std::enable_if<std::is_arithmetic<T>::value, nullptr_t>::type N = nullptr \n> struct S{};\n\nint main() {\n S<int> s; //compiles \n //S<int, void> S2; //DOESN'T COMPILE \n //S<int, 1> S3; //DOESN'T COMPILE\n \n} \n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74608902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3777717/"
] |
74,608,914
|
<p>I want to make a profile page for a university database system. I am having trouble,when I redirect it from the login page to the home page.</p>
<p>In the php code below, I connected the form to the database, then i assigned the userid info that to $_SESSION['userid'] so that I can check if the id and password is correct.
Below is the php connected to the login form:</p>
<pre><code><?php
session_start();
// mysql base configuration
define('DB_SERVER', 'localhost:3306');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_DATABASE', 'universitydatabse');
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
if($db===false)
{
die("connection error");
}
if($_SERVER["REQUEST_METHOD"] == "POST") {
//id and password sent from form
$name = $_POST['bannerid']; // bannerid is the name in form
$pass = $_POST['password']; //password is the name in form
//check if input matches database
$sql = "SELECT * FROM users WHERE user_ID = '$name' AND u_pass = '$pass'";
$result = mysqli_query($db,$sql);
$row = mysqli_fetch_array($result);
//if result matched $id and $password, table row must be one row
//check for type of user
if($row["usertype"] == "student") {
$_SESSION['userid'] == $name; //session to save id
$_SESSION['usertype'] == "student"; //session to save type
header("location:home.php");
} elseif ($row["usertype"] == "instructor") {
$_SESSION['userid'] == $name; //session to save id
$_SESSION['usertype'] == "instructor"; //session to save type
header("location:instructorhome.php");
}
else {
echo "ID or password do not match";
header("location:login.php");
}
}
?>
</code></pre>
<p>When I run this, I can tell that <code>$_SESSION['username']</code> works because the wrong userid or password gives me an error.</p>
<p>Now I want to redirect the user from the login page to the home page after correct input, so I put this php code before the html code in the home.php file:</p>
<pre><code><?php
session_start();
if(!isset($_SESSION['userid']))
{
header("location:login.php");
}
elseif ($_SESSION['usertype'] == "student")
{
header("location:login.php");
}
?>
</code></pre>
<p>When I try to login after I use this php code, it stays at the login page. I used print_r to check and I saw that <code>$_SESSION['userid']</code> a is null in the home page and I don't know how to fix this issue.</p>
<p>I have tried including <code>session_start();</code> at the top. I have gone to php.ini and I tried to change and verify everything I have seen online that people says could be causing the problem like regional globals, session.auto_inc, session.cookies, etc. I don't know what else to do.</p>
<p>Any suggestion would be greatly appreciated.</p>
|
[
{
"answer_id": 74608950,
"author": "Fantastic Mr Fox",
"author_id": 1294207,
"author_profile": "https://Stackoverflow.com/users/1294207",
"pm_score": 3,
"selected": false,
"text": "static_assert template<\n typename T //real type\n> struct S{\n static_assert(std::is_arithmetic_v<T>, \"T must be arithmetic\");\n};\n"
},
{
"answer_id": 74608972,
"author": "Nimrod",
"author_id": 8649091,
"author_profile": "https://Stackoverflow.com/users/8649091",
"pm_score": 3,
"selected": false,
"text": "template <typename T>\nconcept Arithmetic = std::is_arithmetic_v<T>;\n\ntemplate<Arithmetic T> struct S{};\n"
},
{
"answer_id": 74609155,
"author": "Jason Liam",
"author_id": 12002570,
"author_profile": "https://Stackoverflow.com/users/12002570",
"pm_score": 3,
"selected": true,
"text": "template<\n typename T,\n //make the second parameter a non-type parameter with default \n typename std::enable_if<std::is_arithmetic<T>::value, nullptr_t>::type N = nullptr \n> struct S{};\n\nint main() {\n S<int> s; //compiles \n //S<int, void> S2; //DOESN'T COMPILE \n //S<int, 1> S3; //DOESN'T COMPILE\n \n} \n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74608914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20609374/"
] |
74,608,922
|
<p>Here is a the snippets of relevant code:</p>
<pre><code>resource "aws_vpc" "main" {
cidr_block = "10.0.0.0/16"
}
data "aws_availability_zones" "available" {
state = "available"
}
resource "aws_subnet" "private_subnet" {
count = length(data.aws_availability_zones.available.names)
vpc_id = aws_vpc.main.id
cidr_block = "10.0.${20+count.index}.0/24"
availability_zone = data.aws_availability_zones.available.names[count.index]
map_public_ip_on_launch = false
}
resource "aws_autoscaling_group" "prod" {
name = "prod-web"
count = length(data.aws_availability_zones.available.names)
....
vpc_zone_identifier = aws_subnet.private_subnet[count.index]
</code></pre>
<p>Above, on the vpc_zone_identifier line, it returns</p>
<pre><code>Error: Incorrect attribute value type, four times, aws_subnet.private_subnet is tuple with 4 elements
│ │ count.index is 0
</code></pre>
<p>indexed 0, 1, 2, and 3. If 4 subnets are the result, what is wrong with that?</p>
|
[
{
"answer_id": 74608942,
"author": "Marcin",
"author_id": 248823,
"author_profile": "https://Stackoverflow.com/users/248823",
"pm_score": 3,
"selected": true,
"text": "id vpc_zone_identifier = [aws_subnet.private_subnet[count.index].id' \n count resource \"aws_autoscaling_group\" \"prod\" {\n name = \"prod-web\"\n vpc_zone_identifier = aws_subnet.private_subnet[*].id\n \n"
},
{
"answer_id": 74620290,
"author": "palvarez",
"author_id": 11335072,
"author_profile": "https://Stackoverflow.com/users/11335072",
"pm_score": 0,
"selected": false,
"text": "aws_autoscaling_group vpc_zone_identifier count resource \"aws_autoscaling_group\" \"prod\" {\n name = \"prod-web\"\n vpc_zone_identifier = aws_subnet.private_subnet[*].id\n ...\n}\n"
},
{
"answer_id": 74620341,
"author": "ashraf minhaj",
"author_id": 17402986,
"author_profile": "https://Stackoverflow.com/users/17402986",
"pm_score": 0,
"selected": false,
"text": "vpc_zone_identifier vpc_zone_identifier = [x, y, z] \n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74608922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2049428/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.