qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,611,040
|
<p>In Android Hilt, you can apply the @Singleton annotation to a function like this:</p>
<pre class="lang-kotlin prettyprint-override"><code>@Module
@InstallIn(SingletonComponent::class)
object SomeModule {
@Singleton
@Provides
fun provideSomething(): String {
return "Hi there"
}
}
</code></pre>
<p>I don't understand what the purpose of using a singleton on a function accomplishes. A class that has the @Singleton means that an instance of the class only exists once. But you cannot create instances of functions, so I don't see the point.</p>
|
[
{
"answer_id": 74611208,
"author": "MoCoding",
"author_id": 11617754,
"author_profile": "https://Stackoverflow.com/users/11617754",
"pm_score": 2,
"selected": false,
"text": "@Singleton @Singleton SingletonComponent ViewModelComponent ViewModel @Provides\nfun provideString(): String {\n return (1..100).random().toString()\n}\n @Singleton provideString @Singleton @Singleton\n@Provides\nfun provideString(): String {\n return (1..100).random().toString()\n}\n provideString"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/753632/"
] |
74,611,048
|
<p>i have</p>
<pre><code>string = 'Server:xxx-zzzzzzzzz.eeeeeeeeeee.frPIPELININGSIZE'
</code></pre>
<p>i need a python regex expression to identify <code>xxx-zzzzzzzzz.eeeeeeeeeee.fr</code> to do a sub-string function to it</p>
<p><strong>Expected output :</strong></p>
<pre><code>string : 'Server:PIPELININGSIZE'
</code></pre>
<p>the URL is inside a string, i tried a lot of regex expressions</p>
|
[
{
"answer_id": 74611208,
"author": "MoCoding",
"author_id": 11617754,
"author_profile": "https://Stackoverflow.com/users/11617754",
"pm_score": 2,
"selected": false,
"text": "@Singleton @Singleton SingletonComponent ViewModelComponent ViewModel @Provides\nfun provideString(): String {\n return (1..100).random().toString()\n}\n @Singleton provideString @Singleton @Singleton\n@Provides\nfun provideString(): String {\n return (1..100).random().toString()\n}\n provideString"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7849021/"
] |
74,611,078
|
<p>I have a number of video files stored on my Synology of which the audio doesn't play on when opening them with DS File. This is because DS File does not support eac3. I would like to convert those files to aac using ffmpeg, but when doing so, all audio is lost.</p>
<p>This is the file info:</p>
<pre><code>Input #0, matroska,webm, from '<file>.mkv':
Metadata:
encoder : libebml v1.4.2 + libmatroska v1.6.4
Duration: 00:48:43.42, start: 0.000000, bitrate: 6566 kb/s
Stream #0:0: Video: h264 (High), yuv420p(progressive), 1920x1080 [SAR 1:1 DAR 16:9], 23.98 fps, 23.98 tbr, 1k tbn, 47.95 tbc (default)
Stream #0:1(eng): Audio: eac3, 48000 Hz, 5.1 (default)
Stream #0:2(eng): Subtitle: subrip
Metadata:
title : English [SDH]
Stream #0:3(ara): Subtitle: subrip
Metadata:
title : Arabic
Stream #0:4(chi): Subtitle: subrip
</code></pre>
<p>This is my attempt:</p>
<pre><code>ffmpeg -i <file>.mkv -map 0:v -map 0:a:0 -map 0:s -c copy -c:a aac -b:a 640k output.mkv
</code></pre>
<p>Subtitles are kept, but audio is completely removed. I would like to automate the process if possible.</p>
<p>This is my ffmpeg configuration:</p>
<pre><code>ffmpeg version 4.1.8 Copyright (c) 2000-2021 the FFmpeg developers
built with gcc 8.5.0 (GCC)
configuration: --prefix=/usr --incdir='${prefix}/include/ffmpeg' --arch=i686 --target-os=linux --cross-prefix=/usr/local/x86_64-pc-linux-gnu/bin/x86_64-pc-linux-gnu- --enable-cross-compile --enable-optimizations --enable-pic --enable-gpl --enable-shared --disable-static --disable-stripping --enable-version3 --enable-encoders --enable-pthreads --disable-protocols --disable-protocol=rtp --enable-protocol=file --enable-protocol=pipe --disable-muxer=image2 --disable-muxer=image2pipe --disable-swscale-alpha --disable-ffplay --disable-ffprobe --disable-doc --disable-devices --disable-bzlib --disable-altivec --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libmp3lame --disable-vaapi --disable-cuvid --disable-nvenc --disable-decoder=aac --disable-decoder=aac_fixed --disable-encoder=aac --disable-decoder=amrnb --disable-decoder=ac3 --disable-decoder=ac3_fixed --disable-encoder=zmbv --disable-encoder=dca --disable-decoder=dca --disable-encoder=ac3 --disable-encoder=ac3_fixed --disable-encoder=eac3 --disable-decoder=eac3 --disable-encoder=truehd --disable-decoder=truehd --disable-encoder=hevc_vaapi --disable-decoder=hevc --disable-muxer=hevc --disable-demuxer=hevc --disable-parser=hevc --disable-bsf=hevc_mp4toannexb --x86asmexe=yasm --cc=/usr/local/x86_64-pc-linux-gnu/bin/x86_64-pc-linux-gnu-wrap-gcc --enable-yasm --enable-libx264 --enable-encoder=libx264
libavutil 56. 22.100 / 56. 22.100
libavcodec 58. 35.100 / 58. 35.100
libavformat 58. 20.100 / 58. 20.100
libavdevice 58. 5.100 / 58. 5.100
libavfilter 7. 40.101 / 7. 40.101
libswscale 5. 3.100 / 5. 3.100
libswresample 3. 3.100 / 3. 3.100
libpostproc 55. 3.100 / 55. 3.100
</code></pre>
<p>Synology does not support eac3 out of the box. So is this even possible?</p>
|
[
{
"answer_id": 74611208,
"author": "MoCoding",
"author_id": 11617754,
"author_profile": "https://Stackoverflow.com/users/11617754",
"pm_score": 2,
"selected": false,
"text": "@Singleton @Singleton SingletonComponent ViewModelComponent ViewModel @Provides\nfun provideString(): String {\n return (1..100).random().toString()\n}\n @Singleton provideString @Singleton @Singleton\n@Provides\nfun provideString(): String {\n return (1..100).random().toString()\n}\n provideString"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/842381/"
] |
74,611,096
|
<p>my question seems to be quite simple. But in the code below, how is it possible to use "prevState" as function without coding the function ?</p>
<pre><code>handleAddOne() {
this.setState(prevState => {
return {
counter: prevState.counter + 1
};
});
}
</code></pre>
<p>`
Here you can see all the code in which handleAddOne() is include.</p>
<pre><code>import React from "react";
import ReactDOM from "react-dom";
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {
counter: 0
};
this.handleAddOne = this.handleAddOne.bind(this);
}
handleAddOne() {
this.setState(prevState => {
return {
counter: prevState.counter + 1
};
});
}
render() {
return (
<div>
<div>Counter: {this.state.counter}</div>
<button onClick={this.handleAddOne}>Add One</button>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<Counter />, rootElement);
</code></pre>
<p>I didn't try anything special, just need explanation.</p>
|
[
{
"answer_id": 74611208,
"author": "MoCoding",
"author_id": 11617754,
"author_profile": "https://Stackoverflow.com/users/11617754",
"pm_score": 2,
"selected": false,
"text": "@Singleton @Singleton SingletonComponent ViewModelComponent ViewModel @Provides\nfun provideString(): String {\n return (1..100).random().toString()\n}\n @Singleton provideString @Singleton @Singleton\n@Provides\nfun provideString(): String {\n return (1..100).random().toString()\n}\n provideString"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17508438/"
] |
74,611,105
|
<p>How to Set expiry time of hsetnx (<a href="https://redis.io/commands/hsetnx/" rel="nofollow noreferrer">https://redis.io/commands/hsetnx/</a>) to be 1 hour. Currently i don't see a param where i can set expiry time to it.</p>
<pre><code>const IoRedis = require("ioredis");
const redis = new IoRedis();
var message = {
"jobdid": "JCLT",
"email": "a@k.com"
}
checkForDuplicate(message);
async function checkForDuplicate(message){
const email = message.email.toLowerCase();
const jobdid = message.jobdid.toLowerCase();
const resp = await redis.hsetnx(`jobs:${email}`, jobdid, +new Date());
console.log(resp);
}
</code></pre>
|
[
{
"answer_id": 74611208,
"author": "MoCoding",
"author_id": 11617754,
"author_profile": "https://Stackoverflow.com/users/11617754",
"pm_score": 2,
"selected": false,
"text": "@Singleton @Singleton SingletonComponent ViewModelComponent ViewModel @Provides\nfun provideString(): String {\n return (1..100).random().toString()\n}\n @Singleton provideString @Singleton @Singleton\n@Provides\nfun provideString(): String {\n return (1..100).random().toString()\n}\n provideString"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5400992/"
] |
74,611,119
|
<p>Problem Statement</p>
<p>You are given a string S consisting only +(Addition),*(Multiplication). The next line will contain two positive values.</p>
<p>Now, Calculate the sum of every operations. See the explanation for more clarification.</p>
<p>Input Format</p>
<pre><code>First line contains a string S, consisting only +(Addition),*(Multiplication) operator.
The second line will contain two positive integers a and b
</code></pre>
<p>Constraints</p>
<pre><code>1 <= |S| <= 20, where |S| means the length of S.
1<= a, b <= 50
</code></pre>
<p>Output Format</p>
<pre><code>Print the summation which were perform based on String S.
</code></pre>
<p>Sample Input 0</p>
<pre><code></code></pre>
<p>type here</p>
<pre><code></code></pre>
<p>+*
5 10</p>
<p>Sample Output 0</p>
<p>65</p>
<p>Explanation 0</p>
<pre><code>when S[i] = '+',Then a+b = 5 + 10 = 15 and sum = 15
when S[i] = '*',Then a*b = 5 * 10 = 50 and sum = 15 + 50 = 65
</code></pre>
<p>Sample Input 1</p>
<p>+***+
2 1</p>
<p>Sample Output 1</p>
<p>12</p>
<p>Following is my attempted code</p>
<pre><code> #include<stdio.h>
int main(){
char S[20];
int a,b,i,sum=0;
scanf("%s %d %d",S, &a,&b);
for(i=0; i<=20; i++){
if (S[i]= "+"){
sum+=a+b;
}
else{
sum+=a*b;
}
}
printf("%d",sum);
return 0;
}
</code></pre>
|
[
{
"answer_id": 74611250,
"author": "Vlad from Moscow",
"author_id": 2877241,
"author_profile": "https://Stackoverflow.com/users/2877241",
"pm_score": 1,
"selected": false,
"text": " if (S[i]= \"+\"){\n = == \"+\" for ( i = 0; S[i] != '\\0'; ++i ){\n if ( S[i] == '+' ){\n sum += a + b;\n }\n else if ( S[i] == '*' ){\n sum += a * b;\n }\n}\n a b [1, 50] scanf scanf( \"%19s %d %d\", S, &a, &b );.\n"
},
{
"answer_id": 74611345,
"author": "Davide",
"author_id": 20631363,
"author_profile": "https://Stackoverflow.com/users/20631363",
"pm_score": -1,
"selected": false,
"text": "if (S[i]= \"+\"){\n =="
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20584362/"
] |
74,611,138
|
<p>I have the following code</p>
<pre><code>while True:
try:
height_input=input(f"Please enter your height in meters : ")
height=float(height_input)
# weight_input=input(f"Please enter your weight in kilograms")
except ValueError:
print("Invalid Input. Please Try Again")
continue
try:
weight_input=input(f"Please enter your weight in kilograms")
weight=float(weight_input)
except ValueError:
print("Invalid Input. Please Try Again")
continue
try:
bmi=weight/(height*height)
print(round(bmi,2))
finally:
break
</code></pre>
<p>If I encounter an error with an invalid format for the line related to the user entering weight, it asks me for the height again even though that might have been entered correctly and was part of the first try block</p>
<p>How do I specify that if an error is encountered in the second try block, to ask the user to input the weight again (which was part of the second try block) and not return to the user input question from the first try block? (the height)</p>
<p>For example <strong>the current result:</strong></p>
<p>Question: Please Enter height</p>
<p>User Input: 2</p>
<p>Question: Please Enter Weight:</p>
<p>User Input: ghsdek</p>
<p>Error Message: "Invalid Input. Please Try Again"</p>
<p>Question: Please Enter height</p>
<p><strong>Expected result:</strong></p>
<p>Question: Please Enter height</p>
<p>User Input: 2</p>
<p>Question: Please Enter Weight:</p>
<p>User Input: ghsdek</p>
<p>Error Message: "Invalid Input. Please Try Again"</p>
<p>Question: Please Enter Weight</p>
|
[
{
"answer_id": 74611214,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 2,
"selected": false,
"text": "try:\n height_input = input(f\"Please enter your height in meters : \")\n height = float(height_input)\nexcept ValueError:\n print(\"Invalid Input. Please Try Again\")\n continue\n continue break"
},
{
"answer_id": 74611223,
"author": "Orfeas Bourchas",
"author_id": 16781682,
"author_profile": "https://Stackoverflow.com/users/16781682",
"pm_score": 2,
"selected": true,
"text": "while True:\n try:\n height_input = input(\"Please enter your height in meters : \")\n height = float(height_input)\n if height != 0:\n break\n\n except Exception:\n print(\"Invalid Input. Please Try Again\")\n\nwhile True:\n try:\n weight_input = input(\"Please enter your weight in kilograms\")\n weight = float(weight_input)\n\n break\n except Exception:\n print(\"Invalid Input. Please Try Again\")\n\nbmi = weight/(height*height)\nprint(f\"Your bmi is: {round(bmi,2)}\")\n\n"
},
{
"answer_id": 74611402,
"author": "bereal",
"author_id": 770830,
"author_profile": "https://Stackoverflow.com/users/770830",
"pm_score": 1,
"selected": false,
"text": "def input_value(msg, type):\n while True:\n try:\n return type(input(msg))\n except ValueError:\n print(\"Invalid Input. Please Try Again\")\n\nweight = input_value(\"Please enter your weight in kilograms: \", float)\nheight = input_value(\"Please enter your height in meters: \", float)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8267774/"
] |
74,611,141
|
<p>I am a little bit confused how containers run. I am developing on a Mac and when I copy my compiled sources into a docker image and Debian OS, I get an error that the file can not be executed. I googled it and it has something to do with different CPU architectures, I needed to cross compile. That makes sense.</p>
<p>This however work:</p>
<pre><code>FROM rust:1.65 AS builder
WORKDIR app
COPY . .
RUN cargo build --release
FROM debian:buster-slim
COPY --from=builder ./app/target/release/hello ./app/myapp
CMD ["./app/myapp"]
</code></pre>
<p>I can build a binary without knowing in advance which architecture I am compiling for right? This is because I just do a <code>cargo build</code> on a builder called <code>rust:1.65</code>. I am curious how it does know it will be ran on Debian and on the correct CPU.</p>
<p>How does <code>FROM rust:1.65</code> compile for the correct architecture? Or is it just all the same default architecture in a Dockerfile?</p>
|
[
{
"answer_id": 74611387,
"author": "Zeppi",
"author_id": 11998029,
"author_profile": "https://Stackoverflow.com/users/11998029",
"pm_score": 0,
"selected": false,
"text": "docker run --rm -ti rust:1.65 rustc --print target-list\n [build]\ntarget = [\"x86_64-unknown-linux-gnu\", \"i686-unknown-linux-gnu\"]\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6162312/"
] |
74,611,165
|
<p>I have a dataframe like below:</p>
<pre><code>df = pd.DataFrame({'id' : [1,2,3],
'attributes' : [{'dd' : True, 'budget' : '35k'}, {'dd' : True, 'budget' : '25k'}, {'dd' : True, 'budget' : '40k'}],
'prod.attributes' : [{'img' : 'img1.url', 'name' : 'millennials'}, {'img' : 'img2.url', 'name' : 'single'}, {'img' : 'img3.url', 'name' : 'married'}]})
df
id attributes prod.attributes
0 1 {'dd': True, 'budget': '35k'} {'img': 'img1.url', 'name': 'millennials'}
1 2 {'dd': True, 'budget': '25k'} {'img': 'img2.url', 'name': 'single'}
2 3 {'dd': True, 'budget': '40k'} {'img': 'img3.url', 'name': 'married'}
</code></pre>
<p>I have multiple such columns wherein I need to append all columns that have <code>attributes</code> as suffix with the actual <code>attributes</code> column as below:</p>
<pre><code>op = pd.DataFrame({'id' : [1,2,3],
'attributes' : [{'dd' : True, 'budget' : '35k', 'prod' : {'img' : 'img1.url', 'name' : 'millennials'}}, \
{'dd' : True, 'budget' : '25k', 'prod' : {'img' : 'img2.url', 'name' : 'single'}},
{'dd' : True, 'budget' : '40', 'prod' : {'img' : 'img3.url', 'name' : 'married'}}]})
</code></pre>
<p>op</p>
<pre><code> id attributes
0 1 {'dd': True, 'budget': '35k', 'prod': {'img': 'img1.url', 'name': 'millennials'}}
1 2 {'dd': True, 'budget': '25k', 'prod': {'img': 'img2.url', 'name': 'single'}}
2 3 {'dd': True, 'budget': '40', 'prod': {'img': 'img3.url', 'name': 'married'}}
</code></pre>
<p>I tried:</p>
<pre><code>df['attributes'].apply(lambda x : x.update({'audience' : df['prod.attributes']}))
</code></pre>
<p>But I am getting all <code>None</code>. Could someone please help me on this.</p>
|
[
{
"answer_id": 74611198,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 3,
"selected": true,
"text": "apply for d1, d2 in zip(df['attributes'], df['prod.attributes']):\n d1['prod'] = d2\n pop for d1, d2 in zip(df['attributes'], df.pop('prod.attributes')):\n d1['prod'] = d2\n id attributes\n0 1 {'dd': True, 'budget': '35k', 'prod': {'img': 'img1.url', 'name': 'millennials'}}\n1 2 {'dd': True, 'budget': '25k', 'prod': {'img': 'img2.url', 'name': 'single'}}\n2 3 {'dd': True, 'budget': '40k', 'prod': {'img': 'img3.url', 'name': 'married'}}\n df = pd.concat([df]*10000, ignore_index=True)\n\n%%timeit\nfor d1, d2 in zip(df['attributes'], df['prod.attributes']):\n d1['prod'] = d2\n3.49 ms ± 137 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n\n%%timeit\ndf['attributes'] = [{**a, **{'prod' : b}} \n for a, b in zip(df['attributes'], df['prod.attributes'])]\n11.3 ms ± 384 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n\n%%timeit\ndf.apply(lambda r: {**r['attributes'], **{'prod': r['prod.attributes']}}, axis=1)\n173 ms ± 7.03 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)\n"
},
{
"answer_id": 74611209,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 1,
"selected": false,
"text": "** DataFrame.pop df['attributes'] = [{**a, **{'prod' : b}} \n for a, b in zip(df['attributes'], df.pop('prod.attributes'))]\nprint (df)\n id attributes\n0 1 {'dd': True, 'budget': '35k', 'prod': {'img': ...\n1 2 {'dd': True, 'budget': '25k', 'prod': {'img': ...\n2 3 {'dd': True, 'budget': '40k', 'prod': {'img': ...\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10722752/"
] |
74,611,203
|
<p>I need to get weight of order, so I need to sum my results
This table looks like this</p>
<pre><code>SalesOrderID SalesOrderDetailID SubTotal CompanyName Weight
------------ ------------------ --------------------- -------------------------------------------------------------------------------------------------------------------------------- ---------------------------------------
71774 110562 880,3484 Good Toys 1061.40
71774 110563 880,3484 Good Toys 988.83
71776 110567 78,81 West Side Mart 317.00
71780 110616 38418,6895 Nearby Cycle Shop 5098.36
71780 110617 38418,6895 Nearby Cycle Shop 24874.88
71780 110618 38418,6895 Nearby Cycle Shop 78053.76
71780 110619 38418,6895 Nearby Cycle Shop 2431.24
71780 110620 38418,6895 Nearby Cycle Shop 12596.19
</code></pre>
<p>The query:</p>
<pre><code>SELECT a.SalesOrderID, c.SalesOrderDetailID, a.SubTotal,b.CompanyName,
(SELECT c.OrderQty*d.Weight WHERE c.SalesOrderID=c.SalesOrderID) AS Weight
FROM SalesLT.SalesOrderHeader as a
INNER JOIN SalesLT.Customer AS b
ON a.CustomerID=b.CustomerID
INNER JOIN SalesLT.SalesOrderDetail AS c
ON c.SalesOrderID=a.SalesOrderID
INNER JOIN SalesLT.Product as d
ON d.ProductID=c.ProductID
</code></pre>
<p>I've tried to make sum as sum(case when) but this gets me an error
Is there any other method?
Expected output:
71774 | 880,3484 | Good Toys | 2050,23</p>
<p>2050,23 is a sum of two rows of weight</p>
|
[
{
"answer_id": 74611280,
"author": "sbrbot",
"author_id": 1443324,
"author_profile": "https://Stackoverflow.com/users/1443324",
"pm_score": 0,
"selected": false,
"text": "SELECT SalesOrderId,SUM(Weight) SumOfOrderWeights\nFROM SalesLT.SalesOrderDetail\nGROUP BY SalesOrderId\nORDER BY SalesOrderId\n"
},
{
"answer_id": 74611529,
"author": "RF1991",
"author_id": 14799981,
"author_profile": "https://Stackoverflow.com/users/14799981",
"pm_score": 0,
"selected": false,
"text": "declare @a table(\n SalesOrderID INTEGER NOT NULL \n ,SalesOrderDetailID INTEGER NOT NULL\n ,SubTotal VARCHAR(60) NOT NULL\n ,CompanyName VARCHAR(60) NOT NULL\n ,Weight float NOT NULL\n \n);\nINSERT INTO @a\n(SalesOrderID,SalesOrderDetailID,SubTotal,CompanyName,Weight) VALUES \n(71774,110562,'880,3484','Good Toys',1061.40),\n(71774,110563,'880,3484','Good Toys',988.83),\n(71776,110567,'78,81','West Side Mart',317.00),\n(71780,110616,'38418,6895','Nearby Cycle Shop',5098.36),\n(71780,110617,'38418,6895','Nearby Cycle Shop',24874.88),\n(71780,110618,'38418,6895','Nearby Cycle Shop',78053.76),\n(71780,110619,'38418,6895','Nearby Cycle Shop',2431.24),\n(71780,110620,'38418,6895','Nearby Cycle Shop',12596.19);\n select SalesOrderID,SubTotal,CompanyName,sum(Weight) Weight from @a\nwhere CompanyName='Good Toys' --removing filter\ngroup by SalesOrderID,SubTotal,CompanyName\n\n"
},
{
"answer_id": 74611599,
"author": "Delta32000",
"author_id": 12939087,
"author_profile": "https://Stackoverflow.com/users/12939087",
"pm_score": 2,
"selected": true,
"text": "WITH TMP_TABLE AS\n(\n SELECT\n a.SalesOrderID,\n c.SalesOrderDetailID,\n a.SubTotal,\n b.CompanyName,\n (c.OrderQty * d.Weight) AS Weight\n FROM SalesLT.SalesOrderHeader as a\n INNER JOIN SalesLT.Customer AS b ON a.CustomerID=b.CustomerID\n INNER JOIN SalesLT.SalesOrderDetail AS c ON c.SalesOrderID=a.SalesOrderID\n INNER JOIN SalesLT.Product as d ON d.ProductID=c.ProductID\n)\nSELECT SalesOrderId,\n SubTotal,\n CompanyName,\n SUM(Weight)\nFROM TMP_TABLE\nGROUP BY SalesOrderId,\n SubTotal,\n CompanyName\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20286995/"
] |
74,611,212
|
<p>I am trying to build a dropdownbutton in flutter, but I am getting an error</p>
<blockquote>
<p>type 'String' is not a subtype of type 'MorphShape' of 'function result'</p>
</blockquote>
<p>I have a class:</p>
<pre><code>class MorphShape {
Shape value;
String name;
MorphShape(this.value, this.name);
}
</code></pre>
<p>I init a list of possible values for the dropdown</p>
<pre><code> final List<MorphShape> morphShapes = [
MorphShape(Shape.rect, 'rect'),
MorphShape(Shape.cross, 'cross'),
MorphShape(Shape.ellipse, 'ellipse')
];
late MorphShape morphKernelShape = morphShapes[2];
</code></pre>
<p>and finally setup the dropdown</p>
<pre><code> Center(
child: Padding(
padding: const EdgeInsets.fromLTRB(0, 0, 0, 25),
child: DropdownButton(
value: morphKernelShape,
onChanged: (MorphShape? morphShape) {
setState(() {
morphKernelShape = morphShape!;
});
},
items: morphShapes.map<DropdownMenuItem<MorphShape>>(
(MorphShape value) {
return DropdownMenuItem(
value: value, child: Text(value.name));
}).toList(),
),
)),
</code></pre>
<p>The IDE itself doesn't highlight anything as a problem, but when I try to run my app it gives me the above stated error. I can't seem to figure out what is the problem here?</p>
|
[
{
"answer_id": 74611280,
"author": "sbrbot",
"author_id": 1443324,
"author_profile": "https://Stackoverflow.com/users/1443324",
"pm_score": 0,
"selected": false,
"text": "SELECT SalesOrderId,SUM(Weight) SumOfOrderWeights\nFROM SalesLT.SalesOrderDetail\nGROUP BY SalesOrderId\nORDER BY SalesOrderId\n"
},
{
"answer_id": 74611529,
"author": "RF1991",
"author_id": 14799981,
"author_profile": "https://Stackoverflow.com/users/14799981",
"pm_score": 0,
"selected": false,
"text": "declare @a table(\n SalesOrderID INTEGER NOT NULL \n ,SalesOrderDetailID INTEGER NOT NULL\n ,SubTotal VARCHAR(60) NOT NULL\n ,CompanyName VARCHAR(60) NOT NULL\n ,Weight float NOT NULL\n \n);\nINSERT INTO @a\n(SalesOrderID,SalesOrderDetailID,SubTotal,CompanyName,Weight) VALUES \n(71774,110562,'880,3484','Good Toys',1061.40),\n(71774,110563,'880,3484','Good Toys',988.83),\n(71776,110567,'78,81','West Side Mart',317.00),\n(71780,110616,'38418,6895','Nearby Cycle Shop',5098.36),\n(71780,110617,'38418,6895','Nearby Cycle Shop',24874.88),\n(71780,110618,'38418,6895','Nearby Cycle Shop',78053.76),\n(71780,110619,'38418,6895','Nearby Cycle Shop',2431.24),\n(71780,110620,'38418,6895','Nearby Cycle Shop',12596.19);\n select SalesOrderID,SubTotal,CompanyName,sum(Weight) Weight from @a\nwhere CompanyName='Good Toys' --removing filter\ngroup by SalesOrderID,SubTotal,CompanyName\n\n"
},
{
"answer_id": 74611599,
"author": "Delta32000",
"author_id": 12939087,
"author_profile": "https://Stackoverflow.com/users/12939087",
"pm_score": 2,
"selected": true,
"text": "WITH TMP_TABLE AS\n(\n SELECT\n a.SalesOrderID,\n c.SalesOrderDetailID,\n a.SubTotal,\n b.CompanyName,\n (c.OrderQty * d.Weight) AS Weight\n FROM SalesLT.SalesOrderHeader as a\n INNER JOIN SalesLT.Customer AS b ON a.CustomerID=b.CustomerID\n INNER JOIN SalesLT.SalesOrderDetail AS c ON c.SalesOrderID=a.SalesOrderID\n INNER JOIN SalesLT.Product as d ON d.ProductID=c.ProductID\n)\nSELECT SalesOrderId,\n SubTotal,\n CompanyName,\n SUM(Weight)\nFROM TMP_TABLE\nGROUP BY SalesOrderId,\n SubTotal,\n CompanyName\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12243689/"
] |
74,611,284
|
<p>i am stuck in my uni assignment....</p>
<p>i have an linked list of 20 elements, i have to take the value from user and if user enter 5 then print the last 5 elements of linked list</p>
<pre><code>void traverse(List list) {
Node *savedCurrentNode = list.currentNode;
list.currentNode = list.headNode;
for(int i = 1; list.next() == true; i++)
{
std::cout << "Element " << i << " " << list.get() << endl;
}
list.currentNode = savedCurrentNode;
}
</code></pre>
<p>im trying this but this method prints all the elements of my linked list</p>
|
[
{
"answer_id": 74612057,
"author": "sweenish",
"author_id": 6119582,
"author_profile": "https://Stackoverflow.com/users/6119582",
"pm_score": 2,
"selected": true,
"text": "// Why are you passing the list by value? That is wasteful.\nvoid traverse(List list) {\n // I don't see you taking a value anywhere; surely you know how to do that\n\n // What is happening here? Can't you just assign the head to something\n // directly?\n Node *savedCurrentNode = list.currentNode;\n list.currentNode = list.headNode;\n \n // Like you said, this traverses the entire list, it's also poorly\n // formed. You literally don't need i.\n // for (; list.next(); /* However your list increments here */)\n for(int i = 1; list.next() == true; i++)\n {\n std::cout << \"Element \" << i << \" \" << list.get() << endl;\n }\n \n // What is the purpose of this?\n list.currentNode = savedCurrentNode;\n}\n #include <iostream>\n\nclass SList {\n public:\n SList() = default;\n\n //\n // Rule of 5 intentionally left out\n //\n\n void push_front(int val) {\n m_head = new Node{val, m_head};\n ++m_size; // The magic happens here\n }\n\n std::size_t size() const { return m_size; }\n\n void traverse_last(int numElements, std::ostream& sout = std::cout) const {\n int placement = m_size;\n Node* walker = m_head;\n\n // Move our walker node the appropriate amount of steps\n while (walker && placement > numElements) {\n walker = walker->next;\n --placement;\n }\n\n // Now that we're in position, we can print\n while (walker) {\n sout << walker->data << ' ';\n walker = walker->next;\n }\n sout << '\\n';\n }\n\n private:\n struct Node {\n int data;\n Node* next = nullptr;\n };\n\n Node* m_head = nullptr;\n std::size_t m_size = 0ULL;\n};\n\nint main() {\n SList test;\n\n for (int i = 5; i > 0; --i) {\n test.push_front(i);\n }\n\n std::cout << \"Size: \" << test.size() << '\\n';\n\n for (int i = 1; i <= 5; ++i) {\n test.traverse_last(i);\n }\n test.traverse_last(10);\n}\n ❯ ./a.out \nSize: 5\n5 \n4 5 \n3 4 5 \n2 3 4 5 \n1 2 3 4 5 \n1 2 3 4 5 \n"
},
{
"answer_id": 74628884,
"author": "mehar sulaiman",
"author_id": 16727373,
"author_profile": "https://Stackoverflow.com/users/16727373",
"pm_score": 0,
"selected": false,
"text": " void traverse(List list, int printFrom)\n{\n Node *savedCurrentNode = list.currentNode;\n list.currentNode = list.headNode;\n \n for(int i=1; list.next(); i++)\n {\n if(i > printFrom)\n {\n cout << \"Element \" << (i - printFrom) << \" \" << list.get() << endl; \n }\n }\n \n list.currentNode = savedCurrentNode;\n}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16727373/"
] |
74,611,289
|
<p>I am using retrofit2 + kotlinx serialization to deserialize the response. The json response look like something like this.</p>
<pre><code>{
"type": "ETA",
"version": "1.0",
"generated_timestamp": "2022-11-29T15:39:57+08:00",
"data": [
{
"co": "KMB",
"route": "91M",
"dir": "I",
"service_type": 1,
"seq": 13,
"dest_tc": "寶林",
"dest_sc": "宝林",
"dest_en": "PO LAM",
"eta_seq": 1,
"eta": "2022-11-29T15:52:21+08:00",
"rmk_tc": "",
"rmk_sc": "",
"rmk_en": "",
"data_timestamp": "2022-11-29T15:39:44+08:00"
},
{
"co": "KMB",
"route": "91M",
"dir": "I",
"service_type": 1,
"seq": 13,
"dest_tc": "寶林",
"dest_sc": "宝林",
"dest_en": "PO LAM",
"eta_seq": 2,
"eta": "2022-11-29T16:06:39+08:00",
"rmk_tc": "原定班次",
"rmk_sc": "原定班次",
"rmk_en": "Scheduled Bus",
"data_timestamp": "2022-11-29T15:39:44+08:00"
},
{
"co": "KMB",
"route": "91M",
"dir": "I",
"service_type": 1,
"seq": 13,
"dest_tc": "寶林",
"dest_sc": "宝林",
"dest_en": "PO LAM",
"eta_seq": 3,
"eta": "2022-11-29T16:21:39+08:00",
"rmk_tc": "原定班次",
"rmk_sc": "原定班次",
"rmk_en": "Scheduled Bus",
"data_timestamp": "2022-11-29T15:39:44+08:00"
}
]
}
</code></pre>
<p>I try parsing with this model.</p>
<pre><code>@Serializable
data class MarsPhoto(
val type: String = "", //The corresponding API that returns the data
val version: String = "",//The version number of the JSON returned.
val generated_timestamp: String = "",//The timestamp of the initial generated time of the response before it is cached.
val data: Eta
)
@Serializable
data class Eta(
val co:String ="KMB",//The bus company
val route: String = "", //The bus route number of the requested bus company
val dir: String = "",//The direction of the bus route
val service_type: String = "",//The service type of the bus route.
val seq: Int = 0, //The stop sequence number of a bus route
val dest_tc: String = "",//The destination of a bus route in Traditional Chinese
val dest_sc: String = "",//The destination of a bus route in Simplified Chinese.
val dest_en: String = "",//The destination of a bus route in English
val eta_seq: Int = 0,//The sequence number of ETA
val eta: String = "-",//The timestamp of the next ETA
val rmk_tc: String = "",//The remark of an ETA in Traditional Chinese
val rmk_sc: String = "",//The remark of an ETA in Simplified Chinese.
val rmk_en: String = "",//The remark of an ETA in English
val data_timestamp: String = "",//The timestamp of the data when it was initially
)
</code></pre>
<p>but an exception occur!</p>
<pre><code>FATAL EXCEPTION: main Process: com.example.marsphotos, PID: 17692 kotlinx.serialization.json.internal.JsonDecodingException: Expected start of the array '[', but had 'EOF' instead at path: $
JSON input: .....heduled Bus","data_timestamp":"2022-11-29T16:30:16+08:00"}]}
</code></pre>
<p>May i get some help</p>
|
[
{
"answer_id": 74611359,
"author": "pro_go_is",
"author_id": 17149124,
"author_profile": "https://Stackoverflow.com/users/17149124",
"pm_score": 1,
"selected": false,
"text": "@Serializable\ndata class MarsPhoto(\n val type: String = \"\", //The corresponding API that returns the data\n val version: String = \"\",//The version number of the JSON returned.\n val generated_timestamp: String = \"\",//The timestamp of the initial generated time of the response before it is cached.\n val data: Data\n)\n@Serializable\ndata class Eta(\n val co:String =\"KMB\",//The bus company\n val route: String = \"\", //The bus route number of the requested bus company\n val dir: String = \"\",//The direction of the bus route\n val service_type: String = \"\",//The service type of the bus route.\n val seq: Int = 0, //The stop sequence number of a bus route\n val dest_tc: String = \"\",//The destination of a bus route in Traditional Chinese\n val dest_sc: String = \"\",//The destination of a bus route in Simplified Chinese.\n val dest_en: String = \"\",//The destination of a bus route in English\n val eta_seq: Int = 0,//The sequence number of ETA\n val eta: String = \"-\",//The timestamp of the next ETA\n val rmk_tc: String = \"\",//The remark of an ETA in Traditional Chinese\n val rmk_sc: String = \"\",//The remark of an ETA in Simplified Chinese.\n val rmk_en: String = \"\",//The remark of an ETA in English\n val data_timestamp: String = \"\",//The timestamp of the data when it was initially\n)\n\n@Serializable\ndata class Data( val data: List<Eta>)\n"
},
{
"answer_id": 74611910,
"author": "Сергей Коротчик",
"author_id": 11774529,
"author_profile": "https://Stackoverflow.com/users/11774529",
"pm_score": 0,
"selected": false,
"text": "@Serializable\ndata class MarsPhoto(\n val type: String = \"\", \n val version: String = \"\",\n val generated_timestamp: String = \"\",\n val data: List<Eta> = emptyList()\n )\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20631295/"
] |
74,611,309
|
<p>I have 2 cols
ID Value</p>
<ol>
<li>ab^bc^ab^de</li>
<li>mn^mn^op</li>
</ol>
<p>I want the output as
ID Value</p>
<ol>
<li>ab^bc^de</li>
<li>mn^op</li>
</ol>
<p>Can someone please help me in this.✋ I have around 500 rows in the table.</p>
<p>I tried using stuff and other ways but errors are popping up.</p>
|
[
{
"answer_id": 74611436,
"author": "Littlefoot",
"author_id": 9097906,
"author_profile": "https://Stackoverflow.com/users/9097906",
"pm_score": 0,
"selected": false,
"text": "SQL> with\n 2 test (col) as\n 3 (select 'ab^bc^ab^de' from dual union all\n 4 select 'mn^mn^op' from dual\n 5 ),\n 6 temp as\n 7 (select\n 8 col,\n 9 regexp_substr(col, '[^\\^]+', 1, column_value) val,\n 10 column_value lvl\n 11 from test cross join\n 12 table(cast(multiset(select level from dual\n 13 connect by level <= regexp_count(col, '\\^') + 1\n 14 ) as sys.odcinumberlist))\n 15 )\n 16 select col,\n 17 listagg(val, '^') within group (order by lvl) as result\n 18 from (select col, val, min(lvl) lvl\n 19 from temp\n 20 group by col, val\n 21 )\n 22 group by col;\n\nCOL RESULT\n----------- --------------------\nab^bc^ab^de ab^bc^de\nmn^mn^op mn^op\n\nSQL>\n"
},
{
"answer_id": 74611610,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 1,
"selected": false,
"text": "LISTAGG(DISTINCT ... WITH bounds ( rid, value, spos, epos ) AS (\n SELECT ROWID, value, 1, INSTR(value, '^', 1)\n FROM table_name\nUNION ALL\n SELECT rid, value, epos + 1, INSTR(value, '^', epos + 1)\n FROM bounds\n WHERE epos > 0\n)\nSELECT LISTAGG(\n DISTINCT \n CASE epos\n WHEN 0\n THEN SUBSTR(value, spos)\n ELSE SUBSTR(value, spos, epos - spos)\n END,\n '^'\n ) WITHIN GROUP (ORDER BY spos) AS unique_values\nFROM bounds\nGROUP BY rid;\n CREATE TABLE table_name (value) AS\nSELECT 'ab^bc^ab^de' FROM DUAL UNION ALL\nSELECT 'mn^mn^op' FROM DUAL UNION ALL\nSELECT 'ab^bc^ab^de' FROM DUAL UNION ALL\nSELECT 'one^two^three^one^two^one^four' FROM DUAL;\n DISTINCT LISTAGG WITH bounds ( rid, value, spos, epos ) AS (\n SELECT ROWID, value, 1, INSTR(value, '^', 1)\n FROM table_name\nUNION ALL\n SELECT rid, value, epos + 1, INSTR(value, '^', epos + 1)\n FROM bounds\n WHERE epos > 0\n),\nwords (rid, word, spos) AS (\n SELECT rid,\n CASE epos\n WHEN 0\n THEN SUBSTR(value, spos)\n ELSE SUBSTR(value, spos, epos - spos)\n END,\n spos\n FROM bounds\n),\nunique_words ( rid, word, spos ) AS (\n SELECT rid,\n word,\n MIN(spos)\n FROM words\n GROUP BY rid, word\n)\nSELECT LISTAGG(word, '^') WITHIN GROUP (ORDER BY spos) AS unique_values\nFROM unique_words\nGROUP BY rid;\n"
},
{
"answer_id": 74611615,
"author": "p3consulting",
"author_id": 4956336,
"author_profile": "https://Stackoverflow.com/users/4956336",
"pm_score": 0,
"selected": false,
"text": "with data(s) as (\n select 'ab^bc^ab^de' from dual union all\n select 'mn^mn^op' from dual\n),\nsplitted(s, l, r) as (\n select s, level, regexp_substr(s,'[^\\^]+',1,level) from data\n connect by regexp_substr(s,'[^\\^]+',1,level) is not null and s = prior s and prior sys_guid() is not null\n)\nselect s, listagg(distinct r, '^') within group(order by l) as r from splitted\ngroup by s\n;\n with data(id, s) as (\n select 1, 'ab^bc^ab^de' from dual union all\n select 2, 'mn^mn^op' from dual\n),\nsplitted(id, l, r) as (\n select id, level, regexp_substr(s,'[^\\^]+',1,level) from data\n connect by regexp_substr(s,'[^\\^]+',1,level) is not null and id = prior id and prior sys_guid() is not null\n)\nselect id, listagg(distinct r, '^') within group(order by l) as r from splitted\ngroup by id\n;\n"
},
{
"answer_id": 74613001,
"author": "p3consulting",
"author_id": 4956336,
"author_profile": "https://Stackoverflow.com/users/4956336",
"pm_score": 0,
"selected": false,
"text": "with data(s) as (\n select 'ab^bc^ab^de' from dual union all\n select 'mn^mn^op' from dual\n)\nselect * \nfrom data, \n xmltable( \n q'{string-join( for $atom in distinct-values((ora:tokenize($X,\"\\^\"))) order by $atom return $atom, \"^\" )}'\n passing s as \"X\"\n columns \n column_value varchar2(64) path '.'\n )\n;\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611309",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19758773/"
] |
74,611,329
|
<p>I am trying to test a class that handles for me the working directory based on a given parameter. To do so, we are using a class variable to map them.</p>
<p>When a specific value is passed, the path is retrieved from the environment variables (See <code>baz</code> in the example below). This is the specific case that I'm trying to test.</p>
<p>I'm using Python <code>3.8.13</code> and <code>unittest</code>.</p>
<h4>I'm trying to avoid:</h4>
<ul>
<li>I don't want to mock the <code>WorkingDirectory.map</code> dictionary because I want to make sure we are fetching from the <code>environ</code> with that particular variable (<code>BAZ_PATH</code>).</li>
<li>Unless is the only solution, I would like to avoid editing the values during the test, i.e I would prefer not to do something like: <code>os.environ["baz"] = DUMMY_BAZ_PATH</code></li>
</ul>
<h4>What I've tried</h4>
<p>I tried mocking up the <code>environ</code> as a dictionary as suggested in other publications, but I can't make it work for some reason.</p>
<pre class="lang-py prettyprint-override"><code># working_directory.py
import os
class WorkingDirectory:
map = {
"foo": "path/to/foo",
"bar": "path/to/bar",
"baz": os.environ.get("BAZ_PATH"),
}
def __init__(self, env: str):
self.env = env
self.path = self.map[self.env]
@property
def data_dir(self):
return os.path.join(self.path, "data")
# Other similar methods...
</code></pre>
<p>Test file:</p>
<pre class="lang-py prettyprint-override"><code># test.py
import os
import unittest
from unittest import mock
from working_directory import WorkingDirectory
DUMMY_BAZ_PATH = "path/to/baz"
class TestWorkingDirectory(unittest.TestCase):
@mock.patch.dict(os.environ, {"BAZ_PATH": DUMMY_BAZ_PATH})
def test_controlled_baz(self):
wd = WorkingDirectory("baz")
self.assertEqual(wd.path, DUMMY_BAZ_PATH)
</code></pre>
<h4>Error</h4>
<p>As shown in the error, <code>os.environ</code> doesn't seem to be properly patched as it returns <code>Null</code>.</p>
<pre><code>======================================================================
FAIL: test_controlled_baz (test_directory_structure_utils.TestWorkingDirectory)
----------------------------------------------------------------------
Traceback (most recent call last):
File "~/.pyenv/versions/3.8.13/lib/python3.8/unittest/mock.py", line 1756, in _inner
return f(*args, **kw)
File "~/Projects/dummy_project/tests/unit/test_directory_structure_utils.py", line 127, in test_controlled_baz
self.assertEqual(wd.path, DUMMY_BAZ_PATH)
AssertionError: None != 'path/to/baz'
----------------------------------------------------------------------
Ran 136 tests in 0.325s
FAILED (failures=1, skipped=5)
</code></pre>
<p>This seems to be because the <code>BAZ_PATH</code> doesn't exist actually. However, I would expect this to be OK since is being patched.</p>
<p>When, in the mapping dictionary, <code>"baz": os.environ.get("BAZ_PATH")</code>, I repalce <code>BAZ_PATH</code> for a variable that actually exist in my environment, i.e <code>HOME</code>, it returns the actual value of <code>HOME</code> instead of the <code>DUMMY_BAZ_PATH</code>, which lead me to think that I'm definetely doing something wrong patching</p>
<pre><code>AssertionError: '/Users/cestla' != 'path/to/baz'
</code></pre>
<h4>Expected result</h4>
<p>Well, obviously, I am expecting the <code>test_controlled_baz</code> passes succesfully.</p>
|
[
{
"answer_id": 74611454,
"author": "Gameplay",
"author_id": 15923186,
"author_profile": "https://Stackoverflow.com/users/15923186",
"pm_score": 0,
"selected": false,
"text": "[tool.pytest.ini_options]\nenv=[\n\"SOME_VAR_FOR_TESTS=some_value_for_that_var\"\n]\n"
},
{
"answer_id": 74612123,
"author": "Nimrod Shanny",
"author_id": 20631164,
"author_profile": "https://Stackoverflow.com/users/20631164",
"pm_score": 4,
"selected": true,
"text": "class WorkingDirectory:\n\ndef __init__(self, env: str):\n self.map = {\n \"foo\": \"path/to/foo\",\n \"bar\": \"path/to/bar\",\n \"baz\": os.environ.get(\"BAZ_PATH\")\n }\n self.env = env\n self.path = self.map[self.env]\n class TestWorkingDirectory(unittest.TestCase):\n@mock.patch.dict(os.environ, {\"BAZ_PATH\": DUMMY_BAZ_PATH})\ndef test_controlled_baz(self):\n with mock.patch.object(WorkingDirectory, \"map\", {\n \"foo\": \"path/to/foo\",\n \"bar\": \"path/to/bar\",\n \"baz\": os.environ.get(\"BAZ_PATH\")\n }):\n wd = WorkingDirectory(\"baz\")\n self.assertEqual(wd.path, DUMMY_BAZ_PATH)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17019651/"
] |
74,611,371
|
<p>Qt noob here.</p>
<p>I've programmed a little GUI application to accomplish a menial task on Qt Creator for Linux (Ubuntu 22.04). It consists of very few classes and a basic user interface.</p>
<p>I'd like to handout a self-contained executable file for a colleague to use on his Windows machine, but I can't find any idiot-proof instructions on how to do it.</p>
<p>Here's a screenshot of an autogenerated directory of the project build:
<a href="https://i.stack.imgur.com/WtGVW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WtGVW.png" alt="Here's a screenshot of an autogenerated directory of the project build" /></a></p>
<p>How do I go from here? What tools do I need?</p>
|
[
{
"answer_id": 74611454,
"author": "Gameplay",
"author_id": 15923186,
"author_profile": "https://Stackoverflow.com/users/15923186",
"pm_score": 0,
"selected": false,
"text": "[tool.pytest.ini_options]\nenv=[\n\"SOME_VAR_FOR_TESTS=some_value_for_that_var\"\n]\n"
},
{
"answer_id": 74612123,
"author": "Nimrod Shanny",
"author_id": 20631164,
"author_profile": "https://Stackoverflow.com/users/20631164",
"pm_score": 4,
"selected": true,
"text": "class WorkingDirectory:\n\ndef __init__(self, env: str):\n self.map = {\n \"foo\": \"path/to/foo\",\n \"bar\": \"path/to/bar\",\n \"baz\": os.environ.get(\"BAZ_PATH\")\n }\n self.env = env\n self.path = self.map[self.env]\n class TestWorkingDirectory(unittest.TestCase):\n@mock.patch.dict(os.environ, {\"BAZ_PATH\": DUMMY_BAZ_PATH})\ndef test_controlled_baz(self):\n with mock.patch.object(WorkingDirectory, \"map\", {\n \"foo\": \"path/to/foo\",\n \"bar\": \"path/to/bar\",\n \"baz\": os.environ.get(\"BAZ_PATH\")\n }):\n wd = WorkingDirectory(\"baz\")\n self.assertEqual(wd.path, DUMMY_BAZ_PATH)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8584417/"
] |
74,611,380
|
<p>I create a form and if the form had any error from the user, I add a django message in the template. It works but it only show the text. I want to highlight it as an error message but I don't know how to add boostrap to message.</p>
<p>I have no idea how to proceed.</p>
|
[
{
"answer_id": 74611454,
"author": "Gameplay",
"author_id": 15923186,
"author_profile": "https://Stackoverflow.com/users/15923186",
"pm_score": 0,
"selected": false,
"text": "[tool.pytest.ini_options]\nenv=[\n\"SOME_VAR_FOR_TESTS=some_value_for_that_var\"\n]\n"
},
{
"answer_id": 74612123,
"author": "Nimrod Shanny",
"author_id": 20631164,
"author_profile": "https://Stackoverflow.com/users/20631164",
"pm_score": 4,
"selected": true,
"text": "class WorkingDirectory:\n\ndef __init__(self, env: str):\n self.map = {\n \"foo\": \"path/to/foo\",\n \"bar\": \"path/to/bar\",\n \"baz\": os.environ.get(\"BAZ_PATH\")\n }\n self.env = env\n self.path = self.map[self.env]\n class TestWorkingDirectory(unittest.TestCase):\n@mock.patch.dict(os.environ, {\"BAZ_PATH\": DUMMY_BAZ_PATH})\ndef test_controlled_baz(self):\n with mock.patch.object(WorkingDirectory, \"map\", {\n \"foo\": \"path/to/foo\",\n \"bar\": \"path/to/bar\",\n \"baz\": os.environ.get(\"BAZ_PATH\")\n }):\n wd = WorkingDirectory(\"baz\")\n self.assertEqual(wd.path, DUMMY_BAZ_PATH)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19068090/"
] |
74,611,385
|
<p>I'm trying to search of multiple words given from a user ( i used array to store them in ) from one txt file , and then if that word presented once in the file it will be displayed and if it's not it won't.
also for the words itself , if it's duplicated it will search it once.</p>
<p>the problem now when i search for only one it worked , but with multiple words it keeps repeated that the word isn't present even if it's there.</p>
<p>i would like to know where should i put the for loop and what's the possible changes.</p>
<pre><code>package search;
import java.io.*;
import java.util.Scanner;
public class Read {
public static void main(String[] args) throws IOException
{
Scanner sc = new Scanner(System.in);
String[] words=null;
FileReader fr = new FileReader("java.txt");
BufferedReader br = new BufferedReader(fr);
String s;
System.out.println("Enter the number of words:");
Integer n = sc.nextInt();
String wordsArray[] = new String[n];
System.out.println("Enter words:");
for(int i=0; i<n; i++)
{
wordsArray[i]=sc.next();
}
for (int i = 0; i <n; i++) {
int count=0; //Intialize the word to zero
while((s=br.readLine())!=null) //Reading Content from the file
{
{
words=s.split(" "); //Split the word using space
for (String word : words)
{
if (word.equals(wordsArray[i])) //Search for the given word
{
count++; //If Present increase the count by one
}
}
if(count == 1)
{
System.out.println(wordsArray[i] + " is unique in file ");
}
else if (count == 0)
{
System.out.println("The given word is not present in the file");
}
else
{
System.out.println("The given word is present in the file more than 1 time");
}
}
}
}
fr.close();
}
}
</code></pre>
|
[
{
"answer_id": 74611454,
"author": "Gameplay",
"author_id": 15923186,
"author_profile": "https://Stackoverflow.com/users/15923186",
"pm_score": 0,
"selected": false,
"text": "[tool.pytest.ini_options]\nenv=[\n\"SOME_VAR_FOR_TESTS=some_value_for_that_var\"\n]\n"
},
{
"answer_id": 74612123,
"author": "Nimrod Shanny",
"author_id": 20631164,
"author_profile": "https://Stackoverflow.com/users/20631164",
"pm_score": 4,
"selected": true,
"text": "class WorkingDirectory:\n\ndef __init__(self, env: str):\n self.map = {\n \"foo\": \"path/to/foo\",\n \"bar\": \"path/to/bar\",\n \"baz\": os.environ.get(\"BAZ_PATH\")\n }\n self.env = env\n self.path = self.map[self.env]\n class TestWorkingDirectory(unittest.TestCase):\n@mock.patch.dict(os.environ, {\"BAZ_PATH\": DUMMY_BAZ_PATH})\ndef test_controlled_baz(self):\n with mock.patch.object(WorkingDirectory, \"map\", {\n \"foo\": \"path/to/foo\",\n \"bar\": \"path/to/bar\",\n \"baz\": os.environ.get(\"BAZ_PATH\")\n }):\n wd = WorkingDirectory(\"baz\")\n self.assertEqual(wd.path, DUMMY_BAZ_PATH)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20552985/"
] |
74,611,396
|
<p>Since I got this error when building project in Xcode,</p>
<pre><code>ModuleNotFoundError: No module named 'requests'
</code></pre>
<p>and then I'm trying to install the requests module with git command.</p>
<pre><code>python toolchain.py pip install requests
</code></pre>
<p>However, I read the logs and I got this FileNotFoundError message. How can I deal with the error?</p>
<pre><code>[INFO ] Using the bundled version for recipe 'host_setuptools3'
[INFO ] Using the bundled version for recipe 'hostopenssl'
[INFO ] Using the bundled version for recipe 'hostpython3'
[INFO ] Global: hostpython located at /Users/<myname>/Desktop/kivy/kivy-ios/dist/hostpython3/bin/python
[INFO ] Global: hostpgen located at /Users/<myname>/Desktop/kivy/kivy-ios/dist/hostpython3/bin/pgen
[INFO ] Using the bundled version for recipe 'ios'
[INFO ] Using the bundled version for recipe 'kivy'
[INFO ] Using the bundled version for recipe 'libffi'
[INFO ] Include dir added: {arch.arch}/ffi
[INFO ] Using the bundled version for recipe 'openssl'
[INFO ] Include dir added: {arch.arch}/openssl
[INFO ] Using the bundled version for recipe 'pyobjus'
[INFO ] Using the bundled version for recipe 'python3'
[INFO ] Using the bundled version for recipe 'sdl2'
[INFO ] Include dir added: common/sdl2
[INFO ] Using the bundled version for recipe 'sdl2_image'
[INFO ] Include dir added: common/sdl2_image
[INFO ] Using the bundled version for recipe 'sdl2_mixer'
[INFO ] Include dir added: common/sdl2_mixer
[INFO ] Using the bundled version for recipe 'sdl2_ttf'
[INFO ] Include dir added: common/sdl2_ttf
[INFO ] Executing pip with: ['install', '--isolated', '--prefix', '/Users/<myname>/Desktop/kivy/kivy-ios/dist/root/python3', 'requests']
[INFO ] Running Shell: /Users/<myname>/Desktop/kivy/kivy-ios/dist/hostpython3/bin/pip3 ('install', '--isolated', '--prefix', '/Users/<myname>/Desktop/kivy/kivy-ios/dist/root/python3', 'requests') {'_env': {'CC': '/bin/false', 'CXX': '/bin/false', 'PYTHONPATH': '/Users/<myname>/Desktop/kivy/kivy-ios/dist/root/python3/lib/python3.9/site-packages', 'PYTHONOPTIMIZE': '2'}, '_iter': True, '_out_bufsize': 1, '_err_to_out': True}
Traceback (most recent call last):
File "/Users/<myname>/Desktop/kivy/kivy-ios/toolchain.py", line 3, in <module>
main()
File "/Users/<myname>/Desktop/kivy/kivy-ios/kivy_ios/toolchain.py", line 1555, in main
ToolchainCL()
File "/Users/<myname>/Desktop/kivy/kivy-ios/kivy_ios/toolchain.py", line 1299, in __init__
getattr(self, args.command)()
File "/Users/<myname>/Desktop/kivy/kivy-ios/kivy_ios/toolchain.py", line 1514, in pip
_pip(sys.argv[2:])
File "/Users/<myname>/Desktop/kivy/kivy-ios/kivy_ios/toolchain.py", line 1186, in _pip
shprint(pip_cmd, *args, _env=pip_env)
File "/Users/<myname>/Desktop/kivy/kivy-ios/kivy_ios/toolchain.py", line 55, in shprint
cmd = command(*args, **kwargs)
File "/Users/<myname>/Desktop/kivy/kivy-ios/posEnv/lib/python3.9/site-packages/sh.py", line 1524, in __call__
return RunningCommand(cmd, call_args, stdin, stdout, stderr)
File "/Users/<myname>/Desktop/kivy/kivy-ios/posEnv/lib/python3.9/site-packages/sh.py", line 780, in __init__
self.process = OProc(self, self.log, cmd, stdin, stdout, stderr,
File "/Users/<myname>/Desktop/kivy/kivy-ios/posEnv/lib/python3.9/site-packages/sh.py", line 2125, in __init__
raise ForkException(fork_exc)
sh.ForkException:
Original exception:
===================
Traceback (most recent call last):
File "/Users/gordonkwok/Desktop/kivy/kivy-ios/<myenv>/lib/python3.9/site-packages/sh.py", line 2080, in __init__
os.execve(cmd[0], cmd, ca["env"])
FileNotFoundError: [Errno 2] No such file or directory: b'/Users/<myname>/Desktop/kivy/kivy-ios/dist/hostpython3/bin/pip3'
</code></pre>
<p>So I looked the file "/Users//Desktop/kivy/kivy-ios/dist/hostpython3/bin/pip3" and the virtual environment file "/Users//Desktop/kivy/kivy-ios//lib/python3.9/site-packages/sh.py" to see whether they are existed. And both of them are really existed! I'm so confuse with this error. So please help me out here! It is the finally step for me to run my first app soon! Thanks!</p>
|
[
{
"answer_id": 74611517,
"author": "Koedlt",
"author_id": 15405732,
"author_profile": "https://Stackoverflow.com/users/15405732",
"pm_score": 2,
"selected": false,
"text": "toolchain.py requests pip install <module> source <your-venv-path>/bin/activate <your-venv-path>\\Scripts\\activate.bat pip install requests python toolchain.py"
},
{
"answer_id": 74675704,
"author": "Gordon",
"author_id": 19013111,
"author_profile": "https://Stackoverflow.com/users/19013111",
"pm_score": 2,
"selected": true,
"text": "sudo toolchain.py build python kivy toolchain.py build python kivy"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19013111/"
] |
74,611,417
|
<p>I created a new Vue app using <code>npm init vue@latest</code> and selected Playwright for e2e tests. I removed <strong>firefox</strong> and <strong>webkit</strong> from projects in the <code>playwright.config.ts</code> file, so it will only use <strong>chromium</strong>.</p>
<p>Running <code>npm run test:e2e</code> works fine, the process exists with a success code.</p>
<p>When forcing the tests to fail by modifying the <code>./e2e/vue.spec.ts</code> file the output is</p>
<p><a href="https://i.stack.imgur.com/xT7IO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xT7IO.png" alt="enter image description here" /></a></p>
<p>but the process does not exit with an error code, it still opened browser windows and so CI environments would freeze.</p>
<p>I searched <a href="https://playwright.dev/docs/test-cli" rel="nofollow noreferrer">the docs</a> for a specific flag e.g. "headless" and tried <code>--max-failures -x</code> but that didn't help.</p>
<p>How can I tell Playwright to run in headless mode and exit with an error code when something failed?</p>
<hr />
<p>Since <em>playwright.config.ts</em> already makes use of <code>process.env.CI</code> I thought about replacing <code>reporter: "html",</code> with <code>reporter: [["html", { open: !process.env.CI ? "on-failure" : "never" }]],</code></p>
<p>but which arguments should I add to the script <code>"test:e2e:ci": "playwright test",</code> to ensure <code>process.env.CI</code> is set?</p>
|
[
{
"answer_id": 74611517,
"author": "Koedlt",
"author_id": 15405732,
"author_profile": "https://Stackoverflow.com/users/15405732",
"pm_score": 2,
"selected": false,
"text": "toolchain.py requests pip install <module> source <your-venv-path>/bin/activate <your-venv-path>\\Scripts\\activate.bat pip install requests python toolchain.py"
},
{
"answer_id": 74675704,
"author": "Gordon",
"author_id": 19013111,
"author_profile": "https://Stackoverflow.com/users/19013111",
"pm_score": 2,
"selected": true,
"text": "sudo toolchain.py build python kivy toolchain.py build python kivy"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19698303/"
] |
74,611,428
|
<p>There is a span dropdown and inside there are 3 more dropdowns. I need to first select "home" and then "task tracking" and the option in that drop down.</p>
<p>I have seen the <code>iframe</code> present in the source code and I am not able to find and put the solution in my python code.</p>
<p><a href="https://i.stack.imgur.com/qbxlx.png" rel="nofollow noreferrer">example HTML</a></p>
<p>Both <code>find_element_by_css_selector</code> and <code>find_element_by_xpath</code> are giving the error</p>
<pre><code>Errors- AttributeError: type object 'By' has no attribute 'tagName'
</code></pre>
<p>This is my code:</p>
<pre><code>size = self.driver.find_element(By.tagName("iframe"))
print(size)
self.driver.find_element_by_css_selector('#TitleCaret').click() #Drop down
sleep(10)
self.driver.find_element_by_css_selector('#chrome-sidebar > div > div.chrome-links > ul > li:nth-child(1) > a').click() #Select Director from drop down
#self.driver.find_element_by_xpath('//*[@id="LoanBar"]/span[2]/button').click()
size = self.driver.find_element(By.tagName("iframe"))
print(size)
WebDriverWait(self.driver, 30).until(EC.frame_to_be_available_and_switch_to_it(By.ID, self.iframe_id))
sleep(10)
self.driver.switch_to.frame(self.iframe_id)
#self.driver.switch_to.frame('ifr_APP')
self.driver.find_element_by_css_selector('#LoanBar > span.dropdown > button').click()
</code></pre>
|
[
{
"answer_id": 74611517,
"author": "Koedlt",
"author_id": 15405732,
"author_profile": "https://Stackoverflow.com/users/15405732",
"pm_score": 2,
"selected": false,
"text": "toolchain.py requests pip install <module> source <your-venv-path>/bin/activate <your-venv-path>\\Scripts\\activate.bat pip install requests python toolchain.py"
},
{
"answer_id": 74675704,
"author": "Gordon",
"author_id": 19013111,
"author_profile": "https://Stackoverflow.com/users/19013111",
"pm_score": 2,
"selected": true,
"text": "sudo toolchain.py build python kivy toolchain.py build python kivy"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20631406/"
] |
74,611,432
|
<p>json data</p>
<pre><code> const json = [{
link: "animal",
type: [{
link: "animal/dog"
},
{
link: "animal/cat",
type: [{
link: "animal/cat/savannah"
},
{
link: "animal/cat/bombay"
}
]
}
]
},
{
link: "car",
type: [{
link: "car/dodge"
},
{
link: "car/mazda",
type: [{
link: "car/mazda/mx5"
}]
}
]
}
];
</code></pre>
|
[
{
"answer_id": 74611517,
"author": "Koedlt",
"author_id": 15405732,
"author_profile": "https://Stackoverflow.com/users/15405732",
"pm_score": 2,
"selected": false,
"text": "toolchain.py requests pip install <module> source <your-venv-path>/bin/activate <your-venv-path>\\Scripts\\activate.bat pip install requests python toolchain.py"
},
{
"answer_id": 74675704,
"author": "Gordon",
"author_id": 19013111,
"author_profile": "https://Stackoverflow.com/users/19013111",
"pm_score": 2,
"selected": true,
"text": "sudo toolchain.py build python kivy toolchain.py build python kivy"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19519538/"
] |
74,611,456
|
<p>I want to load data from MySQL to BigQuery using Cloud Dataflow. Anyone can share article or work experience about load data from MySQL to BigQuery using Cloud Dataflow with Python language?</p>
<p>Thank you</p>
|
[
{
"answer_id": 74649475,
"author": "Mazlum Tosun",
"author_id": 9261558,
"author_profile": "https://Stackoverflow.com/users/9261558",
"pm_score": 0,
"selected": false,
"text": "MySQL BigQuery MySql Cloud Storage BigQuery Dataflow MySQL Cloud Storage sql gcloud gcloud sql export csv INSTANCE_NAME gs://BUCKET_NAME/FILE_NAME \\\n--database=DATABASE_NAME \\\n--offload \\\n--query=SELECT_QUERY \\\n--quote=\"22\" \\\n--escape=\"5C\" \\\n--fields-terminated-by=\"2C\" \\\n--lines-terminated-by=\"0A\"\n csv BigQuery gcloud bq bq load \\\n --source_format=CSV \\\n mydataset.mytable \\\n gs://mybucket/mydata.csv \\\n ./myschema.json\n ./myschema.json BigQuery"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13939457/"
] |
74,611,463
|
<p>I have this code</p>
<pre><code>import numpy
a=numpy.pad(numpy.empty([8,8]), 1, constant_values=1)
print(a)
</code></pre>
<p>50% of the times I execute it it prints a normal array, 50% of times it prints this</p>
<pre><code>[[ 1.00000000e+000 1.00000000e+000 1.00000000e+000 1.00000000e+000
1.00000000e+000 1.00000000e+000 1.00000000e+000 1.00000000e+000
1.00000000e+000 1.00000000e+000]
[ 1.00000000e+000 3.25639960e-265 2.03709399e-231 -7.49281680e-111
9.57832017e-299 8.17611616e-093 9.57832017e-299 1.31887592e+066
-2.29724802e+236 1.00000000e+000]
[ 1.00000000e+000 5.11889256e-014 -2.29724802e+236 2.19853714e-004
-2.29724802e+236 -9.20964279e+232 2.37057719e+043 1.48921177e+048
5.29583156e-235 1.00000000e+000]
[ 1.00000000e+000 6.37391724e+057 5.68896808e-235 2.73626021e+067
6.08210460e-235 1.17578020e+077 6.66029790e-235 7.05235822e-235
2.13106310e-308 1.00000000e+000]
[ 1.00000000e+000 7.83852638e-235 2.13214956e-308 8.62479942e-235
2.13323602e-308 9.41107246e-235 2.13432248e-308 1.61214828e+063
1.35001671e-284 1.00000000e+000]
[ 1.00000000e+000 7.20990215e-264 9.57831969e-299 5.06352214e+139
3.18093720e+144 1.21642092e-234 1.25562635e-234 2.13866833e-308
1.41045067e-234 1.00000000e+000]
[ 1.00000000e+000 2.13975479e-308 1.56770528e-234 2.14084125e-308
1.72495988e-234 2.14192771e-308 1.88221449e-234 2.14301418e-308
2.03946910e-234 1.00000000e+000]
[ 1.00000000e+000 2.14410064e-308 2.19672371e-234 2.14518710e-308
2.35397832e-234 2.14627356e-308 1.61656736e+063 1.35004493e-284
7.20998544e-264 1.00000000e+000]
[ 1.00000000e+000 3.93674833e-241 7.20999301e-264 6.00700127e-246
2.03709519e-231 -5.20176578e-111 9.57832021e-299 5.66452894e+075
-2.29724802e+236 1.00000000e+000]
[ 1.00000000e+000 1.00000000e+000 1.00000000e+000 1.00000000e+000
1.00000000e+000 1.00000000e+000 1.00000000e+000 1.00000000e+000
1.00000000e+000 1.00000000e+000]]
</code></pre>
<p>what is worse, when i do .astype(int) it keeps doing this</p>
<pre><code>[[ 1 1 1 1 1 1
1 1 1 1]
[ 1 0 0 0 -2147483648 0
-2147483648 0 0 1]
[ 1 0 0 -2147483648 0 0
0 0 -2147483648 1]
[ 1 0 0 0 0 -2147483648
0 0 0 1]
[ 1 0 0 0 0 0
-2147483648 0 0 1]
[ 1 0 0 -2147483648 0 0
0 0 0 1]
[ 1 0 -2147483648 0 0 0
-2147483648 0 -2147483648 1]
[ 1 0 -2147483648 -2147483648 0 -2147483648
0 0 -2147483648 1]
[ 1 0 0 0 0 0
0 0 0 1]
[ 1 1 1 1 1 1
1 1 1 1]]
</code></pre>
<p>tried on normal python 3.11 and anaconda 3.9.</p>
<p>I googled but I couldn't find a way to fix this, so any help would be much appreciated. The post needs to have more text so that it isn't "mostly code" and it lets me post it. I would like to know if there are any good ways to solve the issue I've described. As I wrote, I tested it on two different versions of python. Unfortunately, both lead to the same issue.</p>
|
[
{
"answer_id": 74649475,
"author": "Mazlum Tosun",
"author_id": 9261558,
"author_profile": "https://Stackoverflow.com/users/9261558",
"pm_score": 0,
"selected": false,
"text": "MySQL BigQuery MySql Cloud Storage BigQuery Dataflow MySQL Cloud Storage sql gcloud gcloud sql export csv INSTANCE_NAME gs://BUCKET_NAME/FILE_NAME \\\n--database=DATABASE_NAME \\\n--offload \\\n--query=SELECT_QUERY \\\n--quote=\"22\" \\\n--escape=\"5C\" \\\n--fields-terminated-by=\"2C\" \\\n--lines-terminated-by=\"0A\"\n csv BigQuery gcloud bq bq load \\\n --source_format=CSV \\\n mydataset.mytable \\\n gs://mybucket/mydata.csv \\\n ./myschema.json\n ./myschema.json BigQuery"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15673832/"
] |
74,611,478
|
<p>Consider this database model:</p>
<pre><code>Book
isbn primary key
title
</code></pre>
<p>In a RDBMS, the database makes sure that two identical rows don't exist for the above model.</p>
<p>Similarly, in Java consider this object model:</p>
<pre><code>Book
- isbn: int
- title: String
+ Book(isbn)
</code></pre>
<p>Let's say we are creating a Book object:</p>
<pre><code>Book b = new Book(123456);
</code></pre>
<p>Later, in some other part of the code we are creating again an identical Book object:</p>
<pre><code>Book c = new Book(123456);
</code></pre>
<p>Can Java make sure that no two objects exist in the JVM heap if they are identical? Just like a RDBMS does?</p>
|
[
{
"answer_id": 74611625,
"author": "Joachim Sauer",
"author_id": 40342,
"author_profile": "https://Stackoverflow.com/users/40342",
"pm_score": 3,
"selected": false,
"text": "Book Book WeakReference Book Book new Book(12345) BookFactory.getOrCreateBook(12345) Book Book BookFactory BookSession BookSession BookSession record record Book(int isbn, String title) {}\n\nclass BookSession {\n private final ConcurrentHashMap<Integer, Book> books = new ConcurrentHashMap<>();\n\n public Optional<Book> get(int isbn) {\n return Optional.ofNullable(books.get(isbn));\n }\n\n public Book getOrCreate(int isbn, String title) {\n return books.computeIfAbsent(isbn, (i) -> new Book(i, title));\n }\n}\n findByTitle BookSession public static final BookSession BOOKS"
},
{
"answer_id": 74611633,
"author": "oligofren",
"author_id": 200987,
"author_profile": "https://Stackoverflow.com/users/200987",
"pm_score": 2,
"selected": false,
"text": "public class Book {\n // potential memory leak, see Joachim Sauer's answer (WeakReference)\n Map<Book> created = new Map<>();\n // other internal fields follow\n\n // can only be invoked from factory method\n private Book(String isbn){ /* internals */ }\n\n public Book get(String isbn){\n if(created.has(isbn)) return created.get(isbn);\n var b = new Book(isbn);\n b.add(isbn, b);\n return b;\n }\n}\n synchronized Concurrent* Atomic*"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/618321/"
] |
74,611,496
|
<p>I have a pandas dataframe with data like:</p>
<pre><code>+-----------+-----------------+---------+
| JOB-NAME | Status | SLA |
+-----------+-----------------+---------+
| job_1 | YET_TO_START | --- |
| job_3 | COMPLETED | MET |
| job_4 | RUNNING | MET |
| job_2 | YET_TO_START | LATE |
| job_6 | RUNNING | LATE |
| job_5 | FAILED | LATE |
| job_7 | YET_TO_START | --- |
| job_8 | COMPLETED | NOT_MET |
+-----------+-----------------+---------+
</code></pre>
<p>I need to sort this table based on the <strong>Status</strong> and <strong>SLA</strong> states, like for Status: <em>FAILED</em> will be top on the table, then <em>YET_TO_START</em>, then <em>RUNNING</em>, and finally <em>COMPLETED</em>. Similarly for <strong>SLA</strong> the order will be <em>LATE</em>, <em>---</em>, <em>NOT_MET</em>, and <em>MET</em>.
Like this:</p>
<pre><code>+-----------+-----------------+---------+
| JOB-NAME | Status | SLA |
+-----------+-----------------+---------+
| job_5 | FAILED | LATE |
| job_2 | YET_TO_START | LATE |
| job_1 | YET_TO_START | --- |
| job_7 | YET_TO_START | --- |
| job_6 | RUNNING | LATE |
| job_4 | RUNNING | MET |
| job_8 | COMPLETED | NOT_MET |
| job_3 | COMPLETED | MET |
+-----------+-----------------+---------+
</code></pre>
<p>I am able to do this custom sorting priority-based only on single column <em>Status</em>, but unable to do for multiple columns.</p>
<pre><code>sort_order_dict = {"FAILED":0, "YET_TO_START":1, "RUNNING":2, "COMPLETED":3}
joined_df = joined_df.sort_values(by=['status'], key=lambda x: x.map(sort_order_dict))
</code></pre>
<p>A solution is given <a href="https://stackoverflow.com/questions/13838405/custom-sorting-in-pandas-dataframe">here</a>, but its for single column, not multiple column.</p>
|
[
{
"answer_id": 74611625,
"author": "Joachim Sauer",
"author_id": 40342,
"author_profile": "https://Stackoverflow.com/users/40342",
"pm_score": 3,
"selected": false,
"text": "Book Book WeakReference Book Book new Book(12345) BookFactory.getOrCreateBook(12345) Book Book BookFactory BookSession BookSession BookSession record record Book(int isbn, String title) {}\n\nclass BookSession {\n private final ConcurrentHashMap<Integer, Book> books = new ConcurrentHashMap<>();\n\n public Optional<Book> get(int isbn) {\n return Optional.ofNullable(books.get(isbn));\n }\n\n public Book getOrCreate(int isbn, String title) {\n return books.computeIfAbsent(isbn, (i) -> new Book(i, title));\n }\n}\n findByTitle BookSession public static final BookSession BOOKS"
},
{
"answer_id": 74611633,
"author": "oligofren",
"author_id": 200987,
"author_profile": "https://Stackoverflow.com/users/200987",
"pm_score": 2,
"selected": false,
"text": "public class Book {\n // potential memory leak, see Joachim Sauer's answer (WeakReference)\n Map<Book> created = new Map<>();\n // other internal fields follow\n\n // can only be invoked from factory method\n private Book(String isbn){ /* internals */ }\n\n public Book get(String isbn){\n if(created.has(isbn)) return created.get(isbn);\n var b = new Book(isbn);\n b.add(isbn, b);\n return b;\n }\n}\n synchronized Concurrent* Atomic*"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2245709/"
] |
74,611,514
|
<p>I have created MySql container in kubernetes Pod by using YAML deployment file.
I am able to execute the mysql queries on that container and created few databases and tables with data in it.
But when I make some changes in other code of project not related to kubernetes files and deployed it.
On the recreation of pod all my previous databases are deleted from MySql container. I have also given mount path to mount the PVC to my container.</p>
<p>So my question is <strong>how to store the databases permanently so that on recreation of pod it will not delete the database and able to access that databases through newly created pod</strong></p>
|
[
{
"answer_id": 74611981,
"author": "Srinivas Padala",
"author_id": 20631651,
"author_profile": "https://Stackoverflow.com/users/20631651",
"pm_score": 0,
"selected": false,
"text": "kind: Service\nmetadata:\n name: wordpress-mysql\n labels:\n app: wordpress\nspec:\n ports:\n - port: 3306\n selector:\n app: wordpress\n tier: mysql\n clusterIP: None\n---\napiVersion: v1\nkind: PersistentVolumeClaim\nmetadata:\n name: mysql-pv-claim\n labels:\n app: wordpress\nspec:\n accessModes:\n - ReadWriteOnce\n resources:\n requests:\n storage: 20Gi\n---\napiVersion: apps/v1 # for k8s versions before 1.9.0 use apps/v1beta2 and before 1.8.0 use extensions/v1beta1\nkind: Deployment\nmetadata:\n name: wordpress-mysql\n labels:\n app: wordpress\nspec:\n selector:\n matchLabels:\n app: wordpress\n tier: mysql\n strategy:\n type: Recreate\n template:\n metadata:\n labels:\n app: wordpress\n tier: mysql\n spec:\n containers:\n - image: mysql:5.6\n name: mysql\n env:\n - name: MYSQL_ROOT_PASSWORD\n valueFrom:\n secretKeyRef:\n name: mysql-pass\n key: password\n livenessProbe:\n tcpSocket:\n port: 3306\n ports:\n - containerPort: 3306\n name: mysql\n volumeMounts:\n - name: mysql-persistent-storage\n mountPath: /var/lib/mysql\n volumes:\n - name: mysql-persistent-storage\n persistentVolumeClaim:\n claimName: mysql-pv-claim\n ```\n"
},
{
"answer_id": 74612313,
"author": "Harsh Manvar",
"author_id": 5525824,
"author_profile": "https://Stackoverflow.com/users/5525824",
"pm_score": 1,
"selected": false,
"text": "apiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: mysql\nspec:\n selector:\n matchLabels:\n app: mysql\n strategy:\n type: Recreate\n template:\n metadata:\n labels:\n app: mysql\n spec:\n containers:\n - image: mysql:5.6\n name: mysql\n env:\n # Use secret in real usage\n - name: MYSQL_ROOT_PASSWORD\n value: password\n ports:\n - containerPort: 3306\n name: mysql\n volumeMounts:\n - name: mysql-persistent-storage\n mountPath: /var/lib/mysql\n volumes:\n - name: mysql-persistent-storage\n persistentVolumeClaim:\n claimName: mysql-pv-claim\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18962425/"
] |
74,611,555
|
<p>Here is my list, it's list of object and inside object there is list:
please rev</p>
<pre class="lang-py prettyprint-override"><code>[
{
"id": 1,
"test": [
{
"id__": 1
},
{
"id__": 1
},
{
"id__": 1
},
{
"id__": 2
}
]
},
{
"id": 2,
"test": [
{
"id__": 1
},
{
"id__": 1
},
{
"id__": 1
},
{
"id__": 2
}
]
}
]
</code></pre>
<p>I want to remove matched id with one in <code>objecso</code> it can be like this :</p>
<pre class="lang-py prettyprint-override"><code>[
{
"id": 1,
"test": [
{
"id__": 1
},
{
"id__": 1
},
{
"id__": 1
}
]
},
{
"id": 2,
"test": [
{
"id__": 2
}
]
}
]
</code></pre>
<p>Here is what I try:
and notice that is final is the list mentioned above</p>
<pre class="lang-py prettyprint-override"><code>for i in final:
for j in i["test"]:
if j['id__'] == i["id"]:
i.pop()
</code></pre>
<p>can I use some help of you kind guys, I tried with remove attribute in list, and still no result satisfied.</p>
|
[
{
"answer_id": 74611981,
"author": "Srinivas Padala",
"author_id": 20631651,
"author_profile": "https://Stackoverflow.com/users/20631651",
"pm_score": 0,
"selected": false,
"text": "kind: Service\nmetadata:\n name: wordpress-mysql\n labels:\n app: wordpress\nspec:\n ports:\n - port: 3306\n selector:\n app: wordpress\n tier: mysql\n clusterIP: None\n---\napiVersion: v1\nkind: PersistentVolumeClaim\nmetadata:\n name: mysql-pv-claim\n labels:\n app: wordpress\nspec:\n accessModes:\n - ReadWriteOnce\n resources:\n requests:\n storage: 20Gi\n---\napiVersion: apps/v1 # for k8s versions before 1.9.0 use apps/v1beta2 and before 1.8.0 use extensions/v1beta1\nkind: Deployment\nmetadata:\n name: wordpress-mysql\n labels:\n app: wordpress\nspec:\n selector:\n matchLabels:\n app: wordpress\n tier: mysql\n strategy:\n type: Recreate\n template:\n metadata:\n labels:\n app: wordpress\n tier: mysql\n spec:\n containers:\n - image: mysql:5.6\n name: mysql\n env:\n - name: MYSQL_ROOT_PASSWORD\n valueFrom:\n secretKeyRef:\n name: mysql-pass\n key: password\n livenessProbe:\n tcpSocket:\n port: 3306\n ports:\n - containerPort: 3306\n name: mysql\n volumeMounts:\n - name: mysql-persistent-storage\n mountPath: /var/lib/mysql\n volumes:\n - name: mysql-persistent-storage\n persistentVolumeClaim:\n claimName: mysql-pv-claim\n ```\n"
},
{
"answer_id": 74612313,
"author": "Harsh Manvar",
"author_id": 5525824,
"author_profile": "https://Stackoverflow.com/users/5525824",
"pm_score": 1,
"selected": false,
"text": "apiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: mysql\nspec:\n selector:\n matchLabels:\n app: mysql\n strategy:\n type: Recreate\n template:\n metadata:\n labels:\n app: mysql\n spec:\n containers:\n - image: mysql:5.6\n name: mysql\n env:\n # Use secret in real usage\n - name: MYSQL_ROOT_PASSWORD\n value: password\n ports:\n - containerPort: 3306\n name: mysql\n volumeMounts:\n - name: mysql-persistent-storage\n mountPath: /var/lib/mysql\n volumes:\n - name: mysql-persistent-storage\n persistentVolumeClaim:\n claimName: mysql-pv-claim\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20631524/"
] |
74,611,556
|
<p>I wanted to use <code>getComputedStyle</code> to access css properties, unfortunately it only <code>console.log()</code>'s standard properties.</p>
<p>Below you will find my code.</p>
<p>On the picture you will find what it logs.</p>
<p><img src="https://i.stack.imgur.com/kWYO9.png" alt="logs" /></p>
<pre><code>
<body>
<div id="box">box</div>
<script>
const box = document.getElementById("box");
const boxCS = window.getComputedStyle(box)
console.log(boxCS.zIndex)
</script>
</body>
<style>
#box {
width: 100px;
height: 100px;
border: 1px solid black;
position: absolute;
z-index: 1;
background-color: rgb(200, 200, 200);
}
</style>
</code></pre>
|
[
{
"answer_id": 74611614,
"author": "idleberg",
"author_id": 1329116,
"author_profile": "https://Stackoverflow.com/users/1329116",
"pm_score": 2,
"selected": false,
"text": "window.addEventListener(\"DOMContentLoaded\", () => {\n const box = document.getElementById(\"box\");\n const boxCS = window.getComputedStyle(box)\n \n console.log(boxCS.zIndex)\n});\n"
},
{
"answer_id": 74611652,
"author": "Animus",
"author_id": 3443505,
"author_profile": "https://Stackoverflow.com/users/3443505",
"pm_score": 2,
"selected": true,
"text": "script script"
},
{
"answer_id": 74654390,
"author": "Ajay Thakur",
"author_id": 11013282,
"author_profile": "https://Stackoverflow.com/users/11013282",
"pm_score": -1,
"selected": false,
"text": "let computedStyle = getComputedStyle(element);\nlet propertyValue = computedStyle.getPropertyValue(propertyName);\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20563291/"
] |
74,611,572
|
<p>I am getting the error</p>
<blockquote>
<p>TypeError: 'float' object is not subscriptable</p>
</blockquote>
<p>from the following line:</p>
<pre><code>tuner_nn.search(x_train, y_train, epochs=50, validation_data=(x_val,y_val ), verbose=0, callbacks=[Earlystopping])
</code></pre>
<p>I know there are a lot of questions with the the same error but still could not find a solution for this issue.</p>
<p>While removing the <strong>y_val</strong> from the code and having the following incomplete line:</p>
<pre><code>tuner_nn.search(x_train, y_train, epochs=50, validation_data=(x_val,), verbose=0, callbacks=[Earlystopping])
</code></pre>
<p>The code somewhy pass without errors with green V.</p>
<p>Yet with the warnings:</p>
<blockquote>
<p>INFO:tensorflow:Oracle triggered exit
INFO:tensorflow:Reloading Oracle from existing project /Users/Farid Srouji/Documents/kerastuner\untitled_project\oracle.json
INFO:tensorflow:Reloading Tuner from /Users/Farid Srouji/Documents/kerastuner\untitled_project\tuner0.json
INFO:tensorflow:Oracle triggered exit
INFO:tensorflow:Reloading Oracle from existing project /Users/Farid Srouji/Documents/kerastuner\untitled_project\oracle.json
INFO:tensorflow:Reloading Tuner from /Users/Farid Srouji/Documents/kerastuner\untitled_project\tuner0.json
INFO:tensorflow:Oracle triggered exit</p>
</blockquote>
<p>The full code in this block is:</p>
<pre><code>
# Search hyperparameters
SEED = 121
# NN
tuner_nn = BayesianOptimization(nn_builder,
objective = 'val_loss',
max_trials = 20,
seed = SEED,
directory = '/Users/myuser/Documents/kerastuner',
overwrite = True
)
tuner_nn.search(x_train, y_train, epochs=50, validation_data=(x_val, ), verbose=0, callbacks=[Earlystopping])
## Build model based on the optimized hyperparameters
besthp_nn = tuner_nn.get_best_hyperparameters()[0]
model_nn = tuner_nn.hypermodel.build(besthp_nn)
# lstm
tuner_lstm = BayesianOptimization(lstm_builder,
objective = 'val_loss',
max_trials = 20,
seed = SEED,
directory = '/Users/myuser/Documents/kerastuner')
tuner_lstm.search(x_train, y_train, epochs=50, validation_data=(x_val, y_val), verbose=0, callbacks=[Earlystopping])
## Build model based on the optimized hyperparameters
besthp_lstm = tuner_lstm.get_best_hyperparameters()[0]
model_lstm = tuner_lstm.hypermodel.build(besthp_lstm)
# gru
tuner_gru = BayesianOptimization(gru_builder,
objective = 'val_loss',
max_trials = 20,
seed = SEED,
directory = '/Users/myuser/Documents/kerastuner')
tuner_gru.search(x_train, y_train, epochs=50, validation_data=(x_val, y_val), verbose=0, callbacks=[Earlystopping])
## Build model based on the optimized hyperparameters
besthp_gru = tuner_gru.get_best_hyperparameters()[0]
model_gru = tuner_gru.hypermodel.build(besthp_gru)
</code></pre>
<p>Why the removal of y_val the code works? Also there is no error for missing argument</p>
|
[
{
"answer_id": 74611614,
"author": "idleberg",
"author_id": 1329116,
"author_profile": "https://Stackoverflow.com/users/1329116",
"pm_score": 2,
"selected": false,
"text": "window.addEventListener(\"DOMContentLoaded\", () => {\n const box = document.getElementById(\"box\");\n const boxCS = window.getComputedStyle(box)\n \n console.log(boxCS.zIndex)\n});\n"
},
{
"answer_id": 74611652,
"author": "Animus",
"author_id": 3443505,
"author_profile": "https://Stackoverflow.com/users/3443505",
"pm_score": 2,
"selected": true,
"text": "script script"
},
{
"answer_id": 74654390,
"author": "Ajay Thakur",
"author_id": 11013282,
"author_profile": "https://Stackoverflow.com/users/11013282",
"pm_score": -1,
"selected": false,
"text": "let computedStyle = getComputedStyle(element);\nlet propertyValue = computedStyle.getPropertyValue(propertyName);\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13758002/"
] |
74,611,582
|
<p>In cypress I have
<b>Book</b>
:This is the book of
<b>English</b>
how to test that 'Book:This is book of English' is in order ?
I not having single row I have multiple rows like this</p>
<p><code>cy.get('span').then((Val)=>{ const text=val.text().trim(':').toString(); });</code></p>
|
[
{
"answer_id": 74615188,
"author": "Asad Musharaf",
"author_id": 20633965,
"author_profile": "https://Stackoverflow.com/users/20633965",
"pm_score": 0,
"selected": false,
"text": "cy.get('span').then(span => {\n const words = span.split(':');\n const firstword = words[0]\n const secondword = words[1]\n cy.log(firstword, secondword);\n"
},
{
"answer_id": 74617384,
"author": "Daniel",
"author_id": 197546,
"author_profile": "https://Stackoverflow.com/users/197546",
"pm_score": 0,
"selected": false,
"text": "contains cy.get('span').contains('Book: English').should('exist')\n// or\ncy.get('span:contains(\"Book: English\")').should('exist')\n\n"
},
{
"answer_id": 74622011,
"author": "Blunt",
"author_id": 20473079,
"author_profile": "https://Stackoverflow.com/users/20473079",
"pm_score": 1,
"selected": false,
"text": "cy.get('span')\n .then($span => {\n return $span.text() // extract test\n .split(': ') // split it at \": \"\n })\n .should('deep.equal', ['Book', 'English']) // compare to ordered array\n"
},
{
"answer_id": 74647523,
"author": "Ine Wilmann",
"author_id": 20659725,
"author_profile": "https://Stackoverflow.com/users/20659725",
"pm_score": 0,
"selected": false,
"text": "<b> b cy.get('span b')\n .invoke('text')\n .should('eq', 'BookEnglish')\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20625643/"
] |
74,611,593
|
<p>when I try to summeraize my data I get some strange results. But using group_by and than summeraize gives me only one observation, even though I have more different groups. Adding an Argument to group_by only gives one more Variable in the result.
However, like other post suggest (e.g. <a href="https://stackoverflow.com/questions/26106146/why-does-summarize-or-mutate-not-work-with-group-by-when-i-load-plyr-after-dp">Why does summarize or mutate not work with group_by when I load `plyr` after `dplyr`?</a>) it could be plyr. But actually I didn't load plyr and in my code I directly refer to dplyr. How to I get my expected result (one value each group)?
In the following my dput of my 1) code, 2) my original tabel: comb_extract_all and 3) my resulting table.</p>
<pre><code>comb_extract_all_agg <- comb_extract_all %>% dplyr::group_by("SurveyId", "hhid", "CLUSTER") %>%
dplyr::summarize(hc70 =mean(hc70, na.rm = TRUE)) %>%
ungroup()
dput(comb_extract_all[1:10,1:10])
structure(list(hhid = c(" 1 27", " 1 27", " 1 27",
" 1 27", " 1 67", " 1 67", " 1 67",
" 1 67", " 1 67", " 1225"), hv001 = c(1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), hv002 = c(27L, 27L, 27L,
27L, 67L, 67L, 67L, 67L, 67L, 225L), hv005 = c(1707326L, 1707326L,
1707326L, 1707326L, 1707326L, 1707326L, 1707326L, 1707326L, 1707326L,
1707326L), hv007 = c(2003L, 2003L, 2003L, 2003L, 2003L, 2003L,
2003L, 2003L, 2003L, 2003L), hv021 = c(1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L), hv023 = structure(c(6L, 6L, 6L, 6L, 6L, 6L,
6L, 6L, 6L, 6L), labels = structure(1:23, names = c("tigray urban",
"tigray rural", "affar urban", "affar rural", "amhara urban",
"amhara rural", "oromiya urban", "oromiya rural", "somali urban",
"somali rural", "benishangul-gumuz urban", "benishangul-gumuz rural",
"s.n.n.p. urban", "s.n.n.p. rural", "gambela urban", "gambela rural",
"harari urban", "harari rural", "addis ababa", "dire dawa urban",
"dire dawa rural", "somali oversample urban", "somali oversample rural"
)), label = "Stratification used in sample design", class = c("haven_labelled",
"vctrs_vctr", "integer")), hv024 = structure(c(3L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 3L), labels = c(tigray = 1L, affar = 2L,
amhara = 3L, oromiya = 4L, somali = 5L, `benishangul-gumuz` = 6L,
snnp = 7L, gambela = 12L, harari = 13L, `addis ababa` = 14L,
`dire dawa` = 15L), label = "Region", class = c("haven_labelled",
"vctrs_vctr", "integer")), hv025 = structure(c(2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L), labels = structure(1:2, names = c("urban",
"rural")), label = "Type of place of residence", class = c("haven_labelled",
"vctrs_vctr", "integer")), hc70 = structure(c(NA_real_, NA_real_,
NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_,
NA_real_), labels = c(`height out of plausible limits` = 9996,
`age in days out of plausible limits` = 9997, `flagged cases` = 9998,
missing = 9999), label = "Height/Age standard deviation (new WHO)", class = c("haven_labelled",
"vctrs_vctr", "double"))), row.names = c("ETPR61FL.1", "ETPR61FL.2",
"ETPR61FL.3", "ETPR61FL.4", "ETPR61FL.5", "ETPR61FL.6", "ETPR61FL.7",
"ETPR61FL.8", "ETPR61FL.9", "ETPR61FL.10"), class = "data.frame")
dput(comb_extract_all_agg)
structure(list(`"SurveyId"` = "SurveyId", `"hhid"` = "hhid",
`"CLUSTER"` = "CLUSTER", hc70 = 683.255964376358), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -1L))
</code></pre>
<p>Edit for comment:</p>
<pre><code> comb_extract_all |> select(SurveyId, CLUSTER, hhid, hc70) |> slice_sample(n = 5) |> dput()
structure(list(SurveyId = c("ET2016DHS", "ET2016DHS", "ET2019DHS",
"ZW2010DHS", "ET2005DHS"), CLUSTER = structure(c(561L, 211L,
143L, 166L, 241L), label = "Cluster number"), hhid = structure(c(" 561 51",
" 211 301", " 01430032", " 166 25", " 241246"
), label = "Case Identification"), hc70 = structure(c(NA, NA,
NA, NA, 619), labels = c(`height out of plausible limits` = 9996,
`age in days out of plausible limits` = 9997, `flagged cases` = 9998,
missing = 9999), label = "Height/Age standard deviation (new WHO)", class = c("haven_labelled",
"vctrs_vctr", "double"))), row.names = c("ETPR71FL.64958", "ETPR71FL.24246",
"ETPR81FL.19619", "ZWPR62FL.17019", "147379"), class = "data.frame")
</code></pre>
|
[
{
"answer_id": 74613432,
"author": "Andy Baxter",
"author_id": 10744082,
"author_profile": "https://Stackoverflow.com/users/10744082",
"pm_score": 2,
"selected": true,
"text": "group_by NA library(tidyverse)\n \"ETPR61FL.3\", \"ETPR61FL.4\", \"ETPR61FL.5\", \"ETPR61FL.6\", \"ETPR61FL.7\", \n \"ETPR61FL.8\", \"ETPR61FL.9\", \"ETPR61FL.10\"), class = \"data.frame\")\ncomb_extract_all %>% group_by(hhid) %>% \n summarize(hc70 =mean(hc70, na.rm = TRUE)) %>% \n ungroup()\n#> # A tibble: 3 × 2\n#> hhid hc70\n#> <chr> <dbl>\n#> 1 \" 1 27\" NaN\n#> 2 \" 1 67\" NaN\n#> 3 \" 1225\" NaN\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18169859/"
] |
74,611,595
|
<p>How to make api class where api response start with array ?
Api Response :-</p>
<pre><code> [
{
"reqList": [
{
"_id": "123448478478",
"username": "12345",
"amount": 4100
},
],
"_id": "636e2c5cf0142eed68343335",
"username": "umesh-rajput",
"amount": 95
}
]
</code></pre>
|
[
{
"answer_id": 74611903,
"author": "Taimoor Ghafar",
"author_id": 17082429,
"author_profile": "https://Stackoverflow.com/users/17082429",
"pm_score": 1,
"selected": false,
"text": "class DataProvider{\n List<YourModel> getDate(String URL) async {\n var response = await http.get(url);\n if(resonse.statuscode == 200)\n {\n var List<YourModel> modelList = \n response.body.map((jsonObject)=>YourModel.toJson(jsonObject);\n );\n return modelList;\n }\n return [];\n }\n}\n"
},
{
"answer_id": 74612891,
"author": "Umesh Rajput",
"author_id": 19842804,
"author_profile": "https://Stackoverflow.com/users/19842804",
"pm_score": 0,
"selected": false,
"text": "Future<List<MODEL NAME>> getAllBetNotification() async {\nSharedPreferences prefs = await SharedPreferences.getInstance();\nvar token = prefs.getString('userToken');\nurl = 'API URL';\nvar response = await http.get(Uri.parse(url), headers: {\n'Authorization': 'YOUR TOKEN',\n });\n if (response.statusCode == 200 || response.statusCode == 201) {\n // print(response.body);\n var list1 = (jsonDecode(response.body) as List)\n .map((dynamic i) =>\n UserNotificationModel.fromJson(i as Map<String, dynamic>))\n .toList();\n return list1;\n } else {\n print('do not send notification');\n return [];\n } \n }\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19842804/"
] |
74,611,618
|
<p>I'm stuck trying to vlookup multiples values duplicates and return all match into one cell.</p>
<p>I would like to convert with formulas a sheet like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Name</th>
<th>Product</th>
</tr>
</thead>
<tbody>
<tr>
<td>James</td>
<td>Peach</td>
</tr>
<tr>
<td>James</td>
<td>Apple</td>
</tr>
<tr>
<td>James</td>
<td>Cherry</td>
</tr>
<tr>
<td>Andy</td>
<td>Banana</td>
</tr>
<tr>
<td>Wallace</td>
<td>Peach</td>
</tr>
<tr>
<td>Wallace</td>
<td>Cherry</td>
</tr>
<tr>
<td>Mike</td>
<td>Banana</td>
</tr>
</tbody>
</table>
</div>
<p>On a new sheet like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Name</th>
<th>Product</th>
</tr>
</thead>
<tbody>
<tr>
<td>James</td>
<td>Peach,Apple,Cherry</td>
</tr>
<tr>
<td>Andy</td>
<td>Banana</td>
</tr>
<tr>
<td>Wallace</td>
<td>Peach,Cherry</td>
</tr>
<tr>
<td>Mike</td>
<td>Banana</td>
</tr>
</tbody>
</table>
</div>
<p><a href="https://docs.google.com/spreadsheets/d/1Z7S58GnykkFriL35729Ua-yh-4ih1ZxfpRsuxjgoQdg/edit#gid=2062344380" rel="nofollow noreferrer">Here is an example spreadsheet</a></p>
<p>Edit: I forgot to specify it, but the result should be in a new tab, like a vlookup</p>
<p>I have not found a functional solution in my research, <a href="https://www.extendoffice.com/documents/excel/2706-excel-vlookup-return-multiple-values-in-one-cell.html" rel="nofollow noreferrer">here is the post</a> that seems to come closest to my need. But the proposed formula does not work: <strong>=TEXTJOIN(",",TRUE,IF($A$2:$A$11=E2,$C$2:$C$11,""))</strong></p>
<p>Do you have any idea how I can solve this formula? Your help will be greatly appreciated. I'm going in a loop and I can't find a solution :(</p>
|
[
{
"answer_id": 74611903,
"author": "Taimoor Ghafar",
"author_id": 17082429,
"author_profile": "https://Stackoverflow.com/users/17082429",
"pm_score": 1,
"selected": false,
"text": "class DataProvider{\n List<YourModel> getDate(String URL) async {\n var response = await http.get(url);\n if(resonse.statuscode == 200)\n {\n var List<YourModel> modelList = \n response.body.map((jsonObject)=>YourModel.toJson(jsonObject);\n );\n return modelList;\n }\n return [];\n }\n}\n"
},
{
"answer_id": 74612891,
"author": "Umesh Rajput",
"author_id": 19842804,
"author_profile": "https://Stackoverflow.com/users/19842804",
"pm_score": 0,
"selected": false,
"text": "Future<List<MODEL NAME>> getAllBetNotification() async {\nSharedPreferences prefs = await SharedPreferences.getInstance();\nvar token = prefs.getString('userToken');\nurl = 'API URL';\nvar response = await http.get(Uri.parse(url), headers: {\n'Authorization': 'YOUR TOKEN',\n });\n if (response.statusCode == 200 || response.statusCode == 201) {\n // print(response.body);\n var list1 = (jsonDecode(response.body) as List)\n .map((dynamic i) =>\n UserNotificationModel.fromJson(i as Map<String, dynamic>))\n .toList();\n return list1;\n } else {\n print('do not send notification');\n return [];\n } \n }\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15511682/"
] |
74,611,637
|
<p>I have input data which looks like this:</p>
<p>DF()</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>**symbol</th>
<th>sample1</th>
<th>sample2</th>
<th>sample3**</th>
</tr>
</thead>
<tbody>
<tr>
<td>Cohort</td>
<td>0</td>
<td>1</td>
<td>0</td>
</tr>
<tr>
<td>gene1</td>
<td>2334</td>
<td>99467</td>
<td>3782</td>
</tr>
<tr>
<td>gene2</td>
<td>3889</td>
<td>4893</td>
<td>22891</td>
</tr>
</tbody>
</table>
</div>
<p>and I want to separate "Cohort" and the column names and make a separate data frame. Something like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>symbol</th>
<th>Cohort</th>
</tr>
</thead>
<tbody>
<tr>
<td>sample1</td>
<td>0</td>
</tr>
<tr>
<td>sample2</td>
<td>1</td>
</tr>
</tbody>
</table>
</div>
<p>I tried this:</p>
<pre><code>DF<- data %>% filter(row_number() == 1)
data1<-t(DF)
</code></pre>
<p>but got this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th></th>
<th>V1</th>
</tr>
</thead>
<tbody>
<tr>
<td>symbol</td>
<td>Cohort</td>
</tr>
<tr>
<td>sample1</td>
<td>0</td>
</tr>
<tr>
<td>sample2</td>
<td>1</td>
</tr>
</tbody>
</table>
</div>
<p>Can somebody help me out?</p>
|
[
{
"answer_id": 74611870,
"author": "Maël",
"author_id": 13460602,
"author_profile": "https://Stackoverflow.com/users/13460602",
"pm_score": 2,
"selected": true,
"text": "library(dplyr)\ndat %>% \n filter(symbol == \"Cohort\") %>% \n t() %>% as.data.frame() %>% \n tibble::rownames_to_column() %>% \n janitor::row_to_names(1)\n\n symbol Cohort\n2 sample1 0\n3 sample2 1\n4 sample3 0\n"
},
{
"answer_id": 74612224,
"author": "BenL",
"author_id": 14319579,
"author_profile": "https://Stackoverflow.com/users/14319579",
"pm_score": 1,
"selected": false,
"text": "library(tidyverse)\n\ndf <- tribble(\n ~\"symbol\", ~\"sample1\", ~\"sample2\", ~\"sample3\",\n \"Cohort\", 0, 1, 0,\n \"gene1\", 2334, 99467, 3782,\n \"gene2\", 3889, 4893, 22891\n)\n\ndf %>% \n pivot_longer(\n cols = starts_with(\"sample\")\n ) %>% \n filter(symbol == \"Cohort\") %>% \n select(symbol = name,\n cohort = value)\n"
},
{
"answer_id": 74612242,
"author": "zx8754",
"author_id": 680068,
"author_profile": "https://Stackoverflow.com/users/680068",
"pm_score": 0,
"selected": false,
"text": "myFile = \"symbol sample1 sample2 sample3\nCohort 0 1 0\ngene1 2334 99467 3782\ngene2 3889 4893 22891\n\"\n\n#get gene names ignoring cohort row\nmyCols <- names(read.table(text = myFile, nrows = 1, header = TRUE))\nd1 <- read.table(text = myFile, skip = 2, col.names = myCols)\n\n#get cohort row as vector\ncohort <- read.table(text = myFile, skip = 1, nrows = 1)\ncohort <- as.numeric(cohort[, -1])\n m <- as.matrix(d1[, -1])\ndimnames(m) <- list(d1[, 1], colnames(d1)[ -1 ])\nm\n# sample1 sample2 sample3\n# gene1 2334 99467 3782\n# gene2 3889 4893 22891\n m[ \"gene1\", cohort == 1]\n# [1] 99467\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20511527/"
] |
74,611,681
|
<p>I'm new to pandas and I'm trying to merge the following 2 dataframes into 1 :</p>
<pre><code> nopat
0 2021-12-31 3.580000e+09
1 2020-12-31 6.250000e+08
2 2019-12-31 -1.367000e+09
3 2018-12-31 2.028000e+09
</code></pre>
<pre><code> capital_employed
0 2021-12-31 5.924000e+10
1 2020-12-31 6.062400e+10
2 2019-12-31 5.203500e+10
3 2018-12-31 5.441200e+10
</code></pre>
<p>When I try to apply a function to my new datframe, all columns disappear. Here is my code :</p>
<pre><code>roce_by_year = pd.merge(nopat, capital_employed) \
.rename(columns={"": "date"}) \
.sort_values(by='date') \
.apply(lambda row: compute_roce(row['nopat'], row['capital_employed']), axis=1) \
.reset_index(name='roce')
</code></pre>
<p>Here is the result :</p>
<pre><code> index roce
0 3 3.727119
1 2 -2.627078
2 1 1.030945
3 0 6.043214
</code></pre>
<p>I would like to have the following result :</p>
<pre><code> date roce
0 2018 3.727119
1 2019 -2.627078
2 2020 1.030945
3 2021 6.043214
</code></pre>
<p>Do you have an explanation ?</p>
|
[
{
"answer_id": 74611845,
"author": "Orfeas Bourchas",
"author_id": 16781682,
"author_profile": "https://Stackoverflow.com/users/16781682",
"pm_score": 0,
"selected": false,
"text": "nopat.rename(columns={\"\": \"date\"}, inplace=True)\nnopat.sort_values(by='date', inplace=True)\n\nnopat.set_index('date', inplace=True)\ncapital_employed.rename(columns={\"\": \"date\"}, inplace=True)\ncapital_employed.set_index('date', inplace=True)\ncapital_employed.sort_values(by='date', inplace=True)\ndf = nopat.join(capital_employed, on='date')\ndf['roce'] = df.apply(lambda row: compute_roce(row['nopat'], \n row['capital_employed']), axis=1)\n"
},
{
"answer_id": 74611959,
"author": "Ingwersen_erik",
"author_id": 17587002,
"author_profile": "https://Stackoverflow.com/users/17587002",
"pm_score": 2,
"selected": true,
"text": "import pandas as pd\n\n\nroce_by_year = (\n pd.merge(nopat, capital_employed)\n .rename(columns={\"\": \"date\"})\n .assign(\n date=lambda xdf: pd.to_datetime(\n xdf[\"date\"], errors=\"coerce\"\n ).dt.year\n )\n .assign(\n roce=lambda xdf: xdf.apply(\n lambda row: compute roce(\n row[\"nopat\"], row[\"capital_employed\"]\n ), axis=1\n )\n )\n .sort_values(\"date\", ascending=True)\n)[[\"date\", \"roce\"]]\n\n"
},
{
"answer_id": 74612045,
"author": "Baron Legendre",
"author_id": 14527886,
"author_profile": "https://Stackoverflow.com/users/14527886",
"pm_score": 1,
"selected": false,
"text": "df1['date'] = pd.to_datetime(df1['date'])\ndf1\n###\n date nopat\n0 2021-12-31 3580000000\n1 2020-12-31 625000000\n2 2019-12-31 -1367000000\n3 2018-12-31 2028000000\n df2['date'] = pd.to_datetime(df2['date'])\ndf2\n###\n date capital_employed\n0 2021-12-31 59240000000\n1 2020-12-31 60624000000\n2 2019-12-31 52035000000\n3 2018-12-31 54412000000\n df3 = pd.merge(df1, df2, how='outer', left_on='date', right_on='date')\\\n .pipe(lambda x: x.assign(roe = x['nopat']/x['capital_employed']))\\\n .sort_values(by='date', ascending=True)\\\n .pipe(lambda x: x[['date', 'roe']])\\\n .pipe(lambda x: x.assign(date = x['date'].dt.strftime('%Y'))).reset_index(drop=True)\ndf3\n###\n date roe\n0 2018 0.037271\n1 2019 -0.026271\n2 2020 0.010309\n3 2021 0.060432\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7109343/"
] |
74,611,749
|
<p>I am exploring the use of Promise.all(), but I don't know why it doesn't give me expect result. I try to illustrate it step by step.</p>
<p>Let take a look of my code:</p>
<pre><code>var p2 = 1337;
var p3 = new Promise((resolve, reject) => {
setTimeout(resolve, 2000, 'foo');
});
var apiCall = async () =>{
// to simulate a api call that will response after 5 sec
setTimeout(() => {return 1000}, 5000);
}
Promise.all([p2,p3,apiCall()]).then(values => {
console.log(values); // [3, 1337, undefine], but I expect [3, 1337, 1000]
});
apiCall().then((response)=>{console.log(response)})
</code></pre>
<p>As my understanding, async function will immediately return a Promise, which is what Promise.all will wait for.</p>
<p>So I expect,</p>
<pre><code>.then(values => {
console.log(values); // [3, 1337, undefined]
});
</code></pre>
<p>will only execute after 5 sec.</p>
<p>But the output is like below in 2 sec already, and not [3, 1337, 1000]</p>
<pre><code>undefined
[ 1337, 'foo', undefined ]
</code></pre>
<p>I dont know where the problem lies, I expect</p>
<pre><code>apiCall().then((response)=>{console.log(response)})
</code></pre>
<p>will give me "1000" instead of undefined</p>
<hr />
<p>new edit</p>
<p>After gathering you guys answers, I tried this.</p>
<p>As my understanding, setTimeout is also a async, and it will automatically return a promise like any other promise.</p>
<p>So, based on this understanding, I write below code. but it doesnt work. I understand using Promise constructor will fix the problem. But I dont know what problem lies in this example</p>
<pre><code>var apiCall = async () =>{
// to simulate a api call that will response after 5 sec
const a = setTimeout(() => {return 1000}, 5000);
return a
}
</code></pre>
|
[
{
"answer_id": 74611790,
"author": "Quentin",
"author_id": 19068,
"author_profile": "https://Stackoverflow.com/users/19068",
"pm_score": 3,
"selected": true,
"text": "apiCall var apiCall = async () =>{\n // to simulate a api call that will response after 5 sec \n setTimeout(() => {return 1000}, 5000); \n}\n async setTimeout return undefined setTimeout 1000 setTimeout new Promise p3 async await await await"
},
{
"answer_id": 74611803,
"author": "Xiduzo",
"author_id": 4655177,
"author_profile": "https://Stackoverflow.com/users/4655177",
"pm_score": 3,
"selected": false,
"text": "var apiCall = async () =>{\n // to simulate a api call that will response after 5 sec \n return new Promise(resolve => {\n setTimeout(() => {resolve(1000)}, 5000); \n });\n}\n"
},
{
"answer_id": 74611825,
"author": "Loránd Péter",
"author_id": 6146963,
"author_profile": "https://Stackoverflow.com/users/6146963",
"pm_score": 1,
"selected": false,
"text": "apiCall setTimeout apiCall setTimeout"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611749",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19586543/"
] |
74,611,751
|
<p>Using npm, one can define scripts inside of <code>package.json</code> that can be easily called like</p>
<pre class="lang-bash prettyprint-override"><code>npm run <script-name>
</code></pre>
<p>It is very handy to compile/start/lint the project</p>
<p>How are we suppposed to do this with Nimble when using Nim lang?</p>
|
[
{
"answer_id": 74611790,
"author": "Quentin",
"author_id": 19068,
"author_profile": "https://Stackoverflow.com/users/19068",
"pm_score": 3,
"selected": true,
"text": "apiCall var apiCall = async () =>{\n // to simulate a api call that will response after 5 sec \n setTimeout(() => {return 1000}, 5000); \n}\n async setTimeout return undefined setTimeout 1000 setTimeout new Promise p3 async await await await"
},
{
"answer_id": 74611803,
"author": "Xiduzo",
"author_id": 4655177,
"author_profile": "https://Stackoverflow.com/users/4655177",
"pm_score": 3,
"selected": false,
"text": "var apiCall = async () =>{\n // to simulate a api call that will response after 5 sec \n return new Promise(resolve => {\n setTimeout(() => {resolve(1000)}, 5000); \n });\n}\n"
},
{
"answer_id": 74611825,
"author": "Loránd Péter",
"author_id": 6146963,
"author_profile": "https://Stackoverflow.com/users/6146963",
"pm_score": 1,
"selected": false,
"text": "apiCall setTimeout apiCall setTimeout"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6331372/"
] |
74,611,779
|
<p>i have a text P element</p>
<p>In css ive used text-align: center; to center the text in the middle of the screen
which works.</p>
<p>but if i want the text to have more space on both sides by using "width 80%" it puts all the text on the left side of the screen completely ignore text align center (except for the text still looking centered just not in the center of the screen.</p>
<p><strong>btw, i refuse to just use margin, padding, left, right pixels because it forces the pixels.</strong>
i want to be able to change my window size and keep things in propotion</p>
<p>I want the text to be in the middle. not approxemately or calculated by hand..</p>
<p>so simply, i just want text with some space on both sides equally.</p>
<p>Together with "width: 80%", i tried;</p>
<pre><code>justify-content: center;
justify-self: center;
justify-items: center;
align-content: center;
align-self: center;
align-items: center;
</code></pre>
<p>(not all at the same time obviously)</p>
<p>none of it worked.</p>
|
[
{
"answer_id": 74611893,
"author": "MAYUR SANCHETI",
"author_id": 12238257,
"author_profile": "https://Stackoverflow.com/users/12238257",
"pm_score": 1,
"selected": false,
"text": " p\n {\n width:80%;\n text-align: center;\n } <p>test</p>"
},
{
"answer_id": 74612005,
"author": "Fuzzy",
"author_id": 11352382,
"author_profile": "https://Stackoverflow.com/users/11352382",
"pm_score": 1,
"selected": false,
"text": " p\n {\n width:80%;\n text-align:center;\n margin: auto;\n } <p>test</p>"
},
{
"answer_id": 74612114,
"author": "Guit Adharsh",
"author_id": 16612350,
"author_profile": "https://Stackoverflow.com/users/16612350",
"pm_score": 0,
"selected": false,
"text": " body {\n display: flex;\n align-items: center;\n justify-content: center;\n flex-direction: column;\n height: 80vh;\n width: 100%;\n \n }\n p{\n color: red;\n\n } <html>\n\n<head>\n <title>Center a text</title>\n</head>\n\n<body>\n <p>Mechanical Keyboards have great feedback</p>\n</body>\n\n</html>"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20049894/"
] |
74,611,822
|
<p>Now I have:</p>
<pre><code>for (String userPass : splitted) {
String user = userPass.split("=")[0];
String pass = userPass.split("=")[1];
config.put(user, pass);
}
</code></pre>
<p>which works for file which contains e.g</p>
<p><code>service1.password=dsjahdsahjk!sdafds</code></p>
<p>but as the second part is password it can also be:</p>
<p><code>service1.password=das-=asdwe=12f=</code></p>
<p>then my idea will fail miserably. What is the best approach to ensure that I am splitting by <code>=</code> but not this one which is inside password?</p>
|
[
{
"answer_id": 74611969,
"author": "titzko",
"author_id": 14315387,
"author_profile": "https://Stackoverflow.com/users/14315387",
"pm_score": 4,
"selected": true,
"text": "limit String pass = userPass.split(\"=\", 2)[1];\n"
},
{
"answer_id": 74612207,
"author": "Khalid Saifullah Fuad",
"author_id": 16475595,
"author_profile": "https://Stackoverflow.com/users/16475595",
"pm_score": 1,
"selected": false,
"text": "substring for (String userPass : splitted) {\n int firstEqualIndex = userPass.indexOf(\"=\");\n String user = userPass.substring(0, firstEqualIndex);\n String pass = userPass.substring(firstEqualIndex + 1);\n config.put(user, pass);\n}\n indexOf ="
},
{
"answer_id": 74615354,
"author": "g00se",
"author_id": 16376827,
"author_profile": "https://Stackoverflow.com/users/16376827",
"pm_score": 0,
"selected": false,
"text": "import java.util.Properties;\nimport java.nio.file.Path;\nimport java.nio.file.Files;\nimport java.io.Reader;\n\npublic class Prop {\n public static void main(String[] args) {\n try (Reader in = Files.newBufferedReader(Path.of(args[0]))) {\n Properties p = new Properties();\n p.load(in);\n System.out.println(p.get(\"service1.password\"));\n }\n catch(Throwable t) {\n t.printStackTrace();\n }\n }\n}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4952262/"
] |
74,611,827
|
<p>I want to delete text in '[]' this chracters,I cant delete this chracters because I am using array in array method</p>
<p><a href="https://i.stack.imgur.com/Oyi8x.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Oyi8x.png" alt="enter image description here" /></a></p>
<p>[item1, item2,item3]</p>
<p>I am simply say ı want to</p>
<p>item1 item2 item3</p>
<p>I don't want to '[]' chracters</p>
<pre><code> Row(children: [
Text('işlemler '),
Text('${listeleme(index)}')
],),
</code></pre>
<p>My Firestore Database</p>
<p><a href="https://i.stack.imgur.com/bIKDn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bIKDn.png" alt="enter image description here" /></a></p>
<p>my codes</p>
<pre><code>var veriler= await FirebaseFirestore.instance.collection('salons').doc(kendisalonuuid.toString()).collection('adisyonlar').snapshots().listen((event) async {
for(var doc in event.docs){
FBmusterilist.add(doc.get('musteriuuid'));
FBislemlerlist.add(doc.get('islem'));
FBucretlist.add(doc.get('ucret'));
FBpersonelist.add(doc.get('calisan'));
FBadisyonuuidlist.add(doc.id.toString());
}
for(var doc in FBpersonelist){
var personeladi=await FirebaseFirestore.instance.collection('users').doc(doc).get().then((value) => {
personelismi=value.get('adsoyad'),
print('personel list doc verisi $personelismi'),
FBpersoneladilist.add(value.get('adsoyad')),
setState(() {}),
});
personeladi;
}
for(var doc in FBmusterilist){
var musteriadigetirme=await FirebaseFirestore.instance.collection('salons').doc(kendisalonuuid).collection('müsteriler').doc(doc).get().then((value) =>{
print(doc.toString()),
musteriadi=value.get('ad'),
musterisoyadi=value.get('soyad'),
print('müsteri soyad verisi $musterisoyadi'),
FBmusteriadilist.add('$musteriadi $musterisoyadi'),
setState(() {}),
});
musteriadigetirme;
}
});
</code></pre>
|
[
{
"answer_id": 74611948,
"author": "Gwhyyy",
"author_id": 18670641,
"author_profile": "https://Stackoverflow.com/users/18670641",
"pm_score": 1,
"selected": false,
"text": "List [] List<String> items = [\"item1\", \"item2\", \"item3\"];\nprint(items); // [item1, item2, item3]\nprint(items.join(\" \")); // item1 item2 item3\n"
},
{
"answer_id": 74611972,
"author": "Ravindra S. Patil",
"author_id": 13997210,
"author_profile": "https://Stackoverflow.com/users/13997210",
"pm_score": 0,
"selected": false,
"text": "Text('${listeleme(index).replaceAll(RegExp(r'[^\\w\\s]+'), '')}')\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13620998/"
] |
74,611,900
|
<p>The following code runs 599 instances of bootstrapping using data stored in the dictionary <code>data_rois</code>. <code>data_rois</code> is a dictionary that includes many keys and each key is associated with an array of numeric values. This part of the code works fine when it is coded as below:</p>
<pre><code>boot_i = []
for i in range(599):
boot = np.random.choice(data_rois["interoception"], size=N)
boot = np.mean(boot)
boot_i.append(boot)
</code></pre>
<p>Now, I would like to apply bootstrapping for many keys in the dictionary <code>data_rois</code>. Therefore, I apply a for loop as below that aims to store the bootstrapping results in another dictionary called <code>boot_rois = {}</code>. The code shown below aims to shorten the code above, since the code above would get really long if I had to repeat it many times for all keys in <code>data_rois</code>.</p>
<pre><code>rois = ["interoception", "extero", ...] # A long list of rois
boot_rois = {}
for roi in rois:
for i in range(599):
boot = np.random.choice(data_rois[roi], size=N)
boot = np.mean(boot)
boot_rois[roi] = roi
</code></pre>
<p><strong>The problem:</strong> The code works. However, my code appears to ignore <code>for i in range(599)</code> but only runs <code>boot = np.random.choice(data_rois[roi], size=N)</code> one time instead of 599 times. What line of code is missing in the nested for loop so that it runs bootstrapping 599 times instead of 1 time?</p>
<p><strong>Update:</strong>
I specify my aim here. My aim is to compute the standard deviation (SD) for each roi, based on the 599 bootstraps.</p>
<p>Here is an updated code suggested by someone in this topic. I changed that code to compute the SD and the results look fine.</p>
<pre><code>boot_rois = {}
for roi in rois:
last_boot = None
for i in range(599):
boot = np.random.choice(data_rois[roi], size=N)
boot = np.std(boot)
if(last_boot is not None):
boot = np.std([boot,last_boot])
boot_rois[roi] = boot
last_boot = boot_rois[roi]
</code></pre>
|
[
{
"answer_id": 74612372,
"author": "Matthew Ciaramitaro",
"author_id": 5659781,
"author_profile": "https://Stackoverflow.com/users/5659781",
"pm_score": 2,
"selected": false,
"text": " boot_rois[roi] = boot\n import numpy as np\nN=10\ndata_rois={\"interoception\" : [1,2], \"extero\" : [2,3] }\nrois = data_rois.keys() # A long list of rois\nboot_rois = {}\nfor roi in rois:\n last_boot = None\n for i in range(7):\n boot = np.random.choice(data_rois[roi], size=N)\n print(boot)\n boot = np.mean(boot)\n # During first iteration aggregator last_boot is None\n if(last_boot is not None):\n # Average with the last iteration and repeat\n # This logic may need to be replaced with whatever math you are trying to do\n boot = np.mean([boot,last_boot])\n \n boot_rois[roi] = boot\n last_boot = boot_rois[roi]\n \nprint(boot_rois)\n"
},
{
"answer_id": 74612699,
"author": "Rafalon",
"author_id": 7831383,
"author_profile": "https://Stackoverflow.com/users/7831383",
"pm_score": 2,
"selected": true,
"text": "rois = [\"interoception\", \"extero\", ...] # A long list of rois\nboot_rois = {}\nfor roi in rois:\n # will execute np.random.choice 599 times and store these results in a list\n rand_choices = [np.mean(np.random.choice(data_rois[roi], size=N)) for _ in range(599)]\n # will calculate the standard deviation of those 599 results\n boot_rois[roi] = np.std(rand_choices)\n np.random.choice np.mean(...) np.std boot_rois[roi] import random\nimport numpy as np\n\nrand_ints = [random.randint(0, 50) for _ in range(20)]\nprint(rand_ints)\nstdev = np.std(rand_ints)\nprint(stdev)\n [9, 44, 13, 0, 43, 12, 4, 40, 35, 38, 43, 0, 3, 38, 39, 45, 37, 14, 4, 21]\n16.908281994336384\n [2, 20, 17, 32, 0, 39, 23, 27, 24, 41, 8, 21, 2, 7, 21, 3, 27, 7, 15, 36]\n12.531560158256433\n import random\nimport numpy as np\n\nrand_ints = [np.mean([random.randint(0, 50) for _ in range(10)]) for _ in range(20)]\nprint(rand_ints)\nstdev = np.std(rand_ints)\nprint(stdev)\n [25.8, 16.9, 27.6, 21.8, 20.6, 30.5, 19.4, 32.9, 27.8, 18.5, 24.5, 18.7, 23.1, 26.9, 30.6, 25.1, 24.9, 26.5, 21.8, 25.8]\n4.2607833786758045\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17530552/"
] |
74,611,907
|
<p>I'm using typescript and want to deep copy my object.
I used JSON.parse(JSON.stringify(data)) method here is the code</p>
<p><code>const dataClone: DataType[] = JSON.parse( JSON.stringify(data) ); </code></p>
<p>My data is an array with object which type is DataType[].
But I'm getting warning that I used any type and it is - Unsafe assignment of an <code>any</code> value.</p>
<p>Where I missed the type?</p>
<p>I tried to put type after variable declaration</p>
<p><code>const dataClone: DataType[] = JSON.parse( JSON.stringify(data) ); </code></p>
|
[
{
"answer_id": 74611977,
"author": "Simon",
"author_id": 3581976,
"author_profile": "https://Stackoverflow.com/users/3581976",
"pm_score": 1,
"selected": true,
"text": "string JSON.stringify any JSON.parse DataType[] const dataClone = JSON.parse(JSON.stringify(data)) as DataType[]; \n"
},
{
"answer_id": 74611993,
"author": "Nabed Khan",
"author_id": 10225877,
"author_profile": "https://Stackoverflow.com/users/10225877",
"pm_score": -1,
"selected": false,
"text": "const dataClone: DataType[] = [...state.initialData]\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9832432/"
] |
74,611,915
|
<p>I'm newbie to Kubernetes.
I wonder how to launch a container programmatically in Java (or Scala), and feed the input stream of the process with some binary data. Probably I need a job. I've found how to launch a job, but I have no control over its input stream.</p>
<p>I can use any convenient Kubernetes client library.</p>
<p>I need it to launch a <a href="https://github.com/GoogleContainerTools/kaniko#how-does-kaniko-work" rel="nofollow noreferrer">kaniko</a> container and feed its input stream with a <code>.tar.gz</code> file generated on the fly (via the <code>--context tar://stdin</code> option).</p>
<p>I could do an <code>exec</code> over an existing <code>kaniko</code> container, but don't know to launch the container appropriately for this purpose, because the container doesn't include any shell.</p>
|
[
{
"answer_id": 74612395,
"author": "user2311578",
"author_id": 2311578,
"author_profile": "https://Stackoverflow.com/users/2311578",
"pm_score": 2,
"selected": true,
"text": "kubectl run -i echo \"echo foo\" | kubectl run -i busybox --image=busybox --restart=Never \n"
},
{
"answer_id": 74617025,
"author": "david.perez",
"author_id": 3131939,
"author_profile": "https://Stackoverflow.com/users/3131939",
"pm_score": 0,
"selected": false,
"text": "try (KubernetesClient client = new KubernetesClientBuilder().build()) {\n client.run().inNamespace(\"default\")\n .withName(\"kaniko\")\n .withImage(\"gcr.io/kaniko-project/executor:latest\")\n .done();\n}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3131939/"
] |
74,611,917
|
<p>This problem is from <a href="https://leetcode.com/problems/find-players-with-zero-or-one-losses/" rel="nofollow noreferrer">https://leetcode.com/problems/find-players-with-zero-or-one-losses/</a>. Is it possible to use list comprehension in this problem to create a new list that only has the first item of every tuple that never shows up in the second item of any tuple.</p>
<p>For instance:</p>
<p><code>matches = [[1,3],[2,3],[3,6],[5,6],[5,7],[4,5],[4,8],[4,9],[10,4],[10,9]]</code></p>
<p>I want a new list of:</p>
<p><code>neverLost = [1, 2, 10]</code></p>
<p>I would make two lists, one for each part of the question with list comprehension and then concatenate them together afterwards for the solution. I tried using list comprehension but I'm having syntax issues</p>
<p><code>neverLost = [w for w, l in matches if w not l]</code></p>
<p>The first part <strong>w for w, l in matches</strong> works fine and will create a list of just the first item of each tuple <code>[1, 2, 3, 5, 5, 4, 4, 4, 10, 10]</code>, but I'm struggling with the syntax and understanding of the expression to filter the "winners". Please let me know if this is even a good solution for the problem. I know I can probably do this with a dictionary, but I wanted to know if this way was also possible. Thanks!</p>
|
[
{
"answer_id": 74612010,
"author": "itzMEonTV",
"author_id": 3160881,
"author_profile": "https://Stackoverflow.com/users/3160881",
"pm_score": 2,
"selected": false,
"text": "In [48]: list(set([j[0] for j in matches if j[0] not in [i[1] for i in matches]]))\nOut[48]: [1, 2, 10]\n"
},
{
"answer_id": 74612083,
"author": "Shrirang Mahajan",
"author_id": 17353907,
"author_profile": "https://Stackoverflow.com/users/17353907",
"pm_score": 1,
"selected": false,
"text": "neverLost = [w for w, l in matches if w not l]\n list(set([w[0] for w in matches if w[0] not in [l[1] for l in matches]]))\n"
},
{
"answer_id": 74612176,
"author": "Orfeas Bourchas",
"author_id": 16781682,
"author_profile": "https://Stackoverflow.com/users/16781682",
"pm_score": 1,
"selected": false,
"text": "matches = [[1, 3], [2, 3], [3, 6], [5, 6], [5, 7], [4, 5], [4, 8], [4, 9], [10, 4], [10, 9]]\n\nlosses_dict = {}\nfor (_, value) in matches:\n losses_dict.setdefault(value, 0) # key might exist already\n losses_dict[value] += 1\n\nfinal_list = [\n [k for k, _ in matches if k not in losses_dict.keys()],\n [k for k, v in losses_dict.items() if v == 1]\n ]\n\n"
},
{
"answer_id": 74612208,
"author": "juanpa.arrivillaga",
"author_id": 5014455,
"author_profile": "https://Stackoverflow.com/users/5014455",
"pm_score": 1,
"selected": false,
"text": "seconds = {second for _, second in matches}\nnever_lost = [first for first, _ in matches if first not in seconds]\nnever_lost = list(dict.fromkeys(never_lost)) # idiom for removing duplicates while maintaining order\n never_lost = [\n x for x in\n {\n first: None\n for first, _ in matches \n for seconds in [{second for _, second in matches}] \n if first not in seconds\n }\n]\n"
},
{
"answer_id": 74612608,
"author": "Md. Ashikun Nabi",
"author_id": 11875349,
"author_profile": "https://Stackoverflow.com/users/11875349",
"pm_score": 0,
"selected": false,
"text": "neverLost = list(set(w for w, l in matches if all(w != j for i, j in matches)))\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19313579/"
] |
74,611,957
|
<p>there is some enum class like</p>
<pre><code>enum class first{
a,
b,
...
};
enum class second{
c,
d,
...
};
</code></pre>
<p>the class seems like</p>
<pre><code>template<first N, second M> class A{
public:
A(){}
A(int n) {
var = n;
}
int var;
};
</code></pre>
<p>I wanto use it in gtest which is</p>
<pre><code>template<typename T> class TestA : public ::testing::Test {};
TYPED_TEST_CASE_P(TestA);
TYPED_TEST_P(TestA, SomeTest){
TypeParam x(0);
EXPECT_EQ(x.var,0);
}
REGISTER_TYPED_TEST_CASE_P(TestA, SomeTest);
typedef ::testing::Types<A<first::a, second::c>, A<first::b, second::d>...> MyTypes;
INSTANTIATE_TYPED_TEST_CASE_P(My, TestA, MyTypes);
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
</code></pre>
<p>how can i generate combinations of all possible template parameters
so it easily add test case by increasing enum number
maybe there is 3 or more param</p>
<pre><code>::testing::Types<A<first::a, second::c>, A<first::a, second::c>, A<first::b, second::c>, A<first::b, second::c>>
::testing::Types<A<first::a, second::c, third::e>, A<first::a, second::c, third::f>...>
</code></pre>
<p>I try to contain them in template struct looks like this
then I cam make impl
just like</p>
<pre><code>::testing::Combine(Base<first::a, first::b, ...>,Base<second::c, second::d, ...>;)
</code></pre>
<p>to generate</p>
<pre><code>::testing::Types<A<first::a, second::c>, A<first::c, second::d>.....>
</code></pre>
<p>maybe there is 3 or more param</p>
<pre><code>::testing::Types<A<000>, A<001>, A<010>, A<011>>.....
</code></pre>
|
[
{
"answer_id": 74612010,
"author": "itzMEonTV",
"author_id": 3160881,
"author_profile": "https://Stackoverflow.com/users/3160881",
"pm_score": 2,
"selected": false,
"text": "In [48]: list(set([j[0] for j in matches if j[0] not in [i[1] for i in matches]]))\nOut[48]: [1, 2, 10]\n"
},
{
"answer_id": 74612083,
"author": "Shrirang Mahajan",
"author_id": 17353907,
"author_profile": "https://Stackoverflow.com/users/17353907",
"pm_score": 1,
"selected": false,
"text": "neverLost = [w for w, l in matches if w not l]\n list(set([w[0] for w in matches if w[0] not in [l[1] for l in matches]]))\n"
},
{
"answer_id": 74612176,
"author": "Orfeas Bourchas",
"author_id": 16781682,
"author_profile": "https://Stackoverflow.com/users/16781682",
"pm_score": 1,
"selected": false,
"text": "matches = [[1, 3], [2, 3], [3, 6], [5, 6], [5, 7], [4, 5], [4, 8], [4, 9], [10, 4], [10, 9]]\n\nlosses_dict = {}\nfor (_, value) in matches:\n losses_dict.setdefault(value, 0) # key might exist already\n losses_dict[value] += 1\n\nfinal_list = [\n [k for k, _ in matches if k not in losses_dict.keys()],\n [k for k, v in losses_dict.items() if v == 1]\n ]\n\n"
},
{
"answer_id": 74612208,
"author": "juanpa.arrivillaga",
"author_id": 5014455,
"author_profile": "https://Stackoverflow.com/users/5014455",
"pm_score": 1,
"selected": false,
"text": "seconds = {second for _, second in matches}\nnever_lost = [first for first, _ in matches if first not in seconds]\nnever_lost = list(dict.fromkeys(never_lost)) # idiom for removing duplicates while maintaining order\n never_lost = [\n x for x in\n {\n first: None\n for first, _ in matches \n for seconds in [{second for _, second in matches}] \n if first not in seconds\n }\n]\n"
},
{
"answer_id": 74612608,
"author": "Md. Ashikun Nabi",
"author_id": 11875349,
"author_profile": "https://Stackoverflow.com/users/11875349",
"pm_score": 0,
"selected": false,
"text": "neverLost = list(set(w for w, l in matches if all(w != j for i, j in matches)))\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12495331/"
] |
74,611,973
|
<p>I managed to create a rating control for only displaying rate results, but I am struggling to come up with a solution as to where a user would slide the rating bar with stars and based on the sliding position the stars could fill either half-way or fully, the control would also return the value of the user input. Any tips or suggestions would be helpful, I tried creating a Horizontal Stack Layout, but I am not sure how to dynamically change the photos when sliding for example detect that the photo should be a half star. Attached image for the expected result below. It should work for Android and iOS.</p>
<p><a href="https://i.stack.imgur.com/Yikya.png" rel="nofollow noreferrer">enter image description here</a></p>
|
[
{
"answer_id": 74612010,
"author": "itzMEonTV",
"author_id": 3160881,
"author_profile": "https://Stackoverflow.com/users/3160881",
"pm_score": 2,
"selected": false,
"text": "In [48]: list(set([j[0] for j in matches if j[0] not in [i[1] for i in matches]]))\nOut[48]: [1, 2, 10]\n"
},
{
"answer_id": 74612083,
"author": "Shrirang Mahajan",
"author_id": 17353907,
"author_profile": "https://Stackoverflow.com/users/17353907",
"pm_score": 1,
"selected": false,
"text": "neverLost = [w for w, l in matches if w not l]\n list(set([w[0] for w in matches if w[0] not in [l[1] for l in matches]]))\n"
},
{
"answer_id": 74612176,
"author": "Orfeas Bourchas",
"author_id": 16781682,
"author_profile": "https://Stackoverflow.com/users/16781682",
"pm_score": 1,
"selected": false,
"text": "matches = [[1, 3], [2, 3], [3, 6], [5, 6], [5, 7], [4, 5], [4, 8], [4, 9], [10, 4], [10, 9]]\n\nlosses_dict = {}\nfor (_, value) in matches:\n losses_dict.setdefault(value, 0) # key might exist already\n losses_dict[value] += 1\n\nfinal_list = [\n [k for k, _ in matches if k not in losses_dict.keys()],\n [k for k, v in losses_dict.items() if v == 1]\n ]\n\n"
},
{
"answer_id": 74612208,
"author": "juanpa.arrivillaga",
"author_id": 5014455,
"author_profile": "https://Stackoverflow.com/users/5014455",
"pm_score": 1,
"selected": false,
"text": "seconds = {second for _, second in matches}\nnever_lost = [first for first, _ in matches if first not in seconds]\nnever_lost = list(dict.fromkeys(never_lost)) # idiom for removing duplicates while maintaining order\n never_lost = [\n x for x in\n {\n first: None\n for first, _ in matches \n for seconds in [{second for _, second in matches}] \n if first not in seconds\n }\n]\n"
},
{
"answer_id": 74612608,
"author": "Md. Ashikun Nabi",
"author_id": 11875349,
"author_profile": "https://Stackoverflow.com/users/11875349",
"pm_score": 0,
"selected": false,
"text": "neverLost = list(set(w for w, l in matches if all(w != j for i, j in matches)))\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12695206/"
] |
74,611,974
|
<p>I have a simple node class with Id and Value, but python seems to not be able to access those attributes when i use the objects in a list. This is the class Node for context.</p>
<pre><code>class Node():
def __init__(self, id : int, value : int):
self.id = id
self.value = value
</code></pre>
<p>This is a priority queue implementation (or at least a try to do so) where the error comes from</p>
<pre><code>class ListAlt():
def __init__(self):
self.queue = [Node]
def append(self, node : Node):
self.queue.append(node)
def dequeue(self):
idMax = 0
i = 0
for nodo in self.queue:
if (nodo.value > self.queue[idMax].value):
idMax = i
i += 1
result = self.queue[idMax]
return result
</code></pre>
<p>And this is the full code</p>
<pre><code>#!/usr/bin/python3
class Node():
def __init__(self, id : int, value : int):
self.id = id
self.value = value
class ListAlt():
def __init__(self):
self.queue = [Node]
def append(self, node : Node):
self.queue.append(node)
def dequeue(self):
idMax = 0
i = 0
for nodo in self.queue:
if (nodo.value > self.queue[idMax].value):
idMax = i
i += 1
result = self.queue[idMax]
return result
n1 = Node(1,10)
n2 = Node(2,3)
n3 = Node(3,6)
lista = ListAlt()
lista.append(n1)
lista.append(n2)
lista.append(n3)
print(lista.dequeue())
</code></pre>
<p>Now, i can access the values of n1,n2,n3 directly, but inside the ListAlt object in this exact line</p>
<pre><code>if (nodo.value > self.queue[idMax].value):
</code></pre>
<p>it throws the exception saying "AttributeError: type object 'Node' has no attribute 'value'"
it should have printed "10" if everything worked correctly.</p>
|
[
{
"answer_id": 74612020,
"author": "Daniil Fajnberg",
"author_id": 19770795,
"author_profile": "https://Stackoverflow.com/users/19770795",
"pm_score": 3,
"selected": true,
"text": "class ListAlt():\n def __init__(self):\n self.queue = [Node] # <--\n queue Node dequeue Node 10 print(lista.dequeue().value)\n class Node:\n def __init__(self, node_id: int, value: int) -> None:\n self.id = node_id\n self.value = value\n\nclass ListAlt:\n def __init__(self) -> None:\n self.queue: list[Node] = []\n\n def append(self, node: Node) -> None:\n self.queue.append(node)\n\n def dequeue(self) -> Node:\n id_max = 0\n i = 0\n for nodo in self.queue:\n if nodo.value > self.queue[id_max].value:\n id_max = i\n i += 1\n result = self.queue[id_max]\n return result\n\nif __name__ == \"__main__\":\n n1 = Node(1, 10)\n n2 = Node(2, 3)\n n3 = Node(3, 6)\n \n lista = ListAlt()\n lista.append(n1)\n lista.append(n2)\n lista.append(n3)\n \n print(lista.dequeue().value)\n"
},
{
"answer_id": 74612051,
"author": "Raida",
"author_id": 13763683,
"author_profile": "https://Stackoverflow.com/users/13763683",
"pm_score": 2,
"selected": false,
"text": "Node value class ListAlt():\n def __init__(self):\n self.queue = []\n\n ...\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20631731/"
] |
74,611,976
|
<p>I have a project with 10+ parsers and at the end have this code:</p>
<p>`</p>
<pre><code>cursor = conn.cursor()
my_file = open(r'csv\file.csv')
sql_statement = """
CREATE TEMP TABLE temp
(
LIKE vhcl
)
ON COMMIT DROP;
COPY temp FROM STDIN WITH
CSV
HEADER
DELIMITER AS ',';
INSERT INTO vhcl
SELECT *
FROM temp
ON CONFLICT (id) DO UPDATE SET name= EXCLUDED.name"""
cursor.copy_expert(sql=sql_statement, file=my_file)
conn.commit()
cursor.close()
</code></pre>
<p>`
Everything worked fine until a couple of weeks ago I started to get these errors:</p>
<pre><code>server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
</code></pre>
<p>I noticed, that if parsers works (for example) less, than 10 minutes, I won't get those errors</p>
<p>I tried to make a separate function, that adds data to the DB after the parser ends working.
It still gives me that error. The strange thing is that I ran my parsers on my home pc, and it works fine, also, if I add data manually with the same function, but in a different file, it also works fine.</p>
<p>I asked about banned IP for db, but it's okay. So I have no idea why I have this error.</p>
<p>PostgreSQL log
<a href="https://i.stack.imgur.com/Aw8a3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Aw8a3.png" alt="PostgreSQL log" /></a></p>
|
[
{
"answer_id": 74612020,
"author": "Daniil Fajnberg",
"author_id": 19770795,
"author_profile": "https://Stackoverflow.com/users/19770795",
"pm_score": 3,
"selected": true,
"text": "class ListAlt():\n def __init__(self):\n self.queue = [Node] # <--\n queue Node dequeue Node 10 print(lista.dequeue().value)\n class Node:\n def __init__(self, node_id: int, value: int) -> None:\n self.id = node_id\n self.value = value\n\nclass ListAlt:\n def __init__(self) -> None:\n self.queue: list[Node] = []\n\n def append(self, node: Node) -> None:\n self.queue.append(node)\n\n def dequeue(self) -> Node:\n id_max = 0\n i = 0\n for nodo in self.queue:\n if nodo.value > self.queue[id_max].value:\n id_max = i\n i += 1\n result = self.queue[id_max]\n return result\n\nif __name__ == \"__main__\":\n n1 = Node(1, 10)\n n2 = Node(2, 3)\n n3 = Node(3, 6)\n \n lista = ListAlt()\n lista.append(n1)\n lista.append(n2)\n lista.append(n3)\n \n print(lista.dequeue().value)\n"
},
{
"answer_id": 74612051,
"author": "Raida",
"author_id": 13763683,
"author_profile": "https://Stackoverflow.com/users/13763683",
"pm_score": 2,
"selected": false,
"text": "Node value class ListAlt():\n def __init__(self):\n self.queue = []\n\n ...\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19995417/"
] |
74,612,007
|
<p>I have a bool called isSubmited. Default value is false. I want to change the value when user click on a button but the fact is how can I do it without the setState method in flutter.
I just want to change the value not the user interface. I just want change the bool value nothing else. But not the app state itself!</p>
|
[
{
"answer_id": 74612020,
"author": "Daniil Fajnberg",
"author_id": 19770795,
"author_profile": "https://Stackoverflow.com/users/19770795",
"pm_score": 3,
"selected": true,
"text": "class ListAlt():\n def __init__(self):\n self.queue = [Node] # <--\n queue Node dequeue Node 10 print(lista.dequeue().value)\n class Node:\n def __init__(self, node_id: int, value: int) -> None:\n self.id = node_id\n self.value = value\n\nclass ListAlt:\n def __init__(self) -> None:\n self.queue: list[Node] = []\n\n def append(self, node: Node) -> None:\n self.queue.append(node)\n\n def dequeue(self) -> Node:\n id_max = 0\n i = 0\n for nodo in self.queue:\n if nodo.value > self.queue[id_max].value:\n id_max = i\n i += 1\n result = self.queue[id_max]\n return result\n\nif __name__ == \"__main__\":\n n1 = Node(1, 10)\n n2 = Node(2, 3)\n n3 = Node(3, 6)\n \n lista = ListAlt()\n lista.append(n1)\n lista.append(n2)\n lista.append(n3)\n \n print(lista.dequeue().value)\n"
},
{
"answer_id": 74612051,
"author": "Raida",
"author_id": 13763683,
"author_profile": "https://Stackoverflow.com/users/13763683",
"pm_score": 2,
"selected": false,
"text": "Node value class ListAlt():\n def __init__(self):\n self.queue = []\n\n ...\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74612007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20224649/"
] |
74,612,029
|
<p>What is a correct way to do the matrix multiplication using ctype ?</p>
<p>in my current implementation data going back and forth consuming lots of time, is there any way to do it optimally ? by passing array address and getting pointer in return instead of generating entire array using <code>.contents</code> method.</p>
<p><strong>cpp_function.cpp</strong></p>
<p>compile using <code>g++ -shared -fPIC cpp_function.cpp -o cpp_function.so</code></p>
<pre><code>#include <iostream>
extern "C" {
double* mult_matrix(double *a1, double *a2, size_t a1_h, size_t a1_w,
size_t a2_h, size_t a2_w, int size)
{
double* ret_arr = new double[size];
for(size_t i = 0; i < a1_h; i++){
for (size_t j = 0; j < a2_w; j++) {
double val = 0;
for (size_t k = 0; k < a2_h; k++){
val += a1[i * a1_h + k] * a2[k * a2_h +j] ;
}
ret_arr[i * a1_h +j ] = val;
// printf("%f ", ret_arr[i * a1_h +j ]);
}
// printf("\n");
}
return ret_arr;
}
}
</code></pre>
<p>Python file to call the so file
<strong>main.py</strong></p>
<pre><code>import ctypes
import numpy
from time import time
libmatmult = ctypes.CDLL("./cpp_function.so")
ND_POINTER_1 = numpy.ctypeslib.ndpointer(dtype=numpy.float64,
ndim=2,
flags="C")
ND_POINTER_2 = numpy.ctypeslib.ndpointer(dtype=numpy.float64,
ndim=2,
flags="C")
libmatmult.mult_matrix.argtypes = [ND_POINTER_1, ND_POINTER_2, ctypes.c_size_t, ctypes.c_size_t]
def mult_matrix_cpp(a,b):
shape = a.shape[0] * a.shape[1]
libmatmult.mult_matrix.restype = ctypes.POINTER(ctypes.c_double * shape )
ret_cpp = libmatmult.mult_matrix(a, b, *a.shape, *b.shape , a.shape[0] * a.shape[1])
out_list_c = [i for i in ret_cpp.contents] # <---- regenrating list which is time consuming
return out_list_c
size_a = (300,300)
size_b = size_a
a = numpy.random.uniform(low=1, high=255, size=size_a)
b = numpy.random.uniform(low=1, high=255, size=size_b)
t2 = time()
out_cpp = mult_matrix_cpp(a,b)
print("cpp time taken:{:.2f} ms".format((time() - t2) * 1000))
out_cpp = numpy.array(out_cpp).reshape(size_a[0], size_a[1])
t3 = time()
out_np = numpy.dot(a,b)
# print(out_np)
print("Numpy dot() time taken:{:.2f} ms".format((time() - t3) * 1000))
</code></pre>
<p>This solution <strong>works but time consuming</strong> is there any way to make it faster ?</p>
|
[
{
"answer_id": 74619295,
"author": "Mark Tolonen",
"author_id": 235698,
"author_profile": "https://Stackoverflow.com/users/235698",
"pm_score": 1,
"selected": false,
"text": "ndpointer restype reshape def mult_matrix_cpp(a, b):\n shape = a.shape[0] * a.shape[1]\n libmatmult.mult_matrix.restype = np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, shape=a.shape, flags=\"C\")\n return libmatmult.mult_matrix(a, b, *a.shape, *b.shape , a.shape[0] * a.shape[1])\n"
},
{
"answer_id": 74662536,
"author": "DotNetRussell",
"author_id": 2051392,
"author_profile": "https://Stackoverflow.com/users/2051392",
"pm_score": 0,
"selected": false,
"text": "#include <stdio.h>\n\n// This function multiplies two matrices, and returns the result\n// in a two-dimensional array\nint** matrix_multiply(int** matrix1, int** matrix2, int rows1, int cols1, int rows2, int cols2) {\n int** matrix_result = (int**)malloc(rows1 * sizeof(int*));\n int i, j, k;\n\n // Check if the matrices can be multiplied\n if (cols1 != rows2) {\n printf(\"Matrices cannot be multiplied!\\n\");\n return NULL;\n }\n\n // Perform matrix multiplication\n for (i = 0; i < rows1; i++) {\n matrix_result[i] = (int*)malloc(cols2 * sizeof(int));\n for (j = 0; j < cols2; j++) {\n matrix_result[i][j] = 0;\n for (k = 0; k < cols1; k++) {\n matrix_result[i][j] += matrix1[i][k] * matrix2[k][j];\n }\n }\n }\n\n return matrix_result;\n}\n\nint main(void) {\n // Example matrices\n int** matrix1 = (int**)malloc(2 * sizeof(int*));\n matrix1[0] = (int*)malloc(2 * sizeof(int));\n matrix1[1] = (int*)malloc(2 * sizeof(int));\n matrix1[0][0] = 1; matrix1[0][1] = 2;\n matrix1[1][0] = 3; matrix1[1][1] = 4;\n\n int** matrix2 = (int**)malloc(2 * sizeof(int*));\n matrix2[0] = (int*)malloc(2 * sizeof(int));\n matrix2[1] = (int*)malloc(2 * sizeof(int));\n matrix2[0][0] = 5; matrix2[0][1] = 6;\n matrix2[1][0] = 7; matrix2[1][1] = 8;\n\n // Do matrix multiplication\n int** matrix_result = matrix_multiply(matrix1, matrix2, 2, 2, 2, 2);\n\n // Print the result\n int i, j;\n for (i = 0; i < 2; i++) {\n for (j = 0; j < 2; j++) {\n printf(\"%d \", matrix_result[i][j]);\n }\n printf(\"\\n\");\n }\n\n return 0;\n}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74612029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9427260/"
] |
74,612,035
|
<p>I have a function that should to build route from start to destination.</p>
<pre><code>function solve(start, end, fetchRouts): Promise<string[] | string>;
</code></pre>
<p>There also function that returns Promise with reachable points from current:</p>
<pre><code>function fetchRouts(departurePoint: string): Promise<string[]>;
</code></pre>
<p>I'm trying to solve using a recursive function. But i can't return the value correctly. Second [*] then is visited 3 times, but returns first time, <em>result</em> is undefined here, so returns 'no ticket';</p>
<p>Inside <strong>solve</strong>:</p>
<pre><code>const getRoute = (routes, stations) => {
return routes.then((next) => {
const temp = [...next];
while (temp.length !== 0) {
const current = temp[0];
const copyStations = [...stations];
copyStations.push(current);
if (current === end)
return Promise.resolve({ result: copyStations, end: true }); //how to throw result from here
getRoute(fetchRouts(current), copyStations).then(result => {
if (result && result.end)
return result;
});
temp.splice(0, 1); // delete station, because they were on it
}
}).then(result => { // [*]
if (result && result.end) {
return Promise.resolve(result.result); // to here
}
return Promise.resolve('no ticket');
})
}
return getRoute(fetchRouts(start), [start]);
</code></pre>
<p>a lil function description: <em>first argument</em> - <code>Promise<string[]></code>, contains next stations, also accumulate route (<em>second argument</em>). I split the array and look for the next available one for each station. If available station exists, go to it. If station is destination, return Promise. idk how return its correctly.</p>
|
[
{
"answer_id": 74614036,
"author": "Trevor Dixon",
"author_id": 711902,
"author_profile": "https://Stackoverflow.com/users/711902",
"pm_score": 2,
"selected": true,
"text": "then function solve(start, end, fetchRouts) {\n function getRoute(start, visited = new Set()) {\n visited.add(start);\n return fetchRouts(start).then(nexts => {\n for (const next of nexts) {\n if (next === end) {\n const route = Array.from(visited);\n route.push(end);\n return route;\n }\n if (!visited.has(next)) {\n return getRoute(next, visited);\n }\n }\n });\n }\n return getRoute(start);\n}\n function solve(start, end, fetchRouts) {\n function getRoute(start, visited = new Set()) {\n visited.add(start);\n return fetchRouts(start).then(nexts => {\n for (const next of nexts) {\n if (next === end) {\n const route = Array.from(visited);\n route.push(end);\n return route;\n }\n if (!visited.has(next)) {\n return getRoute(next, visited);\n }\n }\n });\n }\n return getRoute(start);\n}\n\nconst dests = {\"PHX\":[\"LAX\",\"JFK\"],\"BKK\":[\"MEX\",\"LIM\"],\"OKC\":[\"JFK\"],\"JFK\":[\"PHX\",\"OKC\",\"HEL\",\"LOS\"],\"LAX\":[\"PHX\",\"MEX\"],\"MEX\":[\"LAX\",\"BKK\",\"LIM\",\"EZE\"],\"EZE\":[\"MEX\"],\"HEL\":[\"JFK\"],\"LOS\":[\"JFK\"],\"LAP\":[],\"LIM\":[\"MEX\",\"BKK\"]};\nconst fetchRoutes = async (station) => dests[station];\n\nsolve('PHX', 'BKK', fetchRoutes).then(route => console.log(route));"
},
{
"answer_id": 74614521,
"author": "qbr_dude",
"author_id": 17628659,
"author_profile": "https://Stackoverflow.com/users/17628659",
"pm_score": 0,
"selected": false,
"text": "function solve(start, end, fetchRouts) {\n\nconst getRoute = (start, visited = new Set()) => {\n\n const clone = new Set(visited);\n clone.add(start);\n\n return fetchRouts(start).then(nexts => {\n for (const next of nexts) {\n if (next === end) {\n const route = Array.from(clone);\n route.push(end);\n return route;\n }\n if (!clone.has(next)) {\n getRoute(next, clone);\n }\n }\n });\n}\n\nreturn getRoute(start).then(result =>\n result ? Promise.resolve(result) : Promise.resolve('no ticket')\n);\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74612035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17628659/"
] |
74,612,092
|
<p>I have this table:</p>
<pre><code>CREATE TABLE TEST
(
TITLE VARCHAR2(199 BYTE),
AMOUNT NUMBER,
VALUE NUMBER
)
</code></pre>
<p>and this <code>INSERT</code> statement:</p>
<pre><code>INSERT INTO TEST (TITLE, AMOUNT, VAL)
VALUES (Switch, 3000, 12);
COMMIT;
</code></pre>
<p>We have an amount = 3000 up to 12, now we need to calculate.</p>
<p>So</p>
<ul>
<li>3000 multiplied by 1 = 3000</li>
<li>3000 multiplied by 2 = 6000</li>
<li>3000 multiplied by 3 = 9000</li>
<li>3000 multiplied by 4 = 12000</li>
<li>3000 multiplied by 5 = 15000</li>
<li>3000 multiplied by 6 = 18000</li>
<li>3000 multiplied by 7 = 21000</li>
<li>3000 multiplied by 8 = 24000</li>
<li>3000 multiplied by 9 = 27000</li>
<li>3000 multiplied by 10 = 30000</li>
<li>3000 multiplied by 11 = 33000</li>
<li>3000 multiplied by 12 = 36000</li>
</ul>
<p>Regards</p>
<p>Output is needed in the following format.</p>
<pre><code>Title Amount Total
Switch 30000 3000 6000 9000 12000 15000 18000 21000 24000 27000 30000 33000 36000 231000
plug
board
</code></pre>
<p>Can somebody help me how to get this output in SQL?</p>
|
[
{
"answer_id": 74614036,
"author": "Trevor Dixon",
"author_id": 711902,
"author_profile": "https://Stackoverflow.com/users/711902",
"pm_score": 2,
"selected": true,
"text": "then function solve(start, end, fetchRouts) {\n function getRoute(start, visited = new Set()) {\n visited.add(start);\n return fetchRouts(start).then(nexts => {\n for (const next of nexts) {\n if (next === end) {\n const route = Array.from(visited);\n route.push(end);\n return route;\n }\n if (!visited.has(next)) {\n return getRoute(next, visited);\n }\n }\n });\n }\n return getRoute(start);\n}\n function solve(start, end, fetchRouts) {\n function getRoute(start, visited = new Set()) {\n visited.add(start);\n return fetchRouts(start).then(nexts => {\n for (const next of nexts) {\n if (next === end) {\n const route = Array.from(visited);\n route.push(end);\n return route;\n }\n if (!visited.has(next)) {\n return getRoute(next, visited);\n }\n }\n });\n }\n return getRoute(start);\n}\n\nconst dests = {\"PHX\":[\"LAX\",\"JFK\"],\"BKK\":[\"MEX\",\"LIM\"],\"OKC\":[\"JFK\"],\"JFK\":[\"PHX\",\"OKC\",\"HEL\",\"LOS\"],\"LAX\":[\"PHX\",\"MEX\"],\"MEX\":[\"LAX\",\"BKK\",\"LIM\",\"EZE\"],\"EZE\":[\"MEX\"],\"HEL\":[\"JFK\"],\"LOS\":[\"JFK\"],\"LAP\":[],\"LIM\":[\"MEX\",\"BKK\"]};\nconst fetchRoutes = async (station) => dests[station];\n\nsolve('PHX', 'BKK', fetchRoutes).then(route => console.log(route));"
},
{
"answer_id": 74614521,
"author": "qbr_dude",
"author_id": 17628659,
"author_profile": "https://Stackoverflow.com/users/17628659",
"pm_score": 0,
"selected": false,
"text": "function solve(start, end, fetchRouts) {\n\nconst getRoute = (start, visited = new Set()) => {\n\n const clone = new Set(visited);\n clone.add(start);\n\n return fetchRouts(start).then(nexts => {\n for (const next of nexts) {\n if (next === end) {\n const route = Array.from(clone);\n route.push(end);\n return route;\n }\n if (!clone.has(next)) {\n getRoute(next, clone);\n }\n }\n });\n}\n\nreturn getRoute(start).then(result =>\n result ? Promise.resolve(result) : Promise.resolve('no ticket')\n);\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74612092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14699956/"
] |
74,612,121
|
<pre><code>List a = [
AbsentModel(name: "abir", id: 1),
AbsentModel(name: "fahim", id: 2),
AbsentModel(name: "rahim", id: 3),
AbsentModel(name: "akash", id: 4), ]
List b = [
AbsentModel(name: "akash", id: 4),
AbsentModel(name: "fahim", id: 2),
AbsentModel(name: "rahim", id: 3),]
</code></pre>
<p>`
<strong>I need the output of -
the difference between List a and List b</strong></p>
<p>result -</p>
<pre><code>`List c = [ AbsentModel(name: "abir", id: 1),];
</code></pre>
<p>I have tried to toSet() but it only can give me the result If i made all list without model.
Like if made simple id List then it works.
But can not get the difference when I am using model data.</p>
|
[
{
"answer_id": 74612523,
"author": "Ariel",
"author_id": 2298251,
"author_profile": "https://Stackoverflow.com/users/2298251",
"pm_score": 2,
"selected": true,
"text": "void main() {\n List a = [\n\nAbsentModel(name: \"abir\", id: 1),\nAbsentModel(name: \"fahim\", id: 2),\nAbsentModel(name: \"rahim\", id: 3),\nAbsentModel(name: \"akash\", id: 4), ]\n\n\nList b = [\nAbsentModel(name: \"akash\", id: 4),\nAbsentModel(name: \"fahim\", id: 2),\nAbsentModel(name: \"rahim\", id: 3),]\n\n List<AbsentModel> c = a.where((item) => !b.contains(item)).toList();\n print(c); \n}\n AbsentModel import 'package:equatable/equatable.dart';\n\nclass AbsentModel extends Equatable {\n final String name;\n final int id;\n\n AbsentModel({required this.name, required this.id,});\n\n @override\n List<Object> get props => [name, id];\n}\n == hashCode"
},
{
"answer_id": 74613509,
"author": "Jozott",
"author_id": 10127472,
"author_profile": "https://Stackoverflow.com/users/10127472",
"pm_score": 0,
"selected": false,
"text": "a b b a List extension Difference<T> on List<T> {\n List<T> difference(List<T> to) {\n final diff = where((item) => !to.contains(item)).toList();\n diff.addAll(to.where((item) => !contains(item)));\n return diff;\n }\n\nmain() {\n...\n final diff = a.difference(b);\n}\n == class AbsentModel {\n final String name;\n final int id;\n\n AbsentModel({required this.name, required this.id});\n\n @override\n bool operator ==(Object other) {\n return (other is AbsentModel) && other.id == id && other.name == name;\n }\n}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74612121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20631864/"
] |
74,612,132
|
<p>I have defined an example JSON:</p>
<pre><code>"BasicData": {
"country": "United Kingdom"
},
"Phone": {
"Phone prefix": "+44"
}
</code></pre>
<p>I am trying to build an object based on a value in another object. Phone prefixes should have determined by the country value (which will be passed as a parameter). Can we make this using builder and switch case statements in the Phone class, or are there any Lombok annotations that can help solve this problem?</p>
|
[
{
"answer_id": 74612523,
"author": "Ariel",
"author_id": 2298251,
"author_profile": "https://Stackoverflow.com/users/2298251",
"pm_score": 2,
"selected": true,
"text": "void main() {\n List a = [\n\nAbsentModel(name: \"abir\", id: 1),\nAbsentModel(name: \"fahim\", id: 2),\nAbsentModel(name: \"rahim\", id: 3),\nAbsentModel(name: \"akash\", id: 4), ]\n\n\nList b = [\nAbsentModel(name: \"akash\", id: 4),\nAbsentModel(name: \"fahim\", id: 2),\nAbsentModel(name: \"rahim\", id: 3),]\n\n List<AbsentModel> c = a.where((item) => !b.contains(item)).toList();\n print(c); \n}\n AbsentModel import 'package:equatable/equatable.dart';\n\nclass AbsentModel extends Equatable {\n final String name;\n final int id;\n\n AbsentModel({required this.name, required this.id,});\n\n @override\n List<Object> get props => [name, id];\n}\n == hashCode"
},
{
"answer_id": 74613509,
"author": "Jozott",
"author_id": 10127472,
"author_profile": "https://Stackoverflow.com/users/10127472",
"pm_score": 0,
"selected": false,
"text": "a b b a List extension Difference<T> on List<T> {\n List<T> difference(List<T> to) {\n final diff = where((item) => !to.contains(item)).toList();\n diff.addAll(to.where((item) => !contains(item)));\n return diff;\n }\n\nmain() {\n...\n final diff = a.difference(b);\n}\n == class AbsentModel {\n final String name;\n final int id;\n\n AbsentModel({required this.name, required this.id});\n\n @override\n bool operator ==(Object other) {\n return (other is AbsentModel) && other.id == id && other.name == name;\n }\n}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74612132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13096242/"
] |
74,612,135
|
<p>I have a search input and I only want to trigger the <code>this.searchProperties.emit </code> if the user touch or made an input to the input field I don't wanna trigger it after view init. I only want to emit if the user touches or made an input on the input field.</p>
<p>Currently, the issue is it calls the emit after the view is initialized. Thanks for any ideas or help.</p>
<p><strong>html code</strong></p>
<pre><code><mat-form-field id="property-list-filter" appearance="fill">
<mat-label style="font-size:12px">Filter properties</mat-label>
<input matInput #searchInput placeholder="Ex. Property ID" #input>
</mat-form-field>
</code></pre>
<p><strong>ts code snippet</strong></p>
<pre><code>@ViewChild('searchInput') searchInput: ElementRef;
ngAfterViewInit() {
this.dataSource.sort = this.sort;
this.dataSource.paginator = this.paginator
fromEvent<any>(this.searchInput.nativeElement, 'keyup')
.pipe(
map((event) => event.target.value),
startWith(''),
debounceTime(500),
distinctUntilChanged(),
switchMap(async (search) => {
this.searchProperties.emit(this.searchInput.nativeElement.value.trim().toLowerCase())
})
)
.subscribe({ complete: noop });
}
</code></pre>
|
[
{
"answer_id": 74612290,
"author": "Avraham Weinstein",
"author_id": 8938503,
"author_profile": "https://Stackoverflow.com/users/8938503",
"pm_score": 2,
"selected": true,
"text": "startWith input Angular event binding <input (input)=\"onInput()\"/>\n onInput(){\n ...\n}\n focus ReactiveForms"
},
{
"answer_id": 74612572,
"author": "h.zare",
"author_id": 9628852,
"author_profile": "https://Stackoverflow.com/users/9628852",
"pm_score": 2,
"selected": false,
"text": "<mat-form-field id=\"property-list-filter\" appearance=\"fill\">\n <mat-label style=\"font-size:12px\">Filter properties</mat-label>\n <input matInput [(ngModel)]=\"input variable\" (ngModelChange)=\"changeHandlerFunction()\" placeholder=\"Ex. Property ID\" #input>\n</mat-form-field>\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74612135",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19053255/"
] |
74,612,162
|
<p>I am trying to overlap two different <code>compose</code> elements. I want to show a <code>toast</code> kind of message at the top whenever there is an error message. I don't want to use a third party lib for such an easy use case. I plan to use the <code>toast</code> in every other composable screen for displaying error message. Below is the layout which i want to achieve</p>
<p><a href="https://i.stack.imgur.com/cNgdK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cNgdK.png" alt="enter image description here" /></a></p>
<p>So I want to achieve the toast message saying "Invalid PIN, please try again".</p>
<pre><code>@Composable
fun MyToast(title: String) {
Card(
modifier = Modifier
.absoluteOffset(x = 0.dp, y = 40.dp)
.background(
color = MaterialTheme.colors.primaryVariant,
shape = RoundedCornerShape(10.dp)
), elevation = 20.dp
) {
Row(
modifier = Modifier
.background(color = MaterialTheme.colors.primaryVariant)
.padding(12.dp),
horizontalArrangement = Arrangement.Start,
verticalAlignment = Alignment.CenterVertically
) {
Image(
painter = painterResource(id = R.drawable.error_circle),
contentDescription = title
)
Text(
text = title,
fontFamily = FontFamily(Font(R.font.inter_medium)),
fontSize = 12.sp,
color = MaterialTheme.colors.primary,
modifier = Modifier.padding(horizontal = 10.dp)
)
}
}
}
</code></pre>
<p>and my screen composable is as follows</p>
<pre><code>@Composable
fun Registration(navController: NavController, registrationViewModel: RegistrationViewModel) {
Scaffold() {
Box(){
MyToast(
title = "Invalid pin, please try again"
)
Column() {
//my other screen components
}
}
}
</code></pre>
<p>I will add the AnimatedVisibility modifier later to MyToast composable. First I need to overlap MyToast over all the other elements and somehow MyToast is just not visible</p>
|
[
{
"answer_id": 74612347,
"author": "z.y",
"author_id": 19023745,
"author_profile": "https://Stackoverflow.com/users/19023745",
"pm_score": 3,
"selected": true,
"text": "Box Box(\n modifier = Modifier.fillMaxSize(),\n contentAlignment = Alignment.Center\n) {\n\n Box(\n modifier = Modifier.background(Color.Red).size(150.dp)\n )\n\n // your Toast\n Box(\n modifier = Modifier.background(Color.Green).size(80.dp)\n )\n}\n Box(\n modifier = Modifier.fillMaxSize(),\n contentAlignment = Alignment.Center\n) {\n\n // your Toast\n Box(\n modifier = Modifier.background(Color.Green).size(80.dp)\n )\n\n Box(\n modifier = Modifier.background(Color.Red).size(150.dp)\n )\n}\n"
},
{
"answer_id": 74612432,
"author": "MoCoding",
"author_id": 11617754,
"author_profile": "https://Stackoverflow.com/users/11617754",
"pm_score": 2,
"selected": false,
"text": "@Composable\nfun Registration(navController: NavController, registrationViewModel: RegistrationViewModel) {\n Scaffold() {\n Box() {\n Column() {\n //my other screen components\n }\n MyToast(\n title = \"Invalid pin, please try again\"\n )\n }\n }\n} \n @Composable\nfun MyToast(title: String) {\n Card(\n modifier = Modifier\n .absoluteOffset(x = 0.dp, y = 40.dp)\n .zIndex(10f) // add z index here\n .background(\n color = MaterialTheme.colors.primaryVariant,\n shape = RoundedCornerShape(10.dp)\n ), elevation = 20.dp\n ) {\n Row(\n modifier = Modifier\n .background(color = MaterialTheme.colors.primaryVariant)\n .padding(12.dp),\n horizontalArrangement = Arrangement.Start,\n verticalAlignment = Alignment.CenterVertically\n ) {\n Image(\n painter = painterResource(id = R.drawable.error_circle),\n contentDescription = title\n )\n Text(\n text = title,\n fontFamily = FontFamily(Font(R.font.inter_medium)),\n fontSize = 12.sp,\n color = MaterialTheme.colors.primary,\n modifier = Modifier.padding(horizontal = 10.dp)\n )\n }\n }\n\n}\n Card XML Modifier.zIndex(10f)"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74612162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9552485/"
] |
74,612,185
|
<p>Hi stackoverflow I have here a sql statement that is pretty slow performing which I think is due to the subquery seen in the sql below. My question is simply given that this subquery and the fact that it must set 'exists' to 0 or 1 given the logic can this be improved.</p>
<pre><code> SELECT
p.id,
p.name,
(
SELECT
COUNT(*) > 0
FROM
product_log AS pl
WHERE
pl.product_id = p.id
AND
pl.state_name in ("Creation", "Auction", ...)
) AS 'has_log'
from product as p;
</code></pre>
<p>Table creations for log and product</p>
<pre><code>CREATE TABLE `product_log` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`product_id` int(11) DEFAULT NULL,
`state_name` varchar(50) CHARACTER SET latin1 DEFAULT NULL,
`create_datetime` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `product_id` (`product_id`),
KEY `state_name` (`state_name`,`create_datetime`)
(`id`,`product_id`,`state_name`,`create_datetime`)
) ENGINE=InnoDB AUTO_INCREMENT=8132540 DEFAULT CHARSET=utf8;
</code></pre>
<p>Running explain on the query, is a bit different since much of the details where omitted compared to the actual query that is run but here is the output</p>
<pre><code>|id |select_type |table|partitions|type |possible_keys |key |key_len|ref |rows |filtered|Extra |
|---|------------------|-----|----------|------|-----------------------------------------------------------------|-------------------|-------|-----------------------------|------|--------|--------------------------------------------|
|1 |PRIMARY |p | |eq_ref|PRIMARY,guarantee_list_index |PRIMARY |4 |ppd.product_id |1 |100 | |
|2 |DEPENDENT SUBQUERY|pl | |ref |product_id,state_name |product_id |5 |p.id |3 |51.5 |Using where |
</code></pre>
|
[
{
"answer_id": 74612610,
"author": "ufosnowcat",
"author_id": 1728208,
"author_profile": "https://Stackoverflow.com/users/1728208",
"pm_score": 2,
"selected": false,
"text": "select p.id, p.name, CASE WHEN pl.id IS NULL THEN 0 ELSE 1 END AS has_log\nfrom product as p\nleft join product_log AS pl on pl.product_id = p.id AND pl.state_name in (\"Creation\", \"Auction\", ...)\n"
},
{
"answer_id": 74612688,
"author": "Thorsten Kettner",
"author_id": 2270762,
"author_profile": "https://Stackoverflow.com/users/2270762",
"pm_score": 3,
"selected": true,
"text": "EXISTS IN SELECT\n p.id,\n p.name,\n EXISTS\n (\n SELECT null\n FROM product_log AS pl\n WHERE pl.product_id = p.id\n AND pl.state_name in ('Creation', 'Auction', ...)\n ) AS has_log\nFROM product AS p;\n SELECT\n p.id,\n p.name,\n p.id IN\n (\n SELECT pl.product_id\n FROM product_log AS pl\n WHERE pl.state_name in ('Creation', 'Auction', ...)\n ) AS has_log\nFROM product AS p;\n CREATE INDEX idx1 ON product_log (product_id, state_name);\n CREATE INDEX idx2 ON product_log (state_name, product_id);\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74612185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3286164/"
] |
74,612,187
|
<p>I need to push data from multiple Kafka producers to a seperate Kafka broker. Say I have 3 Kafka servers. From Kafka 1 and 2, I need to push the data to Kafka 3 like below, is it possible?</p>
<p><a href="https://i.stack.imgur.com/ZMfrZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZMfrZ.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74612610,
"author": "ufosnowcat",
"author_id": 1728208,
"author_profile": "https://Stackoverflow.com/users/1728208",
"pm_score": 2,
"selected": false,
"text": "select p.id, p.name, CASE WHEN pl.id IS NULL THEN 0 ELSE 1 END AS has_log\nfrom product as p\nleft join product_log AS pl on pl.product_id = p.id AND pl.state_name in (\"Creation\", \"Auction\", ...)\n"
},
{
"answer_id": 74612688,
"author": "Thorsten Kettner",
"author_id": 2270762,
"author_profile": "https://Stackoverflow.com/users/2270762",
"pm_score": 3,
"selected": true,
"text": "EXISTS IN SELECT\n p.id,\n p.name,\n EXISTS\n (\n SELECT null\n FROM product_log AS pl\n WHERE pl.product_id = p.id\n AND pl.state_name in ('Creation', 'Auction', ...)\n ) AS has_log\nFROM product AS p;\n SELECT\n p.id,\n p.name,\n p.id IN\n (\n SELECT pl.product_id\n FROM product_log AS pl\n WHERE pl.state_name in ('Creation', 'Auction', ...)\n ) AS has_log\nFROM product AS p;\n CREATE INDEX idx1 ON product_log (product_id, state_name);\n CREATE INDEX idx2 ON product_log (state_name, product_id);\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74612187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15182263/"
] |
74,612,197
|
<p>I would like to do an ordinal encoding of a column. Pandas has the nice and convenient method of <code>pd.factorize()</code>, however, I would like to achieve the same in polars.</p>
<pre><code> df = pl.DataFrame({"a": [5, 8, 10], "b": ["hi", "hello", "hi"]})
┌─────┬───────┐
│ a ┆ b │
│ --- ┆ --- │
│ i64 ┆ str │
╞═════╪═══════╡
│ 5 ┆ hi │
├╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ 8 ┆ hello │
├╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ 10 ┆ hi │
└─────┴───────┘
</code></pre>
<p>desired result:</p>
<pre><code>┌─────┬─────┐
│ a ┆ b │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 0 ┆ 0 │
├╌╌╌╌╌┼╌╌╌╌╌┤
│ 1 ┆ 1 │
├╌╌╌╌╌┼╌╌╌╌╌┤
│ 2 ┆ 0 │
└─────┴─────┘
</code></pre>
|
[
{
"answer_id": 74614312,
"author": "ritchie46",
"author_id": 6717054,
"author_profile": "https://Stackoverflow.com/users/6717054",
"pm_score": 3,
"selected": true,
"text": "DataFrame df = pl.DataFrame({\"a\": [5, 8, 10], \"b\": [\"hi\", \"hello\", \"hi\"]})\n\nunique = df.select(\n pl.col(\"b\").unique(maintain_order=True)\n).with_row_count(name=\"ordinal\")\n\ndf.join(unique, on=\"b\")\n u32 df.with_column(\n pl.col(\"b\").cast(pl.Categorical).to_physical().alias(\"ordinal\")\n)\n shape: (3, 3)\n┌─────┬───────┬─────────┐\n│ a ┆ b ┆ ordinal │\n│ --- ┆ --- ┆ --- │\n│ i64 ┆ str ┆ u32 │\n╞═════╪═══════╪═════════╡\n│ 5 ┆ hi ┆ 0 │\n├╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┤\n│ 8 ┆ hello ┆ 1 │\n├╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┤\n│ 10 ┆ hi ┆ 0 │\n└─────┴───────┴─────────┘\n\n"
},
{
"answer_id": 74618840,
"author": "Dean MacGregor",
"author_id": 1818713,
"author_profile": "https://Stackoverflow.com/users/1818713",
"pm_score": 0,
"selected": false,
"text": "df.with_columns([pl.col('b').unique().list().alias('uniq'),\n pl.col('b').unique().list().arr.eval(pl.element().rank()).alias('uniqid')]).explode(['uniq','uniqid']).filter(pl.col('b')==pl.col('uniq')).select(pl.exclude('uniq')).with_column(pl.col('uniqid')-1)\n uniq uniqid uniq b rank 1 uniq b"
},
{
"answer_id": 74636771,
"author": "jqurious",
"author_id": 19355181,
"author_profile": "https://Stackoverflow.com/users/19355181",
"pm_score": 0,
"selected": false,
"text": ".rank(method=\"dense\") >>> df.select(pl.all().rank(method=\"dense\") - 1)\nshape: (3, 2)\n┌─────┬─────┐\n│ a ┆ b │\n│ --- ┆ --- │\n│ u32 ┆ u32 │\n╞═════╪═════╡\n│ 0 ┆ 1 │\n├╌╌╌╌╌┼╌╌╌╌╌┤\n│ 1 ┆ 0 │\n├╌╌╌╌╌┼╌╌╌╌╌┤\n│ 2 ┆ 1 │\n└─────┴─────┘\n >>> (\n... df.with_row_count()\n... .with_columns([\n... pl.col(\"row_nr\").first()\n... .over(col)\n... .rank(method=\"dense\")\n... .alias(col) - 1\n... for col in df.columns\n... ])\n... .drop(\"row_nr\")\n... )\nshape: (3, 2)\n┌─────┬─────┐\n│ a ┆ b │\n│ --- ┆ --- │\n│ u32 ┆ u32 │\n╞═════╪═════╡\n│ 0 ┆ 0 │\n├╌╌╌╌╌┼╌╌╌╌╌┤\n│ 1 ┆ 1 │\n├╌╌╌╌╌┼╌╌╌╌╌┤\n│ 2 ┆ 0 │\n└─────┴─────┘\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74612197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12386797/"
] |
74,612,214
|
<p>I have an ASP.NET Core 5 application. There are some log providers that I have as from box. Other words I cannot configure theese providers. But I need to add additional info to every logging message.</p>
<p>For example, code invoke:</p>
<p><code>logger.LogInfo("Hello World");</code></p>
<p>But logging provider must get, for example "UserId: 123; Hello World"</p>
<p>How can I reach this goal?</p>
|
[
{
"answer_id": 74614312,
"author": "ritchie46",
"author_id": 6717054,
"author_profile": "https://Stackoverflow.com/users/6717054",
"pm_score": 3,
"selected": true,
"text": "DataFrame df = pl.DataFrame({\"a\": [5, 8, 10], \"b\": [\"hi\", \"hello\", \"hi\"]})\n\nunique = df.select(\n pl.col(\"b\").unique(maintain_order=True)\n).with_row_count(name=\"ordinal\")\n\ndf.join(unique, on=\"b\")\n u32 df.with_column(\n pl.col(\"b\").cast(pl.Categorical).to_physical().alias(\"ordinal\")\n)\n shape: (3, 3)\n┌─────┬───────┬─────────┐\n│ a ┆ b ┆ ordinal │\n│ --- ┆ --- ┆ --- │\n│ i64 ┆ str ┆ u32 │\n╞═════╪═══════╪═════════╡\n│ 5 ┆ hi ┆ 0 │\n├╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┤\n│ 8 ┆ hello ┆ 1 │\n├╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┤\n│ 10 ┆ hi ┆ 0 │\n└─────┴───────┴─────────┘\n\n"
},
{
"answer_id": 74618840,
"author": "Dean MacGregor",
"author_id": 1818713,
"author_profile": "https://Stackoverflow.com/users/1818713",
"pm_score": 0,
"selected": false,
"text": "df.with_columns([pl.col('b').unique().list().alias('uniq'),\n pl.col('b').unique().list().arr.eval(pl.element().rank()).alias('uniqid')]).explode(['uniq','uniqid']).filter(pl.col('b')==pl.col('uniq')).select(pl.exclude('uniq')).with_column(pl.col('uniqid')-1)\n uniq uniqid uniq b rank 1 uniq b"
},
{
"answer_id": 74636771,
"author": "jqurious",
"author_id": 19355181,
"author_profile": "https://Stackoverflow.com/users/19355181",
"pm_score": 0,
"selected": false,
"text": ".rank(method=\"dense\") >>> df.select(pl.all().rank(method=\"dense\") - 1)\nshape: (3, 2)\n┌─────┬─────┐\n│ a ┆ b │\n│ --- ┆ --- │\n│ u32 ┆ u32 │\n╞═════╪═════╡\n│ 0 ┆ 1 │\n├╌╌╌╌╌┼╌╌╌╌╌┤\n│ 1 ┆ 0 │\n├╌╌╌╌╌┼╌╌╌╌╌┤\n│ 2 ┆ 1 │\n└─────┴─────┘\n >>> (\n... df.with_row_count()\n... .with_columns([\n... pl.col(\"row_nr\").first()\n... .over(col)\n... .rank(method=\"dense\")\n... .alias(col) - 1\n... for col in df.columns\n... ])\n... .drop(\"row_nr\")\n... )\nshape: (3, 2)\n┌─────┬─────┐\n│ a ┆ b │\n│ --- ┆ --- │\n│ u32 ┆ u32 │\n╞═════╪═════╡\n│ 0 ┆ 0 │\n├╌╌╌╌╌┼╌╌╌╌╌┤\n│ 1 ┆ 1 │\n├╌╌╌╌╌┼╌╌╌╌╌┤\n│ 2 ┆ 0 │\n└─────┴─────┘\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74612214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4987836/"
] |
74,612,228
|
<p>If i click on a button, i want to trigger another button selected by class.</p>
<p>I wrote the following HTML:</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><button onclick="document.getElementsByClassName("frame-16nsqo4").click()">Click</button></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74614312,
"author": "ritchie46",
"author_id": 6717054,
"author_profile": "https://Stackoverflow.com/users/6717054",
"pm_score": 3,
"selected": true,
"text": "DataFrame df = pl.DataFrame({\"a\": [5, 8, 10], \"b\": [\"hi\", \"hello\", \"hi\"]})\n\nunique = df.select(\n pl.col(\"b\").unique(maintain_order=True)\n).with_row_count(name=\"ordinal\")\n\ndf.join(unique, on=\"b\")\n u32 df.with_column(\n pl.col(\"b\").cast(pl.Categorical).to_physical().alias(\"ordinal\")\n)\n shape: (3, 3)\n┌─────┬───────┬─────────┐\n│ a ┆ b ┆ ordinal │\n│ --- ┆ --- ┆ --- │\n│ i64 ┆ str ┆ u32 │\n╞═════╪═══════╪═════════╡\n│ 5 ┆ hi ┆ 0 │\n├╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┤\n│ 8 ┆ hello ┆ 1 │\n├╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┤\n│ 10 ┆ hi ┆ 0 │\n└─────┴───────┴─────────┘\n\n"
},
{
"answer_id": 74618840,
"author": "Dean MacGregor",
"author_id": 1818713,
"author_profile": "https://Stackoverflow.com/users/1818713",
"pm_score": 0,
"selected": false,
"text": "df.with_columns([pl.col('b').unique().list().alias('uniq'),\n pl.col('b').unique().list().arr.eval(pl.element().rank()).alias('uniqid')]).explode(['uniq','uniqid']).filter(pl.col('b')==pl.col('uniq')).select(pl.exclude('uniq')).with_column(pl.col('uniqid')-1)\n uniq uniqid uniq b rank 1 uniq b"
},
{
"answer_id": 74636771,
"author": "jqurious",
"author_id": 19355181,
"author_profile": "https://Stackoverflow.com/users/19355181",
"pm_score": 0,
"selected": false,
"text": ".rank(method=\"dense\") >>> df.select(pl.all().rank(method=\"dense\") - 1)\nshape: (3, 2)\n┌─────┬─────┐\n│ a ┆ b │\n│ --- ┆ --- │\n│ u32 ┆ u32 │\n╞═════╪═════╡\n│ 0 ┆ 1 │\n├╌╌╌╌╌┼╌╌╌╌╌┤\n│ 1 ┆ 0 │\n├╌╌╌╌╌┼╌╌╌╌╌┤\n│ 2 ┆ 1 │\n└─────┴─────┘\n >>> (\n... df.with_row_count()\n... .with_columns([\n... pl.col(\"row_nr\").first()\n... .over(col)\n... .rank(method=\"dense\")\n... .alias(col) - 1\n... for col in df.columns\n... ])\n... .drop(\"row_nr\")\n... )\nshape: (3, 2)\n┌─────┬─────┐\n│ a ┆ b │\n│ --- ┆ --- │\n│ u32 ┆ u32 │\n╞═════╪═════╡\n│ 0 ┆ 0 │\n├╌╌╌╌╌┼╌╌╌╌╌┤\n│ 1 ┆ 1 │\n├╌╌╌╌╌┼╌╌╌╌╌┤\n│ 2 ┆ 0 │\n└─────┴─────┘\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74612228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13418217/"
] |
74,612,246
|
<p>I am using disableIntervalMomentum={true} to stop slider on next index. It is working for android but for IOS, on fast scrolling, it does not stop on next index but keeps moving.</p>
<p>here is my code</p>
<pre><code><FlatList
ref={flatListRef}
data={data?.offers || []}
keyExtractor={(item, index) => index.toString()}
horizontal={true}
bounces={(data?.offers || []).length > 1}
pagingEnabled={true}
showsHorizontalScrollIndicator={false}
snapToInterval={!isMultiCard ? snapToInterval : undefined}
onViewableItemsChanged={onViewRef.current}
viewabilityConfig={viewConfigRef.current}
disableIntervalMomentum={true}
decelerationRate={'fast'}
snapToOffsets={isMultiCard && length > 1 ? snapToOffsets : undefined}
scrollEnabled={true}
/>
</code></pre>
<p>I added disableIntervalMomentum={true} but it is not working for IOS.
Let me know if more info is needed.</p>
|
[
{
"answer_id": 74614312,
"author": "ritchie46",
"author_id": 6717054,
"author_profile": "https://Stackoverflow.com/users/6717054",
"pm_score": 3,
"selected": true,
"text": "DataFrame df = pl.DataFrame({\"a\": [5, 8, 10], \"b\": [\"hi\", \"hello\", \"hi\"]})\n\nunique = df.select(\n pl.col(\"b\").unique(maintain_order=True)\n).with_row_count(name=\"ordinal\")\n\ndf.join(unique, on=\"b\")\n u32 df.with_column(\n pl.col(\"b\").cast(pl.Categorical).to_physical().alias(\"ordinal\")\n)\n shape: (3, 3)\n┌─────┬───────┬─────────┐\n│ a ┆ b ┆ ordinal │\n│ --- ┆ --- ┆ --- │\n│ i64 ┆ str ┆ u32 │\n╞═════╪═══════╪═════════╡\n│ 5 ┆ hi ┆ 0 │\n├╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┤\n│ 8 ┆ hello ┆ 1 │\n├╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┤\n│ 10 ┆ hi ┆ 0 │\n└─────┴───────┴─────────┘\n\n"
},
{
"answer_id": 74618840,
"author": "Dean MacGregor",
"author_id": 1818713,
"author_profile": "https://Stackoverflow.com/users/1818713",
"pm_score": 0,
"selected": false,
"text": "df.with_columns([pl.col('b').unique().list().alias('uniq'),\n pl.col('b').unique().list().arr.eval(pl.element().rank()).alias('uniqid')]).explode(['uniq','uniqid']).filter(pl.col('b')==pl.col('uniq')).select(pl.exclude('uniq')).with_column(pl.col('uniqid')-1)\n uniq uniqid uniq b rank 1 uniq b"
},
{
"answer_id": 74636771,
"author": "jqurious",
"author_id": 19355181,
"author_profile": "https://Stackoverflow.com/users/19355181",
"pm_score": 0,
"selected": false,
"text": ".rank(method=\"dense\") >>> df.select(pl.all().rank(method=\"dense\") - 1)\nshape: (3, 2)\n┌─────┬─────┐\n│ a ┆ b │\n│ --- ┆ --- │\n│ u32 ┆ u32 │\n╞═════╪═════╡\n│ 0 ┆ 1 │\n├╌╌╌╌╌┼╌╌╌╌╌┤\n│ 1 ┆ 0 │\n├╌╌╌╌╌┼╌╌╌╌╌┤\n│ 2 ┆ 1 │\n└─────┴─────┘\n >>> (\n... df.with_row_count()\n... .with_columns([\n... pl.col(\"row_nr\").first()\n... .over(col)\n... .rank(method=\"dense\")\n... .alias(col) - 1\n... for col in df.columns\n... ])\n... .drop(\"row_nr\")\n... )\nshape: (3, 2)\n┌─────┬─────┐\n│ a ┆ b │\n│ --- ┆ --- │\n│ u32 ┆ u32 │\n╞═════╪═════╡\n│ 0 ┆ 0 │\n├╌╌╌╌╌┼╌╌╌╌╌┤\n│ 1 ┆ 1 │\n├╌╌╌╌╌┼╌╌╌╌╌┤\n│ 2 ┆ 0 │\n└─────┴─────┘\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74612246",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6916815/"
] |
74,612,302
|
<p>I'm having trouble with the code below. The attacker is doing two rounds before reversing the turn, and the correct thing is to have a round of attack and alternate. Another detail is that the 'for' doesn't seem to be working... it gets information on how much dice the player has, but for some reason, the 'print' I put doesn't return 2 values (for example, for a player with two dice). I believe there is a lot to improve, creating more functions, but I am a beginner.</p>
<p><strong>AutoLoad</strong>:</p>
<pre><code>extends Node2D
var enemy_turn : bool = false
var critical_Hit : bool = false
func _start_combat(player, enemy):
if enemy_turn == false:
turn(enemy, player)
else:
turn(player, enemy)
func roll(dice) -> int:
var random_number = RandomNumberGenerator.new()
random_number.randomize()
return random_number.randi_range(1, dice)
func turn(target, attacker):
print(attacker.char_name, " attack ", target.char_name)
var iniciative_roll = roll(20)
print("Iniciative d20: ", iniciative_roll)
if iniciative_roll == 20:
print("Critical Hit!") #Tenho que verificar se eu estou saindo daqui sem passar para baixo visto que 20 >= abs()
critical_Hit = true
elif iniciative_roll >= abs(target.ac - attacker.thac0):
critical_Hit = false
else:
print(attacker.char_name, " miss.")
enemy_turn =! enemy_turn
_start_combat(attacker,target)
return
var dmg_roll : int = 0
for n in attacker.row:
dmg_roll += roll(attacker.dice)
print(dmg_roll)
return damage(target, attacker, dmg_roll)
func damage(target, attacker, aux):
if critical_Hit == true:
target.hp -= 2 * aux
else:
target.hp -= aux
print(attacker.char_name, " do ", aux, " damage ", target.char_name)
if target.hp <= 0:
target._death()
else:
enemy_turn =! enemy_turn
_start_combat(attacker,target)
</code></pre>
<p>Taking advantage, can the arguments that a function receives be the same as the variables sent? Is this not very ugly or wrong? Ex:</p>
<pre><code>func turn(target, attacker):
...
return damage(target, attacker, dmg_roll)
func damage(target, attacker, dmg_roll):
...
</code></pre>
<p>Thanks</p>
|
[
{
"answer_id": 74616407,
"author": "Theraot",
"author_id": 402022,
"author_profile": "https://Stackoverflow.com/users/402022",
"pm_score": 2,
"selected": true,
"text": "func _start_combat(player, enemy):\n if enemy_turn == false:\n turn(enemy, player)\n else:\n turn(player, enemy)\n turn enemy_turn turn func turn(target, attacker):\n enemy_turn =! enemy_turn\n_start_combat(attacker,target)\n enemy_turn _start_combat _start_combat enemy_turn damage turn enemy_turn =! enemy_turn\n_start_combat(attacker,target)\n damage turn _start_combat turn turn enemy_turn =! enemy_turn _start_combat _start_combat turn _start_combat turn _start_combat turn _start_combat damamge if target.hp <= 0:\n target._death()\n _start_combat func _start_combat(player, enemy):\n var target\n var attacker\n while true:\n if enemy_turn == false:\n target = enemy\n attacker = player\n else:\n target = player\n attacker = enemy\n\n turn(target, attacker)\n if target.hp <= 0:\n target._death()\n break\n enemy_turn func _start_combat(player, enemy):\n var target\n var attacker\n while true:\n if enemy_turn == false:\n target = enemy\n attacker = player\n else:\n target = player\n attacker = enemy\n\n turn(target, attacker)\n if target.hp <= 0:\n target._death()\n break\n\n enemy_turn =! enemy_turn\n damage func damage(target, attacker, aux):\n if critical_Hit == true:\n target.hp -= 2 * aux\n else:\n target.hp -= aux\n print(attacker.char_name, \" do \", aux, \" damage \", target.char_name)\n turn enemy_turn =! enemy_turn\n_start_combat(attacker,target)\n yield yield for n in attacker.row:\n dmg_roll += roll(attacker.dice)\n print(dmg_roll)\n return damage(target, attacker, dmg_roll)\n damage for n in attacker.row:\n dmg_roll += roll(attacker.dice)\n print(dmg_roll)\n\nreturn damage(target, attacker, dmg_roll)\n damage turn return for n in attacker.row:\n dmg_roll += roll(attacker.dice)\n print(dmg_roll)\n\ndamage(target, attacker, dmg_roll)\n damage for n in attacker.row:\n dmg_roll += roll(attacker.dice)\n print(dmg_roll)\n damage(target, attacker, dmg_roll)\n"
},
{
"answer_id": 74621001,
"author": "Marcelo João",
"author_id": 10434751,
"author_profile": "https://Stackoverflow.com/users/10434751",
"pm_score": 0,
"selected": false,
"text": "extends Node2D\n\nvar enemy_turn : bool = false\nvar critical_Hit : bool = false\n\nfunc _start_combat(player, enemy):\n var target\n var attacker\n while true:\n if enemy_turn == false:\n target = enemy\n attacker = player\n else:\n target = player\n attacker = enemy\n \n turn(target, attacker)\n if target.hp <= 0:\n target._death()\n break\n\nfunc roll(dice) -> int:\n var random_number = RandomNumberGenerator.new()\n random_number.randomize()\n return random_number.randi_range(1, dice)\n\nfunc turn(target, attacker):\n print(attacker.char_name, \" atack \", target.char_name)\n var iniciative_roll = roll(20)\n print(\"Iniciative d20: \", iniciative_roll)\n \n if iniciative_roll == 20:\n print(\"Critical Hit!\") #Tenho que verificar se eu estou saindo daqui sem passar para baixo visto que 20 >= abs()\n critical_Hit = true\n elif iniciative_roll >= abs(target.ac - attacker.thac0):\n critical_Hit = false\n else:\n print(attacker.char_name, \" miss.\")\n return\n \n var dmg_roll : int = 0\n for n in attacker.row:\n dmg_roll += roll(attacker.dice)\n print(dmg_roll)\n \n damage(target, attacker, dmg_roll)\n \nfunc damage(target, attacker, dmg_roll):\n if critical_Hit == true:\n target.hp -= 2 * dmg_roll\n else:\n target.hp -= dmg_roll\n print(attacker.char_name, \" do \", dmg_roll, \" damage \", target.char_name)\n Player made an attack action...\nJobson atack Globin\nIniciative d20: 2\nJobson miss.\nJobson atack Globin\nIniciative d20: 16\n10\nJobson do 10 damage Globin\nJobson atack Globin\nIniciative d20: 5\nJobson miss.\nJobson atack Globin\nIniciative d20: 13\n16\nJobson do 16 damage Globin\nGlobin DIE!\n yield"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74612302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10434751/"
] |
74,612,326
|
<p>I am trying to compare floating point values with each another within one column; I need a function that doesn't produce an error...</p>
<p>The functione should loop through the column and compare each value within the columns previous value and also with the next value and create a new DF with all rows matching conditions.</p>
<p>I tried a combination of for loops and if statements but I couldn't figure out a code not producing errors.</p>
<p><strong>Example:</strong></p>
<p>Condition = True if the value of col1 is high than the previous value of col1 and at the same time lower than the next; all within col1
Condition = True as well if the value of col1 is lower than the previous value of col1 and at the same time higher than the next</p>
<p>The first and last value will produce an error so they should be compared each with a variable called compare_first and compare_last which I will define manually</p>
<pre><code>values = [[5.5, 2.5, 10.0], [2.0, 4.5, 1.0], [2.5, 5.2, 8.0],
[4.5, 5.8, 4.8], [4.6, 6.3, 9.6], [4.1, 6.4, 9.0],
[5.1, 2.3, 11.1]]
# creating a pandas dataframe
a_df = pd.DataFrame(values, columns=['col1', 'col2', 'col3'],
index=['a', 'b', 'c', 'd', 'e', 'f', 'g'])
print(a_df)
</code></pre>
<p>output</p>
<pre><code> col1 col2 col3
a 5.5 2.5 10.0
b 2.0 4.5 1.0
c 2.5 5.2 8.0
d 4.5 5.8 4.8
e 4.6 6.3 9.6
f 4.1 6.4 9.0
g 5.1 2.3 11.1
</code></pre>
<p><strong>desired output - all rows matching the described conditions as a new df</strong></p>
<pre><code> col1 col2 col3
b 2.0 4.5 1.0
e 4.6 6.3 9.6
f 4.1 6.4 9.0
</code></pre>
|
[
{
"answer_id": 74616407,
"author": "Theraot",
"author_id": 402022,
"author_profile": "https://Stackoverflow.com/users/402022",
"pm_score": 2,
"selected": true,
"text": "func _start_combat(player, enemy):\n if enemy_turn == false:\n turn(enemy, player)\n else:\n turn(player, enemy)\n turn enemy_turn turn func turn(target, attacker):\n enemy_turn =! enemy_turn\n_start_combat(attacker,target)\n enemy_turn _start_combat _start_combat enemy_turn damage turn enemy_turn =! enemy_turn\n_start_combat(attacker,target)\n damage turn _start_combat turn turn enemy_turn =! enemy_turn _start_combat _start_combat turn _start_combat turn _start_combat turn _start_combat damamge if target.hp <= 0:\n target._death()\n _start_combat func _start_combat(player, enemy):\n var target\n var attacker\n while true:\n if enemy_turn == false:\n target = enemy\n attacker = player\n else:\n target = player\n attacker = enemy\n\n turn(target, attacker)\n if target.hp <= 0:\n target._death()\n break\n enemy_turn func _start_combat(player, enemy):\n var target\n var attacker\n while true:\n if enemy_turn == false:\n target = enemy\n attacker = player\n else:\n target = player\n attacker = enemy\n\n turn(target, attacker)\n if target.hp <= 0:\n target._death()\n break\n\n enemy_turn =! enemy_turn\n damage func damage(target, attacker, aux):\n if critical_Hit == true:\n target.hp -= 2 * aux\n else:\n target.hp -= aux\n print(attacker.char_name, \" do \", aux, \" damage \", target.char_name)\n turn enemy_turn =! enemy_turn\n_start_combat(attacker,target)\n yield yield for n in attacker.row:\n dmg_roll += roll(attacker.dice)\n print(dmg_roll)\n return damage(target, attacker, dmg_roll)\n damage for n in attacker.row:\n dmg_roll += roll(attacker.dice)\n print(dmg_roll)\n\nreturn damage(target, attacker, dmg_roll)\n damage turn return for n in attacker.row:\n dmg_roll += roll(attacker.dice)\n print(dmg_roll)\n\ndamage(target, attacker, dmg_roll)\n damage for n in attacker.row:\n dmg_roll += roll(attacker.dice)\n print(dmg_roll)\n damage(target, attacker, dmg_roll)\n"
},
{
"answer_id": 74621001,
"author": "Marcelo João",
"author_id": 10434751,
"author_profile": "https://Stackoverflow.com/users/10434751",
"pm_score": 0,
"selected": false,
"text": "extends Node2D\n\nvar enemy_turn : bool = false\nvar critical_Hit : bool = false\n\nfunc _start_combat(player, enemy):\n var target\n var attacker\n while true:\n if enemy_turn == false:\n target = enemy\n attacker = player\n else:\n target = player\n attacker = enemy\n \n turn(target, attacker)\n if target.hp <= 0:\n target._death()\n break\n\nfunc roll(dice) -> int:\n var random_number = RandomNumberGenerator.new()\n random_number.randomize()\n return random_number.randi_range(1, dice)\n\nfunc turn(target, attacker):\n print(attacker.char_name, \" atack \", target.char_name)\n var iniciative_roll = roll(20)\n print(\"Iniciative d20: \", iniciative_roll)\n \n if iniciative_roll == 20:\n print(\"Critical Hit!\") #Tenho que verificar se eu estou saindo daqui sem passar para baixo visto que 20 >= abs()\n critical_Hit = true\n elif iniciative_roll >= abs(target.ac - attacker.thac0):\n critical_Hit = false\n else:\n print(attacker.char_name, \" miss.\")\n return\n \n var dmg_roll : int = 0\n for n in attacker.row:\n dmg_roll += roll(attacker.dice)\n print(dmg_roll)\n \n damage(target, attacker, dmg_roll)\n \nfunc damage(target, attacker, dmg_roll):\n if critical_Hit == true:\n target.hp -= 2 * dmg_roll\n else:\n target.hp -= dmg_roll\n print(attacker.char_name, \" do \", dmg_roll, \" damage \", target.char_name)\n Player made an attack action...\nJobson atack Globin\nIniciative d20: 2\nJobson miss.\nJobson atack Globin\nIniciative d20: 16\n10\nJobson do 10 damage Globin\nJobson atack Globin\nIniciative d20: 5\nJobson miss.\nJobson atack Globin\nIniciative d20: 13\n16\nJobson do 16 damage Globin\nGlobin DIE!\n yield"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74612326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20598346/"
] |
74,612,366
|
<p>In R, I have a dataframe with e.g. 4 variables:</p>
<pre><code>df <- data.frame(
v1=c(1,2,3,4),
v2=c("x","y","z","q"),
v3=c("x","b","c","d"),
v4=c("a","y","c","d"),
v5=c("a","b","z","d"),
v6=c("a","b","c","q")
)
</code></pre>
<p>Suppose I use v2 as reference and I want to know what other columns match the values of v2.</p>
<p>How do I match the values from v3, v4, etc... to v2, in such a way that I know from which column the match came?
The result would look something like:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Var 1</th>
<th>Var 2</th>
<th>match</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>x</td>
<td>v3</td>
</tr>
<tr>
<td>2</td>
<td>y</td>
<td>v4</td>
</tr>
<tr>
<td>3</td>
<td>z</td>
<td>v5</td>
</tr>
<tr>
<td>4</td>
<td>q</td>
<td>v6</td>
</tr>
</tbody>
</table>
</div>
<p>I tried match, %in%, and creating matrices of combinations, however I could not find the solution.</p>
|
[
{
"answer_id": 74616407,
"author": "Theraot",
"author_id": 402022,
"author_profile": "https://Stackoverflow.com/users/402022",
"pm_score": 2,
"selected": true,
"text": "func _start_combat(player, enemy):\n if enemy_turn == false:\n turn(enemy, player)\n else:\n turn(player, enemy)\n turn enemy_turn turn func turn(target, attacker):\n enemy_turn =! enemy_turn\n_start_combat(attacker,target)\n enemy_turn _start_combat _start_combat enemy_turn damage turn enemy_turn =! enemy_turn\n_start_combat(attacker,target)\n damage turn _start_combat turn turn enemy_turn =! enemy_turn _start_combat _start_combat turn _start_combat turn _start_combat turn _start_combat damamge if target.hp <= 0:\n target._death()\n _start_combat func _start_combat(player, enemy):\n var target\n var attacker\n while true:\n if enemy_turn == false:\n target = enemy\n attacker = player\n else:\n target = player\n attacker = enemy\n\n turn(target, attacker)\n if target.hp <= 0:\n target._death()\n break\n enemy_turn func _start_combat(player, enemy):\n var target\n var attacker\n while true:\n if enemy_turn == false:\n target = enemy\n attacker = player\n else:\n target = player\n attacker = enemy\n\n turn(target, attacker)\n if target.hp <= 0:\n target._death()\n break\n\n enemy_turn =! enemy_turn\n damage func damage(target, attacker, aux):\n if critical_Hit == true:\n target.hp -= 2 * aux\n else:\n target.hp -= aux\n print(attacker.char_name, \" do \", aux, \" damage \", target.char_name)\n turn enemy_turn =! enemy_turn\n_start_combat(attacker,target)\n yield yield for n in attacker.row:\n dmg_roll += roll(attacker.dice)\n print(dmg_roll)\n return damage(target, attacker, dmg_roll)\n damage for n in attacker.row:\n dmg_roll += roll(attacker.dice)\n print(dmg_roll)\n\nreturn damage(target, attacker, dmg_roll)\n damage turn return for n in attacker.row:\n dmg_roll += roll(attacker.dice)\n print(dmg_roll)\n\ndamage(target, attacker, dmg_roll)\n damage for n in attacker.row:\n dmg_roll += roll(attacker.dice)\n print(dmg_roll)\n damage(target, attacker, dmg_roll)\n"
},
{
"answer_id": 74621001,
"author": "Marcelo João",
"author_id": 10434751,
"author_profile": "https://Stackoverflow.com/users/10434751",
"pm_score": 0,
"selected": false,
"text": "extends Node2D\n\nvar enemy_turn : bool = false\nvar critical_Hit : bool = false\n\nfunc _start_combat(player, enemy):\n var target\n var attacker\n while true:\n if enemy_turn == false:\n target = enemy\n attacker = player\n else:\n target = player\n attacker = enemy\n \n turn(target, attacker)\n if target.hp <= 0:\n target._death()\n break\n\nfunc roll(dice) -> int:\n var random_number = RandomNumberGenerator.new()\n random_number.randomize()\n return random_number.randi_range(1, dice)\n\nfunc turn(target, attacker):\n print(attacker.char_name, \" atack \", target.char_name)\n var iniciative_roll = roll(20)\n print(\"Iniciative d20: \", iniciative_roll)\n \n if iniciative_roll == 20:\n print(\"Critical Hit!\") #Tenho que verificar se eu estou saindo daqui sem passar para baixo visto que 20 >= abs()\n critical_Hit = true\n elif iniciative_roll >= abs(target.ac - attacker.thac0):\n critical_Hit = false\n else:\n print(attacker.char_name, \" miss.\")\n return\n \n var dmg_roll : int = 0\n for n in attacker.row:\n dmg_roll += roll(attacker.dice)\n print(dmg_roll)\n \n damage(target, attacker, dmg_roll)\n \nfunc damage(target, attacker, dmg_roll):\n if critical_Hit == true:\n target.hp -= 2 * dmg_roll\n else:\n target.hp -= dmg_roll\n print(attacker.char_name, \" do \", dmg_roll, \" damage \", target.char_name)\n Player made an attack action...\nJobson atack Globin\nIniciative d20: 2\nJobson miss.\nJobson atack Globin\nIniciative d20: 16\n10\nJobson do 10 damage Globin\nJobson atack Globin\nIniciative d20: 5\nJobson miss.\nJobson atack Globin\nIniciative d20: 13\n16\nJobson do 16 damage Globin\nGlobin DIE!\n yield"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74612366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20631948/"
] |
74,612,390
|
<p>This is really strange. I have a laravel app where I use the module library</p>
<pre><code>https://github.com/nWidart/laravel-modules
</code></pre>
<p>I don't know if it has with the issue to do, but just want to point it out.</p>
<p>Basically, I am writing phpunit tests. The first test is calling an endpoint. In that case, the controller will call a repository class(basically a php-class inside the folder "Repositories", nothing stranger than that) which in turn calls</p>
<pre><code>Mail::queue(new MyFirstMail($arg));
</code></pre>
<p>Well, this works. And I can also have a chech in the test to verify the mail has been queued:</p>
<pre><code>Mail::assertQueued(MyFirstMail::class, 1);
</code></pre>
<p>The second test, instead, is calling an artisan command, this way:</p>
<pre><code>$this->artisan('a_command_job');
</code></pre>
<p>This will basically run the method "handle" inside a class that is located at "Modules/Console/Commands/MyCommand.php"</p>
<p>From inside that handle method, I will call this:</p>
<pre><code>Mail::queue(new MySecondMail($arg));
</code></pre>
<p>This test fails. The error is</p>
<pre><code>View [emails.second_email] not found
</code></pre>
<p>MySecondMail.php is a class that extends "BaseMail". Which is the same for MyFirstMail.php.
They look more or less exactly the same. Of course they include two different views.
MyFirstMail has no problem in including the view. While MySecondMail cannot find the view.
I also tried by passing the same view name for MySecondMail. But I still get the same error.</p>
<p>I suspect that this has to do with the fact that the first one is triggered by a call to an endpoint. While the second one is called by an artisan command. But I really don't understand how to make MySecondMail to pick up the right path to the view. I also have tried with "base_path". But it did not work and Im not sure it is the right way to do it.</p>
|
[
{
"answer_id": 74616407,
"author": "Theraot",
"author_id": 402022,
"author_profile": "https://Stackoverflow.com/users/402022",
"pm_score": 2,
"selected": true,
"text": "func _start_combat(player, enemy):\n if enemy_turn == false:\n turn(enemy, player)\n else:\n turn(player, enemy)\n turn enemy_turn turn func turn(target, attacker):\n enemy_turn =! enemy_turn\n_start_combat(attacker,target)\n enemy_turn _start_combat _start_combat enemy_turn damage turn enemy_turn =! enemy_turn\n_start_combat(attacker,target)\n damage turn _start_combat turn turn enemy_turn =! enemy_turn _start_combat _start_combat turn _start_combat turn _start_combat turn _start_combat damamge if target.hp <= 0:\n target._death()\n _start_combat func _start_combat(player, enemy):\n var target\n var attacker\n while true:\n if enemy_turn == false:\n target = enemy\n attacker = player\n else:\n target = player\n attacker = enemy\n\n turn(target, attacker)\n if target.hp <= 0:\n target._death()\n break\n enemy_turn func _start_combat(player, enemy):\n var target\n var attacker\n while true:\n if enemy_turn == false:\n target = enemy\n attacker = player\n else:\n target = player\n attacker = enemy\n\n turn(target, attacker)\n if target.hp <= 0:\n target._death()\n break\n\n enemy_turn =! enemy_turn\n damage func damage(target, attacker, aux):\n if critical_Hit == true:\n target.hp -= 2 * aux\n else:\n target.hp -= aux\n print(attacker.char_name, \" do \", aux, \" damage \", target.char_name)\n turn enemy_turn =! enemy_turn\n_start_combat(attacker,target)\n yield yield for n in attacker.row:\n dmg_roll += roll(attacker.dice)\n print(dmg_roll)\n return damage(target, attacker, dmg_roll)\n damage for n in attacker.row:\n dmg_roll += roll(attacker.dice)\n print(dmg_roll)\n\nreturn damage(target, attacker, dmg_roll)\n damage turn return for n in attacker.row:\n dmg_roll += roll(attacker.dice)\n print(dmg_roll)\n\ndamage(target, attacker, dmg_roll)\n damage for n in attacker.row:\n dmg_roll += roll(attacker.dice)\n print(dmg_roll)\n damage(target, attacker, dmg_roll)\n"
},
{
"answer_id": 74621001,
"author": "Marcelo João",
"author_id": 10434751,
"author_profile": "https://Stackoverflow.com/users/10434751",
"pm_score": 0,
"selected": false,
"text": "extends Node2D\n\nvar enemy_turn : bool = false\nvar critical_Hit : bool = false\n\nfunc _start_combat(player, enemy):\n var target\n var attacker\n while true:\n if enemy_turn == false:\n target = enemy\n attacker = player\n else:\n target = player\n attacker = enemy\n \n turn(target, attacker)\n if target.hp <= 0:\n target._death()\n break\n\nfunc roll(dice) -> int:\n var random_number = RandomNumberGenerator.new()\n random_number.randomize()\n return random_number.randi_range(1, dice)\n\nfunc turn(target, attacker):\n print(attacker.char_name, \" atack \", target.char_name)\n var iniciative_roll = roll(20)\n print(\"Iniciative d20: \", iniciative_roll)\n \n if iniciative_roll == 20:\n print(\"Critical Hit!\") #Tenho que verificar se eu estou saindo daqui sem passar para baixo visto que 20 >= abs()\n critical_Hit = true\n elif iniciative_roll >= abs(target.ac - attacker.thac0):\n critical_Hit = false\n else:\n print(attacker.char_name, \" miss.\")\n return\n \n var dmg_roll : int = 0\n for n in attacker.row:\n dmg_roll += roll(attacker.dice)\n print(dmg_roll)\n \n damage(target, attacker, dmg_roll)\n \nfunc damage(target, attacker, dmg_roll):\n if critical_Hit == true:\n target.hp -= 2 * dmg_roll\n else:\n target.hp -= dmg_roll\n print(attacker.char_name, \" do \", dmg_roll, \" damage \", target.char_name)\n Player made an attack action...\nJobson atack Globin\nIniciative d20: 2\nJobson miss.\nJobson atack Globin\nIniciative d20: 16\n10\nJobson do 10 damage Globin\nJobson atack Globin\nIniciative d20: 5\nJobson miss.\nJobson atack Globin\nIniciative d20: 13\n16\nJobson do 16 damage Globin\nGlobin DIE!\n yield"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74612390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5668102/"
] |
74,612,409
|
<p>I like to parse string array and update value, what i have for example:</p>
<pre><code>list= ["beam=0", "active=0", "rate=11", "version=4.1", "delay=5"]
</code></pre>
<p>in the above list i want to search for "active" and edit its value, like if "active=0" i want to make it "active=1" , and if its "active=1" i want to make it "active=0".</p>
<pre><code>What i am doing is , but its not correct ,, can someone assist in this:
list.each do |lists|
if lists.include?("active=0")
lists = "active=1"
elsif list.include?("active=1")
lists = "active=0"
end
end
</code></pre>
<p>what i expect in the end if list contains active=0 , than output list = ["beam=0", "active=1", "rate=11", "version=4.1", "delay=5"] and if list contains active=1, then output list = ["beam=0", "active=0", "rate=11", "version=4.1", "delay=5"]</p>
|
[
{
"answer_id": 74612556,
"author": "DannyB",
"author_id": 413924,
"author_profile": "https://Stackoverflow.com/users/413924",
"pm_score": 2,
"selected": true,
"text": "#each list = [\"beam=0\", \"active=0\", \"rate=11\", \"version=4.1\", \"delay=5\"]\n\n# convert to hash\nhash = list.to_h { |x| x.split '=' }\n\n# update any hash value\nhash['active'] = hash['active'] == '0' ? '1' : '0'\n\n# convert back to array\nresult = hash.map { |x| x.join '=' }\n list = [\"beam=0\", \"active=0\", \"rate=11\", \"version=4.1\", \"delay=5\"]\nresult = list.map do |item|\n case item\n when 'active=0' then 'active=1'\n when 'active=1' then 'active=0'\n else\n item\n end\nend\n"
},
{
"answer_id": 74613298,
"author": "Sachin Singh",
"author_id": 13088705,
"author_profile": "https://Stackoverflow.com/users/13088705",
"pm_score": 0,
"selected": false,
"text": "list active= list= [\"beam=0\", \"active=0\", \"rate=11\", \"version=4.1\", \"delay=5\"]\n\nlist.each_with_index do |item, index|\n next unless item.starts_with?('active')\n\n number_with_active = item.split('active=')[1].to_i\n list[index] = \"active=#{(number_with_active+1)%2}\"\nend\n"
},
{
"answer_id": 74617951,
"author": "Michael B",
"author_id": 16452228,
"author_profile": "https://Stackoverflow.com/users/16452228",
"pm_score": 0,
"selected": false,
"text": "each map nil list= [\"beam=0\", \"active=0\", \"rate=11\", \"version=4.1\", \"delay=5\"]\n\nlist.map do |lists|\n if lists.include?(\"active=0\")\n lists = \"active=1\"\n elsif list.include?(\"active=1\")\n lists = \"active=0\"\n else\n lists\n end\nend\n\n#=> [\"beam=0\", \"active=1\", \"rate=11\", \"version=4.1\", \"delay=5\"]\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74612409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20260134/"
] |
74,612,434
|
<p>I'm trying to apply a function row-by-row which takes 5 inputs, 3 of which are lists. I want these lists to come from each row of 3 correspondings dataframes.</p>
<p>I've tried using 'apply' and 'lambda' as follows:</p>
<pre><code>sol['tf_dd']=sol.apply(lambda tsol, rfsol, rbsol:
taurho_difdif(xy=xy,
l=l,
t=tsol,
rf=rfsol,
rb=rbsol),
axis=1)
</code></pre>
<p>However I get the error <code><lambda>() missing 2 required positional arguments: 'rfsol' and 'rbsol'</code></p>
<p>The DataFrame <code>sol</code> and the DataFrames <code>tsol</code>, <code>rfsol</code> and <code>rbsol</code> all have the same length. For each row, I want the entire row from <code>tsol</code>, <code>rfsol</code> and <code>rbsol</code> to be input as three lists.</p>
<p>Here is much simplified example (first with single lists, which I then want to replicate row by row with dataframes):</p>
<p>The output with single lists is a single value (120). With dataframes as inputs I want an output dataframe of length 10 where all values are 120.</p>
<pre><code>t=[1,2,3,4,5]
rf=[6,7,8,9,10]
rb=[11,12,13,14,15]
def simple_func(t, rf, rb):
x=sum(t)
y=sum(rf)
z=sum(rb)
return x+y+z
out=simple_func(t,rf,rb)
# dataframe rows as lists
tsol=pd.DataFrame((t,t,t,t,t,t,t,t,t,t))
rfsol=pd.DataFrame((rf,rf,rf,rf,rf,rf,rf,rf,rf,rf))
rbsol=pd.DataFrame((rb,rb,rb,rb,rb,rb,rb,rb,rb,rb))
out2 = pd.DataFrame(index=range(len(tsol)), columns=['output'])
out2['output'] = out2.apply(lambda tsol, rfsol, rbsol:
simple_func(t=tsol.tolist(),
rf=rfsol.tolist(),
rb=rbsol.tolist()),
axis=1)
</code></pre>
|
[
{
"answer_id": 74612753,
"author": "OuterSoda",
"author_id": 19922257,
"author_profile": "https://Stackoverflow.com/users/19922257",
"pm_score": 0,
"selected": false,
"text": "df.apply() axis=1 out2['output'] = out2.apply(lambda row:\n simple_func(t=row[\"tsol\"],\n rf=row[\"rfsol\"],\n rb=row[\"rbsol\"]),\n axis=1)\n"
},
{
"answer_id": 74613110,
"author": "AntonioRB",
"author_id": 3645050,
"author_profile": "https://Stackoverflow.com/users/3645050",
"pm_score": 3,
"selected": true,
"text": "import pandas as pd\nimport numpy as np\n\n\ndef postional_sum(inot, df1, df2, df3):\n \"\"\"\n Get input index and gather the same position for the other DataFrame collection\n \"\"\"\n\n position = inot.name\n\n x = df1.iloc[position].sum()\n y = df2.iloc[position].sum()\n z = df3.iloc[position].sum()\n return x + y + z\n\n\n# dataframe rows as lists\ntsol = pd.DataFrame(np.random.randn(10, 5), columns=range(5))\nrfsol = pd.DataFrame(np.random.randn(10, 5), columns=range(5))\nrbsol = pd.DataFrame(np.random.randn(10, 5), columns=range(5))\n\nout2 = pd.DataFrame(index=range(len(tsol)), columns=[\"output\"])\n\nout2[\"output\"] = out2.apply(lambda x: postional_sum(x, tsol, rfsol, rbsol), axis=1)\n\nout2\n"
},
{
"answer_id": 74613322,
"author": "ScottC",
"author_id": 20174226,
"author_profile": "https://Stackoverflow.com/users/20174226",
"pm_score": 0,
"selected": false,
"text": "out2[\"output\"] = tsol.sum(axis=1) + rfsol.sum(axis=1) + rbsol.sum(axis=1)\n t=[1,2,3,4,5]\nrf=[6,7,8,9,10]\nrb=[11,12,13,14,15]\n\n# dataframe rows as lists\ntsol=pd.DataFrame((t,t,t,t,t,t,t,t,t,t))\nrfsol=pd.DataFrame((rf,rf,rf,rf,rf,rf,rf,rf,rf,rf))\nrbsol=pd.DataFrame((rb,rb,rb,rb,rb,rb,rb,rb,rb,rb))\n\nout2 = pd.DataFrame(index=range(len(tsol)), columns=[\"output\"])\nout2[\"output\"] = tsol.sum(axis=1) + rfsol.sum(axis=1) + rbsol.sum(axis=1)\n\nprint(out2)\n output\n0 120\n1 120\n2 120\n3 120\n4 120\n5 120\n6 120\n7 120\n8 120\n9 120\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74612434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19357142/"
] |
74,612,457
|
<p>good morning, sorry first of all for my english. I'm trying to do a double loop to iterate through two strings, the thing is, I want the ocrString to start one position later each time, so that it can iterate through the string in order to see if there are any matches. That is, I want to find the matches without necessarily being equal in length and without being able to order it.</p>
<pre class="lang-js prettyprint-override"><code>let ocrString = "casaidespcasa";
let pattern = "idesp";
let conteo = 0;
checkIDESP(ocrString, pattern);
function checkIDESP(ocrString, pattern) {
let ocrStringSeparado = ocrString.split("");
let patternSeparado = pattern.split("");
for (i = 0; i < ocrStringSeparado.length; i++) {
for (x = 0; x < patternSeparado.length; x++) {
console.log(ocrStringSeparado[i], pattern[x]);
if (ocrStringSeparado[i] == pattern[x]) {
conteo++;
}
}
}
if (conteo <= 3) {
console.log(conteo, "No sé si es un dni");
} else {
console.log(conteo, "es un dni");
}
}
</code></pre>
<p>Some way to go through the position of an array so that it first starts with 'Casaidespcasa' and then 'Asaidespcasa' etc.</p>
|
[
{
"answer_id": 74612753,
"author": "OuterSoda",
"author_id": 19922257,
"author_profile": "https://Stackoverflow.com/users/19922257",
"pm_score": 0,
"selected": false,
"text": "df.apply() axis=1 out2['output'] = out2.apply(lambda row:\n simple_func(t=row[\"tsol\"],\n rf=row[\"rfsol\"],\n rb=row[\"rbsol\"]),\n axis=1)\n"
},
{
"answer_id": 74613110,
"author": "AntonioRB",
"author_id": 3645050,
"author_profile": "https://Stackoverflow.com/users/3645050",
"pm_score": 3,
"selected": true,
"text": "import pandas as pd\nimport numpy as np\n\n\ndef postional_sum(inot, df1, df2, df3):\n \"\"\"\n Get input index and gather the same position for the other DataFrame collection\n \"\"\"\n\n position = inot.name\n\n x = df1.iloc[position].sum()\n y = df2.iloc[position].sum()\n z = df3.iloc[position].sum()\n return x + y + z\n\n\n# dataframe rows as lists\ntsol = pd.DataFrame(np.random.randn(10, 5), columns=range(5))\nrfsol = pd.DataFrame(np.random.randn(10, 5), columns=range(5))\nrbsol = pd.DataFrame(np.random.randn(10, 5), columns=range(5))\n\nout2 = pd.DataFrame(index=range(len(tsol)), columns=[\"output\"])\n\nout2[\"output\"] = out2.apply(lambda x: postional_sum(x, tsol, rfsol, rbsol), axis=1)\n\nout2\n"
},
{
"answer_id": 74613322,
"author": "ScottC",
"author_id": 20174226,
"author_profile": "https://Stackoverflow.com/users/20174226",
"pm_score": 0,
"selected": false,
"text": "out2[\"output\"] = tsol.sum(axis=1) + rfsol.sum(axis=1) + rbsol.sum(axis=1)\n t=[1,2,3,4,5]\nrf=[6,7,8,9,10]\nrb=[11,12,13,14,15]\n\n# dataframe rows as lists\ntsol=pd.DataFrame((t,t,t,t,t,t,t,t,t,t))\nrfsol=pd.DataFrame((rf,rf,rf,rf,rf,rf,rf,rf,rf,rf))\nrbsol=pd.DataFrame((rb,rb,rb,rb,rb,rb,rb,rb,rb,rb))\n\nout2 = pd.DataFrame(index=range(len(tsol)), columns=[\"output\"])\nout2[\"output\"] = tsol.sum(axis=1) + rfsol.sum(axis=1) + rbsol.sum(axis=1)\n\nprint(out2)\n output\n0 120\n1 120\n2 120\n3 120\n4 120\n5 120\n6 120\n7 120\n8 120\n9 120\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74612457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20183325/"
] |
74,612,461
|
<p>I am planning to use Azure DevOps for agile project management. I was trying out Jira / Confluence earlier. I do understand confluence is good for document management etc. In Azure DevOps, I understand there is Wiki for content management. I want to link all of my requirements, technical and other documentation currently existing as MS Word documents into ADO Wiki. I am unable to do that though - ADO Wiki allows a link of an object within ADO, but how do I get my word and other docs into ADO in the first place, and where do I put them - is there a general repository? Thanks</p>
<p>I am trying to find out how to link my external documents to ADO Wiki.</p>
|
[
{
"answer_id": 74612753,
"author": "OuterSoda",
"author_id": 19922257,
"author_profile": "https://Stackoverflow.com/users/19922257",
"pm_score": 0,
"selected": false,
"text": "df.apply() axis=1 out2['output'] = out2.apply(lambda row:\n simple_func(t=row[\"tsol\"],\n rf=row[\"rfsol\"],\n rb=row[\"rbsol\"]),\n axis=1)\n"
},
{
"answer_id": 74613110,
"author": "AntonioRB",
"author_id": 3645050,
"author_profile": "https://Stackoverflow.com/users/3645050",
"pm_score": 3,
"selected": true,
"text": "import pandas as pd\nimport numpy as np\n\n\ndef postional_sum(inot, df1, df2, df3):\n \"\"\"\n Get input index and gather the same position for the other DataFrame collection\n \"\"\"\n\n position = inot.name\n\n x = df1.iloc[position].sum()\n y = df2.iloc[position].sum()\n z = df3.iloc[position].sum()\n return x + y + z\n\n\n# dataframe rows as lists\ntsol = pd.DataFrame(np.random.randn(10, 5), columns=range(5))\nrfsol = pd.DataFrame(np.random.randn(10, 5), columns=range(5))\nrbsol = pd.DataFrame(np.random.randn(10, 5), columns=range(5))\n\nout2 = pd.DataFrame(index=range(len(tsol)), columns=[\"output\"])\n\nout2[\"output\"] = out2.apply(lambda x: postional_sum(x, tsol, rfsol, rbsol), axis=1)\n\nout2\n"
},
{
"answer_id": 74613322,
"author": "ScottC",
"author_id": 20174226,
"author_profile": "https://Stackoverflow.com/users/20174226",
"pm_score": 0,
"selected": false,
"text": "out2[\"output\"] = tsol.sum(axis=1) + rfsol.sum(axis=1) + rbsol.sum(axis=1)\n t=[1,2,3,4,5]\nrf=[6,7,8,9,10]\nrb=[11,12,13,14,15]\n\n# dataframe rows as lists\ntsol=pd.DataFrame((t,t,t,t,t,t,t,t,t,t))\nrfsol=pd.DataFrame((rf,rf,rf,rf,rf,rf,rf,rf,rf,rf))\nrbsol=pd.DataFrame((rb,rb,rb,rb,rb,rb,rb,rb,rb,rb))\n\nout2 = pd.DataFrame(index=range(len(tsol)), columns=[\"output\"])\nout2[\"output\"] = tsol.sum(axis=1) + rfsol.sum(axis=1) + rbsol.sum(axis=1)\n\nprint(out2)\n output\n0 120\n1 120\n2 120\n3 120\n4 120\n5 120\n6 120\n7 120\n8 120\n9 120\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74612461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20632137/"
] |
74,612,488
|
<p>I have a small server shop that doesn't really need a database, so I decided to use a json file instead
The json file have multiple objects.</p>
<pre><code>{
"Windows": [
{
"Entry": {
"Price": "900",
"Cores": "2 vCPU",
"RAM": "4GB vRAM",
"Disk": "128GB Disk",
"OS": "Windows Server"
},
"Medium": {
"Price": "1400",
"Cores": "4 vCPU",
"RAM": "8GB vRAM",
"Disk": "512GB Disk",
"OS": "Windows Server"
},
"High": {
"Price": "2000",
"Cores": "8 vCPU",
"RAM": "16GB vRAM",
"Disk": "1TB Disk",
"OS": "Windows Server"
}
}
],
"Linux": [
{
"Entry": {
"Price": "700",
"Cores": "2 vCPU",
"RAM": "4GB vRAM",
"Disk": "128GB Disk",
"OS": "Linux"
},
"Medium": {
"Price": "1200",
"Cores": "4 vCPU",
"RAM": "8GB vRAM",
"Disk": "512GB Disk",
"OS": "Linux"
},
"High": {
"Price": "1800",
"Cores": "8 vCPU",
"RAM": "16GB vRAM",
"Disk": "1TB Disk",
"OS": "Linux"
}
}
]
}
</code></pre>
<p>I want to break the objects in its individual parts to use it in a page where I can enumerate through the values, below is my approach to get the name of a property and its values</p>
<pre><code>public Dictionary<string, object> GetServers()
{
using (var file = new StreamReader(*file directory*))
{
//Deserialize the file file into the RootObject
var json = file.ReadToEnd();
var obj = JsonSerializer.Deserialize<Rootobject>(json);
//Read each object of the json file into a dictionary with the object key and the preceding values which is another object.
Type type = obj.GetType();
PropertyInfo[] properties = type.GetProperties();
var servers = new Dictionary<string, object>();
foreach (var property in properties)
{
servers.Add(property.Name, property.GetValue(obj));
}
return servers;
}
}
</code></pre>
<p>Here is the root object</p>
<pre><code>public class Rootobject
{
public Window[] Windows { get; set; }
public Linux[] Linux { get; set; }
}
public class Window
{
public Entry Entry { get; set; }
public Medium Medium { get; set; }
public High High { get; set; }
}
public class Entry
{
public string Price { get; set; }
public string Cores { get; set; }
public string RAM { get; set; }
public string Disk { get; set; }
public string OS { get; set; }
}
public class Medium
{
public string Price { get; set; }
public string Cores { get; set; }
public string RAM { get; set; }
public string Disk { get; set; }
public string OS { get; set; }
}
public class High
{
public string Price { get; set; }
public string Cores { get; set; }
public string RAM { get; set; }
public string Disk { get; set; }
public string OS { get; set; }
}
public class Linux
{
public Entry1 Entry { get; set; }
public Medium1 Medium { get; set; }
public High1 High { get; set; }
}
public class Entry1
{
public string Price { get; set; }
public string Cores { get; set; }
public string RAM { get; set; }
public string Disk { get; set; }
public string OS { get; set; }
}
public class Medium1
{
public string Price { get; set; }
public string Cores { get; set; }
public string RAM { get; set; }
public string Disk { get; set; }
public string OS { get; set; }
}
public class High1
{
public string Price { get; set; }
public string Cores { get; set; }
public string RAM { get; set; }
public string Disk { get; set; }
public string OS { get; set; }
}
</code></pre>
<p>I want to enumerate through the windows server and split the objects.</p>
<p>So lets say I create a Page consisting of the servers that I offer
I want to enumerate through all the windows as well as the linux servers</p>
<p>Example of entry level server</p>
<pre><code>foreach(var server in Root)
{
<div class="item">
<div>
<div class="card">
<div class="card-header">
//Server Type (Windows or Linux)
<h4 class="p-2 m-0 text-center">@server.Key</h4>
</div>
<div class="card-body p-3" id="card1">
//Server details
<h3 class="fw-bold text-center my-3">@server.Value.Price</h3>
<p id="cores">@server.Value.Cores</p>
<p id="ram">@server.Value.RAM</p>
<p id="disk">@server.Value.Disk</p>
<p id="os"><i class="fa-brands fa-linux me-3 fa-xl"></i>@server.Value.OS</p>
</div>
<button class="btn btn-blue m-3">
View
</button>
</div>
</div>
</div>
}
</code></pre>
<p>An example of 1 card</p>
<p><a href="https://i.stack.imgur.com/KMhxW.png" rel="nofollow noreferrer">Card one example</a></p>
<p>But no matter what I do, I cant seem to find a solution of what I want
Any help will be greatly appreciated</p>
|
[
{
"answer_id": 74612753,
"author": "OuterSoda",
"author_id": 19922257,
"author_profile": "https://Stackoverflow.com/users/19922257",
"pm_score": 0,
"selected": false,
"text": "df.apply() axis=1 out2['output'] = out2.apply(lambda row:\n simple_func(t=row[\"tsol\"],\n rf=row[\"rfsol\"],\n rb=row[\"rbsol\"]),\n axis=1)\n"
},
{
"answer_id": 74613110,
"author": "AntonioRB",
"author_id": 3645050,
"author_profile": "https://Stackoverflow.com/users/3645050",
"pm_score": 3,
"selected": true,
"text": "import pandas as pd\nimport numpy as np\n\n\ndef postional_sum(inot, df1, df2, df3):\n \"\"\"\n Get input index and gather the same position for the other DataFrame collection\n \"\"\"\n\n position = inot.name\n\n x = df1.iloc[position].sum()\n y = df2.iloc[position].sum()\n z = df3.iloc[position].sum()\n return x + y + z\n\n\n# dataframe rows as lists\ntsol = pd.DataFrame(np.random.randn(10, 5), columns=range(5))\nrfsol = pd.DataFrame(np.random.randn(10, 5), columns=range(5))\nrbsol = pd.DataFrame(np.random.randn(10, 5), columns=range(5))\n\nout2 = pd.DataFrame(index=range(len(tsol)), columns=[\"output\"])\n\nout2[\"output\"] = out2.apply(lambda x: postional_sum(x, tsol, rfsol, rbsol), axis=1)\n\nout2\n"
},
{
"answer_id": 74613322,
"author": "ScottC",
"author_id": 20174226,
"author_profile": "https://Stackoverflow.com/users/20174226",
"pm_score": 0,
"selected": false,
"text": "out2[\"output\"] = tsol.sum(axis=1) + rfsol.sum(axis=1) + rbsol.sum(axis=1)\n t=[1,2,3,4,5]\nrf=[6,7,8,9,10]\nrb=[11,12,13,14,15]\n\n# dataframe rows as lists\ntsol=pd.DataFrame((t,t,t,t,t,t,t,t,t,t))\nrfsol=pd.DataFrame((rf,rf,rf,rf,rf,rf,rf,rf,rf,rf))\nrbsol=pd.DataFrame((rb,rb,rb,rb,rb,rb,rb,rb,rb,rb))\n\nout2 = pd.DataFrame(index=range(len(tsol)), columns=[\"output\"])\nout2[\"output\"] = tsol.sum(axis=1) + rfsol.sum(axis=1) + rbsol.sum(axis=1)\n\nprint(out2)\n output\n0 120\n1 120\n2 120\n3 120\n4 120\n5 120\n6 120\n7 120\n8 120\n9 120\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74612488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15505603/"
] |
74,612,521
|
<p>I must Update Oracle database with remove part of string, problem is that this part can be in multiple place in this string. Example:</p>
<p>I must remove part and Update database where clolumn_name like ('%,aaa%') from</p>
<p>'bbb,aaa,ccc,ddd' or 'bbb,ccc,aaa,ddd' or from 'bbb,ccc,eee,fff,aaa,ddd'</p>
<p>Please help me :)</p>
|
[
{
"answer_id": 74612753,
"author": "OuterSoda",
"author_id": 19922257,
"author_profile": "https://Stackoverflow.com/users/19922257",
"pm_score": 0,
"selected": false,
"text": "df.apply() axis=1 out2['output'] = out2.apply(lambda row:\n simple_func(t=row[\"tsol\"],\n rf=row[\"rfsol\"],\n rb=row[\"rbsol\"]),\n axis=1)\n"
},
{
"answer_id": 74613110,
"author": "AntonioRB",
"author_id": 3645050,
"author_profile": "https://Stackoverflow.com/users/3645050",
"pm_score": 3,
"selected": true,
"text": "import pandas as pd\nimport numpy as np\n\n\ndef postional_sum(inot, df1, df2, df3):\n \"\"\"\n Get input index and gather the same position for the other DataFrame collection\n \"\"\"\n\n position = inot.name\n\n x = df1.iloc[position].sum()\n y = df2.iloc[position].sum()\n z = df3.iloc[position].sum()\n return x + y + z\n\n\n# dataframe rows as lists\ntsol = pd.DataFrame(np.random.randn(10, 5), columns=range(5))\nrfsol = pd.DataFrame(np.random.randn(10, 5), columns=range(5))\nrbsol = pd.DataFrame(np.random.randn(10, 5), columns=range(5))\n\nout2 = pd.DataFrame(index=range(len(tsol)), columns=[\"output\"])\n\nout2[\"output\"] = out2.apply(lambda x: postional_sum(x, tsol, rfsol, rbsol), axis=1)\n\nout2\n"
},
{
"answer_id": 74613322,
"author": "ScottC",
"author_id": 20174226,
"author_profile": "https://Stackoverflow.com/users/20174226",
"pm_score": 0,
"selected": false,
"text": "out2[\"output\"] = tsol.sum(axis=1) + rfsol.sum(axis=1) + rbsol.sum(axis=1)\n t=[1,2,3,4,5]\nrf=[6,7,8,9,10]\nrb=[11,12,13,14,15]\n\n# dataframe rows as lists\ntsol=pd.DataFrame((t,t,t,t,t,t,t,t,t,t))\nrfsol=pd.DataFrame((rf,rf,rf,rf,rf,rf,rf,rf,rf,rf))\nrbsol=pd.DataFrame((rb,rb,rb,rb,rb,rb,rb,rb,rb,rb))\n\nout2 = pd.DataFrame(index=range(len(tsol)), columns=[\"output\"])\nout2[\"output\"] = tsol.sum(axis=1) + rfsol.sum(axis=1) + rbsol.sum(axis=1)\n\nprint(out2)\n output\n0 120\n1 120\n2 120\n3 120\n4 120\n5 120\n6 120\n7 120\n8 120\n9 120\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74612521",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18201512/"
] |
74,612,525
|
<p>Say I have such Pandas dataframe</p>
<pre><code>df = pd.DataFrame({
'a': [4, 5, 3, 1, 2],
'b': [20, 10, 40, 50, 30],
'c': [25, 20, 5, 15, 10]
})
</code></pre>
<p>so <code>df</code> looks like:</p>
<pre><code>print(df)
a b c
0 4 20 25
1 5 10 20
2 3 40 5
3 1 50 15
4 2 30 10
</code></pre>
<p>And I want to get the column name of the 2nd largest value in each row. Borrowing the answer from Felex Le in this <a href="https://stackoverflow.com/questions/39066260/get-first-and-second-highest-values-in-pandas-columns">thread</a>, I can now get the 2nd largest value by:</p>
<pre><code>def second_largest(l = []):
return (l.nlargest(2).min())
print(df.apply(second_largest, axis = 1))
</code></pre>
<p>which gives me:</p>
<pre><code>0 20
1 10
2 5
3 15
4 10
dtype: int64
</code></pre>
<p>But what I really want is the column names for those values, or to say:</p>
<pre><code>0 b
1 b
2 c
3 c
4 c
</code></pre>
<p><code>Pandas</code> has a function <code>idxmax</code> which can do the job for the largest value:</p>
<pre><code>df.idxmax(axis = 1)
0 c
1 c
2 b
3 b
4 b
dtype: object
</code></pre>
<p>Is there any elegant way to do the same job but for the 2nd largest value?</p>
|
[
{
"answer_id": 74612558,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 3,
"selected": true,
"text": "numpy.argsort df['new'] = df['new'] = df.columns.to_numpy()[np.argsort(df.to_numpy())[:, -2]]\nprint(df)\n a b c new\n0 4 20 25 b\n1 5 10 20 b\n2 3 40 5 c\n3 1 50 15 c\n4 2 30 10 c\n def second_largest(l = []): \n return (l.nlargest(2).idxmin())\n\nprint(df.apply(second_largest, axis = 1))\n"
},
{
"answer_id": 74612643,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": false,
"text": "numpy.argpartition N = 2\ncols = df.columns.to_numpy()\npd.Series(cols[np.argpartition(df.to_numpy().T, -N, axis=0)[-N]], index=df.index)\n out = df.stack().groupby(level=0).apply(lambda s: s.nlargest(2).index[-1][1])\n 0 b\n1 b\n2 c\n3 c\n4 c\ndtype: object\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74612525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6255138/"
] |
74,612,530
|
<p>I have 2 model. And the two models are connected to the ManyToManyField.</p>
<p>models.py</p>
<pre><code>class PostModel(models.Model):
id = models.AutoField(primary_key=True, null=False)
title = models.TextField()
comments = models.ManyToManyField('CommentModel')
class CommentModel(models.Model):
id = models.AutoField(primary_key=True, null=False)
post_id = models.ForeignKey(Post, on_delete=models.CASCADE)
body = models.TextField()
</code></pre>
<p>and serializers.py</p>
<pre><code>class CommentModel_serializer(serializers.ModelSerializer):
class Meta:
model = MainCommentModel
fields = '__all__'
class PostModel_serializer(serializers.ModelSerializer):
comment = MainCommentModel_serializer(many=True, allow_null=True, read_only=True)
class Meta:
model = MainModel
fields = '__all__'
</code></pre>
<p>and views.py</p>
<pre><code>@api_view(['GET'])
def getPost(request, pk):
post = PostModel.objects.filter(id=pk).first()
comment_list = CommentModel.objects.filter(post_id=post.id)
for i in comments_list:
post.comments.add(i)
serializer = PostModel_serializer(post, many=True)
return Response(serializer.data)
</code></pre>
<p>There is an error when I make a request.</p>
<pre><code>'PostModel' object is not iterable
</code></pre>
<p>and The trackback points here.</p>
<pre><code>return Response(serializer.data)
</code></pre>
<p>I tried to modify a lot of code but I can't find solutions.</p>
<p>Please tell me where and how it went wrong.</p>
|
[
{
"answer_id": 74612685,
"author": "Manoj Tolagekar",
"author_id": 17808039,
"author_profile": "https://Stackoverflow.com/users/17808039",
"pm_score": 0,
"selected": false,
"text": "ManyToManyField() comments = models.ManyToManyField('CommentModel') #Here you made mistake. you should not add single quote to CommentModel. I think that's why you got that error\n comments = models.ManyToManyField(CommentModel)\n"
},
{
"answer_id": 74613214,
"author": "Sunderam Dubey",
"author_id": 17562044,
"author_profile": "https://Stackoverflow.com/users/17562044",
"pm_score": 2,
"selected": true,
"text": "many=True PostModel_serializer comment_list comments_list @api_view(['GET'])\ndef getPost(request, pk):\n post = PostModel.objects.filter(id=pk).first()\n comment_list = CommentModel.objects.filter(post_id=post.id)\n for i in comment_list:\n post.comments.add(i)\n serializer = PostModel_serializer(post)\n return Response(serializer.data)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74612530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14075265/"
] |
74,612,555
|
<p>This is weird. I have created login functions so many times but never noticed this thing.
When we provide a username and password in a form and submit it, and it goes to the server-side as a <code>Payload</code> like this, I can see the data in the Chrome DevTools network tab:</p>
<pre><code>csrfmiddlewaretoken:
mHjXdIDo50tfygxZualuxaCBBdKboeK2R89scsxyfUxm22iFsMHY2xKtxC9uQNni
username: testuser
password: 'dummy pass' #same as i typed(no encryption)
</code></pre>
<p>I got this in the case of incorrect creds because the login failed and it wouldn't redirect to the other page.
But then I tried with valid creds and I checked the <code>Preserve log</code> box in the Chrome network tab. Then I checked there and I could still see the exact entered <code>Username</code> and <code>password</code>. At first I thought I might have missed some encryption logic or something.
But then I tried with multiple reputed tech companies' login functionality and I could still see creds in the payload. Isn't this wrong?</p>
<p>It's supposed to be in the encrypted format right?</p>
<p>Models.py</p>
<pre><code>from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
</code></pre>
<p>html</p>
<pre><code><form method="POST" class="needs-validation mb-4" novalidate>
{% csrf_token %}
<div class="form-outline mb-4">
<input type="email" id="txt_email" class="form-control"
placeholder="Username or email address" required />
</div>
<div class="form-outline mb-4">
<input type="password" id="txt_password" class="form-control"
placeholder="Password" required />
</div>
<div class="d-grid gap-2">
<button class="btn btn-primary fa-lg gradient-custom-2 login_btn" type="submit" id="btn_login"><i class="fa fa-sign-in" aria-hidden="true"> </i> Sign in</button>
<div class="alert alert-danger" id="lbl_error" role="alert" style="display: none;">
</div>
</div>
</form>
</code></pre>
<p>login view</p>
<pre><code>def authcheck(request):
try:
if request.method == "POST":
username = request.POST["username"]
password = request.POST["password"]
user = authenticate(username=username, password=password)
if user is not None:
check_is_partner = Profile.objects.filter(user__username=username, is_partner=True).values("password_reset").first()
if check_is_partner and check_is_partner['password_reset'] is True:
return JsonResponse(({'code':0 ,'username':username}), content_type="json")
if check_ip_restricted(user.profile.ip_restriction, request):
return HttpResponse("ok_ipr", content_type="json")
login(request, user)
session = request.session
session["username"] = username
session["userid"] = user.id
session.save()
if check_is_partner:
return HttpResponse("1", content_type="json")
else:
return HttpResponse("ok", content_type="json")
else:
return HttpResponse("nok", content_type="json")
except Exception:
return HttpResponse("error", content_type="json")
</code></pre>
|
[
{
"answer_id": 74648012,
"author": "kimbo",
"author_id": 9638991,
"author_profile": "https://Stackoverflow.com/users/9638991",
"pm_score": 3,
"selected": true,
"text": "tcpdump https http"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74612555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16250404/"
] |
74,612,565
|
<p>I have 2 arrays, one (array1) which needs to be sorted based on its inner key, role, according to another (array2). I have tried different solutions but cannot progress any further since i don't understand what steps i should take</p>
<p>I have the following output: Array1</p>
<pre><code>{
"id":12,
"roles":[
{
"id":12,
"role":"team_player",
"sub_role":null,
"team_meta":{
"default_player_role":{
"pos":null,
"role":"LWB"
}
}
}
],
"user_email":"w@w.w"
},
{
"id":1575,
"roles":[
{
"id":1672,
"role":"team_player",
"sub_role":null,
"team_meta":{
"default_player_role":{
"pos":null,
"role":"LB"
}
}
}
],
"user_email":"j@j.s"
},
{
"id":1576,
"roles":[
{
"id":1673,
"role":"team_player",
"sub_role":null,
"team_meta":{
"default_player_role":{
"pos":null,
"role":"CAM"
}
}
}
],
"user_email":"E@E.E",
},
</code></pre>
<p>And i want to order the array above according to the order of this:</p>
<pre><code>const array2 = ["LWB", "LB", "CAM"]
</code></pre>
<p>The issue i'm having is that the given key that the sorting should be according to in array1 is too deep, and I haven't found any way to map the "role" from the first array with the array2.</p>
|
[
{
"answer_id": 74612656,
"author": "Nina Scholz",
"author_id": 1447675,
"author_profile": "https://Stackoverflow.com/users/1447675",
"pm_score": 2,
"selected": true,
"text": "role const\n getRole = ({ roles: [{ team_meta: { default_player_role: { role } }}] }) => role,\n data = [{ id: 1576, roles: [{ id: 1673, role: \"team_player\", sub_role: null, team_meta: { default_player_role: { pos: null, role: \"CAM\" } } }], user_email: \"E@E.E\" }, { id: 12, roles: [{ id: 12, role: \"team_player\", sub_role: null, team_meta: { default_player_role: { pos: null, role: \"LWB\" } } }], user_email: \"w@w.w\" }, { id: 1575, roles: [{ id: 1672, role: \"team_player\", sub_role: null, team_meta: { default_player_role: { pos: null, role: \"LB\" } } }], user_email: \"j@j.s\" }],\n order = [\"LWB\", \"LB\", \"CAM\"];\n\ndata.sort((a, b) => order.indexOf(getRole(a)) - order.indexOf(getRole(b)));\n\nconsole.log(data); .as-console-wrapper { max-height: 100% !important; top: 0; }"
},
{
"answer_id": 74612767,
"author": "birim",
"author_id": 18724350,
"author_profile": "https://Stackoverflow.com/users/18724350",
"pm_score": 0,
"selected": false,
"text": "const nestedArray = [...]; // Replace Array \nconst sortByArray = [\"LWB\", \"LB\", \"CAM\"];\nconst sortedArray = [];\n\nsortByArray.forEach(function(sortByArrayValue) {\n nestedArray.forEach(function(nestedArrayValue) {\n nestedArrayValue.roles.forEach(function(role) {\n if (role.team_meta.default_player_role.role === sortByArrayValue) {\n sortedArray.push(nestedArrayValue);\n }\n });\n });\n});\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74612565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20149941/"
] |
74,612,576
|
<p><a href="https://i.stack.imgur.com/xdORY.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xdORY.jpg" alt="output image" /></a>
Above hyperlink is the output image.</p>
<p>Hi All,</p>
<p>I want to convert the whole output in a single line result in powershell.Below is my code,</p>
<pre><code>$containername = "testoutput"
$storageAccKey = (Get-AzStorageAccountKey -ResourceGroupName
$rgname -AccountName $storageAccountName)[0].value
$storagecontext = New-AzStorageContext -StorageAccountName $storageAccountName -StorageAccountKey $storageAccKey
New-AzStorageContainer -Name $containername -Context $storagecontext -Permission Off
Write-Output "Container $($containername) created"
</code></pre>
|
[
{
"answer_id": 74612656,
"author": "Nina Scholz",
"author_id": 1447675,
"author_profile": "https://Stackoverflow.com/users/1447675",
"pm_score": 2,
"selected": true,
"text": "role const\n getRole = ({ roles: [{ team_meta: { default_player_role: { role } }}] }) => role,\n data = [{ id: 1576, roles: [{ id: 1673, role: \"team_player\", sub_role: null, team_meta: { default_player_role: { pos: null, role: \"CAM\" } } }], user_email: \"E@E.E\" }, { id: 12, roles: [{ id: 12, role: \"team_player\", sub_role: null, team_meta: { default_player_role: { pos: null, role: \"LWB\" } } }], user_email: \"w@w.w\" }, { id: 1575, roles: [{ id: 1672, role: \"team_player\", sub_role: null, team_meta: { default_player_role: { pos: null, role: \"LB\" } } }], user_email: \"j@j.s\" }],\n order = [\"LWB\", \"LB\", \"CAM\"];\n\ndata.sort((a, b) => order.indexOf(getRole(a)) - order.indexOf(getRole(b)));\n\nconsole.log(data); .as-console-wrapper { max-height: 100% !important; top: 0; }"
},
{
"answer_id": 74612767,
"author": "birim",
"author_id": 18724350,
"author_profile": "https://Stackoverflow.com/users/18724350",
"pm_score": 0,
"selected": false,
"text": "const nestedArray = [...]; // Replace Array \nconst sortByArray = [\"LWB\", \"LB\", \"CAM\"];\nconst sortedArray = [];\n\nsortByArray.forEach(function(sortByArrayValue) {\n nestedArray.forEach(function(nestedArrayValue) {\n nestedArrayValue.roles.forEach(function(role) {\n if (role.team_meta.default_player_role.role === sortByArrayValue) {\n sortedArray.push(nestedArrayValue);\n }\n });\n });\n});\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74612576",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20587917/"
] |
74,612,611
|
<p>I'm well aware (thanks to Stephen Toub) that constructing a task with <code>new Task(...)</code> is generally not recommended and would normally prefer to use <code>Task.Run</code>, but what is the difference between the three approaches below when passing an async lambda as the task to run? I came across something similar to this in production code, so the code below is a highly contrived and simple example.</p>
<p>When passing an async lambda as a task to <code>Task.Factory.StartNew</code> and to <code>new Task(...)</code> (followed by <code>Task.Start</code>), even though we wait for the returned task the lambda does not finish. However, it does when using <code>Task.Run</code> - what's the difference here?</p>
<p>(and Stephen Toub states that <code>Task.Run</code> is exactly equivalent to</p>
<pre><code>Task.Factory.StartNew(SomeTask
CancellationToken.None,
TaskCreationOptions.DenyChildAttach,
TaskScheduler.Default);
</code></pre>
<p>See
<a href="https://devblogs.microsoft.com/pfxteam/task-run-vs-task-factory-startnew/" rel="nofollow noreferrer">https://devblogs.microsoft.com/pfxteam/task-run-vs-task-factory-startnew/</a></p>
<p>Here is my code:</p>
<pre><code>using System;
using System.Threading.Tasks;
using System.Threading;
namespace TaskDelay
{
class Program
{
static readonly long t0 = DateTime.Now.Ticks;
private static void Main()
{
Console.WriteLine($"{Time} Starting t1");
var t1 = new Task(async () => await F1(5000, "Task 1"));
t1.Start();
t1.Wait();
Console.WriteLine($"{Time} Starting t2");
var t2 = Task.Factory.StartNew(async () => await F1(5000, "Task 2"),
CancellationToken.None,
TaskCreationOptions.DenyChildAttach,
TaskScheduler.Default);
t2.Wait();
Console.WriteLine($"{Time} Starting t3");
var t3 = Task.Run(async () => await F1(2000, "Task 3"));
t3.Wait();
Console.WriteLine($"{Time} State of {nameof(t1)} is {t1.Status}");
Console.WriteLine($"{Time} State of {nameof(t2)} is {t2.Status}");
Console.WriteLine($"{Time} State of {nameof(t3)} is {t3.Status}");
}
private static async Task F1(int delay, string taskName)
{
await Console.Out.WriteLineAsync($"{Time} Started to run F1 for {taskName}");
await Task.Delay(delay);
await Console.Out.WriteLineAsync($"{Time} Finished running F1 for {taskName}");
}
private static string Time => $"{(int)((DateTime.Now.Ticks - t0) / 10_000),5} ms:";
}
}
</code></pre>
<p>And the output is</p>
<p><a href="https://i.stack.imgur.com/jbged.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jbged.png" alt="enter image description here" /></a></p>
<p>Notice we never see "Finished running F1 for Task 1" or "Finished running F1 for Task 2".</p>
|
[
{
"answer_id": 74612961,
"author": "Theodor Zoulias",
"author_id": 11178549,
"author_profile": "https://Stackoverflow.com/users/11178549",
"pm_score": 2,
"selected": false,
"text": "var t1 = new Task(async () => \nvar t2 = Task.Factory.StartNew(async () => \n t1 t2 Task<Task> Task Result Task Task Task Task Task Task Task ThreadPool t1.Wait();\nt1.Result.Wait();\n t1.Result t1.Wait() t1.Wait(); t1.Result.Wait(); Wait Unwrap t1.Unwrap().Wait();\n Task.Run Unwrap Task Task<Task>"
},
{
"answer_id": 74622117,
"author": "tymtam",
"author_id": 581076,
"author_profile": "https://Stackoverflow.com/users/581076",
"pm_score": 1,
"selected": false,
"text": "var t1 = F1(5000, \"Task 1\"); // no 'await', starts the work\n\n... other work\n\nawait t1; \n Func<Task<int>> f = async () => await WorkAsync(); // no work is started\n\nvar result = await f(); // *Starts* and waits\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74612611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1926222/"
] |
74,612,624
|
<p>I am able to browse all the links I need, but these links are redirecting me to the websites which have another links with pdf files, I have to open and process these pdfs. But I do not know what is the most efficient way to do it</p>
<pre><code>import requests
from bs4 import BeautifulSoup
import re
url = 'https://oeil.secure.europarl.europa.eu/oeil/popups/ficheprocedure.do?reference=2014/0124(COD)&l=en'
reqs = requests.get(url)
soup = BeautifulSoup(reqs.text, 'html.parser')
urls = []
for link in soup.find_all("a",href=re.compile("AM")):
print(link.get('href'))
</code></pre>
<p>Output:</p>
<pre><code>https://www.europarl.europa.eu/doceo/document/EMPL-AM-544465_EN.html
https://www.europarl.europa.eu/doceo/document/EMPL-AM-541655_EN.html
https://www.europarl.europa.eu/doceo/document/EMPL-AM-551891_EN.html
https://www.europarl.europa.eu/doceo/document/EMPL-AM-544465_EN.html
https://www.europarl.europa.eu/doceo/document/EMPL-AM-541655_EN.html
https://www.europarl.europa.eu/doceo/document/EMPL-AM-551891_EN.html
</code></pre>
|
[
{
"answer_id": 74612913,
"author": "Abolfazl Danayi",
"author_id": 11219714,
"author_profile": "https://Stackoverflow.com/users/11219714",
"pm_score": 0,
"selected": false,
"text": "for link in soup.find_all(\"a\",href=re.compile(\"AM\")):\n page_url = str(link.get('href'))\n pdf_url = page_url.replace('.html', '.pdf')\n pdf_response = requests.get(url)\n with open('/blah_blah_blah/metadata.pdf', 'wb') as f:\n f.write(response.content)\n https://www.europarl.europa.eu/doceo/document/EMPL-AM-544465_EN.html\n https://www.europarl.europa.eu/doceo/document/EMPL-AM-544465_EN.pdf\n"
},
{
"answer_id": 74613094,
"author": "Admin",
"author_id": 20632132,
"author_profile": "https://Stackoverflow.com/users/20632132",
"pm_score": 1,
"selected": false,
"text": "from urllib.parse import urlparse\n\ndomain = urlparse(\"https://www.europarl.europa.eu/doceo/document/EMPL-AM-544465_EN.html\").netloc\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74612624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20238491/"
] |
74,612,639
|
<p>I have an Xcode project that I want to deploy to App Store.</p>
<p>When I run <strong>Product >Archive</strong> I receive an "Archive failed" error in the Signing & Capabilities section.
(Please see the screenshots)</p>
<p>I tried both "<strong>Automatically Manage Signing</strong>" checked and unchecked.
When "Automatically Manage Signing" is unchecked, I receive 2 errors:</p>
<p><em>"Failed to create provisioning profile. There are no devices registered in your account on the developer website..."</em>
and
<em>"No profiles for 'net.myprojectname' were found. XCode could not find any IOS development provisioning profiles matching 'net.myprojectname'</em></p>
<p>When "Automatically Manage Signing" is checked, I receive those same 2 errors even before I run Product>Archive.</p>
<p>I do have a provisioning profile that appears to be visible to Xcode when the Automatically Manage Signing is unchecked.</p>
<p>When I try to just build the project and run it on the simulator, it works fine.
Again, all I want is to deploy the project to the App Store.</p>
<p>Do I really need a registered iPhone in order to do so? (I don't have one)
Or is there another way to solve it?</p>
<p>Thank you in advance for any help.
<a href="https://i.stack.imgur.com/p8TRS.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/p8TRS.jpg" alt="Auto signing option" /></a>
<a href="https://i.stack.imgur.com/x89nI.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/x89nI.jpg" alt="Non-auto signing" /></a></p>
<p>I tried Automatically Manage Signing checked and unchecked. I have created (and recreated) provisioning profile that matches my project name. I have tried running regular build beforehand. None of these actions solved the problem.</p>
|
[
{
"answer_id": 74612913,
"author": "Abolfazl Danayi",
"author_id": 11219714,
"author_profile": "https://Stackoverflow.com/users/11219714",
"pm_score": 0,
"selected": false,
"text": "for link in soup.find_all(\"a\",href=re.compile(\"AM\")):\n page_url = str(link.get('href'))\n pdf_url = page_url.replace('.html', '.pdf')\n pdf_response = requests.get(url)\n with open('/blah_blah_blah/metadata.pdf', 'wb') as f:\n f.write(response.content)\n https://www.europarl.europa.eu/doceo/document/EMPL-AM-544465_EN.html\n https://www.europarl.europa.eu/doceo/document/EMPL-AM-544465_EN.pdf\n"
},
{
"answer_id": 74613094,
"author": "Admin",
"author_id": 20632132,
"author_profile": "https://Stackoverflow.com/users/20632132",
"pm_score": 1,
"selected": false,
"text": "from urllib.parse import urlparse\n\ndomain = urlparse(\"https://www.europarl.europa.eu/doceo/document/EMPL-AM-544465_EN.html\").netloc\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74612639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13832043/"
] |
74,612,693
|
<p>I am trying to trim a video shoot on an iPhone.</p>
<p>When I execute:</p>
<pre><code>ffmpeg -i IMG_8555.MOV \
-filter_complex " \
[0:v] select='between(t,448.856,1279.240)', setpts=N/FR/TB; \
[0:a] aselect='between(t,448.856,1279.240)', asetpts=N/SR/TB \
" \
output.mov
</code></pre>
<p>the output audio is out of sync - audio is faster (noticeable towards the end of the output video).</p>
<p>I noticed that the outputs frame rate is 29.97 while the inputs is 29.98.</p>
<p>So I did some experimenting and changed setpts to <code>setpts=N/29.98/TB;</code> but still the video is falling behind.
So I changed it even more to <code>setpts=N/30.00/TB;</code> - then it feels almost ok.</p>
<p>I tired adding -vsync 1 - no luck</p>
<p>I tried adding -async 1 - no luck</p>
<p>I tried adding -async 7000 - no luck</p>
<p>edit: If i put setpts=N/29.99/TB then it is ideal.</p>
<p>Any ideas how can I make it always synced (no matter what is the input)?</p>
|
[
{
"answer_id": 74615431,
"author": "kesh",
"author_id": 4516027,
"author_profile": "https://Stackoverflow.com/users/4516027",
"pm_score": 2,
"selected": true,
"text": "ffmpeg -ss 448.86 -to 1279.240 -i IMG_8555.MOV output.mov\n ffmpeg -ss 0 -to 1 -i IMG_8555.MOV \\\n -ss 4 to 5 -i IMG_8555.MOV \\\n ...\n -ss 448.86 -to 1279.240 -i IMG_8555.MOV \\\n -filter_complex [0:v][0:a][1:v][1:a]...[99:v][99:a]concat\n output.mov\n concat IMG_8555_trim.ffconcat ffconcat version 1.0\n\nfile IMG_8555.MOV\ninpoint 0 \noutpoint 1 \n\nfile IMG_8555.MOV\ninpoint 4\noutpoint 5 \n\n...\n\nfile IMG_8555.MOV\ninpoint 448.86\noutpoint 1279.240\n ffmpeg -i IMG_8555_trim.ffconcat output.mov\n"
},
{
"answer_id": 74658931,
"author": "RadekJ",
"author_id": 2318843,
"author_profile": "https://Stackoverflow.com/users/2318843",
"pm_score": 0,
"selected": false,
"text": "enable='between(...)' [start1, end1]---[start2,end2]---[start3,end3]\n ffmpeg -i input.mov \\\n[0:v] \\\nselect='between(t,start1,end1)+between(t,start2,end2)+between(t,start3,end3)', \\\nsetpts='PTS-STARTPTS-(gt(t,end1)*(start2-end1) + gt(t,end2)*(start3-end2) )/TB'; \\\n[0:a] \\\naselect='between(t,start1,end1)+between(t,start2,end2)+between(t,start3,end3)', \\ \nasetpts='PTS-STARTPTS-(gt(t,end1)*(start2-end1) + gt(t,end2)*(start3-end2) )/TB' \\\noutput.mov\n gt(t,100) 1 100 0 (start2-end1) T end1 gt(t,end1) 0 start2-end1"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74612693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2318843/"
] |
74,612,714
|
<p>This is regarding neo4j csv import using LOAD csv. Suppose my csv file format is as following.</p>
<pre><code>Id, OID, name, address, Parents , Children
1, mid1, ratta, hello@aa, ["mid250","mid251","mid253"], ["mid60","mid65"]
2, mid2, butta, ado@bb, ["mid350","mid365","mid320", "mid450","mid700"], ["mid20","mid25","mid30"]
3, mid3, natta, hkk@aa, ["mid50","mid311","mid543"], []
</code></pre>
<p>So the parents and children columns consists of mids basically..while importing csv into neo4j using LOAD CSV.. I want to create following nodes and relationships.</p>
<ol>
<li><p>NODES for each rows (for each id column in csv)</p>
</li>
<li><p>[:PARENT] relationship by matching the OID property in each row and OID properties inside parents column. So as a example when processing the first row...there should be four nodes (mid1, mid250,mid 251 and mid 253) and 3 PARENT relationship between mid1 and other 3 nodes.</p>
</li>
<li><p>[: CHILD ] relationship by matching the OID property in each row and OID properties inside children column.</p>
</li>
</ol>
<p>Please help!!</p>
<p>Tried doing it with for each function but the results didn't come correctly. Im doing it through a python script. just need to edit the cypher query.</p>
<pre><code>def create_AAA(tx):
tx.run(
"LOAD CSV WITH HEADERS FROM 'file:///aaa.csv' AS row MERGE (e:AAA {id: row._id,OID: row.OID,address: row.address,name: row.name})"
)
def create_parent(tx):
tx.run(
"LOAD CSV WITH HEADERS FROM 'file:///aaa.csv' AS row MERGE (a:AAA {OID: row.OID}) FOREACH (t in row.parents | MERGE (e:AAA {OID:t}) MERGE (a)-[:PARENT]->(e) )"
)
def create_child(tx):
tx.run(
"LOAD CSV WITH HEADERS FROM 'file:///aaa.csv' AS row MERGE (a:AAA {OID: row.OID}) FOREACH (t in row.children | MERGE (e:AAA {OID:t}) MERGE (a)-[:CHILD]->(e) )"
)
with driver.session() as session:
session.write_transaction(create_AAA)
session.write_transaction(create_parent)
session.write_transaction(create_child)
</code></pre>
|
[
{
"answer_id": 74620275,
"author": "jose_bacoy",
"author_id": 7371893,
"author_profile": "https://Stackoverflow.com/users/7371893",
"pm_score": 2,
"selected": true,
"text": "LOAD CSV WITH HEADERS FROM 'file:///aaa.csv' AS row \nMERGE (a:AAA {OID: row.OID}) \nFOREACH (t in split(replace(replace(replace(row.parents,'[', ''),']', ''),'\"', ''), ' ') | \n MERGE (e:AAA {OID:t}) MERGE (a)-[:PARENT]->(e) )\n Id,OID,name,address,parents,children\n1,mid1,ratta,hello@aa,[\"mid250\" \"mid251\" \"mid253\"],[\"mid60\" \"mid65\"]\n2,mid2,butta,ado@bb,[\"mid350\" \"mid365\" \"mid320\" \"mid450\" \"mid700\"],[\"mid20\" \"mid25\" \"mid30\"]\n3,mid3,natta,hkk@aa,[\"mid50\" \"mid311\" \"mid543\"],[]\n"
},
{
"answer_id": 74627402,
"author": "Nirmana",
"author_id": 20339889,
"author_profile": "https://Stackoverflow.com/users/20339889",
"pm_score": 0,
"selected": false,
"text": "LOAD CSV WITH HEADERS FROM 'file:///aaa.csv' AS row\nWITH row WHERE row.children <>\"[]\" \nMERGE (a:AAA {OID: row.OID}) \nFOREACH (t in split(replace(replace(replace(row.children,'[', ''),']', ''),'\"', ''), ' ') | \nMERGE (e:AAA {OID:t}) MERGE (a)-[:CHILD]->(e) )\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74612714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20339889/"
] |
74,612,781
|
<p>I want to call a TaskGroup with a Dynamic sub-task id from BranchPythonOperator.</p>
<p>This is the DAG flow that I have:</p>
<p><a href="https://i.stack.imgur.com/BTV9O.png" rel="nofollow noreferrer">branch_dag</a></p>
<p>My case is I want to check whether a table exists in BigQuery or not.</p>
<ul>
<li><p>If exists: do nothing and end the DAG</p>
</li>
<li><p>If not exists: Ingest the data from Postgres to Google Cloud Storage</p>
</li>
</ul>
<p>I know that to call a TaskGroup from BranchPythonOperator is by calling the task id with following format:<br />
<code>group_task_id.task_id</code></p>
<p>The problem is, my task group's sub task id is dynamic, depends on how many time I loop the TaskGroup. So the sub_task will be:</p>
<pre><code>parent_task_id.sub_task_1
parent_task_id.sub_task_2
parent_task_id.sub_task_3
...
parent_task_id.sub_task_x
</code></pre>
<p>This is the following code for the DAG that I have:</p>
<pre><code>import airflow
from airflow.providers.google.cloud.transfers.postgres_to_gcs import PostgresToGCSOperator
from airflow.utils.task_group import TaskGroup
from google.cloud.exceptions import NotFound
from airflow import DAG
from airflow.operators.python import BranchPythonOperator
from airflow.operators.dummy import DummyOperator
from google.cloud import bigquery
default_args = {
'owner': 'Airflow',
'start_date': airflow.utils.dates.days_ago(2),
}
with DAG(dag_id='branch_dag', default_args=default_args, schedule_interval=None) as dag:
def create_task_group(worker=1):
var = dict()
with TaskGroup(group_id='parent_task_id') as tg1:
for i in range(worker):
var[f'sub_task_{i}'] = PostgresToGCSOperator(
task_id = f'sub_task_{i}',
postgres_conn_id = 'some_postgres_conn_id',
sql = 'test.sql',
bucket = 'test_bucket',
filename = 'test_file.json',
export_format = 'json',
gzip = True,
params = {
'worker': worker
}
)
return tg1
def is_exists_table():
client = bigquery.Client()
try:
table_name = client.get_table('dataset_id.some_table')
if table_name:
return 'task_end'
except NotFound as error:
return 'parent_task_id'
task_start = DummyOperator(
task_id = 'start'
)
task_branch_table = BranchPythonOperator(
task_id ='check_table_exists_in_bigquery',
python_callable = is_exists_table
)
task_pg_to_gcs_init = create_task_group(worker=3)
task_end = DummyOperator(
task_id = 'end',
trigger_rule = 'all_done'
)
task_start >> task_branch_table >> task_end
task_start >> task_branch_table >> task_pg_to_gcs_init >> task_end
</code></pre>
<p>When I run the dag, it returns</p>
<p>**<code>airflow.exceptions.TaskNotFound: Task parent_task_id not found</code> **</p>
<p>But this is expected, what I don't know is how to iterate the <code>parent_task_id.sub_task_x</code> on <code>is_exists_table</code> function. Or are there any workaround?</p>
<p>This is the <code>test.sql</code> file if it's needed</p>
<pre><code>
SELECT
id,
name,
country
FROM some_table
WHERE 1=1
AND ABS(MOD(hashtext(id::TEXT), 3)) = {{params.worker}};
-- returns 1M+ rows
</code></pre>
<p>I already seen this question as reference <a href="https://stackoverflow.com/questions/67720424/airflow-use-taskgroup-and-pythonbranchoperator-in-the-same-dag">Question</a> but I think my case is more specific.</p>
|
[
{
"answer_id": 74620275,
"author": "jose_bacoy",
"author_id": 7371893,
"author_profile": "https://Stackoverflow.com/users/7371893",
"pm_score": 2,
"selected": true,
"text": "LOAD CSV WITH HEADERS FROM 'file:///aaa.csv' AS row \nMERGE (a:AAA {OID: row.OID}) \nFOREACH (t in split(replace(replace(replace(row.parents,'[', ''),']', ''),'\"', ''), ' ') | \n MERGE (e:AAA {OID:t}) MERGE (a)-[:PARENT]->(e) )\n Id,OID,name,address,parents,children\n1,mid1,ratta,hello@aa,[\"mid250\" \"mid251\" \"mid253\"],[\"mid60\" \"mid65\"]\n2,mid2,butta,ado@bb,[\"mid350\" \"mid365\" \"mid320\" \"mid450\" \"mid700\"],[\"mid20\" \"mid25\" \"mid30\"]\n3,mid3,natta,hkk@aa,[\"mid50\" \"mid311\" \"mid543\"],[]\n"
},
{
"answer_id": 74627402,
"author": "Nirmana",
"author_id": 20339889,
"author_profile": "https://Stackoverflow.com/users/20339889",
"pm_score": 0,
"selected": false,
"text": "LOAD CSV WITH HEADERS FROM 'file:///aaa.csv' AS row\nWITH row WHERE row.children <>\"[]\" \nMERGE (a:AAA {OID: row.OID}) \nFOREACH (t in split(replace(replace(replace(row.children,'[', ''),']', ''),'\"', ''), ' ') | \nMERGE (e:AAA {OID:t}) MERGE (a)-[:CHILD]->(e) )\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74612781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20413423/"
] |
74,612,788
|
<p>I'm looking for a quick way to, for example, if this was my HTML document:</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<h1>Title</h1>
<p>Hello</p>
<p>This is a text line</p>
</html>
</code></pre>
<p>Select only <em><strong>Title</strong></em>, <em><strong>Hello</strong></em> and <em><strong>This is a text line</strong></em> all at once, ignoring the tags and non-string code.</p>
<p>Is there a keyboard shortcut or a plugin to do it? I'm working with MacOS on a Mac keyboard.</p>
|
[
{
"answer_id": 74620275,
"author": "jose_bacoy",
"author_id": 7371893,
"author_profile": "https://Stackoverflow.com/users/7371893",
"pm_score": 2,
"selected": true,
"text": "LOAD CSV WITH HEADERS FROM 'file:///aaa.csv' AS row \nMERGE (a:AAA {OID: row.OID}) \nFOREACH (t in split(replace(replace(replace(row.parents,'[', ''),']', ''),'\"', ''), ' ') | \n MERGE (e:AAA {OID:t}) MERGE (a)-[:PARENT]->(e) )\n Id,OID,name,address,parents,children\n1,mid1,ratta,hello@aa,[\"mid250\" \"mid251\" \"mid253\"],[\"mid60\" \"mid65\"]\n2,mid2,butta,ado@bb,[\"mid350\" \"mid365\" \"mid320\" \"mid450\" \"mid700\"],[\"mid20\" \"mid25\" \"mid30\"]\n3,mid3,natta,hkk@aa,[\"mid50\" \"mid311\" \"mid543\"],[]\n"
},
{
"answer_id": 74627402,
"author": "Nirmana",
"author_id": 20339889,
"author_profile": "https://Stackoverflow.com/users/20339889",
"pm_score": 0,
"selected": false,
"text": "LOAD CSV WITH HEADERS FROM 'file:///aaa.csv' AS row\nWITH row WHERE row.children <>\"[]\" \nMERGE (a:AAA {OID: row.OID}) \nFOREACH (t in split(replace(replace(replace(row.children,'[', ''),']', ''),'\"', ''), ' ') | \nMERGE (e:AAA {OID:t}) MERGE (a)-[:CHILD]->(e) )\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74612788",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18079177/"
] |
74,612,809
|
<p>I'm modifying an app, trying to use Pydantic for my application models and SQLAlchemy for my database models.</p>
<p>I have existing classes, where I defined attributes inside the <code>__init__</code> method as I was taught to do:</p>
<pre class="lang-py prettyprint-override"><code>class Measure:
def __init__(
self,
t_received: int,
mac_address: str,
data: pd.DataFrame,
battery_V: float = 0
):
self.t_received = t_received
self.mac_address = mac_address
self.data = data
self.battery_V = battery_V
</code></pre>
<p>In both Pydantic and SQLAlchemy, following the docs, I have to define those attributes outside the <code>__init__</code> method, for example in Pydantic:</p>
<pre class="lang-py prettyprint-override"><code>import pydantic
class Measure(pydantic.BaseModel):
t_received: int
mac_address: str
data: pd.DataFrame
battery_V: float
</code></pre>
<p>Why is it the case? Isn't this bad practice? Is there any impact on other methods (classmethods, staticmethods, properties ...) of that class?</p>
<p>Note that this is also <em>very unhandy</em> because when I instantiate an object of that class, I don't get suggestions on what parameters are expected by the constructor!</p>
|
[
{
"answer_id": 74614167,
"author": "Daniil Fajnberg",
"author_id": 19770795,
"author_profile": "https://Stackoverflow.com/users/19770795",
"pm_score": 2,
"selected": true,
"text": "class Foo:\n a: list[int]\n b: str\n\n def __init__(self, b: str) -> None:\n self.a = []\n self.b = b\n BaseModel from pydantic import BaseModel\n\n\nclass MyModel(BaseModel):\n field_a: str\n field_b: int = 1\n\n\nobj = MyModel(\n field_a=\"spam\", # required\n field_b=2, # optional\n field_c=3.14, # unexpected/ignored\n)\n field_a MyModel field_b=\"eggs\" __init__ mypy @dataclass_transform dataclasses __init__ __init__ @property"
},
{
"answer_id": 74627994,
"author": "Alex",
"author_id": 2595183,
"author_profile": "https://Stackoverflow.com/users/2595183",
"pm_score": 0,
"selected": false,
"text": ">>> from sqlalchemy import Column, Integer, String\n>>> class User(Base):\n...\n... id = Column(Integer, primary_key=True)\n... name = Column(String)\n descriptors __set__ class User(Base):\n id = Column(Integer, primary_key=True)\n name = Column(String)\n\nuser = User()\nuser.name = 'John' \n user.name.__set__('John') Column class Column:\n def __init__(self, field=\"\"):\n self.field= field\n def __get__(self, obj, type):\n return obj.__dict__.get(self.field)\n def __set__(self, obj, val):\n if validate_field(val)\n obj.__dict__[self.field] = val\n else:\n print('not a valid value')\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74612809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11696358/"
] |
74,612,813
|
<p>I want to loop through a list and insert each item into a column and iterate 1000 time. I am SQL noob - can anyone help me with this?</p>
<p>What I have so far:</p>
<pre><code>DECLARE @Counter INT
DECLARE @myList varchar(100)
SET @Counter = 0
SET @myList = 'temp,humidity,dewpoint'
WHILE (@Counter <= 1000)
BEGIN
INSERT INTO [DBO].[tbl_var] (VariableNames)
VALUES (@myList)
SET @Counter = @Counter + 1
END
</code></pre>
<p>I get this error:</p>
<blockquote>
<p>Cannot insert the value NULL into column 'VariableNames', table 'master.DBO.tbl_var'; column does not allow nulls. INSERT fails.</p>
</blockquote>
<p>What I expected</p>
<p><code>VariableNames</code> column</p>
<pre><code>1. temp
2. humidity
3. dewpoint
4. temp
5. humidity
6. dewpoint
</code></pre>
<p>and so on until 1000 iterations of list is complete</p>
|
[
{
"answer_id": 74614167,
"author": "Daniil Fajnberg",
"author_id": 19770795,
"author_profile": "https://Stackoverflow.com/users/19770795",
"pm_score": 2,
"selected": true,
"text": "class Foo:\n a: list[int]\n b: str\n\n def __init__(self, b: str) -> None:\n self.a = []\n self.b = b\n BaseModel from pydantic import BaseModel\n\n\nclass MyModel(BaseModel):\n field_a: str\n field_b: int = 1\n\n\nobj = MyModel(\n field_a=\"spam\", # required\n field_b=2, # optional\n field_c=3.14, # unexpected/ignored\n)\n field_a MyModel field_b=\"eggs\" __init__ mypy @dataclass_transform dataclasses __init__ __init__ @property"
},
{
"answer_id": 74627994,
"author": "Alex",
"author_id": 2595183,
"author_profile": "https://Stackoverflow.com/users/2595183",
"pm_score": 0,
"selected": false,
"text": ">>> from sqlalchemy import Column, Integer, String\n>>> class User(Base):\n...\n... id = Column(Integer, primary_key=True)\n... name = Column(String)\n descriptors __set__ class User(Base):\n id = Column(Integer, primary_key=True)\n name = Column(String)\n\nuser = User()\nuser.name = 'John' \n user.name.__set__('John') Column class Column:\n def __init__(self, field=\"\"):\n self.field= field\n def __get__(self, obj, type):\n return obj.__dict__.get(self.field)\n def __set__(self, obj, val):\n if validate_field(val)\n obj.__dict__[self.field] = val\n else:\n print('not a valid value')\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74612813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19975572/"
] |
74,612,965
|
<p>i will import data csv to postgresql via pgAdmin 4. But, there are problem</p>
<pre><code>ERROR: invalid input syntax for type integer: ""
CONTEXT: COPY films, line 1, column gross: ""
</code></pre>
<p>i understand about the error that is line 1 column gross there is null value and in some other columns there are also null values. My questions, how to import file csv but in the that file there is null value. I've been search in google but not found similar my case.</p>
<pre><code>CREATE TABLE public.films
(
id int,
title varchar,
release_year float4,
country varchar,
duration float4,
language varchar,
certification varchar,
gross int,
budget int
);
</code></pre>
<p>And i try in this code below, but failed</p>
<pre><code>CREATE TABLE public.films
(
id int,
title varchar,
release_year float4 null,
country varchar null,
duration float4 null,
language varchar null,
certification varchar null,
gross float4 null,
budget float4 null
);
</code></pre>
<p><a href="https://i.stack.imgur.com/pRjI6.png" rel="nofollow noreferrer">error message in image</a></p>
<p>I've searched on google and on the stackoverflow forums. I hope that someone will help solve my problem</p>
|
[
{
"answer_id": 74614167,
"author": "Daniil Fajnberg",
"author_id": 19770795,
"author_profile": "https://Stackoverflow.com/users/19770795",
"pm_score": 2,
"selected": true,
"text": "class Foo:\n a: list[int]\n b: str\n\n def __init__(self, b: str) -> None:\n self.a = []\n self.b = b\n BaseModel from pydantic import BaseModel\n\n\nclass MyModel(BaseModel):\n field_a: str\n field_b: int = 1\n\n\nobj = MyModel(\n field_a=\"spam\", # required\n field_b=2, # optional\n field_c=3.14, # unexpected/ignored\n)\n field_a MyModel field_b=\"eggs\" __init__ mypy @dataclass_transform dataclasses __init__ __init__ @property"
},
{
"answer_id": 74627994,
"author": "Alex",
"author_id": 2595183,
"author_profile": "https://Stackoverflow.com/users/2595183",
"pm_score": 0,
"selected": false,
"text": ">>> from sqlalchemy import Column, Integer, String\n>>> class User(Base):\n...\n... id = Column(Integer, primary_key=True)\n... name = Column(String)\n descriptors __set__ class User(Base):\n id = Column(Integer, primary_key=True)\n name = Column(String)\n\nuser = User()\nuser.name = 'John' \n user.name.__set__('John') Column class Column:\n def __init__(self, field=\"\"):\n self.field= field\n def __get__(self, obj, type):\n return obj.__dict__.get(self.field)\n def __set__(self, obj, val):\n if validate_field(val)\n obj.__dict__[self.field] = val\n else:\n print('not a valid value')\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74612965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19477773/"
] |
74,612,969
|
<p>I have this dataframe</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ID</th>
<th>product name</th>
</tr>
</thead>
<tbody>
<tr>
<td>1BJM10</td>
<td>1BJM10_RS2022_PK</td>
</tr>
<tr>
<td></td>
<td>L_RS2022_PK</td>
</tr>
<tr>
<td></td>
<td>2PKL10_RS2022_PK</td>
</tr>
<tr>
<td></td>
<td>3BDG10_RS2022_PK</td>
</tr>
<tr>
<td>1BJM10</td>
<td>1BJM10_RS2022_PK</td>
</tr>
</tbody>
</table>
</div>
<p>My desired output is like this</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ID</th>
<th>product name</th>
</tr>
</thead>
<tbody>
<tr>
<td>1BJM10</td>
<td>1BJM10_RS2022_PK</td>
</tr>
<tr>
<td>-</td>
<td>L_RS2022_PK</td>
</tr>
<tr>
<td>2PKL10</td>
<td>2PKL10_RS2022_PK</td>
</tr>
<tr>
<td>3BDG10</td>
<td>3BDG10_RS2022_PK</td>
</tr>
<tr>
<td>1BJM10</td>
<td>1BJM10_RS2022_PK</td>
</tr>
</tbody>
</table>
</div>
<p>2nd row shouldn't get the ID because is has "_" in the product name's first 6 characters.</p>
<p>I have tried this code, but it doesn't work</p>
<pre><code>df.loc[df['ID'].isna()] = df['ID'].fillna(~df['product name'].str[:6].contains("_"))
</code></pre>
|
[
{
"answer_id": 74613071,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 3,
"selected": true,
"text": "& AND Series s = df['product name'].str[:6]\ndf.loc[df['ID'].isna() & ~s.str.contains(\"_\"), 'ID'] = s\nprint (df)\n ID product name\n0 1BJM10 1BJM10_RS2022_PK\n1 NaN L_RS2022_PK\n2 2PKL10 2PKL10_RS2022_PK\n3 3BDG10 3BDG10_RS2022_PK\n4 1BJM10 1BJM10_RS2022_PK\n"
},
{
"answer_id": 74613100,
"author": "sebastian",
"author_id": 15360141,
"author_profile": "https://Stackoverflow.com/users/15360141",
"pm_score": 0,
"selected": false,
"text": "df['ID'] = df['product name'].apply(lambda x: x[:x.find('_')] if x.find('_')>=6 else '')\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74612969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14729437/"
] |
74,612,974
|
<p>I have following code for my dropdown menu. How can I set a value as selected?</p>
<pre><code><div class="input-group mb-3">
<label class="input-group-text labelDropDown" for="inputGroupSelect01">Art der
Integration</label>
<select class="form-select" id="inputGroupSelect01" formControlName="integrationType">
<option value="statisch">statisch</option>
<option value="dynamisch">dynamisch</option>
<option value="nein">nein</option>
</select>
</div>
</code></pre>
<p>I thought it will be selected if I type in the selected keyword? Why does angular not do this?</p>
|
[
{
"answer_id": 74613069,
"author": "Andriu1510",
"author_id": 17238007,
"author_profile": "https://Stackoverflow.com/users/17238007",
"pm_score": 2,
"selected": false,
"text": "selected <option> <div class=\"input-group mb-3\">\n <label class=\"input-group-text labelDropDown\" for=\"inputGroupSelect01\">Art der\n Integration</label>\n <select class=\"form-select\" id=\"inputGroupSelect01\" formControlName=\"integrationType\">\n <option value=\"statisch\">statisch</option>\n <option value=\"dynamisch\">dynamisch</option>\n <option value=\"nein\" selected>nein</option>\n </select>\n</div>\n"
},
{
"answer_id": 74613087,
"author": "MoxxiManagarm",
"author_id": 11011793,
"author_profile": "https://Stackoverflow.com/users/11011793",
"pm_score": 0,
"selected": false,
"text": "integrationType nein nein this.myFormGroup.get('integrationType').setValue('nein');\n this.myFormGroup = this.formBuilder.group({\n integrationType: ['nein'],\n });\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74612974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20589673/"
] |
74,612,991
|
<p>I have three files in a folder with the following names:</p>
<pre><code>./multiqc_data$ ls
</code></pre>
<pre><code>file1.json
file2.json
file3.json
</code></pre>
<p>When I open the files with the <a href="https://github.com/multimeric/TidyMultiqc" rel="nofollow noreferrer">TidyMultiqc package</a> existing NA values in the files might lead to the following error:</p>
<pre><code>files <- dir(path,pattern = "*.json") #locate files
files %>%
map(~ load_multiqc(file.path(path, .))) #parse them
## the error
Error in parse_con(txt, bigint_as_char) :
lexical error: invalid char in json text.
"mapped_failed_pct": NaN, "paired in
(right here) ------^
</code></pre>
<p>I want to create a function to handle this error.</p>
<p>I want every time this error pops up to be able to apply this sed function in all files of the folder.</p>
<pre><code>system(paste("gsed -i 's/NaN/null/g'",paste0(path,"*.json")))
</code></pre>
<p>Any ideas how can I achieve this</p>
|
[
{
"answer_id": 74650608,
"author": "Ric Villalba",
"author_id": 6912817,
"author_profile": "https://Stackoverflow.com/users/6912817",
"pm_score": 1,
"selected": false,
"text": "withCallingHandlers withRestarts sed \npath <- \"../your_path\"\n\n# function that does the error_prone task\ndo_task <- function(path){\n files <- dir(path,pattern = \"*.json\") #locate files\n files %>% \n map(~ withRestart( # set an alternative restart\n load_multiqc(file.path(path, .)), # parsing\n skipFile = function() { # if fails, skip only this file \n message(paste(\"skipping \", file.path(path, .)))\n return(NULL)\n })) \n}\n\n# error handler that invokes \"removeNaN\"\nremoveNaNHandler <- function(e) tryInvokeRestart(\"removeNaN\")\n# error handler that invokes \"skipFile\"\nskipFileHandler <- function(e) tryInvokeRestart(\"skipFile\")\n\n# run the task with handlers in case of error\nwithCallingHandlers(\n condition = removeNaNHandler, # call handler (on generic error)\n # condition = skipFileHandler, # if previous fails skips file\n {\n # run with recovery protocols (can define more than one)\n withRestarts({\n do_task(path)}, \n removeNaN = function() # protocol \"removeNaN\" \n { \n system(paste(\"gsed -i 's/NaN/null/g'\",paste0(path,\"*.json\")))\n do_task(path) # try again\n }\n )\n }\n)\n\n"
},
{
"answer_id": 74657850,
"author": "moodymudskipper",
"author_id": 2270475,
"author_profile": "https://Stackoverflow.com/users/2270475",
"pm_score": 2,
"selected": false,
"text": "safe_load_multiqc <- function(path, file) {\n tryCatch(load_multiqc(file.path(path, file)), error = function(e) {\n system(paste(\"gsed -i 's/NaN/null/g'\",paste0(path,\"*.json\")))\n # retry\n load_multiqc(path, file)\n })\n}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74612991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7179299/"
] |
74,613,028
|
<p>I want to cast the current_timestamp in Big Query to a string but it add <code>+00</code> which stand for UTC as the time zone to the string. I only want the timestamp without the zone i.e. without <code>+00</code>. How can I get that?</p>
<p>This is what I'm doing:</p>
<pre><code>
select STRING(CURRENT_TIMESTAMP()) as now
</code></pre>
<p>The result:</p>
<pre><code>
2022-11-29 10:56:12.793309+00
</code></pre>
<p>I want:</p>
<pre><code>2022-11-29 10:56:12.793309
</code></pre>
|
[
{
"answer_id": 74650608,
"author": "Ric Villalba",
"author_id": 6912817,
"author_profile": "https://Stackoverflow.com/users/6912817",
"pm_score": 1,
"selected": false,
"text": "withCallingHandlers withRestarts sed \npath <- \"../your_path\"\n\n# function that does the error_prone task\ndo_task <- function(path){\n files <- dir(path,pattern = \"*.json\") #locate files\n files %>% \n map(~ withRestart( # set an alternative restart\n load_multiqc(file.path(path, .)), # parsing\n skipFile = function() { # if fails, skip only this file \n message(paste(\"skipping \", file.path(path, .)))\n return(NULL)\n })) \n}\n\n# error handler that invokes \"removeNaN\"\nremoveNaNHandler <- function(e) tryInvokeRestart(\"removeNaN\")\n# error handler that invokes \"skipFile\"\nskipFileHandler <- function(e) tryInvokeRestart(\"skipFile\")\n\n# run the task with handlers in case of error\nwithCallingHandlers(\n condition = removeNaNHandler, # call handler (on generic error)\n # condition = skipFileHandler, # if previous fails skips file\n {\n # run with recovery protocols (can define more than one)\n withRestarts({\n do_task(path)}, \n removeNaN = function() # protocol \"removeNaN\" \n { \n system(paste(\"gsed -i 's/NaN/null/g'\",paste0(path,\"*.json\")))\n do_task(path) # try again\n }\n )\n }\n)\n\n"
},
{
"answer_id": 74657850,
"author": "moodymudskipper",
"author_id": 2270475,
"author_profile": "https://Stackoverflow.com/users/2270475",
"pm_score": 2,
"selected": false,
"text": "safe_load_multiqc <- function(path, file) {\n tryCatch(load_multiqc(file.path(path, file)), error = function(e) {\n system(paste(\"gsed -i 's/NaN/null/g'\",paste0(path,\"*.json\")))\n # retry\n load_multiqc(path, file)\n })\n}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74613028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20220756/"
] |
74,613,091
|
<p>ok so I cannot share the website I'm trying to automate but I'll share a screen shots of the inspect view.</p>
<p><a href="https://i.stack.imgur.com/f7tVy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/f7tVy.png" alt="enter image description here" /></a></p>
<p>ill add the code i used and the log i got from it</p>
<p><a href="https://i.stack.imgur.com/1ZV6w.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1ZV6w.png" alt="enter image description here" /></a>
as you can see the class: data-command has three elements within in the number is dynamic but I need to click on the last one, i do not want to use absolut xpath as the class: data-command is dynamic.
ill add the code i used and the log i got from it</p>
<p>how do i click the last element</p>
<pre><code> #@{element_value}= Get WebElements class:data-value
@{elements_name}= Get WebElements class:data-label
@{element_commands}= Get WebElements class:data-command
WHILE ${i} < 5
#Log To Console ${element_commands[${i}]}
Click Element ${element_commands[${i}]}
Sleep 5s
#Capture Page Screenshot
Run Keyword And Warn On Failure Page Should Contain ${graph}
${i}= Evaluate ${i} + ${one}
END
</code></pre>
|
[
{
"answer_id": 74650608,
"author": "Ric Villalba",
"author_id": 6912817,
"author_profile": "https://Stackoverflow.com/users/6912817",
"pm_score": 1,
"selected": false,
"text": "withCallingHandlers withRestarts sed \npath <- \"../your_path\"\n\n# function that does the error_prone task\ndo_task <- function(path){\n files <- dir(path,pattern = \"*.json\") #locate files\n files %>% \n map(~ withRestart( # set an alternative restart\n load_multiqc(file.path(path, .)), # parsing\n skipFile = function() { # if fails, skip only this file \n message(paste(\"skipping \", file.path(path, .)))\n return(NULL)\n })) \n}\n\n# error handler that invokes \"removeNaN\"\nremoveNaNHandler <- function(e) tryInvokeRestart(\"removeNaN\")\n# error handler that invokes \"skipFile\"\nskipFileHandler <- function(e) tryInvokeRestart(\"skipFile\")\n\n# run the task with handlers in case of error\nwithCallingHandlers(\n condition = removeNaNHandler, # call handler (on generic error)\n # condition = skipFileHandler, # if previous fails skips file\n {\n # run with recovery protocols (can define more than one)\n withRestarts({\n do_task(path)}, \n removeNaN = function() # protocol \"removeNaN\" \n { \n system(paste(\"gsed -i 's/NaN/null/g'\",paste0(path,\"*.json\")))\n do_task(path) # try again\n }\n )\n }\n)\n\n"
},
{
"answer_id": 74657850,
"author": "moodymudskipper",
"author_id": 2270475,
"author_profile": "https://Stackoverflow.com/users/2270475",
"pm_score": 2,
"selected": false,
"text": "safe_load_multiqc <- function(path, file) {\n tryCatch(load_multiqc(file.path(path, file)), error = function(e) {\n system(paste(\"gsed -i 's/NaN/null/g'\",paste0(path,\"*.json\")))\n # retry\n load_multiqc(path, file)\n })\n}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74613091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20147694/"
] |
74,613,105
|
<p>When I run the page, and click on the value in the partial table nothing happens with the onclick event. the values are not populating on the textboxes.I set the style of the anchor element to cursor: pointer. Debugging the code as shown in the images, the values populate correctly they just do not appear in the textboxes.</p>
<p>index.cshtml</p>
<pre><code>@page "{id?}"
@model IndexModel
@{ViewData["Title"] = "Test";}
<div class="container">
<div class="row">
<div class="text-center">
<h1 class="display-4">@Model.PageTitle</h1>
</div>
</div>
<div class="row">
<form class="mt-0" method="get">
<div class="row">
<div class="col-3 offset-1" id="ApplicationResult">
</div>
<div class="col-4" id="ApplicationOwnerResult">
</div>
<div class="col-3" id="ApplicationDmvResult">
</div>
</div>
</form>
</div>
<div class="row">
<form class="mt-0" method="post">
<div class="row">
<label class="col-2 offset-4 col-form-label">Date of Birth:</label>
<div class="col-2">
<input class="form-control" title="Date of birth" oninput="validate()" asp-for="DateOfBirth">
<span asp-validation-for="DateOfBirth"></span>
</div>
</div>
<br>
<div class="row">
<label class="col-2 offset-4 col-form-label">Driver's License Number:</label>
<div class="col-2">
<input class="form-control" title="Driver's license number" oninput="validate()" asp-for="DriversLicenseNumber">
<span asp-validation-for="DriversLicenseNumber"></span>
</div>
</div>
<br>
<div class="row">
<button class="btn btn-outline-dark col-1 offset-5" type="submit" id="Submit" disabled asp-page-handler="Submit">Submit</button>
&nbsp;
<button class="btn btn-outline-dark col-1" type="button" id="Reset" onclick="clearAll()">Reset</button>
</div>
<br>
</form>
</div>
</div>
@section Scripts {
<script>
// Any exemption applications found will be displayed when the page initially loads. On POST request GET form will be hidden
$(document).ready(function () {
if ("@Model.Exist" == "DivIsVisible") {
$.ajax({
url: "Index/?handler=Display",
type: "GET",
data: { value: @Model.Id },
headers: { RequestVerificationToken: $('input:hidden[name="__RequestVerificationToken"]').val() },
success: function (data) { $("#ApplicationResult").html(data); }
});
}
else {
$("#ApplicationResult").hide();
}
});
// autofill the inputs
function displayOwnerInfo(id) {
$.ajax({
url: "Index/?handler=DisplayOwnerInfo&value=" + id,
type: "GET",
success: function (data) { $("#DateOfBirth").val(data.DateOfBirth); $("#DriversLicenseNumber").val(data.DriversLicenseNumber); }
});
}
</script>
}
</code></pre>
<p>index.cshtml.cs</p>
<pre><code>using DMVServiceReference;
using DMV.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Net.Http;
using System.Runtime.Serialization;
using System.Threading.Tasks;
namespace DMV.Pages
{
public class IndexModel : PageModel
{
public Assess50Context _context;
// Id property refers to checking the PropertyId value for the URL
[BindProperty(SupportsGet = true)] public int Id { get; set; }
// Exist property refers to checking if GetDivs exist on POST request
[BindProperty] public string PageTitle { get; set; } = "Residency Check";
public ResidencyCheckCriteria CheckCriteria { get; set; }
[BindProperty, DataMember, MaxLength(8, ErrorMessage = " "), MinLength(8, ErrorMessage = " "), RegularExpression(@"^([0-9]{8}$)", ErrorMessage = " "), Required(ErrorMessage = " ")] public string DateOfBirth { get => CheckCriteria.DateOfBirth; set => CheckCriteria.DateOfBirth = value; }
[BindProperty, DataMember, MaxLength(13, ErrorMessage = " "), MinLength(13, ErrorMessage = " "), RegularExpression(@"^([A-Za-z0-9]{13}$)", ErrorMessage = " "), Required(ErrorMessage = " ")] public string DriversLicenseNumber { get => CheckCriteria.DriverLicenseNumber; set => CheckCriteria.DriverLicenseNumber = value; }
[BindProperty(SupportsGet = true)] public string Exist { get; set; } = "DivIsVisible";
public IndexModel(Assess50Context context)
{
_context = context;
CheckCriteria = new ResidencyCheckCriteria();
}
// Reads all exemption application table information by property id
public PartialViewResult OnGetDisplay(int value) => Partial("_DisplayApplicationPartial", _context.ExemptionApplications.Where(x => x.PropertyId == value).ToList());
// Reads all exemption application owner information by exemption application id
public PartialViewResult OnGetDisplayOwner(int value) => Partial("_DisplayOwnerPartial", _context.ExemptionApplicationOwners.Where(x => x.ExemptionApplicationId == value).GroupBy(x => x.ExemptionApplicationOwnerId).Select(x => x.First()).ToList());
// Reads the dmv information by application owner ID
// public PartialViewResult OnGetDisplayOwnerInfo(int value) => Partial("_DisplayDMVPartial", _context.ExemptionApplicationDmvinformations.Where(x => x.ExemptionApplicationOwnerId == value).ToList());
public JsonResult OnGetDisplayOwnerInfo(int value)
{
ExemptionApplicationDmvinformation data = _context.ExemptionApplicationDmvinformations.Where(x => x.ExemptionApplicationOwnerId == value).First();
return new JsonResult(new { DateOfBirth = data.DmvDob.ToString(), DriversLicenseNumber = data.DriverLicense });
}
</code></pre>
<p>DbContext.cs</p>
<pre><code>using Microsoft.EntityFrameworkCore;
namespace DMV.Models
{
public partial class Assess50Context : DbContext
{
public virtual DbSet<ExemptionApplication> ExemptionApplications { get; set; } = null!;
public virtual DbSet<ExemptionApplicationDmvinformation> ExemptionApplicationDmvinformations { get; set; } = null!;
public virtual DbSet<ExemptionApplicationOwner> ExemptionApplicationOwners { get; set; } = null!;
public Assess50Context() {}
public Assess50Context(DbContextOptions<Assess50Context> options) : base(options) {}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
}
partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}
}
</code></pre>
<p>Application.cs model</p>
<pre><code>using System;
using System.ComponentModel.DataAnnotations;
namespace DMV.Models
{
public partial class ExemptionApplication
{
public int PropertyId { get; set; }
[Display(Name = "Year")] public short YearId { get; set; }
[Display(Name = "App ID")] public int ExemptionApplicationId { get; set; }
[Display(Name = "Reference Number")] public string? ApplicationReference { get; set; }
}
}
</code></pre>
<p>Owner.cs model</p>
<pre><code>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace DMV.Models
{
public partial class ExemptionApplicationOwner
{
public int PropertyId { get; set; }
public int ExemptionApplicationId { get; set; }
[Display(Name = "Application Owner ID")] public int ExemptionApplicationOwnerId { get; set; }
[Display(Name = "Owner ID")] public int? OwnerId { get; set; }
public string? FirstName { get; set; }
public string? LastName { get; set; }
[Display(Name = "Name")]public string? AssessProName { get; set; }
}
}
</code></pre>
<p>DmvInformation.cs model</p>
<pre><code>using SoapCore.ServiceModel;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace DMV.Models
{
public partial class ExemptionApplicationDmvinformation
{
public int PropertyId { get; set; }
public int ExemptionApplicationId { get; set; }
public int ExemptionApplicationOwnerId { get; set; }
[Display(Name = "DOB")] public DateTime? DmvDob { get; set; }
[Display(Name = "Driver's License #")] public string? DriverLicense { get; set; }
}
}
</code></pre>
<p>_DisplayApplicationPartial.cshtml</p>
<pre><code>@model IEnumerable<Models.ExemptionApplication>
@if (Model.Count() != 0)
{
<div id="ExemptionApplicationNav">
<table class="PartialTable">
<thead>
<tr>
<th class="PartialTableRowData" colspan="3">Exemption Applications</th>
</tr>
</thead>
<tbody>
<tr>
<td class="PartialTableRowCategoryData">@Html.DisplayNameFor(m => m.YearId)</td>
<td class="PartialTableRowCategoryData">@Html.DisplayNameFor(m => m.ApplicationReference)</td>
<td class="PartialTableRowCategoryData">@Html.DisplayNameFor(m => m.ExemptionApplicationId)</td>
</tr>
@foreach (Models.ExemptionApplication item in Model)
{
<tr>
<td class="PartialTableRowData">@item.YearId</td>
<td class="PartialTableRowData">@item.ApplicationReference</td>
<td class="PartialTableRowData">
<a class="DMVLabelsTexts" href="Index/?handler=DisplayOwner&value=@item.ExemptionApplicationId">@item.ExemptionApplicationId</a>
</td>
</tr>
}
</tbody>
</table>
</div>
}
else
{
<p>No exemption applications found for this Property ID</p>
}
<script>
$('#ExemptionApplicationNav a').click(function (e) {
$('#ApplicationOwnerResult').hide().load($(this).attr('href'), function () {
$('#ApplicationOwnerResult').show()
})
return false
})
</script>
</code></pre>
<p>_DisplayOwnerPartial.cshtml</p>
<pre><code>@model IEnumerable<Models.ExemptionApplicationOwner>
@if (Model.Count() != 0)
{
<div id="OwnerNav">
<table class="PartialTable">
<thead>
<tr>
<th class="PartialTableRowData" colspan="3">Owner Information</th>
</tr>
</thead>
<tbody>
<tr>
<td class="PartialTableRowCategoryData">@Html.DisplayNameFor(m => m.ExemptionApplicationOwnerId)</td>
<td class="PartialTableRowCategoryData" colspan="2">@Html.DisplayNameFor(m => m.AssessProName)</td>
</tr>
@foreach (Models.ExemptionApplicationOwner item in Model)
{
<tr>
<td class="PartialTableRowData">
<a class="DMVLabelsTexts" onclick="displayOwnerInfo('@item.ExemptionApplicationOwnerId')">@item.ExemptionApplicationOwnerId</a>
<!-- <a class="DMVLabelsTexts" href="Index/?handler=DisplayOwnerInfo&value=@item.ExemptionApplicationOwnerId">@item.ExemptionApplicationOwnerId</a> -->
</td>
<td class="PartialTableRowMultipleData">@item.FirstName</td>
<td class="PartialTableRowMultipleData">@item.LastName</td>
</tr>
}
</tbody>
</table>
</div>
}
else
{
<p>No owner data available</p>
}
<!--
<script>
$('#OwnerNav a').click(function (e) {
$('#ApplicationDmvResult').hide().load($(this).attr('href'), function () {
$('#ApplicationDmvResult').show()
})
return false
})
</script>
-->
</code></pre>
<p>_DisplayDMVPartial.cshtml</p>
<pre><code>@model IEnumerable<Models.ExemptionApplicationDmvinformation>
@if (Model.Count() != 0)
{
<div id="DmvNav">
<table style=" border: 1px solid black;">
<thead>
<tr>
<th colspan="2" style="border: 1px solid black; text-align: center;">DMV Information</th>
</tr>
</thead>
<tbody>
<tr>
<td style="border: 1px solid black; font-weight: bold; text-align: center;">@Html.DisplayNameFor(m => m.DmvDob)</td>
<td style="border: 1px solid black; font-weight: bold; text-align: center;">@Html.DisplayNameFor(m => m.DriverLicense)</td>
</tr>
@foreach (Models.ExemptionApplicationDmvinformation item in Model)
{
<tr>
<!-- <td style="border: 1px solid black; text-align: center;">item.DmvDob.Value.ToString("MMddyyyy")</td> -->
<td style="border: 1px solid black; text-align: center;">@item.DmvDob</td>
<td style="border: 1px solid black; text-align: center;">@item.DriverLicense</td>
</tr>
}
</tbody>
</table>
</div>
}
else
{
<p>No owner data available</p>
}
</code></pre>
<p><a href="https://i.stack.imgur.com/oFCas.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oFCas.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/WC5iX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WC5iX.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/8iHEU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8iHEU.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74613795,
"author": "Mike Brind",
"author_id": 134725,
"author_profile": "https://Stackoverflow.com/users/134725",
"pm_score": 0,
"selected": false,
"text": "#OwnerNav a $('body').on('click', '#OwnerNav a', function (e) {\n // \n"
},
{
"answer_id": 74623254,
"author": "Qing Guo",
"author_id": 17124525,
"author_profile": "https://Stackoverflow.com/users/17124525",
"pm_score": 2,
"selected": true,
"text": "// autofill the inputs\n function displayOwnerInfo(id) {\n $.ajax({\n url: \"Index/?handler=DisplayOwnerInfo&value=\" + id,\n type: \"GET\", \n success: function (data) { \n $(\"#DateOfBirth\").val(data.dateOfBirth); \n $(\"#DriversLicenseNumber\").val(data.driversLicenseNumber); \n }\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74613105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9748930/"
] |
74,613,106
|
<p>web.php</p>
<pre><code><?php
use App\Http\Controllers\settingsController\seoController;
use App\Http\Controllers\settingsController\contactController;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\generalController\generalRoutes;
use App\Http\Controllers\settingsController\usersController;
Route::controller(generalRoutes::class)->group(function () {
Route::get('/', 'index')->name('index');
Route::get('/getNews', 'getNews');
});
Route::prefix('settings')->group(function () {
Route::controller(contactController::class)->group(function () {
Route::get('/contact', 'index')->name('contactIndex');
Route::post('/contact/update/general', 'generalContactUpdate')->name('generalSContactUpdate');
Route::post('/contact/update/html', 'staticHtmlUpdate')->name('staticHtmlUpdate');
});
});
</code></pre>
<p>contactController</p>
<pre><code><?php
namespace App\Http\Controllers\settingsController;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class contactController extends Controller
{
public function index(){
$data = Settings::find(1);
return view('settings.contact',compact('data'));
}
</code></pre>
<p>I wanted create contactController, I had this problem before</p>
<pre><code>Class "App\Http\Controllers\settingsController\contactController" not found
</code></pre>
<p><a href="https://i.stack.imgur.com/6clNk.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>I solve it but now it gives settingsController error
<code>Class "App\Http\Controllers\settingsController\Settings" not found</code>
Please help me))</p>
<p>I want create contactController but it gives settingsController problem</p>
|
[
{
"answer_id": 74613787,
"author": "HeroCode",
"author_id": 20211897,
"author_profile": "https://Stackoverflow.com/users/20211897",
"pm_score": 1,
"selected": false,
"text": "Use App\\Http\\Controllers\\settingsController\\contactController.php;\n"
},
{
"answer_id": 74613929,
"author": "EWW",
"author_id": 20587602,
"author_profile": "https://Stackoverflow.com/users/20587602",
"pm_score": 1,
"selected": true,
"text": "namespace App\\Http\\Controllers;\n \"App\\Http\\Controllers\\settingsController\\Settings\" not found use App\\Models\\Settings;\n $data = Settings::find($id);\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74613106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20590700/"
] |
74,613,117
|
<p>I am trying to read the data from CSV file which has 2200000 records using PowerShell and storing each record in JSON file, but this takes almost 12 hours.</p>
<p><strong>Sample CSV Data:</strong></p>
<p>We will only concern about the 1st column value's.</p>
<p><a href="https://i.stack.imgur.com/dxK7y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dxK7y.png" alt="enter image description here" /></a></p>
<p><strong>Code:</strong></p>
<pre><code>function Read-IPData
{
$dbFilePath = Get-ChildItem -Path $rootDir -Filter "IP2*.CSV" | ForEach-Object{ $_.FullName }
Write-Host "file path - $dbFilePath"
Write-Host "Reading..."
$data = Get-Content -Path $dbFilePath | Select-Object -Skip 1
Write-Host "Reading data finished"
$count = $data.Count
Write-host "Total $count records found"
return $data
}
function Convert-NumbetToIP
{
param(
[Parameter(Mandatory=$true)][string]$number
)
try
{
$w = [int64]($number/16777216)%256
$x = [int64]($number/65536)%256
$y = [int64]($number/256)%256
$z = [int64]$number%256
$ipAddress = "$w.$x.$y.$z"
Write-Host "IP Address - $ipAddress"
return $ipAddress
}
catch
{
Write-Host "$_"
continue
}
}
Write-Host "Getting IP Addresses from $dbFileName"
$data = Read-IPData
Write-Host "Checking whether output.json file exist, if not create"
$outputFile = Join-Path -Path $rootDir -ChildPath "output.json"
if(!(Test-Path $outputFile))
{
Write-Host "$outputFile doestnot exist, creating..."
New-Item -Path $outputFile -type "file"
}
foreach($item in $data)
{
$row = $item -split ","
$ipNumber = $row[0].trim('"')
Write-Host "Converting $ipNumber to ipaddress"
$toIpAddress = Convert-NumbetToIP -number $ipNumber
Write-Host "Preparing document JSON"
$object = [PSCustomObject]@{
"ip-address" = $toIpAddress
"is-vpn" = "true"
"@timestamp" = (Get-Date).ToString("o")
}
$document = $object | ConvertTo-Json -Compress -Depth 100
Write-Host "Adding document - $document"
Add-Content -Path $outputFile $document
}
</code></pre>
<p>Could you please help optimize the code or is there a better way to do it. or is there a way like multi-threading.</p>
|
[
{
"answer_id": 74616405,
"author": "zett42",
"author_id": 7571258,
"author_profile": "https://Stackoverflow.com/users/7571258",
"pm_score": 3,
"selected": true,
"text": "function Get-IPDataPath\n{\n $dbFilePath = Get-ChildItem -Path $rootDir -Filter \"IP2*.CSV\" | ForEach-Object FullName | Select-Object -First 1\n Write-Host \"file path - $dbFilePath\"\n $dbFilePath # implicit output\n}\n\nfunction Convert-NumberToIP\n{\n param(\n [Parameter(Mandatory=$true)][string]$number\n )\n\n [Int64] $numberInt = 0\n if( [Int64]::TryParse( $number, [ref] $numberInt ) ) {\n if( ($numberInt -ge 0) -and ($numberInt -le 0xFFFFFFFFl) ) {\n # Convert to IP address like '192.168.23.42'\n ([IPAddress] $numberInt).ToString()\n }\n }\n # In case TryParse() returns $false or the number is out of range for an IPv4 address, \n # the output of this function will be empty, which converts to $false in a boolean context.\n}\n\n$dbFilePath = Get-IPDataPath\n$outputFile = Join-Path -Path $rootDir -ChildPath \"output.json\"\n\nWrite-Host \"Converting CSV file $dbFilePath to $outputFile\"\n\n$object = [PSCustomObject]@{\n 'ip-address' = ''\n 'is-vpn' = 'true'\n '@timestamp' = ''\n}\n\n# Enclose foreach loop in a script block to be able to pipe its output to Set-Content\n& {\n foreach( $item in [Linq.Enumerable]::Skip( [IO.File]::ReadLines( $dbFilePath ), 1 ) )\n {\n $row = $item -split ','\n $ipNumber = $row[0].trim('\"')\n\n if( $ip = Convert-NumberToIP -number $ipNumber ) \n {\n $object.'ip-address' = $ip\n $object.'@timestamp' = (Get-Date).ToString('o')\n\n # Implicit output\n $object | ConvertTo-Json -Compress -Depth 100\n }\n\n }\n} | Set-Content -Path $outputFile\n Get-Content File.ReadLines Linq.Enumerable.Skip() ReadLines foreach try catch Int64.TryParse() boolean IPAddress .GetAddressBytes() -join [pscustomobject] Write-Host New-Item Set-Content [ ] , & {\n '[' # begin array\n $first = $true\n\n foreach( $item in [Linq.Enumerable]::Skip( [IO.File]::ReadLines( $dbFilePath ), 1 ) )\n {\n $row = $item -split ','\n $ipNumber = $row[0].trim('\"')\n\n if( $ip = Convert-NumberToIP -number $ipNumber ) \n {\n $object.'ip-address' = $ip\n $object.'@timestamp' = (Get-Date).ToString('o')\n \n $row = $object | ConvertTo-Json -Compress -Depth 100\n\n # write array element delimiter if necessary\n if( $first ) { $row; $first = $false } else { \",$row\" } \n }\n\n }\n ']' # end array\n} | Set-Content -Path $outputFile\n"
},
{
"answer_id": 74617254,
"author": "Theo",
"author_id": 9898643,
"author_profile": "https://Stackoverflow.com/users/9898643",
"pm_score": 1,
"selected": false,
"text": "function Convert-NumberToIP {\n param(\n [Parameter(Mandatory=$true)][uint32]$number\n )\n\n # either do the math yourself like this:\n\n # $w = ($number -shr 24) -band 255\n # $x = ($number -shr 16) -band 255\n # $y = ($number -shr 8) -band 255\n # $z = $number -band 255\n # '{0}.{1}.{2}.{3}' -f $w, $x, $y, $z # output the dotted IP string\n\n # or use .Net:\n $n = ([IPAddress]$number).GetAddressBytes()\n [array]::Reverse($n)\n ([IPAddress]$n).IPAddressToString\n}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74613117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6607106/"
] |
74,613,121
|
<p>I am trying to use a stored function I have written in Postgresql as a data source for a Power BI chart.
The function accepts four parameters all of date type. The function signature looks like this:</p>
<p><code>get_revenue_metrics(signup_start_date, signup_end_date, revenue_start_date, revenue_end_date)</code></p>
<p>This function uses these dates in multiple where clauses to create and return a table. I want to use that table to then build charts in my dashboard.</p>
<p>I did come across <a href="https://community.powerbi.com/t5/Desktop/SQL-Functions-in-Power-BI/m-p/235426#M104804" rel="nofollow noreferrer">this link</a> which talks about using a SQL function in Power BI, but it is for Azure SQL Server and not Postgresql. From the very first step as mentioned in the link before, I do not see any option to</p>
<blockquote>
<p>Select the sql function when you initially select your data sources.</p>
</blockquote>
<p>Is there something I am missing?
Thanks for the help!</p>
|
[
{
"answer_id": 74616405,
"author": "zett42",
"author_id": 7571258,
"author_profile": "https://Stackoverflow.com/users/7571258",
"pm_score": 3,
"selected": true,
"text": "function Get-IPDataPath\n{\n $dbFilePath = Get-ChildItem -Path $rootDir -Filter \"IP2*.CSV\" | ForEach-Object FullName | Select-Object -First 1\n Write-Host \"file path - $dbFilePath\"\n $dbFilePath # implicit output\n}\n\nfunction Convert-NumberToIP\n{\n param(\n [Parameter(Mandatory=$true)][string]$number\n )\n\n [Int64] $numberInt = 0\n if( [Int64]::TryParse( $number, [ref] $numberInt ) ) {\n if( ($numberInt -ge 0) -and ($numberInt -le 0xFFFFFFFFl) ) {\n # Convert to IP address like '192.168.23.42'\n ([IPAddress] $numberInt).ToString()\n }\n }\n # In case TryParse() returns $false or the number is out of range for an IPv4 address, \n # the output of this function will be empty, which converts to $false in a boolean context.\n}\n\n$dbFilePath = Get-IPDataPath\n$outputFile = Join-Path -Path $rootDir -ChildPath \"output.json\"\n\nWrite-Host \"Converting CSV file $dbFilePath to $outputFile\"\n\n$object = [PSCustomObject]@{\n 'ip-address' = ''\n 'is-vpn' = 'true'\n '@timestamp' = ''\n}\n\n# Enclose foreach loop in a script block to be able to pipe its output to Set-Content\n& {\n foreach( $item in [Linq.Enumerable]::Skip( [IO.File]::ReadLines( $dbFilePath ), 1 ) )\n {\n $row = $item -split ','\n $ipNumber = $row[0].trim('\"')\n\n if( $ip = Convert-NumberToIP -number $ipNumber ) \n {\n $object.'ip-address' = $ip\n $object.'@timestamp' = (Get-Date).ToString('o')\n\n # Implicit output\n $object | ConvertTo-Json -Compress -Depth 100\n }\n\n }\n} | Set-Content -Path $outputFile\n Get-Content File.ReadLines Linq.Enumerable.Skip() ReadLines foreach try catch Int64.TryParse() boolean IPAddress .GetAddressBytes() -join [pscustomobject] Write-Host New-Item Set-Content [ ] , & {\n '[' # begin array\n $first = $true\n\n foreach( $item in [Linq.Enumerable]::Skip( [IO.File]::ReadLines( $dbFilePath ), 1 ) )\n {\n $row = $item -split ','\n $ipNumber = $row[0].trim('\"')\n\n if( $ip = Convert-NumberToIP -number $ipNumber ) \n {\n $object.'ip-address' = $ip\n $object.'@timestamp' = (Get-Date).ToString('o')\n \n $row = $object | ConvertTo-Json -Compress -Depth 100\n\n # write array element delimiter if necessary\n if( $first ) { $row; $first = $false } else { \",$row\" } \n }\n\n }\n ']' # end array\n} | Set-Content -Path $outputFile\n"
},
{
"answer_id": 74617254,
"author": "Theo",
"author_id": 9898643,
"author_profile": "https://Stackoverflow.com/users/9898643",
"pm_score": 1,
"selected": false,
"text": "function Convert-NumberToIP {\n param(\n [Parameter(Mandatory=$true)][uint32]$number\n )\n\n # either do the math yourself like this:\n\n # $w = ($number -shr 24) -band 255\n # $x = ($number -shr 16) -band 255\n # $y = ($number -shr 8) -band 255\n # $z = $number -band 255\n # '{0}.{1}.{2}.{3}' -f $w, $x, $y, $z # output the dotted IP string\n\n # or use .Net:\n $n = ([IPAddress]$number).GetAddressBytes()\n [array]::Reverse($n)\n ([IPAddress]$n).IPAddressToString\n}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74613121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20632158/"
] |
74,613,194
|
<p>I have a str =<code> /posts/03faf64d3-4a838-9cf474ee66ed/show</code></p>
<p>I would like to extract<code> 03faf64d3-4a838-9cf474ee66ed</code> and and store it into a variable
how can I do that</p>
|
[
{
"answer_id": 74613236,
"author": "Andriu1510",
"author_id": 17238007,
"author_profile": "https://Stackoverflow.com/users/17238007",
"pm_score": 1,
"selected": false,
"text": "var str = \"/posts/03faf64d3-4a838-9cf474ee66ed/show\";\nvar result = str.split(\"/\")[2]\n"
},
{
"answer_id": 74613264,
"author": "Loránd Péter",
"author_id": 6146963,
"author_profile": "https://Stackoverflow.com/users/6146963",
"pm_score": 0,
"selected": false,
"text": "split / const str = '/posts/03faf64d3-4a838-9cf474ee66ed/show';\nconst parts = str.split('/');\nconst id = parts[2]; // contains your uuid\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74613194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16565052/"
] |
74,613,237
|
<p>I need to write a script in Python which will transform bad input from user to float number.</p>
<p>For example
"10,123.20 Kč" to "10123.2"
"10.023,123.45 Kč" to "10023123.45"
"20 743 210.2 Kč" to "20743210.2"
or any other bad input - this is what I've come up with.</p>
<p>Kč is Czech koruna.</p>
<p>My thought process was to get rid of any spaces, letters. Then change every comma to dot to make numbers looks like "123.123.456.78" then delete all dots except of last one in a string and then change it to float so it would looks like "123123456.78". But I don't know how to do it. If you know any faster and easier way to do it, I would like to know.</p>
<p>This is what I have and I'm lost now.</p>
<pre><code>import re
my_list = ['100,30 Kč','10 000,00 Kč', '10,000.00 Kč', '10000 Kč', '32.100,30 Kč', '12.345,678.91 Kč']
for i in my_list:
ws = i.replace("Kč", '')
x = re.sub(',','.', ws).replace(" ","")
print(x)
</code></pre>
|
[
{
"answer_id": 74613410,
"author": "alec_djinn",
"author_id": 3190076,
"author_profile": "https://Stackoverflow.com/users/3190076",
"pm_score": 0,
"selected": false,
"text": "def parse_entry(entry):\n\n #remove currency and spaces\n entry = entry.replace(\"Kč\", \"\")\n entry = entry.replace(\" \", \"\")\n\n #check if a comma is used for decimals or thousands\n comma_i = entry.find(\",\")\n if len(entry[comma_i:]) > 3: #it's a thousands separator, it can be removed\n entry = entry.replace(\",\", \"\")\n else: #it's a decimal separator\n entry = entry.replace(\",\", \".\") #convert it to dot\n\n #remove extra dots\n while entry.count(\".\") > 1:\n entry = entry.replace(\".\", \"\", 1) #replace once\n return round(float(entry), 1) #round to 1 decimal\n\nmy_list = ['100,30 Kč','10 000,00 Kč', '10,000.00 Kč', '10000 Kč', '32.100,30 Kč', '12.345,678.91 Kč']\nparsed = list(map(parse_entry, my_list))\nprint(parsed) #[100.3, 10000.0, 10000.0, 10000.0, 32100.3, 12345678.9]\n"
},
{
"answer_id": 74613434,
"author": "Bob",
"author_id": 12750353,
"author_profile": "https://Stackoverflow.com/users/12750353",
"pm_score": 2,
"selected": true,
"text": "import re\n\nmy_list = ['100,30 Kč','10 000,00 Kč', '10,000.00 Kč', '10000 Kč', '32.100,30 Kč', '12.345,678.91 Kč']\n\nfor s in my_list:\n parts = list(re.findall('\\d+', s))\n if len(parts) == 1 or len(parts[-1]) != 2:\n parts.append('0')\n print(float(''.join(parts[:-1]) + '.' + parts[-1]))\n"
},
{
"answer_id": 74613457,
"author": "alphaBetaGamma",
"author_id": 12959241,
"author_profile": "https://Stackoverflow.com/users/12959241",
"pm_score": 0,
"selected": false,
"text": "import re\n\nmy_list = ['100,30 Kč','10 000,00 Kč', '10,000.00 Kč', '10000 Kč', '32.100,30 Kč', '12.345,678.91 Kč']\n\nfor i in my_list:\n ws = i.replace(\"Kč\", '')\n x = re.sub(',','.', ws).replace(\" \",\"\")\n \n if len( x.split(\".\"))>1:\n end= x.split(\".\")[-1]\n x = \"\".join([i for i in x.split(\".\")[:-1]])+\".\"+end\n print(x)\n"
},
{
"answer_id": 74613680,
"author": "gvee",
"author_id": 2610022,
"author_profile": "https://Stackoverflow.com/users/2610022",
"pm_score": 0,
"selected": false,
"text": "import re\n\nvalues = [\n \"100,30 Kč\",\n \"10 000,00 Kč\",\n \"10,000.00 Kč\",\n \"10000 Kč\",\n \"32.100,30 Kč\",\n \"12.345,678.91 Kč\", # This value is a bit odd... is it _right_?\n]\n\nfor value in values:\n # Remove any character that's not a number or a comma\n value = re.sub(\"[^0-9,]\", \"\", value)\n\n # Replace remaining commas with periods\n value = value.replace(\",\", \".\")\n\n # Convert from string to number\n value = float(value)\n\n print(value)\n 100.3\n10000.0\n10.0\n10000.0\n32100.3\n12345.67891\n"
},
{
"answer_id": 74613983,
"author": "Cobra",
"author_id": 17580381,
"author_profile": "https://Stackoverflow.com/users/17580381",
"pm_score": 0,
"selected": false,
"text": "my_list = ['100,30 Kč','10 000,00 Kč', '10,000.00 Kč', '10000 Kč', '32.100,30 Kč', '12.345,678.91 Kč']\n\ndef fix(s):\n r = []\n for c in s:\n if c in '0123456789':\n r.append(c)\n elif c == ',':\n r.append('.')\n elif not c in '. ':\n break\n return float(''.join(r))\n\nfor n in my_list:\n print(fix(n))\n 100.3\n10000.0\n10.0\n10000.0\n32100.3\n12345.67891\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74613237",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20632408/"
] |
74,613,294
|
<p>I am converting sensor data to byte and writing a byte array from an arduino to a TCP server made with Python, but somehow the sensor data which are in the array triggers variations of the UTF-8 errors displayed below when decoded.</p>
<p><code>UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte</code>
<code>UnicodeDecodeError: 'utf-8' codec can't decode byte 0xcf in position 1: invalid continuation byte</code></p>
<p>Where "0xcf" and "0xff" change from error to error.</p>
<p>I suspect this is because the sensor data can sometimes be negative values. I know a byte cannot hold a negative number and UTF-8 can do 0-256. I think I must send a dedicated "-" sign before the negative values. However, I cannot predict when the negative values occur. Therefore, there must be a better way of doing this. I am able to send the array of bytes without decoding it, but I suspect there are some problems here as well because the two first positions should hold different values than the remaining 6 positions, as shown below:
<code>b'\xff\x00\x00\x00\x00\x00\x00\x00' b'\x02\x00\x00\x00\x00\x00\x00\x00'</code></p>
<p>My question is: how can I send negative values as byte and decode it correctly.</p>
<p>For context I will attach my code.
Arduino Client:
`</p>
<pre><code>#include <Ethernet.h>
#include <SPI.h>
#include "AK09918.h"
#include "ICM20600.h"
#include <Wire.h>
//----------------------------------
//tiltsensor
AK09918_err_type_t err;
int32_t x, y, z;
AK09918 ak09918;
ICM20600 icm20600(true);
int16_t acc_x, acc_y, acc_z;
int32_t offset_x, offset_y, offset_z;
double roll, pitch;
//----------------------------------
//Ethernet
byte mac[] = { 0xBE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //not important if only one ethernet shield
byte ip[] = { 192, 168, X, X}; //IP of this arduino unit
byte server[] = { 192, 168, X, X}; //IP of server you want to contact
int tcp_port = 65432; // a nice port to send/acess the information on
EthernetClient client;
//----------------------------------
//byte array
byte array[8] = {0, 0, 0, 0, 0, 0, 0, 0};
//----------------------------------
void setup()
{
//tiltsensor
Wire.begin();
err = ak09918.initialize();
icm20600.initialize();
ak09918.switchMode(AK09918_POWER_DOWN);
ak09918.switchMode(AK09918_CONTINUOUS_100HZ);
Serial.begin(9600);
err = ak09918.isDataReady();
while (err != AK09918_ERR_OK) {
Serial.println("Waiting Sensor");
delay(100);
err = ak09918.isDataReady();}
Serial.println("Start figure-8 calibration after 2 seconds.");
delay(2000);
//calibrate(10000, &offset_x, &offset_y, &offset_z);
Serial.println("");
//----------------------------------
//Ethernet
Ethernet.begin(mac, ip);
//Serial.begin(9600);
delay(1000);
Serial.println("Connecting...");
if (client.connect(server, tcp_port)) { // Connection to server
Serial.println("Connected to server.js");
client.println();}
else {
Serial.println("connection failed");}
//----------------------------------
}
void loop()
{
//tiltsensor
acc_x = icm20600.getAccelerationX();
acc_y = icm20600.getAccelerationY();
acc_z = icm20600.getAccelerationZ();
roll = atan2((float)acc_y, (float)acc_z) * 57.3;
pitch = atan2(-(float)acc_x, sqrt((float)acc_y * acc_y + (float)acc_z * acc_z)) * 57.3;
//----------------------------------
//bytearray
array[0] = byte(roll);
array[1] = byte(pitch);
//----------------------------------
//test
Serial.write(array, 8);
Serial.println();
delay(500);
//----------------------------------
//Ethernet
if (client.available()) {
//client.print(array);
//client.write(array[0]);
client.write(array, 8);
//client.write(array, 8);//((uint8_t*) array, sizeof(array));
delay(3000);
}
if (!client.connected()) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
for(;;)
;
}
//----------------------------------
}
</code></pre>
<p>`</p>
<p>TCP server (python):</p>
<p>`</p>
<pre><code># echo-server.py
import time
import socket
HOST = "192.168.X.X" # Standard loopback interface address (localhost)
PORT = 65432 # Port to listen on (non-privileged ports are > 1023)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
print(f"Connected by {addr}")
while True:
data = conn.recv(1024)
#msg = s.recv(1024)
#print(msg.decode("utf-8"))
print(data.decode("utf-8"))
#time.sleep(3)
#conn.sendall(data)
if not data:
break
conn.send(data)
</code></pre>
<p>`</p>
<p>I am able to establish a connection to the server and the client can write to it.
However, I get <code>UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa4 in position 0: invalid start byte</code> type errors.</p>
|
[
{
"answer_id": 74613410,
"author": "alec_djinn",
"author_id": 3190076,
"author_profile": "https://Stackoverflow.com/users/3190076",
"pm_score": 0,
"selected": false,
"text": "def parse_entry(entry):\n\n #remove currency and spaces\n entry = entry.replace(\"Kč\", \"\")\n entry = entry.replace(\" \", \"\")\n\n #check if a comma is used for decimals or thousands\n comma_i = entry.find(\",\")\n if len(entry[comma_i:]) > 3: #it's a thousands separator, it can be removed\n entry = entry.replace(\",\", \"\")\n else: #it's a decimal separator\n entry = entry.replace(\",\", \".\") #convert it to dot\n\n #remove extra dots\n while entry.count(\".\") > 1:\n entry = entry.replace(\".\", \"\", 1) #replace once\n return round(float(entry), 1) #round to 1 decimal\n\nmy_list = ['100,30 Kč','10 000,00 Kč', '10,000.00 Kč', '10000 Kč', '32.100,30 Kč', '12.345,678.91 Kč']\nparsed = list(map(parse_entry, my_list))\nprint(parsed) #[100.3, 10000.0, 10000.0, 10000.0, 32100.3, 12345678.9]\n"
},
{
"answer_id": 74613434,
"author": "Bob",
"author_id": 12750353,
"author_profile": "https://Stackoverflow.com/users/12750353",
"pm_score": 2,
"selected": true,
"text": "import re\n\nmy_list = ['100,30 Kč','10 000,00 Kč', '10,000.00 Kč', '10000 Kč', '32.100,30 Kč', '12.345,678.91 Kč']\n\nfor s in my_list:\n parts = list(re.findall('\\d+', s))\n if len(parts) == 1 or len(parts[-1]) != 2:\n parts.append('0')\n print(float(''.join(parts[:-1]) + '.' + parts[-1]))\n"
},
{
"answer_id": 74613457,
"author": "alphaBetaGamma",
"author_id": 12959241,
"author_profile": "https://Stackoverflow.com/users/12959241",
"pm_score": 0,
"selected": false,
"text": "import re\n\nmy_list = ['100,30 Kč','10 000,00 Kč', '10,000.00 Kč', '10000 Kč', '32.100,30 Kč', '12.345,678.91 Kč']\n\nfor i in my_list:\n ws = i.replace(\"Kč\", '')\n x = re.sub(',','.', ws).replace(\" \",\"\")\n \n if len( x.split(\".\"))>1:\n end= x.split(\".\")[-1]\n x = \"\".join([i for i in x.split(\".\")[:-1]])+\".\"+end\n print(x)\n"
},
{
"answer_id": 74613680,
"author": "gvee",
"author_id": 2610022,
"author_profile": "https://Stackoverflow.com/users/2610022",
"pm_score": 0,
"selected": false,
"text": "import re\n\nvalues = [\n \"100,30 Kč\",\n \"10 000,00 Kč\",\n \"10,000.00 Kč\",\n \"10000 Kč\",\n \"32.100,30 Kč\",\n \"12.345,678.91 Kč\", # This value is a bit odd... is it _right_?\n]\n\nfor value in values:\n # Remove any character that's not a number or a comma\n value = re.sub(\"[^0-9,]\", \"\", value)\n\n # Replace remaining commas with periods\n value = value.replace(\",\", \".\")\n\n # Convert from string to number\n value = float(value)\n\n print(value)\n 100.3\n10000.0\n10.0\n10000.0\n32100.3\n12345.67891\n"
},
{
"answer_id": 74613983,
"author": "Cobra",
"author_id": 17580381,
"author_profile": "https://Stackoverflow.com/users/17580381",
"pm_score": 0,
"selected": false,
"text": "my_list = ['100,30 Kč','10 000,00 Kč', '10,000.00 Kč', '10000 Kč', '32.100,30 Kč', '12.345,678.91 Kč']\n\ndef fix(s):\n r = []\n for c in s:\n if c in '0123456789':\n r.append(c)\n elif c == ',':\n r.append('.')\n elif not c in '. ':\n break\n return float(''.join(r))\n\nfor n in my_list:\n print(fix(n))\n 100.3\n10000.0\n10.0\n10000.0\n32100.3\n12345.67891\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74613294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20631974/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.