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: Could not able to get the text body from articles while web scraping I'm scraping news articles from the website https://www.scmp.com/ Though I can get the title or author names from each articles but I can't able to get the text body or main content of the articles. I followed two methods but both didn't work. Fi...
Could not able to get the text body from articles while web scraping
I'm scraping news articles from the website https://www.scmp.com/ Though I can get the title or author names from each articles but I can't able to get the text body or main content of the articles. I followed two methods but both didn't work. First method options = webdriver.ChromeOptions() lists = ['disable-popup-bl...
[ "There are several reasons that you cannot obtain the text from the article on the South China Morning Post.\nFirst when you open Chrome using selenium the URL for the article displays a GDRP notice.\nThe GDRP has to be accepted via a button click.\nSecond the page also displays a popup to set your news preferences...
[ 2 ]
[]
[]
[ "beautifulsoup", "html", "python", "selenium", "web_scraping" ]
stackoverflow_0074457838_beautifulsoup_html_python_selenium_web_scraping.txt
Q: How can i scale between [0,1] a random matrix I have to scale between [0,1] a matrix. So, for each element from matrix i have to do this formula: (Element - min_cols) / (max_cols - min_cols) min_cols -> array with every minimum of each column from the matrix. max_cols -> same but with max My problem is, i want t...
How can i scale between [0,1] a random matrix
I have to scale between [0,1] a matrix. So, for each element from matrix i have to do this formula: (Element - min_cols) / (max_cols - min_cols) min_cols -> array with every minimum of each column from the matrix. max_cols -> same but with max My problem is, i want to calculate result with this: result = (Element- m...
[ "Use numpy\nExample\nimport numpy as np\n\nx = 50*np.random.rand(6,4)\n\narray([[26.7041017 , 46.88118463, 41.24541748, 31.17881807],\n [47.57036124, 16.49040094, 6.62454156, 37.15976348],\n [46.7157895 , 8.53357717, 39.01399714, 5.14287858],\n [24.36012016, 5.67603151, 40.7697121 , 13.0987784...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074464157_python.txt
Q: Python fpdf add dashed line for Index page I want to create an Index page. How can I add a dashed line between cells (name and page) that I don't know the width of? There is the dashed line method, but to use it I need to specify the width and place it between two cells where the first one I don't know the size......
Python fpdf add dashed line for Index page
I want to create an Index page. How can I add a dashed line between cells (name and page) that I don't know the width of? There is the dashed line method, but to use it I need to specify the width and place it between two cells where the first one I don't know the size...
[ "This was my partial solution.\nself.__index is a Dict<string, int>\nfor item in self.__index.items():\n if item[0] and not item[0].isspace() and item[0] != \"Index\":\n # get with of title\n widthl = self.get_string_width(str(item[0])) + 3\n # get width of page number\n widthr = self...
[ 0 ]
[]
[]
[ "fpdf", "python" ]
stackoverflow_0074435849_fpdf_python.txt
Q: Are user provided translations for user provided templates possible with the django template engine? In my webapp, I'd like to allow users who want to deploy an instance to write their own templates. Specifically, I would like to include a template for a data protection declaration using the include tag and have t...
Are user provided translations for user provided templates possible with the django template engine?
In my webapp, I'd like to allow users who want to deploy an instance to write their own templates. Specifically, I would like to include a template for a data protection declaration using the include tag and have this point to a location which users can define in their settings. However, this would not be translatable,...
[ "Not entirely sure if this is possible, but you best bet is probably to use some other mechanism for translation. For example, you could create a template-tag user_translation and make it fetch the translation from the database or settings.\n" ]
[ 0 ]
[]
[]
[ "django", "django_templates", "python", "translation" ]
stackoverflow_0073831490_django_django_templates_python_translation.txt
Q: LLDP module in SCAPY produce malformed packets I am using scapy.contrib.lldp library to craft an LLDP packet, with the following fields: Chassis ID (l1) Port ID (l2) Time to live (l3) System name (l4) Generic Organisation Specific - custom data 1 (l5) Generic Organisation Specific - custom data 2 (l6) End of LLDP...
LLDP module in SCAPY produce malformed packets
I am using scapy.contrib.lldp library to craft an LLDP packet, with the following fields: Chassis ID (l1) Port ID (l2) Time to live (l3) System name (l4) Generic Organisation Specific - custom data 1 (l5) Generic Organisation Specific - custom data 2 (l6) End of LLDP (l7) The options for each field comes from a csv f...
[ "The problem was the encoding, it was wrong since I wrote the data in the data frame.\nThe solution was to encode with base64 BEFORE saving the information in the data frame, I used this explanation: Convert byte[] to base64 and ASCII in Python\nThat changed my data from b'`\\xafE\\x16\\t\\xa0#5\\x02\\x7f\\xd5\\p\\...
[ 0 ]
[]
[]
[ "ethernet", "python", "scapy" ]
stackoverflow_0074294723_ethernet_python_scapy.txt
Q: OR-Tools - Nurse scheduling - prevent shift gaps with binary constraints I am using OR-Tools to solve a problem similar to the Nurse Scheduling problem. The difference in my case is that when I schedule a "Nurse" for a shift, they must then work consecutive days (i.e., there can be no gaps between days worked). Mo...
OR-Tools - Nurse scheduling - prevent shift gaps with binary constraints
I am using OR-Tools to solve a problem similar to the Nurse Scheduling problem. The difference in my case is that when I schedule a "Nurse" for a shift, they must then work consecutive days (i.e., there can be no gaps between days worked). Most of the similar questions point to this code. I have attempted to implement ...
[ "I don't use/know the syntax of or-tools, but you can probably construct a little boolean logic with constraints to do this.\nLet's say we introduce a binary variable to annotate which d day that nurse n starts working:\ns[n, d] ∈ {0, 1}\n\nAnd to enforce only one sequence of days worked, we need to constrain to on...
[ 0, 0 ]
[]
[]
[ "constraint_programming", "or_tools", "python", "scheduling" ]
stackoverflow_0074436487_constraint_programming_or_tools_python_scheduling.txt
Q: How to find common edges from a binary dataframe? This is my dataset: Dept Cell culture Bioinfo Immunology Trigonometry Algebra Biotech Optics Biotech 1 1 1 0 0 1 0 Math 0 0 0 1 1 0 0 Physics 0 0 0 0 0 0 1 How I want my result: Dept 0 Biotech Cell culture Biotech Bioinfo Biotech Immunology Math Trigonome...
How to find common edges from a binary dataframe?
This is my dataset: Dept Cell culture Bioinfo Immunology Trigonometry Algebra Biotech Optics Biotech 1 1 1 0 0 1 0 Math 0 0 0 1 1 0 0 Physics 0 0 0 0 0 0 1 How I want my result: Dept 0 Biotech Cell culture Biotech Bioinfo Biotech Immunology Math Trigonometry Math Algebra Physics Optics...
[ "Try this:\n#df = df.set_index('Dept') if needed move dept into the index\ndf.dot(df.columns+',').str.strip(',').str.split(',').explode().reset_index()\n\nOutput:\n Dept 0\n0 Biotech Cell culture\n1 Biotech Bioinfo\n2 Biotech Immunology\n3 Biotech Biotech\n4 Math Trigonomet...
[ 1 ]
[]
[]
[ "group_by", "multiple_columns", "pandas", "python", "sorting" ]
stackoverflow_0074464296_group_by_multiple_columns_pandas_python_sorting.txt
Q: Moto doesn't mock DynamoDB I'm trying to write my unit tests for a Lambda function that communicates with DynamoDB. I'm using moto but it isn't mocking anything. Whenever I call something in boto3, it communicates using my AWS CLI profile to the actual API and not a mock one. Why is this happening? Here's the code...
Moto doesn't mock DynamoDB
I'm trying to write my unit tests for a Lambda function that communicates with DynamoDB. I'm using moto but it isn't mocking anything. Whenever I call something in boto3, it communicates using my AWS CLI profile to the actual API and not a mock one. Why is this happening? Here's the code: ### Unit test for the visitorC...
[ "I found out that the issue was with the from visitorCounterLambda import handler part because that script already established a boto3 client when imported and therefore mock could not break that. The proper way of doing it is outlined in the Moto documentation under \"Very Important -- Recommended Usage\". You sho...
[ 1, 0 ]
[]
[]
[ "amazon_dynamodb", "aws_lambda", "boto3", "moto", "python" ]
stackoverflow_0062232709_amazon_dynamodb_aws_lambda_boto3_moto_python.txt
Q: Multi-line function calls with strings in python I have a function call in python 2.7: execute_cmd('/sbin/ip addr flush dev ' + args.interface + ' && ' + '/sbin/ifdown ' + args.interface + ' ; ' + '/sbin/ifup ' + args.interf...
Multi-line function calls with strings in python
I have a function call in python 2.7: execute_cmd('/sbin/ip addr flush dev ' + args.interface + ' && ' + '/sbin/ifdown ' + args.interface + ' ; ' + '/sbin/ifup ' + args.interface + ' && ' + '/sbin/ifconf...
[ "Pylint tells you exactly what to do, remove one space:\nexecute_cmd('/sbin/ip addr flush dev '\n + args.interface\n + ' && '\n + '/sbin/ifdown '\n + args.interface\n + ' ; '\n + '/sbin/ifup '\n + args.interface\n + ' && '\n ...
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0047829325_python.txt
Q: How to store Dataframe data to Firebase Storage? Given a pandas Dataframe which contains some data, what is the best to store this data to Firebase? Should I convert the Dataframe to a local file (e.g. .csv, .txt) and then upload it on Firebase Storage, or is it also possible to directly store the pandas Dataframe...
How to store Dataframe data to Firebase Storage?
Given a pandas Dataframe which contains some data, what is the best to store this data to Firebase? Should I convert the Dataframe to a local file (e.g. .csv, .txt) and then upload it on Firebase Storage, or is it also possible to directly store the pandas Dataframe without conversion? Or are there better best practice...
[ "With python-firebase and to_dict:\npostdata = my_df.to_dict()\n\n# Assumes any auth/headers you need are already taken care of.\nresult = firebase.post('/my_endpoint', postdata, {'print': 'pretty'})\nprint(result)\n# Snapshot info\n\nYou can get the data back using the snapshot info and endpoint, and reestablish t...
[ 7, 1, 0, 0 ]
[]
[]
[ "dataframe", "firebase", "pandas", "python" ]
stackoverflow_0053886485_dataframe_firebase_pandas_python.txt
Q: Add x-axis to matplotlib with multiple y-axis line chart How do I add the x-axis(Month) to a simple Matplotlib My Dataset: Month Views CMA30 0 11 24662 24662.000000 1 11 2420 13541.000000 2 11 11318 12800.000000 3 11 8529 11732.250000 4 10 78861 25158.000000 5 10 1281 21178.500...
Add x-axis to matplotlib with multiple y-axis line chart
How do I add the x-axis(Month) to a simple Matplotlib My Dataset: Month Views CMA30 0 11 24662 24662.000000 1 11 2420 13541.000000 2 11 11318 12800.000000 3 11 8529 11732.250000 4 10 78861 25158.000000 5 10 1281 21178.500000 6 10 22701 21396.000000 7 10 17088 20857.500000 ...
[ "If you average the values per month, then try groupby/mean:\ndf.groupby('Month')[['Views','CMA30']].mean().plot(label='Views', figsize=(5, 5))\n\n" ]
[ 2 ]
[]
[]
[ "dataframe", "matplotlib", "pandas", "python" ]
stackoverflow_0074464111_dataframe_matplotlib_pandas_python.txt
Q: Moving average for value present in two dataframe columns in python I'm stuck with the following problem since last night and I haven't found any solution anywhere. Given the dataframe df: team1 team2 score1 score2 0 A B 1 0 1 C A 3 2 2 B A 2 3 3 A C ...
Moving average for value present in two dataframe columns in python
I'm stuck with the following problem since last night and I haven't found any solution anywhere. Given the dataframe df: team1 team2 score1 score2 0 A B 1 0 1 C A 3 2 2 B A 2 3 3 A C 2 1 I would like to pass a function that calculates moving ave...
[ "Given the clarification in comments I'll suggest this...\nIn [2]: df\nOut[2]:\n team1 team2 score1 score2\n0 A B 1 0\n1 C A 3 2\n2 B A 2 3\n3 A C 2 1\n\nIn [3]: # restructure data frame\n ...: df_team_scores = pd.wide_to_long(df.a...
[ 1 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074463830_numpy_pandas_python.txt
Q: Group by a category I have done KMeans clusters and now I need to analyse each individual cluster. For example look at cluster 1 and see what clients are on it and make conclusions. dfRFM['idcluster'] = num_cluster dfRFM.head() idcliente Recencia Frecuencia Monetario idcluster 1 3 251 ...
Group by a category
I have done KMeans clusters and now I need to analyse each individual cluster. For example look at cluster 1 and see what clients are on it and make conclusions. dfRFM['idcluster'] = num_cluster dfRFM.head() idcliente Recencia Frecuencia Monetario idcluster 1 3 251 44 -90.11 ...
[ "To filter a dataframe, the most common way is to use df[df[colname] == val] Then you can use df.sort_values()\nIn your case, that would look like this:\ndfRFM_id0 = dfRFM[dfRFM['idcluster']==0].sort_values('Monetario')\n\nThe way this filtering works is that dfRFM['idcluster']==0 returns a series of True/False bas...
[ 0, 0 ]
[]
[]
[ "k_means", "pandas", "python" ]
stackoverflow_0074464475_k_means_pandas_python.txt
Q: Tkinter delete not working on referenced entry when referenceing lenth of entry I have a tkinter window class that I've made and my delete function is not working properly. my_window = tk.Tk() class QuoteForm(): def __init__(self,master): self.file_data = '' self.master = master self....
Tkinter delete not working on referenced entry when referenceing lenth of entry
I have a tkinter window class that I've made and my delete function is not working properly. my_window = tk.Tk() class QuoteForm(): def __init__(self,master): self.file_data = '' self.master = master self.master.rowconfigure(0, weight=1) self.master.rowconfigure(1, weight= 1) ...
[ "It's all about yourvalidate_ent function. Only when it returns true then your entry text can change. While typing tkinter just sent single chars like '1','2','a'. Even when you remove with backspace, this function gets the character you are trying to remove. However when you try to clear it function gets as an inp...
[ 0 ]
[]
[]
[ "python", "tkinter", "tkinter_entry" ]
stackoverflow_0074464010_python_tkinter_tkinter_entry.txt
Q: Two forms on same template in django. How to collaborate the template with the views.py? I have a template with two forms like this and two textareas where the uploaded content will be returned: <form class="form-inline" role="form" action="/controlepunt140" metho...
Two forms on same template in django. How to collaborate the template with the views.py?
I have a template with two forms like this and two textareas where the uploaded content will be returned: <form class="form-inline" role="form" action="/controlepunt140" method="POST" enctype="multipart/form-data" id="form_pdf" ...
[ "According to the name of the submit buttons:\n#FORM PDF\n<button type=\"submit\" name=\"form_pdf\" class=\"btn btn-warning\">Upload!</button>\n\n#FORM EXCEL\n<button type=\"submit\" name=\"form_excel\" class=\"btn btn-warning\">Upload!</button>\n\nSo, in your views.py you can distinguish them on this way:\nif requ...
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074464152_django_python.txt
Q: Loading pandas data frame from pickle file in S3 bucket to AWS Lambda - problem with type I created a machine-learning model with a KNN classifier. Then, I made a pickle file of the test dataset and uploaded it to the AWS S3 bucket using AWS SDK. For testing purposes, I have downloaded it and tested the type with ...
Loading pandas data frame from pickle file in S3 bucket to AWS Lambda - problem with type
I created a machine-learning model with a KNN classifier. Then, I made a pickle file of the test dataset and uploaded it to the AWS S3 bucket using AWS SDK. For testing purposes, I have downloaded it and tested the type with the following: with open("C:\\...path...\\test_features.pkl", 'rb') as f: test_data= pickle...
[ "You will need to read content first then use pickle to load the content and create data frame\ntest_features = s3.get_object(Bucket=bucket, Key= key)\nbody = test_features['Body'].read()\ntest_data = pickle.loads(body)\nprint(type(test_data))\n\n" ]
[ 0 ]
[]
[]
[ "amazon_web_services", "aws_lambda", "mlops", "pandas", "python" ]
stackoverflow_0074464062_amazon_web_services_aws_lambda_mlops_pandas_python.txt
Q: Saving a cross-validation trained model in Scikit I have trained a model in scikit-learn using Cross-Validation and Naive Bayes classifier. How can I persist this model to later run against new instances? Here is simply what I have, I can get the CV scores but I don't know how to have access to the trained model g...
Saving a cross-validation trained model in Scikit
I have trained a model in scikit-learn using Cross-Validation and Naive Bayes classifier. How can I persist this model to later run against new instances? Here is simply what I have, I can get the CV scores but I don't know how to have access to the trained model gnb = GaussianNB() scores = cross_validation.cross_val_...
[ "cross_val_score doesn't changes your estimator, and it will not return fitted estimator. It just returns score of estimator of cross validation.\nTo fit your estimator - you should call fit on it explicitly with provided dataset.\nTo save (serialize) it - you can use pickle:\n# To fit your estimator\ngnb.fit(data_...
[ 17, 0 ]
[]
[]
[ "cross_validation", "pickle", "python", "scikit_learn" ]
stackoverflow_0032700797_cross_validation_pickle_python_scikit_learn.txt
Q: Use pandas df column as legend label? When plotting a pandas Datafarme column is it possible to use the Dataframe column name as the legend label instead of explicitly specifying the label? Example: import matplotlib.pyplot as plt import pandas as pd df = pd.DataFrame(data={'col1': [0, 2, 1, 3], ...
Use pandas df column as legend label?
When plotting a pandas Datafarme column is it possible to use the Dataframe column name as the legend label instead of explicitly specifying the label? Example: import matplotlib.pyplot as plt import pandas as pd df = pd.DataFrame(data={'col1': [0, 2, 1, 3], 'col2': [9,7,8,9]}, ...
[ "Use the pandas plotting API:\nfig, ax = plt.subplots()\ndf['col1'].plot(ax=ax)\nax.legend()\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "matplotlib", "pandas", "python" ]
stackoverflow_0074464530_dataframe_matplotlib_pandas_python.txt
Q: My Arduino via communication with my Raspberry Pi isn't outputting correctly? I'm trying to test and send a variable from my Raspberry Pi to my Arduino to turn my Stepper Motor, but it's not turning as it would if I put in a variable into the Arduino code itself and turn. Here is my code for the Arduino: #include ...
My Arduino via communication with my Raspberry Pi isn't outputting correctly?
I'm trying to test and send a variable from my Raspberry Pi to my Arduino to turn my Stepper Motor, but it's not turning as it would if I put in a variable into the Arduino code itself and turn. Here is my code for the Arduino: #include <AccelStepper.h> AccelStepper stepper(1,7,6); // Defaults to AccelStepper::FULL4WIR...
[ "Are you sure the Python code you wrote is correct?\nThe code have syntax errors. There is nothing inside the loop. Do you get any exception?\nIt should be like this:\nimport serial\nser = serial.Serial('/dev/ttyACM0',9600) \n\nwhile True: \n theta = 90 \n ser.write(theta)\n\n" ]
[ 0 ]
[]
[]
[ "arduino", "pyserial", "python", "raspberry_pi", "stepper" ]
stackoverflow_0074464582_arduino_pyserial_python_raspberry_pi_stepper.txt
Q: Expanding Nested lists in Python without fully flattening Suppose I have a list with nested lists such of strings such as: items = ['Hello', ['Ben', 'Chris', 'Linda'], '! The things you can buy today are', ['Apples', 'Oranges']] I want a list of strings that combine and flatten the nested lists into all possibili...
Expanding Nested lists in Python without fully flattening
Suppose I have a list with nested lists such of strings such as: items = ['Hello', ['Ben', 'Chris', 'Linda'], '! The things you can buy today are', ['Apples', 'Oranges']] I want a list of strings that combine and flatten the nested lists into all possibilities such that the result is: new_list = ['Hello Ben ! The thin...
[ "You need itertools.product().\nHere is it in action:\n>>> items = [['Hello'], ['Ben', 'Chris', 'Linda']]\n>>> list(itertools.product(*items))\n[('Hello', 'Ben'), ('Hello', 'Chris'), ('Hello', 'Linda')]\n\nSince itertools.product() takes list of lists as an input, so some transformation is needed in your code to co...
[ 3, 0 ]
[]
[]
[ "flatten", "list", "python", "python_itertools" ]
stackoverflow_0074464216_flatten_list_python_python_itertools.txt
Q: making first letter of input uppercase with split in python I got most of the code down but I am having issues getting the string to space back out after making the first letter of each word uppercase here's what I have so far: message = input('Write a short message.') new_message = message.split() glue = "" for i...
making first letter of input uppercase with split in python
I got most of the code down but I am having issues getting the string to space back out after making the first letter of each word uppercase here's what I have so far: message = input('Write a short message.') new_message = message.split() glue = "" for item in new_message: glue += item[0].upper() + item[1:] print(glue...
[ "try with:\nmessage.capitalize()\n\n", "If you want to capitalize each word you can try capitalize() and the code will look like this:\n message = input('Write a short message.')\n \n new_message = message.split()\n cap_message = [x.capitalize() for x in new_message]\n print(cap_message)\n\n\nmessage.split...
[ 1, 0 ]
[]
[]
[ "for_loop", "input", "python", "split", "uppercase" ]
stackoverflow_0074464471_for_loop_input_python_split_uppercase.txt
Q: Appending to array or looping iterable from fixed array I have been using this method for Ranges. I can't work out an equivalent method for fixed lists/arrays. # What I've been using & OUTPUT I'm looking for. degrees = np.arange(10,50,10) ITER = np.array(degrees) for i in range( 4): x1 = np.sin(np.radians(IT...
Appending to array or looping iterable from fixed array
I have been using this method for Ranges. I can't work out an equivalent method for fixed lists/arrays. # What I've been using & OUTPUT I'm looking for. degrees = np.arange(10,50,10) ITER = np.array(degrees) for i in range( 4): x1 = np.sin(np.radians(ITER)) y1 = np.cos(np.radians(ITER )) XY = np.column_stack(...
[ "Your first code runs; why are you trying to write something else?\nBut I think you need to understand the first one better. Let's run it:\nIn [449]: degrees = np.arange(10,50,10)\n ...: ITER = np.array(degrees)\n ...: for i in range( 4): \n ...: x1 = np.sin(np.radians(ITER))\n ...: y1 = np...
[ 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074456449_numpy_python.txt
Q: Calling and splitting a text file I have a text file called test.txt with the words "cat dog frog" in it. I need to split it so each word appears on a new line. Can someone help me please? def get_tokens_from_file(test): with open("test.txt") as f: A: Try this: with open('test.txt','r') as f: for line in...
Calling and splitting a text file
I have a text file called test.txt with the words "cat dog frog" in it. I need to split it so each word appears on a new line. Can someone help me please? def get_tokens_from_file(test): with open("test.txt") as f:
[ "Try this:\nwith open('test.txt','r') as f:\n for line in f:\n for word in line.split():\n print(word) \n\nOr if you want to flatten it:\nwith open('test.txt') as f:\n flat_list=[word for line in f for word in line.split()]\n\n", "The following function does what you need.\nThe function re...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074464290_python.txt
Q: Google OR Tools CP-SAT Solver - scheduling problem with objective to even out shift distribution without hard constraints (max/min per period) I am using Google ORTools using the Python wrapper to solve a nurse scheduling problem but I am having trouble finding a way to implement a constraint that attempts to even...
Google OR Tools CP-SAT Solver - scheduling problem with objective to even out shift distribution without hard constraints (max/min per period)
I am using Google ORTools using the Python wrapper to solve a nurse scheduling problem but I am having trouble finding a way to implement a constraint that attempts to evenly distribute worked shifts without using hard constraints. As an example, I working with a number of weeks, distinct shifts, and employees. For ill...
[ "Fairness is the most complex question in OR.\nYou need to try to capture what you want with equations as sample as possible.\nStd deviation, variance are not simple.\nMinimizing max(worked per person) - min(worked per person);is simple.\nGood luck, this is a tough question to come up with a business acceptable def...
[ 1 ]
[]
[]
[ "constraint_programming", "or_tools", "python" ]
stackoverflow_0074464353_constraint_programming_or_tools_python.txt
Q: COUNT PRIMES: Write a function that returns the number of prime numbers that exist up to and including a given number Can someone help me with my code and let me know what's wrong in it? def count_primes(nums): count = 0 for num in range(2,nums+1): if num%2!=0 or num%3!=0 or num%5!=0: c...
COUNT PRIMES: Write a function that returns the number of prime numbers that exist up to and including a given number
Can someone help me with my code and let me know what's wrong in it? def count_primes(nums): count = 0 for num in range(2,nums+1): if num%2!=0 or num%3!=0 or num%5!=0: count+=1 return count
[ "You need to test it against each number up to the number you are checking for being prime, not just 2, 3 and 5. As there are more primes other than 2, 3 and 5\n", "Does this work? Implemented a basic checker.\ndef check(number):\n if number < 2:\n return False\n else:\n for divisor in range(2...
[ 0, 0 ]
[]
[]
[ "count", "primes", "python" ]
stackoverflow_0074464617_count_primes_python.txt
Q: Remove duplicate rows based on previous rows' values in a specific column I have a dataframe similar to the following example: import pandas as pd data = pd.DataFrame(data={'col1': [1,2,3,4,5,6,7,8,9], 'col2': [1.55,1.55,1.55,1.8,1.9,1.9,1.9,2.1,2.1]}) In the second column, col2, several duplicate values can be s...
Remove duplicate rows based on previous rows' values in a specific column
I have a dataframe similar to the following example: import pandas as pd data = pd.DataFrame(data={'col1': [1,2,3,4,5,6,7,8,9], 'col2': [1.55,1.55,1.55,1.8,1.9,1.9,1.9,2.1,2.1]}) In the second column, col2, several duplicate values can be seen, 3 times 1.55, 3 times 1.9 and 2 times 2.1. What I need to do is remove all...
[ "You can use shift:\ndata.loc[data['col2'] != data['col2'].shift(1)]\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "duplicates", "pandas", "python" ]
stackoverflow_0074464714_dataframe_duplicates_pandas_python.txt
Q: How to insert character ('-") every time my string changes from text to number and vice versa? This is an example of a bigger dataframe. Imagine I have a dataframe like this: import pandas as pd df = pd.DataFrame({"ID":["4SSS50FX","2TT1897FA"], "VALUE":[13, 56]}) df Out[2]: ID VALU...
How to insert character ('-") every time my string changes from text to number and vice versa?
This is an example of a bigger dataframe. Imagine I have a dataframe like this: import pandas as pd df = pd.DataFrame({"ID":["4SSS50FX","2TT1897FA"], "VALUE":[13, 56]}) df Out[2]: ID VALUE 0 4SSS50FX 13 1 2TT1897FA 56 I would like to insert "-" in the strings from df["ID"] e...
[ "You can use a regular expression with lookarounds.\ndf['ID'] = df['ID'].str.replace(r'(?<=\\d)(?=[A-Z])|(?<=[A-Z])(?=\\d)', '-')\n\nThe regexp matches an empty string that's either preceded by a digit and followed by a letter, or vice versa. This empty string is then replaced with -.\n", "Use a regex.\n>>> df['I...
[ 1, 1 ]
[]
[]
[ "pandas", "python", "series" ]
stackoverflow_0074464690_pandas_python_series.txt
Q: exchangelib ews throttling policies python I am trying to build a database with all the emails. But I get the Error: ErrorServerBusy: The server cannot service this request right now. Try again later. Is there any way to work with the throttling policy of ews? One month of emails do work but when I exceed some n...
exchangelib ews throttling policies python
I am trying to build a database with all the emails. But I get the Error: ErrorServerBusy: The server cannot service this request right now. Try again later. Is there any way to work with the throttling policy of ews? One month of emails do work but when I exceed some not known barrier it gets interrupted. Are there ...
[ "You created a Configuration object that defines a retry policy, which is what you want to solve your issue. But you never passed the configuration to your Account object. To do that, create your account as:\naccount = Account(shared_postbox, config=config, autodiscover=True)\n\n" ]
[ 1 ]
[]
[]
[ "exchangelib", "exchangewebservices", "outlook", "python", "python_requests" ]
stackoverflow_0074454121_exchangelib_exchangewebservices_outlook_python_python_requests.txt
Q: Implement Simple linear regression for predicting a response using a single feature using python using this data as refrance import numpy as np import matplotlib.pyplot as plt def estimate_coef(x, y): # number of observations/points n = np.size(x) # mean of x and y vector m_x = np.mean(x) ...
Implement Simple linear regression for predicting a response using a single feature using python
using this data as refrance import numpy as np import matplotlib.pyplot as plt def estimate_coef(x, y): # number of observations/points n = np.size(x) # mean of x and y vector m_x = np.mean(x) m_y = np.mean(y) # calculating cross-deviation and deviation about x SS_xy = np.sum(y*x) -...
[ "I replicate your code on my machine and it works perfectly, there is no bug in your code.\nLibrary and its version that installed in my colab\nPython : 3.7.15\nNumpy : 1.21.6\nMatplotlib : 3.2.2\n\nYou can also restart runtime it may solve your problem\nclick on Runtime\nSelect Restart runtime and then cl...
[ 0 ]
[]
[]
[ "linear_regression", "prediction", "python", "regression" ]
stackoverflow_0074441304_linear_regression_prediction_python_regression.txt
Q: Python change the starting values on the plot I have data set which looks like this: Hour_day Profits 7 645 3 354 5 346 11 153 23 478 7 464 12 356 0 346 I crated a line plot to visualize the hour on the x-axis and the profit va...
Python change the starting values on the plot
I have data set which looks like this: Hour_day Profits 7 645 3 354 5 346 11 153 23 478 7 464 12 356 0 346 I crated a line plot to visualize the hour on the x-axis and the profit values on y-axis. My code worked good with me but the...
[ "From what I know you have two options:\nCreate a sub DF that excludes the rows that have an Hour_day value under 5 and proceed with the rest of your code as normal:\ndf_new = df.where(df['Hour_day'] >= 5)\n\nor, you might be able to set the x_ticks:\ndefault_x_ticks = range(5:23)\nplt.plot(hours, y_values, color='...
[ 0 ]
[]
[]
[ "pandas", "plot", "python", "scikit_learn", "visualization" ]
stackoverflow_0074463935_pandas_plot_python_scikit_learn_visualization.txt
Q: Discrepancy in the number of trainable parameters between model.summary and len(conv_model.trainable_weights) Consider this tensorflow python code that loads a pretrained model: import tensorflow as tf conv_model = keras.applications.vgg16.VGG16( weights='imagenet', include_top=False) conv_model.trainable=...
Discrepancy in the number of trainable parameters between model.summary and len(conv_model.trainable_weights)
Consider this tensorflow python code that loads a pretrained model: import tensorflow as tf conv_model = keras.applications.vgg16.VGG16( weights='imagenet', include_top=False) conv_model.trainable=False print("Number of trainable weights after freezing: ", len(conv_model.trainable_weights)) conv_model.trainable...
[ "Length of the weights doesnt give the total parameters. You should use:\nfrom keras.utils.layer_utils import count_params\nnp.sum([count_params(p) for p in conv_model.trainable_weights])\n#14714688\n\ninstead of,\nlen(conv_model.trainable_weights)\n\nLength gives the number of kernels and biases and each of them c...
[ 1 ]
[]
[]
[ "pre_trained_model", "python", "tensorflow" ]
stackoverflow_0074464164_pre_trained_model_python_tensorflow.txt
Q: Based on a condition, how to fill columns with column names whose row are not null Hello my problem is almost the same as this post : How to fill in a column with column names whose rows are not NULL in Pandas? But in my case, instead of doing a concatenation, I need to fill the column based on wether the columns ...
Based on a condition, how to fill columns with column names whose row are not null
Hello my problem is almost the same as this post : How to fill in a column with column names whose rows are not NULL in Pandas? But in my case, instead of doing a concatenation, I need to fill the column based on wether the columns name are a Country or a Segment. Edit : the table Originally I have this : Segment ...
[ "Given:\n Segment Country Segment 1 Country 1 Segment 2\n0 Seg1;Country1 Seg1;Country1 123456 123456 Nan\n1 Nan Nan Nan Nan Nan\n2 country1;seg2 country1;seg2 Nan 123456 123456\n3 country1;seg2 country1;seg2 Nan 123456 ...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074461934_dataframe_pandas_python.txt
Q: I have a dictionary {string and int}. How do I compare integers values and not the keys within the same dictionary(python) I have a dictionary of people, I want to sort people alphabetically by name IF they are the same age, and to sort people descending by age if they are different age. So essentually, I need to ...
I have a dictionary {string and int}. How do I compare integers values and not the keys within the same dictionary(python)
I have a dictionary of people, I want to sort people alphabetically by name IF they are the same age, and to sort people descending by age if they are different age. So essentually, I need to return two outputs. Here is what I have so far, but it doesn't take in account the condition. How do I just compare the age valu...
[ "You can pass tuple to key of sorted. First sort based on age then sort base alphabet.\npeople = {'Steve' : 20 , 'David': 21 , 'Andrew' : 19 , 'Bruce': 22 ,'James' : 20 , 'Dave': 26 ,'Smith' : 19}\n\nres = dict(sorted(people.items(), key=lambda x: (x[1], x[0])))\n# -------------------------------------------x[1]^^^...
[ 1 ]
[]
[]
[ "dictionary", "python", "sorting" ]
stackoverflow_0074464828_dictionary_python_sorting.txt
Q: How can I create a function that uses loc over multiple columns in a dataframe? I have a number of columns in a pandas dataframe where any values that are less than or equal to zero I want to change to NaN. I'm relatively new to python. I know copying and pasting code over multiple lines is a no-no, but I've strug...
How can I create a function that uses loc over multiple columns in a dataframe?
I have a number of columns in a pandas dataframe where any values that are less than or equal to zero I want to change to NaN. I'm relatively new to python. I know copying and pasting code over multiple lines is a no-no, but I've struggled with writing functions so far. I would imagine there's an easier way to do this,...
[ "You can use df.where, which would replace the values that doesn't satisfy a condition with NaN:\ncols = ['col1', 'col2', 'col3', 'col4']\ndf = df.where(df[cols] > 0)\n\n" ]
[ 0 ]
[]
[]
[ "function", "numpy", "pandas", "python" ]
stackoverflow_0074464803_function_numpy_pandas_python.txt
Q: Using ffmpeg on PythonAnywhere My (first) web app uses pydub, which depends on ffmpeg. On my local windows environment, I installed ffmpeg and added the path to the ffmpeg executables to the windows "path" environment variables. It all works locally, but bow that I have deployed my app to PythonAnywhere, the follo...
Using ffmpeg on PythonAnywhere
My (first) web app uses pydub, which depends on ffmpeg. On my local windows environment, I installed ffmpeg and added the path to the ffmpeg executables to the windows "path" environment variables. It all works locally, but bow that I have deployed my app to PythonAnywhere, the following line in my code is causing an e...
[ "Got home and tried PythonAnywhere myself, and I don't find any issue with it and its FFmpeg.\nWithout installing anything (no FFmpeg, no Python packages), I run successfully in REPL:\n>>> os.system('ffmpeg')\n[snipped ffmpeg banner]\n>>> import pydub\n>>> pydub.utils.get_encoder_name()\n'ffmpeg'\n>>> pydub.utils.g...
[ 1, 1 ]
[]
[]
[ "environment_variables", "ffmpeg", "pydub", "python", "pythonanywhere" ]
stackoverflow_0074448842_environment_variables_ffmpeg_pydub_python_pythonanywhere.txt
Q: Parsing long form dates from string I am aware that there are other solutions to similar problems on stack overflow but they don't work in my particular situation. I have some strings -- here are some examples of them. string_with_dates = "random non-date text, 22 May 1945 and 11 June 2004" string2 = "random non-d...
Parsing long form dates from string
I am aware that there are other solutions to similar problems on stack overflow but they don't work in my particular situation. I have some strings -- here are some examples of them. string_with_dates = "random non-date text, 22 May 1945 and 11 June 2004" string2 = "random non-date text, 01/01/1999 & 11 June 2004" stri...
[ "Okay sorry to anyone who spent time on this -- but I was able to answer my own question. Leaving this up in case anyone else has the same issue.\nThis package was able to work perfectly: https://pypi.org/project/datefinder/\n\nimport datefinder\n\ndef DatesToList(x):\n \n dates = datefinder.find_dates(x)\n ...
[ 2 ]
[]
[]
[ "date", "parsing", "python", "python_3.x", "string" ]
stackoverflow_0074462363_date_parsing_python_python_3.x_string.txt
Q: Error while installing lxml through pip: Microsoft Visual C++ 14.0 is required I am on a windows 10 machine and recently moved from python 2.7 to 3.5. When trying to install lxml through pip, it stops and throws this error message- building 'lxml.etree' extension error: Microsoft Visual C++ 14.0 is required. G...
Error while installing lxml through pip: Microsoft Visual C++ 14.0 is required
I am on a windows 10 machine and recently moved from python 2.7 to 3.5. When trying to install lxml through pip, it stops and throws this error message- building 'lxml.etree' extension error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/vi...
[ "Have you checked that when you installed Visual Studio, you installed the C++ compiler? It seems like a silly question, but this is the mistake I made. Check by going into the setup for visual studio (Programs and features: Modify \"Visual Studio 2015\"), then under Programming Languages->VC++, make sure it's tick...
[ 28, 8, 6, 2, 1, 0, 0 ]
[ "First:\npip install wheel\n\nSecond: go to http://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml\nand download proper wheel.\npip install the file you downloaded (.whl).\n" ]
[ -2 ]
[ "lxml", "pip", "python", "visual_c++" ]
stackoverflow_0038949519_lxml_pip_python_visual_c++.txt
Q: Numpy check that all the element of each row of a 2D numpy array is the same I am sure this is an already answered question, but I couldn't find anywhere. I want to check that all the element of each row of a 2D numpy array is the same and 0 is a possibility. For example: >>> a = np.array([[0, 0, 0], [1, 1, 1], [2...
Numpy check that all the element of each row of a 2D numpy array is the same
I am sure this is an already answered question, but I couldn't find anywhere. I want to check that all the element of each row of a 2D numpy array is the same and 0 is a possibility. For example: >>> a = np.array([[0, 0, 0], [1, 1, 1], [2, 2, 2], [3, 3, 3]]) >>> a array([[0, 0, 0], [1, 1, 1], [2, 2, 2], ...
[ "You can simply do the following:\nresult = (a[:, 1:] == a[:, :-1]).all()\n\nOr, with broadcasting:\nresult = (a[:, 1:] == a[:, [0]]).all()\n\nresult = (a == a[:, [0]]).all() is similar, but the above avoids the redundant comparison of the column a[:,0] to itself.\n" ]
[ 1 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0074464801_arrays_numpy_python.txt
Q: Impute null values based on a group statistic I have a copy dataset using df.dropna() and I have compiled the mean of those data using df.groupby based on different groups with the converted code below assigned in: # Suppose this is a result from df.groupby script impute_data = pd.DataFrame({'PClass': [1, 1, 2, 2...
Impute null values based on a group statistic
I have a copy dataset using df.dropna() and I have compiled the mean of those data using df.groupby based on different groups with the converted code below assigned in: # Suppose this is a result from df.groupby script impute_data = pd.DataFrame({'PClass': [1, 1, 2, 2, 3, 3], 'Sex': ['male', 'female', 'male', 'female'...
[ "You can use update after renaming Mean to Age:\nimpute_data.rename({'Mean':'Age'}, axis=1, inplace=True)\ndf.update(impute_data)\n\nNote that update occurs in place, you shouldn't assign it to another dataframe.\n" ]
[ 0 ]
[]
[]
[ "data_analysis", "data_science", "pandas", "python" ]
stackoverflow_0074464863_data_analysis_data_science_pandas_python.txt
Q: how to convert a method type to a type that can be multiplied: TypeError: unsupported operand type(s) for *: 'method' and 'Piecewise' i have a problem that i need to multiply the type {method} and a piecewise function, all in symbolic sympy. i try to multiply a Piecewise expression with Derivative of another expre...
how to convert a method type to a type that can be multiplied: TypeError: unsupported operand type(s) for *: 'method' and 'Piecewise'
i have a problem that i need to multiply the type {method} and a piecewise function, all in symbolic sympy. i try to multiply a Piecewise expression with Derivative of another expression that. the result of the Derivative expression is from a type 'method' here is my code: import sympy as sp import numpy as np import m...
[ "Okay well the mistake is obvious. u.diff is clearly a function, not a number; but it's not being called like a function. The function itself is being assigned to utag. So, you're trying to multiply the function u.diff with the value Ntag[i]. But u.diff is not a numerical value, it is just a function. You'd have to...
[ 1 ]
[]
[]
[ "methods", "python", "sympy", "typeerror", "types" ]
stackoverflow_0074464674_methods_python_sympy_typeerror_types.txt
Q: Is there a way to define sets, variables and constraints intelligently in PYOMO without cross product? I have three different sets Number of Store - 100 Number of Products - 10 Number of Size in each product - 10 I want to create Parameter in pyomo which is combination of above three sets. Basically i want to sk...
Is there a way to define sets, variables and constraints intelligently in PYOMO without cross product?
I have three different sets Number of Store - 100 Number of Products - 10 Number of Size in each product - 10 I want to create Parameter in pyomo which is combination of above three sets. Basically i want to skip cross product which have code snippet below. Reason to skip below approach is each product can have 10 di...
[ "So, if I understand your dilemma, the sizes are different for different products and a universal cross-set of products and sizes doesn't work because of that.\nI think you have 2 options. Either works.\nThe easies thing to do would be just to make tuples of product-size pairs and use that as a set...basically mer...
[ 0 ]
[]
[]
[ "pyomo", "python" ]
stackoverflow_0074461347_pyomo_python.txt
Q: parse html using Python's "xml" module ParseError on meta tag I'm trying to parse some html using the xml python library. The html I'm trying to parse is from download.docker.com which breaks out to, <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Index of linux/ubuntu/dists/jammy/pool/stable/amd64/</t...
parse html using Python's "xml" module ParseError on meta tag
I'm trying to parse some html using the xml python library. The html I'm trying to parse is from download.docker.com which breaks out to, <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Index of linux/ubuntu/dists/jammy/pool/stable/amd64/</title> </head> <body> <h1>Index of linux/ubuntu/dists/jammy/pool/sta...
[ "\nIs there any way to parse this html using the xml python library instead of lxml?\n\nThe answer is no.\nAn XML library (for example xml.etree.ElementTree) cannot be used to parse arbitrary HTML. It can be used to parse HTML that also happens to be well-formed XML. But your HTML document is not well-formed.\nlxml...
[ 1 ]
[]
[]
[ "html", "python", "xml" ]
stackoverflow_0074353760_html_python_xml.txt
Q: why tensorflow uses 100% of all CPU cores? I've made a fresh install of Jupyter Notebook kernel and python packages, including tensorflow 2.4.1 (using miniconda env). When I train and test a model, my CPU usage saturate. In my old install, that's not happen (low CPU usage), and the time to accomplish the tasks was...
why tensorflow uses 100% of all CPU cores?
I've made a fresh install of Jupyter Notebook kernel and python packages, including tensorflow 2.4.1 (using miniconda env). When I train and test a model, my CPU usage saturate. In my old install, that's not happen (low CPU usage), and the time to accomplish the tasks was barely the same. Is there a config of jupyter a...
[ "In our multiuser environment we need to keep some of the cpu's free for higher prioritized jobs (we don't have the rights to 'nice' processes). So reducing tensorflows (Version 2.8.2) cpu-greed is quite essential. The abovementioned solution works in our purely cpu environment (linux, 40 cores) with a restriction ...
[ 0 ]
[]
[]
[ "cpu", "jupyter_notebook", "python", "tensorflow" ]
stackoverflow_0068954373_cpu_jupyter_notebook_python_tensorflow.txt
Q: Get positional information from one object and apply it to another I am trying to query the location of an object (x,y,z coordinates) with xform, and then set the values harvested from xform to use in a setAttr command to influence the translation of a different object. pos = cmds.xform('pSphere1', r=True, ws=True...
Get positional information from one object and apply it to another
I am trying to query the location of an object (x,y,z coordinates) with xform, and then set the values harvested from xform to use in a setAttr command to influence the translation of a different object. pos = cmds.xform('pSphere1', r=True, ws=True, q=True, t=True ) print(pos) cmds.setAttr('pSphere2', tx=pos[0], ty=pos...
[ "You are supposed to use it like that :\n cmds.setAttr('pSphere2.tx', pos[0])\n\nand your query should be\n pos = cmds.xform('pSphere1', ws=True, q=True, t=True )\n\nTo apply you can also do\n cmds.xform('pSphere2', ws=True, t=pos )\n\n", "Something which is also possible with those commands :\npos = cmd...
[ 0, 0 ]
[]
[]
[ "maya", "python" ]
stackoverflow_0074437245_maya_python.txt
Q: Object not callable in python class in flask application This is my first flask application and i tried my best to get it running. Nevertheless i stuck into one error. I tried to create a python flask app but stuck into an error. here is my code flask.py from test_displayclass import Bartender class MyFlask: ...
Object not callable in python class in flask application
This is my first flask application and i tried my best to get it running. Nevertheless i stuck into one error. I tried to create a python flask app but stuck into an error. here is my code flask.py from test_displayclass import Bartender class MyFlask: bartender = Bartender() def __init__(self): #self...
[ "Need of taken the function self.oled.image(image)\n" ]
[ 0 ]
[]
[]
[ "adafruit_circuitpython", "python" ]
stackoverflow_0074459896_adafruit_circuitpython_python.txt
Q: How to calculate numbers in a list? I have to add every number with one behind it in the list using loops or functions example text; list[1,2,3] => (1+3)+(2+1)+(3+2) output = 12 example code; myList = [1,2,3] x = myList [0] + myList [2] x = x + (myList [1]+myList [0]) x = x + (myList [2]+myList [1]) print(x) # 1...
How to calculate numbers in a list?
I have to add every number with one behind it in the list using loops or functions example text; list[1,2,3] => (1+3)+(2+1)+(3+2) output = 12 example code; myList = [1,2,3] x = myList [0] + myList [2] x = x + (myList [1]+myList [0]) x = x + (myList [2]+myList [1]) print(x) # 12 I dont want to calculate them using su...
[ "In python, list[-1] returns the last element of the list so doing something like this should do the job -\nmyList = [1,2,3]\ntotal = 0\nfor i, num in enumerate(myList):\n print(num, myList[i-1])\n total += num + myList[i-1]\nprint(total)\n\nOutput:\n1 3\n2 1\n3 2\n12\n\n", "Loop through the list, adding th...
[ 1, 1, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074464989_list_python.txt
Q: Skfuzzy - get membership value from output I made a fuzzy logic model using skfuzzy. On the basis of the calculated output, I would like to assign myself a category (low, medium, high) in the dataframe table to which the calculated value belongs. I can't get the category name from the output. How can I do it in sk...
Skfuzzy - get membership value from output
I made a fuzzy logic model using skfuzzy. On the basis of the calculated output, I would like to assign myself a category (low, medium, high) in the dataframe table to which the calculated value belongs. I can't get the category name from the output. How can I do it in skfuzzy? My model: def fuzzy_logic(s, v, d): h...
[ "Here's how you do it. You can use skfuzzy.interp_membership and apply it to all the Consequent membership function and get the max() value:\nprint(interp_membership(diameter.universe, diameter['poor'].mf, diameters.output['diameter']))\nprint(interp_membership(diameter.universe, diameter['average'].mf, diameters.o...
[ 0 ]
[]
[]
[ "fuzzy", "numpy", "pandas", "python", "skfuzzy" ]
stackoverflow_0073373581_fuzzy_numpy_pandas_python_skfuzzy.txt
Q: How to obtain multiple solutions of a binary LP problem using Google's OR-Tools in Python? I am new to integer optimization. I am trying to solve the following large (although not that large) binary linear optimization problem: max_{x} x_1+x_2+...+x_n subject to: A*x <= b ; x_i is binary for all i=1,...,n As you c...
How to obtain multiple solutions of a binary LP problem using Google's OR-Tools in Python?
I am new to integer optimization. I am trying to solve the following large (although not that large) binary linear optimization problem: max_{x} x_1+x_2+...+x_n subject to: A*x <= b ; x_i is binary for all i=1,...,n As you can see, . the control variable is a vector x of lengh, say, n=150; x_i is binary for all i=1,......
[ "Is your matrix A integral ? if not, you are not solving the same problem with scip and CP-SAT.\nFurthermore, why use scip? You should solve both part with the same solver.\nFurthermore, I believe the default solution pool implementation in scip will return all solutions found, in reverse order, thus in decreasing ...
[ 1, 0 ]
[]
[]
[ "integer_programming", "linear_programming", "or_tools", "python" ]
stackoverflow_0074464351_integer_programming_linear_programming_or_tools_python.txt
Q: How to convert a column value to list in Python I need to convert the value in the column 'value' to a list format. The dataframe df: emp_no value 0 390 10.0 1 395 20.0 2 397 30.0 3 522 40.0 4 525 40.0 Output should be: emp_no value 0 390 [5,10.0] 1 395 [5,20.0]...
How to convert a column value to list in Python
I need to convert the value in the column 'value' to a list format. The dataframe df: emp_no value 0 390 10.0 1 395 20.0 2 397 30.0 3 522 40.0 4 525 40.0 Output should be: emp_no value 0 390 [5,10.0] 1 395 [5,20.0] 2 397 [5,30.0] 3 522 [5,40.0] 4 525 ...
[ "import pandas as pd\n\ndf = pd.DataFrame({\"emp_no\": [1, 2, 3], \"value\": [10.0, 20.0, 30.0]})\n\ndf['value'] = df['value'].astype('object')\nfor index, row in df.iterrows():\n df.at[index, 'value'] = [5, df.at[index, 'value']]\n\nprint(df)\n\n# emp_no value\n# 0 1 [5, 10.0]\n# 1 2 [5, ...
[ 1, 1 ]
[]
[]
[ "dataframe", "list", "multiple_columns", "python", "row" ]
stackoverflow_0074465018_dataframe_list_multiple_columns_python_row.txt
Q: Get rid of annoying output I'm working with the following function: from moviepy.video.io.ffmpeg_tools import ffmpeg_extract_subclip if ffmpeg_extract_subclip("c:\\users\\samuel\\desktop\\VideosYT\\randomvideo.mp4", 0, 10, targetname="test.mp4"): print("") which is giving me the following output: Moviepy - Run...
Get rid of annoying output
I'm working with the following function: from moviepy.video.io.ffmpeg_tools import ffmpeg_extract_subclip if ffmpeg_extract_subclip("c:\\users\\samuel\\desktop\\VideosYT\\randomvideo.mp4", 0, 10, targetname="test.mp4"): print("") which is giving me the following output: Moviepy - Running: >>> "+ " ".join(cmd) Movie...
[ "There is a logger parameter of the function after I searched for the source code. Here's a link!\nYou can try to set it to None:\nif ffmpeg_extract_subclip(\"c:\\\\users\\\\samuel\\\\desktop\\\\VideosYT\\\\randomvideo.mp4\", 0, 10, targetname=\"test.mp4\", logger=None):\n print(\"\")\n\n" ]
[ 0 ]
[]
[]
[ "moviepy", "output", "python", "subprocess" ]
stackoverflow_0074465063_moviepy_output_python_subprocess.txt
Q: How to show long text in tkinter tksheet cells? I have been learning tkinter and found a module tksheet, which helps me to show the tables. I am tinkering with the documentation, and try to create a simple table. I encountered one problem, sometimes the text are long and I want to show the whole text in the table....
How to show long text in tkinter tksheet cells?
I have been learning tkinter and found a module tksheet, which helps me to show the tables. I am tinkering with the documentation, and try to create a simple table. I encountered one problem, sometimes the text are long and I want to show the whole text in the table. (I can set geometry of root app, but I am talking ab...
[ "With reference to issues in github: https://github.com/ragardner/tksheet/issues/9\nI found the solution:\nsheet.set_all_cell_sizes_to_text()\n\n" ]
[ 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074464957_python_tkinter.txt
Q: PYQT5 - Update a label when a QPushButton is checked/unchecked How do I change the text of a label when QPushButton with checkable set to True is checked or unchecked. I am using the buttons as a seat selection chart and on clicking a certain seat I want to update a label(or, if possible something else) that will ...
PYQT5 - Update a label when a QPushButton is checked/unchecked
How do I change the text of a label when QPushButton with checkable set to True is checked or unchecked. I am using the buttons as a seat selection chart and on clicking a certain seat I want to update a label(or, if possible something else) that will show the price based on seat selection, and would deduct the value w...
[]
[]
[ "As musicamante mentioned in the comment, connect a slot or that will do what ever you want:\nvseat.buttonToggled.connect(your_slot_function)\n\nAnd impelent the changes inside slot func.\n" ]
[ -1 ]
[ "pyqt5", "python", "qt" ]
stackoverflow_0074463401_pyqt5_python_qt.txt
Q: Validate URL paths with a specified amount of parts only just trying to work out the regex for this. Say I have to following list of URL paths /v1/users/ /v1/users/123abc/ /v1/users/123abc/456def/ /v1/users/123abc/456def/789ghi/ /v1/users/123abc/me/ /v1/users/123abc/me/456def/ where some parts are set, like v1 an...
Validate URL paths with a specified amount of parts only
just trying to work out the regex for this. Say I have to following list of URL paths /v1/users/ /v1/users/123abc/ /v1/users/123abc/456def/ /v1/users/123abc/456def/789ghi/ /v1/users/123abc/me/ /v1/users/123abc/me/456def/ where some parts are set, like v1 and users, and some parts are path parameters so they can be any...
[ "You can replace both .*? with [^/]* or even [^/]+ (as subparts must contain at least one char) and use\n^/v1/users/[^/]+/[^/]+/$\n\nSee the regex demo.\nDetails:\n\n^ - start of string\n/v1/users/ - a literal string\n[^/]+ - one or more chars other than /\n/ - a / char\n[^/]+ - one or more chars other than /\n/ - ...
[ 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074464874_python_regex.txt
Q: Calculating the cumulative sum in a list starting at the next element and going through the list in Python Let's say I got a list like this: L = [600, 200, 100, 80, 20] What is the most efficient way to calculate the cumulative sum starting from the next element for every element in the list. The output of should ...
Calculating the cumulative sum in a list starting at the next element and going through the list in Python
Let's say I got a list like this: L = [600, 200, 100, 80, 20] What is the most efficient way to calculate the cumulative sum starting from the next element for every element in the list. The output of should thus be: x_1 = 400 (200 + 100 + 80 + 20) x_2 = 200 (100 + 80 + 20) x_3 = 20 (20) x_4 = 0
[ "try this:\n l = [600, 200, 100, 80, 20]\n res = [sum(l[i:]) for i in range(1, len(l))]\n print(res)\n\nfor your example the output should be [400, 200, 100, 20]\n", "try using cumsum\nL = [600, 200, 100, 80, 20]\ndf=pd.DataFrame(L,columns=['Value'])\ndf['Running_Total'] = df['Value'].cumsum()\ndf['Runni...
[ 1, 0 ]
[ "You can use the sum functio\nsum(L)-L[0]\n" ]
[ -2 ]
[ "list", "python", "sum" ]
stackoverflow_0074464013_list_python_sum.txt
Q: Can I iterate my context at view to put into my template? I've created this function at my views to iterate through my pages. for chapter in chapters: context["chapter_page"] = math.ceil((chapters.index(chapter) + 1) / 2) context["chapter"] = chapters return context I am still making ...
Can I iterate my context at view to put into my template?
I've created this function at my views to iterate through my pages. for chapter in chapters: context["chapter_page"] = math.ceil((chapters.index(chapter) + 1) / 2) context["chapter"] = chapters return context I am still making a for a loop in my template, so I cannot remove him. I added th...
[ "I'm guessing here, because you have omitted a bunch of details, but it looks like you are expecting one chapter_page value per chapter. That's not what you have implemented. You have exactly one global chapter_page value.\nIf you want one per chapter, then that number needs to be part of the chapter object, not ...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074465103_django_python.txt
Q: Solve second order PDEs with `scipy.integrate`, with both initial and final position known I'm confused reading scipy.integrate.solve_ivp documentation. I'm interested in a ballistic problem with drag and Magnus effect, but I'm focussing first on the simpler problem, considering only gravitational force. The corre...
Solve second order PDEs with `scipy.integrate`, with both initial and final position known
I'm confused reading scipy.integrate.solve_ivp documentation. I'm interested in a ballistic problem with drag and Magnus effect, but I'm focussing first on the simpler problem, considering only gravitational force. The corresponding PDE is Transforming to a first order PDE, we can write I have the initial and final 3...
[ "The function scipy.integrate.solve_bvp is indeed appropriate, with p0 and p1: (x(t), y(t), y(t)) at t=T0, T1. For posterity, here are the two functions required by solve_bvp:\ndef bc(X0, X1, args=None):\n x0, y0, z0, vx0, vy0, vz0 = X0\n x1, y1, z1, vx1, vy1, vz1 = X1\n\n return np.array([\n x0 - p...
[ 0 ]
[]
[]
[ "differential_equations", "odeint", "pde", "python", "scipy" ]
stackoverflow_0074444504_differential_equations_odeint_pde_python_scipy.txt
Q: How to get the mean of each image in a batch? I have a batch of images thus the shape [None, 256, 256, 3] (the batch is set to none for practical purposes on use). I am trying to implement a layer that calculates the average of each of the of images or frames in the batch to result the shape [None, 1] or [None, 1,...
How to get the mean of each image in a batch?
I have a batch of images thus the shape [None, 256, 256, 3] (the batch is set to none for practical purposes on use). I am trying to implement a layer that calculates the average of each of the of images or frames in the batch to result the shape [None, 1] or [None, 1, 1, 1]. I have checked to use tf.keras.layers.Avera...
[ "You can play around with the axes like this:\nimport tensorflow as tf\n\nclass ElementMean(tf.keras.layers.Layer):\n def __init__(self, **kwargs):\n super(ElementMean, self).__init__(**kwargs)\n \n def call(self, inputs):\n return tf.reduce_mean(inputs, axis=(1, 2, 3), keepdims=True)\n\nx = ...
[ 1 ]
[ "there is another way with segment means that allowed you to segment by heights, widths, and channels by remain its properties.\n\nSample: Width x Height x Channels, mean of each channel represent its data as mean value and you may summarize them later.\n\nimport os\nfrom os.path import exists\n\nimport tensorflow ...
[ -2 ]
[ "deep_learning", "keras", "machine_learning", "python", "tensorflow" ]
stackoverflow_0074460032_deep_learning_keras_machine_learning_python_tensorflow.txt
Q: Selenium Edge Python errors auto close Edge browser after test execution I am trying to test selenium for a solution to auto log into a website but I cant even get Selenium to stay open. It does what it is supposed to do right now and then quits immediately without a driver.quit(). I get the following errors and ...
Selenium Edge Python errors auto close Edge browser after test execution
I am trying to test selenium for a solution to auto log into a website but I cant even get Selenium to stay open. It does what it is supposed to do right now and then quits immediately without a driver.quit(). I get the following errors and I wish to understand what they mean: DevTools listening on ws://127.0.0.1:5111...
[ "The errors you are seeing:\n[3420:22152:1110/151643.950:ERROR:edge_auth_errors.cc(387)] EDGE_IDENTITY: Get Default OS Account failed: Error: Primary Error: kImplicitSignInFailure, Secondary Error: kAccountProviderFetchError, Platform error: 0, Error string: \n\n[3420:22152:1110/151644.757:ERROR:fallback_task_prov...
[ 2, 0, 0 ]
[]
[]
[ "microsoft_edge", "python", "selenium", "selenium_edgedriver", "selenium_webdriver" ]
stackoverflow_0069919930_microsoft_edge_python_selenium_selenium_edgedriver_selenium_webdriver.txt
Q: "Failed - Download error" while download a file using Selenium Python I was trying to download a file using selenium but getting "Failed - Download error". I tried to disable the safe browsing but it didn't work. I have attached the screenshot and code as well. logs: DevTools listening on ws://127.0.0.1:53738/devt...
"Failed - Download error" while download a file using Selenium Python
I was trying to download a file using selenium but getting "Failed - Download error". I tried to disable the safe browsing but it didn't work. I have attached the screenshot and code as well. logs: DevTools listening on ws://127.0.0.1:53738/devtools/browser/d75dfd5b-1e3e-45c5-8edd-adf77dd9adb1 [2572:2724:0717/104626.87...
[ "It worked when I removed the \"r\" from the path\n\"download.default_directory\": r\"C:\\\\Users\\\\Awais\\\\projects\\\\selenium\\\\web_email_extractor\\\\csv\",\n\nto:\n\"download.default_directory\": \"C:\\\\Users\\\\Awais\\\\projects\\\\selenium\\\\web_email_extractor\\\\csv\",\n\n" ]
[ 0 ]
[ "Dear: When we configure the options of selenium is what will be defined in its configurations and as you write the route so considers it in the first photo you will see a well-configured route and a bad one, note bars there is the difference enter image description here\nenter image description here\n" ]
[ -1 ]
[ "python", "selenium", "selenium_chromedriver", "selenium_webdriver" ]
stackoverflow_0062947965_python_selenium_selenium_chromedriver_selenium_webdriver.txt
Q: How to insert an item into a Queryset which is sorted by a numeric field and increment the value of the field of all subsequent items Let´s say, there is a Django model called TaskModel which has a field priority and we want to insert a new element and increment the existing element which has already the priority ...
How to insert an item into a Queryset which is sorted by a numeric field and increment the value of the field of all subsequent items
Let´s say, there is a Django model called TaskModel which has a field priority and we want to insert a new element and increment the existing element which has already the priority and increment also the priority of the following elements. priority is just a numeric field without any special flags like unique or primar...
[ "I believe you can do this by using Django's F expressions and overriding the model's save method. I guess you could instead override the model's __init__ method as in this answer, but I think using the save method is best.\nclass TaskModel(models.Model):\n task = models.CharField(max_length=20)\n priority =...
[ 2 ]
[]
[]
[ "django", "python", "sql" ]
stackoverflow_0074463989_django_python_sql.txt
Q: Python type conversion using variable value mytype = "int" myvalue = "35" my_int_val = mytype(myvalue) This throws up - TypeError: 'str' object is not callable I can't seem to remember the way to do so. Any ideas? Please note that I have to use "str", "int" instead of str or int (without quotes), because I am ge...
Python type conversion using variable value
mytype = "int" myvalue = "35" my_int_val = mytype(myvalue) This throws up - TypeError: 'str' object is not callable I can't seem to remember the way to do so. Any ideas? Please note that I have to use "str", "int" instead of str or int (without quotes), because I am getting this value from somewhere else where it's b...
[ "If you want to use any builtin function dynamically to convert the data you can fetch it from __builtins__.\nmytype = \"str\"\nmyvalue = \"34\"\n\nfunc = getattr(__builtins__, mytype)\n\nprint(func(myvalue))\nprint(type(func(myvalue)))\n\nThis will give you\n34\n<class 'str'>\n\nIf you use mytype = \"float\" you'l...
[ 3, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074463894_python.txt
Q: Calculating average of the rating field by applying filter on the dataframe enter image description here I have added image here which shows different columns in a dataframe ,so basically i want to calculate average of rating field based on the value Drama which is present in genre field of the dataframe ,which me...
Calculating average of the rating field by applying filter on the dataframe
enter image description here I have added image here which shows different columns in a dataframe ,so basically i want to calculate average of rating field based on the value Drama which is present in genre field of the dataframe ,which means that I will calculate the average rating of rows containing Drama in genre fi...
[ "If the rating column contains lists, you can use astype to be able to use str.contains properly, and then evaluate the mean:\ndf[df['genre'].astype(str).str.contains('Drama')]['rating'].mean()\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "list", "pandas", "python", "series" ]
stackoverflow_0074465279_dataframe_list_pandas_python_series.txt
Q: Making multiple columns into one for .to_datetime Currently I have a code set up to read through a CSV file, but the CSV file has columns DAY, YEAR, and MONTH all as integers. I want to make them all one column of datetime64[ns] objects. To make them datetime64[ns] objects, I did the following: df.insert(0, "DATE"...
Making multiple columns into one for .to_datetime
Currently I have a code set up to read through a CSV file, but the CSV file has columns DAY, YEAR, and MONTH all as integers. I want to make them all one column of datetime64[ns] objects. To make them datetime64[ns] objects, I did the following: df.insert(0, "DATE", 0, True) df["YEAR"] = df["YEAR"].astype(str) df["MONT...
[ "Looking at the pd.to_datetime docs and the columns you listed you should be able to do something like.\ndf[\"DATE\"] = pd.to_datetime(df[[\"YEAR\", \"MONTH\", \"DAY\"]])\n\nCan't say for sure without the data to try it on, but pd.to_datetime should be able to handle these columns without having to alter them.\n" ]
[ 0 ]
[]
[]
[ "analytics", "pandas", "python" ]
stackoverflow_0074465162_analytics_pandas_python.txt
Q: How can I smooth a graph with hundreds of points? I'm working with data from my Spotify account and I've created a dataframe that contains all the minutes in the day and the total playtime during that minute for the last 5 years. The dataframe is this (by the way, I wonder if there is any way to work with time wit...
How can I smooth a graph with hundreds of points?
I'm working with data from my Spotify account and I've created a dataframe that contains all the minutes in the day and the total playtime during that minute for the last 5 years. The dataframe is this (by the way, I wonder if there is any way to work with time without having to select a specific date): ...
[ "moving average\nfor averaging the last 30 records\ndf['playtime_rolling_30'] = df['playtime'].rolling(30).mean()\n\n", "For technical analysis and finance:\nIt is more convenient to use a reliable third-party package like TA-Lib. A simple moving average operation with period of 3 then would be as simple as tali...
[ 0, 0 ]
[]
[]
[ "matplotlib", "pandas", "python" ]
stackoverflow_0074465004_matplotlib_pandas_python.txt
Q: Can't bind value to button on release in Kivy python I wanted to save output of print to value so I can use it later. I have no idea where to go with it #btn.bind(on_release=lambda btn: print(btn.text)) full code: from kivy.uix.dropdown import DropDown from kivy.uix.button import Button from kivy.base import ...
Can't bind value to button on release in Kivy python
I wanted to save output of print to value so I can use it later. I have no idea where to go with it #btn.bind(on_release=lambda btn: print(btn.text)) full code: from kivy.uix.dropdown import DropDown from kivy.uix.button import Button from kivy.base import runTouchApp # create a dropdown with 10 buttons dropdown...
[ "This may get you closer to what you want. I don't know if this is your whole application or if you pared down to minimal function just to post here.\nfrom kivy.uix.dropdown import DropDown\nfrom kivy.uix.button import Button\nfrom kivy.base import runTouchApp\nfrom functools import partial\n\n# create a dropdown ...
[ 0 ]
[]
[]
[ "kivy", "python", "user_interface" ]
stackoverflow_0074457997_kivy_python_user_interface.txt
Q: Python stdin errors, copied code from pycharm wont work in CMD Learning python as a beginner. I wanted to copy my code into CMD but it won't work. Here is code calculation_to_units = 24 name_of_unit = "hours" def days_to_units(number_of_days): if number_of_days > 0: return f"{number_of_days} days are {n...
Python stdin errors, copied code from pycharm wont work in CMD
Learning python as a beginner. I wanted to copy my code into CMD but it won't work. Here is code calculation_to_units = 24 name_of_unit = "hours" def days_to_units(number_of_days): if number_of_days > 0: return f"{number_of_days} days are {number_of_days * calculation_to_units} {name_of_unit}" else: ...
[ "It can be difficult to paste code that calls input() into a python shell. Both the shell and the input() function read stdin. As soon as python reads the line with input(), it calls input() and that consumes the next line on stdin. In your case, that was a python code line intended to set a variable. That line was...
[ 0 ]
[]
[]
[ "python", "stdin" ]
stackoverflow_0074464754_python_stdin.txt
Q: Yahoo stocks API cause errors for some stocks in Python where except function doesn´t work I use the Yahoo API a lot to get stock data from multiple exchanges in the world. The code normally works, but it look likes that there has been an update in the API. In the past when a stock was delisted, the except functio...
Yahoo stocks API cause errors for some stocks in Python where except function doesn´t work
I use the Yahoo API a lot to get stock data from multiple exchanges in the world. The code normally works, but it look likes that there has been an update in the API. In the past when a stock was delisted, the except function in Python got the error and continued. The strange thing is that this error is caused by only ...
[ "It looks like that the API is updated, the except exception is working again.\n" ]
[ 0 ]
[]
[]
[ "finance", "python", "yahoo" ]
stackoverflow_0074251997_finance_python_yahoo.txt
Q: ValueError: while trying to use the crispy forms I am trying to make use of the crispy forms to display the form for inserting the data. I have a model as: class Athlete(models.Model): athlete_name=models.CharField(max_length=50) GENDER_CHOICES=( ('M','Male'), ('F','Female'), ('O','...
ValueError: while trying to use the crispy forms
I am trying to make use of the crispy forms to display the form for inserting the data. I have a model as: class Athlete(models.Model): athlete_name=models.CharField(max_length=50) GENDER_CHOICES=( ('M','Male'), ('F','Female'), ('O','Others') ) gender=models.CharField(choices=GEN...
[ "It should be = not : so:\nclass AthleteForm(ModelForm):\n class Meta:\n model = Athlete\n fields='__all__'\n\nI'd also recommend you to maintain gaps between template tags like it should be {% endblock %} not {%endblock%} same goes for every tag.\n" ]
[ 3 ]
[]
[]
[ "django", "django_forms", "django_models", "django_templates", "python" ]
stackoverflow_0074465456_django_django_forms_django_models_django_templates_python.txt
Q: Loop Python Script with Alternating Variable Value I was wondering if anyone had experience with looping a Python script in Jupyter Notebook that alternates the variable value through each iteration of the loop? The example below will summarize what I'm looking for: variable_file = [file_1, file_2, file_3, etc.......
Loop Python Script with Alternating Variable Value
I was wondering if anyone had experience with looping a Python script in Jupyter Notebook that alternates the variable value through each iteration of the loop? The example below will summarize what I'm looking for: variable_file = [file_1, file_2, file_3, etc....] Around 20 cells which reference variable_file Final ou...
[ "You need to encapsulate the \"around 20 cells\" inside the loop. The loop has to be contained in a single cell.\nIf you really want the content of each cell to be in a separate cell, you can create a function in each cell by encapsulating its content.\nExample:\nIn cell 1:\ndef cell_1(var):\n <do something using ...
[ 0 ]
[]
[]
[ "loops", "python" ]
stackoverflow_0074465415_loops_python.txt
Q: how to define a "middleman" class's init to successfully passthrough args from the grandchild to the parent in python 3 I have a semi-abstract Parent and Middle classes and some Grandchild fully implemented ones that inherit from each other, but while the Parent and Grandchild need some __init__ args, the middle o...
how to define a "middleman" class's init to successfully passthrough args from the grandchild to the parent in python 3
I have a semi-abstract Parent and Middle classes and some Grandchild fully implemented ones that inherit from each other, but while the Parent and Grandchild need some __init__ args, the middle one is just for shared implemented code: class Parent: def __init__(self, some_arg): ... class Middle(Parent, ABC): d...
[ "\nAs you can see, the super().__init__(some_arg) in the Grandchild would call the default __init__ in the Middle, and not send some_arg to the Parent.\n\nThat's not correct. There is no \"default\" __init__ method in Middle.\nsuper().__init__ refers to the __init__ attribute of the next class in self's method reso...
[ 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074465268_python_python_3.x.txt
Q: create mask with filled color using opencv I have an input image where I have drawn the green boundaries which I need to mask. I am able to identify the boundary, but my mask is all black with baground is black. how can I fill the boundary region with different color. May be keep the background white and mask regi...
create mask with filled color using opencv
I have an input image where I have drawn the green boundaries which I need to mask. I am able to identify the boundary, but my mask is all black with baground is black. how can I fill the boundary region with different color. May be keep the background white and mask region as black Input image im = cv2.imread(imagePa...
[ "To fill the contours drawn on the mask you should use the opencv's fillPoly function :\nim = cv2.imread(imagePath)\nplt.imshow(im)\n#color boundaries [B, G, R]\nlower = np.array([0,120,0])\nupper = np.array([200,255,100])\n\n# threshold on green color\nthresh = cv2.inRange(im, lower, upper)\nplt.imshow(thresh)\n# ...
[ 0, 0 ]
[]
[]
[ "opencv", "python" ]
stackoverflow_0074463028_opencv_python.txt
Q: Unclosed tag on line 6: 'with'. Looking for one of: endwith I'm learning how to use Django Templates but im getting this error Unclosed tag on line 6: 'with'. Looking for one of: endwith. this is my html code <!DOCTYPE html> <html> <body> <h1>Favorite rapper:</h1> {% with person="2pac" %} <h1>{{pe...
Unclosed tag on line 6: 'with'. Looking for one of: endwith
I'm learning how to use Django Templates but im getting this error Unclosed tag on line 6: 'with'. Looking for one of: endwith. this is my html code <!DOCTYPE html> <html> <body> <h1>Favorite rapper:</h1> {% with person="2pac" %} <h1>{{person}}</h1> </body> </html> this is the tutorial that I'm doi...
[ "The error makes complete sense you should close the with tag so:\n<!DOCTYPE html>\n<html>\n <body>\n <h1>Favorite rapper:</h1>\n\n {% with person=\"2pac\" %}\n\n <h1>{{person}}</h1>\n {% endwith %}\n </body>\n</html>\n\n" ]
[ 2 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0074465308_django_django_templates_python.txt
Q: Aggregate the grouped values on many specific columns from list I'd like to perfom groupBy() operation with specific agg(). df = df.groupBy("x", "y").agg(F.max("a").alias("a"), F.max("b").alias("b")) But is there any way to aggregation using list of columns? I don't want to hardcode it. A: You can use list comp...
Aggregate the grouped values on many specific columns from list
I'd like to perfom groupBy() operation with specific agg(). df = df.groupBy("x", "y").agg(F.max("a").alias("a"), F.max("b").alias("b")) But is there any way to aggregation using list of columns? I don't want to hardcode it.
[ "You can use list comprehension.\nlist_of_cols = [\"a\", \"b\"]\ndf = df.groupBy(\"x\", \"y\").agg(*[F.max(x).alias(x) for x in list_of_cols])\n\n" ]
[ 0 ]
[]
[]
[ "aggregate", "group_by", "pyspark", "python" ]
stackoverflow_0074465417_aggregate_group_by_pyspark_python.txt
Q: In selenium the send_keys function ignores spaces when used with VNC Why is the send_keys function ignoring spaces in my python script? I used vnc on ubuntu/debian 10. Everything works correctly when I run the script on my computer, but all spaces disappear on vps with vnc. Error is in Google chrome. ` element.sen...
In selenium the send_keys function ignores spaces when used with VNC
Why is the send_keys function ignoring spaces in my python script? I used vnc on ubuntu/debian 10. Everything works correctly when I run the script on my computer, but all spaces disappear on vps with vnc. Error is in Google chrome. ` element.send_keys("1 2 3") result: "123" ` Replacing the spaces with "Keys.SPACE" d...
[ "Try importing the libs and instantiate actions:\n# Needed libs\nfrom selenium import webdriver\nfrom selenium.webdriver.common.action_chains import ActionChains\nimport time\n\n# We create the driver\ndriver = webdriver.Chrome()\naction = ActionChains(driver)\n\nThen make click into your element with something lik...
[ 0, 0 ]
[]
[]
[ "python", "selenium", "vnc" ]
stackoverflow_0074415389_python_selenium_vnc.txt
Q: Why won't my program find/open my .csv file I'm trying to get my program to read my .csv file and when I run it, it says there is no such file. I converted an excel file of 10000 random numbers that range from 1,100 and I'm trying to run those numbers through my code. Am I getting this error from my .csv file or i...
Why won't my program find/open my .csv file
I'm trying to get my program to read my .csv file and when I run it, it says there is no such file. I converted an excel file of 10000 random numbers that range from 1,100 and I'm trying to run those numbers through my code. Am I getting this error from my .csv file or is it an error from my code? import csv import mat...
[ "I'll not fix your problem, but I'll tell you how you can fix all problems of this sort by yourself in the future.\nDownload Process Monitor and add a filter for python.exe, like so:\n\nThen start recording and look for data5.csv and see in which directory it looks for that file.\n\nIf the file is not found, it wil...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074465568_python.txt
Q: python: structuring complete data I have the following dataframe: df = id date_diag date_medication medication_code 1 01-01-2000 03-01-2000 A 2 01-01-2000 02-01-2000 A 3 01-01-2000 04-01-2000 B 4 01-01-2000 05-01-2000 B I would like to create a table with the count of times a given ...
python: structuring complete data
I have the following dataframe: df = id date_diag date_medication medication_code 1 01-01-2000 03-01-2000 A 2 01-01-2000 02-01-2000 A 3 01-01-2000 04-01-2000 B 4 01-01-2000 05-01-2000 B I would like to create a table with the count of times a given medication was given after the date of ...
[ "here is one way to do it\n# create a temp fields, Seq to count the day of medication\n# and days difference b/w medication and diag\n# pivot\n# add prefix to column\n# and do cleanup\n\n\nout=(df.assign(seq=1, \n days=(pd.to_datetime(df['date_medication'], dayfirst=True).sub(pd.to_datetime(df['date_diag'...
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074464898_pandas_python.txt
Q: How to parse multiple dates from a block of text in Python (or another language) I have a string that has several date values in it, and I want to parse them all out. The string is natural language, so the best thing I've found so far is dateutil. Unfortunately, if a string has multiple date values in it, dateuti...
How to parse multiple dates from a block of text in Python (or another language)
I have a string that has several date values in it, and I want to parse them all out. The string is natural language, so the best thing I've found so far is dateutil. Unfortunately, if a string has multiple date values in it, dateutil throws an error: >>> s = "I like peas on 2011-04-23, and I also like them on easter ...
[ "Looking at it, the least hacky way would be to modify dateutil parser to have a fuzzy-multiple option.\nparser._parse takes your string, tokenizes it with _timelex and then compares the tokens with data defined in parserinfo.\nHere, if a token doesn't match anything in parserinfo, the parse will fail unless fuzzy ...
[ 18, 6, 0, 0, 0 ]
[]
[]
[ "parsing", "python", "python_dateutil" ]
stackoverflow_0007028689_parsing_python_python_dateutil.txt
Q: How can I get slopes from multiple columns in a df? I am using this code below to generate multiple scatter charts from a single dataframe. The first column is "Time" (x-axis for all charts) and the other are A,B,C... (y-axis for each chart). import numpy as np import pandas as pd import matplotlib.pyplot as plt ...
How can I get slopes from multiple columns in a df?
I am using this code below to generate multiple scatter charts from a single dataframe. The first column is "Time" (x-axis for all charts) and the other are A,B,C... (y-axis for each chart). import numpy as np import pandas as pd import matplotlib.pyplot as plt df = pd.read_excel("output.xlsx") columns = ['A', 'B', 'C...
[ "Consider:\nfrom scipy import stats\nimport numpy as np\nimport pandas as pd\n\nnp.random.seed(42)\ncolumns = list('ABCDEFGHIJKLMNOPQRST')\ndf = pd.DataFrame(np.random.rand(10, 21), columns = ['Time']+columns)\nlm = []\nfor c in columns:\n res =[c]+ list(stats.linregress(df['Time'], df[c]))\n lm.append(res)\n...
[ 0 ]
[]
[]
[ "linear_regression", "python", "scipy" ]
stackoverflow_0074436779_linear_regression_python_scipy.txt
Q: AttributeError in async kivy program could you please help me fix this program so that it won't show me an Attribute error. I am a newbie to Async programming and I have barely any idea of what is going on. Here is the code: """Example shows the recommended way of how to run Kivy with the Python built in asyncio e...
AttributeError in async kivy program
could you please help me fix this program so that it won't show me an Attribute error. I am a newbie to Async programming and I have barely any idea of what is going on. Here is the code: """Example shows the recommended way of how to run Kivy with the Python built in asyncio event loop as just another async coroutine....
[ "just in case you want a means to an end, and not specifically a correction to asyncio, I took the liberty of writing something the way I know: Threading.\nas I ran the code it did not display the buttons nicely so I changed the top level to a BoxLayout and in the build string named the top level according to the t...
[ 1 ]
[]
[]
[ "asynchronous", "attributeerror", "kivy", "python", "python_asyncio" ]
stackoverflow_0074445708_asynchronous_attributeerror_kivy_python_python_asyncio.txt
Q: lxml insert new node in tree, with parent's contents inside i have this tree : <TEI> <teiHeader/> <text> <body> <div type="chapter"> <p rend="b"><pb n="1"/>lorem ipsum...</p> <p rend="b">lorem pb n="2"/> ipsum2...</p> <p>lorem ipsum3...</p> </div> <div type="chapter"> <p>lorem ipsum4...</p> <p rend="b">lorem ipsum...
lxml insert new node in tree, with parent's contents inside
i have this tree : <TEI> <teiHeader/> <text> <body> <div type="chapter"> <p rend="b"><pb n="1"/>lorem ipsum...</p> <p rend="b">lorem pb n="2"/> ipsum2...</p> <p>lorem ipsum3...</p> </div> <div type="chapter"> <p>lorem ipsum4...</p> <p rend="b">lorem ipsum5...</p> <p rend="b">pb n="3"/> lorem ipsum6...</p> </div> </body...
[ "If I understand you correctly,you are probably looking for something like this:\nfor p in root.xpath('//p[@rend=\"b\"]'):\n #clone the old <p>\n old = etree.fromstring(etree.tostring(p))\n #change its name\n old.tag = \"hi\"\n #create a new element\n new = etree.fromstring('<p/>') \n #appen...
[ 1 ]
[]
[]
[ "lxml", "python", "xml" ]
stackoverflow_0074464493_lxml_python_xml.txt
Q: Using df.apply() to a time column that indicates times at every 2 seconds in pandas I am new to this data science world and trying to understand some basic pandas examples. I have a pandas data frame that I would like to create a new column and add some conditional values as below: It will include yes at every 2 s...
Using df.apply() to a time column that indicates times at every 2 seconds in pandas
I am new to this data science world and trying to understand some basic pandas examples. I have a pandas data frame that I would like to create a new column and add some conditional values as below: It will include yes at every 2 seconds. Otherwise include no. Here is an example: This is my original data frame. id ...
[ "You can use:\nimport numpy as np\n\nN = 2 # time step\n\n# define bins every N seconds\nbins = np.arange(np.floor(df['time'].min()), df['time'].max()+N, 2)\n# get the index of the first row per group\nidx = df.groupby(pd.cut(df['time'], bins))['time'].idxmin()\n\n# assign \"yes\" to the first else \"no\"\ndf['time...
[ 2, 2 ]
[]
[]
[ "data_science", "pandas", "python" ]
stackoverflow_0074465477_data_science_pandas_python.txt
Q: AWS ParamValidationError: Parameter validation failed: I have set up a trigger/lambda to upload into DynamoDB however i get the following error when uploading..not sure what is going wrong. So far i have just created a blank dDB table with the primary key of "PlayerWeekID" as string but nothing else. Is this an is...
AWS ParamValidationError: Parameter validation failed:
I have set up a trigger/lambda to upload into DynamoDB however i get the following error when uploading..not sure what is going wrong. So far i have just created a blank dDB table with the primary key of "PlayerWeekID" as string but nothing else. Is this an issue because DDB isnt reading in the data types? Do I need to...
[ "Can you share the output of your variable jsonDict.\nDynamoDB needs a JSON object as payload: {}\nFrom what I understand it looks like you're trying to save a list [].\nEnsure you are saving an object which contains the keys of your table and you should have no issue.\nWorking example:\nimport boto3\ndynamodb = bo...
[ 0 ]
[]
[]
[ "amazon_dynamodb", "amazon_web_services", "aws_lambda", "python" ]
stackoverflow_0074463628_amazon_dynamodb_amazon_web_services_aws_lambda_python.txt
Q: ImportError: No module named PytQt5 following are my python, qt and sip versions root@thura:~# python -V Python 2.7.3 root@thura:~# qmake --version QMake version 3.0 Using Qt version 5.0.2 in /usr/lib/i386-linux-gnu root@thura:~# sip -V 4.15.3 I tried to import the PyQt5 by following by this from PyQt5.QtWidgets ...
ImportError: No module named PytQt5
following are my python, qt and sip versions root@thura:~# python -V Python 2.7.3 root@thura:~# qmake --version QMake version 3.0 Using Qt version 5.0.2 in /usr/lib/i386-linux-gnu root@thura:~# sip -V 4.15.3 I tried to import the PyQt5 by following by this from PyQt5.QtWidgets import QtGui, QtCore I got the following...
[ "If you are on ubuntu, just install pyqt5 with apt-get command:\n sudo apt-get install python3-pyqt5 # for python3\n\nor\n sudo apt-get install python-pyqt5 # for python2\n\nHowever, on Ubuntu 14.04 the python-pyqt5 package is left out [source] and need to be installed manually [source]\n", "pip instal...
[ 38, 30, 14, 8, 4, 1, 1, 0, 0 ]
[]
[]
[ "pyqt5", "python" ]
stackoverflow_0020672918_pyqt5_python.txt
Q: How to calculate cumulative sum with django ORM? I'm trying to group_by() data based on dates and with every day I want to calculate Count on that day also the total count so far. Sample output I'm getting: [ { "dates": "2022-11-07", "count": 1 }, { "dates": "2022-11-08", ...
How to calculate cumulative sum with django ORM?
I'm trying to group_by() data based on dates and with every day I want to calculate Count on that day also the total count so far. Sample output I'm getting: [ { "dates": "2022-11-07", "count": 1 }, { "dates": "2022-11-08", "count": 3 }, { "dates": "2022-11-09...
[ "I tried to solve your problem like this\nmodels.py\nclass Demo(models.Model):\n count =models.IntegerField()\n dates = models.DateField()\n \n\nserializers.py\nclass DemoSerializer(serializers.ModelSerializer):\n \n class Meta:\n model = Demo\n fields = \"__all__\"\n\nViews.py\nclass D...
[ 0 ]
[]
[]
[ "django", "django_models", "django_orm", "django_rest_framework", "python" ]
stackoverflow_0074430261_django_django_models_django_orm_django_rest_framework_python.txt
Q: 123 to 321 problem giving errors when iterating I made this program trying to solve a problem which is fliping a number. For example, when the number 123 is the number inputed the number 321 should be the output. #function to swap number positions on the array def swapPositions(list, pos1, pos2): i = list[po...
123 to 321 problem giving errors when iterating
I made this program trying to solve a problem which is fliping a number. For example, when the number 123 is the number inputed the number 321 should be the output. #function to swap number positions on the array def swapPositions(list, pos1, pos2): i = list[pos1] list[pos1] = list[pos2] list[pos2] = i ...
[ "this can be done without converting the number to a string, for example\n# note: this example works for positive numbers only\ndef reverseNum(x):\n y = 0\n while x > 0:\n y = y*10 + x%10\n x //= 10\n return y\n\n>>> reverseNum(3124)\n4213\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074465498_python.txt
Q: pip installing local package for testing in sibling folder I have source code I want to test in a test folder that is a sibling to the src code folder. see structure below ├── src │   ├── modules │   │   ├── module1 │   │   │   ├── __init__.py │   │   │   └── somecode.py │   │   └── module2 │   └── setup.py └── te...
pip installing local package for testing in sibling folder
I have source code I want to test in a test folder that is a sibling to the src code folder. see structure below ├── src │   ├── modules │   │   ├── module1 │   │   │   ├── __init__.py │   │   │   └── somecode.py │   │   └── module2 │   └── setup.py └── tests └── test1.py my setup.py file looks like this setuptool...
[ "So the problem was taht i was doing pip install -e /path/to/package. This was creating some problems with importing for some reason, the links to the egg-info files seemed off. It you want to use a local package in a sibling folder for get about the -e flag, just do pip install /path/to/package and then everything...
[ 0 ]
[]
[]
[ "pip", "python", "python_unittest", "setup.py", "setuptools" ]
stackoverflow_0074465323_pip_python_python_unittest_setup.py_setuptools.txt
Q: How to read a csv file in Spark with multiline text in a cell I have the following file: The 'complaint' column has cases where newlines were created. When I try to create a Spark df with multiline text in the 'complaint' field, it gets shifted and I end up with: Is there a way to fix this? A: Please use quot...
How to read a csv file in Spark with multiline text in a cell
I have the following file: The 'complaint' column has cases where newlines were created. When I try to create a Spark df with multiline text in the 'complaint' field, it gets shifted and I end up with: Is there a way to fix this?
[ "Please use quotes and the multi-line option on the data file.\nI will work you thru your test case that does not work.\n\nData file without quotes.\n\nData file with quotes on text. Text in both examples is multi-line for the complaint column (fields).\n\nBoth files exist in directory in mounted ADLS Generation 2...
[ 0 ]
[]
[]
[ "apache_spark", "python" ]
stackoverflow_0074465262_apache_spark_python.txt
Q: Comparing times in Python I've no idea what I'm doing wrong in the following line of code and it's driving me nuts! As you'll probably know from the code, I only want the if block to run if it's before 5.15pm. if time(datetime.now().hour,datetime.now().minute) < time(17, 15): I've imported date and datetime so th...
Comparing times in Python
I've no idea what I'm doing wrong in the following line of code and it's driving me nuts! As you'll probably know from the code, I only want the if block to run if it's before 5.15pm. if time(datetime.now().hour,datetime.now().minute) < time(17, 15): I've imported date and datetime so that's not the issue (it's TypeEr...
[ "You probably want to from datetime import time:\nfrom datetime import datetime, time\n\nnow = datetime.now()\n\nif time(now.hour, now.minute) < time(20, 15):\n print(\"Hello\")\n\nPrints (now):\nHello\n\n", "a bit shorter:\nfrom datetime import datetime, time\n\ndatetime.now().time() < time(20,10) # False\n\...
[ 2, 1 ]
[]
[]
[ "datetime", "if_statement", "python", "python_3.x", "python_datetime" ]
stackoverflow_0074465296_datetime_if_statement_python_python_3.x_python_datetime.txt
Q: How to save an excel using pywin32? I am trying to save an excel file generated by another application that is open. i.e the excel application is in the foreground. This file has some data and it needs to be saved i.e written into the disk. In other words, I need to do an operation like File->SaveAs. Steps to repr...
How to save an excel using pywin32?
I am trying to save an excel file generated by another application that is open. i.e the excel application is in the foreground. This file has some data and it needs to be saved i.e written into the disk. In other words, I need to do an operation like File->SaveAs. Steps to reproduce: Open an Excel Application. This w...
[ "There could be many sources for your problem so I would apreciate if you shared further code. The second error can for example occur when you are running multiple instances of the line excel = win32.gencache.EnsureDispatch('Excel.Application') for example in a for loop .\nAlso make sure to have a version of excel ...
[ 0, 0, 0 ]
[]
[]
[ "excel", "python", "pywin32", "win32com", "winapi" ]
stackoverflow_0074350835_excel_python_pywin32_win32com_winapi.txt
Q: How to click relative to a window/application in python and how to handle multiple scripts that click? Is there any way to click relative to an open window? For example, clicking a set amount of pixels to the right/up/left/down of an open tab of google chrome? I know how to click using absolute coordinates, or cli...
How to click relative to a window/application in python and how to handle multiple scripts that click?
Is there any way to click relative to an open window? For example, clicking a set amount of pixels to the right/up/left/down of an open tab of google chrome? I know how to click using absolute coordinates, or click on something that matches an image file, but I haven't been able to find anything regarding relative clic...
[ "You can use the library pyautogui.\nI put an example here:\nimport pyautogui as pya\nstart = pya.locateCenterOnScreen('start.png')#If the file is not a png file it will not work\nprint(start)\npya.moveTo(start)#Moves the mouse to the coordinates of the image\n#even you can make click with\npya.click(button='left',...
[ 0, 0 ]
[]
[]
[ "automation", "python" ]
stackoverflow_0061418522_automation_python.txt
Q: filtering out strings in a list Python I'm totally new to Python and I'm sure I'm missing something simple, I want to remove all Strings. def filter_list(l): for f in l: if isinstance(f, str): l.remove(f) return l print(filter_list([1,2,'a','b'])) The output I get is: [1,2,'b'] A: Often when we ne...
filtering out strings in a list Python
I'm totally new to Python and I'm sure I'm missing something simple, I want to remove all Strings. def filter_list(l): for f in l: if isinstance(f, str): l.remove(f) return l print(filter_list([1,2,'a','b'])) The output I get is: [1,2,'b']
[ "Often when we need to filter a sublist from a list given a condition, you'll see this sort of syntax (i.e. list comprehension) quite commonly, which serves to do the exact same thing. It's up to you which style you prefer:\na = [1,2,'a','b']\nb = [x for x in a if not isinstance(x, str)]\nprint(b) # [1, 2]\n\n", ...
[ 2, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074465794_python.txt
Q: Pandas Merge issue I'm trying to merge one column values from df2 to df1. df1.merge(df2, how='outer') seems to be what I needed but result is not what I wanted because of duplicate. Using 'on' introduces _x and _y which I don't want either. In below Example: sub=site1 in both df1 and df2 is same, then 'fred' from ...
Pandas Merge issue
I'm trying to merge one column values from df2 to df1. df1.merge(df2, how='outer') seems to be what I needed but result is not what I wanted because of duplicate. Using 'on' introduces _x and _y which I don't want either. In below Example: sub=site1 in both df1 and df2 is same, then 'fred' from df2 replaces 'own' of df...
[ "A potential somewhat simple solution using pd.concat and loc to filter df1 to just contain records not present in df2 and then concat them together.\n# used to make use loc on index as it is a bit simpler.\ndf1 = df1.set_index('sub')\ndf2 = df2.set_index('sub')\n\nThen pd.concat them together.\ndf3 = pd.concat([df...
[ 0, 0, 0 ]
[]
[]
[ "dataframe", "merge", "pandas", "python" ]
stackoverflow_0074464231_dataframe_merge_pandas_python.txt
Q: How to copy files? How do I copy a file in Python? A: shutil has many methods you can use. One of which is: import shutil shutil.copyfile(src, dst) # 2nd option shutil.copy(src, dst) # dst can be a folder; use shutil.copy2() to preserve timestamp Copy the contents of the file named src to a file named dst. B...
How to copy files?
How do I copy a file in Python?
[ "shutil has many methods you can use. One of which is:\nimport shutil\n\nshutil.copyfile(src, dst)\n\n# 2nd option\nshutil.copy(src, dst) # dst can be a folder; use shutil.copy2() to preserve timestamp\n\n\nCopy the contents of the file named src to a file named dst. Both src and dst need to be the entire filename...
[ 4312, 1954, 914, 235, 178, 108, 81, 49, 37, 33, 23, 20, 20, 13, 13, 13, 9, 8, 5, 1 ]
[ "Here is answer utilizing \" shutil.copyfileobj\" and is highly efficient. I used it in a tool I created some time ago. I didn't wrote this originally but tweaked it a little bit.\ndef copyFile(src, dst, buffer_size=10485760, perserveFileDate=True):\n '''\n @param src: Source File\n @param dst: Desti...
[ -2, -2, -3, -6 ]
[ "copy", "file", "file_copying", "filesystems", "python" ]
stackoverflow_0000123198_copy_file_file_copying_filesystems_python.txt
Q: Issues with facial recognition with sklearn svm I am working on a school project to make a facial recognition program using Python. I am using the face_recognition and scikit-learn libraries. However, I am facing some issues. Here is my code: """ Structure: <Data>/ <person_1>/ <...
Issues with facial recognition with sklearn svm
I am working on a school project to make a facial recognition program using Python. I am using the face_recognition and scikit-learn libraries. However, I am facing some issues. Here is my code: """ Structure: <Data>/ <person_1>/ <person_1_face-1>.jpg <person_1_face-2...
[ "My oppinion is that both your issues are going from here:\nface_names = []\nfor encoding in camera_encodings:\n name = clf.predict([encoding])\n print(name)\n face_names.extend(name)\n\nThere is no tolerance treshold being set, so either it founds the proper image as the most similar first .. or then any ...
[ 0 ]
[]
[]
[ "face_recognition", "python", "scikit_learn", "svm" ]
stackoverflow_0074461674_face_recognition_python_scikit_learn_svm.txt
Q: How can I deal with this "Error: list index out of range"? Im beginner and I have a script that looking for videos on YouTube by search query with youtube-search-python package How can I except this error Error: list index out of range? Code: async def search(self, search: str): results = await asyncio.ga...
How can I deal with this "Error: list index out of range"?
Im beginner and I have a script that looking for videos on YouTube by search query with youtube-search-python package How can I except this error Error: list index out of range? Code: async def search(self, search: str): results = await asyncio.gather(*[self.to_search(search, page=i) for i in range(10)]) ...
[ "If the list is empty, you can check that by checking the length of the list of results through something like this:\nif videos_search['result'].length == 0:\n print(\"No results found\")\nelse:\n # run the code\n\n" ]
[ 1 ]
[]
[]
[ "python", "youtube" ]
stackoverflow_0074463305_python_youtube.txt
Q: Need help performing multiple api requests at once in python I am using a roblox api to determine whether a list of users owns a limited item or does not own it. Here is my code: import requests import json user_ids = ["115687329", "1427501340", "508866135"] with open("myfile.txt", "w") as file: for user_id ...
Need help performing multiple api requests at once in python
I am using a roblox api to determine whether a list of users owns a limited item or does not own it. Here is my code: import requests import json user_ids = ["115687329", "1427501340", "508866135"] with open("myfile.txt", "w") as file: for user_id in user_ids: response = requests.get( f"https:...
[ "The problem is that the last 3 lines of code need to be indented so that they're inside the for loop.\nAlso worth mentioning that this kind of processing is well-suited to multi-threading for improved performance.\nimport requests\nfrom concurrent.futures import ThreadPoolExecutor\n\nuser_ids = [\"115687329\", \"1...
[ 0 ]
[]
[]
[ "api", "python" ]
stackoverflow_0074465689_api_python.txt
Q: Conditions and while loop not working properly py(tkinter) im making a Guess the number game but i have a problem:The user must guess a certain number, and if it exceeds that, the game ends and the user's status is determined,So I created a variable named sam and did this sam = 0 And then I made a loop with while...
Conditions and while loop not working properly py(tkinter)
im making a Guess the number game but i have a problem:The user must guess a certain number, and if it exceeds that, the game ends and the user's status is determined,So I created a variable named sam and did this sam = 0 And then I made a loop with while and said: while sam < 10: And then, every wrong guess will be ...
[ "Writing GUI programs requires a different mindset than writing non-GUI programs. A loop like the one you created is not appropriate for a GUI. The way GUIs work is that you define functions to be called in response to events, and then the event manager (mainloop) is a loop tht waits for events and then dispatches ...
[ 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074465586_python_tkinter.txt
Q: How to get users with 3 or more consecutive weeks in order using pandas? I have a user table like this, USERID Week_Number Year 0 fb 5.0 2021 1 twitter 1.0 2021 2 twitter 2.0 2021 3 twitter 3.0 2021 4 twitter 1.0 2022 5 twitter 2.0 2022 6...
How to get users with 3 or more consecutive weeks in order using pandas?
I have a user table like this, USERID Week_Number Year 0 fb 5.0 2021 1 twitter 1.0 2021 2 twitter 2.0 2021 3 twitter 3.0 2021 4 twitter 1.0 2022 5 twitter 2.0 2022 6 twitter 3.0 2022 7 twitter 15.0 2022 8 twitter ...
[ "Since you are not interested in the details of when the run of at least three weeks occurred (start or end), but only the tuples (user, year) where the user had at least three consecutive weeks of usage, then it is quite simple:\ndef min_consecutive(w, minimum_run=3):\n dy = w.diff() != 1\n runlen = dy.group...
[ 2, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074464008_pandas_python.txt
Q: Error in plotting quiver ufunc 'isfinite' I have the following lists, and I want to plot using the plt.quiver but I got the following error. I do not know what to modify the list so the plot is plotting. import matplotlib.pyplot as plt x=[0.5, 0.09113826200606436, 0.09090926587458355, 0.09090909053329622, 0.09090...
Error in plotting quiver ufunc 'isfinite'
I have the following lists, and I want to plot using the plt.quiver but I got the following error. I do not know what to modify the list so the plot is plotting. import matplotlib.pyplot as plt x=[0.5, 0.09113826200606436, 0.09090926587458355, 0.09090909053329622, 0.09090909090689524, 0.09090909090901886] y=[-0.5, -0....
[ "If you plot each arrow individually, Matplotlib does her job, but all the arrows look the same, even if they are not of the same size (in your data, they are apart by 13 orders of magnitude).\nMy guess is that Matplotib encounters an error when she tries to rasterize, in the same scale, arrow objects that are so d...
[ 0 ]
[]
[]
[ "matplotlib", "plot", "python" ]
stackoverflow_0074465581_matplotlib_plot_python.txt
Q: Pandas "usecols" doesn't seems work perfectly I am reading below excel with below python code but not getting any idea why the first column header has ".1" even though set to ignore the first column. Any idea please? many thanks in advance. python script import pandas as pd import os os.system('cls') df = pd.read...
Pandas "usecols" doesn't seems work perfectly
I am reading below excel with below python code but not getting any idea why the first column header has ".1" even though set to ignore the first column. Any idea please? many thanks in advance. python script import pandas as pd import os os.system('cls') df = pd.read_excel('test_1\Book1.xlsx','sheet1', header=0, ski...
[ "In the file you have two columns named \"PIA IM Equity\" when reading pandas will rename the second identical column by adding .1 in the name. If you would have a third column with the same name it would have added .2 in it.\n" ]
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074465996_pandas_python.txt