content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
How can I get the start and end indices of a note in a volume graph?
I am trying to make a program, that tells me when a note has been pressed.
I have the following notes exported as a .wav file (The C Major Scale 4 times with different rhythms, dynamics and in different octaves):
I can get the volumes of my soun... | How can I get the start and end indices of a note in a volume graph? | I am trying to make a program, that tells me when a note has been pressed.
I have the following notes exported as a .wav file (The C Major Scale 4 times with different rhythms, dynamics and in different octaves):
I can get the volumes of my sound file using the following code:
from scipy.io import wavfile
def get_vol... | [
"think this is what you need:\nfirst you convert negative numbers into positive ones and smooth the line to eliminate noise, to find the lower peaks yo work with the negative values.\nfrom scipy.io import wavfile\nimport matplotlib.pyplot as plt\nfrom scipy.signal import find_peaks\nimport numpy as np\nfrom scipy.s... | [
1,
1
] | [] | [] | [
"audio",
"frequency",
"pyaudio",
"python",
"volume"
] | stackoverflow_0074491739_audio_frequency_pyaudio_python_volume.txt |
Q:
getting standard deviation of the values in two different dataframes
I have two DataFrames and I would like to find the standard deviation per rc_id for one of the columns i.e. imapcted_userscolumn in these two dataframes and create a separate column with the name std with their standard deviation value
df1 :
data... | getting standard deviation of the values in two different dataframes | I have two DataFrames and I would like to find the standard deviation per rc_id for one of the columns i.e. imapcted_userscolumn in these two dataframes and create a separate column with the name std with their standard deviation value
df1 :
data = {"timestamp":["2022-10-29","2022-10-29","2022-10-29","2022-10-29","2022... | [
"IIUC use concat with aggregate std, but because pandas Series.std has default ddof=1 for expected ouput add parameter ddof=0, last append to df1:\ndf1 = df1.groupby([\"timestamp\",\"rc_id\"], as_index=False, sort=False)[\"impacted_users\"].sum()\n \ndf = (df1.join(pd.concat([df1, df2])\n ... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074527590_pandas_python.txt |
Q:
Visual Studio Code - problem about running code
Im new and I started to learn python some time ago but today I have small problem about running code in Visual Studio Code.
When i try to run code then i got:enter image description here
Can you explane me why i got this? And how can I fix it?
I tried nothing and i j... | Visual Studio Code - problem about running code | Im new and I started to learn python some time ago but today I have small problem about running code in Visual Studio Code.
When i try to run code then i got:enter image description here
Can you explane me why i got this? And how can I fix it?
I tried nothing and i just expect fast answer
| [
"First of all you are not running the code but debugging the code. What you show in the picture is just some powershell commands to debug the code.\nBecause vscode uses the system's built-in terminal (power shell or cmd), the execution command is displayed when you run or debug the code. The advantage of this is th... | [
0
] | [] | [] | [
"python",
"visual_studio_code"
] | stackoverflow_0074523988_python_visual_studio_code.txt |
Q:
How to put multiple user inputs in a text file?
this is the code I have right now
fname = input(">>Please Enter a file name followed by .txt ")
def writedata():
i=0
for i in range(3):
f = open(f"{fname}", 'w')
stdname = input('>>\tStudent Name: \t')
marks = input('>>\tMark for exam: \t')
f.writ... | How to put multiple user inputs in a text file? | this is the code I have right now
fname = input(">>Please Enter a file name followed by .txt ")
def writedata():
i=0
for i in range(3):
f = open(f"{fname}", 'w')
stdname = input('>>\tStudent Name: \t')
marks = input('>>\tMark for exam: \t')
f.write(stdname)
f.write("\n")
f.write(marks)
f.clo... | [
"Please take note of\n f = open(f\"{fname}\", 'w')\n\nYou are using the w mode, which overwrites the file everytime. Instead, use a+ mode, which appends to the file, and creates the file if it does not yet exist.\n",
" fname = str(input(\">> Please Enter a file name, followed by .txt: \"))\n f = open(f\"{fna... | [
0,
0
] | [
"You are using the write (w) file method, which overwrites your file with any new data you pass. You need the append (a) file method, which will append to your file each time.\nThe BSD fopen manpage defines the file methods as follows:\nThe argument mode points to a string beginning with one of the following\n sequ... | [
-2
] | [
"python",
"python_3.x"
] | stackoverflow_0074521467_python_python_3.x.txt |
Q:
EmptyDataError No columns to parse from file
i am getting the error "EmptyDataError No columns to parse from file" when i am reading the data from csv file to json file...
i want to insert the data from csv file to json file
A:
replace "/" to "\" in you path variable
A:
find error and used "delim_whitespace=Tr... | EmptyDataError No columns to parse from file | i am getting the error "EmptyDataError No columns to parse from file" when i am reading the data from csv file to json file...
i want to insert the data from csv file to json file
| [
"replace \"/\" to \"\\\" in you path variable\n",
"find error and used \"delim_whitespace=True\" in read_csv\n"
] | [
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074528070_pandas_python.txt |
Q:
How can I classify a string with a partial string and make a boolean column
Say I have the 1st dataframe with the following strings
a
abcd
dabcd
qwerty
oppoupou
Then I have a 2nd dataframe with the following substrings
column
abc
qw
qaz
I've been looking for a code that can classify the 1st dataframe and check e... | How can I classify a string with a partial string and make a boolean column | Say I have the 1st dataframe with the following strings
a
abcd
dabcd
qwerty
oppoupou
Then I have a 2nd dataframe with the following substrings
column
abc
qw
qaz
I've been looking for a code that can classify the 1st dataframe and check each row with all the elements in the 2nd dataframe with a true or false solution.... | [
"You need join values of column col in second DataFrame by | for regex OR:\ndf[\"b\"] = df[\"a\"].str.contains('|'.join(df2['column']))\nprint (df)\n a b\n0 abcd True\n1 dabcd True\n2 qwerty True\n3 oppoupou False\n\n"
] | [
2
] | [] | [] | [
"boolean",
"dataframe",
"pandas",
"python",
"string"
] | stackoverflow_0074528289_boolean_dataframe_pandas_python_string.txt |
Q:
How to split numbers in string type column?
I have a dataframe with column df['EVENT_DTL'] that looks like this;
1. ๋ณ์ฌ์ ์ ๋ณด : Kim_******-1****** 2. ๋ฐ๊ฒฌ์ผ์ : 2013๋
05์18์ผ 13:00 3. ๋ฐ๊ฒฌ์ฅ์ : 1) ์์ฌ๊ธฐ๋ก ์ ์ฃผ์ ์ฃผ๋ฏผ๋ฑ๋ก์ ์ฃผ์ : ์ค๊ฑฐ์ฃผ์ง ์ฃผ์ : ์๋(๋ฐ๊ฒฌ)์ฅ์ ์ฃผ์ : 2) ์ค์ ์กฐ์ฌ์์ด ์
๋ ฅํ ์ฃผ์์ฃผ๋ฏผ๋ฑ๋ก์ ์ฃผ์ : ์ค๊ฑฐ์ฃผ์ง ์ฃผ์ : ์๋(๋ฐ๊ฒฌ)์ฅ์ ์ฃผ์ : ์กฐ์น(์ฌ์ ํฌํจ) : 4. ๋ฐ๊ฒฌ์ฅ์ ์ฝ๋ฉ์ฌ์ : ์ํ / ... | How to split numbers in string type column? | I have a dataframe with column df['EVENT_DTL'] that looks like this;
1. ๋ณ์ฌ์ ์ ๋ณด : Kim_******-1****** 2. ๋ฐ๊ฒฌ์ผ์ : 2013๋
05์18์ผ 13:00 3. ๋ฐ๊ฒฌ์ฅ์ : 1) ์์ฌ๊ธฐ๋ก ์ ์ฃผ์ ์ฃผ๋ฏผ๋ฑ๋ก์ ์ฃผ์ : ์ค๊ฑฐ์ฃผ์ง ์ฃผ์ : ์๋(๋ฐ๊ฒฌ)์ฅ์ ์ฃผ์ : 2) ์ค์ ์กฐ์ฌ์์ด ์
๋ ฅํ ์ฃผ์์ฃผ๋ฏผ๋ฑ๋ก์ ์ฃผ์ : ์ค๊ฑฐ์ฃผ์ง ์ฃผ์ : ์๋(๋ฐ๊ฒฌ)์ฅ์ ์ฃผ์ : ์กฐ์น(์ฌ์ ํฌํจ) : 4. ๋ฐ๊ฒฌ์ฅ์ ์ฝ๋ฉ์ฌ์ : ์ํ / 5. ๋ฐฉ๋ฒ/์๋จ : ๋ชฉ๋งค๋ฌ๊ธฐ6. ๋ฐ๊ฒฌ๊ฒฝ์ : 2013.5.18 13:00๊ฒฝ New Yor... | [
"df['EVENT_DTL'] = \"\\n\" + df['EVENT_DTL'].astype(str)\n",
"You can use replace in pandas with setting regex=True:\ndf['EVENT_DTL'].replace(r\"(\\d+[\\.|\\)] )\", r\"\\n\\1\", regex=True)\n\nThe regex will match any subsequences starting with a number (\\d+) with either a . or ) afterwards ([\\.|\\)]) and then ... | [
0,
0,
0
] | [] | [] | [
"numpy",
"pandas",
"python",
"regex"
] | stackoverflow_0074528041_numpy_pandas_python_regex.txt |
Q:
How to assign variables to a value in text file and check if it satisfies a given condition?
I have a file in.txt
name="XYZ_PP_0" number="0x12" bytesize="4" info="0x0000001A"
name="GK_LMP_2_0" number="0xA5" bytesize="8" info="0x00000000bbae321f"
name="MP_LKO_1_0" number="0x356" bytesize="4" info="0x00000234"
I ne... | How to assign variables to a value in text file and check if it satisfies a given condition? | I have a file in.txt
name="XYZ_PP_0" number="0x12" bytesize="4" info="0x0000001A"
name="GK_LMP_2_0" number="0xA5" bytesize="8" info="0x00000000bbae321f"
name="MP_LKO_1_0" number="0x356" bytesize="4" info="0x00000234"
I need to check whether it satisfies the condition that is check if info value of number "0x12" + 0x00... | [
"Break it into steps.\n\nLook up how to read in a text file, line by line. You'll end up with a list of lines of this file.\nFigure out how to extract the value from the \"number\" field. A simple regular expression would serve you well here I think.\n[Optional] Cast this value to the correct data type for your pr... | [
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074528356_python_python_3.x.txt |
Q:
How to crop an image given proportional coordinates with Python PIL?
I have an image with dimension (1920x1080) with proportional coordinates provided with a description of the detected person region. I want to crop only the detected person from the image using provided proportional coordinates. I looked up PIL cr... | How to crop an image given proportional coordinates with Python PIL? | I have an image with dimension (1920x1080) with proportional coordinates provided with a description of the detected person region. I want to crop only the detected person from the image using provided proportional coordinates. I looked up PIL crop documentation and tried the following:
Provided in the integration docu... | [
"But your drawing contradict your own description of what x0,y0,x1,y1 are. It is said (in a picture of text btw; it is preferable to avoid that) that x0,y0 is the lower right corner, and x1,y1 the upper left corner.\nJust invert x0,y0 and x1,y1.\nAlso, note fyi, that coordinates system in PIL (and generally speakin... | [
1
] | [] | [] | [
"computer_vision",
"image",
"image_processing",
"python",
"python_imaging_library"
] | stackoverflow_0074528174_computer_vision_image_image_processing_python_python_imaging_library.txt |
Q:
Setting function if cell contains string
I had a function that worked fine - it checks the title of a cell for a ipy.datagrid and then sets the color of the cell based on the header
def header_bg_color(cell):
if cell.value in ['Portfolio -30%','Change -30%']:
return '#f3722c'
elif cell.value in ['P... | Setting function if cell contains string | I had a function that worked fine - it checks the title of a cell for a ipy.datagrid and then sets the color of the cell based on the header
def header_bg_color(cell):
if cell.value in ['Portfolio -30%','Change -30%']:
return '#f3722c'
elif cell.value in ['Portfolio -20%','Change -20%']:
return ... | [
"you need to pass igwd_change variable inside the header_bg_color function as a parameter\ndef header_bg_color(cell):\n\nshould be\ndef header_bg_color(cell, igwd_change):\n\nNow when calling this function, make sure you pass the same variable\nheader_bg_color(cell, igwd_change)\n\nor\nheader_bg_color(cell, \"any c... | [
0
] | [] | [] | [
"function",
"python",
"string"
] | stackoverflow_0074522406_function_python_string.txt |
Q:
Un-structured nested JSON to CSV using python
structured nested JSON file that I need to use as a data frame(or CSV) to extract insight from the data.
Below is the sample of 1 part of the JSON.. i have more then 1million records with different details n feature..
what would be the right way to Parse this as a stru... | Un-structured nested JSON to CSV using python | structured nested JSON file that I need to use as a data frame(or CSV) to extract insight from the data.
Below is the sample of 1 part of the JSON.. i have more then 1million records with different details n feature..
what would be the right way to Parse this as a structure Table using Python
{
"CRD" : {
... | [
"you can use json_normalize:\nimport json\nyour_json=json.loads(your_json) #convert string to dict\n\ndf = pd.json_normalize(your_json).explode('CRD.DETAILS.PARADATA.FEATURES').reset_index(drop=True)\ndf = df.join(pd.json_normalize(df.pop('CRD.DETAILS.PARADATA.FEATURES'))).drop_duplicates()\n'''\n| | CRD.FG | ... | [
1
] | [] | [] | [
"json",
"pandas",
"python"
] | stackoverflow_0074528333_json_pandas_python.txt |
Q:
What is the correct way of traversing the following tree pre-oder?
Given the following parse tree:
In:
from nltk.parse import CoreNLPParser
from nltk.treeprettyprinter import TreePrettyPrinter
parser = CoreNLPParser(url='http://localhost:9000')
next(parser.raw_parse('What is the airspeed of an unladen swallow ?')... | What is the correct way of traversing the following tree pre-oder? | Given the following parse tree:
In:
from nltk.parse import CoreNLPParser
from nltk.treeprettyprinter import TreePrettyPrinter
parser = CoreNLPParser(url='http://localhost:9000')
next(parser.raw_parse('What is the airspeed of an unladen swallow ?')).pretty_print()
Out:
ROOT ... | [
"From your description 'What is the airspeed of an unladen swallow ?'. I think you wanted leaf node all the time if i am correct.! you should apply DFS(preorder) which will give output leaf nodes of the tree.\nCode for-:[To print leaf node]\nleafnodes=[]\n\ndef leafnode(node):\n if not node:\n return \n ... | [
0
] | [] | [] | [
"data_structures",
"python",
"tree"
] | stackoverflow_0071690744_data_structures_python_tree.txt |
Q:
How could i make this password get written in a text file
I want to make a program that creates passwords and then write them on a text file but the problem is that the program only writes 1 password on the textfile even tho it generates more, how i could fix this
import random, time,sys
#nombre = input("Platafor... | How could i make this password get written in a text file | I want to make a program that creates passwords and then write them on a text file but the problem is that the program only writes 1 password on the textfile even tho it generates more, how i could fix this
import random, time,sys
#nombre = input("Plataforma: ")
Simbolo = "*><๏ผ ๏ผ๏ผ
๏ผ๏ผ"
letra = "ABCDEFGHIJKLMNOPQRSTUVWXY... | [
"The problem is that you are waiting for an input (parar = input().lower()) before you write the new password to the text file.\nHere is the working solution.\nimport random, time,sys\n\nSimbolo = \"*><๏ผ ๏ผ๏ผ
๏ผ๏ผ\"\nletra = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\nnumeros = \"1234567890\"\nmayusculas = letra.lower()\n\nmayus,min... | [
0
] | [] | [] | [
"file",
"passwords",
"python"
] | stackoverflow_0074528317_file_passwords_python.txt |
Q:
os.environ not getting my environment variables
I have a simple python app with this file directory:
C:.
โโโโSample Project
โ โโโโproject
โ โ โโโโ.vscode
โ โ โโโโbin
โ โ โโโโmodels
โ โ โโโโprojects
โ โ โ โโโโtest
โ โ โโโโutils
โ โโโโvenv
Inside C:\Users\usr\Desktop\raicom\Sample Proj... | os.environ not getting my environment variables | I have a simple python app with this file directory:
C:.
โโโโSample Project
โ โโโโproject
โ โ โโโโ.vscode
โ โ โโโโbin
โ โ โโโโmodels
โ โ โโโโprojects
โ โ โ โโโโtest
โ โ โโโโutils
โ โโโโvenv
Inside C:\Users\usr\Desktop\raicom\Sample Project\project is my project.env which contains:
sample=... | [
"It works in debug mode because when you run it from debug mode the Current working directory is the project root directory, but when you right click and say run python file in terminal it runs it with the current working directory as the directory containing the python script.\nWhen it is run with the current work... | [
1,
0
] | [] | [] | [
"environment_variables",
"python",
"virtualenv",
"visual_studio_code"
] | stackoverflow_0074527980_environment_variables_python_virtualenv_visual_studio_code.txt |
Q:
Removing pycache in git
How can I remove existing and future pycahce files from git repository in Windows? The commands I found online are not working for example when I send the command "git rm -r --cached __pycache__" I get the command "pathspec '__pycache__' did not match any files".
A:
The __pycache__ folder... | Removing pycache in git | How can I remove existing and future pycahce files from git repository in Windows? The commands I found online are not working for example when I send the command "git rm -r --cached __pycache__" I get the command "pathspec '__pycache__' did not match any files".
| [
"The __pycache__ folders that you are seeing are not in your current and future Git commits. Because of the way Git works internallyโwhich Git forces you to know, at least if you're going to understand itโunderstanding this is a bit tricky, even once we get past the \"directory / folder confusion\" we saw in your ... | [
0,
0
] | [] | [] | [
"git",
"pyc",
"python"
] | stackoverflow_0074462238_git_pyc_python.txt |
Q:
Using Python to KNN: What is wrong with my code?
I am working on a class assignment where I need to use KNN to construct a classifier and report accuracy. I have some code I have been working on. I received this error on the code below.
Traceback (most recent call last):
File "c:\Users\jazzm\OneDrive\Desktop\pyth... | Using Python to KNN: What is wrong with my code? | I am working on a class assignment where I need to use KNN to construct a classifier and report accuracy. I have some code I have been working on. I received this error on the code below.
Traceback (most recent call last):
File "c:\Users\jazzm\OneDrive\Desktop\python\HWK6.py", line 20, in
classifier.fit(x_train, y_tr... | [
"the values that you use for the response variable are continuous instead of categorical.\n",
"The main goals are as follows:\n\nApply StandardScaler to continuous variables\nApply LabelEncoder and OnehotEncoder to categorical variables\n\nplease read : link\n"
] | [
2,
0
] | [] | [] | [
"knn",
"pandas",
"python",
"python_3.x",
"scikit_learn"
] | stackoverflow_0074510778_knn_pandas_python_python_3.x_scikit_learn.txt |
Q:
remove sample from anndata .obs and .x
I can see how to remove columns from anndata ie
keep = ['a','b','c']
adata = adata [:, keep]
How does one remove rows from anndata.obs and anndata.x?
for example remove adata.obs[Region='reg012']
Dataframe adata.obs
A:
If you want to remove row if Region contians reg012 the... | remove sample from anndata .obs and .x | I can see how to remove columns from anndata ie
keep = ['a','b','c']
adata = adata [:, keep]
How does one remove rows from anndata.obs and anndata.x?
for example remove adata.obs[Region='reg012']
Dataframe adata.obs
| [
"If you want to remove row if Region contians reg012 then..\nAssuming Data Frame = adata.obs\nadata.obs= adata.obs[~adata.obs.Region.str.contains(\"reg012\")]\n\n"
] | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074528516_dataframe_pandas_python.txt |
Q:
pandas.read_sql_query() throws TypeError: 'NoneType' object is not iterable
I am using pandas.read_sql_query function to read from a few sql files. One query throws an error at one particular bit which I have singled out.
(python bit - nothing exotic and works with other queries)
@contextmanager
def open_db_connec... | pandas.read_sql_query() throws TypeError: 'NoneType' object is not iterable | I am using pandas.read_sql_query function to read from a few sql files. One query throws an error at one particular bit which I have singled out.
(python bit - nothing exotic and works with other queries)
@contextmanager
def open_db_connection(connection_string):
pyodbc.pooling = False
connection = pyodbc.conne... | [
"The issue all along was that I was ignoring/disregarding warning messages in SSMS, which, I believe, results in cursor not being a query and pyodbc throwing ProgrammingError \"No results. Previous SQL was not a query.\" and consequently pandas.read_sql_query() crashing.\nThe warning:\n\nWarning: Null value is elim... | [
1,
0
] | [] | [] | [
"pandas",
"pyodbc",
"python",
"python_3.x",
"sql_server"
] | stackoverflow_0060078342_pandas_pyodbc_python_python_3.x_sql_server.txt |
Q:
How to test APIView in Django, Django Rest Framework
I am making an API with Django + Django Rest Framework. I am trying to test the GET methods of a view:
View:
class StuffView(APIView):
queryset = Stuff.objects.none()
def get(self, request, format=None):
data = Stuff.objects.... | How to test APIView in Django, Django Rest Framework | I am making an API with Django + Django Rest Framework. I am trying to test the GET methods of a view:
View:
class StuffView(APIView):
queryset = Stuff.objects.none()
def get(self, request, format=None):
data = Stuff.objects.all().order_by('-primaryKey')
StuffSerial... | [
"You need to compare the response data with your posted test data, that will be a good test for checking the posted data content. You may also check the order in which the response data is received, by using index response.data[0] for first item, and [1] for second and so on.\nself.assertEqual(response.data[0].get(... | [
0
] | [] | [] | [
"django",
"django_rest_framework",
"python"
] | stackoverflow_0039550163_django_django_rest_framework_python.txt |
Q:
How to segregate the column with respect to OK and not OK conditions in pyspark dataframe column?
I have a dataframe df as shown below:
VehNum Control_circuit control_circuit_status partnumbers errors Flag
4234456 DOC ok A567UR Software Issue 0
4234456 DOC ... | How to segregate the column with respect to OK and not OK conditions in pyspark dataframe column? | I have a dataframe df as shown below:
VehNum Control_circuit control_circuit_status partnumbers errors Flag
4234456 DOC ok A567UR Software Issue 0
4234456 DOC not_okay A568UR Software Issue 1
4234456 DOC not_okay ... | [
"here's the solution\nfrom pyspark.sql import functions as F\nfrom pyspark.sql.types import *\nfrom pyspark.sql import Window\n\ndf = spark.createDataFrame(\n [\n (\"4234456\", \"DOC\", \"ok\", \"A567UR\", \"Software Issue\", 0),\n (\"4234456\", \"DOC\", \"not_okay\", \"A568UR\", \"Software Issue\"... | [
1
] | [] | [] | [
"pyspark",
"python",
"python_3.x"
] | stackoverflow_0074527853_pyspark_python_python_3.x.txt |
Q:
Pandas keep rows where column values change at least twice
Good day,
I have a large dataset with columns that keep track of the scores each person obtains. Here is a sample of the dataset:
In:
data = [[7, 10, 10, 10, 10], [17, 10, 10, 10, 10], [18, 8, 10, 10, 10], [20, 10, 10, 9, 9], [25, 9, 8, 8, 7]]
df = pd.Data... | Pandas keep rows where column values change at least twice | Good day,
I have a large dataset with columns that keep track of the scores each person obtains. Here is a sample of the dataset:
In:
data = [[7, 10, 10, 10, 10], [17, 10, 10, 10, 10], [18, 8, 10, 10, 10], [20, 10, 10, 9, 9], [25, 9, 8, 8, 7]]
df = pd.DataFrame(data, columns = ['person_id', 'score_1', 'score_2', 'score... | [
"IIUC, you want to count the number of unique values, per rows, limited to the \"score*\" columns.\nYou can use nunique on the rows after getting the correct columns with filter. Then slice:\ndf[df.filter(like='score').nunique(axis=1).gt(2)]\n\nIf you really want the changes from left to right so that A->B->A->B co... | [
3,
1,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0071062887_pandas_python.txt |
Q:
How to save the swalign library output (Local Alignment - Smith-Waterman Algorithm)?
I have used the below code to get the local alignment score between two strings using Smith-Waterman Algorithm. However, I'm getting the required output, I'm finding it difficult to save the result into some variable for further a... | How to save the swalign library output (Local Alignment - Smith-Waterman Algorithm)? | I have used the below code to get the local alignment score between two strings using Smith-Waterman Algorithm. However, I'm getting the required output, I'm finding it difficult to save the result into some variable for further analysis.
import swalign
def Local_Alignment(string1, string2):
match_score = 100
... | [
"if you got to the implementation of the library you can see in the dump function the results are dumped on the console.\nThat is why it is returning nothing when you call the function and display temp in your case.\nHowever what you can do is go to the implementation copy the dump function and paste it there and r... | [
0,
0
] | [] | [] | [
"dna_sequence",
"python",
"smith_waterman"
] | stackoverflow_0074121168_dna_sequence_python_smith_waterman.txt |
Q:
Error getting after used hooks in behave framework python (before_scenario and after_scenario)
I used environment.py in my code. I used hooks before_scenario and after_scenario.
After the first test run. Got an error immediately. In this code am i doing something wrong?
from common.selen_base import Browser
def b... | Error getting after used hooks in behave framework python (before_scenario and after_scenario) | I used environment.py in my code. I used hooks before_scenario and after_scenario.
After the first test run. Got an error immediately. In this code am i doing something wrong?
from common.selen_base import Browser
def before_scenario(context,scenario):
context.browser = Browser()
def after_scenario(context,scen... | [
"You can add this at top of environment.py file:\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\n\nThis should resolve the issue\n"
] | [
0
] | [] | [] | [
"hook",
"python",
"python_behave"
] | stackoverflow_0059817925_hook_python_python_behave.txt |
Q:
python program that records number of attempts made during a random number between 1-10
trying to create a Python program to guess a number between 1 to 9 entered by the user and count the number of attempts taken by the computer to guess the correct number.
this is what I have so far, need to add on a counter tha... | python program that records number of attempts made during a random number between 1-10 | trying to create a Python program to guess a number between 1 to 9 entered by the user and count the number of attempts taken by the computer to guess the correct number.
this is what I have so far, need to add on a counter that tells me how many attempts have been made, any advice?
thank you
import random #Python impo... | [
"Just initialize a counter and increment it at each attempt.\ncounter += 1 is a shorcut for counter = counter + 1.\nThe print() function use a f-string to print the counter variable.\nimport random #Python import random module in Python defines a series of functions for generating or manipulating random integers\nt... | [
0,
0
] | [] | [] | [
"numbers",
"python",
"random"
] | stackoverflow_0074528610_numbers_python_random.txt |
Q:
pass variable to scipy curve_fit
I am trying to fit a dataset using a function:
def kel_voigt(x, en2, l2, en3, l3):
# The first term, 300 should be a variable, from the main
const = 300 * 1e-6 * math.pi / (2 * math.tan(math.radians(63.3)))
return const * (((1 - (np.exp(-x / l2))) / en2) +
(... | pass variable to scipy curve_fit | I am trying to fit a dataset using a function:
def kel_voigt(x, en2, l2, en3, l3):
# The first term, 300 should be a variable, from the main
const = 300 * 1e-6 * math.pi / (2 * math.tan(math.radians(63.3)))
return const * (((1 - (np.exp(-x / l2))) / en2) +
((1 - (np.exp(-x / l3))) / en3))
where... | [
"You can add one additional argument for your fixed variable/constant to your function and wrap this function in each loop iteration:\ndef kel_voigt(x, fix_var, en2, l2, en3, l3):\n # The first term, 300 should be a variable, from the main\n const = fix_var * 1e-6 * math.pi / (2 * math.tan(math.radians(63.3)))\n ... | [
1
] | [] | [] | [
"curve_fitting",
"python",
"scipy_optimize"
] | stackoverflow_0074527404_curve_fitting_python_scipy_optimize.txt |
Q:
How to substitute value of variables in Python expression, but not evaluate the expression?
I have a Python expression that looks like the following:
var1 = 'GOOGLE'
var2 = '5'
expr = 'df[df[var1]>=var2]'
In my workspace var1 and var2 are well defined so I can evaluate expr as follows:
eval(expr)
However, I want... | How to substitute value of variables in Python expression, but not evaluate the expression? | I have a Python expression that looks like the following:
var1 = 'GOOGLE'
var2 = '5'
expr = 'df[df[var1]>=var2]'
In my workspace var1 and var2 are well defined so I can evaluate expr as follows:
eval(expr)
However, I want to pass this expr (as string) to another function with values of var1 and var2 substituted in it... | [
"You can simply use Python f-string as demonstrated below\nexpr = f'df[df[{var1}] >= {var2}]'\n\n\n",
"You can parse the expression with ast.parse and use a subclass of ast.NodeTransformer to convert Name nodes to the corresponding values as Constant nodes, and then convert the AST back to code with ast.unparse:\... | [
1,
0
] | [] | [] | [
"eval",
"python"
] | stackoverflow_0074528551_eval_python.txt |
Q:
Python - remove punctuation marks at the end and at the beginning of one or more words
I wanted to know how to remove punctuation marks at the end and at the beginning of one or more words.
If there are punctuation marks between the word, we don't remove.
for example
input:
word = "!.test-one,-"
output:
word = "te... | Python - remove punctuation marks at the end and at the beginning of one or more words | I wanted to know how to remove punctuation marks at the end and at the beginning of one or more words.
If there are punctuation marks between the word, we don't remove.
for example
input:
word = "!.test-one,-"
output:
word = "test-one"
| [
"use strip\n>>> import string\n>>> word = \"!.test-one,-\"\n>>> word.strip(string.punctuation)\n'test-one'\n\n",
"The best solution is to use Python .strip(chars) method of the built-in class str.\nAnother approach will be to use a regular expression and the regular expressions module.\nIn order to understand wha... | [
6,
2,
1,
1
] | [] | [] | [
"algorithm",
"python"
] | stackoverflow_0074528239_algorithm_python.txt |
Q:
python password generator loop problem print error
I trying to make a password generator using python. Currently, I just want the program to print random characters from the ascii table. I will later introduce numbers and symbols. I used a for loop to print random character from a range that the user inputs. It wo... | python password generator loop problem print error | I trying to make a password generator using python. Currently, I just want the program to print random characters from the ascii table. I will later introduce numbers and symbols. I used a for loop to print random character from a range that the user inputs. It works however, when I use the end='' to print the characte... | [
"The % print by your shell (may be zsh), it means the string not end by \"\\n\". It's just a reminder from the shell. There is nothing wrong with you. You can just add a print() in the end of your code to print a \"\\n\", and % will not show again.\n",
"Try this\ncharacters = list(string.ascii_letters + string.di... | [
1,
0,
0,
0
] | [] | [] | [
"loops",
"printing",
"python",
"syntax"
] | stackoverflow_0074528585_loops_printing_python_syntax.txt |
Q:
" The 'from' keyword is not supported in this version of the language. "
I am trying to run tkinter in my notebook, that has windows system, that is the problem I had, all the times that i tried
That is the problem i found!
I wanna run tkinter modules in my Python app.
A:
The 'from' keyword is not supported in ... | " The 'from' keyword is not supported in this version of the language. " | I am trying to run tkinter in my notebook, that has windows system, that is the problem I had, all the times that i tried
That is the problem i found!
I wanna run tkinter modules in my Python app.
| [
"\nThe 'from' keyword is not supported in this version of the language.\n\nis an error message from PowerShell, not Python.\nMake sure you're entering code into the Python interpreter, not the PowerShell PS command line.\n"
] | [
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074528850_python_tkinter.txt |
Q:
Django Many2Many constraint
I am using Django with Django-Rest-Framework (no forms, no django_admin). I have the following models
class Company(models.Model):
...
class Sector(models.Model):
...
company_id = models.ForeignKey(Company)
employees = models.ManyToManyField(Employee)
class Employee(mo... | Django Many2Many constraint | I am using Django with Django-Rest-Framework (no forms, no django_admin). I have the following models
class Company(models.Model):
...
class Sector(models.Model):
...
company_id = models.ForeignKey(Company)
employees = models.ManyToManyField(Employee)
class Employee(models.Model):
...
compan... | [] | [] | [
"The through approach is good and valid on model level. Here is a related link:\nhttps://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships\n"
] | [
-1
] | [
"django",
"django_orm",
"django_rest_framework",
"python"
] | stackoverflow_0074493162_django_django_orm_django_rest_framework_python.txt |
Q:
multiprocessing vs. threading for communicating from osc server to gui
I'm currently quite undecided on what is actually the best approach to tackle this problem.
Assuming the program only consists of:
GUI using imgui and glfw
OSC Server that listens for incoming messages
The gui cannot block and the osc server ... | multiprocessing vs. threading for communicating from osc server to gui | I'm currently quite undecided on what is actually the best approach to tackle this problem.
Assuming the program only consists of:
GUI using imgui and glfw
OSC Server that listens for incoming messages
The gui cannot block and the osc server constantly needs to be able receive new messages.
So first of all, would it ... | [
"I'm in the same situation.\nDid you make some leeway?\nMy experience is/was that if I run the osc server code in a seperate thread it doesn't run reliable and was missing messages, or wasn't completing tasks initiated by received message.\nWhere if i remove the gui and run the server in the main thread everything ... | [
0
] | [] | [] | [
"architecture",
"multithreading",
"python",
"python_multiprocessing",
"user_interface"
] | stackoverflow_0070267294_architecture_multithreading_python_python_multiprocessing_user_interface.txt |
Q:
Save pandas on spark API dataframe to a new table in azure databricks
Context: I have a dataframe that I queried using SQl. From this query, I saved to a dataframe using pandas on spark API. Now, after some transformations, I'd like to save this new dataframe on a new table at a given database.
Example:
spark = Sp... | Save pandas on spark API dataframe to a new table in azure databricks | Context: I have a dataframe that I queried using SQl. From this query, I saved to a dataframe using pandas on spark API. Now, after some transformations, I'd like to save this new dataframe on a new table at a given database.
Example:
spark = SparkSession.builder.appName('transformation').getOrCreate()
df_final = spark... | [
"You can use the following procedure. I have the following demo table.\n\n\nYou can convert it to pandas dataframe of spark API using the following code:\n\ndf_final = spark.sql(\"SELECT * FROM demo\")\npdf = df_final.to_pandas_on_spark()\n#print(type(pdf))\n#<class 'pyspark.pandas.frame.DataFrame'>\n\n\nNow after... | [
1
] | [] | [] | [
"apache_spark",
"azure",
"databricks",
"python"
] | stackoverflow_0074490859_apache_spark_azure_databricks_python.txt |
Q:
Accepting cookies when web scraping
Related to a previous question I am trying to edit the answer to apply to another website, but can't get it to work. What I want to do here is to accept the cookie, and then extract the information from the table. (I also want to scrape the table for all of 2021 later, so any ti... | Accepting cookies when web scraping | Related to a previous question I am trying to edit the answer to apply to another website, but can't get it to work. What I want to do here is to accept the cookie, and then extract the information from the table. (I also want to scrape the table for all of 2021 later, so any tips on how to proceed there is welcomed to... | [
"The click() method returns null, so this expression WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, '//*[@class=\"pure-button\"]'))).click() returns null, so cookie and tbutton are null objects.\nThen you trying to click a null object with driver.execute_script(\"arguments[0].click();\"... | [
1
] | [] | [] | [
"python",
"selenium",
"selenium_webdriver",
"webdriverwait"
] | stackoverflow_0074528831_python_selenium_selenium_webdriver_webdriverwait.txt |
Q:
Can Cython compiled .so extensions be imported into other languages, eg. Java?
I'm in the process of learning Cython and I wasn't able to find a direct answer to this. Also please bear with me as my understanding of C is limited as of now. As far as I understand, with the cythonize command, .pyx files are converte... | Can Cython compiled .so extensions be imported into other languages, eg. Java? | I'm in the process of learning Cython and I wasn't able to find a direct answer to this. Also please bear with me as my understanding of C is limited as of now. As far as I understand, with the cythonize command, .pyx files are converted to C, and are compiled to platform-specific libraries (.so / .pxd). My questions a... | [
"\nCython extensions are fully C, but they heavily use the Python C API. This means they can't be run independent of libpython (and usually the Python standard library). However it is possible to load libpython into other languages and then use a Cython extension. Also bear in mind that anything you import within C... | [
1
] | [] | [] | [
"cython",
"java_native_interface",
"python"
] | stackoverflow_0074528482_cython_java_native_interface_python.txt |
Q:
how to shift non nan value in multiple columns row wise by group?
so i have data frame as below
A1
A2
A3
A4
A5
A6
1
nan
3
7
nan
8
nan
5
nan
11
9
nan
54
6
84
12
3
nan
10
nan
nan
16
nan
45
12
93
13
31
5
91
73
nan
45
nan
nan
9
i want to shift the whole data frame n rows such that it skips nan rows but still p... | how to shift non nan value in multiple columns row wise by group? | so i have data frame as below
A1
A2
A3
A4
A5
A6
1
nan
3
7
nan
8
nan
5
nan
11
9
nan
54
6
84
12
3
nan
10
nan
nan
16
nan
45
12
93
13
31
5
91
73
nan
45
nan
nan
9
i want to shift the whole data frame n rows such that it skips nan rows but still preserve it.
desire output:
for n =2
A1
A2
A3
A4
A5
A6... | [
"try this:\ntmp = df.apply(\n lambda s: s.sort_values(\n key=lambda v: pd.notnull(v)\n ).values\n )\nres = tmp.shift(2)\nres\n\n",
"Use lambda function with Series.dropna and Series.shift:\ndf = df.apply(lambda x: x.dropna().shift(2))\n\nprint (df)\n A1 A2 A3 A4 A5 A6\n0 NaN... | [
0,
0
] | [] | [] | [
"pandas",
"python",
"shift"
] | stackoverflow_0074527018_pandas_python_shift.txt |
Q:
Why can't My GUI program built by PyQt5 show?
I refer to the article1 to build my GUI by PyQt5,The difference between the program of the article and mine is the module <img_controller.py>. When I initilize my img_controller instance,I only need the parameter ui(the class I got from Qtdesigner)and my program ,img_c... | Why can't My GUI program built by PyQt5 show? | I refer to the article1 to build my GUI by PyQt5,The difference between the program of the article and mine is the module <img_controller.py>. When I initilize my img_controller instance,I only need the parameter ui(the class I got from Qtdesigner)and my program ,img_controller. will revise the attributes of ui. Initia... | [
"What you DIDN'T say was the key piece of information -- the rest of the traceback. Notice that Img_controller.__init__ calls self.read_img, which calls self.set_img_ratio, which calls self.__update_img, which uses self.ui, and that all happens BEFORE you set self.ui. You need to swap the order of that initializa... | [
0
] | [] | [] | [
"pyqt5",
"python"
] | stackoverflow_0074528626_pyqt5_python.txt |
Q:
Python mongodb/motor "'ObjectId' object is not iterable" error while trying to find item in collection
I know that there are similar questions, but I've tried everything that was advised and still getting an error. I'm trying to fetch item from mongo collection by id, converting string to an ObjectId, like that:
f... | Python mongodb/motor "'ObjectId' object is not iterable" error while trying to find item in collection | I know that there are similar questions, but I've tried everything that was advised and still getting an error. I'm trying to fetch item from mongo collection by id, converting string to an ObjectId, like that:
from bson import ObjectId
async def get_single_template(db, template_id):
template = await db.templates... | [
"Well, I've found out what caused that issue. The problem was not in the way I've tried to query data, but in the way I've tried to return it. I've forgotten to convert ObjectId to string in the entity that I've retrieved from database and tried to return it 'as is'. My bad.\n",
"I encountered this problem as wel... | [
2,
1,
0
] | [] | [] | [
"fastapi",
"mongodb",
"pymongo",
"python"
] | stackoverflow_0065970988_fastapi_mongodb_pymongo_python.txt |
Q:
How to add median value labels to a Seaborn boxplot using the hue argument
In addition to the solution posted in this link I would also like if I can also add the Hue Parameter, and add the Median Values in each of the plots.
The Current Code:
testPlot = sns.boxplot(x='Pclass', y='Age', hue='Sex', data=trainData)
... | How to add median value labels to a Seaborn boxplot using the hue argument | In addition to the solution posted in this link I would also like if I can also add the Hue Parameter, and add the Median Values in each of the plots.
The Current Code:
testPlot = sns.boxplot(x='Pclass', y='Age', hue='Sex', data=trainData)
m1 = trainData.groupby(['Pclass', 'Sex'])['Age'].median().values
mL1 = [str(np.r... | [
"Place your labels manually according to hue parameter and width of bars for every category in a cycle of all xticklabels:\nimport seaborn as sns\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pylab as plt\n\ntrainData = pd.read_csv('titanic.csv')\ntestPlot = sns.boxplot(x='pclass', y='age', hue='sex',... | [
13,
1
] | [] | [] | [
"boxplot",
"matplotlib",
"python",
"seaborn"
] | stackoverflow_0045475962_boxplot_matplotlib_python_seaborn.txt |
Q:
Python Equivalent for R's order function
According to this post np.argsort() would be the function I am looking for.
However, this is not giving me my desire result.
Below is the R code that I am trying to convert to Python and my current Python code.
R Code
data.frame %>% select(order(colnames(.)))
Python Code... | Python Equivalent for R's order function | According to this post np.argsort() would be the function I am looking for.
However, this is not giving me my desire result.
Below is the R code that I am trying to convert to Python and my current Python code.
R Code
data.frame %>% select(order(colnames(.)))
Python Code
dataframe.iloc[numpy.array(dataframe.columns)... | [
"Do you have mixed case? This is handled differently in python and R.\nR:\norder(c('a', 'b', 'B', 'A', 'c'))\n# [1] 1 4 2 3 5\n\nx <- c('a', 'b', 'B', 'A', 'c')\nx[order(c('a', 'b', 'B', 'A', 'c'))]\n# [1] \"a\" \"A\" \"b\" \"B\" \"c\"\n\nPython:\nnp.argsort(['a', 'b', 'B', 'A', 'c'])+1\n# array([4, 3, 1, 2, 5])\n\... | [
2,
1
] | [] | [] | [
"pandas",
"python",
"r"
] | stackoverflow_0074528672_pandas_python_r.txt |
Q:
Python: create 3D array using values of another 3D array that meet a condition
I'm basically trying to take the weighted mean of a 3D dataset, but only on a filtered subset of the data, where the filter is based off of another (2D) array. The shape of the 2D data matches the first 2 dimensions of the 3D data, and ... | Python: create 3D array using values of another 3D array that meet a condition | I'm basically trying to take the weighted mean of a 3D dataset, but only on a filtered subset of the data, where the filter is based off of another (2D) array. The shape of the 2D data matches the first 2 dimensions of the 3D data, and is thus repeated for each slice in the 3rd dimension.
Something like:
import numpy a... | [
"The most glaring efficiency issue, even the loop aside, is that np.where(...) is being called multiple times inside the loop, on the same condition! You can just do this a single time beforehand. Moreover, there is no need for a loop. Your operation basically equates to:\nmask = myarr2 > 5\naverage = (myarr[mask] ... | [
1
] | [] | [] | [
"arrays",
"numpy",
"python",
"vectorization"
] | stackoverflow_0074527214_arrays_numpy_python_vectorization.txt |
Q:
In a given string, match all numbers where a certain word is not present either ahead or behind it [Regex, Python]
I have a string like
"10.0 banana 30 apple 50 TOM 70 mango 100 peach 33 TOM 4.5"
and from this, I want to match only numbers which do not have the word TOM either behind or ahead of them.
So match s... | In a given string, match all numbers where a certain word is not present either ahead or behind it [Regex, Python] | I have a string like
"10.0 banana 30 apple 50 TOM 70 mango 100 peach 33 TOM 4.5"
and from this, I want to match only numbers which do not have the word TOM either behind or ahead of them.
So match should be only numbers 10.0, 30, 100; numbers 50, 70, 33 and 4.5 should not be matched.
Regex101. I have tried with negat... | [
"You can use negative lookaround patterns like this:\n(?<!\\bTOM )(?<![\\d.])\\d+(?:\\.\\d+)?(?![\\d.])(?! TOM\\b)\n\nDemo: https://regex101.com/r/v8IaEu/1\n"
] | [
2
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074529040_python_regex.txt |
Q:
Pass python dictionary to javascript
I have a Python + JS application connected to a PostgreSQL database. The database contains data about users in different countries, which is queried by the server.py file. The result of this query is a dictionary that would look something like this:
{'US': 2,
'CA': 5}
This dict... | Pass python dictionary to javascript | I have a Python + JS application connected to a PostgreSQL database. The database contains data about users in different countries, which is queried by the server.py file. The result of this query is a dictionary that would look something like this:
{'US': 2,
'CA': 5}
This dictionary needs to be passed to my map.js fil... | [
"what a fun project!\nLet's get the work under way.\nOn your server side,\nimport json\n\n@app.route('/map')\ndef show_mapjs():\n country_count = {\n \"US\": 0, \"CA\": 0,\n }\n \n #place your own code here to get the data from the database#\n\n country_list = [] \n for country, count ... | [
1
] | [] | [] | [
"flask",
"javascript",
"json",
"python",
"visualization"
] | stackoverflow_0074528238_flask_javascript_json_python_visualization.txt |
Q:
Validating file paths in Python
I have this code where the user has to input the name of a file which includes a message and the name of a file where the message must be written after its encrypted via Caesar-Cipher.
I would like to validate the inputs, so that if there's a wrong input, the code won't crash but as... | Validating file paths in Python | I have this code where the user has to input the name of a file which includes a message and the name of a file where the message must be written after its encrypted via Caesar-Cipher.
I would like to validate the inputs, so that if there's a wrong input, the code won't crash but ask the user for a valid file path unti... | [
"Not quite sure what you meant by not being able to use a while loop, but here is a simple way of checking if the paths exists using pathlib.\nfrom pathlib import Path\n\nwhile True:\n source_path = Path(input(\"Enter the name of the file including the message: \"))\n if source_path.exists():\n break\n... | [
1,
1
] | [] | [] | [
"caesar_cipher",
"python",
"validation"
] | stackoverflow_0074528514_caesar_cipher_python_validation.txt |
Q:
how to get non continuous date time in dataframe datetime column pandas
I have a datetime based dataframe as below,
timestamp value ... metric
36 2014-04-02 17:20:00 125.098263 ... 25.098263
14 2014-04-06 16:25:00 140.072787 ... 265.171050 ... | how to get non continuous date time in dataframe datetime column pandas | I have a datetime based dataframe as below,
timestamp value ... metric
36 2014-04-02 17:20:00 125.098263 ... 25.098263
14 2014-04-06 16:25:00 140.072787 ... 265.171050
10 2014-04-11 09:00:00 127.882020 ... 393.053070
... | [
"You can compare the successive rows to see if this is the same date (extracted with dt.normalize) and use this as grouper to get the size with groupby.transform('size'), if the size is > 1, set 'same' else 'diff' with help of numpy.where:\nimport numpy as np\n\n# ensure datetime\ndf['timestamp'] = pd.to_datetime(d... | [
2
] | [] | [] | [
"pandas",
"python",
"python_datetime"
] | stackoverflow_0074529166_pandas_python_python_datetime.txt |
Q:
Selenium scrolls to the element but does not click
Trying to click next button from navigation bar of website "https://uk.trustpilot.com/categories/bars_cafes?subcategories=cafe" using selenium in python.
from selenium.webdriver import Chrome
from webdriver_manager.chrome import ChromeDriverManager
from selenium.w... | Selenium scrolls to the element but does not click | Trying to click next button from navigation bar of website "https://uk.trustpilot.com/categories/bars_cafes?subcategories=cafe" using selenium in python.
from selenium.webdriver import Chrome
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from bs4 import BeautifulSo... | [
"Include the following imports:\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nimport time as t\n\nEdit your next_page function like so:\nwait = WebDriverWait(driver, 25)\n\nnext_page_button = w... | [
1,
0
] | [] | [] | [
"python",
"selenium",
"web_scraping"
] | stackoverflow_0074524342_python_selenium_web_scraping.txt |
Q:
ChoiceField doesn't display an empty label when using a tuple
What I'm trying to do
I'm going to be keeping data about competitions in my database. I want to be able to search the competitions by certain criteria - competition type in particular.
About competition types
Competition types are kept in a tuple. A sli... | ChoiceField doesn't display an empty label when using a tuple | What I'm trying to do
I'm going to be keeping data about competitions in my database. I want to be able to search the competitions by certain criteria - competition type in particular.
About competition types
Competition types are kept in a tuple. A slightly shortened example:
COMPETITION_TYPE_CHOICES = (
(1, 'Olym... | [
"I've found a solution that works the way I want it to without violating the DRY principle. Not very clean, but it'll have to do I suppose.\nAccording to the documentation choices don't have to be a tuple:\n\nFinally, note that choices can be any\n iterable object -- not necessarily a\n list or tuple. This lets y... | [
36,
32,
10,
8,
7,
6,
0,
0,
0
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0001765757_django_django_forms_python.txt |
Q:
python Or operator notworking
sorry im really new to python
im trying to keep the cursor within a 100x100 box but it doesnt do that, im still able to move it within a t shape spanning the whole screen and not a box in the middle of it.
it seems like its just ignoring 1 of the variables
what this is supposed to do ... | python Or operator notworking | sorry im really new to python
im trying to keep the cursor within a 100x100 box but it doesnt do that, im still able to move it within a t shape spanning the whole screen and not a box in the middle of it.
it seems like its just ignoring 1 of the variables
what this is supposed to do is simply detect if the mouse has l... | [
"ok no clue but i fixed it by putting not infront of it\npyautogui.moveTo(550,550)\n\nwhile True:\n mos = pyautogui.position()\n print(mos[0],mos[1])\n if not (500 < mos[0] < 600) or not(500 < mos[1] < 600):\n break\n\n",
"Your first version should have been\nif (500 < mos[0] < 600) and (500 < mos... | [
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074527424_python.txt |
Q:
Split a string at uppercase letters
What is the pythonic way to split a string before the occurrences of a given set of characters?
For example, I want to split
'TheLongAndWindingRoad'
at any occurrence of an uppercase letter (possibly except the first), and obtain
['The', 'Long', 'And', 'Winding', 'Road'].
Edit:... | Split a string at uppercase letters | What is the pythonic way to split a string before the occurrences of a given set of characters?
For example, I want to split
'TheLongAndWindingRoad'
at any occurrence of an uppercase letter (possibly except the first), and obtain
['The', 'Long', 'And', 'Winding', 'Road'].
Edit: It should also split single occurrences,... | [
"Unfortunately it's not possible to split on a zero-width match in Python. But you can use re.findall instead:\n>>> import re\n>>> re.findall('[A-Z][^A-Z]*', 'TheLongAndWindingRoad')\n['The', 'Long', 'And', 'Winding', 'Road']\n>>> re.findall('[A-Z][^A-Z]*', 'ABC')\n['A', 'B', 'C']\n\n",
"Here is an alternative re... | [
180,
42,
23,
20,
14,
10,
6,
6,
5,
5,
2,
2,
1,
1,
0,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"python",
"regex",
"string"
] | stackoverflow_0002277352_python_regex_string.txt |
Q:
How to return the value of a while loop counter
I want to return the counter of the while loops, i and b after every loop repetition to use in another function. I haven't found anything related to returning these values.
def dis(reps, towards, back):
t = 0 # move towards t times
b = 0 # move back b times... | How to return the value of a while loop counter | I want to return the counter of the while loops, i and b after every loop repetition to use in another function. I haven't found anything related to returning these values.
def dis(reps, towards, back):
t = 0 # move towards t times
b = 0 # move back b times
i = 0 # repetitions
n = 1 # counts every s... | [
"You have to watch on python Generators. Here's a link!\n"
] | [
1
] | [] | [] | [
"loops",
"python",
"return",
"while_loop"
] | stackoverflow_0074529177_loops_python_return_while_loop.txt |
Q:
Complex queryset with django content type model
I have a set of models that contain content that is created and contributed by users.
Model User:
class User(models.Model):
first_name = models.CharField(max_length=30, blank=True)
last_name = models.CharField(max_length=150, blank=True)
is_active = model... | Complex queryset with django content type model | I have a set of models that contain content that is created and contributed by users.
Model User:
class User(models.Model):
first_name = models.CharField(max_length=30, blank=True)
last_name = models.CharField(max_length=150, blank=True)
is_active = models.BooleanField(default=True)
Model Tip:
class Tip(mo... | [
"I think you can get most of this by writing an admin class object for your models and create list_filter to access the content of child or sibling models. Assuming the UserContribution model is the 'parent' model. As example in your main app's admin.py create a admin model for UserContribution and register it: eg.... | [
0
] | [] | [] | [
"django",
"django_contenttypes",
"django_models",
"django_queryset",
"python"
] | stackoverflow_0069503835_django_django_contenttypes_django_models_django_queryset_python.txt |
Q:
Pandas Merging Multiple Columns at the Same Between Two Dataframes
I'm trying to find a way to merge in multiple columns at the same time with Pandas. I have the output I want by doing five separate merges, but it feels like there should be a more pythonic way to do it.
Essentially I have a dataframe with five key... | Pandas Merging Multiple Columns at the Same Between Two Dataframes | I'm trying to find a way to merge in multiple columns at the same time with Pandas. I have the output I want by doing five separate merges, but it feels like there should be a more pythonic way to do it.
Essentially I have a dataframe with five keyword columns in a dataframe called df_striking which I'm trying to merge... | [
"If you already have the empty columns, you can use:\nmapping = df_keyword_vol.set_index('Keyword')['Volume']\n\ndf_striking.iloc[:, 1::2] = df_striking.iloc[:, ::2].replace(mapping)\n\n\nElse, if you only have the KWx columns:\ndf2 = (pd.concat([df, df.replace(mapping)], axis=1)\n .sort_index(axis=1)\n ... | [
3,
1,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0069366947_pandas_python.txt |
Q:
How do I shorten a for loop with arithmetic inside?
I've been wondering if I can shorten a for loop with arithmetic inside of it
Here is my code:
n = int(input("n: "))
string = ''
for i in range(n):
string += input()
I want to make it a one line code, Is it possible?
This is what I tried:
[string+=input() fo... | How do I shorten a for loop with arithmetic inside? | I've been wondering if I can shorten a for loop with arithmetic inside of it
Here is my code:
n = int(input("n: "))
string = ''
for i in range(n):
string += input()
I want to make it a one line code, Is it possible?
This is what I tried:
[string+=input() for i in range(n)]
| [
"Well, if you really want, you can do:\nstring = ''.join(input() for _ in range(int(input(\"n: \"))))\n\n"
] | [
0
] | [] | [] | [
"for_loop",
"python",
"python_3.x"
] | stackoverflow_0074529241_for_loop_python_python_3.x.txt |
Q:
ASAMMDF - MemoryError: Unable to allocate 16.8 MiB for an array with shape (2207220,) and data type float64
I am trying to extract data from a ".dat" file by using asammdf.
After extracting the data using asammdf, I am trying to convert the data into a dataframe that can be analyzed using pandas and matplotlib.
Fo... | ASAMMDF - MemoryError: Unable to allocate 16.8 MiB for an array with shape (2207220,) and data type float64 | I am trying to extract data from a ".dat" file by using asammdf.
After extracting the data using asammdf, I am trying to convert the data into a dataframe that can be analyzed using pandas and matplotlib.
Following is the code that I am using for extracting the data and converting to dataframe:
import pandas as pd
impo... | [
"You need to use the raster argument whenc alling to_dataframe because you have too many individual timestamps in the file (see https://asammdf.readthedocs.io/en/master/api.html#asammdf.mdf.MDF.iter_to_dataframe)\n"
] | [
0
] | [] | [] | [
"asammdf",
"data_files",
"memory",
"pandas",
"python"
] | stackoverflow_0074490140_asammdf_data_files_memory_pandas_python.txt |
Q:
Is there a way to assign enum values from variable in Python?
Here's my problem.
At first, I implemented in the code something like this:
class HttpMethod(enum.Enum):
GET = requests.get
POST = requests.post
...
def __call__(self, *args, **kwargs):
return self.value(*args, **kwargs)
But no... | Is there a way to assign enum values from variable in Python? | Here's my problem.
At first, I implemented in the code something like this:
class HttpMethod(enum.Enum):
GET = requests.get
POST = requests.post
...
def __call__(self, *args, **kwargs):
return self.value(*args, **kwargs)
But now I want to call session.get instead of requests.get from the follo... | [
"I did finally come to a solution with the package aenum which comes with an __ignore__ field for enums.\nclass HttpMethod(Enum):\n POST, GET, PUT, PATH, DELETE = range(1, 6)\n\n __pool = HttpPooling()\n __ignore__ = (\"__pool\",)\n\n def __repr__(self):\n return self.value.__repr__()\n\n @pro... | [
-1
] | [] | [] | [
"enums",
"python"
] | stackoverflow_0074518691_enums_python.txt |
Q:
Same label multiple times in one image - Tensorflow
I'm trying to create a tf model, which can detect any handwriting in any image. In order to do that, i made the labels in all train pictures with just one label: edit.
It means, one image can have this labels many times.
After many hours of training using cpu i d... | Same label multiple times in one image - Tensorflow | I'm trying to create a tf model, which can detect any handwriting in any image. In order to do that, i made the labels in all train pictures with just one label: edit.
It means, one image can have this labels many times.
After many hours of training using cpu i did't get the expected result. The model can't see any of ... | [
"CPU vs GPU\nGPU has the only advantage that the training is faster. It shouldn't have any effect on the expected result. It just takes longer. Though, for some models, the difference could be large. Monitoring your training might give you more insight.\nTraining monitoring\nWhat does it mean you did not get the ex... | [
0
] | [] | [] | [
"python",
"tensorflow"
] | stackoverflow_0074527315_python_tensorflow.txt |
Q:
Floating point exception (core dumped) for UNet implementation
I am trying to do an implementation of KiuNet ( https://github.com/jeya-maria-jose/KiU-Net-pytorch ). But when I am executing the train command like so:
python train.py --train_dataset "KiuNet/Train Folder/" --val_dataset "KiuNet/Validation Folder/" --... | Floating point exception (core dumped) for UNet implementation | I am trying to do an implementation of KiuNet ( https://github.com/jeya-maria-jose/KiU-Net-pytorch ). But when I am executing the train command like so:
python train.py --train_dataset "KiuNet/Train Folder/" --val_dataset "KiuNet/Validation Folder/" --direc 'KiuNet/Results/' --batch_size 1 --epoch 200 --save_freq 10 --... | [
"The repository author mentions the following.\n\"This bug occurs when the ground truth masks have more classes than the number of classes in prediction. Please make sure you ground truth images have only 0 or 1 labels of pixels if you are training for binary segmentation. The datasets usually have the ground truth... | [
1
] | [] | [] | [
"cudnn",
"floating_point",
"python",
"pytorch",
"torch"
] | stackoverflow_0074520038_cudnn_floating_point_python_pytorch_torch.txt |
Q:
Profile picture (Portrait) validation in web services
I am developing a service which can validate input picture either it is suitable portrait (Profile picture) or not.
If possible service can return scoring. Each consumer can set required accepted criteria.
Some key rules I want to implement for image validation... | Profile picture (Portrait) validation in web services | I am developing a service which can validate input picture either it is suitable portrait (Profile picture) or not.
If possible service can return scoring. Each consumer can set required accepted criteria.
Some key rules I want to implement for image validation are
Background of image is not busy
Person face is recogn... | [
"This issue related to face Recognition.\nIf you don't want to use the cognitive-services from Microsoft or other providers. You can check the FaceRecognitionDotNet.\nAnd here is the sample(asp.net core), you can check it.\n\nIf you face the error below, please search it via google, and there are a lot of github is... | [
0
] | [] | [] | [
"asp.net_core_webapi",
"image_processing",
"python"
] | stackoverflow_0074517363_asp.net_core_webapi_image_processing_python.txt |
Q:
Exported image black with 0 value
I tried to use the following code but when exporting my map and I check my output data in arcmap. It is totally black and the value is 0.
I don't know what is wrong with my code.
https://code.earthengine.google.com/476db72426a67e03a604b6712ce97ef4?hl=ar
// The purpose of this scri... | Exported image black with 0 value | I tried to use the following code but when exporting my map and I check my output data in arcmap. It is totally black and the value is 0.
I don't know what is wrong with my code.
https://code.earthengine.google.com/476db72426a67e03a604b6712ce97ef4?hl=ar
// The purpose of this script is to estimate sub-pixel fractions
/... | [
"You're only exporting a single pixel - the region is set to point. All bands are actually not 0, but whatever tool you're using to visualise the image will have problems picking a good stretch, giving you a black pixel.\nYou could for instance use image.geometry() instead of pixel in this case:\nExport.image.toDri... | [
1
] | [] | [] | [
"arrays",
"google_earth_engine",
"java",
"python",
"python_3.x"
] | stackoverflow_0074516317_arrays_google_earth_engine_java_python_python_3.x.txt |
Q:
Align cell content in excel using python
I am struggling to set the alignment for data in excel using python
My python function loads data from excel into a pandas dataframe, calculates some new columns, then adds these columns to the original sheet. This all works well, but I now want to tidy up the result.
I can... | Align cell content in excel using python | I am struggling to set the alignment for data in excel using python
My python function loads data from excel into a pandas dataframe, calculates some new columns, then adds these columns to the original sheet. This all works well, but I now want to tidy up the result.
I can set italics / bold etc using
sheet['E1:J24'].... | [
"Use 'VerticalAlignment' and/or 'HorizontalAlignment'.\nImport VAlign, HAlign from the Xlwings constants to use the name or just use the Excel code. I have copied these into the comments for your information.\nimport xlwings as xw\nfrom xlwings.constants import VAlign, HAlign\n\n### Xlwings constants\n\"\"\"\nVAlig... | [
0
] | [] | [] | [
"excel",
"pandas",
"python",
"xlwings"
] | stackoverflow_0074518839_excel_pandas_python_xlwings.txt |
Q:
How can I vectorize the following algorithm?
Is there a way that I could do vectorization instead of for loop for the following algorithm?
def test_func(df):
idx_lst = [df.index[0]]
end = df.loc[df.index[0], "end"]
for idx in df.index[1:]:
if df.loc[idx, "begin"] > end:
end = df.... | How can I vectorize the following algorithm? | Is there a way that I could do vectorization instead of for loop for the following algorithm?
def test_func(df):
idx_lst = [df.index[0]]
end = df.loc[df.index[0], "end"]
for idx in df.index[1:]:
if df.loc[idx, "begin"] > end:
end = df.loc[idx, "end"]
idx_lst.append(idx)
... | [
"I agree with the earlier comment that it is hard or even impossible to use\nvectorization.\nBut try instead the following function:\ndef myFunc(df):\n arr = df.begin.values > df.end[:, np.newaxis]\n r = 0\n idx_lst = [r]\n while True:\n wrk = np.nonzero(arr[r])[0]\n if wrk.size == 0:\n ... | [
0
] | [] | [] | [
"pandas",
"python",
"vectorization"
] | stackoverflow_0074527883_pandas_python_vectorization.txt |
Q:
make Keras 'None' batch size unchanged, using tf.scatter_nd
I need to input a pooling module to the LSTM decoder, and I'm constructing this using a custom layer with the encoder LSTM states and Keras Input layer as inputs. In this custom layer, I need to scatter the updates to the indices:
updates: <tf.Tensor --- ... | make Keras 'None' batch size unchanged, using tf.scatter_nd | I need to input a pooling module to the LSTM decoder, and I'm constructing this using a custom layer with the encoder LSTM states and Keras Input layer as inputs. In this custom layer, I need to scatter the updates to the indices:
updates: <tf.Tensor --- shape=(None, 225, 5, 32) dtype=float32>
indices: <tf.Tensor --- s... | [
"I had similar issue with tf.scatter_nd operation. I solved it by infering batch size during runtime using tf.shape(input)[0]. So in your case, the following code should work:\nbs = tf.shape(indices)[0]\ntf.scatter_nd(tf.expand_dims(indices, 2), updates, shape=[bs, 960, 5, 32])\n\n"
] | [
0
] | [] | [] | [
"deep_learning",
"keras",
"python",
"tensorflow"
] | stackoverflow_0064193001_deep_learning_keras_python_tensorflow.txt |
Q:
Checking input of a method if it exists on a list Python
@dataclass
class Product:
name: str
quantity: int
price: float
class Transaction:
def __init__(self):
self.mapDict = {}
self.mapVal = []
def add_item(self, name, quantity, price):
res = name not in self.map... | Checking input of a method if it exists on a list Python | @dataclass
class Product:
name: str
quantity: int
price: float
class Transaction:
def __init__(self):
self.mapDict = {}
self.mapVal = []
def add_item(self, name, quantity, price):
res = name not in self.mapVal
if res:
self.mapDict[len(self.mapVal)]... | [
"You can return a True or False in check_if_not_exists.\ndef add_item(self, name, quantity, price):\n product_doesnt_exists = self.check_if_not_exists(name)\n if product_doesnt_exists:\n self.mapDict[len(self.mapVal)] = Product(name, quantity, price)\n self.mapVal.append(name)\n return Tr... | [
1
] | [] | [] | [
"class",
"dictionary",
"oop",
"python"
] | stackoverflow_0074529171_class_dictionary_oop_python.txt |
Q:
Print Latex for system of equations in SymPy?
How would I write a system of equations in SymPy and output the equivalent Latex? The latex function seems to accept only one expression at a time.
import sympy as sp
x, y, z = sp.symbols('x, y, z')
eq1 = sp.Eq(x + y + z, 1)
eq2 = sp.Eq(x + y + 2 * z, 3)
output = sp.l... | Print Latex for system of equations in SymPy? | How would I write a system of equations in SymPy and output the equivalent Latex? The latex function seems to accept only one expression at a time.
import sympy as sp
x, y, z = sp.symbols('x, y, z')
eq1 = sp.Eq(x + y + z, 1)
eq2 = sp.Eq(x + y + 2 * z, 3)
output = sp.latex() # Do something here?
| [
"One way is to create a function and combine the latex output of each equation.\ndef system_to_latex(*equations):\n n = len(equations)\n if n == 0:\n return \"\"\n l1 = r\"\\left\\{\\begin{matrix}%s\\end{matrix}\\right.\"\n l2 = r\" \\\\ \".join(sp.latex(eq) for eq in equations)\n return l1 % ... | [
1
] | [] | [] | [
"python",
"sympy"
] | stackoverflow_0074527451_python_sympy.txt |
Q:
Multihead model based on DenseNet201 using Keras
I am trying to use this notebook where we define a 3-head model based on DenseNet201. The AlexNet based works correctly but DenseNet201 throws me an error. I am a Pytorch user and have not been able to figure out the error of ValueError: Missing data for input "inpu... | Multihead model based on DenseNet201 using Keras | I am trying to use this notebook where we define a 3-head model based on DenseNet201. The AlexNet based works correctly but DenseNet201 throws me an error. I am a Pytorch user and have not been able to figure out the error of ValueError: Missing data for input "input_5". You passed a data dictionary with keys ['img_inp... | [
"The issue is that your input node does not have the same name as the dictionary key holding your input.\nYou can create your input layer before hand wit the right name, and pass it to the DenseNet201 function as the input tensor.\nself.image_input = keras.Input((self.side_dim, self.side_dim, 3), name=\"img_input\"... | [
2
] | [] | [] | [
"densenet",
"keras",
"python",
"tensorflow"
] | stackoverflow_0074527844_densenet_keras_python_tensorflow.txt |
Q:
How to make user hyperlink in python telegram bot?
Stack overflow!
I'm using telebot module for my telegram bot (from telebot import types).
I want to send messages to telegram users.
In this messages I want to paste a link to another telegram users.
My code is:
linked_user = '[username](tg://user?id=999999999)'
b... | How to make user hyperlink in python telegram bot? | Stack overflow!
I'm using telebot module for my telegram bot (from telebot import types).
I want to send messages to telegram users.
In this messages I want to paste a link to another telegram users.
My code is:
linked_user = '[username](tg://user?id=999999999)'
bot.send_message(
admin_chat_id, f'{linked_user}',
... | [
"Some Users have specific privacy settings. So even though you can pm them, you cant \"publish\" their usernames so anyone else can Contact them. So you are not doing anything wrong.\n"
] | [
0
] | [] | [] | [
"python",
"python_telegram_bot",
"telebot",
"telegram",
"telegram_bot"
] | stackoverflow_0071180687_python_python_telegram_bot_telebot_telegram_telegram_bot.txt |
Q:
How can I check the loss of a model at a specific epoch in pytorch?
I was training a deep learning model (link) and it was printing the loss and robustness stats after each epoch, but when it was done executing the terminal closed so I could not see the stats (I am using ssh+screen function so that is normal). I d... | How can I check the loss of a model at a specific epoch in pytorch? | I was training a deep learning model (link) and it was printing the loss and robustness stats after each epoch, but when it was done executing the terminal closed so I could not see the stats (I am using ssh+screen function so that is normal). I did 120 epochs and after training a folder called log was generated which ... | [
"Those files are likely to only contain the model states and training checkpoints. If you saved your loss and metrics inside the checkpoint archives then you will be able to retrieve this information. Else this information is simply not accessible anymore.\nWhat are you saving inside the .tar archives?\n"
] | [
0
] | [] | [] | [
"deep_learning",
"python",
"pytorch"
] | stackoverflow_0074529449_deep_learning_python_pytorch.txt |
Q:
Is there any way to show the dependency trees for pip packages?
I have a project with multiple package dependencies, the main requirements being listed in requirements.txt. When I call pip freeze it prints the currently installed packages as plain list. I would prefer to also get their dependency relationships, so... | Is there any way to show the dependency trees for pip packages? | I have a project with multiple package dependencies, the main requirements being listed in requirements.txt. When I call pip freeze it prints the currently installed packages as plain list. I would prefer to also get their dependency relationships, something like this:
Flask==0.9
Jinja2==2.7
Werkzeug==0.8.3
Ji... | [
"You should take a look at pipdeptree:\n$ pip install pipdeptree\n$ pipdeptree -fl\nWarning!!! Cyclic dependencies found:\n------------------------------------------------------------------------\nxlwt==0.7.5\nruamel.ext.rtf==0.1.1\nxlrd==0.9.3\nopenpyxl==2.0.4\n - jdcal==1.0\npymongo==2.7.1\nreportlab==3.1.8\n -... | [
235,
12,
5,
0
] | [] | [] | [
"pip",
"python",
"requirements.txt"
] | stackoverflow_0017194301_pip_python_requirements.txt.txt |
Q:
How is the time complexity of a nested for loop n^2 +1?
So I was reviewing some slides my teacher gave us and we are given the following Python code:
a=5
b=6
c=10
for i in range(n):
for j in range(n):
x = i * j
y = j * j
z = i * j
for k in range(n):
w = a*k + 45
v = b*b
d=33
For the ... | How is the time complexity of a nested for loop n^2 +1? | So I was reviewing some slides my teacher gave us and we are given the following Python code:
a=5
b=6
c=10
for i in range(n):
for j in range(n):
x = i * j
y = j * j
z = i * j
for k in range(n):
w = a*k + 45
v = b*b
d=33
For the first part (variable declaration) the time complexity is cons... | [
"formula for a for loop: x*n+1.\nx - number of operations performs for each iteration.\nn - number of iterations\n+1 - creating range obj.\nSo in your case the formula is 1 + n(3n + 1) <=>1 + 3n^2 + n.\ncreating main loop range obj + n iterations * (3 operations * n iterations + creating 1 range object)\nThe time c... | [
1
] | [] | [] | [
"big_o",
"python",
"time_complexity"
] | stackoverflow_0074529134_big_o_python_time_complexity.txt |
Q:
Return json/dictionary from psycopg3 SELECT query
I've been asked to migrate a program from psycopg2 to psycopg3. In this program they use
with connection.cursor(cursor_factory=RealDictCursor) as cursor:
to obtain a dictionary that's later turned into a JSON file.
My problem is that RealDictCursor appears to be a... | Return json/dictionary from psycopg3 SELECT query | I've been asked to migrate a program from psycopg2 to psycopg3. In this program they use
with connection.cursor(cursor_factory=RealDictCursor) as cursor:
to obtain a dictionary that's later turned into a JSON file.
My problem is that RealDictCursor appears to be a psycopg2 extra feature, and as such get an error when ... | [
"The way to generate rows as dictionaries in psycopg3 is by passing the dict_row row factory to the connection.\n>>> from psycopg.rows import dict_row\n>>>\n>>> conn = psycopg.connect(dbname='test', row_factory=dict_row)\n>>> cur = conn.cursor()\n>>> cur.execute('select id, name from users')\n<psycopg.Cursor [TUPLE... | [
0
] | [] | [] | [
"postgresql",
"psycopg3",
"python"
] | stackoverflow_0074529506_postgresql_psycopg3_python.txt |
Q:
Some Python objects were not bound to checkpointed values
I am trying to get started with Tensorflow 2.0 Object Detection API. I have gone through the installation following the official tutorial and I pass all the tests. However, I keep getting an error message that I don't understand when I try to run the main m... | Some Python objects were not bound to checkpointed values | I am trying to get started with Tensorflow 2.0 Object Detection API. I have gone through the installation following the official tutorial and I pass all the tests. However, I keep getting an error message that I don't understand when I try to run the main module. This is how I run it:
python model_main_tf2.py --model_d... | [
"From the file name you provided (ssd_resnet50_v1_fpn_640x640_coco17_tpu-8), I can see you are trying to work with an object detection task. Therefore, in your pipeline.config file change this line:\nfine_tune_checkpoint_type: \"classification\"\n\nTo:\nfine_tune_checkpoint_type: \"detection\"\n\nThis should solve ... | [
42,
4,
0,
0
] | [] | [] | [
"deep_learning",
"object_detection_api",
"python",
"tensorflow",
"tensorflow2.0"
] | stackoverflow_0063552169_deep_learning_object_detection_api_python_tensorflow_tensorflow2.0.txt |
Q:
How to keep django-q run on ubuntu nginx server
I use ubuntu with nginx & gunicorn and try to run django-q
How can I keep django-q run when shutdown terminal please
A:
You will need to either run it as service (refer to answer) or use a process manager as described in the documentation
| How to keep django-q run on ubuntu nginx server | I use ubuntu with nginx & gunicorn and try to run django-q
How can I keep django-q run when shutdown terminal please
| [
"You will need to either run it as service (refer to answer) or use a process manager as described in the documentation\n"
] | [
0
] | [] | [] | [
"django",
"django_q",
"python"
] | stackoverflow_0074516668_django_django_q_python.txt |
Q:
Plot a Pandas Pivoted table using python
Iam trying to produce a line plot for the following table such that:
X- axis is the dates[shown in the columns]
Y-axis is the number value for each Region/Date
Chart legend would be the Region[index]. [ARABIAN GULF/BALTIC SEA ...]
Hence, there would be total of 3 line plo... | Plot a Pandas Pivoted table using python | Iam trying to produce a line plot for the following table such that:
X- axis is the dates[shown in the columns]
Y-axis is the number value for each Region/Date
Chart legend would be the Region[index]. [ARABIAN GULF/BALTIC SEA ...]
Hence, there would be total of 3 line plots, one for each Region, where x-axis is the d... | [
"I think you want:\ndf.set_index('REGION').T.plot()\n\nOutput:\n\nIntermediate:\ndf.set_index('REGION').T\n\nREGION ANDAMAN SEA ARABIAN GULF BALTIC SEA\n2022-08-29 13 28 121\n2022-09-05 13 24 120\n2022-09-12 12 26 114\n202... | [
1
] | [] | [] | [
"pandas",
"python",
"visualization"
] | stackoverflow_0074529558_pandas_python_visualization.txt |
Q:
pip subprocess to install build dependencies did not run successfully
With the following docker file,
FROM python:3.9-slim-buster
WORKDIR /python-docker
COPY requirements.txt requirements.txt
RUN python3 -m pip install --upgrade pip
RUN pip3 install -r requirements.txt
COPY . .
EXPOSE 5000
CMD [ "python3", ... | pip subprocess to install build dependencies did not run successfully | With the following docker file,
FROM python:3.9-slim-buster
WORKDIR /python-docker
COPY requirements.txt requirements.txt
RUN python3 -m pip install --upgrade pip
RUN pip3 install -r requirements.txt
COPY . .
EXPOSE 5000
CMD [ "python3", "-m" , "flask", "run", "--host=0.0.0.0"]
requirement file as follows,
boto... | [
"ok man just try to install packages one by one or you can remove the version in front of every package so it will automatically adjust\njust like this\nboto3\nFlask\nFlask_Cors\nhvac\nPyJWT\nPyMySQL\nzenpy\ngunicorn\npandas```\n#I think it will work fine\n\n"
] | [
0
] | [] | [] | [
"docker",
"pip",
"python"
] | stackoverflow_0074529519_docker_pip_python.txt |
Q:
{TypeError} Object of type Commit is not JSON serializable
I've a dict with some repo information and I want to write it a json file, but this error raises during dumps method: {TypeError} Object of type Commit is not JSON serializable.
__repo_path = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
... | {TypeError} Object of type Commit is not JSON serializable | I've a dict with some repo information and I want to write it a json file, but this error raises during dumps method: {TypeError} Object of type Commit is not JSON serializable.
__repo_path = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
repo = Repo(__repo_path)
__tags = sorted(
(tag for tag in... | [
"Make sure to use names/text messages not objects:\nimport git, json\n\nrepo = git.Repo('C:/data/foo')\n__current_branch = repo.active_branch.name\n__tags = repo.tags\n\nSCM_DATA = {\n \"CHANGESET\": repo.head.commit.message,\n \"BRANCH\": __current_branch,\n \"TAG\": __tags[-1].name,\n \"IS_DIRTY\": re... | [
1
] | [] | [] | [
"json",
"python"
] | stackoverflow_0074529527_json_python.txt |
Q:
How to exclude a specific element from a list comprehension with conditionals
I am trying to use a list comprehension to extract specific elements from a list, using conditionals on the list indices.
When the list indices differ, specific operations need to happen.
When the list indices are the same, no element sh... | How to exclude a specific element from a list comprehension with conditionals | I am trying to use a list comprehension to extract specific elements from a list, using conditionals on the list indices.
When the list indices differ, specific operations need to happen.
When the list indices are the same, no element should be added.
The latter is what I do not know how to do, except by adding '' and ... | [
"You can put if clauses after for to filter some elements.\nx2 = [2 * x[j] - x[i] if j > i else 2 * x[i] - x[j] for j in x if j != i]\n\n",
"You can apply two kind of conditionals to a list comprehension. The one you are applying is applied to every element that make it to that point of code to get a value, that ... | [
2,
2
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074529555_list_python.txt |
Q:
How do I render Displacy on Spyder Notebook?
I want Spyder to display the plot of dependencies using Displacy visualizer of Spacy.
Here is the code:
import spacy
nlp = spacy.load('en_core_web_sm')
from spacy import displacy
doc = nlp(u'This is a short text.')
displacy.render(doc, style='dep', options={'distance':... | How do I render Displacy on Spyder Notebook? | I want Spyder to display the plot of dependencies using Displacy visualizer of Spacy.
Here is the code:
import spacy
nlp = spacy.load('en_core_web_sm')
from spacy import displacy
doc = nlp(u'This is a short text.')
displacy.render(doc, style='dep', options={'distance':110})
The program ends without displaying anythin... | [
"In my case running your code in Spyder 5.1.2 returns me the string for the svg of the plot.\nTo visualize the plot while running the code from Spyder you will need to use displacy.serve method. That will run a web server serving the svg/plot. You should be able to access/view it at that point through your browser ... | [
2,
0
] | [] | [] | [
"jupyter_notebook",
"python",
"spacy",
"spyder"
] | stackoverflow_0069078885_jupyter_notebook_python_spacy_spyder.txt |
Q:
foreign key dynamic filter with another foreign key in admin.py in django
I have a problem with the dynamic design of the admin.
I want the selected productCategory to be dynamically filtered when I select the productType.
For example, I do this manually in models.py (ProductCategory.objects.filter(productType=2 ... | foreign key dynamic filter with another foreign key in admin.py in django | I have a problem with the dynamic design of the admin.
I want the selected productCategory to be dynamically filtered when I select the productType.
For example, I do this manually in models.py (ProductCategory.objects.filter(productType=2 or 1 or 4 ...( i cant dynamic))
models.py
class ProductType(models.Model)... | [
"I tried to do same think for long time but haven't solved yet. But i can tell you why this is not work.\nThe problem is self.instance.productType.id is None because you have not selected yet.\nTry to type print() like this and you will see why its not work.\ndef __init__(self, *args, **kwargs):\n super(ProductF... | [
0
] | [] | [] | [
"django",
"django_admin",
"django_models",
"foreign_keys",
"python"
] | stackoverflow_0073804134_django_django_admin_django_models_foreign_keys_python.txt |
Q:
how to scrape this interactive chart data at desired datetime?
I am currently attempting to scrape this website to print all data in the blue rectangle from
https://mempool.jhoenicke.de/#BTC,6m,weight
Desired point that I want to scrape
I would like to scrape the text in all the individual tooltips because I can s... | how to scrape this interactive chart data at desired datetime? | I am currently attempting to scrape this website to print all data in the blue rectangle from
https://mempool.jhoenicke.de/#BTC,6m,weight
Desired point that I want to scrape
I would like to scrape the text in all the individual tooltips because I can see that the data is under the id="tooltip"
like this
data under id="... | [
"Essentially you need to move your mouse in a horizontal line across the page, near to the bottom of the chart, and record the tooltip content each time that it changes.\n# wait until key elements are loaded\ncanvas = WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.CSS_SELECTOR, \"canvas[class='fl... | [
0
] | [] | [] | [
"charts",
"interactive",
"python",
"selenium",
"web_scraping"
] | stackoverflow_0074528872_charts_interactive_python_selenium_web_scraping.txt |
Q:
How can I make and train custom-dataset in my own dataset?
I have questions on my work.
I build a multiclass classification model that classifies an input image as one label of 4 classes.
Currently, I have 100,000 images that are made up 4 classes imbalanced. And I also have csv file including information of file ... | How can I make and train custom-dataset in my own dataset? | I have questions on my work.
I build a multiclass classification model that classifies an input image as one label of 4 classes.
Currently, I have 100,000 images that are made up 4 classes imbalanced. And I also have csv file including information of file name, class, path. I made a csv file using Pandas library.
Now g... | [
"Here's the solution I found, although it might not be the most optimal one. Assuming that you have 5,000 images for each class.\nIf you have a dataframe (your csv file) that is structured as follows:\n>>> df\n\n filename class\n0 one.png 1\n1 two.png 2\n.\n.\n.\n99,000 name.png 4\n... | [
0
] | [] | [] | [
"keras",
"pandas",
"python",
"tensorflow2.0"
] | stackoverflow_0074515506_keras_pandas_python_tensorflow2.0.txt |
Q:
how to read and verify a text file exists or not in python in while loop?
I'm trying to verify if a file exists or not in the current directory. At the same time, read if the file exists. The below is my code
import os.path
def readdata():
isFileExist = False
while isFileExist == False:
userIN ... | how to read and verify a text file exists or not in python in while loop? | I'm trying to verify if a file exists or not in the current directory. At the same time, read if the file exists. The below is my code
import os.path
def readdata():
isFileExist = False
while isFileExist == False:
userIN = str(input("Please Enter a file name, followed by .txt: "))
isExist = os.p... | [
"There is a couple of methods to check it.\n\ntry except\n\ntry:\n file = open(file_name)\nexcept FileNotFoundError:\n # do something when file not exist\n\n\npathlib.Path object has exists method.\nos.path.isfile method\n\nTo read data from file use:\nwith open(file_name) as f:\n for line in f:\n #... | [
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074529629_python_python_3.x.txt |
Q:
Django UserCreationForm and Bootstrap Forms Layouts
I am trying to extend the UserCreationForm using a Bootstrap layout style for the field username. After the input tag in the registration form, I would like to add a div element like an example that I have readapted from the Bootstrap page: i.e. suggesting the us... | Django UserCreationForm and Bootstrap Forms Layouts | I am trying to extend the UserCreationForm using a Bootstrap layout style for the field username. After the input tag in the registration form, I would like to add a div element like an example that I have readapted from the Bootstrap page: i.e. suggesting the user to enter the same username as the company domain.
Let'... | [
"If you want to use only {{ form.as_p }} with bootstrap then you need to install django-bootstrap.\nInstall it using pip:\npip install django-bootstrap4\n\nAfter installation, add it in INSTALLED_APPS in settings.py file.\nINSTALLED_APPS = [\n 'bootstrap4',\n]\n\nAnd in templates, you need to load it.\n{% load bo... | [
1
] | [] | [] | [
"bootstrap_5",
"django",
"python"
] | stackoverflow_0074529800_bootstrap_5_django_python.txt |
Q:
Libtorrent. Answer some questions
To begin with, English is not my native language, so it's hard for me to read the libtorrent documentation and all this question has been translated.
I ask you to answer these questions, if you know any of them, answer only him.
I am using libtorrent 2.0.7 and Python 3.8
It is not... | Libtorrent. Answer some questions | To begin with, English is not my native language, so it's hard for me to read the libtorrent documentation and all this question has been translated.
I ask you to answer these questions, if you know any of them, answer only him.
I am using libtorrent 2.0.7 and Python 3.8
It is not necessary to answer questions in pytho... | [
"I found the answer to the 1st and 2nd question:\ntest = handle.status()\nfor i in range(test.torrent_file.files().num_files()):\n print(test.torrent_file.files().file_path(i))\n\n"
] | [
0
] | [] | [] | [
"libtorrent",
"python"
] | stackoverflow_0074529732_libtorrent_python.txt |
Q:
Cant able to install streamlit-webrtc package
when i try to install this package using this command(pip install -U streamlit-webrtc) iam a getting an error which i am not aware of that Please let me know how to resolve this issue
A:
go to https://visualstudio.microsoft.com/visual-cpp-build-tools/ and install thi... | Cant able to install streamlit-webrtc package | when i try to install this package using this command(pip install -U streamlit-webrtc) iam a getting an error which i am not aware of that Please let me know how to resolve this issue
| [
"go to https://visualstudio.microsoft.com/visual-cpp-build-tools/ and install this. Then install the microsoft build tools(just check-mark it). After the installation of around 1.7gb, run the \"pip install streamlit-webrtc\" command. Installation will be completed.\n"
] | [
0
] | [] | [] | [
"python",
"streamlit",
"webrtc"
] | stackoverflow_0073126521_python_streamlit_webrtc.txt |
Q:
Split one excel file into multiple with specific number of rows in Pandas
Let's say I have an excel file with 101 rows, I need to split and write into 11 excel files with equivalent row number 10 for each new file, except the last one since there is only one row left.
This is code I have tried, but I get KeyError... | Split one excel file into multiple with specific number of rows in Pandas | Let's say I have an excel file with 101 rows, I need to split and write into 11 excel files with equivalent row number 10 for each new file, except the last one since there is only one row left.
This is code I have tried, but I get KeyError: 11:
df = pd.DataFrame(data=np.random.rand(101, 3), columns=list('ABC'))
group... | [
"I think you need np.arange:\ndf = pd.DataFrame(data=np.random.rand(101, 3), columns=list('ABC'))\ngroups = df.groupby(np.arange(len(df.index))//10)\nfor i, g in groups:\n print(g)\n\n",
"I solved a similar problem as follows. Backstory to my issue was that I have created an Azure Function with an HTTP trigger... | [
2,
1
] | [] | [] | [
"dataframe",
"pandas",
"pandas_groupby",
"python",
"python_3.x"
] | stackoverflow_0060000054_dataframe_pandas_pandas_groupby_python_python_3.x.txt |
Q:
Unexpected increase of memory usage on datetime index when using pandas.to_numeric with apply()
I followed the example from the docs to downcast datatypes to decrease memory usage:
https://pandas.pydata.org/docs/user_guide/scale.html#use-efficient-datatypes
I tried to downcast two columns of a dataframe with a dat... | Unexpected increase of memory usage on datetime index when using pandas.to_numeric with apply() | I followed the example from the docs to downcast datatypes to decrease memory usage:
https://pandas.pydata.org/docs/user_guide/scale.html#use-efficient-datatypes
I tried to downcast two columns of a dataframe with a datetime index from float64 to float32 with pd.to_numeric.
Given the following dataframe:
import pandas ... | [
"It seems to be a bug in older pandas versions (btw, same on Windows and Ubuntu). I just installed pandas 1.5.1 and it works as expected. Unfortunately, I can't update the pandas version in my project yet, so I won't use the apply() method until I'm ready to use a newer version.\nAnyway, thanks to juanpa.arrivillag... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074525557_pandas_python.txt |
Q:
I was trying to see the seasonal and trend factor in the timeseries, but graph is not working correctly. Tried after deleting cache memory too
Hi was trying to do seasonal_decomposition for a time series, but wasn't getting proper result:
date value
2020-02-01 67.05
2020-03-01 69.08
2020-06-01 70.25
202... | I was trying to see the seasonal and trend factor in the timeseries, but graph is not working correctly. Tried after deleting cache memory too | Hi was trying to do seasonal_decomposition for a time series, but wasn't getting proper result:
date value
2020-02-01 67.05
2020-03-01 69.08
2020-06-01 70.25
2020-07-01 68.74
2020-08-01 67.31
.
.
.
till 2022-11-04
Code:
from statsmodels.tsa.seasonal import seasonal_decompose
df_add_decompose = seasonal_de... | [
"you have to sort index:\nfrom statsmodels.tsa.seasonal import seasonal_decompose\ndf_modified = df_modified.sort_index()\ndf_add_decompose = seasonal_decompose(df_modified, model = 'additive', period=12)\ndf_add_decompose.plot()\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"decomposition",
"python",
"time_series",
"timeserieschart"
] | stackoverflow_0074529646_dataframe_decomposition_python_time_series_timeserieschart.txt |
Q:
How to prevent double quotes at start and end of DAT file, while writing a pandas DF using to_csv()?
My panda DF contains huge data and giving filename with '.DAT' extension (client requirement) and using to_csv() to write data.
When I open the file in notepad or any other text viewer, I see double quotes at start... | How to prevent double quotes at start and end of DAT file, while writing a pandas DF using to_csv()? | My panda DF contains huge data and giving filename with '.DAT' extension (client requirement) and using to_csv() to write data.
When I open the file in notepad or any other text viewer, I see double quotes at start and end of the file:
" col1|Col2|Col3
D1|D2|D3
... So On
D1n|D2n|D3n "
How to remove these double q... | [
"To write to a CSV you would do it like this normally.\nGenerally, this should not give you quotes in the file by default.\nimport pandas as pd\n\ndf = pd.read_csv('path\\to\\source_folder\\input.dat')\n\ndf.to_csv('path\\to\\folder\\s.dat')\n\nCan we see a sample of the Code?\n",
"Try this\ndf.to_csv(\"data.dat\... | [
0,
0
] | [] | [] | [
"apache_spark_sql",
"dataframe",
"pandas",
"pyspark",
"python"
] | stackoverflow_0074326096_apache_spark_sql_dataframe_pandas_pyspark_python.txt |
Q:
Python py7zr can't list files in archive - how to read 7z archive without extracting it
I tried to list all files inside 7z archive (I don't want to extract them).
I followed the documentation of the creators of py7zr.
My code look like this:
def checkArchive(archivePath):
for filename in os.listdir(archivePath):
... | Python py7zr can't list files in archive - how to read 7z archive without extracting it | I tried to list all files inside 7z archive (I don't want to extract them).
I followed the documentation of the creators of py7zr.
My code look like this:
def checkArchive(archivePath):
for filename in os.listdir(archivePath):
print("Filename is: " + filename)
cmd = "py7zr l " + filename
os.system(cmd)
I a... | [
"I think can use this to list files in a 7z archive.\nimport py7zr\n\nwith py7zr.SevenZipFile(r'<PATH TO 7Z FILE>.7z', 'r') as archive:\n all_paths = archive.getnames()\n\n"
] | [
0
] | [] | [] | [
"7zip",
"py7zr",
"python",
"python_3.x"
] | stackoverflow_0072306786_7zip_py7zr_python_python_3.x.txt |
Q:
conditionally_trigger for TriggerDagRunOperator
I have 2 DAGs: dag_a and dag_b (dag_a -> dag_b)
After dag_a is executed, TriggerDagRunOperator is called, which starts dag_b. The problem is, when dag_b is off (paused), dag_a's TriggerDagRunOperator creates scheduled runs in dag_b that queue up for as long as dag_a ... | conditionally_trigger for TriggerDagRunOperator | I have 2 DAGs: dag_a and dag_b (dag_a -> dag_b)
After dag_a is executed, TriggerDagRunOperator is called, which starts dag_b. The problem is, when dag_b is off (paused), dag_a's TriggerDagRunOperator creates scheduled runs in dag_b that queue up for as long as dag_a is running. After turning dag_b back ON, the executio... | [
"You can use ShortCircuitOperator to execute/skip the downstream dag_b. Then, use the Airflow Rest API (or shell/CLI) to figure out whether dag_b is paused or not.\ndag_a = TriggerDagRunOperator(\n trigger_dag_id='dag_a',\n ...\n)\n\npause_check = ShortCircuitOperator(\n task_id='pause_check',\n python_... | [
1,
0
] | [] | [] | [
"airflow",
"python"
] | stackoverflow_0074492876_airflow_python.txt |
Q:
Direction of the rotation not the same as the angle
The helicopter should fly according to angle 1. when a key is pressed, it should fly according to angle 2. It is working. With angle 1 = 0 the helicopter flies parallel to the x axis. The helicopter image also shows this. With angle 2 = 45 it goes diagonally down... | Direction of the rotation not the same as the angle | The helicopter should fly according to angle 1. when a key is pressed, it should fly according to angle 2. It is working. With angle 1 = 0 the helicopter flies parallel to the x axis. The helicopter image also shows this. With angle 2 = 45 it goes diagonally down. But the picture shows diagonally upwards. How can I rec... | [
"In the Pygame coordinate system the y-axis points down the screen, but the mathematical y axis points form the bottom to the top. To compansate that you have to invert the angle of rotation when you call pygame.transform.rotate:\nself.image = pygame.transform.rotate(self.img, self.rot)\nself.image = pygame.transfo... | [
3
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0074529739_pygame_python.txt |
Q:
Python: How to connect to Bluestacks or another emulator by ppadb?
I'm trying to simulate simple gestures like tap or swipe in BlueStacks emulator by using Python and PPADB. The problem is when I'm trying to connect.
Client(host="127.0.0.1", port=5037)
There is no devices. Emulator have address:
But when I try t... | Python: How to connect to Bluestacks or another emulator by ppadb? | I'm trying to simulate simple gestures like tap or swipe in BlueStacks emulator by using Python and PPADB. The problem is when I'm trying to connect.
Client(host="127.0.0.1", port=5037)
There is no devices. Emulator have address:
But when I try to connect to it by PPADB, then nothing happened and terminal stops work.... | [
"BlueStacks uses port 5037 for ADB. This means that\nadb = Client(host='127.0.0.1', port=5555)\nshould instead be\nadb = Client(host='127.0.0.1', port=5037)\n"
] | [
0
] | [] | [] | [
"adb",
"android_emulator",
"bluestacks",
"python"
] | stackoverflow_0074530092_adb_android_emulator_bluestacks_python.txt |
Q:
Get info from str-list
My info-resource (binance-api) returns info as string list. Can you help me and explain how can I take variable 'initialLeverage':
Code
def long():
lever = client.futures_leverage_bracket()
lever = pd.DataFrame(lever)
print(lever)
#vol()
Terminal
symbol ... | Get info from str-list | My info-resource (binance-api) returns info as string list. Can you help me and explain how can I take variable 'initialLeverage':
Code
def long():
lever = client.futures_leverage_bracket()
lever = pd.DataFrame(lever)
print(lever)
#vol()
Terminal
symbol ... | [
"you can use a lambda function. This creates a new column in the dataframe x and saves the data in a list.\ndf['initialLeverage']=df['brackets'].apply(lambda x: [i['initialLeverage'] for i in x])\n\nDetails:\n#create sample df\ndf=pd.DataFrame(data={'symbol':['SUSHIUSDT','BTSUSDT'],'brackets':[[{'bracket': 1, 'init... | [
0
] | [] | [] | [
"api",
"binance",
"dataframe",
"keyerror",
"python"
] | stackoverflow_0074525724_api_binance_dataframe_keyerror_python.txt |
Q:
How to select element by classpath (SELENIUM, PYTHON)
I Trying select this path but not works,
chrome_options = Options()
caps = DesiredCapabilities().CHROME
caps["pageLoadStrategy"] = "eager" # interactive
#chrome_options.add_argument("--headless")
driver = uc.Chrome(options=chrome_options, desired_capabilities=... | How to select element by classpath (SELENIUM, PYTHON) | I Trying select this path but not works,
chrome_options = Options()
caps = DesiredCapabilities().CHROME
caps["pageLoadStrategy"] = "eager" # interactive
#chrome_options.add_argument("--headless")
driver = uc.Chrome(options=chrome_options, desired_capabilities=caps)
driver.get('https://www.santander.com.br/emprestimo/l... | [
"The field you are trying to select is inside Shadow DOM. Such elements are quite straightforward to access using Chrome and Selenium 4:\nshadow_host = driver.find_element(By.TAG_NAME, \"pdc-juc-root\")\nshadow_root = shadow_host.shadow_root\ninput = shadow_root.find_element(By.ID, \"cpf\")\naction = webdriver.Act... | [
0
] | [] | [] | [
"css",
"python",
"selenium"
] | stackoverflow_0074526629_css_python_selenium.txt |
Q:
How to preserve column names in scikit-learn ColumnTransformer?
I', creating some pipelines using scikit-learn but I'm having some trouble keeping the variables names as the original names, and not as the transformer_name__feature_name format
This is the scenario:
I have a set of transformers, both custom and som... | How to preserve column names in scikit-learn ColumnTransformer? | I', creating some pipelines using scikit-learn but I'm having some trouble keeping the variables names as the original names, and not as the transformer_name__feature_name format
This is the scenario:
I have a set of transformers, both custom and some from scikit-learn itself
The set of transformers used in each step ... | [
"The ColumnTransformer can only perform one transform per column.\nIf you want to perform for column2 2 transformation, you should define a pipeline that perform first the MinMaxScaler and then your CustomTransformer.\nI would modify your code as follows:\nfrom sklearn.pipeline import make_pipeline\ndata = [\n {... | [
0
] | [] | [] | [
"python",
"scikit_learn",
"scikit_learn_pipeline"
] | stackoverflow_0074524532_python_scikit_learn_scikit_learn_pipeline.txt |
Q:
how to read sonar data in python
I need to read sonar datatype file in python. Sonar data contains the ocean details, It used to measure the depth of the sea. The file contains binary data and extension as .s7k format.
A:
I downloaded a sample s7k file to test whether I could read it---and I could. (The sample f... | how to read sonar data in python | I need to read sonar datatype file in python. Sonar data contains the ocean details, It used to measure the depth of the sea. The file contains binary data and extension as .s7k format.
| [
"I downloaded a sample s7k file to test whether I could read it---and I could. (The sample file I used to test can be downloaded here.)\n\nFirst, in a new project folder, download this dg_formats.py file, which contains a list of reson datagram codes and helpers.\n\nNext, download this reader.py file to the same fo... | [
1
] | [] | [] | [
"numpy",
"pandas",
"python",
"sonarqube"
] | stackoverflow_0074514680_numpy_pandas_python_sonarqube.txt |
Q:
I need only top 20 highest review count among all the cars bar graph?
Basically i have a dataset with car models and i need a bar graph where the highest review count of 20 car brands should be displayed in the bar graph!
I have tried this below code but i am getting all the brand models from the dataset but i nee... | I need only top 20 highest review count among all the cars bar graph? | Basically i have a dataset with car models and i need a bar graph where the highest review count of 20 car brands should be displayed in the bar graph!
I have tried this below code but i am getting all the brand models from the dataset but i need only top 20 highest review count car brands in bar graph.
Used Dataset :... | [
"Pandas contain a feature to sort values for a DataFrame e.g.: DataFrame.sort_values(<column_name>, ascending=False).\nFor more information on sorting values using pandas can be found in pandas.sort_values documentation.\nSorting:\nData=Data.sort_values('reviews_count', ascending=False).reset_index(drop=True)\n\nSl... | [
0,
0
] | [] | [] | [
"dataset",
"machine_learning",
"python",
"scikit_learn",
"visualization"
] | stackoverflow_0074529863_dataset_machine_learning_python_scikit_learn_visualization.txt |
Q:
how to get rid of KeyError: 'kivy.garden.matplotlib'?
i am using matplotlib with kivy when i am running my file i am getting this error can anyone suggest something.
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/root/pycharm-2019.3.3/plugins/python/helpers/pydev/_pydev_bundl... | how to get rid of KeyError: 'kivy.garden.matplotlib'? | i am using matplotlib with kivy when i am running my file i am getting this error can anyone suggest something.
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/root/pycharm-2019.3.3/plugins/python/helpers/pydev/_pydev_bundle/pydev_umd.py", line 197, in runfile
pydev_imports.ex... | [
"use these commands it helped mine that had error for\nfrom kivy.garden.matplotlib :\npython 3.7 using anaconda\n\npip install kivy\npip install kivy-garden\ngarden install matplotlib\npip install matplotlib==2.2.2\n\n",
"If I were you, I would clone \"https://github.com/kivy-garden/garden.matplotlib\" to the \"v... | [
1,
0
] | [] | [] | [
"android",
"kivy",
"matplotlib",
"python",
"runtime_error"
] | stackoverflow_0063655196_android_kivy_matplotlib_python_runtime_error.txt |
Q:
python numpy how to insert multiple rows between each row
I have a numpy array like this:
26.4812 32.0000 -5.0000 10000.0000 20000.0000 2.0000
26.4812 32.0000 10.0000 10000.0000 20000.0000 2.0000
26.4812 32.0000 0.0000 10000.0000 20000.0000 2.0000...
I want to change it so that the 3rd column(z value) has more s... | python numpy how to insert multiple rows between each row | I have a numpy array like this:
26.4812 32.0000 -5.0000 10000.0000 20000.0000 2.0000
26.4812 32.0000 10.0000 10000.0000 20000.0000 2.0000
26.4812 32.0000 0.0000 10000.0000 20000.0000 2.0000...
I want to change it so that the 3rd column(z value) has more steps like this:
26.4812 32.0000 -5.0000 10000.0000 20000.0000 ... | [
"This is little ugly maybe but it does what you want:\narr1 = np.array([[1, -3, -3],\n [1, 3, 3],\n [1, 3, 7]])\nz=arr1[:, 2]\nnew_z = []\nfor i in range(len(z)-1):\n new_z.append(np.arange(z[i],z[i+1]+1))\nnew_z = np.unique(np.concatenate(new_z))\nnew_array = np.c_[np.repeat(arr1[0, 0], new... | [
0,
0
] | [] | [] | [
"numpy",
"numpy_ndarray",
"python"
] | stackoverflow_0074529980_numpy_numpy_ndarray_python.txt |
Q:
kivymd application crashes on android when using MDRaisedButton
My application works perfectly on the machine. I am using kivymd without any external libraries.
but application crashes on android when using MDRaisedButton
MDRaisedButton:
text: 'Enter'
custom_color: app.theme_cls.primary_col... | kivymd application crashes on android when using MDRaisedButton | My application works perfectly on the machine. I am using kivymd without any external libraries.
but application crashes on android when using MDRaisedButton
MDRaisedButton:
text: 'Enter'
custom_color: app.theme_cls.primary_color
pos_hint: {"center_x": 0.5, "center_y": 0.35}
... | [
"Try kivymd=1.0.2 in the buildozer.spec requirements\n"
] | [
0
] | [] | [] | [
"kivy",
"kivymd",
"python"
] | stackoverflow_0074459968_kivy_kivymd_python.txt |
Q:
error driver.find_element or find_elements
I'm trying to click "Create New Network" by using selenium.
<button type="button" id="dt-refreshBtn" class="btn wc-btn--link" data-label="Create New Network" role="link"><span class="icon-button" data-testid="dnxButton-iconButtonContainer" data-awt="networkListing-button-... | error driver.find_element or find_elements | I'm trying to click "Create New Network" by using selenium.
<button type="button" id="dt-refreshBtn" class="btn wc-btn--link" data-label="Create New Network" role="link"><span class="icon-button" data-testid="dnxButton-iconButtonContainer" data-awt="networkListing-button-createNew"><i class="dnac-icon-add-circle" data-... | [
"Now let's go through each error .find_elements() is used for multiple elements and .click() | send_keys() is used for a single element is why the majority will give 'list' object has no attribute 'click' unless you access the individual element.\n.send_keys() is normally used for input tags or textareas and you'd ... | [
0,
0,
0
] | [] | [] | [
"css_selectors",
"python",
"selenium",
"selenium_webdriver"
] | stackoverflow_0074396966_css_selectors_python_selenium_selenium_webdriver.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.