qid int64 4 22.2M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
74,425,441 | <p>This is for my class project, once a user has signed in and clicked on the members page, I wish for them to see the list of all the other members who've signed in previously and show how many projects they each have with a .length of the projects. Everything works except for the projects part and I don't know why. The error i'm getting is this:</p>
<p><a href="https://i.stack.imgur.com/AMkwa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AMkwa.png" alt="error I get" /></a></p>
<p>This is the page:
<a href="https://i.stack.imgur.com/YKBmy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YKBmy.png" alt="page" /></a></p>
<p>This is my firebase data:
<a href="https://i.stack.imgur.com/KbVRI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KbVRI.png" alt="firebase data" /></a></p>
<p>Thank you all truly!</p>
<p>This here is my code on the Membres.js file</p>
<pre><code>import { useState, useContext, useEffect } from "react";
import { onSnapshot, collection, addDoc } from 'firebase/firestore';
import { db } from '../../config/firebase';
import { authContexte } from "../../Contexte/authContexte";
import { Link } from "react-router-dom";
const Membres = () =>{
const ctx = useContext(authContexte);
const [membres, setMembres] = useState([]);
useEffect(() => {
const unsub = onSnapshot(collection(db, 'membres'), (snapshot) => {
setMembres(snapshot.docs.map(doc => {
return {
...doc.data(),
id: doc.id
};
}));
});
return unsub;
}, []);
return(
<ul className="list-group">
{membres.map((membre)=>(
<li className="list-group-item d-flex justify-content-between align-items-center" key={membre.nom + membre.email}>
{membre.nom} <p>{membre.email}</p>
<span className="badges">{membre.projets.length}</span> //Need this to work
{console.log(membre.projets)}
</li>
))}
</ul>
);
};
export default Membres;
</code></pre>
| [
{
"answer_id": 74425510,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 1,
"selected": false,
"text": "my_fun <- function(data,expr = ~ hp > 150){\n \n feols(mpg ~ disp + drat,\n data = data,\n subset = expr)\n}\n"
},
{
"answer_id": 74425751,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 2,
"selected": true,
"text": "rlang::new_formula()"
},
{
"answer_id": 74427913,
"author": "G. Grothendieck",
"author_id": 516548,
"author_profile": "https://Stackoverflow.com/users/516548",
"pm_score": 2,
"selected": false,
"text": "my_fun <- function(data, hp.c.off) {\n \n feols(mpg ~ disp + drat,\n data = data,\n subset = as.formula(paste(\"~ hp >\", hp.c.off)))\n}\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74425441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20495003/"
] |
74,425,460 | <p>I'm trying to print a whole number (such as 39 for example) in the following format: 39.
It must not be a str type object like '39.' for example, but a number</p>
<p>e. g. n = 39.0 should be printed like 39.</p>
<pre><code>n = 39.0
#magic stuff with output
39.
</code></pre>
<p>I tried using :.nf methods (:.0f apparently -- didn't work), print(float(39.)) or just print(39.)
In the first case, it looks like 39, in the second and third 39.0
I also tried float(str(39) + '.') and obviously it didn't work</p>
<p>Sorry, if it's a stupid question, I've been trying to solve it for several hours already, still can't find any information.</p>
| [
{
"answer_id": 74425500,
"author": "Mark Tolonen",
"author_id": 235698,
"author_profile": "https://Stackoverflow.com/users/235698",
"pm_score": 4,
"selected": true,
"text": "'#'"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74425460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20495861/"
] |
74,425,488 | <p>i’m a beginner and i’m just starting to learn how to python code. I’m having trouble with this one. Whenever I type in the correct result, it shows that it is incorrect still. I'm wondering what i'm missing or what I did wrong.</p>
<pre><code>array1 = ([5, 10, 15, 20, 25])
print("Question 2: What is the reverse of the following array?", array1)
userAns = input("Enter your answer: ")
array1.reverse()
arrayAns = array1
if userAns == arrayAns:
print("You are correct")
else:
print("You are incorrect")
</code></pre>
| [
{
"answer_id": 74425506,
"author": "StonedTensor",
"author_id": 6023918,
"author_profile": "https://Stackoverflow.com/users/6023918",
"pm_score": 0,
"selected": false,
"text": "input"
},
{
"answer_id": 74425514,
"author": "Celius Stingher",
"author_id": 11897007,
"author_profile": "https://Stackoverflow.com/users/11897007",
"pm_score": 1,
"selected": false,
"text": "input()"
},
{
"answer_id": 74425626,
"author": "kconsiglio",
"author_id": 20473839,
"author_profile": "https://Stackoverflow.com/users/20473839",
"pm_score": 0,
"selected": false,
"text": "temp = userAns.split(\",\")\nuserAns = [int(item) for item in temp]\n"
},
{
"answer_id": 74425636,
"author": "Mark",
"author_id": 2203038,
"author_profile": "https://Stackoverflow.com/users/2203038",
"pm_score": 0,
"selected": false,
"text": "input"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74425488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20495924/"
] |
74,425,490 | <p><strong>Problem</strong></p>
<p>I have a collection of images with linked captions on a page. I want them each to have identical HTML.</p>
<p>Typically, i copy and paste the HTML over and over for each item. The problem is, if i want to tweak the HTML, i have to do it for all of them. It's time-consuming, and there's risk of mistakes.</p>
<p><strong>Quick and Dirty Templating</strong></p>
<p>I'd like to write just one copy of the HTML, list the content items as plain text, and on page-render the HTML would get automatically repeated for each content-item.</p>
<p><strong>HTML</strong></p>
<pre><code><p><img src=IMAGE-URL>
<br>
<a target='_blank' href=LINK-URL>CAPTION</a></p>
</code></pre>
<p><strong>Content List</strong></p>
<pre><code>IMAGE-URL, LINK-URL, CAPTION
/data/khang.jpg, https://khangssite.com, Khang Le
/data/sam.jpg, https://samssite.com, Sam Smith
/data/joy.jpg, https://joyssite.com, Joy Jones
/data/sue.jpg, https://suessite.com, Sue Sneed
/data/dog.jpg, https://dogssite.com, Brown Dog
/data/cat.jpg, https://catssite.com, Black Cat
</code></pre>
<p><strong>Single Item</strong></p>
<p>Ideally, i could put the plain-text content for a single item anywhere on a page, with some kind of identifier to indicate which HTML template to use (similar to classes with CSS).</p>
<pre><code>TEMPLATE=MyTemplate1, IMAGE-URL=khang.jpg, LINK-URL=https://khangssite.com, CAPTION=Khang Le
</code></pre>
<p><strong>Implementation</strong></p>
<p>Templating systems are widely used, like <a href="https://docs.djangoproject.com/en/4.1/ref/templates/language/" rel="nofollow noreferrer">Django</a> and <a href="https://www.smarty.net/" rel="nofollow noreferrer">Smarty</a> on the server side, and Mustache on the client side. This question seeks a simple, single-file template solution, without using external libs.</p>
<p>I want to achieve this without a framework, library, etc. I'd like to put the HTML and content-list in the same .html file.</p>
<p>Definitely no database. It should be quick and simple to set it up within a page, without installing or configuring additional services.</p>
<p>Ideally, i'd like to do this without javascript, but that's not a strict requirement. If there's javascript, it should be ignorant of the fieldnames. Ideally, very short and simple. No jquery please.</p>
| [
{
"answer_id": 74425711,
"author": "Mister Jojo",
"author_id": 10669010,
"author_profile": "https://Stackoverflow.com/users/10669010",
"pm_score": 1,
"selected": false,
"text": "const arrData = \n [ { img: '/data/khang.jpg', link: 'https://khangssite.com', txt: 'Khang Le' } \n , { img: '/data/sam.jpg', link: 'https://samssite.com', txt: 'Sam Smith' } \n , { img: '/data/joy.jpg', link: 'https://joyssite.com', txt: 'Joy Jones' } \n , { img: '/data/sue.jpg', link: 'https://suessite.com', txt: 'Sue Sneed' } \n , { img: '/data/dog.jpg', link: 'https://dogssite.com', txt: 'Brown Dog' } \n , { img: '/data/cat.jpg', link: 'https://catssite.com', txt: 'Black Cat' } \n ] \n\nconst myObj = document.querySelector('#my-div')\n\narrData.forEach(({ img, link, txt }) => \n {\n myObj.innerHTML += `\n <p>\n <img src=\"${img}\">\n <br>\n <a target='_blank' href=\"${link}\">${txt}</a>\n </p>`\n });"
},
{
"answer_id": 74458819,
"author": "johny why",
"author_id": 209942,
"author_profile": "https://Stackoverflow.com/users/209942",
"pm_score": -1,
"selected": true,
"text": "<span id=\"template-container\"></span>\n\n<div hidden id=\"template-data\">\n IMG,, LINK,, CAPTION\n https://www.referenseo.com/wp-content/uploads/2019/03/image-attractive.jpg,, khangssite.com,, Khang Le\n https://i.redd.it/jeuusd992wd41.jpg,, suessite.com,, Sue Sneed\n https://picsum.photos/536/354,, catssite.com,, Black Cat\n</div>\n\n<template id=\"art-template\">\n <span class=\"art-item\">\n <p>\n <a href=\"${LINK}\" target=\"_blank\">\n <img src=\"${IMG}\" alt=\"\" />\n <br>\n ${CAPTION}\n </a>\n </p>\n </span>\n</template>\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74425490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/209942/"
] |
74,425,579 | <p>I have a dataframe with the following columns.
<a href="https://i.stack.imgur.com/MUqx2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MUqx2.png" alt="enter image description here" /></a>
When I do correlation matrix, I see only the columns that are of int data types. I am new to ML, Can someone guide me what is the mistake I am doing here ?</p>
<p><a href="https://i.stack.imgur.com/gAaGb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gAaGb.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74425595,
"author": "Kraigolas",
"author_id": 11659881,
"author_profile": "https://Stackoverflow.com/users/11659881",
"pm_score": 1,
"selected": false,
"text": "numeric_only"
},
{
"answer_id": 74425625,
"author": "Celius Stingher",
"author_id": 11897007,
"author_profile": "https://Stackoverflow.com/users/11897007",
"pm_score": 3,
"selected": true,
"text": "df.corr(numeric_only=False)\n"
},
{
"answer_id": 74425692,
"author": "Python16367225",
"author_id": 16367225,
"author_profile": "https://Stackoverflow.com/users/16367225",
"pm_score": 1,
"selected": false,
"text": "df = df.apply([pd.to_numeric])\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74425579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2511487/"
] |
74,425,580 | <p>I have the following in my <code>Modal.svelte</code> file:</p>
<pre class="lang-html prettyprint-override"><code><script>
import Modal from "svelte-simple-modal";
import { modalState } from "$lib/stores";
const imports = {
Person: () => import("./modals/Person.svelte")
};
</script>
<Modal>
{#if $modalState.open}
{#await imports[$modalState.type]() then module}
<svelte:component this={module.default} />
{/await}
{/if}
</Modal>
</code></pre>
<p>And this is what is in my <code>stores.js</code> file:</p>
<pre class="lang-js prettyprint-override"><code>import { writable } from "svelte/store";
export const modalState = writable({
open: true,
type: "Person",
});
</code></pre>
<p>This renders the contents of the passed <code>modalState.type</code> file (which is <code>modals/Person.svelte</code>) perfectly, but the content isn't nested in the <code>Modal</code> element whatsoever. There is no popup, no close button, and no greyed-out background.</p>
<p>How do I make sure the contents of the imported component are part of the <code>Modal</code> and not just added to the page like a non-modal component?</p>
| [
{
"answer_id": 74425595,
"author": "Kraigolas",
"author_id": 11659881,
"author_profile": "https://Stackoverflow.com/users/11659881",
"pm_score": 1,
"selected": false,
"text": "numeric_only"
},
{
"answer_id": 74425625,
"author": "Celius Stingher",
"author_id": 11897007,
"author_profile": "https://Stackoverflow.com/users/11897007",
"pm_score": 3,
"selected": true,
"text": "df.corr(numeric_only=False)\n"
},
{
"answer_id": 74425692,
"author": "Python16367225",
"author_id": 16367225,
"author_profile": "https://Stackoverflow.com/users/16367225",
"pm_score": 1,
"selected": false,
"text": "df = df.apply([pd.to_numeric])\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74425580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6456163/"
] |
74,425,591 | <p>I have a string and k = number, which is the length of a substring that has the same letter repeated in a row. How can I have the wanted output only?
The expected output: For length 3, found the substring ddd!</p>
<pre><code>my_string = 'aabadddefggg'
k = 3
x = 1
c = 1
while x < len(my_string):
if my_string\[x\] == my_string\[x-1\]:
c += 1
else:
c = 1
if c == k:
print("For length " + str(k) + ", found the substring " + my_string\[x\] \* k + "!")
break
else:
print("Didn't find a substring of length " + str(k))
break
x += 1
The output:
Didn't find a substring of length 3
Didn't find a substring of length 3
Didn't find a substring of length 3
Didn't find a substring of length 3
Didn't find a substring of length 3
For length 3, found the substring ddd!
</code></pre>
| [
{
"answer_id": 74425595,
"author": "Kraigolas",
"author_id": 11659881,
"author_profile": "https://Stackoverflow.com/users/11659881",
"pm_score": 1,
"selected": false,
"text": "numeric_only"
},
{
"answer_id": 74425625,
"author": "Celius Stingher",
"author_id": 11897007,
"author_profile": "https://Stackoverflow.com/users/11897007",
"pm_score": 3,
"selected": true,
"text": "df.corr(numeric_only=False)\n"
},
{
"answer_id": 74425692,
"author": "Python16367225",
"author_id": 16367225,
"author_profile": "https://Stackoverflow.com/users/16367225",
"pm_score": 1,
"selected": false,
"text": "df = df.apply([pd.to_numeric])\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74425591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20495967/"
] |
74,425,622 | <p>I have a row where i want to display an image on the left side and text on the right side. My image should have the same height as my text. My html looks like this:</p>
<pre><code><div class="container pt-3">
<div class="row pt-5 pb-5">
<div class="col-12 col-lg-6 order-lg-last">
<div class="text-start">
<h1 class="mx-auto mb-2">title...</h1>
<p style="text-align: justify !important">text...</p>
<p style="text-align: justify !important">text...</p>
</div>
</div>
<div class="col-12 col-lg-6">
<img
class="img-fluid"
src="../../../assets/img/participation.png"
alt="Participation"
/>
</div>
</div>
</div>
</code></pre>
<p>No matter what I try the image always exceeds the height of the neighbouring column and thus increases the height of the row. Any solutions for this?</p>
| [
{
"answer_id": 74427850,
"author": "CQLI",
"author_id": 1345734,
"author_profile": "https://Stackoverflow.com/users/1345734",
"pm_score": 2,
"selected": true,
"text": " @import url(https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css);\n .imgPlaceholder {\n position: relative;\n }\n .imgPlaceholder::before {\n content: \"\";\n position: absolute;\n width: 100%;\n height: 100%;\n background-image: url(https://images.pexels.com/photos/14297669/pexels-photo-14297669.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1);\n background-repeat: no-repeat;\n background-size: contain;\n background-position: center;\n }\n @media screen and (max-width: 991px){\n .wrapper {\n display: grid !important;\n grid-auto-rows: 1fr;\n }\n .imgPlaceholder::before {\n background-position: left;\n }\n }"
},
{
"answer_id": 74428919,
"author": "Sharif Mia",
"author_id": 8060704,
"author_profile": "https://Stackoverflow.com/users/8060704",
"pm_score": -1,
"selected": false,
"text": "<div class=\"container my-container pt-3\">\n <div class=\"row pt-5 pb-5\">\n <div class=\"col-12 col-lg-6 order-lg-last\">\n <div class=\"text-start\">\n <h1 class=\"mx-auto mb-2\">title...</h1>\n <p style=\"text-align: justify !important\">1.2. Your access to and use of the Service is conditioned on your acceptance of and compliance with these Terms. These Terms apply to all photographers, visitors, users and others who access and/or use the Service.\n 1.3. By accessing or using the Service, whether as a photographer, visitor or user of the Website, you agree to be bound by these Terms. These Terms serve to protect and safeguard your rights, the rights of other users, our rights and the rights of third parties in the course of operating the Website. If you do not agree to the terms of use, you must immediately stop using any part of the Service.\n 1.4. We reserve the right to change or adapt these Terms at any time and without giving reasons with effect for the future. You will be notified of these changes at least two weeks before they take effect by posting them on the Website and should you have created a user account on our Website by notifying your registered e-mail address. You have the right to immediately cancel and terminate your account on our Website if you do not agree to the changes to the Terms. Changes shall be deemed approved by you if you continue to use the Service after the new Terms come into effect.\n 1.5. The use of the Service is subject to the Terms in force at the time of use.\n 2. Accounts and Registration\n 2.1. You have the option of creating a user account on our Website so that you can use the additional functions of the Website, in particular for uploading photos and other Content or for participating in any contests made available through the Service. The opening of a user account can only take place with the agreement to these Terms.\n 2.2. Upon registration, Pexels and you enter into a contract for the use of the Website and the Services. There is no claim to the conclusion of this contract. Pexels is entitled to refuse your registration without giving reasons.\n 2.3. You may only register with Pexels if you are 18 years of age or if you act with the consent of your parents or guardian to register under these Terms. Pexels reserves the right to verify the consent of your parents or guardian. Therefore, you must provide an e-mail address of your parents or guardian when you register, so that we can obtain a declaration of consent from your parents or guardian.\n 2.4. When you create an account with us, you must provide us with the information and data requested by Pexels that is accurate, complete, and current at all times. If your data changes after registration, you are obliged to correct the information in your account immediately.\n 2.5. You may not use as a username the name of another person or entity or that is not lawfully available for use, a name or trademark that is subject to any rights of another person or entity other than you without authorization, or a name that is otherwise offensive, vulgar or obscene.\n 2.6. You are responsible for safeguarding the password that you use to access the Service and for any activities or actions under your password, whether your password is with our Service or a third-party service. If you are not responsible for the misuse of your member account, you are not liable. You agree not to disclose your password to any third party. You must notify us immediately at info@pexels.com upon becoming aware of any breach of security or unauthorized use of your account.</p>\n <p style=\"text-align: justify !important\">text...</p>\n </div>\n </div>\n <div class=\"col-12 col-lg-6\">\n <img class=\"img-fluid\" src=\"https://images.pexels.com/photos/8342074/pexels-photo-8342074.jpeg?auto=compress&cs=tinysrgb&w=600&lazy=load\" alt=\"Participation\" />\n </div>\n </div>\n</div>\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74425622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17390662/"
] |
74,425,660 | <p>I am working with Puppeteer and trying to get each item informations from Amazon.</p>
<p>I want get the 10 first result items from this <a href="https://www.amazon.com/s?k=rtx%203070&ref=nb_sb_ss_pltr-ranker-24hours_2_2" rel="nofollow noreferrer">article</a>, but nothing can do</p>
<p>I already test all class on Chrome console, this returns what I want</p>
<pre><code>(async() => {
const browser = await puppeteer.launch({headless: false});
const page = await browser.newPage();
await page.setViewport({ width: 1366, height: 768});
await page.goto("https://www.amazon.com/s?k=rtx+3070&ref=nb_sb_ss_pltr-ranker-24hours_2_2");
const itemList = [];
//class elements
const item = await page.$(".sg-col-20-of-24.s-result-item.s-asin.sg-col-0-of-12.sg-col-16-of-20.sg-col.s-widget-spacing-small.sg-col-12-of-16");
const item_title = await page.$(".a-size-medium.a-color-base.a-text-normal");
const item_img = await page.$(".s-image");
const item_price = await page.$(".a-price-whole");
const item_review = await page.$(".a-size-base.s-underline-text");
for (let i = 0; i < Math.min(9, item.length); i++) {
const title = await (await item_title[i].getProperty('innerText')).jsonValue();
const img = await (await item_img[i].getAttribute('src'));
const price = await (await item_price[i].getProperty('innerText')).jsonValue();
const review = await (await item_review[i].getProperty('innerText')).jsonValue();
//scroll action
if (i % 4 === 5) {
await page.evaluate( () => {
window.scrollBy(0, window.innerHeight);
new Promise(function(resolve) {
setTimeout(resolve, 3000)
});
});
itemList.push(title, img, price, review)
console.log(itemList);
}
console.log(textOnTheDiv);
//console.log(imgAuteur);
};
})()
</code></pre>
<p>Do you think my problem comes from the increment, guys?
Thanks</p>
| [
{
"answer_id": 74427850,
"author": "CQLI",
"author_id": 1345734,
"author_profile": "https://Stackoverflow.com/users/1345734",
"pm_score": 2,
"selected": true,
"text": " @import url(https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css);\n .imgPlaceholder {\n position: relative;\n }\n .imgPlaceholder::before {\n content: \"\";\n position: absolute;\n width: 100%;\n height: 100%;\n background-image: url(https://images.pexels.com/photos/14297669/pexels-photo-14297669.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1);\n background-repeat: no-repeat;\n background-size: contain;\n background-position: center;\n }\n @media screen and (max-width: 991px){\n .wrapper {\n display: grid !important;\n grid-auto-rows: 1fr;\n }\n .imgPlaceholder::before {\n background-position: left;\n }\n }"
},
{
"answer_id": 74428919,
"author": "Sharif Mia",
"author_id": 8060704,
"author_profile": "https://Stackoverflow.com/users/8060704",
"pm_score": -1,
"selected": false,
"text": "<div class=\"container my-container pt-3\">\n <div class=\"row pt-5 pb-5\">\n <div class=\"col-12 col-lg-6 order-lg-last\">\n <div class=\"text-start\">\n <h1 class=\"mx-auto mb-2\">title...</h1>\n <p style=\"text-align: justify !important\">1.2. Your access to and use of the Service is conditioned on your acceptance of and compliance with these Terms. These Terms apply to all photographers, visitors, users and others who access and/or use the Service.\n 1.3. By accessing or using the Service, whether as a photographer, visitor or user of the Website, you agree to be bound by these Terms. These Terms serve to protect and safeguard your rights, the rights of other users, our rights and the rights of third parties in the course of operating the Website. If you do not agree to the terms of use, you must immediately stop using any part of the Service.\n 1.4. We reserve the right to change or adapt these Terms at any time and without giving reasons with effect for the future. You will be notified of these changes at least two weeks before they take effect by posting them on the Website and should you have created a user account on our Website by notifying your registered e-mail address. You have the right to immediately cancel and terminate your account on our Website if you do not agree to the changes to the Terms. Changes shall be deemed approved by you if you continue to use the Service after the new Terms come into effect.\n 1.5. The use of the Service is subject to the Terms in force at the time of use.\n 2. Accounts and Registration\n 2.1. You have the option of creating a user account on our Website so that you can use the additional functions of the Website, in particular for uploading photos and other Content or for participating in any contests made available through the Service. The opening of a user account can only take place with the agreement to these Terms.\n 2.2. Upon registration, Pexels and you enter into a contract for the use of the Website and the Services. There is no claim to the conclusion of this contract. Pexels is entitled to refuse your registration without giving reasons.\n 2.3. You may only register with Pexels if you are 18 years of age or if you act with the consent of your parents or guardian to register under these Terms. Pexels reserves the right to verify the consent of your parents or guardian. Therefore, you must provide an e-mail address of your parents or guardian when you register, so that we can obtain a declaration of consent from your parents or guardian.\n 2.4. When you create an account with us, you must provide us with the information and data requested by Pexels that is accurate, complete, and current at all times. If your data changes after registration, you are obliged to correct the information in your account immediately.\n 2.5. You may not use as a username the name of another person or entity or that is not lawfully available for use, a name or trademark that is subject to any rights of another person or entity other than you without authorization, or a name that is otherwise offensive, vulgar or obscene.\n 2.6. You are responsible for safeguarding the password that you use to access the Service and for any activities or actions under your password, whether your password is with our Service or a third-party service. If you are not responsible for the misuse of your member account, you are not liable. You agree not to disclose your password to any third party. You must notify us immediately at info@pexels.com upon becoming aware of any breach of security or unauthorized use of your account.</p>\n <p style=\"text-align: justify !important\">text...</p>\n </div>\n </div>\n <div class=\"col-12 col-lg-6\">\n <img class=\"img-fluid\" src=\"https://images.pexels.com/photos/8342074/pexels-photo-8342074.jpeg?auto=compress&cs=tinysrgb&w=600&lazy=load\" alt=\"Participation\" />\n </div>\n </div>\n</div>\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74425660",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19105052/"
] |
74,425,685 | <p>I'm currently displaying some bitmaps inside a <code>LazyVerticalGrid</code>. To avoid out of memory error, I'm trying to recycle bitmap doing the following:</p>
<pre><code>@Composable
fun ComicsList(covers: List<ComicCover>, onComicClicked: (ComicCover) -> Unit) {
LazyVerticalGrid(
columns = GridCells.Fixed(3),
contentPadding = PaddingValues(16.dp),
verticalArrangement = spacedBy(8.dp),
horizontalArrangement = spacedBy(8.dp)
) {
items(
items = covers,
key = { it.id }) {
ComicCoverView(it, onComicClicked)
}
}
}
@Composable
fun ComicCoverView(comic: ComicCover, onComicClicked: (ComicCover) -> Unit) {
Card {
DisposableEffect(
Image(
modifier = Modifier
.height(180.dp)
.clickable { onComicClicked(comic) },
bitmap = comic.cover.asImageBitmap(),
contentDescription = null,
contentScale = ContentScale.FillHeight,
)
) { onDispose { comic.cover.recycle() } }
}
}
</code></pre>
<p>But I got the following error:</p>
<blockquote>
<p>java.lang.RuntimeException: Canvas: trying to use a recycled bitmap
android.graphics.Bitmap@eb4ab61</p>
</blockquote>
<p>Any idea on how to properly clean up resources?</p>
| [
{
"answer_id": 74427850,
"author": "CQLI",
"author_id": 1345734,
"author_profile": "https://Stackoverflow.com/users/1345734",
"pm_score": 2,
"selected": true,
"text": " @import url(https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css);\n .imgPlaceholder {\n position: relative;\n }\n .imgPlaceholder::before {\n content: \"\";\n position: absolute;\n width: 100%;\n height: 100%;\n background-image: url(https://images.pexels.com/photos/14297669/pexels-photo-14297669.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1);\n background-repeat: no-repeat;\n background-size: contain;\n background-position: center;\n }\n @media screen and (max-width: 991px){\n .wrapper {\n display: grid !important;\n grid-auto-rows: 1fr;\n }\n .imgPlaceholder::before {\n background-position: left;\n }\n }"
},
{
"answer_id": 74428919,
"author": "Sharif Mia",
"author_id": 8060704,
"author_profile": "https://Stackoverflow.com/users/8060704",
"pm_score": -1,
"selected": false,
"text": "<div class=\"container my-container pt-3\">\n <div class=\"row pt-5 pb-5\">\n <div class=\"col-12 col-lg-6 order-lg-last\">\n <div class=\"text-start\">\n <h1 class=\"mx-auto mb-2\">title...</h1>\n <p style=\"text-align: justify !important\">1.2. Your access to and use of the Service is conditioned on your acceptance of and compliance with these Terms. These Terms apply to all photographers, visitors, users and others who access and/or use the Service.\n 1.3. By accessing or using the Service, whether as a photographer, visitor or user of the Website, you agree to be bound by these Terms. These Terms serve to protect and safeguard your rights, the rights of other users, our rights and the rights of third parties in the course of operating the Website. If you do not agree to the terms of use, you must immediately stop using any part of the Service.\n 1.4. We reserve the right to change or adapt these Terms at any time and without giving reasons with effect for the future. You will be notified of these changes at least two weeks before they take effect by posting them on the Website and should you have created a user account on our Website by notifying your registered e-mail address. You have the right to immediately cancel and terminate your account on our Website if you do not agree to the changes to the Terms. Changes shall be deemed approved by you if you continue to use the Service after the new Terms come into effect.\n 1.5. The use of the Service is subject to the Terms in force at the time of use.\n 2. Accounts and Registration\n 2.1. You have the option of creating a user account on our Website so that you can use the additional functions of the Website, in particular for uploading photos and other Content or for participating in any contests made available through the Service. The opening of a user account can only take place with the agreement to these Terms.\n 2.2. Upon registration, Pexels and you enter into a contract for the use of the Website and the Services. There is no claim to the conclusion of this contract. Pexels is entitled to refuse your registration without giving reasons.\n 2.3. You may only register with Pexels if you are 18 years of age or if you act with the consent of your parents or guardian to register under these Terms. Pexels reserves the right to verify the consent of your parents or guardian. Therefore, you must provide an e-mail address of your parents or guardian when you register, so that we can obtain a declaration of consent from your parents or guardian.\n 2.4. When you create an account with us, you must provide us with the information and data requested by Pexels that is accurate, complete, and current at all times. If your data changes after registration, you are obliged to correct the information in your account immediately.\n 2.5. You may not use as a username the name of another person or entity or that is not lawfully available for use, a name or trademark that is subject to any rights of another person or entity other than you without authorization, or a name that is otherwise offensive, vulgar or obscene.\n 2.6. You are responsible for safeguarding the password that you use to access the Service and for any activities or actions under your password, whether your password is with our Service or a third-party service. If you are not responsible for the misuse of your member account, you are not liable. You agree not to disclose your password to any third party. You must notify us immediately at info@pexels.com upon becoming aware of any breach of security or unauthorized use of your account.</p>\n <p style=\"text-align: justify !important\">text...</p>\n </div>\n </div>\n <div class=\"col-12 col-lg-6\">\n <img class=\"img-fluid\" src=\"https://images.pexels.com/photos/8342074/pexels-photo-8342074.jpeg?auto=compress&cs=tinysrgb&w=600&lazy=load\" alt=\"Participation\" />\n </div>\n </div>\n</div>\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74425685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1370087/"
] |
74,425,687 | <p>I want to return a message whenever there is a win or a draw in my tic-tac-toe game. As of right now, I got my "It's player ___'s turn" messages to show up. But my winning message doesn't show up no matter what, and my draw message appears automatically without me clicking anything(the board is empty)</p>
<p>This is what I have so far:
(Below is my HTML first, then JS following.)</p>
<pre><code><html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1" />
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>TIC-TAC-TOE</h1>
<h2 id="player1"> Player 1: </h2>
<h2 id="player2">Player 2: </h2>
<h2 id="result"></h2>
<table id="board">
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
<button>Restart</button>
</body>
<script src="app.js"></script>
</html>
```
let players = ['x', 'o']
let board = [
null, null, null,
null, null, null,
null, null, null
]
let boardWins = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6]
]
let result = document.getElementById('result')
let cells = document.querySelectorAll('td')
let currentPlayer = players[0]
cells.forEach(function(cell) {
cell.addEventListener('click', function() {
if (cell.innerHTML != '') {
return;
}
if (!cell) {
return;
}
if (currentPlayer === players[0]) { //idk why it's making me get the definition of the variable again?
currentPlayer = players[1]
cell.innerHTML = players[0]
result.innerHTML = "Player O's turn!"
} else if (currentPlayer === players[1]){
currentPlayer = players[0]
cell.innerHTML = players[1]
result.innerHTML = "Player X's turn!"
}
})
wins()
})
function wins() {
for (let i = 0; i < boardWins.length; i++) {
let win = boardWins[i]
let zero = win[0]
let one = win[1]
let two = win[2]
if (board[zero] === players[0] && board[zero] === board[one] && board[zero] === board[two]) {
result.innerHTML = 'Player X wins!' //I want this message to show up when there is 3 in a row for 'X'
}
else if (board[i] != null) {
result.innerHTML = 'Draw!'
} //I want this message to show up when the board fills up and neither player gets 3 in a row. But right now it pops up automatically before I click on any cell
}
}
}
```
I have tried if(board[zero] === board[one] && board[zero] === board[two]), if(board[zero] === board[one] && board[one] === board[two]), and if(board[zero] && board[zero] === board[one] && board[zero] === board[two]); the likes of those.
I have also tried to hard-code it in the addEventListener function, like if(board[0] === players[0] && board[1] === players[0] && board[2] === players[0]). I've also tried just writing 'x', which also hasn't worked.
I've also tried putting the wins function above the cells.forEach code and putting wins() at the bottom of the function of addEventListener.
</code></pre>
| [
{
"answer_id": 74427850,
"author": "CQLI",
"author_id": 1345734,
"author_profile": "https://Stackoverflow.com/users/1345734",
"pm_score": 2,
"selected": true,
"text": " @import url(https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css);\n .imgPlaceholder {\n position: relative;\n }\n .imgPlaceholder::before {\n content: \"\";\n position: absolute;\n width: 100%;\n height: 100%;\n background-image: url(https://images.pexels.com/photos/14297669/pexels-photo-14297669.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1);\n background-repeat: no-repeat;\n background-size: contain;\n background-position: center;\n }\n @media screen and (max-width: 991px){\n .wrapper {\n display: grid !important;\n grid-auto-rows: 1fr;\n }\n .imgPlaceholder::before {\n background-position: left;\n }\n }"
},
{
"answer_id": 74428919,
"author": "Sharif Mia",
"author_id": 8060704,
"author_profile": "https://Stackoverflow.com/users/8060704",
"pm_score": -1,
"selected": false,
"text": "<div class=\"container my-container pt-3\">\n <div class=\"row pt-5 pb-5\">\n <div class=\"col-12 col-lg-6 order-lg-last\">\n <div class=\"text-start\">\n <h1 class=\"mx-auto mb-2\">title...</h1>\n <p style=\"text-align: justify !important\">1.2. Your access to and use of the Service is conditioned on your acceptance of and compliance with these Terms. These Terms apply to all photographers, visitors, users and others who access and/or use the Service.\n 1.3. By accessing or using the Service, whether as a photographer, visitor or user of the Website, you agree to be bound by these Terms. These Terms serve to protect and safeguard your rights, the rights of other users, our rights and the rights of third parties in the course of operating the Website. If you do not agree to the terms of use, you must immediately stop using any part of the Service.\n 1.4. We reserve the right to change or adapt these Terms at any time and without giving reasons with effect for the future. You will be notified of these changes at least two weeks before they take effect by posting them on the Website and should you have created a user account on our Website by notifying your registered e-mail address. You have the right to immediately cancel and terminate your account on our Website if you do not agree to the changes to the Terms. Changes shall be deemed approved by you if you continue to use the Service after the new Terms come into effect.\n 1.5. The use of the Service is subject to the Terms in force at the time of use.\n 2. Accounts and Registration\n 2.1. You have the option of creating a user account on our Website so that you can use the additional functions of the Website, in particular for uploading photos and other Content or for participating in any contests made available through the Service. The opening of a user account can only take place with the agreement to these Terms.\n 2.2. Upon registration, Pexels and you enter into a contract for the use of the Website and the Services. There is no claim to the conclusion of this contract. Pexels is entitled to refuse your registration without giving reasons.\n 2.3. You may only register with Pexels if you are 18 years of age or if you act with the consent of your parents or guardian to register under these Terms. Pexels reserves the right to verify the consent of your parents or guardian. Therefore, you must provide an e-mail address of your parents or guardian when you register, so that we can obtain a declaration of consent from your parents or guardian.\n 2.4. When you create an account with us, you must provide us with the information and data requested by Pexels that is accurate, complete, and current at all times. If your data changes after registration, you are obliged to correct the information in your account immediately.\n 2.5. You may not use as a username the name of another person or entity or that is not lawfully available for use, a name or trademark that is subject to any rights of another person or entity other than you without authorization, or a name that is otherwise offensive, vulgar or obscene.\n 2.6. You are responsible for safeguarding the password that you use to access the Service and for any activities or actions under your password, whether your password is with our Service or a third-party service. If you are not responsible for the misuse of your member account, you are not liable. You agree not to disclose your password to any third party. You must notify us immediately at info@pexels.com upon becoming aware of any breach of security or unauthorized use of your account.</p>\n <p style=\"text-align: justify !important\">text...</p>\n </div>\n </div>\n <div class=\"col-12 col-lg-6\">\n <img class=\"img-fluid\" src=\"https://images.pexels.com/photos/8342074/pexels-photo-8342074.jpeg?auto=compress&cs=tinysrgb&w=600&lazy=load\" alt=\"Participation\" />\n </div>\n </div>\n</div>\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74425687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20492341/"
] |
74,425,690 | <p>Im trying to create a script that will run a function if a value is above 0 and refresh the page if its under 0 using html.
Im trying to run this script in chrome dev tools</p>
<p>here is my script so far. var is erroring.</p>
<pre class="lang-html prettyprint-override"><code>
function Above()
var text = document.querySelector("#belowcard > h3:nth-child(2)");
if (text == &#60) {
location.reload();
}
else{
PowerP();
}
}
</code></pre>
<pre><code></code></pre>
| [
{
"answer_id": 74427850,
"author": "CQLI",
"author_id": 1345734,
"author_profile": "https://Stackoverflow.com/users/1345734",
"pm_score": 2,
"selected": true,
"text": " @import url(https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css);\n .imgPlaceholder {\n position: relative;\n }\n .imgPlaceholder::before {\n content: \"\";\n position: absolute;\n width: 100%;\n height: 100%;\n background-image: url(https://images.pexels.com/photos/14297669/pexels-photo-14297669.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1);\n background-repeat: no-repeat;\n background-size: contain;\n background-position: center;\n }\n @media screen and (max-width: 991px){\n .wrapper {\n display: grid !important;\n grid-auto-rows: 1fr;\n }\n .imgPlaceholder::before {\n background-position: left;\n }\n }"
},
{
"answer_id": 74428919,
"author": "Sharif Mia",
"author_id": 8060704,
"author_profile": "https://Stackoverflow.com/users/8060704",
"pm_score": -1,
"selected": false,
"text": "<div class=\"container my-container pt-3\">\n <div class=\"row pt-5 pb-5\">\n <div class=\"col-12 col-lg-6 order-lg-last\">\n <div class=\"text-start\">\n <h1 class=\"mx-auto mb-2\">title...</h1>\n <p style=\"text-align: justify !important\">1.2. Your access to and use of the Service is conditioned on your acceptance of and compliance with these Terms. These Terms apply to all photographers, visitors, users and others who access and/or use the Service.\n 1.3. By accessing or using the Service, whether as a photographer, visitor or user of the Website, you agree to be bound by these Terms. These Terms serve to protect and safeguard your rights, the rights of other users, our rights and the rights of third parties in the course of operating the Website. If you do not agree to the terms of use, you must immediately stop using any part of the Service.\n 1.4. We reserve the right to change or adapt these Terms at any time and without giving reasons with effect for the future. You will be notified of these changes at least two weeks before they take effect by posting them on the Website and should you have created a user account on our Website by notifying your registered e-mail address. You have the right to immediately cancel and terminate your account on our Website if you do not agree to the changes to the Terms. Changes shall be deemed approved by you if you continue to use the Service after the new Terms come into effect.\n 1.5. The use of the Service is subject to the Terms in force at the time of use.\n 2. Accounts and Registration\n 2.1. You have the option of creating a user account on our Website so that you can use the additional functions of the Website, in particular for uploading photos and other Content or for participating in any contests made available through the Service. The opening of a user account can only take place with the agreement to these Terms.\n 2.2. Upon registration, Pexels and you enter into a contract for the use of the Website and the Services. There is no claim to the conclusion of this contract. Pexels is entitled to refuse your registration without giving reasons.\n 2.3. You may only register with Pexels if you are 18 years of age or if you act with the consent of your parents or guardian to register under these Terms. Pexels reserves the right to verify the consent of your parents or guardian. Therefore, you must provide an e-mail address of your parents or guardian when you register, so that we can obtain a declaration of consent from your parents or guardian.\n 2.4. When you create an account with us, you must provide us with the information and data requested by Pexels that is accurate, complete, and current at all times. If your data changes after registration, you are obliged to correct the information in your account immediately.\n 2.5. You may not use as a username the name of another person or entity or that is not lawfully available for use, a name or trademark that is subject to any rights of another person or entity other than you without authorization, or a name that is otherwise offensive, vulgar or obscene.\n 2.6. You are responsible for safeguarding the password that you use to access the Service and for any activities or actions under your password, whether your password is with our Service or a third-party service. If you are not responsible for the misuse of your member account, you are not liable. You agree not to disclose your password to any third party. You must notify us immediately at info@pexels.com upon becoming aware of any breach of security or unauthorized use of your account.</p>\n <p style=\"text-align: justify !important\">text...</p>\n </div>\n </div>\n <div class=\"col-12 col-lg-6\">\n <img class=\"img-fluid\" src=\"https://images.pexels.com/photos/8342074/pexels-photo-8342074.jpeg?auto=compress&cs=tinysrgb&w=600&lazy=load\" alt=\"Participation\" />\n </div>\n </div>\n</div>\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74425690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20496075/"
] |
74,425,710 | <p>I'm trying to understand if the way I'm writing my queries in postgres is not performant at scale (because of how I'm using Views to organize DRY code).</p>
<p>I think it boils down to whether filtering tables before joining them is equivalent to joining the tables, then filtering.</p>
<p>Here's an example: Can someone tell me if Option 1 and Option 2 are equally performant on very large tables?</p>
<p>Option 1</p>
<pre><code>with filteredTable1 as
(select *
from table1
where table1.id = 1),
filteredtTable2 as
(select *
from table2
where table2.id = 1)
select *
from filteredTable1
inner join filteredTable2 filteredTable1.id = filteredTable2.id
</code></pre>
<p>Option 2</p>
<pre><code>with joinedTables as
(select *
from table1
inner join table2 on table1.id = table2.id)
select *
from joinedTables
where id1 = 1
</code></pre>
<p>Thanks!</p>
| [
{
"answer_id": 74425983,
"author": "Bergi",
"author_id": 1048572,
"author_profile": "https://Stackoverflow.com/users/1048572",
"pm_score": 1,
"selected": true,
"text": "EXPLAIN"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74425710",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5286851/"
] |
74,425,734 | <p>I have a task that returns me a list of following dictionaries:</p>
<pre><code>[
{
"state": available
"id": "obj-1"
"tags": {
"Name": "pub-obj-1"
}
},
{
"state": available
"id": "obj-2"
"tags": {
"Name": "pub-obj-2"
}
},
{
"state": available
"id": "obj-3"
"tags": {
"Name": "pvt-obj-3"
}
}
]
</code></pre>
<p>I need to perform a lookup based on tags, with the prefix <code>pub</code> in the name and return the <code>id</code> fields of those objects in a new list. What is the correct way of doing this?</p>
| [
{
"answer_id": 74426037,
"author": "blhsing",
"author_id": 6890912,
"author_profile": "https://Stackoverflow.com/users/6890912",
"pm_score": 2,
"selected": true,
"text": "if"
},
{
"answer_id": 74426125,
"author": "Vladimir Botka",
"author_id": 6482561,
"author_profile": "https://Stackoverflow.com/users/6482561",
"pm_score": 2,
"selected": false,
"text": "tags"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74425734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5846366/"
] |
74,425,749 | <p>I have data with timestamps and duration of each operation. I want to convert the data into 1 minute time series and fill the rows based on the duration column and leave other rows NaN when it is not continuous.
Data:</p>
<pre><code>datetime action duration
2022-01-01 00:00 3 40
2022-01-01 00:40 1 10
2022-01-01 02:34 5 50
</code></pre>
<p>Desired outcome:</p>
<pre><code>datetime action duration
2022-01-01 00:00 3 40
2022-01-01 00:01 3 40
...
2022-01-01 00:39 3 40
2022-01-01 00:40 1 10
...
2022-01-01 00:49 1 10
2022-01-01 00:50 NaN NaN
2022-01-01 00:51 NaN NaN
...
2022-01-01 02:34 5 50
2022-01-01 02:35 5 50
</code></pre>
<p>I've tried: <code>df.resample("1min").fillna("pad")</code> but it fills the in-between times with the latest input. Action entries should be filled based on the duration, then leave NaN.</p>
<p>How can I achieve this?</p>
| [
{
"answer_id": 74426069,
"author": "gputrain",
"author_id": 20472812,
"author_profile": "https://Stackoverflow.com/users/20472812",
"pm_score": 2,
"selected": false,
"text": "df = df.asfreq('60S')\n"
},
{
"answer_id": 74426113,
"author": "ziying35",
"author_id": 16755671,
"author_profile": "https://Stackoverflow.com/users/16755671",
"pm_score": 2,
"selected": true,
"text": "tmp = df.copy()\ntmp['datetime'] = tmp.apply(lambda x: pd.date_range(\n x[0], periods=x[-1], freq='1min'), axis=1)\ntmp = tmp.explode('datetime').set_index('datetime')\ndf['datetime'] = pd.to_datetime(df['datetime'])\ndf = df.set_index('datetime')\ndf[:] = float('nan')\nres = df.resample(rule='1min').ffill().combine_first(tmp)\nprint(res)\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74425749",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20489776/"
] |
74,425,757 | <p>I am a student and I have a test coming up where I strongly believe that there is going to be at least one question about print loops. I understand the general idea behind them but I have a hard time finding the necessary patterns to solve the problem completely. For example:</p>
<p><a href="https://i.stack.imgur.com/2ipFc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2ipFc.png" alt="Sorry for bad screen shot not sure why that is happening" /></a></p>
<p>to solve this problem I have the following code:</p>
<pre><code> public static void drawTriangle(int width)
{
for (int r = 1; r <= (width + 1) / 2; r++)
{
for (int c = 1; c <= width; c++)
{
if (r == 1 || c == r)
{
System.out.println("*");
} else {
System.out.println("_");
}
}
System.out.println();
}
}
</code></pre>
<p>This is what I have so far which is almost correct but I am missing r+c == width + 1. I know that this is the code to form the side of the triangle going up. My problem is that I did not or rather could not recognize that I needed this part in the solution. Is there any tips that anybody has for identifying these patterns?</p>
| [
{
"answer_id": 74426069,
"author": "gputrain",
"author_id": 20472812,
"author_profile": "https://Stackoverflow.com/users/20472812",
"pm_score": 2,
"selected": false,
"text": "df = df.asfreq('60S')\n"
},
{
"answer_id": 74426113,
"author": "ziying35",
"author_id": 16755671,
"author_profile": "https://Stackoverflow.com/users/16755671",
"pm_score": 2,
"selected": true,
"text": "tmp = df.copy()\ntmp['datetime'] = tmp.apply(lambda x: pd.date_range(\n x[0], periods=x[-1], freq='1min'), axis=1)\ntmp = tmp.explode('datetime').set_index('datetime')\ndf['datetime'] = pd.to_datetime(df['datetime'])\ndf = df.set_index('datetime')\ndf[:] = float('nan')\nres = df.resample(rule='1min').ffill().combine_first(tmp)\nprint(res)\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74425757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20146539/"
] |
74,425,766 | <p>How can I update multiple XML elements within a single document?</p>
<p>For example, if I have the XML below and I want to change any elements with an attribute <code>Store_ID="13"</code> to instead have <code>Store_ID="99"</code>.</p>
<pre><code>declare @x xml
select @x = N'
<Games>
<Game>
<Place City="LAS" State="NV" />
<Place City="ATL" State="GA" />
<Store Store_ID="12" Price_ID="162" Description="Doom" />
<Store Store_ID="12" Price_ID="575" Description="Pac-man" />
<Store Store_ID="13" Price_ID="167" Description="Demons v3" />
<Store Store_ID="13" Price_ID="123" Description="Whatever" />
</Game>
</Games>
'
select @x
</code></pre>
<p>I can find all the elements with SQL like this:</p>
<pre><code>select t.c.query('.')
from @x.nodes('.//*[@Store_ID="13"]') as t(c)
</code></pre>
<p>To update only the first element I could do an update like this (or change '1' to '2' to update the 2nd element, etc):</p>
<pre><code>SET @x.modify('
replace value of (.//*[@Store_ID="13"]/@Store_ID)[1]
with "99"
');
SELECT @x;
</code></pre>
<p>The <a href="https://learn.microsoft.com/en-us/sql/t-sql/xml/replace-value-of-xml-dml?view=sql-server-ver16#arguments" rel="nofollow noreferrer">docs for <code>replace value of</code></a> say I can only update one node at a time:</p>
<blockquote>
<p>It must identify only a single node ... When multiple nodes are selected, an error is raised.</p>
</blockquote>
<p>So how do I update multiple elements? I can imagine querying first to find how many elements there are, then looping through and calling <code>@x.modify()</code> once for each element, passing an index parameter... but a) that feels wrong and b) when I try it I get an error</p>
<pre><code>-- Find how many elements there are with the attribute to update
declare @numberOfElements int
select @numberOfElements = count(*)
from (
select element = t.c.query('.')
from @x.nodes('.//*[@Store_ID="13"]') as t(c)
) x
declare @i int = 1
declare @query nvarchar(max)
-- loop through and update each one
while @i <= @numberOfElements begin
SET @x.modify('
replace value of (.//*[@Store_ID="13"]/@Store_ID)[sql:variable("@i")]
with "99"
');
set @i = @i + 1 ;
end
SELECT @x;
</code></pre>
<p>Running the sql above gives me the error:</p>
<pre><code>Msg 2337, Level 16, State 1, Line 31
XQuery [modify()]: The target of 'replace' must be at most one node, found 'attribute(Store_ID,xdt:untypedAtomic) *'
</code></pre>
<p>Furthermore, if I'm wanting to run this against many rows of a table with XML data stored in a column, it becomes very procedural.</p>
<p>Otherwise I could cast to <code>nvarchar(max)</code> and do string manipulation on it and then cast back to <code>xml</code>. Again, this feels icky, but also means I don't get the power of xml expressions to find the elements to update.</p>
| [
{
"answer_id": 74426419,
"author": "AlwaysLearning",
"author_id": 390122,
"author_profile": "https://Stackoverflow.com/users/390122",
"pm_score": 1,
"selected": false,
"text": "XML.modify()"
},
{
"answer_id": 74431846,
"author": "Rory",
"author_id": 8479,
"author_profile": "https://Stackoverflow.com/users/8479",
"pm_score": 0,
"selected": false,
"text": "modify()"
},
{
"answer_id": 74438014,
"author": "Yitzhak Khabinsky",
"author_id": 1932311,
"author_profile": "https://Stackoverflow.com/users/1932311",
"pm_score": 1,
"selected": false,
"text": "DECLARE @x XML =\nN'<Games>\n <Game>\n <Place City=\"LAS\" State=\"NV\"/>\n <Place City=\"ATL\" State=\"GA\"/>\n <Store Store_ID=\"12\" Price_ID=\"162\" Description=\"Doom\"/>\n <Store Store_ID=\"12\" Price_ID=\"575\" Description=\"Pac-man\"/>\n <Store Store_ID=\"13\" Price_ID=\"167\" Description=\"Demons v3\"/>\n <Store Store_ID=\"13\" Price_ID=\"123\" Description=\"Whatever\"/>\n </Game>\n</Games>';\n\nDECLARE @oldId int = 13\n , @newId int = 99;\n\nSET @x = @x.query('<Games><Game>\n {\n for $i in /Games/Game/*\n return if ($i[(local-name()=\"Store\") and @Store_ID=sql:variable(\"@oldId\")]) then\n element Store { attribute Store_ID {sql:variable(\"@newId\")}, $i/@*[not(local-name()=\"Store_ID\")]}\n else $i\n }\n</Game></Games>');\n\n-- test\nSELECT @x;\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74425766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8479/"
] |
74,425,774 | <p>Is it possible to prevent a function execution if an object is returned?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function number(a) {
console.log(a)
return {
add: b => console.log(a + b)
}
}
number(6).add(4)</code></pre>
</div>
</div>
</p>
<p>This will print <code>6</code> and then <code>10</code>. The behaviour I am looking for is to only print <code>10</code> when <code>.add()</code> is called but print <code>6</code> if <code>.add()</code> is not called. <code>.add()</code> should somehow stop <code>number()</code> execution after It has happened (what?). I have never seen such a thing in javascript, so I am almost sure It's not possible but maybe I am missing something?</p>
<h3>Edit</h3>
<p>As requested, I will include a more realistic example. Note: this is only a research for nice syntax, I know how to achieve the functionality with different syntax.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function update(obj, props) {
for (const p in props) {
obj[p] = props[p]
}
return {
if(condition) {
for (const p in condition) {
if (obj[p] === condition[p]) {
obj[p] = props[p]
}
}
}
}
}
const obj1 = {z: 0, h: 0}
const obj2 = {a: 0, b: 'hi'}
update(obj1, {z: 10, h: 10}) // Will update the object regardless.
update(obj2, {a: 100, b: 'hello'}).if({a: 'x', b: 'y'}) // This would not update the object, because the condition is not met. (But it does)
console.log(obj1)
console.log(obj2)</code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74425844,
"author": "Brad",
"author_id": 362536,
"author_profile": "https://Stackoverflow.com/users/362536",
"pm_score": 0,
"selected": false,
"text": "console.log()"
},
{
"answer_id": 74425956,
"author": "Bergi",
"author_id": 1048572,
"author_profile": "https://Stackoverflow.com/users/1048572",
"pm_score": 3,
"selected": true,
"text": "if"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74425774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17607331/"
] |
74,425,822 | <p>Im using PySimpleGui to make a simple file format conversion program, but the little window of my program keeps telling me (not responding) like if it was crushing while in reality it's working and its writing the new file.</p>
<p>The issue is the cycle, if i remove it everything works but the user doesnt have any response on the progression of the conversion. I reed some documentation on python threading and i think that everything should work, any tips?
here's the code:
`</p>
<pre><code>def main():
sg.theme('DarkGrey3')
layout1 = [[sg.Text('File converter (.csv to sdf)')],
[sg.Frame('Input Filename',
[[sg.Input(key='-IN-'), sg.FileBrowse(), ],])],
[sg.Frame('Output Path',
[[sg.Input(key='-OUT-'), sg.FolderBrowse(), ],])],
[sg.Button('Convert'), sg.Button('Exit')], [sg.Text('', key='-c-')]]
window=sg.Window(title='.csv to .sdf file converter', layout=layout1, margins=(50, 25))
window.read()
while True:
event, values = window.read()
if event=='Exit' or event==None:
break
if event=='Convert':
csvfilepath=values['-IN-']
outpath=values['-OUT-']
x=threading.Thread(target=Converter, args=[csvfilepath, outpath])
x.start()
time.sleep(1)
while x.is_alive():
window['-c-'].Update('Conversion')
time.sleep(1)
window['-c-'].Update('Conversion.')
time.sleep(1)
window['-c-'].Update('Conversion..')
time.sleep(1)
window['-c-'].Update('Conversion...')
time.sleep(1)
</code></pre>
<p>`</p>
| [
{
"answer_id": 74425844,
"author": "Brad",
"author_id": 362536,
"author_profile": "https://Stackoverflow.com/users/362536",
"pm_score": 0,
"selected": false,
"text": "console.log()"
},
{
"answer_id": 74425956,
"author": "Bergi",
"author_id": 1048572,
"author_profile": "https://Stackoverflow.com/users/1048572",
"pm_score": 3,
"selected": true,
"text": "if"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74425822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20496158/"
] |
74,425,832 | <p>Is there anyone here who thinks they can help me solve an estimate calculator issue?</p>
<p>The user clicks on different checkboxes which stores a price value and for each checkbox they click it adds a total price. I got that working. But I cant find a way to give the checkbox a range price to display to the user</p>
<p><a href="https://i.stack.imgur.com/CDDB5.png" rel="nofollow noreferrer">like this</a></p>
<p>This is mine, i put in plane text the range, but the value is actually only the first portion of the range unfortunately and I'm not getting to display the range
<a href="https://i.stack.imgur.com/qGMzd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qGMzd.png" alt="enter image description here" /></a></p>
<p>This is what is the code i tried:
`</p>
<pre><code> <p class = "dropdown-details">Includes cost of parts and services for the <u>Engine</u></p>
<div id = "test"></div>
</div>
<br>
<!--Services with prices-->
<form action="" method="post" id= "engineRepair-form" class="price-form">
<table>
<tr>
<td class="services-row">
<input type="checkbox" name="array[]" id="oil" value="2126.15">
<label for="oil">Air Filter</label>
</td>
<td class = "price">
$2,126.15 - $2,622.25
</td>
</tr>
<tr>
<td class="service">
<input type="checkbox" name="array[]" id="gas" value="1063.08">
<label for="gas">Gas Filter</label>
</td>
<td class = "price">
$1,063.08 - $1,275.69
</td>
</tr>
<tr>
<td class="service">
<input type="checkbox" name="array[]" id="tires" value = "3614.46">
<label for="tires">Fuel Filter</label>
</td>
<td class = "price">
$3,614.46 - $4,394.05
</td>
</tr>
<tr>
<td class="service">
<input type="checkbox" name="array[]" id="sparkPlug" value = "5244.51">
<label for="sparkPlug">Spark Plug</label>
</td>
<td class = "price">
$5,244.51 - $6,449.33
</td>
</tr>
<tr>
<td class="service">
<input type="checkbox" name="array[]" id="belt_chain" value = "9355.07">
<label for="belt_chain">Timing Belt/Chain</label>
</td>
<td class = "price">
$9,355.07 - $1,1410.35
</td>
</tr>
<tr>
<td class="service">
<input type="checkbox" name="array[]" id="belt_drive" value = "3685.33">
<label for="belt_drive">Fan Belt/Drive Belt</label>
</td>
<td class = "price">
$3,685.33 - $4,323.18
</td>
</tr>
<tr>
<td class="service">
<input type="checkbox" name="array[]" id="radiatorHoseSet" value = "7228.92">
<label for="radiatorHoseSet">Radiator Hose Set</label>
</td>
<td class = "price">
$7,228.92 - $8,858.97
</td>
</tr>
<tr>
<td class="service">
<input type="checkbox" name="array[]" id="radiator" value = "27214.74">
<label for="radiator">Radiator</label>
</td>
<td class = "price">
$27,214.74 - $33,309.71
</td>
</tr>
</table>
</form>
</code></pre>
<p>`</p>
<p>Javascrip:
`</p>
<pre><code>$(function() {
$('input').click(function() {
var total = 0;
$('input:checked').each(function(index, item) {
total += parseFloat(item.value);
});
$('#test').text(total.toFixed(2));
});
});
</code></pre>
<p>`</p>
<p>As you can see, the prices did add but it didn't display the range as showed in the first image I sent. It's supposed to display the total estimated price range</p>
<p><a href="https://codepen.io/360hazzy/pen/JjZJKNR?editors=1011" rel="nofollow noreferrer">enter link description here</a></p>
<p>this is also the codepen</p>
| [
{
"answer_id": 74425906,
"author": "ryuhojin",
"author_id": 20496118,
"author_profile": "https://Stackoverflow.com/users/20496118",
"pm_score": 2,
"selected": false,
"text": "$(function() {\n $('input').click(function() {\n var total1 = 0;\n var total2 = 0;\n $('input:checked').each(function(index, item) {\n var items = item.parentElement.nextElementSibling.innerText.replace(/[$, ]/g,'').split(\"-\");\n total1 += Number(items[0]);\n total2 += Number(items[1]);\n });\n $('#costOutput').text('$'+total1.toFixed(2)+' - '+ '$'+total2.toFixed(2));\n });\n});\n"
},
{
"answer_id": 74425931,
"author": "Jon P",
"author_id": 4665,
"author_profile": "https://Stackoverflow.com/users/4665",
"pm_score": 2,
"selected": true,
"text": "table"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74425832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14627041/"
] |
74,425,834 | <p>I have this function:</p>
<pre><code>class myClass: ObservableObject {
func doSomethingElse<T:Decodable>(url: URL,
config: URLSessionConfiguration,
type: T.Type) -> AnyPublisher<Int, any Error> {
return URLSession(configuration:config).dataTaskPublisher(for: url)
.tryMap{ response in
guard let valueResponse = response.response as? HTTPURLResponse else {
return 000
}
return valueResponse.statusCode
}.mapError{error in
return error
}
.eraseToAnyPublisher()
}
}
</code></pre>
<p>and it works just fine but I'm trying to add this function to <code>URLSession</code> extension:</p>
<pre><code>extension URLSession {
func doSomethingElse<T:Decodable>(url: URL,
config: URLSessionConfiguration,
type: T.Type) -> AnyPublisher<Int, any Error> {
return self(configuration:config).dataTaskPublisher(for: url)
.tryMap{ response in
guard let valueResponse = response.response as? HTTPURLResponse else {
return 000
}
return valueResponse.statusCode
}.mapError{error in
return error
}
.eraseToAnyPublisher()
}
</code></pre>
<p>But I'm getting this error:</p>
<p><a href="https://i.stack.imgur.com/n636R.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/n636R.png" alt="enter image description here" /></a></p>
<pre><code>Cannot call value of non-function type 'URLSession'
</code></pre>
<p>Any of you knows why I'm getting this error? or how can configure URLSession to have the configuration?</p>
<p>I'll really appreciate your help</p>
| [
{
"answer_id": 74425906,
"author": "ryuhojin",
"author_id": 20496118,
"author_profile": "https://Stackoverflow.com/users/20496118",
"pm_score": 2,
"selected": false,
"text": "$(function() {\n $('input').click(function() {\n var total1 = 0;\n var total2 = 0;\n $('input:checked').each(function(index, item) {\n var items = item.parentElement.nextElementSibling.innerText.replace(/[$, ]/g,'').split(\"-\");\n total1 += Number(items[0]);\n total2 += Number(items[1]);\n });\n $('#costOutput').text('$'+total1.toFixed(2)+' - '+ '$'+total2.toFixed(2));\n });\n});\n"
},
{
"answer_id": 74425931,
"author": "Jon P",
"author_id": 4665,
"author_profile": "https://Stackoverflow.com/users/4665",
"pm_score": 2,
"selected": true,
"text": "table"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74425834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2924482/"
] |
74,425,847 | <p>So pretty much i'm coding a webpage for A class and I cannot figure out how to make space so that the body expands on its own to the end of the page, so that I don't have all this extra space, I'll drop the html code and the css below so that you get what I'm talking about. Any help would be much appreciated.</p>
<p>I've tried margining and a lot of other stuff in the book and I cannot figure it out.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
background-color: #faf86f;
font-family: 'Times New Roman', Times, serif;
}
header {
text-align: center;
font-style: oblique;
font-size: 2.0em;
color:rgb(47, 79, 219);
background-image: url(bistro_logo.png);
background-size: 10%;
background-repeat: no-repeat round;
text-shadow: 2px 3px rgb(81, 177, 241);
}
#wrapper {
width: 100%;
margin:auto;
border: 4px solid blue;
}
img { float:left;
}
nav {
flex:1;
border: 4px solid rgb(47, 79, 219);
}
nav ul{ list-style-type: none;
text-align: center;
font-size: 1.5em;
}
nav li {
display: flex;
flex-wrap: wrap;
flex-flow: row wrap;
justify-content: space-around;
}
nav a {
text-decoration: none;
padding-right: 10px;
}
nav a:link { color:blue}
nav a:visited { color:rgb(96, 10, 175)}
nav a:hover { color:aqua}
main {
flex: 7;
margin: auto;
}
p {
text-align: center;
color:blueviolet;
font-size: 1.1em;
font-family:'Times New Roman', Times, serif;
float: center;
text-align-last: auto;
}
h2 {
text-align: center;
color:blue;
font-size: 1.6em;
font-style:oblique;
}
footer {
border-top: 3px solid blue;
text-align: center;
}
.float {
float: left;
}
@media(min-width: 800px) {
#wrapper { width: 80%;
margin:auto;
}
nav li {
display: inline;
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><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>Bistro Cafe - Home</title>
<link href="bistro.css" rel="stylesheet">
</head>
<body>
<div id="wrapper">
<header>
<h1>The Bistro Cafe</h1>
</header>
<nav>
<ul>
<li><a href="bistro_home.html">Home</a></li>
<li><a href="bistro_history.html">Bistro Cafe's History</a></li>
<li><a href="bistro_specials.html">Bistro Specials</a></li>
<li><a href="bistro_contact.html">Contact Bistro Cafe</a></li>
</ul>
</nav>
<main>
<h2>Home</h2>
<p>The Bistro Cafe is located in the heart of Techieville! We specialize in good-ole home cooking. Our menu ranges from chicken dumplings to our famous fiesta burrito. Our breakfast menu is available all day. Please come by and share a meal with us. We are conveniently located on the corner of 5th and Hypertext Avenue.
</p>
</main>
<footer>
<a href="bistro_home.html">Home</a>
<a href="bistro_history.html">Bistro Cafe's History</a>
<a href="bistro_specials.html">Bistro Specials</a>
<a href="bistro_contact.html">Contact Bistro Cafe</a>
&copy; copyright 2022 <a href="mailto:jmmartin@mail.mccneb.edu">Josh Martin</a>
</footer>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74425906,
"author": "ryuhojin",
"author_id": 20496118,
"author_profile": "https://Stackoverflow.com/users/20496118",
"pm_score": 2,
"selected": false,
"text": "$(function() {\n $('input').click(function() {\n var total1 = 0;\n var total2 = 0;\n $('input:checked').each(function(index, item) {\n var items = item.parentElement.nextElementSibling.innerText.replace(/[$, ]/g,'').split(\"-\");\n total1 += Number(items[0]);\n total2 += Number(items[1]);\n });\n $('#costOutput').text('$'+total1.toFixed(2)+' - '+ '$'+total2.toFixed(2));\n });\n});\n"
},
{
"answer_id": 74425931,
"author": "Jon P",
"author_id": 4665,
"author_profile": "https://Stackoverflow.com/users/4665",
"pm_score": 2,
"selected": true,
"text": "table"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74425847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20028219/"
] |
74,425,885 | <p>Is there any way to access <code>ApplicationRecord</code> and its <code>models</code> inside an initialization script? Like:</p>
<pre class="lang-rb prettyprint-override"><code># config/initializers/start.rb
include ApplicationRecord
User.all.each do |user|
# do stuff with users
end
</code></pre>
| [
{
"answer_id": 74425906,
"author": "ryuhojin",
"author_id": 20496118,
"author_profile": "https://Stackoverflow.com/users/20496118",
"pm_score": 2,
"selected": false,
"text": "$(function() {\n $('input').click(function() {\n var total1 = 0;\n var total2 = 0;\n $('input:checked').each(function(index, item) {\n var items = item.parentElement.nextElementSibling.innerText.replace(/[$, ]/g,'').split(\"-\");\n total1 += Number(items[0]);\n total2 += Number(items[1]);\n });\n $('#costOutput').text('$'+total1.toFixed(2)+' - '+ '$'+total2.toFixed(2));\n });\n});\n"
},
{
"answer_id": 74425931,
"author": "Jon P",
"author_id": 4665,
"author_profile": "https://Stackoverflow.com/users/4665",
"pm_score": 2,
"selected": true,
"text": "table"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74425885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11107859/"
] |
74,425,894 | <p>I am building a straight-forward Flask API. After each decorator for the API endpoint, I have to define a function that simply calls another function I have in a separate file. This works fine, but seems redundant. I would rather just call that pre-defined function directly, instead of having to wrap it within another function right after the decorator. Is this possible?</p>
<p>What I have currently:</p>
<pre><code>import routes.Locations as Locations
# POST: /api/v1/locations
@app.route('/locations', methods=['GET'])
def LocationsRead ():
return Locations.read()
</code></pre>
<p>Locations.read() function looks like this:</p>
<pre><code>def read():
return {
'id': 1,
'name': 'READ'
}
</code></pre>
<p>What I am hoping to do:</p>
<pre><code>import routes.Locations as Locations
# POST: /api/v1/locations
@app.route('/locations', methods=['GET'])
Locations.read()
</code></pre>
| [
{
"answer_id": 74425971,
"author": "Dunes",
"author_id": 529630,
"author_profile": "https://Stackoverflow.com/users/529630",
"pm_score": 1,
"selected": false,
"text": "@"
},
{
"answer_id": 74426099,
"author": "Austin Wilcox",
"author_id": 4249346,
"author_profile": "https://Stackoverflow.com/users/4249346",
"pm_score": 1,
"selected": true,
"text": "# GET: /api/v1/locations\napp.route(basepath + '/locations', methods=['GET'])(Locations.read)\n# GET: /api/v1/locations/{id}\napp.route(basepath + '/locations/<int:id>', methods=['GET'])(Locations.read)\n# POST: /api/v1/locations\napp.route(basepath + '/locations', methods=['POST'])(Locations.create)\n# PUT: /api/v1/locations/{id}\napp.route(basepath + '/locations/<int:id>', methods=['PUT'])(Locations.update)\n# DELETE: /api/v1/locations/{id}\napp.route(basepath + '/locations/<int:id>', methods=['DELETE'])(Locations.delete)\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74425894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4249346/"
] |
74,425,896 | <p>In forms, I am trying to filter marketplace drop down field that belong to the logged in user based on its group. Its listing all the dropdown field items. I tried below but I think something is wrong with the filter part.</p>
<blockquote>
<pre><code> class InfringementForm(ModelForm):
def __init__(self, user, *args, **kwargs):
super(InfringementForm,self).__init__(*args, **kwargs)
self.fields['marketplace'].queryset =
Marketplace.objects.filter(groups__user=self.user)
class Meta:
model = Infringement
</code></pre>
</blockquote>
<blockquote>
<pre><code>class Meta:
ordering = ['-updated', '-created']
def __str__(self):
return self.name
</code></pre>
<blockquote>
<pre><code> fields = ['name', 'link', 'infringer', 'player', 'remove', 'status',
'screenshot','marketplace']
</code></pre>
</blockquote>
</blockquote>
<p>models.py</p>
<blockquote>
<pre><code>class Marketplace (models.Model):
name = models.CharField(max_length=100)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
groups = models.ForeignKey(Group, on_delete=models.CASCADE,default=1)
</code></pre>
</blockquote>
| [
{
"answer_id": 74426021,
"author": "Sunderam Dubey",
"author_id": 17562044,
"author_profile": "https://Stackoverflow.com/users/17562044",
"pm_score": 1,
"selected": false,
"text": "__init__()"
},
{
"answer_id": 74426622,
"author": "Farid",
"author_id": 20453400,
"author_profile": "https://Stackoverflow.com/users/20453400",
"pm_score": 1,
"selected": true,
"text": " class InfringementForm(ModelForm):\n def __init__(self, user, *args, **kwargs):\n self.user = user \n super(InfringementForm,self).__init__(*args, **kwargs)\n self.fields['marketplace'].queryset = \n Marketplace.objects.filter(groups__user=self.user)\n class Meta:\n model = Infringement\n \n fields = ['name', 'link', 'infringer', 'player', 'remove', 'status', \n 'screenshot', 'marketplace']\n"
},
{
"answer_id": 74430584,
"author": "Mahammadhusain kadiwala",
"author_id": 19205926,
"author_profile": "https://Stackoverflow.com/users/19205926",
"pm_score": 0,
"selected": false,
"text": "groups"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74425896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20453400/"
] |
74,425,899 | <p>I would like to take create a code that takes an input of numbers, and then takes the average (mean) of these numbers. So far, I have this:</p>
<pre><code>from statistics import mean
numbers=int(input("Enter some numbers. Seperate each number by a space: ")
average=mean(grades)
print(average)
</code></pre>
<p>Running this code gives me an error stating "invalid literal for int() with base 10: ' 12 13 14 15 16 17 17'". I have tried to convert the input into a list, but this also failed; I don't know what else to do or try.</p>
| [
{
"answer_id": 74425930,
"author": "NOP da CALL",
"author_id": 5352244,
"author_profile": "https://Stackoverflow.com/users/5352244",
"pm_score": 1,
"selected": false,
"text": "from statistics import mean\n\nuser_input = input(\"Enter some numbers. Seperate each number by a space: \").strip()\n\nnumbers = [int(x) for x in user_input.split(' ')]\n\naverage = mean(numbers)\n\nprint(average)\n"
},
{
"answer_id": 74425933,
"author": "Romalex",
"author_id": 11208064,
"author_profile": "https://Stackoverflow.com/users/11208064",
"pm_score": 0,
"selected": false,
"text": "numbers = list(map(int, input().split(\" \")))\naverage = mean(grades)\nprint(average)\n"
},
{
"answer_id": 74425936,
"author": "Andres Ospina",
"author_id": 11920063,
"author_profile": "https://Stackoverflow.com/users/11920063",
"pm_score": 1,
"selected": true,
"text": "numbers=[int(x) for x in input(\"Enter some numbers. Seperate each \nnumber by a space: \").split()]\nprint(numbers)\naverage=mean(numbers)\nprint(average)\n"
},
{
"answer_id": 74425942,
"author": "Sai",
"author_id": 11030653,
"author_profile": "https://Stackoverflow.com/users/11030653",
"pm_score": 0,
"selected": false,
"text": "from statistics import mean\n\nnumbers = input(\"Enter some numbers. Separate each number by a space: \")\n\n# After the input numbers is a string that looks like this \"1 2 3 4\"\n\n# .split(\" \") splits the string based on the space. It returns a list of individual items\n# strip removes the trailing and leading white spaces\n# map applies the first arg (here int) on each element of the second arg (here a list of numbers as strings)\nnumbers = list(map(int, numbers.strip().split(\" \")))\n\naverage = mean(numbers)\nprint(average)\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74425899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20113832/"
] |
74,425,914 | <p>I am trying to convert a D3 force-directed graph codebase.
Source code:
<a href="https://codesandbox.io/s/d3js-draggable-force-directed-graph-py3rf" rel="nofollow noreferrer">https://codesandbox.io/s/d3js-draggable-force-directed-graph-py3rf</a></p>
<pre><code>var nodes = [
{ color: "red", size: 5 },
{ color: "orange", size: 10 },
{ color: "yellow", size: 15 },
{ color: "green", size: 20 },
{ color: "blue", size: 25 },
{ color: "purple", size: 30 }
];
var links = [
{ source: "red", target: "orange" },
{ source: "orange", target: "yellow" },
{ source: "yellow", target: "green" },
{ source: "green", target: "blue" },
{ source: "blue", target: "purple" },
{ source: "purple", target: "red" },
{ source: "green", target: "red" }
];
var svg = d3
.select("svg")
.attr("width", width)
.attr("height", height);
var linkSelection = svg
.selectAll("line")
.data(links)
.enter()
.append("line")
.attr("stroke", "black")
.attr("stroke-width", 1);
var nodeSelection = svg
.selectAll("circle")
.data(nodes)
.enter()
.append("circle")
.attr("r", d => d.size)
.attr("fill", d => d.color)
.call(
d3
.drag()
.on("start", dragStart)
.on("drag", drag)
.on("end", dragEnd)
);
</code></pre>
<p>the current product looks like this:</p>
<p><a href="https://i.stack.imgur.com/ZTs2P.png?s=256" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZTs2P.png?s=256" alt="enter image description here" /></a></p>
<p>And the snippet is here:</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>/* eslint-disable no-undef */
var width = 600;
var height = 600;
var nodes = [
{ color: "red", size: 5 },
{ color: "orange", size: 10 },
{ color: "yellow", size: 15 },
{ color: "green", size: 20 },
{ color: "blue", size: 25 },
{ color: "purple", size: 30 }
];
var links = [
{ source: "red", target: "orange" },
{ source: "orange", target: "yellow" },
{ source: "yellow", target: "green" },
{ source: "green", target: "blue" },
{ source: "blue", target: "purple" },
{ source: "purple", target: "red" },
{ source: "green", target: "red" }
];
var svg = d3
.select("svg")
.attr("width", width)
.attr("height", height);
var linkSelection = svg
.selectAll("line")
.data(links)
.enter()
.append("line")
.attr("stroke", "black")
.attr("stroke-width", 1);
var nodeSelection = svg
.selectAll("circle")
.data(nodes)
.enter()
.append("circle")
.attr("r", d => d.size)
.attr("fill", d => d.color)
.call(
d3
.drag()
.on("start", dragStart)
.on("drag", drag)
.on("end", dragEnd)
);
var simulation = d3.forceSimulation(nodes);
simulation
.force("center", d3.forceCenter(width / 2, height / 2))
.force("nodes", d3.forceManyBody())
.force(
"links",
d3
.forceLink(links)
.id(d => d.color)
.distance(d => 5 * (d.source.size + d.target.size))
)
.on("tick", ticked);
function ticked() {
// console.log(simulation.alpha());
nodeSelection.attr("cx", d => d.x).attr("cy", d => d.y);
linkSelection
.attr("x1", d => d.source.x)
.attr("y1", d => d.source.y)
.attr("x2", d => d.target.x)
.attr("y2", d => d.target.y);
}
function dragStart(d) {
// console.log('drag start');
simulation.alphaTarget(0.5).restart();
d.fx = d.x;
d.fy = d.y;
}
function drag(d) {
// console.log('dragging');
// simulation.alpha(0.5).restart()
d.fx = d3.event.x;
d.fy = d3.event.y;
}
function dragEnd(d) {
// console.log('drag end');
simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script>
<svg
version="1.1"
baseProfile="full"
xmlns="http://www.w3.org/2000/svg"
></svg></code></pre>
</div>
</div>
</p>
<p>But my goal is draw lines with arrows on the end, where the arrows are pointing to a target from a source. Does anyone know how to properly change the line type, and have it point the right way?</p>
| [
{
"answer_id": 74425930,
"author": "NOP da CALL",
"author_id": 5352244,
"author_profile": "https://Stackoverflow.com/users/5352244",
"pm_score": 1,
"selected": false,
"text": "from statistics import mean\n\nuser_input = input(\"Enter some numbers. Seperate each number by a space: \").strip()\n\nnumbers = [int(x) for x in user_input.split(' ')]\n\naverage = mean(numbers)\n\nprint(average)\n"
},
{
"answer_id": 74425933,
"author": "Romalex",
"author_id": 11208064,
"author_profile": "https://Stackoverflow.com/users/11208064",
"pm_score": 0,
"selected": false,
"text": "numbers = list(map(int, input().split(\" \")))\naverage = mean(grades)\nprint(average)\n"
},
{
"answer_id": 74425936,
"author": "Andres Ospina",
"author_id": 11920063,
"author_profile": "https://Stackoverflow.com/users/11920063",
"pm_score": 1,
"selected": true,
"text": "numbers=[int(x) for x in input(\"Enter some numbers. Seperate each \nnumber by a space: \").split()]\nprint(numbers)\naverage=mean(numbers)\nprint(average)\n"
},
{
"answer_id": 74425942,
"author": "Sai",
"author_id": 11030653,
"author_profile": "https://Stackoverflow.com/users/11030653",
"pm_score": 0,
"selected": false,
"text": "from statistics import mean\n\nnumbers = input(\"Enter some numbers. Separate each number by a space: \")\n\n# After the input numbers is a string that looks like this \"1 2 3 4\"\n\n# .split(\" \") splits the string based on the space. It returns a list of individual items\n# strip removes the trailing and leading white spaces\n# map applies the first arg (here int) on each element of the second arg (here a list of numbers as strings)\nnumbers = list(map(int, numbers.strip().split(\" \")))\n\naverage = mean(numbers)\nprint(average)\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74425914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1223975/"
] |
74,425,959 | <p>As simple as it sounds. I'm a newb when it comes to c++, but I have been following cpp reference and some online tutorials to write code. My code should output a string as "SuCh", but instead it outputs something as "SSuuCChh". Is there a practical error I'm missing?</p>
<pre><code>#include <cctype>
#include <iostream>
using namespace std;
int main()
{
string mani;
int L = 0;
getline(cin, mani);
for (int i = 0; i<mani.length();i++){
if(mani.at(i) == ' '){
cout << ' ' << flush;
L = L - 2;
} else if(L%2==0){
putchar(toupper(mani.at(i)));
L++;
} else if(L%1==0) {
putchar(tolower(mani.at(i)));
L++;
}
}
return 0;
}
</code></pre>
| [
{
"answer_id": 74425974,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 3,
"selected": true,
"text": "putchar"
},
{
"answer_id": 74426042,
"author": "Khrisys",
"author_id": 17895879,
"author_profile": "https://Stackoverflow.com/users/17895879",
"pm_score": 0,
"selected": false,
"text": "#include <cctype>\n#include <cstdio>\n#include <iostream>\n#include <string>\n\nint main(void) {\n std::string mani, F;\n getline(std::cin, mani);\n\n for(int i = 0; i < mani.length; i++) {\n if(i % 2 == 0) { \n std::cout << std::toupper(mani.at(i));\n } else {\n std::cout << std::tolower(mani.at(i));\n }\n }\n\n std::cout << std::endl;\n return 0;\n}\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74425959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20496290/"
] |
74,425,998 | <p>I'm trying to do the following: "# drop all rows where tag == train_loop and start is NaN".</p>
<p>Here's my current attempt (thanks Copilot):</p>
<pre><code># drop all rows where tag == train_loop and start is NaN
# apply filter function to each row
# return True if row should be dropped
def filter_fn(row):
return row["tag"] == "train_loop" and pd.isna(row["start"]):
old_len = len(df)
df = df[~df.apply(filter_fn, axis=1)]
</code></pre>
<p>It works well, but I'm wondering if there is a less verbose way.</p>
| [
{
"answer_id": 74426013,
"author": "Michael Delgado",
"author_id": 3888719,
"author_profile": "https://Stackoverflow.com/users/3888719",
"pm_score": 3,
"selected": true,
"text": "apply"
},
{
"answer_id": 74426014,
"author": "BENY",
"author_id": 7964527,
"author_profile": "https://Stackoverflow.com/users/7964527",
"pm_score": 1,
"selected": false,
"text": "df = df.loc[~(df['tag'].eq('train_loop') & df['start'].isna())]\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74425998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3847117/"
] |
74,426,007 | <p>I'm writing a function that will subset a dataframe based on different conditions. I need to return the dataframe with maximum row count.</p>
<pre><code>df2 <- as.data.frame(matrix(runif(n=10, min=1, max=20), nrow=200))
df3 <- as.data.frame(matrix(runif(n=10, min=1, max=20), nrow=90))
df4 <- as.data.frame(matrix(runif(n=10, min=1, max=20), nrow=600))
df5 <- as.data.frame(matrix(runif(n=10, min=1, max=20), nrow=70))
max_row_df = ifelse(nrow(df) > nrow(df2) & nrow(df) > nrow(df5), deparse(substitute(df)),
ifelse(nrow(df2) > nrow(df3), deparse(substitute(df2)),
ifelse(nrow(df3) > nrow(df4), deparse(substitute(df3)),
ifelse(nrow(df4) > nrow(df5),deparse(substitute(df4)),
deparse(substitute(df5))))))
max_row_df
</code></pre>
<blockquote>
<p>This statement has flaw in logic but is only method to return the name
of the dataframe, which is what I need in order to return the selected
dataframe from the function.</p>
</blockquote>
<pre><code>row_lengths <- c(nrow(df), nrow(df2), nrow(df3), nrow(df4), nrow(df5))
max_row <- max(row_lengths)
</code></pre>
<p>Can't deparse the df names in the method above. Is there a better approach as if and for only returning boolean values.</p>
<p>Any insight appreciated.</p>
| [
{
"answer_id": 74426324,
"author": "Santiago",
"author_id": 13507658,
"author_profile": "https://Stackoverflow.com/users/13507658",
"pm_score": 1,
"selected": false,
"text": "purrr::reduce"
},
{
"answer_id": 74429615,
"author": "Magnetar",
"author_id": 14730773,
"author_profile": "https://Stackoverflow.com/users/14730773",
"pm_score": 0,
"selected": false,
"text": "# create a list of objects collected based on specified name\n df_list = mget(paste0(\"df\", c(\"\", as.character(2:5))))\n \n # find the object in the list with max rows and return\n i_most = which.max(sapply(df_list, nrow))\n \n return(df_list[[i_most]])\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14730773/"
] |
74,426,012 | <p>I would like to search in a set of sets in a specific way:</p>
<p>Example (Pseudocode):</p>
<pre><code>search = {{1}, {3}}
search_base = {{1, 2}, {3, 4}}
# search results in True
</code></pre>
<p>because the 1 can be found in the first set and the 3 in the second.
Order doesn't matter, but the number of subsets has to be identical, the search consists always of singletons.</p>
<p>Example (Intuition):</p>
<pre><code>search = {{"Vitamin D"}, {"Sodium"}}
search_base = {{"Vitamin D", "Vitamin"}, {"Sodium", "NA"}}
</code></pre>
<p>I want to know if search (a combination of two materials with different hierachical names) is in the search base. The search base here only contains a single entry.</p>
<hr />
<p>What I tried:</p>
<p><em>Using frozensets instead if sets for the hash.</em></p>
<pre><code>search = frozenset([frozenset([1]), frozenset([3])])
search_base = frozenset([frozenset([1, 2]), frozenset([3, 4])])
all_matched = []
for i, set_ in enumerate(search):
for bset_ in search_base:
if not set_.isdisjoint(bset_):
all_matched.append(True)
print(len(all_matched) == len(search))
</code></pre>
<p>It feels very clunky and therefore my question is if there is a much smarter (better performance) way to solve this.</p>
| [
{
"answer_id": 74426103,
"author": "j1-lee",
"author_id": 11450820,
"author_profile": "https://Stackoverflow.com/users/11450820",
"pm_score": 3,
"selected": true,
"text": "all"
},
{
"answer_id": 74432028,
"author": "Andreas",
"author_id": 11971785,
"author_profile": "https://Stackoverflow.com/users/11971785",
"pm_score": 0,
"selected": false,
"text": "search = {1, 3}\nsearch_base = ({1, 2}, {3, 4})\n\nfrom itertools import product\nnew_search_base = tuple(set(x) for x in product(*search_base))\nprint(search in new_search_base)\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11971785/"
] |
74,426,040 | <p>I am getting an InvalidOperationException when using a projection into a record type (.Net 7). The query works fine if the where clause is chained. It also works if where clause is not chained and the projection is not into a record (class, anonymous type both ok).</p>
<pre><code>public record TestDto(
int CellLocationId,
string AreaCode
);
</code></pre>
<p><strong>This works</strong> - Chained:</p>
<pre><code>var query = _context.myTable.Where(x => x.AreaCode == areaCode).Select(s => new TestDto(s.CellLocationId, s.AreaCode));
</code></pre>
<p><strong>This fails</strong> - Unchained with record:</p>
<pre><code>var query = _context.myTable.Select(s => new TestDto(s.CellLocationId, s.AreaCode));
query = query.Where(x => x.AreaCode == areaCode);
</code></pre>
<p><strong>This works</strong> - Unchained with anonymous type:</p>
<pre><code>var query = _context.myTable.Select(s => new {s.CellLocationId, s.AreaCode});
query = query.Where(x => x.AreaCode == areaCode);
</code></pre>
<p>When projecting into a record the sql shown in the error appears as:</p>
<blockquote>
<p>System.InvalidOperationException: The LINQ expression 'DbSet().Where(v => new TestDto(v.CellLocationId, v.AreaCode).AreaCode == __areaCode_0)' could not be translated.</p>
</blockquote>
<p>Why can I not use a record when my IQueryable is using an unchained where clause?</p>
<p><strong>15/11/2022 Update.</strong><br />
<a href="https://github.com/dotnet/efcore/issues/27281" rel="nofollow noreferrer">Github</a> issue<br />
Possible workarounds - project into class, anonymous type or as per Bagus Tesa answer (and my preferred option) project into record type at end of statement.</p>
| [
{
"answer_id": 74427866,
"author": "Bagus Tesa",
"author_id": 4648586,
"author_profile": "https://Stackoverflow.com/users/4648586",
"pm_score": 1,
"selected": false,
"text": "IEnumerable"
},
{
"answer_id": 74429064,
"author": "quetzalcoatl",
"author_id": 717732,
"author_profile": "https://Stackoverflow.com/users/717732",
"pm_score": -1,
"selected": false,
"text": "<of-you-custom-type>"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7759286/"
] |
74,426,052 | <p>I have 2 components, the Favorites component, makes a request to the api and maps the data to Card.</p>
<p>I also have a BtnFav button, which receives an individual item, and renders a full or empty heart according to a boolean.</p>
<p>Clicking on the BtnFav render removes a certain item from the favorites database.</p>
<p>What I need is that in the Favorites component, when I click on the BtnFavs component, the useEffect of Favorites is triggered again to bring the updated favorites.</p>
<p>How can i solve this? I have partially solved it with a global context(favoritesUser), but is there any other neater alternative?</p>
<p>The data flow for now would be something like this:</p>
<p>Favorites component fetches all the complete data and passes it to the Card component, the Card component passes individual data to the BtnFavs component.</p>
<pre><code>Favorites Component:
const fetchWines = async () => {
try {
const vinos = await axios.get(`/api/favoritos/${id}`);
const arrVinos = vinos.data.map((vino) => {
return vino.product;
});
setVinosFavs(arrVinos);
} catch (err) {
console.error(err);
}
};
useEffect(() => {
fetchWines();
}, [favoritesUser]);
return (
<div>
<h1>Mis favoritos</h1>
<Card listWines={vinosFavs} />
</div>
);
</code></pre>
<pre><code>BtnFavs:
const handleClickFav = (e) => {
if (!boton) {
axios.post("/api/favoritos/add", { userId, productId }).then((data) => {
setBoton(true);
return;
});
}
axios.put("/api/favoritos/delete ", { userId, productId }).then((data) => {
setBoton(false);
setFavoritesUser(data);
});
};
</code></pre>
<p>What I need is that in the Favorites component, when I click on the BtnFavs component, the useEffect of Favorites is triggered again to bring the updated favorites.</p>
<p>How can i solve this? I have partially solved it with a global context(favoritesUser), but is there any other neater alternative?</p>
| [
{
"answer_id": 74427866,
"author": "Bagus Tesa",
"author_id": 4648586,
"author_profile": "https://Stackoverflow.com/users/4648586",
"pm_score": 1,
"selected": false,
"text": "IEnumerable"
},
{
"answer_id": 74429064,
"author": "quetzalcoatl",
"author_id": 717732,
"author_profile": "https://Stackoverflow.com/users/717732",
"pm_score": -1,
"selected": false,
"text": "<of-you-custom-type>"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20496336/"
] |
74,426,054 | <p>I'm working with a React MUI DataGrid. I need to get the values of the selected rows. At the moment, only the ids are coming through, and I get several errors throughout.</p>
<pre><code>rows = data;
const columns = [
{
field: "id",
headerName: "ID",
sortable: false,
hide: true,
},
{
field: "firstName",
headerName: "First Name",
},
{
field: "lastName",
headerName: "Last Name",
},
{
field: "age",
headerName: "Age",
}
];
</code></pre>
<p>This is my React Hook.</p>
<pre><code>const [ selection, setSelection ] = useState<GridSelectionModel>([]);
</code></pre>
<p>And this is the DataGrid.</p>
<pre><code><div style={{ height: 400, width: "100%" }}>
<DataGrid
rows={rows}
columns={columns}
checkboxSelection
getRowId={(row) => row.id}
onSelectionModelChange={(newSelection) => {
setSelection(newSelection);
console.log("selection", selection)
}}
{...rows}
/>
</div>
</code></pre>
<p>This prints the id.</p>
<pre><code><p>{selection.map((data) => data)}</p>
</code></pre>
<p>But, what I need, and I'm not able to figure out is:</p>
<pre><code>{selection.map((data) => {
return (
<div key={data.id}>. <---ERROR
<p>{data.firstName}</p> <---ERROR
<p>{data.lastName}</p> <---ERROR
</div>
)
})}
</code></pre>
<p>When I do it this way, I get the following error: "Property does not exist on type 'GridRowId'."</p>
| [
{
"answer_id": 74427866,
"author": "Bagus Tesa",
"author_id": 4648586,
"author_profile": "https://Stackoverflow.com/users/4648586",
"pm_score": 1,
"selected": false,
"text": "IEnumerable"
},
{
"answer_id": 74429064,
"author": "quetzalcoatl",
"author_id": 717732,
"author_profile": "https://Stackoverflow.com/users/717732",
"pm_score": -1,
"selected": false,
"text": "<of-you-custom-type>"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20453262/"
] |
74,426,086 | <p>I'm still a beginner, but I've managed to put the following portfolio site together because I want to start blogging.</p>
<p><a href="https://steviebrooks.github.io/folioSite.io/#home" rel="nofollow noreferrer">https://steviebrooks.github.io/folioSite.io/#home</a></p>
<p>I've had great feedback on the design, but I'm having issues with the menu when I access the site from a mobile device. My mentor advised me to include this code <a href="https://i.stack.imgur.com/j3rTg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/j3rTg.png" alt="enter image description here" /></a> but it hasn't fixed the problem.</p>
<p>Basically, I just want the menu to disappear once the user has selected an option.</p>
<p>Any suggestions are much appreciated. Cheers!</p>
<p>I asked my mentor for help and expected the problem to be solved, given that he is a professional. I am now going to experiment with different commands but will be surprised if I can fix this by myself. I have been practicing Javascript for one month.</p>
| [
{
"answer_id": 74427866,
"author": "Bagus Tesa",
"author_id": 4648586,
"author_profile": "https://Stackoverflow.com/users/4648586",
"pm_score": 1,
"selected": false,
"text": "IEnumerable"
},
{
"answer_id": 74429064,
"author": "quetzalcoatl",
"author_id": 717732,
"author_profile": "https://Stackoverflow.com/users/717732",
"pm_score": -1,
"selected": false,
"text": "<of-you-custom-type>"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426086",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20166771/"
] |
74,426,158 | <p>I am trying to write a query in azure databricks and I am getting the following error</p>
<pre><code>"IN/EXISTS predicate sub-queries can only be used in Filter/Join and a few commands"
</code></pre>
<p>This is the code I am using.</p>
<pre><code>SELECT id,
(CASE WHEN id in (SELECT id from aTable) THEN 1 ELSE 0 END) as a,
(CASE WHEN id in (SELECT id from bTable) THEN 1 ELSE 0 END) as b,
(CASE WHEN id in (SELECT id from cTable) THEN 1 ELSE 0 END) as c
FROM table
</code></pre>
<p>I read that sql doesn't let you do this because the case statements are evaluated row by row, and it wants to prevent you from doing a SELECT statement for each row evaluation. If that is the case, is there an alternative or workaround to accomplish this? Thanks</p>
| [
{
"answer_id": 74427866,
"author": "Bagus Tesa",
"author_id": 4648586,
"author_profile": "https://Stackoverflow.com/users/4648586",
"pm_score": 1,
"selected": false,
"text": "IEnumerable"
},
{
"answer_id": 74429064,
"author": "quetzalcoatl",
"author_id": 717732,
"author_profile": "https://Stackoverflow.com/users/717732",
"pm_score": -1,
"selected": false,
"text": "<of-you-custom-type>"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7822387/"
] |
74,426,167 | <p>I am writing a piece of code to accept an array containing several objects with the properties "category", "itemName", and "Onsale" and then reorganize it into an object that takes the items in the "category" property and makes them into properties containing values from the "itemNames" property with an additional ($) added next to the value if the "onSale" property in the object it was listed in was true. After writing and testing the code it kept returning the "Cannot read property '0' of undefined" at line 13 where I was trying to call an the the [i] object in an array. My array is defined at that index value so I am not sure what is going on. I apologize if My code looks amateurish I am new to javascript. Any help would be greatly appreciated.</p>
<p>I tried to split up the assignment; for example instead of:</p>
<pre><code>myObj = items[i]["category"][0];
</code></pre>
<p>I wrote:</p>
<pre><code>myObj = items[i]["category"][0];
myObj.item[i] = ["category"][0];
</code></pre>
<p>I tried to switch my initial conditions for my for loop; for example to <code>i = 1</code> instead of <code>i = 0</code></p>
<p>I tried inputing a different array such as: <code>myArray = [1, 2, 3, 5]</code> but I ended up getting the same error but in a different location</p>
<p>Here is my code:</p>
<pre><code>function organizeItems(items) {
let myObj = {}
for (let i = 0; i < items.length; i++) {
if (items[i]["category"][0] in myObj === false) {
if (items[i]["onSale"] === true) {
myObj = items[i]["category"][0];
myObj.items[i]["category"][0] = [];
myObj.items[i]["category"][0].push(items[i]["itemName"][0] + '($)');
}
else {
myObj = items[i]["category"][0];
myObj.items[i]["category"][0] = [];
myObj.items[i]["category"][0].push(items[i]["itemName"][0]);
}
}
else {
if (items[i]["onSale"] === true) {
myObj.items[i]["category"][0].push(items[i]["itemName"][0] + '($)');
}
else {
myObj.items[i]["category"][0].push(items[i]["itemName"][0]);
}
}
}
console.log(myObj);
return myObj;
}
var iten = [1, 2, 3, 4, 5, 6];
var itemData = [
{ category: 'fruit', itemName: 'apple', onSale: false },
{ category: 'canned', itemName: 'beans', onSale: false },
{ category: 'canned', itemName: 'corn', onSale: true },
{ category: 'frozen', itemName: 'pizza', onSale: false },
{ category: 'fruit', itemName: 'melon', onSale: true },
{ category: 'canned', itemName: 'soup', onSale: false },
];
organizeItems(itemData);
</code></pre>
<p>And here is the error I received:</p>
<pre class="lang-bash prettyprint-override"><code>/usr/src/app/test/unit_tests_spec.js:19
myObj.items[i]["category"][0] = [];
^
TypeError: Cannot read property '0' of undefined
at organizeItems (/usr/src/app/test/unit_tests_spec.js:20:12)
at Object.<anonymous> (/usr/src/app/test/unit_tests_spec.js:47:1)
at Module._compile (module.js:653:30)
at loader (/usr/src/app/node_modules/babel-register/lib/node.js:144:5)
at Object.require.extensions.(anonymous function) [as .js] (/usr/src/app/node_modules/babel- register/lib/node.js:154:7)
at Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12)
at Function.Module._load (module.js:498:3)
at Module.require (module.js:597:17)
at require (internal/module.js:11:18)
at /usr/src/app/node_modules/mocha/lib/mocha.js:231:27
at Array.forEach (<anonymous>)
at Mocha.loadFiles (/usr/src/app/node_modules/mocha/lib/mocha.js:228:14)
at Mocha.run (/usr/src/app/node_modules/mocha/lib/mocha.js:514:10)
at Object.<anonymous> (/usr/src/app/node_modules/mocha/bin/_mocha:480:18)
at Module._compile (module.js:653:30)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12)
at Function.Module._load (module.js:498:3)
at Function.Module.runMain (module.js:694:10)
at startup (bootstrap_node.js:204:16)
at bootstrap_node.js:625:3
npm ERR! Test failed. See above for more details.
</code></pre>
| [
{
"answer_id": 74426236,
"author": "ryuhojin",
"author_id": 20496118,
"author_profile": "https://Stackoverflow.com/users/20496118",
"pm_score": 1,
"selected": true,
"text": "function organizeItems(items) {\n let myObj = {}\n for(let i = 0; i < items.length; i++) {\n if(items[i][\"category\"] in myObj === false) {\n if(items[i][\"onSale\"] === true) {\n myObj[items[i][\"category\"]] = [];\n myObj[items[i][\"category\"]].push(items[i][\"itemName\"] + '($)');\n }\n else {\n myObj[items[i][\"category\"]] = [];\n myObj[items[i][\"category\"]].push(items[i][\"itemName\"]);\n }\n }\n else {\n if(items[i][\"onSale\"] === true) {\n myObj[items[i][\"category\"]].push(items[i][\"itemName\"] + '($)');\n }\n else {\n myObj[items[i][\"category\"]].push(items[i][\"itemName\"]);\n }\n }\n}\nconsole.log(myObj); \nreturn myObj; \n \n}\nvar iten = [1,2,3,4,5,6];\nvar itemData = [\n{ category: 'fruit', itemName: 'apple', onSale: false },\n{ category: 'canned', itemName: 'beans', onSale: false },\n{ category: 'canned', itemName: 'corn', onSale: true },\n{ category: 'frozen', itemName: 'pizza', onSale: false },\n{ category: 'fruit', itemName: 'melon', onSale: true },\n{ category: 'canned', itemName: 'soup', onSale: false },\n ];\n\norganizeItems(itemData);\n"
},
{
"answer_id": 74426731,
"author": "Muthulakshmi M",
"author_id": 8350081,
"author_profile": "https://Stackoverflow.com/users/8350081",
"pm_score": 0,
"selected": false,
"text": " function organizeItems(items) {\n let myObj = {};\n for (let i = 0; i < items.length; i++) {\n if(Object.hasOwn(myObj, `${items[i][\"category\"]}`)){\n let arrVal = myObj[`${items[i][\"category\"]}`];\n arrVal.push((items[i][\"itemName\"]));\n }else{\n myObj[`${items[i][\"category\"]}`]=[`${items[i][\"itemName\"]}`];\n }\n }\n console.log(myObj);\n return myObj;\n }\n var itemData = [\n { category: 'fruit', itemName: 'apple', onSale: false },\n { category: 'canned', itemName: 'beans', onSale: false },\n { category: 'canned', itemName: 'corn', onSale: true },\n { category: 'frozen', itemName: 'pizza', onSale: false },\n { category: 'fruit', itemName: 'melon', onSale: true },\n { category: 'canned', itemName: 'soup', onSale: false },\n ];\n\n organizeItems(itemData);"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20496262/"
] |
74,426,208 | <p>I am new to CSS and not quite sure how to do spacing. Currently I have tried to center 5 wheels on the page like this:</p>
<p><a href="https://i.stack.imgur.com/tQyhn.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tQyhn.jpg" alt="enter image description here" /></a></p>
<p>The CSS is</p>
<pre><code>body{
padding: 0px;
margin: 0px;
}
#wheels{
display: flex;
margin: 0;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
align-items: stretch;
width: 100%
}
#wheel1, #wheel2, #wheel3, #wheel4, #wheel5, canvas{
flex-grow: 1;
margin: 0;
padding: 0;
}
canvas{
width: 100%;
}
</code></pre>
<p>I already have margin 0 and padding 0. I need to reduce the spacing between the wheels so that they will display bigger. Not sure about how to do this. Any help is appreciated.</p>
<p><strong>EDITED:</strong></p>
<p>The program is based on javascript. It is related to my <a href="https://stackoverflow.com/questions/74248288/phaser-javascript-spinning-wheel-auto-spin-issue">other issue</a>. But we were not able to do the spacing properly.</p>
<p>Complete code:</p>
<pre><code><html>
<head>
<style>
body{
padding: 0px;
margin: 0px;
}
#wheels{
display: flex;
margin: 0;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
align-items: stretch;
width: 100%
}
#wheel1, #wheel2, #wheel3, #wheel4, #wheel5, canvas{
flex-grow: 1;
margin: 0;
padding: 0;
}
canvas{
width: 100%;
}
</style>
<script src = "phaser.min.js"></script>
<script>
// the game itself
var game;
var gameOptions = {
// slices (prizes) placed in the wheel
slices: 8,
// prize names, starting from 12 o'clock going clockwise
slicePrizes: ["A KEY!!!", "50 STARS", "500 STARS", "BAD LUCK!!!", "200 STARS", "100 STARS", "150 STARS", "BAD LUCK!!!"],
// wheel rotation duration, in milliseconds
rotationTime: 3000
}
var gameConfig;
// once the window loads...
window.onload = function () {
gameConfig = {
type: Phaser.CANVAS,
parent: 'wheel1',
width: 600,
height: 600,
backgroundColor: 0xffffff,
scene: [playGame]
};
var game = new Phaser.Game(gameConfig);
game.scene.start('PlayGame', { degrees: 50 });
gameConfig = {
type: Phaser.CANVAS,
parent: 'wheel2',
width: 600,
height: 600,
backgroundColor: 0xffffff,
scene: [playGame]
};
var game2 = new Phaser.Game(gameConfig);
game2.scene.start('PlayGame', { degrees:100 });
gameConfig = {
type: Phaser.CANVAS,
parent: 'wheel3',
width: 600,
height: 600,
backgroundColor: 0xffffff,
scene: [playGame]
};
var game3 = new Phaser.Game(gameConfig);
game3.scene.start('PlayGame', { degrees: 150 });
gameConfig = {
type: Phaser.CANVAS,
parent: 'wheel4',
width: 600,
height: 600,
backgroundColor: 0xffffff,
scene: [playGame]
};
var game4 = new Phaser.Game(gameConfig);
game4.scene.start('PlayGame', { degrees: 250 });
gameConfig = {
type: Phaser.CANVAS,
parent: 'wheel5',
width: 600,
height: 600,
backgroundColor: 0xffffff,
scene: [playGame]
};
var game5 = new Phaser.Game(gameConfig);
game5.scene.start('PlayGame', { degrees: 300 });
}
// PlayGame scene
class playGame extends Phaser.Scene {
// constructor
constructor() {
super({ key: "PlayGame" });
}
// method to be executed when the scene preloads
preload() {
//loading assets
this.load.image("wheel", "wheel.png");
this.load.image("pin", "pin.png");
}
// method to be executed once the scene has been created
create(data) {
// adding the wheel in the middle of the canvas
this.wheel = this.add.sprite(gameConfig.width / 2, gameConfig.height / 2, "wheel");
// adding the pin in the middle of the canvas
this.pin = this.add.sprite(gameConfig.width / 2, gameConfig.height / 2, "pin");
// adding the text field
this.prizeText = this.add.text(gameConfig.width / 2, gameConfig.height - 20, "Spin the wheel", {
font: "bold 32px Arial",
align: "center",
color: "black"
});
// center the text
this.prizeText.setOrigin(0.5);
// the game has just started = we can spin the wheel
this.canSpin = true;
//this.input.on("pointerdown", this.spinWheel, this);
this.spinWheel(data.degrees);
}
// function to spin the wheel
spinWheel(degrees) {
// can we spin the wheel?
if (this.canSpin) {
// resetting text field
this.prizeText.setText("");
// the wheel will spin round from 2 to 4 times. This is just coreography
var rounds = Phaser.Math.Between(8, 10);
// var degrees = Phaser.Math.Between(0, 360);
var prize = gameOptions.slices - 1 - Math.floor(degrees / (360 / gameOptions.slices));
// now the wheel cannot spin because it's already spinning
this.canSpin = false;
// animation tweeen for the spin: duration 3s, will rotate by (360 * rounds + degrees) degrees
// the quadratic easing will simulate friction
this.tweens.add({
// adding the wheel to tween targets
targets: [this.wheel],
// angle destination
angle: 360 * rounds + degrees,
// tween duration
duration: gameOptions.rotationTime,
// tween easing
ease: "Cubic.easeOut",
// callback scope
callbackScope: this,
// function to be executed once the tween has been completed
onComplete: function (tween) {
// displaying prize text
this.prizeText.setText(gameOptions.slicePrizes[prize]);
// player can spin again
this.canSpin = true;
}
});
}
}
}
</script>
</head>
<body>
<div id="wheels">
<div id="wheel1"></div>
<div id="wheel2"></div>
<div id="wheel3"></div>
<div id="wheel4"></div>
<div id="wheel5"></div>
</div>
</body>
</html>
</code></pre>
| [
{
"answer_id": 74426358,
"author": "Mad7Dragon",
"author_id": 6467902,
"author_profile": "https://Stackoverflow.com/users/6467902",
"pm_score": 0,
"selected": false,
"text": ".container {\n width: 100vw;\n height: 150px;\n border: 1px solid;\n background: lightcoral;\n display: flex;\n justify-content: center;\n align-items: center;\n}\n\n.circle {\n min-width: 40px;\n min-height: 40px;\n padding: 40px;\n /* this margin will control space between circles */\n margin: 0 5px;\n background: blue;\n border-radius: 50%;\n display: flex;\n justify-content: center;\n align-items: center;\n}"
},
{
"answer_id": 74427559,
"author": "Damzaky",
"author_id": 7552340,
"author_profile": "https://Stackoverflow.com/users/7552340",
"pm_score": 2,
"selected": true,
"text": "gameConfig"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4139461/"
] |
74,426,222 | <p>Here is the target code with the <code>Invoke</code> call:
<a href="https://i.stack.imgur.com/313Ky.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/313Ky.png" alt="image" /></a></p>
<p>Here is the player code:
<a href="https://i.stack.imgur.com/xIjHs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xIjHs.png" alt="Image" /></a></p>
<p>I have also tried without the <code>nameof</code> statement but it doesnt work.</p>
| [
{
"answer_id": 74430679,
"author": "Pavlos Mavris",
"author_id": 16523060,
"author_profile": "https://Stackoverflow.com/users/16523060",
"pm_score": 0,
"selected": false,
"text": "Invoke()"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426222",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15616896/"
] |
74,426,229 | <p>Is this a bug, or am I doing something wrong? I already tried providing hashing and equality functors for the pointer type, but it doesn't seem to work. I even tried creating my own miniature template container just to test the functors.</p>
<p>Hashing functor:</p>
<pre><code>class CharPtHash
{
private:
using pChar = char*;
public:
size_t operator()(const pChar& c) const
{
std::hash<char> hasher;
if (c == nullptr)
{
return 0;
}
return hasher(*c);
}
};
</code></pre>
<p>Equality:</p>
<pre><code>class CharPtEqual
{
private:
using pChar = char*;
public:
bool operator()(const pChar& lhs, const pChar& rhs)const
{
if (lhs == rhs)//not sure of nullptr is equal to itself.
{
return true;
}
else if (lhs==nullptr || rhs==nullptr)
{
return false;
}
return *lhs == *rhs;
}
};
</code></pre>
<p>Main:</p>
<pre><code>int main()
{
cout << "Testing unordered_multiset with keys being simple types:\n";
unordered_multiset<char> sA1({ 'a','b','c' });
unordered_multiset<char> sA2({ 'a','c','b' });
cout << "Values: " << endl << sA1 << endl << sA2 << endl;
cout << (sA1 == sA2 ? "Equal" : "Not Equal");
cout << endl;
cout << "Testing unordered_multiset with keys being pointers to simple types:\n";
char** c1 = new char* [3]{ new char('a'), new char('b'), new char('c') };
char** c2 = new char* [3]{ new char('a'), new char('c'), new char('b') };
unordered_multiset<char*,CharPtHash,CharPtEqual> sB1;
unordered_multiset<char*,CharPtHash,CharPtEqual> sB2;
sB1.insert(c1[0]);
sB1.insert(c1[1]);
sB1.insert(c1[2]);
sB2.insert(c2[0]);
sB2.insert(c2[1]);
sB2.insert(c2[2]);
cout << "Values: " << endl << sB1 << endl << sB2 << endl;
cout << (sB1 == sB2 ? "Equal" : "Not Equal");
cout << endl;
cin.get();
}
</code></pre>
<p>I tried compiling it to c++20 and c++14 using Visual Studio 2022.</p>
<p>This is the output:</p>
<pre><code>Testing unordered_multiset with keys being simple types:
Values:
{ a, b, c }
{ a, c, b }
Equal
Testing unordered_multiset with keys being pointers to simple types:
Values:
{ a, b, c }
{ a, c, b }
Not Equal
</code></pre>
| [
{
"answer_id": 74426307,
"author": "Yksisarvinen",
"author_id": 7976805,
"author_profile": "https://Stackoverflow.com/users/7976805",
"pm_score": 1,
"selected": false,
"text": "Hash"
},
{
"answer_id": 74427152,
"author": "Ranoiaetep",
"author_id": 12861639,
"author_profile": "https://Stackoverflow.com/users/12861639",
"pm_score": 1,
"selected": true,
"text": "KeyEqual"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18548896/"
] |
74,426,240 | <p>I need to print the second largest number on the list,
the output from the below code is all elements in the list except the first and the last one.
What is the mistake?</p>
<pre><code>void main () {
List a = [9,6,4,10,13,2,3,5];
a.sort;
for(int x in a){
for (int max in a){
for (int second_last in a){
if (x > max) {
second_last = max;
max = x;
} else if (x > second_last && x != max) {
second_last = x;
print(second_last);
}
}
}
}
}
</code></pre>
| [
{
"answer_id": 74426307,
"author": "Yksisarvinen",
"author_id": 7976805,
"author_profile": "https://Stackoverflow.com/users/7976805",
"pm_score": 1,
"selected": false,
"text": "Hash"
},
{
"answer_id": 74427152,
"author": "Ranoiaetep",
"author_id": 12861639,
"author_profile": "https://Stackoverflow.com/users/12861639",
"pm_score": 1,
"selected": true,
"text": "KeyEqual"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20496497/"
] |
74,426,254 | <p>I just created a new flutter project with no dependencies added and I'm getting this errors</p>
<p>`* What went wrong:
A problem occurred evaluating project ':app'.</p>
<blockquote>
<p>Could not initialize class com.android.build.gradle.internal.crash.PluginCrashReporter`</p>
</blockquote>
<p>`</p>
<pre><code>Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, 3.3.8, on Microsoft Windows [Version 10.0.19043.2251], locale en-US)
Checking Android licenses is taking an unexpectedly long time...[!] Android toolchain - develop for Android devices (Android SDK versio
n 32.0.0)
! Some Android licenses not accepted. To resolve this, run: flutter doctor --android-licenses
[√] Chrome - develop for the web
[X] Visual Studio - develop for Windows
X Visual Studio not installed; this is necessary for Windows development.
Download at https://visualstudio.microsoft.com/downloads/.
Please install the "Desktop development with C++" workload, including all of its default components
[√] Android Studio (version 2021.1)
[√] VS Code (version 1.73.1)
[√] Connected device (4 available)
[√] HTTP Host Availability
</code></pre>
<p>`
...and as you can see from my flutter doctor, everything looks fine and okay. Can someone please help me on this because I actually can't figure it out. Thank You.</p>
<p>I have tried upgrading the gradle but I'm still not getting a good result</p>
| [
{
"answer_id": 74426300,
"author": "Clode Morales Pampanga III",
"author_id": 5813279,
"author_profile": "https://Stackoverflow.com/users/5813279",
"pm_score": 1,
"selected": false,
"text": "rm -rf $HOME/.gradle/caches/"
},
{
"answer_id": 74426594,
"author": "MrShakila",
"author_id": 19292778,
"author_profile": "https://Stackoverflow.com/users/19292778",
"pm_score": 0,
"selected": false,
"text": "flutter doctor --android-licenses"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17801062/"
] |
74,426,285 | <p>I would like to uncheck a radio input without necessarily being forced to check another one. What would be the simplest way to do this?</p>
<pre><code> <C.SingleCard>
<h2>Pizza</h2>
<div>
<hr />
<h3>Flavors</h3>
<hr />
</div>
<div>
<h4>Pepperoni</h4>
<input type="radio" name='flavor' />
</div>
<div>
<h4>Chicken</h4>
<input type="radio" name='flavor' />
</div>
<div>
<h4>Bacon</h4>
<input type="radio" name='flavor' />
</div>
<div>
<button>Add</button>
</div>
</C.SingleCard>
</code></pre>
| [
{
"answer_id": 74426300,
"author": "Clode Morales Pampanga III",
"author_id": 5813279,
"author_profile": "https://Stackoverflow.com/users/5813279",
"pm_score": 1,
"selected": false,
"text": "rm -rf $HOME/.gradle/caches/"
},
{
"answer_id": 74426594,
"author": "MrShakila",
"author_id": 19292778,
"author_profile": "https://Stackoverflow.com/users/19292778",
"pm_score": 0,
"selected": false,
"text": "flutter doctor --android-licenses"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15653306/"
] |
74,426,289 | <p>I have a variable set to a string of about 30 characters. I used .split() to turn the string into an array. Now the part I am struggling with is looping through the array I just made, incrementing a counter I have set to a variable, and the variable incrementing anything the array iterates past the last 5 numbers in the array?</p>
<p>Thanks in advance to anyone that can help!</p>
<p>I tried this inside my function...</p>
<pre><code>let numsArr = [0, 1, 2, 3, ...... ,30]
let numOfInvalidElement = 0;
function() {
for(let i = 0; i < numsArr.length; i++) {
if (numsArr >= 20) {
return numofInvalidElement++
}
}
}
</code></pre>
| [
{
"answer_id": 74426300,
"author": "Clode Morales Pampanga III",
"author_id": 5813279,
"author_profile": "https://Stackoverflow.com/users/5813279",
"pm_score": 1,
"selected": false,
"text": "rm -rf $HOME/.gradle/caches/"
},
{
"answer_id": 74426594,
"author": "MrShakila",
"author_id": 19292778,
"author_profile": "https://Stackoverflow.com/users/19292778",
"pm_score": 0,
"selected": false,
"text": "flutter doctor --android-licenses"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20496058/"
] |
74,426,291 | <p>I would like to generate an OTP 6-digit pin in my C# .NET Application. However, for security reasons, I heard that using the Random() package to perform this action might not be the most appropriate. Are there any other methods available?</p>
| [
{
"answer_id": 74426320,
"author": "Igor",
"author_id": 17005821,
"author_profile": "https://Stackoverflow.com/users/17005821",
"pm_score": 0,
"selected": false,
"text": "System.Security.Cryptography.RNGCryptoServiceProvider.GetBytes"
},
{
"answer_id": 74426500,
"author": "Enigmativity",
"author_id": 259769,
"author_profile": "https://Stackoverflow.com/users/259769",
"pm_score": 1,
"selected": false,
"text": "System.Security.Cryptography"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19561210/"
] |
74,426,312 | <p>In the parent component, I get the width, which may differ depending on the device on which the application is opened:</p>
<pre><code>const projectVisor = useRef()
const [width, setWidth] = useState(0)
useEffect(() => {
setWidth(projectVisor.current.offsetWidth)
}, [])
</code></pre>
<p>Now i want to pass this value to child in props</p>
<pre><code><ProjectItem
width={width}
/>
</code></pre>
<p>But in the child, I always get 0. I think this is due to the fact that the useEffect runs at the same time as the child is rendered, which means that at the time the child is rendered, the value is 0. But I do not know how to avoid this.</p>
| [
{
"answer_id": 74426320,
"author": "Igor",
"author_id": 17005821,
"author_profile": "https://Stackoverflow.com/users/17005821",
"pm_score": 0,
"selected": false,
"text": "System.Security.Cryptography.RNGCryptoServiceProvider.GetBytes"
},
{
"answer_id": 74426500,
"author": "Enigmativity",
"author_id": 259769,
"author_profile": "https://Stackoverflow.com/users/259769",
"pm_score": 1,
"selected": false,
"text": "System.Security.Cryptography"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18146547/"
] |
74,426,314 | <p>I saved the value of 'result.address' received from the address api as a variable called final _resultAddress.</p>
<p>Assuming that you want to use this value in Text inside Child of Container, if you use Text(result.address), an error occurs. (undefiend name 'result.address)!</p>
<p>My question is simple. How can I use a variable in multiple places? (other methods, functions, etc.)</p>
<pre><code>
GestureDetector(
onTap: ()async{
await Navigator.push(context, MaterialPageRoute(
builder: (_) => KpostalView(
callback: (Kpostal result) {
final _resultAddress = result.address;
print(_resultAddress);
},
),
));
},
child: Container(
height: 48.0,
decoration: BoxDecoration(
color: Colors.red,
border: Border.all(
color: Colors.green,
),
),
child: Text(_resultAddress),
),
),
</code></pre>
<p>I tried to name the variable final, const, static, but it didn't work.</p>
| [
{
"answer_id": 74426320,
"author": "Igor",
"author_id": 17005821,
"author_profile": "https://Stackoverflow.com/users/17005821",
"pm_score": 0,
"selected": false,
"text": "System.Security.Cryptography.RNGCryptoServiceProvider.GetBytes"
},
{
"answer_id": 74426500,
"author": "Enigmativity",
"author_id": 259769,
"author_profile": "https://Stackoverflow.com/users/259769",
"pm_score": 1,
"selected": false,
"text": "System.Security.Cryptography"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19443112/"
] |
74,426,329 | <p>I can embed type A into B.</p>
<pre class="lang-golang prettyprint-override"><code>type A struct {
R int64
S int64
}
type B struct {
A
}
</code></pre>
<p>But how do I embed just a single field?</p>
<pre class="lang-golang prettyprint-override"><code>type B struct {
A.R // does not work
}
</code></pre>
| [
{
"answer_id": 74426373,
"author": "Igor",
"author_id": 17005821,
"author_profile": "https://Stackoverflow.com/users/17005821",
"pm_score": 0,
"selected": false,
"text": "type R struct {\n R int64\n}\n\ntype B struct {\n R\n}\n"
},
{
"answer_id": 74427246,
"author": "tim-montague",
"author_id": 1404726,
"author_profile": "https://Stackoverflow.com/users/1404726",
"pm_score": 0,
"selected": false,
"text": "type A struct {\n R int64\n S int64\n}\n\ntype B struct {\n R A\n}\n"
},
{
"answer_id": 74427384,
"author": "Hymns For Disco",
"author_id": 11424673,
"author_profile": "https://Stackoverflow.com/users/11424673",
"pm_score": 3,
"selected": true,
"text": "A"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1404726/"
] |
74,426,331 | <p>The input (account numbers) I have are currently in the format <strong>005-947864-296</strong>, I'm using the translate function to remove dashes as follows: <em><xsl:value-of select="translate(($account_number), '-', '')"/></em> The problem is that the output I'm getting in the csv is <strong>5947864296</strong> (which is removing Leading Zeros). How do I remove the dashes WITHOUT removing the leading zeros?</p>
<p>I'm using XSLT 2.0 and I tried both translate and replace functions but getting the same result!</p>
| [
{
"answer_id": 74426355,
"author": "Igor",
"author_id": 17005821,
"author_profile": "https://Stackoverflow.com/users/17005821",
"pm_score": -1,
"selected": false,
"text": "<xsl:value-of select=\"replace($account_number, '-', '')\"/>\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426331",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20496609/"
] |
74,426,371 | <p>I have a problem to find the fastest way to check if a substring is in a string as an entire word or term. Currently, I'm using RegEx, but I need to perform thousands of verifications and RegEx is being VERY slow.</p>
<p>There are many ways to respond to this. The easier way to verify is <code>substring in string</code>:</p>
<pre><code>substring = "programming"
string = "Python is a high-level programming language"
substring in string
>>> True
</code></pre>
<p>In other hand, it's a naivy solution when we need to find the substring as an entire word or term:</p>
<pre><code>substring = "program"
string = "Python is a high-level programming language"
substring in string
>>> True
</code></pre>
<p>Another solution is to split the string into a list of words and verify if the substring is in that list:</p>
<pre><code>substring = "program"
string = "Python is a high-level programming language"
substring in string.split()
>>> False
</code></pre>
<p>Nevertheless, it doesn't work if the substring is a term. To resolve this, another solution would be to use RegEx:</p>
<pre><code>import re
substring = "high-level program"
string = "Python is a high-level programming language"
re.search(r"\b{}\b".format(substring), string) != None
>>> False
</code></pre>
<p>However, my biggest problem is that the solution is REALLY slow if you need to perform thousands of verifications.</p>
<p>To mitigate this issue, I created some approaches that, although they are faster than RegEx (for the use I need), still are a lot slower than <code>substring in string</code>:</p>
<pre><code>substring = "high-level program"
string = "Python is a high-level programming language"
all([word in string.split() for word in substring.split()])
>>> False
</code></pre>
<p>Although simple, the above approach didn't fit because it ignores substring word order, returning <code>True</code> if the substring was <code>"programming high-level"</code>, unlike the solution in RegEx. So, I created another approach verifying if the substring is in a ngram list where each ngram has the same number of words as the substring:</p>
<pre><code>from nltk import ngrams
substring = "high-level program"
string = "Python is a high-level programming language"
ngram = list(ngrams(string.split(), len(substring.split())))
substring in [" ".join(tuples) for tuples in ngram]
>>> False
</code></pre>
<p><strong>EDIT:</strong> Here is a less slow version, working with the same principle, but using only built-in functions:</p>
<pre><code>substring = "high-level program"
string = "Python is a high-level programming language"
length = len(substring.split())
words = string.split()
ngrams = [" ".join(words[i:i+length]) for i in range(len(words) - length)]
substring in ngrams
>>> False
</code></pre>
<p>Someone knows some a faster approach to find a substring inside a string as an entire word or term?</p>
| [
{
"answer_id": 74426355,
"author": "Igor",
"author_id": 17005821,
"author_profile": "https://Stackoverflow.com/users/17005821",
"pm_score": -1,
"selected": false,
"text": "<xsl:value-of select=\"replace($account_number, '-', '')\"/>\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19371714/"
] |
74,426,378 | <p>I am just wondering, functionally, what is the difference between:</p>
<pre><code>private int var {get; set;}
</code></pre>
<p>and</p>
<pre><code>public int var {get; private set;}
</code></pre>
<p>Also, why does</p>
<pre><code>private int var {get; set;}
</code></pre>
<p>return an error?</p>
<p>I am new to using getters and setters.</p>
| [
{
"answer_id": 74426420,
"author": "Igor",
"author_id": 17005821,
"author_profile": "https://Stackoverflow.com/users/17005821",
"pm_score": 3,
"selected": true,
"text": "private int var {get; set;}\n"
},
{
"answer_id": 74426630,
"author": "koishi",
"author_id": 17993868,
"author_profile": "https://Stackoverflow.com/users/17993868",
"pm_score": 0,
"selected": false,
"text": "public int var { get; set; }"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20496642/"
] |
74,426,387 | <p>I have a pandas.DataFrame with columns 'start', 'end', and 'vals_to_sum'. I want to sum all values in the latter column for dates in a list of days in datetime.date format: <code>date_list = [start_date + datetime.timedelta(days=i) for i in range(366)]</code> where start_date is of datetime.date. I have a problem where when I try to index my start and date times, python seems to convert them to str format and I get a TypeError.</p>
<p>My code currently is:</p>
<pre><code># Initialise empty array to fill with summed values for each day
output = numpy.zeros(len(date_list))
for idx, date in enumerate(date_list):
# Concatonate all values within date range start < x < end
print(type(start),'start') # <class 'datetime.date'> start
print(type(end), 'end') # <class 'datetime.date'> end
print(type(date), 'date') # <class 'datetime.date'> date
to_sum = [value for i, value in enumerate(df['vals_to_sum'])
if df['start'] <= date & df['end'] >= date]
output[idx] = numpy.sum(numpy.array(to_sum).astype(numpy.float))
</code></pre>
<p>However, I get the following error:
TypeError: unsupported operand type(s) for &: 'str' and 'datetime.date'</p>
| [
{
"answer_id": 74426420,
"author": "Igor",
"author_id": 17005821,
"author_profile": "https://Stackoverflow.com/users/17005821",
"pm_score": 3,
"selected": true,
"text": "private int var {get; set;}\n"
},
{
"answer_id": 74426630,
"author": "koishi",
"author_id": 17993868,
"author_profile": "https://Stackoverflow.com/users/17993868",
"pm_score": 0,
"selected": false,
"text": "public int var { get; set; }"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20443881/"
] |
74,426,394 | <p>I am trying to save a Token variable in a <code>LoginResponseModel</code> but I am getting:</p>
<pre><code>Error: 'await' can only be used in 'async' or 'async*' methods.
await storage.write(key: 'Token', value: mapOfBody['key']);
^^^^^
</code></pre>
<p>Here is the Class:</p>
<pre><code>class LoginResponseModel {
dynamic? key;
List<dynamic>? non_field_errors;
LoginResponseModel({this.key, this.non_field_errors});
LoginResponseModel.fromJson(mapOfBody) {
key:
mapOfBody['key'];
non_field_errors:
mapOfBody['non_field_errors'];
print(mapOfBody['key']);
// Create storage
final storage = const FlutterSecureStorage();
// Write value
await storage.write(key: 'Token', value: mapOfBody['key']);
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['key'] = key;
_data['non_field_errors'] = non_field_errors;
return _data;
}
}
</code></pre>
<p>to access the value:</p>
<pre><code>var value = LoginResponseModel.storage.read(key: 'Token');
</code></pre>
<p>How can I fix the await problem so that I can easily access the token?</p>
| [
{
"answer_id": 74426420,
"author": "Igor",
"author_id": 17005821,
"author_profile": "https://Stackoverflow.com/users/17005821",
"pm_score": 3,
"selected": true,
"text": "private int var {get; set;}\n"
},
{
"answer_id": 74426630,
"author": "koishi",
"author_id": 17993868,
"author_profile": "https://Stackoverflow.com/users/17993868",
"pm_score": 0,
"selected": false,
"text": "public int var { get; set; }"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13176726/"
] |
74,426,433 | <p>I created FunA in App.vue Mounted(). I created FunB in HomeView.vue Mounted().<br>
I go to HomeView Page and Refresh the page, FunB run before FunA. <br>
My Question is isn't App.vue Stuff run first before the compoment stuff ? I created FunC in App.vue beforeCreate(), and go back HomeView page and refresh again. I saw that Fun B still run before FunC and FunA.<br>
If I am using FunA as a global function to setup Axios Auth Headers, all compoment Mounted functions with Axios get will return 403 error.<br>
All stuff is working correctly if I enter the view by router-view.
<br>
What should I do except adding the auth headers to all Axios Request.</p>
<p>App.vue</p>
<pre><code>async mounted() {
await this.getServerTokenAuth()
},
methods: {
async getServerTokenAuth(){
await this.$mainApi.post('api/auth/', {
"username": "qweqwe",
"password": "qweqweqwe"
})
.then(response => {
console.log(response.data.token)
this.$store.commit("setServerToken")
this.$mainApi.defaults.headers.common['Authorization'] = "Token " + response.data.token;
this.$mainApi.defaults.headers.common['Accept-Language'] = this.$store.state.language;
if(this.$store.state.isAuthenticated === true){
this.$mainApi.defaults.headers.common['CUSTOM_HEADERS'] = "qweqweqwe";
console.log("User Data Added to Headers")
}
})
},
</code></pre>
<p>HomeView</p>
<pre><code> async mounted() {
await this.getBackendData() // return 403 error
},
methods: {
async getBackendData(){
// try to console log the Auth Headers, return undefined
await this.$mainApi.get('api/product/list/')
.then(response => {
if(response.data.status === 80){
this.tabulator.setData(response.data.details)
this.totalProduct = response.data.details.length
}
})
}
},
</code></pre>
| [
{
"answer_id": 74426420,
"author": "Igor",
"author_id": 17005821,
"author_profile": "https://Stackoverflow.com/users/17005821",
"pm_score": 3,
"selected": true,
"text": "private int var {get; set;}\n"
},
{
"answer_id": 74426630,
"author": "koishi",
"author_id": 17993868,
"author_profile": "https://Stackoverflow.com/users/17993868",
"pm_score": 0,
"selected": false,
"text": "public int var { get; set; }"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9547157/"
] |
74,426,451 | <p>I have an object:
`</p>
<pre><code>{
"object": {
"id": 1,
"string": {
"stringWithoutData":"there is no data here"
"stringWithData": "this is a string with this {{data.extended.action}}",
},
}
}
</code></pre>
<p><code>I have an API with output</code></p>
<pre><code>{
"data": {
"extended": {
"action": "new sub string value "
}
}
}
</code></pre>
<p><code>I want the first object to be:</code></p>
<pre><code>{
"object": {
"id": 1,
"string": {
"stringWithoutData":"there is no data here"
"stringWithData": "this is a string with this new sub string value",
},
}
}
</code></pre>
<p>`</p>
<p>how do I access the "object" and check if the values which are starting with '{{' and ending with '}}' and if the value with this substring exists, I have to extract that value to make an api call and based on the response, replace with the data into the object.</p>
<p>I did try to parse through the object but never was able to extract it properly and check the api response object for data and replace that in place of {{data.extended.action}}</p>
| [
{
"answer_id": 74426522,
"author": "collinsuz",
"author_id": 12972377,
"author_profile": "https://Stackoverflow.com/users/12972377",
"pm_score": 0,
"selected": false,
"text": "{{data.extended.action}}"
},
{
"answer_id": 74426715,
"author": "code",
"author_id": 15359157,
"author_profile": "https://Stackoverflow.com/users/15359157",
"pm_score": 2,
"selected": false,
"text": "Array#reduce"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16820249/"
] |
74,426,503 | <pre><code> Dim Mysqlconn = New SqlConnection
Mysqlconn.ConnectionString = "Data Source=DESKTOP-D32ONKB;Initial Catalog=Attendance;Integrated Security=True"
Dim dt As DataTable = New DataTable("studentdata")
Mysqlconn.Open()
Dim query As String
query = "select ID from studentdata where Class='" & ComboBox1.Text & "'"
Dim Command = New SqlCommand(query, Mysqlconn)
Dim dr = Command.ExecuteReader(CommandBehavior.CloseConnection)
ListView1.Items.Clear()
Dim x As ListViewItem
Do While dr.Read = True
x = New ListViewItem(dr("ID").ToString)
ListView1.Items.Add(x)
Loop
For i = 0 To ListView1.Items.Count - 1
TextBox1.Text = ListView1.Items(i).SubItems(0).Text
Next
</code></pre>
<p>In this code, <code>Textbox1</code> is showing the last row from <code>Listview1</code>. My requirement is all the Listview1 data show in textbox1 one after one from Listview1. Is this possible to show in textbox1 read all data from Listview1 using loop. Thank you...</p>
| [
{
"answer_id": 74426522,
"author": "collinsuz",
"author_id": 12972377,
"author_profile": "https://Stackoverflow.com/users/12972377",
"pm_score": 0,
"selected": false,
"text": "{{data.extended.action}}"
},
{
"answer_id": 74426715,
"author": "code",
"author_id": 15359157,
"author_profile": "https://Stackoverflow.com/users/15359157",
"pm_score": 2,
"selected": false,
"text": "Array#reduce"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20369318/"
] |
74,426,513 | <p>i have a dataset which is a .txt file and each line has items separated by spaces. each line is a different transaction.</p>
<p>the dataset looks like this:</p>
<p>data.txt file</p>
<pre><code>1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
20 12 5 41 65
41 6 11 27 81 21
65 15 27 8 31 65 20 19 44 29 41
</code></pre>
<p>i created a dictionary with keys as serial num. starting from 0 and each line values seperated by commas as values like this</p>
<pre><code>{0: '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15', 1:'20,12,5,41,65', 2:'41,6,11,27,81,21', 3: '65,15,27,8,31,65,20,19,44,29,41'}
</code></pre>
<p>but i am not able to iterate through each value in dict , is there any way i can convert it into a list of values for each key</p>
<p>i want to find the frequency of each time in the whole dictionary and create a table</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>item</th>
<th>frequency</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>1</td>
</tr>
<tr>
<td>20</td>
<td>2</td>
</tr>
<tr>
<td>41</td>
<td>3</td>
</tr>
</tbody>
</table>
</div>
<p>like the above</p>
<pre><code>my_dict = {}
with open('text.csv', 'r') as file:
lines = file.readlines()
for line in lines:
my_dict[lines.index(line)] = line.strip()
</code></pre>
<p>this is the code i used to create the dictionary but i am not sure what i should change, also i need to find frequency of each value.</p>
<p>Any help would be appreciated. thank u.</p>
| [
{
"answer_id": 74426522,
"author": "collinsuz",
"author_id": 12972377,
"author_profile": "https://Stackoverflow.com/users/12972377",
"pm_score": 0,
"selected": false,
"text": "{{data.extended.action}}"
},
{
"answer_id": 74426715,
"author": "code",
"author_id": 15359157,
"author_profile": "https://Stackoverflow.com/users/15359157",
"pm_score": 2,
"selected": false,
"text": "Array#reduce"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15174562/"
] |
74,426,517 | <p>My first program is getting much bigger than excepted. :)</p>
<pre><code>import configparser
config = configparser.ConfigParser()
configfile = 'RealGui.ini'
class FolderLeftSettings:
def __init__(self):
self.name = "SECTION"
self.last_directory = ""
self.row_size = 6
self.column_size = 9
def write_to_ini(self):
if not config.has_section(str(self.name)):
config.add_section(str(self.name))
with open('configfile', 'w') as configfile:
config.set(self.name, 'last_directory', str(self.last_directory))
config.set(self.name, 'row_size', str(self.row_size))
config.set(self.name, 'column_size', str(self.column_size))
config.write(configfile)
def read_from_ini(self):
try:
config.read('configfile')
if config.has_section(str(self.name)):
self.last_directory = (config[self.name]['last_directory'])
self.row_size = int((config[self.name]['row_size']))
self.column_size = int((config[self.name]['column_size']))
except Exception as e:
print("failed to read ini....overwriting with defaults")
print(e)
self.write_to_ini()
settings=FolderLeftSettings()
</code></pre>
<p>My problem was, that every setting from the <strong>init</strong> needs to be written manually in the 2 methods as well.
I found the solution, and the answer is on the bottom.
Working Example!</p>
| [
{
"answer_id": 74426522,
"author": "collinsuz",
"author_id": 12972377,
"author_profile": "https://Stackoverflow.com/users/12972377",
"pm_score": 0,
"selected": false,
"text": "{{data.extended.action}}"
},
{
"answer_id": 74426715,
"author": "code",
"author_id": 15359157,
"author_profile": "https://Stackoverflow.com/users/15359157",
"pm_score": 2,
"selected": false,
"text": "Array#reduce"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6086645/"
] |
74,426,527 | <p>I have table like follows</p>
<pre><code>location rank
location_A 1
location_B 2
location_C 3
location_D 4
location_E 5
location_F 6
・
・
・
</code></pre>
<p>And, closest location = <code>location_E</code> and second scond closest location =<code>location_D</code>
so I would like to get following intermidiate table</p>
<pre><code>location rank
location_E 1
location_D 2
</code></pre>
<p>My desired result is as follows.<code>location_E</code> and <code>location_D</code> is moved its rank as <code>1</code> and <code>2</code> and remaining location preserve its <code>order</code> but slide its <code>rank</code></p>
<pre><code>location rank
location_E 1
location_D 2
location_A 3
location_B 4
location_C 5
location_F 6
・
・
</code></pre>
<p>Are there any good way to achieve this?
thanks</p>
| [
{
"answer_id": 74426522,
"author": "collinsuz",
"author_id": 12972377,
"author_profile": "https://Stackoverflow.com/users/12972377",
"pm_score": 0,
"selected": false,
"text": "{{data.extended.action}}"
},
{
"answer_id": 74426715,
"author": "code",
"author_id": 15359157,
"author_profile": "https://Stackoverflow.com/users/15359157",
"pm_score": 2,
"selected": false,
"text": "Array#reduce"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6724844/"
] |
74,426,546 | <p>I need to calculate code coverage for golang project where source of tests will be integration tests written in Java language . This requires go build to be instrumented first and then run on server so that tests can run and we will get to know after tests have ended, how much is code coverage? I haven't found a single reference for this on internet all there is present is unit tests which can be run easily and used to calculate coverage</p>
| [
{
"answer_id": 74427395,
"author": "kozmo",
"author_id": 8030651,
"author_profile": "https://Stackoverflow.com/users/8030651",
"pm_score": 0,
"selected": false,
"text": "-coverprofile"
},
{
"answer_id": 74431565,
"author": "Sergey Kurenkov",
"author_id": 20202768,
"author_profile": "https://Stackoverflow.com/users/20202768",
"pm_score": -1,
"selected": false,
"text": "go help build"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1999335/"
] |
74,426,552 | <p>I am running this for loop code and it is creating an error, I cannot find out the problem with it</p>
<pre><code>print("""\
This program will prompt you to enter your budget, and amount spent
for a certain month and calculate if your were under or over budget.
You will have the option of choosing how many months you would like to
monitor.\n""")
AmountSpent = 0
Budget = 0
numMonths = int(input("Enter the number of months you would like to monitor:"))
while numMonths<0:
print("\nNegative value detected!")
numMonths = int(input("Enter the number of months you would like to monitor"))
for month in range(1, numMonths+1):
print("\n=====================================")
AmountBudgeted = float(input("Enter amount budgeted for month "+month+":"))
while AmountBudgeted<0:
print("Negative value detected!")
AmountBudgeted = float(input("Enter amount budgeted for month "+month+":"))
AmountSpent = float(input("Enter amount spent for month "+month+":"))
while AmountSpent<0:
print("Negative value detected!")
AmountSpent = float(input("Enter amount spent for month "+month+":"))
if AmountSpent <= AmountBudgeted:
underBy = AmountBudgeted - AmountSpent
print("Under budget by " + underBy)
else:
overBy = AmountSpent - AmountBudgeted
print("Over budget by " + overBy)
if month == "1":
print(f'your budget is {AmountBudgeted}.')
</code></pre>
<p>Any ideas on why I am getting this error? I have tried to figure it out on my own but I dont know why it is wrong</p>
| [
{
"answer_id": 74427395,
"author": "kozmo",
"author_id": 8030651,
"author_profile": "https://Stackoverflow.com/users/8030651",
"pm_score": 0,
"selected": false,
"text": "-coverprofile"
},
{
"answer_id": 74431565,
"author": "Sergey Kurenkov",
"author_id": 20202768,
"author_profile": "https://Stackoverflow.com/users/20202768",
"pm_score": -1,
"selected": false,
"text": "go help build"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20391565/"
] |
74,426,554 | <p>I have a table that stores the response from certain API.
It has 1.7 million rows.
pk is a kind of UnixTime(not exactly, but smilliar).
I call the API very frequently to see if the data had changed.
To check if the data had changed, I have to run this command:</p>
<pre><code>SELECT 1
FROM RATE
WHERE REGDATE = '$apiReponseDate' --yymmddhhmmss
</code></pre>
<p>If the answer is <code>False</code>, that means the reponse had changed, and then I insert.
I have an INDEX on REGDATE, and I know this makes the table to do the binary search, not a full-search.</p>
<p>but I do know that in order to know if the data had updated, I only need to check the recent rows.
To me, using WHERE for the whole table seems an inefficient way.</p>
<p>Is there any good way to see if the data I got from the API response is already in DB or not?
I'm using Oracle, but that is not a main point because I'm thinking about searching the query's efficiency.</p>
| [
{
"answer_id": 74427395,
"author": "kozmo",
"author_id": 8030651,
"author_profile": "https://Stackoverflow.com/users/8030651",
"pm_score": 0,
"selected": false,
"text": "-coverprofile"
},
{
"answer_id": 74431565,
"author": "Sergey Kurenkov",
"author_id": 20202768,
"author_profile": "https://Stackoverflow.com/users/20202768",
"pm_score": -1,
"selected": false,
"text": "go help build"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20496722/"
] |
74,426,555 | <p>I have an entity that has as children several lists of objects that, although they have different classes, all have the order attribute, in several parts I end up with repeated code, for example in one part I need to order the lists by that attribute and I cannot simplify because they are of different type.</p>
<p>The relevant part of the entity is this:</p>
<pre><code>contenido={
"educaciones":[
{
...
"orden":0
},{
...
"orden":1
}
],
"experiencias":[
{
...
"orden":0
},{
...
"orden":1
}
]
},
...
</code></pre>
<p>The code I would like to simplify:</p>
<pre><code>if(tipo.equals("experiencias")){
List<Experiencia> iterable=contenido.getExperiencias();
for(int i = 0; i < iterable.size(); i++){
iterable.get(i).setOrden( orden.get(i) ); //orden = [0,3,5,...]
}
iterable.sort((it1,it2)-> it1.getOrden().compareTo(it2.getOrden()));
}else if(tipo.equals("educaciones")){
List<Educacion> iterable=contenido.getEducaciones();
for(int i = 0; i < iterable.size(); i++){
iterable.get(i).setOrden( orden.get(i) );
}
iterable.sort((it1,it2)-> it1.getOrden().compareTo(it2.getOrden()));
}else if...
</code></pre>
<p>Is there a way to create a code that is more generic and supports different objects?</p>
| [
{
"answer_id": 74427395,
"author": "kozmo",
"author_id": 8030651,
"author_profile": "https://Stackoverflow.com/users/8030651",
"pm_score": 0,
"selected": false,
"text": "-coverprofile"
},
{
"answer_id": 74431565,
"author": "Sergey Kurenkov",
"author_id": 20202768,
"author_profile": "https://Stackoverflow.com/users/20202768",
"pm_score": -1,
"selected": false,
"text": "go help build"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20496515/"
] |
74,426,580 | <p>I have a dataframe that looks something like this:</p>
<pre><code> i j
0 a b
1 a c
2 b c
</code></pre>
<p>I would like to convert it to another dataframe that looks like this:</p>
<pre><code> a b c
0 1 -1 0
1 1 0 -1
2 0 1 -1
</code></pre>
<p>The idea is to look at each row in the first dataframe and assign the value 1 to the item in the first column and the value -1 for the item in the second column and 0 for all other items in the new dataframe.
The second dataframe will have as many rows as the first and as many columns as the number of unique entries in the first dataframe. Thank you.</p>
<p>Couldn't really get a start on this.</p>
| [
{
"answer_id": 74427395,
"author": "kozmo",
"author_id": 8030651,
"author_profile": "https://Stackoverflow.com/users/8030651",
"pm_score": 0,
"selected": false,
"text": "-coverprofile"
},
{
"answer_id": 74431565,
"author": "Sergey Kurenkov",
"author_id": 20202768,
"author_profile": "https://Stackoverflow.com/users/20202768",
"pm_score": -1,
"selected": false,
"text": "go help build"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20496839/"
] |
74,426,581 | <p>I have a dataset with a column of unemployment, a column of months, and one for years.</p>
<p>I want to do a line plot where I have month number on the x axis, unemployment on the y axis and that each line represents a different year.</p>
<p>I first filtered the dataframe by year to have the y values for each year individually and I tried the following code:</p>
<pre><code>y1 = df %>% filter(year == 1996)
y1 = y1$unemploy
y2 = df %>% filter(year == 1997)
y2 = y2$unemploy
y3 = df %>% filter(year == 1998)
y3 = y3$unemploy
plot1 = ggplot() +
geom_line(mapping = aes(x = df$month, y = y1), color = "navyblue") +
geom_line(mapping = aes(x = df$month,y = y2), color = "black") +
geom_line(mapping = aes(x = df$month,y = y3), color = "red") +
scale_y_continuous(limits=c(0,10)) +
scale_x_continuous(limits=c(1,15))
plot1
</code></pre>
<p>But when I try to print the plot, I get the following error message:</p>
<pre><code>Error in `check_aesthetics()`:
! Aesthetics must be either length 1 or the same as the data (128): y
Run `rlang::last_error()` to see where the error occurred.
</code></pre>
<p>Does anyone know what could be the problem with this plot?</p>
<p>The output of <code>dput(head(df,20))</code> is the following:</p>
<pre><code>dput(head(df, 20))
structure(list(unemploy = c(6.7, 6.7, 6.4, 5.9, 5.2, 4.8, 4.8,
4, 4.2, 4.4, 5, 5, 6.4, 6.5, 6.3, 5.9, 4.9, 4.8, 4.5, 4), month = c(1L,
2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 1L, 2L, 3L, 4L,
5L, 6L, 7L, 8L), year = c(1996L, 1996L, 1996L, 1996L, 1996L,
1996L, 1996L, 1996L, 1996L, 1996L, 1996L, 1996L, 1997L, 1997L,
1997L, 1997L, 1997L, 1997L, 1997L, 1997L)), row.names = c(NA,
20L), class = "data.frame")
</code></pre>
| [
{
"answer_id": 74426766,
"author": "M--",
"author_id": 6461462,
"author_profile": "https://Stackoverflow.com/users/6461462",
"pm_score": 2,
"selected": false,
"text": "month"
},
{
"answer_id": 74426846,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 1,
"selected": false,
"text": "geom_line()"
},
{
"answer_id": 74427750,
"author": "Rui Barradas",
"author_id": 8245406,
"author_profile": "https://Stackoverflow.com/users/8245406",
"pm_score": 0,
"selected": false,
"text": "ggplot"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17975485/"
] |
74,426,583 | <p>Is there any way to find which table was recently modified (in terms of data) in SQL Server? For example, I am dealing with a badly written code which is very hard to debug, and in order to be able to find what is going on, I would like to create a record via that system and then query what has been changed in the database.</p>
<p>I came across this query</p>
<pre><code>select schema_name(schema_id) as schema_name,
name as table_name,
create_date,
modify_date
from sys.tables
where modify_date > DATEADD(DAY, -30, CURRENT_TIMESTAMP)
order by modify_date desc;
</code></pre>
<p>but it doesn't seem to give me what I need. As when I try to manually update and insert records in a table, this query still shows zero results.</p>
<p>I cannot enable the <code>CDC</code> feature on that database.</p>
| [
{
"answer_id": 74426766,
"author": "M--",
"author_id": 6461462,
"author_profile": "https://Stackoverflow.com/users/6461462",
"pm_score": 2,
"selected": false,
"text": "month"
},
{
"answer_id": 74426846,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 1,
"selected": false,
"text": "geom_line()"
},
{
"answer_id": 74427750,
"author": "Rui Barradas",
"author_id": 8245406,
"author_profile": "https://Stackoverflow.com/users/8245406",
"pm_score": 0,
"selected": false,
"text": "ggplot"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4701022/"
] |
74,426,591 | <p>I add a function that adds text to <code>FlowDocument</code> when the mouse clicks.
There is no <code>Click</code> event in <code>FlowDocument</code>, so I listen to <code>FlowDocument.MouseLeftButtonDown</code> and <code>MouseLeftButtonUp</code> and check whether the mouse moves between down and up. When I click the mouse left button, the text successfully adds. However, I can't select any text in the <code>FlowDocument</code>.</p>
<p>I tried <code>PreviewMouseLeftButtonDown</code> and <code>PreviewMouseLeftButtonUp</code>. The behavior is the same. Isn't there a <code>PostMouseLeftButtonDown</code>?</p>
<p>My Code:</p>
<pre><code> Point mouseDownPoint;
private void doc_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
mouseDownPoint = Mouse.GetPosition(doc);
e.Handled = true;
}
private void doc_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
var mouseUpPoint = Mouse.GetPosition(doc);
if ((mouseUpPoint - mouseDownPoint).Length < 8) /* add text */;
}
</code></pre>
| [
{
"answer_id": 74426766,
"author": "M--",
"author_id": 6461462,
"author_profile": "https://Stackoverflow.com/users/6461462",
"pm_score": 2,
"selected": false,
"text": "month"
},
{
"answer_id": 74426846,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 1,
"selected": false,
"text": "geom_line()"
},
{
"answer_id": 74427750,
"author": "Rui Barradas",
"author_id": 8245406,
"author_profile": "https://Stackoverflow.com/users/8245406",
"pm_score": 0,
"selected": false,
"text": "ggplot"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16660279/"
] |
74,426,642 | <p>I want to create a list like the following, based on a starting point <code>(x, y)</code>:</p>
<pre class="lang-py prettyprint-override"><code>[[0,0], [0,1], [0,2], [1,0], [1,1], [1,2], [2,0], [2,1], [2,2]]
</code></pre>
<p>My actual starting point is <code>(71, 180)</code> and</p>
<pre class="lang-py prettyprint-override"><code>x_distance = 105
y_distance = 111
</code></pre>
<p>My expected output is (6x5) format:</p>
<pre class="lang-py prettyprint-override"><code>[[71,180], [176,180], [281,180], [386,180], [491,180], [596,180],
[71,291], [176,291], [281,291], [386,291], [491,291], [596,291],
[71,402], [176,402], [281,402], [386,402], [491,402], [596,402],
[71,513], [176,513], [281,513], [386,513], [491,513], [596,513],
[71,624], [176,624], [281,624], [386,624], [491,624], [596,624]]
</code></pre>
<p>I've tried the following code:</p>
<pre class="lang-py prettyprint-override"><code>first_xy_x = 71
first_xy_y = 180
x_distance = 150
y_distance = 111
predict_xy_list = []
tem_predict_xy_list = [ ]
tem_predict_xy_list.append(first_xy_x)
tem_predict_xy_list.append(first_xy_y)
predict_xy_list.append(tem_predict_xy_list)
last_x = first_xy_x
last_y = first_xy_y
for x in range(5):
tem_predict_xy_list = [ ]
last_x = int(last_x) + int(x_distance)
for y in range(5):
tem_predict_xy_list = [ ]
last_y = int(last_y) + int(y_distance)
tem_predict_xy_list.append(last_x)
tem_predict_xy_list.append(last_y)
predict_xy_list.append(tem_predict_xy_list)
</code></pre>
<p>Output (<code>predict_xy_list</code>):</p>
<pre><code>[[71, 180], [176, 291], [176, 402], [176, 513], [176, 624], [176, 735], [281, 846], [281, 957], [281, 1068], [281, 1179], [281, 1290], [386, 1401], [386, 1512], [386, 1623], [386, 1734], [386, 1845], [491, 1956], [491, 2067], [491, 2178], [491, 2289], [491, 2400], [596, 2511], [596, 2622], [596, 2733], [596, 2844], [596, 2955], [701, 3066], [701, 3177], [701, 3288], [701, 3399], [701, 3510]]
</code></pre>
<p>I've also tried the following code:</p>
<pre class="lang-py prettyprint-override"><code>first_xy_x = 71
first_xy_y = 180
x_distance = 150
y_distance = 111
predict_xy_list = []
tem_predict_xy_list = [ ]
tem_predict_xy_list.append(first_xy_x)
tem_predict_xy_list.append(first_xy_y)
predict_xy_list.append(tem_predict_xy_list)
last_x = first_xy_x
last_y = first_xy_y
tem_predict_xy_list = [ ]
for y in range(4):
tem_predict_xy_list = [ ]
last_y = int(last_y) + int(y_distance)
tem_predict_xy_list.append(first_xy_x)
tem_predict_xy_list.append(last_y)
predict_xy_list.append(tem_predict_xy_list)
print(predict_xy_list)
print(len(predict_xy_list))
print("= = = = = ")
for x in range(5):
tem_predict_xy_list = [ ]
last_x = int(last_x) + int(x_distance)
last_y = first_xy_y
for y in range(5):
tem_predict_xy_list = [ ]
last_y = int(last_y) + int(y_distance)
tem_predict_xy_list.append(last_x)
tem_predict_xy_list.append(last_y)
predict_xy_list.append(tem_predict_xy_list)
print(predict_xy_list)
print(len(predict_xy_list))
</code></pre>
<p>The output is close, but the y-maximum is 624 and not 735 as expected:</p>
<pre class="lang-py prettyprint-override"><code>[[71, 180], [71, 291], [71, 402], [71, 513], [71, 624], [221, 291], [221, 402], [221, 513], [221, 624], [221, 735], [371, 291], [371, 402], [371, 513], [371, 624], [371, 735], [521, 291], [521, 402], [521, 513], [521, 624], [521, 735], [671, 291], [671, 402], [671, 513], [671, 624], [671, 735], [821, 291], [821, 402], [821, 513], [821, 624], [821, 735]]
</code></pre>
| [
{
"answer_id": 74427819,
"author": "DC con",
"author_id": 20396381,
"author_profile": "https://Stackoverflow.com/users/20396381",
"pm_score": 1,
"selected": false,
"text": "first_xy_x = 71\nfirst_xy_y = 180\n\nx_distance = 150\ny_distance = 111\n\npredict_xy_list = []\ntem_predict_xy_list = [ ] \n\ntem_predict_xy_list.append(first_xy_x)\ntem_predict_xy_list.append(first_xy_y)\npredict_xy_list.append(tem_predict_xy_list)\n\nlast_x = first_xy_x\nlast_y = first_xy_y\n\ntem_predict_xy_list = [ ] \nfor y in range(4):\n tem_predict_xy_list = [ ] \n last_y = int(last_y) + int(y_distance)\n tem_predict_xy_list.append(first_xy_x)\n tem_predict_xy_list.append(last_y)\n predict_xy_list.append(tem_predict_xy_list)\n\nfor x in range(5):\n tem_predict_xy_list = [ ] \n last_x = int(last_x) + int(x_distance)\n tem_predict_xy_list.append(last_x)\n tem_predict_xy_list.append(first_xy_y)\n predict_xy_list.append(tem_predict_xy_list)\n\nprint(predict_xy_list)\nprint(len(predict_xy_list))\nprint(\"= = = = = \")\n\nfor x in range(5):\n tem_predict_xy_list = [ ] \n last_x = int(last_x) + int(x_distance)\n last_y = first_xy_y\n for y in range(4):\n tem_predict_xy_list = [ ] \n last_y = int(last_y) + int(y_distance)\n tem_predict_xy_list.append(last_x)\n tem_predict_xy_list.append(last_y)\n predict_xy_list.append(tem_predict_xy_list)\n\nprint(predict_xy_list)\nprint(len(predict_xy_list))\n\nsorted_predict_xy_list = (sorted(predict_xy_list , key=lambda k: [k[1], k[0]]))\nprint(sorted_predict_xy_list) \n"
},
{
"answer_id": 74429881,
"author": "Timus",
"author_id": 14311263,
"author_profile": "https://Stackoverflow.com/users/14311263",
"pm_score": 2,
"selected": false,
"text": "range"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20384021/"
] |
74,426,647 | <p>I'm relatively new to Typescript and though I think I understand most of it, what I don't understand is why I can't use standard JS methods on values that have a type of Cypress.Chainable.</p>
<p>For instance:</p>
<pre><code>const chainedString: Cypress.Chainable<string> = cy.wrap(" test ")
const trimmed = chainedString.trim()
</code></pre>
<p>Throws an error like so: <code>Property 'trim' does not exist on type 'Chainable<string>'</code></p>
<p>How would one work with returned, chainable values and use JS methods on them without erring out on typing?</p>
<p>Searching online did not prove very helpful - limited resources for Typescript projects in Cypress</p>
<p>More below...</p>
<p>This is the custom command. Below it is the type definitions</p>
<pre><code>Cypress.Commands.add('checkText', (XpathSelector, options?: CheckTextType ) => {
return cy.xpath(XpathSelector).invoke('text').then(text=>{
text = text.trim() // remove trailing whitespace
if(options!=undefined){
// if options has values provided, run checks
if(options.matchCase==undefined || options.matchCase==true){
//* Matching case!
try {
expect(text).to.contain(options.textToAssert)
} catch (error) {
if(options.ignoreError==false || options.ignoreError==undefined){
if(options.messageOnFail!=undefined){
throw new AssertionError(`${options.messageOnFail}. Error was \n ${error}`)
} else if(options.messageOnFail==undefined){
throw error
}
} else {
return cy.wrap(false)
}
}
} else {
//* NOT matching case!
try {
expect(Cypress._.toLower(text)).to.contain(Cypress._.toLower(options.textToAssert))
} catch (error) {
if(options.ignoreError==false || options.ignoreError==undefined){
if(options.messageOnFail!=undefined){
throw new AssertionError(`${options.messageOnFail}. Error was \n ${error}`)
} else if(options.messageOnFail==undefined){
throw error
}
} else {
return cy.wrap(false)
}
}
}
return cy.wrap(true);
}
return cy.wrap(text)
})
})
</code></pre>
<p>Here is the type definition</p>
<pre><code>export type CheckTextType = {
textToAssert:string
matchCase?:boolean
ignoreError?:boolean
messageOnFail?:string
}
declare global {
namespace Cypress {
/**
* @description Checks the asserted text against what the element has. Matching case default is *true*.
* @returns String of text from the element
* @param {String} XpathSelector The **Xpath** selector to use to grab the element in question.
* @param {String} textToAssert The string of element's text you want to assert on.
* @param {Boolean} matchCase Specify false if you want to use lowercase strings. Else, case will be matched
* @param {Boolean} ignoreError Speficy true if you want to ignore the default error thrown when command assertion fails
* @param {String} messageOnFail Input a string to include in the output if the command assertion fails
* @example cy.checkText("//div[contains(@class,'email-address')]", {textToAssert:"example@gmail.com", matchCase:false})
*/
checkText(XpathSelector:string, {textToAssert, matchCase, ignoreError, messageOnFail}?:CheckTextType):Chainable<Chainable<string> | Chainable<boolean>>
}
}
</code></pre>
| [
{
"answer_id": 74426868,
"author": "Mike G",
"author_id": 19530524,
"author_profile": "https://Stackoverflow.com/users/19530524",
"pm_score": 2,
"selected": false,
"text": "const chainedString: Cypress.Chainable<string> = cy.wrap(\" test \");\n"
},
{
"answer_id": 74466576,
"author": "Grainger",
"author_id": 20487878,
"author_profile": "https://Stackoverflow.com/users/20487878",
"pm_score": 1,
"selected": false,
"text": "@returns String of text from the element"
},
{
"answer_id": 74485361,
"author": "Austin",
"author_id": 9150977,
"author_profile": "https://Stackoverflow.com/users/9150977",
"pm_score": 0,
"selected": false,
"text": "String"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9150977/"
] |
74,426,655 | <p>I have a React native project</p>
<p>I want to display manufacture's name (brand name) above the product name like below</p>
<pre><code><View style={styles.infromationView}>
<Text>{data.manufacturers.name}</Text>
<Text>{data.product_description.name}</Text>
</View>
</code></pre>
<p><a href="https://i.stack.imgur.com/EbG20.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EbG20.png" alt="enter image description here" /></a></p>
<p>While adding the name, I am getting error as <strong>Cannot read property 'name' of undefined</strong> while getting the <strong>manufacturer / brand</strong> name table, But I am able to get the same product name from <strong>product_description</strong> table</p>
<p><a href="https://i.stack.imgur.com/NDTDB.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NDTDB.jpg" alt="enter image description here" /></a>
<a href="https://i.stack.imgur.com/VKYub.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VKYub.jpg" alt="enter image description here" /></a></p>
<blockquote>
<p><strong>Please check below for db structure...</strong></p>
</blockquote>
<p><a href="https://i.stack.imgur.com/tFAKq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tFAKq.png" alt="enter image description here" /></a></p>
<blockquote>
<p><strong>Above table data is working as expected..</strong></p>
</blockquote>
<blockquote>
<p><strong>But, when I try to get the data from this table, I am getting error</strong></p>
</blockquote>
<p><a href="https://i.stack.imgur.com/ZWddm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZWddm.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74426868,
"author": "Mike G",
"author_id": 19530524,
"author_profile": "https://Stackoverflow.com/users/19530524",
"pm_score": 2,
"selected": false,
"text": "const chainedString: Cypress.Chainable<string> = cy.wrap(\" test \");\n"
},
{
"answer_id": 74466576,
"author": "Grainger",
"author_id": 20487878,
"author_profile": "https://Stackoverflow.com/users/20487878",
"pm_score": 1,
"selected": false,
"text": "@returns String of text from the element"
},
{
"answer_id": 74485361,
"author": "Austin",
"author_id": 9150977,
"author_profile": "https://Stackoverflow.com/users/9150977",
"pm_score": 0,
"selected": false,
"text": "String"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3110145/"
] |
74,426,674 | <p>If I have a switch statement that handles all enum cases explicitly, is the compiler allowed to optimise away the default case statement?</p>
<pre><code>enum MyEnum {
ZERO = 0,
ONE = 1,
TWO = 2,
THREE = 3,
};
bool foo(MyEnum e) {
switch(e) {
case ZERO:
case ONE:
case TWO:
case THREE:
return true;
default: // Could a compiler optimise this away?
return false;
}
}
</code></pre>
<p><a href="https://en.cppreference.com/w/cpp/language/enum" rel="nofollow noreferrer">Cpp Reference</a> says regarding enums (emphasis mine):</p>
<blockquote>
<p>Values of integer, floating-point, and enumeration types can be converted by static_cast or explicit cast, to any enumeration type. <strong>If the underlying type is not fixed and the source value is out of range, the behavior is undefined</strong>. (The source value, as converted to the enumeration's underlying type if floating-point, is in range if it would fit in the smallest bit field large enough to hold all enumerators of the target enumeration.) Otherwise, the result is the same as the result of implicit conversion to the underlying type.</p>
<p>Note that the value after such conversion may not necessarily equal any of the named enumerators defined for the enumeration.</p>
</blockquote>
<p>Which indicates it would be allowed to optimise out the default statement in the above example since the underlying type is not fixed and every 2-bit value is specified (though maybe you would need to include negative values to -4).</p>
<p>However, it is not clear if this also applies to fixed type enums or enum classes.</p>
<hr />
<p>In practice, GCC, clang, and MSVC do <em>not</em> assume that the enum is one of the defined values. (<a href="https://godbolt.org/#z:OYLghAFBqd5QCxAYwPYBMCmBRdBLAF1QCcAaPECAMzwBtMA7AQwFtMQByARg9KtQYEAysib0QXACx8BBAKoBnTAAUAHpwAMvAFYTStJg1DIApACYAQuYukl9ZATwDKjdAGFUtAK4sGe1wAyeAyYAHI%2BAEaYxBIAnKQADqgKhE4MHt6%2BekkpjgJBIeEsUTFc8XaYDmlCBEzEBBk%2Bfly2mPZ5DDV1BAVhkdF6CrX1jVktQ929RSUSAJS2qF7EyOwcjD4A1ACyAJ7YDJsmAOxWGgCCGwBa2ABKAPIbJgDMACIbGqQm5xt3odiPrw2LS%2BFwAKgB1B7PN5mT7fUEACRu2H%2B0I2TzhZ2OL2epyx5wiqE8G34qAgu32m0ws0eJxBGwUAHdCMgEBBqbS8RtREorrc7iB6TzMD8/oLvsKNhCBUKmLzEcjsOKLhtiJgCEsGBsCMQvJhcfSsFQmF5aAQQBsAPSWjYeU3obUIEVoFgJOjRDaoBKOFh4XkEBB%2BjZMRlMHbPABi9NV6s1JLESgN32xIJT5w481onAArLw/BwtKRUJw3NZrAzFssReYnjxSOaCxn5gBrEBPSQAOiOsSOkgAbLEyhonrENFI%2B/pOJI85peMWOLwFCAPg2tPM4LAYIgUKhXe6yBQIC63fQYsgDEYuNmNB8sAA3PArABqeEwjLuCUYnDrNDN0SXEARLOpARMEdQ7N%2BvAumwgh3AwtAQY2pBYCwhjAOISH4GqVR3pgS5IZgqiVF4BCrHWwSkVmSG0HgETEOBHhYMBOp4CwkHzFQBjAAoL5vh%2BX7cLw/CCCIYjsFIMiCIoKjqEhugtBexhlpY%2Bi0UukDzF6HT4QAtHcTwbDp4JiLQhlDOg0KmJY1hmIWFRVM47IMO4nhNP4zlTP0pSJMkqQCKMzQ%2BbkaSecUAzjG0lQdF0IyuWMrTtNUww9MEfRhd5EyxZkgWZSlhReXMCxLCshVUbmpD5oW84bKoAAcfY6X2kjcopQLZh2GgdRsEC4IQJCPGYtazLwq5NqQra1h29WDj2khHH2ZjzdmZgTlR06kGx14VcB86Lsu9azuuW4QEgx77uQlBnaeIB3sgCQJAA%2BneZQPU8TwPaoTXIZgD7Pq%2B76fvmP50KRxAAUBSGgcwxCIXW0GMAQcEIcBKFoRhhZYVFeC4fhhaEcRpGQeQghtMBNF0QxGCrIWLFsYJHFcTx/38UDQmyKJ4gScJ8hKGowG6BiikoMpNjk%2BpECad6aS6XcZhWuZwvWZYtmLpFDl%2BE5LnZe56ChTMLQ5H56RxYFhsdHr4UJVjAgxQ0JuDGr0XJRbGXJQFgzO6l0zhfMCiViVXCZjmM5IdVn3NSwCi3Rsz2xB2b3db1RDEANQ0jYd8xOkwWAxBLk4cOtm0fJVc6cHtK4Z%2BNbZcFNA5lL282LX2y2rZwTwh1VZcHY2R3wCdO57qeF1HruJ4DHULBNcAXBmLZ32/ZgvEAwJwN/mDlAQ4WUPgUT8OwfBiEY5gqFGOjvCYzheHAfjyAkWRvAUaT1G0fRMOMdTI3EKx7F8IzS8s0TbmHNxLSG5tJPmckQCwiFlZKwKkxbwEltpTgekDJGRMmZAgFlXiwJsnZR2aQXDOXdi0QIXsCoG18h0EhQUjYuwdolG2bt7YRUYZ0T2%2BV0oe26DQ3K9DA5FSrKVYO21Q6cA2GcG4WwmobGAMgZAQIzAdiURoRO%2BBk6p0DunHuLY2xPHjm9QxRijH53WiXIsXclwVx0fnMwHdS4Lm7mueYuEwaEMkEAA" rel="nofollow noreferrer">Godbolt</a> with full optimization enabled like <code>-O3 -std=c++20</code>.)</p>
<p>Is that a missed optimization, or is the standard saying that if the implementation picks <code>int</code> as the underlying type (even though you didn't specify) then any <code>int</code> value is legal?</p>
<p>CppReference shows an example under the paragraph quoted:</p>
<pre><code>enum access_t { read = 1, write = 2, exec = 4 };
// enumerators: 1, 2, 4 range: 0..7
access_t y = static_cast<access_t>(8); // undefined behavior since CWG1766
</code></pre>
<p>That makes it clear that "range" is tied to the named enumerator values, not the full width of any integer type. Assuming that cppreference example is an accurate reflection of the ISO standard, of course, that implies that explicit or implicit conversion can't legally produce an <code>enum</code> object with a value that isn't accounted for.</p>
| [
{
"answer_id": 74436138,
"author": "user17732522",
"author_id": 17732522,
"author_profile": "https://Stackoverflow.com/users/17732522",
"pm_score": 3,
"selected": true,
"text": "default"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10638233/"
] |
74,426,737 | <p>I having an requirement from business users and need your help.</p>
<p>From the screenshot, we have BatchNo column, for example the BatchNo HL18002040, business users want to merge Loading Dates into 1 row if they have same BatchNo and then summerizing NetWeight Shipped togother as the Expecting result. I have tried a lot with DAX language but cannot solve the issue.</p>
<p>Please help.</p>
<p>Thank you in advance.</p>
<p><a href="https://i.stack.imgur.com/qKY4W.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qKY4W.png" alt="enter image description here" /></a></p>
<p>The model
<a href="https://i.stack.imgur.com/Aw73k.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Aw73k.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74428261,
"author": "Marcus",
"author_id": 16528000,
"author_profile": "https://Stackoverflow.com/users/16528000",
"pm_score": 2,
"selected": true,
"text": "Loading Date"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14142514/"
] |
74,426,744 | <p>I have an array of word(s), it can contain one word or more. In case of one word, it's easy to remove it, but when choose to remove multiple words if they are all in the stop words list is difficult for me to figure it out. I prefer solving it with LINQ.</p>
<p>Imagin, I have this array of strings</p>
<pre><code>then use
then he
the image
and the
should be in
should be written
</code></pre>
<p>I want to get only</p>
<pre><code>then use
the image
should be written
</code></pre>
<p>So, the lines that <strong>all it words</strong> are in the stop words should be removed, while keep the lines that has mixed words.</p>
<p>My stop words array
<code> string[] stopWords = {"a", "an", "x", "y", "z", "this", "the", "me", "you", "our", "we", "I", "them", "then", "ours", "more", "will", "he", "she", "should", "be", "at", "on", "in", "has", "have", "and"};</code></p>
<p>Thank you,</p>
| [
{
"answer_id": 74426928,
"author": "Rezaeimh7",
"author_id": 5516527,
"author_profile": "https://Stackoverflow.com/users/5516527",
"pm_score": 2,
"selected": false,
"text": " foreach (string word in WordsList)\n {\n List<string> splitData = word.Split(new string[] { \" \"}, StringSplitOptions.RemoveEmptyEntries).ToList();\n bool allOfWordsIsInStopWords = splitData.Intersect(stopWords).Count() == splitData.Count();\n }\n"
},
{
"answer_id": 74426938,
"author": "Jorge Zapata",
"author_id": 8653215,
"author_profile": "https://Stackoverflow.com/users/8653215",
"pm_score": 0,
"selected": false,
"text": "using System.Text.RegularExpressions;\n\nstring[] stopWords = { \"a\", \"an\", \"x\", \"y\", \"z\", \"this\", \"the\", \"me\", \"you\", \"our\", \"we\", \"I\", \"them\", \"ours\", \"more\", \"will\", \"he\", \"she\", \"should\", \"be\", \"at\", \"on\", \"in\", \"has\", \"have\", \"and\" };\n\nstring[] inputStrings = { \"then use\", \"then he\", \"the image\", \"and the\", \"should be in\", \"should be written\" };\n\nvar wordSeparatorPattern = new Regex(@\"\\s+\");\n\nvar outputStrings = inputStrings.Where((words) => \n{\n return wordSeparatorPattern.Split(words).Any((word) =>\n {\n return !stopWords.Contains(word);\n });\n});\n\n\nforeach (var item in outputStrings)\n{\n Console.WriteLine(item);\n}\n"
},
{
"answer_id": 74426951,
"author": "R J",
"author_id": 8356484,
"author_profile": "https://Stackoverflow.com/users/8356484",
"pm_score": 3,
"selected": true,
"text": "string[] stopWords = { \"a\", \"an\", \"x\", \"y\", \"z\", \"this\", \"the\", \"me\", \"you\", \"our\", \"we\", \"I\", \"them\", \"ours\", \"more\", \"will\", \"he\", \"she\", \"should\", \"be\", \"at\", \"on\", \"in\", \"has\", \"have\", \"and\" };\n\nstring input = \"\"\"\"\n then use \n then he\n the image\n and the\n should be in\n should be written\n \"\"\"\";\n\nvar array = input.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);\n\nvar filteredArray = array.Where(x => x.Split(' ').Any(y => !stopWords.Contains(y))).ToList();\nvar result = string.Join(Environment.NewLine, filteredArray);\n\nConsole.WriteLine(result);\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7662223/"
] |
74,426,763 | <p>I am currently building an app that has a first page with two buttons: 'New users -->" and "Existing users -->". The goal is for new users to click their button and go through a setup process that ends with their home page that is saved when the app is closed. The next time a user opens the app, once they click their existing users button, I want the app to open to the home page the setup process ends at. How do I achieving this? Any help would be appreciated!</p>
| [
{
"answer_id": 74426928,
"author": "Rezaeimh7",
"author_id": 5516527,
"author_profile": "https://Stackoverflow.com/users/5516527",
"pm_score": 2,
"selected": false,
"text": " foreach (string word in WordsList)\n {\n List<string> splitData = word.Split(new string[] { \" \"}, StringSplitOptions.RemoveEmptyEntries).ToList();\n bool allOfWordsIsInStopWords = splitData.Intersect(stopWords).Count() == splitData.Count();\n }\n"
},
{
"answer_id": 74426938,
"author": "Jorge Zapata",
"author_id": 8653215,
"author_profile": "https://Stackoverflow.com/users/8653215",
"pm_score": 0,
"selected": false,
"text": "using System.Text.RegularExpressions;\n\nstring[] stopWords = { \"a\", \"an\", \"x\", \"y\", \"z\", \"this\", \"the\", \"me\", \"you\", \"our\", \"we\", \"I\", \"them\", \"ours\", \"more\", \"will\", \"he\", \"she\", \"should\", \"be\", \"at\", \"on\", \"in\", \"has\", \"have\", \"and\" };\n\nstring[] inputStrings = { \"then use\", \"then he\", \"the image\", \"and the\", \"should be in\", \"should be written\" };\n\nvar wordSeparatorPattern = new Regex(@\"\\s+\");\n\nvar outputStrings = inputStrings.Where((words) => \n{\n return wordSeparatorPattern.Split(words).Any((word) =>\n {\n return !stopWords.Contains(word);\n });\n});\n\n\nforeach (var item in outputStrings)\n{\n Console.WriteLine(item);\n}\n"
},
{
"answer_id": 74426951,
"author": "R J",
"author_id": 8356484,
"author_profile": "https://Stackoverflow.com/users/8356484",
"pm_score": 3,
"selected": true,
"text": "string[] stopWords = { \"a\", \"an\", \"x\", \"y\", \"z\", \"this\", \"the\", \"me\", \"you\", \"our\", \"we\", \"I\", \"them\", \"ours\", \"more\", \"will\", \"he\", \"she\", \"should\", \"be\", \"at\", \"on\", \"in\", \"has\", \"have\", \"and\" };\n\nstring input = \"\"\"\"\n then use \n then he\n the image\n and the\n should be in\n should be written\n \"\"\"\";\n\nvar array = input.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);\n\nvar filteredArray = array.Where(x => x.Split(' ').Any(y => !stopWords.Contains(y))).ToList();\nvar result = string.Join(Environment.NewLine, filteredArray);\n\nConsole.WriteLine(result);\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20199452/"
] |
74,426,782 | <p>All I want in life is this grid of squares to be in the center of the page on both axes and it's driving me nuts. It is centered on the x-axis, but I cannot for the life of me figure out how to center it along the y-axis. How can I do this while still maintaining responsiveness? You will see that I created a div called margin-help to try to get it to work but to no avail. Here is a link to the codepen, the code itself, as well as a screenshot of what I'm dealing with. All help is very much appreciated. Thanks! <a href="https://codepen.io/Brianna-Drew/pen/WNyOoWJ" rel="nofollow noreferrer">https://codepen.io/Brianna-Drew/pen/WNyOoWJ</a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>@font-face {
font-family: This Is The Future;
src: url(fonts/This\ Is\ The\ Future.ttf);
}
html,
body {
min-height: 100%;
}
body {
margin: 0;
text-align: center;
background-color: black;
font-family: This Is The Future;
display: block;
height: 100vh;
padding-top: auto;
padding-bottom: auto;
}
.margin-help {
display: flex;
margin: auto;
}
.grid {
display: grid;
margin: auto;
grid-template-columns: auto auto auto auto;
grid-template-rows: auto auto auto auto;
justify-content: center;
align-content: center;
gap: 10px;
}
.squares {
display: flex;
background-color: white;
max-width: 100px;
width: 15vw;
max-height: 100px;
height: 15vw;
align-items: center;
justify-content: center;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><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>SENSUS</title>
<link href="styles.css" rel="stylesheet" />
</head>
<body>
<div class="margin-help">
<div class="grid">
<div class="squares" id="a1"></div>
<div class="squares" id="b1"></div>
<div class="squares" id="c1"></div>
<div class="squares" id="d1"></div>
<div class="squares" id="a2"></div>
<div class="squares" id="b2"></div>
<div class="squares" id="c2"></div>
<div class="squares" id="d2"></div>
<div class="squares" id="a3"></div>
<div class="squares" id="b3"></div>
<div class="squares" id="c3"></div>
<div class="squares" id="d3"></div>
<div class="squares" id="a4"></div>
<div class="squares" id="b4"></div>
<div class="squares" id="c4"></div>
<div class="squares" id="d4"></div>
</div>
</div>
<script src="script.js"></script>
</body>
</html></code></pre>
</div>
</div>
</p>
<p><a href="https://i.stack.imgur.com/CLRJx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CLRJx.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74426928,
"author": "Rezaeimh7",
"author_id": 5516527,
"author_profile": "https://Stackoverflow.com/users/5516527",
"pm_score": 2,
"selected": false,
"text": " foreach (string word in WordsList)\n {\n List<string> splitData = word.Split(new string[] { \" \"}, StringSplitOptions.RemoveEmptyEntries).ToList();\n bool allOfWordsIsInStopWords = splitData.Intersect(stopWords).Count() == splitData.Count();\n }\n"
},
{
"answer_id": 74426938,
"author": "Jorge Zapata",
"author_id": 8653215,
"author_profile": "https://Stackoverflow.com/users/8653215",
"pm_score": 0,
"selected": false,
"text": "using System.Text.RegularExpressions;\n\nstring[] stopWords = { \"a\", \"an\", \"x\", \"y\", \"z\", \"this\", \"the\", \"me\", \"you\", \"our\", \"we\", \"I\", \"them\", \"ours\", \"more\", \"will\", \"he\", \"she\", \"should\", \"be\", \"at\", \"on\", \"in\", \"has\", \"have\", \"and\" };\n\nstring[] inputStrings = { \"then use\", \"then he\", \"the image\", \"and the\", \"should be in\", \"should be written\" };\n\nvar wordSeparatorPattern = new Regex(@\"\\s+\");\n\nvar outputStrings = inputStrings.Where((words) => \n{\n return wordSeparatorPattern.Split(words).Any((word) =>\n {\n return !stopWords.Contains(word);\n });\n});\n\n\nforeach (var item in outputStrings)\n{\n Console.WriteLine(item);\n}\n"
},
{
"answer_id": 74426951,
"author": "R J",
"author_id": 8356484,
"author_profile": "https://Stackoverflow.com/users/8356484",
"pm_score": 3,
"selected": true,
"text": "string[] stopWords = { \"a\", \"an\", \"x\", \"y\", \"z\", \"this\", \"the\", \"me\", \"you\", \"our\", \"we\", \"I\", \"them\", \"ours\", \"more\", \"will\", \"he\", \"she\", \"should\", \"be\", \"at\", \"on\", \"in\", \"has\", \"have\", \"and\" };\n\nstring input = \"\"\"\"\n then use \n then he\n the image\n and the\n should be in\n should be written\n \"\"\"\";\n\nvar array = input.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);\n\nvar filteredArray = array.Where(x => x.Split(' ').Any(y => !stopWords.Contains(y))).ToList();\nvar result = string.Join(Environment.NewLine, filteredArray);\n\nConsole.WriteLine(result);\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10968586/"
] |
74,426,831 | <p>Looking assistance in PL/SQL query.</p>
<p>Business Case:<br />
Extract previous 2 days of data from DATE column excluding weekends.</p>
<pre><code>select * from holddbo.pos where eff_date = '15-NOV-2022'
</code></pre>
<ol>
<li>on 15-11-2022, I'm looking data for 14-11 and 11-11 [exclude weekend]</li>
<li>on 14-11-2022, I'm looking data for 11-11 and 10-11 [exclude weekend]</li>
<li>on 11-11-2022, I'm looking data for 10-11 and 09-11 [exclude weekend]</li>
</ol>
| [
{
"answer_id": 74426928,
"author": "Rezaeimh7",
"author_id": 5516527,
"author_profile": "https://Stackoverflow.com/users/5516527",
"pm_score": 2,
"selected": false,
"text": " foreach (string word in WordsList)\n {\n List<string> splitData = word.Split(new string[] { \" \"}, StringSplitOptions.RemoveEmptyEntries).ToList();\n bool allOfWordsIsInStopWords = splitData.Intersect(stopWords).Count() == splitData.Count();\n }\n"
},
{
"answer_id": 74426938,
"author": "Jorge Zapata",
"author_id": 8653215,
"author_profile": "https://Stackoverflow.com/users/8653215",
"pm_score": 0,
"selected": false,
"text": "using System.Text.RegularExpressions;\n\nstring[] stopWords = { \"a\", \"an\", \"x\", \"y\", \"z\", \"this\", \"the\", \"me\", \"you\", \"our\", \"we\", \"I\", \"them\", \"ours\", \"more\", \"will\", \"he\", \"she\", \"should\", \"be\", \"at\", \"on\", \"in\", \"has\", \"have\", \"and\" };\n\nstring[] inputStrings = { \"then use\", \"then he\", \"the image\", \"and the\", \"should be in\", \"should be written\" };\n\nvar wordSeparatorPattern = new Regex(@\"\\s+\");\n\nvar outputStrings = inputStrings.Where((words) => \n{\n return wordSeparatorPattern.Split(words).Any((word) =>\n {\n return !stopWords.Contains(word);\n });\n});\n\n\nforeach (var item in outputStrings)\n{\n Console.WriteLine(item);\n}\n"
},
{
"answer_id": 74426951,
"author": "R J",
"author_id": 8356484,
"author_profile": "https://Stackoverflow.com/users/8356484",
"pm_score": 3,
"selected": true,
"text": "string[] stopWords = { \"a\", \"an\", \"x\", \"y\", \"z\", \"this\", \"the\", \"me\", \"you\", \"our\", \"we\", \"I\", \"them\", \"ours\", \"more\", \"will\", \"he\", \"she\", \"should\", \"be\", \"at\", \"on\", \"in\", \"has\", \"have\", \"and\" };\n\nstring input = \"\"\"\"\n then use \n then he\n the image\n and the\n should be in\n should be written\n \"\"\"\";\n\nvar array = input.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);\n\nvar filteredArray = array.Where(x => x.Split(' ').Any(y => !stopWords.Contains(y))).ToList();\nvar result = string.Join(Environment.NewLine, filteredArray);\n\nConsole.WriteLine(result);\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12830411/"
] |
74,426,882 | <p>I am writing some integration tests in which I need to send in an api call to create a resource and then perform subsequent api calls based on that resource. I wanted to send the first call inside my @BeforeAll method.</p>
<p>In my test class:</p>
<pre><code>@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("test")
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class ExampleResourceTest {
@Autowired
private MockMvc mockMvc;
@BeforeAll
private void createExampleResource() throws Exception {
Map<String, Object> requestBody = new HashMap<>();
requestBody.put("email", "example@email.com");
requestBody.put("username", "example");
requestBody.put("firstName", "Example");
requestBody.put("lastName", "Name");
requestBody.put("password", "@password123");
Gson gson = new Gson();
String json = gson.toJson(requestBody);
mockMvc.perform(
post("/api/v1/resourcename")
.contentType(MediaType.APPLICATION_JSON)
.content(json));
}
// More stuff...
}
</code></pre>
<p>However, the method annotated @BeforeAll method is not being called before I run the tests in the class.</p>
<p>As I understand from trying to find a solution, @BeforeAll methods need to be static. However, then I wouldn't be able to use my injected MockMvc. I've also tried annotating my test class with
<code>@TestInstance(TestInstance.Lifecycle.PER_CLASS)</code>, but I've faced no luck with that either.</p>
| [
{
"answer_id": 74426928,
"author": "Rezaeimh7",
"author_id": 5516527,
"author_profile": "https://Stackoverflow.com/users/5516527",
"pm_score": 2,
"selected": false,
"text": " foreach (string word in WordsList)\n {\n List<string> splitData = word.Split(new string[] { \" \"}, StringSplitOptions.RemoveEmptyEntries).ToList();\n bool allOfWordsIsInStopWords = splitData.Intersect(stopWords).Count() == splitData.Count();\n }\n"
},
{
"answer_id": 74426938,
"author": "Jorge Zapata",
"author_id": 8653215,
"author_profile": "https://Stackoverflow.com/users/8653215",
"pm_score": 0,
"selected": false,
"text": "using System.Text.RegularExpressions;\n\nstring[] stopWords = { \"a\", \"an\", \"x\", \"y\", \"z\", \"this\", \"the\", \"me\", \"you\", \"our\", \"we\", \"I\", \"them\", \"ours\", \"more\", \"will\", \"he\", \"she\", \"should\", \"be\", \"at\", \"on\", \"in\", \"has\", \"have\", \"and\" };\n\nstring[] inputStrings = { \"then use\", \"then he\", \"the image\", \"and the\", \"should be in\", \"should be written\" };\n\nvar wordSeparatorPattern = new Regex(@\"\\s+\");\n\nvar outputStrings = inputStrings.Where((words) => \n{\n return wordSeparatorPattern.Split(words).Any((word) =>\n {\n return !stopWords.Contains(word);\n });\n});\n\n\nforeach (var item in outputStrings)\n{\n Console.WriteLine(item);\n}\n"
},
{
"answer_id": 74426951,
"author": "R J",
"author_id": 8356484,
"author_profile": "https://Stackoverflow.com/users/8356484",
"pm_score": 3,
"selected": true,
"text": "string[] stopWords = { \"a\", \"an\", \"x\", \"y\", \"z\", \"this\", \"the\", \"me\", \"you\", \"our\", \"we\", \"I\", \"them\", \"ours\", \"more\", \"will\", \"he\", \"she\", \"should\", \"be\", \"at\", \"on\", \"in\", \"has\", \"have\", \"and\" };\n\nstring input = \"\"\"\"\n then use \n then he\n the image\n and the\n should be in\n should be written\n \"\"\"\";\n\nvar array = input.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);\n\nvar filteredArray = array.Where(x => x.Split(' ').Any(y => !stopWords.Contains(y))).ToList();\nvar result = string.Join(Environment.NewLine, filteredArray);\n\nConsole.WriteLine(result);\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16050570/"
] |
74,426,885 | <p>I have a web scrapped string containing key value pairs i.e <code>firstName:"Quaran", lastName:"McPherson"</code></p>
<pre><code>st = '{"accountId":405266,"firstName":"Quaran","lastName":"McPherson","accountIdentifier":"StudentAthlete","profilePicUrl":"https://pbs.twimg.com/profile_images/1331475329014181888/4z19KrCf.jpg","networkProfileCode":"quaran-mcpherson","hasDeals":true,"activityMin":11,"sports":["Men\'s Basketball","Basketball"],"currentTeams":["Nebraska Cornhuskers"],"previousTeams":[],"facebookReach":null,"twitterReach":619,"instagramReach":0,"linkedInReach":null},{"accountId":375964,"firstName":"Micole","lastName":"Cayton","accountIdentifier":"StudentAthlete","profilePicUrl":"https://opendorsepr.blob.core.windows.net/media/375964/20220622223838_46dbe3fd-a683-436b-84d4-90c84a5af35f.jpg","networkProfileCode":"micole-cayton","hasDeals":true,"activityMin":16,"sports":["Basketball","Women\'s Basketball"],"currentTeams":["Minnesota Golden Gophers"],"previousTeams":["Cal Berkeley Golden Bears"],"facebookReach":0,"twitterReach":1273,"instagramReach":5700,"linkedInReach":null}'
</code></pre>
<p>I am trying to extract the first_name, last_name and a few other parameters from this string in list format such that I will be having a first_name list with all first_names from the string</p>
<p>I tried using <code>re.findall('"firstName":'"(.*)\S$",st)</code> to access the text <code>"Quaran"</code> but result is coming in the following format</p>
<p><code>'"Quaran","lastName":"McPherson","accountIdentifier":"StudentAthlete","profilePicUrl":"https://pbs.twimg.com/profile_images/1331475329014181888/4z19KrCf.jpg","networkProfileCode":"quaran-mcpherson","hasDeals":true,"activityMin":11,"sports":["Men\'s Basketball","Basketball"],"currentTeams":["Nebraska Cornhuskers"],"previousTeams":[],"facebookReach":null,"twitterReach":619,"instagramReach":0,"linkedInReach":null}</code></p>
<p>how do I end the specify within the regex to end the search at the end of the name in quotes??</p>
<p>TIA</p>
| [
{
"answer_id": 74426928,
"author": "Rezaeimh7",
"author_id": 5516527,
"author_profile": "https://Stackoverflow.com/users/5516527",
"pm_score": 2,
"selected": false,
"text": " foreach (string word in WordsList)\n {\n List<string> splitData = word.Split(new string[] { \" \"}, StringSplitOptions.RemoveEmptyEntries).ToList();\n bool allOfWordsIsInStopWords = splitData.Intersect(stopWords).Count() == splitData.Count();\n }\n"
},
{
"answer_id": 74426938,
"author": "Jorge Zapata",
"author_id": 8653215,
"author_profile": "https://Stackoverflow.com/users/8653215",
"pm_score": 0,
"selected": false,
"text": "using System.Text.RegularExpressions;\n\nstring[] stopWords = { \"a\", \"an\", \"x\", \"y\", \"z\", \"this\", \"the\", \"me\", \"you\", \"our\", \"we\", \"I\", \"them\", \"ours\", \"more\", \"will\", \"he\", \"she\", \"should\", \"be\", \"at\", \"on\", \"in\", \"has\", \"have\", \"and\" };\n\nstring[] inputStrings = { \"then use\", \"then he\", \"the image\", \"and the\", \"should be in\", \"should be written\" };\n\nvar wordSeparatorPattern = new Regex(@\"\\s+\");\n\nvar outputStrings = inputStrings.Where((words) => \n{\n return wordSeparatorPattern.Split(words).Any((word) =>\n {\n return !stopWords.Contains(word);\n });\n});\n\n\nforeach (var item in outputStrings)\n{\n Console.WriteLine(item);\n}\n"
},
{
"answer_id": 74426951,
"author": "R J",
"author_id": 8356484,
"author_profile": "https://Stackoverflow.com/users/8356484",
"pm_score": 3,
"selected": true,
"text": "string[] stopWords = { \"a\", \"an\", \"x\", \"y\", \"z\", \"this\", \"the\", \"me\", \"you\", \"our\", \"we\", \"I\", \"them\", \"ours\", \"more\", \"will\", \"he\", \"she\", \"should\", \"be\", \"at\", \"on\", \"in\", \"has\", \"have\", \"and\" };\n\nstring input = \"\"\"\"\n then use \n then he\n the image\n and the\n should be in\n should be written\n \"\"\"\";\n\nvar array = input.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);\n\nvar filteredArray = array.Where(x => x.Split(' ').Any(y => !stopWords.Contains(y))).ToList();\nvar result = string.Join(Environment.NewLine, filteredArray);\n\nConsole.WriteLine(result);\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20497123/"
] |
74,426,898 | <p>I have an XML file like the following.</p>
<pre><code><paper>
<Question_01>
<QNo>1a</QNo>
<Question>What is Semantic Web? </Question>
</Question_01>
<Question_01>
<QNo>1b</QNo>
<Question>“Web 2.0 applications can be used to increase the profit of a business“ Discuss.</Question>
</Question_01>
<Question_01>
<QNo>1c</QNo>
<Question>Discuss the advantage of the Extensible Markup Language.</Question>
</Question_01>
</paper>
</code></pre>
<p>I want to select questions that start from 'W', as the QNo - 1a and 1b should be the output XSLT. So that I wrote the following code in XSL.</p>
<pre><code><xsl:for-each select = "paper/Question_01">
<xsl:if test = "starts-with(Question, 'W')">
<li>
<xsl:value-of select = "Question"/>
</li>
</xsl:if>
</xsl:for-each>
</code></pre>
<p>But it selects only the QNo - 1a. How can I write the XSL code as it selects both QNo - 1a and 1b and also as if the relevant sentence can start with several special characters and whitespace following 'W'? Thank you.</p>
| [
{
"answer_id": 74427368,
"author": "zx485",
"author_id": 1305969,
"author_profile": "https://Stackoverflow.com/users/1305969",
"pm_score": 2,
"selected": true,
"text": "translate"
},
{
"answer_id": 74429527,
"author": "Abhay Kumar Gupta",
"author_id": 19307998,
"author_profile": "https://Stackoverflow.com/users/19307998",
"pm_score": -1,
"selected": false,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"\n xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n exclude-result-prefixes=\"xs\"\n version=\"2.0\">\n <xsl:output indent=\"yes\"/>\n <xsl:template match=\"/\">\n <xsl:for-each select = \"paper/Question_01\">\n <xsl:if test = \"starts-with(normalize-space(translate(Question,'“','')), 'W')\">\n <li>\n <xsl:value-of select = \"Question\"/>\n </li>\n </xsl:if> \n </xsl:for-each>\n </xsl:template>\n</xsl:stylesheet>\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17493607/"
] |
74,426,902 | <p>I'm working on Hrms application in django rest framework. I've created employee details module now next part is leave management system. Actually my company policy has different leave policies like cl,sl,ml,compo off, and permissions.I'm unable to understand how to make the logic for it and and don't know where to write the logic in serializers or views? Since a newbee i find somewhat difficult. Also when a employee apply a leave it should be requested to T.L. and then should be visible to hr and manager. T.l would give permission and it all should be in application and also in email process. How to make request and approval in rest api also how to send mail using django rest api? Can anyone guide me. If employee select Cl, he got total 12 cl and he can avail monthly once and cl can carryforward upto 3 leaves after that it will expire, then sl means quarterly 2 available, then half day leaves, what will be the logic here and how should i progress?</p>
<p>class LeaveType(models.Model):</p>
<pre><code> Leave_type = (
('CL', 'Casual Leave'),
('SL', 'Sick Leave'),
('ML', 'Medical Leave'),
('Comp Off', 'Compensation'),
('L.O.P', 'Loss of Pay')
)
Leave_Choice = (
('Full Day', 'Full Day Leave'),
('Fore Noon', 'Fore Noon Only'),
('After Noon', 'After Noon Only'),
Status_choices = (
('Approved', 'Approved'),
('Rejected', 'Rejected'),
('Pending', 'Pending'),
leave_type = models.CharField(max_length=50, choices=Leave_type)
status = models.CharField(max_length=50, choices=Status_choices, default='Pending')
leave_choice = models.CharField(max_length=50, choices=Leave_Choice, default='Full Day')
if leave_type == 'CL':
total_leave_per_year = 12
monthly_leave_applicable = 1
carry_forawrd_monthly_leave = 3
elif leave_type == 'SL':
Quarterly_days_applicable = 2
annual_leave_applicable = 8
</code></pre>
| [
{
"answer_id": 74427368,
"author": "zx485",
"author_id": 1305969,
"author_profile": "https://Stackoverflow.com/users/1305969",
"pm_score": 2,
"selected": true,
"text": "translate"
},
{
"answer_id": 74429527,
"author": "Abhay Kumar Gupta",
"author_id": 19307998,
"author_profile": "https://Stackoverflow.com/users/19307998",
"pm_score": -1,
"selected": false,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"\n xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n exclude-result-prefixes=\"xs\"\n version=\"2.0\">\n <xsl:output indent=\"yes\"/>\n <xsl:template match=\"/\">\n <xsl:for-each select = \"paper/Question_01\">\n <xsl:if test = \"starts-with(normalize-space(translate(Question,'“','')), 'W')\">\n <li>\n <xsl:value-of select = \"Question\"/>\n </li>\n </xsl:if> \n </xsl:for-each>\n </xsl:template>\n</xsl:stylesheet>\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20338785/"
] |
74,426,904 | <p>Do you guys know how to make pop up that small and appear below icon like this? I have made it with AlertDialog, but the pop up is on the center of the screen and too big.</p>
<p><a href="https://i.stack.imgur.com/dpJSf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dpJSf.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74426975,
"author": "ahmed",
"author_id": 20033412,
"author_profile": "https://Stackoverflow.com/users/20033412",
"pm_score": 0,
"selected": false,
"text": "popupmenu"
},
{
"answer_id": 74427186,
"author": "K K Muhammed Fazil",
"author_id": 11922179,
"author_profile": "https://Stackoverflow.com/users/11922179",
"pm_score": 2,
"selected": false,
"text": " void showPopUpMenuAtTap(BuildContext context, TapDownDetails details) {\n showMenu(\n context: context,\n position: RelativeRect.fromLTRB(\n details.globalPosition.dx,\n details.globalPosition.dy,\n details.globalPosition.dx,\n details.globalPosition.dy,\n ),\n items: const [\n PopupMenuItem<String>(value: '1', child: Text('menu option 1')),\n PopupMenuItem<String>(value: '2', child: Text('menu option 2')),\n PopupMenuItem<String>(value: '3', child: Text('menu option 3')),\n ],\n ).then((value) {\n if (value == null) return;\n\n if (value == \"1\") {\n //code here\n log(\"message\", name: value);\n } else if (value == \"2\") {\n //code here\n log(\"message\", name: value);\n } else if (value == \"3\") {\n //code here\n log(\"message\", name: value);\n }\n });\n }\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19875840/"
] |
74,426,908 | <p>I was doing a form using HTML and i found that when I'm using my submit button it is showing my local C drive</p>
<p>It doesn't submit my form</p>
<p>CODE:</p>
<pre><code><div class="container">
<form id="form" action="/">
<h1>Registration</h1>
<div class="input-control">
<label for="username">Username</label>
<input id="username" name="username" type="text">
<div class="error"> </div>
</div>
<div class="input-control">
<label for="username">Email</label>
<input id="email" name="username" type="text">
<div class="error"> </div>
</div>
<div class="input-control">
<label for="Message">Message </label>
<input id="Message" name="username" type="text">
<div class="error"> </div>
<button type="submit">Sign up</button>
</form>
</code></pre>
| [
{
"answer_id": 74426975,
"author": "ahmed",
"author_id": 20033412,
"author_profile": "https://Stackoverflow.com/users/20033412",
"pm_score": 0,
"selected": false,
"text": "popupmenu"
},
{
"answer_id": 74427186,
"author": "K K Muhammed Fazil",
"author_id": 11922179,
"author_profile": "https://Stackoverflow.com/users/11922179",
"pm_score": 2,
"selected": false,
"text": " void showPopUpMenuAtTap(BuildContext context, TapDownDetails details) {\n showMenu(\n context: context,\n position: RelativeRect.fromLTRB(\n details.globalPosition.dx,\n details.globalPosition.dy,\n details.globalPosition.dx,\n details.globalPosition.dy,\n ),\n items: const [\n PopupMenuItem<String>(value: '1', child: Text('menu option 1')),\n PopupMenuItem<String>(value: '2', child: Text('menu option 2')),\n PopupMenuItem<String>(value: '3', child: Text('menu option 3')),\n ],\n ).then((value) {\n if (value == null) return;\n\n if (value == \"1\") {\n //code here\n log(\"message\", name: value);\n } else if (value == \"2\") {\n //code here\n log(\"message\", name: value);\n } else if (value == \"3\") {\n //code here\n log(\"message\", name: value);\n }\n });\n }\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20465350/"
] |
74,426,921 | <p>I have a table:</p>
<pre><code>Id Name
1 phucuong
2 ksks
3 na
</code></pre>
<p>I want output is:</p>
<pre><code>phucuongksksna
</code></pre>
<p>how to write in sql?</p>
<p>I tried <code>concat</code>, but it is not working.</p>
| [
{
"answer_id": 74427076,
"author": "Uday Dodiya",
"author_id": 19663739,
"author_profile": "https://Stackoverflow.com/users/19663739",
"pm_score": 2,
"selected": false,
"text": "SELECT Name AS [text()] FROM YourTable FOR XML PATH ('')\n"
},
{
"answer_id": 74427758,
"author": "Jonas Metzler",
"author_id": 18794826,
"author_profile": "https://Stackoverflow.com/users/18794826",
"pm_score": 1,
"selected": false,
"text": "STRING_AGG"
},
{
"answer_id": 74442378,
"author": "masoud rafiee",
"author_id": 4256602,
"author_profile": "https://Stackoverflow.com/users/4256602",
"pm_score": 0,
"selected": false,
"text": "SELECT DISTINCT \n STUFF(\n(\n SELECT ',' + name\n FROM table A1\n WHERE A1.ID = A2.ID FOR XML PATH('')\n), 1, 1, '') AS aliasName\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18259310/"
] |
74,426,934 | <p>An implementation using Fork and Pipe in C</p>
<p>Where I have 2 Forks reading .txt files and writing to , for each reading Forks create threads to write to
And a Fork reading the to update a list.</p>
<p>Problem is when reading, I only find this result: SEV :: Token -> 0 1 1001
Files only have the first line with the value 1001 and the other 99 lines are 1000.</p>
<p>I don't understand why there is no overwrite and there is no EOF in the </p>
<pre><code>void* holdToken(void* tok) {
token* value = (token *)tok;
token it = *value;
pthread_mutex_lock(&wt);
printf("Holding Token\t::\t%d\t%d\n", it.count, it.value);
close(fd[0]);
write(fd[1], &it, sizeof(token));
countThreads++;
close(fd[1]);
pthread_mutex_unlock(&wt);
return NULL;
}
</code></pre>
<pre><code>void doToken() {
int i = 0;
int status;
while(1) {
token tok;
close(fd[1]);
status = read(fd[0], &tok, sizeof(token));
close(fd[0]);
if(status != 0) {
printf("SEV\t::\tToken\t->\t%d\t%d\t%d\n", tok.count, tok.oper, tok.value);
exe(tok);
} else {
printf("\n\nEOF BREAK\n\n");
break;
}
i++;
}
printList(accList, sizeAccList);
}
void sendToken(token tok, int pid) {
pthread_t atm;
pthread_create(&atm, NULL, holdToken, &tok);
pthread_join(atm, NULL);
}
</code></pre>
<p>Here is where I have pipe and Fork</p>
<pre><code> int main()
{
initList(accList, sizeAccList);
// printf("PID\t::\t%d\n", getpid());
if(pipe(fd) < 0) {
printf("PIPE FD OPEN");
}
for(int i = 0; i < 1; i++) {
if(fork()==0) {
printf("[son] pid %d from [parent] pid %d\n", getpid(), getppid());
if(getpid() != 0) {
// sleep(5);
printf("SERVER\t::\t%d\n", getpid());
doToken();
}
exit(0);
}
}
for(int i=5;i<7;i++)
{
char fileName[10];
snprintf(fileName, 10,"file%d.txt", i);
if(fork() == 0)
{
printf("[son] pid %d from [parent] pid %d\n", getpid(), getppid());
if(getpid() != 0) {
printf("PID\t::\t%d\n", getpid());
printf("Read\t::\t%s\n", fileName);
readToken(fileName, getpid());
} else {
printf("FORK FAIL\n");
}
exit(0);
}
}
for(int i=0;i<3;i++) // loop will run 'n' times
wait(NULL);
printf("Hello World\n");
}
</code></pre>
<p>Full Proj:
<a href="https://www.stackoverflow.com/">https://github.com/Claus-K/ForkTest/blob/main/forkTest/main.c</a></p>
<p>I tried everything I could find, Am I missing something here, in reading and writing, in creating the Fork? The output value must be 0 -> 200001. Rest 0.</p>
<p>Here is a simplification of the problem:</p>
<pre><code>#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
int fd[2];
int main() {
if(pipe(fd) == 0) {
printf("Pipe is Open\n");
}
for(int i = 0; i < 5; i++) {
close(fd[1]);
write(fd[0], &i, sizeof(int));
close(fd[0]);
}
for(int i = 0; i < 5; i++) {
int value;
close(fd[0]);
read(fd[1], &value, sizeof(int));
close(fd[1]);
printf("%d\n", value);
}
return 0;
}
</code></pre>
<p>Output:</p>
<pre><code>Pipe is Open
4
4
4
4
4
</code></pre>
| [
{
"answer_id": 74427076,
"author": "Uday Dodiya",
"author_id": 19663739,
"author_profile": "https://Stackoverflow.com/users/19663739",
"pm_score": 2,
"selected": false,
"text": "SELECT Name AS [text()] FROM YourTable FOR XML PATH ('')\n"
},
{
"answer_id": 74427758,
"author": "Jonas Metzler",
"author_id": 18794826,
"author_profile": "https://Stackoverflow.com/users/18794826",
"pm_score": 1,
"selected": false,
"text": "STRING_AGG"
},
{
"answer_id": 74442378,
"author": "masoud rafiee",
"author_id": 4256602,
"author_profile": "https://Stackoverflow.com/users/4256602",
"pm_score": 0,
"selected": false,
"text": "SELECT DISTINCT \n STUFF(\n(\n SELECT ',' + name\n FROM table A1\n WHERE A1.ID = A2.ID FOR XML PATH('')\n), 1, 1, '') AS aliasName\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11444183/"
] |
74,426,977 | <p>I'm trying to make a function that takes an array as input and a target, and then iterates the array to check if the current index is equal to the target. If so, it will splice the current index from the array.</p>
<p>Everything works fine so far, however when i implement an if statement to check if the index is at the end of the array and then check if the result array is equal to the input array. I really don't know why this is taking me so long it's kind of embarrassing... Here's my code:</p>
<pre class="lang-js prettyprint-override"><code>let array = ['fox', 'tiger', 'elephant', 'jaguar', 'wolf', 'deer', 'hog', 'dhole', 'leopard', 'eagle', 'bear'];
const splice = (arr, target) => {
//creates empty result array
let result = [];
//iterate through the input array and push each item to the result array
for(let i = 0; i < arr.length; i++) {
result.push(arr[i]);
}
let j = 0;
//iterate through result array
while(j < result.length) {
if (result[j] === target) {
result.splice(j, 1);
}
//i have tried this multiple times with the if statement in and out of the loop
if (j === result.length && result === arr) {
//throw new Error(`${target} was not found in the array`);
console.log({result, arr, j});
return 'equal';
} else if (j === result.length && result !== arr ) {
console.log({result, arr, j});
return 'different';
}
j++;
}
};
//should return 'equal' but returns 'different'
console.log(splice(array, 'turtle'));
//should return 'different' but returns undefined
console.log(splice(array, 'bear'));
</code></pre>
| [
{
"answer_id": 74427134,
"author": "N_A_P",
"author_id": 10693800,
"author_profile": "https://Stackoverflow.com/users/10693800",
"pm_score": 2,
"selected": true,
"text": "const splice = (arr, target) => {\n //creates empty result array\n let result = [];\n //iterate through the input array and push each item to the result array\n for(let i = 0; i < arr.length; i++) {\n result.push(arr[i]);\n }\n let j = 0;\n //iterate through result array\n while(j < result.length) {\n if (result[j] === target) {\n result.splice(j, 1); \n /* since you modified the length of result array here,\n u can simply check the length of result array\n with the original array to see if there's a different */\n }\n // result === arr will always resolve to fasle as they are not the same object, so check the length instead\n if (j === result.length && result.length !== arr.length) {\n //throw new Error(`${target} was not found in the array`);\n console.log({result, arr, j});\n return 'equal';\n } else if (j === result.length && result.length === arr.length ) {\n console.log({result, arr, j});\n return 'different';\n }\n j++;\n }\n // a better way of doing it is to move the if check outside of while loop to avoid it run multiple time\n if (result.length !== arr.length) { // different length, that mean we found the target and the result array got modified \n console.log({result, arr, j});\n return 'equal';\n } else {\n console.log({result, arr, j});\n return 'different';\n }\n\n};\n"
},
{
"answer_id": 74427160,
"author": "jerry",
"author_id": 20493210,
"author_profile": "https://Stackoverflow.com/users/20493210",
"pm_score": 1,
"selected": false,
"text": "let arr1 = [1, 2, 3, -2, null];\nlet arr2 = [1, 2, 3, -2, null];\n\nlet bool = true;\n\nlet i;\nfor (i = 0; i < arr1.length; i++) {\n if (arr1[i] !== arr2[i]) {\n bool = false;\n break;\n }\n}\nif (arr1[i] === arr2[i]) bool = true;\nif (arr1[i] !== arr2[i] || arr1.length !== arr2.length) bool = false;\n\nif (bool) console.log(\"same\");\nelse console.log(\"different\");\n"
},
{
"answer_id": 74427508,
"author": "Ping",
"author_id": 20288037,
"author_profile": "https://Stackoverflow.com/users/20288037",
"pm_score": 0,
"selected": false,
"text": "const arr1 = [1,2,3,\"A\"];\nconst arr2 = [1,2,3,\"A\"];\n\nfunction compareArr(A,B) {\n return (A.length === B.length) && A.every((v,i) => B[i] === v)\n}\n\nconsole.log(compareArr(arr1,arr2))"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17109812/"
] |
74,426,986 | <p>Given an API that for invalid requests, along with 400-range HTTP status code the server returns a JSON payload that includes a readable message. As an example, the server could return <code>{ "message": "Not Found" }</code> with a 404 status code for deleted or non-existent content.</p>
<p>Without using publishers, the code would read,</p>
<pre class="lang-swift prettyprint-override"><code>struct APIErrorResponse: Decodable, Error {
let message: String
}
func request(request: URLRequest) async throws -> Post {
let (data, response) = try await URLSession.shared.data(for: request)
let statusCode = (response as! HTTPURLResponse).statusCode
if 400..<500 ~= statusCode {
throw try JSONDecoder().decode(APIErrorResponse.self, from: data)
}
return try JSONDecoder().decode(Post.self, from: data)
}
</code></pre>
<p>Can this be expressed succinctly using only functional code?
In other words, how can the following pattern be adapted to decode a different type based on the <code>HTTPURLResponse.statusCode</code> property, to return as an error, or more generally, how can the <code>response</code> property be handled separately from <code>data</code> attribute?</p>
<pre class="lang-swift prettyprint-override"><code>URLSession.shared.dataTaskPublisher(for: request)
.map(\.data)
.decode(type: Post.self, decoder: JSONDecoder())
.eraseToAnyPublisher()
</code></pre>
| [
{
"answer_id": 74427304,
"author": "workingdog support Ukraine",
"author_id": 11969817,
"author_profile": "https://Stackoverflow.com/users/11969817",
"pm_score": 1,
"selected": false,
"text": "func request(request: URLRequest) -> AnyPublisher<Post, any Error> {\n URLSession.shared.dataTaskPublisher(for: request)\n .tryMap { (output) -> Data in\n let statusCode = (output.response as! HTTPURLResponse).statusCode\n if 400..<500 ~= statusCode {\n throw try JSONDecoder().decode(APIErrorResponse.self, from: output.data)\n }\n return output.data\n }\n .decode(type: Post.self, decoder: JSONDecoder())\n .eraseToAnyPublisher()\n}\n"
},
{
"answer_id": 74428786,
"author": "LuLuGaGa",
"author_id": 7948372,
"author_profile": "https://Stackoverflow.com/users/7948372",
"pm_score": 1,
"selected": false,
"text": "extension Publisher where Output == (data: Data, response: HTTPURLResponse) {\n\n func decode<Success, Failure>(\n success: Success.Type,\n failure: Failure.Type,\n decoder: JSONDecoder\n ) -> AnyPublisher<Success, Error> where Success: Decodable, Failure: DecodableError {\n tryMap { data, httpResponse -> Success in\n guard httpResponse.statusCode < 500 else {\n throw MyCustomError.serverUnavailable(status: httpResponse.statusCode)\n }\n guard httpResponse.statusCode < 400 else {\n let error = try decoder.decode(failure, from: data)\n throw error\n }\n let success = try decoder.decode(success, from: data)\n\n return success\n }\n .eraseToAnyPublisher()\n }\n}\n\ntypealias DecodableError = Decodable & Error\n"
},
{
"answer_id": 74436033,
"author": "Rob",
"author_id": 1271826,
"author_profile": "https://Stackoverflow.com/users/1271826",
"pm_score": 0,
"selected": false,
"text": ".badServerResponse"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74426986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/414415/"
] |
74,427,038 | <p>My way of binding not working. please correct me.</p>
<pre><code>const ob = {
name:'arif',
getName:() => {
console.log(this)
return this.name;
}
}
const x = ob.getName.bind(ob);
console.log(x()); //return the global name!!
</code></pre>
| [
{
"answer_id": 74427048,
"author": "Code Maniac",
"author_id": 9624435,
"author_profile": "https://Stackoverflow.com/users/9624435",
"pm_score": 2,
"selected": true,
"text": "const ob = {\n name:'arif',\n getName: function(){\n console.log(this)\n return this.name; \n }\n}\nconst x = ob.getName.bind(ob);\nconsole.log(x()); "
},
{
"answer_id": 74427063,
"author": "Asadbek Eshboev",
"author_id": 16938897,
"author_profile": "https://Stackoverflow.com/users/16938897",
"pm_score": 0,
"selected": false,
"text": " const ob = {\n name:'arif',\n getName: function() {\n console.log(this)\n return this.name; \n }\n}\nconst x = ob.getName.bind(ob);\nconsole.log(x()); //returns the object name !!\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74427038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2024080/"
] |
74,427,088 | <p>Here's a script that reads a JPG image and then writes 2 JPG images:</p>
<pre class="lang-py prettyprint-override"><code>import cv2
# https://github.com/opencv/opencv/blob/master/samples/data/baboon.jpg
input_path = './baboon.jpg'
# Read image
im = cv2.imread(input_path)
# Write image using default quality (95)
cv2.imwrite('./baboon_out.jpg', im)
# Write image using best quality
cv2.imwrite('./baboon_out_100.jpg', im, [cv2.IMWRITE_JPEG_QUALITY, 100])
</code></pre>
<p>after running the above script, here's what the files look like:</p>
<pre><code>.
├── baboon.jpg
├── baboon_out.jpg
├── baboon_out_100.jpg
└── main.py
</code></pre>
<p>However, the MD5 checksums of the JPGs created by the script do not match the original:</p>
<pre><code>>>> md5 ./baboon.jpg
MD5 (./baboon.jpg) = 9a7171af1d6c6f0901d36d04e1bd68ad
>>> md5 ./baboon_out.jpg
MD5 (./baboon_out.jpg) = 1014782b9e228e848bc63bfba3fb49d9
>>> md5 ./baboon_out_100.jpg
MD5 (./baboon_out_100.jpg) = dbadd2fadad900e289e285393778ad89
</code></pre>
<p>Is there anyway to preserve the original image content with OpenCV? In which step is the data being modified?</p>
| [
{
"answer_id": 74427239,
"author": "ti7",
"author_id": 4541045,
"author_profile": "https://Stackoverflow.com/users/4541045",
"pm_score": 2,
"selected": false,
"text": "baboon.jpg"
},
{
"answer_id": 74428535,
"author": "Mark Setchell",
"author_id": 2836621,
"author_profile": "https://Stackoverflow.com/users/2836621",
"pm_score": 1,
"selected": false,
"text": "print(100)\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74427088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10720618/"
] |
74,427,103 | <p>Let's say I have the following PostgreSQL table called <code>products</code> which has millions of records:</p>
<pre><code>CREATE TABLE IF NOT EXISTS mytable (
id serial NOT NULL PRIMARY KEY,
label VARCHAR(50) NOT NULL,
info jsonb NOT NULL,
created_at timestamp NOT NULL DEFAULT now()
);
</code></pre>
<p>I have a <code>SELECT</code> statement targeting this table with several <code>JOIN</code>'s that is generating duplicate rows. This appears to be common: <a href="https://stackoverflow.com/questions/23786401/why-do-multiple-table-joins-produce-duplicate-rows">Why do multiple-table joins produce duplicate rows?</a></p>
<p>I know I can fix this issue using <code>SELECT DISTINCT ...</code>. However, the query is taking several seconds, whereas the vanilla <code>SELECT ...</code> query takes milliseconds.</p>
<p>I presume this has to do with the <code>info</code> JSONB field, which can be very large. When I remove <code>info</code> from the <code>DISTINCT</code> calculation by using <code>SELECT DISTINCT ON (id) ...</code> then the query is much faster.</p>
<p>However, <code>DISTINCT ON</code> breaks some of my queries that use <code>ORDER BY [non-id field]</code> due to this condition:</p>
<blockquote>
<p>SELECT DISTINCT ON expressions must match initial ORDER BY expressions</p>
</blockquote>
<p>I've noticed I can fix the error by using subqueries (<a href="https://stackoverflow.com/questions/74426689/postgresql-select-distinct-on-expressions-must-match-initial-order-by-expressio#74426829">good example here</a>):</p>
<pre><code>SELECT * FROM (
SELECT DISTINCT ON (id) ...
) ORDER BY [non-id field]
</code></pre>
<p>Two questions:</p>
<ul>
<li>Is passing a JSONB field through <code>DISTINCT</code> a known performance problem? I want to make sure my theory is reasonable.</li>
<li>Is my solution of using subqueries a good solution for fixing the <code>SELECT DISTINCT ON expressions must match initial ORDER BY expressions</code> error? Or is there a better solution I'm not thinking of?</li>
</ul>
| [
{
"answer_id": 74427222,
"author": "Erwin Brandstetter",
"author_id": 939860,
"author_profile": "https://Stackoverflow.com/users/939860",
"pm_score": 1,
"selected": false,
"text": "DISTINCT"
},
{
"answer_id": 74428032,
"author": "Laurenz Albe",
"author_id": 6464308,
"author_profile": "https://Stackoverflow.com/users/6464308",
"pm_score": 0,
"selected": false,
"text": "SELECT DISTINCT ON ([non-id column], id) ...\nORDER BY [non-id column], id;\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74427103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6611672/"
] |
74,427,193 | <p>I'm trying to display the another view in a current page.</p>
<p>In ASP.NET MVC (running on the full/classic .NET framework), it was possible like this:</p>
<pre><code>return View("view name", MyModel);
</code></pre>
<p>As the method of ASP.NET Core, I found this article:</p>
<p><a href="https://stackoverflow.com/questions/57759375/how-to-return-a-different-view-with-object-in-razor-pages">How to return a different view with object in Razor Pages?</a></p>
<p>Here's its alternative method.</p>
<pre><code>return new RedirectToPageResult("view", MyModel);
</code></pre>
<p>However, the first method does not change the URL in the address bar, while the following method does change the URL.</p>
<p>Does anyone know how to do it in ASP.NET Core MVC without changing the url?</p>
| [
{
"answer_id": 74427222,
"author": "Erwin Brandstetter",
"author_id": 939860,
"author_profile": "https://Stackoverflow.com/users/939860",
"pm_score": 1,
"selected": false,
"text": "DISTINCT"
},
{
"answer_id": 74428032,
"author": "Laurenz Albe",
"author_id": 6464308,
"author_profile": "https://Stackoverflow.com/users/6464308",
"pm_score": 0,
"selected": false,
"text": "SELECT DISTINCT ON ([non-id column], id) ...\nORDER BY [non-id column], id;\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74427193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5829469/"
] |
74,427,229 | <p>I was solving a question on merging k sorted linked lists and I came across this <code>vector<Node<int>*></code>:</p>
<pre><code>Node<int>* mergeKLists(vector<Node<int>*> &listArray);
</code></pre>
<p>I want to know if it is a declaration of all the linked lists, if it is how it has been declared?</p>
| [
{
"answer_id": 74427294,
"author": "rcgldr",
"author_id": 3282056,
"author_profile": "https://Stackoverflow.com/users/3282056",
"pm_score": 2,
"selected": false,
"text": "K"
},
{
"answer_id": 74431976,
"author": "rturrado",
"author_id": 260313,
"author_profile": "https://Stackoverflow.com/users/260313",
"pm_score": 0,
"selected": false,
"text": "Node<int>"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74427229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19609814/"
] |
74,427,286 | <p>Hi I am new to angular while I am trying to learn rxjs , on following the tutorial i got this error, I tried many ways but not working anything.</p>
<p>previous error was 'error TS7008: Member '(Missing)' implicitly has an 'any' type.' and I changed the "tsconfig.json" strict =false. now I am getting this error on the picture I attached please help me to resolve</p>
<p>code part------</p>
<pre><code>export class RxjsComponent implements OnInit {
// agents: any = [];
@ViewChild(validate);
validate!:ElementRef;
</code></pre>
<p>error----------
Error: src/app/rxjs/rxjs.component.ts:12:23 - error TS1146: Declaration expected.
<a href="https://i.stack.imgur.com/oqWSY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oqWSY.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74427321,
"author": "jerry",
"author_id": 20493210,
"author_profile": "https://Stackoverflow.com/users/20493210",
"pm_score": 1,
"selected": false,
"text": "<p #validate></p>\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74427286",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12056439/"
] |
74,427,299 | <p>I've a typical Jmeter test plan with a login, some user operations and a logout. I've observed that the login passes only if I use an HTTP cookie manager type as Standard which makes the user operations fail. The user operaitons pass only if I use the HTTP cookie manager type rfc2109 which fails the login. Any idea how I can deal with this situation?</p>
<p>I've tried using two HTTP cookie managers in my test plan but only the last cookie manager takes effect. I've also tried including the appropirate cookie manager within the transaction controllers but that didnt work too.
Please advise.</p>
<p>Jmeter version is 5.3.</p>
| [
{
"answer_id": 74427321,
"author": "jerry",
"author_id": 20493210,
"author_profile": "https://Stackoverflow.com/users/20493210",
"pm_score": 1,
"selected": false,
"text": "<p #validate></p>\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74427299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20497401/"
] |
74,427,305 | <p>I am rendering a simple react app component but I am not able to understand why "Inside useeffect hook." is being printed on console twice. Should it not just be printed once after the component is rendered, since there is no state change and the dependency array is also empty?
Below is the code:
`</p>
<pre><code>export default function App(){
const [count, setCount] = React.useState(0);
useEffect(()=>{
console.log("Inside useeffect hook.")
},[]);
return(
<h1>hey.</h1>
);
}
</code></pre>
<p>`</p>
| [
{
"answer_id": 74427321,
"author": "jerry",
"author_id": 20493210,
"author_profile": "https://Stackoverflow.com/users/20493210",
"pm_score": 1,
"selected": false,
"text": "<p #validate></p>\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74427305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20497431/"
] |
74,427,317 | <pre><code>for line in lines
if any(word in line for word in Array):
print(word)
</code></pre>
<p>I am using something similar to this, but I am not able to print it out.
For example:</p>
<pre><code>String1 = " I am a newbie".
String2 = " Hello There".
Array = [newbie, hello, world]
</code></pre>
<p>I want to get the repeated word when I loop through each line.
Thanks!!</p>
<pre><code>String1 = " I am a newbie".
String2 = " Hello There".
Array = [newbie, hello, world]
</code></pre>
<p>loop 1:
newbie
loop 2:
Hello</p>
| [
{
"answer_id": 74427321,
"author": "jerry",
"author_id": 20493210,
"author_profile": "https://Stackoverflow.com/users/20493210",
"pm_score": 1,
"selected": false,
"text": "<p #validate></p>\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74427317",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20497534/"
] |
74,427,336 | <p>Im coding a snake game for a project but for some reason it says that the variable playerNumber is not defined even though i very clearly defined it in the previous function. I dont really know whats wrong and i have tried various things and nothing has helped.</p>
<pre><code>import turtle
gt = turtle.Turtle()
t1 = turtle.Turtle()
t2 = turtle.Turtle()
t3 = turtle.Turtle()
t4 = turtle.Turtle()
turtle.bgcolor("White")
def start():
print ("Welcome to python Snake! A game made by Kippo and inspired by the famous game: Snake!")
playerNumber = int(input("How many players are going to play? (2-4)"))
if playerNumber >= 5:
print("Too many players! Try again.")
start()
elif playerNumber <= 1:
print("Too few players! Try again.")
start()
else:
playerColour()
def playerColour():
global playerNumber
if playerNumber == 1:
player1colour = input("player 1, what colour do you want to be?")
elif playerno == 2:
player1colour = input("player 1, what colour do you want to be?")
player2colour = input("player 2, what colour do you want to be?")
elif playerno == 3:
player1colour = input("player 1, what colour do you want to be?")
player2colour = input("player 2, what colour do you want to be?")
player3colour = input("player 3, what colour do you want to be?")
elif playerno == 4:
player1colour = input("player 1, what colour do you want to be?")
player2colour = input("player 2, what colour do you want to be?")
player3colour = input("player 3, what colour do you want to be?")
player4colour = input("player 4, what colour do you want to be?")
else:
print ("Too many players, try again.")
quit()
def gridSize():
gridsize = int(input("What size do you want your grid to be?"))
gt.circle(2)
start()
</code></pre>
<p>I have tried changing the name of the variable, moving the functions around, and trying various other methods of using the variable and nothing has changed.</p>
| [
{
"answer_id": 74427321,
"author": "jerry",
"author_id": 20493210,
"author_profile": "https://Stackoverflow.com/users/20493210",
"pm_score": 1,
"selected": false,
"text": "<p #validate></p>\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74427336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20497564/"
] |
74,427,362 | <p><a href="https://i.stack.imgur.com/0djyd.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0djyd.jpg" alt="cards" /></a></p>
<p>So i can't get all the cards to be the same height, the reason this is happening is that main title is sometimes 2 or 1 lines (i have handled the image height case). What would be the best way to solve this? I have have tried using min-height but it leaves too much room in the bottom of the 1 line cases. I am using angular material library in my angular project.</p>
<p>component html</p>
<pre><code> <mat-card class="example-card " >
<mat-card-header >
<mat-card-title class="hres">{{ product.name }}</mat-card-title>
<mat-card-subtitle> {{ product.type | titlecase }}</mat-card-subtitle>
</mat-card-header>
<div >
<img *ngIf="product.type=='video'" class="imh" mat-card-image src="../../assets/images/Products/Videos/{{product.image.imageSrc[0]}}" >
<div>
<img *ngIf="product.type=='book'" class="imh" mat-card-image src="../../assets/images/Products/Books/{{product.image.imageSrc[0]}}" >
</div>
</div>
<mat-card-content>
<button mat-button>PRICE</button>
<p style="display: inline;">$ {{ product.price }}</p>
<button mat-raised-button style="float: right;" *ngIf="!isAdmin" color="primary">Add to cart</button>
</mat-card-content>
<!-- <mat-card-actions>
</mat-card-actions> -->
</mat-card>
</code></pre>
<p>component css</p>
<pre><code> h2 {
font-size: 1em;
flex: 1;
}
h4 {
font-size: 0.8em;
margin: 0;
padding: 0;
}
.tools {
justify-content: flex-end;
display: inline-block;
margin-top: 8px;
display: flex;
flex-wrap: nowrap;
}
.mC{
cursor: pointer;
}
.cardH{
}
.imh{
/* overflow-y: auto;
overflow-x: hidden;
*/
object-fit:scale-down;
max-height: 25vh;
min-height: 25vh;
/* object-position: top; */
}
.hres{
/* max-height: 5vh; */
/* min-height: 5.5vh; */
padding-bottom: 0;
}
</code></pre>
<p>This is more a single card, the image just shows all the cards (looped from a array) in a grid.</p>
| [
{
"answer_id": 74427321,
"author": "jerry",
"author_id": 20493210,
"author_profile": "https://Stackoverflow.com/users/20493210",
"pm_score": 1,
"selected": false,
"text": "<p #validate></p>\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74427362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18667485/"
] |
74,427,396 | <p>Is there a way to make <code>all()</code> method return false on empty iter ?</p>
<p>example</p>
<pre class="lang-rust prettyprint-override"><code>let list = "";
let res = list.chars().all(|c| c == 'a');
println!("{}", res); // res here will print true and I want it to be false
</code></pre>
<p>I'm open for any other solution.</p>
| [
{
"answer_id": 74428348,
"author": "Oussama Gammoudi",
"author_id": 3978243,
"author_profile": "https://Stackoverflow.com/users/3978243",
"pm_score": 2,
"selected": false,
"text": "let list = \"\";\nlet res = !list.is_empty() && list.chars().all(|c| c == 'a');\nprintln!(\"{}\", res); // res here will print false\n"
},
{
"answer_id": 74436422,
"author": "Richard Neumann",
"author_id": 3515670,
"author_profile": "https://Stackoverflow.com/users/3515670",
"pm_score": 0,
"selected": false,
"text": "trait"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74427396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2308955/"
] |
74,427,404 | <p>How to make cmds.duplicate execute immediately when called in maya? Instead of waiting for the entire script to run and then executing it in batches. For example, for this script below, all execution results will appear immediately after the entire script is executed</p>
<pre><code>import time
for i in range(1, 6):
pm.select("pSphere{}".format(i))
time.sleep(0.5)
cmds.duplicate()
</code></pre>
<p>I have tried to use python multithreading, like this</p>
<pre><code>import threading
import time
def test():
for i in range(50):
cmds.duplicate('pSphere1')
time.sleep(0.1)
thread = threading.Thread(target=test)
thread.start()
#thread.join()
</code></pre>
<p>Sometimes it can success, but sometimes it will crash maya. If the main thread join, it will not achieve the effect. When I want to do a large number of cmds.duplicate, it will resulting in a very high memory consumption, and the program runs more and more slowly. In addition, all duplicate results appear together after the entire python script runs, so I suspect that when I call cmds When duplicating, Maya did not finish executing and outputting the command, but temporarily put the results in a container with variable capacity. With the increase of my calls, the process of dynamic expansion of the container causes the program to become slower and slower, and the memory consumption also increase dramatically. Because I saw that other plug-ins can see the command execution results in real time, so I thought that this should be a proper way to do this just thath I haven't found yet</p>
<pre><code></code></pre>
| [
{
"answer_id": 74429173,
"author": "haggi krey",
"author_id": 9142615,
"author_profile": "https://Stackoverflow.com/users/9142615",
"pm_score": 2,
"selected": false,
"text": "pm.refresh()\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74427404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10138962/"
] |
74,427,426 | <p>I have an input attribute key value and I want to remove all its occurences from a json/dictionary/object. Here's an example:</p>
<pre><code>{
"$type":"NewRunner.SingleValueExpression",
"name":"ABC",
"age":23
"nestedJSON": {
"$type":"NewRunner.SingleValueExpression003",
"field3":"edvrvbte"
}
}
</code></pre>
<p>I want to remove "$type" attribute from everywhere in the given string and the output should be:</p>
<pre><code>{
"name":"ABC",
"age":23
"nestedJSON": {
"field3":"edvrvbte"
}
}
</code></pre>
<p>How can I write a regex for the same? Can someone help me?</p>
<p>Ideally it would be like: string.replace("regexValue",replacement)</p>
<p>I am looking for writing the <code>regex</code> value.</p>
<p>I tried this:</p>
<pre><code>\"\$type\":\".+?(?=abc)\",
</code></pre>
<p>and this as well:</p>
<pre><code>\"\$type\":\"(?<=\[)(.*?)(?=\])\",
</code></pre>
<p>But confused what should I write in center <code>\".+?(?=abc)\"</code> to match anything in value</p>
| [
{
"answer_id": 74429173,
"author": "haggi krey",
"author_id": 9142615,
"author_profile": "https://Stackoverflow.com/users/9142615",
"pm_score": 2,
"selected": false,
"text": "pm.refresh()\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74427426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8176451/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.