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:
Split a huge csv based on time intervals depending on inner text tags
I have a huge ".csv" file which corresponds to an one-day data file.
Every half-hour of the day, data was recorded during ten minutes. In the file, each half-hour is separated by a text tag, such as "zzzz" or "system sleep", depending on the .cs... | Split a huge csv based on time intervals depending on inner text tags | I have a huge ".csv" file which corresponds to an one-day data file.
Every half-hour of the day, data was recorded during ten minutes. In the file, each half-hour is separated by a text tag, such as "zzzz" or "system sleep", depending on the .csv.
I would like to split the CSV breaking it into the 48 half-hour blocks, ... | [
"What I did was to use the function\nwhich(startsWith(df$treeID, \"system sleep.\")),\nthis retrieved me all the columns that started with this value.\nThen using the function slice and the previous column I can cut the dataframe. However, I can only do it one by one (selecting with [1], [2], etc. the row and slici... | [
0
] | [] | [] | [
"csv",
"intervals",
"python",
"r",
"split"
] | stackoverflow_0074342924_csv_intervals_python_r_split.txt |
Q:
Python request with authentication (access_token)
I am trying to get an API query into python. The command line
curl --header "Authorization:access_token myToken" https://website.example/id
gives some JSON output. myToken is a hexadecimal variable that remains constant throughout. I would like to make this call f... | Python request with authentication (access_token) | I am trying to get an API query into python. The command line
curl --header "Authorization:access_token myToken" https://website.example/id
gives some JSON output. myToken is a hexadecimal variable that remains constant throughout. I would like to make this call from python so that I can loop through different ids and... | [
"The requests package has a very nice API for HTTP requests, adding a custom header works like this (source: official docs):\n>>> import requests\n>>> response = requests.get(\n... 'https://website.example/id', headers={'Authorization': 'access_token myToken'})\n\nIf you don't want to use an external dependency, th... | [
171,
40,
20,
8,
5,
5,
2,
0
] | [] | [] | [
"access_token",
"authentication",
"curl",
"python"
] | stackoverflow_0013825278_access_token_authentication_curl_python.txt |
Q:
TypeError: list indices must be integers or slices, not str in Global terrorism dataset
filterYear = data['Year'] == 1970
I am getting an error of
1 filterYear = data['Year'] == 1970
TypeError: list indices must be integers or slices, not str
I tried to see the datatype of the series and its numeric.
I am at a los... | TypeError: list indices must be integers or slices, not str in Global terrorism dataset | filterYear = data['Year'] == 1970
I am getting an error of
1 filterYear = data['Year'] == 1970
TypeError: list indices must be integers or slices, not str
I tried to see the datatype of the series and its numeric.
I am at a loss
| [
"Without a fuller selection of code that you're trying (unsuccessfully) to run, it's hard to be sure of just where your bug lies, but I suspect your data is a list, of the type:\ndata = [thing1, thing2, thing3, etc.]\n\nIf so, then to retrieve thing2 from data, you must index it using an integer representing the po... | [
0,
0,
0
] | [] | [] | [
"data_science",
"exploratory_data_analysis",
"python"
] | stackoverflow_0074357991_data_science_exploratory_data_analysis_python.txt |
Q:
How to remove a specific line on a text file base on 2 user inputs with Python?
So far this is what I have. I'm trying to make it so that the program asks for the user to input the author of a book and the ISBN of a book, then if there is a line in the file that contains both of these variables, it will remove tha... | How to remove a specific line on a text file base on 2 user inputs with Python? | So far this is what I have. I'm trying to make it so that the program asks for the user to input the author of a book and the ISBN of a book, then if there is a line in the file that contains both of these variables, it will remove that line completely.
print()
print("Removing a Book")
print()
... | [
"Your if condition is not written correctly. You could use not in for your both conditions:\nremovebookAuthor = input(\"Provide the author of the book you would like to remove>\")\nremovebookISBN = input(\"Provide the ISBN of the book you would like to remove>\")\n\nwith open(\"books.txt\", \"r+\") as f:\n lines... | [
0
] | [] | [] | [
"file",
"input",
"python",
"seek",
"truncate"
] | stackoverflow_0074357981_file_input_python_seek_truncate.txt |
Q:
Why does write memory code running for one process only
i have a python code to write memory process , by pymem lib , but this code is run to one process only , when i open more than one active task process for same exe like , game.exe game.exe game.exe in task manager
this code is run for only first process , why... | Why does write memory code running for one process only | i have a python code to write memory process , by pymem lib , but this code is run to one process only , when i open more than one active task process for same exe like , game.exe game.exe game.exe in task manager
this code is run for only first process , why ?
`
from pymem.process import *
from pymem import *
mem = ... | [
"you have a while True: expecting the 3 lines to run more than once, right?\nThat break is telling the while to never run more than once.\nTo answer your question; it runs only once because you are breaking the loop at the end of the first iteration.\n"
] | [
0
] | [] | [] | [
"python",
"python_2.7",
"python_3.x"
] | stackoverflow_0074354931_python_python_2.7_python_3.x.txt |
Q:
How to fillna when based on other column's percentage change when there are more than one NaN value
I have dataframe which has one nan value in column B.
df_stack = pd.DataFrame({'A': [2, 4, 8, 0,6],
'B': [2, 4, np.NaN, 5,7],
'C': [10, 2, 1, 8,9]},
... | How to fillna when based on other column's percentage change when there are more than one NaN value | I have dataframe which has one nan value in column B.
df_stack = pd.DataFrame({'A': [2, 4, 8, 0,6],
'B': [2, 4, np.NaN, 5,7],
'C': [10, 2, 1, 8,9]},
index=['1', '2', '3', '4', '5'])
A B C
1 2 2.0 10
2 4 4.0 2
3 8 NaN 1
4 0... | [
"For a vectorial approach you can use a cumprod per group:\ngroup = df_stack['B'].shift().notna().cumsum()\nfactor = df_stack['C'].pct_change().add(1)\nfill = (df_stack['B'].shift()\n .mul(factor, fill_value=1)\n .groupby(group).cumprod()\n )\n\ndf_stack['B'] = df_stack['B'].fillna(fill)\n\noutp... | [
1,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074357465_pandas_python.txt |
Q:
How to increase count if function called by another function in Python
I am trying to count all tokens given by func1 and print out the result from func2. The problem is that each time func2 gets called the counter does not update for natural reasons because we call the function over and over again. Are there any ... | How to increase count if function called by another function in Python | I am trying to count all tokens given by func1 and print out the result from func2. The problem is that each time func2 gets called the counter does not update for natural reasons because we call the function over and over again. Are there any ways of solving this? NOTE: only func2 is supposed to be changed
import nltk... | [
"You can do like this\nimport nltk\n\ncount = 0\ndef func1(tokens):\n listOfTokens = tokens.split()\n for token in listOfTokens:\n func2(token)\n\ndef func2(token):\n global count\n nltk_tokens = nltk.word_tokenize(token)\n count += len(nltk_tokens)\n print(count) # expected to be 4 but is ... | [
1,
0
] | [] | [] | [
"counter",
"function",
"nltk",
"python",
"token"
] | stackoverflow_0074357973_counter_function_nltk_python_token.txt |
Q:
pandas nested IFs and logic does not get the correct results
Not sure what is the issue in my flow:
This is sample df:
df = pd.DataFrame({'customer':['A','B','C','D','E','F'],
'Traveled':[1,1,1,0,1,0],
'Travel_count':[2,3,5,0,1,0],
'country1':['UK','Italy','... | pandas nested IFs and logic does not get the correct results | Not sure what is the issue in my flow:
This is sample df:
df = pd.DataFrame({'customer':['A','B','C','D','E','F'],
'Traveled':[1,1,1,0,1,0],
'Travel_count':[2,3,5,0,1,0],
'country1':['UK','Italy','CA', '0','UK','0'],
'country2':['JP','IN','CO',... | [
"I would use boolean indexing and numpy.sign:\nimport numpy as np\n\ntravel = (np.sign(df['Travel_count'].sub(3))\n .map({1: ' traveled more than 3 times',\n -1: ' traveled less than 3 times'})\n )\n\nm1 = df['Traveled'].eq(1)\nm2 = df['shopping'].eq('High')\nm3 = travel.notna()\... | [
1,
1,
1
] | [] | [] | [
"if_statement",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074357961_if_statement_pandas_python_python_3.x.txt |
Q:
Python Multiprocessing with Distributed Cluster
I am looking for a python package that can do multiprocessing not just across different cores within a single computer, but also with a cluster distributed across multiple machines. There are a lot of different python packages for distributed computing, but most seem... | Python Multiprocessing with Distributed Cluster | I am looking for a python package that can do multiprocessing not just across different cores within a single computer, but also with a cluster distributed across multiple machines. There are a lot of different python packages for distributed computing, but most seem to require a change in code to run (for example a pr... | [
"If you want a very easy solution, there isn't one.\nHowever, there is a solution that has the multiprocessing interface -- pathos -- which has the ability to establish connections to remote servers through a parallel map, and to do multiprocessing.\nIf you want to have a ssh-tunneled connection, you can do that… ... | [
22,
18,
12,
0
] | [
"Have you looked to disco?\nFeatures:\n\nMap / Reduce paradigm\nPython programming\nDistributed shared disk\nssh underlaying transport\nweb and console interfaces\neasy to add/block/delete a node\nmaster launch slaves nodes without user intervention\nslaves nodes are automatically restarted in case of failure\nnice... | [
-1
] | [
"distributed_computing",
"multiprocessing",
"python"
] | stackoverflow_0026876898_distributed_computing_multiprocessing_python.txt |
Q:
multiplying through multiple tuple elements inside a list to find the minimum value using lambda, filter and map functions
from functools import reduce
orders = [ [1, ("5464", 4, 9.99), ("8274",18,12.99), ("9744", 9, 44.95)]],
[2, ("5464", 9, 9.99), ("9744", 9, 44.95)],
[3, ("5464", 9, 9.99... | multiplying through multiple tuple elements inside a list to find the minimum value using lambda, filter and map functions | from functools import reduce
orders = [ [1, ("5464", 4, 9.99), ("8274",18,12.99), ("9744", 9, 44.95)]],
[2, ("5464", 9, 9.99), ("9744", 9, 44.95)],
[3, ("5464", 9, 9.99), ("88112", 11, 24.99)],
[4, ("8732", 7, 11.99), ("7733",11,18.99), ("88112", 5, 39.95)] ]
print(list(map(lambda x:... | [
"You could try:\nresult = list(map(lambda order: (order[0], min(order[1:], key=lambda o: o[1] * o[2])[0]), orders))\n\nBut I would replace map with a list comprehension:\nresult = [(no, min(order, key=lambda o: o[1] * o[2])[0]) for no, *order in orders]\n\nBoth result in:\n[(1, '5464'), (2, '5464'), (3, '5464'), (4... | [
1,
0
] | [] | [] | [
"filter",
"list_comprehension",
"python",
"reduce"
] | stackoverflow_0074355390_filter_list_comprehension_python_reduce.txt |
Q:
PyQt5. Painting On top of a Button while Keeping the Button Active
I am new to PyQt, but I can't find this question asked. I am trying to have a QT widget that paints on top of a QTbutton. So the user presses the button and a nice rectange is colored on top of the button, but the button still must remain active an... | PyQt5. Painting On top of a Button while Keeping the Button Active | I am new to PyQt, but I can't find this question asked. I am trying to have a QT widget that paints on top of a QTbutton. So the user presses the button and a nice rectange is colored on top of the button, but the button still must remain active and ideally the color has a low opacity to read the lettering. I am trying... | [
"After some very good guidance from @musicamante (thank you!), I was able to solve the problem. Here is a minimum viable implementation\nimport os\nimport sys\n\nfrom PyQt5.QtCore import Qt\nimport PyQt5.QtCore as QtCore\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import *\n\nclass DrawRangeButton(QPushButton)... | [
1
] | [] | [] | [
"pyqt5",
"python",
"qt5",
"qt6"
] | stackoverflow_0074357189_pyqt5_python_qt5_qt6.txt |
Q:
Write a dataframe to a csv file with multicharacter delimiter using Pandas/Python
Any one can please help me to save a Pyspark Dataframe as csv file with multicharacter delimiter using Pandas /python.
Did a research and found to_csv of Pypspark/Pandas can take only 1 character delimiter and there is no option to p... | Write a dataframe to a csv file with multicharacter delimiter using Pandas/Python | Any one can please help me to save a Pyspark Dataframe as csv file with multicharacter delimiter using Pandas /python.
Did a research and found to_csv of Pypspark/Pandas can take only 1 character delimiter and there is no option to provide multicharacter delimiter as separator.
dataframe.to_csv(file.csv, sep="@@")
Erro... | [
"It appears that the pandas to_csv function only allows single-character delimiters/separators.\nSo, Use numpy-savetxt.\nnp.savetxt(file.dat, chunk_data.values, delimiter='~|', fmt='%s',encoding='utf-8')\n\nThen you can convert it to csv format.\n",
"In pyspark, you can use option(\"delimiter\", \"@@\") for multi... | [
0,
0
] | [] | [] | [
"pandas",
"pyspark",
"python"
] | stackoverflow_0074354150_pandas_pyspark_python.txt |
Q:
How to add more fields and remove or change the text from django UserCreationForm?
Im building an django web page for a personal proyect with basic login/signUp system. My problem is that i want to add more input fields like name and lastname ando aslo modify the default text, basically to change it to another lan... | How to add more fields and remove or change the text from django UserCreationForm? | Im building an django web page for a personal proyect with basic login/signUp system. My problem is that i want to add more input fields like name and lastname ando aslo modify the default text, basically to change it to another language.
Thx for the help. :c
I tried to create an CustomField but didn't work
| [
"Django provided UserCreationForm api for creating a new user with three required fields (username,password1,password2), but you can override UserCreationForm like this and can add more fields from Django's default User Model.\nform.py\nfrom django.contrib.auth.forms import UserCreationForm\n\n# User Signup\nclass ... | [
0
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0074352814_django_django_forms_python.txt |
Q:
Is there any efficient way to to make a mask on each cell of a grid rather than using a loop?
I have a catalog of the sky coordinates (for example for 12 million galaxies), ra, dec (perpendicular to the line of sight) and redshift (along the line of sight) and I made a grid on the sky and then I compute different... | Is there any efficient way to to make a mask on each cell of a grid rather than using a loop? | I have a catalog of the sky coordinates (for example for 12 million galaxies), ra, dec (perpendicular to the line of sight) and redshift (along the line of sight) and I made a grid on the sky and then I compute different physical properties in each cell of this grid.
For the pixelization perpendicular to the line of s... | [
"I am not a specialist, but you can use convolution on a 2d array instead of doing a for loop on each elements. It's like applying a mask to it. I can't really give you a clear example. But that's the idea.\n",
"I think you might be looking for np.where\nand you could have your mask with:\nmask = np.where(your_co... | [
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074209003_list_python.txt |
Q:
How to programmatically generate markdown output in Jupyter notebooks?
I want to write a report for classes in Jupyter notebook. I'd like to count some stuff, generate some results and include them in markdown. Can I set the output of the cell to be interpreted as markdown?
I'd like such command: print '$\phi$' to... | How to programmatically generate markdown output in Jupyter notebooks? | I want to write a report for classes in Jupyter notebook. I'd like to count some stuff, generate some results and include them in markdown. Can I set the output of the cell to be interpreted as markdown?
I'd like such command: print '$\phi$' to generate phi symbol, just like in markdown.
In other words, I'd like to hav... | [
"The functions you want are in the IPython.display module.\nfrom IPython.display import display, Markdown, Latex\ndisplay(Markdown('*some markdown* $\\phi$'))\n# If you particularly want to display maths, this is more direct:\ndisplay(Latex('\\phi'))\n\n",
"You are basically asking for two different things:\n\nMa... | [
228,
38,
4,
0,
0
] | [] | [] | [
"ipython",
"jupyter",
"jupyter_notebook",
"python"
] | stackoverflow_0036288670_ipython_jupyter_jupyter_notebook_python.txt |
Q:
Trying to remove linebreaks from text files
I currently have a text file which i wish to convert into an excel worksheet so that it is easier for viewing. The entire text is separated into paragraphs where the sentences contain line breaks and each paragraphs end with a full stop and 2 line breaks before the new p... | Trying to remove linebreaks from text files | I currently have a text file which i wish to convert into an excel worksheet so that it is easier for viewing. The entire text is separated into paragraphs where the sentences contain line breaks and each paragraphs end with a full stop and 2 line breaks before the new paragraph starts as follows:
This is the first ite... | [
"simply you can use this code for parcing using replace methods\ndf1=df.applymap(lambda x: x.replace(\";\",'') if isinstance(x, str) else x) # map function for replacing punctuations\ndf1=df1.applymap(lambda x: x.replace(\",\",'') if isinstance(x, str) else x)\n\n"
] | [
1
] | [] | [] | [
"dataframe",
"excel",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074354795_dataframe_excel_pandas_python_python_3.x.txt |
Q:
DynamoDB - Securely Put/Update to avoid "SQL" Injection (Python)?
I have a Python function that receives user input with no character limitations (spaces, special chars, etc. all allowed). It then writes the input to a DynamoDB table.
In relational SQL, any write transaction to a database should be parameterized t... | DynamoDB - Securely Put/Update to avoid "SQL" Injection (Python)? | I have a Python function that receives user input with no character limitations (spaces, special chars, etc. all allowed). It then writes the input to a DynamoDB table.
In relational SQL, any write transaction to a database should be parameterized to avoid SQL injection. Are there any similar best practices to avoid se... | [
"Injection attacks are absolutely possible in NoSQL databases!\nThe best thing you can do is validate your input and then escape the string parameters\nThe impact of an injection attack in DynamoDB might not be so severe. Still, you can sometimes retrieve results you were not supposed to recover, which could be pro... | [
2,
0
] | [] | [] | [
"amazon_dynamodb",
"dynamodb_queries",
"python",
"security",
"sql_injection"
] | stackoverflow_0074354046_amazon_dynamodb_dynamodb_queries_python_security_sql_injection.txt |
Q:
Pandas Timedelta Multiple If Condition
I would like to create a new column called time_of_day for a dataframe such as below so that 06-12:59 is morning, 13-17:59 is afternoon, 18-22:59 is evening and rest of the time is night.
id
TIME
25
00:01
25
02:01
25
06:55
18
22:03
18
23:33
18
00:33
What I expect
id
... | Pandas Timedelta Multiple If Condition | I would like to create a new column called time_of_day for a dataframe such as below so that 06-12:59 is morning, 13-17:59 is afternoon, 18-22:59 is evening and rest of the time is night.
id
TIME
25
00:01
25
02:01
25
06:55
18
22:03
18
23:33
18
00:33
What I expect
id
TIME
TIME_OF_DAY
25
00:... | [
"Assuming the sample DataFrame you mentioned in the question, you can make the following modifications to make the code work:\ndef conditions(t: pd.Timedelta):\n if pd.Timestamp('06:00:00') <= t < pd.Timestamp('13:00:00'):\n return \"Morning\" \n elif pd.Timestamp('13:00:00') <= t < pd.Timestamp('18:00:00... | [
1,
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074358159_pandas_python.txt |
Q:
How to update and change the current domain array list
For example i have a list of website name examples
exist = ['http://sushiblast.com', 'http://funnyvideos-funny.info', 'https://youtube.com','https://api.forms.app/user/infobyname/minecraft']
Here is the code example that i used
input_str = exist
# Printin... | How to update and change the current domain array list | For example i have a list of website name examples
exist = ['http://sushiblast.com', 'http://funnyvideos-funny.info', 'https://youtube.com','https://api.forms.app/user/infobyname/minecraft']
Here is the code example that i used
input_str = exist
# Printing original string
print ("Original string: " + input_str) ... | [
"import re\n\ninput_str = ['http://sushiblast.com', 'http://funnyvideos-funny.info', 'https://youtube.com','https://api.forms.app/user/infobyname/minecraft']\n \nresult_str = []\n \nfor i in input_str: \n url = re.compile(r\"https?://\")\n url = url.sub('', i)\n if '/' in url:\n url = url.split(... | [
1
] | [] | [] | [
"arrays",
"jupyter",
"python",
"string"
] | stackoverflow_0074358186_arrays_jupyter_python_string.txt |
Q:
Python Blackjack Project Type Error: Chips.place_bet() missing 1 required positional argument
I am trying to write my first python project blackjack. I was advised to write the program with each class and its methods in a different file so that the code would be more manageable. I divided my code up into smaller f... | Python Blackjack Project Type Error: Chips.place_bet() missing 1 required positional argument | I am trying to write my first python project blackjack. I was advised to write the program with each class and its methods in a different file so that the code would be more manageable. I divided my code up into smaller files and used import statements.
When I run my code I get the following error message:
Chips.place... | [
"A few issues:\n\nThe file class.py is redundant. It is not imported, and only defines a class that is already defined in card.py.\n\nThere are two main function definitions. One in blackjack.py and one in player.py. The first one defines a player 'strikeouts27', while the other defines 'seraph', 'codecademy'. The ... | [
0
] | [] | [] | [
"blackjack",
"class",
"function",
"methods",
"python"
] | stackoverflow_0074351716_blackjack_class_function_methods_python.txt |
Q:
python flask import. import error unknown location
i am trying to import create_app from init.py that is located in the website file
but everytime I try to run the code I get
ImportError: cannot import name 'create_app' from 'website' (unknown location)
this is my files
.vscode
env
website
--static
--templa... | python flask import. import error unknown location | i am trying to import create_app from init.py that is located in the website file
but everytime I try to run the code I get
ImportError: cannot import name 'create_app' from 'website' (unknown location)
this is my files
.vscode
env
website
--static
--templates
--__init__.py
--auth.py
--views.py
--mod... | [
"When importing, try from website.templates import create_app. So basically after you put it to import from website, add . following the sub-folder that you desired to import from (in this case it is templates).\n",
"I ran into the same thing, but it appears that these files \"models, views, etc\" isn't in websit... | [
0,
0,
0,
0,
0
] | [] | [] | [
"flask",
"importerror",
"python",
"python_import",
"visual_studio_code"
] | stackoverflow_0066170358_flask_importerror_python_python_import_visual_studio_code.txt |
Q:
Is it possible to use argsort in descending order?
Consider the following code:
avgDists = np.array([1, 8, 6, 9, 4])
ids = avgDists.argsort()[:n]
This gives me indices of the n smallest elements. Is it possible to use this same argsort in descending order to get the indices of n highest elements?
A:
If you nega... | Is it possible to use argsort in descending order? | Consider the following code:
avgDists = np.array([1, 8, 6, 9, 4])
ids = avgDists.argsort()[:n]
This gives me indices of the n smallest elements. Is it possible to use this same argsort in descending order to get the indices of n highest elements?
| [
"If you negate an array, the lowest elements become the highest elements and vice-versa. Therefore, the indices of the n highest elements are:\n(-avgDists).argsort()[:n]\n\nAnother way to reason about this, as mentioned in the comments, is to observe that the big elements are coming last in the argsort. So, you c... | [
327,
91,
10,
8,
7,
4,
3,
2,
0
] | [
"Another way is to use only a '-' in the argument for argsort as in : \"df[np.argsort(-df[:, 0])]\", provided df is the dataframe and you want to sort it by the first column (represented by the column number '0'). Change the column-name as appropriate. Of course, the column has to be a numeric one.\n"
] | [
-1
] | [
"numpy",
"python"
] | stackoverflow_0016486252_numpy_python.txt |
Q:
How to read NumPy 2D array from string?
How can I read a Numpy array from a string? Take a string like:
"[[ 0.5544 0.4456], [ 0.8811 0.1189]]"
and convert it to an array:
a = from_string("[[ 0.5544 0.4456], [ 0.8811 0.1189]]")
where a becomes the object: np.array([[0.5544, 0.4456], [0.8811, 0.1189]]).
I'm lo... | How to read NumPy 2D array from string? | How can I read a Numpy array from a string? Take a string like:
"[[ 0.5544 0.4456], [ 0.8811 0.1189]]"
and convert it to an array:
a = from_string("[[ 0.5544 0.4456], [ 0.8811 0.1189]]")
where a becomes the object: np.array([[0.5544, 0.4456], [0.8811, 0.1189]]).
I'm looking for a very simple interface. A way to c... | [
"The challenge is to save not only the data buffer, but also the shape and dtype. np.fromstring reads the data buffer, but as a 1d array; you have to get the dtype and shape from else where.\nIn [184]: a=np.arange(12).reshape(3,4)\n\nIn [185]: np.fromstring(a.tostring(),int)\nOut[185]: array([ 0, 1, 2, 3, 4, ... | [
24,
9,
8,
0,
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0035612235_numpy_python.txt |
Q:
java.io.FileNotFoundException: Can't find file: How i can save xlxb file from calling URL
Their is new error now i want to download this from calling to url. Means in this code i have to upload it on live but their is no option in live that give the static path of our computer. So, now how i can save the file call... | java.io.FileNotFoundException: Can't find file: How i can save xlxb file from calling URL | Their is new error now i want to download this from calling to url. Means in this code i have to upload it on live but their is no option in live that give the static path of our computer. So, now how i can save the file calling for the url.
import asposecells
import urllib.request
jpype.startJVM("-Xmx10g")
from aspos... | [
"You can try this to increase your memory to 2gb\njpype.startJVM(\"-Xms2g\")\n"
] | [
1
] | [] | [] | [
"java",
"python"
] | stackoverflow_0074342719_java_python.txt |
Q:
How to create a loop to simplify this script so I can perform more iterations
Initial Conditions
Re1i = 3.2*10**7
Re2i = (3/4)*Re1i
lambda1i = ((1/(-2*np.log10((ks/3.7) + (5.74/(Re1i**0.9)))))**2)
lambda2i = ((1/(-2*np.log10((ks/3.7) + (5.74/(Re2i**0.9)))))**2)
V1i = np.sqrt((dh*2*g*d1*d2)/((l1*lambda1i*d2) + (lam... | How to create a loop to simplify this script so I can perform more iterations | Initial Conditions
Re1i = 3.2*10**7
Re2i = (3/4)*Re1i
lambda1i = ((1/(-2*np.log10((ks/3.7) + (5.74/(Re1i**0.9)))))**2)
lambda2i = ((1/(-2*np.log10((ks/3.7) + (5.74/(Re2i**0.9)))))**2)
V1i = np.sqrt((dh*2*g*d1*d2)/((l1*lambda1i*d2) + (lambda2i*l2*((A1**2)/(A2**2)))))
Perform Iteration without loop
Re1ii = (rho*V1i*... | [
"Rather than creating many i, ii, iii... variables, I would recommend storing each type of information in a list. This way you append as you loop and can easily access all the data. So:\nRe1_list = [Re1i, Re2ii,...]\n# = [3.2*10**7, (rho*V1i*d1)/mu,...]\nRe2_list = [Re2i,...]\n...\n\n"
] | [
0
] | [] | [] | [
"for_loop",
"loops",
"math",
"python",
"while_loop"
] | stackoverflow_0074346988_for_loop_loops_math_python_while_loop.txt |
Q:
Can't import name 'sync_playwright' from 'playwright.sync_api' on MacOS and ubutunOS
I'm trying import playwright framework. However, I faced an issue as below:
Traceback (most recent call last):
File "simple.py", line 1, in <module>
from playwright.sync_api import sync_playwright
ImportError: cannot import ... | Can't import name 'sync_playwright' from 'playwright.sync_api' on MacOS and ubutunOS | I'm trying import playwright framework. However, I faced an issue as below:
Traceback (most recent call last):
File "simple.py", line 1, in <module>
from playwright.sync_api import sync_playwright
ImportError: cannot import name 'sync_playwright' from 'playwright.sync_api' (/home/acid/dev/play/venv
/lib/python3.8... | [
"Referencing this:\n\n\npip install --upgrade pip\n\n\n\npip uninstall playwright\n\n\n\npip install playwright\n\n\nChange to your script directory\n\n\nplaywright install\n\n\n\n",
"the problem might be that your file is named playwright.py, maybe try renaming it to trying_playwright.py instead. mxschmitt\n"
] | [
1,
0
] | [] | [] | [
"playwright",
"python"
] | stackoverflow_0070435390_playwright_python.txt |
Q:
Import "tkcalendar" could not be resolved
I am building a GUI on TKinter and wanted to include a calendar to pick dates. I had imported tkcalendar and followed he steps mentioned in its documentation to install tkcalendar.
But, it shows a problem while running the code in VSCode while importing.
from tkcalendar im... | Import "tkcalendar" could not be resolved | I am building a GUI on TKinter and wanted to include a calendar to pick dates. I had imported tkcalendar and followed he steps mentioned in its documentation to install tkcalendar.
But, it shows a problem while running the code in VSCode while importing.
from tkcalendar import Calendar
Import "tkcalendar" could not be... | [
"Open the VS Code Integrated Terminal using the Ctrl+Shift+` shortcut and type the command which python. Then locate the settings.json file inside the .vscode folder of your project and specify the python interpreter path as shown below:\n\"python.pythonPath\": \"output_of_which_python_command\"\n\nThen open VS Cod... | [
3
] | [] | [] | [
"python",
"tkcalendar",
"tkinter"
] | stackoverflow_0074357008_python_tkcalendar_tkinter.txt |
Q:
TFBertForSequenceClassification requires the TensorFlow library but it was not found in your environment
this:
import tensorflow as tf
from transformers import BertTokenizer, TFBertForSequenceClassification
model = TFBertForSequenceClassification.from_pretrained("bert-base-uncased")
Outputs the following error:
... | TFBertForSequenceClassification requires the TensorFlow library but it was not found in your environment | this:
import tensorflow as tf
from transformers import BertTokenizer, TFBertForSequenceClassification
model = TFBertForSequenceClassification.from_pretrained("bert-base-uncased")
Outputs the following error:
ImportError:
TFBertForSequenceClassification requires the TensorFlow library but it was not found in your env... | [
"import tensorflow as tf\nfrom transformers import BertTokenizer, TFBertForSequenceClassification\n\nWorked with\n\nTensorflow-2.7.0\nhuggingface-hub-0.2.1\ntokenizers-0.10.3\ntransformers-4.15.0\nPython-3.7\n\nInstall Tensorflow and Transformers\n!pip install tensorflow\n!pip install transformers\n\n",
"I believ... | [
0,
0,
0,
0
] | [] | [] | [
"huggingface_transformers",
"installation",
"python",
"tensorflow"
] | stackoverflow_0070624869_huggingface_transformers_installation_python_tensorflow.txt |
Q:
Python script does not run through CGI on Apache2
I am using apache2 version Apache/2.4.23
I created a simple python script that I want executed via CGI.
The script does not execute when I open http://localhost/cgi-bin/hello.py.
Instead, I just see the python code in the script:
The script looks like so:
#!/usr/l... | Python script does not run through CGI on Apache2 | I am using apache2 version Apache/2.4.23
I created a simple python script that I want executed via CGI.
The script does not execute when I open http://localhost/cgi-bin/hello.py.
Instead, I just see the python code in the script:
The script looks like so:
#!/usr/local/bin/python
print "Python ok!"
The rights on the s... | [
"Without the cgi_module, even code that is chmod +x will not be executable, so uncomment this line:\n#LoadModule cgi_module libexec/apache2/mod_cgi.so\n\nAnd change your Directory to look like this (mine works like this):\n<Directory \"/Library/WebServer/CGI-Executables\">\n AllowOverride None\n Allow from al... | [
3,
0
] | [] | [] | [
"apache2",
"cgi",
"python"
] | stackoverflow_0043727053_apache2_cgi_python.txt |
Q:
TypeError: check_password() missing 1 required positional argument: 'encoded'
I am trying to authenticate the user made using python manage.py shell,
the password looks like :- pbkdf2_sha256$390000$------------------------$- .
I have used custom user model (abstractbaseuser) and a email authentication backend,
rig... | TypeError: check_password() missing 1 required positional argument: 'encoded' | I am trying to authenticate the user made using python manage.py shell,
the password looks like :- pbkdf2_sha256$390000$------------------------$- .
I have used custom user model (abstractbaseuser) and a email authentication backend,
right now I am handling the user authentication by diretly creating the user in the DB... | [
"check_password() method takes two arguments (entered_password, current_password) you need to pass the user's current password with a user object like this...\nfrom django.contrib.auth.models import check_password\nuser = Usermanagement.objects.get(emailid=username)\n\ncheck_password(password, user.password)\n\n"
] | [
0
] | [] | [] | [
"django",
"django_authentication",
"django_models",
"django_views",
"python"
] | stackoverflow_0074355923_django_django_authentication_django_models_django_views_python.txt |
Q:
How to scrape a URL on a page only once?
I'm not sure how I can count a URL on a page just once.
For example, this page https://www.ig.com/uk/news-and-trade-ideas/ includes the article https://www.ig.com/uk/news-and-trade-ideas/early-morning-call--221103 4 times in different sections.
How can I record it just once... | How to scrape a URL on a page only once? | I'm not sure how I can count a URL on a page just once.
For example, this page https://www.ig.com/uk/news-and-trade-ideas/ includes the article https://www.ig.com/uk/news-and-trade-ideas/early-morning-call--221103 4 times in different sections.
How can I record it just once.
from cgitb import text
import requests
from ... | [
"There are several approaches:\n\nAppend urls to list and lookup while iterating if actual url is not in list else skip scraping it.\n\nOr as mentioned use set and operate from the links:\narticles = []\n\nfor e in set(soup.select('h3>a')):\n e = e.find_parent('div')\n articles.append({\n 'url':e.a.get... | [
0
] | [] | [] | [
"beautifulsoup",
"python",
"web_scraping"
] | stackoverflow_0074357989_beautifulsoup_python_web_scraping.txt |
Q:
make pandas DataFrame to a dict and dropna
I have some pandas DataFrame with NaNs in it.
Like this:
import pandas as pd
import numpy as np
raw_data={'A':{1:2,2:3,3:4},'B':{1:np.nan,2:44,3:np.nan}}
data=pd.DataFrame(raw_data)
>>> data
A B
1 2 NaN
2 3 44
3 4 NaN
Now I want to make a dict out of it and at t... | make pandas DataFrame to a dict and dropna | I have some pandas DataFrame with NaNs in it.
Like this:
import pandas as pd
import numpy as np
raw_data={'A':{1:2,2:3,3:4},'B':{1:np.nan,2:44,3:np.nan}}
data=pd.DataFrame(raw_data)
>>> data
A B
1 2 NaN
2 3 44
3 4 NaN
Now I want to make a dict out of it and at the same time remove the NaNs.
The result should ... | [
"There are many ways you could accomplish this, I spent some time evaluating performance on a not-so-large (70k) dataframe. Although @der_die_das_jojo's answer is functional, it's also pretty slow.\nThe answer suggested by this question actually turns out to be about 5x faster on a large dataframe.\nOn my test data... | [
33,
18,
9,
9,
6,
5,
3,
2,
2,
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0026033301_pandas_python.txt |
Q:
Plotly chart not showing in Jupyter notebook
I have been trying to solve this issue for hours. I followed the steps on the Plotly website and the chart still doesn't show in the notebook.
This is my code for the plot:
colorway = ['#f3cec9', '#e7a4b6', '#cd7eaf', '#a262a9', '#6f4d96', '#3d3b72', '#182844']
data = ... | Plotly chart not showing in Jupyter notebook | I have been trying to solve this issue for hours. I followed the steps on the Plotly website and the chart still doesn't show in the notebook.
This is my code for the plot:
colorway = ['#f3cec9', '#e7a4b6', '#cd7eaf', '#a262a9', '#6f4d96', '#3d3b72', '#182844']
data = [
go.Scatter(
x = immigration.columns,... | [
"You need to change init_notebook_mode call and remove connected=True, if you want to work in offline mode.\nSuch that:\n# Import the necessaries libraries\nimport plotly.offline as pyo\nimport plotly.graph_objs as go\n# Set notebook mode to work in offline\npyo.init_notebook_mode()\n# Create traces\ntrace0 = go.Sc... | [
82,
39,
27,
10,
7,
6,
2,
1,
0
] | [] | [] | [
"jupyter",
"jupyter_lab",
"jupyter_notebook",
"plotly",
"python"
] | stackoverflow_0052771328_jupyter_jupyter_lab_jupyter_notebook_plotly_python.txt |
Q:
Python AttributeError: module 'pandas' has no attribute 'Dataframe'
I'm very new to python and pandas and I'm working a project for a distance matrix.
I got an API that gets distance data from two points and I 'd like to export to excel or csv.
I'm getting a module "pandas" has no attribute "Dataframe"
import requ... | Python AttributeError: module 'pandas' has no attribute 'Dataframe' | I'm very new to python and pandas and I'm working a project for a distance matrix.
I got an API that gets distance data from two points and I 'd like to export to excel or csv.
I'm getting a module "pandas" has no attribute "Dataframe"
import requests
import json
import pandas as pd
origin="Centro Hospitalar Univers... | [
"It is DataFrame, python is case-sensitive, so use it like this:\ndf = pd.DataFrame.from_dict(response.json())\n\n"
] | [
1
] | [
"the reason is because Dataframe column names are essentially string values, which are case sensitive in Python.\nBecause of this, you will need to be careful whenever you utilize column names, such as when renaming a column, accessing columns or performing functions on them.\nAlso not sure, if you're limited by th... | [
-1
] | [
"pandas",
"python"
] | stackoverflow_0074306733_pandas_python.txt |
Q:
Customize the Sidebar (Pages) in Streamlit to Have Sections
I am working on a simple multipage Streamlit app that allows CRUD operations to be performed on some data. I understand that creating a pages directory will allows me to have multiple pages in my app, which is what I have done as shown here,
My project s... | Customize the Sidebar (Pages) in Streamlit to Have Sections | I am working on a simple multipage Streamlit app that allows CRUD operations to be performed on some data. I understand that creating a pages directory will allows me to have multiple pages in my app, which is what I have done as shown here,
My project structure looks like this,
/Home.py
/pages/Add_Pikcups.py
/pages/V... | [
"pages/drops.py\n\nimport streamlit as st\n\n\nst.sidebar.radio('drops sub-menu', options=['add drops', 'view drops'])\nst.sidebar.checkbox('special')\n\npages/pickups.py\n\nimport streamlit as st\n\n\nst.sidebar.selectbox('Person incharge', options=['john', 'peter'], index=0)\nst.sidebar.selectbox('location', opti... | [
0
] | [] | [] | [
"python",
"python_3.x",
"streamlit"
] | stackoverflow_0074355967_python_python_3.x_streamlit.txt |
Q:
RTTM file format
I am currently developing a program making use of the RTTM file format. However, there does not seem to be documentation on the contents. Does anyone have specific elaborations on the fields indicated in this file format?
A:
You can find this in Appendix A of NIST's The 2009 (RT-09) Rich Transcr... | RTTM file format | I am currently developing a program making use of the RTTM file format. However, there does not seem to be documentation on the contents. Does anyone have specific elaborations on the fields indicated in this file format?
| [
"You can find this in Appendix A of NIST's The 2009 (RT-09) Rich Transcription\nMeeting Recognition Evaluation Plan (archived version, original link is dead).\n",
"There is also https://catalog.ldc.upenn.edu/docs/LDC2004T12/RTTM-format-v13.pdf which differs from the spec given by @bernlim mostly in the omission o... | [
5,
5,
1
] | [] | [] | [
"file",
"format",
"python"
] | stackoverflow_0030975084_file_format_python.txt |
Q:
How to use workbook.use_zip64()?
When I use the shodan convert command to convert one of my json.gz files to xlsx in my kali linux, the following message pops up, I want to know how to solve it. Thank you!
`
\Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/xlsxwriter/workbook.py", line 32... | How to use workbook.use_zip64()? | When I use the shodan convert command to convert one of my json.gz files to xlsx in my kali linux, the following message pops up, I want to know how to solve it. Thank you!
`
\Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/xlsxwriter/workbook.py", line 324, in close
- self._store_workbook(... | [
"If you were using XlsxWriter directly you could use workbook.use_zip64() or via the workbook constructor options. I don't know if that option is available via Shodan. It probably isn't.\n"
] | [
0
] | [] | [] | [
"linux",
"python",
"shodan",
"xlsxwriter"
] | stackoverflow_0074357921_linux_python_shodan_xlsxwriter.txt |
Q:
How to override FOR IN loop list behavior?
I try to implement list which returns wrapped elements when accessing directly (by index) or via FOR IN loop statement. At present I have following code:
class ItemWrappedList(list):
def __getitem__(self, y):
result = super().__getitem__(y)
return f'<... | How to override FOR IN loop list behavior? | I try to implement list which returns wrapped elements when accessing directly (by index) or via FOR IN loop statement. At present I have following code:
class ItemWrappedList(list):
def __getitem__(self, y):
result = super().__getitem__(y)
return f'<item>{result}</item>'
lst = ItemWrappedList(['... | [
"Overriding the __iter__ method should do the trick:\nclass ItemWrappedList(list):\n\n def __getitem__(self, y):\n result = super().__getitem__(y)\n return f'<item>{result}</item>'\n\n def __iter__(self):\n return (f'<item>{x}</item>' for x in list.__iter__(self))\n\n\nlst = ItemWrappedLi... | [
1,
0
] | [] | [] | [
"list",
"overriding",
"python"
] | stackoverflow_0074358376_list_overriding_python.txt |
Q:
Include my markdown README into Sphinx
I would like to include my project's README.md into my Sphinx documentation like in
Can sphinx link to documents that are not located in directories below the root document?
- which is that in the resulting Sphinx html documentation I click on a link in the table of contents ... | Include my markdown README into Sphinx | I would like to include my project's README.md into my Sphinx documentation like in
Can sphinx link to documents that are not located in directories below the root document?
- which is that in the resulting Sphinx html documentation I click on a link in the table of contents on the welcome page and get to the README.md... | [
"You need to edit your readme_link.rst as follows: \nReadme File\n===========\n\n.. mdinclude:: ../../README.md\n\nNote that the section header is designated with = characters rather than - characters.\nThere are two factors that contribute to that.\nHow include works\nStandard include (not mdinclude) actually read... | [
32,
29,
12,
9,
6,
0,
0
] | [] | [] | [
"markdown",
"python",
"python_sphinx",
"restructuredtext"
] | stackoverflow_0046278683_markdown_python_python_sphinx_restructuredtext.txt |
Q:
How can a GRIB file be opened with pygrib without first downloading the file?
The documentation for pygrib shows a function called fromstring which creates a gribmessage instance from a python bytes object representing a binary grib message. I might be misunderstanding the purpose of this function, but it leads me... | How can a GRIB file be opened with pygrib without first downloading the file? | The documentation for pygrib shows a function called fromstring which creates a gribmessage instance from a python bytes object representing a binary grib message. I might be misunderstanding the purpose of this function, but it leads me to believe I can use it in place of downloading a GRIB file and using the open fun... | [
"As stated by jasonharper you can use pygrib.fromstring(). I just tried it myself and this works.\nHere is the link to the documentation.\n",
"Starting with pygrib v2.1.4, the changelog says that pygrib.open() now accepts io.BufferedReader object as an input argument.\nsee pygrib changelog here\nThat would theore... | [
1,
0
] | [] | [] | [
"grib",
"pygrib",
"python"
] | stackoverflow_0061737401_grib_pygrib_python.txt |
Q:
Is a list content is in a long string?
I want to know whether a list content is in a long string. such as:
aa=["column","is","the","word","others", "excludition"] # the list content
bb="from the long text" #the long string
cc=[wd in bb for wd in aa]
but the cc is [False, False, True, False, False, False].
I want ... | Is a list content is in a long string? | I want to know whether a list content is in a long string. such as:
aa=["column","is","the","word","others", "excludition"] # the list content
bb="from the long text" #the long string
cc=[wd in bb for wd in aa]
but the cc is [False, False, True, False, False, False].
I want to need the True. if one of the items is tr... | [
"You can use any:\ncc=any([wd in bb for wd in aa])\n\n",
"aa=[\"column\",\"is\",\"the\",\"word\",\"others\", \"excludition\"] # the list content\nbb=\"from the long text\" #the long string\ncc=[wd in bb for wd in aa]\n\nif any(word in bb for word in aa):\n print('yes')\n\n"
] | [
2,
2
] | [] | [] | [
"list",
"python",
"string"
] | stackoverflow_0074358609_list_python_string.txt |
Q:
How to match input and output shapes of Conv2D AutoEncoder
Having a set of black and white images with the following shape (1000, 11, 1). I'm trying to modify the keras mnist example to work with my data, so I've written the following code:
input_img = layers.Input(shape=(1000, 11, 1))
x = layers.Conv2D(16, (3, 3... | How to match input and output shapes of Conv2D AutoEncoder | Having a set of black and white images with the following shape (1000, 11, 1). I'm trying to modify the keras mnist example to work with my data, so I've written the following code:
input_img = layers.Input(shape=(1000, 11, 1))
x = layers.Conv2D(16, (3, 3), activation='relu', padding='same')(input_img)
x = layers.MaxP... | [
"You can modify the network structure of the decoder as follows to match the input shape of the encoder and output shape of the decoder. The Cropping2D layer crops along spatial dimensions, i.e. height and width.\ninput_img = layers.Input(shape=(1000, 11, 1))\n\nx = layers.Conv2D(16, (3, 3), activation='relu', padd... | [
1
] | [] | [] | [
"autoencoder",
"keras",
"machine_learning",
"python",
"tensorflow"
] | stackoverflow_0068802229_autoencoder_keras_machine_learning_python_tensorflow.txt |
Q:
Python nested Json to Dataframe (Injixo WFM API)
I'm trying to model a DataFrame from a JSON file, which has a nested list for the values.
Here is the Json i try to get into a DF:
{'curve_values':
[{'curve_event_type_id': 4,
'curve_id': 1031,
'curve_value_type_id': 1005,
'curve_version_id': 1001,
'date': '202... | Python nested Json to Dataframe (Injixo WFM API) | I'm trying to model a DataFrame from a JSON file, which has a nested list for the values.
Here is the Json i try to get into a DF:
{'curve_values':
[{'curve_event_type_id': 4,
'curve_id': 1031,
'curve_value_type_id': 1005,
'curve_version_id': 1001,
'date': '2022-09-01',
'raster': 1800,
'values': [6.84, 5.09, 4.85... | [
"can you try:\nif response.ok:\n dictr = response.json()\n recs = dictr['curve_values']\n df = pd.DataFrame(dictr['curve_values'])\n df=df.explode('values')\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"json",
"nested",
"pandas",
"python"
] | stackoverflow_0074358681_dataframe_json_nested_pandas_python.txt |
Q:
Pipenv Install command not able to find compatible version
I am trying to install pyarrow 4.0.0 in my project. Python version is 3.6.
install pyarrow==4.0.0
I am getting the following error
ERROR: Could not find a version that satisfies the requirement pyarrow~=4.0.0 (from versions: 0.9.0, 0.10.0, 0.11.0, 0.11.1,... | Pipenv Install command not able to find compatible version | I am trying to install pyarrow 4.0.0 in my project. Python version is 3.6.
install pyarrow==4.0.0
I am getting the following error
ERROR: Could not find a version that satisfies the requirement pyarrow~=4.0.0 (from versions: 0.9.0, 0.10.0, 0.11.0, 0.11.1, 0.12.0, 0.12.1, 0.13.0, 0.14.0, 0.15.1, 0.16.0, 0.17.0, 0.17.1,... | [
"The first pyarrow release that was released with wheels support for M1 was 5.0.0. See this JIRA ticket for some historic:\nhttps://issues.apache.org/jira/browse/ARROW-12122\n"
] | [
1
] | [] | [] | [
"pip",
"pipenv",
"pipenv_install",
"pyarrow",
"python"
] | stackoverflow_0074356470_pip_pipenv_pipenv_install_pyarrow_python.txt |
Q:
Selenium: Issue with reassignment in For Loop
I tried debugging my program with print statements to see what was going on during each iteration.
This part works fine:
The program goes through a total of 50 combinations of the drop-down menus (25 for each year).
This part isn't working:
However, for some reason the... | Selenium: Issue with reassignment in For Loop | I tried debugging my program with print statements to see what was going on during each iteration.
This part works fine:
The program goes through a total of 50 combinations of the drop-down menus (25 for each year).
This part isn't working:
However, for some reason the totals dictionary is only storing the inputs from ... | [
"@Alex Karamfilov figured it out with his comment:\n\"Just a wild guess but is it possible that you overwrite the value for the same key in the dictionary. Since this is a dictionary and keys should be unique, this might be the reason to have only the second iteration values \"\nIt was a dumb error on my part. The ... | [
2
] | [] | [] | [
"python",
"selenium",
"selenium_webdriver"
] | stackoverflow_0074358541_python_selenium_selenium_webdriver.txt |
Q:
Multiple exceptions in one block
I have socket.error and socket.timeout in one exception block because it wouldn't allow two exception blocks with socket argument, like so:
except socket.error as e:
print("2")
server_response.setCode(ServerResponse.CRITICAL)
server_response.writeCriticalMessage('Custom... | Multiple exceptions in one block | I have socket.error and socket.timeout in one exception block because it wouldn't allow two exception blocks with socket argument, like so:
except socket.error as e:
print("2")
server_response.setCode(ServerResponse.CRITICAL)
server_response.writeCriticalMessage('Customer: ' + user['name'] + ' - Connection ... | [
"I try this explanation because you have put the tag python-unittest in your question.\nSimulate the exceptions by unittest.mock\n\nI have put socket.timeout before socket.error (see the function socket_func() in the code below)\nI have created a test class called MyTestCase with 2 test: test_exception_socket_error... | [
0
] | [] | [] | [
"python",
"python_unittest",
"sockets"
] | stackoverflow_0074358229_python_python_unittest_sockets.txt |
Q:
Why does mypy report error: Argument after ** must be a mapping, not "object"
I have code that looks something like this:
class MyClass:
k: int
v: int
def __init__(self, *, k, v):
self.k = k
self.v = v
def getkv(self):
return self.k, self.v
def test():
a = [{"k": 5, "... | Why does mypy report error: Argument after ** must be a mapping, not "object" | I have code that looks something like this:
class MyClass:
k: int
v: int
def __init__(self, *, k, v):
self.k = k
self.v = v
def getkv(self):
return self.k, self.v
def test():
a = [{"k": 5, "v": 25}, {"k": 7, "v": 49}, {"k": 9, "v": 81}]
mcl = dict(MyClass(**x).getkv()... | [
"For what mypy knows, a might be a list of anything. Help it by typing it as a list of dicts:\nfrom typing import List\n\n...\n\na: List[dict] = [{\"k\": 5, \"v\": 25}, {\"k\": 7, \"v\": 49}, {\"k\": 9, \"v\": 81}]\n\n"
] | [
2
] | [] | [] | [
"mypy",
"python"
] | stackoverflow_0074358778_mypy_python.txt |
Q:
word cloud for expressions more than one word
I have an excel file with a column containing some string values. some of these values are more than one word. for example I have a cell with the value "Mental health". but when I create the word cloud it divides it into two words. what should I do if I want to have ea... | word cloud for expressions more than one word | I have an excel file with a column containing some string values. some of these values are more than one word. for example I have a cell with the value "Mental health". but when I create the word cloud it divides it into two words. what should I do if I want to have each column as one observation?
df = pd.read_csv(r"C:... | [
"To solve this problem first I used the value_counts() function to get the frequency of my \"Name\" values.\nthen i changed my code as follows...\nd = dict(zip(df[\"Name\"], df[\"frequencies\"]))\nwc = WordCloud(background_color = \"white\", font_path='arial',\n colormap='prism', random_state=1,repeat... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074254971_python.txt |
Q:
How to transpose a 2D-list into a column view?
I have this 2D-list
[["a1", "b1", "c1"], ["a2", "b2", "c2"]]
That I want to transpose to a column-view.
Each inner list has the same size.
Expected result :
[['a1', 'a2'], ['b1', 'b2'], ['c1', 'c2']]
I'm looking for a one-liner answer.
I've tried the code below that... | How to transpose a 2D-list into a column view? | I have this 2D-list
[["a1", "b1", "c1"], ["a2", "b2", "c2"]]
That I want to transpose to a column-view.
Each inner list has the same size.
Expected result :
[['a1', 'a2'], ['b1', 'b2'], ['c1', 'c2']]
I'm looking for a one-liner answer.
I've tried the code below that works but needs one line to initialize the l_col va... | [
"In newer versions of Python, you can use:\nA = [[\"a1\", \"b1\", \"c1\"], [\"a2\", \"b2\", \"c2\"]]\nA_transpose = list(map(list,zip(*A)))\n\nprint('A_transpose: ', A_transpose)\n\n# output:\n# A_transpose: [['a1', 'a2'], ['b1', 'b2'], ['c1', 'c2']]\n\n\nPS. For many applications, list(zip(*A)) also... | [
2,
1
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074358784_list_python.txt |
Q:
How to append 1 row to DataFrame
I have a text file which I read into a pandas DataFrame.
File A:
2009,7,1,3,101,13.03,89.33,0.6,287.69,0
2009,7,1,6,102,19.3,55,1,288.67,0
2009,7,1,9,103,22.33,39.67,1,289.6,0
2009,7,1,12,104,21.97,41,1,295.68,0
Read this into a DataFrame
>>> import pandas as pd
>>> from datetime ... | How to append 1 row to DataFrame | I have a text file which I read into a pandas DataFrame.
File A:
2009,7,1,3,101,13.03,89.33,0.6,287.69,0
2009,7,1,6,102,19.3,55,1,288.67,0
2009,7,1,9,103,22.33,39.67,1,289.6,0
2009,7,1,12,104,21.97,41,1,295.68,0
Read this into a DataFrame
>>> import pandas as pd
>>> from datetime import datetime as dtdt
>>> par3 = lam... | [
"pandas indexer can make row or column\ndf.loc[bb] = c.split()\n\n"
] | [
2
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074358673_dataframe_pandas_python.txt |
Q:
if a row satisfies a condition drop it, else don't drop it
import pandas as pd; import numpy as np;
df = {'id': [1, 2, 3, 4, 5, 6],
'created_at': ['2020-02-01', '2020-02-02', '2020-02-02', '2020-02-02', '2020-02-03','2020-02-02'],
'type': ['red', np.nan, np.nan, 'blue', 'yellow', np.nan]}
df = pd.DataFrame ... | if a row satisfies a condition drop it, else don't drop it | import pandas as pd; import numpy as np;
df = {'id': [1, 2, 3, 4, 5, 6],
'created_at': ['2020-02-01', '2020-02-02', '2020-02-02', '2020-02-02', '2020-02-03','2020-02-02'],
'type': ['red', np.nan, np.nan, 'blue', 'yellow', np.nan]}
df = pd.DataFrame (df, columns = ['id', 'created_at','type'])
If created_at=2020-... | [
"You would need to use boolean indexing:\n# is the date 2020-02-01?\nm1 = df['created_at'].eq('2020-02-01')\n# is the id 2 or 6?\nm2 = df['id'].isin([2, 6])\n\n# keep if NOT both conditions are matched\nout = df[~(m1&m2)]\n\nAlternatively:\n# is the date NOT 2020-02-01?\nm1 = df['created_at'].ne('2020-02-01')\n# is... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074358860_dataframe_pandas_python.txt |
Q:
405 HTML: Method Not Allowed
I have created a calendar that is embedded in my website. There is an option for admins to create events and when I try to create an event, I get faced with a 405 Error. Could someone please point me in the right direction into why this isn't working, when in previous versions of Pytho... | 405 HTML: Method Not Allowed | I have created a calendar that is embedded in my website. There is an option for admins to create events and when I try to create an event, I get faced with a 405 Error. Could someone please point me in the right direction into why this isn't working, when in previous versions of Python Django, it was working?
My code ... | [
"Your calendar/event/new/ route points to EventView, which only has a get method defined. Posting to a view without a post method will produce a 405 error.\nAlso, your EditEventView doesn't edit an event, but instead always creates a new event.\nTo fix this, you need to do this:\n\nCopy the post method in EditEvent... | [
1
] | [] | [] | [
"django",
"html",
"http_status_code_405",
"python",
"python_3.x"
] | stackoverflow_0074357216_django_html_http_status_code_405_python_python_3.x.txt |
Q:
Removing a key in a list of dictionary with if value condition in python
Here's my sample data, I want to remove the keys with "N/A" values using python.
Data = [
{
"Area": "Los Angeles",
"Idle": "N/A",
"Downtime": "N/A",
"Production": "N/A",
"Total": "0.00 kWh",
"Total_Cost": "$ 0.00",
... | Removing a key in a list of dictionary with if value condition in python | Here's my sample data, I want to remove the keys with "N/A" values using python.
Data = [
{
"Area": "Los Angeles",
"Idle": "N/A",
"Downtime": "N/A",
"Production": "N/A",
"Total": "0.00 kWh",
"Total_Cost": "$ 0.00",
"Total_Idle_Cost": "N/A"
},
{
"Area": "Oklohoma",
"Idle": "N/A"... | [
"you can try:\nData = [{key: value for key, value in entry.items() if value != \"N/A\"} for entry in Data]\n\n",
"Try this:\ndef returnNewDict(oldDict):\n newDict = {}\n for key, value in oldDict.items():\n if value != 'N/A':\n newDict[key] = value\n return newDict\n\nnewData = [returnN... | [
2,
0,
0
] | [] | [] | [
"dictionary",
"list",
"python",
"python_2.7",
"python_3.x"
] | stackoverflow_0073030845_dictionary_list_python_python_2.7_python_3.x.txt |
Q:
Get indices in maximum sum of non-consecutive elements of an array
I came up with a DP algorithm to compute the maximum sum of non-consecutive elements of an array. I understand there are similar questions but none of them record the indices of the elements which make up the maximum sum.
Original algorithm:
def ma... | Get indices in maximum sum of non-consecutive elements of an array | I came up with a DP algorithm to compute the maximum sum of non-consecutive elements of an array. I understand there are similar questions but none of them record the indices of the elements which make up the maximum sum.
Original algorithm:
def maxSum(arr) {
sum = [0]*len(arr);
sum_indices = []
for i in ra... | [
"If we can assume that arr has only nonnegative elements, then the following should work.\ndef max_sum(arr):\n sum_and_ind= []\n for i in range(len(arr)):\n best = (arr[i], -1)\n if 1 < i:\n best = max(best, (sum_and_ind[i-2][0] + arr[i], i-2))\n if 2 < i:\n best = m... | [
0
] | [] | [] | [
"algorithm",
"dynamic_programming",
"python"
] | stackoverflow_0074356079_algorithm_dynamic_programming_python.txt |
Q:
How to merge rows into one selecting best data from each row?
I am trying to make a function that goes through a dataframe, this df has a column, let's call it "matched" which is numerical and it's an identifier for rows that I need to merge, so it looks something like this:
Id
matched
name
animals
flying
hierarc... | How to merge rows into one selecting best data from each row? | I am trying to make a function that goes through a dataframe, this df has a column, let's call it "matched" which is numerical and it's an identifier for rows that I need to merge, so it looks something like this:
Id
matched
name
animals
flying
hierarchy
1
1
peter
cow
yes
1
2
1
pedro
no
2
3
2
angel
dog
yes... | [
"You can use:\n# is the hierarchy equal to the min per group?\nm = df.groupby('matched')['hierarchy'].transform('min').eq(df['hierarchy'])\n\n# keep the matching conditions\nout = df[m]\n\noutput:\n Id matched name animals flying hierarchy\n0 1 1 peter cow yes 1\n2 3 2 ange... | [
0,
0
] | [] | [] | [
"loops",
"merge",
"pandas",
"python"
] | stackoverflow_0074358900_loops_merge_pandas_python.txt |
Q:
How to resolve "Invalid Python interpreter name 'python.exe'!" error in PyCharm
I'm trying to add my Python interpreter to PyCharm but whenever I navigate to python.exe and click Ok it says Invalid Python interpeter name 'python.exe'! (the spelling mistake for interpeter is how it's spelled in the dialog that appe... | How to resolve "Invalid Python interpreter name 'python.exe'!" error in PyCharm | I'm trying to add my Python interpreter to PyCharm but whenever I navigate to python.exe and click Ok it says Invalid Python interpeter name 'python.exe'! (the spelling mistake for interpeter is how it's spelled in the dialog that appears)
I installed Python through the Microsoft app store. The interpreter is located a... | [
"I got the same error message when I imported a project of an existing virtual environment to pyCharm. Though the name and path of the exe was correct, pyCharm did not accept it.\nMy solution was to remove the Interpreter in pyCharm and to add it again. Then the Error was gone. Perhaps that can help someone ...\n",... | [
4,
1,
0,
0
] | [
"Try PyCharm 2019.2 EAP build. The problem should be fixed: https://youtrack.jetbrains.com/issue/PY-33406 (or better use Python from python.org).\nI reported the typo to PyCharm's bug tracker, thanks https://youtrack.jetbrains.com/issue/PY-36686\n",
"In case anyone else is still facing this issue, reinstalling Py... | [
-1,
-1
] | [
"pycharm",
"python",
"python_3.7",
"python_3.x"
] | stackoverflow_0056815082_pycharm_python_python_3.7_python_3.x.txt |
Q:
django.db.utils.OperationalError: no such table: product, django cannot import form.py into view.py
I've 3 pages Model, Forms and View
In model.py i define my table
#model.py
class Prod(models.Model):
id = models.CharField(primary_key=True, max_length=10, blank=False, null=False)
description = models.Te... | django.db.utils.OperationalError: no such table: product, django cannot import form.py into view.py | I've 3 pages Model, Forms and View
In model.py i define my table
#model.py
class Prod(models.Model):
id = models.CharField(primary_key=True, max_length=10, blank=False, null=False)
description = models.TextField(blank=True, null=True)
class Meta:
managed = False
db_table = 'prod... | [
"Remove the ProdForm definition from forms.py\nCall python manage.py makemigrations\nCall python manage.py migrate\nAdd form back into forms.py\n\nNote: Always migrate your new model definitions before using them as a dependency\n\n"
] | [
1
] | [] | [] | [
"django",
"django_forms",
"django_models",
"django_views",
"python"
] | stackoverflow_0074358798_django_django_forms_django_models_django_views_python.txt |
Q:
Unable to open chromium browser in VPS with Selenium
I need to open chromium or chrome with selenium in Ubuntu 22 deployed in Digital Ocean VPS droplet. The issue is it doesnt open a chrome tab, the chromium and chromedriver are same version.This works fine in my localhost, with ubuntu 22.However, I was not able t... | Unable to open chromium browser in VPS with Selenium | I need to open chromium or chrome with selenium in Ubuntu 22 deployed in Digital Ocean VPS droplet. The issue is it doesnt open a chrome tab, the chromium and chromedriver are same version.This works fine in my localhost, with ubuntu 22.However, I was not able to run it when deployed in vps
options = webdriver.Chrome... | [
"After several attempt, I finally found the reason\nVPS doesn't allow selenium to open the browser.It only works in headless mode, which doesn't fit my requirements since I have plugins and headless mode will not run with plugins\n"
] | [
0
] | [] | [] | [
"python",
"selenium",
"vps"
] | stackoverflow_0074274849_python_selenium_vps.txt |
Q:
Comparing hex number ranges for unicode encodings gives unexpected result
I'm using UTF-8 encodings of Japanese Characters to distinguish so called Hiragana characters from Kanji characters in my script. The Unicode table for the relevant characters can be found here. As is evident from the table, the knji I want ... | Comparing hex number ranges for unicode encodings gives unexpected result | I'm using UTF-8 encodings of Japanese Characters to distinguish so called Hiragana characters from Kanji characters in my script. The Unicode table for the relevant characters can be found here. As is evident from the table, the knji I want to identify are part of the last table called "CJK unifed ideographs - Common a... | [
"You don't need this encoding business at all. Just compare unicode characters directly:\ndef find_kanji(chars):\n min_char = '\\u4e00'\n max_char = '\\u9faf'\n\n return [\n c for c in chars\n if min_char <= c <= max_char\n ]\n\nAlternatively, consider using a range regular expression, or ... | [
1
] | [] | [] | [
"encoding",
"python",
"unicode",
"utf_8"
] | stackoverflow_0074359004_encoding_python_unicode_utf_8.txt |
Q:
scrapy: "YourSpider" object has no attribute 'crawler'
I'm building a simple crawler for a project, and I have this error in my code. it runs anyway but I would like to understand and get it sorted out.
My spider looks like this:
class BookSpider(scrapy.Spider):
name = "books"
@classmethod
def from_crawler(cls,... | scrapy: "YourSpider" object has no attribute 'crawler' | I'm building a simple crawler for a project, and I have this error in my code. it runs anyway but I would like to understand and get it sorted out.
My spider looks like this:
class BookSpider(scrapy.Spider):
name = "books"
@classmethod
def from_crawler(cls, crawler):
return cls(crawler.stats)
def __init__(self,... | [
"I don't think your spider is correctly inheriting from the crawler class. When I ran into this error, I was able to solve it by adding a super() call in the from_crawler() method that brings in the crawler attributes/methods into your custom spider\nHere's an example of this (see the from_crawler method):\nfrom sc... | [
1,
0
] | [] | [] | [
"python",
"scrapy",
"web_crawler"
] | stackoverflow_0050492234_python_scrapy_web_crawler.txt |
Q:
How to replace the values of nested lists stored in python dataframe?
I have the following dataframe
data = [[[[[1, 2, 0], [1]],[[1, 2], [4]]],
[[[[1, 2], [4]]]], [[[1]]]], [[[[1, 2, 0], [1]],[[1, 2], [4]]],
[[[[1, 2], [4]]]], [[[1]]]]]
df = pd.DataFrame(data)
Also, I have a second dataframe df2:... | How to replace the values of nested lists stored in python dataframe? | I have the following dataframe
data = [[[[[1, 2, 0], [1]],[[1, 2], [4]]],
[[[[1, 2], [4]]]], [[[1]]]], [[[[1, 2, 0], [1]],[[1, 2], [4]]],
[[[[1, 2], [4]]]], [[[1]]]]]
df = pd.DataFrame(data)
Also, I have a second dataframe df2:
data2 = [[1, 10], [1, 15], [1, 14], [1, 20], [1, 18]]
df2 = pd.DataFrame(d... | [
"Try this recursive solution\ndata = [[[[[1, 2, 0], [1]],[[1, 2], [4]]],\n [[[[1, 2], [4]]]], [[[1]]]], [[[[1, 2, 0], [1]],[[1, 2], [4]]],\n [[[[1, 2], [4]]]], [[[1]]]]]\ndata2 = [[1, 10], [1, 15], [1, 14], [1, 20], [1, 18]]\ndef new_data(data, data2):\n res = []\n for i in data:\n if isinstance(... | [
2,
0
] | [] | [] | [
"list",
"nested",
"pandas",
"python"
] | stackoverflow_0074358830_list_nested_pandas_python.txt |
Q:
Check if Excel is empty
I have a bunch of excel files automatically generated by a process. However, some of them are empty because the process stopped before actually writing anything. These excels do not even contain any columns, so they are just an empty sheet.
I'm now runnin some scripts on each of the excels,... | Check if Excel is empty | I have a bunch of excel files automatically generated by a process. However, some of them are empty because the process stopped before actually writing anything. These excels do not even contain any columns, so they are just an empty sheet.
I'm now runnin some scripts on each of the excels, so I would like to check if ... | [
"Why not using a try/except:\ntry:\n # try reading the excel file\n df = pd.read_excel(…) # or pd.read_csv(…)\nexcept pd.errors.EmptyDataError:\n # do something else if this fails\n df = pd.DataFrame()\n\n"
] | [
1
] | [] | [] | [
"excel",
"pandas",
"python"
] | stackoverflow_0074359218_excel_pandas_python.txt |
Q:
Finding fft peaks with scipy and plotting them
I'm trying to learn how to efficiently use SciPy.
My task is to take a series of audio samples, to plot their fft and try to characterize them finding peaks.
I have the following test program:
import struct
import numpy as np
import scipy
from matplotlib import pyplot... | Finding fft peaks with scipy and plotting them | I'm trying to learn how to efficiently use SciPy.
My task is to take a series of audio samples, to plot their fft and try to characterize them finding peaks.
I have the following test program:
import struct
import numpy as np
import scipy
from matplotlib import pyplot as plt
def fft_plot(audio, rate):
n = len(audi... | [
"It turns out I had (at least) two mistakes in my code:\n\nI did not cut high end of fft (I just avoided plotting it), so peaks were found in the high end of spectrum.\nI forgot to rescale peak plotting.\n\nHere follows a correctly working test script.\nimport struct\nimport numpy as np\nimport scipy\nfrom matplotl... | [
0
] | [] | [] | [
"fft",
"python",
"scipy"
] | stackoverflow_0074354449_fft_python_scipy.txt |
Q:
Extracting Excel Charts as PNG Files. Getting some corrupted photos as a result
I am trying to save some Excel charts as PNG files on my documents folder, so I can later automatically send outlook emails with the corresponding charts images on the email body.
However, some png files are being extracted as corrupte... | Extracting Excel Charts as PNG Files. Getting some corrupted photos as a result | I am trying to save some Excel charts as PNG files on my documents folder, so I can later automatically send outlook emails with the corresponding charts images on the email body.
However, some png files are being extracted as corrupted unable to open.
Below is the code I am currently using and, in theory, is working ... | [
"Seems like an issue of Zoom in / Zoom out on the Excel Worksheet. I had big zoom on some sheets and the graphs that were not currently \"showing\" on the screen were not loading the information.\nAs a result, this was generating an PNG corrupted file.\n"
] | [
0
] | [] | [] | [
"charts",
"excel",
"png",
"python"
] | stackoverflow_0074358899_charts_excel_png_python.txt |
Q:
I want my program to not count same numbers again
Here is my code:
from random import randint
total = int(input('Enter the number of iterations'))
count=0
for i in range(1,total+1):
print('i',i)
number1=randint(1,5)
print('num1',number1)
number2=randint(1,5)
print('num2',number2)
if numbe... | I want my program to not count same numbers again | Here is my code:
from random import randint
total = int(input('Enter the number of iterations'))
count=0
for i in range(1,total+1):
print('i',i)
number1=randint(1,5)
print('num1',number1)
number2=randint(1,5)
print('num2',number2)
if number1==number2:
count+=1
print('The number matched... | [
"from random import randint\ntotal = int(input('Enter the number of iterations')) \ncount=0\nmy_dict = {}\nfor i in range(1,6):\n my_dict[i] = 0\nfor i in range(1,total+1):\n print('i',i)\n number1=randint(1,5)\n print('num1',number1)\n number2=randint(1,5)\n print('num2',number2)\n if number1... | [
0,
0
] | [] | [] | [
"data_structures",
"line",
"python"
] | stackoverflow_0074359032_data_structures_line_python.txt |
Q:
How to remove duplicates lists in a column
I'm a beginner at coding & I'm stuck! :(
I have 2 columns: Purpose and Frequency for 10 000++ of data with a list of items in each row under "Purpose"
Purpose
Frequency
Bathe, Eat, Sleep
5
Sleep, Eat, Bathe
4
Talk, Eat, Sleep, Movie
10
Sleep, Talk, Movie, Eat
8
Slee... | How to remove duplicates lists in a column | I'm a beginner at coding & I'm stuck! :(
I have 2 columns: Purpose and Frequency for 10 000++ of data with a list of items in each row under "Purpose"
Purpose
Frequency
Bathe, Eat, Sleep
5
Sleep, Eat, Bathe
4
Talk, Eat, Sleep, Movie
10
Sleep, Talk, Movie, Eat
8
Sleep, Eat, Talk, Movie
2
My desired o... | [
"You can aggregate sum with frozensets:\ns = df['Purpose'].apply(lambda x: frozenset(x.split(', ')))\ndf.groupby(s)['Frequency'].sum().reset_index()\n\nOr by sorted splitted values:\ns = df['Purpose'].apply(lambda x: ', '.join(sorted(x.split(', '))))\ndf = df.groupby(s)['Frequency'].sum().reset_index()\nprint (df)\... | [
1,
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074358985_pandas_python.txt |
Q:
How to plot a horizon bar with heatmap style in matplotlib?
I'd like to plot a 1D array horizontally in matplotlib. It needs to be drawn as a bar, but different from the ordinary bar chart, its color changes according to the size of the value, which is similar to a heatmap. You can think of it as a heatmap (horizo... | How to plot a horizon bar with heatmap style in matplotlib? | I'd like to plot a 1D array horizontally in matplotlib. It needs to be drawn as a bar, but different from the ordinary bar chart, its color changes according to the size of the value, which is similar to a heatmap. You can think of it as a heatmap (horizontal) with only one row.
The simulated data is as follows. It con... | [
"\nMatplotlib has an ad hoc norm to deal with your problem, matplotlib.colors.TwoSlopeNorm.\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\n\nnp.random.seed()\ndiverging_cmap = np.random.choice([\n 'PiYG', 'PRGn', 'BrBG', 'PuOr', 'RdGy', 'RdBu',\n 'RdYlBu', 'RdYlGn', 'Spectral'... | [
1
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074358637_matplotlib_python.txt |
Q:
Mine Sweeper project
I am relatively new to python, and i have was given a 2d list that contains '-' and '#', where the hashtags are bombs, my output is meant to replace all the '-' with a count that shows all the bombs around the cell
So if someone could please walk me through how to do this step by step, it woul... | Mine Sweeper project | I am relatively new to python, and i have was given a 2d list that contains '-' and '#', where the hashtags are bombs, my output is meant to replace all the '-' with a count that shows all the bombs around the cell
So if someone could please walk me through how to do this step by step, it would really mean a lot, this ... | [
"There are two approaches to dealing with this issue.\nOne is the \"look-before-you-leap\" approach, which in this case would mean making sure that you're trying to access the lists at valid indices - something along the lines of what @mozway suggested.\nThe second is \"ask forgiveness, not permission\" - wrap the ... | [
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074358187_python.txt |
Q:
What is convenient way of parsing rfc3339 in python?
I found several ways of doing it and found a lot of answers/articles and all of them offer different ways:
a) Using dateutil.parser.isoparse. This package is mentioned in datetime documentation as package for parsing ISO 8601 format and I guess, it would have be... | What is convenient way of parsing rfc3339 in python? | I found several ways of doing it and found a lot of answers/articles and all of them offer different ways:
a) Using dateutil.parser.isoparse. This package is mentioned in datetime documentation as package for parsing ISO 8601 format and I guess, it would have been the answer to my question, but I guess there is possibi... | [
"Are you sure datetime.datetime.fromisoformat() wouldn't work for your use case(s)?\n"
] | [
0
] | [] | [] | [
"python",
"rfc3339"
] | stackoverflow_0074206982_python_rfc3339.txt |
Q:
Installing Python plugin with WebStorm
Is there a way to install the Python plugin on WebStorm?
Some StackOverflow posts say to go to project settings (or project structure), then go to "modules", but I think that is just for IntelliJ and not specifically WebStorm, as I can't seem to find it.
I also downloaded h... | Installing Python plugin with WebStorm | Is there a way to install the Python plugin on WebStorm?
Some StackOverflow posts say to go to project settings (or project structure), then go to "modules", but I think that is just for IntelliJ and not specifically WebStorm, as I can't seem to find it.
I also downloaded https://plugins.jetbrains.com/plugin/631-pyth... | [
"That is not possible: this plugin is not compatible with WebStorm (as WebStorm does not have other plugins/functionality that is needed for Python plugin).\nList of supported IDEs is clearly written at the top of that page:\n\n\nIf you need full Python support, have a look at PyCharm -- JetBrains IDE for Python: h... | [
3,
0
] | [] | [] | [
"python",
"python_2.7",
"python_3.x",
"webstorm"
] | stackoverflow_0053804804_python_python_2.7_python_3.x_webstorm.txt |
Q:
filtering products by categories [PROBLEM]
I got a problem with filtering products by categories. My issue is I want to order my products by "category" as I've made in my JSON file. If a customer would click "Amulets" the page shows only products with category "Amulets".
How to do that? I guess I should to use "F... | filtering products by categories [PROBLEM] | I got a problem with filtering products by categories. My issue is I want to order my products by "category" as I've made in my JSON file. If a customer would click "Amulets" the page shows only products with category "Amulets".
How to do that? I guess I should to use "Filter" but I'm a beginner so I don't know how ... | [
"there is 2 ways:\n\nfiltering on FE\nfiltering on BE\n\n\nin case of filtering in FE:\nproducts.filter(x => x.category == selectedCategory)\n\nWhere the selectedCategory is state hold in useState -> which change in the UI interaction, which your user make with page.\nin case of filtering in BE:\n\nBE needs to get ... | [
0
] | [] | [] | [
"django",
"javascript",
"python",
"react_native",
"reactjs"
] | stackoverflow_0074359279_django_javascript_python_react_native_reactjs.txt |
Q:
Multiple separated graphs on Matplotlib
I am facing a simple problem I can't figure out: I am trying to plot multiple graphs with Matplotlib, but in separated graphs. This is an example code with random numbers:
import numpy as np
import matplotlib.pyplot as plt
x1 = np.random.normal(10, 1, 100)
x2 = np.random.u... | Multiple separated graphs on Matplotlib | I am facing a simple problem I can't figure out: I am trying to plot multiple graphs with Matplotlib, but in separated graphs. This is an example code with random numbers:
import numpy as np
import matplotlib.pyplot as plt
x1 = np.random.normal(10, 1, 100)
x2 = np.random.uniform(8, 12, 100)
fig, ax = plt.subplots()
a... | [
"Without using subplots, I think one (quite ugly) way to do this is\nx1 = np.random.normal(10, 1, 100) \nx2 = np.random.uniform(8, 12, 100)\n\ndata = [x1, x2]\nlabel_list = ['Normal', 'Uniform']\nfor i, x in enumerate(data):\n fig = plt.figure()\n plt.plot(np.sort(x), label = label_list[i])\n\n plt.legend(... | [
0
] | [] | [] | [
"graph",
"matplotlib",
"plot",
"python"
] | stackoverflow_0074359134_graph_matplotlib_plot_python.txt |
Q:
Is there a pathlib equivalent to os.path.basename under Windows?
When running Python 3.9.5 on Windows 10:
Path("c:/temp/one/two/").name == "two"
PurePath("c:/temp/one/two/").name == "two"
PureWindowsPath("c:/temp/one/two/").name == "two"
while
os.path.basename("c:/temp/one/two/").name == ""
A:
According to th... | Is there a pathlib equivalent to os.path.basename under Windows? | When running Python 3.9.5 on Windows 10:
Path("c:/temp/one/two/").name == "two"
PurePath("c:/temp/one/two/").name == "two"
PureWindowsPath("c:/temp/one/two/").name == "two"
while
os.path.basename("c:/temp/one/two/").name == ""
| [
"According to the Python documentation os.path.basename simply uses .split(). It therefore is a fairly rudimentary implementation. (The docs even explicitly mention to not expect the same result as for the Unix \"basename\" program.)\nIn pathlib, the Path, PurePath or PureWindowsPath objects are more sophisticate... | [
0
] | [] | [] | [
"pathlib",
"python",
"python_3.x",
"windows"
] | stackoverflow_0072236592_pathlib_python_python_3.x_windows.txt |
Q:
Left-align a pandas rolling object
Using pandas 0.18.1, I'd like to take the rolling average of a one-column dataframe. Since version 0.18.0, this is done with rolling() objects. The default for these rolling objects is to be right-justified. There is a boolean argument you can pass, center=True, to align the roll... | Left-align a pandas rolling object | Using pandas 0.18.1, I'd like to take the rolling average of a one-column dataframe. Since version 0.18.0, this is done with rolling() objects. The default for these rolling objects is to be right-justified. There is a boolean argument you can pass, center=True, to align the rolling object to the center value, but ther... | [
"I think you can use shift:\na = df.rolling(window=3).mean().shift(-2)\nprint (a)\n A\n0 3.666667\n1 5.666667\n2 11.333333\n3 18.333333\n4 NaN\n5 NaN\n\n",
"Another solution is to simply reverse the DataFrame/Series before applying the right-aligned rolling window, and re-reverse it ... | [
35,
4,
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0038055632_pandas_python.txt |
Q:
Succinct / pythonic method of groupby percentage calculation
I want to groupby and calculate the percentage within each respective group over a certain value. I have achieved this by two groupbys into temporary dataframes (group count over a value, and group count), then merging the dataframes before calculating t... | Succinct / pythonic method of groupby percentage calculation | I want to groupby and calculate the percentage within each respective group over a certain value. I have achieved this by two groupbys into temporary dataframes (group count over a value, and group count), then merging the dataframes before calculating the percentage. I assume there is a more succinct method that doesn... | [
"You can use method chaining (pipeline) to avoid using named intermediates:\nout = (df\n .groupby(['n', 'm'], as_index=False)\n # compute count and latecount\n .agg(**{'count': ('v', 'count'),\n 'latecount': ('v', lambda v: len(v[v>1]))\n })\n # filter rows with latecount > 0\n .query('... | [
3,
1
] | [] | [] | [
"dataframe",
"group_by",
"pandas",
"python"
] | stackoverflow_0074359072_dataframe_group_by_pandas_python.txt |
Q:
Python finding local extrema AND assuring alternating minima/maxima
I'm trying to implement some algorithms in Python from different papers and some require a peak/through detection where local minima and maxima are alternating. That should always be the case of course in an analog signal.
However when working wit... | Python finding local extrema AND assuring alternating minima/maxima | I'm trying to implement some algorithms in Python from different papers and some require a peak/through detection where local minima and maxima are alternating. That should always be the case of course in an analog signal.
However when working with discrete Signals this is not always the case as you can see with this s... | [
"I found a solution I previously disregarded unfortunately. The Problem with argrelmax,argrelmin and argrelextrema was that they had difficulties detecting flat peaks/throughs because sometimes they found two maxima using np.greater_equal as comparator (beginning and end of flat peak), which lead to non alternating... | [
0
] | [] | [] | [
"python",
"scipy",
"signal_processing",
"signals"
] | stackoverflow_0074357645_python_scipy_signal_processing_signals.txt |
Q:
Rearrange the values in a file in python
I have a very large file of about 900k values. It is a repetition of values like
/begin throw
COLOR red
DESCRIPTION
"cashmere sofa throw"
10
10
156876
DIMENSION
140
200
STORE_ADDRESS 59110
/end throw
The values keep chan... | Rearrange the values in a file in python | I have a very large file of about 900k values. It is a repetition of values like
/begin throw
COLOR red
DESCRIPTION
"cashmere sofa throw"
10
10
156876
DIMENSION
140
200
STORE_ADDRESS 59110
/end throw
The values keep changing, but I need it like below:
/begin thr... | [
"You can read the file structure by structure so that you don't have to store the whole content in memory and manipulate it there. By structure, I mean all the values between and including /begin throw and /end throw. This should be much faster.\ndef rearrange_structure_and_write_into_file(structure, output_file):\... | [
0,
0
] | [] | [] | [
"file",
"python"
] | stackoverflow_0074358702_file_python.txt |
Q:
How to load CSV files data from S3 to MySQL RDS Using Lambda?
enter image description here
enter image description here
Let's say
Database name = EmployeeDB
In this Database we are having 5 tables which are table1, table2, table3, table4 and table5
and we also having 5 CSV files which are sketching, profile, readi... | How to load CSV files data from S3 to MySQL RDS Using Lambda? | enter image description here
enter image description here
Let's say
Database name = EmployeeDB
In this Database we are having 5 tables which are table1, table2, table3, table4 and table5
and we also having 5 CSV files which are sketching, profile, reading, health, error
Scenario:
Whenever CSV file upload in S3 bucket t... | [
"You can create a dictionary with your files and queries. For every file/table a different insert query is needed.\ntables_dict = {\n 'sketching.csv': 'INSERT INTO table1.sketching (empid, empname, empaddress) VALUES (%s, %s, %s)',\n 'profile.csv': '',\n 'reading.csv': '',\n 'health.csv': '',\n 'error.csv': ''... | [
1,
0
] | [] | [] | [
"amazon_web_services",
"aws_lambda",
"csv",
"mysql",
"python"
] | stackoverflow_0070286801_amazon_web_services_aws_lambda_csv_mysql_python.txt |
Q:
How can I use SVGs with pygame (or perhaps display PNGs at a higher definition)?
I'm trying to make a chess opening trainer with Pygame. Graphically, it's incredibly simple; it works like a slideshow, I am only blitting a single image to the screen at a time which updates when I press the return key. I am using ch... | How can I use SVGs with pygame (or perhaps display PNGs at a higher definition)? | I'm trying to make a chess opening trainer with Pygame. Graphically, it's incredibly simple; it works like a slideshow, I am only blitting a single image to the screen at a time which updates when I press the return key. I am using chess.svg to generate an SVG of the current game state. Not being able to use SVGs nativ... | [
"I found that using smoothscale like so image = pygame.transform.smoothscale(image, (width, height)) helped a little, but it still wasn't perfect. In the end I decided to rewrite it in javascript using cm-chessboard.\n",
"chess.svg.board has a size keyword argument:\n\nsize – The size of the image in pixels (e.g.... | [
1,
1,
0
] | [] | [] | [
"chess",
"pygame",
"python",
"python_chess",
"svg"
] | stackoverflow_0067078966_chess_pygame_python_python_chess_svg.txt |
Q:
Convert python file into exe using auto-py-to-exe
I have just finished a project where I have made a connect 4 game and am trying to convert it to an exe file using auto-py-to-exe.
I want to use the one-file option, however every time it finishes and I run it, it would come up with an error:
Failed to execute scr... | Convert python file into exe using auto-py-to-exe | I have just finished a project where I have made a connect 4 game and am trying to convert it to an exe file using auto-py-to-exe.
I want to use the one-file option, however every time it finishes and I run it, it would come up with an error:
Failed to execute script 'main' due to unhandled exception: No file 'Assets/... | [
"I was also facing this problem then I got the solutions from analysing other threads.\nYou have to update your script by adding this function\nimport sys\nimport os\n\ndef resource_path(relative_path):\n \"\"\" Get absolute path to resource, works for dev and for PyInstaller \"\"\"\n base_path=getattr(sys,'... | [
0
] | [] | [] | [
"auto_py_to_exe",
"python",
"python_3.x"
] | stackoverflow_0071846222_auto_py_to_exe_python_python_3.x.txt |
Q:
Why is my multiclass keras model not training at a high accuracy despite parameters?
Firstly I read in my cvs file which contained a 1 or 0 matrix
df = pd.read_csv(url)
print(df.head())
print(df.columns)
Next I gathered the Pictures and resized them
image_directory = 'Directory/'
dir_list = os.listdir(path)
p... | Why is my multiclass keras model not training at a high accuracy despite parameters? | Firstly I read in my cvs file which contained a 1 or 0 matrix
df = pd.read_csv(url)
print(df.head())
print(df.columns)
Next I gathered the Pictures and resized them
image_directory = 'Directory/'
dir_list = os.listdir(path)
print("Files and directories in '", image_directory, "' :")
# print the list
print(dir_li... | [
"Here are some notes that might help:\n\nWhen using Batch Normalization, avoid too small batch sizes. For more details see the Group Normalization paper by Yuxin Wu and Kaiming He.\n\nIt may worth looking at metrics like AUC, and F1 as well since you have an imbalanced multiclass case. You can add tf.keras.metrics.... | [
0
] | [] | [] | [
"computer_vision",
"keras",
"model_optimizer",
"python"
] | stackoverflow_0074320159_computer_vision_keras_model_optimizer_python.txt |
Q:
Upsampling the Spatial Dimensions Of a 4D Tensor using transposed convolution
I have a tensor with the size of (16, 64, 4,4) and I want to upsample the spatial size of this tensor using transposed convolution. How can I select the kernel size, stride, padding to have a tensor with size of (16, 64, 4,6)?
For exampl... | Upsampling the Spatial Dimensions Of a 4D Tensor using transposed convolution | I have a tensor with the size of (16, 64, 4,4) and I want to upsample the spatial size of this tensor using transposed convolution. How can I select the kernel size, stride, padding to have a tensor with size of (16, 64, 4,6)?
For example this is my code for upsampling from (16, 64, 1,1) to (16, 64, 4,4):
nn.convTransp... | [
"The equation for computing the output size is in the pytorch documentation of ConvTranspose2d. Put in your input size, set your desired output size and solve the equation for kernel size, stride, padding, etc. There may be multiple valid solutions.\nFor your specific problem, the following works:\nfrom torch impor... | [
3
] | [] | [] | [
"conv_neural_network",
"python",
"pytorch"
] | stackoverflow_0074358922_conv_neural_network_python_pytorch.txt |
Q:
python pandas: add several columns to a DF based on applying func to index
I would like to add columns to a dataframe based on the index, which is of a string type.
Provided I have a df as follows:
# Creating the DataFrame
df = pd.DataFrame({'Date':['10/2/2011', '11/2/2011', '12/2/2011', '13/2/2011'],
... | python pandas: add several columns to a DF based on applying func to index | I would like to add columns to a dataframe based on the index, which is of a string type.
Provided I have a df as follows:
# Creating the DataFrame
df = pd.DataFrame({'Date':['10/2/2011', '11/2/2011', '12/2/2011', '13/2/2011'],
'Event':['Music', 'Poetry', 'Theatre', 'Comedy'],
'C... | [
"You can use map directly on the index after instantiating your class:\nclass telbook():\n def __init__(self):\n self.data = {'john':'python','mike':'C','alfred':'excel','jerry':'python'}\n self.country = {'john':'spain','mike':'India','alfred':'germany','jerry':'themoon'}\n\n\ntb = telbook()\n\ndf... | [
0
] | [] | [] | [
"apply",
"indexing",
"pandas",
"python"
] | stackoverflow_0074359473_apply_indexing_pandas_python.txt |
Q:
How to loop through a jsonfield serializer
I've been trying to loop through the incoming data from a json serializer for a couple of weeks now. Tried a few different approaches, but i can't seem to loop through the json and return a list with all facility_id's for example. Ultimately i want to create one leadfacil... | How to loop through a jsonfield serializer | I've been trying to loop through the incoming data from a json serializer for a couple of weeks now. Tried a few different approaches, but i can't seem to loop through the json and return a list with all facility_id's for example. Ultimately i want to create one leadfacility object for each json item using it's facilit... | [
"I'd suggest a different, arguably better approach. Instead of JSONField use a nested model serializer.\nclass AssignedFacilitySerializer(serializers.ModelSerializer):\n fields = ('assigned_facilities_id', 'datetime')\n model = Facility\n\nclass LeadUpdateSerializer(serializers.ModelSerializer):\n assigned... | [
1,
0,
0,
0,
0
] | [] | [] | [
"django",
"django_rest_framework",
"python"
] | stackoverflow_0074303934_django_django_rest_framework_python.txt |
Q:
Getting dishes ordered by a user in python
I actually want the dishes a particular user ordered from the given dataset. For example, if I give user_id = U1077, I want to get the dishes he ordered in return. I am using python code. Can anyone help me with this.
user_id
dish
U1077
Prawns Biryani
U1077
Chilli Pota... | Getting dishes ordered by a user in python | I actually want the dishes a particular user ordered from the given dataset. For example, if I give user_id = U1077, I want to get the dishes he ordered in return. I am using python code. Can anyone help me with this.
user_id
dish
U1077
Prawns Biryani
U1077
Chilli Potatoes
U1077
Paneer Multani Tikka
U1068... | [
"Your data that you provided has been saved to a csv file. Added one more line for clarity: U1077 Prawns Biryani.\nWith the help of Pandas I read them, this is how they look:\n user_id dish\n0 U1077 Prawns Biryani\n1 U1077 Chilli Potatoes\n2 U1077 Paneer Multani Tikka\n3 U107... | [
0
] | [] | [] | [
"data_analysis",
"exploratory_data_analysis",
"python"
] | stackoverflow_0074342111_data_analysis_exploratory_data_analysis_python.txt |
Q:
Calling Scrapy from another file without threading
I have to call the crawler from another python file, for which I use the following code.
def crawl_koovs():
spider = SomeSpider()
settings = get_project_settings()
crawler = Crawler(settings)
crawler.signals.connect(reactor.stop, signal=signals.spi... | Calling Scrapy from another file without threading | I have to call the crawler from another python file, for which I use the following code.
def crawl_koovs():
spider = SomeSpider()
settings = get_project_settings()
crawler = Crawler(settings)
crawler.signals.connect(reactor.stop, signal=signals.spider_closed)
crawler.configure()
crawler.crawl(sp... | [
"The first thing I would say to you is when you're executing Scrapy from external file the loglevel is set to INFO,you should change it to DEBUG to see what's happening if your code doesn't work\nyou should change the line:\n log.start()\n\nfor:\nlog.start(loglevel=log.DEBUG)\n\nTo store everything in the log and g... | [
6,
0
] | [] | [] | [
"multithreading",
"python",
"scrapy",
"scrapy_spider",
"twisted.internet"
] | stackoverflow_0030210493_multithreading_python_scrapy_scrapy_spider_twisted.internet.txt |
Q:
How do I get the list from my result in python 3.8?
I have written the following code in python 3.8;
import galois
GF = galois.GF(2)
f = galois.Poly([1,0,0,1], field=GF)
g = galois.Poly([1,1,0], field=GF)
c=f * g
d=c.coeffs
The output I am getting is
d=GF([1, 1, 0, 1, 1, 0], order=2)
Now,... | How do I get the list from my result in python 3.8? | I have written the following code in python 3.8;
import galois
GF = galois.GF(2)
f = galois.Poly([1,0,0,1], field=GF)
g = galois.Poly([1,1,0], field=GF)
c=f * g
d=c.coeffs
The output I am getting is
d=GF([1, 1, 0, 1, 1, 0], order=2)
Now, I only want the list as my answer, i.e,
d=[1,1,0,1,1,0]
... | [
"This output is a numpy array so simply convert it into a list\nd.tolist()\n\nOutput\n[1, 1, 0, 1, 1, 0]\n\n"
] | [
1
] | [] | [] | [
"python",
"python_2.7",
"python_3.x"
] | stackoverflow_0074359545_python_python_2.7_python_3.x.txt |
Q:
Get gender from first name using API Python
I am looking for gender detection based on first name from pandas column.
For example i have array
array(['Walker', 'Daniel', 'Steph', ..., 'Dr. Sylvia', 'Gwendy'],
dtype=object)
I want to create new column in dataframe with gender
name
gender
Walker
M
Daniel
M
Dr. S... | Get gender from first name using API Python | I am looking for gender detection based on first name from pandas column.
For example i have array
array(['Walker', 'Daniel', 'Steph', ..., 'Dr. Sylvia', 'Gwendy'],
dtype=object)
I want to create new column in dataframe with gender
name
gender
Walker
M
Daniel
M
Dr. Sylvia
W
Gwendy
W
I used Python API ... | [
"You might want something like this (with caching for duplicate names, a shared HTTP session, and proper error handling too):\nfrom functools import cache\nimport pandas as pd\nimport requests\n\n# Use a single session for performance\nsess = requests.Session()\n\n\n@cache\ndef get_gender(name: str) -> str:\n re... | [
1
] | [] | [] | [
"api",
"pandas",
"python",
"python_requests"
] | stackoverflow_0074359458_api_pandas_python_python_requests.txt |
Q:
Merge Dataframes based on a column of unsorted/unsortable lists
I want to merge two dataframes based on values from the first dataframe. But the identifier column is filled with lists and to make it worse, the order of the elements within the lists is unsortable and might be different from the order of the element... | Merge Dataframes based on a column of unsorted/unsortable lists | I want to merge two dataframes based on values from the first dataframe. But the identifier column is filled with lists and to make it worse, the order of the elements within the lists is unsortable and might be different from the order of the elements within the lists from the second dataframe, even though the element... | [
"You can consider joining them by previously sorting them:\ndf1['Info'] = df1['Info'].map(lambda x: str(sorted(x)) if type(x) == list else x)\ndf2['Info'] = df2['Info'].map(lambda x: str(sorted(x)) if type(x) == list else x)\n\nAfterwards you can safely join them by using:\noutput = df1.merge(df2,how='left',on='Inf... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074359584_python.txt |
Q:
Python JSON append
I'm trying to find out how to format my json file for my puprose.
My json file looks like this (pulled from sql db):
[
{
"type": "xy",
"view_code": "english",
"short": "xy",
"product": "simple",
"amount": "4"
},
]
what I am trying to achive is som... | Python JSON append | I'm trying to find out how to format my json file for my puprose.
My json file looks like this (pulled from sql db):
[
{
"type": "xy",
"view_code": "english",
"short": "xy",
"product": "simple",
"amount": "4"
},
]
what I am trying to achive is something like this:
[
{
... | [
"ao = array of object\nao = [ { \"type\": \"xy\", \"view_code\": \"english\", \"short\": \"xy\", \"product\": \"simple\", \"amount\": \"4\" }]\n\nprint(ao)\narr = []\n\nfor el in ao:\n vals = {}\n vals[el['product']]=el\n arr.append(vals)\n \nprint(arr)\n\nwhere:\nvals[el['product']]=el\n\nis the value,... | [
-1
] | [
"Do you have a JSON file or a list of dictionaries? If you have a JSON file, you'll first want to load the JSON into Python datastructures like so:\nimport json\n\ndata = json.loads(my_string)\n\nYou can then do this:\nnew_data = [{\"products\": item} for item in data]\n\nIf you need to convert it back to JSON you ... | [
-1
] | [
"json",
"python"
] | stackoverflow_0074359557_json_python.txt |
Q:
While loop keeps going back to end condition
I'm just going over some python basics, and wrote some code that I thought would print every even element inside of a list:
def print_evens(numbers):
"""Prints all even numbers in the list
"""
length = len(numbers)
i = 0
while i < length:
if ... | While loop keeps going back to end condition | I'm just going over some python basics, and wrote some code that I thought would print every even element inside of a list:
def print_evens(numbers):
"""Prints all even numbers in the list
"""
length = len(numbers)
i = 0
while i < length:
if numbers[i] % 2 == 0:
print (numbers[i]... | [
"The problem is that when you start with 1 the variable i never get updated, because it's not even. So the solution is to increment the i every time without a condition:\nwhile i < length:\n if numbers[i] % 2 == 0:\n print (numbers[i])\n i += 1\n\n",
"If you don't want to bother with inde... | [
3,
1
] | [] | [] | [
"loops",
"python"
] | stackoverflow_0074359455_loops_python.txt |
Q:
All possible binary label generation (not binary byte generation) and/or save numbers using commas
I want to generate a binary label systematically and I hope I can generate a three or four labels later, if my first analysis worked well.
Here is the code to make the binary label combinations:
lst = sorted([i for i... | All possible binary label generation (not binary byte generation) and/or save numbers using commas | I want to generate a binary label systematically and I hope I can generate a three or four labels later, if my first analysis worked well.
Here is the code to make the binary label combinations:
lst = sorted([i for i in itertools.product([1, 0], repeat=len(my_data))], key=sum)
The above code worked well if the samples ... | [
"Regarding itatools.product, I figured out and solved by myself referring by those website.\n\nWhy do I get a MemoryError with itertools.product?\nhttps://note.nkmk.me/en/python-itertools-product/\nCreate dataframe from itertools product\nWriting to csv file with itertools.product\n\nIn my case, I simply removed th... | [
0
] | [] | [] | [
"format",
"python",
"python_itertools"
] | stackoverflow_0074341338_format_python_python_itertools.txt |
Q:
How do I read a different size of an icon file?
I have a folder of icon files (ico) that I want to convert to PNG. Each icon has two sizes, each size is a different image. To be clear, the two sizes look different and are not just the same icon at different resolutions. I want to save the smaller version of each i... | How do I read a different size of an icon file? | I have a folder of icon files (ico) that I want to convert to PNG. Each icon has two sizes, each size is a different image. To be clear, the two sizes look different and are not just the same icon at different resolutions. I want to save the smaller version of each icon.
The PIL documentation states:
ICO is used to st... | [
"I had a try at this and wrote some code to:\n\nopen an ICO file\nparse out the contained icons\ncreate an in-memory ICO file for each one individually\nopen that with PIL and append the resulting PIL Image to a list\n\nCode is as follows - there's a link describing the ICO format on Wikipedia here:\n#!/usr/bin/env... | [
0
] | [] | [] | [
"ico",
"icons",
"python",
"python_imaging_library"
] | stackoverflow_0074341558_ico_icons_python_python_imaging_library.txt |
Q:
Area under the histogram is not 1 when using density in plt.hist
Consider the following dataset with random data:
test_dataset = np.array([ -2.09601881, -4.26602684, 1.09105452, -4.59559669,
1.05865251, -0.93076762, -14.70398945, -18.01937129,
4.64126152, -10.34178822, -9.46058493, -5.6686... | Area under the histogram is not 1 when using density in plt.hist | Consider the following dataset with random data:
test_dataset = np.array([ -2.09601881, -4.26602684, 1.09105452, -4.59559669,
1.05865251, -0.93076762, -14.70398945, -18.01937129,
4.64126152, -10.34178822, -9.46058493, -5.66864965,
-3.17562022, 15.7030379 , 10.59675205, -5.80882413,
... | [
"you do not calculate the area, area you should calculate as follow (in your example):\nsum(data1 * np.diff(bins)) == 1\n\n"
] | [
2
] | [] | [] | [
"distribution",
"histogram",
"matplotlib",
"probability_density",
"python"
] | stackoverflow_0074359594_distribution_histogram_matplotlib_probability_density_python.txt |
Q:
Linked list problem (Leetcode) - understanding inputs
I am starting to complete some Leetcode problems, having finished an online Data Structures and Algorithms course, but I'm struggling to understand what some of the input variables represent. I've included one of the solutions as an example. The problem gives m... | Linked list problem (Leetcode) - understanding inputs | I am starting to complete some Leetcode problems, having finished an online Data Structures and Algorithms course, but I'm struggling to understand what some of the input variables represent. I've included one of the solutions as an example. The problem gives me the head of a sorted linked list as input and asks me to ... | [
"You can try this:\nclass Solution:\n def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:\n temp = head\n seen = set() # this will keep track if element is duplicate or not\n prev = head # this will keep track of previous node\n while temp:\n if tem... | [
1
] | [] | [] | [
"algorithm",
"data_structures",
"linked_list",
"list",
"python"
] | stackoverflow_0074359459_algorithm_data_structures_linked_list_list_python.txt |
Q:
Discord webhook sends along with previous messages problem in python
from discord_webhook import DiscordWebhook, DiscordEmbed
import csv
import os
webhook = DiscordWebhook(url='https://discordapp.c.........')
file_name = 'symbols.csv'
all_data = []
def load_csv():
with open(file_name, 'r') as dict:
r... | Discord webhook sends along with previous messages problem in python | from discord_webhook import DiscordWebhook, DiscordEmbed
import csv
import os
webhook = DiscordWebhook(url='https://discordapp.c.........')
file_name = 'symbols.csv'
all_data = []
def load_csv():
with open(file_name, 'r') as dict:
rows = csv.DictReader(dict)
for row in rows:
all_data.... | [
"webhook.add_embed(embed) adds new embed to the webhook, and you are not removing it before next iteration\nyou should place this line inside your while loop\nwebhook = DiscordWebhook(url='https://discordapp.c.........')\n\nor somehow remove embed from your webhook variable after sending it\n"
] | [
0
] | [] | [] | [
"discord.py",
"python",
"webhooks"
] | stackoverflow_0074358439_discord.py_python_webhooks.txt |
Q:
Python - download entire directory from Google Cloud Storage with progress bar
I am downloading a entire directory from Google Cloud Storage using below python code
from google.cloud import storage
from pathlib import Path
def download_blob():
"""Downloads a blob from the bucket."""
# The ID of your GCS bucket
bu... | Python - download entire directory from Google Cloud Storage with progress bar | I am downloading a entire directory from Google Cloud Storage using below python code
from google.cloud import storage
from pathlib import Path
def download_blob():
"""Downloads a blob from the bucket."""
# The ID of your GCS bucket
bucket_name = "Bucket name"
# The ID of your GCS object
blob_name = input("Enter the ... | [
"I will assume that you have a Python library that is capable of showing a progress bar on the console/terminal where you plan to run this program.\nWhat you can do at a coarse level is the following:\n\nYou have a list of blobs that are present in the specific Google Cloud Bucket + prefix.\nFor each of the blob, y... | [
1
] | [] | [] | [
"cmd",
"google_cloud_platform",
"progress_bar",
"python"
] | stackoverflow_0074358644_cmd_google_cloud_platform_progress_bar_python.txt |
Q:
Save img to text result and check if duplicate one by one
I'm doing python OCR image to text, and compare if there is duplicate, I'm checking one by one so that I can locate easier
ex: listA = [1, 2 ,3 , 4, 4, 5, 6]
so when I append list A, can show 4 is duplicate
Mian issue: my list "listOfElems" is empty and w... | Save img to text result and check if duplicate one by one | I'm doing python OCR image to text, and compare if there is duplicate, I'm checking one by one so that I can locate easier
ex: listA = [1, 2 ,3 , 4, 4, 5, 6]
so when I append list A, can show 4 is duplicate
Mian issue: my list "listOfElems" is empty and want to save text and detect is duplicate in list one by one
fro... | [
"You are creating an empty list, never add anything to it and then iterate over it (nothing)\ni = 1\nlistOfElems = [] # <- empty\nNumber_of_onlyfiles = len(onlyfiles)\nwhile i < Number_of_onlyfiles :\n each_file_path = '/home/DC_ton/desktop/test_11_8/output02/'+ onlyfiles[i]\n image = Image.open(each_file_pat... | [
0
] | [] | [] | [
"list",
"python",
"python_3.x"
] | stackoverflow_0074359217_list_python_python_3.x.txt |
Q:
How to change list of dictionaries into list of lists where every list is a key,value pair?
I have a list of dictionaries (with multiple key, value pairs) in python, and I'm trying to make each dictionary into a list, where each key,value pair is also it's own list. For example:
list = [{a: 1, b: 2, c: 3}, {d: 4, ... | How to change list of dictionaries into list of lists where every list is a key,value pair? | I have a list of dictionaries (with multiple key, value pairs) in python, and I'm trying to make each dictionary into a list, where each key,value pair is also it's own list. For example:
list = [{a: 1, b: 2, c: 3}, {d: 4, e: 5, f: 6}, {g: 7,h: 8,i: 9}]
What i want it to output is:
newlist = [[[a, 1], [b, 2], [c, 3]], ... | [
"my_list = [{'a': 1, 'b': 2, 'c': 3}, {'d': 4, 'e': 5, 'f': 6}, {'g': 7,'h': 8,'i': 9}]\nr = []\nfor _ in my_list:\n r.append([[k,v] for k,v in _.items()])\n\nprint(r)\n\n[[['a', 1], ['b', 2], ['c', 3]], [['d', 4], ['e', 5], ['f', 6]], [['g', 7], ['h', 8], ['i', 9]]]\n",
"Please do not use list as an identifier... | [
0,
0
] | [] | [] | [
"dictionary",
"list",
"nested",
"nested_lists",
"python"
] | stackoverflow_0074359760_dictionary_list_nested_nested_lists_python.txt |
Q:
Strange behavior with bar plots
I'm getting strange results when attempting a bar plot:
labels = [f'{i+1}/{3}' for i in range(3)]
main_team_values = ['0:05:01', '0:06:54', '0:05:41']
other_team_values = ['0:07:56', '0:07:06', '0:07:04']
X = np.arange(3)
fig, ax = plt.subplots()
ax.bar(X, main_team_values, color =... | Strange behavior with bar plots | I'm getting strange results when attempting a bar plot:
labels = [f'{i+1}/{3}' for i in range(3)]
main_team_values = ['0:05:01', '0:06:54', '0:05:41']
other_team_values = ['0:07:56', '0:07:06', '0:07:04']
X = np.arange(3)
fig, ax = plt.subplots()
ax.bar(X, main_team_values, color = 'k', width = 0.35)
ax.bar(X + width,... | [
"the list you are plotting is string, either convert to timestamps or duration in second and plot\nmain_team_values = [sum(map(lambda x: int(x[0]) * x[1], zip(d.split(':'), [3600, 60, 1]))) for d in main_team_values]\nother_team_values = [sum(map(lambda x: int(x[0]) * x[1], zip(d.split(':'), [3600, 60, 1]))) for ... | [
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074359743_matplotlib_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.