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: Python Newscatcher throws errors When I try to install Newscatcher in the Conda virtual env (Python 3.7.13), it throws the following errors; I tried the following way; pip install git+https://github.com/kotartemiy/newscatcher.git Following is the error; Collecting git+https://github.com/kotartemiy/newscatcher.git...
Python Newscatcher throws errors
When I try to install Newscatcher in the Conda virtual env (Python 3.7.13), it throws the following errors; I tried the following way; pip install git+https://github.com/kotartemiy/newscatcher.git Following is the error; Collecting git+https://github.com/kotartemiy/newscatcher.git Cloning https://github.com/kotartem...
[ "The module you're trying to install is a bit old (3 years), however, setup tools removed support for 2to3 during builds.\nTry downgrading setup tools:\npip install \"setuptools<58.0.0\"\n\nAnd then\npip install newscatcher --upgrade\n\n" ]
[ 1 ]
[]
[]
[ "pip", "python", "python_3.x", "web_scraping" ]
stackoverflow_0074437928_pip_python_python_3.x_web_scraping.txt
Q: chi2inv in Python What is the corresponding function for calculating the inverse chi squared distribution in python? In MATLAB, for example, a 95% confidence interval with n degrees of freedom is given by chi2inv(0.95, n) A: from scipy.stats.distributions import chi2 chi2.ppf(0.975, df=2) 7.377758908227871 octa...
chi2inv in Python
What is the corresponding function for calculating the inverse chi squared distribution in python? In MATLAB, for example, a 95% confidence interval with n degrees of freedom is given by chi2inv(0.95, n)
[ "from scipy.stats.distributions import chi2\nchi2.ppf(0.975, df=2)\n\n7.377758908227871\noctave:4> chi2inv(0.975,2)\nans = 7.3778\n\n", "Additional information to the current answer:\nchi2.ppf and chi2.cdf are inverse of each-other:\nfrom scipy.stats.distributions import chi2\nchi2.ppf(0.95, df=5) # 11.07\nc...
[ 9, 0, 0 ]
[]
[]
[ "python", "scipy", "statistics" ]
stackoverflow_0053019080_python_scipy_statistics.txt
Q: How to print each element of a list on a new line in a nested list I wanted to print each individual element of a list that's in nested list. it should also print symbols to show where the different lists end. There are only going to be 3 lists total in the big list. For Example, list1 = [['assign1', 'assign2'], [...
How to print each element of a list on a new line in a nested list
I wanted to print each individual element of a list that's in nested list. it should also print symbols to show where the different lists end. There are only going to be 3 lists total in the big list. For Example, list1 = [['assign1', 'assign2'], ['final,'assign4'], ['exam','study']] Output should be: ################...
[ "You can create another for loop around the one you know how to create. So:\nfor list2 in list1:\n # print some stuff here\n for word in list2:\n print(word)\n # print some more stuff\n\n", "Assuming that there is a single nesting level.\nsymbols = \"#-*\"\nlist1 = [['assign1', 'assign2'], ['final', 'assign...
[ 1, 1 ]
[]
[]
[ "list", "nested_lists", "nested_loops", "python" ]
stackoverflow_0074438540_list_nested_lists_nested_loops_python.txt
Q: Why does it not work when I define the range of my while loop with a variable? I'm a complete novice at python and am trying to list the first n positive numbers, where n is an inputted value. E.g. when n=5, I want to output 5, 4, 3, 2 and 1. This is my code which doesn't work: n= int(input("Please enter a number:...
Why does it not work when I define the range of my while loop with a variable?
I'm a complete novice at python and am trying to list the first n positive numbers, where n is an inputted value. E.g. when n=5, I want to output 5, 4, 3, 2 and 1. This is my code which doesn't work: n= int(input("Please enter a number: ")) i=0 while i<n: print(n) n=n-1 i=i+1 I know I can answer the ques...
[ "You are decrementing the number and incrementing the counter at the same time.\nFor example:\n\n\n\n\nn\ni\ni<n\n\n\n\n\n5\n0\nTrue\n\n\n4\n1\nTrue\n\n\n3\n2\nTrue\n\n\n2\n3\nFalse\n\n\n\n\nThe loop exits once False is encountered. To solve this you need to only increment i and use print(n-i), keep the i<n compari...
[ 2, 1 ]
[]
[]
[ "python", "while_loop" ]
stackoverflow_0074438555_python_while_loop.txt
Q: Trying to convert tuple to a dictionary and after that looking for the smallest item that contains a certain number So I was toying around with this code: def cheapest_shark(prices: List, sharks: List ) -> Tuple: shp = zip(sharks, prices) sharkprices = tuple(shp) print(sharkprices) My input is ch...
Trying to convert tuple to a dictionary and after that looking for the smallest item that contains a certain number
So I was toying around with this code: def cheapest_shark(prices: List, sharks: List ) -> Tuple: shp = zip(sharks, prices) sharkprices = tuple(shp) print(sharkprices) My input is cheapest_shark([230, 180, 52, 390, 520], [1, 0, 0, 1, 1]) (Each number is connected to each other in the output: (230, 1) ...
[ "Try to filter the tuples (keep only values where the shark is 1) and use min():\ndef cheapest_shark(prices, sharks):\n shp = ((p, s) for p, s in zip(prices, sharks) if s == 1)\n return min(shp, default=None)\n\n\nx = cheapest_shark([230, 180, 52, 390, 520], [1, 0, 0, 1, 1])\nprint(x)\n\nPrints:\n(230, 1)\n\n...
[ 1 ]
[]
[]
[ "dictionary", "python", "tuples" ]
stackoverflow_0074438547_dictionary_python_tuples.txt
Q: Find the average of a column that meets criteria of other columns I have a dataset and I need to use Python and Pandas to find the average prices of specific items in a column that meet specific criteria. The criteria are "Honda" and "Toyota" in the "manufacturer" column, "good" in the "condition" column, and "sed...
Find the average of a column that meets criteria of other columns
I have a dataset and I need to use Python and Pandas to find the average prices of specific items in a column that meet specific criteria. The criteria are "Honda" and "Toyota" in the "manufacturer" column, "good" in the "condition" column, and "sedan" in the "type" column. The prices are in the "price" column. I would...
[ "df.groupby(['criteria','manufacturer','condition'])['price'].mean()\n\nThis is the right Groupby function. you had an extra \".\" dot before ['price'] and you are missing a pair of parentheses ().\nadd this code after your dataframe\ndf = df[(df[ \"manufacturer\"]==\"Honda\") | (df[ \"manufacturer\"]==\"Toyota\") ...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074438543_pandas_python.txt
Q: abstracting the conversion between id3 tags, m4a tags, flac tags I'm looking for a resource in python or bash that will make it easy to take, for example, mp3 file X and m4a file Y and say "copy X's tags to Y". Python's "mutagen" module is great for manupulating tags in general, but there's no abstract concept of ...
abstracting the conversion between id3 tags, m4a tags, flac tags
I'm looking for a resource in python or bash that will make it easy to take, for example, mp3 file X and m4a file Y and say "copy X's tags to Y". Python's "mutagen" module is great for manupulating tags in general, but there's no abstract concept of "artist field" that spans different types of tag; I want a library tha...
[ "I needed this exact thing, and I, too, realized quickly that mutagen is not a distant enough abstraction to do this kind of thing. Fortunately, the authors of mutagen needed it for their media player QuodLibet.\nI had to dig through the QuodLibet source to find out how to use it, but once I understood it, I wrote ...
[ 9, 2, 2, 0, 0, 0 ]
[]
[]
[ "bash", "m4a", "mp3", "python" ]
stackoverflow_0000697776_bash_m4a_mp3_python.txt
Q: minimalmodbus checksum error in rtu mode with 2 devices I have a RPI with a USB CH340 dongle connected to a EM340 energy meter. It works fine with the code below. When I connect 2 x EM340 energy meters I get the following error: pi@raspberrypi:~ $ python3 modbus_test.py Traceback (most recent call last): File "m...
minimalmodbus checksum error in rtu mode with 2 devices
I have a RPI with a USB CH340 dongle connected to a EM340 energy meter. It works fine with the code below. When I connect 2 x EM340 energy meters I get the following error: pi@raspberrypi:~ $ python3 modbus_test.py Traceback (most recent call last): File "modbus_test.py", line 21, in <module> freq2 = instrument.r...
[ "As per the comments if you attach two Modbus RTU devices with the same ID in parallel then they will both respond to any request addressed to that Slave ID. The responses will probably collide which means your code will receive a garbled response (detected via the CRC).\nThe solution is to change the ID of one of ...
[ 0 ]
[]
[]
[ "minimalmodbus", "modbus", "python" ]
stackoverflow_0074434524_minimalmodbus_modbus_python.txt
Q: Updating Nested dictionary with new information in table/dictionary using update Given the following dictionary: dict1 = {'AA':['THISISSCARY'], 'BB':['AREYOUAFRAID'], 'CC':['DONOTWORRY']} I'd like to update the values in the dictionary given the information in the following table Table = pd.Data...
Updating Nested dictionary with new information in table/dictionary using update
Given the following dictionary: dict1 = {'AA':['THISISSCARY'], 'BB':['AREYOUAFRAID'], 'CC':['DONOTWORRY']} I'd like to update the values in the dictionary given the information in the following table Table = pd.DataFrame({'KEY':['AA','AA','BB','CC'], 'POSITION':[2,4,9,3], ...
[ "you can use:\ndict_df=Table.to_dict('records')\nprint(dict_df)\n'''\n[{'KEY': 'AA', 'POSITION': 2, 'oldval': 'I', 'newval': 'X'}, {'KEY': 'AA', 'POSITION': 4, 'oldval': 'I', 'newval': 'X'}, {'KEY': 'BB', 'POSITION': 9, 'oldval': 'A', 'newval': 'U'}, {'KEY': 'CC', 'POSITION': 3, 'oldval': 'O', 'newval': 'I'}]\n'''\...
[ 1, 1 ]
[]
[]
[ "dictionary", "pandas", "python" ]
stackoverflow_0074437741_dictionary_pandas_python.txt
Q: How to pass HTML input text value as a parameter to python function? So I have a python code, that I have implemented in HTML using pyscript. My python code has a function which takes in a word as a parameter and does something with it. How can I make it so whatever I put in the text field in HTML, gets passed as ...
How to pass HTML input text value as a parameter to python function?
So I have a python code, that I have implemented in HTML using pyscript. My python code has a function which takes in a word as a parameter and does something with it. How can I make it so whatever I put in the text field in HTML, gets passed as a parameter and calls the python function? The alternative, if anyone know...
[ "Here's an example that does a very basic anagram service. Put this in a file called something.py, then bring up http://yourwebsite/something.py in your browser.\n#! /usr/bin/env python3\n\nimport cgi\nimport random\nform = cgi.FieldStorage()\nif 'submit' not in form:\n print('''Content-Type: text/html\n\n<form...
[ 0 ]
[]
[]
[ "html", "javascript", "pyscript", "python" ]
stackoverflow_0074438369_html_javascript_pyscript_python.txt
Q: How can I merge 3 Pandas DataFrames containing the same data except for a few columns? I have 3 pd.DataFrames that I need to merge. Each of them contains the same data except for the last 5 columns, and each is 9276 rows x 67 cols. Schematically, they look like this: MWE of the data: df1 = pd.DataFrame({"A": [4, ...
How can I merge 3 Pandas DataFrames containing the same data except for a few columns?
I have 3 pd.DataFrames that I need to merge. Each of them contains the same data except for the last 5 columns, and each is 9276 rows x 67 cols. Schematically, they look like this: MWE of the data: df1 = pd.DataFrame({"A": [4, 5, 6, 7, 8, 9], "B": [2, 2, 2, 3, 3, 3], "C": [np.nan, np.nan, 5, 5, 6, 6]}) df2 = pd.DataFr...
[ "Since all of your indexes are the same, the simplest approach would be DataFrame.fillna() with a dataframe argument:\ndf1.fillna(df2).fillna(df3)\n\nOutput:\n A B C\n0 4 2 4.0\n1 5 2 4.0\n2 6 2 5.0\n3 7 3 5.0\n4 8 3 6.0\n5 9 3 6.0\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "merge", "pandas", "python" ]
stackoverflow_0074438393_dataframe_merge_pandas_python.txt
Q: How to export Azure Prices REST API to CSV I would like to save the whole Azure Prices REST API to CSV. In order to do so I have to query the endpoint https://prices.azure.com/api/retail/prices which ends with a: "NextPageLink":"https://prices.azure.com:443/api/retail/prices?$skip=100","Count":100} I wrote a Pyth...
How to export Azure Prices REST API to CSV
I would like to save the whole Azure Prices REST API to CSV. In order to do so I have to query the endpoint https://prices.azure.com/api/retail/prices which ends with a: "NextPageLink":"https://prices.azure.com:443/api/retail/prices?$skip=100","Count":100} I wrote a Python scripts that could help me grab that NextPage...
[ "To get all data from the API you can try (there are 4558 requests total):\nimport requests\nimport pandas as pd\n\nurl = \"https://prices.azure.com/api/retail/prices\"\n\nall_data = []\nwhile True:\n print(url)\n data = requests.get(url).json()\n all_data.extend(data[\"Items\"])\n if data[\"NextPageLin...
[ 1 ]
[]
[]
[ "json", "pandas", "python", "rest", "web_scraping" ]
stackoverflow_0074438621_json_pandas_python_rest_web_scraping.txt
Q: How is "secret_key.txt" more secure in Django project? I apologize if this is a duplicate question but I can't find an answer online. In Django Checklist Docs I see the following to keep secret key secure. with open('/etc/secret_key.txt') as f: SECRET_KEY = f.read().strip() My project is deployed with AWS EBS...
How is "secret_key.txt" more secure in Django project?
I apologize if this is a duplicate question but I can't find an answer online. In Django Checklist Docs I see the following to keep secret key secure. with open('/etc/secret_key.txt') as f: SECRET_KEY = f.read().strip() My project is deployed with AWS EBS. I've created a separate file called "secret_key.txt" which...
[ "You usually add that file to the .gitignore, such that the file is not part of the (GitHub) repository. This means that you can add (other) settings in the project, and you load \"sensitive\" settings through environment variables, or files.\nThis hackernoon post for example, discusses four ways to define sensitiv...
[ 8 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074438709_django_python.txt
Q: python: ValueError: too many values to unpack (expected 2) data from excell I want to take data from excel and plot 2D kernel density estimate in python, but it says "ValueError: too many values to unpack (expected 2)". how to fix it? following the coding: # libraries import matplotlib.pyplot as plt from scipy.sta...
python: ValueError: too many values to unpack (expected 2) data from excell
I want to take data from excel and plot 2D kernel density estimate in python, but it says "ValueError: too many values to unpack (expected 2)". how to fix it? following the coding: # libraries import matplotlib.pyplot as plt from scipy.stats import kde import pandas as pd # create data x = pd.read_excel(r'C:\Users\Ez...
[ "When you're getting an error from your code, it would help to pose the actual traceback, especially the part that indicates which line of your sample code is causing the error.\nWhen you call a function that returns multiple values, you can \"unpack\" it into individual variables. ValueError: too many values to u...
[ 4, 0 ]
[]
[]
[ "gaussian", "kernel", "pandas", "python" ]
stackoverflow_0067458085_gaussian_kernel_pandas_python.txt
Q: How do I include integers in a string in Python? import random q = random.randint(10, 100) w = random.randint(10, 100) e = (q, " * ", w) r = int(input(e)) This outputs (i.e): >>> (60, ' * ', 24) I tried following this post but I faced an error. I want output to atleast look like: >>> (60 * 24) What I tried was...
How do I include integers in a string in Python?
import random q = random.randint(10, 100) w = random.randint(10, 100) e = (q, " * ", w) r = int(input(e)) This outputs (i.e): >>> (60, ' * ', 24) I tried following this post but I faced an error. I want output to atleast look like: >>> (60 * 24) What I tried was doing import random q = random.randint(10, 100) w...
[ "A great way to do this is with f-strings\ne = f\"{q} * {w}\"\n\nYou just need to start your string with an f, then include any variables in curly braces {}\n", "Your value e has mixed types. q and w are ints while the string is a string. Python prints the types in the tuple as their types. Those quotation marks ...
[ 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0074438710_python.txt
Q: Wrapper causes change in the funcName attribute in custom python logger I have created a wrapper in custom python logger to add additional attributes in the log formatter. logFormat = logging.Formatter('[%(levelname)s],[%(asctime)-15s], %(API_SERVER)s, %(funcName)s,%(lineno)d, %(message)s') Additional Attribute -...
Wrapper causes change in the funcName attribute in custom python logger
I have created a wrapper in custom python logger to add additional attributes in the log formatter. logFormat = logging.Formatter('[%(levelname)s],[%(asctime)-15s], %(API_SERVER)s, %(funcName)s,%(lineno)d, %(message)s') Additional Attribute -> API_SERVER The log shows the wrapper method as the funcName instead of actu...
[ "The wrong function name is happening because loggingMethodsWrapper is the one actually doing the call to log.\n\nWhat you want seems to be function that calls loggingMethodsWrapper. The fix is to change your formatter so that it doesn't include %(funcName)s and move that to be part of the arguments passed to %(mes...
[ 1, 1, 0, 0, 0 ]
[]
[]
[ "logging", "python", "wrapper" ]
stackoverflow_0044164587_logging_python_wrapper.txt
Q: How to query blockchain for latest smart contract deployments with web3.py? How would I get a list of addresses of the newest smart contracts deployed to the ethereum blockchain? I would like to use web3.py if possible or a free api solution. I need the contract address and the time of deployment in the returned r...
How to query blockchain for latest smart contract deployments with web3.py?
How would I get a list of addresses of the newest smart contracts deployed to the ethereum blockchain? I would like to use web3.py if possible or a free api solution. I need the contract address and the time of deployment in the returned results. If possible I would like a solution that is cross chain compatible. Thank...
[ "\nget a list of addresses of the newest smart contracts deployed to the ethereum blockchain\n\nEthereum nodes do not index this information in their internal database, so you cannot query directly.\nYou can do this by walking through the transactions of each new block, then picking up transactions that contract de...
[ 1, 0 ]
[]
[]
[ "blockchain", "ethereum", "python", "smartcontracts", "web3py" ]
stackoverflow_0074381837_blockchain_ethereum_python_smartcontracts_web3py.txt
Q: Vectorized way to find first occurrence per row I have two Pandas DataFrames df_x and df_y. df_x has two columns 'high target' and 'low target'. Per every row of df_x, I would like to search through the instances of df_y and see whether the 'high target' was reached before the 'low target'. Currently, I implemente...
Vectorized way to find first occurrence per row
I have two Pandas DataFrames df_x and df_y. df_x has two columns 'high target' and 'low target'. Per every row of df_x, I would like to search through the instances of df_y and see whether the 'high target' was reached before the 'low target'. Currently, I implemented the above using .apply. However, my code is too ine...
[ "This is what you could do:\nFirst of all put the open column in your main dataframe, let's call it df (note: this only works if you have the exact same index on df_y, if you don't, consider other solutions like pd.concat or pd.merge_asof)\ndf = df_x\ndf[\"open\"] = df_y[\"open\"]\n\nI also took the liberty of rena...
[ 0, 0 ]
[]
[]
[ "pandas", "performance", "python", "vectorization" ]
stackoverflow_0072449562_pandas_performance_python_vectorization.txt
Q: How can I install the latest Anaconda with wget I'm looking at installing anaconda via wget on my server. I've come across https://askubuntu.com/questions/505919/installing-anaconda-python-on-ubuntu and http://ericjonas.com/anaconda.html and it looks promising . As of this writing the current version( https://www....
How can I install the latest Anaconda with wget
I'm looking at installing anaconda via wget on my server. I've come across https://askubuntu.com/questions/505919/installing-anaconda-python-on-ubuntu and http://ericjonas.com/anaconda.html and it looks promising . As of this writing the current version( https://www.continuum.io/downloads#_unix ) is 4.0 . How can I wge...
[ "wget just downloads the file...\nfor python 2.7 :\nwget https://repo.continuum.io/archive/Anaconda2-2018.12-Linux-x86_64.sh\n\nfor python3.X:\nwget https://repo.continuum.io/archive/Anaconda3-2018.12-Linux-x86_64.sh\n\nThis is a shell script that guides you though the install. \nRun the following line inside of th...
[ 40, 15, 6, 1, 0, 0 ]
[]
[]
[ "anaconda", "linux", "python", "wget" ]
stackoverflow_0038080407_anaconda_linux_python_wget.txt
Q: Convert strings in a list to dataframe - Python I have scraped the necesary items from a PDF to convert it to a dataframe, but im having a hard time to correctly organizating the rows and columns. # open the PDF as an object and read it into PyPDF2. pdfFileObj = open('/FuentesDeDatos/AltaVista-Datos/lista3-pes.pdf...
Convert strings in a list to dataframe - Python
I have scraped the necesary items from a PDF to convert it to a dataframe, but im having a hard time to correctly organizating the rows and columns. # open the PDF as an object and read it into PyPDF2. pdfFileObj = open('/FuentesDeDatos/AltaVista-Datos/lista3-pes.pdf', 'rb') pdfReader = PyPDF2.PdfFileReader(pdfFileObj)...
[ "You can try:\nimport re\nimport pandas as pd\nfrom itertools import groupby\n\npage1 = [\n \"001-12 Discos rígidos\",\n \"1779 HD 1 TB SATA 3 WD BLUE 64MB WD10EZEX,$ 9.041.78,1860 HD 2 TB SATA 3 WD BLUE 64MB WD20EZAZ,$ 10.467.19,1986 HD 2 TB SATA 6 SEAGATE BARRACUDA,$ 11.588.09,3119 HD 1 TB SATA 6 SEAGATE BA...
[ 0 ]
[]
[]
[ "dataframe", "list", "pandas", "python", "string" ]
stackoverflow_0074438650_dataframe_list_pandas_python_string.txt
Q: calculate the average of each dimension defining the group in python I have a dataframe (df) that has three columns (user, vector, and group name), the vector column with multiple comma-separated values in each row. df = pd.DataFrame({'user': ['user_1', 'user_2', 'user_3', 'user_4', 'user_5', 'user_6'], 'vector':...
calculate the average of each dimension defining the group in python
I have a dataframe (df) that has three columns (user, vector, and group name), the vector column with multiple comma-separated values in each row. df = pd.DataFrame({'user': ['user_1', 'user_2', 'user_3', 'user_4', 'user_5', 'user_6'], 'vector': [[1, 0, 2, 0], [1, 8, 0, 2],[6, 2, 0, 0], [5, 0, 2, 2], [3, 8, 0, 0],[6, ...
[ "I'm not sure if you were looking for the results stored in a single array/dataframe, or if you're just looking to get the results as separate arrays.\nIf the latter, something like this should work for you:\nfor group in df.group.unique():\n print(f'Group {group} results: ')\n tmp_df = pd.DataFrame(df[df.gro...
[ 1, 0 ]
[]
[]
[ "dataframe", "grouping", "pandas", "python" ]
stackoverflow_0074438566_dataframe_grouping_pandas_python.txt
Q: how can I open (or create) list_{i}=[] I edited this to specifics: see part B for specifics: updated agian, a dictionary does not work because it's values aren't' indexed. *''' I have a bunch of lists names that vary slightly. And rather than writing the code that manipulates these lists multiple times, how can I ...
how can I open (or create) list_{i}=[]
I edited this to specifics: see part B for specifics: updated agian, a dictionary does not work because it's values aren't' indexed. *''' I have a bunch of lists names that vary slightly. And rather than writing the code that manipulates these lists multiple times, how can I input the name of the list to open? so: (and...
[ "You should never get a user to provide input which should then be matched to variable names (like the names of list variables). If you need data in a data structure where a specific element should be selected based on user input, use a dictionary instead, so that you can access the appropriate list in the dictiona...
[ 2 ]
[]
[]
[ "list", "numpy", "python" ]
stackoverflow_0074438805_list_numpy_python.txt
Q: Grayscale doesn't seem to be working, even with proper confidence import pyautogui import time dir = 'ingame/' while True: time.sleep(1) test = pyautogui.locateOnScreen(dir + 'test2.png',grayscale=False,confidence=.7) if test: print('found') This is the code I'm running, I have the same image...
Grayscale doesn't seem to be working, even with proper confidence
import pyautogui import time dir = 'ingame/' while True: time.sleep(1) test = pyautogui.locateOnScreen(dir + 'test2.png',grayscale=False,confidence=.7) if test: print('found') This is the code I'm running, I have the same image, with and without grayscale. Pyautogui still detects the grayscale im...
[ "import pyautogui\nimport time\n\ntime.sleep(5)\nimage = 'overwatch.png'\nloc = pyautogui.locateOnScreen(image, grayscale=False, confidence=.3)\nprint (loc)\n\noutput\nBox(left=405, top=778, width=88, height=93)\n\nbut as Tim said above it's more complicated with grayscale than in RGB mode\n" ]
[ 0 ]
[]
[]
[ "pyautogui", "python" ]
stackoverflow_0074438767_pyautogui_python.txt
Q: How could I get an am/pm date format? I have this code: arr=pd.date_range(start='1/1/2021', end='12/31/2021 23:00:00', freq='h') df = pd.DataFrame({'year': arr.year}) dg = pd.DataFrame({'month': arr.month}) dh = pd.DataFrame({'day': arr.day}) di = pd.DataFrame({'hour': arr.hour,'minute': arr.minute,'second': arr....
How could I get an am/pm date format?
I have this code: arr=pd.date_range(start='1/1/2021', end='12/31/2021 23:00:00', freq='h') df = pd.DataFrame({'year': arr.year}) dg = pd.DataFrame({'month': arr.month}) dh = pd.DataFrame({'day': arr.day}) di = pd.DataFrame({'hour': arr.hour,'minute': arr.minute,'second': arr.second}) I would like to get a csv format...
[ "I think this may be what you are looking for\ntimevalue_12hour = time.strftime( \"%I:%M %p\", t )\n\nthis would convert a time from datetime 24 hours format to 12 hours, the %I would convert the hour from 23 to 11 and the %p would get you the AM/PM value.\n", "For any time format that you want you can use .strft...
[ 2, 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074438860_dataframe_pandas_python.txt
Q: Python static typing: Annotating multiple returns types In short, I have a function that returns either int or float. The caller function then checks the return-type of the first function and return -1 if float else return the original value since it must be int. # pseudo code for the aforementioned def f1(*args...
Python static typing: Annotating multiple returns types
In short, I have a function that returns either int or float. The caller function then checks the return-type of the first function and return -1 if float else return the original value since it must be int. # pseudo code for the aforementioned def f1(*args, **kwargs) -> int | float: ... def f2(*args, **kwargs) -> ...
[ "You need to check with isinstance:\ndef f1(*args, **kwargs) -> int | float: ... \n\ndef f2(*args, **kwargs) -> int:\n ans = f1(...)\n if isinstance(ans, float):\n return -1\n # now the typechecker can infer the type of 'ans' as int\n return ans \n\nMore info in Mypy documentation\n" ]
[ 1 ]
[]
[]
[ "annotations", "mypy", "python" ]
stackoverflow_0074438790_annotations_mypy_python.txt
Q: Replace special characters in pandas dataframe from a string of special characters I have created a pandas dataframe called df using this code: import numpy as np import pandas as pd ds = {'col1' : ['1','3/','4'], 'col2':['A','!B','@C']} df =pd.DataFrame(data=ds) The dataframe looks like this: print(df) col1 ...
Replace special characters in pandas dataframe from a string of special characters
I have created a pandas dataframe called df using this code: import numpy as np import pandas as pd ds = {'col1' : ['1','3/','4'], 'col2':['A','!B','@C']} df =pd.DataFrame(data=ds) The dataframe looks like this: print(df) col1 col2 0 1 A 1 3/ !B 2 4 @C The columns contain some special characters (/...
[ "You can use apply with str.replace:\nimport re\nchars = ''.join(map(re.escape, listOfSpecialChars))\n\ndf2 = df.apply(lambda c: c.str.replace(f'[{chars}]', '', regex=True))\n\nAlternatively, stack/unstack:\ndf2 = df.stack().str.replace(f'[{chars}]', '', regex=True).unstack()\n\noutput:\n col1 col2\n0 1 A\n1...
[ 1, 0 ]
[]
[]
[ "pandas", "python", "replace", "special_characters" ]
stackoverflow_0072630943_pandas_python_replace_special_characters.txt
Q: Unexpected datetime differencing with Python 3 I am using Python 3 - Linux Rocky 8. I am not getting the expected results when subtracting datetime objects. import datetime x = datetime.datetime.strptime('11 Nov 2022 17:36', '%d %b %Y %H:%M') y = datetime.datetime.strptime('10 Nov 2022 17:30', '%d %b %Y %H:%M') z ...
Unexpected datetime differencing with Python 3
I am using Python 3 - Linux Rocky 8. I am not getting the expected results when subtracting datetime objects. import datetime x = datetime.datetime.strptime('11 Nov 2022 17:36', '%d %b %Y %H:%M') y = datetime.datetime.strptime('10 Nov 2022 17:30', '%d %b %Y %H:%M') z = (x - y).seconds print(str(z)) 360 y = datetime.da...
[ "You're printing the .seconds attribute of a timedelta object. Not the total seconds\nLook at x - y directly. In the first case.\ndatetime.timedelta(days=1, seconds=360)\n\nIn the second\ndatetime.timedelta(seconds=86160)\n\nThe seconds attribute will never be negative, and you do not have a full day.\nPerhaps you ...
[ 1 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0074438866_datetime_python.txt
Q: Plot big dataset in pandas I have time serie of measurements of temeprature and light: no,DateTime,Temp,Light 1,11/09/2022 00:01:20,18.10,21.27 2,11/09/2022 00:01:30,18.19,41.70 3,11/09/2022 00:01:40,18.36,5.94 ... each measurement is taken every 10 seconds and I have ~40 000 of measurements sorted by dates. Now ...
Plot big dataset in pandas
I have time serie of measurements of temeprature and light: no,DateTime,Temp,Light 1,11/09/2022 00:01:20,18.10,21.27 2,11/09/2022 00:01:30,18.19,41.70 3,11/09/2022 00:01:40,18.36,5.94 ... each measurement is taken every 10 seconds and I have ~40 000 of measurements sorted by dates. Now I would like to plot a line char...
[ "You can resample to a lower frequency (here 1 hour):\ndf['DateTime'] = pd.to_datetime(df['DateTime'])\n\n(df.resample('1h', on='DateTime')\n ['Light'].mean()\n .plot()\n )\n\n" ]
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074438853_pandas_python.txt
Q: Adjacency Matrix Class I was wondering how to create a method that would return a list of neighbors of vertex u and also a method that returns true if two vertices are adjacent to each other in a matrix. I also wanted to know if I was setting up my matrix correctly. I saw a solution for an adjacency list but I thi...
Adjacency Matrix Class
I was wondering how to create a method that would return a list of neighbors of vertex u and also a method that returns true if two vertices are adjacent to each other in a matrix. I also wanted to know if I was setting up my matrix correctly. I saw a solution for an adjacency list but I think the setup for a matrix is...
[ "I feel I basically just answered this; (Did flag as dup)\nCreating an adjacency list class in Python\n class Matrix:\n def __init__(self, size):\n self.matrix = [[0 for x in range(size)] for y in range(size)]\n\n def addEdge(self, u, v):\n self.matrix[u][v] = 1\n\n def deleteEdge(self, u, ...
[ 0 ]
[]
[]
[ "adjacency_matrix", "python" ]
stackoverflow_0074438969_adjacency_matrix_python.txt
Q: M1 Mac Tensorflow VS Code Rosetta2 I'm struggling to install tensorflow with a M1 mac. I've got python 3.9.7 and Monterrey 12.3 and apple silicon visual studio code. There is an apple solution involving miniconda apple dependancies and tensorflow-macos and tensorflow-metal. However this solution is not good for me...
M1 Mac Tensorflow VS Code Rosetta2
I'm struggling to install tensorflow with a M1 mac. I've got python 3.9.7 and Monterrey 12.3 and apple silicon visual studio code. There is an apple solution involving miniconda apple dependancies and tensorflow-macos and tensorflow-metal. However this solution is not good for me as I have to use Rosetta2 emulator for ...
[ "Running TensorFlow on miniforge + conda-forge (arm64)\nTensorFlow can run natively on M1 (arm64) macs. A highly recommended, easy way to install TensorFlow on arm64 macs is to via conda-forge. You should install python via miniforge or miniconda, because there is an arm64 (Apple Sillicon) distribution. With this, ...
[ 1 ]
[]
[]
[ "apple_m1", "python", "rosetta", "tensorflow" ]
stackoverflow_0073461385_apple_m1_python_rosetta_tensorflow.txt
Q: JAR's signer information conflict with another class I'm trying to load two jars into my AWS Glue/Spark read method but got an error: An error occurred while calling o142.save. : java.lang.SecurityException: class "com.microsoft.sqlserver.jdbc.ISQLServerBulkData"'s signer information does not match signer informat...
JAR's signer information conflict with another class
I'm trying to load two jars into my AWS Glue/Spark read method but got an error: An error occurred while calling o142.save. : java.lang.SecurityException: class "com.microsoft.sqlserver.jdbc.ISQLServerBulkData"'s signer information does not match signer information of other classes in the same package at java.lang....
[ "Using com.microsoft.sqlserver:mssql-jdbc:8.4.1.jre8 is one thing but also you need proper version of MS' Spark SQL Connector\ncom.microsoft.azure:spark-mssql-connector_2.12_3.0:1.0.0-alpha and com.microsoft.sqlserver:mssql-jdbc:8.4.1.jre8 did not work for my case as I'm using AWS Glue 3.0 (which is Spark 3.1)\nI h...
[ 0 ]
[]
[]
[ "apache_spark", "aws_glue", "jar", "python", "sql" ]
stackoverflow_0074435120_apache_spark_aws_glue_jar_python_sql.txt
Q: Drop rows WHERE date is a certain condition Pandas I have a dataset where I would like to remove all rows where the date is 4/1/2022 within a column in my dataset. The Date column is datetime64ns Data ID Date AA 1/1/2022 BB 1/1/2022 CC 4/1/2022 Desired ID Date AA 1/1/2022 BB 1/1/2022 Doing new = df[df['Date']...
Drop rows WHERE date is a certain condition Pandas
I have a dataset where I would like to remove all rows where the date is 4/1/2022 within a column in my dataset. The Date column is datetime64ns Data ID Date AA 1/1/2022 BB 1/1/2022 CC 4/1/2022 Desired ID Date AA 1/1/2022 BB 1/1/2022 Doing new = df[df['Date'].str.contains('4/1/2022')==False] However, this is not ...
[ "Use boolean indexing:\ndf[df['Date'].ne('2022-04-01')]\n\nOutput:\n ID Date\n0 AA 2022-01-01\n1 BB 2022-01-01\n\nIf for some reason you need to use drop (e.g. to modify a DataFrame in place):\nm = df['Date'].eq('2022-04-01')\n\ndf.drop(m[m].index, inplace=True)\n\nmultiple dates\ndf[~df['Date'].isin(['20...
[ 2, 1 ]
[]
[]
[ "datetime", "numpy", "pandas", "python" ]
stackoverflow_0074438906_datetime_numpy_pandas_python.txt
Q: what's the difference between pandas DataFrame methods agg() and apply()? There are a number of SO questions regarding agg and apply on pandas DataFrame.groupby() objects, but I don't understand the difference between DataFrame.agg() and DataFrame.apply(). From the docs and the snippet below, they look the same to...
what's the difference between pandas DataFrame methods agg() and apply()?
There are a number of SO questions regarding agg and apply on pandas DataFrame.groupby() objects, but I don't understand the difference between DataFrame.agg() and DataFrame.apply(). From the docs and the snippet below, they look the same to me. If there are issues specifically related to row operations that don't appl...
[ "They both actually call the same frame_apply(...) function with generally the same things going into them. One difference is that df.agg() (which actually itself is identical to df.aggregate()) has a step where it calls a reconstruct_func() function that does a little bit of cleanup/handling of what func you pass ...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074438891_dataframe_pandas_python.txt
Q: What is a reason to use warnings instead of print? I wonder what is the advantage of using warnings.warn over using just print and why should I use it. Not only the code is a bit more messy, but also the warnings.warn's output: /path/to/script/script.py:42: UserWarning: Warning message. warn("Warning message.", ...
What is a reason to use warnings instead of print?
I wonder what is the advantage of using warnings.warn over using just print and why should I use it. Not only the code is a bit more messy, but also the warnings.warn's output: /path/to/script/script.py:42: UserWarning: Warning message. warn("Warning message.", stacklevel=1) I just don't see a need to print a script...
[ "warnings.warn is different from print.\nIt could show different kind of Warnings: Categories\nThese warnings could be filtered: enter link description here\nSo Warnings are very configurable, could be printed (stderr), do nothing, or thrown an Exception.\nLogging is another thing completely different, I would say ...
[ 0 ]
[]
[]
[ "python", "warnings" ]
stackoverflow_0074438631_python_warnings.txt
Q: Why are we using Square Brackets in python to access MIMEMultipart() components like ['From'], ['To'] for sending email using python? In a python code, which is sending an email using "smtplib" and "MIMEMultipart" libraries, I got a doubt on, why we are using "square brackets" for ['From'], ['To'] and ['Subject'] ...
Why are we using Square Brackets in python to access MIMEMultipart() components like ['From'], ['To'] for sending email using python?
In a python code, which is sending an email using "smtplib" and "MIMEMultipart" libraries, I got a doubt on, why we are using "square brackets" for ['From'], ['To'] and ['Subject'] when referring to "MIMEMultipart ()". Could any anyone explain on this part ? Below is the code snipet, observe the commenting lines : impo...
[ "You're not accessing; you're setting.\nMIMEMultipart defines a magic method __setitem__ which defines the syntax for OBJECT[key] = value\n\nThe conceptual model provided by an EmailMessage object is that of an ordered dictionary of headers coupled with a payload that represents the RFC 5322 body of the message\n\n...
[ 1 ]
[]
[]
[ "list", "mimemultipart", "python", "smtplib" ]
stackoverflow_0074439060_list_mimemultipart_python_smtplib.txt
Q: Using a list as input to a function I have a function that translates subnet IPs into IP ranges, but I need to input a list of subnets to this function and I am having trouble doing it: My function at the moment: import ipaddress cidr = ["187.11.62.93,187.11.62.95"] def get_ip_range(cidr): net = ipaddress.ip_...
Using a list as input to a function
I have a function that translates subnet IPs into IP ranges, but I need to input a list of subnets to this function and I am having trouble doing it: My function at the moment: import ipaddress cidr = ["187.11.62.93,187.11.62.95"] def get_ip_range(cidr): net = ipaddress.ip_network(cidr) return net[0], net[-1]...
[ "Your list is global, so there is no need to pass it as parameter.\nAlso you did not put a comma nor quotation marks in your list (See below).\nI am not entirely sure what you want to do, but your now you can pass the list :)\nimport ipaddress\n\n\ncidr = [\"187.11.62.93\", \"187.11.62.95\"] # cidr[0] = 187.11.62.9...
[ 0 ]
[]
[]
[ "function", "python" ]
stackoverflow_0074435755_function_python.txt
Q: How to expand dictionaries in rows of pandas dataframe with unique column names? I have a dataframe with rows as dictionaries as below: Col1 A B {'A': 1, 'B': 23} apple carrot {'A': 3, 'B': 35} banana spinach I want to expand Col1 such that the dataframe looks like this: Col1.A Col2.B A...
How to expand dictionaries in rows of pandas dataframe with unique column names?
I have a dataframe with rows as dictionaries as below: Col1 A B {'A': 1, 'B': 23} apple carrot {'A': 3, 'B': 35} banana spinach I want to expand Col1 such that the dataframe looks like this: Col1.A Col2.B A B 1 23 apple carrot 3 35 banana spinach How can I do this us...
[ "df[\"Col1.A\"] = df[\"Col1\"].map(lambda x: x[\"A\"])\ndf[\"Col1.B\"] = df[\"Col1\"].map(lambda x: x[\"B\"])\ndf.drop(\"Col1\", axis=1, inplace=True)\n\n", "As a generic method that doesn't require knowledge of the dictionary keys:\ndf = (pd.json_normalize(df.pop('Col1'))\n .add_prefix('Col1.').join(df)\n...
[ 3, 2, 2 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074439019_dataframe_pandas_python.txt
Q: How to debug the loop in my Python hangman game I am trying to create a hangman game but there is a problem. Whenever I run my code the random.choice(words_to_guess) chooses a word and when I write the word it has chosen and it's the correct word, it does not stop. It keeps going in loops. What can I do to make st...
How to debug the loop in my Python hangman game
I am trying to create a hangman game but there is a problem. Whenever I run my code the random.choice(words_to_guess) chooses a word and when I write the word it has chosen and it's the correct word, it does not stop. It keeps going in loops. What can I do to make stop the loop? import random lives = 10 def welcome()...
[ "If you guess a correct letter the while loop will run forever as it never changes the variable called user. Instead of using a while loop, you should be using an if.\ndef game_correct():\n user = input(\"enter a letter: \")\n if user in computer:\n print(\"Correct guess\")\n\nShould point you in the r...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074439080_python.txt
Q: How to call pass javascript value as parameter to python function I have a HTML input and onClick with a button, I get the value of text input and store in a varibale in Javascipt. Now how can I use this varibale as a paramter to a python function? In JavaScript I have: var text = document.getElementById("text").v...
How to call pass javascript value as parameter to python function
I have a HTML input and onClick with a button, I get the value of text input and store in a varibale in Javascipt. Now how can I use this varibale as a paramter to a python function? In JavaScript I have: var text = document.getElementById("text").value; and in Python I have: someFunction(text): print(text) # text ...
[ "You can submit the form to send values to a Python file or use API's with Ajax this article about difference between server-side and client-side.\nAnd in regard to @JohnHanley comment you can use py-script to do that, take a look here\n\n\n<link rel=\"stylesheet\" href=\"https://pyscript.net/latest/pyscript.css\" ...
[ 0, 0 ]
[]
[]
[ "html", "javascript", "pyscript", "python" ]
stackoverflow_0074439139_html_javascript_pyscript_python.txt
Q: python notebook Callgraph I am trying to creat a callgraph of my python code in Notebook. I tried the %callgraph and it seems to work only for one level (i.e., great for recursive functions). So, it only shows the first level of the tree. Am I doing something wrong? is there another way to create call graphs for p...
python notebook Callgraph
I am trying to creat a callgraph of my python code in Notebook. I tried the %callgraph and it seems to work only for one level (i.e., great for recursive functions). So, it only shows the first level of the tree. Am I doing something wrong? is there another way to create call graphs for python/notebook?
[ "Q: Am I doing something wrong?\nA: Unless you show us what you have done, we cannot answer that.\nQ: Is there another way to create call graphs for python/notebook?\nA: Yes, most certainly.\nThere are many 'callgraph' out there. Which one have you used?\n\nI tried the %callgraph and it seems to work only for one l...
[ 0 ]
[ "try use -w flag. for example,\n%callgraph -w10 lev(\"big\", \"dog\"); lev(\"dig\", \"dog\")\nsource: https://callgraph.readthedocs.io/en/latest/\n" ]
[ -1 ]
[ "call_graph", "jupyter_notebook", "python" ]
stackoverflow_0066082777_call_graph_jupyter_notebook_python.txt
Q: how to find the most frequent character in each postion of multiple strings I have a list of words with different length. I want to find the most frequent character in each position of all words. what is the efficient way to do that and prevent the Error index out of range in different length strings? for example:...
how to find the most frequent character in each postion of multiple strings
I have a list of words with different length. I want to find the most frequent character in each position of all words. what is the efficient way to do that and prevent the Error index out of range in different length strings? for example: alist = ['fowey', 'tynemouth', 'unfortunates', 'patroness', 'puttying', 'presump...
[ "Try:\nfrom collections import Counter\n\nalist = [\n \"fowey\",\n \"tynemouth\",\n \"unfortunates\",\n \"patroness\",\n \"puttying\",\n \"presumptuousness\",\n \"lustrous\",\n \"gloxinia\",\n]\n\nfor i in (\n (w[idx] if idx < len(w) else None for w in alist)\n for idx in range(len(max...
[ 2 ]
[]
[]
[ "algorithm", "list", "python", "python_3.x" ]
stackoverflow_0074439160_algorithm_list_python_python_3.x.txt
Q: How to display the final calculation of a list once without it being displayed as many times as there are items in a list? I am new to python and would like some help please. Please refer to the screenshots in this post. I have iniated a list and need to calculate the total average marks inputted by the user and d...
How to display the final calculation of a list once without it being displayed as many times as there are items in a list?
I am new to python and would like some help please. Please refer to the screenshots in this post. I have iniated a list and need to calculate the total average marks inputted by the user and display the total average marks. The problem seems like the total average marks is being displayed as many times as there is an i...
[ "There is no need to include a loop in your code. The sum and len functions take care of iterating over the list.\nprint(sum(marks_collection)/len(marks_collection))\n\nIs enough.\nAs a side note, you can and should add the code to your question. Copying it into the question is enough but if you put ``` above and b...
[ 0 ]
[]
[]
[ "list", "loops", "python" ]
stackoverflow_0074438952_list_loops_python.txt
Q: Python: Working with configparser inside a class. How to access my attributes names and values dynamically inside my class-methods My first program is getting much bigger than excepted. :) import configparser config = configparser.ConfigParser() configfile = 'RealGui.ini' class FolderLeftSettings: ...
Python: Working with configparser inside a class. How to access my attributes names and values dynamically inside my class-methods
My first program is getting much bigger than excepted. :) import configparser config = configparser.ConfigParser() configfile = 'RealGui.ini' class FolderLeftSettings: def __init__(self): self.name = "SECTION" self.last_directory = "" self.row_size = 6 self.column_size = ...
[ "My comments were getting lengthy, so here is a post:\nDynamically Accessing Attributes\nAs per this answer, you can access attributes for an instance using vars(my_object).\nIt became more clear from our discussion, because the original post didn't include some details, but you can access instance variables, like ...
[ 1, 1 ]
[]
[]
[ "class", "configparser", "ini", "python" ]
stackoverflow_0074426517_class_configparser_ini_python.txt
Q: Pandas timedelta calculations for common sense late/early differences My dataframe has two timestamp columns and I need to add a third time difference column. How do I get common sense time difference between an expected time and the actual time? If your expected time is 0800 and you're early at 0730, then you get...
Pandas timedelta calculations for common sense late/early differences
My dataframe has two timestamp columns and I need to add a third time difference column. How do I get common sense time difference between an expected time and the actual time? If your expected time is 0800 and you're early at 0730, then you get common sense output: t1 = pd.to_datetime('1/1/2022 08:00') t2 = pd.to_date...
[ "You should use total_seconds, not seconds:\npd.Timedelta(t1-t2).total_seconds()/60\n\nOutput: -30\n" ]
[ 1 ]
[]
[]
[ "pandas", "python", "timedelta" ]
stackoverflow_0074439233_pandas_python_timedelta.txt
Q: Check for specific character in if statement I wanted to ask a question today, that how can I use the dataframe.str.contains function to search for a specific character in a if statement. I will elaborate the details in the following, and Thank you everyone for helping me. So I want to do a calculation through the...
Check for specific character in if statement
I wanted to ask a question today, that how can I use the dataframe.str.contains function to search for a specific character in a if statement. I will elaborate the details in the following, and Thank you everyone for helping me. So I want to do a calculation through the data, but first I need to sort the data by using ...
[ "Your code checks the whole column for the character not element-by-element. You can use the numpy where function (note there is a pandas where function but it works in a slightly different way). So your code could be:\nimport numpy as np # better placed with other imports\n\ndf['Price'] = np.where(df['ColumnA']...
[ 0 ]
[]
[]
[ "if_statement", "python" ]
stackoverflow_0074438905_if_statement_python.txt
Q: How can I trim only (10) numbers in Python hashCode = 0x39505b04f1c2e5c03ea3 I want to see only 10 characters, How ? A: If you want to see the first 10 characters: hashCode = '0x39505b04f1c2e5c03ea3' print(hashCode[:10]) outputs: '0x39505b04' If you want to instead see the last 10 characters: hashCode = '0x3...
How can I trim only (10) numbers in Python
hashCode = 0x39505b04f1c2e5c03ea3 I want to see only 10 characters, How ?
[ "If you want to see the first 10 characters:\nhashCode = '0x39505b04f1c2e5c03ea3'\n\nprint(hashCode[:10])\n\noutputs:\n'0x39505b04'\n\nIf you want to instead see the last 10 characters:\nhashCode = '0x39505b04f1c2e5c03ea3'\n\nprint(hashCode[10:])\n\noutputs:\n'f1c2e5c03ea3'\n\n" ]
[ 1 ]
[]
[]
[ "hash", "numbers", "python", "trim" ]
stackoverflow_0074439302_hash_numbers_python_trim.txt
Q: Pandas: copying values of a certain row based on a different column What I'm trying to achieve is that when a row in col2 has a 1, it will copy that 1 onto all the other values in col2 as long as the rows in col1 have the same name. As an example, if the dataframe looks like this col1 col2 xx 1 xx 0 xx ...
Pandas: copying values of a certain row based on a different column
What I'm trying to achieve is that when a row in col2 has a 1, it will copy that 1 onto all the other values in col2 as long as the rows in col1 have the same name. As an example, if the dataframe looks like this col1 col2 xx 1 xx 0 xx 0 xx 0 yy 0 yy 0 yy 0 zz 0 zz 0 zz ...
[ "Use groupby.transform('max'):\ndf['col2'] = df.groupby('col1')['col2'].transform('max')\n\nOutput:\n col1 col2\n0 xx 1\n1 xx 1\n2 xx 1\n3 xx 1\n4 yy 0\n5 yy 0\n6 yy 0\n7 zz 1\n8 zz 1\n9 zz 1\n\n", "The generic trick here is to perform a .groupby that ...
[ 6, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074439252_dataframe_pandas_python.txt
Q: What is the pythonic way to represent an Iterable that can be iterated over multiple times I would like to get your advice on the most pythonic way to express the following function in python with type hints: I'd like to expose a function as part of a library that accepts an input argument and returns an output. T...
What is the pythonic way to represent an Iterable that can be iterated over multiple times
I would like to get your advice on the most pythonic way to express the following function in python with type hints: I'd like to expose a function as part of a library that accepts an input argument and returns an output. The contract for the input argument should be that: my function can iterate over it it's ok if m...
[ "There are two natural ways of representing this that I can think of.\nThe first would be to use Iterable[str], and mention in the documentation, that Iterator and Generator objects should not be used since you may have multiple calls to __iter__. The whole point of Iterable is that you can get an iterator on it, a...
[ 1, 0 ]
[]
[]
[ "api_design", "python", "type_hinting" ]
stackoverflow_0063104689_api_design_python_type_hinting.txt
Q: Restrict access per customer in django I am trying to restrict access to records based on each customer so users can't access each others data through URL. I have added this but its restricting everything. if request.user.customer != Infringement.customer: return HttpResponse('Your are not allowed ...
Restrict access per customer in django
I am trying to restrict access to records based on each customer so users can't access each others data through URL. I have added this but its restricting everything. if request.user.customer != Infringement.customer: return HttpResponse('Your are not allowed here!!')" views.py @login_required...
[ "Try:\n@login_required(login_url='login') \ndef infringement(request, pk): \n infringement = Infringement.objects.get(id=pk)\n if request.user.customer.id != infringement.customer.id:\n return HttpResponse('Your are not allowed here!!')\n\n" ]
[ 1 ]
[]
[]
[ "access_control", "django", "python", "security" ]
stackoverflow_0074439228_access_control_django_python_security.txt
Q: How to convert 01:00:00 into integer in Python? I need to convert a column of a dataframe that is in the format of HH:MM:SS as a string to an integer, for example: 01:00:00 to 01 or 1. data = ['01:00:00','02:00:00','03:00:00','04:00:00'] df = pd.DataFrame(data, columns=['Numbers']) I already tried the parameter as...
How to convert 01:00:00 into integer in Python?
I need to convert a column of a dataframe that is in the format of HH:MM:SS as a string to an integer, for example: 01:00:00 to 01 or 1. data = ['01:00:00','02:00:00','03:00:00','04:00:00'] df = pd.DataFrame(data, columns=['Numbers']) I already tried the parameter astype(int) but it does not accept the format 01:00:00
[ "df[\"Numbers\"] = df[\"Numbers\"].map(lambda x: int(x[:2]))\n\n" ]
[ 2 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074439311_dataframe_pandas_python.txt
Q: Repeating regex in Python I need to parse the line similar to the: '''Object{identifier='d6e461c5-fd55-42cb-b3e8-40072670fd0f', name='some_name2', identifier='d6e461c5-fd55-42cb-b3e8-40072670fd0f', name='some_name3', value=value_without_quotes}''' The line is much longer, but the pattern is the same. Basically, I...
Repeating regex in Python
I need to parse the line similar to the: '''Object{identifier='d6e461c5-fd55-42cb-b3e8-40072670fd0f', name='some_name2', identifier='d6e461c5-fd55-42cb-b3e8-40072670fd0f', name='some_name3', value=value_without_quotes}''' The line is much longer, but the pattern is the same. Basically, I need a list (or dict) with key...
[ "You may face this problem in an easier way.\nsentence = '''Object{identifier='d6e461c5-fd55-42cb-b3e8-40072670fd0f', name='some_name2', identifier='d6e461c5-fd55-42cb-b3e8-40072670fd0f', name='some_name3', value=value_without_quotes}'''\nlisting = [couple.split(\"=\") for couple in sentence.split(\",\")]\n\nFlat t...
[ 3, 1 ]
[]
[]
[ "python", "split", "string" ]
stackoverflow_0074438887_python_split_string.txt
Q: Creating a rect for each tile in Pygame to make collisions I am trying to create a rect for each tile in Pygame in order to make collisions- so enabling me to walk on blocks when I jump and not being able to run through a block. My map is a 2D list and I render it on the screen using for loops. I need help with co...
Creating a rect for each tile in Pygame to make collisions
I am trying to create a rect for each tile in Pygame in order to make collisions- so enabling me to walk on blocks when I jump and not being able to run through a block. My map is a 2D list and I render it on the screen using for loops. I need help with collisions and creating a rect for each tile- would I need to crea...
[ "One way of doing this, is to make a rectangle for each tile as the level1 like function iterates over all the tiles. You know the cell-position of the tile in the map, so multiplying this by the tile dimensions gives the rectangle parameters:\n`tile_rect = pygame.Rect( map_x * TILE_SIZE, map_y * TILE_SIZE, TILE_S...
[ 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074421370_pygame_python.txt
Q: Check if different word combinations exist in text using Python I want to write a function that finds certain word combinations in text and tells it belongs to which list. Example: my_list1 = ["Peter Parker", "Eddie Brock"] my_list2 = ["Harry Potter", "Severus Snape", "Dumbledore"] Example input: "Harry Potter wa...
Check if different word combinations exist in text using Python
I want to write a function that finds certain word combinations in text and tells it belongs to which list. Example: my_list1 = ["Peter Parker", "Eddie Brock"] my_list2 = ["Harry Potter", "Severus Snape", "Dumbledore"] Example input: "Harry Potter was very sad" Example output: my_list1
[ "You could iterate over the string and then append the occuring words into a list and then check for which words occur most to determine which list the whole string belongs to:\nmy_list1 = [\"Peter Parker\", \"Eddie Brock\"]\nmy_list2 = [\"Harry Potter\", \"Severus Snape\", \"Dumbledore\"]\n\n\nto_check = \"Harry P...
[ 0, 0, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0074438498_python_string.txt
Q: I have know idea how this is appending my list I have made a list of all number from 0 to 500 and then I am looking for all number that end with a certain integer. The thing is I don't under stand how its working. I am new to coding so don't know what to expect here or how it is working. x = 0 y = [] while x <= 50...
I have know idea how this is appending my list
I have made a list of all number from 0 to 500 and then I am looking for all number that end with a certain integer. The thing is I don't under stand how its working. I am new to coding so don't know what to expect here or how it is working. x = 0 y = [] while x <= 500: y.append(x) x = x + 1 a = 0 b = [] c = 0...
[ "The short answer is\nc = 0\nb = [x for x in range(501) if x % 10 == c]\nprint(len(b))\nprint(b)\n\n", "\nfor x in range(...) loops is better than while loops when start and end of loop are defined.\nso you can use this code to make y list:\n\ny = []\nfor x in range(501):\n y.append(x)\n\nThe shorter code is:\ny...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074439199_python.txt
Q: Reading blob from function app works in local - not when published I want to access string data from a blob with a Python function app. The function app works fine in local but doesn't return anything when published (Even though Configuration section in the portal is updated with all environment variables needed i...
Reading blob from function app works in local - not when published
I want to access string data from a blob with a Python function app. The function app works fine in local but doesn't return anything when published (Even though Configuration section in the portal is updated with all environment variables needed in local.settings.json) The part data.readall() is what I am returning wh...
[ "So it would appear that there are different behaviors according to the version of azure-storage-blob pip installed.\ndata.readall() seemed to work only for one version of the package but once upgraded to azure-storage-blob==12.14.1, the prior method doesn't work, but this one does:\ndata.content_as_text() (in loca...
[ 0 ]
[]
[]
[ "azure", "azure_blob_storage", "azure_functions", "python", "python_3.x" ]
stackoverflow_0074438391_azure_azure_blob_storage_azure_functions_python_python_3.x.txt
Q: Python: Change just one entry in nested dictionary Basically I just want to change nested dictionaries but in my code I change multiple sublevel dictionaries at once. So I have a nested dictionary which looks this way d1 = {'a': {0: [1,2], 1: [1,2]}, 'b': {0: [1,2], 1: [1,2]}} Then I want to add an entry d1['a'][...
Python: Change just one entry in nested dictionary
Basically I just want to change nested dictionaries but in my code I change multiple sublevel dictionaries at once. So I have a nested dictionary which looks this way d1 = {'a': {0: [1,2], 1: [1,2]}, 'b': {0: [1,2], 1: [1,2]}} Then I want to add an entry d1['a'][2] = [2,2] And then I get what I want {'a': {0: [1, 2],...
[ "You can check answers here:\nUnwanted behaviour from dict.fromkeys\nIf dict().fromkeys() all point to the same object, what purpose does the default value argument serve?\nIn particular, if you try:\ndict.fromkeys(['a','b'], object())\n\nyou will see that the adresses are the same:\n{'a': <object at 0x2fa88dfebe0>...
[ 0 ]
[ "When you run dict.fromkeys(keys, default) it creates a dictionary with the keys you provided and gives all of them the same default value you provided. Your problem is that the default value you provided is itself a dictionary which is mutable. Because it is mutable it is stored as a reference to one object. When ...
[ -1 ]
[ "dictionary", "nested", "python" ]
stackoverflow_0074439329_dictionary_nested_python.txt
Q: How to change the name of a Django app? I have changed the name of an app in Django by renaming its folder, imports and all its references (templates/indexes). But now I get this error when I try to run python manage.py runserver Error: Could not import settings 'nameofmynewapp.settings' (Is it on sys.path?): No m...
How to change the name of a Django app?
I have changed the name of an app in Django by renaming its folder, imports and all its references (templates/indexes). But now I get this error when I try to run python manage.py runserver Error: Could not import settings 'nameofmynewapp.settings' (Is it on sys.path?): No module named settings How can I debug and sol...
[ "Follow these steps to change an app's name in Django:\n\nRename the folder which is in your project root\nChange any references to your app in their dependencies, i.e. the app's views.py, urls.py , manage.py , and settings.py files.\nEdit the database table django_content_type with the following command: UPDATE dj...
[ 389, 41, 19, 12, 10, 4, 0, 0, 0 ]
[ "Why not just use the option Find and Replace. (every code editor has it)?\nFor example Visual Studio Code (under Edit option):\n\nYou just type in old name and new name and replace everyhting in the project with one click.\nNOTE: This renames only file content, NOT file and folder names. Do not forget renaming fol...
[ -5 ]
[ "django", "python" ]
stackoverflow_0008408046_django_python.txt
Q: How can I change this code to not use the lambda function? import csv #working with csv files from datetime import datetime #this will allow accessing time for later use #initialize class for every output class InventoryReports: def __init__(self, item_list): self.item_lis...
How can I change this code to not use the lambda function?
import csv #working with csv files from datetime import datetime #this will allow accessing time for later use #initialize class for every output class InventoryReports: def __init__(self, item_list): self.item_list = item_list #provide list to create new file #Part ...
[ "Here is a very verbose method, untested.\nimport csv #working with csv files\nfrom datetime import datetime #this will allow accessing time for later use\n\n#initialize class for every output\nclass InventoryReports:\n def __init__(self, item_list):\n self.item_list = item_li...
[ 0, 0 ]
[]
[]
[ "lambda", "python" ]
stackoverflow_0074439218_lambda_python.txt
Q: Error with an if statement that I can't figure out I am making a project for school using Python, and I keep getting a traceback error after I input the age, no matter what age I input. I can't figure out why, so hopefully someone else can figure it out. After I input the age, it does tell me "You have selected a ...
Error with an if statement that I can't figure out
I am making a project for school using Python, and I keep getting a traceback error after I input the age, no matter what age I input. I can't figure out why, so hopefully someone else can figure it out. After I input the age, it does tell me "You have selected a 15-year-old character." (or any other age), but after th...
[ "Here is a working solution. But the code could be improved, see at the bottom there are some recommendations.\nerror001 = \"\\nError 001: Invalid Sex!\"\nerror002 = \"\\nError 002: Invalid Age!\"\nerror003 = \"\\nError 003: Invalid Activity Level!\"\nerror004 = \"\\nError 004: Invalid Age Group!\"\n\nprint(\"Hello...
[ 0 ]
[]
[]
[ "if_statement", "python", "syntax", "syntax_error", "traceback" ]
stackoverflow_0074438598_if_statement_python_syntax_syntax_error_traceback.txt
Q: Spacy Installation error - oserror Can't find model 'en_core_web_sm' I have tried all the previous solution provided but am not able to resolve the error. The steps which I have followed. Installation pip install -U spacy python -m spacy download en_core_web_sm Then in jupyter notebook am running the following c...
Spacy Installation error - oserror Can't find model 'en_core_web_sm'
I have tried all the previous solution provided but am not able to resolve the error. The steps which I have followed. Installation pip install -U spacy python -m spacy download en_core_web_sm Then in jupyter notebook am running the following command. import spacy nlp = spacy.load('en_core_web_sm') But it is not wo...
[ "\"em_core_web_sm\" should be replaced by \"en_core_web_sm\"\n" ]
[ 0 ]
[]
[]
[ "installation", "oserror", "python", "spacy" ]
stackoverflow_0067222943_installation_oserror_python_spacy.txt
Q: Python - Trying to use a range function to iterate through dictionary response = requests.get('https://v2.jokeapi.dev/joke/Any?safe-mode&amount=5') json_string = response.content parsed_json = json.loads(json_string) #part of the joke is that this code will sometimes run and sometimes not run. real funny if...
Python - Trying to use a range function to iterate through dictionary
response = requests.get('https://v2.jokeapi.dev/joke/Any?safe-mode&amount=5') json_string = response.content parsed_json = json.loads(json_string) #part of the joke is that this code will sometimes run and sometimes not run. real funny if you ask me. for i in range(4): print("your jokes sir: ", parsed_json['...
[ "Not all jokes have the setup and delivery keys (I think the joke key and the setup delivery key pair to be mutually exclusive: there are jokes that consist of a whole joke string and jokes made of a setup and delivery) hence the error.\nWith dict.get() you can get values from dict while having a default value in c...
[ 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074439436_dictionary_python.txt
Q: Return the column that contains value in another column in Python Pandas I have the following dataframe in Pandas. There're 1 column shows 'Name', 1 column shows "Status", and uncertain amount of columns show "Comment". | Name | Status | Comment1 | Comment2 | Comment... | CommentN | | -------- | -------- |...
Return the column that contains value in another column in Python Pandas
I have the following dataframe in Pandas. There're 1 column shows 'Name', 1 column shows "Status", and uncertain amount of columns show "Comment". | Name | Status | Comment1 | Comment2 | Comment... | CommentN | | -------- | -------- | -------- | -------- | -------- | -------- | | Abby | Valid | Abby....
[ "try this:\ntmp = (df.apply(\n lambda x: x[1:].values[x[1:].str.contains(x[0])],\n axis=1)\n .apply(pd.Series))\nout = df[['Name']].join(tmp.set_axis(['Result'], axis=1))\nprint(out)\n>>>\n Name Result\n0 Abby Abby.aom\n1 Bob Bob.aom\n2 Chris Chris.bom\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074439149_dataframe_pandas_python.txt
Q: Why does a comma not work in variable assignment but does in print() my_name = "Ali" my_age = 22 place_of_work = " TD Bank" introduction = 'Hi, my name is ' + my_name + ' and I am' , my_age , 'years old.' + ' I work at' + place_of_work + '.' print (introduction) It prints with brackets and quotations. It works...
Why does a comma not work in variable assignment but does in print()
my_name = "Ali" my_age = 22 place_of_work = " TD Bank" introduction = 'Hi, my name is ' + my_name + ' and I am' , my_age , 'years old.' + ' I work at' + place_of_work + '.' print (introduction) It prints with brackets and quotations. It works well when I change the variable introduction to print() but I just wanted...
[ "In some places you use commas and some places you use \"+\", replace commas with the + sign and it should work.\n", "You can concatenate strings via the method you used but because my_age is an int, it will not concatenate with the strings. Replace with:\nintroduction = 'Hi, my name is ' + my_name + ' and I am' ...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074439553_python.txt
Q: I need help converting this code from one for loop to two nested for loops This is an example of the wheat and chessboard problem. I need to write the code using one for loop and two nested for loops. I have written it using one for loop but am having trouble figuring out what I would do for my second for loop. An...
I need help converting this code from one for loop to two nested for loops
This is an example of the wheat and chessboard problem. I need to write the code using one for loop and two nested for loops. I have written it using one for loop but am having trouble figuring out what I would do for my second for loop. Any help in the right direction would be appreciated! Code with one for loop: grai...
[ "I am not particularly sure the reason for needing a nested loop other than you want to see how to get a comparable output, but you can analyze the following example. Which removes the need for the \"board\" variable.\ngrains = 1\ntotal = 0\n\nn = int(input(\"How many squares are on one side of your chessboard?: \...
[ 0 ]
[]
[]
[ "for_loop", "nested_for_loop", "python", "python_3.x" ]
stackoverflow_0074439453_for_loop_nested_for_loop_python_python_3.x.txt
Q: how to list files from a S3 bucket folder using python I tried to list all files in a bucket. Here is my code import boto3 s3 = boto3.resource('s3') my_bucket = s3.Bucket('my_project') for my_bucket_object in my_bucket.objects.all(): print(my_bucket_object.key) it works. I get all files' names. However, when...
how to list files from a S3 bucket folder using python
I tried to list all files in a bucket. Here is my code import boto3 s3 = boto3.resource('s3') my_bucket = s3.Bucket('my_project') for my_bucket_object in my_bucket.objects.all(): print(my_bucket_object.key) it works. I get all files' names. However, when I tried to do the same thing on a folder, the code raise an...
[ "You can't indicate a prefix/folder in the Bucket constructor. Instead use the client-level API and call list_objects_v2 something like this:\nimport boto3\n\nclient = boto3.client('s3')\n\nresponse = client.list_objects_v2(\n Bucket='my_bucket',\n Prefix='data/')\n\nfor content in response.get('Contents', []...
[ 5, 1 ]
[]
[]
[ "amazon_s3", "amazon_web_services", "python" ]
stackoverflow_0071344134_amazon_s3_amazon_web_services_python.txt
Q: Pandas DateTimeIndex indexing random multiple days I am trying to extract random multiple whole day data from pandas DateTimeIndex series, But it returns only the first hour data when the multiple days are passed as a list. dt = pd.date_range('11-1-2022','11-4-2022',freq='6H').to_series() When I want to extract s...
Pandas DateTimeIndex indexing random multiple days
I am trying to extract random multiple whole day data from pandas DateTimeIndex series, But it returns only the first hour data when the multiple days are passed as a list. dt = pd.date_range('11-1-2022','11-4-2022',freq='6H').to_series() When I want to extract single day it works fine In [204]: dt['11-3-2022'] Out[20...
[ "This is one way you can filter your time series:\nAssuming you want all times between '11-1-2022' and '11-3-2022' inclusive:\nda = dt.where(dt >= pd.to_datetime('11-1-2022')).where(dt <= pd.to_datetime('11-3-2022'))\nda.dropna() \n\nYields:\n2022-11-01 00:00:00 2022-11-01 00:00:00\n2022-11-01 06:00:00 2022-...
[ 0 ]
[]
[]
[ "datetimeindex", "pandas", "python" ]
stackoverflow_0074439185_datetimeindex_pandas_python.txt
Q: Python encoding characters with urllib.quote I'm trying to encode non-ASCII characters so I can put them inside an url and use them in urlopen. The problem is that I want an encoding like JavaScript (that for example encodes ó as %C3%B3): encodeURIComponent(ó) '%C3%B3' But urllib.quote in python returns ó as %F3:...
Python encoding characters with urllib.quote
I'm trying to encode non-ASCII characters so I can put them inside an url and use them in urlopen. The problem is that I want an encoding like JavaScript (that for example encodes ó as %C3%B3): encodeURIComponent(ó) '%C3%B3' But urllib.quote in python returns ó as %F3: urllib.quote(ó) '%F3' I want to know how to achi...
[ "in Python 3 the urllib.quote has been renamed to urllib.parse.quote.\nAlso in Python 3 all strings are unicode strings (the byte strings are called bytes).\nExample:\nfrom urllib.parse import quote\n\nprint(quote('ó'))\n# output: %C3%B3\n\n", "You want to make sure you're using unicode.\nExample:\nimport urllib\...
[ 40, 38, 0 ]
[]
[]
[ "encoding", "python", "urllib" ]
stackoverflow_0006431061_encoding_python_urllib.txt
Q: How to remove something from one list and add it to another in python I have a nested list that has certain elements with an [x] at the beginning. I want the function to remove those elements and move them to the last list in list1 (at index 2). But it should remove the [x] from it before placing it in the last li...
How to remove something from one list and add it to another in python
I have a nested list that has certain elements with an [x] at the beginning. I want the function to remove those elements and move them to the last list in list1 (at index 2). But it should remove the [x] from it before placing it in the last list. It should also count how many were removed from each list. For example:...
[ "This is how you would do that:\nlist1 = [['[x]homework', '[x]eat','stretch'], ['[x]final', 'school'], ['sleep','midterm']]\nfor x in range(0,len(list1)-1):\n lst = list1[x]\n count = 0\n to_be_removed = []\n for str in lst:\n if str[0:3] == \"[x]\":\n to_be_removed.append(str)\n ...
[ 0, 0, 0 ]
[]
[]
[ "list", "nested_lists", "python" ]
stackoverflow_0074439284_list_nested_lists_python.txt
Q: How to I create a new column in pandas using if/elif conditions on multiple lists I am trying to create a new column in my dataset to classify soil texture into 3 textural classes. I have a column ('texture') containing 6 different soil texture. I created 3 lists as shown below: Defining soil textural column (ie f...
How to I create a new column in pandas using if/elif conditions on multiple lists
I am trying to create a new column in my dataset to classify soil texture into 3 textural classes. I have a column ('texture') containing 6 different soil texture. I created 3 lists as shown below: Defining soil textural column (ie fine, coarse and medium) # Defining soil textural column (ie fine, coarse and medium) co...
[ "try this:\nimport numpy as np\ncond1 = sha_df['texture'].isin(coarse_tex)\ncond2 = sha_df['texture'].isin(medium_tex)\ncond3 = sha_df['texture'].isin(fine_tex)\n\nsha_df['textural_class'] = np.select(\n [cond1, cond2, cond3],\n ['coarse_tex', 'medium_tex', 'fine_tex'],\n None\n)\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "if_statement", "pandas", "python" ]
stackoverflow_0074439435_dataframe_if_statement_pandas_python.txt
Q: How do I print colored text to the terminal? How do I output colored text to the terminal in Python? A: This somewhat depends on what platform you are on. The most common way to do this is by printing ANSI escape sequences. For a simple example, here's some Python code from the Blender build scripts: class bcolo...
How do I print colored text to the terminal?
How do I output colored text to the terminal in Python?
[ "This somewhat depends on what platform you are on. The most common way to do this is by printing ANSI escape sequences. For a simple example, here's some Python code from the Blender build scripts:\nclass bcolors:\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKCYAN = '\\033[96m'\n OKGREEN = '\\033[9...
[ 2619, 1105, 982, 617, 302, 166, 112, 105, 86, 70, 65, 63, 58, 45, 44, 41, 38, 32, 30, 28, 27, 24, 24, 23, 21, 19, 17, 15, 15, 12, 11, 11, 11, 10, 10, 10, 10, 10, 8, 7, 7, 6, 6, 6, 5, 4, 4, 4, 4, 4, 4, 3, 3, 3, ...
[]
[]
[ "ansi_colors", "output", "python", "terminal" ]
stackoverflow_0000287871_ansi_colors_output_python_terminal.txt
Q: Print slow in python but in a box I need to type some text inside a box but the text needs to be like typing but the box to just be thare. I also need it to be yellow. My code: from termcolor import colored import sys, time, random import os os.system('clear') def print_slow(str): for letter in str: ...
Print slow in python but in a box
I need to type some text inside a box but the text needs to be like typing but the box to just be thare. I also need it to be yellow. My code: from termcolor import colored import sys, time, random import os os.system('clear') def print_slow(str): for letter in str: sys.stdout.write(letter) sys.st...
[ "Here's one way to do it:\nfrom termcolor import colored\nimport sys, time, random\nimport os\n\nos.system(\"cls\")\n\n\ndef getText(i, str):\n totalLength = 12\n subString = str[:i]\n spaces = \" \" * (totalLength - i)\n return subString + spaces\n\n\ndef print_slow(string):\n for i in range(len(str...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074439428_python.txt
Q: pytest results not matching - data corrupted somehow? I have the following python code: class CSVFile: def __init__(self, filename): self.filename = filename def write_csv_line(self, row, mode): for value in row: if value == "None": value = "" writer = c...
pytest results not matching - data corrupted somehow?
I have the following python code: class CSVFile: def __init__(self, filename): self.filename = filename def write_csv_line(self, row, mode): for value in row: if value == "None": value = "" writer = csv.writer(open(self.filename, mode)) writer.writero...
[ "I fixed the problem, and with that, some bugs. I realized the problem was with writing the file, i.e. the file getting corrupted data at that point. So I focused on that function.\n def write_csv_line(self, row, mode):\n i = 0\n for value in row:\n print(row)\n if value == \...
[ 0 ]
[]
[]
[ "parametrized_testing", "pytest", "python" ]
stackoverflow_0074437590_parametrized_testing_pytest_python.txt
Q: Finding the amount of minutes from a set time for a list of times I have a list of times and I want to make a list of lists where the elements of the larger list is a list where the first element is the time and the second element is the number of minutes from a set time. So for example, this is what I have ['2022...
Finding the amount of minutes from a set time for a list of times
I have a list of times and I want to make a list of lists where the elements of the larger list is a list where the first element is the time and the second element is the number of minutes from a set time. So for example, this is what I have ['2022-04-08, 1:05 pm', '2022-04-09, 4:05 pm', '2022-04-10, 7:08 pm', '202...
[ "You could do something like this:\ntimes = ['2022-04-08, 1:05 pm', \n'2022-04-09, 4:05 pm', \n'2022-04-10, 7:08 pm',\n'2022-04-11, 7:05 pm',\n'2022-04-12, 7:05 pm',\n'2022-04-13, 7:05 pm',\n'2022-04-14, 7:05 pm',\n'2022-04-22, 7:05 pm',\n'2022-04-23, 1:05 pm',\n'2022-04-24, 1:35 pm',\n'2022-04-26, 7:05 pm',\n'2022...
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074439556_python.txt
Q: How to identify optimal item prices given a list of quantities and orders? I have a set of orders where I have the total order value and item quantities but not the cost of individual items. I'm trying to back into what item prices would best explain these totals given the quantity for each order. Note that there ...
How to identify optimal item prices given a list of quantities and orders?
I have a set of orders where I have the total order value and item quantities but not the cost of individual items. I'm trying to back into what item prices would best explain these totals given the quantity for each order. Note that there are hundreds of items and thousands of orders but I've provided an example probl...
[ "Here is a formulation and a few ideas that might help.\nI popped your data into a .csv file and removed the \"$\" to make this work. Realize that the case you gave is infeasible (there are no EXACT prices that make those 4 equations work). The model should be formulated to allow for slack using the constraint as...
[ 1 ]
[]
[]
[ "optimization", "pulp", "python" ]
stackoverflow_0074438757_optimization_pulp_python.txt
Q: flask-smorest response and return type different I am learning/working on a Rest Api suing flask-smorest and adding the schema using marshmallow. Below is the code that I am confused with and have a question. Schemas.py class ChildAddressDetailsSchema(Schema): class Meta: unknown = EXCLUDE addre...
flask-smorest response and return type different
I am learning/working on a Rest Api suing flask-smorest and adding the schema using marshmallow. Below is the code that I am confused with and have a question. Schemas.py class ChildAddressDetailsSchema(Schema): class Meta: unknown = EXCLUDE address_id = fields.String(required=True) address_type ...
[ "It's because you called Blueprint.response() before Blueprint.get(). So do like this.\n@address_blueprint.get('/child/address/<string:person_id>/list')\n@address_blueprint.response(status_code=200, schema=ChildAddressDetailsSchema)\ndef get_child_address(person_id):\n ...\n\nA Python decorator returns a new fun...
[ 1 ]
[]
[]
[ "flask", "flask_restful", "flask_smorest", "marshmallow", "python" ]
stackoverflow_0074427203_flask_flask_restful_flask_smorest_marshmallow_python.txt
Q: Putting items from a dictionary into a string I want to use data from a list of dictionaries in a string. For example dict = [{'name':'Matt', 'age':'21'},{'name':'Sally','age':'28'}] print(f"His name is {??} and he is {??} years old") I need to know what to replace the question marks with to make it work. I have...
Putting items from a dictionary into a string
I want to use data from a list of dictionaries in a string. For example dict = [{'name':'Matt', 'age':'21'},{'name':'Sally','age':'28'}] print(f"His name is {??} and he is {??} years old") I need to know what to replace the question marks with to make it work. I have looked a lot of stack overflow and found some thi...
[ "Iterate over the dicts, and then use the [] operator to get the name and age keys.\npeople = [{'name':'Matt', 'age':'21'},{'name':'Sally','age':'28'}]\n\nfor p in people:\n print(f\"Their name is {p['name']} and they are {p['age']} years old\")\n\nTheir name is Matt and they are 21 years old\nTheir name is Sall...
[ 1, 1, 1 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0074439663_dictionary_list_python.txt
Q: Using VSCode to remotely debug Python code in local Docker container Background: We have Sphinx, a Python application for generating documentation, running inside a Docker Container. I'm running into an issue with converting drawio files. When executed in our GitLab pipelines it executes fine but when the project ...
Using VSCode to remotely debug Python code in local Docker container
Background: We have Sphinx, a Python application for generating documentation, running inside a Docker Container. I'm running into an issue with converting drawio files. When executed in our GitLab pipelines it executes fine but when the project is executed locally on my M2 Mac it fails to convert the image and throws ...
[ "You can try remote-ssh.\nAccording to the docs,\nThe Visual Studio Code Remote - SSH extension allows you to open a remote folder on any remote machine, virtual machine, or container with a running SSH server and take full advantage of VS Code's feature set. Once connected to a server, you can interact with files ...
[ 0 ]
[]
[]
[ "debugpy", "docker", "python", "visual_studio_code", "vscode_debugger" ]
stackoverflow_0074428178_debugpy_docker_python_visual_studio_code_vscode_debugger.txt
Q: 0-1 Knapsack problem with bound in the number of items I have a list with the weight, value and number of copies available of the items in a shop in the form [w_i, v_i, c_i]. I can not carry more than W weight with me, that is why I need to optimize my decision. How many copies of what item I should take? And, wha...
0-1 Knapsack problem with bound in the number of items
I have a list with the weight, value and number of copies available of the items in a shop in the form [w_i, v_i, c_i]. I can not carry more than W weight with me, that is why I need to optimize my decision. How many copies of what item I should take? And, what is the max value I can generate with this selection? This ...
[ "With nb being the number of copies available for each item:\nocc_max = max(nb)\nn= len(val)\ntable = [[[0]*(occ_max+1) for x in range(W + 1)] for x in range(n + 1)]\nfor i in range(n + 1): \n for j in range(W + 1):\n if i == 0:\n table[i][j][0] = 0\n else:\n for k in range(nb...
[ 1 ]
[]
[]
[ "algorithm", "data_structures", "python" ]
stackoverflow_0074271669_algorithm_data_structures_python.txt
Q: Can't Install Python Package onto Docker Trying to install a package (flake8) onto a Docker container (or maybe it's an image). I've pip installed the package locally, and when I try to pip install it again, I get: Requirement already satisfied: flake8 in c:\python39\lib\site-packages (5.0.4) But then when I run ...
Can't Install Python Package onto Docker
Trying to install a package (flake8) onto a Docker container (or maybe it's an image). I've pip installed the package locally, and when I try to pip install it again, I get: Requirement already satisfied: flake8 in c:\python39\lib\site-packages (5.0.4) But then when I run this code snippet: docker-compose run --rm app...
[ "Use the following command to install in the docker container instead of in the base environment:\npip install flake8\n\n", "The issue was that Flake8 was only installed locally as opposed to on the Docker image (See David's comment above for more on this).\nTo remedy this, the following line was added to a requi...
[ 1, 0 ]
[]
[]
[ "docker", "docker_compose", "python", "visual_studio_code" ]
stackoverflow_0074368650_docker_docker_compose_python_visual_studio_code.txt
Q: How would I create a duplicate category and delete the original category in Discord.py? I currently have a command which will clone and delete a specific channel using message context: @bot.command(name="refresh=", aliases=["refresh"]) @commands.has_permissions(manage_messages=True) async def refresh(ctx): awa...
How would I create a duplicate category and delete the original category in Discord.py?
I currently have a command which will clone and delete a specific channel using message context: @bot.command(name="refresh=", aliases=["refresh"]) @commands.has_permissions(manage_messages=True) async def refresh(ctx): await ctx.channel.clone(reason="refresh channel command") await ctx.channel.delete() But I ...
[ "There is according to the API\ni believe it would be\nawait ctx.category.clone() \n\nand\nawait ctx.category.delete()\n\n" ]
[ 0 ]
[]
[]
[ "discord", "discord.py", "python" ]
stackoverflow_0074418640_discord_discord.py_python.txt
Q: ModuleNotFoundError: No module named 'common.config' oanda api python I am trying to connect to Oanda REST API using juypter notebook with the following code: #!/usr/bin/env python import sys import select import argparse import common.config from .account import Account def main(): """ Create an API con...
ModuleNotFoundError: No module named 'common.config' oanda api python
I am trying to connect to Oanda REST API using juypter notebook with the following code: #!/usr/bin/env python import sys import select import argparse import common.config from .account import Account def main(): """ Create an API context, and use it to fetch an Account state and then continually poll f...
[ "I added the 2 line on the top of the code then run it correctly.I think it's because of error path.\n\n\n\n\n\n\n\n\n\n\nimport sys\nsys.path.append('/Users/apple/Documents/code/PythonX86/OandaAPI/example/v20-python-samples/src')\n\n\n\n\n\n\n\n\n\n\n\n" ]
[ 0 ]
[]
[]
[ "oanda", "python" ]
stackoverflow_0067075396_oanda_python.txt
Q: Pandas use start/end datetimes to find concurrent phone calls I have a set of phone call records with connect/disconnect times and I want to find out the concurrent number of calls for every second of the period of time in the data. Then I'd like to use that concurrent call data to get peak call times during the d...
Pandas use start/end datetimes to find concurrent phone calls
I have a set of phone call records with connect/disconnect times and I want to find out the concurrent number of calls for every second of the period of time in the data. Then I'd like to use that concurrent call data to get peak call times during the day. I have a working example, but iterating with a timedelta of 1 s...
[ "Use the linked method, and then do asfreq~\nout = (df.melt(var_name='status',value_name='time')\n .sort_values('time')\n .assign(counter=lambda x: x.status.map({'dateTimeConnect': 1, 'dateTimeDisconnect': -1}).cumsum())\n .set_index('time')\n .asfreq('s', 'pad'))\n\nprint(out)\n\nOutput:\n ...
[ 0 ]
[]
[]
[ "datetime", "pandas", "python" ]
stackoverflow_0074439679_datetime_pandas_python.txt
Q: How would I add the results of for loop into a dictionary? I am required to take 52 random outputs of cards. I got that in a for loop. Problem is, I need to save that output inside a variable.` import random r=random.randint(0, 9) cards={'Spades':r, 'Clubs':r, 'Hearts':r, 'Diamonds':r,'Jack':10, 'King':10, 'quee...
How would I add the results of for loop into a dictionary?
I am required to take 52 random outputs of cards. I got that in a for loop. Problem is, I need to save that output inside a variable.` import random r=random.randint(0, 9) cards={'Spades':r, 'Clubs':r, 'Hearts':r, 'Diamonds':r,'Jack':10, 'King':10, 'queen':10,"Aces":1} print(cards) cards2={} for i in range(52): ...
[ "first remove the double assignment (res = key, val) and i see no point on using global variable here. just do _dict[key] = value as shown below it will work fine. also remember that you cant get all 52 random cards because if key exists then value will be replaced\nimport random\nr=random.randint(0, 9)\ncards={'Sp...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074439653_python.txt
Q: How can I send user input to my host using Paramiko? I am trying to automate the deployment of a linux server using python and paramiko. The problem is that the first time I connect to this custom Linux OS it ask for parameters for it's initial "installer". You cannot do anything with the server until these parame...
How can I send user input to my host using Paramiko?
I am trying to automate the deployment of a linux server using python and paramiko. The problem is that the first time I connect to this custom Linux OS it ask for parameters for it's initial "installer". You cannot do anything with the server until these parameters are set. The first parameter is to set a new password...
[ "I was able to find a solution for this using the .invoke_shell method and the .send method. Once the channel was opened I used .send to pass my inputs and then used .recv to get my feedback and ensure the installer was proceeding. I simply repeated this for all of the inputs needed. I will convert this into a func...
[ 0 ]
[]
[]
[ "linux", "paramiko", "python", "ssh" ]
stackoverflow_0074416821_linux_paramiko_python_ssh.txt
Q: Python code to count integers based on length and starting digit I have a list of numbers of varying lengths stored in a file, like this... 98 132145 132324848 4435012341 1254545221 2314565447 I need a function that looks through the list and counts every number that is 10 digits in length and begins with the num...
Python code to count integers based on length and starting digit
I have a list of numbers of varying lengths stored in a file, like this... 98 132145 132324848 4435012341 1254545221 2314565447 I need a function that looks through the list and counts every number that is 10 digits in length and begins with the number 1. I have stored the list in both a .txt and a .csv with no luck. ...
[ "You could simply do like this :\n# Get your file content as a string.\nwith open(r\"C:\\Desktop\\file.csv\") as f:\n s = \" \".join([l.rstrip(\"\\n\").strip() for l in f])\n\n# Look for the 10 digits number starting with a one.\nnb = [n for n in s.split(' ') if len(n)==10 and n[0]=='1']\n\nIn your case, the outpu...
[ 0 ]
[ "So I ended up using the following, seems to work great..\ndef filterNumberOne(n):\n if (len(n)==10:\n if str(n)[0] == '1':\n return True\n else:\n return False\none = list(filter(filterNumberOne, x ))\nprint(len(one))\n\n" ]
[ -1 ]
[ "count", "integer", "python" ]
stackoverflow_0074391842_count_integer_python.txt
Q: VSCode -- How can I change the run configuration? I am working with a single python file. The first time I launched it, VSCode prompted me to choose a run configuration, and I accidentally chose Module instead of Python File. Now every time I click Run I get the error python.exe: No module named enter-your-module-...
VSCode -- How can I change the run configuration?
I am working with a single python file. The first time I launched it, VSCode prompted me to choose a run configuration, and I accidentally chose Module instead of Python File. Now every time I click Run I get the error python.exe: No module named enter-your-module-name. I want to just change the run config to run as a ...
[ "You can click Run Python File in the running options in the upper right corner.\n\nThe situation you described seems to use the debug mode incorrectly. You can delete launch.json in the .vscode folder on the left workspcae.\n\nYou can alse set in the Run and Debug button.\n\nor it may look like it:\n\n" ]
[ 0 ]
[]
[]
[ "python", "visual_studio_code" ]
stackoverflow_0074435155_python_visual_studio_code.txt
Q: askopenfilename handling cancel on dialogue I have a gui which initializes the askopenfilename when a button is pressed but I want to be able to account for when the user selects cancel on the askopenfilename dialogue Here is my function to handle the clicked button yet the if statement line doesnt seem to work! ...
askopenfilename handling cancel on dialogue
I have a gui which initializes the askopenfilename when a button is pressed but I want to be able to account for when the user selects cancel on the askopenfilename dialogue Here is my function to handle the clicked button yet the if statement line doesnt seem to work! def openFileClicked(self): self.filename=filedi...
[ ".askopenfilename() returns an empty string on cancel, not None. So you can either compare to '' or False. For the sake of having a code sample:\ndef openFileClicked(self):\n self.filename = filedialog.askopenfilename()\n if not self.filename:\n # config...delete...etc.\n # Rest of function\n\nAt ...
[ 9, 6, 0, 0 ]
[]
[]
[ "python", "tkinter", "user_interface" ]
stackoverflow_0015010461_python_tkinter_user_interface.txt
Q: How to read Lines of text from a file into a 2D matrix in python? I want to read a text file that contains the following: -------------------- ---+---+---+--+----- -------------+------ ++-----------+------ -+-+----+------+---- -------------------- -----------+-------+ ------+----+-------+ +------------------- --+-...
How to read Lines of text from a file into a 2D matrix in python?
I want to read a text file that contains the following: -------------------- ---+---+---+--+----- -------------+------ ++-----------+------ -+-+----+------+---- -------------------- -----------+-------+ ------+----+-------+ +------------------- --+--------+------+- I want to not only split this data into separate line...
[ "you can try this:\nwith open(\"file.txt\",\"r\") as f:\n print([[y for y in x[:-1]] for x in f.readlines()])\n\nIt will create a list of many lists, the x[:-1] is to escape the \"\\n\" at the end of each line.\n", "Use list inside a list comprehension to convert each line to a list.\nwith open(\"file.txt\") a...
[ 0, 0 ]
[]
[]
[ "matrix", "python" ]
stackoverflow_0074439763_matrix_python.txt
Q: How to create DataFrame in Python if values from list are in row of a different DataFrame? I have a sample dataframe: | ID | SampleColumn1| SampleColumn2 | SampleColumn3 | |:-- |:------------:| ------------ :| ------------ | | 1 |sample Apple | sample Cherry |sample Lime | | 2 |sample Cherry | sample lemon ...
How to create DataFrame in Python if values from list are in row of a different DataFrame?
I have a sample dataframe: | ID | SampleColumn1| SampleColumn2 | SampleColumn3 | |:-- |:------------:| ------------ :| ------------ | | 1 |sample Apple | sample Cherry |sample Lime | | 2 |sample Cherry | sample lemon | sample Grape | I would like to create a new DataFrame based off of this initial dataframe. ...
[ "try this:\nkeywords = ['Apple', 'Lime', 'Cherry']\ntmp = (df.melt(ignore_index=False)\n .value.str.extract(\n f'({\"|\".join(keywords)})',\n expand=False)\n .dropna())\n\nres = (pd.crosstab(index=tmp.index, columns=tmp)\n .rename_axis(index=None, columns=None))\nprint(res)\n>>...
[ 1, 0 ]
[]
[]
[ "dataframe", "list", "pandas", "python" ]
stackoverflow_0074439491_dataframe_list_pandas_python.txt
Q: Struggling to analyse numbers on documents with openCv and pyTesseract I'm new on the OCR world and I have document with numbers to analyse with Python, openCV and pytesserract. The files I received are pdfs and the numbers are not text. So, I converted it to jpg with this : first_page = convert_from_path(path__to...
Struggling to analyse numbers on documents with openCv and pyTesseract
I'm new on the OCR world and I have document with numbers to analyse with Python, openCV and pytesserract. The files I received are pdfs and the numbers are not text. So, I converted it to jpg with this : first_page = convert_from_path(path__to_pdf, dpi=600, first_page=1, last_page=1) first_page[0].save(TEMP_FOLDER+'te...
[ "Whenever you see that Tesseract is missing a character or digit, think about page segmentation modes. If the character is not correct but was read, it is a recognition issue.\nOCR engines split the text in the image we input, and this splitting is called page segmentation. Then, the engines try to recognize the te...
[ 1, 0 ]
[]
[]
[ "ocr", "python", "python_tesseract", "tesseract" ]
stackoverflow_0074415476_ocr_python_python_tesseract_tesseract.txt
Q: Unable to insert values I create a table but I'm not able to insert values. Database class: import sqlite3 class Database: word_list = ["RAFAY", "LION", "PANDA", "TIGER", "DOG", "CAT", "RABBIT", "MOUSE", "PENGUIN"] def __init__(self, db): self.con = sqlite3.connect(db) self.cur = self...
Unable to insert values
I create a table but I'm not able to insert values. Database class: import sqlite3 class Database: word_list = ["RAFAY", "LION", "PANDA", "TIGER", "DOG", "CAT", "RABBIT", "MOUSE", "PENGUIN"] def __init__(self, db): self.con = sqlite3.connect(db) self.cur = self.con.cursor() self.cu...
[ "You can't re-use the cursor.\nDeclare a local cursor each time:\n# Get a Record in DB\ndef get_valid_guessing_word(self, id):\n cursor = self.con.cursor() # <<-- HERE new cursor\n cursor.execute(\"SELECT * FROM DICTIONARY WHERE id=?\", (id,))\n valid_word = cursor.fetch...
[ 0 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0074439295_python_sqlite.txt
Q: Pythonic way to create dataset for multilabel text classification I have a text dataset that looks like this. import pandas as pd df = pd.DataFrame({'Sentence': ['Hello World', 'The quick brown fox jumps over the lazy dog.', 'Just some text to make th...
Pythonic way to create dataset for multilabel text classification
I have a text dataset that looks like this. import pandas as pd df = pd.DataFrame({'Sentence': ['Hello World', 'The quick brown fox jumps over the lazy dog.', 'Just some text to make third sentence!' ], 'la...
[ "You can use pandas.Series.explode to explode the label column then cross it with the sentences column by using pandas.crosstab.\nTry this :\ndef cross_labels(df):\n return pd.crosstab(df[\"Sentence\"], df[\"label\"])\n\nout = (\n df.assign(label= df[\"label\"].str.split(\",\"))\n .explode(\"labe...
[ 0 ]
[]
[]
[ "nlp", "pandas", "python", "scikit_learn" ]
stackoverflow_0074440007_nlp_pandas_python_scikit_learn.txt
Q: When and why to use self.__dict__ instead of self.variable I'm trying to understand some code which is using this class below: class Base(object): def __init__(self, **kwargs): self.client = kwargs.get('client') self.request = kwargs.get('request') ... def to_dict(self): data ...
When and why to use self.__dict__ instead of self.variable
I'm trying to understand some code which is using this class below: class Base(object): def __init__(self, **kwargs): self.client = kwargs.get('client') self.request = kwargs.get('request') ... def to_dict(self): data = dict() for key in iter(self.__dict__): # <-----------...
[ "Almost all of the time, you shouldn't use self.__dict__.\nIf you're accessing an attribute like self.client, i.e. the attribute name is known and fixed, then the only difference between that and self.__dict__['client'] is that the latter won't look up the attribute on the class if it's missing on the instance. The...
[ 15, 2, 0 ]
[]
[]
[ "class", "dictionary", "oop", "python" ]
stackoverflow_0060104564_class_dictionary_oop_python.txt
Q: Use Enum value without .value attribute class Color(Enum): GREEN = '#1c5f17' BLUE = '#565fcc' Is it possible to call Color.GREEN and return '#1c5f17'? I don't want to call Color.GREEN.value everytime I want to use this. A: If you want the traditional-style "call", just drop the inheritance from Enum: cl...
Use Enum value without .value attribute
class Color(Enum): GREEN = '#1c5f17' BLUE = '#565fcc' Is it possible to call Color.GREEN and return '#1c5f17'? I don't want to call Color.GREEN.value everytime I want to use this.
[ "If you want the traditional-style \"call\", just drop the inheritance from Enum:\nclass Color:\n GREEN = '#1c5f17'\n BLUE = '#565fcc'\n\n", "IIRC prior to Python 3.11 the official documentation recommended subclassing string:\nclass Sample(str, Enum):\n FOO = \"foo\"\n BAR = \"bar\"\n BAZ = \"baz\...
[ 5, 1 ]
[ "Since Python 3.8, you can use assignment expressions:\nclass Color(Enum):\n GREEN = (Green := '...')\n BLUE = (Blue := '...')\n\nNow, you can keep all the inherited behavior of enums while accessing attributes without .value like this:\nmy_color = Color.Green\n\n" ]
[ -2 ]
[ "python" ]
stackoverflow_0054502574_python.txt
Q: if elif else condition to insert new data into the existing column How to use the if elif else condition to insert the data into the existing column? Example, if the columnA = 'abc' then columnB return '123', if the columnA = 'efg' then columnB return '345', else return '0'. so based on the data it should be: if t...
if elif else condition to insert new data into the existing column
How to use the if elif else condition to insert the data into the existing column? Example, if the columnA = 'abc' then columnB return '123', if the columnA = 'efg' then columnB return '345', else return '0'. so based on the data it should be: if the Sale id = 'sale001' then Sale no return 'clo sale', elif the Sale id ...
[ "You don't need an \"existing column\" for computed/derived values.\nWrite a function with that logic.\ndef sale_no(sale_id):\n if sale_id == 'sale001':\n return 'clo sale'\n elif sale_id == 'sale002':\n return 'blo sale'\n return ''\n\nIterate over your data to call it to add a new column... pandas create...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074440021_python.txt
Q: Need help filling in box plot with custom colors Data: import numpy as np import pandas as pd import matplotlib.pyplot as plt data = pd.DataFrame(np.random.normal(size=(15,4))) #Rename columns data.set_axis(['Column A', 'Column B', 'Column C', 'Column D'], axis=1, inplace=True) data Column A Column B ...
Need help filling in box plot with custom colors
Data: import numpy as np import pandas as pd import matplotlib.pyplot as plt data = pd.DataFrame(np.random.normal(size=(15,4))) #Rename columns data.set_axis(['Column A', 'Column B', 'Column C', 'Column D'], axis=1, inplace=True) data Column A Column B Column C Column D 0 0.786186 -0.416792 0....
[ "I'd suggest using seaborn or another more powerful library than just matplotlib:\nimport seaborn as sns\n\n# Let's melt the data first into long format.\ndf = df.melt()\n\n# You appear to have two groups, let's make them:\ndf['group'] = df.variable.isin(['Column A', 'Column C'])\n\ncolors = ['#002072', '#00BDF2']\...
[ 1, 1 ]
[]
[]
[ "boxplot", "dataframe", "matplotlib", "pandas", "python" ]
stackoverflow_0074439620_boxplot_dataframe_matplotlib_pandas_python.txt
Q: 404 error when polling Reddit's developer API I am trying to use Reddit's developer API to build a simple scraper that grabs posts and their replies in a target subreddit and produces JSON with the information. I am getting a 404 error that I don't understand. This is my code: import praw import json def scrape(s...
404 error when polling Reddit's developer API
I am trying to use Reddit's developer API to build a simple scraper that grabs posts and their replies in a target subreddit and produces JSON with the information. I am getting a 404 error that I don't understand. This is my code: import praw import json def scrape(subreddit, limit): r = praw.Reddit(user_agent='R...
[ "r.subreddit(subreddit) - subreddit should just be the name of the subreddit e.g. \"funny\" and not the full URL.\nSee the docs here: https://praw.readthedocs.io/en/stable/getting_started/quick_start.html#obtain-a-subreddit\n" ]
[ 1 ]
[]
[]
[ "json", "python", "web_scraping" ]
stackoverflow_0074440066_json_python_web_scraping.txt
Q: 5.3.2: Function call in expression Python Here's the prompt: Assign max_sum with the greater of num_a and num_b, PLUS the greater of num_y and num_z. Use just one statement. Hint: Call find_max() twice in an expression. Here's my code: def find_max(num_1, num_2): max_val = 0.0 if (num_1 > num_2): # if ...
5.3.2: Function call in expression Python
Here's the prompt: Assign max_sum with the greater of num_a and num_b, PLUS the greater of num_y and num_z. Use just one statement. Hint: Call find_max() twice in an expression. Here's my code: def find_max(num_1, num_2): max_val = 0.0 if (num_1 > num_2): # if num1 is greater than num2, max_val = num_...
[ "def find_max(num_1, num_2):\n\n max_val = 0.0\n if (num_1 > num_2): # if num1 is greater than num2,\n max_val = num_1 # then num1 is the maxVal.\n else: # Otherwise,\n max_val = num_2 # num2 is the maxVal\n return max_val\n\nnum_a = float(input())\nnum_b = float(input())\nnum_y = floa...
[ 2, 2, 0 ]
[]
[]
[ "expression", "function", "python" ]
stackoverflow_0067680659_expression_function_python.txt
Q: Tensorflow-directml vs tensorflow-CPU I'm currently starting to study CNN in Python with Tensorflow. I do understand that Tensorflow uses CUDA, so I instead tried using Tensorflow-directml because I'm using an AMD gpu (RX 580 and I3 10100f CPU). I tried to build a basic model for an object detection using CIFAR-10...
Tensorflow-directml vs tensorflow-CPU
I'm currently starting to study CNN in Python with Tensorflow. I do understand that Tensorflow uses CUDA, so I instead tried using Tensorflow-directml because I'm using an AMD gpu (RX 580 and I3 10100f CPU). I tried to build a basic model for an object detection using CIFAR-10 dataset with this model: model = models.Se...
[ "Its probably because you have a more modern cpu than gpu. I ran a CNN on my cpu(R5 5500) and it was only a little bit slower than my gpu(Radeon RX 5600XT).\n" ]
[ 0 ]
[]
[]
[ "deep_learning", "keras", "python", "tensorflow" ]
stackoverflow_0071769429_deep_learning_keras_python_tensorflow.txt
Q: "Python.h" file not found on MACOSX, how to fix this? `pip3 install PyAudio==0.2.12 Defaulting to user installation because normal site-packages is not writeable Collecting PyAudio==0.2.12 Using cached PyAudio-0.2.12.tar.gz (42 kB) Installing build dependencies ... done Getting requirements to build wheel ... done...
"Python.h" file not found on MACOSX, how to fix this?
`pip3 install PyAudio==0.2.12 Defaulting to user installation because normal site-packages is not writeable Collecting PyAudio==0.2.12 Using cached PyAudio-0.2.12.tar.gz (42 kB) Installing build dependencies ... done Getting requirements to build wheel ... done Preparing metadata (pyproject.toml) ... done Building whee...
[ "Export these from the command line terminal but change the path to be your correct path, then try again from the same command line terminal\nexport CPLUS_INCLUDE_PATH=/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/Headers\nexport C_INCLUDE_PATH=/Library/Developer/CommandLine...
[ 1 ]
[]
[]
[ "macos", "pyaudio", "python", "python_3.x" ]
stackoverflow_0074419576_macos_pyaudio_python_python_3.x.txt