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:
Django 2 - How to register a user using email confirmation and CBVs?
This question specifically aims for a Django 2.0 answer as the registration module isn't available (yet) for it.
More, this might seem to broad, but I often found myself in situations where I can't use any 3rd party module because ... oh well..po... | Django 2 - How to register a user using email confirmation and CBVs? | This question specifically aims for a Django 2.0 answer as the registration module isn't available (yet) for it.
More, this might seem to broad, but I often found myself in situations where I can't use any 3rd party module because ... oh well..policies. I'm sure many did. And I know that looking and putting together in... | [
"The User Model\nFirst, you will need to create a custom User model and a custom UserManager to remove the username field and use email instead.\nIn models.py the UserManager should look like this:\nfrom django.contrib.auth.models import BaseUserManager\n\n\nclass MyUserManager(BaseUserManager):\n \"\"\"\n A ... | [
47,
2,
0,
0
] | [] | [] | [
"authentication",
"django",
"python"
] | stackoverflow_0050298114_authentication_django_python.txt |
Q:
Bot won't detect message using on_message in discord.py
Starting on line 35, the bot is supposed to detect the message and print it in the console, but it does not print the message in the console.
I've tried looking for a solution but every solution I try does not work. Am I doing something wrong?
import discord
... | Bot won't detect message using on_message in discord.py | Starting on line 35, the bot is supposed to detect the message and print it in the console, but it does not print the message in the console.
I've tried looking for a solution but every solution I try does not work. Am I doing something wrong?
import discord
from discord import channel
from discord import message
from ... | [
"Why are you using multiple on_message events? Use one:\n@client.event\nasync def on_message(message):\n print(message.content)\n\n ctx = await client.get_context(message)\n if ctx.valid:\n await client.invoke(ctx)\n\nAnd also remember that you have to enable intents.messages.\n",
"It didn't work ... | [
4,
1,
0,
0
] | [] | [] | [
"discord.py",
"python"
] | stackoverflow_0070424324_discord.py_python.txt |
Q:
Using typeguard decorator: @typechecked in Python, whilst evading circular imports?
Context
To prevent circular imports in Python when using type-hints, one can use the following construct:
# controllers.py
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from models impor... | Using typeguard decorator: @typechecked in Python, whilst evading circular imports? | Context
To prevent circular imports in Python when using type-hints, one can use the following construct:
# controllers.py
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from models import Book
class BookController:
def __init__(self, book: "Book") -> None:
self... | [
"Your problem is that by using the denamespacing import form (from x import y) the contents of an imported module can't be resolved lazily, so one side or the other will require a name before the other module has finished importing (and therefore before it has defined the name).\nThe typical solution here is to use... | [
4,
0
] | [] | [] | [
"circular_dependency",
"python",
"type_hinting",
"typeguards"
] | stackoverflow_0074308059_circular_dependency_python_type_hinting_typeguards.txt |
Q:
Convert incorrect excel date from integer to date but in pandas
there is an incorrect date - 44288.
In excel i can change format and get 02.04.2021, but how to get this result in pandas?
A:
This has been done similarly in: Convert Excel style date with pandas
However, with this you just add abs() to turn the neg... | Convert incorrect excel date from integer to date but in pandas | there is an incorrect date - 44288.
In excel i can change format and get 02.04.2021, but how to get this result in pandas?
| [
"This has been done similarly in: Convert Excel style date with pandas\nHowever, with this you just add abs() to turn the negative integer into a positive, if you want it done for all in a column:\nimport datetime\nimport pandas as pd\n\ndf = pd.DataFrame({'date':[-44288,-44289]})\n\ndf['date'] = pd.TimedeltaIndex(... | [
1
] | [] | [] | [
"date",
"pandas",
"python"
] | stackoverflow_0074375872_date_pandas_python.txt |
Q:
selenium.common.exceptions.SessionNotCreatedException: Message: Failed to start browser /snap/firefox/current/firefox.launcher
I am trying to open Firefox with this simple program in python, I am using the latest version of Ubuntu.
from selenium import webdriver
brow = webdriver.Firefox()
But I am getting the er... | selenium.common.exceptions.SessionNotCreatedException: Message: Failed to start browser /snap/firefox/current/firefox.launcher | I am trying to open Firefox with this simple program in python, I am using the latest version of Ubuntu.
from selenium import webdriver
brow = webdriver.Firefox()
But I am getting the error message,
"selenium.common.exceptions.SessionNotCreatedException: Message: Failed to start browser /snap/firefox/current/firefox.... | [
"Surely you should take a good look at the paths you enter, however, i recommend a generic approach.\nYou can use a webdriver-manager that takes care of any problems in this respect automatically and in any supported operating system\nfrom selenium import webdriver\nfrom webdriver_manager.firefox import GeckoDriver... | [
1
] | [] | [] | [
"geckodriver",
"linux",
"python",
"selenium"
] | stackoverflow_0074376177_geckodriver_linux_python_selenium.txt |
Q:
How to solve an error that appears in conda proxy configuration?
I am trying to install Rdkit on ubuntu and I have problem with the conda configuration.
I have reinstalled anaconda3 and python3 versions on my desktop and installed it from the beginning.
When I run the command: conda create -c rdkit -n my-rdkit-en... | How to solve an error that appears in conda proxy configuration? | I am trying to install Rdkit on ubuntu and I have problem with the conda configuration.
I have reinstalled anaconda3 and python3 versions on my desktop and installed it from the beginning.
When I run the command: conda create -c rdkit -n my-rdkit-env rdkit
The error I am experiencing is this one:
Collecting package me... | [
"I had a similar error on my work machine. I'm on Windows 10.\nFor me, the fix was to add *.anaconda.org to my list of proxy exceptions under Control Panel > Internet Options > Connections > LAN Settings > Advanced\nHope this helps.\n",
"Hi I had the same error.\nIn my case was that in environment variables from ... | [
5,
4,
3,
2,
1,
1,
1,
1,
0,
0,
0,
0
] | [] | [] | [
"conda",
"python",
"rdkit"
] | stackoverflow_0058797984_conda_python_rdkit.txt |
Q:
Converting grayscale images to binary and storing in a numpy array in python
I am working on a binary image segmentation problem using Tensorflow Keras. The masks are in grayscale and images are in RGB. I need to convert the grayscale masks to binary and store them in a Numpy array. The following is the code:
fro... | Converting grayscale images to binary and storing in a numpy array in python | I am working on a binary image segmentation problem using Tensorflow Keras. The masks are in grayscale and images are in RGB. I need to convert the grayscale masks to binary and store them in a Numpy array. The following is the code:
from tensorflow.keras.preprocessing.image import load_img,ImageDataGenerator
from... | [
"Found the solution to my problem. I am setting a global threshold after empirical evaluations and then thresholding the images to binarize them. Edits made to the posted code.\n",
"You can easily convert a numeric array inot a boolean one using comparison operation in numpy (pandas ...).\narray = np.random.rando... | [
0,
0
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0074375192_arrays_numpy_python.txt |
Q:
Regex captures more digits that I defined. Mistake explanation
I am trying to capture all numbers with a following format:
Digits with length from 1-5(and not more!) but not starting with 0
Next goes either . or ,
Next goes digits of the length 2-3
Optionally goes ,
Optionally goes digits
I have the following re... | Regex captures more digits that I defined. Mistake explanation | I am trying to capture all numbers with a following format:
Digits with length from 1-5(and not more!) but not starting with 0
Next goes either . or ,
Next goes digits of the length 2-3
Optionally goes ,
Optionally goes digits
I have the following regex: (?<!\d)[\d]{1,5}(?!\d)[.,][\d]{2,3}[,]*[\d]*
and it should matc... | [
"You can exclude matching digits and comma's to the left and right and optionally match a comma followed by 1 or more digits.\nNote that the [\\d]* by itself does not have to be between square brackets.\n(?<![\\d.])\\d{1,5}[.,]\\d{2,3}(?:,\\d+)?(?![\\d.])\n\nExplanation\n\n(?<![\\d.]) Assert not either a digit or .... | [
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074375730_python_regex.txt |
Q:
airflow dynamic task returns list instead of dictionary
Please refer my code below.
While recon_rule_setup task is running, each time it is getting Dictionary (recon_conf) as input from previous read_recon_config task.
However, while recon_rule_exec is running, it is getting List as input (recon_rule) from previou... | airflow dynamic task returns list instead of dictionary | Please refer my code below.
While recon_rule_setup task is running, each time it is getting Dictionary (recon_conf) as input from previous read_recon_config task.
However, while recon_rule_exec is running, it is getting List as input (recon_rule) from previous task.
My expectation was, recon_rule_setup should run 2 tim... | [
"Since you are trying to return the dictionary as a list that’s why it is returning the dictionary inside a list. For your requirement, you can try the below code which is returning a dictionary.\nCode:\nfrom datetime import datetime\nfrom airflow.models import DAG, XCom\nfrom airflow.utils.dates import days_ago\nf... | [
1
] | [] | [] | [
"airflow",
"airflow_2.x",
"google_cloud_composer",
"google_cloud_platform",
"python"
] | stackoverflow_0074300521_airflow_airflow_2.x_google_cloud_composer_google_cloud_platform_python.txt |
Q:
How to sum input numbers using while loop? (python)
Beginner question, I have to create a program that asks user to input numbers (input 0 to break), then calculates the amount of numbers in total and then the sum of the input numbers.
How do i print the sum of user-input numbers using while loop? This is what I g... | How to sum input numbers using while loop? (python) | Beginner question, I have to create a program that asks user to input numbers (input 0 to break), then calculates the amount of numbers in total and then the sum of the input numbers.
How do i print the sum of user-input numbers using while loop? This is what I got so far
amount = 0
while True:
amount += 1
numb... | [
"You are close. Same as you have amount = 0, create a variable total = 0. And, inside the loop, add total += number, after the line where you are reading it.\n",
"You can simply use the same technique that you used for the number of inputs:\namount = 0\nnumber = 0\nwhile True:\n amount += 1\n number += int(... | [
0,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0071827868_python.txt |
Q:
How to delete multiple rows of a .csv file in jupyter notebook using Python?
Hi so I am very new to coding!
I have a huge .csv file (over 1 million rows) and need to delete all data that is before 1st January 2010 at 00:00.
Have tried googling how to do this but can't seem to find anything that doesn't use row num... | How to delete multiple rows of a .csv file in jupyter notebook using Python? | Hi so I am very new to coding!
I have a huge .csv file (over 1 million rows) and need to delete all data that is before 1st January 2010 at 00:00.
Have tried googling how to do this but can't seem to find anything that doesn't use row numbers, rather than deleting by the date/time.
I tried:
df [(df['Date Time'].dt.year... | [
"It looks like your file is semi-colon separated rather than comma seperated and so has read all columns as a single heading.\nTry df = pd.read_csv(file_path, sep=';')\nSimilar discussion here:\nHow to read a file with a semi colon separator in pandas\n"
] | [
0
] | [] | [] | [
"csv",
"delete_row",
"jupyter_notebook",
"python"
] | stackoverflow_0074348881_csv_delete_row_jupyter_notebook_python.txt |
Q:
How to make a calculation based on a value and multiple columns in pandas?
I am trying to create a column, that should do a calculation per product, based on multiple columns.
Logic for the calculation column:
Calculations should be done per product
Use quantity as default
IF promo[Y/N] = 1, then take previous we... | How to make a calculation based on a value and multiple columns in pandas? | I am trying to create a column, that should do a calculation per product, based on multiple columns.
Logic for the calculation column:
Calculations should be done per product
Use quantity as default
IF promo[Y/N] = 1, then take previous weeks quantity * season perc. change.
Except when the promo is on the first week o... | [
"groupby() is a good approach in my opinion.\nLet's build our dataset first :\ncsvfile = StringIO(\n \"\"\"week\\tproduct\\tpromo\\tquantity\\tseason\n 1\\tA\\t0\\t100\\t6 \n 2\\tA\\t0\\t100\\t10\n 3\\tA\\t1\\tnan\\t-10\n 4\\tA\\t1\\tnan\\t20\n 5\\tA\\t0\\t80\\t4 \n ... | [
2,
2
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074375476_pandas_python.txt |
Q:
ImportError: cannot import name 'find_objects' why?
*when import find_objects from moviepy.video.tools.segmenting
i get in the result *
ImportError: cannot import name 'find_objects' from 'moviepy.video.tools.segmenting'
when follow documentation
first i check if method is found by dir()
get findObjects in the re... | ImportError: cannot import name 'find_objects' why? | *when import find_objects from moviepy.video.tools.segmenting
i get in the result *
ImportError: cannot import name 'find_objects' from 'moviepy.video.tools.segmenting'
when follow documentation
first i check if method is found by dir()
get findObjects in the result
my problem solved
ImportError: cannot import name '... | [
"my problem solved ImportError: cannot import name 'find_objects' from moviepy.video.tools.segmenting import findObjects\nthen replace find_objects by findObjects\n"
] | [
0
] | [] | [] | [
"importerror",
"modulenotfounderror",
"moviepy",
"python"
] | stackoverflow_0074376530_importerror_modulenotfounderror_moviepy_python.txt |
Q:
What is the process after Azure AD B2C signup/login is implemented in a web framework?
I am now able to register/login a user via Azure AD B2C using the msal library following the sample code sign-in-b2c for the Django framework. But what is the process now to make use of all of this in the application itself?
Do ... | What is the process after Azure AD B2C signup/login is implemented in a web framework? | I am now able to register/login a user via Azure AD B2C using the msal library following the sample code sign-in-b2c for the Django framework. But what is the process now to make use of all of this in the application itself?
Do I need to create a user model saving the users sub or ID from Azure? Is it possible to make ... | [
"It depends a lot on the application you are making. Ideally your application should store as little user information as realistic, instead getting that information from the token fresh each time. This limits conflicts that may arise where the user is updated in B2C, but not in your application or vice versa, and l... | [
1
] | [] | [] | [
"azure_ad_b2c",
"msal",
"python"
] | stackoverflow_0074373995_azure_ad_b2c_msal_python.txt |
Q:
How to depict small charges on a spherical object using vpython library?
I am working on a project related to charge distribution on the sphere and I decided to simulate the problem using vpython and Coulomb's law. I ran into an issue when I created a sphere because I am trying to evenly place out like 1000 points... | How to depict small charges on a spherical object using vpython library? | I am working on a project related to charge distribution on the sphere and I decided to simulate the problem using vpython and Coulomb's law. I ran into an issue when I created a sphere because I am trying to evenly place out like 1000 points (charges) on the sphere and I can't seem to succeed, I have tried several way... | [
"I found a great way to do it, it creates a bunch of spheres in the area that is described by an if statement this is the code I am using for my simulation that creates the sphere with points on it.\ndef SOSE (radi, number_of_charges, height):\n Charged_Sphere = sphere(pos=vector(0,height,0), radius=radi, color=ve... | [
2
] | [] | [] | [
"python",
"simulation",
"vpython"
] | stackoverflow_0074354233_python_simulation_vpython.txt |
Q:
Login system with number of tries on python how can i simplify it?
I am a Beginner in Python and i made this login system with number of tries. I think it can be simplified Can anyone help?
a=int(input("Enter the Password: "))
i=5
if a==1234:
print("ACCESS GRANTED")
while not a==1234:
print(f"... | Login system with number of tries on python how can i simplify it? | I am a Beginner in Python and i made this login system with number of tries. I think it can be simplified Can anyone help?
a=int(input("Enter the Password: "))
i=5
if a==1234:
print("ACCESS GRANTED")
while not a==1234:
print(f"INVALID PASSWORD ( {i} times left)")
a=int(input("Enter the Password... | [
"Maybe something like this:\na = 0\ni = 6\nwhile not a==1234:\n a=int(input(\"Enter the Password: \"))\n i-=1\n if a==1234:\n print(\"ACCESS GRANTED\")\n elif i==0:\n print(\"Console has been locked\")\n break\n else:\n print(f\"INVALID PASSWORD ( {i} times left)\")\n\n",
... | [
0,
0,
0,
0
] | [] | [] | [
"authentication",
"loops",
"python",
"simplify"
] | stackoverflow_0074376338_authentication_loops_python_simplify.txt |
Q:
How to use APScheduler in Python to run program daily at exact time?
I am trying to run something at the exact time to the second everyday.
I have tried Schedule and used a sleep time of 1 second but it runs twice sometimes so I want to switch to APScheduler. But I have never used anything Cron like before and the... | How to use APScheduler in Python to run program daily at exact time? | I am trying to run something at the exact time to the second everyday.
I have tried Schedule and used a sleep time of 1 second but it runs twice sometimes so I want to switch to APScheduler. But I have never used anything Cron like before and their webpage's "User Guide" thing doesn't resemble a detailed documentation ... | [
"I believe what you want is the BackgroundScheduler from APScheduler using a CronTrigger.\nA minimal example of the program would be the following:\nfrom time import sleep\n\nfrom apscheduler.schedulers.background import BackgroundScheduler\nfrom apscheduler.triggers.cron import CronTrigger\n\n\ndef foo(bar):\n ... | [
6,
0
] | [
"apscheduler.schedulers.background import BackgroundScheduler\nfrom apscheduler.triggers.cron import CronTrigger\n\n"
] | [
-1
] | [
"apscheduler",
"python"
] | stackoverflow_0067386508_apscheduler_python.txt |
Q:
How can I take the first values from a list of dictionaries and create another list with it?
I am very new to python and machine learning and i searched for this specific question but could not find something useful.
I have a list:
data=[{'a':1,
'b':2},
{'a':3,
'b':4}]
I want a separate l... | How can I take the first values from a list of dictionaries and create another list with it? | I am very new to python and machine learning and i searched for this specific question but could not find something useful.
I have a list:
data=[{'a':1,
'b':2},
{'a':3,
'b':4}]
I want a separate list for a and b with their values. For example:
a=[1,3]
b=[2,4]
I tried to do:
a=[lst['a'] for l... | [
"If you have a list of dicts, with identical keys, then in that case you could use the the library called Pandas and its DataFrames, which essentially is a Matrix. If you're working with machine learning you'll most likely use this library quite a lot anyways. But then you can select a specific column.\nimport pand... | [
-1
] | [] | [] | [
"linear_regression",
"python",
"python_3.x",
"regression"
] | stackoverflow_0074376379_linear_regression_python_python_3.x_regression.txt |
Q:
gTTS Python Script in background getting tcgetattr(): Inappropriate ioctl for device
Im developing an application on my raspberry Pi 3, using gTTS for Python:
from gtts import gTTS
import os
import threading
def greet_thread(word):
tts_thread = threading.Thread(target = greet, args=[word])
tts_thread.star... | gTTS Python Script in background getting tcgetattr(): Inappropriate ioctl for device | Im developing an application on my raspberry Pi 3, using gTTS for Python:
from gtts import gTTS
import os
import threading
def greet_thread(word):
tts_thread = threading.Thread(target = greet, args=[word])
tts_thread.start()
def greet(word):
tts = gTTS(text=word, lang='es')
tts.save("words.mp3")
p... | [
"The problem is that the program needs to be executed using the same user that executes the GUI. So if you are going to execute it in a command shell, avoid using 'root' user.\nIn my case i need the program executes on start up too. So i solved it using \"auto start\" instead of a crontab\n\nNavigate to ~/.config/l... | [
1,
0
] | [] | [] | [
"python",
"raspbian",
"text_to_speech"
] | stackoverflow_0050996129_python_raspbian_text_to_speech.txt |
Q:
Python Airlflow Google Cloud Storage library import error
I want to create an airflow DAG to transfer files to cloud storage but I'm running into a problem importing Google Cloud libraries.
Libraries I want to use:
from airflow.providers.google.cloud.operators.gcs import GCSCreateBucketOperator, GCSDeleteBucketOpe... | Python Airlflow Google Cloud Storage library import error | I want to create an airflow DAG to transfer files to cloud storage but I'm running into a problem importing Google Cloud libraries.
Libraries I want to use:
from airflow.providers.google.cloud.operators.gcs import GCSCreateBucketOperator, GCSDeleteBucketOperator
from airflow.providers.google.cloud.operators.gcs import ... | [
"In your virtual env, you can try to install the Apache Airflow package with extra gcp to prevent depencencies conflicts :\nExample with pip :\nrequirements.txt file\napache-airflow[gcp]==2.4.2\n\npip command :\npip install -r requirements.txt\n\nYou can also use another package manager with Python like pipenv and ... | [
1
] | [] | [] | [
"airflow",
"google_cloud_storage",
"python"
] | stackoverflow_0074371999_airflow_google_cloud_storage_python.txt |
Q:
Can't install pyenv on MacOS Ventura 13.0
A programmer friend recommended I re-installed python on my mac using pyenv. I didn't understand why but given that he's much more expert than me in python I decided to trust him.
He said to do
brew install pyenv
pyenv install 3.10.0
pyenv global 3.10.0
and brew install p... | Can't install pyenv on MacOS Ventura 13.0 | A programmer friend recommended I re-installed python on my mac using pyenv. I didn't understand why but given that he's much more expert than me in python I decided to trust him.
He said to do
brew install pyenv
pyenv install 3.10.0
pyenv global 3.10.0
and brew install pyenv worked fine, but pyenv install 3.10.0 gave... | [
"Im not completely sure of what the problem regarding installing this on your system may be, but I would urge you to check out the pyenv installation guide to check if there are steps you may need to take! Check the usage guide to see how it is used.\nAlso, you could try installing the latest version of 3.10 by jus... | [
0
] | [] | [] | [
"installation",
"pyenv",
"python"
] | stackoverflow_0074375996_installation_pyenv_python.txt |
Q:
How to change row height for pandas export .to_excel() after wrapping texts in DataFrame?
I'm wrapping texts in a Pandas DataFrame with this code:
for column in dataframe:
if column != '':
dataframe[column] = dataframe[column].str.wrap(len(column) + 20)
and export the DataFrame to an... | How to change row height for pandas export .to_excel() after wrapping texts in DataFrame? | I'm wrapping texts in a Pandas DataFrame with this code:
for column in dataframe:
if column != '':
dataframe[column] = dataframe[column].str.wrap(len(column) + 20)
and export the DataFrame to an excel document with .to_excel('filename'). And the result is (LibreOffice on Linux) shown in t... | [
"How can I change the row height of the row with the wrapped text in order to see the entire text in Libre Office Calc as shown in the image?\nThe 'problem' you experience is a result of the wrong expectation that the from pandas dataframe with .to_excel() exported .xls file will auto-magically contain beside the ... | [
1
] | [] | [] | [
"export_to_excel",
"pandas",
"python"
] | stackoverflow_0074359787_export_to_excel_pandas_python.txt |
Q:
Download Attachment from gmail api using Python
I am trying to download the attachment from gmail using the python and I am not able to fetch the attachment id from my mail. Please find my code below
import os.path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials... | Download Attachment from gmail api using Python | I am trying to download the attachment from gmail using the python and I am not able to fetch the attachment id from my mail. Please find my code below
import os.path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFl... | [
"There are two main issues with this code.\n\nresults.get() method either returns a Message or MessagePart Object. So you only need to use the get() method once to get the complete object and then you can target the specific part of the object you want.\nFor Example. results.get('messages', [])[0]['id']\n\nA payloa... | [
0
] | [] | [] | [
"api",
"gmail_api",
"python",
"rest"
] | stackoverflow_0071818626_api_gmail_api_python_rest.txt |
Q:
Spread percentage summary in dataframe pandas
If for example I have one column data frame pandas.
A 20
B 20
C 15
D 10
E 10
F 8
G 7
H 5
I 5
And I want to get data spread such as then the biggest 75%, 15% and last 10% is
A F H
B G I
C
D
E
Is there pandas function that ... | Spread percentage summary in dataframe pandas | If for example I have one column data frame pandas.
A 20
B 20
C 15
D 10
E 10
F 8
G 7
H 5
I 5
And I want to get data spread such as then the biggest 75%, 15% and last 10% is
A F H
B G I
C
D
E
Is there pandas function that can make this summary faster ?
Do I need to make in... | [
"The exact input and expected output is not fully clear, but assuming this DataFrame as input:\n col\nA 20\nB 20\nC 15\nD 10\nE 10\nF 8\nG 7\nH 5\nI 5\n\nYou can get a dictionary of the indices using:\nimport numpy as np\n\ntarget = [75, 15, 10]\n\ngroup = pd.cut(df['col'].cumsum(), bins=np.... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074376591_dataframe_pandas_python.txt |
Q:
Create unit test for method in class using selenium
I am trying to create a unit test for a method in my file crypto.py. This file runs a webscraper that collects data from cryto.com. I am struggling to understand how to create a unit test for some of the methods if I would like these tests to be in a separate fil... | Create unit test for method in class using selenium | I am trying to create a unit test for a method in my file crypto.py. This file runs a webscraper that collects data from cryto.com. I am struggling to understand how to create a unit test for some of the methods if I would like these tests to be in a separate file. For instance, this is the first method in crytpo.py:
c... | [
"To test any method you need to ensure it did what it should. So, you need to check the result of the method.\nThe main goal of accept_cookies method is to get rid of the cookies pop-up. This means you need to ensure the button was clicked. So you need to check if the pop-up (or the button itself) disappeared from ... | [
0
] | [] | [] | [
"methods",
"python",
"selenium",
"unit_testing"
] | stackoverflow_0074376159_methods_python_selenium_unit_testing.txt |
Q:
Pandas DataFrame groupby and aggregation per unique value in another column
I have following data:
value = [["time1", "client1", None, "username1"], ["time2", "client1", "event1", "username1"], ["time3", "client1", None, "username2"], ["time4", "client2", None, "username3"], ["time5", "client2", "event2", "usernam... | Pandas DataFrame groupby and aggregation per unique value in another column | I have following data:
value = [["time1", "client1", None, "username1"], ["time2", "client1", "event1", "username1"], ["time3", "client1", None, "username2"], ["time4", "client2", None, "username3"], ["time5", "client2", "event2", "username4"], ["time6", "client3", None, "username5"]]
columns = ["timestamp", "clients",... | [
"IIUC, you can try:\ndf.groupby('clients')['events'].agg(('nunique', 'count')).eval('nunique / count')\n\nOutput:\nclients\nclient1 1.0\nclient2 1.0\nclient3 NaN\ndtype: float64\n\nIf you want to divide the number of unique events per client, you can use size instead of count\n",
"I'm sure you can see so... | [
0,
0
] | [] | [] | [
"aggregation",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074316176_aggregation_dataframe_pandas_python.txt |
Q:
How to add a dataclass field without annotating the type?
When there is a field in a dataclass for which the type can be anything, how can you omit the annotation?
@dataclass
class Favs:
fav_number: int = 80085
fav_duck = object()
fav_word: str = 'potato'
It seems the code above doesn't actually creat... | How to add a dataclass field without annotating the type? | When there is a field in a dataclass for which the type can be anything, how can you omit the annotation?
@dataclass
class Favs:
fav_number: int = 80085
fav_duck = object()
fav_word: str = 'potato'
It seems the code above doesn't actually create a field for fav_duck. It just makes that a plain old class a... | [
"The dataclass decorator examines the class to find fields, by looking for names in __annotations__. It is the presence of annotation which makes the field, so, you do need an annotation.\nYou can, however, use a generic one:\n@dataclass\nclass Favs:\n fav_number: int = 80085\n fav_duck: 'typing.Any' = objec... | [
21,
5,
1,
0
] | [] | [] | [
"annotations",
"duck_typing",
"python",
"python_3.7",
"python_dataclasses"
] | stackoverflow_0049931096_annotations_duck_typing_python_python_3.7_python_dataclasses.txt |
Q:
ImportError: The `scipy` install you are using seems to be broken, (extension modules cannot be imported), please try reinstalling
I'm coniststently getting this error when trying to use scipy or sklearn packages in Python3.9 via a Jupyter notebook.
The error is:
---------------------------------------------------... | ImportError: The `scipy` install you are using seems to be broken, (extension modules cannot be imported), please try reinstalling | I'm coniststently getting this error when trying to use scipy or sklearn packages in Python3.9 via a Jupyter notebook.
The error is:
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
~/opt/anaconda3/lib/python3.9/site-... | [
"I had also face the same problem but reinstallation worked for me.\nUse Anaconda(or Miniconda) to uninstall and install scipy\npip uninstall scipy\npip install scipy\n.\nduring debugging I also upgrade pip and install spider maybe they contain any package which helped me.\n"
] | [
0
] | [] | [] | [
"numpy",
"python",
"python_3.x",
"scikit_learn",
"scipy"
] | stackoverflow_0073446317_numpy_python_python_3.x_scikit_learn_scipy.txt |
Q:
Create timeseries data - Pandas
I have a multi-index dataframe of timeseries data which looks like the following;
A B C
1 1 21 32 4
2 4 2 23
3 12 9 10
4 1 56 37
.
.
.
.
30 63 1 27
31 32 2 32
.
.
.
12 1 2 3 23
2 23 1 12
3 32 3 23
.
.
.
31 23 2 32
It is essentially... | Create timeseries data - Pandas | I have a multi-index dataframe of timeseries data which looks like the following;
A B C
1 1 21 32 4
2 4 2 23
3 12 9 10
4 1 56 37
.
.
.
.
30 63 1 27
31 32 2 32
.
.
.
12 1 2 3 23
2 23 1 12
3 32 3 23
.
.
.
31 23 2 32
It is essentially a multi-index of month and dates wit... | [
"You can use:\ndf.index = pd.to_datetime(df.index.rename(['month', 'day']).to_frame().assign(year=2022))\n\nOutput:\n A B C\n2022-01-01 21 32 4\n2022-01-02 4 2 23\n2022-01-03 12 9 10\n2022-01-04 1 56 37\n2022-01-30 63 1 27\n2022-01-31 32 2 32\n2022-12-01 2 3 23\n2022-12... | [
2
] | [] | [] | [
"datetime",
"indexing",
"multi_index",
"pandas",
"python"
] | stackoverflow_0074376675_datetime_indexing_multi_index_pandas_python.txt |
Q:
Asking for help breaking down a piece of code --- Head First Python 2nd Edition (11/9/2022) pg 102
https://prnt.sc/B4pFd_w5reM0
<<< photo of page
https://prnt.sc/bfCN6MN3P9DM
<<< screenshot of code
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
friends ... | Asking for help breaking down a piece of code --- Head First Python 2nd Edition (11/9/2022) pg 102 | https://prnt.sc/B4pFd_w5reM0
<<< photo of page
https://prnt.sc/bfCN6MN3P9DM
<<< screenshot of code
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
friends = ['phil', 'sarah']
for name in favorite_languages.keys():
print(f"Hi {name.title()}.")
if name... | [
"You are asking several questions at once, so I will answer them one at a time.\nI will preface my answer by saying this:\nPython is a programming language. A programming language consists of instructions that are provided to a computer program. The computer program simply reads one instruction at a time, and perfo... | [
-2
] | [] | [] | [
"python"
] | stackoverflow_0074376250_python.txt |
Q:
correct way to update a pandas dataframe with a shifted version of itself?
The below code appears to work, however I fail to understand why it's working and if it's correct/safe:
>>> df = pd.DataFrame(np.random.randint(1, 100, 10).reshape(-1, 2), columns = list('ab'))
>>> df
a b
0 45 44
1 89 45
2 80 93... | correct way to update a pandas dataframe with a shifted version of itself? | The below code appears to work, however I fail to understand why it's working and if it's correct/safe:
>>> df = pd.DataFrame(np.random.randint(1, 100, 10).reshape(-1, 2), columns = list('ab'))
>>> df
a b
0 45 44
1 89 45
2 80 93
3 66 27
4 89 73
>>> df.at[1,'a']=0
>>> df.at[2,'a']=0
>>> df
a b
0 4... | [
"In general I avoid using .loc, .at etc. if only because the code can end up a bit obtuse. You may find an expression involving the where function a tad clearer since by definition the purpose of where is to conditionally replace values.\ndf['a'] = df['a'].where(df['a'] != 0, df['a'].shift(-2))\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074376016_dataframe_pandas_python.txt |
Q:
Create new column with values in long format pandas dataframe
I am looking to calculate the vote share for a candidate in a particular district for a particular election.
I've got a dataset that gives me the party of the candidate, the district that they ran in, and the year of the election.
However, I have their ... | Create new column with values in long format pandas dataframe | I am looking to calculate the vote share for a candidate in a particular district for a particular election.
I've got a dataset that gives me the party of the candidate, the district that they ran in, and the year of the election.
However, I have their competitors as well and want to calculate the vote share for one of... | [
"Filter your df for the kind of party you want. Then get the Dem_votes_share and map its results to the df.\nNew Input:\ndf = pd.DataFrame({\n 'year': [1976, 1976, 1980, 1980, 1976, 1976, 1980, 1980], \n 'state': ['alabama', 'alabama', 'alaska', 'alaska', 'alabama', 'alabama', 'alaska', 'alaska'], \n ... | [
1,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074376589_pandas_python.txt |
Q:
python script error : Local variable referenced before assignment
we wrote a python test script to automate a few tasks including adding service accounts and resource groups . At execution I get an error message :
'UnboundLocalError: local variable 'sa_clientId' referenced before assignment'
i read a few stackove... | python script error : Local variable referenced before assignment | we wrote a python test script to automate a few tasks including adding service accounts and resource groups . At execution I get an error message :
'UnboundLocalError: local variable 'sa_clientId' referenced before assignment'
i read a few stackoverflow threads where they speak about problems related to global variabl... | [
"well in the above code you only assign \"clientId\" when it passes through\n\"if response.text != '':\", by doing so and returning \"clientId\" it would be referenced before assignment unless it passes through the if statement.\ntry adding a default value state.\nEx.\ndef take_command():\n with sr.Microphone() ... | [
0
] | [] | [] | [
"debugging",
"exception",
"python",
"testing",
"variables"
] | stackoverflow_0074376653_debugging_exception_python_testing_variables.txt |
Q:
How to split a csv_file into two file: one containing 40% of the original data, the other 60%. The data should be shuffled first
I have a csv file. The columns are ['A' 'B' 'C'], and there are 1000 rows of original data.
A B C
1 0 1
-1 2 0
.
.
.
1 0 0.
So I need 40% of these data in one csv_file, 60 % in th... | How to split a csv_file into two file: one containing 40% of the original data, the other 60%. The data should be shuffled first | I have a csv file. The columns are ['A' 'B' 'C'], and there are 1000 rows of original data.
A B C
1 0 1
-1 2 0
.
.
.
1 0 0.
So I need 40% of these data in one csv_file, 60 % in the other. But first, the rows must be shuffled randomly. Hopefully using the pandas module in python.
I tried
Import pandas as pd
df=pd... | [
"Try this way\nwith shuffling before saving & complete snippet\nimport numpy as np\nimport pandas as pd\n\n\nper = 40\nmask =int(len(df))\n\nperdf=df.head(int((mask*(per/100))))\n\nperdf =perdf.iloc[np.random.permutation(len(perdf))]\nperdf.to_csv('40perdf.csv')\n\n\nperdf60=df[:mask]\nperdf60 =perdf60.iloc[np.rand... | [
1,
1,
0
] | [] | [] | [
"csv",
"dataframe",
"python"
] | stackoverflow_0074376447_csv_dataframe_python.txt |
Q:
How to update values on tkinter window?
I am trying to make a window that would show the location of the mouse at all times by using pyautogui and tkinter. I am new to tkinter and python overall so I am not quite sure how to make it so that the values would keep updating in the window, if it is even possible. Here... | How to update values on tkinter window? | I am trying to make a window that would show the location of the mouse at all times by using pyautogui and tkinter. I am new to tkinter and python overall so I am not quite sure how to make it so that the values would keep updating in the window, if it is even possible. Here is my code so far:
from tkinter import *
imp... | [
"Create a StringVar() to store the coords, and then assign it to the label's textvariable. You can then bind a '<Motion>' handler to your root window to update the label whenever the mouse moves.\ncoord_var = StringVar(window)\n\n\ndef on_mousemove(event):\n coord_var.set(f'Mouse coordinates: {event.x}, {event.y... | [
2
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074376780_python_tkinter.txt |
Q:
How to refer to model class (name) from html form to views.py with Django?
I want users to be able to download a Django model which is being displayed in the app. There can be many types of models, therefore I want to generalize my code. Currently I let users download the model in excel by means of the following c... | How to refer to model class (name) from html form to views.py with Django? | I want users to be able to download a Django model which is being displayed in the app. There can be many types of models, therefore I want to generalize my code. Currently I let users download the model in excel by means of the following code in HTML:
<form id="downloadfile" method="post" action="{% url 'download_file... | [
"from django.conf import settings\nfrom django.apps import apps\n\n\ndef get_all_models():\n model_name_list = []\n installed_apps = settings.INSTALLED_APPS[6:]\n # just exclude system app that is not installed by you\n for app in installed_apps:\n app_config = apps.get_app_config(app)\n f... | [
1,
0
] | [] | [] | [
"django",
"django_templates",
"django_views",
"python"
] | stackoverflow_0074372445_django_django_templates_django_views_python.txt |
Q:
Adding a column to dataframe based on conditions met for each row (pandas)
Suppose I have a data frame that has the following elements say:
Element
0 a_1
1 a_2
2 b_1
3 a_3
4 b_2
.....
and so on.
Now suppose I have two categories A and B. Every element falls into one of these cat... | Adding a column to dataframe based on conditions met for each row (pandas) | Suppose I have a data frame that has the following elements say:
Element
0 a_1
1 a_2
2 b_1
3 a_3
4 b_2
.....
and so on.
Now suppose I have two categories A and B. Every element falls into one of these categories, and let's say I have lists As = [a_1, a_2, ...] and Bs = [b_1, b_2, ...... | [
"Rather than lists, use a dictionary and reverse it to use with map:\nd = {'A': ['a_1', 'a_2', 'a_3'],\n 'B': ['b_1', 'b_2'],\n }\n\nd2 = {k: v for v, l in d.items() for k in l}\n\ndf['Category'] = df['Element'].map(d2)\n\noutput:\n Element Category\n0 a_1 A\n1 a_2 A\n2 b_1 ... | [
2,
0
] | [] | [] | [
"numpy",
"pandas",
"python"
] | stackoverflow_0074376512_numpy_pandas_python.txt |
Q:
How to make matplotlib widget in PyQt5 clickable?
I am working on GUI where I have tab system with graphs. I want that if a user clicks (or puts cursor) at any point in the graph, it shows the exact x and y values in that point like that:
I know that in usual matplotlib it is easy to implement; however I do not ... | How to make matplotlib widget in PyQt5 clickable? | I am working on GUI where I have tab system with graphs. I want that if a user clicks (or puts cursor) at any point in the graph, it shows the exact x and y values in that point like that:
I know that in usual matplotlib it is easy to implement; however I do not know how to do that in PyQt5.
My tabs system and canvas... | [
"import this module:\nimport mplcursors as mpl\nand add : mpl.cursor(hover=True)\nin your def plot() function.\n"
] | [
0
] | [] | [] | [
"matplotlib",
"pyqt5",
"python"
] | stackoverflow_0060377534_matplotlib_pyqt5_python.txt |
Q:
Creating Blank Spaces for Letters in Randomly Selected Word
I'm a super-newbie Computing Science student, and I don't understand what the "blank answer = ''" statement does. My professor explained (I believe), that this will create a new space, but I'm not sure how this works. Thanks for reading the question!
corr... | Creating Blank Spaces for Letters in Randomly Selected Word | I'm a super-newbie Computing Science student, and I don't understand what the "blank answer = ''" statement does. My professor explained (I believe), that this will create a new space, but I'm not sure how this works. Thanks for reading the question!
correct_word = random.choice(['apple','banana','watermelon','kiwi','p... | [
"The way I'm interpreting the code fragment is that your are building a set of underscores that when strung together create a blank line for printing on a page or other medium. \nFor instance let's say the choice was apple. The variable blank_answer would be set to \"_____\" . One '_' for each letter in the work ... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0052770906_python.txt |
Q:
Why is my python discord bot rate limited?
So I made a discord bot two years ago which filters certain channels and deletes messages which don‘t start with %z in one channel and %v in the other. It worked well for like 1 and a half years, but now it always states to be rate limited. This is the error I‘ve been con... | Why is my python discord bot rate limited? | So I made a discord bot two years ago which filters certain channels and deletes messages which don‘t start with %z in one channel and %v in the other. It worked well for like 1 and a half years, but now it always states to be rate limited. This is the error I‘ve been consistently getting:
Traceback (most recent call l... | [
"There is many reasons why you can get rate-limited from the Discord API. The official info is listed here.\nFrom your comments, you said you were using replit. Replit is actually not all that good for hosting bots (but of course its easy, cheap/free, and friendly for beginners). This is for multiple reasons, inclu... | [
3
] | [] | [] | [
"bots",
"discord",
"discord.py",
"python"
] | stackoverflow_0074367238_bots_discord_discord.py_python.txt |
Q:
Flutter TCP Socket with Python send any different string
I'm trying send data to python on flutter. But I am only send "data", ı want send different "string" but this code not working. I want to send "psk" and "ssid" string. Can you help me?
import 'package:flutter/material.dart';
import 'package:tcp_socket_connec... | Flutter TCP Socket with Python send any different string | I'm trying send data to python on flutter. But I am only send "data", ı want send different "string" but this code not working. I want to send "psk" and "ssid" string. Can you help me?
import 'package:flutter/material.dart';
import 'package:tcp_socket_connection/tcp_socket_connection.dart';
class UsersPage extends Sta... | [
"I added the following parts to the flutter code to send a different string. And it worked I was able to send a new string. Here is the new code. I just changed these.\n void messageReceivedd(String psk) {\nsetState(() {\n wifi = psk;\n});}\n ElevatedButton(\n onPressed: () {\n so... | [
0
] | [] | [] | [
"flutter",
"p_lang",
"python",
"ssid",
"tcpsocket"
] | stackoverflow_0074348986_flutter_p_lang_python_ssid_tcpsocket.txt |
Q:
How to make a powerset in ascending order for the first item in a list?
I am trying to make a powerset of a list for the first item of that list in ascending order. However, I couldn't find on StackOverflow how to tackle this specific problem.
When making a powerset of the following list:
backlog = [1, 2, 3, 4, 5]... | How to make a powerset in ascending order for the first item in a list? | I am trying to make a powerset of a list for the first item of that list in ascending order. However, I couldn't find on StackOverflow how to tackle this specific problem.
When making a powerset of the following list:
backlog = [1, 2, 3, 4, 5]
with function:
def powerset(backlog):
s = backlog
return chain.from... | [
"You could filter the powerset leaving only the elements that you care about (their 1st element is the 1st element of the starting list (backlog))\nBut (as I specified in the comment) this is kind of inefficient as it generates lots of values (half) just to later discard them.\nSo, an alternative would be to genera... | [
0
] | [] | [] | [
"powerset",
"python"
] | stackoverflow_0074376434_powerset_python.txt |
Q:
How to pivot multiple columns
Input Table
index
income
Education
age1to_20
pcd
1
income_1
Education_0
1
A5009
2
income_2
Education_2
1
A3450
3
income_1
Education_0
1
A5009
4
income_3
Education_1
0
A3450
How do I convert this table into
index
income_1
income_2
INCOME_3
Education_0
Education_1
Education_2
age... | How to pivot multiple columns | Input Table
index
income
Education
age1to_20
pcd
1
income_1
Education_0
1
A5009
2
income_2
Education_2
1
A3450
3
income_1
Education_0
1
A5009
4
income_3
Education_1
0
A3450
How do I convert this table into
index
income_1
income_2
INCOME_3
Education_0
Education_1
Education_2
age1to_20
1
A5009
0... | [
"Another possible solution:\n(pd.concat([\n df.pivot(index=['index', 'age1to_20'], columns=['income'], values='pcd'),\n df.pivot(index=['index', 'age1to_20'], columns=['Education'], values='pcd')], axis=1)\n .fillna(0).reset_index())\n\nOutput:\n index age1to_20 income_1 income_2 income_3 Education_0 Educa... | [
3,
2,
1,
0
] | [] | [] | [
"dataframe",
"multiple_columns",
"pandas",
"python"
] | stackoverflow_0074372851_dataframe_multiple_columns_pandas_python.txt |
Q:
target __blank doesn't change page source and current url in Selenium
I use Selenium with Python to extract some data from a website.
My question is simple, I click on a link which opens with target="__blank", and the problem is that I want to get the current URL of the just opened page. Unfortunately, neither the... | target __blank doesn't change page source and current url in Selenium | I use Selenium with Python to extract some data from a website.
My question is simple, I click on a link which opens with target="__blank", and the problem is that I want to get the current URL of the just opened page. Unfortunately, neither the page URL is changed, nor the page source. I found that changing the elemen... | [
"target=\"_blank\"\n\nOpens the requested URL in a new Tab/Window.\nSeleniums only focusses on the current window, so the newly opened window won't be focussed by Selenium.\nThats why\ntarget=\"_self\"\n\nworks as intended, as it changes the current window.\nSee target behaviour here: https://wiki.selfhtml.org/wiki... | [
1,
1
] | [] | [] | [
"python",
"selenium"
] | stackoverflow_0074371585_python_selenium.txt |
Q:
Python Json manipulation
I'm trying to manipulate JSON file data.
What my JSON file looks like:
[
{
"sku": "2",
"view_code": "english",
"short_description": "xy",
"product_type": "simple",
"attribute_set_code": "4"
},
{
"sku": "1",
"view_code": "e... | Python Json manipulation | I'm trying to manipulate JSON file data.
What my JSON file looks like:
[
{
"sku": "2",
"view_code": "english",
"short_description": "xy",
"product_type": "simple",
"attribute_set_code": "4"
},
{
"sku": "1",
"view_code": "english",
"short_descri... | [
"tmp=[\n {\n \"sku\": \"2\",\n \"view_code\": \"english\",\n \"short_description\": \"xy\",\n \"product_type\": \"simple\",\n \"attribute_set_code\": \"4\"\n },\n {\n \"sku\": \"1\",\n \"view_code\": \"english\",\n \"short_description\": \"xy\",\n ... | [
0
] | [] | [] | [
"json",
"python"
] | stackoverflow_0074377141_json_python.txt |
Q:
Mypy not resolving type correctly for compound conditions
Whenever mypy tries to resolve Unions, it seems to use the code flow to resolve the type:
import typing as typ
def foo(x: typ.Union[int, None] = None, y: typ.Union[int, None] = None) -> int:
if x is None and y is None:
raise ValueError
if x... | Mypy not resolving type correctly for compound conditions | Whenever mypy tries to resolve Unions, it seems to use the code flow to resolve the type:
import typing as typ
def foo(x: typ.Union[int, None] = None, y: typ.Union[int, None] = None) -> int:
if x is None and y is None:
raise ValueError
if x is None:
x = 1
if y is None:
y = 2
re... | [
"You can write assert expressions, but it's not very beutiful, I suppose\ndef foo(x: typ.Union[int, None] = None, y: typ.Union[int, None] = None) -> int:\n if x is None and y is None:\n raise ValueError\n if x is None and y is not None:\n x = 1\n if y is None and x is not None:\n y = 2... | [
0
] | [] | [] | [
"mypy",
"python",
"python_typing",
"typing"
] | stackoverflow_0074376625_mypy_python_python_typing_typing.txt |
Q:
KeyError: How to exclude certain parts when a part of the serializer is empty
I have this piece in my serializer which is using a nested serializer field. When i try to submit my form it will return a KeyError if I don't add anything inside "assigned facilities". I tried adding an else statement but that doesn't s... | KeyError: How to exclude certain parts when a part of the serializer is empty | I have this piece in my serializer which is using a nested serializer field. When i try to submit my form it will return a KeyError if I don't add anything inside "assigned facilities". I tried adding an else statement but that doesn't seem to be helping. The debugger is actually complaining about line two when the fie... | [
"You can add default value in pop function, so it wont raise keyerror\n def create(self, validated_data):\n assigned_facilities = validated_data.pop(\"assigned_facilities\", [])\n instance = Lead.objects.create(**validated_data)\n\n for item in assigned_facilities:\n instance.lead... | [
1
] | [] | [] | [
"django",
"django_rest_framework",
"python"
] | stackoverflow_0074376872_django_django_rest_framework_python.txt |
Q:
PYTHON EXCEL COMBINE WORKSHEETS
Have an excel file consisting of multiple worksheets and each worksheet has one column named "Close" and under the "Close" column I have multiple numbers and data. Now using Python I want to combine all multiple worksheet in to one worksheet with side by side column of close and wor... | PYTHON EXCEL COMBINE WORKSHEETS | Have an excel file consisting of multiple worksheets and each worksheet has one column named "Close" and under the "Close" column I have multiple numbers and data. Now using Python I want to combine all multiple worksheet in to one worksheet with side by side column of close and worksheet title as the header for each c... | [
"To make pd.concat fully works, you need to concat all dataframe in one. Either by having a list of all dataframe and then call concat, either by looping iteratively. I advice to read one worksheet at a time.\nSecond solution :\ndf_combined = pd.DataFrame() \nfile = \"\"\n\nfor worksheet_name in worksheet_names : #... | [
0
] | [] | [] | [
"dataframe",
"excel",
"pandas",
"python"
] | stackoverflow_0074376854_dataframe_excel_pandas_python.txt |
Q:
A program where it requires the user to ONLY type a Yes or No answer, otherwise repeat the whole question
while True:
#SOME CODE...
ch = input("\nWould you like to try again? Y/N: ").upper()
if ch == 'Y':
continue # continue the whole program
elif:
print("Thanks for using the program... | A program where it requires the user to ONLY type a Yes or No answer, otherwise repeat the whole question | while True:
#SOME CODE...
ch = input("\nWould you like to try again? Y/N: ").upper()
if ch == 'Y':
continue # continue the whole program
elif:
print("Thanks for using the program.")
break # stops the program
else:
# repeats the Y or N question only; and prints 'Please ... | [
"You would use a second loop to validate the input before acting on one of the two valid inputs.\nwhile True:\n # do something\n\n while True:\n ch = input(\"Try again\").upper()\n if ch in ['YES', 'NO']:\n break\n print(\"Please enter yes or no\")\n\n if ch == \"NO\":\n ... | [
1,
0
] | [] | [] | [
"conditional_statements",
"python",
"python_3.x",
"while_loop"
] | stackoverflow_0074377223_conditional_statements_python_python_3.x_while_loop.txt |
Q:
merge multiple csv files present in hadoop into one csv files in local
I have multiple csv files present in hadoop folder. each csv files will have the header present with it. the header will remain the same in each file.
I am writing these csv files with the help of spark dataset like this in java
df.write().csv(... | merge multiple csv files present in hadoop into one csv files in local | I have multiple csv files present in hadoop folder. each csv files will have the header present with it. the header will remain the same in each file.
I am writing these csv files with the help of spark dataset like this in java
df.write().csv(somePath)
I was also thinking of using coalsec(1) but it is not memory effic... | [
"coalesce(1) is exactly what you want.\nSpeed/memory usage is the tradeoff you get for wanting exactly one file\n",
"It seems this will do it for you:\n# importing libraries\nimport pandas as pd\nimport glob\nimport os\n \n# merging the files\njoined_files = os.path.join(\"/hadoop\", \"*.csv\")\n \n# A list of ... | [
1,
0
] | [] | [] | [
"apache_spark",
"csv",
"hadoop",
"hdfs",
"python"
] | stackoverflow_0074364964_apache_spark_csv_hadoop_hdfs_python.txt |
Q:
How to print out 'Live' mouse position coordinates using pyautogui?
I used lots of different source codes, and even copied and pasted but I keep getting random symbols that shift when i move my mouse over them
here is my code...
import pyautogui, time, sys
print('Press Ctrl-C to quit.')
try:
while True:
... | How to print out 'Live' mouse position coordinates using pyautogui? | I used lots of different source codes, and even copied and pasted but I keep getting random symbols that shift when i move my mouse over them
here is my code...
import pyautogui, time, sys
print('Press Ctrl-C to quit.')
try:
while True:
CurserPos = pyautogui.position()
print('\b' * len(CurserPos),... | [
"Code :\nimport pyautogui\npyautogui.displayMousePosition()\n\nHere is some output :\nPress Ctrl-C to quit.\nX: 0 Y: 1143 RGB: ( 38, 38, 38)\n\nHere is the video where this is being demonstrated https://youtu.be/dZLyfbSQPXI?t=809\n",
"This code will print the live position of your mouse after every one second.... | [
20,
6,
0,
0
] | [] | [] | [
"pyautogui",
"python",
"python_3.x"
] | stackoverflow_0044533241_pyautogui_python_python_3.x.txt |
Q:
How can I make my python program choose option by itself randomly if I kept it in one variable?
If I have made a variable which has like
a = apple, banana, orange
than how can I make my python program choose one randomly by itself
I had made a variable which had four options
a = addition, subtraction, multiplicati... | How can I make my python program choose option by itself randomly if I kept it in one variable? | If I have made a variable which has like
a = apple, banana, orange
than how can I make my python program choose one randomly by itself
I had made a variable which had four options
a = addition, subtraction, multiplication
and I want my python to print one randomly by itself
| [
"If your variable is a list (or just it's subscriptable, like a tuple ,etc..) you can do by:\nimport random\n\nl = ['apple', 'banana', 'orange']\nprint(random.choice(l))\n\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074377277_python.txt |
Q:
Multiplying a specific column in txt file with constant number
I have txt file with 7 column...I want to mutiply a 3rd column with a constant number keeping all other column same and then output the file containing all the columns. Anyone can help?
1 2 1
2 2 1
3 2 1
mutiplying column 3 with "14" the output should... | Multiplying a specific column in txt file with constant number | I have txt file with 7 column...I want to mutiply a 3rd column with a constant number keeping all other column same and then output the file containing all the columns. Anyone can help?
1 2 1
2 2 1
3 2 1
mutiplying column 3 with "14" the output should be like
1 2 14
2 2 14
3 2 14
| [
"Can be done as below:\nMULTIPLIER = 14\n\ninput_file_name = \"numbers_in.txt\"\noutput_file_name = \"numbers_out.txt\"\nwith open(input_file_name, 'r') as f:\n lines = f.readlines()\n\nwith open(output_file_name, 'w+') as f:\n for line in lines:\n new_line = \"\"\n for i, x in enumerate(line.st... | [
0,
0,
0
] | [] | [] | [
"c++17",
"python"
] | stackoverflow_0074376134_c++17_python.txt |
Q:
drf-spectacular post method not working with form field
I am using Django Rest Framework. And for documentation I am using drf-spectacular.
But the problem I am facing is that when I am trying to submit using form, I can not submit. But I can submit using JSON type normally.
This Does not Work:
This Works:
How c... | drf-spectacular post method not working with form field | I am using Django Rest Framework. And for documentation I am using drf-spectacular.
But the problem I am facing is that when I am trying to submit using form, I can not submit. But I can submit using JSON type normally.
This Does not Work:
This Works:
How can I make the form to work? It does not even let me submit th... | [
"Same here with application/x-www-form-urlencoded. While it works from curl. I am thinking of dropping the application/x-www-form-urlencoded and multipart/form-data options - as I only need JSON - entirely out of the html using css or javascript if I can..\n",
"Add this option your SPECTACULAR_SETTINGS:\n'COMPONE... | [
0,
0
] | [] | [] | [
"django",
"django_rest_framework",
"drf_spectacular",
"python"
] | stackoverflow_0071495090_django_django_rest_framework_drf_spectacular_python.txt |
Q:
Add config file outside Pyinstaller --onefile exe into dist directory
Situation
I'm using Pyinstaller on Windows to make an .exe file of my project.
I would like to use --onefile option to have a clean result and an easy to distribute file/program.
My program use a config.ini file for storing config options. This ... | Add config file outside Pyinstaller --onefile exe into dist directory | Situation
I'm using Pyinstaller on Windows to make an .exe file of my project.
I would like to use --onefile option to have a clean result and an easy to distribute file/program.
My program use a config.ini file for storing config options. This file could be customized by users.
Problem
Using --onefile option Pyinstall... | [
"A repository on Github helped me to find a solution to my question.\nI've used shutil module and .spec file to add extra data files (in my case a config-sample.ini file) to dist folder using Pyinstaller --onefile option.\nMake a .spec file for pyinstaller\nFirst of all I've create a makespec file with the options ... | [
35,
3,
3,
1,
0,
0
] | [] | [] | [
"pyinstaller",
"python"
] | stackoverflow_0047850064_pyinstaller_python.txt |
Q:
Django Model Multi Select form not rendering properly
I am trying to display all the categories to appear as a list that I can click and select from, just an exact replica of what I have in my admin panel, but it still display's as a list that isn't clickable.
forms.py
class ProfileEditForm(forms.ModelForm):
"... | Django Model Multi Select form not rendering properly | I am trying to display all the categories to appear as a list that I can click and select from, just an exact replica of what I have in my admin panel, but it still display's as a list that isn't clickable.
forms.py
class ProfileEditForm(forms.ModelForm):
"""
Form for updating Profile data
"""
class Me... | [
"You need to create the form itself:\n<form method='post'>\n\n</form>\n\nAnd print each field on a new line:\n{{ form.as_p }}\n\nis a security check.\n{% csrf_token %}\n\nIn the view, I left get_context_data. In it, you can add values to the context, for example, like this:\ndef get_context_data(self, **kwargs):\... | [
2
] | [] | [] | [
"django",
"django_forms",
"django_models",
"django_templates",
"python"
] | stackoverflow_0074365546_django_django_forms_django_models_django_templates_python.txt |
Q:
How can we use tqdm in a parallel execution with joblib?
I want to run a function in parallel, and wait until all parallel nodes are done, using joblib. Like in the example:
from math import sqrt
from joblib import Parallel, delayed
Parallel(n_jobs=2)(delayed(sqrt)(i ** 2) for i in range(10))
But, I want that the... | How can we use tqdm in a parallel execution with joblib? | I want to run a function in parallel, and wait until all parallel nodes are done, using joblib. Like in the example:
from math import sqrt
from joblib import Parallel, delayed
Parallel(n_jobs=2)(delayed(sqrt)(i ** 2) for i in range(10))
But, I want that the execution will be seen in a single progressbar like with tqdm... | [
"Just put range(10) inside tqdm(...)! It probably seemed too good to be true for you, but it really works (on my machine):\nfrom math import sqrt\nfrom joblib import Parallel, delayed \nfrom tqdm import tqdm \nresult = Parallel(n_jobs=2)(delayed(sqrt)(i ** 2) for i in tqdm(range(100000)))\n\n",
"I've created pq... | [
54,
39,
23,
16,
7,
3,
2,
2,
1
] | [] | [] | [
"joblib",
"parallel_processing",
"python",
"tqdm"
] | stackoverflow_0037804279_joblib_parallel_processing_python_tqdm.txt |
Q:
How to get a day based on a number from 1 to 365
I want to get a day based on a number from 1 to 365. An integer in the range of 1 to 365 is given and I need to find the day of the week for a given day in a year (starting with Sunday).
a = int(input()) # Integer from 1 to 365
print( # day )
Example: input 1, out... | How to get a day based on a number from 1 to 365 | I want to get a day based on a number from 1 to 365. An integer in the range of 1 to 365 is given and I need to find the day of the week for a given day in a year (starting with Sunday).
a = int(input()) # Integer from 1 to 365
print( # day )
Example: input 1, output 4
| [
"Here's what they want you to solve:\nIt is known that the first day of the year is a Thursday, if they were to give you another day of the year, you have to find what day of the week it is.\nFor example, if they ask you what day of the week it is on day 2 (of the year), then you would say it is a Friday (since day... | [
1,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074377314_python.txt |
Q:
How to change the date when using pd.to_datetime?
I am having a bit of a struggle to use a dataframe that I have created. The dataframe is to keep track each day of the wake up time, 1st meal, last meal (2ndMeal here) and time when the person goes to sleep (Sleep time).
Here attached you can see what the initial d... | How to change the date when using pd.to_datetime? | I am having a bit of a struggle to use a dataframe that I have created. The dataframe is to keep track each day of the wake up time, 1st meal, last meal (2ndMeal here) and time when the person goes to sleep (Sleep time).
Here attached you can see what the initial dataframe looks like:
Unnamed: 1 Unnamed: 2 Unname... | [
"You can concatenate the first column to the other before using to_datetime, then convert the first column separately:\ntime_cols = df.columns[1:]\ndf[time_cols] = (df[time_cols].radd(df['Unnamed: 1']+' ', axis=0)\n .apply(pd.to_datetime)\n )\ndf['Unnamed: 1'] = pd.to_datetime(df['Un... | [
0,
0
] | [] | [] | [
"datetime",
"matplotlib",
"python",
"spyder",
"time"
] | stackoverflow_0074377320_datetime_matplotlib_python_spyder_time.txt |
Q:
Issue detecting nan in for loop using numpy
Why can't I detect the np.nan value in data using np.isnan() in the list comprehension below? Does the list comprehension transform the type of values in some way?
data = pd.DataFrame({'col':['a', 'b', np.nan]})
[print('NaN') if np.isnan(i) else print('Not NaN') for i i... | Issue detecting nan in for loop using numpy | Why can't I detect the np.nan value in data using np.isnan() in the list comprehension below? Does the list comprehension transform the type of values in some way?
data = pd.DataFrame({'col':['a', 'b', np.nan]})
[print('NaN') if np.isnan(i) else print('Not NaN') for i in data.col]
| [
"Yes, you will get into trouble using np.isnan() because of the mixed types in the column. From pandas' docs\n\nBecause NaN is a float, a column of integers with even one missing values is cast to floating-point dtype (see Support for integer NA for more)\n\nTherefore you should consider, as @saeedghadiri suggested... | [
3,
2,
1,
1
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074377360_numpy_python.txt |
Q:
Check for a condition in windows in a Pandas Dateframe and returning last True value
Sorry for the title gore, but here's an example code showing my issue.
df = pd.DataFrame({
'var': [True, True, False, False, False, True],
'letter': ['A', 'C', 'D', 'T', 'S', 'Y']},
index = [1, 2, 5, 7, 8, 9])
So I want to iter... | Check for a condition in windows in a Pandas Dateframe and returning last True value | Sorry for the title gore, but here's an example code showing my issue.
df = pd.DataFrame({
'var': [True, True, False, False, False, True],
'letter': ['A', 'C', 'D', 'T', 'S', 'Y']},
index = [1, 2, 5, 7, 8, 9])
So I want to iterate through the index and check every 2 values for a True value. If there's a True value ... | [
"You can use:\n(df['letter'].where(df['var']) # get letters if True\n .groupby(np.arange(len(df))//2) # for every pair\n .last() # get last True value (or None)\n .fillna(False) # replace None with False\n)\n\nOutput:\n0 C\n1 False\n2 Y\nName: letter, dtyp... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074377571_dataframe_pandas_python.txt |
Q:
Display number with leading zeros
How do I display a leading zero for all numbers with less than two digits?
1 → 01
10 → 10
100 → 100
A:
In Python 2 (and Python 3) you can do:
number = 1
print("%02d" % (number,))
Basically % is like printf or sprintf (see docs).
For Python 3.+, the same behavior can a... | Display number with leading zeros | How do I display a leading zero for all numbers with less than two digits?
1 → 01
10 → 10
100 → 100
| [
"In Python 2 (and Python 3) you can do:\nnumber = 1\nprint(\"%02d\" % (number,))\n\nBasically % is like printf or sprintf (see docs).\n\nFor Python 3.+, the same behavior can also be achieved with format:\nnumber = 1\nprint(\"{:02d}\".format(number))\n\n\nFor Python 3.6+ the same behavior can be achieved with f-str... | [
1684,
1178,
382,
154,
109,
92,
72,
57,
35,
9,
8,
6,
4,
2,
2,
1,
1
] | [
"Its built into python with string formatting\nf'{number:02d}'\n\n",
"If dealing with numbers that are either one or two digits:\n'0'+str(number)[-2:] or '0{0}'.format(number)[-2:]\n"
] | [
-1,
-2
] | [
"integer",
"python",
"string_formatting"
] | stackoverflow_0000134934_integer_python_string_formatting.txt |
Q:
How to convert time stamp format in Python from dd/mm/yy hh:mm:ss:msmsms to yyyy-mm-dd hh:mm:ss:msmsmsmsmsms
I have created an automated data client that pulls data from a txt file and inputs it into a csv file. Each data entry contains a timestamp, but it is not in the format I need it in, I need it to match the ... | How to convert time stamp format in Python from dd/mm/yy hh:mm:ss:msmsms to yyyy-mm-dd hh:mm:ss:msmsmsmsmsms | I have created an automated data client that pulls data from a txt file and inputs it into a csv file. Each data entry contains a timestamp, but it is not in the format I need it in, I need it to match the datetime.now() format:
ORIGINAL FORMAT
[03/11/22 01:06:09:190]
DESIRED FORMAT
2022-11-03 01:06:09.190000
I am curr... | [
"Try it with the datetime.datetime.strptime() and datetime.datetime.stftime() function:\ndate = datetime.datetime.strptime(time_string, format=\"%d/%m%/%y %H:%M:%S.%f\")\ndate.strftime(\"%Y-%m-%d %H:%M:%S.%f\")\n\nFor more info on the format string check out the documentation:\nhttps://docs.python.org/3/library/dat... | [
0
] | [] | [] | [
"automation",
"database",
"format",
"python",
"timestamp"
] | stackoverflow_0074377392_automation_database_format_python_timestamp.txt |
Q:
Python .exe containing alive progress bar error (FileNotFound)
I converted my .py file which contains the alive progress bar package https://pypi.org/project/alive-progress/ into a .exe for windows using the pyinstaller command pyinstaller --console . I however receive an error when I run the program. It runs fine... | Python .exe containing alive progress bar error (FileNotFound) | I converted my .py file which contains the alive progress bar package https://pypi.org/project/alive-progress/ into a .exe for windows using the pyinstaller command pyinstaller --console . I however receive an error when I run the program. It runs fine until the alive bar is called and then it prints out the error belo... | [
"A shorter alternative to what @Pluckerpluck has suggested would be using --collect-data grapheme instead of --add-data <...>.\n",
"alive-progress uses a library called grapheme. This library requires a JSON file which you will have to manually specify when using PyInstaller.\nIn my case, I had it under .venv so ... | [
1,
0
] | [] | [] | [
"executable",
"package",
"pyinstaller",
"python",
"windows"
] | stackoverflow_0074256747_executable_package_pyinstaller_python_windows.txt |
Q:
PyTorch different between ones_tensor = torch.ones((2, 3,)) and ones_tensor = torch.ones(2, 3)?
In PyTorch, what is different between
ones_tensor = torch.ones((2, 3,))
and
ones_tensor = torch.ones(2, 3)
?
A:
There's no difference between the two. As stated in the documentation,
size (int...) – a sequence of i... | PyTorch different between ones_tensor = torch.ones((2, 3,)) and ones_tensor = torch.ones(2, 3)? | In PyTorch, what is different between
ones_tensor = torch.ones((2, 3,))
and
ones_tensor = torch.ones(2, 3)
?
| [
"There's no difference between the two. As stated in the documentation,\n\nsize (int...) – a sequence of integers defining the shape of the output tensor. Can be a variable number of arguments or a collection like a list or tuple.\n\nIf you test it, they both produce the same tensor with the same shape.\ntensor([[1... | [
1
] | [] | [] | [
"machine_learning",
"python",
"pytorch",
"tensor"
] | stackoverflow_0074377393_machine_learning_python_pytorch_tensor.txt |
Q:
index out of range in same making loop
I'm trying to understand my little exercise. I tested with the same input but in two different coding ways. One of them ran well, the other one got string index out of range.Input: abBAcC
I got this problem:
Traceback (most recent call last):
File "d:\python_courses\leetcod... | index out of range in same making loop | I'm trying to understand my little exercise. I tested with the same input but in two different coding ways. One of them ran well, the other one got string index out of range.Input: abBAcC
I got this problem:
Traceback (most recent call last):
File "d:\python_courses\leetcode_make_string_great\make_string_great.py", l... | [
"Try to imagine how your first code works: in your example at each iteration index will take values from 0 to len(s)-1, i.e. 5.\nBut when index is 1 you find 'bB' and s becomes 'aAcC'. When index is 2 you find 'cC' and s is now only 'aA'. Now index becomes 3 and you get the error.\n"
] | [
0
] | [] | [] | [
"for_loop",
"loops",
"python",
"python_3.x",
"range"
] | stackoverflow_0074376868_for_loop_loops_python_python_3.x_range.txt |
Q:
Find a string between two certain strings, capture the middle string and replace everything with new string in Python using regular expressions
I'm refactoring some code and I wanted to automate some of it using Python, here is what I'm trying to do:
Let's say I have an initial string like 'void testsuite_testname... | Find a string between two certain strings, capture the middle string and replace everything with new string in Python using regular expressions | I'm refactoring some code and I wanted to automate some of it using Python, here is what I'm trying to do:
Let's say I have an initial string like 'void testsuite_testname(void)' and I want to substitute all of this with 'TEST_F(other_stuff, testname)'.
So, as you can see, I need to extract the testname from the first ... | [
"Try this:\n\nimport re\n\nstring = 'void testsuite_testname(void)'\n\nresult = re.search(r\"void testsuite_(\\w+)\\(void\\)\", string)\n\nstring2 = 'TEST_F(other_stuff, ' + result.group(1) + ')'\n\n\nprint(string2)\n\n#Output: TEST_F(other_stuff, testname)\n\n\nstring = 'void testsuite_testname(void)' this is the ... | [
0
] | [] | [] | [
"python",
"regex",
"replace",
"string"
] | stackoverflow_0074376558_python_regex_replace_string.txt |
Q:
Make a Python program print out data from a file while excluding stuff from other file
Sorry for my bad explanation, but Im trying to be as precise as I can.
So lets say that I have 2 files. First file has vehicle details (vehicles.txt) (reg number, make, transmission) etc. The other file (rented.txt) has only reg... | Make a Python program print out data from a file while excluding stuff from other file | Sorry for my bad explanation, but Im trying to be as precise as I can.
So lets say that I have 2 files. First file has vehicle details (vehicles.txt) (reg number, make, transmission) etc. The other file (rented.txt) has only registration numbers and rental dates in it. Goal is to print out all the available cars for re... | [
"For future use please provide some code so we can better understand what you have already tried. I dont know what your code looks like but in terms of the program structure I would read them both into lists. Then loop through all of the vechicles and check that currentVehicle not in RentedVehicleList and if that i... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074377549_python.txt |
Q:
How to create a window without minimize, maximized, and close button in python?
I would like to know if tkinter can remove minimize, maximized and closed button on the upper right portion of the screen. Or is there any other python library can do this? If so, what is the code?
A:
I explained this in a comment ab... | How to create a window without minimize, maximized, and close button in python? | I would like to know if tkinter can remove minimize, maximized and closed button on the upper right portion of the screen. Or is there any other python library can do this? If so, what is the code?
| [
"I explained this in a comment above, but I wanted to put it here for better readability. AFAIK, you can hide the minimize and maximize buttons on windows that are instances of Toplevel, but you can't do this on root windows that are instances of Tk - at least not using the method shown.\n# basic example\nimport tk... | [
0
] | [] | [] | [
"python",
"tkinter",
"user_interface"
] | stackoverflow_0074377434_python_tkinter_user_interface.txt |
Q:
sum of all numbers in a text file without knowing how many lines or how many numbers per line
How could I make a program that sums up all numbers in a txt file like this:
12 49 1 4 5
4 5
14
20
4 5 91
etc..
I was thinking of doing for line in readline(), then checking if there are spaces in the line and splitting ... | sum of all numbers in a text file without knowing how many lines or how many numbers per line | How could I make a program that sums up all numbers in a txt file like this:
12 49 1 4 5
4 5
14
20
4 5 91
etc..
I was thinking of doing for line in readline(), then checking if there are spaces in the line and splitting it if there is. How would I go about and do that?
| [
"You can do this by reading the entire file content - i.e., no need to read one line at a time. Note how str.split() is called with no parameters which will have the effect of splitting on whitespace.\nwith open('test.txt') as test:\n print(sum(map(int, test.read().split())))\n\n",
"You just need to split with... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074377462_python.txt |
Q:
python keyboard does not recognize keys
I am trying to detect the keys being pressed in python with "keyboard" but apparently it does not recognize the keys.
(I use python 3.11.0 with macOs ventura 13.0)
my code
import keyboard
while True:
if keyboard.is_pressed("a"):
print("You pressed 'a'.")
... | python keyboard does not recognize keys | I am trying to detect the keys being pressed in python with "keyboard" but apparently it does not recognize the keys.
(I use python 3.11.0 with macOs ventura 13.0)
my code
import keyboard
while True:
if keyboard.is_pressed("a"):
print("You pressed 'a'.")
break
and I get this error
Traceback (most r... | [
"It can work well in Windows and Linux. But it is experimental on macos. There may be many bugs or no support. The author of the keyboard-module has declared, Details boppreh/keyboard.\n"
] | [
1
] | [] | [] | [
"detect",
"keyboard",
"keylogger",
"macos",
"python"
] | stackoverflow_0074377405_detect_keyboard_keylogger_macos_python.txt |
Q:
Define field in Django which can be of any type
Pymodm is being used to define my model for the MongoDB collection in Django. I want to declare a field that can store values of any type (List, String, or Integer).
from pymodm import MongoModel, fields
class DefinitionEntity(MongoModel):
version = fields.In... | Define field in Django which can be of any type | Pymodm is being used to define my model for the MongoDB collection in Django. I want to declare a field that can store values of any type (List, String, or Integer).
from pymodm import MongoModel, fields
class DefinitionEntity(MongoModel):
version = fields.IntegerField(required=True)
value = fields.CharFiel... | [
"You can use Charfield in your model when it should be more generic. Take into consider that your model has to map the database.\n"
] | [
2
] | [] | [] | [
"django",
"mongodb",
"pymodm",
"python"
] | stackoverflow_0074376666_django_mongodb_pymodm_python.txt |
Q:
Reading a text file with pandas/numpy array
I need to read the observations from this file and store them per day basis. The daily observations start with a # and below that line are the daily observations. The columns in the observations are 'LVLpTYP', 'ETIME', 'PRESSURE','GPH','TEMP','RH','DPDP','WDIR','WSPD'res... | Reading a text file with pandas/numpy array | I need to read the observations from this file and store them per day basis. The daily observations start with a # and below that line are the daily observations. The columns in the observations are 'LVLpTYP', 'ETIME', 'PRESSURE','GPH','TEMP','RH','DPDP','WDIR','WSPD'respectively. I don't want to skip the heading rows ... | [
"This question is extremely vague and needs more detail in order for the question to be answered accurately. This includes clarification on what \"proper\" storage format of this file, and likely code that you have as an attempt to solve this problem yourself first.\n",
"What stopping you read this file?\nimport ... | [
0,
0
] | [] | [] | [
"csv",
"numpy",
"pandas",
"python",
"text"
] | stackoverflow_0074377516_csv_numpy_pandas_python_text.txt |
Q:
Python doesn't see a module
I'm new in python , and in the first place I've encountered a "Module not found error" , My folder structure is the following. I need to access the a.py , and b.py file from c.py file.
dir_1
├── __init__.py
└── a.py
└── b.py
dir_2
└── c.py
I've tried to add all file in ... | Python doesn't see a module | I'm new in python , and in the first place I've encountered a "Module not found error" , My folder structure is the following. I need to access the a.py , and b.py file from c.py file.
dir_1
├── __init__.py
└── a.py
└── b.py
dir_2
└── c.py
I've tried to add all file in my init.py as follow
from .ImageT... | [
"There are a few solutions:\n\nWithin your IDE (e.g. PyCharm) add those directories as Sources Root\nRefer to the modules with relative pathing\nInstall the module into your environment\nAdd the folders to your code to look in as sys.path.append('dir_1')\n\n"
] | [
0
] | [] | [] | [
"init",
"module",
"python"
] | stackoverflow_0074377719_init_module_python.txt |
Q:
PyTorch Dataloader for multiple files with sliding window
I am working on a problem where I have multiple CSVs files and I need to read those multiple CSVs one by one with a sliding window. Let’s assume that, one CSV file is having 330 data points and the window size is 32 so we should be having (10*32 = 320) and ... | PyTorch Dataloader for multiple files with sliding window | I am working on a problem where I have multiple CSVs files and I need to read those multiple CSVs one by one with a sliding window. Let’s assume that, one CSV file is having 330 data points and the window size is 32 so we should be having (10*32 = 320) and the last 10 points will be discarded.
I started making a datase... | [
"I propose the following workaround. According to this, the getitem function retrieves a specific window which belongs to a csv file and not the file itself. Towards this direction, find_num_of_windows computes the number of windows occur for a given csv file. The len(self) function will return the sum of the windo... | [
1
] | [] | [] | [
"machine_learning",
"python",
"pytorch",
"pytorch_dataloader",
"torch"
] | stackoverflow_0074375033_machine_learning_python_pytorch_pytorch_dataloader_torch.txt |
Q:
Is there a way to define an piecewise function in sympy where the intervals depend on indexed symbols?
As the title says. I have created an indexed symbol 't' and I wish to create a piecewise function that is (-1)^k when t[1]+t[2]+...+t[k]<=x<t[1]+t[2]+...+t[k]+t[k+1], up to a given maximum value of k=n. My code i... | Is there a way to define an piecewise function in sympy where the intervals depend on indexed symbols? | As the title says. I have created an indexed symbol 't' and I wish to create a piecewise function that is (-1)^k when t[1]+t[2]+...+t[k]<=x<t[1]+t[2]+...+t[k]+t[k+1], up to a given maximum value of k=n. My code is currently as follows:
def SumToN(x,n):
result = 0
for i in range(1,n+1):
result += x[i]
... | [
"You cannot create a compound inequality with symbols, only numbers. So 1<2<3 works but 1<Symbol('x')<3 must be written as x = Symbol('x'); And(1 < x, x < 3). Also, Piecewise does not work with an iterator, so try:\nPiecewise(*[((-1)^(k-1), And(SumToN(t,k)<=x, x<SumToN(t,k+1)))\n for k in range(1,n+1)])\n\n"
] | [
1
] | [] | [] | [
"indexing",
"piecewise",
"python",
"symbols",
"sympy"
] | stackoverflow_0074377163_indexing_piecewise_python_symbols_sympy.txt |
Q:
Is it appropriate to use OO-style interfaces and classes when all you really need is function-like behavior?
Is it appropriate to use OO-style interfaces and classes when all you really need is function-like behavior (i.e. no need to track or mutate state and the instance exists just to call its only exposed metho... | Is it appropriate to use OO-style interfaces and classes when all you really need is function-like behavior? | Is it appropriate to use OO-style interfaces and classes when all you really need is function-like behavior (i.e. no need to track or mutate state and the instance exists just to call its only exposed method once)?
For example, I often end up with (python) code that looks like this:
from abc import ABC, abstractmethod
... | [
"\nIs it appropriate to use OO-style interfaces and classes when all you really need is function-like behavior?\n\nNo. If all you need is a function, then you should use a function.\nIf someone says their implementation is complicated enough to warrant using a class, they can still do so by simply defining a class ... | [
1,
0
] | [] | [] | [
"class",
"function",
"functional_programming",
"oop",
"python"
] | stackoverflow_0073253685_class_function_functional_programming_oop_python.txt |
Q:
Need to add cookie to API header in opened web browser running with python selenium?
Now I am working with python selenium and I want to know one problem.
I am running js script in opened web browser
result = driver.execute_script('''
return await fetch("https://example.com", {
"headers": {
... | Need to add cookie to API header in opened web browser running with python selenium? | Now I am working with python selenium and I want to know one problem.
I am running js script in opened web browser
result = driver.execute_script('''
return await fetch("https://example.com", {
"headers": {
"accept": "application/json",
"accept-language": "en-US,en;q=... | [
"You can set credentials: \"include\" so that cookies and other credential-related info, like HTTP authentication entries and TLS client certificates are sent with the request. You can read more about it here.\nSomething like this should work:\nreturn await fetch(\"https://example.com\", {\n \"headers\": {\n ... | [
1
] | [] | [] | [
"javascript",
"python",
"selenium",
"selenium_webdriver"
] | stackoverflow_0074377464_javascript_python_selenium_selenium_webdriver.txt |
Q:
tkinter label and button grid placing
i have created window, in that window i put frame. Then i want to create two labels after them button widget.
But, button widget appears upper than second label widget even though i put btn in row=2, and label2 in row=1. It 's hard for me to get why?
from tkinter import *
wi... | tkinter label and button grid placing | i have created window, in that window i put frame. Then i want to create two labels after them button widget.
But, button widget appears upper than second label widget even though i put btn in row=2, and label2 in row=1. It 's hard for me to get why?
from tkinter import *
window=Tk()
window.geometry('620x540+33+33')
... | [
"You must pass the parent object when calling super, otherwise your custom object will always be a child of the root window.\nclass lbl_custom(Label):\n def __init__(self,frame_window):\n super().__init__(frame_window)\n # ^^^^^^^^^^^^\n\nYou can pass other options as well, which wil... | [
2
] | [] | [] | [
"button",
"grid",
"label",
"python",
"tkinter"
] | stackoverflow_0074373551_button_grid_label_python_tkinter.txt |
Q:
why Attention layer not improving my model's performance
I am working on a multi-label text classification problem. following given is my samples description
x_train shape: (8066, 3000)
x_test shape: (1729, 3000)
x_valid shape: (1573, 3000)
i implemented an RCNN model which gives me 60 MiF score on my data but wh... | why Attention layer not improving my model's performance | I am working on a multi-label text classification problem. following given is my samples description
x_train shape: (8066, 3000)
x_test shape: (1729, 3000)
x_valid shape: (1573, 3000)
i implemented an RCNN model which gives me 60 MiF score on my data but when i add attention layer to RCNN model still it is giving me s... | [
"I have made some changes try this, I have removed most of the things and then add some the things, Bi-directional LSTM most of the time in classification performs as equal to LSTM. SO, I removed it, and then I add Multihead Attention Layer. I have run this model and this is working fine. But one thing to notice he... | [
0
] | [] | [] | [
"deep_learning",
"keras",
"neural_network",
"python"
] | stackoverflow_0074375957_deep_learning_keras_neural_network_python.txt |
Q:
How to create order in admin after payment is completed
I'm making a website where you buy stuff and pay through PayPal.
I am done with the PayPal part now I am trying to get a situation where after the payment is complete in checkout the item purchased goes to orders in the admin.
This is the order model.py:
clas... | How to create order in admin after payment is completed | I'm making a website where you buy stuff and pay through PayPal.
I am done with the PayPal part now I am trying to get a situation where after the payment is complete in checkout the item purchased goes to orders in the admin.
This is the order model.py:
class Order (models.Model):
product = models.ForeignKey(Coinpac... | [
"Do not use actions.order.create() / actions.order.capture() to create and capture an order on the client side if you are then going to be doing server-side operations with the completed payment. Those JS functions are for simple use cases, not what you are trying to do.\nInstead, use PayPal's v2/checkout/orders AP... | [
0
] | [] | [] | [
"django",
"e_commerce",
"payment_gateway",
"paypal",
"python"
] | stackoverflow_0074377107_django_e_commerce_payment_gateway_paypal_python.txt |
Q:
Python: Pulling data using URL giving JSONDcodeError
I am trying to pull transactions for a list of addresses:
wallet_addresses = ['0x7abe0ce388281d2acf297cb089caef3819b13448', '0xC098B2a3Aa256D2140208C3de6543aAEf5cd3A94',
'0x2FAF487A4414Fe77e2327F0bf4AE2a264a776AD2']
for address in wallet_address... | Python: Pulling data using URL giving JSONDcodeError | I am trying to pull transactions for a list of addresses:
wallet_addresses = ['0x7abe0ce388281d2acf297cb089caef3819b13448', '0xC098B2a3Aa256D2140208C3de6543aAEf5cd3A94',
'0x2FAF487A4414Fe77e2327F0bf4AE2a264a776AD2']
for address in wallet_addresses:
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT... | [
"You're trying to convert the server's response into json, but it's not json. Try getting the raw content instead:\n...\nresult = response.content\nprint(content)\n\netherscan.io has an API, which should return the same data in a more easily consumable JSON format\n"
] | [
2
] | [] | [] | [
"json",
"python",
"python_requests",
"url"
] | stackoverflow_0074377849_json_python_python_requests_url.txt |
Q:
python move circle around another circle in graphics.py
I am writing a program in Python using graphics.py library. I want to draw two circles, and then in loop move one of them around another one. I know I have to use sin and cos function, but I have no idea what is a mathematical formula for that.
That's my code... | python move circle around another circle in graphics.py | I am writing a program in Python using graphics.py library. I want to draw two circles, and then in loop move one of them around another one. I know I have to use sin and cos function, but I have no idea what is a mathematical formula for that.
That's my code:
from graphics import *
from math import sin, cos, pi
from t... | [
"A bit of mathematics have to be used. Based on your example, you want the circles to be adjacent to each other.\nBecause of that, distance between their centres will always be r1+r2. This is a length of our vector. We need to split that vector into x axis and y axis parts. This is where sine and cosine functions c... | [
0
] | [] | [] | [
"graphics",
"python"
] | stackoverflow_0074377665_graphics_python.txt |
Q:
Updating large dataframe with around 6500 rows into xlsm file using Xlwings in python
I am trying to update excel file with extension .xlsm with ws[cellid].options(header=False, index=False).value = df.It doesn't contains empty columns or Nan values or any equations.But the same code is working when I try to updat... | Updating large dataframe with around 6500 rows into xlsm file using Xlwings in python | I am trying to update excel file with extension .xlsm with ws[cellid].options(header=False, index=False).value = df.It doesn't contains empty columns or Nan values or any equations.But the same code is working when I try to update few rows.When I try to execute I am getting this error
self._oleobj_.Invoke(*(args + (v... | [
"For big DataFrames, you can chunk the data like this:\nws[cellid].options(header=False, index=False, chunksize=10_000).value = df\n\nCheck out the documentation for options.\n"
] | [
0
] | [] | [] | [
"dataframe",
"python",
"pywin",
"xlwings"
] | stackoverflow_0074374941_dataframe_python_pywin_xlwings.txt |
Q:
How to ensure data is received between commands
I'm using Paramiko to issue a number of commands and collect results for further analysis. Every once in a while the results from the first command are note fully returned in time and end up in the output for the second command.
I'm attempting to use recv_ready to a... | How to ensure data is received between commands | I'm using Paramiko to issue a number of commands and collect results for further analysis. Every once in a while the results from the first command are note fully returned in time and end up in the output for the second command.
I'm attempting to use recv_ready to account for this, but it is not working, so I assume I... | [
"I would use transport directly and create a new channel for each command. Then you can use something like:\ndef issue_command(transport, pause, command):\n chan = transport.open_session()\n chan.exec_command(command)\n\n buff_size = 1024\n stdout = \"\"\n stderr = \"\"\n\n while not chan.exit_sta... | [
11,
0
] | [] | [] | [
"paramiko",
"python"
] | stackoverflow_0021083195_paramiko_python.txt |
Q:
How do I solve this Error with Array Dimensionality
I tried to follow a tutorial on Machine learning Algothim and I keep getting this error. It kept giving me this error I have tried all manner of debugging and still getting the same error message. What do I do?
Stack overflow doesn't want me to post all code so i... | How do I solve this Error with Array Dimensionality | I tried to follow a tutorial on Machine learning Algothim and I keep getting this error. It kept giving me this error I have tried all manner of debugging and still getting the same error message. What do I do?
Stack overflow doesn't want me to post all code so i tried to short the error message
import matplotlib.pyplo... | [
"If you look at your error, it states that the function expects a 2D array but you only passed a 1D array. This happens because predictedImage = numberImages.data[-4] returns a 1D array.\nIf you take another look at your stacktrace, you can see Reshape your data either using array.reshape(-1, 1) if your data has a ... | [
0
] | [] | [] | [
"python",
"scikit_learn"
] | stackoverflow_0074377994_python_scikit_learn.txt |
Q:
How to multiply this matrix?
How can I multiply such matrix as below?
I want to multiply A^2 * B , I have a code but it doesn't work.
import numpy as np
A = np.array([[0,-1,1], [3,2,2], [1,0,-2]])
B = np.array([[1,0], [2,1], [-2,7]])
print (A)
print(B)
C=A*A
print(C)
C*B
+I try t... | How to multiply this matrix? | How can I multiply such matrix as below?
I want to multiply A^2 * B , I have a code but it doesn't work.
import numpy as np
A = np.array([[0,-1,1], [3,2,2], [1,0,-2]])
B = np.array([[1,0], [2,1], [-2,7]])
print (A)
print(B)
C=A*A
print(C)
C*B
+I try to multiply A*B^2 so I write:
D=A@B... | [
"Here is the solution, let me know if this is what you are looking for.\n\nimport numpy as np\n\nA = np.array([[0,-1,1], [3,2,2], [1,0,-2]])\nB = np.array([[1,0], [2,1], [-2,7]])\nprint (A)\nprint(B)\n\nC= A @ A @ B\nprint(C)\n\n\n[[ 0 -1 1]\n [ 3 2 2]\n [ 1 0 -2]]\n[[ 1 0]\n [ 2 1]\n [-2 7]]\n[[ 2 -30]\n [... | [
0,
0
] | [] | [] | [
"matrix",
"python"
] | stackoverflow_0058559405_matrix_python.txt |
Q:
Assignment a values to columns inside df.apply()
I need to assign multiple values to multiple columns inside a pandas.DataFrame.
What I want to do looks like that:
df.apply(
lambda x: x['card_{}'.format(card)] = score
for card, score in zip(
x['card_id'].split('|'),
x['score_id'].s... | Assignment a values to columns inside df.apply() | I need to assign multiple values to multiple columns inside a pandas.DataFrame.
What I want to do looks like that:
df.apply(
lambda x: x['card_{}'.format(card)] = score
for card, score in zip(
x['card_id'].split('|'),
x['score_id'].split('|')
),
axis=1
)
How can I do it wi... | [
"You can create a function\ndef assign_card(row):\n for card, score in zip(x['card_id'].split('|'),\n x['score_id'].split('|')):\n row['card_{}'.format(card)] = score\n return row\n\ndf = df.apply(assign_card, axis=1)\n\n"
] | [
0
] | [] | [] | [
"pandas",
"pandas_apply",
"python"
] | stackoverflow_0074363229_pandas_pandas_apply_python.txt |
Q:
Convert words between verb/noun/adjective forms
i would like a python library function that translates/converts across different parts of speech. sometimes it should output multiple words (e.g. "coder" and "code" are both nouns from the verb "to code", one's the subject the other's the object)
# :: String => List ... | Convert words between verb/noun/adjective forms | i would like a python library function that translates/converts across different parts of speech. sometimes it should output multiple words (e.g. "coder" and "code" are both nouns from the verb "to code", one's the subject the other's the object)
# :: String => List of String
print verbify('writer') # => ['write']
prin... | [
"This is more a heuristic approach. I have just coded it so appologies for the style. It uses the derivationally_related_forms() from wordnet. I have implemented nounify. I guess verbify works analogous. From what I've tested works pretty well:\nfrom nltk.corpus import wordnet as wn\n\ndef nounify(verb_word):\n ... | [
23,
14,
4,
3,
0
] | [] | [] | [
"nlp",
"nltk",
"python",
"wordnet"
] | stackoverflow_0014489309_nlp_nltk_python_wordnet.txt |
Q:
Limiting user input to number of variables when using split() to prevent 'ValueError: too many values to unpack'?
a,b = map(int, input().split())
In the above code or anything similar, we use split to separate multiple inputs on a single line, typically separated with a space, and assign the results to the variab... | Limiting user input to number of variables when using split() to prevent 'ValueError: too many values to unpack'? | a,b = map(int, input().split())
In the above code or anything similar, we use split to separate multiple inputs on a single line, typically separated with a space, and assign the results to the variables.
This is very convenient feature, however I am facing a problem:
Say I want to populate a list A with n integers in... | [
"You can catch any additional unwanted values with an asterisk (an underscore typically represents an unused variable):\na, b, *_ = map(int, input().split())\n\nThis will place any additional inputs into a list called _. Note that this method requires at least two input values separated by a space.\n",
"Your idea... | [
1,
0
] | [] | [] | [
"python",
"split",
"user_input",
"valueerror"
] | stackoverflow_0074378065_python_split_user_input_valueerror.txt |
Q:
Tensorflow Model Fit : AttributeError: 'numpy.dtype[float64]' object has no attribute 'is_floating'
I develop a model using Tensorflow 2.9.1.
My inputs are like this :
x = [...] # Array of 24 floats
y = 0.0
When I process this data :
x = tf.convert_to_tensor(x, dtype=tf.float32)
x = tf.reshape(x, shape=(1,24))
x.... | Tensorflow Model Fit : AttributeError: 'numpy.dtype[float64]' object has no attribute 'is_floating' | I develop a model using Tensorflow 2.9.1.
My inputs are like this :
x = [...] # Array of 24 floats
y = 0.0
When I process this data :
x = tf.convert_to_tensor(x, dtype=tf.float32)
x = tf.reshape(x, shape=(1,24))
x.dtype.is_floating # Is True
y = tf.convert_to_tensor(y, dtype=tf.float32)
y = tf.reshape(y, shape=(1, 1)... | [
"Probably, you have larger float values in the x array which is taken as float64. However I tried the same code with TF 2.9 in Google Colab and it does not show any error.\nimport numpy as np\nimport tensorflow as tf\nx=np.arange(0.0, 24.0)\nprint(x)\n#x = [...] # Array of 24 floats\ny = 0.0\nprint(y)\n\nx = tf.con... | [
0
] | [] | [] | [
"data_fitting",
"numpy",
"python",
"tensorflow"
] | stackoverflow_0074170725_data_fitting_numpy_python_tensorflow.txt |
Q:
Troubles with Python School assingment
I am trying to output
Grace was planning a dream vacation to Paris.
Grace was especially looking forward to trying the local
cuisine, including stinky soup and bananas.
Grace will have to practice the language quietly to
make it easier to jump with people.
Grace has a long ... | Troubles with Python School assingment | I am trying to output
Grace was planning a dream vacation to Paris.
Grace was especially looking forward to trying the local
cuisine, including stinky soup and bananas.
Grace will have to practice the language quietly to
make it easier to jump with people.
Grace has a long list of sights to see, including the
button ... | [
"The problem in here is the first comma. Python doesn't allow commas with nothing before them. There is a such a comma in the very beginning, after print( and there's an other one in abj1+ ,food1. The example won't crash anymore when you these commas.\nHowever, the output will look as follows:\nLet's play Sill Se... | [
3
] | [
"print( , name + \"was planning a dream vacation to \" ,place +\".\",name+ \"was especially looking forward to trying the local cusine,including \",abj1+ ,food1+\"and \",food2)\n\nThis is wrong. First of all, ypu put a comma at the start. Remove it.\nprint( name + \"was planning a dream vacation to \" ,place +\".\"... | [
-1
] | [
"python"
] | stackoverflow_0074349666_python.txt |
Q:
How do I get indices of N maximum values in a NumPy array?
NumPy proposes a way to get the index of the maximum value of an array via np.argmax.
I would like a similar thing, but returning the indexes of the N maximum values.
For instance, if I have an array, [1, 3, 2, 4, 5], then nargmax(array, n=3) would return ... | How do I get indices of N maximum values in a NumPy array? | NumPy proposes a way to get the index of the maximum value of an array via np.argmax.
I would like a similar thing, but returning the indexes of the N maximum values.
For instance, if I have an array, [1, 3, 2, 4, 5], then nargmax(array, n=3) would return the indices [4, 3, 1] which correspond to the elements [5, 4, 3]... | [
"Newer NumPy versions (1.8 and up) have a function called argpartition for this. To get the indices of the four largest elements, do\n>>> a = np.array([9, 4, 4, 3, 3, 9, 0, 4, 6, 0])\n>>> a\narray([9, 4, 4, 3, 3, 9, 0, 4, 6, 0])\n\n>>> ind = np.argpartition(a, -4)[-4:]\n>>> ind\narray([1, 5, 8, 0])\n\n>>> top4 = a[... | [
912,
490,
75,
50,
44,
15,
14,
10,
7,
5,
4,
4,
1,
1,
0,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"max",
"numpy",
"numpy_ndarray",
"python"
] | stackoverflow_0006910641_max_numpy_numpy_ndarray_python.txt |
Q:
Unable to install Pillow module
I am unable to install PIL/Pillow using pip command
C:\Users\Username>pip install Pillow
Collecting Pillow
Using cached Pillow-9.3.0.tar.gz (50.4 MB)
Preparing metadata (setup.py) ... done
Installing collected packages: Pillow
DEPRECATION: Pillow is being installed using the l... | Unable to install Pillow module | I am unable to install PIL/Pillow using pip command
C:\Users\Username>pip install Pillow
Collecting Pillow
Using cached Pillow-9.3.0.tar.gz (50.4 MB)
Preparing metadata (setup.py) ... done
Installing collected packages: Pillow
DEPRECATION: Pillow is being installed using the legacy 'setup.py install' method, beca... | [
"As mentioned in Error:\nThe headers or library files could not be found for zlib, a required dependency when compiling Pillow from source.\n\nYou might try to install zlib first and then install Pillow by\npython3 -m pip install --upgrade pip\npython3 -m pip install --upgrade Pillow\n\nThere is also warning in the... | [
0
] | [] | [] | [
"pip",
"python",
"python_3.x",
"python_imaging_library"
] | stackoverflow_0074378063_pip_python_python_3.x_python_imaging_library.txt |
Q:
How to make a only 1 window GUI in python?
I am trying to make a GUI in python that only consists of 1 window. I think this is better explained with examples. If you have say the settings app open on the computer when you click an option a new window doesn't pop up, the original window changes the a new layout. Is... | How to make a only 1 window GUI in python? | I am trying to make a GUI in python that only consists of 1 window. I think this is better explained with examples. If you have say the settings app open on the computer when you click an option a new window doesn't pop up, the original window changes the a new layout. Is there a way to do this without deleting everyth... | [
"If you're using a QT based gui framework like PyQT or PySimpleGUI, you can accomplish this task using a Tab object. Here is a link to a sample program with using Tabs in PySimpleGUI\nPySimpleGUI is a really good option for getting your feet wet with GUI development in Python. You can get a lot done with very littl... | [
1
] | [] | [] | [
"python",
"user_interface",
"window"
] | stackoverflow_0074377779_python_user_interface_window.txt |
Q:
Count number of words in a spark dataframe
How can we find the number of words in a column of a spark dataframe without using REPLACE() function of SQL ? Below is the code and input I am working with but the replace() function does not work.
from pyspark.sql import SparkSession
my_spark = SparkSession \
.build... | Count number of words in a spark dataframe | How can we find the number of words in a column of a spark dataframe without using REPLACE() function of SQL ? Below is the code and input I am working with but the replace() function does not work.
from pyspark.sql import SparkSession
my_spark = SparkSession \
.builder \
.appName("Python Spark SQL example") \
... | [
"\nThere are number of ways to count the words using pyspark DataFrame functions, depending on what it is you are looking for.\nCreate Example Data\nimport pyspark.sql.functions as f\ndata = [\n (\"2015-05-14 03:53:00\", \"WARRANT ARREST\"),\n (\"2015-05-14 03:53:00\", \"TRAFFIC VIOLATION\"),\n (\"2015-05-... | [
41,
2,
1,
0
] | [] | [] | [
"apache_spark",
"apache_spark_sql",
"pyspark",
"python"
] | stackoverflow_0048927271_apache_spark_apache_spark_sql_pyspark_python.txt |
Q:
having error while using 'Series' object has no attribute 'ix'
'Series' object has no attribute 'ix'
refer this image (https://i.stack.imgur.com/yLm32.png)](https://i.stack.imgur.com/yLm32.png)
A:
I believe .iloc is used for Series instead of .ix.
| having error while using 'Series' object has no attribute 'ix' | 'Series' object has no attribute 'ix'
refer this image (https://i.stack.imgur.com/yLm32.png)](https://i.stack.imgur.com/yLm32.png)
| [
"I believe .iloc is used for Series instead of .ix.\n"
] | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074378288_pandas_python.txt |
Q:
Sending/Receiving data between two different programs
I'm looking for some advice mainly here.
I'm working on an application, where the main processing (stored on a server) is carried out in C++ and the GUI (front-end) is carried out in Python. These two programs will communicate with each other. The Python will s... | Sending/Receiving data between two different programs | I'm looking for some advice mainly here.
I'm working on an application, where the main processing (stored on a server) is carried out in C++ and the GUI (front-end) is carried out in Python. These two programs will communicate with each other. The Python will send across the files needed for the C++ program to work, an... | [
"Try ZeroMQ\n\nØMQ (also known as ZeroMQ, 0MQ, or zmq) looks like an embeddable\n networking library but acts like a concurrency framework. It gives you\n sockets that carry atomic messages across various transports like\n in-process, inter-process, TCP, and multicast. You can connect sockets\n N-to-N with patt... | [
4,
0,
0,
0
] | [
"Python is based on C++ and it's it like improvement.\nIf you want to send it between these applications on one computer, you can use file mapping.\nhttp://msdn.microsoft.com/en-us/library/windows/desktop/aa366551(v=vs.85).aspx\nImo it's oen of the best ways how to do that.\nBut, if you want to send it between two ... | [
-1
] | [
"c++",
"python",
"sockets"
] | stackoverflow_0020839944_c++_python_sockets.txt |
Q:
Convert a list of integers to a list of consecutive positive integers
I came up with this code to convert a list of already ordered integers into a list of consecutive positive integers.
def consecutive_positive_inc(l):
"""
[0, 1, 1, 3, 4, 4, 5] -> [0, 1, 1, 2, 3, 3, 4]
"""
from collections import ... | Convert a list of integers to a list of consecutive positive integers | I came up with this code to convert a list of already ordered integers into a list of consecutive positive integers.
def consecutive_positive_inc(l):
"""
[0, 1, 1, 3, 4, 4, 5] -> [0, 1, 1, 2, 3, 3, 4]
"""
from collections import defaultdict
d = defaultdict(int)
for i in l:
d[i] += 1
... | [
"I think you've made it more complicated than it needs to be. Just keep a counter and bump when the number changes.\ndef consecutive_positive_inc(l):\n \"\"\"\n [0, 1, 1, 3, 4, 4, 5] -> [0, 1, 1, 2, 3, 3, 4]\n \"\"\"\n last = l[0]\n idx = 0\n for i in l:\n if i != last:\n idx +=... | [
5,
1,
0,
0
] | [
"\n\n\nfrom collections import Counter\ndef consecutive_positive_inc(arr):\n... return [i for i, count in enumerate(Counter(arr).values()) for _ in range(count)]\n...\nconsecutive_positive_inc([0, 1, 1, 3, 4, 4, 5])\n[0, 1, 1, 2, 3, 3, 4]\n\n\n\n"
] | [
-1
] | [
"python"
] | stackoverflow_0073243281_python.txt |
Q:
Count NA and none-NA per group in pandas
I assume this is a simple task for pandas but I don't get it.
I have data liket this
Group Val
0 A 0
1 A 1
2 A <NA>
3 A 3
4 B 4
5 B <NA>
6 B 6
7 B <NA>
And I want to know the frequency of valid and invalid values i... | Count NA and none-NA per group in pandas | I assume this is a simple task for pandas but I don't get it.
I have data liket this
Group Val
0 A 0
1 A 1
2 A <NA>
3 A 3
4 B 4
5 B <NA>
6 B 6
7 B <NA>
And I want to know the frequency of valid and invalid values in Val per group Group. This is the expected re... | [
"You are close with using groupby and isna\nnew = df.groupby(['Group', df['Val'].isna().replace({True: 'NA', False: 'Valid'})])['Group'].count().unstack(level=0)\nnew['Total'] = new.sum(axis=1)\nprint(new)\n\nGroup A B Total\nVal \nNA 1 2 3\nValid 3 2 5\n\n",
"here is one way to ... | [
2,
1,
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074378057_pandas_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.