content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: How did datetime decide '22' in %y is 2022 and not 1922? Example code a = '27-10-80' b = '27-10-22' c = '27-10-50' x = datetime.strptime(a, '%d-%m-%y') print(x) y = datetime.strptime(b, '%d-%m-%y') print(y) z = datetime.strptime(c, '%d-%m-%y') print(z) Output: 1980-10-27 00:00:00 2022-10-27 00:00:00 2050-10-27 ...
How did datetime decide '22' in %y is 2022 and not 1922?
Example code a = '27-10-80' b = '27-10-22' c = '27-10-50' x = datetime.strptime(a, '%d-%m-%y') print(x) y = datetime.strptime(b, '%d-%m-%y') print(y) z = datetime.strptime(c, '%d-%m-%y') print(z) Output: 1980-10-27 00:00:00 2022-10-27 00:00:00 2050-10-27 00:00:00 How did datetime decide the year generated from stri...
[ "The Python documentation indicates that strftime/strptime follows the semantics of C\n\nMost of the functions defined in this module call platform C library functions with the same name.\n\nas well as documents the behaviour of %y:\n\nFunction strptime() can parse 2-digit years when given %y format code. When 2-di...
[ 2, 1 ]
[ "From the documentation of time\n\nFunction strptime() can parse 2-digit years when given %y format code. When 2-digit years are parsed, they are converted according to the POSIX and ISO C standards: values 69–99 are mapped to 1969–1999, and values 0–68 are mapped to 2000–2068.\n\n" ]
[ -1 ]
[ "datetime", "python" ]
stackoverflow_0074218240_datetime_python.txt
Q: What will happen to expired PubSub message in Dataflow streaming pipeline? Dataflow streaming job reads messages from PubSub and processes it somehow. But sometimes, for example because of very long processing time, this message is not acked on time and PubSub redelivers this message. We can see it in dataflow log...
What will happen to expired PubSub message in Dataflow streaming pipeline?
Dataflow streaming job reads messages from PubSub and processes it somehow. But sometimes, for example because of very long processing time, this message is not acked on time and PubSub redelivers this message. We can see it in dataflow logs where two in fact the same messages (the same message_id) are processed at the...
[ "Dataflow messages will be acked after a message is successfully processed by first fused stage.\nIn cases where a message is seen twice, Dataflow will mark the latter message as Duplicate and filter it out provided you are using the built-in Apache Beam PubsubIO. This filtering is achieved based on the unique mess...
[ 1, 1 ]
[]
[]
[ "apache_beam_io", "google_cloud_dataflow", "google_cloud_pubsub", "python" ]
stackoverflow_0074217082_apache_beam_io_google_cloud_dataflow_google_cloud_pubsub_python.txt
Q: django set initial value in form class UserEditFormView(FormView): template_name = "edit.html" form_class = UserEditForm def get_initial(self): return {'nickname': self.request.user.nickname} class UserEditForm(forms.Form): nickname = forms.CharField(required=False, max_length=120) <...
django set initial value in form
class UserEditFormView(FormView): template_name = "edit.html" form_class = UserEditForm def get_initial(self): return {'nickname': self.request.user.nickname} class UserEditForm(forms.Form): nickname = forms.CharField(required=False, max_length=120) <!DOCTYPE html> <html> <head> ...
[ "You need to call super().get_initial first\nclass UserEditFormView(FormView):\n template_name = \"edit.html\"\n form_class = UserEditForm\n \n def get_initial(self):\n initial = super().get_initial()\n\n initial['nickname'] = self.request.user.nickname\n\n return initial\n\n" ]
[ 0 ]
[]
[]
[ "django", "django_forms", "django_views", "python" ]
stackoverflow_0074218299_django_django_forms_django_views_python.txt
Q: Finding letters in a string I'm trying to write a code that finds the letters in a string containing special characters, numbers and letters. The following code returns nothing: a ="&*&)*&GOKJHOHGOUIGougyY^&*^x".lower() print(a) final = a.split() for y in final: if (y.isalpha == True): print(y) Output...
Finding letters in a string
I'm trying to write a code that finds the letters in a string containing special characters, numbers and letters. The following code returns nothing: a ="&*&)*&GOKJHOHGOUIGougyY^&*^x".lower() print(a) final = a.split() for y in final: if (y.isalpha == True): print(y) Output: &&)&gokjhohgouigougyy^&*^x => N...
[ "You need to call y.isalpha as y.isalpha() this is because isalpha is a function or method.\n>>> y='y'\n>>> y.isalpha\n<built-in method isalpha of str object at 0x00FA3A40>\n>>> y.isalpha()\nTrue\n\nNote that your split will give you words not letters - which may not be what you are expecting:\n>>> s = \"Yes! These...
[ 4, 2, 1, 1, 1, 1, 0 ]
[]
[]
[ "findall", "python", "python_3.x" ]
stackoverflow_0030284855_findall_python_python_3.x.txt
Q: How to iterate and edit values of a column in pandas dataframe I got the following data frame: rowid url text domain_id domain_id_label ... punsafe pwatermark aesthetic hash __index_l...
How to iterate and edit values of a column in pandas dataframe
I got the following data frame: rowid url text domain_id domain_id_label ... punsafe pwatermark aesthetic hash __index_level_0__ 0 1 https://cdn.idahopotato.com/cache/4075b86c99bc....
[ "You can write a custom function for this and call it in df.apply:\nFollowing is a working example with dummy data:\ndef download_url(row):\n img_data = requests.get(row[\"url\"]).content\n with open(f\"/content/sample_data/tmp/image_{row.name}.jpg\", \"wb\") as handler:\n handler.write(img_data)\n return f\"...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074217716_dataframe_pandas_python.txt
Q: Handling exceptions inside context managers I have some code where I try to reach a resource but sometimes it is unavailable, and results in an exception. I tried to implement a retry engine using context managers, but I can't handle the exception raised by the caller inside the __enter__ context for my context ma...
Handling exceptions inside context managers
I have some code where I try to reach a resource but sometimes it is unavailable, and results in an exception. I tried to implement a retry engine using context managers, but I can't handle the exception raised by the caller inside the __enter__ context for my context manager. class retry(object): def __init__(self...
[ "Quoting __exit__,\n\nIf an exception is supplied, and the method wishes to suppress the exception (i.e., prevent it from being propagated), it should return a true value. Otherwise, the exception will be processed normally upon exit from this method.\n\nBy default, if you don't return a value explicitly from a fun...
[ 43, 15, 8, 2, 0 ]
[]
[]
[ "contextmanager", "exception", "python" ]
stackoverflow_0035483359_contextmanager_exception_python.txt
Q: How to Add keys to python dicitonary dynamically? I am trying to creating python dictionary keys dynamically in order to serve the data into csv file but not getting anywhere so far. Here is my code: import requests from bs4 import BeautifulSoup import csv class ZiwiScraper: results = [] headers = {...
How to Add keys to python dicitonary dynamically?
I am trying to creating python dictionary keys dynamically in order to serve the data into csv file but not getting anywhere so far. Here is my code: import requests from bs4 import BeautifulSoup import csv class ZiwiScraper: results = [] headers = { 'authority': '99petshops.com.au', 'accept': 't...
[ "You were creating csv header based only upon the first result, which didn't contained whole set of unique keys.\nChange to_csv function to this to resolve your problem:\ndef to_csv(self):\n key_list = list()\n for key_list_for_one_element in [list(x.keys()) for x in self.results]:\n key_list.extend(...
[ 0, 0 ]
[]
[]
[ "beautifulsoup", "csv", "python" ]
stackoverflow_0074209914_beautifulsoup_csv_python.txt
Q: Splitting setup.py into multiple modules I have inherited a complex setup.py which uses various python modules inside a separate folder called buildchain. The entire repository is basically structured like - setup.py - buildchain - __init__.py - extension_generator.py - src - my_package - __init__.p...
Splitting setup.py into multiple modules
I have inherited a complex setup.py which uses various python modules inside a separate folder called buildchain. The entire repository is basically structured like - setup.py - buildchain - __init__.py - extension_generator.py - src - my_package - __init__.py - my_module.py with setup.py stating ...
[ "@sinoroc and @9769953 pointed out that I do not want buildchain/ inside the wheel, but I do want it inside the sdist. Therefore it should be included in the manifest (which informs sdist), but not constitute package data.\nHow to achieve that is a question answered eg. in Include files in sdist but not wheel.\n[I...
[ 0 ]
[]
[]
[ "python", "setup.py" ]
stackoverflow_0074180432_python_setup.py.txt
Q: Plotting a single column data frame in real-time I have a single column data frame constantly collecting data from an external device running in a while loop in real time. In order to plot the data frame I have used tkinter but due to its resource intensive issues I abandoned it, I have tried using matplotlib, but...
Plotting a single column data frame in real-time
I have a single column data frame constantly collecting data from an external device running in a while loop in real time. In order to plot the data frame I have used tkinter but due to its resource intensive issues I abandoned it, I have tried using matplotlib, but couldn't get it to update accordingly. Any other sugg...
[ "Okay so I found some help online and managed to neatly and efficiently display the data incoming from my sensors. So here are my steps to achieve the result, Open the python command window, and type python YourDataretrievingScript.py this will run your script of retrieving data from your sensors, just make sure yo...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074205351_python.txt
Q: Regex: Use \b (word boundary) separator but ignore some characters Given this example: s = "Hi, domain: (foo.bar.com) bye" I'd like to create a regex that matches both word and non-word strings, separately, i.e: re.findall(regex, s) # Returns: ["Hi", ", ", "domain", ": (", "foo.bar.com", ") ", "bye"] My approach...
Regex: Use \b (word boundary) separator but ignore some characters
Given this example: s = "Hi, domain: (foo.bar.com) bye" I'd like to create a regex that matches both word and non-word strings, separately, i.e: re.findall(regex, s) # Returns: ["Hi", ", ", "domain", ": (", "foo.bar.com", ") ", "bye"] My approach was to use the word boundary separator \b to catch any string that is b...
[ "You may use this regex in findall:\n\\w+(?:\\.\\w+)*|\\W+\n\nWhich finds a word followed by 0 or more repeats of dot separated words or 1+ of non-word characters.\nCode:\nimport re\n\ns = \"Hi, domain: (foo.bar.com) bye\"\nprint (re.findall(r'\\w+(?:\\.\\w+)*|\\W+', s))\n\nOutput:\n['Hi', ', ', 'domain', ': (', 'f...
[ 2, 1, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074218181_python_regex.txt
Q: Print 4 letter combinations of a string without using lists or itertools we are to write a function that takes a single parameter string, and then outputs each 4 letter permutation from the possible combinations of the string. so for example even if it is a 5 letter word you have to return all 4 letter combination...
Print 4 letter combinations of a string without using lists or itertools
we are to write a function that takes a single parameter string, and then outputs each 4 letter permutation from the possible combinations of the string. so for example even if it is a 5 letter word you have to return all 4 letter combinations of the string. it can also only be solved iteratively so no recursion. curre...
[ "You can just use a + operator to join two strings together:\na = 'str1'\nb = 'str2'\nc = a + b\nprint(c)\n\noutput:\n'st1str2'\n\nSo you can use this to join together i, x, z and y into one string, and print it as 1 'word'.\n", "The question is not very clear so I suppose that for word='abcd' you have to print t...
[ 1, 0 ]
[]
[]
[ "iteration", "list", "python" ]
stackoverflow_0074218346_iteration_list_python.txt
Q: Pyspark efficiently create patterns within each window I want to create a base dataframe from the existing one, which does not contain all I want, for example, I have the dataframe collecting the number of candies each people (tracked by "id") bought each year-month (but in this case each person didn't buy candies...
Pyspark efficiently create patterns within each window
I want to create a base dataframe from the existing one, which does not contain all I want, for example, I have the dataframe collecting the number of candies each people (tracked by "id") bought each year-month (but in this case each person didn't buy candies every month) |id|year_month|num_of_candies_bought 1 2022...
[ "I'd simply add a 0 (zero) line for each id and each id and year_month.\nLet's assume df is your dataframe.\nfrom pyspark.sql import functions as F\n\n# generate a list of all year_month you need\nyear_month = [\"2022-01\", \"2022-02\", \"2022-03\", \"2022-04\", \"2022-05\"]\n\ndf_id = (\n df.select(\"id\")\n ...
[ 1 ]
[]
[]
[ "data_science", "dataframe", "pyspark", "python", "tabula" ]
stackoverflow_0074193648_data_science_dataframe_pyspark_python_tabula.txt
Q: Avoid overflow in random matrix multiplication in python I have to multiply many (about 700) matrices with a random element (in the following, I'm using a box distribution) in python: #define parameters ΞΌ=2. Οƒ=2. L=700 #define random matrix T=[None]*L product=np.array([[1,0],[0,1]]) for i in range(L): m=np.r...
Avoid overflow in random matrix multiplication in python
I have to multiply many (about 700) matrices with a random element (in the following, I'm using a box distribution) in python: #define parameters ΞΌ=2. Οƒ=2. L=700 #define random matrix T=[None]*L product=np.array([[1,0],[0,1]]) for i in range(L): m=np.random.uniform(ΞΌ-Οƒ*3**(1/2), ΞΌ+Οƒ*3**(1/2)) #box distribution ...
[ "I will take m instead of m/2 to simplify the formulae, but it does not change anything.\nThe product of first two mtrices is\n[-1 -m1 ] * [-1 -m2 ] = [1-m1 m2 ]\n[ 1 0 ] [ 1 0 ] [-1 -m2 ]\n\nif you take the det, that is (-m2+m1*m2) + m2\nYou can see a form of cancellation of bigger terms (m2), resulti...
[ 1, 0 ]
[]
[]
[ "floating_point", "matrix_multiplication", "numpy", "overflow", "python" ]
stackoverflow_0074179556_floating_point_matrix_multiplication_numpy_overflow_python.txt
Q: Tensorflow variable length timeseries training error with batch size I'm trying to build a network with one input layer with 7 neurons, at least one LSTM layer, and an output layer of dimension 1. I've split my training data into smaller chunks so that I could train each topology candidate faster, but my validatio...
Tensorflow variable length timeseries training error with batch size
I'm trying to build a network with one input layer with 7 neurons, at least one LSTM layer, and an output layer of dimension 1. I've split my training data into smaller chunks so that I could train each topology candidate faster, but my validation data is only one sample (but a long time-series nonetheless). But it see...
[ "You have passed the input shape as (1, 7), but when you check the shape of x_train[0], it is (6, 7). The data is batch_major and not time_major, hence kindly set time_major=False and also change the batch size of x_val and y_val. Please find the working code below\nimport tensorflow as tf\nimport numpy as np\n\nrn...
[ 0 ]
[]
[]
[ "keras", "lstm", "python", "tensorflow" ]
stackoverflow_0069411284_keras_lstm_python_tensorflow.txt
Q: Python: How to Apply Style on Pandas Dataframe by Comparing Two Values on the Same Column but on the Different Rows? Suppose that we have this dataframe: Value 1 Value 2 Value 3 6 5 6 6 5 10 How to apply color if values on the same column is equals but skip the first column? In my case, column Value 2 must be ...
Python: How to Apply Style on Pandas Dataframe by Comparing Two Values on the Same Column but on the Different Rows?
Suppose that we have this dataframe: Value 1 Value 2 Value 3 6 5 6 6 5 10 How to apply color if values on the same column is equals but skip the first column? In my case, column Value 2 must be colored I have used Pandas df.apply, but the example is compare column on the same row
[ "Hi, you can try like this one:\ndf = df.style.apply(lambda x: ['background-color: lightgreen']*len(df) if (x.iloc[0] == x.iloc[1] and x.name != 'Value1') else ['background-color: white']*len(df), axis = 0)\n\n", "You can use:\ndef color(s):\n return s.duplicated(keep=False).map({True: 'background-color: yello...
[ 1, 0, 0 ]
[]
[]
[ "colors", "dataframe", "pandas", "python", "python_applymap" ]
stackoverflow_0074218512_colors_dataframe_pandas_python_python_applymap.txt
Q: extract words where vowel sign is used consecutively I am trying to extract words where vowel sign is used consecutively twice (or more than 2 times) next to each other. texts = ['ane', 'mood', 'xao', 'pqr', 'aa'] signs = ['a', 'e', 'i', 'o', 'u'] for i in texts: for x in i: if x in signs: ...
extract words where vowel sign is used consecutively
I am trying to extract words where vowel sign is used consecutively twice (or more than 2 times) next to each other. texts = ['ane', 'mood', 'xao', 'pqr', 'aa'] signs = ['a', 'e', 'i', 'o', 'u'] for i in texts: for x in i: if x in signs: print ("double vowel sign exists in", i) This will print...
[ "You can do this,\ntexts = ['ane', 'mood', 'xao', 'pqr', 'aa']\nsigns = ['a', 'e', 'i', 'o', 'u']\n\nfor i in texts:\n for x in zip(i, i[1:]):\n if all(check in signs for check in x):\n print(f\"double vowel sign exists in {i}\")\n\nOutput:\ndouble vowel sign exists in mood\ndouble vowel sign e...
[ 5, 1, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074216594_python.txt
Q: Difference between render_template and redirect? return redirect(url_for('index', var=var)) return render_template('index.html', var=var) Are these two lines essentially the same thing? What is the difference between the two functions? A: redirect returns a 302 header to the browser, with its Location header as...
Difference between render_template and redirect?
return redirect(url_for('index', var=var)) return render_template('index.html', var=var) Are these two lines essentially the same thing? What is the difference between the two functions?
[ "redirect returns a 302 header to the browser, with its Location header as the URL for the index function. render_template returns a 200, with the index.html template returned as the content at that URL.\n", "On a much simpler note, consider this - If none of your endpoints rendered templates, and all your redire...
[ 37, 13, 3, 3, 1 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0021668481_flask_python.txt
Q: Python if error in a loop continue loop from next iteration I have such code: for i in range(0,5): try: print(f"opened some_file_{i}") except Exception as e: print(f"error opening some_file_{i}") return print(f"i = {i}") After exception, I need contuinue the loop from the next iteration, b...
Python if error in a loop continue loop from next iteration
I have such code: for i in range(0,5): try: print(f"opened some_file_{i}") except Exception as e: print(f"error opening some_file_{i}") return print(f"i = {i}") After exception, I need contuinue the loop from the next iteration, but not continue code (print(f"i = {i}") How can I do it? I tried ...
[ "Sorry, continue works\nfor i in range(0,5):\n try:\n print(f\"opened some_file_{i}\")\n except Exception as e:\n print(f\"error opening some_file_{i}\")\n continue\n print(f\"i = {i}\")\n\nSo if I had an exception, continue will skip this loop iteration\n", "If you have handled the exception pr...
[ 0, 0 ]
[]
[]
[ "loops", "python" ]
stackoverflow_0074217910_loops_python.txt
Q: ParserError: Unknown string format: EM:AIL I have a df with a column - queue time. It has time values. But the type of these values are str. It might also contain incorrect values like 'abc' or 'email' in it as well. The time values are of the form '10:23', '22:22', '1:1', etc. I want to convert these values to '1...
ParserError: Unknown string format: EM:AIL
I have a df with a column - queue time. It has time values. But the type of these values are str. It might also contain incorrect values like 'abc' or 'email' in it as well. The time values are of the form '10:23', '22:22', '1:1', etc. I want to convert these values to '10:23:00', '22:22:00', '01:01:00' and so on. If i...
[ "IIUC, just use:\ndf['queue time'] = pd.to_datetime(df['queue time'], format='%H:%M', errors='coerce').dt.time\n\noutput:\n queue time\n0 10:23:00\n1 22:22:00\n2 01:01:00\n3 NaT\n\nUsed input:\ndf = pd.DataFrame({'queue time': ['10:23', '22:22', '1:1', 'EM:AIL']})\n\n", "Just addition @Mozway soluti...
[ 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074218607_pandas_python.txt
Q: Will Deploying a code along with excel file work? I am trying to create a small application in flask. So I will be web scraping the data from a website and updating it in a excel file which is in the path of my code files. Later I read the excel and manipulate data using pandas. So basically I am using this excel ...
Will Deploying a code along with excel file work?
I am trying to create a small application in flask. So I will be web scraping the data from a website and updating it in a excel file which is in the path of my code files. Later I read the excel and manipulate data using pandas. So basically I am using this excel file as a mini database My question is when I deploy th...
[ "Depends on how heavily the file will be used and if it may cause concurrency issues. Consider that if you have multiple requests coming into the Flask application that triggers multiple concurrent reads/writes to the excel / csv file, you may end up overwriting over content unintentionally.\nIf the information tha...
[ 0 ]
[]
[]
[ "deployment", "python", "web_applications" ]
stackoverflow_0074218637_deployment_python_web_applications.txt
Q: In PyCharm the Jupyter Server tool window to preview server's configuration details gives nothing I use PyCharm Professional and I am trying to launch Jupyter Notebook inside PyCharm IDE. I followed the official instructions Manage Jupyter notebook servers. I installed Jupyter and configured python 3.8 interpreter...
In PyCharm the Jupyter Server tool window to preview server's configuration details gives nothing
I use PyCharm Professional and I am trying to launch Jupyter Notebook inside PyCharm IDE. I followed the official instructions Manage Jupyter notebook servers. I installed Jupyter and configured python 3.8 interpreter using virtual environment. I do not use conda. When I run the first cell "Starting Jupyter Server" mes...
[ "I have just found the answer by myself.\nI have Jupyter configuration already in the folder ~/.jupyter/jupyter_notebook_config.py where the password and other parameters are set. So, to enter the server all I had to do is to enter the password which I set on my own in the above configuration file in the past.\n" ]
[ 0 ]
[]
[]
[ "jupyter", "jupyter_notebook", "pycharm", "python" ]
stackoverflow_0074218677_jupyter_jupyter_notebook_pycharm_python.txt
Q: Confuse about self attribute and declaration in Python i am currently trying to understand some basic concept of Python. Here is my code : class BorgSingleton: _shared_borg_state = {} test = "toto" def __init__(self): self.__dict__ = self._shared_borg_state print("borg created") ...
Confuse about self attribute and declaration in Python
i am currently trying to understand some basic concept of Python. Here is my code : class BorgSingleton: _shared_borg_state = {} test = "toto" def __init__(self): self.__dict__ = self._shared_borg_state print("borg created") print(self.test) class Point(BorgSingleton) : de...
[ "The code you've wrote should've worked if self.__dict__ had not been overridden in the parent BorgSingleton class.\nIn Python, it is not a good practice to override magic methods (ones that start and end with double-unders) unless you know what you're doing.\nTo generalize what happened, lets see the below two cla...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074218380_python.txt
Q: Slice dataframe based on last row valuse I would like to slice a dataframe so, that I output only columns where values in the last row (or at a certain index) are bigger than a certain criterion. Example: The dataframe: Name T TU TUXT TEXT TEST Date ...
Slice dataframe based on last row valuse
I would like to slice a dataframe so, that I output only columns where values in the last row (or at a certain index) are bigger than a certain criterion. Example: The dataframe: Name T TU TUXT TEXT TEST Date 2022-10-02 0.207906 0.2...
[ "Use DataFrame.loc for select rows by labels and then filter, first : means get all rows and columns by mask:\ndf1 = df.loc[:, df.loc['2022-10-30'].gt(0.1)]\nprint (df1)\n T TEST\nDate \n2022-10-02 0.207906 0.230134\n2022-10-09 0.196817 0.213108\n2022-10-16 0.228...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python", "slice" ]
stackoverflow_0074218837_dataframe_pandas_python_slice.txt
Q: How can I run selenium webdriver with two different users? I wrote a small python script on my Ubuntu server to run a chrome browser in headless mode and open a url (see the script below). Currently I have two different users on my server: Let’s say user1 and user2. What I want to achieve: Login with user1 and us...
How can I run selenium webdriver with two different users?
I wrote a small python script on my Ubuntu server to run a chrome browser in headless mode and open a url (see the script below). Currently I have two different users on my server: Let’s say user1 and user2. What I want to achieve: Login with user1 and user2 (two terminal sessions) Start the script from user1, when fi...
[ "I think the problem is that only user1 has rights on /tmp/Crashpad, because this user created the folder in the first place. root can read/write anywhere, so with the root user it works. Your user2 cannot read/write from/to /tmp/Crashpad and this leads to the error message.\nTo check if user specific tmp dirs will...
[ 2 ]
[]
[]
[ "python", "selenium", "selenium_chromedriver", "selenium_webdriver" ]
stackoverflow_0072630883_python_selenium_selenium_chromedriver_selenium_webdriver.txt
Q: Sort list of strings using lambda and with multiple conditions in python I have a list of strings and I want to sort the resulting list by string length. Strings with equal length should be sorted by how often the letter ’A’ occurs in them, so that the ones with the largest number of As come first and the others n...
Sort list of strings using lambda and with multiple conditions in python
I have a list of strings and I want to sort the resulting list by string length. Strings with equal length should be sorted by how often the letter ’A’ occurs in them, so that the ones with the largest number of As come first and the others next. I have tried using lambda function to sort but its not working result = s...
[ "You can try\na = [\"AAd\", \"aAAd\", \"AAAd\", \"adAA\"]\na.sort(key=lambda x: (len(x), -x.count('A')))\n# output\n[ 'AAd', 'AAAd', 'aAAd', 'adAA']\n\nWe are firstly sorting based on the length if length is equal then sort based on -x.count('A') so if we have 3 elements then we do counting of A in them, lets say c...
[ 3 ]
[]
[]
[ "list", "python", "sorting" ]
stackoverflow_0074218825_list_python_sorting.txt
Q: Display SQLite table in excel using python do any of you know how to create an excel file which can display a table from Sqlite using python? A: You can use pandas read_sql_query function with a query and your sqlite connection as arguments sql_query = pd.read_sql_query ( 'SELECT * FROM YOUR_TABLE', conn...
Display SQLite table in excel using python
do any of you know how to create an excel file which can display a table from Sqlite using python?
[ "You can use pandas read_sql_query function with a query and your sqlite connection as arguments\nsql_query = pd.read_sql_query (\n 'SELECT * FROM YOUR_TABLE',\n conn\n)\ndf = pd.DataFrame(sql_query, columns = ['COL1', 'COL2', 'COL3'])\ndf.to_excel(\"YOUR_TABLE.xlsx\")\n\nYou will also need to install openpyx...
[ 1 ]
[]
[]
[ "database", "datatable", "excel", "python", "sqlite" ]
stackoverflow_0074218702_database_datatable_excel_python_sqlite.txt
Q: Recursive feature elimination (RFE) with random forest I want to use Recursive feature elimination (RFE) for feature selection on my datase using random forest. I came up with this code: from sklearn.feature_selection import RFE # Create the RFE object and rank each pixel clf_rf_3 = RandomForestClassifier() ...
Recursive feature elimination (RFE) with random forest
I want to use Recursive feature elimination (RFE) for feature selection on my datase using random forest. I came up with this code: from sklearn.feature_selection import RFE # Create the RFE object and rank each pixel clf_rf_3 = RandomForestClassifier() rfe = RFE(estimator=clf_rf_3, n_features_to_select=6, step=1...
[ "This code snippet seems to expect a pandas dataframe. For a numpy array X_train[:, rfe.support_] should succeed.\n" ]
[ 1 ]
[]
[]
[ "feature_extraction", "feature_selection", "python", "rfe", "scikit_learn" ]
stackoverflow_0074214863_feature_extraction_feature_selection_python_rfe_scikit_learn.txt
Q: Unnest pandas column of lists to columns I have column of lists looks like that - df['movie-data'][0] (30K rows) [{'genre': 'movie genre', 'movie': 'movie title', 'actor-name': 'name', 'co-stars': [['name', 'name', 'name']]}] I would like to take this column and split it to 4 different columns. I tried this...
Unnest pandas column of lists to columns
I have column of lists looks like that - df['movie-data'][0] (30K rows) [{'genre': 'movie genre', 'movie': 'movie title', 'actor-name': 'name', 'co-stars': [['name', 'name', 'name']]}] I would like to take this column and split it to 4 different columns. I tried this solution - split_df = pd.DataFrame(list(df['m...
[ "You can use:\nlst = [{'genre': 'movie genre',\n 'movie': 'movie title',\n 'actor-name': 'name',\n 'co-stars': [['name', 'name', 'name']]}]\n\ndf = pd.DataFrame(lst).explode('co-stars').explode('co-stars')\n\nOr, if you always have a [[]] format:\ndf = (pd.DataFrame(lst)\n .assign(**{'co-stars': lambda d: d...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074218878_dataframe_pandas_python.txt
Q: tqdm in Jupyter Notebook prints new progress bars repeatedly I am using tqdm to print progress in a script I'm running in a Jupyter notebook. I am printing all messages to the console via tqdm.write(). However, this still gives me a skewed output like so: That is, each time a new line has to be printed, a new pro...
tqdm in Jupyter Notebook prints new progress bars repeatedly
I am using tqdm to print progress in a script I'm running in a Jupyter notebook. I am printing all messages to the console via tqdm.write(). However, this still gives me a skewed output like so: That is, each time a new line has to be printed, a new progress bar is printed on the next line. This does not happen when I...
[ "Try using tqdm.notebook.tqdm instead of tqdm, as outlined here.\nThis could be as simple as changing your import to:\nfrom tqdm.notebook import tqdm\nGood luck!\nEDIT: After testing, it seems that tqdm actually works fine in 'text mode' in Jupyter notebook. It's hard to tell because you haven't provided a minimal ...
[ 336, 52, 33, 23, 19, 17, 6, 4, 1, 0, 0, 0 ]
[]
[]
[ "jupyter_notebook", "python", "tqdm" ]
stackoverflow_0042212810_jupyter_notebook_python_tqdm.txt
Q: how to hide "py4j.java_gateway:Received command c on object id p0"? Once logging is started in INFO level I keep getting bunch of py4j.java_gateway:Received command c on object id p0 on your logs. How can I hide it? A: using the logging module run: logging.getLogger("py4j").setLevel(logging.ERROR) A: None of t...
how to hide "py4j.java_gateway:Received command c on object id p0"?
Once logging is started in INFO level I keep getting bunch of py4j.java_gateway:Received command c on object id p0 on your logs. How can I hide it?
[ "using the logging module run:\nlogging.getLogger(\"py4j\").setLevel(logging.ERROR)\n", "None of these answers have worked for me. Even after using the above solutions, I was still getting the logging errors.\nAfter a long search I came across the following that solved my issue.\nimport logging\nlogger = spark._j...
[ 40, 3, 0, 0 ]
[]
[]
[ "py4j", "pyspark", "python" ]
stackoverflow_0037252527_py4j_pyspark_python.txt
Q: How to make the ball rotate in pygame, python? I'm making a game with a basketball moving and I want to make the image of the ball rotate for it to look realistic. I have seen many things on the internet but nothing works. On this program I used pygame.transform.rotate() but it does scarcely anything. What to do? ...
How to make the ball rotate in pygame, python?
I'm making a game with a basketball moving and I want to make the image of the ball rotate for it to look realistic. I have seen many things on the internet but nothing works. On this program I used pygame.transform.rotate() but it does scarcely anything. What to do? Here is my current program: ` Simple pygame program...
[ "The main problem is:\nball = pygame.transform.rotate(ball, -10)\n\nYou have to keep the original image and rotate the original image e.g.:\nangle -= 10\nball = pygame.transform.rotate(original_ball, angle)\n\nThis is all well explained in the answer to the question How do I rotate an image around its center using ...
[ 0 ]
[]
[]
[ "pygame", "python", "rotation" ]
stackoverflow_0074214342_pygame_python_rotation.txt
Q: How do I scrape websites that do not have html content in the source page I have this site I want to scrape data from. I'm trying to extract the data below the two graphs, specifically, Volume, Fees and TVL. The problem is that when I use Selenium, I don't get any elements to access the values. I tried accessing t...
How do I scrape websites that do not have html content in the source page
I have this site I want to scrape data from. I'm trying to extract the data below the two graphs, specifically, Volume, Fees and TVL. The problem is that when I use Selenium, I don't get any elements to access the values. I tried accessing the source page and it also does not have content that is being shown on the pag...
[ "You can try the next example:\nfrom selenium import webdriver\nimport time\nfrom bs4 import BeautifulSoup\nfrom selenium.webdriver.chrome.service import Service\nimport pandas as pd\nwebdriver_service = Service(\"./chromedriver\") #Your chromedriver path\ndriver = webdriver.Chrome(service=webdriver_service)\n\ndat...
[ 0 ]
[]
[]
[ "beautifulsoup", "python", "python_requests", "selenium" ]
stackoverflow_0074218561_beautifulsoup_python_python_requests_selenium.txt
Q: Selenium Can't Scrape Vivino Information? I'm trying to obtain tasting notes and food pairing information about wines from Vivino that can't be accessed from their API, but am getting NoSuchElementException when using Selenium in Python. I've been able to scrape price and year information, but not the data further...
Selenium Can't Scrape Vivino Information?
I'm trying to obtain tasting notes and food pairing information about wines from Vivino that can't be accessed from their API, but am getting NoSuchElementException when using Selenium in Python. I've been able to scrape price and year information, but not the data further down. The page I'm trying to scrape from https...
[ "As furas mentioned in the comment, this page has lazy load so you need to scroll the page. But scrolling to the bottom doesn't help here as the page loads only the content you are looking at. So you need to scroll the page slowly to the bottom.\nHere is the code how you can do it. Not sure if it's the most elegant...
[ 0 ]
[]
[]
[ "python", "selenium", "web_scraping" ]
stackoverflow_0074215108_python_selenium_web_scraping.txt
Q: Apply a look ahead in regex that should be followed by the specified pattern and give a match other wise a no match Hello i am new to regex , i needed to apply a regex to a string of us zip codes , which we got from concatenating rows of pandas columns for example zip being header of the column zip you have some t...
Apply a look ahead in regex that should be followed by the specified pattern and give a match other wise a no match
Hello i am new to regex , i needed to apply a regex to a string of us zip codes , which we got from concatenating rows of pandas columns for example zip being header of the column zip you have some thing 70456 90876 78905 we get the string zip you have some thing 70456 90876 78905 as single literal string which should...
[ "I suggest using word-boundary (\\b) as follows\nimport re\nt1 = 'zip 1234' # less than 5, should not match\nt2 = 'zip 12345' # should match\nt3 = 'zip 123456' # more than 5, should not match\npattern = r'zip\\s\\d{5}\\b'\nprint(re.search(pattern, t1)) # None\nprint(re.search(pattern, t2)) # <re.Match object; s...
[ 0, 0 ]
[]
[]
[ "python", "python_3.x", "regex" ]
stackoverflow_0074218060_python_python_3.x_regex.txt
Q: xml.etree.ElementTree.Element' object has no attribute 'getchildren' and relative XPath does not find attributes I am not able parse and print elements and attributes from a collection category from web page using atom-xml. From the Python script below, the "print(response.content)" lists contents ok and includes:...
xml.etree.ElementTree.Element' object has no attribute 'getchildren' and relative XPath does not find attributes
I am not able parse and print elements and attributes from a collection category from web page using atom-xml. From the Python script below, the "print(response.content)" lists contents ok and includes: ''' "xmlns= <atom:category scheme="http://www.zooo.com/types" term="changetimber/has-game"/> ''' And prints child t...
[ "Change hasgame.getchildren() into list(hasgame)\n", "Alternatively you can change Change hasgame.getchildren() into hasgame.iter() and then modify accordingly\n" ]
[ 7, 1 ]
[]
[]
[ "api", "python" ]
stackoverflow_0072203390_api_python.txt
Q: insert a beep sound into an audio file for a particular word using python Can anyone tell me how to insert a beep sound into an audio file for a particular word using python? I am a beginner in python so I don't know much about it.Only thing which I get on Google is how to generate beep sound and not how I can add...
insert a beep sound into an audio file for a particular word using python
Can anyone tell me how to insert a beep sound into an audio file for a particular word using python? I am a beginner in python so I don't know much about it.Only thing which I get on Google is how to generate beep sound and not how I can add that beep sound into an audio.
[ "There's an \\a escape sequence in computers that is only designed to produce beep sound.\n" ]
[ 1 ]
[]
[]
[ "audio", "beep", "python" ]
stackoverflow_0074219039_audio_beep_python.txt
Q: Pandas extract word from link domain I have dataframe : import pandas as pd d = {'domain': ['linkedin.com','aumniversal.tumblr.com','plasticdrea.ms','linkedin.com','s-lw.tumblr.com','newsonline.media','creshendo.co.vu','deadly-skz-gods-cb.tumblr.com','deo.progr.am']} df = pd.DataFrame(d) df I want to extract ...
Pandas extract word from link domain
I have dataframe : import pandas as pd d = {'domain': ['linkedin.com','aumniversal.tumblr.com','plasticdrea.ms','linkedin.com','s-lw.tumblr.com','newsonline.media','creshendo.co.vu','deadly-skz-gods-cb.tumblr.com','deo.progr.am']} df = pd.DataFrame(d) df I want to extract the words before the last word (for exampl...
[ "Use Series.str.split and select previous last value by indexing:\ndf['words'] = df['domain'].str.split('\\.').str[-2]\nprint (df)\n domain words\n0 linkedin.com linkedin\n1 aumniversal.tumblr.com tumblr\n2 plasticdrea.ms plasticd...
[ 1, 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074219079_dataframe_pandas_python.txt
Q: How to split a list column and add them as new column values in polars dataframe? I have a data frame as below. pl.DataFrame({'combine_address':[ ["Yes|#456 Lane|Apt#4|ABC|VA|50566", "Yes|#456 Lane|Apt#4|ABC|VA|50566", "No|#456 Lane|Apt#4|ABC|VA|50566"], ["No|#8495|APT#94|SWE|WA|43...
How to split a list column and add them as new column values in polars dataframe?
I have a data frame as below. pl.DataFrame({'combine_address':[ ["Yes|#456 Lane|Apt#4|ABC|VA|50566", "Yes|#456 Lane|Apt#4|ABC|VA|50566", "No|#456 Lane|Apt#4|ABC|VA|50566"], ["No|#8495|APT#94|SWE|WA|43593", "No|#8495|APT#94|SWE|WA|43593", "Yes|#8495|APT#94|SWE|WA|43593"] ...
[ "Is this what you are looking for?\n\n\ndf = pl.DataFrame({\"combine_address\":[\n [\"Yes|#456 Lane|Apt#4|ABC|VA|50566\", \"Yes|#456 Lane|Apt#4|ABC|VA|50566\", \"No|#456 Lane|Apt#4|ABC|VA|50566\"],\n [\"No|#8495|APT#94|SWE|WA|43593\", \"No|#8495|APT#94|SWE|WA|43593\", \"Yes|#8495|APT#94|SWE|WA|43593\"]\n]})\n...
[ 3, 0 ]
[]
[]
[ "python", "python_polars" ]
stackoverflow_0074217352_python_python_polars.txt
Q: Splitting string values in List I have a huge number of string values in a list like below: a = ['1-0.0','1-0.1','4-0.1','4-0.2','4-1.0','4-1.1','4-2.0',...,'23012-11.23'] --> Approx 25000 values In each value (consider example as '4-0.1'): 4 is x, 0 is y and 1 is z. I want to analyze this data and get info like b...
Splitting string values in List
I have a huge number of string values in a list like below: a = ['1-0.0','1-0.1','4-0.1','4-0.2','4-1.0','4-1.1','4-2.0',...,'23012-11.23'] --> Approx 25000 values In each value (consider example as '4-0.1'): 4 is x, 0 is y and 1 is z. I want to analyze this data and get info like below: There are total n values starti...
[ "To split string and get integers:\nimport re\n\na=[\"4-1.0\", \"4-2.0\", \"4-1.2\", \"1-1.0\"]\nb = [[int(x) for x in re.split(\"-|\\.\", c)] for c in a]\nprint(b)\n\nResult:\n[[4, 1, 0], [4, 2, 0], [4, 1, 2], [1, 1, 0]]\n", "You can do this using split() and find():\ns=\"4-1.0\"\n\nl = [int(s) for s in (s[:s.fi...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074210532_python.txt
Q: How to add interval or condition on Z Projection on 3D Plot from Plotly (Python)? I'm trying to plot a matrix with a z projection but I don't want to project at each 0.5 values like below. I want to project the values that are "< 7.5" for example but I don't know if it's possible with Plotly Library on Python. If...
How to add interval or condition on Z Projection on 3D Plot from Plotly (Python)?
I'm trying to plot a matrix with a z projection but I don't want to project at each 0.5 values like below. I want to project the values that are "< 7.5" for example but I don't know if it's possible with Plotly Library on Python. If someone knows how to deal with it, I would be grateful Here is the code I've tried: ...
[ "Add something like this to update_layout:\nscene = dict(\n xaxis = dict(nticks=9, range=[0,80],),\n yaxis = dict(nticks=7, range=[0,120],),\n zaxis = dict(nticks=4, range=[5,8],),\n ),\n\n" ]
[ 0 ]
[]
[]
[ "plotly", "projection_matrix", "python" ]
stackoverflow_0074219099_plotly_projection_matrix_python.txt
Q: How to use tf.estimator.predict for single data item I'm new to tf.estimator having previously used an older version of tensorflow. Passing in "input_fn" has confused me slightly. I have a DNNClassifier and a numpy array containing a single data item (x) which I'd like to predict a "y" value for. This is the code ...
How to use tf.estimator.predict for single data item
I'm new to tf.estimator having previously used an older version of tensorflow. Passing in "input_fn" has confused me slightly. I have a DNNClassifier and a numpy array containing a single data item (x) which I'd like to predict a "y" value for. This is the code I have so far. dnn_clf = tf.estimator.DNNClassifier(featur...
[ "This works for me:\nYou should load the exported model that you saved before and feed it with an example\nmodel_estimate_k = tf.saved_model.load('estimatior_k/save_model/1666855778')\n\n\ndef predict(scores: list):\n example = tf.train.Example()\n example.features.feature[\"scores\"].float_list.value.extend(...
[ 0 ]
[]
[]
[ "prediction", "python", "tensorflow" ]
stackoverflow_0055689387_prediction_python_tensorflow.txt
Q: How to compare two columns in a grouped pandas dataframe? I am unable to compare two columns inside a grouped pandas dataframe. I used groupby method to group the fields with respect to two columns I am required to get the list of fields that are not matching with the actual output. file_name | page_no | field_nam...
How to compare two columns in a grouped pandas dataframe?
I am unable to compare two columns inside a grouped pandas dataframe. I used groupby method to group the fields with respect to two columns I am required to get the list of fields that are not matching with the actual output. file_name | page_no | field_name | value | predicted_value | actual_value --------------------...
[ "Here is solution for test columns outside groups:\ndf1 = df[df['predicted_value'] != df['actual_value']] \n\ns = df.loc[df['predicted_value'] != df['actual_value'], 'field_name']\n\nL = s.tolist()\n\n", "Does this solve your problem ?\n\n# Create a new dataframe retrieving only non-matching values\n\ndf1=df[df['...
[ 1, 0 ]
[]
[]
[ "dataframe", "group_by", "pandas", "python" ]
stackoverflow_0074218970_dataframe_group_by_pandas_python.txt
Q: Iterator pattern return infinite objects Hello I am trying to build a class list based like this class DummyList(Iterator): ... def __next__(self) -> int: list = [1, 2, 3, 4, 5] for i in list: yield i And I am using like this dl = DummyList() for i in dl: print(i) The out...
Iterator pattern return infinite objects
Hello I am trying to build a class list based like this class DummyList(Iterator): ... def __next__(self) -> int: list = [1, 2, 3, 4, 5] for i in list: yield i And I am using like this dl = DummyList() for i in dl: print(i) The output that I expected was 1 2 3 4 5 But instead...
[ "This would be the correct way to implement an iterator:\nfrom collections.abc import Iterator\n\n\nclass DummyList(Iterator):\n def __init__(self):\n self.lst = [1, 2, 3, 4, 5]\n self.current = -1\n\n def __iter__(self):\n return self\n\n def __next__(self):\n self.current += 1...
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0074219085_python.txt
Q: How to Send a failure email to third party in Synapse if the conditions in our Code is not satisfying the Rules? I am Currently Looking for a Solution in which we are Doing some transformations in our Synapse Notebook and we should send a mail to third party regarding the failure if the rules are not satisfying . ...
How to Send a failure email to third party in Synapse if the conditions in our Code is not satisfying the Rules?
I am Currently Looking for a Solution in which we are Doing some transformations in our Synapse Notebook and we should send a mail to third party regarding the failure if the rules are not satisfying . The Scenario here is i am currently writing a code in my Synapse Notebook using Pyspark for transforming the Source Fi...
[ "In this repro, I used dataflow activity to check the count of data in each column before and after transformation. Then I added If activity to check if count after transformation is lesser than source and basis the if activity's output, the mail will be triggered. Below are the steps.\n\nIn dataflow activity, add ...
[ 0 ]
[]
[]
[ "azure_synapse", "pyspark", "python" ]
stackoverflow_0074212307_azure_synapse_pyspark_python.txt
Q: pandas replace all nan values of a column with regex on another column So i have this dataset below which has some nan values on "a" column. I need to replace only the nan values of column "a" applying a regex on rows of column b and count the number of hashtags on its values. I need to do it inplace since I have ...
pandas replace all nan values of a column with regex on another column
So i have this dataset below which has some nan values on "a" column. I need to replace only the nan values of column "a" applying a regex on rows of column b and count the number of hashtags on its values. I need to do it inplace since I have a very big dataset. import pandas as pd import numpy as np df = pd.DataFram...
[ "Use str.count:\nregex_hashtag = \"#[a-zA-Z0-9_]+\" # or '#\\w+'\n\nm = df['a'].isna()\n\ndf.loc[m, 'a'] = df.loc[m, 'b'].str.count(regex_hashtag)\n\noutput:\n a b\n0 0 #hello world\n1 2 #hello #world\n2 1 hello #world\n\n" ]
[ 2 ]
[]
[]
[ "na", "pandas", "python" ]
stackoverflow_0074219247_na_pandas_python.txt
Q: Generate a random number for each row dependent on another column Pandas DataFrame Let it be the following Dataframe of pandas in Python. Column_1 Column_2 Number UDKA 1234 5 MAKU 1544 5 POKA 5434 2 UJFK 9104 3 I want to generate a random number column that generates for each row a random number between 1 an...
Generate a random number for each row dependent on another column Pandas DataFrame
Let it be the following Dataframe of pandas in Python. Column_1 Column_2 Number UDKA 1234 5 MAKU 1544 5 POKA 5434 2 UJFK 9104 3 I want to generate a random number column that generates for each row a random number between 1 and its value in the Number column df['Random'] = rand(1, x.Number). Example r...
[ "You can generate a random [0,1) float, then multiply by the upper bound and add 1:\nimport numpy as np\n\ndf['random'] = (df['Number'].mul(np.random.random(size=len(df))).astype(int)\n .add(1)\n )\nprint(df)\n\noutput:\n Column_1 Column_2 Number random\n0 UDKA 1234 5...
[ 2 ]
[]
[]
[ "dataframe", "pandas", "python", "random" ]
stackoverflow_0074219315_dataframe_pandas_python_random.txt
Q: Panda Dataframe - I don't know how to make a mean of certain column, not all of them i'm a highschool student and i'm doing a homework rn. I'm at the end of it but there's just something that doesn't work quite like i want it to.. For some reason, my code above is doing the mean of the value "year) and it's not so...
Panda Dataframe - I don't know how to make a mean of certain column, not all of them
i'm a highschool student and i'm doing a homework rn. I'm at the end of it but there's just something that doesn't work quite like i want it to.. For some reason, my code above is doing the mean of the value "year) and it's not something i want, but it seems it take the value "year" and not "Life expectency" as i want....
[ "You may try the following:\ndf_life_exp = (df\n .loc[df.year.isin([1952, 2007]), ['year', 'continent', 'lifeExp']]\n .groupby(['year', 'continent'])\n .mean()\n .reset_index()\n .pivot(index='continent', columns='year',values='lifeExp')\n)\nax = (df_life_exp\n .plot.bar(rot = 0, figsize=(16, 6))\...
[ 1, 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074218526_dataframe_pandas_python.txt
Q: couldn't write data to postgres using apache beam i am trying to use Beam to read a csv and send data to postgres. But the pipeline is failing due to a conversion mismatch. note that this pipeline work when the 2 column are of type int and fail when the type of column contains a string. here one of the things that...
couldn't write data to postgres using apache beam
i am trying to use Beam to read a csv and send data to postgres. But the pipeline is failing due to a conversion mismatch. note that this pipeline work when the 2 column are of type int and fail when the type of column contains a string. here one of the things that i tried. from past.builtins import unicode ExampleRow ...
[ "I think your problem is due to you have BeamSchema structure instead of expected NamedTuple in your output PCollection.\nAlso, according to the documentation, a code instruction is missing in your example coders.registry.register_coder(ExampleRow, coders.RowCoder) :\napache_beam_io_jdbc doc\nExampleRow = typing.Na...
[ 4 ]
[]
[]
[ "apache_beam", "python" ]
stackoverflow_0074213246_apache_beam_python.txt
Q: How to Filter Instances by Checking for a String in the Instance Name I am writing a python script to retrieve a list of instances that were incorrectly tagged. I need to filter by checked if a specific string exists in the name. What is the best way to do this? I was going to use describe_instances and use the ta...
How to Filter Instances by Checking for a String in the Instance Name
I am writing a python script to retrieve a list of instances that were incorrectly tagged. I need to filter by checked if a specific string exists in the name. What is the best way to do this? I was going to use describe_instances and use the tag filter (where the key is 'Name') but that filter requires that I provide ...
[ "For whoever is reading this, you can do what John Rotenstein suggested in his answer, or, you can alternatively use the wildcard character '*' in the tag name, so your filter will be something like:\nfilters = [{'Name':'tag:Name', 'Values':['string*']}]\n\n", "The easiest method is to call describe_instances() w...
[ 1, 0, 0 ]
[]
[]
[ "amazon_ec2", "amazon_web_services", "boto3", "python" ]
stackoverflow_0051200726_amazon_ec2_amazon_web_services_boto3_python.txt
Q: The problem with showing wxStaticText in Python while using wxFormBuilder I'm new at the python learning, so I can't quite understand some things. So I'm trying to make a small desktop app, and I didn't want to make all the design with a code, so I have found the thing like wxFormBuilder, which is very suits me. T...
The problem with showing wxStaticText in Python while using wxFormBuilder
I'm new at the python learning, so I can't quite understand some things. So I'm trying to make a small desktop app, and I didn't want to make all the design with a code, so I have found the thing like wxFormBuilder, which is very suits me. The problem is when I have made all the "design" of the window, it looks fine in...
[ "I have figure it out what was the problem. Default color of text was white, and the background of form is white. In code for every StaticText you need to add: self.m_staticText1.SetForegroundColour('black')\nSo it will appear.\n" ]
[ 1 ]
[]
[]
[ "label", "pycharm", "python", "static_text", "wxformbuilder" ]
stackoverflow_0074207526_label_pycharm_python_static_text_wxformbuilder.txt
Q: Fastest way to identify all pairs of lists that their difference is lower than a given threshold when the overall list is very long (10000) ahi, everyone. sorry to bother you. I have this task that I have a list of hash codings stored in a list with 30 positions with value 0 and 1. In total, I have over 10000 such...
Fastest way to identify all pairs of lists that their difference is lower than a given threshold when the overall list is very long (10000)
ahi, everyone. sorry to bother you. I have this task that I have a list of hash codings stored in a list with 30 positions with value 0 and 1. In total, I have over 10000 such 30 size (0/1) hash codes and I would like to find all pairs of such hash codes which have the difference lower than a given threshold (say 0, 1,...
[ "If you only need 30-bit vectors, it would be much better to represent then as 30 bits in a 32-bit integer. Then the Hamming distance between two \"vectors\" is just the number of bits in the xor of the two integers. There are efficient algorithms for computing the number of non-zero bits in an integer. Those ca...
[ 1, 1, 1 ]
[]
[]
[ "for_loop", "hash", "performance", "python", "python_3.x" ]
stackoverflow_0074217040_for_loop_hash_performance_python_python_3.x.txt
Q: Getting data from Excel in python using pandas in dictionary format I Have a Excel Data Like This Category Item old apple new mango old grape new ginger I need to get that data in python using pandas in the dictionary format like - {'old': ['apple', 'grape'], 'new': ['mango', gi...
Getting data from Excel in python using pandas in dictionary format
I Have a Excel Data Like This Category Item old apple new mango old grape new ginger I need to get that data in python using pandas in the dictionary format like - {'old': ['apple', 'grape'], 'new': ['mango', ginger']} From one of the references from stack overflow They provide code...
[ "You can use apply function after groupby.\ndf\n\n Category Item\n0 old apple\n1 new mango\n2 old grape\n3 new ginger\n\ndf.groupby('Category')['Item'].apply(list).to_dict()\n\n{'new': ['mango', 'ginger'], 'old': ['apple', 'grape']}\n\n" ]
[ 2 ]
[]
[]
[ "pandas", "python", "python_3.x" ]
stackoverflow_0074219381_pandas_python_python_3.x.txt
Q: Transforming Pandas pivot-table to multiple arrays of objects I have a Pandas pivot table; The goal is to pass this to a Django rest framework in the form of multiple arrays which I can easily filter in React JavaScript. pivot: x y z Magazine date M1 ...
Transforming Pandas pivot-table to multiple arrays of objects
I have a Pandas pivot table; The goal is to pass this to a Django rest framework in the form of multiple arrays which I can easily filter in React JavaScript. pivot: x y z Magazine date M1 2018-01 173 68 10 2018-02...
[ "Try:\nout = {}\nfor (m, d), row in df.iterrows():\n out.setdefault(m, {}).setdefault(d, {})\n out[m][d] = dict(row)\n\nout = {k: [{kk: vv} for kk, vv in v.items()] for k, v in out.items()}\nprint(out)\n\nPrints:\n{\n \"M1\": [\n {\"2018-01\": {\"x\": 173, \"y\": 68, \"z\": 10}},\n {\"2018-02...
[ 1, 0 ]
[]
[]
[ "arrays", "list", "object", "pivot_table", "python" ]
stackoverflow_0074219161_arrays_list_object_pivot_table_python.txt
Q: How to parse a cookie file in beautiful soup My organization needs me to authenticate a two factor authentication to scrape an internal website. Every time when i open a browser it will ask for an authentication . The authentication cookie is stored in c://users//.way//cookie.bat . I want to use this cookie file t...
How to parse a cookie file in beautiful soup
My organization needs me to authenticate a two factor authentication to scrape an internal website. Every time when i open a browser it will ask for an authentication . The authentication cookie is stored in c://users//.way//cookie.bat . I want to use this cookie file to scrape an internal website . can some one help m...
[ "BeautifulSoup will not handle cookies, instead it's requests job. Automatically parsing cookies from a file and adding them to your request session is going to be a bit a complicated but the general idea would be:\n\nread the contents of the file with open\nparse the file to a python dict (this depends on the form...
[ 0, 0 ]
[]
[]
[ "python", "web_scraping" ]
stackoverflow_0074219378_python_web_scraping.txt
Q: NLTK to Identify Names I am attepmting to extract names with the nltk python module. import nltk #!pip install svgling nltk.download('punkt') nltk.download('averaged_perceptron_tagger') nltk.download('maxent_ne_chunker') nltk.download('words') import nltk from nltk import ne_chunk, pos_tag, word_tokenize from n...
NLTK to Identify Names
I am attepmting to extract names with the nltk python module. import nltk #!pip install svgling nltk.download('punkt') nltk.download('averaged_perceptron_tagger') nltk.download('maxent_ne_chunker') nltk.download('words') import nltk from nltk import ne_chunk, pos_tag, word_tokenize from nltk.tree import Tree text =...
[ "You could give a try to Spacy\nimport spacy\nfrom spacy import displacy\n\nNER = spacy.load(\"en_core_web_lg\")\n\nraw_text = \"Elon Musk 889-888-8888 elonpie@tessa.net Jeff Bezos (345)123-1234 bezzi@zonbi.com Reshma Saujani example.email@email.com 888-888-8888 Barkevious Mingo\"\n\ntext = NER(raw_text)\n\n\nfor w...
[ 1 ]
[]
[]
[ "jupyter", "nlp", "nltk", "python", "python_3.x" ]
stackoverflow_0073805267_jupyter_nlp_nltk_python_python_3.x.txt
Q: Use list comprehension to build a tuple How can I use list comprehension to build a tuple of 2-tuple from a list. It would be equivalent to tup = () for element in alist: tup = tup + ((element.foo, element.bar),) A: tup = tuple((element.foo, element.bar) for element in alist) Technically, it's a generator e...
Use list comprehension to build a tuple
How can I use list comprehension to build a tuple of 2-tuple from a list. It would be equivalent to tup = () for element in alist: tup = tup + ((element.foo, element.bar),)
[ "tup = tuple((element.foo, element.bar) for element in alist)\n\nTechnically, it's a generator expression. It's like a list comprehension, but it's evaluated lazily and won't need to allocate memory for an intermediate list.\nFor completeness, the list comprehension would look like this:\ntup = tuple([(element.foo,...
[ 122, 1 ]
[ "You may use the following expression\ntup = *[(element.foo, element.bar) for element in alist]\n\nThis will first of all generate a list of tuples and then it will convert that list of tuples into a tuple of tuples.\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0015410119_python.txt
Q: pivot table - how to add percent by calculating using exist results - python I have a table as below: after before a 200 630 b 750 852 c 457 76738 d 3205 32235 e 12408 188561 f 1192 497130 I'd like to add a percent result and expected result as below: (percent = after/(after+...
pivot table - how to add percent by calculating using exist results - python
I have a table as below: after before a 200 630 b 750 852 c 457 76738 d 3205 32235 e 12408 188561 f 1192 497130 I'd like to add a percent result and expected result as below: (percent = after/(after+before)) after before percent a 200 630 0.240963855 b 750 ...
[ "You could try something like below:\nimport numpy as np\nimport pandas as pd\n\n# Helper function to get percentage values from our source data frame\ndef get_percent(sourceDataframe):\n \" for each value in row, return a percentage by after/(after+before) corresponds to \"\n sourceDataframe['percent'] = sourceD...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074215579_python.txt
Q: Long lived resource access I'm trying to package an application with some data in the structure. This application will perform a series of queries to DDBB and finally generate a script that will be launched to a batch system (SLURM). The script will be based on a template (part of the resources I'm accessing) and ...
Long lived resource access
I'm trying to package an application with some data in the structure. This application will perform a series of queries to DDBB and finally generate a script that will be launched to a batch system (SLURM). The script will be based on a template (part of the resources I'm accessing) and will refer to some helper script...
[ "As @sinoroc commented, there's no way to do that. The best approach is to have a \"setup/installation\" step where the data is copied from the package to a destination in disk outside the package (typically $XDG_DATA_HOME/$APPLICATION).\nThe code I used for that is:\nfrom pathlib import Path\nfrom importlib.resour...
[ 0 ]
[]
[]
[ "python", "python_importlib", "python_packaging" ]
stackoverflow_0074207000_python_python_importlib_python_packaging.txt
Q: How to effienctly divide blocks of numpy array I dont even know how to phrase what I am trying to do so I'm going straight to a simple example. I have a blocked array that looks something like this: a = np.array([ [1,2,0,0], [3,4,0,0], [9,9,0,0], [0,0,5,6], ...
How to effienctly divide blocks of numpy array
I dont even know how to phrase what I am trying to do so I'm going straight to a simple example. I have a blocked array that looks something like this: a = np.array([ [1,2,0,0], [3,4,0,0], [9,9,0,0], [0,0,5,6], [0,0,7,8], [0,0,8,8] ]) ...
[ "Reshape to three dimensions, apply the normalization for each block (last row (index 2) of each 3-row-block (step 3), then reshape back to original shape:\nb = a.reshape(-1, 3, 4)\nb = b / b[:,2::3].max(axis=2,keepdims=True)\nb = b.reshape(a.shape)\n\n", "np.concatenate may help you\n a = np.array([\n ...
[ 0, 0 ]
[]
[]
[ "array_broadcasting", "numpy", "python" ]
stackoverflow_0074219299_array_broadcasting_numpy_python.txt
Q: How to save a zip archive in Fastapi? Tell me how to save a zip archive in Fastapi Purpose: Open the url in the browser to save the file to the computer. I get an answer like this (base64) UEsDBBQAAAAIAO5cW1WrW13OHg8AAImRAAAMAAAAc3RhdHVzZXMueG1s7V3dbhvHFX6VhW4sAwrDXf6IBGznommL3v ...... HN0YXR1c2VzLnhtbFBLBQYAAAAAA...
How to save a zip archive in Fastapi?
Tell me how to save a zip archive in Fastapi Purpose: Open the url in the browser to save the file to the computer. I get an answer like this (base64) UEsDBBQAAAAIAO5cW1WrW13OHg8AAImRAAAMAAAAc3RhdHVzZXMueG1s7V3dbhvHFX6VhW4sAwrDXf6IBGznommL3v ...... HN0YXR1c2VzLnhtbFBLBQYAAAAAAQABADoAAABIDwAAAAA= I try to convert and a...
[ "Sorry for my carelessness\nI'll need to decode not encode\ncontent_msg = base64.b64decode(content)\n\n" ]
[ 0 ]
[]
[]
[ "fastapi", "python", "python_3.x" ]
stackoverflow_0074219169_fastapi_python_python_3.x.txt
Q: How do I activate a django view as a scheduled task on pythonanywhere? I am about to deploy my Django app to PythonAnywhere. I have a view (below) that cleans up all guest accounts older than a time period. I can activate this by manually going to the url (/cleanup/), however it would be nice to schedule this auto...
How do I activate a django view as a scheduled task on pythonanywhere?
I am about to deploy my Django app to PythonAnywhere. I have a view (below) that cleans up all guest accounts older than a time period. I can activate this by manually going to the url (/cleanup/), however it would be nice to schedule this automatically. I see PythonAnywhere handles scheduled tasks that ask for a path ...
[ "You need to write custom management command and run it as Scheduled Task on PythonAnywhere. You may extract the code doing what you want to separate function and call it both from the view and from the management command.\nhttps://docs.djangoproject.com/en/4.1/howto/custom-management-commands/\n" ]
[ 2 ]
[]
[]
[ "django", "python", "pythonanywhere", "scheduled_tasks" ]
stackoverflow_0074217205_django_python_pythonanywhere_scheduled_tasks.txt
Q: Comparing Dates in Lists between two Dictionaries I have two dictionaries where the values of both the dictionaries are lists of dates. What I would like to do is match the keys from both the dictionaries, and then compare the lists of dates between them in order to determine the total number of days between the d...
Comparing Dates in Lists between two Dictionaries
I have two dictionaries where the values of both the dictionaries are lists of dates. What I would like to do is match the keys from both the dictionaries, and then compare the lists of dates between them in order to determine the total number of days between the dates. However, I only want to do it on the condition th...
[ "This is a way that you can do what you want:\nthis answer is assuming that all of the dates are in chronological order\nimport datetime\n\ndef convert_to_time_obj(str_date):\n return datetime.datetime.strptime(str_date, \"%Y-%m-%d\")\n \n# get common keys between both dicts\ndict1_keys = set(dict1.keys())\nd...
[ 1, 0 ]
[]
[]
[ "date", "datetime", "dictionary", "python" ]
stackoverflow_0074202980_date_datetime_dictionary_python.txt
Q: Changing config and loading Hugging Face model fine-tuned on a downstream task I am using HuggingFace models for TokenClassification task. I have the following label2id mapping. I am using version 3.3.0 of the library label2id = { "B-ADD": 4, "B-ARRESTED": 7, "B-CRIME": 2, "B-INCIDENT_DATE": 3, ...
Changing config and loading Hugging Face model fine-tuned on a downstream task
I am using HuggingFace models for TokenClassification task. I have the following label2id mapping. I am using version 3.3.0 of the library label2id = { "B-ADD": 4, "B-ARRESTED": 7, "B-CRIME": 2, "B-INCIDENT_DATE": 3, "B-SUSPECT": 9, "B-VICTIMS": 1, "B-WPN": 5, "I-ADD": 8, "I-ARRESTED...
[ "Once a part of the model is in the saved pre-trained model, you cannot change its hyperparameters. By setting the pre-trained model and the config, you are saying that you want a model that classifies into 15 classes and that you want to initialize with a model that uses 9 classes and that does not work.\nIf I und...
[ 2, 0 ]
[]
[]
[ "bert_language_model", "huggingface_transformers", "python", "pytorch" ]
stackoverflow_0066148641_bert_language_model_huggingface_transformers_python_pytorch.txt
Q: Pandas: extract different values via regex in a single column I'm trying to extract some values from 1 column. Some rows have 4 values I want to extract and different notations for that values. My dataset: wow 0 wow-555555 1000110001 DT000333-6403, Hellostreet 45 Town1 1 (wow-666666) - 1000110002; DT00...
Pandas: extract different values via regex in a single column
I'm trying to extract some values from 1 column. Some rows have 4 values I want to extract and different notations for that values. My dataset: wow 0 wow-555555 1000110001 DT000333-6403, Hellostreet 45 Town1 1 (wow-666666) - 1000110002; DT000333-6404 Hellostreet 55 Town2 2 wow 777777 DT000333-6405 Hellos...
[ "Seems to work with:\nregex = r'\\w{3}[-\\s](?P<number1>\\d{6}).*?(?P<number2>\\d{10})?\\D*?(?P<number3>DT\\d{6}-\\d{4}).*?(?P<address>\\w.*)'\n\ndf2 = df['wow'].str.extract(regex)\n\noutput:\n number1 number2 number3 address\n0 555555 1000110001 DT000333-6403 Hellostreet 45 Town1\...
[ 3 ]
[]
[]
[ "extract", "pandas", "python", "regex" ]
stackoverflow_0074219699_extract_pandas_python_regex.txt
Q: Python - deleting a DM in Discord with on_raw_reaction_add I'm trying to have my Discord bot delete messages when reacting with an emoji. I have some code for it, which works in a Discord server, but it does not work in DMs This is my code self = discord.Bot() @self.event async def on_raw_reaction_add(ctx): if...
Python - deleting a DM in Discord with on_raw_reaction_add
I'm trying to have my Discord bot delete messages when reacting with an emoji. I have some code for it, which works in a Discord server, but it does not work in DMs This is my code self = discord.Bot() @self.event async def on_raw_reaction_add(ctx): if ctx.emoji.name == '❌': message = await self.get_channel...
[ "You need to use user.fetch_message to fetch a message in a DMChannel. So you could check if the channel exists, and if it does not, you can get the user instead.\nExample:\n@self.event\nasync def on_raw_reaction_add(ctx):\n if ctx.emoji.name == \"❌\":\n channel = self.get_channel(ctx.channel_id)\n ...
[ 0 ]
[]
[]
[ "discord", "discord.py", "python" ]
stackoverflow_0074215781_discord_discord.py_python.txt
Q: Passing instanct attributes to an object from a dictionary in Python? I have a class C with n instance attributes a1, a2, a3, ..., an and a dictionary d = {'ai': x, 'aj': y, 'ak': z, ..., 'be': p, 'bf': q, 'bg': r, ...} containing values for some of those instance attributes and some other entries. An object O = C...
Passing instanct attributes to an object from a dictionary in Python?
I have a class C with n instance attributes a1, a2, a3, ..., an and a dictionary d = {'ai': x, 'aj': y, 'ak': z, ..., 'be': p, 'bf': q, 'bg': r, ...} containing values for some of those instance attributes and some other entries. An object O = C() is constructed. Is there a better way to pass the attribute values that ...
[ "If C is a regular class, you can update its __dict__ directly:\nclass C:\n def update(self, d):\n vars(self).update(d)\n\n\nc = C()\nc.update({'foo': 123, 'bar': 456})\nprint(c.foo)\nprint(c.bar)\n\nTo make your IDE or mypy happy, it would make sense to declare these attributes in the class body or __ini...
[ 0 ]
[]
[]
[ "attributes", "class", "object", "python", "python_3.x" ]
stackoverflow_0074219744_attributes_class_object_python_python_3.x.txt
Q: Catching 'division by zero' in a function with array parameters I pass an array of values as arguments to a function. This function divides somewhere by the values given as arguments. I want to bypass the calculation for zero-value values so that I don't have to divide by zero. import numpy as np def test(t): ...
Catching 'division by zero' in a function with array parameters
I pass an array of values as arguments to a function. This function divides somewhere by the values given as arguments. I want to bypass the calculation for zero-value values so that I don't have to divide by zero. import numpy as np def test(t): e = np.where(t==0,0,10/t) return e i = np.arange(0, 5, 1) print...
[ "Use np.divide(10, t, where=t!=0):\nimport numpy as np\n\ndef test(t):\n e = np.divide(10, i, where=i!=0)\n return e\n\ni = np.arange(0, 5, 1)\nprint('in: ',i)\n\no = test(i)\nprint('out:',o)\n\n", "Yes, you can test if the divisor is zero, like you do but consider testing if it is equal to a floating point...
[ 1, 0 ]
[]
[]
[ "arrays", "numpy", "python", "python_3.x", "where_clause" ]
stackoverflow_0074219788_arrays_numpy_python_python_3.x_where_clause.txt
Q: Locust headless csv reports I am running Locust with the --headless parameter, as well as --csv=locust_stats and --csv-full-history. My tests are running correctly, but I don't see the .cvs reports in my working directory. Are there other parameters needed to create the reports? Where and when would you expect to ...
Locust headless csv reports
I am running Locust with the --headless parameter, as well as --csv=locust_stats and --csv-full-history. My tests are running correctly, but I don't see the .cvs reports in my working directory. Are there other parameters needed to create the reports? Where and when would you expect to see them? I also have stats.CSV_S...
[ "No other parameters are required. CSV reports are expected in the working directory where you kick the test. Usually, it's a project's root directory or a directory where the specific test is placed. Searching tools like \"Everything\" for Windows help to find files fast.\n" ]
[ 0 ]
[]
[]
[ "locust", "python" ]
stackoverflow_0073225888_locust_python.txt
Q: Integrate for loop in twitter scrapper in Python Hy all, I need a little wisdom. I maage to make a scrapper using the Twitter API and Tweepy. It scrapes tweets from individual profiles. I have a list of around 100 profiles that I want to scrape tweets from, but I cant figure out how to instruct the scraper to extr...
Integrate for loop in twitter scrapper in Python
Hy all, I need a little wisdom. I maage to make a scrapper using the Twitter API and Tweepy. It scrapes tweets from individual profiles. I have a list of around 100 profiles that I want to scrape tweets from, but I cant figure out how to instruct the scraper to extract data from multiple profiles and how to save the ou...
[ "If you put your scraping code into a function, you can then concat its results into an overall dataframe in a loop:\ndef get_tweets(username, no_of_tweets):\n #Creation of column list to rename the columns in the dataframe\n columns = [\"Date Created\", \"Number of Likes\", \"Source of Tweet\", \"Tweet\"]\n ...
[ 0 ]
[]
[]
[ "for_loop", "loops", "python", "tweepy", "web_scraping" ]
stackoverflow_0074219809_for_loop_loops_python_tweepy_web_scraping.txt
Q: tuple() in python is splitting strings when it shouldn't I'm trying to convert a list of strings into a list of tuples of those strings. When I use tuple() in python it splits each string into its constituents. print(BPID_list) BPID_list = [tuple(x) for x in BPID_list] print(BPID_list) >['900383', '7716922', '991...
tuple() in python is splitting strings when it shouldn't
I'm trying to convert a list of strings into a list of tuples of those strings. When I use tuple() in python it splits each string into its constituents. print(BPID_list) BPID_list = [tuple(x) for x in BPID_list] print(BPID_list) >['900383', '7716922', '99140154'] >[('9', '0', '0', '3', '8', '3'), ('7', '7', '1', '6',...
[ "You can do this:\nBPID_list = [(x,) for x in BPID_list]\n\nIn your example, it should provide the following:\n[('900383',), ('7716922',), ('99140154',)]\n\n" ]
[ 2 ]
[]
[]
[ "list_comprehension", "python", "split" ]
stackoverflow_0074219922_list_comprehension_python_split.txt
Q: How to perform a DELETE request using the Django REST Framework? I have gone through the Django REST Framework tutorials completely and cannot find a way to delete the test JSON that I created using POST. I don't have a strong understanding of how Django chooses the methods to get called, but here is what I have s...
How to perform a DELETE request using the Django REST Framework?
I have gone through the Django REST Framework tutorials completely and cannot find a way to delete the test JSON that I created using POST. I don't have a strong understanding of how Django chooses the methods to get called, but here is what I have so far: @api_view(['GET', 'PUT', 'DELETE']) def snippet_detail(request,...
[ "@api_view(['DELETE'])\ndef delete (request,id):\n category = Categories.objects.get(pk = id)\n category.delete()\n result = {\n 'status' : 'Done'\n }\n return Response(result, status = status.HTTP_200_OK)\n\n" ]
[ 0 ]
[]
[]
[ "django", "django_rest_framework", "python", "rest" ]
stackoverflow_0038386692_django_django_rest_framework_python_rest.txt
Q: Why does this specific code run faster in Python 3.11? I have the following code in a Python file called benchmark.py. source = """ for i in range(1000): a = len(str(i)) """ import timeit print(timeit.timeit(stmt=source, number=100000)) When I tried to run with multiple python versions I am seeing a drasti...
Why does this specific code run faster in Python 3.11?
I have the following code in a Python file called benchmark.py. source = """ for i in range(1000): a = len(str(i)) """ import timeit print(timeit.timeit(stmt=source, number=100000)) When I tried to run with multiple python versions I am seeing a drastic performance difference. C:\Users\Username\Desktop>py -3.10...
[ "There's a big section in the \"what's new\" page labeled \"faster runtime\". It looks like the most likely cause of the speedup here is PEP 659, which is a first start towards JIT optimization (perhaps not quite JIT compilation, but definitely JIT optimization).\nParticularly, the lookup and call for len and str n...
[ 6 ]
[]
[]
[ "cpython", "performance", "python", "python_3.11", "python_3.x" ]
stackoverflow_0074206978_cpython_performance_python_python_3.11_python_3.x.txt
Q: Loop request in python I'm trying to retrieve datas from an API. As the API can only accept one request at time, I'm struggling to implement the loop on my code. import requests url = "https://api.website.com/v1/" payload="[{\"city\":\"\amsterdam", \"location_code\":2250, \"language_code\":\"en\"}]" headers = {...
Loop request in python
I'm trying to retrieve datas from an API. As the API can only accept one request at time, I'm struggling to implement the loop on my code. import requests url = "https://api.website.com/v1/" payload="[{\"city\":\"\amsterdam", \"location_code\":2250, \"language_code\":\"en\"}]" headers = { 'Authorization': 'Basic...
[ "If you have your request data in a dictionary you can do\nimport requests\n\nurl = \"https://api.website.com/v1/\"\npayloads = {\n 1: {'city': 'amsterdam', 'location_code': 2250, 'language_code': 'en'},\n 2: {'city': 'vienna', 'location_code': 2120, 'language_code': 'de'}\n}\nheaders = {\n 'Authorization'...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074219007_python.txt
Q: what does axis = -1 mean? x= array([[1, 1, 1], [1, 1, 1]] tf.reduce_sum(x, axis = -1) If axis = 0 implies rows and axis = 1 indicates columns, what does axis = -1 mean? A: It specifies the last axis (first from the end). Negative indexes are a concept that is used quite often in Python and other languages as...
what does axis = -1 mean?
x= array([[1, 1, 1], [1, 1, 1]] tf.reduce_sum(x, axis = -1) If axis = 0 implies rows and axis = 1 indicates columns, what does axis = -1 mean?
[ "It specifies the last axis (first from the end).\nNegative indexes are a concept that is used quite often in Python and other languages as well, for example:\na = [1, 2, 3, 4]\nprint(a[-1]) # 4\nprint(a[-2]) # 3\n\nHere's a relevant article if you want to look more into it.\n" ]
[ 1 ]
[]
[]
[ "python", "tensorflow" ]
stackoverflow_0074219910_python_tensorflow.txt
Q: How to remove this type of pixels How to remove this type of pixels Examples : A: You can try morphological transformations such as Opening or Erosion. This is the documentation of OpenCV where you can find more information. https://docs.opencv.org/4.x/d9/d61/tutorial_py_morphological_ops.html It's hard to tell ...
How to remove this type of pixels
How to remove this type of pixels Examples :
[ "You can try morphological transformations such as Opening or Erosion.\nThis is the documentation of OpenCV where you can find more information.\nhttps://docs.opencv.org/4.x/d9/d61/tutorial_py_morphological_ops.html\nIt's hard to tell which method would give better results without knowing anything more specific.\n"...
[ 0 ]
[]
[]
[ "image_processing", "opencv", "python" ]
stackoverflow_0074220063_image_processing_opencv_python.txt
Q: Does augmentation in keras modify the dataset at each epoch or it is performed only once? I have a question regarding the image dataset function tf.keras.utils.image_dataset_from_directory and augmentation: If we set a seed in this dataset creation function a provide some augmentations layers in the model (those l...
Does augmentation in keras modify the dataset at each epoch or it is performed only once?
I have a question regarding the image dataset function tf.keras.utils.image_dataset_from_directory and augmentation: If we set a seed in this dataset creation function a provide some augmentations layers in the model (those layers also with a seed specified), will there be new augmented images at each epoch or will it ...
[ "The images are augmented right when the image_dataset_from_directory method is executed. Hence, no, it will not create new images for each epoch. Also, for increasing the number of images with augmentation, try reading this blog:\nhttps://machinelearningmastery.com/image-augmentation-with-keras-preprocessing-layer...
[ 0 ]
[]
[]
[ "keras", "machine_learning", "python", "tensorflow" ]
stackoverflow_0074218196_keras_machine_learning_python_tensorflow.txt
Q: How can I extract the star ratings from an icon element that only has class using Python beautifulsoup? I was trying to scrap the rating from a website, but the rating was a few "i" elements grouped together to form the numbers of star shown in the picture rating.png. Therefore, I tried to check the class attribut...
How can I extract the star ratings from an icon element that only has class using Python beautifulsoup?
I was trying to scrap the rating from a website, but the rating was a few "i" elements grouped together to form the numbers of star shown in the picture rating.png. Therefore, I tried to check the class attribute of the element and then compare it, if matches, append the result into an list called ratings. I have found...
[ "The website is dynamic and bs4 can't render JavaScript.So you can try bs4 along with Selenium.\nExample:\nfrom selenium import webdriver\nimport time\nfrom bs4 import BeautifulSoup\nfrom selenium.webdriver.chrome.service import Service\nimport pandas as pd\nwebdriver_service = Service(\"./chromedriver\") #Your chr...
[ 1 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0074220037_beautifulsoup_python_web_scraping.txt
Q: Python Find all points where a mesh intersects a plane I have verts and faces generated by skimage.measure.marching_cubes. How to find all points where a mesh intersects a plane? I would like to get something like this but on python and scikit-image A: As stated in the answer you referred, your starting point sh...
Python Find all points where a mesh intersects a plane
I have verts and faces generated by skimage.measure.marching_cubes. How to find all points where a mesh intersects a plane? I would like to get something like this but on python and scikit-image
[ "As stated in the answer you referred, your starting point should be similar and the steps will be the same, regardless of python or javascript.\nWithout example code it will be difficult to determine what part of it gives you problems.\nBy looping over the faces (consisting of 3 points if triangles) of the mesh an...
[ 1 ]
[]
[]
[ "python", "python_3.x", "scikit_image" ]
stackoverflow_0074220030_python_python_3.x_scikit_image.txt
Q: Joining individual elements of an array I have an array consisting of labels but each label has been broken down by individual characters. For example, this is the first 2 elements of the array: array([['1', '.', ' ', 'I', 'd', 'e', 'n', 't', 'i', 'f', 'y', 'i', 'n', 'g', ',', ' ', 'A', 's', 's', 'e', 's',...
Joining individual elements of an array
I have an array consisting of labels but each label has been broken down by individual characters. For example, this is the first 2 elements of the array: array([['1', '.', ' ', 'I', 'd', 'e', 'n', 't', 'i', 'f', 'y', 'i', 'n', 'g', ',', ' ', 'A', 's', 's', 'e', 's', 's', 'i', 'n', 'g', ' ', 'a', 'n', '...
[ "import numpy as np\nk=np.array([['1', '.', ' ', 'I', 'd', 'e', 'n', 't', 'i', 'f', 'y', 'i', 'n',\n 'g', ',', ' ', 'A', 's', 's', 'e', 's', 's', 'i', 'n', 'g', ' ',\n 'a', 'n', 'd', ' ', 'I', 'm', 'p', 'r', 'o', 'v', 'i', 'n', 'g',\n ' ', 'C', 'a', 'r', 'e', '', ''],\n ['9', '.', ' ', 'N...
[ 3, 3, 0, 0, 0 ]
[]
[]
[ "arrays", "concatenation", "python" ]
stackoverflow_0074220097_arrays_concatenation_python.txt
Q: Django REST list-only (no details) ViewSet There is a router: router.register('users', UsersViewSet, base_name='users') And a ViewSet: class UserViewSet(viewsets.ReadOnlyModelViewSet): def get_queryset(self): return self.get_object_list() def get_object(self): for input in self.get_object...
Django REST list-only (no details) ViewSet
There is a router: router.register('users', UsersViewSet, base_name='users') And a ViewSet: class UserViewSet(viewsets.ReadOnlyModelViewSet): def get_queryset(self): return self.get_object_list() def get_object(self): for input in self.get_object_list(): if input.id == self.kwargs[...
[ "Would you be able to inherit from mixins.ListModelMixin directly in your handler function? \n", "For anyone as late to the party as me, whilst Nimnam1's answer does lead you to the correct answer, I think a more full answer is justified as this is a great question.\nfrom rest_framework import generics\nfrom rest...
[ 0, 0 ]
[]
[]
[ "django", "python", "python_2.7", "rest" ]
stackoverflow_0040223575_django_python_python_2.7_rest.txt
Q: Python.h header file missing on Mac OS X 10.6 I'm trying to access a shared C library in Python with ctypes on Mac OS X 10.6.8 with Python 2.7.4. To do this, I need to #include <Python.h> in my C code. If I try to compile a C script that only has that one include statement in it, call it "sample.c", I get: $ gcc ...
Python.h header file missing on Mac OS X 10.6
I'm trying to access a shared C library in Python with ctypes on Mac OS X 10.6.8 with Python 2.7.4. To do this, I need to #include <Python.h> in my C code. If I try to compile a C script that only has that one include statement in it, call it "sample.c", I get: $ gcc -shared -o sample.so sample.c sample.c:1:20: error:...
[ "Python is a framework on Mac OS X so you need to,\n#include <Python/Python.h>\n\nYou also need to call gcc with the -framework argument to actually do anything inside C,\ngcc -shared -o sample.so sample.c -framework Python\n\n", "I'm not sure about 10.6.8, but Python.h should be in \n/Library/Frameworks/Python.f...
[ 33, 3, 3, 2, 1 ]
[]
[]
[ "header_files", "macos", "osx_snow_leopard", "python", "xcode" ]
stackoverflow_0016454129_header_files_macos_osx_snow_leopard_python_xcode.txt
Q: Creating a plot using matplotlib using dataframes containing two lists I am using matplotlib for the very first time and trying to learn dataframes. Now , In my code I have two lists.I have created a dataframe seperately for those two lists. I intend to create a step plot using those lists. energy_price = [33.28, ...
Creating a plot using matplotlib using dataframes containing two lists
I am using matplotlib for the very first time and trying to learn dataframes. Now , In my code I have two lists.I have created a dataframe seperately for those two lists. I intend to create a step plot using those lists. energy_price = [33.28, 30.00, 29.15, 28.49, 34.66, 50.01, #14 sept nord pool day ahead SE1 ...
[ "There in your code you assign df two times, the second time overwrites the first. The proper way should be:\nimport pandas as pd\n\ndf = pd.DataFrame({'time1': time1,\n 'price_energy': price_energy})\n\nThen plot the step plot:\nimport matplotlib.pyplot as plt\n\nplt.step(x='time1', y='price_ener...
[ 0, 0 ]
[]
[]
[ "dataframe", "matplotlib", "pandas", "plot", "python" ]
stackoverflow_0074219990_dataframe_matplotlib_pandas_plot_python.txt
Q: How to select multiple JSON Objects using python I have a Json data as following. The Json has many such objects with same NameId's: [{ "NameId": "name1", "exp": { "exp1": "test1" } }, { "NameId": "name1", "exp": { "exp2": "test2" } } ] Now, what I am after is to create a n...
How to select multiple JSON Objects using python
I have a Json data as following. The Json has many such objects with same NameId's: [{ "NameId": "name1", "exp": { "exp1": "test1" } }, { "NameId": "name1", "exp": { "exp2": "test2" } } ] Now, what I am after is to create a new Json Object that has a merged exp and create a file...
[ "You can do the manual work, merging the entries while rebuilding the structure. You can keep a dictionary with the exp to merge them.\nimport json\n\njsonData = [{\n \"NameId\": \"name1\",\n \"exp\": {\n \"exp1\": \"test1\"\n }\n}, {\n \"NameId\": \"name1\",\n \"exp\": {\n \"exp2\": \"...
[ 1, 0 ]
[]
[]
[ "json", "python" ]
stackoverflow_0074219494_json_python.txt
Q: select between lists elements with regex I have 2 lists: images = ['ND_row_id_4026.png', 'ND_row_id_7693.png', 'ND_row_id_5285.png', 'ND_row_id_1045.png', 'ND_row_id_2135.png', 'ND_row_id_8155.png', 'ND_row_id_3135.png'] masks = ['MA_row_id_4026.png', ...
select between lists elements with regex
I have 2 lists: images = ['ND_row_id_4026.png', 'ND_row_id_7693.png', 'ND_row_id_5285.png', 'ND_row_id_1045.png', 'ND_row_id_2135.png', 'ND_row_id_8155.png', 'ND_row_id_3135.png'] masks = ['MA_row_id_4026.png', 'MA_row_id_7693.png', 'MA_row_...
[ "It seems (based on your sample data) a simple list comprehension should suffice, just replacing the prefix for comparison:\nres = [im for im in images if im.replace('ND', 'MA') in masks]\n\nOutput (for your sample data):\n[\n 'ND_row_id_4026.png',\n 'ND_row_id_7693.png',\n 'ND_row_id_5285.png',\n 'ND_row_id_1045.p...
[ 2, 1, 1 ]
[]
[]
[ "list", "python", "string" ]
stackoverflow_0074218194_list_python_string.txt
Q: How to group/average dataframe with the custom date range in pandas? Could you please help with question how to group/average one dataframe with the date index from another df in pandas? I have two dfs - one with weekly price data (with irregular dates) and the second df with daily exchange rates. I want to calcul...
How to group/average dataframe with the custom date range in pandas?
Could you please help with question how to group/average one dataframe with the date index from another df in pandas? I have two dfs - one with weekly price data (with irregular dates) and the second df with daily exchange rates. I want to calculate averages of FX rate by date periods from weekly price data df. ...
[ "The output is not fully clear, but you can use a merge_asof to align the two datasets:\ndf1.index = pd.to_datetime(df1.index, dayfirst=True)\ndf2.index = pd.to_datetime(df2.index, dayfirst=True)\n\n(pd.merge_asof(df2, df1.assign(date=df1.index),\n left_index=True, right_index=True, direction='fo...
[ 1 ]
[]
[]
[ "group_by", "pandas", "python" ]
stackoverflow_0074220251_group_by_pandas_python.txt
Q: Force streamlit to run in specific python version (or under specific environment) I have a streamlit app that is set to run by doubleclicking a *.bat file that contains the command to start the app: streamlit run myApp.py. Does anyone know how to force that app to run in specific python version? My base python is ...
Force streamlit to run in specific python version (or under specific environment)
I have a streamlit app that is set to run by doubleclicking a *.bat file that contains the command to start the app: streamlit run myApp.py. Does anyone know how to force that app to run in specific python version? My base python is 3.9, I created an environment (conda env create ...) based on python 3.6 where I instal...
[ "Although Streamlit is a Python library (and used to be a stand-alone company), streamlit run myApp.py in that context is a reference to an executable streamlit. In cases where there are multiple, you can specify the exact one you want to use:\n/path/to/conda/env/streamlit run myApp.py\n", "/path/to/your/python -...
[ 0, 0 ]
[]
[]
[ "environment", "python", "python_venv", "streamlit" ]
stackoverflow_0072705042_environment_python_python_venv_streamlit.txt
Q: Python add item to the tuple I have some object.ID-s which I try to store in the user session as tuple. When I add first one it works but tuple looks like (u'2',) but when I try to add new one using mytuple = mytuple + new.id got error can only concatenate tuple (not "unicode") to tuple. A: You need to make the...
Python add item to the tuple
I have some object.ID-s which I try to store in the user session as tuple. When I add first one it works but tuple looks like (u'2',) but when I try to add new one using mytuple = mytuple + new.id got error can only concatenate tuple (not "unicode") to tuple.
[ "You need to make the second element a 1-tuple, eg:\na = ('2',)\nb = 'z'\nnew = a + (b,)\n\n", "Since Python 3.5 (PEP 448) you can do unpacking within a tuple, list set, and dict:\na = ('2',)\nb = 'z'\nnew = (*a, b)\n\n", "From tuple to list to tuple :\na = ('2',)\nb = 'b'\n\nl = list(a)\nl.append(b)\n\ntuple(l...
[ 396, 92, 42, 18, 12, 9, 3, 2 ]
[ "\ntup=(23,2,4,5,6,8)\nn_tup= tuple(map(lambda x: x+3,tup))\nprint(n_tup)\n" ]
[ -1 ]
[ "python", "tuples" ]
stackoverflow_0016730339_python_tuples.txt
Q: Do the folder structures of minor version updates for Python conflict with each other? I have Python 3.10.x on my system and have just updated to the latest version (3.11.xx). Do I need to remove the 3.10 folder or can it be left? Disc space is not an issue. Have not tried to remove and there does not appear to be...
Do the folder structures of minor version updates for Python conflict with each other?
I have Python 3.10.x on my system and have just updated to the latest version (3.11.xx). Do I need to remove the 3.10 folder or can it be left? Disc space is not an issue. Have not tried to remove and there does not appear to be any current conflicts. However the Scripts folder in 3.10 has a lot of files that are not a...
[ "You don't necessarily need to remove the old version. Be sure to check which one is present in the System Environmental Variables > Path, that's the one Windows will see and use.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074219933_python.txt
Q: Can't install python3-venv in Ubuntu 20.04, some broken packages This might be long but please bear with me till the end When I tried to install python3-venv while following this article sudo apt install build-essential libssl-dev libffi-dev python3-dev It threw the following error: libffi-dev python3-dev Reading...
Can't install python3-venv in Ubuntu 20.04, some broken packages
This might be long but please bear with me till the end When I tried to install python3-venv while following this article sudo apt install build-essential libssl-dev libffi-dev python3-dev It threw the following error: libffi-dev python3-dev Reading package lists... Done Building dependency tree Reading state i...
[ "The main reason for these issues was the version of python3.8\nI had version 3.8.13-1+bionic2 but we needed 3.8.10-0ubuntu1~20.04.5\nI think this generally occurs when you upgrade from Ubuntu 18.04 LTS to Ubuntu 20.04 LTS using in-built Software & Updates\nSo I found this command which rolled back the versions now...
[ 0 ]
[]
[]
[ "python", "ubuntu" ]
stackoverflow_0074218920_python_ubuntu.txt
Q: Running multiple python scripts from kubernetes I want to run multiple python scripts with passing arguments to the python script, how I can do that? Is it possible in Kubernetes? Like I have multiple python scripts with different inputs: "./main.py", "1" , "./main2.py", "2", "./main3.py", "3" I can not put all of...
Running multiple python scripts from kubernetes
I want to run multiple python scripts with passing arguments to the python script, how I can do that? Is it possible in Kubernetes? Like I have multiple python scripts with different inputs: "./main.py", "1" , "./main2.py", "2", "./main3.py", "3" I can not put all of them in one file to run need to run them separately ...
[ "can you try as shown below\nkind: Pod\nmetadata:\n name: hello-world-1\nspec: # specification of the pod’s contents\n restartPolicy: Never\n containers:\n - name: hello\n image: \"ubuntu:14.04\"\n env:\n - name: MESSAGE\n value: \"hello world\"\n command: [ \"python\" ]\n args: [ \...
[ 1, 0 ]
[]
[]
[ "kubernetes", "python", "yaml" ]
stackoverflow_0074217036_kubernetes_python_yaml.txt
Q: Could not install packages due to an OSError: [WinError 5] Access is denied This occurs when I install specific packages, even if I run as admin; for this case specifically I was running pip install shapash But would get this error ERROR: Could not install packages due to an OSError: [WinError 5] Access is denied...
Could not install packages due to an OSError: [WinError 5] Access is denied
This occurs when I install specific packages, even if I run as admin; for this case specifically I was running pip install shapash But would get this error ERROR: Could not install packages due to an OSError: [WinError 5] Access is denied: 'C:\\Users\\USER\\AppData\\Roaming\\Python\\Python39\\site-packages\\Python\\P...
[ "I fixed this error by running VS Code as Administrator.\n" ]
[ 3 ]
[]
[]
[ "pip", "python", "python_3.x" ]
stackoverflow_0073339138_pip_python_python_3.x.txt
Q: How to return error response when database failed to commit Introduction: In our FastAPI app, we implemented dependency which is being used to commit changes in the database (according to https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/). Issue: The issue we are facing (which is also par...
How to return error response when database failed to commit
Introduction: In our FastAPI app, we implemented dependency which is being used to commit changes in the database (according to https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/). Issue: The issue we are facing (which is also partially mentioned on the website provided above) is that the route...
[ "This is the solution we have implemented for this individual use case.\nAs a reminder, the main purpose was to catch a database error and react to it by sending proper response to the client. The tricky part was that we wanted to omit the scenario of adding the same line of code to every endpoint as we have plenty...
[ 1, 0 ]
[]
[]
[ "fastapi", "python", "sqlalchemy" ]
stackoverflow_0073785023_fastapi_python_sqlalchemy.txt
Q: Incomplete _pb2.py file generated by python protobuf? I want to generate _pb2.py files from .proto files and use them for bigquery data upload. The proto file contains simple messages with only string and int32 fields like: syntax = "proto2"; package duplicate; message duplicate { required int32 id = 1; ...
Incomplete _pb2.py file generated by python protobuf?
I want to generate _pb2.py files from .proto files and use them for bigquery data upload. The proto file contains simple messages with only string and int32 fields like: syntax = "proto2"; package duplicate; message duplicate { required int32 id = 1; optional string title = 2; ... I need to use a new protoc...
[ "I've got the same problem. In my case, generating the pb2 files makes my old code fail as the generated files are not exporting properly the classes, they have to be directly accessible through the pb2 class:\n\nIn my case, I've got protoc:3.21.8. As a next step, I am trying to find out why the new pb2 does not ex...
[ 0 ]
[]
[]
[ "macos", "protoc", "protocol_buffers", "python" ]
stackoverflow_0074214692_macos_protoc_protocol_buffers_python.txt
Q: datetime.date.today() always returns the same value I have a Django project. I use nginx + gunicorn. The views.py file has a combined_data() function that creates and returns an HTML page. As you can see, I am passing the objects in 'rows' and the current date in 'time'. A function that returns objects looks like...
datetime.date.today() always returns the same value
I have a Django project. I use nginx + gunicorn. The views.py file has a combined_data() function that creates and returns an HTML page. As you can see, I am passing the objects in 'rows' and the current date in 'time'. A function that returns objects looks like this The problem is that in this function, reporting_da...
[ "The default value for the parameter reported_date is the value of the first time the function gets imported. You should do something like\ndef get_combined(reported_date=None, ...):\n reported_date = reported_date or datetime.datetime.today()\n ...\n\n", "Instead of\ndef get_combined(reported_date=datetime...
[ 2, 1 ]
[]
[]
[ "datetime", "django", "gunicorn", "python" ]
stackoverflow_0074220346_datetime_django_gunicorn_python.txt
Q: 'NoneType' object is not subscriptable First , I created 4 table : Artist, Genre, Album , Track . I want to travarse through xml file , then obtain necessary data and then insert into Track table. Everything works fine , until the i try to get the id on Genre table and try to assign it to genre_id. When I run my p...
'NoneType' object is not subscriptable
First , I created 4 table : Artist, Genre, Album , Track . I want to travarse through xml file , then obtain necessary data and then insert into Track table. Everything works fine , until the i try to get the id on Genre table and try to assign it to genre_id. When I run my program it is showing that 'NoneType' object ...
[ "You need to add the condition if 'genre is None' as indicated below.\nif name is None or artist is None or album is None or genre is None :\n continue\n\n" ]
[ 0 ]
[]
[]
[ "python", "sql", "sqlite" ]
stackoverflow_0072334232_python_sql_sqlite.txt
Q: Comparing list and returning odd element in list query Given two almost identical lists of worker IDs x and y where one of the lists contains an additional ID, write a function solution(x, y) that compares the lists and returns the additional ID. For example, given the lists x = [13, 5, 6, 2, 5] and y = [5, 2, 5, ...
Comparing list and returning odd element in list query
Given two almost identical lists of worker IDs x and y where one of the lists contains an additional ID, write a function solution(x, y) that compares the lists and returns the additional ID. For example, given the lists x = [13, 5, 6, 2, 5] and y = [5, 2, 5, 13], the function solution(x, y) would return 6 because the ...
[ "As suggested in comments, you can use collections.Counter to solve this.\ndef solution(x, y):\n cx, cy = Counter(x), Counter(y)\n return [k for k in cx.keys() | cy.keys() \n if not ((a := cx.get(k)) and (b := cy.get(k))) or a != b]\n\nA key from either Counter is the answer if it's either not in both ...
[ 0, 0 ]
[ "Sort each list then enumerate them in parallel (zip) until you find a difference. You know that the lists differ by one value. Therefore the value from the longest list is what you're looking for.\nHence:\nfrom itertools import zip_longest\n\ndef solution(x, y):\n for _x, _y in zip_longest(sorted(x), sorted(y))...
[ -1 ]
[ "python" ]
stackoverflow_0074212017_python.txt
Q: Connect to another database and dumpdata from it in json format My task is to populate my two existing City and Province model using two json files cities.json' and 'provinces.json. Data in these files are as below. provinces.json: [ { "model": "salesnetwork.provinces", "id": "1", "name": ...
Connect to another database and dumpdata from it in json format
My task is to populate my two existing City and Province model using two json files cities.json' and 'provinces.json. Data in these files are as below. provinces.json: [ { "model": "salesnetwork.provinces", "id": "1", "name": "EA" } ] cities.json: [ { "model": "salesnetwork.cities", ...
[ "Try to paste json into new file in vscode and save it.\nErrorjson.decoder.JSONDecodeError: Unexpected UTF-8 BOM because your json files have UTF8-BOM encoding:\nhttps://www.coderedcorp.com/blog/how-to-dump-your-django-database-and-load-it-into-/\n" ]
[ 1 ]
[]
[]
[ "django", "json", "python" ]
stackoverflow_0074220027_django_json_python.txt
Q: Csv file only store single row pf data using python I scrape a website and try to store it into Csv format but when i did it is store only single row of data. how to write multiples Row of data in csv. for lis in lists: title = lis.find('a', class_="title").text tag = lis.find('span', class_="et...
Csv file only store single row pf data using python
I scrape a website and try to store it into Csv format but when i did it is store only single row of data. how to write multiples Row of data in csv. for lis in lists: title = lis.find('a', class_="title").text tag = lis.find('span', class_="etc-mark").text datetime = lis.find('span', class_=...
[ "data gets overwritten in every iteration, so after the loop it contains the data from the last iteration only.\n\nInitialize data before the loop, the append to it in every iteration.\n\nUse writerows instead of writerow.\n\n\ndata = []\n\nfor lis in lists:\n title = lis.find('a', class_=\"title\").text\n ta...
[ 2 ]
[]
[]
[ "beautifulsoup", "csv", "python" ]
stackoverflow_0074220798_beautifulsoup_csv_python.txt
Q: Looping through a list when KeyError occurs I would like to know, how I can loop through a list when a KeyError occurs in python. The code is just representatively. In my real problem I want to loop through api keys (when the KeyError occurs use the next api key and do the request again). Imagine I have a list cal...
Looping through a list when KeyError occurs
I would like to know, how I can loop through a list when a KeyError occurs in python. The code is just representatively. In my real problem I want to loop through api keys (when the KeyError occurs use the next api key and do the request again). Imagine I have a list called keys but in my dict only the 3rd to 5th key w...
[ "keys = ['key1', 'key2', 'key3', 'key4', 'key5']\n\nmy_dict = {\n \"key3\": \"3\",\n \"key4\": \"4\",\n \"key5\": \"5\"\n}\n\nfor key in keys:\n key = my_dict.get(key)\n if key:\n print(key)\n break\n\n", "keys = ['key1', 'key2', 'key3', 'key4', 'key5']\n\ncheck_dict_values = {\n \...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074220286_python.txt
Q: Exploding a list of dictionaries in pandas to multiple rows and columns I'm working with Shopify's Order API and I receive the following responses, which currently sit in a dataframe (very simplified). +----------+-----------+-----------------------------------------------------------------------------+ | order_id...
Exploding a list of dictionaries in pandas to multiple rows and columns
I'm working with Shopify's Order API and I receive the following responses, which currently sit in a dataframe (very simplified). +----------+-----------+-----------------------------------------------------------------------------+ | order_id | name | item_order ...
[ "Use DataFrame.explode with json_normalize:\ndf = df.explode('item_order').reset_index(drop=True)\ndf = df.join(pd.json_normalize(df.pop('item_order')))\n\n", "First explode and then agg(pd.Series):\nnew_df = df.explode('item_order')\nnew_df[['item_order.id', 'item_order.price', 'item_order.sku']] = ( new_df['ite...
[ 1, 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074220810_pandas_python.txt