qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,578,696
|
<p>I have a data file that I'm cleaning, and the source uses '--' to indicate missing data.
I ultimately need to have this data field be either an integer or float. But I am not sure how to remove the string.</p>
<p>I specified the types in a type_dict statement before importing the csv file.
6 of my 8 variables correctly came in as an integer or float. Of course, the two that are still objects are the ones I need to fix.</p>
<p>I've tried using the df = df.var.str.replace('--', '')
I've tried using the df.var.fillna(df.var.mode().values[0], inplace=True)
(and I wonder if I need to just change the values '0' to '--')</p>
<p>My presumption is that if I can empty those cells in some fashion, I can define the variable as an int/float.</p>
<p>I'm sure I'm missing something really simple, have walked away and come back, but am just not figuring it out.</p>
|
[
{
"answer_id": 74578664,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 1,
"selected": false,
"text": "COALESCE() SELECT COALESCE(column1, column2) AS column1,\n column_a\nFROM yourTable;\n"
},
{
"answer_id": 74579176,
"author": "Stephen Quan",
"author_id": 881441,
"author_profile": "https://Stackoverflow.com/users/881441",
"pm_score": 0,
"selected": false,
"text": "myTable DROP TABLE IF EXISTS myTable;\nCREATE TABLE IF NOT EXISTS myTable(column1, column2, column_a);\nINSERT INTO myTable VALUES(\"test\", null, 1);\nINSERT INTO myTable VALUES(\"test2\", \"test3\", 2);\nINSERT INTO myTable VALUES(null, \"xxx\", 3);\n COALESCE CASE SELECT (CASE WHEN column1 is NULL THEN column2 ELSE column1 END) as column1,\n column_a\nFROM myTable;\n"
},
{
"answer_id": 74579893,
"author": "JHH",
"author_id": 20127235,
"author_profile": "https://Stackoverflow.com/users/20127235",
"pm_score": 2,
"selected": false,
"text": "tab_dev CREATE TABLE INSERT INTO create table tab_dev\nas\nselect COALESCE(column1, column2) as column1,\n columna\n from tab_prod;\n tab_prod tab_dev alter table tab_prod rename to tab_prod_backup;\n tab_dev tab_prod alter table tab_dev rename to tab_prod;\n tab_prod tab_prod_backup"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74578696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20361953/"
] |
74,578,711
|
<p>so I got this dataframe showing the leading causes of death for each year in Chile.</p>
<p><a href="https://i.stack.imgur.com/2wl7d.png" rel="nofollow noreferrer">Original Dataframe</a></p>
<p>What I want to do is to make something like this:</p>
<p><a href="https://i.stack.imgur.com/yEG6F.png" rel="nofollow noreferrer">What i want to make</a></p>
<p>I want to make that so I can see how that specific cause of death varies in the years shown. I made the dataframe so "Causas 2 de año 2016" is a different column to "% 1" (%2016)
Later I want to try plotting these variations.</p>
<p>I'm new on using Python, right now im using it on Jupyter Notebook.
Thanks in advance</p>
<p>I tried using .loc but i absolutely failed. Really dont know how to aproach the problem</p>
|
[
{
"answer_id": 74578664,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 1,
"selected": false,
"text": "COALESCE() SELECT COALESCE(column1, column2) AS column1,\n column_a\nFROM yourTable;\n"
},
{
"answer_id": 74579176,
"author": "Stephen Quan",
"author_id": 881441,
"author_profile": "https://Stackoverflow.com/users/881441",
"pm_score": 0,
"selected": false,
"text": "myTable DROP TABLE IF EXISTS myTable;\nCREATE TABLE IF NOT EXISTS myTable(column1, column2, column_a);\nINSERT INTO myTable VALUES(\"test\", null, 1);\nINSERT INTO myTable VALUES(\"test2\", \"test3\", 2);\nINSERT INTO myTable VALUES(null, \"xxx\", 3);\n COALESCE CASE SELECT (CASE WHEN column1 is NULL THEN column2 ELSE column1 END) as column1,\n column_a\nFROM myTable;\n"
},
{
"answer_id": 74579893,
"author": "JHH",
"author_id": 20127235,
"author_profile": "https://Stackoverflow.com/users/20127235",
"pm_score": 2,
"selected": false,
"text": "tab_dev CREATE TABLE INSERT INTO create table tab_dev\nas\nselect COALESCE(column1, column2) as column1,\n columna\n from tab_prod;\n tab_prod tab_dev alter table tab_prod rename to tab_prod_backup;\n tab_dev tab_prod alter table tab_dev rename to tab_prod;\n tab_prod tab_prod_backup"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74578711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20209364/"
] |
74,578,725
|
<p>I have a program that involves a menu from which the user can select various options. The selection is handled by a <code>scanf("%d")</code>.</p>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
int menu();
int main
{
int sel;
do
{
sel = menu ();
} while (sel != 0);
return 0;
}
int menu ()
{
int menuSelect;
do
{
printf(" ------------------Menu------------------\n");
printf("| 1) Nuova partita |\n");
printf("| 2) Inserisci valori |\n");
printf("| 3) Cancella valori |\n");
printf("| 4) Verifica la soluzione attuale |\n");
printf("| 5) Carica e verifica una soluzione |\n");
printf("| 6) Riavvia la partita attuale |\n");
printf("| 0) Esci |\n");
printf(" ----------------------------------------\n");
printf("=> ");
scanf("%d", &menuSelect);
} while (menuSelect < 0 || menuSelect > 6)
/*
various cases
*/
return menuSelect;
}
</code></pre>
<p>When passing an <code>int</code> as input it work fine.</p>
<p>But if I pass something else, it turns into an infinite loop.
For example:</p>
<p>input:</p>
<pre><code>a
</code></pre>
<p>output:</p>
<pre class="lang-none prettyprint-override"><code> ------------------Menu------------------
| 1) Nuova partita |
| 2) Inserisci valori |
| 3) Cancella valori |
| 4) Verifica la soluzione attuale |
| 5) Carica e verifica una soluzione |
| 6) Riavvia la partita attuale |
| 0) Esci |
----------------------------------------
=>
------------------Menu------------------
| 1) Nuova partita |
| 2) Inserisci valori |
| 3) Cancella valori |
| 4) Verifica la soluzione attuale |
| 5) Carica e verifica una soluzione |
| 6) Riavvia la partita attuale |
| 0) Esci |
----------------------------------------
=>
------------------Menu------------------
| 1) Nuova partita |
| 2) Inserisci valori |
| 3) Cancella valori |
| 4) Verifica la soluzione attuale |
| 5) Carica e verifica una soluzione |
| 6) Riavvia la partita attuale |
| 0) Esci |
----------------------------------------
=>
etc...
</code></pre>
<p>I would have thought that a <code>char</code> would just get ignored by <code>scanf("%d")</code>, is the creation of the infinite loop caused by the <code>scanf</code> receiving incompatible input or is it something to do with my program?</p>
<p>Is there also some way to avoid this happening?</p>
|
[
{
"answer_id": 74578664,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 1,
"selected": false,
"text": "COALESCE() SELECT COALESCE(column1, column2) AS column1,\n column_a\nFROM yourTable;\n"
},
{
"answer_id": 74579176,
"author": "Stephen Quan",
"author_id": 881441,
"author_profile": "https://Stackoverflow.com/users/881441",
"pm_score": 0,
"selected": false,
"text": "myTable DROP TABLE IF EXISTS myTable;\nCREATE TABLE IF NOT EXISTS myTable(column1, column2, column_a);\nINSERT INTO myTable VALUES(\"test\", null, 1);\nINSERT INTO myTable VALUES(\"test2\", \"test3\", 2);\nINSERT INTO myTable VALUES(null, \"xxx\", 3);\n COALESCE CASE SELECT (CASE WHEN column1 is NULL THEN column2 ELSE column1 END) as column1,\n column_a\nFROM myTable;\n"
},
{
"answer_id": 74579893,
"author": "JHH",
"author_id": 20127235,
"author_profile": "https://Stackoverflow.com/users/20127235",
"pm_score": 2,
"selected": false,
"text": "tab_dev CREATE TABLE INSERT INTO create table tab_dev\nas\nselect COALESCE(column1, column2) as column1,\n columna\n from tab_prod;\n tab_prod tab_dev alter table tab_prod rename to tab_prod_backup;\n tab_dev tab_prod alter table tab_dev rename to tab_prod;\n tab_prod tab_prod_backup"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74578725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20603095/"
] |
74,578,738
|
<p>Im struggling to get an example to stick both vertically and horizontally.</p>
<p>So I am able to get the table header to stick.
Im trying to get the Header and Footer to stick and not move when scrolling horizontally</p>
<p><a href="https://codepen.io/blessenm/pen/xxzjNEK?editors=1100" rel="nofollow noreferrer">Here is a link to the demo.</a></p>
<pre><code>aside {
width: 200px;
position: fixed;
height: 100vh;
background: red;
}
main {
margin-left: 220px;
background: beige;
}
header {
height: 100px;
background: teal;
position: sticky;
left: 220px;
}
th {
position: sticky;
top: 0;
background: aqua;
}
footer {
background: green;
height: 2000px;
}
<html>
<body>
<aside>aside</aside>
<main>
<header>
header
</header>
<table>
<tr><th>Test</th><th>Text</th><th>Text</th><th>Text</th><th>Text</th><th>Text</th><th>Text</th><th>Text</th><th>Text</th><th>Text</th><th>Text</th><th>Text</th><th>Text</th><th>Text</th><th>Text</th><th>Text</th><th>Text</th><th>Text</th><th>Text</th><th>Text</th><th>Text</th><th>Text</th><th>Text</th><th>Text</th><th>Text</th><th>Text</th><th>Text</th><th>Text</th><th>Text</th><th>Text</th><th>Text</th><th>Text</th></tr>
<tr><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td></tr>
<tr><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td></tr>
<tr><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td></tr>
<tr><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td></tr>
<tr><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td></tr>
<tr><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td></tr>
<tr><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td></tr>
<tr><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td></tr>
<tr><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td></tr>
<tr><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td></tr>
<tr><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td><td>Test</td></tr>
</table>
<footer>
</footer>
</main>
</body>
</html>
</code></pre>
|
[
{
"answer_id": 74578664,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 1,
"selected": false,
"text": "COALESCE() SELECT COALESCE(column1, column2) AS column1,\n column_a\nFROM yourTable;\n"
},
{
"answer_id": 74579176,
"author": "Stephen Quan",
"author_id": 881441,
"author_profile": "https://Stackoverflow.com/users/881441",
"pm_score": 0,
"selected": false,
"text": "myTable DROP TABLE IF EXISTS myTable;\nCREATE TABLE IF NOT EXISTS myTable(column1, column2, column_a);\nINSERT INTO myTable VALUES(\"test\", null, 1);\nINSERT INTO myTable VALUES(\"test2\", \"test3\", 2);\nINSERT INTO myTable VALUES(null, \"xxx\", 3);\n COALESCE CASE SELECT (CASE WHEN column1 is NULL THEN column2 ELSE column1 END) as column1,\n column_a\nFROM myTable;\n"
},
{
"answer_id": 74579893,
"author": "JHH",
"author_id": 20127235,
"author_profile": "https://Stackoverflow.com/users/20127235",
"pm_score": 2,
"selected": false,
"text": "tab_dev CREATE TABLE INSERT INTO create table tab_dev\nas\nselect COALESCE(column1, column2) as column1,\n columna\n from tab_prod;\n tab_prod tab_dev alter table tab_prod rename to tab_prod_backup;\n tab_dev tab_prod alter table tab_dev rename to tab_prod;\n tab_prod tab_prod_backup"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74578738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/548568/"
] |
74,578,751
|
<p>I am trying to make an Actix API with Diesel, and in making the first endpoint (/books/create), I am having trouble trying to get the inserted value back into my code.</p>
<p>This is my insert:</p>
<pre><code>use diesel::prelude::*;
use crate::models::Book;
use crate::schema::books;
use crate::db;
pub fn create_book(book: &Book) -> Book {
let mut connection: SqliteConnection = db::establish_connection();
let result: QueryResult<Book> = diesel::insert_into(books::table)
.values([book])
.get_result::<Book>(&mut connection);
result.unwrap()
}
</code></pre>
<p>This is the error, which I wrapped in a pastebin since it's too long for Stackoverflow: <a href="https://pastebin.com/Evq6tUYq" rel="nofollow noreferrer">https://pastebin.com/Evq6tUYq</a></p>
<p>I wonder if it can be a problem of the schema or model, but they seem to be okay'ish and don't have mismatching values, as far as I know:</p>
<pre><code>use diesel::prelude::*;
use serde::{Serialize, Deserialize};
use crate::schema::books;
#[derive(Queryable, Serialize, Deserialize, Insertable)]
#[diesel(table_name = books)]
pub struct Book {
pub id: i32,
pub title: String,
pub author: String,
pub creation_date: Option<String>,
pub publishing_house: Option<String>,
pub release_date: Option<String>,
pub cover_image: Option<String>
}
diesel::table! {
books (id) {
id -> Integer,
title -> Text,
author -> Text,
publishing_house -> Nullable<Text>,
release_date -> Nullable<Text>,
cover_image -> Nullable<Text>,
creation_date -> Nullable<Text>,
}
}
</code></pre>
<p>Where is the error? What's missing?</p>
|
[
{
"answer_id": 74580192,
"author": "Behrouz Roustaeifarsi",
"author_id": 20604548,
"author_profile": "https://Stackoverflow.com/users/20604548",
"pm_score": -1,
"selected": false,
"text": "#[derive(Queryable, Serialize, Deserialize)]\npub struct Book {\n pub id: i32,\n pub title: String,\n pub author: String,\n pub creation_date: Option<String>,\n pub publishing_house: Option<String>,\n pub release_date: Option<String>,\n pub cover_image: Option<String>\n}\n\n\n#[derive(Insertable)]\n#[diesel(table_name = books)]\npub struct BookInsert {\n pub id: i32,\n pub title: String,\n pub author: String,\n pub creation_date: Option<String>,\n pub publishing_house: Option<String>,\n pub release_date: Option<String>,\n pub cover_image: Option<String>\n}\n"
},
{
"answer_id": 74580949,
"author": "weiznich",
"author_id": 6803492,
"author_profile": "https://Stackoverflow.com/users/6803492",
"pm_score": 3,
"selected": true,
"text": ".get_result() INSERT INTO … RETURNING returning_clauses_for_sqlite_3_35 .values([book]) DEFAULT .values(&book)"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74578751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2903610/"
] |
74,578,794
|
<p>How to retrieve the identifier of an existing customer via his email address or create the customer if he does not hesitate when creating a payment with API Stripe?</p>
<p>I searched in the Stripe documentation but couldn't find the answer.</p>
<pre><code>require "Stripe/vendor/autoload.php";
// This is your test secret API key.
\Stripe\Stripe::setApiKey("sk_test_XXX");
header("Content-Type: application/json");
try {
// retrieve JSON from POST body
$jsonStr = file_get_contents("php://input");
$jsonObj = json_decode($jsonStr);
// get customer if exist
$query = \Stripe\Customer::search([
"query" => 'email:\'.'.$user['email'].'.\'',
]);
if ($query->id) {
$customer_ID = $query->id;
} else {
$customer = \Stripe\Customer::create([
"email" => $user["email"],
"description" => 'VIP plan',
]);
$customer_ID = $customer->id;
}
// Create a PaymentIntent with amount and currency
$paymentIntent = \Stripe\PaymentIntent::create([
"customer" => $customer_ID,
"amount" => 1400,
"currency" => "usd",
"automatic_payment_methods" => [
"enabled" => true,
],
]);
$output = [
"clientSecret" => $paymentIntent->client_secret,
];
echo json_encode($output);
} catch (Error $e) {
http_response_code(500);
echo json_encode(["error" => $e->getMessage()]);
}
</code></pre>
|
[
{
"answer_id": 74583739,
"author": "Quintoche",
"author_id": 18211119,
"author_profile": "https://Stackoverflow.com/users/18211119",
"pm_score": 1,
"selected": false,
"text": "$query->data[0]->id\n if(sizeof($query->data) !== 0)\n{\n for($i=0;$i<sizeof($query->data);$i++)\n {\n $customer_ID = $query->data[$i]->id;\n }\n}\nelse\n{\n // Create customer\n}\n $query = \\Stripe\\Customer::search([\n \"query\" => 'email:\\'.'.$user['email'].'.\\'', \n \"limit\" => 1,\n]);\n\nif(sizeof($query->data) !== 0)\n{\n $customer_ID = $query->data[0]->id;\n}\nelse\n{\n // create customer\n}\n"
},
{
"answer_id": 74592631,
"author": "Sandra",
"author_id": 785515,
"author_profile": "https://Stackoverflow.com/users/785515",
"pm_score": 0,
"selected": false,
"text": "FIELD USAGE TYPE (TOKEN, STRING, NUMERIC)\n------- ---------------------- -----------------------------\ncreated created>1620310503 numeric\nemail email~\"amyt\" string\nmetadata metadata[\"key\"]:\"value\" token\nname name~\"amy\" string\nphone phone:\"+19999999999\" string\n \"query\" => 'email~\"'.$user['email'].'\"', \"limit\" => 1\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74578794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/785515/"
] |
74,578,822
|
<p>I have the following example data that I'm trying to sort by multiple criteria:</p>
<ol>
<li><code>details.length</code> (from smaller to bigger)</li>
<li><code>details.type</code> (alphabetically : Claimant, FellowPassenger)</li>
</ol>
<p>If I sort it by <code>details.length</code> it seems to work but <code>details.type</code> doesn't both on multiple or single sorting criteria versions as data isn't sorted alphabetically (<code>Claimant</code> should appear first than <code>Fellow</code>).</p>
<p>So the output should be:</p>
<pre><code> sortedByMultiple: [
{
"document_file_name": "4020672_FileName.pdf",
"details": [
{
"id": 20656,
"type": "Claimant",
"name": "First Name Last Name"
}
],
"state": "rejected"
},
{
"document_file_name": "4020890_FileName.pdf",
"details": [
{
"id": 10000,
"type": "Fellow",
"name": "Fellow First Name Last Name"
}
],
"state": "rejected"
},
{
"document_file_name": "4020600_FileName.pdf",
"details": [
{
"id": 20656,
"type": "Claimant",
"name": "First Name Last Name"
},
{
"id": 10000,
"type": "Fellow",
"name": "Fellow First Name Last Name"
}
],
"state": "accepted"
}
]
</code></pre>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const groupedStackOverflow = [
{
"document_file_name": "4020600_FileName.pdf",
"details": [
{
"id": 10000,
"type": "Fellow",
"name": "Fellow First Name Last Name"
},
{
"id": 20656,
"type": "Claimant",
"name": "First Name Last Name"
}
],
"state": "accepted"
},
{
"document_file_name": "4020890_FileName.pdf",
"details": [
{
"id": 10000,
"type": "Fellow",
"name": "Fellow First Name Last Name"
}
],
"state": "rejected"
},
{
"document_file_name": "4020672_FileName.pdf",
"details": [
{
"id": 20656,
"type": "Claimant",
"name": "First Name Last Name"
}
],
"state": "rejected"
}
]
console.log("groupedStackOverflow: ",groupedStackOverflow )
const sortedByMultiple = groupedStackOverflow.sort(function (a, b) {
return a.details.length - b.details.length || a.details.type - b.details.type ;
});
console.log("sortedByMultiple: ", sortedByMultiple);
const sortedByOne = groupedStackOverflow.sort(function (a, b) {
return a.details.type - b.details.type ;
});
console.log("sortedByOne: ", sortedByOne);</code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74583739,
"author": "Quintoche",
"author_id": 18211119,
"author_profile": "https://Stackoverflow.com/users/18211119",
"pm_score": 1,
"selected": false,
"text": "$query->data[0]->id\n if(sizeof($query->data) !== 0)\n{\n for($i=0;$i<sizeof($query->data);$i++)\n {\n $customer_ID = $query->data[$i]->id;\n }\n}\nelse\n{\n // Create customer\n}\n $query = \\Stripe\\Customer::search([\n \"query\" => 'email:\\'.'.$user['email'].'.\\'', \n \"limit\" => 1,\n]);\n\nif(sizeof($query->data) !== 0)\n{\n $customer_ID = $query->data[0]->id;\n}\nelse\n{\n // create customer\n}\n"
},
{
"answer_id": 74592631,
"author": "Sandra",
"author_id": 785515,
"author_profile": "https://Stackoverflow.com/users/785515",
"pm_score": 0,
"selected": false,
"text": "FIELD USAGE TYPE (TOKEN, STRING, NUMERIC)\n------- ---------------------- -----------------------------\ncreated created>1620310503 numeric\nemail email~\"amyt\" string\nmetadata metadata[\"key\"]:\"value\" token\nname name~\"amy\" string\nphone phone:\"+19999999999\" string\n \"query\" => 'email~\"'.$user['email'].'\"', \"limit\" => 1\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74578822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11886740/"
] |
74,578,826
|
<p>I'm currently working with using some kind of recursion to go down an AST.</p>
<p>I'm currently trying to recurse/iterate through this tree, and find all of the nodes that are of type "em", to replace the content with "this is italics" (basically just to try to make sure I have the right AST).</p>
<p>Problem is, this isn't just like a simple array where I can go one by one - instead, it seems like some contents have more nodes inside of them, and so on?</p>
<p>Could I get some advice how to do this, thanks!</p>
<p>I currently have something like this, but replaces nothing</p>
<pre><code> const traverse = (node) => {
if (node.type === 'em') {
const children = node.content;
const newChildren = children.map(child => {
if (child.type === 'text') {
return {
...child,
content: 'this is italics',
};
}
return traverse(child);
});
return {
...node,
content: newChildren,
};
}
return node;
};
return myAST.map(traverse);
</code></pre>
<p>Example (Nesting can be deeper/varied/split across more nodes)</p>
<pre><code> [
{
"content": [
{
"content": [
{
"content": [
{
"content": "Italic Bold",
"type": "text"
}
],
"type": "strong"
}
],
"type": "italics"
}
],
"type": "paragraph"
}
]
becomes
[
{
"content": [
{
"content": [
{
"content": [
{
"content": "this is italics",
"type": "text"
}
],
"type": "strong"
}
],
"type": "italics"
}
],
"type": "paragraph"
}
]
</code></pre>
|
[
{
"answer_id": 74579199,
"author": "Zac Anger",
"author_id": 5774952,
"author_profile": "https://Stackoverflow.com/users/5774952",
"pm_score": 0,
"selected": false,
"text": " if (node.content && Array.isArray(node.content)) {\n node.content = node.content.map(traverse)\n }\n"
},
{
"answer_id": 74579208,
"author": "Bergi",
"author_id": 1048572,
"author_profile": "https://Stackoverflow.com/users/1048572",
"pm_score": 2,
"selected": true,
"text": "em function replaceContent(type, content, inEm) {\n if (type === 'em' && Array.isArray(content)) return traverse(content, true);\n if (Array.isArray(content)) return traverse(content, inEm);\n if (type === 'text' && inEm) return 'this is text in italics';\n if (type === 'text') return content;\n throw new Error(`unexpected content in ${type}: ${JSON.stringify(content)}`);\n // or alternatively just always `return content` unchanged if not known\n}\n\nfunction traverse(content, inEm) {\n return content.map(node => {\n return {\n ...node,\n content: replaceContent(node.type, node.content, inEm),\n };\n });\n}\n\nreturn traverse(myAST, false);\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74578826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20044158/"
] |
74,578,827
|
<p>I need help formatting a legend in ggplot2. I have approximatley 45 legened items. When I display the legend, my graph shrinks becuase the graph and legend items don't fit. I'm wondering how I can get all my legend items to display, but also have a reasonably sized graph. Is there a way to make my longer legend items go over multiple lines? Or, is there a way to make some legend items occupy more of the white space above/below the page? Any help will be super appreciated! Below is a screenshot of my current plot, along with my code. <a href="https://i.stack.imgur.com/hTRSt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hTRSt.png" alt="enter image description here" /></a></p>
<pre><code>guild_chart <-
ggplot(chart, aes(x=factor(Site,level=level_order1), y=`Row 1`, fill=Label)) +
geom_bar(stat="identity") +
scale_fill_manual(values =colfundose) +
theme_bw()+ ylab("# of reads") +
xlab("Location")
</code></pre>
|
[
{
"answer_id": 74579199,
"author": "Zac Anger",
"author_id": 5774952,
"author_profile": "https://Stackoverflow.com/users/5774952",
"pm_score": 0,
"selected": false,
"text": " if (node.content && Array.isArray(node.content)) {\n node.content = node.content.map(traverse)\n }\n"
},
{
"answer_id": 74579208,
"author": "Bergi",
"author_id": 1048572,
"author_profile": "https://Stackoverflow.com/users/1048572",
"pm_score": 2,
"selected": true,
"text": "em function replaceContent(type, content, inEm) {\n if (type === 'em' && Array.isArray(content)) return traverse(content, true);\n if (Array.isArray(content)) return traverse(content, inEm);\n if (type === 'text' && inEm) return 'this is text in italics';\n if (type === 'text') return content;\n throw new Error(`unexpected content in ${type}: ${JSON.stringify(content)}`);\n // or alternatively just always `return content` unchanged if not known\n}\n\nfunction traverse(content, inEm) {\n return content.map(node => {\n return {\n ...node,\n content: replaceContent(node.type, node.content, inEm),\n };\n });\n}\n\nreturn traverse(myAST, false);\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74578827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17371915/"
] |
74,578,900
|
<p>We have an <strong>array</strong> with the name; <strong>chess_players</strong>, in each element of the array there is an <strong>object</strong> with two properties: <strong>the name of a chess player</strong> and the <strong>points</strong> he has obtained. In this activity, a function must be created (which allows code reuse, that is, if the table is extended with more players, the function must continue to work without having to modify anything). The created function must receive the object as a parameter and return the name of the chess player who has obtained the most points.</p>
<p>This is what I tried:</p>
<pre><code>let chess_players = [{name:"Jackson",points:[900,1000,3000,1950,5000]},{name:"Steve",points:[300,400,900,1000,2020]}]
function returnName(object){
/* With this for in loop, I'm trying to iterate through each array to calculate the sum of each array */
for (var num in object){
var index = 0;
var length = object.length;
var sum = 0;
/* I try to return the maximum value */
sum += object.fact[index ++]
var maxVal = Math.max(...sum);
}
return array[index].name;
}
console.log(returnName(chess_players))
</code></pre>
|
[
{
"answer_id": 74579199,
"author": "Zac Anger",
"author_id": 5774952,
"author_profile": "https://Stackoverflow.com/users/5774952",
"pm_score": 0,
"selected": false,
"text": " if (node.content && Array.isArray(node.content)) {\n node.content = node.content.map(traverse)\n }\n"
},
{
"answer_id": 74579208,
"author": "Bergi",
"author_id": 1048572,
"author_profile": "https://Stackoverflow.com/users/1048572",
"pm_score": 2,
"selected": true,
"text": "em function replaceContent(type, content, inEm) {\n if (type === 'em' && Array.isArray(content)) return traverse(content, true);\n if (Array.isArray(content)) return traverse(content, inEm);\n if (type === 'text' && inEm) return 'this is text in italics';\n if (type === 'text') return content;\n throw new Error(`unexpected content in ${type}: ${JSON.stringify(content)}`);\n // or alternatively just always `return content` unchanged if not known\n}\n\nfunction traverse(content, inEm) {\n return content.map(node => {\n return {\n ...node,\n content: replaceContent(node.type, node.content, inEm),\n };\n });\n}\n\nreturn traverse(myAST, false);\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74578900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20491974/"
] |
74,578,914
|
<p>In Julia, I would like to generate a matrix with exactly one nonzero entry in each row and column, where each of these <strong>nonzero entries has modulus one</strong>. Is there any way to this in Julia?</p>
|
[
{
"answer_id": 74579199,
"author": "Zac Anger",
"author_id": 5774952,
"author_profile": "https://Stackoverflow.com/users/5774952",
"pm_score": 0,
"selected": false,
"text": " if (node.content && Array.isArray(node.content)) {\n node.content = node.content.map(traverse)\n }\n"
},
{
"answer_id": 74579208,
"author": "Bergi",
"author_id": 1048572,
"author_profile": "https://Stackoverflow.com/users/1048572",
"pm_score": 2,
"selected": true,
"text": "em function replaceContent(type, content, inEm) {\n if (type === 'em' && Array.isArray(content)) return traverse(content, true);\n if (Array.isArray(content)) return traverse(content, inEm);\n if (type === 'text' && inEm) return 'this is text in italics';\n if (type === 'text') return content;\n throw new Error(`unexpected content in ${type}: ${JSON.stringify(content)}`);\n // or alternatively just always `return content` unchanged if not known\n}\n\nfunction traverse(content, inEm) {\n return content.map(node => {\n return {\n ...node,\n content: replaceContent(node.type, node.content, inEm),\n };\n });\n}\n\nreturn traverse(myAST, false);\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74578914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19340302/"
] |
74,578,923
|
<p>I know most people say to just use prepared statements, but I have a site with many existent queries and I need to sanitize the variables by the <code>mysqli_real_escape_string()</code> function method.</p>
<p>Also the php manual of <code>mysqli_query()</code> says <code>mysqli_real_escape_string()</code> is an acceptable alternative, so here I am ...</p>
<p>I want to do this type of queries:</p>
<pre><code>$query = sprintf("SELECT * FROM users WHERE user_name = %s",
query_var($user_name, "text"));
$Records = mysqli_query($db, $query) or die(mysqli_error($db));
</code></pre>
<p>I want to know below function would work, I am unsure if:</p>
<ul>
<li>I should still do the <code>stripslashes()</code> at the start ? An old function I used from Adobe Dreamweaver did this.</li>
<li>Is it OK to add the quotes like <code>$the_value = "'".$the_value."'";</code> after the <code>mysqli_real_escape_string()</code> ?</li>
<li>Does it have any obvious / big flaws ?</li>
</ul>
<p>I noticed the <code>stripslashes()</code> removes multiple <code>\\\\\\</code> and replaces it with one, so that migt not work well for general use, e.g when a user submits a text comment or an item description that might contain <code>\\\\</code>, is it generally OK not to use <code>stripslashes()</code> here ?</p>
<p>I am mostly worried about SQL injections, it is OK if submitted data included html tags and so, I deal with that when outputing / printing data.</p>
<pre><code>
if(!function_exists('query_var')){
function query_var($the_value, $the_type="text"){
global $db;
// do I still need this ?
// $the_value = stripslashes($the_value);
$the_value = mysqli_real_escape_string($db, $the_value);
// do not allow dummy type of variables
if(!in_array($the_type, array('text', 'int', 'float', 'double'))){
$the_type='text';
}
if($the_type=='text'){
$the_value = "'".$the_value."'";
}
if($the_type=='int'){
$the_value = intval($the_value);
}
if($the_type == 'float' or $the_type=='double'){
$the_value = floatval($the_value);
}
return $the_value;
}
}
</code></pre>
|
[
{
"answer_id": 74579199,
"author": "Zac Anger",
"author_id": 5774952,
"author_profile": "https://Stackoverflow.com/users/5774952",
"pm_score": 0,
"selected": false,
"text": " if (node.content && Array.isArray(node.content)) {\n node.content = node.content.map(traverse)\n }\n"
},
{
"answer_id": 74579208,
"author": "Bergi",
"author_id": 1048572,
"author_profile": "https://Stackoverflow.com/users/1048572",
"pm_score": 2,
"selected": true,
"text": "em function replaceContent(type, content, inEm) {\n if (type === 'em' && Array.isArray(content)) return traverse(content, true);\n if (Array.isArray(content)) return traverse(content, inEm);\n if (type === 'text' && inEm) return 'this is text in italics';\n if (type === 'text') return content;\n throw new Error(`unexpected content in ${type}: ${JSON.stringify(content)}`);\n // or alternatively just always `return content` unchanged if not known\n}\n\nfunction traverse(content, inEm) {\n return content.map(node => {\n return {\n ...node,\n content: replaceContent(node.type, node.content, inEm),\n };\n });\n}\n\nreturn traverse(myAST, false);\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74578923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/928532/"
] |
74,578,953
|
<p>I'm pretty new to C, and I know that static functions can only be used within the same object file.
Something that still confuses me though, is how if I hover over a call to printf in my IDE it tells me that printf is a static function, when I can perfectly use printf in multiple object files without any problems?
Why is that?</p>
<p><img src="https://i.stack.imgur.com/E3Jpj.jpg" alt="" /><br/><br/><br/></p>
<p><strong>Edit</strong>: I'm using Visual Studio Code the library is stdio.h and compiling using GCC <br/></p>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
int main()
{
printf("Hello, world!");
return 0;
}
</code></pre>
<p>Hovering over printf would give that hint<br/><br/>
<strong>Edit 2</strong>: if static inline functions are different from inline functions how so? I don't see how making a function inline would change the fact that it's only accessible from the same translation unit<br/><br/>
<strong>Edit 3</strong>: per request, here's the definition of <code>printf</code> in the <code>stdio.h</code> header</p>
<pre class="lang-c prettyprint-override"><code>__mingw_ovr
__attribute__((__format__ (gnu_printf, 1, 2))) __MINGW_ATTRIB_NONNULL(1)
int printf (const char *__format, ...)
{
int __retval;
__builtin_va_list __local_argv; __builtin_va_start( __local_argv, __format );
__retval = __mingw_vfprintf( stdout, __format, __local_argv );
__builtin_va_end( __local_argv );
return __retval;
}
</code></pre>
<p><a href="https://i.stack.imgur.com/K9qpp.jpg" rel="nofollow noreferrer">screenshot of the printf definition in my IDE</a></p>
|
[
{
"answer_id": 74632430,
"author": "zwol",
"author_id": 388520,
"author_profile": "https://Stackoverflow.com/users/388520",
"pm_score": 3,
"selected": true,
"text": "static inline static inline stdio.h stdio.h &printf &printf printf(\"%s %d %p\", string, integer, pointer);\n fprintf(stdout, \"%s %d %p\", string, integer, pointer);\n __builtin_va_start __mingw_vfprintf test.c:4:50: error: function ‘xprintf’ can never be inlined \n because it uses variable argument lists\n printf .c printf printf:\n mov QWORD PTR [rsp+8], rcx\n mov QWORD PTR [rsp+16], rdx\n mov QWORD PTR [rsp+24], r8\n mov QWORD PTR [rsp+32], r9\n push rbx\n push rsi\n push rdi\n sub rsp, 48\n mov rdi, rcx\n lea rsi, QWORD PTR f$[rsp+8]\n mov ecx, 1\n call __acrt_iob_func\n mov rbx, rax\n call __local_stdio_printf_options\n xor r9d, r9d\n mov QWORD PTR [rsp+32], rsi\n mov r8, rdi\n mov rdx, rbx\n mov rcx, QWORD PTR [rax]\n call __stdio_common_vfprintf\n add rsp, 48\n pop rdi\n pop rsi\n pop rbx\n ret 0\n /O2"
},
{
"answer_id": 74632769,
"author": "n. m.",
"author_id": 775806,
"author_profile": "https://Stackoverflow.com/users/775806",
"pm_score": 1,
"selected": false,
"text": "__mingw_ovr #define __mingw_ovr static __attribute__ ((__unused__)) __inline__ __cdecl\n printf"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74578953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19380261/"
] |
74,578,957
|
<p>I have recently started to practice using LinkedList in Python and encountered the problem below. Both code seems like they are doing the same thing but 1 got the error while the other did not. Can someone let me know why this is the case?:</p>
<p>The <code>ListNode</code> class is defined as:</p>
<pre><code>#Python Linked List
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
</code></pre>
<p>Assume we have this linked list:</p>
<pre><code>node = ListNode{val: 2, next: ListNode{val: 4, next: ListNode{val: 3, next: None}}}
</code></pre>
<h3>Code 1</h3>
<p>This can run fine and will print "2 4 3":</p>
<pre><code>while node:
print(node.val) # access the values of the node by node.val
node=node.next`
</code></pre>
<h3>Code 2:</h3>
<p>This gives me an error saying 'NoneType' object has no attribute 'val' while still printing "2"</p>
<pre><code>node = node.next
print(node.val)
</code></pre>
<p>I expect to see code 2 to print "2" and <em>not</em> giving me the error.</p>
<p>Note that code 1 and code 2 are run independently with</p>
<pre><code>node = ListNode{val: 2, next: ListNode{val: 4, next: ListNode{val: 3, next: None}}}
</code></pre>
<p>In fact, code 2 <strong>does print 2</strong>, it just prints 2 with the <code>Nonetype</code> error, which I want to avoid.</p>
|
[
{
"answer_id": 74632430,
"author": "zwol",
"author_id": 388520,
"author_profile": "https://Stackoverflow.com/users/388520",
"pm_score": 3,
"selected": true,
"text": "static inline static inline stdio.h stdio.h &printf &printf printf(\"%s %d %p\", string, integer, pointer);\n fprintf(stdout, \"%s %d %p\", string, integer, pointer);\n __builtin_va_start __mingw_vfprintf test.c:4:50: error: function ‘xprintf’ can never be inlined \n because it uses variable argument lists\n printf .c printf printf:\n mov QWORD PTR [rsp+8], rcx\n mov QWORD PTR [rsp+16], rdx\n mov QWORD PTR [rsp+24], r8\n mov QWORD PTR [rsp+32], r9\n push rbx\n push rsi\n push rdi\n sub rsp, 48\n mov rdi, rcx\n lea rsi, QWORD PTR f$[rsp+8]\n mov ecx, 1\n call __acrt_iob_func\n mov rbx, rax\n call __local_stdio_printf_options\n xor r9d, r9d\n mov QWORD PTR [rsp+32], rsi\n mov r8, rdi\n mov rdx, rbx\n mov rcx, QWORD PTR [rax]\n call __stdio_common_vfprintf\n add rsp, 48\n pop rdi\n pop rsi\n pop rbx\n ret 0\n /O2"
},
{
"answer_id": 74632769,
"author": "n. m.",
"author_id": 775806,
"author_profile": "https://Stackoverflow.com/users/775806",
"pm_score": 1,
"selected": false,
"text": "__mingw_ovr #define __mingw_ovr static __attribute__ ((__unused__)) __inline__ __cdecl\n printf"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74578957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13655702/"
] |
74,578,963
|
<p>Take this class:</p>
<pre><code>class Foo {
public:
using MyType = Foo;
MyType* m = nullptr; //ok
MyType* functor() { //ok
return nullptr;
}
MyType() = default; //error
~MyType() = default; //error
};
</code></pre>
<p>Why can you use alias names for members, but not for constructors or destructors?</p>
|
[
{
"answer_id": 74579020,
"author": "Remy Lebeau",
"author_id": 65863,
"author_profile": "https://Stackoverflow.com/users/65863",
"pm_score": 3,
"selected": true,
"text": "m functor()"
},
{
"answer_id": 74579090,
"author": "bitmask",
"author_id": 430766,
"author_profile": "https://Stackoverflow.com/users/430766",
"pm_score": 3,
"selected": false,
"text": "language-lawyer template <typename T> class C { C foo(); };\n C C C<T> foo(); C C C<T>"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74578963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19333949/"
] |
74,578,980
|
<p>I am trying to make a profile settings page where people can chane name email and password and only the password gets updated but all the rest remain the same. I cant understand why below i have the code
Note i use breeze</p>
<p>settings.blade.php</p>
<pre><code><x-app-layout>
<x-slot name="header">
<h2 class="font-semibold text-xl text-gray-800 leading-tight">
{{ __('Settings') }}
</h2>
</x-slot>
<div class="py-12">
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
<div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
<div class="p-6 bg-white border-b border-gray-200">
<!-- Personal Details heading -->
<div class="mb-4">
<h2 class="font-semibold text-xl text-gray-800 leading-tight">
{{ __('Personal Details') }}
</h2>
</div>
<!-- Show id with prefix-->
<div class="mb-4">
<x-label for="id" :value="__('ID')" />
<x-input id="id" class="block mt-1 w-full" type="text" name="id" :value="Auth::user()->id + 243254" disabled />
</div>
<form method="POST" action="{{ route('settings.update')}}">
@method('PUT')
@csrf
<div class="grid grid-cols-2 gap-6">
<div class="grid grid-rows-2 gap-6">
<div>
<x-label for="name" :value="__('Name')" />
<x-input id="name" class="block mt-1 w-full" type="text" name="name" value="{{ auth()->user()->name }}" autofocus />
</div>
<br />
<div>
<x-label for="email" :value="__('Email')" />
<x-input id="email" class="block mt-1 w-full" type="email" name="email" value="{{ auth()->user()->email }}" autofocus />
</div>
</div>
<br />
<div class="grid grid-rows-2 gap-6">
<div>
<x-label for="new_password" :value="__('New password')" />
<x-input id="new_password" class="block mt-1 w-full"
type="password"
name="password"
autocomplete="new-password" />
</div>
<br />
<div>
<x-label for="confirm_password" :value="__('Confirm password')" />
<x-input id="confirm_password" class="block mt-1 w-full"
type="password"
name="password_confirmation"
autocomplete="confirm-password" />
</div>
</div>
</div>
<div class="flex items-center justify-end mt-4">
<x-button class="ml-3">
{{ __('Update') }}
</x-button>
</div>
</form>
<!-- Address History heading -->
<div class="mt-4">
<h2 class="font-semibold text-xl text-gray-800 leading-tight">
{{ __('Address History') }}
</h2>
</div>
<br />
<form method="POST" action="#">
@csrf
<!-- Previous Addresses History Table using tr -->
<table>
<tr>
<th>Address</th>
<th>Postcode</th>
<th>City</th>
<th>Country</th>
<th>From</th>
<th>To</th>
</tr>
</table>
<br />
<!--Add heading to add new address-->
<h3 class="font-semibold text-xl text-gray-800 leading-tight">
{{ __('Add new address') }}
</h3>
<br />
<!-- New Address form-->
<div class="grid grid-cols-2 gap-6">
<div class="grid grid-rows-2 gap-6">
<div>
<x-label for="address" :value="__('Address')" />
<x-input id="address" class="block mt-1 w-full" type="text" name="address" value="{{ auth()->user()->address }}" autofocus />
</div>
<br />
<div>
<x-label for="city" :value="__('City')" />
<x-input id="city" class="block mt-1 w-full" type="text" name="city" value="{{ auth()->user()->city }}" autofocus />
</div>
</div>
<br />
<div class="grid grid-rows-2 gap-6">
<div>
<x-label for="state" :value="__('State')" />
<x-input id="state" class="block mt-1 w-full" type="text" name="state" value="{{ auth()->user()->state }}" autofocus />
</div>
<br />
<div>
<x-label for="zip" :value="__('Zip')" />
<x-input id="zip" class="block mt-1 w-full" type="text" name="zip" value="{{ auth()->user()->zip }}" autofocus />
</div>
</div><br />
<!-- add from to which day living in this address-->
<div class="grid grid-rows-2 gap-6">
<div>
<x-label for="from" :value="__('From')" />
<x-input id="from" class="block mt-1 w-full" type="date" name="from" value="{{ auth()->user()->from }}" autofocus />
</div>
<br />
<div>
<x-label for="to" :value="__('To')" />
<x-input id="to" class="block mt-1 w-full" type="date" name="to" value="{{ auth()->user()->to }}" autofocus />
</div>
</div>
<div class="flex items-center justify-end mt-4">
<x-button class="ml-3">
{{ __('Add Address') }}
</x-button>
</div>
</form>
</div>
</div>
</div>
</div>
</x-app-layout>
</code></pre>
<p>SettingsController.php</p>
<pre><code><?php
namespace App\Http\Controllers;
use App\Http\Requests\UpdateSettingsRequest;
use Illuminate\Http\Request;
class SettingsController extends Controller
{
public function update(UpdateSettingsRequest $request){
auth()->user()->update($request->only('name', 'email'));
if ($request->input('password')){
auth()->user()->update([
'password' => bcrypt($request->input('password'))
]);
}
return redirect()->route('settings')->with('message', 'Settings updated');
}
}
</code></pre>
<p>web.php</p>
<pre><code><?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::group(['middleware' => 'auth'], function(){
Route::get('/dashboard', function () {
return view('dashboard');
})->name('dashboard');
Route::view('settings', 'settings')->name('settings');
Route::view('creditcards', 'creditcards')->name('creditcards');
Route::view('loans', 'loans')->name('loans');
Route::put('settings', [\App\Http\Controllers\SettingsController::class, 'update'])
->name('settings.update');
});
require __DIR__.'/auth.php';
</code></pre>
<p>anyone knows why?</p>
<p>I tried to do ifs, to take out the values on the form and still</p>
|
[
{
"answer_id": 74579020,
"author": "Remy Lebeau",
"author_id": 65863,
"author_profile": "https://Stackoverflow.com/users/65863",
"pm_score": 3,
"selected": true,
"text": "m functor()"
},
{
"answer_id": 74579090,
"author": "bitmask",
"author_id": 430766,
"author_profile": "https://Stackoverflow.com/users/430766",
"pm_score": 3,
"selected": false,
"text": "language-lawyer template <typename T> class C { C foo(); };\n C C C<T> foo(); C C C<T>"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74578980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13067971/"
] |
74,578,995
|
<p>The goal is to start a Task, that loads some resources from the disk, on the UI thread, and then when it is finished to check if it threw an Exception without blocking the UI thread, and if it did, to rethrow the exception on the UI thread so the program ends and I get a stack trace.</p>
<p>I have been able to figure out that I can start a Task on a background thread without blocking, and awaiting the Task blocks the main thread.</p>
<p>I absolutely can not call await on the Task, because it would block the UI thread, but it appears I need to call it to access the Exception property after the Task has completed. I also can not use continueWith, because that also runs asynchronously, so propagating the exception from there will not work.</p>
<p>The docs I see all block to wait for the Exception.</p>
<p><a href="https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/exception-handling-task-parallel-library" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/exception-handling-task-parallel-library</a></p>
<p><a href="https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task?view=net-7.0#WaitingForOne" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task?view=net-7.0#WaitingForOne</a></p>
<p>For the Exception property of the Task, it would be nice if I could use something like RegisterPropertyChangedCallback, but that is not an available method in the Task object.</p>
<p>This is the code where I want to rethrow an Exception in the UI thread without blocking it</p>
<pre class="lang-cs prettyprint-override"><code> public TitlePage()
{
this.InitializeComponent();
string baseFolder = AppDomain.CurrentDomain.BaseDirectory;
string folder = baseFolder + @"Assets\";
Task task = DataSource.Load(folder);
// This is where I want to rethrow the Exception if it was thrown
// unless I can end the program and print the stack trace
// from the Task when it throws an Exception.
// Note that this is inside the constructor of a Page class;
// it is vital that the UI thread is not blocked.
}
</code></pre>
|
[
{
"answer_id": 74579028,
"author": "Gabriel Luci",
"author_id": 1202807,
"author_profile": "https://Stackoverflow.com/users/1202807",
"pm_score": 2,
"selected": false,
"text": "private TitlePage() {}\n\npublic static async Task<TitlePage> CreateTitlePage()\n{\n var titlePage = new TitlePage();\n titlePage.InitializeComponent();\n\n string baseFolder = AppDomain.CurrentDomain.BaseDirectory;\n string folder = baseFolder + @\"Assets\\\";\n Task task = DataSource.Load(folder);\n \n await task;\n return titlePage;\n}\n var newTitlePage = await TitlePage.CreateTitlePage();\n"
},
{
"answer_id": 74581651,
"author": "Mike Nakis",
"author_id": 773113,
"author_profile": "https://Stackoverflow.com/users/773113",
"pm_score": 0,
"selected": false,
"text": "Result Task Task.IsCompleted Task.IsFaulted Task.Exception Task<T>.Result Task Action<R> Dispatcher.BeginInvoke() using Sys = System;\nusing Wpf = System.Windows;\nusing WpfThreading = System.Windows.Threading;\n\nprivate void TaskCompletionAction( R result )\n{\n Assert( not-in-UI-thread );\n Sys.Action action = () => ReceiveResult( result );\n Wpf.Application.Current.Dispatcher.BeginInvoke(\n WpfThreading.DispatcherPriority.Background, \n action );\n}\n\nprivate void ReceiveResult( R result )\n{\n Assert( in-UI-thread );\n ...do something with the result...\n}\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74578995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13264143/"
] |
74,578,996
|
<p>Im starting to play around with the QUERY function on Google Sheets and I have 3 Columns with data from different users. Just as follows.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Users</th>
<th>Amount</th>
<th>Type</th>
</tr>
</thead>
<tbody>
<tr>
<td>User 1</td>
<td>4</td>
<td>Credit</td>
</tr>
<tr>
<td>User 2</td>
<td>5</td>
<td>Debit</td>
</tr>
<tr>
<td>User 3</td>
<td>2</td>
<td>Debit</td>
</tr>
<tr>
<td>User 2</td>
<td>3</td>
<td>Credit</td>
</tr>
<tr>
<td>User 3</td>
<td>4</td>
<td>Credit</td>
</tr>
<tr>
<td>User 1</td>
<td>6</td>
<td>Debit</td>
</tr>
</tbody>
</table>
</div>
<p>I'm trying to use one single QUERY to return a table with all my users grouped showing the total balance where all the credit add up minus all the debits</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Users</th>
<th>Balance</th>
</tr>
</thead>
<tbody>
<tr>
<td>User 1</td>
<td>-2</td>
</tr>
<tr>
<td>User 2</td>
<td>-2</td>
</tr>
<tr>
<td>User 3</td>
<td>-6</td>
</tr>
</tbody>
</table>
</div>
<p>At the time, I have</p>
<pre><code>SELECT Col1,
Sum(Col2) WHERE Col3 = 'CREDIT',
Sum(Col2) WHERE Col3 = 'DEBIT'
Group by Col1 ")
</code></pre>
<p>What of course, is not working. Any idea how to approach this?</p>
<p>I'm currently using one Query for each group then using and SUMIFS with the users to do the math, but definitely would love to know how to do it using one single query</p>
|
[
{
"answer_id": 74579028,
"author": "Gabriel Luci",
"author_id": 1202807,
"author_profile": "https://Stackoverflow.com/users/1202807",
"pm_score": 2,
"selected": false,
"text": "private TitlePage() {}\n\npublic static async Task<TitlePage> CreateTitlePage()\n{\n var titlePage = new TitlePage();\n titlePage.InitializeComponent();\n\n string baseFolder = AppDomain.CurrentDomain.BaseDirectory;\n string folder = baseFolder + @\"Assets\\\";\n Task task = DataSource.Load(folder);\n \n await task;\n return titlePage;\n}\n var newTitlePage = await TitlePage.CreateTitlePage();\n"
},
{
"answer_id": 74581651,
"author": "Mike Nakis",
"author_id": 773113,
"author_profile": "https://Stackoverflow.com/users/773113",
"pm_score": 0,
"selected": false,
"text": "Result Task Task.IsCompleted Task.IsFaulted Task.Exception Task<T>.Result Task Action<R> Dispatcher.BeginInvoke() using Sys = System;\nusing Wpf = System.Windows;\nusing WpfThreading = System.Windows.Threading;\n\nprivate void TaskCompletionAction( R result )\n{\n Assert( not-in-UI-thread );\n Sys.Action action = () => ReceiveResult( result );\n Wpf.Application.Current.Dispatcher.BeginInvoke(\n WpfThreading.DispatcherPriority.Background, \n action );\n}\n\nprivate void ReceiveResult( R result )\n{\n Assert( in-UI-thread );\n ...do something with the result...\n}\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74578996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20603396/"
] |
74,579,046
|
<p>I hope you all have a great day. I am coding my own personal website and I have a section called to contact me. The problem I have with this section is that I am trying to send my client email to my email and when I am trying to send their message to my server through Graphql I get this error</p>
<pre><code>[
{
"message": "Syntax Error: Unterminated string.",
"locations": [
{
"line": 3,
"column": 123
}
]
}
]
</code></pre>
<p>the request I sent to my server is</p>
<pre><code>'\n mutation{\n sendEmail(EmailInput: {name: "Test name", email: "Test@email.com",
subject: "this is test subject", message: "\n
this is the first line \nthis is the second line\nwhen I have multiple lines I have these problem\n
"}) {\n success\n message\n }\n }\n '
</code></pre>
<p>I don't know how to fix it I don't know why I get this error.
I used fetch to send my code backend :</p>
<pre><code>const emailMutationQuery = `
mutation{
sendEmail(EmailInput: {name: "${senderName.value}", email: "${senderEmail.value}", subject: "${senderSubject.value}", message: "
${senderMessage.value}
"}) {
success
message
}
}
`;
const result = await fetch("http://localhost:2882/graphql", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
query: emailMutationQuery,
}),
});
const convertedResult = await result.json();
</code></pre>
|
[
{
"answer_id": 74580242,
"author": "Farbod Shabani",
"author_id": 14712252,
"author_profile": "https://Stackoverflow.com/users/14712252",
"pm_score": 0,
"selected": false,
"text": "JSON.stringify() const emailMutationQuery = `\n mutation{\n sendEmail(EmailInput: {name: \"${senderName.value}\", email: \"${senderEmail.value}\", subject: \"${senderSubject.value}\", \n message:${JSON.stringify(senderMessage.value)}}) {\n success\n message\n }\n }\n `;\n"
},
{
"answer_id": 74582249,
"author": "David Maze",
"author_id": 10008173,
"author_profile": "https://Stackoverflow.com/users/10008173",
"pm_score": 1,
"selected": false,
"text": "const emailMutationQuery = `\nmutation SendEmail($emailInput: SendEmailInput!) {\n sendEmail(EmailInput: $emailInput) {\n success\n message\n }\n}\n`;\n const variables = {\n emailInput: {\n name: senderName.value,\n email: senderEmail.value,\n subject: senderSubject.value,\n message: senderMessage.value\n }\n};\n const result = await fetch(\"http://localhost:2882/graphql\", {\n ...,\n body: JSON.stringify({\n query: emailMutationQuery,\n variables: variables\n })\n});\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74579046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14712252/"
] |
74,579,048
|
<p>I am trying to display multiple checkbox values in a separate DIV to show the results of the checkboxes to the user. But I also want to remove the value if the user de-selects the checkbox. This is the code I have so far but can only display/hide one value at a time. For example, if I click checkboxes a, b, and c, it will show all values. But If I uncheck, they will hide. Thanks</p>
<pre><code><input onchange="selectArr(this)" type="checkbox" name="accessory" value="a"/>
<input onchange="selectArr(this)" type="checkbox" name="accessory" value="b"/>
<input onchange="selectArr(this)" type="checkbox" name="accessory" value="c"/>
<div id="acc"></div>
function selectAcc(cb) {
var x = cb.checked ? cb.value : '';
document.getElementById("acc").innerHTML = x;
}
</code></pre>
|
[
{
"answer_id": 74579080,
"author": "Samuel Schlemper",
"author_id": 19848531,
"author_profile": "https://Stackoverflow.com/users/19848531",
"pm_score": 0,
"selected": false,
"text": "var checked = []\n\nfunction selectAcc(cb) {\n if(cb.checked){\n checked.push(cb.value)\n } else {\n var index = checked.indexOf(cb.value)\n checked.splice(index, 1)\n}\n document.getElementById(\"acc\").innerHTML = checked.join(' ');\n}\n"
},
{
"answer_id": 74579113,
"author": "Tarmah",
"author_id": 6894272,
"author_profile": "https://Stackoverflow.com/users/6894272",
"pm_score": 0,
"selected": false,
"text": "function selectAcc(cb) {\n // get previous div value\n var previousValue = document.getElementById(\"acc\").getAttribute('value');\n var newValue = previousValue;\n //store the new clicked value\n var value = cb.value;\n // if the new value is checked and the value is not present in the div add it to the div string value\n if (cb.checked && !previousValue.includes(value)) newValue+=value ;\n // else remove the value from div string value\n else previousValue = newValue.replace(value, '');\n // update new value in div\n document.getElementById(\"acc\").innerHTML = newValue;\n }\n"
},
{
"answer_id": 74579180,
"author": "Nikkkshit",
"author_id": 11850259,
"author_profile": "https://Stackoverflow.com/users/11850259",
"pm_score": 2,
"selected": true,
"text": "// selecting input type checkboxes\nconst inputCheckBoxes = document.querySelectorAll(\"input[type=checkbox]\");\nconst main = document.querySelector(\"#main\");\n// function to print in main div\nconst printCheckedValue = (array) => {\n main.innerText = \"\";\n array.forEach(value => {\n main.innerText += value;\n })\n}\n// to store checkboxed values\nlet checkedValue = [];\n// looping through all inputcheckboxes and attching onchange event\nObject.values(inputCheckBoxes).forEach((inputCheckBoxe, index) => {\n inputCheckBoxe.onchange = (e) => {\n // checking if value is checkedbox or not\n if (checkedValue.includes(e.target.value)) {\n // if checkeboxed than filtering array\n checkedValue = checkedValue.filter(val => val != e.target.value)\n printCheckedValue(checkedValue);\n } else {\n checkedValue.push(e.target.value);\n printCheckedValue(checkedValue);\n }\n }\n}) <input type=\"checkbox\" name=\"accessory\" value=\"a\" />\n<input type=\"checkbox\" name=\"accessory\" value=\"b\" />\n<input type=\"checkbox\" name=\"accessory\" value=\"c\" />\n\n\n<div id=\"main\"></div>"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74579048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16513652/"
] |
74,579,088
|
<pre><code>print("test")
m = input("Name: ")
print(m)
</code></pre>
<p>I was getting ready to start programing. I opened cmd and ran my program and it opened a new cmd and printed out my code. Why is python opening a new cmd window to run my script unstead of using the cmd that was opened?</p>
<p>Also I recently updated python to python 3.10</p>
|
[
{
"answer_id": 74579080,
"author": "Samuel Schlemper",
"author_id": 19848531,
"author_profile": "https://Stackoverflow.com/users/19848531",
"pm_score": 0,
"selected": false,
"text": "var checked = []\n\nfunction selectAcc(cb) {\n if(cb.checked){\n checked.push(cb.value)\n } else {\n var index = checked.indexOf(cb.value)\n checked.splice(index, 1)\n}\n document.getElementById(\"acc\").innerHTML = checked.join(' ');\n}\n"
},
{
"answer_id": 74579113,
"author": "Tarmah",
"author_id": 6894272,
"author_profile": "https://Stackoverflow.com/users/6894272",
"pm_score": 0,
"selected": false,
"text": "function selectAcc(cb) {\n // get previous div value\n var previousValue = document.getElementById(\"acc\").getAttribute('value');\n var newValue = previousValue;\n //store the new clicked value\n var value = cb.value;\n // if the new value is checked and the value is not present in the div add it to the div string value\n if (cb.checked && !previousValue.includes(value)) newValue+=value ;\n // else remove the value from div string value\n else previousValue = newValue.replace(value, '');\n // update new value in div\n document.getElementById(\"acc\").innerHTML = newValue;\n }\n"
},
{
"answer_id": 74579180,
"author": "Nikkkshit",
"author_id": 11850259,
"author_profile": "https://Stackoverflow.com/users/11850259",
"pm_score": 2,
"selected": true,
"text": "// selecting input type checkboxes\nconst inputCheckBoxes = document.querySelectorAll(\"input[type=checkbox]\");\nconst main = document.querySelector(\"#main\");\n// function to print in main div\nconst printCheckedValue = (array) => {\n main.innerText = \"\";\n array.forEach(value => {\n main.innerText += value;\n })\n}\n// to store checkboxed values\nlet checkedValue = [];\n// looping through all inputcheckboxes and attching onchange event\nObject.values(inputCheckBoxes).forEach((inputCheckBoxe, index) => {\n inputCheckBoxe.onchange = (e) => {\n // checking if value is checkedbox or not\n if (checkedValue.includes(e.target.value)) {\n // if checkeboxed than filtering array\n checkedValue = checkedValue.filter(val => val != e.target.value)\n printCheckedValue(checkedValue);\n } else {\n checkedValue.push(e.target.value);\n printCheckedValue(checkedValue);\n }\n }\n}) <input type=\"checkbox\" name=\"accessory\" value=\"a\" />\n<input type=\"checkbox\" name=\"accessory\" value=\"b\" />\n<input type=\"checkbox\" name=\"accessory\" value=\"c\" />\n\n\n<div id=\"main\"></div>"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74579088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20551179/"
] |
74,579,119
|
<p>I have a list as follows:</p>
<pre><code>['1', '5', '6', '7', '10']
</code></pre>
<p>I want to find the missing element between two elements in the above list. For example, I want to get the missing elements between <code>'1'</code> and <code>'5'</code>, i.e. <code>'2'</code>, <code>'3'</code> and <code>'4'</code>. Another example, there are no elements between <code>'5'</code> and <code>'6'</code>, so it doesn't need to return anything.</p>
<p>Following the list above, I expect it to return a list like this:</p>
<pre><code>['2', '3', '4', '8', '9']
</code></pre>
<p>My code:</p>
<pre><code># Sort elements in a list
input_list.sort()
# Remove duplicates from a list
input_list = list(dict.fromkeys(input_list))
</code></pre>
<p>How to return the above list? I would appreciate any help. Thank you in advance!</p>
|
[
{
"answer_id": 74579139,
"author": "wim",
"author_id": 674039,
"author_profile": "https://Stackoverflow.com/users/674039",
"pm_score": 2,
"selected": false,
"text": "L = ['1', '5', '6', '7', '10']\nresult = []\nfor left, right in zip(L, L[1:]):\n left, right = int(left), int(right)\n result += map(str, range(left + 1, right))\n"
},
{
"answer_id": 74579140,
"author": "Dash",
"author_id": 11542834,
"author_profile": "https://Stackoverflow.com/users/11542834",
"pm_score": 2,
"selected": false,
"text": "range() itertools.pairwise() pairwise zip(arr, arr[1:]) import itertools\narr = ['1', '5', '6', '7', '10']\n\nnew_arr = []\n\nfor p, c in itertools.pairwise(arr):\n prev, curr = int(p), int(c)\n if (prev + 1) != curr:\n new_arr.extend([str(i) for i in range(prev + 1, curr)])\n"
},
{
"answer_id": 74579157,
"author": "Damzaky",
"author_id": 7552340,
"author_profile": "https://Stackoverflow.com/users/7552340",
"pm_score": 0,
"selected": false,
"text": "range() arr = ['1', '5', '6', '7', '10']\nans = []\n\nfor i in range(len(arr) - 1): ans += map(str, list(range(int(arr[i]) + 1, int(arr[i + 1]))))\n \nprint(ans)\n ['2', '3', '4', '8', '9']"
},
{
"answer_id": 74579162,
"author": "atru",
"author_id": 2763915,
"author_profile": "https://Stackoverflow.com/users/2763915",
"pm_score": 2,
"selected": false,
"text": "for input_list = ['1', '5', '6', '7', '10']\n\nmissing_list = []\n\nfor ind in range(0, len(input_list)-1):\n\n el_0 = int(input_list[ind])\n el_f = int(input_list[ind+1])\n\n for num in range(el_0 + 1, el_f):\n missing_list.append(str(num))\n enumerate"
},
{
"answer_id": 74579191,
"author": "OneMadGypsy",
"author_id": 10292330,
"author_profile": "https://Stackoverflow.com/users/10292330",
"pm_score": 3,
"selected": true,
"text": "range set #original data\ndata = ['1', '5', '6', '7', '10']\n\n#convert to list[int]\nL = list(map(int, data))\n\n#get a from/to count\nR = range(min(L), max(L)+1)\n\n#remove duplicates and convert back to list[str]\nout = list(map(str, set(R) ^ set(L)))\n\nprint(out)\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74579119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16124033/"
] |
74,579,137
|
<p>I have a large table something like this below. I want to filter the table by Office and Month. I was thinking to do this I would some how use .indexOf() twice. I tried to do this in different ways and did not figure it out.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Office</th>
<th>Name</th>
<th>Month</th>
<th>Sales</th>
</tr>
</thead>
<tbody>
<tr>
<td>1a</td>
<td>Abe D</td>
<td>Jan</td>
<td>10</td>
</tr>
<tr>
<td>1a</td>
<td>Abe D</td>
<td>Feb</td>
<td>13</td>
</tr>
<tr>
<td>1a</td>
<td>Abe D</td>
<td>Mar</td>
<td>11</td>
</tr>
<tr>
<td>1a</td>
<td>Abe D</td>
<td>Apr</td>
<td>12</td>
</tr>
<tr>
<td>1a</td>
<td>Jon R</td>
<td>Jan</td>
<td>9</td>
</tr>
<tr>
<td>1a</td>
<td>Jon R</td>
<td>Feb</td>
<td>12</td>
</tr>
<tr>
<td>1a</td>
<td>Jon R</td>
<td>Mar</td>
<td>9</td>
</tr>
<tr>
<td>1a</td>
<td>Jon R</td>
<td>Apr</td>
<td>13</td>
</tr>
<tr>
<td>2b</td>
<td>Eve C</td>
<td>Jan</td>
<td>13</td>
</tr>
<tr>
<td>2b</td>
<td>Eve C</td>
<td>Feb</td>
<td>14</td>
</tr>
<tr>
<td>2b</td>
<td>Eve C</td>
<td>Mar</td>
<td>13</td>
</tr>
<tr>
<td>2b</td>
<td>Eve C</td>
<td>Apr</td>
<td>15</td>
</tr>
</tbody>
</table>
</div>
<p>This is what I tried.</p>
<pre><code> let office = "1a";
let mth = "Jan";
$("#Table2 tbody tr").filter(function() {
let step1 = $(this).toggle($(this).text().indexOf(office) > -1);
$(step1).toggle($(step1).text().indexOf(mth) > -1);
});
</code></pre>
<p>The code does not yield what I want. Below is what I want the output to be.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Office</th>
<th>Name</th>
<th>Month</th>
<th>Sales</th>
</tr>
</thead>
<tbody>
<tr>
<td>1a</td>
<td>Abe D</td>
<td>Jan</td>
<td>10</td>
</tr>
<tr>
<td>1a</td>
<td>Jon R</td>
<td>Jan</td>
<td>9</td>
</tr>
</tbody>
</table>
</div>
<p>thank you</p>
|
[
{
"answer_id": 74579139,
"author": "wim",
"author_id": 674039,
"author_profile": "https://Stackoverflow.com/users/674039",
"pm_score": 2,
"selected": false,
"text": "L = ['1', '5', '6', '7', '10']\nresult = []\nfor left, right in zip(L, L[1:]):\n left, right = int(left), int(right)\n result += map(str, range(left + 1, right))\n"
},
{
"answer_id": 74579140,
"author": "Dash",
"author_id": 11542834,
"author_profile": "https://Stackoverflow.com/users/11542834",
"pm_score": 2,
"selected": false,
"text": "range() itertools.pairwise() pairwise zip(arr, arr[1:]) import itertools\narr = ['1', '5', '6', '7', '10']\n\nnew_arr = []\n\nfor p, c in itertools.pairwise(arr):\n prev, curr = int(p), int(c)\n if (prev + 1) != curr:\n new_arr.extend([str(i) for i in range(prev + 1, curr)])\n"
},
{
"answer_id": 74579157,
"author": "Damzaky",
"author_id": 7552340,
"author_profile": "https://Stackoverflow.com/users/7552340",
"pm_score": 0,
"selected": false,
"text": "range() arr = ['1', '5', '6', '7', '10']\nans = []\n\nfor i in range(len(arr) - 1): ans += map(str, list(range(int(arr[i]) + 1, int(arr[i + 1]))))\n \nprint(ans)\n ['2', '3', '4', '8', '9']"
},
{
"answer_id": 74579162,
"author": "atru",
"author_id": 2763915,
"author_profile": "https://Stackoverflow.com/users/2763915",
"pm_score": 2,
"selected": false,
"text": "for input_list = ['1', '5', '6', '7', '10']\n\nmissing_list = []\n\nfor ind in range(0, len(input_list)-1):\n\n el_0 = int(input_list[ind])\n el_f = int(input_list[ind+1])\n\n for num in range(el_0 + 1, el_f):\n missing_list.append(str(num))\n enumerate"
},
{
"answer_id": 74579191,
"author": "OneMadGypsy",
"author_id": 10292330,
"author_profile": "https://Stackoverflow.com/users/10292330",
"pm_score": 3,
"selected": true,
"text": "range set #original data\ndata = ['1', '5', '6', '7', '10']\n\n#convert to list[int]\nL = list(map(int, data))\n\n#get a from/to count\nR = range(min(L), max(L)+1)\n\n#remove duplicates and convert back to list[str]\nout = list(map(str, set(R) ^ set(L)))\n\nprint(out)\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74579137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5091720/"
] |
74,579,143
|
<p>I have two columns in Google Sheets, A,B with a long list of words. Something like this:</p>
<pre><code>A: Red, yellow, blue
C: Extra
</code></pre>
<p>
I also have an empty cell, D1, to type in. And E2 to show the result.</p>
<p>What I need is a formula that will return TRUE in E2 whenever any of the values from column A are found by themselves or combined with values from column C. However, if only a value from C is found or a word from outside the list it should return FALSE.</p>
<p>There can be one or more values from column A, separated by a " + " sign.</p>
<p>So for example, if I type some values in D1 his is the result I would expect:</p>
<ul>
<li>Red -> TRUE</li>
<li>Red + Yellow -> TRUE</li>
<li>Yellow + Extra -> TRUE</li>
<li>Extra -> FALSE</li>
<li>Blue + Red + Dog -> FALSE</li>
<li>Dog + Extra -> FALSE</li>
<li>Cat + Dog -> FALSE</li>
<li>Red + Yellow + Blue + Extra -> TRUE</li>
</ul>
<p>So to summarise, if the values are from:</p>
<pre><code>Column A (one or several values): TRUE
Column C: FALSE
Column A + COLUMN C (one or several values): TRUE
Any other combination or random words from outside of the list: FALSE
</code></pre>
<p>Any ideas on how to achieve this? I've been trying and trying but I am not there yet.
Thanks!</p>
|
[
{
"answer_id": 74579139,
"author": "wim",
"author_id": 674039,
"author_profile": "https://Stackoverflow.com/users/674039",
"pm_score": 2,
"selected": false,
"text": "L = ['1', '5', '6', '7', '10']\nresult = []\nfor left, right in zip(L, L[1:]):\n left, right = int(left), int(right)\n result += map(str, range(left + 1, right))\n"
},
{
"answer_id": 74579140,
"author": "Dash",
"author_id": 11542834,
"author_profile": "https://Stackoverflow.com/users/11542834",
"pm_score": 2,
"selected": false,
"text": "range() itertools.pairwise() pairwise zip(arr, arr[1:]) import itertools\narr = ['1', '5', '6', '7', '10']\n\nnew_arr = []\n\nfor p, c in itertools.pairwise(arr):\n prev, curr = int(p), int(c)\n if (prev + 1) != curr:\n new_arr.extend([str(i) for i in range(prev + 1, curr)])\n"
},
{
"answer_id": 74579157,
"author": "Damzaky",
"author_id": 7552340,
"author_profile": "https://Stackoverflow.com/users/7552340",
"pm_score": 0,
"selected": false,
"text": "range() arr = ['1', '5', '6', '7', '10']\nans = []\n\nfor i in range(len(arr) - 1): ans += map(str, list(range(int(arr[i]) + 1, int(arr[i + 1]))))\n \nprint(ans)\n ['2', '3', '4', '8', '9']"
},
{
"answer_id": 74579162,
"author": "atru",
"author_id": 2763915,
"author_profile": "https://Stackoverflow.com/users/2763915",
"pm_score": 2,
"selected": false,
"text": "for input_list = ['1', '5', '6', '7', '10']\n\nmissing_list = []\n\nfor ind in range(0, len(input_list)-1):\n\n el_0 = int(input_list[ind])\n el_f = int(input_list[ind+1])\n\n for num in range(el_0 + 1, el_f):\n missing_list.append(str(num))\n enumerate"
},
{
"answer_id": 74579191,
"author": "OneMadGypsy",
"author_id": 10292330,
"author_profile": "https://Stackoverflow.com/users/10292330",
"pm_score": 3,
"selected": true,
"text": "range set #original data\ndata = ['1', '5', '6', '7', '10']\n\n#convert to list[int]\nL = list(map(int, data))\n\n#get a from/to count\nR = range(min(L), max(L)+1)\n\n#remove duplicates and convert back to list[str]\nout = list(map(str, set(R) ^ set(L)))\n\nprint(out)\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74579143",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19899375/"
] |
74,579,151
|
<p>In the Next.js I'm working,you can get a post in the route <code>/posts/[id].tsx</code> ,I am using react-query to make the get request.
I get the postId with</p>
<blockquote>
<p>const {id}=router.query</p>
</blockquote>
<p>But everytime I enter the page it sends the request to the server with <code>undefined</code> ,and also, do you guys know how to disable the React property of sending twice the requests when we enter a page? I think it is a waste of processing (correct me if I'm wrong please)
Thank you for reading until here !!!</p>
|
[
{
"answer_id": 74579288,
"author": "Edtimer",
"author_id": 10017656,
"author_profile": "https://Stackoverflow.com/users/10017656",
"pm_score": 1,
"selected": false,
"text": "//[newsId].tsx\nimport {useRouter} from 'next/router\n\nfunction DetailPage(){\nconst router = useRouter();\n\n//gives us the value in url\n\nconsole.log(router.query.newsId;)\n\nreturn <h1>hello</h1>\n}\nexport default DetailPage\n"
},
{
"answer_id": 74579301,
"author": "Jay F.",
"author_id": 20504019,
"author_profile": "https://Stackoverflow.com/users/20504019",
"pm_score": 2,
"selected": false,
"text": "useEffect(() => {\n if (!id) return;\n console.log(id);\n}, [id]);\n"
},
{
"answer_id": 74583361,
"author": "TkDodo",
"author_id": 8405310,
"author_profile": "https://Stackoverflow.com/users/8405310",
"pm_score": 2,
"selected": false,
"text": "useRouter().query enabled const router = useRouter()\nconst { id } = router.query\n\nuseQuery({\n queryKey: ['my-query', id],\n queryFn: () => fetchMyQuery(id)\n enabled: router.isReady\n})\n Boolean(id) !!id enabled"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74579151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19739351/"
] |
74,579,152
|
<p>my url query string is <code>http://website.local/residences/?status=status2&type=apartments&price=null</code></p>
<p>When I echo $_GET['status'] from my page template I get 'status2', which is obviously correct.
But I try to get that value from my functions.php it returns false. I'm using ajax to load in more posts with the below function. It should be getting that status value with $_GET for the tax query.. No idea why it's returning false only in my functions.php.</p>
<p>Any ideas?</p>
<pre><code>function load_more_members($offset = 0, $post_type = 'project'){
$offset = 0;
$post_type = 'project';
$status_array = array();
$tax_arr = array(
'relation' => 'AND',
);
if(isset($_POST['offset'])) {
$offset = $_POST['offset'];
}
if(isset($_POST['post_type'])) {
$post_type = $_POST['post_type'];
}
if (isset($_GET['status']) && !empty($_GET['status']) && $_GET['status'] !== 'null') {
$status = $_GET['status'];
array_push($status_array, array(
'taxonomy' => 'status',
'field' => 'slug',
'terms' => $status,
));
}
if (!empty($status_array)) {
array_push($tax_arr, $status_array);
}
$args = array(
'post_type' => 'project',
'posts_per_page' => '4',
'offset' => $offset,
'order' => 'DESC',
'order_by' => 'date',
'tax_query' => $tax_arr
);
$the_query = new WP_Query( $args );
$posts_left = $offset + 4;
$found_posts = $the_query->found_posts;
if ( $the_query->have_posts() ) :
ob_start();
while ( $the_query->have_posts() ) : $the_query->the_post();
echo get_template_part('template-parts/latest', 'loop');
endwhile;
$output = ob_get_contents();
ob_end_clean();
endif;
echo json_encode(array(
'html' => $output,
'offset' => $posts_left,
'found_posts' => $found_posts
));
exit();
}
add_action('wp_ajax_nopriv_load_more_members', 'load_more_members');
add_action('wp_ajax_load_more_members', 'load_more_members');
</code></pre>
<pre><code> function load_more_posts(offset, post_type) {
$.ajax({
type: "POST",
url: WPURLS.ajax_url,
data: {
action: "load_more_members",
offset: offset,
post_type: post_type,
},
beforeSend: function (data) {
$(".load-more-" + post_type).addClass("loading");
},
success: function (response) {
var obj = JSON.parse(response);
$("." + post_type + "-repeat").append(obj.html);
},
error: function (error) {
console.log("est" + error);
},
});
}
$(".load-more-post").on("click tap touch", function (e) {
e.preventDefault();
var this_offset = $(this).attr("data-offset");
load_more_posts(this_offset, "post");
});
</code></pre>
|
[
{
"answer_id": 74579613,
"author": "Vijay Hardaha",
"author_id": 11848895,
"author_profile": "https://Stackoverflow.com/users/11848895",
"pm_score": 2,
"selected": false,
"text": "$_GET http://website.local/residences/?status=status2&type=apartments&price=null http://website.local/wp-admin/admin-ajax.php $_GET $_GET $_GET $_POST $_POST"
},
{
"answer_id": 74581231,
"author": "Krunal Bhimajiyani",
"author_id": 19587288,
"author_profile": "https://Stackoverflow.com/users/19587288",
"pm_score": 2,
"selected": true,
"text": "function getQueryString() {\n let string = [], hash;\n let hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');\n for (var i = 0; i < hashes.length; i++) {\n hash = hashes[i].split('=');\n string.push(hash[0]);\n string[hash[0]] = hash[1];\n }\n return string;\n}\n let status = getQueryString()[\"status\"]; data function load_more_posts(offset, post_type) {\n let status = getQueryString()[\"status\"];\n $.ajax({\n type: \"POST\",\n url: WPURLS.ajax_url,\n data: {\n action: \"load_more_members\",\n offset: offset,\n post_type: post_type,\n status: status\n },\n beforeSend: function (data) {\n $(\".load-more-\" + post_type).addClass(\"loading\");\n },\n success: function (response) {\n var obj = JSON.parse(response);\n $(\".\" + post_type + \"-repeat\").append(obj.html);\n },\n error: function (error) {\n console.log(\"est\" + error);\n },\n });\n}\n$(\".load-more-post\").on(\"click tap touch\", function (e) {\n e.preventDefault();\n var this_offset = $(this).attr(\"data-offset\");\n load_more_posts(this_offset, \"post\");\n});\n add_action('wp_ajax_nopriv_load_more_members', 'load_more_members');\nadd_action('wp_ajax_load_more_members', 'load_more_members');\n\nfunction load_more_members()\n{\n echo $_POST['status'];\n}\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74579152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8529928/"
] |
74,579,167
|
<p>I have a pandas dataframe. In column I have list. But, some rows NaN. I want to find length of each list, in case it is NaN, I want 0 as length.</p>
<pre><code>My_column
[1, 2]-> should return 2
[] -> should return 0
NaN -> should return 0
</code></pre>
<p>Any help?</p>
<p>Thank you.</p>
|
[
{
"answer_id": 74579204,
"author": "Marat",
"author_id": 271641,
"author_profile": "https://Stackoverflow.com/users/271641",
"pm_score": 2,
"selected": false,
"text": "df['column'].str.len().fillna(0).astype(int)\n"
},
{
"answer_id": 74581261,
"author": "ScottC",
"author_id": 20174226,
"author_profile": "https://Stackoverflow.com/users/20174226",
"pm_score": 1,
"selected": false,
"text": "output = [len(x) if isinstance(x, list) else 0 for x in df['column']]\n import pandas as pd\nimport numpy as np\n\ndf = pd.DataFrame({'column': [['a','b'], np.nan, []]})\n\noutput = [len(x) if isinstance(x, list) else 0 for x in df['column']]\n\nprint(output)\n [2, 0, 0]\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74579167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/626664/"
] |
74,579,269
|
<p>Edit:
I shall thank Magoo for the detailed answer.
I edited my batch file according to Magoo's answer.
Here is the new code:</p>
<pre><code>@echo off
mode 62,22
:Begin
choice /c 12345 /M "Insert a number (min. 1 - max. 5): "
set "CommandVar0=%errorlevel%"
choice /c 12345 /M "Please confirm the number you entered: "
set "CommandVarC=%errorlevel%"
if %CommandVarC% NEQ %CommandVar0% (
echo Insert a matching number between 1~5 for confirmation
goto Begin
)
if %CommandVar0% == 1 set /P CommandVar1=Insert ID:
if %CommandVar0% == 2 set /P CommandVar1=Insert ID: & set /P CommandVar2=Insert ID:
if %CommandVar0% == 3 set /P CommandVar1=Insert ID: & set /P CommandVar2=Insert ID: & set /P CommandVar3=Insert ID:
if %CommandVar0% == 4 set /P CommandVar1=Insert ID: & set /P CommandVar2=Insert ID: & set /P CommandVar3=Insert ID: & set /P CommandVar4=Insert ID:
if %CommandVar0% == 5 set /P CommandVar1=Insert ID: & set /P CommandVar2=Insert ID: & set /P CommandVar3=Insert ID: & set /P CommandVar4=Insert ID: & set /P CommandVar5=Insert ID:
:loop
start EXAMPLE.exe %CommandVar1%
if defined commandvar2 start EXAMPLE.exe %CommandVar2%
if defined commandvar3 start EXAMPLE.exe %CommandVar3%
if defined commandvar4 start EXAMPLE.exe %CommandVar4%
if defined commandvar5 start EXAMPLE.exe %CommandVar5%
rem wait 10 seconds
for /L %%y in (1,1,10) do (
timeout /t 1 > nul
tasklist /fi "imagename eq EXAMPLE.exe" |find ":" > nul
if NOT errorlevel 1 goto begin
)
taskkill /f /im EXAMPLE.exe
timeout /t 5
goto loop
</code></pre>
<p>The issue I'm having right now is that;</p>
<ol>
<li>Due to my lack of knowledge, I don't know how to expand this command:</li>
</ol>
<pre><code>set "commandvar1="
set "commandvar2="
set /P CommandVar1=Insert ID:
if not defined commandvar1 goto begin
if "%CommandVar0%"=="2" (
set /P CommandVar2=Insert ID:
if not defined commandvar2 goto begin
)
</code></pre>
<p>e.g. to set "commandvar5=" etc. So instead I'm still using my complicated command which does the job for now.</p>
<ol start="2">
<li>How can I add the normal timer to this command?</li>
</ol>
<pre><code>for /L %%y in (1,1,10) do (
timeout /t 1 > nul
tasklist /fi "imagename eq EXAMPLE.exe" |find ":" > nul
if NOT errorlevel 1 goto begin
)
</code></pre>
<p>I want a timer to actually display the countdown of the command being executed like the usual timeout /t command if possible.</p>
|
[
{
"answer_id": 74579677,
"author": "DSalomon",
"author_id": 10402876,
"author_profile": "https://Stackoverflow.com/users/10402876",
"pm_score": -1,
"selected": false,
"text": "start EXAMPLE.exe %CommandVar1% && start EXAMPLE.exe %CommandVar2% && tasklist /fi \"imagename eq EXAMPLE.exe\" |find \":\" > nul \n"
},
{
"answer_id": 74579772,
"author": "Magoo",
"author_id": 2128947,
"author_profile": "https://Stackoverflow.com/users/2128947",
"pm_score": 3,
"selected": true,
"text": "start EXAMPLE.exe %CommandVar1% & start EXAMPLE.exe %CommandVar2%\n start example.exe commandvar? response to \"Insert ID:\" tasklist : tasklist : find : errorlevel 1 tasklist INFO: No tasks are running which match the specified criteria. : errorlevel 0 if **either** task is running (errorlevel 1), say \"not found\" and go to Begin Begin begin CommandVar2 set set \"var=value\" \" set var=\"value\" set /p % set /p if %var1% == %var2% ... break me if break me == 2 ... me == if \"%var1%\" == \"%var2%\" ... break \" me choice choice /? choice /c 12 /M \"Insert a number (min. 1 - max. 2): \"\nset \"CommandVar0=%errorlevel%\"\nchoice /c 12 /M \"Please confirm the number you entered: \"\nset \"CommandVarC=%errorlevel%\"\n commandvar? 1 2 if %CommandVarC% NEQ %CommandVar0% (\n echo Insert a matching number between 1~2 for confirmation\n goto Begin\n) \n %errorlevel% set /a var=%errorlevel% set /a else... goto if %CommandVarC% GTR 2 (echo Maximum number is 2.\n goto Begin\n ) else (\n CommandVarC 1 2 if %CommandVar0% == 1 set /P CommandVar1=Insert ID: \nif %CommandVar0% == 2 set /P CommandVar1=Insert ID: & set /P CommandVar2=Insert ID: \n CommandVar1 CommandVar2 set set set \"commandvar1=\"\nset \"commandvar2=\"\nset /P CommandVar1=Insert ID: \nif not defined commandvar1 goto begin\nif %CommandVar0% == 2 set /P CommandVar2=Insert ID: \n commandvar0 == commandvar2 if \"%CommandVar0%\"==\"2\" (\n set /P CommandVar2=Insert ID: \n if not defined commandvar2 goto begin\n)\n choice /c 12 /M \"Insert a number (min. 1 - max. 2): \"\nset \"CommandVar0=%errorlevel%\"\nchoice /c 12 /M \"Please confirm the number you entered: \"\nset \"CommandVarC=%errorlevel%\"\n\nif %CommandVarC% NEQ %CommandVar0% (\n echo Insert a matching number between 1~2 for confirmation\n goto Begin\n) \n\nset \"commandvar1=\"\nset \"commandvar2=\"\nset /P CommandVar1=Insert ID: \nif not defined commandvar1 goto begin\nif \"%CommandVar0%\"==\"2\" (\n set /P CommandVar2=Insert ID: \n if not defined commandvar2 goto begin\n)\n start EXAMPLE.exe %CommandVar1%\nrem only start a second instance if commandvar2 has been specified\nif defined commandvar2 start EXAMPLE.exe %CommandVar2%\nrem wait a sec...or 10\nfor /L %%y in (1,1,10) do (\n timeout /t 1 >nul\n tasklist /fi \"imagename eq EXAMPLE.exe\" |find \":\" > nul\n if NOT errorlevel 1 goto begin\n)\nrem kill tasks still running\ntaskkill /f /im EXAMPLE.exe\ntimeout /t 5 \ngoto begin\n for /L for /? %%y tasklist : errorlevel 0 IF ERRORLEVEL n errorlevel IF ERRORLEVEL 0 IF NOT ERRORLEVEL 1 begin for /L taskkill 12 choice 123456789 for /L %%e in (1,1,9) do set \"commandvar%%e=\"\n set \"commandvar1=\" set \"commandvar2=\" commandvar1..9 for /L %%e in (1,1,9) do (\n set /P CommandVar%%e=\"Insert ID for instance %%e: \"\n if not defined commandvar%%e (\n if %%e==1 goto begin\n goto startprocs\n )\n)\n:startprocs\nfor /L %%e in (1,1,9) do if defined commandvar%%e call start \"Instance %%e\" u:\\dummy.bat %%commandvar%%e%%\n set/p goto exit cmd exit /b cmd for /L start Start start call %%e 2 call start \"Instance 2\" u:\\dummy.bat %%commandvar%%e%% %%commandvar%%e%% %commandvar2% % % %%e 2 metavariable CALL start \"Instance 2\" u:\\dummy.bat %commandvar2% commandvar2 commandvaar 9 Insert ID for instance ??: "
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74579269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12261902/"
] |
74,579,272
|
<p>Below is the code that I want to replicate without using break
///</p>
<pre><code>while True:
choice = input("Is it time to choose(Y/N)? ")
if choice.upper() == "N":
break
idx = random.randint(0, len(contents))
fnd = False
for i in range(3):
for j in range(3):
if table[i][j] == contents[idx]:
table[i][j] = "SEEN"
fnd = True
break
if fnd:
break
won = check_win(table)
print_table(table)
if won:
print("The game has been won!!")
break
</code></pre>
<p>Can't figure out, already tried using variables but can't make it work</p>
|
[
{
"answer_id": 74579677,
"author": "DSalomon",
"author_id": 10402876,
"author_profile": "https://Stackoverflow.com/users/10402876",
"pm_score": -1,
"selected": false,
"text": "start EXAMPLE.exe %CommandVar1% && start EXAMPLE.exe %CommandVar2% && tasklist /fi \"imagename eq EXAMPLE.exe\" |find \":\" > nul \n"
},
{
"answer_id": 74579772,
"author": "Magoo",
"author_id": 2128947,
"author_profile": "https://Stackoverflow.com/users/2128947",
"pm_score": 3,
"selected": true,
"text": "start EXAMPLE.exe %CommandVar1% & start EXAMPLE.exe %CommandVar2%\n start example.exe commandvar? response to \"Insert ID:\" tasklist : tasklist : find : errorlevel 1 tasklist INFO: No tasks are running which match the specified criteria. : errorlevel 0 if **either** task is running (errorlevel 1), say \"not found\" and go to Begin Begin begin CommandVar2 set set \"var=value\" \" set var=\"value\" set /p % set /p if %var1% == %var2% ... break me if break me == 2 ... me == if \"%var1%\" == \"%var2%\" ... break \" me choice choice /? choice /c 12 /M \"Insert a number (min. 1 - max. 2): \"\nset \"CommandVar0=%errorlevel%\"\nchoice /c 12 /M \"Please confirm the number you entered: \"\nset \"CommandVarC=%errorlevel%\"\n commandvar? 1 2 if %CommandVarC% NEQ %CommandVar0% (\n echo Insert a matching number between 1~2 for confirmation\n goto Begin\n) \n %errorlevel% set /a var=%errorlevel% set /a else... goto if %CommandVarC% GTR 2 (echo Maximum number is 2.\n goto Begin\n ) else (\n CommandVarC 1 2 if %CommandVar0% == 1 set /P CommandVar1=Insert ID: \nif %CommandVar0% == 2 set /P CommandVar1=Insert ID: & set /P CommandVar2=Insert ID: \n CommandVar1 CommandVar2 set set set \"commandvar1=\"\nset \"commandvar2=\"\nset /P CommandVar1=Insert ID: \nif not defined commandvar1 goto begin\nif %CommandVar0% == 2 set /P CommandVar2=Insert ID: \n commandvar0 == commandvar2 if \"%CommandVar0%\"==\"2\" (\n set /P CommandVar2=Insert ID: \n if not defined commandvar2 goto begin\n)\n choice /c 12 /M \"Insert a number (min. 1 - max. 2): \"\nset \"CommandVar0=%errorlevel%\"\nchoice /c 12 /M \"Please confirm the number you entered: \"\nset \"CommandVarC=%errorlevel%\"\n\nif %CommandVarC% NEQ %CommandVar0% (\n echo Insert a matching number between 1~2 for confirmation\n goto Begin\n) \n\nset \"commandvar1=\"\nset \"commandvar2=\"\nset /P CommandVar1=Insert ID: \nif not defined commandvar1 goto begin\nif \"%CommandVar0%\"==\"2\" (\n set /P CommandVar2=Insert ID: \n if not defined commandvar2 goto begin\n)\n start EXAMPLE.exe %CommandVar1%\nrem only start a second instance if commandvar2 has been specified\nif defined commandvar2 start EXAMPLE.exe %CommandVar2%\nrem wait a sec...or 10\nfor /L %%y in (1,1,10) do (\n timeout /t 1 >nul\n tasklist /fi \"imagename eq EXAMPLE.exe\" |find \":\" > nul\n if NOT errorlevel 1 goto begin\n)\nrem kill tasks still running\ntaskkill /f /im EXAMPLE.exe\ntimeout /t 5 \ngoto begin\n for /L for /? %%y tasklist : errorlevel 0 IF ERRORLEVEL n errorlevel IF ERRORLEVEL 0 IF NOT ERRORLEVEL 1 begin for /L taskkill 12 choice 123456789 for /L %%e in (1,1,9) do set \"commandvar%%e=\"\n set \"commandvar1=\" set \"commandvar2=\" commandvar1..9 for /L %%e in (1,1,9) do (\n set /P CommandVar%%e=\"Insert ID for instance %%e: \"\n if not defined commandvar%%e (\n if %%e==1 goto begin\n goto startprocs\n )\n)\n:startprocs\nfor /L %%e in (1,1,9) do if defined commandvar%%e call start \"Instance %%e\" u:\\dummy.bat %%commandvar%%e%%\n set/p goto exit cmd exit /b cmd for /L start Start start call %%e 2 call start \"Instance 2\" u:\\dummy.bat %%commandvar%%e%% %%commandvar%%e%% %commandvar2% % % %%e 2 metavariable CALL start \"Instance 2\" u:\\dummy.bat %commandvar2% commandvar2 commandvaar 9 Insert ID for instance ??: "
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74579272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20603684/"
] |
74,579,275
|
<p>I cannot create the table named <code>signal</code>, it shows me error like below:</p>
<p><img src="https://i.stack.imgur.com/CX1Fp.png" alt="MySQL CREATE TABLE signal error 1064" /></p>
<p>I tried with other name it works, when the table name is <code>signal</code> it does not work.</p>
<p>I also ensured that there is no table named <code>signal</code> in my database.</p>
|
[
{
"answer_id": 74579322,
"author": "akseli",
"author_id": 482270,
"author_profile": "https://Stackoverflow.com/users/482270",
"pm_score": 0,
"selected": false,
"text": "signal signal"
},
{
"answer_id": 74580043,
"author": "Jonas Metzler",
"author_id": 18794826,
"author_profile": "https://Stackoverflow.com/users/18794826",
"pm_score": 2,
"selected": false,
"text": "CREATE TABLE `signal` (id int);\n SELECT id FROM signal;\n SELECT id FROM `signal`;\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74579275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16183593/"
] |
74,579,330
|
<p>I tried to make the simplest example of this here. When you check the box, the parent text Text #1 alternates back and forth from "true" to "false" while the child text Text #2 never changes. I want Text #2 to change just like Text #1 does.</p>
<pre><code>function Parent(props) {
const [state1, setState1] = useState(true);
const [currentView, setCurrentView] = useState(<Child checkHandler={checkHandler} state1={state1} />);
function checkHandler(event) {
setState1(event.target.checked);
}
return (
<div>
Text #1: {state1 ? "true" : "false"}
{currentView}
</div>
);
}
export default Parent;
function Child({
state1,
checkHandler
}) {
return (
<div>
Text #2: {state1 ? "true" : "false"}
<form>
<input type="checkbox" id="checkbox" onChange={checkHandler} />
<label for="checkbox">Check</label>
</form>
</div>
);
}
export default Child;
</code></pre>
<p>I've searched for similar answers, but I can't find anywhere a simple explanation on how to do what I think would be a very fundamental thing to do in React Redux.</p>
|
[
{
"answer_id": 74579322,
"author": "akseli",
"author_id": 482270,
"author_profile": "https://Stackoverflow.com/users/482270",
"pm_score": 0,
"selected": false,
"text": "signal signal"
},
{
"answer_id": 74580043,
"author": "Jonas Metzler",
"author_id": 18794826,
"author_profile": "https://Stackoverflow.com/users/18794826",
"pm_score": 2,
"selected": false,
"text": "CREATE TABLE `signal` (id int);\n SELECT id FROM signal;\n SELECT id FROM `signal`;\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74579330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5732910/"
] |
74,579,355
|
<p>I need a SVG image something like the image bellow (open door architectural symbol ) that will be resized proportional but the height in green and width in red will stay same.The colors and sizes are just for illustrative purpose.</p>
<p><a href="https://i.stack.imgur.com/8s9i6.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8s9i6.jpg" alt="preview svg" /></a></p>
<p>I made try with this code bellow but don't know how to make the height in green and width in red to be fixed when image is resized.</p>
<p>If you can help thank you very much on your time!</p>
<pre><code><svg id="imgsvg" width="400px" height="400px" version="1.0" state='normal'
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<defs>
<!-- The left head -->
<svg class="head input-source" id="left"
height="100%"
width="100%"
viewBox="0 0 10 200"
preserveAspectRatio="xMinYMax"
>
<rect
width="100%"
height="100%"
stroke='black'
stroke-width='0'
fill="#000"
/>
</svg>
<!-- The bottom head -->
<svg class="head input-source" id="bottom"
height="100%"
width='100%'
viewBox="0 0 200 20"
preserveAspectRatio="xMinYMax"
>
<rect
width="100%"
height="100%"
stroke='gray'
stroke-width='0'
fill="gray"
/>
</svg>
</defs>
<!-- The Quad -->
<svg class='head input-source' id="quad"
height="100%"
width='100%'
viewBox="0 0 200 200"
preserveAspectRatio="xMinYmax"
>
<path
d="M0,1 Q199,0 199,199"
fill="#ffffff"
fill-opacity="0"
stroke="#000000"
stroke-width="2"
/>
</svg>
<use xlink:href='#left'/>
<use xlink:href='#bottom'/>
</svg>
</code></pre>
|
[
{
"answer_id": 74579322,
"author": "akseli",
"author_id": 482270,
"author_profile": "https://Stackoverflow.com/users/482270",
"pm_score": 0,
"selected": false,
"text": "signal signal"
},
{
"answer_id": 74580043,
"author": "Jonas Metzler",
"author_id": 18794826,
"author_profile": "https://Stackoverflow.com/users/18794826",
"pm_score": 2,
"selected": false,
"text": "CREATE TABLE `signal` (id int);\n SELECT id FROM signal;\n SELECT id FROM `signal`;\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74579355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1740652/"
] |
74,579,373
|
<p>i'm reading the source code of sentinel, i find when the map need adding a entry, it create a new hashmap replacing the old rather than using map.put directly. like this:</p>
<pre class="lang-java prettyprint-override"><code>public class NodeSelectorSlot extends AbstractLinkedProcessorSlot<Object> {
private volatile Map<String, DefaultNode> map = new HashMap<String, DefaultNode>(10);
@Override
public void entry(Context context, ResourceWrapper resourceWrapper, Object obj, int count, boolean prioritized, Object... args)
throws Throwable {
DefaultNode node = map.get(context.getName());
if (node == null) {
synchronized (this) {
node = map.get(context.getName());
if (node == null) {
node = new DefaultNode(resourceWrapper, null);
// create a new hashmap
HashMap<String, DefaultNode> cacheMap = new HashMap<String, DefaultNode>(map.size());
cacheMap.putAll(map);
cacheMap.put(context.getName(), node);
map = cacheMap;
((DefaultNode) context.getLastNode()).addChild(node);
}
}
}
context.setCurNode(node);
fireEntry(context, resourceWrapper, node, count, prioritized, args);
}
...
}
</code></pre>
<p>what's the different between them?</p>
|
[
{
"answer_id": 74579322,
"author": "akseli",
"author_id": 482270,
"author_profile": "https://Stackoverflow.com/users/482270",
"pm_score": 0,
"selected": false,
"text": "signal signal"
},
{
"answer_id": 74580043,
"author": "Jonas Metzler",
"author_id": 18794826,
"author_profile": "https://Stackoverflow.com/users/18794826",
"pm_score": 2,
"selected": false,
"text": "CREATE TABLE `signal` (id int);\n SELECT id FROM signal;\n SELECT id FROM `signal`;\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74579373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16321604/"
] |
74,579,427
|
<p>This is a stupid question, but I really didn't make it...</p>
<p>Here's what you get with "archive/zip", I don't clear the order is unchanged.</p>
<pre class="lang-js prettyprint-override"><code>[
"a/",
"e.txt",
"a/b/",
"a/b/c/",
"a/b/c/d.txt"
]
</code></pre>
<p>I want:</p>
<pre class="lang-js prettyprint-override"><code>[{
"path": "a/",
"isFolder": true,
"childs":[{
"path": "a/b/",
"isFolder": true,
"childs":[{
"path": "a/b/c/",
"isFolder": true,
"childs":[{
"path": "a/b/c/d.txt",
"isFolder": false
}]
}]
}]
},{
"path": "e.txt",
"isFolder": false
}]
</code></pre>
<p>How should it be converted?</p>
|
[
{
"answer_id": 74579322,
"author": "akseli",
"author_id": 482270,
"author_profile": "https://Stackoverflow.com/users/482270",
"pm_score": 0,
"selected": false,
"text": "signal signal"
},
{
"answer_id": 74580043,
"author": "Jonas Metzler",
"author_id": 18794826,
"author_profile": "https://Stackoverflow.com/users/18794826",
"pm_score": 2,
"selected": false,
"text": "CREATE TABLE `signal` (id int);\n SELECT id FROM signal;\n SELECT id FROM `signal`;\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74579427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9266268/"
] |
74,579,455
|
<p>I was wondering if with <em>grep</em> and regex we can do something in the spirit of the following example:</p>
<p><strong>Original text</strong>:</p>
<pre><code>name_1_extratext
name_2_extratext
</code></pre>
<p><strong>Target</strong>:</p>
<pre><code>name_extratext_1
name_extratext_2
</code></pre>
<p>I am particularly interested in doing this within <em>Vim</em>. Thanks</p>
|
[
{
"answer_id": 74579597,
"author": "Bohemian",
"author_id": 256196,
"author_profile": "https://Stackoverflow.com/users/256196",
"pm_score": 0,
"selected": false,
"text": "grep sed echo \"name_1_extratext\" | sed -E 's/_([^_]+)_(.*)/_\\2_\\1/'\n"
},
{
"answer_id": 74580725,
"author": "romainl",
"author_id": 546861,
"author_profile": "https://Stackoverflow.com/users/546861",
"pm_score": 3,
"selected": true,
"text": "grep grep :%s/\\(.*\\)\\(_\\d\\+\\)\\(.*\\)/\\1\\3\\2\n :%s/_\\([^_]\\+\\)_\\(.*\\)/_\\2_\\1/\n :s :help 10.2 :help :s % :help 10.3 :help :range :help pattern"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74579455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4207869/"
] |
74,579,472
|
<p>I want to know how to create a rating component with filled or unfilled stars based on the information in my json files. I already have the rating number on my json file, I must put it on my rating component.</p>
<pre><code>import React, { useRef, useState } from "react";
import { ReactComponent as Star } from "../assets/star.png";
import logements from "../data/logements.json";
import "../style/Stars.css";
function Stars(rating, color) {
const rating = useRef();
const [starfilled, setStarFilled] = useState(0);
const [starUnfilled, setStarUnfilled] = useState(0);
function ratingStars() {
if (rating.length >= 0) {
setStarFilled(starfilled++);
} else {
setStarUnfilled(starUnfilled(0));
}
}
return (
<div>
<img src={Star} className="starStyle" alt='star'></img>
</div>
);
}
export default Stars;
</code></pre>
|
[
{
"answer_id": 74579507,
"author": "Opay Hero",
"author_id": 10766263,
"author_profile": "https://Stackoverflow.com/users/10766263",
"pm_score": 1,
"selected": false,
"text": "disabled=true --rating=1"
},
{
"answer_id": 74579527,
"author": "ray",
"author_id": 636077,
"author_profile": "https://Stackoverflow.com/users/636077",
"pm_score": 2,
"selected": false,
"text": ".demo {\n display: inline-flex;\n flex-direction: column;\n}\n\n.stars {\n position: relative;\n display: inline-block;\n}\n\n.bg {\n opacity: 0.35;\n filter: grayscale(1);\n}\n\n.stars::after {\n content: '⭐⭐⭐⭐⭐';\n position: absolute;\n top: 0;\n left: 0;\n width: calc(100% * var(--rating));\n overflow: hidden;\n} <div class=\"demo\">\n <div class=\"stars\" style=\"--rating: 0.1\">\n <div class=\"bg\">⭐⭐⭐⭐⭐</div>\n </div>\n\n <div class=\"stars\" style=\"--rating: 0.2\">\n <div class=\"bg\">⭐⭐⭐⭐⭐</div>\n </div>\n\n <div class=\"stars\" style=\"--rating: 0.4\">\n <div class=\"bg\">⭐⭐⭐⭐⭐</div>\n </div>\n\n <div class=\"stars\" style=\"--rating: 0.5\">\n <div class=\"bg\">⭐⭐⭐⭐⭐</div>\n </div>\n\n <div class=\"stars\" style=\"--rating: 0.6\">\n <div class=\"bg\">⭐⭐⭐⭐⭐</div>\n </div>\n\n <div class=\"stars\" style=\"--rating: 0.8\">\n <div class=\"bg\">⭐⭐⭐⭐⭐</div>\n </div>\n\n <div class=\"stars\" style=\"--rating: 1\">\n <div class=\"bg\">⭐⭐⭐⭐⭐</div>\n </div>\n</div>"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74579472",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18944378/"
] |
74,579,491
|
<p>I am doing time series analysis in R using the forecast package. The forecast::autoplot() creates a ggplot object.</p>
<p>I have two questions about plotting decomposed series:</p>
<ol>
<li>How do I place text in the trend panel (next to the vertical red line). Using ggplot or other packages?</li>
<li>How can I rename the "data" panel to be capitalized as "Data"?</li>
</ol>
<p>Here is my code:</p>
<pre><code>library(forecast)
# Load in AirPassengers time series
data("AirPassengers")
# Decomopose time series
decomposed_ts <- decompose(AirPassengers)
# Plot decomposed time series
forecast::autoplot(decomposed_ts) + geom_vline(xintercept = 1954, colour = "red")
</code></pre>
<p><a href="https://i.stack.imgur.com/ovd8b.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ovd8b.png" alt="Screenshot of two questions" /></a></p>
<p>For Q1, I tried to use annotate() but it places the same text labels on each facet, whereas I only want one label on only the trend panel (see screenshot). I also tried to use the ggtext package, but could not get it to work. I couldn't figure out what the faceted variable is because forecast::autoplot() automatically created the faceting.</p>
<p>For Q2. I saved the plot as a variable i.e. myPlot <- forecast::autoplot(decomposed_ts) + geom_vline(xintercept = 1954, colour = "red"). I then tried myPlot$ looking for where the "data" facet is named.</p>
|
[
{
"answer_id": 74579845,
"author": "AndS.",
"author_id": 9778513,
"author_profile": "https://Stackoverflow.com/users/9778513",
"pm_score": 2,
"selected": false,
"text": "library(tidyverse)\nlibrary(forecast) \n\n\nmy_new_autoplot <- function(decomp, \n facet_labels = c(\"data\", \"trend\", \"seasonal\", \"remainder\")){\n list(\ntibble(Time = time(decomp$x),\n val = decomp$x,\n type = facet_labels[1]),\n\ntibble(Time = time(decomp$trend),\n val = decomp$trend,\n type = facet_labels[2]),\n\ntibble(Time = time(decomp$seasonal),\n val = decomp$seasonal,\n type = facet_labels[3]),\n\ntibble(Time = time(decomp$random),\n val = decomp$random,\n type = facet_labels[4]) |>\n mutate(t1 = pmax(0, val),\n t2 = pmin(val, 0),\n val = 0)\n) |>\n bind_rows() |>\n mutate(type = factor(type, levels = facet_labels)) |>\n ggplot(aes(Time, val))+\n geom_path()+\n geom_errorbar(aes(ymin = t2, ymax = t1))+\n facet_wrap(~type, ncol = 1, scales = \"free_y\", strip.position = \"left\")+\n labs(y = \"\")\n}\n\nmy_new_autoplot(decomposed_ts) + \n geom_vline(xintercept = 1954, colour = \"red\")\n my_new_autoplot(decomposed_ts, \n facet_labels = c(\"my_data!\", \"trend..\", \"~seasonal~\", \"rEmainDeR\")) + \n geom_vline(xintercept = 1954, colour = \"red\")\n my_plot <- my_new_autoplot(decomposed_ts, \n facet_labels = c(\"my_data!\", \"trend..\", \"~seasonal~\", \"rEmainDeR\")) + \n geom_vline(xintercept = 1954, colour = \"red\")\n\n\nadd_text <- function(plot, facet, text, x, y, ...){\n text_data <- tibble(Time = x, val = y, type = facet, label = text) |>\n mutate(type = factor(type, levels = levels(plot$data$type)))\n \n plot+\n geom_text(data = text_data, aes(label = label), ...)\n}\n\nadd_text(plot = my_plot, \n facet = \"rEmainDeR\", \n text = \"This is red\", \n x = 1955, \n y = 40,\n color = \"red\")\n"
},
{
"answer_id": 74580406,
"author": "Isaiah",
"author_id": 1738003,
"author_profile": "https://Stackoverflow.com/users/1738003",
"pm_score": 2,
"selected": true,
"text": "annotation <- data.frame(\n x = c(1950),\n y = c(250),\n parts = c(\"trend\"),\n label = c(\"label 1\")\n)\n\nforecast::autoplot(decomposed_ts) +\n geom_vline(xintercept = 1954, colour = \"red\") +\n geom_text(data = annotation, aes(x = x, y = y, label = label)) \n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74579491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6390497/"
] |
74,579,506
|
<p>This is the program to find mean, median, and mode of element in array and then make histogram from it,</p>
<p>but the problem i have is only at the star count and print the star</p>
<pre class="lang-c prettyprint-override"><code>#include<stdio.h>
int main()
{
int sample[50] = {4,3,5,5,1,5,5,5,4,3,5,3,3,5,5,5,2,5,5,5,5,4,3,5,5,2,5,2,5,4,3,5,3,3,5,5,5,5,5,5,3,5,4,3,5,3,3,5,5,5,};
int i;
int j;
int f1;
int f2;
int f3;
int f4;
int f5;
int temp;
int sum = 0;
int count = 0;
int median;
float mean;
for(i = 0; i < count; i++)
{
if(sample[i] == 1)
{
f1++;
}
else if(sample[i] == 2)
{
f2++;
}
else if(sample[i] == 3)
{
f3++;
}
else if(sample[i] == 4)
{
f4++;
}
else if(sample[i] == 5)
{
f5++;
}
}
for(i = 0; i < 5; i++)
{
printf("\t%d\t", i + 1);
if(i == 0)
{
printf(" %d\t", f1);
for(j = 0; j < f1; j++)
{
printf("*");
}
}
else if(i == 1)
{
printf(" %d\t", f2);
for(j = 0; j < f2; j++)
{
printf("*");
}
}
else if(i == 2)
{
printf(" %d\t", f3);
for(j = 0; j < f3; j++)
{
printf("*");
}
}
else if(i == 3)
{
printf(" %d\t", f4);
for(j = 0; j < f4; j++)
{
printf("*");
}
}
else if(i == 4)
{
printf(" %d\t", f5);
for(j = 0; j < f5; j++);
{
printf("*");
}
}
printf("\n");
}
return 0;
}
</code></pre>
<p><strong><a href="https://i.stack.imgur.com/EcDb9.png" rel="nofollow noreferrer">The output should be like this</a></strong></p>
<p>but</p>
<p><strong><a href="https://i.stack.imgur.com/JAVa7.png" rel="nofollow noreferrer">My output right now is this</a></strong></p>
<p>it seems the loop happened because the frequency of number 4 is 4205314, so the star looped until that number, but i can't find why the frequency goes that high</p>
|
[
{
"answer_id": 74579745,
"author": "qbizzle68",
"author_id": 18984369,
"author_profile": "https://Stackoverflow.com/users/18984369",
"pm_score": 1,
"selected": false,
"text": "int f1 = 0, f2 = 0, f3 = 0, f4 = 0, f5 = 0;\n"
},
{
"answer_id": 74579785,
"author": "abelenky",
"author_id": 34824,
"author_profile": "https://Stackoverflow.com/users/34824",
"pm_score": 2,
"selected": false,
"text": "#include <stdio.h>\n\nint main(void) {\n static const int sample[50] = {4,3,5,5,1,5,5,5,4,3,5,3,3,5,5,5,2,5,5,5,5,4,3,5,5,2,5,2,5,4,3,5,3,3,5,5,5,5,5,5,3,5,4,3,5,3,3,5,5,5,};\n int count = sizeof(sample)/sizeof(*sample); \n int histo[5] = {};\n for(int i=0; i<count; ++i)\n {\n histo[sample[i]-1]++;\n }\n \n char stars[count];\n ((char*)memset(stars, '*', count))[count-1] = '\\0';\n \n printf(\"%-20s%-20s%-20s\\n\", \"Response\", \"Frequency\", \"Histogram\");\n for(int i=0; i<5; ++i)\n {\n printf(\"%-20d%-20d%.*s\\n\", i+1, histo[i], histo[i], stars);\n }\n\n return 0;\n}\n Success #stdin #stdout 0s 5500KB\nResponse Frequency Histogram \n1 1 *\n2 3 ***\n3 12 ************\n4 5 *****\n5 29 *****************************\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74579506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20596587/"
] |
74,579,512
|
<p>When I try to run the code below, it gives me the response:</p>
<blockquote>
<p>"Python: Download video with Youtube and pytube - fix error (regex...)"</p>
</blockquote>
<p>Tried multiple solutions, all to no avail.</p>
<p><strong>Here is my code:</strong></p>
<pre class="lang-py prettyprint-override"><code>link = "https://www.youtube.com/watch?v=vEQ8CXFWLZU&t=475s&ab_channel=InternetMadeCoder"
yt = YouTube(link)
print(yt.title)
</code></pre>
<p>I have tried to reinstall pytube and I have tried downloading it from github but the problem still occurs.</p>
|
[
{
"answer_id": 74579745,
"author": "qbizzle68",
"author_id": 18984369,
"author_profile": "https://Stackoverflow.com/users/18984369",
"pm_score": 1,
"selected": false,
"text": "int f1 = 0, f2 = 0, f3 = 0, f4 = 0, f5 = 0;\n"
},
{
"answer_id": 74579785,
"author": "abelenky",
"author_id": 34824,
"author_profile": "https://Stackoverflow.com/users/34824",
"pm_score": 2,
"selected": false,
"text": "#include <stdio.h>\n\nint main(void) {\n static const int sample[50] = {4,3,5,5,1,5,5,5,4,3,5,3,3,5,5,5,2,5,5,5,5,4,3,5,5,2,5,2,5,4,3,5,3,3,5,5,5,5,5,5,3,5,4,3,5,3,3,5,5,5,};\n int count = sizeof(sample)/sizeof(*sample); \n int histo[5] = {};\n for(int i=0; i<count; ++i)\n {\n histo[sample[i]-1]++;\n }\n \n char stars[count];\n ((char*)memset(stars, '*', count))[count-1] = '\\0';\n \n printf(\"%-20s%-20s%-20s\\n\", \"Response\", \"Frequency\", \"Histogram\");\n for(int i=0; i<5; ++i)\n {\n printf(\"%-20d%-20d%.*s\\n\", i+1, histo[i], histo[i], stars);\n }\n\n return 0;\n}\n Success #stdin #stdout 0s 5500KB\nResponse Frequency Histogram \n1 1 *\n2 3 ***\n3 12 ************\n4 5 *****\n5 29 *****************************\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74579512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20200629/"
] |
74,579,535
|
<p>Im trying to achieve the gradient of the following image:
Basically, I want a <strong>vertical</strong> gradient with 3 colors, left to right. And then I want a <strong>horizontal</strong> opacity gradient from top to bottom.</p>
<p><img src="https://i.stack.imgur.com/TAXN2.png" alt="Different degree gradient" /></p>
<p>I have no idea how to make a gradient that will "erase" the one below it.</p>
|
[
{
"answer_id": 74579745,
"author": "qbizzle68",
"author_id": 18984369,
"author_profile": "https://Stackoverflow.com/users/18984369",
"pm_score": 1,
"selected": false,
"text": "int f1 = 0, f2 = 0, f3 = 0, f4 = 0, f5 = 0;\n"
},
{
"answer_id": 74579785,
"author": "abelenky",
"author_id": 34824,
"author_profile": "https://Stackoverflow.com/users/34824",
"pm_score": 2,
"selected": false,
"text": "#include <stdio.h>\n\nint main(void) {\n static const int sample[50] = {4,3,5,5,1,5,5,5,4,3,5,3,3,5,5,5,2,5,5,5,5,4,3,5,5,2,5,2,5,4,3,5,3,3,5,5,5,5,5,5,3,5,4,3,5,3,3,5,5,5,};\n int count = sizeof(sample)/sizeof(*sample); \n int histo[5] = {};\n for(int i=0; i<count; ++i)\n {\n histo[sample[i]-1]++;\n }\n \n char stars[count];\n ((char*)memset(stars, '*', count))[count-1] = '\\0';\n \n printf(\"%-20s%-20s%-20s\\n\", \"Response\", \"Frequency\", \"Histogram\");\n for(int i=0; i<5; ++i)\n {\n printf(\"%-20d%-20d%.*s\\n\", i+1, histo[i], histo[i], stars);\n }\n\n return 0;\n}\n Success #stdin #stdout 0s 5500KB\nResponse Frequency Histogram \n1 1 *\n2 3 ***\n3 12 ************\n4 5 *****\n5 29 *****************************\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74579535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12028720/"
] |
74,579,537
|
<p>I am new to programming and I am stuck on this. I have to edit a file to be able to sort an array. Previously, it was programmed to sort arrays that are powers of two. Now I have to make a change for it to be able to sort arrays of any number. I Could have sworn this worked when I submitted it, but my professor came back and said it doesn't work ♀️</p>
<p>I have to use <code>calloc</code>. The other files don't need to be changed. The only change I need to make is in the <strong>mergesort.c</strong> file and the <strong>main.c</strong> file that houses the array. I absolutely cannot change the other files so I'm not going to include them but they are correct as I have copied them directly from my text book and have ran them previously for arrays of power 2.</p>
<p>I also previously tried creating an altkey and assigning it the key but he said not to do that..</p>
<h4>This is the code in <strong>main.c</strong>:</h4>
<pre class="lang-c prettyprint-override"><code>#include "mergesort.h"
int main(void) {
int key[] = { 4, 3, 1, 67, 55, 8, 0, 4, -5, 37, 7, 4, 2, 9, 1 };
int sz = sizeof(key) / sizeof(int); /* the size of key[] */
printf("Before mergesort:\n");
wrt(key, sz);
mergesort(key, sz);
printf("After mergesort:\n");
wrt(key, sz);
}
</code></pre>
<h4>This is the current code in <strong>mergesort.c</strong>:</h4>
<pre class="lang-c prettyprint-override"><code>#include "mergesort.h"
void mergesort(int key[], int n) {
int j, k, m, *w, i;
w = calloc(n, sizeof(int)); /* allocate workspace */
assert(w != NULL); /* check that calloc() worked */
for (k = 1; k < n; k *= 2) {
for (j = 0; j < n - k; j += 2 * k)
merge(key + j, key + j + k, w + j, k, k);
for (j = 0; j < n; ++j)
key[j] = w[j]; /* 11/12/22 write w back into key */
}
free(w); /* free the workspace */
}
</code></pre>
<h4>Merge Function in <strong>merge.c</strong> (I can't edit this file)</h4>
<pre><code>#include "mergesort.h"
void merge(int a[], int b[], int c[], int m, int n) {
int i = 0, j = 0, k = 0;
while (i < m && j < n)
if (a[i] < b[j])
c[k++] = a[i++];
else
c[k++] = b[j++];
while (i < m) /* pick up any remainder */
c[k++] = a[i++];
while (j < n)
c[k++] = b[j++];
}
</code></pre>
<h4>Output:</h4>
<pre><code>Before mergesort:
4 3 1 67 55 8 0 4 -5 37 7 4 2 9 1
After mergesort:
-5 0 0 1 2 3 4 4 4 7 8 9 15 15 55
</code></pre>
|
[
{
"answer_id": 74580203,
"author": "Clement Faisandier",
"author_id": 20603928,
"author_profile": "https://Stackoverflow.com/users/20603928",
"pm_score": 0,
"selected": false,
"text": "merge(key + j, key + j + k, w + j, k, k); k k=2 j=12 merge(key + j, key + j + k, w + j, k, k-((n-j)/2)) c[k++] = a[i++];"
},
{
"answer_id": 74581712,
"author": "chqrlie",
"author_id": 4593267,
"author_profile": "https://Stackoverflow.com/users/4593267",
"pm_score": 2,
"selected": true,
"text": "mergesort void mergesort(int key[], int n) {\n int i, j, k;\n int *w = calloc(n, sizeof(*w)); /* allocate workspace */\n assert(w != NULL); /* check that calloc() worked */\n\n for (k = 1; k < n; k *= 2) {\n /* merge all the full pairs */\n for (j = 0; j + 2 * k < n; j += 2 * k) {\n merge(key + j, key + j + k, w + j, k, k);\n }\n if (j + k < n) {\n /* merge the last pair if right half is not empty */\n merge(key + j, key + j + k, w + j, k, n - (j + k));\n j = n;\n }\n /* write merged pairs in w back into key */\n for (i = 0; i < j; i++) {\n key[i] = w[i];\n }\n }\n free(w); /* free the workspace */\n}\n merge a b const int * if (a[i] <= b[j]) size_t void mergesort(int key[], int n) {\n int i, j, k;\n int *w = calloc(n, sizeof(*w)); /* allocate workspace */\n assert(w != NULL); /* check that calloc() worked */\n\n int *w1 = key;\n int *w2 = w;\n int *w3;\n\n for (k = 1; k < n; k *= 2) {\n /* merge all the full pairs */\n for (j = 0; j + 2 * k < n; j += 2 * k) {\n merge(w1 + j, w1 + j + k, w2 + j, k, k);\n }\n if (j + k < n) {\n /* merge the last pair if right half is not empty */\n merge(w1 + j, w1 + j + k, w2 + j, k, n - (j + k));\n } else {\n /* copy the left slice of the last pair */\n for (i = j; i < n; i++) {\n w2[i] = w1[i];\n }\n /* swap the working pointers */\n w3 = w2;\n w2 = w1;\n w1 = w3;\n }\n /* write w back to key if needed */\n if (w1 == w) {\n for (i = 0; i < j; i++) {\n key[i] = w[i];\n }\n }\n free(w); /* free the workspace */\n}\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74579537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20603897/"
] |
74,579,540
|
<p>I've checked the answer to a similar question, but it doesn't quite solve it.</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 qties = [
[12, 45, 56, "", 45, "", "", ""]
]
const incomingBulkQty = qties[0].reduce((partialSum, a) => partialSum + a, 0);
console.log('Result: ' + incomingBulkQty)</code></pre>
</div>
</div>
</p>
<p><strong>Result should be</strong> <code>158</code></p>
<p>I have to identify the elements' indexes as such, given my real world context.</p>
|
[
{
"answer_id": 74579591,
"author": "Samathingamajig",
"author_id": 12101554,
"author_profile": "https://Stackoverflow.com/users/12101554",
"pm_score": 4,
"selected": true,
"text": "Number isNaN let qties = [\n [12, 45, 56, \"\", 45, \"\", \"\", \"\"]\n]\nconst incomingBulkQty = qties[0].reduce((partialSum, a) => partialSum + Number(a), 0);\nconsole.log('Result: ' + incomingBulkQty)"
},
{
"answer_id": 74579596,
"author": "brk",
"author_id": 2181397,
"author_profile": "https://Stackoverflow.com/users/2181397",
"pm_score": 0,
"selected": false,
"text": "incomingSizes let incoming = [\n [12, 45, 56, \"\", 45, \"\", \"\", \"\", null, 158]\n]\n\nconst osCol = 0;\nconst incomingSizes = incoming.map(e => [e[osCol], e[osCol + 1], e[osCol + 2], e[osCol + 3], e[osCol + 4], e[osCol + 5], e[osCol + 6], e[osCol + 7]])[0];\nconst incomingBulkQty = incomingSizes.reduce((partialSum, a) => {\n if (parseInt(a, 10)) {\n partialSum += a\n }\n return partialSum;\n}, 0);\nconsole.log('Result: ' + incomingBulkQty)"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74579540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11832197/"
] |
74,579,557
|
<pre><code>class WithdrawRequests(models.Model):
withdraw_hash = models.CharField(max_length=255, unique=True, db_index=True)
timestamp = models.DateTimeField(auto_now_add=True)
username = models.CharField(max_length=255, unique=False, db_index=True)
currency = models.CharField(max_length=255, unique=False, db_index=True)
user_balance = models.DecimalField(max_digits=300, default=0.0, decimal_places=150)
withdraw_address = models.CharField(max_length=255, unique=False, db_index=True)
withdraw_amount = models.DecimalField(max_digits=30, default=0.0, decimal_places=15)
</code></pre>
<p>This is my models.py file.</p>
<pre><code> currency = request.data['currency']
payload = jwt.decode(token, settings.SECRET_KEY)
user = User.objects.get(id=payload['user_id'])
timestamp = datetime.datetime.now()
timestamp = timestamp.timestamp()
withdraw_hash = hashlib.sha256()
withdraw_hash.update(str(timestamp).encode("utf-8"))
withdraw_hash = withdraw_hash.hexdigest()
username = user.username
currency_balance = GAME_CURRENCIES[request.data['currency']]
user_balance = getattr(user, currency_balance)
withdraw_address = request.data['withdraw_address']
withdraw_amount = request.data['withdraw_amount']
if user_balance < withdraw_amount:
return Response({
"message": "Not enough funds."
})
else:
# row format - hash timestamp username currency user_balance withdraw_address withdraw_amount
withdraw = WithdrawRequests()
withdraw.withdraw_hash = withdraw_hash,
withdraw.timestamp = datetime.datetime.now(),
withdraw.username = username,
withdraw.currency = currency,
withdraw.user_balance = user_balance,
withdraw.withdraw_address = withdraw_address,
withdraw.withdraw_amount = withdraw_amount
withdraw.save()
</code></pre>
<p>And here is the views.py file. Whatever I do the error is the following.</p>
<pre><code> ...
File "C:\Users\Msi\cover_game\cover\lib\site-packages\django\db\models\fields\__init__.py", line 1554, in to_python
raise exceptions.ValidationError(
django.core.exceptions.ValidationError: ['“(0.011095555563904999,)” value must be a decimal number.']
</code></pre>
<p>As you can see with user_balance everything is fine and it's floating number.</p>
<p>Edited: added the whole view and the other model so that it will be more clear.</p>
|
[
{
"answer_id": 74579646,
"author": "akdev",
"author_id": 2065831,
"author_profile": "https://Stackoverflow.com/users/2065831",
"pm_score": 1,
"selected": false,
"text": "“(0.011095555563904999,)” withdraw_amount"
},
{
"answer_id": 74579698,
"author": "Sunderam Dubey",
"author_id": 17562044,
"author_profile": "https://Stackoverflow.com/users/17562044",
"pm_score": 0,
"selected": false,
"text": "x=request.data[\"withdraw_amount\"]\nnum_list=\"0123456789.\"\nactual_str=\"\"\nfor i,k in enumerate(x):\n if k in num_list:\n actual_str+=k\nwithdraw_amount=float(actual_str)\nprint(withdraw_amount)\n currency = request.data['currency']\n payload = jwt.decode(token, settings.SECRET_KEY)\n user = User.objects.get(id=payload['user_id'])\n timestamp = datetime.datetime.now()\n timestamp = timestamp.timestamp()\n withdraw_hash = hashlib.sha256()\n withdraw_hash.update(str(timestamp).encode(\"utf-8\"))\n withdraw_hash = withdraw_hash.hexdigest()\n username = user.username\n currency_balance = GAME_CURRENCIES[request.data['currency']]\n user_balance = getattr(user, currency_balance)\n withdraw_address = request.data['withdraw_address']\n \n x=request.data[\"withdraw_amount\"]\n num_list=\"0123456789.\"\n actual_str=\"\"\n for i,k in enumerate(x):\n if k in num_list:\n actual_str+=k\n \n withdraw_amount=float(actual_str)\n print(withdraw_amount)\n\n if user_balance < withdraw_amount:\n return Response({\n \"message\": \"Not enough funds.\"\n })\n else:\n # row format - hash timestamp username currency user_balance withdraw_address withdraw_amount\n withdraw = WithdrawRequests()\n withdraw.withdraw_hash = withdraw_hash,\n withdraw.timestamp = datetime.datetime.now(),\n withdraw.username = username,\n withdraw.currency = currency,\n withdraw.user_balance = user_balance,\n withdraw.withdraw_address = withdraw_address,\n withdraw.withdraw_amount = withdraw_amount\n\n withdraw.save()\n"
},
{
"answer_id": 74584144,
"author": "Mels Hakobyan",
"author_id": 6904605,
"author_profile": "https://Stackoverflow.com/users/6904605",
"pm_score": 0,
"selected": false,
"text": "withdraw.withdraw_hash = withdraw_hash,\nwithdraw.timestamp = datetime.datetime.now()\nwithdraw.username = username\nwithdraw.currency = currency\nwithdraw.user_balance = user_balance\nwithdraw.withdraw_address = withdraw_address\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74579557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6904605/"
] |
74,579,566
|
<p>I have create a pipeline and trying to trigger and download the artifacts via Azure CLI (tried both windows powershell and Developer powershell).</p>
<p>I can log in, trigger the pipeline without any issue, but when tried the below command to download the artifact it throws the error message 'TF400813: The user '' is not authorized to access this resource'</p>
<pre><code>az pipelines runs artifact download --org <organization> --project <Project name> --artifact-name <Pipeline name> --path <local download path> --run-id 11
</code></pre>
<p>I am using PAT to log in and the user is assigned as the administrator and assigned to the relevant project too. PAT has full access.</p>
<p>Further, i tried log in interactively by using <em>az login</em>, but same error occurs.</p>
<p><strong>PAT Setting</strong></p>
<p><a href="https://i.stack.imgur.com/PpTJN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PpTJN.png" alt="PAT Setting" /></a></p>
<p><strong>Organization Setting</strong></p>
<p><a href="https://i.stack.imgur.com/BQwKA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BQwKA.png" alt="Organization Setting" /></a></p>
<p><a href="https://i.stack.imgur.com/mUUF3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mUUF3.png" alt="Organization User Setting" /></a></p>
<p><strong>Project Setting</strong></p>
<p><a href="https://i.stack.imgur.com/9xLvc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9xLvc.png" alt="enter image description here" /></a></p>
<p>Thanks.</p>
|
[
{
"answer_id": 74579646,
"author": "akdev",
"author_id": 2065831,
"author_profile": "https://Stackoverflow.com/users/2065831",
"pm_score": 1,
"selected": false,
"text": "“(0.011095555563904999,)” withdraw_amount"
},
{
"answer_id": 74579698,
"author": "Sunderam Dubey",
"author_id": 17562044,
"author_profile": "https://Stackoverflow.com/users/17562044",
"pm_score": 0,
"selected": false,
"text": "x=request.data[\"withdraw_amount\"]\nnum_list=\"0123456789.\"\nactual_str=\"\"\nfor i,k in enumerate(x):\n if k in num_list:\n actual_str+=k\nwithdraw_amount=float(actual_str)\nprint(withdraw_amount)\n currency = request.data['currency']\n payload = jwt.decode(token, settings.SECRET_KEY)\n user = User.objects.get(id=payload['user_id'])\n timestamp = datetime.datetime.now()\n timestamp = timestamp.timestamp()\n withdraw_hash = hashlib.sha256()\n withdraw_hash.update(str(timestamp).encode(\"utf-8\"))\n withdraw_hash = withdraw_hash.hexdigest()\n username = user.username\n currency_balance = GAME_CURRENCIES[request.data['currency']]\n user_balance = getattr(user, currency_balance)\n withdraw_address = request.data['withdraw_address']\n \n x=request.data[\"withdraw_amount\"]\n num_list=\"0123456789.\"\n actual_str=\"\"\n for i,k in enumerate(x):\n if k in num_list:\n actual_str+=k\n \n withdraw_amount=float(actual_str)\n print(withdraw_amount)\n\n if user_balance < withdraw_amount:\n return Response({\n \"message\": \"Not enough funds.\"\n })\n else:\n # row format - hash timestamp username currency user_balance withdraw_address withdraw_amount\n withdraw = WithdrawRequests()\n withdraw.withdraw_hash = withdraw_hash,\n withdraw.timestamp = datetime.datetime.now(),\n withdraw.username = username,\n withdraw.currency = currency,\n withdraw.user_balance = user_balance,\n withdraw.withdraw_address = withdraw_address,\n withdraw.withdraw_amount = withdraw_amount\n\n withdraw.save()\n"
},
{
"answer_id": 74584144,
"author": "Mels Hakobyan",
"author_id": 6904605,
"author_profile": "https://Stackoverflow.com/users/6904605",
"pm_score": 0,
"selected": false,
"text": "withdraw.withdraw_hash = withdraw_hash,\nwithdraw.timestamp = datetime.datetime.now()\nwithdraw.username = username\nwithdraw.currency = currency\nwithdraw.user_balance = user_balance\nwithdraw.withdraw_address = withdraw_address\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74579566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20263228/"
] |
74,579,595
|
<p>I am trying to create a loading sequence of 3 dots that repeats itself until input from the user breaks the loading sequence specifically the enter key. i connot for the life of me get the infinite while loop to end with input</p>
<pre><code>public class loop {
public static void AnyKey() {
try {
System.in.read();
loading(false);
} catch (Exception e){}
}
public static void pause(long duration) {
try{
Thread.sleep(duration);
} catch (InterruptedException e){}
}
public static void loading(boolean status){
if (status == true) {
while (status) {
pause(500);
int i;
for (i = 0; i <3; i++){
System.out.print(".");
pause(500);
}
System.out.print("\b\b\b");
}
}
}
public static void main(String[] args) {
loading(true);
AnyKey();
}
}
</code></pre>
|
[
{
"answer_id": 74579673,
"author": "Clement Faisandier",
"author_id": 20603928,
"author_profile": "https://Stackoverflow.com/users/20603928",
"pm_score": 2,
"selected": false,
"text": "loading(true) while(status) AnyKey() System.in.read(); .read() .available()"
},
{
"answer_id": 74588564,
"author": "Mattsimus",
"author_id": 20602881,
"author_profile": "https://Stackoverflow.com/users/20602881",
"pm_score": 2,
"selected": true,
"text": " import java.util.Scanner;\n\nclass AnyKey extends Thread {\n\n public void run() {\n Scanner scanner = new Scanner(System.in);\n scanner.nextLine();\n loadingDots.loadingStatus = false;\n }\n}\npublic class loadingDots {\n public static boolean loadingStatus;\n public static void pause(long duration) {\n try {\n Thread.sleep(duration);\n } catch (InterruptedException e) {}\n }\n public static void loading(){\n loadingStatus = true;\n while (loadingStatus) {\n pause(500);\n int i;\n for (i = 0; i < 3; i++) {\n if (!loadingStatus){\n break;\n }\n System.out.print(\".\");\n pause(500);\n }\n System.out.print(\"\\b\\b\\b\");\n }\n }\n\n public static void main(String[] args) {\n AnyKey anykey = new AnyKey();\n anykey.start();\n loading();\n }\n}\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74579595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20602881/"
] |
74,579,623
|
<pre><code>local player = game.Players.LocalPlayer
local mouse = player:GetMouse()
local mutebutton = script.Parent
while true do
wait()
local b = game.StarterGui.MusicPlayer.Playlist:GetChildren()
local c = math.random(1, #b)
local d = b[c]
d:Play()
wait(d.TimeLength)
mutebutton.MouseButton1Click:Connect(function()
d.Volume = 0
end)
end
</code></pre>
<p>If i was to replace d.Volume = 0 with print(d.Volume) or print("testing") then it will work however when I change it to actually mute the audio, it dosent want to work. Anyone know why?</p>
|
[
{
"answer_id": 74579919,
"author": "ivy",
"author_id": 20604326,
"author_profile": "https://Stackoverflow.com/users/20604326",
"pm_score": 2,
"selected": false,
"text": "Sound :Pause() mutebutton.MouseButton1Click:Connect(function()\n d:Pause()\nend)\n"
},
{
"answer_id": 74581544,
"author": "Heliodex",
"author_id": 12576382,
"author_profile": "https://Stackoverflow.com/users/12576382",
"pm_score": 2,
"selected": true,
"text": "MouseButton1Click:Connect wait(d.TimeLength) d:Pause() while true do\n local b = game.StarterGui.MusicPlayer.Playlist:GetChildren()\n local d = b[math.random(1, #b)]\n d:Play()\n \n local connection = mutebutton.MouseButton1Click:Connect(function()\n if d.IsPaused then -- Makes the pause button a play button if the song is paused already\n d:Resume()\n else\n d:Pause()\n end\n end) \n \n d.Ended:Wait() -- Wait until music ends\n connection:Disconnect() -- Remove connection (to prevent multiple functions on the same button click)\nend\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74579623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16091352/"
] |
74,579,624
|
<p>I am relatively new to using Regular Expressions with JavaScript and come across a particular situation with regards to the '@' username pattern that has given me about 3 hours of trouble.</p>
<p>I would like to replicate the @username pattern found on social media text fields on websites such as Facebook and Twitter. (I understand that they parse tokenized macros but I would like a pure RegEx version).</p>
<p>I have attached an image of the closest pattern that I have achieved, however I will also type this in order to make it easier for anyone to copy and paste into their own RegEx pattern checker.</p>
<p>As you can see, the @ symbol aught to catch all subsequent alpha characters and nothing preceding that @ symbol and be terminated by a space. There is a special case where a URL that contains an @ symbol should be ignored. (As illustrated in the image) and the @ symbol could be used at the very start of the textfield and in this case the handle should be parsed.</p>
<p>Clearly, my existing pattern is collecting the preceding character to the @ symbol which is incorrect. Any help would be fantastic.</p>
<h1>RegEx101 example (with highlights)</h1>
<p><a href="https://i.stack.imgur.com/4DJyB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4DJyB.png" alt="RegEx101 example" /></a></p>
<h1>RegEx that is not working</h1>
<pre><code>/(^^|[^\/])(@[A-Za-z0-9_.]{3,25})/gm
</code></pre>
<h1>Text version for copy+paste convenience</h1>
<pre><code>@test testing
@test testing
testing ,@test
https://youtube.com/@test
</code></pre>
<p>I tried multiple combinations of patterns, over 3 hours, to try to isolate @handle style tags as seen in popular social networks. I expected to be able to isolate only the portion of the patter that contain a single @ deliminated username. I expected that I could ignore this patter where it is part of a URL.</p>
<p>My actual results cause the preceding character to be collected and added to the final string which is incorrect.</p>
|
[
{
"answer_id": 74579651,
"author": "Samathingamajig",
"author_id": 12101554,
"author_profile": "https://Stackoverflow.com/users/12101554",
"pm_score": 3,
"selected": true,
"text": "(?<=YOUR_REGEX)\n /(?<=^|[^\\/])(@[A-Za-z0-9_.]{3,25})/gm\n"
},
{
"answer_id": 74579720,
"author": "Delta",
"author_id": 10521934,
"author_profile": "https://Stackoverflow.com/users/10521934",
"pm_score": 0,
"selected": false,
"text": "/(?<=[^\\/]|^)@[A-Za-z0-9_.]{3,25}/g\n / @ _ ."
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74579624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19588421/"
] |
74,579,628
|
<p>I am integrating stripe with my application. I want to receive a one time payment from a logged in user and once the payment is done maybe save the payment status in the database.</p>
<p>I have set up the stripe-checkout and stripe-webhook. But how would i know which logged in user from the client side has made the payment so that i can set the payment status for that user in the database.</p>
<p>Here is how my checkout and webhook look like.</p>
<pre><code>app.post("/checkout-session", async (req, res) => {
try {
const session = await stripe.checkout.sessions.create({
payment_method_types: ["card"],
mode: "payment",
line_items: req.body.items.map((item) => {
const storeItem = storeItems.get(item.id);
return {
price_data: {
currency: "usd",
product_data: {
name: storeItem.name,
},
unit_amount: storeItem.priceInCents,
},
quantity: item.quantity,
};
}),
success_url: `${process.env.CLIENT_URL}/success`,
cancel_url: `${process.env.CLIENT_URL}/failure`,
});
res.json({ url: session.url });
} catch (e) {
res.status(500).json({ error: e.message });
}
});
app.post("/webhook", express.raw({ type: "application/json" }), (req, res) => {
let event;
// Only verify the event if you have an endpoint secret defined.
// Otherwise use the basic event deserialized with JSON.parse
if (process.env.STRIPE_WEBHOOK_SECRET) {
// Get the signature sent by Stripe
const signature = req.headers["stripe-signature"];
try {
event = stripe.webhooks.constructEvent(
req.body,
signature,
process.env.STRIPE_WEBHOOK_SECRET
);
} catch (err) {
console.log(`⚠️ Webhook signature verification failed.`, err.message);
return res.sendStatus(400);
}
}
// Handle the event
switch (event.type) {
case "payment_intent.succeeded":
const paymentIntent = event.data.object;
console.log(`PaymentIntent for ${paymentIntent.amount} was successful!`);
console.log(paymentIntent);
// Then define and call a methstripe loginod to handle the successful payment intent.
// handlePaymentIntentSucceeded(paymentIntent);
break;
case "payment_method.attached":
const paymentMethod = event.data.object;
// Then define and call a method to handle the successful attachment of a PaymentMethod.
// handlePaymentMethodAttached(paymentMethod);
break;
case "payment_intent.payment_failed":
const failedpaymentIntent = event.data.object;
console.log(`PaymentIntent for ${paymentIntent.amount} failed!`);
// Then define and call a methstripe loginod to handle the successful payment intent.
// handlePaymentIntentSucceeded(paymentIntent);
break;
case "checkout.session.completed":
console.log(event.data.object);
// console.log(`PaymentIntent for ${paymentIntent.amount} failed!`);
// Then define and call a methstripe loginod to handle the successful payment intent.
// handlePaymentIntentSucceeded(paymentIntent);
break;
default:
// Unexpected event type
console.log(`Unhandled event type ${event.type}.`);
}
// Return a 200 response to acknowledge receipt of the event
res.send();
});```
</code></pre>
|
[
{
"answer_id": 74579766,
"author": "mb_const",
"author_id": 20597869,
"author_profile": "https://Stackoverflow.com/users/20597869",
"pm_score": 0,
"selected": false,
"text": "json web token (jwt) local storage"
},
{
"answer_id": 74591288,
"author": "yuting",
"author_id": 18960736,
"author_profile": "https://Stackoverflow.com/users/18960736",
"pm_score": 2,
"selected": true,
"text": "checkout.session.completed customer_details.email metadata checkout.session.completed"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74579628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12886867/"
] |
74,579,676
|
<p>I have a PDF file, I need to convert it into a CSV file this is my pdf file example as link <a href="https://online.flippingbook.com/view/352975479/" rel="nofollow noreferrer">https://online.flippingbook.com/view/352975479/</a> the code used is</p>
<pre><code>import re
import parse
import pdfplumber
import pandas as pd
from collections import namedtuple
file = "Battery Voltage.pdf"
lines = []
total_check = 0
with pdfplumber.open(file) as pdf:
pages = pdf.pages
for page in pdf.pages:
text = page.extract_text()
for line in text.split('\n'):
print(line)
</code></pre>
<p>with the above script I am not getting proper output, For Time column "AM" is getting in the next line. The output I am getting is like this</p>
<p><a href="https://i.stack.imgur.com/25Yxc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/25Yxc.png" alt="[1]: https://i.stack.imgur.com/25Yxc.png" /></a></p>
|
[
{
"answer_id": 74581099,
"author": "Edo Akse",
"author_id": 9267296,
"author_profile": "https://Stackoverflow.com/users/9267296",
"pm_score": 1,
"selected": false,
"text": "import pdfplumber\n\n\nfile = \"Battery Voltage.pdf\"\nskiplines = [\n \"Battery Voltage\",\n \"AM\",\n \"PM\",\n \"Sr No DateTIme Voltage (v) Ignition\",\n \"\"\n]\n\n\nwith open(\"output.csv\", \"w\") as outfile:\n header = \"serialnumber;date;time;voltage;ignition\\n\"\n outfile.write(header)\n with pdfplumber.open(file) as pdf:\n for page in pdf.pages:\n for line in page.extract_text().split('\\n'):\n if line.strip() in skiplines:\n continue\n outfile.write(\";\".join(line.split())+\"\\n\")\n import pdfplumber\nimport json\n\n\nfile = \"Battery Voltage.pdf\"\nskiplines = [\n \"Battery Voltage\",\n \"AM\",\n \"PM\",\n \"Sr No DateTIme Voltage (v) Ignition\",\n \"\"\n]\nresult = []\n\n\nwith pdfplumber.open(file) as pdf:\n for page in pdf.pages:\n for line in page.extract_text().split(\"\\n\"):\n if line.strip() in skiplines:\n continue\n serialnumber, date, time, voltage, ignition = line.split()\n result.append(\n {\n \"serialnumber\": serialnumber,\n \"date\": date,\n \"time\": time,\n \"voltage\": voltage,\n \"ignition\": ignition,\n }\n )\n\nwith open(\"output.json\", \"w\") as outfile:\n json.dump(result, outfile)\n"
},
{
"answer_id": 74582437,
"author": "K J",
"author_id": 10802527,
"author_profile": "https://Stackoverflow.com/users/10802527",
"pm_score": 2,
"selected": false,
"text": "BT\n/F1 12 Tf\n1 0 0 1 224.20265 754.6322 Tm\n[<001D001E>] TJ\nET\n AM \" \",AM,\" \",\" \" pdftotext -layout \"Battery Voltage.pdf\" ,,Battery Vo,ltage,\n\n\n\n\nSr No,DateT,Ime,Voltage (v),Ignition\n1,01/11/2022,00:08:10,47.15,Off\n,AM,,,\n2,01/11/2022,00:23:10,47.15,Off\n,AM,,,\n3,01/11/2022,00:38:10,47.15,Off\n,AM,,,\n4,01/11/2022,00:58:10,47.15,Off\n,AM,,,\n5,01/11/2022,01:18:10,47.15,Off\n,AM,,,\n6,01/11/2022,01:33:10,47.15,Off\n,AM,,,\n7,01/11/2022,01:48:10,47.15,Off\n,AM,,,\n8,01/11/2022,02:03:10,47.15,Off\n,AM,,,\n9,01/11/2022,02:18:10,47.15,Off\n,AM,,,\n10,01/11/2022,02:37:12,47.15,Off\n,AM,,,\n ,,Battery,Voltage,\nSr No,Date,Time,Voltage (v),Ignition\n1,01/11/2022,00:08:10,47.15,Off,AM,,,\n2,01/11/2022,00:23:10,47.15,Off,AM,,,\n3,01/11/2022,00:38:10,47.15,Off,AM,,,\n4,01/11/2022,00:58:10,47.15,Off,AM,,,\n5,01/11/2022,01:18:10,47.15,Off,AM,,,\n6,01/11/2022,01:33:10,47.15,Off,AM,,,\n7,01/11/2022,01:48:10,47.15,Off,AM,,,\n8,01/11/2022,02:03:10,47.15,Off,AM,,,\n9,01/11/2022,02:18:10,47.15,Off,AM,,,\n10,01/11/2022,02:37:12,47.15,Off,AM,,,\n pdftotext -layout -nopgbrk -x 0 -y 60 -W 800 -H 800 -fixed 6 \"Battery Voltage.pdf\" &type \"battery voltage.txt\"|findstr \"O\">battery.txt 1 01-11-2022 00:08:10 47.15 Off\n 2 01-11-2022 00:23:10 47.15 Off\n 3 01-11-2022 00:38:10 47.15 Off\n 4 01-11-2022 00:58:10 47.15 Off\n 5 01-11-2022 01:18:10 47.15 Off\n...\n 32357 24-11-2022 17:48:43 45.40 On\n 32358 24-11-2022 17:48:52 44.51 On\n 32359 24-11-2022 17:48:55 44.51 On\n 32360 24-11-2022 17:48:58 44.51 On\n 32361 24-11-2022 17:48:58 44.51 On\n for /f \"tokens=1,2,3,4,5 delims= \" %%a In ('Findstr /C:\"O\" battery.txt') do echo csv is \"%%a,%%b,%%c,%%d,%%e\">output.txt\n...\ncsv is \"32357,24-11-2022,17:48:43,45.40,On\"\ncsv is \"32358,24-11-2022,17:48:52,44.51,On\"\ncsv is \"32359,24-11-2022,17:48:55,44.51,On\"\ncsv is \"32360,24-11-2022,17:48:58,44.51,On\"\ncsv is \"32361,24-11-2022,17:48:58,44.51,On\"\n {\"line_id\":1,\"created\":{\"date\":\"01-11-2022\"},{\"time\":\"00:08:10\"},{\"Voltage\":\"47.15\"},{\"State\",\"Off\"}}\n{\"line_id\":2,\"created\":{\"date\":\"01-11-2022\"},{\"time\":\"00:23:10\"},{\"Voltage\":\"47.15\"},{\"State\",\"Off\"}}\n{\"line_id\":3,\"created\":{\"date\":\"01-11-2022\"},{\"time\":\"00:38:10\"},{\"Voltage\":\"47.15\"},{\"State\",\"Off\"}}\n{\"line_id\":4,\"created\":{\"date\":\"01-11-2022\"},{\"time\":\"00:58:10\"},{\"Voltage\":\"47.15\"},{\"State\",\"Off\"}}\n{\"line_id\":5,\"created\":{\"date\":\"01-11-2022\"},{\"time\":\"01:18:10\"},{\"Voltage\":\"47.15\"},{\"State\",\"Off\"}}\n{\"line_id\":6,\"created\":{\"date\":\"01-11-2022\"},{\"time\":\"01:33:10\"},{\"Voltage\":\"47.15\"},{\"State\",\"Off\"}}\n{\"line_id\":7,\"created\":{\"date\":\"01-11-2022\"},{\"time\":\"01:48:10\"},{\"Voltage\":\"47.15\"},{\"State\",\"Off\"}}\n{\"line_id\":8,\"created\":{\"date\":\"01-11-2022\"},{\"time\":\"02:03:10\"},{\"Voltage\":\"47.15\"},{\"State\",\"Off\"}}\n{\"line_id\":9,\"created\":{\"date\":\"01-11-2022\"},{\"time\":\"02:18:10\"},{\"Voltage\":\"47.15\"},{\"State\",\"Off\"}}\n{\"line_id\":10,\"created\":{\"date\":\"01-11-2022\"},{\"time\":\"02:37:12\"},{\"Voltage\":\"47.15\"},{\"State\",\"Off\"}}\n pdftotext -layout -nopgbrk -x 0 -y 60 -W 700 -H 800 -fixed 8 \"%~1\" battery.txt\n\necho Heading however you wish it for json perhaps just opener [ but note only one redirect chevron >\"%~dpn1.txt\"\n\nfor /f \"tokens=1,2,3,4,5 delims= \" %%a In ('Findstr /C:\"O\" battery.txt') do @echo \"%%a\": { \"Date\": \"%%b\", \"Time\": \"%%c\", \"Voltage\": %%d, \"Ignition\": \"%%e\" },>>\"%~dpn1.txt\"\nREM another json style could be { \"Line_Id\": %%a, \"Date\": \"%%b\", \"Time\": \"%%c\", \"Voltage\": %%d, \"Ignition\": \"%%e\" },\nREM another for an array can simply be [%%a,\"%%b\",\"%%c\",%%d,\"%%e\" ],\n\necho Tailing however you wish it for json perhaps just final closer ] but note double chevron >>\"%~dpn1.txt\"\n @echo { @echo %%a&echo {"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74579676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19908761/"
] |
74,579,694
|
<p>I am using JDK/Java 19 in Windows 11 x64, IntelliJ IDEA 2022 Ultimate.</p>
<pre class="lang-java prettyprint-override"><code>import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ZooInfo {
public static void main(String[] args) {
ExecutorService executorService = null;
Runnable runnable1 = () -> System.out.println("Printing zoo inventory");
Runnable runnable2 = () -> {
for (int i = 0; i < 3; i++) {
System.out.println("Printing record " + i);
}
};
try {
executorService = Executors.newSingleThreadExecutor();
System.out.println("Begin");
executorService.execute(runnable1);
executorService.execute(runnable2);
executorService.execute(runnable1);
System.out.println("End.");
} finally {
if (executorService != null) {
executorService.shutdown();
}
}
}
}
// Result:
// Begin
// End.
// Printing zoo inventory
// Printing record 0
// Printing record 1
// Printing record 2
// Printing zoo inventory
</code></pre>
<p>I read page 850, book OCP Oracle Certified Professional Java SE 11 Developer - Complete Study Guide), they said</p>
<blockquote>
<p>With a single-thread executor, results are guaranteed to be executed
sequentially.</p>
</blockquote>
<p>Why the order was not guaranteed by <code>Executors.newSingleThreadExecutor()</code> ? ("end" not at the end of line in console's result.)</p>
|
[
{
"answer_id": 74579703,
"author": "James Grey",
"author_id": 3728901,
"author_profile": "https://Stackoverflow.com/users/3728901",
"pm_score": -1,
"selected": false,
"text": "executorService = Executors.newSingleThreadExecutor();"
},
{
"answer_id": 74579796,
"author": "Basil Bourque",
"author_id": 642706,
"author_profile": "https://Stackoverflow.com/users/642706",
"pm_score": 3,
"selected": false,
"text": "shutdownAndAwaitTermination shutdownAndAwaitTermination ExecutorService Runnable executorService = Executors.newSingleThreadExecutor();\nSystem.out.println(\"Begin\");\nexecutorService.execute(runnable1);\nexecutorService.execute(runnable2);\nexecutorService.execute(runnable1);\nshutdownAndAwaitTermination( executorService ) ; // Block here to wait for executor service to complete its assigned tasks. \nSystem.out.println(\"End.\");\n"
},
{
"answer_id": 74579812,
"author": "yshavit",
"author_id": 1076640,
"author_profile": "https://Stackoverflow.com/users/1076640",
"pm_score": 2,
"selected": false,
"text": "executorService.execute Executors.newSingleThreadExecutor() newSingleThreadExecutor executorService.shutdown() awaitTermination(...) submit execute Future get(...) executorService.invokeAll(...)"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74579694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3728901/"
] |
74,579,753
|
<p>Anyways I’m trying to make a lightbulb. It’s just a circle, I have an <code>onclick</code> event on a button, and the event function toggled a class, changing the color. But I want the text in the button to toggle as well when that class is activated.</p>
<p>I finally made it work as I was writing this question. But it still isn’t working how I want it. I only want to have one if statement.</p>
<p>I only want to solve it this specific way, by checking if a class is activated, and if yes, then change the text content of the button, if not, then leave it how it is.</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 bulb = document.getElementById("light");
let lightSwitch = document.getElementById("switch");
function activity(event) {
bulb.classList.toggle("lightOn");
if (bulb.classList.contains("lightOn")) {
lightSwitch.textContent = "OFF";
} else if (bulb.classList.contains("lightOff")) {
lightSwitch.textContent = "ON";
}
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.lightOn {
background: yellow;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="light" class="lightOff"></div>
<button id="switch" onclick="activity()">ON</button></code></pre>
</div>
</div>
</p>
<p>How can I write it with only one if statement, Also, is there a way easier than this? Just vanilla not jQuery.</p>
|
[
{
"answer_id": 74579778,
"author": "Layhout",
"author_id": 17308201,
"author_profile": "https://Stackoverflow.com/users/17308201",
"pm_score": 3,
"selected": true,
"text": "...\n\nfunction activity(event) {\n bulb.classList.toggle(\"lightOn\");\n lightSwitch.textContent = bulb.classList.contains(\"lightOn\") ? \"OFF\" : \"ON\";\n}\n\n...\n"
},
{
"answer_id": 74579799,
"author": "Michael M.",
"author_id": 13376511,
"author_profile": "https://Stackoverflow.com/users/13376511",
"pm_score": 2,
"selected": false,
"text": "light lightOn !important lightOn let bulb = document.getElementById(\"light\");\nlet lightSwitch = document.getElementById(\"switch\");\n\nlightSwitch.addEventListener('click', function() {\n bulb.classList.toggle('lightOn');\n lightSwitch.textContent = bulb.classList.contains(\"lightOn\") ? \"OFF\" : \"ON\";\n}); .light {\n width: 100px;\n height: 100px;\n border-radius: 100%;\n background: gray;\n}\n\n.lightOn {\n background: yellow !important;\n} <div id=\"light\" class=\"light\"></div>\n<button id=\"switch\">ON</button>"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74579753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19943108/"
] |
74,579,755
|
<p>I want to fetch the latest entry to the database</p>
<p>I have this data</p>
<p><a href="https://i.stack.imgur.com/OhbgC.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OhbgC.jpg" alt="enter image description here" /></a></p>
<p>When I run this query</p>
<p><code>select id, parent_id, amount, max(created_at) from table group by parent_id</code>
it correctly returns the latest entry but not the rest of the column</p>
<p><a href="https://i.stack.imgur.com/km0nT.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/km0nT.jpg" alt="enter image description here" /></a></p>
<p>what I want is</p>
<p><a href="https://i.stack.imgur.com/EEq3v.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EEq3v.jpg" alt="enter image description here" /></a></p>
<p>how do I achieve that?</p>
<p>Sorry that I posted image instead of table, the table won't work for some reason</p>
|
[
{
"answer_id": 74579807,
"author": "npe",
"author_id": 20561457,
"author_profile": "https://Stackoverflow.com/users/20561457",
"pm_score": -1,
"selected": false,
"text": "select id, parent_id, amount, max(created_at)\nfrom table\ngroup by parent_id \norder by max(created_at) desc \nlimit 1\n"
},
{
"answer_id": 74579892,
"author": "Prasuna",
"author_id": 15126914,
"author_profile": "https://Stackoverflow.com/users/15126914",
"pm_score": 1,
"selected": false,
"text": "SELECT * FROM yourtable t WHERE t.created_at = \n(SELECT MAX(created_at) FROM yourtable WHERE parent_id = t.parent_id);\n SELECT * FROM yourtable t WHERE t.id = \n(SELECT MAX(id) FROM yourtable WHERE parent_id = t.parent_id);\n"
},
{
"answer_id": 74579927,
"author": "Jonas Metzler",
"author_id": 18794826,
"author_profile": "https://Stackoverflow.com/users/18794826",
"pm_score": 1,
"selected": false,
"text": "RANK SELECT id, parent_id, amount, created_at \nFROM ( \n SELECT id, parent_id, amount, created_at, \n RANK() OVER (PARTITION BY parent_id ORDER BY created_at DESC) parentID_rank\n FROM yourtable) groupedData\nWHERE parentID_rank = 1;\n ORDER BY SELECT id, parent_id, amount, created_at \nFROM ( \n SELECT id, parent_id, amount, created_at, \n RANK() OVER (PARTITION BY parent_id ORDER BY created_at DESC) parentID_rank\n FROM yourtable) groupedData\nWHERE parentID_rank = 1\nORDER BY id;\n PARTITION BY ORDER BY WHERE"
},
{
"answer_id": 74580569,
"author": "Thorsten Kettner",
"author_id": 2270762,
"author_profile": "https://Stackoverflow.com/users/2270762",
"pm_score": 0,
"selected": false,
"text": "SET sql_mode = 'ONLY_FULL_GROUP_BY';\n MAX GROUP BY select\n any_value(id),\n parent_id,\n any_value(amount),\n max(created_at)\nfrom table\ngroup by parent_id;\n ANY_VALUE select *\nfrom table \nwhere (parent_id, created_at) in\n(\n select parent_id, max(created_at)\n from table\n group by parent_id\n);\n select *\nfrom table t\nwhere not exists\n(\n select null\n from table newer\n where newer.parent_id = t.parent_id\n and newer.created_at > t.created_at\n);\n select id, parent_id, amount, created_at\nfrom\n(\n select t.*, max(created_at) over (partition by parent_id) as max_created_at\n from table t\n) with_max_created_at\nwhere created_at = max_created_at;\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74579755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19999746/"
] |
74,579,763
|
<p>I have below kind of kind of array of object data which contain nested array of object inside it, and I want to structure it based on what my Api needed.</p>
<pre><code> [{
containerId: 'c12',
containerNumber: '4321dkjkfdj',
goods: [{
weight: '32kg',
quantity: '3'
}]
},
{ containerId: 'c12', containerNumber: '4321dkjkfdj', goods: [{
weight: '322kg',
quantity: '32'
}]
},
{
containerId: 'c13',
containerNumber: '1212dkjkfdj',
goods: [{
weight: '13kg',
quantity: '3'
}]
},
{containerId: 'c13', containerNumber: '1212dkjkfdj', goods: [{
weight: '13kg',
quantity: '3'
}]
},
]
</code></pre>
<p>and I want to have an Object with same 'containerId' as a one object by including the 'goods' property that has the same 'containerId' like the below code:</p>
<pre><code> [{
containerId: 'c12',
containerNumber: '4321dkjkfdj',
goods: [{
weight: '32kg',
quantity: '3'
},
{
weight: '322kg',
quantity: '32'
}
]
},
{
containerId: 'c13',
containerNumber: '1212dkjkfdj',
goods: [{
weight: '13kg',
quantity: '3'
},
{
weight: '13kg',
quantity: '3'
}
]
}
]
</code></pre>
|
[
{
"answer_id": 74579821,
"author": "Layhout",
"author_id": 17308201,
"author_profile": "https://Stackoverflow.com/users/17308201",
"pm_score": 0,
"selected": false,
"text": "const a = [\n {\n containerId: 'c12',\n containerNumber: '4321dkjkfdj',\n goods: [{\n weight: '32kg',\n quantity: '3'\n }]\n },\n {\n containerId: 'c12',\n containerNumber: '4321dkjkfdj',\n goods: [{\n weight: '322kg',\n quantity: '32'\n }]\n },\n {\n containerId: 'c13',\n containerNumber: '1212dkjkfdj',\n goods: [{\n weight: '13kg',\n quantity: '3'\n }]\n },\n {\n containerId: 'c13',\n containerNumber: '1212dkjkfdj',\n goods: [{\n weight: '13kg',\n quantity: '3'\n }]\n }\n]\n\nconst result = a.reduce((p, c) => {\n const found = p.findIndex(p => p.containerId === c.containerId);\n found === -1 ? p.push(c) : p[found].goods.push(c.goods);\n return p\n}, []);\n\nconsole.log(result);"
},
{
"answer_id": 74580134,
"author": "Asraf",
"author_id": 20361860,
"author_profile": "https://Stackoverflow.com/users/20361860",
"pm_score": 2,
"selected": false,
"text": ".reduce() containerId {containerId, containerNumber, goods} a[containerId] goods const arr = [{ containerId: 'c12', containerNumber: '4321dkjkfdj', goods: [{ weight: '32kg', quantity: '3' }] }, { containerId: 'c12', containerNumber: '4321dkjkfdj', goods: [{ weight: '322kg', quantity: '32' }] }, { containerId: 'c13', containerNumber: '1212dkjkfdj', goods: [{ weight: '13kg', quantity: '3' }] }, { containerId: 'c13', containerNumber: '1212dkjkfdj', goods: [{ weight: '13kg', quantity: '3' }] } ]\n\nconst res = arr.reduce((a,{containerId, containerNumber, goods}) => ((a[containerId] ??= {containerId, containerNumber, goods: []}).goods = [...a[containerId].goods, ...goods],a), {});\nconsole.log(Object.values(res)); .as-console-wrapper { max-height: 100% !important }"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74579763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9700487/"
] |
74,579,779
|
<p>I'm tasked to create an intrepreter for c#</p>
<p>basically I want to split this string:</p>
<p><code>"multiply (add 5 5) 5"</code></p>
<p>into an array of string:</p>
<p><code>["multiply", "(add 5 5)", "5"]</code></p>
<p>if I'm using string.Split based on delimiter of space: " ", the result will be:</p>
<p><code>["multiply", "(add", "5", "5)", "5"]</code>
which is not what I'm expecting</p>
<p>Is this achievable in C#?</p>
<p>Edit:
I also need to support nested expression:</p>
<p><code>"multiply (add (add 2 5) 5) 5"</code></p>
<p>For example above, needs to become:</p>
<p><code>["multiply", "(add (add 2 5) 5)", 5]</code></p>
|
[
{
"answer_id": 74579821,
"author": "Layhout",
"author_id": 17308201,
"author_profile": "https://Stackoverflow.com/users/17308201",
"pm_score": 0,
"selected": false,
"text": "const a = [\n {\n containerId: 'c12',\n containerNumber: '4321dkjkfdj',\n goods: [{\n weight: '32kg',\n quantity: '3'\n }]\n },\n {\n containerId: 'c12',\n containerNumber: '4321dkjkfdj',\n goods: [{\n weight: '322kg',\n quantity: '32'\n }]\n },\n {\n containerId: 'c13',\n containerNumber: '1212dkjkfdj',\n goods: [{\n weight: '13kg',\n quantity: '3'\n }]\n },\n {\n containerId: 'c13',\n containerNumber: '1212dkjkfdj',\n goods: [{\n weight: '13kg',\n quantity: '3'\n }]\n }\n]\n\nconst result = a.reduce((p, c) => {\n const found = p.findIndex(p => p.containerId === c.containerId);\n found === -1 ? p.push(c) : p[found].goods.push(c.goods);\n return p\n}, []);\n\nconsole.log(result);"
},
{
"answer_id": 74580134,
"author": "Asraf",
"author_id": 20361860,
"author_profile": "https://Stackoverflow.com/users/20361860",
"pm_score": 2,
"selected": false,
"text": ".reduce() containerId {containerId, containerNumber, goods} a[containerId] goods const arr = [{ containerId: 'c12', containerNumber: '4321dkjkfdj', goods: [{ weight: '32kg', quantity: '3' }] }, { containerId: 'c12', containerNumber: '4321dkjkfdj', goods: [{ weight: '322kg', quantity: '32' }] }, { containerId: 'c13', containerNumber: '1212dkjkfdj', goods: [{ weight: '13kg', quantity: '3' }] }, { containerId: 'c13', containerNumber: '1212dkjkfdj', goods: [{ weight: '13kg', quantity: '3' }] } ]\n\nconst res = arr.reduce((a,{containerId, containerNumber, goods}) => ((a[containerId] ??= {containerId, containerNumber, goods: []}).goods = [...a[containerId].goods, ...goods],a), {});\nconsole.log(Object.values(res)); .as-console-wrapper { max-height: 100% !important }"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74579779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11817809/"
] |
74,579,786
|
<p>I'm using the Stripe extension in Firebase to create subscriptions in a NextJS web app.</p>
<p>My goal is to create a link for a returning user to edit their payments in Stripe without authenticating again (they are already auth in my web app and Firebase recognizes the auth).</p>
<p>I'm using the test mode of Stripe and I have a test customer and test products.</p>
<h2>I've tried</h2>
<ul>
<li><p>The Firebase Stripe extension library does not have any function which can just return a billing portal link: <a href="https://github.com/stripe/stripe-firebase-extensions/blob/next/firestore-stripe-web-sdk/markdown/firestore-stripe-payments.md" rel="nofollow noreferrer">https://github.com/stripe/stripe-firebase-extensions/blob/next/firestore-stripe-web-sdk/markdown/firestore-stripe-payments.md</a></p>
</li>
<li><p>Use the NextJS recommended import of Stripe foudn in this <a href="https://vercel.com/guides/getting-started-with-nextjs-typescript-stripe#step-2:-creating-a-checkoutsession-and-redirecting-to-stripe-checkout" rel="nofollow noreferrer">Vercel blog</a></p>
<p>First I setup the import for Stripe-JS: <a href="https://github.com/vercel/next.js/blob/758990dc06da4c2913f42fdfdacfe53e29e56593/examples/with-stripe-typescript/utils/get-stripejs.ts" rel="nofollow noreferrer">https://github.com/vercel/next.js/blob/758990dc06da4c2913f42fdfdacfe53e29e56593/examples/with-stripe-typescript/utils/get-stripejs.ts</a></p>
<pre class="lang-js prettyprint-override"><code>export default function Settings() {
import stripe from "../../stripe_utils/get_stripejs"
async function editDashboard() {
const dashboardLink = await stripe.billingPortal.sessions.create({
customer: "cus_XXX",
})
}
console.log(dashboardLink.url)
return (
<Button
onClick={() => editDashboard()}>
DEBUG: See payments
</Button>
)
}
</code></pre>
<p>This would result in an error:</p>
<pre class="lang-js prettyprint-override"><code>TypeError: Cannot read properties of undefined (reading 'sessions')
</code></pre>
</li>
<li><p>Use the <code>stripe</code> library. This seemed like the most promising solution but from what I read this is a backend library though I tried to use on the front end. There were no errors with this approach but I figure it hangs on the <code>await</code></p>
<pre class="lang-js prettyprint-override"><code>import Stripe from "stripe"
const stripe = new Stripe(process.env.STRIPE_SECRET)
...
const session = await stripe.billingPortal.sessions.create({
customer: 'cus_XXX',
return_url: 'https://example.com/account',
})
console.log(session.url) // Does not reach here
</code></pre>
</li>
<li><p>Use a pre-made Stripe link to redirect but the user will have to authenticate on Stripe using their email (this works but I would rather have a short-lived link from Stripe)</p>
<pre class="lang-js prettyprint-override"><code><Button component={Link} to={"https://billing.stripe.com/p/login/XXX"}>
Edit payment info on Stripe
</Button>
</code></pre>
</li>
<li><p>Using POST HTTPS API call found at <a href="https://stripe.com/docs/api/authentication" rel="nofollow noreferrer">https://stripe.com/docs/api/authentication</a>. Unlike the previous options, this optional will register a Stripe Dashboard Log event.</p>
<pre class="lang-js prettyprint-override"><code>const response = await fetch("https://api.stripe.com/v1/billing_portal/sessions", {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json',
'Authorization': 'bearer sk_test_XXX',
'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *client
body: JSON.stringify(data), // body data type must match "Content-Type" header
})
</code></pre>
<p>The error is I'm missing some parameter <code>parameter_missing -customer</code>. So I'm closer to a resolution but I feel as if I should still be able to make the solution above work.</p>
</li>
</ul>
|
[
{
"answer_id": 74579821,
"author": "Layhout",
"author_id": 17308201,
"author_profile": "https://Stackoverflow.com/users/17308201",
"pm_score": 0,
"selected": false,
"text": "const a = [\n {\n containerId: 'c12',\n containerNumber: '4321dkjkfdj',\n goods: [{\n weight: '32kg',\n quantity: '3'\n }]\n },\n {\n containerId: 'c12',\n containerNumber: '4321dkjkfdj',\n goods: [{\n weight: '322kg',\n quantity: '32'\n }]\n },\n {\n containerId: 'c13',\n containerNumber: '1212dkjkfdj',\n goods: [{\n weight: '13kg',\n quantity: '3'\n }]\n },\n {\n containerId: 'c13',\n containerNumber: '1212dkjkfdj',\n goods: [{\n weight: '13kg',\n quantity: '3'\n }]\n }\n]\n\nconst result = a.reduce((p, c) => {\n const found = p.findIndex(p => p.containerId === c.containerId);\n found === -1 ? p.push(c) : p[found].goods.push(c.goods);\n return p\n}, []);\n\nconsole.log(result);"
},
{
"answer_id": 74580134,
"author": "Asraf",
"author_id": 20361860,
"author_profile": "https://Stackoverflow.com/users/20361860",
"pm_score": 2,
"selected": false,
"text": ".reduce() containerId {containerId, containerNumber, goods} a[containerId] goods const arr = [{ containerId: 'c12', containerNumber: '4321dkjkfdj', goods: [{ weight: '32kg', quantity: '3' }] }, { containerId: 'c12', containerNumber: '4321dkjkfdj', goods: [{ weight: '322kg', quantity: '32' }] }, { containerId: 'c13', containerNumber: '1212dkjkfdj', goods: [{ weight: '13kg', quantity: '3' }] }, { containerId: 'c13', containerNumber: '1212dkjkfdj', goods: [{ weight: '13kg', quantity: '3' }] } ]\n\nconst res = arr.reduce((a,{containerId, containerNumber, goods}) => ((a[containerId] ??= {containerId, containerNumber, goods: []}).goods = [...a[containerId].goods, ...goods],a), {});\nconsole.log(Object.values(res)); .as-console-wrapper { max-height: 100% !important }"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74579786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8278075/"
] |
74,579,793
|
<p>I'm new to AWS and a little perplexed as to the situation with var/www/html folder in an EC2 instance in which Apache has been installed.</p>
<p>After setting up an Elastic Beanstalk service and uploading the files, I see that these are stored in the regular var/www/html folder of the instance.</p>
<p>From reading AWS documents, it seems that instances may be deleted and re-provisioned, which is why use of an S3 bucket, EFS or EBS is recommended.</p>
<p>Why, then, is source code stored in the EC2 instance when using an apache server? Won't these files potentially be deleted with the instance?</p>
|
[
{
"answer_id": 74579821,
"author": "Layhout",
"author_id": 17308201,
"author_profile": "https://Stackoverflow.com/users/17308201",
"pm_score": 0,
"selected": false,
"text": "const a = [\n {\n containerId: 'c12',\n containerNumber: '4321dkjkfdj',\n goods: [{\n weight: '32kg',\n quantity: '3'\n }]\n },\n {\n containerId: 'c12',\n containerNumber: '4321dkjkfdj',\n goods: [{\n weight: '322kg',\n quantity: '32'\n }]\n },\n {\n containerId: 'c13',\n containerNumber: '1212dkjkfdj',\n goods: [{\n weight: '13kg',\n quantity: '3'\n }]\n },\n {\n containerId: 'c13',\n containerNumber: '1212dkjkfdj',\n goods: [{\n weight: '13kg',\n quantity: '3'\n }]\n }\n]\n\nconst result = a.reduce((p, c) => {\n const found = p.findIndex(p => p.containerId === c.containerId);\n found === -1 ? p.push(c) : p[found].goods.push(c.goods);\n return p\n}, []);\n\nconsole.log(result);"
},
{
"answer_id": 74580134,
"author": "Asraf",
"author_id": 20361860,
"author_profile": "https://Stackoverflow.com/users/20361860",
"pm_score": 2,
"selected": false,
"text": ".reduce() containerId {containerId, containerNumber, goods} a[containerId] goods const arr = [{ containerId: 'c12', containerNumber: '4321dkjkfdj', goods: [{ weight: '32kg', quantity: '3' }] }, { containerId: 'c12', containerNumber: '4321dkjkfdj', goods: [{ weight: '322kg', quantity: '32' }] }, { containerId: 'c13', containerNumber: '1212dkjkfdj', goods: [{ weight: '13kg', quantity: '3' }] }, { containerId: 'c13', containerNumber: '1212dkjkfdj', goods: [{ weight: '13kg', quantity: '3' }] } ]\n\nconst res = arr.reduce((a,{containerId, containerNumber, goods}) => ((a[containerId] ??= {containerId, containerNumber, goods: []}).goods = [...a[containerId].goods, ...goods],a), {});\nconsole.log(Object.values(res)); .as-console-wrapper { max-height: 100% !important }"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74579793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9158810/"
] |
74,579,824
|
<p>This is my original CSV file
<a href="https://i.stack.imgur.com/xtosi.jpg" rel="nofollow noreferrer">enter image description here</a></p>
<p>I want to make the genre column only the first tag. when I use</p>
<pre><code>dataframe['genre'] = dataframe['genre'].str.extract('^(.+?),')
</code></pre>
<p>it gets the string before the first comma but it also gets rid of columns without commas</p>
<p><a href="https://i.stack.imgur.com/RuuFD.jpg" rel="nofollow noreferrer">enter image description here</a></p>
<p>how can I make it keep the ones without commas as well?</p>
|
[
{
"answer_id": 74579844,
"author": "Dash",
"author_id": 11542834,
"author_profile": "https://Stackoverflow.com/users/11542834",
"pm_score": 1,
"selected": false,
"text": "dataframe['genre'] = dataframe['genre'].str.split(',').str[0]\n"
},
{
"answer_id": 74579869,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 3,
"selected": true,
"text": "dataframe['genre'] = dataframe['genre'].str.extract('^([^,]+)')\n ^ # match start of line\n([^,]+) # capture everything but comma\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74579824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20604215/"
] |
74,579,861
|
<p>I'm working in a Django project and it has a postgreSQL db.</p>
<p>I'm calling multiple times the model to filter the results:</p>
<pre><code>latest = Product.objects.all().order_by('-update_date')[:4]
best_rate = Product.objects.all().order_by('rating')[:2]
expensive = Product.objects.all().order_by('-price')[:3]
</code></pre>
<p>But I wonder if it's better for performance and resources consumption to just do 1 query and get all the objects from the database and do the filtering inside my Django view.</p>
<pre><code>all = Product.objects.all()
# Do some filtering here iterating over variable all
</code></pre>
<p>Which of these do you think would be the best approximation? Or do you have a better option?</p>
|
[
{
"answer_id": 74579844,
"author": "Dash",
"author_id": 11542834,
"author_profile": "https://Stackoverflow.com/users/11542834",
"pm_score": 1,
"selected": false,
"text": "dataframe['genre'] = dataframe['genre'].str.split(',').str[0]\n"
},
{
"answer_id": 74579869,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 3,
"selected": true,
"text": "dataframe['genre'] = dataframe['genre'].str.extract('^([^,]+)')\n ^ # match start of line\n([^,]+) # capture everything but comma\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74579861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9672537/"
] |
74,579,935
|
<p>We want to migrate some spreadsheets from Google sheets to Excel. We figured out how to manage all the needed formulas, except one: <code>SPLIT</code>.</p>
<p>Here is a public view link to a sample file, which shows you how we currently do this in Google sheets:
<a href="https://docs.google.com/spreadsheets/d/1D1ceuF28CqMtr0tEPdAQNLSvvuFMFAQE54fopS2wvAo/edit?usp=sharing" rel="nofollow noreferrer">https://docs.google.com/spreadsheets/d/1D1ceuF28CqMtr0tEPdAQNLSvvuFMFAQE54fopS2wvAo/edit?usp=sharing</a></p>
<p>Column B contains, for each record, a list of the record's favorite charitable causes, such as Animal welfare, Cancer, Digital divide, Environment, Human Rights, Hunger, Medical research, etc. A cell in that column might contain no content, one cause, or as many as 16 causes, each on a separate line within that cell. The Google delimiter for those line breaks within a cell is "char(10)." (I do not know if Excel uses the same for a line break).</p>
<p>In Google sheets, our formula in column C is
<code>=if(len(B2)=0,"",split(B2,char(10)))</code>. The first part just makes sure that we do not get a #VALUE error if the cell is empty.</p>
<p>We are familiar with the 'Text to Columns' menu options, but we need a formula in column C such that everything gets updated automatically whenever the content of column B is changed; we cannot do it manually each time.</p>
<p>Please note that the number of entries in column B is inconsistent, as is the length of each element.</p>
<p>How can we do this?</p>
|
[
{
"answer_id": 74579844,
"author": "Dash",
"author_id": 11542834,
"author_profile": "https://Stackoverflow.com/users/11542834",
"pm_score": 1,
"selected": false,
"text": "dataframe['genre'] = dataframe['genre'].str.split(',').str[0]\n"
},
{
"answer_id": 74579869,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 3,
"selected": true,
"text": "dataframe['genre'] = dataframe['genre'].str.extract('^([^,]+)')\n ^ # match start of line\n([^,]+) # capture everything but comma\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74579935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10602249/"
] |
74,579,938
|
<p>I want to preserve references during function calls in C++. In The following example the function <code>baz</code> creates two classes: <code>Foo</code> and <code>Bar</code>. The class <code>foo</code> is then passed to <code>Bar</code> as reference but instead of keeping <code>foo</code> until <code>Bar</code> is destroyed, it is destroyed after function execution.</p>
<p>In all other cases the <code>foo</code> references stays until the referencing <code>Bar</code> class is destroyed.</p>
<p>My question now: is there a way of preserving references inside of classes until they are destroyed without new/delete or do I have to go the buffer-overflow way ?</p>
<p>Also what is the sense of references when they create such faulty behavior, because I can't safely access <code>Foo</code> references in <code>Bar</code> like this.</p>
<p>What I want is either pass a default (null, <code>nofoo</code>) class to <code>Bar</code> or a customized one without keeping track of new/delete because I am planning of passing a whole bunch of different classes without the memory overhead derivation would cause. Similar to a container based behavior.</p>
<pre><code>class Foo
{
private:
int size;
int state;
int property;
float value;
public:
Foo ( int s )
{
size = s;
state = 0;
property = 0;
value = 0.0;
print ( "class Foo constructed with size: %i\n", size );
}
~Foo ( )
{
print ( "class Foo destructed with size: %i\n", size );
}
};
Foo nofoo ( 0 );
class Bar
{
private:
Foo &fooref;
public:
Bar ( Foo &ref = nofoo ) : fooref ( ref )
{
print ( "class Bar constructed with foo: %i, nofoo: %i\n", (Foo *)&fooref, (void *)&ref==(void *)&nofoo );
}
~Bar ( )
{
print ( "class Bar destructed with foo: %i\n", (Foo *)&fooref );
}
};
Foo faz()
{
print ( "function faz called\n" );
Foo ret ( 2 );
return ret; // Foo is not destroyed here
}
Bar baz()
{
print ( "function baz called\n" );
Foo foo4 ( 4 );
Bar ret ( foo4 );
return ret; // Foo is destroyed here but stays as reference in Bar
}
int main ()
{
print ( "test code started\n" );
Foo foo ( 1 );
Bar bar ( foo );
print ( "size of foo: %i\n", sizeof(foo) );
print ( "size of bar: %i\n", sizeof(bar) );
Foo fooref = faz();
print ( "size of fooref=faz(): %i\n", sizeof(fooref) );
Bar bar2;
print ( "size of bar2: %i\n", sizeof(bar2) );
Bar barref = baz();
print ( "size of barref=baz(): %i\n", sizeof(barref) );
return 0;
}
</code></pre>
<p>Output of this code:</p>
<pre><code>test code started
class Foo constructed with size: 1
class Bar constructed with foo: -96188384, nofoo: 0
size of foo: 16
size of bar: 8
function faz called
class Foo constructed with size: 2
size of fooref=faz(): 16
class Bar constructed with foo: 1977483344, nofoo: 1
size of bar2: 8
function baz called
class Foo constructed with size: 4
class Bar constructed with foo: -96188480, nofoo: 0
class Foo destructed with size: 4
size of barref=baz(): 8
class Bar destructed with foo: -96188480
class Bar destructed with foo: 1977483344
class Foo destructed with size: 2
class Bar destructed with foo: -96188384
class Foo destructed with size: 1
class Foo destructed with size: 0
</code></pre>
<p>One could use pointers instead of references, but references are (at least should be) safer. Whenever I would call a member of a <code>Foo</code> pointer I have to check if it is valid.</p>
<p>A way could be <code>unique_ptr<></code> template type which, at least, keeps track of deletion. But still I would have to check for <code>nullptr</code>. What I require is some kind of <code>unique_ptr</code> for references.</p>
|
[
{
"answer_id": 74579999,
"author": "rokuz",
"author_id": 20599616,
"author_profile": "https://Stackoverflow.com/users/20599616",
"pm_score": 0,
"selected": false,
"text": "Foo foo4 ( 4 ); Foo Bar delete"
},
{
"answer_id": 74580464,
"author": "Dean Johnson",
"author_id": 6324364,
"author_profile": "https://Stackoverflow.com/users/6324364",
"pm_score": 3,
"selected": true,
"text": "baz foo4"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74579938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11875359/"
] |
74,579,960
|
<p>i want to make a grid of image by 3 like instagram based on user upload. the streambuilder is not displaying any data from firestore.
i already separate the stream so its not inside the streambuilder.</p>
<p>this is the code</p>
<pre><code>import 'dart:io';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
File? imageFile;
String? imageUrl;
final FirebaseAuth _auth = FirebaseAuth.instance;
String? myImage;
String? myName;
String buttonName = 'click';
int currentIndex = 0;
final icon = CupertinoIcons.chat_bubble_2;
final _constructed = FirebaseFirestore.instance
.collection('fotoupload')
.orderBy("createAt", descending: true)
.snapshots(); //construct stream first
//final Stream<QuerySnapshot> _constructed = FirebaseFirestore.instance
// .collection('fotoupload')
// .orderBy("createAt", descending: true)
// .snapshots();
void read_userInfo() async {
FirebaseAuth.instance.currentUser!;
FirebaseFirestore.instance
.collection('users')
.doc(FirebaseAuth.instance.currentUser!.uid)
.get()
.then<dynamic>((DocumentSnapshot snapshot) async {
myImage = snapshot.get('userImage');
myName = snapshot.get('name');
});
}
@override
void initState() {
// TODO: implement initState
super.initState();
read_userInfo(); // refresh and read the user info both myName and myImage
}
Widget gridViewWidget(String docId, String img, String userImg, String name,
DateTime date, String userId, int downloads) {
return GridView.count(
primary: false,
padding: EdgeInsets.all(5),
crossAxisSpacing: 1,
crossAxisCount: 1,
children: [
GestureDetector(
onTap: () {
//createOwnerDetails
},
child: Center(
child: Text(date.toString()),
),
),
GestureDetector(
onTap: () {
//createOwnerDetails
},
child: Image.network(
img,
fit: BoxFit.cover,
),
),
Center(child: Text(userId)),
],
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: StreamBuilder<QuerySnapshot>(
stream: _constructed,
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
} else if (snapshot.connectionState == ConnectionState.active) {
if (snapshot.data!.docs.isNotEmpty) {
return GridView.builder(
itemCount: snapshot.data!.docs.length,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3),
itemBuilder: (BuildContext context, int index) {
return gridViewWidget(
snapshot.data!.docs[index].id,
snapshot.data!.docs[index]['Image'],
snapshot.data!.docs[index]['userImage'],
snapshot.data!.docs[index]['name'],
snapshot.data!.docs[index]['createAt '].toDate(),
snapshot.data!.docs[index]['uid'],
snapshot.data!.docs[index]['downloads'],
);
},
);
} else {
return Center(
child: Text(
'There is no tasks',
style: TextStyle(fontSize: 20),
),
);
}
}
return Center(
child: Text(
'Something went wrong',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 30),
),
);
},
),
);
}
}
</code></pre>
<p>does anyone have suggestion? the streambuilder is not displaying the data. and its shows "There is no task".</p>
<p><a href="https://i.stack.imgur.com/EVpZE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EVpZE.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/pHqd6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pHqd6.png" alt="Debug Console" /></a></p>
|
[
{
"answer_id": 74579999,
"author": "rokuz",
"author_id": 20599616,
"author_profile": "https://Stackoverflow.com/users/20599616",
"pm_score": 0,
"selected": false,
"text": "Foo foo4 ( 4 ); Foo Bar delete"
},
{
"answer_id": 74580464,
"author": "Dean Johnson",
"author_id": 6324364,
"author_profile": "https://Stackoverflow.com/users/6324364",
"pm_score": 3,
"selected": true,
"text": "baz foo4"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74579960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19826650/"
] |
74,579,995
|
<p>I am trying switch to a different screen in Flutter project using onPressed but it is not generating any outcome not sure what is the reason.</p>
<p>Here is the homescreen page:</p>
<pre><code> onPressed: () {
const User_Profile();
print("Hello");
},
</code></pre>
<p>Here is the user profile:</p>
<pre><code>class User_Profile extends StatefulWidget {
const User_Profile({Key? key}) : super(key: key);
@override
State<User_Profile> createState() => _user_profileState();
}
class _user_profileState extends State<User_Profile> {
@override
Widget build(BuildContext context) {
return const Text("User Profile");
}
}
</code></pre>
<p>Question:
How to switch screens using Onpressed? What am I doing wrong noting that the word Hello for debugging is printed everytime.</p>
|
[
{
"answer_id": 74580032,
"author": "Ravindra S. Patil",
"author_id": 13997210,
"author_profile": "https://Stackoverflow.com/users/13997210",
"pm_score": 2,
"selected": false,
"text": "Navigator.push ElevatedButton(\n onPressed: () {\n Navigator.push(\n context,\n MaterialPageRoute(\n builder: (context) => User_Profile(),\n ),\n );\n },\n child: const Text('User Profile'),\n ),\n"
},
{
"answer_id": 74580035,
"author": "aminjafari-dev",
"author_id": 19699656,
"author_profile": "https://Stackoverflow.com/users/19699656",
"pm_score": 3,
"selected": true,
"text": "Navigator.push(context, MaterialPageRoute(builder: (context)=>User_profile()));\n onPressed: () {\n Navigator.push(context, MaterialPageRoute(builder: (context)=>User_profile()));\n },\n onPressed: () {\n const User_Profile();\n print(\"Hello\");\n },\n"
},
{
"answer_id": 74581206,
"author": "Amirali_Eric_J",
"author_id": 8388842,
"author_profile": "https://Stackoverflow.com/users/8388842",
"pm_score": 2,
"selected": false,
"text": "Navigator.push Navigator.push(\n context,\n MaterialPageRoute(\n builder: (context) => User_Profile(),\n ),\n );\n User_Profile(name: 'yourName') Navigator.pushNamed Future<void> main() async {\n WidgetsFlutterBinding.ensureInitialized();\n runApp(\n MyApp(),\n );\n}\nclass MyApp extends StatefulWidget {\n MyApp({Key? key}) : super(key: key);\n\n @override\n _MyAppState createState() => _MyAppState();\n}\n\nclass _MyAppState extends State<MyApp> {\n @override\n Widget build(BuildContext context) {\n return MaterialApp(\n debugShowCheckedModeBanner: false,\n theme: ThemeData(\n canvasColor: Colors.transparent,\n ),\n initialRoute: '/',\n routes: {\n '/': (context) => Splash(),\n '/user_profile': (context) => User_Profile(),\n },\n );\n }\n}\n '/user_profile' Navigator.pushNamed arguments Navigator.pushNamed(\n context,\n '/user_profile',\n arguments: {\"name\" : \"yourName\"},);\n var arguments = ModalRoute.of(context)!.settings.arguments as Map;\nvar name = arguments['name'] as String;\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74579995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14574691/"
] |
74,580,008
|
<p>i am trying to remove all paddings (top + bottom) for a text inside a block using Bootstrap 5.</p>
<p>when using html without Bootstrap, setting <code>padding: 0px</code> does exactly what i expect:</p>
<p><code><div style="padding: 0px; background-color: gray;">no bootstrap</div></code> // works!</p>
<p>however, the moment i use Bootstrap, the padding is never 0, even after setting class <code>my-0</code>. there is always extra padding that seems to be added regardless.</p>
<p><code><div class="my-0 bg-info">using bootstrap my-0</div></code> // doesn't work</p>
<p>using style to override the padding to 0 also doesn't work when the Bootstrap css is included.</p>
<p><code><div class="my-0 bg-info" style="padding: 0px !important;">using bootstrap my-0</div></code> // doesn't work</p>
<p>is there a solution here?</p>
|
[
{
"answer_id": 74580070,
"author": "Imran Mohammed",
"author_id": 7102863,
"author_profile": "https://Stackoverflow.com/users/7102863",
"pm_score": 0,
"selected": false,
"text": "<div class=\"p-0 m-0 bg-info\">Will remove all Paddings and margins (no extra space inside and outside div)</div>\n <div class=\"p-0 bg-info\">Will remove all Paddings (no extra space inside div)</div>\n"
},
{
"answer_id": 74580094,
"author": "malaccan",
"author_id": 6212776,
"author_profile": "https://Stackoverflow.com/users/6212776",
"pm_score": 1,
"selected": false,
"text": "line-height"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74580008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6212776/"
] |
74,580,010
|
<p>On creating / cloning Spring project using IDEA Ultimate, i always get PKIX path validation failed: java.security.cert.CertPathValidatorException: validity check failed</p>
<p><a href="https://i.stack.imgur.com/ehn6g.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ehn6g.png" alt="Error on start" /></a></p>
<p>Here is the full error message</p>
<pre><code> problem occurred configuring root project 'cuanku'.
> Could not resolve all files for configuration ':classpath'.
> Could not resolve org.springframework.boot:spring-boot-buildpack-platform:2.7.5.
Required by:
project : > org.springframework.boot:org.springframework.boot.gradle.plugin:2.7.5 > org.springframework.boot:spring-boot-gradle-plugin:2.7.5
> Could not resolve org.springframework.boot:spring-boot-buildpack-platform:2.7.5.
> Could not get resource 'https://plugins.gradle.org/m2/org/springframework/boot/spring-boot-buildpack-platform/2.7.5/spring-boot-buildpack-platform-2.7.5.pom'.
> Could not GET 'https://jcenter.bintray.com/org/springframework/boot/spring-boot-buildpack-platform/2.7.5/spring-boot-buildpack-platform-2.7.5.pom'.
> PKIX path validation failed: java.security.cert.CertPathValidatorException: validity check failed
> Could not resolve org.springframework.boot:spring-boot-loader-tools:2.7.5.
Required by:
project : > org.springframework.boot:org.springframework.boot.gradle.plugin:2.7.5 > org.springframework.boot:spring-boot-gradle-plugin:2.7.5
> Could not resolve org.springframework.boot:spring-boot-loader-tools:2.7.5.
> Could not get resource 'https://plugins.gradle.org/m2/org/springframework/boot/spring-boot-loader-tools/2.7.5/spring-boot-loader-tools-2.7.5.pom'.
> Could not GET 'https://jcenter.bintray.com/org/springframework/boot/spring-boot-loader-tools/2.7.5/spring-boot-loader-tools-2.7.5.pom'.
> PKIX path validation failed: java.security.cert.CertPathValidatorException: validity check failed
> Could not resolve org.apache.commons:commons-compress:1.21.
Required by:
project : > org.springframework.boot:org.springframework.boot.gradle.plugin:2.7.5 > org.springframework.boot:spring-boot-gradle-plugin:2.7.5
> Could not resolve org.apache.commons:commons-compress:1.21.
> Could not get resource 'https://plugins.gradle.org/m2/org/apache/commons/commons-compress/1.21/commons-compress-1.21.pom'.
> Could not GET 'https://jcenter.bintray.com/org/apache/commons/commons-compress/1.21/commons-compress-1.21.pom'.
> PKIX path validation failed: java.security.cert.CertPathValidatorException: validity check failed
> Could not resolve org.springframework:spring-core:5.3.23.
Required by:
project : > org.springframework.boot:org.springframework.boot.gradle.plugin:2.7.5 > org.springframework.boot:spring-boot-gradle-plugin:2.7.5
> Could not resolve org.springframework:spring-core:5.3.23.
> Could not get resource 'https://plugins.gradle.org/m2/org/springframework/spring-core/5.3.23/spring-core-5.3.23.pom'.
> Could not GET 'https://jcenter.bintray.com/org/springframework/spring-core/5.3.23/spring-core-5.3.23.pom'.
> PKIX path validation failed: java.security.cert.CertPathValidatorException: validity check failed
</code></pre>
<p>I can't seem to find answers related on this problem, there's alot of PKIX path validation failed out there, but i can't seem to find the solution for my problem.</p>
|
[
{
"answer_id": 74580751,
"author": "Dev Lens",
"author_id": 13121943,
"author_profile": "https://Stackoverflow.com/users/13121943",
"pm_score": 1,
"selected": false,
"text": "systemProp.http.ssl.insecure=true\nsystemProp.http.ssl.allowall=true\nsystemProp.http.ssl.ignore.validity.dates=true\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74580010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15513319/"
] |
74,580,049
|
<p>so you see the code here its working fine. But there is error that prevents be from building it. check the code</p>
<p>im trying to assign onChange to onChange so when user press a key it will show up in the text field. Currently using <code>onChange={onChange}</code> it works in browser and for run dev but wont build. And when I find any solution/change whats its equal to the browser breaks or stops accepting text input. Very frustrating this is last thing I need to deploy app.</p>
<pre><code>import {useState} from 'react'
type Props = {
label: string
placeholder?: string
onChange: (e?: Event) => void
name?: string
value?: any
}
export const TextField = ({ label, onChange, placeholder, name, value }: Props) => {
const [inputs, setInputs] = useState({})
const handleChange = (event: any) => {
const name = event.target.name
const value = event.target.value
setInputs(values => ({...values, [name]: value}))
}
const handleSubmit = (event: any) => {
event.preventDefault()
console.log(inputs)
}
return (
<div style={{width:'100%'}}>
<div className='text-sm my-2'>{label}</div>
<input
className='border-blue-200 border-2 rounded focus:ring-blue-200 focus:border-blue-200 focus:outline-none px-2'
style={{ height: '45px', maxWidth: '280px', width: '100%', backgroundColor: '#0D0D0D' }}
placeholder={placeholder}
onChange={onChange}
name={name}
value={value}
/>
</div>
)
}
</code></pre>
<p>and there is following error</p>
<pre><code>[{
"resource": "/d:/dropship/src/components/TextFiled.tsx",
"owner": "typescript",
"code": "2322",
"severity": 8,
"message": "Type '(e?: Event | undefined) => void' is not assignable to type 'ChangeEventHandler<HTMLInputElement>'.\n Types of parameters 'e' and 'event' are incompatible.\n Type 'ChangeEvent<HTMLInputElement>' is missing the following properties from type 'Event': cancelBubble, composed, returnValue, srcElement, and 7 more.",
"source": "ts",
"startLineNumber": 33,
"startColumn": 9,
"endLineNumber": 33,
"endColumn": 17,
"relatedInformation": [
{
"startLineNumber": 2254,
"startColumn": 9,
"endLineNumber": 2254,
"endColumn": 17,
"message": "The expected type comes from property 'onChange' which is declared here on type 'DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>'",
"resource": "/d:/dropship/node_modules/@types/react/index.d.ts"
}
]
},{
"resource": "/d:/dropship/src/components/TextFiled.tsx",
"owner": "typescript",
"code": "6133",
"severity": 4,
"message": "'handleChange' is declared but its value is never read.",
"source": "ts",
"startLineNumber": 17,
"startColumn": 9,
"endLineNumber": 17,
"endColumn": 21,
"tags": [
1
]
},{
"resource": "/d:/dropship/src/components/TextFiled.tsx",
"owner": "typescript",
"code": "6133",
"severity": 4,
"message": "'handleSubmit' is declared but its value is never read.",
"source": "ts",
"startLineNumber": 22,
"startColumn": 9,
"endLineNumber": 22,
"endColumn": 21,
"tags": [
1
]
}]
</code></pre>
<p>i have tried many changes but I cannot get this error to go away. If anyone is react expert will be greatly appreciated.</p>
|
[
{
"answer_id": 74580067,
"author": "GMKHussain",
"author_id": 4689036,
"author_profile": "https://Stackoverflow.com/users/4689036",
"pm_score": 0,
"selected": false,
"text": "onChange={handleChange}\n"
},
{
"answer_id": 74580216,
"author": "Elvis Ohemeng Gyaase",
"author_id": 16387398,
"author_profile": "https://Stackoverflow.com/users/16387398",
"pm_score": 2,
"selected": true,
"text": "handleSubmit handleChange handleSubmit handleChange import { ChangeEvent, useState } from \"react\";\n\ntype Props = {\n label: string;\n placeholder?: string;\n onChange: (e?:Event) => void;\n name?: string;\n value?: any;\n};\n\nexport const TextField = ({\n label,\n onChange,\n placeholder,\n name,\n value,\n}: Props) => {\n const [inputs, setInputs] = useState({});\n const handleChange = (event: any) => {\n const targetName = event.target.name;\n const targetValue = event.target.value;\n setInputs((values) => ({ ...values, [targetName]: targetValue }));\n onChange(event);\n };\n const handleSubmit = (event: any) => {\n event.preventDefault();\n console.log(inputs);\n };\n return (\n <div style={{ width: \"100%\" }}>\n <div className=\"text-sm my-2\">{label}</div>\n <input\n className=\"border-blue-200 border-2 rounded focus:ring-blue-200 focus:border-blue-200 focus:outline-none px-2\"\n style={{\n height: \"45px\",\n maxWidth: \"280px\",\n width: \"100%\",\n backgroundColor: \"#0D0D0D\",\n }}\n placeholder={placeholder}\n onChange={handleChange}\n name={name}\n value={value}\n />\n </div>\n );\n}; <script src=\"https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js\"></script>"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74580049",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19934976/"
] |
74,580,074
|
<p>I am using Java in my project. I see code like below and not able to understand the flow.</p>
<pre><code>public static void main(String[] args) {
Person p1 = new Person("test1");
Person p2 = new Person("test2");
List<Person> l = List.of(p1, p2);
var count = l.stream().filter(checkMethod(Person::getName)).count();
System.out.println(count);
}
public static final <T> Predicate<T> checkMethod(Function<? super T, ?> keyExtractor) {
Objects.requireNonNull(keyExtractor);
final var seen = ConcurrentHashMap.newKeySet();
return t -> seen.add(keyExtractor.apply(t));
}
Person.java
public class Person {
Person(String name) {
this.name = name;
}
private String name;
//getters and setters for name
}
}
</code></pre>
<p>It identifies the count of unique name from list of person objects. I see check method is called only once. But usually filter method will be executed for each items in list.</p>
<p>Is it like entire list of persons is sent to check method and called only once?</p>
|
[
{
"answer_id": 74580067,
"author": "GMKHussain",
"author_id": 4689036,
"author_profile": "https://Stackoverflow.com/users/4689036",
"pm_score": 0,
"selected": false,
"text": "onChange={handleChange}\n"
},
{
"answer_id": 74580216,
"author": "Elvis Ohemeng Gyaase",
"author_id": 16387398,
"author_profile": "https://Stackoverflow.com/users/16387398",
"pm_score": 2,
"selected": true,
"text": "handleSubmit handleChange handleSubmit handleChange import { ChangeEvent, useState } from \"react\";\n\ntype Props = {\n label: string;\n placeholder?: string;\n onChange: (e?:Event) => void;\n name?: string;\n value?: any;\n};\n\nexport const TextField = ({\n label,\n onChange,\n placeholder,\n name,\n value,\n}: Props) => {\n const [inputs, setInputs] = useState({});\n const handleChange = (event: any) => {\n const targetName = event.target.name;\n const targetValue = event.target.value;\n setInputs((values) => ({ ...values, [targetName]: targetValue }));\n onChange(event);\n };\n const handleSubmit = (event: any) => {\n event.preventDefault();\n console.log(inputs);\n };\n return (\n <div style={{ width: \"100%\" }}>\n <div className=\"text-sm my-2\">{label}</div>\n <input\n className=\"border-blue-200 border-2 rounded focus:ring-blue-200 focus:border-blue-200 focus:outline-none px-2\"\n style={{\n height: \"45px\",\n maxWidth: \"280px\",\n width: \"100%\",\n backgroundColor: \"#0D0D0D\",\n }}\n placeholder={placeholder}\n onChange={handleChange}\n name={name}\n value={value}\n />\n </div>\n );\n}; <script src=\"https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js\"></script>"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74580074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/646276/"
] |
74,580,083
|
<p>In my JavaScript learning journey, I encountered a complex problem that lasted more than 24 hours to research and try several published solutions, but unfortunately, I did not succeed in solving my problem. Which tempted me to write this reply to solve this complex problem for me!</p>
<pre class="lang-js prettyprint-override"><code>class db{
async findOne(search){
try {
const doc = this.collection.doc(search).get();
return get.data()
} catch (error) {
console.error(Error(red(error)).message);
process.exit(1)
}
}
}
</code></pre>
<p>Output</p>
<pre class="lang-js prettyprint-override"><code>Promise { <pending> }
</code></pre>
<p>What I really want is for the output to be done without using <code>then</code> and be like the following output:</p>
<pre class="lang-json prettyprint-override"><code>{
name:'Johan',
age:'15',
}
</code></pre>
|
[
{
"answer_id": 74580067,
"author": "GMKHussain",
"author_id": 4689036,
"author_profile": "https://Stackoverflow.com/users/4689036",
"pm_score": 0,
"selected": false,
"text": "onChange={handleChange}\n"
},
{
"answer_id": 74580216,
"author": "Elvis Ohemeng Gyaase",
"author_id": 16387398,
"author_profile": "https://Stackoverflow.com/users/16387398",
"pm_score": 2,
"selected": true,
"text": "handleSubmit handleChange handleSubmit handleChange import { ChangeEvent, useState } from \"react\";\n\ntype Props = {\n label: string;\n placeholder?: string;\n onChange: (e?:Event) => void;\n name?: string;\n value?: any;\n};\n\nexport const TextField = ({\n label,\n onChange,\n placeholder,\n name,\n value,\n}: Props) => {\n const [inputs, setInputs] = useState({});\n const handleChange = (event: any) => {\n const targetName = event.target.name;\n const targetValue = event.target.value;\n setInputs((values) => ({ ...values, [targetName]: targetValue }));\n onChange(event);\n };\n const handleSubmit = (event: any) => {\n event.preventDefault();\n console.log(inputs);\n };\n return (\n <div style={{ width: \"100%\" }}>\n <div className=\"text-sm my-2\">{label}</div>\n <input\n className=\"border-blue-200 border-2 rounded focus:ring-blue-200 focus:border-blue-200 focus:outline-none px-2\"\n style={{\n height: \"45px\",\n maxWidth: \"280px\",\n width: \"100%\",\n backgroundColor: \"#0D0D0D\",\n }}\n placeholder={placeholder}\n onChange={handleChange}\n name={name}\n value={value}\n />\n </div>\n );\n}; <script src=\"https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js\"></script>"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74580083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19574722/"
] |
74,580,132
|
<p>I would like a keyboard shortcut to copy the full path of the currently open file. Do I need to add a new key binding, or is there an already existing shortcut?</p>
<p>I'm using a Mac.</p>
|
[
{
"answer_id": 74580149,
"author": "Dash",
"author_id": 11542834,
"author_profile": "https://Stackoverflow.com/users/11542834",
"pm_score": 2,
"selected": true,
"text": "Preferences > Keyboard Shortcuts @command:copyFilePath"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74580132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4493564/"
] |
74,580,139
|
<p><strong>This is a live demo of my calculator: <a href="https://kepplin.github.io/odin-calculator/" rel="nofollow noreferrer">https://kepplin.github.io/odin-calculator/</a></strong></p>
<p>After the equals button is pressed and the calculation is displayed, if a number button is pressed, then instead of starting a new calculation, the calculator evaluates with the operator of the previous calculation.</p>
<p>I have 3 global variables: <em>num1</em>, <em>num2</em>, <em>operator</em>. As well as a previous display and current display.</p>
<p>Example of the problem (step-by-step):</p>
<p>12</p>
<pre><code>console.log(num1) // 12
console.log(num2) //
console.log(operator) //
</code></pre>
<p>12 +</p>
<pre><code>console.log(num1) //
console.log(num2) // 12
console.log(operator) // +
</code></pre>
<p>12 + 4</p>
<pre><code>console.log(num1) // 4
console.log(num2) // 12
console.log(operator) // +
</code></pre>
<p>After the '=' button is pressed, the calculator displays:</p>
<p>16</p>
<pre><code>console.log(num1) //
console.log(num2) // 16
console.log(operator) // +
</code></pre>
<p>The calculator immediately evaluates if there are values for <em>num1</em>, <em>num2</em>, and <em>operator</em>. The problem comes here, if the user wants to start a different calculation (e.g, 5 - 4):</p>
<p>5</p>
<pre><code>console.log(num1) // 5
console.log(num2) // 16
console.log(operator) // +
</code></pre>
<p>5 -</p>
<pre><code>console.log(num1) //
console.log(num2) // 21
console.log(operator) // -
</code></pre>
<p>The calculator did 5 + 16. I want the values of num1, num2 and operator to be reset back to ' ' if a number button is pressed after the calculator has evaluated (only for a number button not an operator button).</p>
<p>An example of the behaviour I want is this:</p>
<p><a href="https://mike-monta.github.io/calculator-pro/" rel="nofollow noreferrer">https://mike-monta.github.io/calculator-pro/</a></p>
<p><a href="https://github.com/Mike-Monta/calculator-pro" rel="nofollow noreferrer">https://github.com/Mike-Monta/calculator-pro</a></p>
<p>Here's my code:</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calculator</title>
<link rel="stylesheet" href="style.css">
<link rel="icon" type="image/x-icon" href="img/favicon.ico">
</head>
<body>
<div class="calcBody">
<div class="calcDisplay">
<div class="screenDisplay">
<div class="prevDisplay"></div>
<div class="currentDisplay">0</div>
</div>
</div>
<div class="buttonsBody">
<div class="numberButtons">
<!--Row 1-->
<button class="clearButton inputButton" data-all="AC"><span class="buttonsText">AC</span></button>
<button class="deleteButton inputButton" data-all="C"><span class="buttonsText">C</span></button>
<button class="percentButton inputButton" data-all="%" data-operator="%"><span class="buttonsText">%</span></button>
<button class="divideButton inputButton" data-all="÷" data-operator="÷"><span class="buttonsText">÷</span></button>
<!--Row 2-->
<button class="sevenButton inputButton" data-all="7" data-num="7"><span class="buttonsText">7</span></button>
<button class="eightButton inputButton" data-all="8" data-num="8"><span class="buttonsText">8</span></button>
<button class="nineButton inputButton" data-all="9" data-num="9"><span class="buttonsText">9</span></button>
<button class="multiplyButton inputButton" data-all="×" data-operator="×"><span class="buttonsText">×</span></button>
<!--Row 3-->
<button class="fourButton inputButton" data-all="4" data-num="4"><span class="buttonsText">4</span></button>
<button class="fiveButton inputButton" data-all="5" data-num="5"><span class="buttonsText">5</span></button>
<button class="sixButton inputButton" data-all="6" data-num="6"><span class="buttonsText">6</span></button>
<button class="minusButton inputButton" data-all="-" data-operator="-"><span class="buttonsText">-</span></button>
<!--Row 4-->
<button class="oneButton inputButton" data-all="1" data-num="1"><span class="buttonsText">1</span></button>
<button class="twoButton inputButton" data-all="2" data-num="2"><span class="buttonsText">2</span></button>
<button class="threeButton inputButton" data-all="3" data-num="3"><span class="buttonsText">3</span></button>
<button class="plusButton inputButton" data-all="+" data-operator="+"><span class="buttonsText">+</span></button>
<!--Row 5 -->
<button class="doubleZeroButton inputButton" data-all="00" data-num="00"><span class="buttonsText">00</span></button>
<button class="zeroButton inputButton" data-all="0" data-num="0"><span class="buttonsText">0</span></button>
<button class="decimalButton inputButton" data-all="."><span class="buttonsText">.</span></button>
<button class="equalsButton inputButton" data-all="="><span class="buttonsText">=</span></button>
</div>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
</code></pre>
<pre><code>const prevDisplay = document.querySelector('.prevDisplay');
const currentDisplay = document.querySelector('.currentDisplay');
const inputButton = document.querySelectorAll('.inputButton');
const divideButton = document.querySelector('.divideButton');
const equalsButton = document.querySelector('.equalsButton');
const operatorButton = document.querySelectorAll('[data-operator]');
const numberButton = document.querySelectorAll('[data-num]');
const clearButton = document.querySelector('.clearButton');
const deleteButton = document.querySelector('.deleteButton');
const decimalButton = document.querySelector('.decimalButton')
//Global variables
let num1 = "";
let operator = "";
let num2 = "";
let removeDot;
//Current display
numberButton.forEach((btn) => {
btn.addEventListener('click', (e) => {
handleNumber(e.target.textContent);
})
}
)
function handleNumber(number){
if (num1.length <= 21){
num1 += number;
currentDisplay.textContent = num1;
}
}
//Previous display
operatorButton.forEach((btn) => {
btn.addEventListener('click', (e) => {
handleOperator(e.target.textContent);
})
})
function handleOperator(op){
if (num1 == '' && num2 == ''){
num1 = '0';
}
else if (operator == '' && num2 !== ''){
num2 = ''
}
else if (num2 === "") {
num2 = num1;
operatorCheck(op);
} else if (num1 === "") {
operatorCheck(op);
} else {
operate();
operator = op;
currentDisplay.textContent = "0";
prevDisplay.textContent = num2 + " " + operator;
}
}
function operatorCheck(text) {
operator = text;
prevDisplay.textContent = num2 + " " + operator;
currentDisplay.textContent = "0";
num1 = "";
}
//Clear button
function clearCalc(){
prevDisplay.textContent = '';
currentDisplay.textContent = '';
num1 = '';
num2 = '';
operator = '';
}
clearButton.addEventListener('click', clearCalc)
//Delete button
function deleteCalc(){
num1 = num1.slice(0, currentDisplay.textContent.length - 1)
currentDisplay.textContent = currentDisplay.textContent.slice(0, currentDisplay.textContent.length - 1)
}
deleteButton.addEventListener('click', deleteCalc)
//Equals button
function equalsCalc(){
if (num1 != '' && num2 != ''){
operate()
}
}
equalsButton.addEventListener('click', equalsCalc)
//Decimal button
function decimalCalc(){
if (num1.includes('.') == false){
currentDisplay.textContent = currentDisplay.textContent + '.'
num1 = num1 + '.'
}
}
decimalButton.addEventListener('click', decimalCalc)
//Doing the calculation
function calcPercent(num1, num2){
return (num2 / 100) * num1
}
function calcDivide(num1, num2){
return num2 / num1
}
function calcMultiply(num1, num2){
return num1 * num2
}
function calcSubtract(num1, num2){
return num2 - num1
}
function calcAdd(num1, num2){
return num1 + num2
}
function operate() {
num1 = Number(num1)
num2 = Number(num2)
switch (operator) {
case '+':
num2 = calcAdd(num1, num2)
break
case '-':
num2 = calcSubtract(num1, num2)
break
case '×':
num2 = calcMultiply(num1, num2)
break
case '%':
num2 = calcPercent(num1, num2)
break
case '÷':
num2 = num2.toString();
if (num1 == 0){
num2 = "Error, you can't divide by 0"
} else{
num2 = calcDivide(num1, num2);
}
break
}
num2 = roundNum(num2)
prevDisplay.textContent = "";
currentDisplay.textContent = num2;
num1 = '';
}
//Round Number
function roundNum(num){
return Math.round(num * 1000000) / 1000000;
}
//Event listeners for key presses
window.addEventListener('keydown', removeDot = function(e){
switch (e.key){
case "7":
handleNumber(7)
break
case "8":
handleNumber(8)
break
case "9":
handleNumber(9)
break
case "4":
handleNumber(4)
break
case "5":
handleNumber(5)
break
case "6":
handleNumber(6)
break
case "1":
handleNumber(1)
break
case "2":
handleNumber(2)
break
case "3":
handleNumber(3)
break
case "0":
handleNumber(0)
break
case ")":
handleNumber(00)
break
case "Delete":
clearCalc();
break
case "+":
handleOperator('+')
break
case "-":
handleOperator('-')
break
case "*":
handleOperator('×')
break
case "/":
handleOperator('÷')
break
case "%":
handleOperator('%')
break
case ".":
decimalCalc();
break
case "Backspace":
deleteCalc();
break
case "Enter":
e.preventDefault();
equalsCalc();
break
}
}, true)
</code></pre>
|
[
{
"answer_id": 74643699,
"author": "Alex Badea",
"author_id": 11309337,
"author_profile": "https://Stackoverflow.com/users/11309337",
"pm_score": 0,
"selected": false,
"text": "typeof num2 !== 'string' function handleNumber(number) {\n if (typeof num2 !== 'string' && operator === '') num2 = ''; // Add this line\n if (num1.length <= 21) {\n num1 += number;\n currentDisplay.textContent = num1;\n }\n }\n"
},
{
"answer_id": 74657255,
"author": "dangarfield",
"author_id": 3265253,
"author_profile": "https://Stackoverflow.com/users/3265253",
"pm_score": 2,
"selected": true,
"text": "= handleNumber num2 ...\n\nfunction handleNumber(number) {\n if (num1.length <= 21) {\n num1 += number;\n currentDisplay.textContent = num1;\n }\n if (operator === '=') { // <-- Added\n num2 = ''\n }\n}\n\n...\n\nfunction equalsCalc() {\n if (num1 != '' && num2 != '') {\n operate()\n operator = '=' // <-- Added\n }\n}\n\n...\n const prevDisplay = document.querySelector('.prevDisplay');\nconst currentDisplay = document.querySelector('.currentDisplay');\nconst inputButton = document.querySelectorAll('.inputButton');\nconst divideButton = document.querySelector('.divideButton');\nconst equalsButton = document.querySelector('.equalsButton');\nconst operatorButton = document.querySelectorAll('[data-operator]');\nconst numberButton = document.querySelectorAll('[data-num]');\nconst clearButton = document.querySelector('.clearButton');\nconst deleteButton = document.querySelector('.deleteButton');\nconst decimalButton = document.querySelector('.decimalButton')\n//Global variables\nlet num1 = \"\";\nlet operator = \"\";\nlet num2 = \"\";\nlet removeDot;\n//Current display\nnumberButton.forEach((btn) => {\n btn.addEventListener('click', (e) => {\n handleNumber(e.target.textContent);\n })\n})\n\nfunction handleNumber(number) {\n console.log('handleNumber', num1, operator, num2, '->', number)\n if (num1.length <= 21) {\n num1 += number;\n currentDisplay.textContent = num1;\n }\n if (operator === '=') {\n num2 = ''\n }\n console.log('handleNumber END', num1, operator, num2)\n}\n//Previous display\noperatorButton.forEach((btn) => {\n btn.addEventListener('click', (e) => {\n handleOperator(e.target.textContent);\n })\n})\n\nfunction handleOperator(op) {\n console.log('handleOperator', num1, operator, num2, '->', op)\n if (num1 == '' && num2 == '') {\n num1 = '';\n } else if (operator == '' && num2 !== '') {\n num2 = ''\n } else if (num2 === \"\") {\n num2 = num1;\n operatorCheck(op);\n } else if (num1 === \"\") {\n operatorCheck(op);\n } else {\n operate();\n operator = op;\n currentDisplay.textContent = \"0\";\n prevDisplay.textContent = num2 + \" \" + operator;\n }\n console.log('handleOperator END', num1, operator, num2)\n}\n\nfunction operatorCheck(text) {\n operator = text;\n prevDisplay.textContent = num2 + \" \" + operator;\n currentDisplay.textContent = \"0\";\n num1 = \"\";\n}\n//Clear button\nfunction clearCalc() {\n prevDisplay.textContent = '';\n currentDisplay.textContent = '';\n num1 = '';\n num2 = '';\n operator = '';\n}\nclearButton.addEventListener('click', clearCalc)\n//Delete button\nfunction deleteCalc() {\n num1 = num1.slice(0, currentDisplay.textContent.length - 1)\n currentDisplay.textContent = currentDisplay.textContent.slice(0, currentDisplay.textContent.length - 1)\n}\ndeleteButton.addEventListener('click', deleteCalc)\n//Equals button\nfunction equalsCalc() {\n if (num1 != '' && num2 != '') {\n operate()\n console.log('equalsCalc END', num1, operator, num2)\n operator = '='\n }\n}\nequalsButton.addEventListener('click', equalsCalc)\n//Decimal button\nfunction decimalCalc() {\n if (num1.includes('.') == false) {\n currentDisplay.textContent = currentDisplay.textContent + '.'\n num1 = num1 + '.'\n }\n}\ndecimalButton.addEventListener('click', decimalCalc)\n//Doing the calculation\nfunction calcPercent(num1, num2) {\n return (num2 / 100) * num1\n}\n\nfunction calcDivide(num1, num2) {\n return num2 / num1\n}\n\nfunction calcMultiply(num1, num2) {\n return num1 * num2\n}\n\nfunction calcSubtract(num1, num2) {\n return num2 - num1\n}\n\nfunction calcAdd(num1, num2) {\n return num1 + num2\n}\n\nfunction operate() {\n num1 = Number(num1)\n num2 = Number(num2)\n\n switch (operator) {\n case '+':\n num2 = calcAdd(num1, num2)\n break\n case '-':\n num2 = calcSubtract(num1, num2)\n break\n case '×':\n num2 = calcMultiply(num1, num2)\n break\n case '%':\n num2 = calcPercent(num1, num2)\n break\n case '÷':\n num2 = num2.toString();\n if (num1 == 0) {\n num2 = \"Error, you can't divide by 0\"\n } else {\n num2 = calcDivide(num1, num2);\n }\n break\n }\n num2 = roundNum(num2)\n prevDisplay.textContent = \"\";\n currentDisplay.textContent = num2;\n num1 = '';\n}\n//Round Number\nfunction roundNum(num) {\n return Math.round(num * 1000000) / 1000000;\n}\n//Event listeners for key presses\nwindow.addEventListener('keydown', removeDot = function(e) {\n switch (e.key) {\n case \"7\":\n handleNumber(7)\n break\n case \"8\":\n handleNumber(8)\n break\n case \"9\":\n handleNumber(9)\n break\n case \"4\":\n handleNumber(4)\n break\n case \"5\":\n handleNumber(5)\n break\n case \"6\":\n handleNumber(6)\n break\n case \"1\":\n handleNumber(1)\n break\n case \"2\":\n handleNumber(2)\n break\n case \"3\":\n handleNumber(3)\n break\n case \"0\":\n handleNumber(0)\n break\n case \")\":\n handleNumber(00)\n break\n case \"Delete\":\n clearCalc();\n break\n case \"+\":\n handleOperator('+')\n break\n case \"-\":\n handleOperator('-')\n break\n case \"*\":\n handleOperator('×')\n break\n case \"/\":\n handleOperator('÷')\n break\n case \"%\":\n handleOperator('%')\n break\n case \".\":\n decimalCalc();\n break\n case \"Backspace\":\n deleteCalc();\n break\n case \"Enter\":\n e.preventDefault();\n equalsCalc();\n break\n }\n}, true) html,\nbody {\n display: flex;\n justify-content: center;\n align-items: center;\n height: 100%;\n padding: 0;\n margin: 0;\n}\n\n.calcBody {\n display: flex;\n background-color: rgb(160, 160, 160);\n width: 500px;\n height: 700px;\n border: 2px solid black;\n border-radius: 35px;\n padding-bottom: 25px;\n transform: scale(0.95, 1);\n}\n\n.calcDisplay {\n display: flex;\n height: 200px;\n width: 500px;\n position: absolute;\n justify-content: center;\n border-radius: 30px;\n}\n\n.screenDisplay {\n display: flex;\n align-self: center;\n background-color: rgb(248, 248, 248);\n width: 450px;\n height: 150px;\n justify-content: flex-end;\n border-radius: 45px;\n border: 2px solid black;\n}\n\n.prevDisplay {\n display: flex;\n justify-content: flex-end;\n align-items: flex-start;\n width: 85%;\n height: 50px;\n position: absolute;\n margin-top: 50px;\n margin-right: 25px;\n font-family: Verdana, Geneva, Tahoma, sans-serif;\n font-size: 20px;\n margin-bottom: 20px;\n}\n\n.currentDisplay {\n display: flex;\n align-self: flex-end;\n justify-self: end;\n height: 50px;\n width: 100%;\n justify-content: flex-end;\n margin-right: 25px;\n font-family: Verdana, Geneva, Tahoma, sans-serif;\n font-size: 30px;\n margin-bottom: 20px;\n}\n\n.buttonsBody {\n display: flex;\n width: 100%;\n height: 500px;\n align-self: flex-end;\n justify-content: center;\n}\n\n.numberButtons {\n display: grid;\n grid-template-columns: 1fr 1fr 1fr 1fr;\n grid-template-rows: 1fr 1fr 1fr 1fr 1fr;\n width: 450px;\n height: 500px;\n gap: 5px;\n}\n\n.inputButton {\n padding: 0px;\n margin: 0px;\n border: 2px solid black;\n border-radius: 20px;\n transition: 200ms;\n background-color: rgb(231, 231, 231);\n}\n\n.buttonsText {\n padding: 0;\n margin: 0;\n font-size: 20px;\n font-family: Verdana, Geneva, Tahoma, sans-serif;\n transition: 150ms;\n display: flex;\n align-items: center;\n justify-content: center;\n height: 100%;\n width: 100%;\n}\n\n.inputButton:hover {\n background-color: darkgray;\n cursor: pointer;\n}\n\n.buttonsText:hover {\n font-size: 30px;\n}\n\n.clearButton,\n.deleteButton {\n background-color: rgb(223, 145, 145);\n}\n\n.equalsButton {\n background-color: rgb(187, 238, 110);\n} <div class=\"calcBody\">\n <div class=\"calcDisplay\">\n <div class=\"screenDisplay\">\n <div class=\"prevDisplay\"></div>\n <div class=\"currentDisplay\"></div>\n </div>\n </div>\n <div class=\"buttonsBody\">\n <div class=\"numberButtons\">\n <!--Row 1-->\n <button class=\"clearButton inputButton\" data-all=\"AC\"><span class=\"buttonsText\">AC</span></button>\n <button class=\"deleteButton inputButton\" data-all=\"C\"><span class=\"buttonsText\">C</span></button>\n <button class=\"percentButton inputButton\" data-all=\"%\" data-operator=\"%\"><span class=\"buttonsText\">%</span></button>\n <button class=\"divideButton inputButton\" data-all=\"÷\" data-operator=\"÷\"><span class=\"buttonsText\">÷</span></button>\n <!--Row 2-->\n <button class=\"sevenButton inputButton\" data-all=\"7\" data-num=\"7\"><span class=\"buttonsText\">7</span></button>\n <button class=\"eightButton inputButton\" data-all=\"8\" data-num=\"8\"><span class=\"buttonsText\">8</span></button>\n <button class=\"nineButton inputButton\" data-all=\"9\" data-num=\"9\"><span class=\"buttonsText\">9</span></button>\n <button class=\"multiplyButton inputButton\" data-all=\"×\" data-operator=\"×\"><span class=\"buttonsText\">×</span></button>\n <!--Row 3-->\n <button class=\"fourButton inputButton\" data-all=\"4\" data-num=\"4\"><span class=\"buttonsText\">4</span></button>\n <button class=\"fiveButton inputButton\" data-all=\"5\" data-num=\"5\"><span class=\"buttonsText\">5</span></button>\n <button class=\"sixButton inputButton\" data-all=\"6\" data-num=\"6\"><span class=\"buttonsText\">6</span></button>\n <button class=\"minusButton inputButton\" data-all=\"-\" data-operator=\"-\"><span class=\"buttonsText\">-</span></button>\n <!--Row 4-->\n <button class=\"oneButton inputButton\" data-all=\"1\" data-num=\"1\"><span class=\"buttonsText\">1</span></button>\n <button class=\"twoButton inputButton\" data-all=\"2\" data-num=\"2\"><span class=\"buttonsText\">2</span></button>\n <button class=\"threeButton inputButton\" data-all=\"3\" data-num=\"3\"><span class=\"buttonsText\">3</span></button>\n <button class=\"plusButton inputButton\" data-all=\"+\" data-operator=\"+\"><span class=\"buttonsText\">+</span></button>\n <!--Row 5 -->\n <button class=\"doubleZeroButton inputButton\" data-all=\"00\" data-num=\"00\"><span class=\"buttonsText\">00</span></button>\n <button class=\"zeroButton inputButton\" data-all=\"0\" data-num=\"0\"><span class=\"buttonsText\">0</span></button>\n <button class=\"decimalButton inputButton\" data-all=\".\"><span class=\"buttonsText\">.</span></button>\n <button class=\"equalsButton inputButton\" data-all=\"=\"><span class=\"buttonsText\">=</span></button>\n </div>\n </div>\n</div>"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74580139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15580759/"
] |
74,580,151
|
<p>I have this code and it the result is Unhandled Rejection (TypeError): Cannot read properties of undefined (reading 'data')</p>
<p>My create account function is giving me this error</p>
<pre><code>const sendRequest = async () => {
if (!name || !email || !password) return;
const user = { name, email, password };
const res = await axios
.post('/api/v1/auth/register', {
user,
})
.catch((err) => console.log(err));
const data = await res.data;
return data;
};
const handleSubmit = (e) => {
e.preventDefault();
sendRequest().then(() => setMloggi(true));
};
</code></pre>
|
[
{
"answer_id": 74643699,
"author": "Alex Badea",
"author_id": 11309337,
"author_profile": "https://Stackoverflow.com/users/11309337",
"pm_score": 0,
"selected": false,
"text": "typeof num2 !== 'string' function handleNumber(number) {\n if (typeof num2 !== 'string' && operator === '') num2 = ''; // Add this line\n if (num1.length <= 21) {\n num1 += number;\n currentDisplay.textContent = num1;\n }\n }\n"
},
{
"answer_id": 74657255,
"author": "dangarfield",
"author_id": 3265253,
"author_profile": "https://Stackoverflow.com/users/3265253",
"pm_score": 2,
"selected": true,
"text": "= handleNumber num2 ...\n\nfunction handleNumber(number) {\n if (num1.length <= 21) {\n num1 += number;\n currentDisplay.textContent = num1;\n }\n if (operator === '=') { // <-- Added\n num2 = ''\n }\n}\n\n...\n\nfunction equalsCalc() {\n if (num1 != '' && num2 != '') {\n operate()\n operator = '=' // <-- Added\n }\n}\n\n...\n const prevDisplay = document.querySelector('.prevDisplay');\nconst currentDisplay = document.querySelector('.currentDisplay');\nconst inputButton = document.querySelectorAll('.inputButton');\nconst divideButton = document.querySelector('.divideButton');\nconst equalsButton = document.querySelector('.equalsButton');\nconst operatorButton = document.querySelectorAll('[data-operator]');\nconst numberButton = document.querySelectorAll('[data-num]');\nconst clearButton = document.querySelector('.clearButton');\nconst deleteButton = document.querySelector('.deleteButton');\nconst decimalButton = document.querySelector('.decimalButton')\n//Global variables\nlet num1 = \"\";\nlet operator = \"\";\nlet num2 = \"\";\nlet removeDot;\n//Current display\nnumberButton.forEach((btn) => {\n btn.addEventListener('click', (e) => {\n handleNumber(e.target.textContent);\n })\n})\n\nfunction handleNumber(number) {\n console.log('handleNumber', num1, operator, num2, '->', number)\n if (num1.length <= 21) {\n num1 += number;\n currentDisplay.textContent = num1;\n }\n if (operator === '=') {\n num2 = ''\n }\n console.log('handleNumber END', num1, operator, num2)\n}\n//Previous display\noperatorButton.forEach((btn) => {\n btn.addEventListener('click', (e) => {\n handleOperator(e.target.textContent);\n })\n})\n\nfunction handleOperator(op) {\n console.log('handleOperator', num1, operator, num2, '->', op)\n if (num1 == '' && num2 == '') {\n num1 = '';\n } else if (operator == '' && num2 !== '') {\n num2 = ''\n } else if (num2 === \"\") {\n num2 = num1;\n operatorCheck(op);\n } else if (num1 === \"\") {\n operatorCheck(op);\n } else {\n operate();\n operator = op;\n currentDisplay.textContent = \"0\";\n prevDisplay.textContent = num2 + \" \" + operator;\n }\n console.log('handleOperator END', num1, operator, num2)\n}\n\nfunction operatorCheck(text) {\n operator = text;\n prevDisplay.textContent = num2 + \" \" + operator;\n currentDisplay.textContent = \"0\";\n num1 = \"\";\n}\n//Clear button\nfunction clearCalc() {\n prevDisplay.textContent = '';\n currentDisplay.textContent = '';\n num1 = '';\n num2 = '';\n operator = '';\n}\nclearButton.addEventListener('click', clearCalc)\n//Delete button\nfunction deleteCalc() {\n num1 = num1.slice(0, currentDisplay.textContent.length - 1)\n currentDisplay.textContent = currentDisplay.textContent.slice(0, currentDisplay.textContent.length - 1)\n}\ndeleteButton.addEventListener('click', deleteCalc)\n//Equals button\nfunction equalsCalc() {\n if (num1 != '' && num2 != '') {\n operate()\n console.log('equalsCalc END', num1, operator, num2)\n operator = '='\n }\n}\nequalsButton.addEventListener('click', equalsCalc)\n//Decimal button\nfunction decimalCalc() {\n if (num1.includes('.') == false) {\n currentDisplay.textContent = currentDisplay.textContent + '.'\n num1 = num1 + '.'\n }\n}\ndecimalButton.addEventListener('click', decimalCalc)\n//Doing the calculation\nfunction calcPercent(num1, num2) {\n return (num2 / 100) * num1\n}\n\nfunction calcDivide(num1, num2) {\n return num2 / num1\n}\n\nfunction calcMultiply(num1, num2) {\n return num1 * num2\n}\n\nfunction calcSubtract(num1, num2) {\n return num2 - num1\n}\n\nfunction calcAdd(num1, num2) {\n return num1 + num2\n}\n\nfunction operate() {\n num1 = Number(num1)\n num2 = Number(num2)\n\n switch (operator) {\n case '+':\n num2 = calcAdd(num1, num2)\n break\n case '-':\n num2 = calcSubtract(num1, num2)\n break\n case '×':\n num2 = calcMultiply(num1, num2)\n break\n case '%':\n num2 = calcPercent(num1, num2)\n break\n case '÷':\n num2 = num2.toString();\n if (num1 == 0) {\n num2 = \"Error, you can't divide by 0\"\n } else {\n num2 = calcDivide(num1, num2);\n }\n break\n }\n num2 = roundNum(num2)\n prevDisplay.textContent = \"\";\n currentDisplay.textContent = num2;\n num1 = '';\n}\n//Round Number\nfunction roundNum(num) {\n return Math.round(num * 1000000) / 1000000;\n}\n//Event listeners for key presses\nwindow.addEventListener('keydown', removeDot = function(e) {\n switch (e.key) {\n case \"7\":\n handleNumber(7)\n break\n case \"8\":\n handleNumber(8)\n break\n case \"9\":\n handleNumber(9)\n break\n case \"4\":\n handleNumber(4)\n break\n case \"5\":\n handleNumber(5)\n break\n case \"6\":\n handleNumber(6)\n break\n case \"1\":\n handleNumber(1)\n break\n case \"2\":\n handleNumber(2)\n break\n case \"3\":\n handleNumber(3)\n break\n case \"0\":\n handleNumber(0)\n break\n case \")\":\n handleNumber(00)\n break\n case \"Delete\":\n clearCalc();\n break\n case \"+\":\n handleOperator('+')\n break\n case \"-\":\n handleOperator('-')\n break\n case \"*\":\n handleOperator('×')\n break\n case \"/\":\n handleOperator('÷')\n break\n case \"%\":\n handleOperator('%')\n break\n case \".\":\n decimalCalc();\n break\n case \"Backspace\":\n deleteCalc();\n break\n case \"Enter\":\n e.preventDefault();\n equalsCalc();\n break\n }\n}, true) html,\nbody {\n display: flex;\n justify-content: center;\n align-items: center;\n height: 100%;\n padding: 0;\n margin: 0;\n}\n\n.calcBody {\n display: flex;\n background-color: rgb(160, 160, 160);\n width: 500px;\n height: 700px;\n border: 2px solid black;\n border-radius: 35px;\n padding-bottom: 25px;\n transform: scale(0.95, 1);\n}\n\n.calcDisplay {\n display: flex;\n height: 200px;\n width: 500px;\n position: absolute;\n justify-content: center;\n border-radius: 30px;\n}\n\n.screenDisplay {\n display: flex;\n align-self: center;\n background-color: rgb(248, 248, 248);\n width: 450px;\n height: 150px;\n justify-content: flex-end;\n border-radius: 45px;\n border: 2px solid black;\n}\n\n.prevDisplay {\n display: flex;\n justify-content: flex-end;\n align-items: flex-start;\n width: 85%;\n height: 50px;\n position: absolute;\n margin-top: 50px;\n margin-right: 25px;\n font-family: Verdana, Geneva, Tahoma, sans-serif;\n font-size: 20px;\n margin-bottom: 20px;\n}\n\n.currentDisplay {\n display: flex;\n align-self: flex-end;\n justify-self: end;\n height: 50px;\n width: 100%;\n justify-content: flex-end;\n margin-right: 25px;\n font-family: Verdana, Geneva, Tahoma, sans-serif;\n font-size: 30px;\n margin-bottom: 20px;\n}\n\n.buttonsBody {\n display: flex;\n width: 100%;\n height: 500px;\n align-self: flex-end;\n justify-content: center;\n}\n\n.numberButtons {\n display: grid;\n grid-template-columns: 1fr 1fr 1fr 1fr;\n grid-template-rows: 1fr 1fr 1fr 1fr 1fr;\n width: 450px;\n height: 500px;\n gap: 5px;\n}\n\n.inputButton {\n padding: 0px;\n margin: 0px;\n border: 2px solid black;\n border-radius: 20px;\n transition: 200ms;\n background-color: rgb(231, 231, 231);\n}\n\n.buttonsText {\n padding: 0;\n margin: 0;\n font-size: 20px;\n font-family: Verdana, Geneva, Tahoma, sans-serif;\n transition: 150ms;\n display: flex;\n align-items: center;\n justify-content: center;\n height: 100%;\n width: 100%;\n}\n\n.inputButton:hover {\n background-color: darkgray;\n cursor: pointer;\n}\n\n.buttonsText:hover {\n font-size: 30px;\n}\n\n.clearButton,\n.deleteButton {\n background-color: rgb(223, 145, 145);\n}\n\n.equalsButton {\n background-color: rgb(187, 238, 110);\n} <div class=\"calcBody\">\n <div class=\"calcDisplay\">\n <div class=\"screenDisplay\">\n <div class=\"prevDisplay\"></div>\n <div class=\"currentDisplay\"></div>\n </div>\n </div>\n <div class=\"buttonsBody\">\n <div class=\"numberButtons\">\n <!--Row 1-->\n <button class=\"clearButton inputButton\" data-all=\"AC\"><span class=\"buttonsText\">AC</span></button>\n <button class=\"deleteButton inputButton\" data-all=\"C\"><span class=\"buttonsText\">C</span></button>\n <button class=\"percentButton inputButton\" data-all=\"%\" data-operator=\"%\"><span class=\"buttonsText\">%</span></button>\n <button class=\"divideButton inputButton\" data-all=\"÷\" data-operator=\"÷\"><span class=\"buttonsText\">÷</span></button>\n <!--Row 2-->\n <button class=\"sevenButton inputButton\" data-all=\"7\" data-num=\"7\"><span class=\"buttonsText\">7</span></button>\n <button class=\"eightButton inputButton\" data-all=\"8\" data-num=\"8\"><span class=\"buttonsText\">8</span></button>\n <button class=\"nineButton inputButton\" data-all=\"9\" data-num=\"9\"><span class=\"buttonsText\">9</span></button>\n <button class=\"multiplyButton inputButton\" data-all=\"×\" data-operator=\"×\"><span class=\"buttonsText\">×</span></button>\n <!--Row 3-->\n <button class=\"fourButton inputButton\" data-all=\"4\" data-num=\"4\"><span class=\"buttonsText\">4</span></button>\n <button class=\"fiveButton inputButton\" data-all=\"5\" data-num=\"5\"><span class=\"buttonsText\">5</span></button>\n <button class=\"sixButton inputButton\" data-all=\"6\" data-num=\"6\"><span class=\"buttonsText\">6</span></button>\n <button class=\"minusButton inputButton\" data-all=\"-\" data-operator=\"-\"><span class=\"buttonsText\">-</span></button>\n <!--Row 4-->\n <button class=\"oneButton inputButton\" data-all=\"1\" data-num=\"1\"><span class=\"buttonsText\">1</span></button>\n <button class=\"twoButton inputButton\" data-all=\"2\" data-num=\"2\"><span class=\"buttonsText\">2</span></button>\n <button class=\"threeButton inputButton\" data-all=\"3\" data-num=\"3\"><span class=\"buttonsText\">3</span></button>\n <button class=\"plusButton inputButton\" data-all=\"+\" data-operator=\"+\"><span class=\"buttonsText\">+</span></button>\n <!--Row 5 -->\n <button class=\"doubleZeroButton inputButton\" data-all=\"00\" data-num=\"00\"><span class=\"buttonsText\">00</span></button>\n <button class=\"zeroButton inputButton\" data-all=\"0\" data-num=\"0\"><span class=\"buttonsText\">0</span></button>\n <button class=\"decimalButton inputButton\" data-all=\".\"><span class=\"buttonsText\">.</span></button>\n <button class=\"equalsButton inputButton\" data-all=\"=\"><span class=\"buttonsText\">=</span></button>\n </div>\n </div>\n</div>"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74580151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16540622/"
] |
74,580,166
|
<p>I have a bookstore project, and have 2 table: <code>publishers</code> and <code>books</code>.
These is my two migrate file for books and publishers.</p>
<pre><code><?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateBooksTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('books', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->integer('available_quantity');
$table->string('isbn');
$table->string('language');
$table->integer('total_pages');
$table->float('price');
$table->string('book_image');
$table->string('description')->nullable();
$table->date('published_date');
$table->unsignedBigInteger('publisher_id');
$table->foreign('publisher_id')->references('id')->on('publishers');
$table->unique('isbn');
$table->softDeletes();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('books');
}
}
</code></pre>
<pre><code><?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('publishers', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name')->unique();
$table->string('address');
$table->string('phone');
$table->string('description')->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('publishers');
}
};
</code></pre>
<p>As you see, <code>books</code> has a foreign key <code>publisher_id</code>, which has reference to <code>publishers</code> on <code>id</code>, so when I run <code>php artisan db:seed</code>,both tables will be seeded at the same time, but as we know, the <code>publishers</code> table should be seeded before <code>books</code> table be. So are there any way to seed tables orderly (not at the same time) ?</p>
|
[
{
"answer_id": 74643699,
"author": "Alex Badea",
"author_id": 11309337,
"author_profile": "https://Stackoverflow.com/users/11309337",
"pm_score": 0,
"selected": false,
"text": "typeof num2 !== 'string' function handleNumber(number) {\n if (typeof num2 !== 'string' && operator === '') num2 = ''; // Add this line\n if (num1.length <= 21) {\n num1 += number;\n currentDisplay.textContent = num1;\n }\n }\n"
},
{
"answer_id": 74657255,
"author": "dangarfield",
"author_id": 3265253,
"author_profile": "https://Stackoverflow.com/users/3265253",
"pm_score": 2,
"selected": true,
"text": "= handleNumber num2 ...\n\nfunction handleNumber(number) {\n if (num1.length <= 21) {\n num1 += number;\n currentDisplay.textContent = num1;\n }\n if (operator === '=') { // <-- Added\n num2 = ''\n }\n}\n\n...\n\nfunction equalsCalc() {\n if (num1 != '' && num2 != '') {\n operate()\n operator = '=' // <-- Added\n }\n}\n\n...\n const prevDisplay = document.querySelector('.prevDisplay');\nconst currentDisplay = document.querySelector('.currentDisplay');\nconst inputButton = document.querySelectorAll('.inputButton');\nconst divideButton = document.querySelector('.divideButton');\nconst equalsButton = document.querySelector('.equalsButton');\nconst operatorButton = document.querySelectorAll('[data-operator]');\nconst numberButton = document.querySelectorAll('[data-num]');\nconst clearButton = document.querySelector('.clearButton');\nconst deleteButton = document.querySelector('.deleteButton');\nconst decimalButton = document.querySelector('.decimalButton')\n//Global variables\nlet num1 = \"\";\nlet operator = \"\";\nlet num2 = \"\";\nlet removeDot;\n//Current display\nnumberButton.forEach((btn) => {\n btn.addEventListener('click', (e) => {\n handleNumber(e.target.textContent);\n })\n})\n\nfunction handleNumber(number) {\n console.log('handleNumber', num1, operator, num2, '->', number)\n if (num1.length <= 21) {\n num1 += number;\n currentDisplay.textContent = num1;\n }\n if (operator === '=') {\n num2 = ''\n }\n console.log('handleNumber END', num1, operator, num2)\n}\n//Previous display\noperatorButton.forEach((btn) => {\n btn.addEventListener('click', (e) => {\n handleOperator(e.target.textContent);\n })\n})\n\nfunction handleOperator(op) {\n console.log('handleOperator', num1, operator, num2, '->', op)\n if (num1 == '' && num2 == '') {\n num1 = '';\n } else if (operator == '' && num2 !== '') {\n num2 = ''\n } else if (num2 === \"\") {\n num2 = num1;\n operatorCheck(op);\n } else if (num1 === \"\") {\n operatorCheck(op);\n } else {\n operate();\n operator = op;\n currentDisplay.textContent = \"0\";\n prevDisplay.textContent = num2 + \" \" + operator;\n }\n console.log('handleOperator END', num1, operator, num2)\n}\n\nfunction operatorCheck(text) {\n operator = text;\n prevDisplay.textContent = num2 + \" \" + operator;\n currentDisplay.textContent = \"0\";\n num1 = \"\";\n}\n//Clear button\nfunction clearCalc() {\n prevDisplay.textContent = '';\n currentDisplay.textContent = '';\n num1 = '';\n num2 = '';\n operator = '';\n}\nclearButton.addEventListener('click', clearCalc)\n//Delete button\nfunction deleteCalc() {\n num1 = num1.slice(0, currentDisplay.textContent.length - 1)\n currentDisplay.textContent = currentDisplay.textContent.slice(0, currentDisplay.textContent.length - 1)\n}\ndeleteButton.addEventListener('click', deleteCalc)\n//Equals button\nfunction equalsCalc() {\n if (num1 != '' && num2 != '') {\n operate()\n console.log('equalsCalc END', num1, operator, num2)\n operator = '='\n }\n}\nequalsButton.addEventListener('click', equalsCalc)\n//Decimal button\nfunction decimalCalc() {\n if (num1.includes('.') == false) {\n currentDisplay.textContent = currentDisplay.textContent + '.'\n num1 = num1 + '.'\n }\n}\ndecimalButton.addEventListener('click', decimalCalc)\n//Doing the calculation\nfunction calcPercent(num1, num2) {\n return (num2 / 100) * num1\n}\n\nfunction calcDivide(num1, num2) {\n return num2 / num1\n}\n\nfunction calcMultiply(num1, num2) {\n return num1 * num2\n}\n\nfunction calcSubtract(num1, num2) {\n return num2 - num1\n}\n\nfunction calcAdd(num1, num2) {\n return num1 + num2\n}\n\nfunction operate() {\n num1 = Number(num1)\n num2 = Number(num2)\n\n switch (operator) {\n case '+':\n num2 = calcAdd(num1, num2)\n break\n case '-':\n num2 = calcSubtract(num1, num2)\n break\n case '×':\n num2 = calcMultiply(num1, num2)\n break\n case '%':\n num2 = calcPercent(num1, num2)\n break\n case '÷':\n num2 = num2.toString();\n if (num1 == 0) {\n num2 = \"Error, you can't divide by 0\"\n } else {\n num2 = calcDivide(num1, num2);\n }\n break\n }\n num2 = roundNum(num2)\n prevDisplay.textContent = \"\";\n currentDisplay.textContent = num2;\n num1 = '';\n}\n//Round Number\nfunction roundNum(num) {\n return Math.round(num * 1000000) / 1000000;\n}\n//Event listeners for key presses\nwindow.addEventListener('keydown', removeDot = function(e) {\n switch (e.key) {\n case \"7\":\n handleNumber(7)\n break\n case \"8\":\n handleNumber(8)\n break\n case \"9\":\n handleNumber(9)\n break\n case \"4\":\n handleNumber(4)\n break\n case \"5\":\n handleNumber(5)\n break\n case \"6\":\n handleNumber(6)\n break\n case \"1\":\n handleNumber(1)\n break\n case \"2\":\n handleNumber(2)\n break\n case \"3\":\n handleNumber(3)\n break\n case \"0\":\n handleNumber(0)\n break\n case \")\":\n handleNumber(00)\n break\n case \"Delete\":\n clearCalc();\n break\n case \"+\":\n handleOperator('+')\n break\n case \"-\":\n handleOperator('-')\n break\n case \"*\":\n handleOperator('×')\n break\n case \"/\":\n handleOperator('÷')\n break\n case \"%\":\n handleOperator('%')\n break\n case \".\":\n decimalCalc();\n break\n case \"Backspace\":\n deleteCalc();\n break\n case \"Enter\":\n e.preventDefault();\n equalsCalc();\n break\n }\n}, true) html,\nbody {\n display: flex;\n justify-content: center;\n align-items: center;\n height: 100%;\n padding: 0;\n margin: 0;\n}\n\n.calcBody {\n display: flex;\n background-color: rgb(160, 160, 160);\n width: 500px;\n height: 700px;\n border: 2px solid black;\n border-radius: 35px;\n padding-bottom: 25px;\n transform: scale(0.95, 1);\n}\n\n.calcDisplay {\n display: flex;\n height: 200px;\n width: 500px;\n position: absolute;\n justify-content: center;\n border-radius: 30px;\n}\n\n.screenDisplay {\n display: flex;\n align-self: center;\n background-color: rgb(248, 248, 248);\n width: 450px;\n height: 150px;\n justify-content: flex-end;\n border-radius: 45px;\n border: 2px solid black;\n}\n\n.prevDisplay {\n display: flex;\n justify-content: flex-end;\n align-items: flex-start;\n width: 85%;\n height: 50px;\n position: absolute;\n margin-top: 50px;\n margin-right: 25px;\n font-family: Verdana, Geneva, Tahoma, sans-serif;\n font-size: 20px;\n margin-bottom: 20px;\n}\n\n.currentDisplay {\n display: flex;\n align-self: flex-end;\n justify-self: end;\n height: 50px;\n width: 100%;\n justify-content: flex-end;\n margin-right: 25px;\n font-family: Verdana, Geneva, Tahoma, sans-serif;\n font-size: 30px;\n margin-bottom: 20px;\n}\n\n.buttonsBody {\n display: flex;\n width: 100%;\n height: 500px;\n align-self: flex-end;\n justify-content: center;\n}\n\n.numberButtons {\n display: grid;\n grid-template-columns: 1fr 1fr 1fr 1fr;\n grid-template-rows: 1fr 1fr 1fr 1fr 1fr;\n width: 450px;\n height: 500px;\n gap: 5px;\n}\n\n.inputButton {\n padding: 0px;\n margin: 0px;\n border: 2px solid black;\n border-radius: 20px;\n transition: 200ms;\n background-color: rgb(231, 231, 231);\n}\n\n.buttonsText {\n padding: 0;\n margin: 0;\n font-size: 20px;\n font-family: Verdana, Geneva, Tahoma, sans-serif;\n transition: 150ms;\n display: flex;\n align-items: center;\n justify-content: center;\n height: 100%;\n width: 100%;\n}\n\n.inputButton:hover {\n background-color: darkgray;\n cursor: pointer;\n}\n\n.buttonsText:hover {\n font-size: 30px;\n}\n\n.clearButton,\n.deleteButton {\n background-color: rgb(223, 145, 145);\n}\n\n.equalsButton {\n background-color: rgb(187, 238, 110);\n} <div class=\"calcBody\">\n <div class=\"calcDisplay\">\n <div class=\"screenDisplay\">\n <div class=\"prevDisplay\"></div>\n <div class=\"currentDisplay\"></div>\n </div>\n </div>\n <div class=\"buttonsBody\">\n <div class=\"numberButtons\">\n <!--Row 1-->\n <button class=\"clearButton inputButton\" data-all=\"AC\"><span class=\"buttonsText\">AC</span></button>\n <button class=\"deleteButton inputButton\" data-all=\"C\"><span class=\"buttonsText\">C</span></button>\n <button class=\"percentButton inputButton\" data-all=\"%\" data-operator=\"%\"><span class=\"buttonsText\">%</span></button>\n <button class=\"divideButton inputButton\" data-all=\"÷\" data-operator=\"÷\"><span class=\"buttonsText\">÷</span></button>\n <!--Row 2-->\n <button class=\"sevenButton inputButton\" data-all=\"7\" data-num=\"7\"><span class=\"buttonsText\">7</span></button>\n <button class=\"eightButton inputButton\" data-all=\"8\" data-num=\"8\"><span class=\"buttonsText\">8</span></button>\n <button class=\"nineButton inputButton\" data-all=\"9\" data-num=\"9\"><span class=\"buttonsText\">9</span></button>\n <button class=\"multiplyButton inputButton\" data-all=\"×\" data-operator=\"×\"><span class=\"buttonsText\">×</span></button>\n <!--Row 3-->\n <button class=\"fourButton inputButton\" data-all=\"4\" data-num=\"4\"><span class=\"buttonsText\">4</span></button>\n <button class=\"fiveButton inputButton\" data-all=\"5\" data-num=\"5\"><span class=\"buttonsText\">5</span></button>\n <button class=\"sixButton inputButton\" data-all=\"6\" data-num=\"6\"><span class=\"buttonsText\">6</span></button>\n <button class=\"minusButton inputButton\" data-all=\"-\" data-operator=\"-\"><span class=\"buttonsText\">-</span></button>\n <!--Row 4-->\n <button class=\"oneButton inputButton\" data-all=\"1\" data-num=\"1\"><span class=\"buttonsText\">1</span></button>\n <button class=\"twoButton inputButton\" data-all=\"2\" data-num=\"2\"><span class=\"buttonsText\">2</span></button>\n <button class=\"threeButton inputButton\" data-all=\"3\" data-num=\"3\"><span class=\"buttonsText\">3</span></button>\n <button class=\"plusButton inputButton\" data-all=\"+\" data-operator=\"+\"><span class=\"buttonsText\">+</span></button>\n <!--Row 5 -->\n <button class=\"doubleZeroButton inputButton\" data-all=\"00\" data-num=\"00\"><span class=\"buttonsText\">00</span></button>\n <button class=\"zeroButton inputButton\" data-all=\"0\" data-num=\"0\"><span class=\"buttonsText\">0</span></button>\n <button class=\"decimalButton inputButton\" data-all=\".\"><span class=\"buttonsText\">.</span></button>\n <button class=\"equalsButton inputButton\" data-all=\"=\"><span class=\"buttonsText\">=</span></button>\n </div>\n </div>\n</div>"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74580166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20138812/"
] |
74,580,180
|
<p>How to extract items from a 2d array.</p>
<pre><code>const array = [["1", "3"],["4", "3"]]
const itemToExclude = "3"
</code></pre>
<p>Use <code>itemToExclude</code> variable to exclude item from result (in this case <code>3</code>)</p>
<p><strong>Expected result</strong> is <code>["1", "4"]</code></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const array = [["1", "3"],["4", "3"]]
const itemToExclude = "3"
const result = array.map((item) => {
return item.map((subitem) => {
return subitem
// exclude itemToExclude
})
})
console.log(result)</code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74643699,
"author": "Alex Badea",
"author_id": 11309337,
"author_profile": "https://Stackoverflow.com/users/11309337",
"pm_score": 0,
"selected": false,
"text": "typeof num2 !== 'string' function handleNumber(number) {\n if (typeof num2 !== 'string' && operator === '') num2 = ''; // Add this line\n if (num1.length <= 21) {\n num1 += number;\n currentDisplay.textContent = num1;\n }\n }\n"
},
{
"answer_id": 74657255,
"author": "dangarfield",
"author_id": 3265253,
"author_profile": "https://Stackoverflow.com/users/3265253",
"pm_score": 2,
"selected": true,
"text": "= handleNumber num2 ...\n\nfunction handleNumber(number) {\n if (num1.length <= 21) {\n num1 += number;\n currentDisplay.textContent = num1;\n }\n if (operator === '=') { // <-- Added\n num2 = ''\n }\n}\n\n...\n\nfunction equalsCalc() {\n if (num1 != '' && num2 != '') {\n operate()\n operator = '=' // <-- Added\n }\n}\n\n...\n const prevDisplay = document.querySelector('.prevDisplay');\nconst currentDisplay = document.querySelector('.currentDisplay');\nconst inputButton = document.querySelectorAll('.inputButton');\nconst divideButton = document.querySelector('.divideButton');\nconst equalsButton = document.querySelector('.equalsButton');\nconst operatorButton = document.querySelectorAll('[data-operator]');\nconst numberButton = document.querySelectorAll('[data-num]');\nconst clearButton = document.querySelector('.clearButton');\nconst deleteButton = document.querySelector('.deleteButton');\nconst decimalButton = document.querySelector('.decimalButton')\n//Global variables\nlet num1 = \"\";\nlet operator = \"\";\nlet num2 = \"\";\nlet removeDot;\n//Current display\nnumberButton.forEach((btn) => {\n btn.addEventListener('click', (e) => {\n handleNumber(e.target.textContent);\n })\n})\n\nfunction handleNumber(number) {\n console.log('handleNumber', num1, operator, num2, '->', number)\n if (num1.length <= 21) {\n num1 += number;\n currentDisplay.textContent = num1;\n }\n if (operator === '=') {\n num2 = ''\n }\n console.log('handleNumber END', num1, operator, num2)\n}\n//Previous display\noperatorButton.forEach((btn) => {\n btn.addEventListener('click', (e) => {\n handleOperator(e.target.textContent);\n })\n})\n\nfunction handleOperator(op) {\n console.log('handleOperator', num1, operator, num2, '->', op)\n if (num1 == '' && num2 == '') {\n num1 = '';\n } else if (operator == '' && num2 !== '') {\n num2 = ''\n } else if (num2 === \"\") {\n num2 = num1;\n operatorCheck(op);\n } else if (num1 === \"\") {\n operatorCheck(op);\n } else {\n operate();\n operator = op;\n currentDisplay.textContent = \"0\";\n prevDisplay.textContent = num2 + \" \" + operator;\n }\n console.log('handleOperator END', num1, operator, num2)\n}\n\nfunction operatorCheck(text) {\n operator = text;\n prevDisplay.textContent = num2 + \" \" + operator;\n currentDisplay.textContent = \"0\";\n num1 = \"\";\n}\n//Clear button\nfunction clearCalc() {\n prevDisplay.textContent = '';\n currentDisplay.textContent = '';\n num1 = '';\n num2 = '';\n operator = '';\n}\nclearButton.addEventListener('click', clearCalc)\n//Delete button\nfunction deleteCalc() {\n num1 = num1.slice(0, currentDisplay.textContent.length - 1)\n currentDisplay.textContent = currentDisplay.textContent.slice(0, currentDisplay.textContent.length - 1)\n}\ndeleteButton.addEventListener('click', deleteCalc)\n//Equals button\nfunction equalsCalc() {\n if (num1 != '' && num2 != '') {\n operate()\n console.log('equalsCalc END', num1, operator, num2)\n operator = '='\n }\n}\nequalsButton.addEventListener('click', equalsCalc)\n//Decimal button\nfunction decimalCalc() {\n if (num1.includes('.') == false) {\n currentDisplay.textContent = currentDisplay.textContent + '.'\n num1 = num1 + '.'\n }\n}\ndecimalButton.addEventListener('click', decimalCalc)\n//Doing the calculation\nfunction calcPercent(num1, num2) {\n return (num2 / 100) * num1\n}\n\nfunction calcDivide(num1, num2) {\n return num2 / num1\n}\n\nfunction calcMultiply(num1, num2) {\n return num1 * num2\n}\n\nfunction calcSubtract(num1, num2) {\n return num2 - num1\n}\n\nfunction calcAdd(num1, num2) {\n return num1 + num2\n}\n\nfunction operate() {\n num1 = Number(num1)\n num2 = Number(num2)\n\n switch (operator) {\n case '+':\n num2 = calcAdd(num1, num2)\n break\n case '-':\n num2 = calcSubtract(num1, num2)\n break\n case '×':\n num2 = calcMultiply(num1, num2)\n break\n case '%':\n num2 = calcPercent(num1, num2)\n break\n case '÷':\n num2 = num2.toString();\n if (num1 == 0) {\n num2 = \"Error, you can't divide by 0\"\n } else {\n num2 = calcDivide(num1, num2);\n }\n break\n }\n num2 = roundNum(num2)\n prevDisplay.textContent = \"\";\n currentDisplay.textContent = num2;\n num1 = '';\n}\n//Round Number\nfunction roundNum(num) {\n return Math.round(num * 1000000) / 1000000;\n}\n//Event listeners for key presses\nwindow.addEventListener('keydown', removeDot = function(e) {\n switch (e.key) {\n case \"7\":\n handleNumber(7)\n break\n case \"8\":\n handleNumber(8)\n break\n case \"9\":\n handleNumber(9)\n break\n case \"4\":\n handleNumber(4)\n break\n case \"5\":\n handleNumber(5)\n break\n case \"6\":\n handleNumber(6)\n break\n case \"1\":\n handleNumber(1)\n break\n case \"2\":\n handleNumber(2)\n break\n case \"3\":\n handleNumber(3)\n break\n case \"0\":\n handleNumber(0)\n break\n case \")\":\n handleNumber(00)\n break\n case \"Delete\":\n clearCalc();\n break\n case \"+\":\n handleOperator('+')\n break\n case \"-\":\n handleOperator('-')\n break\n case \"*\":\n handleOperator('×')\n break\n case \"/\":\n handleOperator('÷')\n break\n case \"%\":\n handleOperator('%')\n break\n case \".\":\n decimalCalc();\n break\n case \"Backspace\":\n deleteCalc();\n break\n case \"Enter\":\n e.preventDefault();\n equalsCalc();\n break\n }\n}, true) html,\nbody {\n display: flex;\n justify-content: center;\n align-items: center;\n height: 100%;\n padding: 0;\n margin: 0;\n}\n\n.calcBody {\n display: flex;\n background-color: rgb(160, 160, 160);\n width: 500px;\n height: 700px;\n border: 2px solid black;\n border-radius: 35px;\n padding-bottom: 25px;\n transform: scale(0.95, 1);\n}\n\n.calcDisplay {\n display: flex;\n height: 200px;\n width: 500px;\n position: absolute;\n justify-content: center;\n border-radius: 30px;\n}\n\n.screenDisplay {\n display: flex;\n align-self: center;\n background-color: rgb(248, 248, 248);\n width: 450px;\n height: 150px;\n justify-content: flex-end;\n border-radius: 45px;\n border: 2px solid black;\n}\n\n.prevDisplay {\n display: flex;\n justify-content: flex-end;\n align-items: flex-start;\n width: 85%;\n height: 50px;\n position: absolute;\n margin-top: 50px;\n margin-right: 25px;\n font-family: Verdana, Geneva, Tahoma, sans-serif;\n font-size: 20px;\n margin-bottom: 20px;\n}\n\n.currentDisplay {\n display: flex;\n align-self: flex-end;\n justify-self: end;\n height: 50px;\n width: 100%;\n justify-content: flex-end;\n margin-right: 25px;\n font-family: Verdana, Geneva, Tahoma, sans-serif;\n font-size: 30px;\n margin-bottom: 20px;\n}\n\n.buttonsBody {\n display: flex;\n width: 100%;\n height: 500px;\n align-self: flex-end;\n justify-content: center;\n}\n\n.numberButtons {\n display: grid;\n grid-template-columns: 1fr 1fr 1fr 1fr;\n grid-template-rows: 1fr 1fr 1fr 1fr 1fr;\n width: 450px;\n height: 500px;\n gap: 5px;\n}\n\n.inputButton {\n padding: 0px;\n margin: 0px;\n border: 2px solid black;\n border-radius: 20px;\n transition: 200ms;\n background-color: rgb(231, 231, 231);\n}\n\n.buttonsText {\n padding: 0;\n margin: 0;\n font-size: 20px;\n font-family: Verdana, Geneva, Tahoma, sans-serif;\n transition: 150ms;\n display: flex;\n align-items: center;\n justify-content: center;\n height: 100%;\n width: 100%;\n}\n\n.inputButton:hover {\n background-color: darkgray;\n cursor: pointer;\n}\n\n.buttonsText:hover {\n font-size: 30px;\n}\n\n.clearButton,\n.deleteButton {\n background-color: rgb(223, 145, 145);\n}\n\n.equalsButton {\n background-color: rgb(187, 238, 110);\n} <div class=\"calcBody\">\n <div class=\"calcDisplay\">\n <div class=\"screenDisplay\">\n <div class=\"prevDisplay\"></div>\n <div class=\"currentDisplay\"></div>\n </div>\n </div>\n <div class=\"buttonsBody\">\n <div class=\"numberButtons\">\n <!--Row 1-->\n <button class=\"clearButton inputButton\" data-all=\"AC\"><span class=\"buttonsText\">AC</span></button>\n <button class=\"deleteButton inputButton\" data-all=\"C\"><span class=\"buttonsText\">C</span></button>\n <button class=\"percentButton inputButton\" data-all=\"%\" data-operator=\"%\"><span class=\"buttonsText\">%</span></button>\n <button class=\"divideButton inputButton\" data-all=\"÷\" data-operator=\"÷\"><span class=\"buttonsText\">÷</span></button>\n <!--Row 2-->\n <button class=\"sevenButton inputButton\" data-all=\"7\" data-num=\"7\"><span class=\"buttonsText\">7</span></button>\n <button class=\"eightButton inputButton\" data-all=\"8\" data-num=\"8\"><span class=\"buttonsText\">8</span></button>\n <button class=\"nineButton inputButton\" data-all=\"9\" data-num=\"9\"><span class=\"buttonsText\">9</span></button>\n <button class=\"multiplyButton inputButton\" data-all=\"×\" data-operator=\"×\"><span class=\"buttonsText\">×</span></button>\n <!--Row 3-->\n <button class=\"fourButton inputButton\" data-all=\"4\" data-num=\"4\"><span class=\"buttonsText\">4</span></button>\n <button class=\"fiveButton inputButton\" data-all=\"5\" data-num=\"5\"><span class=\"buttonsText\">5</span></button>\n <button class=\"sixButton inputButton\" data-all=\"6\" data-num=\"6\"><span class=\"buttonsText\">6</span></button>\n <button class=\"minusButton inputButton\" data-all=\"-\" data-operator=\"-\"><span class=\"buttonsText\">-</span></button>\n <!--Row 4-->\n <button class=\"oneButton inputButton\" data-all=\"1\" data-num=\"1\"><span class=\"buttonsText\">1</span></button>\n <button class=\"twoButton inputButton\" data-all=\"2\" data-num=\"2\"><span class=\"buttonsText\">2</span></button>\n <button class=\"threeButton inputButton\" data-all=\"3\" data-num=\"3\"><span class=\"buttonsText\">3</span></button>\n <button class=\"plusButton inputButton\" data-all=\"+\" data-operator=\"+\"><span class=\"buttonsText\">+</span></button>\n <!--Row 5 -->\n <button class=\"doubleZeroButton inputButton\" data-all=\"00\" data-num=\"00\"><span class=\"buttonsText\">00</span></button>\n <button class=\"zeroButton inputButton\" data-all=\"0\" data-num=\"0\"><span class=\"buttonsText\">0</span></button>\n <button class=\"decimalButton inputButton\" data-all=\".\"><span class=\"buttonsText\">.</span></button>\n <button class=\"equalsButton inputButton\" data-all=\"=\"><span class=\"buttonsText\">=</span></button>\n </div>\n </div>\n</div>"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74580180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3717114/"
] |
74,580,194
|
<p>I followed this tutorial on youtube for my school project. The app is able to display selected images from gallery but the recycler view have gaps in every row. What do I code to fix this app? help. <a href="https://i.stack.imgur.com/07V7b.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>here's my activity_main.xml</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:scrollbarStyle="insideInset"
android:scrollbars="vertical"
tools:context=".MainActivity">
<Button
android:id="@+id/pick"
android:layout_width="53dp"
android:layout_height="64dp"
android:layout_margin="12dp"
android:layout_weight="0"
android:backgroundTint="#FF5722"
android:text="+"
android:textSize="24sp"
app:cornerRadius="64dp" />
<TextView
android:id="@+id/totalPhotos"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0"
android:gravity="center"
android:textColor="#FFFFFF" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView_Gallery_Images"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_weight="1"
</LinearLayout>
</code></pre>
<p>RecyclerAdapter.java</p>
<pre><code>package com.example.mygram;
import android.media.Image;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private ArrayList<Uri> uriArrayList;
public RecyclerAdapter(ArrayList<Uri> uriArrayList) {
this.uriArrayList = uriArrayList;
}
@NonNull
@Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.custom_single_image,parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull RecyclerAdapter.ViewHolder holder, int position) {
holder.imageView.setImageURI(uriArrayList.get(position));
}
@Override
public int getItemCount() {
return uriArrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
public ViewHolder(@NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.image);
}
}
}
</code></pre>
<p>Custom <em>single images.xml</em></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<ImageView
android:id="@+id/image"
android:layout_width="match_parent"
android:layout_height="0dp"
android:scaleType="centerCrop"
app:layout_constraintDimensionRatio="1"
tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>
</code></pre>
<p>And here's the MainActivity.java</p>
<pre><code>package com.example.mygram;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
TextView textView;
Button pick;
ArrayList <Uri> uri = new ArrayList<>();
RecyclerAdapter adapter ;
private static final int Read_Permission = 101;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.totalPhotos);
recyclerView = findViewById(R.id.recyclerView_Gallery_Images);
pick = findViewById(R.id.pick);
adapter = new RecyclerAdapter(uri);
recyclerView.setLayoutManager(new GridLayoutManager(MainActivity.this,3));
recyclerView.setAdapter(adapter);
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Read_Permission);
}
pick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2){
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
}
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 1);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1 && resultCode == Activity.RESULT_OK){
if(data.getClipData() !=null) {
int x = data.getClipData().getItemCount();
for (int i = 0; i < x; i++) {
uri.add(data.getClipData().getItemAt(i).getUri());
}
adapter.notifyDataSetChanged();
textView.setText("Photos ("+uri.size()+")");
}else if (data.getData()!=null){
String imageURL=data.getData().getPath();
uri.add(Uri.parse(imageURL));
}
}
}
}
</code></pre>
<p>The concept of the app is instagram feed tester. I want to be able to display images like the grid in instagram but the gap is appearing preventing it to happen. help me please thankyou</p>
|
[
{
"answer_id": 74643699,
"author": "Alex Badea",
"author_id": 11309337,
"author_profile": "https://Stackoverflow.com/users/11309337",
"pm_score": 0,
"selected": false,
"text": "typeof num2 !== 'string' function handleNumber(number) {\n if (typeof num2 !== 'string' && operator === '') num2 = ''; // Add this line\n if (num1.length <= 21) {\n num1 += number;\n currentDisplay.textContent = num1;\n }\n }\n"
},
{
"answer_id": 74657255,
"author": "dangarfield",
"author_id": 3265253,
"author_profile": "https://Stackoverflow.com/users/3265253",
"pm_score": 2,
"selected": true,
"text": "= handleNumber num2 ...\n\nfunction handleNumber(number) {\n if (num1.length <= 21) {\n num1 += number;\n currentDisplay.textContent = num1;\n }\n if (operator === '=') { // <-- Added\n num2 = ''\n }\n}\n\n...\n\nfunction equalsCalc() {\n if (num1 != '' && num2 != '') {\n operate()\n operator = '=' // <-- Added\n }\n}\n\n...\n const prevDisplay = document.querySelector('.prevDisplay');\nconst currentDisplay = document.querySelector('.currentDisplay');\nconst inputButton = document.querySelectorAll('.inputButton');\nconst divideButton = document.querySelector('.divideButton');\nconst equalsButton = document.querySelector('.equalsButton');\nconst operatorButton = document.querySelectorAll('[data-operator]');\nconst numberButton = document.querySelectorAll('[data-num]');\nconst clearButton = document.querySelector('.clearButton');\nconst deleteButton = document.querySelector('.deleteButton');\nconst decimalButton = document.querySelector('.decimalButton')\n//Global variables\nlet num1 = \"\";\nlet operator = \"\";\nlet num2 = \"\";\nlet removeDot;\n//Current display\nnumberButton.forEach((btn) => {\n btn.addEventListener('click', (e) => {\n handleNumber(e.target.textContent);\n })\n})\n\nfunction handleNumber(number) {\n console.log('handleNumber', num1, operator, num2, '->', number)\n if (num1.length <= 21) {\n num1 += number;\n currentDisplay.textContent = num1;\n }\n if (operator === '=') {\n num2 = ''\n }\n console.log('handleNumber END', num1, operator, num2)\n}\n//Previous display\noperatorButton.forEach((btn) => {\n btn.addEventListener('click', (e) => {\n handleOperator(e.target.textContent);\n })\n})\n\nfunction handleOperator(op) {\n console.log('handleOperator', num1, operator, num2, '->', op)\n if (num1 == '' && num2 == '') {\n num1 = '';\n } else if (operator == '' && num2 !== '') {\n num2 = ''\n } else if (num2 === \"\") {\n num2 = num1;\n operatorCheck(op);\n } else if (num1 === \"\") {\n operatorCheck(op);\n } else {\n operate();\n operator = op;\n currentDisplay.textContent = \"0\";\n prevDisplay.textContent = num2 + \" \" + operator;\n }\n console.log('handleOperator END', num1, operator, num2)\n}\n\nfunction operatorCheck(text) {\n operator = text;\n prevDisplay.textContent = num2 + \" \" + operator;\n currentDisplay.textContent = \"0\";\n num1 = \"\";\n}\n//Clear button\nfunction clearCalc() {\n prevDisplay.textContent = '';\n currentDisplay.textContent = '';\n num1 = '';\n num2 = '';\n operator = '';\n}\nclearButton.addEventListener('click', clearCalc)\n//Delete button\nfunction deleteCalc() {\n num1 = num1.slice(0, currentDisplay.textContent.length - 1)\n currentDisplay.textContent = currentDisplay.textContent.slice(0, currentDisplay.textContent.length - 1)\n}\ndeleteButton.addEventListener('click', deleteCalc)\n//Equals button\nfunction equalsCalc() {\n if (num1 != '' && num2 != '') {\n operate()\n console.log('equalsCalc END', num1, operator, num2)\n operator = '='\n }\n}\nequalsButton.addEventListener('click', equalsCalc)\n//Decimal button\nfunction decimalCalc() {\n if (num1.includes('.') == false) {\n currentDisplay.textContent = currentDisplay.textContent + '.'\n num1 = num1 + '.'\n }\n}\ndecimalButton.addEventListener('click', decimalCalc)\n//Doing the calculation\nfunction calcPercent(num1, num2) {\n return (num2 / 100) * num1\n}\n\nfunction calcDivide(num1, num2) {\n return num2 / num1\n}\n\nfunction calcMultiply(num1, num2) {\n return num1 * num2\n}\n\nfunction calcSubtract(num1, num2) {\n return num2 - num1\n}\n\nfunction calcAdd(num1, num2) {\n return num1 + num2\n}\n\nfunction operate() {\n num1 = Number(num1)\n num2 = Number(num2)\n\n switch (operator) {\n case '+':\n num2 = calcAdd(num1, num2)\n break\n case '-':\n num2 = calcSubtract(num1, num2)\n break\n case '×':\n num2 = calcMultiply(num1, num2)\n break\n case '%':\n num2 = calcPercent(num1, num2)\n break\n case '÷':\n num2 = num2.toString();\n if (num1 == 0) {\n num2 = \"Error, you can't divide by 0\"\n } else {\n num2 = calcDivide(num1, num2);\n }\n break\n }\n num2 = roundNum(num2)\n prevDisplay.textContent = \"\";\n currentDisplay.textContent = num2;\n num1 = '';\n}\n//Round Number\nfunction roundNum(num) {\n return Math.round(num * 1000000) / 1000000;\n}\n//Event listeners for key presses\nwindow.addEventListener('keydown', removeDot = function(e) {\n switch (e.key) {\n case \"7\":\n handleNumber(7)\n break\n case \"8\":\n handleNumber(8)\n break\n case \"9\":\n handleNumber(9)\n break\n case \"4\":\n handleNumber(4)\n break\n case \"5\":\n handleNumber(5)\n break\n case \"6\":\n handleNumber(6)\n break\n case \"1\":\n handleNumber(1)\n break\n case \"2\":\n handleNumber(2)\n break\n case \"3\":\n handleNumber(3)\n break\n case \"0\":\n handleNumber(0)\n break\n case \")\":\n handleNumber(00)\n break\n case \"Delete\":\n clearCalc();\n break\n case \"+\":\n handleOperator('+')\n break\n case \"-\":\n handleOperator('-')\n break\n case \"*\":\n handleOperator('×')\n break\n case \"/\":\n handleOperator('÷')\n break\n case \"%\":\n handleOperator('%')\n break\n case \".\":\n decimalCalc();\n break\n case \"Backspace\":\n deleteCalc();\n break\n case \"Enter\":\n e.preventDefault();\n equalsCalc();\n break\n }\n}, true) html,\nbody {\n display: flex;\n justify-content: center;\n align-items: center;\n height: 100%;\n padding: 0;\n margin: 0;\n}\n\n.calcBody {\n display: flex;\n background-color: rgb(160, 160, 160);\n width: 500px;\n height: 700px;\n border: 2px solid black;\n border-radius: 35px;\n padding-bottom: 25px;\n transform: scale(0.95, 1);\n}\n\n.calcDisplay {\n display: flex;\n height: 200px;\n width: 500px;\n position: absolute;\n justify-content: center;\n border-radius: 30px;\n}\n\n.screenDisplay {\n display: flex;\n align-self: center;\n background-color: rgb(248, 248, 248);\n width: 450px;\n height: 150px;\n justify-content: flex-end;\n border-radius: 45px;\n border: 2px solid black;\n}\n\n.prevDisplay {\n display: flex;\n justify-content: flex-end;\n align-items: flex-start;\n width: 85%;\n height: 50px;\n position: absolute;\n margin-top: 50px;\n margin-right: 25px;\n font-family: Verdana, Geneva, Tahoma, sans-serif;\n font-size: 20px;\n margin-bottom: 20px;\n}\n\n.currentDisplay {\n display: flex;\n align-self: flex-end;\n justify-self: end;\n height: 50px;\n width: 100%;\n justify-content: flex-end;\n margin-right: 25px;\n font-family: Verdana, Geneva, Tahoma, sans-serif;\n font-size: 30px;\n margin-bottom: 20px;\n}\n\n.buttonsBody {\n display: flex;\n width: 100%;\n height: 500px;\n align-self: flex-end;\n justify-content: center;\n}\n\n.numberButtons {\n display: grid;\n grid-template-columns: 1fr 1fr 1fr 1fr;\n grid-template-rows: 1fr 1fr 1fr 1fr 1fr;\n width: 450px;\n height: 500px;\n gap: 5px;\n}\n\n.inputButton {\n padding: 0px;\n margin: 0px;\n border: 2px solid black;\n border-radius: 20px;\n transition: 200ms;\n background-color: rgb(231, 231, 231);\n}\n\n.buttonsText {\n padding: 0;\n margin: 0;\n font-size: 20px;\n font-family: Verdana, Geneva, Tahoma, sans-serif;\n transition: 150ms;\n display: flex;\n align-items: center;\n justify-content: center;\n height: 100%;\n width: 100%;\n}\n\n.inputButton:hover {\n background-color: darkgray;\n cursor: pointer;\n}\n\n.buttonsText:hover {\n font-size: 30px;\n}\n\n.clearButton,\n.deleteButton {\n background-color: rgb(223, 145, 145);\n}\n\n.equalsButton {\n background-color: rgb(187, 238, 110);\n} <div class=\"calcBody\">\n <div class=\"calcDisplay\">\n <div class=\"screenDisplay\">\n <div class=\"prevDisplay\"></div>\n <div class=\"currentDisplay\"></div>\n </div>\n </div>\n <div class=\"buttonsBody\">\n <div class=\"numberButtons\">\n <!--Row 1-->\n <button class=\"clearButton inputButton\" data-all=\"AC\"><span class=\"buttonsText\">AC</span></button>\n <button class=\"deleteButton inputButton\" data-all=\"C\"><span class=\"buttonsText\">C</span></button>\n <button class=\"percentButton inputButton\" data-all=\"%\" data-operator=\"%\"><span class=\"buttonsText\">%</span></button>\n <button class=\"divideButton inputButton\" data-all=\"÷\" data-operator=\"÷\"><span class=\"buttonsText\">÷</span></button>\n <!--Row 2-->\n <button class=\"sevenButton inputButton\" data-all=\"7\" data-num=\"7\"><span class=\"buttonsText\">7</span></button>\n <button class=\"eightButton inputButton\" data-all=\"8\" data-num=\"8\"><span class=\"buttonsText\">8</span></button>\n <button class=\"nineButton inputButton\" data-all=\"9\" data-num=\"9\"><span class=\"buttonsText\">9</span></button>\n <button class=\"multiplyButton inputButton\" data-all=\"×\" data-operator=\"×\"><span class=\"buttonsText\">×</span></button>\n <!--Row 3-->\n <button class=\"fourButton inputButton\" data-all=\"4\" data-num=\"4\"><span class=\"buttonsText\">4</span></button>\n <button class=\"fiveButton inputButton\" data-all=\"5\" data-num=\"5\"><span class=\"buttonsText\">5</span></button>\n <button class=\"sixButton inputButton\" data-all=\"6\" data-num=\"6\"><span class=\"buttonsText\">6</span></button>\n <button class=\"minusButton inputButton\" data-all=\"-\" data-operator=\"-\"><span class=\"buttonsText\">-</span></button>\n <!--Row 4-->\n <button class=\"oneButton inputButton\" data-all=\"1\" data-num=\"1\"><span class=\"buttonsText\">1</span></button>\n <button class=\"twoButton inputButton\" data-all=\"2\" data-num=\"2\"><span class=\"buttonsText\">2</span></button>\n <button class=\"threeButton inputButton\" data-all=\"3\" data-num=\"3\"><span class=\"buttonsText\">3</span></button>\n <button class=\"plusButton inputButton\" data-all=\"+\" data-operator=\"+\"><span class=\"buttonsText\">+</span></button>\n <!--Row 5 -->\n <button class=\"doubleZeroButton inputButton\" data-all=\"00\" data-num=\"00\"><span class=\"buttonsText\">00</span></button>\n <button class=\"zeroButton inputButton\" data-all=\"0\" data-num=\"0\"><span class=\"buttonsText\">0</span></button>\n <button class=\"decimalButton inputButton\" data-all=\".\"><span class=\"buttonsText\">.</span></button>\n <button class=\"equalsButton inputButton\" data-all=\"=\"><span class=\"buttonsText\">=</span></button>\n </div>\n </div>\n</div>"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74580194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20604535/"
] |
74,580,202
|
<p>Every time I run <code>npx create-react-app my-app</code> I get this error:</p>
<pre><code>npm ERR! code ENOENT
npm ERR! syscall mkdir
npm ERR! path foo:\bar\node_modules\react
npm ERR! errno -4058
npm ERR! enoent ENOENT: no such file or directory, mkdir 'foo:\bar\node_modules\react'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent
</code></pre>
<p>I've been looking for a fix all day but cant seem to get past it.</p>
|
[
{
"answer_id": 74643699,
"author": "Alex Badea",
"author_id": 11309337,
"author_profile": "https://Stackoverflow.com/users/11309337",
"pm_score": 0,
"selected": false,
"text": "typeof num2 !== 'string' function handleNumber(number) {\n if (typeof num2 !== 'string' && operator === '') num2 = ''; // Add this line\n if (num1.length <= 21) {\n num1 += number;\n currentDisplay.textContent = num1;\n }\n }\n"
},
{
"answer_id": 74657255,
"author": "dangarfield",
"author_id": 3265253,
"author_profile": "https://Stackoverflow.com/users/3265253",
"pm_score": 2,
"selected": true,
"text": "= handleNumber num2 ...\n\nfunction handleNumber(number) {\n if (num1.length <= 21) {\n num1 += number;\n currentDisplay.textContent = num1;\n }\n if (operator === '=') { // <-- Added\n num2 = ''\n }\n}\n\n...\n\nfunction equalsCalc() {\n if (num1 != '' && num2 != '') {\n operate()\n operator = '=' // <-- Added\n }\n}\n\n...\n const prevDisplay = document.querySelector('.prevDisplay');\nconst currentDisplay = document.querySelector('.currentDisplay');\nconst inputButton = document.querySelectorAll('.inputButton');\nconst divideButton = document.querySelector('.divideButton');\nconst equalsButton = document.querySelector('.equalsButton');\nconst operatorButton = document.querySelectorAll('[data-operator]');\nconst numberButton = document.querySelectorAll('[data-num]');\nconst clearButton = document.querySelector('.clearButton');\nconst deleteButton = document.querySelector('.deleteButton');\nconst decimalButton = document.querySelector('.decimalButton')\n//Global variables\nlet num1 = \"\";\nlet operator = \"\";\nlet num2 = \"\";\nlet removeDot;\n//Current display\nnumberButton.forEach((btn) => {\n btn.addEventListener('click', (e) => {\n handleNumber(e.target.textContent);\n })\n})\n\nfunction handleNumber(number) {\n console.log('handleNumber', num1, operator, num2, '->', number)\n if (num1.length <= 21) {\n num1 += number;\n currentDisplay.textContent = num1;\n }\n if (operator === '=') {\n num2 = ''\n }\n console.log('handleNumber END', num1, operator, num2)\n}\n//Previous display\noperatorButton.forEach((btn) => {\n btn.addEventListener('click', (e) => {\n handleOperator(e.target.textContent);\n })\n})\n\nfunction handleOperator(op) {\n console.log('handleOperator', num1, operator, num2, '->', op)\n if (num1 == '' && num2 == '') {\n num1 = '';\n } else if (operator == '' && num2 !== '') {\n num2 = ''\n } else if (num2 === \"\") {\n num2 = num1;\n operatorCheck(op);\n } else if (num1 === \"\") {\n operatorCheck(op);\n } else {\n operate();\n operator = op;\n currentDisplay.textContent = \"0\";\n prevDisplay.textContent = num2 + \" \" + operator;\n }\n console.log('handleOperator END', num1, operator, num2)\n}\n\nfunction operatorCheck(text) {\n operator = text;\n prevDisplay.textContent = num2 + \" \" + operator;\n currentDisplay.textContent = \"0\";\n num1 = \"\";\n}\n//Clear button\nfunction clearCalc() {\n prevDisplay.textContent = '';\n currentDisplay.textContent = '';\n num1 = '';\n num2 = '';\n operator = '';\n}\nclearButton.addEventListener('click', clearCalc)\n//Delete button\nfunction deleteCalc() {\n num1 = num1.slice(0, currentDisplay.textContent.length - 1)\n currentDisplay.textContent = currentDisplay.textContent.slice(0, currentDisplay.textContent.length - 1)\n}\ndeleteButton.addEventListener('click', deleteCalc)\n//Equals button\nfunction equalsCalc() {\n if (num1 != '' && num2 != '') {\n operate()\n console.log('equalsCalc END', num1, operator, num2)\n operator = '='\n }\n}\nequalsButton.addEventListener('click', equalsCalc)\n//Decimal button\nfunction decimalCalc() {\n if (num1.includes('.') == false) {\n currentDisplay.textContent = currentDisplay.textContent + '.'\n num1 = num1 + '.'\n }\n}\ndecimalButton.addEventListener('click', decimalCalc)\n//Doing the calculation\nfunction calcPercent(num1, num2) {\n return (num2 / 100) * num1\n}\n\nfunction calcDivide(num1, num2) {\n return num2 / num1\n}\n\nfunction calcMultiply(num1, num2) {\n return num1 * num2\n}\n\nfunction calcSubtract(num1, num2) {\n return num2 - num1\n}\n\nfunction calcAdd(num1, num2) {\n return num1 + num2\n}\n\nfunction operate() {\n num1 = Number(num1)\n num2 = Number(num2)\n\n switch (operator) {\n case '+':\n num2 = calcAdd(num1, num2)\n break\n case '-':\n num2 = calcSubtract(num1, num2)\n break\n case '×':\n num2 = calcMultiply(num1, num2)\n break\n case '%':\n num2 = calcPercent(num1, num2)\n break\n case '÷':\n num2 = num2.toString();\n if (num1 == 0) {\n num2 = \"Error, you can't divide by 0\"\n } else {\n num2 = calcDivide(num1, num2);\n }\n break\n }\n num2 = roundNum(num2)\n prevDisplay.textContent = \"\";\n currentDisplay.textContent = num2;\n num1 = '';\n}\n//Round Number\nfunction roundNum(num) {\n return Math.round(num * 1000000) / 1000000;\n}\n//Event listeners for key presses\nwindow.addEventListener('keydown', removeDot = function(e) {\n switch (e.key) {\n case \"7\":\n handleNumber(7)\n break\n case \"8\":\n handleNumber(8)\n break\n case \"9\":\n handleNumber(9)\n break\n case \"4\":\n handleNumber(4)\n break\n case \"5\":\n handleNumber(5)\n break\n case \"6\":\n handleNumber(6)\n break\n case \"1\":\n handleNumber(1)\n break\n case \"2\":\n handleNumber(2)\n break\n case \"3\":\n handleNumber(3)\n break\n case \"0\":\n handleNumber(0)\n break\n case \")\":\n handleNumber(00)\n break\n case \"Delete\":\n clearCalc();\n break\n case \"+\":\n handleOperator('+')\n break\n case \"-\":\n handleOperator('-')\n break\n case \"*\":\n handleOperator('×')\n break\n case \"/\":\n handleOperator('÷')\n break\n case \"%\":\n handleOperator('%')\n break\n case \".\":\n decimalCalc();\n break\n case \"Backspace\":\n deleteCalc();\n break\n case \"Enter\":\n e.preventDefault();\n equalsCalc();\n break\n }\n}, true) html,\nbody {\n display: flex;\n justify-content: center;\n align-items: center;\n height: 100%;\n padding: 0;\n margin: 0;\n}\n\n.calcBody {\n display: flex;\n background-color: rgb(160, 160, 160);\n width: 500px;\n height: 700px;\n border: 2px solid black;\n border-radius: 35px;\n padding-bottom: 25px;\n transform: scale(0.95, 1);\n}\n\n.calcDisplay {\n display: flex;\n height: 200px;\n width: 500px;\n position: absolute;\n justify-content: center;\n border-radius: 30px;\n}\n\n.screenDisplay {\n display: flex;\n align-self: center;\n background-color: rgb(248, 248, 248);\n width: 450px;\n height: 150px;\n justify-content: flex-end;\n border-radius: 45px;\n border: 2px solid black;\n}\n\n.prevDisplay {\n display: flex;\n justify-content: flex-end;\n align-items: flex-start;\n width: 85%;\n height: 50px;\n position: absolute;\n margin-top: 50px;\n margin-right: 25px;\n font-family: Verdana, Geneva, Tahoma, sans-serif;\n font-size: 20px;\n margin-bottom: 20px;\n}\n\n.currentDisplay {\n display: flex;\n align-self: flex-end;\n justify-self: end;\n height: 50px;\n width: 100%;\n justify-content: flex-end;\n margin-right: 25px;\n font-family: Verdana, Geneva, Tahoma, sans-serif;\n font-size: 30px;\n margin-bottom: 20px;\n}\n\n.buttonsBody {\n display: flex;\n width: 100%;\n height: 500px;\n align-self: flex-end;\n justify-content: center;\n}\n\n.numberButtons {\n display: grid;\n grid-template-columns: 1fr 1fr 1fr 1fr;\n grid-template-rows: 1fr 1fr 1fr 1fr 1fr;\n width: 450px;\n height: 500px;\n gap: 5px;\n}\n\n.inputButton {\n padding: 0px;\n margin: 0px;\n border: 2px solid black;\n border-radius: 20px;\n transition: 200ms;\n background-color: rgb(231, 231, 231);\n}\n\n.buttonsText {\n padding: 0;\n margin: 0;\n font-size: 20px;\n font-family: Verdana, Geneva, Tahoma, sans-serif;\n transition: 150ms;\n display: flex;\n align-items: center;\n justify-content: center;\n height: 100%;\n width: 100%;\n}\n\n.inputButton:hover {\n background-color: darkgray;\n cursor: pointer;\n}\n\n.buttonsText:hover {\n font-size: 30px;\n}\n\n.clearButton,\n.deleteButton {\n background-color: rgb(223, 145, 145);\n}\n\n.equalsButton {\n background-color: rgb(187, 238, 110);\n} <div class=\"calcBody\">\n <div class=\"calcDisplay\">\n <div class=\"screenDisplay\">\n <div class=\"prevDisplay\"></div>\n <div class=\"currentDisplay\"></div>\n </div>\n </div>\n <div class=\"buttonsBody\">\n <div class=\"numberButtons\">\n <!--Row 1-->\n <button class=\"clearButton inputButton\" data-all=\"AC\"><span class=\"buttonsText\">AC</span></button>\n <button class=\"deleteButton inputButton\" data-all=\"C\"><span class=\"buttonsText\">C</span></button>\n <button class=\"percentButton inputButton\" data-all=\"%\" data-operator=\"%\"><span class=\"buttonsText\">%</span></button>\n <button class=\"divideButton inputButton\" data-all=\"÷\" data-operator=\"÷\"><span class=\"buttonsText\">÷</span></button>\n <!--Row 2-->\n <button class=\"sevenButton inputButton\" data-all=\"7\" data-num=\"7\"><span class=\"buttonsText\">7</span></button>\n <button class=\"eightButton inputButton\" data-all=\"8\" data-num=\"8\"><span class=\"buttonsText\">8</span></button>\n <button class=\"nineButton inputButton\" data-all=\"9\" data-num=\"9\"><span class=\"buttonsText\">9</span></button>\n <button class=\"multiplyButton inputButton\" data-all=\"×\" data-operator=\"×\"><span class=\"buttonsText\">×</span></button>\n <!--Row 3-->\n <button class=\"fourButton inputButton\" data-all=\"4\" data-num=\"4\"><span class=\"buttonsText\">4</span></button>\n <button class=\"fiveButton inputButton\" data-all=\"5\" data-num=\"5\"><span class=\"buttonsText\">5</span></button>\n <button class=\"sixButton inputButton\" data-all=\"6\" data-num=\"6\"><span class=\"buttonsText\">6</span></button>\n <button class=\"minusButton inputButton\" data-all=\"-\" data-operator=\"-\"><span class=\"buttonsText\">-</span></button>\n <!--Row 4-->\n <button class=\"oneButton inputButton\" data-all=\"1\" data-num=\"1\"><span class=\"buttonsText\">1</span></button>\n <button class=\"twoButton inputButton\" data-all=\"2\" data-num=\"2\"><span class=\"buttonsText\">2</span></button>\n <button class=\"threeButton inputButton\" data-all=\"3\" data-num=\"3\"><span class=\"buttonsText\">3</span></button>\n <button class=\"plusButton inputButton\" data-all=\"+\" data-operator=\"+\"><span class=\"buttonsText\">+</span></button>\n <!--Row 5 -->\n <button class=\"doubleZeroButton inputButton\" data-all=\"00\" data-num=\"00\"><span class=\"buttonsText\">00</span></button>\n <button class=\"zeroButton inputButton\" data-all=\"0\" data-num=\"0\"><span class=\"buttonsText\">0</span></button>\n <button class=\"decimalButton inputButton\" data-all=\".\"><span class=\"buttonsText\">.</span></button>\n <button class=\"equalsButton inputButton\" data-all=\"=\"><span class=\"buttonsText\">=</span></button>\n </div>\n </div>\n</div>"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74580202",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20604579/"
] |
74,580,208
|
<p>new to kotlin and struggle with the syntax of compareBy and its lambda to get the 'a' and 'b' parameters for a custom compare:</p>
<pre><code>public inline fun <T> compareBy(crossinline selector: (T) -> Comparable<*>?): Comparator<T> =
Comparator { a, b -> compareValuesBy(a, b, selector) }
</code></pre>
<p>Basically I want to compare 2d points that are stored as IntArray(x,y) but don't know how to access the a and b elements of the declaration. Here where I am stuck:</p>
<pre><code>val compareByDistance: Comparator<IntArray> = compareBy {
// b - a to origin = (bx2 - 0)^2 - (by2 - 0)^2 -> no need square root
val distance = -1
distance
}
val points = PriorityQueue<IntArray>(compareByDistance)
points.add(intArrayOf(1, 2))
points.add(intArrayOf(2, 3))
</code></pre>
<p>when I run the debugger I see the 'a' and 'b' parameters, but I have to idea how to access them.</p>
<p><a href="https://i.stack.imgur.com/fthoe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fthoe.png" alt="enter image description here" /></a></p>
<p>If I do:</p>
<pre><code>val k = it.first()
</code></pre>
<p>it does not give k = a = [2,3] just k =2, but still I can't access b.</p>
<p>What is the correct syntax for the lambda? I looked in this thread by did not help:</p>
<p><a href="https://www.bezkoder.com/kotlin-priority-queue/" rel="nofollow noreferrer">https://www.bezkoder.com/kotlin-priority-queue/</a></p>
<p>thank you.</p>
|
[
{
"answer_id": 74582919,
"author": "Gowtham K K",
"author_id": 9248098,
"author_profile": "https://Stackoverflow.com/users/9248098",
"pm_score": 2,
"selected": true,
"text": " val compareByDistance = Comparator<IntArray> { a:IntArray, b:IntArray ->\n // Return -1 , +1 ,0 - Based on your Formula\n 0\n }\n compareBy Comparable<T> Comparator Comparator"
},
{
"answer_id": 74583114,
"author": "Tenfour04",
"author_id": 506796,
"author_profile": "https://Stackoverflow.com/users/506796",
"pm_score": 0,
"selected": false,
"text": "compareBy it it[0] it[1] val compareByDistance: Comparator<IntArray> = compareBy { (a, b) ->\n a * a + b * b\n}\n"
},
{
"answer_id": 74584431,
"author": "cactustictacs",
"author_id": 13598222,
"author_profile": "https://Stackoverflow.com/users/13598222",
"pm_score": 0,
"selected": false,
"text": "fun <T> compareBy(\n vararg selectors: (T) -> Comparable<*>?\n): Comparator<T>\n a b Comparable Comparable a b Comparator Comparator abstract fun compare(a: T, b: T): Int\n Comparator compare a b compareBy compareBy(\n { it.length }\n}\n\n compare a b compareBy a b // skipping the parentheses since it's one selector function\ncompareBy { myArray ->\n // evaluate to the value we want to \"return\"\n val x = myArray[0]\n val y = myArray[1]\n // I think this is what you meant? This gives you distance-squared\n (x * x) + (y * y)\n}\n Comparator compare a b"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74580208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3657747/"
] |
74,580,213
|
<p>I have an ASP.NET Core Web API published to Amazon ECS using AWS Fargate with working PATCH request that I have successfully tested using POSTMAN. Now I am trying to make that request in the client side application by following <a href="https://github.com/KevinDockx/JsonPatch#:%7E:text=Here%27s%20how%20to,support%20is%20planned." rel="nofollow noreferrer">this</a>.</p>
<p>What I have on client side is this:</p>
<pre><code>public async Task<ActionResult> Patch(int companyId, string description)
{
JsonPatchDocument<CompanyInfo> patchDoc = new JsonPatchDocument<CompanyInfo>();
patchDoc.Replace(e => e.Description, description);
var jsonSerializeObject = JsonConvert.SerializeObject(patchDoc);
Debug.WriteLine(jsonSerializeObject);
var method = new HttpMethod("PATCH");
var request = new HttpRequestMessage(method, "api/CompanyInfo/" + companyId)
{
Content = new StringContent(jsonSerializeObject, Encoding.Unicode, "application/json")
};
response = await _httpClient.SendAsync(request);
Debug.WriteLine(response);
return RedirectToAction(nameof(Index));
}
</code></pre>
<p>This is what I get in my response:</p>
<pre><code>StatusCode: 405, ReasonPhrase: 'Method Not Allowed', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:
{
Date: Sat, 26 Nov 2022 06:06:08 GMT
Connection: keep-alive
Server: Kestrel
Content-Length: 0
Allow: GET, PUT
}
</code></pre>
<p>As previously mentioned I have already confirmed the following json patch document using POSTMAN:</p>
<pre><code>[
{
"value":"some text value",
"path":"/Description",
"op":"replace"
}
]
</code></pre>
<p>The API:</p>
<pre><code>
[HttpPatch]
public async Task<ActionResult> PartiallyUpdateCompanyInfo(int companyId, JsonPatchDocument<CompanyInfoForPatchDto> patchDocument)
{
var companyEntity = await _moviePlanetRepository.GetCompanyById(companyId, false);
if (companyEntity == null)
{
return NotFound();
}
var companyToPatch = _mapper.Map<CompanyInfoForPatchDto>(companyEntity);
patchDocument.ApplyTo(companyToPatch, ModelState);
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (!TryValidateModel(companyToPatch))
{
return BadRequest(ModelState);
}
_mapper.Map(companyToPatch, companyEntity);
await _moviePlanetRepository.Save();
return NoContent();
}
</code></pre>
|
[
{
"answer_id": 74582919,
"author": "Gowtham K K",
"author_id": 9248098,
"author_profile": "https://Stackoverflow.com/users/9248098",
"pm_score": 2,
"selected": true,
"text": " val compareByDistance = Comparator<IntArray> { a:IntArray, b:IntArray ->\n // Return -1 , +1 ,0 - Based on your Formula\n 0\n }\n compareBy Comparable<T> Comparator Comparator"
},
{
"answer_id": 74583114,
"author": "Tenfour04",
"author_id": 506796,
"author_profile": "https://Stackoverflow.com/users/506796",
"pm_score": 0,
"selected": false,
"text": "compareBy it it[0] it[1] val compareByDistance: Comparator<IntArray> = compareBy { (a, b) ->\n a * a + b * b\n}\n"
},
{
"answer_id": 74584431,
"author": "cactustictacs",
"author_id": 13598222,
"author_profile": "https://Stackoverflow.com/users/13598222",
"pm_score": 0,
"selected": false,
"text": "fun <T> compareBy(\n vararg selectors: (T) -> Comparable<*>?\n): Comparator<T>\n a b Comparable Comparable a b Comparator Comparator abstract fun compare(a: T, b: T): Int\n Comparator compare a b compareBy compareBy(\n { it.length }\n}\n\n compare a b compareBy a b // skipping the parentheses since it's one selector function\ncompareBy { myArray ->\n // evaluate to the value we want to \"return\"\n val x = myArray[0]\n val y = myArray[1]\n // I think this is what you meant? This gives you distance-squared\n (x * x) + (y * y)\n}\n Comparator compare a b"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74580213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14503866/"
] |
74,580,238
|
<p>I am trying to learn TS for the first time, but there is one case, which does not click quite well in my mind. Let's say we have two variables:</p>
<pre><code>let value1: 'POST' | number | boolean = 'POST';
let value2: 'POST' | number | boolean | string = 'POST';
</code></pre>
<p>And let's say we have another variable to which we want to assign one of the variables specified above:</p>
<pre><code>let copiedValue: 'POST'
</code></pre>
<p>When I assign to the variable <strong>copiedValue</strong> variable labeled <strong>value1</strong> it works okay, but when I attempt to assign <strong>value2</strong> complier shows me an error and I have to cast it to get rid of this error. I suppose that is because of additional <em>string</em> type that I added to <strong>value2</strong> variable and TS compiler just warns that if something is labeled as a <em>string</em> it can be anything and not only 'POST', but is not it a problem that <strong>value1</strong> variable has <em>boolean</em> and <em>numeric</em> types set on it too? Also, if TS compiler allows <strong>value1</strong> because it knows that this variable holds "POST" at the moment of assignment to <strong>copiedValue</strong> variable, what is a problem with <strong>value2</strong> variable if it also holds absolutely the same "POST" value?</p>
|
[
{
"answer_id": 74582919,
"author": "Gowtham K K",
"author_id": 9248098,
"author_profile": "https://Stackoverflow.com/users/9248098",
"pm_score": 2,
"selected": true,
"text": " val compareByDistance = Comparator<IntArray> { a:IntArray, b:IntArray ->\n // Return -1 , +1 ,0 - Based on your Formula\n 0\n }\n compareBy Comparable<T> Comparator Comparator"
},
{
"answer_id": 74583114,
"author": "Tenfour04",
"author_id": 506796,
"author_profile": "https://Stackoverflow.com/users/506796",
"pm_score": 0,
"selected": false,
"text": "compareBy it it[0] it[1] val compareByDistance: Comparator<IntArray> = compareBy { (a, b) ->\n a * a + b * b\n}\n"
},
{
"answer_id": 74584431,
"author": "cactustictacs",
"author_id": 13598222,
"author_profile": "https://Stackoverflow.com/users/13598222",
"pm_score": 0,
"selected": false,
"text": "fun <T> compareBy(\n vararg selectors: (T) -> Comparable<*>?\n): Comparator<T>\n a b Comparable Comparable a b Comparator Comparator abstract fun compare(a: T, b: T): Int\n Comparator compare a b compareBy compareBy(\n { it.length }\n}\n\n compare a b compareBy a b // skipping the parentheses since it's one selector function\ncompareBy { myArray ->\n // evaluate to the value we want to \"return\"\n val x = myArray[0]\n val y = myArray[1]\n // I think this is what you meant? This gives you distance-squared\n (x * x) + (y * y)\n}\n Comparator compare a b"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74580238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17564668/"
] |
74,580,243
|
<p>Given the code below, which runs selenium as a <code>multiprocessing.Process</code>. Despite the process being terminated on macOS Ventura <code>13.0.1</code>, selenium window stays open. Why does the window stay? how to force its termination?</p>
<pre><code>from multiprocessing import Process
from selenium.webdriver import Chrome
def func():
driver = Chrome()
driver.get('https://google.com')
if __name__ == '__main__':
p = Process(target=func)
p.daemon = True
p.start()
p.join(timeout=1)
if p.is_alive():
p.terminate()
</code></pre>
<p>A current workaround I'm using:</p>
<pre><code>os.system("ps aux | grep Google | awk ' { print $2 } ' | xargs kill -9")
</code></pre>
|
[
{
"answer_id": 74582919,
"author": "Gowtham K K",
"author_id": 9248098,
"author_profile": "https://Stackoverflow.com/users/9248098",
"pm_score": 2,
"selected": true,
"text": " val compareByDistance = Comparator<IntArray> { a:IntArray, b:IntArray ->\n // Return -1 , +1 ,0 - Based on your Formula\n 0\n }\n compareBy Comparable<T> Comparator Comparator"
},
{
"answer_id": 74583114,
"author": "Tenfour04",
"author_id": 506796,
"author_profile": "https://Stackoverflow.com/users/506796",
"pm_score": 0,
"selected": false,
"text": "compareBy it it[0] it[1] val compareByDistance: Comparator<IntArray> = compareBy { (a, b) ->\n a * a + b * b\n}\n"
},
{
"answer_id": 74584431,
"author": "cactustictacs",
"author_id": 13598222,
"author_profile": "https://Stackoverflow.com/users/13598222",
"pm_score": 0,
"selected": false,
"text": "fun <T> compareBy(\n vararg selectors: (T) -> Comparable<*>?\n): Comparator<T>\n a b Comparable Comparable a b Comparator Comparator abstract fun compare(a: T, b: T): Int\n Comparator compare a b compareBy compareBy(\n { it.length }\n}\n\n compare a b compareBy a b // skipping the parentheses since it's one selector function\ncompareBy { myArray ->\n // evaluate to the value we want to \"return\"\n val x = myArray[0]\n val y = myArray[1]\n // I think this is what you meant? This gives you distance-squared\n (x * x) + (y * y)\n}\n Comparator compare a b"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74580243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20280771/"
] |
74,580,244
|
<p>I am using javascript to hide an image after one scroll. The code is working fine but I am unable to add any transition to it due to which there is a very choppy and rough feel.</p>
<p>This is the code which I am using</p>
<hr />
<pre><code>function runOnScroll() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
document.getElementById("logoimg-hidden").style.maxWidth = "0";
document.getElementById("logoimg-hidden").style.transition = "max-width .4s linear"
}
else{
document.getElementById("logoimg-hidden").style.maxWidth = "inherit";
document.getElementById("logoimg-hidden").style.transition = "max-width .4s linear"
}
};
window.addEventListener("scroll", runOnScroll);
</code></pre>
<hr />
<p>The transition doesn't work. I would be really thankful if I can get a solution to add transition as well on scroll. Thanks!</p>
|
[
{
"answer_id": 74582919,
"author": "Gowtham K K",
"author_id": 9248098,
"author_profile": "https://Stackoverflow.com/users/9248098",
"pm_score": 2,
"selected": true,
"text": " val compareByDistance = Comparator<IntArray> { a:IntArray, b:IntArray ->\n // Return -1 , +1 ,0 - Based on your Formula\n 0\n }\n compareBy Comparable<T> Comparator Comparator"
},
{
"answer_id": 74583114,
"author": "Tenfour04",
"author_id": 506796,
"author_profile": "https://Stackoverflow.com/users/506796",
"pm_score": 0,
"selected": false,
"text": "compareBy it it[0] it[1] val compareByDistance: Comparator<IntArray> = compareBy { (a, b) ->\n a * a + b * b\n}\n"
},
{
"answer_id": 74584431,
"author": "cactustictacs",
"author_id": 13598222,
"author_profile": "https://Stackoverflow.com/users/13598222",
"pm_score": 0,
"selected": false,
"text": "fun <T> compareBy(\n vararg selectors: (T) -> Comparable<*>?\n): Comparator<T>\n a b Comparable Comparable a b Comparator Comparator abstract fun compare(a: T, b: T): Int\n Comparator compare a b compareBy compareBy(\n { it.length }\n}\n\n compare a b compareBy a b // skipping the parentheses since it's one selector function\ncompareBy { myArray ->\n // evaluate to the value we want to \"return\"\n val x = myArray[0]\n val y = myArray[1]\n // I think this is what you meant? This gives you distance-squared\n (x * x) + (y * y)\n}\n Comparator compare a b"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74580244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20604634/"
] |
74,580,249
|
<p>I want Split one row into multiple rows of 6 hours data based on 15 mins time interval in pandas data frame</p>
<pre><code> start_time end_time
0 2022-08-22 00:15:00 2022-08-22 06:15:00
</code></pre>
<p>I have tried one hrs time split and used below code</p>
<pre><code>result['start_time'] = result.apply(lambda d: pd.date_range(d['start_time'],
d['end_time'],
freq='h')[:-1],
axis=1)
</code></pre>
<p>and it worked for me to get this</p>
<pre><code> result["start_time"][0]
</code></pre>
<p>Output:</p>
<pre><code>DatetimeIndex(['2022-08-22 00:15:00', '2022-08-22 01:15:00',
'2022-08-22 02:15:00', '2022-08-22 03:15:00',
'2022-08-22 04:15:00', '2022-08-22 05:15:00'],
dtype='datetime64[ns]', freq='H')
</code></pre>
<p>now i want the frequency for 15 mins time interval, so it should give me 24 timestamp</p>
|
[
{
"answer_id": 74580348,
"author": "JayPeerachai",
"author_id": 12135518,
"author_profile": "https://Stackoverflow.com/users/12135518",
"pm_score": 1,
"selected": false,
"text": "from datetime import timedelta\n\ndf = pd.DataFrame({'start_time': ['2022-08-22 00:15:00'],'end_time': ['2022-08-22 06:15:00']})\ndf['start_time'] = pd.to_datetime(df['start_time'])\ndf['end_time'] = pd.to_datetime(df['end_time'])\ndf['start_time'] = df['start_time'].dt.strftime('%Y-%m-%d %H:%M:%S')\ndf['end_time'] = df['end_time'].dt.strftime('%Y-%m-%d %H:%M:%S')\n\n# start_time end_time\n# 0 2022-08-22 00:15:00 2022-08-22 06:15:00\n\nnew_df = pd.date_range(start=df['start_time'][0], end=df['end_time'][0], freq='15min')[:-1]\nresult_df = pd.DataFrame({'start_time': new_df, 'end_time': new_df + timedelta(minutes=15)})\n > result_df\n\n start_time end_time\n0 2022-08-22 00:15:00 2022-08-22 00:30:00\n1 2022-08-22 00:30:00 2022-08-22 00:45:00\n2 2022-08-22 00:45:00 2022-08-22 01:00:00\n3 2022-08-22 01:00:00 2022-08-22 01:15:00\n4 2022-08-22 01:15:00 2022-08-22 01:30:00\n5 2022-08-22 01:30:00 2022-08-22 01:45:00\n6 2022-08-22 01:45:00 2022-08-22 02:00:00\n7 2022-08-22 02:00:00 2022-08-22 02:15:00\n8 2022-08-22 02:15:00 2022-08-22 02:30:00\n9 2022-08-22 02:30:00 2022-08-22 02:45:00\n10 2022-08-22 02:45:00 2022-08-22 03:00:00\n11 2022-08-22 03:00:00 2022-08-22 03:15:00\n12 2022-08-22 03:15:00 2022-08-22 03:30:00\n13 2022-08-22 03:30:00 2022-08-22 03:45:00\n14 2022-08-22 03:45:00 2022-08-22 04:00:00\n15 2022-08-22 04:00:00 2022-08-22 04:15:00\n16 2022-08-22 04:15:00 2022-08-22 04:30:00\n17 2022-08-22 04:30:00 2022-08-22 04:45:00\n18 2022-08-22 04:45:00 2022-08-22 05:00:00\n19 2022-08-22 05:00:00 2022-08-22 05:15:00\n20 2022-08-22 05:15:00 2022-08-22 05:30:00\n21 2022-08-22 05:30:00 2022-08-22 05:45:00\n22 2022-08-22 05:45:00 2022-08-22 06:00:00\n23 2022-08-22 06:00:00 2022-08-22 06:15:00\n"
},
{
"answer_id": 74580355,
"author": "ScottC",
"author_id": 20174226,
"author_profile": "https://Stackoverflow.com/users/20174226",
"pm_score": 3,
"selected": true,
"text": "15T h result['start_time'] = result.apply(lambda d: pd.date_range(d['start_time'],\n d['end_time'], \n freq='15T')[:-1], \n axis=1) \n\n DatetimeIndex(['2022-08-22 00:15:00', '2022-08-22 00:30:00',\n '2022-08-22 00:45:00', '2022-08-22 01:00:00',\n '2022-08-22 01:15:00', '2022-08-22 01:30:00',\n '2022-08-22 01:45:00', '2022-08-22 02:00:00',\n '2022-08-22 02:15:00', '2022-08-22 02:30:00',\n '2022-08-22 02:45:00', '2022-08-22 03:00:00',\n '2022-08-22 03:15:00', '2022-08-22 03:30:00',\n '2022-08-22 03:45:00', '2022-08-22 04:00:00',\n '2022-08-22 04:15:00', '2022-08-22 04:30:00',\n '2022-08-22 04:45:00', '2022-08-22 05:00:00',\n '2022-08-22 05:15:00', '2022-08-22 05:30:00',\n '2022-08-22 05:45:00', '2022-08-22 06:00:00'],\n dtype='datetime64[ns]', freq='15T')\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74580249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5506647/"
] |
74,580,252
|
<p>For example, lets say the original number is 1. When I click (+), it increases to 2. Then I cannot click(+) anymore. Then When I click (-), it decreases to 0 when the original num is 1. Then I cannot click(-) anymore. How can I go about this? Thank you for your time.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const container = document.getElementById("container");
container.addEventListener('click', (e) => {
const tgt = e.target.closest("button");
if (!tgt) return; // or use e.target and test tgt.matches("button")
const numSpan = tgt.closest(".rating").querySelector(".num");
let num = +numSpan.textContent;
num += tgt.classList.contains("countUp") ? 1 : -1;
numSpan.textContent = num
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
<div class="rating">
<button class="countUp">+</button>
<span class="num">0</span>
<button class="countDown">-</button>
</div>
<div class="rating">
<button class="countUp">+</button>
<span class="num">0</span>
<button class="countDown">-</button>
</div>
</div></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74580348,
"author": "JayPeerachai",
"author_id": 12135518,
"author_profile": "https://Stackoverflow.com/users/12135518",
"pm_score": 1,
"selected": false,
"text": "from datetime import timedelta\n\ndf = pd.DataFrame({'start_time': ['2022-08-22 00:15:00'],'end_time': ['2022-08-22 06:15:00']})\ndf['start_time'] = pd.to_datetime(df['start_time'])\ndf['end_time'] = pd.to_datetime(df['end_time'])\ndf['start_time'] = df['start_time'].dt.strftime('%Y-%m-%d %H:%M:%S')\ndf['end_time'] = df['end_time'].dt.strftime('%Y-%m-%d %H:%M:%S')\n\n# start_time end_time\n# 0 2022-08-22 00:15:00 2022-08-22 06:15:00\n\nnew_df = pd.date_range(start=df['start_time'][0], end=df['end_time'][0], freq='15min')[:-1]\nresult_df = pd.DataFrame({'start_time': new_df, 'end_time': new_df + timedelta(minutes=15)})\n > result_df\n\n start_time end_time\n0 2022-08-22 00:15:00 2022-08-22 00:30:00\n1 2022-08-22 00:30:00 2022-08-22 00:45:00\n2 2022-08-22 00:45:00 2022-08-22 01:00:00\n3 2022-08-22 01:00:00 2022-08-22 01:15:00\n4 2022-08-22 01:15:00 2022-08-22 01:30:00\n5 2022-08-22 01:30:00 2022-08-22 01:45:00\n6 2022-08-22 01:45:00 2022-08-22 02:00:00\n7 2022-08-22 02:00:00 2022-08-22 02:15:00\n8 2022-08-22 02:15:00 2022-08-22 02:30:00\n9 2022-08-22 02:30:00 2022-08-22 02:45:00\n10 2022-08-22 02:45:00 2022-08-22 03:00:00\n11 2022-08-22 03:00:00 2022-08-22 03:15:00\n12 2022-08-22 03:15:00 2022-08-22 03:30:00\n13 2022-08-22 03:30:00 2022-08-22 03:45:00\n14 2022-08-22 03:45:00 2022-08-22 04:00:00\n15 2022-08-22 04:00:00 2022-08-22 04:15:00\n16 2022-08-22 04:15:00 2022-08-22 04:30:00\n17 2022-08-22 04:30:00 2022-08-22 04:45:00\n18 2022-08-22 04:45:00 2022-08-22 05:00:00\n19 2022-08-22 05:00:00 2022-08-22 05:15:00\n20 2022-08-22 05:15:00 2022-08-22 05:30:00\n21 2022-08-22 05:30:00 2022-08-22 05:45:00\n22 2022-08-22 05:45:00 2022-08-22 06:00:00\n23 2022-08-22 06:00:00 2022-08-22 06:15:00\n"
},
{
"answer_id": 74580355,
"author": "ScottC",
"author_id": 20174226,
"author_profile": "https://Stackoverflow.com/users/20174226",
"pm_score": 3,
"selected": true,
"text": "15T h result['start_time'] = result.apply(lambda d: pd.date_range(d['start_time'],\n d['end_time'], \n freq='15T')[:-1], \n axis=1) \n\n DatetimeIndex(['2022-08-22 00:15:00', '2022-08-22 00:30:00',\n '2022-08-22 00:45:00', '2022-08-22 01:00:00',\n '2022-08-22 01:15:00', '2022-08-22 01:30:00',\n '2022-08-22 01:45:00', '2022-08-22 02:00:00',\n '2022-08-22 02:15:00', '2022-08-22 02:30:00',\n '2022-08-22 02:45:00', '2022-08-22 03:00:00',\n '2022-08-22 03:15:00', '2022-08-22 03:30:00',\n '2022-08-22 03:45:00', '2022-08-22 04:00:00',\n '2022-08-22 04:15:00', '2022-08-22 04:30:00',\n '2022-08-22 04:45:00', '2022-08-22 05:00:00',\n '2022-08-22 05:15:00', '2022-08-22 05:30:00',\n '2022-08-22 05:45:00', '2022-08-22 06:00:00'],\n dtype='datetime64[ns]', freq='15T')\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74580252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20464992/"
] |
74,580,351
|
<p>I am trying to perform a DB migration with <a href="https://github.com/dimitri/pgloader/" rel="nofollow noreferrer">pgloader</a> and I would like to define a <a href="https://pgloader.readthedocs.io/en/latest/ref/transforms.html" rel="nofollow noreferrer">custom lisp transformation file for a datetime</a>, but I don't know LISP (!)</p>
<p>So I have cut&paste one of the <a href="https://github.com/dimitri/pgloader/blob/master/src/utils/transforms.lisp#L127" rel="nofollow noreferrer">pgloader transform functions</a> and I tried to invoke it with no luck after spending a bunch of hours (!) in studying LISP.</p>
<p>I have extracted and simplified the function</p>
<pre><code>(defun date-with-no-separator
(date-string
&optional (formato '((:year 0 4)
(:month 4 6)
(:day 6 8)
(:hour 8 10)
(:minute 10 12)
(:seconds 12 14))))
"Apply this function when input date in like '20041002152952'"
(let ((str-length (length date-string))
(expected-length (reduce #'max (mapcar #'third formato))))
(print str-length)
(print expected-length)))
</code></pre>
<p>I have changed <code>format</code> to <code>formato</code> in order to be sure that it is a variable and not the <code>format</code> LISP function. It seems to me that I have been right at least in this assumption. Am I?</p>
<p>I have tried:</p>
<pre><code>(setq my-date "20041002152952")
(date-with-no-separator my-date)
</code></pre>
<p>and by running <code>clisp test.lisp</code> I got the output</p>
<pre><code>14
14
</code></pre>
<p>and then I have done some failing attempts that you can see below with ANY LUCK:</p>
<pre><code>(setq my-date "2004")
; (setf (get 'formato 'year) '(0 4))
(setq formato (#':year 0 4))
(date-with-no-separator my-date formato) ;(formato (:year 0 4))) ; '((12 16) (6 8) (1 3)) ))
</code></pre>
<p>At this time I just expect to get</p>
<pre><code>4
4
</code></pre>
<p>when I set my-date to "2004" and my format to (:year 0 4)
but also</p>
<pre><code>10
10
</code></pre>
<p>when I set my-date to "01/01/1970" and my format to (:year 6 10) (:month 3 5) (:day 0 2)</p>
<p>I am a pythonist if it could be useful to make me understanding the topic with pythonic examples.</p>
|
[
{
"answer_id": 74580348,
"author": "JayPeerachai",
"author_id": 12135518,
"author_profile": "https://Stackoverflow.com/users/12135518",
"pm_score": 1,
"selected": false,
"text": "from datetime import timedelta\n\ndf = pd.DataFrame({'start_time': ['2022-08-22 00:15:00'],'end_time': ['2022-08-22 06:15:00']})\ndf['start_time'] = pd.to_datetime(df['start_time'])\ndf['end_time'] = pd.to_datetime(df['end_time'])\ndf['start_time'] = df['start_time'].dt.strftime('%Y-%m-%d %H:%M:%S')\ndf['end_time'] = df['end_time'].dt.strftime('%Y-%m-%d %H:%M:%S')\n\n# start_time end_time\n# 0 2022-08-22 00:15:00 2022-08-22 06:15:00\n\nnew_df = pd.date_range(start=df['start_time'][0], end=df['end_time'][0], freq='15min')[:-1]\nresult_df = pd.DataFrame({'start_time': new_df, 'end_time': new_df + timedelta(minutes=15)})\n > result_df\n\n start_time end_time\n0 2022-08-22 00:15:00 2022-08-22 00:30:00\n1 2022-08-22 00:30:00 2022-08-22 00:45:00\n2 2022-08-22 00:45:00 2022-08-22 01:00:00\n3 2022-08-22 01:00:00 2022-08-22 01:15:00\n4 2022-08-22 01:15:00 2022-08-22 01:30:00\n5 2022-08-22 01:30:00 2022-08-22 01:45:00\n6 2022-08-22 01:45:00 2022-08-22 02:00:00\n7 2022-08-22 02:00:00 2022-08-22 02:15:00\n8 2022-08-22 02:15:00 2022-08-22 02:30:00\n9 2022-08-22 02:30:00 2022-08-22 02:45:00\n10 2022-08-22 02:45:00 2022-08-22 03:00:00\n11 2022-08-22 03:00:00 2022-08-22 03:15:00\n12 2022-08-22 03:15:00 2022-08-22 03:30:00\n13 2022-08-22 03:30:00 2022-08-22 03:45:00\n14 2022-08-22 03:45:00 2022-08-22 04:00:00\n15 2022-08-22 04:00:00 2022-08-22 04:15:00\n16 2022-08-22 04:15:00 2022-08-22 04:30:00\n17 2022-08-22 04:30:00 2022-08-22 04:45:00\n18 2022-08-22 04:45:00 2022-08-22 05:00:00\n19 2022-08-22 05:00:00 2022-08-22 05:15:00\n20 2022-08-22 05:15:00 2022-08-22 05:30:00\n21 2022-08-22 05:30:00 2022-08-22 05:45:00\n22 2022-08-22 05:45:00 2022-08-22 06:00:00\n23 2022-08-22 06:00:00 2022-08-22 06:15:00\n"
},
{
"answer_id": 74580355,
"author": "ScottC",
"author_id": 20174226,
"author_profile": "https://Stackoverflow.com/users/20174226",
"pm_score": 3,
"selected": true,
"text": "15T h result['start_time'] = result.apply(lambda d: pd.date_range(d['start_time'],\n d['end_time'], \n freq='15T')[:-1], \n axis=1) \n\n DatetimeIndex(['2022-08-22 00:15:00', '2022-08-22 00:30:00',\n '2022-08-22 00:45:00', '2022-08-22 01:00:00',\n '2022-08-22 01:15:00', '2022-08-22 01:30:00',\n '2022-08-22 01:45:00', '2022-08-22 02:00:00',\n '2022-08-22 02:15:00', '2022-08-22 02:30:00',\n '2022-08-22 02:45:00', '2022-08-22 03:00:00',\n '2022-08-22 03:15:00', '2022-08-22 03:30:00',\n '2022-08-22 03:45:00', '2022-08-22 04:00:00',\n '2022-08-22 04:15:00', '2022-08-22 04:30:00',\n '2022-08-22 04:45:00', '2022-08-22 05:00:00',\n '2022-08-22 05:15:00', '2022-08-22 05:30:00',\n '2022-08-22 05:45:00', '2022-08-22 06:00:00'],\n dtype='datetime64[ns]', freq='15T')\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74580351",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/720743/"
] |
74,580,358
|
<p>First time when my page loaded then my app total lost page.
but when I comments my array /*ClientsList.map(item => so on */ which is displaying data then page loaded. then I uncomments my array then data displayed successfully and app run.
Again If I refresh my page then app lost.</p>
<pre><code> const [ClientsList, setUsersList] = useState({});
React.useEffect(() => {
let BaseURL = 'https://******.com/taxplanner/rest-apis/users/clientslist';
fetch(BaseURL, {
method: 'POST',
data: {id:loggedIn}
})
.then((response) => response.json())
.then((res) => {
setUsersList(res.clients);
})
.catch((error) => {
console.log(error);
});
}, [""]);
return (
<>
<List type="unstyled" className="p-0 text-left bg-white">
{
/* when I comments my following array*/
ClientsList.map(item =>
<li className="my-2">
<a
className="allFormTitle"
href="#pablo"
onClick={(e) => {
e.preventDefault();
setSingleClient(item);
}}
>
{item.first_name +' '+ item.last_name}
</a>
</li>
)
}
</List>
</>
)
</code></pre>
<p>My Array Object is like this</p>
<hr />
<pre><code> [
{
"id": 1,
"first_name": "Mohammad",
"last_name": "Shafique",
"project_title": "attarisoft@gmail.com",
"business_name": "Attarisoft",
"street_address": "*****",
"city": "Faisalabad",
"state": "Alaska",
"zip": "48000",
"phone": "+923238383992",
"dependents": 25,
"registration_date": "2022-09-28 15:23:28",
"status": 1
},
{
"id": 2,
"first_name": "Mohammad",
"last_name": "Ateeq Raza",
"project_title": "*****@gmail.com",
"business_name": "Abuateeq",
"street_address": "*****",
"city": "Faisalabad",
"state": "Alabama",
"zip": "48000",
"phone": "+923238383992",
"dependents": 25,
"registration_date": "2022-09-28 15:23:28",
"status": 1
},
]
</code></pre>
<p>////////////////////////////////////////
I am trying a lot but not resolved my issue . please help to resolve my problem with thanks
Regards</p>
|
[
{
"answer_id": 74580475,
"author": "Muhammad Shafique Attari",
"author_id": 11185806,
"author_profile": "https://Stackoverflow.com/users/11185806",
"pm_score": 0,
"selected": false,
"text": " const [ClientsList, setUsersList] = useState({}); \n\n ///To////\n\n const [ClientsList, setUsersList] = useState([]); \n"
},
{
"answer_id": 74580549,
"author": "Amirhossein",
"author_id": 11342834,
"author_profile": "https://Stackoverflow.com/users/11342834",
"pm_score": 2,
"selected": false,
"text": "const [ClientsList, setUsersList] = useState([]);\n React.useEffect(() => {\n \n let BaseURL = 'https://******.com/taxplanner/rest-apis/users/clientslist';\n \n fetch(BaseURL, {\n method: 'POST',\n data: {id:loggedIn}\n })\n .then((response) => response.json())\n .then((res) => {\n setUsersList(res.clients); \n })\n .catch((error) => {\n console.log(error);\n });\n}, []);\n const [usersList, setUsersList] = useState([]); \n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74580358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11185806/"
] |
74,580,360
|
<p>I am trying to make a Python script that will check appointment availability and inform me when an earlier date opens up.</p>
<p>I am stuck at the 4th selection page, for locations. I can't seem to click the 'regions' to display the available actual locations.</p>
<p>This is what I have:</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions as EC
options = Options()
options.add_experimental_option("detach", True)
browser = webdriver.Chrome(options=options)
browser.get('url')
medical = browser.find_element(By.XPATH, "//button[@class='btn btn-primary next-button show-loading-text']")
medical.click()
timesensitive = WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.XPATH,"//button[@class='btn btn-primary next-button show-loading-text']")))
timesensitive.click()
test = WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.XPATH,"//button[@class='btn btn-primary next-button show-loading-text']")))
test.click()
region = WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.XPATH,"//label[@class='btn btn-sm btn-default'][4]")))
region.click()
</code></pre>
|
[
{
"answer_id": 74580475,
"author": "Muhammad Shafique Attari",
"author_id": 11185806,
"author_profile": "https://Stackoverflow.com/users/11185806",
"pm_score": 0,
"selected": false,
"text": " const [ClientsList, setUsersList] = useState({}); \n\n ///To////\n\n const [ClientsList, setUsersList] = useState([]); \n"
},
{
"answer_id": 74580549,
"author": "Amirhossein",
"author_id": 11342834,
"author_profile": "https://Stackoverflow.com/users/11342834",
"pm_score": 2,
"selected": false,
"text": "const [ClientsList, setUsersList] = useState([]);\n React.useEffect(() => {\n \n let BaseURL = 'https://******.com/taxplanner/rest-apis/users/clientslist';\n \n fetch(BaseURL, {\n method: 'POST',\n data: {id:loggedIn}\n })\n .then((response) => response.json())\n .then((res) => {\n setUsersList(res.clients); \n })\n .catch((error) => {\n console.log(error);\n });\n}, []);\n const [usersList, setUsersList] = useState([]); \n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74580360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20604717/"
] |
74,580,370
|
<p>The assigment is to write a program where the user enters numbers, and the program adds the entered number to a sum. At each entry, the sum is printed. The program terminates when the user enters 0.</p>
<p>My code is:</p>
<pre><code>#include <stdio.h>
int main(){
int n;
int i;
int sum = 0;
for(i=0; i<=n; i++){
scanf("%d", &i);
if(i==0){
break;
}
sum += i;
}
printf("%d\n", sum);
return 0;
}
</code></pre>
<p>However, the output isn't a favorable one.</p>
<p>If the input is: 1,2,3,4,5,0
The output should be:1,3,6,10,15</p>
<p>Right now it only outputs the total sum 15.</p>
<p>I'm new to programming and thankful for any advice on what I might be doing wrong :)</p>
|
[
{
"answer_id": 74580475,
"author": "Muhammad Shafique Attari",
"author_id": 11185806,
"author_profile": "https://Stackoverflow.com/users/11185806",
"pm_score": 0,
"selected": false,
"text": " const [ClientsList, setUsersList] = useState({}); \n\n ///To////\n\n const [ClientsList, setUsersList] = useState([]); \n"
},
{
"answer_id": 74580549,
"author": "Amirhossein",
"author_id": 11342834,
"author_profile": "https://Stackoverflow.com/users/11342834",
"pm_score": 2,
"selected": false,
"text": "const [ClientsList, setUsersList] = useState([]);\n React.useEffect(() => {\n \n let BaseURL = 'https://******.com/taxplanner/rest-apis/users/clientslist';\n \n fetch(BaseURL, {\n method: 'POST',\n data: {id:loggedIn}\n })\n .then((response) => response.json())\n .then((res) => {\n setUsersList(res.clients); \n })\n .catch((error) => {\n console.log(error);\n });\n}, []);\n const [usersList, setUsersList] = useState([]); \n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74580370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20586358/"
] |
74,580,371
|
<p>Hi I'm using 3GB txt file and want to change it to CSV but it gives error_bad_lines</p>
<pre><code>ParserError: ' ' expected after '"'
</code></pre>
<p>Code I am using</p>
<pre><code>df1 = df.read_csv("path\\logs.txt", delimiter = "\t", encoding = 'cp437',engine="python")
df1.to_csv("C:\\Data\\log1.csv",quotechar='"',error_bad_lines=False, header=None, on_bad_lines='skip')
</code></pre>
|
[
{
"answer_id": 74580475,
"author": "Muhammad Shafique Attari",
"author_id": 11185806,
"author_profile": "https://Stackoverflow.com/users/11185806",
"pm_score": 0,
"selected": false,
"text": " const [ClientsList, setUsersList] = useState({}); \n\n ///To////\n\n const [ClientsList, setUsersList] = useState([]); \n"
},
{
"answer_id": 74580549,
"author": "Amirhossein",
"author_id": 11342834,
"author_profile": "https://Stackoverflow.com/users/11342834",
"pm_score": 2,
"selected": false,
"text": "const [ClientsList, setUsersList] = useState([]);\n React.useEffect(() => {\n \n let BaseURL = 'https://******.com/taxplanner/rest-apis/users/clientslist';\n \n fetch(BaseURL, {\n method: 'POST',\n data: {id:loggedIn}\n })\n .then((response) => response.json())\n .then((res) => {\n setUsersList(res.clients); \n })\n .catch((error) => {\n console.log(error);\n });\n}, []);\n const [usersList, setUsersList] = useState([]); \n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74580371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20604779/"
] |
74,580,413
|
<p>I'm writing a Rust <a href="https://github.com/btzy/nfde-rs" rel="noreferrer">library</a> that wraps around some platform-specific API calls (in this case, to open the file picker).</p>
<p>On Linux, there are two ways ("backends") to open the file picker - using GTK or using Portals (what they actually are doesn't matter very much for the purposes of this question - just think of them as two different system libraries that one can use to open the file picker). Typically, the choice depends on whether the application developer wants portability (GTK) or "native"-ness (Portal), and the choice of backend affects the libraries that my library needs to link (specified in build.rs). It is impossible to use both, since the interface exposed to the user is identical (and that's the point - the code calling my library shouldn't have to care about what backend is being used, and only link with one of the system libraries).</p>
<p>How should one write the Cargo.toml file to allow the user of my library to pick the backend they want?</p>
<p>In CMake, this would typically look like the following:</p>
<pre><code>set(BACKEND "GTK" CACHE STRING "Select the backend (GTK or Portal)")
</code></pre>
<p>In Cargo, we have "<a href="https://doc.rust-lang.org/cargo/reference/features.html" rel="noreferrer">features</a>". However, features can only be "enabled" or "disabled", and semantically features seem to be meant to conditionally <em>add</em> code into the library to be compiled. While there's a section about mutually exclusive features, it looks very much like a hack, and the other options don't seem to be ideal either.</p>
<p>Ideally, if other libraries have a dependency on my library, they shouldn't need to (or even try to) select the desired backend. The developer of the final executable application should be the one making the decision.</p>
|
[
{
"answer_id": 74581229,
"author": "Finomnis",
"author_id": 2902833,
"author_profile": "https://Stackoverflow.com/users/2902833",
"pm_score": 2,
"selected": false,
"text": "trait struct trait Option<dyn BackendTrait> main"
},
{
"answer_id": 74586266,
"author": "Chayim Friedman",
"author_id": 7884305,
"author_profile": "https://Stackoverflow.com/users/7884305",
"pm_score": 0,
"selected": false,
"text": "gtk portals #[cfg(not(any(\n all(feature = \"gtk\", not(feature = \"portals\")),\n all(feature = \"portals\", not(feature = \"gtk\")),\n)))]\ncompile_error!(\"only one, and exactly one of the features `gtk` and `portals` must be enabled.\");\n gtk portals [features]\ndefault = [\"gtk\"]\ngtk = []\nportals = []\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74580413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1021959/"
] |
74,580,432
|
<p>I'm trying to hide all <code><thead></thead></code> except first table by using the following CSS rule:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>@media screen {
.container>table:not(:first-child)>thead {
display: none !important;
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
<div>Table Caption</div>
<table>
<thead></thead>
<tbody></tbody>
</table>
<div>Table Caption</div>
<table>
<thead></thead>
<tbody></tbody>
</table>
<div>Table Caption</div>
<table>
<thead></thead>
<tbody></tbody>
</table>
</div></code></pre>
</div>
</div>
</p>
<p>But this rule hides all <code><thead></thead></code>. Any help?</p>
|
[
{
"answer_id": 74580697,
"author": "F. Müller",
"author_id": 1294283,
"author_profile": "https://Stackoverflow.com/users/1294283",
"pm_score": -1,
"selected": false,
"text": "<thead> @media screen {\n .container>table:not(:first-child)>thead {\n display: none !important;\n }\n} <div class=\"container\">\n <table>\n <caption>Table Caption 1</caption>\n <thead>\n <tr>\n <th>Col1</th>\n <th>Col2</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>Lorem</td>\n <td>Ipsun</td>\n </tr>\n </tbody>\n </table>\n <table>\n <caption>Table Caption 2</caption>\n <thead>\n <tr>\n <th>Col1</th>\n <th>Col2</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>Lorem</td>\n <td>Ipsun</td>\n </tr>\n </tbody>\n </table>\n <table>\n <caption>Table Caption 3</caption>\n <thead>\n <tr>\n <th>Col1</th>\n <th>Col2</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>Lorem</td>\n <td>Ipsun</td>\n </tr>\n </tbody>\n </table>\n</div>"
},
{
"answer_id": 74581288,
"author": "A Haworth",
"author_id": 10867454,
"author_profile": "https://Stackoverflow.com/users/10867454",
"pm_score": 0,
"selected": false,
"text": ".container>table:not(:first-of-type)>thead {\n display: none;\n} <div class=\"container\">\n <div>Table Caption</div>\n <table>\n <thead>\n <tr>\n <th>thead1</th>\n </tr>\n </thead>\n <tbody></tbody>\n </table>\n <div>Table Caption</div>\n <table>\n <thead>\n <tr>\n <th>thead2</th>\n </tr>\n </thead>\n <tbody></tbody>\n </table>\n <div>Table Caption</div>\n <table>\n <thead>\n <tr>\n <th>thead3</th>\n </tr>\n </thead>\n <tbody></tbody>\n </table>\n</div>"
},
{
"answer_id": 74583741,
"author": "Rohit Khandelwal",
"author_id": 15220748,
"author_profile": "https://Stackoverflow.com/users/15220748",
"pm_score": 1,
"selected": true,
"text": ":not :first-of-type thead CSS thead @media screen {\n .container>:not(table:first-of-type)>thead {\n display: none;\n }\n} <div class=\"container\">\n <div>Table Caption</div>\n <table>\n <thead>\n <tr>\n <td>xyz-head</td>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>xyz-body</td>\n </tr>\n </tbody>\n </table>\n <div>Table Caption</div>\n <table>\n <thead>\n <tr>\n <td>zxc-head</td>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>zxc-body</td>\n </tr>\n </tbody>\n </table>\n <div>Table Caption</div>\n <table>\n <thead>\n <tr>\n <td>esd-head</td>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>esd-body</td>\n </tr>\n </tbody>\n </table>\n</div>"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74580432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/770135/"
] |
74,580,452
|
<p>I have some data in an object called all_lines that is a character class in R (as a result of reading into R a PDF file). My objective: to delete everything before a certain string and delete everything after another string.</p>
<p>The data looks like this and it is stored in the object all_lines</p>
<pre><code>class(all_lines)
"character"
[1] LABORATORY Research Cover Sheet
[2] Number 201111EZ Title Maximizing throughput"
[3] " in Computers
[4] Start Date 01/15/2000
....
[49] Introduction
[50] Some text here and there
[51] Look more text
....
[912] Citations
[913] Author_1 Paper or journal
[914] Author_2 Book chapter
</code></pre>
<p>I want to delete everything before the string 'Introduction' and everything after 'Citations'. However, nothing I find seems to do the trick. I have tried the following commands from these posts: <a href="https://stackoverflow.com/questions/53503266/how-to-delete-everything-after-matching-string-in-r">How to delete everything after a matching string in R</a> and multiple on-line R tutorials on how to do just this. Here are some commands that I have tried and all I get is the string 'Introduction' deleted in the all_lines with everything else returned.</p>
<pre><code>str_remove(all_lines, "^.*(?=(Introduction))")
sub(".*Introduction", "", all_lines)
gsub(".*Introduction", "", all_lines)
</code></pre>
<p>I have also tried to delete everything after the string 'Citations' using the same commands, such as:</p>
<pre><code>sub("Citations.*", "", all_lines)
</code></pre>
<p>Am I missing anything? Any help would really be appreciated!</p>
|
[
{
"answer_id": 74580700,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 0,
"selected": false,
"text": "gsub() all_lines <- paste(all_lines, collapse = \" \")\noutput <- gsub(\"^.*?(?=\\\\bIntroduction\\\\b)|(?<=\\\\bCitations\\\\b).*$\", \"\", all_lines)\n"
},
{
"answer_id": 74583397,
"author": "Dave2e",
"author_id": 5792244,
"author_profile": "https://Stackoverflow.com/users/5792244",
"pm_score": 2,
"selected": true,
"text": "grep() #line numbers containing the start and end\nIntro <- grep(\"Introduction\", all_lines)\nCitation <- grep(\"Citations\", all_lines)\n\n#extract out the desired portion.\nabridged <- all_lines[Intro:Citation]\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74580452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7504055/"
] |
74,580,472
|
<p>I am trying to remove Test2 value from an input decorator value from the change component. But not able to remove it. so how to get solution for this.</p>
<p>change component:</p>
<pre><code>export class ChangeComponent implements OnInit {
@ViewChild('changeComponent') changeComponent: TableComponent;
constructor() {}
ngOnInit() {}
changeName() {
this.changeComponent.names.pop('Test2');
console.log(this.changeComponent.names);
}
}
</code></pre>
<p>Demo:<a href="https://stackblitz.com/edit/angular-pass-table-data-to-input-property-qvwy2q?file=src%2Fapp%2Fapp.component.ts" rel="nofollow noreferrer">https://stackblitz.com/edit/angular-pass-table-data-to-input-property-qvwy2q?file=src%2Fapp%2Fapp.component.ts</a></p>
|
[
{
"answer_id": 74580700,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 0,
"selected": false,
"text": "gsub() all_lines <- paste(all_lines, collapse = \" \")\noutput <- gsub(\"^.*?(?=\\\\bIntroduction\\\\b)|(?<=\\\\bCitations\\\\b).*$\", \"\", all_lines)\n"
},
{
"answer_id": 74583397,
"author": "Dave2e",
"author_id": 5792244,
"author_profile": "https://Stackoverflow.com/users/5792244",
"pm_score": 2,
"selected": true,
"text": "grep() #line numbers containing the start and end\nIntro <- grep(\"Introduction\", all_lines)\nCitation <- grep(\"Citations\", all_lines)\n\n#extract out the desired portion.\nabridged <- all_lines[Intro:Citation]\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74580472",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19099386/"
] |
74,580,505
|
<p>I have a Vue front end that collects data (and files) from a user and POST it to a Django Rest Framework end point using Axios.</p>
<p>Here is the code for that function:</p>
<pre><code>import { ref } from "vue";
import axios from "axios";
const fields = ref({
audience: "",
cancomment: "",
category: "",
body: "",
errors: [],
previews: [],
images: [],
video: [],
user: user,
});
function submitPost() {
const formData = {
'category': fields.value.category.index,
'body': fields.value.body,
'can_view': fields.value.audience,
'can_comment': fields.value.cancomment,
'video': fields.value.video,
'uploaded_images': fields.value.images,
'user': store.userId
};
console.log(formData['uploaded_images'])
axios
.post('api/v1/posts/create/', formData, {
headers: {
"Content-Type": "multipart/form-data",
"X-CSRFToken": "{{csrf-token}}"
}
})
.then((response) => {
if(response.status == 201){
store.messages.push("Post created successfully")
}
})
.catch((error) => {
messages.value.items.push(error.message)
})
}
</code></pre>
<p>When I post data the response I see on the server side is:</p>
<pre><code>uploaded_data = validated_data.pop('uploaded_images')
KeyError: 'uploaded_images'
</code></pre>
<p>that comes from this serializer:</p>
<pre><code>class PostImageSerializer(serializers.ModelSerializer):
class Meta:
model = PostImage
fields = ['image', 'post']
class PostSerializer(serializers.ModelSerializer):
images = PostImageSerializer(many=True, read_only=True, required=False)
uploaded_images = serializers.ListField(required=False, child=serializers.FileField(max_length=1000000, allow_empty_file=False, use_url=False),write_only=True)
class Meta:
model = Post
fields = [
"category",
"body",
"images",
"uploaded_images",
"video",
"can_view",
"can_comment",
"user",
"published",
"pinned",
"created_at",
"updated_at",
]
def create(self, validated_data):
uploaded_data = validated_data.pop('uploaded_images')
new_post = Post.objects.create(**validated_data)
try:
for uploaded_item in uploaded_data:
PostImage.objects.create(post = new_post, images = uploaded_item)
except:
PostImage.objects.create(post=new_post)
return new_post
</code></pre>
<p>Trying to make sense of this so am I correct in my thinking that DRF saves the serializer when the data is sent to the endpoint? The variable validated_data I presume is the request.data object? Why am I getting the KeyError then and how can I see what the data is that is being validated, or sent in the post request on the server side. The data sent in the post request in the browser looks like this:</p>
<pre><code>-----------------------------2091287168172869498837072731
Content-Disposition: form-data; name="body"
Post
-----------------------------2091287168172869498837072731
Content-Disposition: form-data; name="can_view"
Everybody
-----------------------------2091287168172869498837072731
Content-Disposition: form-data; name="can_comment"
Everybody
-----------------------------2091287168172869498837072731
Content-Disposition: form-data; name="uploaded_images.0"; filename="tumblr_42e2ad7e187aaa1b4c6f4f7e698d03f2_c9a2b230_640.jpg"
Content-Type: image/jpeg
-----------------------------2091287168172869498837072731
Content-Disposition: form-data; name="body"
Post
-----------------------------2091287168172869498837072731
Content-Disposition: form-data; name="can_view"
Everybody
-----------------------------2091287168172869498837072731
Content-Disposition: form-data; name="can_comment"
Everybody
-----------------------------2091287168172869498837072731
Content-Disposition: form-data; name="uploaded_images.0"; filename="tumblr_42e2ad7e187aaa1b4c6f4f7e698d03f2_c9a2b230_640.jpg"
Content-Type: image/jpeg
(¼T¼Þ7ó[®«ý;>7гô
eIqegy[XbkéÉc¤ÎSFÌÔÂåÄAR§*P!I<R,4AP9ÖgÅÖYÔ×éu«ÅÉ<IJª+`,.uòÜtK7xéu.Ô¬]{ù£æÍ÷·n²±×:îã¡`UÐKxªyjxñDUAP¢+ÄÅB1yõçùuS5å
D÷ zö4®n¦Öod&<z¼P
W9©xeúD5ÈMpÖö¬ðÓKÊľO«oµÊMçÇy|z=^<AKêôz¼x##:ù;«OdÞ¢¶WRùººRêÜêú8ø¡ãÄ"¼AãÅj¿3ÆõÙRÆ]_MTÆ^;;
`ttR}mì¤*bêwy¾=d<xòøòxÄ(
</code></pre>
<p>Here is the ViewSet that sits at the endpoint:</p>
<pre><code>class PostViewSet(viewsets.ModelViewSet):
queryset = Post.objects.all()
serializer_class = PostSerializer
filter_backends = [django_filters.rest_framework.DjangoFilterBackend, filters.SearchFilter, django_filters.rest_framework.OrderingFilter]
# filterset_class = PostFilter
ordering_fields = ['created_at',]
search_fields = ['category', 'body']
permission_classes = [permissions.IsAuthenticated]
def get_serializer_context(self):
return {'request': self.request}
parser_classes = [MultiPartParser, FormParser]
lookup_field = 'slug'
</code></pre>
|
[
{
"answer_id": 74580700,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 0,
"selected": false,
"text": "gsub() all_lines <- paste(all_lines, collapse = \" \")\noutput <- gsub(\"^.*?(?=\\\\bIntroduction\\\\b)|(?<=\\\\bCitations\\\\b).*$\", \"\", all_lines)\n"
},
{
"answer_id": 74583397,
"author": "Dave2e",
"author_id": 5792244,
"author_profile": "https://Stackoverflow.com/users/5792244",
"pm_score": 2,
"selected": true,
"text": "grep() #line numbers containing the start and end\nIntro <- grep(\"Introduction\", all_lines)\nCitation <- grep(\"Citations\", all_lines)\n\n#extract out the desired portion.\nabridged <- all_lines[Intro:Citation]\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74580505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9361135/"
] |
74,580,506
|
<p>2 tables employee_1 and bonus_1 joined and trying to update but gives me the error -</p>
<pre><code>ERROR REPORT UNKNOWN COMMAND
</code></pre>
<pre class="lang-sql prettyprint-override"><code>UPDATE(
SELECT e.first_name,
sum(b.bonus_amount) as bon
from employee_1 e
LEFT join bonus_1 b
on e.employee_id=b.employee_id
group by e.first_name
)
set bon=0.2*e.salary
where bon IS NULL;
</code></pre>
<p>Please help me update this join query to give 2% bonus to employees whose bonus amount will be null in <code>bonus_amount</code>.</p>
|
[
{
"answer_id": 74580700,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 0,
"selected": false,
"text": "gsub() all_lines <- paste(all_lines, collapse = \" \")\noutput <- gsub(\"^.*?(?=\\\\bIntroduction\\\\b)|(?<=\\\\bCitations\\\\b).*$\", \"\", all_lines)\n"
},
{
"answer_id": 74583397,
"author": "Dave2e",
"author_id": 5792244,
"author_profile": "https://Stackoverflow.com/users/5792244",
"pm_score": 2,
"selected": true,
"text": "grep() #line numbers containing the start and end\nIntro <- grep(\"Introduction\", all_lines)\nCitation <- grep(\"Citations\", all_lines)\n\n#extract out the desired portion.\nabridged <- all_lines[Intro:Citation]\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74580506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20604900/"
] |
74,580,519
|
<p>If there is an incorrect user input that was put into the commandline, for example I clear it by using</p>
<pre><code>menu:
answer = Console.ReadLine();
if(!int.TryParse(answer, out val))
{
Console.Clear();
goto menu;
}
</code></pre>
<p>However, doing this clears all the console window, what I want to know is that if there is a way to only clear the unwanted/incorrect user input and leave the rest of the Command Line stay the same and uncleared.</p>
|
[
{
"answer_id": 74580741,
"author": "Steve",
"author_id": 1197518,
"author_profile": "https://Stackoverflow.com/users/1197518",
"pm_score": 2,
"selected": true,
"text": "static void Main(string[] args)\n{\n Console.SetCursorPosition(5, 5);\n Console.Write(\"Hello:\");\n while (true)\n {\n string input = Console.ReadLine();\n if (Int32.TryParse(input, out int val))\n {\n Console.WriteLine(\" Valid input. Exiting \");\n break;\n\n }\n Console.WriteLine(\" Invalid input. Try again\");\n Console.SetCursorPosition(11, 5);\n string delete = new string(' ', input.Length);\n Console.Write(delete);\n Console.SetCursorPosition(11, 5);\n }\n}\n"
},
{
"answer_id": 74581168,
"author": "Programmable Physics",
"author_id": 19987539,
"author_profile": "https://Stackoverflow.com/users/19987539",
"pm_score": 0,
"selected": false,
"text": " int val;\n string answer; \n var top = Console.CursorTop;\n var left = Console.CursorLeft;\n menu:\n answer = Console.ReadLine();\n if (!int.TryParse(cevap, out val))\n {\n Console.SetCursorPosition(left, top);\n Console.Write(new string(' ', answer.Length));\n Console.SetCursorPosition(left, top);\n goto menu;\n }\n while(true){} top = Console.CursorTop;\n left = Console.CursorLeft;\n string answer1;\n while (true)\n {\n answer1 = Console.ReadLine();\n\n if (int.TryParse(answer1, out val))\n {\n break;\n }\n\n Console.SetCursorPosition(left, top);\n Console.Write(new string(' ', answer1.Length));\n Console.SetCursorPosition(left, top);\n }\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74580519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19987539/"
] |
74,580,527
|
<p>I have a simple graph to make, whose source code is below:</p>
<pre><code>import pandas as pd
def plot_responses(index, y):
index='Arsen initial'
y=pd.Series({1: 0.8, 2: 0.8, 3: 0.59, 4: 0.54, 5: 0.86, 6: 0.54, 7: 0.97, 8: 0.69, 9: 1.39, 10: 0.95, 11: 2.12, 12: 1.95, 13: 0.99, 14: 0.76, 15: 0.82, 16: 0.63, 17: 1.09, 18: 0.9, 19: 1.0, 20: 0.84, 21: 0.71, 22: 0.71, 23: 0.59, 24: 0.58, 25: 1.66, 26: 1.48, 27: 1.71, 28: 1.69, 29: 1.98, 30: 1.22, 31: 1.09, 32: 1.41, 33: 1.11, 34: 0.83, 35: 4.11, 36: 4.81, 37: 5.28, 38: 4.87, 39: 4.66, 40: 5.1, 41: 0.61, 42: 0.58, 43: 0.74, 44: 0.43, 45: 0.69, 46: 0.43, 47: 0.62, 48: 0.2, 49: 0.77, 50: 0.93, 51: 0.56, 52: 0.77, 53: 0.91, 54: 0.55, 55: 1.15, 56: 0.53, 57: 0.62, 58: 0.42, 59: 0.55, 60: 0.41, 61: 0.67, 62: 0.5, 63: 0.72, 64: 0.53, 65: 0.77, 66: 0.68, 67: 0.65, 68: 0.42, 69: 0.59, 70: 0.3, 71: 0.8, 72: 0.54, 73: 0.61, 74: 0.77, 75: 0.8, 76: 0.37, 77: 1.21, 78: 0.73, 79: 0.81, 80: 0.8, 81: 0.45, 82: 0.43})
values_for_5 = []
values_for_30 = []
for i in range(1, y.size + 1):
if i % 2 == 0:
values_for_5.append(y[i])
else:
values_for_30.append(y[i])
sample_no_for_5 = [i for i in range(1, len(y), 2)]
sample_no_for_30 = [i + 1 for i in range(1, len(y), 2)]
fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(1, 1, 1)
ax.spines['left'].set_position('zero')
ax.plot(sample_no_for_5, values_for_5, 'yo')
ax.plot(sample_no_for_30, values_for_30, 'bo')
plt.xlabel('Numarul mostrei', fontsize=15)
plt.ylabel(index, fontsize=15)
plt.title('Continutul de ' + str(index.replace(' initial', '')) + ' din gudronul acid netratat')
for i in range(len(values_for_30)):
ax.text(sample_no_for_5[i], values_for_5[i], '5')
ax.text(sample_no_for_30[i], values_for_30[i], '30')
plt.xticks(range(0, y.size, 5))
ax.grid()
plt.savefig(str(index.replace('initial', '').strip()) + '.jpg')
plt.show()
</code></pre>
<p>Running this code, I get the following figure:</p>
<p><a href="https://i.stack.imgur.com/el4ZL.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/el4ZL.jpg" alt="Initial picture" /></a></p>
<p>Which is pretty good, but I want two more things and I don't know how to do it:</p>
<ol>
<li>I want to make the origin of the y-axis overlap to the origin of the x-axis (the two zeros to have the same place);</li>
<li>I want to get rid of the grid lines from the left of the y-axis</li>
</ol>
<p>How do I do that?</p>
|
[
{
"answer_id": 74580741,
"author": "Steve",
"author_id": 1197518,
"author_profile": "https://Stackoverflow.com/users/1197518",
"pm_score": 2,
"selected": true,
"text": "static void Main(string[] args)\n{\n Console.SetCursorPosition(5, 5);\n Console.Write(\"Hello:\");\n while (true)\n {\n string input = Console.ReadLine();\n if (Int32.TryParse(input, out int val))\n {\n Console.WriteLine(\" Valid input. Exiting \");\n break;\n\n }\n Console.WriteLine(\" Invalid input. Try again\");\n Console.SetCursorPosition(11, 5);\n string delete = new string(' ', input.Length);\n Console.Write(delete);\n Console.SetCursorPosition(11, 5);\n }\n}\n"
},
{
"answer_id": 74581168,
"author": "Programmable Physics",
"author_id": 19987539,
"author_profile": "https://Stackoverflow.com/users/19987539",
"pm_score": 0,
"selected": false,
"text": " int val;\n string answer; \n var top = Console.CursorTop;\n var left = Console.CursorLeft;\n menu:\n answer = Console.ReadLine();\n if (!int.TryParse(cevap, out val))\n {\n Console.SetCursorPosition(left, top);\n Console.Write(new string(' ', answer.Length));\n Console.SetCursorPosition(left, top);\n goto menu;\n }\n while(true){} top = Console.CursorTop;\n left = Console.CursorLeft;\n string answer1;\n while (true)\n {\n answer1 = Console.ReadLine();\n\n if (int.TryParse(answer1, out val))\n {\n break;\n }\n\n Console.SetCursorPosition(left, top);\n Console.Write(new string(' ', answer1.Length));\n Console.SetCursorPosition(left, top);\n }\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74580527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1999585/"
] |
74,580,543
|
<p>I'm newish to HTML/CSS (~2 months overall) and stack overflow (first post). Using fontawesome.com my idea is to make this icon flip when the cursor hovers over it. The icon flips when the class includes 'fa-flip' and doesn't when it's not. So I was trying to change the class with hover. How can i fix this?</p>
<p>HTML:</p>
<p><code><body></code>
<code><i class="fa-solid fa-user"></i></code>
<code></body></code></p>
<p>CSS:</p>
<p><code>body[class="fa-solid fa-user fa-flip"]:hover</code></p>
<p><code>{<i class="fa-solid fa-user fa-flip"></i>}</code></p>
|
[
{
"answer_id": 74580741,
"author": "Steve",
"author_id": 1197518,
"author_profile": "https://Stackoverflow.com/users/1197518",
"pm_score": 2,
"selected": true,
"text": "static void Main(string[] args)\n{\n Console.SetCursorPosition(5, 5);\n Console.Write(\"Hello:\");\n while (true)\n {\n string input = Console.ReadLine();\n if (Int32.TryParse(input, out int val))\n {\n Console.WriteLine(\" Valid input. Exiting \");\n break;\n\n }\n Console.WriteLine(\" Invalid input. Try again\");\n Console.SetCursorPosition(11, 5);\n string delete = new string(' ', input.Length);\n Console.Write(delete);\n Console.SetCursorPosition(11, 5);\n }\n}\n"
},
{
"answer_id": 74581168,
"author": "Programmable Physics",
"author_id": 19987539,
"author_profile": "https://Stackoverflow.com/users/19987539",
"pm_score": 0,
"selected": false,
"text": " int val;\n string answer; \n var top = Console.CursorTop;\n var left = Console.CursorLeft;\n menu:\n answer = Console.ReadLine();\n if (!int.TryParse(cevap, out val))\n {\n Console.SetCursorPosition(left, top);\n Console.Write(new string(' ', answer.Length));\n Console.SetCursorPosition(left, top);\n goto menu;\n }\n while(true){} top = Console.CursorTop;\n left = Console.CursorLeft;\n string answer1;\n while (true)\n {\n answer1 = Console.ReadLine();\n\n if (int.TryParse(answer1, out val))\n {\n break;\n }\n\n Console.SetCursorPosition(left, top);\n Console.Write(new string(' ', answer1.Length));\n Console.SetCursorPosition(left, top);\n }\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74580543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20513242/"
] |
74,580,570
|
<p>Can't bind to 'dataSource' since it isn't a known property of 'mat-table'.</p>
<ol>
<li>If 'mat-table' is an Angular component and it has 'dataSource' input, then verify that it is part of this module.</li>
<li>If 'mat-table' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.</li>
<li>To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.</li>
</ol>
<p>This is my app.component.html file</p>
<pre><code><mat-table #table [dataSource]="dataSource" >
<!-- Checkbox Column -->
<ng-container matColumnDef="select">
<th mat-header-cell *matHeaderCellDef>
<mat-checkbox (change)="$event ? toggleAllRows() : null"
[checked]="selection.hasValue() && isAllSelected()"
[indeterminate]="selection.hasValue() && !isAllSelected()"
[aria-label]="checkboxLabel()">
</mat-checkbox>
</th>
<td mat-cell *matCellDef="let row">
<mat-checkbox (click)="$event.stopPropagation()"
(change)="$event ? selection.toggle(row) : null"
[checked]="selection.isSelected(row)"
[aria-label]="checkboxLabel(row)">
</mat-checkbox>
</td>
</ng-container>
<!-- Position Column -->
<ng-container matColumnDef="position">
<th mat-header-cell *matHeaderCellDef> No. </th>
<td mat-cell *matCellDef="let element"> {{element.position}} </td>
</ng-container>
<!-- Name Column -->
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef> Name </th>
<td mat-cell *matCellDef="let element"> {{element.name}} </td>
</ng-container>
<!-- Weight Column -->
<ng-container matColumnDef="weight">
<th mat-header-cell *matHeaderCellDef> Weight </th>
<td mat-cell *matCellDef="let element"> {{element.weight}} </td>
</ng-container>
<!-- Symbol Column -->
<ng-container matColumnDef="symbol">
<th mat-header-cell *matHeaderCellDef> Symbol </th>
<td mat-cell *matCellDef="let element"> {{element.symbol}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"
(click)="selection.toggle(row)">
</tr>
</mat-table>
</code></pre>
|
[
{
"answer_id": 74581137,
"author": "Mohameden Haden",
"author_id": 14815961,
"author_profile": "https://Stackoverflow.com/users/14815961",
"pm_score": 1,
"selected": false,
"text": " ngAfterViewInit(): void {\n this.dataSource = new TablesDataSource(this.data);\n this.dataSource.sort = this.sort;\n this.dataSource.paginator = this.paginator;\n this.table.dataSource = this.dataSource;\n\n }\n"
},
{
"answer_id": 74590465,
"author": "Selaka Nanayakkara",
"author_id": 4672460,
"author_profile": "https://Stackoverflow.com/users/4672460",
"pm_score": 0,
"selected": false,
"text": "import { MatTableModule } from '@angular/material/table'\n imports: [\n CommonModule,\n MatTableModule <==\n ],\n import { MatTableDataSource, MatSort } from '@angular/material';\nimport { DataSource } from '@angular/cdk/table';\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74580570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15998078/"
] |
74,580,590
|
<p>Could someone help me with the following task? Unfortunately, I find it too complicated.</p>
<p>Write a recursive function ADD that takes a list as a parameter and adds all the numbers from the list together, sums up the result and outputs it. The function should be defined so that the passed list can also contain symbols and strings.</p>
<p>This is the function I wrote:</p>
<pre><code>(defun add (l)
(cond
((null l) nil)
((not (numberp (first l))) nil) (add (rest l))
((numberp (first l) (+ (first l) (add (rest l)))))
(t (+ (add (first l) (add (rest l)))))))`
</code></pre>
|
[
{
"answer_id": 74581161,
"author": "Martin Půda",
"author_id": 13590263,
"author_profile": "https://Stackoverflow.com/users/13590263",
"pm_score": 2,
"selected": false,
"text": "(defun add (l)\n (if (null l) 0\n (+ (first l) (add (rest l)))))\n (defun add (l)\n (cond ((null l) 0)\n ((numberp (first l))\n (+ (first l)\n (add (rest l))))\n (t (add (rest l)))))\n (defun add (l)\n (cond ((null l) 0)\n ((listp (first l))\n (+ (add (first l))\n (add (rest l))))\n (t (+ (first l)\n (add (rest l))))))\n (defun add (l)\n (cond ((null l) 0)\n ((listp (first l))\n (+ (add (first l))\n (add (rest l))))\n ((numberp (first l))\n (+ (first l)\n (add (rest l))))\n (t (add (rest l)))))\n > (add '(1 2 3 4 5 \"foo\" 6))\n21\n\n> (add '(\"bar\" 1 2 3 4 5 \"foo\" 6 'y))\n21\n\n> (add '((1 2 (3))))\n6\n"
},
{
"answer_id": 74584624,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 0,
"selected": false,
"text": "let* (defun add (lst)\n (if (null lst) \n 0\n (let* ((hd (first lst))\n (tl (rest lst))\n (sum-tl (add tl)))\n (cond ((numberp hd) \n (+ hd sum-tl))\n ((listp hd) \n (+ (add hd) sum-tl))\n (t sum-tl))))) \n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74580590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20434143/"
] |
74,580,650
|
<p>Here is a console command I wrote in Laravel, and I was wondering how can I make it better and faster?
What have I done wrong?</p>
<p>And if you can introtuce me a book so I can get better at algorithms and writing better code I would appreciate it.</p>
<p>Thanks</p>
<pre><code>$process = Process::create([
'started_at' => now()
]);
//set how many subscription to get from db in each iteration
//we use this for loop to prevent memory exhaustion
$subscriptionsCountPerIteration = 1000;
$subscriptionsCount = Subscription::count();
$numberOfIterations = $subscriptionsCount/$subscriptionsCountPerIteration;
for($i=0; $i < $numberOfIterations; $i++){
$subscriptions = Subscription::query()->limit($subscriptionsCountPerIteration)->offset($subscriptionsCountPerIteration * $i)->get();
foreach($subscriptions as $subscription){
$subscription->updateStatus($process);
}
}
$process->finished_at = now();
$process->save();
</code></pre>
<p>I think the fact that I have two loops is a bad Idea.</p>
|
[
{
"answer_id": 74581161,
"author": "Martin Půda",
"author_id": 13590263,
"author_profile": "https://Stackoverflow.com/users/13590263",
"pm_score": 2,
"selected": false,
"text": "(defun add (l)\n (if (null l) 0\n (+ (first l) (add (rest l)))))\n (defun add (l)\n (cond ((null l) 0)\n ((numberp (first l))\n (+ (first l)\n (add (rest l))))\n (t (add (rest l)))))\n (defun add (l)\n (cond ((null l) 0)\n ((listp (first l))\n (+ (add (first l))\n (add (rest l))))\n (t (+ (first l)\n (add (rest l))))))\n (defun add (l)\n (cond ((null l) 0)\n ((listp (first l))\n (+ (add (first l))\n (add (rest l))))\n ((numberp (first l))\n (+ (first l)\n (add (rest l))))\n (t (add (rest l)))))\n > (add '(1 2 3 4 5 \"foo\" 6))\n21\n\n> (add '(\"bar\" 1 2 3 4 5 \"foo\" 6 'y))\n21\n\n> (add '((1 2 (3))))\n6\n"
},
{
"answer_id": 74584624,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 0,
"selected": false,
"text": "let* (defun add (lst)\n (if (null lst) \n 0\n (let* ((hd (first lst))\n (tl (rest lst))\n (sum-tl (add tl)))\n (cond ((numberp hd) \n (+ hd sum-tl))\n ((listp hd) \n (+ (add hd) sum-tl))\n (t sum-tl))))) \n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74580650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14786603/"
] |
74,580,659
|
<p>For the given code</p>
<pre><code>def greater(n):
if n > 3:
res = True
else:
res = False
return res
a = greater(5)
print(hex(id(a)))
print(hex(id(True)))
b = True
print(hex(id(b)))
if a == True:
print('yes')
else:
print('no')
</code></pre>
<p><code>pylint</code> suggests <code>pylint_example.py:16:4: C0121: Comparison 'a == True' should be 'a is True' if checking for the singleton value True, or 'a' if testing for truthiness (singleton-comparison)</code></p>
<p><code>a is True</code> will check <a href="https://stackoverflow.com/questions/132988/is-there-a-difference-between-and-is">both address and value</a>
and I <a href="https://stackoverflow.com/questions/67657554/why-two-list-having-exactly-same-data-shows-different-memory-address-in-python-w">cannot assume immutable variables will have the same address</a></p>
<p>Thus, changing <code>a == True</code> to <code>a is True</code> may lead to incorrect results (<code>a</code> and <code>True</code> may have different addresses in memory). Why does <code>pylint</code> suggest that?</p>
<p>Though</p>
<pre><code>print(hex(id(a)))
print(hex(id(True)))
b = True
print(hex(id(b)))
</code></pre>
<p>part gives consistent results. I am not sure if that would work in general.</p>
|
[
{
"answer_id": 74580681,
"author": "Daweo",
"author_id": 10785975,
"author_profile": "https://Stackoverflow.com/users/10785975",
"pm_score": 0,
"selected": false,
"text": "if greeting:\n if greeting == True:\n if greeting is True:\n"
},
{
"answer_id": 74580711,
"author": "Dash",
"author_id": 11542834,
"author_profile": "https://Stackoverflow.com/users/11542834",
"pm_score": 3,
"selected": true,
"text": "True False a True a True"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74580659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20038265/"
] |
74,580,707
|
<p>A common problem in React, especially among beginners (like me). This is due to the fact that setState is an asynchronous function and React does not change values one by one, but accumulates some pool if it is not otherwise instructed. (please correct me if the wording is wrong)</p>
<p>So here's the question. One simple solution is to put the desired state into the useEffect dependency array.
For example, I have such a component:</p>
<pre><code>const [first, setFirst] = useState()
const [second, setSecond] = useState()
useEffect(() => {
Something logic by first and second...
}, [first])
</code></pre>
<p>Here, the useEffect is executed every time the first state changes. At the same time, at the moment of its operation, the second state is not relevant, next time it will become as it should be now, and so on. Always one step behind.</p>
<p>But if I add a second state to the useEffect dependency array, then everything works as it should.</p>
<pre><code>useEffect(() => {
Something logic by first and second...
}, [first, second])
</code></pre>
<p>At the same time, it is not necessary that the useEffect work on changing the second state, I added it only in order to have an up-to-date version inside the useEffect. Can I use the useEffect dependency array this way?</p>
|
[
{
"answer_id": 74580681,
"author": "Daweo",
"author_id": 10785975,
"author_profile": "https://Stackoverflow.com/users/10785975",
"pm_score": 0,
"selected": false,
"text": "if greeting:\n if greeting == True:\n if greeting is True:\n"
},
{
"answer_id": 74580711,
"author": "Dash",
"author_id": 11542834,
"author_profile": "https://Stackoverflow.com/users/11542834",
"pm_score": 3,
"selected": true,
"text": "True False a True a True"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74580707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18146547/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.