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: Why are my labels being displayed at the same time in tkinter? This is an example code of my problem: from tkinter import * root = Tk() def large_list(): my_list = [i for i in range(100000000)] def make_large_list(): my_label = Label(root, text='0% completed') my_label.pack() large_list() ...
Why are my labels being displayed at the same time in tkinter?
This is an example code of my problem: from tkinter import * root = Tk() def large_list(): my_list = [i for i in range(100000000)] def make_large_list(): my_label = Label(root, text='0% completed') my_label.pack() large_list() my_label2 = Label(root, text='Completed') my_label2.pack() m...
[ "You forgot that inside make_large_list() none of your actions update the GUI. Its only when that function ends that tkinter takes control and processes all the changes.\nNote how when you click on the button is stays in the down state and never animates back to the up state.\nHowever, you can force tkinter to do a...
[ 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074338603_python_tkinter.txt
Q: How to replace Matplotlib bar patches with an exact same size image? How to replace Matplotlib bar patches with an exact same size image so that it can be seen more fancy in some way. I looked up the docs of the Matplotlib Patch, it seems that it can just set face color or edge color, but no way to set an image. A...
How to replace Matplotlib bar patches with an exact same size image?
How to replace Matplotlib bar patches with an exact same size image so that it can be seen more fancy in some way. I looked up the docs of the Matplotlib Patch, it seems that it can just set face color or edge color, but no way to set an image. Also tried the AnnotationBBox, it seems that the params of position can be ...
[ "Instead of trying to change the bars, you can plot the bars unfilled and then just put the image you want on top of each bar (using imshow).\nFor instance:\nimport matplotlib.pyplot as plt\n \nfig, ax = plt.subplots()\n\n# a single bar with some random data\nbar = ax.barh([0,],[90,],fill=False) # note the fi...
[ 0 ]
[]
[]
[ "matplotlib", "python", "visualization" ]
stackoverflow_0074335846_matplotlib_python_visualization.txt
Q: Ordering one list using another list by using an intermediate dictionary loses items in the result There are two lists as follows: names = ["Alice", "Bob", "Bob"] heights = [155, 185, 150] names[i]'s height is heights[i], where i=0,1,2. I want to order names using their height from high to low. That said the outp...
Ordering one list using another list by using an intermediate dictionary loses items in the result
There are two lists as follows: names = ["Alice", "Bob", "Bob"] heights = [155, 185, 150] names[i]'s height is heights[i], where i=0,1,2. I want to order names using their height from high to low. That said the output should be ["Bob", "Alice", "Bob"]. Below is the code I wrote: temp = dict(zip(names, heights)) sort_t...
[ "You are creating a dictionary using the names as key. But a dictionary cannot have each key more than once, therefore the second \"Bob\" (with height 150) overwrites the existing \"Bob\" (with height 185).\nIt's not clear why you create a dictionary at all. Just create a list of tuples directly:\nChange dict(...) ...
[ 3 ]
[]
[]
[ "dictionary", "python", "sorting" ]
stackoverflow_0074338604_dictionary_python_sorting.txt
Q: How do I use line_profiler (from Robert Kern)? I have tried using the line_profiler module for getting a line-by-line profile over a Python file. This is what I've done so far: 1) Installed line_profiler from pypi by using the .exe file (I am on WinXP and Win7). Just clicked through the installation wizard. 2) Wri...
How do I use line_profiler (from Robert Kern)?
I have tried using the line_profiler module for getting a line-by-line profile over a Python file. This is what I've done so far: 1) Installed line_profiler from pypi by using the .exe file (I am on WinXP and Win7). Just clicked through the installation wizard. 2) Written a small piece of code (similar to what has been...
[ "This answer is a copy of my answer here for how to get line_profiler statistics from within a Python script (without using kernprof from the command line or having to add @profile decorators to functions and class methods). All answers (that I've seen) to similar line_profiler questions only describe using kernpro...
[ 80, 21, 5, 5, 4, 0 ]
[]
[]
[ "line_profiler", "profiling", "python", "python_2.7" ]
stackoverflow_0023885147_line_profiler_profiling_python_python_2.7.txt
Q: Running Python from HTML using Javascript with a single button I am trying to get HTML/webpage interface to run a python script I wrote that generates a graph and saves it in a local directory. I would like to click a single button and have the python code run, generate the graph and save it in a folder which then...
Running Python from HTML using Javascript with a single button
I am trying to get HTML/webpage interface to run a python script I wrote that generates a graph and saves it in a local directory. I would like to click a single button and have the python code run, generate the graph and save it in a folder which then HTML could embed it on the HTML page. My issue is this code isn't w...
[ "You'll need a webserver software (as in nginx) which understands how to run python scripts (as in a WSGI application). The script then needs to be something that understands HTTP. Your script needs then to answer with an HTTP response.\nSince you're asking a question on that level, these are many concepts. I sugge...
[ 1 ]
[]
[]
[ "html", "python" ]
stackoverflow_0074338657_html_python.txt
Q: Per line numpy roll Is there an elegant way to perform a per-line roll of a numpy array? Example: >>> arr array([[1, 2, 3, 4], [5, 6, 7, 8]]) >>> desired_func(arr, shift=np.array([1, 2])) array([[4, 1, 2, 3], [7, 8, 5, 6]]) The function np.roll doesn't seem to allow that. A: You can use fancy inde...
Per line numpy roll
Is there an elegant way to perform a per-line roll of a numpy array? Example: >>> arr array([[1, 2, 3, 4], [5, 6, 7, 8]]) >>> desired_func(arr, shift=np.array([1, 2])) array([[4, 1, 2, 3], [7, 8, 5, 6]]) The function np.roll doesn't seem to allow that.
[ "You can use fancy indexing:\n# define the roll per row\nroll = np.array([1, 2])\n\n# compute the rolled indices \nidx = (np.arange(arr.shape[1]) - roll[:,None]) % arr.shape[1]\n\n# index as 2D\nout = arr[np.arange(arr.shape[0])[:,None], idx]\n\noutput:\narray([[4, 1, 2, 3],\n [7, 8, 5, 6]])\n\n" ]
[ 2 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074338631_numpy_python.txt
Q: TensorFlow ValueError: Input 0 of layer "sequential" is incompatible with the layer I am working on a code that loads spectogram data from .npy files using a custom generator using the from_generator function. When I start training the network the error I get is as mentioned in the title. ValueError: Input 0 of la...
TensorFlow ValueError: Input 0 of layer "sequential" is incompatible with the layer
I am working on a code that loads spectogram data from .npy files using a custom generator using the from_generator function. When I start training the network the error I get is as mentioned in the title. ValueError: Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 99, 43, 1), found ...
[ "gen_train_dataset = gen_train_dataset.shuffle(len(train_dataset)).batch(batch_size)\n\n" ]
[ 0 ]
[]
[]
[ "keras", "numpy", "python", "tensorflow" ]
stackoverflow_0074337511_keras_numpy_python_tensorflow.txt
Q: calculate the sum of the effective daily average temperatures I'm new to python and I want to calculate the sum of the daily average temperatures on many hours and then append it to the dataframe e.g : date Temperature 2015-04-01 00:00:00 3.9 2015-04-01 01:00:00 2.10 2015-04-01 02:00:00 4.8 ⋮ ⋮ 2015-10-31 2...
calculate the sum of the effective daily average temperatures
I'm new to python and I want to calculate the sum of the daily average temperatures on many hours and then append it to the dataframe e.g : date Temperature 2015-04-01 00:00:00 3.9 2015-04-01 01:00:00 2.10 2015-04-01 02:00:00 4.8 ⋮ ⋮ 2015-10-31 23:00:00 2.16 I'm trying to get this output: date ...
[ "df['averageT'] = df.resample(rule='D', on='date').transform('mean')\n\n", "I used this as input data:\ndf = pd.DataFrame({\n 'date': [pd.Timestamp('2015-04-01 00:00:00'),pd.Timestamp('2015-04-01 01:00:00'),pd.Timestamp('2015-04-01 02:00:00'),pd.Timestamp('2015-10-31 23:00:00')],\n 'Temperature': [3.9, 2.1,...
[ 0, 0 ]
[]
[]
[ "dataframe", "date", "pandas", "python", "sum" ]
stackoverflow_0074338540_dataframe_date_pandas_python_sum.txt
Q: Python Multiprocessing function not working I am currently learning how to use multiprocessing from Corey Schafer's YouTube video: https://www.youtube.com/watch?v=fKl2JW_qrso&ab_channel=CoreySchafer I am at the 10-minute mark on the video and I had copied my codes exactly like what was shown in the video but the r...
Python Multiprocessing function not working
I am currently learning how to use multiprocessing from Corey Schafer's YouTube video: https://www.youtube.com/watch?v=fKl2JW_qrso&ab_channel=CoreySchafer I am at the 10-minute mark on the video and I had copied my codes exactly like what was shown in the video but the results I have gotten are frustratingly different....
[ "that's because it crashed ... because on windows you should put all \"command\" code inside an if __name__ == \"__main__\": block as follows, function definitions and imports should be before this line.\nimport time\nimport multiprocessing\n\ndef do_something():\n print('Sleeping 1 second....')\n time.sleep(...
[ 2 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0074333349_multiprocessing_python.txt
Q: User input for SPARQL query in a python function I am writing a function in python which calls a SPARQL endpoint of an API. I would like to modify the query (mesh:"+d+" meshv:treeNumber ?treeNum .) according to the user input. Below is my function. def get_disease(d): query = ''' PREFIX rdf: <http://ww...
User input for SPARQL query in a python function
I am writing a function in python which calls a SPARQL endpoint of an API. I would like to modify the query (mesh:"+d+" meshv:treeNumber ?treeNum .) according to the user input. Below is my function. def get_disease(d): query = ''' PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX rdf...
[ "Thank you @UninformedUser. The below changes in the script worked!\n´´´\ndef get_disease(d):\nquery = '''\n PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>\n PREFIX owl: <http://www.w3.org...
[ 0 ]
[]
[]
[ "function", "python", "sparql" ]
stackoverflow_0074331521_function_python_sparql.txt
Q: The Analyzing part of the code don't work properly I try reading data from shown file. After opening the file i need to count the rows on file and trying to split the data for further analyzes (to count total value of the inventory). I don't see where i have mistake, as it counts the rows, but seemingly dont do an...
The Analyzing part of the code don't work properly
I try reading data from shown file. After opening the file i need to count the rows on file and trying to split the data for further analyzes (to count total value of the inventory). I don't see where i have mistake, as it counts the rows, but seemingly dont do anything with the data itself (i have print there to see ...
[ "The issue is that after the first iteration on your file, the second iteration has nothing to iterate on. Moreover, the variable Rivi at the end of the first iteration is the empty string, so its length is 0; this means that the body of the while is not run.\nYou can refactor your code like this:\nfrom dataclasses...
[ 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074338325_python_python_3.x.txt
Q: Django unique_together() for field1 and field2 and vice versa (field2 and field1) It's possible to create duplicate thread with same first_person and second_person using unique_together() in django. class Meta: unique_together = ['first_person', 'second_person'] But just like that, Is it possible to make ...
Django unique_together() for field1 and field2 and vice versa (field2 and field1)
It's possible to create duplicate thread with same first_person and second_person using unique_together() in django. class Meta: unique_together = ['first_person', 'second_person'] But just like that, Is it possible to make it work for same second_person and first_person too ? For example if first_person is ab...
[ "Since django-4.1, you can use functional uniqness filters (and indexes) with a UniqueConstraint [Django-doc], and you thus can determine the lower and greater item:\nfrom django.db import models\nfrom django.db.models.functions import Greatest, Least\n\n# …\n\n\nclass MyModel(models.Model):\n # …\n class Met...
[ 1 ]
[]
[]
[ "django", "django_models", "django_views", "python", "python_3.x" ]
stackoverflow_0074334354_django_django_models_django_views_python_python_3.x.txt
Q: Why this code doesn't fit the given problem? I have to calculate the monthly payment of a debt until it reaches 0 and show the progress, payment by payment. The only variable is that if the guy has more money than the debt, it should be done in 1 payment only. Beecrowd keeps telling me it is wrong. Do you see anyt...
Why this code doesn't fit the given problem?
I have to calculate the monthly payment of a debt until it reaches 0 and show the progress, payment by payment. The only variable is that if the guy has more money than the debt, it should be done in 1 payment only. Beecrowd keeps telling me it is wrong. Do you see anything I could change? I have tried 10 different way...
[ "If I understand the problem correctly then I suggest:\nant = int(input())\np = int(input())\n\ndef doprint(pagamento=1, *, antes, depois):\n print(f\"pagamento: {pagamento}\")\n print(f\"antes = {antes}\")\n print(f\"depois = {depois}\")\n print('-' * 5)\n\nif p < ant:\n pg = 1\n dps = 0\n whi...
[ 0 ]
[]
[]
[ "if_statement", "loops", "python" ]
stackoverflow_0074338680_if_statement_loops_python.txt
Q: Scrapping Text Content of a Tag, But Not Text from Other Tags Inside of First I need to get the text from first <td> element of each <tr>. But not all the text, only the one inside tags <a> and outside of any other tag. I wrote examples of necessary text as "yyy"/"y" and examples of not necessary as "zzz" <table> ...
Scrapping Text Content of a Tag, But Not Text from Other Tags Inside of First
I need to get the text from first <td> element of each <tr>. But not all the text, only the one inside tags <a> and outside of any other tag. I wrote examples of necessary text as "yyy"/"y" and examples of not necessary as "zzz" <table> <tbody> <tr> <td> <b>zzz</b> <a href="#">yyy</a> ...
[ "Try:\nfrom bs4 import BeautifulSoup, Tag, NavigableString\n\nhtml_doc = \"\"\"\\\n<table>\n <tbody>\n <tr>\n <td>\n <b>zzz</b>\n <a href=\"#\">yyy</a>\n \"y\"\n <a href=\"#\">yyy</a>\n <sup>zzz</sup>\n <a href=\"#\">yyy</a>\n <a href=\"#\">yyy</a>\n ...
[ 0, 0 ]
[]
[]
[ "beautifulsoup", "parsing", "python", "selenium", "web_scraping" ]
stackoverflow_0074337881_beautifulsoup_parsing_python_selenium_web_scraping.txt
Q: Why does summing numbers in ascending or descending sorting change the result? I searched the answer to this question a lot, and I found that, in my case, it's the opposite. I am trying to sum single precision float numbers in descending and ascending order to figure it out which one gives the smallest error. Intu...
Why does summing numbers in ascending or descending sorting change the result?
I searched the answer to this question a lot, and I found that, in my case, it's the opposite. I am trying to sum single precision float numbers in descending and ascending order to figure it out which one gives the smallest error. Intuitively I would say in ascending order, since adding small numbers you can get a num...
[ "You should sum them in ascending order. You need to think about how floating point numbers work.\nConsider, for example, summing the following set:\n1\n2\n3\n4\n1,000,000\n2,000,000\n3,000,000\n\nAnd lets assume we're using a computer that only holds 6 significant digits. If you add them in ascending order, you ...
[ 0 ]
[]
[]
[ "python", "single_precision" ]
stackoverflow_0074338677_python_single_precision.txt
Q: Changing array variable changes another variable In python, when I append to the "sim" variable the "history" variable changes. history = [[[1],[2],[3],[4],[5]]] sim = list(history[0]) sim[0].append(5) Result: [[[1, 5], [2], [3], [4], [5]]] How do I fix this? Thank you for your help! A: From the built-in copy ...
Changing array variable changes another variable
In python, when I append to the "sim" variable the "history" variable changes. history = [[[1],[2],[3],[4],[5]]] sim = list(history[0]) sim[0].append(5) Result: [[[1, 5], [2], [3], [4], [5]]] How do I fix this? Thank you for your help!
[ "From the built-in copy module's docs:\n\nAssignment statements in Python do not copy objects, they create\nbindings between a target and an object. For collections that are\nmutable or contain mutable items, a copy is sometimes needed so one\ncan change one copy without changing the other. This module provides\nge...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074338646_python.txt
Q: What should be the input shape for ConvLSTM1D I have a time-series dataset which is having 10000 samples and 50 features, I want to use ConvLSTM for prediction for that I am using TensorFlow for implementation but I am getting the below error Input 0 of layer "conv_lstm1d_10" is incompatible with the layer: expect...
What should be the input shape for ConvLSTM1D
I have a time-series dataset which is having 10000 samples and 50 features, I want to use ConvLSTM for prediction for that I am using TensorFlow for implementation but I am getting the below error Input 0 of layer "conv_lstm1d_10" is incompatible with the layer: expected ndim=4, found ndim=3. Full shape received: (None...
[ "For time-series data, You can use LSTM with this strucutre : (input_shape=(time_steps, features)) and for your problem : (10000, 50).\nTry this:\nmodel = tf.keras.models.Sequential(\n [\n tf.keras.layers.LSTM(filters=64, kernel_size=3, activation='relu', \n input_shape=(len(df...
[ 0 ]
[]
[]
[ "data_science", "python", "tensorflow" ]
stackoverflow_0074338808_data_science_python_tensorflow.txt
Q: Is there a way to resample a pandas dataframe with minute data to daily data? I'm using the following script to take a csv with minute data and perform some operations like adding new data columns with calculations. As an edit to include csv data as mentioned in comments: 2022/11/05 23:40:02,1000.13575463,0.02115 ...
Is there a way to resample a pandas dataframe with minute data to daily data?
I'm using the following script to take a csv with minute data and perform some operations like adding new data columns with calculations. As an edit to include csv data as mentioned in comments: 2022/11/05 23:40:02,1000.13575463,0.02115 2022/11/05 23:41:01,1000.13575463,0.0147 2022/11/05 23:42:02,1000.13573563,0.01058 ...
[ "As the error says (and the comments imply), .resample() produces an groupby-like object that is ready to perform reducing operations, such as sum(), mean(), size(), count(), etc. Without one of these operations, the resampling operation is undefined.\nIn other words, what you are doing is similar to:\ngb = df.gro...
[ 1, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074336742_dataframe_pandas_python.txt
Q: how to select some value from multiple table in Django? I want to to select some students from table A where students username and class code are not inside table B. So it will show all student that not inside the student class list yet. the query was like SELECT students from TableA WHERE username NOT IN tableB A...
how to select some value from multiple table in Django?
I want to to select some students from table A where students username and class code are not inside table B. So it will show all student that not inside the student class list yet. the query was like SELECT students from TableA WHERE username NOT IN tableB AND classcode = CODE models.py class modelStudentclassss m(mo...
[ "You can work with:\nStudentclass.objects.exclude(username__in=User.objects.values('username')).filter(\n classcode=code\n)\n\n\nNote: Models normally have no Model… prefix. Therefore it might be better to rename modelUser to User.\n\n\n\nNote: Specifying null=False [Django-doc] is not necessary: fields are by d...
[ 0 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0074338926_django_mysql_python.txt
Q: Check if EXACT string is in file. Python Programme that checks if password is in file. File is from a different programme that generates a password. The problem is that I want to check if the exact password is in the file not parts of the password. Passwords are each on newlines. For example, when password = 'CrGQ...
Check if EXACT string is in file. Python
Programme that checks if password is in file. File is from a different programme that generates a password. The problem is that I want to check if the exact password is in the file not parts of the password. Passwords are each on newlines. For example, when password = 'CrGQlkGiYJ95' : ...
[ "One option assuming you have one password per line:\ndef check():\n with open(FILENAME, 'r') as myfile:\n return any(password == x.strip() for x in myfile.readlines())\n\nUsing a generator enables to stop immediately if there is a match.\nIf you need to repeat this often, the best would be to build a set...
[ 1 ]
[]
[]
[ "file", "python" ]
stackoverflow_0074338871_file_python.txt
Q: How to strip off left side of binary number in Python? I got this binary number 101111111111000 I need to strip off the 8 most significant bits and have 11111000 at the end. I tried to make 101111111111000 << 8, but this results in 10111111111100000000000, it hasn't the same effect as >> which strips the lower bit...
How to strip off left side of binary number in Python?
I got this binary number 101111111111000 I need to strip off the 8 most significant bits and have 11111000 at the end. I tried to make 101111111111000 << 8, but this results in 10111111111100000000000, it hasn't the same effect as >> which strips the lower bits. So how can this be done? The final result MUST BE binary ...
[ "You can get the rightmost 8 bits of an integer n using bitwise-and:\nn&255\n\n255 is the sum of the values of the smallest 8 bits.\nSo, starting with 101111111111000, which is 24568 decimal, n&255 gives 11111000, which is 248 decimal. \n", "another general way to do this is:\nn = int('101111111111000', 2) # 2456...
[ 4, 1, 0, 0 ]
[]
[]
[ "binary", "python" ]
stackoverflow_0053472702_binary_python.txt
Q: VS22 python - txt file in project and labeled as content cannot be found I've been receiving this error for quite some time on a few assignments. Message=[Errno 2] No such file or directory: 'frankenstein.txt' Source=C:\Users\richy\OneDrive\Documents\Python Scripts\CIS 521\CIS 521\CIS 521\Homework8\homework8....
VS22 python - txt file in project and labeled as content cannot be found
I've been receiving this error for quite some time on a few assignments. Message=[Errno 2] No such file or directory: 'frankenstein.txt' Source=C:\Users\richy\OneDrive\Documents\Python Scripts\CIS 521\CIS 521\CIS 521\Homework8\homework8.py StackTrace: File "C:\Users\richy\OneDrive\Documents\Python Scripts\CIS ...
[ "I have created a file frankenstein.txt with the following content:\nfrankenstein\n\nThe file frankenstein.txt is in the folder C:\\Users\\richy\\OneDrive\\Documents\\Python Scripts\\CIS 521\\CIS 521\\CIS 521\\Homework8.\nI have executed the code below:\npath = \"C:\\\\Users\\\\richy\\\\OneDrive\\\\Documents\\\\Pyt...
[ 0 ]
[]
[]
[ "python", "visual_studio_project" ]
stackoverflow_0074338360_python_visual_studio_project.txt
Q: Add (1,2) shape of array to (1, 10, 2) shape of array. result (1, 11, 2) A = [[2 , 3]] A = np.array(A) A.shape, A shape A -> (1,2) A -> array([[2, 3]]) B = [[[5, 7], [4, 8]]] B = np.array(B) B.shape -> (1, 2, 2) B -> array([[[5, 7], [4, 8]]])) Now I want to append A to B. The result should be the s...
Add (1,2) shape of array to (1, 10, 2) shape of array. result (1, 11, 2)
A = [[2 , 3]] A = np.array(A) A.shape, A shape A -> (1,2) A -> array([[2, 3]]) B = [[[5, 7], [4, 8]]] B = np.array(B) B.shape -> (1, 2, 2) B -> array([[[5, 7], [4, 8]]])) Now I want to append A to B. The result should be the shape of -> (1, 3, 2) The array should look like: array([[[5, 7], [...
[ "You can use np.concatenate. Sample code:\nnp.concatenate([B, A[:,np.newaxis,:]], axis=1)\n\nResult:\narray([[[5, 7],\n [4, 8],\n [2, 3]]])\n\n" ]
[ 0 ]
[]
[]
[ "append", "arrays", "np", "python", "reshape" ]
stackoverflow_0074338921_append_arrays_np_python_reshape.txt
Q: OpenCV 'NoneType' object has no attribute 'shape' I am trying to get this to work: https://circuitdigest.com/tutorial/real-life-object-detection-using-opencv-python-detecting-objects-in-live-video (scroll to the 'Object detection using ORB' part) ` import cv2 import numpy as np def ORB_detector(new_image, image_t...
OpenCV 'NoneType' object has no attribute 'shape'
I am trying to get this to work: https://circuitdigest.com/tutorial/real-life-object-detection-using-opencv-python-detecting-objects-in-live-video (scroll to the 'Object detection using ORB' part) ` import cv2 import numpy as np def ORB_detector(new_image, image_template): # Function that compares input image to ...
[ "Your read is not returning a frame. The following code:\ncap = cv2.VideoCapture(0)\nret, frame = cap.read()\n\nshould check if you actually managed to read a frame. cap.read() will return False if it failed, so you need to:\nif not ret:\n print(\"Couldn't read a frame!\")\n ... do something to handle this fa...
[ 0 ]
[]
[]
[ "numpy", "opencv", "python" ]
stackoverflow_0074338968_numpy_opencv_python.txt
Q: Change parameter inside button command every loop I have a for loop which iterates through a list. I have a counter that increases with every loop, which is supplied as the parameter. I want the counter to increase by 1 every loop where it is then supplied as the new parameter for that button command (similar to t...
Change parameter inside button command every loop
I have a for loop which iterates through a list. I have a counter that increases with every loop, which is supplied as the parameter. I want the counter to increase by 1 every loop where it is then supplied as the new parameter for that button command (similar to the original command where each button has a different v...
[ "Unfortunately the lambda only captures index once. You can force it to capture a different one each time:\n items.config(command = lambda index = index: self.get_location(index))\n\n" ]
[ 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074338894_python_tkinter.txt
Q: PyQt5, asyncqt | asyncSlot() still freezes the event loop The problem is that even though I put the function in a separate thread, the window still does not respond to actions until it is fully executed. What is the problem? Just ctrl+c, ctrl+v the code below, you will see what i mean. If you have any questions, f...
PyQt5, asyncqt | asyncSlot() still freezes the event loop
The problem is that even though I put the function in a separate thread, the window still does not respond to actions until it is fully executed. What is the problem? Just ctrl+c, ctrl+v the code below, you will see what i mean. If you have any questions, feel free to ask import sys import asyncio from asyncqt import ...
[ "Function time.sleep(5) is blocking, and await asyncio.sleep(5) is non-blocking.\n" ]
[ 0 ]
[]
[]
[ "asynchronous", "pyqt5", "python" ]
stackoverflow_0074339072_asynchronous_pyqt5_python.txt
Q: Where does flask look for image files? I am setting up a local server using flask. All I want to do currently is display an image using the img tag in the index.html page. But I keep getting error GET http://localhost:5000/ ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg 404 (NOT FOUND) Where does flask lo...
Where does flask look for image files?
I am setting up a local server using flask. All I want to do currently is display an image using the img tag in the index.html page. But I keep getting error GET http://localhost:5000/ ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg 404 (NOT FOUND) Where does flask look for files? A Little help would be great. ...
[ "Is the image file ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg in your static directory? If you move it to your static directory and update your HTML as such:\n<img src=\"/static/ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg\">\n\nIt should work.\nAlso, it is worth noting, there is a better way to str...
[ 138, 46, 9, 9, 0 ]
[]
[]
[ "file_upload", "flask", "python", "web_development_server" ]
stackoverflow_0028207761_file_upload_flask_python_web_development_server.txt
Q: Create a program that allows the user to convert a range of values from feet to centimeter or centimeter to feet I'm having a hard time including the conversion rates and the range. Can you help me with this? I'm a beginner programming in Python. Thank you so much. (https://i.stack.imgur.com/0PW99.jpg)] Sample of ...
Create a program that allows the user to convert a range of values from feet to centimeter or centimeter to feet
I'm having a hard time including the conversion rates and the range. Can you help me with this? I'm a beginner programming in Python. Thank you so much. (https://i.stack.imgur.com/0PW99.jpg)] Sample of expected output: This program will convert a range of LENGTH Enter (F) to convert Feet to Centimeter Enter (C to con...
[ "Try this code\nprint(\"This program will convert a range of LENGTH \")\nprint(\"Enter (F) to convert Feet to Centimeter\")\nprint(\"Enter (C) to convert Centimeter to Feet\")\nprint()\nfeet = 'F'\ncentimeter = 'C'\nwhich = input(\"Enter Selection: \", )\nmeas_start = int(input(\"Enter starting length to convert: ...
[ 0, 0 ]
[]
[]
[ "python", "range" ]
stackoverflow_0074338110_python_range.txt
Q: Python dictConfig time rotation not working I want daily rotation logs. I set this dictConfig and this config creates log file dinfo.log but not rotating it even after I waited 1 day. What's wrong? 'info_time_handler': { 'class': 'logging.handlers.TimedRotatingFileHandler', 'level': 'INFO', ...
Python dictConfig time rotation not working
I want daily rotation logs. I set this dictConfig and this config creates log file dinfo.log but not rotating it even after I waited 1 day. What's wrong? 'info_time_handler': { 'class': 'logging.handlers.TimedRotatingFileHandler', 'level': 'INFO', 'formatter': 'simple', "when": "d", #...
[ "Rotation only happens when you actually log an event and it gets to the handler. So if you have a long-lived process that doesn't log at INFO (the level you set in your snippet) or above regularly, then you may not see rollover until that happens. You waited a day, but did something get logged at INFO or higher on...
[ 0 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0074338587_logging_python.txt
Q: Python: Print a list with recursion I have these two test cases: calc1 = [['print', 5]] # 5 calc2 = [['print', 2], ['print', 4], ['print', 8]] # 2 4 8 And I can print them correctly with this function: def exec_program(p): if len(p) == 1: print(p[0][1]) else: for i in p: print(...
Python: Print a list with recursion
I have these two test cases: calc1 = [['print', 5]] # 5 calc2 = [['print', 2], ['print', 4], ['print', 8]] # 2 4 8 And I can print them correctly with this function: def exec_program(p): if len(p) == 1: print(p[0][1]) else: for i in p: print(i[1]) print(exec_program(calc2)) >>> 2 >...
[ "def do_print(calc):\n if not calc:\n return\n if calc[0] == 'print':\n print(calc[1])\n else:\n for subcalc in calc:\n do_print(subcalc)\n\nThat will work for any depth of nested lists.\nYou will want to add some error checking on the inputs, better yet use some more strict ...
[ 2, 0, 0 ]
[]
[]
[ "python", "recursion" ]
stackoverflow_0074339099_python_recursion.txt
Q: How to create a deployable Python Lamba zip using Poetry I've been spending a few days trying to figure out how best to build a Python Lambda bundle when using Poetry. I found a few blogs that that outline the same technique but those didn't work in my situation. The solution provided in the blogs is to use pip in...
How to create a deployable Python Lamba zip using Poetry
I've been spending a few days trying to figure out how best to build a Python Lambda bundle when using Poetry. I found a few blogs that that outline the same technique but those didn't work in my situation. The solution provided in the blogs is to use pip install to install the needed dependencies into a specific direc...
[ "Ultimately I found this documentation from AWS for how to create a lambda archive from a Python virtual environment. Using Poetry's install command, I was able to install just the main runtime dependencies into the Poetry projects created virtual environment, including any local path based dependencies. However, t...
[ 0, 0 ]
[]
[]
[ "aws_lambda", "python", "python_poetry" ]
stackoverflow_0074292510_aws_lambda_python_python_poetry.txt
Q: Docker arguments work w/ COPY but not ADD Got this solved! I learned my smart quotes lesson the hard way... Although, now that I know this- I find it crazy that Docker themselves used smart quotes in this tutorial: https://www.docker.com/blog/how-to-dockerize-your-python-applications/ Just want to figure this out...
Docker arguments work w/ COPY but not ADD
Got this solved! I learned my smart quotes lesson the hard way... Although, now that I know this- I find it crazy that Docker themselves used smart quotes in this tutorial: https://www.docker.com/blog/how-to-dockerize-your-python-applications/ Just want to figure this out for my edification.. Just learning Docker and ...
[ "It's not the ADD or COPY causing this issue, it's the two different CMD statements you're using:\n\nCMD [“python”, “./main.py”]\nCMD [\"python\", \"./main.py\"]\n\nReplace the smart quotes with normal quotes, and you should be good.\n" ]
[ 1 ]
[]
[]
[ "docker", "python", "python_3.x" ]
stackoverflow_0074339187_docker_python_python_3.x.txt
Q: How to capture pygame screen? How can I capture and save a sequence of images or a video of a pygame screen? Basically I want to share my game video on youtube. Also, want to make a tutorial. The game is rendered mainly in a loop: def main(): while True: GetInput() Move() Shift() ...
How to capture pygame screen?
How can I capture and save a sequence of images or a video of a pygame screen? Basically I want to share my game video on youtube. Also, want to make a tutorial. The game is rendered mainly in a loop: def main(): while True: GetInput() Move() Shift() Draw() With the Draw() function...
[ "Use pygame.image.save on your screen surface:\nwindow = pygame.display.set_mode(...)\n\n...\n\npygame.image.save(window, \"screenshot.jpeg\")\n\nNote that this will slow down your program tremendously. If it is time-based, you may wish to fake the framerate when doing a capture.\n", "The accepted answer said you...
[ 42, 1, 1, 0 ]
[]
[]
[ "pygame", "python", "video_capture" ]
stackoverflow_0006087484_pygame_python_video_capture.txt
Q: Keras get optimal AUC threshold for a model I have trained a binary classifier with Keras. This is the model definition: model_binary = Sequential() model_binary.add(layers.Dense(64, activation='relu',input_shape=(7,))) model_binary.add(layers.Dropout(0.5)) model_binary.add(layers.Dense(32, activation='relu')) mod...
Keras get optimal AUC threshold for a model
I have trained a binary classifier with Keras. This is the model definition: model_binary = Sequential() model_binary.add(layers.Dense(64, activation='relu',input_shape=(7,))) model_binary.add(layers.Dropout(0.5)) model_binary.add(layers.Dense(32, activation='relu')) model_binary.add(layers.Dropout(0.5)) model_binary.a...
[ "Notes | points 1 and 2 are optional readings\n\nSince you have a skewed dataset, the AUC metric with the PR curve might be more insightful. Please feel free to see the paper entitled \"The Precision-Recall Plot Is More Informative than the ROC Plot When Evaluating Binary Classifiers on Imbalanced Datasets\" by Sai...
[ 1 ]
[]
[]
[ "keras", "python", "statistics", "tensorflow" ]
stackoverflow_0074258564_keras_python_statistics_tensorflow.txt
Q: ImportError: DLL load failed while importing open3d_pybind: The specified module could not be found I see that other users have also run into this issue when using Pycharm, but coundn't find a fix when error with import open3d. I have tried the approaches suggested however, adding to Path did not work (Windows 10)...
ImportError: DLL load failed while importing open3d_pybind: The specified module could not be found
I see that other users have also run into this issue when using Pycharm, but coundn't find a fix when error with import open3d. I have tried the approaches suggested however, adding to Path did not work (Windows 10). Many thanks for your help! The error message is: I tried adding the following Environment variables to...
[ "After several tries, the only thing that worked for me was install CUDA (and visual studio before, because demanded by CUDA). I had forgotten that wasn't installed since my reinstallation of windows operating system...\n", "Found a solution! The issue was multiple versions of Python installed. I deleted Anaconda...
[ 1, 0 ]
[]
[]
[ "importerror", "open3d", "python" ]
stackoverflow_0068820367_importerror_open3d_python.txt
Q: AttributeError: 'float' object has no attribute 'lower' I'm facing this attribute error and I'm stuck at how to handle float values if they appear in a tweet.The streaming tweet has to be lower cased and tokenized so i have used split function. Can somebody please help me to deal with it, any workaround or solutio...
AttributeError: 'float' object has no attribute 'lower'
I'm facing this attribute error and I'm stuck at how to handle float values if they appear in a tweet.The streaming tweet has to be lower cased and tokenized so i have used split function. Can somebody please help me to deal with it, any workaround or solution ..? Here's the error which m gettin.... AttributeError ...
[ "Thank you @Dick Kniep. Yes,it is Pandas CSV reader. Your suggestion worked.\nFollowing is the python code which worked for me by specifying the field datatype,\n(in this case, its string)\np_test = pd.read_csv('TrainSA.csv')\np_test.SentimentText=p_test.SentimentText.astype(str)\n\n", "I get the feeling that you...
[ 41, 19, 4, 3, 0, 0 ]
[]
[]
[ "python", "sentiment_analysis", "tweets", "twitter" ]
stackoverflow_0034724246_python_sentiment_analysis_tweets_twitter.txt
Q: Python - Including frequency table at the beginning of a Huffman-compressed file I am trying to implement Huffman compression and decompression of files, where all the information needed to decompress must be included in the compressed file. For this implementation I want to include the frequency table in the comp...
Python - Including frequency table at the beginning of a Huffman-compressed file
I am trying to implement Huffman compression and decompression of files, where all the information needed to decompress must be included in the compressed file. For this implementation I want to include the frequency table in the compressed file, such that the decompression program can rebuild the Huffman codes from th...
[ "No, you do not want to include the frequency table in your compressed data. You are trying to compress, so you want to use as few bits as possible to provide the information required to decompress. Sending the frequency table is the worst way to do that. The frequency table contains extraneous information that is ...
[ 2, 0 ]
[]
[]
[ "compression", "huffman_code", "python", "python_3.x" ]
stackoverflow_0074338685_compression_huffman_code_python_python_3.x.txt
Q: Python - Binding different names to equal objects, turns out Python considers them the same I fear my question is extremely basic but in spite of an extensive search I could not make any sense of it. I found the following snippet at Geeks for Geeks a = "first" b = "first" print(id(a)) print(id(b)) print(a is b) ...
Python - Binding different names to equal objects, turns out Python considers them the same
I fear my question is extremely basic but in spite of an extensive search I could not make any sense of it. I found the following snippet at Geeks for Geeks a = "first" b = "first" print(id(a)) print(id(b)) print(a is b) The output being True, the snippet demonstrates how names are bound to immutable objects such a...
[ "As far as I understand, there is no guarantee that a is b for your example code. It probably is a CPython optimization.\nThe documentation of id() says:\n\nThis is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the s...
[ 1 ]
[]
[]
[ "binding", "parameter_passing", "python" ]
stackoverflow_0074326874_binding_parameter_passing_python.txt
Q: How to automatically generate versions for python packages in a monorepo? When it comes to generate versions using conventional commits from a repo that contains only one python package things are easy, you just need to use one tool that loops through all the repo commits and compute the version by parsing these c...
How to automatically generate versions for python packages in a monorepo?
When it comes to generate versions using conventional commits from a repo that contains only one python package things are easy, you just need to use one tool that loops through all the repo commits and compute the version by parsing these conventional commits (break-change=major, feat=minor, fix=patch), so far so good...
[ "Here is an example of how we do it with Reliza Hub (out tool): https://github.com/relizaio/rebom/blob/master/.github/workflows/github_actions.yml\nIdea:\n\nEvery push generates a release per branch that is stored in the tool.\nThe tool is also responsible for producing next release version based on chosen schema (...
[ 0 ]
[]
[]
[ "conventional_commits", "monorepo", "python", "version_control", "versioning" ]
stackoverflow_0074335331_conventional_commits_monorepo_python_version_control_versioning.txt
Q: Trying to draw a 'box' using python recursion I am trying to use python recursion in order to draw a box, but have a hard time finding where to start. In principle I want to pass two numbers as arguments which will be the amount of '*''s that are printed both vertically and horizontally like this: >>> drawRectangl...
Trying to draw a 'box' using python recursion
I am trying to use python recursion in order to draw a box, but have a hard time finding where to start. In principle I want to pass two numbers as arguments which will be the amount of '*''s that are printed both vertically and horizontally like this: >>> drawRectangle(4, 4) **** * * * * ****
[ "Whenever you are requesting a help from community you need to tell what you have tried so far, this way other members don't have to start from scratch.\ndef box(n, c, k): # n=number of rows, c=number of cols, k=number of rows to keep the track of original number\n if n>0 and c>0:\n if n==1:\n print(\"*\"*...
[ 0, 0 ]
[]
[]
[ "drawing", "outline", "python", "recursion" ]
stackoverflow_0074339181_drawing_outline_python_recursion.txt
Q: How to write WHERE Sql Statement I want to write a WHERE statement, but it shows either error: not such table or nothing i tried statements in the pic and expected a filtered table A: Can you try the fully qualified name? Something like "Select * from test_db.CreditCardApps where (rest of statment here)" If tha...
How to write WHERE Sql Statement
I want to write a WHERE statement, but it shows either error: not such table or nothing i tried statements in the pic and expected a filtered table
[ "Can you try the fully qualified name?\nSomething like \"Select * from test_db.CreditCardApps where (rest of statment here)\"\nIf that still doesn't work it might be this command line utility (sqllite3) that may be the problem.\nCan I ask, what exactly are you trying to do? There may be an easier way.\n" ]
[ 0 ]
[]
[]
[ "python", "where_clause" ]
stackoverflow_0074339332_python_where_clause.txt
Q: Have different sorting orders in single column in pandas I'm trying to sort a small df by values in two columns, but I need different sorting orders (ascending/descending) for column A (price) depending on the values in column B (action). So the df looks like this: dfindex price action 4 0.9 'sell' 7 0.7 'buy' ...
Have different sorting orders in single column in pandas
I'm trying to sort a small df by values in two columns, but I need different sorting orders (ascending/descending) for column A (price) depending on the values in column B (action). So the df looks like this: dfindex price action 4 0.9 'sell' 7 0.7 'buy' 2 0.9 'buy' 3 0.4 'sell' 6 0.6 'sell' 5 0.8 'bu...
[ "make 2 columns named sort1 and sort2 for sorting\nsort1 column divide between group buy and group sell\nbuy group have negative price in sort2 column\nthen sort by sort1 and sort2\n(df\n .sort_values('dfindex')\n .assign(sort1=df1['action'].ne(df1['action'].shift(1)).cumsum())\n .assign(sort2=df1['price'].mask(df1...
[ 1 ]
[]
[]
[ "data_science", "pandas", "python", "sorting" ]
stackoverflow_0074339180_data_science_pandas_python_sorting.txt
Q: Interdependent Validation for Pydantic Model Fields I have a model for a FastAPI request and I want to add some validation for its fields. from pydantic import BaseModel from typing import List, Optional class RequestModel(BaseModel): types: List[str] segments: Optional[List[str]] = [] For the above snip...
Interdependent Validation for Pydantic Model Fields
I have a model for a FastAPI request and I want to add some validation for its fields. from pydantic import BaseModel from typing import List, Optional class RequestModel(BaseModel): types: List[str] segments: Optional[List[str]] = [] For the above snippet I want to ensure that segments list should only conta...
[ "You mean like this?\nfrom typing import Any\n\nfrom pydantic import BaseModel, ValidationError, root_validator\n\n\nclass RequestModel(BaseModel):\n types: list[str]\n segments: list[str] = []\n\n @root_validator\n def my_validator(cls, values: dict[str, Any]) -> dict[str, Any]:\n if len(values....
[ 0 ]
[]
[]
[ "fastapi", "pydantic", "python", "python_3.x" ]
stackoverflow_0074338246_fastapi_pydantic_python_python_3.x.txt
Q: 'numpy.ndarray' object has no attribute 'load_img' I am a beginner to this and I am unsure how to overcome this problem. Cleary variable img is a numpy array. I am unsure how to amend this. I have tried allot but I doubt it is relevant. If there is more required, feel free to ask. A: image is already a numpy arr...
'numpy.ndarray' object has no attribute 'load_img'
I am a beginner to this and I am unsure how to overcome this problem. Cleary variable img is a numpy array. I am unsure how to amend this. I have tried allot but I doubt it is relevant. If there is more required, feel free to ask.
[ "image is already a numpy array.\njust put:\nx = image\n\nrest you can keep the same\nIf you are passing image as a filepath or string, your code will work\n" ]
[ 0 ]
[]
[]
[ "dataset", "image", "numpy", "python", "tensorflow" ]
stackoverflow_0074339414_dataset_image_numpy_python_tensorflow.txt
Q: Comparing results with Beautiful Soup in Python I've got the following code that filters a particular search on an auction site. I can display the titles of each value & also the len of all returned values: from bs4 import BeautifulSoup import requests url = requests.get("https://www.trademe.co.nz/a/marketplace/m...
Comparing results with Beautiful Soup in Python
I've got the following code that filters a particular search on an auction site. I can display the titles of each value & also the len of all returned values: from bs4 import BeautifulSoup import requests url = requests.get("https://www.trademe.co.nz/a/marketplace/music-instruments/instruments/guitar-bass/electric-gu...
[ "With length-comparison, there is the issue of some results being removed between checks, so it might look like there are no new results even if there are; and text-comparison does not account for results with similar titles.\nI can suggest 3 other methods. (The 3rd uses my preferred approach.)\n\n\nClosing time\n\...
[ 0, 0 ]
[]
[]
[ "beautifulsoup", "comparison", "list", "python", "web_scraping" ]
stackoverflow_0074300154_beautifulsoup_comparison_list_python_web_scraping.txt
Q: Python multiple csv files onto 1 plot I am trying to plot multiple csv files within a folder onto 1 single graph, but when I try to plot the graph and call the plt.plot(x="..",y=".."), I get an 'unexpected keyword' argument I am unsure where I am going wrong, if anyone has any ideas, that would be great from matpl...
Python multiple csv files onto 1 plot
I am trying to plot multiple csv files within a folder onto 1 single graph, but when I try to plot the graph and call the plt.plot(x="..",y=".."), I get an 'unexpected keyword' argument I am unsure where I am going wrong, if anyone has any ideas, that would be great from matplotlib import pyplot as plt import os import...
[ "The plot function from matplotlib.pyplot does not have x or y keyword parameters. You can simply pass x and y (and optional formatting) like plot(x, y, 'bo').\nSee the matplotlib documentations for more.\n" ]
[ 0 ]
[]
[]
[ "graph", "matplotlib", "python" ]
stackoverflow_0074339373_graph_matplotlib_python.txt
Q: How do I extract the keys of a dictionary based on a conditional? I am asked to extract the dates of dictionary in which the values exceed the input threshold. See code beneath: def get_dates(prices,threshold): {k:v for k,v in prices if threshold>130} prc = [ { 'price': 1279.79, 'date': '2020-01-0...
How do I extract the keys of a dictionary based on a conditional?
I am asked to extract the dates of dictionary in which the values exceed the input threshold. See code beneath: def get_dates(prices,threshold): {k:v for k,v in prices if threshold>130} prc = [ { 'price': 1279.79, 'date': '2020-01-01' }, { 'price': 139.01, 'date': '2020-01-02' }, { 'price': 134...
[ "You can use list comprehensions and return dicts if the price is larger than the threshold.\nWhy dict.get(key) instead of dict[key]?\n# we use 'dict.get' with default value '0' for price if don't exists.\ndef get_dates(prices,threshold):\n return [dct['date'] for dct in prices if dct.get('price', 0) > threshold...
[ 1, 1, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074339390_dictionary_python.txt
Q: Avoid creating duplicate class instances I am working with a very large dataset, and am looping over chunks of data to add elements to a class. There are many duplicated values in my data, meaning that I am creating a class instance for the same data many times. From some of the testing I've done, it seems that ac...
Avoid creating duplicate class instances
I am working with a very large dataset, and am looping over chunks of data to add elements to a class. There are many duplicated values in my data, meaning that I am creating a class instance for the same data many times. From some of the testing I've done, it seems that actually creating the instance of the class is t...
[ "seen can be used as cache to associate the person _id with an already created Person object.\nThis can look like (code up to and including the main for-loop, remaining code doesn't need a change):\nseen = {}\nteam_directory = defaultdict(list)\n\nstart_time = time.time()\nfor team in teams:\n for i, person in e...
[ 1, 0 ]
[]
[]
[ "performance", "python" ]
stackoverflow_0074335047_performance_python.txt
Q: appJar keyboard events while the window is not focused - Python I'm trying to write some code that checks if any keys are pressed while we have a GUI with appJar and it's not focused. So if the "v" key is pressed it will write something to the console while we are focused in the program window, but I want somethin...
appJar keyboard events while the window is not focused - Python
I'm trying to write some code that checks if any keys are pressed while we have a GUI with appJar and it's not focused. So if the "v" key is pressed it will write something to the console while we are focused in the program window, but I want something to be written even if we are not focused on the program window. App...
[ "You have to use the' keyboard' module to catch the v key event when the window is not focused.\nimport appJar\nimport keyboard\n\napp = appJar.gui()\n\ndef keyPress(key):\n global startStop\n if key == \"v\":\n print(0)\n\napp.setSize(\"550x350\")\napp.setResizable(canResize=False)\napp.setBg(\"white\"...
[ 0 ]
[]
[]
[ "appjar", "keyevent", "python", "user_interface" ]
stackoverflow_0074339456_appjar_keyevent_python_user_interface.txt
Q: How to make a new list by comparing pandas Dataframe Columns with Set I have already a set named "bad_outcomes" and a dataframe where a column name is "Outcome". Using the "Outcome", I want to create a list where the element is 0 if the corresponding row in Outcome is in the set bad_outcomes; otherwise, it's 1. Th...
How to make a new list by comparing pandas Dataframe Columns with Set
I have already a set named "bad_outcomes" and a dataframe where a column name is "Outcome". Using the "Outcome", I want to create a list where the element is 0 if the corresponding row in Outcome is in the set bad_outcomes; otherwise, it's 1. Then I want to assign it to the variable 'landing_class'. I have written this...
[ "First, the return of this condition is df['Outcome'].isin(set(bad_outcomes)) is a series of true and false values like that if {true, true, false,....} and that is invalid input to if-statement. In order to solve this problem, you need to use one of the functions such as all() or any().\nBut adding any or all only...
[ 2, 0, 0 ]
[]
[]
[ "conditional_statements", "database", "pandas", "python", "set" ]
stackoverflow_0068812620_conditional_statements_database_pandas_python_set.txt
Q: Django custom form - cleaned_data has incorrect values for IntegerField In my Django app (v. 3.1), I've added a custom form to trigger a data export that, among other things, can collect two integer values that represent years in a date range. When the form is submitted, no matter what values the user has set in t...
Django custom form - cleaned_data has incorrect values for IntegerField
In my Django app (v. 3.1), I've added a custom form to trigger a data export that, among other things, can collect two integer values that represent years in a date range. When the form is submitted, no matter what values the user has set in the number fields, the values that appear in the form's cleaned_data attribute...
[ "In your form definition you have\nyear_from = forms.IntegerField(required=False, disabled=True,\n\nFrom the docs\n\nThe disabled boolean argument, when set to True, disables a form field\nusing the disabled HTML attribute so that it won’t be editable by\nusers. Even if a user tampers with the field’s value submitt...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074338523_django_python.txt
Q: No module named "netifaces" during "Vagrant Up" When I do vagrant up, I get the following error: The following SSH command responded with a non-zero exit status. Vagrant assumes that this means the command failed! mv -f '/tmp/vagrant-network-entry-1624290630' '/etc/netplan/50-vagrant.yaml' chown root:root '/etc/n...
No module named "netifaces" during "Vagrant Up"
When I do vagrant up, I get the following error: The following SSH command responded with a non-zero exit status. Vagrant assumes that this means the command failed! mv -f '/tmp/vagrant-network-entry-1624290630' '/etc/netplan/50-vagrant.yaml' chown root:root '/etc/netplan/50-vagrant.yaml' chmod 0644 '/etc/netplan/50-v...
[ "sudo -H will install for the current user. For netplan to work, it should be installed for root.\nInstall the package for root:\nsudo python3 -m pip install --force-reinstall --no-cache-dir netifaces\n\n", "You can try sudo apt-get update -y and then sudo apt-get install -y python3-netifaces\n" ]
[ 1, 0 ]
[]
[]
[ "python", "python_netifaces", "vagrant" ]
stackoverflow_0068071042_python_python_netifaces_vagrant.txt
Q: A problem i'm facing concerning if and elif fonction the cost of renting a car per day is 40 dollars. if the days you rented the car in is equal or superior to 7 you get 50 dollars off the total cost if the days you rented the car in is equal or superior to 3 you get 20 dollars off the total cost You can't get bot...
A problem i'm facing concerning if and elif fonction
the cost of renting a car per day is 40 dollars. if the days you rented the car in is equal or superior to 7 you get 50 dollars off the total cost if the days you rented the car in is equal or superior to 3 you get 20 dollars off the total cost You can't get both reductions at the same time............. days=raw_input(...
[ "I simply tried this code\ndays=8\ncost= 40*days\nif days>=7:\ncost-=50\nelif days>=3 and days<7:\ncost-=20 \nprint(cost)\n\nAnd other options of Days. the code is working alright\n" ]
[ 0 ]
[]
[]
[ "if_statement", "python" ]
stackoverflow_0074339474_if_statement_python.txt
Q: Why does tkinter creating two windows here? And how can i stop it? import tkinter as tk from subprocess import check_call def copy_name(): cmd = 'echo ' + name.strip() + '|clip' return check_call(cmd, shell=True) root = tk.Toplevel(background="black") root.title("Copying") root.resizable(False, False) T...
Why does tkinter creating two windows here? And how can i stop it?
import tkinter as tk from subprocess import check_call def copy_name(): cmd = 'echo ' + name.strip() + '|clip' return check_call(cmd, shell=True) root = tk.Toplevel(background="black") root.title("Copying") root.resizable(False, False) T = tk.Label(root, text=name, height=2, width=len(name) + 25, backgrou...
[ "Every tkinter window requires a root window - an instance of Tk. If you don't create one, one will be created automatically. When you do root = tk.Toplevel(background=\"black\"), tkinter will first create an instance of Tk and then it will create your Toplevel, resulting in two windows.\nThe solution in this case ...
[ 0, 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074338670_python_tkinter.txt
Q: Attempting to read pk from url in django, but getting error NoReverseMatch at / I am attempting to insert a link into my navbar (header.html - which is included in my base.html) which leads to the users profile. In order to provide the profile of the user who is currently logged in, I am attempting to use a primar...
Attempting to read pk from url in django, but getting error NoReverseMatch at /
I am attempting to insert a link into my navbar (header.html - which is included in my base.html) which leads to the users profile. In order to provide the profile of the user who is currently logged in, I am attempting to use a primary key via the url. However, I am receiving the following error message: Reverse for '...
[ "If you add the header to all items, then that means that all views should pass profile to the context, not only the DetailView.\nIt might also be the case that there is no profile, for example if the user is logged out. You thus should check if the profile is indeed valid. You can however obtain the profile for re...
[ 1 ]
[]
[]
[ "django", "django_urls", "django_views", "html", "python" ]
stackoverflow_0074339432_django_django_urls_django_views_html_python.txt
Q: loading simulation data from a dataframe of lists into a multi-index in Python I am trying to create a more efficient way of capturing stock price simulation and associated metrics (option price, option delta etc.) in a dataframe. Here's the code: def bscall_val(S0, strike, sigma, ttm, rf): d1 = (np.log(S0/str...
loading simulation data from a dataframe of lists into a multi-index in Python
I am trying to create a more efficient way of capturing stock price simulation and associated metrics (option price, option delta etc.) in a dataframe. Here's the code: def bscall_val(S0, strike, sigma, ttm, rf): d1 = (np.log(S0/strike) + 0.5 * np.power(sigma, 2) * ttm )/(sigma * np.power(ttm, 0.5)) d2 = d1 - s...
[ "I figured out this rather inelegant way to get this to work:\ndef sim_results(strike, sigma, ttm, r, numSteps, numPaths, quantity):\n dt = ttm/numSteps\n \n\n path = simpath(S0, sigma, ttm, numSteps, numPaths)\n delta = bscall_delta(path, sigma, ttm, numSteps, numPaths)\n\n cpth = []\n cdel = []\...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074333037_pandas_python.txt
Q: python subprocess create directory import sys import subprocess def generateFiles(numFiles): for i in range(0,numFiles): postfixDir = str(i) subprocess.check_call(['mkdir','example' + postfixDir]) return def main(): numFiles = int(sys.argv[1]) generateFiles(numFiles) main() after...
python subprocess create directory
import sys import subprocess def generateFiles(numFiles): for i in range(0,numFiles): postfixDir = str(i) subprocess.check_call(['mkdir','example' + postfixDir]) return def main(): numFiles = int(sys.argv[1]) generateFiles(numFiles) main() after i enter commandline python .\batchingCo...
[ "Python is telling you it asked the operating system to run the program mkdir, which doesn't exist. Unlike in unix, mkdir isn't an actual program on Windows - it's built into powershell and command.com themselves.\nTo instruct python to run the given command as arguments to a shell - instead of a raw program - use ...
[ 2 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0074339609_python_subprocess.txt
Q: Increase the ball speed as Pong game progress I am writing a Pong clone and I want to make the game get harder as the game progress. For every point (or few points), increase the speed of the ball. My code is as follows: import pygame import sys import math class Ball(object): def __init__(self, x, y, width, ...
Increase the ball speed as Pong game progress
I am writing a Pong clone and I want to make the game get harder as the game progress. For every point (or few points), increase the speed of the ball. My code is as follows: import pygame import sys import math class Ball(object): def __init__(self, x, y, width, height, vx, vy, colour): self.x = x ...
[ "I suggest you to add one method that updates the ball speed depending on the score, and you can call it just after the collision detection (because there is where you increase the score). You can include a call to that method like this, inside your play method:\n # (...) all your current code\n self....
[ 1 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074339338_pygame_python.txt
Q: Creating a list of video links /// blocked by email obfuscation I'm fairly new to Python and coding in general so please bare with me. Overall, what im attempting is to create a script to open up my monthly fire department training, go to the monthly training video's, make a list of the potential videos in that da...
Creating a list of video links /// blocked by email obfuscation
I'm fairly new to Python and coding in general so please bare with me. Overall, what im attempting is to create a script to open up my monthly fire department training, go to the monthly training video's, make a list of the potential videos in that data pod that change monthly and vary in how many video's we have for t...
[ "I really can't tell what's going on with you because you didn't provided us with any more information in order to check and verify\nBasically you are dealing with website which is behind CloudFlare protection\nand the results you get is an email support@targetsolutions.com\nyou can try to decod the result with thi...
[ 2, 1 ]
[]
[]
[ "automation", "beautifulsoup", "python", "selenium", "web_scraping" ]
stackoverflow_0074339452_automation_beautifulsoup_python_selenium_web_scraping.txt
Q: Page not found (404) No x matches the given query I'm not sure of why I can't get the pk which I think it's the problem here. I am trying to do a like functionality to a product model, with a like the page would refresh and the result be shown but it does not save the like and the error Page not found (404) No Pro...
Page not found (404) No x matches the given query
I'm not sure of why I can't get the pk which I think it's the problem here. I am trying to do a like functionality to a product model, with a like the page would refresh and the result be shown but it does not save the like and the error Page not found (404) No Product matches the given query. My Model: class Product(m...
[ "A couple of things that could be giving you problems:\nIn your redirect for ProductLike you use args\nreturn HttpResponseRedirect(reverse('product-detail', args=[str(pk)]))\n\nBut when you get back to the view, you are looking for kwargs\nlikes_connected = get_object_or_404(Product, id=self.kwargs['pk'])\n\nTry us...
[ 1 ]
[]
[]
[ "django", "django_views", "python" ]
stackoverflow_0074338333_django_django_views_python.txt
Q: Difference between global/local variables in Python test=4 def sum1(var): print("in function, test",test) var+=1 test=7 print("in function, var",var) print("in function, test",test) sum1(5) print(test) I'm trying to understand global and local variable, so I try it this way: a global and a ...
Difference between global/local variables in Python
test=4 def sum1(var): print("in function, test",test) var+=1 test=7 print("in function, var",var) print("in function, test",test) sum1(5) print(test) I'm trying to understand global and local variable, so I try it this way: a global and a local variable that has same names (I know we normally do...
[ "Because your local test shadows the name of the global test, it's unclear to which one you're referring. If you comment out the line test = 7 in your function, you won't get the error, as python assumes you're referring to the global test.\nIf you insist on using var names in your local scope that shadow global va...
[ 0 ]
[]
[]
[ "global_variables", "local_variables", "python" ]
stackoverflow_0074339655_global_variables_local_variables_python.txt
Q: How to append a Tkinter widget to an existing pdf without creating a temporary intermediate file? I want to append the contents of a Tkinter widget to the end of an existing pdf. First, I capture the widget to an PIL image. Then, it seems it is required when using PyPDF2 to create an intermediate temporary file fr...
How to append a Tkinter widget to an existing pdf without creating a temporary intermediate file?
I want to append the contents of a Tkinter widget to the end of an existing pdf. First, I capture the widget to an PIL image. Then, it seems it is required when using PyPDF2 to create an intermediate temporary file from the image, which feels unnecessary. Instead I would like to append the image directly, or at least c...
[ "So I was able to find a solution myself. The trick is writing the PIL image to a byte array (see this question), then converting that to a pdf using img2pdf. For img2pdf, it is required to use the format = \"jpeg\" argument during saving to byte array.\nSubsequently, the result of img2pdf can be written to another...
[ 0 ]
[]
[]
[ "pdf", "pypdf2", "python", "python_imaging_library", "tkinter" ]
stackoverflow_0074269697_pdf_pypdf2_python_python_imaging_library_tkinter.txt
Q: read all text files in directory and subdirectories and extract all email addresses from the textfiles I need to extract all email addresses from all text files within a directory with a lot of subdirectories. It is to much work to do this manually. I wrote the python script below to automate this task. However, w...
read all text files in directory and subdirectories and extract all email addresses from the textfiles
I need to extract all email addresses from all text files within a directory with a lot of subdirectories. It is to much work to do this manually. I wrote the python script below to automate this task. However, when I execute the script I end up with an empty array printed. No errors shown. Can one please indicate what...
[ "to check subdirectories as said you want, you need to check if the current item in the os.listdir() list is a folder and if so check all the file in that folder (and if there are more folders in that folder check them as well) or a file that ends with .txt\nyou also need to read() the file (f.read()) and only then...
[ 0 ]
[ "When your code doesn't produce expected results, you need to debug it to find the cause. Is it your regex? Is it your list.insert()? Is it the conversion of the file handle f to a string directly Something else entirely? Let's find out by modifying your read_text_file() func to print status:\ndef read_text_file(fi...
[ -1 ]
[ "python", "python_3.x" ]
stackoverflow_0074339518_python_python_3.x.txt
Q: How to join 3 tables in SQL without duplicates? I have this work: We have to get players with at least 30,000 points in their career, who have won a prize and are still alive. And I have in my sql 3 different tables for this information. I can obtain the players with more than 30K and still alive with this code:...
How to join 3 tables in SQL without duplicates?
I have this work: We have to get players with at least 30,000 points in their career, who have won a prize and are still alive. And I have in my sql 3 different tables for this information. I can obtain the players with more than 30K and still alive with this code: SELECT players.playerID, lastName, SUM(points) AS Al...
[ "The problem is that a player may have multiple awards - in that case, the second join \"multiplies\" the rows, and the total points go off.\nSince you just want to check if the player has any award, I would recommend exists:\nselect p.playerid, p.lastname, sum(pt.points) as allpoints, p.deathdate\nfrom players p\n...
[ 1 ]
[]
[]
[ "aggregate_functions", "inner_join", "mysql", "python", "sql" ]
stackoverflow_0074339679_aggregate_functions_inner_join_mysql_python_sql.txt
Q: Matplotlib symlog linear region I'm having some difficulties plotting lines which go to zero on a logarithmic (or symlog) axis. Consider this simple example: import numpy as np import matplotlib.pylab as pl pl.close('all') z = np.linspace(0,1,20) x = np.ones_like(z) x[0] = 0 pl.figure() pl.subplot(131) pl.plot(...
Matplotlib symlog linear region
I'm having some difficulties plotting lines which go to zero on a logarithmic (or symlog) axis. Consider this simple example: import numpy as np import matplotlib.pylab as pl pl.close('all') z = np.linspace(0,1,20) x = np.ones_like(z) x[0] = 0 pl.figure() pl.subplot(131) pl.plot(x, z, '-x') pl.xlim(-0.1,1.1) pl.sub...
[ "I had the same problem until I realized that the keyword is linthreshy rather than linthresy:\nimport numpy as np\nimport matplotlib.pylab as pl\n\npl.close('all')\n\nz = np.linspace(0,1,20)\nx = np.ones_like(z)\nx[0] = 0\n\npl.figure()\npl.subplot(121)\npl.plot(x, z, '-x')\npl.yscale('symlog', linthresy=1e-2)\npl...
[ 4, 1 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0033935758_matplotlib_python.txt
Q: Converting Image Converter python program to Exe not executing properly i am trying to convert my ImageConverter.py program to an Executable. I use python3.6.7 pyinstaller --onefile ImageConverter.py The Executable is made along with the folder pycache , build, and dist The executable file is in the dist folder, w...
Converting Image Converter python program to Exe not executing properly
i am trying to convert my ImageConverter.py program to an Executable. I use python3.6.7 pyinstaller --onefile ImageConverter.py The Executable is made along with the folder pycache , build, and dist The executable file is in the dist folder, when I try to run the exe the terminal pops up and performs the program and sa...
[ "sys.executable is the location of the Python interpreter you are running, e.g. /usr/bin/python3 or C:\\Program Files\\Python\\Scripts\\python.exe, not the location of the script you are running.\nTherefore, for a system-installed Python binary, os.path.dirname(sys.executable) will return something like /usr/bin or...
[ 0 ]
[]
[]
[ "executable", "image_processing", "python", "python_3.x", "python_imaging_library" ]
stackoverflow_0074339730_executable_image_processing_python_python_3.x_python_imaging_library.txt
Q: How to read txt.file and find sum of different products with different prices I have a following text-file products.txt: Product;Amount;Price Apple;3;10.00 Banana;1;5.00 Lemon;2;3.00 Orange;4;20.00 Apple;4;8.00 I want read this file and make a new text-file newfile.txt, which contains value of each row (Amount X P...
How to read txt.file and find sum of different products with different prices
I have a following text-file products.txt: Product;Amount;Price Apple;3;10.00 Banana;1;5.00 Lemon;2;3.00 Orange;4;20.00 Apple;4;8.00 I want read this file and make a new text-file newfile.txt, which contains value of each row (Amount X Price): 30.00 5.00 6.00 80.00 32.00 Finally, I want to find the total sum of newfile...
[ "This should work:\ndef read(name):\n total = 0\n\n ori = open(name, 'r', encoding=\"UTF-8\")\n row = ori.readline()\n\n dest = open(\"newfile.txt\", 'w', encoding=\"UTF-8\")\n\n row = ori.readline()\n while (row != \"\"):\n row = row[:-1].split(';')\n res = int(row[1]) * float(row[...
[ 0, 0 ]
[]
[]
[ "list", "python", "sum", "txt" ]
stackoverflow_0074337463_list_python_sum_txt.txt
Q: Scraping with Selenium some executions scan a data, others do not I am designing a Python code using the Selenium library to scrape hotel data available on the e-dreams platform. The aim of the code is to scrape some data such as the title and the current price, store them in lists and then create a dataset. The t...
Scraping with Selenium some executions scan a data, others do not
I am designing a Python code using the Selenium library to scrape hotel data available on the e-dreams platform. The aim of the code is to scrape some data such as the title and the current price, store them in lists and then create a dataset. The thing is that the code runs but in some of the executions the price data...
[ "Try find div with prices first using xpath:\ndiv = driver.find_element(By.XPATH, '//div[@data-testid=\"price-and-discounted-price\"])\n\nIn this div contains spans with prices, find them:\nspans = div.find_elements(By.TAG_NAME, 'span')\n\nHow i see, if 2 spans, first is old\nif len(spans) == 1:\n current_price ...
[ 0 ]
[]
[]
[ "python", "selenium", "web_scraping" ]
stackoverflow_0074339600_python_selenium_web_scraping.txt
Q: How can i make a program go back to it's original state when i click a button? (Tkinter) I have am making a Account Manager program, and I want to make a reset button so every time it's clicked everything goes back to it's original state(When I mean original state I mean before other buttons were clicked), can any...
How can i make a program go back to it's original state when i click a button? (Tkinter)
I have am making a Account Manager program, and I want to make a reset button so every time it's clicked everything goes back to it's original state(When I mean original state I mean before other buttons were clicked), can anyone help me please? Here is my code: https://paste.pythondiscord.com/hozasazohe I tried to rem...
[ "The short answer is that tkinter doesn't have any feature to do this. You'll have to write all of the code to make it happen.\nSolutions fall into one of two categories. First, you can write a function that resets all widgets and data structures to their default values. The second solution involves writing one or ...
[ 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074338687_python_tkinter.txt
Q: Iterate through the rows of a multidimensional array - Python Hello, in this code snippet I assign the string for all 6 rows in the matrix. I'm trying to figure out if there is a way to do this in a for loop that iterates through the rows of the matrix. Thanks. A: Try: row_struct = [ [' | '] ]*5 + [ [6] ] or r...
Iterate through the rows of a multidimensional array - Python
Hello, in this code snippet I assign the string for all 6 rows in the matrix. I'm trying to figure out if there is a way to do this in a for loop that iterates through the rows of the matrix. Thanks.
[ "Try:\nrow_struct = [ [' | '] ]*5 + [ [6] ]\n\nor\nrow_struct = [ [n] for n in range(7) ] \nresult=[[' | '] if i<=5 else val for i, val in enumerate(row_struct)] \n\nor\nfor i in range(6):\n row_struct[i][0] = ' | '\n\n" ]
[ 0 ]
[]
[]
[ "multidimensional_array", "python" ]
stackoverflow_0074339745_multidimensional_array_python.txt
Q: Is there a Pandas function to separate rows based on one column value and other column diversity? This is a DataFrame sample: Folder Model 0 123 A 1 123 A 2 123 A 3 4541 A 4 4541 B 5 4541 C 6 4541 A 7 11 B 8 11...
Is there a Pandas function to separate rows based on one column value and other column diversity?
This is a DataFrame sample: Folder Model 0 123 A 1 123 A 2 123 A 3 4541 A 4 4541 B 5 4541 C 6 4541 A 7 11 B 8 11 C 9 222 D 10 222 D 11 222 B 12 222 A I need to s...
[ "group must have 'A' and must not have only 'A'\nuse groupby filter\n(df\n .groupby('Folder')\n .filter(\n lambda x: (x['Model'].eq('A').sum() > 0) & (x['Model'].ne('A').sum() > 0)\n )\n)\n\n\nor if you want use transform + boolean indexing\ncond1 = (df\n .groupby('Folder')['Model']\n .transform...
[ 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074339499_pandas_python.txt
Q: Copy Data Frm Multiple .xlsx files&Paste in Destination .xlsm Files That Are In Diff Folders Python This is follow up to a previous question, I am trying to copy data From multiple .xlsx files and paste in multiple corresponding destination .xlsm files that are in different sub folders. eg copy data from ABC_Repor...
Copy Data Frm Multiple .xlsx files&Paste in Destination .xlsm Files That Are In Diff Folders Python
This is follow up to a previous question, I am trying to copy data From multiple .xlsx files and paste in multiple corresponding destination .xlsm files that are in different sub folders. eg copy data from ABC_Report.xlsx and paste in existing file ABC_2023.xlsm, copy data from DEF_Report.xlsx and paste in existing fil...
[ "Just incase it will help someone out there, I figured out how to get the code to copy data from source files in one folder and paste into destinations files that are in different individual sub folders, see below:\nimport os\nfrom glob import glob\nimport openpyxl\nfrom openpyxl import load_workbook\n\ndef copy_da...
[ 0 ]
[]
[]
[ "copy", "openpyxl", "python" ]
stackoverflow_0074307447_copy_openpyxl_python.txt
Q: How to correctly extract the phase of the spectrum in python I describe a pulse in the time domain and do a Fourier Transform to convert it to the frequency domain. I add an e-index polynomial phase e^{i*phase}to it in the frequency domain,phase is a polynomial. At this time, I use the angle function under numpy t...
How to correctly extract the phase of the spectrum in python
I describe a pulse in the time domain and do a Fourier Transform to convert it to the frequency domain. I add an e-index polynomial phase e^{i*phase}to it in the frequency domain,phase is a polynomial. At this time, I use the angle function under numpy to extract the phase, and what I get is such dense peaks as shown ...
[ "Two things. To center your data relative to phase, you need to either fftshift your data before the FFT, or flip the sign of the imaginary component in every other result element.\nThen look at the magnitude result. When the magnitudes go sufficiently near zero, the phase becomes that of random numerical noise, ...
[ 0 ]
[]
[]
[ "angle", "fft", "numpy", "phase", "python" ]
stackoverflow_0074196625_angle_fft_numpy_phase_python.txt
Q: flask-migrate not detecting existing tables I followed this tutorial to learn about migrating databases. After running the "flask db init" command the migrations folder is created as expected. However when I run flask db migrate -m 'Initial_Migration' then it doesn't detect the tables in the already existing datab...
flask-migrate not detecting existing tables
I followed this tutorial to learn about migrating databases. After running the "flask db init" command the migrations folder is created as expected. However when I run flask db migrate -m 'Initial_Migration' then it doesn't detect the tables in the already existing database. It therefore proposes to add all tables from...
[ "To solve this issue: change your table names to all lowercase letters.\nLike this:\nclass TopicSubscription(db.Model): #based upon: https://stackoverflow.com/questions/5756559/how-to-build-many-to-many-relations-using-sqlalchemy-a-good-example\n __tablename__=\"topic_subscription\" #We set our own name because ...
[ 0 ]
[]
[]
[ "alembic", "python", "sqlalchemy" ]
stackoverflow_0074332722_alembic_python_sqlalchemy.txt
Q: Python function with list without any spaces Define a function convert(input str) to return a list of characters based on the input string input str. Specifically, each character in input str will be included as a separate element of the returned list, while any spaces in input str will be ignored def convert(inpu...
Python function with list without any spaces
Define a function convert(input str) to return a list of characters based on the input string input str. Specifically, each character in input str will be included as a separate element of the returned list, while any spaces in input str will be ignored def convert(input_str): newlist = [] reallist = [char for ...
[ "Instead of using a list comprehension and then filter the resulting list, you can do it in one step using if in the list comprehension:\ndef convert(input_str: str):\n return [c for c in input_str if not c.isspace()]\n\nprint(convert(\"Hi You\")) # ['H', 'i', 'Y', 'o', 'u']\n\nInstead of using isspace, you coul...
[ 2, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074339815_python.txt
Q: Can you reference a class name with a variable? I am making an RPG text based game with classes and subclasses. I'm importing other python files, each of which have their own classes. Each python file is the name of their RPG main class, each of which have multiple classes for the respective RPG subclass. My quest...
Can you reference a class name with a variable?
I am making an RPG text based game with classes and subclasses. I'm importing other python files, each of which have their own classes. Each python file is the name of their RPG main class, each of which have multiple classes for the respective RPG subclass. My question is, if I wanted to access a variable from one of ...
[ "While you can do what you're asking (through a combination of globals() and getattr), it's a bad idea to do so. Your variable names should not be data in your program. Variable names are for you the programmer to use, not for your users.\nInstead, use a dictionary or some other data structure to map from one kind ...
[ 0 ]
[]
[]
[ "class", "python", "variables" ]
stackoverflow_0074339801_class_python_variables.txt
Q: FFT of sinosidal signal- posetive and negetive frequency I am trying to work with FFT in python but I am faced with a strange problem regarding negative and positive frequency I would like to use fft (scipy.fftpack) to find the magnitude and phase of the main harmonic of my signal. My signal is close to the Sinusi...
FFT of sinosidal signal- posetive and negetive frequency
I am trying to work with FFT in python but I am faced with a strange problem regarding negative and positive frequency I would like to use fft (scipy.fftpack) to find the magnitude and phase of the main harmonic of my signal. My signal is close to the Sinusial signal with some noise nad frequency close 50 Hz. Now when ...
[ "You can't just take the positive frequency if you want your time domain signal to be strictly real (not imaginary or complex). That's just the way the math works, like 1+1=2.\nYou need to feed an IFFT a complex conjugate symmetric signal (thus including matching negative frequency data) if you want your result to...
[ 0 ]
[]
[]
[ "fft", "python", "signal_processing" ]
stackoverflow_0074248745_fft_python_signal_processing.txt
Q: New line character as user input in Python While joining items in a list and printing them out as a string, I wanted to take user input for a character that will be used a separator. What if the separator is to be a newline? What can the user input be? Because if the user input is simply '\n' then that is being us...
New line character as user input in Python
While joining items in a list and printing them out as a string, I wanted to take user input for a character that will be used a separator. What if the separator is to be a newline? What can the user input be? Because if the user input is simply '\n' then that is being used literally ('\n' is being added as text). Code...
[ "you need to add the following line of code after the input\nsepchar = bytes(sepchar, \"utf-8\").decode(\"unicode_escape\")\n\nsource\n" ]
[ 0 ]
[]
[]
[ "newline", "python", "string", "user_input" ]
stackoverflow_0074339829_newline_python_string_user_input.txt
Q: I´ve got some errors in my code, what can i do?(I am programming whit python 3.10) I was doing a program that consisted of through these modules below create a new page on google, but it was not possible, because of some errors. from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManage...
I´ve got some errors in my code, what can i do?(I am programming whit python 3.10)
I was doing a program that consisted of through these modules below create a new page on google, but it was not possible, because of some errors. from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.chrome.service import Service servico=Service(ChromeDriverMan...
[ "I solved my own problem.\nFirst I changed the editor from Visual studio Code to Pycharm.\nAfter that I instaled the packages that Pycharm asked for, and to solve the big problem of from packaging install version I just did pip install packaging and pip install version, after that i just wrote the line of the error...
[ 1, 0, 0 ]
[]
[]
[ "module", "python", "selenium", "selenium_webdriver", "webdriver_manager" ]
stackoverflow_0074331639_module_python_selenium_selenium_webdriver_webdriver_manager.txt
Q: Mac + virtualenv + pip + postgresql = Error: pg_config executable not found I was trying to install postgres for a tutorial, but pip gives me error: pip install psycopg A snip of error I get: Error: pg_config executable not found. Please add the directory containing pg_config to the PATH or specify the full exe...
Mac + virtualenv + pip + postgresql = Error: pg_config executable not found
I was trying to install postgres for a tutorial, but pip gives me error: pip install psycopg A snip of error I get: Error: pg_config executable not found. Please add the directory containing pg_config to the PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to...
[ "On the Mac, if you're using Postgres.app, the pg_config file is in your /Applications/Postgres.app/Contents/Versions/<current_version>/bin directory. That'll need to be added to your system path to fix this error, like this:\nexport PATH=$PATH:/Applications/Postgres.app/Contents/Versions/<current_version>/bin\n\nS...
[ 137, 126, 42, 19, 10, 9, 7, 6, 3, 2, 1, 1, 1, 0, 0, 0, 0 ]
[]
[]
[ "macos", "postgresql", "psycopg2", "python" ]
stackoverflow_0020170895_macos_postgresql_psycopg2_python.txt
Q: How to append empty row after each customers in a python dataframe? df1: Customer Manager Time Period Amount Samsung Rosalie 90D 46726190 Samsung Rosalie 18M 46726190 Samsung Rosalie 18M 46726...
How to append empty row after each customers in a python dataframe?
df1: Customer Manager Time Period Amount Samsung Rosalie 90D 46726190 Samsung Rosalie 18M 46726190 Samsung Rosalie 18M 46726190 Samsung Rosalie 18M 46726190 Sams...
[ "if you have range index\n Customer Manager Time Period Amount\n0 Samsung Rosalie 90D 46726190 NaN\n1 Samsung Rosalie 18M 46726190 NaN\n2 Samsung Rosalie 18M 46726190 NaN\n3 Samsung Rosalie 18M 46726190 NaN\n4 Samsung Rosalie 30D 46726190 ...
[ 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074339734_dataframe_pandas_python.txt
Q: Py installer issue I want to extract my python script to exe file I am using a lot of packeges but customtkinter is different you have to do like this and my command is this pyinstaller --noconfirm --onefile --windowed --icon "C:/Users/pc/Desktop/main_icon.ico" --name "Automated gmail" --add-binary "c:\users\pc\ap...
Py installer issue
I want to extract my python script to exe file I am using a lot of packeges but customtkinter is different you have to do like this and my command is this pyinstaller --noconfirm --onefile --windowed --icon "C:/Users/pc/Desktop/main_icon.ico" --name "Automated gmail" --add-binary "c:\users\pc\appdata\local\programs\pyt...
[ "You are putting a . in front of the destination address, and you want to use the --add-data not --add-binary arguments. You can leave the . there just put a path seperator in front of it.\nTry:\npyinstaller --noconfirm --onefile --windowed --icon C:/Users/pc/Desktop/main_icon.ico --name \"Automated gmail\" --add-...
[ 0 ]
[]
[]
[ "auto_py_to_exe", "customtkinter", "pyinstaller", "python", "python_3.x" ]
stackoverflow_0074338296_auto_py_to_exe_customtkinter_pyinstaller_python_python_3.x.txt
Q: Combine 3 dataframe with different number of column I have 3 data frame. 2 of them are only one column, another one is two columns. 3 dataframe looks like this Itemcode Itemcode2 Itemcode count AAC AAC AAC 2 AAB AAB AAB 1 AAG AAF AAT 0 AAD ...
Combine 3 dataframe with different number of column
I have 3 data frame. 2 of them are only one column, another one is two columns. 3 dataframe looks like this Itemcode Itemcode2 Itemcode count AAC AAC AAC 2 AAB AAB AAB 1 AAG AAF AAT 0 AAD AAD AAD 1 AAC ...
[ "You can certainly use pandas.concat:\n(pd.concat([df1['Itemcode'].value_counts(), \n df2['Itemcode2'].value_counts(), \n df3.set_index('Itemcode')\n ], axis=1, keys=['df1', 'df2', 'df3'])\n .droplevel(1, axis=1)\n .fillna(0, downcast='infer')\n )\n\nAlternative without value_cou...
[ 1, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074339594_dataframe_pandas_python.txt
Q: pyopengl glGenVertexArrays() causes segfault in threads Working on a basic minecraft imitation in python using opengl, specifically the pyopengl python module. Found that updating world geometry in the main thread was talking too long, so I decided to make a thread to do it(using the threading library). Before th...
pyopengl glGenVertexArrays() causes segfault in threads
Working on a basic minecraft imitation in python using opengl, specifically the pyopengl python module. Found that updating world geometry in the main thread was talking too long, so I decided to make a thread to do it(using the threading library). Before this, glGenVertexArrays() was working fine. However, after I st...
[ "You need a valid and \"current\" OpenGL context to call an OpenGL API function. If you do not have a current context, this will result in a segfault. However, the OpenGL context is local to a thread. If you want to call an OpenGL function from another thread, you must make the OpenGL Context current in that thread...
[ 0 ]
[]
[]
[ "pyopengl", "python", "python_multithreading" ]
stackoverflow_0074339949_pyopengl_python_python_multithreading.txt
Q: Validating an Input I am a beginner python programmer and was hoping to get some help. I was trying to create a procedure where it would check if a user's input is either empty or a single alphabetic character. I am having trouble as every time I run it, and I type 2, it doesn't print anything. However, if I do mu...
Validating an Input
I am a beginner python programmer and was hoping to get some help. I was trying to create a procedure where it would check if a user's input is either empty or a single alphabetic character. I am having trouble as every time I run it, and I type 2, it doesn't print anything. However, if I do multiples letters such as "...
[ "You need to change the order of your checks. At the moment, the check for the length happens before the check for the type of character, and a success on the first check will skip the later ones.\ndef validate_input(LETTER):\n if len(LETTER) == 0:\n pass\n elif len(LETTER) >= 2 or not LETTER.isalp...
[ 1 ]
[]
[]
[ "procedure", "python" ]
stackoverflow_0074340046_procedure_python.txt
Q: Determining neighbours of cell two dimensional list I have a list of lists, something like [[1, 2, 3,],[4, 5, 6,],[7, 8, 9]]. Represented graphically as: 1 2 3 4 5 6 7 8 9 I'm looking for an elegant approach to check the value of neighbours of a cell, horizontally, vertically and diagonally. For instance, the n...
Determining neighbours of cell two dimensional list
I have a list of lists, something like [[1, 2, 3,],[4, 5, 6,],[7, 8, 9]]. Represented graphically as: 1 2 3 4 5 6 7 8 9 I'm looking for an elegant approach to check the value of neighbours of a cell, horizontally, vertically and diagonally. For instance, the neighbours of [0][2] are [0][1], [1][1] and [1][2] or the ...
[ "# Size of \"board\"\nX = 10\nY = 10\n\nneighbors = lambda x, y : [(x2, y2) for x2 in range(x-1, x+2)\n for y2 in range(y-1, y+2)\n if (-1 < x <= X and\n -1 < y <= Y and\n (x != x2 or y !=...
[ 30, 23, 12, 7, 5, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ "maybe you are checking a sudoku box. If the box is n x n and current cell is (x,y) start checking:\nstartingRow = x / n * n;\nstartingCol = y/ n * n\n\n" ]
[ -1 ]
[ "matrix", "python" ]
stackoverflow_0001620940_matrix_python.txt
Q: How to remove distance between two bars in matplotlib? I am trying to plot bar graphs in matplotlib. I have set frequency of X-axis manually in matplotlib by using plt.xticks. But i can not remove the distance between two bars (first and second). What should i do to remove the distance between two horizontal bars?...
How to remove distance between two bars in matplotlib?
I am trying to plot bar graphs in matplotlib. I have set frequency of X-axis manually in matplotlib by using plt.xticks. But i can not remove the distance between two bars (first and second). What should i do to remove the distance between two horizontal bars? import matplotlib.pyplot as plt import numpy as np x = np....
[ "As a quick by-hand solution, you could use your x-values just as labels and equidistant ones for the plotting:\nx = np.array([0, 15, 20, 25])\ny = np.array([3500, 4239, 5239, 6239])\n\nx_new = np.arange(len(x))\n\nplt.bar(x_new, y, width = 0.5, edgecolor='black', color=['olive', 'seagreen', 'green', 'darkgreen'] )...
[ 0 ]
[]
[]
[ "axis", "bar_chart", "matplotlib", "python" ]
stackoverflow_0074340013_axis_bar_chart_matplotlib_python.txt
Q: python remove zero values from column in dataframe I have a dataframe (df) that has two columns (samples, results) df = pd.DataFrame({'samples': ['sample_1', 'sample_2', 'sample_3', 'sample_4', 'sample_5'], 'results': [[0.0,0.0,2.0,0.0,0.0,2.0,0.0,3.0,3.0], [1.0,3.0...
python remove zero values from column in dataframe
I have a dataframe (df) that has two columns (samples, results) df = pd.DataFrame({'samples': ['sample_1', 'sample_2', 'sample_3', 'sample_4', 'sample_5'], 'results': [[0.0,0.0,2.0,0.0,0.0,2.0,0.0,3.0,3.0], [1.0,3.0,1.0,1.0,1.0,3.0,1.0,0.0,1.0], ...
[ "Using a list comprehension seems to do the trick (if you don't care about the type, you get rid of the tuple() call):\ndf['count'].apply(lambda x: tuple([y for y in x if y != 0]))\n\nGiving you:\n0 (5, 2, 2)\n1 (1, 6, 2)\n2 (7, 2)\n3 (3, 6)\n4 (7, 2)\nName: count, dtype: object\n\n" ]
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074339956_pandas_python.txt
Q: VS Code > Preferences > User Settings > Extensions > Python > Linting > Flake8 Args Added Item stopped working Please don't treat this as an "asked and answered" question. I sincerely have been clobbering to try to figure out why this has stopped working, if it's a VS Code problem, or a Flake8 one, or if I'm just ...
VS Code > Preferences > User Settings > Extensions > Python > Linting > Flake8 Args Added Item stopped working
Please don't treat this as an "asked and answered" question. I sincerely have been clobbering to try to figure out why this has stopped working, if it's a VS Code problem, or a Flake8 one, or if I'm just crazy and should find another way around this. Looking for a way to stop the Flake8 linter's "file is too long" and ...
[ "This is an edit to finding my own answer. I found that if I make the suggested edits in the actual settings.json file instead of through the VS Code User Settings interface, the edit actually does work. \nI'm not sure if I can say that just changing it there alone is sufficient because in my research and searches ...
[ 3, 1, 1, 0 ]
[]
[]
[ "flake8", "python", "vscode_settings" ]
stackoverflow_0058977983_flake8_python_vscode_settings.txt
Q: Pandas pd.to_datetime returning 'NaT' when format is valid I am unable to convert a Column from a DataFrame (temp_series) containing date and time information to datetime object. When usind pd.to_datetime() I only get 'NaT' values. Here is my DataFrame: Timestamp[ms] D0_Tc0 1 11/05/2022 07:33:57:851 PM 25...
Pandas pd.to_datetime returning 'NaT' when format is valid
I am unable to convert a Column from a DataFrame (temp_series) containing date and time information to datetime object. When usind pd.to_datetime() I only get 'NaT' values. Here is my DataFrame: Timestamp[ms] D0_Tc0 1 11/05/2022 07:33:57:851 PM 25 2 11/05/2022 07:33:57:967 PM 25 3 11/05/2022 07:33:58:083 ...
[ "There must be something incorrect with your data as I cannot reproduce your issue:\ntemp_series = pd.DataFrame({'Timestamp[ms]': ['11/05/2022 07:33:57:851 PM', '11/05/2022 07:33:57:967 PM', '11/05/2022 07:33:58:083 PM', '11/05/2022 07:33:58:184 PM', '11/05/2022 07:33:58:299 PM'], 'D0_Tc0': [25, 25, 25, 25, 25]})\n...
[ 1 ]
[]
[]
[ "dataframe", "datetime", "pandas", "python" ]
stackoverflow_0074340023_dataframe_datetime_pandas_python.txt
Q: Python EEL + wxpython: open "parentless" file dialog in front of all other windows and programs I am developing an EEL project, and I needed to create a file dialog on the python side in order to preprocess data before sending it to javascript. I tried to use tk.filedialog.askopenfilename, but that somehow froze t...
Python EEL + wxpython: open "parentless" file dialog in front of all other windows and programs
I am developing an EEL project, and I needed to create a file dialog on the python side in order to preprocess data before sending it to javascript. I tried to use tk.filedialog.askopenfilename, but that somehow froze the javascript event loop. I found an answer on StackOverflow that used wxpython to create a non-block...
[ "I was able to get it working with the following code. I used a regular window instead of a wx.Dialog or similar class.\nclass FancyFilePickerApplication:\n \n def __init__(self):\n self.app = wx.App()\n self.frame = wx.Frame(None,title=\"Fancy File Picker\")\n self.build_ui()\n #@priv...
[ 0 ]
[]
[]
[ "eel", "filepicker", "python", "python_3.x", "wxpython" ]
stackoverflow_0074304275_eel_filepicker_python_python_3.x_wxpython.txt
Q: Polynomial Regression using sliding windows? I'm trying to predict a stock's closing price for the next week using linear regression and a sliding window. This is an example of the database I'm working with... Week_Number Year Open Close 0 2020 46.270000 46.045000 1 2020 ...
Polynomial Regression using sliding windows?
I'm trying to predict a stock's closing price for the next week using linear regression and a sliding window. This is an example of the database I'm working with... Week_Number Year Open Close 0 2020 46.270000 46.045000 1 2020 46.748001 47.506000 2 2020 50....
[ "I'm not sure I understand the problem but a window sliding may easily be accomplished with 'slicing' of your arrays.\nFor example, regression( x[-5:], y[-5:], d) would analyze the last 5 days.\nAnd if you do backtesting, regression( x[t:t+5], y[t:t+5], d) will analyse 5 older days.\n" ]
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074339802_pandas_python.txt
Q: Error: No nodes replied within time constraint I'm running a worker on Celery [version 5.1.0 (sun-harmonics)] like this: celery -A task_scheduler.celery_task worker --loglevel=debug -n ekkis -E the worker seems to run fine and responds to requests. here's a partial log: [2022-11-06 03:02:15,913: DEBUG/MainProces...
Error: No nodes replied within time constraint
I'm running a worker on Celery [version 5.1.0 (sun-harmonics)] like this: celery -A task_scheduler.celery_task worker --loglevel=debug -n ekkis -E the worker seems to run fine and responds to requests. here's a partial log: [2022-11-06 03:02:15,913: DEBUG/MainProcess] | Worker: Preparing bootsteps. [2022-11-06 03:02:...
[ "ok, I figured it out. we had configured a task:\n@celeryd_after_setup.connect()\ndef configure_task(conf=None, **kwargs):\n genesis_subscribe()\n\nwhich, due to a failure in a foreign system, never returned:\ndef genesis_subscribe():\n try:\n from task_scheduler.third_party.backfilling import BackFil...
[ 0 ]
[]
[]
[ "celery", "python", "redis" ]
stackoverflow_0074333035_celery_python_redis.txt
Q: Multiple Postgres schema issue when using pandas to_sql with SQL Alchemy core I am exporting a pandas df to postgres using the SA core. Here is the basic script: engine = db.create_engine(f'postgresql://data-catalogue:{dbpwd}@postgres-data-catalogue-dev/data-catalogue') metadata = db.MetaData(schema="abn") esh...
Multiple Postgres schema issue when using pandas to_sql with SQL Alchemy core
I am exporting a pandas df to postgres using the SA core. Here is the basic script: engine = db.create_engine(f'postgresql://data-catalogue:{dbpwd}@postgres-data-catalogue-dev/data-catalogue') metadata = db.MetaData(schema="abn") eshc_underlyers = db.Table('eshc_underlyers', metadata, db.Column('description...
[ "ok, figured this out. You have to pass the schema into BOTH the Metadata() statement AND the to_sql statement. In this case the public schema is not created at all.\n" ]
[ 0 ]
[]
[]
[ "postgresql", "python", "sql", "sqlalchemy" ]
stackoverflow_0074320639_postgresql_python_sql_sqlalchemy.txt
Q: How to remove row from excel using Python/PySimpleGUI Dears, How to remove row from excel using Python/PySimpleGUI. Knowing that I'm using the reverse process of adding rows to excel file using PySimple : Add Row : import PySimpleGUI as sg import pandas as pd .......... [sg.Button('Submit', size=(6, 1), button_co...
How to remove row from excel using Python/PySimpleGUI
Dears, How to remove row from excel using Python/PySimpleGUI. Knowing that I'm using the reverse process of adding rows to excel file using PySimple : Add Row : import PySimpleGUI as sg import pandas as pd .......... [sg.Button('Submit', size=(6, 1), button_color=('White','Dark'))] if event == 'Submit': new_reco...
[ "Could you drop the column from the df and then rewrite to excel if needed?\ndf = df.drop(['rowToDelete'])\n" ]
[ 1 ]
[]
[]
[ "delete_row", "excel", "key", "pysimplegui", "python" ]
stackoverflow_0074340056_delete_row_excel_key_pysimplegui_python.txt
Q: Extracting and altering dictionary items with 2 conditions I have been breaking my head with this function. def snatch(data,threshold): Given I have the following data: data = { 'x': [1, 2, 3, 7], 'y': [1, 3, 7, 2] } threshold = { 'x': 3, 'y': 2 } Briefly, the data dictionaries' values are supposed to merge as o...
Extracting and altering dictionary items with 2 conditions
I have been breaking my head with this function. def snatch(data,threshold): Given I have the following data: data = { 'x': [1, 2, 3, 7], 'y': [1, 3, 7, 2] } threshold = { 'x': 3, 'y': 2 } Briefly, the data dictionaries' values are supposed to merge as one list, if they are above or equal to the threshold's values. i...
[ "Use a list comprehension like this:\ndef snatch(data, threshold):\n return [v for k in threshold for v in data[k] if v >= threshold[k]]\n\nEssentially, the function above is doing this:\ndef snatch(data, threshold):\n snatched = []\n for key in threshold:\n for value in data[key]:\n if v...
[ 2, 0 ]
[]
[]
[ "conditional_statements", "dictionary", "python" ]
stackoverflow_0074340052_conditional_statements_dictionary_python.txt
Q: Django, different result between `all()` method and `all().values()` method I am facing this problem, where i can't access the url of some image using values() method, but it still can be accessed if it is a queryset object rather than a pythonic list: class MyModel(models.Model): name = models.CharField(lengt...
Django, different result between `all()` method and `all().values()` method
I am facing this problem, where i can't access the url of some image using values() method, but it still can be accessed if it is a queryset object rather than a pythonic list: class MyModel(models.Model): name = models.CharField(length=100) img = models.ImageField(upload_to='media') # the image is stored in aw...
[ "This is one of the very many reasons not to use .values() in the first place: this will make a database query, and then transform the items in dictionaries, and thus losing all model logic attached to it. This thus means that .img will no longer return a FieldFile object, but a simple string, and thus show the pat...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074340077_django_python.txt
Q: How do I create a new column in my dataframe based on a date condition, within Python? How do I create a column in my dataframe called 'Declined Or Hired', where a '1' is input into each row where the '(Declined - Reason) Or Hire' column starts with "Offer Declined -..." and the 'Date' column is between January an...
How do I create a new column in my dataframe based on a date condition, within Python?
How do I create a column in my dataframe called 'Declined Or Hired', where a '1' is input into each row where the '(Declined - Reason) Or Hire' column starts with "Offer Declined -..." and the 'Date' column is between January and March 2022. I started with the code below, which works for my first condition, but not su...
[ "Use a second condition:\ndf['Declined Or Hired'] = (df['(Declined - Reason) Or Hire'].str.startswith('Offer Declined', na=False)\n & pd.to_datetime(df['Date'], dayfirst=True)\n .between(pd.Timestamp('2022-01-01'), pd.Timestamp('2022-03-31'))\n ...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074340201_dataframe_pandas_python.txt
Q: Python Turtle error in python main modules File "/usr/lib/python3.10/turtle.py", line 107, in import tkinter as TK ModuleNotFoundError: No module named 'tkinter' Error occurring in linux python modules A: In Arch, Tk is available in the Arch repository. The following fixed it for me on Manjaro. Just type on the...
Python Turtle error in python main modules
File "/usr/lib/python3.10/turtle.py", line 107, in import tkinter as TK ModuleNotFoundError: No module named 'tkinter' Error occurring in linux python modules
[ "In Arch, Tk is available in the Arch repository.\nThe following fixed it for me on Manjaro. Just type on the terminal:\npacman -S tk\n\nIf you are using one of Debian flavours, Ubuntu, Mint etc...\napt-get install tk\n\n" ]
[ 0 ]
[]
[]
[ "linux", "python", "python_3.x", "python_turtle" ]
stackoverflow_0073753120_linux_python_python_3.x_python_turtle.txt
Q: How to find out the color at specific coordinates in matplotlib? I have the following Code: import numpy from PIL import Image import matplotlib.pyplot as plt img=Image.open(r'C:\Users\User\OneDrive\Desktop\database\db1.jpg') small_img=img.resize((16,16),Image.BILINEAR) plt.imshow(small_img) plt.show() and it sh...
How to find out the color at specific coordinates in matplotlib?
I have the following Code: import numpy from PIL import Image import matplotlib.pyplot as plt img=Image.open(r'C:\Users\User\OneDrive\Desktop\database\db1.jpg') small_img=img.resize((16,16),Image.BILINEAR) plt.imshow(small_img) plt.show() and it shows this image: How can I find out if I have a black or a white Pixel...
[ "PIL images have the getpixel function. Take a look here: https://www.geeksforgeeks.org/python-pil-getpixel-method/\nYou can make like that:\nsmall_img.getpixel((6, 6))\n\n" ]
[ 0 ]
[]
[]
[ "image_processing", "matplotlib", "python" ]
stackoverflow_0074339675_image_processing_matplotlib_python.txt