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:
Python/Plotly: px bar costumize hover
Having this dataframe:
df_grafico2 = pd.DataFrame(data = {
"Usos" : ['Total','BK','BI','CyL','PyA','BC','VA','Resto','Total','BK','BI','CyL','PyA','BC','VA','Resto'],
"Periodo" : ['Octubre 2021*','Octubre 2021*','Octubre 2021*','Octubre 2021*','Octubre 2021*','Octubre ... | Python/Plotly: px bar costumize hover | Having this dataframe:
df_grafico2 = pd.DataFrame(data = {
"Usos" : ['Total','BK','BI','CyL','PyA','BC','VA','Resto','Total','BK','BI','CyL','PyA','BC','VA','Resto'],
"Periodo" : ['Octubre 2021*','Octubre 2021*','Octubre 2021*','Octubre 2021*','Octubre 2021*','Octubre 2021*','Octubre 2021*','Octubre 2021*','Oct... | [
"The easiest way to do hover text is to use fig.data (in your case, plot_impo_usos.data). to get the graph configuration data, so it is easy to customize it. So copy the hover template that is set up for the two listograms and edit it. Being able to customize it with the configuration information gives you more fre... | [
1,
0
] | [] | [] | [
"plotly",
"plotly_express",
"python"
] | stackoverflow_0074658732_plotly_plotly_express_python.txt |
Q:
Python Pandas Converting Dataframe to Tidy Format
dt = {'ID': [1, 1, 1, 1, 2, 2, 2, 2],
'Test': [‘Math’, 'Math', 'Writing', 'Writing', ‘Math’, 'Math', 'Writing', 'Writing', ‘Math’]
'Year': ['2008', '2009', '2008', '2009', '2008', ‘2009’, ‘2008’, ‘2009’],
'Fall': [15, 12, 22, ... | Python Pandas Converting Dataframe to Tidy Format | dt = {'ID': [1, 1, 1, 1, 2, 2, 2, 2],
'Test': [‘Math’, 'Math', 'Writing', 'Writing', ‘Math’, 'Math', 'Writing', 'Writing', ‘Math’]
'Year': ['2008', '2009', '2008', '2009', '2008', ‘2009’, ‘2008’, ‘2009’],
'Fall': [15, 12, 22, 10, 12, 16, 13, 23]
‘Spring’: [16, 13, 22, ... | [
"You can try with set_index with stack + unstack\nout = (df.set_index(['ID','Test','Year']).\n stack().unstack(level=1).\n add_suffix('_Score').reset_index())\nout\nOut[271]: \nTest ID Year level_2 Math_Score Writing_Score\n0 1 2008 Fall 15 22\n1 1 2008 ... | [
0,
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0072933196_pandas_python.txt |
Q:
`pip install` Gives Error on Some Packages
Some packages give errors when I try to install them using pip install. This is the error when I try to install chatterbot, but some other packages give this error as well:
pip install chatterbot
Collecting chatterbot
Using cached ChatterBot-1.0.5-py2.py3-none-any.whl (... | `pip install` Gives Error on Some Packages | Some packages give errors when I try to install them using pip install. This is the error when I try to install chatterbot, but some other packages give this error as well:
pip install chatterbot
Collecting chatterbot
Using cached ChatterBot-1.0.5-py2.py3-none-any.whl (67 kB)
Collecting pint>=0.8.1
Downloading Pint... | [
"The real error in your case is:\nImportError: cannot import name 'msvccompiler' from 'distutils'\n\nIt occured because setuptools has broken distutils in version 65.0.0 (and has already fixed it in version 65.0.2). According to your log, the error occured in your global setuptools installation (see the path in err... | [
1,
0
] | [] | [] | [
"dependencies",
"pip",
"python",
"setup.py",
"setuptools"
] | stackoverflow_0073378545_dependencies_pip_python_setup.py_setuptools.txt |
Q:
Finding element by the second class in Selenium
Using inspect element, I have one element with two states:
<span class="c-form-control-feedback c-form-control-feedback-error" title="" data-original-title="that username is already taken"></span>
<span class="c-form-control-feedback c-form-control-feedback-error" ti... | Finding element by the second class in Selenium | Using inspect element, I have one element with two states:
<span class="c-form-control-feedback c-form-control-feedback-error" title="" data-original-title="that username is already taken"></span>
<span class="c-form-control-feedback c-form-control-feedback-error" title=""></span>
Sometimes the element has the first fo... | [
"You can retrieve them by checking whether contains the data-original-title attribute.\nSelenium:\ndriver.find_elements(by=By.XPATH, value=\"//*[contains(@data-original-title, '')]\")\n\nBeautifulsoup:\nsoup.find_all(\"span\", attrs={\"data-original-title\": True})\n\n\nOutput:\n[<span class=\"c-form-control-feedba... | [
1
] | [] | [] | [
"python",
"selenium"
] | stackoverflow_0074667563_python_selenium.txt |
Q:
My dataframe is not changed when I run for loop(comparing two dataframes)
I have two dataset, one with over 100,000 rows and 300 columns and the other with 200 rows and 6 columns.
I'm comparing these two datasets and updating df1 from df2 using for loop.
Here is the sample dataset
df1:
KEY MAIN_METHO... | My dataframe is not changed when I run for loop(comparing two dataframes) | I have two dataset, one with over 100,000 rows and 300 columns and the other with 200 rows and 6 columns.
I'm comparing these two datasets and updating df1 from df2 using for loop.
Here is the sample dataset
df1:
KEY MAIN_METHOD DRUG_ETCDTL
0 100944 1 unknown
1 67488 ... | [
"This solution avoids for loops and instead uses a temporary data frame to perform the task. The strings in the Unnamed: 4 column are split using the str.split() function provided by Pandas. The MAIN_METHOD information is transformed using a mapping. The df1 data frame is conditionally updated using numpy.where() b... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074666370_dataframe_pandas_python.txt |
Q:
Free alternative to HEROKU?
I have a simple script that is a code that fetches the tweets of a specific account on Twitter and publishes them on Facebook using Python , facebook-sdk and BeautifulSoup library. I used to host script on HEROKU, but now everything in HEROKU needs money. I want a host that I can hostin... | Free alternative to HEROKU? | I have a simple script that is a code that fetches the tweets of a specific account on Twitter and publishes them on Facebook using Python , facebook-sdk and BeautifulSoup library. I used to host script on HEROKU, but now everything in HEROKU needs money. I want a host that I can hosting for my script, thank you
I trie... | [
"Have you ever considered using \"GitHub-Actions\", or \"Google Firebase-Cloud Functions\" ? Those sound like good candidates for your demand.\n"
] | [
0
] | [] | [] | [
"heroku",
"python",
"pythonanywhere"
] | stackoverflow_0074667292_heroku_python_pythonanywhere.txt |
Q:
How to save file with a number such as 2 so it isnt the same as first file saved
import qrcode
import time
import tkinter as tk
import os
import shutil
from sys import exit
# GUI with tkinter
root = tk.Tk()
root.title('Window')
root.geometry("400x400+50+50")
root.iconbitmap('QRCODE-GENERATOR.ico')
root.configure... | How to save file with a number such as 2 so it isnt the same as first file saved | import qrcode
import time
import tkinter as tk
import os
import shutil
from sys import exit
# GUI with tkinter
root = tk.Tk()
root.title('Window')
root.geometry("400x400+50+50")
root.iconbitmap('QRCODE-GENERATOR.ico')
root.configure(bg="grey")
lbl_1 = tk.Label(root, text="Qrcode generator", font="1")
entry_1 = tk.En... | [
"Based on what i understand you want to add something at the end of the name file to prevent throwing an error.\nimport time\nFILE_NAME = f\"output-{time.time()}.png\"\nimg.save(FILE_NAME)\n\n",
"Try this:\n\nPut all your code into a while true loop.\n\nDeclare a variable \"num\" and assign it to the integer 0. M... | [
0,
0
] | [] | [] | [
"file",
"python",
"python_3.x",
"tkinter"
] | stackoverflow_0074667518_file_python_python_3.x_tkinter.txt |
Q:
How to set a column for checkbox value in MySQL in Python?
I'm a beginner of python and mysql.
Now I want build a small project, user will enter name and email on the website. And there will be a checkbox to check if the users read policy. So if the box is checked, the database will save "true", if not then save "... | How to set a column for checkbox value in MySQL in Python? | I'm a beginner of python and mysql.
Now I want build a small project, user will enter name and email on the website. And there will be a checkbox to check if the users read policy. So if the box is checked, the database will save "true", if not then save "false". Could someone help me the code? Thanks.
users = Table('a... | [
"The following code can be used to set a column for checkbox value in MySQL in Python:\nfrom mysql.connector import connect\n\ndb_connection = connect(\n host='localhost',\n user='username',\n password='password',\n database='my_database'\n)\n\n# Create a cursor object\ncursor = db_connection.cursor()\n... | [
0
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0074665816_mysql_python.txt |
Q:
TCLab issues with python 3.10 (and python 3.9)
OS:
macOS 11.7.1 (Big Sur)
A few months ago I purchased a TCLab kit and at the time did some very rudimentary tests where the device worked as expected.
Recently I decided that I wanted to work on some of the APMonitor lessons and connected the TCLab to my computer ex... | TCLab issues with python 3.10 (and python 3.9) | OS:
macOS 11.7.1 (Big Sur)
A few months ago I purchased a TCLab kit and at the time did some very rudimentary tests where the device worked as expected.
Recently I decided that I wanted to work on some of the APMonitor lessons and connected the TCLab to my computer expecting that it would work as it had done in the pas... | [
"Serial Connection Issue\nThis error AttributeError: module 'serial' has no attribute 'Serial' suggests that the package serial or a local file name serial.py has a conflict with pyserial. Rename your file to something else besides serial.py and/or uninstall the serial package (not needed for TCLab). Your pyserial ... | [
1
] | [] | [] | [
"iterable",
"python"
] | stackoverflow_0074663465_iterable_python.txt |
Q:
Why doesn't type() work in if statements in Python?
user_input = int(input('Enter input: '))
if type(user_input) == "<class 'int'>":
print('This is a integer.')
The code above outputs nothing to the console. I am just confused because it is very simple and looks like it should work.
I've tried removing the i... | Why doesn't type() work in if statements in Python? | user_input = int(input('Enter input: '))
if type(user_input) == "<class 'int'>":
print('This is a integer.')
The code above outputs nothing to the console. I am just confused because it is very simple and looks like it should work.
I've tried removing the int() in the input line which output nothing, I understand... | [
"Fix\nThat is because type(user_input) returns a type, not a string, don't confuse yourself with what you see printed and the real thing. When you print something you only see a representation of the thing. Only if it's a string you can copy and compare it directly\nprint(type(type(user_input))) # <class 'type'>\n... | [
0,
0,
0
] | [] | [] | [
"conditional_statements",
"if_statement",
"input",
"python",
"types"
] | stackoverflow_0074667623_conditional_statements_if_statement_input_python_types.txt |
Q:
why 'set' function doesn't work in Jupyter
when I write in cell
set('hello')
it raises error 'tuple' object is not callable
| why 'set' function doesn't work in Jupyter | when I write in cell
set('hello')
it raises error 'tuple' object is not callable
| [] | [] | [
"To set an env variable in a jupyter notebook, just use a % magic commands, either %env or %set_env , e.g., %env VAR = VALUE or %env VAR VALUE .\n"
] | [
-1
] | [
"jupyter_notebook",
"python",
"set"
] | stackoverflow_0074667529_jupyter_notebook_python_set.txt |
Q:
Input 0 of layer "conv2d_5" is incompatible with the layer: expected min_ndim=4, found ndim=2. Full shape received: (None, 2)
I am trying to use CNN on multivariate time series instead the most common usage on images. The number of features is between 90 and 120, depending on which I need to consider and experimen... | Input 0 of layer "conv2d_5" is incompatible with the layer: expected min_ndim=4, found ndim=2. Full shape received: (None, 2) | I am trying to use CNN on multivariate time series instead the most common usage on images. The number of features is between 90 and 120, depending on which I need to consider and experiment with. This is my code
scaler = StandardScaler()
X_train_s = scaler.fit_transform(X_train)
X_test_s = scaler.transform(X_test)
X_... | [
"Data loading\nI have made a simple class that demonstrates a reasonable approach to doing so. Mind you, I am not that familiar with TensorFlow, mainly using PyTorch, so the code might not be optimized.\nYou are probably best at defining a custom generator if one can't be used for this. After reading the comments, ... | [
0
] | [] | [] | [
"conv_neural_network",
"python"
] | stackoverflow_0074590804_conv_neural_network_python.txt |
Q:
SqlAlchemy AsyncSession transaction
When using async session as context manager, what happens is if an exception raises, I get a warning that I wanna get rid of.
here's how I use the session:
async with session.begin():
retailer: model.Retailer = (await session.scalars(select(model.Retailer).filter(model.Retai... | SqlAlchemy AsyncSession transaction | When using async session as context manager, what happens is if an exception raises, I get a warning that I wanna get rid of.
here's how I use the session:
async with session.begin():
retailer: model.Retailer = (await session.scalars(select(model.Retailer).filter(model.Retailer.name=="default"))).first()
await ... | [
"The warning message you are seeing, RuntimeWarning: coroutine 'Transaction.rollback' was never awaited, is indicating that you are using an async context manager (async with session.begin()) but you are not awaiting the rollback of the transaction if an exception is raised.\nIn your code, you are using an async co... | [
0
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0074667608_python_sqlalchemy.txt |
Q:
Remove empty strings from a list of strings on each row in a pandas dataframe
I have a pandas dataframe and one of the columns contains a list of strings e.g:
['', 'Hello', 'The house is warm', '', 'What time is it']
The strings are different for each row of the dataframe but all lists on each row contain empty st... | Remove empty strings from a list of strings on each row in a pandas dataframe | I have a pandas dataframe and one of the columns contains a list of strings e.g:
['', 'Hello', 'The house is warm', '', 'What time is it']
The strings are different for each row of the dataframe but all lists on each row contain empty strings. How can I remove these?
The column is called 'Description'.
I have tried the... | [
"create new list and append only string that is not empty\nuse eval() if they are string representation of list\ndf['Description'] = df['Description'].apply(lambda x: [item for item in eval(x) if item != ''])\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"list",
"pandas",
"python",
"string"
] | stackoverflow_0074667700_dataframe_list_pandas_python_string.txt |
Q:
Dynamically add attributes to instance and use attribute like @Property with get and set
Im learning Python here so please spare me for silly questions. I Encounter an issue with adding attribute to a class instance
I have a dictionary of people with name,age and strength, i.e
{
"Mary": {"age":25, "strength": 80},... | Dynamically add attributes to instance and use attribute like @Property with get and set | Im learning Python here so please spare me for silly questions. I Encounter an issue with adding attribute to a class instance
I have a dictionary of people with name,age and strength, i.e
{
"Mary": {"age":25, "strength": 80},
"John": {"age": 40, "strength": 70},
...
}
and a class that will get in list of people as co... | [
"I don't think this is possible. The expression group.Mary[\"strength\"] essentially consists of 2 steps:\n\nretrieving the attribute named \"Mary\" from the object group, and;\ncalling the method __getitem__ on the retrieved attribute with argument \"strength\".\n\nHowever, note that in your example you require St... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074665577_python.txt |
Q:
Loading older sklearn models with new sklearn package
I have upgraded my python version from 3.6.5 to 3.10.6 and scikit-learn version from 0.20.3 to 1.1.3.
I am getting the following error when I am trying to load my older models built on older sklearn version using the new sklearn version:
Traceback (most recent ... | Loading older sklearn models with new sklearn package | I have upgraded my python version from 3.6.5 to 3.10.6 and scikit-learn version from 0.20.3 to 1.1.3.
I am getting the following error when I am trying to load my older models built on older sklearn version using the new sklearn version:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/... | [
"This is the problem which I faced during a production release.\nComplete details and the solution to this issue are discussed at -\nhttps://www.kaggle.com/code/adeepak7/load-old-sklearn-models-with-new-sklearn-package\n"
] | [
0
] | [] | [] | [
"model_management",
"python",
"python_3.x",
"scikit_learn"
] | stackoverflow_0074667759_model_management_python_python_3.x_scikit_learn.txt |
Q:
Return a list of weekdays, starting with given weekday
My task is to define a function weekdays(weekday) that returns a list of weekdays, starting with the given weekday. It should work like this:
>>> weekdays('Wednesday')
['Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday']
So far I've c... | Return a list of weekdays, starting with given weekday | My task is to define a function weekdays(weekday) that returns a list of weekdays, starting with the given weekday. It should work like this:
>>> weekdays('Wednesday')
['Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday']
So far I've come up with this one:
def weekdays(weekday):
days = ('Mo... | [
"The reason your code is only returning one day name is because weekday will never match more than one string in the days tuple and therefore won't add any of the days of the week that follow it (nor wrap around to those before it). Even if it did somehow, it would still return them all as one long string because y... | [
15,
10,
7,
4,
4,
4,
2,
1,
1,
0,
0,
0
] | [] | [] | [
"calendar",
"python",
"weekday"
] | stackoverflow_0004082772_calendar_python_weekday.txt |
Q:
I want to convert array of intensities to an image
I have the MNIST dataset. The CSV file contains 70,000 rows and 785 columns. The last column is the label. I want to convert the first columns of a row to the respective grayscale image with dimensions 28x28.
Image of the data:
A:
So you just want to convert you... | I want to convert array of intensities to an image | I have the MNIST dataset. The CSV file contains 70,000 rows and 785 columns. The last column is the label. I want to convert the first columns of a row to the respective grayscale image with dimensions 28x28.
Image of the data:
| [
"So you just want to convert your data from csv to grayscale?\nfrom keras.preprocessing.image import ImageDataGenerator\ndata_generator = ImageDataGenerator()\ndata = data_generator.flow_from_dataframe(df, color_mode=\"grayscale\")\n\nThe df variable is your read csv. your data should return grayscale images using ... | [
0
] | [] | [] | [
"csv",
"mnist",
"python"
] | stackoverflow_0074667006_csv_mnist_python.txt |
Q:
How do you loop through api with list of parameters and store resulting calls in one dataframe
I'm trying to loop a list of match ids (LMID5) as parameters for api calls. I think I have the looping the API calls correct as it prints the urls but I'm struggling to store the results every time in the same dataframe.... | How do you loop through api with list of parameters and store resulting calls in one dataframe | I'm trying to loop a list of match ids (LMID5) as parameters for api calls. I think I have the looping the API calls correct as it prints the urls but I'm struggling to store the results every time in the same dataframe.
The results of the API come through in JSON. Which I then normalise into a DF.
When just using one ... | [
"Can you try this:\ndfMatchDetails=pd.DataFrame()\nfor i in list(LMID5):\n url = 'https://api.football-data-api.com/match?key=&match_id=' + str(i)\n rm = requests.get(url)\n print(url)\n dfMatchDetails=pd.concat([dfMatchDetails,pd.json_normalize(rm.json()['data'])])\n\n"
] | [
1
] | [] | [] | [
"api",
"loops",
"pandas",
"python",
"python_requests"
] | stackoverflow_0074667638_api_loops_pandas_python_python_requests.txt |
Q:
Add memoization to recursive function, Python
Python. First of all, I did recursive code that find how many the shortests paths has matrix, path from last cell in matrix to frist cell in matrix. This is my code that work:
def matrix_explorer(n,m):
"""
Recursive function that find number of the shortest pat... | Add memoization to recursive function, Python | Python. First of all, I did recursive code that find how many the shortests paths has matrix, path from last cell in matrix to frist cell in matrix. This is my code that work:
def matrix_explorer(n,m):
"""
Recursive function that find number of the shortest paths from beginning cell of matrix to last cell
:... | [] | [] | [
"To add memoization to your matrix_explorer function, you can use a dictionary to store the results of previously computed paths. When the function is called, you can check if the result for the given n and m values has already been computed. If so, you can simply return the stored result from the dictionary instea... | [
-3
] | [
"function",
"matrix",
"memoization",
"python",
"recursion"
] | stackoverflow_0074667818_function_matrix_memoization_python_recursion.txt |
Q:
switch case matching with array index value
I have this function in which I want to assign the values of img array that has 1 to 4 numbers, and I want to put red,yellow,green,blue into array matrixColored, but when I use switch case it gives erros in 4th line, help me thanks.
def colorPrint():
for i in range(r):
... | switch case matching with array index value | I have this function in which I want to assign the values of img array that has 1 to 4 numbers, and I want to put red,yellow,green,blue into array matrixColored, but when I use switch case it gives erros in 4th line, help me thanks.
def colorPrint():
for i in range(r):
for j in range(c):
match img[i][j]:
... | [
"Can't say what the problem is without the error message but, match is not the only way to do this.\nHere's an example using a dictionary:\ncolorDict = {1:'red', 2:'green', 3:'blue', 4:'yellow'}\n\nimg = 3\ncolor = colorDict.get(img)\nif img in colorDict:\n matrixColored = colorDict[img]\n print(matrixColored... | [
0
] | [] | [] | [
"arrays",
"for_loop",
"indexing",
"python",
"range"
] | stackoverflow_0074644591_arrays_for_loop_indexing_python_range.txt |
Q:
npm ERR! gyp ERR! stack Error: Could not find any Visual Studio installation to use
Alright,
After quite some reinstalling, reading I still can't figure what is going on.
I'm trying to run npm install --force on a codecanyon script, reinstalled node to latest version, same as python and build tools, added VCINSTAL... | npm ERR! gyp ERR! stack Error: Could not find any Visual Studio installation to use | Alright,
After quite some reinstalling, reading I still can't figure what is going on.
I'm trying to run npm install --force on a codecanyon script, reinstalled node to latest version, same as python and build tools, added VCINSTALLDIR to path, restarted windows multiple times and still the same issue.
npm ERR! code 1
... | [
"It seems it has something to do with Windows 11, running a VM of Win10 Pro where it executes perfectly with the latest packages.\nPS: Windows Build Tools are now embedded in the latest Node, so no need to install them manually. Just Node, Git, Visual Studio Code and restart for PATH to update automatically.\n"
] | [
0
] | [] | [] | [
"node.js",
"npm",
"python"
] | stackoverflow_0074632361_node.js_npm_python.txt |
Q:
update a value by running through every row in a data frame with conditions (extension)
This is an extension to the question, 'update a value by running through every row in a data frame with conditions' update a value by running through every row in a data frame with conditions
Working with the same data frame:
D... | update a value by running through every row in a data frame with conditions (extension) | This is an extension to the question, 'update a value by running through every row in a data frame with conditions' update a value by running through every row in a data frame with conditions
Working with the same data frame:
Df:
Index
A
B
A_yes
B_yes
0
2.43
1.55
1
0
1
2.58
1.49
0
1
2
1.61
2.32
1
0
3
2.7
... | [
"You could try the following with df your dataframe:\nstart = 500\nweights = (df[\"A\"].where(df[\"A_yes\"].eq(1), df[\"B\"]) * 0.5 + 0.5).cumprod()\ndf[\"Points\"] = start * weights\n\n\nUse .where to select between the value in A or B based on the A_yes and B_yes entries (my assumption here is that there's a 1 ei... | [
0
] | [] | [] | [
"conditional_statements",
"dataframe",
"loops",
"pandas",
"python"
] | stackoverflow_0074662788_conditional_statements_dataframe_loops_pandas_python.txt |
Q:
How to acces all the file from the directory using Python?
for i in os.listdir(r"C:\Users\Xmall\same-resume-year-wise-master\same-resume-year-wise-master"):
print(i)
if i.endswith('.pdf'):
a=open(i)
s=PyPDF2.PdfFileReader(a)
for j in range(s.numPages):
z=s.getPage(j)
... | How to acces all the file from the directory using Python? | for i in os.listdir(r"C:\Users\Xmall\same-resume-year-wise-master\same-resume-year-wise-master"):
print(i)
if i.endswith('.pdf'):
a=open(i)
s=PyPDF2.PdfFileReader(a)
for j in range(s.numPages):
z=s.getPage(j)
er=z.extractText()
print(re.findall('\S+@\S... | [
"I'll post two solutions using two different libraries .\nI'm not sure if this will work , or is what you are looking for but it could lead you somewhere .\n #extract email addresses using pyPDF2\ndef extractEmails(pdfFile):\n pdfReader = PyPDF2.PdfFileReader(pdfFile)\n emails = []\n for pageNum in rang... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074667852_python.txt |
Q:
python sqlite3 update binary field
SELECT from one database sqlite3 gives me result:
b'\n\x0b24 JUN 1974"-\x08\x01\x10\x00\x18\x00 \x18(\x060\xb6\x0f8\x00@\x00H\x00P\x00X\xbf\x84=`\x00h\x00p\x00x\x00\x80\x01\x00\x88\x01\x01\x90\x01\xa0\xdc\x90^'
This is field data (VARCHAR(255)) of database My heritage and i want... | python sqlite3 update binary field | SELECT from one database sqlite3 gives me result:
b'\n\x0b24 JUN 1974"-\x08\x01\x10\x00\x18\x00 \x18(\x060\xb6\x0f8\x00@\x00H\x00P\x00X\xbf\x84=`\x00h\x00p\x00x\x00\x80\x01\x00\x88\x01\x01\x90\x01\xa0\xdc\x90^'
This is field data (VARCHAR(255)) of database My heritage and i want to save the same result to the same dat... | [
"To update a field in a SQLite database using Python, you can use the UPDATE statement in combination with the execute() method provided by the sqlite3 module.\nFor example, if you want to update the date field of the individual_fact_main_data table in your database, you can use the following Python code:\nimport s... | [
0
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0074667914_python_sqlite.txt |
Q:
How to group by data in a column with pandas?
I have a table with 8,000 rows of data and a small sample of it here:
Customer ItemDescription Invoice PurchaseDate
1064 Produce 55514 22-01
1064 Snack 55514 22-01
1080 ... | How to group by data in a column with pandas? | I have a table with 8,000 rows of data and a small sample of it here:
Customer ItemDescription Invoice PurchaseDate
1064 Produce 55514 22-01
1064 Snack 55514 22-01
1080 Drink 56511 23-01
1080... | [
"You can use groupby. By using groupby, you can group the products according to the customers and store them in the form of a list.\ndfx=df.groupby('Customer').agg({'ItemDescription':list})\n'''\n ItemDescription\nCustomer \n1064 [Produce, Snack]\n108... | [
0,
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074666835_dataframe_pandas_python.txt |
Q:
Fit data with a function that equals 0 and could not be converted to the form f(x) = x
I have 2 columns and 31 rows in a pandas dataframe.
I want to plot this x,y data and fit them to a complex function with 4 parameters.
The function looks something like this.
The function has to be 0
# Data:
T,p = df["T"], df["p... | Fit data with a function that equals 0 and could not be converted to the form f(x) = x | I have 2 columns and 31 rows in a pandas dataframe.
I want to plot this x,y data and fit them to a complex function with 4 parameters.
The function looks something like this.
The function has to be 0
# Data:
T,p = df["T"], df["p"] #31 rows
# known constants: a,b,Ta,c0,x
def c(T,v,VP,a=...,b=...,Ta=...,c0=...):
c... | [
"I find an answer myself.\nFirst I wrap my function in a way that the y-value p is the first argument.\nAnd I used lmfit parameter class as arguments. Lmfit Parameters are basically dictionaries.\np_solvable = lambda p,T,parameter : function(p,T,parameter[\"p0\"],parameter[\"v\"],...)\n\nThen I solve the equation b... | [
0
] | [] | [] | [
"curve_fitting",
"lmfit",
"pandas",
"python",
"scipy_optimize"
] | stackoverflow_0074437309_curve_fitting_lmfit_pandas_python_scipy_optimize.txt |
Q:
How to freeze a requirement with pipenv?
For example we have some pipfile (below) and I'd like to freeze the django version. We don't have a requirements.txt and we only use pipenv. How can I freeze the django version?
[[source]]
url = "https://pypi.org/simple"
verify_ssl = true
name = "pypi"
[packages]
django = ... | How to freeze a requirement with pipenv? | For example we have some pipfile (below) and I'd like to freeze the django version. We don't have a requirements.txt and we only use pipenv. How can I freeze the django version?
[[source]]
url = "https://pypi.org/simple"
verify_ssl = true
name = "pypi"
[packages]
django = "*"
[dev-packages]
black = "*"
[requires]
py... | [
"Pipenv do natively implement freezing requirements.txt.\nIt is as simple as:\npipenv lock -r > requirements.txt\n\n",
"Assuming you have your virtual environment activated, you have three simple approaches. I will list them from less verbose to more verbose.\npip\n$ pip freeze > requirements.txt\n\npip3\n$ pip3 ... | [
99,
26,
24,
11,
9,
1,
0,
0,
0,
0
] | [
"You can create a requirements.txt using this command : \npip3 freeze > requirements.txt\n\n"
] | [
-3
] | [
"pipenv",
"pipfile",
"python"
] | stackoverflow_0051845562_pipenv_pipfile_python.txt |
Q:
jupyter notebook can not import keras
I have installed Keras and TensorFlow-GPU but when I try to import these libraries into Jupiter notebook there is an error
Keras-applications 1.0.8 pypi_0 pypi
keras-preprocessing 1.1.2 pypi_0 pypi
tensorboard ... | jupyter notebook can not import keras | I have installed Keras and TensorFlow-GPU but when I try to import these libraries into Jupiter notebook there is an error
Keras-applications 1.0.8 pypi_0 pypi
keras-preprocessing 1.1.2 pypi_0 pypi
tensorboard 2.1.1 pypi_0 pypi... | [
"If you're using tensorflow >= 2.0, then import keras using\nfrom tensorflow import keras\n\nCommon convention is to import it as kr\n",
"Can you please tell me if you're using multiple versions of python on the same device, if so please check if you've installed TensorFlow on the same version of python which you... | [
1,
0,
0
] | [] | [] | [
"anaconda",
"jupyter_notebook",
"keras",
"python",
"tensorflow"
] | stackoverflow_0064861794_anaconda_jupyter_notebook_keras_python_tensorflow.txt |
Q:
Fetching data from GCP cloud storage (avro files) based on last modified date
I am in the process of fetching the latest data in Avro format from the GCP cloud storage to Bigquery. I have come across this resource that shows how to do it. Questions
Is it possible to get the latest modified Avro file ?
Are there m... | Fetching data from GCP cloud storage (avro files) based on last modified date | I am in the process of fetching the latest data in Avro format from the GCP cloud storage to Bigquery. I have come across this resource that shows how to do it. Questions
Is it possible to get the latest modified Avro file ?
Are there metadata files from the GCP storage bucket that can help with this?
| [
"You can use this command to sort files to get the latest file from GCS bucket, you can change the condition based on the requirement.\ngsutil ls -l gs://[bucket-name]/ | sort -k 2 | tail -n 2\n\nTo specifically get the latest .avro file from the GCS Bucket, you can consider this code:\nfrom google.cloud import sto... | [
0
] | [] | [] | [
"avro",
"google_bigquery",
"google_cloud_platform",
"google_cloud_storage",
"python"
] | stackoverflow_0074655356_avro_google_bigquery_google_cloud_platform_google_cloud_storage_python.txt |
Q:
mysql + sqlalchemy create table auto increment
In sqlalchemy, I am trying to create a table with a primary key tenant_id and a different auto increment column tenant_index as below
class Tenant(Base):
"""Data Model for tenants table"""
__tablename__ = "tenants"
__table_args__ = {"schema": DATABASE}
... | mysql + sqlalchemy create table auto increment | In sqlalchemy, I am trying to create a table with a primary key tenant_id and a different auto increment column tenant_index as below
class Tenant(Base):
"""Data Model for tenants table"""
__tablename__ = "tenants"
__table_args__ = {"schema": DATABASE}
tenant_index = Column(
BigInteger,
... | [
"A table cannot have two primary keys, but a single primary key may include two columns. This means you need to define the primary key constraint separately, not as an attribute of either column.\nhttps://docs.sqlalchemy.org/en/14/core/constraints.html#primary-key-constraint shows an example:\nmy_table = Table(\n ... | [
0
] | [] | [] | [
"mysql",
"python",
"sqlalchemy"
] | stackoverflow_0074667920_mysql_python_sqlalchemy.txt |
Q:
build speech to text system from scratch using python
I am in need to Speech to text system so that I can transcribe audio files to text format.
While researching on that I found systems created by big companies e.g Amazon Transcribe, Google Speech to Text, IBM Watson etc.
And found all the libraries in python in... | build speech to text system from scratch using python | I am in need to Speech to text system so that I can transcribe audio files to text format.
While researching on that I found systems created by big companies e.g Amazon Transcribe, Google Speech to Text, IBM Watson etc.
And found all the libraries in python internal make use of those APIs.
What would be the steps if I... | [
"One place to start would be to review the offerings of www.voxforge.org; review the tutorial and forums sections to get an overview of the use of open source projects such as Julius and CMU Sphinx. It's a quite extensive subject and you will find that many people have trodden the path before you, so you can learn ... | [
0,
0
] | [] | [] | [
"deep_learning",
"machine_learning",
"python",
"speech_recognition",
"speech_to_text"
] | stackoverflow_0058796931_deep_learning_machine_learning_python_speech_recognition_speech_to_text.txt |
Q:
Quicksight Dashboard using existing Template
I am trying to create a template in Quicksight, so that it allows me to create dashboards with different datasets, but with the same structure.
I am using boto3 (Python) and the documentation indicates that a template is capable of creating a dashboard using different d... | Quicksight Dashboard using existing Template | I am trying to create a template in Quicksight, so that it allows me to create dashboards with different datasets, but with the same structure.
I am using boto3 (Python) and the documentation indicates that a template is capable of creating a dashboard using different datasets, as long as the new dataset has the same s... | [
"Follow link to image here\nhttps://i.stack.imgur.com/69rHj.png\nSee line 32 and description on line33.\nThis had me going for 2 or 3 hours, too. Same error as yourself.\nFrom AWS CLI I derived my QS data set id. That was wrong in my case.\nUse the TEMPLATE data set id instead. Issue resolved, dashboard created.\n"... | [
0,
0
] | [] | [] | [
"amazon_quicksight",
"amazon_web_services",
"boto3",
"dashboard",
"python"
] | stackoverflow_0070516228_amazon_quicksight_amazon_web_services_boto3_dashboard_python.txt |
Q:
how could i count longest sequence of 01 in list
i need to count longest 01 from list
ex:
[1,1,1,0,0,1,1,1,0,1,0,1,0,1,0]
suppose to print 4 (sequence could also start with 10):
1,0,1,0 = 2
import itertools
with open("file.txt", 'r+') as file:
file_context = file.read()
print(file_context)
def func1... | how could i count longest sequence of 01 in list | i need to count longest 01 from list
ex:
[1,1,1,0,0,1,1,1,0,1,0,1,0,1,0]
suppose to print 4 (sequence could also start with 10):
1,0,1,0 = 2
import itertools
with open("file.txt", 'r+') as file:
file_context = file.read()
print(file_context)
def func1(arg):
global key
key = list(arg)
print(key)
fu... | [
"You can do this with a fairly straightforward double loop - i.e., two iterations checking for 0,1 then 1,0 pairs\nlst = [1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0]\n\nms = 0\n\nfor t in [0, 1], [1, 0]:\n i, c = 0, 0\n while i < len(lst)-1:\n if lst[i:i+2] == t:\n c += 1\n i += ... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074667264_python.txt |
Q:
OpenAI Gym Manual Play function automatically presses key
import gym
from gym.utils import play
play.play(gym.make('MountainCar-v0', render_mode='rgb_array').env, zoom=1, keys_to_action={"0":0, "2":2, "1":1})
The above code is all that is needed to play MountainCar manually.
The controls are as follows:
0 = noth... | OpenAI Gym Manual Play function automatically presses key | import gym
from gym.utils import play
play.play(gym.make('MountainCar-v0', render_mode='rgb_array').env, zoom=1, keys_to_action={"0":0, "2":2, "1":1})
The above code is all that is needed to play MountainCar manually.
The controls are as follows:
0 = nothing
1 = left
2 = right
However when I run the code, if I'm not ... | [
"import gym\nfrom gym.utils import play\nenv = play.play(gym.make('MountainCar-v0', render_mode='rgb_array').env, zoom=1, keys_to_action={\"2\":2, \"1\":0}, noop=1)\n\nthe noop sets the default action\n"
] | [
0
] | [] | [] | [
"openai_gym",
"python"
] | stackoverflow_0074658467_openai_gym_python.txt |
Q:
Connecting the board to the player objects
Having coded for the players for my boardgame, I am facing difficulties with creating the board and connectying it to the players.
The board is a list containig 10 slots, where each slot is a string with a hidden from the player letter (A,B,C,D,E,F,G,I,J,K). The letter is... | Connecting the board to the player objects | Having coded for the players for my boardgame, I am facing difficulties with creating the board and connectying it to the players.
The board is a list containig 10 slots, where each slot is a string with a hidden from the player letter (A,B,C,D,E,F,G,I,J,K). The letter is only known to the owner of the slot.
At the beg... | [
"Here; I modified the player creation a little too.\nfrom dataclasses import dataclass\n@dataclass\nclass Player: \n firstname: str\n lastname: str\n coins: int\n slot: int\n def full_info(self) -> str:\n return f\"{self.firstname} {self.lastname} {self.coins} {self.slot}\"\n\n @classmethod... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074667709_python.txt |
Q:
Select column containing several value with range of number in pandas
If I have a dataframe `
A Variant&Price Qty
AAC 7:124|25: 443 1
AAD 35:|35: 1
AAS 32:98|3:40 1
AAG 2: |25: ... | Select column containing several value with range of number in pandas | If I have a dataframe `
A Variant&Price Qty
AAC 7:124|25: 443 1
AAD 35:|35: 1
AAS 32:98|3:40 1
AAG 2: |25: 1
AAC 25:443|26:344 1
and I want to get varia... | [
"You can use a regex to extractall the number before :, convert to integer and check if any is between 2 and 7:\nm = (df['Variant&Price'].str.extractall('(\\d+):')[0]\n .astype(int).between(2,7).groupby(level=0).any()\n )\n\nout = df[m]\n\nOutput:\n A Variant&Price Qty\n0 AAC 7:124|25: 443 1\n2 A... | [
3,
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074667993_pandas_python.txt |
Q:
python program not running is html webpage
this my html code
<!DOCTYPE html>
<html lang="en">
<head>
<title>pyscript demo</title>
<link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
<script defer src="https://pyscript.net/latest/pyscript.js"></script>
</head>
<body>
<py-script src="pythonf... | python program not running is html webpage | this my html code
<!DOCTYPE html>
<html lang="en">
<head>
<title>pyscript demo</title>
<link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
<script defer src="https://pyscript.net/latest/pyscript.js"></script>
</head>
<body>
<py-script src="pythonfile.py"></py-script>
</body>
</html>
and this ... | [
"If you have vs-code, install \"Live-Server\" extension and open live-server.\nor\nopen terminal/command-prompt in the same folder. Assuming you have named your html file as \"index.html\", enter following command in terminal:\npython3 -m http.server 8000\nthen open http://0.0.0.0:8000 in your browser\n",
"You ar... | [
0,
0,
0
] | [] | [] | [
"html",
"python",
"python_3.x"
] | stackoverflow_0074667822_html_python_python_3.x.txt |
Q:
Expression of double summation in python
I am trying to solve an optimization problem using Pulp in Python, but I'm having some trouble in expressing my constraints.
def Kakuro(M):
prob = pulp.LpProblem()
rows = range(1,4)
cols = range(1,4)
vals = range(1,10)
X = pulp.LpVariable.dicts("X",(ro... | Expression of double summation in python | I am trying to solve an optimization problem using Pulp in Python, but I'm having some trouble in expressing my constraints.
def Kakuro(M):
prob = pulp.LpProblem()
rows = range(1,4)
cols = range(1,4)
vals = range(1,10)
X = pulp.LpVariable.dicts("X",(rows,cols,vals),cat='Binary')
for i in rows... | [
"If I understand what you are trying to do, you can just augment the summation expression to include 2 variables... Something like:\nfor i in cols:\n prob += sum(x[i][j][k] for j in rows for k in vals) <= M[i][0]\n\n"
] | [
0
] | [] | [] | [
"for_loop",
"optimization",
"pulp",
"python"
] | stackoverflow_0074665043_for_loop_optimization_pulp_python.txt |
Q:
Creating an Equal Area Spatial Grid Over a Large Area (R or Python)
I am facing a challenge trying to create a 12km spatial grid covering the African continent with open source tools. The main challenge appears to be that most of these tools are based on projected (metric) coordinate reference systems (CRS), which... | Creating an Equal Area Spatial Grid Over a Large Area (R or Python) | I am facing a challenge trying to create a 12km spatial grid covering the African continent with open source tools. The main challenge appears to be that most of these tools are based on projected (metric) coordinate reference systems (CRS), which are inaccurate for very large areas. I need grid creating software based... | [
"I think you are trying to do the impossible. You can either have a 12km x 12km grid in a projected CRS that is approximately 12km x 12km and approximately square on the ground, or you have a regular Z by Z degrees grid in a lat-long projection that is approximately square and approximately 12km x 12 km on the grou... | [
0
] | [] | [] | [
"geospatial",
"python",
"r"
] | stackoverflow_0074655449_geospatial_python_r.txt |
Q:
VSCode 1.39.x & Python 3.7.x: "ImportError: attempted relative import with no known parent package" - when started without debugging (CTRL+F5))
when running Python test from withing VS Code using CTRL+F5 I'm getting error message
ImportError: attempted relative import with no known parent package
when running Pyt... | VSCode 1.39.x & Python 3.7.x: "ImportError: attempted relative import with no known parent package" - when started without debugging (CTRL+F5)) |
when running Python test from withing VS Code using CTRL+F5 I'm getting error message
ImportError: attempted relative import with no known parent package
when running Python test from VS Code terminal by using command line
python test_HelloWorld.py
I'm getting error message
ValueError: attempted relative import b... | [
"You're bumping into two issues. One is you're running your test file from within the directory it's written, and so Python doesn't know what .. represents. There are a couple of ways to fix this.\nOne is to take the solution that @lesiak proposed by changing the import to from solutions import helloWorldPackage bu... | [
4,
3,
1,
0,
0
] | [] | [] | [
"import",
"package",
"python",
"python_unittest",
"visual_studio_code"
] | stackoverflow_0058709973_import_package_python_python_unittest_visual_studio_code.txt |
Q:
Assigning lines in text files to a list in python
I am making an app that stores its settings in a .txt file. I am able to get the line count, but I don't know, how to store the text in one line in a variable.
For example:
linecount = 0
datainfile = []
with open("txt.txt" , "r") as t:
linecount += 1
#Ho... | Assigning lines in text files to a list in python | I am making an app that stores its settings in a .txt file. I am able to get the line count, but I don't know, how to store the text in one line in a variable.
For example:
linecount = 0
datainfile = []
with open("txt.txt" , "r") as t:
linecount += 1
#Hoe to add lines to datainfile?
config1 = datainfile[0]... | [
"First, it is always a good practice to use context manager when opening a file (using the with keyword). Second, read the file to a list and address the line number by index.\nimport os\n\n\nwith open(\"config.txt\", \"r\") as cf:\n file_lines = [line.replace(os.linesep, \"\") for line in cf.readlines()]\n\nNo... | [
0,
0
] | [] | [] | [
"file",
"line",
"python",
"python_3.x",
"variables"
] | stackoverflow_0074162036_file_line_python_python_3.x_variables.txt |
Q:
Why glVertexAttribPointer throws 1282 error while trying to draw one point on screen with pyOpenGL and glfw?
I have separated the program to three different files, but I don't understand why I get error on glVertexAttribPointer on line 70. I'm using Python 3.10.8
main.py
import glfw
import Shaders
from OpenGL.GL i... | Why glVertexAttribPointer throws 1282 error while trying to draw one point on screen with pyOpenGL and glfw? | I have separated the program to three different files, but I don't understand why I get error on glVertexAttribPointer on line 70. I'm using Python 3.10.8
main.py
import glfw
import Shaders
from OpenGL.GL import *
from OpenGL.GLUT import *
from Math_3d import Vector2f
class Window:
def __init__(self, width: int, ... | [
"You're using a Core profile OpenGL Context (glfw.OPENGL_CORE_PROFILE). Therefore you have to create a Vertex Array Obejct:\nclass Window:\n # [...]\n\n def createshaders(self):\n # [...]\n\n v2f_1 = Vector2f(0.0, 0.0)\n # Request a buffer slot from GPU\n buffer = glGenBuffers(1)\n... | [
1
] | [] | [] | [
"opengl",
"pyopengl",
"python",
"python_3.x"
] | stackoverflow_0074668037_opengl_pyopengl_python_python_3.x.txt |
Q:
Generate random binary matrix constrained to no null row
I want to generate a random binary matrix, so I'm using W=np.random.binomial(1, p, (n,n)).
It works fine, but I want a constraint that no row is just of 0s.
I create the following function:
def random_matrix(p,n):
m=0
while m==0:
W = np.rand... | Generate random binary matrix constrained to no null row | I want to generate a random binary matrix, so I'm using W=np.random.binomial(1, p, (n,n)).
It works fine, but I want a constraint that no row is just of 0s.
I create the following function:
def random_matrix(p,n):
m=0
while m==0:
W = np.random.binomial(1, p, (n,n))
m=min(W.sum(axis=1))
retu... | [
"One way to make the process of generating a random binary matrix with no rows of only 0s more efficient is to use the np.random.choice function to randomly choose a non-zero entry from each row of the matrix and set its value to 1. This avoids the need to use a while loop and repeatedly check for rows of only 0s, ... | [
0,
0
] | [] | [] | [
"loops",
"matrix",
"numpy",
"python",
"random"
] | stackoverflow_0074667612_loops_matrix_numpy_python_random.txt |
Q:
What is the Python equivalent of static variables inside a function?
What is the idiomatic Python equivalent of this C/C++ code?
void foo()
{
static int counter = 0;
counter++;
printf("counter is %d\n", counter);
}
specifically, how does one implement the static member at the function level, as oppose... | What is the Python equivalent of static variables inside a function? | What is the idiomatic Python equivalent of this C/C++ code?
void foo()
{
static int counter = 0;
counter++;
printf("counter is %d\n", counter);
}
specifically, how does one implement the static member at the function level, as opposed to the class level? And does placing the function into a class change an... | [
"A bit reversed, but this should work:\ndef foo():\n foo.counter += 1\n print \"Counter is %d\" % foo.counter\nfoo.counter = 0\n\nIf you want the counter initialization code at the top instead of the bottom, you can create a decorator:\ndef static_vars(**kwargs):\n def decorate(func):\n for k in kwa... | [
822,
270,
251,
70,
60,
33,
32,
17,
16,
11,
10,
9,
7,
6,
4,
4,
4,
4,
4,
4,
3,
3,
2,
1,
0,
0,
0
] | [
"Sure this is an old question but I think I might provide some update.\nIt seems that the performance argument is obsolete. \nThe same test suite appears to give similar results for siInt_try and isInt_re2.\nOf course results vary, but this is one session on my computer with python 3.4.4 on kernel 4.3.01 with Xeon ... | [
-2
] | [
"python",
"static"
] | stackoverflow_0000279561_python_static.txt |
Q:
Verifying types in a python function (including types from the typing module)
I am trying to create a function in python that can be used in other functions to verify that arguments passed into the function are of the correct type(s)
It works for standard python types, e.g. 'str', 'int', etc.,
but I want it to be ... | Verifying types in a python function (including types from the typing module) | I am trying to create a function in python that can be used in other functions to verify that arguments passed into the function are of the correct type(s)
It works for standard python types, e.g. 'str', 'int', etc.,
but I want it to be able to check more complex types, such as a list containing strings and integers (t... | [
"You can't do this, at least in a general way, because while you can get the type annotations of the function's parameters, the objects that your function receives at runtime as arguments don't have type annotations attached to them.\nA function's types and their parameters can be inspected via its __annotations__ ... | [
2
] | [] | [] | [
"function",
"python",
"types",
"typing"
] | stackoverflow_0074668288_function_python_types_typing.txt |
Q:
Django registration form gives error, when password can not pass validation
I am trying to make user registration with automatic login. When passwords are different or do not pass validation, there is no message from the form. It throws an error:
AttributeError at /accounts/register/
'AnonymousUser' object has no ... | Django registration form gives error, when password can not pass validation | I am trying to make user registration with automatic login. When passwords are different or do not pass validation, there is no message from the form. It throws an error:
AttributeError at /accounts/register/
'AnonymousUser' object has no attribute '_meta'
I think the error comes from the login(request, self.object) l... | [
"You need to override form_valid() instead of post().\nfrom django.http import HttpResponseRedirect\n\ndef form_valid(self, form):\n user = form.save() #save the user\n login(request, user)\n return HttpResponseRedirect(self.get_success_url())\n\n"
] | [
0
] | [] | [] | [
"authentication",
"django",
"python"
] | stackoverflow_0074667644_authentication_django_python.txt |
Q:
How do you count the number of negative items in a list using a recursive function?
I have to make a recursive function that counts how many negative values there are in a given list, but I can't figure out what I am supposed to return for each conditional.
def countNegatives(list):
"""Takes in a list of numbe... | How do you count the number of negative items in a list using a recursive function? | I have to make a recursive function that counts how many negative values there are in a given list, but I can't figure out what I am supposed to return for each conditional.
def countNegatives(list):
"""Takes in a list of numbers and
returns the number of negative numbers
that are inside the list."""
co... | [
"When list[0] < 0 your code ignores the rest of the list, yet there could be more negative values there to count.\nSo in that case don't do:\n return count + 1\n\nbut:\n return 1 + countNegatives(list[1:])\n\n",
"The step you were missing is to add the count to the returned value of the recursive ca... | [
0,
0,
0,
0
] | [
"The problem with your code is that you are not keeping track of the running count of negative numbers in the recursive calls. Specifically, you are returning count + 1 when the first item of the list is negative, and discarding the rest of the list, instead of using a recursive call to count the number of negative... | [
-1,
-1
] | [
"python",
"recursion"
] | stackoverflow_0074659510_python_recursion.txt |
Q:
How to redirect an authenticated (using Django) user to VueJS frontend?
I have a simple VueJS setup that involves some use of a router. This runs on one local server. I also have a django backend project that runs on a second local server. I would like for a django view to take my user to my vue frontend. What app... | How to redirect an authenticated (using Django) user to VueJS frontend? | I have a simple VueJS setup that involves some use of a router. This runs on one local server. I also have a django backend project that runs on a second local server. I would like for a django view to take my user to my vue frontend. What approach could I take to reach this?
I have not yet made an attempt but if there... | [
"\nfrom django.shortcuts import redirect\n\ndef login(request):\n # Verify the user's authentication data\n # and authenticate the user if the data is valid\n # ...\n\n # Redirect the user to the VueJS frontend\n return redirect('https://vuejs.app')\n\n\nIn this example, when the user is successfully... | [
0
] | [] | [] | [
"django",
"python",
"vite",
"vue.js",
"webpack"
] | stackoverflow_0074668331_django_python_vite_vue.js_webpack.txt |
Q:
Inserting cli options into virtualenv.cli_run within a python file
Problem Code Picture
I want to write a Python script that creates a new virtual environment with the following virtualenv CLI options:
--app-data APP_DATA (a folder APP_DATA for the cache)
--seeder {app-data,pip}
If I give those two as strings in... | Inserting cli options into virtualenv.cli_run within a python file | Problem Code Picture
I want to write a Python script that creates a new virtual environment with the following virtualenv CLI options:
--app-data APP_DATA (a folder APP_DATA for the cache)
--seeder {app-data,pip}
If I give those two as strings in a list (see picture) I get:
TypeError: options must be of type VirtualE... | [
"When you call cli_run as part of virtualenv, you don't need to include the first argument, in this case \"venv\".\nthis should work:\nfrom virtualenv import cli_run\ncli_run([\"--app-data APP_DATA\", \"--seeder {app-data,pip}\"]);\n\n",
"According to virtualenv's documentation section \"Programmatic API\", this ... | [
0,
0
] | [] | [] | [
"python",
"virtualenv"
] | stackoverflow_0074662331_python_virtualenv.txt |
Q:
Get Text from SVG using Python Selenium
My first time trying to extract data from an SVG element, following is the SVG element and the code I have tried to put up by reading stuff on the internet, I have absolutely no clue how wrong I am and why so.
<svg class="rv-xy-plot__inner" width="282" height="348">
<g cla... | Get Text from SVG using Python Selenium | My first time trying to extract data from an SVG element, following is the SVG element and the code I have tried to put up by reading stuff on the internet, I have absolutely no clue how wrong I am and why so.
<svg class="rv-xy-plot__inner" width="282" height="348">
<g class="rv-xy-plot__series rv-xy-plot__series--ba... | [
"You can try something like :\nfor sv in driver.find_elements(By.XPATH,\"//*[local-name()='svg' and @class='rv-xy-plot__inner']//*[local-name()='g' and @class='rv-xy-plot__series rv-xy-plot__series--label typography-body-medium-xs text-primary']\"):\n txt= sv.find_emlement(By.XPATH, './/text').text\n print(... | [
1,
0
] | [] | [] | [
"python",
"selenium",
"svg",
"web_scraping"
] | stackoverflow_0074663657_python_selenium_svg_web_scraping.txt |
Q:
Why system path behaviour in pycharm seems to be different that using directly the conda env?
this is actually my first question in stack overflow :D. As background: I started learning python by myself almost 1 year ago in parallel of my work (Industrial Engineer), so feel free to point any mistakes. Any feedback ... | Why system path behaviour in pycharm seems to be different that using directly the conda env? | this is actually my first question in stack overflow :D. As background: I started learning python by myself almost 1 year ago in parallel of my work (Industrial Engineer), so feel free to point any mistakes. Any feedback will be very appreciated (including the format of this question).
I was trying to a have a project ... | [
"Solved.\nAfter some more investigation it was clear that I was facing 2 problems:\n\nNot declaring the env path in the system\nNot activating the virtual enviroment properly (hence the SSL error)\n\nSince I do not have the admin rights of the laptop (corporate one) I solved the path issue by defining the the proje... | [
0
] | [] | [] | [
"import",
"path",
"pycharm",
"python"
] | stackoverflow_0074352567_import_path_pycharm_python.txt |
Q:
Cutting an array into consistent pieces of any size, with recursion
The problem is to, given an array, write a generator function that will yield all combinations of cutting the array into consistent pieces(arrays of elements that are consecutive in the given array) of any size and which together make up the whole... | Cutting an array into consistent pieces of any size, with recursion | The problem is to, given an array, write a generator function that will yield all combinations of cutting the array into consistent pieces(arrays of elements that are consecutive in the given array) of any size and which together make up the whole given array. The elements in any one of the combinations don't have to b... | [
"One of the algorithm commonly used for these type of questions (permutations and combinations) is using depth-first-search (DFS). Here's a link to a more similar but harder leetcode problem on palindrome partitioning that uses backtracking and DFS. My solution is based off of that leetcode post.\nAlgorithm\nIf my ... | [
0
] | [] | [] | [
"generator",
"multidimensional_array",
"python",
"recursion"
] | stackoverflow_0074667555_generator_multidimensional_array_python_recursion.txt |
Q:
Trying to run Jupyter-Dash and getting "an integer is required" error
I am trying to get the first Dash example from https://dash.plotly.com/basic-callbacks running in a Jupyter Notebook with Jupyter Dash and the app runs fine as a standalone application, but errors out when implemented in the notebook and I can't... | Trying to run Jupyter-Dash and getting "an integer is required" error | I am trying to get the first Dash example from https://dash.plotly.com/basic-callbacks running in a Jupyter Notebook with Jupyter Dash and the app runs fine as a standalone application, but errors out when implemented in the notebook and I can't figure this out. I get
TypeError: an integer is required (got type NoneTy... | [
"I had the same problem, and I found your question while trying to find a solution.\nTry adding host as string and port as integer types inside run_server like this:\napp.run_server(mode='external', host='your_host', port=your_port)\nMy host is 127.0.0.1, and the port is 8050.\nHope it helps\n"
] | [
0
] | [] | [] | [
"jupyter_notebook",
"jupyterdash",
"plotly_dash",
"python"
] | stackoverflow_0073421435_jupyter_notebook_jupyterdash_plotly_dash_python.txt |
Q:
Rolling difference in group and divivded by group sum in Pandas
I am wondering if there's an easier/faster way (ideally in pipe method so it looks nicer!) I can work out the rolling difference divided by previous group sum. In the result outout, pc column is the column I am after.
import pandas as pd
df = pd.Data... | Rolling difference in group and divivded by group sum in Pandas | I am wondering if there's an easier/faster way (ideally in pipe method so it looks nicer!) I can work out the rolling difference divided by previous group sum. In the result outout, pc column is the column I am after.
import pandas as pd
df = pd.DataFrame(
{
"Date": ["2020-01-01", "2020-01-01", "2020-01-01... | [
"Here is one way to do it with Pandas assign and pipe:\ndf = (\n df.assign(total=df.groupby(\"Date\")[\"Pop\"].transform(\"sum\"))\n .pipe(\n lambda df_: df_.assign(\n pc=df_.groupby([\"City\"])\n .agg({\"Pop\": \"diff\", \"total\": \"shift\"})\n .pipe(lambda x: x[\"Pop... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074654758_pandas_python.txt |
Q:
How do I get variables from a Python script that are visible in the sh script?
I need to send notifications about new ssh connections.
I was able to implement this through the sh script. But it is difficult to maintain, I would like to use a python script instead.
notify-lo.py
#!/usr/bin/env python3
....
....
I ... | How do I get variables from a Python script that are visible in the sh script? | I need to send notifications about new ssh connections.
I was able to implement this through the sh script. But it is difficult to maintain, I would like to use a python script instead.
notify-lo.py
#!/usr/bin/env python3
....
....
I made the script an executable file.
chmod +x notify-lo.py
I added my script call to... | [
"These variables that are available to the shell script are called environment variables and are separate from Python variables. To get environment variables in python, you need to use the os.environ dictionary. You can do it like this:\nimport os\n\n\npam_type = os.environ['PAM_TYPE']\nprint(pam_type)\n\npam_servi... | [
2
] | [] | [] | [
"linux",
"python",
"shell"
] | stackoverflow_0074668478_linux_python_shell.txt |
Q:
Add a reaction to a message in with interaction
Discord.py 2.0
I cant add reaction in interaction message
@bot.tree.command()
@app_commands.describe(question="Give a title")
async def poll(interaction: discord.Interaction, question: str):
emb = discord.Embed(title=f":bar_chart: {question}\n",
... | Add a reaction to a message in with interaction | Discord.py 2.0
I cant add reaction in interaction message
@bot.tree.command()
@app_commands.describe(question="Give a title")
async def poll(interaction: discord.Interaction, question: str):
emb = discord.Embed(title=f":bar_chart: {question}\n",
type="rich")
message = await interaction.... | [
"I think it is:\nawait message.add_reaction(emoji)\n\n"
] | [
0
] | [] | [] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0074668456_discord_discord.py_python.txt |
Q:
DevOps: Building a production server
I'm completely new to devops and I'm quickly becoming overwhelmed with all the options.
I write python web applications as a solo developer, on my local machine. I have a "staging" server on DigitalOcean, I have multiple websites under different subdomains (eg. myapp.staging.my... | DevOps: Building a production server | I'm completely new to devops and I'm quickly becoming overwhelmed with all the options.
I write python web applications as a solo developer, on my local machine. I have a "staging" server on DigitalOcean, I have multiple websites under different subdomains (eg. myapp.staging.mywebsite.dev). I use git on my local machin... | [
"In our systems, we handle this scenario with a dedicated publish branch.\nThe GitHub action workflow for publishing starts like this:\nname: Publish\n\non:\n push:\n branches: [publish]\n\nso it's only triggered by a push to publish and it deploys to the gh-pages branch in our case.\nAll the draft work and the... | [
0
] | [] | [] | [
"digital_ocean",
"git",
"python"
] | stackoverflow_0074667043_digital_ocean_git_python.txt |
Q:
Dict to DataFrame: Value instead of list in DataFrame
How when i convert a dictionary to a dataframe do i stop each value being within a list.
i tried to converting with the pandas from_dict
A:
You can use orient='records'.
all_kpi.to_dict(orient='records')
Check out the pandas documentation for different orien... | Dict to DataFrame: Value instead of list in DataFrame |
How when i convert a dictionary to a dataframe do i stop each value being within a list.
i tried to converting with the pandas from_dict
| [
"You can use orient='records'.\nall_kpi.to_dict(orient='records')\n\nCheck out the pandas documentation for different orientation.\n"
] | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074668474_dataframe_pandas_python.txt |
Q:
Fail to overwrite a 2D numpy.ndarray in a loop
I found my program failed to overwrite an np.ndarray (the X variable) in the for loop by assignment statement like "X[i] = another np.ndarray with matched shape". I have no idea how this could happen...
Codes:
import numpy as np
def qr_tridiagonal(T: np.ndarray):
... | Fail to overwrite a 2D numpy.ndarray in a loop | I found my program failed to overwrite an np.ndarray (the X variable) in the for loop by assignment statement like "X[i] = another np.ndarray with matched shape". I have no idea how this could happen...
Codes:
import numpy as np
def qr_tridiagonal(T: np.ndarray):
m, n = T.shape
X = T.copy()
Qt = np.identity... | [
"Many thanks to @hpaulj\nIt turns out to be a problem of datatype. The program is ok but the input datatype is int, which results in intermediate trancation errors.\nA lesson learned: be aware of the dtype of np.ndarray!\n"
] | [
0
] | [] | [] | [
"multidimensional_array",
"numpy",
"python"
] | stackoverflow_0074668253_multidimensional_array_numpy_python.txt |
Q:
End conversation in chatbot
def send():
send = "You: " + e.get()
txt.insert(END, "\n" + send)
user = e.get().lower()
if (user == "hello" or user == "hi" or user == "hey" or user == "oi" or user == "halo"):
txt.insert(END, "\n" + "Rob: Hi there, how can I help you? ... | End conversation in chatbot | def send():
send = "You: " + e.get()
txt.insert(END, "\n" + send)
user = e.get().lower()
if (user == "hello" or user == "hi" or user == "hey" or user == "oi" or user == "halo"):
txt.insert(END, "\n" + "Rob: Hi there, how can I help you? \n 0.Contact seller directly \n 1... | [
"If you want a method to end in python you can just use return. In your ** ** case just type return under the if statement and it will ends. And in your ** case you just print goodbye or so and then use return.\n"
] | [
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074668415_python_tkinter.txt |
Q:
django rest framework translation does not work for me
I tried django rest framework internationalization.
doc drf internationalization
From official drf documentation a set this code in settings.py
from django.utils.translation import gettext_lazy as _
MIDDLEWARE = [
...
'django.middleware.locale.LocaleM... | django rest framework translation does not work for me | I tried django rest framework internationalization.
doc drf internationalization
From official drf documentation a set this code in settings.py
from django.utils.translation import gettext_lazy as _
MIDDLEWARE = [
...
'django.middleware.locale.LocaleMiddleware'
]
LANGUAGE_CODE = "it"
LANGUAGES = (
('en',... | [
"Looks like you added LocaleMiddleware to the end of middlewares list. But order is matter here. From the docs:\n\nBecause middleware order matters, follow these guidelines:\nMake sure it’s one of the first middleware installed.\nIt should come after SessionMiddleware, because LocaleMiddleware makes use of session ... | [
0
] | [] | [] | [
"django",
"django_rest_framework",
"internationalization",
"python"
] | stackoverflow_0074668527_django_django_rest_framework_internationalization_python.txt |
Q:
Applying Riemann–Liouville derivative to Lorenz 3D equation
I am using a module in python differint to solve the system of Lorenz 3D equation. After running my 3D system over differint ==> Riemann-Liouville operator for alpha value 1 the original equation and Riemann-Liouville results are not same . The code is me... | Applying Riemann–Liouville derivative to Lorenz 3D equation | I am using a module in python differint to solve the system of Lorenz 3D equation. After running my 3D system over differint ==> Riemann-Liouville operator for alpha value 1 the original equation and Riemann-Liouville results are not same . The code is mentioned below
from scipy.integrate import odeint
import numpy as ... | [
"The call to DF.RL requires a function of the differential equation, however, you used the solution to a differential equation - state (output of odeint call). From the package site https://pypi.org/project/differint/\ndef f(x):\n return x**0.5\n\nDF = df.RL(0.5, f)\nprint(DF)\n\nCan you try DF = df.RL(1, Lorenz,... | [
0
] | [] | [] | [
"derivative",
"differential_equations",
"python",
"python_3.x"
] | stackoverflow_0070625237_derivative_differential_equations_python_python_3.x.txt |
Q:
How to get JSON data from a post in grequests library (async-requests) python
so im trying to make an async-requests thingy and i cant get the json data from a post
import grequests as requests
headers = {SOME HEADERS}
data = {
SOME DATA...
}
r = requests.post(
"some url (NOT A REAL URL)", headers=headers, ... | How to get JSON data from a post in grequests library (async-requests) python | so im trying to make an async-requests thingy and i cant get the json data from a post
import grequests as requests
headers = {SOME HEADERS}
data = {
SOME DATA...
}
r = requests.post(
"some url (NOT A REAL URL)", headers=headers, data=data
)
var = r.json["SOME VALUE"]
NOTE: THE VALUES IN TH IS CODE AREN'T RE... | [
"r.json is a method. So you need to call it with parentheses first:\nvar = r.json() #type(var) -- > dictionary\nvar = var['SOME VALUE']\n\n#or (shorter)\nvar = r.json()['SOME VALUE']\n\n"
] | [
2
] | [] | [] | [
"grequests",
"python"
] | stackoverflow_0074664802_grequests_python.txt |
Q:
how to run selenium script from a bash file
I have a windows laptop in which i have written a selenium script written in python which creates a github repository. It works fine when a run the python file but it gives error when i try to run the script from a bash file. what should i do
my bash file:
python3 login.... | how to run selenium script from a bash file | I have a windows laptop in which i have written a selenium script written in python which creates a github repository. It works fine when a run the python file but it gives error when i try to run the script from a bash file. what should i do
my bash file:
python3 login.py
my python file which i am calling from bash:... | [
"When you run the python file in windows it uses Chrome installed in you Windows machine, but when you work in a bash terminal you do it on a Linux machine that runs as a virtual machine in you Windows.\nSo it is a separate machine and it cannot use Chrome from your Windows. It needs to have its own Chrome. Additio... | [
0
] | [] | [] | [
"automation",
"bash",
"python",
"selenium",
"selenium_chromedriver"
] | stackoverflow_0074666192_automation_bash_python_selenium_selenium_chromedriver.txt |
Q:
Incorrect Output to .csv file
I am getting an error when I try to export the output to a .csv file.
import csv
import random
header = ['Results']
file = open("populationModel5.csv", "w")
import random
startPopulation = 50
infantMortality = 25
agriculture = 5
disasterChance = 10
fertilityx = 18
fertilityy = 35
fo... | Incorrect Output to .csv file | I am getting an error when I try to export the output to a .csv file.
import csv
import random
header = ['Results']
file = open("populationModel5.csv", "w")
import random
startPopulation = 50
infantMortality = 25
agriculture = 5
disasterChance = 10
fertilityx = 18
fertilityy = 35
food = 0
peopleDictionary = []
cla... | [
"It looks like the error is happening because you're trying to write an object of the Person class to the CSV file, but the csv.writerow method expects a string or a list of strings as input.\nTo fix the error, you can modify your code to convert the Person object to a string before writing it to the CSV file. One ... | [
0
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0074667718_csv_python.txt |
Q:
Loop through outlook mails with python
I receive a daily mail with the subject “XYZ” containing a CSV file with some information. I also got this python code which goes into my outlook account, looks for the mail with the subject “XYZ” and extracts the attachment and finally extends a certain database with the new... | Loop through outlook mails with python | I receive a daily mail with the subject “XYZ” containing a CSV file with some information. I also got this python code which goes into my outlook account, looks for the mail with the subject “XYZ” and extracts the attachment and finally extends a certain database with the new information from the attachment. However, ... | [
"Firstly, there is no reason to loop though all messages in a folder - that would be extremely slow in folders with thousands of messages, especially if the cached mode is off.\nUse Items.Restrict or Items.Find/FindNext - let the store provider do the heavy lifting for you. You will be able to specify a restriction... | [
0
] | [] | [] | [
"email",
"office_automation",
"outlook",
"python",
"python_3.x"
] | stackoverflow_0074640759_email_office_automation_outlook_python_python_3.x.txt |
Q:
Why do I get a TypeError: unsupported operand type(s) for /: 'NoneType' and 'int'
Sorry for the short essay but I think context is important here. This is for a course but I have struggled the entire semester with grasping this and the teacher hasn't been much help to me personally.
I have a dataset with 30 categ... | Why do I get a TypeError: unsupported operand type(s) for /: 'NoneType' and 'int' | Sorry for the short essay but I think context is important here. This is for a course but I have struggled the entire semester with grasping this and the teacher hasn't been much help to me personally.
I have a dataset with 30 categories and 500 images in each category (google maps stills of specific terrain). The go... | [
"One issue with your code is that you are using the mean function on the desc array, which is not a valid input for the mean function because it is not a numerical array. The desc array is a 2D array of shape (N, 128), where N is the number of keypoints detected by the SIFT algorithm, and 128 is the length of the f... | [
1
] | [] | [] | [
"python",
"typeerror"
] | stackoverflow_0074668707_python_typeerror.txt |
Q:
Trying to write a user_defined function in python that multiplies a formula of constants and coeff by the median of dataframe columns?
I am trying to write a user defined function that takes median col values from a dataframe and places those values in a formula of constants and coefficients. I need the median col... | Trying to write a user_defined function in python that multiplies a formula of constants and coeff by the median of dataframe columns? | I am trying to write a user defined function that takes median col values from a dataframe and places those values in a formula of constants and coefficients. I need the median col values to be multiplied one by one by the constants and coefficients. Below is what I need the function to do.
median = data[['col 1','col ... | [
"Separate the values and plug them into the formula.\na,b,c = median.array\ncalc = [(-.5447 + .1712 * a + -.5447 + .9601 * b + -.5447 + .8474 * c)]\n\n\nAdd parenthesis around the terms to ensure order of operations.\n\nOr\nq = median.array * (.1712,.9601,.8474)\n# q = median.to_numpy() * (.1712,.9601,.8474)\nq ... | [
0
] | [] | [] | [
"array_formulas",
"for_loop",
"function",
"python"
] | stackoverflow_0074667892_array_formulas_for_loop_function_python.txt |
Q:
Optimizing Loop for memory
def getWhiteLightLength(n, m, lights):
lt_nv = []
ctd = 0
for clr, inic, fim in lights:
for num in range(inic, fim+1):
lt_nv.append(num)
c = Counter(lt_nv)
for ch, vl in c.items():
if vl == m:
ctd += 1
return(ctd)
I'm doing... | Optimizing Loop for memory | def getWhiteLightLength(n, m, lights):
lt_nv = []
ctd = 0
for clr, inic, fim in lights:
for num in range(inic, fim+1):
lt_nv.append(num)
c = Counter(lt_nv)
for ch, vl in c.items():
if vl == m:
ctd += 1
return(ctd)
I'm doing this HackerRank solution, it pa... | [
"One way to optimize the memory usage in this code is to avoid using a list to store the numbers of the lightbulbs that are turned on. Instead, you can use a Python set to store the numbers of the lightbulbs, which is more memory-efficient.\nHere is an updated version of the code that uses a set to store the number... | [
0
] | [] | [] | [
"loops",
"memory",
"memory_management",
"python"
] | stackoverflow_0074668660_loops_memory_memory_management_python.txt |
Q:
How to make Titlebar height fit new Title Font size increase in WxPython?
I've increased the custon AddPrivateFont pointsize to
self.label_font.SetPointSize(27)
of the Title bar of the sample_one.py script from this shared project:
https://wiki.wxpython.org/How%20to%20add%20a%20menu%20bar%20in%20the%20title%20bar... | How to make Titlebar height fit new Title Font size increase in WxPython? | I've increased the custon AddPrivateFont pointsize to
self.label_font.SetPointSize(27)
of the Title bar of the sample_one.py script from this shared project:
https://wiki.wxpython.org/How%20to%20add%20a%20menu%20bar%20in%20the%20title%20bar%20%28Phoenix%29
From the script of my previous question here:
https://web.arch... | [
"Thanks to @Rolf of Saxony headsup I figured it out!\nIt took the following 3 steps:\n1st Step:\nTop Title Text Display from:\nclass MyTitleBarPnl(wx.Panel):\n def CreateCtrls(self):\n self.titleBar.SetSize((w, 54))\n\n def OnResize(self, event):\n self.titleBar.SetSize((w, 54))\n\n\n2nd Step:\n... | [
1
] | [] | [] | [
"height",
"python",
"python_3.x",
"wxpython",
"wxwidgets"
] | stackoverflow_0074663982_height_python_python_3.x_wxpython_wxwidgets.txt |
Q:
Wagtail CMS(Django) - Display Inline Model Fields in Related Model
I have two custom models(not inheriting from Page) that are specific to the admin in a Wagtail CMS website. I can get this working in regular Django, but in Wagtail I can't get the inline model fields to appear. I get a key error. The code...
On mo... | Wagtail CMS(Django) - Display Inline Model Fields in Related Model | I have two custom models(not inheriting from Page) that are specific to the admin in a Wagtail CMS website. I can get this working in regular Django, but in Wagtail I can't get the inline model fields to appear. I get a key error. The code...
On model.py:
from django.db import models
from wagtail.admin.panels import (
... | [
"Try changing your Book model to inherit from ClusterableModel (which itself inherits from models.Model)\nfrom modelcluster.models import ClusterableModel\n\nclass Book(ClusterableModel):\n\n"
] | [
0
] | [] | [] | [
"django",
"django_models",
"python",
"wagtail",
"wagtail_admin"
] | stackoverflow_0074576306_django_django_models_python_wagtail_wagtail_admin.txt |
Q:
Override PageLinkHandler in wagtail
I have a site that has custom JS for handling link clicks, so that only part of the page reloads and audio playback isn't interrupted. This requires each link to have an onclick attribute. All of the hard coded links in the site have this, but links in page content created in th... | Override PageLinkHandler in wagtail | I have a site that has custom JS for handling link clicks, so that only part of the page reloads and audio playback isn't interrupted. This requires each link to have an onclick attribute. All of the hard coded links in the site have this, but links in page content created in the wagtail CMS don't. I know there's a cou... | [
"I think since you want to replace rather than extend some functionality, monkey patching is the correct approach.\n"
] | [
0
] | [] | [] | [
"python",
"wagtail"
] | stackoverflow_0074553383_python_wagtail.txt |
Q:
How can I fix this python simple recursion problem
I have a function that prints the first multiples of a number (n) starting with zero and stopping at num_multiples, but it keeps printing out one too many multiples. I'm hoping someone can explain what I'm doing wrong so I can understand recursion a bit more.
def ... | How can I fix this python simple recursion problem | I have a function that prints the first multiples of a number (n) starting with zero and stopping at num_multiples, but it keeps printing out one too many multiples. I'm hoping someone can explain what I'm doing wrong so I can understand recursion a bit more.
def print_first_multiples(n, num_multiples):
if num_... | [
"First, 0 is not a multiple of 5. The first multiple of 5 is 5 (5*1). The problem with your code is that you only stop when num_multiples is negative (less than 0). Instead, you want to stop when it is zero. Like this:\ndef print_first_multiples(n, num_multiples): \n if num_multiples == 0:\n return\n ... | [
1,
0,
0
] | [] | [] | [
"function",
"python",
"recursion"
] | stackoverflow_0074668764_function_python_recursion.txt |
Q:
How to enter file path?
How can I do to type something in the field of the image below?
I've tried without success:
from threading import local
import pandas as pd
import pyautogui
from time import sleep
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys ... | How to enter file path? | How can I do to type something in the field of the image below?
I've tried without success:
from threading import local
import pandas as pd
import pyautogui
from time import sleep
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.web... | [
"Selenium can't upload files using the Windows select file option, so you'll have to do something else - you might be able to use the send_keys function, i.e.:\nelem = driver.find_element(By.XPATH, \"//input[@type='file']\")\nelem.send_keys('C:\\\\Path\\\\To\\\\File')\n\nNote that this may not work, depending on th... | [
0,
0
] | [] | [] | [
"python",
"selenium"
] | stackoverflow_0074663050_python_selenium.txt |
Q:
\t didn't appear in the for loop
I'm practicing format fuction and when I use this code with \t in it, the first 9 output did not have any big space
`
import random
lst = [random.randint(1,100) for i in range(51)]
for index, val in enumerate(lst):
print(f'{index=}\t{val=}')
`
It works with \n but not \t, I do... | \t didn't appear in the for loop | I'm practicing format fuction and when I use this code with \t in it, the first 9 output did not have any big space
`
import random
lst = [random.randint(1,100) for i in range(51)]
for index, val in enumerate(lst):
print(f'{index=}\t{val=}')
`
It works with \n but not \t, I don't know why. Can anyone explain it?
| [
"It's just the terminal following tab(4 spaces in your case) convention. So add spaces before and after \\t.\n",
"All results has \\t\nRun your code with python yourcode.py | cat -T\nThis is the results. ^I is the tab.\n$ python yourcode.py | cat -T\nindex=0^Ival=14\nindex=1^Ival=46\nindex=2^Ival=87\nindex=3^Ival... | [
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074667173_python.txt |
Q:
Could not find a version that satisfies the requirement in python
I am trying to create virtual env with python2 in mac os from here.
While running pip install virtualenv command in terminal I am getting following error.
Could not find a version that satisfies the requirement virtualenv (from versions: )
No matchi... | Could not find a version that satisfies the requirement in python | I am trying to create virtual env with python2 in mac os from here.
While running pip install virtualenv command in terminal I am getting following error.
Could not find a version that satisfies the requirement virtualenv (from versions: )
No matching distribution found for virtualenv
| [
"If you are using python 3.x, Please try this commands\n\nsudo pip3 install --upgrade pip\nsudo pip3 install virtualenv\n\n",
"Run this command and try again\ncurl https://bootstrap.pypa.io/get-pip.py | python\n\nThe detailed description can be found in the link shared by Anupam in the comments.\n",
"Please try... | [
15,
14,
13,
1,
0,
0
] | [
"pip install --upgrade virtualenv\nThis solution works for me in Centos8\n",
"If you are using Windows, you have to run cmd as admin.\n"
] | [
-1,
-5
] | [
"pip",
"python",
"virtualenv"
] | stackoverflow_0049745105_pip_python_virtualenv.txt |
Q:
Pandas : Calculate the Mean of the value_counts() from row 0 to row n
I am struggling to create a function that could first calculate the number of occurrences for each string in a specific column (from row 0 to row n) and then reduce this to one single value by calculating the mean of the value_counts from the fi... | Pandas : Calculate the Mean of the value_counts() from row 0 to row n | I am struggling to create a function that could first calculate the number of occurrences for each string in a specific column (from row 0 to row n) and then reduce this to one single value by calculating the mean of the value_counts from the first row to the row n.
More precisely, what I would like to do is to create ... | [
"The logic is unclear, but assuming you want the expanding average count of values, use:\ndf['mean'] = pd.Series(pd.factorize(df['Name'])[0], index=df.index)\n .expanding()\n .apply(lambda s: s.value_counts().mean())\n )\n\nOutput:\n Date... | [
2
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074668825_pandas_python.txt |
Q:
h2o-pysparkling-2.4 and Glue Jobs with: {"error":"TypeError: 'JavaPackage' object is not callable","errorType":"EXECUTION_FAILURE"}
I am try to using pysparkling.ml.H2OMOJOModel for predict a spark dataframe using a MOJO model trained with h2o==3.32.0.2 in AWS Glue Jobs, how ever a got the error: TypeError: 'JavaP... | h2o-pysparkling-2.4 and Glue Jobs with: {"error":"TypeError: 'JavaPackage' object is not callable","errorType":"EXECUTION_FAILURE"} | I am try to using pysparkling.ml.H2OMOJOModel for predict a spark dataframe using a MOJO model trained with h2o==3.32.0.2 in AWS Glue Jobs, how ever a got the error: TypeError: 'JavaPackage' object is not callable.
I opened a ticket in AWS support and they confirmed that Glue environment is ok and the problem is probab... | [
"I could run successfully following the steps:\n\nDownloaded sparkling water distribution zip: http://h2o-release.s3.amazonaws.com/sparkling-water/spark-3.1/3.36.1.1-1-3.1/index.html\nDependent JARs path: s3://bucket_name/sparkling-water-assembly-scoring_2.12-3.36.1.1-1-3.1-all.jar\n--additional-python-modules, h2o... | [
0
] | [] | [] | [
"apache_spark",
"h2o",
"python",
"sparkling_water"
] | stackoverflow_0071928885_apache_spark_h2o_python_sparkling_water.txt |
Q:
How do I get the return value when using Python exec on the code object of a function?
For testing purposes I want to directly execute a function defined inside of another function.
I can get to the code object of the child function, through the code (func_code) of the parent function, but when I exec it, i get no... | How do I get the return value when using Python exec on the code object of a function? | For testing purposes I want to directly execute a function defined inside of another function.
I can get to the code object of the child function, through the code (func_code) of the parent function, but when I exec it, i get no return value.
Is there a way to get the return value from the exec'ed code?
| [
"Yes, you need to have the assignment within the exec statement:\n>>> def foo():\n... return 5\n...\n>>> exec(\"a = foo()\")\n>>> a\n5\n\nThis probably isn't relevant for your case since its being used in controlled testing, but be careful with using exec with user defined input. \n",
"A few years later, but ... | [
37,
29,
10,
4,
3,
3,
2,
0,
0
] | [
"if we need a function that is in a file in another directory, eg\nwe need the function1 in file my_py_file.py \nlocated in /home/.../another_directory\n\nwe can use the following code:\n\n\ndef cl_import_function(a_func,py_file,in_Dir): \n... import sys\n... sys.path.insert(0, in_Dir)\n... ax='from %s import %s'%(... | [
-1,
-1
] | [
"exec",
"function",
"python",
"return"
] | stackoverflow_0023917776_exec_function_python_return.txt |
Q:
Create Sample Noisy signal in C
I am trying to create a sample noisy signal that I will be filtering in C. I have written the code in python but will be deploying it to a microcotroller so I want to create it in C.
Here is the python code I am trying to replicate
# 1000 samples per second
sample_rate = 1000
# freq... | Create Sample Noisy signal in C | I am trying to create a sample noisy signal that I will be filtering in C. I have written the code in python but will be deploying it to a microcotroller so I want to create it in C.
Here is the python code I am trying to replicate
# 1000 samples per second
sample_rate = 1000
# frequency in Hz
center_freq = 20
# filter... | [
"\nhave written the code in python but will be deploying it to a\nmicrocotroller so I want to create it in C.\n\nThere exist MicroPython\n\nMicroPython is a lean and efficient implementation of the Python 3\nprogramming language that includes a small subset of the Python\nstandard library and is optimised to run on... | [
0,
0
] | [] | [] | [
"arduino",
"c",
"python"
] | stackoverflow_0074632566_arduino_c_python.txt |
Q:
Converting pandas DataFrame to datacube?
I have a DataFrame with four columns: X, Y, Z, and t. The values in the first three columns are discrete and represent a 3D index. The fourth column is a floating-point number. For example,
df = pd.DataFrame({'X':[1,2,3,2,3,1],
'Y':[1,1,2,2,3,3],
... | Converting pandas DataFrame to datacube? | I have a DataFrame with four columns: X, Y, Z, and t. The values in the first three columns are discrete and represent a 3D index. The fourth column is a floating-point number. For example,
df = pd.DataFrame({'X':[1,2,3,2,3,1],
'Y':[1,1,2,2,3,3],
'Z':[1,2,1,2,1,2],
... | [
"Here is one way to do it with product from Python standard library's itertool module:\nfrom itertools import product\n\nimport pandas as pd\n\n\naxis = [\"X\", \"Y\", \"Z\"]\n\ndf = (\n pd.concat(\n [\n df,\n pd.DataFrame(\n product(df[\"X\"].unique(), repeat=df[\"X\"... | [
1
] | [] | [] | [
"data_cube",
"dataframe",
"numpy",
"pandas",
"python"
] | stackoverflow_0074636925_data_cube_dataframe_numpy_pandas_python.txt |
Q:
How to print Docstring of python function from inside the function itself?
I want to print the docstring of a python function from inside the function itself.
for eg.
def my_function(self):
"""Doc string for my function."""
# print the Docstring here.
At the moment I am doing this directly after my_function h... | How to print Docstring of python function from inside the function itself? | I want to print the docstring of a python function from inside the function itself.
for eg.
def my_function(self):
"""Doc string for my function."""
# print the Docstring here.
At the moment I am doing this directly after my_function has been defined.
print my_function.__doc__
But would rather let the function do... | [
"def my_func():\n \"\"\"Docstring goes here.\"\"\"\n print my_func.__doc__\n\nThis will work as long as you don't change the object bound to the name my_func. \nnew_func_name = my_func\nmy_func = None\n\nnew_func_name()\n# doesn't print anything because my_func is None and None has no docstring\n\nSituations ... | [
89,
10,
6,
6,
2,
2,
1,
0
] | [
"inserting \nprint __doc__\njust after the class declaration,, before the def __init__, will print the doc string to the console every time you initiate an object with the class\n"
] | [
-1
] | [
"docstring",
"function",
"printing",
"python"
] | stackoverflow_0008822701_docstring_function_printing_python.txt |
Q:
How to split the data in a group of N lines and find intersection character
I have a dataset like below:
data="""vJrwpWtwJgWrhcsFMMfFFhFp
jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL
PmmdzqPrVvPwwTWBwg
wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn
ttgJtRGJQctTZtZT
CrZsJsPPZsGzwwsLwLmpwMDw"""
These are separate lines. Now, I want to group t... | How to split the data in a group of N lines and find intersection character | I have a dataset like below:
data="""vJrwpWtwJgWrhcsFMMfFFhFp
jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL
PmmdzqPrVvPwwTWBwg
wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn
ttgJtRGJQctTZtZT
CrZsJsPPZsGzwwsLwLmpwMDw"""
These are separate lines. Now, I want to group the data in a set of 3 rows and find the intersecting character in those lines. Fo... | [
"For the record: this was the Advent of Code 2022 Day 3 Part 2 challenge. I kept my data in a file called input.txt and just read line by line, but this solution can be applied to a string too.\nI turned converted every line into a set and used the & intersection operator. From there, I converted it to a list and r... | [
1,
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074668908_python_python_3.x.txt |
Q:
Finding the most frequent character in a string
I found this programming problem while looking at a job posting on SO. I thought it was pretty interesting and as a beginner Python programmer I attempted to tackle it. However I feel my solution is quite...messy...can anyone make any suggestions to optimize it or ma... | Finding the most frequent character in a string | I found this programming problem while looking at a job posting on SO. I thought it was pretty interesting and as a beginner Python programmer I attempted to tackle it. However I feel my solution is quite...messy...can anyone make any suggestions to optimize it or make it cleaner? I know it's pretty trivial, but I had ... | [
"There are many ways to do this shorter. For example, you can use the Counter class (in Python 2.7 or later):\nimport collections\ns = \"helloworld\"\nprint(collections.Counter(s).most_common(1)[0])\n\nIf you don't have that, you can do the tally manually (2.5 or later has defaultdict):\nd = collections.defaultdict... | [
36,
5,
2,
2,
2,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0
] | [
"#file:filename\n#quant:no of frequent words you want\n\ndef frequent_letters(file,quant):\n file = open(file)\n file = file.read()\n cnt = Counter\n op = cnt(file).most_common(quant)\n return op \n\n",
"# This code is to print all characters in a string which have highest frequency\n \ndef find(... | [
-1,
-1
] | [
"algorithm",
"optimization",
"python",
"time_complexity"
] | stackoverflow_0004131123_algorithm_optimization_python_time_complexity.txt |
Q:
Why is there an incorrect display of objects in the Pygame?
I'm creating a game on Pygame and faced with the problem that the objects are displayed incorrectly
I want the objects in a row but I wrote it diagonally
My game:
import pygame, controls
from gun import Gun
from pygame.sprite import Group
def run():
... | Why is there an incorrect display of objects in the Pygame? | I'm creating a game on Pygame and faced with the problem that the objects are displayed incorrectly
I want the objects in a row but I wrote it diagonally
My game:
import pygame, controls
from gun import Gun
from pygame.sprite import Group
def run():
pygame.init()
screen = pygame.display.set_mode((700, 600))
... | [
"The images are diagonal because you calculate the y-coordinate depending on the ino_number, so that the y-coordinate increases with increasing ino_number. The y-coordinate must be the same for all objects. Only the coordinated x must increase with the number ino_number:\ndef create_army(screen, inos):\n # [...]... | [
0
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0074668817_pygame_python.txt |
Q:
Clearing an animated plot in tkinter to reload animation
I have an arduino connected to a pressure sensor collecting data. I am able to connect to the sensor and plot the data with an animation via the code below in a tkinter window/frame. When I open the tkinter window, I click the graph button and the animation ... | Clearing an animated plot in tkinter to reload animation | I have an arduino connected to a pressure sensor collecting data. I am able to connect to the sensor and plot the data with an animation via the code below in a tkinter window/frame. When I open the tkinter window, I click the graph button and the animation loads as expected. I want to click the clear button to delete ... | [
"Well it took me 3 days and A LOT of searching, trial and error but ive been able to get the desired result. It may not be the most efficient but it's a start.\nIve created a new function to create the subplots setup() I call that initially when the program opens. Then in the clear() function I am able to forget th... | [
0
] | [] | [] | [
"arduino",
"matplotlib",
"python",
"tkinter"
] | stackoverflow_0074658736_arduino_matplotlib_python_tkinter.txt |
Q:
How to print "\'" in python
I would like to print in python print("\'/"),
expected output \'/
Thanks for helping me !
I just need to know how to print an antislash with a ' after thanks !
A:
You can use either
print("\\'/")
or
print(r"\'/")
The escape character in Python is \ and the option of r before the ... | How to print "\'" in python | I would like to print in python print("\'/"),
expected output \'/
Thanks for helping me !
I just need to know how to print an antislash with a ' after thanks !
| [
"You can use either\nprint(\"\\\\'/\") \n\nor \nprint(r\"\\'/\")\n\nThe escape character in Python is \\ and the option of r before the string represent the string as literals without the need of escape chars. \n",
"Is this what you're looking for?\nprint(\"\\\\\\'/\")\n",
">>> print(r\"\\'/\")\n\\'/\n\n"
] | [
2,
2,
2
] | [
"The Best way to do this is to Add a Front Slash() and then inverted commas.\nprint('a'')\na='That's a Sample Case'\nprint(a)\n"
] | [
-1
] | [
"python"
] | stackoverflow_0062311463_python.txt |
Q:
ValueError: could not broadcast input array from shape (200,200,3) into shape (200,200)
ValueError: could not broadcast input array from shape (200,200,3) into shape (200,200)
img_000= np.array(img_00)
A:
use
np.asarray(img_00)
your image needs 3 channels: (width, height,colorchannels)
A:
A small example that... | ValueError: could not broadcast input array from shape (200,200,3) into shape (200,200) | ValueError: could not broadcast input array from shape (200,200,3) into shape (200,200)
img_000= np.array(img_00)
| [
"use\nnp.asarray(img_00)\n\nyour image needs 3 channels: (width, height,colorchannels)\n",
"A small example that displays a similar error\nIn [72]: alist = [np.ones((3,3,3)), np.zeros((3,3))]\n\nIn [73]: np.array(alist)\nC:\\Users\\paul\\AppData\\Local\\Temp\\ipykernel_7196\\2629805649.py:1: VisibleDeprecationWar... | [
1,
0
] | [] | [] | [
"numpy",
"python",
"tensorflow"
] | stackoverflow_0074667144_numpy_python_tensorflow.txt |
Q:
Load very large pickle file?
so for my bachelors thesis I am supposed to train a classifier on a very large dataset. I'm gonna get access to my Uni's deep learning cluster at some point, but for now I was told to do a bit of data exploration on the data on my own device. I was told to only use 10% of the data. Thi... | Load very large pickle file? | so for my bachelors thesis I am supposed to train a classifier on a very large dataset. I'm gonna get access to my Uni's deep learning cluster at some point, but for now I was told to do a bit of data exploration on the data on my own device. I was told to only use 10% of the data. Thing is the pickle file is absolutel... | [
"Instead of sample your file I would recommend you working with the entire file using cloud competing.\nYou can create a free account in AWS or AZURE using those links\nhttps://aws.amazon.com/pt/free \nhttps://azure.microsoft.com/pt-br/free/\nI would suggest you use AZURE because you will receive 200 dollars and wi... | [
0
] | [] | [] | [
"deserialization",
"machine_learning",
"pickle",
"python"
] | stackoverflow_0074668920_deserialization_machine_learning_pickle_python.txt |
Q:
Is it possible to use Python as scripts for Linux PAM?
I want to use a python script to call it in the pam_exec module.
The first answer in this question says that I can't use a python script and a PAM module together.
First off - you cannot use python code as a PAM module, it has to be compiled code that satisfi... | Is it possible to use Python as scripts for Linux PAM? | I want to use a python script to call it in the pam_exec module.
The first answer in this question says that I can't use a python script and a PAM module together.
First off - you cannot use python code as a PAM module, it has to be compiled code that satisfies certain interface requirements. See here for more info.
... | [
"The difference between the two answers you cite is because of how the script is used.\nIn the negative answer, the python script was listed directly as the PAM module. This will not work. PAM modules need to be shared objects, e.g. binary compiled code. The are directly linked into the running process that is u... | [
1,
0
] | [] | [] | [
"linux",
"python"
] | stackoverflow_0074668675_linux_python.txt |
Q:
How to change text color and font in px.timeline
Not really a specific code issue, it's just I can't find how to edit text size and font in a px.timeline, neither for go.bar.
import pandas as pd
import plotly.express as px
import plotly.subplots as sp
df1 = pd.DataFrame([
dict(unit='MVT',Task="Job A", Start='2009... | How to change text color and font in px.timeline | Not really a specific code issue, it's just I can't find how to edit text size and font in a px.timeline, neither for go.bar.
import pandas as pd
import plotly.express as px
import plotly.subplots as sp
df1 = pd.DataFrame([
dict(unit='MVT',Task="Job A", Start='2009-01-01', Finish='2009-02-28'),
dict(unit='MVT',Task="J... | [
"You can style the text inside each bar through insidetextfont:\nfig1.update_traces(insidetextfont=dict(color='white', size=16,family='Times New Roman'))\n\n\n"
] | [
0
] | [] | [] | [
"plotly",
"python"
] | stackoverflow_0074668596_plotly_python.txt |
Q:
I get AttributeError: 'WebDriver' object has no attribute 'find_element_by_class_name'
(The below code is not mine) Ive been trying to get this ixl math bot to work but everytime i run it i get
AttributeError: 'WebDriver' object has no attribute 'find_element_by_class_name'
Im using selenium 4.3 and the latest pyt... | I get AttributeError: 'WebDriver' object has no attribute 'find_element_by_class_name' | (The below code is not mine) Ive been trying to get this ixl math bot to work but everytime i run it i get
AttributeError: 'WebDriver' object has no attribute 'find_element_by_class_name'
Im using selenium 4.3 and the latest python version, if no one can help then at least an explanation of what this error means and ho... | [
"All the find_element_by_* and find_elements_by_* methods are deprecated in current Selenium versions. You need to use driver.find_element(By.CLASS_NAME, \" \"), driver.find_element(By.XPATH, \" \") etc. methods.\n"
] | [
0
] | [] | [] | [
"attributeerror",
"automation",
"bots",
"python",
"selenium"
] | stackoverflow_0074669026_attributeerror_automation_bots_python_selenium.txt |
Q:
Why does my While loop omit the last input and adding a 0 in the list?
I want to build a program that takes the amount of rainfall each day for 7 days and then output the total and average rainfall for those days.
Initially, I've created a while loop to take the input:
rainfall = 0
rain = []
counter = 1
while cou... | Why does my While loop omit the last input and adding a 0 in the list? | I want to build a program that takes the amount of rainfall each day for 7 days and then output the total and average rainfall for those days.
Initially, I've created a while loop to take the input:
rainfall = 0
rain = []
counter = 1
while counter < 8:
rain.append(rainfall)
rainfall = float(input("Enter the ra... | [
"In the first line of your while:\nrain.append(rainfall)\n\nat this point since you didn't reassign it rainfall is still the value that you set it to earlier:\nrainfall = 0\n\nand your while runs for the numbers\n1, 2, 3, 4, 5, 6, 7\n\nsince those are the integers < 8\n",
"This is the correct version for your aim... | [
1,
1
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074668944_list_python.txt |
Q:
How to find the index of the last odd number in a list, without reversing the list?
Have this so far, and essentially want to get there is something wrong with the position of last_odd as the compiler says the pop index is out of range?
def remove_last_odd(numbers):
has_odd = False
last_odd = 0
for nu... | How to find the index of the last odd number in a list, without reversing the list? | Have this so far, and essentially want to get there is something wrong with the position of last_odd as the compiler says the pop index is out of range?
def remove_last_odd(numbers):
has_odd = False
last_odd = 0
for num in range(len(numbers)):
if numbers[num] % 2 == 1:
has_odd = True
... | [
"As @DeepSpace said, list.pop will\n\nRemove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list.\n\nSo basically, the solution to your problem would be to replace last_odd = numbers[num] with last_odd = num.\n",
"list.pop() re... | [
0,
0,
0,
0,
0
] | [] | [] | [
"iteration",
"python"
] | stackoverflow_0074668354_iteration_python.txt |
Q:
Plotting images side by side using matplotlib
I was wondering how I am able to plot images side by side using matplotlib for example something like this:
The closest I got is this:
This was produced by using this code:
f, axarr = plt.subplots(2,2)
axarr[0,0] = plt.imshow(image_datas[0])
axarr[0,1] = plt.imshow(i... | Plotting images side by side using matplotlib | I was wondering how I am able to plot images side by side using matplotlib for example something like this:
The closest I got is this:
This was produced by using this code:
f, axarr = plt.subplots(2,2)
axarr[0,0] = plt.imshow(image_datas[0])
axarr[0,1] = plt.imshow(image_datas[1])
axarr[1,0] = plt.imshow(image_datas[... | [
"The problem you face is that you try to assign the return of imshow (which is an matplotlib.image.AxesImage to an existing axes object. \nThe correct way of plotting image data to the different axes in axarr would be\nf, axarr = plt.subplots(2,2)\naxarr[0,0].imshow(image_datas[0])\naxarr[0,1].imshow(image_datas[1]... | [
148,
56,
32,
26,
13,
8,
4,
0
] | [
"Plotting images present in a dataset\nHere rand gives a random index value which is used to select a random image present in the dataset and labels has the integer representation for every image type and labels_dict is a dictionary holding key val information\nfig,ax = plt.subplots(5,5,figsize = (15,15))\nax = ax.... | [
-2
] | [
"matplotlib",
"python"
] | stackoverflow_0041793931_matplotlib_python.txt |
Q:
Can not use numba in the class
I recently want to use @njit(parallel=True) in package numba to speed up my nbodysimulation code, but when I separate the original function out of the class, my code can not work anymore. How to fix this problem?
The following block is the original code to calculate acceleration.
def... | Can not use numba in the class | I recently want to use @njit(parallel=True) in package numba to speed up my nbodysimulation code, but when I separate the original function out of the class, my code can not work anymore. How to fix this problem?
The following block is the original code to calculate acceleration.
def _calculate_acceleration(self, mass,... | [
"It seems like you want to use the numba.njit decorator to speed up your code by making it run in parallel. To use numba.njit with parallel execution, you will need to specify the parallel=True keyword argument when you decorate your function. Additionally, you will need to use the prange function instead of the bu... | [
0
] | [] | [] | [
"jit",
"jupyter_notebook",
"numba",
"python"
] | stackoverflow_0074668846_jit_jupyter_notebook_numba_python.txt |
Q:
How to put a limit for the player in the game
I have this game, there could be unlimited amount of players, I want to make it minimum 2 and maximum 5.
from dataclasses import dataclass
@dataclass
class Player:
firstname: str
lastname: str
coins: int
slot: int
def full_info(self) -> str:
... | How to put a limit for the player in the game | I have this game, there could be unlimited amount of players, I want to make it minimum 2 and maximum 5.
from dataclasses import dataclass
@dataclass
class Player:
firstname: str
lastname: str
coins: int
slot: int
def full_info(self) -> str:
return f"{self.firstname} {self.lastname} {self.c... | [
"You can write something like this:\nnumber_of_players = int(input(\"Number of players:\"))\nwhile not (2 <= number_of_players <= 5):\n print(\"please chose a number between 2 and 5\")\n number_of_players = int(input(\"Number of players: \"))\n\nGood luck :)\n"
] | [
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074669041_list_python.txt |
Q:
What is this connection error for roberta model?
I want to run a roberta model, But it has a connection error...
Here is the error: Connection error, and we cannot find the requested files in the cached path. Please try again or make sure your Internet connection is on.
from transformers import AutoTokenizer
from ... | What is this connection error for roberta model? | I want to run a roberta model, But it has a connection error...
Here is the error: Connection error, and we cannot find the requested files in the cached path. Please try again or make sure your Internet connection is on.
from transformers import AutoTokenizer
from transformers import AutoModelForSequenceClassification... | [
"I wonder whether or not you have resolved this. But the problem is that your Kaggle notebook is not connected to the internet. You can try opening the setting on the right of your screen, and make sure your internet is toggled on. This may require you to verify your phone number. Good luck\n"
] | [
0
] | [] | [] | [
"data_science",
"python"
] | stackoverflow_0074532943_data_science_python.txt |
Q:
Error with tatsu : does not recognize the right grammar pattern
I am getting started with tatsu and I am trying to implement a grammar for the miniML language.
Once my grammar successfully parsed, I tried to parse some little expressions to check that it was working ; however I discovered Tatsu was unable to recog... | Error with tatsu : does not recognize the right grammar pattern | I am getting started with tatsu and I am trying to implement a grammar for the miniML language.
Once my grammar successfully parsed, I tried to parse some little expressions to check that it was working ; however I discovered Tatsu was unable to recognize some of the expected patterns.
Here is the code :
`
grammar="""
... | [
"\nIt seems the failure of assign comes from a conflict with the varname rule; to solve it, simply place |assign BEFORE |variable in your expression rule.\n\nA now obsolete workaround, that I'll leave anyway:\n# I added a negative lookahead for '=' so it will not conflict with the assign rule\nvarname = /[a-z]+/!'=... | [
0
] | [] | [] | [
"grammar",
"parsing",
"python",
"tatsu"
] | stackoverflow_0074668215_grammar_parsing_python_tatsu.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.