qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,555,970
|
<p>Currently I'm getting data from some sensors with voltage(V) and current(C) values which is decoded into text as <code>V040038038039C125067</code> to be stored in MYSQL DB table. The voltage contains 4 different voltage values combined while the current contains 2 different current values combined where each value represented by 3 digits in the format of <code>Voltage xx.x C: Current xx.x</code>. For example, the current value of C125067 is actually 12.5 and 06.7A respectively. I tried to use python slicing some and some simple math to achieve this by dividing the values by 10 e.g. C125067 = 125/10 = 12.5. While this works for integers with first non-zero values (e.g. 125), when I tried to perform the same for values such as 040 or 067, I get the <em>SyntaxError: leading zeros in decimal integer literals are not permitted</em> error. Are there any better ways to achieve the desired decoding output of xx.x or to insert a decimal point before the last digit etc? Thanks.</p>
<pre><code>v1 = voltage[1:4]
v2 = voltage[4:7]
v3 = voltage[7:10]
v4 = voltage[10:13]
c1 = current[1:4]
c2 = current[4:7]
volt_1 = int(v1)/10
volt_2 = int(v2)/10
volt_3 = int(v3)/10
volt_4 = int(v4)/10
curr_1 = int(c1)/10
curr_2 = int(c2)/10
</code></pre>
|
[
{
"answer_id": 74556164,
"author": "PRADDYUMN YADAV",
"author_id": 15584394,
"author_profile": "https://Stackoverflow.com/users/15584394",
"pm_score": -1,
"selected": false,
"text": "a = int(input(\"Enter a random number: \"))\nprint(float(a/10))\n volt_1 = float(int(v1)/10)\nvolt_2 = float(int(v2)/10)\nvolt_3 = float(int(v3)/10)\nvolt_4 = float(int(v4)/10)\n\ncurr_1 = float(int(c1)/10)\ncurr_2 = float(int(c2)/10)\n"
},
{
"answer_id": 74556179,
"author": "Olsgaard",
"author_id": 11148296,
"author_profile": "https://Stackoverflow.com/users/11148296",
"pm_score": 0,
"selected": false,
"text": "int '040' Python 3.9.13 | packaged by conda-forge | (main, May 27 2022, 16:56:21) \nType 'copyright', 'credits' or 'license' for more information\nIPython 8.4.0 -- An enhanced Interactive Python. Type '?' for help.\n\nIn [1]: int('040')\nOut[1]: 40\n\nIn [2]: \n int(040) int('040') voltage = \"V040038038039C125067\"\n\nv1 = voltage[1:4]\nv2 = voltage[4:7]\nv3 = voltage[7:10]\nv4 = voltage[10:13]\n\nvolt_1 = int(v1)/10\nvolt_2 = int(v2)/10\nvolt_3 = int(v3)/10\nvolt_4 = int(v4)/10\n\nprint(v1, v2, v3, v4, volt_1, volt_2, volt_3, volt_4)\n# 040 038 038 039 4.0 3.8 3.8 3.9\n"
},
{
"answer_id": 74557280,
"author": "0x0fba",
"author_id": 20339407,
"author_profile": "https://Stackoverflow.com/users/20339407",
"pm_score": 0,
"selected": false,
"text": "import re\n\npattern = re.compile(r\"(\\d{3})\")\ndata = \"V040038038039C125067\"\nvalues = [int(x.lstrip(\"0\")) / 10.0 for x in pattern.findall(data)]\nvoltage, current = values[:4], values[4:]\nprint(voltage, current) # [4.0, 3.8, 3.8, 3.9] [12.5, 6.7]\n def parse(data):\n values = [int(x.lstrip(\"0\")) / 10.0 for x in pattern.findall(data)]\n return values[:4], values[4:]\n\nvoltage, current = parse(\"V040038038039C125067\")\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7234087/"
] |
74,556,020
|
<p>I am creating widget which displays the current path in a filesystem to the user.</p>
<p>For example, here is windows file path.
<a href="https://i.stack.imgur.com/mL8il.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mL8il.png" alt="enter image description here" /></a></p>
<p>With each folder opened, the folder name is added to the path. The issue is, when too many folders are added to the path, the Row overflows. Windows solves this by truncating the excess folders to the left
<a href="https://i.stack.imgur.com/V4B15.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/V4B15.png" alt="enter image description here" /></a></p>
<p>How can I determine if a widget will overflow, then render it with the overflowing portions removed?</p>
<p>I have tried a method involving calculating the length of the file path using TextPainter, however since my file path widgets are not purely text (icons, padding, etc), the result is rough and does not always work perfectly.</p>
|
[
{
"answer_id": 74556164,
"author": "PRADDYUMN YADAV",
"author_id": 15584394,
"author_profile": "https://Stackoverflow.com/users/15584394",
"pm_score": -1,
"selected": false,
"text": "a = int(input(\"Enter a random number: \"))\nprint(float(a/10))\n volt_1 = float(int(v1)/10)\nvolt_2 = float(int(v2)/10)\nvolt_3 = float(int(v3)/10)\nvolt_4 = float(int(v4)/10)\n\ncurr_1 = float(int(c1)/10)\ncurr_2 = float(int(c2)/10)\n"
},
{
"answer_id": 74556179,
"author": "Olsgaard",
"author_id": 11148296,
"author_profile": "https://Stackoverflow.com/users/11148296",
"pm_score": 0,
"selected": false,
"text": "int '040' Python 3.9.13 | packaged by conda-forge | (main, May 27 2022, 16:56:21) \nType 'copyright', 'credits' or 'license' for more information\nIPython 8.4.0 -- An enhanced Interactive Python. Type '?' for help.\n\nIn [1]: int('040')\nOut[1]: 40\n\nIn [2]: \n int(040) int('040') voltage = \"V040038038039C125067\"\n\nv1 = voltage[1:4]\nv2 = voltage[4:7]\nv3 = voltage[7:10]\nv4 = voltage[10:13]\n\nvolt_1 = int(v1)/10\nvolt_2 = int(v2)/10\nvolt_3 = int(v3)/10\nvolt_4 = int(v4)/10\n\nprint(v1, v2, v3, v4, volt_1, volt_2, volt_3, volt_4)\n# 040 038 038 039 4.0 3.8 3.8 3.9\n"
},
{
"answer_id": 74557280,
"author": "0x0fba",
"author_id": 20339407,
"author_profile": "https://Stackoverflow.com/users/20339407",
"pm_score": 0,
"selected": false,
"text": "import re\n\npattern = re.compile(r\"(\\d{3})\")\ndata = \"V040038038039C125067\"\nvalues = [int(x.lstrip(\"0\")) / 10.0 for x in pattern.findall(data)]\nvoltage, current = values[:4], values[4:]\nprint(voltage, current) # [4.0, 3.8, 3.8, 3.9] [12.5, 6.7]\n def parse(data):\n values = [int(x.lstrip(\"0\")) / 10.0 for x in pattern.findall(data)]\n return values[:4], values[4:]\n\nvoltage, current = parse(\"V040038038039C125067\")\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14556195/"
] |
74,556,021
|
<p>I have an array of Objects `filteredG`, Every single object contains some Json data about route. Objects inside <strong>filteredG</strong> can change frequently. The url I want to fetch from is changing based on <strong>route.id</strong>. If I try to map this data it isn't getting mapped inside a single array, since I try to fetch data from multiple link. Note that, there is many to many relations between <strong>routes</strong> and <strong>stoppages.</strong></p>
<p><strong>My code example:</strong></p>
<p><code>filteredG = [{id: 1, attributes: {…}, calendarId: 0, name: 'Rupsha'}, {id: 2, attributes: {…}, calendarId: 0, name: 'Boyra'}]</code> this array has variable length.</p>
<pre><code>filteredG.forEach((route) => fetch(`/api/stoppages?routeId=${route.id}`)
.then((response) => response.json())
.then((data) => {
data.map((stoppage) => console.log(stoppage));
}));
</code></pre>
<p><strong>Result:</strong></p>
<p>this snippet is printing bunch of <strong>stoppages</strong> objects in the console.</p>
<p>What I want is to store these objects which is currently get printed in a single array. How can I make that happen?</p>
<p>Please help.</p>
|
[
{
"answer_id": 74556154,
"author": "Dmytro Kudryk",
"author_id": 19069336,
"author_profile": "https://Stackoverflow.com/users/19069336",
"pm_score": 0,
"selected": false,
"text": "Promise.all(filteredG.map(route =>\n fetch(`/api/stoppages?routeId=${route.id}`)\n .then(response => response.json())\n)).then(results => {\n ...here you map the result to an array\n})\n"
},
{
"answer_id": 74556187,
"author": "Gia Huy Nguyễn",
"author_id": 20485039,
"author_profile": "https://Stackoverflow.com/users/20485039",
"pm_score": 1,
"selected": false,
"text": "const allData = filteredG.map((route) => fetch(`/api/stoppages?routeId=${route.id}`)\n .then((response) => response.json()));\nconst aData = Promise.all(allData).then((arrayData) =>\n arrayData.reduce((data, item) => ([...data, ...item]), []));\n\n//result\naData.then(data => console.log(data));\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19905399/"
] |
74,556,063
|
<p>I want to store the information of multiple inputs entered into <a href="https://ant.design/components/select" rel="nofollow noreferrer">antd Select</a> components in a single state variable but am having trouble getting the below to work.</p>
<p>This example is solved <a href="https://stackoverflow.com/questions/63710791/react-hooks-handle-multiple-inputs">here</a> for a form but the same solution doesn't seem to work for antd Select component. There are two inputs: a first name and a last name that I want to remember. The below code doesn't work because e doesn't have an attribute called name is what the console tells me. I also tried e.target.name and e.target.value but I get an error that e doesn't have an attribute called a target either. What is the right way to do this?</p>
<pre><code>import React, { useState } from 'react';
import { Select } from 'antd';
const App = () =>{
const [varState, setVarState] = useState({firstName:'Jack', lastName:'Smith'});
const firstNameOptions = [ {label:'Jack', value:'Jack'}, {label:'Jill',value:'Jill'}, {label:'Bill',value:'Bill'} ];
const lastNameOptions = [ {label:'Smith', value:'Smith'}, {label:'Potter',value:'Potter'}, {label:'Bach',value:'Bach'} ];
const changeState = (e) => {
setVarState( prevState => ({ ...prevState, [e.name]: e.value}));
console.log(varState)
};
return ( <>
<div>
<Select name={'firstName'} defaultValue={'Pick One'} options={firstNameOptions} onChange={changeState} />
<Select name={'lastName'} defaultValue={'Pick One'} options={lastNameOptions} onChange={changeState} />
</div>
</>
);
}
export default App;
</code></pre>
<ol>
<li>At the heart of it, it seems that I don't know how to name the Select components in such a way that their names can be passed on to the onChange handler.</li>
<li>More generally, given a component like antd Select, how can I figure out what the right "name field" is for this component so that it's value can be passed on to an onChange handler? For instance, what in the <a href="https://ant.design/components/select" rel="nofollow noreferrer">documentation</a> for select gives this information?</li>
</ol>
|
[
{
"answer_id": 74556154,
"author": "Dmytro Kudryk",
"author_id": 19069336,
"author_profile": "https://Stackoverflow.com/users/19069336",
"pm_score": 0,
"selected": false,
"text": "Promise.all(filteredG.map(route =>\n fetch(`/api/stoppages?routeId=${route.id}`)\n .then(response => response.json())\n)).then(results => {\n ...here you map the result to an array\n})\n"
},
{
"answer_id": 74556187,
"author": "Gia Huy Nguyễn",
"author_id": 20485039,
"author_profile": "https://Stackoverflow.com/users/20485039",
"pm_score": 1,
"selected": false,
"text": "const allData = filteredG.map((route) => fetch(`/api/stoppages?routeId=${route.id}`)\n .then((response) => response.json()));\nconst aData = Promise.all(allData).then((arrayData) =>\n arrayData.reduce((data, item) => ([...data, ...item]), []));\n\n//result\naData.then(data => console.log(data));\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2260079/"
] |
74,556,075
|
<p>I am trying below array to display</p>
<pre><code> myData = {
"data": {
"ZSLatencies": {
"Recharging API Latency": [
[
"<200ms",
2320
],
[
">200ms",
4
],
[
">500ms",
0
],
[
">1000ms",
0
],
[
">2000ms",
0
],
[
">3000ms",
0
]
]
}
}
}
</code></pre>
<p>I am trying to read a json file and trying to display in angular template</p>
<pre><code><div *ngFor="i of myData.data.ZSLatencies" >
<p *ngFor="let d of i">
{{d}}
</p>
</div>
</code></pre>
<p>It shows below error
<a href="https://i.stack.imgur.com/vAhGk.png" rel="nofollow noreferrer">enter image description here</a></p>
|
[
{
"answer_id": 74556345,
"author": "GouriSankar",
"author_id": 7235140,
"author_profile": "https://Stackoverflow.com/users/7235140",
"pm_score": 1,
"selected": false,
"text": " <div *ngFor=\"let i of myData.data.ZSLatencies.Recharging API Latency\">\n {{i | json}}\n </div>\n"
},
{
"answer_id": 74556922,
"author": "Navoneel Talukdar",
"author_id": 5651109,
"author_profile": "https://Stackoverflow.com/users/5651109",
"pm_score": 0,
"selected": false,
"text": "ts let allLatencyValues = myData[\"data\"][\"ZSLatencies\"][\"Recharging API Latency\"].map(x => x).reduce((acc, val) => acc.concat(val), []);\n <p *ngFor=\"let val of allLatencyValues; let i = index\">\n {{i + 1}}. {{ val }}\n</p>\n"
},
{
"answer_id": 74557960,
"author": "Md Ratan Hossain",
"author_id": 11649905,
"author_profile": "https://Stackoverflow.com/users/11649905",
"pm_score": 0,
"selected": false,
"text": "<div class=\"container\">\n <table class=\"table table-striped \" *ngFor=\"let item of myData | keyvalue\" style=\"width: auto\">\n <ng-container *ngFor=\"let innerkey of item.value| keyvalue\">\n <ng-container *ngFor=\"let innerkey2 of innerkey.value| keyvalue\">\n <thead>\n <tr>\n <th scope=\"col\">{{innerkey2.key}}</th>\n <th scope=\"col\">{{innerkey2.key}}</th>\n </tr>\n </thead>\n <tbody>\n <tr *ngFor=\"let row of innerkey2.value | keyvalue\">\n <td>{{row.value}}</td>\n <td>{{row.value}}</td>\n </tr>\n </tbody>\n </ng-container>\n \n </ng-container>\n </table>\n</div>\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11649905/"
] |
74,556,090
|
<p>I am reading a table to a dataframe which has a column "day_dt" which is in date format "2022/01/08". I want the format to be in "1/8/2022" (M/d/yyyy) Is it possible in pyspark? I have tried using date_format() but resulting in null.</p>
|
[
{
"answer_id": 74556345,
"author": "GouriSankar",
"author_id": 7235140,
"author_profile": "https://Stackoverflow.com/users/7235140",
"pm_score": 1,
"selected": false,
"text": " <div *ngFor=\"let i of myData.data.ZSLatencies.Recharging API Latency\">\n {{i | json}}\n </div>\n"
},
{
"answer_id": 74556922,
"author": "Navoneel Talukdar",
"author_id": 5651109,
"author_profile": "https://Stackoverflow.com/users/5651109",
"pm_score": 0,
"selected": false,
"text": "ts let allLatencyValues = myData[\"data\"][\"ZSLatencies\"][\"Recharging API Latency\"].map(x => x).reduce((acc, val) => acc.concat(val), []);\n <p *ngFor=\"let val of allLatencyValues; let i = index\">\n {{i + 1}}. {{ val }}\n</p>\n"
},
{
"answer_id": 74557960,
"author": "Md Ratan Hossain",
"author_id": 11649905,
"author_profile": "https://Stackoverflow.com/users/11649905",
"pm_score": 0,
"selected": false,
"text": "<div class=\"container\">\n <table class=\"table table-striped \" *ngFor=\"let item of myData | keyvalue\" style=\"width: auto\">\n <ng-container *ngFor=\"let innerkey of item.value| keyvalue\">\n <ng-container *ngFor=\"let innerkey2 of innerkey.value| keyvalue\">\n <thead>\n <tr>\n <th scope=\"col\">{{innerkey2.key}}</th>\n <th scope=\"col\">{{innerkey2.key}}</th>\n </tr>\n </thead>\n <tbody>\n <tr *ngFor=\"let row of innerkey2.value | keyvalue\">\n <td>{{row.value}}</td>\n <td>{{row.value}}</td>\n </tr>\n </tbody>\n </ng-container>\n \n </ng-container>\n </table>\n</div>\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20587622/"
] |
74,556,099
|
<p>I have a json file which looks like this</p>
<pre><code>[
{
path1:"xyz",
path2: "xyz2",
file1: "filea",
file2: "fileb",
state: "equal"
},
{
path1:"xyz",
path2: "xyz2",
file1: "filec",
file2: "filed",
state: "distinct"
},
{
path1:"xyz",
path2: "xyz2",
file1: "filee",
file2: "filef",
state: "equal"
},
{
path1:"xyz4",
path2: "xyz3",
file1: "fileg",
file2: "fileh",
state: "distinct"
}
]
</code></pre>
<p>The problem is I should get the json object data which have the type of <code>state:distinct</code>
which should look like this</p>
<pre><code>[
{
path1:"xyz",
path2: "xyz2",
file1: "filec",
file2: "filed",
state: "distinct"
},
{
path1:"xyz4",
path2: "xyz3",
file1: "fileg",
file2: "fileh",
state: "distinct"
}
]
</code></pre>
<p>Is there any solution so that, I can get a json data like above in JavaScript?</p>
|
[
{
"answer_id": 74556254,
"author": "Sunil Nagre",
"author_id": 2739512,
"author_profile": "https://Stackoverflow.com/users/2739512",
"pm_score": 0,
"selected": false,
"text": "enter code here\nvar data = [\n{\n path1:\"xyz\",\n path2: \"xyz2\",\n file1: \"filea\",\n file2: \"fileb\", \n state: \"equal\"\n},\n{\n path1:\"xyz\",\n path2: \"xyz2\",\n file1: \"filec\",\n file2: \"filed\",\n state: \"distinct\"\n},\n{\n path1:\"xyz\",\n path2: \"xyz2\",\n file1: \"filee\",\n file2: \"filef\",\n state: \"equal\"\n},\n{\n path1:\"xyz4\",\n path2: \"xyz3\",\n file1: \"fileg\",\n file2: \"fileh\",\n state: \"distinct\"\n}\n];\n\nvar distinctStates = _.filter(data, { 'state': 'distinct'});\n"
},
{
"answer_id": 74556267,
"author": "ChanHyeok-Im",
"author_id": 6329353,
"author_profile": "https://Stackoverflow.com/users/6329353",
"pm_score": 0,
"selected": false,
"text": "filter() Array const datas = [\n {\n path1:\"xyz\",\n path2: \"xyz2\",\n file1: \"filea\",\n file2: \"fileb\", \n state: \"equal\"\n },\n {\n path1:\"xyz\",\n path2: \"xyz2\",\n file1: \"filec\",\n file2: \"filed\",\n state: \"distinct\"\n },\n {\n path1:\"xyz\",\n path2: \"xyz2\",\n file1: \"filee\",\n file2: \"filef\",\n state: \"equal\"\n },\n {\n path1:\"xyz4\",\n path2: \"xyz3\",\n file1: \"fileg\",\n file2: \"fileh\",\n state: \"distinct\"\n }\n];\n const distincts = datas.filter(data => data.state === 'distinct');\n"
},
{
"answer_id": 74556273,
"author": "Gia Huy Nguyễn",
"author_id": 20485039,
"author_profile": "https://Stackoverflow.com/users/20485039",
"pm_score": 3,
"selected": true,
"text": "const data = [\n{\n path1:\"xyz\",\n path2: \"xyz2\",\n file1: \"filea\",\n file2: \"fileb\", \n state: \"equal\"\n},\n{\n path1:\"xyz\",\n path2: \"xyz2\",\n file1: \"filec\",\n file2: \"filed\",\n state: \"distinct\"\n},\n{\n path1:\"xyz\",\n path2: \"xyz2\",\n file1: \"filee\",\n file2: \"filef\",\n state: \"equal\"\n},\n{\n path1:\"xyz4\",\n path2: \"xyz3\",\n file1: \"fileg\",\n file2: \"fileh\",\n state: \"distinct\"\n}\n]\n\nconst result = data.filter((item) => item.state === 'distinct');\nconsole.log(result)"
},
{
"answer_id": 74556314,
"author": "pope_maverick",
"author_id": 3065781,
"author_profile": "https://Stackoverflow.com/users/3065781",
"pm_score": 1,
"selected": false,
"text": "function filterData (data, key, value) {\n return data.filter((item) => item[key] === value )\n}\n\nconst filteredData = filterData(data, 'state', 'distinct')\n"
},
{
"answer_id": 74556422,
"author": "Vishnu Prabhu",
"author_id": 20587586,
"author_profile": "https://Stackoverflow.com/users/20587586",
"pm_score": 0,
"selected": false,
"text": "const myJson = [\n {\n path1: \"xyz\",\n path2: \"xyz2\",\n file1: \"filea\",\n file2: \"fileb\",\n state: \"equal\",\n },\n {\n path1: \"xyz\",\n path2: \"xyz2\",\n file1: \"filec\",\n file2: \"filed\",\n state: \"distinct\",\n },\n {\n path1: \"xyz\",\n path2: \"xyz2\",\n file1: \"filee\",\n file2: \"filef\",\n state: \"equal\",\n },\n {\n path1: \"xyz4\",\n path2: \"xyz3\",\n file1: \"fileg\",\n file2: \"fileh\",\n state: \"distinct\",\n },\n];\n\nconst result = myJson.filter((item) => item.state === \"distinct\");\n\nconsole.log(result);"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556099",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9257578/"
] |
74,556,100
|
<p>I'm learning react for the first time, I have an app where it fetches some data from a public API. I currently have it show 10 cards with random items from the API, and I have added a button to fetch a random item from the API and add it to the array, I managed to get the new item added to the array using push() but it does not show in the app itself. How can I make it that the new item is shown in the app as well?</p>
<p>Here is my code</p>
<p><strong>Home.js</strong></p>
<pre><code>import { useState, useEffect} from "react";
import Card from './Card';
const Home = () => {
const [animals, setAnimals] = useState([]);
const handleDelete = (id) => {
const newAnimals = animals.filter(animal => animal.id !== id);
setAnimals(newAnimals);
}
useEffect(() => {
fetch('https://zoo-animal-api.herokuapp.com/animals/rand/10')
.then(res => {return res.json()})
.then(data => {
setAnimals(data);
});
}, []);
const handleAddAnimal = () => {
fetch('https://zoo-animal-api.herokuapp.com/animals/rand/')
.then(res => {return res.json()})
.then(data => {
animals.push(data);
console.log(animals);
//what to do after this
})
}
return (
<div className="home">
<h2>Animals</h2>
<button onClick={handleAddAnimal}>Add Animal</button>
<Card animals={animals} handleDelete={handleDelete}/>
</div>
);
}
export default Home;
</code></pre>
<p><strong>Card.js</strong></p>
<pre><code>const Card = ({animals, handleDelete}) => {
// const animals = props.animals;
return (
<div className="col-3">
{animals.map((animal) => (
<div className="card" key={animal.id}>
<img
src={animal.image_link}
alt={animal.latin_name}
className="card-img-top"
/>
<div className="card-body">
<h3 className="card-title">{animal.name}</h3>
<p>Habitat: {animal.habitat}</p>
<button onClick={() => handleDelete(animal.id)}>Delete Animal</button>
</div>
</div>
))}
</div>
);
}
export default Card;
</code></pre>
<p><strong>App.js</strong></p>
<pre><code>import Navbar from './navbar';
import Home from './Home';
function App() {
return (
<section id="app">
<div className="container">
<Navbar />
<div className="row">
<Home />
</div>
</div>
</section>
);
}
export default App;
</code></pre>
<p><strong>Screenshot of what I see now</strong>
<a href="https://i.stack.imgur.com/EpYuI.png" rel="nofollow noreferrer">screenshot</a>
(I was also wondering how to fix the items going down instead of side by side but wanted to fix the add button first)</p>
<p>Let me know if there's anything else I should add, any help is appreciated, thank you!</p>
|
[
{
"answer_id": 74592701,
"author": "Zehan Khan",
"author_id": 16884475,
"author_profile": "https://Stackoverflow.com/users/16884475",
"pm_score": 0,
"selected": false,
"text": " const handleAddAnimal = () => {\n fetch('https://zoo-animal-api.herokuapp.com/animals/rand/')\n .then(res => {return res.json()})\n .then(data => {\n setAnimals([...animals,data])\n console.log(animals);\n //what to do after this\n })\n }\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18139951/"
] |
74,556,129
|
<p>My npm version is 8.11.0.</p>
<p>When I create react package, but it gives me a Warn.</p>
<p>How can I uninstall it?</p>
|
[
{
"answer_id": 74556169,
"author": "EWW",
"author_id": 20587602,
"author_profile": "https://Stackoverflow.com/users/20587602",
"pm_score": 0,
"selected": false,
"text": "npm uninstall <package_name_which_you_want_to_uninstall>\n"
},
{
"answer_id": 74556185,
"author": "S M Samnoon Abrar",
"author_id": 8188682,
"author_profile": "https://Stackoverflow.com/users/8188682",
"pm_score": 1,
"selected": false,
"text": "npm uninstall <package-name>\n package.json devDependencies package.json -D --save-dev npm uninstall -D <package-name>\n -g --global npm uninstall -g <package-name>\n"
},
{
"answer_id": 74556224,
"author": "pupilNew",
"author_id": 20587717,
"author_profile": "https://Stackoverflow.com/users/20587717",
"pm_score": 2,
"selected": false,
"text": "npm uninstall <package_name>\n uninstall -g npm uninstall -g <package_name>\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17848207/"
] |
74,556,138
|
<p>This code doesn't seem to work</p>
<pre><code>function ScrollToBottom(int listCount){
this.FindByName<CollectionView>
("MyCollectioNView").ScrollTo(listCount- 1, animate: false);
}
</code></pre>
<p>Note: The function will be called inside <code>MessagingCenter.Subscribe()</code>
What could be the workaround for this problem?</p>
|
[
{
"answer_id": 74556169,
"author": "EWW",
"author_id": 20587602,
"author_profile": "https://Stackoverflow.com/users/20587602",
"pm_score": 0,
"selected": false,
"text": "npm uninstall <package_name_which_you_want_to_uninstall>\n"
},
{
"answer_id": 74556185,
"author": "S M Samnoon Abrar",
"author_id": 8188682,
"author_profile": "https://Stackoverflow.com/users/8188682",
"pm_score": 1,
"selected": false,
"text": "npm uninstall <package-name>\n package.json devDependencies package.json -D --save-dev npm uninstall -D <package-name>\n -g --global npm uninstall -g <package-name>\n"
},
{
"answer_id": 74556224,
"author": "pupilNew",
"author_id": 20587717,
"author_profile": "https://Stackoverflow.com/users/20587717",
"pm_score": 2,
"selected": false,
"text": "npm uninstall <package_name>\n uninstall -g npm uninstall -g <package_name>\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8951304/"
] |
74,556,157
|
<p>I ad trying to pass parameters to call the following C# method</p>
<pre><code>public ActionResult GenerateInvoicePDFByInvoiceNum(string id,string apikey)
{
IInvoiceRepository rep = db.GetInvoiceRepository();
//
var api = Guid.Parse(apikey);
Invoice invoice = rep.GetByExpression(i => i.InvoiceNo.Equals(id) && i.Visit.Branch.Practice.APIKey.ToString().Equals(apikey)).FirstOrDefault();
if (invoice==null)
{
return HttpNotFound();
}
//return new Rotativa.ActionAsPdf("PrintInvoice", new { id = invoice.Id })
//{
// //CustomSwitches = "--load-error-handling ignore "
// CustomSwitches = "--disable-javascript"
//};
return RedirectToAction("GenerateInvoicePDF", new { id = invoice.Hash });
}
</code></pre>
<p>From the browser I am trying to call it with a call like this which worked when I had only one parameter, but I don't know how to change those to pass the second parameter</p>
<pre><code>http://foobar.n.co.za/Newlook/PrintInvoice/GenerateInvoicePDFByInvoiceNum/72341d
</code></pre>
<p>Thanks</p>
|
[
{
"answer_id": 74556304,
"author": "hossein sabziani",
"author_id": 4301195,
"author_profile": "https://Stackoverflow.com/users/4301195",
"pm_score": 1,
"selected": false,
"text": "\"?param1=value1¶m2=value2\" http://foobar.n.co.za/Newlook/PrintInvoice/GenerateInvoicePDFByInvoiceNum?id=1&1pikey=2\n"
},
{
"answer_id": 74561934,
"author": "RezA",
"author_id": 17942760,
"author_profile": "https://Stackoverflow.com/users/17942760",
"pm_score": 0,
"selected": false,
"text": " routes.MapRoute(\n name: \"RouteName\",\n url: \"{controller}/{action}/{id}/{apikey}\"\n );\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1688277/"
] |
74,556,210
|
<p>I am working with a dataframe which is similar to this:</p>
<pre><code>df1 <- data.frame(p1 = c("John", "John", "John", "John", "John", "John", "Jim", "Jim", "Jim", "Jim", "Jim", "Jim", "Jim","Jim" ),
elapsed_time = c(0, 4, 6, 9, 12, 14, 17, 22, 27, 35, 42, 47, 51, 57),
event_type = c("start of period", "play", "play", "play", "play", "play", "play", "play", "play", "timeout", "play", "play", "play", "play"))
</code></pre>
<p>and looks like this:</p>
<pre><code> p1 elapsed_time event_type
1 John 0 start of period
2 John 4 play
3 John 6 play
4 John 9 play
5 John 12 play
6 John 14 play
7 Jim 17 play
8 Jim 22 play
9 Jim 27 play
10 Jim 35 timeout
11 Jim 42 play
12 Jim 47 play
13 Jim 51 play
14 Jim 57 play
</code></pre>
<p>What I'd like to do is add a 4th column that calculates elapsed time since 1 of 3 things happened: 1) event_type == "start of period" 2) eventtype == "timeout" 3) p1 was changed (like in row 7 from John to Jim). Any of these three things should reset the 4th column to zero.</p>
<p>My desired output is</p>
<pre><code> p1 elapsed_time event_type elapsed_time_since_last_break
1 John 0 start of period 0
2 John 4 play 4
3 John 6 play 6
4 John 9 play 9
5 John 12 play 12
6 John 14 play 14
7 Jim 17 play 0
8 Jim 22 play 5
9 Jim 27 play 10
10 Jim 35 timeout 0
11 Jim 42 play 7
12 Jim 47 play 12
13 Jim 51 play 16
14 Jim 57 play 22
</code></pre>
<p>I'm somewhat new to r and haven't had much success. I'm sure there's probably a simple solution I'm overlooking.</p>
|
[
{
"answer_id": 74556412,
"author": "onyambu",
"author_id": 8380272,
"author_profile": "https://Stackoverflow.com/users/8380272",
"pm_score": 3,
"selected": false,
"text": "df1 %>%\n group_by(p1, elps = cumsum(event_type != 'play'))%>%\n mutate(elps = elapsed_time - elapsed_time[1])\n\n# A tibble: 14 × 4\n# Groups: p1, elps [13]\n p1 elapsed_time event_type elps\n <chr> <dbl> <chr> <dbl>\n 1 John 0 start of period 0\n 2 John 4 play 4\n 3 John 6 play 6\n 4 John 9 play 9\n 5 John 12 play 12\n 6 John 14 play 14\n 7 Jim 17 play 0\n 8 Jim 22 play 5\n 9 Jim 27 play 10\n10 Jim 35 timeout 0\n11 Jim 42 play 7\n12 Jim 47 play 12\n13 Jim 51 play 16\n14 Jim 57 play 22\n"
},
{
"answer_id": 74557798,
"author": "ThomasIsCoding",
"author_id": 12158757,
"author_profile": "https://Stackoverflow.com/users/12158757",
"pm_score": 2,
"selected": false,
"text": "data.table setDT(df1)[\n ,\n grp := (rowid(p1) == 1 | (event_type != \"play\"))\n][\n ,\n elps := elapsed_time - elapsed_time[grp][cumsum(grp)]\n][\n ,\n grp := NULL\n]\n > df1\n p1 elapsed_time event_type elps\n 1: John 0 start of period 0\n 2: John 4 play 4\n 3: John 6 play 6\n 4: John 9 play 9\n 5: John 12 play 12\n 6: John 14 play 14\n 7: Jim 17 play 0\n 8: Jim 22 play 5\n 9: Jim 27 play 10\n10: Jim 35 timeout 0\n11: Jim 42 play 7\n12: Jim 47 play 12\n13: Jim 51 play 16\n14: Jim 57 play 22\n"
},
{
"answer_id": 74616283,
"author": "D.J",
"author_id": 12440276,
"author_profile": "https://Stackoverflow.com/users/12440276",
"pm_score": 0,
"selected": false,
"text": "df1 %>% \n group_by(p1) %>% \n mutate(result=elapsed_time-ifelse(elapsed_time==elapsed_time[1] | event_type!='play', elapsed_time, 0)[1])\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19128163/"
] |
74,556,221
|
<p>I would like populate the blue area with random numbers.</p>
<p>sum of C3 to R3 should be equal to B3 value: 124
also;
sum of C3 to C26 should be equal to C2 value: 705</p>
<p>I tried to achieve it with the following code:
(this code was originally posted here: <a href="https://stackoverflow.com/questions/60637394/how-to-generate-ranges-of-random-values-on-x-columns-and-y-rows-that-sum-up-to-s">Code by @Mech</a></p>
<pre><code>Sub RandomNumbersArray()
' dim your variables. this tells vba what type of variable it is working with
Dim lRow As Long
Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet: Set ws = wb.Worksheets("SPLIT BY DAYS")
' find the last row in column b (2) in the above defined ws
lRow = ws.Cells(ws.Rows.Count, 2).End(xlUp).Row
' loop through rows 3 to last row
For i = 3 To lRow
' generate a random number between 0 and the row contents of column B (5)
ws.Cells(i, 3).Value = Int(Rnd() * (ws.Cells(i, 2).Value + 1))
' generate a random number between 0 and the difference between column B and colum C
ws.Cells(i, 4).Value = Int(Rnd() * (ws.Cells(i, 2).Value - ws.Cells(i, 3).Value))
' subtract the difference between column B and the sum of column C and column D
ws.Cells(i, 5).Value = ws.Cells(i, 2).Value - (ws.Cells(i, 3).Value + ws.Cells(i, 4).Value)
' subtract the difference between column B and the sum of column C and column D and column E
ws.Cells(i, 6).Value = ws.Cells(i, 2).Value - (ws.Cells(i, 3).Value + ws.Cells(i, 4).Value + ws.Cells(i, 5).Value)
' subtract the difference between column B and the sum of column C and column D and column E and column F
ws.Cells(i, 7).Value = ws.Cells(i, 2).Value - (ws.Cells(i, 3).Value + ws.Cells(i, 4).Value + ws.Cells(i, 5).Value + ws.Cells(i, 6).Value)
Next i
' sum column C (column 3) and place the value in C2
ws.Cells(2, 3).Value = Application.WorksheetFunction.Sum(Range(Cells(3, 3), Cells(lRow, 3)))
' sum column D (column 4) and place the value in D2
ws.Cells(2, 4).Value = Application.WorksheetFunction.Sum(Range(Cells(3, 4), Cells(lRow, 4)))
' sum column E (column 5) and place the value in E2
ws.Cells(2, 5).Value = Application.WorksheetFunction.Sum(Range(Cells(3, 5), Cells(lRow, 5)))
' sum column F (column 6) and place the value in F2
ws.Cells(2, 6).Value = Application.WorksheetFunction.Sum(Range(Cells(3, 6), Cells(lRow, 6)))
' sum column G (column 7) and place the value in F2
ws.Cells(2, 7).Value = Application.WorksheetFunction.Sum(Range(Cells(3, 7), Cells(lRow, 7)))
End Sub
</code></pre>
<p><a href="https://i.stack.imgur.com/T139n.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/T139n.png" alt="enter image description here" /></a></p>
<p>EDIT: Just to clarify, no zeros or negative numbers.</p>
|
[
{
"answer_id": 74598631,
"author": "Notus_Panda",
"author_id": 19353309,
"author_profile": "https://Stackoverflow.com/users/19353309",
"pm_score": 0,
"selected": false,
"text": "Sub RandomNumbersArray()\n Dim lRow As Long, lColumn As Long, remainingValue As Long\n Dim wb As Workbook: Set wb = ActiveWorkbook\n Dim ws As Worksheet: Set ws = wb.Worksheets(\"SPLIT BY DAYS\")\n \n lRow = ws.Cells(ws.Rows.Count, 2).End(xlUp).Row\n lColumn = ws.Cells(2, ws.Columns.Count).End(xlToLeft).Column\n\n For i = 3 To lRow 'loop through the rows\n remainingValue = ws.Cells(i, 2).Value2\n For j = 3 To lColumn 'loop through all the columns per row\n ' generate a random number between 0 and the row contents of column B - previous column\n If j = lColumn Then 'last cell can't be random unless you want to extend the columns until the sum in B-column is met\n ws.Cells(i, j).Value2 = remainingValue\n Else\n ws.Cells(i, j).Value2 = Int((remainingValue + 1) * Rnd)\n End If\n remainingValue = remainingValue - ws.Cells(i, j).Value2\n Next j\n Next i\n For j = 3 To lColumn 'loop through the columns to set the sum\n ws.Cells(2, j).Value2 = Application.WorksheetFunction.Sum(Range(Cells(3, j), Cells(lRow, j)))\n Next j\n \nEnd Sub\n"
},
{
"answer_id": 74639296,
"author": "Spencer Barnes",
"author_id": 12231984,
"author_profile": "https://Stackoverflow.com/users/12231984",
"pm_score": 0,
"selected": false,
"text": "Sub RandomFillArray(Total As Double, Address As Range)\n\nDim Cell As Range, rndTotal As Double\n\n'Put completely random values in the cells\nFor Each Cell In Address\n Cell.Value = Rnd\nNext\nrndTotal = WorksheetFunction.Sum(Address)\n\n'Use those random values as proportions of the total\nFor Each Cell In Address\n Cell.Value = Round(Cell.Value / rndTotal * Total)\nNext\n\n'There may be a difference due to rounding errors\n'Just add that to a random cell in the range\nIf WorksheetFunction.Sum(Address) <> Total Then\n 'Pick a random cell in the range\n Set Cell = Address.Cells(Int(Address.Cells.Count * Rnd + 1))\n 'Add or subtract whatever necessary to/from it to fix the total\n Cell.Value = Cell.Value - WorksheetFunction.Sum(Address) + Total\n \n 'Warning - this may result in a negative value!\nEnd If\n\nEnd Sub\n Sub CrossFillRandomly(Address As Range)\nDim ws As Worksheet: Set ws = Address.Worksheet\n\nDim Row As Long, Column As Long\nRow = 1: Column = 1\n\nDo Until Row + Column >= Address.Rows.Count + Address.Columns.Count + 1\n\n'Fill a Row \nIf Row < Address.Rows.Count Or Column = Address.Columns.Count Then\n Call RandomFillArray( _\n Total:=Address.Cells(Row, 1).Offset(0, -1) - IIf(Column > 1, WorksheetFunction.Sum(ws.Range(Address.Cells(Row, 1), Address.Cells(Row, Column - 1))), 0), _\n Address:=ws.Range(Address.Cells(Row, Column), Address.Cells(Row, Address.Columns.Count)))\n Row = Row + 1\nEnd If\n\n'Fill a Column\nIf Column < Address.Columns.Count Or Row = Address.Rows.Count Then\n Call RandomFillArray( _\n Total:=Address.Cells(1, Column).Offset(-1, 0) - WorksheetFunction.Sum(ws.Range(Address.Cells(1, Column), Address.Cells(Row, Column))), _\n Address:=ws.Range(Address.Cells(Row, Column), Address.Cells(Address.Rows.Count, Column)))\n Column = Column + 1\nEnd If\n\nLoop\nEnd Sub\n Sub CallCross()\n Dim wb As Workbook: Set wb = ThisWorkbook\n Dim ws As Worksheet: Set ws = wb.Worksheets(\"SPLIT BY DAYS\")\n CrossFillRandomly ws.Range(\"C3:R26\")\nEnd Sub\n"
},
{
"answer_id": 74654078,
"author": "Spencer Barnes",
"author_id": 12231984,
"author_profile": "https://Stackoverflow.com/users/12231984",
"pm_score": 0,
"selected": false,
"text": "Sub Call_Random_Array\nDim wb As Workbook: Set wb = ThisWorkbook\nDim ws As Worksheet: Set ws = wb.Worksheets(\"SPLIT BY DAYS\")\nDim RangeToFill as Range: Set RangeToFill = ws.Range(\"C3:R26\") 'Edit this line to select whatever range you need to fill randomly\n\n'Proportionately fill the array to fit totals:\nCall ProportionateFillArray(RangeToFill)\n\n'Randomize it x times\nFor x = 1 to 10 'increase this number for more randomisation\n Call RandomizeValues(RangeToFill)\nNext\n\nEnd Sub\n Sub ProportionateFillArray(rngAddress As Range)\nDim ws As Worksheet: Set ws = rngAddress.Worksheet\n\n'Horizontal and Vertical target values as ranges:\nDim hTarg As Range, vTarg As Range\nSet hTarg = rngAddress.Rows(1).Offset(-1, 0)\nSet vTarg = rngAddress.Columns(1).Offset(0, -1)\n\n'Check the totals match\nIf Not WorksheetFunction.Sum(hTarg) = WorksheetFunction.Sum(vTarg) Then\n 'totals don't match\n MsgBox \"Change the targets so both the horizontal and vertical targets add up to the same number.\"\n Exit Sub\nEnd If\n\nWith rngAddress\n \n 'Now fill rows and columns with integers\n Dim Row As Long, Col As Long\n For Row = 1 To .Rows.Count\n For Col = 1 To .Columns.Count\n .Cells(Row, Col) = Round( _\n hTarg.Cells(Col) * vTarg.Cells(Row) / WorksheetFunction.Sum(hTarg) _\n )\n Next\n Next\n \n 'Correct rounding errors\n For Row = 1 To .Rows.Count\n For Col = 1 To .Columns.Count\n If Row = .Rows.Count Then\n 'Last row, so this column must be corrected come what may\n .Cells(Row, Col) = .Cells(Row, Col) - WorksheetFunction.Sum(.Columns(Col)) + hTarg.Cells(Col)\n ElseIf Col = .Columns.Count Then\n 'Last column, so must be corrected come what may\n .Cells(Row, Col) = .Cells(Row, Col) - WorksheetFunction.Sum(.Rows(Row)) + vTarg.Cells(Row)\n ElseIf _\n (WorksheetFunction.Sum(.Rows(Row)) - vTarg.Cells(Row)) * _\n (WorksheetFunction.Sum(.Columns(Col)) - hTarg.Cells(Col)) > 0 Then\n 'both row and column are incorrect in the same direction\n .Cells(Row, Col) = WorksheetFunction.Max( _\n .Cells(Row, Col) - WorksheetFunction.Sum(.Rows(Row)) + vTarg.Cells(Row), _\n .Cells(Row, Col) - WorksheetFunction.Sum(.Columns(Col)) + hTarg.Cells(Col))\n End If\n Next\n Next\n\nEnd With\nEnd Sub\n Sub RandomizeValues(rngAddress As Range)\nDim ws As Worksheet: Set ws = rngAddress.Worksheet\nDim rngIncrease(1 To 2) As Range, rngDecrease(1 To 2) As Range, lDiff As Long\n\nWith rngAddress\n 'Select two cells to increase at random\n For a = 1 To 2\n Set rngIncrease(a) = .Cells(RndIntegerBetween(1, .Rows.Count), RndIntegerBetween(1, .Columns.Count))\n rngIncrease(a).Select\n Next\n \n 'Corresponding cells to decrease to make totals the same:\n Set rngDecrease(1) = ws.Cells(rngIncrease(1).Row, rngIncrease(2).Column)\n Set rngDecrease(2) = ws.Cells(rngIncrease(2).Row, rngIncrease(1).Column)\n \n 'Set the value to increase/decrease by - can't be more than the smallest rngDecrease Value, to prevent negative values\n lDiff = RndIntegerBetween(1, WorksheetFunction.Min(rngDecrease))\n \n 'Now apply the edits\n For a = 1 To 2\n rngIncrease(a) = rngIncrease(a) + lDiff\n rngDecrease(a) = rngDecrease(a) - lDiff\n Next\nEnd With\nEnd Sub\n\n'The below is the Random Integer function, I also used it in my other answer\nFunction RndIntegerBetween(Min As Long, Max As Long) As Long\nRndIntegerBetween = Int((Max - Min + 1) * Rnd + Min)\nEnd Function\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4441676/"
] |
74,556,243
|
<p>I'm starting to code on Javascript and practicing on codewars, I got this problem where I have to find the amount of times the most recurring number is repeated and I do get the correct answer but I also get an "undefined" below the answer and I can't seem to find the reason why... It may be something really simple that I'm missing but I'm stuck here and would appreaciate some help with an explanation.</p>
<pre><code>function mostFrequentItemCount(collection){
let a, b, c = 0, d = 0;
collection.sort((a,b) => a - b)
for (i=0; i<collection.length; i++){
if (collection[i] == collection[i-1]){
b = a = a + 1;
if (b>(c && d)){c = i; d = b}
} else {b = a; a = 1}
} console.log(d)
} console.log(mostFrequentItemCount([3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3]))
</code></pre>
<p>And this is the answer we get:</p>
<p>5</p>
<p>undefined</p>
|
[
{
"answer_id": 74556288,
"author": "walieeldin",
"author_id": 14979656,
"author_profile": "https://Stackoverflow.com/users/14979656",
"pm_score": -1,
"selected": false,
"text": "function mostFrequentItemCount(collection){\n \ncollection.sort((a,b) => a - b)\n let a, b, c , d = 0; \n for (i=0; i<collection.length; i++){\n if (collection[i] == collection[i-1]){\n b = a = a + 1;\n if (b>(c && d)){c=i; d=b}\n } else {b=a; a=1}\n } console.log(d)\n\n} console.log(mostFrequentItemCount([3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3]))\n"
},
{
"answer_id": 74556308,
"author": "Abirami Balasubramaniyan",
"author_id": 5755531,
"author_profile": "https://Stackoverflow.com/users/5755531",
"pm_score": 0,
"selected": false,
"text": "console.log(mostFrequentItemCount([3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3])).\n"
},
{
"answer_id": 74556463,
"author": "Suresh Ponnukalai",
"author_id": 3607064,
"author_profile": "https://Stackoverflow.com/users/3607064",
"pm_score": 0,
"selected": false,
"text": "5 console.log undefined console.log function mostFrequentItemCount(collection){\n let a, b, c = 0, d = 0; \n collection.sort((a,b) => a - b)\n \n for (i=0; i<collection.length; i++){\n if (collection[i] == collection[i-1]){\n b = a = a + 1;\n if (b>(c && d)){c = i; d = b}\n } else {b = a; a = 1}\n } console.log(d) // This is showing the expected output\n \n return d; //This will return the value to where the function called\n} \n\nconsole.log(mostFrequentItemCount([3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3]))"
},
{
"answer_id": 74556800,
"author": "Mexo",
"author_id": 20587652,
"author_profile": "https://Stackoverflow.com/users/20587652",
"pm_score": -1,
"selected": false,
"text": "function mostFrequentItemCount(collection){\n\nif(collection.length == 0) return 0\n\nelse{ let a, b, c = 1; \ncollection.sort((a,b) => a - b)\n\nfor (i=0; i<collection.length; i++){\n if (collection[i] == collection[i-1]){\n b = a = a + 1;\n if (b >= c){c = b}\n } else {b = a; a = 1}\n} return c }}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20587652/"
] |
74,556,281
|
<p>I was Wondering how to give style to two tags in react without using the className(as not using className is the main challenge).</p>
<pre><code><a href="">Menu Here</a>
<a href="">Click Me </a>
</code></pre>
<p><a href="https://i.stack.imgur.com/OHgvC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OHgvC.png" alt="enter image description here" /></a></p>
<p>So for the "curry dish," it should only underline when hovering.
And for the click me it should be underlined first and disappear while hovering on it.
I got both underlines removed using the code below. But still can't figure out how to apply separate styling please help.</p>
<pre><code>a: hover {
text-decoration: underline;
}
</code></pre>
|
[
{
"answer_id": 74556288,
"author": "walieeldin",
"author_id": 14979656,
"author_profile": "https://Stackoverflow.com/users/14979656",
"pm_score": -1,
"selected": false,
"text": "function mostFrequentItemCount(collection){\n \ncollection.sort((a,b) => a - b)\n let a, b, c , d = 0; \n for (i=0; i<collection.length; i++){\n if (collection[i] == collection[i-1]){\n b = a = a + 1;\n if (b>(c && d)){c=i; d=b}\n } else {b=a; a=1}\n } console.log(d)\n\n} console.log(mostFrequentItemCount([3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3]))\n"
},
{
"answer_id": 74556308,
"author": "Abirami Balasubramaniyan",
"author_id": 5755531,
"author_profile": "https://Stackoverflow.com/users/5755531",
"pm_score": 0,
"selected": false,
"text": "console.log(mostFrequentItemCount([3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3])).\n"
},
{
"answer_id": 74556463,
"author": "Suresh Ponnukalai",
"author_id": 3607064,
"author_profile": "https://Stackoverflow.com/users/3607064",
"pm_score": 0,
"selected": false,
"text": "5 console.log undefined console.log function mostFrequentItemCount(collection){\n let a, b, c = 0, d = 0; \n collection.sort((a,b) => a - b)\n \n for (i=0; i<collection.length; i++){\n if (collection[i] == collection[i-1]){\n b = a = a + 1;\n if (b>(c && d)){c = i; d = b}\n } else {b = a; a = 1}\n } console.log(d) // This is showing the expected output\n \n return d; //This will return the value to where the function called\n} \n\nconsole.log(mostFrequentItemCount([3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3]))"
},
{
"answer_id": 74556800,
"author": "Mexo",
"author_id": 20587652,
"author_profile": "https://Stackoverflow.com/users/20587652",
"pm_score": -1,
"selected": false,
"text": "function mostFrequentItemCount(collection){\n\nif(collection.length == 0) return 0\n\nelse{ let a, b, c = 1; \ncollection.sort((a,b) => a - b)\n\nfor (i=0; i<collection.length; i++){\n if (collection[i] == collection[i-1]){\n b = a = a + 1;\n if (b >= c){c = b}\n } else {b = a; a = 1}\n} return c }}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7518534/"
] |
74,556,293
|
<p><strong>Output what I got</strong></p>
<pre><code>{
0:{modifierId: 4, modifierName: 'Garlic', modifierPrice: 60 }
1:{modifierId: 1, modifierName: 'Tartar ', modifierPrice: 60}
2:{modifierId: 3, modifierName: 'Herb ', modifierPrice: 60}
itemId:387
itemName:"BUFFALO WINGS"
itemPrice:500
itemQuantity:0
}
</code></pre>
<p>I am working on a <strong>point of sale</strong> project using <strong>angular</strong>
The concept is when the user clicks on <strong>itemName</strong> button, it will display it's modifiers in a dialog box. All this data is coming from restful API.
When I click on a <strong>modifier</strong>, it's object is passed into the item's object. In that case, when I call the items to display in cart using ngFor*, it gives an error. Because angular does not allow objects to be passed in ngFor*, it only works with arrays.</p>
<p><strong>Output I expect</strong></p>
<pre><code>[
0:{modifierId: 4, modifierName: 'Garlic', modifierPrice: 60}
1:{modifierId: 1, modifierName: 'Tartar ', modifierPrice: 60}
2:{modifierId: 3, modifierName: 'Herb ', modifierPrice: 60}
itemId:387
itemName:"BUFFALO WINGS"
itemPrice:500
itemQuantity:0
*length:3*
]
</code></pre>
<p>Now what I want is, to pass the modifier's object into an array. So, how can I do that</p>
|
[
{
"answer_id": 74556288,
"author": "walieeldin",
"author_id": 14979656,
"author_profile": "https://Stackoverflow.com/users/14979656",
"pm_score": -1,
"selected": false,
"text": "function mostFrequentItemCount(collection){\n \ncollection.sort((a,b) => a - b)\n let a, b, c , d = 0; \n for (i=0; i<collection.length; i++){\n if (collection[i] == collection[i-1]){\n b = a = a + 1;\n if (b>(c && d)){c=i; d=b}\n } else {b=a; a=1}\n } console.log(d)\n\n} console.log(mostFrequentItemCount([3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3]))\n"
},
{
"answer_id": 74556308,
"author": "Abirami Balasubramaniyan",
"author_id": 5755531,
"author_profile": "https://Stackoverflow.com/users/5755531",
"pm_score": 0,
"selected": false,
"text": "console.log(mostFrequentItemCount([3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3])).\n"
},
{
"answer_id": 74556463,
"author": "Suresh Ponnukalai",
"author_id": 3607064,
"author_profile": "https://Stackoverflow.com/users/3607064",
"pm_score": 0,
"selected": false,
"text": "5 console.log undefined console.log function mostFrequentItemCount(collection){\n let a, b, c = 0, d = 0; \n collection.sort((a,b) => a - b)\n \n for (i=0; i<collection.length; i++){\n if (collection[i] == collection[i-1]){\n b = a = a + 1;\n if (b>(c && d)){c = i; d = b}\n } else {b = a; a = 1}\n } console.log(d) // This is showing the expected output\n \n return d; //This will return the value to where the function called\n} \n\nconsole.log(mostFrequentItemCount([3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3]))"
},
{
"answer_id": 74556800,
"author": "Mexo",
"author_id": 20587652,
"author_profile": "https://Stackoverflow.com/users/20587652",
"pm_score": -1,
"selected": false,
"text": "function mostFrequentItemCount(collection){\n\nif(collection.length == 0) return 0\n\nelse{ let a, b, c = 1; \ncollection.sort((a,b) => a - b)\n\nfor (i=0; i<collection.length; i++){\n if (collection[i] == collection[i-1]){\n b = a = a + 1;\n if (b >= c){c = b}\n } else {b = a; a = 1}\n} return c }}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556293",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14418119/"
] |
74,556,330
|
<p>In the <code>home_screen.dart</code>, I added 5 of <em>bottomNavigationBar</em> to move easily to other pages. At the second tab(<code>Icons.directions_boat_filled</code>), when I tab this It shows the <em>AppBar</em> and <em>bottomNavigationBar</em> also.</p>
<p>However, the <em>GestureDetector</em> which moves to the <code>vessel_screen.dart</code>, I couldn't find any <em>AppBar</em> and <em>bottomNavigationBar</em> when I click this button.</p>
<p>How can I see the <strong>AppBar and bottomNavigationBar</strong> in the same way when I clicked the second bottomNavigationBar Icon?</p>
<p>Here is the <code>home_screen.dart</code></p>
<pre><code>import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:shipda/constants.dart';
import 'package:shipda/screens/home/home_main.dart';
import 'package:get/get.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:shipda/screens/license_screen/license_screen.dart';
import 'package:shipda/screens/parts_screen/parts_screen.dart';
import 'package:shipda/screens/tab_bar_screen/tab_bar_screen.dart';
import 'package:shipda/screens/vessel_screen/vessel_screen.dart';
class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key}) : super(key: key);
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
final _authentication = FirebaseAuth.instance;
User? loggedUser;
final firestore = FirebaseFirestore.instance;
var resultData;
void getData() async {
var result = await firestore
.collection('user')
.doc('vUj4U27JoAU6zgFDk6sSZiwadQ13')
.get();
setState(() {
resultData = result.data();
});
}
@override
void initState() {
super.initState();
getCurrentUser();
getData();
}
void getCurrentUser() {
try {
final user = _authentication.currentUser;
if (user != null) {
loggedUser = user;
print(loggedUser!.email);
}
} catch (e) {
print(e);
}
}
// Bottom Navigation Bar 스크린 인덱스
int _selectedIndex = 0;
final List<Widget> _widgetOptions = <Widget>[
HomeMain(),
VesselScreen(),
LicenseScreen(),
PartsScreen(),
TabBarScreen(),
];
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
// ----
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
'쉽다로고',
style: TextStyle(
color: baseColor50,
),
),
backgroundColor: baseColor10,
elevation: 0.0,
),
body: SafeArea(
child: _widgetOptions.elementAt(_selectedIndex),
),
// 바텀네비게이션바
bottomNavigationBar: BottomNavigationBar(
selectedItemColor: primaryColor50,
currentIndex: _selectedIndex,
onTap: _onItemTapped,
type: BottomNavigationBarType.fixed,
items: [
BottomNavigationBarItem(
icon: _selectedIndex == 0
? Icon(Icons.home)
: Icon(Icons.home_outlined),
label: '홈',
),
// This is the icon.
BottomNavigationBarItem(
icon: _selectedIndex == 1
? Icon(Icons.directions_boat_filled)
: Icon(Icons.directions_boat_outlined),
label: '선박',
),
BottomNavigationBarItem(
icon: _selectedIndex == 2
? Icon(Icons.document_scanner)
: Icon(Icons.document_scanner_outlined),
label: '허가',
),
BottomNavigationBarItem(
icon: _selectedIndex == 3
? Icon(Icons.handyman)
: Icon(Icons.handyman_outlined),
label: '부품',
),
BottomNavigationBarItem(
icon: Icon(Icons.menu),
label: '전체',
),
],
),
);
}
}
</code></pre>
<p><code>home_main.dart</code></p>
<pre><code>import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:shipda/screens/vessel_screen/vessel_screen.dart';
import '../../constants.dart';
import '../vessel_screen/fishing_vessel/fishing_vessel_screen.dart';
class HomeMain extends StatelessWidget {
const HomeMain({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Container(
height: 680,
width: MediaQuery.of(context).size.width,
color: baseColor20,
child: Padding(
padding: const EdgeInsets.fromLTRB(16.0, 0.0, 16.0, 0.0),
child: Column(
children: [
marginHeight22,
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
// 최근검색버튼
GestureDetector(
onTap: () {},
child: Container(
decoration: BoxDecoration(
color: primaryColor20,
border: Border.all(
color: primaryColor20,
),
borderRadius: BorderRadius.all(
Radius.circular(12.0),
),
),
height: 48,
width: MediaQuery.of(context).size.width * 0.435,
child: Center(
child: Text(
'최근검색',
style: TextStyle(
color: primaryColor50,
fontFamily: 'semi-bold',
fontSize: titleSmall,
),
),
),
),
),
// 관심매물버튼
GestureDetector(
onTap: () {},
child: Container(
decoration: BoxDecoration(
color: primaryColor20,
border: Border.all(
color: primaryColor20,
),
borderRadius: BorderRadius.all(
Radius.circular(12.0),
),
),
height: 48,
width: MediaQuery.of(context).size.width * 0.435,
child: Center(
child: Text(
'관심매물',
style: TextStyle(
color: primaryColor50,
fontFamily: 'semi-bold',
fontSize: titleSmall,
),
),
),
),
),
],
),
marginHeight22,
// 광고영역
Container(
decoration: BoxDecoration(
color: primaryColor30,
borderRadius: BorderRadius.all(
Radius.circular(12.0),
),
),
height: 120,
width: MediaQuery.of(context).size.width,
child: Center(
child: Text(
'광고영역',
style: TextStyle(
fontSize: titleLarge,
color: baseColor10,
),
),
),
),
marginHeight22,
// 선박판매 버튼
Container(
decoration: BoxDecoration(
color: primaryColor50,
borderRadius: BorderRadius.all(
Radius.circular(12.0),
),
),
height: 48,
width: MediaQuery.of(context).size.width,
child: Center(
child: Text(
'내 선박 판매하기',
style: TextStyle(
fontSize: titleMedium,
fontFamily: 'semi-bold',
color: baseColor10,
),
),
),
),
marginHeight22,
// 선박매물검색, 허가, 부품
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
// This is the button to move the vessel_screeen.dart
GestureDetector(
onTap: (){
Get.to(() => VesselScreen());
},
child: Container(
decoration: BoxDecoration(
color: baseColor10,
borderRadius: BorderRadius.all(
Radius.circular(12.0),
),
),
height: 196,
width: MediaQuery.of(context).size.width * 0.435,
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'선박매물',
style: TextStyle(
fontSize: titleLarge,
fontFamily: 'semi-bold',
color: baseColor50,
),
),
marginHeight4,
Text(
'검색하러가기',
style: TextStyle(
fontSize: bodyLarge,
fontFamily: 'regular',
color: baseColor50,
),
),
],
),
),
),
),
Column(
children: [
// 어업 허가
Container(
decoration: BoxDecoration(
color: baseColor10,
borderRadius: BorderRadius.all(
Radius.circular(12.0),
),
),
height: 90,
width: MediaQuery.of(context).size.width * 0.435,
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'어업허가',
style: TextStyle(
fontSize: titleLarge,
fontFamily: 'semi-bold',
color: baseColor50,
),
),
marginHeight4,
Text(
'매매',
style: TextStyle(
fontSize: bodyLarge,
fontFamily: 'regular',
),
)
],
),
),
),
marginHeight16,
Container(
decoration: BoxDecoration(
color: baseColor10,
borderRadius: BorderRadius.all(
Radius.circular(12.0),
),
),
height: 90,
width: MediaQuery.of(context).size.width * 0.435,
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'부품',
style: TextStyle(
fontSize: titleLarge,
fontFamily: 'semi-bold',
color: baseColor50,
),
),
marginHeight4,
Text(
'중고부품거래',
style: TextStyle(
fontSize: bodyLarge,
fontFamily: 'regular',
),
)
],
),
),
),
],
),
],
),
marginHeight22,
// 내 선박 등록하기
Container(
decoration: BoxDecoration(
color: baseColor10,
borderRadius: BorderRadius.all(
Radius.circular(12.0),
),
),
height: 132,
width: MediaQuery.of(context).size.width,
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'어선번호 입력하고 선박관리 한 번에!',
style: TextStyle(
fontSize: titleMedium,
color: baseColor50,
fontFamily: 'semi-bold',
),
),
marginHeight16,
Container(
decoration: BoxDecoration(
color: baseColor10,
border: Border.all(
color: primaryColor50,
),
borderRadius: BorderRadius.all(
Radius.circular(12.0),
),
),
height: 48,
width: MediaQuery.of(context).size.width * 0.75,
child: Center(
child: Text(
'내 선박 등록하기',
style: TextStyle(
fontSize: titleMedium,
fontFamily: 'semi-bold',
color: primaryColor50,
),
),
),
),
],
),
),
),
],
),
),
),
);
}
}
</code></pre>
<p>Here is the <code>vessel_screen.dart</code></p>
<pre><code>import 'package:flutter/material.dart';
import 'package:shipda/constants.dart';
import 'package:shipda/screens/vessel_screen/fishing_vessel/fishing_vessel_screen.dart';
import 'package:shipda/screens/vessel_screen/leisure_vessel/leisure_vessel_screen.dart';
import 'package:shipda/screens/vessel_screen/other_vessel/other_vessel_screen.dart';
class VesselScreen extends StatelessWidget {
const VesselScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return DefaultTabController(
length: 3,
child: Scaffold(
appBar: TabBar(
indicatorColor: informationColor50,
labelStyle: TextStyle(
fontSize: titleMedium,
fontFamily: 'semi-bold',
),
unselectedLabelColor: primaryColor50,
labelColor: informationColor50,
tabs: [
Tab(text: '어선'),
Tab(text: '레저선'),
Tab(text: '특수선/기타선'),
],
),
body: TabBarView(
children: [
FishingVesselScreen(),
LeisureVesselScreen(),
OtherVesselScreen(),
],
),
),
);
}
}
</code></pre>
<p><a href="https://i.stack.imgur.com/zvhH6.png" rel="nofollow noreferrer">original</a>
<a href="https://i.stack.imgur.com/yxbt5.png" rel="nofollow noreferrer">missing appear and bottomnavbar</a></p>
|
[
{
"answer_id": 74556288,
"author": "walieeldin",
"author_id": 14979656,
"author_profile": "https://Stackoverflow.com/users/14979656",
"pm_score": -1,
"selected": false,
"text": "function mostFrequentItemCount(collection){\n \ncollection.sort((a,b) => a - b)\n let a, b, c , d = 0; \n for (i=0; i<collection.length; i++){\n if (collection[i] == collection[i-1]){\n b = a = a + 1;\n if (b>(c && d)){c=i; d=b}\n } else {b=a; a=1}\n } console.log(d)\n\n} console.log(mostFrequentItemCount([3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3]))\n"
},
{
"answer_id": 74556308,
"author": "Abirami Balasubramaniyan",
"author_id": 5755531,
"author_profile": "https://Stackoverflow.com/users/5755531",
"pm_score": 0,
"selected": false,
"text": "console.log(mostFrequentItemCount([3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3])).\n"
},
{
"answer_id": 74556463,
"author": "Suresh Ponnukalai",
"author_id": 3607064,
"author_profile": "https://Stackoverflow.com/users/3607064",
"pm_score": 0,
"selected": false,
"text": "5 console.log undefined console.log function mostFrequentItemCount(collection){\n let a, b, c = 0, d = 0; \n collection.sort((a,b) => a - b)\n \n for (i=0; i<collection.length; i++){\n if (collection[i] == collection[i-1]){\n b = a = a + 1;\n if (b>(c && d)){c = i; d = b}\n } else {b = a; a = 1}\n } console.log(d) // This is showing the expected output\n \n return d; //This will return the value to where the function called\n} \n\nconsole.log(mostFrequentItemCount([3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3]))"
},
{
"answer_id": 74556800,
"author": "Mexo",
"author_id": 20587652,
"author_profile": "https://Stackoverflow.com/users/20587652",
"pm_score": -1,
"selected": false,
"text": "function mostFrequentItemCount(collection){\n\nif(collection.length == 0) return 0\n\nelse{ let a, b, c = 1; \ncollection.sort((a,b) => a - b)\n\nfor (i=0; i<collection.length; i++){\n if (collection[i] == collection[i-1]){\n b = a = a + 1;\n if (b >= c){c = b}\n } else {b = a; a = 1}\n} return c }}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19443112/"
] |
74,556,391
|
<p>I have a column named data and I have to update its content from something like <code>{}</code> to <code>[{}]</code> for each record in table <em><strong>A</strong></em>, I tried to use <strong>JSON_ARRAY()</strong> but it gives me a quoted</p>
<pre class="lang-json prettyprint-override"><code>["{\"something\": \"true\"}"]
</code></pre>
<p>but I'd like to have something like</p>
<pre class="lang-json prettyprint-override"><code>[{ "something": "true" }]
</code></pre>
<p>How I do it now?</p>
<pre class="lang-sql prettyprint-override"><code>SELECT JSON_ARRAY(data) FROM A;
</code></pre>
<p>How should I update it either using <code>JSON_SET()</code> or <code>UPDATE</code>?</p>
|
[
{
"answer_id": 74556440,
"author": "Barmar",
"author_id": 1491895,
"author_profile": "https://Stackoverflow.com/users/1491895",
"pm_score": 1,
"selected": false,
"text": "$ update A \nSET data = CASE\n WHEN data IS NULL THEN '[]' -- NULL becomes empty array\n WHEN LEFT(data, 1) = '[' THEN data -- leave existing array alone\n ELSE JSON_ARRAY(data->\"$\") -- put object inside array\nEND\n"
},
{
"answer_id": 74556554,
"author": "EWW",
"author_id": 20587602,
"author_profile": "https://Stackoverflow.com/users/20587602",
"pm_score": 0,
"selected": false,
"text": "SELECT JSON_ARRAY_AGG(JSON_OBJECT(data)) from A;\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20587905/"
] |
74,556,392
|
<p>I have an abstract class that looks like this:</p>
<pre class="lang-java prettyprint-override"><code>abstract class Handler<T> {
Handler(Class<T> clazz) {
// ...
}
abstract void handle(T object);
}
</code></pre>
<p>I'm trying to extent it, where <code>T</code> is a type with a wildcard generic parameter (for the sake of the example, say <code>List<?></code>). What I want to be able to do is something like:</p>
<pre class="lang-java prettyprint-override"><code>class MyHandler extends Handler<List<?>> {
MyHandler() {
super(List.class);
// ^ Compiler error: The constructor Handler<List<?>>(Class<List>) is undefined
// super(List<?>.class); is also a compiler error
}
void handle(List<?> object) {
// ...
}
}
</code></pre>
<p>As far as I can tell the above is totally safe, so I'm not sure why the compiler doesn't allow it. My current solution involves the use of raw types, unsafe casting and suppression of the warnings and seems like it can't be solution the language intends me to use:</p>
<pre class="lang-java prettyprint-override"><code>class MyHandler extends Handler<List> { // Warning: List is a raw type
MyHandler() {
super(List.class);
}
void handle(List objectRaw) { // Warning: List is a raw type
List<?> object = (List<?>) objectRaw;
// ...
}
}
</code></pre>
<p>This needs to be a singleton so I can't add generic parameters to <code>MyHandler</code>. How do I avoid all these bad practices (raw types and the cast)? Theres no reason this should be unsafe and I'm having a hard time believing there's no way to do this in Java.</p>
|
[
{
"answer_id": 74556440,
"author": "Barmar",
"author_id": 1491895,
"author_profile": "https://Stackoverflow.com/users/1491895",
"pm_score": 1,
"selected": false,
"text": "$ update A \nSET data = CASE\n WHEN data IS NULL THEN '[]' -- NULL becomes empty array\n WHEN LEFT(data, 1) = '[' THEN data -- leave existing array alone\n ELSE JSON_ARRAY(data->\"$\") -- put object inside array\nEND\n"
},
{
"answer_id": 74556554,
"author": "EWW",
"author_id": 20587602,
"author_profile": "https://Stackoverflow.com/users/20587602",
"pm_score": 0,
"selected": false,
"text": "SELECT JSON_ARRAY_AGG(JSON_OBJECT(data)) from A;\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556392",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8448397/"
] |
74,556,434
|
<p>If i send messages locally from the same system than the boost server receives messages properly.</p>
<p>When the client is a remote application on other system and sending messages through TCP\IP than randomly some messages break(Line Enter).</p>
<p>Like if the client has sent "THIS IS A MESSAGE" the server will read it as</p>
<p>"THIS IS A ME</p>
<p>SSAGE"</p>
<p>This is the Server class.</p>
<pre><code>#pragma once
#include <boost/asio/io_context.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/spawn.hpp>
#include <boost/asio/steady_timer.hpp>
#include <boost/asio/write.hpp>
#include <iostream>
#include <global.h>
#include <memory>
#include <fstream>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <memory>
#include <queue>
using boost::asio::ip::tcp;
class session
: public std::enable_shared_from_this<session>
{
public:
session(tcp::socket socket)
: socket_(std::move(socket))
{
}
void start()
{
auto self(shared_from_this());
// dispatch not strictly necessary for single-threaded contexts
dispatch(
socket_.get_executor(),
[this, self]
{
do_read();
});
}
private:
void handleCommand()
{
enqueueAnswer();
}
void enqueueAnswer()
{
if (stdqueAnswers.size() == 1)
{
do_write();
}
}
void do_read()
{
auto self(shared_from_this());
socket_.async_read_some(boost::asio::buffer(data_, max_length),
[this, self](boost::system::error_code ec, std::size_t length)
{
if (!ec)
{
if (length > 0) {
// In case the message has a leading 1 than we have to send a answer back to the client.
if (data_[0] == '1') {
std::string stdstrCmd(data_);
stdstrCmd.erase(0, 2);
wavefrontAccess->ReceiveCommandExternalGet(stdstrCmd);
handleCommand();
}
else
{
std::string strData(data_, length);
if(!strData.empty() || strData.find_first_not_of(' ') != std::string::npos)
{
// There's a non-space.
commandsQueue.push(strData); // this is std Queue
}
}
}
do_read();
}
});
}
void do_write()
{
if (stdqueAnswers.empty())
return;
auto self(shared_from_this());
async_write(
socket_,
boost::asio::buffer(stdqueAnswers.front()),
[this, self](boost::system::error_code ec, size_t)
{
if (!ec)
{
stdqueAnswers.pop();
do_write();
}
});
}
tcp::socket socket_;
enum { max_length = 12000 };
char data_[max_length];
};
class server
{
public:
server(boost::asio::io_context& io_context, std::uint16_t port)
: acceptor_{ io_context, tcp::endpoint(tcp::v4(), port) }
{
acceptor_.listen();
do_accept();
}
private:
void do_accept()
{
acceptor_.async_accept(
make_strand(acceptor_.get_executor()),
[this](boost::system::error_code ec, tcp::socket socket)
{
if (!ec)
{
std::make_shared<session>(std::move(socket))->start();
do_accept();
}
});
}
tcp::acceptor acceptor_;
};
</code></pre>
|
[
{
"answer_id": 74556440,
"author": "Barmar",
"author_id": 1491895,
"author_profile": "https://Stackoverflow.com/users/1491895",
"pm_score": 1,
"selected": false,
"text": "$ update A \nSET data = CASE\n WHEN data IS NULL THEN '[]' -- NULL becomes empty array\n WHEN LEFT(data, 1) = '[' THEN data -- leave existing array alone\n ELSE JSON_ARRAY(data->\"$\") -- put object inside array\nEND\n"
},
{
"answer_id": 74556554,
"author": "EWW",
"author_id": 20587602,
"author_profile": "https://Stackoverflow.com/users/20587602",
"pm_score": 0,
"selected": false,
"text": "SELECT JSON_ARRAY_AGG(JSON_OBJECT(data)) from A;\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12651320/"
] |
74,556,437
|
<p>The question is how to sort the letter in alphabetic order based on the input in a HTML input tag, then clicks a button to sort it, after click the button the input will move to a text area and is already sorted when button is click, so that button need to have the insert function and sorting function, now the input can be insert to the textarea but not sorted, thanks.
Example of input:
andwe
output:
adenw</p>
<p>i want to define my input as an element, and write onclick="sortstring(element of my input)" in button, but i dont know how to define and dont have a sort function yet.</p>
|
[
{
"answer_id": 74556440,
"author": "Barmar",
"author_id": 1491895,
"author_profile": "https://Stackoverflow.com/users/1491895",
"pm_score": 1,
"selected": false,
"text": "$ update A \nSET data = CASE\n WHEN data IS NULL THEN '[]' -- NULL becomes empty array\n WHEN LEFT(data, 1) = '[' THEN data -- leave existing array alone\n ELSE JSON_ARRAY(data->\"$\") -- put object inside array\nEND\n"
},
{
"answer_id": 74556554,
"author": "EWW",
"author_id": 20587602,
"author_profile": "https://Stackoverflow.com/users/20587602",
"pm_score": 0,
"selected": false,
"text": "SELECT JSON_ARRAY_AGG(JSON_OBJECT(data)) from A;\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18908496/"
] |
74,556,477
|
<p>Need to get record of current month but query return the wrong result.There is only one record in db.but i get wrong count for the current month</p>
<pre><code>$data = UserData::select(
DB::raw("count(phone) as total")
)
->whereMonth('creation_date', Carbon::now()->month)
->get();
return view('kpidata', compact('data'));
</code></pre>
<p>this is result of mysql query
<a href="https://i.stack.imgur.com/LgYSu.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>and this is the result i get using laravel query<a href="https://i.stack.imgur.com/AuL8h.png" rel="nofollow noreferrer">enter image description here</a></p>
|
[
{
"answer_id": 74556580,
"author": "Heroherm",
"author_id": 20461089,
"author_profile": "https://Stackoverflow.com/users/20461089",
"pm_score": 1,
"selected": false,
"text": "UserData:select(DB::raw(\"count(phone) as total\"))\n ->whereBetween('creation_date', \n [\n Carbon::now()->startOfMonth(), \n Carbon::now()->endOfMonth()\n ])\n ->get();\n UserData:select(DB::raw(\"count(phone) as total\"))\n ->whereYear('creation_date', Carbon::now()->year)\n ->whereMonth('creation_date', Carbon::now()->month)\n ->get();\n"
},
{
"answer_id": 74556877,
"author": "EWW",
"author_id": 20587602,
"author_profile": "https://Stackoverflow.com/users/20587602",
"pm_score": 0,
"selected": false,
"text": "$data = Item::select('*')\n ->whereMonth('created_at', Carbon::now()->month)\n ->get();\n \nprint_r($data);\n"
},
{
"answer_id": 74557161,
"author": "kapitan",
"author_id": 2503592,
"author_profile": "https://Stackoverflow.com/users/2503592",
"pm_score": 0,
"selected": false,
"text": "whereMonth $data = UserData::whereMonth('creation_date', Carbon::now())->get();\n\nreturn view('kpidata', compact('data'));\n $data = UserData::whereMonth('creation_date', Carbon::now())->count();\n"
},
{
"answer_id": 74559958,
"author": "nnichols",
"author_id": 1191247,
"author_profile": "https://Stackoverflow.com/users/1191247",
"pm_score": 0,
"selected": false,
"text": "whereMonth() $data = UserData::select(\n DB::raw(\"count(phone) as total\")\n)\n ->whereMonth('creation_date', Carbon::now()->month)\n ->get();\n select count(phone) as total\nfrom users\nwhere month(creation_date) = :month\n month() creation_date creation_date whereBetween() $data = UserData::selectRaw('count(phone) as total')\n ->whereBetween('creation_date',\n [\n Carbon::now()->startOfMonth()->format('Y-m-d'),\n Carbon::now()->endOfMonth()->format('Y-m-d')\n ]\n )\n ->get();\n select count(phone) as total\nfrom users\nwhere creation_date between :start and :end\n ->dd() ->get()"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19124962/"
] |
74,556,481
|
<p>In the following C++ code, a template placeholder in argument of function <code>fun1</code>, and in the return type of function <code>ret1</code>, does not compile:</p>
<pre><code>template <typename T = int>
class type {
T data;
};
void fun1(type arg); // Error: template placeholder not permitted in this context
void fun2(type<> arg); // Ok
void fun3(type<int> arg); // Ok
type ret1(); // Error: Deduced class type 'type' in function return type
type<> ret2(); // Ok
type<int> ret3(); // Ok
int main() {
type var1; // Ok!!!!!!
type<> var2; // Ok
type<int> var3; // Ok
}
</code></pre>
<p>But, <code>var1</code> is ok.</p>
<ul>
<li>Why does <code>var1</code> compile, but <code>fun1</code> and <code>ret1</code> do not?</li>
<li>Is there any logic behind this inconsistent behavior between function declarations and variable declarations?</li>
</ul>
|
[
{
"answer_id": 74556567,
"author": "bitmask",
"author_id": 430766,
"author_profile": "https://Stackoverflow.com/users/430766",
"pm_score": 4,
"selected": true,
"text": "var1"
},
{
"answer_id": 74556568,
"author": "user17732522",
"author_id": 17732522,
"author_profile": "https://Stackoverflow.com/users/17732522",
"pm_score": 2,
"selected": false,
"text": "type var1; auto"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5688911/"
] |
74,556,487
|
<p>I am trying to automate the azure resource deployment using powershell.</p>
<p>Requirments : In a particular resource group(RG), there are multiple VMs. the naming convention are like,</p>
<p>XXX-XX-X-XXXXXX-VM-01,</p>
<p>XXX-XX-X-XXXXXX-VM-02,</p>
<p>XXX-XX-X-XXXXXX-VM-03.</p>
<p>I am trying to create a script which will look for the last sequence(is this case 03) and deploy the next VM with next sequence(here it should be 04).</p>
<p>I have the script to deploy the VM using powershell. Need help to fix the sequence logic.</p>
|
[
{
"answer_id": 74556567,
"author": "bitmask",
"author_id": 430766,
"author_profile": "https://Stackoverflow.com/users/430766",
"pm_score": 4,
"selected": true,
"text": "var1"
},
{
"answer_id": 74556568,
"author": "user17732522",
"author_id": 17732522,
"author_profile": "https://Stackoverflow.com/users/17732522",
"pm_score": 2,
"selected": false,
"text": "type var1; auto"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20587917/"
] |
74,556,503
|
<p>This is my table structure:</p>
<pre><code>PERSON (4.1 M rows)
id : UUID
notes: string
...
---
ATTRIBUTES (21 M rows)
id: UUID
person_id: <persons id> non null
name: ENUM : full_name | birthday | email | phone | photo
value: JSONB : {value:""} | { first_name:""} | {arbitrary schema based on `name`}
edited_value: JSONB : {value:""} | { first_name:""} | {arbitrary schema based on `name`}
...
---
1 Person -> N Attributes
</code></pre>
<p>So now the query response should look something like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>person_id</th>
<th>notes</th>
<th>attributes</th>
</tr>
</thead>
<tbody>
<tr>
<td>uuid</td>
<td>some stuff</td>
<td>[{a1},{a2}...(all attributes)]</td>
</tr>
<tr>
<td>uuid</td>
<td>some stuff</td>
<td>[{a1},{a2}...(all attributes)]</td>
</tr>
</tbody>
</table>
</div>
<p>The issue is I need to sort and filter the list based on certain conditions.</p>
<ol>
<li>Sort based on <code>ATTRIBUTE->edited_value</code>||<code>ATTRIBUTE->value</code> for particular <code>ATTRIBUTE->name</code>
<ul>
<li>like sort by first_name (so sort by rows in ATTRIBUTES where name=first_name)</li>
</ul>
</li>
<li>Filter by <code>Attributes -> name</code>
<ul>
<li>like GET all person who have a birthday (but the output <code>attributes</code> column should have all attributes)</li>
</ul>
</li>
</ol>
<p>My current query looks like this:</p>
<ol>
<li>To get all person with <code>birthday</code> and sort by their <code>first_name</code></li>
</ol>
<p>The query I have now looks like this but it takes 5 seconds to execute on local</p>
<pre><code>SELECT
p.id,
JSONB_AGG(a.*) as attributes,
FROM
person p
LEFT JOIN
"attribute" a ON a.person_id = p.id
AND a.deleted is false
LEFT JOIN
"attribute" ba ON ba.name = 'birthday'
AND ba.person_id = p.id
AND ba.deleted is false
LEFT JOIN
"attribute" fa ON fa.name = 'full_name'
AND fa.person_id = p.id
AND fa.deleted is false
WHERE
p.som_col_id = 'e046dd1d-3444-4195-9c46-e208b2a51703'
AND ba.id IS NOT NULL
AND p.deleted_at IS NULL
GROUP BY
p.id
ORDER BY
LOWER(MAX(COALESCE(fa.edited_value, fa.value)->>'first_name')) ASC NULLS LAST
</code></pre>
<p>I have an index on almost all the columns on the where clause except <code>attribute.deleted</code>.</p>
<p>From the explain plan, the sort seems to be taking a lot of time</p>
<pre><code>Sort (cost=46184.33..46185.19 rows=344 width=80) (actual time=284.351..284.604 rows=115 loops=1) |
Sort Key: (lower(max((COALESCE(fa.edited_value, fa.value) ->> 'first_name'::text)))) |
Sort Method: quicksort Memory: 1750kB |
Buffers: shared hit=7685 read=29921, temp read=314 written=315 |
-> GroupAggregate (cost=46159.52..46169.84 rows=344 width=80) (actual time=258.759..283.345 rows=115 loops=1) |
Group Key: p.id |
Buffers: shared hit=7685 read=29921, temp read=314 written=315 |
-> Sort (cost=46159.52..46160.38 rows=344 width=116) (actual time=258.709..261.751 rows=15967 loops=1) |
Sort Key: p.id |
Sort Method: external merge Disk: 2512kB |
Buffers: shared hit=7685 read=29921, temp read=314 written=315 |
-> Gather (cost=3553.65..46145.03 rows=344 width=116) (actual time=35.024..243.703 rows=15967 loops=1) |
Workers Planned: 2 |
Workers Launched: 2 |
Buffers: shared hit=7685 read=29921 |
-> Nested Loop Left Join (cost=2553.65..45110.63 rows=143 width=116) (actual time=19.666..108.066 rows=5322 loops=3) |
Buffers: shared hit=7685 read=29921 |
-> Nested Loop Left Join (cost=2553.23..41298.71 rows=52 width=80) (actual time=18.861..100.495 rows=38 loops=3) |
Buffers: shared hit=6341 read=29921 |
-> Parallel Hash Join (cost=2552.80..40360.76 rows=52 width=16) (actual time=18.794..99.999 rows=38 loops=3) |
Hash Cond: (ba.contact_id = p.id) |
Buffers: shared hit=5879 read=29921 |
-> Parallel Seq Scan on attribute ba (cost=0.00..37806.51 rows=554 width=16) (actual time=0.624..94.651 rows=1072 loops=3) |
Filter: ((deleted IS FALSE) AND (id IS NOT NULL) AND (name = 'birthday'::attribute_name)) |
Rows Removed by Filter: 177008 |
Buffers: shared hit=5103 read=29921 |
-> Parallel Hash (cost=2486.66..2486.66 rows=5291 width=16) (actual time=3.893..3.894 rows=776 loops=3) |
Buckets: 16384 Batches: 1 Memory Usage: 256kB |
Buffers: shared hit=692 |
-> Parallel Bitmap Heap Scan on contact p (cost=504.00..2486.66 rows=5291 width=16) (actual time=1.132..10.831 rows=2329 loops=1) |
Recheck Cond: (user_id = 'e046dd1d-3444-4195-9c46-e208b2a51703'::uuid) |
Filter: (deleted_at IS NULL) |
Rows Removed by Filter: 9180 |
Heap Blocks: exact=568 |
Buffers: shared hit=692 |
-> Bitmap Index Scan on contact_user_id_index (cost=0.00..501.75 rows=11378 width=0) (actual time=1.014..1.014 rows=11526 loops=1) |
Index Cond: (user_id = 'e046dd1d-3444-4195-9c46-e208b2a51703'::uuid) |
Buffers: shared hit=120 |
-> Index Scan using attribute_contact_id_name_deleted_index on attribute fa (cost=0.42..17.97 rows=7 width=80) (actual time=0.011..0.011 rows=1 loops=115)|
Index Cond: ((contact_id = p.id) AND (name = 'full_name'::attribute_name) AND (deleted = false)) |
Buffers: shared hit=462 |
-> Index Scan using attribute_contact_id_name_deleted_index on attribute a (cost=0.42..59.95 rows=1336 width=52) (actual time=0.004..0.059 rows=139 loops=115) |
Index Cond: ((contact_id = p.id) AND (deleted = false)) |
Buffers: shared hit=1344 |
Planning Time: 0.467 ms |
Execution Time: 285.484 ms |
</code></pre>
<p>Can you guys give me any suggestion regarding the improvemnets i can do</p>
<p>Thanks</p>
<p>Edit 1 : Updated Explain Plain with Analyze , buffers
Edit 2 : Updated the query to remove Ambiguity</p>
|
[
{
"answer_id": 74557008,
"author": "a_horse_with_no_name",
"author_id": 330315,
"author_profile": "https://Stackoverflow.com/users/330315",
"pm_score": 1,
"selected": false,
"text": "jsonb[] birthday SELECT p.id,\n a.attributes\nFROM person p\n LEFT JOIN ( \n select person_id, \n jsonb_object_agg(att.name, att.canonical_value)) as attributes,\n jsonb_object_agg(att.name, MAX(COALESCE(fa.edited_value, fa.value))) as attributes,\n from attribute att\n where att.deleted = false\n group by att.person_id \n ) a ON a.person_id = p.id\n LEFT JOIN \n \"attribute\" fa ON fa.name = 'full_name'\n AND fa.person_id = p.id\n AND fa.deleted is false\nWHERE p.som_col_id = 'e046dd1d-3444-4195-9c46-e208b2a51703'\n AND a.attributes ? 'birthday'\n AND p.deleted_at IS NULL\nORDER BY LOWER(MAX(COALESCE(fa.edited_value, fa.value)->>'first_name')) ASC NULLS LAST\n canonical_value value edited_value full_name SELECT p.id,\n a.attributes\nFROM person p\n LEFT JOIN ( \n select att.person_id, \n jsonb_object_agg(att.name, att.canonical_value) as attributes,\n jsonb_object_agg(att.name, COALESCE(att.edited_value, fa.value)) as real_values\n from attribute att\n where att.deleted = false\n group by att.person_id \n ) a ON a.person_id = p.id\nWHERE p.som_col_id = 'e046dd1d-3444-4195-9c46-e208b2a51703'\n AND attributes ? 'birthday'\n AND p.deleted_at IS NULL\nORDER BY LOWER(real_values ->> 'first_name') ASC NULLS LAST \n"
},
{
"answer_id": 74563174,
"author": "jjanes",
"author_id": 1721239,
"author_profile": "https://Stackoverflow.com/users/1721239",
"pm_score": 0,
"selected": false,
"text": "WHERE deleted is false"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11897377/"
] |
74,556,507
|
<p>I would like to ask for your help...</p>
<p>I have this string where I have to get the <strong>4.75</strong>. I've tried many regex expression but I could not get it to work and been through browsing lots of examples as well.</p>
<p><a href="https://i.stack.imgur.com/HsdCQ.png" rel="nofollow noreferrer">Regexr Image</a></p>
<pre><code>Loan Amount Interest Rate
$336,550 4.75 %
</code></pre>
<p>So far, below is my current expression</p>
<pre><code>1. (?<=Interest Rate\s*\n*)([^\s]+).+(?=%)
</code></pre>
<p>I'm getting the <strong>$336,550 4.75</strong></p>
<pre><code>2. ([^\s]+).(?=%)
</code></pre>
<p>Resulted into multiple output. In my entire text, which I can't share, there are also other data that is in %.</p>
<p>I am only after the 4.75. I know I can just select the first match via code (i guess) but for now it is not an option.</p>
<p>Thanks in advance!</p>
<p>I've tried different regex expression</p>
|
[
{
"answer_id": 74556645,
"author": "Rusty cole",
"author_id": 3636626,
"author_profile": "https://Stackoverflow.com/users/3636626",
"pm_score": 0,
"selected": false,
"text": "(?<=Interest Rate\\n\\n\\$\\d{3},\\d{3}\\s)(\\d{1,5}\\.\\d{1,5}\\s%)\n"
},
{
"answer_id": 74556658,
"author": "Suraj Mahendrakar",
"author_id": 20588006,
"author_profile": "https://Stackoverflow.com/users/20588006",
"pm_score": -1,
"selected": false,
"text": "[0-9]+.[0-9]+\n"
},
{
"answer_id": 74558050,
"author": "Wiktor Stribiżew",
"author_id": 3832970,
"author_profile": "https://Stackoverflow.com/users/3832970",
"pm_score": 0,
"selected": false,
"text": "(?<=Interest Rate\\s+\\S+\\s+)(\\S+)(?=\\s*%)\n (?<=Interest Rate\\s+\\S+\\s+) Interest Rate (\\S+) (?=\\s*%) %"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8665920/"
] |
74,556,522
|
<p>I want the function to return the string that follows the below condition.</p>
<ol>
<li>after "def"</li>
<li>in the parentheses right before the first %ile after "def"</li>
</ol>
<p>So the desirable output is "4", not "5". So far, I was able to extract "2)(3)(4". If I change the function to str_extract_all, the output became "2)(3)(4" and "5" . I couldn't figure out how to fix this problem. Thanks!</p>
<pre><code>x <- "abc(0)(1)%ile, def(2)(3)(4)%ile(5)%ile"
string.after.match <- str_match(string = x,
pattern = "(?<=def)(.*)")[1, 1]
parentheses.value <- str_extract(string.after.match, # get value in ()
"(?<=\\()(.*?)(?=\\)\\%ile)")
parentheses.value
</code></pre>
<p>Take the</p>
|
[
{
"answer_id": 74556784,
"author": "Josh White",
"author_id": 20289207,
"author_profile": "https://Stackoverflow.com/users/20289207",
"pm_score": 3,
"selected": true,
"text": "gsub() gsub(\".*def.*(\\\\d+)\\\\)%ile.*%ile\", \"\\\\1\", x, perl = TRUE)\n str_split() x <- \"abc(0)(1)%ile, def(2)(3)(4)%ile(5)%ile(9)%ile\"\nx %>% \n str_split(\"def\", simplify = TRUE) %>% \n subset(TRUE, 2) %>% \n str_split(\"%ile\", simplify = TRUE) %>% \n subset(TRUE, 1) %>% \n str_replace(\".*(\\\\d+)\\\\)$\", \"\\\\1\")\n"
},
{
"answer_id": 74556933,
"author": "onyambu",
"author_id": 8380272,
"author_profile": "https://Stackoverflow.com/users/8380272",
"pm_score": 2,
"selected": false,
"text": " sub(\".*?def.*?(\\\\d)\\\\)%ile.*\", \"\\\\1\", x)\n[1] \"4\"\n"
},
{
"answer_id": 74557711,
"author": "Wiktor Stribiżew",
"author_id": 3832970,
"author_profile": "https://Stackoverflow.com/users/3832970",
"pm_score": 1,
"selected": false,
"text": "x <- \"abc(0)(1)%ile, def(2)(3)(4)%ile(5)%ile\"\nlibrary(stringr)\nresult <- str_match(x, \"\\\\bdef(?:\\\\((\\\\d+)\\\\))+%ile\")\nresult[,2]\n \\b def def (?:\\((\\d+)\\))+ ( ) %ile %ile"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17237764/"
] |
74,556,539
|
<p>I have an excel workbook with 100s of sheets with tab named as strings (sheet1, R Import, etc.) and numeric (123, 456, etc.). But I want to import all the sheets for which the tab names are in numeric only. I have the following code to import all sheets but not sure how to import just the sheets with numeric tab names only:</p>
<pre><code>read_excel_allsheets <- function(filename) {
sheets <- readxl::excel_sheets(filename)
x <- lapply(sheets, function(X) readxl::read_excel(filename, sheet = X))
names(x) <- sheets
x
}
</code></pre>
<p>I want to perform this operation in R. Any help would be much appreciated. Thanks!</p>
|
[
{
"answer_id": 74556784,
"author": "Josh White",
"author_id": 20289207,
"author_profile": "https://Stackoverflow.com/users/20289207",
"pm_score": 3,
"selected": true,
"text": "gsub() gsub(\".*def.*(\\\\d+)\\\\)%ile.*%ile\", \"\\\\1\", x, perl = TRUE)\n str_split() x <- \"abc(0)(1)%ile, def(2)(3)(4)%ile(5)%ile(9)%ile\"\nx %>% \n str_split(\"def\", simplify = TRUE) %>% \n subset(TRUE, 2) %>% \n str_split(\"%ile\", simplify = TRUE) %>% \n subset(TRUE, 1) %>% \n str_replace(\".*(\\\\d+)\\\\)$\", \"\\\\1\")\n"
},
{
"answer_id": 74556933,
"author": "onyambu",
"author_id": 8380272,
"author_profile": "https://Stackoverflow.com/users/8380272",
"pm_score": 2,
"selected": false,
"text": " sub(\".*?def.*?(\\\\d)\\\\)%ile.*\", \"\\\\1\", x)\n[1] \"4\"\n"
},
{
"answer_id": 74557711,
"author": "Wiktor Stribiżew",
"author_id": 3832970,
"author_profile": "https://Stackoverflow.com/users/3832970",
"pm_score": 1,
"selected": false,
"text": "x <- \"abc(0)(1)%ile, def(2)(3)(4)%ile(5)%ile\"\nlibrary(stringr)\nresult <- str_match(x, \"\\\\bdef(?:\\\\((\\\\d+)\\\\))+%ile\")\nresult[,2]\n \\b def def (?:\\((\\d+)\\))+ ( ) %ile %ile"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556539",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19305713/"
] |
74,556,541
|
<p>i am not experienced working with docker and docker-compose, but atleast i know how to get a container running, below is my compose file of a simple react app boiler plate. my intention was to assign an IP to it so that i can ping it from the external network, and also to access it without any port mapping to the host</p>
<pre><code>version: "3.9"
services:
front-web:
build:
context: .
dockerfile: Dockerfile
args:
buildno: 1.0.0
container_name: web-front
domainname: fontend
dns: 8.8.8.8
network_mode: "host"
hostname: alpha
restart: unless-stopped
stop_grace_period: 1m
expose:
- 4000
tty: true
pid: host
stdin_open: true
ports:
- target: 4000
published: 4000
protocol: tcp
mode: host
networks:
web-net:
ipv4_address: 192.168.1.195
volumes:
- web-front:/app/data
networks:
web-net:
name: web-net
driver: bridge
driver_opts:
enable_ipv4: 1
enable_ipv6: 1
ipam:
driver: default
config:
- subnet: 192.168.1.1/24
ip_range: 192.168.1.195/24
gateway: 192.168.1.195/24
volumes:
web-front:
</code></pre>
<p>the docker file of the app is below</p>
<pre><code>FROM node:alpine3.16
# RUN addgroup app && adduser -SG app app
# USER app
WORKDIR /app
RUN mkdir data
EXPOSE 4000
COPY package* .
RUN npm install
COPY . .
CMD [ "npm", "start" ]
</code></pre>
<p>ignore the "adduser" although it also failed to workout. whenever i run docker-compose up, i get an error saying:</p>
<pre><code>Attaching to web-front
Error response from daemon: failed to add interface vethcf21a7d to sandbox: error setting interface "vethcf21a7d" IP to 192.168.1.195/24: cannot program address 192.168.1.195/24 in sandbox interface because it conflicts with existing route {Ifindex: 31 Dst: 192.168.1.0/24 Src: 192.168.1.1 Gw: <nil> Flags: [] Table: 254}
</code></pre>
<p>i am not sure how to go about this, kindly assist</p>
<p>I tried changing the driver part in the Networks section from brigde to macvlan, the build would pass but again i could not ping the the container with its ip. adding external:true, makes the whole thing fail</p>
|
[
{
"answer_id": 74556784,
"author": "Josh White",
"author_id": 20289207,
"author_profile": "https://Stackoverflow.com/users/20289207",
"pm_score": 3,
"selected": true,
"text": "gsub() gsub(\".*def.*(\\\\d+)\\\\)%ile.*%ile\", \"\\\\1\", x, perl = TRUE)\n str_split() x <- \"abc(0)(1)%ile, def(2)(3)(4)%ile(5)%ile(9)%ile\"\nx %>% \n str_split(\"def\", simplify = TRUE) %>% \n subset(TRUE, 2) %>% \n str_split(\"%ile\", simplify = TRUE) %>% \n subset(TRUE, 1) %>% \n str_replace(\".*(\\\\d+)\\\\)$\", \"\\\\1\")\n"
},
{
"answer_id": 74556933,
"author": "onyambu",
"author_id": 8380272,
"author_profile": "https://Stackoverflow.com/users/8380272",
"pm_score": 2,
"selected": false,
"text": " sub(\".*?def.*?(\\\\d)\\\\)%ile.*\", \"\\\\1\", x)\n[1] \"4\"\n"
},
{
"answer_id": 74557711,
"author": "Wiktor Stribiżew",
"author_id": 3832970,
"author_profile": "https://Stackoverflow.com/users/3832970",
"pm_score": 1,
"selected": false,
"text": "x <- \"abc(0)(1)%ile, def(2)(3)(4)%ile(5)%ile\"\nlibrary(stringr)\nresult <- str_match(x, \"\\\\bdef(?:\\\\((\\\\d+)\\\\))+%ile\")\nresult[,2]\n \\b def def (?:\\((\\d+)\\))+ ( ) %ile %ile"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20569584/"
] |
74,556,543
|
<p>Am displaying list haviing</p>
<pre><code>Date
News Heading
Short Descrption
</code></pre>
<p>The list is spread to around 100 pages, having 20 news in each page</p>
<p>Issue is: This is working absolute fine in php 7.3, 7.4 in joomla 3.10 where on clicking url - list is shown spread over multiple pages having sort by date wise as first criteria, latest date of publishing is coming</p>
<p>But when same used on php 8.0.x - its showing incorrectly, where on clicking URL - last page of list having page number 100 is shown first. Now when i add on limitstart=0 in url then its showing correctly as the first page.</p>
<p>Now when i change from descending to ascending - its bringing the content on last page and its opening, but page number is 100 again</p>
<p>Seems like URL when opened is directly taking to last page of news item as published (although no limitstart is mentioned in it), which is incorrect as ideally should open in descending order and open the page having latest one</p>
<p>Below is code of views/list/tmpl/default.php</p>
<pre><code>if(count($this->items) >0){
//$i=1;
foreach($this->items as $newslist)
{
$date = JFactory::getDate($newslist->n_date);
$list .='<h3><strong>'.$newslist->v_heading.'</strong></h3>
<p>'. $date->format('F j, Y').'</p>
<p>'.substr($newslist->v_short_description,0,100).'</p>
<p><i>Know More on:- </i><a href="index.php?option=com_news&view=detail&v_id='.$newslist->id.'&Itemid='.$Itemid.'"><b><i>'.$newslist->v_heading.'</i></b></a></p><hr/><br>';
//$i=$i+1;
}
}else{
JError::raiseError(404, "Message");
}
<?php echo $list?>
</code></pre>
<p>and for models/list.php this is the function</p>
<pre><code>protected function getListQuery()
{
// Create a new query object.
$db = $this->getDbo();
$query = $db->getQuery(true);
// Select the required fields from the table.
$query
->select(
$this->getState(
'list.select', 'DISTINCT a.*'
)
);
$query->from('`#__news` AS a');
if (!JFactory::getUser()->authorise('core.edit', 'com_news'))
{
$query->where('a.state = 1');
}
// Filter by search in title
$search = $this->getState('filter.search');
if (!empty($search))
{
if (stripos($search, 'id:') === 0)
{
$query->where('a.id = ' . (int) substr($search, 3));
}
else
{
$search = $db->Quote('%' . $db->escape($search, true) . '%');
$query->where('( a.n_heading LIKE ' . $search . ' )');
}
}
/*
// Add the list ordering clause.
$orderCol = $this->state->get('list.ordering');
$orderDirn = $this->state->get('list.direction');
if ($orderCol && $orderDirn)
{
$query->order($db->escape($orderCol . ' ' . $orderDirn));
}
*/ //Order by date
$query->order ('a.n_date DESC');
$query->order ('a.id DESC');
return $query;
}
</code></pre>
<p>This is the code for views/list/view.html.php</p>
<pre><code>public function display($tpl = null)
{
$app = JFactory::getApplication();
$this->state = $this->get('State');
$this->items = $this->get('Items');
$this->pagination = $this->get('Pagination');
$this->params = $app->getParams('com_news');
$this->filterForm = $this->get('FilterForm');
$this->activeFilters = $this->get('ActiveFilters');
// Check for errors.
if (count($errors = $this->get('Errors')))
{
throw new Exception(implode("\n", $errors));
}
$this->_prepareDocument();
parent::display($tpl);
}
</code></pre>
<p>Unsure how to achieve in and why its not working in php 8.0 where url should open the 1st page and not last page</p>
|
[
{
"answer_id": 74656911,
"author": "cyberpunk_unicorn",
"author_id": 20666543,
"author_profile": "https://Stackoverflow.com/users/20666543",
"pm_score": 0,
"selected": false,
"text": "$query->order('a.n_date DESC');\n $query->order('a.n_date DESC, a.id DESC');\n"
},
{
"answer_id": 74666445,
"author": "Begging",
"author_id": 16606223,
"author_profile": "https://Stackoverflow.com/users/16606223",
"pm_score": 0,
"selected": false,
"text": "$query->order ('a.n_date DESC, a.id DESC');\n n_date n_date JFactory::getDate $newslist->n_date"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2259881/"
] |
74,556,545
|
<p>When I use JAVA 8,String is saved with char[],so if i write like follow
String test = "a";
i think <code>a</code> is one element in char[],
as we know,char occupied 2byte in JAVA,so i think test.getBytes().length may be 2 but 1</p>
<pre><code>String test = "a";
System.out.println(test.getBytes().length);
char c = 'c';
System.out.println(charToByte(c).length);
</code></pre>
<h2>result is</h2>
<h2>1
2</h2>
<p>letter occupied 1byte as we know,but <code>a</code> is saved as one element in char[],char occupied 2byte
so i wonder where did i misunderstand</p>
|
[
{
"answer_id": 74557449,
"author": "Joop Eggen",
"author_id": 984823,
"author_profile": "https://Stackoverflow.com/users/984823",
"pm_score": 3,
"selected": true,
"text": "String char char char String byte]} Charset Charset charset = Charset.defaultCharset();\nbyte[] b = s.getBytes(cjarset);\nString s = new String(b, charset);\n \"ruĝa\" char String char byte public static int bytesInMemory(String s) {\n return s.getBytes(StandardCharsets.UTF_16).length;\n}\n é e"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16632481/"
] |
74,556,598
|
<p><strong>Code</strong></p>
<pre><code> public class main {
public static void main(String[] args) {
System.out.println(1101101101*10);
}
}
</code></pre>
<p><strong>OUTPUT</strong></p>
<pre><code>-1873890878
</code></pre>
<p><a href="https://i.stack.imgur.com/IpxpT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IpxpT.png" alt="calci" /></a></p>
<p>I do the same thing in python it gives the output.</p>
<pre><code> Microsoft Windows [Version 10.0.19044.2251]
(c) Microsoft Corporation. All rights reserved.
C:\Users\pradeep>python
Python 3.10.8 (tags/v3.10.8:aaaf517, Oct 11 2022, 16:50:30) [MSC v.1933 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 1101101101*10
11011011010
</code></pre>
<p>How can I solve this in java ?</p>
|
[
{
"answer_id": 74556673,
"author": "Abirami Balasubramaniyan",
"author_id": 5755531,
"author_profile": "https://Stackoverflow.com/users/5755531",
"pm_score": 1,
"selected": false,
"text": " public static void main(String[] args) {\n\n Long longVal = 1101101101l;\n System.out.println(longVal*10);\n}\n"
},
{
"answer_id": 74556714,
"author": "Tan Sang",
"author_id": 10297961,
"author_profile": "https://Stackoverflow.com/users/10297961",
"pm_score": 2,
"selected": false,
"text": "1101101101 10 Numeric overflow in expression"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10870644/"
] |
74,556,605
|
<p>I have a data set as below</p>
<pre><code>
tmp_dict = {
'a': ?,
'b': ?,
'c': ?,
}
</code></pre>
<p>and I have a data is a list of dictionaries like</p>
<pre><code>tmp_list = [tmp_dict1, tmp_dict2, tmp_dict3....]
</code></pre>
<p>and I found some of dictionaries are not perfectly have keys about 'a','b','c'.</p>
<p>How do I check and fill the key is not existing</p>
|
[
{
"answer_id": 74556725,
"author": "ScottC",
"author_id": 20174226,
"author_profile": "https://Stackoverflow.com/users/20174226",
"pm_score": 1,
"selected": false,
"text": "# List of keys to look for in each dictionary\ndict_keys = ['a','b','c']\n\n# Generate the dictionaries for demonstration purposes only\ntmp_dict1 = {'a':[1,2,3], 'b':[4,5,6]}\ntmp_dict2 = {'a':[7,8,9], 'b':[10,11,12], 'c':[13,14,15]}\ntmp_dict3 = {'a':[16,17,18], 'c':[19,20,21]}\n\n# Add the dictionaries to a list as per OP instructions\ntmp_list = [tmp_dict1, tmp_dict2, tmp_dict3]\n\n#--------------------------------------------------------\n# Check for missing keys in each dict. \n# Print the dict name and keys missing.\n# -------------------------------------------------------\nfor i, dct in enumerate(tmp_list, start=1):\n for k in dict_keys:\n if dct.get(k) == None:\n print(f\"tmp_dict{i} is missing key:\", k)\n tmp_dict1 is missing key: c\ntmp_dict3 is missing key: b\n"
},
{
"answer_id": 74556742,
"author": "Barmar",
"author_id": 1491895,
"author_profile": "https://Stackoverflow.com/users/1491895",
"pm_score": 0,
"selected": false,
"text": "for d in tmp_list:\n if set(d) != {'a', 'b', 'c'}:\n print(d)\n"
},
{
"answer_id": 74556764,
"author": "Syrenthia",
"author_id": 3944303,
"author_profile": "https://Stackoverflow.com/users/3944303",
"pm_score": 1,
"selected": true,
"text": "tmp_dict = {'a':1, 'b': 2, 'c':3}\ndefault_keys = tmp_dict.keys()\ntmp_list = [{'a': 1}, {'b': 2,}, {'c': 3}]\n\nfor t in tmp_list:\n current_dict = t.keys()\n if default_keys - current_dict:\n t.update({diff: None for diff in list(default_keys-current_dict)})\nprint(tmp_list)\n [{'a': 1, 'c': None, 'b': None}, {'b': 2, 'a': None, 'c': None}, {'c': 3, 'a': None, 'b': None}]\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11684420/"
] |
74,556,614
|
<p>I was trying to use getline for user input and I manage to do so but each time I try to print everything after %s (like .) it gets put to the next line and I am also trying to get rid of trailing space characters input so I use the function below but for some reason this isn't working, any help, sorry for anything improper still learning:</p>
<p>Also can I print the contents of buff like an ordinary array (for loop) or is it different if I use getline?</p>
<pre><code>/******************************************************************************
*******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int trim (char *s)
{
int i = strlen(s) - 1;
while (i > 0){
if (s[i] == ' '|| s[i] == '0'){
i--;
}
else {
break;
}
}
s[i + 1] = '\0';
printf("%d\n", i);
return (strlen(s));
}
int main()
{
char *buff = NULL;
size_t sizeAllocated = 0;
printf("Begining!!\n");
printf("> ");
size_t numCh = getline(&buff, &sizeAllocated, stdin);
//numCh = trim(buff);
printf("%s.", buff);
free (buff);
buff = NULL;
return 0;
}
</code></pre>
<p>Thank you in advance for any help</p>
|
[
{
"answer_id": 74556920,
"author": "P.P",
"author_id": 1275169,
"author_profile": "https://Stackoverflow.com/users/1275169",
"pm_score": 0,
"selected": false,
"text": "getline \\n isspace trim int trim (char *s)\n{\n size_t i = strlen(s);\n if (i == 0) return 0;\n while(isspace((unsigned char)s[i-1])) {\n i--;\n }\n s[i] = '\\0';\n return i; \n}\n strlen size_t i int size_t"
},
{
"answer_id": 74556978,
"author": "David Ranieri",
"author_id": 1606345,
"author_profile": "https://Stackoverflow.com/users/1606345",
"pm_score": 2,
"selected": true,
"text": "numCh ssize_t getline int i = strlen(s) - 1; strlen unsigned size_t SIZE_MAX #define _POSIX_C_SOURCE 200809L\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <sys/types.h>\n\nstatic char *trim(char *str)\n{\n while (*str && isspace((unsigned char)*str))\n {\n str++;\n }\n if (*str)\n {\n // Here it is safe to use `strlen - 1` because\n // `if (*str)` ensures that there is a character\n char *end = str + strlen(str) - 1;\n\n while (*end && isspace((unsigned char)*end))\n {\n end--;\n }\n *(end + 1) = '\\0';\n }\n return str;\n}\n\nint main(void)\n{\n char *str = NULL;\n size_t size = 0;\n ssize_t len = 0;\n\n if ((len = getline(&str, &size, stdin)) != -1)\n {\n const char *trimmed = trim(str);\n\n printf(\"<%s>\\n\", trimmed); // Use trimmed\n }\n free(str);\n return 0;\n}\n"
},
{
"answer_id": 74558129,
"author": "David C. Rankin",
"author_id": 3422102,
"author_profile": "https://Stackoverflow.com/users/3422102",
"pm_score": 1,
"selected": false,
"text": "numCh ssize_t getline() strlen(s) - 1 strlen(s) 0 '\\n' string.h strcspn() '\\n' '\\n' strlen(s) - 1 strcspn() trim() size_t trim (char *s)\n{\n size_t len; /* length of s after trailing whitespace trimmed */\n \n s[(len = strcspn (s, \"\\n\"))] = 0; /* trim \\n saving length */\n \n /* trim remaining whitespace */\n while (len && isspace ((unsigned char)s[len - 1])) {\n len--;\n }\n s[len] = 0; /* nul-terminate at len */\n \n return len; /* return new len */\n}\n ctype.h unsigned char stdin printf() fputs() buff trim() #include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n\nsize_t trim (char *s)\n{\n size_t len; /* length of s after trailing whitespace trimmed */\n \n s[(len = strcspn (s, \"\\n\"))] = 0; /* trim \\n saving length */\n \n /* trim remaining whitespace */\n while (len && isspace ((unsigned char)s[len - 1])) {\n len--;\n }\n s[len] = 0; /* nul-terminate at len */\n \n return len; /* return new len */\n}\n\nint main()\n{\n char *buff = NULL;\n size_t sizeAllocated = 0;\n ssize_t numCh = 0;\n \n fputs (\"Begining!!\\n> \", stdout); /* no conversion, fputs() is fine */\n \n /* validate EVERY input function */\n if ((numCh = getline(&buff, &sizeAllocated, stdin)) == -1) {\n fputs (\"error: during getline read.\\n\", stderr);\n return 1;\n }\n \n printf (\"buff '%s' (numCh: %zu)\\n\", buff, numCh);\n numCh = trim (buff);\n printf (\"\\nbuff '%s' (numCh: %zu)\\n\", buff, numCh);\n \n free (buff);\n}\n $ ./bin/getline-trimws\nBegining!!\n> my dog has fleas\nbuff 'my dog has fleas\n' (numCh: 29)\n\nbuff 'my dog has fleas' (numCh: 18)\n $ ./bin/getline-trimws\nBegining!!\n>\nbuff '\n' (numCh: 1)\n\nbuff '' (numCh: 0)\n EOF $ ./bin/getline-trimws\nBegining!!\n> error: during getline read.\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20550841/"
] |
74,556,632
|
<pre><code><textarea class="form-control quiz"{item.title}"" id="exampleFormControlTextarea1" rows="3"></textarea>
</code></pre>
<p>in this example i want to add item.title prop with quiz class</p>
<p>I want to add prop with quiz class so how should I concatenate this scenario</p>
|
[
{
"answer_id": 74556716,
"author": "Mohammed Raoof",
"author_id": 6568129,
"author_profile": "https://Stackoverflow.com/users/6568129",
"pm_score": 1,
"selected": false,
"text": "<textarea className={`form-control quiz${item.title}`} id=\"exampleFormControlTextarea1\" rows=\"3\">"
},
{
"answer_id": 74556944,
"author": "Muhiq kapadia",
"author_id": 17160128,
"author_profile": "https://Stackoverflow.com/users/17160128",
"pm_score": 1,
"selected": true,
"text": "<textarea className={`form-control quiz${item.title}`} id=\"exampleFormControlTextarea1\" rows=\"3\">\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20588092/"
] |
74,556,638
|
<p>If I have a list like this</p>
<pre><code>lista=[(0.11838, 0.1926, 0.12071, 0.27438, -0.0253, -0.18799, 0.01544, 0.24514, 0.19905, 0.18563, 0.19999, 0.25336, 783, 783, 783, 783), (nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan), (nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan), (0.11838, 0.1926, 0.12071, 0.27438, -0.0253, -0.18799, 0.01544, 0.24514, 0.19905, 0.18563, 0.19999, 0.25336, 783, 783, 783, 783), (nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan), (nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan), (0.11838, 0.1926, 0.12071, 0.27438, -0.0253, -0.18799, 0.01544, 0.24514, 0.19905, 0.18563, 0.19999, 0.25336, 783, 783, 783, 783), (nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan)]
</code></pre>
<p>is there a way that when transforming them into dataframes the integers (<code>783</code>) does not get transformed into floats?</p>
<p>Now I get this</p>
<pre><code>pd.DataFrame(lista)
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
0 0.11838 0.1926 0.12071 0.27438 -0.0253 -0.18799 0.01544 0.24514 0.19905 0.18563 0.19999 0.25336 783.0 783.0 783.0 783.0
1 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
3 0.11838 0.1926 0.12071 0.27438 -0.0253 -0.18799 0.01544 0.24514 0.19905 0.18563 0.19999 0.25336 783.0 783.0 783.0 783.0
4 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
5 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
6 0.11838 0.1926 0.12071 0.27438 -0.0253 -0.18799 0.01544 0.24514 0.19905 0.18563 0.19999 0.25336 783.0 783.0 783.0 783.0
7 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
</code></pre>
|
[
{
"answer_id": 74556674,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 3,
"selected": true,
"text": "np.nan float Dtype Dtypes DataFrame.convert_dtypes df = pd.DataFrame(lista).convert_dtypes()\nprint (df)\n 0 1 2 3 4 5 6 7 \\\n0 0.11838 0.1926 0.12071 0.27438 -0.0253 -0.18799 0.01544 0.24514 \n1 <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> \n2 <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> \n3 0.11838 0.1926 0.12071 0.27438 -0.0253 -0.18799 0.01544 0.24514 \n4 <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> \n5 <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> \n6 0.11838 0.1926 0.12071 0.27438 -0.0253 -0.18799 0.01544 0.24514 \n7 <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> \n\n 8 9 10 11 12 13 14 15 \n0 0.19905 0.18563 0.19999 0.25336 783 783 783 783 \n1 <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> \n2 <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> \n3 0.19905 0.18563 0.19999 0.25336 783 783 783 783 \n4 <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> \n5 <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> \n6 0.19905 0.18563 0.19999 0.25336 783 783 783 783 \n7 <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> \n df = pd.DataFrame(lista)\n\nm = df.apply(lambda x: x.dropna().astype(int).eq(x)).any()\n\ndf.loc[:, m] = df.loc[:, m].astype('Int64')\nprint (df)\n 0 1 2 3 4 5 6 7 \\\n0 0.11838 0.1926 0.12071 0.27438 -0.0253 -0.18799 0.01544 0.24514 \n1 NaN NaN NaN NaN NaN NaN NaN NaN \n2 NaN NaN NaN NaN NaN NaN NaN NaN \n3 0.11838 0.1926 0.12071 0.27438 -0.0253 -0.18799 0.01544 0.24514 \n4 NaN NaN NaN NaN NaN NaN NaN NaN \n5 NaN NaN NaN NaN NaN NaN NaN NaN \n6 0.11838 0.1926 0.12071 0.27438 -0.0253 -0.18799 0.01544 0.24514 \n7 NaN NaN NaN NaN NaN NaN NaN NaN \n\n 8 9 10 11 12 13 14 15 \n0 0.19905 0.18563 0.19999 0.25336 783 783 783 783 \n1 NaN NaN NaN NaN <NA> <NA> <NA> <NA> \n2 NaN NaN NaN NaN <NA> <NA> <NA> <NA> \n3 0.19905 0.18563 0.19999 0.25336 783 783 783 783 \n4 NaN NaN NaN NaN <NA> <NA> <NA> <NA> \n5 NaN NaN NaN NaN <NA> <NA> <NA> <NA> \n6 0.19905 0.18563 0.19999 0.25336 783 783 783 783 \n7 NaN NaN NaN NaN <NA> <NA> <NA> <NA> \n"
},
{
"answer_id": 74556715,
"author": "Ahmed Aredah",
"author_id": 5800005,
"author_profile": "https://Stackoverflow.com/users/5800005",
"pm_score": 0,
"selected": false,
"text": "convert_dict = {'c1': int,\n 'c2': float\n } # c1 and c2 are example columns here\n\ndf = df.astype(convert_dict)\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4451521/"
] |
74,556,646
|
<p>I have <code>object</code> as following :</p>
<pre><code>0 : {rYear: '1Y', rType: 'TypeA', rVal: 41}
1 : {rYear: '2Y', rType: 'TypeA', rVal: 11}
2 : {rYear: '3Y', rType: 'TypeA', rVal: 32}
3 : {rYear: '1Y', rType: 'TypeB', rVal: 12}
4 : {rYear: '2Y', rType: 'TypeB', rVal: 21}
5 : {rYear: '3Y', rType: 'TypeB', rVal: 16}
</code></pre>
<p>I want to transfer the <code>object</code> as below format :</p>
<pre><code>0 : {rType: 'TypeA', 1Y: 41, 2Y: 11, 3Y: 32}
1 : {rType: 'TypeB', 1Y: 12, 2Y: 21, 3Y: 16}
</code></pre>
<p>I’ve tried to use <em>.groupBy(collection, [iteratee=</em>.identity]) from <strong>lodash</strong>, but dose not get what I need to achieve.</p>
|
[
{
"answer_id": 74556740,
"author": "flyingfox",
"author_id": 3176419,
"author_profile": "https://Stackoverflow.com/users/3176419",
"pm_score": 1,
"selected": false,
"text": "Array.reduce() let data = [ \n {rYear: '1Y', rType: 'TypeA', rVal: 41},\n {rYear: '2Y', rType: 'TypeA', rVal: 11},\n {rYear: '3Y', rType: 'TypeA', rVal: 32},\n {rYear: '1Y', rType: 'TypeB', rVal: 12},\n {rYear: '2Y', rType: 'TypeB', rVal: 21},\n {rYear: '3Y', rType: 'TypeB', rVal: 16}\n]\n\nlet result = data.reduce((a,v) =>{\n let obj = a.find(i => i.rType === v.rType)\n if(obj){\n obj[v.rYear] = v.rVal\n }else{\n obj = {'rType':v.rType}\n obj[v.rYear] = v.rVal\n a.push(obj)\n }\n return a\n},[])\nconsole.log(result)"
},
{
"answer_id": 74556747,
"author": "adiga",
"author_id": 3082296,
"author_profile": "https://Stackoverflow.com/users/3082296",
"pm_score": 3,
"selected": true,
"text": "reduce rType const input = [\n { rYear: '1Y', rType: 'TypeA', rVal: 41 },\n { rYear: '2Y', rType: 'TypeA', rVal: 11 },\n { rYear: '3Y', rType: 'TypeA', rVal: 32 },\n { rYear: '1Y', rType: 'TypeB', rVal: 12 },\n { rYear: '2Y', rType: 'TypeB', rVal: 21 },\n { rYear: '3Y', rType: 'TypeB', rVal: 16 },\n]\n\nconst grouped = input.reduce((acc, { rYear, rType, rVal }) => {\n acc[rType] ??= { rType };\n acc[rType][rYear] = rVal\n return acc\n }, {})\n \nconst output = Object.values(grouped)\n\nconsole.log(output)"
},
{
"answer_id": 74556968,
"author": "ssspuer_ege",
"author_id": 20580063,
"author_profile": "https://Stackoverflow.com/users/20580063",
"pm_score": 1,
"selected": false,
"text": "const arr = [\n { rYear: \"1Y\", rType: \"TypeA\", rVal: 41 },\n { rYear: \"2Y\", rType: \"TypeA\", rVal: 11 },\n { rYear: \"3Y\", rType: \"TypeA\", rVal: 32 },\n { rYear: \"1Y\", rType: \"TypeB\", rVal: 12 },\n { rYear: \"2Y\", rType: \"TypeB\", rVal: 21 },\n { rYear: \"3Y\", rType: \"TypeB\", rVal: 16 },\n ];\n const objMap = new Map();\n arr.forEach((e) => {\n const obj = {};\n obj[e.rYear] = e.rVal;\n obj[\"rType\"] = e.rType;\n if (objMap.get(e.rType) === undefined) {\n objMap.set(e.rType, obj);\n }\n objMap.get(e.rType)[e.rYear] = e.rVal;\n });\n const resultArr = [];\n objMap.forEach((e) => {\n resultArr.push(e);\n });"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6681701/"
] |
74,556,655
|
<pre><code>def execute():
d = read_input_file_mock()
lst = []
for in in d:
if in.get("Message"):
message = in.get("Message")
message = json.loads(message)
in_string = message.get("in")
lst.append(in_string)
data = json.dumps(list(set(lst)))
return data
</code></pre>
<p><strong>output</strong></p>
<p>["5700302618082", "4063617555079", "4048803188064", "4017182874431", "4006175499096", "0098132561704", "5700302496406", "4056867023092"]</p>
<p>want to save this result in csv file as a integer!</p>
|
[
{
"answer_id": 74557479,
"author": "abokey",
"author_id": 16120011,
"author_profile": "https://Stackoverflow.com/users/16120011",
"pm_score": 1,
"selected": false,
"text": "csvwriter.writerows import csv\n\nwith open(\"path_to_the_outputfile.csv\", \"w\", newline=\"\") as f:\n writer=csv.writer(f)\n writer.writerows([[row] for row in data])\n 5700302618082\n4063617555079\n4048803188064\n4017182874431\n4006175499096\n...\n List_of_Numbers csvwriter.writerow with open(\"path_to_the_outputfile.csv\", \"w\", newline=\"\") as f:\n writer=csv.writer(f)\n writer.writerow(['List_of_Numbers'])\n writer.writerows([[row] for row in data])\n \n"
},
{
"answer_id": 74558617,
"author": "Omaro rai",
"author_id": 16163401,
"author_profile": "https://Stackoverflow.com/users/16163401",
"pm_score": 0,
"selected": false,
"text": "import pandas as pd\nimport numpy as np\npd.DataFrame(np.array(your_data,dtype=\"int64\")).to_csv('your_path.csv')\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13607593/"
] |
74,556,657
|
<p>I'm pretty new to Java and I am trying to implement prefix sum</p>
<pre><code>package Arrays;
public class prefixSum {
static void sumArray(int arr[]) {
int n = arr.length;
int aux[] = new int[n];
int curr = arr[0];
aux[0] = curr;
for (int i = 1; i < n; i++) {
aux[i] = arr[i] + curr;
}
}
static int getSum(int arr[],int start,int end){
int n=arr.length;
sumArray(arr);
if(start==0){
return aux[end];
}
return aux[end]-aux[start-1]
}
public static void main(String[] args) {
int arr[] = { 2, 5, 7, 3, 4, 5, 3 };
int start = 2;
int end = 5;
System.out.print(getSum(arr, start, end));
}
}
</code></pre>
<p>I want aux[] to be a global array that can be accessed anywhere. Also, I would like the length of the aux[] array to be the same as the length as arr[].</p>
|
[
{
"answer_id": 74556834,
"author": "Joshgun",
"author_id": 7061312,
"author_profile": "https://Stackoverflow.com/users/7061312",
"pm_score": 0,
"selected": false,
"text": "aux[] main public class prefixSum {\n static int[] aux;\n\n...\n public static void main(String[] args) {\n int[] arr = { 2, 5, 7, 3, 4, 5, 3 };\n aux = new int[arr.length];\n ...\n }\n aux sumArray int[] arr int arr[] public class prefixSum {\n static int aux[];\n\n static void sumArray(int[] arr) {\n int n = arr.length;\n int curr = arr[0];\n aux[0] = curr;\n for (int i = 1; i < n; i++) {\n aux[i] = arr[i] + curr;\n }\n }\n\n static int getSum(int[] arr, int start, int end) {\n int n = arr.length;\n sumArray(arr);\n if (start == 0) {\n return aux[end];\n }\n return aux[end] - aux[start - 1];\n }\n\n public static void main(String[] args) {\n int[] arr = {2, 5, 7, 3, 4, 5, 3};\n aux = new int[arr.length];\n\n int start = 2;\n int end = 5;\n System.out.print(getSum(arr, start, end));\n\n }\n}\n"
},
{
"answer_id": 74556963,
"author": "Yonatan Karp-Rudin",
"author_id": 3899765,
"author_profile": "https://Stackoverflow.com/users/3899765",
"pm_score": 1,
"selected": false,
"text": "public class PrefixSum {\n\n private static int[] aux;\n\n ...\n\n}\n int[] aux int aux[] public class PrefixSum {\n\n static int[] sumArray(int[] arr) {\n int n = arr.length;\n int[] aux = new int[n];\n int curr = arr[0];\n aux[0] = curr;\n for (int i = 1; i < n; i++) {\n aux[i] = arr[i] + curr;\n }\n\n return aux;\n }\n\n static int getSum(int[] arr, int start, int end) {\n int[] aux = sumArray(arr);\n if (start == 0) {\n return aux[end];\n }\n return aux[end] - aux[start - 1];\n }\n\n public static void main(String[] args) {\n int[] arr = {2, 5, 7, 3, 4, 5, 3};\n int start = 2;\n int end = 5;\n System.out.print(getSum(arr, start, end));\n }\n}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20588048/"
] |
74,556,770
|
<p>After Two weeks I opened my project. My coworker made some big changes. But when I update the project from GitHub, This Error occurred. it doesn't generate Internationalize files.</p>
<p><a href="https://i.stack.imgur.com/3KaHh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3KaHh.png" alt="enter image description here" /></a></p>
<p>I tried to run <code>flutter gen-l10n</code> but here's the output
<a href="https://i.stack.imgur.com/QIGRh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QIGRh.png" alt="enter image description here" /></a></p>
<p>And here are the files inside the l10n folder</p>
<p><a href="https://i.stack.imgur.com/raEzM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/raEzM.png" alt="enter image description here" /></a></p>
<p>Now how can I solve it??</p>
|
[
{
"answer_id": 74556834,
"author": "Joshgun",
"author_id": 7061312,
"author_profile": "https://Stackoverflow.com/users/7061312",
"pm_score": 0,
"selected": false,
"text": "aux[] main public class prefixSum {\n static int[] aux;\n\n...\n public static void main(String[] args) {\n int[] arr = { 2, 5, 7, 3, 4, 5, 3 };\n aux = new int[arr.length];\n ...\n }\n aux sumArray int[] arr int arr[] public class prefixSum {\n static int aux[];\n\n static void sumArray(int[] arr) {\n int n = arr.length;\n int curr = arr[0];\n aux[0] = curr;\n for (int i = 1; i < n; i++) {\n aux[i] = arr[i] + curr;\n }\n }\n\n static int getSum(int[] arr, int start, int end) {\n int n = arr.length;\n sumArray(arr);\n if (start == 0) {\n return aux[end];\n }\n return aux[end] - aux[start - 1];\n }\n\n public static void main(String[] args) {\n int[] arr = {2, 5, 7, 3, 4, 5, 3};\n aux = new int[arr.length];\n\n int start = 2;\n int end = 5;\n System.out.print(getSum(arr, start, end));\n\n }\n}\n"
},
{
"answer_id": 74556963,
"author": "Yonatan Karp-Rudin",
"author_id": 3899765,
"author_profile": "https://Stackoverflow.com/users/3899765",
"pm_score": 1,
"selected": false,
"text": "public class PrefixSum {\n\n private static int[] aux;\n\n ...\n\n}\n int[] aux int aux[] public class PrefixSum {\n\n static int[] sumArray(int[] arr) {\n int n = arr.length;\n int[] aux = new int[n];\n int curr = arr[0];\n aux[0] = curr;\n for (int i = 1; i < n; i++) {\n aux[i] = arr[i] + curr;\n }\n\n return aux;\n }\n\n static int getSum(int[] arr, int start, int end) {\n int[] aux = sumArray(arr);\n if (start == 0) {\n return aux[end];\n }\n return aux[end] - aux[start - 1];\n }\n\n public static void main(String[] args) {\n int[] arr = {2, 5, 7, 3, 4, 5, 3};\n int start = 2;\n int end = 5;\n System.out.print(getSum(arr, start, end));\n }\n}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14029095/"
] |
74,556,771
|
<p>Table</p>
<pre><code>CREATE TABLE users
(
username VARCHAR(128) PRIMARY KEY,
info JSONB
);
INSERT INTO users (username, info)
VALUES
('Lana', '[
{
"id": "first"
},
{
"id": "second"
}
]'),
('Andy', '[
{
"id": "first"
},
{
"id": "third"
}
]');
</code></pre>
<p>So I want to find all users, whose <code>info.id</code> contained in array like ["first"].</p>
<p>request should be like:</p>
<pre><code>SELECT *
FROM users
where jsonb_path_exists(info, '$.id ? (@ in ("first", "second", "third",...) )');
</code></pre>
<p>But I can't find the correct implementation</p>
|
[
{
"answer_id": 74556834,
"author": "Joshgun",
"author_id": 7061312,
"author_profile": "https://Stackoverflow.com/users/7061312",
"pm_score": 0,
"selected": false,
"text": "aux[] main public class prefixSum {\n static int[] aux;\n\n...\n public static void main(String[] args) {\n int[] arr = { 2, 5, 7, 3, 4, 5, 3 };\n aux = new int[arr.length];\n ...\n }\n aux sumArray int[] arr int arr[] public class prefixSum {\n static int aux[];\n\n static void sumArray(int[] arr) {\n int n = arr.length;\n int curr = arr[0];\n aux[0] = curr;\n for (int i = 1; i < n; i++) {\n aux[i] = arr[i] + curr;\n }\n }\n\n static int getSum(int[] arr, int start, int end) {\n int n = arr.length;\n sumArray(arr);\n if (start == 0) {\n return aux[end];\n }\n return aux[end] - aux[start - 1];\n }\n\n public static void main(String[] args) {\n int[] arr = {2, 5, 7, 3, 4, 5, 3};\n aux = new int[arr.length];\n\n int start = 2;\n int end = 5;\n System.out.print(getSum(arr, start, end));\n\n }\n}\n"
},
{
"answer_id": 74556963,
"author": "Yonatan Karp-Rudin",
"author_id": 3899765,
"author_profile": "https://Stackoverflow.com/users/3899765",
"pm_score": 1,
"selected": false,
"text": "public class PrefixSum {\n\n private static int[] aux;\n\n ...\n\n}\n int[] aux int aux[] public class PrefixSum {\n\n static int[] sumArray(int[] arr) {\n int n = arr.length;\n int[] aux = new int[n];\n int curr = arr[0];\n aux[0] = curr;\n for (int i = 1; i < n; i++) {\n aux[i] = arr[i] + curr;\n }\n\n return aux;\n }\n\n static int getSum(int[] arr, int start, int end) {\n int[] aux = sumArray(arr);\n if (start == 0) {\n return aux[end];\n }\n return aux[end] - aux[start - 1];\n }\n\n public static void main(String[] args) {\n int[] arr = {2, 5, 7, 3, 4, 5, 3};\n int start = 2;\n int end = 5;\n System.out.print(getSum(arr, start, end));\n }\n}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12966384/"
] |
74,556,778
|
<p>I'm beginner, i have homework that requires the user to input a number and it convert it to words.For example:</p>
<pre><code>15342
</code></pre>
<p>to</p>
<pre><code>one five three four two
</code></pre>
<p>this's my code, but it only work with a number:</p>
<pre><code>def convert_text():
arr = ['zero','one','two','three','four','five','six','seven','eight','nine']
word = arr[n]
return word
n =int(input())
print(convert_text())
</code></pre>
<p>I am not allowed to use the num2word library and dictionary.</p>
|
[
{
"answer_id": 74556834,
"author": "Joshgun",
"author_id": 7061312,
"author_profile": "https://Stackoverflow.com/users/7061312",
"pm_score": 0,
"selected": false,
"text": "aux[] main public class prefixSum {\n static int[] aux;\n\n...\n public static void main(String[] args) {\n int[] arr = { 2, 5, 7, 3, 4, 5, 3 };\n aux = new int[arr.length];\n ...\n }\n aux sumArray int[] arr int arr[] public class prefixSum {\n static int aux[];\n\n static void sumArray(int[] arr) {\n int n = arr.length;\n int curr = arr[0];\n aux[0] = curr;\n for (int i = 1; i < n; i++) {\n aux[i] = arr[i] + curr;\n }\n }\n\n static int getSum(int[] arr, int start, int end) {\n int n = arr.length;\n sumArray(arr);\n if (start == 0) {\n return aux[end];\n }\n return aux[end] - aux[start - 1];\n }\n\n public static void main(String[] args) {\n int[] arr = {2, 5, 7, 3, 4, 5, 3};\n aux = new int[arr.length];\n\n int start = 2;\n int end = 5;\n System.out.print(getSum(arr, start, end));\n\n }\n}\n"
},
{
"answer_id": 74556963,
"author": "Yonatan Karp-Rudin",
"author_id": 3899765,
"author_profile": "https://Stackoverflow.com/users/3899765",
"pm_score": 1,
"selected": false,
"text": "public class PrefixSum {\n\n private static int[] aux;\n\n ...\n\n}\n int[] aux int aux[] public class PrefixSum {\n\n static int[] sumArray(int[] arr) {\n int n = arr.length;\n int[] aux = new int[n];\n int curr = arr[0];\n aux[0] = curr;\n for (int i = 1; i < n; i++) {\n aux[i] = arr[i] + curr;\n }\n\n return aux;\n }\n\n static int getSum(int[] arr, int start, int end) {\n int[] aux = sumArray(arr);\n if (start == 0) {\n return aux[end];\n }\n return aux[end] - aux[start - 1];\n }\n\n public static void main(String[] args) {\n int[] arr = {2, 5, 7, 3, 4, 5, 3};\n int start = 2;\n int end = 5;\n System.out.print(getSum(arr, start, end));\n }\n}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20025193/"
] |
74,556,789
|
<pre><code>int main() {
string getEmail;
string email, firstName, lastName;
char dot = '.';
cout << "What is your email?" << endl;
getline(cin, email);
double pos = email.find(dot);
firstName = //store every letter before the dot;
cout << firstName << endl;
return 0;
}
</code></pre>
<p>How can I read the email, let's say I encounter <code>'.'</code>, I want to read the word before it. For example: <code>Yes.no</code>. I find <code>'.'</code> and read <code>Yes</code> and store it in a variable.</p>
|
[
{
"answer_id": 74556853,
"author": "john",
"author_id": 882003,
"author_profile": "https://Stackoverflow.com/users/882003",
"pm_score": 2,
"selected": false,
"text": "pos double size_t size_t pos = email.find(dot);\n substr firstName = email.substr(0, pos);\n email firstName size_t pos = email.find(dot);\nif (pos == string::npos) // if no dot\n cout << \"no dot in email address\";\n"
},
{
"answer_id": 74556872,
"author": "user17443931",
"author_id": 17443931,
"author_profile": "https://Stackoverflow.com/users/17443931",
"pm_score": 0,
"selected": false,
"text": "substr() pos double int main()\n{\n string getEmail;\n \n string email, firstName, lastName;\n char dot = '.';\n cout << \"What is your email?\" << endl;\n getline(cin, email);\n \n size_t pos = email.find(dot);\n firstName = email.substr(0, pos);\n cout << firstName << endl;\n return 0;\n}\n"
},
{
"answer_id": 74561609,
"author": "rturrado",
"author_id": 260313,
"author_profile": "https://Stackoverflow.com/users/260313",
"pm_score": 0,
"selected": false,
"text": "#include <fmt/core.h>\n#include <regex>\n#include <string>\n\nint main() {\n std::regex pattern{ R\"((\\w+)\\.(\\w+)@.+)\" };\n for (std::string email : { \"john.doe@xyz.com\", \"anne.doe@abc.org\", \"foo@so.com\" }) {\n std::smatch matches{};\n if (std::regex_match(email, matches, pattern)) {\n fmt::print(\"email: '{}', first name: '{}', second name: '{}'\\n\",\n matches[0].str(), matches[1].str(), matches[2].str());\n } else {\n fmt::print(\"Warning: username does not contain a dot: '{}'.\\n\", email);\n }\n }\n}\n\n// Outputs:\n//\n// email: 'john.doe@xyz.com', first name: 'john', second name: 'doe'\n// email: 'anne.doe@abc.org', first name: 'anne', second name: 'doe'\n// Warning: username does not contain a dot: 'foo@so.com'.\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20289819/"
] |
74,556,794
|
<p>running monit 5.30 on Rocky 8.7</p>
<p>Linux vpn-uk2 4.18.0-372.9.1.el8.x86_64</p>
<p>monit control file syntax is valid,</p>
<p>heres control file</p>
<pre><code>set daemon 5 # Poll at 5-second intervals
set logfile /var/log/monit.log
set eventqueue basedir /home/monit/tmp slots 1000
set mmonit http://monit:monit@server1:19840/collector
set httpd port 19841
allow localhost
allow 127.0.0.1
allow monit:monit
check filesystem vpn-uk2-/ with path /
if space usage > 95% then alert
if space usage > 90% then alert
if space usage > 85% then alert
if space usage > 80% then alert
if space usage > 75% then alert
</code></pre>
<p>if I try to start systemd monit service, or run "monit reload" as monit user, I get</p>
<pre><code>[2022-11-24T06:57:22+0000] error : Cannot connect to [localhost]:19841 -- Cannot assign requested address
[2022-11-24T06:57:27+0000] info : Reinitializing monit daemon
[2022-11-24T06:57:27+0000] error : Cannot signal the monit daemon process -- Operation not permitted
</code></pre>
<p>selinux is turned off.</p>
<p>Not sure what the error msg means, logs are not providing any meaningful information.</p>
<p>whats weird is that I have same exact monit config deployed via Saltstack to other hosts, same OS, etc, but not getting this error on other hosts</p>
<p>(nothing in kernel log either)</p>
|
[
{
"answer_id": 74556853,
"author": "john",
"author_id": 882003,
"author_profile": "https://Stackoverflow.com/users/882003",
"pm_score": 2,
"selected": false,
"text": "pos double size_t size_t pos = email.find(dot);\n substr firstName = email.substr(0, pos);\n email firstName size_t pos = email.find(dot);\nif (pos == string::npos) // if no dot\n cout << \"no dot in email address\";\n"
},
{
"answer_id": 74556872,
"author": "user17443931",
"author_id": 17443931,
"author_profile": "https://Stackoverflow.com/users/17443931",
"pm_score": 0,
"selected": false,
"text": "substr() pos double int main()\n{\n string getEmail;\n \n string email, firstName, lastName;\n char dot = '.';\n cout << \"What is your email?\" << endl;\n getline(cin, email);\n \n size_t pos = email.find(dot);\n firstName = email.substr(0, pos);\n cout << firstName << endl;\n return 0;\n}\n"
},
{
"answer_id": 74561609,
"author": "rturrado",
"author_id": 260313,
"author_profile": "https://Stackoverflow.com/users/260313",
"pm_score": 0,
"selected": false,
"text": "#include <fmt/core.h>\n#include <regex>\n#include <string>\n\nint main() {\n std::regex pattern{ R\"((\\w+)\\.(\\w+)@.+)\" };\n for (std::string email : { \"john.doe@xyz.com\", \"anne.doe@abc.org\", \"foo@so.com\" }) {\n std::smatch matches{};\n if (std::regex_match(email, matches, pattern)) {\n fmt::print(\"email: '{}', first name: '{}', second name: '{}'\\n\",\n matches[0].str(), matches[1].str(), matches[2].str());\n } else {\n fmt::print(\"Warning: username does not contain a dot: '{}'.\\n\", email);\n }\n }\n}\n\n// Outputs:\n//\n// email: 'john.doe@xyz.com', first name: 'john', second name: 'doe'\n// email: 'anne.doe@abc.org', first name: 'anne', second name: 'doe'\n// Warning: username does not contain a dot: 'foo@so.com'.\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7327476/"
] |
74,556,804
|
<p>I'm trying to deploy the following Django-rest api on gcp ubuntu 22.0.4 using python 3.9.</p>
<p><a href="https://github.com/OkunaOrg/okuna-api" rel="nofollow noreferrer">https://github.com/OkunaOrg/okuna-api</a></p>
<p>The entire setup is supposed to be done and get setup using a single command :</p>
<p>python3.9 okuna-cli.py up-full</p>
<p>The execution seems stuck at "Waiting for server to come up..." and doesn't proceed ahead. The setup should complete by stating "Okuna is live at "domain". Another important aspect of the setup is the 5 docker containers are running and working fine when i run the py file. I'm even able to access the database after creating a superuser.</p>
<p>The code is as follows :</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>import random
import time
import click
import subprocess
import colorlog
import logging
import os.path
from shutil import copyfile
import json
import atexit
import os, errno
import requests
from halo import Halo
handler = colorlog.StreamHandler()
handler.setFormatter(colorlog.ColoredFormatter(
'%(log_color)s%(name)s -> %(message)s'))
logger = colorlog.getLogger('')
logger.addHandler(handler)
logger.setLevel(level=logging.DEBUG)
current_dir = os.path.dirname(__file__)
OKUNA_CLI_CONFIG_FILE = os.path.join(current_dir, '.okuna-cli.json')
OKUNA_CLI_CONFIG_FILE_TEMPLATE = os.path.join(current_dir, 'templates/.okuna-cli.json')
LOCAL_API_ENV_FILE = os.path.join(current_dir, '.env')
LOCAL_API_ENV_FILE_TEMPLATE = os.path.join(current_dir, 'templates/.env')
DOCKER_COMPOSE_ENV_FILE = os.path.join(current_dir, '.docker-compose.env')
DOCKER_COMPOSE_ENV_FILE_TEMPLATE = os.path.join(current_dir, 'templates/.docker-compose.env')
REQUIREMENTS_TXT_FILE = os.path.join(current_dir, 'requirements.txt')
DOCKER_API_IMAGE_REQUIREMENTS_TXT_FILE = os.path.join(current_dir, '.docker', 'api', 'requirements.txt')
DOCKER_WORKER_IMAGE_REQUIREMENTS_TXT_FILE = os.path.join(current_dir, '.docker', 'worker', 'requirements.txt')
DOCKER_SCHEDULER_IMAGE_REQUIREMENTS_TXT_FILE = os.path.join(current_dir, '.docker', 'scheduler', 'requirements.txt')
DOCKER_API_TEST_IMAGE_REQUIREMENTS_TXT_FILE = os.path.join(current_dir, '.docker', 'api-test', 'requirements.txt')
CONTEXT_SETTINGS = dict(
default_map={}
)
random_generator = random.SystemRandom()
def _remove_file_silently(filename):
try:
os.remove(filename)
except OSError as e: # this would be "except OSError, e:" before Python 2.6
if e.errno != errno.ENOENT: # errno.ENOENT = no such file or directory
raise # re-raise exception if a different error occurred
def _get_random_string(length=12,
allowed_chars='abcdefghijklmnopqrstuvwxyz'
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
"""
Return a securely generated random string.
The default length of 12 with the a-z, A-Z, 0-9 character set returns
a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
"""
return ''.join(random.choice(allowed_chars) for i in range(length))
def _get_django_secret_key():
"""
Return a 50 character random string usable as a SECRET_KEY setting value.
"""
chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'
return _get_random_string(50, chars)
def _get_mysql_password():
return _get_random_string(64)
def _get_redis_password():
return _get_random_string(128)
def _copy_requirements_txt_to_docker_images_dir():
copyfile(REQUIREMENTS_TXT_FILE, DOCKER_API_IMAGE_REQUIREMENTS_TXT_FILE)
copyfile(REQUIREMENTS_TXT_FILE, DOCKER_WORKER_IMAGE_REQUIREMENTS_TXT_FILE)
copyfile(REQUIREMENTS_TXT_FILE, DOCKER_SCHEDULER_IMAGE_REQUIREMENTS_TXT_FILE)
def _check_okuna_api_is_running(address, port):
# Create a TCP socket
try:
response = requests.get('http://%s:%s/health/' % (address, port))
response_status = response.status_code
return response_status == 200
except requests.ConnectionError as e:
return False
def _wait_until_api_is_running(address, port, message='Waiting for server to come up...', sleep=None):
spinner = Halo(text=message, spinner='dots')
spinner.start()
if sleep:
time.sleep(sleep)
is_running = _check_okuna_api_is_running(address=address, port=port)
while not is_running:
is_running = _check_okuna_api_is_running(address=address, port=port)
spinner.stop()
def _clean():
"""
Cleans everything that the okuna-cli has created. Docker volumes, config files, everything.
:return:
"""
logger.info(' Cleaning up database')
subprocess.run(["docker", "volume", "rm", "okuna-api_mariadb"])
subprocess.run(["docker", "volume", "rm", "okuna-api_redisdb"])
logger.info(' Cleaning up config files')
_remove_file_silently(LOCAL_API_ENV_FILE)
_remove_file_silently(DOCKER_COMPOSE_ENV_FILE)
_remove_file_silently(OKUNA_CLI_CONFIG_FILE)
logger.info('✅ Clean up done!')
def _print_okuna_logo():
print(r"""
____ _
/ __ \| |
| | | | | ___ _ _ __ __ _
| | | | |/ | | | | '_ \ / _` |
| |__| | <| |_| | | | | (_| |
\____/|_|\_\\__,_|_| |_|\__,_|
""")
def _file_exists(filename):
return os.path.exists(filename) and os.path.isfile(filename)
def _replace_in_file(filename, texts):
with open(filename, 'r') as file:
filedata = file.read()
# Replace the target string
for key in texts:
value = texts[key]
filedata = filedata.replace(key, value)
# Write the file out again
with open(filename, 'w') as file:
file.write(filedata)
def _ensure_has_local_api_environment_file(okuna_cli_config):
if _file_exists(LOCAL_API_ENV_FILE):
return
logger.info('Local API .env file does not exist. Creating %s' % LOCAL_API_ENV_FILE)
if not _file_exists(LOCAL_API_ENV_FILE_TEMPLATE):
raise Exception('Local API .env file template did not exist')
copyfile(LOCAL_API_ENV_FILE_TEMPLATE, LOCAL_API_ENV_FILE)
_replace_in_file(LOCAL_API_ENV_FILE, {
"{{DJANGO_SECRET_KEY}}": okuna_cli_config['djangoSecretKey'],
"{{SQL_PASSWORD}}": okuna_cli_config['sqlPassword'],
"{{REDIS_PASSWORD}}": okuna_cli_config['redisPassword'],
})
def _ensure_has_docker_compose_api_environment_file(okuna_cli_config):
if _file_exists(DOCKER_COMPOSE_ENV_FILE):
return
logger.info('Docker compose env file does not exist. Creating %s' % DOCKER_COMPOSE_ENV_FILE)
if not _file_exists(DOCKER_COMPOSE_ENV_FILE_TEMPLATE):
raise Exception('Docker compose env file template did not exist')
copyfile(DOCKER_COMPOSE_ENV_FILE_TEMPLATE, DOCKER_COMPOSE_ENV_FILE)
_replace_in_file(DOCKER_COMPOSE_ENV_FILE, {
"{{DJANGO_SECRET_KEY}}": okuna_cli_config['djangoSecretKey'],
"{{SQL_PASSWORD}}": okuna_cli_config['sqlPassword'],
"{{REDIS_PASSWORD}}": okuna_cli_config['redisPassword'],
})
def _ensure_has_okuna_config_file():
if _file_exists(OKUNA_CLI_CONFIG_FILE):
return
django_secret_key = _get_django_secret_key()
mysql_password = _get_mysql_password()
redis_password = _get_redis_password()
logger.info('Generated DJANGO_SECRET_KEY=%s' % django_secret_key)
logger.info('Generated SQL_PASSWORD=%s' % mysql_password)
logger.info('Generated REDIS_PASSWORD=%s' % redis_password)
logger.info('Config file does not exist. Creating %s' % OKUNA_CLI_CONFIG_FILE)
if not _file_exists(OKUNA_CLI_CONFIG_FILE_TEMPLATE):
raise Exception('Config file template did not exists')
copyfile(OKUNA_CLI_CONFIG_FILE_TEMPLATE, OKUNA_CLI_CONFIG_FILE)
_replace_in_file(OKUNA_CLI_CONFIG_FILE, {
"{{DJANGO_SECRET_KEY}}": django_secret_key,
"{{SQL_PASSWORD}}": mysql_password,
"{{REDIS_PASSWORD}}": redis_password,
})
def _bootstrap(is_local_api):
logger.info(' Bootstrapping Okuna with some data')
if is_local_api:
subprocess.run(["./utils/scripts/bootstrap_development_data.sh"])
else:
subprocess.run(["docker-compose", "-f", "docker-compose-full.yml", "exec", "webserver",
"/bootstrap_development_data.sh"])
def _ensure_has_required_cli_config_files():
_ensure_has_okuna_config_file()
with open(OKUNA_CLI_CONFIG_FILE, 'r+') as okuna_cli_config_file:
okuna_cli_config = json.load(okuna_cli_config_file)
_ensure_has_docker_compose_api_environment_file(okuna_cli_config=okuna_cli_config)
_ensure_has_local_api_environment_file(okuna_cli_config=okuna_cli_config)
def _ensure_was_bootstrapped(is_local_api):
with open(OKUNA_CLI_CONFIG_FILE, 'r+') as okuna_cli_config_file:
okuna_cli_config = json.load(okuna_cli_config_file)
if okuna_cli_config['bootstrapped']:
return
logger.info('Okuna was not bootstrapped.')
_bootstrap(is_local_api=is_local_api)
okuna_cli_config['bootstrapped'] = True
okuna_cli_config_file.seek(0)
json.dump(okuna_cli_config, okuna_cli_config_file, indent=4)
okuna_cli_config_file.truncate()
logger.info('Okuna was bootstrapped.')
@click.group()
def cli():
pass
def _down_test():
"""Bring Okuna down"""
logger.error('⬇️ Bringing the Okuna test services down...')
subprocess.run(["docker-compose", "-f", "docker-compose-test-services-only.yml", "down"])
def _down_full():
"""Bring Okuna down"""
logger.error('⬇️ Bringing the whole of Okuna down...')
subprocess.run(["docker-compose", "-f", "docker-compose-full.yml", "down"])
def _down_services_only():
"""Bring Okuna down"""
logger.error('⬇️ Bringing the Okuna services down...')
subprocess.run(["docker-compose", "-f", "docker-compose-services-only.yml", "down"])
@click.command()
def down_services_only():
_down_services_only()
@click.command()
def down_full():
_down_full()
@click.command()
def up_full():
"""Bring the whole of Okuna up"""
_print_okuna_logo()
_ensure_has_required_cli_config_files()
_copy_requirements_txt_to_docker_images_dir()
logger.info('⬆️ Bringing the whole of Okuna up...')
atexit.register(_down_full)
subprocess.run(["docker-compose", "-f", "docker-compose-full.yml", "up", "-d", "-V"])
okuna_api_address = 'domain'
okuna_api_port = 80
_wait_until_api_is_running(address=okuna_api_address, port=okuna_api_port)
_ensure_was_bootstrapped(is_local_api=False)
logger.info(' Okuna is live at http://%s:%s.' % (okuna_api_address, okuna_api_port))
subprocess.run(["docker-compose", "-f", "docker-compose-full.yml", "logs", "--follow", "--tail=0", "webserver"])
input()
@click.command()
def up_services_only():
"""Bring only the Okuna services up. API is up to you."""
_print_okuna_logo()
_ensure_has_required_cli_config_files()
_copy_requirements_txt_to_docker_images_dir()
logger.info('⬆️ Bringing only the Okuna services up...')
atexit.register(_down_services_only)
subprocess.run(["docker-compose", "-f", "docker-compose-services-only.yml", "up", "-d", "-V"])
_ensure_was_bootstrapped(is_local_api=True)
logger.info(' Okuna services are up')
subprocess.run(["docker-compose", "-f", "docker-compose-services-only.yml", "logs", "--follow"])
input()
@click.command()
def down_test():
_down_test()
@click.command()
def up_test():
"""Bring the Okuna test services up"""
_print_okuna_logo()
_ensure_has_required_cli_config_files()
logger.info('⬆️ Bringing the Okuna test services up...')
atexit.register(_down_test)
subprocess.run(["docker-compose", "-f", "docker-compose-test-services-only.yml", "up", "-d", "-V"])
logger.info(' Okuna tests services are live')
subprocess.run(
["docker-compose", "-f", "docker-compose-test-services-only.yml", "logs", "--follow", "--tail=0"])
input()
@click.command()
def build_full():
"""Rebuild Okuna services"""
_ensure_has_required_cli_config_files()
logger.info('♀️ Rebuilding Okuna full services...')
_copy_requirements_txt_to_docker_images_dir()
subprocess.run(["docker-compose", "-f", "docker-compose-full.yml", "build"])
@click.command()
def build_services_only():
"""Rebuild Okuna services"""
_ensure_has_required_cli_config_files()
logger.info('♀️ Rebuilding only Okuna services...')
_copy_requirements_txt_to_docker_images_dir()
subprocess.run(["docker-compose", "-f", "docker-compose-services-only.yml", "build"])
@click.command()
def status():
"""Get Okuna status"""
logger.info('️♂️ Retrieving services status...')
subprocess.run(["docker-compose", "ps"])
@click.command()
def clean():
"""Bootstrap Okuna"""
_clean()
cli.add_command(up_full)
cli.add_command(down_full)
cli.add_command(up_test)
cli.add_command(down_test)
cli.add_command(up_services_only)
cli.add_command(down_services_only)
cli.add_command(build_full)
cli.add_command(build_services_only)
cli.add_command(clean)
cli.add_command(status)
if __name__ == '__main__':
cli()</code></pre>
</div>
</div>
</p>
<p>I checked that the def status() isn't working as well which is supposed to check the running docker containers as defined in docker-compose.env and show results. I can se following error when I try:</p>
<p><strong>python3.9 okuna-cli.py status</strong></p>
<blockquote>
<p>Can't find a suitable configuration file in this directory or any parent.Are you in the right directory?Supported filenames: docker-compose.yml, docker-compose.yaml, compose.yml, compose.yaml</p>
</blockquote>
<p>When i do <strong>docker-compose -f docker-compose-full.yml up</strong></p>
<p>I have the following warning displayed :</p>
<p><strong>Aborted connection 3 to db: 'unconnected' user: 'unauthenticated' host: '172.16.16.2' (This connection closed normally without authentication)</strong></p>
<p><strong>Aborted connection 4 to db: 'unconnected' user: 'unauthenticated' host: '172.16.16.3' (This connection closed normally without authentication)</strong></p>
<p><strong>EDIT : The above Warning disappears after downgrading Mariadb version to 10.2</strong></p>
<p>I'm getting the 2 additional warnings as well. This is despite running inside a virtual environment and I've done everything using only pip3 without sudo:</p>
<p><strong>1.The directory '/root/.cache/pip' or its parent directory is not owned or is not writable by the current user. The cache has been disabled. Check the permissions and owner of that directory. If executing pip with sudo, you should use sudo's -H flag</strong></p>
<p><strong>2.Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: <a href="https://pip.pypa.io/warnings/venv" rel="nofollow noreferrer">https://pip.pypa.io/warnings/venv</a></strong></p>
<p>My docker-compose:</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>version: '3'
services:
webserver:
container_name: okuna-api
build:
dockerfile: Dockerfile
context: ./.docker/api
privileged: true
extra_hosts:
- db.okuna:172.16.16.4
- redis.okuna:172.16.16.5
volumes:
- ./:/opt/okuna-api-core
- ./.docker-cache/pip:/root/.cache/pip
ports:
- 80:80
working_dir: /opt/okuna-api-core
networks:
okuna:
ipv4_address: 172.16.16.1
depends_on:
- db
- redis
env_file:
- .docker-compose.env
worker:
container_name: okuna-worker
build:
dockerfile: Dockerfile
context: ./.docker/worker
privileged: true
extra_hosts:
- db.okuna:172.16.16.4
- redis.okuna:172.16.16.5
volumes:
- ./:/opt/okuna-api-core
- ./.docker-cache/pip:/root/.cache/pip
working_dir: /opt/okuna-api-core
networks:
okuna:
ipv4_address: 172.16.16.2
depends_on:
- webserver
env_file:
- .docker-compose.env
scheduler:
container_name: okuna-scheduler
build:
dockerfile: Dockerfile
context: ./.docker/scheduler
privileged: true
extra_hosts:
- db.okuna:172.16.16.4
- redis.okuna:172.16.16.5
volumes:
- ./:/opt/okuna-api-core
- ./.docker-cache/pip:/root/.cache/pip
working_dir: /opt/okuna-api-core
networks:
okuna:
ipv4_address: 172.16.16.3
depends_on:
- webserver
env_file:
- .docker-compose.env
db:
image: mariadb:latest
hostname: db.okuna
volumes:
- mariadb:/var/lib/mysql
ports:
- 3306
privileged: false
networks:
okuna:
ipv4_address: 172.16.16.4
command: --character-set-server=utf8 --collation-server=utf8_unicode_ci
env_file:
- .docker-compose.env
redis:
image: bitnami/redis:latest
privileged: false
ports:
- 6379
networks:
okuna:
ipv4_address: 172.16.16.5
env_file:
- .docker-compose.env
volumes:
- redisdb:/bitnami/redis/data
volumes:
mariadb:
redisdb:
networks:
okuna:
ipam:
driver: default
config:
- subnet: "172.16.16.0/16"</code></pre>
</div>
</div>
</p>
<p>my docker-compose.env :</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>
# Variable specifying execution environment
# Required always.
# Possible values: production,development,acceptance, test
ENVIRONMENT=development
# ============= START NON-ENV SPECIFIC VARIABLES ============= #
# [NAME] ALLOWED_HOSTS
# [DESCRIPTION] Django variable specifying allowed hosts.
# [REQUIRED][PRODUCTION]
# [MORE] https://docs.djangoproject.com/en/2.1/ref/settings/#allowed-hosts
#ALLOWED_HOSTS=www.openbook.social
# [NAME] SECRET_KEY
# [DESCRIPTION] Django variable to provide cryptographic signing. If using okuna-cli, obtained from .okuna-cli.json
# [REQUIRED][ALWAYS]
# [MORE] https://docs.djangoproject.com/en/2.1/ref/settings/#secret-key
SECRET_KEY=949m="long passwrod generated here"
# [NAME] JWT_ALGORITHM
# [DESCRIPTION] Django variable to provide cryptographic signing.
# [REQUIRED][ALWAYS]
# [MORE] https://docs.djangoproject.com/en/2.1/ref/settings/#secret-key
JWT_ALGORITHM=HS256
# [NAME] MEDIA_ROOT
# [DESCRIPTION] Absolute filesystem path to the directory that will hold user-uploaded files.
# [MORE] https://docs.djangoproject.com/en/2.1/ref/settings/#media-root
# [OPTIONAL=./media]
# MEDIA_ROOT=
# [NAME] MEDIA_URL
# [DESCRIPTION] URL that handles the media served from MEDIA_ROOT, used for managing stored files. It must end in a slash if set
# [MORE] https://docs.djangoproject.com/en/2.1/ref/settings/#media-url
# [OPTIONAL=/media/]
# MEDIA_URL=
# [GROUP] SQL Database Configuration
# [DESCRIPTION] The SQL database configuration
# [REQUIRED][ALWAYS]
RDS_DB_NAME=okuna
RDS_USERNAME=root
RDS_HOSTNAME=db.okuna
RDS_PORT=3306
RDS_HOSTNAME_READER=db.okuna
RDS_HOSTNAME_WRITER=db.okuna
#[NAME] RDS_PASSWORD
# [DESCRIPTION] The password for the SQL Database. If using okuna-cli, obtained from .okuna-cli.json
RDS_PASSWORD=long passwrod generated here
# [GROUP] Redis Database configuration Configuration
# [DESCRIPTION] The redis database configuration
# [REQUIRED][ALWAYS]
REDIS_HOST=redis.okuna
REDIS_PORT=6379
#[NAME] REDIS_PASSSWORD
# [DESCRIPTION] The password for the REDIS Database.
REDIS_PASSWORD=long password generated here
# [GROUP] Top posts criteria
# [DESCRIPTION] The criteria under which posts will be added to the Explore/Top posts section of the app
# [OPTIONAL=2]
# MIN_UNIQUE_TOP_POST_REACTIONS_COUNT=
# MIN_UNIQUE_TOP_POST_COMMENTS_COUNT=
# [NAME] NEW_USER_SUGGESTED_COMMUNITIES
# [DESCRIPTION] The ids of the communities to be suggested to a new user
# [OPTIONAL=1]
# NEW_USER_SUGGESTED_COMMUNITIES=1,1310,216
# [GROUP] Allowed media sizes
# [DESCRIPTION] The criteria under which posts will be added to the Explore/Top posts section of the app
# [OPTIONAL]
# POST_MEDIA_MAX_SIZE=30485760
# PROFILE_AVATAR_MAX_SIZE=10485760
# PROFILE_COVER_MAX_SIZE=10485760
# COMMUNITY_AVATAR_MAX_SIZE=10485760
# COMMUNITY_COVER_MAX_SIZE=10485760
# [NAME] MODERATORS_COMMUNITY_NAME
# [DESCRIPTION] The community which when joined, will become global moderators
# [OPTIONAL=mods]
# MODERATORS_COMMUNITY_NAME=
# ============= END NON-ENV SPECIFIC VARIABLES ============= #
# ============= START DOCKER COMPOSE SPECIFIC VARIABLES ============= #
# [GROUP] Mysql Docker Image env vars
# [DESCRIPTION] This must match the RDS_PASSWORD AND RDS_DATABASE env vars on top
# [REQUIRED][ALWAYS]
MYSQL_ROOT_PASSWORD=long password generated here
MYSQL_DATABASE=okuna
# [NAME] WAIT_HOSTS
# [DESCRIPTION] The hosts that the Kosmos API should wait for
# [REQUIRED]
WAIT_HOSTS:db.okuna:3306
# ============= END DOCKER COMPOSE SPECIFIC VARIABLES ============= # </code></pre>
</div>
</div>
</p>
<p>This is despite the configuration files are intact and in the right place.
Help appreciated.</p>
|
[
{
"answer_id": 74556853,
"author": "john",
"author_id": 882003,
"author_profile": "https://Stackoverflow.com/users/882003",
"pm_score": 2,
"selected": false,
"text": "pos double size_t size_t pos = email.find(dot);\n substr firstName = email.substr(0, pos);\n email firstName size_t pos = email.find(dot);\nif (pos == string::npos) // if no dot\n cout << \"no dot in email address\";\n"
},
{
"answer_id": 74556872,
"author": "user17443931",
"author_id": 17443931,
"author_profile": "https://Stackoverflow.com/users/17443931",
"pm_score": 0,
"selected": false,
"text": "substr() pos double int main()\n{\n string getEmail;\n \n string email, firstName, lastName;\n char dot = '.';\n cout << \"What is your email?\" << endl;\n getline(cin, email);\n \n size_t pos = email.find(dot);\n firstName = email.substr(0, pos);\n cout << firstName << endl;\n return 0;\n}\n"
},
{
"answer_id": 74561609,
"author": "rturrado",
"author_id": 260313,
"author_profile": "https://Stackoverflow.com/users/260313",
"pm_score": 0,
"selected": false,
"text": "#include <fmt/core.h>\n#include <regex>\n#include <string>\n\nint main() {\n std::regex pattern{ R\"((\\w+)\\.(\\w+)@.+)\" };\n for (std::string email : { \"john.doe@xyz.com\", \"anne.doe@abc.org\", \"foo@so.com\" }) {\n std::smatch matches{};\n if (std::regex_match(email, matches, pattern)) {\n fmt::print(\"email: '{}', first name: '{}', second name: '{}'\\n\",\n matches[0].str(), matches[1].str(), matches[2].str());\n } else {\n fmt::print(\"Warning: username does not contain a dot: '{}'.\\n\", email);\n }\n }\n}\n\n// Outputs:\n//\n// email: 'john.doe@xyz.com', first name: 'john', second name: 'doe'\n// email: 'anne.doe@abc.org', first name: 'anne', second name: 'doe'\n// Warning: username does not contain a dot: 'foo@so.com'.\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9359102/"
] |
74,556,810
|
<p>I have searched for available questions but didn't get my solution.</p>
<p>I am trying to set the height of all the elements of a horizontally overflowed container equal as that of the longest one.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
}
section{
width: 300px;
background: lightblue;
overflow: auto;
white-space: nowrap;
}
div{
display: inline-block ;
max-width: 150px;
background: lightgreen;
margin: 5px;
white-space: normal;
/* not working */
height: 100%;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<section>
<div>
hi there how are you push just IV by Rd hi TX cu
</div>
<div>
hi there how are you push just IV by Rd hi TX cu jdi HD so of fr edg of Dr edg KB hi
</div>
<div>
hi there how are you push just IV by Rd hi TX cu
</div>
</section>
</body>
</html></code></pre>
</div>
</div>
</p>
<p>As you see here, the second div is longest. The other divs should be equal to the second one.
Also, I don't need a fix height.</p>
|
[
{
"answer_id": 74556853,
"author": "john",
"author_id": 882003,
"author_profile": "https://Stackoverflow.com/users/882003",
"pm_score": 2,
"selected": false,
"text": "pos double size_t size_t pos = email.find(dot);\n substr firstName = email.substr(0, pos);\n email firstName size_t pos = email.find(dot);\nif (pos == string::npos) // if no dot\n cout << \"no dot in email address\";\n"
},
{
"answer_id": 74556872,
"author": "user17443931",
"author_id": 17443931,
"author_profile": "https://Stackoverflow.com/users/17443931",
"pm_score": 0,
"selected": false,
"text": "substr() pos double int main()\n{\n string getEmail;\n \n string email, firstName, lastName;\n char dot = '.';\n cout << \"What is your email?\" << endl;\n getline(cin, email);\n \n size_t pos = email.find(dot);\n firstName = email.substr(0, pos);\n cout << firstName << endl;\n return 0;\n}\n"
},
{
"answer_id": 74561609,
"author": "rturrado",
"author_id": 260313,
"author_profile": "https://Stackoverflow.com/users/260313",
"pm_score": 0,
"selected": false,
"text": "#include <fmt/core.h>\n#include <regex>\n#include <string>\n\nint main() {\n std::regex pattern{ R\"((\\w+)\\.(\\w+)@.+)\" };\n for (std::string email : { \"john.doe@xyz.com\", \"anne.doe@abc.org\", \"foo@so.com\" }) {\n std::smatch matches{};\n if (std::regex_match(email, matches, pattern)) {\n fmt::print(\"email: '{}', first name: '{}', second name: '{}'\\n\",\n matches[0].str(), matches[1].str(), matches[2].str());\n } else {\n fmt::print(\"Warning: username does not contain a dot: '{}'.\\n\", email);\n }\n }\n}\n\n// Outputs:\n//\n// email: 'john.doe@xyz.com', first name: 'john', second name: 'doe'\n// email: 'anne.doe@abc.org', first name: 'anne', second name: 'doe'\n// Warning: username does not contain a dot: 'foo@so.com'.\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19199587/"
] |
74,556,812
|
<p>I tried to program this code on an STM8 Controller:</p>
<pre><code>#include "Imagedata.h"
void main(void)
{
unsigned char *pArray;
pArray=IMAGE_DATA;
while(pArray<=(IMAGE_DATA+(sizeof(IMAGE_DATA)/sizeof(pArray))))
{
SPI_SendData(SPI1,*pArray++ );
}
}
</code></pre>
<p>Actually the array is much longer than this but it would take to much space here. The Array is defined in imagedata.c:</p>
<pre><code>#include "imagedata.h"
const unsigned char IMAGE_DATA[]= { 0X00,0X01,0XC8,0X00,0XC8,0X00};
</code></pre>
<p>After compiling this code I get the error message: array size unknown. This refers to the line where I put sizeof(IMAGE_DATA). I don't quiet understand what the problem is. Can anyone help?</p>
|
[
{
"answer_id": 74557882,
"author": "hyde",
"author_id": 1717300,
"author_profile": "https://Stackoverflow.com/users/1717300",
"pm_score": 0,
"selected": false,
"text": "const unsigned char *pArray = IMAGE_DATA;\nconst unsigned char * const pEnd = pArray + sizeof(IMAGE_DATA) / sizeof(*pArray);\n\nwhile(pArray < pEnd) {\n ...\n sizeof char / sizeof(*pArray) *pEnd IMAGE_DATA sizeof IMAGE_DATA pEnd char foo[] = { 33, , 34 , 35 }; // compliers counts size 3\n char foo[3];\n"
},
{
"answer_id": 74558187,
"author": "Lundin",
"author_id": 584518,
"author_profile": "https://Stackoverflow.com/users/584518",
"pm_score": 2,
"selected": false,
"text": "extern extern const unsigned char IMAGE_DATA[]; IMAGE_DATA[6] const unsigned char IMAGE_DATA[]= pArray=IMAGE_DATA; sizeof(pArray) sizeof while(pArray<= < for #include \"imagedata.h\" #include \"Imagedata.h\" // imagedata.h\n\n/* \n Normally size_t would be used for array size, but since this is STM8 I picked a \n byte type, under the assumption that size will not be larger than 256.\n*/\nconst char* image_get_data (unsigned char* size);\n // imagedata.c\n#include \"imagedata.h\"\n\nstatic const unsigned char IMAGE_DATA[]= { 0X00,0X01,0XC8,0X00,0XC8,0X00};\n\nconst char* image_get_data (unsigned char* size)\n{\n *size = (unsigned char) sizeof(IMAGE_DATA);\n return IMAGE_DATA;\n}\n // main.c\n#include \"imagedata.h\"\nvoid main(void)\n{\n const unsigned char *pArray;\n unsigned char size;\n parray = image_get_data(&size);\n\n for(unsigned char i=0; i<size; i++)\n {\n SPI_SendData(SPI1, pArray[i]);\n }\n}\n // imagedata.h\nstatic inline const char* image_get_data (unsigned char* size)\n{\n static const unsigned char IMAGE_DATA[]= { 0X00,0X01,0XC8,0X00,0XC8,0X00};\n\n *size = (unsigned char) sizeof(IMAGE_DATA);\n return IMAGE_DATA;\n}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20560622/"
] |
74,556,828
|
<p>how do I get the sum of money and spent from a list of dictionaries where</p>
<p>sum of money = (sum of money of shirt color blue and red) and (sum of money of shirt color yellow and green)</p>
<p>sum of spent = (sum of spent of shirt color blue and red) and (sum of spent of shirt color yellow and green)</p>
<p>should i make new dictionary for shirtcolor blue and red and another one for yellow and green?</p>
<pre><code>people = [{'name': 'A', 'shirtcolor':'blue', 'money':'100', spent:'50'}, {'name': 'B', 'shirtcolor':'red', 'money':'70', spent:'50'}, {'name': 'C', 'shirtcolor':'yellow', 'money':'100', spent:'70'}, {'name': 'D', 'shirtcolor':'blue', 'money':'200', spent:'110'},{'name': 'E', 'shirtcolor':'red', 'money':'130', spent:'50'}, {'name': 'F', 'shirtcolor':'yellow', 'money':'200', spent:'70'},{'name': 'G', 'shirtcolor':'green', 'money':'100', spent:'50'}]
</code></pre>
<p>expected output:</p>
<pre><code>Total Money: 500 and 400
Total spent: 260 and 190
</code></pre>
|
[
{
"answer_id": 74557061,
"author": "Johs",
"author_id": 14993329,
"author_profile": "https://Stackoverflow.com/users/14993329",
"pm_score": 0,
"selected": false,
"text": "money_blue = 0\nfor i in range(len(people)):\n if people[i]['shirtcolor'] == \"blue\":\n money += int(people[i]['money'])\n \n\nprint(money_blue)\n"
},
{
"answer_id": 74557077,
"author": "Matthias",
"author_id": 1209921,
"author_profile": "https://Stackoverflow.com/users/1209921",
"pm_score": 1,
"selected": false,
"text": "people = [{'name': 'A', 'shirtcolor': 'blue', 'money': '100', 'spent': '50'},\n {'name': 'B', 'shirtcolor': 'red', 'money': '70', 'spent': '50'},\n {'name': 'C', 'shirtcolor': 'yellow', 'money': '100', 'spent': '70'},\n {'name': 'D', 'shirtcolor': 'blue', 'money': '200', 'spent': '110'},\n {'name': 'E', 'shirtcolor': 'red', 'money': '130', 'spent': '50'},\n {'name': 'F', 'shirtcolor': 'yellow', 'money': '200', 'spent': '70'},\n {'name': 'G', 'shirtcolor': 'green', 'money': '100', 'spent': '50'}]\n color_sum = dict()\nfor entry in people:\n if entry['shirtcolor'] not in color_sum:\n color_sum[entry['shirtcolor']] = {'money':0, 'spent':0}\n color_sum[entry['shirtcolor']]['money'] += int(entry['money'])\n color_sum[entry['shirtcolor']]['spent'] += int(entry['spent'])\n defaultdict from collections import defaultdict\n\ncolor_sum = defaultdict(lambda: {'money':0, 'spent':0})\nfor entry in people:\n color_sum[entry['shirtcolor']]['money'] += int(entry['money'])\n color_sum[entry['shirtcolor']]['spent'] += int(entry['spent'])\n color_sum {'blue': {'money': 300, 'spent': 160}, \n 'red': {'money': 200, 'spent': 100}, \n 'yellow': {'money': 300, 'spent': 140}, \n 'green': {'money': 100, 'spent': 50}}\n money_red_blue = color_sum[\"red\"][\"money\"] + color_sum[\"blue\"][\"money\"]\nmoney_yellow_green = color_sum[\"yellow\"][\"money\"]+ color_sum[\"green\"][\"money\"]\nprint(f'Total money: {money_red_blue} and {money_yellow_green}')\n Total money: 500 and 400 money = 0\nfor k, v in color_sum.items():\n if k not in {'green', 'yellow'}:\n money += v['money']\nprint(money)\n sum money = sum(v['money'] for k, v in color_sum.items() if k not in {'green', 'yellow'})\nprint(money)\n"
},
{
"answer_id": 74557268,
"author": "Suriyakani B",
"author_id": 5558355,
"author_profile": "https://Stackoverflow.com/users/5558355",
"pm_score": 0,
"selected": false,
"text": "product_list=[\n {\"name\": \"A\", \"shirtcolor\":\"blue\", \"money\":\"100\", \"spent\":\"50\"},\n {\"name\": \"B\", \"shirtcolor\":\"red\", \"money\":\"70\", \"spent\":\"50\"}, \n {\"name\": \"C\", \"shirtcolor\":\"yellow\", \"money\":\"100\", \"spent\":\"70\"},\n {\"name\": \"D\", \"shirtcolor\":\"blue\", \"money\":\"200\", \"spent\":\"110\"},\n {\"name\": \"E\", \"shirtcolor\":\"red\", \"money\":\"130\", \"spent\":\"50\"},\n {\"name\": \"F\", \"shirtcolor\":\"yellow\", \"money\":\"200\", \"spent\":\"70\"},\n {\"name\": \"G\", \"shirtcolor\":\"green\", \"money\":\"100\", \"spent\":\"50\"}\n]\n\nprint(product_list)\n\n#sum of spent for blue and red\nblueSpent = sum([int(x[\"spent\"]) for x in product_list if x[\"shirtcolor\"]==\"blue\" or x[\"shirtcolor\"]==\"red\"])\nprint(blueSpent)\n\n#sum of spent for green and yellow\ngreenSpent = sum([int(x[\"spent\"]) for x in product_list if x[\"shirtcolor\"]==\"green\" or x[\"shirtcolor\"]==\"yellow\"])\nprint(greenSpent)\n\n#sum of spent for blue and red\nblueMoney = sum([int(x[\"money\"]) for x in product_list if x[\"shirtcolor\"]==\"blue\" or x[\"shirtcolor\"]==\"red\"])\nprint(blueMoney)\n\n#sum of money for green and yellow\ngreenMoney = sum([int(x[\"money\"]) for x in product_list if x[\"shirtcolor\"]==\"green\" or x[\"shirtcolor\"]==\"yellow\"])\nprint(greenMoney)\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556828",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20196165/"
] |
74,556,859
|
<p>I need to break monthly membership data by single complete month and it looked simple, but then I found that there are not complete month segments in different flavors so it became more complex.<br />
Do you think it's possible to achieve in single step (without breaking input by complete/non complete month ) ?
I tried and looks like in this case I need to modify eStart/eEnd dates which I don't want to deal. Trying to keep input intact.</p>
<p>Below is my self inclusive script setup, input and desired output.
Current code does only job for complete month, do you think it's possible to include also all head and tails ??.</p>
<pre><code> --- SQL Server 2019
SELECT DISTINCT t.*, '--' f, d.*
FROM #t t
JOIN #date_dim d ON d.CalDate BETWEEN eStart AND eEnd
AND d.dd = 1
JOIN #date_dim d2 ON d2.CalDate BETWEEN eStart AND eEnd
AND d2.dd = d2.mm_Last_DD
/* ----- data prep part
SELECT * INTO #t FROM ( -- DROP TABLE IF EXISTS #t
SELECT 100 ID, CAST('2022-03-02' AS DATE) eStart , CAST('2022-03-15' AS DATE) eEnd, '1 Same Month island' note
UNION SELECT 200, '2022-03-01' , '2022-03-27', '2 Same Month Start'
UNION SELECT 300, '2022-03-08' , '2022-03-31', '3 Same Month End'
UNION SELECT 440, '2022-01-15' , '2022-02-28', '4 Diff Month End'
UNION SELECT 550, '2022-03-08' , '2022-05-10', '5 Diff Month Island'
UNION SELECT 660, '2022-03-1' , '2022-6-15', '6 Diff Month Start'
) b -- SELECT * FROM #t
;WITH cte AS ( --DROP TABLE IF EXISTS #date_dim
SELECT TOP 180
CAST('1/1/2022' AS DATETIME) + ROW_NUMBER() OVER(ORDER BY number) CalDate
FROM master..spt_values )
SELECT CalDate
, MONTH(Caldate) MM, DATEADD(dd, -( DAY( Caldate ) -1 ), Caldate) MM_start, EOMONTH(Caldate) MM_End, day(Caldate) dd, DAY(EOMONTH(Caldate)) mm_Last_DD
, CONVERT(nvarchar(6), Caldate, 112) YYYYMM, YEAR(CalDate) YYYY
,CASE WHEN CalDate = EOMONTH(Caldate) THEN 'Y' ELSE 'N' END month_End_YN
INTO #date_dim ---- SELECT * FROM #date_dim
FROM cte
*/
</code></pre>
<p><a href="https://i.stack.imgur.com/7QaB8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7QaB8.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74557061,
"author": "Johs",
"author_id": 14993329,
"author_profile": "https://Stackoverflow.com/users/14993329",
"pm_score": 0,
"selected": false,
"text": "money_blue = 0\nfor i in range(len(people)):\n if people[i]['shirtcolor'] == \"blue\":\n money += int(people[i]['money'])\n \n\nprint(money_blue)\n"
},
{
"answer_id": 74557077,
"author": "Matthias",
"author_id": 1209921,
"author_profile": "https://Stackoverflow.com/users/1209921",
"pm_score": 1,
"selected": false,
"text": "people = [{'name': 'A', 'shirtcolor': 'blue', 'money': '100', 'spent': '50'},\n {'name': 'B', 'shirtcolor': 'red', 'money': '70', 'spent': '50'},\n {'name': 'C', 'shirtcolor': 'yellow', 'money': '100', 'spent': '70'},\n {'name': 'D', 'shirtcolor': 'blue', 'money': '200', 'spent': '110'},\n {'name': 'E', 'shirtcolor': 'red', 'money': '130', 'spent': '50'},\n {'name': 'F', 'shirtcolor': 'yellow', 'money': '200', 'spent': '70'},\n {'name': 'G', 'shirtcolor': 'green', 'money': '100', 'spent': '50'}]\n color_sum = dict()\nfor entry in people:\n if entry['shirtcolor'] not in color_sum:\n color_sum[entry['shirtcolor']] = {'money':0, 'spent':0}\n color_sum[entry['shirtcolor']]['money'] += int(entry['money'])\n color_sum[entry['shirtcolor']]['spent'] += int(entry['spent'])\n defaultdict from collections import defaultdict\n\ncolor_sum = defaultdict(lambda: {'money':0, 'spent':0})\nfor entry in people:\n color_sum[entry['shirtcolor']]['money'] += int(entry['money'])\n color_sum[entry['shirtcolor']]['spent'] += int(entry['spent'])\n color_sum {'blue': {'money': 300, 'spent': 160}, \n 'red': {'money': 200, 'spent': 100}, \n 'yellow': {'money': 300, 'spent': 140}, \n 'green': {'money': 100, 'spent': 50}}\n money_red_blue = color_sum[\"red\"][\"money\"] + color_sum[\"blue\"][\"money\"]\nmoney_yellow_green = color_sum[\"yellow\"][\"money\"]+ color_sum[\"green\"][\"money\"]\nprint(f'Total money: {money_red_blue} and {money_yellow_green}')\n Total money: 500 and 400 money = 0\nfor k, v in color_sum.items():\n if k not in {'green', 'yellow'}:\n money += v['money']\nprint(money)\n sum money = sum(v['money'] for k, v in color_sum.items() if k not in {'green', 'yellow'})\nprint(money)\n"
},
{
"answer_id": 74557268,
"author": "Suriyakani B",
"author_id": 5558355,
"author_profile": "https://Stackoverflow.com/users/5558355",
"pm_score": 0,
"selected": false,
"text": "product_list=[\n {\"name\": \"A\", \"shirtcolor\":\"blue\", \"money\":\"100\", \"spent\":\"50\"},\n {\"name\": \"B\", \"shirtcolor\":\"red\", \"money\":\"70\", \"spent\":\"50\"}, \n {\"name\": \"C\", \"shirtcolor\":\"yellow\", \"money\":\"100\", \"spent\":\"70\"},\n {\"name\": \"D\", \"shirtcolor\":\"blue\", \"money\":\"200\", \"spent\":\"110\"},\n {\"name\": \"E\", \"shirtcolor\":\"red\", \"money\":\"130\", \"spent\":\"50\"},\n {\"name\": \"F\", \"shirtcolor\":\"yellow\", \"money\":\"200\", \"spent\":\"70\"},\n {\"name\": \"G\", \"shirtcolor\":\"green\", \"money\":\"100\", \"spent\":\"50\"}\n]\n\nprint(product_list)\n\n#sum of spent for blue and red\nblueSpent = sum([int(x[\"spent\"]) for x in product_list if x[\"shirtcolor\"]==\"blue\" or x[\"shirtcolor\"]==\"red\"])\nprint(blueSpent)\n\n#sum of spent for green and yellow\ngreenSpent = sum([int(x[\"spent\"]) for x in product_list if x[\"shirtcolor\"]==\"green\" or x[\"shirtcolor\"]==\"yellow\"])\nprint(greenSpent)\n\n#sum of spent for blue and red\nblueMoney = sum([int(x[\"money\"]) for x in product_list if x[\"shirtcolor\"]==\"blue\" or x[\"shirtcolor\"]==\"red\"])\nprint(blueMoney)\n\n#sum of money for green and yellow\ngreenMoney = sum([int(x[\"money\"]) for x in product_list if x[\"shirtcolor\"]==\"green\" or x[\"shirtcolor\"]==\"yellow\"])\nprint(greenMoney)\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10242281/"
] |
74,556,864
|
<p>I just want to clear out that I am new to coding.
I am trying to solve a problem set that counts the occurrence of characters in a string and prints out the 3 most reoccurring characters</p>
<p>Heres the code I wrote</p>
<pre><code> s = input().lower()
b = []
for i in s:
templst = []
templst.append(i)
templst.append(s.count(i))
if templst not in b:
b.append(templst)
final = sorted(b, key=itemgetter(1),reverse=True)
print (final)
for i in final[:3]:
print(*i, sep=" ")
</code></pre>
<p>now if I gave it an input of</p>
<pre><code>szrmtbttyyaymadobvwniwmozojggfbtswdiocewnqsjrkimhovimghixqryqgzhgbakpncwupcadwvglmupbexijimonxdowqsjinqzytkooacwkchatuwpsoxwvgrrejkukcvyzbkfnzfvrthmtfvmbppkdebswfpspxnelhqnjlgntqzsprmhcnuomrvuyolvzlni
</code></pre>
<p>the output of final would be</p>
<pre><code>[['o', 12], ['m', 11], ['w', 11], ['n', 11], ['t', 9], ['v', 9], ['i', 9], ['p', 9], ['s', 8], ['z', 8], ['r', 8], ['b', 8], ['g', 8], ['k', 8], ['y', 7], ['c', 7], ['q', 7], ['h', 7], ['a', 6], ['j', 6], ['u', 6], ['d', 5], ['f', 5], ['e', 5], ['x', 5], ['l', 5]
</code></pre>
<p>so, the most occurring characters are</p>
<pre><code>['o', 12], ['m', 11], ['w', 11], ['n', 11]
</code></pre>
<p>instead of</p>
<pre><code>['o', 12], ['m', 11], ['n', 11], ['w', 11]
</code></pre>
<p>and since "m", "w" and "n" occurred equal times how do I sort the first element alphabetically while having the second element reversely sorted</p>
|
[
{
"answer_id": 74556973,
"author": "Ahmed Aredah",
"author_id": 5800005,
"author_profile": "https://Stackoverflow.com/users/5800005",
"pm_score": 2,
"selected": true,
"text": "final= Sorted(b, key = lambda e: (-e[1], e[0]))\n"
},
{
"answer_id": 74557221,
"author": "cafce25",
"author_id": 442760,
"author_profile": "https://Stackoverflow.com/users/442760",
"pm_score": 0,
"selected": false,
"text": "b.sort(key=lambda x: x[0])\nb.sort(key=lambda x: x[1], reverse=True)\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20501260/"
] |
74,556,882
|
<p>I'm writing java selenium. Everything is ok, but when the new tab is opened, the scrool code I added does not open in the new tab? How can I include the codes I wrote in the new tab?</p>
<p>I want the page to go down in the new tab and click on the image I want</p>
|
[
{
"answer_id": 74557026,
"author": "wowcode",
"author_id": 20588290,
"author_profile": "https://Stackoverflow.com/users/20588290",
"pm_score": 1,
"selected": false,
"text": " System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\*\\\\Desktop\\\\driver\\\\chromedriver_win32\\\\chromedriver.exe\");\n WebDriver driver;\n driver = new ChromeDriver();\n driver.manage().window().maximize();\n driver.get(\"https://www.hepsiburada.com/\");\n Thread.sleep(5000);\n driver.findElement(By.xpath(\"//button[text()='Kabul Et']\")).click();\n ////input[@name='query_text']\n driver.findElement(By.xpath(\"//input[@class='desktopOldAutosuggestTheme-UyU36RyhCTcuRs_sXL9b']\")).sendKeys(\"HBCV00000ODHHV\"); ////bu arama çubuğuna yazıyor\n Thread.sleep(2000);\n driver.findElement(By.xpath(\"//input[@class='desktopOldAutosuggestTheme-UyU36RyhCTcuRs_sXL9b']\")).sendKeys(Keys.ENTER); ////bu tıklattırıyor\n Thread.sleep(5000);\n JavascriptExecutor jse = (JavascriptExecutor)driver;\n jse.executeScript(\"scroll(0, 300);\");\n Thread.sleep(5000); \n driver.findElement(By.xpath(\"//div[@type='comfort']\")).click();\n Thread.sleep(5000);\n JavascriptExecutor jsx = (JavascriptExecutor)driver;\n jsx.executeScript(\"scroll(0, 300);\");\n"
},
{
"answer_id": 74559827,
"author": "Alex Karamfilov",
"author_id": 7031148,
"author_profile": "https://Stackoverflow.com/users/7031148",
"pm_score": 0,
"selected": false,
"text": " \n public static void main(String[] args) {\n WebDriverManager.chromedriver().setup();\n WebDriver driver = new ChromeDriver();\n driver.get(\"https://mrslavchev.com\");\n JavascriptExecutor js = (JavascriptExecutor) driver;\n //This will scroll the page till the element is found\n WebElement footer = driver.findElement(By.xpath(\"//div[@class='site-info-text']\"));\n js.executeScript(\"arguments[0].scrollIntoView();\", footer);\n }\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20588290/"
] |
74,556,929
|
<p>I am trying to run a PowerShell script via SMB connection, but it does not run the script:</p>
<pre><code>smbclient hostname -U username%password -c "Powershell -File run.ps1"
</code></pre>
<p>It fails saying:</p>
<pre><code>Powershell: command not found
</code></pre>
<p>I want to run a PowerShell script via SMB on a remote server.</p>
<p>linux(from) -> Windows(to)</p>
|
[
{
"answer_id": 74557949,
"author": "stackprotector",
"author_id": 11942268,
"author_profile": "https://Stackoverflow.com/users/11942268",
"pm_score": 0,
"selected": false,
"text": "-c --command smbclient smb: \\> ?\n? allinfo altname archive backup \nblocksize cancel case_sensitive cd chmod \nchown close del deltree dir \ndu echo exit get getfacl \ngeteas hardlink help history iosize \nlcd link lock lowercase ls \nl mask md mget mkdir \nmore mput newer notify open \nposix posix_encrypt posix_open posix_mkdir posix_rmdir \nposix_unlink posix_whoami print prompt put \npwd q queue quit readlink \nrd recurse reget rename reput \nrm rmdir showacls setea setmode \nscopy stat symlink tar tarmode \ntimeout translate unlock volume vuid \nwdel logon listconnect showconnect tcon \ntdis tid utimes logoff .. \n!\n ! <SHELL_COMMAND>"
},
{
"answer_id": 74566731,
"author": "Ralph Sch",
"author_id": 20551048,
"author_profile": "https://Stackoverflow.com/users/20551048",
"pm_score": 0,
"selected": false,
"text": "Invoke-Command PSSession -ComputerName <remotecomputer> -ArgumentList PARAM()"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20469205/"
] |
74,556,936
|
<p>I was trying to get all pdf files from device storage and it's done now I want to show the size of that file in listview. builder trailing.</p>
<p><strong>path of my file</strong></p>
<pre><code>files[index].path
</code></pre>
<p><strong>print of files[index].path is</strong>
/storage/emulated/0/android/data/......../name.pdf</p>
<p><strong>this is what im trying</strong></p>
<pre><code> title: Text(files[index].path.split('/').last),
trailing: Text(files[index].path.length()),
</code></pre>
|
[
{
"answer_id": 74557039,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 2,
"selected": true,
"text": "File length() var size = await files[index].length();\nprint(size);\n var size = await File(files[index].path).length();\nprint(size);\n Text FutureBuilder trailing: FutureBuilder<int>(\n builder: (context, snapshot) {\n return Text(snapshot.data.toString());\n },\n future: files[index].length(),\n),\n"
},
{
"answer_id": 74557212,
"author": "Suraj Mahendrakar",
"author_id": 20588006,
"author_profile": "https://Stackoverflow.com/users/20588006",
"pm_score": 0,
"selected": false,
"text": "int sizeInBytes = File(files[index].path).lengthSync();\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20378705/"
] |
74,556,948
|
<p>So, I'm getting the following error:</p>
<p><strong>SwiftUI/EnvironmentObject.swift:70: Fatal error: No ObservableObject of type AppViewModel found. A View.environmentObject(_:) for AppViewModel may be missing as an ancestor of this view.</strong></p>
<p>However, I <em>do actually in fact</em> have <code>.environmentObject(AppViewModel())</code> on every preview and I'm not sure why.</p>
<p>Here's the code in question:</p>
<pre><code>import SwiftUI
struct SignUpView: View {
@State var email = ""
@State var password = ""
@EnvironmentObject var model:AppViewModel
var body: some View {
ZStack {
Color.theme.blue
RoundedRectangle(cornerRadius: 30, style: .continuous)
.foregroundStyle(LinearGradient(colors: [.orange, .red], startPoint: .topLeading, endPoint: .bottomTrailing))
.frame(width: 1000, height: 475)
.rotationEffect(.degrees(15))
.offset(x: 20)
VStack(spacing: 20) {
Image("logo")
.resizable()
.scaledToFill()
.frame(width: 100)
.offset(y: 10)
Text("Welcome")
.foregroundColor(.white)
.font(Font.custom("Poppins-Bold", size: 44))
Text("Please Sign Up")
.foregroundColor(Color.theme.blue)
.font(Font.custom("Poppins-Regular", size: 22))
.offset(y:-20)
// Email TextField
TextField("", text: $email)
.disableAutocorrection(true)
.autocapitalization(.none)
.foregroundColor(.white)
.textFieldStyle(.plain)
.placeholder(when: email.isEmpty) {
Text("Email Address")
.foregroundColor(.white)
.font(Font.custom("Poppins-Light", size: 20))
}
// Email TextBox
Rectangle()
.frame(width:350, height: 1)
.foregroundColor(.white)
.padding(.top, -5)
// Password TextField
SecureField("", text: $password)
.disableAutocorrection(true)
.autocapitalization(.none)
.foregroundColor(.white)
.textFieldStyle(.plain)
.placeholder(when: password.isEmpty) {
Text("Password")
.foregroundColor(.white)
.font(Font.custom("Poppins-Light", size: 20))
}
// Password TextBox
Rectangle()
.frame(width:350, height: 1)
.foregroundColor(.white)
.padding(.top, -5)
Button {
guard !email.isEmpty, !password.isEmpty else {
return
}
model.signUp(email: email, password: password)
} label: {
Text("Sign Up")
.frame(width: 200, height: 40)
.background(
Color.theme.blue
// RoundedRectangle(cornerRadius: 10, style: .continuous)
// .fill(.linearGradient(colors: [.red, .orange], startPoint: .topTrailing, endPoint: .bottomTrailing))
)
.cornerRadius(10)
.foregroundColor(.white)
.font(Font.custom("Poppins-Medium", size: 18))
}
Spacer()
// Login Link
HStack {
Text("Already Have An Account?")
.foregroundColor(.white)
.font(Font.custom("Poppins-Medium", size: 18))
NavigationLink("Login", destination: SignInView())
.foregroundColor(.orange)
.font(Font.custom("Poppins-Medium", size: 18))
}.offset(y: 100)
}
.frame(width: 350, height: 60)
}.ignoresSafeArea()
}
}
struct SignUpView_Previews: PreviewProvider {
static var previews: some View {
SignUpView().environmentObject(AppViewModel())
}
}
</code></pre>
<p>Here's my AppViewModel:</p>
<pre><code>
import Foundation
import Firebase
class AppViewModel: ObservableObject {
let auth = Auth.auth()
@Published var signedIn = false
var isSignedIn: Bool {
// If it does NOT equal nil, then this means it is TRUE that, YES, we are indeed signed in. Yay!
return auth.currentUser != nil
}
// If you want to pass information, you have to make placeholders for the variables to be passed in.
func signUp(email: String, password: String) {
auth.createUser(withEmail: email, password: password) { [weak self] result, error in
guard result != nil, error == nil else {
return
}
DispatchQueue.main.async {
// Successfully signed up
self?.signedIn = true
}
}
}
func login(email: String, password: String) {
auth.signIn(withEmail: email, password: password) { [weak self] result, error in
guard result != nil, error == nil else {
return
}
DispatchQueue.main.async {
// Successfully signed in
self?.signedIn = true
}
// if error != nil {
// print(error!.localizedDescription)
// }
}
}
func signOut() {
try? auth.signOut()
self.signedIn = false
}
}
</code></pre>
<p>Please let me know if I need to include more code...? Thanks in advance! (I'm a newbie.)</p>
|
[
{
"answer_id": 74557039,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 2,
"selected": true,
"text": "File length() var size = await files[index].length();\nprint(size);\n var size = await File(files[index].path).length();\nprint(size);\n Text FutureBuilder trailing: FutureBuilder<int>(\n builder: (context, snapshot) {\n return Text(snapshot.data.toString());\n },\n future: files[index].length(),\n),\n"
},
{
"answer_id": 74557212,
"author": "Suraj Mahendrakar",
"author_id": 20588006,
"author_profile": "https://Stackoverflow.com/users/20588006",
"pm_score": 0,
"selected": false,
"text": "int sizeInBytes = File(files[index].path).lengthSync();\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2596591/"
] |
74,556,969
|
<p>Say I had an input of:</p>
<pre><code>john bob alex liam # names
15 17 16 19 # age
70 92 70 100 # iq
</code></pre>
<p>How do I make it so that john is assigned to age 15 and iq of 70, bob is assigned to age 17 and iq of 92, alex is assigned to age 16 and iq of 70, and liam is assigned to age 19 and iq of 100?</p>
<p>Right now I have:</p>
<pre><code>names = input().split()
</code></pre>
<p>From there, I know have to make 2 more variables for age and iq and assign them to inputs as well but how do I assign those numbers to the names in the same order?</p>
|
[
{
"answer_id": 74557014,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 3,
"selected": true,
"text": "names = \"john bob alex liam\"\nages = \"15 17 16 19\"\niq = \"70 92 70 100\"\nlist_a = names.split()\nlist_b = ages.split()\nlist_c = iq.split()\nzipped = zip(list_a, list_b, list_c)\nzipped_list = list(zipped) \n\nprint(zipped_list)\n [('john', '15', '70'), ('bob', '17', '92'), ('alex', '16', '70'), ('liam', '19', '100')]\n"
},
{
"answer_id": 74557015,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 1,
"selected": false,
"text": "text = '''john bob alex liam # names\n15 17 16 19 # age\n70 92 70 100 # iq'''\n\nd = {key: [age, iq] for key, age, iq in \n zip(*(s.split() for s in \n (s.split(' #', 1)[0] for s in \n text.split('\\n'))))}\n {'john': ['15', '70'],\n 'bob': ['17', '92'],\n 'alex': ['16', '70'],\n 'liam': ['19', '100']}\n key: [int(age), int(iq)] out = list(zip(*(s.split() for s in \n (s.split(' #', 1)[0] for s in text.split('\\n')))))\n [('john', '15', '70'),\n ('bob', '17', '92'),\n ('alex', '16', '70'),\n ('liam', '19', '100')]\n"
},
{
"answer_id": 74557019,
"author": "lemmgua",
"author_id": 20281146,
"author_profile": "https://Stackoverflow.com/users/20281146",
"pm_score": 0,
"selected": false,
"text": "names ages iqs names = [\"John\", \"Bob\", \"Alex\", \"Liam\"]\nages = [15, 17, 16, 19]\niqs = [70, 92, 70, 100]\n print(names[0], ages[0], iqs[0])\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20066884/"
] |
74,556,998
|
<p><strong>Requirement:</strong></p>
<p>In a BASH script,</p>
<p>...iterate over an array of environment variable names as shown below:</p>
<p><code>arr = ('env_var1' 'env_var2' 'env_var3')</code></p>
<p>and, using <a href="https://stedolan.github.io/jq/" rel="nofollow noreferrer">jq</a> generate a JSON of environment variable name-value pairs like below:</p>
<pre class="lang-json prettyprint-override"><code>{
"env_var1": "env_var1_value_is_1",
"env_var2": "env_var2_value_is_2",
"env_var3": "env_var3_value_is_3"
}
</code></pre>
<p><strong>Current approach:</strong>
Using this <a href="https://stackoverflow.com/questions/61807377/in-bash-create-json-object-of-key-filename-and-value-file-contents-given-sequen?noredirect=1&lq=1">stackoverflow question's solution</a> as a reference</p>
<pre><code>printf '%s\n' "${arr[@]}" |
xargs -L 1 -I {} jq -sR --arg key {} '{ ($key): . }' | jq -s 'add'
</code></pre>
<p>where <code>arr</code> array contains the environment variable names for which I want the values, however I am unable to interpolate the <code>${environment_variable_name}</code> into the JSON's <code>value</code> in each key-value pair</p>
|
[
{
"answer_id": 74557113,
"author": "hobbs",
"author_id": 152948,
"author_profile": "https://Stackoverflow.com/users/152948",
"pm_score": 3,
"selected": true,
"text": "jq -n '$ARGS.positional | map({ (.): env[.] }) | add' --args \"${arr[@]}\"\n $ARGS.positional --args env"
},
{
"answer_id": 74558074,
"author": "peak",
"author_id": 997358,
"author_profile": "https://Stackoverflow.com/users/997358",
"pm_score": 1,
"selected": false,
"text": "arr printf printf '%s\\n' \"${arr[@]}\" | jq -nR '[inputs | {(.): env[.] }] | add'\n gojq fq"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74556998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9197213/"
] |
74,557,013
|
<p>Asking for help:</p>
<pre><code>Data: map (nullable = true)
|-- key: string
|-- value: map (valueContainsNull = true)
| |-- key : string
| |-- value : string (valueContainsNull = true) reffer you
</code></pre>
<p>I reffer you below link
<a href="https://stackoverflow.com/questions/41806914/passing-a-map-with-struct-type-key-into-a-spark-udf?newreg=bfa1fe2c5a044d16b2d1ceb82a3be88e">Passing a map with struct-type key into a Spark UDF</a>
and created one udf to concat string:</p>
<pre><code>val myUDF1 = udf((inputMapping:Map[String,Row]) => inputMapping
.map{case(key,value)=>(key, (value.getString(0),value.getString(1)))}
.map{ case (key,(i1,i2))=> (key,(i1 + i2)) }
)
df.withColumn("udfResult", myUDF($"Data")).show()
</code></pre>
<p>Same thing I want to do but instead of adding integer, I want to delete key from the values which is of string type. how can I Archive same I tried this but getting error
Caused by: java.lang.ClassCastException: class java.lang.String cannot be cast to class org.apache.spark.sql.Row (java.lang.String is in module java.base of loader 'bootstrap'; org.apache.spark.sql.Row is in unnamed module of loader 'app')</p>
<p>I want to delete specific key from the vale mapType nested column in outer map:</p>
<pre><code>Data: map (nullable = true)
|-- key: string
|--** value: map (valueContainsNull = true)**
| |-- key : string
| |-- value : string (valueContainsNull = true) reffer you
</code></pre>
|
[
{
"answer_id": 74557113,
"author": "hobbs",
"author_id": 152948,
"author_profile": "https://Stackoverflow.com/users/152948",
"pm_score": 3,
"selected": true,
"text": "jq -n '$ARGS.positional | map({ (.): env[.] }) | add' --args \"${arr[@]}\"\n $ARGS.positional --args env"
},
{
"answer_id": 74558074,
"author": "peak",
"author_id": 997358,
"author_profile": "https://Stackoverflow.com/users/997358",
"pm_score": 1,
"selected": false,
"text": "arr printf printf '%s\\n' \"${arr[@]}\" | jq -nR '[inputs | {(.): env[.] }] | add'\n gojq fq"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74557013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20587599/"
] |
74,557,022
|
<p>I'm wondering how to clear a timeout, which is set in an onclick event in React.
I'm aware you can easily cancel timeouts, when they are set in 'useEffect', but how about this use case?</p>
<pre><code>export default function SomeComponent() {
const onClick = () => {
setTimeout(() => {
// dome some logic like API calls,
// which should be terminated, in case the component
// is unmounted
}, 2_500)
}
return (
<div><button onClick={onClick}>Click me!</button></div>
)
}
</code></pre>
|
[
{
"answer_id": 74557180,
"author": "Amirhossein",
"author_id": 11342834,
"author_profile": "https://Stackoverflow.com/users/11342834",
"pm_score": 0,
"selected": false,
"text": "export default function SomeComponent() {\n const [timeoutInstance, setTimeoutInstance] = useState(null);\n const onClick = () => {\n const timeout = setTimeout(() => {\n // dome some logic like API calls,\n // which should be terminated, in case the component\n // is unmounted\n }, 2_500);\n setTimeoutInstance(timeout);\n }\n\n useEffect(() => {\n return () => {\n if(timeoutInstance) {\n clearTimeout(timeoutInstance);\n setTimeoutInstance(null);\n }\n }\n }, []);\n\n return (\n <div><button onClick={onClick}>Click me!</button></div>\n )\n}\n"
},
{
"answer_id": 74557188,
"author": "TSxo",
"author_id": 20313186,
"author_profile": "https://Stackoverflow.com/users/20313186",
"pm_score": 2,
"selected": true,
"text": "\n/* Code taken from MDN Docs */\nconst alarm = {\n remind(aMessage) {\n alert(aMessage);\n this.timeoutID = undefined;\n },\n\n setup() {\n if (typeof this.timeoutID === 'number') {\n this.cancel();\n }\n\n this.timeoutID = setTimeout((msg) => {\n this.remind(msg);\n }, 1000, 'Wake up!');\n },\n\n cancel() {\n clearTimeout(this.timeoutID);\n }\n};\n\n/* Clear timeout on component unmount */\nuseEffect(() => {\n return () => {\n alarm.cancel()\n }\n}, [alarm])\n\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74557022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12039643/"
] |
74,557,045
|
<p>I have this function</p>
<pre><code> export const getColor = (color: string): string => colors[color] || colors.white;
</code></pre>
<p>but I get warning line under <code>colors[color] || colors.white</code> saying that <code>Unsafe return of an any typed value</code>
I made sure that this method accepts string and returns string but I don't know what is the exact problem + it's forbidden to use <code>any</code></p>
<pre><code>export const colors = {
'dark-grey': '#606060',
'light-grey': '#909090',
'slate-grey': '#7889a0',
'olive-green': '#8fd683',
'light-blue': '#0371ff',
'dark-gray': '#4b6c89',
'blue-700-new': 'var(--color-brand-primary-default-new)',
azure: '#1676ff',
blue: '#1676ff',
white: '#fff',
black: '#000',
brandPrimaryDefault: 'var(--color-brand-primary-default-new)',
brandPrimaryLight: 'var(--color-brand-primary-light-new)',
naturalGrayDarker2: 'var(--color-natural-gray-darker-2)',
};
</code></pre>
|
[
{
"answer_id": 74557107,
"author": "lpizzinidev",
"author_id": 13211263,
"author_profile": "https://Stackoverflow.com/users/13211263",
"pm_score": 2,
"selected": false,
"text": "colors export const colors: { [key: string]: string; } = {\n 'dark-grey': '#606060',\n 'light-grey': '#909090',\n 'slate-grey': '#7889a0',\n 'olive-green': '#8fd683',\n 'light-blue': '#0371ff',\n 'dark-gray': '#4b6c89',\n 'blue-700-new': 'var(--color-brand-primary-default-new)',\n azure: '#1676ff',\n blue: '#1676ff',\n white: '#fff',\n black: '#000',\n brandPrimaryDefault: 'var(--color-brand-primary-default-new)',\n brandPrimaryLight: 'var(--color-brand-primary-light-new)',\n naturalGrayDarker2: 'var(--color-natural-gray-darker-2)',\n};\n"
},
{
"answer_id": 74557138,
"author": "nate-kumar",
"author_id": 9987590,
"author_profile": "https://Stackoverflow.com/users/9987590",
"pm_score": 0,
"selected": false,
"text": "colors string export const colors = {\n 'dark-grey': '#606060',\n 'light-grey': '#909090',\n 'slate-grey': '#7889a0',\n 'olive-green': '#8fd683',\n 'light-blue': '#0371ff',\n 'dark-gray': '#4b6c89',\n 'blue-700-new': 'var(--color-brand-primary-default-new)',\n azure: '#1676ff',\n blue: '#1676ff',\n white: '#fff',\n black: '#000',\n brandPrimaryDefault: 'var(--color-brand-primary-default-new)',\n brandPrimaryLight: 'var(--color-brand-primary-light-new)',\n naturalGrayDarker2: 'var(--color-natural-gray-darker-2)',\n};\n\nexport type Color = keyof typeof colors // 'dark-grey' | 'light-grey' | ...\nexport const getColor = (color: Color): string => colors[color] || colors.white;\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74557045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10692884/"
] |
74,557,050
|
<p>wanted to traverse in json body and get values from list using powershell.</p>
<p>json file</p>
<pre><code>{
"TopicPropProfiles": [
{
"TP1":{
"enable-duplicate-detection": true,
"enable-batched-operations": true,
"enable-ordering": true
},
"TP2":{
"max-delivery-count": 3,
"enable-batched-operations": true
}
}
],
"SubPropProfiles": [
{
"SP1":{
"enable-duplicate-detection": true,
"max-size": 1024
},
"SP2":{
"max-delivery-count": 3,
"enable-batched-operations": true,
"enable-session": false
}
}
],
"Topics":[
{
"TopicName": "topic1",
"SubNames": ["sub1","sub2","sub3"],
"TopicPropertyProfile": "TP1",
"SubPropertyProfile": "SP2"
},
{
"TopicName": "topic2",
"SubNames": ["sub4","sub5","sub6"],
"TopicPropertyProfile": "TP2",
"SubPropertyProfile": "SP1"
}
]
}
</code></pre>
<p>powershell --getting file from somepath($profilepath)</p>
<pre><code>$profilejson = Get-Content -Raw $profilePath | ConvertFrom-Json;
$profileObject = [PSCustomObject]$profilejson;
$TopicProps=$profileObject.TopicPropProfiles.**TP1**;
Write-Host $TopicProps.'enable-duplicate-detection'
</code></pre>
<p>Wanted to get fields values under TP1 or TP2(this value will be passed dynamically through some other parameters). Is above syntax/approach correct?</p>
|
[
{
"answer_id": 74557107,
"author": "lpizzinidev",
"author_id": 13211263,
"author_profile": "https://Stackoverflow.com/users/13211263",
"pm_score": 2,
"selected": false,
"text": "colors export const colors: { [key: string]: string; } = {\n 'dark-grey': '#606060',\n 'light-grey': '#909090',\n 'slate-grey': '#7889a0',\n 'olive-green': '#8fd683',\n 'light-blue': '#0371ff',\n 'dark-gray': '#4b6c89',\n 'blue-700-new': 'var(--color-brand-primary-default-new)',\n azure: '#1676ff',\n blue: '#1676ff',\n white: '#fff',\n black: '#000',\n brandPrimaryDefault: 'var(--color-brand-primary-default-new)',\n brandPrimaryLight: 'var(--color-brand-primary-light-new)',\n naturalGrayDarker2: 'var(--color-natural-gray-darker-2)',\n};\n"
},
{
"answer_id": 74557138,
"author": "nate-kumar",
"author_id": 9987590,
"author_profile": "https://Stackoverflow.com/users/9987590",
"pm_score": 0,
"selected": false,
"text": "colors string export const colors = {\n 'dark-grey': '#606060',\n 'light-grey': '#909090',\n 'slate-grey': '#7889a0',\n 'olive-green': '#8fd683',\n 'light-blue': '#0371ff',\n 'dark-gray': '#4b6c89',\n 'blue-700-new': 'var(--color-brand-primary-default-new)',\n azure: '#1676ff',\n blue: '#1676ff',\n white: '#fff',\n black: '#000',\n brandPrimaryDefault: 'var(--color-brand-primary-default-new)',\n brandPrimaryLight: 'var(--color-brand-primary-light-new)',\n naturalGrayDarker2: 'var(--color-natural-gray-darker-2)',\n};\n\nexport type Color = keyof typeof colors // 'dark-grey' | 'light-grey' | ...\nexport const getColor = (color: Color): string => colors[color] || colors.white;\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74557050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3347456/"
] |
74,557,069
|
<p>I want to subtract the next number in the sequence from the previous number so 2 from 1, 4 from 3 and so on. Ideally, it would find those "pairs" and then subtract the time from that row so I also need a way to do that</p>
<p><a href="https://i.stack.imgur.com/gCR0u.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gCR0u.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74557203,
"author": "Dominique",
"author_id": 4279155,
"author_profile": "https://Stackoverflow.com/users/4279155",
"pm_score": 1,
"selected": false,
"text": "=IF(AND(D2=\"START\",D3=\"STOP\"),B3-B2,\"\")\n Difference\n<BLANK>\n9.8\n<BLANK>\n21.3\n<BLANK>\n12.8\n...\n"
},
{
"answer_id": 74557644,
"author": "JvdV",
"author_id": 9758194,
"author_profile": "https://Stackoverflow.com/users/9758194",
"pm_score": 3,
"selected": true,
"text": "F2 =IF(D2=\"START\",XLOOKUP(C2,C3:C$11,B3:B$11)-B2,\"\")\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74557069",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6380393/"
] |
74,557,131
|
<p>First of all, I want to describe that there are more than five thousand records. Please let me know the best method for best performance from the following:</p>
<pre><code>String hmVALUE = "";
try
{
hmVALUE = hashmapRECORDS.get(key).toString();
}
catch(Exception ex)
{
hmVALUE = "";
}
// Second method:
String hmVALUE = "";
if(Module.hmQUEUED_REQUESTS.containsKey(key))
{
hmVALUE = hashmapRECORDS.get(key).toString();
}
else
{
hmVALUE = "";
}
</code></pre>
<p>I am using try-catch and want to know which method is best.</p>
|
[
{
"answer_id": 74557157,
"author": "Yonatan Karp-Rudin",
"author_id": 3899765,
"author_profile": "https://Stackoverflow.com/users/3899765",
"pm_score": 0,
"selected": false,
"text": "condition ? if true : if false String hmVALUE = Module.hmQUEUED_REQUESTS.containsKey(key) ? hashmapRECORDS.get(key).toString() : \"\"\n getOrDefault() String hmVALUE = hashmapRECORDS.getOrDefault(key, \"\");\n"
},
{
"answer_id": 74557189,
"author": "shmosel",
"author_id": 1553851,
"author_profile": "https://Stackoverflow.com/users/1553851",
"pm_score": 1,
"selected": false,
"text": "get() String hmVALUE = \"\";\nObject value = hashmapRECORDS.get(key);\nif (value != null) {\n hmVALUE = value.toString();\n}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74557131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3591863/"
] |
74,557,176
|
<pre><code>print("Welcome to Agurds. Before we begin can you tell me your name?")
Name = input("name: ")
print("Hello " + Name + " When were you born " + Name + "?")
year = int(input("Born year:"))
age = str(2022 - year)
print("You must be " + age + " this year.")
if age < str(18):
print("You're too young to be here. Exiting world.")
else:
print("I see we have an adult here. Would you like to buy some of our products before hand?")
Pens = input("How much do you have right now?")
if Pens < str(100):
print("You can only buy some of our products?")
if Pens > str(100):
print("You can buy most of our products")
</code></pre>
<p>The result:
Welcome to Agurds. Before we begin can you tell me your name?
name: Hein
Hello Hein When were you born Hein?
Born year:2000
You must be 22 this year.
I see we have an adult here. Would you like to buy some of our products before hand?
How much do you have right now? 99
You can buy most of our products</p>
<p>I was expecting it to give me the first line I wrote but it doesn't work. I'm just started python not too long ago so I don't know what I am doing wrong.</p>
|
[
{
"answer_id": 74557157,
"author": "Yonatan Karp-Rudin",
"author_id": 3899765,
"author_profile": "https://Stackoverflow.com/users/3899765",
"pm_score": 0,
"selected": false,
"text": "condition ? if true : if false String hmVALUE = Module.hmQUEUED_REQUESTS.containsKey(key) ? hashmapRECORDS.get(key).toString() : \"\"\n getOrDefault() String hmVALUE = hashmapRECORDS.getOrDefault(key, \"\");\n"
},
{
"answer_id": 74557189,
"author": "shmosel",
"author_id": 1553851,
"author_profile": "https://Stackoverflow.com/users/1553851",
"pm_score": 1,
"selected": false,
"text": "get() String hmVALUE = \"\";\nObject value = hashmapRECORDS.get(key);\nif (value != null) {\n hmVALUE = value.toString();\n}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74557176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20588406/"
] |
74,557,207
|
<p>I have a list where I have all the index of values to be replaced. I have to change them in 8 diferent columns with 8 diferent lists. The replacement could be a simple string.
How can I do it?
I have more than 20 diferent columns in this df</p>
<p>Eg:</p>
<pre><code>list1 = [0,1,2]
list2 =[2,4]
list8 = ...
</code></pre>
<p>sustitution = 'no data'</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Column A</th>
<th>Column B</th>
</tr>
</thead>
<tbody>
<tr>
<td>marcos</td>
<td>peter</td>
</tr>
<tr>
<td>Julila</td>
<td>mike</td>
</tr>
<tr>
<td>Fran</td>
<td>Ramon</td>
</tr>
<tr>
<td>Pedri</td>
<td>Gavi</td>
</tr>
<tr>
<td>Olmo</td>
<td>Torres</td>
</tr>
</tbody>
</table>
</div>
<pre><code>OUTPUT:
| Column A | Column B |
| -------- | -------- |
| no data | peter |
| no data | mike |
| no data | no data |
| Pedri | Gavi |
| Olmo | no data |`
</code></pre>
|
[
{
"answer_id": 74557243,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 2,
"selected": true,
"text": "DataFrame.loc list1 = [0,1,2]\nlist2 =[2,4]\n\nL = [list1,list2]\ncols = ['Column A','Column B']\n\nsustitution = 'no data'\n\nfor c, i in zip(cols, L):\n df.loc[i, c] = sustitution\nprint (df)\n Column A Column B\n0 no data peter\n1 no data mike\n2 no data no data\n3 Pedri Gavi\n4 Olmo no data\n"
},
{
"answer_id": 74557359,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 0,
"selected": false,
"text": "list1 = [0,1,2]\nlist2 = [2,4]\n\nlists = [list1, list2]\n\ncol = np.repeat(np.arange(len(lists)), list(map(len, lists)))\n# array([0, 0, 0, 1, 1])\nrow = np.concatenate(lists)\n# array([0, 1, 2, 2, 4])\n\ndf.values[row, col] = 'no data'\n Column A Column B\n0 no data peter\n1 no data mike\n2 no data no data\n3 Pedri Gavi\n4 Olmo no data\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74557207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20588451/"
] |
74,557,249
|
<p>I am trying to calculate every lowercase letter from a mixed uppercase and lowercase string and form a new string of only lowercase. For example I have a string named st="ABcASFatBD" and I expect an output of low= "cat" but I am getting only "c" as the output. Below is my code.</p>
<pre><code> class Solution(object):
def find_crowd(self, st):
lo = ""
for i in range(len(st)):
if st[i].islower():
lo += st[i]
return lo
else:
pass
if __name__ == "__main__":
p = Solution()
s = "ABcASFatBD"
print(p.find_crowd(s))
</code></pre>
|
[
{
"answer_id": 74557243,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 2,
"selected": true,
"text": "DataFrame.loc list1 = [0,1,2]\nlist2 =[2,4]\n\nL = [list1,list2]\ncols = ['Column A','Column B']\n\nsustitution = 'no data'\n\nfor c, i in zip(cols, L):\n df.loc[i, c] = sustitution\nprint (df)\n Column A Column B\n0 no data peter\n1 no data mike\n2 no data no data\n3 Pedri Gavi\n4 Olmo no data\n"
},
{
"answer_id": 74557359,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 0,
"selected": false,
"text": "list1 = [0,1,2]\nlist2 = [2,4]\n\nlists = [list1, list2]\n\ncol = np.repeat(np.arange(len(lists)), list(map(len, lists)))\n# array([0, 0, 0, 1, 1])\nrow = np.concatenate(lists)\n# array([0, 1, 2, 2, 4])\n\ndf.values[row, col] = 'no data'\n Column A Column B\n0 no data peter\n1 no data mike\n2 no data no data\n3 Pedri Gavi\n4 Olmo no data\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74557249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20502753/"
] |
74,557,255
|
<p>For example if a use <code>ma</code> <code>mb</code> etc to create some markers in buffer. Then i record a macro, then i want to execute macro to all these markers, how can i do to accomplish this goal</p>
<p>Maybe it can be completed by writing a function by <code>lua</code> or <code>viml</code>, or use some plugins or just a vim command is all accepted. I'd like someone can give a example function to make me learn more about neovim or vim</p>
|
[
{
"answer_id": 74558726,
"author": "LoneExile",
"author_id": 20253319,
"author_profile": "https://Stackoverflow.com/users/20253319",
"pm_score": 0,
"selected": false,
"text": "local keymap = vim.api.nvim_set_keymap\nkeymap('n', '<leader>xx', '<Plug>(Marks-next)', { noremap = true, silent = true })\n"
},
{
"answer_id": 74565015,
"author": "Luc Hermitte",
"author_id": 15934,
"author_profile": "https://Stackoverflow.com/users/15934",
"pm_score": 3,
"selected": true,
"text": "getpos(\"'\".mark_name) exe 'normal @'.macro_name function! s:exec(macro, marks) abort\n for mark in split(a:marks, '\\zs\\ze')\n call setpos('.', getpos(\"'\".mark))\n exe 'normal @'.a:macro\n endfor\nendfunction\n\ncommand! -nargs=+ RunMacroOnMarks call s:exec(<f-args>)\n m a b :RunMacroOnMarks m ab\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74557255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20588551/"
] |
74,557,285
|
<p>I was working on admin registration and admin data retrieving react app. The registration works fine but retrieving admin data is crushing my backend. I have encountered this error when call the given endpoint from my react app. But when I call it from Postman it works very fine. And when I see the console on my browser my react app sends two calls simultaneously instead of one. On these calls my app crushes. If any one can show me how to solve this problem?
For backend = Node.js with express.js framework
For frontend = React</p>
<p>This is the error I am getting</p>
<pre><code>node:internal/errors:465
ErrorCaptureStackTrace(err);
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot remove headers after they are sent to the client
at new NodeError (node:internal/errors:372:5)
at ServerResponse.removeHeader (node:_http_outgoing:654:11)
at ServerResponse.send (C:\Users\Momentum\Documents\The Technologies\Madudi-App-Api\node_modules\express\lib\response.js:214:10)
at C:\Users\Momentum\Documents\The Technologies\Madudi-App-Api\api\index.js:22:72
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
code: 'ERR_HTTP_HEADERS_SENT'
}
[nodemon] app crashed - waiting for file changes before starting...
</code></pre>
<p>This is how I setup my endpoint and changed the data to a string in order to get simple response but it crushes</p>
<pre><code>const makeHttpRequest = (controller, helper) => {
const makeRequest = (req, res) => {
try {
var data = "Trying response";
res.status(200).send({ status: true, data: data });
} catch (error) {
console.log(`ERROR: ${error.message}`);
res.status(400).send({ status: false, error: error.message });
}
};
return { makeRequest };
};
const makeApi = ({router, controller, helper}) => {
router.get("/test", (req, res) => res.send("Router is Woking..."));
router.get("/admin/get_all_admins", async (req, res) => res.send(await makeHttpRequest(controller, helper).makeRequest(req, res)));
}
module.exports = { makeApi }
</code></pre>
<p>And this is the call from my react app</p>
<pre><code>export default function GetAllUsers() {
useEffect(() =>{
try{
const response = axios.get('http://localhost:5000/admin/get_all_admins').then(async (response) => {
console.log('response ', response)
return response.data;
});
}catch(error) {
return [];
}
}, [])
</code></pre>
|
[
{
"answer_id": 74557367,
"author": "Reinier68",
"author_id": 11225065,
"author_profile": "https://Stackoverflow.com/users/11225065",
"pm_score": 0,
"selected": false,
"text": "router.get(\"/admin/get_all_admins\" makeHttpRequest Cannot remove headers after they are sent to the client"
},
{
"answer_id": 74557634,
"author": "jfriend00",
"author_id": 816620,
"author_profile": "https://Stackoverflow.com/users/816620",
"pm_score": 1,
"selected": true,
"text": "res.send() makeRequest() router.get(\"/admin/get_all_admins\", async (req, res) => res.send(await makeHttpRequest(controller, helper).makeRequest(req, res)));\n makeRquest() makeRequest()"
},
{
"answer_id": 74558235,
"author": "Abdul-Rasheed",
"author_id": 17716334,
"author_profile": "https://Stackoverflow.com/users/17716334",
"pm_score": 1,
"selected": false,
"text": "const handler = (req,res) => {\n return res.status(200).json(data)}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74557285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18360726/"
] |
74,557,287
|
<p>I make a draft implementation for my reusable <strong>input</strong> component.
The code below obviously throws an error.</p>
<p>Question is how to pass the <code>$event</code> back to <strong>register</strong> blade to get or log the value of the input?</p>
<p><strong>register.blade.php</strong></p>
<pre><code><div>
<x-input onChange="(value) => {console.log('value', value)}"></x-input>
<div/>
</code></pre>
<p><strong>input.blade.php</strong></p>
<pre><code>@props(['onChange' => 'null'])
<input x-on:change="{{ $onChange($event) }}">
</code></pre>
|
[
{
"answer_id": 74557367,
"author": "Reinier68",
"author_id": 11225065,
"author_profile": "https://Stackoverflow.com/users/11225065",
"pm_score": 0,
"selected": false,
"text": "router.get(\"/admin/get_all_admins\" makeHttpRequest Cannot remove headers after they are sent to the client"
},
{
"answer_id": 74557634,
"author": "jfriend00",
"author_id": 816620,
"author_profile": "https://Stackoverflow.com/users/816620",
"pm_score": 1,
"selected": true,
"text": "res.send() makeRequest() router.get(\"/admin/get_all_admins\", async (req, res) => res.send(await makeHttpRequest(controller, helper).makeRequest(req, res)));\n makeRquest() makeRequest()"
},
{
"answer_id": 74558235,
"author": "Abdul-Rasheed",
"author_id": 17716334,
"author_profile": "https://Stackoverflow.com/users/17716334",
"pm_score": 1,
"selected": false,
"text": "const handler = (req,res) => {\n return res.status(200).json(data)}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74557287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12010133/"
] |
74,557,295
|
<p>When creating a custom package that contains font as a .ttf file. I try to download the font file also in the example app that is contained in the package.</p>
<p>The font is downloaded successfully on iOS and macOS apps but not on Linux or Web.</p>
<p>The web console is giving me an error
<code>Failed to load font My-Custom-Icons at assets/../lib/assets/fonts/My-Custom-Icons.ttf</code></p>
<pre><code>...
my_package:
# When depending on this package from a real application you should use:
# custom_package: ^x.y.z
# See https://dart.dev/tools/pub/dependencies#version-constraints
# The example app is bundled with the plugin so we use a path dependency on
# the parent directory to use the current plugin's version.
path: ../
...
flutter:
uses-material-design: true
fonts:
- family: My-Custom-Icons
fonts:
- asset: ../lib/assets/fonts/My-Custom-Icons.ttf
</code></pre>
<p>I would expect that font would be downloaded the same way on all different platforms. What I'm missing here?</p>
|
[
{
"answer_id": 74557367,
"author": "Reinier68",
"author_id": 11225065,
"author_profile": "https://Stackoverflow.com/users/11225065",
"pm_score": 0,
"selected": false,
"text": "router.get(\"/admin/get_all_admins\" makeHttpRequest Cannot remove headers after they are sent to the client"
},
{
"answer_id": 74557634,
"author": "jfriend00",
"author_id": 816620,
"author_profile": "https://Stackoverflow.com/users/816620",
"pm_score": 1,
"selected": true,
"text": "res.send() makeRequest() router.get(\"/admin/get_all_admins\", async (req, res) => res.send(await makeHttpRequest(controller, helper).makeRequest(req, res)));\n makeRquest() makeRequest()"
},
{
"answer_id": 74558235,
"author": "Abdul-Rasheed",
"author_id": 17716334,
"author_profile": "https://Stackoverflow.com/users/17716334",
"pm_score": 1,
"selected": false,
"text": "const handler = (req,res) => {\n return res.status(200).json(data)}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74557295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12067877/"
] |
74,557,312
|
<p>i have fields named "Date of Payment" and "Type of Application". i have also unbound textbox with a name "txtCount". i want to display in "txtCount" the total count of records if "Date of Payment" = year 2022 AND "Type of Application" = "New Transaction". The year 2022 is in another table field name "Calendar Year" and the year 2022 is in text159 using: <code>=DLookUp("CalendarYear","tblControlNumber","ControlID")</code><br />
this is my current formula in my unbound textbox and i am getting error.<br />
<code>=Sum(IIf([Type of Application]="New Transaction" And Year([Date of Payment])=[Text159.Value],1,0))</code></p>
<p>can anyone help pls, thank you</p>
<p>i want to get Number of New transaction in year 2022 only. and if i update my calendar year 2023, i can also get the number of new transactions in year 2023.</p>
|
[
{
"answer_id": 74557367,
"author": "Reinier68",
"author_id": 11225065,
"author_profile": "https://Stackoverflow.com/users/11225065",
"pm_score": 0,
"selected": false,
"text": "router.get(\"/admin/get_all_admins\" makeHttpRequest Cannot remove headers after they are sent to the client"
},
{
"answer_id": 74557634,
"author": "jfriend00",
"author_id": 816620,
"author_profile": "https://Stackoverflow.com/users/816620",
"pm_score": 1,
"selected": true,
"text": "res.send() makeRequest() router.get(\"/admin/get_all_admins\", async (req, res) => res.send(await makeHttpRequest(controller, helper).makeRequest(req, res)));\n makeRquest() makeRequest()"
},
{
"answer_id": 74558235,
"author": "Abdul-Rasheed",
"author_id": 17716334,
"author_profile": "https://Stackoverflow.com/users/17716334",
"pm_score": 1,
"selected": false,
"text": "const handler = (req,res) => {\n return res.status(200).json(data)}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74557312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20588242/"
] |
74,557,319
|
<p>Inside my React function component, I have a code that looks like this:</p>
<p><a href="https://i.stack.imgur.com/wwB1T.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wwB1T.png" alt="enter image description here" /></a></p>
<p>How to pass the FontAwesomeIcon element as a parameter into markATaskAsDone?
I tried to pass in 'this' but got an error that says <a href="https://i.stack.imgur.com/UEtJO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UEtJO.png" alt="enter image description here" /></a></p>
<p>I also tried to cast this as a JSX.Element before passing it into markATaskAsDone but still get the same error.</p>
|
[
{
"answer_id": 74557430,
"author": "Šimon Slabý",
"author_id": 13647969,
"author_profile": "https://Stackoverflow.com/users/13647969",
"pm_score": 2,
"selected": true,
"text": "<FontAwesomeIcon icon=(faCircleCheck} onClick={()=>{markATaskAsDone }} /> <FontAwesomeIcon icon=(faCircleCheck} onClick={(event)=>{markATaskAsDone (event)}} /> const [isDone, setIsDone]\nconst markATaskAsDone = () => {\n setIsDone(!isDone)\n}\n\nreturn <FontAwesomeIcon icon=(isDone ? faCheck : faCircleCheck} onClick={()=>{markATaskAsDone ()}} />\n const markATaskAsDone = (event) => {\n console.log(event)\n}\n\nreturn <FontAwesomeIcon icon=(isDone ? faCheck : faCircleCheck} onClick={(event)=>{markATaskAsDone (event)}} />\n"
},
{
"answer_id": 74557439,
"author": "Navoneel Talukdar",
"author_id": 5651109,
"author_profile": "https://Stackoverflow.com/users/5651109",
"pm_score": 0,
"selected": false,
"text": "<FontAwesomeIcon icon={faCircleCheck} onClick={(e) => markTaskAsDone(e)} />\n\nconst markTaskAsDone = (e) => {\n e.preventDefault(); \n};\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74557319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16235524/"
] |
74,557,348
|
<p><a href="https://i.stack.imgur.com/SnQr5.png" rel="nofollow noreferrer">constant variables and functions in the same program cpp</a></p>
<pre><code>#include<bits/stdc++.h>
using namespace std;
class student
{
public:
const int roll;
const string name;
student (int r,string n)
:roll(r),name(n)
{
cout<<roll<<endl;
cout<<name<<endl;
}
void display()
{
cout<<"Disp\n";
}
};
int main()
{
student obj(2003081,"ismail");
student o; //ERROR
o.display();
return 0;
}
</code></pre>
<p>I can't understand, why the compiler shows "no matching function for call to 'student::student()' "?
Where is the problem and how can I overcome this?</p>
|
[
{
"answer_id": 74557430,
"author": "Šimon Slabý",
"author_id": 13647969,
"author_profile": "https://Stackoverflow.com/users/13647969",
"pm_score": 2,
"selected": true,
"text": "<FontAwesomeIcon icon=(faCircleCheck} onClick={()=>{markATaskAsDone }} /> <FontAwesomeIcon icon=(faCircleCheck} onClick={(event)=>{markATaskAsDone (event)}} /> const [isDone, setIsDone]\nconst markATaskAsDone = () => {\n setIsDone(!isDone)\n}\n\nreturn <FontAwesomeIcon icon=(isDone ? faCheck : faCircleCheck} onClick={()=>{markATaskAsDone ()}} />\n const markATaskAsDone = (event) => {\n console.log(event)\n}\n\nreturn <FontAwesomeIcon icon=(isDone ? faCheck : faCircleCheck} onClick={(event)=>{markATaskAsDone (event)}} />\n"
},
{
"answer_id": 74557439,
"author": "Navoneel Talukdar",
"author_id": 5651109,
"author_profile": "https://Stackoverflow.com/users/5651109",
"pm_score": 0,
"selected": false,
"text": "<FontAwesomeIcon icon={faCircleCheck} onClick={(e) => markTaskAsDone(e)} />\n\nconst markTaskAsDone = (e) => {\n e.preventDefault(); \n};\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74557348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19661888/"
] |
74,557,350
|
<p>I was reading about chained ternary operators in JavaScript and MDN says that they are right associative. This means that they will be evaluated from right to left.</p>
<blockquote>
<p>The ternary operator is right-associative, which means it can be "chained" in the following way, similar to an if … else if … else if … else chain:</p>
</blockquote>
<p>However, this is confusing me a lot. Here is some sample code:</p>
<pre><code>var AQI = 340;
var result =
AQI > 300 //if condition
? "Air Quality is BAD" //if first condition satisfies
: AQI > 200 //first else-if condition
? "Air Quality is NORMAL"
: AQI > 100 //second else-if condition
? "Air Quality is GOOD"
: "Air Quality is EXCELLENT"; //if all the conditions fail
</code></pre>
<p>If the ternary operator is right associative, it would evaluate this part first:</p>
<pre><code>AQI > 100 //second else-if condition
? "Air Quality is GOOD"
: "Air Quality is EXCELLENT";
</code></pre>
<p>Since, AQI is over 340, AQI > 100 would be true and we will get "Air Quality is Good". However, the real output is "Air Quality is Bad".</p>
<p>So, is MDN wrong about right associativity or am I misunderstanding something?</p>
<p>Thanks.</p>
|
[
{
"answer_id": 74557407,
"author": "Barmar",
"author_id": 1491895,
"author_profile": "https://Stackoverflow.com/users/1491895",
"pm_score": 1,
"selected": false,
"text": "var result =\n AQI > 300 //if condition\n ?\n \"Air Quality is BAD\" //if first condition satisfies\n :\n (AQI > 200 //first else-if condition\n ?\n \"Air Quality is NORMAL\" :\n (AQI > 100 //second else-if condition\n ?\n \"Air Quality is GOOD\" :\n \"Air Quality is EXCELLENT\" //if all the conditions fail\n )\n ); if/else if/.../else"
},
{
"answer_id": 74557482,
"author": "slebetman",
"author_id": 167735,
"author_profile": "https://Stackoverflow.com/users/167735",
"pm_score": 3,
"selected": true,
"text": "AQI > 300 //if condition\n ? \"Air Quality is BAD\" //if first condition satisfies\n : AQI > 200 //first else-if condition\n ? \"Air Quality is NORMAL\" \n : AQI > 100 //second else-if condition\n ? \"Air Quality is GOOD\"\n : \"Air Quality is EXCELLENT\";\n (((AQI > 300 ?\n \"Air Quality is BAD\"\n : AQI ) > 200 ?\n \"Air Quality is NORMAL\" \n : AQI) > 100 ?\n \"Air Quality is GOOD\"\n : \"Air Quality is EXCELLENT\")\n AQI 300 \"Air Quality is BAD\" 200 \"Air Quality is NORMAL\" 100 (AQI > 300 ?\n \"Air Quality is BAD\"\n : (AQI > 200 ?\n \"Air Quality is NORMAL\" \n : (AQI > 100 ?\n \"Air Quality is GOOD\"\n : \"Air Quality is EXCELLENT\")))\n AQI 300 AQI 200 AQI 100"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74557350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10449848/"
] |
74,557,354
|
<p>I have data in Column A in excel..I am iterating through column and i need to find if a cell value has hyperlink init.</p>
<pre><code>LR=Activeworkbook.Worksheets("Emp").Range("A65000").End(xlup).Row
for j=1 to LR
if Thisworkbooks.Worksheets("Emp").cells(j,1)="" then 'Logic to find hyperlink
'Function
end if
</code></pre>
<p>next</p>
|
[
{
"answer_id": 74557539,
"author": "Troy",
"author_id": 4697251,
"author_profile": "https://Stackoverflow.com/users/4697251",
"pm_score": 0,
"selected": false,
"text": "Private Sub cmdFollowLink_Click() \n"
},
{
"answer_id": 74558013,
"author": "VBasic2008",
"author_id": 9814069,
"author_profile": "https://Stackoverflow.com/users/9814069",
"pm_score": 2,
"selected": true,
"text": "Dim cell As Range: Set cell = Sheet1.Range(\"A1\")\nIf cell.Hyperlinks.Count > 0 Then ' has a hyperlink\nElse ' has no hyperlink\nEnd If\n Hyperlinks.Count Hyperlinks object Hyperlinks property If cell.Hyperlinks.Count = 1 Then ' has a hyperlink\n Option Explicit\n\nSub IdentifyCellsWithHyperlink()\n\n Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code\n ' If it's not, modify accordingly.\n \n Dim ws As Worksheet: Set ws = wb.Worksheets(\"Emp\")\n Dim rg As Range\n Set rg = ws.Range(\"A2\", ws.Cells(ws.Rows.Count, \"A\").End(xlUp))\n \n Dim cell As Range\n \n For Each cell In rg.Cells\n If cell.Hyperlinks.Count > 0 Then ' has a hyperlink\n \n Else ' has no hyperlink\n \n End If\n Next cell\n\nEnd Sub\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74557354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19742621/"
] |
74,557,378
|
<p>So I was used to use this bot about one year ago, now I wanted to launch it again but after discord.py 2.0 update it seems doesn't work propery</p>
<pre><code>import discord
from keep_alive import keep_alive
class MyClient(discord.Client):
async def on_ready(self):
print('bot is online now', self.user)
async def on_message(self, message):
word_list = ['ffs','gdsgds']
if message.author == self.user:
return
messageContent = message.content
if len(messageContent) > 0:
for word in word_list:
if word in messageContent:
await message.delete()
await message.channel.send('Do not say that!')
# keep_alive()
client = discord.Client(intents=discord.Intents.default())
client.run('OTkxfsa9WC5G34')
</code></pre>
<pre><code>from flask import Flask
from threading import Thread
app = Flask('')
@app.route('/')
def home():
return 'dont forget uptime robot monitor'
def run():
app.run(host='0.0.0.0',port=8000)
def keep_alive():
t = Thread(target=run)
t.start()
</code></pre>
<p>I tried to fix it by my own by changing this line</p>
<p><code>client = discord.Client(intents=discord.Intents.default())</code></p>
<p>It has to be some trivial syntax mistake, but I cannot locate it</p>
<p>Edit1: so i turned on intents in bot developer portal and made my code to looks like this but still seems something doesn't work</p>
<pre><code>import discord
from keep_alive import keep_alive
class MyClient(discord.Client):
async def on_ready(self):
print('bot is online now', self.user)
async def on_message(self, message):
word_list = ['fdsfds','fsa']
if message.author == self.user:
return
messageContent = message.content
if len(messageContent) > 0:
for word in word_list:
if word in messageContent:
await message.delete()
await message.channel.send('Do not say that!')
# keep_alive()
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents = intents)
client.run('OTkxMDcxMTUx')
</code></pre>
|
[
{
"answer_id": 74558850,
"author": "MrHDumpty",
"author_id": 18867363,
"author_profile": "https://Stackoverflow.com/users/18867363",
"pm_score": -1,
"selected": false,
"text": "import discord\nfrom discord.ext import commands # you need to import this to be able to use commands and events\nfrom keep_alive import keep_alive\nclient = commands.Bot(intents=discord.Intents.default())\n\n@bot.event\nasync def on_ready(): # you don't need self in here\n print('bot is online now', client.user) # you can just use client.user\n\n@bot.event\nasync def on_message(message): # again, you do not need self\n word_list = ['ffs','gdsgds']\n if message.author == client.user: # you can use client.user here too\n return\n messageContent = message.content\n if len(messageContent) > 0:\n for word in word_list:\n if word in messageContent:\n await message.delete()\n await message.channel.send('Do not say that!')\n\nkeep_alive()\nclient.run('OTkxfsa9WC5G34') #if this is your real token/you have been using this token since you made the bot, you should definitely generate a new one\n"
},
{
"answer_id": 74559158,
"author": "stijndcl",
"author_id": 13568999,
"author_profile": "https://Stackoverflow.com/users/13568999",
"pm_score": 2,
"selected": false,
"text": "Intents.default() intents = discord.Intents.default()\nintents.message_content = True\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74557378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20588585/"
] |
74,557,423
|
<p>I looked at some articles on the internet but I couldn't find what I wanted. After the site loads for the first time, when I scroll and scroll to a paragraph, I want the text to scroll from the bottom and come after 1 second.Like on this site:<a href="https://www.armoli.com/" rel="nofollow noreferrer">https://www.armoli.com/</a>.
For example I want to apply it here</p>
<pre><code><h6 style="margin-right: 70px;" class="section-title text-center">Our Solutions</h6>
<h6 style="margin-right: 120px;" class="section-subtitle text-center mb-5 pb-3">We offer efficient, high performance and guaranteed solutions with our experienced team having strong references</h6>
<div class="solutionout1">
<img class="solu" style="height:80px ;" src="assets/imgs/webdevelop.png" alt="web development logo" >
<div ><p class="solutionhead">Web Development</p><p class="solutiontext">
We offer fast, profitable, safe and effective solutions in the light of the latest innovations to those who entrust us with their companies' showcases in the internet world.</p></div>
</div>
</code></pre>
|
[
{
"answer_id": 74557811,
"author": "Graham",
"author_id": 15224555,
"author_profile": "https://Stackoverflow.com/users/15224555",
"pm_score": 1,
"selected": false,
"text": "const intersectionCallback = (entries) => {\n entries.forEach((entry) => {\n if (entry.isIntersecting) {\n let elem = entry.target;\n if (entry.intersectionRatio >= 0.75) {\n elem.classList.add(\"animate\");\n }\n }\n });\n};\n\nconst Animateditems = document.querySelectorAll(\"div.text\");\nlet options = {\n threshold: 1.0,\n};\nlet observer = new IntersectionObserver(intersectionCallback, options);\n\nAnimateditems.forEach((item) => {\n observer.observe(item);\n}); body {\n min-height: 100vh;\n display: flex;\n flex-direction: column;\n}\nhtml {\n font-size: 66.6%;\n}\n.scrolldown {\n display: flex;\n align-items: center;\n justify-content: center;\n height: 100vh;\n}\nh1 {\n font-size: 3rem;\n}\n.flex-container {\n display: flex;\n flex-wrap: wrap;\n justify-content: space-between;\n width: 100%;\n gap: 2rem;\n}\n.flex-container > div {\n flex: 1 1 100%;\n border: 0.1rem solid black;\n padding: 2rem;\n margin: 2rem;\n}\n\n.flex-container > div.animate p {\n animation: fadeIn 2s;\n opacity: 1;\n}\n.flex-container > div.animate h2 {\n animation: fadeIn 2s;\n opacity: 1;\n}\n\n.flex-container > div h2 {\n font-size: 2.5rem;\n opacity: 0;\n transform: translateY(0rem);\n}\n.flex-container > div p {\n font-size: 1.8rem;\n opacity: 0;\n}\n\n@media screen and (min-width: 650px) {\n .flex-container > div {\n flex: 1 1 40%;\n border: 0.1rem solid black;\n }\n}\n\n@keyframes fadeIn {\n from {\n transform: translateY(2rem);\n opacity: 0;\n }\n to {\n transform: translateY(0rem);\n opacity: 1;\n }\n} <!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <link rel=\"stylesheet\" href=\"styles.css\" />\n <title>animation</title>\n </head>\n <body>\n <div class=\"scrolldown\"><h1>scroll down</h1></div>\n <div class=\"flex-container\">\n <div class=\"text\">\n <h2>This is a title</h2>\n <p>\n Lorem ipsum dolor sit amet consectetur adipisicing elit. Vel\n inventore, aut id laboriosam reprehenderit consectetur? Praesentium,\n aperiam corporis. Iste asperiores molestiae, itaque a minus dicta! Id\n omnis suscipit iure illum.\n </p>\n </div>\n <div class=\"text\">\n <h2>This is a title</h2>\n <p>\n Lorem ipsum dolor sit amet consectetur adipisicing elit. Vel\n inventore, aut id laboriosam reprehenderit consectetur? Praesentium,\n aperiam corporis. Iste asperiores molestiae, itaque a minus dicta! Id\n omnis suscipit iure illum.\n </p>\n </div>\n <div class=\"text\">\n <h2>This is a title</h2>\n <p>\n Lorem ipsum dolor sit amet consectetur adipisicing elit. Vel\n inventore, aut id laboriosam reprehenderit consectetur? Praesentium,\n aperiam corporis. Iste asperiores molestiae, itaque a minus dicta! Id\n omnis suscipit iure illum.\n </p>\n </div>\n <div class=\"text\">\n <h2>This is a title</h2>\n <p>\n Lorem ipsum dolor sit amet consectetur adipisicing elit. Vel\n inventore, aut id laboriosam reprehenderit consectetur? Praesentium,\n aperiam corporis. Iste asperiores molestiae, itaque a minus dicta! Id\n omnis suscipit iure illum.\n </p>\n </div>\n </div>\n <script src=\"main.js\"></script>\n </body>\n</html>"
},
{
"answer_id": 74559068,
"author": "Guit Adharsh",
"author_id": 16612350,
"author_profile": "https://Stackoverflow.com/users/16612350",
"pm_score": 3,
"selected": true,
"text": " window.addEventListener('scroll', reveal);\n\n function reveal(){\n var reveals = document.querySelectorAll('.reveal');\n\n for(var i = 0; i < reveals.length; i++){\n\n var windowheight = window.innerHeight;\n var revealtop = reveals[i].getBoundingClientRect().top;\n var revealpoint = 150;\n\n if(revealtop < windowheight - revealpoint){\n reveals[i].classList.add('active');\n }\n else{\n reveals[i].classList.remove('active');\n }\n }\n } *{\n margin: 0;\n padding: 0;\n box-sizing: border-box;\n}\n\nbody{\n background: #1D212B;\n}\n\nsection{\n min-height: 100vh;\n display: flex;\n justify-content: center;\n align-items: center;\n}\n\nsection:nth-child(1){\n color: #fff;\n}\n\nsection:nth-child(2){\n color: #1D212B;\n background: #fff;\n}\n\nsection:nth-child(3){\n color: #fff;\n}\n\nsection:nth-child(4){\n color: #1D212B;\n background: #fff;\n}\n\nsection .container{\n margin: 100px;\n}\n\nsection h1{\n font-size: 60px;\n}\n\nsection h2{\n font-size: 40px;\n text-align: center;\n text-transform: uppercase;\n}\n\nsection .cards{\n display: flex;\n}\n\nsection .cards .text-card{\n background: #2696E9;\n margin: 20px;\n padding: 20px;\n}\n\nsection .cards .text-card h3{\n font-size: 30px;\n text-align: center;\n text-transform: uppercase;\n margin-bottom: 10px;\n}\n\n@media (max-width: 900px){\n section h1{\n font-size: 40px;\n }\n\n section .cards{\n flex-direction: column;\n }\n}\n\n.reveal{\n position: relative;\n transform: translateY(150px);\n opacity: 0;\n transition: all 2s ease;\n}\n\n.reveal.active{\n transform: translateY(0px);\n opacity: 1;\n}\n <!DOCTYPE html>\n<html lang=\"en\" dir=\"ltr\">\n <head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Scroll Reveal</title>\n </head>\n <body>\n\n <section>\n <h1>Reveal Elements On Scroll</h1>\n </section>\n <section>\n <div class=\"container reveal\">\n <h2>Your Title</h2>\n <div class=\"cards\">\n <div class=\"text-card\">\n <h3>Title</h3>\n <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>\n </div>\n <div class=\"text-card\">\n <h3>Title</h3>\n <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>\n </div>\n <div class=\"text-card\">\n <h3>Title</h3>\n <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>\n </div>\n </div>\n </div>\n </section>\n <section>\n <div class=\"container reveal\">\n <h2>Your Title</h2>\n <div class=\"cards\">\n <div class=\"text-card\">\n <h3>Title</h3>\n <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>\n </div>\n <div class=\"text-card\">\n <h3>Title</h3>\n <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>\n </div>\n <div class=\"text-card\">\n <h3>Title</h3>\n <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>\n </div>\n </div>\n </div>\n </section>\n <section>\n <div class=\"container reveal\">\n <h2>Your Title</h2>\n <div class=\"cards\">\n <div class=\"text-card\">\n <h3>Title</h3>\n <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>\n </div>\n <div class=\"text-card\">\n <h3>Title</h3>\n <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>\n </div>\n <div class=\"text-card\">\n <h3>Title</h3>\n <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>\n </div>\n </div>\n </div>\n </section>\n </body>\n</html>"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74557423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20107962/"
] |
74,557,437
|
<p>I have a list of URLs that are linked to the user. Currently, once the user adds those URLs to the app, I'm saving each URL as an individual document and then read any document that matches their UID.</p>
<p>Is this the right way to do it?</p>
<p>And with Firestore, is it cost per read per document or read per item no matter if there are 100 items in one document?</p>
<p>Just trying to wrap my head around it so any help would be great!</p>
|
[
{
"answer_id": 74557811,
"author": "Graham",
"author_id": 15224555,
"author_profile": "https://Stackoverflow.com/users/15224555",
"pm_score": 1,
"selected": false,
"text": "const intersectionCallback = (entries) => {\n entries.forEach((entry) => {\n if (entry.isIntersecting) {\n let elem = entry.target;\n if (entry.intersectionRatio >= 0.75) {\n elem.classList.add(\"animate\");\n }\n }\n });\n};\n\nconst Animateditems = document.querySelectorAll(\"div.text\");\nlet options = {\n threshold: 1.0,\n};\nlet observer = new IntersectionObserver(intersectionCallback, options);\n\nAnimateditems.forEach((item) => {\n observer.observe(item);\n}); body {\n min-height: 100vh;\n display: flex;\n flex-direction: column;\n}\nhtml {\n font-size: 66.6%;\n}\n.scrolldown {\n display: flex;\n align-items: center;\n justify-content: center;\n height: 100vh;\n}\nh1 {\n font-size: 3rem;\n}\n.flex-container {\n display: flex;\n flex-wrap: wrap;\n justify-content: space-between;\n width: 100%;\n gap: 2rem;\n}\n.flex-container > div {\n flex: 1 1 100%;\n border: 0.1rem solid black;\n padding: 2rem;\n margin: 2rem;\n}\n\n.flex-container > div.animate p {\n animation: fadeIn 2s;\n opacity: 1;\n}\n.flex-container > div.animate h2 {\n animation: fadeIn 2s;\n opacity: 1;\n}\n\n.flex-container > div h2 {\n font-size: 2.5rem;\n opacity: 0;\n transform: translateY(0rem);\n}\n.flex-container > div p {\n font-size: 1.8rem;\n opacity: 0;\n}\n\n@media screen and (min-width: 650px) {\n .flex-container > div {\n flex: 1 1 40%;\n border: 0.1rem solid black;\n }\n}\n\n@keyframes fadeIn {\n from {\n transform: translateY(2rem);\n opacity: 0;\n }\n to {\n transform: translateY(0rem);\n opacity: 1;\n }\n} <!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <link rel=\"stylesheet\" href=\"styles.css\" />\n <title>animation</title>\n </head>\n <body>\n <div class=\"scrolldown\"><h1>scroll down</h1></div>\n <div class=\"flex-container\">\n <div class=\"text\">\n <h2>This is a title</h2>\n <p>\n Lorem ipsum dolor sit amet consectetur adipisicing elit. Vel\n inventore, aut id laboriosam reprehenderit consectetur? Praesentium,\n aperiam corporis. Iste asperiores molestiae, itaque a minus dicta! Id\n omnis suscipit iure illum.\n </p>\n </div>\n <div class=\"text\">\n <h2>This is a title</h2>\n <p>\n Lorem ipsum dolor sit amet consectetur adipisicing elit. Vel\n inventore, aut id laboriosam reprehenderit consectetur? Praesentium,\n aperiam corporis. Iste asperiores molestiae, itaque a minus dicta! Id\n omnis suscipit iure illum.\n </p>\n </div>\n <div class=\"text\">\n <h2>This is a title</h2>\n <p>\n Lorem ipsum dolor sit amet consectetur adipisicing elit. Vel\n inventore, aut id laboriosam reprehenderit consectetur? Praesentium,\n aperiam corporis. Iste asperiores molestiae, itaque a minus dicta! Id\n omnis suscipit iure illum.\n </p>\n </div>\n <div class=\"text\">\n <h2>This is a title</h2>\n <p>\n Lorem ipsum dolor sit amet consectetur adipisicing elit. Vel\n inventore, aut id laboriosam reprehenderit consectetur? Praesentium,\n aperiam corporis. Iste asperiores molestiae, itaque a minus dicta! Id\n omnis suscipit iure illum.\n </p>\n </div>\n </div>\n <script src=\"main.js\"></script>\n </body>\n</html>"
},
{
"answer_id": 74559068,
"author": "Guit Adharsh",
"author_id": 16612350,
"author_profile": "https://Stackoverflow.com/users/16612350",
"pm_score": 3,
"selected": true,
"text": " window.addEventListener('scroll', reveal);\n\n function reveal(){\n var reveals = document.querySelectorAll('.reveal');\n\n for(var i = 0; i < reveals.length; i++){\n\n var windowheight = window.innerHeight;\n var revealtop = reveals[i].getBoundingClientRect().top;\n var revealpoint = 150;\n\n if(revealtop < windowheight - revealpoint){\n reveals[i].classList.add('active');\n }\n else{\n reveals[i].classList.remove('active');\n }\n }\n } *{\n margin: 0;\n padding: 0;\n box-sizing: border-box;\n}\n\nbody{\n background: #1D212B;\n}\n\nsection{\n min-height: 100vh;\n display: flex;\n justify-content: center;\n align-items: center;\n}\n\nsection:nth-child(1){\n color: #fff;\n}\n\nsection:nth-child(2){\n color: #1D212B;\n background: #fff;\n}\n\nsection:nth-child(3){\n color: #fff;\n}\n\nsection:nth-child(4){\n color: #1D212B;\n background: #fff;\n}\n\nsection .container{\n margin: 100px;\n}\n\nsection h1{\n font-size: 60px;\n}\n\nsection h2{\n font-size: 40px;\n text-align: center;\n text-transform: uppercase;\n}\n\nsection .cards{\n display: flex;\n}\n\nsection .cards .text-card{\n background: #2696E9;\n margin: 20px;\n padding: 20px;\n}\n\nsection .cards .text-card h3{\n font-size: 30px;\n text-align: center;\n text-transform: uppercase;\n margin-bottom: 10px;\n}\n\n@media (max-width: 900px){\n section h1{\n font-size: 40px;\n }\n\n section .cards{\n flex-direction: column;\n }\n}\n\n.reveal{\n position: relative;\n transform: translateY(150px);\n opacity: 0;\n transition: all 2s ease;\n}\n\n.reveal.active{\n transform: translateY(0px);\n opacity: 1;\n}\n <!DOCTYPE html>\n<html lang=\"en\" dir=\"ltr\">\n <head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Scroll Reveal</title>\n </head>\n <body>\n\n <section>\n <h1>Reveal Elements On Scroll</h1>\n </section>\n <section>\n <div class=\"container reveal\">\n <h2>Your Title</h2>\n <div class=\"cards\">\n <div class=\"text-card\">\n <h3>Title</h3>\n <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>\n </div>\n <div class=\"text-card\">\n <h3>Title</h3>\n <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>\n </div>\n <div class=\"text-card\">\n <h3>Title</h3>\n <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>\n </div>\n </div>\n </div>\n </section>\n <section>\n <div class=\"container reveal\">\n <h2>Your Title</h2>\n <div class=\"cards\">\n <div class=\"text-card\">\n <h3>Title</h3>\n <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>\n </div>\n <div class=\"text-card\">\n <h3>Title</h3>\n <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>\n </div>\n <div class=\"text-card\">\n <h3>Title</h3>\n <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>\n </div>\n </div>\n </div>\n </section>\n <section>\n <div class=\"container reveal\">\n <h2>Your Title</h2>\n <div class=\"cards\">\n <div class=\"text-card\">\n <h3>Title</h3>\n <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>\n </div>\n <div class=\"text-card\">\n <h3>Title</h3>\n <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>\n </div>\n <div class=\"text-card\">\n <h3>Title</h3>\n <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>\n </div>\n </div>\n </div>\n </section>\n </body>\n</html>"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74557437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16034511/"
] |
74,557,512
|
<p>I've a simple DIV-Container for the main-content of the webpage. I.E</p>
<pre><code>#main { width: 50%; margin: 0 auto; }
</code></pre>
<p>Now I would like to fix another container, right and fixed at the top of the #main-Container. See Screenshot:</p>
<p><a href="https://i.stack.imgur.com/U3DKl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/U3DKl.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74557568,
"author": "Rajilesh Panoli",
"author_id": 1581095,
"author_profile": "https://Stackoverflow.com/users/1581095",
"pm_score": 0,
"selected": false,
"text": "<div id=\"main\" style=\"position:relative;\">\n <div id=\"green_div\" style=\"position:absolute; left:100%; margin-left:20px; background:green;\">\n <div>\n</div>\n"
},
{
"answer_id": 74557626,
"author": "S M Samnoon Abrar",
"author_id": 8188682,
"author_profile": "https://Stackoverflow.com/users/8188682",
"pm_score": 1,
"selected": false,
"text": ".flex-container {\n display: flex;\n width: calc(66.66% - 20px);\n float: right;\n}\n\n.main {\n flex: 1;\n color: white;\n text-align: center;\n margin-right: 33.33%;\n}\n\n.main:first-child {\n width: 50%;\n margin: 0 auto;\n margin-right: 10px;\n}\n\n.red {\n background-color: red;\n height: 200px;\n line-height: 200px;\n}\n\n.green {\n background-color: green;\n height: 100px;\n line-height: 100px;\n max-width: 15%;\n} <div class=\"flex-container\">\n\n <div class=\"main red\">\n Main content\n </div>\n\n <div class=\"main green\">\n ?\n </div>\n\n</div>"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74557512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1736442/"
] |
74,557,546
|
<p>I need to clean a dataset filtering only modified rows (compared to the previous one) based on certain fields (in the example below we only consider cities and sports, for each id), keeping only the first occurrence.
If a row goes back to a previous state (but not for the immediately preceding), I still want to keep it.</p>
<p><code>Input df1</code></p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>city</th>
<th>sport</th>
<th>date</th>
</tr>
</thead>
<tbody>
<tr>
<td>abc</td>
<td>london</td>
<td>football</td>
<td>2022-02-11</td>
</tr>
<tr>
<td><strong>abc</strong></td>
<td><strong>paris</strong></td>
<td><strong>football</strong></td>
<td><strong>2022-02-12</strong></td>
</tr>
<tr>
<td><em>abc</em></td>
<td><em>paris</em></td>
<td><em>football</em></td>
<td><em>2022-02-13</em></td>
</tr>
<tr>
<td><em>abc</em></td>
<td><em>paris</em></td>
<td><em>football</em></td>
<td><em>2022-02-14</em></td>
</tr>
<tr>
<td><em>abc</em></td>
<td><em>paris</em></td>
<td><em>football</em></td>
<td><em>2022-02-15</em></td>
</tr>
<tr>
<td>abc</td>
<td>london</td>
<td>football</td>
<td>2022-02-16</td>
</tr>
<tr>
<td>abc</td>
<td>paris</td>
<td>football</td>
<td>2022-02-17</td>
</tr>
<tr>
<td><strong>def</strong></td>
<td><strong>paris</strong></td>
<td><strong>volley</strong></td>
<td><strong>2022-02-10</strong></td>
</tr>
<tr>
<td><em>def</em></td>
<td><em>paris</em></td>
<td><em>volley</em></td>
<td><em>2022-02-11</em></td>
</tr>
<tr>
<td>ghi</td>
<td>manchester</td>
<td>basketball</td>
<td>2022-02-09</td>
</tr>
</tbody>
</table>
</div>
<p><code>Output DESIDERED</code></p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>city</th>
<th>sport</th>
<th>date</th>
</tr>
</thead>
<tbody>
<tr>
<td>abc</td>
<td>london</td>
<td>football</td>
<td>2022-02-11</td>
</tr>
<tr>
<td><strong>abc</strong></td>
<td><strong>paris</strong></td>
<td><strong>football</strong></td>
<td><strong>2022-02-12</strong></td>
</tr>
<tr>
<td>abc</td>
<td>london</td>
<td>football</td>
<td>2022-02-16</td>
</tr>
<tr>
<td>abc</td>
<td>paris</td>
<td>football</td>
<td>2022-02-17</td>
</tr>
<tr>
<td><strong>def</strong></td>
<td><strong>paris</strong></td>
<td><strong>volley</strong></td>
<td><strong>2022-02-10</strong></td>
</tr>
<tr>
<td>ghi</td>
<td>manchester</td>
<td>basketball</td>
<td>2022-02-09</td>
</tr>
</tbody>
</table>
</div>
|
[
{
"answer_id": 74559649,
"author": "Azhar Khan",
"author_id": 2847330,
"author_profile": "https://Stackoverflow.com/users/2847330",
"pm_score": -1,
"selected": false,
"text": "from pyspark.sql.window import Window\n\ndf = spark.createDataFrame(data=[[\"abc\",\"london\",\"football\",\"2022-02-11\"],[\"abc\",\"paris\",\"football\",\"2022-02-12\"],[\"abc\",\"paris\",\"football\",\"2022-02-13\"],[\"abc\",\"paris\",\"football\",\"2022-02-14\"],[\"abc\",\"paris\",\"football\",\"2022-02-15\"],[\"abc\",\"london\",\"football\",\"2022-02-16\"],[\"abc\",\"paris\",\"football\",\"2022-02-17\"],[\"def\",\"paris\",\"volley\",\"2022-02-10\"],[\"def\",\"paris\",\"volley\",\"2022-02-11\"],[\"ghi\",\"manchester\",\"basketball\",\"2022-02-09\"]], schema=[\"id\",\"city\",\"sport\",\"date\"])\n\ndf = df.withColumn(\"date\", F.to_date(\"date\", format=\"yyyy-MM-dd\"))\ndf = df.withColumn(\"dummy_serial_key\", F.lit(0))\ndummy_w = Window.partitionBy(\"dummy_serial_key\").orderBy(\"dummy_serial_key\")\ndf = df.withColumn(\"city_prev\", F.lag(\"city\", offset=1).over(dummy_w))\ndf = df.withColumn(\"sport_prev\", F.lag(\"sport\", offset=1).over(dummy_w))\ndf = df.filter(\n (F.col(\"city_prev\").isNull())\n | (F.col(\"sport_prev\").isNull())\n | (F.col(\"city\") != F.col(\"city_prev\"))\n | (F.col(\"sport\") != F.col(\"sport_prev\"))\n)\ndf = df.drop(\"dummy_serial_key\", \"city_prev\", \"sport_prev\")\n\n+---+----------+----------+----------+\n| id| city| sport| date|\n+---+----------+----------+----------+\n|abc| london| football|2022-02-11|\n|abc| paris| football|2022-02-12|\n|abc| london| football|2022-02-16|\n|abc| paris| football|2022-02-17|\n|def| paris| volley|2022-02-10|\n|ghi|manchester|basketball|2022-02-09|\n+---+----------+----------+----------+\n"
},
{
"answer_id": 74562630,
"author": "Steven",
"author_id": 5013752,
"author_profile": "https://Stackoverflow.com/users/5013752",
"pm_score": 1,
"selected": false,
"text": "from pyspark.sql import functions as F, Window\n\noutput_df = (\n df.withColumn(\"hash\", F.hash(F.col(\"city\"), F.col(\"sport\")))\n .withColumn(\n \"prev_hash\", F.lag(\"hash\").over(Window.partitionBy(\"id\").orderBy(\"date\"))\n )\n .where(~F.col(\"hash\").eqNullSafe(F.col(\"prev_hash\")))\n .drop(\"hash\", \"prev_hash\")\n)\n\n\noutput_df.show()\n+---+----------+----------+----------+\n| id| city| sport| date|\n+---+----------+----------+----------+\n|abc| london| football|2022-02-11|\n|abc| paris| football|2022-02-12|\n|abc| london| football|2022-02-16|\n|abc| paris| football|2022-02-17|\n|def| paris| volley|2022-02-10|\n|ghi|manchester|basketball|2022-02-09|\n+---+----------+----------+----------+\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74557546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14820295/"
] |
74,557,559
|
<p>I want to find the find the highest value that is less than a given number to a specified number in a sorted list of integers.</p>
<p>I have the following code</p>
<pre><code>List<int> list = new List<int> { 2, 5, 7, 10 };
int number = 9;
</code></pre>
<p>In the above example the expected outcome is 7.
I do</p>
<pre><code>int closestSmaller = list.Aggregate((x,y) => Math.Abs(x-number) < Math.Abs(y-number) ? x : y);
</code></pre>
<p>But it returns 10.
My list has hundreds of thousands of numbers. The above was just a sample.</p>
|
[
{
"answer_id": 74557807,
"author": "Klaus Gütter",
"author_id": 2142950,
"author_profile": "https://Stackoverflow.com/users/2142950",
"pm_score": 3,
"selected": false,
"text": "List<int> list = new List<int> { 2, 5, 7, 10 };\nint number = 1;\n\nvar index = Array.BinarySearch(list.ToArray(), number);\nif (index < 0)\n{\n index = ~index - 1;\n if (index >= 0)\n Console.WriteLine(list[index]);\n else\n Console.WriteLine(\"less than all elements in the list\");\n}\nelse\n{\n Console.WriteLine(list[index]);\n}\n"
},
{
"answer_id": 74557966,
"author": "hossein sabziani",
"author_id": 4301195,
"author_profile": "https://Stackoverflow.com/users/4301195",
"pm_score": 2,
"selected": false,
"text": "var result = list.Where(x => x < number).LastOrDefault();\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74557559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1173307/"
] |
74,557,590
|
<p>My problem is as follows. I am generating a random bitstring of size n, and need to iterate over the indices for which the random bit is 1. For example, if my random bitstring ends up being 00101, I want to retrieve [2, 4] (on which I will iterate over). The goal is to do so in the fastest way possible with Python/NumPy.</p>
<p>One of the fast methods is to use NumPy and do</p>
<pre><code>bitstring = np.random.randint(2, size=(n,))
l = np.nonzero(bitstring)[0]
</code></pre>
<p>The advantage with <code>np.non_zero</code> is that it finds indices of bits set to 1 much faster than if one iterates (with a for loop) over each bit and checks if it is set to 1.</p>
<p>Now, NumPy can generate a random bitstring faster via <code>np.random.bit_generator.randbits(n)</code>. The problem is that it returns it as an integer, on which I cannot use <code>np.nonzero</code> anymore. I saw that for integers one can get the count of bits set to 1 in an integer x by using <code>x.bit_count()</code>, however there is no function to get the indices where bits are set to 1. So currently, I have to resort to a slow <code>for</code> loop, hence losing the initial speedup given by <code>np.random.bit_generator.randbits(n)</code>.</p>
<p>How would you do something similar to (and as fast as) <code>np.non_zero</code>, but on integers instead?</p>
<p>Thank you in advance for your suggestions!</p>
|
[
{
"answer_id": 74557874,
"author": "Armin",
"author_id": 8055760,
"author_profile": "https://Stackoverflow.com/users/8055760",
"pm_score": 0,
"selected": false,
"text": "n = 10\nl = np.random.bit_generator.randbits(n) # gives you the int 616\nl_string = f'{l:0{n}b}' # gives you a string representation of the int in length n 1001101000\nl_nparray = np.array(list(l_string), dtype=int) # gives you the numpy.ndarray like np.random.randint [1 0 0 1 1 0 1 0 0 0]\n"
},
{
"answer_id": 74563725,
"author": "Sam Mason",
"author_id": 1358308,
"author_profile": "https://Stackoverflow.com/users/1358308",
"pm_score": 1,
"selected": false,
"text": "bool rng = np.random.default_rng()\n\ndef original(n):\n bitstring = rng.integers(2, size=n, dtype=bool)\n return np.nonzero(bitstring)[0]\n n def perm(n):\n a = rng.permutation(n)\n return a[:rng.binomial(n, 0.5)]\n n n rng.shuffle n = 32\na = np.arange(n)\n\ndef shuffle():\n rng.shuffle(a)\n return a[:rng.binomial(n, 0.5)]\n"
},
{
"answer_id": 74579573,
"author": "adrien_vdb",
"author_id": 13725755,
"author_profile": "https://Stackoverflow.com/users/13725755",
"pm_score": 1,
"selected": false,
"text": "n def func1(n):\n bit_array = np.random.randint(2, size=n)\n return np.nonzero(bit_array)[0]\n\ndef func2(n):\n bit_int = np.random.bit_generator.randbits(n)\n a = np.zeros(bit_int.bit_count())\n i = 0\n for j in range(n):\n if 1 & (bit_int >> j):\n a[i] = j\n i += 1\n return a\n\ndef func3(n):\n bit_string = format(np.random.bit_generator.randbits(n), f'0{n}b')\n bit_array = np.array(list(bit_string), dtype=int)\n return np.nonzero(bit_array)[0]\n\ndef func4(n):\n rng = np.random.default_rng()\n a = rng.permutation(n)\n return a[:rng.binomial(n, 0.5)]\n\ndef func5(n):\n a = np.arange(n)\n rng.shuffle(a)\n return a[:rng.binomial(n, 0.5)]\n n func1 n n>32 n n randbits for func2 n for nonzero func3 nonzero randbits shuffle func5 permutation func4 n func5"
},
{
"answer_id": 74594266,
"author": "Sam Mason",
"author_id": 1358308,
"author_profile": "https://Stackoverflow.com/users/1358308",
"pm_score": 1,
"selected": false,
"text": "from cpython.pycapsule cimport PyCapsule_IsValid, PyCapsule_GetPointer\n\nimport numpy as np\ncimport numpy as np\ncimport cython\n\nfrom numpy.random cimport bitgen_t\n\nnp.import_array()\n\nDTYPE = np.uint32\nctypedef np.uint32_t DTYPE_t\n\ncdef extern int __builtin_popcountl(unsigned long) nogil\ncdef extern int __builtin_ffsl(unsigned long) nogil\n\ncdef const char *bgen_capsule_name = \"BitGenerator\"\n\n@cython.boundscheck(False) # Deactivate bounds checking\n@cython.wraparound(False) # Deactivate negative indexing.\ncdef size_t generate_bits(object bitgen, np.uint64_t *state, Py_ssize_t state_len, np.uint64_t last_mask):\n cdef Py_ssize_t i\n cdef size_t nset\n cdef bitgen_t *rng\n\n capsule = bitgen.capsule\n if not PyCapsule_IsValid(capsule, bgen_capsule_name):\n raise ValueError(\"Expecting Numpy BitGenerator Capsule\")\n rng = <bitgen_t *> PyCapsule_GetPointer(capsule, bgen_capsule_name)\n\n with bitgen.lock:\n nset = 0\n for i in range(state_len-1):\n state[i] = rng.next_uint64(rng.state)\n nset += __builtin_popcountl(state[i])\n\n i = state_len-1\n state[i] = rng.next_uint64(rng.state) & last_mask\n nset += __builtin_popcountl(state[i])\n \n return nset\n\ncdef size_t write_setbits(DTYPE_t *result, DTYPE_t off, np.uint64_t state) nogil:\n cdef size_t j\n cdef int k\n j = 0\n while state:\n # find first set bit returns zero when nothing is set\n k = __builtin_ffsl(state) - 1\n # clear out bit k\n state &= ~(1ul<<k)\n # record in output\n result[j] = off + k\n j += 1\n return j\n\n@cython.boundscheck(False) # Deactivate bounds checking\n@cython.wraparound(False) # Deactivate negative indexing.\ndef rint(bitgen, unsigned int n):\n cdef Py_ssize_t i, j, nset\n cdef np.uint64_t[::1] state\n cdef DTYPE_t[::1] result\n\n state = np.empty((n + 63) // 64, dtype=np.uint64)\n\n nset = generate_bits(bitgen, &state[0], len(state), (1ul << (n & 63)) - 1)\n\n pyresult = np.empty(nset, dtype=DTYPE)\n result = pyresult\n\n j = 0\n for i in range(len(state)):\n j += write_setbits(&result[j], i * 64, state[i])\n\n return pyresult\n import random\nimport timeit\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nbitgen = np.random.PCG64()\n\ndef func1(n):\n # bool type is a bit faster\n bit_array = np.random.randint(2, size=n, dtype=bool)\n return np.nonzero(bit_array)[0]\n\ndef func2(n):\n # OPs variant ends up using a CSPRNG which is slower\n bit_int = random.getrandbits(n)\n # this is much easier than using numpy arrays\n return [i for i in range(n) if 1 & (bit_int >> i)]\n\ndef func3(n):\n bit_string = format(random.getrandbits(n), f'0{n}b')\n bit_array = np.array(list(bit_string), dtype='int8')\n return np.nonzero(bit_array)[0]\n\ndef func4(n):\n # shuffle variant is mostly the same\n # plot already busy enough\n a = np.random.permutation(n)\n return a[:np.random.binomial(n, 0.5)]\n\ndef func_cython(n):\n return rint(bitgen, n)\n\nresult = {}\nniter = [2**i for i in range(1, 17)]\nfor name in 'func1 func2 func3 func4 func_cython'.split():\n result[name] = res = []\n for n in niter:\n t = timeit.Timer(f\"fn({n})\", f\"fn = {name}\", globals=globals())\n nit, dt = t.autorange()\n res.append(dt / nit)\n\nplt.loglog()\nfor name, times in result.items():\n plt.plot(niter, np.array(times) * 1000, '.-', label=name)\nplt.legend()\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74557590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13725755/"
] |
74,557,620
|
<p>I want to affect element's display,color or something when i hover a element.Class names can be different. Will not always contain sub.</p>
<p>Example:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.main{
background:yellow;
display:inline-block;
}
.sub{
width:50px;
height:50px;
background:blue;
float:left;
margin-right:10px;
opacity:.2;
}
.sub2{
width:50px;
height:50px;
background:blue;
float:left;
margin-right:10px;
opacity:.2;
}
.main:hover .sub,sub2{
opacity:1;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='main'>
<div class='sub'></div>
<div class='sub'></div>
<div class='sub'></div>
<div class="sub2"></div>
</div></code></pre>
</div>
</div>
</p>
<p>I can do it like that but its look like dublicate.If i can do it will save 30 lines of code. Can i do it at once. Is it possible?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.main:hover .sub{
opacity:1;
}
.main:hover .sub2{
opacity:1;
}</code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74557760,
"author": "André",
"author_id": 13970434,
"author_profile": "https://Stackoverflow.com/users/13970434",
"pm_score": 3,
"selected": true,
"text": ".main:hover .sub, .main:hover .sub2{\n opacity:1;\n}\n"
},
{
"answer_id": 74557845,
"author": "Sfili_81",
"author_id": 6592881,
"author_profile": "https://Stackoverflow.com/users/6592881",
"pm_score": 2,
"selected": false,
"text": "[class^=sub]\n .main{\n background:yellow;\n display:inline-block;\n}\n.sub{\n width:50px;\n height:50px;\n background:blue;\n float:left;\n margin-right:10px;\n opacity:.2;\n}\n.sub2{\n width:50px;\n height:50px;\n background:blue;\n float:left;\n margin-right:10px;\n opacity:.2;\n}\n.main:hover [class^=sub]{\n opacity:1;\n} <div class='main'>\n <div class='sub'></div>\n <div class='sub'></div>\n <div class='sub'></div>\n <div class=\"sub2\"></div>\n</div>"
},
{
"answer_id": 74558831,
"author": "Romualds Cirsis",
"author_id": 1031255,
"author_profile": "https://Stackoverflow.com/users/1031255",
"pm_score": 1,
"selected": false,
"text": ".main:hover div {\n opacity:1;\n}\n .main {\n background:yellow;\n display:inline-block;\n}\ndiv.sub {\n width:50px;\n height:50px;\n background:blue;\n float:left;\n margin-right:10px;\n opacity:.3;\n}\ndiv.sub2 {\n width:50px;\n height:50px;\n background:blue;\n float:left;\n margin-right:10px;\n opacity:.3;\n}\ndiv.sub3 {\n width:25px;\n height:100px;\n background:red;\n opacity:.5;\n}\n\n\n.main:hover div {\n opacity:1;\n border: 1px solid black;\n} <div class='main'>\n <div class='sub'></div>\n <div class='sub'>\n <div class='sub3'></div>\n </div>\n <div class='sub'></div>\n <div class='sub2'></div>\n</div> .main:hover > div {\n opacity:1;\n}\n .main {\n background:yellow;\n display:inline-block;\n}\ndiv.sub {\n width:50px;\n height:50px;\n background:blue;\n float:left;\n margin-right:10px;\n opacity:.3;\n}\ndiv.sub2 {\n width:50px;\n height:50px;\n background:blue;\n float:left;\n margin-right:10px;\n opacity:.3;\n}\ndiv.sub3 {\n width:25px;\n height:100px;\n background:red;\n opacity:.5;\n}\n\n\n.main:hover > div {\n opacity:1;\n border: 1px solid black;\n} <div class='main'>\n <div class='sub'></div>\n <div class='sub'>\n <div class='sub3'></div>\n </div>\n <div class='sub'></div>\n <div class='sub2'></div>\n</div> .main:hover > * {\n opacity:1;\n}\n .main {\n background:yellow;\n display:inline-block;\n}\ndiv.sub {\n width:50px;\n height:50px;\n background:blue;\n float:left;\n margin-right:10px;\n opacity:.3;\n}\ndiv.sub2 {\n width:50px;\n height:50px;\n background:blue;\n float:left;\n margin-right:10px;\n opacity:.3;\n}\ndiv.sub3 {\n width:25px;\n height:100px;\n background:red;\n opacity:.5;\n}\n\n\n.main:hover * {\n opacity:1;\n border: 1px solid black;\n} <div class='main'>\n <div class='sub'></div>\n <div class='sub'>\n <div class='sub3'></div>\n </div>\n <div class='sub'></div>\n <div class='sub2'></div>\n</div>"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74557620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17619616/"
] |
74,557,625
|
<p>The task is to add 10 buttons (0...9) with labels using for in loop.
I created buttons based on class ButtonPrototype. I assigned label to each button via counter inside for in loop.</p>
<p>It works, but there is incorrect labels order:</p>
<p><a href="https://i.stack.imgur.com/ZXjt1.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZXjt1.jpg" alt="enter image description here" /></a></p>
<p>I need another order:</p>
<p><a href="https://i.stack.imgur.com/LhfnW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LhfnW.png" alt="enter image description here" /></a></p>
<p>How can I implement correct order?</p>
<p>Code:</p>
<pre><code>func createButtons() {
for y in 0...1 {
for x in 0...4 {
counterForLoop += 1
self.button = ButtonPrototype(pos: .init( CGFloat(x)/7, CGFloat(y)/7, 0 ), imageName: "\(counterForLoop)")
parentNode.addChildNode(button)
parentNode.position = SCNVector3(x: 100,
y: 100,
z: 100)
}
}
}
</code></pre>
|
[
{
"answer_id": 74557760,
"author": "André",
"author_id": 13970434,
"author_profile": "https://Stackoverflow.com/users/13970434",
"pm_score": 3,
"selected": true,
"text": ".main:hover .sub, .main:hover .sub2{\n opacity:1;\n}\n"
},
{
"answer_id": 74557845,
"author": "Sfili_81",
"author_id": 6592881,
"author_profile": "https://Stackoverflow.com/users/6592881",
"pm_score": 2,
"selected": false,
"text": "[class^=sub]\n .main{\n background:yellow;\n display:inline-block;\n}\n.sub{\n width:50px;\n height:50px;\n background:blue;\n float:left;\n margin-right:10px;\n opacity:.2;\n}\n.sub2{\n width:50px;\n height:50px;\n background:blue;\n float:left;\n margin-right:10px;\n opacity:.2;\n}\n.main:hover [class^=sub]{\n opacity:1;\n} <div class='main'>\n <div class='sub'></div>\n <div class='sub'></div>\n <div class='sub'></div>\n <div class=\"sub2\"></div>\n</div>"
},
{
"answer_id": 74558831,
"author": "Romualds Cirsis",
"author_id": 1031255,
"author_profile": "https://Stackoverflow.com/users/1031255",
"pm_score": 1,
"selected": false,
"text": ".main:hover div {\n opacity:1;\n}\n .main {\n background:yellow;\n display:inline-block;\n}\ndiv.sub {\n width:50px;\n height:50px;\n background:blue;\n float:left;\n margin-right:10px;\n opacity:.3;\n}\ndiv.sub2 {\n width:50px;\n height:50px;\n background:blue;\n float:left;\n margin-right:10px;\n opacity:.3;\n}\ndiv.sub3 {\n width:25px;\n height:100px;\n background:red;\n opacity:.5;\n}\n\n\n.main:hover div {\n opacity:1;\n border: 1px solid black;\n} <div class='main'>\n <div class='sub'></div>\n <div class='sub'>\n <div class='sub3'></div>\n </div>\n <div class='sub'></div>\n <div class='sub2'></div>\n</div> .main:hover > div {\n opacity:1;\n}\n .main {\n background:yellow;\n display:inline-block;\n}\ndiv.sub {\n width:50px;\n height:50px;\n background:blue;\n float:left;\n margin-right:10px;\n opacity:.3;\n}\ndiv.sub2 {\n width:50px;\n height:50px;\n background:blue;\n float:left;\n margin-right:10px;\n opacity:.3;\n}\ndiv.sub3 {\n width:25px;\n height:100px;\n background:red;\n opacity:.5;\n}\n\n\n.main:hover > div {\n opacity:1;\n border: 1px solid black;\n} <div class='main'>\n <div class='sub'></div>\n <div class='sub'>\n <div class='sub3'></div>\n </div>\n <div class='sub'></div>\n <div class='sub2'></div>\n</div> .main:hover > * {\n opacity:1;\n}\n .main {\n background:yellow;\n display:inline-block;\n}\ndiv.sub {\n width:50px;\n height:50px;\n background:blue;\n float:left;\n margin-right:10px;\n opacity:.3;\n}\ndiv.sub2 {\n width:50px;\n height:50px;\n background:blue;\n float:left;\n margin-right:10px;\n opacity:.3;\n}\ndiv.sub3 {\n width:25px;\n height:100px;\n background:red;\n opacity:.5;\n}\n\n\n.main:hover * {\n opacity:1;\n border: 1px solid black;\n} <div class='main'>\n <div class='sub'></div>\n <div class='sub'>\n <div class='sub3'></div>\n </div>\n <div class='sub'></div>\n <div class='sub2'></div>\n</div>"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74557625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19277065/"
] |
74,557,640
|
<p>If you toggle <code>display:flex</code> on a shadow root child it also affects the element outside. (All big browsers behave like this.) Why?</p>
<p>There is a web component with a shadow root:</p>
<pre><code><web-comp style="display: inline-block;"></web-comp>
</code></pre>
<p>Inside the shadow root there is a div with display:flex:</p>
<pre><code>div.style="display:flex; align-items:center; height:50px;"
</code></pre>
<p>The complete example:
<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 demo extends HTMLElement {
connectedCallback() {
const shadow = this.attachShadow({mode: 'open'});
const div = document.createElement('div');
div.innerHTML= "I am in a shadow root!"
div.style="display:flex;align-items:center;height:50px;background:lightblue"
shadow.appendChild(div);
}
}
customElements.define('web-comp', demo);</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code> <h3>flexbox styles do not respect shadow root border</h3>
<web-comp style="display: inline-block;"></web-comp>
And I am not.
<button onclick="document.querySelector('web-comp').shadowRoot.querySelector('div').style.alignItems='baseline'">
Click to change 'align-items' of div in shadow root.
</button></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74559117,
"author": "Krokomot",
"author_id": 19980636,
"author_profile": "https://Stackoverflow.com/users/19980636",
"pm_score": 0,
"selected": false,
"text": "body <p style=\"display:flex;align-items:center;height:50px;background:lightgreen\">And I am not.</p>"
},
{
"answer_id": 74559503,
"author": "Danny '365CSI' Engelman",
"author_id": 2520800,
"author_profile": "https://Stackoverflow.com/users/2520800",
"pm_score": 1,
"selected": false,
"text": "inline-block display-block flex <span> <style>\n web-comp {\n display: inline-block;\n background: lightgreen;\n padding: 1em; /* becomes the \"margin\" above <span> */\n }\n span { background: pink }\n</style>\n<h3>Click the light green boxes</h3>\n<div style=\"background:green\">\n <web-comp></web-comp>\n <span>span</span>\n <span>span</span>\n <span>span</span>\n <web-comp></web-comp>\n <span>span</span>\n <span>span</span>\n</div>\n\n<script>\n customElements.define('web-comp', class extends HTMLElement {\n connectedCallback() {\n this.attachShadow({mode:'open'})\n .append(this.div = document.createElement('div'));\n this.div.style = \"display:flex;height:60px\";\n this.DIValign(\"center\");\n this.onclick = () => {\n if (this.div.style.alignItems == \"center\") this.DIValign(\"baseline\");\n else this.DIValign(\"center\");\n };\n }\n DIValign(val) {\n this.div.innerHTML = ` align-items: ${this.div.style.alignItems = val}`;\n }\n })\n</script>"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74557640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3526448/"
] |
74,557,664
|
<p>I want to see how the containers of an application are distributed/spread in the cluster. Which command can be used to find it out? I want to check if the containers are all running in the same AZ.</p>
|
[
{
"answer_id": 74559117,
"author": "Krokomot",
"author_id": 19980636,
"author_profile": "https://Stackoverflow.com/users/19980636",
"pm_score": 0,
"selected": false,
"text": "body <p style=\"display:flex;align-items:center;height:50px;background:lightgreen\">And I am not.</p>"
},
{
"answer_id": 74559503,
"author": "Danny '365CSI' Engelman",
"author_id": 2520800,
"author_profile": "https://Stackoverflow.com/users/2520800",
"pm_score": 1,
"selected": false,
"text": "inline-block display-block flex <span> <style>\n web-comp {\n display: inline-block;\n background: lightgreen;\n padding: 1em; /* becomes the \"margin\" above <span> */\n }\n span { background: pink }\n</style>\n<h3>Click the light green boxes</h3>\n<div style=\"background:green\">\n <web-comp></web-comp>\n <span>span</span>\n <span>span</span>\n <span>span</span>\n <web-comp></web-comp>\n <span>span</span>\n <span>span</span>\n</div>\n\n<script>\n customElements.define('web-comp', class extends HTMLElement {\n connectedCallback() {\n this.attachShadow({mode:'open'})\n .append(this.div = document.createElement('div'));\n this.div.style = \"display:flex;height:60px\";\n this.DIValign(\"center\");\n this.onclick = () => {\n if (this.div.style.alignItems == \"center\") this.DIValign(\"baseline\");\n else this.DIValign(\"center\");\n };\n }\n DIValign(val) {\n this.div.innerHTML = ` align-items: ${this.div.style.alignItems = val}`;\n }\n })\n</script>"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74557664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/825920/"
] |
74,557,673
|
<p>I am learning <code>LazyColum</code> in <a href="https://developer.android.com/jetpack/compose/lists#lazylistscope" rel="nofollow noreferrer">jetpack compose</a>. I want to add <code>Separator</code> in my each item in some condition, please have a look on below <code>MessageList()</code> function. Also I'll add a screenshot to clearly understand what I want. Please make a function reusable. Condions are as follow:-</p>
<p><strong>1.</strong> <code>Top</code> and <code>Bottom</code> Separator.</p>
<p><a href="https://i.stack.imgur.com/ceqrC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ceqrC.png" alt="enter image description here" /></a></p>
<p><strong>2</strong> Without separator in both <code>Top</code> and <code>Bottom</code></p>
<p><a href="https://i.stack.imgur.com/WfSZO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WfSZO.png" alt="enter image description here" /></a></p>
<p>But problem is that I don't know in idiomatic way in jetpack compose. I did this in Xml using <code>Recyclerview</code>.</p>
<pre><code>import androidx.compose.foundation.lazy.items
@Composable
fun MessageList(messages: List<Message>) {
LazyColumn {
items(messages) { message ->
MessageRow(message)
}
}
}
</code></pre>
<p>Can you guys help me on this? Many Thanks</p>
|
[
{
"answer_id": 74557777,
"author": "Stephan",
"author_id": 1031556,
"author_profile": "https://Stackoverflow.com/users/1031556",
"pm_score": 1,
"selected": false,
"text": "LazyColumn {\n\n items(messages) { message ->\n MessageRow(message)\n Box(Modifier.fillMaxWidth().height(1.dp).background(Color.Red)) //for after every element\n }\n}\n LazyColumn {\n item { Box(Modifier.fillMaxWidth().height(1.dp).background(Color.Red)) }\n items(messages) { message ->\n MessageRow(message)\n }\n}\n LazyColumn {\n itemsIndexed(messages) { index, message ->\n if(index == 0) {\n //First element, either show divider or don't\n }\n ....\n MessageRow(message)\n ....\n if (index == messages.size) {\n // last item, show divider or don't\n }\n }\n}\n"
},
{
"answer_id": 74557816,
"author": "Hamed",
"author_id": 8357673,
"author_profile": "https://Stackoverflow.com/users/8357673",
"pm_score": 0,
"selected": false,
"text": "MessageRow @Composable\nfun MessageRow(message:Message){\n Column(){\n Divider(Modifier.fillMaxWidth(), thickness = 1.dp, color = Color.LightGray) //above your row\n Row(Modifier.fillMaxWidth){\n \n }\n }\n}\n"
},
{
"answer_id": 74558782,
"author": "vivek modi",
"author_id": 11560810,
"author_profile": "https://Stackoverflow.com/users/11560810",
"pm_score": 0,
"selected": false,
"text": "package com.abc.app.common.composables\n\nimport androidx.compose.foundation.layout.*\nimport androidx.compose.foundation.lazy.LazyColumn\nimport androidx.compose.foundation.lazy.itemsIndexed\nimport androidx.compose.material.Divider\nimport androidx.compose.material.Text\nimport androidx.compose.runtime.Composable\nimport androidx.compose.ui.Modifier\nimport androidx.compose.ui.graphics.Color\nimport androidx.compose.ui.res.dimensionResource\nimport androidx.compose.ui.tooling.preview.Preview\nimport com.abc.app.R\nimport com.abc.app.theme.Cloudy\nimport com.abc.app.theme.AbcTheme\nimport com.abc.app.theme.Red\n\n@Composable\nfun <T : Any> LazyListScopeColumn(\n itemList: List<T>,\n content: @Composable (T: Any) -> Unit,\n dividerColor: Color = Cloudy,\n dividerThickness: Int = R.dimen.separator_height_width,\n showDivider: Boolean = true,\n) {\n LazyColumn(modifier = Modifier.fillMaxWidth()) {\n itemsIndexed(itemList) { index, item ->\n if (index == 0 && showDivider) {\n Divider(color = dividerColor, thickness = dimensionResource(dividerThickness))\n }\n content(item)\n if (index <= itemList.lastIndex && showDivider) {\n Divider(color = dividerColor, thickness = dimensionResource(dividerThickness))\n }\n }\n }\n}\n\n@Preview(showBackground = true)\n@Composable\nfun LazyColumnListScopePreview() {\n AbcTheme {\n Column {\n Spacer(modifier = Modifier.height(10.dp)\n LazyListScopeColumn(\n listOf(\"item 1\", \"item 2\"),\n content = { item ->\n Text(\n text = \"$item\",\n modifier = Modifier.padding(vertical = 10.dp)\n )\n },\n dividerColor = Red,\n )\n Spacer(modifier = Modifier.height(10.dp))\n }\n }\n}\n\n@Preview(showBackground = true)\n@Composable\nfun LazyColumnListScopePreviewNoBorder() {\n AbcTheme {\n Column {\n Spacer(modifier = Modifier.height(10.dp)\n LazyListScopeColumn(\n listOf(\"item 1\", \"item 2\"),\n content = { item ->\n Text(\n text = \"$item\",\n modifier = modifier = Modifier.padding(vertical = 10.dp))\n },\n dividerColor = Red,\n showDivider = false,\n )\n Spacer(modifier = Modifier.height(10.dp))\n }\n }\n}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74557673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11560810/"
] |
74,557,686
|
<p>I am creating a header for a chrome extension, but upon implementing the icons an unknow space is added as shown below</p>
<p><a href="https://i.stack.imgur.com/Ug0j5.png" rel="nofollow noreferrer">You can see that the space is only present on buttons with an icon</a></p>
<p>Here is the css for the button element, block and header component</p>
<pre><code>
button {
box-shadow: -4px -4px 10px rgba(56, 68, 90, 0.1), 4px 4px 10px #252B39;
border-radius: 10px;
text-align: center;
border: none;
}
.block {
box-shadow: 0px -20px 60px rgba(0, 0, 0, 0.25);
border-radius: 10px;
}
.header {
text-align: center;
height: 60px;
width: 100%;
border-top-left-radius: 0px;
border-top-right-radius: 0px;
}
.header button {
margin: 10px 15px 0;
width: 40px;
height: 40px;
}
</code></pre>
<p>and here is the html code</p>
<pre><code>
<div class="header block">
<button></button>
<button class="">
<img src="assets/score.svg"/>
</button>
<button class="button-off-dark">
<img src="assets/score.svg"/>
</button>
<button class="button-off-dark">
<img src="assets/score.svg"/>
</button>
</div>
</code></pre>
<p>And here are the icons (score.svg) taken from Figma</p>
<pre><code> <svg width="30" height="26" viewBox="0 0 30 26" fill="none" xmlns="http://www.w3.org/2000/svg">
<g filter="url(#filter0_d_685_136)">
<path d="M26.9697 21.5303C27.2626 21.8232 27.7374 21.8232 28.0303 21.5303C28.3232 21.2374 28.3232 20.7626 28.0303 20.4697L26.9697 21.5303ZM26.1553 18.5947C25.8624 18.3018 25.3876 18.3018 25.0947 18.5947C24.8018 18.8876 24.8018 19.3624 25.0947 19.6553L26.1553 18.5947ZM8.75 14.25C9.16421 14.25 9.5 13.9142 9.5 13.5C9.5 13.0858 9.16421 12.75 8.75 12.75V14.25ZM2.5 12.75C2.08579 12.75 1.75 13.0858 1.75 13.5C1.75 13.9142 2.08579 14.25 2.5 14.25V12.75ZM8.75 8C9.16421 8 9.5 7.66421 9.5 7.25C9.5 6.83579 9.16421 6.5 8.75 6.5V8ZM2.5 6.5C2.08579 6.5 1.75 6.83579 1.75 7.25C1.75 7.66421 2.08579 8 2.5 8V6.5ZM18.75 1.75C19.1642 1.75 19.5 1.41421 19.5 1C19.5 0.585786 19.1642 0.25 18.75 0.25V1.75ZM2.5 0.25C2.08579 0.25 1.75 0.585786 1.75 1C1.75 1.41421 2.08579 1.75 2.5 1.75V0.25ZM28.0303 20.4697L26.1553 18.5947L25.0947 19.6553L26.9697 21.5303L28.0303 20.4697ZM26.75 13.5C26.75 17.2279 23.7279 20.25 20 20.25V21.75C24.5563 21.75 28.25 18.0563 28.25 13.5H26.75ZM20 20.25C16.2721 20.25 13.25 17.2279 13.25 13.5H11.75C11.75 18.0563 15.4437 21.75 20 21.75V20.25ZM13.25 13.5C13.25 9.77208 16.2721 6.75 20 6.75V5.25C15.4437 5.25 11.75 8.94365 11.75 13.5H13.25ZM20 6.75C23.7279 6.75 26.75 9.77208 26.75 13.5H28.25C28.25 8.94365 24.5563 5.25 20 5.25V6.75ZM8.75 12.75H2.5V14.25H8.75V12.75ZM8.75 6.5H2.5V8H8.75V6.5ZM18.75 0.25H2.5V1.75H18.75V0.25Z" fill="white"/>
</g>
<defs>
<filter id="filter0_d_685_136" x="-2.25" y="0.25" width="34.5" height="29.5" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
<feFlood flood-opacity="0" result="BackgroundImageFix"/>
<feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/>
<feOffset dy="4"/>
<feGaussianBlur stdDeviation="2"/>
<feComposite in2="hardAlpha" operator="out"/>
<feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.25 0"/>
<feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_685_136"/>
<feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_685_136" result="shape"/>
</filter>
</defs>
</svg>
</code></pre>
<p>So far, I've tried to change the display to block, use vertical align:top.</p>
<p>It seems to be linked to the component heigth because upon removing the constrains, the extra space dissapear. Howerver I need the button to have a heigth of 40px.</p>
<p>I haven't been able to find another solution so far.</p>
|
[
{
"answer_id": 74557777,
"author": "Stephan",
"author_id": 1031556,
"author_profile": "https://Stackoverflow.com/users/1031556",
"pm_score": 1,
"selected": false,
"text": "LazyColumn {\n\n items(messages) { message ->\n MessageRow(message)\n Box(Modifier.fillMaxWidth().height(1.dp).background(Color.Red)) //for after every element\n }\n}\n LazyColumn {\n item { Box(Modifier.fillMaxWidth().height(1.dp).background(Color.Red)) }\n items(messages) { message ->\n MessageRow(message)\n }\n}\n LazyColumn {\n itemsIndexed(messages) { index, message ->\n if(index == 0) {\n //First element, either show divider or don't\n }\n ....\n MessageRow(message)\n ....\n if (index == messages.size) {\n // last item, show divider or don't\n }\n }\n}\n"
},
{
"answer_id": 74557816,
"author": "Hamed",
"author_id": 8357673,
"author_profile": "https://Stackoverflow.com/users/8357673",
"pm_score": 0,
"selected": false,
"text": "MessageRow @Composable\nfun MessageRow(message:Message){\n Column(){\n Divider(Modifier.fillMaxWidth(), thickness = 1.dp, color = Color.LightGray) //above your row\n Row(Modifier.fillMaxWidth){\n \n }\n }\n}\n"
},
{
"answer_id": 74558782,
"author": "vivek modi",
"author_id": 11560810,
"author_profile": "https://Stackoverflow.com/users/11560810",
"pm_score": 0,
"selected": false,
"text": "package com.abc.app.common.composables\n\nimport androidx.compose.foundation.layout.*\nimport androidx.compose.foundation.lazy.LazyColumn\nimport androidx.compose.foundation.lazy.itemsIndexed\nimport androidx.compose.material.Divider\nimport androidx.compose.material.Text\nimport androidx.compose.runtime.Composable\nimport androidx.compose.ui.Modifier\nimport androidx.compose.ui.graphics.Color\nimport androidx.compose.ui.res.dimensionResource\nimport androidx.compose.ui.tooling.preview.Preview\nimport com.abc.app.R\nimport com.abc.app.theme.Cloudy\nimport com.abc.app.theme.AbcTheme\nimport com.abc.app.theme.Red\n\n@Composable\nfun <T : Any> LazyListScopeColumn(\n itemList: List<T>,\n content: @Composable (T: Any) -> Unit,\n dividerColor: Color = Cloudy,\n dividerThickness: Int = R.dimen.separator_height_width,\n showDivider: Boolean = true,\n) {\n LazyColumn(modifier = Modifier.fillMaxWidth()) {\n itemsIndexed(itemList) { index, item ->\n if (index == 0 && showDivider) {\n Divider(color = dividerColor, thickness = dimensionResource(dividerThickness))\n }\n content(item)\n if (index <= itemList.lastIndex && showDivider) {\n Divider(color = dividerColor, thickness = dimensionResource(dividerThickness))\n }\n }\n }\n}\n\n@Preview(showBackground = true)\n@Composable\nfun LazyColumnListScopePreview() {\n AbcTheme {\n Column {\n Spacer(modifier = Modifier.height(10.dp)\n LazyListScopeColumn(\n listOf(\"item 1\", \"item 2\"),\n content = { item ->\n Text(\n text = \"$item\",\n modifier = Modifier.padding(vertical = 10.dp)\n )\n },\n dividerColor = Red,\n )\n Spacer(modifier = Modifier.height(10.dp))\n }\n }\n}\n\n@Preview(showBackground = true)\n@Composable\nfun LazyColumnListScopePreviewNoBorder() {\n AbcTheme {\n Column {\n Spacer(modifier = Modifier.height(10.dp)\n LazyListScopeColumn(\n listOf(\"item 1\", \"item 2\"),\n content = { item ->\n Text(\n text = \"$item\",\n modifier = modifier = Modifier.padding(vertical = 10.dp))\n },\n dividerColor = Red,\n showDivider = false,\n )\n Spacer(modifier = Modifier.height(10.dp))\n }\n }\n}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74557686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20580361/"
] |
74,557,704
|
<p>I want the text written on my banner image to come down from the top, but when I do that with margin-top the banner portion from the top is coming down with it and the text is stuck on the top.</p>
<p><a href="https://i.stack.imgur.com/9AeUQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9AeUQ.png" alt="Image with problem highlighted" /></a></p>
<p>This is my code, help will be appreciated!</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.banner-image-main {
height: 294px;
width: 100%;
background-image: url('https://www.quackit.com/html/templates/download/bootstrap/business-1/images/light_bulb.jpg');
background-size: cover;
}
.banner-text-and-button {
color: white;
font-family: Arial, Helvetica, sans-serif;
margin-left: 40px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="navbar-default">
<div class="navbar-brand" href="#">
<span class="glyphicon glyphicon-fire pr-2"></span><span>LOGO</span></div>
<ul>
<li>Home</li>
<li>Product</li>
<li>
<select>
<option value="">Services</option>
<option value="">Engage</option>
<option value="">Pontificate</option>
<option value="">Synergize</option>
</select>
</li>
<li>My Account</li>
<li> <span class="glyphicon glyphicon-shopping-cart pr-2"></span>My Cart</li>
</ul>
</div>
<div class="banner-image-main">
<div class="banner-text-and-button">
<h1><span class="glyphicon glyphicon-equalizer"></span>Dramatically Engage</h1>
<p>Objectively innovate empowered manufactured products whereas parallel platforms.</p>
<a class="btn btn-default" href="#" style="margin-left:12px;">Engage Now</a>
</div>
</div>
</div></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74557777,
"author": "Stephan",
"author_id": 1031556,
"author_profile": "https://Stackoverflow.com/users/1031556",
"pm_score": 1,
"selected": false,
"text": "LazyColumn {\n\n items(messages) { message ->\n MessageRow(message)\n Box(Modifier.fillMaxWidth().height(1.dp).background(Color.Red)) //for after every element\n }\n}\n LazyColumn {\n item { Box(Modifier.fillMaxWidth().height(1.dp).background(Color.Red)) }\n items(messages) { message ->\n MessageRow(message)\n }\n}\n LazyColumn {\n itemsIndexed(messages) { index, message ->\n if(index == 0) {\n //First element, either show divider or don't\n }\n ....\n MessageRow(message)\n ....\n if (index == messages.size) {\n // last item, show divider or don't\n }\n }\n}\n"
},
{
"answer_id": 74557816,
"author": "Hamed",
"author_id": 8357673,
"author_profile": "https://Stackoverflow.com/users/8357673",
"pm_score": 0,
"selected": false,
"text": "MessageRow @Composable\nfun MessageRow(message:Message){\n Column(){\n Divider(Modifier.fillMaxWidth(), thickness = 1.dp, color = Color.LightGray) //above your row\n Row(Modifier.fillMaxWidth){\n \n }\n }\n}\n"
},
{
"answer_id": 74558782,
"author": "vivek modi",
"author_id": 11560810,
"author_profile": "https://Stackoverflow.com/users/11560810",
"pm_score": 0,
"selected": false,
"text": "package com.abc.app.common.composables\n\nimport androidx.compose.foundation.layout.*\nimport androidx.compose.foundation.lazy.LazyColumn\nimport androidx.compose.foundation.lazy.itemsIndexed\nimport androidx.compose.material.Divider\nimport androidx.compose.material.Text\nimport androidx.compose.runtime.Composable\nimport androidx.compose.ui.Modifier\nimport androidx.compose.ui.graphics.Color\nimport androidx.compose.ui.res.dimensionResource\nimport androidx.compose.ui.tooling.preview.Preview\nimport com.abc.app.R\nimport com.abc.app.theme.Cloudy\nimport com.abc.app.theme.AbcTheme\nimport com.abc.app.theme.Red\n\n@Composable\nfun <T : Any> LazyListScopeColumn(\n itemList: List<T>,\n content: @Composable (T: Any) -> Unit,\n dividerColor: Color = Cloudy,\n dividerThickness: Int = R.dimen.separator_height_width,\n showDivider: Boolean = true,\n) {\n LazyColumn(modifier = Modifier.fillMaxWidth()) {\n itemsIndexed(itemList) { index, item ->\n if (index == 0 && showDivider) {\n Divider(color = dividerColor, thickness = dimensionResource(dividerThickness))\n }\n content(item)\n if (index <= itemList.lastIndex && showDivider) {\n Divider(color = dividerColor, thickness = dimensionResource(dividerThickness))\n }\n }\n }\n}\n\n@Preview(showBackground = true)\n@Composable\nfun LazyColumnListScopePreview() {\n AbcTheme {\n Column {\n Spacer(modifier = Modifier.height(10.dp)\n LazyListScopeColumn(\n listOf(\"item 1\", \"item 2\"),\n content = { item ->\n Text(\n text = \"$item\",\n modifier = Modifier.padding(vertical = 10.dp)\n )\n },\n dividerColor = Red,\n )\n Spacer(modifier = Modifier.height(10.dp))\n }\n }\n}\n\n@Preview(showBackground = true)\n@Composable\nfun LazyColumnListScopePreviewNoBorder() {\n AbcTheme {\n Column {\n Spacer(modifier = Modifier.height(10.dp)\n LazyListScopeColumn(\n listOf(\"item 1\", \"item 2\"),\n content = { item ->\n Text(\n text = \"$item\",\n modifier = modifier = Modifier.padding(vertical = 10.dp))\n },\n dividerColor = Red,\n showDivider = false,\n )\n Spacer(modifier = Modifier.height(10.dp))\n }\n }\n}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74557704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20588760/"
] |
74,557,749
|
<p>I wrote this code to check if something is a prime number or not.</p>
<pre><code> .data
is_prime: .asciiz "--Prime--"
not_prime: .asciiz "--No prime--"
element: .word 2
.text
main:
#importeer prime messages
la $t3, is_prime
la $t4, not_prime
lw $t1, element
# input variabele n
li $v0, 5
syscall
move $t0, $v0
if_loop:
beq $t0, 1, prime_true
bgt $t0, 1, prime_check
prime_check:
beq $t0, $t1, prime_true
div $t1, $t0
mfhi $t6
beq $t6, 0, prime_false
addi $t0, $t0, 1
prime_true:
li $v0, 4
move $a0, $t3
syscall
j exit
prime_false:
li $v0, 4
move $a0, $t4
syscall
j exit
exit:
</code></pre>
<p>However, every time I run it with any input like 3, 4, 5 or 6 it gives --Prime-- when for 4 and 6 it shouldn't.</p>
|
[
{
"answer_id": 74557777,
"author": "Stephan",
"author_id": 1031556,
"author_profile": "https://Stackoverflow.com/users/1031556",
"pm_score": 1,
"selected": false,
"text": "LazyColumn {\n\n items(messages) { message ->\n MessageRow(message)\n Box(Modifier.fillMaxWidth().height(1.dp).background(Color.Red)) //for after every element\n }\n}\n LazyColumn {\n item { Box(Modifier.fillMaxWidth().height(1.dp).background(Color.Red)) }\n items(messages) { message ->\n MessageRow(message)\n }\n}\n LazyColumn {\n itemsIndexed(messages) { index, message ->\n if(index == 0) {\n //First element, either show divider or don't\n }\n ....\n MessageRow(message)\n ....\n if (index == messages.size) {\n // last item, show divider or don't\n }\n }\n}\n"
},
{
"answer_id": 74557816,
"author": "Hamed",
"author_id": 8357673,
"author_profile": "https://Stackoverflow.com/users/8357673",
"pm_score": 0,
"selected": false,
"text": "MessageRow @Composable\nfun MessageRow(message:Message){\n Column(){\n Divider(Modifier.fillMaxWidth(), thickness = 1.dp, color = Color.LightGray) //above your row\n Row(Modifier.fillMaxWidth){\n \n }\n }\n}\n"
},
{
"answer_id": 74558782,
"author": "vivek modi",
"author_id": 11560810,
"author_profile": "https://Stackoverflow.com/users/11560810",
"pm_score": 0,
"selected": false,
"text": "package com.abc.app.common.composables\n\nimport androidx.compose.foundation.layout.*\nimport androidx.compose.foundation.lazy.LazyColumn\nimport androidx.compose.foundation.lazy.itemsIndexed\nimport androidx.compose.material.Divider\nimport androidx.compose.material.Text\nimport androidx.compose.runtime.Composable\nimport androidx.compose.ui.Modifier\nimport androidx.compose.ui.graphics.Color\nimport androidx.compose.ui.res.dimensionResource\nimport androidx.compose.ui.tooling.preview.Preview\nimport com.abc.app.R\nimport com.abc.app.theme.Cloudy\nimport com.abc.app.theme.AbcTheme\nimport com.abc.app.theme.Red\n\n@Composable\nfun <T : Any> LazyListScopeColumn(\n itemList: List<T>,\n content: @Composable (T: Any) -> Unit,\n dividerColor: Color = Cloudy,\n dividerThickness: Int = R.dimen.separator_height_width,\n showDivider: Boolean = true,\n) {\n LazyColumn(modifier = Modifier.fillMaxWidth()) {\n itemsIndexed(itemList) { index, item ->\n if (index == 0 && showDivider) {\n Divider(color = dividerColor, thickness = dimensionResource(dividerThickness))\n }\n content(item)\n if (index <= itemList.lastIndex && showDivider) {\n Divider(color = dividerColor, thickness = dimensionResource(dividerThickness))\n }\n }\n }\n}\n\n@Preview(showBackground = true)\n@Composable\nfun LazyColumnListScopePreview() {\n AbcTheme {\n Column {\n Spacer(modifier = Modifier.height(10.dp)\n LazyListScopeColumn(\n listOf(\"item 1\", \"item 2\"),\n content = { item ->\n Text(\n text = \"$item\",\n modifier = Modifier.padding(vertical = 10.dp)\n )\n },\n dividerColor = Red,\n )\n Spacer(modifier = Modifier.height(10.dp))\n }\n }\n}\n\n@Preview(showBackground = true)\n@Composable\nfun LazyColumnListScopePreviewNoBorder() {\n AbcTheme {\n Column {\n Spacer(modifier = Modifier.height(10.dp)\n LazyListScopeColumn(\n listOf(\"item 1\", \"item 2\"),\n content = { item ->\n Text(\n text = \"$item\",\n modifier = modifier = Modifier.padding(vertical = 10.dp))\n },\n dividerColor = Red,\n showDivider = false,\n )\n Spacer(modifier = Modifier.height(10.dp))\n }\n }\n}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74557749",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20588909/"
] |
74,557,751
|
<pre class="lang-sql prettyprint-override"><code>select
regexp_substr('a-b--->d--->e f','[^--->]+',1,1) col1
,regexp_substr('a-b--->d--->e f','[^--->]+',1,2) col2
,regexp_substr('a-b--->d--->e f','[^--->]+',1,3) col3
,regexp_substr('a-b--->d--->e f','[^--->]+',1,4) col4
from dual
</code></pre>
<p>output</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>col1</th>
<th>col2</th>
<th>col3</th>
<th>col4</th>
</tr>
</thead>
<tbody>
<tr>
<td>a</td>
<td>b</td>
<td>d</td>
<td>e f</td>
</tr>
</tbody>
</table>
</div>
<p>Required output</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>col1</th>
<th>col2</th>
<th>col3</th>
<th>col4</th>
</tr>
</thead>
<tbody>
<tr>
<td>a-b</td>
<td>d</td>
<td>e f</td>
<td></td>
</tr>
</tbody>
</table>
</div>
|
[
{
"answer_id": 74557846,
"author": "p3consulting",
"author_id": 4956336,
"author_profile": "https://Stackoverflow.com/users/4956336",
"pm_score": 0,
"selected": false,
"text": "select \n regexp_substr('a-b--->d--->e f','[a-z]+([ \\-][a-z]+){0,1}',1,1) col1\n,regexp_substr('a-b--->d--->e f','[a-z]+([ \\-][a-z]+){0,1}',1,2) col2\n,regexp_substr('a-b--->d--->e f','[a-z]+([ \\-][a-z]+){0,1}',1,3) col3\n,regexp_substr('a-b--->d--->e f','[a-z]+([ \\-][a-z]+){0,1}',1,4) col4\n from dual\n ;\n\na-b d e f (null)\n"
},
{
"answer_id": 74558007,
"author": "horcrux",
"author_id": 4607733,
"author_profile": "https://Stackoverflow.com/users/4607733",
"pm_score": 1,
"selected": false,
"text": "[^--->] (-*[^->])+\n >"
},
{
"answer_id": 74558154,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 2,
"selected": true,
"text": "select regexp_substr(value,'(.*?)(-+>|$)',1,1, NULL, 1) AS col1\n, regexp_substr(value,'(.*?)(-+>|$)',1,2, NULL, 1) AS col2\n, regexp_substr(value,'(.*?)(-+>|$)',1,3, NULL, 1) AS col3\n, regexp_substr(value,'(.*?)(-+>|$)',1,4, NULL, 1) AS col4\n from table_name\n ---> SELECT CASE\n WHEN pos1 = 0 THEN value\n ELSE SUBSTR(value, 1, pos1 - 1)\n END AS col1,\n CASE\n WHEN pos1 = 0 THEN NULL\n WHEN pos2 = 0 THEN SUBSTR(value, pos1 + 4)\n ELSE SUBSTR(value, pos1 + 4, pos2 - pos1 - 4)\n END AS col2,\n CASE\n WHEN pos2 = 0 THEN NULL\n WHEN pos3 = 0 THEN SUBSTR(value, pos2 + 4)\n ELSE SUBSTR(value, pos3 + 4, pos3 - pos2 - 4)\n END AS col3,\n CASE\n WHEN pos3 = 0 THEN NULL\n ELSE SUBSTR(value, pos3 + 4)\n END AS col4\nFROM (\n SELECT value,\n INSTR(value, '--->', 1, 1) AS pos1,\n INSTR(value, '--->', 1, 2) AS pos2,\n INSTR(value, '--->', 1, 3) AS pos3\n FROM table_name\n)\n CREATE TABLE table_name (value) AS\nSELECT 'a-b--->d--->e f' FROM DUAL;\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74557751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10378076/"
] |
74,557,763
|
<p>I have a bash script that sets a directory as a lock, and if the lock is in place then it send a message to the user who attempted to run it.</p>
<p>I'm wondering if its possible to somehow suppress the "directory already exists" message, but still run the other function (warning_run_in_place). Because if using the -p flag on mkdir it would not execute the warning_run_in_place portion.</p>
<p>Essentially it's something like</p>
<pre><code>mkdir MYLOCK || warning_run_in_place
warning_run_in_place()
{
echo "Hey I'm already running..."
exit 1;
}
</code></pre>
|
[
{
"answer_id": 74558148,
"author": "Antonio Petricca",
"author_id": 418599,
"author_profile": "https://Stackoverflow.com/users/418599",
"pm_score": 2,
"selected": true,
"text": "mkdir MYLOCK mkdir MYLOCK 2>/dev/null"
},
{
"answer_id": 74558907,
"author": "Dudi Boy",
"author_id": 6266192,
"author_profile": "https://Stackoverflow.com/users/6266192",
"pm_score": 0,
"selected": false,
"text": "-p mkdir mkdir -p MYLOCK || warning_run_in_place\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74557763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18965152/"
] |
74,557,796
|
<p>I have the below data in an excel spreadsheet</p>
<p><a href="https://i.stack.imgur.com/ZFXeX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZFXeX.png" alt="Initial Data" /></a></p>
<p>I want to cycle through column B and capture consecutive Paid Leaves for each employee and generate a another aggregated table like the below one:</p>
<p><a href="https://i.stack.imgur.com/yFLCI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yFLCI.png" alt="End State Data" /></a></p>
<p>So for each employee to calculate the days of consecutive Paid Leaves in an extra row together with a Start and an End date (Start the first day and End the last day of the consecutive Leave).</p>
<p>I haven't managed to think of a way to tackle that. I have minimum experience in VBA and this logic seems very complex to my knowledge so far. I would appreciate if anyone could help.</p>
|
[
{
"answer_id": 74558329,
"author": "Notus_Panda",
"author_id": 19353309,
"author_profile": "https://Stackoverflow.com/users/19353309",
"pm_score": 3,
"selected": true,
"text": "Sub paid_leave()\n Dim wb As Workbook 'declare all your variables upfront and go through your code with F8 from the VBE (VB environment)\n Dim ws As Worksheet, ws2 As Worksheet\n Dim CurrentRow As Long, Lastrow As Long, Lastrow2 As Long, amtDays As Long, i As Long\n \n Set wb = ActiveWorkbook\n Set ws = wb.Sheets(\"Blad1\") 'a lot easier to write the rest of the code with\n Set ws2 = wb.Sheets(\"Blad2\") 'and it helps when you need the change the name of the sheet/workbook\n CurrentRow = 2\n \n Lastrow = ws.Range(\"B\" & Rows.Count).End(xlUp).Row\n amtDays = 1\n For i = CurrentRow To Lastrow 'could technically work with a while loop since we're not using the i and increment our CurrentRow as well\n If ws.Range(\"B\" & CurrentRow).Value2 = \"Paid Leave\" Then\n Lastrow2 = ws2.Range(\"A\" & Rows.Count).End(xlUp).Row\n ws2.Range(\"A\" & Lastrow2 + 1).Value2 = ws.Range(\"C\" & CurrentRow).Value2 'start and endrow not necessary this way\n ws2.Range(\"B\" & Lastrow2 + 1).Value2 = ws.Range(\"B\" & CurrentRow).Value2\n ws2.Range(\"D\" & Lastrow2 + 1).Value2 = ws.Range(\"A\" & CurrentRow).Value2\n 'Do While CurrentRow <> Lastrow 'this is a bad condition, we're already going through all the rows with the for loop, base it on the criteria we want to keep finding aka \"Paid Leave\"\n Do While ws.Range(\"B\" & CurrentRow + 1).Value2 = \"Paid Leave\" 'if it's only one day, CurrentRow and amtDays remain on values where it started\n CurrentRow = CurrentRow + 1\n amtDays = amtDays + 1\n Loop\n ws2.Range(\"C\" & Lastrow2 + 1).Value2 = amtDays\n ws2.Range(\"E\" & Lastrow2 + 1).Value2 = ws.Range(\"A\" & CurrentRow).Value2\n amtDays = 1\n End If\n CurrentRow = CurrentRow + 1\n If CurrentRow > Lastrow Then Exit For 'no need to go further (with a while loop this isn't necessary anymore)\n Next i\nEnd Sub\n"
},
{
"answer_id": 74559650,
"author": "Antonios Prappas",
"author_id": 20588704,
"author_profile": "https://Stackoverflow.com/users/20588704",
"pm_score": 0,
"selected": false,
"text": "Sub paid_leave()\nDim wb As Workbook\nDim sh, sh2 As Worksheet\n\nSet wb = ActiveWorkbook\nSet sh = wb.Sheets(\"Sheet1\")\nSet sh2 = wb.Sheets(\"Sheet2\")\n\nCurrentrow = 2\ni = 2\nlastrow = wb.Sheets(\"Sheet1\").Range(\"A\" & Rows.Count).End(xlUp).Row\namtDays = 1\n\nDo While i <= lastrow\n If wb.Sheets(\"Sheet1\").Range(\"B\" & i).Value2 = \"Paid Leave\" Then\n startRow = i\n endrow = i\n Do While wb.Sheets(\"Sheet1\").Range(\"B\" & i + 1).Value2 = \"Paid Leave\"\n endrow = endrow + 1\n amtDays = amtDays + 1\n i = i + 1\n Loop\n lastrow2 = wb.Sheets(\"Sheet2\").Range(\"A\" & Rows.Count).End(xlUp).Row\n wb.Sheets(\"Sheet2\").Range(\"A\" & lastrow2 + 1).Value2 = wb.Sheets(\"Sheet1\").Range(\"C\" & startRow).Value2\n wb.Sheets(\"Sheet2\").Range(\"B\" & lastrow2 + 1).Value2 = wb.Sheets(\"Sheet1\").Range(\"B\" & startRow).Value2\n wb.Sheets(\"Sheet2\").Range(\"C\" & lastrow2 + 1).Value2 = amtDays\n wb.Sheets(\"Sheet2\").Range(\"D\" & lastrow2 + 1).Value2 = wb.Sheets(\"Sheet1\").Range(\"A\" & startRow).Value2\n wb.Sheets(\"Sheet2\").Range(\"E\" & lastrow2 + 1).Value2 = wb.Sheets(\"Sheet1\").Range(\"A\" & endrow).Value2\n amtDays = 1\n i = i + 1\n End If\n i = i + 1\nLoop\nEnd Sub\n"
},
{
"answer_id": 74561133,
"author": "Ron Rosenfeld",
"author_id": 2872922,
"author_profile": "https://Stackoverflow.com/users/2872922",
"pm_score": 2,
"selected": false,
"text": "Data => Get&Transform => from Table/Range from within sheet Home => Advanced Editor Applied Steps let\n\n//Change Name in next line to reflect actual data source\n Source = Excel.CurrentWorkbook(){[Name=\"Table5\"]}[Content],\n\n//Set the data types\n #\"Changed Type\" = Table.TransformColumnTypes(Source,{{\"Date\", type date}, {\"Status\", type text}, {\"Name\", type text}}),\n\n//Group by status and Name with \"GroupKind.Local\" argument\n #\"Grouped Rows\" = Table.Group(#\"Changed Type\", {\"Status\", \"Name\"}, {\n {\"Days\", each Table.RowCount(_), Int64.Type}, \n {\"Start Date\", each List.Min([Date]), type nullable date}, \n {\"End Date\", each List.Max([Date]), type nullable date}},\n GroupKind.Local),\n\n//Select only \"Paid Leave\" in the Status column\n #\"Filtered Rows\" = Table.SelectRows(#\"Grouped Rows\", each ([Status] = \"Paid Leave\"))\nin\n #\"Filtered Rows\"\n type Date datetime date GroupKind.Local"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74557796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20588704/"
] |
74,557,859
|
<p>In python, I am able to get intersection of multiple lists:</p>
<pre><code>arr = [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
result = set.intersection(*map(set, arr))
</code></pre>
<p>Output:</p>
<pre><code>result = {3}
</code></pre>
<p>Now, I want the result as intersection of all 3 nested lists taken 2 at a time:</p>
<pre><code>result = {2, 3, 4}
</code></pre>
<p>as [2, 3] is common between 1st and 2nd lists, [3, 4] is common between 2nd and 3rd lists and [3] is common between 1st and 3rd lists.</p>
<p>Is there a built in function for this?</p>
|
[
{
"answer_id": 74557895,
"author": "Epsi95",
"author_id": 6660638,
"author_profile": "https://Stackoverflow.com/users/6660638",
"pm_score": 0,
"selected": false,
"text": "itertools.combinations from itertools import combinations\narr = [[1, 2, 3], [2, 3, 4], [3, 4, 5]]\nresult = [set.intersection(*map(set, i)) for i in combinations(arr,2)] \n# print(list(combinations(arr,2)) to get the combinations\n# [{2, 3}, {3}, {3, 4}]\n"
},
{
"answer_id": 74557986,
"author": "bn_ln",
"author_id": 10535824,
"author_profile": "https://Stackoverflow.com/users/10535824",
"pm_score": 1,
"selected": false,
"text": "import itertools as it\narr = [[1, 2, 3], [2, 3, 4], [3, 4, 5]]\nres = set.union(*(set(i).intersection(set(j)) for i,j in it.combinations(arr,2)))\n# output {2, 3, 4}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74557859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15324584/"
] |
74,557,873
|
<p>I have a file that has a large list of Countries, years, and ages of living expectancies. I cannot figure out how to make sure the user is only allowed to input a year that actually exists. After figuring this out, I will need to call only those years (with corresponding country name, code, and living expectancies. How can I do this?</p>
<pre class="lang-py prettyprint-override"><code>
import pathlib
cwd = pathlib.Path(__file__).parent.resolve()
data_file = f'{cwd}/life-expectancy.csv'
with open(data_file) as f:
while True:
user_year = input('Enter the year of interest: ')
for lines in f:
cat = lines.strip().split(',')
country = cat[0]
code = cat[1]
year = cat[2]
age = cat[3]
if any( [year in user_year for year in cat[2]] ):
print(f'Your year is {user_year}. That is one of our known years.')
print(year)
print()
continue
else:
print('Please enter a valid year (1751-2019)')
print('test')
</code></pre>
|
[
{
"answer_id": 74557895,
"author": "Epsi95",
"author_id": 6660638,
"author_profile": "https://Stackoverflow.com/users/6660638",
"pm_score": 0,
"selected": false,
"text": "itertools.combinations from itertools import combinations\narr = [[1, 2, 3], [2, 3, 4], [3, 4, 5]]\nresult = [set.intersection(*map(set, i)) for i in combinations(arr,2)] \n# print(list(combinations(arr,2)) to get the combinations\n# [{2, 3}, {3}, {3, 4}]\n"
},
{
"answer_id": 74557986,
"author": "bn_ln",
"author_id": 10535824,
"author_profile": "https://Stackoverflow.com/users/10535824",
"pm_score": 1,
"selected": false,
"text": "import itertools as it\narr = [[1, 2, 3], [2, 3, 4], [3, 4, 5]]\nres = set.union(*(set(i).intersection(set(j)) for i,j in it.combinations(arr,2)))\n# output {2, 3, 4}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74557873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14018457/"
] |
74,557,877
|
<p>I am creating an android application to save the passwords.
On the main screen i am using recycler view to show all the passwords.
I have 2 two buttons one to add new password and second to update the password, when the user clicks on add new password, new activity (add new password activity) will be open. how should i reload the recycler view on the main screen after returning from the add new password activity?</p>
<p>i tried to recall the initial recyclerview function but it didn't worked.</p>
<pre><code>addData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// action to be performed after it was clicked;
Intent i = new Intent(MainScreen.this, AddNewPassword.class);
i.putExtra("id", (String) null);
i.putExtra("Platform", "");
i.putExtra("User", "");
i.putExtra("password", "");
i.putExtra("boolean", false);
startActivity(i);
}
});
</code></pre>
<p>how should i refresh the current screen after returning fromm the AddNewPassword activity ?</p>
|
[
{
"answer_id": 74557895,
"author": "Epsi95",
"author_id": 6660638,
"author_profile": "https://Stackoverflow.com/users/6660638",
"pm_score": 0,
"selected": false,
"text": "itertools.combinations from itertools import combinations\narr = [[1, 2, 3], [2, 3, 4], [3, 4, 5]]\nresult = [set.intersection(*map(set, i)) for i in combinations(arr,2)] \n# print(list(combinations(arr,2)) to get the combinations\n# [{2, 3}, {3}, {3, 4}]\n"
},
{
"answer_id": 74557986,
"author": "bn_ln",
"author_id": 10535824,
"author_profile": "https://Stackoverflow.com/users/10535824",
"pm_score": 1,
"selected": false,
"text": "import itertools as it\narr = [[1, 2, 3], [2, 3, 4], [3, 4, 5]]\nres = set.union(*(set(i).intersection(set(j)) for i,j in it.combinations(arr,2)))\n# output {2, 3, 4}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74557877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20530242/"
] |
74,557,900
|
<p>The dataframe is as follows:</p>
<p>df1:</p>
<pre><code>name | age | state | number | score
------------------------------------------------------
A 23 AZ 5434567 92.1
B 54 AZ 1234543 87.6
C 32 AZ 7654344 89.9
D 44 GA 8765433 72.4
</code></pre>
<p>df2:</p>
<pre><code>name | age | state | number | score
------------------------------------------------------
A 23 GA 5434567 92.1
D 54 AZ 1234543 76.4
C 33 AZ 7654344 99.9
D 46 GA 8765433 72.4
</code></pre>
<p>The desired dataframe is as follows:</p>
<pre><code>name | age | state | number | score
-------------------------------------------------------
1 1 0 1 1
0 1 1 1 0
1 0 1 1 0
1 0 1 1 1
</code></pre>
<p>The code I tried is:</p>
<pre><code>outputdf = df1.eq(df2)
</code></pre>
<p>and</p>
<pre><code>outputdf = df1.ne(df2)
</code></pre>
<p>But neither of them seem to work correctly.</p>
<p>wrong output after using the <strong>eq</strong> line:</p>
<pre><code>name | age | state | number | score
-------------------------------------------------------
1 1 0 1 0
0 1 1 1 1
1 0 1 1 1
1 0 1 1 1
</code></pre>
<p>wrong output after using the <strong>ne</strong> line:</p>
<pre><code>name | age | state | number | score
-------------------------------------------------------
1 1 0 1 0
0 1 1 1 1
1 0 0 0 1
0 0 0 0 1
</code></pre>
<p>Could anyone please help me out here?
Thank you</p>
|
[
{
"answer_id": 74557935,
"author": "anon01",
"author_id": 5032941,
"author_profile": "https://Stackoverflow.com/users/5032941",
"pm_score": 1,
"selected": false,
"text": "df1.eq(df2).astype(int)\n# or (df1 == df2).astype(int)\n name age state number\n0 1 1 0 1\n1 0 1 1 1\n2 1 0 1 1\n3 1 0 1 1\n"
},
{
"answer_id": 74558143,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 1,
"selected": false,
"text": "out = (df1.select_dtypes('number').round(2) # use the desired precision\n .eq(df2.select_dtypes('number').round(2))\n .astype(int)\n)\n age number score\n0 1 1 1\n1 1 1 0\n2 0 1 0\n3 0 1 1\n # initial output\nout = df1.eq(df2).astype(int)\n\n# correction to account for floating point approximation\n# use the atol/rtol parameters if needed\ncols = list(df1.select_dtypes('number'))\nout[cols] = np.isclose(df1[cols], df2[cols]).astype(int)\n\n# or correction with round\n# out[cols] = df1[cols].round(2).eq(df2[cols].round(2)).astype(int)\n name age state number score\n0 1 1 0 1 1\n1 0 1 1 1 0\n2 1 0 1 1 0\n3 1 0 1 1 1\n"
},
{
"answer_id": 74558172,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 1,
"selected": false,
"text": "numpy.isclose concat cols = df1.select_dtypes('floating').columns\ncols1 = df1.columns.difference(cols)\n\ndf3 = pd.DataFrame(np.isclose(df1[cols], df2[cols]).astype(int), columns=cols)\ndf4 = df1[cols1].eq(df2[cols1]).astype(int)\n\ndf = pd.concat([df3, df4], axis=1).reindex(df1.columns, axis=1)\nprint (df)\n name age state number score\n0 1 1 0 1 1\n1 0 1 1 1 0\n2 1 0 1 1 0\n3 1 0 1 1 1\n"
},
{
"answer_id": 74558596,
"author": "ScottC",
"author_id": 20174226,
"author_profile": "https://Stackoverflow.com/users/20174226",
"pm_score": 0,
"selected": false,
"text": "outputdf = df1.eq(df2).astype(int) df1 = pd.DataFrame({ 'name': ['A', 'B', 'C', 'D'],\n 'age': [23, 54, 32, 44],\n 'state': ['AZ', 'AZ', 'AZ', 'GA'],\n 'number': [5434567, 1234543, 7654344, 8765433],\n 'score': [92.1, 87.6, 89.9, 72.4]})\n\ndf2 = pd.DataFrame({ 'name': ['A', 'D', 'C', 'D'],\n 'age': [23, 54, 33, 46],\n 'state': ['GA', 'AZ', 'AZ', 'GA'],\n 'number': [5434567, 1234543, 7654344, 8765433],\n 'score': [92.1, 76.4, 99.9, 72.4]})\n\noutputdf = df1.eq(df2).astype(int)\nprint(outputdf)\n name age state number score\n0 1 1 0 1 1\n1 0 1 1 1 0\n2 1 0 1 1 0\n3 1 0 1 1 1\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74557900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20346798/"
] |
74,557,942
|
<p>I want to get an individual row from the QueryJob in BQ. My query: <code>select count(*) from ...</code> returns a single row & I want to read the count value which is its first column. So if I can get the first row then I can do <code>row[0]</code> for the first column. I can iterate: <code>row in queryJob</code> but since I require only the first row this seems unneccesary.</p>
<p>Below is what I've tried:</p>
<pre><code>row = self.client.query(count_query)
count = row.result()[0]
</code></pre>
<p>This gives an error:</p>
<pre><code>'QueryJob' object is not subscriptable"
</code></pre>
<p>How can I get individual rows from queryJob by the row index?</p>
|
[
{
"answer_id": 74557935,
"author": "anon01",
"author_id": 5032941,
"author_profile": "https://Stackoverflow.com/users/5032941",
"pm_score": 1,
"selected": false,
"text": "df1.eq(df2).astype(int)\n# or (df1 == df2).astype(int)\n name age state number\n0 1 1 0 1\n1 0 1 1 1\n2 1 0 1 1\n3 1 0 1 1\n"
},
{
"answer_id": 74558143,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 1,
"selected": false,
"text": "out = (df1.select_dtypes('number').round(2) # use the desired precision\n .eq(df2.select_dtypes('number').round(2))\n .astype(int)\n)\n age number score\n0 1 1 1\n1 1 1 0\n2 0 1 0\n3 0 1 1\n # initial output\nout = df1.eq(df2).astype(int)\n\n# correction to account for floating point approximation\n# use the atol/rtol parameters if needed\ncols = list(df1.select_dtypes('number'))\nout[cols] = np.isclose(df1[cols], df2[cols]).astype(int)\n\n# or correction with round\n# out[cols] = df1[cols].round(2).eq(df2[cols].round(2)).astype(int)\n name age state number score\n0 1 1 0 1 1\n1 0 1 1 1 0\n2 1 0 1 1 0\n3 1 0 1 1 1\n"
},
{
"answer_id": 74558172,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 1,
"selected": false,
"text": "numpy.isclose concat cols = df1.select_dtypes('floating').columns\ncols1 = df1.columns.difference(cols)\n\ndf3 = pd.DataFrame(np.isclose(df1[cols], df2[cols]).astype(int), columns=cols)\ndf4 = df1[cols1].eq(df2[cols1]).astype(int)\n\ndf = pd.concat([df3, df4], axis=1).reindex(df1.columns, axis=1)\nprint (df)\n name age state number score\n0 1 1 0 1 1\n1 0 1 1 1 0\n2 1 0 1 1 0\n3 1 0 1 1 1\n"
},
{
"answer_id": 74558596,
"author": "ScottC",
"author_id": 20174226,
"author_profile": "https://Stackoverflow.com/users/20174226",
"pm_score": 0,
"selected": false,
"text": "outputdf = df1.eq(df2).astype(int) df1 = pd.DataFrame({ 'name': ['A', 'B', 'C', 'D'],\n 'age': [23, 54, 32, 44],\n 'state': ['AZ', 'AZ', 'AZ', 'GA'],\n 'number': [5434567, 1234543, 7654344, 8765433],\n 'score': [92.1, 87.6, 89.9, 72.4]})\n\ndf2 = pd.DataFrame({ 'name': ['A', 'D', 'C', 'D'],\n 'age': [23, 54, 33, 46],\n 'state': ['GA', 'AZ', 'AZ', 'GA'],\n 'number': [5434567, 1234543, 7654344, 8765433],\n 'score': [92.1, 76.4, 99.9, 72.4]})\n\noutputdf = df1.eq(df2).astype(int)\nprint(outputdf)\n name age state number score\n0 1 1 0 1 1\n1 0 1 1 1 0\n2 1 0 1 1 0\n3 1 0 1 1 1\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74557942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20220756/"
] |
74,557,958
|
<p>I wanted to select / delete all duplicate rows on multiple table. I have searched the internet for clues but all I see are queries that selects duplicate rows <strong>based one or more column</strong>. Like this:
<code>SELECT col1 count(*) from table_name group by col1 having count(*) > 1</code></p>
<p>What I want to achieve is to select duplicate rows based on <strong>ALL COLUMNS</strong>, as long as all their values in each column are the same.</p>
<p>I am dealing with multiple tables so I want it to be generic so it could work on any tables.</p>
|
[
{
"answer_id": 74558465,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 1,
"selected": false,
"text": "ROWID ROW_NUMBER DELETE FROM table_name\nWHERE ROWID IN (\n SELECT ROWID\n FROM (\n SELECT ROW_NUMBER() OVER (\n PARTITION BY col1, col2, col3, /*...,*/ colN -- List all the columns\n ORDER BY ROWID\n ) AS rn\n FROM table_name\n )\n WHERE rn > 1\n);\n DELETE FROM table_name\nWHERE ROWID IN (\n SELECT ROWID\n FROM (\n SELECT COUNT(*) OVER (\n PARTITION BY col1, col2, col3, /*...,*/ colN -- List all the columns\n ) AS cnt\n FROM table_name\n )\n WHERE cnt > 1\n);\n"
},
{
"answer_id": 74575222,
"author": "psaraj12",
"author_id": 1297792,
"author_profile": "https://Stackoverflow.com/users/1297792",
"pm_score": 0,
"selected": false,
"text": " declare\n l_column_list varchar2(32767);\n l_table_name varchar2(4000) := 'AAAA_DATES';\n begin\n for rec in (select column_name, column_id\n from dba_tab_cols\n where table_name = l_table_name\n order by column_id) loop\n if (rec.column_id = 1) then\n l_column_list := rec.column_name;\n else\n l_column_list := l_column_list || ',' || rec.column_name;\n end if;\n end loop;\n\n execute immediate 'DELETE FROM ' || l_table_name ||\n ' WHERE ROWID IN (\n SELECT ROW_id\n FROM (\n SELECT rowid row_id, ROW_NUMBER() OVER (\n PARTITION BY ' || l_column_list ||\n ' ORDER BY ROWNUM\n ) AS rn\n FROM ' || l_table_name || '\n )\n WHERE rn > 1\n )';\n dbms_output.put_line(sql%rowcount);\n commit;\n end;\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74557958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14745431/"
] |
74,557,996
|
<blockquote>
<p>`views.py</p>
<pre><code>from allauth.account.views import SignupView
from .forms import HODSignUpForm
class HodSignUp(SignupView):
template_name = 'account/signup.html'
form_class = HODSignUpForm
redirect_field_name = ''
view_name = 'hod_sign_up'
def get_context_data(self, **kwargs):
ret = super(HodSignUp, self).get_context_data(**kwargs)
ret.update(self.kwargs)
return ret
</code></pre>
<p>forms.py</p>
<pre><code>from .models import Admin
from po.models import User
from allauth.account.forms import SignupForm
class HODSignUpForm(SignupForm):
first_name=forms.CharField(required=False)
last_name=forms.CharField(required=False)
class Meta:
model= Admin
fields = ['first_name','last_name']
def save(self,request):
user = super(HODSignUpForm, self).save(request)
user.is_hod = True
user= User(first_name=self.cleaned_data.get('first_name'),
last_name=self.cleaned_data.get('last_name'))
user.save()
return user
</code></pre>
</blockquote>
<p>models.py</p>
<blockquote>
<pre><code>from po.models import User
class Admin(models.Model):
user = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL)
first_name = models.CharField(max_length=30, db_column='first_name')
last_name = models.CharField(max_length=30, db_column='last_name')
</code></pre>
<p>po.models.py</p>
<pre><code>from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
is_active = models.BooleanField(default=True)
is_hod= models.BooleanField(default=False)
first_name = models.CharField(null=True, max_length=50)
last_name=models.CharField(null=True, max_length=50)
</code></pre>
</blockquote>
<p><strong>admin.py</strong></p>
<pre><code>from po.models import User
class Schooladmin(admin.ModelAdmin):
list_display = ("id","is_active","is_hod","first_name","last_name")
list_filter = ("is_active","is_hod")
add_fieldsets = (
('Personal Info', {
'fields': ('first_name', 'last_name')
}),
)
</code></pre>
<blockquote>
<p><code>admin.site.register(User,Schooladmin)</code></p>
<pre><code></code></pre>
</blockquote>
<p><a href="https://i.stack.imgur.com/7WTmw.png" rel="nofollow noreferrer">enter image description here</a>
i want this image show name but how does show firstname and lastname on database? <a href="https://i.stack.imgur.com/LA8tN.png" rel="nofollow noreferrer">enter image description here</a> here's porblem.</p>
|
[
{
"answer_id": 74558465,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 1,
"selected": false,
"text": "ROWID ROW_NUMBER DELETE FROM table_name\nWHERE ROWID IN (\n SELECT ROWID\n FROM (\n SELECT ROW_NUMBER() OVER (\n PARTITION BY col1, col2, col3, /*...,*/ colN -- List all the columns\n ORDER BY ROWID\n ) AS rn\n FROM table_name\n )\n WHERE rn > 1\n);\n DELETE FROM table_name\nWHERE ROWID IN (\n SELECT ROWID\n FROM (\n SELECT COUNT(*) OVER (\n PARTITION BY col1, col2, col3, /*...,*/ colN -- List all the columns\n ) AS cnt\n FROM table_name\n )\n WHERE cnt > 1\n);\n"
},
{
"answer_id": 74575222,
"author": "psaraj12",
"author_id": 1297792,
"author_profile": "https://Stackoverflow.com/users/1297792",
"pm_score": 0,
"selected": false,
"text": " declare\n l_column_list varchar2(32767);\n l_table_name varchar2(4000) := 'AAAA_DATES';\n begin\n for rec in (select column_name, column_id\n from dba_tab_cols\n where table_name = l_table_name\n order by column_id) loop\n if (rec.column_id = 1) then\n l_column_list := rec.column_name;\n else\n l_column_list := l_column_list || ',' || rec.column_name;\n end if;\n end loop;\n\n execute immediate 'DELETE FROM ' || l_table_name ||\n ' WHERE ROWID IN (\n SELECT ROW_id\n FROM (\n SELECT rowid row_id, ROW_NUMBER() OVER (\n PARTITION BY ' || l_column_list ||\n ' ORDER BY ROWNUM\n ) AS rn\n FROM ' || l_table_name || '\n )\n WHERE rn > 1\n )';\n dbms_output.put_line(sql%rowcount);\n commit;\n end;\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74557996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16965714/"
] |
74,558,008
|
<p>I'm after a more elegant tidyverse equivalent for <code>[()</code> that works for piping and in chains of pipes. I'm tempted to just wrap around it with my own function, because I ideally want all the functionality for it (working for different datatypes, matrices, vectors, dataframes etc).</p>
<pre><code>piped_subset <- function(x, ...) `[`(x, ...)
</code></pre>
<p>So for example, using this function, the following operations all work.</p>
<pre><code>mat <- matrix(1:25, nrow = 5)
vec <- LETTERS[1:25]
df <- ToothGrowth
l <- list(vec)
mat %>% piped_subset(1, 2)
vec %>% piped_subset(24)
df %>% piped_subset(1, 2)
l %>% piped_subset(1) #not very useful here, but works.
</code></pre>
<p>But I'd be happier if there was a solution out there in one of the common packages, so I'm doing something a little more standard. Any ideas?</p>
<ul>
<li>I'm aware of <code>subset()</code> but for the selection of rows you have to use a logical (and I'm not sure how to access row numbers), so <code>mat %>% subset(1, 2)</code> doesn't work.</li>
<li>I'm aware of <code>filter()</code> and <code>select()</code>, but it takes two steps with them, and it doesn't work on matrices.</li>
<li>I'm aware of <code>pluck()</code> and <code>purr()</code> from <code>dplyr</code> but they do too little. So you have to chain a few together. Plus they don't work on matrices (well pluck does, but not in a useful way).</li>
<li>I'm aware that I can use <code>`[`()</code> but that's just ugly.</li>
</ul>
|
[
{
"answer_id": 74558465,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 1,
"selected": false,
"text": "ROWID ROW_NUMBER DELETE FROM table_name\nWHERE ROWID IN (\n SELECT ROWID\n FROM (\n SELECT ROW_NUMBER() OVER (\n PARTITION BY col1, col2, col3, /*...,*/ colN -- List all the columns\n ORDER BY ROWID\n ) AS rn\n FROM table_name\n )\n WHERE rn > 1\n);\n DELETE FROM table_name\nWHERE ROWID IN (\n SELECT ROWID\n FROM (\n SELECT COUNT(*) OVER (\n PARTITION BY col1, col2, col3, /*...,*/ colN -- List all the columns\n ) AS cnt\n FROM table_name\n )\n WHERE cnt > 1\n);\n"
},
{
"answer_id": 74575222,
"author": "psaraj12",
"author_id": 1297792,
"author_profile": "https://Stackoverflow.com/users/1297792",
"pm_score": 0,
"selected": false,
"text": " declare\n l_column_list varchar2(32767);\n l_table_name varchar2(4000) := 'AAAA_DATES';\n begin\n for rec in (select column_name, column_id\n from dba_tab_cols\n where table_name = l_table_name\n order by column_id) loop\n if (rec.column_id = 1) then\n l_column_list := rec.column_name;\n else\n l_column_list := l_column_list || ',' || rec.column_name;\n end if;\n end loop;\n\n execute immediate 'DELETE FROM ' || l_table_name ||\n ' WHERE ROWID IN (\n SELECT ROW_id\n FROM (\n SELECT rowid row_id, ROW_NUMBER() OVER (\n PARTITION BY ' || l_column_list ||\n ' ORDER BY ROWNUM\n ) AS rn\n FROM ' || l_table_name || '\n )\n WHERE rn > 1\n )';\n dbms_output.put_line(sql%rowcount);\n commit;\n end;\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74558008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20289207/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.