qid int64 4 22.2M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
74,417,895 | <p>I had this problem for class, <em>Given integer coefficients of two linear equations with variables x and y, use brute force to find an integer solution for x and y in the range -10 to 10.</em> My question is, is there an alternate method to get 'There is no solution.' to print just once?</p>
<p>I've tried making a count and adding +1 to that count every time there is no solution in both of the lists. This works once the count has reached over 436. But I want to know if there is a more efficient solution. Thanks for any help!</p>
<pre><code>a = int(input())
b = int(input())
c = int(input())
d = int(input())
e = int(input())
f = int(input())
x = [-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = [-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
count = 0
for i in x:
for o in y:
if a*i + b*o == c and d*i + e*o == f:
print('x =', i,',', 'y =', o)
elif a*i + b*o != c and d*i + e*o !=f:
count += 1
if count > 436:
print('There is no solution')
</code></pre>
| [
{
"answer_id": 74417938,
"author": "selbie",
"author_id": 104458,
"author_profile": "https://Stackoverflow.com/users/104458",
"pm_score": 1,
"selected": false,
"text": "solved = False\nfor i in x:\n if solved:\n break\n for o in y:\n if a*i + b*o == c and d*i + e*o == f:\n print('x =', i,',', 'y =', o)\n solved = True\n break\n\nif not solved:\n print('There is no solution')\n"
},
{
"answer_id": 74417984,
"author": "kosciej16",
"author_id": 3361462,
"author_profile": "https://Stackoverflow.com/users/3361462",
"pm_score": 3,
"selected": true,
"text": "import itertools\n\nfor i, o in itertools.product(range(-10,11), range(-10,11)):\n if a*i + b*o == c and d*i + e*o == f: \n print('x =', i,',', 'y =', o)\n break\nelse:\n print('There is no solution')\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74417895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20294935/"
] |
74,417,898 | <p>I need to save a userId and username coming from an API call with the context API.</p>
<p>I need the data, so I can use them globally in my React project, and the API data I need is only send after you successfully log in.</p>
<p>LoginContext.js</p>
<pre><code>import { createContext } from "react";
export const LoginDataContext = createContext(null)
</code></pre>
<p>App.js</p>
<pre><code>// React
import { useState, useMemo } from "react";
// React router dom
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
// Context
import { LoginDataContext } from "./Contexts/LoginContext";
// Pages
import HomePage from "./pages/HomePage";
import NotFound from "./pages/404";
import MailSignup from "./pages/MailSignup";
import AdminLogin from "./pages/LoginAdmin";
import AdminDashboard from "./pages/Dashboard";
function App() {
const [token, setToken] = useState(null);
const [user, setUser] = useState(null);
const userValue = useMemo(() => ({ user, setUser }), [user, setUser]);
return (
<div className="App">
<LoginDataContext.Provider value={userValue}>
<Router>
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/EmailReceipt" element={<MailSignup />} />
<Route path="/Admin" element={<AdminLogin setToken={setToken} />} />
<Route path="/Dashboard" element={<AdminDashboard token={token}/>} />
<Route path={"*"} element={<NotFound />} />
</Routes>
</Router>
</LoginDataContext.Provider>
</div>
);
}
export default App;
</code></pre>
<p>LoginAdmin.js</p>
<pre class="lang-js prettyprint-override"><code>// React
import { useNavigate } from "react-router-dom";
import { useState, useContext } from "react";
import { Link } from "react-router-dom";
// Axios
import axios from "axios";
// Context
import { LoginDataContext } from "../Contexts/LoginContext";
// Logo
import DyreLogo from "../assets/logo.png";
// Icons
import { HiArrowNarrowLeft } from "react-icons/hi";
const AdminLogin = ({setToken}) =\> {
const \[isLoggingIn, setIsLoggingIn\] = useState(false);
const \[badLogin, setBadLogin\] = useState(false);
const { user, setUser} = useContext(LoginDataContext)
let navigate = useNavigate();
function handleLogin(e) {
e.preventDefault();
setIsLoggingIn(true);
setBadLogin(false);
const form = e.target;
const username = form\[0\].value;
const password = form\[1\].value;
// console.log(username + ' ' + password);
axios
.post("http://localhost:4000/auth/token", {
username: username,
password: password,
})
.then((response) => {
if (response.status === 200) {
console.log(response.data)
const userID = response.data.userId
setToken(response.data.token);
axios
.get("http://localhost:4000/api/v1/users/" + userID, {
headers: { Authorization: `Bearer ${response.data.token}` },
})
.then((response) => {
if (response.status === 200) {
console.log(response)
setIsLoggingIn(false);
navigate("/Dashboard");
}
});
}
})
.catch((error) => {
setIsLoggingIn(false);
setBadLogin(true);
});
}
return (
\<div className="flex justify-center items-center flex-col h-screen bg-gray-200"\>
\<img
src={DyreLogo}
alt="Logo of hands holding a dog"
className="w-28 h-28 border-4 border-blue-600 p-2 rounded-full"
/\>
\<form
className="bg-white flex flex-col gap-10 w-\[28rem\] px-28 pb-24 pt-10 mt-10 rounded-md shadow-md"
onSubmit={handleLogin}
\\>
\<div\>
\<h2\>Brugernavn\</h2\>
\<input
className="bg-gray-300 rounded-sm w-full p-2 mt-2 outline-none"
type="text"
/\>
\</div\>
\<div\>
\<h2\>Adgangskode\</h2\>
\<input
className="bg-gray-300 rounded-sm w-full p-2 mt-2 outline-none"
type="password"
/\>
\</div\>
{badLogin && (
\<div className="bg-red-500 text-white text-center visible rounded-sm"\>Brugernavn eller adganskode var forkert\</div\>
)}
\<button className="p-2 px-3 bg-blue-600 rounded-sm text-white w-full"\>
{!isLoggingIn ? "Log ind" : "Logger ind"}
\</button\>
\<Link to="/"\>
\<div className="flex items-center gap-2"\>
\<HiArrowNarrowLeft className="w-5 h-5" /\>
\<p\>Hjem\</p\>
\</div\>
\</Link\>
\</form\>
\</div\>
);
};
export default AdminLogin;
</code></pre>
<p>Here you can see the two api calls i am getting from the LoginAdmin.js page:</p>
<p><a href="https://i.stack.imgur.com/BQJxW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BQJxW.png" alt="api call number 1" /></a></p>
<p><a href="https://i.stack.imgur.com/Ok7DP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ok7DP.png" alt="api call number 2" /></a></p>
<p>I have not yet found a way to store the username and userId and i no longer know what to try/do</p>
<p>Please ask if you need more info regarding the question</p>
<p>I have tried saving the username and id dirrectly from the axios response without any luck.</p>
<pre><code>axios
.post("http://localhost:4000/auth/token", {
username: username,
password: password,
})
.then((response) => {
if (response.status === 200) {
console.log(response.data)
const userID = response.data.userId
setToken(response.data.token);
axios
.get("http://localhost:4000/api/v1/users/" + userID, {
headers: { Authorization: `Bearer ${response.data.token}` },
})
.then((response) => {
if (response.status === 200) {
console.log(response)
setIsLoggingIn(false);
navigate("/Dashboard");
}
});
}
})
.catch((error) => {
setIsLoggingIn(false);
setBadLogin(true);
});
</code></pre>
<p>I have also watched a lot of videos on the topic, to see if they could help me out. I have not found any videos that could explain it, in a situation like mine.</p>
| [
{
"answer_id": 74417968,
"author": "Matias Bertoni",
"author_id": 19272564,
"author_profile": "https://Stackoverflow.com/users/19272564",
"pm_score": 0,
"selected": false,
"text": "localStorage"
},
{
"answer_id": 74418112,
"author": "Azzy",
"author_id": 2122822,
"author_profile": "https://Stackoverflow.com/users/2122822",
"pm_score": 2,
"selected": true,
"text": "const AdminLogin = ({setToken}) => {\n\n const [isLoggingIn, setIsLoggingIn] = useState(false);\n const [badLogin, setBadLogin] = useState(false);\n \n const { user, setUser} = useContext(LoginDataContext)\n \n let navigate = useNavigate();\n \n async function handleLogin(e) {\n\n e.preventDefault();\n setIsLoggingIn(true);\n setBadLogin(false);\n const form = e.target;\n const username = form[0].value;\n const password = form[1].value;\n \n // console.log(username + ' ' + password);\n\n const authResponse = await axios\n .post(\"http://localhost:4000/auth/token\", {\n username: username,\n password: password,\n });\n\n if (authResponse.status === 200) {\n const userID = authResponse.data.userId\n setToken(authResponse.data.token);\n\n const userResponse = await axios\n .get(\"http://localhost:4000/api/v1/users/\" + userID, {\n headers: { Authorization: `Bearer ${authResponse.data.token}` },\n })\n\n const user = userResponse.data.user;\n setUser(user) // set the user \n navigate(\"/Dashboard\");\n\n }\n \n setIsLoggingIn(false);\n \n }\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74417898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15035445/"
] |
74,417,902 | <p>When I push my navigator to any new page, the styling is completely messed up. The font is bigger than my future, red and yellow underlined.
<a href="https://i.stack.imgur.com/ukBL8.png" rel="nofollow noreferrer">look at this</a></p>
<p>Here is my push:
<a href="https://i.stack.imgur.com/bptTd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bptTd.png" alt="enter image description here" /></a></p>
<p>Why is this happening? I am using macOS/Desktop, I don't know if that matters.</p>
<p>Thanks.</p>
<p>When I add my page (widget) to another page, it works fine.</p>
| [
{
"answer_id": 74417968,
"author": "Matias Bertoni",
"author_id": 19272564,
"author_profile": "https://Stackoverflow.com/users/19272564",
"pm_score": 0,
"selected": false,
"text": "localStorage"
},
{
"answer_id": 74418112,
"author": "Azzy",
"author_id": 2122822,
"author_profile": "https://Stackoverflow.com/users/2122822",
"pm_score": 2,
"selected": true,
"text": "const AdminLogin = ({setToken}) => {\n\n const [isLoggingIn, setIsLoggingIn] = useState(false);\n const [badLogin, setBadLogin] = useState(false);\n \n const { user, setUser} = useContext(LoginDataContext)\n \n let navigate = useNavigate();\n \n async function handleLogin(e) {\n\n e.preventDefault();\n setIsLoggingIn(true);\n setBadLogin(false);\n const form = e.target;\n const username = form[0].value;\n const password = form[1].value;\n \n // console.log(username + ' ' + password);\n\n const authResponse = await axios\n .post(\"http://localhost:4000/auth/token\", {\n username: username,\n password: password,\n });\n\n if (authResponse.status === 200) {\n const userID = authResponse.data.userId\n setToken(authResponse.data.token);\n\n const userResponse = await axios\n .get(\"http://localhost:4000/api/v1/users/\" + userID, {\n headers: { Authorization: `Bearer ${authResponse.data.token}` },\n })\n\n const user = userResponse.data.user;\n setUser(user) // set the user \n navigate(\"/Dashboard\");\n\n }\n \n setIsLoggingIn(false);\n \n }\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74417902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20489642/"
] |
74,417,904 | <h1>Consider following models:</h1>
<pre><code># models.py
from django.db import models
class Tag(models.Model):
name = models.CharField(max_length=40)
number_of_publications = models.PositiveIntegerField(default=0)
def __str__(self):
return self.name
class Publication(models.Model):
name = models.CharField(max_length=80)
text = models.TextField()
tags = models.ManyToManyField(Tag, related_name="publications")
</code></pre>
<pre><code># urls.py
from .views import publications_tagged
from django.urls import path
urlpatterns = [
path('publications/tagged/<str:name>', publications_tagged)
]
</code></pre>
<pre><code># views.py
from .models import Tag, Publication
from django.shortcuts import get_object_or_404, render
def publications_tagged(request, name):
tag = get_object_or_404(Tag.objects.prefetch_related('publications'), name=name)
return render(request, 'myapp/tagged_questions.html', {'tag': tag})
</code></pre>
<p>Ok, so when we'd go to a template and make a for-loop that will create a representation of every publication and show appropriate tags of it, Django would make a database call for every publication to fetch all the tags the publication has, meaning:</p>
<p>Iteration <code>x</code> of <code>tag.publications</code> -> check what tags match with <code>publication X</code>.</p>
<p>Of course, we can just not show tags and everything will work like magic (utilizing <code>prefetch_related</code>), but that's not what we want :)</p>
<h1><strong>How could we do something similar in Django?</strong></h1>
<p>What we want is some kind of optimized way to achieve such a result, because stackoverflow renders 15 items really fast, which makes me think they do not do it the monkey way that Django does by default.</p>
<p><a href="https://imgur.com/a/kxNbk3d" rel="nofollow noreferrer">This is what html might look like</a></p>
<p><a href="https://pastebin.com/GtY3gmwF" rel="nofollow noreferrer">This is what html <strong>code</strong> might look like</a></p>
<p>P.S. My problem doesn't quite sound like that. But just in case anyone would say: "Oh, it's a bad design, you shouldn't do that at all" I decided to show an example.</p>
| [
{
"answer_id": 74420641,
"author": "Zkh",
"author_id": 19235697,
"author_profile": "https://Stackoverflow.com/users/19235697",
"pm_score": 1,
"selected": false,
"text": "Publication"
},
{
"answer_id": 74422159,
"author": "whatserface",
"author_id": 15389768,
"author_profile": "https://Stackoverflow.com/users/15389768",
"pm_score": 0,
"selected": false,
"text": "prefetch_related"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74417904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15389768/"
] |
74,417,940 | <p>I am trying to make a module for personal uses, but I want to make it so as soon as I import it, it will run a function. Is there any way to do this. (preferably use the threading module as I already am using it)</p>
| [
{
"answer_id": 74417956,
"author": "xiaxio",
"author_id": 3372006,
"author_profile": "https://Stackoverflow.com/users/3372006",
"pm_score": 2,
"selected": true,
"text": "def run_this_first():\n # write your code here\n pass\n\nrun_this_first()\n"
},
{
"answer_id": 74417967,
"author": "D.Manasreh",
"author_id": 7509907,
"author_profile": "https://Stackoverflow.com/users/7509907",
"pm_score": 0,
"selected": false,
"text": "if __name__ == \"__main__\":\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74417940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20080282/"
] |
74,417,944 | <p>I have an assembly language code I'm calling from C but I keep getting error: <strong>Segmentation fault (core dumped)</strong> I don't know what's the cause.<br></p>
<pre><code>; this is the assembly code
section .text
global isPrime
isPrime: mov ecx, 2
.test: cmp ecx, [rsi]
jle .doif
jg .prime
.doif: mov eax, [rdi]
mov edx, 0
mov ebx, [rsi]
div ebx
cmp edx, 0
jle .notPrime
jg .checkAgain
.notPrime:
mov eax, 1
ret
.checkAgain:
inc ecx
jmp .test
.prime: mov eax, 0
ret
</code></pre>
<p><br> The C code:</p>
<pre><code>// C code
#include <stdio.h>
extern int isPrime(int *number, int *mValue);
int main() {
int limit, m, input = 0;
printf("Enter the limit of the prime numbers:");
input = scanf("%d", &limit);
while (input != 1) {
printf("Not a number!\n");
scanf("%*[^\n]");
printf("Enter the limit of the prime numbers:");
input = scanf("%d", &limit);
}
for (int i = 2; i <= limit; ++i) {
m = i / 2;
int flag = isPrime(&i, &m); //this is what I'm trying to implement
// for (int j = 2; j <= m; j++) {
// if (i % j == 0) {
// printf("Number %d is not prime\n", i);
// flag = 1;
// break;
// }
// }
printf("%d\n", flag);
if (flag == 0)
printf("Number %d is prime\n", i);
}
return 0;
}
</code></pre>
<p><br> Error:</p>
<pre><code>Enter the limit of the prime numbers:10
0
0
Segmentation fault (core dumped)
</code></pre>
<p><br> the commented part in the C code is what I want to write in assembly but got the error I mentioned above. From my research, I'm trying to write a memory address I do not have access to. The error is from assembly code but I don't know where exactly, please any possible solutions?</p>
| [
{
"answer_id": 74418119,
"author": "dimich",
"author_id": 14772619,
"author_profile": "https://Stackoverflow.com/users/14772619",
"pm_score": 2,
"selected": false,
"text": "rbx"
},
{
"answer_id": 74420054,
"author": "Bille Ibinabo",
"author_id": 14262141,
"author_profile": "https://Stackoverflow.com/users/14262141",
"pm_score": 1,
"selected": false,
"text": "section .text\nglobal isPrime\n\nisPrime: mov ecx, 2\n.test: cmp ecx, [rsi]\n jle .doif\n jg .prime\n\n.doif: mov eax, [rdi]\n mov edx, 0\n div ecx\n cmp edx, 0\n jg .checkAgain\n mov eax, 1\n ret\n\n.checkAgain:\n inc ecx\n jmp .test\n\n.prime: mov eax, 0\n ret\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74417944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14262141/"
] |
74,417,950 | <p>I need to organize the information from a long (and old) text file containing thousands of items into a dataframe. The information in the text file follows the same structure in all the items. My goal is to arrange each item in a different row of the dataframe.</p>
<p>Structure of the text file:</p>
<pre><code>Title (number of books) Country
Date time (author) Page number CODES letter,letter...
Notes
</code></pre>
<p>An example of the content, showing the first 3 items:</p>
<pre><code>Pride and Prejudice (5) United Kingdom
1981 10:23 h (Jane Austen) Page 241 CODES OB,IT,CA
Deposited by the G.M.W.
Brave New World (2) United Kingdom
1977 09:14 h (Aldous Huxley) Page 205 CODES OB,PU
Deposited by the E.L.
Wide Sargasso Sea (1) Jamaica
1989 16:51 h (Jean Rhys) Page 183 CODES OB,CA
Sent to the N.U.C.
</code></pre>
<p>I need to extract the first 6 elements of each item (title, number, country, date, time, author) and ignore the rest. The desired dataframe would be:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Title</th>
<th>NoBooks</th>
<th>Country</th>
<th>Date</th>
<th>time</th>
<th>Author</th>
</tr>
</thead>
<tbody>
<tr>
<td>Pride and Prejudice</td>
<td>5</td>
<td>United Kingdom</td>
<td>1981</td>
<td>10:23</td>
<td>Jane Austen</td>
</tr>
<tr>
<td>Brave New World</td>
<td>2</td>
<td>United Kingdom</td>
<td>1977</td>
<td>09:14</td>
<td>JAldous Huxley</td>
</tr>
<tr>
<td>Wide Sargasso Sea</td>
<td>1</td>
<td>Jamaica</td>
<td>1989</td>
<td>16:51</td>
<td>Jean Rhys</td>
</tr>
</tbody>
</table>
</div>
<p>I have just found two similar posts (<a href="https://stackoverflow.com/questions/2391364/converting-multiple-lines-of-text-into-a-data-frame">converting multiple lines of text into a data frame</a> and <a href="https://stackoverflow.com/questions/61708054/converting-text-file-into-dataframe-in-r">Converting text file into dataframe in R</a>) but my database doesn't have key characters to be used as separators.</p>
<p>Is there a way to separate my elemets? I've found a solution using Python libraries, but I would like to do it with R. Any suggestions?</p>
| [
{
"answer_id": 74418252,
"author": "Ric Villalba",
"author_id": 6912817,
"author_profile": "https://Stackoverflow.com/users/6912817",
"pm_score": 3,
"selected": true,
"text": "data<-\"Pride and Prejudice (5) United Kingdom\n1981 10:23 h (Jane Austen) Page 241 CODES OB,IT,CA\nDeposited by the G.M.W.\n\nBrave New World (2) United Kingdom\n1977 09:14 h (Aldous Huxley) Page 205 CODES OB,PU\nDeposited by the E.L.\n\nWide Sargasso Sea (1) Jamaica\n1989 16:51 h (Jean Rhys) Page 183 CODES OB,CA\nSent to the N.U.C.\"\n\ncon <- textConnection(data, \"r\") # replace with: con <- file(\"yourfile.txt\") \ndata <- readLines(con)\nclose(con)\n\nl1 <- data[seq(1,length(data), 4)]\nl2 <- data[seq(2,length(data), 4)]\n\nd1 <- regmatches(l1, regexec(\"^(.*) \\\\((\\\\d+)\\\\) (.*)\", l1 ))\nd2 <- regmatches(l2, regexec(\"^(\\\\d{4}) (\\\\d{2}:\\\\d{2}) h \\\\((.*)\\\\)\", l2))\ndf <- as.data.frame(do.call(rbind, mapply(c, d1, d2, SIMPLIFY = F))[,c(-1,-5)])\n\ncolnames(df) <- c(\"Title\",\"NoBooks\",\"Country\",\"Date\",\"time\",\"Author\")\n\ndf\n#> Title NoBooks Country Date time Author\n#> 1 Pride and Prejudice 5 United Kingdom 1981 10:23 Jane Austen\n#> 2 Brave New World 2 United Kingdom 1977 09:14 Aldous Huxley\n#> 3 Wide Sargasso Sea 1 Jamaica 1989 16:51 Jean Rhys\n"
},
{
"answer_id": 74418307,
"author": "Mako212",
"author_id": 4421870,
"author_profile": "https://Stackoverflow.com/users/4421870",
"pm_score": 1,
"selected": false,
"text": "read.delim"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74417950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17007844/"
] |
74,417,952 | <p>Sorry if this is basic, but I'm trying to create my first react-native app and I'm a bit confused about react-navigation and the npm dependencies.</p>
<p>I'm using Expo to build my project, and it deploys correctly on web, but when I try o connect using my iphone, I don't see anything within the Stack.Navigator component.</p>
<p>I suspect it has to do with the npm packages. Perhaps some don't work on ios? Also I don't get any error code so I'm not sure how to debug. Any clues?</p>
<p>For context, here is my code</p>
<p>App.js</p>
<pre><code>import { StatusBar } from "expo-status-bar";
import { useEffect, useState } from "react";
import * as Font from "expo-font";
import { StyleSheet, Text, SafeAreaView } from "react-native";
import { initializeApp } from "firebase/app";
import * as SplashScreen from "expo-splash-screen";
import { credentials } from "./src/utils/firebase";
import MyStack from "./src/screens/stack/navigation";
import AppStack from "./src/screens/stack/appstack";
// Keep the splash screen visible while we fetch resources
SplashScreen.preventAutoHideAsync();
export default function App() {
const [dataLoaded, setDataLoaded] = useState(false);
useEffect(() => {
async function prepare() {
try {
await initializeApp(credentials);
await SplashScreen.preventAutoHideAsync();
await fetchFonts();
} catch (e) {
console.warn(e);
} finally {
setDataLoaded(true);
}
}
prepare();
}, []);
if (!dataLoaded) {
return null;
}
return (
<SafeAreaView style={styles.container}>
<Text>SHAKA!</Text>
<AppStack />
<StatusBar style="auto" />
</SafeAreaView>
);
}
const fetchFonts = () => {
return Font.loadAsync({
"PlusJakartaSans-Regular": require("./assets/fonts/PlusJakartaSans-Regular.ttf"),
"PlusJakartaSans-Medium": require("./assets/fonts/PlusJakartaSans-Medium.ttf"),
"PlusJakartaSans-Bold": require("./assets/fonts/PlusJakartaSans-Bold.ttf"),
"Poppins-Regular": require("./assets/fonts/Poppins-Regular.ttf"),
"Poppins-Medium": require("./assets/fonts/Poppins-Medium.ttf"),
"Poppins-Bold": require("./assets/fonts/Poppins-Bold.ttf"),
"Poppins-SemiBold": require("./assets/fonts/Poppins-SemiBold.ttf"),
});
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center",
},
});
</code></pre>
<p>appstack.js</p>
<pre><code>mport React from "react";
import { Provider } from "react-redux";
import { createStore } from "react-redux";
import ContextWrapper from "../../context/context";
import { NavigationContainer } from "@react-navigation/native";
import { createNativeStackNavigator } from "@react-navigation/native-stack";
import { StyleSheet, Button, Text, SafeAreaView } from "react-native";
import { StatusBar } from "expo-status-bar";
import Home from "../Home";
const Stack = createNativeStackNavigator();
const HomeScreen = ({ navigation }) => {
return (
<SafeAreaView style={styles.container}>
<Text>Home jjkdjfk</Text>
<Button title="Next Screen" />
<StatusBar style="auto" />
</SafeAreaView>
);
};
export default function AppStack() {
return (
<ContextWrapper>
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen
name="HomeScreen"
component={HomeScreen}
options={{ title: "button" }}
/>
<Stack.Screen
name="Home"
component={Home}
options={{ title: "Home" }}
/>
</Stack.Navigator>
</NavigationContainer>
</ContextWrapper>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center",
},
});
</code></pre>
<p>package.json</p>
<pre><code>{
"name": "shaka",
"version": "1.0.0",
"main": "node_modules/expo/AppEntry.js",
"scripts": {
"start": "expo start",
"android": "expo start --android",
"ios": "expo start --ios",
"web": "expo start --web"
},
"dependencies": {
"@expo/webpack-config": "^0.17.0",
"@react-navigation/native": "^6.0.10",
"@react-navigation/native-stack": "^6.6.2",
"@react-navigation/stack": "^6.3.4",
"expo": "~45.0.0",
"expo-splash-screen": "~0.15.1",
"expo-status-bar": "~1.3.0",
"firebase": "^9.12.1",
"react": "17.0.2",
"react-dom": "17.0.2",
"react-native": "0.68.2",
"react-native-safe-area-context": "^4.4.1",
"react-native-screens": "^3.11.2",
"react-native-web": "~0.18.7",
"react-redux": "^8.0.4"
},
"devDependencies": {
"@babel/core": "^7.12.9"
},
"private": true
}
</code></pre>
| [
{
"answer_id": 74418252,
"author": "Ric Villalba",
"author_id": 6912817,
"author_profile": "https://Stackoverflow.com/users/6912817",
"pm_score": 3,
"selected": true,
"text": "data<-\"Pride and Prejudice (5) United Kingdom\n1981 10:23 h (Jane Austen) Page 241 CODES OB,IT,CA\nDeposited by the G.M.W.\n\nBrave New World (2) United Kingdom\n1977 09:14 h (Aldous Huxley) Page 205 CODES OB,PU\nDeposited by the E.L.\n\nWide Sargasso Sea (1) Jamaica\n1989 16:51 h (Jean Rhys) Page 183 CODES OB,CA\nSent to the N.U.C.\"\n\ncon <- textConnection(data, \"r\") # replace with: con <- file(\"yourfile.txt\") \ndata <- readLines(con)\nclose(con)\n\nl1 <- data[seq(1,length(data), 4)]\nl2 <- data[seq(2,length(data), 4)]\n\nd1 <- regmatches(l1, regexec(\"^(.*) \\\\((\\\\d+)\\\\) (.*)\", l1 ))\nd2 <- regmatches(l2, regexec(\"^(\\\\d{4}) (\\\\d{2}:\\\\d{2}) h \\\\((.*)\\\\)\", l2))\ndf <- as.data.frame(do.call(rbind, mapply(c, d1, d2, SIMPLIFY = F))[,c(-1,-5)])\n\ncolnames(df) <- c(\"Title\",\"NoBooks\",\"Country\",\"Date\",\"time\",\"Author\")\n\ndf\n#> Title NoBooks Country Date time Author\n#> 1 Pride and Prejudice 5 United Kingdom 1981 10:23 Jane Austen\n#> 2 Brave New World 2 United Kingdom 1977 09:14 Aldous Huxley\n#> 3 Wide Sargasso Sea 1 Jamaica 1989 16:51 Jean Rhys\n"
},
{
"answer_id": 74418307,
"author": "Mako212",
"author_id": 4421870,
"author_profile": "https://Stackoverflow.com/users/4421870",
"pm_score": 1,
"selected": false,
"text": "read.delim"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74417952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13984779/"
] |
74,417,972 | <p>I am using panel data that looks like this.</p>
<pre><code>d <- data.frame(id = c("a", "a", "a", "a", "a", "b", "b", "b", "b", "b", "c", "c", "c", "c", "c"),
time = c(1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5),
iz = c(0,1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1))
id time iz
1 a 1 0
2 a 2 1
3 a 3 1
4 a 4 0
5 a 5 0
6 b 1 0
7 b 2 0
8 b 3 0
9 b 4 0
10 b 5 1
11 c 1 0
12 c 2 0
13 c 3 0
14 c 4 1
15 c 5 1
</code></pre>
<p>Now I want to create an event time indicator that measures the time since the first event as below.</p>
<pre><code> id time iz nvar
1 a 1 0 -1
2 a 2 1 0
3 a 3 1 1
4 a 4 1 2
5 a 5 1 3
6 b 1 0 -4
7 b 2 0 -3
8 b 3 0 -2
9 b 4 0 -1
10 b 5 1 0
11 c 1 0 -1
12 c 2 0 -2
13 c 3 0 -3
14 c 4 1 0
15 c 5 1 1
</code></pre>
<p>I have tried the solutions in the link posted below but can't make it work in my case. Especially I struggle to make it to count the time after event as specified as above. Let me know in case you have any advice on what I should try.</p>
<p><a href="https://stackoverflow.com/questions/65954866/create-a-time-to-and-time-after-event-variables">Create a time to and time after event variables</a></p>
| [
{
"answer_id": 74418252,
"author": "Ric Villalba",
"author_id": 6912817,
"author_profile": "https://Stackoverflow.com/users/6912817",
"pm_score": 3,
"selected": true,
"text": "data<-\"Pride and Prejudice (5) United Kingdom\n1981 10:23 h (Jane Austen) Page 241 CODES OB,IT,CA\nDeposited by the G.M.W.\n\nBrave New World (2) United Kingdom\n1977 09:14 h (Aldous Huxley) Page 205 CODES OB,PU\nDeposited by the E.L.\n\nWide Sargasso Sea (1) Jamaica\n1989 16:51 h (Jean Rhys) Page 183 CODES OB,CA\nSent to the N.U.C.\"\n\ncon <- textConnection(data, \"r\") # replace with: con <- file(\"yourfile.txt\") \ndata <- readLines(con)\nclose(con)\n\nl1 <- data[seq(1,length(data), 4)]\nl2 <- data[seq(2,length(data), 4)]\n\nd1 <- regmatches(l1, regexec(\"^(.*) \\\\((\\\\d+)\\\\) (.*)\", l1 ))\nd2 <- regmatches(l2, regexec(\"^(\\\\d{4}) (\\\\d{2}:\\\\d{2}) h \\\\((.*)\\\\)\", l2))\ndf <- as.data.frame(do.call(rbind, mapply(c, d1, d2, SIMPLIFY = F))[,c(-1,-5)])\n\ncolnames(df) <- c(\"Title\",\"NoBooks\",\"Country\",\"Date\",\"time\",\"Author\")\n\ndf\n#> Title NoBooks Country Date time Author\n#> 1 Pride and Prejudice 5 United Kingdom 1981 10:23 Jane Austen\n#> 2 Brave New World 2 United Kingdom 1977 09:14 Aldous Huxley\n#> 3 Wide Sargasso Sea 1 Jamaica 1989 16:51 Jean Rhys\n"
},
{
"answer_id": 74418307,
"author": "Mako212",
"author_id": 4421870,
"author_profile": "https://Stackoverflow.com/users/4421870",
"pm_score": 1,
"selected": false,
"text": "read.delim"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74417972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20489693/"
] |
74,418,008 | <p>I am trying to Convert PCollection of Strings into Pcollection of BQ TableRow.
My Apache beam version is 2.41 and JAVA 11. I tried multiple ways but could not able to fix this error.
TableSchema is loaded from avro file and providing it to pcollection as ValueProvider.<br />
Please help me to fix this.</p>
<p>Code:</p>
<pre><code>public static void main(String[] args) {
PipelineOptions options = PipelineOptionsFactory.create();
options.setRunner(DirectRunner.class);
options.setTempLocation("data/temp/");
Pipeline p = Pipeline.create(options);
BeamShemaUtil beamShemaUtil = new BeamShemaUtil("data/ship_data_schema.avsc");
TableSchema tableSchema = beamShemaUtil.convertBQTableSchema();
ValueProvider<TableSchema> ts= ValueProvider.StaticValueProvider.of(tableSchema);
PCollection<String> pc1 = p.apply(TextIO.read().from("data/ship_data.csv"));
PCollection<TableRow> pc2 = pc1.apply(MapElements.via(new ConvertStringToTableRow(ts))) ;
PipelineResult result = p.run();
result.waitUntilFinish();
</code></pre>
<p>SimpleFunction Class</p>
<pre><code> public static class ConvertStringToTableRow extends SimpleFunction<String, TableRow> {
ValueProvider<TableSchema> tableSchema;
public ConvertStringToTableRow(ValueProvider<TableSchema> tableSchema) {
this.tableSchema = tableSchema;
}
public TableRow buildTableRow(TableSchema sc,String[] arr) {
List<TableFieldSchema> fieldSchemaList = sc.getFields();
List<String> data = Arrays.stream(arr).collect(Collectors.toList());
TableRow row = new TableRow();
TableCell record = new TableCell();
List<TableCell> tc = new ArrayList<TableCell>();
for ( int i = 0; i < fieldSchemaList.size(); i++ ){
TableFieldSchema sc2 = fieldSchemaList.get(i);
String fieldName = sc2.getName();
String fieldType = sc2.getType();
String fieldValue = data.get(i);
if (fieldValue.isEmpty()) {
record.set(fieldName,null);
tc.add(record);
}
else {
switch (fieldType) {
case "STRING":
record.set(fieldName,fieldValue);
tc.add(record);
case "BYTES":
record.set(fieldName,fieldValue.getBytes());
tc.add(record);
case "INT64":
record.set(fieldName,Integer.valueOf(fieldValue));
tc.add(record);
case "INTEGER":
record.set(fieldName,Integer.valueOf(fieldValue));
tc.add(record);
case "FLOAT64":
record.set(fieldName,Float.valueOf(fieldValue));
tc.add(record);
case "FLOAT":
record.set(fieldName,Float.valueOf(fieldValue));
tc.add(record);
case "BOOL":
case "BOOLEAN":
case "NUMERIC":
record.set(fieldName,Integer.valueOf(fieldValue));
tc.add(record);
case "TIMESTAMP":
case "TIME":
case "DATE":
case "DATETIME":
case "STRUCT":
case "RECORD":
default:
// row.set(fieldName,fieldValue);
// throw new UnsupportedOperationException("Unsupported BQ Data Type");
}
}
}
return row.setF(tc);
}
@Override
public TableRow apply(String element) {
String[] arr = element.split(",");
// BeamShemaUtil beamShemaUtil = new BeamShemaUtil("data/ship_data_schema.avsc");
// TableSchema tableSchema = beamShemaUtil.convertBQTableSchema();
TableRow row = buildTableRow(tableSchema.get(), arr);
return row;
}
</code></pre>
<p>Error Messages:</p>
<pre><code>Exception in thread "main" java.lang.IllegalArgumentException: unable to serialize DoFnWithExecutionInformation{doFn=org.apache.beam.sdk.transforms.MapElements$1@270a620, mainOutputTag=Tag<output>, sideInputMapping={}, schemaInformation=DoFnSchemaInformation{elementConverters=[], fieldAccessDescriptor=*}}
at org.apache.beam.sdk.util.SerializableUtils.serializeToByteArray(SerializableUtils.java:59)
at org.apache.beam.repackaged.direct_java.runners.core.construction.ParDoTranslation.translateDoFn(ParDoTranslation.java:737)
at org.apache.beam.repackaged.direct_java.runners.core.construction.ParDoTranslation$1.translateDoFn(ParDoTranslation.java:268)
at org.apache.beam.repackaged.direct_java.runners.core.construction.ParDoTranslation.payloadForParDoLike(ParDoTranslation.java:877)
at org.apache.beam.repackaged.direct_java.runners.core.construction.ParDoTranslation.translateParDo(ParDoTranslation.java:264)
at org.apache.beam.repackaged.direct_java.runners.core.construction.ParDoTranslation.translateParDo(ParDoTranslation.java:225)
at org.apache.beam.repackaged.direct_java.runners.core.construction.ParDoTranslation$ParDoTranslator.translate(ParDoTranslation.java:191)
at org.apache.beam.repackaged.direct_java.runners.core.construction.PTransformTranslation.toProto(PTransformTranslation.java:248)
at org.apache.beam.repackaged.direct_java.runners.core.construction.ParDoTranslation.getParDoPayload(ParDoTranslation.java:788)
at org.apache.beam.repackaged.direct_java.runners.core.construction.ParDoTranslation.isSplittable(ParDoTranslation.java:803)
at org.apache.beam.repackaged.direct_java.runners.core.construction.PTransformMatchers$6.matches(PTransformMatchers.java:274)
at org.apache.beam.sdk.Pipeline$2.visitPrimitiveTransform(Pipeline.java:290)
at org.apache.beam.sdk.runners.TransformHierarchy$Node.visit(TransformHierarchy.java:593)
at org.apache.beam.sdk.runners.TransformHierarchy$Node.visit(TransformHierarchy.java:585)
at org.apache.beam.sdk.runners.TransformHierarchy$Node.visit(TransformHierarchy.java:585)
at org.apache.beam.sdk.runners.TransformHierarchy$Node.visit(TransformHierarchy.java:585)
at org.apache.beam.sdk.runners.TransformHierarchy$Node.access$500(TransformHierarchy.java:240)
at org.apache.beam.sdk.runners.TransformHierarchy.visit(TransformHierarchy.java:214)
at org.apache.beam.sdk.Pipeline.traverseTopologically(Pipeline.java:469)
at org.apache.beam.sdk.Pipeline.replace(Pipeline.java:268)
at org.apache.beam.sdk.Pipeline.replaceAll(Pipeline.java:218)
at org.apache.beam.runners.direct.DirectRunner.performRewrites(DirectRunner.java:254)
at org.apache.beam.runners.direct.DirectRunner.run(DirectRunner.java:175)
at org.apache.beam.runners.direct.DirectRunner.run(DirectRunner.java:67)
at org.apache.beam.sdk.Pipeline.run(Pipeline.java:323)
at org.apache.beam.sdk.Pipeline.run(Pipeline.java:309)
at BuildWriteBQTableRowExample01.main(BuildWriteBQTableRowExample01.java:50)
Caused by: java.io.NotSerializableException: com.google.api.services.bigquery.model.TableSchema
at java.base/java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1185)
at java.base/java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1553)
at java.base/java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1510)
at java.base/java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1433)
at java.base/java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1179)
at java.base/java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1553)
at java.base/java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1510)
at java.base/java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1433)
at java.base/java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1179)
at java.base/java.io.ObjectOutputStream.writeArray(ObjectOutputStream.java:1379)
at java.base/java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1175)
at java.base/java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1553)
at java.base/java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1510)
at java.base/java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1433)
at java.base/java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1179)
at java.base/java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1553)
at java.base/java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1510)
at java.base/java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1433)
at java.base/java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1179)
at java.base/java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1553)
at java.base/java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1510)
at java.base/java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1433)
at java.base/java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1179)
at java.base/java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1553)
at java.base/java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1510)
at java.base/java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1433)
at java.base/java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1179)
at java.base/java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1553)
at java.base/java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1510)
at java.base/java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1433)
at java.base/java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1179)
at java.base/java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:349)
at org.apache.beam.sdk.util.SerializableUtils.serializeToByteArray(SerializableUtils.java:55)
... 26 more
Process finished with exit code 1
</code></pre>
| [
{
"answer_id": 74418482,
"author": "Bruno Volpato",
"author_id": 1695821,
"author_profile": "https://Stackoverflow.com/users/1695821",
"pm_score": 1,
"selected": false,
"text": "PCollection<String> pc1 = p.apply(TextIO.read().from(\"data/ship_data.csv\"));\nPCollection<TableRow> pc2 = pc1.apply(MapElements.via(\n new ConvertStringToTableRow(\n () -> new BeamShemaUtil(\"data/ship_data_schema.avsc\").convertBQTableSchema()\n )));\nPipelineResult result = p.run();\nresult.waitUntilFinish();\n"
},
{
"answer_id": 74425475,
"author": "Mazlum Tosun",
"author_id": 9261558,
"author_profile": "https://Stackoverflow.com/users/9261558",
"pm_score": 1,
"selected": true,
"text": "TableFieldSchema"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15976162/"
] |
74,418,036 | <p>I would like to automatically calculate and set an age when creating an instance.
I made a function that calculates and returns an age.
It works, but I wonder if it's possible to write the function/method in the Member Class without using the global space.</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>class Member {
static id = 0;
constructor(firstName, lastName, birthDay) {
Member.id++;
this.id = Member.id;
this.firstName = firstName;
this.lastName = lastName;
this.birthDay = birthDay;
this.age = getAge(birthDay);
}
}
const m1 = new Member('Oliver', 'Cruz', '11/13/1990');
console.log('m1:', m1.age); // 32 (as of Nov 13rd, 2022)
const m2 = new Member('Sophia', 'Brown', '11/30/1992');
console.log('m2:', m2.age); // 29 (as of Nov 13rd, 2022)
/**
* Calculate age function
* @param {String} birthDay - ex '11/13/1990'
* @returns {Number} - age
*/
function getAge(birthDay) {
const now = new Date();
const bd = new Date(birthDay);
const diff = now - bd;
const age = new Date(diff).getFullYear() - 1970;
return age;
}</code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74418052,
"author": "ksav",
"author_id": 5385381,
"author_profile": "https://Stackoverflow.com/users/5385381",
"pm_score": 2,
"selected": true,
"text": "class Member {\n static id = 0;\n\n constructor(firstName, lastName, birthDay) {\n Member.id++;\n this.id = Member.id;\n this.firstName = firstName;\n this.lastName = lastName;\n this.birthDay = birthDay;\n this.age = Member.getAge(birthDay);\n }\n\n /**\n * Calculate age function\n * @param {String} birthDay - ex '11/13/1990'\n * @returns {Number} - age\n */\n static getAge = (birthDay) => {\n const now = new Date();\n const bd = new Date(birthDay);\n const diff = now - bd;\n const age = new Date(diff).getFullYear() - 1970;\n\n return age;\n }\n}\n\nconst m1 = new Member('Oliver', 'Cruz', '11/13/1990');\nconsole.log('m1:', m1.age); // 32 (as of Nov 13rd, 2022)\n\nconst m2 = new Member('Sophia', 'Brown', '11/30/1992');\nconsole.log('m2:', m2.age); // 29 (as of Nov 13rd, 2022)"
},
{
"answer_id": 74418056,
"author": "Itz Blinkzy",
"author_id": 14057924,
"author_profile": "https://Stackoverflow.com/users/14057924",
"pm_score": 0,
"selected": false,
"text": "class Member {\n static id = 0;\n\n constructor(firstName, lastName, birthDay) {\n Member.id++;\n this.id = Member.id;\n this.firstName = firstName;\n this.lastName = lastName;\n this.birthDay = birthDay;\n this.age = this.getAge(birthDay);\n }\n getAge(birthDay) {\n const now = new Date();\n const bd = new Date(birthDay);\n const diff = now - bd;\n const age = new Date(diff).getFullYear() - 1970;\n\n return age;\n }\n}\nconst m2 = new Member('Sophia', 'Brown', '11/30/1992');\nconsole.log('m2:', m2.age);\n"
},
{
"answer_id": 74418085,
"author": "azhen7",
"author_id": 20341797,
"author_profile": "https://Stackoverflow.com/users/20341797",
"pm_score": 1,
"selected": false,
"text": "class Member {\n static id = 0;\n\n static getAge(birthDay) {\n const now = new Date();\n const bd = new Date(birthDay);\n const diff = now - bd;\n const age = new Date(diff).getFullYear() - 1970;\n\n return age;\n }\n\n constructor(firstName, lastName, birthDay) {\n Member.id++;\n this.id = Member.id;\n this.firstName = firstName;\n this.lastName = lastName;\n this.birthDay = birthDay;\n this.age = Member.getAge(birthDay);\n }\n}\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11451181/"
] |
74,418,042 | <p>Using Jmeter n my Json response couldn't extract the below <code>"_MESSAGE_"</code> response value as well need to capture first five value in our variable like (10000) alone</p>
<pre><code>"{\"_STATUS_\":\"SUCCESS\",\"_MESSAGE_\":\"10000,1111111111\"}"
</code></pre>
<p>Note : This is invalid json and dev team not supporting to build the right json.</p>
<p>it's high priority task - anyone have a solution for this issue. please share your input.</p>
<p>I am looking for the solution to extract the <code>"_MESSAGE_"</code> and need to capture first five value in our variable like (10000) alone</p>
| [
{
"answer_id": 74418052,
"author": "ksav",
"author_id": 5385381,
"author_profile": "https://Stackoverflow.com/users/5385381",
"pm_score": 2,
"selected": true,
"text": "class Member {\n static id = 0;\n\n constructor(firstName, lastName, birthDay) {\n Member.id++;\n this.id = Member.id;\n this.firstName = firstName;\n this.lastName = lastName;\n this.birthDay = birthDay;\n this.age = Member.getAge(birthDay);\n }\n\n /**\n * Calculate age function\n * @param {String} birthDay - ex '11/13/1990'\n * @returns {Number} - age\n */\n static getAge = (birthDay) => {\n const now = new Date();\n const bd = new Date(birthDay);\n const diff = now - bd;\n const age = new Date(diff).getFullYear() - 1970;\n\n return age;\n }\n}\n\nconst m1 = new Member('Oliver', 'Cruz', '11/13/1990');\nconsole.log('m1:', m1.age); // 32 (as of Nov 13rd, 2022)\n\nconst m2 = new Member('Sophia', 'Brown', '11/30/1992');\nconsole.log('m2:', m2.age); // 29 (as of Nov 13rd, 2022)"
},
{
"answer_id": 74418056,
"author": "Itz Blinkzy",
"author_id": 14057924,
"author_profile": "https://Stackoverflow.com/users/14057924",
"pm_score": 0,
"selected": false,
"text": "class Member {\n static id = 0;\n\n constructor(firstName, lastName, birthDay) {\n Member.id++;\n this.id = Member.id;\n this.firstName = firstName;\n this.lastName = lastName;\n this.birthDay = birthDay;\n this.age = this.getAge(birthDay);\n }\n getAge(birthDay) {\n const now = new Date();\n const bd = new Date(birthDay);\n const diff = now - bd;\n const age = new Date(diff).getFullYear() - 1970;\n\n return age;\n }\n}\nconst m2 = new Member('Sophia', 'Brown', '11/30/1992');\nconsole.log('m2:', m2.age);\n"
},
{
"answer_id": 74418085,
"author": "azhen7",
"author_id": 20341797,
"author_profile": "https://Stackoverflow.com/users/20341797",
"pm_score": 1,
"selected": false,
"text": "class Member {\n static id = 0;\n\n static getAge(birthDay) {\n const now = new Date();\n const bd = new Date(birthDay);\n const diff = now - bd;\n const age = new Date(diff).getFullYear() - 1970;\n\n return age;\n }\n\n constructor(firstName, lastName, birthDay) {\n Member.id++;\n this.id = Member.id;\n this.firstName = firstName;\n this.lastName = lastName;\n this.birthDay = birthDay;\n this.age = Member.getAge(birthDay);\n }\n}\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11004745/"
] |
74,418,063 | <p>This is simplified example of what Im working on</p>
<pre><code>return SizedBox(
width: 300,
height: 200,
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text('text line'),
Row(
children: [
Checkbox(
value: false,
onChanged: (bool? value) {}),
const Expanded(
child: Text(
'Lorem ipsum dolor sit amet, consectetur adipiscing elit,'
'sed do eiusmod tempor incididunt ut labore et dolore magna'
'aliqua. Ut enim ad minim veniam, quis nostrud exercitation'
'ullamco laboris nisi ut aliquip ex ea commodo consequat.'),
),
],
),
],
),
),
);
</code></pre>
<p>Since Im trying to vertical Align the checkbox(leading) in the row with the 3 lines of text(trailing).</p>
<p>Is it possible to modify the vertical alignment of the checkbox without having to go with a fully custom widget, like using a stack/positioned?</p>
<p>I have tried modifying with visual density, transform.translate with very little vertical control.
I tried to also both CheckBox and CheckBoxListTile using controlAffinity.leading, contentpadding.zero.</p>
<p><a href="https://i.stack.imgur.com/tIPQM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tIPQM.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74418940,
"author": "Yeasin Sheikh",
"author_id": 10157127,
"author_profile": "https://Stackoverflow.com/users/10157127",
"pm_score": 1,
"selected": false,
"text": "crossAxisAlignment: CrossAxisAlignment.start,"
},
{
"answer_id": 74419031,
"author": "Alwayss Bijoy",
"author_id": 8312884,
"author_profile": "https://Stackoverflow.com/users/8312884",
"pm_score": 0,
"selected": false,
"text": " CheckboxListTile(\n controlAffinity: ListTileControlAffinity.leading,\n title: Text('In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document or a typeface without relying on meaningful content. Lorem ipsum may be used as a placeholder before final copy is available.'),\n value: true, onChanged: (value) {}),\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11518948/"
] |
74,418,102 | <p>I am trying to split a very large (70 hours) mp3 file into smaller files. My first step is the get the timestamps using the silencedetect command in ffmpeg. It works fine for the first few timestamps, but unfortunately, the results are rounded to six significant digits.</p>
<p>The code I am executing is:</p>
<pre><code>ffmpeg -i input.mp3 -af silencedetect=d=3 -hide_banner -nostats -f null -
</code></pre>
<p>My results are:</p>
<pre><code>Input #0, mp3, from 'input.mp3':
Duration: 70:46:05.32, start: 0.050113, bitrate: 64 kb/s
Stream #0:0: Audio: mp3, 22050 Hz, stereo, fltp, 64 kb/s
Stream mapping:
Stream #0:0 -> #0:0 (mp3 (mp3float) -> pcm_s16le (native))
Press [q] to stop, [?] for help
Output #0, null, to 'pipe:':
Metadata:
encoder : Lavf58.29.100
Stream #0:0: Audio: pcm_s16le, 22050 Hz, stereo, s16, 705 kb/s
Metadata:
encoder : Lavc58.54.100 pcm_s16le
[silencedetect @ 0x5590d08bd700] silence_start: 10.6895
[silencedetect @ 0x5590d08bd700] silence_end: 15.0054 | silence_duration: 4.31587
[silencedetect @ 0x5590d08bd700] silence_start: 446.958
[silencedetect @ 0x5590d08bd700] silence_end: 450.959 | silence_duration: 4.00168
[silencedetect @ 0x5590d08bd700] silence_start: 1168.17
[silencedetect @ 0x5590d08bd700] silence_end: 1172.17 | silence_duration: 4.00694
[silencedetect @ 0x5590d08bd700] silence_start: 1880.8
[silencedetect @ 0x5590d08bd700] silence_end: 1884.8 | silence_duration: 3.99265
...
[silencedetect @ 0x5590d08bd700] silence_start: 123108
[silencedetect @ 0x5590d08bd700] silence_end: 123111 | silence_duration: 3.61946
[silencedetect @ 0x5590d08bd700] silence_start: 123286
[silencedetect @ 0x5590d08bd700] silence_end: 123290 | silence_duration: 4.01646
[silencedetect @ 0x5590d08bd700] silence_start: 124229
[silencedetect @ 0x5590d08bd700] silence_end: 124233 | silence_duration: 4.01846
[silencedetect @ 0x5590d08bd700] silence_start: 124442
[silencedetect @ 0x5590d08bd700] silence_end: 124446 | silence_duration: 4.0298
...
</code></pre>
<p>Rounding to the nearest second is not sufficient for my purposes. Ideally, I would like each timestamp to be accurate to the hundredth of a second or something similar. Does anybody know a way to achieve this?</p>
| [
{
"answer_id": 74419105,
"author": "Brad",
"author_id": 362536,
"author_profile": "https://Stackoverflow.com/users/362536",
"pm_score": 0,
"selected": false,
"text": "static inline char *av_ts_make_time_string(char *buf, int64_t ts, AVRational *tb)\n{\n if (ts == AV_NOPTS_VALUE) snprintf(buf, AV_TS_MAX_STRING_SIZE, \"NOPTS\");\n else snprintf(buf, AV_TS_MAX_STRING_SIZE, \"%.6g\", av_q2d(*tb) * ts);\n return buf;\n}\n"
},
{
"answer_id": 74424056,
"author": "kesh",
"author_id": 4516027,
"author_profile": "https://Stackoverflow.com/users/4516027",
"pm_score": 2,
"selected": true,
"text": "ametadata=print:file=-"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20489710/"
] |
74,418,107 | <p>I have data with timestamps. Users respond to questions and they also select day period (morning or evening). I want to drop rows where recorded timestamp and day period mismatch. So check, if timestamp is between 6am-12pm and discard if "daytime" is "evening", etc.</p>
<pre><code>df
timestamps daytime
2020-04-10 11:40 Morning
2022-04-12 19:32 Morning *(discard)*
2022-04-12 20:53 Evening
2022-04-15 22:50 Morning *(discard)*
2022-04-16 09:31 Evening*(discard)*
</code></pre>
<p>The rule should be: if between 06:00-12:00 and 'daytime' is Evening ==> Remove row/ if between 18:00 - 00:00 and 'daytime' is Morning ==> Remove row</p>
<p>I've tried:</p>
<pre><code>remove = df[ (6< df['timestamp'].dt.hour < 12 & df['period'] == 'Evening')
| (18< df['timestamp'].dt.hour < 23 & df['period'] == 'Morning')]
df.drop(remove , inplace=True)
</code></pre>
| [
{
"answer_id": 74419105,
"author": "Brad",
"author_id": 362536,
"author_profile": "https://Stackoverflow.com/users/362536",
"pm_score": 0,
"selected": false,
"text": "static inline char *av_ts_make_time_string(char *buf, int64_t ts, AVRational *tb)\n{\n if (ts == AV_NOPTS_VALUE) snprintf(buf, AV_TS_MAX_STRING_SIZE, \"NOPTS\");\n else snprintf(buf, AV_TS_MAX_STRING_SIZE, \"%.6g\", av_q2d(*tb) * ts);\n return buf;\n}\n"
},
{
"answer_id": 74424056,
"author": "kesh",
"author_id": 4516027,
"author_profile": "https://Stackoverflow.com/users/4516027",
"pm_score": 2,
"selected": true,
"text": "ametadata=print:file=-"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20489776/"
] |
74,418,132 | <p>Is it possible to do an UPDATE query but not actually update a value and leave it alone?</p>
<p>I would like to have queries like this:</p>
<pre><code>UPDATE homes SET age = 25, SET name = (don’t update) WHERE id = 1.
</code></pre>
<p>Of course I could just leave out "SET name =", but I am using this as part of prepared statements in PHP.
The query is first prepared and then queries that match it are sent. But I frequently want to not set a value, but not begin yet another prepared query. Here is an example of my use case</p>
<pre><code>$figures = [ ['age' => 'foo1', 'name' => 'DO NOT UPDATE'], ['age' => 'foo1', 'name' => 'bar1'], ['age' => 'foo2', 'name' => 'bar2']];
$stmt = $pdo->prepare("UPDATE homes SET age = ?, name = ?");
foreach ($figures as $row) {
$stmt->execute([$row['age'], $row['name']]);
}
</code></pre>
<p>The query and the data values can be changed. I'd like to use a single UPDATE prepared statement instead of doing 100s of different prepared statements with a different prepare() for each.</p>
| [
{
"answer_id": 74419105,
"author": "Brad",
"author_id": 362536,
"author_profile": "https://Stackoverflow.com/users/362536",
"pm_score": 0,
"selected": false,
"text": "static inline char *av_ts_make_time_string(char *buf, int64_t ts, AVRational *tb)\n{\n if (ts == AV_NOPTS_VALUE) snprintf(buf, AV_TS_MAX_STRING_SIZE, \"NOPTS\");\n else snprintf(buf, AV_TS_MAX_STRING_SIZE, \"%.6g\", av_q2d(*tb) * ts);\n return buf;\n}\n"
},
{
"answer_id": 74424056,
"author": "kesh",
"author_id": 4516027,
"author_profile": "https://Stackoverflow.com/users/4516027",
"pm_score": 2,
"selected": true,
"text": "ametadata=print:file=-"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14746212/"
] |
74,418,139 | <p>Using docker-compose, I am running a postgres container (db). The data itself is persistently stored on my Windows machine. And this works. I am unable to get another container running a python application to access the database.</p>
<p>My docker-compose file is as follows, where I use ## to denote some options that I've tried that :</p>
<pre><code>version: '0.1'
services
db: #also the server name
image: postgres:15.0
restart: always
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: my_password
##POSTGRES_HOST_AUTH_METHOD: trust
##POSTGRES_HOST: postgres
##PGDATA: d:/pg #/var/lib/postgresql/data/pgdata
ports:
#port on machine:port on container
- 1234:5432
volumes:
#path on my windows machine:path to postgres default folder
- D:/pg:/var/lib/postgresql/data
privileged:
true
app:
image: simple_python_debug
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=my_password
- POSTGRES_PORT=5432
- POSTGRES_DB_NAME=postgres
- POSTGRES_HOSTNAME=localhost
depends_on:
- db
</code></pre>
<p>My dockerfile (simple_python_debug) for the python script is</p>
<pre><code>FROM python:3.9
# Install pip requirements
COPY requirements.txt .
RUN pip3 install -r requirements.txt
WORKDIR /app #this is where the .py file is located
COPY . /app
# Creates a non-root user with an explicit UID and adds permission to access the /app folder
# For more info, please refer to https://aka.ms/vscode-docker-python-configure-containers
RUN adduser -u 5678 --disabled-password --gecos "" appuser && chown -R appuser /app
USER appuser
CMD ["python", "test.py"]
</code></pre>
<p>The dockerfile for postgres is simply:</p>
<pre><code>services:
db:
image: postgres:15.0
restart: always
environment:
POSTGRES_PASSWORD: my_password
</code></pre>
<p>test.py (stored in /app) contains</p>
<pre><code>import os
from sqlalchemy import create_engine
port = os.getenv('POSTGRES_PORT')#'5432'
password = os.getenv('POSTGRES_PASSWORD')#'my_password'
user = os.getenv('POSTGRES_USER')#'postgres'
hostname = os.getenv('POSTGRES_HOSTNAME') #'localhost'
database_name = os.getenv('POSTGRES_DB_NAME') #'postgres'
connection_params = 'postgresql+psycopg2://' + user + ':' + password + '@' + hostname + '/' + database_name
#+\ "connect_args = {'options': '-csearch_path={}'.format(" + schema + ')}'
engine = create_engine(connection_params)
</code></pre>
<p>With docker desktop running on my local windows machine and postgres service on the local windows machine shutdown for good measure, I run</p>
<p><code>.../test>docker-compose up</code> from powershell 7; part of the message for the working postgres container is:</p>
<pre><code>test-db-1 |
test-db-1 | PostgreSQL Database directory appears to contain a database; Skipping initialization
test-db-1 |
test-db-1 | 2022-11-12 15:27:14.665 UTC [1] LOG: starting PostgreSQL 15.0 (Debian 15.0-1.pgdg110+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit
test-db-1 | 2022-11-12 15:27:14.665 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432
test-db-1 | 2022-11-12 15:27:14.665 UTC [1] LOG: listening on IPv6 address "::", port 5432
test-db-1 | 2022-11-12 15:27:14.674 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
</code></pre>
<p>test.py fails on calling create_engine; the tail of the error message is</p>
<pre><code>test-app-1 | Is the server running on host "localhost" (127.0.0.1) and accepting
test-app-1 | TCP/IP connections on port 5432?
test-app-1 | could not connect to server: Cannot assign requested address
test-app-1 | Is the server running on host "localhost" (::1) and accepting
test-app-1 | TCP/IP connections on port 5432?
test-app-1 |
test-app-1 | (Background on this error at: https://sqlalche.me/e/14/e3q8)
</code></pre>
<p>There are several stack overflow related questions and the error message. There's even medium articles on using postgres with python and docker.</p>
<p><a href="https://stefanopassador.medium.com/docker-compose-with-python-and-posgresql-45c4c5174299" rel="nofollow noreferrer">https://stefanopassador.medium.com/docker-compose-with-python-and-posgresql-45c4c5174299</a></p>
<p><a href="https://stackoverflow.com/questions/37099564/docker-how-can-run-the-psql-command-in-the-postgres-container">Docker - How can run the psql command in the postgres container?</a></p>
<p><a href="https://stackoverflow.com/questions/57404177/cant-connect-python-app-container-to-local-postgres">Can't connect python app container to local postgres</a></p>
<p><a href="https://stackoverflow.com/questions/24319662/from-inside-of-a-docker-container-how-do-i-connect-to-the-localhost-of-the-mach">From inside of a Docker container, how do I connect to the localhost of the machine?</a></p>
<p>Perhaps I'm missing something simple, but any suggestions or pointing to the appropriate docker docs could help get me unstuck.</p>
<p>EDIT:
As recommended by @JRichardz complete error message is below for posterity:</p>
<pre><code>test-app-1 | Traceback (most recent call last):
test-app-1 | File "/usr/local/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 3212, in _wrap_pool_connect
test-app-1 | return fn()
test-app-1 | File "/usr/local/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 307, in connect
test-app-1 | return _ConnectionFairy._checkout(self)
test-app-1 | File "/usr/local/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 767, in _checkout
test-app-1 | fairy = _ConnectionRecord.checkout(pool)
test-app-1 | File "/usr/local/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 425, in checkout
test-app-1 | rec = pool._do_get()
test-app-1 | File "/usr/local/lib/python3.9/site-packages/sqlalchemy/pool/impl.py", line 146, in _do_get
test-app-1 | self._dec_overflow()
test-app-1 | File "/usr/local/lib/python3.9/site-packages/sqlalchemy/util/langhelpers.py", line 70, in __exit__
test-app-1 | compat.raise_(
test-app-1 | File "/usr/local/lib/python3.9/site-packages/sqlalchemy/util/compat.py", line 207, in raise_
test-app-1 | raise exception
test-app-1 | File "/usr/local/lib/python3.9/site-packages/sqlalchemy/pool/impl.py", line 143, in _do_get
test-app-1 | return self._create_connection()
test-app-1 | File "/usr/local/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 253, in _create_connection
test-app-1 | return _ConnectionRecord(self)
test-app-1 | File "/usr/local/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 368, in __init__
test-app-1 | self.__connect()
test-app-1 | File "/usr/local/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 611, in __connect
test-app-1 | pool.logger.debug("Error on connect(): %s", e)
test-app-1 | File "/usr/local/lib/python3.9/site-packages/sqlalchemy/util/langhelpers.py", line 70, in __exit__
test-app-1 | compat.raise_(
test-app-1 | File "/usr/local/lib/python3.9/site-packages/sqlalchemy/util/compat.py", line 207, in raise_
test-app-1 | raise exception
test-app-1 | File "/usr/local/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 605, in __connect
test-app-1 | connection = pool._invoke_creator(self)
test-app-1 | File "/usr/local/lib/python3.9/site-packages/sqlalchemy/engine/create.py", line 578, in connect
test-app-1 | return dialect.connect(*cargs, **cparams)
test-app-1 | File "/usr/local/lib/python3.9/site-packages/sqlalchemy/engine/default.py", line 584, in connect
test-app-1 | return self.dbapi.connect(*cargs, **cparams)
test-app-1 | File "/usr/local/lib/python3.9/site-packages/psycopg2/__init__.py", line 122, in connect
test-app-1 | conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
test-app-1 | psycopg2.OperationalError: could not connect to server: Connection refused
test-app-1 | Is the server running on host "localhost" (127.0.0.1) and accepting
test-app-1 | TCP/IP connections on port 5432?
test-app-1 | could not connect to server: Cannot assign requested address
test-app-1 | Is the server running on host "localhost" (::1) and accepting
test-app-1 | TCP/IP connections on port 5432?
test-app-1 |
test-app-1 |
test-app-1 | The above exception was the direct cause of the following exception:
test-app-1 |
test-app-1 | Traceback (most recent call last):
test-app-1 | File "/app/btc_sma_recommendations_1_inflection.py", line 51, in <module>
test-app-1 | with engine.connect() as connection:
test-app-1 | File "/usr/local/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 3166, in connect
test-app-1 | return self._connection_cls(self, close_with_result=close_with_result)
test-app-1 | File "/usr/local/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 96, in __init__
test-app-1 | else engine.raw_connection()
test-app-1 | File "/usr/local/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 3245, in raw_connection
test-app-1 | return self._wrap_pool_connect(self.pool.connect, _connection)
test-app-1 | File "/usr/local/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 3215, in _wrap_pool_connect
test-app-1 | Connection._handle_dbapi_exception_noconnection(
test-app-1 | File "/usr/local/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 2069, in _handle_dbapi_exception_noconnection
test-app-1 | util.raise_(
test-app-1 | File "/usr/local/lib/python3.9/site-packages/sqlalchemy/util/compat.py", line 207, in raise_
test-app-1 | raise exception
test-app-1 | File "/usr/local/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 3212, in _wrap_pool_connect
test-app-1 | return fn()
test-app-1 | File "/usr/local/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 307, in connect
test-app-1 | return _ConnectionFairy._checkout(self)
test-app-1 | File "/usr/local/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 767, in _checkout
test-app-1 | fairy = _ConnectionRecord.checkout(pool)
test-app-1 | File "/usr/local/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 425, in checkout
test-app-1 | rec = pool._do_get()
test-app-1 | File "/usr/local/lib/python3.9/site-packages/sqlalchemy/pool/impl.py", line 146, in _do_get
test-app-1 | self._dec_overflow()
test-app-1 | File "/usr/local/lib/python3.9/site-packages/sqlalchemy/util/langhelpers.py", line 70, in __exit__
test-app-1 | compat.raise_(
test-app-1 | File "/usr/local/lib/python3.9/site-packages/sqlalchemy/util/compat.py", line 207, in raise_
test-app-1 | raise exception
test-app-1 | File "/usr/local/lib/python3.9/site-packages/sqlalchemy/pool/impl.py", line 143, in _do_get
test-app-1 | return self._create_connection()
test-app-1 | File "/usr/local/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 253, in _create_connection
test-app-1 | return _ConnectionRecord(self)
test-app-1 | File "/usr/local/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 368, in __init__
test-app-1 | self.__connect()
test-app-1 | File "/usr/local/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 611, in __connect
test-app-1 | pool.logger.debug("Error on connect(): %s", e)
test-app-1 | File "/usr/local/lib/python3.9/site-packages/sqlalchemy/util/langhelpers.py", line 70, in __exit__
test-app-1 | compat.raise_(
test-app-1 | File "/usr/local/lib/python3.9/site-packages/sqlalchemy/util/compat.py", line 207, in raise_
test-app-1 | raise exception
test-app-1 | File "/usr/local/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 605, in __connect
test-app-1 | connection = pool._invoke_creator(self)
test-app-1 | File "/usr/local/lib/python3.9/site-packages/sqlalchemy/engine/create.py", line 578, in connect
test-app-1 | return dialect.connect(*cargs, **cparams)
test-app-1 | File "/usr/local/lib/python3.9/site-packages/sqlalchemy/engine/default.py", line 584, in connect
test-app-1 | return self.dbapi.connect(*cargs, **cparams)
test-app-1 | File "/usr/local/lib/python3.9/site-packages/psycopg2/__init__.py", line 122, in connect
test-app-1 | conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
test-app-1 | sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) could not connect to server: Connection refused
test-app-1 | Is the server running on host "localhost" (127.0.0.1) and accepting
test-app-1 | TCP/IP connections on port 5432?
test-app-1 | could not connect to server: Cannot assign requested address
test-app-1 | Is the server running on host "localhost" (::1) and accepting
test-app-1 | TCP/IP connections on port 5432?
test-app-1 |
test-app-1 | (Background on this error at: https://sqlalche.me/e/14/e3q8)
test-app-1 exited with code 1
test-db-1 |
test-db-1 | PostgreSQL Database directory appears to contain a database; Skipping initialization
test-db-1 |
test-db-1 | 2022-11-14 00:00:02.724 UTC [1] LOG: starting PostgreSQL 15.0 (Debian 15.0-1.pgdg110+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit
test-db-1 | 2022-11-14 00:00:02.724 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432
test-db-1 | 2022-11-14 00:00:02.724 UTC [1] LOG: listening on IPv6 address "::", port 5432
test-db-1 | 2022-11-14 00:00:02.731 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
test-db-1 | 2022-11-14 00:00:02.771 UTC [29] LOG: database system was shut down at 2022-11-13 02:41:42 UTC
test-db-1 | 2022-11-14 00:00:02.867 UTC [1] LOG: database system is ready to accept connections
</code></pre>
| [
{
"answer_id": 74419105,
"author": "Brad",
"author_id": 362536,
"author_profile": "https://Stackoverflow.com/users/362536",
"pm_score": 0,
"selected": false,
"text": "static inline char *av_ts_make_time_string(char *buf, int64_t ts, AVRational *tb)\n{\n if (ts == AV_NOPTS_VALUE) snprintf(buf, AV_TS_MAX_STRING_SIZE, \"NOPTS\");\n else snprintf(buf, AV_TS_MAX_STRING_SIZE, \"%.6g\", av_q2d(*tb) * ts);\n return buf;\n}\n"
},
{
"answer_id": 74424056,
"author": "kesh",
"author_id": 4516027,
"author_profile": "https://Stackoverflow.com/users/4516027",
"pm_score": 2,
"selected": true,
"text": "ametadata=print:file=-"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1873237/"
] |
74,418,156 | <p>I have this assemly code for ARM.</p>
<pre><code>.text
.global main
fib:
push { r4}
MOV r1, #1
MOV r2, #0
MOV r3, #1
loop:
CMP r3, r0
BGE exit
mov r4,r1
ADD r1, r1,r2
mov r2, r4
add r3, r3, #1
B loop
exit:
pop {r4}
mov r0, r1
MOV PC, lr
main:
mov r0, #13
push {lr}
BL fib
pop {lr}
mov r1, r0
ldr r0, =output_string
push {lr}
bl printf
pop {lr}
MOV PC, lr
@ The 'data' section contains static data for our program
.data
output_string:
.asciz "%d\n"
</code></pre>
<p>But I am wondering, why do I need the ".global main" for it to compile? I read on an answer <a href="https://stackoverflow.com/questions/17882936/global-main-in-assembly">here</a> that this tells the compiler that it will be visible to the linker because other object files will use it. But don't I only have one object file here?</p>
<p>Does it also tell us that the program should start there, is it therefore it doesn't work without it?</p>
| [
{
"answer_id": 74419105,
"author": "Brad",
"author_id": 362536,
"author_profile": "https://Stackoverflow.com/users/362536",
"pm_score": 0,
"selected": false,
"text": "static inline char *av_ts_make_time_string(char *buf, int64_t ts, AVRational *tb)\n{\n if (ts == AV_NOPTS_VALUE) snprintf(buf, AV_TS_MAX_STRING_SIZE, \"NOPTS\");\n else snprintf(buf, AV_TS_MAX_STRING_SIZE, \"%.6g\", av_q2d(*tb) * ts);\n return buf;\n}\n"
},
{
"answer_id": 74424056,
"author": "kesh",
"author_id": 4516027,
"author_profile": "https://Stackoverflow.com/users/4516027",
"pm_score": 2,
"selected": true,
"text": "ametadata=print:file=-"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418156",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10916973/"
] |
74,418,158 | <p>I currently have sixteen images (A,B,C,D,E,F,G,...) which must be concatenated into one as part of a Tensorflow Dataset workflow. Each image is 128 x 128 and has the shape of (128, 128, 3). The final output should be a 512 x 512 image of shape (512,512,3). All of the images come from an image sequence, known as <code>img_seq</code>. This img_seq has the shape of (None, 128, 128, 3)</p>
<p>Right now, this is accomplished through the following code:</p>
<pre><code>@tf.function
def glue_to_one(imgs_seq):
first_row= tf.concat((imgs_seq[0], imgs_seq[1],imgs_seq[2],imgs_seq[3]), 0)
second_row = tf.concat((imgs_seq[4], imgs_seq[5], imgs_seq[6], imgs_seq[7]), 0)
third_row = tf.concat((imgs_seq[8], imgs_seq[9], imgs_seq[10], imgs_seq[11]), 0)
fourth_row = tf.concat((imgs_seq[12], imgs_seq[13], imgs_seq[14], imgs_seq[15]), 0)
img_glue = tf.stack((first_row, second_row, third_row, fourth_row), axis=1)
img_glue = tf.reshape(img_glue, [512,512,3])
return img_glue
</code></pre>
<p>It is suspected that this method is inefficient and is learning to a bottleneck.
A different approach would be to allocate a 512 x 512 tensor and then replace the elements. Would this be more efficient? How would it be done? Can you please recommend a better approach?</p>
| [
{
"answer_id": 74419105,
"author": "Brad",
"author_id": 362536,
"author_profile": "https://Stackoverflow.com/users/362536",
"pm_score": 0,
"selected": false,
"text": "static inline char *av_ts_make_time_string(char *buf, int64_t ts, AVRational *tb)\n{\n if (ts == AV_NOPTS_VALUE) snprintf(buf, AV_TS_MAX_STRING_SIZE, \"NOPTS\");\n else snprintf(buf, AV_TS_MAX_STRING_SIZE, \"%.6g\", av_q2d(*tb) * ts);\n return buf;\n}\n"
},
{
"answer_id": 74424056,
"author": "kesh",
"author_id": 4516027,
"author_profile": "https://Stackoverflow.com/users/4516027",
"pm_score": 2,
"selected": true,
"text": "ametadata=print:file=-"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19961760/"
] |
74,418,171 | <p>I have a simple django app where users can create and login to their accounts.</p>
<p>When a user is registering for a new account, the user object is created and saved in the database with the <code>is_active</code> flag set to false. Once the user clicks the confirmation email, the user object has its <code>is_active</code> flag set to true.</p>
<p>I have built out a password reset flow using Django's views: <code>PasswordResetView</code>, <code>PasswordResetDoneView</code>, <code>PasswordResetConfirmView</code>, and <code>PasswordResetCompleteView</code>.</p>
<p>Everything works as expected unless I am trying to reset the password for an account which has not yet been activated (<code>is_active == False</code>), in which case, the reset password email is never sent to the user.</p>
<p>The edge case I am considering here is for a user who created an account, and never clicked the registration link which expires after 72 hours, and thus have a user account which exists but is not active. Then the user wants to get a new registration link, and to do so I require a user to enter their username and password (so that no malicious actors can spam a random users email inbox with new registration link emails). If the user has since forgotten their password, they are bricked and cannot activate their account, nor can they refresh their password.</p>
<p>How can I send a password reset link to accounts which are not active?</p>
| [
{
"answer_id": 74425568,
"author": "redtomato",
"author_id": 9542315,
"author_profile": "https://Stackoverflow.com/users/9542315",
"pm_score": 2,
"selected": true,
"text": "PasswordResetForm"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9542315/"
] |
74,418,174 | <p>I am trying to create a function</p>
<p><code>update_money :: Transaction -> Int -> Int</code></p>
<p>that takes a transaction and the current amount of money that you have, and returns the amount of money that you have
after the transaction. So if the transaction buys a stock the amount of money you have will decrease,
and if the transaction sells a stock the amount of money you have will increase. For example:</p>
<pre><code>ghci> update_money ('B', 1, 10, "VTI", 5) 100
90
</code></pre>
<pre><code>ghci> update_money ('S', 2, 10, "VTI", 5) 100
120
</code></pre>
<p>This is the data that has been provided:</p>
<pre><code>
type Transaction = (Char, Int, Int, String, Int)
test_log :: [Transaction]
test_log = [('B', 100, 1104, "VTI", 1),
('B', 200, 36, "ONEQ", 3),
('B', 50, 1223, "VTI", 5),
('S', 150, 1240, "VTI", 9),
('B', 100, 229, "IWRD", 10),
('S', 200, 32, "ONEQ", 11),
('S', 100, 210, "IWRD", 12)]
</code></pre>
<p>Here is my attempt at the problem:</p>
<pre><code>update_money :: Transaction -> Int -> Int
update_money x (action, units, price, stocks, day) =
let money_type | action == 'B' = show (units - x)
| action == 'S' = show (units + x)
| otherwise = "Incorrect, please input either B for bought or S for sold. "
in
money_type
</code></pre>
<p>However, when stating action and (show units) on the same line I am getting a type conversion so am not sure in how I can approach this.</p>
| [
{
"answer_id": 74418371,
"author": "Daniel Wagner",
"author_id": 791604,
"author_profile": "https://Stackoverflow.com/users/791604",
"pm_score": 2,
"selected": false,
"text": "import qualified Data.Map as M\n\ntrans lst = M.fromListWith (+)\n [ (stock, (if transaction == 'B' then id else negate) (units * price_per_unit))\n | (transaction, units, price_per_unit, stock, day) <- lst\n ]\n"
},
{
"answer_id": 74452098,
"author": "shy45",
"author_id": 20313707,
"author_profile": "https://Stackoverflow.com/users/20313707",
"pm_score": 1,
"selected": true,
"text": "update_money (action, units, price, stocks, day) sum = \n let money_type | action == 'B' = sum - units * price\n | action == 'S' = sum + units * price\n | otherwise = 0\n in\n money_type\n\nmain = print $ update_money ('S', 2, 10, \"VTI\", 5) 100\n\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,418,177 | <p>The goal is to create a simple and CSS-only modal window (popup), when the user clicks a link.</p>
<p>With no dependencies or any kind of script, and with as less code as possible.</p>
| [
{
"answer_id": 74418371,
"author": "Daniel Wagner",
"author_id": 791604,
"author_profile": "https://Stackoverflow.com/users/791604",
"pm_score": 2,
"selected": false,
"text": "import qualified Data.Map as M\n\ntrans lst = M.fromListWith (+)\n [ (stock, (if transaction == 'B' then id else negate) (units * price_per_unit))\n | (transaction, units, price_per_unit, stock, day) <- lst\n ]\n"
},
{
"answer_id": 74452098,
"author": "shy45",
"author_id": 20313707,
"author_profile": "https://Stackoverflow.com/users/20313707",
"pm_score": 1,
"selected": true,
"text": "update_money (action, units, price, stocks, day) sum = \n let money_type | action == 'B' = sum - units * price\n | action == 'S' = sum + units * price\n | otherwise = 0\n in\n money_type\n\nmain = print $ update_money ('S', 2, 10, \"VTI\", 5) 100\n\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6719976/"
] |
74,418,220 | <p>I'm trying to get some text using Cheerio that is placed after a single <code><br></code> tag.</p>
<p>I've already tried the following lines:</p>
<pre><code>let price = $(this).nextUntil('.col.search_price.discounted.responsive_secondrow').find('br').text().trim();
let price = $(this).nextUntil('.col.search_price.discounted.responsive_secondrow.br').text().trim();
</code></pre>
<p>Here is the HTML I'm trying to scrape:</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-html lang-html prettyprint-override"><code><div class="col search_price_discount_combined responsive_secondrow" data-price-final="5039">
<div class="col search_discount responsive_secondrow">
<span>-90%</span>
</div>
<div class="col search_price discounted responsive_secondrow">
<span style="color: #888888;"><strike>ARS$ 503,99</strike></span><br>ARS$ 50,39
</div>
</div></code></pre>
</div>
</div>
</p>
<p>I would like to get "ARS$ 50,39".</p>
| [
{
"answer_id": 74418458,
"author": "userx",
"author_id": 6632888,
"author_profile": "https://Stackoverflow.com/users/6632888",
"pm_score": 0,
"selected": false,
"text": "$('.col.search_price.discounted.responsive_secondrow').html().trim().split('<br>')\n"
},
{
"answer_id": 74418510,
"author": "ggorlen",
"author_id": 6243352,
"author_profile": "https://Stackoverflow.com/users/6243352",
"pm_score": 2,
"selected": true,
"text": ".contents().last()"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418220",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14445367/"
] |
74,418,239 | <p>I'm rather new to Angular and have tried implementing Lazy Loading but unable to see chunks while loading</p>
<p><strong>here is my project structure</strong> :</p>
<p>[![enter image description here][2]][2]</p>
<p><strong>my code as follows</strong>:
features routing module</p>
<pre><code>import { Injectable, NgModule } from '@angular/core';
import { Routes, RouterModule} from '@angular/router';
import { HomeComponent } from './HomeComponent/home-component.component';
const routes: Routes = [
{ path: "", component: HomeComponent, children:[
{ path: "home", component: HomeComponent }
]},
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class FeatureRoutingModule {
}
</code></pre>
<p>features module</p>
<pre><code>import { CommonModule } from "@angular/common";
import { NgModule } from "@angular/core";
import { ReactiveFormsModule } from "@angular/forms";
import { HomeComponent } from "./HomeComponent/home-component.component";
import { FeatureRoutingModule } from "./feature.routing.module";
import { Signup } from "./SignupComponent/signup.component";
@NgModule({
imports: [FeatureRoutingModule ,CommonModule, ReactiveFormsModule],// importing loaded childs here
declarations:[Signup , HomeComponent]// declaring components here
})
export class FeatureModule {
}
</code></pre>
<p>app-routing module</p>
<pre><code>import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { CatalogComponentComponent } from './catalog/catalog-component/catalog-component.component';
const route1: Routes=[
{path:'catalog' , component: CatalogComponentComponent},
{path: 'home' , loadChildren: ()=> import('./FeaturesModules/feature.module').then(m=>m.FeatureModule)}
]
@NgModule({
imports: [RouterModule.forRoot(route1)],
exports: [RouterModule]
})
export class AppRoutingModule { }
</code></pre>
<p>app-module</p>
<pre><code>import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HeaderComponentComponent } from './shared/header-component/header-component.component';
import { HttpClientModule } from '@angular/common/http';
import { FeatureModule } from './FeaturesModules/feature.module';
import { CatalogComponentComponent } from './catalog/catalog-component/catalog-component.component';
@NgModule({
declarations: [
AppComponent,
HeaderComponentComponent,
CatalogComponentComponent
],
imports: [
BrowserModule,
AppRoutingModule,
ReactiveFormsModule,
HttpClientModule,
FeatureModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HeaderComponentComponent } from './shared/header-component/header-component.component';
import { HttpClientModule } from '@angular/common/http';
import { FeatureModule } from './FeaturesModules/feature.module';
import { CatalogComponentComponent } from './catalog/catalog-component/catalog-component.component';
@NgModule({
declarations: [
AppComponent,
HeaderComponentComponent,
CatalogComponentComponent
],
imports: [
BrowserModule,
AppRoutingModule,
ReactiveFormsModule,
HttpClientModule,
FeatureModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
</code></pre>
<p>edit : updated app routing module module path
[1]: <a href="https://i.stack.imgur.com/NqlgR.png" rel="nofollow noreferrer">https://i.stack.imgur.com/NqlgR.png</a>
[2]: <a href="https://i.stack.imgur.com/S7GPS.png" rel="nofollow noreferrer">https://i.stack.imgur.com/S7GPS.png</a>
[3]: <a href="https://i.stack.imgur.com/fHR4F.png" rel="nofollow noreferrer">https://i.stack.imgur.com/fHR4F.png</a>
[4]: <a href="https://i.stack.imgur.com/gB60q.png" rel="nofollow noreferrer">https://i.stack.imgur.com/gB60q.png</a>
[5]: <a href="https://i.stack.imgur.com/mNp3e.png" rel="nofollow noreferrer">https://i.stack.imgur.com/mNp3e.png</a>
[6]: <a href="https://i.stack.imgur.com/oz3qg.png" rel="nofollow noreferrer">https://i.stack.imgur.com/oz3qg.png</a></p>
| [
{
"answer_id": 74418305,
"author": "Parth M. Dave",
"author_id": 12119351,
"author_profile": "https://Stackoverflow.com/users/12119351",
"pm_score": 1,
"selected": false,
"text": "home"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12876430/"
] |
74,418,243 | <p>The following is meant to toggle stylesheets:</p>
<pre><code>body.light {
background: var(--bg);
color: var(--text);
& a {
color: var(--link_color);
}
}
body.dark {
color: var(--bg);
background: var(--text);
& a {
color: white;
}
}
</code></pre>
<p>This snippet is in the last loaded file, amongst a few CSS files.</p>
<p>Problem: while the attributes are executed properly, the nesting for the selectors is not being picked up (It was expected the ampersand was the proper way to go).</p>
<p>There is a framework CSS file (loaded before the file where this code is placed) and it is those attributes that are executed.</p>
<p>What are the syntactic requirements to run properly nested selectors (be they native tag selectors (such as `a) or user-defined selectors?</p>
<p><strong>update</strong></p>
<p>The theme is being generated via a <code>cookies[:theme]</code>
and the body tag adopts it this way:</p>
<pre><code><body class="<%= cookies[:theme] %>">
</code></pre>
| [
{
"answer_id": 74418336,
"author": "Christian",
"author_id": 3842598,
"author_profile": "https://Stackoverflow.com/users/3842598",
"pm_score": 1,
"selected": false,
"text": ">"
},
{
"answer_id": 74418378,
"author": "John Li",
"author_id": 20436957,
"author_profile": "https://Stackoverflow.com/users/20436957",
"pm_score": 3,
"selected": true,
"text": "&"
},
{
"answer_id": 74418557,
"author": "Lakruwan Pathirage",
"author_id": 12383492,
"author_profile": "https://Stackoverflow.com/users/12383492",
"pm_score": 1,
"selected": false,
"text": "<div class=\"parent\">\n parent\n <div class=\"child\">\n child\n <div class=\"container desc\">container</div>\n </div>\n</div>\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2291357/"
] |
74,418,274 | <p>Just like the title, I want a box with size 320px*40px, with 4 smaller boxes, size 80px*40px, and with no margin or padding. I used <code>* { margin: 0; padding: 0; }</code>, but the margin is still there.</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-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>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.box {
height: 40px;
width: 320px;
border-top: 3px solid #ff8500;
border-bottom: 1px solid #edeef0;
}
.box .minibox {
padding: 0;
margin: 0;
text-decoration: none;
display: inline-block;
font-size: 12px;
color: #4C4C4C;
width: 80px;
height: 40px;
line-height: 40px;
text-align: center;
}
.box .minibox:hover {
background-color: #edeef0;
color: #ff8400;
}
</style>
</head>
<body>
<div class="box">
<a href="#" class="minibox">guideline</a>
<a href="#" class="minibox">guideline</a>
<a href="#" class="minibox">guideline</a>
<a href="#" class="minibox">guideline</a>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
<p>I tried to add <code>margin: 0; padding: 0;</code> in the selector of the tag, but nothing happened.</p>
| [
{
"answer_id": 74418336,
"author": "Christian",
"author_id": 3842598,
"author_profile": "https://Stackoverflow.com/users/3842598",
"pm_score": 1,
"selected": false,
"text": ">"
},
{
"answer_id": 74418378,
"author": "John Li",
"author_id": 20436957,
"author_profile": "https://Stackoverflow.com/users/20436957",
"pm_score": 3,
"selected": true,
"text": "&"
},
{
"answer_id": 74418557,
"author": "Lakruwan Pathirage",
"author_id": 12383492,
"author_profile": "https://Stackoverflow.com/users/12383492",
"pm_score": 1,
"selected": false,
"text": "<div class=\"parent\">\n parent\n <div class=\"child\">\n child\n <div class=\"container desc\">container</div>\n </div>\n</div>\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20362982/"
] |
74,418,280 | <p>hello I have the following code, the problem is that when iterating with forEach it affects all the elements of the nodeList that are 3 how could I do to affect it only generates the call to the eventListener?? I need that when I mouse over one of the projects it affects only this one and not the rest</p>
<pre><code>const $projects = document.querySelectorAll(".projects__grid__element")
$projects.forEach( (project,index) => {
addEventListener('mouseover', (event) => {
// const $projectDescription= project.querySelector(project[index]);
// $projectDescription.style.display= "flex"
});
addEventListener('mouseout', (event) => {
// const $projectDescription= project.querySelector(".projects__grid__element__description");
// $projectDescription.style.display = "none"
});
})
</code></pre>
<p>I need that when I mouse over one of the projects it affects only this one and not the rest</p>
| [
{
"answer_id": 74418336,
"author": "Christian",
"author_id": 3842598,
"author_profile": "https://Stackoverflow.com/users/3842598",
"pm_score": 1,
"selected": false,
"text": ">"
},
{
"answer_id": 74418378,
"author": "John Li",
"author_id": 20436957,
"author_profile": "https://Stackoverflow.com/users/20436957",
"pm_score": 3,
"selected": true,
"text": "&"
},
{
"answer_id": 74418557,
"author": "Lakruwan Pathirage",
"author_id": 12383492,
"author_profile": "https://Stackoverflow.com/users/12383492",
"pm_score": 1,
"selected": false,
"text": "<div class=\"parent\">\n parent\n <div class=\"child\">\n child\n <div class=\"container desc\">container</div>\n </div>\n</div>\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20139985/"
] |
74,418,295 | <p>I made my front component similar to a login page. When I try to pass the begin prop Front doesn't render for some reason. If I don't pass it any props then it renders fine. I'm not sure why this is happening. Any help would be appreciated!</p>
<pre><code>export default function App() {
const [start, setStart] = React.useState(false);
function startGame() {
setStart(prevStart => !prevStart);
}
return (
<div>
<Front begin={startGame()} />
</div>
)
</code></pre>
<p>}</p>
<pre><code>export default function Front(props) {
return (
<div className="login">
<h1>Quizzical</h1>
<h3>Read the questions carefully!</h3>
<button onClick={props.begin} className="startButton">Start Quiz</button>
<div className="blob-1"></div>
<div className="blob-2"></div>
</div>
)
</code></pre>
<p>}</p>
| [
{
"answer_id": 74418312,
"author": "John Li",
"author_id": 20436957,
"author_profile": "https://Stackoverflow.com/users/20436957",
"pm_score": 3,
"selected": true,
"text": "<Front begin={startGame} />"
},
{
"answer_id": 74418845,
"author": "Kundan",
"author_id": 11003837,
"author_profile": "https://Stackoverflow.com/users/11003837",
"pm_score": 0,
"selected": false,
"text": "<Front begin={() => startGame()} />\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19260499/"
] |
74,418,303 | <p>I'm creating a command line app in Java and wanted to know if it was possible to output an image in the terminal. Looked up online but could not find anything...</p>
<p>Thanks!</p>
| [
{
"answer_id": 74479142,
"author": "Mark Setchell",
"author_id": 2836621,
"author_profile": "https://Stackoverflow.com/users/2836621",
"pm_score": 0,
"selected": false,
"text": "showimg"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15697573/"
] |
74,418,309 | <p>So I currently have this code that asks the user if they want to delete a record from the database via ReactJS</p>
<pre><code>methods: {
async deleteStatus(id) {
try {
if (window.confirm("Do you really want to delete?")){
await axios.delete(`http://localhost:5000/delete-status/${id}`);
}
window.location.reload();
} catch (err) {
console.log(err);
}
},
},
</code></pre>
<p>Now my goal is to create an error message saying "Cannot Delete" If the record cannot be deleted, mainly due to a foreign key constraint in the backend. Is there a window function or a button function that relay that information to the user?</p>
| [
{
"answer_id": 74418352,
"author": "LakshyaK2011",
"author_id": 20192114,
"author_profile": "https://Stackoverflow.com/users/20192114",
"pm_score": 1,
"selected": false,
"text": "alert(\"Cannot Delete\");"
},
{
"answer_id": 74427855,
"author": "Rohìt Jíndal",
"author_id": 4116300,
"author_profile": "https://Stackoverflow.com/users/4116300",
"pm_score": 2,
"selected": false,
"text": "try"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418309",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15344032/"
] |
74,418,323 | <p>I am attempting to encrypt sensitive data before storing it. First, I generate a key to be used for the encryption process:</p>
<pre><code>import (
"crypto/aes"
CR "crypto/rand"
"encoding/hex"
"errors"
"log"
"os"
)
// []byte key used to encrypt tokens before saving to local file system
var key = make([]byte, 32)
func createKey(key *[]byte) {
_, err = CR.Read(*key)
if err != nil {
log.Println("Error creating key from crypto/rand package:", err)
}
}
</code></pre>
<p>Next I create functions that encrypt and decrypt a string respectively:</p>
<pre><code>func encryptToken(t token) string {
original := t.ID // ID is string member of token
cipher, err := aes.NewCipher(key)
if err != nil {
log.Println("Error creating cipher during encrypt:", err)
}
out := make([]byte, len(original))
cipher.Encrypt(out, []byte(original))
return hex.EncodeToString(out) // this will be written to a csv file
// appears in file as: cec35df876e1b77diefg9023366c5f2f000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
}
func decryptToken(s string) string {
ciphertext, err := hex.DecodeString(s) // s is read from csv file
if err != nil {
log.Println("Error decoding string from hex:", err)
}
cipher, err := aes.NewCipher(key)
if err != nil {
log.Println("Error creating cipher during decrypt:", err)
}
original := make([]byte, len(ciphertext))
cipher.Decrypt(original, ciphertext)
originalAsString := string(original[:])
return originalAsString // returns: 6f928e728f485403
// original token was: 6f928e728f485403e254049f684ea5ec853adcfa9553cdfc956fr45671447c57
}
</code></pre>
<p>Considering that <code>encryptToken()</code> returns a hex string with so many zeros, I am certain this is where my problem is. I've experimented adjusting the length of <code>key</code>, but using a value other than 32 in <code>var key = make([]byte, 32)</code> will result in a panic involving invalid memory address or nil pointer dereference. Why is this?</p>
| [
{
"answer_id": 74418346,
"author": "Grady Player",
"author_id": 593382,
"author_profile": "https://Stackoverflow.com/users/593382",
"pm_score": 2,
"selected": false,
"text": "full size mod 16 = 0"
},
{
"answer_id": 74419673,
"author": "NotX",
"author_id": 5767484,
"author_profile": "https://Stackoverflow.com/users/5767484",
"pm_score": 3,
"selected": true,
"text": "ciphertext = make([]byte, len(plaintext))\ncbc := cipher.NewCBCEncrypter(cipher, iv)\ncbc.CryptBlocks(ciphertext, plaintext)\n"
},
{
"answer_id": 74420985,
"author": "John Harrington",
"author_id": 15239077,
"author_profile": "https://Stackoverflow.com/users/15239077",
"pm_score": 0,
"selected": false,
"text": "var key = make([]byte, 32)\n\nfunc encryptToken(t token) string {\n original := t.ID // ID is string member of token\n var nonce = make([]byte, 12)\n\n // read random bytes into nonce\n _, err := rand.Read(nonce)\n if err != nil {\n log.Println(\"Error reading random bytes into nonce:\", err)\n }\n\n block, err := aes.NewCipher(key)\n if err != nil {\n log.Println(\"Error creating cipher during encrypt:\", err)\n }\n\n aesgcm, err := cipher.NewGCM(block)\n if err != nil {\n log.Println(\"Error creating GCM during encrypt:\", err)\n }\n\n ciphertext := aesgcm.Seal(nil, nonce, []byte(original), nil)\n\n // prepend the ciphertext with the nonce\n out := append(nonce, ciphertext...)\n\n return hex.EncodeToString(out)\n}\n\nfunc decryptToken(s string) string {\n // read hex string describing nonce and ciphertext\n enc, err := hex.DecodeString(s)\n if err != nil {\n log.Println(\"Error decoding string from hex:\", err)\n }\n\n // separate ciphertext from nonce\n nonce := enc[0:12]\n ciphertext := enc[12:]\n\n block, err := aes.NewCipher(key)\n if err != nil {\n log.Println(\"Error creating cipher during decrypt:\", err)\n }\n\n aesgcm, err := cipher.NewGCM(block)\n if err != nil {\n log.Println(\"Error creating GCM during decrypt:\", err)\n }\n\n original, err := aesgcm.Open(nil, nonce, ciphertext, nil)\n if err != nil {\n log.Println(\"Error decrypting to string:\", err)\n }\n originalAsString := string(original)\n\n return originalAsString\n}\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15239077/"
] |
74,418,329 | <p>When a put day 31 in the input field, the JSON 'dt_ini_vigencia' and 'dt_fin_vigencia' is changing for
day 1.
could anyone help me understand this?</p>
<p>JSON date format in input: '2022-12-31T03:00:00.000Z'
this is what the JSON returns after this function:
'2022-12-01T03:00:00.000Z' to 'dt_ini_vigencia'
'2023-12-01T03:00:00.000Z' to 'dt_fin_vigencia'.</p>
<p>this problem only happens when a put day 31 in the input</p>
<p>`</p>
<pre><code>var cotacaoJson = JSON.parse(resp[0].ds_cotacao_json);
var date = new Date();
date.setDate(cotacaoJson.dt_ini_vigencia.substring(8, 10)); //apparently is on this line
date.setMonth(cotacaoJson.dt_ini_vigencia.substring(5, 7) - 1);
date.setFullYear(cotacaoJson.dt_ini_vigencia.substring(0, 4));
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
var dateF = new Date();
dateF.setDate(cotacaoJson.dt_fin_vigencia.substring(8, 10));
dateF.setMonth(cotacaoJson.dt_fin_vigencia.substring(5, 7) - 1);
dateF.setFullYear(cotacaoJson.dt_fin_vigencia.substring(0, 4));
dateF.setHours(0);
dateF.setMinutes(0);
dateF.setSeconds(0);
dateF.setMilliseconds(0);
this.cotacao = cotacaoJson;
if (!this.editar)
{
this.cotacao.clausulas_particulares = 'N/A';
}
this.cotacao.dt_ini_vigencia = date;
this.cotacao.dt_fin_vigencia = dateF;
</code></pre>
<p>`</p>
<p>save the 31st in date and dateF</p>
| [
{
"answer_id": 74418411,
"author": "Azizbek PhD",
"author_id": 14389316,
"author_profile": "https://Stackoverflow.com/users/14389316",
"pm_score": 3,
"selected": true,
"text": "new Date()"
},
{
"answer_id": 74421566,
"author": "Edmunds Folkmanis",
"author_id": 19886561,
"author_profile": "https://Stackoverflow.com/users/19886561",
"pm_score": 1,
"selected": false,
"text": "parseJSON"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12734093/"
] |
74,418,330 | <p><strong>I write the code below,</strong></p>
<pre><code> source={require(`../../assets/images/${post.image}`)}
</code></pre>
<p><strong>in this {post.image} have dynamic values, its something like an array - img1.png,img2.png likewise</strong></p>
<p><strong>How to concatenate this path and values.
It's working on react but it's not working on react-native, How to solve that issue ?</strong></p>
| [
{
"answer_id": 74418411,
"author": "Azizbek PhD",
"author_id": 14389316,
"author_profile": "https://Stackoverflow.com/users/14389316",
"pm_score": 3,
"selected": true,
"text": "new Date()"
},
{
"answer_id": 74421566,
"author": "Edmunds Folkmanis",
"author_id": 19886561,
"author_profile": "https://Stackoverflow.com/users/19886561",
"pm_score": 1,
"selected": false,
"text": "parseJSON"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20163879/"
] |
74,418,358 | <p>I hope you're having a great day. Firstly, I would like to state that I am still a beginner to C++ and the coding world. I am working on a program that simulates a vending machine. This is done using while loops and if and else statements for the conditions and checks. I DO UNDERSTAND that my code is not optimized! I want to UNDERSTAND what I am reading in order for me to learn.</p>
<p>The vending machine program is roughly split into 4 parts.
1- Header
2-money loop
3-drink loop
4-exit loop</p>
<p>I am having a very hard time trying to piece it all together! When I fix one problem I run into another!</p>
<p>I am going to annotate my code in order to explain my thinking and then hopefully criticism is more effective.</p>
<p>`</p>
<pre><code>
#include <iostream>
using namespace std;
/*
What I plan on using for conditions, etc.
*/
char orderCharacter;
char orderNumber;
float fundsAvailable = 0;
char moreMoney;
char moreDrinks;
bool quit = false;
bool quitTwo = false;
int main()
{
/*
simple header.
*/
cout<<"========================================"<<endl;
cout<<"Welcome to the Vending Machine"<<endl;
cout<<"========================================"<<endl;
/*
While loop for inserting coins and bills. After user input, if and else output
*/
while (quit == false){
cout<<"Please insert your coins/bills"<<endl;
cout<<"(1)$1, (2)$5, (3)$10, (4)$20 :"<<endl;
cin>>orderNumber;
if (orderNumber == '1'){
fundsAvailable = fundsAvailable + 1;
cout<<"You've inserted: $1"<<endl;
cout<<"Funds available: $"<<fundsAvailable<<endl;
quit = true;
}else if (orderNumber == '2'){
fundsAvailable = fundsAvailable + 5;
cout<<"You've inserted: $5"<<endl;
cout<<"Funds available: $"<<fundsAvailable<<endl;
quit = true;
}else if (orderNumber == '3'){
fundsAvailable = fundsAvailable + 10;
cout<<"You've inserted: $10"<<endl;
cout<<"Funds available: $"<<fundsAvailable<<endl;
quit = true;
}else if (orderNumber == '4'){
fundsAvailable = fundsAvailable + 20;
cout<<"You've inserted: $20"<<endl;
cout<<"Funds available: $"<<fundsAvailable<<endl;
quit = true;
}else{
cout<<"Invalid Selection"<<endl;
quit = false;
}
//same process but for money...
cout<<"Add more coins/bills? (Y/N): ";
cin>>moreMoney;
if ((moreMoney == 'N' || moreMoney == 'n') && (fundsAvailable>=1.50)){
quit = true;
}else if ((moreMoney == 'Y') || (moreMoney == 'y')){
quit = false;
}else if ((moreMoney == 'N' || moreMoney == 'n') && (fundsAvailable<=1.49)){
cout<<"Insufficient funds to make a purchase."<<endl;
cout<<"Please take your change."<<endl;
quit = true;
quitTwo = true;
cout<<"Thank you for using our vending machine!"<<endl;
}else{
cout<<"Your answer is invalid. Please answer Y or N"<<endl;
cout<<"Add more coins/bills? (Y/N): ";
cin>>moreMoney;
}
}
//second while loop drink loop
while (quitTwo == false){
cout<<"Please make a selection:"<<endl;
cout<<"(A)quaVeena $1.50, (B)epsi $2.00, (C)ool Cola $2.00, (G)atorade $2.25"<<endl;
cin>>orderCharacter;
if ((fundsAvailable <= 1.49) && (quitTwo == false)){
cout<<"Insufficient funds to make a purchase."<<endl;
cout<<"Please take your change."<<endl;
cout<<"Thank you for using our vending machine!"<<endl;
}
//calculations
switch (orderCharacter){
case 'A':{
fundsAvailable = fundsAvailable - 1.50;
break;
}
case 'a':{
fundsAvailable = fundsAvailable - 1.50;
break;
}
case 'B':{
fundsAvailable = fundsAvailable - 2.00;
break;
}
case 'b':{
fundsAvailable = fundsAvailable - 2.00;
break;
}
case 'C':{
fundsAvailable = fundsAvailable - 2.00;
break;
}
case 'c':{
fundsAvailable = fundsAvailable - 2.00;
break;
}
case 'G':{
fundsAvailable = fundsAvailable - 2.25;
break;
}
case 'g':{
fundsAvailable = fundsAvailable - 2.25;
break;
}
}
cout<<"Add more drinks (Y/N): ";
cin>>moreDrinks;
//trying to checking available funds before selection, if lower than 1.50, automatically end and other options.
if ((fundsAvailable >=1.50) && (moreDrinks == 'Y' || moreDrinks =='y')){
quitTwo = false;
}else if ((fundsAvailable <=1.49) && (moreDrinks == 'Y' || moreDrinks =='y')){
quitTwo = true;
cout<<"Funds available: $"<<fundsAvailable<<endl;
cout<<"Please take your change."<<endl;
cout<<"Thank you for using our vending machine!"<<endl;
}else if ((fundsAvailable >=1.50) && (moreDrinks == 'N' || moreDrinks =='n')){
quitTwo = true;
cout<<"Funds available: $"<<fundsAvailable<<endl;
cout<<"Please take your change."<<endl;
cout<<"Thank you for using our vending machine!"<<endl;
}else{
cout<<"Your answer is invalid. Please answer Y or N"<<endl;
cout<<"Add more drinks (Y/N): ";
cin>>moreDrinks;
quitTwo = false;
}
}
return 0;
}
</code></pre>
<p>`</p>
<p>I am having trouble mostly with drink loop as well as the exit loops. It is simple to have one loop with a condition or two. however I am having a hard time implanting all in sync. For example, if I click '2' for the first user input I have 5 dollars and purchase myself a gatorade for 2.25. the program will work as intended.
however now if I make an invalid selection I will bypass the check for available funds. So even if I have 1 dollar, the vending machine will ask the user to make the selection (even though minimum is 1.50).</p>
<p>I know that my fundamentals of my code are lacking. I feel as if my loops aren't correctly stated or formed.</p>
<p>Known issues: Cant make invalid input more than once or code just skips ahead to next loop, fails to check conditions (this is an error of mine of course)</p>
| [
{
"answer_id": 74418485,
"author": "Igor",
"author_id": 17005821,
"author_profile": "https://Stackoverflow.com/users/17005821",
"pm_score": 0,
"selected": false,
"text": "quit = true;\n"
},
{
"answer_id": 74418506,
"author": "azhen7",
"author_id": 20341797,
"author_profile": "https://Stackoverflow.com/users/20341797",
"pm_score": 0,
"selected": false,
"text": "fundsAvailable"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19204562/"
] |
74,418,382 | <p>I am currently working on a small clicker game for university and its my first time using flutter dart.</p>
<p>Ive created an upgrade tab which displays different upgrades.
Thoose upgrades are being stored and loaded from a .json file</p>
<p>Whenever i try to open the upgrade tab, dart throws an exception
-> RangeError (index): Index out of range: no indices are valid: 0
This is due to the json not being loaded yet and axeList is empty
But due to dart calling build method multiple times its being loaded afterwards</p>
<p>Still... there is a frame with an error. Here is a slowed down gif:</p>
<p><a href="https://i.stack.imgur.com/ds6V6.gif" rel="nofollow noreferrer">slowed down gif (imgur.com)</a></p>
<p>Here is my code:</p>
<pre><code>class Upgrades extends StatefulWidget {
const Upgrades({Key? key}) : super(key: key);
@override
State<Upgrades> createState() => _UpgradesState();
}
class _UpgradesState extends State<Upgrades> with Store {
List axeList = [];
@override
void initState() {
readJson();
super.initState();
}
Future<void> readJson() async {
final String response = await rootBundle.loadString("/axe_list.json");
final data = await json.decode(response);
setState(() {
axeList = data["axe"];
});
}
@override
Widget build(BuildContext context) {
return //I need the content of axeList in this buildMethod
</code></pre>
<p>Order:</p>
<ul>
<li>initState()</li>
<li>readJson()</li>
<li>build()
|-> exception because axeList isnt loaded yet</li>
<li>readJson ready</li>
</ul>
<p>The problem is that i cant use async in initState:</p>
<pre><code> @override
Future<void> initState() async{
// Call the readJson method when the app starts & ensure loaded
await readJson();
super.initState();
}
</code></pre>
<p>This will resolve in following exception:
"_UpgradeState.initState() returned a Future. State.initState() must be a void method without an async keyword"</p>
<p>Loading the json on app startup doesnt seem to be the solution either, because Upgrades will not be called directly at Startup, but at a later point. Also id have to hand over the data in like 7 constructors</p>
<p>How do i ensure the async method is loaded before the build method?
thx for answers <3</p>
| [
{
"answer_id": 74418485,
"author": "Igor",
"author_id": 17005821,
"author_profile": "https://Stackoverflow.com/users/17005821",
"pm_score": 0,
"selected": false,
"text": "quit = true;\n"
},
{
"answer_id": 74418506,
"author": "azhen7",
"author_id": 20341797,
"author_profile": "https://Stackoverflow.com/users/20341797",
"pm_score": 0,
"selected": false,
"text": "fundsAvailable"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17265026/"
] |
74,418,385 | <p>In my React project, I have a page that is reading a param called "itemId" and fetching from a list of items the one item that has id === itemId. My code so far is the following. (Ellipsis "..." means code omitted for brevity.)</p>
<p>App.js</p>
<pre><code>...
const App = () => {
const tempItems = [
{
id: 1
...
},
...
];
const Routes = (
<Routes>
...
<Route path="/item/:itemId" element=<Item items={tempItems}/> exact/>
...
<Routes/>
);
};
...
</code></pre>
<p>Item.js</p>
<pre><code>const Item = ({items}) => {
let {itemId} = useParams();
console.log("Item id: " + itemId);
console.log(items);
const item = items.find((i) => i.id === itemId);
console.log(item);
if (item === undefined) {
console.log("redirected because item with id " + itemId + " doesn't exist");
return <Navigate to="/"/>
}
console.log("rendering item page");
return (
<div>
<h1>Rendering item page</h1>
</div>
);
};
</code></pre>
<p>When I enter "localhost:3000/item/1", the following console logs are printed. (Please don't ask me why all the item names are corn themed, lol.)</p>
<pre><code>Item id: 1
Array(8) [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…} ]
0: Object { id: 1, itemName: "Shepherd's Pie", itemType: "Cuisine", … }
1: Object { id: 2, itemName: "Cornmeal-Fried Fish", itemType: "Cuisine", … }
2: Object { id: 3, itemName: "Cornbread", itemType: "Side", … }
3: Object { id: 4, itemName: "Grilled corn", itemType: "Side", … }
4: Object { id: 5, itemName: "Corn Milk", itemType: "Drink", … }
5: Object { id: 6, itemName: "Corn Beer", itemType: "Drink", … }
6: Object { id: 7, itemName: "Corn Pudding", itemType: "Dessert", … }
7: Object { id: 8, itemName: "Sweet Corn Cake", itemType: "Dessert", … }
length: 8
<prototype>: Array []
undefined
redirected because item with id 1 doesn't exist
</code></pre>
<p>The itemId param in the URL is being parsed correctly because when I enter "localhost:3000/item/1" the console logs "Item id: 1". The items prop that I'm passing into Item.js is correct because it's printing out the complete array. But for some reason, the find function is returning undefined even though I know for a fact that the array contains an element where item.id === itemId (in this case 1). Is there some secret magic I'm missing? So far in learning React, it really seems like there's some confusing workarounds for confusing problems, so I wouldn't be surprised if there's some crazy solution that I'm missing that you can't just figure out with intuition.</p>
| [
{
"answer_id": 74418410,
"author": "Sachila Ranawaka",
"author_id": 6428638,
"author_profile": "https://Stackoverflow.com/users/6428638",
"pm_score": 1,
"selected": false,
"text": "const item = items.find((i) => i.id === Number(itemId));\n"
},
{
"answer_id": 74418427,
"author": "hddananjaya",
"author_id": 9471491,
"author_profile": "https://Stackoverflow.com/users/9471491",
"pm_score": 1,
"selected": false,
"text": "let {itemId} = useParams();\n"
},
{
"answer_id": 74418441,
"author": "John Li",
"author_id": 20436957,
"author_profile": "https://Stackoverflow.com/users/20436957",
"pm_score": 2,
"selected": true,
"text": "+itemId"
},
{
"answer_id": 74418617,
"author": "Kamran Davar",
"author_id": 12510464,
"author_profile": "https://Stackoverflow.com/users/12510464",
"pm_score": 2,
"selected": false,
"text": "itemId"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16426887/"
] |
74,418,401 | <p>For example, I have two dataframes like:</p>
<pre class="lang-py prettyprint-override"><code>X = pd.DataFrame({f"id{i}": np.random.randn(200) for i in range(100)})
Y = pd.DataFrame({f"id{i}": np.random.randn(200) for i in range(100)})
</code></pre>
<p>In pandas, the rolling calculation of two DFs col by col (the columns with same id) can be writen easily by:</p>
<pre class="lang-py prettyprint-override"><code># rolling corr:
X.rolling(5).corr(Y)
# rolling cov:
X.rolling(5).cov(Y)
# rolling slope:
X.rolling(5).cov(Y) / X.rolling(5).var()
</code></pre>
<p>How to use polars to implement such calculations?
Thanks!</p>
| [
{
"answer_id": 74418410,
"author": "Sachila Ranawaka",
"author_id": 6428638,
"author_profile": "https://Stackoverflow.com/users/6428638",
"pm_score": 1,
"selected": false,
"text": "const item = items.find((i) => i.id === Number(itemId));\n"
},
{
"answer_id": 74418427,
"author": "hddananjaya",
"author_id": 9471491,
"author_profile": "https://Stackoverflow.com/users/9471491",
"pm_score": 1,
"selected": false,
"text": "let {itemId} = useParams();\n"
},
{
"answer_id": 74418441,
"author": "John Li",
"author_id": 20436957,
"author_profile": "https://Stackoverflow.com/users/20436957",
"pm_score": 2,
"selected": true,
"text": "+itemId"
},
{
"answer_id": 74418617,
"author": "Kamran Davar",
"author_id": 12510464,
"author_profile": "https://Stackoverflow.com/users/12510464",
"pm_score": 2,
"selected": false,
"text": "itemId"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19868974/"
] |
74,418,406 | <p>I need my program to show a list and then ask the user if they want to add anything; then it adds that input to the list. It then asks the user again in separate input if they want to add anything else and if they hit enter it prints the list including all the new inputs and ends the big while loop.</p>
<pre><code>list1 = [1,2,3,4,5,6]
def list_adder(liist):
print("Here is the list:\n")
def show_list():
for element in liist:
print(element)
show_list()
x = True
while x == True:
counter = 0
if counter == 0:
add_input1 = input("\nWhat would you like to add:\n")
liist.append(add_input1)
counter +1
while counter == 1:
add_input2 = input("\nWhat else would you like to add to the list?: \n")
to_do_list.append(add_input2)
if not add_input2:
show_list()
counter += 1
x == False
list_adder(list1)
</code></pre>
<p>I tried this but it keeps saying "What would you like to add" over and over</p>
| [
{
"answer_id": 74418410,
"author": "Sachila Ranawaka",
"author_id": 6428638,
"author_profile": "https://Stackoverflow.com/users/6428638",
"pm_score": 1,
"selected": false,
"text": "const item = items.find((i) => i.id === Number(itemId));\n"
},
{
"answer_id": 74418427,
"author": "hddananjaya",
"author_id": 9471491,
"author_profile": "https://Stackoverflow.com/users/9471491",
"pm_score": 1,
"selected": false,
"text": "let {itemId} = useParams();\n"
},
{
"answer_id": 74418441,
"author": "John Li",
"author_id": 20436957,
"author_profile": "https://Stackoverflow.com/users/20436957",
"pm_score": 2,
"selected": true,
"text": "+itemId"
},
{
"answer_id": 74418617,
"author": "Kamran Davar",
"author_id": 12510464,
"author_profile": "https://Stackoverflow.com/users/12510464",
"pm_score": 2,
"selected": false,
"text": "itemId"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418406",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17347665/"
] |
74,418,481 | <pre><code>library(data.table)
tab1 <- data.table(id1 = c(1, 2, 100, 100),
class = c(2, 2, 1, 5),
number = c(96, 100, 55, 55),
code1 = c("123", "125", "999", "999"))
tab2 <- data.table(id2 = c(100, 200, 200, 205, 205, 205),
class = c(2, 2, 1, 5, 2, 2),
max_number = c(100, 80, 80, 95, 95, 95),
min_number = c(0, 50, 50, 10, 10, 10),
code2 = c("123,999", "100,105", "100,105", "555,999", "234,999", "123,999,555"))
> tab1
id1 class number code1
1: 1 2 96 123
2: 2 2 100 125
3: 100 1 55 999
4: 100 5 55 999
> tab2
id2 class max_number min_number code2
1: 100 2 100 0 123,999
2: 200 2 80 50 100,105
3: 200 1 80 50 100,105
4: 205 5 95 10 555,999
5: 205 2 95 10 234,999
6: 205 2 95 10 123,999,555
</code></pre>
<p>I have two tables. For each <code>id1</code>, I would like to match on <code>class</code>, <code>min_number <= number <= max_number</code> and see if <code>code1</code> matches anything (partially) in <code>code2</code>. That is, "123" would be a match for "123, 999, 555".</p>
<p>My attempt is below. The column <code>V1</code> contains the <code>id2</code>s that matched.</p>
<pre><code>> tab2[tab1, on = c("class", "max_number >= number", "min_number <= number"), .(list(id2)), by = .EACHI]
class max_number min_number V1
1: 2 96 96 100
2: 2 100 100 100
3: 1 55 55 200
4: 5 55 55 205
</code></pre>
<p>Just matching on <code>class</code> and <code>min_number <= number <= max_number</code> works fine. But trying to do the partial string match with <code>grepl</code> gives the following error:</p>
<pre><code>> tab2[tab1, on = c("class", "max_number >= number", "min_number <= number", grepl("code2", "code1")), .(list(id2)), by = .EACHI]
Error in colnamesInt(x, names(on), check_dups = FALSE) :
argument specifying columns specify non existing column(s): cols[4]='FALSE'
</code></pre>
<p>The desired output is something like this (where <code>V1</code> contains the <code>id2</code>s that matches each row in <code>tab1</code>):</p>
<pre><code> id1 class max_number min_number V1
1: 1 2 96 96 100
2: 2 2 100 100 <NA>
3: 100 1 55 55 <NA>
4: 100 5 55 55 205,205
</code></pre>
| [
{
"answer_id": 74418410,
"author": "Sachila Ranawaka",
"author_id": 6428638,
"author_profile": "https://Stackoverflow.com/users/6428638",
"pm_score": 1,
"selected": false,
"text": "const item = items.find((i) => i.id === Number(itemId));\n"
},
{
"answer_id": 74418427,
"author": "hddananjaya",
"author_id": 9471491,
"author_profile": "https://Stackoverflow.com/users/9471491",
"pm_score": 1,
"selected": false,
"text": "let {itemId} = useParams();\n"
},
{
"answer_id": 74418441,
"author": "John Li",
"author_id": 20436957,
"author_profile": "https://Stackoverflow.com/users/20436957",
"pm_score": 2,
"selected": true,
"text": "+itemId"
},
{
"answer_id": 74418617,
"author": "Kamran Davar",
"author_id": 12510464,
"author_profile": "https://Stackoverflow.com/users/12510464",
"pm_score": 2,
"selected": false,
"text": "itemId"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3391549/"
] |
74,418,488 | <p>Looked at some of the other posts asking about the error 'column "column_name" referenced in foreign key constraint does not exist' but none of the answers/situations seem to match exactly:</p>
<p>Currently have two migration files:</p>
<p><strong>20210123122225_createReservationsTable.js</strong></p>
<pre><code>exports.up = function (knex) {
return knex.schema.createTable("reservations", (table) => {
table.increments("reservation_id").primary();
table.string("first_name").notNullable();
table.string("last_name").notNullable();
table.string("mobile_number").notNullable();
table.date("reservation_date").notNullable();
table.time("reservation_time").notNullable();
table.integer("people");
table.timestamps(true, true);
});
};
exports.down = function (knex) {
return knex.schema.dropTable("reservations");
};
</code></pre>
<p><strong>20221112222830_tables.js</strong></p>
<pre><code>
exports.up = function(knex) {
return knex.schema.createTable("tables", (table) => {
table.increments("table_id").primary();
table.string("table_name").notNullable();
table.integer("capacity").unsigned().notNullable();
table
.foreign("reservation_id")
.references("reservation_id")
.inTable("reservations")
.onDelete("cascade");
table.timestamps(true, true);
})
};
exports.down = function(knex) {
return knex.schema.dropTable("tables");
};
</code></pre>
<p>Running the migration results in:</p>
<blockquote>
<p>migration file "20210123122225_createReservationsTable.js" failed
migration failed with error: alter table "tables" add constraint "tables_reservation_id_foreign" foreign key ("reservation_id") references "reservations" ("reservation_id") on delete cascade - column "reservation_id" referenced in foreign key constraint does not exist</p>
</blockquote>
<p>I figured maybe the "reservations" table was being made after the "tables" table. But from what I understand, the migrations are run in order of the file names. Given that the "reservations" table's migration file is dated earlier, it should be running first. I've also done this exact same method of migrations before and didn't have an issue.</p>
<p>Either way, I tried running the migration for the "reservations" table first, and then the "tables" table migration separately. Same issue.</p>
<p>I tried other suggestions in previously asked questions here, like placing both table creations in the same file, using async tags to avoid race conditions, and still the same error.</p>
<p>Starting to feel like I'm missing something really obvious.</p>
| [
{
"answer_id": 74418538,
"author": "fwippy",
"author_id": 19326850,
"author_profile": "https://Stackoverflow.com/users/19326850",
"pm_score": 1,
"selected": false,
"text": "exports.up = function(knex) {\n return knex.schema.createTable(\"tables\", (table) => {\n table.increments(\"table_id\").primary();\n table.string(\"table_name\").notNullable();\n table.integer(\"capacity\").unsigned().notNullable();\n **table.integer(\"reservation_id\").unsigned();**\n table\n .foreign(\"reservation_id\")\n .references(\"reservation_id\")\n .inTable(\"reservations\")\n .onDelete(\"cascade\");\n table.timestamps(true, true);\n })\n};\n\nexports.down = function(knex) {\n return knex.schema.dropTable(\"tables\");\n};\n"
},
{
"answer_id": 74418544,
"author": "J_H",
"author_id": 8431111,
"author_profile": "https://Stackoverflow.com/users/8431111",
"pm_score": 0,
"selected": false,
"text": ".down"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19326850/"
] |
74,418,492 | <p>What regex(es) will extract the URL from strings with these patterns?</p>
<pre><code>https://xxx##.safelinks.protection.outlook.com/?url=[encoded URL to extract]&data=[more detritus]
https://example.com/link/?url=[encoded URL to extract]%3Fl%3Den-us
https://example.com/link/?url=[encoded URL to extract]
</code></pre>
<p>The first part will be <code>\?url=</code>; I am less certain about what comes next, and whether I need to use separate regexes for each pattern. Taking the first pattern,</p>
<pre><code>https://xxx##.safelinks.protection.outlook.com/?url=https%3A%2F%2Fwww.domain.com%2Fsubd%2Fdoc.aspx%2F&data=[more detritus]
</code></pre>
<p>I would want to extract <code>https%3A%2F%2Fwww.domain.com%2Fsubd%2Fdoc.aspx%2F</code> (to decode with an existing function.)</p>
| [
{
"answer_id": 74418787,
"author": "great_pan",
"author_id": 20200173,
"author_profile": "https://Stackoverflow.com/users/20200173",
"pm_score": 2,
"selected": false,
"text": "url=(.+?)(&|$)"
},
{
"answer_id": 74418889,
"author": "SaSkY",
"author_id": 18104248,
"author_profile": "https://Stackoverflow.com/users/18104248",
"pm_score": 3,
"selected": true,
"text": "(?<=url=)[^&\\s]+%2[fF](?:[^&\\s%]*)\n"
},
{
"answer_id": 74420524,
"author": "The fourth bird",
"author_id": 5424988,
"author_profile": "https://Stackoverflow.com/users/5424988",
"pm_score": 2,
"selected": false,
"text": "\\K"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2319146/"
] |
74,418,499 | <p>How do I use the method <code>()</code> to implement the following changes?</p>
<p>Add a new experience "HIVE" to the employee whose <code>empeId</code> is 'e001'.</p>
<p>and</p>
<p>Change the email account for employee e001 to "jamesbond$hotmail.com".</p>
<p>Below is the database in question</p>
<pre><code>db.empeProject.insert([ {
"Employee": [ { "empeId": "e001",
"fName": "James",
"lName": "Bond",
"email": "jamesbond@hotmail.com",
"experience": [
"Database Design",
"SQL",
"Java" ]
},
{ "empeId": "e002",
"fName": "Harry",
"lName": "Potter",
"experience": [
"Data Warehouse",
"SQL",
"Spark Scala",
"Java Scripts" ]
} ],
"Project": [ { "projectId": "p001",
"projectTitle": "Install MongoDB" },
{ "projectId": "p002",
"projectTitle": "Install Oracle" },
{ "projectId": "p003",
"projectTitle": "Install Hadoop" } ],
"EmployeeProject": [ { "empeId": "e001",
"projectId": "p001",
"hoursWorked": 4 },
{ "empeId": "e001",
"projectId": "p003",
"hoursWorked": 2 },
{ "empeId": "e002",
"projectId": "p003",
"hoursWorked": 5 } ]
} ] );
</code></pre>
<p>Currently what I've tried for the first is</p>
<pre><code>db.empeProject.update(
{"Employee.empeId":"e001"},
{"$push":{"Employee.experience":"HIVE"}}
)
</code></pre>
<p>and the second is</p>
<pre><code>db.empeProject.update(
{"Employee.empeId":"e001"},{"$set":
{"Employee.email":"jamesbond$hotmail.com"}}
)
</code></pre>
<p>In both cases, I got an error</p>
<blockquote>
<p>cannot create field in element</p>
</blockquote>
| [
{
"answer_id": 74418787,
"author": "great_pan",
"author_id": 20200173,
"author_profile": "https://Stackoverflow.com/users/20200173",
"pm_score": 2,
"selected": false,
"text": "url=(.+?)(&|$)"
},
{
"answer_id": 74418889,
"author": "SaSkY",
"author_id": 18104248,
"author_profile": "https://Stackoverflow.com/users/18104248",
"pm_score": 3,
"selected": true,
"text": "(?<=url=)[^&\\s]+%2[fF](?:[^&\\s%]*)\n"
},
{
"answer_id": 74420524,
"author": "The fourth bird",
"author_id": 5424988,
"author_profile": "https://Stackoverflow.com/users/5424988",
"pm_score": 2,
"selected": false,
"text": "\\K"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10874912/"
] |
74,418,522 | <pre><code>using System;
class HelloWorld
{
public static int GetYear()
{
Console.WriteLine("Please enter year: ");
int year = Convert.ToInt32(Console.ReadLine());
return year;
}
public static int GetMonth()
{
Console.WriteLine("Please enter month number (Febuary is 2): ");
int month = Convert.ToInt32(Console.ReadLine());
return month;
}
static string GetMonthName(int month)
{
string[] monthName = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
string monthValue = monthName[month - 1];
return monthValue;
}
public static bool LeapYear(int Year)
{
if (((Year % 4 == 0) && (Year % 100 != 0)) || (Year % 400 == 0))
return true;
else
return false;
}
public static void print(string monthValue, int days, int year, int month)
{
Console.WriteLine("{0} {1} has {2} days\n", year, monthValue, days);
}
static void Main()
{
int[] days = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
int[] leapDays = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
int monthDays;
while (true)
{
int year = GetYear();
int month = GetMonth();
if (year > 0 && month > 0 && month <= 12)
{
string monthValue = GetMonthName(month);
bool leap = LeapYear(year);
if (leap)
{
monthDays = leapDays[month - 1];
print(monthValue, monthDays, year, month);
}
else
{
monthDays = days[month - 1];
print(monthValue, monthDays, year, month);
}
}
else
{
Console.WriteLine("Invalid Year or Month entered!! Please enter a correct value");
break;
}
}
}
}
</code></pre>
<p>I kept getting an error in Github actions, the error was "could not find public class name" even though the Main class is capitalized. I don't know what I'm doing wrong here</p>
<p>When using dotnetfiddle as instructed by my teacher, the error message I received was "Public Main() method is required in a public class" but like I mentioned above, making sure the Main function was capitalized did nothing</p>
| [
{
"answer_id": 74418572,
"author": "Igor",
"author_id": 17005821,
"author_profile": "https://Stackoverflow.com/users/17005821",
"pm_score": 1,
"selected": false,
"text": "Main"
},
{
"answer_id": 74418582,
"author": "vivek nuna",
"author_id": 6527049,
"author_profile": "https://Stackoverflow.com/users/6527049",
"pm_score": 0,
"selected": false,
"text": "public static void Main()"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20235997/"
] |
74,418,579 | <pre class="lang-java prettyprint-override"><code>class Generate // to print all numbers from 1000 to 9999 whose digits are in ascending order
{
private boolean order(int n, int i) // checks if the digits of given number are in ascending order
{
if (n == 0) return true;
if (n % 10 < i) return (order(n / 10, n % 10));
return false;
}
void show(int n) // recursive function to generate numbers from 1000 to 9999
{
if (n > 9999) // base case for recursor
System.out.print("");
else
{
if (order(n, 10)) // if digits are in ascending order, prints the number
System.out.println(n);
show(n + 1); // recursive call
}
}
}
</code></pre>
<p>The above code was supposed to print all numbers from 1000 to 9999. Code compiled and run but received a runtime exception: <code>java.lang.StackOverflowError: null</code>. Would a try-catch block fix my problem? This is my first time posting here hence I am not familiar with the question etiquette, please correct me if I'm wrong.</p>
| [
{
"answer_id": 74418572,
"author": "Igor",
"author_id": 17005821,
"author_profile": "https://Stackoverflow.com/users/17005821",
"pm_score": 1,
"selected": false,
"text": "Main"
},
{
"answer_id": 74418582,
"author": "vivek nuna",
"author_id": 6527049,
"author_profile": "https://Stackoverflow.com/users/6527049",
"pm_score": 0,
"selected": false,
"text": "public static void Main()"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16629978/"
] |
74,418,580 | <p>I've spent all day trying to figure out how I can simply have a list of colors (for example: Colors.AliceBlue) as my ItemsSource for a GridView and bind those colors to a Fill property of a Rectangle inside the DataTemplate. I know the Fill property must be a brush, so I have tried using a converter to convert the color to a SolidColorBrush, but it has not worked. I've also tried not using a converter and instead changing the List to List but that did not work either. No matter what I do, I keep getting binding errors that say:</p>
<blockquote>
<p>Converter failed to convert value of type '#FFF0F8FF' to type 'Brush'. Binding: Path='' DataItem='#FFF0F8FF'; target element is 'Microsoft.UI.Xaml.Shapes.Rectangle' (Name='null'); target property is 'Fill' (type 'Brush')</p>
</blockquote>
<p>Everything I try always seems to return my color as an ARGB, in this case "#FFF0F8FF", which is not what the property accepts. Any ideas on how to bind my list of colors to my item/data template? I definitely want to use color names in my list, as it is easier to access colors this way rather than looking up their RGB codes and whatnot.</p>
<hr />
<p><strong>Page.xaml</strong></p>
<pre><code><GridView ItemsSource="{x:Bind ColorOptions}" IsItemClickEnabled="True" SelectionMode="Single">
<GridView.ItemTemplate>
<DataTemplate>
<Rectangle Fill="{Binding}" Width="40" Height="40" />
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
</code></pre>
<p><strong>Page.xaml.cs</strong></p>
<pre><code>using System.Windows.Media;
...
public readonly List<Color> ColorOptions = new()
{
Colors.AliceBlue,
Colors.Black,
Colors.DarkBlue,
Colors.Brown,
Colors.DarkGreen,
Colors.Magenta
};
</code></pre>
<hr />
<p>Also, if you're interested, here's the converter I created and tried, but also did not work.</p>
<p><strong>BrushConverter.cs</strong></p>
<pre><code>using System.Windows.Media;
using Microsoft.UI.Xaml.Data;
namespace App.Helpers;
public class BrushConverter : IValueConverter
{
public object? Convert(object value, Type targetType, object parameter, string language)
{
return new SolidColorBrush((Color)value);
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
return ((SolidColorBrush)value).Color;
}
}
</code></pre>
<p><strong>Page.xaml (using converter)</strong></p>
<pre><code><GridView ItemsSource="{x:Bind ColorOptions}" IsItemClickEnabled="True" SelectionMode="Single">
<GridView.ItemTemplate>
<DataTemplate>
<Rectangle Fill="{Binding Converter={StaticResource BrushConverter}}" Width="40" Height="40" />
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
</code></pre>
| [
{
"answer_id": 74418572,
"author": "Igor",
"author_id": 17005821,
"author_profile": "https://Stackoverflow.com/users/17005821",
"pm_score": 1,
"selected": false,
"text": "Main"
},
{
"answer_id": 74418582,
"author": "vivek nuna",
"author_id": 6527049,
"author_profile": "https://Stackoverflow.com/users/6527049",
"pm_score": 0,
"selected": false,
"text": "public static void Main()"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8173997/"
] |
74,418,583 | <p>I have an object that looks something like this</p>
<pre><code>palette: {
black: "#000",
white: "#fff",
primary: {
"50": "#somecolor",
"100": "#somecolor",
"300": "#somecolor",
"500": "#somecolor",
"700": "#somecolor",
},
grey: {
"50": "#somecolor",
"300": "#somecolor",
"500": "#somecolor",
"700": "#somecolor",
"900": "#somecolor",
},
green: {
"100": "#somecolor",
"300": "#somecolor",
"500": "#somecolor",
"700": "#somecolor",
},
blue: {
"100": "#somecolor",
"300": "#somecolor",
"500": "#somecolor",
"700": "#somecolor",
},
pink: {
"100": "#somecolor",
"300": "#somecolor",
"500": "#somecolor",
"700": "#somecolor",
},
red: {
"300": "#somecolor",
"500": "#somecolor",
"700": "#somecolor",
},
background: {
"500": "#somecolor",
"700": "#somecolor",
}
}
</code></pre>
<p>I want to create a TypeScript type that is only a subset of some of the keys. My ideal type would look like <code>const theme = ["blue", "green", "pink", "primary"] as const</code> or <code>type Theme = "blue" | "green" | "primary" | "pink"</code></p>
<p>I am unable to extract this type. The purpose of this type is to do things like:
<code>const currentColor = palette[theme][500]</code> where <code>theme</code> is a variable that can be either the <code>Theme</code> or <code>theme</code> type from the above paragraph.</p>
<p>Not sure if it matters but I am in a NextJS + React Native environment.</p>
<p>How can I do this?</p>
| [
{
"answer_id": 74418854,
"author": "Kamran Davar",
"author_id": 12510464,
"author_profile": "https://Stackoverflow.com/users/12510464",
"pm_score": 4,
"selected": true,
"text": "export default function Home() {\n type themeItemType = \"blue\" | \"green\" | \"primary\" | \"pink\";\n const theme: themeItemType[] = [\"blue\", \"green\", \"pink\", \"primary\"];\n console.log(palette[theme[2]][500]) //#somecolor\n\n return <div>{palette[theme[2]][500]}</div>;\n}\n\nconst palette = {\n black: \"#000\",\n white: \"#fff\",\n primary: {\n \"50\": \"#somecolor\",\n \"100\": \"#somecolor\",\n \"300\": \"#somecolor\",\n \"500\": \"#somecolor\",\n \"700\": \"#somecolor\",\n },\n grey: {\n \"50\": \"#somecolor\",\n \"300\": \"#somecolor\",\n \"500\": \"#somecolor\",\n \"700\": \"#somecolor\",\n \"900\": \"#somecolor\",\n },\n green: {\n \"100\": \"#somecolor\",\n \"300\": \"#somecolor\",\n \"500\": \"#somecolor\",\n \"700\": \"#somecolor\",\n },\n blue: {\n \"100\": \"#somecolor\",\n \"300\": \"#somecolor\",\n \"500\": \"#somecolor\",\n \"700\": \"#somecolor\",\n },\n pink: {\n \"100\": \"#somecolor\",\n \"300\": \"#somecolor\",\n \"500\": \"#somecolor\",\n \"700\": \"#somecolor\",\n },\n red: {\n \"300\": \"#somecolor\",\n \"500\": \"#somecolor\",\n \"700\": \"#somecolor\",\n },\n background: {\n \"500\": \"#somecolor\",\n \"700\": \"#somecolor\",\n },\n}; \n"
},
{
"answer_id": 74418902,
"author": "Jumpa",
"author_id": 2606899,
"author_profile": "https://Stackoverflow.com/users/2606899",
"pm_score": 0,
"selected": false,
"text": "type PaletteKeys = keyof Partial<Record<keyof typeof palette, string>>\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20394462/"
] |
74,418,584 | <p>I have A Data like this, or you can see my Notebook here : <a href="https://colab.research.google.com/drive/1pKAQjOV38A0o211CjCW45DIk9RWywLhh#scrollTo=pV4HijQhRxGK" rel="nofollow noreferrer">link</a>
or the raw file here : <a href="https://raw.githubusercontent.com/gacha321/data_cleaning/main/Help.csv" rel="nofollow noreferrer">link</a></p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Id</th>
<th>Type</th>
<th>Label</th>
<th>Value</th>
<th>Value2</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>A</td>
<td>Introduction</td>
<td>This Project will be created By Mr.X</td>
<td></td>
</tr>
<tr>
<td>1</td>
<td>A</td>
<td>Capacity</td>
<td>100MB</td>
<td></td>
</tr>
<tr>
<td>1</td>
<td>A</td>
<td>Speed</td>
<td>10Km/h</td>
<td></td>
</tr>
<tr>
<td>1</td>
<td>A</td>
<td>Weight</td>
<td>10kg</td>
<td></td>
</tr>
<tr>
<td>2</td>
<td>A</td>
<td>Introduction</td>
<td>This-Project-will-be-created-By-Mr.A</td>
<td></td>
</tr>
<tr>
<td>2</td>
<td>A</td>
<td>Capacity</td>
<td>100MB</td>
<td></td>
</tr>
<tr>
<td>2</td>
<td>A</td>
<td>Speed</td>
<td>5km/h</td>
<td></td>
</tr>
<tr>
<td>2</td>
<td>A</td>
<td>Weight</td>
<td>1kg</td>
<td></td>
</tr>
<tr>
<td>3</td>
<td>B</td>
<td>Introduction</td>
<td></td>
<td>This Project will be created By Mr.C</td>
</tr>
<tr>
<td>3</td>
<td>B</td>
<td>Capacity</td>
<td></td>
<td>100MB</td>
</tr>
<tr>
<td>3</td>
<td>B</td>
<td>Speed</td>
<td></td>
<td>5km/h</td>
</tr>
<tr>
<td>3</td>
<td>B</td>
<td>Weight</td>
<td></td>
<td>1kg</td>
</tr>
<tr>
<td>4</td>
<td>B</td>
<td>Introduction</td>
<td></td>
<td>This Project will be created By Mr.D</td>
</tr>
<tr>
<td>4</td>
<td>B</td>
<td>Capacity</td>
<td></td>
<td>100MB</td>
</tr>
<tr>
<td>4</td>
<td>B</td>
<td>Speed</td>
<td></td>
<td>5km/h</td>
</tr>
<tr>
<td>4</td>
<td>B</td>
<td>Weight</td>
<td></td>
<td>1kg</td>
</tr>
<tr>
<td>4</td>
<td>B</td>
<td>Height</td>
<td></td>
<td>1m</td>
</tr>
<tr>
<td>4</td>
<td>B</td>
<td>Color</td>
<td></td>
<td>red</td>
</tr>
</tbody>
</table>
</div>
<p>You can see that Type A has label value in <code>Value</code> column but the type B has label value in <code>Value2</code> Column. I want to grouping for each ID and transposing a <code>Label</code> value to be columns like this.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Id</th>
<th>PJ</th>
<th>Capacity</th>
<th>Speed</th>
<th>Weight</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Mr.X</td>
<td>100MB</td>
<td>10Km/h</td>
<td>10kg</td>
</tr>
<tr>
<td>2</td>
<td>Mr.A</td>
<td>100MB</td>
<td>5Km/h</td>
<td>1kg</td>
</tr>
<tr>
<td>3</td>
<td>Mr.C</td>
<td>100MB</td>
<td>5Km/h</td>
<td>1kg</td>
</tr>
</tbody>
</table>
</div>
<p>Where <code>PJ</code> Column is from the Value of <code>Introduction</code> But we only get the People Name, and my data also have <code>-</code> symbol for several value.</p>
<p>I'm a beginner Using Python and I didn't know how to do. Because I think It's hard if I cleaning the data using excel because there is a lot of data. Thank you</p>
| [
{
"answer_id": 74418698,
"author": "Panda Kim",
"author_id": 20430449,
"author_profile": "https://Stackoverflow.com/users/20430449",
"pm_score": 0,
"selected": false,
"text": "Value"
},
{
"answer_id": 74419010,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": true,
"text": "melt"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14033243/"
] |
74,418,586 | <p>I can copy file to Google Cloud Storage:</p>
<pre><code>% gsutil -m cp audio/index.csv gs://passive-english/audio/
If you experience problems with multiprocessing on MacOS, they might be related to https://bugs.python.org/issue33725. You can disable multiprocessing by editing your .boto config or by adding the following flag to your command: `-o "GSUtil:parallel_process_count=1"`. Note that multithreading is still available even if you disable multiprocessing.
Copying file://audio/index.csv [Content-Type=text/csv]...
\ [1/1 files][196.2 KiB/196.2 KiB] 100% Done
Operation completed over 1 objects/196.2 KiB.
</code></pre>
<p>But I can't change it metadata:</p>
<pre><code>% gsutil setmeta -h "Cache-Control:public, max-age=7200" gs://passive-english/audio/index.csv
Setting metadata on gs://passive-english/audio/index.csv...
AccessDeniedException: 403 Access denied.
</code></pre>
<p>I'm authorizing using json file:</p>
<pre><code>% env | grep GOOGL
GOOGLE_APPLICATION_CREDENTIALS=/app-342xxx-2cxxxxxx.json
</code></pre>
<p>How can I grant access so that gsutil can change metadata for the file?</p>
<p><strong>Update 1:</strong></p>
<p>I give the service account role Editor and <code>Storage Object Admin</code> permission.</p>
<p><strong>Update 2</strong>:
I give the service account role Owner and Storage Object Admin permission. Still no use</p>
<p><a href="https://i.stack.imgur.com/xxGzu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xxGzu.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74418998,
"author": "John Hanley",
"author_id": 8016720,
"author_profile": "https://Stackoverflow.com/users/8016720",
"pm_score": 1,
"selected": false,
"text": "storage.objects.update"
},
{
"answer_id": 74420402,
"author": "Sathi Aiswarya",
"author_id": 18265638,
"author_profile": "https://Stackoverflow.com/users/18265638",
"pm_score": 0,
"selected": false,
"text": "Owner"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/244000/"
] |
74,418,596 | <p>I am making an app where mousewheel up and down are used to navigate to and from different pre set routes.</p>
<p>currently the routes look like this:</p>
<p><strong>main -> skills -> aboutme -> work</strong></p>
<p>mousewheel-down cycles from left to right in the order above, and mousewheel-up does the same but in reverse.</p>
<p>this is the logic:</p>
<pre><code>import React, { useState, useEffect } from "react";
import { useNavigate, useLocation } from "react-router-dom";
const Context = React.createContext();
function ContextProvider({ children }) {
const navigate = useNavigate();
const location = useLocation();
useEffect(() => {
window.addEventListener("wheel", (e) => handleNavigation(e));
return () => {
window.removeEventListener("wheel", (e) => handleNavigation(e));
};
}, [location]);
function handleNavigation(e) {
if (location.pathname.includes("/work/")) {
return;
} else {
if (e.deltaY > 1 && location.pathname === "/") {
navigate("/skills");
} else if (e.deltaY < 1 && location.pathname === "/skills") {
navigate("");
} else if (e.deltaY > 1 && location.pathname === "/skills") {
navigate("/aboutme");
} else if (e.deltaY < 1 && location.pathname === "/aboutme") {
navigate("/skills");
} else if (e.deltaY > 1 && location.pathname === "/aboutme") {
navigate("/work");
} else if (e.deltaY < 1 && location.pathname === "/work") {
navigate("/aboutme");
}
}
}
return <Context.Provider value={{}}>{children}</Context.Provider>;
}
export { ContextProvider, Context };
</code></pre>
<p>now this is working perfectly fine however in the <code>work</code> component I have nested routes (e.g. <code>/work/blahblahblah</code>) where I don't want the mouse wheel to scroll to different routes, so you can see on the first line of the <code>handleNavigation()</code> function I added a simple conditional where if the <code>location.pathname</code> contains <code>/work/</code> to return out of the function and not run the logic below.</p>
<p>However I have found that this is not working, when I scroll to the <code>/work</code> route and then click to go into the nested route scrolling still runs the logic below the if statement taking me to routes which I did not intend for, if I for example manually in the address bar go into the nested route such as <code>/work/foo</code> and then try scrolling my if conditional works correctly and scrolling on that page does not navigate me to different routes.</p>
<p>for a replicable example please look here:</p>
<p><a href="https://codesandbox.io/s/fast-sky-kbm006?fontsize=14&hidenavigation=1&theme=dark" rel="nofollow noreferrer"><img src="https://codesandbox.io/static/img/play-codesandbox.svg" alt="Edit fast-sky-kbm006" /></a></p>
<p>scroll with the mouse wheel down to the <code>/work</code> route and then click the link to take you to the <code>/work/click-here</code> link.</p>
<p>I have tried playing around with the <code>useEffect</code> dependency array but nothing seems to be working.</p>
| [
{
"answer_id": 74418998,
"author": "John Hanley",
"author_id": 8016720,
"author_profile": "https://Stackoverflow.com/users/8016720",
"pm_score": 1,
"selected": false,
"text": "storage.objects.update"
},
{
"answer_id": 74420402,
"author": "Sathi Aiswarya",
"author_id": 18265638,
"author_profile": "https://Stackoverflow.com/users/18265638",
"pm_score": 0,
"selected": false,
"text": "Owner"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5580057/"
] |
74,418,599 | <p>New to vuejs. I am trying to write javascript directly in the vue file. Below is the code. I keep getting the following errors...</p>
<p>compiled with problems</p>
<pre><code> 70:18 error 'openpopup' is defined but never used no-unused-vars
73:18 error 'closepopup' is defined but never used no-unused-vars
</code></pre>
<p>Html with script:</p>
<pre><code><template>
<div class="customers-page">
<h2>Customers</h2>
<button type="add" class="add-button" onclick="openpopup()">Add</button>
<div class="popup" id="popup">
<h3>Input the following information</h3>
<button type="add-customer" class="submit-customer-button" onclick="closepopup()">Submit</button>
</div>
</div>
</template>
<script type="application/javascript" >
let popup = document.getElementById("popup");
function openpopup(){
popup.classList.add("open-popup")
}
function closepopup(){
popup.classList.remove("open-popup")
}
</script>
</code></pre>
| [
{
"answer_id": 74418659,
"author": "Kaneki21",
"author_id": 19514458,
"author_profile": "https://Stackoverflow.com/users/19514458",
"pm_score": 3,
"selected": true,
"text": "Vue"
},
{
"answer_id": 74420077,
"author": "Remicaster",
"author_id": 18665782,
"author_profile": "https://Stackoverflow.com/users/18665782",
"pm_score": 0,
"selected": false,
"text": ".getElementById"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20490297/"
] |
74,418,606 | <p>I am a beginner and I am trying to learn Next js. I have a webpage which has a card and in the card i have an Arrow Right. I want a link to open when the Arrow right is clicked.</p>
<p>I have this code for the ArrowRight and I basically want to open a link, lets say google.com in a new tab on the click of this.</p>
<pre><code><ArrowRight
className="heart"
onClick={}
/>
</code></pre>
| [
{
"answer_id": 74418623,
"author": "Ali Sattarzadeh",
"author_id": 11434567,
"author_profile": "https://Stackoverflow.com/users/11434567",
"pm_score": 2,
"selected": false,
"text": " <a href=\"https://www.google.com/\" target=\"_blank\">\n <ArrowRight\n className=\"heart\" \n />\n </a>\n"
},
{
"answer_id": 74418636,
"author": "DevAra",
"author_id": 4122324,
"author_profile": "https://Stackoverflow.com/users/4122324",
"pm_score": 0,
"selected": false,
"text": " export default function SampleComponent(){\n \n const redirectPage= (e) => {\n e.preventDefault()\n document.location.href = 'https://google.com/';\n }\n return(\n <div>\n <ArrowRight\n className=\"heart\"\n onClick={() => redirectPage()}\n />\n </div>\n )\n }\n"
},
{
"answer_id": 74418701,
"author": "Lakruwan Pathirage",
"author_id": 12383492,
"author_profile": "https://Stackoverflow.com/users/12383492",
"pm_score": 0,
"selected": false,
"text": "import Link from \"next/link\";\n\n\n<Link href=\"https://www.google.com/\" target=\"_blank\">\n <ArrowRight\n className=\"heart\" \n />\n </Link >\n"
},
{
"answer_id": 74418797,
"author": "Kundan",
"author_id": 11003837,
"author_profile": "https://Stackoverflow.com/users/11003837",
"pm_score": 0,
"selected": false,
"text": "<ArrowRight\n className=\"heart\"\n onClick={() => window.open(\"google.com\", \"_blank\")}\n/>\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19472616/"
] |
74,418,628 | <pre><code>#include<iostream>
using namespace std;
void reverse(int arr[],int n){
int start=0,end=n-1;
int temp;
while(start<=end){
temp=arr[end];
arr[end]=arr[start];
arr[start]=temp;
}
start++;
end--;
}
void print(int arr[],int n){
for(int i=0;i<n;i++){
cout<<arr;
}
cout<<endl;
}
int main(){
int arr[5]={1,2,3,4,5};
int brr[6]={3,6,8,2,1,0};
reverse(arr,5);
reverse(brr,6);
print(arr,5);
print(brr,6);
}
</code></pre>
<p>I am not able to run this code at any compiler, can anyone tell me where I am making the mistake
after running it I am getting nothing</p>
| [
{
"answer_id": 74418678,
"author": "Pepijn Kramer",
"author_id": 16649550,
"author_profile": "https://Stackoverflow.com/users/16649550",
"pm_score": 1,
"selected": false,
"text": "using namespace std;"
},
{
"answer_id": 74418767,
"author": "Lasersköld",
"author_id": 3748275,
"author_profile": "https://Stackoverflow.com/users/3748275",
"pm_score": 0,
"selected": false,
"text": "std::reverse()"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16951269/"
] |
74,418,639 | <p>I've been trying to align the entries and buttons on this password manager I built for a while now but haven't been able to find a solution that works.<a href="https://i.stack.imgur.com/QWFGb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QWFGb.png" alt="The password manager that I built" /></a></p>
<p>I tried changing the width, columnspan, and coordinates but it doesn't seem to work.
I want the password entry to be aligned just like the other two but with a lower width so that the generate button does not go over. I also want the add button to be aligned equally with the row and column.</p>
<pre><code>window = Tk()
window.title("Password Manager")
window.config(padx=50, pady=50)
canvas = Canvas(width=200, height=200)
my_pass_img = PhotoImage(file="logo.png")
canvas.create_image(100, 100, image=my_pass_img)
canvas.grid(column=1, row=0)
web_label = Label(text="Website:", fg="black")
web_label.grid(row=1, column=0)
user_label = Label(text="Email/Username:", fg="black")
user_label.grid(row=2, column=0)
pass_label = Label(text="Password:", fg="black")
pass_label.grid(row=3, column=0)
web_entry = Entry(width=35)
web_entry.grid(row=1, column=1, columnspan=2)
web_entry.focus()
user_entry = Entry(width=35)
user_entry.grid(row=2, column=1, columnspan=2)
user_entry.insert(0, "-@gmail.com")
pass_entry = Entry(width=30)
pass_entry.grid(row=3, column=1)
generate_button = Button(text="Generate Password", fg="black", command=generate_password)
generate_button.grid(row=3, column=2)
add_button = Button(width=36, text="Add", fg="black", command=save)
add_button.grid(row=4, column=1, columnspan=2)
window.mainloop()
</code></pre>
| [
{
"answer_id": 74420632,
"author": "acw1668",
"author_id": 5317403,
"author_profile": "https://Stackoverflow.com/users/5317403",
"pm_score": 0,
"selected": false,
"text": "sticky"
},
{
"answer_id": 74420777,
"author": "Pavloski",
"author_id": 19665312,
"author_profile": "https://Stackoverflow.com/users/19665312",
"pm_score": 1,
"selected": false,
"text": "sticky"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19975231/"
] |
74,418,650 | <p>My ultimate goal is a function combining two nested lists, like this:</p>
<pre><code>def tuples_maker(l1, l2):
return sample_data
</code></pre>
<p>I know that I can use zip, but I don't know how to utilize "for" loop. I got stuck at first step then I cannot continue....</p>
<p>for example,</p>
<pre><code>l1 = [[1,2,3,4], [10,11,12]]
l2 = [[-1,-2,-3,-4], [-10,-11,-12]]
</code></pre>
<p>I want something like this:</p>
<pre><code>[[(1, -1), (2, -2), (3, -3), (4, -4)], [(10, -10), (11, -11), (12, -12)]]
</code></pre>
<p>On stack overflow I actually found a solution
<a href="https://stackoverflow.com/a/13675517/12159353">https://stackoverflow.com/a/13675517/12159353</a></p>
<pre><code>print(list(zip(a,b) for a,b in zip(l1,l2)))
</code></pre>
<p>but it generates a iteration not a list:</p>
<pre><code>[<zip object at 0x000002286F965208>, <zip object at 0x000002286F965AC8>]
</code></pre>
<p>so I try not to use list comprehension:</p>
<pre><code>for a,b in zip(l1,l2):
c=list(zip(a,b))
print(c)
</code></pre>
<p>it is overlapped:</p>
<pre><code>[(10, -10), (11, -11), (12, -12)]
</code></pre>
<p>I know this's not right but I still make a try:</p>
<pre><code>for a,b in zip(l1,l2):
c=list(zip(a,b))
print(c)
</code></pre>
<p>Now it seems right, but not a list:</p>
<pre><code>[(1, -1), (2, -2), (3, -3), (4, -4)]
[(10, -10), (11, -11), (12, -12)]
</code></pre>
<p>Can anyone help me with this? Thanks in advance!</p>
| [
{
"answer_id": 74420632,
"author": "acw1668",
"author_id": 5317403,
"author_profile": "https://Stackoverflow.com/users/5317403",
"pm_score": 0,
"selected": false,
"text": "sticky"
},
{
"answer_id": 74420777,
"author": "Pavloski",
"author_id": 19665312,
"author_profile": "https://Stackoverflow.com/users/19665312",
"pm_score": 1,
"selected": false,
"text": "sticky"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12159353/"
] |
74,418,658 | <p>I'm running <code>wsl -l -v</code> to get a list of WSL VMs on my computer and I get a list like this:</p>
<pre class="lang-none prettyprint-override"><code>NAME STATE VERSION
Ubuntu-18-04 Stopped 2
Ubuntu-20-04 Running 2
</code></pre>
<p>I only want to see the ones that are running.<br />
I tried:</p>
<pre><code>wsl -l -v | Select-Object NAME
</code></pre>
<p>but I just get a list of blank lines.</p>
| [
{
"answer_id": 74420632,
"author": "acw1668",
"author_id": 5317403,
"author_profile": "https://Stackoverflow.com/users/5317403",
"pm_score": 0,
"selected": false,
"text": "sticky"
},
{
"answer_id": 74420777,
"author": "Pavloski",
"author_id": 19665312,
"author_profile": "https://Stackoverflow.com/users/19665312",
"pm_score": 1,
"selected": false,
"text": "sticky"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33581/"
] |
74,418,687 | <p>i'm new to python and programming at all
Was trying to make a code to give me all the factors of a number, but can't see where i'm lacking</p>
<pre><code>def divisores(numero):
divisor = 0
while divisor < numero :
divisor += 1
if numero % divisor == 0:
return(divisor)
divisores(50)
</code></pre>
<p>all it shows is "1", that is the first factor. If i use "print", it indeed gives all the factors,but i wanted it to be all in a single line</p>
| [
{
"answer_id": 74418700,
"author": "selbie",
"author_id": 104458,
"author_profile": "https://Stackoverflow.com/users/104458",
"pm_score": 1,
"selected": false,
"text": "def divisores(numero):\n divisor = 0\n divs = [] # empty list\n while divisor <= numero :\n divisor += 1\n if numero % divisor == 0:\n divs.append(divisor)\n return divs\n"
},
{
"answer_id": 74420941,
"author": "Cobra",
"author_id": 17580381,
"author_profile": "https://Stackoverflow.com/users/17580381",
"pm_score": 0,
"selected": false,
"text": "def factors(n):\n def y(f):\n nonlocal neg\n yield f\n if neg:\n yield -f\n if n == 0:\n raise ValueError('Cannot factor zero')\n if neg := n < 0:\n n = -n\n yield from y(1)\n for factor in range(2, n // 2 + 1):\n if n % factor == 0:\n yield from y(factor)\n yield from y(n)\n\nprint(*factors(50))\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20490432/"
] |
74,418,713 | <p>If we have a dataframe like the below one</p>
<pre><code> A B C
0 5 3 8
1 5 3 9
2 8 4 9
</code></pre>
<p>We can calculate the mean using <code>df.mean()</code> and the output looks like</p>
<pre><code>A 6.000000
B 3.333333
C 8.666667
dtype: float64
</code></pre>
<p>Now, I want to save the mean in a column-wise format like the below one.</p>
<pre><code> A B C
0 6.0 3.3 8.6
</code></pre>
<p>How can I do this?</p>
<p>I have gone through a couple of posts but have not gotten any idea and the sample data was taken from this <a href="https://stackoverflow.com/questions/31037298/pandas-get-column-average-mean">post</a>.</p>
| [
{
"answer_id": 74418749,
"author": "ThePyGuy",
"author_id": 9136348,
"author_profile": "https://Stackoverflow.com/users/9136348",
"pm_score": 2,
"selected": true,
"text": "to_frame"
},
{
"answer_id": 74418859,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 0,
"selected": false,
"text": "out = pd.DataFrame([df.mean()])\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3291513/"
] |
74,418,716 | <p>I want to make a 404 page for a single page React app. This is my current code:</p>
<pre class="lang-js prettyprint-override"><code>import { BrowserRouter as Router, Route, Routes} from "react-router-dom";
export default function App() {
return (
<>
<Router>
<Routes>
<Route path = "/">
<Navbar/>
<Home />
<Experience />
<Skills />
<Projects />
<Contact />
<Floaters />
<Cursor />
</Route>
<Route path = "*">
<NotFound/>
</Route>
</Routes>
</Router>
</>
);
}
</code></pre>
<p>My localhost just shows a blank page. What is wrong here?</p>
<p>Do all of the components need to be a single component for this to work?</p>
| [
{
"answer_id": 74418749,
"author": "ThePyGuy",
"author_id": 9136348,
"author_profile": "https://Stackoverflow.com/users/9136348",
"pm_score": 2,
"selected": true,
"text": "to_frame"
},
{
"answer_id": 74418859,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 0,
"selected": false,
"text": "out = pd.DataFrame([df.mean()])\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418716",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16120374/"
] |
74,418,720 | <p>Suppose there is an array like this:</p>
<pre><code>const a = [ {p:1}, {p:2}, {p:3} ];
</code></pre>
<p>Is it possible to destructure this array in order to obtain <code>p = [1, 2, 3]</code> ?</p>
<p>Because this does not work :</p>
<pre><code>const [ ...{ p } ] = a; // no error, same as const p = a.p;
// p = undefined;
</code></pre>
<hr />
<p><strong>Edit</strong></p>
<p>In response to all the answers saying that I need to use <code>Array.prototype.map</code>, I am aware of this. I was simply wondering if there was a way to map <em>during</em> the destructuring process, and the answer is : no, I need to destructure the array itself, then use map as a separate step.</p>
<p>For example:</p>
<pre><code>const data = {
id: 123,
name: 'John',
attributes: [{ id:300, label:'attrA' }, { id:301, label:'attrB' }]
};
function format(data) {
const { id, name, attributes } = data;
const attr = attributes.map(({ label }) => label);
return { id, name, attr };
}
console.log( format(data) };
// { id:123, name:'John', attr:['attrA', 'attrB'] }
</code></pre>
<p>I was simply wondering if there was a way, directly during destructuring, without using <code>map</code> (and, respectfully, without the bloated <code>lodash</code> library), to retrive all <code>label</code> properties into an array of strings.</p>
| [
{
"answer_id": 74418755,
"author": "Antony Acosta",
"author_id": 9596863,
"author_profile": "https://Stackoverflow.com/users/9596863",
"pm_score": 3,
"selected": true,
"text": "map"
},
{
"answer_id": 74418774,
"author": "Ali Sattarzadeh",
"author_id": 11434567,
"author_profile": "https://Stackoverflow.com/users/11434567",
"pm_score": 0,
"selected": false,
"text": "const [{ p }] = a;\n"
},
{
"answer_id": 74418789,
"author": "Brother58697",
"author_id": 17804016,
"author_profile": "https://Stackoverflow.com/users/17804016",
"pm_score": 0,
"selected": false,
"text": "const group = (array) => array.reduce((acc,obj) => {\n for(let [key,val] of Object.entries(obj)){\n acc[key] ||= [];\n acc[key].push(val)\n }\n return acc\n }, {})\n\nconst ar = [ {p:1}, {p:2}, {p:3} ]; \nconst {p} = group(ar)\nconsole.log(p)\n\nconst ar2 = [{a:2,b:1},{a:5,b:4}, {c:1}]\nconst {a,b,c} = group(ar2)\nconsole.log(a,b,c)"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/320700/"
] |
74,418,735 | <p>I am new to bash (but not to programming). I have a bash script that looks for all <code>.txt</code> files in a project</p>
<pre><code>for i in `find . -name "*.txt"`;
do
basename= "${i}"
cp ${basename} ./dest
done
</code></pre>
<p>However, I would like to get the .txt files only from a specific sub directory. For e.g this is my project structure:</p>
<pre><code>project/
├── controllers/
│ ├── a/
│ │ ├── src/
│ │ │ ├── xxx
│ │ │ └── xxx
│ │ └── files/
│ │ ├── abc.txt
│ │ └── xxxx
│ └── b/
│ ├── src/
│ │ ├── xxx
│ │ └── xxx
│ └── files/
│ ├── abcd.txt
│ └── xxxx
├── lib
└── tests
</code></pre>
<p>I would like to get <code>.txt</code> files only from <code>controllers/a/files</code> and <code>controllers/b/files</code>. I tried replacing <code>find . -name "*.txt"</code> with <code>find ./controllers/*/files/*txt</code>, it works fine, but errors out on GitHub actions with <code>No such file or directory found</code>. So I'm looking for a more robust way of finding <code>.txt</code> files from the subdirectory without having to hardcode the path in the for loop. Is that possible?</p>
| [
{
"answer_id": 74418762,
"author": "David C. Rankin",
"author_id": 3422102,
"author_profile": "https://Stackoverflow.com/users/3422102",
"pm_score": 3,
"selected": true,
"text": "find ./project/controllers/{a,b} -type f -name \"*.txt\"\n"
},
{
"answer_id": 74419530,
"author": "M. Nejat Aydin",
"author_id": 13809001,
"author_profile": "https://Stackoverflow.com/users/13809001",
"pm_score": 0,
"selected": false,
"text": "cp"
},
{
"answer_id": 74428759,
"author": "user1934428",
"author_id": 1934428,
"author_profile": "https://Stackoverflow.com/users/1934428",
"pm_score": 0,
"selected": false,
"text": "find ./controllers/*/files/*txt"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6466023/"
] |
74,418,739 | <p>I am trying to create a new row automatically, every night in Google sheet with todays date as top row.</p>
<p>I have added the following script and set a daily trigger and it is working fine, but I have formulas in several columns and I wish to retain them in the newly added row. Can someone help me edit the script to do this? Thanks
`</p>
<pre><code>function addNewRow() {
var spreadsheet = SpreadsheetApp.openById("1xwF-kM6KvOJYAfsmcDVBgO0yv6ZcFFMFvH33U7SzGtc");
var sheet = spreadsheet.getSheetByName("Attendance");
sheet.insertRowBefore(2);
var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();
today = dd + '/' + mm + '/' + yyyy;
sheet.getRange(2,3).setValue(today);
</code></pre>
<p>`
<a href="https://i.stack.imgur.com/GlTuC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GlTuC.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74418762,
"author": "David C. Rankin",
"author_id": 3422102,
"author_profile": "https://Stackoverflow.com/users/3422102",
"pm_score": 3,
"selected": true,
"text": "find ./project/controllers/{a,b} -type f -name \"*.txt\"\n"
},
{
"answer_id": 74419530,
"author": "M. Nejat Aydin",
"author_id": 13809001,
"author_profile": "https://Stackoverflow.com/users/13809001",
"pm_score": 0,
"selected": false,
"text": "cp"
},
{
"answer_id": 74428759,
"author": "user1934428",
"author_id": 1934428,
"author_profile": "https://Stackoverflow.com/users/1934428",
"pm_score": 0,
"selected": false,
"text": "find ./controllers/*/files/*txt"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4486377/"
] |
74,418,761 | <p>Lately I have started to use venv virtual environments for my development. (before I was just using docker images and conda environments)</p>
<p>However I notice that virtual environments are created for some code you have.</p>
<p>My question is isn't that wasteful?</p>
<p>I mean if we have 20 repos of code, and they all need opencv, having 20 virtual environments make it install opencv 20 times?</p>
<p>What is under the hood of the virtual environment practice?</p>
| [
{
"answer_id": 74418762,
"author": "David C. Rankin",
"author_id": 3422102,
"author_profile": "https://Stackoverflow.com/users/3422102",
"pm_score": 3,
"selected": true,
"text": "find ./project/controllers/{a,b} -type f -name \"*.txt\"\n"
},
{
"answer_id": 74419530,
"author": "M. Nejat Aydin",
"author_id": 13809001,
"author_profile": "https://Stackoverflow.com/users/13809001",
"pm_score": 0,
"selected": false,
"text": "cp"
},
{
"answer_id": 74428759,
"author": "user1934428",
"author_id": 1934428,
"author_profile": "https://Stackoverflow.com/users/1934428",
"pm_score": 0,
"selected": false,
"text": "find ./controllers/*/files/*txt"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4451521/"
] |
74,418,804 | <p>I wanted to my program display a list and ask the user what list item they completed. After they input that which will be an item in the list, it should insert an "X " in front of it. E.g if the list is [homework, chores] the list should then become [X homework, chores] if the user inputs "homework".</p>
<pre><code>
run = True
while run:
input000 = input("Which items do you wish to record as done?")
# Something the adds X to the front of the chosen list item (from the input)
</code></pre>
| [
{
"answer_id": 74418843,
"author": "D.Manasreh",
"author_id": 7509907,
"author_profile": "https://Stackoverflow.com/users/7509907",
"pm_score": 0,
"selected": false,
"text": "for item in list_item:\n if item == input000:\n item = 'X ' + item\n"
},
{
"answer_id": 74418861,
"author": "Attiq Rahman",
"author_id": 19311030,
"author_profile": "https://Stackoverflow.com/users/19311030",
"pm_score": 2,
"selected": false,
"text": "list_item = [\"homework\", \"chores\"]\nwhile True:\n input000 = input(\"enter something\")\n for i in range(len(list_item)):\n if input000 == list_item[i]:\n list_item[i] = f\"X {list_item[i]}\"\n"
},
{
"answer_id": 74419086,
"author": "Cobra",
"author_id": 17580381,
"author_profile": "https://Stackoverflow.com/users/17580381",
"pm_score": 1,
"selected": false,
"text": "todo_list = ['homework', 'chores']\n\ndef todo():\n for e in todo_list:\n if e[0] != 'X':\n yield e\n\nwhile sum(1 for _ in todo()) > 0:\n print(*todo(), sep='\\n')\n item = input('Choose something: ')\n try:\n i = todo_list.index(item)\n todo_list[i] = f'X {item}'\n except ValueError:\n print(\"\\aThat's not in the list\")\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17347665/"
] |
74,418,821 | <p>I have a program which I have set up several jobs inside it. According to the figure, these jobs are executed every day at a certain time and, for example, send an SMS to a group of numbers.
When I deploy this to Kubernetes, multiple copies are created.
I want to know, do all these original and replica versions do this and send SMS? If it is true that one SMS should be sent to one number, not that several SMS messages should be sent to the same number.
My question is, how does Kubernetes deal with these programs and how should we deploy them correctly?
<a href="https://i.stack.imgur.com/nlLGN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nlLGN.png" alt="enter image description here" /></a></p>
<p>I have read various articles but I don't know which is the right way.</p>
| [
{
"answer_id": 74419056,
"author": "Amila Senadheera",
"author_id": 8510405,
"author_profile": "https://Stackoverflow.com/users/8510405",
"pm_score": 1,
"selected": false,
"text": "CronJob"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20490532/"
] |
74,418,851 | <p>According to the official documentation of React, key attributes are needed to let React know if any element in the array is added, removed, or modified.
So supposed I have a nested for loop in a render function.</p>
<p>Supposed we have</p>
<pre><code>parents.map((each, index)=>{
return(
<div key={index}>
each.map((number, i)=>{
return <Child number={number} key={i} />
})
</div>
)
});
</code></pre>
<p>Both the parent div elements and the Child components have key attribute to identify them, and they are all in an array. However, do all the values of the key attributes among the div and the Child component need to be unique? None the less, they are from different loops. In case each item inside the parents array is also an array, and all of these arrays have a same length. Eventually, the "key" value will be duplicated, such as</p>
<pre><code>const parents = [[1,2],[2,3]]
</code></pre>
<p>We will have</p>
<pre><code><div key={0}>
<Child number={1} key={0} />
<Child number={2} key={1} />
</div>
<div key={1}>
<Child number={2} key={0} />
<Child number={3} key={1} />
</div>
</code></pre>
| [
{
"answer_id": 74419066,
"author": "Lakruwan Pathirage",
"author_id": 12383492,
"author_profile": "https://Stackoverflow.com/users/12383492",
"pm_score": -1,
"selected": false,
"text": "export default function App() {\n let val = 0;\n const parents = [\n [1, 2],\n [2, 3]\n ];\n\n return (\n <div>\n {parents.map((each, index) => {\n val = val + 1;\n return (\n <div key={val}>\n {val}\n {each.map((number, i) => {\n val = val + 1;\n return <div key={val}> {val}</div>;\n })}\n </div>\n );\n })}\n </div>\n );\n}\n"
},
{
"answer_id": 74419243,
"author": "DSDmark",
"author_id": 16517581,
"author_profile": "https://Stackoverflow.com/users/16517581",
"pm_score": 0,
"selected": false,
"text": "which in turn leads to better performance"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6707111/"
] |
74,418,884 | <p>Help me please.
I have a 3d vector. I need to make a new vector from this using existing internal indices. I hope the input and output information will be clear.</p>
<p>Input:</p>
<pre><code> a = {
{ {1,1,1,1}, {2,2,2,2}, {3,3,3,3}, {4,4,4,4}, {5,5,5,5}, {6,6,6,6} },
{ {10,10,10,10}, {20,20,20,20}, {30,30,30,30}, {40,40,40,40}, {50,50,50,50}, {60,60,60,60} },
{ {100,100,100,100}, {200,200,200,200}, {300,300,300,300}, {400,400,400,400}, {500,500,500,500}, {600,600,600,600} },
};
</code></pre>
<p>Output:</p>
<pre><code> b = {
{{ 1,1,1,1}, {10,10,10,10}, {100,100,100,100}},
{{ 2,2,2,2}, {20,20,20,20}, {200,200,200,200}},
{{ 3,3,3,3}, {30,30,30,30}, {300,300,300,300}},
{{ 4,4,4,4}, {40,40,40,40}, {400,400,400,400}},
{{ 5,5,5,5}, {50,50,50,50}, {500,500,500,500}},
{{ 6,6,6,6}, {60,60,60,60}, {600,600,600,600}},
}
</code></pre>
<p>I don't know how to iterate over indices in a 3D array to create a new 3D array (Output). I want to create a 3D vector from the columns (n-indices) of an existing 3D vector. I have a 3D vector ('Input'). I need to make a 3D vector out of this ('Output').</p>
<pre><code>#include <iostream>
#include <vector>
using namespace std;
void show3D_vector(std::vector<std::vector<std::vector<double>>>& a);
void show2D_vector(std::vector<std::vector<double>>& a);
template<typename T> std::vector<std::vector<T>> SplitVector(const std::vector<T>& vec, size_t n);
int main()
{
a = {
{ {1,1,1,1}, {2,2,2,2}, {3,3,3,3}, {4,4,4,4}, {5,5,5,5}, {6,6,6,6} },
{ {10,10,10,10}, {20,20,20,20}, {30,30,30,30}, {40,40,40,40}, {50,50,50,50}, {60,60,60,60} },
{ {100,100,100,100}, {200,200,200,200}, {300,300,300,300}, {400,400,400,400}, {500,500,500,500}, {600,600,600,600} },
};
}
void show3D_vector(std::vector<std::vector<std::vector<double>>>& a)
{
for (double i = 0; i < a.size(); ++i)
{
for (double j = 0; j < a[i].size(); ++j)
{
for (double k = 0; k < a[i][j].size(); ++k)
std::cout << a[i][j][k] << " ";
std::cout << endl;
}
std::cout << endl;
}
}
void show2D_vector(std::vector<std::vector<double>>& a)
{
for (int i = 0; i < a.size(); i++) {
for (auto it = a[i].begin(); it != a[i].end(); it++)
{
std::cout << *it << " ";
}
std::cout << endl << endl;
}
}
template<typename T>
std::vector<std::vector<T>> SplitVector(const std::vector<T>& vec, size_t n)
{
std::vector<std::vector<T>> outVec;
size_t length = vec.size() / n;
size_t remain = vec.size() % n;
size_t begin = 0;
size_t end = 0;
for (size_t i = 0; i < std::min(n, vec.size()); ++i)
{
end += (remain > 0) ? (length + !!(remain--)) : length;
outVec.push_back(std::vector<T>(vec.begin() + begin, vec.begin() + end));
begin = end;
}
return outVec;
}
</code></pre>
<p>Thank you.</p>
| [
{
"answer_id": 74420237,
"author": "shy45",
"author_id": 20313707,
"author_profile": "https://Stackoverflow.com/users/20313707",
"pm_score": 2,
"selected": true,
"text": " for(const auto& a1 : a){\n b.resize(a1.size());\n auto b1 = b.begin();\n for(const auto& a2 : a1){\n b1->push_back(a2);\n b1++;\n }\n }\n"
},
{
"answer_id": 74422593,
"author": "PaulMcKenzie",
"author_id": 3133316,
"author_profile": "https://Stackoverflow.com/users/3133316",
"pm_score": 0,
"selected": false,
"text": "n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20477416/"
] |
74,418,918 | <p>What I need is to increase the value of a variable dynamically (within a loop) by another variable. Here is my code:</p>
<pre><code>while read Plate City Town Village Area Population; do
echo "$Plate $City $Town $Village $Area $Population"
printf "\n$totalNumberOfTowns\n "
totalNumberOfTowns=$totalNumberOfTowns+$Town
totalNumberOfVillages=$totalNumberOfVillages+$Village
done < "cities.txt"
</code></pre>
<p>what I get when I run my code is a little bit not-correct.
<img src="https://i.stack.imgur.com/FOAN1.png" alt="enter image description here" /></p>
<p>I didn't understand why there is "Town" inside $totalNumberOfTowns variable. Another interesting part is it also does calculation(it sums third parameter which is number of town in that city. For ADANA it is 15 and for ADIYAMAN it is 9 and so on.).</p>
<h1><strong>Edit:</strong></h1>
<p>First line of cities.txt is:</p>
<p>Plate City Town Village Area Population</p>
<p>see screenshot:<br />
<img src="https://i.stack.imgur.com/XjKnX.png" alt="enter image description here" /></p>
<h1><strong>Edit-2:</strong> # I have tried these different syntaxes:</h1>
<pre><code>let "totalNumberOfTowns+=$Town" #1 I tried these different syntaxes
totalNumberOfTowns=$((expr $totalNumberOfTowns + $Town)) #2
totalNumberOfTowns=$((totalNumberOfTowns + Town)) #3
</code></pre>
<p>Yet, each of them gave me some errors.</p>
<p>Here are sample cities.txt and sample code:</p>
<p>Plate City Town Village Area Population
1 ADANA 15 508 14030 2258718
2 ADIYAMAN 9 420 7614 632459
3 AFYONKARAHİSAR 18 395 14230 736912
4 AĞRI 8 566 11376 535435
5 AMASYA 7 352 5520 335494
6 ANKARA 25 711 25706 5663322
7 ANTALYA 19 545 20723 2548308
34 İSTANBUL 40 166 5196 15462452</p>
<p><strong>code</strong></p>
<pre><code>#!/usr/bin/env bash
average=0
numberOfCities=80
declare -i totalNumberOfTowns=0 totalNumberOfVillages=0
arrayWithOut=""
while read Plate City Town Village Area Population; do
echo "$Plate $City $Town $Village $Area $Population"
printf "\n$totalNumberOfTowns\n "
totalNumberOfTowns+=$Town
totalNumberOfVillages+=$Village
done < "cities.txt"
</code></pre>
| [
{
"answer_id": 74418927,
"author": "Maxwell D. Dorliea",
"author_id": 12906648,
"author_profile": "https://Stackoverflow.com/users/12906648",
"pm_score": 0,
"selected": false,
"text": "$((your_expression))"
},
{
"answer_id": 74419100,
"author": "Shawn",
"author_id": 9952196,
"author_profile": "https://Stackoverflow.com/users/9952196",
"pm_score": 1,
"selected": false,
"text": "#!/usr/bin/env bash\n\ndeclare -i totalNumberOfTowns=0 totalNumberOfVillages=0\n\nwhile read Plate City Town Village Area Population; do\n printf \"%s %s %s %s %s %s\\n\" \"$Plate\" \"$City\" \"$Town\" \"$Village\" \"$Area\" \"$Population\"\n totalNumberOfTowns+=$Town\n totalNumberOfVillages+=$Village\ndone < \"cities.txt\"\n\nprintf \"Total towns: %d\\nTotal villages: %d\\n\" \"$totalNumberOfTowns\" \"$totalNumberOfVillages\"\n"
},
{
"answer_id": 74419177,
"author": "KamilCuk",
"author_id": 9072753,
"author_profile": "https://Stackoverflow.com/users/9072753",
"pm_score": 2,
"selected": true,
"text": "#!/usr/bin/env bash\n\naverage=0\nnumberOfCities=80\n\ndeclare -i totalNumberOfTowns=0 totalNumberOfVillages=0\narrayWithOut=\"\"\n\n{\nread -r first_line\nwhile read -r Plate City Town Village Area Population; do\n echo \"$Plate $City $Town $Village $Area $Population\"\n\n printf \"\\n$totalNumberOfTowns\\n \" \n totalNumberOfTowns+=$Town\n totalNumberOfVillages+=$Village\n\ndone \n} < \"cities.txt\"\n"
},
{
"answer_id": 74423770,
"author": "tink",
"author_id": 1394729,
"author_profile": "https://Stackoverflow.com/users/1394729",
"pm_score": 0,
"selected": false,
"text": "awk"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10446509/"
] |
74,418,933 | <p>I'm designing a landing page containing multiple sections each having the same padding from left and right but different background colors. Can I apply this padding to the entire landing page? The issue I'm supposed to face is that the padded area will have the background color of that page not of that section( as it varies for each section). Any feasible solution to this problem would be appreciated. I've attached a screenshot of that page as well.<a href="https://i.stack.imgur.com/Rm7Lk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Rm7Lk.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74418927,
"author": "Maxwell D. Dorliea",
"author_id": 12906648,
"author_profile": "https://Stackoverflow.com/users/12906648",
"pm_score": 0,
"selected": false,
"text": "$((your_expression))"
},
{
"answer_id": 74419100,
"author": "Shawn",
"author_id": 9952196,
"author_profile": "https://Stackoverflow.com/users/9952196",
"pm_score": 1,
"selected": false,
"text": "#!/usr/bin/env bash\n\ndeclare -i totalNumberOfTowns=0 totalNumberOfVillages=0\n\nwhile read Plate City Town Village Area Population; do\n printf \"%s %s %s %s %s %s\\n\" \"$Plate\" \"$City\" \"$Town\" \"$Village\" \"$Area\" \"$Population\"\n totalNumberOfTowns+=$Town\n totalNumberOfVillages+=$Village\ndone < \"cities.txt\"\n\nprintf \"Total towns: %d\\nTotal villages: %d\\n\" \"$totalNumberOfTowns\" \"$totalNumberOfVillages\"\n"
},
{
"answer_id": 74419177,
"author": "KamilCuk",
"author_id": 9072753,
"author_profile": "https://Stackoverflow.com/users/9072753",
"pm_score": 2,
"selected": true,
"text": "#!/usr/bin/env bash\n\naverage=0\nnumberOfCities=80\n\ndeclare -i totalNumberOfTowns=0 totalNumberOfVillages=0\narrayWithOut=\"\"\n\n{\nread -r first_line\nwhile read -r Plate City Town Village Area Population; do\n echo \"$Plate $City $Town $Village $Area $Population\"\n\n printf \"\\n$totalNumberOfTowns\\n \" \n totalNumberOfTowns+=$Town\n totalNumberOfVillages+=$Village\n\ndone \n} < \"cities.txt\"\n"
},
{
"answer_id": 74423770,
"author": "tink",
"author_id": 1394729,
"author_profile": "https://Stackoverflow.com/users/1394729",
"pm_score": 0,
"selected": false,
"text": "awk"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18640404/"
] |
74,418,957 | <p>I have a requirement not to execute the code inside <code>useEffect()</code> when the component renders for the first time. For that, I defined a variable outside of the component function and set it to <code>true</code>. And then I checked if the variable is <code>true</code> inside <code>useEffect()</code> hook and if it was <code>true</code>, I set the variable to <code>false</code> and set it to <code>return</code> as shown below. But the code is not working as I expected. The code inside <code>useEffect()</code> executes regardless.</p>
<pre class="lang-js prettyprint-override"><code>import { useEffect, useState } from 'react';
let isInitial = true;
function App() {
const [message, setMessage] = useState('First');
useEffect(() => {
if (isInitial) {
isInitial = false;
return;
}
setMessage('Executed');
}, []);
return <p>{message}</p>;
}
export default App;
</code></pre>
<p>I wanted to print <strong>'First'</strong> inside the <code><p></code>. But the result was <strong>'Executed'</strong> inside <code><p></code> which is not what I expected.</p>
| [
{
"answer_id": 74418927,
"author": "Maxwell D. Dorliea",
"author_id": 12906648,
"author_profile": "https://Stackoverflow.com/users/12906648",
"pm_score": 0,
"selected": false,
"text": "$((your_expression))"
},
{
"answer_id": 74419100,
"author": "Shawn",
"author_id": 9952196,
"author_profile": "https://Stackoverflow.com/users/9952196",
"pm_score": 1,
"selected": false,
"text": "#!/usr/bin/env bash\n\ndeclare -i totalNumberOfTowns=0 totalNumberOfVillages=0\n\nwhile read Plate City Town Village Area Population; do\n printf \"%s %s %s %s %s %s\\n\" \"$Plate\" \"$City\" \"$Town\" \"$Village\" \"$Area\" \"$Population\"\n totalNumberOfTowns+=$Town\n totalNumberOfVillages+=$Village\ndone < \"cities.txt\"\n\nprintf \"Total towns: %d\\nTotal villages: %d\\n\" \"$totalNumberOfTowns\" \"$totalNumberOfVillages\"\n"
},
{
"answer_id": 74419177,
"author": "KamilCuk",
"author_id": 9072753,
"author_profile": "https://Stackoverflow.com/users/9072753",
"pm_score": 2,
"selected": true,
"text": "#!/usr/bin/env bash\n\naverage=0\nnumberOfCities=80\n\ndeclare -i totalNumberOfTowns=0 totalNumberOfVillages=0\narrayWithOut=\"\"\n\n{\nread -r first_line\nwhile read -r Plate City Town Village Area Population; do\n echo \"$Plate $City $Town $Village $Area $Population\"\n\n printf \"\\n$totalNumberOfTowns\\n \" \n totalNumberOfTowns+=$Town\n totalNumberOfVillages+=$Village\n\ndone \n} < \"cities.txt\"\n"
},
{
"answer_id": 74423770,
"author": "tink",
"author_id": 1394729,
"author_profile": "https://Stackoverflow.com/users/1394729",
"pm_score": 0,
"selected": false,
"text": "awk"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2497156/"
] |
74,418,977 | <p>I want to generate all config from a dict like this:</p>
<pre><code>dict = {
"a": [1,2,3],
"b":{
"b1":[True, False],
"b2":[0],
}
}
</code></pre>
<p>List attributes are needed to be enumerated.
And output is like this:</p>
<pre><code>config = [{
"a": 1,
"b":{
"b1":True,
"b2":0,
},
{
"a": 2,
"b":{
"b1":True,
"b2":0,
},
...
]
</code></pre>
<p>How can I reach this?</p>
<p>I think recursion is a good idea, but I don't know how to use it</p>
| [
{
"answer_id": 74418927,
"author": "Maxwell D. Dorliea",
"author_id": 12906648,
"author_profile": "https://Stackoverflow.com/users/12906648",
"pm_score": 0,
"selected": false,
"text": "$((your_expression))"
},
{
"answer_id": 74419100,
"author": "Shawn",
"author_id": 9952196,
"author_profile": "https://Stackoverflow.com/users/9952196",
"pm_score": 1,
"selected": false,
"text": "#!/usr/bin/env bash\n\ndeclare -i totalNumberOfTowns=0 totalNumberOfVillages=0\n\nwhile read Plate City Town Village Area Population; do\n printf \"%s %s %s %s %s %s\\n\" \"$Plate\" \"$City\" \"$Town\" \"$Village\" \"$Area\" \"$Population\"\n totalNumberOfTowns+=$Town\n totalNumberOfVillages+=$Village\ndone < \"cities.txt\"\n\nprintf \"Total towns: %d\\nTotal villages: %d\\n\" \"$totalNumberOfTowns\" \"$totalNumberOfVillages\"\n"
},
{
"answer_id": 74419177,
"author": "KamilCuk",
"author_id": 9072753,
"author_profile": "https://Stackoverflow.com/users/9072753",
"pm_score": 2,
"selected": true,
"text": "#!/usr/bin/env bash\n\naverage=0\nnumberOfCities=80\n\ndeclare -i totalNumberOfTowns=0 totalNumberOfVillages=0\narrayWithOut=\"\"\n\n{\nread -r first_line\nwhile read -r Plate City Town Village Area Population; do\n echo \"$Plate $City $Town $Village $Area $Population\"\n\n printf \"\\n$totalNumberOfTowns\\n \" \n totalNumberOfTowns+=$Town\n totalNumberOfVillages+=$Village\n\ndone \n} < \"cities.txt\"\n"
},
{
"answer_id": 74423770,
"author": "tink",
"author_id": 1394729,
"author_profile": "https://Stackoverflow.com/users/1394729",
"pm_score": 0,
"selected": false,
"text": "awk"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15768582/"
] |
74,418,984 | <p>I wanted to change the MUI-5 Accordion title font size. I think I have to override it. but I don't know how to override CSS in MUI-5. it also doesn't have 'SX', it has 'htmlSx'. I tried to use it. but it didn't work.</p>
<pre><code>const AccordionNew: FC<AccordionProps> = ({ header, children }) => {
return (
<Box>
<Accordion
defaultExpanded={false}
title={header}
detailsContent={children}
htmlSx={(theme: Theme) => ({
'& .MuiTypography-h5': {
fontSize: '9px',
}
}),
}
/>
</Box>
);
};
</code></pre>
<p>I tried to override the css</p>
| [
{
"answer_id": 74419022,
"author": "Ali Sattarzadeh",
"author_id": 11434567,
"author_profile": "https://Stackoverflow.com/users/11434567",
"pm_score": 0,
"selected": false,
"text": ".MuiAccordion-root .MuiAccordionSummary-content p{\n font-size:9px\n}\n"
},
{
"answer_id": 74419131,
"author": "Majid M.",
"author_id": 14986372,
"author_profile": "https://Stackoverflow.com/users/14986372",
"pm_score": 2,
"selected": true,
"text": "sx"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20490686/"
] |
74,418,989 | <p>How can i convert string into XPATH, below is the code</p>
<pre><code>let $ti := "item/title"
let $tiValue := "Welcome to America"
return db:open('test')/*[ $tiValue = $ti]/base-uri()
</code></pre>
| [
{
"answer_id": 74419022,
"author": "Ali Sattarzadeh",
"author_id": 11434567,
"author_profile": "https://Stackoverflow.com/users/11434567",
"pm_score": 0,
"selected": false,
"text": ".MuiAccordion-root .MuiAccordionSummary-content p{\n font-size:9px\n}\n"
},
{
"answer_id": 74419131,
"author": "Majid M.",
"author_id": 14986372,
"author_profile": "https://Stackoverflow.com/users/14986372",
"pm_score": 2,
"selected": true,
"text": "sx"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1856067/"
] |
74,418,999 | <p>I have several classes which all receive raw data on the form of an uint8 buffer, and the underlying datatype of the data in the buffer is decided at runtime. The buffer needs to go through a converter function that's templated, and decided in a big switch statement at runtime, depending on the received data type which templated version of the converter function that's going to be executed. So I have one 'inner' converter function, and one 'outer' switch function that calls different templated versions of the 'inner' function, depending on the data type that the underlying data had. Since the 'inner' converter functions all look a bit different, I have until now had a separate 'outer' function for every 'inner' function.</p>
<p>Now I want to do a more general 'outer' function that can take the the 'inner' function as an input argument. But I'm a bit stuck on how to do the templating.</p>
<p>This is my current approach:</p>
<pre><code>struct InputParams
{
size_t num_elements;
size_t num_bytes_per_vec;
};
struct OutputData
{
float *q0;
float *q1;
};
template <typename T> OutputData testFunction(const uint8_t* const input_data, const InputParams& input_params)
{
OutputData output;
// Allocate 'output' in some way...
const T* const t_ptr = reinterpret_cast<const T* const>(input_data);
for(size_t k = 0; k < input_params.num_elements; k++)
{
output.q0[k] = input_data[k];
output.q1[k] = ...
// ...
}
return output;
}
template <typename O, template <typename> typename F, typename T, typename I>
O applyFunctionForDataType(const uint8_t* const input_data,
const DataType data_type,
const F<T>& converter_function,
const I& input_params)
{
O output_data;
if (data_type == DataType::FLOAT)
{
output_data = converter_function<float>(input_data, input_params);
}
else if (data_type == DataType::DOUBLE)
{
output_data = converter_function<double>(input_data, input_params);
}
else if (data_type == DataType::INT8)
{
output_data = converter_function<int8_t>(input_data, input_params);
}
else if ...
return output_data;
}
</code></pre>
<p>The template arguments <code>typename O</code> and <code>typename I</code> are for the output data structure, and input parameters, as these differ depending on which function that will call all of this. In one use case, <code>OutputData</code> might have two float pointers, in another a float pointer and an int pointer. <code>InputParams</code> will probably always be pretty similar, but I figured I might as well have that as a template arguments, since <code>OutputData</code> already is one.</p>
<p>Calling <code>applyFunctionForDataType</code>:</p>
<pre><code>InputParams input_params;
OutputData oo = applyFunctionForDataType<OutputData>(data_ptr_, data_type_, testFunction, input_params);
</code></pre>
<p>I get the following error message from the compiler:</p>
<pre><code><source>:68:23: error: 'converter_function' does not name a template but is followed by template arguments
output_data = converter_function<float>(input_data, input_params);
^ ~~~~~~~
<source>:61:40: note: non-template declaration found by name lookup
const F<T>& converter_function,
</code></pre>
<p><a href="https://godbolt.org/z/WEEcjW57h" rel="nofollow noreferrer">Compiler test</a></p>
<p>Alternative solutions are of course welcome.</p>
| [
{
"answer_id": 74419022,
"author": "Ali Sattarzadeh",
"author_id": 11434567,
"author_profile": "https://Stackoverflow.com/users/11434567",
"pm_score": 0,
"selected": false,
"text": ".MuiAccordion-root .MuiAccordionSummary-content p{\n font-size:9px\n}\n"
},
{
"answer_id": 74419131,
"author": "Majid M.",
"author_id": 14986372,
"author_profile": "https://Stackoverflow.com/users/14986372",
"pm_score": 2,
"selected": true,
"text": "sx"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74418999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13684901/"
] |
74,419,002 | <p>Laravel is trying to use <code>uuid</code> field as foreign key. And I want to use foreign key with the field <code>id</code>. Is there any option there?</p>
<p>Using this trait on Model. And then it is trying to use the <code>uuid</code> as foreign key. But still I want to use <code>id</code> as foreign key.</p>
<pre><code><?php
namespace App\Library;
use Ramsey\Uuid\Uuid;
trait UsesUuid
{
/**
* @return string
*/
public function getKeyName()
{
return 'uuid';
}
/**
* @return string
*/
public function getKeyType()
{
return 'string';
}
/**
* @return false
*/
public function getIncrementing()
{
return false;
}
/**
* @param $query
* @param $uuid
* @return mixed
*/
public function scopeUuid($query, $uuid)
{
return $query->where($this->getUuidName(), $uuid);
}
/**
* @return string
*/
public function getUuidName()
{
return property_exists($this, 'uuidName') ? $this->uuidName : 'uuid';
}
/**
* @return string
*/
public function getRouteKeyName()
{
return property_exists($this, 'uuidName') ? $this->uuidName : 'uuid';
}
/**
*
*/
protected static function boot()
{
parent::boot();
static::creating(function ($model) {
$model->{$model->getUuidName()} = Uuid::uuid4()->toString();
});
}
}
</code></pre>
| [
{
"answer_id": 74419022,
"author": "Ali Sattarzadeh",
"author_id": 11434567,
"author_profile": "https://Stackoverflow.com/users/11434567",
"pm_score": 0,
"selected": false,
"text": ".MuiAccordion-root .MuiAccordionSummary-content p{\n font-size:9px\n}\n"
},
{
"answer_id": 74419131,
"author": "Majid M.",
"author_id": 14986372,
"author_profile": "https://Stackoverflow.com/users/14986372",
"pm_score": 2,
"selected": true,
"text": "sx"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74419002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7004312/"
] |
74,419,007 | <p>The problem I have with the code below is it prints all of the a-href stuff, I want to know how to change it so that it only prints the hyperlinks found in "info" on the far right of the tables on the webpage "https://www.tennisexplorer.com/results/?type=atp-single&year=2022&month=09&day=08".</p>
<pre><code>import requests
from bs4 import BeautifulSoup
import pandas as pd
response = requests.get('https://www.tennisexplorer.com/results/?type=atp-single&year=2022&month=09&day=08')
webpage = response.content
soup = BeautifulSoup(response.text, "html.parser")
col1 = [a.get('href') for a in soup.find_all('a')]
print(pd.DataFrame({"MatchLink":col1}))
</code></pre>
| [
{
"answer_id": 74419130,
"author": "Barry the Platipus",
"author_id": 19475185,
"author_profile": "https://Stackoverflow.com/users/19475185",
"pm_score": 2,
"selected": false,
"text": "import requests\nfrom bs4 import BeautifulSoup as bs\nimport pandas as pd\n\npd.set_option('display.max_columns', None)\npd.set_option('display.max_colwidth', None)\n\nurl = 'https://www.tennisexplorer.com/results/?type=atp-single&year=2022&month=09&day=08'\n\nbig_list = []\nr = requests.get(url)\nsoup = bs(r.text, 'html.parser')\nlinks = soup.select('table tbody tr td:last-child a')\nfor l in links:\n big_list.append(l.get('href'))\ndf = pd.DataFrame(big_list, columns = ['Url'])\nprint(df)\n"
},
{
"answer_id": 74419291,
"author": "Driftr95",
"author_id": 6146136,
"author_profile": "https://Stackoverflow.com/users/6146136",
"pm_score": 2,
"selected": true,
"text": "col1 = [\n a.get('href') for a in soup.find_all('a') if a.parent.name == 'td' \n and a.string == 'info' and not a.parent.find_next_sibling()\n]\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74419007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14745788/"
] |
74,419,013 | <p>I’ve been learning vue and im trying to understand what app.use() is used for is it anything similar to app.use in express?</p>
<p>I have looked at the vue he documentation and cannot find any helpfu information</p>
| [
{
"answer_id": 74430155,
"author": "tao",
"author_id": 1891677,
"author_profile": "https://Stackoverflow.com/users/1891677",
"pm_score": 0,
"selected": false,
"text": "use()"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74419013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20490762/"
] |
74,419,063 | <p>Having given a command line parameter which is a hex string I use <code>org.apache.commons.codec.binary.Hex.decodeHex</code> to get a <code>byte[]</code>.</p>
<p>But of course Java bytes are <em>signed</em>. I'd like to treat this as a bunch of <em>unsigned</em> bytes (so where I have a <code>byte</code> value of, say, <code>-128</code> I want it to be <code>0x80 = 128</code>, or for <code>-103</code> I want it to be <code>0x99 = 153</code>.</p>
<p>It's not going to fit in a <code>byte[]</code> anymore, so let's make it a <code>char[]</code> (<code>short[]</code> would also work).</p>
<p>What is the way to do this in Java. I can write the obvious loop (or better: stream pipeline) but is there something better, built-in, e.g. some library method that I'm unaware of?</p>
<ul>
<li>This isn't something <code>java.nio.ByteBuffer</code> does</li>
<li><code>java.nio.charset.CharsetDecoder</code> has an API with the right signature but I don't know if there is (or how to get) an "identity" decoder.</li>
</ul>
<p>(No work to show: internet searches turned up nothing like this.)</p>
| [
{
"answer_id": 74419155,
"author": "Stephen C",
"author_id": 139985,
"author_profile": "https://Stackoverflow.com/users/139985",
"pm_score": 3,
"selected": true,
"text": "byte[]"
},
{
"answer_id": 74419347,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "byte[] byteArray = {0, 1, -128, -103};\nint[] intArray = IntStream.range(0, byteArray.length)\n .map(i -> byteArray[i] & 0xff)\n .toArray();\nSystem.out.println(Arrays.toString(intArray));\n"
},
{
"answer_id": 74421727,
"author": "g00se",
"author_id": 16376827,
"author_profile": "https://Stackoverflow.com/users/16376827",
"pm_score": 0,
"selected": false,
"text": "String"
},
{
"answer_id": 74421828,
"author": "oleg.cherednik",
"author_id": 3461397,
"author_profile": "https://Stackoverflow.com/users/3461397",
"pm_score": 0,
"selected": false,
"text": "& 0xFF"
},
{
"answer_id": 74427020,
"author": "davidbak",
"author_id": 751579,
"author_profile": "https://Stackoverflow.com/users/751579",
"pm_score": 0,
"selected": false,
"text": " private @NotNull short[] toUnsignedBuffer(@NotNull byte[] signedBuffer) {\n short[] r = new short[signedBuffer.length];\n int i = 0;\n for (byte b : signedBuffer) r[i++] = (short) toUnsignedInt(b);\n return r;\n\n // Q: Why doesn't `Arrays` have a `static void SetAll(byte[] array, IntToShortFunction\n // generator)`?\n // A: Because `short` is the bastard stepchild of Java's framework libraries. P.S., there's\n // no `IntToShortFunction` interface either ... or `ShortStream` class, or\n // `Streams::toArray` overload that'll give you a `short[]`, etc. etc. etc.\n }\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74419063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/751579/"
] |
74,419,069 | <p>I'm adding some text to a textarea by using JS everytime I click on a button. The thing is that everytime the text is added, the scroll goes to top of the textarea and I don't want that. I don't want the scroll to move automatically when I add the content.</p>
<p>This is part of my code:</p>
<pre><code>const textarea = document.getElementById('my_textarea');
let data = "new content added";
textarea.innerHTML = data + textarea.innerHTML;
</code></pre>
<p>Could someone please help me out?</p>
<p>Thanks in advance.</p>
| [
{
"answer_id": 74419128,
"author": "Hoda Shakourbin",
"author_id": 12005644,
"author_profile": "https://Stackoverflow.com/users/12005644",
"pm_score": 0,
"selected": false,
"text": "var textarea = document.getElementById('textarea_id');\ntextarea.scrollTop = textarea.scrollHeight;\n"
},
{
"answer_id": 74419159,
"author": "Abbas Shaikh",
"author_id": 12667283,
"author_profile": "https://Stackoverflow.com/users/12667283",
"pm_score": 2,
"selected": true,
"text": "textarea.scrollTo(0,textarea.scrollHeight)\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74419069",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17502807/"
] |
74,419,089 | <p>I am currently studying selenium. I need to capture all network requests in order to see them like in Chrome DevTools. Is there a way to do this?</p>
<p><a href="https://i.stack.imgur.com/ZUDqQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZUDqQ.png" alt="Chrome_DevTools" /></a></p>
<p><code>RequestIntercepted</code> event doesn't help</p>
<p>I've been trying to find a solution for the past few days and nothing. I would also appreciate any advice from other libraries.</p>
<p>What I need: execute some commands or scripts like in selenium, intercept network requests.</p>
<p>My code:</p>
<pre><code>Imports OpenQA.Selenium
Imports OpenQA.Selenium.Chrome
Imports OpenQA.Selenium.DevTools
Imports OpenQA.Selenium.DevTools.V107.Network
Public Class SeleniumTest
Private Driver As OpenQA.Selenium.IWebDriver
Private Session As OpenQA.Selenium.DevTools.DevToolsSession
Private WithEvents Network As OpenQA.Selenium.DevTools.V107.Network.NetworkAdapter
Public Async Sub Load(Url As String)
Driver = New ChromeDriver(New ChromeOptions)
Dim DevTools As IDevTools = Driver
Session = DevTools.GetDevToolsSession()
Network = Session.GetVersionSpecificDomains(Of OpenQA.Selenium.DevTools.V107.DevToolsSessionDomains).Network
Await Network.Enable(New EnableCommandSettings())
Driver.Navigate.GoToUrl(Url)
End Sub
Public Sub Click()
Try
Dim elem As IWebElement = Driver.FindElement(By.ClassName("video-holder"))
elem.Click()
Catch ex As Exception
End Try
End Sub
Private Sub Network_ResponseReceived(sender As Object, e As ResponseReceivedEventArgs) Handles Network.ResponseReceived
Debug.WriteLine(e.Response.Url)
End Sub
End Class
</code></pre>
| [
{
"answer_id": 74441494,
"author": "ggeorge",
"author_id": 5276946,
"author_profile": "https://Stackoverflow.com/users/5276946",
"pm_score": 1,
"selected": false,
"text": "Selenium 4.6.0"
},
{
"answer_id": 74582913,
"author": "ms777",
"author_id": 20607294,
"author_profile": "https://Stackoverflow.com/users/20607294",
"pm_score": 0,
"selected": false,
"text": "using System;\nusing DevToolsSessionDomains = OpenQA.Selenium.DevTools.V107.DevToolsSessionDomains;\nusing Network = OpenQA.Selenium.DevTools.V107.Network;\nusing OpenQA.Selenium.Chrome;\nusing OpenQA.Selenium.DevTools;\n\nnamespace Selenium$id {\n\n public class SeleniumTest {\n\n[STAThread]\n public void Start() {\n string url = \"https://www.google.de/\";\n Uri uri = new Uri(url);\n var driver = new ChromeDriver(\"C:\\\\Users\\\\martin\\\\git\\\\libraries\\\\selenium\\\\\");\n var devTools = (OpenQA.Selenium.DevTools.IDevTools)driver;\n OpenQA.Selenium.DevTools.IDevToolsSession session = devTools.GetDevToolsSession();\n var domains = session.GetVersionSpecificDomains<DevToolsSessionDomains>();\n domains.Network.ResponseReceived += ResponseReceivedHandler;\n System.Threading.Tasks.Task task = domains.Network.Enable(new Network.EnableCommandSettings());\n task.Wait();\n driver.Navigate().GoToUrl(uri);\n var name = Console.ReadLine();\n Console.WriteLine(\"finished\");\n driver.Dispose();\n\n void ResponseReceivedHandler(object sender, Network.ResponseReceivedEventArgs e)\n {\n Console.WriteLine($\"Status: { e.Response.Status } : {e.Response.StatusText} | File: { e.Response.MimeType } | Url: { e.Response.Url }\");\n }\n }\n }\n}\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74419089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10729804/"
] |
74,419,111 | <p>I need to check if a string is a number and then I need to check the arrange of this number. So I use the TryParse method for it but I need for strings "00" or "01" or similiar get false.
With my code I get true:</p>
<pre><code>var isNum = int.TryParse(s, out int n);
</code></pre>
<p>So I have a trouble with such strings ("00", "01" etc) because I got true but I want to get false</p>
| [
{
"answer_id": 74419126,
"author": "vivek nuna",
"author_id": 6527049,
"author_profile": "https://Stackoverflow.com/users/6527049",
"pm_score": 0,
"selected": false,
"text": "if (s.StartsWith(\"0\") == false)"
},
{
"answer_id": 74419154,
"author": "Nopesound",
"author_id": 1503161,
"author_profile": "https://Stackoverflow.com/users/1503161",
"pm_score": 0,
"selected": false,
"text": "var isNum = !s.StartsWith(\"0\") && int.TryParse(s, out int n);\n"
},
{
"answer_id": 74419160,
"author": "Caspar Kleijne",
"author_id": 400223,
"author_profile": "https://Stackoverflow.com/users/400223",
"pm_score": 2,
"selected": false,
"text": "var isNum = int.TryParse(s, out int n);\nisNum = n.ToString().Equals(s) \n"
},
{
"answer_id": 74419835,
"author": "Guru Stron",
"author_id": 2501279,
"author_profile": "https://Stackoverflow.com/users/2501279",
"pm_score": 1,
"selected": false,
"text": "var isNumberNotPrefixedWith0 = Regex.IsMatch(s, @\"^(0|[1-9]\\d*)$\");\n"
},
{
"answer_id": 74419944,
"author": "Max",
"author_id": 13523921,
"author_profile": "https://Stackoverflow.com/users/13523921",
"pm_score": 0,
"selected": false,
"text": "(((byte)s[0] ^ 0x30) == 0)\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74419111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17380103/"
] |
74,419,117 | <p>I am trying to extract the legend of the plot in Altair. The problem is that I have trouble finding a way to remove the square and the circle inside the square next to the legend. Here is a sample code and the result I have. Any suggestion and help is appreciated.</p>
<pre><code>import pandas as pd
import altair as alt
df = pd.DataFrame({'x':['a','b','c'],
'y':[1,2,3]})
legend = alt.Chart(df).mark_point().encode(
color=alt.Color('x:N')
)
legend
</code></pre>
<p><a href="https://i.stack.imgur.com/vzOoY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vzOoY.png" alt="enter image description here" /></a></p>
<pre><code></code></pre>
| [
{
"answer_id": 74422307,
"author": "LazyClown",
"author_id": 3392461,
"author_profile": "https://Stackoverflow.com/users/3392461",
"pm_score": 0,
"selected": false,
"text": "legend.configure_view(strokeWidth=0)\n"
},
{
"answer_id": 74422391,
"author": "pholzm",
"author_id": 18259637,
"author_profile": "https://Stackoverflow.com/users/18259637",
"pm_score": 1,
"selected": false,
"text": "pseudo_legend = alt.Chart(df).mark_point().encode(\n alt.Y('x',axis=alt.Axis(orient = 'right', tickSize=0, titleAngle=0, titleAnchor='start', titlePadding=-22)),\n color=alt.Color('x:N', legend=None),\n size=alt.value(80)\n).configure_axis(\n grid=False,\n domain=False\n).configure_view(\n strokeWidth=0\n)\npseudo_legend\n"
},
{
"answer_id": 74649798,
"author": "joelostblom",
"author_id": 2166823,
"author_profile": "https://Stackoverflow.com/users/2166823",
"pm_score": 1,
"selected": false,
"text": "alt.Chart(df).mark_point(size=0).encode(\n color=alt.Color('x:N')\n).configure_view(strokeWidth=0)\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74419117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20474937/"
] |
74,419,158 | <p>I am using Tessaract Package (<a href="https://pub.dev/packages/flutter_tesseract_ocr" rel="nofollow noreferrer">https://pub.dev/packages/flutter_tesseract_ocr</a>) for my flutter app and facing this issue.</p>
<pre><code> Swift Compiler Error (Xcode): Could not find module 'SwiftyTesseract' for target 'arm64-apple-ios-simulator'; found: x86_64-apple-ios-simulator, x86_64,
</code></pre>
<p>For me I am a Flutter developer and have a very small idea about iOS native things! Can somebody give me any idea to solution to above error what is this for and what does it mean?</p>
<p>How to set the archtecture for my simulator through xCode or Android Studio?
Will it work on real device, and will not be a blocker for me!</p>
<p>Thanks in advance</p>
| [
{
"answer_id": 74422307,
"author": "LazyClown",
"author_id": 3392461,
"author_profile": "https://Stackoverflow.com/users/3392461",
"pm_score": 0,
"selected": false,
"text": "legend.configure_view(strokeWidth=0)\n"
},
{
"answer_id": 74422391,
"author": "pholzm",
"author_id": 18259637,
"author_profile": "https://Stackoverflow.com/users/18259637",
"pm_score": 1,
"selected": false,
"text": "pseudo_legend = alt.Chart(df).mark_point().encode(\n alt.Y('x',axis=alt.Axis(orient = 'right', tickSize=0, titleAngle=0, titleAnchor='start', titlePadding=-22)),\n color=alt.Color('x:N', legend=None),\n size=alt.value(80)\n).configure_axis(\n grid=False,\n domain=False\n).configure_view(\n strokeWidth=0\n)\npseudo_legend\n"
},
{
"answer_id": 74649798,
"author": "joelostblom",
"author_id": 2166823,
"author_profile": "https://Stackoverflow.com/users/2166823",
"pm_score": 1,
"selected": false,
"text": "alt.Chart(df).mark_point(size=0).encode(\n color=alt.Color('x:N')\n).configure_view(strokeWidth=0)\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74419158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9718622/"
] |
74,419,168 | <p>I have a table, <code>Item</code>, which stores key/value pairs. So my JSON returns key-value pairs.
Key can be of three types: 'Item Name', 'Location', and 'Date'.</p>
<p>Model:</p>
<pre class="lang-cs prettyprint-override"><code>public class Item
{
public Guid Id { get; set; }
public string ItemKey { get; set; }
public string Key { get; set; } // Key can be of three types `'Item Name', 'Location', 'Date'`
public string Value { get; set; }
}
</code></pre>
<p>How do I display all info of <code>ItemKey</code> on to one row, from the JSON? Grouping by <code>ItemKey</code>.</p>
<pre><code>[
{"id":"1","itemKey":"item1","key":"ItemName","value":"Apple"},
{"id":"2","itemKey":"item2","key":"ItemName","value":"Orange"},
{"id":"3","itemKey":"item1","key":"Location","value":"USA"},
{"id":"4","itemKey":"item2","key":"Location","value":"Angola"},
{"id":"5","itemKey":"item2","key":"Date","value":"03.11.2022"},
{"id":"6","itemKey":"item3","key":"ItemName","value":"Banana"},
{"id":"7","itemKey":"item3","key":"Date","value":"24.10.2022"}
]
</code></pre>
<p>I would like to display each <code>itemKey</code> detail in the razor page as below:</p>
<p>For eg: Grouping by item1 would return:</p>
<blockquote>
<p>itemKey - Item1, itemName - Apple, Location -USA (date is not available for item1)</p>
</blockquote>
<pre><code><thead>
<tr>
<th>ItemKey</th>
<th>ItemName</th>
<th>Location</th>
<th>Date</th>
</tr>
</thead>
</code></pre>
<p>The current code is below for reference:</p>
<p>Below gets me list of items from the JSON</p>
<p>ItemService.cs:</p>
<pre class="lang-cs prettyprint-override"><code>public async Task<List<FecMetaDatum>> GetItems()
{
return await _httpClient.GetFromJsonAsync<List<Item>>("api/Item");
}
</code></pre>
<p>Index.razor:</p>
<pre><code>@foreach (var r in items)
{
<tr>
<td>@r.id</td>
<td>@r.itemKey</td>
<td>@r.key</td>
<td>@r.value</td>
</tr>
}
protected override async Task OnInitializedAsync()
{
items= await ItemService.GetItems();
}
</code></pre>
| [
{
"answer_id": 74419286,
"author": "Yong Shun",
"author_id": 8017690,
"author_profile": "https://Stackoverflow.com/users/8017690",
"pm_score": 3,
"selected": true,
"text": "key"
},
{
"answer_id": 74419588,
"author": "Ibrahim Timimi",
"author_id": 8316900,
"author_profile": "https://Stackoverflow.com/users/8316900",
"pm_score": 0,
"selected": false,
"text": "JAarray"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74419168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16732381/"
] |
74,419,172 | <p>I am trying to create a tab bar with a hover effects on its direct children, therefore i have the following code with the intent of applying an effect on each element inside the list individually, but idoesn't work.</p>
<p>HTML code :</p>
<pre><code> <!-- navigation -->
<div>
<nav>
<ul class="primary-navigation underline-indicators flex">
<li class="active">
<a class="uppercase text-white letter-spacing-2" href="#"
><span>01</span>Active</a
>
</li>
<li>
<a class="uppercase text-white letter-spacing-2" href="#"
><span>02</span>Hovered</a
>
</li>
<li>
<a class="uppercase text-white letter-spacing-2" href="#"
><span>03</span>Idle</a
>
</li>
</ul>
</nav>
</div>
</code></pre>
<p>CSS code :</p>
<pre><code>.underline-indicators > * {
padding: var(--underline-gap, 1rem) 0;
border-bottom: 0.2rem solid hsl(var(--clr-white) / 0);
}
.underline-indicators > *:hover,
.underline-indicators > *:focus {
border-color: hsl(var(--clr-white) / 0.5);
}
.underline-indicators > .active {
border-color: hsl(var(--clr-white) / 1);
}
</code></pre>
<p>is it possible to apply this effect and if yes what is the optimal way to do it?</p>
<p>Providing that when i replace <code>*:hover</code> with <code>li:hover</code> it works just fine, but i want to use <code>*</code> so i can reuse the same style on different parts of my code.</p>
| [
{
"answer_id": 74419782,
"author": "M. R. A. Chowdhury",
"author_id": 18111831,
"author_profile": "https://Stackoverflow.com/users/18111831",
"pm_score": 0,
"selected": false,
"text": "<style>\n.underline-indicators {\n list-style:none;\n}\n\n.underline-indicators li > *{\n padding: var(--underline-gap, 1rem) 0;\n border-bottom: 0.2rem solid hsl(var(--clr-white) / 0);\n color:green;\n}\n\n.underline-indicators *:hover,\n.underline-indicators *:focus {\n border-color: hsl(var(--clr-white) / 0.5);\n}\n.underline-indicators .active {\n border-color: hsl(var(--clr-white) / 1);\n}\n</style>\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74419172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11249543/"
] |
74,419,185 | <pre><code>import { useEffect, useState } from 'react';
function useBookmarks() {
const [bookmarks, setBookmarks] = useState(() => {
const ls = localStorage.getItem('bookmarks');
if (ls) return JSON.parse(ls);
else return [];
});
const toggleItemInLocalStorage = (id) => () => {
const isBookmarked = bookmarks.includes(id);
if (isBookmarked) setBookmarks((prev) => prev.filter((b) => b !== id));
else setBookmarks((prev) => [...prev, id]);
};
useEffect(() => {
localStorage.setItem('bookmarks', JSON.stringify(bookmarks));
}, [bookmarks]);
return [bookmarks, toggleItemInLocalStorage];
}
export default useBookmarks;
</code></pre>
<p>Please tell me why the localStorage is not defined.
when I use localStorage why always, ReferenceError: localStorage is not defined.
is there something wrong with my code.
Please help me</p>
| [
{
"answer_id": 74419782,
"author": "M. R. A. Chowdhury",
"author_id": 18111831,
"author_profile": "https://Stackoverflow.com/users/18111831",
"pm_score": 0,
"selected": false,
"text": "<style>\n.underline-indicators {\n list-style:none;\n}\n\n.underline-indicators li > *{\n padding: var(--underline-gap, 1rem) 0;\n border-bottom: 0.2rem solid hsl(var(--clr-white) / 0);\n color:green;\n}\n\n.underline-indicators *:hover,\n.underline-indicators *:focus {\n border-color: hsl(var(--clr-white) / 0.5);\n}\n.underline-indicators .active {\n border-color: hsl(var(--clr-white) / 1);\n}\n</style>\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74419185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20490929/"
] |
74,419,191 | <p>I'm trying out to forward output stream from XCode (v12.4) to Processing (<a href="https://processing.org/" rel="nofollow noreferrer">https://processing.org/</a>).
My goal is: To draw a simple object in Processing according to my XCode project data.</p>
<p>I need to see value of my variable in the Processing.</p>
<pre><code>int main(int argc, const char * argv[]) {
// insert code here...
for (int i=0; i<10; i++)
std::cout << "How to send value of i to the Processing!\n";
return 0;
}
</code></pre>
| [
{
"answer_id": 74419939,
"author": "George Profenza",
"author_id": 89766,
"author_profile": "https://Stackoverflow.com/users/89766",
"pm_score": 1,
"selected": false,
"text": "args"
},
{
"answer_id": 74424873,
"author": "OverFF",
"author_id": 20490825,
"author_profile": "https://Stackoverflow.com/users/20490825",
"pm_score": 2,
"selected": false,
"text": "int main(int argc, char const *argv[])\n{\n std::string hostname{\"127.0.0.1\"};\n uint16_t port = 6000;\n\n int sock = ::socket(AF_INET, SOCK_DGRAM, 0);\n\n sockaddr_in destination;\n destination.sin_family = AF_INET;\n destination.sin_port = htons(port);\n destination.sin_addr.s_addr = inet_addr(hostname.c_str());\n \n \n \n std::string msg = \"Hello world!\";\n for(int i=0; i<5; i++){\n long n_bytes = ::sendto(sock, msg.c_str(), msg.length(), 0, reinterpret_cast<sockaddr*>(&destination), sizeof(destination));\n std::cout << n_bytes << \" bytes sent\" << std::endl;\n }\n ::close(sock);\n \n return 0;\n}\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74419191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20490825/"
] |
74,419,192 | <p>Need to use multiple if condition in a ternary</p>
<pre><code>const handleEditTask = (id) =>{
return (
tasks.map((x)=>{
return x.id === id? setTitle(x.title): ;
})
)
}
</code></pre>
<p>with true of that condition need to call two setState operatoion</p>
<p>using the ternary, just need to include the setNote() as well</p>
| [
{
"answer_id": 74419939,
"author": "George Profenza",
"author_id": 89766,
"author_profile": "https://Stackoverflow.com/users/89766",
"pm_score": 1,
"selected": false,
"text": "args"
},
{
"answer_id": 74424873,
"author": "OverFF",
"author_id": 20490825,
"author_profile": "https://Stackoverflow.com/users/20490825",
"pm_score": 2,
"selected": false,
"text": "int main(int argc, char const *argv[])\n{\n std::string hostname{\"127.0.0.1\"};\n uint16_t port = 6000;\n\n int sock = ::socket(AF_INET, SOCK_DGRAM, 0);\n\n sockaddr_in destination;\n destination.sin_family = AF_INET;\n destination.sin_port = htons(port);\n destination.sin_addr.s_addr = inet_addr(hostname.c_str());\n \n \n \n std::string msg = \"Hello world!\";\n for(int i=0; i<5; i++){\n long n_bytes = ::sendto(sock, msg.c_str(), msg.length(), 0, reinterpret_cast<sockaddr*>(&destination), sizeof(destination));\n std::cout << n_bytes << \" bytes sent\" << std::endl;\n }\n ::close(sock);\n \n return 0;\n}\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74419192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14869824/"
] |
74,419,203 | <p>I am trying to find a maximum/minimum value corresponding to a day.</p>
<p>list1 includes all 7 days of the week.
list two is empty []
I have a loop that iterates as many times as the len of list 1,(7), which asks the user to input how many hours they did an activity each day.
how can I print the day that has the max/min value??</p>
<pre><code>count = 0
list1 = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
list2 = []
total = 0
for x in range(len(list1)):
try:
num = float(input(f"Enter amount of hours of exercise for {list1[x]}: "))
list2.append(num)
total += num
except:
print("Please enter a number.")
sys.exit()
total = sum(list2)
#THESE LINES ARE WHERE I AM HAVING DIFFICULTY!
mamimum = max(list2[list1])
minimum = min(list2[list1])
print("Day with most amount of exercise: ", maximum)
print("Day with least amount of exercise: ", minimum)
</code></pre>
| [
{
"answer_id": 74419245,
"author": "ShlomiF",
"author_id": 5024514,
"author_profile": "https://Stackoverflow.com/users/5024514",
"pm_score": 0,
"selected": false,
"text": "np.argmax"
},
{
"answer_id": 74419281,
"author": "Bhargav",
"author_id": 15358800,
"author_profile": "https://Stackoverflow.com/users/15358800",
"pm_score": 1,
"selected": false,
"text": "zipping"
},
{
"answer_id": 74419292,
"author": "The Myth",
"author_id": 15042008,
"author_profile": "https://Stackoverflow.com/users/15042008",
"pm_score": -1,
"selected": false,
"text": "count = 0\nlist1 = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"]\n\nlist2 = []\ntotal = 0\nfor x in range(len(list1)):\n try:\n num = float(input(f\"Enter amount of hours of exercise for {list1[x]}: \"))\n list2.append(num)\n total += num\n except:\n print(\"Please enter a number.\")\n sys.exit()\n total = sum(list2)\nmaximum = max(list2) # gets the max value corresponding to list2\nminimum = min(list2) # gets the min value corresponding to list2\n# Compatibility for two max/min values:\ndef moreThanTwo(value, lst):\n return [i for i, j in enumerate(lst) if j == value] # returns the index with max/min values\nmaximum = [list1[idx] for idx in moreThanTwo(maximum, list2)] # gets the max values\nminimum = [list1[idx] for idx in moreThanTwo(minimum, list2)] # gets the min values\nprint(f\"Day with most amount of exercise: {', '.join(maximum)}\")\nprint(f\"Day with least amount of exercise: {', '.join(minimum)}\")\n"
},
{
"answer_id": 74419302,
"author": "saeid rasouli",
"author_id": 14885209,
"author_profile": "https://Stackoverflow.com/users/14885209",
"pm_score": 0,
"selected": false,
"text": "count = 0\nlist1 = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"]\n\nlist2 = []\ntotal = 0\nfor x in range(len(list1)):\n try:\n num = float(input(f\"Enter amount of hours of exercise for {list1[x]}: \"))\n list2.append(num)\n total += num\n except:\n print(\"Please enter a number.\")\n total = sum(list2)\n \n\n#THESE LINES ARE WHERE I AM HAVING DIFFICULTY!\nmax_index = list2.index((max(list2)))\nmin_index = list2.index((min(list2)))\n\nprint(\"Day with most amount of exercise: \", list1[max_index])\nprint(\"Day with least amount of exercise: \", list1[min_index])\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74419203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20220196/"
] |
74,419,215 | <p>I have created a customTextfield and placed IconButton as suffix icon,</p>
<p>here when I tap on icon button, its splash radius showing bigger than textfield,</p>
<p>here I want to fix height of splash radius based on it's parent.. like if it is inside of container of 100height..it must be set according to it...</p>
<p>here is my code</p>
<pre><code>class CustomTextField extends StatelessWidget {
final String hint;
final bool isitpassword;
final TextEditingController controller;
const CustomTextField({Key? key,required this.hint,this.isitpassword=false,required this.controller}) : super(key: key);
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 10.0),
child: Container(
padding: EdgeInsets.symmetric(horizontal: 20),
decoration: BoxDecoration(
color: Colors.grey,
borderRadius: BorderRadius.circular(20),
),
child: TextField(
style: TextStyle(
fontSize: 20,color: Colors.white,),
controller: controller,
obscureText: isitpassword,
decoration: InputDecoration(
border: InputBorder.none,
hintText: hint,
suffixIcon: IconButton(
//what spread radius to set for better view
icon: Icon(Icons.close,color: Colors.white,),onPressed: (){
controller.text='';
},),
),
)),
);
}
}
</code></pre>
| [
{
"answer_id": 74419260,
"author": "Yeasin Sheikh",
"author_id": 10157127,
"author_profile": "https://Stackoverflow.com/users/10157127",
"pm_score": 2,
"selected": false,
"text": "splashRadius: 48 / 2"
},
{
"answer_id": 74419273,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 2,
"selected": true,
"text": "InkWell"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74419215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18817235/"
] |
74,419,227 | <p>I'm trying to concatenate two files, sort them by last name, delete duplicates and store them in a new file.</p>
<p>File's: "firstName lastName"</p>
<p>FileA + FileB --> FileC</p>
<p>I tried it with the sort command:</p>
<p>sort -uk2 fileA fileB > fileC</p>
<p>The problem is that this command deletes names with the same last name but diffrent first name.</p>
<p>"Hans Smith" + "Hans Smith" --> only one "Hans Smith" should remain.
"Friedrich Bauer" + "Colin Bauer" --> should both be kept.</p>
<p>Any ideas?</p>
| [
{
"answer_id": 74419260,
"author": "Yeasin Sheikh",
"author_id": 10157127,
"author_profile": "https://Stackoverflow.com/users/10157127",
"pm_score": 2,
"selected": false,
"text": "splashRadius: 48 / 2"
},
{
"answer_id": 74419273,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 2,
"selected": true,
"text": "InkWell"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74419227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20490869/"
] |
74,419,229 | <p>I am trying to improve a search function to allow for a space when people search involving data from 2 columns in the same table. For example location and keyword ie they search for Townsville marketing.</p>
<p>I tried the following:</p>
<pre><code>SELECT *
FROM `partners`
WHERE location_keywords LIKE '%$result%'
OR keywords LIKE '%$result%'
OR keywords[&#32]+location_keywords LIKE '%$result%'
OR location_keywords[&#32]+keywords LIKE '%$result%'
</code></pre>
<p>I want it to return all results that contain Townsville, Marketing, Townsville marketing, or marketing townsville.</p>
<p>This throws a syntax error.</p>
<p>Can anyone help me fix this please?</p>
| [
{
"answer_id": 74419260,
"author": "Yeasin Sheikh",
"author_id": 10157127,
"author_profile": "https://Stackoverflow.com/users/10157127",
"pm_score": 2,
"selected": false,
"text": "splashRadius: 48 / 2"
},
{
"answer_id": 74419273,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 2,
"selected": true,
"text": "InkWell"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74419229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13669766/"
] |
74,419,231 | <p>I have been having issues with a query that I am creating to search for books in a system, I am searching for a keyword in all columns in a table. It could be anything and I need it to search the booktitle, author, publisher and language. I need to be able to select the category then also search for they keyword. I am looking for all values as I want to display this to the user.</p>
<p>Here is the query I am trying but I keep getting error after trying a few different things. Can anyone suggest a better approach?</p>
<p><code>SELECT * FROM book WHERE category='Fiction' AND booktitle, author, publisher, language LIKE '%King%';</code></p>
<p>I have tried different combinations using WHERE and LIKE but keep getting errors or 0 results for my query.</p>
| [
{
"answer_id": 74419366,
"author": "masoud rafiee",
"author_id": 4256602,
"author_profile": "https://Stackoverflow.com/users/4256602",
"pm_score": 1,
"selected": false,
"text": "SELECT * FROM book \nWHERE category='Fiction' AND (\nbooktitle LIKE '%King%' \nOR author LIKE '%King%' \nOR publisher LIKE '%King%' \nOR language LIKE '%King%');\n"
},
{
"answer_id": 74419470,
"author": "Jonas Metzler",
"author_id": 18794826,
"author_profile": "https://Stackoverflow.com/users/18794826",
"pm_score": 0,
"selected": false,
"text": "SELECT * FROM book \nWHERE category='Fiction' \nAND CONCAT(booktitle, author, publisher, language) LIKE '%King%';\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74419231",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,419,277 | <p>When I execute my code it shows me error as below, I don't know what is this <code>visqol_find.py:33 ERROR: /bin/sh: 1: visqol: not found</code> meaning, and I pretty sure that <code>visqol_value</code> and <code>visqol_threshold</code> are both defined as float because the program is working fine with my professor.</p>
<p>My system is Ubuntu 18.04 and python is 3.6.12.</p>
<p>This is code for <code>visqol_value</code></p>
<pre><code>def visqol(reference_file: str, degraded_file: str, visqol_model_path: str = __visqol_model_path__) -> float:
status, output = subprocess.getstatusoutput("visqol --reference_file {} --degraded_file {} --similarity_to_quality_model {} --use_speech_mode".format(reference_file, degraded_file, visqol_model_path))
if status != 0:
for _line_ in output.split('\n'):
logger.error(_line_)
raise RuntimeError("VISQOL Command-Line Error.")
visqol_score = None
for output_line in output.split("\n"):
if output_line.startswith('MOS-LQO:'):
visqol_score = float(output_line.split()[1])
if visqol_score is not None:
return visqol_score
raise RuntimeError("VISQOL Command-Line Error.")
</code></pre>
<pre><code> visqol_value = visqol(clip_file, adversarial_path)
if visqol_value < visqol_threshold:
right_bound = potential_delta
if _delete_failed_wav_: # delete
for _file_ in glob.glob(adversarial_path[:-4] + "*"):
os.remove(_file_)
logger.debug("VISQOL Exceeds for music clip '{}' with 'delta_db={}'.".format(clip_name, potential_delta))
continue
</code></pre>
<p>This is code for <code>visqol_threshold</code></p>
<pre><code>def get_visqol_threshold(formant_weight: Union[list, np.ndarray], phoneme_num: int) -> float:
formant_weight = np.array(formant_weight)
_alpha = 0.95 # The higher the value of _alpha and _beta is, the faster the visqol threshold decreases.
_beta = 8.0
_theta = 10.0
o = np.sum(formant_weight != 0.)
if o == 5:
base = 1.7
elif o == 4:
base = 1.8
elif o == 3:
base = 2.2
else:
if formant_weight[1] < 0.75:
base = 2.3
else:
base = 2.25
return base * (_alpha ** (max((phoneme_num - _theta) / _beta, 0.)))
</code></pre>
<p>I would like to know how I should fix it?
Since I am running this project in a virtual python environment, is it possible that it is because I put visqol in the wrong place, and if so, where should I download visqol to</p>
<p>The program works but keeps looping with these two error messages until I manually terminate it</p>
<pre><code>(.venv) dunliu@dun:~/research/Phantom-of-Formants-master$ python3 2022gen_100song_bing_001.py
2022-11-13 17:23:58 2022gen_100song_bing_001.py:433 WARNING: The destination folder './task/weather1/generate/0490c9606d8e333e' will be removed. Please backup this folder, and then enter 'Y' to continue, or others to exit...
y
2022-11-13 17:24:01 2022gen_100song_bing_001.py:437 INFO: The destination folder './task/weather1/generate/0490c9606d8e333e' was removed.
2022-11-13 17:24:01 2022gen_100song_bing_001.py:325 INFO: ******************** Start Binary-search Generation. ********************
2022-11-13 17:24:01 visqol_find.py:34 ERROR: /bin/sh: 1: visqol: not found
2022-11-13 17:24:01 utils.py:361 ERROR: program exit!
Traceback (most recent call last):
File "/home/dunliu/research/Phantom-of-Formants-master/utils.py", line 357, in wrapper
return function(*args, **kwargs)
File "/home/dunliu/research/Phantom-of-Formants-master/visqol_find.py", line 35, in visqol
raise RuntimeError("VISQOL Command-Line Error.")
RuntimeError: VISQOL Command-Line Error.
2022-11-13 17:24:01 utils.py:361 ERROR: program exit!
Traceback (most recent call last):
File "/home/dunliu/research/Phantom-of-Formants-master/utils.py", line 357, in wrapper
return function(*args, **kwargs)
File "2022gen_100song_bing_001.py", line 257, in generate
if visqol_value < visqol_threshold:
TypeError: '<' not supported between instances of 'NoneType' and 'float'
2022-11-13 17:24:01 visqol_find.py:34 ERROR: /bin/sh: 1: visqol: not found
2022-11-13 17:24:01 utils.py:361 ERROR: program exit!
Traceback (most recent call last):
File "/home/dunliu/research/Phantom-of-Formants-master/utils.py", line 357, in wrapper
return function(*args, **kwargs)
File "/home/dunliu/research/Phantom-of-Formants-master/visqol_find.py", line 35, in visqol
raise RuntimeError("VISQOL Command-Line Error.")
RuntimeError: VISQOL Command-Line Error.
2022-11-13 17:24:01 utils.py:361 ERROR: program exit!
Traceback (most recent call last):
File "/home/dunliu/research/Phantom-of-Formants-master/utils.py", line 357, in wrapper
return function(*args, **kwargs)
File "2022gen_100song_bing_001.py", line 257, in generate
if visqol_value < visqol_threshold:
TypeError: '<' not supported between instances of 'NoneType' and 'float'
</code></pre>
<p>after I terminate it, it shows</p>
<pre><code>^CTraceback (most recent call last):
File "2022gen_100song_bing_001.py", line 448, in <module>
binary_generation_task()
File "2022gen_100song_bing_001.py", line 444, in binary_generation_task
binary_generation(params)
File "2022gen_100song_bing_001.py", line 395, in binary_generation
generate(_wake_up_analysis_file_, _command_analysis_file_, _clip_file_, output_folder, params)
File "/home/dunliu/research/Phantom-of-Formants-master/utils.py", line 359, in wrapper
raise _err
File "/home/dunliu/research/Phantom-of-Formants-master/utils.py", line 357, in wrapper
return function(*args, **kwargs)
File "2022gen_100song_bing_001.py", line 251, in generate
adversarial_path = gen_by_command(delta_db_list, bandwidth_list, command_analysis_file, clip_file, output_folder, adversarial_filename, params)
File "/home/dunliu/research/Phantom-of-Formants-master/utils.py", line 359, in wrapper
raise _err
File "/home/dunliu/research/Phantom-of-Formants-master/utils.py", line 357, in wrapper
return function(*args, **kwargs)
File "/home/dunliu/research/Phantom-of-Formants-master/formant_processor.py", line 688, in gen_by_command
command_filter_list = generate_filter(command_formant_list, m_sample_rate, bandwidth, min_fre, max_fre, filter_order, reserved_fre_gap_ratio)
File "/home/dunliu/research/Phantom-of-Formants-master/formant_processor.py", line 356, in generate_filter
signal.butter(f_order, [_s_fre_, _e_fre_], btype='band', output='sos')
File "/home/dunliu/research/Phantom-of-Formants-master/.venv/lib/python3.6/site-packages/scipy/signal/filter_design.py", line 2894, in butter
output=output, ftype='butter', fs=fs)
File "/home/dunliu/research/Phantom-of-Formants-master/.venv/lib/python3.6/site-packages/scipy/signal/filter_design.py", line 2407, in iirfilter
return zpk2sos(z, p, k)
File "/home/dunliu/research/Phantom-of-Formants-master/.venv/lib/python3.6/site-packages/scipy/signal/filter_design.py", line 1447, in zpk2sos
z = np.concatenate(_cplxreal(z))
File "/home/dunliu/research/Phantom-of-Formants-master/.venv/lib/python3.6/site-packages/scipy/signal/filter_design.py", line 887, in _cplxreal
z = atleast_1d(z)
File "<__array_function__ internals>", line 6, in atleast_1d
File "/home/dunliu/research/Phantom-of-Formants-master/.venv/lib/python3.6/site-packages/numpy/core/shape_base.py", line 25, in atleast_1d
@array_function_dispatch(_atleast_1d_dispatcher)
KeyboardInterrupt
</code></pre>
| [
{
"answer_id": 74419417,
"author": "Constantin Hong",
"author_id": 20307768,
"author_profile": "https://Stackoverflow.com/users/20307768",
"pm_score": 1,
"selected": true,
"text": "which visqol\n"
},
{
"answer_id": 74419515,
"author": "Mark Setchell",
"author_id": 2836621,
"author_profile": "https://Stackoverflow.com/users/2836621",
"pm_score": 1,
"selected": false,
"text": "/bin/sh"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74419277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18264823/"
] |
74,419,299 | <p>When I run the code the external configuration in the application.properties file does not get populated into the variable within the DataBucketUtil. I'm sure I'm doing something stupid,but I can not find out wheres the problem.</p>
<pre><code>public class DataBucketUtil {
private static final Logger logger = LoggerFactory.getLogger(DataBucketUtil.class);
@Value("${gcp.config.file}")
private String gcpConfigFile;
@Value("${gcp.project.id}")
private String gcpProjectId;
@Value("${gcp.bucket.id}")
private String gcpBucketId;
@Value("${gcp.directory.name}")
private String gcpDirectoryName;
/**
* Upload file to GCS
*
* @param multipartFile-
* @param fileName-
* @param contentType-
* @return -
*/
public FileDto uploadFile(MultipartFile multipartFile, String fileName, String contentType) {
try {
logger.debug("Start file uploading process on GCS");
byte[] fileData = FileUtils.readFileToByteArray(convertFile(multipartFile));
InputStream inputStream = new ClassPathResource(gcpConfigFile).getInputStream();
StorageOptions options = StorageOptions.newBuilder().setProjectId(gcpProjectId)
.setCredentials(GoogleCredentials.fromStream(inputStream)).build();
Storage storage = options.getService();
Bucket bucket = storage.get(gcpBucketId, Storage.BucketGetOption.fields());
RandomString id = new RandomString(6, ThreadLocalRandom.current());
Blob blob = bucket.create(gcpDirectoryName + "/"
+ fileName + "-" + id.nextString() + checkFileExtension(fileName),
fileData, contentType);
if (blob != null) {
logger.debug("File successfully uploaded to GCS");
return new FileDto(blob.getName(), blob.getMediaLink());
}
} catch (IOException e) {
logger.error("An error occurred while uploading data. Exception: ", e);
throw new RuntimeException("An error occurred while uploading data to GCS");
}
throw new RuntimeException("An error occurred while uploading data to GCS");
}
</code></pre>
<p>My application properties is given below:</p>
<pre><code> gcp.config.file=gcp-config/gcs-prod-ho-finance.json
gcp.project.id=brac-main gcp.bucket.id=prod-ho-finance
gcp.dir.name=gs://prod-ho-finance
</code></pre>
| [
{
"answer_id": 74419408,
"author": "Johannes Gasser",
"author_id": 17268345,
"author_profile": "https://Stackoverflow.com/users/17268345",
"pm_score": 2,
"selected": false,
"text": "DataBucketUtil"
},
{
"answer_id": 74419769,
"author": "shafiul islam",
"author_id": 5602405,
"author_profile": "https://Stackoverflow.com/users/5602405",
"pm_score": 0,
"selected": false,
"text": "@EnableConfigurationProperties\n@Component\npublic class DataBucketUtil {\n\nprivate static final Logger logger = LoggerFactory.getLogger(DataBucketUtil.class);\n\n@Value(\"${gcp.config.file}\")\nprivate String gcpConfigFile;\n\n@Value(\"${gcp.project.id}\")\nprivate String gcpProjectId;\n\n@Value(\"${gcp.bucket.id}\")\nprivate String gcpBucketId;\n\n@Value(\"${gcp.directory.name}\")\nprivate String gcpDirectoryName;\n\n/** ............ **/\n\n}\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74419299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7315831/"
] |
74,419,354 | <p>A newbie IT student here trying to code my subject requirement which is a ecommerce web app. The problem that im having rn is with the login form that is written in Php. Regardless if the input that I type is right or wrong, the alert still displays "Please fill up all fields".</p>
<p>This is my Php Login Form</p>
<pre><code><?php
$conn = mysql_connect("localhost","root","1234");
if(!$conn)
{
die('Could not connect: ' . mysql_error());
}mysql_select_db("registration", $conn);
$email=$_POST["email"];
$pwd=md5($_POST["password"]);
$query = mysql_query("SELECT * FROM tbl_reg where password='$pwd' AND email='$email'",$conn);
$rows = mysql_num_rows($query);
if(!$email|| !$pwd)
{
echo"<script>alert(\"please fill up fields\");window.location='sign-in.html'</script>";
}
if ($rows == 1)
{
echo"<script>alert(\"login Succes\");window.location='index2.html'</script>";
}
else
{
$error = "Username or Password is invalid";
}
if ($rows == 0)
{
echo"<script>alert(\"Username or Password is Incorrect\");window.location='login.php'</script>";}
mysql_close($conn);
?>
</code></pre>
<p>Here is basically my HTML Login Form</p>
<pre><code><!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors">
<meta name="generator" content="Hugo 0.104.2">
<title>Log in Form</title>
<link rel="canonical" href="https://getbootstrap.com/docs/5.2/examples/sign-in/">
<link href="assets/css/bootstrap.min.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
<style>
.bd-placeholder-img {
font-size: 1.125rem;
text-anchor: middle;
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
}
@media (min-width: 768px) {
.bd-placeholder-img-lg {
font-size: 3.5rem;
}
}
.b-example-divider {
height: 3rem;
background-color: rgba(0, 0, 0, .1);
border: solid rgba(0, 0, 0, .15);
border-width: 1px 0;
box-shadow: inset 0 .5em 1.5em rgba(0, 0, 0, .1), inset 0 .125em .5em rgba(0, 0, 0, .15);
}
.b-example-vr {
flex-shrink: 0;
width: 1.5rem;
height: 100vh;
}
.bi {
vertical-align: -.125em;
fill: currentColor;
}
.nav-scroller {
position: relative;
z-index: 2;
height: 2.75rem;
overflow-y: hidden;
}
.nav-scroller .nav {
display: flex;
flex-wrap: nowrap;
padding-bottom: 1rem;
margin-top: -1px;
overflow-x: auto;
text-align: center;
white-space: nowrap;
-webkit-overflow-scrolling: touch;
}
</style>
<!-- Custom styles for this template -->
<link href="assets/css/signin.css" rel="stylesheet">
</head>
<body class="text-center">
<main class="form-signin w-100 m-auto">
<form method="post" action="login.php">
<img class="mb-4" src="../assets/brand/bootstrap-logo.svg" alt="" width="72" height="57">
<h1 class="h3 mb-3 fw-normal">Please sign in</h1>
<div class="form-floating">
<input type="email" class="form-control" id="floatingInput" placeholder="name@example.com" name="email">
<label for="floatingInput">Email address</label>
</div>
<div class="form-floating">
<input type="password" class="form-control" id="floatingPassword" placeholder="Password" name="password">
<label for="floatingPassword">Password</label>
</div>
<div class="checkbox mb-3">
<label>
<input type="checkbox" value="remember-me" > Remember me
</label>
</div>
<button class="w-100 btn btn-lg btn-primary" type="submit"><a href="appDev Assignment/index.html">Sign in</a></button>
<p class="mt-5 mb-3 text-muted">&copy; 2017–2022</p>
</form>
<center>
<p class="mt-5 mb-3 text-muted" id="q">&copy;</p>
</center>
</main>
<script>
var category = 'happiness'
$.ajax({
method: 'GET',
url: 'https://api.api-ninjas.com/v1/quotes?category=' + category,
headers: { 'X-Api-Key': 'ToCfG0A/2Y9rS7AiwSj0BA==5YvMUReDisFAtJ0P'},
contentType: 'application/json',
success: function(result) {
console.log(result);
var q=result;
var quote=result[0].quote;
console.log(quote);
let q1 = document.getElementById("q")
q1.textContent =quote
},
error: function ajaxError(jqXHR) {
console.error('Error: ', jqXHR.responseText);
}
});
</script>
</body>
</html>
</code></pre>
<p>I have a pretty shitty Prof. who just posted the syntax in a Ppt. file without any kind of information. Just pure hard code. Nothing more. nothing less. without even a sliver of teaching. I tried everything from rewriting my code to dropping my database or deleting my Table but to no avail. I even tried to rewrite everything even the HTML form one. Please i need help because our midterms are just at the end of the month and i really need help.</p>
| [
{
"answer_id": 74419582,
"author": "Professor Abronsius",
"author_id": 3603681,
"author_profile": "https://Stackoverflow.com/users/3603681",
"pm_score": 3,
"selected": true,
"text": "<?php\n\n # start & maintain session variables for all pages\n session_start();\n \n # enable error reporting\n error_reporting( E_ALL );\n mysqli_report( MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT );\n \n # create the mysql connection - the OO format is much less verbose!\n $conn = new mysqli('localhost','root','1234','registration)';\n \n \n # test that the request is a POST request and you have important variables set ( using `isset` )\n if( $_SERVER['REQUEST_METHOD']=='POST' && isset(\n $_POST['email'],\n $_POST['password']\n )){\n \n # create the basic sql and construct the `prepared statement`\n $sql='select `password` from `tbl_reg` where `email`=?';\n $stmt=$conn->prepare( $sql );\n # bind the placeholder(s) to variables\n $stmt->bind_param('s', $_POST['email'] );\n $stmt->bind_result( $hash );\n $stmt->execute();\n \n # if the stored hash matches the value generated by `password_verify` that is a success\n if( password_verify( $_POST['password'], $hash ) ){\n \n # OK - set a session variable to be propagated throughout entire session.\n $_SESSION['username']=$_POST['email'];\n \n # redirect to a PHP page that maintains the session\n exit( header( 'Location: index.php' ) );\n }else{\n # FAIL\n exit( header( 'Location: login.php' ) );\n }\n }\n\n?>\n"
},
{
"answer_id": 74419877,
"author": "M. R. A. Chowdhury",
"author_id": 18111831,
"author_profile": "https://Stackoverflow.com/users/18111831",
"pm_score": -1,
"selected": false,
"text": "<button class=\"w-100 btn btn-lg btn-primary\" type=\"submit\"><a href=\"appDev Assignment/index.html\">Sign in</a></button>\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74419354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20431827/"
] |
74,419,365 | <p>const datafromback=[[{name:ravi}],[{}],[{}],[{}]]</p>
<p>I want to access ravi. Can anyone help me how can i see ravi in my console.with dealing with nested arrays</p>
<p>I not getting approach but i can use map to map through datafromback array but don't know how to get inside it</p>
| [
{
"answer_id": 74419441,
"author": "N_A_P",
"author_id": 10693800,
"author_profile": "https://Stackoverflow.com/users/10693800",
"pm_score": 0,
"selected": false,
"text": "flat"
},
{
"answer_id": 74419454,
"author": "Ali Sattarzadeh",
"author_id": 11434567,
"author_profile": "https://Stackoverflow.com/users/11434567",
"pm_score": 0,
"selected": false,
"text": "const datafromback=[[{name:'ravi'}],[{}],[{}],[{}]]\n\nconst [{name}] = datafromback.find(data=>data.find(item=>item.name === 'ravi')?.name === 'ravi')\n\n console.log(name)"
},
{
"answer_id": 74419460,
"author": "Lucasbk38",
"author_id": 20480528,
"author_profile": "https://Stackoverflow.com/users/20480528",
"pm_score": 0,
"selected": false,
"text": "const handle = e => {\n if (Array.isArray(e))\n return e.map(handle)\n else {\n console.log(e.name)\n }\n}\n\nhandle(array)\n"
},
{
"answer_id": 74419491,
"author": "Amit Bhattacharjee",
"author_id": 5835545,
"author_profile": "https://Stackoverflow.com/users/5835545",
"pm_score": 0,
"selected": false,
"text": "datafromback.forEach(data => {\n //this is the nested array that contains the objects\n data.forEach(obj => {\n //here you can access the actual object\n if (obj?.name) console.log(obj.name);\n });\n});\n"
},
{
"answer_id": 74439466,
"author": "Fauzan DP",
"author_id": 18874268,
"author_profile": "https://Stackoverflow.com/users/18874268",
"pm_score": 1,
"selected": false,
"text": "const datafromback = [[{ name: 'ravi' }], [{}], [{}], [{}]]\n\nconst dataFrom = (arr, nameRavi) => {\n let result\n arr.forEach((ele) => {\n if (ele[0].name === nameRavi) result = ele[0].name\n })\n return result\n}\n\nconsole.log(dataFrom(datafromback, 'ravi'))"
},
{
"answer_id": 74440984,
"author": "Ahmad Mehmood",
"author_id": 20506894,
"author_profile": "https://Stackoverflow.com/users/20506894",
"pm_score": 0,
"selected": false,
"text": "const datafromback = [[{ name: 'ravi' }], [{}], [{}], [{}]];\nconst names = [];\n\ndatafromback.map((items) => {\n items.map((item) => {\n if (item?.name) names.push(item?.name);\n });\n});\nconsole.log(names);"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74419365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18202450/"
] |
74,419,397 | <p>Hi I have this map function I found in a tutorial, and I'm interested as to how I'd write this in the old way - i.e writing the word "function" rather than the "=>" arrow format.</p>
<pre><code>const example = spaceships.map((spaceship) => ({
homePlanet: spaceship.homePlanet,
color: spaceship.color
}));
</code></pre>
<p>I assumed that I could write it like this, but I get an error when adding the extra brackets.</p>
<pre><code>const example = spaceships.map(function(spaceship) ({
homePlanet: spaceship.homePlanet,
color: spaceship.color
}));
</code></pre>
| [
{
"answer_id": 74419441,
"author": "N_A_P",
"author_id": 10693800,
"author_profile": "https://Stackoverflow.com/users/10693800",
"pm_score": 0,
"selected": false,
"text": "flat"
},
{
"answer_id": 74419454,
"author": "Ali Sattarzadeh",
"author_id": 11434567,
"author_profile": "https://Stackoverflow.com/users/11434567",
"pm_score": 0,
"selected": false,
"text": "const datafromback=[[{name:'ravi'}],[{}],[{}],[{}]]\n\nconst [{name}] = datafromback.find(data=>data.find(item=>item.name === 'ravi')?.name === 'ravi')\n\n console.log(name)"
},
{
"answer_id": 74419460,
"author": "Lucasbk38",
"author_id": 20480528,
"author_profile": "https://Stackoverflow.com/users/20480528",
"pm_score": 0,
"selected": false,
"text": "const handle = e => {\n if (Array.isArray(e))\n return e.map(handle)\n else {\n console.log(e.name)\n }\n}\n\nhandle(array)\n"
},
{
"answer_id": 74419491,
"author": "Amit Bhattacharjee",
"author_id": 5835545,
"author_profile": "https://Stackoverflow.com/users/5835545",
"pm_score": 0,
"selected": false,
"text": "datafromback.forEach(data => {\n //this is the nested array that contains the objects\n data.forEach(obj => {\n //here you can access the actual object\n if (obj?.name) console.log(obj.name);\n });\n});\n"
},
{
"answer_id": 74439466,
"author": "Fauzan DP",
"author_id": 18874268,
"author_profile": "https://Stackoverflow.com/users/18874268",
"pm_score": 1,
"selected": false,
"text": "const datafromback = [[{ name: 'ravi' }], [{}], [{}], [{}]]\n\nconst dataFrom = (arr, nameRavi) => {\n let result\n arr.forEach((ele) => {\n if (ele[0].name === nameRavi) result = ele[0].name\n })\n return result\n}\n\nconsole.log(dataFrom(datafromback, 'ravi'))"
},
{
"answer_id": 74440984,
"author": "Ahmad Mehmood",
"author_id": 20506894,
"author_profile": "https://Stackoverflow.com/users/20506894",
"pm_score": 0,
"selected": false,
"text": "const datafromback = [[{ name: 'ravi' }], [{}], [{}], [{}]];\nconst names = [];\n\ndatafromback.map((items) => {\n items.map((item) => {\n if (item?.name) names.push(item?.name);\n });\n});\nconsole.log(names);"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74419397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5220731/"
] |
74,419,426 | <p>I have been learning about arrays and an interesting question popped up in my head.</p>
<p>I was wondering that with the current Java version, is there a way for me to print a character <code>string n</code> and make it appear for a brief moment at every index of an array consisting of only <code>""</code>, and then towards the end of the array, it can stop when it reaches the end index of the array.</p>
<p>For example if here is the given array and <code>string n = "2"</code> :</p>
<pre><code>[2,"","","",""]
</code></pre>
<p>the code will continously update like</p>
<pre><code>["2","","","",""]
["","2","","",""]
["","","2","",""]
["","","","2",""]
["","","","","2"]
</code></pre>
<p>and the end result would be</p>
<pre><code>["","","","","2"]
</code></pre>
<p>I would like to see the whole movement of <code>"2"</code> being played out without printing any excess arrays ( no more than one array should be in the output).</p>
<p>Is this possible? If yes, can you please suggest what should I look over to learn how to do this?</p>
| [
{
"answer_id": 74419441,
"author": "N_A_P",
"author_id": 10693800,
"author_profile": "https://Stackoverflow.com/users/10693800",
"pm_score": 0,
"selected": false,
"text": "flat"
},
{
"answer_id": 74419454,
"author": "Ali Sattarzadeh",
"author_id": 11434567,
"author_profile": "https://Stackoverflow.com/users/11434567",
"pm_score": 0,
"selected": false,
"text": "const datafromback=[[{name:'ravi'}],[{}],[{}],[{}]]\n\nconst [{name}] = datafromback.find(data=>data.find(item=>item.name === 'ravi')?.name === 'ravi')\n\n console.log(name)"
},
{
"answer_id": 74419460,
"author": "Lucasbk38",
"author_id": 20480528,
"author_profile": "https://Stackoverflow.com/users/20480528",
"pm_score": 0,
"selected": false,
"text": "const handle = e => {\n if (Array.isArray(e))\n return e.map(handle)\n else {\n console.log(e.name)\n }\n}\n\nhandle(array)\n"
},
{
"answer_id": 74419491,
"author": "Amit Bhattacharjee",
"author_id": 5835545,
"author_profile": "https://Stackoverflow.com/users/5835545",
"pm_score": 0,
"selected": false,
"text": "datafromback.forEach(data => {\n //this is the nested array that contains the objects\n data.forEach(obj => {\n //here you can access the actual object\n if (obj?.name) console.log(obj.name);\n });\n});\n"
},
{
"answer_id": 74439466,
"author": "Fauzan DP",
"author_id": 18874268,
"author_profile": "https://Stackoverflow.com/users/18874268",
"pm_score": 1,
"selected": false,
"text": "const datafromback = [[{ name: 'ravi' }], [{}], [{}], [{}]]\n\nconst dataFrom = (arr, nameRavi) => {\n let result\n arr.forEach((ele) => {\n if (ele[0].name === nameRavi) result = ele[0].name\n })\n return result\n}\n\nconsole.log(dataFrom(datafromback, 'ravi'))"
},
{
"answer_id": 74440984,
"author": "Ahmad Mehmood",
"author_id": 20506894,
"author_profile": "https://Stackoverflow.com/users/20506894",
"pm_score": 0,
"selected": false,
"text": "const datafromback = [[{ name: 'ravi' }], [{}], [{}], [{}]];\nconst names = [];\n\ndatafromback.map((items) => {\n items.map((item) => {\n if (item?.name) names.push(item?.name);\n });\n});\nconsole.log(names);"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74419426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18984687/"
] |
74,419,451 | <p>Let's say there is some arbitrary polygons having adjusting common sides.</p>
<p><a href="https://i.stack.imgur.com/jkHAF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jkHAF.png" alt="enter image description here" /></a></p>
<p>The task is to subdivide horizontal sides, where points Xs don't much with each other, by using simple algorithm method <code>simpleInterpolation(curve_, n_)</code>, in a way so the result would be:</p>
<p><a href="https://i.stack.imgur.com/YTSNS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YTSNS.png" alt="enter image description here" /></a></p>
<p>The attached snippet need to be updated at polygons.forEach(...).</p>
<pre><code>polygons.forEach((polygon_, i_) => {
let segments = [];
for(let i = 0; i < polygon_.length; i++){
let p1 = polygon_[i];
let p2 = polygon_[(i + 1) % polygon_.length];
let p3 = polygon_[(i + 2) % polygon_.length];
if(p1.x !== p2.x && p3.x !== p2.x){
if(segments.length === 0) {
segments.push({ indices: [i, (i + 1) % polygon_.length, (i + 2) % polygon_.length], points: [p1, p2, p3]});
}
else{
let lastSegment = segments[segments.length - 1];
if((i + 1) % polygon_.length !== lastSegment.indices[lastSegment.indices.length - 1]){
segments.push({ indices: [i, (i + 1) % polygon_.length, (i + 2) % polygon_.length], points: [p1, p2, p3] });
}
else {
lastSegment.indices.push((i + 2) % polygon_.length);
lastSegment.points.push(p3);
}
}
}
}
segments.forEach((segment_) => { segment_.points = simpleInterpolation(segment_.points, 4); })
console.log(segments);
})
</code></pre>
<p>There is already part which finds whose segments to be updated, I couldn't figure out how to replace old points with a new ones generated by <code>simpleInterpolation(curve_, n_)</code>. These segments could have start index greater than end, since the code checks last points with two first ones, so it makes updating tricky and segments could be shuffles, so starting indices couldn't fit simple increment.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const data = {
up: [
{ x: 200, y: 140 },
{ x: 300, y: 100 },
{ x: 500, y: 120 },
{ x: 600, y: 140 },
{ x: 600, y: 352.2 },
{ x: 400, y: 532.2 },
{ x: 200, y: 352.2 }
],
down: [
{ x: 200, y: 352.2 },
{ x: 400, y: 532.2 },
{ x: 600, y: 352.2 },
{ x: 600, y: 660 },
{ x: 200, y: 660 }
],
debug0: [
{ x: 200, y: 140 },
{ x: 400, y: 100 },
{ x: 600, y: 140 },
],
debug1: [
{ x: 200, y: 352.2 },
{ x: 400, y: 532.2 },
{ x: 600, y: 352.2 }
],
debugUp: [
{ x: 200, y: 140},
{ x: 212.5, y: 137.5},
{ x: 275, y: 130},
{ x: 400, y: 125},
{ x: 525, y: 130},
{ x: 587.5, y: 137.5},
{ x: 600, y: 140},
{ x: 600, y: 352.2},
{ x: 587.5, y: 363.45},
{ x: 525, y: 397.2},
{ x: 400, y: 419.70},
{ x: 275, y: 397.2},
{ x: 212.5, y: 363.45},
{ x: 200, y: 352.2}
],
debugDown: [
{ x: 200, y: 352.2},
{ x: 212.5, y: 363.45},
{ x: 275, y: 397.2},
{ x: 400, y: 419.70},
{ x: 525, y: 397.2},
{ x: 587.5, y: 363.45},
{ x: 600, y: 352.2},
{ x: 600, y: 660 },
{ x: 200, y: 660 }
]
};
let svg, curve0, curve1, EPS = 1E-5;
svg = d3.select("#scene");
let polygons = [data.up, data.down];
polygons.forEach((polygon_, i_) => {
let segments = [];
for(let i = 0; i < polygon_.length; i++){
let p1 = polygon_[i];
let p2 = polygon_[(i + 1) % polygon_.length];
let p3 = polygon_[(i + 2) % polygon_.length];
if(p1.x !== p2.x && p3.x !== p2.x){
if(segments.length === 0) {
segments.push({ indices: [i, (i + 1) % polygon_.length, (i + 2) % polygon_.length], points: [p1, p2, p3]});
}
else{
let lastSegment = segments[segments.length - 1];
if((i + 1) % polygon_.length !== lastSegment.indices[lastSegment.indices.length - 1]){
segments.push({ indices: [i, (i + 1) % polygon_.length, (i + 2) % polygon_.length], points: [p1, p2, p3] });
}
else {
lastSegment.indices.push((i + 2) % polygon_.length);
lastSegment.points.push(p3);
}
}
}
}
segments.forEach((segment_) => { segment_.points = simpleInterpolation(segment_.points, 4); })
console.log(segments);
})
let left = svg.append("g");
left.append("path")
.attr("d", generatePathFromPoints(data.up, true))
.attr("stroke", "#FF00FF")
.attr("fill", "#808080");
left.append("path")
.attr("d", generatePathFromPoints(data.down, true))
.attr("stroke", "#00FFFF")
.attr("fill", "#404040");
debugCurve0 = simpleInterpolation(data.debug0, 4);
left. append("path")
.attr("d", generatePathFromPoints(debugCurve0, false))
.attr("stroke", "#FF0000")
.attr("fill", "none");
let dots0 = left.selectAll(".debug0")
.data(debugCurve0)
.enter()
.append("circle")
.attr("class", "debug0")
.attr("cx", d_ => d_.x)
.attr("cy", d_ => d_.y)
.attr("r", 4)
.attr("fill", "#FF0000");
debugCurve1 = simpleInterpolation(data.debug1, 4);
left.append("path")
.attr("d", generatePathFromPoints(debugCurve1, false))
.attr("stroke", "#FF0000")
.attr("fill", "none");
let dots1 = left.selectAll(".debug1")
.data(debugCurve1)
.enter()
.append("circle")
.attr("class", "debug0")
.attr("cx", d_ => d_.x)
.attr("cy", d_ => d_.y)
.attr("r", 4)
.attr("fill", "#FF0000");
let right = svg.append("g").attr("transform", "translate(800, 0)");
right.append("path")
.attr("d", generatePathFromPoints(data.debugUp, true))
.attr("stroke", "#FF00FF")
.attr("fill", "#808080");
right.append("path")
.attr("d", generatePathFromPoints(data.debugDown, true))
.attr("stroke", "#00FFFF")
.attr("fill", "#404040");
function simpleInterpolation(curve_, n_){
let out, input = [...curve_];
for(let i = 0; i < n_; i++){
out = [input[0]];
for(let j = 0; j < input.length - 1; j++){
let p0 = input[j];
let p1 = input[j + 1];
let m01 = median(p0, p1, 0.5);
out.push(m01);
}
out.push(input[input.length - 1]);
input = out;
}
return out;
}
function median(p0_, p1_, t_){ return {x: p0_.x + (p1_.x - p0_.x) * t_, y: p0_.y + (p1_.y - p0_.y) * t_}; }
function generatePathFromPoints(points_, closed_){
let d = `M${points_[0].x} ${points_[0].y}`;
for(let i = 1; i < points_.length; i++) { d += `L${points_[i].x} ${points_[i].y}`; }
if(closed_) { d += "Z"; }
return d;
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>body: { margin: 0; }</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg id="scene" viewBox="0 0 1600 800" preserveAspectRatio="xMinYMin meet"></svg></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74419441,
"author": "N_A_P",
"author_id": 10693800,
"author_profile": "https://Stackoverflow.com/users/10693800",
"pm_score": 0,
"selected": false,
"text": "flat"
},
{
"answer_id": 74419454,
"author": "Ali Sattarzadeh",
"author_id": 11434567,
"author_profile": "https://Stackoverflow.com/users/11434567",
"pm_score": 0,
"selected": false,
"text": "const datafromback=[[{name:'ravi'}],[{}],[{}],[{}]]\n\nconst [{name}] = datafromback.find(data=>data.find(item=>item.name === 'ravi')?.name === 'ravi')\n\n console.log(name)"
},
{
"answer_id": 74419460,
"author": "Lucasbk38",
"author_id": 20480528,
"author_profile": "https://Stackoverflow.com/users/20480528",
"pm_score": 0,
"selected": false,
"text": "const handle = e => {\n if (Array.isArray(e))\n return e.map(handle)\n else {\n console.log(e.name)\n }\n}\n\nhandle(array)\n"
},
{
"answer_id": 74419491,
"author": "Amit Bhattacharjee",
"author_id": 5835545,
"author_profile": "https://Stackoverflow.com/users/5835545",
"pm_score": 0,
"selected": false,
"text": "datafromback.forEach(data => {\n //this is the nested array that contains the objects\n data.forEach(obj => {\n //here you can access the actual object\n if (obj?.name) console.log(obj.name);\n });\n});\n"
},
{
"answer_id": 74439466,
"author": "Fauzan DP",
"author_id": 18874268,
"author_profile": "https://Stackoverflow.com/users/18874268",
"pm_score": 1,
"selected": false,
"text": "const datafromback = [[{ name: 'ravi' }], [{}], [{}], [{}]]\n\nconst dataFrom = (arr, nameRavi) => {\n let result\n arr.forEach((ele) => {\n if (ele[0].name === nameRavi) result = ele[0].name\n })\n return result\n}\n\nconsole.log(dataFrom(datafromback, 'ravi'))"
},
{
"answer_id": 74440984,
"author": "Ahmad Mehmood",
"author_id": 20506894,
"author_profile": "https://Stackoverflow.com/users/20506894",
"pm_score": 0,
"selected": false,
"text": "const datafromback = [[{ name: 'ravi' }], [{}], [{}], [{}]];\nconst names = [];\n\ndatafromback.map((items) => {\n items.map((item) => {\n if (item?.name) names.push(item?.name);\n });\n});\nconsole.log(names);"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74419451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15818978/"
] |
74,419,493 | <p>I tried to export the generated chart to png file from the menu in this <a href="https://re.jrc.ec.europa.eu/pvg_tools/en/" rel="nofollow noreferrer">website</a>. After I manage to enter a city name and Visualize Results with script, the website shows some information and chart where I can export to png, either with small or large option. However, I could not manage to export large png file (option that I selected) of the chart because the script reach the timeout exception. The following is line that I've tried:</p>
<pre><code>elem = wait(driver, 10).until(EC.presence_of_element_located((By.ID, 'tr_exportpngl')))
elem.click()
</code></pre>
<p>i tried also solutions from other questions such as wait until 'lement_to_be_clickable' or finding by XPATH, still no success.</p>
<pre><code>elem = wait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//div[@id="tr_exportpngl"]')))
elem.click()
</code></pre>
<p>How can i make this work?</p>
<p>i look forward for your suggestion. thank you in advance.</p>
<p><a href="https://i.stack.imgur.com/3xnE1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3xnE1.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74419441,
"author": "N_A_P",
"author_id": 10693800,
"author_profile": "https://Stackoverflow.com/users/10693800",
"pm_score": 0,
"selected": false,
"text": "flat"
},
{
"answer_id": 74419454,
"author": "Ali Sattarzadeh",
"author_id": 11434567,
"author_profile": "https://Stackoverflow.com/users/11434567",
"pm_score": 0,
"selected": false,
"text": "const datafromback=[[{name:'ravi'}],[{}],[{}],[{}]]\n\nconst [{name}] = datafromback.find(data=>data.find(item=>item.name === 'ravi')?.name === 'ravi')\n\n console.log(name)"
},
{
"answer_id": 74419460,
"author": "Lucasbk38",
"author_id": 20480528,
"author_profile": "https://Stackoverflow.com/users/20480528",
"pm_score": 0,
"selected": false,
"text": "const handle = e => {\n if (Array.isArray(e))\n return e.map(handle)\n else {\n console.log(e.name)\n }\n}\n\nhandle(array)\n"
},
{
"answer_id": 74419491,
"author": "Amit Bhattacharjee",
"author_id": 5835545,
"author_profile": "https://Stackoverflow.com/users/5835545",
"pm_score": 0,
"selected": false,
"text": "datafromback.forEach(data => {\n //this is the nested array that contains the objects\n data.forEach(obj => {\n //here you can access the actual object\n if (obj?.name) console.log(obj.name);\n });\n});\n"
},
{
"answer_id": 74439466,
"author": "Fauzan DP",
"author_id": 18874268,
"author_profile": "https://Stackoverflow.com/users/18874268",
"pm_score": 1,
"selected": false,
"text": "const datafromback = [[{ name: 'ravi' }], [{}], [{}], [{}]]\n\nconst dataFrom = (arr, nameRavi) => {\n let result\n arr.forEach((ele) => {\n if (ele[0].name === nameRavi) result = ele[0].name\n })\n return result\n}\n\nconsole.log(dataFrom(datafromback, 'ravi'))"
},
{
"answer_id": 74440984,
"author": "Ahmad Mehmood",
"author_id": 20506894,
"author_profile": "https://Stackoverflow.com/users/20506894",
"pm_score": 0,
"selected": false,
"text": "const datafromback = [[{ name: 'ravi' }], [{}], [{}], [{}]];\nconst names = [];\n\ndatafromback.map((items) => {\n items.map((item) => {\n if (item?.name) names.push(item?.name);\n });\n});\nconsole.log(names);"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74419493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9461467/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.