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: Fetch the latest tweet from Twitter with Tweepy I want to fetch the latest tweet if the keyword is met from a bounch of users at Twitter in real time. This code fetchs the latest tweet if 'Twitter' keyword is met, and stores it in the "store" variable every 5 seconds and goes on forever. Is there a way to make it ...
Fetch the latest tweet from Twitter with Tweepy
I want to fetch the latest tweet if the keyword is met from a bounch of users at Twitter in real time. This code fetchs the latest tweet if 'Twitter' keyword is met, and stores it in the "store" variable every 5 seconds and goes on forever. Is there a way to make it to only fetch the tweet if it isent already present i...
[ "I think the important piece of data would be the 'id' field returned in the list. You could either add the tweets to a dictionary where the key would be the 'id' and the value the text of the tweet, or create a second list that contains the 'id' and then create a filter condition to validate that the 'id' isn't pr...
[ 0 ]
[]
[]
[ "python", "tweepy", "web_scraping" ]
stackoverflow_0074537755_python_tweepy_web_scraping.txt
Q: Order queryset by the number of foreign key instances in a Django field I am trying to return the objects relating to a through table which counts the number of reactions on a blog post. I have an Article model, Sentiment model and Reactions model. The sentiment is simply a 1 or 2, 1 representing like and 2 for di...
Order queryset by the number of foreign key instances in a Django field
I am trying to return the objects relating to a through table which counts the number of reactions on a blog post. I have an Article model, Sentiment model and Reactions model. The sentiment is simply a 1 or 2, 1 representing like and 2 for dislike. On the frontend users can react to an article and their reactions are ...
[ "I solved a simular Problem a different way.\nFor me I wanted to sort a queryset of Person by how often the Country was used.\nI added a property to the Model\nclass Country(models.Model):\n .\n .\n def _get_count(self):\n count = len(Person.objects.filter(country=self.id))\n\n return count o...
[ 0, 0 ]
[]
[]
[ "count", "django", "python" ]
stackoverflow_0074534666_count_django_python.txt
Q: How do I capture the result of assertion in a variable? In pytest, I would like to capture, for example, the result of something like assert a==b in a variable. Any idea how do I do that? var = assert fruit1 == fruit2 does not capture the assert value in var. Thanks in advance! Tried var = assert fruit1 == fruit2...
How do I capture the result of assertion in a variable?
In pytest, I would like to capture, for example, the result of something like assert a==b in a variable. Any idea how do I do that? var = assert fruit1 == fruit2 does not capture the assert value in var. Thanks in advance! Tried var = assert fruit1 == fruit2 Expecting the value of assert (true or false) to be capture...
[ "In newer versions of Python, you can use the Walrus operator:\nhttps://realpython.com/python-walrus-operator/\nassert (var := (fruit1 == fruit2))\nprint('var = ', var)\n# output: var = True # otherwise, the code would have already crashed :)\n\nThe Walrus operator can also be used inside if-statements, nested expr...
[ 1, 0 ]
[]
[]
[ "pytest", "python" ]
stackoverflow_0074537222_pytest_python.txt
Q: Avoiding console prints by Libvirt Qemu python APIs I am trying to check if a domain exists by using the libvirt python API "lookupbyname()". If the domain does not exist, it prints an error message on the console saying "Domain not found". I need the errors or logs only in syslog. I have tried redirecting stde...
Avoiding console prints by Libvirt Qemu python APIs
I am trying to check if a domain exists by using the libvirt python API "lookupbyname()". If the domain does not exist, it prints an error message on the console saying "Domain not found". I need the errors or logs only in syslog. I have tried redirecting stderr and stdout. But, it doesn't have any effect. I have al...
[ "This is a historical design mistake of libvirt, which we unfortunately can't remove without breaking back-compat for apps relying in this mis-feature. So you need to manually turn off printing to console using\ndef libvirt_callback(userdata, err):\n pass\n\nlibvirt.registerErrorHandler(f=libvirt_callback, ctx=N...
[ 2, 0 ]
[]
[]
[ "libvirt", "logging", "python", "qemu" ]
stackoverflow_0045541725_libvirt_logging_python_qemu.txt
Q: Im trying to get links from a TXT file, but it ends with 0 results So I have a txt file that contains several links along with other text, More specifically a list of twitter like data, (tweets that I have liked), And im trying to compile the image links specifically (t.co links) into a single txt file. So I made ...
Im trying to get links from a TXT file, but it ends with 0 results
So I have a txt file that contains several links along with other text, More specifically a list of twitter like data, (tweets that I have liked), And im trying to compile the image links specifically (t.co links) into a single txt file. So I made this script. FileObject = open(r"like.txt","r") word = str(FileObject) ...
[]
[]
[ "try this for the file reading:\nhttps://www.tutorialkart.com/python/python-read-file-as-string/\n#open text file in read mode\ntext_file = open(\"D:/data.txt\", \"r\")\n\n#read whole file to a string\nword = text_file.read()\n\n" ]
[ -1 ]
[ "python", "python_3.x" ]
stackoverflow_0074538093_python_python_3.x.txt
Q: How to import a module to a script in a sub-directory I have a basic directory strucrure model_folder | | ------- model_modules | | | ---- __init__.py | | | ---- foo.py | | | ---- bar.py | | ------- research | | | ----- trai...
How to import a module to a script in a sub-directory
I have a basic directory strucrure model_folder | | ------- model_modules | | | ---- __init__.py | | | ---- foo.py | | | ---- bar.py | | ------- research | | | ----- training.ipynb | | | ----- eda.ipynb | | ...
[ "I believe your ipynb is not in the same directory as your module.\nIn this case, you must add the module path as the code below.\nPrepare the absolute path of the model_folder.\nI suggest this code below.\nimport sys\nsys.path.append('/absolute/path/model_folder')\nfrom model_modules.foo import Foo\nfrom model_mod...
[ 1 ]
[]
[]
[ "directory", "python", "python_module" ]
stackoverflow_0074538012_directory_python_python_module.txt
Q: How to remove extra parentheses, if and only if, in between they contain a regex pattern? import re, datetime input_text = "hhhh ((44_-_44)) ggj ((2022_-_02_-_18 20:00 pm)) ((((2022_-_02_-_18 20:00 pm))) (2022_-_02_-_18 00:00 am)" identify_dates_regex_00 = r"(?P<year>\d*)_-_(?P<month>\d{2})_-_(?P<startDay>\d{2})...
How to remove extra parentheses, if and only if, in between they contain a regex pattern?
import re, datetime input_text = "hhhh ((44_-_44)) ggj ((2022_-_02_-_18 20:00 pm)) ((((2022_-_02_-_18 20:00 pm))) (2022_-_02_-_18 00:00 am)" identify_dates_regex_00 = r"(?P<year>\d*)_-_(?P<month>\d{2})_-_(?P<startDay>\d{2})" identify_time_regex = r"(?P<hh>\d{2}):(?P<mm>\d{2})[\s|]*(?P<am_or_pm>(?:am|pm))" restructur...
[ "You can use a single capture group to capture the date and time format between parenthesis, and then remove any surrounding parenthesis.\nTo do the replacement, you don't need the named capture groups.\nIn the replacement use capture group 1.\n\\(*(\\(\\d{4}_-_\\d{2}_-_\\d{2} \\d{2}:\\d{2}[\\s|]*[ap]m\\))\\)*\n\nR...
[ 2 ]
[]
[]
[ "python", "python_3.x", "regex", "regex_group", "replace" ]
stackoverflow_0074528223_python_python_3.x_regex_regex_group_replace.txt
Q: Create line graph from database that assigns lines to each name I have an SQLite table I want to make a line graph from: import sqlite3 conn = sqlite3.connect('sales_sheet.db') cur = conn.cursor() cur.execute("""CREATE TABLE IF NOT EXISTS sales(id INTEGER PRIMARY KEY NOT NULL, sales_rep TEXT, ...
Create line graph from database that assigns lines to each name
I have an SQLite table I want to make a line graph from: import sqlite3 conn = sqlite3.connect('sales_sheet.db') cur = conn.cursor() cur.execute("""CREATE TABLE IF NOT EXISTS sales(id INTEGER PRIMARY KEY NOT NULL, sales_rep TEXT, client TEXT, number_of_sales INTEGER)""") case1 = (...
[ "You can use pandas.read_sql or pandas.read_sql_query to read the sqlite table as a dataframe then seaborn.lineplot to make the multicolor linegraph.\nimport pandas as pd\nimport seaborn as sns\n\ndf = pd.read_sql_query(\"SELECT * FROM sales LIMIT 0,30\", conn)\n\nsns.lineplot(data=df, x='id', y='number_of_sales', ...
[ 1 ]
[]
[]
[ "linegraph", "matplotlib", "python", "sqlite" ]
stackoverflow_0074538086_linegraph_matplotlib_python_sqlite.txt
Q: other way to solve Least common multiple of two integers a and b PPCM which is the least common multiple, lowest common multiple, or smallest common multiple of two integers a and b, is the smallest positive integer that is divisible by both a and b. Since division of integers by zero is undefined, this definition...
other way to solve Least common multiple of two integers a and b
PPCM which is the least common multiple, lowest common multiple, or smallest common multiple of two integers a and b, is the smallest positive integer that is divisible by both a and b. Since division of integers by zero is undefined, this definition has meaning only if a and b are both different from zero. However, so...
[ "The lcm is computed from the gcd and the latter using Euclid's agorithm.\ndef gcd(a, b):\n while b > 0:\n a, b= b, a % b\n return a\n\ndef lcm(a, b):\n return a * b // gcd(a, b)\n\n(The trivial cases are not handled.)\n", "You can do this with a single loop; there's no need to build a bunch of li...
[ 1, 0 ]
[]
[]
[ "algorithm", "list", "math", "performance", "python" ]
stackoverflow_0074537912_algorithm_list_math_performance_python.txt
Q: How to create a virtual environment in python (venv) and add libraries from anaconda installed in the operating system? Without internet connection Is it possible to create a python virtual environment (venv) from the local anaconda repository and add packages from there? I have anaconda distribution installed he...
How to create a virtual environment in python (venv) and add libraries from anaconda installed in the operating system? Without internet connection
Is it possible to create a python virtual environment (venv) from the local anaconda repository and add packages from there? I have anaconda distribution installed here: C: \ ProgramData \ Anaconda3 I want to create a virtual environment for a new project. Here: C: \ new_project \ venv For example, I want to add p...
[ "I did it.\nhttps://docs.conda.io/projects/conda/en/latest/commands/install.html\n[SOLUTION]\nI solved it as follows:\n\"path\" - your path\n\"libs\" - library names\n\nconda create -p \"path\" --copy\n\nconda install -p \"path\" \"libs\" --offline --use-local\n\n\nExample:\n1.conda create -p c: \\ my_project \\ ve...
[ 0 ]
[]
[]
[ "anaconda", "numpy", "pandas", "python", "python_venv" ]
stackoverflow_0074535319_anaconda_numpy_pandas_python_python_venv.txt
Q: Pafy+Youtub_dl+OpenCV is slow to display videos I am trying a basic example of displaying a youtube video using opencv, and I seem to get 50% or less of the framerate as in the browser. Eventually I want to make a real-time computer vision application from youtube streams (well, a fixed delay is fine, but I want ...
Pafy+Youtub_dl+OpenCV is slow to display videos
I am trying a basic example of displaying a youtube video using opencv, and I seem to get 50% or less of the framerate as in the browser. Eventually I want to make a real-time computer vision application from youtube streams (well, a fixed delay is fine, but I want it to be able to keep up), and so if just displaying ...
[ "Turns out there was a bug in youtube_dl: https://github.com/ytdl-org/youtube-dl/issues/29326 that essentially caused youtube to throttle the connection.\n" ]
[ 0 ]
[]
[]
[ "opencv", "pafy", "python", "youtube_dl" ]
stackoverflow_0074512218_opencv_pafy_python_youtube_dl.txt
Q: How to get columns titles from googlesheets to print in Python? Basically I'm using Python to pull information off a google spreadsheet. enter image description here I have no problem pulling the information I need but when I start to break it down into specific catergories like "goals scored" i get the informatio...
How to get columns titles from googlesheets to print in Python?
Basically I'm using Python to pull information off a google spreadsheet. enter image description here I have no problem pulling the information I need but when I start to break it down into specific catergories like "goals scored" i get the information but can print it to the terminal with the column headings. Example ...
[ "Use \"get_all_records()\" instead of \"get_all_values()\".\n" ]
[ 0 ]
[]
[]
[ "google_sheets", "gspread", "python" ]
stackoverflow_0069472788_google_sheets_gspread_python.txt
Q: Django runserver_plus pyOpenSSL not installed error, although it is Linux Mint 19.3, Python 3.8 virtual environment. So I try to run runserver_plus using ssl: python manage.py runserver_plus --cert-file cert.crt Then I get following error: CommandError: Python OpenSSL Library is required to use runserver_plus wit...
Django runserver_plus pyOpenSSL not installed error, although it is
Linux Mint 19.3, Python 3.8 virtual environment. So I try to run runserver_plus using ssl: python manage.py runserver_plus --cert-file cert.crt Then I get following error: CommandError: Python OpenSSL Library is required to use runserver_plus with ssl support. Install via pip (pip install pyOpenSSL). But the deal is...
[ "Such issue can appear when you need to recompile cryptography with the correct openssl.\nTo do that you can check the cryptography docs.\n$ pip uninstall pyopenssl\n$ pip uninstall cryptography\n$ env LDFLAGS=\"-L$(brew --prefix openssl)/lib\" CFLAGS=\"-I$(brew --prefix openssl)/include\" pip install cryptography\...
[ 0 ]
[]
[]
[ "django", "pyopenssl", "python" ]
stackoverflow_0074538243_django_pyopenssl_python.txt
Q: how to change the python version from default 3.5 to 3.8 of google colab I downloaded python version 3.8 on google colab using: !apt-get install python3.8 Now I want to change the default python version used in google colab uses from 3.6 to 3.8. how to do it?? I have read few ans but there are no updates... A: ...
how to change the python version from default 3.5 to 3.8 of google colab
I downloaded python version 3.8 on google colab using: !apt-get install python3.8 Now I want to change the default python version used in google colab uses from 3.6 to 3.8. how to do it?? I have read few ans but there are no updates...
[ "Colab has default python 3.7 and alternative 3.6 (on 26.07.2021)\n#**Add python version you wish** to list\n!sudo apt-get update -y\n!sudo apt-get install python3.8\nfrom IPython.display import clear_output \nclear_output()\n!sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.8 1\n\n# Cho...
[ 13, 5, 3, 0, 0, 0 ]
[]
[]
[ "google_colaboratory", "python" ]
stackoverflow_0063168301_google_colaboratory_python.txt
Q: How can I add new dimensions to a Numpy array? I'm starting off with a numpy array of an image. In[1]:img = cv2.imread('test.jpg') The shape is what you might expect for a 640x480 RGB image. In[2]:img.shape Out[2]: (480, 640, 3) However, this image that I have is a frame of a video, which is 100 frames long. Ide...
How can I add new dimensions to a Numpy array?
I'm starting off with a numpy array of an image. In[1]:img = cv2.imread('test.jpg') The shape is what you might expect for a 640x480 RGB image. In[2]:img.shape Out[2]: (480, 640, 3) However, this image that I have is a frame of a video, which is 100 frames long. Ideally, I would like to have a single array that conta...
[ "A dimension can be added to a numpy array as follows:\nimage = image[..., np.newaxis]\n\n", "Alternatively to \nimage = image[..., np.newaxis]\n\nin @dbliss' answer, you can also use numpy.expand_dims like\nimage = np.expand_dims(image, <your desired dimension>)\n\nFor example (taken from the link above):\nx = n...
[ 182, 97, 33, 23, 9, 3, 2, 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0017394882_arrays_numpy_python.txt
Q: How can i ignore comments in a string based on compiler design? I want to ignore every comment like { comments } and // comments. I have a pointer named peek that checks my string character by character. I know how to ignore newlines, tabs, and spaces but I don't know how to ignore comments. string = """ beGI...
How can i ignore comments in a string based on compiler design?
I want to ignore every comment like { comments } and // comments. I have a pointer named peek that checks my string character by character. I know how to ignore newlines, tabs, and spaces but I don't know how to ignore comments. string = """ beGIn west WEST north//comment1 \n north north west East east sou...
[ "Simply use global variable skip = False and set it True when you get { and set False when you get } and the rest of your if/else run in if not skip:\nstring = \"\"\" beGIn west WEST north//comment1 \\n\nnorth north west East east south\\n\n// comment west\\n\n{\\n\n comment\\n\n}\\n end\n\"\"\"\n\ntok...
[ 1, 0 ]
[]
[]
[ "compiler_construction", "lexical_analysis", "python" ]
stackoverflow_0070069741_compiler_construction_lexical_analysis_python.txt
Q: Scoping in Python 'for' loops I'm not asking about Python's scoping rules; I understand generally how scoping works in Python for loops. My question is why the design decisions were made in this way. For example (no pun intended): for foo in xrange(10): bar = 2 print(foo, bar) The above will print (9,2). Thi...
Scoping in Python 'for' loops
I'm not asking about Python's scoping rules; I understand generally how scoping works in Python for loops. My question is why the design decisions were made in this way. For example (no pun intended): for foo in xrange(10): bar = 2 print(foo, bar) The above will print (9,2). This strikes me as weird: 'foo' is rea...
[ "The likeliest answer is that it just keeps the grammar simple, hasn't been a stumbling block for adoption, and many have been happy with not having to disambiguate the scope to which a name belongs when assigning to it within a loop construct. Variables are not declared within a scope, it is implied by the locati...
[ 143, 74, 48, 3, 1, 1, 0 ]
[ "For starters, if variables were local to loops, those loops would be useless for most real-world programming.\nIn the current situation:\n# Sum the values 0..9\ntotal = 0\nfor foo in xrange(10):\n total = total + foo\nprint total\n\nyields 45. Now, consider how assignment works in Python. If loop variables were...
[ -8 ]
[ "python", "scope" ]
stackoverflow_0003611760_python_scope.txt
Q: trying to make subclass but nothing seems to work :( So i'm basicly trying to fetch some data from the duolingo api and make all the different parts accesible via a class (I think that's the best way to make the data accesible in other files?) I currently have this code: class DuoData: def __init__(self, usern...
trying to make subclass but nothing seems to work :(
So i'm basicly trying to fetch some data from the duolingo api and make all the different parts accesible via a class (I think that's the best way to make the data accesible in other files?) I currently have this code: class DuoData: def __init__(self, username): self.username = username self.URL = ...
[ "This is how you would do a subclass. A subclass means that ActiveLanguage is a specific kind of DuoData.\nHowever, in this particular case, I'm not sure that's what you want. It may be you want \"encapsulation\", where ActiveLanguage is a class that stands alone and USES an instance of DuoData to do its work.\nc...
[ 0, 0, 0 ]
[]
[]
[ "class", "oop", "python" ]
stackoverflow_0074538048_class_oop_python.txt
Q: Fill form input with Scrapy I'm trying to input a word to search products with Scrapy, this is the url = https://www.mercadolivre.com.br/ The problem is that I cant even pass the input form, recieving the following error: '[scrapy.downloadermiddlewares.retry] DEBUG: Retrying <GET https://www.mercadolivre.com.br/jm...
Fill form input with Scrapy
I'm trying to input a word to search products with Scrapy, this is the url = https://www.mercadolivre.com.br/ The problem is that I cant even pass the input form, recieving the following error: '[scrapy.downloadermiddlewares.retry] DEBUG: Retrying <GET https://www.mercadolivre.com.br/jm/search?as_word=&cb1-edit=smartph...
[ "There is no need to use the FormRequest.\nTheir search api is to just add the search term as the last path of the url.\nfor example:\nimport scrapy\n\nsearch_terms = ['smartphone', 'charger']\n\nclass Mlspider(scrapy.Spider):\n name = 'ml'\n start_urls = ['https://lista.mercadolivre.com.br/' + i for i in sea...
[ 0 ]
[]
[]
[ "python", "scrapy" ]
stackoverflow_0074535831_python_scrapy.txt
Q: How to work with MultipleCheckBox with Django? I'm new to Django and I'm trying to make an application that registers the attendance of entrepreneurs (I'm currently working on this). There are some services that I would like to select, sometimes the same person requires more than one service per appointment. Howev...
How to work with MultipleCheckBox with Django?
I'm new to Django and I'm trying to make an application that registers the attendance of entrepreneurs (I'm currently working on this). There are some services that I would like to select, sometimes the same person requires more than one service per appointment. However, part of the application uses the Models and part...
[ "It sounds like you have many Entrepreneurs, each of which can choose many Services. This is a ManyToMany Relationship and you can create it in Django by having one model for each and creating the link between them like this\nclass CadastroEmpreendedor(models.Model):\n ...\n descricao_atendimento = models.Ma...
[ 0 ]
[]
[]
[ "checkbox", "django", "django_models", "frameworks", "python" ]
stackoverflow_0074538014_checkbox_django_django_models_frameworks_python.txt
Q: How to skip a tag when using Beautifulsoup find_all? I want to edit an HTML document and parse some text using Beautifulsoup. I'm interested in <span> tags but the ones that are NOT inside a <table> element. I want to skip all tables when finding the <span> elements. I've tried to find all <span> elements first an...
How to skip a tag when using Beautifulsoup find_all?
I want to edit an HTML document and parse some text using Beautifulsoup. I'm interested in <span> tags but the ones that are NOT inside a <table> element. I want to skip all tables when finding the <span> elements. I've tried to find all <span> elements first and then filter out the ones that have <table> in any parent...
[ "The way I would approach this would be to simply remove all tables from the html before doing my find_all on span.\nHere is a thread I found on removing tables. I like the accepted answer because .extract() gives you the opportunity to capture the removed tables, though .decompose() would be better if you don't c...
[ 2, 0 ]
[]
[]
[ "beautifulsoup", "html", "python" ]
stackoverflow_0074538402_beautifulsoup_html_python.txt
Q: Failed to upload photos on FaceBook 2022 using .send_keys() with selenium python I'm trying to upload or post a image on facebook with selenium and python for that i tryed with this This is the path of the section "Add Photos/Videos": post=driver.find_element_by_xpath('//*[@id="mount_0_0_fQ"]/div/div1/div/div[4]/...
Failed to upload photos on FaceBook 2022 using .send_keys() with selenium python
I'm trying to upload or post a image on facebook with selenium and python for that i tryed with this This is the path of the section "Add Photos/Videos": post=driver.find_element_by_xpath('//*[@id="mount_0_0_fQ"]/div/div1/div/div[4]/div/div/div1/div/div[2]/div/div/div/form/div/div1/div/div/div/div[2]/div1/div[2]/div/d...
[ "if you use free fb It's easier\nfree fb\npost=driver.find_element_by_name(\"view_post\").click() \npost.send_keys(r\"G:\\PY SCRIPTS\\IMAGES\\img.png\")\n\n", "This xpath worked for me trying to upload a video:\nelement = bot.find_element(By.XPATH, '//form[contains(@method, \"POST\")]//input[contains(@accept, \"v...
[ 0, 0 ]
[]
[]
[ "facebook", "python", "selenium_webdriver", "sendkeys" ]
stackoverflow_0071058452_facebook_python_selenium_webdriver_sendkeys.txt
Q: Typehint Union Dictionary branching error I want to implement a function like the one below, but it throws a type hint warning. def test(flag: bool)->Dict[str, int]| Dict[str, str]: a: Dict[str, str]| Dict[str, int] = {} if flag: a['a'] = 1 else: a['a'] = 'hello' return post_process...
Typehint Union Dictionary branching error
I want to implement a function like the one below, but it throws a type hint warning. def test(flag: bool)->Dict[str, int]| Dict[str, str]: a: Dict[str, str]| Dict[str, int] = {} if flag: a['a'] = 1 else: a['a'] = 'hello' return post_process(a) With the following warning by Pylance: Ar...
[ "Edit:\nSince your comment outlined that you truly want the return value to be only ever a dict of strings or a dict of ints, and never a mix of both, you can use the @overload decorator to determine return types based on the boolean flag:\nfrom typing import Dict, overload, Literal\n\n\n@overload\ndef test(flag: L...
[ 1 ]
[]
[]
[ "dictionary", "python", "type_hinting" ]
stackoverflow_0074536240_dictionary_python_type_hinting.txt
Q: How to check if second value of slice() is a certain value? I have a function that takes in a slice. What I want to do is to check if the end value in this slice is equal to -1. If that is the case, I want to reset the slice to another value. I can't find supporting documentation and do not know how to proceed. da...
How to check if second value of slice() is a certain value?
I have a function that takes in a slice. What I want to do is to check if the end value in this slice is equal to -1. If that is the case, I want to reset the slice to another value. I can't find supporting documentation and do not know how to proceed. datalist=[None, 'Grey', 'EE20-700', 'EE-42-01', 'EE15-767', 'EE0-70...
[ "You could define a wrapper for slice(). Something like:\ndef nonwrapping_slice(start=0, stop=None, stride=1):\n if stop is not None and stop < 0 and stride > 0:\n stop = None\n return slice(start, stop, stride)\n\nThen you can call nonwrapping_slice(1, -1) and it will return slice(1, None, 1)\n", "s...
[ 2, 1 ]
[]
[]
[ "function", "list", "python", "slice" ]
stackoverflow_0074538403_function_list_python_slice.txt
Q: Converting int arrays to string arrays in numpy without truncation Trying to convert int arrays to string arrays in numpy In [66]: a=array([0,33,4444522]) In [67]: a.astype(str) Out[67]: array(['0', '3', '4'], dtype='|S1') Not what I intended In [68]: a.astype('S10') Out[68]: array(['0', '33', '4444522']...
Converting int arrays to string arrays in numpy without truncation
Trying to convert int arrays to string arrays in numpy In [66]: a=array([0,33,4444522]) In [67]: a.astype(str) Out[67]: array(['0', '3', '4'], dtype='|S1') Not what I intended In [68]: a.astype('S10') Out[68]: array(['0', '33', '4444522'], dtype='|S10') This works but I had to know 10 was big enough t...
[ "Again, this can be solved in pure Python:\n>>> map(str, [0,33,4444522])\n['0', '33', '4444522']\n\nOr if you need to convert back and forth:\n>>> a = np.array([0,33,4444522])\n>>> np.array(map(str, a))\narray(['0', '33', '4444522'], \n dtype='|S7')\n\n", "You can stay in numpy, doing\nnp.char.mod('%d', a)\n...
[ 53, 50, 16, 3, 0, 0 ]
[]
[]
[ "arrays", "numpy", "python", "string" ]
stackoverflow_0009958846_arrays_numpy_python_string.txt
Q: Is it possible to recursively traverse nested data classes \ convert them to a nested dictionary without expanding some types of dataclasses? I have a nested set of dataclasses that I want to convert to a dictionary however, some classes should remain as a class, and not be converted to a dataclass (the full struc...
Is it possible to recursively traverse nested data classes \ convert them to a nested dictionary without expanding some types of dataclasses?
I have a nested set of dataclasses that I want to convert to a dictionary however, some classes should remain as a class, and not be converted to a dataclass (the full structure is deeper and more complex) in this example: from dataclasses import dataclass, field, asdict @dataclass class C: x: int = 1 @dataclass c...
[ "Although dataclasses.asdict allows for a \"dict_factory\" parameter, its use is limited, as it is only called for pairs of name/value for each field recursively, but \"depth first\": meaning all dataclass values are already serialized to a dict when the custom factory is called.\nSo, it is very hard to customize a...
[ 1 ]
[]
[]
[ "python", "python_dataclasses" ]
stackoverflow_0074535848_python_python_dataclasses.txt
Q: How do I perform query filtering in django templates I need to perform a filtered query from within a django template, to get a set of objects equivalent to python code within a view: queryset = Modelclass.objects.filter(somekey=foo) In my template I would like to do {% for object in data.somekey_set.FILTER %} b...
How do I perform query filtering in django templates
I need to perform a filtered query from within a django template, to get a set of objects equivalent to python code within a view: queryset = Modelclass.objects.filter(somekey=foo) In my template I would like to do {% for object in data.somekey_set.FILTER %} but I just can't seem to find out how to write FILTER.
[ "You can't do this, which is by design. The Django framework authors intended a strict separation of presentation code from data logic. Filtering models is data logic, and outputting HTML is presentation logic.\nSo you have several options. The easiest is to do the filtering, then pass the result to render_to_re...
[ 137, 50, 13, 12, 9, 1, 0 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0000223990_django_django_templates_python.txt
Q: generate a set of of all combinations of special characters and numbers around a string - python I am attempting to generate all combinations of special characters and numbers around a string. For example, suppose the string is 'notebook' and the special characters are @, #, $, %, & and numbers 0-9. This could g...
generate a set of of all combinations of special characters and numbers around a string - python
I am attempting to generate all combinations of special characters and numbers around a string. For example, suppose the string is 'notebook' and the special characters are @, #, $, %, & and numbers 0-9. This could generate: $#notebook12, notebook8, @5notebook0&. I am assuming no repeats of characters. Thanks in ad...
[ "Try this:\nfrom itertools import combinations, permutations\n\nresult = [\n ''.join(p)\n for n_chars in range(len(special) + 1)\n for chars in combinations(special, n_chars)\n for p in permutations(('notebook',) + chars)\n]\n\nExample with special = ['@','#','$']:\n['notebook', 'notebook@', '@notebook'...
[ 3, 2, 2, 1 ]
[]
[]
[ "combinations", "permutation", "python" ]
stackoverflow_0074536936_combinations_permutation_python.txt
Q: Assign involving both reducing & non-reducing operations in Pandas I'm an R/Tidyverse guy getting my feet wet in python/pandas and having trouble discerning if there is a way to do the following as elegantly in pandas as tidyverse: ( dat %>% group_by(grp) %>% mutate( value = value/max(value) ...
Assign involving both reducing & non-reducing operations in Pandas
I'm an R/Tidyverse guy getting my feet wet in python/pandas and having trouble discerning if there is a way to do the following as elegantly in pandas as tidyverse: ( dat %>% group_by(grp) %>% mutate( value = value/max(value) ) ) So, there's a grouped mutate that involves a non-reducing operati...
[ "For this specific case, a transform is a better fit, and should be more performant than apply:\ndf.assign(value = df.value/df.groupby('grp').value.transform('max'))\n grp value\n1 0 1.000000\n2 1 -0.290494\n3 1 1.000000\n4 1 0.214848\n6 2 8.242604\n7 2 1.000000\n8 2 1.156246\n0 ...
[ 2, 1 ]
[]
[]
[ "pandas", "python", "tidyverse" ]
stackoverflow_0074536116_pandas_python_tidyverse.txt
Q: XPath get one attribute or another? I have a Python XML XPath expression ancestor-or-self::*[@foo]/@foo, and I need to modify it to get attribute @foo if it exists otherwise get attribute @bar. I've tried to use or operator similar to condition like [@foo or @bar], but got an expression error. A: XPath 1.0 For a...
XPath get one attribute or another?
I have a Python XML XPath expression ancestor-or-self::*[@foo]/@foo, and I need to modify it to get attribute @foo if it exists otherwise get attribute @bar. I've tried to use or operator similar to condition like [@foo or @bar], but got an expression error.
[ "XPath 1.0\nFor a correct XPath_Prefix, this XPath,\n\nXPath_Prefix/@*[name()='foo' or name()='bar'][1]\n\nwill select the foo attribute if available; otherwise, the bar attribute.\n" ]
[ 2 ]
[]
[]
[ "elementtree", "python", "xml", "xpath" ]
stackoverflow_0074538241_elementtree_python_xml_xpath.txt
Q: How to add or remove hairs from a hair curve in Blender Python (bpy) I am trying to write my own scripts for working with hair in blender. I can already modify the position of points on a blender hair curve object like this: bpy.data.objects["HairCurves"].data.curves[0].points[0].position = (1., 1., 1.) But how c...
How to add or remove hairs from a hair curve in Blender Python (bpy)
I am trying to write my own scripts for working with hair in blender. I can already modify the position of points on a blender hair curve object like this: bpy.data.objects["HairCurves"].data.curves[0].points[0].position = (1., 1., 1.) But how can I add or remove curves and points from this hair_curve object? I have t...
[ "Follow this: [https://developer.blender.org/T68981]\nNote that the box next to the Python API is not checked yet.\n" ]
[ 1 ]
[]
[]
[ "blender", "bpy", "python" ]
stackoverflow_0074526682_blender_bpy_python.txt
Q: How ensure subprocess is killed on timeout when using `run`? I am using the following code to launch a subprocess : # Run the program subprocess_result = subprocess.run( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False, ...
How ensure subprocess is killed on timeout when using `run`?
I am using the following code to launch a subprocess : # Run the program subprocess_result = subprocess.run( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False, timeout=timeout, cwd=directory, e...
[ "The most likely culprit for the behaviour you see is that the subprocess you are spawning is probably using multiprocessing and spawning its own child processes. Killing the parent process does not automatically kill the whole set of descendants. The granchildren are inherited by the init process (i.e. the process...
[ 0 ]
[]
[]
[ "kill_process", "python", "subprocess" ]
stackoverflow_0074524193_kill_process_python_subprocess.txt
Q: Why is plotly express so much more performant than plotly graph_objects? I'm visualizing a scatterplots with between 400K and 2.5M points. I expectected to need to downsample before visualizing but to see just how much I ran a pilot test with a 400k dataset in plotly express, and the plot popped up quickly, beaut...
Why is plotly express so much more performant than plotly graph_objects?
I'm visualizing a scatterplots with between 400K and 2.5M points. I expectected to need to downsample before visualizing but to see just how much I ran a pilot test with a 400k dataset in plotly express, and the plot popped up quickly, beautifully, and responsively. In order to make the interractive figure I really ne...
[ "Running the following simple example:\nimport numpy as np\nimport plotly.graph_objects as go\nimport plotly.express as px\n\nx = np.linspace(-2, 2, 100000)\ny = np.cos(x)\n\nfig = go.Figure(data=[go.Scatter(x=x, y=y)])\nfig2 = px.scatter(x=x, y=y)\n\ntype(fig.data[0]), type(fig2.data[0])\n# out: (plotly.graph_objs...
[ 3 ]
[]
[]
[ "plotly", "plotly_express", "python" ]
stackoverflow_0074536056_plotly_plotly_express_python.txt
Q: How to generate a unique name for each uploaded file? I am building a Flask website, and I want to save a path of a file to my sqlite database I have a "create" view, where user uploads an image and it gets stored in a folder @app.route('/create', methods = ["GET", "POST"]) @login_required def create(): ...
How to generate a unique name for each uploaded file?
I am building a Flask website, and I want to save a path of a file to my sqlite database I have a "create" view, where user uploads an image and it gets stored in a folder @app.route('/create', methods = ["GET", "POST"]) @login_required def create(): if request.method == "POST": file = request.files['fi...
[ "An easy way to generate a unique file name would be to just use a numbering system (first file being 1, then increasing by 1). Like so:\n counter = 0 #put this at the beginning of your script\n\nthen when creating file name:\n counter += 1\n filename = counter\n\nIf you do not want your files to be named jus...
[ 1 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0074538676_flask_python.txt
Q: How do I control where pip3 installs packages? I updated pip3 and now packages are being installed for python 3.8 and not 3.9. What do I do to make it so that packages are installed to where they used to be installed? I updated pip3 today using the command pip3 install --upgrade pip and then installed a new packag...
How do I control where pip3 installs packages?
I updated pip3 and now packages are being installed for python 3.8 and not 3.9. What do I do to make it so that packages are installed to where they used to be installed? I updated pip3 today using the command pip3 install --upgrade pip and then installed a new package with pip3 install statsmodels which did indeed ins...
[ "If you want to change your default installation target\nThe --target switch is the thing you're looking for:\npip config set global.target /Users/Bob/Library/Python/3.8/lib/python/site-packages\n\nInstalls packages into directory provied. By default this will not replace existing files/folders in the directory. Us...
[ 0 ]
[]
[]
[ "pip", "python" ]
stackoverflow_0074538632_pip_python.txt
Q: Using Tweepy and Twitter API v2 to retrieve replies from a single Tweet I'm currently trying to generate the replies for a single tweet, but can't retrieve all of them. While it works to retrieve some, adding .flatten(limit=1000) breaks my code and will return an error. I need to return all replies from a single t...
Using Tweepy and Twitter API v2 to retrieve replies from a single Tweet
I'm currently trying to generate the replies for a single tweet, but can't retrieve all of them. While it works to retrieve some, adding .flatten(limit=1000) breaks my code and will return an error. I need to return all replies from a single tweet and am using paginator to do so, but for some reason am only seeing 6 re...
[ "It's a small issue with your code. In the for loop you are overwriting the tweets and users lists with each pass instead of appending to it. Corrected loop:\nq = 'conversation_id:XXX'\ntweets = []\nusers = []\n\nfor tweet_batch in tweepy.Paginator(client.search_recent_tweets, query=q,\n ...
[ 0 ]
[]
[]
[ "paginator", "python", "tweepy", "twitter" ]
stackoverflow_0073085747_paginator_python_tweepy_twitter.txt
Q: Splitting a txt file into indiviudal words andwriting them to a new txt file I wanted to take a txt file that is formatted as such: apple banana peach pear (item then space then next item) and then print it so that it prints as: apple banana peach pear At the same time, it has to write to the file called output...
Splitting a txt file into indiviudal words andwriting them to a new txt file
I wanted to take a txt file that is formatted as such: apple banana peach pear (item then space then next item) and then print it so that it prints as: apple banana peach pear At the same time, it has to write to the file called output.txt in the same manner (each word on a new line). My code so far as is follows an...
[ "Your code has a lot of small mistakes:\ndef task_2():\n in_file = open(\"input.txt\", \"r\") # this is better with a context manager\n out_file = open(\"output.txt\", \"w\")\n line = in_file.line() # .line() does not exist, you wanted .readline()\n words = line.strip() # you want .split() here\n ...
[ 0 ]
[]
[]
[ "object", "python" ]
stackoverflow_0074538694_object_python.txt
Q: How to annotate grouped bars with group count instead of bar height To draw plot, I am using seaborn and below is my code import seaborn as sns sns.set_theme(style="whitegrid") tips = sns.load_dataset("tips") tips=tips.head() ax = sns.barplot(x="day", y="total_bill",hue="sex", data=tips, palette="tab20_r") I wa...
How to annotate grouped bars with group count instead of bar height
To draw plot, I am using seaborn and below is my code import seaborn as sns sns.set_theme(style="whitegrid") tips = sns.load_dataset("tips") tips=tips.head() ax = sns.barplot(x="day", y="total_bill",hue="sex", data=tips, palette="tab20_r") I want to get and print frequency of data plots that is no. of times it occur...
[ "\nHow to display custom values on a bar plot does not clearly show how to annotate grouped bars, nor does it show how to determine the frequency of each hue category for each day.\nHow to plot and annotate grouped bars in seaborn / matplotlib shows how to annotate grouped bars, but not with custom labels.\nfor rec...
[ 1 ]
[]
[]
[ "grouped_bar_chart", "matplotlib", "pandas", "python", "seaborn" ]
stackoverflow_0074524083_grouped_bar_chart_matplotlib_pandas_python_seaborn.txt
Q: Check if inputed date is under 18 How can I check with a inputed date if that date of birthday is under 18? year=int(input("Year born: ")) month = int(input("Month born: ")) day = int(input("Day born: ")) date = date(year,month,day) What code can I use with date.today() in order to check if user is under 18? Beca...
Check if inputed date is under 18
How can I check with a inputed date if that date of birthday is under 18? year=int(input("Year born: ")) month = int(input("Month born: ")) day = int(input("Day born: ")) date = date(year,month,day) What code can I use with date.today() in order to check if user is under 18? Because if I substract 2022- year it could ...
[ "You can compare all date parts sequentially:\nfrom datetime import date\n\ndef is_under_18(birth):\n now = date.today()\n return (\n now.year - birth.year < 18\n or now.year - birth.year == 18 and (\n now.month < birth.month \n or now.month == birth.month and now.day <= bi...
[ 0 ]
[]
[]
[ "date", "python" ]
stackoverflow_0074538629_date_python.txt
Q: How to assign array in a dataframe to a variable I need to fetch my array field in dataframe and assign it to a variable for further proceeding further. I am using collect() function, but its not working properly. Input dataframe: Department Language [A, B, C] English [] Spanish How can i fetch and assign vari...
How to assign array in a dataframe to a variable
I need to fetch my array field in dataframe and assign it to a variable for further proceeding further. I am using collect() function, but its not working properly. Input dataframe: Department Language [A, B, C] English [] Spanish How can i fetch and assign variable like below: English = [A,B,C] Spanish =...
[ "The simplest solution I came with is just extracting data with collect and explicitly assigning it to the predefined variables, like so:\nfrom pyspark.sql.types import StringType, ArrayType, StructType, StructField\n\nschema = StructType([\n StructField(\"Department\", ArrayType(StringType()), True),\n Struc...
[ 2, 1 ]
[]
[]
[ "function", "pyspark", "python" ]
stackoverflow_0074538022_function_pyspark_python.txt
Q: How to search through an array of integers and strings and return the name and score of the highest competitor - python 3.10 this will probably be comically simple but I can't figure out the answer basically have to search through a 2d array something that I can't remember what I have figured out doesn't help so w...
How to search through an array of integers and strings and return the name and score of the highest competitor - python 3.10
this will probably be comically simple but I can't figure out the answer basically have to search through a 2d array something that I can't remember what I have figured out doesn't help so was looking for some help the code I have is as follows: competitors = [["John", 11], ["Jenny", 13], ["Matthew", 3], ["Bev", 22], [...
[ "The max() function can take an optional key argument that lets you specify what python should be looking specifically to determine the maximum value, especially helpful when you have complex objects and you need to determine whether the max is the alphabetical sort of the name as a string (for example), or the top...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074538873_python.txt
Q: Python Error (TypeError: 'pygame.Surface' object is not callable) I have a problem with python when creating functions with images here is the code: This usually happens when creating classes with a function I want to run that displays an image to the screen. import pygame white = (255,255,255) width,height = 800...
Python Error (TypeError: 'pygame.Surface' object is not callable)
I have a problem with python when creating functions with images here is the code: This usually happens when creating classes with a function I want to run that displays an image to the screen. import pygame white = (255,255,255) width,height = 800,500 win = pygame.display.set_mode((width,height)) pygame.display.set_c...
[ "class Game:\n def __init__(self):\n self.player = pygame.image.load(\"graphics/player/player.png\")\n def player(self):\n win.blit(self.player, (0,0))\n pygame.display.update()\n\n__init__() defines an attribute named self.player.\nThere is also a class instance method named player.\nYou...
[ 0 ]
[]
[]
[ "error_handling", "python" ]
stackoverflow_0074538734_error_handling_python.txt
Q: Stop canvas from leaving frame tkinter I am trying to create pong and i have basic movement of the paddle, but how would you go about keeping the paddle on the screen? I have tried to read the cords and only allowing moment if cords is less then a certain amount, but the cords stay the same no matter the actual po...
Stop canvas from leaving frame tkinter
I am trying to create pong and i have basic movement of the paddle, but how would you go about keeping the paddle on the screen? I have tried to read the cords and only allowing moment if cords is less then a certain amount, but the cords stay the same no matter the actual position of the paddle. Thoughts? import tkint...
[ "Just adding conditionals that check pongMovement seems to do it:\nimport tkinter as tk\n\nypong = 0\n\n\ndef keyup(e):\n global pongMovement\n global pongEdit\n global Pong\n if pongMovement > 0:\n pongMovement = pongMovement - 10\n pongEdit.place(x=1, y=pongMovement)\n pongEdit.up...
[ 0 ]
[]
[]
[ "python", "tkinter", "tkinter_canvas" ]
stackoverflow_0074538852_python_tkinter_tkinter_canvas.txt
Q: How to use pandas.dataframe.corr with only a specific number of columns? Let's say for example I have a dataset with 1000 rows, and 10 variables: Now, let's say I want to calculate the correlation between the first 4 variables... How would I go about doing this? import pandas as pd df = pd.read_csv('random_data.cs...
How to use pandas.dataframe.corr with only a specific number of columns?
Let's say for example I have a dataset with 1000 rows, and 10 variables: Now, let's say I want to calculate the correlation between the first 4 variables... How would I go about doing this? import pandas as pd df = pd.read_csv('random_data.csv') df.corr()[0:4] This code I have calculates the correlation between the fi...
[ "To do this you want to use a subset of the dataframe that contains only the columns you want.\ndf[['col1', 'col2', 'col3', 'col4']].corr()\nOR\ndf.iloc[:, :4].corr() to select first 4 columns\n" ]
[ 2 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074538936_dataframe_pandas_python.txt
Q: Handling try except multiple times while web scraping BeautifulSoup while web scraping using BeautifulSoup I have to write try except multiple times. See the code below: try: addr1 = soup.find('span', {'class' : 'addr1'}).text except: addr1 = '' try: addr2 = soup.find('span', {'class' : 'addr2'}).text...
Handling try except multiple times while web scraping BeautifulSoup
while web scraping using BeautifulSoup I have to write try except multiple times. See the code below: try: addr1 = soup.find('span', {'class' : 'addr1'}).text except: addr1 = '' try: addr2 = soup.find('span', {'class' : 'addr2'}).text except: addr2 = '' try: city = soup.find('strong', {'class' : '...
[ "Use a for loop that iterates through a sequence containing your arguments. Then use a conditional statement that checks if the return value is None, prior to attempting to get the text attribute. Then store the results in a dictionary. This way there is no need to use try/except at all.\nseq = [('span', 'addr1'...
[ 0 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0074538717_beautifulsoup_python.txt
Q: How to send push notifications to iOS using a python api I have create a webscraper that sends notifications to my phone whenever certain events are detected. So far I have achieved this by sending emails through the sendgrid api. Its a pretty nice service, and it is free, but it clutters up the mailbox quite a bi...
How to send push notifications to iOS using a python api
I have create a webscraper that sends notifications to my phone whenever certain events are detected. So far I have achieved this by sending emails through the sendgrid api. Its a pretty nice service, and it is free, but it clutters up the mailbox quite a bit. In stead I’d like to send messages directly to the iOS noti...
[ "Maybe you should check out pushover.net. They have a simple WebAPI to send customized notifications to iOS devices.\nSee https://support.pushover.net/i44-example-code-and-pushover-libraries#python for code samples.\n" ]
[ 1 ]
[]
[]
[ "iphone", "push_notification", "python" ]
stackoverflow_0074538831_iphone_push_notification_python.txt
Q: How to use python output as input for next step in argo workflow? Based on the last line of the output of a python script (I cannot adapt the output-format) I want to trigger multiple new steps in argo-wf. How can I ignore all output lines except the last one in below example? I cannot adapt thy python-code so I g...
How to use python output as input for next step in argo workflow?
Based on the last line of the output of a python script (I cannot adapt the output-format) I want to trigger multiple new steps in argo-wf. How can I ignore all output lines except the last one in below example? I cannot adapt thy python-code so I guess I have to include an additional step to exclude all lines except l...
[ "I never got the\ncommand: [ python ]\nsource |\n import json\n\nto work, however, this works for me:\n command: [ python, -c ]\n args: &script\n - |\n import json\n\n" ]
[ 0 ]
[]
[]
[ "argo", "python" ]
stackoverflow_0074275358_argo_python.txt
Q: How to add python version as environment variable in poetry? I have created a simple django project using poetry in my local machine , the pyproject.toml is the following [tool.poetry] name = "vending-machine-api" version = "0.1.0" description = "" authors = ["mohamed ibrahim"] readme = "README.md" packages = [{in...
How to add python version as environment variable in poetry?
I have created a simple django project using poetry in my local machine , the pyproject.toml is the following [tool.poetry] name = "vending-machine-api" version = "0.1.0" description = "" authors = ["mohamed ibrahim"] readme = "README.md" packages = [{include = "vending_machine_api"}] [tool.poetry.dependencies] python...
[ "It's not using an environment variable like you asked, but this solved the issue of incompatibility:\npython = \">=3.9,<3.11\"\n\nto add a range of compatible python versions\n" ]
[ 1 ]
[]
[]
[ "django", "pip", "python", "python_poetry" ]
stackoverflow_0074539017_django_pip_python_python_poetry.txt
Q: applying function to list of dataframes in python beginner python question here that I've had struggles getting answered from related stack questions. I've got a list dfList = df0,df1,df2,...,df7 I've got a function that I've defined and takes a dataframe as its argument. I'm not sure the function itself matters,...
applying function to list of dataframes in python
beginner python question here that I've had struggles getting answered from related stack questions. I've got a list dfList = df0,df1,df2,...,df7 I've got a function that I've defined and takes a dataframe as its argument. I'm not sure the function itself matters, but to be safe it is basically def rateCalc (outcomeDa...
[ "I think it is because the assing function returns another Data Frame which only exists inside the function scope, here is an example\nimport pandas as pd\ndf_0 = pd.DataFrame(data = [{'column':'a'}])\ndf_1 = pd.DataFrame(data = [{'column':'c'}])\ndf_2 = pd.DataFrame(data = [{'column':'d'}])\ndf_altos = df_0,df_1,d...
[ 1 ]
[]
[]
[ "apply", "dataframe", "list", "pandas", "python" ]
stackoverflow_0074538258_apply_dataframe_list_pandas_python.txt
Q: How to optimize reading and cleaning file? I have a file, which contains strings separated by spaces, tabs and carriage return: one two three four I'm trying to remove all spaces, tabs and carriage return: def txt_cleaning(fname): with open(fname) as f: new_txt = [] fname = f.r...
How to optimize reading and cleaning file?
I have a file, which contains strings separated by spaces, tabs and carriage return: one two three four I'm trying to remove all spaces, tabs and carriage return: def txt_cleaning(fname): with open(fname) as f: new_txt = [] fname = f.readline().strip() new_txt += [line.split...
[ "def txt_cleaning(fname):\n new_text = []\n with open(fname) as f:\n for line in f.readlines():\n new_text += [s.strip() for s in line.split() if s]\n return new_text\n\nOr\ndef txt_cleaning(fname):\n with open(fname) as f:\n return [word.strip() for word in f.read().split() if ...
[ 2, 0 ]
[]
[]
[ "file", "python", "txt" ]
stackoverflow_0074537382_file_python_txt.txt
Q: String-based enum in Python To encapsulate a list of states I am using enum module: from enum import Enum class MyEnum(Enum): state1='state1' state2 = 'state2' state = MyEnum.state1 MyEnum['state1'] == state # here it works 'state1' == state # here it does not throw but returns False (fail!) However,...
String-based enum in Python
To encapsulate a list of states I am using enum module: from enum import Enum class MyEnum(Enum): state1='state1' state2 = 'state2' state = MyEnum.state1 MyEnum['state1'] == state # here it works 'state1' == state # here it does not throw but returns False (fail!) However, the issue is that I need to seam...
[ "It seems that it is enough to inherit from str class at the same time as Enum:\nfrom enum import Enum\n\nclass MyEnum(str, Enum):\n state1 = 'state1'\n state2 = 'state2'\n\nThe tricky part is that the order of classes in the inheritance chain is important as this:\nclass MyEnum(Enum, str):\n state1 = 'sta...
[ 116, 60, 4, 4, 1, 1, 0 ]
[ "Simply use .value :\nMyEnum.state1.value == 'state1'\n# True\n\n" ]
[ -1 ]
[ "enums", "python", "python_3.x", "string" ]
stackoverflow_0058608361_enums_python_python_3.x_string.txt
Q: Populate dataframe by unnesting list of the first column I have the following issue with a csv in panda the data looks as follow : Column A :row1: [« a », « b »; « c » Row2 : [« d »; « e », « f » Etc … Note the different delimiters. I would like it to populate next column based on the cell keys in the list in it ...
Populate dataframe by unnesting list of the first column
I have the following issue with a csv in panda the data looks as follow : Column A :row1: [« a », « b »; « c » Row2 : [« d »; « e », « f » Etc … Note the different delimiters. I would like it to populate next column based on the cell keys in the list in it like this : ColA row 1: [a] col b:[b] colc[c] Row 2: [d] co...
[ "I'm not sure I understand your I/O but you can try this :\nimport pandas as pd\n\ndf= (\n pd.read_csv(\"test.txt\", sep=\"[;,]\", engine=\"python\",\n header=None, skiprows=1)\n .astype(str).apply(lambda x: x.str.strip(\"« »\"))\n )\n\n# convert the numeric index columns to ...
[ 0 ]
[]
[]
[ "dataframe", "delimiter", "list", "pandas", "python" ]
stackoverflow_0074538750_dataframe_delimiter_list_pandas_python.txt
Q: Get Pyrebase HTTPError information Using the pyrebase wrapper for Firebase Authentication, when attempting to create a new user that is already a user pyrebase wraps the google API response in an HTTPError message. But when I try to capture this exception it doesn't recognize HTTPError as an exception. I can acces...
Get Pyrebase HTTPError information
Using the pyrebase wrapper for Firebase Authentication, when attempting to create a new user that is already a user pyrebase wraps the google API response in an HTTPError message. But when I try to capture this exception it doesn't recognize HTTPError as an exception. I can access the exception by using expect Exceptio...
[ "json.loads(e.args[1])['error']['message']\n\nthis will give you as a result : EMAIL_EXISTS\n", "For your case, try it, with firebase-admin==6.0.0:\nimport firebase_admin\n\ntry:\n user = auth.create_user_with_email_and_password('myemail@email.com', 'mypassword')\nexcept firebase_admin._auth_utils.EmailAlready...
[ 3, 0 ]
[]
[]
[ "flask", "pyrebase", "python" ]
stackoverflow_0061627506_flask_pyrebase_python.txt
Q: pyinstaller command not found I am using Ubuntu on VirtualBox. How do I add pyinstaller to the PATH? The issue is when I say pyinstaller file.py it says pyinstaller command not found It says it installed correctly, and according to other posts, I think it has, but I just can't get it to work. I ran: pip install ...
pyinstaller command not found
I am using Ubuntu on VirtualBox. How do I add pyinstaller to the PATH? The issue is when I say pyinstaller file.py it says pyinstaller command not found It says it installed correctly, and according to other posts, I think it has, but I just can't get it to work. I ran: pip install pyinstaller and pyinstaller file....
[ "You can use the following command if you do not want to create additional python file. \npython -m PyInstaller myscript.py\n\n", "There is another way to use pyinstaller using it as a Python script.\nThis is how I did it, go through pyinstaller's documentation\nCreate a Python script named setup.py or whatever y...
[ 52, 3, 3, 3, 0, 0 ]
[]
[]
[ "executable", "pyinstaller", "python", "python_3.x" ]
stackoverflow_0053798660_executable_pyinstaller_python_python_3.x.txt
Q: How to fix "NameError: name 'api' is not defined" Tweepy.py The Error " Traceback (most recent call last): File "/home/dcaus/tweet-custom-label.py", line 16, in <module> api.update_with_media(filename, status, in_reply_to_status_id = in_reply_to_status_id) NameError: name 'api' is not defined " My code impo...
How to fix "NameError: name 'api' is not defined" Tweepy.py
The Error " Traceback (most recent call last): File "/home/dcaus/tweet-custom-label.py", line 16, in <module> api.update_with_media(filename, status, in_reply_to_status_id = in_reply_to_status_id) NameError: name 'api' is not defined " My code import tweepy # Authenticate to Twitter auth = tweepy.OAuthHandler(...
[ "After you set up authentication, you need to create an API object. You're missing something like\napi = tweepy.API(auth, wait_on_rate_limit=True)\n\n" ]
[ 0 ]
[]
[]
[ "python", "tweepy" ]
stackoverflow_0074539099_python_tweepy.txt
Q: more efficient ways other than itterrows() on my code? this code is taking forever to run given i have 1million rows and 43 columns. the idea of it is try and find pairs which have the same values for a specific number of columns but the 'CA' column must be opposite and we remove this pair as they will be consider...
more efficient ways other than itterrows() on my code?
this code is taking forever to run given i have 1million rows and 43 columns. the idea of it is try and find pairs which have the same values for a specific number of columns but the 'CA' column must be opposite and we remove this pair as they will be considered reversing rows. i.e I have a dataframe = df Column A ...
[ "Here is my solution. The idea is to have an additional structure to quickly find opposite pairs and create a boolean mask for filtering instead of calling drop() in a loop.\nimport pandas as pd\n\ndata = pd.DataFrame(\n [\n [\"Brown\", \"Bottle\", 1234555, 100],\n [\"yellow\", \"Cup\", 1234555, 80...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "performance", "python" ]
stackoverflow_0074526965_dataframe_pandas_performance_python.txt
Q: What is wrong with this isPrime function? I'm making an isPrime function. Any odd number that I put in (unless it's 1, 2 or 3, which break it) says that it is prime even when they clearly aren't. from even import * num = input("What number? ") def isPrime(n): n = int(n) if isEven(n): return False ...
What is wrong with this isPrime function?
I'm making an isPrime function. Any odd number that I put in (unless it's 1, 2 or 3, which break it) says that it is prime even when they clearly aren't. from even import * num = input("What number? ") def isPrime(n): n = int(n) if isEven(n): return False i = 2 while i < n: a = n / i i...
[ "Here is what you meant to type. This is not the best way, but this is parallel to the approach you were taking:\ndef isEven(num):\n return num % 2 == 0\n\ndef isPrime(n):\n if isEven(n):\n return False\n\n for i in range(2,n//2):\n if n % i != 0:\n return False\n return True\n...
[ 1 ]
[]
[]
[ "primes", "python" ]
stackoverflow_0074539008_primes_python.txt
Q: I am stuck trying to create a script for reading a txt file I am trying to create a script for reading a txt file and calculating data The purpose of creating this is to read a txt file with data such as John Smith 11/18/2022 9:33 7.96 Chris Rock 11/19/2022 9:31 8.64 Jane Doe 11/12/2022 10:08 7.6 John Smith ...
I am stuck trying to create a script for reading a txt file
I am trying to create a script for reading a txt file and calculating data The purpose of creating this is to read a txt file with data such as John Smith 11/18/2022 9:33 7.96 Chris Rock 11/19/2022 9:31 8.64 Jane Doe 11/12/2022 10:08 7.6 John Smith 11/9/2022 12:18 5.28 I am curious how I can create objects with ...
[]
[]
[ "The simplest way would be to create a dictionary with names as keys, and hours as values.\nYou could do something like:\nhours_dict = {}\n\n\nwith open('myfile.txt', 'r') as myfile:\n for line in myfile:\n # parse the line to extract the name and hours\n name = ...\n hours = ...\n\n ...
[ -1 ]
[ "python" ]
stackoverflow_0074538969_python.txt
Q: Python Regular Expression matching extra characters So I might be misunderstanding how this works, but I can't figure it out. I have a string in python that has some text info and then contains a bunch of ip addresses in parenthesis followed by newline. So "(192.168.2.101)\n(192.168.2.102)\n(192.168.2.103)\n..." ...
Python Regular Expression matching extra characters
So I might be misunderstanding how this works, but I can't figure it out. I have a string in python that has some text info and then contains a bunch of ip addresses in parenthesis followed by newline. So "(192.168.2.101)\n(192.168.2.102)\n(192.168.2.103)\n..." What I want to do is re to get a list of all the differen...
[ "You can match a sequence of digits followed by )\\n.\nips = \"(192.168.2.101)\\n(192.168.2.102)\\n(192.168.2.103)\\n...\"\nre.findall(r'\\d+(?=\\)\\n)', ips)\n\n(?=\\)\\n) is a lookahead that constrains the match to be followed by close paren and newline.\n" ]
[ 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074539201_python_regex.txt
Q: cannot access global variable after trying to modify it inside a function I encounter no problems running this code: x = 1 def func(): print(x + 1) func() 2 But when I run this: x = 1 def func(): try: x += 1 except: pass print(x + 1) func() An error pops: UnboundLocalError: c...
cannot access global variable after trying to modify it inside a function
I encounter no problems running this code: x = 1 def func(): print(x + 1) func() 2 But when I run this: x = 1 def func(): try: x += 1 except: pass print(x + 1) func() An error pops: UnboundLocalError: cannot access local variable 'x' where it is not associated with a value I am n...
[ "The first example works because the function does not assign to the x variable; it only reads the variable.\nThe second example fails because if a function assigns to a variable then it is assumed to be a local variable, even if there is a global variable of the same name.\nIf you want to use the global variable i...
[ 0 ]
[]
[]
[ "function", "local", "python", "scope", "variables" ]
stackoverflow_0074539222_function_local_python_scope_variables.txt
Q: Spark: Count occurrence of each word for each column of a dataframe I have a pyspark dataframe with some columns. I want to count the occurrence of each word for each column of the dataframe. I can count the word using the group by query, but I need to figure out how to get this detail for each column using only a...
Spark: Count occurrence of each word for each column of a dataframe
I have a pyspark dataframe with some columns. I want to count the occurrence of each word for each column of the dataframe. I can count the word using the group by query, but I need to figure out how to get this detail for each column using only a single query. I have attached a sample data frame for reference and expe...
[ "Data\ndf =spark.createDataFrame([\n('1' , 'null' , ''),\n('1' , '' , 'null'),\n('1' ,'0' , '0'),\n('1' , '1' , 'null'),\n('1' , '1' , '0'),\n('null' ,'1' , '0'),\n('' , '1' , ''),\n('0' , '1' , '1'),\n('' , '1' , '1')],\n('Ratings', 'Vo...
[ 0 ]
[]
[]
[ "apache_spark", "databricks", "pyspark", "python" ]
stackoverflow_0074538581_apache_spark_databricks_pyspark_python.txt
Q: Python: using join on a list , output has brackets I feel like its probably a simple solution but I can’t seem to figure it out and my google-fu is failing me. currently, I’m consuming data from a CSV file, I then read each line and append to a list. I then use join to combine them all but the output is separated ...
Python: using join on a list , output has brackets
I feel like its probably a simple solution but I can’t seem to figure it out and my google-fu is failing me. currently, I’m consuming data from a CSV file, I then read each line and append to a list. I then use join to combine them all but the output is separated by brackets. What am I missing here? Code: data_file = c...
[ "row evaluates as a list even if it is only a list of 1 in your case, so the first thing you need to do is convert row to a string before appending it to ip_addr. Then, as pointed out by @wrbp you only need to join the (now) string contents of ip_addr:\ndata_file = csv.reader(open(\"data.csv\",\"r\"))\nip_addr=[]\...
[ 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074539110_list_python.txt
Q: Scrollable window Tkinter We created a browser on tkinter with a first window asking the user to enter criteria for a research. But for the results window, we have a problem. We can't scroll down on the window, even if there is more results below. How can we add a scroll bar? We tried this: We tried this: result_w...
Scrollable window Tkinter
We created a browser on tkinter with a first window asking the user to enter criteria for a research. But for the results window, we have a problem. We can't scroll down on the window, even if there is more results below. How can we add a scroll bar? We tried this: We tried this: result_window = Tk() result_window....
[ "You can try this:\nresult_window = Tk()\n result_window.geometry(\"1080x600\")\n result_window.minsize(480,360)\n my_canvas= Canvas(result_window)\n my_canvas.pack(side=LEFT, fill=BOTH, expand=1)\n swin = ttk.Scrollbar(result_window, orient=VERTICAL, command=my_canvas.yview)\n swin.pack(side=RIGH...
[ 0 ]
[]
[]
[ "interface", "python", "scrollbar", "tkinter", "window" ]
stackoverflow_0074534933_interface_python_scrollbar_tkinter_window.txt
Q: Find all combinations that add up to given number python with list of lists I've seen plenty of threads on how to find all combinations that add up to a number with one list, but wanted to know how to expand this such that you can only pick one number at a time, from a list of lists Question: You must select 1 num...
Find all combinations that add up to given number python with list of lists
I've seen plenty of threads on how to find all combinations that add up to a number with one list, but wanted to know how to expand this such that you can only pick one number at a time, from a list of lists Question: You must select 1 number from each list, how do you find all combinations that sum to N? Given: 3 list...
[ "My solution\nSo my attempt with Branch&Bound\n\ndef bb(target):\n L=[l1,l2,l3,l4,l5,l6,l7,l8]\n mn=[min(l) for l in L]\n mx=[max(l) for l in L]\n return bbrec([], target, L, mn, mx)\n \neps=1e-9\n\ndef bbrec(sofar, target, L, mn, mx):\n if len(L)==0:\n if target<eps and target>-eps: return...
[ 2, 2, 2 ]
[]
[]
[ "algorithm", "combinations", "python", "subset_sum", "sum" ]
stackoverflow_0074538180_algorithm_combinations_python_subset_sum_sum.txt
Q: Numpy: Making overlapping vectorized modifications to an existing numpy array I'm interested in knowing if its possible to modify individual indices of a numpy array in a manner flexible enough to modify the same index multiple times: import numpy as np zeros = np.zeros(10) indices = np.array([0,0]) adders = np.a...
Numpy: Making overlapping vectorized modifications to an existing numpy array
I'm interested in knowing if its possible to modify individual indices of a numpy array in a manner flexible enough to modify the same index multiple times: import numpy as np zeros = np.zeros(10) indices = np.array([0,0]) adders = np.array([5,8]) indexing adders in this way can give you a sum of 10 In [17]: adders[i...
[ "figured it out\nnp.add.at(zeros, indices, adders[indices])\n\n" ]
[ 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074536692_numpy_python.txt
Q: How to override methods decorated @overload? I made a class inheritted QGraphicsItem (of pyside6) and wrote two overridings. from PySide6.QtCore import QRectF, QLineF, QPointF from PySide6.QtWidgets import QGraphicsItem class myItem(QGraphicsItem): def setPos(self, x: float, y: float): # do something ...
How to override methods decorated @overload?
I made a class inheritted QGraphicsItem (of pyside6) and wrote two overridings. from PySide6.QtCore import QRectF, QLineF, QPointF from PySide6.QtWidgets import QGraphicsItem class myItem(QGraphicsItem): def setPos(self, x: float, y: float): # do something and the coordinates maybe changed super()....
[ "At the expense of installing another package you could achieve what you are trying to do. These libraries will re-direct to methods based on the type signature of the method definition.\ne.g. plum and multidispatch.\nThis example is with plum.\nfrom plum import dispatch\n\n\nclass MyClass:\n pass\n\n\nclass Mul...
[ 0 ]
[]
[]
[ "overloading", "overriding", "python" ]
stackoverflow_0071329090_overloading_overriding_python.txt
Q: Python while not true loops door = input("Do you want to open the door? Enter yes or no: ").lower() while door != "yes" and door != "no": print("Invalid answer.") door = input("Do you want to open the door? Enter yes or no: ").lower() if door == "yes": print("You try to twist open the doorknob but it...
Python while not true loops
door = input("Do you want to open the door? Enter yes or no: ").lower() while door != "yes" and door != "no": print("Invalid answer.") door = input("Do you want to open the door? Enter yes or no: ").lower() if door == "yes": print("You try to twist open the doorknob but it is locked.") elif door == "no": ...
[ "One way to avoid the extra line:\nwhile True\n door = input(\"Do you want to open the door? Enter yes or no: \").lower()\n if door in (\"yes\", \"no\"):\n break\n print(\"Invalid answer.\")\n\nOr if you do this a lot make a helper function.\ndef get_input(prompt, error, choices):\n while True:\n...
[ 2 ]
[ "while True:\n answer = (\"Enter yes or no: \").lower()\n if answer in [\"yes\", \"no\"]:\n break\n print(\"Invalid answer.\")\n # loop will repeat again\n \n\n" ]
[ -1 ]
[ "function", "if_statement", "python", "while_loop" ]
stackoverflow_0074539288_function_if_statement_python_while_loop.txt
Q: Pydantic Model: Convert UUID to string when calling .dict() Thank you for your time. I'm trying to convert UUID field into string when calling .dict() to save to a monogdb using pymongo. I tried with .json() but seems like mongodb doesn't like it TypeError: document must be an instance of dict, bson.son.SON, bson....
Pydantic Model: Convert UUID to string when calling .dict()
Thank you for your time. I'm trying to convert UUID field into string when calling .dict() to save to a monogdb using pymongo. I tried with .json() but seems like mongodb doesn't like it TypeError: document must be an instance of dict, bson.son.SON, bson.raw_bson.RawBSONDocument, or a type that inherits from collection...
[ "Following on Pydantic's docs for classes-with-get_validators\nI created the following custom type NewUuid.\nIt accepts a string matching the UUID format and validates it by consuming the value with uuid.UUID(). If the value is invalid, uuid.UUID() throws an exception (see example output) and if it's valid, then Ne...
[ 2, 0, 0 ]
[ "You don’t need to convert a UUID to a string for mongodb. You can just add the record to the DB as a UUID and it will save it as Binary.\nHere is an example creating a quick UUID and saving it directly to the DB:\n from pydantic import BaseModel\n from uuid import UUID, uuid4\n\n\n class Example(BaseMode...
[ -1 ]
[ "pydantic", "python", "python_3.x" ]
stackoverflow_0068826089_pydantic_python_python_3.x.txt
Q: How to sort a list of strings containing letters and numbers I am trying to sort a list containing strings that are written in a certain format. Here is an example of said list: numberList = ['Task #59;', 'Task #40.5; additional', 'Task #40.9; test', 'Task #40; Task Description Difference; test', 'Task #11;', 'Tas...
How to sort a list of strings containing letters and numbers
I am trying to sort a list containing strings that are written in a certain format. Here is an example of said list: numberList = ['Task #59;', 'Task #40.5; additional', 'Task #40.9; test', 'Task #40; Task Description Difference; test', 'Task #11;', 'Task #12;', 'Task #1;', 'Task #30.1;'] I am currently use this funct...
[ "Use a regex that extracts the number part and converts it to a float to be used as the key\nnumberList = ['Task #59;', 'Task #40.5; additional', 'Task #40.9; test',\n 'Task #40; Task Description Difference; test', 'Task #11;', 'Task #12;', 'Task #1;', 'Task #30.1;']\n\nnumberList = sorted(numberList, ...
[ 2 ]
[]
[]
[ "python", "sorting" ]
stackoverflow_0074539276_python_sorting.txt
Q: Converting from local time to UTC time in Python Pandas dataframe? How would I efficiently convert local times in a dataframe to UTC times? There are 3 columns with information: the date (string), the timezone code (string), and the hour of the day (integer). date timezone hour 7/31/2010 0:00:00 EST 1 6/14/2010...
Converting from local time to UTC time in Python Pandas dataframe?
How would I efficiently convert local times in a dataframe to UTC times? There are 3 columns with information: the date (string), the timezone code (string), and the hour of the day (integer). date timezone hour 7/31/2010 0:00:00 EST 1 6/14/2010 0:00:00 PST 3 6/14/2010 0:00:00 PST 4 5/30/2010 0:00:00 EDT ...
[ "Gday.\nWorking with dates is described reasonably well in this answer here: converting utc to est time in python\nIn that case they have the timezone offsets as numbers e.g +11:00. You have the US short code. So you could convert that column to the numerical equivalent first and then use that function.\nPersonally...
[ 1 ]
[]
[]
[ "dataframe", "datetime", "pandas", "python" ]
stackoverflow_0074538986_dataframe_datetime_pandas_python.txt
Q: Matplotlib Inset Axes modify the rectange connectors I would like to change the inset zoom rectangle to not be a rectangle but just two lines. IE I obtain the image on the left but want the one one the right. I've tried a few things around modifying the rectangular draw. But I think I can't get it to just draw on...
Matplotlib Inset Axes modify the rectange connectors
I would like to change the inset zoom rectangle to not be a rectangle but just two lines. IE I obtain the image on the left but want the one one the right. I've tried a few things around modifying the rectangular draw. But I think I can't get it to just draw only a portion. I would really prefer not to manually just s...
[ "Axes.indicate_axes_zoom returns the Rectangle object:\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfig, ax = plt.subplots()\n\nax.plot(np.arange(0, 10, 0.1)**(1/2))\n\naxins = ax.inset_axes([0.6, 0.1, 0.2, 0.2])\naxins.plot(np.arange(0, 10, 0.1)**(1/2))\naxins.set_xlim([20, 60])\naxins.set_ylim([1, 2.5]...
[ 1 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0074539093_matplotlib_python.txt
Q: How to get all tweets (more than 100) and associated user fields in python using twitter search API v2 and Tweepy? I am trying to get all tweets and their associated user fields (username, name,...etc) that match a certain query using search_recent_tweets. I tried to use pagination and flattening but it only flatt...
How to get all tweets (more than 100) and associated user fields in python using twitter search API v2 and Tweepy?
I am trying to get all tweets and their associated user fields (username, name,...etc) that match a certain query using search_recent_tweets. I tried to use pagination and flattening but it only flattens the tweets (not the user fields). So I am trying to implement something like next_token in get_user_tweets but searc...
[ "You can use GTdownloader for that:\nfrom gtdownloader import TweetDownloader\n\n# create downloader using Twitter API credentials\ngtd = TweetDownloader(credentials='twitter_keys.yaml')\n\ngtd.get_tweets('myquery', \n lang='en', \n max_tweets=100,\n start_time='09/19/2022'...
[ 0 ]
[]
[]
[ "python", "tweepy", "twitter" ]
stackoverflow_0073810522_python_tweepy_twitter.txt
Q: What is the best way to initiate parameters on a Python library? I have a homegrown python library. As it is a library, it should be initialized with parameters every time it is used, based on different projects using it. For example, here is the sample pseudo code: import myownlibrary myownlibrary.init('path_to...
What is the best way to initiate parameters on a Python library?
I have a homegrown python library. As it is a library, it should be initialized with parameters every time it is used, based on different projects using it. For example, here is the sample pseudo code: import myownlibrary myownlibrary.init('path_to_config_file_containing_details_to_process_data') Any idea how this c...
[ "I added it to the __init__.py as below\nglobal configpath\n\ndef setpath(self, pathpassedin):\n self.configpath = pathpassedin\n print(\"Value passed in: \", pathpassedin)\n\nI thought self was required, but having self also requires that the method be called as below:\nimport myownlibrary as mylib\n\nmyownlib...
[ 0 ]
[]
[]
[ "python", "python_3.x", "shared_libraries" ]
stackoverflow_0074496771_python_python_3.x_shared_libraries.txt
Q: Exception occurred processing WSGI script Flask Apche2 EC2 my wsgi file #dico.wsgi import sys import os sys.path.insert(0, '/var/www/html/disco') from disco import app as application application.debug = True 000-default.conf <VirtualHost *:80> ServerName 10.402.120.106 ServerAdmin webmaster@lo...
Exception occurred processing WSGI script Flask Apche2 EC2
my wsgi file #dico.wsgi import sys import os sys.path.insert(0, '/var/www/html/disco') from disco import app as application application.debug = True 000-default.conf <VirtualHost *:80> ServerName 10.402.120.106 ServerAdmin webmaster@localhost DocumentRoot /var/www/html WSGIDaemonPr...
[ "You should declare your virtual environment path and run activate file on wsgi file. And if there are, don't forget environmental variables.\npython_home = '/usr/local/envs/myapp1'\n\nactivate_this = python_home + '/bin/activate_this.py'\nexecfile(activate_this, dict(__file__=activate_this))\n\n" ]
[ 0 ]
[]
[]
[ "apache2.4", "flask", "python" ]
stackoverflow_0069077466_apache2.4_flask_python.txt
Q: function that checks if a number is a float I currently have this how can I get it so it checks for a float and uses a while loop def get_float(): number = input('Input a decimal number ') while number != float: print('bad input ') number = input('Input a decimal number ') else: ...
function that checks if a number is a float
I currently have this how can I get it so it checks for a float and uses a while loop def get_float(): number = input('Input a decimal number ') while number != float: print('bad input ') number = input('Input a decimal number ') else: return number get_float() rig...
[ "Sometimes it's better to ask for forgiveness than permission.\ndef get_float():\n while True:\n number = input('Input a number ')\n try:\n return float(number)\n except ValueError:\n print('\\n bad input\\n ')\n\n", "number = input('Input a decimal number ')\nwhile n...
[ 3, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074524638_python.txt
Q: Flattening multi nested json into a pandas dataframe I'm trying to flatten this json response into a pandas dataframe to export to csv. It looks like this: j = [ { "id": 401281949, "teams": [ { "school": "Louisiana Tech", "conference": "Conference USA...
Flattening multi nested json into a pandas dataframe
I'm trying to flatten this json response into a pandas dataframe to export to csv. It looks like this: j = [ { "id": 401281949, "teams": [ { "school": "Louisiana Tech", "conference": "Conference USA", "homeAway": "away", "po...
[ "can you try this:\nmultiple_level_data = pd.json_normalize(j, record_path =['teams'])\nmultiple_level_data = multiple_level_data.explode('stats').reset_index(drop=True)\nmultiple_level_data=multiple_level_data.join(pd.json_normalize(multiple_level_data.pop('stats')))\n\n#convert rows to columns.\nmultiple_level_da...
[ 3, 2, 1 ]
[]
[]
[ "dataframe", "json", "pandas", "python" ]
stackoverflow_0074538822_dataframe_json_pandas_python.txt
Q: How to overlay plots with different dates? I would like to overlay two plots that are in different date or time. To do so, I have implemented the following code. import random import pandas as pd import numpy as np import plotly.express as px df = pd.DataFrame({'DATE_TIME':pd.date_range('2022-11-01', '2022-11-06 ...
How to overlay plots with different dates?
I would like to overlay two plots that are in different date or time. To do so, I have implemented the following code. import random import pandas as pd import numpy as np import plotly.express as px df = pd.DataFrame({'DATE_TIME':pd.date_range('2022-11-01', '2022-11-06 23:00:00',freq='20min'), 'ID'...
[ "Would a secondary x-axis work for you? Like this?\n\nIn that case you can set up a figure with multiple axes like this:\nfig=make_subplots(\n specs=[[{\"secondary_y\": True}]])\nfig.update_layout(xaxis2= {'anchor': 'y', 'overlaying': 'x', 'side': 'top'})\n\nAnd then make a few tweaks with:\nfig1.for_each_tr...
[ 1 ]
[]
[]
[ "plotly", "plotly_dash", "python" ]
stackoverflow_0074531824_plotly_plotly_dash_python.txt
Q: Reversing bits of Python integer Given a decimal integer (eg. 65), how does one reverse the underlying bits in Python? i.e.. the following operation: 65 → 01000001 → 10000010 → 130 It seems that this task can be broken down into three steps: Convert the decimal integer to binary representation Reverse the bits C...
Reversing bits of Python integer
Given a decimal integer (eg. 65), how does one reverse the underlying bits in Python? i.e.. the following operation: 65 → 01000001 → 10000010 → 130 It seems that this task can be broken down into three steps: Convert the decimal integer to binary representation Reverse the bits Convert back to decimal Steps #2 and 3...
[ "int('{:08b}'.format(n)[::-1], 2)\n\nYou can specify any filling length in place of the 8. If you want to get really fancy,\nb = '{:0{width}b}'.format(n, width=width)\nint(b[::-1], 2)\n\nlets you specify the width programmatically.\n", "If you are after more speed, you can use the technique described in\nhttp://l...
[ 60, 11, 10, 8, 3, 3, 3, 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "bit_manipulation", "integer", "python" ]
stackoverflow_0012681945_bit_manipulation_integer_python.txt
Q: pb avec web scraping import requests import pandas as pd from urllib.request import urlopen from bs4 import BeautifulSoup df = [] for x in range(1,31): url_allocine= 'https://www.allocine.fr/film/meilleurs/?page=' page = requests.get(url_allocine + str(x)) soup = BeautifulSoup(page.content, 'html.pars...
pb avec web scraping
import requests import pandas as pd from urllib.request import urlopen from bs4 import BeautifulSoup df = [] for x in range(1,31): url_allocine= 'https://www.allocine.fr/film/meilleurs/?page=' page = requests.get(url_allocine + str(x)) soup = BeautifulSoup(page.content, 'html.parser') films_all = sou...
[ "To get \"Note Presse\" and \"Note Spectateurs\" you can use next example:\nimport requests\nimport pandas as pd\nfrom bs4 import BeautifulSoup\n\ndata = []\nfor page in range(1, 3): # <-- increase number of pages here\n url = f\"https://www.allocine.fr/film/meilleurs/?page={page}\"\n soup = BeautifulSoup(re...
[ 1, 0 ]
[]
[]
[ "pandas", "python", "urllib", "web_scraping" ]
stackoverflow_0074532249_pandas_python_urllib_web_scraping.txt
Q: Changing NaN cells in pandas dataframe with different type of columns How can I fill all the NaN values in pandas dataframe with the empty value of column type. For example, I have 2 columns - "Name" - str, "Age" - int. I want to fill all the NaN cells in "Name" with "" and all the NaN in "Age" with 0. Do pandas h...
Changing NaN cells in pandas dataframe with different type of columns
How can I fill all the NaN values in pandas dataframe with the empty value of column type. For example, I have 2 columns - "Name" - str, "Age" - int. I want to fill all the NaN cells in "Name" with "" and all the NaN in "Age" with 0. Do pandas has a method to implement it. I can do that separately for "Name" and "Age" ...
[ "The parameter value of pandas.DataFrame.fillna accept dictionnaries. So, assuming your dataframe is df, you can fill NaN values with multiple values in multiple columns by using :\ndf.fillna({\"Name\": \"\", \"Age\": 0}, inplace=True)\n\nFurthermore, if you need to fill NaN values based on the type of the columns,...
[ 2 ]
[]
[]
[ "dataframe", "jupyter_notebook", "pandas", "python", "python_3.x" ]
stackoverflow_0074539559_dataframe_jupyter_notebook_pandas_python_python_3.x.txt
Q: Platform does not define a GLUT font retrieval function I am trying to install a cozmo SDK on my ubuntu (v 20.4). I followed the instructions from the http://cozmosdk.anki.com/docs/install-linux.html and at the end I always get the same error. "Platform does not define a GLUT font retrieval function". I did try in...
Platform does not define a GLUT font retrieval function
I am trying to install a cozmo SDK on my ubuntu (v 20.4). I followed the instructions from the http://cozmosdk.anki.com/docs/install-linux.html and at the end I always get the same error. "Platform does not define a GLUT font retrieval function". I did try installing it on my Host PC however I ended up with the same er...
[ "It turned out to be a problem with the python version. Easy solution: use ubuntu version 20.04.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074041603_python.txt
Q: fetch value from two fields (Date and Monetary) and convert it in text in Odoo I have two fields in Sale order, i need to get values from each one change its value in text and display in another field in custom model Two fiedls in sale.order module: amount_total = fields.Monetary(string="Total", store=True, comput...
fetch value from two fields (Date and Monetary) and convert it in text in Odoo
I have two fields in Sale order, i need to get values from each one change its value in text and display in another field in custom model Two fiedls in sale.order module: amount_total = fields.Monetary(string="Total", store=True, compute='_compute_amounts', tracking=4) date_order = fields.Datetime() and this is my c...
[ "You can use odoo related field attribute.\nIn your custom model add a relational field with sale.order and then create related fields.\nsale_order_id = fields.Many2one(comodel_name=\"sale.order\")\nsale_order_amount_total = fields.Monetary(related=\"sale_order_id.amount_total\")\nsale_order_date_order = fields.Dat...
[ 0 ]
[]
[]
[ "field", "odoo", "odoo_15", "python" ]
stackoverflow_0074474619_field_odoo_odoo_15_python.txt
Q: Fourier transform of 2D Gaussian kernel is not matching up with its counterpart in the spatial domain We know the Fourier transform of a Gaussian filter is again Gaussian in the frequency domain, I have written the following method to build a Gaussian kernel: def get_gaussian(size, sigma): g_kernel = np.zeros((s...
Fourier transform of 2D Gaussian kernel is not matching up with its counterpart in the spatial domain
We know the Fourier transform of a Gaussian filter is again Gaussian in the frequency domain, I have written the following method to build a Gaussian kernel: def get_gaussian(size, sigma): g_kernel = np.zeros((size,size)) x_center = size // 2 y_center = size // 2 for i in range(size): for j in range(size): ...
[ "In the frequency domain, the Gaussian has a sigma of size / (2 * pi * sigma), with size the size of the image, and sigma the spatial-domain sigma. Yes, for a non-square image, an isotropic Gaussian in the spatial domain is not isotropic in the frequency domain.\nYour computation sigma / (np.sqrt(2) * np.pi) is wro...
[ 1 ]
[]
[]
[ "convolution", "fft", "image_processing", "python", "signal_processing" ]
stackoverflow_0074539485_convolution_fft_image_processing_python_signal_processing.txt
Q: Openpyxl Python Copy From One Excel Sheet&Paste in Existing Individual Workbooks in Subfolders I have a code that copies data based on Column ['A'] cell value from one .xlsx workbook call it my source file and pastes it into the most recently modified .xlsm file in a subfolder. The problem I have is that I have 50...
Openpyxl Python Copy From One Excel Sheet&Paste in Existing Individual Workbooks in Subfolders
I have a code that copies data based on Column ['A'] cell value from one .xlsx workbook call it my source file and pastes it into the most recently modified .xlsm file in a subfolder. The problem I have is that I have 50 subfolders but my code only works for one, so I am repeating the script 50 times which is not produ...
[ "I figured it out, I am pasting the code below to help anybodyelse who may be doing similar project. I listed my cities in a list, listed my abbreviations(which also double as my folder name) in a list, I paired the list using zip and used the zip to enumerate and set my subfolder names.\nwb_sf= load_workbook(r'C:\...
[ 0 ]
[]
[]
[ "openpyxl", "python" ]
stackoverflow_0074523924_openpyxl_python.txt
Q: Formatting the scientific notation phone number in python I have my phone_number column listed below. phone_number -------------- 001 1234567890 380 1234567890 27 1234567890 001 +11234567890 2.56898E+11 1 1234567890 123-456-7890 +1 (123) 456-7890 (123) 456-7890 NaN The following step worked fine character = '[^...
Formatting the scientific notation phone number in python
I have my phone_number column listed below. phone_number -------------- 001 1234567890 380 1234567890 27 1234567890 001 +11234567890 2.56898E+11 1 1234567890 123-456-7890 +1 (123) 456-7890 (123) 456-7890 NaN The following step worked fine character = '[^0-9]+' df.phone_number.str.replace(character, '') The result I...
[ "You can use conversion to Int64/string dtypes:\ns1 = (pd.to_numeric(df['phone_number'], errors='coerce')\n .astype('Int64').astype('string')\n )\n\ns2 = df['phone_number'].str.replace(r'\\D+', '', regex=True)\n\ndf['phone_number_clean'] = s1.fillna(s2)\n\nprint(df)\n\nOutput:\n phone_number phon...
[ 2 ]
[]
[]
[ "data_cleaning", "formatting", "pandas", "phone_number", "python" ]
stackoverflow_0074539685_data_cleaning_formatting_pandas_phone_number_python.txt
Q: "database or disk is full" error when joining two tables With California Traffic Collision Data from Kaggle I want to join two tables based on case id but selecting only rows that have a collision date of > 2020: con = sqlite3.connect(".../switrs.sqlite") df_sqllite = pd.read_sql_query('SELECT * FROM parties JOIN...
"database or disk is full" error when joining two tables
With California Traffic Collision Data from Kaggle I want to join two tables based on case id but selecting only rows that have a collision date of > 2020: con = sqlite3.connect(".../switrs.sqlite") df_sqllite = pd.read_sql_query('SELECT * FROM parties JOIN collisions USING (case_id) WHERE collision_date >= "2020-01-0...
[ "SELECT * FROM parties as p JOIN collisions as c USING c.case_id WHERE c.collision_date >= \"2020-01-01\n" ]
[ 0 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0074539729_python_sqlite.txt
Q: How keep latest records in dataframe according to last version using pandas I have a dataframe like this Id b_num b_type b_ver price 100 55 A 0 100 101 55 A 0 50 102 55 A 1 100 103 55 A 1 60 104 ...
How keep latest records in dataframe according to last version using pandas
I have a dataframe like this Id b_num b_type b_ver price 100 55 A 0 100 101 55 A 0 50 102 55 A 1 100 103 55 A 1 60 104 30 C 2 100 105 30 C 2 50 1...
[ "Consider trying with:\ndf.merge(df.groupby(['b_num','b_type'],as_index=False)['b_ver'].last(),\n on=['b_num','b_type','b_ver'])\n\nOutputting:\n Id b_num b_type b_ver price\n0 102 55 A 1 100\n1 103 55 A 1 60\n2 108 30 C 4 200\n3 109 30 ...
[ 3, 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074539711_dataframe_pandas_python.txt
Q: how to check if file exists outside of current working directory in python I am trying to find if a file exists that is not in the current directory. The file is here: ~/Documents/project/data.csv I am trying to locate it by absolute path like this: os.path.isfile(f'~/Documents/project/data.csv') I always get fal...
how to check if file exists outside of current working directory in python
I am trying to find if a file exists that is not in the current directory. The file is here: ~/Documents/project/data.csv I am trying to locate it by absolute path like this: os.path.isfile(f'~/Documents/project/data.csv') I always get false because I am running this code from outside of ~/Documents/project/. I unders...
[ "What version of Python are you using? As of 3.4 you can use the pathlib library functions:\nfrom pathlib import Path\n\np = Path(\"~/Documents/project/data.csv\")\np.exists()\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074539755_python.txt
Q: Unresponsive tkinter SimpleDialog box Below is an outline of a tkinter GUI in which I want the same dialog box to be opened in various ways. The response selected by the user from choices in the dialog then needs to be returned to the mainloop. The SimpleDialog class looks to be ideal for this and here I have jus...
Unresponsive tkinter SimpleDialog box
Below is an outline of a tkinter GUI in which I want the same dialog box to be opened in various ways. The response selected by the user from choices in the dialog then needs to be returned to the mainloop. The SimpleDialog class looks to be ideal for this and here I have just used the example provided in the dialog c...
[ "The problem appears to lie in the print statement in the do_test callback, as splitting this into two lines fixes it\n #print(d.go()) \n answer = d.go()\n print(answer)\n\nAs reported in a comment this may be only an issue for MacOS (I am using MacOS 11.1 and Python 3.10.8 ).\n" ]
[ 0 ]
[]
[]
[ "macos", "python", "simpledialog", "tkinter" ]
stackoverflow_0074398183_macos_python_simpledialog_tkinter.txt
Q: import jwt ImportError: No module named jwt I have been trying to run this project https://github.com/udacity/FSND-Deploy-Flask-App-to-Kubernetes-Using-EKS I installed all the dependencies. I still did not make any adjustments. I need to run it first but I get this error when I type the command python main.py thi...
import jwt ImportError: No module named jwt
I have been trying to run this project https://github.com/udacity/FSND-Deploy-Flask-App-to-Kubernetes-Using-EKS I installed all the dependencies. I still did not make any adjustments. I need to run it first but I get this error when I type the command python main.py this is the error i get: Traceback (most recent call...
[ "\nCheck if PyJWTY is in the requirements file or if is installed in you system, using: pip3 install PyJWT\nYou could also face this error if you have running on your machine two versions of python. So the correct command will be python3 main.py\n\n", "I have hit the same issue with pyjwt 2.1.0 which was clearly ...
[ 15, 3, 2, 2, 0, 0, 0 ]
[]
[]
[ "jwt", "python" ]
stackoverflow_0063309591_jwt_python.txt
Q: "key error" when using an enum as a dictionary key in Python3 I want to use an enum as the key for a dictionary, but get a KeyError. #!/usr/bin/python3 from enum import Enum, unique from typing import List @unique class Color(Enum): RED = "cherry" GREEN = "cucumber" BLUE = "blueberry" allColors = {}...
"key error" when using an enum as a dictionary key in Python3
I want to use an enum as the key for a dictionary, but get a KeyError. #!/usr/bin/python3 from enum import Enum, unique from typing import List @unique class Color(Enum): RED = "cherry" GREEN = "cucumber" BLUE = "blueberry" allColors = {} def countColors(colors: List[Color]): for c in colors: ...
[ "I think this is failing because of two things:\n\n+= update expects to have the key already in the dictionary.\n\nFor this you will have to check if the dictionary has the key and if it doesn't then update the item\n\nthe access to the enum item like allColors[c] uses the __get_item__ method for enums.\n\nhttps://...
[ 0 ]
[ "Could it be that you have set 3 colors but in line 18 you have 4\ncountColors([Color.RED, Color.RED, Color.BLUE, Color.GREEN])\n\ntry\ncountColors ([Color.RED, Color.Blue, Color.Green])\n\n" ]
[ -1 ]
[ "dictionary", "enums", "python", "python_3.x" ]
stackoverflow_0058054345_dictionary_enums_python_python_3.x.txt
Q: Replace Value on dict comprehension based on condition a = ('A','B','C') b = (45.43453453, 'Bad Val', 76.45645657 ) I want to create a dict, very simple: { k:v for k,v in zip(a,b) } My problem is, now I want to apply float (if possible) or replace it with None so, I want to apply a round of 2 and therefore my ou...
Replace Value on dict comprehension based on condition
a = ('A','B','C') b = (45.43453453, 'Bad Val', 76.45645657 ) I want to create a dict, very simple: { k:v for k,v in zip(a,b) } My problem is, now I want to apply float (if possible) or replace it with None so, I want to apply a round of 2 and therefore my output should be: {'A': 45.43, 'B': None, 'C': 76.46}
[ "Since round raises a TypeError whenever something doesn't implement __round__, this isn't possible directly with dictionary comprehensions, but you can write your own function to use inside of it.\ndef safe_round(val, decimals):\n try:\n return round(val, decimals)\n except TypeError:\n return None\n\na = ...
[ 1, 0 ]
[]
[]
[ "dictionary", "python", "python_zip", "rounding" ]
stackoverflow_0074539840_dictionary_python_python_zip_rounding.txt
Q: IndexError is being generated when deleting first and last terms in a Numpy array I have a simple program that I'm writing for a math class that generates an array of numbers from 1 to 10. After removing the 10s I would like to count and remove pairs of numbers that add up to at least 10, therefore I order the arr...
IndexError is being generated when deleting first and last terms in a Numpy array
I have a simple program that I'm writing for a math class that generates an array of numbers from 1 to 10. After removing the 10s I would like to count and remove pairs of numbers that add up to at least 10, therefore I order the array in ascending order and check if the sum of the first and last numbers is greater tha...
[ "I checked and tested your code and I found two problems.\nFirst, let's see about the both errors that you mentioned\na) index 0 is out of bounds for axis 0 with size 0 on sum = dice[0]\nOn that case, I tried to print dice to check if dice was empty (since that error refers that you tried to get an element from tha...
[ 0 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0074539450_arrays_numpy_python.txt
Q: How to append output values of a function to a new empty list? My aim is to create a function, list_powers, and use a for loop to take a list and return a new list (power_list) where each element is exponentiated to a specified power. I have moved the return statement appropriately in order to collect all topowers...
How to append output values of a function to a new empty list?
My aim is to create a function, list_powers, and use a for loop to take a list and return a new list (power_list) where each element is exponentiated to a specified power. I have moved the return statement appropriately in order to collect all topowers in power_list and return them but it still returns None. How do I c...
[ "return leaves the function. You have to return after the loop, not unconditional in the loop. And of course you don't want to return the last value for topower but the full list.\ndef list_powers(iterable, power = 2):\n power_list = []\n\n for elem in iterable:\n topower = elem ** power\n power...
[ 2, 1 ]
[]
[]
[ "append", "function", "loops", "python" ]
stackoverflow_0074539884_append_function_loops_python.txt
Q: Trying to run a container on docker but can not access the website of the application we created We've been using python3 and Docker as our framework. Our main issue is that while we try to run the docker container it redirects us to the browser but the website can not be reached. But it is working when we run the...
Trying to run a container on docker but can not access the website of the application we created
We've been using python3 and Docker as our framework. Our main issue is that while we try to run the docker container it redirects us to the browser but the website can not be reached. But it is working when we run the commands python manage.py runserver manualy from the terminal of VS code here is the docker-compose.y...
[ "As you copied the source folder(happy_traveller) in your docker file, you don't need to run the cd command again, so the docker-compose file would look like this:\nversion: \"2.12.2\"\n\nservices:\n web:\n tty: true\n build:\n dockerfile: Dockerfile\n context: .\n command: bash -c \"python mana...
[ 1 ]
[]
[]
[ "django", "docker", "docker_compose", "dockerfile", "python" ]
stackoverflow_0074539893_django_docker_docker_compose_dockerfile_python.txt
Q: Update column value if another column has a certain substring I'm facing a lot of trouble on what seems to be a simple matter: I have a column with some beverages names, but they are poluted with "12oz" and "Boxes". I want to get only the name of the beverages. Unfortunally, they are not typed in the same particul...
Update column value if another column has a certain substring
I'm facing a lot of trouble on what seems to be a simple matter: I have a column with some beverages names, but they are poluted with "12oz" and "Boxes". I want to get only the name of the beverages. Unfortunally, they are not typed in the same particular form, so i cant just [0:5] them. I know all the beverages names ...
[ "Just use replace statements, set regex to true, and replace with an empty string, like this:\ndf.replace('12oz', '', regex=True)\n\nThis is assuming you know what text you will have to replace.\n", "If you have the list of all the beverages, you can use pandas.Series.extract :\nimport re\n​\nlist_of_bvr= [\"ball...
[ 2, 1 ]
[]
[]
[ "pandas", "python", "substring" ]
stackoverflow_0074539589_pandas_python_substring.txt
Q: PyJWT won't import jwt.algorithms (ModuleNotFoundError: No module named 'jwt.algorithms') For some reason, PyJTW doesn't seem to work on my virtualenv on Ubuntu 16.04, but it worked fine on my local Windows machine (inside a venv too). I'm clueless, I've tried different versions, copied the exact same versions as ...
PyJWT won't import jwt.algorithms (ModuleNotFoundError: No module named 'jwt.algorithms')
For some reason, PyJTW doesn't seem to work on my virtualenv on Ubuntu 16.04, but it worked fine on my local Windows machine (inside a venv too). I'm clueless, I've tried different versions, copied the exact same versions as I had on my Windows machine, and yet I still couldn't get this to work. Installed packages: Pac...
[ "I had the same issue. The error seems to be a conflict between the pyjwt and jwt modules (as mentioned by @vimalloc above). What worked for me was to run the following command (NOTE: I am using Python 3.6.10).\npip3 install -U pyjwt\n\n", "You don't have to register with the 'RSAAlgorithm'.\nYou have install the...
[ 3, 3, 1, 0, 0 ]
[]
[]
[ "oauth_2.0", "python", "python_3.x" ]
stackoverflow_0064128255_oauth_2.0_python_python_3.x.txt
Q: Include Value from Dictionary in New Dictionary Only if Number How can I create a new dictionary from an existing dictionary to include only key and values where values are numeric? Example dictionary: simple_dict = { 'a': 1, 'b': 2, 'c': 3, 'd': 'John', 'e': 4, 'f': 'Sandra' } What I have so far: ...
Include Value from Dictionary in New Dictionary Only if Number
How can I create a new dictionary from an existing dictionary to include only key and values where values are numeric? Example dictionary: simple_dict = { 'a': 1, 'b': 2, 'c': 3, 'd': 'John', 'e': 4, 'f': 'Sandra' } What I have so far: new_dict = {key: value for key, value in simple_dict.items() if } I...
[ "import numbers\n...\nnew_dict = {\n key:value for key, value in simple_dict.items()\n if isinstance(value, numbers.Number)\n}\n\n" ]
[ 1 ]
[]
[]
[ "dictionary", "dictionary_comprehension", "python" ]
stackoverflow_0074539976_dictionary_dictionary_comprehension_python.txt
Q: Use class methods to list the names and positions of teachers and facility at a mock university I'm trying to list the names and positions of teachers and facility at a university. When I try to run the program it does not work and I get an error message that says 'str' object has no attribute 'dean_print' class T...
Use class methods to list the names and positions of teachers and facility at a mock university
I'm trying to list the names and positions of teachers and facility at a university. When I try to run the program it does not work and I get an error message that says 'str' object has no attribute 'dean_print' class TSC: def __init__(self, President, Dean1, Dean2, Dean3, Dean4, Dean5, Chair1, Chair2, Chair3, Cha...
[ "There are many errors in the code. For example, in your Wizardy class, you have the class method dean_print1 which tries to reference \"self.dean_five_b\". You have not defined the instance attribute dean_five_b for this class, only dean_one_b. I'm not going to point out all these errors to you as I'm sure you can...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074539750_python.txt
Q: How to use two APIs to get the response of an endpoint once it processed? I have two APIs: triggerAPI and triggerAPIResult. When I hit the first one, it would trigger a process which could take a few minutes to return the response. The second API is used to check if the process is successfully finished or not. The...
How to use two APIs to get the response of an endpoint once it processed?
I have two APIs: triggerAPI and triggerAPIResult. When I hit the first one, it would trigger a process which could take a few minutes to return the response. The second API is used to check if the process is successfully finished or not. Therefore, when the second API returns true, that means now the response from the ...
[ "You need to implement long running operations. This is an implementation strategy used by fe. Google (in their GCP APIs), IBM, and other big companies.\nThe principle is quite simple.\n\nDo a request to the triggerAPI and immediately return a unique operation ID.\nStore this ID somewhere and have an is_done value ...
[ 1 ]
[]
[]
[ "api", "python", "request", "url" ]
stackoverflow_0074539254_api_python_request_url.txt