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:
PyQt5: make QCompleter popup readonly
I have a QCompleter for a QLineEdit and it's working fine.
All I want is for this completer to be only read-only. So the user can only see the matches but cannot select any one of them. No highlighting, no selected item. Only a visible list of matches should be shown.
I tried ... | PyQt5: make QCompleter popup readonly | I have a QCompleter for a QLineEdit and it's working fine.
All I want is for this completer to be only read-only. So the user can only see the matches but cannot select any one of them. No highlighting, no selected item. Only a visible list of matches should be shown.
I tried for so long, but I'm still stuck and could ... | [
"One way to do this would be to use a custom item-view and selection-model with reimplemented methods that disable all the default selection, mouse and keyboard handling. It will also be necessary to ensure the custom selection-model is linked to the completer's internal proxy model.\nHere is a working demo based o... | [
2
] | [] | [] | [
"pyqt5",
"python",
"qcompleter",
"qlineedit",
"readonly"
] | stackoverflow_0074112532_pyqt5_python_qcompleter_qlineedit_readonly.txt |
Q:
How to compare date(different format) from a list of Variables in Python
I need to extract the string variable with latest timestamp from a list.
The variables are in below format:
|Name|
|:---|
|First_Record2022-10-11_NameofRecord.txt|
|Second_Record_20221017.txt|
for now, i am fetching this in a list and iterati... | How to compare date(different format) from a list of Variables in Python | I need to extract the string variable with latest timestamp from a list.
The variables are in below format:
|Name|
|:---|
|First_Record2022-10-11_NameofRecord.txt|
|Second_Record_20221017.txt|
for now, i am fetching this in a list and iterating in a for loop to get the latest date from the two records using below line ... | [
"IIUC , is that what you're looking for?\ndf['date']= df['Name'].str.extract(r'(\\d{4}.*?(?=[_|\\.]))').replace(r'-','',regex=True)\ndf.sort_values('date').tail(1)['Name'].squeeze()\n\n\n'Second_Record_20221017.txt'\n\n"
] | [
1
] | [] | [] | [
"azure_databricks",
"dataframe",
"datetime",
"python"
] | stackoverflow_0074116348_azure_databricks_dataframe_datetime_python.txt |
Q:
How to delete a line of a data frame in python using pandas?
I want to delete the line that is in the loop.
I tried data.drop(), but it doesn't work
for i, receb in enumerate(data['recebimento']):
if ordem == data.iloc[i, data.columns.get_loc('ordem')]:
driver.find_element(By.XPATH,'//*::cont... | How to delete a line of a data frame in python using pandas? | I want to delete the line that is in the loop.
I tried data.drop(), but it doesn't work
for i, receb in enumerate(data['recebimento']):
if ordem == data.iloc[i, data.columns.get_loc('ordem')]:
driver.find_element(By.XPATH,'//*::content"]').send_keys(str(imei))
print(imei)
data.drop... | [
"Pandas drop method is not defaulted to perform the operation in place, but it returns a resulting dataframe; to change this, use the inplace flag. It is also good idea to specify the axis you're dropping; it defaults to 0 (Rows), but makes your code cleaner. Finally, your drop should look something like this:\ndat... | [
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074116201_pandas_python.txt |
Q:
create bookmarks for separate pdf files using the filename
Hi I am trying to merge multiple pdfs with the filename of each pdf as the bookmark I intent to do this by merging the pdfs once the bookmark has been created on each pdf individually, I have managed to merge all pdfs and I have managed to make a bookmark ... | create bookmarks for separate pdf files using the filename | Hi I am trying to merge multiple pdfs with the filename of each pdf as the bookmark I intent to do this by merging the pdfs once the bookmark has been created on each pdf individually, I have managed to merge all pdfs and I have managed to make a bookmark for an individual pdf using the pdfs filename however I have not... | [
"\nhttps://pypdf2.readthedocs.io/en/latest/user/merging-pdfs.html\nhttps://pypdf2.readthedocs.io/en/latest/modules/PdfMerger.html?highlight=bookmark#PyPDF2.PdfMerger.add_bookmark\n\nYou can merge the pdfs and create the bookmarks as you go.\nfrom PyPDF2 import PdfMerger\nmerger = PdfMerger()\n//files is supposed to... | [
0
] | [] | [] | [
"pypdf2",
"python"
] | stackoverflow_0074071638_pypdf2_python.txt |
Q:
How to remove items from 2 lists based on duplicate items in one of the lists while maintaining order?
I have 2 lists:
list_1 = [[1,1], [1,3], [1,1], [1,4]]
list_2 = ["string_1", "string_2", "string_3", "string_4"]
My goal is to remove the duplicate sublists from list_1 and also the strings in list_2 that have th... | How to remove items from 2 lists based on duplicate items in one of the lists while maintaining order? | I have 2 lists:
list_1 = [[1,1], [1,3], [1,1], [1,4]]
list_2 = ["string_1", "string_2", "string_3", "string_4"]
My goal is to remove the duplicate sublists from list_1 and also the strings in list_2 that have the same index as the sublists removed, while maintaining the order of the sublists.
I found that I can remove... | [
"You can use zip:\nlist_1 = [[1,1], [1,3], [1,1], [1,4]]\nlist_2 = [\"string_1\", \"string_2\", \"string_3\", \"string_4\"]\n\noutput_1, output_2 = [], []\n\nseen = set()\n\nfor sublst, s in zip(list_1, list_2):\n if (tup := tuple(sublst)) in seen:\n continue\n\n seen.add(tup)\n\n output_1.append(su... | [
2,
0,
0,
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074116204_list_python.txt |
Q:
Python Pandas - add two groupby functions to one df
DF has data like -
students = [{'Class':'Class 8', 'Div': 'A', 'Name':'Ankit', 'Marks':94, 'Practical_Marks':48},
{'Class':'Class 8', 'Div': 'A', 'Name':'Swapnil', 'Marks':92, 'Practical_Marks':50},
{'Class':'Class 9', 'Div': 'A', 'Name':'... | Python Pandas - add two groupby functions to one df | DF has data like -
students = [{'Class':'Class 8', 'Div': 'A', 'Name':'Ankit', 'Marks':94, 'Practical_Marks':48},
{'Class':'Class 8', 'Div': 'A', 'Name':'Swapnil', 'Marks':92, 'Practical_Marks':50},
{'Class':'Class 9', 'Div': 'A', 'Name':'Priya', 'Marks':96, 'Practical_Marks':49},
{'... | [
"The following snippet should do the job for you:\nimport pandas as pd\n\n# Sample Data\nstudents = [{'Class':'Class 8', 'Div': 'A', 'Name':'Ankit', 'Marks':94, 'Practical_Marks':48}, {'Class':'Class 8', 'Div': 'A', 'Name':'Swapnil', 'Marks':92, 'Practical_Marks':50}, {'Class':'Class 9', 'Div': 'A', 'Name':'Priya',... | [
1,
1
] | [] | [] | [
"group_by",
"pandas",
"python"
] | stackoverflow_0074116083_group_by_pandas_python.txt |
Q:
How to modify the values of variables in one python file from another?
I want to create a python program where I can modify the values in a program and use the modified values in another program.
Here's an example:
vars.py
a = 20
b = 30
x = 20+30
func.py
import vars
def changevalues():
vars.a = 40
vars.b ... | How to modify the values of variables in one python file from another? | I want to create a python program where I can modify the values in a program and use the modified values in another program.
Here's an example:
vars.py
a = 20
b = 30
x = 20+30
func.py
import vars
def changevalues():
vars.a = 40
vars.b = 50
main.py
import vars
import func
func.changevalues()
print(vars.x)
Wh... | [
"The only change you need to make to your code is to change the existing variable x from within your function. So, for example, add just one line to changevalues():\ndef changevalues():\n vars.a = 40\n vars.b = 50\n vars.x = vars.a + vars.b\n\nThen run main.py and your result will be:\n90\n\n"
] | [
1
] | [] | [] | [
"python",
"python_module"
] | stackoverflow_0074105723_python_python_module.txt |
Q:
Partial update of an Object field in MongoDB document FastAPI
I am trying to update only given fields in an Object. In this case the object is a user whose schema looks like this:
class BasicUser(BaseModel):
timestamp: datetime = Field(default_factory=datetime.now)
name: str = Field(...)
surname: str =... | Partial update of an Object field in MongoDB document FastAPI | I am trying to update only given fields in an Object. In this case the object is a user whose schema looks like this:
class BasicUser(BaseModel):
timestamp: datetime = Field(default_factory=datetime.now)
name: str = Field(...)
surname: str = Field(...)
email: EmailStr = Field(...)
phone: constr(
... | [
"Assuming that the generated new_user object does indeed only contain fields to change that are nested inside of the user field in the document (which sounds like it is the case), then probably the most straightforward option here is to use an aggregation pipeline to describe the update. This approach allows you to... | [
1
] | [] | [] | [
"fastapi",
"mongodb",
"nosql",
"python"
] | stackoverflow_0074114320_fastapi_mongodb_nosql_python.txt |
Q:
Stuck with a MySQLdb SSL connection error in Python2.7
I have to maintain an old website built using Python2.7 that needs to continue working until we've finished creating a completely new version with more modern tools. Now this old website needs access to a remote MySQL database (connection is set up and working... | Stuck with a MySQLdb SSL connection error in Python2.7 | I have to maintain an old website built using Python2.7 that needs to continue working until we've finished creating a completely new version with more modern tools. Now this old website needs access to a remote MySQL database (connection is set up and working correctly), which so far has worked using the following:
im... | [
"Locate and add the line skip_ssl in /etc/mysql/my.cnf ( have tried this on MySQL 8.0.29 , Ubuntu 18)\nThis was the only thing that worked for me.\n[mysqld]\nskip_ssl\n"
] | [
0
] | [] | [] | [
"mysql_python",
"openssl",
"python",
"ubuntu"
] | stackoverflow_0072491528_mysql_python_openssl_python_ubuntu.txt |
Q:
Sending a timed messege on discord with python
How do I send a message on discord channel from python? I tried YouTube videos they aren't working also I want the messages to be timed like after every 1 minute the message should go
import requests
token = '(my_token)'
channel_id = '(my_channel_id)'
message = 'th... | Sending a timed messege on discord with python | How do I send a message on discord channel from python? I tried YouTube videos they aren't working also I want the messages to be timed like after every 1 minute the message should go
import requests
token = '(my_token)'
channel_id = '(my_channel_id)'
message = 'thanks'
def sendmessage(token, channel_id, message):... | [
"You have typo - it should be z in authorization.\n\nYour code works for me if I run discord in browser and copy my private token from browser\nbut it doesn't work with my bot token.\nFor bot it needs:\nheaders = {'Authorization': f'Bot {token}'}\n\nEventually it may need also User-Agent with bot's name (but I'm no... | [
0
] | [] | [] | [
"discord",
"message",
"python",
"timed"
] | stackoverflow_0074111865_discord_message_python_timed.txt |
Q:
Is there a way to store values of loop in a dataframe into another column in same dataframe?
Need to generate new column in df which have output stored corresponding to variables like this:
Output required
import pandas as pd
#create simple dataframe
x=1
y=2
data = {'var': ['print(x)', 'print(y)']}
df=pd.DataFrame... | Is there a way to store values of loop in a dataframe into another column in same dataframe? | Need to generate new column in df which have output stored corresponding to variables like this:
Output required
import pandas as pd
#create simple dataframe
x=1
y=2
data = {'var': ['print(x)', 'print(y)']}
df=pd.DataFrame(data)
#print values
n=0
while n<len(df['var']):
exec(df['var'].iloc[n])
n=n+1
| [
"I think there are better approaches you must to consider before. This kind of code is difficult to maintain and any thing can break it up easily.\n# factory decorator\ndef factory_1(**kwargs):\n def decorator(function):\n def wrapper(text_func):\n func = function\n result = func(tex... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074115087_python.txt |
Q:
Transforming Python Dataframe to combine column and row headers into new table
Is there a way to combine a column and a row to make a new column where a value will be stored? I have a dataframe below that I would like to format to achieve the output at the bottom. Any help would be appreciated. The following table... | Transforming Python Dataframe to combine column and row headers into new table | Is there a way to combine a column and a row to make a new column where a value will be stored? I have a dataframe below that I would like to format to achieve the output at the bottom. Any help would be appreciated. The following table is extracted using beautifulsoup, pandas and selenium. I'll use the sixth df as an ... | [
"Probably something like this (without the overheads of selenium) would be what you're after?\nimport requests\nimport pandas as pd\nfrom bs4 import BeautifulSoup as bs\n\n\npd.set_option('display.max_columns', None)\npd.set_option('display.max_colwidth', None)\n\nheaders = {\n'User-Agent': 'Mozilla/5.0 (X11; Linux... | [
0
] | [] | [] | [
"beautifulsoup",
"dataframe",
"pandas",
"python",
"selenium"
] | stackoverflow_0074116162_beautifulsoup_dataframe_pandas_python_selenium.txt |
Q:
How can I change a variable in a child class so that its dependent variables can also be changed?
Does anyone know if it is even possible to change the inherited variables of the parent class by changing a variable in a child class?
Without declaring them in the __init__ child?
class Foo(object):
def __init__(... | How can I change a variable in a child class so that its dependent variables can also be changed? | Does anyone know if it is even possible to change the inherited variables of the parent class by changing a variable in a child class?
Without declaring them in the __init__ child?
class Foo(object):
def __init__(self):
self.data = "abc"
self.data_2 = self.data
class Bar(Foo):
def __init__(self... | [
"this solves the issue if you don't want to accept data as an argument to your init func as someone pointed out above\nclass Foo(object):\n def __init__(self):\n self.data = \"abc\"\n\n @property\n def data_2(self):\n return self.data\n\nclass Bar(Foo):\n def __init__(self):\n super... | [
0
] | [] | [] | [
"class",
"oop",
"python",
"python_3.x"
] | stackoverflow_0074116505_class_oop_python_python_3.x.txt |
Q:
Tensorflow Attribute Error: 'method' object has no attribute '_from_serialized'
I'm trying to train a model in Tensorflow and get the error:
Attribute Error: 'method' object has no attribute '_from_serialized'
This is code that I have copied and seen work.
It seems that it has something to do with the compatibilit... | Tensorflow Attribute Error: 'method' object has no attribute '_from_serialized' | I'm trying to train a model in Tensorflow and get the error:
Attribute Error: 'method' object has no attribute '_from_serialized'
This is code that I have copied and seen work.
It seems that it has something to do with the compatibility of my tensorflow version and python version. I'm able to run other models, but this... | [
"The attribute error here is raised because you can't set any attribute on a method object i.e;\nclass Foo:\n def bar(self):\n print(\"bar\")\n\n\nif __name__ == \"__main__\":\n Foo().bar.baz = 1\n\nOutput:\nTraceback (most recent call last): line 7, in <module>\n Foo().bar.baz = 1\nAttributeError: ... | [
2,
1
] | [] | [] | [
"python",
"tensorflow"
] | stackoverflow_0073981914_python_tensorflow.txt |
Q:
fastapi mongodb how to add pagination and limit number of items per page?
I am using pymongo. Category.city_collection.find() getting all collection of result. But I want to show only 5 result per page. I tried this Category.city_collection.find().limit(5) which showing 5 result on first page but how to go others ... | fastapi mongodb how to add pagination and limit number of items per page? | I am using pymongo. Category.city_collection.find() getting all collection of result. But I want to show only 5 result per page. I tried this Category.city_collection.find().limit(5) which showing 5 result on first page but how to go others page like second page, third page etc? I am using mongo db with my fastapi proj... | [
"You need to use skip and limit\nWith skip, you set the number of documents that you will skip.\nWith limit, you set the page size.\nExample:\ndb.test.find({}).skip(10).limit(10)\n\nWould return the 2nd page in 10 document page sizes.\nA skip(20).limit(10), would return the 3rd page...\nMost of the times you should... | [
1
] | [] | [] | [
"fastapi",
"mongodb",
"pymongo",
"python",
"python_3.x"
] | stackoverflow_0074114016_fastapi_mongodb_pymongo_python_python_3.x.txt |
Q:
what's wrong with this decorator
this is my decorator function, it should only check validation like email is valid, and password length is above 8 but I can't understand what is wrong
def my_decorator(func):
def wrapper_function(*args, **kwargs):
user_email = kwargs.get("email", '')
use... | what's wrong with this decorator | this is my decorator function, it should only check validation like email is valid, and password length is above 8 but I can't understand what is wrong
def my_decorator(func):
def wrapper_function(*args, **kwargs):
user_email = kwargs.get("email", '')
user_password = kwargs.get("password", ""... | [
"In your decorator you expect to receive email and password in **kwargs. However, only named (aka keyword) arguments are stored inside **kwargs while positional arguments are contained inside *args.\nWhen you call your login function you pass the arguments in a positional maner, so the arguments are positional. If ... | [
2
] | [] | [] | [
"decorator",
"function",
"python"
] | stackoverflow_0074116792_decorator_function_python.txt |
Q:
How to skip the "\n" in the output while using the readlines() method?
I want to read a notepad file by using the readlines() method.
f = open('/home/user/Desktop/my_file', 'r')
print(f.readlines())
The output is:
['Hello!\n', 'Welcome to Barbara restaurant. \n', 'Here is the menu. \n']
As you see the newlines wi... | How to skip the "\n" in the output while using the readlines() method? | I want to read a notepad file by using the readlines() method.
f = open('/home/user/Desktop/my_file', 'r')
print(f.readlines())
The output is:
['Hello!\n', 'Welcome to Barbara restaurant. \n', 'Here is the menu. \n']
As you see the newlines will be mentioned in the output, too. What should I do? Note that I want to us... | [
"Update (Since you need the readlines() method)\nf = open('/home/user/Desktop/my_file', 'r')\nfor line in f.readlines():\n print(line, end='')\n\nOutput\nHello!\nWelcome to Barbara restaurant.\nHere is the menu.\n\n\nOriginal\nYou can read then split each line\nf = open('/home/user/Desktop/my_file', 'r')\nprint(... | [
1,
0
] | [] | [] | [
"file",
"linux",
"python",
"readlines"
] | stackoverflow_0074116711_file_linux_python_readlines.txt |
Q:
Dataframe compare, combine and merge for rectangular meshgrid
I have two dataframes shown below:
df_1 =
Lon Lat N
0 2 1 1
1 2 2 3
2 2 3 1
3 3 2 2
and
df_2 =
Lon Lat N
0 1.0 1.0 NaN
1 2.0 1.0 NaN
2 3.0 1.0 NaN
3 4.0 1.0 NaN
4 1.0 2.0 NaN
5 2.0 2.0 NaN
6 3.0 2.0 NaN
7 ... | Dataframe compare, combine and merge for rectangular meshgrid | I have two dataframes shown below:
df_1 =
Lon Lat N
0 2 1 1
1 2 2 3
2 2 3 1
3 3 2 2
and
df_2 =
Lon Lat N
0 1.0 1.0 NaN
1 2.0 1.0 NaN
2 3.0 1.0 NaN
3 4.0 1.0 NaN
4 1.0 2.0 NaN
5 2.0 2.0 NaN
6 3.0 2.0 NaN
7 4.0 2.0 NaN
8 1.0 3.0 NaN
9 2.0 3.0 NaN
10 3.0 3.0 NaN
11 4.... | [
"If you first create the df_2 with all needed values you can update it with the second DataFrame by using pandas.DataFrame.update.\nFor this you need to first set the the correct index by using pandas.DataFrame.set_index.\nHave a look at this Post for more information.\n",
"df_2.drop(columns = 'N').merge(df_1, on... | [
1,
1
] | [] | [] | [
"contourf",
"dataframe",
"nan",
"pandas",
"python"
] | stackoverflow_0074114855_contourf_dataframe_nan_pandas_python.txt |
Q:
python command line arguments, how to pass argument as value for script
I am having a hard time passing the arguments as value for my script in python. Here's my code:
import request, json, sys
def main():
url = 'https://jsonplaceholder.typicode.com/posts'
r = requests.get(url)
data = json.loads(r.tex... | python command line arguments, how to pass argument as value for script | I am having a hard time passing the arguments as value for my script in python. Here's my code:
import request, json, sys
def main():
url = 'https://jsonplaceholder.typicode.com/posts'
r = requests.get(url)
data = json.loads(r.text)
if len(sys.argv) != 3:
print("Usage must equal [userId] [pos... | [
"The problem is that command line arguments are strings and the data you seek are integers. You could convert arg[1] and arg[2] to integers or you could use the argparse module to build a more comprehensive command line parser.\nimport requests, json, sys, argparse\n\ndef main():\n parser = argparse.ArgumentPars... | [
1
] | [] | [] | [
"arguments",
"command_line_interface",
"python"
] | stackoverflow_0074116346_arguments_command_line_interface_python.txt |
Q:
How to read json file which has double quotes using python?
I have been trying to parse a JSON string that has double quotes, but always get the error.
I have looked at many StackOverflow links to solve the issue, but none of them worked.
How to read the json file (not string) which has double quotes and backslash... | How to read json file which has double quotes using python? | I have been trying to parse a JSON string that has double quotes, but always get the error.
I have looked at many StackOverflow links to solve the issue, but none of them worked.
How to read the json file (not string) which has double quotes and backslashes?
import json
#===== ignore this part, this is just file I wan... | [
"You're also missing a closing bracket ] on snippet's value. However, if you fix that, you can just make it a raw string by leading with an r\nimport json\n\njson_str = r\"\"\"\n{\"name\" : \"Help\",\n \"snippet\" : [\n \"cd \\\"C:\\\\Downloads\\\" \"]\n\n}\n\"\"\"\n\ndata = json.loads(json_st... | [
1
] | [] | [] | [
"json",
"python"
] | stackoverflow_0074116868_json_python.txt |
Q:
Formating a new table using python. Punch in and Punch out employee data
I have a list of employee punch date:
that needs to be formatted into a different table LIKE:
each new row has to be a new date. I have gotten started with variables, however I am failing at iterating through the columns to get the IN and O... | Formating a new table using python. Punch in and Punch out employee data | I have a list of employee punch date:
that needs to be formatted into a different table LIKE:
each new row has to be a new date. I have gotten started with variables, however I am failing at iterating through the columns to get the IN and OUT times. A little guidance would be appreciate for a beginner.
Code:
impo... | [
"method 01\n\nmerge, join, concatenate\n\nimport pandas as pd\n\ndata = [\n['MCDONALD', 123987, 'IN', '4/1/22', '3:56:00 AM'],\n['MCDONALD', 123987, 'OUT', '4/1/22', '##########'],\n['MCDONALD', 123987, 'IN', '4/1/22', '3:54:00 PM'],\n['MCDONALD', 123987, 'OUT', '4/1/22', '8:02:00 PM'],\n[... | [
0
] | [] | [] | [
"data_analysis",
"dataframe",
"excel",
"pandas",
"python"
] | stackoverflow_0074116769_data_analysis_dataframe_excel_pandas_python.txt |
Q:
Filtering the columns (not rows) of a DataFrame based on vertical (not horizontal) average or sum in PySpark or Pandas
data = [[12, 112, 14],
[120, 112, 114],
[88, 92, 74],
[17, 118, 133],
[19, 19, 14],
[11, 12, 14]]
columns = ['Subject_1', 'Subject_2', 'Subject_3']
datafram... | Filtering the columns (not rows) of a DataFrame based on vertical (not horizontal) average or sum in PySpark or Pandas | data = [[12, 112, 14],
[120, 112, 114],
[88, 92, 74],
[17, 118, 133],
[19, 19, 14],
[11, 12, 14]]
columns = ['Subject_1', 'Subject_2', 'Subject_3']
dataframe = spark.createDataFrame(data, columns)
dataframe.show()
# +---------+---------+---------+
# |Subject_1|Subject_2|Subject_3... | [
"Using this dataframe...\nfrom pyspark.sql import functions as F\ndata = [[12, 112, 14, 15, 100],\n [120, 112, 114, 17, 87],\n [88, 92, 74, 76, 11],\n [17, 118, 133, 99, 51],\n [19, 19, 14, 54, 48],\n [11, 12, 14, 75, 60]]\ncolumns = ['Subject_1', 'Subject_2', 'Subject_3', 'Subjec... | [
1
] | [] | [] | [
"apache_spark",
"average",
"pandas",
"pyspark",
"python"
] | stackoverflow_0074116102_apache_spark_average_pandas_pyspark_python.txt |
Q:
Getting python clicks from host to register in Virtual Machine
Im working on some scripts that I need to run on top of a VM. I'm using VMWare Workstation 15 Pro. The test script I ran to see if this would work is:
def main():
time.sleep(5)
pydirectinput.click()
The clicks on the virtual machine don't re... | Getting python clicks from host to register in Virtual Machine | Im working on some scripts that I need to run on top of a VM. I'm using VMWare Workstation 15 Pro. The test script I ran to see if this would work is:
def main():
time.sleep(5)
pydirectinput.click()
The clicks on the virtual machine don't register while the clicks on the host system do. Is there a way to ge... | [
"This may be impossible to achieve as even the people in the VMWare community have no advice.\nA virtual machine normally communicates to the mouse on a lower level than normal programs. You see this for example if you don't install the VMWare Tools in the guest system. If you want to work with such a virtual machi... | [
2
] | [] | [] | [
"python",
"python_3.x",
"virtual_machine",
"vmware",
"vmware_workstation"
] | stackoverflow_0074070605_python_python_3.x_virtual_machine_vmware_vmware_workstation.txt |
Q:
Python: Christmas Tree with user input for the base
I'm trying to get a christmas tree, where the user can input the number of stars, which should be in the last row. The problem is, I don't get, how to get the height from the number of stars in the last row.
So far, I got the tree with an input from the user for ... | Python: Christmas Tree with user input for the base | I'm trying to get a christmas tree, where the user can input the number of stars, which should be in the last row. The problem is, I don't get, how to get the height from the number of stars in the last row.
So far, I got the tree with an input from the user for how high the tree should get.
eingabe = input("Bitte gebe... | [
"The number of stars in the last row is:\nstars = rows * 2 - 1\n\nTherefore, the height of the tree, knowing the number of stars in the last row, is:\nrows = (stars + 1) / 2\n\ngiven that the number of stars must be odd because of the way you're drawing it.\n"
] | [
0
] | [] | [] | [
"for_loop",
"python"
] | stackoverflow_0074116731_for_loop_python.txt |
Q:
How to add string in front of every character?
I tried this but I can't.
I want to add "pp" string in front of every character of input.
x=str(input("give me the characters"))
print("pp"+x[0]+"pp"+x[1]+"sa"+x[3])
A:
You can use str.join to add pp. For example:
x = input("give me the characters: ")
print("pp".joi... | How to add string in front of every character? | I tried this but I can't.
I want to add "pp" string in front of every character of input.
x=str(input("give me the characters"))
print("pp"+x[0]+"pp"+x[1]+"sa"+x[3])
| [
"You can use str.join to add pp. For example:\nx = input(\"give me the characters: \")\nprint(\"pp\".join([\"\", *x]))\n\nPrints:\ngive me the characters: abcd\nppappbppcppd\n\n"
] | [
0
] | [] | [] | [
"indexing",
"out",
"python",
"range",
"string"
] | stackoverflow_0074116361_indexing_out_python_range_string.txt |
Q:
How to add an empty Worksheet into an existing Workbook using Pandas ExcelWriter
I am trying to add an empty excel sheet into an existing Excel File using python xlsxwriter.
Setting the formula up as follows works well.
workbook = xlsxwriter.Workbook(file_name)
worksheet_cover = workbook.add_worksheet("Cover")
Out... | How to add an empty Worksheet into an existing Workbook using Pandas ExcelWriter | I am trying to add an empty excel sheet into an existing Excel File using python xlsxwriter.
Setting the formula up as follows works well.
workbook = xlsxwriter.Workbook(file_name)
worksheet_cover = workbook.add_worksheet("Cover")
Output4 = workbook
Output4.close()
But once I try to add further sheets with dataframes ... | [
"You could use pandas.ExcelWriter with optional mode='a' argument for appending to existing Excel workbook. \n\nYou can also append to an existing Excel file:\n\n>>> with ExcelWriter('path_to_file.xlsx', mode='a') as writer:`\n... df.to_excel(writer, sheet_name='Sheet3')`\n\nHowever unfortunately, this requires... | [
0,
0,
0
] | [] | [] | [
"excel",
"pandas",
"python",
"xlsxwriter"
] | stackoverflow_0056497804_excel_pandas_python_xlsxwriter.txt |
Q:
How to count reviews for a product in django?
I am building an ecommerce website with django. In my models I have a Product and review model. How should i connect the two for the number of reviews and average rating attribute?
This is my current models file
class Product(models.Model):
name = models.CharField(... | How to count reviews for a product in django? | I am building an ecommerce website with django. In my models I have a Product and review model. How should i connect the two for the number of reviews and average rating attribute?
This is my current models file
class Product(models.Model):
name = models.CharField(max_length=200, null=True, blank=True)
brand = ... | [
"I would make them into model methods.. I don't think there will be any issues that the Review object is defined below the method\nand for the Avg I used a Django command aggregate which forces the DB to do the work.\nmodels.py\nclass Product(models.Model):\n name = models.CharField(max_length=200, null=True, bl... | [
1
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0074116689_django_django_models_python.txt |
Q:
How to extract a single value from a nested Dictionary?
I have the following nested dictionary my_dict (which was originally JSON from a response to a request to an endpoint):
my_dict = {'SalesStatusResult': {'next_offset': -1,
'customers': [{'caCustomerID': 'N872-1665582527-adhoc-0:0',
'identifier': 'N872',... | How to extract a single value from a nested Dictionary? | I have the following nested dictionary my_dict (which was originally JSON from a response to a request to an endpoint):
my_dict = {'SalesStatusResult': {'next_offset': -1,
'customers': [{'caCustomerID': 'N872-1665582527-adhoc-0:0',
'identifier': 'N872',
'customertype': '',
'blocked': False,
'location'... | [
"Here is a hint: starting from where you want and go upward: caCustomerID -> customers (this is a list) -> SalesStatusResult (this is a dictionary). After that, writing code which traverse back down:\nfor record in my_dict[\"SalesStatusResult\"][\"customers\"]:\n print(record[\"caCustomerID\"])\n print(record... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074116902_python.txt |
Q:
Getting flake8 most critical errors on big python codebase
Given a large Python 3.6 codebase deployed in GitLab with lots of "minor" violations with flake8 (e.g. stylistic violations), I would like to first find the most serious violations (e.g. variable may be undefined, name not found...). The idea is to avoid b... | Getting flake8 most critical errors on big python codebase | Given a large Python 3.6 codebase deployed in GitLab with lots of "minor" violations with flake8 (e.g. stylistic violations), I would like to first find the most serious violations (e.g. variable may be undefined, name not found...). The idea is to avoid being overwhelmed with thousands of violations reported as this t... | [
"After researching, it seems there is no classification by seriousness of errors that comes out of the box in flake8, although other tools may have it. The solution I chose is simply to phase in static code analysis by explicitly listing flake8 violations that would be good \"first candidates\" (I chose F631,F704,F... | [
0
] | [] | [] | [
"cicd",
"flake8",
"gitlab",
"python"
] | stackoverflow_0071120337_cicd_flake8_gitlab_python.txt |
Q:
In Scrapy Why getting this Error not match the date format I Even read its documentation and I hope I am doing code same to the documentation
In Scrapy Why getting this Error not match the date format I Even read its documentation and I hope I am doing code same to the documentation
Published_Date = response.css('... | In Scrapy Why getting this Error not match the date format I Even read its documentation and I hope I am doing code same to the documentation | In Scrapy Why getting this Error not match the date format I Even read its documentation and I hope I am doing code same to the documentation
Published_Date = response.css('span[class="published-date-day"] ::text').get().strip().replace(",","").replace(".","")#Sept. 23, 2022
Published_Date = datetime.strptime(Pu... | [
"Why don't you do:\npublished_date = response.xpath('//time[@class=\"published-date\"]/@datetime').get().split('T')[0]\n\nThis way you obtain the date in ISO format.\n"
] | [
2
] | [] | [] | [
"datetime",
"python",
"scrapy",
"web_scraping",
"xpath"
] | stackoverflow_0074116913_datetime_python_scrapy_web_scraping_xpath.txt |
Q:
Sorting list of strings that contain number with Python
I have list of strings that look like this:
l = ["sometext-2022-21_sometext",
"sometext-2022-4_sometext",
"sometext-2022-121_sometext",
"sometext-2022-321_sometext",
"sometext-2022-1_sometext",
"sometext-2022-31_sometext"]
I want to sort it so that bigges... | Sorting list of strings that contain number with Python | I have list of strings that look like this:
l = ["sometext-2022-21_sometext",
"sometext-2022-4_sometext",
"sometext-2022-121_sometext",
"sometext-2022-321_sometext",
"sometext-2022-1_sometext",
"sometext-2022-31_sometext"]
I want to sort it so that biggest number be on top, for example:
l = ["sometext-2022-321_some... | [
"You may be able to use a regular expression as long as the pattern searched is not also contained in \"sometext\", resulting in false positives. list.sort takes a function that returns a key to use for sorting instead of of the original value in the list. In this case, we can convert string digits to a tuple of in... | [
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0074116904_python.txt |
Q:
Convert string to negative number
I need to convert from string type to a number
list = ["-5","4","-3","variable"] # Input
list = [-5,4,-3,"variable"] # epected output
I have a problem when converting the negative number
list[0]=int(list[0])
ValueError: invalid literal for int() with base 10: '-5'
A:
... | Convert string to negative number | I need to convert from string type to a number
list = ["-5","4","-3","variable"] # Input
list = [-5,4,-3,"variable"] # epected output
I have a problem when converting the negative number
list[0]=int(list[0])
ValueError: invalid literal for int() with base 10: '-5'
| [
"Actually, I cannot reproduce your error , it just work in python 2.7.13\n>>>int(\"-5\")\n>>> -5\n\nand in python 3.4\nso, it could be a python version problem , \nI recommend updating your python version , by reinstalling the newer , from the site , it will replace it perfectly ( packages untouched ) , unless you ... | [
10,
7,
0,
0,
0,
0
] | [] | [] | [
"python",
"python_2.7"
] | stackoverflow_0042102468_python_python_2.7.txt |
Q:
Flask hangs when run as a subprocess alongside pytest
I've spent the last hour and a half trying and failing to debug this test and I am utterly stumped. To simplify the process of testing the Flask server I am building, I have made a relatively simple script which starts the server, then runs pytest, kills the se... | Flask hangs when run as a subprocess alongside pytest | I've spent the last hour and a half trying and failing to debug this test and I am utterly stumped. To simplify the process of testing the Flask server I am building, I have made a relatively simple script which starts the server, then runs pytest, kills the server, writes the outputs to files, and exits with Pytest's ... | [
"It turns out that my server output was filling up all the buffer space in the pipe, meaning that it would wait for the buffer to empty. The issue is that my test script was waiting for the tests to exit, and the tests could not progress unless the server was active. As such, the code reached a three-way deadlock. ... | [
0
] | [] | [] | [
"flask",
"pytest",
"python",
"python_requests",
"subprocess"
] | stackoverflow_0074114409_flask_pytest_python_python_requests_subprocess.txt |
Q:
QQ-Plot in Python using Plotnine
I want to plot an array of values against a theoretical distribution using a QQ-Plot in Python. Ideally, I want to create the plot using the library Plotnine.
But when I try to create the plot, I'm getting error messages... here's my code with example data:
from scipy.stats import ... | QQ-Plot in Python using Plotnine | I want to plot an array of values against a theoretical distribution using a QQ-Plot in Python. Ideally, I want to create the plot using the library Plotnine.
But when I try to create the plot, I'm getting error messages... here's my code with example data:
from scipy.stats import beta
from plotnine import *
import sta... | [
"This is a bug in plotnine, until it is fixed you can try to pass the arguments as a tuple instead of a dict. However, be careful about the positional matching of the arguments (a, b, loc, scale).\nEdit\nThe bug is fixed in the current development version of plotnine and you can use a dict to pass the arguments.\n"... | [
1
] | [] | [] | [
"plotnine",
"python"
] | stackoverflow_0070798622_plotnine_python.txt |
Q:
Unable to use quit() to end execution in Google Colab or Jupyter Notebook
When run in Google Collaboratory of the following code should be just 1, but both 1 and 2 are printed:
print(1)
quit()
print(2)
Here is a screenshot from Google Colab. The same result holds on my local Jupiter notebook.
I searched online s... | Unable to use quit() to end execution in Google Colab or Jupyter Notebook | When run in Google Collaboratory of the following code should be just 1, but both 1 and 2 are printed:
print(1)
quit()
print(2)
Here is a screenshot from Google Colab. The same result holds on my local Jupiter notebook.
I searched online some examples about quit() and exit() using for loop. I ran their codes and it t... | [] | [] | [
"You can try to use -\nPython exit commands: exit(), sys.exit() and os._exit()\n"
] | [
-4
] | [
"google_colaboratory",
"jupyter_notebook",
"python"
] | stackoverflow_0074117086_google_colaboratory_jupyter_notebook_python.txt |
Q:
Creating folders in a directory using variables (os.path)
I'm feeding my code lines from a txt file and using that to determine folder names.
import os
folderdir = r'C:\Users\myname\Documents\Folders'
txtfile = r'C:\Users\myname\Documents\foldernames.txt'
with open(txtfile) as f:
for line in f.readlines():
... | Creating folders in a directory using variables (os.path) | I'm feeding my code lines from a txt file and using that to determine folder names.
import os
folderdir = r'C:\Users\myname\Documents\Folders'
txtfile = r'C:\Users\myname\Documents\foldernames.txt'
with open(txtfile) as f:
for line in f.readlines():
folderpath = folderdir + "\\" + line
print(fold... | [
"See the resulting path in the error-message Albert#2000555\\n. It has a newline character \\n at the end. This makes the path invalid to use.\nAs commented by jasonharper:\n\nuse repr(str) to print the actual representation\nuse str.strip() to remove the newline at the end of the read lines:\n\nimport os\n\nfolder... | [
0
] | [] | [] | [
"os.path",
"python",
"txt"
] | stackoverflow_0074117068_os.path_python_txt.txt |
Q:
How to inject mock objects into instance attributes in Python unit testing
I am learning python
I'm wondering if there is a mechanism to "inject" an object (a fake object in my case) into the class under test without explicitly adding it in the costructor/setter.
## source file
class MyBusinessClass():
def __... | How to inject mock objects into instance attributes in Python unit testing | I am learning python
I'm wondering if there is a mechanism to "inject" an object (a fake object in my case) into the class under test without explicitly adding it in the costructor/setter.
## source file
class MyBusinessClass():
def __init__(self):
self.__engine = RepperEngine()
def doSomething(self):... | [
"IOC is not needed in Python. Here's a Pythonic approach.\nclass MyBusinessClass(object):\n def __init__(self, engine=None):\n self._engine = engine or RepperEngine() \n # Note: _engine doesn't exist until constructor is called.\n\n def doSomething(self):\n ## bla bla ...\n success... | [
7,
2,
0
] | [
"Your question seems somewhat unclear, but there is nothing preventing you from using class inheritance to override the original methods. In that case the derivative class would just look like this:\nclass MyBusinessClassFake(MyBusinessClass):\n def __init__(self):\n pass\n\n"
] | [
-1
] | [
"mocking",
"python",
"python_unittest"
] | stackoverflow_0042397189_mocking_python_python_unittest.txt |
Q:
Python Requests Ignores Path Portion of Filename When Uploading Files
I am trying to use Python Requests and boto3 to upload JSON files using a pre-signed POST url. But requests ignores the path portion of the key.
Here is a minimal, working example:
import boto3, requests, json, tempfile
s3_client = boto3.clien... | Python Requests Ignores Path Portion of Filename When Uploading Files | I am trying to use Python Requests and boto3 to upload JSON files using a pre-signed POST url. But requests ignores the path portion of the key.
Here is a minimal, working example:
import boto3, requests, json, tempfile
s3_client = boto3.client('s3')
bucket_name = "some_bucket"
response = s3_client.generate_presigned... | [
"I figured this out! generate_presigned_post() returns an object with two dictionaries, url and fields, the latter which contains a key called key which can be set to this/path/is/ignored/buthisworks.json\nSending that request with the modified key field works!\n"
] | [
0
] | [] | [] | [
"amazon_s3",
"boto3",
"python",
"python_requests"
] | stackoverflow_0074113450_amazon_s3_boto3_python_python_requests.txt |
Q:
Invalid entry 0 in condlist: should be boolean ndarray using np.select
I have a piece of code which meant to create year_week out of datetimes. My startdate is different from the normal year start and I am trying to add LY, NY, +LY prefixes if the year is below or above my year, which starts at 2021-06-24 and ends... | Invalid entry 0 in condlist: should be boolean ndarray using np.select | I have a piece of code which meant to create year_week out of datetimes. My startdate is different from the normal year start and I am trying to add LY, NY, +LY prefixes if the year is below or above my year, which starts at 2021-06-24 and ends in 2022-06-04 denoting LY = last year and NY = next year.
This is a follow-... | [
"np.select() expects an ndarray of type bool. When using .eq() you will return a Series that is type boolean instead of bool. All you have to do to fix the issue is to cast it to the correct type with .astype(bool).\nNote that even if you are using eq as part of a larger logical expression, the result will have the... | [
0
] | [] | [] | [
"date",
"numpy",
"python"
] | stackoverflow_0068618078_date_numpy_python.txt |
Q:
How to run FastAPI and connect to a MySQL database using a Docker compose file?
I am trying to deploy a FastAPI application on a VPS running Linux CentOS 7 by using Docker and Docker compose, but I am running into issues connecting to a database I have stored on the server. Either the database instance won't conne... | How to run FastAPI and connect to a MySQL database using a Docker compose file? | I am trying to deploy a FastAPI application on a VPS running Linux CentOS 7 by using Docker and Docker compose, but I am running into issues connecting to a database I have stored on the server. Either the database instance won't connect or the FastAPI workers can't attach themselves to a port.
I am using FastAPI to ru... | [
"It's a little bit hard to tell from your description, but it sounds like the problem is probably with your database. You've said you're running the database on a remote VPS; if that's the case, your database hostname would be the address of that VPS.\nI've attempted to reproduce things here.\nFirst, I have a datab... | [
1
] | [] | [] | [
"docker",
"docker_compose",
"fastapi",
"python"
] | stackoverflow_0074114540_docker_docker_compose_fastapi_python.txt |
Q:
Write array of dictionaries to csv in Python 3?
I have been wrestling with this for a day or two now, and I can't seem to get it right.
project_index = [
{A: ['1', '2', '3']},
{B: ['4', '5', '6']},
{C: ['7', '8', '9']},
{D: ['10', '11', '12']},
{E: ['13', '14', '15']},
{F: ['16', '17', '18']}
]
I have tried so ma... | Write array of dictionaries to csv in Python 3? | I have been wrestling with this for a day or two now, and I can't seem to get it right.
project_index = [
{A: ['1', '2', '3']},
{B: ['4', '5', '6']},
{C: ['7', '8', '9']},
{D: ['10', '11', '12']},
{E: ['13', '14', '15']},
{F: ['16', '17', '18']}
]
I have tried so many different things to try to get this into a .CSV ta... | [
"Assuming all your keys are unique... then this (Modified Slightly):\nproject_index = [\n{'A': ['1', '2', '3']},\n{'B': ['4', '5', '6']},\n{'C': ['7', '8', '9']},\n{'D': ['10', '11', '12', '20']},\n{'E': ['13', '14', '15']},\n{'F': ['16', '17', '18']}\n]\n\nShould probably look like this:\nproject_index_dict = {}\n... | [
2,
1
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0074116077_csv_python.txt |
Q:
Why can't I change values in the list this way?
I am trying to change the value of the elements in the list so that every single element is increased by 2 however this code does not work:
v = [-1, 1, 10]
for e in v:
e = e + 2
but this one does:
v = [-1, 1, 10]
for i in range(len(v)):
v[i] = v[i] + 2
can ... | Why can't I change values in the list this way? | I am trying to change the value of the elements in the list so that every single element is increased by 2 however this code does not work:
v = [-1, 1, 10]
for e in v:
e = e + 2
but this one does:
v = [-1, 1, 10]
for i in range(len(v)):
v[i] = v[i] + 2
can someone please explain why?
| [
"In the first example, e takes on the value of each element in the list in a temporary variable. The values of each v[i] are copied to e, so e = e + 2 is only changing that variable.\nIn the second example v[i] = v[i] + 2 is directly changing the elements in the list without using another variable.\n"
] | [
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074117179_list_python.txt |
Q:
combining array and list elemint by index
I have an array (which comes from a kdtree):
array = [[a b c d e]
[a b c d e]
[a b c d e]]
and a list :
lst = [1, 2, 3, 4, 5]
I want to do some list comprehension (using array and lst) that makes it look like this:
desired_result = [[a, b, c, d, e, 1... | combining array and list elemint by index | I have an array (which comes from a kdtree):
array = [[a b c d e]
[a b c d e]
[a b c d e]]
and a list :
lst = [1, 2, 3, 4, 5]
I want to do some list comprehension (using array and lst) that makes it look like this:
desired_result = [[a, b, c, d, e, 1]
[a, b, c, d, e, 2]
... | [
"If you want a list comprehension:\nresult = [l+[x] for l,x in zip(array, lst)]\n\n",
"An alternative way to list comprehension if array is of the type numpy.ndarray:\nresult = numpy.c_[array, lst]\n\nPlease check this answer for more details.\n"
] | [
1,
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074117010_numpy_python.txt |
Q:
Telegram bot to send auto message every n hours with python-telegram-bot
I am quite new in building bots so I created a very simple Telegram bot and it works great but can't figure out how to make the bot send messages every n minutes or n hours when /start_auto command is initiated.
I made a workaround with whil... | Telegram bot to send auto message every n hours with python-telegram-bot | I am quite new in building bots so I created a very simple Telegram bot and it works great but can't figure out how to make the bot send messages every n minutes or n hours when /start_auto command is initiated.
I made a workaround with while loop but it looks stupid and during the loop users won't be able to interact... | [
"python-telegram-bot has a built-in feature for scheduling tasks, called JobQueue. Please have a look at this wiki page for more info.\n\nDisclaimer: I'm currently the maintainer of python-telegram-bot.\n",
"will post a solution which I found:\ndef callback_auto_message(context):\n context.bot.send_message(cha... | [
2,
1,
0
] | [
"Why don't you use pyrogram. It has made everything easier.\nfrom pyrogram import Client, filters \nimport time\n\napp = Client('my_account', #Update this line with\n api_id=API_ID, #your API_ID\n api_hash=API_HASH, #your API_HASH\n bot_token=BOT_TOKEN) #yo... | [
-2
] | [
"python",
"python_telegram_bot",
"scheduled_tasks",
"telegram",
"telegram_bot"
] | stackoverflow_0072156750_python_python_telegram_bot_scheduled_tasks_telegram_telegram_bot.txt |
Q:
Keras loss value significant jump
I am working on a simple neural network in Keras with Tensorflow. There is a significant jump in loss value from the last mini-batch of epoch L-1 to the first mini-batch of epoch L.
I am aware that the loss should decrease with an increase in the number of iterations but a signif... | Keras loss value significant jump | I am working on a simple neural network in Keras with Tensorflow. There is a significant jump in loss value from the last mini-batch of epoch L-1 to the first mini-batch of epoch L.
I am aware that the loss should decrease with an increase in the number of iterations but a significant jump in loss after each epoch doe... | [
"Keras in fact shows the moving average instead of the \"raw\" loss values. The moving average array is reset after each epoch that's why we can see a huge jump after each epoch. In order to acquire the raw loss values, one should implement a callback as shown below:\nclass LossHistory(keras.callbacks.Callback):\n ... | [
0,
0
] | [] | [] | [
"deep_learning",
"keras",
"neural_network",
"python",
"tensorflow"
] | stackoverflow_0072119572_deep_learning_keras_neural_network_python_tensorflow.txt |
Q:
Split time series with multiple records per day
I have a dataset of daily transactions where there are multiple records per day. I need to split it into different cross validation folds to train a ML model, however I can't user TimeSeriesSplit from sklearn as there are multiple transactions per day. Do you know ho... | Split time series with multiple records per day | I have a dataset of daily transactions where there are multiple records per day. I need to split it into different cross validation folds to train a ML model, however I can't user TimeSeriesSplit from sklearn as there are multiple transactions per day. Do you know how can I do this in python?
| [
"Input data:\nimport numpy as np\nimport pandas as pd\ndata = np.array(\n [['DAY_1','afds',5],\n ['DAY_1','rtws', 4],\n ['DAY_1','gtssd', 2],\n ['DAY_2','ititl', 4],\n ['DAY_2','uius', 7],\n ['DAY_3','hyaah', 6],\n ['DAY_4','apsaj', 9]])\ndf = pd.DataFrame(data,columns=['DATEDAY','TRANSAC... | [
0
] | [] | [] | [
"cross_validation",
"machine_learning",
"python",
"scikit_learn",
"time_series"
] | stackoverflow_0074043308_cross_validation_machine_learning_python_scikit_learn_time_series.txt |
Q:
How do I check collision between a line and a rect in pygame?
I am currently creating a game in python with pygame and my AI is currently "seeing" my character through the walls and shoot at it, but the AI is not supposed to shoot. So my question is : how to prevent that ? I've thought about a line collision where... | How do I check collision between a line and a rect in pygame? | I am currently creating a game in python with pygame and my AI is currently "seeing" my character through the walls and shoot at it, but the AI is not supposed to shoot. So my question is : how to prevent that ? I've thought about a line collision where the line goes from my AI to my character, and if this line collide... | [
"This is a great question!\nYour rectangle can be thought of as 4 lines:\n(x, y) → (x+width, y) # top\n(x+width, y) → (x+width, y+height) # right\n(x, y+height) → (x+width, y+height) # bottom\n(x, y) → (x, y+height) # left \n\nTaking your intersecting line, it's possible to use the two-l... | [
3,
0,
0
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0056100547_pygame_python.txt |
Q:
Fail GitLab CI/CD Pipeline on added flake8 violations
Given a large, legacy Python codebase in GitLab, it is unreasonable to fail the CI/CD pipeline on flake8 violations, because solving problems in such an amount of legacy code would completely stall development. Is there instead a way to configure the "code qual... | Fail GitLab CI/CD Pipeline on added flake8 violations | Given a large, legacy Python codebase in GitLab, it is unreasonable to fail the CI/CD pipeline on flake8 violations, because solving problems in such an amount of legacy code would completely stall development. Is there instead a way to configure the "code quality" CI/CD pipeline for it to fail on added flake8 violatio... | [
"The more important is the number of violations in the new code.\nIf your flake8 report is like\nflake8 \n.\\main.py:4:1: E302 expected 2 blank lines, found 1\n.\\main.py:4:4: E271 multiple spaces after keyword\n.\\main.py:4:14: E203 whitespace before ':'\n.\\main.py:5:3: E111 indentation i... | [
0
] | [] | [] | [
"cicd",
"flake8",
"gitlab",
"python",
"static_analysis"
] | stackoverflow_0074117093_cicd_flake8_gitlab_python_static_analysis.txt |
Q:
how to assign key to each string in the list of strings using python
I have the below list for example consider:
my_list = ['1,ad,help,green','2,bc,quote,green','3,ef,mask,red','4,ad,help,green']
I need the output list to be like:
output = ['Rule:1,Key:ad,Message:help,Status:green','Rule:2,Key:bc,Message:quote,St... | how to assign key to each string in the list of strings using python | I have the below list for example consider:
my_list = ['1,ad,help,green','2,bc,quote,green','3,ef,mask,red','4,ad,help,green']
I need the output list to be like:
output = ['Rule:1,Key:ad,Message:help,Status:green','Rule:2,Key:bc,Message:quote,Status:green','Rule:3,Key:ef,Message:mask,Status:red','Rule:4,Key:ad,Message... | [
"\nI need the output list to be like:\n\nsolution\nThe idea is just to split each string and then format the output string accordingly.\noutput = [\"Rule:{},Key:{},Message:{},Status:{}\".format(*s.split(',')) for s in my_list]\n\ndemo\nmy_list = ['1,ad,help,green','2,bc,quote,green','3,ef,mask,red','4,ad,help,green... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074117318_python.txt |
Q:
write the python statement that would print out "abc","def",and. "ghi" in column format in python?
Input: ABCDEFGHIJKLIMNOQRSTUVWXYZ
This is my input. Now I want my output to print in this format:
Expected Output:
ABC
DEF
GHI
JKL
MNO
PQR
STU
VWX
YZ
A:
count = 0
for char in input_str:
count +=1
if count %... | write the python statement that would print out "abc","def",and. "ghi" in column format in python? | Input: ABCDEFGHIJKLIMNOQRSTUVWXYZ
This is my input. Now I want my output to print in this format:
Expected Output:
ABC
DEF
GHI
JKL
MNO
PQR
STU
VWX
YZ
| [
"count = 0\nfor char in input_str:\n count +=1\n if count % 3 == 0:\n print(char, end=' ')\n else:\n print(char, end='')\n\n"
] | [
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074117352_python_python_3.x.txt |
Q:
Write pandas dataframe into AWS athena database
I have run a query using pyathena, and have created a pandas dataframe. Is there a way to write the pandas dataframe to AWS athena database directly?
Like data.to_sql for MYSQL database.
Sharing a example of dataframe code below for reference need to write into AWS... | Write pandas dataframe into AWS athena database | I have run a query using pyathena, and have created a pandas dataframe. Is there a way to write the pandas dataframe to AWS athena database directly?
Like data.to_sql for MYSQL database.
Sharing a example of dataframe code below for reference need to write into AWS athena database:
data=pd.DataFrame({'id':[1,2,3,4,5,... | [
"Another modern (as for February 2020) way to achieve this goal is to use aws-data-wrangler library. It's authomating many routine (and sometimes annoying) tasks in data processing.\nCombining the case from the question the code would look like below:\nimport pandas as pd\nimport awswrangler as wr\n\ndata=pd.DataFr... | [
6,
3,
0,
0
] | [] | [] | [
"amazon_athena",
"database",
"pandas",
"python"
] | stackoverflow_0056286093_amazon_athena_database_pandas_python.txt |
Q:
How to create dynamic directory for downloads in Selenium Python?
I am creating a new directory for downloads in the setup class using the script:
import time
from os import getenv
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Opt... | How to create dynamic directory for downloads in Selenium Python? | I am creating a new directory for downloads in the setup class using the script:
import time
from os import getenv
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.wait import WebDriverWait
from sel... | [
"I found a fix. I created the base directory manually and that resolved the error\n"
] | [
0
] | [] | [] | [
"mkdir",
"python",
"selenium"
] | stackoverflow_0073732516_mkdir_python_selenium.txt |
Q:
XML Transform with Python
I have a XML file like this:
<recommendations>
<para>
<text>Text.</text>
</para>
<para>
<text>Text2.</text>
</para>
</recommendations>
I want to make a new recommendations tag with "Text" concatenate with "Text2" using python:
Text.Text2.
can someone help ... | XML Transform with Python | I have a XML file like this:
<recommendations>
<para>
<text>Text.</text>
</para>
<para>
<text>Text2.</text>
</para>
</recommendations>
I want to make a new recommendations tag with "Text" concatenate with "Text2" using python:
Text.Text2.
can someone help me?
I tried so far:
xml_parsed ... | [
"To solve this problem, I introduce a function get_text() which iterates through the root of the input and collect all texts. The rest would be easy:\nfrom xml.etree import ElementTree as ET\n\ndef get_text(r):\n buffer = \"\"\n for para in r:\n for text in para:\n buffer += text.text\n r... | [
2
] | [] | [] | [
"python",
"transform",
"xml"
] | stackoverflow_0074115662_python_transform_xml.txt |
Q:
why can't i use next() on range()
I am trying to get familiar with python generators.
I was playing with the range() function, which seems to return a range object, which my understanding is a generator.
since it's a generator, then I should be able to do
a = range(10)
print(next(a))
but I get:
TypeError: 'range'... | why can't i use next() on range() | I am trying to get familiar with python generators.
I was playing with the range() function, which seems to return a range object, which my understanding is a generator.
since it's a generator, then I should be able to do
a = range(10)
print(next(a))
but I get:
TypeError: 'range' object is not an iterator
why does it... | [] | [] | [
"Iterators and generators are different types of things (objects). There's a pretty good explanation here\n"
] | [
-2
] | [
"generator",
"iterator",
"python",
"python_3.x"
] | stackoverflow_0074117445_generator_iterator_python_python_3.x.txt |
Q:
How to select rows for each group whose value are within certain limits?
I have a data set like this:
dfdict = {
'year' : [2021, 2021, 2021, 2021, 2021, 2022, 2022, 2022, 2022, 2022],
'value' : [1,2,3,4,5,6,7,8,9,10]
}
df = pd.DataFrame(dfdict)
I also have a dictionary whose keys are years and values are ... | How to select rows for each group whose value are within certain limits? | I have a data set like this:
dfdict = {
'year' : [2021, 2021, 2021, 2021, 2021, 2022, 2022, 2022, 2022, 2022],
'value' : [1,2,3,4,5,6,7,8,9,10]
}
df = pd.DataFrame(dfdict)
I also have a dictionary whose keys are years and values are the limit values of each year I want to apply a condition:
limitdict = {
'... | [
"I suggest splitting the dataframe by year and then using between to filter out values in the range specified in the limitdict. Note that I am using the ~ symbol to filter out values within the range specified in the limitdic: df_year[~df_year.value.between(limitdict[str(year)][0],limitdict[str(year)][1])].\nlist_o... | [
1,
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074116677_pandas_python.txt |
Q:
Change unicode text emoji color using python with pandas style
Context: I'm trying to show this emoji as a triangle point up (like this one ), but in green.
Let's say we're trying to apply a formatting style to a table to display it as HTML as such:
arrays = [
["bar", "bar", "baz", "baz", "foo", "foo", "qux", ... | Change unicode text emoji color using python with pandas style | Context: I'm trying to show this emoji as a triangle point up (like this one ), but in green.
Let's say we're trying to apply a formatting style to a table to display it as HTML as such:
arrays = [
["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"],
["one", "two", "one", "two", "one", "two", "one", "two"]... | [
"You can try something like this (it will change the font color as well, however if anyone knows how to change the color of just the emoji feel free to post as well):\ndf.style\n .format(lambda x :\" {:.0%}\".format(x) if x > 0 else \" {:.0%}\".format(x) if \"{:.0%}\".format(x) == '0%' else \" {:.0%}\".format(x))\... | [
1
] | [] | [] | [
"css",
"dataframe",
"python"
] | stackoverflow_0074101686_css_dataframe_python.txt |
Q:
How do I get non-aggregated batch statistics with tf.keras.callbacks?
I am trying to train a model using the keras model.fit() method. This method returns a history object which contains loss values for each epoch - however I would like to have loss values for each individual batch.
Looking online I have found sug... | How do I get non-aggregated batch statistics with tf.keras.callbacks? | I am trying to train a model using the keras model.fit() method. This method returns a history object which contains loss values for each epoch - however I would like to have loss values for each individual batch.
Looking online I have found suggestions to use a custom callback class with an on_batch_end(self, logs={})... | [
"You could do that easily with a custom training loop, where you can just append a list with the loss value of every batch.\ntrain_loss_per_train_batch.append(loss_value.numpy())\n\nHere's how to do all of it:\nimport tensorflow as tf\nimport tensorflow_datasets as tfds\n\nds = tfds.load('iris', split='train', as_s... | [
0,
0
] | [] | [] | [
"keras",
"python",
"tensorflow"
] | stackoverflow_0065633357_keras_python_tensorflow.txt |
Q:
What is Python Ishell command to show the variables and dataframes that have been loaded?
I'm trying to see the variables and dataframes that are already loaded. I'm learning on datacamp. They have an online IDE which is quite simple but it doesn't show the variables that have been loaded. I'm wondering if there i... | What is Python Ishell command to show the variables and dataframes that have been loaded? | I'm trying to see the variables and dataframes that are already loaded. I'm learning on datacamp. They have an online IDE which is quite simple but it doesn't show the variables that have been loaded. I'm wondering if there is any IShell command to show those.
| [
"Try this magic command:\n%whos\n\nThis is what an output would look like:\nVariable Type Data/Info\n---------------------------------\nStringIO type <class '_io.StringIO'>\nTESTDATA StringIO <_io.StringIO object at 0x7f6f8e81c550>\ndf DataFrame 1 2 3 4 5\\na <...>z5... | [
0
] | [] | [] | [
"pandas",
"python",
"shell"
] | stackoverflow_0074115678_pandas_python_shell.txt |
Q:
Pylint not running as expected in VScode
When I am running via shell a pylint:
$ pylint decorator.py
No config file found, using default configuration
************* Module decorator
C: 7, 0: Unnecessary parens after 'print' keyword (superfluous-parens)
C: 15, 0: Unnecessary parens after 'print' keyword (superflu... | Pylint not running as expected in VScode | When I am running via shell a pylint:
$ pylint decorator.py
No config file found, using default configuration
************* Module decorator
C: 7, 0: Unnecessary parens after 'print' keyword (superfluous-parens)
C: 15, 0: Unnecessary parens after 'print' keyword (superfluous-parens)
C: 1, 0: Missing module docstring... | [
"Assuming you have configured Python's Extension correctly and you have Pylint installed,\nVSCode's Python Extension will do minimal checking by default if you do not provide a Pylint configuration option.\nSimply enter \"python.linting.pylintUseMinimalCheckers\": false, into your .vscode/settings.json to force thi... | [
38,
12,
0
] | [] | [] | [
"lint",
"python",
"visual_studio_code"
] | stackoverflow_0055726180_lint_python_visual_studio_code.txt |
Q:
(Python3) - Random number inserted at the end of only 1 word in a string of many words
I am trying to make a random word/phrase generator that is like the one that bitwarden has (in python3). But the issue I am running into and need some help with is the addition of 1 number at the end of 1 of the words that is sh... | (Python3) - Random number inserted at the end of only 1 word in a string of many words | I am trying to make a random word/phrase generator that is like the one that bitwarden has (in python3). But the issue I am running into and need some help with is the addition of 1 number at the end of 1 of the words that is shown.
Something like this Referee-Outrank-Cymbal-Cupping-Cresting-Fiber7-Expensive-Myth-Unvei... | [
"If I am understanding correctly, here is a solution:\n#Returns True or False. Basically Yes or No?\n capital_words = ''\n default_words = ''\n if beaupy.confirm(\"Capitalize?\"):\n \"\"\"Make list of words with the first letter capitalized.\"\"\"\n c_lst = []\n for i in word_list:\n ... | [
0,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074116050_python_python_3.x.txt |
Q:
statmodels predict train data: shapes not aligned
import numpy as np
import statsmodels.api as sm
duncan_prestige = sm.datasets.get_rdataset("Duncan", "carData")
Y = duncan_prestige.data['income']
print(Y.shape)
X = duncan_prestige.data['education']
print(X.shape)
X = sm.add_constant(X)
print(X.shape)
model = sm.O... | statmodels predict train data: shapes not aligned | import numpy as np
import statsmodels.api as sm
duncan_prestige = sm.datasets.get_rdataset("Duncan", "carData")
Y = duncan_prestige.data['income']
print(Y.shape)
X = duncan_prestige.data['education']
print(X.shape)
X = sm.add_constant(X)
print(X.shape)
model = sm.OLS(Y,X)
results = model.fit()
model.predict(X)
results.... | [
"Should have called\nresults.predict(X)\n\n"
] | [
0
] | [] | [] | [
"numpy",
"python",
"statmodels"
] | stackoverflow_0074117483_numpy_python_statmodels.txt |
Q:
Problem animating polar plots from measured data
Problem
I'm trying to animate a polar plot from a measured temperature data from a cylinder using the plotly.express command line_polar by using a dataset of 6 radial values (represented by columns #1 - #6) over 10 rows (represented by column Time) distributed over ... | Problem animating polar plots from measured data | Problem
I'm trying to animate a polar plot from a measured temperature data from a cylinder using the plotly.express command line_polar by using a dataset of 6 radial values (represented by columns #1 - #6) over 10 rows (represented by column Time) distributed over a polar plot. I'm struggling to make it animate and ge... | [
"I have found the solution to this problem, its also possible with scatterpolar but I recommend line_polar from plotly express, its way more elegant and easy. What you need to do is format the data from wide to long format using the pandas command melt(). This will allow you to correctly walk through the data and m... | [
0
] | [] | [] | [
"dataframe",
"plotly_python",
"polar_coordinates",
"python",
"visualization"
] | stackoverflow_0074080527_dataframe_plotly_python_polar_coordinates_python_visualization.txt |
Q:
python: recreating a function's typed parameter/defaults from strings
i have the following code:
import inspect, importlib
from pydoc import locate
def func(var:str = 'test', var2: int = 1, var3:list[int] = [1,2,3]):
pass
fspec = inspect.getfullargspec(func)
dflts = fspec.defaults
# fspec
spec_dict = {}
for ... | python: recreating a function's typed parameter/defaults from strings | i have the following code:
import inspect, importlib
from pydoc import locate
def func(var:str = 'test', var2: int = 1, var3:list[int] = [1,2,3]):
pass
fspec = inspect.getfullargspec(func)
dflts = fspec.defaults
# fspec
spec_dict = {}
for i, (a) in enumerate(fspec.annotations.items()):
type_name = a[1].__name... | [
"typing.get_type_hints is able to convert forward-ref strings into the actual types. i.e.:\ndef f(x: \"int\") -> \"str\":\n pass\n\nprint(get_type_hints(f))\n\nWill output:\n{'x': <class 'int'>, 'return': <class 'str'>}\n\nKnowing this, you can make a function, set its function signature and annotations with the ... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074117206_python.txt |
Q:
Scrapy spider not found error
This is Windows 7 with python 2.7
I have a scrapy project in a directory called caps (this is where scrapy.cfg is)
My spider is located in caps\caps\spiders\campSpider.py
I cd into the scrapy project and try to run
scrapy crawl campSpider -o items.json -t json
I get an error that t... | Scrapy spider not found error | This is Windows 7 with python 2.7
I have a scrapy project in a directory called caps (this is where scrapy.cfg is)
My spider is located in caps\caps\spiders\campSpider.py
I cd into the scrapy project and try to run
scrapy crawl campSpider -o items.json -t json
I get an error that the spider can't be found. The class... | [
"Make sure you have set the \"name\" property of the spider. \nExample:\nclass campSpider(BaseSpider):\n name = 'campSpider'\n\nWithout the name property, the scrapy manager will not be able to find your spider.\n",
"Also make sure that your project is not called scrapy! I made that mistake and renaming it fixe... | [
71,
29,
7,
7,
3,
2,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"python",
"scrapy"
] | stackoverflow_0009876793_python_scrapy.txt |
Q:
Create new column in Pandas that describes all elements in list column
I have 2 dataframes:
df1 = pd.DataFrame({"ID":[1, 2, 3, 4],
"item":[[22, 78], [78], [78,79], [78,456,254]}
df2 = pd.DataFrame({"IDs":[1,2], [3], [1,3,4], [3,4]}
and desired output is df2 with an extra column with all the items in 1 list desc... | Create new column in Pandas that describes all elements in list column | I have 2 dataframes:
df1 = pd.DataFrame({"ID":[1, 2, 3, 4],
"item":[[22, 78], [78], [78,79], [78,456,254]}
df2 = pd.DataFrame({"IDs":[1,2], [3], [1,3,4], [3,4]}
and desired output is df2 with an extra column with all the items in 1 list describing the "ID" elements. Ideally without duplicates and ordered by descendi... | [
"You could do explode + map then groupby get the unique value\ndf2['new'] = df2['IDs'].explode().map(dict(zip(df1['ID'],df1['item']))).explode().groupby(level=0).unique()\ndf2\nOut[47]: \n IDs new\n0 [1, 2] [22, 78]\n1 [3] [78, 79]\n2 [1, 3, 4]... | [
1
] | [] | [] | [
"list",
"pandas",
"python",
"replace"
] | stackoverflow_0074117348_list_pandas_python_replace.txt |
Q:
python dataframe slicing
Since today I have a problem with dataframe slicing with python (3.8.):
I use a large dataframe df (shape 25000, 1500)
When I used pandas series slicing ( df["No"] ) I got
No
null
null
null
null
null
null
null
null
when I use dataframe slicing ( df[["No"]] ) I got correctly
No
0
C_... | python dataframe slicing | Since today I have a problem with dataframe slicing with python (3.8.):
I use a large dataframe df (shape 25000, 1500)
When I used pandas series slicing ( df["No"] ) I got
No
null
null
null
null
null
null
null
null
when I use dataframe slicing ( df[["No"]] ) I got correctly
No
0
C_1
1
C_2
... | [
"Thank you for the response! No, the error was the same, however now \"\" is displayed instead of \"null\". The same error was shown in large numpy arrays (50000, 1500). I tried the identical code (python 3.8.13) in VS Code (1.72.2) and in contrast to Pycharm (PyCharm 2022.2.3 (Professional Edition)) the CORRECT va... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python",
"slice"
] | stackoverflow_0074098054_dataframe_pandas_python_slice.txt |
Q:
How to make a Python function that let me decide if a person is a teenager or not using if statement and fixed numbers
I have a "school" task that i need help to solve.
I have just learned about functions so i need to use them.
I got 3 persons age:
Ola 12 years old
kari 15 years old
Lise 20 years old
I need to p... | How to make a Python function that let me decide if a person is a teenager or not using if statement and fixed numbers | I have a "school" task that i need help to solve.
I have just learned about functions so i need to use them.
I got 3 persons age:
Ola 12 years old
kari 15 years old
Lise 20 years old
I need to print out using a function that i made if the ages is between 13 and 19 years old it should print out "you are a teenager" or... | [
"name = 'Ola'\nage = 12\n\ndef age_number(name, age):\n if (age >= 13 and age <= 19):\n print(f\"{name}, you are {age}. You are a teenager\")\n else: \n print(f\"{name}, you are {age}. You are not a teenager\")\n\n\nage_number(name, age)\n\n\nTry to read a book or blog to learn basics of funtions.\n",
"t... | [
1,
1,
1
] | [] | [] | [
"function",
"if_statement",
"python"
] | stackoverflow_0074117413_function_if_statement_python.txt |
Q:
Merge two columns from different df and put the results in the same columns pandas
I would like to join two dataframes columns by particular columns but I would like some columns to be joined together. I asked something similar here: old question
But now I would need to further split the results in the merge colum... | Merge two columns from different df and put the results in the same columns pandas | I would like to join two dataframes columns by particular columns but I would like some columns to be joined together. I asked something similar here: old question
But now I would need to further split the results in the merge column:
df1 = pd.DataFrame({'List' : ['P111:P666', 'P999', 'P111;P999:P777 ','P555', 'P666:P1... | [
"You can split, explode, then merge and aggregate again:\nout = df1.join(\n df1['List']\n .str.split(';')\n .explode().reset_index(name='Cod')\n .merge(df2, how='left')\n .fillna('-')\n .groupby('index')\n .agg({'Animal': ':'.join,\n 'Letter': '|'.join})\n )\n\nOutput:\n List Color An... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074117549_dataframe_pandas_python.txt |
Q:
Why do I have to use "py" to execute python commands instead of "python"?
I am a newbie in Python and had a problem with installing Python packages on my windows computer.
I installed Python itself and then had to install the packages "Numpy" and "Matplotlib" as well. My teacher told us to do it with the commands:... | Why do I have to use "py" to execute python commands instead of "python"? | I am a newbie in Python and had a problem with installing Python packages on my windows computer.
I installed Python itself and then had to install the packages "Numpy" and "Matplotlib" as well. My teacher told us to do it with the commands:
python -m pip install --upgrade pip
pip install numpy
pip install matplotlib
... | [
"When you install python on windows it usually comes with the python launcher. This provides a way to easily access all the python versions installed on your computer.\nThe python launcher uses the py command which access the default python version.\npy -0p will show you all the installed versions.\nSee https://www... | [
1
] | [] | [] | [
"cmd",
"python"
] | stackoverflow_0074115257_cmd_python.txt |
Q:
Html body displaying different from the source
I want to add a product to my Shopify Account using shopify-api.
Just for the description part of the product, I have a problem and that's because my product description formatting gets different from source website description.Thats my code to achieve this problem:
d... | Html body displaying different from the source | I want to add a product to my Shopify Account using shopify-api.
Just for the description part of the product, I have a problem and that's because my product description formatting gets different from source website description.Thats my code to achieve this problem:
description = soup.find("div",class_="description-con... | [
"You can do like this,\ndescription = soup.find(\"div\",class_=\"description-container\")\nhighlights = description.find(\"div\", {\"data-sort\": 13})\nselling_point = description.find(\"div\", {\"data-sort\": 14})\nspecifications = description.find(\"div\", {\"data-sort\": 15})\n\npayload ={\n \"product\":\n ... | [
0
] | [] | [] | [
"beautifulsoup",
"python",
"shopify",
"shopify_api"
] | stackoverflow_0074117625_beautifulsoup_python_shopify_shopify_api.txt |
Q:
Understanding the speed difference in threading
This is the script both threading functions call:
def searchBadWireless( hub ):
host = f'xxx.xxx.xxx.{hub}'
results = {}
try:
netConnect = ConnectHandler( device_type=platform, ip=host, username=cisco_username, password=cisco_password, )
... | Understanding the speed difference in threading | This is the script both threading functions call:
def searchBadWireless( hub ):
host = f'xxx.xxx.xxx.{hub}'
results = {}
try:
netConnect = ConnectHandler( device_type=platform, ip=host, username=cisco_username, password=cisco_password, )
output = netConnect.send_command( 'sh int status | i ... | [
"The first function is faster for the simple reason that all threads are started immediately. If your work items are of number N, you are lunching N threads in parallel. If your machine can handle that load, it will be fast.\nFor the second function, the ThreadPoolExecutor, by default, limits the number of threads ... | [
1
] | [] | [] | [
"netmiko",
"python",
"python_multithreading"
] | stackoverflow_0074112647_netmiko_python_python_multithreading.txt |
Q:
Writing data to excel from a formula in python
What I want is with openpyxl to write a value I get form a len() or dups() to an excel cell.
Here are my imports:
import xlwings as xw
Here is the code:
#Load workbook
app = xw.App(visible = False)
wb = xw.Book(FilePath)
RawData_ws = wb.sheets['Raw Data']
Sheet1 = w... | Writing data to excel from a formula in python | What I want is with openpyxl to write a value I get form a len() or dups() to an excel cell.
Here are my imports:
import xlwings as xw
Here is the code:
#Load workbook
app = xw.App(visible = False)
wb = xw.Book(FilePath)
RawData_ws = wb.sheets['Raw Data']
Sheet1 = wb.sheets['Sheet 1']
RawData_ws['A1'] = (len(df.inde... | [
"So, I already found the solution.\nChange:\nRawData_ws['A1'] = (len(df.index))\n\nFor:\nRawData_ws['A1'].values = (len(df.index))\n\n"
] | [
0
] | [] | [] | [
"openpyxl",
"python",
"python_3.x"
] | stackoverflow_0074117694_openpyxl_python_python_3.x.txt |
Q:
Using a dictionary i would like to have this string sequence ACCTAGCCCTA as {'AC': 1, 'CC': 3, 'CT': 2, 'TA': 2, 'AG': 1, 'GC': 1}
Using a dictionary I would like to have the string sequence "ACCTAGCCCTA" as {'AC': 1, 'CC': 3, 'CT': 2, 'TA': 2, 'AG': 1, 'GC': 1}
but my code gives me {'AC': 1, 'CC': 2, 'CT': 2, ... | Using a dictionary i would like to have this string sequence ACCTAGCCCTA as {'AC': 1, 'CC': 3, 'CT': 2, 'TA': 2, 'AG': 1, 'GC': 1} | Using a dictionary I would like to have the string sequence "ACCTAGCCCTA" as {'AC': 1, 'CC': 3, 'CT': 2, 'TA': 2, 'AG': 1, 'GC': 1}
but my code gives me {'AC': 1, 'CC': 2, 'CT': 2, 'TA': 2, 'AG': 1, 'GC': 1}, only CC 2.
p = input(str("entrez une chaine de caractere"))
dic = {p[i:i+2] : p.count(p[i:i+2] ) for i in ra... | [
"For an efficient solution, use collections.Counter and a generator expression:\ns = 'ACCTAGCCCTA'\n\nfrom collections import Counter\n\nout = dict(Counter(s[i:i+2] for i in range(len(s)-1)))\n\nOutput:\n{'AC': 1, 'CC': 3, 'CT': 2, 'TA': 2, 'AG': 1, 'GC': 1}\n\nvariant without import\nout = {}\nfor i in range(len(s... | [
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0074117430_python.txt |
Q:
Change String to Float Python
I would like to convert a list that I took out from a txt file into a float so I can make some calculous after in Python. I have the following list:
['1,0,1.2', '2,-1.5,1.2', '3,-1.5,0', '4,0,0', '5,1.5,1.2']
And I would like it to look like this:
[1,0,1.2,2,-1.5,1.2,3,-1.5,0,4,0,0,5... | Change String to Float Python | I would like to convert a list that I took out from a txt file into a float so I can make some calculous after in Python. I have the following list:
['1,0,1.2', '2,-1.5,1.2', '3,-1.5,0', '4,0,0', '5,1.5,1.2']
And I would like it to look like this:
[1,0,1.2,2,-1.5,1.2,3,-1.5,0,4,0,0,5,1.5,1.2]
All of them being float ... | [
"Two loops are needed here, an outer for the array and an inner loop over the spitted strings.\n>>> new = [float(v) for inner in a for v in inner.split(\",\")]\n>>> new\n[1.0, 0.0, 1.2, 2.0, -1.5, 1.2, 3.0, -1.5, 0.0, 4.0, 0.0, 0.0, 5.0, 1.5, 1.2]\n\nEDIT:\nTo up it to accept any case, differentiate between int/flo... | [
1,
0
] | [] | [] | [
"floating_point",
"python",
"python_3.x"
] | stackoverflow_0074117755_floating_point_python_python_3.x.txt |
Q:
How select cities from country (geopandas)?
I would like to select cities from polygon (Poland), but filter points in polygon doesn't work.
I have code:
import geopandas
world = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowres'))
world=world[world.name == 'Poland']
cities = geopandas.read_file(... | How select cities from country (geopandas)? | I would like to select cities from polygon (Poland), but filter points in polygon doesn't work.
I have code:
import geopandas
world = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowres'))
world=world[world.name == 'Poland']
cities = geopandas.read_file(geopandas.datasets.get_path('naturalearth_cities'... | [
"Doing read_file() with mask argument or an sjoin() should be the same. Currently due to an issues with compatibility of geos and gdal versions these are not the same on my environment.\nimport geopandas\n\nworld = geopandas.read_file(geopandas.datasets.get_path(\"naturalearth_lowres\"))\nworld = world[world.name ... | [
0
] | [] | [] | [
"geopandas",
"python"
] | stackoverflow_0074117666_geopandas_python.txt |
Q:
Translate text into english under certain conditions, python
I wrote a function that takes in a dataframe and a boolean list. If a value in the boolean list is 0 then we know where the text is not english. I wrote this function but I do not think its pythonic and follows best practices.
def translate_text(df, mask... | Translate text into english under certain conditions, python | I wrote a function that takes in a dataframe and a boolean list. If a value in the boolean list is 0 then we know where the text is not english. I wrote this function but I do not think its pythonic and follows best practices.
def translate_text(df, mask):
gs = goslate.Goslate()
for sd, d, r, m in zip(df['short... | [
"You can put the boolean as a column in your dataframe and use loc to filter out the row that needs to be translated. Also, you can define a function that takes in an array and do the translation.\n# function to translate language\ndef translation(array):\n return [gs.translate(i, 'en') for i in array]\n\ndf_sam... | [
2,
2
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074042596_pandas_python.txt |
Q:
Python - Error when running the 'help()' command outside of the interpreter?
I am starting out playing around with Python and trying to understand how to navigate it.
I noticed that in the regular command line (Power shell) I can at times run a python command like 'python -m ABC' and it executes just fine.
I recen... | Python - Error when running the 'help()' command outside of the interpreter? | I am starting out playing around with Python and trying to understand how to navigate it.
I noticed that in the regular command line (Power shell) I can at times run a python command like 'python -m ABC' and it executes just fine.
I recently learned about the "help()" function within the Python interpreter so for examp... | [
"help isn't a module; it's a callable class. To execute code, (which can include a call to a function/callable), you want -c:\npython -c 'help(print)'\n\n"
] | [
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074117880_python_python_3.x.txt |
Q:
Custom JSON format from dataframe
I have a following test code
import numpy as np
import pandas as pd
x = np.array([['101', 'title1', 'body1', 'answer1'], ['102', 'title2', 'body2', 'answer2'], ['103', 'title3', 'body3', 'answer3']])
df = pd.DataFrame(x, columns = ['col1', 'col2', 'col3', 'col4'])
df.head()... | Custom JSON format from dataframe | I have a following test code
import numpy as np
import pandas as pd
x = np.array([['101', 'title1', 'body1', 'answer1'], ['102', 'title2', 'body2', 'answer2'], ['103', 'title3', 'body3', 'answer3']])
df = pd.DataFrame(x, columns = ['col1', 'col2', 'col3', 'col4'])
df.head()
| col1 |col2 |col3 |col4
------... | [
"It's not dificult, I recommend you read at documentations of library.\nimport numpy as np\nimport pandas as pd\n\nx = np.array([['101', 'title1', 'body1', 'answer1'], ['102', 'title2', 'body2', 'answer2'],\n ['103', 'title3', 'body3', 'answer3']])\n\ndf = pd.DataFrame(x, columns=['col1', 'col2', 'col3... | [
1,
0,
0
] | [] | [] | [
"dataframe",
"json",
"pandas",
"python"
] | stackoverflow_0074115873_dataframe_json_pandas_python.txt |
Q:
ModuleNotFoundError: No module named 'MySQLdb'
After finishing of one of my Flask projects, I uploaded it on github just like everybody else. after a 2-3 months period I downloaded the entire githube repository on another machine to run it. However, the app is not working because the packages are not found giving ... | ModuleNotFoundError: No module named 'MySQLdb' | After finishing of one of my Flask projects, I uploaded it on github just like everybody else. after a 2-3 months period I downloaded the entire githube repository on another machine to run it. However, the app is not working because the packages are not found giving the following message
ModuleNotFoundError: No modu... | [
"I have read that mysqldb is not supported by python3\nAnd it looks like when you are trying to connect to your database you are using mysql db to connect to the database by default!\nyou need to change it by editing your DATABASE_URI configuration\nBut before you need to install the connector extension :\nwith thi... | [
52,
17,
12,
9,
2,
2,
2,
0
] | [] | [] | [
"flask",
"mysql_python",
"python"
] | stackoverflow_0053024891_flask_mysql_python_python.txt |
Q:
How do I sum the different values of an array corresponding with the values of a different array?
I am trying to sum the different values of an array, a, that corresponds with the values of b.
a = np.array([2,3,4,5,6,7,8,9,10])
b = np.array([1,1,1,2,3,4,5,5,6])
For example, array b has 3 elements that are 1 (firs... | How do I sum the different values of an array corresponding with the values of a different array? | I am trying to sum the different values of an array, a, that corresponds with the values of b.
a = np.array([2,3,4,5,6,7,8,9,10])
b = np.array([1,1,1,2,3,4,5,5,6])
For example, array b has 3 elements that are 1 (first 3 elements) and I want to add all the numbers in array a corresponding to this value. Also, 8 and 9 i... | [
"Try itertools.groupby:\nfrom itertools import groupby\n\na = np.array([2, 3, 4, 5, 6, 7, 8, 9, 10])\nb = np.array([1, 1, 1, 2, 3, 4, 5, 5, 6])\n\nc = [sum(v for v, _ in g) for v, g in groupby(zip(a, b), lambda x: x[1])]\nprint(c)\n\nPrints:\n[9, 5, 6, 7, 17, 10]\n\n"
] | [
1
] | [] | [] | [
"arrays",
"for_loop",
"numpy",
"python",
"sum"
] | stackoverflow_0074117831_arrays_for_loop_numpy_python_sum.txt |
Q:
Can you bypass a "Terms and Conditions" prompt with BeautifulSoup?
I want to scrape a GIS city website for project names active in town of Brighton. https://brighton.maps.arcgis.com/apps/webappviewer/index.html?id=2e3dacc6615e4cf59b6db043cc3f12cc
However, I can't seem to bypass the initial Terms & Agreements check... | Can you bypass a "Terms and Conditions" prompt with BeautifulSoup? | I want to scrape a GIS city website for project names active in town of Brighton. https://brighton.maps.arcgis.com/apps/webappviewer/index.html?id=2e3dacc6615e4cf59b6db043cc3f12cc
However, I can't seem to bypass the initial Terms & Agreements checkbox. I'm still new to webscraping so I'm not sure where to begin with t... | [
"No reason to bypass the checkbox as you are interested in the content anyway.\nYou can right-click the page, select inspect and then the network tab on the right side. Here you can see all the requests your browsers sends to load the page. As you can see its quite a lot.\nIf you are using requests, you have to mim... | [
1
] | [] | [] | [
"beautifulsoup",
"python",
"python_requests",
"web_scraping"
] | stackoverflow_0074117824_beautifulsoup_python_python_requests_web_scraping.txt |
Q:
Get value counts and date between for groupby
I have a dataframe that looks something like this:
df = pd.DataFrame(
[[1,'A','X','1/2/22 12:00:00AM'],
[1,'A','X','1/3/22 12:00:00AM'],
[1,'A','X','1/1/22 12:00:00AM'],
[1,'A','X','1/2/22 1:00:00AM'],
[1,'B','Y','1/1/22 1:00:00AM'],
[2,'A','Z','1/2/22 12:00:00AM']... | Get value counts and date between for groupby | I have a dataframe that looks something like this:
df = pd.DataFrame(
[[1,'A','X','1/2/22 12:00:00AM'],
[1,'A','X','1/3/22 12:00:00AM'],
[1,'A','X','1/1/22 12:00:00AM'],
[1,'A','X','1/2/22 1:00:00AM'],
[1,'B','Y','1/1/22 1:00:00AM'],
[2,'A','Z','1/2/22 12:00:00AM'],
[2,'A','Z','1/1/22 12:00:00AM'],
columns=['ID', ... | [
"Try:\n# convert the \"Task Completed\" column to datetime:\ndf[\"Task Completed\"] = pd.to_datetime(df[\"Task Completed\"], dayfirst=False)\n\n\nx = df.groupby([\"ID\", \"Category\", \"Site\"], as_index=False).agg(\n **{\n \"Time Difference\": (\n \"Task Completed\",\n lambda x: (x.... | [
3,
1
] | [] | [] | [
"dataframe",
"group_by",
"pandas",
"python"
] | stackoverflow_0074116723_dataframe_group_by_pandas_python.txt |
Q:
Using PyMuPDF "draw_rect" function is working inconsistent
I'm blacking out some information from several PDF's but there are some of these that the rectangles made by "draw_rect" functions are't being drawn correctly. I have checked the rectangles and they look right, that and I'm also usind the "add_redact_annot... | Using PyMuPDF "draw_rect" function is working inconsistent | I'm blacking out some information from several PDF's but there are some of these that the rectangles made by "draw_rect" functions are't being drawn correctly. I have checked the rectangles and they look right, that and I'm also usind the "add_redact_annot" with the exact same rectangle and works good.
def hide_text_re... | [
"The probable reason for this behaviour is a sloppy specification of the page's coordinate system.\nFor example the standard point (0,0) = bottom-left in PDF may have been redefined to be top-left.\nIf this type of coordinate change is not wrapped within PDF stacking operators q / Q (as it should), then any inserti... | [
0
] | [] | [] | [
"pdf",
"pymupdf",
"python"
] | stackoverflow_0074103404_pdf_pymupdf_python.txt |
Q:
Does this question need a for or while loop or?
A University is testing a new fertilizer. They are interested in how long the fertilizer may be kept before its effectiveness is lost. They have done some calculations that indicate the fertilizer loses 6% of its potency every month. Design a Python algorithm that fi... | Does this question need a for or while loop or? |
A University is testing a new fertilizer. They are interested in how long the fertilizer may be kept before its effectiveness is lost. They have done some calculations that indicate the fertilizer loses 6% of its potency every month. Design a Python algorithm that finds how many months it takes before the fertilizer h... | [
"Either works. For a class for \"complete beginners\", they'd almost certainly expect you to use a while, because there's no fixed number of iterations to solve the problem, so a while testing your stop condition is the straightforward solution; you'd just have to manually track how many months had passed along wit... | [
1,
0
] | [] | [] | [
"for_loop",
"iteration",
"python",
"while_loop"
] | stackoverflow_0074117870_for_loop_iteration_python_while_loop.txt |
Q:
Django CSRF Cookie Not Set
I have some problem for a while now, I'm experiencing CSRF Cookie not set. Please look at the codes below:
views.py:
def deposit(request, account_num):
if request.method == 'POST':
account = get_object_or_404(account_info, acct_number=account_num)
form_ = AccountForm(... | Django CSRF Cookie Not Set | I have some problem for a while now, I'm experiencing CSRF Cookie not set. Please look at the codes below:
views.py:
def deposit(request, account_num):
if request.method == 'POST':
account = get_object_or_404(account_info, acct_number=account_num)
form_ = AccountForm(request.POST or None, instance=a... | [
"This can also occur if CSRF_COOKIE_SECURE = True is set and you are accessing the site non-securely or if CSRF_COOKIE_HTTPONLY = True is set as stated here and here\n",
"from django.http import HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\n\n@csrf_exempt \ndef your_view(request):\n if re... | [
158,
85,
26,
24,
9,
6,
2,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
"In your view are you using the csrf decorator??\nfrom django.views.decorators.csrf import csrf_protect\n@csrf_protect\n def view(request, params):\n ....\n"
] | [
-4
] | [
"django",
"django_cookies",
"python"
] | stackoverflow_0017716624_django_django_cookies_python.txt |
Q:
python pandas assign values to column based on formula
I have a formula as a text that is generated on the fly (dynamic)
formula = "(-500) + 7.7* df['A'] + -0.1234 * df['B']"
the formula is a text string and it is configured at run time, but it will always have dependency on existing other fields.
I would like to... | python pandas assign values to column based on formula | I have a formula as a text that is generated on the fly (dynamic)
formula = "(-500) + 7.7* df['A'] + -0.1234 * df['B']"
the formula is a text string and it is configured at run time, but it will always have dependency on existing other fields.
I would like to use this formaul to create a new field df['calculated'] tha... | [
"Using pd.assign and eval\nformula = \"(-500) + 7.7 * df['A'] + -0.1234 * df['B']\"\ndf = df.assign(calculated=eval(formula))\n\n"
] | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074117949_pandas_python.txt |
Q:
Python selenium click on a button multiples times
I'm trying to click on an "Add" button located in diffents page places, and I need to click on it many times as I have a list containing numbers which is equal to numbers of clicking the "Add" button. I've enumerate a that return index and numbers like:
1: 10
2: 9
... | Python selenium click on a button multiples times | I'm trying to click on an "Add" button located in diffents page places, and I need to click on it many times as I have a list containing numbers which is equal to numbers of clicking the "Add" button. I've enumerate a that return index and numbers like:
1: 10
2: 9
3: 9
4: 3
5: 4
The index belongs to the location of th... | [
"I finnaly managed to get a solution, if it could help someone, here's the code:\n for location, add in enumerate(get_click_number_by_location):\n n_location = location\n add_click = self.driver.find_element(By.XPATH, f\"//div[@id='part-{n_location}/accordeon']//div[contains(@class,'btn... | [
1
] | [] | [] | [
"python",
"selenium"
] | stackoverflow_0074107526_python_selenium.txt |
Q:
Find the nearest value in dataframe column and calculate the difference for each row
Even though I was googling a lot, I couldn't find the solution for my problem.
I have dataframe
filter10 REF
0 NaN 0.00
1 NaN 0.75
2 NaN 1.50
3 NaN 2.25
4 NaN 3.00
5 NaN ... | Find the nearest value in dataframe column and calculate the difference for each row | Even though I was googling a lot, I couldn't find the solution for my problem.
I have dataframe
filter10 REF
0 NaN 0.00
1 NaN 0.75
2 NaN 1.50
3 NaN 2.25
4 NaN 3.00
5 NaN 3.75
6 NaN 4.50
...
15 2.804688 11.25
16 3.021875 12.00
17 3.578... | [
"Use pandas.merge_asof to find the nearest value:\ndf['DIFF'] = (pd.merge_asof(df['filter10'].dropna().sort_values().reset_index(),\n df[['REF']].dropna().sort_values('REF'),\n left_on='filter10', right_on='REF', direction='nearest')\n .set_index(... | [
2,
0
] | [] | [] | [
"dataframe",
"find",
"pandas",
"python"
] | stackoverflow_0074117715_dataframe_find_pandas_python.txt |
Q:
Python list while loop check
my aim is to run the while loop until the user inputs a option that is in my list. If they do the while loop should end.
exchangeCurrency = input("what currency would you like to convert to: ").upper()
myList = ["USD", "ERU", "BRL", "JPY", "TRY"]
while exchangeCurrency != myList:
... | Python list while loop check | my aim is to run the while loop until the user inputs a option that is in my list. If they do the while loop should end.
exchangeCurrency = input("what currency would you like to convert to: ").upper()
myList = ["USD", "ERU", "BRL", "JPY", "TRY"]
while exchangeCurrency != myList:
print("this is not a valid inpit"... | [
"while True:\n exchangeCurrency = input(\"what currency would you like to convert to: \").upper()\n if exchangeCurrency in myList:\n break\n\n",
"This would be the code:\nmyList = [\"USD\", \"ERU\", \"BRL\", \"JPY\", \"TRY\"]\n\nuserInput = input(\"Enter a currency: \").upper()\nwhile userInput not i... | [
3,
1,
0
] | [
"a simple solution that may work\nisTrue = True\n\nwhile isTrue:\n if exchangeCurrency != myList:\n print(\"try again. Invalid currency\")\n else:\n print(\"this currency is on the list\")\n isTrue = False\n\n"
] | [
-1
] | [
"python"
] | stackoverflow_0074118010_python.txt |
Q:
Python SMTP 'unable to get local issuer certificate' in python virtualenv
Sorry if title is unclear.
I'm trying to send an email through python 3.10 through the standard library. It works locally on my machine with these default settings.
smtp_server = "smtp.office365.com"
port = 587 # For starttls
sender_email =... | Python SMTP 'unable to get local issuer certificate' in python virtualenv | Sorry if title is unclear.
I'm trying to send an email through python 3.10 through the standard library. It works locally on my machine with these default settings.
smtp_server = "smtp.office365.com"
port = 587 # For starttls
sender_email = os.environ.get("EMAIL")
password = os.environ.get("EMAIL_PASSWORD")
# Create ... | [
"You are seeing two separate issues. TLS/certificate issues, and then an authentication issue which most likely has nothing to do with TLS.\nThere is no need for you to use unverified TLS. You can get the catrust from mozilla via the certifi package. Not sure if microsoft uses browser trust to sign their certifi... | [
2
] | [] | [] | [
"email",
"python",
"smtp",
"ssl",
"ubuntu"
] | stackoverflow_0074117934_email_python_smtp_ssl_ubuntu.txt |
Q:
Python/Pandas/NLTK: Iterating through a DataFrame, get value, transform it and add the new value to a new column
I scraped some data from google news into a dataframe:
DataFrame:
df
title link pubDate description source source_url
0 Australian research finds cost-effective way t... https://news.... | Python/Pandas/NLTK: Iterating through a DataFrame, get value, transform it and add the new value to a new column | I scraped some data from google news into a dataframe:
DataFrame:
df
title link pubDate description source source_url
0 Australian research finds cost-effective way t... https://news.google.com/__i/rss/rd/articles/CB... Sat, 15 Oct 2022 23:51:00 GMT Australian research finds cost-effective way t.... | [
"This will be a very slow solution with a for loop, but it might work for a small dataset. Iterating through all the links and then applying the transformations needed, and ultimately create a new column in the dataframe\nsummaries = []\nfor l in df['source_url'].values:\n article = Article(l)\n article.downl... | [
0
] | [] | [] | [
"dataframe",
"loops",
"nltk",
"pandas",
"python"
] | stackoverflow_0074116535_dataframe_loops_nltk_pandas_python.txt |
Q:
lxml.etree Invalid Predicate: "./tbody/tr[position() = 1]"
The XPath './tbody/tr[position() = 1]' is accepted by Firefox's XPath engine, but it's being rejected on lxml 4.5.0 (libxml2 2.9.10; Python 3.8.10; Ubuntu 20.04.5).
…
File "src/lxml/etree.pyx", line 1532, in lxml.etree._Element.find
File "src/lxml/_e... | lxml.etree Invalid Predicate: "./tbody/tr[position() = 1]" | The XPath './tbody/tr[position() = 1]' is accepted by Firefox's XPath engine, but it's being rejected on lxml 4.5.0 (libxml2 2.9.10; Python 3.8.10; Ubuntu 20.04.5).
…
File "src/lxml/etree.pyx", line 1532, in lxml.etree._Element.find
File "src/lxml/_elementpath.py", line 323, in lxml._elementpath.find
File "src/... | [
"\n File \"src/lxml/etree.pyx\", line 1532, in lxml.etree._Element.find\n\n\n\nElementPath\n… advanced features like value comparison and functions are not available.\n\nFor the particular use-case in the OP, .find('./tbody/tr[1]') will work.\nIf you end up needing more advanced queries, use .xpath instead:\n\nXPa... | [
0
] | [] | [] | [
"lxml",
"python",
"xpath"
] | stackoverflow_0074117878_lxml_python_xpath.txt |
Q:
How to convert a large csv file to a pickle file?
I have a very big csv file (73.1 GB). I want to convert this CSV file to a Pickle file format.
Is there a way to do this in Python?
Thank you very much!
A:
This takes the csv and dumpsit into a .pkl file
import csv
import pickle
with open('hello.csv', 'r') as f:... | How to convert a large csv file to a pickle file? | I have a very big csv file (73.1 GB). I want to convert this CSV file to a Pickle file format.
Is there a way to do this in Python?
Thank you very much!
| [
"This takes the csv and dumpsit into a .pkl file\nimport csv\nimport pickle\n\nwith open('hello.csv', 'r') as f:\n reader = csv.reader(f)\n pickle.dump(list(reader), open('hello.pkl', 'wb'))\n\n"
] | [
1
] | [] | [] | [
"csv",
"dataframe",
"pandas",
"pickle",
"python"
] | stackoverflow_0074118040_csv_dataframe_pandas_pickle_python.txt |
Q:
flask-sqlalchemy max value of column
Lets say I have a user model as such
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_ke... | flask-sqlalchemy max value of column | Lets say I have a user model as such
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.Strin... | [
"You could order by numLogins and take the first result, but that won't work if multiple people have the same number. Instead, find the max number, then find all users with that number.\nfrom sqlalchemy import func\n\nmax_logins = db.session.query(func.max(User.numLogins)).scalar()\nusers = db.session.query(User).f... | [
21,
1
] | [] | [] | [
"flask",
"flask_sqlalchemy",
"python",
"sqlalchemy"
] | stackoverflow_0023067750_flask_flask_sqlalchemy_python_sqlalchemy.txt |
Q:
How to generate 3D mesh from a numpy binary mask
I did a 3D segmentation of an organ in a 3D volume of data acquired in CT.
The output of the segmentation is defined as a binary 3D ndarray, where 1 is inside the organ, and 0 is outside the organ.
What is the best tool to extract the surface of this object as a mes... | How to generate 3D mesh from a numpy binary mask | I did a 3D segmentation of an organ in a 3D volume of data acquired in CT.
The output of the segmentation is defined as a binary 3D ndarray, where 1 is inside the organ, and 0 is outside the organ.
What is the best tool to extract the surface of this object as a mesh, that I can then export into a mesh format such as .... | [
"I'm not sure that is a best variant, but there is easy way to do it if use MeshLib.\nTo install it on Windows use py -3.10 -m pip install --upgrade meshlib\nScript to do this will look like:\nimport meshlib.mrmeshpy as mr\n\n#export NDarray to file\n#\"W50_H100_S150_V1000_F\" - parameters of voxels data\n#W - widt... | [
0
] | [] | [] | [
"marching_cubes",
"mesh",
"numpy",
"python"
] | stackoverflow_0069524209_marching_cubes_mesh_numpy_python.txt |
Q:
SQLAlchemy engine.execute not committing COPY large table from .csv
According to the docs, engine.execute autocommits. However, the COPY command does not commit when ran in the code below. When I directly run the exact same queries in the postgres command line it works.
The .csv contains ~3e6 rows and ~25 columns,... | SQLAlchemy engine.execute not committing COPY large table from .csv | According to the docs, engine.execute autocommits. However, the COPY command does not commit when ran in the code below. When I directly run the exact same queries in the postgres command line it works.
The .csv contains ~3e6 rows and ~25 columns, so I wonder if this has to do with the issue and if there's a workaround... | [
"SQLAlchemy does not autocommit by default. It will depend on the dialect being used.\nFor postgresql, the sqlalchemy engine sends a non auto-committable transaction behind the scenes and it will wait for commit command.\nFor autocommits, you will need to explicitly enable it in your engine or connection.\neg:\nen... | [
1
] | [] | [] | [
"postgresql",
"python",
"sqlalchemy"
] | stackoverflow_0074118049_postgresql_python_sqlalchemy.txt |
Q:
Decrypt Secure Strings in Windows DPAPI using Python
Given a Windows DPAPI file with values stored as Secure Strings How would one decrypt those values in Python? The secure string is created with PowerShell like this.
$global:Credentials.AuthToken = Read-Host -AsSecureString -Prompt "Auth-Token:"
and these value... | Decrypt Secure Strings in Windows DPAPI using Python | Given a Windows DPAPI file with values stored as Secure Strings How would one decrypt those values in Python? The secure string is created with PowerShell like this.
$global:Credentials.AuthToken = Read-Host -AsSecureString -Prompt "Auth-Token:"
and these values are stored using DPAPI on a Windows 10 or similar Comput... | [
"Using Python extract the Secure String from the DPAPI file and feed it to the function below. The secure string will be stored as a base64 encoded value.\nNote: when you read the DPAPI file created by PowerShell ensure you use \"utf-16-le\" encoding.\nimport codecs\nimport win32crypt\nimport base64\n \ndef ... | [
1
] | [] | [] | [
"dpapi",
"powershell",
"python",
"windows"
] | stackoverflow_0074118073_dpapi_powershell_python_windows.txt |
Q:
Dataframe not properly writing to excel file
I have the below dataframe:
Customer Code 05-01-2021 06-01-2021 07-01-2021 08-01-2021 09-01-2021 10-01-2021 11-01-2021 ... 02-01-2022 03-01-2022 04-01-2022 05-01-2022 06-01-2022 07-01-2022 08-01-2022 09-01-2022
0 C04209 NaN NaN 132.25 57... | Dataframe not properly writing to excel file | I have the below dataframe:
Customer Code 05-01-2021 06-01-2021 07-01-2021 08-01-2021 09-01-2021 10-01-2021 11-01-2021 ... 02-01-2022 03-01-2022 04-01-2022 05-01-2022 06-01-2022 07-01-2022 08-01-2022 09-01-2022
0 C04209 NaN NaN 132.25 579.0 1228.49 NaN 1978.08 ... 2060.... | [
"Maybe try to identify the index as that first column?\ndf.to_excel(writer, sheet_name=e, index=0) writer.save()\n",
"You could also try using the first column as an index\ndf2 = df.copy()\ndf2 = df2.drop(\"Customer Code\", axis=1)\ndf2.index = df['Customer Code']\ndf2.to_excel(writer, sheet_name=3, index=False)\... | [
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074118119_pandas_python.txt |
Q:
How to control all objects within a group in pygame
I've been trying to use classes and adding sprites to groups, this works fine but I don't know how to refer to everything in a group, I tried to look this up but I'm still stuck, I might need to use def functions or whatever inside the class but I couldn't get th... | How to control all objects within a group in pygame | I've been trying to use classes and adding sprites to groups, this works fine but I don't know how to refer to everything in a group, I tried to look this up but I'm still stuck, I might need to use def functions or whatever inside the class but I couldn't get that to work, here my code:
import random
pygame.init()
sc... | [
"if you have a .update method in your class, it will be called by Pygame when you call group.update(). Otherwise, just loop through your sprites by using the group with a for loop:\nfor sprite in RainGroup:\n # do things to sprite here\n ...\n\n"
] | [
0
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0074117975_pygame_python.txt |
Q:
How to increase speed on finding an index?
I have two dataframes:
df2
Time(s) vehicle_id
10 1
11 1
12 1
13 1
... ...
78 2
79 2
80 2
And com:
index v1 v2
1 1 2
I would like to find out the index of the row which matches the fo... | How to increase speed on finding an index? | I have two dataframes:
df2
Time(s) vehicle_id
10 1
11 1
12 1
13 1
... ...
78 2
79 2
80 2
And com:
index v1 v2
1 1 2
I would like to find out the index of the row which matches the following condition:
if (abs(max(df2.loc[df2['vehi... | [
"It looks like you only need to consider the max time for each id, so why not sort then drop duplicates to keep only the max time per vehicle id. Then you can replace the vehicle ids in your comm df w/the times and perform your filter conditions on the entire result, saving the resulting indexes to an array.\nimp... | [
1
] | [] | [] | [
"indexing",
"pandas",
"python",
"subset"
] | stackoverflow_0074118067_indexing_pandas_python_subset.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.