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:
How do I convert time series data from wide to long format using python (pandas package)?
I have some data taken at different time points in wide format, and need to convert it to long format to aid with analysis and to merge it with another dataset.
The format of the data is (where A_0 means value of A at time 0,... | How do I convert time series data from wide to long format using python (pandas package)? | I have some data taken at different time points in wide format, and need to convert it to long format to aid with analysis and to merge it with another dataset.
The format of the data is (where A_0 means value of A at time 0, A_15 means value at time 15):
import pandas as pd
df_wide = pd.DataFrame({'Subject': ['AA', '... | [
"You can use pd.wide_to_long:\nx = pd.wide_to_long(\n df_wide, i=\"Subject\", j=\"Time\", stubnames=[\"A\", \"B\", \"C\"], sep=\"_\"\n)\nprint(x)\n\nPrints:\n A B C\nSubject Time \nAA 0 1 1 1\nBB 0 2 2 2\nCC 0 3 3 3\nDD 0 4 4 4\nAA 15 2 ... | [
2,
0
] | [] | [] | [
"melt",
"pivot",
"python",
"reshape"
] | stackoverflow_0074448683_melt_pivot_python_reshape.txt |
Q:
How to convert a string to an integer class within a python function?
In a python function, I have defined two variables as letters.
def Vandermonde(x, d):
x_0=-1
a = np.arange(d)
I am getting the error that "d"is not defined in a = np.arange(d). I suspect, but could be wrong, that this is because d is classi... | How to convert a string to an integer class within a python function? | In a python function, I have defined two variables as letters.
def Vandermonde(x, d):
x_0=-1
a = np.arange(d)
I am getting the error that "d"is not defined in a = np.arange(d). I suspect, but could be wrong, that this is because d is classified as a string not an integer.
I was expecting this to not matter in the ... | [
"Indentation! Python functions (and their respective scopes) are defined via indentations.\ndef Vandermonde(x, d):\n x_0=-1\n a = np.arange(d) # Note the indentation here\n\nshould fix the problem...\n"
] | [
0
] | [] | [] | [
"integer",
"python",
"range",
"string"
] | stackoverflow_0074449354_integer_python_range_string.txt |
Q:
Calling a variable from a def function to another def function
I'm having a hard time with calling the recordtable variable from my def btn3function() to my def update(). Anyone can help how I can call it without any error? Here's the full detail. I hope this will help, and thank you in advance again. I'm open to ... | Calling a variable from a def function to another def function | I'm having a hard time with calling the recordtable variable from my def btn3function() to my def update(). Anyone can help how I can call it without any error? Here's the full detail. I hope this will help, and thank you in advance again. I'm open to any suggestion or ideas. Willing to be enlightened.
reg = []
def re... | [
"Pass the recordtable variable into update as a parameter: def btn3function(rt). I'm not sure where you're actually calling update, but when you do you should do this: update(recordtable) somewhere after the declaration of recordtable\n"
] | [
0
] | [] | [] | [
"python",
"python_3.x",
"tkinter",
"tkinter_entry"
] | stackoverflow_0074449313_python_python_3.x_tkinter_tkinter_entry.txt |
Q:
Salesforce Pyforce replacement
I am pulling cases/tickets in Salesforce and responding to each case via email.
I had been doing this using Pyforce but it is no longer compatible so I need an alternative. I am using simple salesforce to login and query all the tickets but I can't find a way to respond on the ticke... | Salesforce Pyforce replacement | I am pulling cases/tickets in Salesforce and responding to each case via email.
I had been doing this using Pyforce but it is no longer compatible so I need an alternative. I am using simple salesforce to login and query all the tickets but I can't find a way to respond on the ticket via email.
Previously I was using ... | [
"It seems that PyForce uses SOAP API which well, all cool kids moved on to REST API. SOAP has dedicated sendEmail() call. You might still be able to hand-craft the matching XML message and send it using credentials obtained from simple-salesforce...\nBut have a look at https://developer.salesforce.com/docs/atlas.en... | [
0
] | [] | [] | [
"python",
"salesforce",
"simple_salesforce"
] | stackoverflow_0074447938_python_salesforce_simple_salesforce.txt |
Q:
(python - cpp) - How to split the c++ codes while writing a lexical analyzer in python?
I wrote a lexical analyzer for cpp codes in python, but the problem is when I use input.split(" ") it won't recognize codes like x=2 or function() as three different tokens unless I add an space between them manually, like: x =... | (python - cpp) - How to split the c++ codes while writing a lexical analyzer in python? | I wrote a lexical analyzer for cpp codes in python, but the problem is when I use input.split(" ") it won't recognize codes like x=2 or function() as three different tokens unless I add an space between them manually, like: x = 2 .
also it fails to recognize the tokens at the beginning of each line.
(if i add spaces be... | [
"Obviously, if you try to have success splitting such an expression like x=2 and also x = 2... it seems pretty obvious that isn't going to work.\nWhat you are looking is for a solution that works with both right?\nBasic solution is to use an and operator, and use the conditions that you need to parse. Note that thi... | [
0
] | [
"The usual approach is to scan the incoming text from left to right. At each character position, the lexical analyser selects the longest string which fits some pattern for a \"lexeme\", which is either a token or ignored input (whitespace and comments, for example). Then the scan continues at the next character.\n... | [
-1
] | [
"c++",
"lexical_analysis",
"python"
] | stackoverflow_0074444548_c++_lexical_analysis_python.txt |
Q:
Loop Searches for String within a String from Two DataFrames
I have two DataFrames of maintenance schedules from a dealership's repair shop for multiple car models:
The first DataFrame, titled "firstworkitems", is the all car models' first maintenance schedule consolidated into one df.
The second DataFrame, title... | Loop Searches for String within a String from Two DataFrames | I have two DataFrames of maintenance schedules from a dealership's repair shop for multiple car models:
The first DataFrame, titled "firstworkitems", is the all car models' first maintenance schedule consolidated into one df.
The second DataFrame, titled "lastworkitems", is all the car models' last maintenance schedul... | [
"You want to use pd.merge() https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.merge.html to merge these two dataframes based on the work item (and car model if item is not unique). From there, you can use your np.where condition to search for appropriate text without having to loop\n"
] | [
0
] | [] | [] | [
"dataframe",
"for_loop",
"pandas",
"python",
"string"
] | stackoverflow_0074448836_dataframe_for_loop_pandas_python_string.txt |
Q:
FastAPI with redirects on AWS Lambda : Too many redirects
I have a Spotify project needing authorization codes through their API. I built an API to redirect the user to Spotify's login and then turn back to my API along with the user's code.
The API:
import boto3
import requests
import base64
from fastapi import A... | FastAPI with redirects on AWS Lambda : Too many redirects | I have a Spotify project needing authorization codes through their API. I built an API to redirect the user to Spotify's login and then turn back to my API along with the user's code.
The API:
import boto3
import requests
import base64
from fastapi import APIRouter
from fastapi.responses import RedirectResponse
from ma... | [
"Does it makes a different if you call baseurl/ vs baseurl/login ?\nIf someone is already logged in and hits the baseurl you redirecting him.\n/ -> /login -> spotify -> /home\nYou can try sort / -> /login into one as its still just a redirection.\nUpdate 1:\nDo not use the same variable base in login and main.\n\nL... | [
0
] | [] | [] | [
"amazon_web_services",
"aws_lambda",
"fastapi",
"python"
] | stackoverflow_0074447370_amazon_web_services_aws_lambda_fastapi_python.txt |
Q:
how can I control three different threads using threading in python?
I have thread1, thread2 and thread3, global variable x and three different functions to increament x,
import threading
import time
#check = threading.Condition()
x=1
def add_by1():
global x
x+=1
time.sleep(1)
print(x)
def ... | how can I control three different threads using threading in python? | I have thread1, thread2 and thread3, global variable x and three different functions to increament x,
import threading
import time
#check = threading.Condition()
x=1
def add_by1():
global x
x+=1
time.sleep(1)
print(x)
def add_by2():
x+=2
time.sleep(1)
print(x)
def add_by3():
x+=... | [
"I guess this approach is reliable. You can synchronize your threads using three lock objects - one for each.\nThe way this setup works is each thread acquires its lock and after doing its job, it releases next thread's lock! IOW, add_by1 releases thread_lock_two, add_by2 releases thread_lock_three and lastly add_b... | [
1
] | [] | [] | [
"global",
"multithreading",
"python",
"python_multithreading",
"variables"
] | stackoverflow_0074425842_global_multithreading_python_python_multithreading_variables.txt |
Q:
Collecting data from a dictionary
I have a dictionary which has many different sessions that start and end at different datetimes. Each session bucket has multiple results and each result has a timestamp.
Every result can be an error or not not.
I want to collect the data for all sessions to answer the question: d... | Collecting data from a dictionary | I have a dictionary which has many different sessions that start and end at different datetimes. Each session bucket has multiple results and each result has a timestamp.
Every result can be an error or not not.
I want to collect the data for all sessions to answer the question: do errors occur more often at the end or... | [
"The target \"buckets\" within the object \"aggregations\" is not a dictionary but a list.\nCorrent answer for your problem\nbuckets = resp[\"aggregations\"][\"Sessioncount\"][\"buckets\"][0]\nsessionTimestamps = buckets[\"SessionTimestamps\"]\n\ndf = pd.json_normalize(sessionTimestamps)\n\nWhy has the problem occu... | [
3
] | [] | [] | [
"dictionary",
"elasticsearch",
"python"
] | stackoverflow_0074448757_dictionary_elasticsearch_python.txt |
Q:
AWS: numpy ndarray to 'Bytes' conversion
I am trying to use Amazon Textract via Python (boto3) interface.
While uploading file from local drive everything goes well:
import boto3
import numpy as np
def filename_to_json(self, filename):
client = boto3.client('textract')
if filename is not None:
wit... | AWS: numpy ndarray to 'Bytes' conversion | I am trying to use Amazon Textract via Python (boto3) interface.
While uploading file from local drive everything goes well:
import boto3
import numpy as np
def filename_to_json(self, filename):
client = boto3.client('textract')
if filename is not None:
with open(filename, 'rb') as image:
r... | [
"You could use pip install amazon-textract-textractor which is a package that offers easy-to-use methods that take care of the conversions for you.\nfrom PIL import Image\nfrom textractor import Textractor\n\nextractor = Textractor(profile_name=\"default\")\ndocument = extractor.detect_document_text(\n file_sour... | [
1
] | [] | [] | [
"amazon_textract",
"python"
] | stackoverflow_0074449187_amazon_textract_python.txt |
Q:
is it possible to recheck an index in a list in the same loop again? python
What I'm trying to do is to make the loop goes to every index in the "investments" list then checks if it's equal to "aMoney" variable or not. if the statement is True then the same index of "investments" in "revenue" list data will be add... | is it possible to recheck an index in a list in the same loop again? python | What I'm trying to do is to make the loop goes to every index in the "investments" list then checks if it's equal to "aMoney" variable or not. if the statement is True then the same index of "investments" in "revenue" list data will be added to "totalMoney" variable and goes back again to do next.
My problem is that I ... | [
"In python, we don't need to initialise int variables as int(number), just declaring them with the corresponding value suffices. So instead of aMoney = int(2040), just aMoney = 2040 works.\nYou can use zip to sort the investments and revenue together. Here's a simplified code which does what you need -\ninitialMone... | [
0
] | [] | [] | [
"if_statement",
"list",
"loops",
"python"
] | stackoverflow_0074449339_if_statement_list_loops_python.txt |
Q:
Training loss not decreasing when training - tensorflow gpu
I am training a graph neural network on a node cluster with one gpu Titan RTX. I am using Tensorflow-gpu 1.15 and it can recognize the gpu successfully. The training involves some tensors operations of type float 64, where the training set is formed by 25... | Training loss not decreasing when training - tensorflow gpu | I am training a graph neural network on a node cluster with one gpu Titan RTX. I am using Tensorflow-gpu 1.15 and it can recognize the gpu successfully. The training involves some tensors operations of type float 64, where the training set is formed by 256K sparse block-circulant matrices of moderate size. I evaluate 2... | [
"Type tf.float64 is not the problem when you select the correct optimizer when I am running on version 1 compatibility mode 'tf.compat.v1.disable_eager_execution()'\n\nSelect the correct input data and target optimizer.\nSelect the correct tf.Variable.\nSelect the optimized equation or methods.\nInput may require s... | [
0
] | [] | [] | [
"deep_learning",
"gpu",
"loss_function",
"python",
"tensorflow"
] | stackoverflow_0074447861_deep_learning_gpu_loss_function_python_tensorflow.txt |
Q:
How to get the latest offset from each partition using kafka-python?
I'm trying to get the latest offset (not committed offset) from each partition for a given topic.
from kafka import KafkaConsumer, TopicPartition
topic = 'test-topic'
broker = 'localhost:9092'
consumer = KafkaConsumer(bootstrap_servers=broker)
... | How to get the latest offset from each partition using kafka-python? | I'm trying to get the latest offset (not committed offset) from each partition for a given topic.
from kafka import KafkaConsumer, TopicPartition
topic = 'test-topic'
broker = 'localhost:9092'
consumer = KafkaConsumer(bootstrap_servers=broker)
tp = TopicPartition(topic, 0) #1
consumer.assign([tp]) ... | [
"You can use the end_offsets(partitions) function in that client to get the last offset for the partitions specified. Note that the returned offset is the next offset, that is the current end +1. Documentation here.\nEdit: Example implementation:\nfrom kafka import KafkaProducer, KafkaConsumer, TopicPartition\nfrom... | [
3,
1
] | [] | [] | [
"apache_kafka",
"python"
] | stackoverflow_0055831931_apache_kafka_python.txt |
Q:
Check for null values in if statement
I am very new to Python, and I wanted to ask a question about how to check the null values as condition in if statement. I am not sure how to construct the syntax. Hopefully someone can help me to solve the problem. Thank you so much, and wish you all have a wonderful day.
So ... | Check for null values in if statement | I am very new to Python, and I wanted to ask a question about how to check the null values as condition in if statement. I am not sure how to construct the syntax. Hopefully someone can help me to solve the problem. Thank you so much, and wish you all have a wonderful day.
So here is problem. I am working with a datafr... | [
"Use boolean indexing.\nE.g., something like:\ndf.loc[df['A'].notnull() & df['B'].notnull(), \"Avg\"] = (df['A'].astype(float) + df['B'].astype(float))/2\n\nAnd similarly for the other conditions.\n"
] | [
0
] | [] | [] | [
"if_statement",
"python"
] | stackoverflow_0074448912_if_statement_python.txt |
Q:
Enum member as a default value on signature
I know that assign a mutable object as a default value on function is bad practice.
Something like:
def foo(a = []):
pass
My question is assign a Enum member is also a bad practice?
Something like:
Class SomeEnum(Enum)
ENUM_KEY = SomeClass()
def foo(a = SomeEnum.... | Enum member as a default value on signature | I know that assign a mutable object as a default value on function is bad practice.
Something like:
def foo(a = []):
pass
My question is assign a Enum member is also a bad practice?
Something like:
Class SomeEnum(Enum)
ENUM_KEY = SomeClass()
def foo(a = SomeEnum.ENUM_KEY)
pass
| [
"Using an enum member as a default parameter is (usually) fine.\nThe value of an enum member is usually constant (such as 1, debug, or Monday), but it is possible to use a mutable value, such as an empty list. If you are going to mutate the value of the enum in the function, then you have the same risks as directl... | [
0
] | [] | [] | [
"enums",
"mutable",
"python"
] | stackoverflow_0074441625_enums_mutable_python.txt |
Q:
QDoubleSpinBox which accept dots and also commas as a decimal separator
I need a spinbox which accept dots and also commas as a decimal separator.
I've changed the Locale settings: self.setLocale(QLocale(QLocale.C))
Because of that, my spinbox accept a dot as a decimal separator. A comma also shows up on screen wh... | QDoubleSpinBox which accept dots and also commas as a decimal separator | I need a spinbox which accept dots and also commas as a decimal separator.
I've changed the Locale settings: self.setLocale(QLocale(QLocale.C))
Because of that, my spinbox accept a dot as a decimal separator. A comma also shows up on screen when the comma button is pressed, but it disappears after editing.
I've redefin... | [
"You should override validate() and valueFromText() methods instead, see https://stackoverflow.com/a/72054836/12108865\n"
] | [
0
] | [] | [] | [
"pyqt",
"pyqt5",
"python",
"python_3.x",
"qdoublespinbox"
] | stackoverflow_0057492304_pyqt_pyqt5_python_python_3.x_qdoublespinbox.txt |
Q:
How to create a large pandas dataframe from an sql query without running out of memory?
I have trouble querying a table of > 5 million records from MS SQL Server database. I want to select all of the records, but my code seems to fail when selecting to much data into memory.
This works:
import pandas.io.sql as ps... | How to create a large pandas dataframe from an sql query without running out of memory? | I have trouble querying a table of > 5 million records from MS SQL Server database. I want to select all of the records, but my code seems to fail when selecting to much data into memory.
This works:
import pandas.io.sql as psql
sql = "SELECT TOP 1000000 * FROM MyTable"
data = psql.read_frame(sql, cnxn)
...but this ... | [
"As mentioned in a comment, starting from pandas 0.15, you have a chunksize option in read_sql to read and process the query chunk by chunk: \nsql = \"SELECT * FROM My_Table\"\nfor chunk in pd.read_sql_query(sql , engine, chunksize=5):\n print(chunk)\n\nReference: http://pandas.pydata.org/pandas-docs/version/0.1... | [
73,
60,
18,
2,
2,
1,
0
] | [
"If you want to limit the number of rows in output, just use:\ndata = psql.read_frame(sql, cnxn,chunksize=1000000).__next__()\n\n"
] | [
-1
] | [
"bigdata",
"pandas",
"python",
"sql"
] | stackoverflow_0018107953_bigdata_pandas_python_sql.txt |
Q:
how to update pandas column multiple values based on another column
so I am creating a dummy data for a project, and I have a million row of this table:
you can see the sub-reason column contains NaN values all of it cz i'm creating this data. what I want is to put a value based on the Reason column:
if the Reas... | how to update pandas column multiple values based on another column | so I am creating a dummy data for a project, and I have a million row of this table:
you can see the sub-reason column contains NaN values all of it cz i'm creating this data. what I want is to put a value based on the Reason column:
if the Reason is 'Maintenance' I want to put a random value between: ['Indoor Connec... | [
"Did you try apply method? , it's probably faster\n df['Sub-Reason'] = df['Reason'].apply(\n lambda x: np.random.choice(list(subReason1)) if x=='Maintenance' \n else (np.random.choice(list(subReason2)) if x=='Connection' \nelse (np.random.choice(list(subReason3)) if x=='Billing' \nelse np.ran... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074449399_pandas_python.txt |
Q:
CMOS XOR propagation delay in Python
I have been struggling with something relatively simple but haven't yet figure out a good way to solve it.
I need to simulate, at a very high level, XOR gates. I have two streams of 0/1 and want to do piece-wise XOR and that's the easy bit. Now I wanted to add a limitation of r... | CMOS XOR propagation delay in Python | I have been struggling with something relatively simple but haven't yet figure out a good way to solve it.
I need to simulate, at a very high level, XOR gates. I have two streams of 0/1 and want to do piece-wise XOR and that's the easy bit. Now I wanted to add a limitation of real life CMOS XOR gates, simply the propag... | [
"For high level simulation, you could apply a time wheel. The time wheel has a fixed number of slots corresponding to multiples of a basic time unit (fractions of a nanosecond). Attached to each slot is a list of events scheduled for this time.\nAn event is a transition of an input or output line. The simulation al... | [
0
] | [] | [] | [
"python",
"xor"
] | stackoverflow_0074448797_python_xor.txt |
Q:
Tkinter OptionMenu cannot open a second time using space
I am having some trouble working around what I can only assume is a bug in Tkinter.
from tkinter import *
def refocus(event, obj):
obj.focus()
root = Tk()
options = ["Hello", "world", "How", "are", "you"]
v1 = StringVar()
v2 = StringVar()
v3 = StringVa... | Tkinter OptionMenu cannot open a second time using space | I am having some trouble working around what I can only assume is a bug in Tkinter.
from tkinter import *
def refocus(event, obj):
obj.focus()
root = Tk()
options = ["Hello", "world", "How", "are", "you"]
v1 = StringVar()
v2 = StringVar()
v3 = StringVar()
o1 = OptionMenu(root, v1, *options)
o1.configure(takefocu... | [
"Look at this:\nimport tkinter as tk\n\n\ndef open_option_menu(event):\n # Get the widget from the event that tkinter passed in\n obj = event.widget\n # Calculate the x/y position of the popup window\n x = obj.winfo_rootx()\n y = obj.winfo_rooty() + obj.winfo_height()\n # Show the popup window\n ... | [
3
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074393322_python_tkinter.txt |
Q:
How to run all functions in Module based one global variable?
Module.py:
def a_1()
print("a_1") if global_var !=True:
def a_2()
print("a_2")if global_var !=True:
def a_n()
print("a_n")if global_var !=True:
global_var =True
Program
from Module import *
global global_var =True
a_1() # should not print anything ... | How to run all functions in Module based one global variable? | Module.py:
def a_1()
print("a_1") if global_var !=True:
def a_2()
print("a_2")if global_var !=True:
def a_n()
print("a_n")if global_var !=True:
global_var =True
Program
from Module import *
global global_var =True
a_1() # should not print anything
If global_var == True then all function in module should be show ... | [] | [] | [
"You could just try doing an if statement\nglobal_var = True\ndef a_1():\n print(\"a_1\")\ndef a_2():\n print(\"a_2\")\ndef a_n():\n print(\"a_n\")\nif global_var:\n a_1()\n a_2()\n a_n()\n\n"
] | [
-1
] | [
"module",
"python",
"python_3.x"
] | stackoverflow_0074449550_module_python_python_3.x.txt |
Q:
how i can rotate an object by a specified angle in python or jypiter notebook?
enter image description here
I need to rotate object in python with this formula (enter image description here)
rotate an object by a specified angle.
A:
If you want to rotate an object, you are just changing the coordinates of the v... | how i can rotate an object by a specified angle in python or jypiter notebook? | enter image description here
I need to rotate object in python with this formula (enter image description here)
rotate an object by a specified angle.
| [
"If you want to rotate an object, you are just changing the coordinates of the vertices.\nYou can do this using matrix multiplication:\nimport numpy as np\n\ntheta = np.radians(int(input(\"How many radians? \")))\nc,s = np.cos(theta), np.sin(theta) #get sin and cosine of the angle\n\nrotate = np.array(((c, -s), (s,... | [
0,
0
] | [] | [] | [
"2d",
"anaconda",
"jupyter_notebook",
"numpy",
"python"
] | stackoverflow_0074433408_2d_anaconda_jupyter_notebook_numpy_python.txt |
Q:
Connect to Athena without access?
I need to connect to Athena using Python.
The code used is as follows:
import pyathena
import pandas as pd
athena_conn = pyathena.connect(access_key,
secret_key,
s3_staging_dir,
region_name)
df = pd.read_sql("SELECT * FROM db.t... | Connect to Athena without access? | I need to connect to Athena using Python.
The code used is as follows:
import pyathena
import pandas as pd
athena_conn = pyathena.connect(access_key,
secret_key,
s3_staging_dir,
region_name)
df = pd.read_sql("SELECT * FROM db.tableLIMIT 10", athena_conn)
df.head(5)
... | [
"From pyathena · PyPI documentation:\nfrom pyathena import connect\n\ncursor = connect(aws_access_key_id=\"YOUR_ACCESS_KEY_ID\",\n aws_secret_access_key=\"YOUR_SECRET_ACCESS_KEY\",\n s3_staging_dir=\"s3://YOUR_S3_BUCKET/path/to/\",\n region_name=\"us-west-2\").cursor(... | [
0,
0
] | [] | [] | [
"amazon_athena",
"amazon_web_services",
"pyathena",
"python",
"python_3.x"
] | stackoverflow_0074280663_amazon_athena_amazon_web_services_pyathena_python_python_3.x.txt |
Q:
How to optimize the code and reduce memory usage Python
The purpose is to reduce memory usage.
Meaning that it should be optimized in a way that the hash is equal to the test hash.
What I've tried so far:
Adding __slots__ but it didn't make any changes.
Change default dtype float64 to float32. Although it reduces... | How to optimize the code and reduce memory usage Python | The purpose is to reduce memory usage.
Meaning that it should be optimized in a way that the hash is equal to the test hash.
What I've tried so far:
Adding __slots__ but it didn't make any changes.
Change default dtype float64 to float32. Although it reduces the mem usage significantly, it brakes the test by changing ... | [
"If you avoid pd.concat() and use the preferred way of augmenting dataframes:\ndf[\"new_col_name\"] = new_col_data\n\nthis will reduce peak memory consumption significantly.\n\nIn your code it is sufficient to fix the Transform class:\nclass Transform:\n \"\"\"adding a column of random data\"\"\"\n __slots__ ... | [
3
] | [] | [] | [
"dataframe",
"numpy",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074407024_dataframe_numpy_pandas_python_python_3.x.txt |
Q:
AttributeError: can't set attribute for workbook
So I have the followiing code where I am writing to an already existing excel file:
book = load_workbook(file_path)
writer = pd.ExcelWriter(file_path, engine = 'openpyxl')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
I am gettin... | AttributeError: can't set attribute for workbook | So I have the followiing code where I am writing to an already existing excel file:
book = load_workbook(file_path)
writer = pd.ExcelWriter(file_path, engine = 'openpyxl')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
I am getting an error at line
writer.book = book as
writer.book =... | [
"I have found that the key is to use writer.workbook instead of writer.book in code here: \nwriter.workbook = openpyxl.load_workbook('test.xlsx') \nand to add options in: \npd.ExcelWriter( ... , mode='a', if_sheet_exists='overlay')\nimport pandas as pd\nimport openpyxl\nimport warnings\n\nwarnings.simplefilter... | [
2,
1,
0
] | [] | [] | [
"dataframe",
"excel",
"openpyxl",
"pandas",
"python"
] | stackoverflow_0073915662_dataframe_excel_openpyxl_pandas_python.txt |
Q:
Regrouping pandas dataframe
How can I make this dataframe:
datecreated timestamp value
2022-11-15 1 4000
2022-11-15 2 3900
2022-11-15 3 3850
2022-11-15 4 3810
2022-11-15 5 3790
to become:
datecreated 1 2 3 4 5
0 2022-11-15 4... | Regrouping pandas dataframe | How can I make this dataframe:
datecreated timestamp value
2022-11-15 1 4000
2022-11-15 2 3900
2022-11-15 3 3850
2022-11-15 4 3810
2022-11-15 5 3790
to become:
datecreated 1 2 3 4 5
0 2022-11-15 4000 3900 3850 3810 3790
I t... | [
"What you're seeing is just the column's axis name being automatically set to timestamp because of your pivot. This can be remedied by renaming the axis:\nout = (df.pivot(index='datecreated', \n columns='timestamp', \n values='value')\n .reset_index()\n .rename_axis(col... | [
2
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074449211_pandas_python.txt |
Q:
How to add a Table to Excel Worksheet using openpyxl
I'm trying to add a table to an Excel worksheet using openpyxl.
I know how to add a dataframe to a Worksheet, and it works great. Here's my sample code:
import pandas as pd
from openpyxl import Workbook
from openpyxl.utils.dataframe import dataframe_to_rows
df ... | How to add a Table to Excel Worksheet using openpyxl | I'm trying to add a table to an Excel worksheet using openpyxl.
I know how to add a dataframe to a Worksheet, and it works great. Here's my sample code:
import pandas as pd
from openpyxl import Workbook
from openpyxl.utils.dataframe import dataframe_to_rows
df = pd.DataFrame({
'name': ['Lorem', 'Ipsum', 'Dolor', '... | [
"Well, for task one, I figured out a way. I'm not sure if it's the right way, but here it goes:\nimport pandas as pd\n\nfrom openpyxl import Workbook\n# Additional imports:\nfrom openpyxl.utils import get_column_letter\nfrom openpyxl.utils.dataframe import dataframe_to_rows\n\ndf = pd.DataFrame({\n 'name': ['Lor... | [
0
] | [] | [] | [
"excel",
"excel_tables",
"openpyxl",
"pandas",
"python"
] | stackoverflow_0074449800_excel_excel_tables_openpyxl_pandas_python.txt |
Q:
How I end a loop for not sum first and last number as a pair?
I've got everything working correctly except this one problem - with the third output it says the max pair sum is 13 due to taking sum of the first and last number. It should be 11 (as 9+2 or 4+7). I can't figure it out how I fix this problem - ending t... | How I end a loop for not sum first and last number as a pair? | I've got everything working correctly except this one problem - with the third output it says the max pair sum is 13 due to taking sum of the first and last number. It should be 11 (as 9+2 or 4+7). I can't figure it out how I fix this problem - ending the loop with the first and last position.
Thank you for all advice.... | [
"in your solution, for first element value of j is [-1, 0] beacuse of this it is taking 4 and adding with 0th index element and making their sum as max value. you need to fix it by starting from index 1. A simple way to do that is below\ndef _sum(num_list): \n maxSum = -9999999\n for i in range(1, len(num_lis... | [
0,
0
] | [] | [] | [
"loops",
"max",
"neighbours",
"python",
"sum"
] | stackoverflow_0074449591_loops_max_neighbours_python_sum.txt |
Q:
Is there an alternative way to install dependencies for an Alexa Skill (requirements.txt is troublesome)?
I'm trying to develop an Alexa Skill which uses MechanicalSoup to scrape some data from a web search. My code works but I'm unable to install MechanicalSoup via the 'requirements.txt' file. I've even added all... | Is there an alternative way to install dependencies for an Alexa Skill (requirements.txt is troublesome)? | I'm trying to develop an Alexa Skill which uses MechanicalSoup to scrape some data from a web search. My code works but I'm unable to install MechanicalSoup via the 'requirements.txt' file. I've even added all of MechanicalSoup's dependencies, like so:
boto3==1.9.216
ask-sdk-core==1.11.0
requests==2.25.1
beautifulsoup4... | [
"Maybe:\n\nyour requirements.txt doesn't work? you could try to pip install -r requirements.txt on your computer, to see if the requirements actually work\nYour build server builds with a different version of python then your computer? for example, you could have python 3.10, while alexa has python 2.7\n\n"
] | [
1
] | [] | [] | [
"alexa",
"alexa_skills_kit",
"pip",
"python",
"requirements.txt"
] | stackoverflow_0074449543_alexa_alexa_skills_kit_pip_python_requirements.txt.txt |
Q:
How to plot perform linear regression analysis on a simple data set
I am writing a simple Python program to analyze a data set using linear regression. The program is constructed like so
# Author: Evan Gertis
# Date 11/15
# program: linear regression
import pandas as pd
import seaborn as sns
import matplotlib.pyp... | How to plot perform linear regression analysis on a simple data set | I am writing a simple Python program to analyze a data set using linear regression. The program is constructed like so
# Author: Evan Gertis
# Date 11/15
# program: linear regression
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import logging
logging.basicConfig(level=lo... | [
"Assuming that the csv file has exactly the same format you shown in the question and that the first column represents the independent variable, while the second one is the dependent:\n# few libraries\nimport pandas as pd\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom scipy import stats\n\n#read th... | [
1
] | [] | [] | [
"numpy",
"python",
"statistics"
] | stackoverflow_0074446087_numpy_python_statistics.txt |
Q:
not supported between instances of 'Button' and 'int' tkinter
im making a guess number game but i have a problem:In general, I would like to say how the process of the program is like this: the user first enters the number and clicks the registration option,The second user should try to guess what the number is in... | not supported between instances of 'Button' and 'int' tkinter | im making a guess number game but i have a problem:In general, I would like to say how the process of the program is like this: the user first enters the number and clicks the registration option,The second user should try to guess what the number is in a specific number, but my problem is that if I want to create a wh... | [
"In the beginning, your code sets sum_1 to an integer (0). You later make a button and set the same variable to that button. The gusses() function expects sum_1 to be an integer, so the button should probably have a different name.\n",
"sum_1 is an Button object. You are trying to compare it to an integer. This i... | [
3,
2
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074449698_python_tkinter.txt |
Q:
Solving a tridiagonal matrix in python
I have been looking at numerical methods to solve differential equations for chemical reactions. Usually I put the differential equation into a tridiagonal matrix using finite difference method, and then using a column vector for the boundary conditions. Once I have the matri... | Solving a tridiagonal matrix in python |
I have been looking at numerical methods to solve differential equations for chemical reactions. Usually I put the differential equation into a tridiagonal matrix using finite difference method, and then using a column vector for the boundary conditions. Once I have the matrix and vector I use scipy's linalg. However ... | [
"So I decided to use newton method for a system of equations to solve this problem, as recommended by @LutzLehmann.'J' is the Jacobian matrix and f is original matrix. This is not very efficient code but it got the job done.\nguess = np.array([4,4,4,4,4,4,4,4,4,4,4])\nfor i in range(10):\n J = np.array([[-20003... | [
0
] | [] | [] | [
"finite_difference",
"linear_algebra",
"numerical_methods",
"python",
"scipy"
] | stackoverflow_0074391184_finite_difference_linear_algebra_numerical_methods_python_scipy.txt |
Q:
How to update records to their parent record's values on multiple conditions?
Let's say I have a dataframe like this:
import pandas as pd
df = pd.DataFrame([[1,2,3,"P", 1, "A", "SOMETHING"],
[1,2,3,"C", 0, "B", "NOTHING"],
[1,2,3,"C", 0, "B", "SOMETHING"],
[4,... | How to update records to their parent record's values on multiple conditions? | Let's say I have a dataframe like this:
import pandas as pd
df = pd.DataFrame([[1,2,3,"P", 1, "A", "SOMETHING"],
[1,2,3,"C", 0, "B", "NOTHING"],
[1,2,3,"C", 0, "B", "SOMETHING"],
[4,5,6,"P", 1, "A", "SOMETHING"],
[4,5,6,"C", 1, "A", "NOTHING"]],
... | [
"You can avoid sorting the dataframe, and create a dictionary of key values for the parent ids and then modify the data field to update children accordingly while respecting the conditions, the code to achieve this would look like this :\nimport pandas as pd\n\ndf = pd.DataFrame([[1,2,3,\"P\", 1, \"A\", \"SOMETHING... | [
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074448975_pandas_python.txt |
Q:
How can I make each Thread to join in python?
Let me describe an example:
import time
import threading
def some_heavy_function():
pass
while True:
t1 = threading.Thread(target=some_heavy_function, args=(,))
t2 = threading.Thread(target=some_heavy_function, args=(,))
t3 = threading.Thread(target=s... | How can I make each Thread to join in python? | Let me describe an example:
import time
import threading
def some_heavy_function():
pass
while True:
t1 = threading.Thread(target=some_heavy_function, args=(,))
t2 = threading.Thread(target=some_heavy_function, args=(,))
t3 = threading.Thread(target=some_heavy_function, args=(,))
t1.start()
t... | [
"You need some kind of control structure (a dictionary is ideal) wherein you can monitor the state of your threads.\nFor each thread you need to make a note of when it started. In that way you can determine how long it's been running.\nYou can use Thread.is_alive() to determine the state of your threads.\nHere, the... | [
3
] | [] | [] | [
"multithreading",
"python",
"python_multithreading"
] | stackoverflow_0074449194_multithreading_python_python_multithreading.txt |
Q:
add prefix from sub-directory to the name of file
Can You give me tips how I can add to copied files name the prefix comes from name of sub-directory for example
this is my source dir '/home/ip/input/IP10/STAT-IP_202211151610_7428/some_files'
import os
import glob
import shutil
for f in glob.glob('/opt/data/input... | add prefix from sub-directory to the name of file | Can You give me tips how I can add to copied files name the prefix comes from name of sub-directory for example
this is my source dir '/home/ip/input/IP10/STAT-IP_202211151610_7428/some_files'
import os
import glob
import shutil
for f in glob.glob('/opt/data/input/IP10/**/*.*', recursive=True):
shutil.copy(f, '/o... | [
"This might help:\nimport os, glob, shutil\n\nrootpath = os.path.join(\"..\", \"Desktop\", \"*\")\n\nfor f in glob.glob(os.path.join(rootpath, 'IP10/**/*.*'), recursive=True):\n last_two = os.path.join(*f.split(os.sep)[-2:]) # get two last path items. I.e. dir/file.txt\n shutil.copy(f, os.path.join(rootpath, ... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074449077_python.txt |
Q:
what is the error in my sorting algorithm?
I am trying to make a sorting algorithm using python, but I am encountering a problem and I can't figure it out. I'll paste my code below.
basic function:
gets an array of numbers
goes through and checks if a number is bigger than the next one
if it is, swap it and set a... | what is the error in my sorting algorithm? | I am trying to make a sorting algorithm using python, but I am encountering a problem and I can't figure it out. I'll paste my code below.
basic function:
gets an array of numbers
goes through and checks if a number is bigger than the next one
if it is, swap it and set a variable to tell the function to run again
at t... | [
"First, you need to actually call your sort() function:\nprint(mainArr) # print the unsorted list\nprint()\nsort() # sort the list\nprint()\nprint(mainArr) # print the sorted list\n\nThis gets you an error:\n for x in range(0, mainArr.len - 1):\nAttributeError: 'list' object has no attribute 'len'\n\n... | [
1,
0
] | [] | [] | [
"python",
"sorting"
] | stackoverflow_0074449778_python_sorting.txt |
Q:
Is there A Way To Format Serialized Response for Groups and their Permissions in Django Rest Framework?
I created an API endpoint in which I am sending a JSON data. to create a group and then assigned permission to the models (e.g add_user, change_user etc) programmatically.
It works fine.
The issue now is that I ... | Is there A Way To Format Serialized Response for Groups and their Permissions in Django Rest Framework? | I created an API endpoint in which I am sending a JSON data. to create a group and then assigned permission to the models (e.g add_user, change_user etc) programmatically.
It works fine.
The issue now is that I will like to format data retrieved in the same format I sent it in
This is for the Django's inbuilt Group, Pe... | [
"In Serializer there is a method called to_represetation you can override the Response\ndef to_representation(self, instance):\n response = super().to_representation(instance)\n # response is the dictionary you can overwrite it accordingly\n\n \n return response\n\n"
] | [
0
] | [] | [] | [
"django",
"django_rest_framework",
"django_serializer",
"python"
] | stackoverflow_0074448879_django_django_rest_framework_django_serializer_python.txt |
Q:
How to scrape the speech of president to dataframe?
I want to web scrape the following website: https://www.assemblee-nationale.fr/12/cri/2003-2004/20040001.asp#TopOfPage .
Here is an example of the HTML:
<html>
<body>
<div align="center">
<p align="JUSTIFY">
<strong></strong>
<strong> M. le présiden... | How to scrape the speech of president to dataframe? | I want to web scrape the following website: https://www.assemblee-nationale.fr/12/cri/2003-2004/20040001.asp#TopOfPage .
Here is an example of the HTML:
<html>
<body>
<div align="center">
<p align="JUSTIFY">
<strong></strong>
<strong> M. le président </strong>
Conformément...
<br>
Mes chers...... | [
"EDIT\nThanks to your comments, so lets try the other way around and decompose() all empty <strong>\nfor tag in soup.select('strong'):\n if len(tag.get_text(strip=True)) == 0:\n tag.decompose()\n\nThan iterate each <strong> next_siblings and break if one of them is a <strong>:\nfor e in soup.select('p[ali... | [
1
] | [] | [] | [
"beautifulsoup",
"html",
"pandas",
"python",
"web_scraping"
] | stackoverflow_0074448199_beautifulsoup_html_pandas_python_web_scraping.txt |
Q:
Transform 3D points to 2D plot
I have a data-set of 3D points (x,y,z) projected onto a plane and i'd like to transform them into a simple 2D plot by looking at the points from an orthogonal direction to that plane. Any python explanation are much appreciated!
A:
You can use this :
import pylab
from mpl_toolkits.... | Transform 3D points to 2D plot | I have a data-set of 3D points (x,y,z) projected onto a plane and i'd like to transform them into a simple 2D plot by looking at the points from an orthogonal direction to that plane. Any python explanation are much appreciated!
| [
"You can use this :\nimport pylab\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom mpl_toolkits.mplot3d import proj3d\nfig = pylab.figure()\nax = fig.add_subplot(111, projection = '3d')\nx = y = z = [1, 2, 3]\nsc = ax.scatter(x,y,z)\n\n##################### \nx2, y2, _ = proj3d.proj_transform(1, 1, 1, ax.get_proj(... | [
0,
0
] | [] | [] | [
"geometry",
"plot",
"python"
] | stackoverflow_0074444850_geometry_plot_python.txt |
Q:
run function to element of inner list of a nest list and append the output while maintaining the nested list structure
I have a list of dictionary which I will be using the the key and values to pass as parameter of a function. The function does some calculation to these key and values. What I want to achieve is t... | run function to element of inner list of a nest list and append the output while maintaining the nested list structure | I have a list of dictionary which I will be using the the key and values to pass as parameter of a function. The function does some calculation to these key and values. What I want to achieve is this:
dList = [{k1:v1, k2:v2, k3:v3}, {k4:v4, k5:v5}, {k6:v6 k7:v7,k8:v8}]
finalList = [[kv1, kv2, kv3], [kv4,kv5], [kv6,kv7... | [
"You need to create an inner list each time through the outer loop. You append the results of the function to that list, and then append that list to the final result.\nfinalList = []\nfor d in dList:\n innerList = []\n for k, v in d.items():\n innerList.append(setupTime(k, v))\n finalList.append(in... | [
1
] | [] | [] | [
"dictionary",
"loops",
"nested_lists",
"python"
] | stackoverflow_0074449814_dictionary_loops_nested_lists_python.txt |
Q:
Printing first letter of full name python
Hello I'm trying to create a program that takes input and prints out the initials all uppercase but I can't figure out why my program is only printing the first letter of the last item of the list after string is split
this is my code:
full_name = input("Please enter your ... | Printing first letter of full name python | Hello I'm trying to create a program that takes input and prints out the initials all uppercase but I can't figure out why my program is only printing the first letter of the last item of the list after string is split
this is my code:
full_name = input("Please enter your full name: ")
name = full_name.split()
for it... | [
"You can make a new, empty variable like initials and add the first letter to it\nfull_name = input(\"full name: \")\n\nname = full_name.split()\n\ninitials = \"\"\n\nfor item in name:\n initials += item[0].upper()\n\nprint(initials)\n\n",
"I think this can help you:\n# get the full name from the user\nfull_na... | [
1,
1
] | [] | [] | [
"for_loop",
"input",
"methods",
"python",
"split"
] | stackoverflow_0074449437_for_loop_input_methods_python_split.txt |
Q:
Find optimal (smallest) convex hull around a portion of a large dataset in Python
I have many (x, y) points. I want to fit the smallest (or an approximation or estimation of the smallest) convex hull around a variable percentage of those points.
The existing implementations I can find get the convex hull around al... | Find optimal (smallest) convex hull around a portion of a large dataset in Python | I have many (x, y) points. I want to fit the smallest (or an approximation or estimation of the smallest) convex hull around a variable percentage of those points.
The existing implementations I can find get the convex hull around all the points. How can I have a function like so:
def get_convec_hull(points, percentage... | [
"Please realize I am risking my life posting this; I am fairly certain actual computer scientists are already tracing my IP.\nI have rewritten your function in the following manner:\ndef get_suboptimal_hull(points,p,magic_number):\n n_points = points.shape[0]\n tp = int(n_points * p)\n \n d_mat = distan... | [
1
] | [] | [] | [
"convex_hull",
"convex_optimization",
"numpy",
"python"
] | stackoverflow_0074429734_convex_hull_convex_optimization_numpy_python.txt |
Q:
How to count duplicate rows in pandas dataframe where the order of the column values is not important?
I wonder if we can extend the logic of How to count duplicate rows in pandas dataframe?, so that we also consider rows which have similar values on the columns with other rows, but the values are unordered.
Imagi... | How to count duplicate rows in pandas dataframe where the order of the column values is not important? | I wonder if we can extend the logic of How to count duplicate rows in pandas dataframe?, so that we also consider rows which have similar values on the columns with other rows, but the values are unordered.
Imagine a dataframe like this:
fruit1 fruit2
0 apple banana
1 cherry orange
3 apple banana
4 ba... | [
"You can directly re-assign the np.sort values like so, then use value_counts():\nimport numpy as np\n\ndf.loc[:] = np.sort(df, axis=1)\nout = df.value_counts().reset_index(name='occurences')\nprint(out)\n\nOutput:\n fruit1 fruit2 occurences\n0 apple banana 3\n1 cherry orange 1\n\n",
... | [
2,
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074449578_pandas_python.txt |
Q:
Finding neighbors in a matrix and storing those neighbors in a new matrix
What I have is a matrix of characters that looks like this:
matrix = [
['-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-'],
['-', '-', '-', '+', '-', '-', '-', '+', '-', '-', '-', '+',... | Finding neighbors in a matrix and storing those neighbors in a new matrix | What I have is a matrix of characters that looks like this:
matrix = [
['-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-'],
['-', '-', '-', '+', '-', '-', '-', '+', '-', '-', '-', '+', '-', '-', '+', '-', '-', '-', '-', '-'],
['-', '-', '-', '-', '-', '-', '-... | [
"If you are working with list, and you want to append all neighbour to the neighbours you could do like this, in any case I wrote a more general code, that you could edit easily based on what you want.\ndef getNeighbours(matrix):\n m , n = len(matrix), len(matrix[0])\n neighbourMatrix = [['' for j in range(n... | [
0
] | [] | [] | [
"matrix",
"neighbours",
"python"
] | stackoverflow_0074449111_matrix_neighbours_python.txt |
Q:
Im having difficulty utilizing an array in python
I'm trying to manipulate text from a word file however when I save it to an array of classes, all the indexes are being overwritten instead of the one particular index I intend to change.
for line in modified:
if line.startswith('Date'):
output.append(line... | Im having difficulty utilizing an array in python | I'm trying to manipulate text from a word file however when I save it to an array of classes, all the indexes are being overwritten instead of the one particular index I intend to change.
for line in modified:
if line.startswith('Date'):
output.append(line)
list2=line.split(' ')
work.date=list2[1]
#... | [
"Every index in the daylist array references the same work object. When you change an attribute of work (e.g. work.date) it's reflected in all references to that single object. You want each index to reference a separate, independent object but that's not what the code is doing.\nTry something like this where work ... | [
0
] | [] | [] | [
"arrays",
"list",
"python",
"variable_assignment"
] | stackoverflow_0074449452_arrays_list_python_variable_assignment.txt |
Q:
AWS CDK - ImportError: cannot import name 'AssetManifestOptions' from 'aws_cdk.cloud_assembly_schema'
When trying to synthesize my CDK app, I receive the following error:
`
Traceback (most recent call last):
File "C:\Users\myusername\PycharmProjects\rbds-cdk_testing\app.py", line 2, in <module>
from aws_cdk.... | AWS CDK - ImportError: cannot import name 'AssetManifestOptions' from 'aws_cdk.cloud_assembly_schema' | When trying to synthesize my CDK app, I receive the following error:
`
Traceback (most recent call last):
File "C:\Users\myusername\PycharmProjects\rbds-cdk_testing\app.py", line 2, in <module>
from aws_cdk.core import App, Environment
File "C:\Users\myusername\PycharmProjects\rbds-cdk_testing\.venv\lib\site-pa... | [
"Its the same here, I think the issue can be in wrong package version.\ncloud-assembly-schema==2.50.0 contains AssetManifestOptions.\nCan you please paste here output of\npip list -v | grep aws\nIam able to install 2.50.0, however it depends on other packages of the same version (see attach)\n\nAnd I cant set up co... | [
0
] | [] | [] | [
"amazon_web_services",
"aws_cdk",
"node.js",
"npm",
"python"
] | stackoverflow_0074355962_amazon_web_services_aws_cdk_node.js_npm_python.txt |
Q:
Lock in Asyncio
I'm trying to use Lock in Asyncio to prevent the function method() to run "more that ones at the same time".
My motivation:
I use the Asyncio library for asynchronous communication with multiple devices. The issue is, that the devices need some time to respond and if other request is send in the me... | Lock in Asyncio | I'm trying to use Lock in Asyncio to prevent the function method() to run "more that ones at the same time".
My motivation:
I use the Asyncio library for asynchronous communication with multiple devices. The issue is, that the devices need some time to respond and if other request is send in the meantime to the same de... | [
"Change code the following way and it will work:\nimport asyncio\n\n\nasync def method(wait: int, locker: asyncio.Lock):\n async with locker:\n print(f\"Method with waiting {wait}s starting\")\n await asyncio.sleep(wait)\n print(f\"Method with waiting {wait}s finished\")\n\n\nasync def main(... | [
0
] | [] | [] | [
"locking",
"python",
"python_asyncio"
] | stackoverflow_0074438347_locking_python_python_asyncio.txt |
Q:
how to write exif tags with Python in a self generated image
I have generated an image with pillow and now I want to add metadata to the image.
In my image it didn't have a data structure yet, I suppose I have to create one first but how do I do that?
Reading or changing tags from existing images with exif data st... | how to write exif tags with Python in a self generated image | I have generated an image with pillow and now I want to add metadata to the image.
In my image it didn't have a data structure yet, I suppose I have to create one first but how do I do that?
Reading or changing tags from existing images with exif data structure is very easy with the "exif" tool.
Every hint is welcome.
... | [
"from PIL import Image, PngImagePlugin\n\n#path to image file\nfile = \"myimage.png\"\n\n#create the metadata object\npngMetaData = PngImagePlugin.PngInfo()\n\n#add the data\npngMetaData.add_text('key 1', 'value 1')\npngMetaData.add_text('key 2', 'value 2')\n\n#open the image file and save the metadata\nwith Image.... | [
0
] | [] | [] | [
"exif",
"generated",
"python",
"python_imaging_library",
"self"
] | stackoverflow_0071560052_exif_generated_python_python_imaging_library_self.txt |
Q:
When does Dash release memory?
I wrote a python Dash app and made it available within my organization using OpenShift. I’m not really knowledgeable about OpenShift but it seems to be running correctly, including when multiple users are involved.
My problem is with memory management. Each time a user initiates a ne... | When does Dash release memory? | I wrote a python Dash app and made it available within my organization using OpenShift. I’m not really knowledgeable about OpenShift but it seems to be running correctly, including when multiple users are involved.
My problem is with memory management. Each time a user initiates a new session, the memory used by Dash a... | [
"How much memory are you allocating to the container? Also, does the memory continually go up? Or once it reaches a certain level does it plateau? Are you tracking any GC behavior in Python?\nI'm not an expert on Python memory management, and know nothing about Dash, but Python does manage its own memory heap and h... | [
0,
0
] | [] | [] | [
"openshift",
"plotly_dash",
"python"
] | stackoverflow_0070220228_openshift_plotly_dash_python.txt |
Q:
Extract images of people in call from Google Meets recording
I want to extract the individual persons from the video screenshot as an image.
So from this frame I want 5 images, which I'll export as 1.jpg, 2.jpg ..., 5.jpg, by creating bounding boxes for each box of video.
zoom conference example.
How would you tac... | Extract images of people in call from Google Meets recording | I want to extract the individual persons from the video screenshot as an image.
So from this frame I want 5 images, which I'll export as 1.jpg, 2.jpg ..., 5.jpg, by creating bounding boxes for each box of video.
zoom conference example.
How would you tackle this? I need a robust method.
Is there any fast simple method ... | [
"Your thresholding result looks fine to me. findContours() plus boundingRect() would clean up the black parts of each camera view. contourArea() could be used to reject small white parts from becoming their own camera view.\nSo, for example, here's how to run findContours():\n# This is your post-thresholding image\... | [
3
] | [] | [] | [
"computer_vision",
"google_meet",
"image_processing",
"opencv",
"python"
] | stackoverflow_0074449285_computer_vision_google_meet_image_processing_opencv_python.txt |
Q:
'RuntimeWarning: coroutinge "main" was never awatied' error when creating cogs
I am trying to learn discord.py v2.0 but I just cant figure out how I am supposed to use cogs and slash commands at the same time. I am trying to look at a realesed example of slash commands (https://github.com/Rapptz/discord.py/tree/ma... | 'RuntimeWarning: coroutinge "main" was never awatied' error when creating cogs | I am trying to learn discord.py v2.0 but I just cant figure out how I am supposed to use cogs and slash commands at the same time. I am trying to look at a realesed example of slash commands (https://github.com/Rapptz/discord.py/tree/master/examples/app_commands) and just try to mix it up so it works with cogs but I ca... | [
"When using your code, I didn't have the same error. But changing\nasync def setup(bot):\n await bot.add_cog(bot)\n\nwith\nasync def setup(bot):\n await bot.add_cog(events(bot))\n\nworked for me.\n"
] | [
1
] | [] | [] | [
"discord",
"discord.py",
"python",
"python_asyncio"
] | stackoverflow_0074449120_discord_discord.py_python_python_asyncio.txt |
Q:
Save keras model for production mode without Tensorflow
I want to save a trained keras model so that it can be used in the django rest backend of an application.
I did a lot of research but it seems there is no way to use these models without tensorflow installed.
So, what is the use of this storage? I don't want ... | Save keras model for production mode without Tensorflow | I want to save a trained keras model so that it can be used in the django rest backend of an application.
I did a lot of research but it seems there is no way to use these models without tensorflow installed.
So, what is the use of this storage? I don't want to install a heavy library like tensorflow on the server.
I t... | [] | [] | [
"you do not need to use Tensorflow in production you can use coefficient by replacing what random functions in your programming language.\nSample: Input array time coefficients matrixes, unboxed system inputs to output with feedback system in the box containers.\ntemp = tf.random.normal([10], 1, 0.2, tf.float32)\nt... | [
-2
] | [
"keras",
"python",
"tensorflow"
] | stackoverflow_0074450055_keras_python_tensorflow.txt |
Q:
Concatenate dataframes without doubling columns number
I am trying to concatenate DF1:
datecreated 1 2 3 4 5 ... 331 332 333 334 335 336
0 2022-11-14 4000 3900 3850 3810 3790 ... 5520 5300 5180 4990 4730 4520
with DF2:
datecreated 1 2 3 ... ... | Concatenate dataframes without doubling columns number | I am trying to concatenate DF1:
datecreated 1 2 3 4 5 ... 331 332 333 334 335 336
0 2022-11-14 4000 3900 3850 3810 3790 ... 5520 5300 5180 4990 4730 4520
with DF2:
datecreated 1 2 3 ... 333 334 335 336
0 2022-11-15 4000 3... | [
"I don't appear to be able to reproduce your issue... but to give a guess, I'd bet columns names are integers in one, and strings in the other:\nGiven:\n# df1\n datecreated 1 2 3 4 5\n0 2022-11-14 4000 3900 3850 3810 3790\n\n# df2\n datecreated 1 2 3\n0 2022-11-15 ... | [
2
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074450056_pandas_python.txt |
Q:
How to Remove only Digit with Parentheses () from String in Python Pandas?
I want to remove Digits with Parentheses () from string using regex in Python
Example : Hello World(4353)
Output: Hello World
Example : Hello World(ABC)
Output : Hello World(ABC)
I tried this reg but not working Perfectly...
s = "Satbaulia... | How to Remove only Digit with Parentheses () from String in Python Pandas? | I want to remove Digits with Parentheses () from string using regex in Python
Example : Hello World(4353)
Output: Hello World
Example : Hello World(ABC)
Output : Hello World(ABC)
I tried this reg but not working Perfectly...
s = "Satbaulia Khurd(159ds)"
# pattern=r"([\d ]*(\(\d+\))?[\d ])"
pattern= r'\([^()]*\)'
res ... | [
"As suggested by Quang Hoang in comments '\\(\\d+\\)' is a valid regex. That is the code I written based on your examples.\nimport re\nstring = \"Hello World(12345)\"\npattern = re.sub(r'\\(\\d+\\)', '', string)\n# Hello World(ABC) -> Hello World(ABC)\n\nprint(pattern)\n\n"
] | [
1
] | [] | [] | [
"pandas",
"python",
"regex"
] | stackoverflow_0074447967_pandas_python_regex.txt |
Q:
How to edit message with button | discord.py
I am trying to do button, that editing message, but this button doesn't work.
class Buttons(discord.ui.View):
def __init__(self, *, timeout=180):
super().__init__(timeout=timeout)
@discord.ui.button(label="Button",style=discord.ButtonStyle.gray)
asyn... | How to edit message with button | discord.py | I am trying to do button, that editing message, but this button doesn't work.
class Buttons(discord.ui.View):
def __init__(self, *, timeout=180):
super().__init__(timeout=timeout)
@discord.ui.button(label="Button",style=discord.ButtonStyle.gray)
async def blurple_button(self,button:discord.ui.Button... | [
"Your callback's arguments are the wrong way around. The first one is supposed to be the Interaction, and the second the Button.\nYour error message should also tell you this, though. You may not have configured logging properly.\n"
] | [
0
] | [] | [] | [
"discord.py",
"python"
] | stackoverflow_0074449291_discord.py_python.txt |
Q:
Set python system path to project root directory: can not use absolute imports this way
If I have a project with the following structure:
.
├── another_sub_dir
└── sub_dir
├── random_module.py
└── script.py
The project has two subdirectories. When I run my script.py from my root folder with the command py... | Set python system path to project root directory: can not use absolute imports this way | If I have a project with the following structure:
.
├── another_sub_dir
└── sub_dir
├── random_module.py
└── script.py
The project has two subdirectories. When I run my script.py from my root folder with the command python sub_dir/script.py and print the sys.path it prints the sub_dir as path. So Users/me/pro... | [
"As I said in the comments, you want to make sub_dir a package. You can do this by adding a file called __init__.py to it. You want your structure to look like\n.\n├── another_sub_dir\n└── sub_dir\n ├── __init__.py\n ├── random_module.py\n └── script.py\n\nYou can then run python sub_dir/script.py from the... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074435684_python.txt |
Q:
How to know the middle trajectory of ode solver in python
I am using Python package to solve ODE equation. However, I need to know the middle state or in other words the trajectory of ode solver in python.
from scipy.integrate import odeint
solution = odeint(fun,initial_values,tspan)
Here the output just gives... | How to know the middle trajectory of ode solver in python | I am using Python package to solve ODE equation. However, I need to know the middle state or in other words the trajectory of ode solver in python.
from scipy.integrate import odeint
solution = odeint(fun,initial_values,tspan)
Here the output just gives me me the final state, not the middle steps, How can I get the... | [
"The third parameter of odeint is the set of time values at which you want the solution to be returned. In your case, put the desired times in your tspan argument. E.g. tspan = np.linspace(0, 1, 101) will get you the solution at t=0.0, 0.01, 0.02, ..., 0.99, 1.0. Take another look at the example in the docstring,... | [
0
] | [] | [] | [
"differential_equations",
"math",
"ode",
"python",
"scipy"
] | stackoverflow_0074446781_differential_equations_math_ode_python_scipy.txt |
Q:
Unable to install http module
My Ubuntu server version is 22.04 and Python is 3.10.6.
And the pip version is 22.0.2
pip install htttp
The above command was entered to install the http module, but an error occurred.
Collecting http
Downloading http-0.02.tar.gz (32 kB)
Preparing metadata (setup.py) ... error
error:... | Unable to install http module | My Ubuntu server version is 22.04 and Python is 3.10.6.
And the pip version is 22.0.2
pip install htttp
The above command was entered to install the http module, but an error occurred.
Collecting http
Downloading http-0.02.tar.gz (32 kB)
Preparing metadata (setup.py) ... error
error: subprocess-exited-with-error
× py... | [
"Python3 contains http package by default.\nYou don't need to install it.\nJust do import http at your script, it will run fine.\n"
] | [
2
] | [
"I had the same problem.\nI found the solution in this post. Install pip2 and python2. Then, type:\n\npip2 install http\n\nSo I think, this is the only way.\n"
] | [
-1
] | [
"pip",
"python"
] | stackoverflow_0074258055_pip_python.txt |
Q:
I want to make place to collect all path of folder
This is my code.
folder_out = []
for a in range(1,80):
folder_letter = "/content/drive/MyDrive/project/Dataset/data/"
folder_out[a] = os.path.join(folder_letter, str(a))
folder_out.append(folder_out[a])
and this is an error
and this what I want
A:
... | I want to make place to collect all path of folder | This is my code.
folder_out = []
for a in range(1,80):
folder_letter = "/content/drive/MyDrive/project/Dataset/data/"
folder_out[a] = os.path.join(folder_letter, str(a))
folder_out.append(folder_out[a])
and this is an error
and this what I want
| [
"You are using the os method wrong, you want to use os.listdir(Your directory here) to get a list of all directories\nimport os\n\ndir = os.listdir(\"/content/drive/MyDrive/project/Dataset/data/\")\nfor f in dir:\n print(f)\n\nIf you just want a list of all directories, just use os.listdir(\"/content/drive/MyDri... | [
0,
0
] | [] | [] | [
"arrays",
"for_loop",
"google_colaboratory",
"path",
"python"
] | stackoverflow_0074449886_arrays_for_loop_google_colaboratory_path_python.txt |
Q:
Check if function passed as argument to class __init__ returns right type
I am trying to set up a class to generalize some numerical simulations, the core of the problem is the following:
Imagine I have a function that returns a numpy.ndarray type, like
def new_fun():
return numpy.zeros((2,2,2,2))
and then I ... | Check if function passed as argument to class __init__ returns right type | I am trying to set up a class to generalize some numerical simulations, the core of the problem is the following:
Imagine I have a function that returns a numpy.ndarray type, like
def new_fun():
return numpy.zeros((2,2,2,2))
and then I have a class declaration like:
class NewClass:
def __init__(self,function):... | [
"Check if it's callable\ndef __init__(self, fn):\n assert callable(fn)\n\nIt's not practical to know what some functions will return, but you can use type hints around this\nfrom typing import Callable\n...\n\n def __init__(self, fn: Callable[[None], numpy.ndarray]):\n if not callable(fn):\n ... | [
2
] | [] | [] | [
"class",
"numpy",
"python"
] | stackoverflow_0074450199_class_numpy_python.txt |
Q:
Remove the automatic two spaces between columns that Pandas DataFrame.to_string inserts
I'm looking for a solution to remove/turn off the 2 spaces between columns that df.to_string creates automatically.
Example:
from pandas import DataFrame
df = DataFrame()
df = df.append({'a':'12345', 'b': '12345'})
df.to_strin... | Remove the automatic two spaces between columns that Pandas DataFrame.to_string inserts | I'm looking for a solution to remove/turn off the 2 spaces between columns that df.to_string creates automatically.
Example:
from pandas import DataFrame
df = DataFrame()
df = df.append({'a':'12345', 'b': '12345'})
df.to_string(index=False, header=False)
'12345 1235'
For clarity, the result is: '12345..12345' where ... | [
"You can use the pd.Series.str.cat method, which accepts a sep keyword argument. By default sep is set to '' so there is no separation between values. Here are the docs: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.cat.html\nYou can also use pd.Series.str.strip to remove any leading or t... | [
4,
0,
0
] | [] | [] | [
"dataframe",
"display",
"formatting",
"pandas",
"python"
] | stackoverflow_0052030631_dataframe_display_formatting_pandas_python.txt |
Q:
Create new dataframes in python pandas based on the value of a column
I have a dataset that looks like that:
There are 15 unique values in the column 'query id', so I am trying to create new dataframes for each unique value. I thought of having a loop for every unique value in column 'query id' with a code like t... | Create new dataframes in python pandas based on the value of a column | I have a dataset that looks like that:
There are 15 unique values in the column 'query id', so I am trying to create new dataframes for each unique value. I thought of having a loop for every unique value in column 'query id' with a code like this:
df_list = []
i = 0
for x in df['query id'].unique():
df{i} = pd.D... | [
"Pandas has a built-in function for iterating unique values in a column and selecting the matching rows. The function is groupby\nIn your case, you can create the dictionary as a one-liner using:\ndfs = {query_id: grp.copy() for query_id, grp in df.groupby(\"query id\")}\n\nOnce you have your dictionary of datafram... | [
2,
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074449475_dataframe_pandas_python.txt |
Q:
Horizontal text alignment in openpyxl
I'm trying to change the text alignment to the center of 2 merged cells. I've found some answers that didn't work for my case:
currentCell = ws.cell('A1')
currentCell.style.alignment.horizontal = 'center' #TypeError: cannot set horizontal attribute
#or
currentCell.style.alignm... | Horizontal text alignment in openpyxl | I'm trying to change the text alignment to the center of 2 merged cells. I've found some answers that didn't work for my case:
currentCell = ws.cell('A1')
currentCell.style.alignment.horizontal = 'center' #TypeError: cannot set horizontal attribute
#or
currentCell.style.alignment.vertical = Alignment.HORIZONTAL_CENTER ... | [
"yes, there is a way to do this with openpyxl:\nfrom openpyxl.styles import Alignment\n\ncurrentCell = ws.cell('A1') #or currentCell = ws['A1']\ncurrentCell.alignment = Alignment(horizontal='center')\n\nhope this will help you\n",
"This is what finally worked for me with the latest version from PIP (2.2.5)\n #... | [
63,
12,
5,
0,
0
] | [
"You can achieve this by using Python XlsxWriter library. \nimport xlsxwriter\n\nworkbook = xlsxwriter.Workbook('example.xlsx')\nworksheet = workbook.add_worksheet()\n\ncell_format = workbook.add_format({'align': 'center'})\n\nworksheet.merge_range('A1:B1', \"\")\nworksheet.write_rich_string('A1','Example', cell_fo... | [
-2
] | [
"openpyxl",
"python",
"xlsx"
] | stackoverflow_0026671581_openpyxl_python_xlsx.txt |
Q:
Compute monthly covariance in xarray
I have wind speed data in the form of xarray.DataArray:
u_250
Dims:
time: 600 latitude: 20 longitude: 40
Coordinates:
time (time) datetime64[ns] 1970-01-01 ... 2019-12-01
longitude (longitude) float64 101.0 103.0 105.0 ... 177.0 179.0
latitude (latitude) ... | Compute monthly covariance in xarray | I have wind speed data in the form of xarray.DataArray:
u_250
Dims:
time: 600 latitude: 20 longitude: 40
Coordinates:
time (time) datetime64[ns] 1970-01-01 ... 2019-12-01
longitude (longitude) float64 101.0 103.0 105.0 ... 177.0 179.0
latitude (latitude) float64 1.0 3.0 5.0 7.0 ... 35.0 ... | [
"You could bundle your arrays into a dataset and then use xr.Dataset.groupby with .apply and then apply xr.cov\nIn [3]: ds = xr.Dataset({\"u_250\": u_250, \"u_850\": u_850})\n ...: ds\nOut[3]:\n<xarray.Dataset>\nDimensions: (time: 49, latitude: 20, longitude: 40)\nCoordinates:\n * time (time) datetime64... | [
1
] | [] | [] | [
"covariance",
"python",
"python_xarray"
] | stackoverflow_0074446772_covariance_python_python_xarray.txt |
Q:
Scraping href value, but only for items that are in stock
I'm trying to scrape the href values for the items on the following page, however only if the items show as in stock: https://www.waitrosecellar.com/whisky-shop/view-all-whiskies/whisky-by-brand/macallan
With the following code, I've managed to successfully... | Scraping href value, but only for items that are in stock | I'm trying to scrape the href values for the items on the following page, however only if the items show as in stock: https://www.waitrosecellar.com/whisky-shop/view-all-whiskies/whisky-by-brand/macallan
With the following code, I've managed to successfully scrape the hrefs, however the out_of_stock flag does not appea... | [
"Here is one way to differentiate between out of stock/available products:\nimport requests\nfrom bs4 import BeautifulSoup as bs\n\nheaders = {\n'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.5112.79 Safari/537.36'\n}\n\nurl = 'https://www.waitrosecellar.com/whisk... | [
0
] | [] | [] | [
"beautifulsoup",
"python",
"web_scraping"
] | stackoverflow_0074450254_beautifulsoup_python_web_scraping.txt |
Q:
This easy python code suddenly doesn't work
I created a little program as part of my learning experience using python crash course and the code worked pretty well yesterday. But now that I woke up and tried to launch the thing it refuses to do anything and says that "self" is not defined. I honestly have no idea w... | This easy python code suddenly doesn't work | I created a little program as part of my learning experience using python crash course and the code worked pretty well yesterday. But now that I woke up and tried to launch the thing it refuses to do anything and says that "self" is not defined. I honestly have no idea why it happens and would very much like to know ex... | [
"The problem arises when the file is not found: you return None, but don't actually asign it to self.username. So when you do if self.username, an error will rise. I tweaked two lines of your code, here are the functions to change:\n def get_stored_username(self):\n \"\"\"Get the username if stored.\"\"\"... | [
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074450274_python.txt |
Q:
why do i keep getting this python error cost is not defined?
i wrote this code i get an error say cost is not defined
print("============================================================\n"
" Welcome to Pizza Store \n"
"=======================================... | why do i keep getting this python error cost is not defined? | i wrote this code i get an error say cost is not defined
print("============================================================\n"
" Welcome to Pizza Store \n"
"============================================================\n")
def welcomescreen():
print("1) Menu ... | [
"cost is only defined if kind is one of the three strings you check against in your if/elifs. Specifically, I think whats happening is that you're putting in 'pepperoni' but you really want to put in 'Pepperoni' (notice the capitalization)\nTo handle this more generally, you probably want to:\n\n.lower() the input ... | [
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074450391_python_python_3.x.txt |
Q:
Modify and Replace just 1 line from a file using Pyhton
I have a script that pulls data and writes it into a TXT file, then in the same code I have a For Loop that changes the format by replacing quotes to double quotes and concatenates the result with a text in another new file.
with open ('myfile.txt', 'w') as f... | Modify and Replace just 1 line from a file using Pyhton | I have a script that pulls data and writes it into a TXT file, then in the same code I have a For Loop that changes the format by replacing quotes to double quotes and concatenates the result with a text in another new file.
with open ('myfile.txt', 'w') as f:
print(response['animals']['mammals'], file=f)
fout = op... | [
"Get numbers of strings in list and start indexing from [last_word +1\n"
] | [
0
] | [] | [] | [
"for_loop",
"python",
"python_3.x",
"with_statement"
] | stackoverflow_0074450462_for_loop_python_python_3.x_with_statement.txt |
Q:
How to avoid repeating the default argument value for a function called from another function?
Consider some function that accepts a default value:
def print_number(number=42):
print(number)
Now you might happen to want to use this from another function, but the argument is still provided by the user:
def pri... | How to avoid repeating the default argument value for a function called from another function? | Consider some function that accepts a default value:
def print_number(number=42):
print(number)
Now you might happen to want to use this from another function, but the argument is still provided by the user:
def print_number_twice(number=42):
print_number(number)
print_number(number)
And here you happen t... | [
"You could check for None, like so:\ndef print_number_twice(number=None):\n if number is None:\n print_number()\n print_number()\n else:\n print_number(number)\n print_number(number)\n\nHowever personally I think it would be better to just define the default arguments to both funct... | [
2
] | [] | [] | [
"default_arguments",
"python",
"python_3.x"
] | stackoverflow_0074450439_default_arguments_python_python_3.x.txt |
Q:
Python SQLModel - Optional ID value for auto-increment causes type errors when retrieving from database
If I have a model like this:
class MyModel(DBModel, table=True):
id: Optional[int] = Field( primary_key=True)
Then when saving new records to the database, the ID is automatically assigned, which is great.... | Python SQLModel - Optional ID value for auto-increment causes type errors when retrieving from database | If I have a model like this:
class MyModel(DBModel, table=True):
id: Optional[int] = Field( primary_key=True)
Then when saving new records to the database, the ID is automatically assigned, which is great.
However, when I retrieve the model like this I get type errors
model = session.get(MyModel, 1)
id: int = mod... | [
"You might find your answer here: https://sqlmodel.tiangolo.com/tutorial/fastapi/multiple-models/#multiple-models-with-inheritance\nBasically what you can do is define your models like this:\nclass MyModelBase(SQLModel):\n arg1: str\n ...\n\n\nclass MyModel(MyModelBase, table=True):\n id: Optional[int] = F... | [
1,
0
] | [] | [] | [
"fastapi",
"python",
"sqlmodel"
] | stackoverflow_0072720210_fastapi_python_sqlmodel.txt |
Q:
GPA Calculator troubles
For some reason that is unknown to me, my GPA calculator only calculates the last input in the list, I only have 2 days left to complete this and hopefully i can in time.
I tried to make it to where it calculates every input nd not just the last one, but i dont know how.
here is my code:
na... | GPA Calculator troubles | For some reason that is unknown to me, my GPA calculator only calculates the last input in the list, I only have 2 days left to complete this and hopefully i can in time.
I tried to make it to where it calculates every input nd not just the last one, but i dont know how.
here is my code:
name = input("What is your name... | [
"It looks like the problem is the input you give to the function, grades this variable will be changed and then added to class_data in the tuple but it will keep just one value, meaning it will keep the last value it was given and calculate the gpa with just that. Instead you should give a list so it can iterate th... | [
0,
0,
0
] | [] | [] | [
"computer_science",
"python"
] | stackoverflow_0074449733_computer_science_python.txt |
Q:
How to detect objects with a custom YOLOv5 model?
I trained a YOLOv5 model from a custom dataset with the provided training routine on github (from inside tutorial.ipynb).
Using this model for detecting objects in unseen images gets me decent results when executing:
!python detect.py --weights custom_weights.pt --... | How to detect objects with a custom YOLOv5 model? | I trained a YOLOv5 model from a custom dataset with the provided training routine on github (from inside tutorial.ipynb).
Using this model for detecting objects in unseen images gets me decent results when executing:
!python detect.py --weights custom_weights.pt --img 224 --conf 0.5 --source data/images
Now I want to ... | [
"Simply clone the yolov5 github repository on your desktop. Paste your custom weights files in yolov5 folder and then run the inference command using detect.py. Is your model providing good results that way? If not then most probably the size of your training data is the culprit. You should train your custom model ... | [
0,
0,
0
] | [] | [] | [
"object_detection",
"python",
"pytorch",
"yolov5"
] | stackoverflow_0072584233_object_detection_python_pytorch_yolov5.txt |
Q:
How to get all subset from a set composed by couples and singles
I have to implement an algorithm in python with these features:
Let there be a set of n elements, and suppose that each element can be paired with some other element or can be unpaired ("single"). Each element can be paired only once. An algorithm is... | How to get all subset from a set composed by couples and singles | I have to implement an algorithm in python with these features:
Let there be a set of n elements, and suppose that each element can be paired with some other element or can be unpaired ("single"). Each element can be paired only once. An algorithm is implemented to find out the total number of ways in which the n eleme... | [
"This is an interesting problem. I'm sure you can figure out the formula with math alone, but it is probably easier to do it with code. One way to do it would be to create a set of all the unique subsets and then combine those subsets to form valid supersets.\nWhat? (I hear you say)\nSo start by adding each member ... | [
0
] | [] | [] | [
"dynamic",
"list",
"python"
] | stackoverflow_0074450221_dynamic_list_python.txt |
Q:
Poetry using wrong Python version
Trying to install packages using poetry
And getting :
Current Python version (3.10.4) is not allowed by the project (>=3.8,<3.10).
Then I'm trying to do:
poetry env use python3.8
Or
poetry env use 3.8
And the same error popping. Any reason this could happen?
A:
Make sure that... | Poetry using wrong Python version | Trying to install packages using poetry
And getting :
Current Python version (3.10.4) is not allowed by the project (>=3.8,<3.10).
Then I'm trying to do:
poetry env use python3.8
Or
poetry env use 3.8
And the same error popping. Any reason this could happen?
| [
"Make sure that when you are switching python version you are using a full path, so poetry has no problem with resolving the version:\npoetry env use /usr/bin/python3.8\n\nIf that didn't help, check your pyproject.toml and make sure that the version of python is compatible, something like:\npython = \"^3.8\"\n\nIf ... | [
0
] | [] | [] | [
"installation",
"package_managers",
"python",
"python_3.8",
"python_3.x"
] | stackoverflow_0073606035_installation_package_managers_python_python_3.8_python_3.x.txt |
Q:
How to code the Simple Harmonic Oscillator system at the atomic scale using Euler method in python
I am writing code to solve the simple harmonic oscillator system using the Euler Method. The second order ODE for the system is given as two first order ODEs, x' = v and v' = -k/m x. The question says to solve the pa... | How to code the Simple Harmonic Oscillator system at the atomic scale using Euler method in python | I am writing code to solve the simple harmonic oscillator system using the Euler Method. The second order ODE for the system is given as two first order ODEs, x' = v and v' = -k/m x. The question says to solve the pair of equations for x and v as functions of time and plot x vs t. The model being used is a sodium atom ... | [
"Having tried out your code and made some changes to parameters, I believe that your problem is caused by the size of your time step.\nIf you consider the acceleration of that sodium atom when acted upon by the spring constant, it will be very large, around 10^16 ms^-2, so the atom will be moving very quickly aroun... | [
0
] | [] | [] | [
"math",
"physics",
"python"
] | stackoverflow_0074450022_math_physics_python.txt |
Q:
Pandas multiples conditions resulting in zeros
The pandas conditional statement resulting in '0' while evaluating below conditions in pandas, not sure why the results are not printing as required.
Source:
t_type Att Name
ABC NaN A1
CCC A_XY NaN
ABC NaN NaN
CDE... | Pandas multiples conditions resulting in zeros | The pandas conditional statement resulting in '0' while evaluating below conditions in pandas, not sure why the results are not printing as required.
Source:
t_type Att Name
ABC NaN A1
CCC A_XY NaN
ABC NaN NaN
CDE NaN NaN
CDE A_ZZ A2
... | [
"Numpy.select has a default parameter, you can specify it to be whatever you want:\ndf['Remarks'] = np.select(conditions, values, np.NaN)\n\nprint(df)\n\nOutput:\n t_type Att Name Remarks\n0 ABC NaN A1 Att is Null\n1 CCC A_XY NaN Name is ... | [
2
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074450518_pandas_python.txt |
Q:
Calculating mean of columns using python regular expression
pcd
DCF
DDF
FFD
AB106
1
2
1
AB107
2
3
2
AC200
2
4
5
AC200
1
6
6
AC201
2
3
1
SD234
3
1
3
Required Table
pcd
DCF(mean)
DDF(mean)
AB106
0.5
1
AB107
1
1.5
AC200
1
3.33
AC201
0.66
1
SD234
3
1
Explanation:
For "AB106" DCF(mean), it is 0.5 (1/2), w... | Calculating mean of columns using python regular expression |
pcd
DCF
DDF
FFD
AB106
1
2
1
AB107
2
3
2
AC200
2
4
5
AC200
1
6
6
AC201
2
3
1
SD234
3
1
3
Required Table
pcd
DCF(mean)
DDF(mean)
AB106
0.5
1
AB107
1
1.5
AC200
1
3.33
AC201
0.66
1
SD234
3
1
Explanation:
For "AB106" DCF(mean), it is 0.5 (1/2), where the denominator is the number of... | [
"from io import StringIO\n\nimport pandas as pd # 1.5.1\n\nf = StringIO(\"\"\"pcd DCF DDF FFD\nAB106 1 2 1\nAB107 2 3 2\nAC200 2 4 5\nAC200 1 6 6\nAC201 2 3 1\nSD234 3 1 3\"\"\")\n\ndf = pd.read_csv(f, sep=\"\\t\")\n\n# start\nprint(df)\n\n pcd DCF DDF FFD\n0 AB106 1 ... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074450210_pandas_python.txt |
Q:
Python string FIFO
Does Python have any data types for FIFO buffering of strings? I created something (below) but suspect I'm reinventing the wheel.
class Buffer(list):
def __init__(self):
super(Buffer, self).__init__()
def put(self, nlmsg):
for c in nlmsg: self.append(c)
def peek(se... | Python string FIFO | Does Python have any data types for FIFO buffering of strings? I created something (below) but suspect I'm reinventing the wheel.
class Buffer(list):
def __init__(self):
super(Buffer, self).__init__()
def put(self, nlmsg):
for c in nlmsg: self.append(c)
def peek(self, number):
ret... | [
"Using collections.deque it would be implemented as follows:\nfrom collections import deque\n\nclass Buffer(deque):\n def put(self, iterable):\n for i in iterable:\n self.append(i)\n\n def peek(self, how_many):\n return ''.join([self[i] for i in xrange(how_many)])\n\n def get(self,... | [
3,
0,
0
] | [] | [] | [
"buffer",
"python",
"string"
] | stackoverflow_0009219093_buffer_python_string.txt |
Q:
Mocking kubernetes client for Python unittest creating AttributeError
I was mocking a function that is used to read k8s secret to fetch secret token. But running unittest is creating error - AttributeError: <module 'kubernetes.client' from '/usr/lib/python3.6/site-packages/kubernetes/client/init.py'> does not have... | Mocking kubernetes client for Python unittest creating AttributeError | I was mocking a function that is used to read k8s secret to fetch secret token. But running unittest is creating error - AttributeError: <module 'kubernetes.client' from '/usr/lib/python3.6/site-packages/kubernetes/client/init.py'> does not have the attribute 'read_namespaced_secret()' I have gone through How do you mo... | [
"You need to mock kubernetes.client.CoreV1Api instead of kubernetes.client. Here is an example:\nimport base64\nimport unittest\nfrom unittest.mock import patch, Mock\n\nimport requests\nfrom kubernetes import client, config\n\n\nclass kubernetesServices():\n def get_secret_vault_token(self):\n config.loa... | [
0
] | [] | [] | [
"kubernetes",
"mocking",
"python",
"python_unittest",
"unit_testing"
] | stackoverflow_0074285773_kubernetes_mocking_python_python_unittest_unit_testing.txt |
Q:
Using IDLE to display script output like in Shell
I hope this makes sense. When using the IDLE python shell and typing the commands one by one, there is an output or response to most lines of code typed.
When writing a script and then running that script in IDLE I don't get to see the same output in the shell, is ... | Using IDLE to display script output like in Shell | I hope this makes sense. When using the IDLE python shell and typing the commands one by one, there is an output or response to most lines of code typed.
When writing a script and then running that script in IDLE I don't get to see the same output in the shell, is there a way of enabling it, or a line of code to add to... | [
"A feature of both standard interactive mode and the IDLE Shell (and presumably of other Python IDEs) is that the value of expressions entered in response to the >>> or other interactive prompt is echoed on a line below.\nWhen running a script, the value of an expression statement is not printed. This is because s... | [
0
] | [] | [] | [
"python",
"python_idle"
] | stackoverflow_0074441525_python_python_idle.txt |
Q:
How to make a validate_data field optional?
I am trying to create a RESTful api endpoint for creating a new user. And this is what I put in my serializer.py
class UserSerializer(serializers.ModelSerializer):
Class Meta:
model = User
field = ('name', 'division', 'image',)
extra_kwargs = ... | How to make a validate_data field optional? | I am trying to create a RESTful api endpoint for creating a new user. And this is what I put in my serializer.py
class UserSerializer(serializers.ModelSerializer):
Class Meta:
model = User
field = ('name', 'division', 'image',)
extra_kwargs = {'division': {'required': False}}
def create... | [
"To make a field optional, you can use the extra_kwargs dict. In order for this to work, the field must be explicitly declared in fields.\nclass FooSerializer(serializers.ModelSerializer):\n ...\n\n class Meta:\n ...\n fields = ('bar', 'baz',)\n extra_kwargs = {'bar': {'required': False}}... | [
1,
0,
0
] | [] | [] | [
"django",
"django_models",
"django_rest_framework",
"django_serializer",
"python"
] | stackoverflow_0052764006_django_django_models_django_rest_framework_django_serializer_python.txt |
Q:
how do i solve "list index out of range" error in python? (IndexError)
I tried to create a sorting algorithm but it didn't work.
Here's my code:
from random import *
sort = [9, 7, 4, 5, 8, 3, 2, 1, 6, 10]
def sort_array(array):
for i in range(len(array)):
if array[i + 1] < array[i + 2]:
a... | how do i solve "list index out of range" error in python? (IndexError) | I tried to create a sorting algorithm but it didn't work.
Here's my code:
from random import *
sort = [9, 7, 4, 5, 8, 3, 2, 1, 6, 10]
def sort_array(array):
for i in range(len(array)):
if array[i + 1] < array[i + 2]:
array[i + 1], array[i + 2] = array[i + 2], array[i + 1]
else:
... | [
"You should try an iteration until the array length - 2 since i+2 will go out of bound throwing an error try with for i in range(len(array)-2).\nAnyway i don't think your code will work.\nRead about Sorting algorithms or if you're too lazy there's a spoiler:\n\nsort = [9, 7, 4, 5, 8, 3, 2, 1, 6, 10]\n\n\ndef sort_... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0074450138_python.txt |
Q:
Find Specific Element on Japanese Website via Selenium or BeautifulSoup on Python
So, I want to find a specific element on a Japanese real estate website via Selenium or BeautifulSoup.
The website URL, with the specifications I set, is:
CHINTAI_URL = "https://www.chintai.net/list/?cf=0&ct=70&jk=0&jl=0&sf=0&st=0&b=... | Find Specific Element on Japanese Website via Selenium or BeautifulSoup on Python | So, I want to find a specific element on a Japanese real estate website via Selenium or BeautifulSoup.
The website URL, with the specifications I set, is:
CHINTAI_URL = "https://www.chintai.net/list/?cf=0&ct=70&jk=0&jl=0&sf=0&st=0&b=1&b=2&b=3&h=99&j=6&k=1&st=0&ue=000013609&ue=000000849&ue=000006985&prefkey=ibaragi&&rt=... | [
"Okay, I think is like this\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n#Define web driver as a Chrome driver and navigate\ndriver = webdriver.Chrome()\ndriver... | [
0
] | [] | [] | [
"beautifulsoup",
"python",
"selenium",
"web_scraping"
] | stackoverflow_0074447296_beautifulsoup_python_selenium_web_scraping.txt |
Q:
Python text based game - TypeError: bool oject not callable
I am creating my first python program and have been struggling with a "TypeError: 'bool' object is not callable" error. I have only been studying for a few weeks so any assistance would be great! Also, if there are any tips on how to reduce some of the co... | Python text based game - TypeError: bool oject not callable | I am creating my first python program and have been struggling with a "TypeError: 'bool' object is not callable" error. I have only been studying for a few weeks so any assistance would be great! Also, if there are any tips on how to reduce some of the code that'd be great! Thanks!
import random
class Spacecraft:
... | [
"def ship_destroyed(self):\n self.ship_destroyed = True\n\nYou're trying to make a function and an attribute that are both named ship_destroyed. You can't do that. Pick a different name for one of them.\n"
] | [
0
] | [] | [] | [
"boolean_expression",
"class",
"object",
"python"
] | stackoverflow_0074450697_boolean_expression_class_object_python.txt |
Q:
Finding the mean of elements that meet certain criteria using groupby
I have a dataset and I need to use Python and Pandas to find the average prices of specific items in a column that meet specific criteria. The criteria are "Honda" and "Toyota" in the "manufacturer" column, "good" in the "condition" column, and ... | Finding the mean of elements that meet certain criteria using groupby | I have a dataset and I need to use Python and Pandas to find the average prices of specific items in a column that meet specific criteria. The criteria are "Honda" and "Toyota" in the "manufacturer" column, "good" in the "condition" column, and "sedan" in the "type" column. The prices are in the "price" column. I would... | [
"You may filter the dataframe columns values with the required criteria conditions:\nfiltered_df = df[df['manufacturer'].isin(['Honda','Toyota']) & (df['condition'] == 'good') & (df['type'] == 'sedan')]\n\nAfter that you can find the mean of the filtered dataframe using groupby:\nfiltered_df.groupby(['manufacturer'... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074450344_pandas_python.txt |
Q:
How to use Python multiprocessing Pool to consume items from queue forever
I'm trying to create a worker that listens to http requests and adds jobs IDs to a queue. I'm using Python's built-in multiprocessing module for that.
I need a Pool with a few processes that will process the job from queue and respawn. Proc... | How to use Python multiprocessing Pool to consume items from queue forever | I'm trying to create a worker that listens to http requests and adds jobs IDs to a queue. I'm using Python's built-in multiprocessing module for that.
I need a Pool with a few processes that will process the job from queue and respawn. Processes have to restart, bacause for some cases job processing can cause memory le... | [
"What you are doing with your pool initializer is most unusual. Such an initializer is run for each pool process and is used to initialize that process (for example, setting global variables) so that it is able to run tasks that are submitted. A multiprocessing pool implements a hidden task queue for holding submit... | [
1,
1
] | [] | [] | [
"multiprocessing",
"pool",
"python",
"queue",
"worker"
] | stackoverflow_0074448892_multiprocessing_pool_python_queue_worker.txt |
Q:
How to read data from a file into a dictionary?
I am trying to read information from a.txt file where each label is a dictionary key and each associated column of readings is the respective value.
Here's some lines in the file:
increments ideal actual measured
0.0, 1000.0, 1000.0, 1006.4882
1.0, 950.0, 973.2774, 9... | How to read data from a file into a dictionary? | I am trying to read information from a.txt file where each label is a dictionary key and each associated column of readings is the respective value.
Here's some lines in the file:
increments ideal actual measured
0.0, 1000.0, 1000.0, 1006.4882
1.0, 950.0, 973.2774, 994.5579
2.0, 902.5, 897.6053, 998.9594
3.0, 857.375, ... | [
"Here's your solution:\nwith open(\"test.csv\", 'r') as file:\n \n labels = file.readline().rstrip('\\n').split() # read first line for labels\n data_dict = {l:[] for l in labels} # init empty container for each label\n\n for line in file.readlines(): # loop through rest of lines\n data = line.rs... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074450140_python.txt |
Q:
remove all argument from a list that start with a letter
i have a problem with python list:
in the file I have to insert a function that takes as argument a path of a folder and that returns a list of strings with the complete path of the image files inside the folder that I go to specify, excluding all images who... | remove all argument from a list that start with a letter | i have a problem with python list:
in the file I have to insert a function that takes as argument a path of a folder and that returns a list of strings with the complete path of the image files inside the folder that I go to specify, excluding all images whose file name does not start by number.
I wrote this code but I... | [
"Several issues:\nimport os\nimport numpy as np\n\n\ndef funzione(folder: str) -> list:\n files = []\n for (root, dirs, file) in os.walk(folder):\n for f in file:\n if f.startswith(\"r\"): # <- if else not needed. use not f.startswith('r')\n pass\n else:\n ... | [
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074450145_list_python.txt |
Q:
Python - reference class each other (information flow)
I would like to know, what is the concept of information flow in GUI based apps, or any other app with same problem. When you have two seperate classes and their objects, how is the messeging process done between them. For example you have a GUI and AppLogic.
... | Python - reference class each other (information flow) | I would like to know, what is the concept of information flow in GUI based apps, or any other app with same problem. When you have two seperate classes and their objects, how is the messeging process done between them. For example you have a GUI and AppLogic.
Scenario 1: Button is pressed -> GUI is processing event -> ... | [
"You need to initialize your variables.\ngui = Gui()\n\nthen you can call the methods\nFor example:\nclass AppLogic:\n gui: Gui\n\n def image_clicked(self):\n gui = Gui()\n gui.render_image()\n \nclass Gui:\n logic: AppLogic\n\n def render_image(self) :\n pass\n\nOr you can initialize your... | [
0,
0,
0
] | [] | [] | [
"class",
"design_patterns",
"python",
"reference"
] | stackoverflow_0074450198_class_design_patterns_python_reference.txt |
Q:
What's the fastest way to update a scatterplot?
I have a dashboard that is very similar to this-
import datetime
import dash
from dash import dcc, html
import plotly
from dash.dependencies import Input, Output
# pip install pyorbital
from pyorbital.orbital import Orbital
satellite = Orbital('TERRA')
external_st... | What's the fastest way to update a scatterplot? | I have a dashboard that is very similar to this-
import datetime
import dash
from dash import dcc, html
import plotly
from dash.dependencies import Input, Output
# pip install pyorbital
from pyorbital.orbital import Orbital
satellite = Orbital('TERRA')
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.... | [
"You can use extendData property of graph to add data to an existing graph without building the graph from scratch every time the interveral triggers. As written in the documentation:\n\nextendData (list | dict; optional): Data that should be appended to\nexisting traces. Has the form [updateData, traceIndices, max... | [
2
] | [] | [] | [
"plotly",
"plotly_dash",
"plotly_python",
"python"
] | stackoverflow_0074445610_plotly_plotly_dash_plotly_python_python.txt |
Q:
Why is my Python code not working when referencing a dictionary key above 14?
So i was working on some python code so i could get a better understanding of dictionaries. I have only been learning python 2 weeks and its my first language, so there is definitely a lack of knowledge on my end. I started the program o... | Why is my Python code not working when referencing a dictionary key above 14? | So i was working on some python code so i could get a better understanding of dictionaries. I have only been learning python 2 weeks and its my first language, so there is definitely a lack of knowledge on my end. I started the program originally to have a user input the section number they were on in a video series an... | [
"The whole thing can just be this:\nvideo_dict = {\n 1 : 19, 2 : 54, 3 : 122, 4 : 9, 5 : 75, 6 : 174, 7 : 100, 8 : 81, 9 : 29, 10 : 46, 11 : 138, 12 : 23, 13 : 17, 14 : 143, 15 : 143,\n 16 : 24, 17 : 45, 18 : 28, 19 : 3, 20 : 41, 21 : 45, 22 : 15, 23 : 1\n}\n\ncurrent_section = int(input('What section are you... | [
2,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074449599_dictionary_python.txt |
Q:
How to make directory in c drive using python
Hello I want to create directory in c:\program files using this code
import os
os.mkdir('C:\\Program Files\\new_dir')
but this problem is shown
PermissionError: [WinError 5] Access is denied: 'C:\\Program Files\\new_dir'
A:
The error is due to the fact that the user... | How to make directory in c drive using python | Hello I want to create directory in c:\program files using this code
import os
os.mkdir('C:\\Program Files\\new_dir')
but this problem is shown
PermissionError: [WinError 5] Access is denied: 'C:\\Program Files\\new_dir'
| [
"The error is due to the fact that the user does not have permission to create a directory in the C:\\Program Files directory.\nTo fix this, the user would need to either:\n\nRun the code as an administrator\nChange the permissions for the C:\\Program Files directory to allow the user to create directories.\n\nOnce... | [
0
] | [] | [] | [
"cmd",
"python"
] | stackoverflow_0074450796_cmd_python.txt |
Q:
Problems sending GET http requests from localhost:5000 to localhost:8000
I have a backend cython flask app, which has a GET endpoint with route http://127.0.0.1:8000/items. My second app is a html website hosted at http://127.0.0.1:5000. And I'm trying to send a request from my website to said endpoint.
Flask app:... | Problems sending GET http requests from localhost:5000 to localhost:8000 | I have a backend cython flask app, which has a GET endpoint with route http://127.0.0.1:8000/items. My second app is a html website hosted at http://127.0.0.1:5000. And I'm trying to send a request from my website to said endpoint.
Flask app:
@app.route('/items', methods=["GET"])
def getPrices():
.......
# "stu... | [
"mode: no-cors in your Flask endpoint is being used incorrectly here and will lead to responses of type: \"opaque\" which have unreadable bodies. Explained here.\nBrowsers don't allow cross-origin requests to work unless servers explicitly allow them.\nOne way of resolving this is to use flask-cors (can be installe... | [
1
] | [] | [] | [
"fetch",
"flask",
"javascript",
"python",
"request"
] | stackoverflow_0074450757_fetch_flask_javascript_python_request.txt |
Q:
MATLAB to Python datestr
I have a MATLAB script that I would like to convert to Python. The MATLAB code is
c = fix(clock);
t = 26912214.000820093;
t_str=datestr(t/24/60/60 + datenum(c(1),1,1),'yyyy_mm_dd_HH_MM_SS')
which returns
t_str =
'2022_11_08_11_36_54'
I would like to limit solutions to only utilize th... | MATLAB to Python datestr | I have a MATLAB script that I would like to convert to Python. The MATLAB code is
c = fix(clock);
t = 26912214.000820093;
t_str=datestr(t/24/60/60 + datenum(c(1),1,1),'yyyy_mm_dd_HH_MM_SS')
which returns
t_str =
'2022_11_08_11_36_54'
I would like to limit solutions to only utilize the Python datetime library and ... | [
"I found that the Python equivalent is,\nimport datetime\nt = 26912214.000820093;\nt_str = (datetime.datetime(datetime.datetime.now().year, 1, 1) + datetime.timedelta(seconds=t)).strftime('%Y_%m_%d_%H_%M_%S')\n\nI would still greatly appreciate any suggestions or improvements.\n"
] | [
0
] | [] | [] | [
"datetime",
"matlab",
"python"
] | stackoverflow_0074438967_datetime_matlab_python.txt |
Q:
convert data from tcp socket in python
I have a data struct that I am converting to uint8_t and sending it over a tcp socket connection. For the server side I have a python. How do I convert the data and display the struct information.
//data struct
typedef struct {
int enable;
string name;
int numbers[5];
float c... | convert data from tcp socket in python | I have a data struct that I am converting to uint8_t and sending it over a tcp socket connection. For the server side I have a python. How do I convert the data and display the struct information.
//data struct
typedef struct {
int enable;
string name;
int numbers[5];
float counter;
}Student;
//convert data to uint8 ... | [
"You simply cannot do std::memcpy(data.data(), reinterpret_cast<void*>(&student),size)\n&student is not a POD class. Specifically, in memory, the string name; member will be a small struct, say 16 bytes, with pointers to the actual content.\nUse something like Protobuff or any other stock serialization. This is the... | [
1
] | [] | [] | [
"c++",
"python",
"server",
"struct",
"tcp"
] | stackoverflow_0074450725_c++_python_server_struct_tcp.txt |
Q:
Get a random sample of a dict
I'm working with a big dictionary and for some reason I also need to work on small random samples from that dictionary. How can I get this small sample (for example of length 2)?
Here is a toy-model:
dy={'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
I need to perform some task on dy which invo... | Get a random sample of a dict | I'm working with a big dictionary and for some reason I also need to work on small random samples from that dictionary. How can I get this small sample (for example of length 2)?
Here is a toy-model:
dy={'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
I need to perform some task on dy which involves all the entries. Let us say, t... | [
"def sample_from_dict(d, sample=10):\n keys = random.sample(list(d), sample)\n values = [d[k] for k in keys]\n return dict(zip(keys, values))\n\n",
"Given your example of:\ndy = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}\n\nThen the sum of all the values is more simply put as:\ns = sum(dy.values())\n\nThen if i... | [
8,
3,
1,
0
] | [
"import random\norigin_dict = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}\nsample_rate = 0.3\nrandom_keys = random.sample(list(origin_dict.keys()), int(sample_rate * len(origin_dict)))\nrandom_values = [origin_dict[k] for k in random_keys]\n\nsample_dict = dict(zip(random_keys, random_values))\n\noutput:\n{'d': 4, 'c': 3}... | [
-1,
-1
] | [
"dictionary",
"python",
"python_3.4",
"random"
] | stackoverflow_0040001646_dictionary_python_python_3.4_random.txt |
Q:
PyInstaller failing to build exe -- cannot find pyproj.libs
Here's the traceback:
Traceback (most recent call last):
File "main.py", line 5, in <module>
File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
File "<frozen import... | PyInstaller failing to build exe -- cannot find pyproj.libs | Here's the traceback:
Traceback (most recent call last):
File "main.py", line 5, in <module>
File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
File "PyInstaller\l... | [
"Add the pyproj lib directory to your data files.\nFor example, in your spec file:\na = Analysis(\n ['myscript.py'],\n pathex=[],\n binaries=...,\n datas=[('...\\\\Lib\\\\site-packages\\\\pyproj.libs','pyproj.libs')],\n hiddenimports=['pyproj', ...],\n hookspath=[],\n hooksconfig={},\n runti... | [
1
] | [] | [] | [
"geopandas",
"pyinstaller",
"python"
] | stackoverflow_0074449924_geopandas_pyinstaller_python.txt |
Q:
How to covert dataframe to list without none values
How can I remove the None values from this dataframe df and convert the columns from a to f as a list
emp_no a b c d e f id
0 11390 [1, 28.4] [7, 32.2] [7, 31.3] [28, 40.7] [28, 40.... | How to covert dataframe to list without none values | How can I remove the None values from this dataframe df and convert the columns from a to f as a list
emp_no a b c d e f id
0 11390 [1, 28.4] [7, 32.2] [7, 31.3] [28, 40.7] [28, 40.0] [28, 39.6] nhvm657mjhgmjhm
1 11395 [1, 31.4] ... | [
"This isn't really a panda's problem, here with just list comprehension:\nout = [[y for y in x if None not in y] for x in df.iloc[:, 1:].to_dict('list').values()]\nprint(out)\n\nOutput:\n[[[1, 28.4], [7, 32.2], [7, 31.3], [28, 40.7], [28, 40.0], [28, 39.6]],\n [[1, 31.4], [7, 32.8], [28, 37.3], [28, 39.2]],\n [[1, ... | [
1,
0,
0
] | [] | [] | [
"dataframe",
"nonetype",
"pandas",
"python"
] | stackoverflow_0074449345_dataframe_nonetype_pandas_python.txt |
Q:
A function that returns ones at the boundary of a matrix
I just started learning the numpy library and I have a question.
I wrote a function decorate_matrix that takes one integer greater than one as input. The function should return an n by n matrix with 1's on the edges and 0's at all other positions.
My code:
i... | A function that returns ones at the boundary of a matrix | I just started learning the numpy library and I have a question.
I wrote a function decorate_matrix that takes one integer greater than one as input. The function should return an n by n matrix with 1's on the edges and 0's at all other positions.
My code:
import numpy
def decorate_matrix(n: int):
matrix = numpy.ze... | [
"I like your implementation, there's nothing wrong with it and it's clever. But if you're goal is to not use transpose, then you could do this\ndef decorate_matrix(n: int):\n matrix = numpy.zeros((n, n))\n matrix[:,0]=1 # first column\n matrix[0,:]=1 # first row\n matrix[:,-1]=1 # last column\n ... | [
0
] | [] | [] | [
"matrix",
"numpy",
"python"
] | stackoverflow_0074450156_matrix_numpy_python.txt |
Q:
Trying to see if a number in a list is within 1 of its neighbour
I'm trying to compare all the numbers in this list and if any of them are within 1 of the number next to them in the list, if so then I want the command to print True. I realised that by applying the [x+1] to the last item in the list I'd be going ou... | Trying to see if a number in a list is within 1 of its neighbour | I'm trying to compare all the numbers in this list and if any of them are within 1 of the number next to them in the list, if so then I want the command to print True. I realised that by applying the [x+1] to the last item in the list I'd be going out of the range of the list. I've tried to avoid this but I'm still get... | [
"itertools.pairwise gives you nice neighboring pairs from a list that you can work with:\nfrom itertools import pairwise\n\nvals = [x for x in pairwise(listed) if abs(x[0] - x[1]) <= 1]\nprint(vals)\n\nOutput:\n[(4, 5)]\n\n",
"Your request to access out of index resulted in an error. You can use range(len(listed)... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074450899_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.