content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
python automating data collection issue
Is there any wrong with my code here, when I want to automate collecting some data from the web:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected... | python automating data collection issue | Is there any wrong with my code here, when I want to automate collecting some data from the web:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import requests
from bs4 im... | [
"It looks like there may be a problem with the finally clause in your code. The finally clause is executed whether or not an exception is thrown in the try clause, and it is typically used to clean up resources, such as closing open files or network connections. In your code, the finally clause is executing even wh... | [
0
] | [] | [] | [
"forum",
"html",
"python",
"web_scraping"
] | stackoverflow_0074664317_forum_html_python_web_scraping.txt |
Q:
How can I make a statement go through even though there's a needed break statement?
My instructions are to help a child their way home. For example if the input is:
R
-JOHN
-L
-KING
-L
-SCHOOL
this means that to get to school from his has he had to turn right on john, left on king, and left to school
The output ... | How can I make a statement go through even though there's a needed break statement? | My instructions are to help a child their way home. For example if the input is:
R
-JOHN
-L
-KING
-L
-SCHOOL
this means that to get to school from his has he had to turn right on john, left on king, and left to school
The output needs to help him find his way back home an example of this is:
R
KING
-R
-JOHN
-L
-HOME... | [
"Firstly, you are checking if street is school way early before even appending it. This causes your loop to break and the data for school direction isn't updated.\nNext, you don't need to reverse your list again in the end since it is already in the order you require. So remove [::-1]. Here's the fixed code:\ndirec... | [
0
] | [] | [] | [
"counter",
"list",
"python"
] | stackoverflow_0074664350_counter_list_python.txt |
Q:
Using multiple datasets in Gridspec
I am trying to create subplot inside a subplot, and I have found some code which can do this using the gridspec method. I have managed to fix the code so the figures are displayed as I want, but I can't figure out how to get a different dataset in each sub-figure.
This is what I... | Using multiple datasets in Gridspec | I am trying to create subplot inside a subplot, and I have found some code which can do this using the gridspec method. I have managed to fix the code so the figures are displayed as I want, but I can't figure out how to get a different dataset in each sub-figure.
This is what I have:
import matplotlib.pyplot as plt
im... | [
"I have managed to solve my problem now. What I did was, instead of trying to put multple ax.plot() lines or putting multiple DataFrames inside ax.plot(df1, df2, df3) etc. I created a list which I put inside the For Loop. I also created a column variable to go in the \"inner loop\".\nIf using Nested Loops like this... | [
0
] | [] | [] | [
"python",
"subplot"
] | stackoverflow_0074661191_python_subplot.txt |
Q:
How to install OpenCV in Mac M1?
My goal is to install $ pip install opencv-python in Mac M1. The problem is I don't know opencv, so I would like to learn from the Getting Started Page. However, the very first code of opencv throws me an error.
What I've did:
$ pip install opencv-python -> same error
$ pip uninst... | How to install OpenCV in Mac M1? | My goal is to install $ pip install opencv-python in Mac M1. The problem is I don't know opencv, so I would like to learn from the Getting Started Page. However, the very first code of opencv throws me an error.
What I've did:
$ pip install opencv-python -> same error
$ pip uninstall opencv-python -> $ pip install ope... | [
"It looks like the cv.imread() function is unable to find the image file \"starry_night.jpg\" in your current directory. This is likely because the findFile() function is returning an empty string, which indicates that the file could not be found.\nTo fix this issue, you will need to make sure that the \"starry_nig... | [
0
] | [] | [] | [
"apple_m1",
"opencv",
"python"
] | stackoverflow_0074664356_apple_m1_opencv_python.txt |
Q:
How to write by column rather than rows - Python to CSV
I want to write my python list all_results to CSV. However when I use the following code, it saves each individual record in rows rather than columns.
import csv
fh = open('output.csv', 'w')
cvs_writer = csv.writer(fh)
# write one row with headers (using `wr... | How to write by column rather than rows - Python to CSV | I want to write my python list all_results to CSV. However when I use the following code, it saves each individual record in rows rather than columns.
import csv
fh = open('output.csv', 'w')
cvs_writer = csv.writer(fh)
# write one row with headers (using `writerow` without `s` at the end)
cvs_writer.writerow(["Column ... | [
"To write all rows in a single column, you can use a list comprehension to create a list of lists, where each inner list contains a single item. You can then write the resulting list using the writerows method of the csv module.\nHere is an example:\nimport csv\n\n# Create a list of lists, where each inner list con... | [
1
] | [] | [] | [
"export_to_csv",
"python"
] | stackoverflow_0074664313_export_to_csv_python.txt |
Q:
How to write value != '' in Python Pandas
I dont know how to write a blank value, no data; not null; (!= '') in pandas. Below is an example that I am using.
df['Column4'] = np.where(df['Column1'].notnull(), 'Yes',
np.where(df['Column2']== 0, 'NO',
np.where(df['Column2'].notnull(), (df... | How to write value != '' in Python Pandas | I dont know how to write a blank value, no data; not null; (!= '') in pandas. Below is an example that I am using.
df['Column4'] = np.where(df['Column1'].notnull(), 'Yes',
np.where(df['Column2']== 0, 'NO',
np.where(df['Column2'].notnull(), (df['Column2']),
np.where(df['Colum... | [
"You can use the notnull method of a pandas dataframe to check if a column contains any non-null values, and then use the np.where function to write the appropriate value based on that check. Here is an example:\n# create a sample dataframe with some null values\ndf = pd.DataFrame({'Column1': [1, 2, None, 3],\n ... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074664374_pandas_python.txt |
Q:
Accesing the parent __init__ variable to Child Python
Hello im trying to make a oop function but im currently stuck on how can i inherit the __init__ arguments of my parent class to the child class, is there a method that can i use to adapt the variable from my main to use in child?
class a:
def __init__(self,... | Accesing the parent __init__ variable to Child Python | Hello im trying to make a oop function but im currently stuck on how can i inherit the __init__ arguments of my parent class to the child class, is there a method that can i use to adapt the variable from my main to use in child?
class a:
def __init__(self, name):
self.name = name
class b(a):
d... | [
"In the b class, you need to include the name argument in the __init__ method and pass it to the super() method as shown below:\nclass a:\n def __init__(self, name):\n self.name = name\n \nclass b(a):\n def __init__(self, name, age):\n super().__init__(name)\n self.age = age\n\nNow... | [
0,
0
] | [] | [] | [
"oop",
"python",
"python_3.x"
] | stackoverflow_0074664396_oop_python_python_3.x.txt |
Q:
tensorflow.python.framework.errors_impl.ResourceExhaustedError: failed to allocate memory [Op:AddV2]
Hi I am a beginner in DL and tensorflow,
I created a CNN (you can see the model below)
model = tf.keras.Sequential()
model.add(tf.keras.layers.Conv2D(filters=64, kernel_size=7, activation="relu", input_shape=[512,... | tensorflow.python.framework.errors_impl.ResourceExhaustedError: failed to allocate memory [Op:AddV2] | Hi I am a beginner in DL and tensorflow,
I created a CNN (you can see the model below)
model = tf.keras.Sequential()
model.add(tf.keras.layers.Conv2D(filters=64, kernel_size=7, activation="relu", input_shape=[512, 640, 3]))
model.add(tf.keras.layers.MaxPooling2D(2))
model.add(tf.keras.layers.Conv2D(filters=128, kernel... | [
"The error is telling you that it couldn't allocate as much VRAM as you are using. The easiest way to overcome this kind of problem is to reduce to batch-size to a number that fits on your GPU's VRAM.\n",
"The error message you received tensorflow.python.framework.errors_impl.ResourceExhaustedError: failed to all... | [
7,
4,
0,
0
] | [] | [] | [
"conv_neural_network",
"deep_learning",
"gpu",
"python",
"tensorflow"
] | stackoverflow_0069641708_conv_neural_network_deep_learning_gpu_python_tensorflow.txt |
Q:
How to add new video files to HLS?
I'm having trouble live streaming a video file that is constantly updated using HLS.
Video files recorded by POST from the client are sent to the server.
The server converts the received video to HLS (.m3u8 .ts).
You can convert to .m3u8 and .ts with the following code.
def to_m3... | How to add new video files to HLS? | I'm having trouble live streaming a video file that is constantly updated using HLS.
Video files recorded by POST from the client are sent to the server.
The server converts the received video to HLS (.m3u8 .ts).
You can convert to .m3u8 and .ts with the following code.
def to_m3u8(movie_path: Path):
"""
Conver... | [
"To make sure that the HLS stream is constantly updated, you can use the -hls_flags append_list option in the ffmpeg command that you are using to create the HLS stream. This option will make sure that the HLS playlist is constantly updated with new segments as they are added, so that the stream is always up-to-dat... | [
0
] | [] | [] | [
"ffmpeg",
"http_live_streaming",
"python"
] | stackoverflow_0074664406_ffmpeg_http_live_streaming_python.txt |
Q:
python continue download from where I left off
I'm trying to download a very large file in collab to my gDrive. Sometimes the connection cuts out, and It requires I restart. Is there a way I can download from where I left off?
My code looks like so:
from requests import get
import sys
def download(url, file_nam... | python continue download from where I left off | I'm trying to download a very large file in collab to my gDrive. Sometimes the connection cuts out, and It requires I restart. Is there a way I can download from where I left off?
My code looks like so:
from requests import get
import sys
def download(url, file_name):
# open in binary mode
with open(file_nam... | [
"To download a file from a specific point, you can use the Range request header to specify the byte range that you want to download. For example, to download the last 100 bytes of a file, you can use the following code:\nfrom requests import get\nimport sys\n\ndef download(url, file_name, start_byte, end_byte):\n ... | [
1
] | [] | [] | [
"download",
"python"
] | stackoverflow_0074664425_download_python.txt |
Q:
Is there any difference between manualluy login and selenium-python?
There are two method.
First, launch chrome debugging mode by using os.system() module and manually login, then connect selenium to get page source.
Second, launch and login are also controlled by selenium, Then get page source.
Because too diffic... | Is there any difference between manualluy login and selenium-python? | There are two method.
First, launch chrome debugging mode by using os.system() module and manually login, then connect selenium to get page source.
Second, launch and login are also controlled by selenium, Then get page source.
Because too difficult to login webpage(2 session needed), i didn't try second method.
So, i ... | [
"There may be a difference between manually logging in to a website and using Selenium to login to the same website. This difference may be due to a number of factors, such as the way in which the website authenticates users, the specific actions that are performed during the login process, and the way in which the... | [
1
] | [] | [] | [
"python",
"selenium"
] | stackoverflow_0074664211_python_selenium.txt |
Q:
Can we use the "SInce" and "Until" option in TWEEPY to fetch tweets from a specific date?
Actually, I am working on a project which collects tweets if we pass a certain keyword. For ex. If I pass the keyword as "Messi", it will collect every tweets regarding Messi. We are passing the parameters as "query" and "no ... | Can we use the "SInce" and "Until" option in TWEEPY to fetch tweets from a specific date? | Actually, I am working on a project which collects tweets if we pass a certain keyword. For ex. If I pass the keyword as "Messi", it will collect every tweets regarding Messi. We are passing the parameters as "query" and "no of tweets". No of tweets will restrict the count of tweets that we need. So, tweepy collects th... | [
"Yes, you can use the since and until parameters in the tweepy code to collect tweets within a certain timeline. These parameters can be passed as part of the query parameter in the Cursor object when calling the Cursor.items() method.\nHere is an example of how you can use these parameters:\nimport tweepy\n\n# aut... | [
0
] | [] | [] | [
"postman",
"python",
"tweepy",
"twitter_api_v2"
] | stackoverflow_0074664447_postman_python_tweepy_twitter_api_v2.txt |
Q:
count the number of values in data frame's column that exist in another data frame's column
I have two data frames:
df1:
Index
Date
0
2016-03-21 20:10:00
1
2016-03-22 21:09:00
2
2016-05-03 17:05:00
df2:
Index
Date
0
2016-03-21 20:10:00
1
2016-03-21 21:00:00
2
2016-03-22 21:09:00
3
2016-05-03 17:05:00
4
... | count the number of values in data frame's column that exist in another data frame's column | I have two data frames:
df1:
Index
Date
0
2016-03-21 20:10:00
1
2016-03-22 21:09:00
2
2016-05-03 17:05:00
df2:
Index
Date
0
2016-03-21 20:10:00
1
2016-03-21 21:00:00
2
2016-03-22 21:09:00
3
2016-05-03 17:05:00
4
2017-06-01 16:10:00
There's probably a really simple way to do this but ... | [
"The simplest approach to solve your problem will be use set intersection(find common element from set).\nEg:\ndf1=pd.DataFrame({\"date\":['2016-03-21 20:10:00','2016-03-22 21:09:00','2016-05-03 17:05:00']})\n\ndf2=pd.DataFrame({\"date\":['2016-03-21 20:10:00','2016-03-21 21:00:00',\n '2016-03-22 21:... | [
0,
0
] | [] | [] | [
"count",
"date",
"pandas",
"python"
] | stackoverflow_0074664246_count_date_pandas_python.txt |
Q:
Illegalargumentexception : java.net.URISyntaxException : Relative path in absolute path URI getting while reading json files recursively from ADLSS
Folder structure:
A -> B1->C1->.json
-> B2->C2->.json
There can be many folders under A and B which doesn't follow any pattern.
The above is the folder structure i... | Illegalargumentexception : java.net.URISyntaxException : Relative path in absolute path URI getting while reading json files recursively from ADLSS | Folder structure:
A -> B1->C1->.json
-> B2->C2->.json
There can be many folders under A and B which doesn't follow any pattern.
The above is the folder structure in ADLS while reading Json files recursively using spark we are getting below error.
java.net.URISyntaxException : Relative path in absolute path URI
de... | [
"You might need to modify the sourceFilePath variable to include the full URI of the file you want to load, including the scheme (e.g. adl:// or wasbs://) and the hostname or storage account name. For example:\nsourceFilePath = 'adl://<storage_account_name>.dfs.core.windows.net/mnt/pp-working-1/A'\n\nYou can also t... | [
0
] | [] | [] | [
"azure_data_lake",
"databricks",
"pyspark",
"python"
] | stackoverflow_0074664413_azure_data_lake_databricks_pyspark_python.txt |
Q:
How can I efficiently randomly select items from a dictionary that meet my requirements?
So at the moment, I have a large dictionary of items. Might be a little confusing, but each of these keys have different values, and the values themselves correspond to another dictionary.
I need to make sure that my random se... | How can I efficiently randomly select items from a dictionary that meet my requirements? | So at the moment, I have a large dictionary of items. Might be a little confusing, but each of these keys have different values, and the values themselves correspond to another dictionary.
I need to make sure that my random selection from the first dict covers all possible values in the second dict. I'll provide a rudi... | [
"One way to improve the efficiency of your method is to first create a set of all the numbers in Dict 2 and then iterate through Dict 1, adding the corresponding numbers from Dict 2 to a temporary set. Then, you can check if the temporary set is a subset of the set of all numbers from 1 to 10. If it is, you can ret... | [
0
] | [] | [] | [
"dictionary",
"python",
"random",
"set",
"subset"
] | stackoverflow_0074664141_dictionary_python_random_set_subset.txt |
Q:
How to solve "ModuleNotFoundError: No module named 'tensorflow.tsl'"?
I installed python but didn't work. Then all of the following but when, I was supposed to import the following it didn't work.
!pip install -U pip
!pip install tensorflow
from tensorflow import keras
from tensorflow.keras import layers
A:
I ... | How to solve "ModuleNotFoundError: No module named 'tensorflow.tsl'"? | I installed python but didn't work. Then all of the following but when, I was supposed to import the following it didn't work.
!pip install -U pip
!pip install tensorflow
from tensorflow import keras
from tensorflow.keras import layers
| [
"I think you can try to run pip install tensorflow in command\n",
"If you're having trouble importing a package in Python, it's possible that you haven't installed it properly or that it's not installed at all. To check if tensorflow is installed, you can try running pip freeze in your terminal. This will print o... | [
1,
0
] | [] | [] | [
"python",
"python_3.x",
"tensorflow"
] | stackoverflow_0074664203_python_python_3.x_tensorflow.txt |
Q:
how to assume roles twice (or multiple times) in the script
I am trying to assume a role twice in the script, I assume the role first like this
import boto3 session = boto3.Session(profile_name="learnaws-test")
sts = session.client("sts")
response = sts.assume_role(
RoleArn="arn:aws:iam::xxx:role/s3-readonly-acces... | how to assume roles twice (or multiple times) in the script | I am trying to assume a role twice in the script, I assume the role first like this
import boto3 session = boto3.Session(profile_name="learnaws-test")
sts = session.client("sts")
response = sts.assume_role(
RoleArn="arn:aws:iam::xxx:role/s3-readonly-access",
RoleSessionName="learnaws-test-session"
)
new_session = Sessi... | [
"Call AssumeRole\nWhen calling AssumeRole(), a new set of credentials is returned. You can then use these credentials to create new clients, including another Security Token Service (STS) client that can be used to call AssumeRole() again.\nHere is an example:\nimport boto3\n\n# Create STS client using default cred... | [
0
] | [] | [] | [
"amazon_web_services",
"assume_role",
"boto3",
"python"
] | stackoverflow_0074657438_amazon_web_services_assume_role_boto3_python.txt |
Q:
Append dictionary in json using Python
I am doing my first Python program and its Hangman game. I managed to make it work but as a part of the task I need to write "best results -hall of fame" table as json file. Each entry in the table should consist of name of the person and the result they achieved (number of t... | Append dictionary in json using Python | I am doing my first Python program and its Hangman game. I managed to make it work but as a part of the task I need to write "best results -hall of fame" table as json file. Each entry in the table should consist of name of the person and the result they achieved (number of tries before guessing a word). My idea is to ... | [
"you should read your old json content. then append new item to it. an finally write it to your json file again. use code below:\nwith open (\"hall.json\") as f:\n dct=json.load(f)\n\n#add new item to dct\ndct.update(hall_of_fame)\n\n#write new dct to json file\nwith open(\"hall.json\",\"w\") as f:\n json.dum... | [
1,
0
] | [] | [] | [
"append",
"dictionary",
"json",
"python"
] | stackoverflow_0074663995_append_dictionary_json_python.txt |
Q:
How do I run my main function in parallel with a multiprocessing.Process without it freezing? (sorry for the sloppy code, I'm new and self taught)
My main function is an app that I want to use for macros, the macros themselves all work as intended, and the function is technically able to work. The issue arises wh... | How do I run my main function in parallel with a multiprocessing.Process without it freezing? (sorry for the sloppy code, I'm new and self taught) | My main function is an app that I want to use for macros, the macros themselves all work as intended, and the function is technically able to work. The issue arises when you start the function, as you can't interact with the GUI because it is frozen, it unfreezes when the function ends and then the GUI becomes usable ... | [
"It looks like you're trying to use multiple threads to run your macros simultaneously. However, the GUI freezes because you're blocking the main thread, which is responsible for updating the GUI.\nTo fix this, you need to make sure that your macro functions are non-blocking, i.e. they don't freeze the main thread.... | [
0
] | [] | [] | [
"multiprocessing",
"python",
"tkinter"
] | stackoverflow_0074664305_multiprocessing_python_tkinter.txt |
Q:
How can I slow down the refresh rate in pygame?
I'm new to python and I'm trying to make a simple platformer game using pygame. My issue is that when I use a while loop to make a block fall until it hits the bottom of the screen, it travels there all at once and I can't see it happening. However when I move the bl... | How can I slow down the refresh rate in pygame? | I'm new to python and I'm trying to make a simple platformer game using pygame. My issue is that when I use a while loop to make a block fall until it hits the bottom of the screen, it travels there all at once and I can't see it happening. However when I move the block side to side using if statements, I can see that ... | [
"If you want it to fully 'animate' down, you should add the code that keeps the pygame screen/player updating in your while loop, otherwise you're just changing the y without changing the screen. So your code would look somewhat like this:\nclock = pygame.time.Clock()\nfps = 60\nrun = True\nwhile run:\n clock.ti... | [
1
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0074664312_pygame_python.txt |
Q:
do you have to pass SSO profile credentials in order to assume the IAM role using boto3
I have my config file set up with multiple profiles and I am trying to assume an IAM role, but all the articles I see about assuming roles are starting with making an sts client using
import boto3 client = boto3.client('sts')
... | do you have to pass SSO profile credentials in order to assume the IAM role using boto3 | I have my config file set up with multiple profiles and I am trying to assume an IAM role, but all the articles I see about assuming roles are starting with making an sts client using
import boto3 client = boto3.client('sts')
which makes sense but the only problem is, It gives me an error when I try to do it like this... | [
"Yes. This line:\nsts = session.client(\"sts\")\n\ntells boto3 to create a session using the default credentials.\nThe credentials can be provided in the ~/.aws/credentials file. If the code is running on an Amazon EC2 instance, boto3 will automatically use credentials associated with the IAM Role associated with t... | [
0
] | [] | [] | [
"amazon_iam",
"amazon_web_services",
"assume_role",
"boto3",
"python"
] | stackoverflow_0074656007_amazon_iam_amazon_web_services_assume_role_boto3_python.txt |
Q:
C# gives me different result of ModPow from Java & Python. Is this a bug?
all
I am Joshua.
Currently I am developing some kind of calculation logic in C#, .NET 4.7.
And I am stuck for a couple of days when using ModPow from BigInteger class.
Finally I compared with some other languages like Javascript and Python.
... | C# gives me different result of ModPow from Java & Python. Is this a bug? | all
I am Joshua.
Currently I am developing some kind of calculation logic in C#, .NET 4.7.
And I am stuck for a couple of days when using ModPow from BigInteger class.
Finally I compared with some other languages like Javascript and Python.
Here are the codes;
C#
var _a = BigInteger.Parse("-1125040... | [
"Python and C# have different definitions of Mod. Python uses the mathematical definition of mod (the result is always a non-negative number) while C# returns a value with the same sign as you started with.\nYou'll notice that the difference between C#'s answer and Python's answer is precisely the modulus. In eff... | [
1
] | [] | [] | [
"biginteger",
"c#",
"javascript",
"mod",
"python"
] | stackoverflow_0074664517_biginteger_c#_javascript_mod_python.txt |
Q:
Creating a nested list using insert() in Python
I'm trying to find a way to create a nested list out of an already-existing non-empty list using built-in list fuctions.
Here is a small example:
a=['Groceries', 'School Fees', 'Medicines', 'Furniture']
When I try a[0].insert(0, 1000) for example, I'm met with an err... | Creating a nested list using insert() in Python | I'm trying to find a way to create a nested list out of an already-existing non-empty list using built-in list fuctions.
Here is a small example:
a=['Groceries', 'School Fees', 'Medicines', 'Furniture']
When I try a[0].insert(0, 1000) for example, I'm met with an error. Is there any way to do this?
| [] | [] | [
"Make a function for inner inserting.\nTry this\na=['Groceries', 'School Fees', 'Medicines', 'Furniture']\ndef innerInsert(index, value):\n try:\n a[index].insert(index, value)\n except AttributeError:\n a[index] = []\n a[index].insert(index, value)\n\ninnerInsert(0, 10000)\ninnerInsert(0... | [
-1,
-1
] | [
"list",
"nested_lists",
"python"
] | stackoverflow_0074664508_list_nested_lists_python.txt |
Q:
Calculating multilabel recall for this problem
I have a table with two columns, and the two entries of a row show that they are related:
Col1
Col2
a
A
b
B
a
C
c
A
b
D
Here a is related to A, C and b to B, D and c to A, meaning the same entry in col1 might have multiple labels in col2 related. I trained a Ma... | Calculating multilabel recall for this problem | I have a table with two columns, and the two entries of a row show that they are related:
Col1
Col2
a
A
b
B
a
C
c
A
b
D
Here a is related to A, C and b to B, D and c to A, meaning the same entry in col1 might have multiple labels in col2 related. I trained a Machine Learning model to quantify the re... | [
"You can use a clustering algorithm to group the entries in Col1 and Col2 into clusters. Then you can use the MultilabelRecall metric to calculate the recall for each cluster. This way, you don't have to specify the number of labels for each entry in Col1.\n",
"If you have a large number of rows in your table, it... | [
0,
0
] | [] | [] | [
"machine_learning",
"precision_recall",
"python",
"pytorch"
] | stackoverflow_0074633636_machine_learning_precision_recall_python_pytorch.txt |
Q:
Why use * here instead of + in regex for password must contain at least one number and both lower and uppercase letters?
The regex is like:
"^(?=.*[a-z])(?=.*[A-Z])[A-Za-z\d]{8,}$"
The * matches the previous token between zero and unlimited times.
The + matches the previous token between one and unlimited times.
p... | Why use * here instead of + in regex for password must contain at least one number and both lower and uppercase letters? | The regex is like:
"^(?=.*[a-z])(?=.*[A-Z])[A-Za-z\d]{8,}$"
The * matches the previous token between zero and unlimited times.
The + matches the previous token between one and unlimited times.
plus sign + should make sense here.
Why use * here instead of +?
| [
"(?=.*[a-z]) and (?=.*[A-Z]) are positive lookaheads for at least one lowercase and one uppercase letter, respectively. .* means skip 0+ chars. If you change that to .+ it would skip 1+ chars, so (?=.+[A-Z]) would not match password Aaaaaaaaa even though it has an uppercase char.\n"
] | [
1
] | [] | [] | [
"javascript",
"python",
"regex"
] | stackoverflow_0074664594_javascript_python_regex.txt |
Q:
Cannot download using coursera-dl, Error 404
I am trying to use coursera-dl in windows to download coursera videos using this command:
coursera-dl neural-networks-deep-learning
it gives this error:
coursera_dl version 0.11.5
Downloading class: neural-networks-deep-learning (1 / 1)
Parsing syllabus of on-demand co... | Cannot download using coursera-dl, Error 404 | I am trying to use coursera-dl in windows to download coursera videos using this command:
coursera-dl neural-networks-deep-learning
it gives this error:
coursera_dl version 0.11.5
Downloading class: neural-networks-deep-learning (1 / 1)
Parsing syllabus of on-demand course (id=W_mOXCrdEeeNPQ68_4aPpA). This may take so... | [
"Per the documentation you should download as follows:\ncoursera-dl -u my_coursera_username -p my_coursera_password neural-networks-deep-learning\n\nNote that you won't be able to access the course materials if you are not officially enrolled via the website.\n"
] | [
0
] | [] | [] | [
"cmd",
"coursera_api",
"python"
] | stackoverflow_0074662735_cmd_coursera_api_python.txt |
Q:
Is this an effective way to determine if a someone has won in connect 4?
I'm using the following function to determine if a winner has been crowned in connect four. Piece is whether they are green or red, last is the last played move (by piece), and name is the discord name of the person playing the game, as it is... | Is this an effective way to determine if a someone has won in connect 4? | I'm using the following function to determine if a winner has been crowned in connect four. Piece is whether they are green or red, last is the last played move (by piece), and name is the discord name of the person playing the game, as it is a file based connect four game. Board is a 2d array being made of all empty a... | [
"Keeping in mind your conditions are apt, your code could be enhanced in the following manners:\n\nReplacing conditions with all()\nAvoiding nested if conditions\nUsing elif in places of if\nUse min() to check inequality for smallest rather than checking both i and j\nCombine conditions to make it faster\n\nHere's ... | [
0,
0
] | [] | [] | [
"connect_four",
"discord.py",
"python"
] | stackoverflow_0074664215_connect_four_discord.py_python.txt |
Q:
Pip not recognized to install program
I'm trying to install instaloader and running into problems.
IU've downloaded the github file, extracted it, installed python and pip, i think. Now while runninng
pip3 install instaloader
in the windows command prompt its responding:
'pip3' is not recognized as an internal or... | Pip not recognized to install program | I'm trying to install instaloader and running into problems.
IU've downloaded the github file, extracted it, installed python and pip, i think. Now while runninng
pip3 install instaloader
in the windows command prompt its responding:
'pip3' is not recognized as an internal or external command,
operable program or batc... | [
"You can try to install pip by 'python get-pip.py' rather than 'pip install pip'.\n"
] | [
0
] | [] | [] | [
"instaloader",
"python"
] | stackoverflow_0074664616_instaloader_python.txt |
Q:
How to connect to mariadb5.5.52 using python3
My development environment
python3.8
mariadb 5.5.52
pymysql 1.0.2
django 4.1.3
try to migrate
but vscode tips django.db.utils.NotSupportedError: MariaDB 10.3 or later is required (found 5.5.52).
A:
To connect to a MariaDB 5.5.52 database using Python 3, you can use t... | How to connect to mariadb5.5.52 using python3 | My development environment
python3.8
mariadb 5.5.52
pymysql 1.0.2
django 4.1.3
try to migrate
but vscode tips django.db.utils.NotSupportedError: MariaDB 10.3 or later is required (found 5.5.52).
| [
"To connect to a MariaDB 5.5.52 database using Python 3, you can use the pymysql library. This library provides a Python interface for connecting to and working with a MariaDB database.\nTo use pymysql, you will need to first install it using pip:\npip install pymysql\n\nOnce you have installed pymysql, you can use... | [
1
] | [] | [] | [
"django",
"mariadb",
"python"
] | stackoverflow_0074664116_django_mariadb_python.txt |
Q:
How to count how many times a word in a list appeared in-another list
I have 2 lists and I want to see how many of the text in list 1 is in list 2 but I don't really know of a way to like combine them the output isn't summed and I have tried sum method but it does it for all words counted not each word.
Code:
l1 =... | How to count how many times a word in a list appeared in-another list | I have 2 lists and I want to see how many of the text in list 1 is in list 2 but I don't really know of a way to like combine them the output isn't summed and I have tried sum method but it does it for all words counted not each word.
Code:
l1 = ['hello', 'hi']
l2 = ['hey', 'hi', 'hello', 'hello']
for i in l2:
prin... | [
"I think a simple fix is to just flip the way you are looping through the lists:\nl1 = ['hello', 'hi']\nl2 = ['hey', 'hi', 'hello', 'hello']\nfor i in l1:\n print(f'{l2.count(i)}: {i}')\n\nOutput:\n2: hello\n1: hi\n\n",
"You can use the in operator to check if each element in l1 is in l2. You can then use a Co... | [
3,
1,
1,
0,
0
] | [] | [] | [
"count",
"for_loop",
"list",
"python",
"sum"
] | stackoverflow_0074664429_count_for_loop_list_python_sum.txt |
Q:
How to make environment variable in Python
I need a help in making variables as ENV in python, so that I can see that variable by using 'export' command in Linux. So I tested a below short script and I can see variable using export command. But the problem is that, below two command didn't work.
var1 = os.environ[... | How to make environment variable in Python | I need a help in making variables as ENV in python, so that I can see that variable by using 'export' command in Linux. So I tested a below short script and I can see variable using export command. But the problem is that, below two command didn't work.
var1 = os.environ['LINE']
print(var1)
Can you guide me how can I ... | [
"Try with\nos.environ['LINE'] = var\n\ninstead of using putenv. Using putenv \"bypasses\" os.environ, that is, it doesn't update os.environ.\nIn fact, from the documentation for os.putenv:\n\nAssignments to items in os.environ are automatically translated into corresponding calls to putenv(); however, calls to pute... | [
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074664627_python_python_3.x.txt |
Q:
GitLab-CI: Run Python Script and Exit (VPS)
I am trying to do a CI script on GitLab where it connects to my VPS, Git Pulls and then runs the python script and exits, while leaving my python script running 24/7 (until the next pipeline run/commit).
How do I do get it do make my python script run 24/7?
script:
-... | GitLab-CI: Run Python Script and Exit (VPS) | I am trying to do a CI script on GitLab where it connects to my VPS, Git Pulls and then runs the python script and exits, while leaving my python script running 24/7 (until the next pipeline run/commit).
How do I do get it do make my python script run 24/7?
script:
- 'apt-get update -y && apt-get install openssh-cl... | [
"Check first if this is a tty allocation issue, as in here.\nssh -t -o ...\n ^^\n\nAlso consider calling just one script (which does the cd, git pull and python3)\nThat way you can test the script locally (on 'host'), and then call it remotely (through ssh)\n\nFrom the OP Kevin A. in the comments:\n\nmy code goe... | [
1
] | [] | [] | [
"gitlab",
"gitlab_ci",
"python",
"python_3.x"
] | stackoverflow_0074661343_gitlab_gitlab_ci_python_python_3.x.txt |
Q:
Sum of each row and each column in python
Hi I have more than 20 txt file that include a matrix (9*7) 9 rows and 7 columns:
I want to find sum of each 7 rows and 9 columns for each matrix
My code that I have used is for one matrix how can I use for multi matrix is there any way with python?
import numpy as np
... | Sum of each row and each column in python | Hi I have more than 20 txt file that include a matrix (9*7) 9 rows and 7 columns:
I want to find sum of each 7 rows and 9 columns for each matrix
My code that I have used is for one matrix how can I use for multi matrix is there any way with python?
import numpy as np
# Get the size m and n
m , n = 7, 9
... | [
"To calculate the row and column sums for multiple matrices, you can create a function that takes a list of matrices and calculates the row and column sums for each matrix in the list. Here is an example:\nimport numpy as np\n\n# Get the size m and n\nm, n = 7, 9\n\n# Function to calculate sum of each row\ndef row_... | [
0
] | [] | [] | [
"matrix",
"python"
] | stackoverflow_0074664693_matrix_python.txt |
Q:
update column to two based on condition
I am trying to modify ONE column, I want to set some rows as true the others convert them to false
update products set on_sale=False where status=1 and seller=test;
update products set on_sale=true Where price > 100 and status=1 and seller=test;
the above works, but I belie... | update column to two based on condition | I am trying to modify ONE column, I want to set some rows as true the others convert them to false
update products set on_sale=False where status=1 and seller=test;
update products set on_sale=true Where price > 100 and status=1 and seller=test;
the above works, but I believe it can be done in 1 query, I.e something l... | [
"You could do a single update with the help of a CASE expression:\nUPDATE products\nSET on_sale = CASE WHEN price > 100 THEN True ELSE False END\nWHERE status = 1 AND seller = test;\n\n"
] | [
1
] | [] | [] | [
"postgresql",
"python"
] | stackoverflow_0074664787_postgresql_python.txt |
Q:
Python Heatmap with calculated fields
Looking to create a heatmap from a dataframe. Index is each event of car crashes. Columns are Year, Month (1 - 12, Day of the Week (1- 7), Hour of Day (0 - 23), Fatal (1) non Fatal (2), etc.
I trying to create a heatmap with the x axis being Hour of Day, and y axis being Day o... | Python Heatmap with calculated fields | Looking to create a heatmap from a dataframe. Index is each event of car crashes. Columns are Year, Month (1 - 12, Day of the Week (1- 7), Hour of Day (0 - 23), Fatal (1) non Fatal (2), etc.
I trying to create a heatmap with the x axis being Hour of Day, and y axis being Day of the Week. Looking to create a calculated ... | [
"First, use your data to make a 2-D matrix with rows representing the days (sunday, ...) and the columns representing the numbers (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18).\nOnce you have this 2-D matrix use the below code to plot the heatmap\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# ... | [
0
] | [] | [] | [
"group_by",
"heatmap",
"pandas",
"python"
] | stackoverflow_0074664195_group_by_heatmap_pandas_python.txt |
Q:
Why is exponentiation applied right to left?
I am reading an Intro to Python textbook and came across this line:
Operators on the same row have equal precedence and are applied left to right, except for exponentiation, which is applied right to left.
I understand most of this, but I do not understand why they sa... | Why is exponentiation applied right to left? | I am reading an Intro to Python textbook and came across this line:
Operators on the same row have equal precedence and are applied left to right, except for exponentiation, which is applied right to left.
I understand most of this, but I do not understand why they say exponentiation is applied right to left. They do... | [
"The ** operator follows normal mathematical conventions; it is right-associative:\n\nIn the usual computer science jargon, exponentiation in mathematics is right-associative, which means that xyz should be read as x(yz), not (xy)z. In expositions of the BODMAS rules that are careful enough to address this question... | [
23,
2,
0,
0
] | [] | [] | [
"exponentiation",
"operators",
"python",
"python_3.x"
] | stackoverflow_0047429513_exponentiation_operators_python_python_3.x.txt |
Q:
Trying to Combine Two Scatter Plots and Two Line Graphs with Matplotlib
I'm trying to create a graph that lists the high and low temperature per city on a specific day, but it seems like the y axes are just overlapping instead of plotting the point along it.
Here is what I have:
fig, al = plt.subplots()
al.scatter... | Trying to Combine Two Scatter Plots and Two Line Graphs with Matplotlib | I'm trying to create a graph that lists the high and low temperature per city on a specific day, but it seems like the y axes are just overlapping instead of plotting the point along it.
Here is what I have:
fig, al = plt.subplots()
al.scatter(al_cities, al_min)
al.scatter(al_cities, al_max, c='red')
al.plot(al_cities,... | [
"The problem you are seeing is because matplotlib classifies your y-axis values as categorical instead of numeric continuous values.\nThis might be because your list of al_min and al_max contain strings ['1','2','3'] instead of integers [1,2,3].\nAll you have to do is convert the strings in the list to integers. Yo... | [
1,
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074664603_matplotlib_python.txt |
Q:
Look up values from one df to another df based on a specific column
I am attempting to populate values from one DataFrame to another DataFrame based on a common column present in both DataFrames.
The code I wrote for this operation is as follows:
for i in df1.zipcodes:
for j in df2.zipcodes.unique():
i... | Look up values from one df to another df based on a specific column | I am attempting to populate values from one DataFrame to another DataFrame based on a common column present in both DataFrames.
The code I wrote for this operation is as follows:
for i in df1.zipcodes:
for j in df2.zipcodes.unique():
if i == j:
#print("this is i:",i, "this is j:",j)
df1['ren... | [
"Use a merge with the groupby.mean of df2:\nout = df1.merge(df2.groupby('zipcodes', as_index=False)['rent'].mean(),\n on='zipcodes', how='left')\n\n",
"You can divide that into 2 phases:\n\n1st phase: Aggregate the df2 to calculate the average rent by zip code. If the zip code has only one rent the... | [
1,
1
] | [] | [] | [
"average",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074664746_average_dataframe_pandas_python.txt |
Q:
Get 5 minutes Interval by creating columns as start and end time from date & time stamp column in pandas
data = {'col_ts': ['2022-11-02T08:26:40', '2022-11-02T08:25:10', '2022-11-02T08:26:00', '2022-11-02T08:30:20',
'2022-11-02T08:33:30', '2022-11-02T08:36:40', '2022-11-02T08:26:20', '2022-11-02T... | Get 5 minutes Interval by creating columns as start and end time from date & time stamp column in pandas | data = {'col_ts': ['2022-11-02T08:26:40', '2022-11-02T08:25:10', '2022-11-02T08:26:00', '2022-11-02T08:30:20',
'2022-11-02T08:33:30', '2022-11-02T08:36:40', '2022-11-02T08:26:20', '2022-11-02T08:50:10',
'2022-11-02T08:30:40', '2022-11-02T08:39:40']}
df = pd.DataFrame(data, columns =... | [
"Here is one way to do it using Pandas to_datetime and dt.accessor:\ndf[\"col_ts\"] = pd.to_datetime(df[\"col_ts\"])\ndf[\"start_interval\"] = df[\"col_ts\"].dt.floor(\"5T\")\ndf[\"end_interval\"] = df[\"col_ts\"].dt.ceil(\"5T\")\n\nThen:\n col_ts start_interval end_interval\n0 2022-11-02 ... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074663425_pandas_python.txt |
Q:
Python Multi-Criteria Lookup From one of Many Columns
Trying to add a factor to a dataframe based on a lookup of multiple criteria in another dataframe. Code to create sample data:
import pandas as pd
df_RawData = pd.DataFrame({
'Value' : [31000, 36000, 42000],
'Type' : [0,1,5]
})
df_Lookup = pd.DataFram... | Python Multi-Criteria Lookup From one of Many Columns | Trying to add a factor to a dataframe based on a lookup of multiple criteria in another dataframe. Code to create sample data:
import pandas as pd
df_RawData = pd.DataFrame({
'Value' : [31000, 36000, 42000],
'Type' : [0,1,5]
})
df_Lookup = pd.DataFrame({
'Min Value' : [0,10000,20000,25000,30000,35000,4000... | [
"Create the intervalindex:\nintervals = pd.IntervalIndex.from_arrays(df_Lookup['Min Value'], \n df_Lookup['Max Value'], \n closed='neither')\n\nGet the matching positions:\npos = intervals.get_indexer(df_RawData.Value)\n\nIndex the Type... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074664682_dataframe_pandas_python.txt |
Q:
Wrapping a shell in Python and then launching subprocesses in said shell
Python can be used to spawn a shell and communicate with it:
p = subprocess.Popen(['cmd'], shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # use 'bash' if Linux.
With this set-up sending a command such as '... | Wrapping a shell in Python and then launching subprocesses in said shell | Python can be used to spawn a shell and communicate with it:
p = subprocess.Popen(['cmd'], shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # use 'bash' if Linux.
With this set-up sending a command such as 'echo foo' or 'cd' command works. However, problems arise when we try to use a ... | [
"Here’s an example of how asyncio can run a shell command and obtain its result:\nimport asyncio\n\nasync def run(cmd):\n proc = await asyncio.create_subprocess_shell(\n cmd,\n stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.PIPE)\n\n stdout, stderr = await proc.communicate()\... | [
0
] | [] | [] | [
"python",
"subprocess"
] | stackoverflow_0074664917_python_subprocess.txt |
Q:
PySpark: How to get range of dates from dataframe into a new dataframe
I have this PySpark data frame with a single row:
spark_session_tbl_df.printSchema()
spark_session_tbl_df.show()
root
|-- strm: string (nullable = true)
|-- acad_career: string (nullable = true)
|-- session_code: string (nullable = true... | PySpark: How to get range of dates from dataframe into a new dataframe | I have this PySpark data frame with a single row:
spark_session_tbl_df.printSchema()
spark_session_tbl_df.show()
root
|-- strm: string (nullable = true)
|-- acad_career: string (nullable = true)
|-- session_code: string (nullable = true)
|-- sess_begin_dt: timestamp (nullable = true)
|-- sess_end_dt: timesta... | [
"One of the approaches when you are dealing with timeseries is to convert date to timestamp and solve the question in a numerical way and the end convert it to date again.\nfrom pyspark.sql import functions as F\n\ndata = [['2022-08-20 00:00:00', '2022-12-03 00:00:00']]\ndf = spark.createDataFrame(data = data, sche... | [
0
] | [] | [] | [
"apache_spark_sql",
"dataframe",
"pyspark",
"python",
"sequence"
] | stackoverflow_0074662709_apache_spark_sql_dataframe_pyspark_python_sequence.txt |
Q:
Configure Gmail API on Ubuntu VPS
How to configure Gmail API on a AWS Ubuntu VPS? I am able to make it work properly on my Linux Machine, but after I run the code on my VPS, it asks me to authenticate by visiting the URL. I copied the URL and tried authenticating myself. While authenticating myself in browser, I a... | Configure Gmail API on Ubuntu VPS | How to configure Gmail API on a AWS Ubuntu VPS? I am able to make it work properly on my Linux Machine, but after I run the code on my VPS, it asks me to authenticate by visiting the URL. I copied the URL and tried authenticating myself. While authenticating myself in browser, I am redirected to localhost:<random-port>... | [
"I have encountered the same problem.\nWhen you will try to authenticate using your browser, it will try to redirect you to some localhost URL. Just copy that localhost URL, log in to your VPS, open the terminal, type python3 (or python), and finally type these commands:\nimport requests\nurl = \"http://localhost:x... | [
0
] | [] | [] | [
"api",
"gmail",
"python",
"ubuntu",
"vps"
] | stackoverflow_0072126436_api_gmail_python_ubuntu_vps.txt |
Q:
Telegram-Python-Bot How to make the bot receive message from user?
so when a user send /help command in a GROUP then the bot should reply "please send your query " and wait for the user to rely, and when user replies , i want the bot to store that reply in a variable, and i am really confuse on how to do that. and... | Telegram-Python-Bot How to make the bot receive message from user? | so when a user send /help command in a GROUP then the bot should reply "please send your query " and wait for the user to rely, and when user replies , i want the bot to store that reply in a variable, and i am really confuse on how to do that. and the bot should only take the reply of the user who sent the /help comma... | [
"Configuring the Telegram Bot\n\nGo to https://telegram.me/BotFather.\nTo create a new bot type /newbot to the message box and press enter.\nEnter the name of the user name of your new bot.\nYou have received the message from BotFather containing the token, which you can use to connect Telegram Bot to Make.\n\nTo a... | [
0
] | [] | [] | [
"python",
"python_telegram_bot",
"telegram_bot"
] | stackoverflow_0074664890_python_python_telegram_bot_telegram_bot.txt |
Q:
Write Persian in slug and use it in address bar in django
I use django and in my models I want to write Persian in slugfield (by using utf-8 or something else) and use the slug in address of page
I write this class for model:
class Category(models.Model):
name = models.CharField(max_length=20, unique=True)
... | Write Persian in slug and use it in address bar in django | I use django and in my models I want to write Persian in slugfield (by using utf-8 or something else) and use the slug in address of page
I write this class for model:
class Category(models.Model):
name = models.CharField(max_length=20, unique=True)
slug = models.SlugField(max_length=20, unique=True)
descr... | [
"The docstring for the slugify function is:\n\nConvert to ASCII if 'allow_unicode' is False. Convert spaces to hyphens.\n Remove characters that aren't alphanumerics, underscores, or hyphens.\n Convert to lowercase. Also strip leading and trailing whitespace.\n\nSo you need to set the allow_unicode flag to True t... | [
8,
2,
1,
0
] | [] | [] | [
"django",
"persian",
"python"
] | stackoverflow_0047938594_django_persian_python.txt |
Q:
Tensorflow import error: No module named 'tensorflow'
I installed TensorFlow on my Windows Python 3.5 Anaconda environment
The validation was successful (with a warning)
(tensorflow) C:\>python
Python 3.5.3 |Intel Corporation| (default, Apr 27 2017, 17:03:30) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "cop... | Tensorflow import error: No module named 'tensorflow' | I installed TensorFlow on my Windows Python 3.5 Anaconda environment
The validation was successful (with a warning)
(tensorflow) C:\>python
Python 3.5.3 |Intel Corporation| (default, Apr 27 2017, 17:03:30) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
Intel... | [
"The reason Python 3.5 environment is unable to import Tensorflow is that Anaconda does not store the tensorflow package in the same environment.\nOne solution is to create a new separate environment in Anaconda dedicated to TensorFlow with its own Spyder\nconda create -n newenvt anaconda python=3.5\nactivate newen... | [
28,
15,
12,
5,
3,
2,
2,
1,
1,
1,
1,
0,
0
] | [
"Try worked for me\npython3 -m pip install --upgrade https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.12.0-py3-none-any.whl \n\n"
] | [
-1
] | [
"anaconda",
"installation",
"python",
"tensorflow",
"windows"
] | stackoverflow_0046568913_anaconda_installation_python_tensorflow_windows.txt |
Q:
open file for random write without truncating?
In python, there are a few flags you can supply when opening a file for operation. I am a bit baffled at finding a combination that allow me to do random write without truncating. The behavior I am looking for is equivalent to C: create it if it doesn't exist, otherwi... | open file for random write without truncating? | In python, there are a few flags you can supply when opening a file for operation. I am a bit baffled at finding a combination that allow me to do random write without truncating. The behavior I am looking for is equivalent to C: create it if it doesn't exist, otherwise, open for write (not truncating)
open(filename, O... | [
"You can do it with os.open:\nimport os\nf = os.fdopen(os.open(filename, os.O_RDWR | os.O_CREAT), 'rb+')\n\nNow you can read, write in the middle of the file, seek, and so on. And it creates the file. Tested on Python 2 and 3.\n",
"You should try reading the file then open writing mode, as seen here:\nwith open(\... | [
10,
0,
0
] | [
"You need to use \"a\" to append, it will create the file if it does not exist or append to it if it does.\nYou cannot do what you want with append as the pointer automatically moves to the end of the file when you call the write method. \nYou could check if the file exists then use fileinput.input with inplace=Tr... | [
-2
] | [
"python"
] | stackoverflow_0028918302_python.txt |
Q:
Adding Text/watermark to ‘Download Plot’ button image in Plotly
Is there any way to add a text/watermark to the image which is downloaded by clicking on the “Download Plot” button ("toImageButtonOptions") in Plotly figures?
Reference code:
config = {
‘toImageButtonOptions’: {
‘format’: ‘png’,
‘filename’: ‘download... | Adding Text/watermark to ‘Download Plot’ button image in Plotly | Is there any way to add a text/watermark to the image which is downloaded by clicking on the “Download Plot” button ("toImageButtonOptions") in Plotly figures?
Reference code:
config = {
‘toImageButtonOptions’: {
‘format’: ‘png’,
‘filename’: ‘download_image’,
}
}
| [
"You can do it by using templates:\nimport plotly.graph_objects as go\n\ndraft_template = go.layout.Template()\ndraft_template.layout.annotations = [\n dict(\n name=\"draft watermark\",\n text=\"DRAFT\",\n textangle=-30,\n opacity=0.1,\n font=dict(color=\"black\", size=100),\n ... | [
0
] | [] | [] | [
"plotly",
"plotly_dash",
"plotly_python",
"python"
] | stackoverflow_0074662095_plotly_plotly_dash_plotly_python_python.txt |
Q:
Index out of range on BS4 selecting elements
I need to get the ID of the li element but I dont want the other elements IDs. I have attached my code below but its throwing a Index out of range error somewhere in it
HTML:
<ul class="product-attributes list-inline product-attributes-two-sizes">
<li class="ease " ... | Index out of range on BS4 selecting elements | I need to get the ID of the li element but I dont want the other elements IDs. I have attached my code below but its throwing a Index out of range error somewhere in it
HTML:
<ul class="product-attributes list-inline product-attributes-two-sizes">
<li class="ease " id="12345"></li>
<li class="dsadsad" id="000">... | [
"Here is a one-liner way of retrieving the information you're after:\nfrom bs4 import BeautifulSoup as bs\n\nhtml = '''\n<ul class=\"product-attributes list-inline product-attributes-two-sizes\">\n <li class=\"ease \" id=\"12345\"></li>\n <li class=\"dsadsad\" id=\"000\"></li>\n <li class=\"dadsda\" id=\"0... | [
0
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0074661220_beautifulsoup_python.txt |
Q:
Reading part of lines from a txt
I'm trying to read a txt file with informations about time, temperature and humidity, this is the shape
07:54:03.383 -> Humidity:38.00%;Temperature:20.50°C;Heat index:19.60°C;
07:59:03.415 -> Humidity:37.00%;Temperature:20.90°C;Heat index:20.01°C;
08:04:03.435 -> Humidity:37.00... | Reading part of lines from a txt | I'm trying to read a txt file with informations about time, temperature and humidity, this is the shape
07:54:03.383 -> Humidity:38.00%;Temperature:20.50°C;Heat index:19.60°C;
07:59:03.415 -> Humidity:37.00%;Temperature:20.90°C;Heat index:20.01°C;
08:04:03.435 -> Humidity:37.00%;Temperature:20.90°C;Heat index:20.0... | [
"Assuming you can tolerate reading your data into a Python string, we can use re.findall here:\n# -*- coding: utf-8 -*-\nimport re\n\ninp = \"\"\"07:54:03.383 -> Humidity:38.00%;Temperature:20.50°C;Heat index:19.60°C;\n07:59:03.415 -> Humidity:37.00%;Temperature:20.90°C;Heat index:20.01°C;\n08:04:03.435 -> Humi... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074665084_python.txt |
Q:
How to tunnel localhost on android
I have a python webserver which has webhooks , when posted in localhost on desktop and tunnel it through loophole.site it works
I further ran the python webserver code in Android 12 it works on ports > 1024 but my trading view alert webhooks only accepts from http Port:80 or http... | How to tunnel localhost on android | I have a python webserver which has webhooks , when posted in localhost on desktop and tunnel it through loophole.site it works
I further ran the python webserver code in Android 12 it works on ports > 1024 but my trading view alert webhooks only accepts from http Port:80 or https:443 also localhost address its not acc... | [
"If you use android emulator use http://10.0.2.2:[your port]\n"
] | [
0
] | [] | [] | [
"android",
"http_tunneling",
"localhost",
"python",
"webserver"
] | stackoverflow_0074664974_android_http_tunneling_localhost_python_webserver.txt |
Q:
Conditional Fillna in Pandas with conditional increment from the previous value
I want to fillna values in the 'last unique id' column based on the increment values from the previous row
**input is**
Channel last unique id
0 MYNTRA MN000351370
1 NYKAA NYK00038219
2 NYKAA NaN
3 NYKAA NaN
4 NYKAA ... | Conditional Fillna in Pandas with conditional increment from the previous value | I want to fillna values in the 'last unique id' column based on the increment values from the previous row
**input is**
Channel last unique id
0 MYNTRA MN000351370
1 NYKAA NYK00038219
2 NYKAA NaN
3 NYKAA NaN
4 NYKAA NaN
5 NYKAA NaN
6 MYNTRA NaN
7 MYNTRA NaN
8 MYNTRA NaN
9 MYNTRA NaN
... | [
"Example\ndata = {'col1': {0: 'A', 1: 'B', 2: 'A', 3: 'A', 4: 'B', 5: 'B'},\n 'col2': {0: 'A001', 1: 'BC020', 2: None, 3: None, 4: 'BC021', 5: None}}\ndf = pd.DataFrame(data)\n\ndf\n col1 col2\n0 A A001\n1 B BC020\n2 A None\n3 A None\n4 B BC021\n5 B None\n\nCode\ndf[['col3', 'col4']] = df.... | [
0,
0,
0
] | [] | [] | [
"dataframe",
"loops",
"numpy",
"pandas",
"python"
] | stackoverflow_0074664488_dataframe_loops_numpy_pandas_python.txt |
Q:
How to mute/unmute sound using pywin32?
My searches lead me to the Pywin32 which should be able to mute/unmute the sound and detect its state (on Windows 10, using Python 3+). I found a way using an AutoHotkey script, but I'm looking for a pythonic way.
More specifically, I'm not interested in playing with the Win... | How to mute/unmute sound using pywin32? | My searches lead me to the Pywin32 which should be able to mute/unmute the sound and detect its state (on Windows 10, using Python 3+). I found a way using an AutoHotkey script, but I'm looking for a pythonic way.
More specifically, I'm not interested in playing with the Windows GUI. Pywin32 works using a Windows DLL.
... | [
"You can use the Windows Sound Manager by paradoxis (https://github.com/Paradoxis/Windows-Sound-Manager). \nfrom sound import Sound\nSound.mute()\n\nEvery call to Sound.mute() will toggle mute on or off. Have a look at the main.py to see how to use the setter and getter methods.\n",
"If you're also building a GUI... | [
2,
0
] | [] | [] | [
"audio",
"python",
"python_3.x",
"pywin32",
"windows"
] | stackoverflow_0055399396_audio_python_python_3.x_pywin32_windows.txt |
Q:
How to prettyprint a JSON file?
How do I pretty-print a JSON file in Python?
A:
Use the indent= parameter of json.dump() or json.dumps() to specify how many spaces to indent by:
>>> import json
>>>
>>> your_json = '["foo", {"bar": ["baz", null, 1.0, 2]}]'
>>> parsed = json.loads(your_json)
>>> print(json.dumps(p... | How to prettyprint a JSON file? | How do I pretty-print a JSON file in Python?
| [
"Use the indent= parameter of json.dump() or json.dumps() to specify how many spaces to indent by:\n>>> import json\n>>>\n>>> your_json = '[\"foo\", {\"bar\": [\"baz\", null, 1.0, 2]}]'\n>>> parsed = json.loads(your_json)\n>>> print(json.dumps(parsed, indent=4))\n[\n \"foo\",\n {\n \"bar\": [\n ... | [
2665,
446,
120,
61,
45,
23,
19,
9,
8,
7,
3,
3,
0,
0,
0
] | [
"It's far from perfect, but it does the job.\ndata = data.replace(',\"',',\\n\"')\n\nyou can improve it, add indenting and so on, but if you just want to be able to read a cleaner json, this is the way to go.\n"
] | [
-8
] | [
"formatting",
"json",
"pretty_print",
"python"
] | stackoverflow_0012943819_formatting_json_pretty_print_python.txt |
Q:
Creating a Snapchat bot in python
I am new in python programming and I was trying to create a Snapchat bot
Can you help me create a request based Snapchat bot.
I will be using this for marketing with my existing clients to help schedule posts. It will also be an auto responder to act as Thank you or Welcome messa... | Creating a Snapchat bot in python | I am new in python programming and I was trying to create a Snapchat bot
Can you help me create a request based Snapchat bot.
I will be using this for marketing with my existing clients to help schedule posts. It will also be an auto responder to act as Thank you or Welcome messages.
If you got any ideas you can share... | [
"Snapchat now supports the web or browser. So you can take a look at the tutorials of pyautogui module in python. you can manipulate the keyboard and mouse events and respond to the messages with prewritten messages of yours. Your task can be done easily.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074665242_python.txt |
Q:
Accessing python variable outside function scope when reassigning to update variable
I want to keep track of the current max of a calculated cosine similarity score. However, I keep getting the error UnboundLocalError: cannot access local variable 'current_max_cosine_similarity_score' where it is not associated wi... | Accessing python variable outside function scope when reassigning to update variable | I want to keep track of the current max of a calculated cosine similarity score. However, I keep getting the error UnboundLocalError: cannot access local variable 'current_max_cosine_similarity_score' where it is not associated with a value
In Javascript, I can typically do this without a problem using the let keyword ... | [
"You have to declare current_max_cosine_similarity_score as global (or nonlocal) in func().\nBut that's nevertheless a bad idea. The \"pythonic\" way would be to use a generator, closure or a class with a get_current_maximum().\nProbably the most \"pythonic\" closure solves your problem:\nfrom functools import redu... | [
2
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074665130_python_python_3.x.txt |
Q:
How do I get the args from a post or get with Python without using cgi.FieldStorage
I just read that cgi is deprecated and so cgi.FieldStorage will stop working.
I'm struggling to find the replacement for this functionality. All the searches I've tried refer to urllib or requests, both of which (AFAIK) are designe... | How do I get the args from a post or get with Python without using cgi.FieldStorage | I just read that cgi is deprecated and so cgi.FieldStorage will stop working.
I'm struggling to find the replacement for this functionality. All the searches I've tried refer to urllib or requests, both of which (AFAIK) are designed to create requests, not to respond to them.
Thanks in advance
| [
"The reference to urllib is actually a bit misleading. The following might give some insight to the cgi interface from a python programmers point of view:\n#!/usr/bin/python3\n'''\npreflight_cgi.py\ncheck the preflight option call\n'''\n\nimport sys\nimport os\n\nif __name__ == \"__main__\":\n print(\"Content-Ty... | [
0
] | [] | [] | [
"python",
"webserver"
] | stackoverflow_0074225287_python_webserver.txt |
Q:
Change values in lists that are in pandas column
I have a dataset where a column contains lists of previously received tokenized words. I need to replace a couple of values in these lists.
Initial data set:
df
date text
2022-06-02 [municipal', 'districts', 'mikhailovsky', '84', 'kamyshinsky', '56']
...... | Change values in lists that are in pandas column | I have a dataset where a column contains lists of previously received tokenized words. I need to replace a couple of values in these lists.
Initial data set:
df
date text
2022-06-02 [municipal', 'districts', 'mikhailovsky', '84', 'kamyshinsky', '56']
...
Required result:
df_res
date text
2022-06-0... | [
"df = pd.DataFrame([['2022-06-02', ['municipal', 'districts', 'mikhailovsky', '84', 'kamyshinsky', '56']], ['2022-06-02', ['municipal', 'districts', 'mikhailovsky', '84', 'kamyshinsky', '56']], ['2022-06-02', ['municipal', 'districts', 'mikhailovsky', '84', 'kamyshinsky', '56']]], columns=['date', 'text'])\n\nmappe... | [
2
] | [] | [] | [
"dataframe",
"list",
"pandas",
"python"
] | stackoverflow_0074664930_dataframe_list_pandas_python.txt |
Q:
Resolve warning "A NumPy version >=1.16.5 and <1.23.0 is required for this version of SciPy"?
When I import SciPy or a library dependent on it, I receive the following warning message:
UserWarning: A NumPy version >=1.16.5 and <1.23.0 is required for this version of SciPy (detected version 1.23.1
It's true that I... | Resolve warning "A NumPy version >=1.16.5 and <1.23.0 is required for this version of SciPy"? | When I import SciPy or a library dependent on it, I receive the following warning message:
UserWarning: A NumPy version >=1.16.5 and <1.23.0 is required for this version of SciPy (detected version 1.23.1
It's true that I am running NumPy version 1.23.1, however this message is a mystery to me since I am running SciPy ... | [
"I have the same issue.\nThe scipy 1.7.3 docs specifies\n1.16.5 <= numpy <1.24.0 while in scipy 1.7.3 code setup.py and __init__.py we have np_maxversion = '1.23.0'.\nAs I rely on conda channel defaults to setup Intel MKL libraries for numpy and scipy I decided to pin \"numpy>=1.22.3,<1.23.0\" until a newer scipy i... | [
7,
5,
0
] | [] | [] | [
"conda",
"numpy",
"python",
"scipy"
] | stackoverflow_0073072257_conda_numpy_python_scipy.txt |
Q:
How to extract number from a txt file
First my file
amtdec = open("amt.txt", "r+")
gc = open("gamecurrency.txt", "r+")
eg = gc.readline()
u = amtdec.readline()
The main code
user_balance = int(u)
egc = int(eg)
while True:
deposit_amount = int(input("Enter deposit amount: $"))
if deposit_amount<=user_bal... | How to extract number from a txt file | First my file
amtdec = open("amt.txt", "r+")
gc = open("gamecurrency.txt", "r+")
eg = gc.readline()
u = amtdec.readline()
The main code
user_balance = int(u)
egc = int(eg)
while True:
deposit_amount = int(input("Enter deposit amount: $"))
if deposit_amount<=user_balance:
entamount = deposit_amoun... | [
"Usually an error like this should turn you to check the formatting of your file. As some others mentioned, the first line could be empty for whatever reason. You can check for an empty file prior to this by doing the following:\ntest.txt contents:\n(empty file)\nimport os\n\nf = open(\"test.txt\")\n\nif os.path.ge... | [
0
] | [] | [] | [
"function",
"python",
"runtime_error",
"syntax_error"
] | stackoverflow_0074664866_function_python_runtime_error_syntax_error.txt |
Q:
This error is coming and i am not able to understand why. Error = TypeError: 'NoneType' object is not subscriptable
I am using SQL connectivity , python , tkinter and
I am trying to display the record after creating it but there is an error coming
The records are created and stored in my sql but it can't display t... | This error is coming and i am not able to understand why. Error = TypeError: 'NoneType' object is not subscriptable | I am using SQL connectivity , python , tkinter and
I am trying to display the record after creating it but there is an error coming
The records are created and stored in my sql but it can't display them on tkinter
here is the code
import tkinter
import mysql.connector
from tkinter import Label
from tkinter import Entr... | [
"You are trying to create new label widgits in your function when you should just be updating the already existing ones.\nTry:\ndef Creation():\n mycur=mydb.cursor()\n \n name=a.get()\n dob=b.get()\n Class=c.get()\n admn=d.get()\n add=e.get()\n mob=f.get()\n tra=g.get()\n query3=(\"ins... | [
0
] | [] | [] | [
"mysql",
"python",
"tkinter"
] | stackoverflow_0074665189_mysql_python_tkinter.txt |
Q:
group column values with difference of 3(say) digit in python
I am new in python, problem statement is like we have below data as dataframe
df = pd.DataFrame({'Diff':[1,1,2,3,4,4,5,6,7,7,8,9,9,10], 'value':[x,x,y,x,x,x,y,x,z,x,x,y,y,z]})
Diff value
1 x
1 x
2 y
3 x
4 x
4 x
5 ... | group column values with difference of 3(say) digit in python | I am new in python, problem statement is like we have below data as dataframe
df = pd.DataFrame({'Diff':[1,1,2,3,4,4,5,6,7,7,8,9,9,10], 'value':[x,x,y,x,x,x,y,x,z,x,x,y,y,z]})
Diff value
1 x
1 x
2 y
3 x
4 x
4 x
5 y
6 x
7 z
7 x
8 x
9 y
9 y
... | [
"Example\nexample code is wrong. someone who want exercise, use following code\ndf = pd.DataFrame({'Diff':[1,1,2,3,4,4,5,6,7,7,8,9,9,10], \n 'value':'x,x,y,x,x,x,y,x,z,x,x,y,y,z'.split(',')})\n\nCode\nlabels = ['0-3', '3-6', '6-9', '>=9']\ngrouper = pd.cut(df['Diff'], bins=[0, 3, 6, 9, float('inf'... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074665214_dataframe_pandas_python_python_3.x.txt |
Q:
Editing specific line in text file in Python
Let's say I have a text file containing:
Dan
Warrior
500
1
0
Is there a way I can edit a specific line in that text file? Right now I have this:
#!/usr/bin/env python
import io
myfile = open('stats.txt', 'r')
dan = myfile.readline()
print dan
print "Your name: " + dan... | Editing specific line in text file in Python | Let's say I have a text file containing:
Dan
Warrior
500
1
0
Is there a way I can edit a specific line in that text file? Right now I have this:
#!/usr/bin/env python
import io
myfile = open('stats.txt', 'r')
dan = myfile.readline()
print dan
print "Your name: " + dan.split('\n')[0]
try:
myfile = open('stats.txt... | [
"You want to do something like this:\n# with is like your try .. finally block in this case\nwith open('stats.txt', 'r') as file:\n # read a list of lines into data\n data = file.readlines()\n\nprint data\nprint \"Your name: \" + data[0]\n\n# now change the 2nd line, note that you have to add a newline\ndata[... | [
162,
34,
28,
16,
3,
2,
0,
0,
0
] | [
"#read file lines and edit specific item\n\nfile=open(\"pythonmydemo.txt\",'r')\na=file.readlines()\nprint(a[0][6:11])\n\na[0]=a[0][0:5]+' Ericsson\\n'\nprint(a[0])\n\nfile=open(\"pythonmydemo.txt\",'w')\nfile.writelines(a)\nfile.close()\nprint(a)\n\n",
"This is the easiest way to do this.\nf = open(\"file.txt\",... | [
-1,
-2
] | [
"io",
"python"
] | stackoverflow_0004719438_io_python.txt |
Q:
python get dictionary key from value is list
I have two dictionaries:
first_dict = {'a': ['1', '2', '3'],
'b': ['4', '5'],
'c': ['6'],
}
second_dict = {'1': 'wqeewe',
'2': 'efsafa',
'4': 'fsasaf',
'6': 'kgoeew',
... | python get dictionary key from value is list | I have two dictionaries:
first_dict = {'a': ['1', '2', '3'],
'b': ['4', '5'],
'c': ['6'],
}
second_dict = {'1': 'wqeewe',
'2': 'efsafa',
'4': 'fsasaf',
'6': 'kgoeew',
'7': 'fkowew'
}
I want to have a t... | [
"you can do it like that:\nCode\nfirst_dict = {'a': ['1', '2', '3'],\n 'b': ['4', '5'],\n 'c': ['6'],\n }\n\nsecond_dict = {'1': 'wqeewe',\n '2': 'efsafa',\n '4': 'fsasaf',\n '6': 'kgoeew',\n '7': 'fkowew'\n ... | [
1,
1,
0,
0
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0074664870_dictionary_list_python.txt |
Q:
How to set a variable, that isnt iter variable, to increases in each iteration and doesnt always return to its value prior to its entry into for loop?
import re, datetime
def add_months(datestr, months):
ref_year, ref_month = "", ""
ref_year_is_leap_year = False
aux_date = str(datetime.datetime.strpt... | How to set a variable, that isnt iter variable, to increases in each iteration and doesnt always return to its value prior to its entry into for loop? | import re, datetime
def add_months(datestr, months):
ref_year, ref_month = "", ""
ref_year_is_leap_year = False
aux_date = str(datetime.datetime.strptime(datestr, "%Y-%m-%d"))
print(repr(aux_date))
for i_month in range(int(months)):
# I add a unit since the months are "numerical quantiti... | [
"Because at the end of every iteration of your for loop you are reconverting the value that is given in the parameter datestr and that value is never updated. You are also converting it to a string while trying to add a timedelta object. You should leave the value as a datetime object and convert to string once t... | [
2,
2
] | [] | [] | [
"for_loop",
"loops",
"python",
"python_3.x",
"variables"
] | stackoverflow_0074665124_for_loop_loops_python_python_3.x_variables.txt |
Q:
pandas/regex: Remove the string after the hyphen or parenthesis character (including) carry string after the comma in pandas dataframe
I have a dataframe contains one column which has multiple strings separated by the comma, but in this string, I want to remove all matter after hyphen (including hyphen), main poin... | pandas/regex: Remove the string after the hyphen or parenthesis character (including) carry string after the comma in pandas dataframe | I have a dataframe contains one column which has multiple strings separated by the comma, but in this string, I want to remove all matter after hyphen (including hyphen), main point is after in some cases hyphen is not there but directed parenthesis is there so I also want to remove that as well and carry all the after... | [
"The following code seems to reproduce your desired result:\ndd['sin'] = dd['sin'].str.split(\", \")\ndd = dd.explode('sin').reset_index()\ndd['sin'] = dd['sin'].str.replace('\\W.*', '', regex=True)\n\nWhich gives dd['sin'] as:\n0 U147\n1 U35\n2 P01\n3 P02\n4 P3\n5 P032\n6 P034\n7 ... | [
1,
0
] | [] | [] | [
"pandas",
"python",
"replace"
] | stackoverflow_0074664899_pandas_python_replace.txt |
Q:
pandas.read_excel parameter "sheet_name" not working
According to pandas doc for 0.21+, pandas.read_excel has a parameter sheet_name that allows specifying which sheet is read. But when I am trying to read the second sheet from an excel file, no matter how I set the parameter (sheet_name = 1, sheet_name = 'Sheet2'... | pandas.read_excel parameter "sheet_name" not working | According to pandas doc for 0.21+, pandas.read_excel has a parameter sheet_name that allows specifying which sheet is read. But when I am trying to read the second sheet from an excel file, no matter how I set the parameter (sheet_name = 1, sheet_name = 'Sheet2'), the dataframe always shows the first sheet, and passing... | [
"It looks like you're using the old version of Python.\nSo try to change your code \ndf = pd.read_excel(file_with_data, sheetname=sheet_with_data)\n\nIt should work properly.\n",
"You can try to use pd.ExcelFile:\nxls = pd.ExcelFile('path_to_file.xls')\ndf1 = pd.read_excel(xls, 'Sheet1')\ndf2 = pd.read_excel(xls,... | [
22,
7,
2,
1,
0,
0
] | [] | [] | [
"excel",
"pandas",
"python"
] | stackoverflow_0047975866_excel_pandas_python.txt |
Q:
Python evdev [Error 16] Device or resource busy
I connected 2D barcode scanner with Raspberry Pi 4 Model B and tried to scan few codes. on using evdev library I got the output successfully. But the issue is after 3 continues scans it's throwing me an exception saying "[Error 16] Device or resource busy". I can't a... | Python evdev [Error 16] Device or resource busy | I connected 2D barcode scanner with Raspberry Pi 4 Model B and tried to scan few codes. on using evdev library I got the output successfully. But the issue is after 3 continues scans it's throwing me an exception saying "[Error 16] Device or resource busy". I can't able to find the root cause of this issue and tried ma... | [
"I am not sure if the problem is related to your code. I think it is more related to your scanner. I have tested your script with the R32 QR Code reader (https://www.sycreader.com/en/3650/) and this is working perfect.\nWhat scanner type are you using?\nResult:\nScanned value:Toiletbezoek DateTime:2022-12-03 09:49:... | [
0,
0
] | [] | [] | [
"barcode_scanner",
"evdev",
"linux",
"python",
"raspberry_pi4"
] | stackoverflow_0074325312_barcode_scanner_evdev_linux_python_raspberry_pi4.txt |
Q:
google foobar : 'please pass the coded messages'. What is the matter in my code?
I happend to see the google foobar challenges and
i'm struggling to solve a problem, 'please pass the coded messages'
When submiting my solution code, i get the response that one failing in 5 tests.
I really scrutinize my code, but i ... | google foobar : 'please pass the coded messages'. What is the matter in my code? | I happend to see the google foobar challenges and
i'm struggling to solve a problem, 'please pass the coded messages'
When submiting my solution code, i get the response that one failing in 5 tests.
I really scrutinize my code, but i can't discover any error in mine.
--Problem--
You need to pass a message to the bunny ... | [
"You need to be thinking in terms of permutations of the digits in the input list. Bear in mind that the challenge states that \"some or all\" of the values may be used. So you need to be looking at permutations from 1 to the length of the input list (inclusive).\nThere's probably a more efficient way to do this bu... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074665209_python.txt |
Q:
How can I use Selenium, Webdriver-manager, Chromedriver on virtual environment?
I am using Github codespace for creating an automated web scraping application using Webdriver-manager webdriver-manager with Selenium.
I have tried: How can we use Selenium Webdriver in collab.research.google.com?
!pip install selen... | How can I use Selenium, Webdriver-manager, Chromedriver on virtual environment? | I am using Github codespace for creating an automated web scraping application using Webdriver-manager webdriver-manager with Selenium.
I have tried: How can we use Selenium Webdriver in collab.research.google.com?
!pip install selenium
!apt-get update # to update ubuntu to correctly run apt install
!apt install chro... | [
"Please consider rephrasing the question in a better way. The problematic is not clear.\n",
"please check https://stackoverflow.com/posts/46929945\nthis should work for you,\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\noptions = Options()\noptions.headless = True\ndriver... | [
0,
0
] | [] | [] | [
"codespaces",
"jupyter_notebook",
"python"
] | stackoverflow_0074657070_codespaces_jupyter_notebook_python.txt |
Q:
How can I increase my model performance in classification
Hi I am facing the problem that I have the dataset to tell if the person feels cold or not and the dataset given to me is known as the bad dataset and I want to maximize the accuracy and the precision of the model.
Right now the aacuracy is 53% and precisio... | How can I increase my model performance in classification | Hi I am facing the problem that I have the dataset to tell if the person feels cold or not and the dataset given to me is known as the bad dataset and I want to maximize the accuracy and the precision of the model.
Right now the aacuracy is 53% and precision is 19% the columns description is :-
Age AMV Met Clo Dwpt ... | [
"It sounds like you're trying to build a machine learning model to predict whether a person is feeling cold or not based on the dataset you provided. To improve the accuracy and precision of your model, there are several steps you can take.\nFirst, make sure you're using the right evaluation metrics for your proble... | [
0
] | [] | [] | [
"numpy",
"pandas",
"python"
] | stackoverflow_0074665415_numpy_pandas_python.txt |
Q:
How do i loop through the fields of a form in python?
I am trying to find out how "complete" a users profile is as a percentage.
I want to loop through the fields of a form to see which are still left blank and return a completion percentage.
My question is how do I reference each form value in the loop without ha... | How do i loop through the fields of a form in python? | I am trying to find out how "complete" a users profile is as a percentage.
I want to loop through the fields of a form to see which are still left blank and return a completion percentage.
My question is how do I reference each form value in the loop without having to write out the name of each field?
Is this possible?... | [
"To reference each form value in a loop without having to write out the name of each field in Python, you can use the items() method on the form.fields.values dictionary to iterate over the key-value pairs in the dictionary.\nHere is an example of how you could update your code to use the items() method to loop ove... | [
0
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0074665090_django_django_forms_python.txt |
Q:
why "if else" doesn't work in this piece of code
page = 1
img_count = 0
result_list = []
while True:
url = f'https://s3.landingfolio.com/inspiration?page={page}&sortBy=free-first'
response = requests.get(url=url, headers=headers)
data = response.json()
for item in data:
if page <= 11:
... | why "if else" doesn't work in this piece of code | page = 1
img_count = 0
result_list = []
while True:
url = f'https://s3.landingfolio.com/inspiration?page={page}&sortBy=free-first'
response = requests.get(url=url, headers=headers)
data = response.json()
for item in data:
if page <= 11:
screenshots = item.get('screenshots')
... | [
"The code in the else block will not be executed because the return statement is inside the else block. The return statement causes the function to immediately return a value and exit, so the code in the else block will never be executed.\nYou can fix this by moving the return statement outside of the else block, l... | [
1
] | [] | [] | [
"if_statement",
"python"
] | stackoverflow_0074665438_if_statement_python.txt |
Q:
To find sum of 5 55 555 5555 .... n using python
We need to find the sum of the following number to a given range n which describes is n=5 then the last term will be 55555.
A:
You can use the mul operator to repeat the digit, convert back to an integer and sum.
def find_sum(digit, max_repeats):
return sum(in... | To find sum of 5 55 555 5555 .... n using python | We need to find the sum of the following number to a given range n which describes is n=5 then the last term will be 55555.
| [
"You can use the mul operator to repeat the digit, convert back to an integer and sum.\ndef find_sum(digit, max_repeats):\n return sum(int(str(digit)*(i+1)) for i in range(max_repeats))\n\nprint(find_sum(5, 5))\n#output 61725\n\n",
"You can use the idea from the following algorithm:\ndef sum(n):\n # This wi... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074665350_python.txt |
Q:
if else condition how to print even odd
Given an integer, , perform the following conditional actions:
If is odd, print "Weird".
If is even and in the inclusive range of to , print "Not Weird".
If is even and in the inclusive range of to , print "Weird".
If is even and greater than , print "Not Weird".
Input... | if else condition how to print even odd | Given an integer, , perform the following conditional actions:
If is odd, print "Weird".
If is even and in the inclusive range of to , print "Not Weird".
If is even and in the inclusive range of to , print "Weird".
If is even and greater than , print "Not Weird".
Input Format:
A single line containing a positive ... | [] | [] | [
"I believe something like this:\ndef conditional_print(text):\n number = int(text)\n if number % 2 == 1:\n print(\"Weird\")\n elif ... <= number <= ...:\n print(\"Not Weird\")\n elif ... <= number <= ...:\n print(\"Weird\")\n elif ... < number:\n print(\"Not Weird\")\ncond... | [
-1
] | [
"python"
] | stackoverflow_0074665401_python.txt |
Q:
How to solve the error: 'tuple' object has no attribute 'decode' with django-channels
When I tried to execute the channels' tutorial in order to establishing the django website with websocket, the error message emerged:
AttributeError: 'tuple' object has no attribute 'decode'
I just executed following code:
$ pyth... | How to solve the error: 'tuple' object has no attribute 'decode' with django-channels | When I tried to execute the channels' tutorial in order to establishing the django website with websocket, the error message emerged:
AttributeError: 'tuple' object has no attribute 'decode'
I just executed following code:
$ python3 manage.py shell
>>> import channels.layers
>>> channel_layer = channels.layers.get_chan... | [
"It looks like you are encountering an AttributeError when trying to send a message to a channel using the channels and asgiref libraries in Python. This error is raised when you try to call a method on an object that does not have that method.\nIn this case, it appears that the decode method is being called on a t... | [
0
] | [] | [] | [
"channels",
"django_channels",
"python"
] | stackoverflow_0074665490_channels_django_channels_python.txt |
Q:
Add a custom javascript to the FastAPI Swagger UI docs webpage in Python
I want to load my custom javascript file or code to the FastAPI Swagger UI webpage, to add some dynamic interaction when I create a FastAPI object.
For example, in Swagger UI on docs webpage I would like to
<script src="custom_script.js"></sc... | Add a custom javascript to the FastAPI Swagger UI docs webpage in Python | I want to load my custom javascript file or code to the FastAPI Swagger UI webpage, to add some dynamic interaction when I create a FastAPI object.
For example, in Swagger UI on docs webpage I would like to
<script src="custom_script.js"></script>
or
<script> alert('worked!') </script>
I tried:
api = FastAPI(docs_ur... | [
"Finally I made it working. This is what I did:\nfrom fastapi.openapi.docs import (\n get_redoc_html,\n get_swagger_ui_html,\n get_swagger_ui_oauth2_redirect_html,\n)\nfrom fastapi.staticfiles import StaticFiles\n\napi = FastAPI(docs_url=None) \n\npath_to_static = os.path.join(os.path.dirname(__file__), 's... | [
1
] | [] | [] | [
"fastapi",
"python",
"swagger_ui"
] | stackoverflow_0074661044_fastapi_python_swagger_ui.txt |
Q:
Django QuerySet: additional field for counting value's occurence
I have a QuerySet object with 100 items, for each of them I need to know how many times a particular contract_number occurs in the contract_number field.
Example of expected output:
[{'contract_number': 123, 'contract_count': 2}, {'contract_number':... | Django QuerySet: additional field for counting value's occurence | I have a QuerySet object with 100 items, for each of them I need to know how many times a particular contract_number occurs in the contract_number field.
Example of expected output:
[{'contract_number': 123, 'contract_count': 2}, {'contract_number': 456, 'contract_count': 1} ...]
This means that value 123 occurs 2 ti... | [
"You can use annotation like this:\nfrom django.db.models import Count\nTracker.objects.values('contract_number').annotate(contract_count=Count('contract_number')).order_by()\n\n",
"Solutions:\ncounttraker=Traker.objects.values('contract_number').annotate(Count('contract_number'))\nsubquery=counttraker.filter(con... | [
5,
0
] | [] | [] | [
"django",
"django_queryset",
"extra",
"python",
"sql"
] | stackoverflow_0051150898_django_django_queryset_extra_python_sql.txt |
Q:
Arduino extract data from serial monitor
I wrote a simple controller for my robot in Python and now I want to send the data over the serial monitor to the Arduino. I managed to send the values but now I want to know how I can extract the data from the monitor with the Arduino. My Python code:
import PySimpleGUI as... | Arduino extract data from serial monitor | I wrote a simple controller for my robot in Python and now I want to send the data over the serial monitor to the Arduino. I managed to send the values but now I want to know how I can extract the data from the monitor with the Arduino. My Python code:
import PySimpleGUI as sg
import serial
import time
import math
Arm... | [
"I am assuming that the data goes to Serial in this Format as String:\n\n[1,valX,valY,valZ]\n\nAfter reading the data from Serial and converting the data line to String with String() function, you can assign the values to desired variables using sscanf() function.\nThe function works like this -\n\nsscanf(const cha... | [
0
] | [] | [] | [
"arduino",
"python",
"python_3.x",
"serial_port"
] | stackoverflow_0074656927_arduino_python_python_3.x_serial_port.txt |
Q:
JavaScript JSON reviver in Python
I'm having problem translating my JavaScript snippet to Python.
The JavaScript code looks like this:
const reviver = (_key, value) => {
try {
return JSON.parse(value, reviver);
} catch {
if(typeof value === 'string') {
const semiValues = value.split(';');
i... | JavaScript JSON reviver in Python | I'm having problem translating my JavaScript snippet to Python.
The JavaScript code looks like this:
const reviver = (_key, value) => {
try {
return JSON.parse(value, reviver);
} catch {
if(typeof value === 'string') {
const semiValues = value.split(';');
if(semiValues.length > 1) {
retu... | [
"I solved my issue by iterating through the values and parse them accordingly\nimport json\n\ndef parse_value(value):\n if(isinstance(value, str)):\n try:\n return parse_value(json.loads(value))\n except:\n pass\n semi_values = value.split(';')\n if(len(semi_valu... | [
0,
0
] | [
"Does this code works for you?\ndef reviver(_key, value):\n try:\n return json.loads(value, object_hook=reviver)\n except:\n if type(value) == str:\n semi_values = value.split(';')\n if len(semi_values) > 1:\n return string_to_object(json.dumps(semi_values))\... | [
-1
] | [
"javascript",
"json",
"python",
"reviver_function"
] | stackoverflow_0074654080_javascript_json_python_reviver_function.txt |
Q:
Skips the first page. Scraping python
The program does not want to collect data from the first page. Starts collecting from the second page.
If I try to collect data from the first page separately, everything works. And with the help of a cycle through the pages, then the first page is skipped
import requests
from... | Skips the first page. Scraping python | The program does not want to collect data from the first page. Starts collecting from the second page.
If I try to collect data from the first page separately, everything works. And with the help of a cycle through the pages, then the first page is skipped
import requests
from bs4 import BeautifulSoup
headers = {
... | [
"import httpx\nimport trio\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nfrom urllib.parse import urljoin\n\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:107.0) Gecko/20100101 Firefox/107.0'\n}\n\n\nclass Spider:\n def __init__(self, client) -> None:\n self.client = ... | [
0
] | [] | [] | [
"beautifulsoup",
"python",
"web_scraping"
] | stackoverflow_0074665378_beautifulsoup_python_web_scraping.txt |
Q:
Filling Algorithm for Equal Distribution
Need your help resolving algorithm task -
There are 3 baskets, basket 1 has 10 balls and a possible max capacity of 100, basket 2 has 50 balls and a possible max capacity of 200, and basket 3 has 100 balls and a possible max capacity of 300.
Please help me to write an algor... | Filling Algorithm for Equal Distribution | Need your help resolving algorithm task -
There are 3 baskets, basket 1 has 10 balls and a possible max capacity of 100, basket 2 has 50 balls and a possible max capacity of 200, and basket 3 has 100 balls and a possible max capacity of 300.
Please help me to write an algorithm or code that split another 100 balls betw... | [
"As already mentioned in one of my comments. If you want to have an equal distribution of %fill, then you could add the balls individually to the current lowest filled basket:\nimport numpy as np\n\ndef fill_baskets(baskets, ballsToDistribute):\n for i in range(ballsToDistribute, 0, -1):\n # find the bask... | [
1
] | [] | [] | [
"algorithm",
"dart",
"python"
] | stackoverflow_0074665160_algorithm_dart_python.txt |
Q:
Get count of objects in a specific S3 folder using Boto3
Trying to get count of objects in S3 folder
Current code
bucket='some-bucket'
File='someLocation/File/'
objs = boto3.client('s3').list_objects_v2(Bucket=bucket,Prefix=File)
fileCount = objs['KeyCount']
This gives me the count as 1+actual number of objects ... | Get count of objects in a specific S3 folder using Boto3 | Trying to get count of objects in S3 folder
Current code
bucket='some-bucket'
File='someLocation/File/'
objs = boto3.client('s3').list_objects_v2(Bucket=bucket,Prefix=File)
fileCount = objs['KeyCount']
This gives me the count as 1+actual number of objects in S3.
Maybe it is counting "File" as a key too?
| [
"Assuming you want to count the keys in a bucket and don't want to hit the limit of 1000 using list_objects_v2. The below code worked for me but I'm wondering if there is a better faster way to do it! Tried looking if there's a packaged function in boto3 s3 connector but there isn't!\n# connect to s3 - assuming you... | [
15,
3,
1,
0,
0
] | [] | [] | [
"amazon_s3",
"boto3",
"python"
] | stackoverflow_0054656455_amazon_s3_boto3_python.txt |
Q:
How to access command history in Python shell on Windows Terminal Bash?
I sometimes want to experiment with Python code in the Python shell. In other languages (Haskell, F#) I'm used to be able to experiment in a REPL that supports command history.
I start the Python shell from (Git) Bash running in Windows Termin... | How to access command history in Python shell on Windows Terminal Bash? | I sometimes want to experiment with Python code in the Python shell. In other languages (Haskell, F#) I'm used to be able to experiment in a REPL that supports command history.
I start the Python shell from (Git) Bash running in Windows Terminal:
$ py
Python 3.11.0 (main, Oct 24 2022, 18:26:48) [MSC v.1933 64 bit (AMD6... | [
"In the Python shell, you can use the up and down arrow keys to scroll through the command history. This should work both in the Command Prompt and in Bash in Windows Terminal.\nIf this does not work for you, you can try enabling command history in the Python shell by running the following commands:\nimport readlin... | [
1
] | [] | [] | [
"bash",
"python",
"windows_terminal"
] | stackoverflow_0074665663_bash_python_windows_terminal.txt |
Q:
How to draw animation in pyopengltk framework
I am using pyopengl, tkinter, pyopengltk to draw a Rubik's cube and am going to implement a Rubik's cube recovery animation, now I have implemented to display a Rubik's cube in tkinter with this quiz. How to rotate slices of a Rubik's Cube in python PyOpenGL? But I can... | How to draw animation in pyopengltk framework | I am using pyopengl, tkinter, pyopengltk to draw a Rubik's cube and am going to implement a Rubik's cube recovery animation, now I have implemented to display a Rubik's cube in tkinter with this quiz. How to rotate slices of a Rubik's Cube in python PyOpenGL? But I can't implement the tesseract animation step by step n... | [
"You must implement the keyebord events similar as in the Pygame implementation decribed in the answer to How to rotate slices of a Rubik's Cube in python PyOpenGL?.\nRemove:\nself.animate, self.action = True, rot_slice_map['K_1']\nChange the key mapping to a mapping to be used with tkinter\nrot_cube_map = {'Up': (... | [
0
] | [] | [] | [
"opengl",
"pyopengl",
"python",
"tkinter"
] | stackoverflow_0074664263_opengl_pyopengl_python_tkinter.txt |
Q:
3D Delaunay triangulation: bad output (extra simplices appearing)
I am using python3.11 to create the Delaunay triangulation of a point cloud with script.Delaunay and it is misbehaving by creating some extra faces. In the image below you can see a 3D scatter plot of the points.
The image was created using the nex... | 3D Delaunay triangulation: bad output (extra simplices appearing) | I am using python3.11 to create the Delaunay triangulation of a point cloud with script.Delaunay and it is misbehaving by creating some extra faces. In the image below you can see a 3D scatter plot of the points.
The image was created using the next very few lines of code:
import plotly.graph_objects as go
fig = go.Fi... | [
"Firstly, I congratulate you on such an exquisite example. I recommend you explore examples of the function Delaunay. The documentation exhibits several properties whose output may interest you.\n",
"Referring to my comments for your original question... The extra simplices occur because some of your vertices are... | [
0,
0
] | [] | [] | [
"3d",
"plotly_python",
"python",
"scipy",
"triangulation"
] | stackoverflow_0074642689_3d_plotly_python_python_scipy_triangulation.txt |
Q:
Powershell's Prompt change to just "PS" when I run "conda activate xx" in, What happend?
When I activate my conda environment in powershell, The Prompt change to just "PS".
In normal, the Prompt is "(base) PS C:\Users\xxx", but It's just "PS" now. What happend? I want to get it back.
My conda's version is "conda 2... | Powershell's Prompt change to just "PS" when I run "conda activate xx" in, What happend? | When I activate my conda environment in powershell, The Prompt change to just "PS".
In normal, the Prompt is "(base) PS C:\Users\xxx", but It's just "PS" now. What happend? I want to get it back.
My conda's version is "conda 22.11.0".
I want it to be "(xx) PS C:\Users\xxx", not just "PS".
| [
"I found a solution.\nI can update powershell to 7 to solve the problem. But that's so weird. Why?\n"
] | [
0
] | [] | [] | [
"conda",
"powershell",
"python"
] | stackoverflow_0074665678_conda_powershell_python.txt |
Q:
AttributeError: module 'ipyparallel' has no attribute 'Cluster'
I am going through the tutorial to learn ipyparallel and while doing so, I got the error: AttributeError: module 'ipyparallel' has no attribute 'Cluster'
I uninstalled and reinstalled the package but the error persisted, does anyone have any tips for ... | AttributeError: module 'ipyparallel' has no attribute 'Cluster' | I am going through the tutorial to learn ipyparallel and while doing so, I got the error: AttributeError: module 'ipyparallel' has no attribute 'Cluster'
I uninstalled and reinstalled the package but the error persisted, does anyone have any tips for solving this issue?
My Code/ Issue:
Thanks
| [
"Make sure your ipyparallel version is greater or equal to 7.0.\nIn [1]: import ipyparallel as ipp\n\nIn [2]: ipp.__version__\nOut[2]: '6.3.0'\n\nIn [3]: hasattr(ipp, \"Cluster\")\nOut[3]: False\n\nSometimes conda install ipyparallel may not install the newest version. Try using pip install ipyparallel. After versi... | [
0
] | [] | [] | [
"ipython",
"ipython_parallel",
"python"
] | stackoverflow_0072331252_ipython_ipython_parallel_python.txt |
Q:
Cython --embed flag in setup.py
I am starting to compile my Python 3 project with Cython, and I would like to know if it's possible to reduce my current compile time workflow to a single instruction.
This is my setup.py as of now:
from distutils.core import setup
from distutils.extension import Extension
from Cyth... | Cython --embed flag in setup.py | I am starting to compile my Python 3 project with Cython, and I would like to know if it's possible to reduce my current compile time workflow to a single instruction.
This is my setup.py as of now:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
extensions... | [
"Start off with checking out the docs for the utility you're using. If there are complicated arguments, there is probably a config file.\nThis should tidy up your first command:\n# setup.cfg\n[build_ext]\ninplace=1\n\nI don't see anything in the docs about a post-build step, and I wouldn't really expect this proce... | [
0,
0
] | [] | [] | [
"cython",
"python",
"python_3.5"
] | stackoverflow_0046824143_cython_python_python_3.5.txt |
Q:
when installing pyaudio, pip cannot find portaudio.h in /usr/local/include
I'm using mac osx 10.10
As the PyAudio Homepage said, I install the PyAudio using
brew install portaudio
pip install pyaudio
the installation of portaudio seems successful, I can find headers and libs in /usr/local/include and /usr/local/... | when installing pyaudio, pip cannot find portaudio.h in /usr/local/include | I'm using mac osx 10.10
As the PyAudio Homepage said, I install the PyAudio using
brew install portaudio
pip install pyaudio
the installation of portaudio seems successful, I can find headers and libs in /usr/local/include and /usr/local/lib
but when I try to install pyaudio, it gives me an error that
src/_portaudiom... | [
"Since pyAudio has portAudio as a dependency, you first have to install portaudio.\nbrew install portaudio\n\nThen try: pip install pyAudio. If the problem persists after installing portAudio, you can specify the directory path where the compiler will be able to find the source programs (e.g: portaudio.h). Since th... | [
182,
27,
16,
13,
9,
8,
8,
6,
5,
4,
1,
1,
1,
0
] | [] | [] | [
"macos",
"pyaudio",
"python"
] | stackoverflow_0033513522_macos_pyaudio_python.txt |
Q:
replace multiple words from a string at the same time
I have this dict in python.
reflections = {
'I am': 'you are',
'I was': 'you were',
'I': 'you',
"I'm": 'you are',
"I'd": 'you would',
"I've": 'you have',
"I'll": 'you will',
'my': 'your',
'you are': 'I am',
'you were': '... | replace multiple words from a string at the same time | I have this dict in python.
reflections = {
'I am': 'you are',
'I was': 'you were',
'I': 'you',
"I'm": 'you are',
"I'd": 'you would',
"I've": 'you have',
"I'll": 'you will',
'my': 'your',
'you are': 'I am',
'you were': 'I was',
"you've": 'I have',
"you'll": 'I will',
... | [
"Solution 1 - str.index\nYou can do it as follows:\n\ncreate a new string variable new_see, which is initially empty, but will ultimately contain the result of the replacements\nmake each iteration only process the part of the input string up until the point where a matching key is encountered, and append the itera... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0058393229_python.txt |
Q:
Google SheetsAPI: ValueError: Client secrets must be for a web or installed app
Very similar to this question: ValueError: Client secrets must be for a web or installed app but with a twist: I'm trying to do this through a Google Cloud Virtual Machine.
Recently, the Out-Of-Band (OOB) flow stopped working for me (i... | Google SheetsAPI: ValueError: Client secrets must be for a web or installed app | Very similar to this question: ValueError: Client secrets must be for a web or installed app but with a twist: I'm trying to do this through a Google Cloud Virtual Machine.
Recently, the Out-Of-Band (OOB) flow stopped working for me (it seems the reason may lie here: oob-migration. Until then, I was able to easily run ... | [
"The code you are are using was designed for an installed. Which is exactly what your error message is saying. The QuickStart clearly states Click Application type > Desktop app.\nWhile i agree the error message states installed or web, i am not sure that code can be used for a web application.\n\nClient secrets ... | [
1
] | [] | [] | [
"google_api",
"google_api_python_client",
"google_oauth",
"google_sheets_api",
"python"
] | stackoverflow_0074663524_google_api_google_api_python_client_google_oauth_google_sheets_api_python.txt |
Q:
How to lowercase selected item in a list
I have
x= ['AA', 'BB', 'CC']
and I want to lower case only 'BB'.
A:
To transform a string to lowercase, you use
string.lower()
To answer your question, use
x[1] = x[1].lower()
A:
perhaps try
`
x = ['AA', 'BB', 'CC']
Str = x[1]
print(Str.lower())
`
#0 = AA, 1 = BB, 2 =... | How to lowercase selected item in a list | I have
x= ['AA', 'BB', 'CC']
and I want to lower case only 'BB'.
| [
"To transform a string to lowercase, you use\nstring.lower()\n\nTo answer your question, use\nx[1] = x[1].lower()\n\n",
"perhaps try\n`\nx = ['AA', 'BB', 'CC']\nStr = x[1]\nprint(Str.lower())\n`\n#0 = AA, 1 = BB, 2 = CC\nuse 0 1 or 2 with x[NUMBER]\nI hope this works for you!! \nEDIT: or you can use x[num] direct... | [
0,
0
] | [] | [] | [
"lowercase",
"python",
"string"
] | stackoverflow_0074665441_lowercase_python_string.txt |
Q:
RuntimeWarning: coroutine 'setup' was never awaited setup(self)
I am trying to create a discord bot, but I am caught in an unending loop of problems. In every video I've watched, it is recommended that you write the cog loading function as thus:
async def load_auto():
for filename in os.listdir('./cogs'):
... | RuntimeWarning: coroutine 'setup' was never awaited setup(self) | I am trying to create a discord bot, but I am caught in an unending loop of problems. In every video I've watched, it is recommended that you write the cog loading function as thus:
async def load_auto():
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
await bot.load_extens... | [
"The add_cog is not an async function or coroutine. It's a normal function. This is easily fixable by removing the await statement.\nBefore\nawait bot.add_cog(Personality(bot))\n\nAfter\nbot.add_cog(Personality(bot))\n\nEdit.\nSorry, I forgot to answer the question, Does await bot.load_extension(cogs) actually not ... | [
0,
0
] | [] | [] | [
"bots",
"discord",
"discord.py",
"python"
] | stackoverflow_0074664982_bots_discord_discord.py_python.txt |
Q:
Pretty JSON Formatting in IPython Notebook
Is there an existing way to get json.dumps() output to appear as "pretty" formatted JSON inside ipython notebook?
A:
json.dumps has an indent argument, printing the result should be enough:
print(json.dumps(obj, indent=2))
A:
This might be slightly different than wha... | Pretty JSON Formatting in IPython Notebook | Is there an existing way to get json.dumps() output to appear as "pretty" formatted JSON inside ipython notebook?
| [
"json.dumps has an indent argument, printing the result should be enough:\nprint(json.dumps(obj, indent=2))\n\n",
"This might be slightly different than what OP was asking for, but you can do use IPython.display.JSON to interactively view a JSON/dict object.\nfrom IPython.display import JSON\nJSON({'a': [1, 2, 3,... | [
101,
74,
39,
7,
3,
0,
0,
0
] | [] | [] | [
"ipython_notebook",
"json",
"python"
] | stackoverflow_0018873066_ipython_notebook_json_python.txt |
Q:
'NoneType' object is not callable when tryna do a histogram on datafram
rfm = df3.groupby('CustomerID').agg({
'InvoiceNo' : lambda num: len(num),
'TotalSum' : lambda price: price.sum(),
'InvoiceDay': lambda x: ref_date- x.max()})
rfm.rename(columns={
'InvoiceNo' : 'Frequency',
'TotalSum' : 'M... | 'NoneType' object is not callable when tryna do a histogram on datafram | rfm = df3.groupby('CustomerID').agg({
'InvoiceNo' : lambda num: len(num),
'TotalSum' : lambda price: price.sum(),
'InvoiceDay': lambda x: ref_date- x.max()})
rfm.rename(columns={
'InvoiceNo' : 'Frequency',
'TotalSum' : 'Monetary',
'InvoiceDay': 'Recency'
}, inplace=True)
rfm['Recency'] = rfm... | [
"Still trying to figure out what moment it happens as we need the whole error log. But that error is trying to tell you that you are invoking a method on a None type. Meaning that some of the attributes return None, and you are still trying to access them.\nTo debug, recommend checking the pandas DataFrame first, p... | [
0
] | [] | [] | [
"dataframe",
"python"
] | stackoverflow_0074665665_dataframe_python.txt |
Q:
Change Django Default Language
I've been developing a web application in English, and now I want to change the default language to German.
I tried changing the language code and adding the locale directory with all the translations, but Django still shows everything in English. I also want all my table names to be... | Change Django Default Language | I've been developing a web application in English, and now I want to change the default language to German.
I tried changing the language code and adding the locale directory with all the translations, but Django still shows everything in English. I also want all my table names to be in German along with the content in... | [
"Turns out everything is just right, and the only thing that messed things up was a typo in LOCALE_PATHS.\nsettings.py:\nLOCALE_PATHS = ( # notice the S which was forgotten\n os.path.join(BASE_DIR, 'locale')\n)\n\n"
] | [
0
] | [] | [] | [
"django",
"django_i18n",
"python",
"translation"
] | stackoverflow_0074590212_django_django_i18n_python_translation.txt |
Q:
TypeError: unsupported operand type(s) for -=: 'str' and 'float'
I've tried to write a program which converts decimal to binary and vice versa but when I try 23, it flags line 17 (answer2 -= x) as a type error.
import math
x = 4096
y = ""
z = 10
q = 1
final_answer = 0
answer1 = str(in... | TypeError: unsupported operand type(s) for -=: 'str' and 'float' | I've tried to write a program which converts decimal to binary and vice versa but when I try 23, it flags line 17 (answer2 -= x) as a type error.
import math
x = 4096
y = ""
z = 10
q = 1
final_answer = 0
answer1 = str(input("Do you want to convert decimal into binary (1) or binary into dec... | [
"Your variable is still a string when you apply an operation involving a numeric value. In your case, you still need to convert the variable to a float:\nanswer2 = float(answer2)\n\nFurthermore, I do not know if isdigit() catches floats (involving a decimal point). This post might help out if you get stuck there: U... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074665643_python.txt |
Q:
Python - Can I sort a dictionary by one of the values that is in a list?
How can I have the following dictionary sorted based on a value that is in a list?
Data = {1:["name",2010],2:["name",2005],3:["name",2000]}
sortedDataByYear = {3:["name",2000],2:["name",2005],1:["name",2010]}
I have tried sorted(lambda), but... | Python - Can I sort a dictionary by one of the values that is in a list? | How can I have the following dictionary sorted based on a value that is in a list?
Data = {1:["name",2010],2:["name",2005],3:["name",2000]}
sortedDataByYear = {3:["name",2000],2:["name",2005],1:["name",2010]}
I have tried sorted(lambda), but there is something wrong.
| [
"Dictionaries can't be sorted.\nHowever, you can do this:\nData = {1:[\"name\",2010],2:[\"name\",2005],3:[\"name\",2000]}\nsorted(Data.items(), key = lambda x: x[1])\n\nThis will return a list instead, but sorted on the first index in ascending order.\n"
] | [
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074665953_dictionary_python.txt |
Q:
How to create classes with information from a JSON file
My goal is to send multiple emails with information coming from json.
What is the best way to loop through the file and create classes for each page?
Thanks in advance
This is the JSON data:
{
"object": "list",
"results": [
{
"object": "page",
... | How to create classes with information from a JSON file | My goal is to send multiple emails with information coming from json.
What is the best way to loop through the file and create classes for each page?
Thanks in advance
This is the JSON data:
{
"object": "list",
"results": [
{
"object": "page",
"id": "2",
"created_time": "2022-12-03T09:15:00.00... | [
"You may try using pandas to load the JSON into a dataframe. Then, you can create a new class for each page and assign the relevant data to its fields. For example, you could create a class like this:\nclass Email:\n def __init__(self, email_sender, email_receiver, subject, text):\n self.email_sender = em... | [
0
] | [] | [] | [
"json",
"python",
"python_3.x"
] | stackoverflow_0074665661_json_python_python_3.x.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.