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: button.configure() command not running inside while loop in Python Tkinter I am trying to configure the button based on the value of turn which is determined by the while loop which is determined by the value of game_over The while loop is interfering with the main loop of tkinter. I can't seem to figure out a way...
button.configure() command not running inside while loop in Python Tkinter
I am trying to configure the button based on the value of turn which is determined by the while loop which is determined by the value of game_over The while loop is interfering with the main loop of tkinter. I can't seem to figure out a way around this. This is the code. from tkinter import * connect = Toplevel() col1...
[ "First, I would not recommend to use potentially infinite while loops. Second you should check how to create a tkinter application, first create your root window before you create any TopLevel widget. Next, buttons can execute functions specified as command. Lastly, if you work with a GUI based approach, you can ge...
[ 5 ]
[]
[]
[ "button", "python", "tkinter", "while_loop" ]
stackoverflow_0074149154_button_python_tkinter_while_loop.txt
Q: Remove overlapped line over text with opencv I'm processing images that have a line across the 4 letters. After some processing, i have get this result: The only thing I can't get to do is remove that black line, so it can be more clear to be recognized with some OCR library. The final image should look like this...
Remove overlapped line over text with opencv
I'm processing images that have a line across the 4 letters. After some processing, i have get this result: The only thing I can't get to do is remove that black line, so it can be more clear to be recognized with some OCR library. The final image should look like this (not losing quality of text): I have tried to di...
[ "Without knowing the allowed character shapes, this is simply an impossible task. Because from an image processing point of view, nothing qualitatively distinguishes a character and the same character with a line across. So any \"blind\" processing that removes thin lines will as well destroy thin lines that can le...
[ 0 ]
[]
[]
[ "captcha", "image_processing", "ocr", "opencv", "python" ]
stackoverflow_0074149573_captcha_image_processing_ocr_opencv_python.txt
Q: price Histogram in python pandas I have the following table which shows the item and price for that item. item CAR_PRIC1 Car_PRICE2 0 H1 17400.00 18400.00 1 H2 35450.00 27400.00 2 H3 55780.00 57400.00 3 H4 78500.00 37400.00 4 H5 ...
price Histogram in python pandas
I have the following table which shows the item and price for that item. item CAR_PRIC1 Car_PRICE2 0 H1 17400.00 18400.00 1 H2 35450.00 27400.00 2 H3 55780.00 57400.00 3 H4 78500.00 37400.00 4 H5 25609.55 77400.00 5 H6 ...
[ "It's straightforward with seaborn displot (editing your df a bit to make the plot more readable):\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\ndata = {\n 'item': {0: 'H1', 1: 'H2', 2: 'H3', 3: 'H4', 4: 'H5', 5: 'H6'},\n 'CAR_PRICE1': {0: 7400.0, 1: 135450.0, 2: 5780.0, 3: 7...
[ 0 ]
[]
[]
[ "matplotlib", "pandas", "python", "seaborn" ]
stackoverflow_0074151371_matplotlib_pandas_python_seaborn.txt
Q: How to convert Unicode codepoint to UTF-8 Hex Bytes? Given a list of all emojis, I need to convert unicode codepoint to UTF-8 hex bytes programmatically. For example: Take this emoji: https://unicode-table.com/en/1F606/ and convert 1F606 to F0 9F 98 86 Please provide code examples in python or hacklang (php). A: ...
How to convert Unicode codepoint to UTF-8 Hex Bytes?
Given a list of all emojis, I need to convert unicode codepoint to UTF-8 hex bytes programmatically. For example: Take this emoji: https://unicode-table.com/en/1F606/ and convert 1F606 to F0 9F 98 86 Please provide code examples in python or hacklang (php).
[ "If you want to know how to notate a Unicode character like U+1F606 in PHP, then do this:\n$myChar = \"\\u{1F606}\";\n\nYou must write it down like this and not make it up from substrings.\nIf you have '1F606' as a character string, you must convert it.\n$code = \"1F606\";\n\n$myChar = html_entity_decode('&#x'.$cod...
[ 1 ]
[]
[]
[ "hacklang", "php", "python", "python_unicode", "unicode_string" ]
stackoverflow_0074142477_hacklang_php_python_python_unicode_unicode_string.txt
Q: Error when trying to plot a map in folium I'm getting an error which is really weird to me because I have done the exact same thing before and no error popped up. Here I'm trying to plot some points in a map of Jacksonville FL. This is my code: map_jsv = folium.Map(location = [latitud, longit], zoom_start = 10 ) f...
Error when trying to plot a map in folium
I'm getting an error which is really weird to me because I have done the exact same thing before and no error popped up. Here I'm trying to plot some points in a map of Jacksonville FL. This is my code: map_jsv = folium.Map(location = [latitud, longit], zoom_start = 10 ) for lat, lng, neighborhood in zip(df['Latitude']...
[ "Hey folk I just solved it, the problem wasn't with Folium, it was with the df, it changed his type when I dropped the null values with df.dropna, fixed it with a parenthesis: df.dropna() LOL. Have a great day\n" ]
[ 0 ]
[]
[]
[ "folium", "python" ]
stackoverflow_0074137125_folium_python.txt
Q: Returning a `tuple[str, str]` from `str.split(s, maxsplit=1)` I have this function: __version__: str | None = ... def get_version_parts() -> tuple[str, str] | None: if __version__ is None: return None return tuple(__version__.split('+', maxsplit=1)) Unsurprisingly, Mypy does not realize that the ...
Returning a `tuple[str, str]` from `str.split(s, maxsplit=1)`
I have this function: __version__: str | None = ... def get_version_parts() -> tuple[str, str] | None: if __version__ is None: return None return tuple(__version__.split('+', maxsplit=1)) Unsurprisingly, Mypy does not realize that the returned value here is indeed tuple[str, str], instead thinking tha...
[ "Edit: I forgot about the case when the string does not contain a +. Then only one value is produced, not two. Credit to \"Ry-\" in the comments for pointing this out.\nI am leaving this post and answer up because I think the \"unpack, then return\" idiom might be useful to other people.\n\nOne workaround that make...
[ 1, 1 ]
[]
[]
[ "mypy", "python", "type_hinting" ]
stackoverflow_0074146380_mypy_python_type_hinting.txt
Q: ModuleNotFoundError: NO module named 'binance.spot' hello I'm running into a loop of errors when running a python code with all requirements installed, already try to python -m pip install python-binance and had no success bellow the some of the loop errors C:\Users\djino\Documents\Bot\Trading_Bot_9000 [main ≡]> p...
ModuleNotFoundError: NO module named 'binance.spot'
hello I'm running into a loop of errors when running a python code with all requirements installed, already try to python -m pip install python-binance and had no success bellow the some of the loop errors C:\Users\djino\Documents\Bot\Trading_Bot_9000 [main ≡]> python get_data.py sh run_signal.sh python tradebot.py Exe...
[ "To fix this problem ModuleNotFoundError: NO module named 'binance.spot'\ninstall the module binance-connector\npip install binance-connector\ndocs here:https://binance-connector.readthedocs.io/en/latest/getting_started.html\n", "Αs @Tanner Martin mentioned hereWhy am I getting this error 'ModuleNotFoundError\nYo...
[ 1, 0 ]
[]
[]
[ "modulenotfounderror", "pip", "python", "python_3.x" ]
stackoverflow_0074137131_modulenotfounderror_pip_python_python_3.x.txt
Q: Conditional import in Python when creating an object inheriting from it I create a package connecting to other libraries (livelossplot). It has a lot of optional dependencies (deep learning frameworks), and I don't want to force people to install them. Right now I use conditional imports, in the spirit of: try: ...
Conditional import in Python when creating an object inheriting from it
I create a package connecting to other libraries (livelossplot). It has a lot of optional dependencies (deep learning frameworks), and I don't want to force people to install them. Right now I use conditional imports, in the spirit of: try: from .keras_plot import PlotLossesKeras except ImportError: # import ke...
[ "The most straighforward and most easily understood solution would be to split your library into submodules.\nIt has several advantages over trying to do imports on object initialization:\n\nThe user knows what to expect. import my_lib.keras is very likely to depend on keras\nImport errors happen during import, not...
[ 4, 0 ]
[]
[]
[ "class", "inheritance", "python", "python_import" ]
stackoverflow_0053958762_class_inheritance_python_python_import.txt
Q: Maya script won't run in Maya 2022. `reload` is not defined Trying to run a script that works fine in maya 2018 but wont in 2022 import gw_anim_clip reload(gw_anim_clip) gw_anim_clip.anim_clip_ui() I'm getting this error: Error: name 'reload' is not defined Traceback (most recent call last): File "<maya console...
Maya script won't run in Maya 2022. `reload` is not defined
Trying to run a script that works fine in maya 2018 but wont in 2022 import gw_anim_clip reload(gw_anim_clip) gw_anim_clip.anim_clip_ui() I'm getting this error: Error: name 'reload' is not defined Traceback (most recent call last): File "<maya console>", line 2, in <module> NameError: name 'reload' is not defined #...
[ "reload is not available in python 3.9 and maya 2022 already in 3.9. So you have to use importlib.reload to reload a module.\nimport importlib\nimport gw_anim_clip\nimportlib.reload(gw_anim_clip)\ngw_anim_clip.anim_clip_ui()\n\n", "Maya 2022 use python 3.7 and you need to import reload first.\nfrom imp import rel...
[ 1, 0 ]
[]
[]
[ "maya", "python", "python_2to3" ]
stackoverflow_0072349091_maya_python_python_2to3.txt
Q: trouble getting pending transaction receipt for Binance Smart Chain I can not get transaction receipt for BSC chain. I tried 3 different approaches but I failed. Here is my code: def get_transaction_recipt(txid): recipt = web3.eth.getTransactionReceipt(txid) print(recipt) async def get_event(): async ...
trouble getting pending transaction receipt for Binance Smart Chain
I can not get transaction receipt for BSC chain. I tried 3 different approaches but I failed. Here is my code: def get_transaction_recipt(txid): recipt = web3.eth.getTransactionReceipt(txid) print(recipt) async def get_event(): async with connect('wss://bsc.getblock.io/mainnet/?api_key=<api-key>') as ws: ...
[ "Without looking at your code, seems like you try to get receipts for transactions that didn't take place yet. Block needs to be closed before they're available.\n" ]
[ 0 ]
[]
[]
[ "binance_smart_chain", "python", "web3py" ]
stackoverflow_0071691092_binance_smart_chain_python_web3py.txt
Q: Find the row index number of an array in a 2D numpy array If I have a 2D numpy array A: [[6 9 6] [1 1 2] [8 7 3]] And I have access to array [1 1 2]. Clearly, [1 1 2] belongs to index 1 of array A. But how do I do this? A: Access the second row using the following operator: import numpy as np ...
Find the row index number of an array in a 2D numpy array
If I have a 2D numpy array A: [[6 9 6] [1 1 2] [8 7 3]] And I have access to array [1 1 2]. Clearly, [1 1 2] belongs to index 1 of array A. But how do I do this?
[ "Access the second row using the following operator:\nimport numpy as np \n \na = np.array([[6, 9, 6], ...
[ 1, 0, 0, 0 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0074151870_arrays_numpy_python.txt
Q: 'and' operator in string.contains I have a pandas series in which I am applying string search this way df['column_name'].str.contains('test1') This gives me true/false list depending on string 'test1' is contained in column 'column_name' or not. However I am not able to test two strings where I need to check if ...
'and' operator in string.contains
I have a pandas series in which I am applying string search this way df['column_name'].str.contains('test1') This gives me true/false list depending on string 'test1' is contained in column 'column_name' or not. However I am not able to test two strings where I need to check if both strings are there or not. Somethin...
[ "No you have to create 2 conditions and use & and wrap parentheses around the conditions due to operator precedence:\n(df['column_name'].str.contains('test1')) & (df['column_name'].str.contains('test2))\n\nIf you wanted to test for either word then the following would work:\ndf['column_name'].str.contains('test1|te...
[ 6, 2, 2, 0, 0 ]
[]
[]
[ "pandas", "python", "series", "string" ]
stackoverflow_0035344564_pandas_python_series_string.txt
Q: Trying to make a program that randomises teams acording to user input (amount of teams and names of all participants) these will then be equal in size I need to make a program where the user inputs all students names (this is then converted into a list each name becomes an item) and y amount of teams, the program ...
Trying to make a program that randomises teams acording to user input (amount of teams and names of all participants) these will then be equal in size
I need to make a program where the user inputs all students names (this is then converted into a list each name becomes an item) and y amount of teams, the program will then randomize the teams with the names of the students. Ex. The user chooses 2 teams and has 4 different students the program then spits out 2 randomi...
[ "list.pop() is an easy way here:\nimport random\n\nplayers = [\"Anton\", \"Bernd\", \"Charlie\", \"Dickins\", \"Eugine\", \"Franco\"]\nteams = {}\nnum_teams = 5 # This is what you would ask the user\n\ndef run():\n for team_number in range(num_teams):\n teams.update({team_number: []})\n\n while len(p...
[ 1, 0 ]
[]
[]
[ "python", "random" ]
stackoverflow_0074151341_python_random.txt
Q: Python 3 Opencv set up problem: "cannot find reference 'VideoCapture' in __init__.py" on Pycharm IDE I am trying to install OpenCv and run some code on PyCharm on Mac. I have installed the opencv package as well as numpy but when I run the code this error shows up on Pycharm IDE: "cannot find reference 'VideoCaptu...
Python 3 Opencv set up problem: "cannot find reference 'VideoCapture' in __init__.py" on Pycharm IDE
I am trying to install OpenCv and run some code on PyCharm on Mac. I have installed the opencv package as well as numpy but when I run the code this error shows up on Pycharm IDE: "cannot find reference 'VideoCapture' in __init__.py" In fact, every time I write example_variable = cv2., PyCharm is not giving me any opti...
[ "Try one of this solutions:\n\nRight-click on source Directory\nMark Directory as -> source root\nFile --> Invalidate Caches / Restart... -> Invalidate and Restart\n\nOR:\n\nIn your IDE, go to settings -> preferences -> django\nEnsure your Root directory, your settings.py and your manage.py are in the right place\n...
[ 3, 2, 0, 0 ]
[]
[]
[ "macos", "opencv", "pycharm", "python", "python_3.x" ]
stackoverflow_0060229392_macos_opencv_pycharm_python_python_3.x.txt
Q: Match index and save in a new column I have table with two columns: Index Col_1 Key 1 3,5 1001 2 4,5,6 2004 3 7845 4 1,6 9658 5 2,3 5236 6 6066 Need to check Col_1 and save the Key for each index number mentioned in the Col_1. For Example: in Index 1, Col_1 has values 3,5 so need to save the Key of Index...
Match index and save in a new column
I have table with two columns: Index Col_1 Key 1 3,5 1001 2 4,5,6 2004 3 7845 4 1,6 9658 5 2,3 5236 6 6066 Need to check Col_1 and save the Key for each index number mentioned in the Col_1. For Example: in Index 1, Col_1 has values 3,5 so need to save the Key of Index 3,5 in Key_Checked column. ...
[ "You can use:\n# ensure we have strings everywhere\ndf = df.astype(str)\n\ndf['Key_Checked'] = (df['Col_1'].str.split(',').explode()\n .map(df.set_index('Index')['Key']).dropna()\n .groupby(level=0).agg(','.join)\n .reindex(df.index, fill_value='')\n ...
[ 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074151748_pandas_python.txt
Q: Jupyter Notebook ValueError: min() arg is an empty sequence For some background, I read a csv file for my dataset and isolated some of the data using: isolated = diff['2012-09-28' <= pd.to_datetime(diff['start_date'])] isolated The code worked well until I code this: counter = 0 xlim = [] current = '' for date in...
Jupyter Notebook ValueError: min() arg is an empty sequence
For some background, I read a csv file for my dataset and isolated some of the data using: isolated = diff['2012-09-28' <= pd.to_datetime(diff['start_date'])] isolated The code worked well until I code this: counter = 0 xlim = [] current = '' for date in isolated['start_date']: if date in debates and current != da...
[ "min([])\n\nValueError: min() arg is an empty sequence\n\nSo, error is clear. Your line x_min = min(xlim) is computing min([]). Or said otherwise xlim is empty.\nYour real problem is to understand why it is. That we can't say, it is in your data.\n" ]
[ 0 ]
[]
[]
[ "jupyter_notebook", "python" ]
stackoverflow_0074152216_jupyter_notebook_python.txt
Q: Google Earth Engine with Jupyter Notebook I want to transfer to Google Earth Engine satellite images without downloading to Jupyter Notebook. Namely, I want for process in Jupyter Notebook of Google Earth Engine images brought to screen. I tried some solution paths but I can't. Can you help me please? Thank you. M...
Google Earth Engine with Jupyter Notebook
I want to transfer to Google Earth Engine satellite images without downloading to Jupyter Notebook. Namely, I want for process in Jupyter Notebook of Google Earth Engine images brought to screen. I tried some solution paths but I can't. Can you help me please? Thank you. My output image from GEE; >>> print(type(image4)...
[ "If by brought to screen you mean displayed in Jupyter Notebooks, you can use Geemap.\nimport geemap\n\nMap=geemap.Map()\nMap.addLayer(image4, {}, 'image name')\nMap\n\nn.b. {} can be a dictionary of visualization parameters for your image.\nThe image will be displayed in Jupyter but will still be held on the cloud...
[ 0 ]
[]
[]
[ "geemap", "google_earth_engine", "jupyter_notebook", "python" ]
stackoverflow_0073614252_geemap_google_earth_engine_jupyter_notebook_python.txt
Q: how to get the values in a class by using a classmethod in python This is my first question here, very exciting. I have a class with a bunch of values attached to it. I would like to get a specific value using a classmethod, or return a list of values. However I just don't seem to be able to get it right. class St...
how to get the values in a class by using a classmethod in python
This is my first question here, very exciting. I have a class with a bunch of values attached to it. I would like to get a specific value using a classmethod, or return a list of values. However I just don't seem to be able to get it right. class StrEnum(str, Enum): def __str__(self) -> str: return str.__st...
[ "Welcome to StackOverflow!!!! Here's a way to return any sublist of the creatures. It also has a branch to return ALL if no creatures are specified:\nfrom enum import Enum \n ...
[ 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074151912_list_python.txt
Q: How to resolve this error of "Cannot find reference 'imread' in '__init__.py" in python after installing opencv? I am new to python and installed opencv by typing: pip install opencv-contrib-python in the command prompt. Below I have shown a very simple example of reading in an image and showing it on the screen: ...
How to resolve this error of "Cannot find reference 'imread' in '__init__.py" in python after installing opencv?
I am new to python and installed opencv by typing: pip install opencv-contrib-python in the command prompt. Below I have shown a very simple example of reading in an image and showing it on the screen: However, I get this error: When I hover over the imread method in PyCharm, it says Cannot find reference 'imread' in...
[ "If you are using python interpreter with anaconda change it to default python one. if you have not installed python separately then install it and assign the path to it.\nsomewhat this will be the path\nc://user/APpData/Local/Programs/Python/python39/python.exe\n", "The NumPy multicore import error is a result o...
[ 1, 0 ]
[ "To solve it, you should upgrade numpy installation. Try:\npip install -U numpy\n\nFor information here\n", "Instead of doing:\nimport cv2\ntry doing:\nfrom cv2 import cv2\nThis worked for me after a lot of troubleshooting also using pycharm. I now have access to all of the regular cv2 methods.\n" ]
[ -1, -1 ]
[ "numpy", "opencv", "python" ]
stackoverflow_0065582347_numpy_opencv_python.txt
Q: Read straming data from Azure Blob storage into Databricks I'm trying to read files from an blob storage in databricks, make some computation through dataframe and write the dataframe on cassandra. At the moment file are of append blob type storage so, like said in the documentation page https://learn.microsoft.co...
Read straming data from Azure Blob storage into Databricks
I'm trying to read files from an blob storage in databricks, make some computation through dataframe and write the dataframe on cassandra. At the moment file are of append blob type storage so, like said in the documentation page https://learn.microsoft.com/en-us/azure/databricks/kb/data-sources/wasb-check-blob-types, ...
[ "Changed approach and streamed the file directly into a dataframe. The answer was due to this post Read csv from Azure blob Storage and store in a DataFrame, the answer from \"lsl__\".\nfrom io import BytesIO\nimport pandas as pd\n\nblob_service_client = BlobServiceClient(account_url=\"https://\"+STORAGEACCOUNTURL+...
[ 1 ]
[]
[]
[ "azure", "azure_blob_storage", "azure_databricks", "python" ]
stackoverflow_0074150951_azure_azure_blob_storage_azure_databricks_python.txt
Q: What is the correct way to convert a csv file with text to recordIO format? I need to convert my dataset (includes text format) to recordIO format. I have tried below code. However, I am unable to fix the below error. Do I need to make further changes in my data format? ValueError: Unsupported dtype object on arra...
What is the correct way to convert a csv file with text to recordIO format?
I need to convert my dataset (includes text format) to recordIO format. I have tried below code. However, I am unable to fix the below error. Do I need to make further changes in my data format? ValueError: Unsupported dtype object on array Code: import io import sagemaker.amazon.common as smac X = df[['Subject','Bod...
[ "According to documentation in \"Common Data Formats for Training\",\nyour content-type is associated with the algorithms in the following table:\n\n\n\n\nContentType\nAlgorithm\n\n\n\n\napplication/x-recordio\nObject Detection Algorithm\n\n\napplication/x-recordio-protobuf\nFactorization Machines, K-Means, k-NN, L...
[ 0 ]
[]
[]
[ "amazon_sagemaker", "csv", "protocol_buffers", "python", "record" ]
stackoverflow_0074138440_amazon_sagemaker_csv_protocol_buffers_python_record.txt
Q: Can't import pandas nor numpy, AttributeError: "module 'numpy.random' has no attribute 'Generator'" I tried with updating everything (conda, ipython, numpy, pandas) but I always get an error AttributeError: module 'numpy.random' has no attribute 'Generator' when trying to import numpy, pandas and sklearn. I have n...
Can't import pandas nor numpy, AttributeError: "module 'numpy.random' has no attribute 'Generator'"
I tried with updating everything (conda, ipython, numpy, pandas) but I always get an error AttributeError: module 'numpy.random' has no attribute 'Generator' when trying to import numpy, pandas and sklearn. I have no idea how to fix it, did someone had a same problem in a last few days?
[ "For me it worked again, when restarting the kernel. I´m using VSCode and notebook files.\n" ]
[ 0 ]
[]
[]
[ "error_handling", "jupyter_notebook", "numpy", "pandas", "python" ]
stackoverflow_0071742405_error_handling_jupyter_notebook_numpy_pandas_python.txt
Q: Drop rows with at least a cell having a value in a given list with the .isin pandas.DataFrame method I'm trying to use the .isin method but I don't have the expected result. Here is a minimal reproducible example import pandas as pd df = pd.DataFrame({'num_legs': [2, 4], 'num_wings': [2, 0]}, index=['falcon', 'dog...
Drop rows with at least a cell having a value in a given list with the .isin pandas.DataFrame method
I'm trying to use the .isin method but I don't have the expected result. Here is a minimal reproducible example import pandas as pd df = pd.DataFrame({'num_legs': [2, 4], 'num_wings': [2, 0]}, index=['falcon', 'dog']) print(df) print(df[df.isin([0, 2])]) It doesn't delete the row, but replaces the cell by NaN.
[ "For filtering need bolean Series, if check all column get boolean DataFrame:\nSo if need test if at least one True per row use DataFrame.any, If need test if all True per row use DataFrame.all:\nprint (df.isin([0, 2]))\n num_legs num_wings\nfalcon True True\ndog False True\n\nprint...
[ 2 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074152405_pandas_python.txt
Q: Cannot install psycopg2 with pip3 on M1 Mac I cannot install psycopg2 on my M1 Mac and I used pip3. When I tried to install with pip3 install psycopg2 The output like that: ERROR: Command errored out with exit status 1: command: /opt/homebrew/opt/python@3.9/bin/python3.9 -c 'import sys, setuptools, tokenize...
Cannot install psycopg2 with pip3 on M1 Mac
I cannot install psycopg2 on my M1 Mac and I used pip3. When I tried to install with pip3 install psycopg2 The output like that: ERROR: Command errored out with exit status 1: command: /opt/homebrew/opt/python@3.9/bin/python3.9 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/m5/vhny...
[ "try this:\nbrew install libpq --build-from-source\nbrew install openssl\n\nexport LDFLAGS=\"-L/opt/homebrew/opt/openssl@1.1/lib -L/opt/homebrew/opt/libpq/lib\"\nexport CPPFLAGS=\"-I/opt/homebrew/opt/openssl@1.1/include -I/opt/homebrew/opt/libpq/include\"\n\npip3 install psycopg2\n\n", "Before reverting to any of...
[ 80, 30, 6, 1 ]
[]
[]
[ "apple_m1", "pip", "psycopg2", "python", "python_3.x" ]
stackoverflow_0066888087_apple_m1_pip_psycopg2_python_python_3.x.txt
Q: Python re matching fails to work for extened unicode range import re pat = re.compile(r"[\u20000-\u2A6D6]+") pat.match("Hello World!") This will give us a result <re.Match object; span=(0, 5), match='Hello'> But in fact, the input string here is fully ASCII which is not from the unicode range. Is this expected...
Python re matching fails to work for extened unicode range
import re pat = re.compile(r"[\u20000-\u2A6D6]+") pat.match("Hello World!") This will give us a result <re.Match object; span=(0, 5), match='Hello'> But in fact, the input string here is fully ASCII which is not from the unicode range. Is this expected? If so, how to compile those unicode range in practice?
[ "The pattern currently describes a character class consisting of either \\u2000, any character in the range 0-\\u2A6D or 6.\nFor python character literals that are wider than 2 bytes, you need to use the escape sequence \\U with 8 hex digits:\npat = re.compile(r\"[\\U00020000-\\U0002A6D6]+\")\n\n" ]
[ 1 ]
[]
[]
[ "python", "python_re", "unicode" ]
stackoverflow_0074152156_python_python_re_unicode.txt
Q: Paramiko ssh client ssh_stderr comes as 'sudo: no tty present and no askpass program specified' while executing docker command in Python I tried to read the docker container logs using an ssh connection. def test_read_ssh(): ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy(...
Paramiko ssh client ssh_stderr comes as 'sudo: no tty present and no askpass program specified' while executing docker command in Python
I tried to read the docker container logs using an ssh connection. def test_read_ssh(): ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(IPAddress, username='usr', password='pwd') ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command('sudo docker logs -f 16...
[ "The problem was due to a password request that comes immediately after 'sudo' command.\nFor this, I need to enter a Password and then the problem was solved!\ndef test_read_ssh():\n ssh = paramiko.SSHClient()\n ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n ssh.connect(IPAddress, username='us...
[ -1 ]
[]
[]
[ "openssh", "paramiko", "python", "ssh", "stdout" ]
stackoverflow_0074140694_openssh_paramiko_python_ssh_stdout.txt
Q: Download from S3, store in /tmp/ of Lambda and unzip in /tmp/ directory I have a zip file on S3. I need to use /tmp folder of a Lambda for lazy-loading that I am using to store the zip file and then I need the folder to contain the unzipped contents. I am using Python for the operations. Below is the code: import ...
Download from S3, store in /tmp/ of Lambda and unzip in /tmp/ directory
I have a zip file on S3. I need to use /tmp folder of a Lambda for lazy-loading that I am using to store the zip file and then I need the folder to contain the unzipped contents. I am using Python for the operations. Below is the code: import sys import zipfile import subprocess s3 = boto3.resource('s3') s3.meta.clien...
[ "First thing is to confirm that the file has been downloaded (How to Check if a File Exists in Python – dbader.org).\nThe problem might be that the sub-process can't find unzip.\nI notice you have imported zipfile, so you could that library to unzip. From Unzipping files in python:\nimport zipfile\nwith zipfile.Zip...
[ 2, 0 ]
[]
[]
[ "amazon_s3", "amazon_web_services", "aws_lambda", "python", "zip" ]
stackoverflow_0057189443_amazon_s3_amazon_web_services_aws_lambda_python_zip.txt
Q: diff in different periods and variable I would like to create a function to transform some specific features in a df with the pandas method .diff in the different indicated periods. I got it in a two step mode, but I am sure this can be one liner, iow, it can be simpler. Given the following df: df = pd.DataFrame({...
diff in different periods and variable
I would like to create a function to transform some specific features in a df with the pandas method .diff in the different indicated periods. I got it in a two step mode, but I am sure this can be one liner, iow, it can be simpler. Given the following df: df = pd.DataFrame({"Category":["A"]*10+["B"]*50+["C"]*15+["D"]*...
[ "You just need list comprehesion and some reduce function in a manner that you can concat with pandas:\nimport functools\nimport operator\n \ndef functools_reduce(a):\n return functools.reduce(operator.concat, a)\n\npd.concat(functools_reduce(map(lambda dict_items: [df[dict_items[0]].diff(periods=diff_value).ren...
[ 2 ]
[]
[]
[ "dictionary", "feature_engineering", "python" ]
stackoverflow_0074135635_dictionary_feature_engineering_python.txt
Q: Unable to extract full src attribute from img tag It seemed simple enough at first - just use soup.find and then .get('src') or .attrs['src'], but major chunks of the src has been replaced with "/////" The value is actually much longer: DevTools screenshot What's baffling me is that I saved str(soup) as a html fi...
Unable to extract full src attribute from img tag
It seemed simple enough at first - just use soup.find and then .get('src') or .attrs['src'], but major chunks of the src has been replaced with "/////" The value is actually much longer: DevTools screenshot What's baffling me is that I saved str(soup) as a html file, and also used display(HTML(str(soup))) and with bo...
[ "I figured it out as I was writing in the question about inspecting the saved html file - I only used devtools and didn't open and see all the saved html code itself.\nWhen I open the html on vscode, there are actually two occurrences of the id dimg_179 - the one in the img tag itself, and another in a script tag:\...
[ 0 ]
[]
[]
[ "beautifulsoup", "html", "python" ]
stackoverflow_0074152499_beautifulsoup_html_python.txt
Q: How to print all lemma_names of word without repeating its synonyms and pos_tag more than once in NLTK synsets? I'm trying to find a synsets of words. Here's my codes: from nltk.corpus import wordnet as wn from nltk import pos_tag def getSynonyms(word1): synonymList1 = [] for data1 in word1: wordn...
How to print all lemma_names of word without repeating its synonyms and pos_tag more than once in NLTK synsets?
I'm trying to find a synsets of words. Here's my codes: from nltk.corpus import wordnet as wn from nltk import pos_tag def getSynonyms(word1): synonymList1 = [] for data1 in word1: wordnetSynset1 = wn.synsets(data1) tempList1=[] for synset1 in wordnetSynset1: synLemmas = syn...
[ "If you simply want to get all synonyms for a word using nltk, this is the fastest implementation I have found so far:\ndef get_word_synonyms(word):\n synonyms = set()\n for ss in nltk.corpus.wordnet.synsets(word):\n synonyms = synonyms.union(ss.lemma_names())\n return synonyms\n\nYou can then call ...
[ 2, 1 ]
[ "syn1 = set(getSynonyms(word1))\nMaking the returned list into a set will remove duplicates. I am assuming here that the order is not important since a set does not have a defined order.\n" ]
[ -1 ]
[ "nltk", "python", "synonym", "tags", "wordnet" ]
stackoverflow_0045251901_nltk_python_synonym_tags_wordnet.txt
Q: why am I getting this error : AttributeError: 'LocalStack' object has no attribute '__ident_func__' in SQLAlchemy I am trying to create an app with flask, and I am in this step that I need to connect my database which is in my local server, to achieve this I have used the command db = SQLAlchemy(app) and imported ...
why am I getting this error : AttributeError: 'LocalStack' object has no attribute '__ident_func__' in SQLAlchemy
I am trying to create an app with flask, and I am in this step that I need to connect my database which is in my local server, to achieve this I have used the command db = SQLAlchemy(app) and imported SQLALchemy from flask-alchemy(I have provided my codes bellow in detail).when I start my flask app server I get the err...
[ "I had a similar issue, I uninstalled it using python -m pip uninstall flask-sqlalchemy and installed with python -m pip install flask-sqlalchemy . The issue was solved.\n", "I was able to fix this problem by editing my requirements.txt to include the psycopg2-binary instead of psycopg2 itself.\nAfterwards, I re-...
[ 11, 1, 1, 0 ]
[ "I really should have mentioned that the source codes I had cloned from a GitHub repo so there was code pollution that affected my code files I guess despite installing all the requirements with the command pip install -r requirement.txt. A work around this is that I deleted all my project files and started my proj...
[ -1, -2 ]
[ "flask", "flask_sqlalchemy", "python", "sqlalchemy" ]
stackoverflow_0072256625_flask_flask_sqlalchemy_python_sqlalchemy.txt
Q: No module named 'scikit_posthocs' I am trying to run a post-hoc test on an LM in pandas and I want to use the scikit_posthocs package as follows: import statsmodels.api as sa import statsmodels.formula.api as sfa import scikit_posthocs as sp sp.posthoc_ttest(newdf, val_col='duration', group_col='alcohol', p_adjust...
No module named 'scikit_posthocs'
I am trying to run a post-hoc test on an LM in pandas and I want to use the scikit_posthocs package as follows: import statsmodels.api as sa import statsmodels.formula.api as sfa import scikit_posthocs as sp sp.posthoc_ttest(newdf, val_col='duration', group_col='alcohol', p_adjust='holm') However, I am getting the err...
[ "The issue has now been solved. I tried the following command again:\n\nconda install -c conda-forge scikit-posthocs\n\nAnd it worked!\nHave a great day :)\n" ]
[ 0 ]
[]
[]
[ "api", "pandas", "python", "statistics", "statsmodels" ]
stackoverflow_0074152423_api_pandas_python_statistics_statsmodels.txt
Q: Converting an element of a dataframe into string element - python In python, I have such a data frame: pn Out[249]: a b c d e 2 4 8 12 131 127 cn.dtypes Out[253]: c1 object c2 object c3 object dtype: object I want to select pn["b"] as string. When I paste below, I get the below value:...
Converting an element of a dataframe into string element - python
In python, I have such a data frame: pn Out[249]: a b c d e 2 4 8 12 131 127 cn.dtypes Out[253]: c1 object c2 object c3 object dtype: object I want to select pn["b"] as string. When I paste below, I get the below value: pn["b"] Out[257]: 2 8 Name: b, dtype: object But I want the outp...
[ "You can cast the column b to string type using astype method and then use iloc to access the specific row.\n>>> import pandas as pd\n>>>\n>>> pn = pd.DataFrame({'b': [8]}, index=[2])\n>>> pn\n b\n2 8\n>>> pn['b'].astype(str).iloc[0]\n'8'\n>>> type(pn['b'].astype(str).iloc[0])\n<class 'str'>\n\n" ]
[ 1 ]
[]
[]
[ "python", "string" ]
stackoverflow_0074152462_python_string.txt
Q: Pandas dataframe row operation within a group I have a dataframe with information about a stock that looks like this: Product ID Initial stock Quantity a1 5 -2 a1 5 -1 a1 5 7 a2 10 2 a2 10 -6 b1 14 -9 b1 14 11 Each row represents a purchase/sale of a certain product. I want to add a new column to know the...
Pandas dataframe row operation within a group
I have a dataframe with information about a stock that looks like this: Product ID Initial stock Quantity a1 5 -2 a1 5 -1 a1 5 7 a2 10 2 a2 10 -6 b1 14 -9 b1 14 11 Each row represents a purchase/sale of a certain product. I want to add a new column to know the current stock of the product. The f...
[ "Compute a groupby.cumsum of the quantity and subtract it from the Initial stock :\ndf['Current stock'] = (df['Initial stock']\n .add(df.groupby('Product ID')['Quantity'].cumsum())\n )\n\noutput:\n Product ID Initial stock Quantity Current stock\n0 a1 ...
[ 2 ]
[]
[]
[ "group_by", "pandas", "python" ]
stackoverflow_0074152449_group_by_pandas_python.txt
Q: IPython Notebook Kernel getting dead while running Kmeans I am running K-means clustering on some 400K observations with 12 variables. Initially as soon as I run the cell with Kmeans code, it would pop up a message after 2 mins saying the kernel is interrupted and would restart. And then it takes ages like as if t...
IPython Notebook Kernel getting dead while running Kmeans
I am running K-means clustering on some 400K observations with 12 variables. Initially as soon as I run the cell with Kmeans code, it would pop up a message after 2 mins saying the kernel is interrupted and would restart. And then it takes ages like as if the kernel got dead and the code won't run anymore. So I tried ...
[ "From some investigation, this likely has nothing to do with iPython Notebook / Jupyter. It seems this is an issue with sklearn, which traces back to an issue with numpy. See related github issues sklearn here and here, and the underlying numpy issue here.\nUltimately, calculating the Silhouette Score requires calc...
[ 6, 0 ]
[]
[]
[ "ipython", "numpy", "pandas", "python", "scikit_learn" ]
stackoverflow_0032573948_ipython_numpy_pandas_python_scikit_learn.txt
Q: Create a function that has 3 parameters: list of integers (num), integer number (n1), and another integer number (n2) The function will return a list of integers that are multiples of either n1 or n2. This is my code def exercise_3(nums, n1, n2): multiples = [] for i in nums: if i % n1 == 0 and i ...
Create a function that has 3 parameters: list of integers (num), integer number (n1), and another integer number (n2)
The function will return a list of integers that are multiples of either n1 or n2. This is my code def exercise_3(nums, n1, n2): multiples = [] for i in nums: if i % n1 == 0 and i % n2 == 0: multiples.append(i) return multiples It gives an Assertion Error AssertionError ...
[ "as per question, you are required to find The function will return a list of integers that are multiples of either n1 or n2.\ninteger which are multiple of n1 or n2. ie if any integer of any one of n1 or n2, it is fine.\nso in you code you have wrote if i % n1 == 0 and i % n2 == 0: which say that integer should be...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074152550_python.txt
Q: determine OS distribution of a docker image I need to determine the OS distribution name for any docker image. I can tag ubuntu:latest as image1:latest, but I should be able to get the distribution information of image1:latest when it is launched. For achieving this, I used the below mentioned command to determine...
determine OS distribution of a docker image
I need to determine the OS distribution name for any docker image. I can tag ubuntu:latest as image1:latest, but I should be able to get the distribution information of image1:latest when it is launched. For achieving this, I used the below mentioned command to determine the OS version: $ docker tag ubuntu image1 $ $ d...
[ "The Filesystem Hierarchy Standard has a standard definition for /etc/os-release, which should be available on most distributions:\n\nThe /etc/os-release and /usr/lib/os-release files contain operating system identification data.\nThe basic file format of os-release is a newline-separated list of environment-like s...
[ 40, 8, 6, 2, 1, 0 ]
[]
[]
[ "docker", "dockerfile", "python" ]
stackoverflow_0035689431_docker_dockerfile_python.txt
Q: Calculating the min and max timing for going to bed I am a novice in using python and pandas so please pardon my ignorance. I am tracking my sleep habits using a watch to see what time I usually go to bed. In this hypothetical example, I have this data (just an excerpt of the overall data I have): import pandas as...
Calculating the min and max timing for going to bed
I am a novice in using python and pandas so please pardon my ignorance. I am tracking my sleep habits using a watch to see what time I usually go to bed. In this hypothetical example, I have this data (just an excerpt of the overall data I have): import pandas as pd df = pd.DataFrame( { "Date": ["16/10/202...
[ "Since the problem (as far as I can see) comes from PM having to be considered earlier than AM, an obvious solution would be to swap these, get the min and max, then swap the results; here's my take on this:\nimport pandas as pd\nimport datetime as dt\n\ndf = pd.DataFrame(\n {\n \"Date\": [\"16/10/2022\",...
[ 2, 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074135650_pandas_python.txt
Q: Making an animation of a line following a half circle using python Matplotlib As the title says, I am attempting to make a metronome animation however, I am unsure of what to do from this point. Right now, I have been successful in animating a stick that moves up and down from a fixed point however, the issue that...
Making an animation of a line following a half circle using python Matplotlib
As the title says, I am attempting to make a metronome animation however, I am unsure of what to do from this point. Right now, I have been successful in animating a stick that moves up and down from a fixed point however, the issue that I have run into is making that stick move back in forth in a half circle (like a m...
[ "Library Matplotlib is not necessary for PySimpleGUI used here.\nExample Code here just to demo the animation, bpm is not correct or exact, also no sound here.\nimport math\nimport time\nimport threading\nimport PySimpleGUI as sg\n\ndef func(window):\n global running\n while running:\n time.sleep(0.031...
[ 0 ]
[]
[]
[ "animation", "matplotlib", "python", "uibutton", "user_interface" ]
stackoverflow_0074149006_animation_matplotlib_python_uibutton_user_interface.txt
Q: Automatically edit last Telegram bot message after expiration period I'm trying to figure out how I can set an "expiration timer" on a message sent by a Telegram bot, containing a few buttons. Long story short, there's a function which selects a random picture from a folder, then sends it to a group, and in a sepa...
Automatically edit last Telegram bot message after expiration period
I'm trying to figure out how I can set an "expiration timer" on a message sent by a Telegram bot, containing a few buttons. Long story short, there's a function which selects a random picture from a folder, then sends it to a group, and in a separate message it sends an InlineKeyboard object with some buttons for the p...
[ "You apparently already know how to use PTBs JobQueue, so I'm sure that you can figure out how to schedule a new job from within the send_stuff function that edits the sent message :) All you need for that is context.job_queue.run_once and the return value of context.bot.send_message(job.context, text='RATE', reply...
[ 1, 0 ]
[]
[]
[ "bots", "python", "python_telegram_bot", "telegram" ]
stackoverflow_0074125542_bots_python_python_telegram_bot_telegram.txt
Q: "GET /static/my_style.css HTTP/1.1" 404 1660 Im getting this error "GET /static/my_style.css HTTP/1.1" 404 1660 in my terminal whenever I update my page I build. I think it's my code in my settings.py that is wrong and with the static files also. Tried different thing but still not working My static code right now...
"GET /static/my_style.css HTTP/1.1" 404 1660
Im getting this error "GET /static/my_style.css HTTP/1.1" 404 1660 in my terminal whenever I update my page I build. I think it's my code in my settings.py that is wrong and with the static files also. Tried different thing but still not working My static code right now STATIC_URL = '/static/' STATICFILES_DIRS = [ ...
[ "Change your main Django apps sittings below this code. \nSTATIC_URL = '/static/'\nSTATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), ]\nSTATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), \"static\")\n\nThis above code is enough to remove your errors. But you also can use this below code too. \nPut this code...
[ 0, 0 ]
[]
[]
[ "django", "django_staticfiles", "python", "static", "syntax_error" ]
stackoverflow_0058737660_django_django_staticfiles_python_static_syntax_error.txt
Q: Read EventBridge event output JSON using Lambda python I need some help with filtering some data from a EventBridge Notification. Currently, we have an EventBridge "RDS Cluster Event" Rule with Target = SNS. So, whenever an RDS Cluster even is encountered, we get email notification via SNS but there is too much in...
Read EventBridge event output JSON using Lambda python
I need some help with filtering some data from a EventBridge Notification. Currently, we have an EventBridge "RDS Cluster Event" Rule with Target = SNS. So, whenever an RDS Cluster even is encountered, we get email notification via SNS but there is too much info in the json email and we want to format it. Current email...
[ "You can try below workaround.\nprint(event['detail'])\n" ]
[ 0 ]
[]
[]
[ "amazon_rds", "aws_event_bridge", "lambda", "python" ]
stackoverflow_0071962818_amazon_rds_aws_event_bridge_lambda_python.txt
Q: How to convert a GCP kubeflow dataset into a pandas dataframe I'm trying to run my first kubeflow pipeline in GCP. This basically ingest data from a BigQuery data frame then sends that to a dataset where the next component in the pipeline pulls the dataset and runs that data inside a PyMC model. But I'm getting ...
How to convert a GCP kubeflow dataset into a pandas dataframe
I'm trying to run my first kubeflow pipeline in GCP. This basically ingest data from a BigQuery data frame then sends that to a dataset where the next component in the pipeline pulls the dataset and runs that data inside a PyMC model. But I'm getting errors, because the code does not recognize the dataset as a datafr...
[ "I figured this out....I needed to put a .output on the input_data variable inside the DataFrame function.\n" ]
[ 0 ]
[]
[]
[ "google_cloud_platform", "kubernetes", "pandas", "python" ]
stackoverflow_0074113959_google_cloud_platform_kubernetes_pandas_python.txt
Q: Error message: "'chromedriver' executable needs to be available in the path" I am using selenium with python and have downloaded the chromedriver for my windows computer from this site: http://chromedriver.storage.googleapis.com/index.html?path=2.15/ After downloading the zip file, I unpacked the zip file to my d...
Error message: "'chromedriver' executable needs to be available in the path"
I am using selenium with python and have downloaded the chromedriver for my windows computer from this site: http://chromedriver.storage.googleapis.com/index.html?path=2.15/ After downloading the zip file, I unpacked the zip file to my downloads folder. Then I put the path to the executable binary (C:\Users\michael\Do...
[ "I see the discussions still talk about the old way of setting up chromedriver by downloading the binary and configuring the path manually.\nThis can be done automatically using webdriver-manager\npip install webdriver-manager\n\nNow the above code in the question will work simply with below change,\nfrom selenium ...
[ 426, 291, 68, 20, 16, 10, 8, 7, 6, 5, 3, 3, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ "For mac osx users\n brew tap homebrew/cask\n brew cask install chromedriver\n\n\n", "For MAC users:\n\nDownload Chromedriver: https://sites.google.com/a/chromium.org/chromedriver/downloads\n\n2.In Terminal type \"sudo nano /etc/paths\"\n3.Add line with path to Cromedriver as example: \"/Users/username/Down...
[ -1, -2, -4 ]
[ "python", "selenium", "selenium_chromedriver" ]
stackoverflow_0029858752_python_selenium_selenium_chromedriver.txt
Q: How to implement batch normalization merging in python? I have defined the model as in the code below, and I used batch normalization merging to make 3 layers into 1 linear layer. The first layer of the model is a linear layer and there is no bias. The second layer of the model is a batch normalization and there ...
How to implement batch normalization merging in python?
I have defined the model as in the code below, and I used batch normalization merging to make 3 layers into 1 linear layer. The first layer of the model is a linear layer and there is no bias. The second layer of the model is a batch normalization and there is no weight and bias ( affine is false ) The third layer of ...
[ "Short Answer: As far as I can tell you need a model.eval() before the line\ninput = torch.randn(batch_size, in_nodes)\n\nsuch that the end looks like this\n...\nmodel.eval()\ninput = torch.randn(batch_size, in_nodes)\ntest_input = torch.ones(batch_size,internal_nodes)/100\nprint(model(input))\nprint(torch.t(torch....
[ 1 ]
[]
[]
[ "batch_normalization", "python", "pytorch" ]
stackoverflow_0074150653_batch_normalization_python_pytorch.txt
Q: Python pandas cross check substring and contain relations between columns A B C catastrop animal True ani count True rows cata False Second rownumbers False counter counters True column inner False time strong kind membrane A and B contain both string and substring, I want to check if column A has a val...
Python pandas cross check substring and contain relations between columns
A B C catastrop animal True ani count True rows cata False Second rownumbers False counter counters True column inner False time strong kind membrane A and B contain both string and substring, I want to check if column A has a value 'counter', and that value is either having a subs...
[ "One way to achieve this is as follows:\n\nFor a_contains_b, use Series.str.contains with a string consisting of a list of values from column B, joined with | delimiter to create alternatives (so: 'animal|count|cata|rownumbers|counters|inner|time|strong|kind|membrane').\nFor b_contains_a, we want to use Series.str....
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074152487_pandas_python.txt
Q: Call Function after Combobox Clicked I am creating a program that automatically generates a graph of real estate in cities and displays it through the Tkinter window just to expand my understanding of Python. In this program, I added a feature that allows users to choose many options when they decide which option ...
Call Function after Combobox Clicked
I am creating a program that automatically generates a graph of real estate in cities and displays it through the Tkinter window just to expand my understanding of Python. In this program, I added a feature that allows users to choose many options when they decide which option should they choose to generate the graph. ...
[ "Updated - since <<ComboboxSelected>> isn't supported, I'd suggest using a variable trace bound to your combobox's variable attribute instead, as it seems to support that at least\nself.cb_var = StringVar()\nself.combobox1 = ctk.CTkComboBox(\n master=self,\n values=cities, \n command=result, \n variable...
[ 2 ]
[]
[]
[ "customtkinter", "python", "python_3.x", "tkinter" ]
stackoverflow_0074149197_customtkinter_python_python_3.x_tkinter.txt
Q: How to plot confusion matrix with string axis rather than integer in python I am following a previous thread on how to plot confusion matrix in Matplotlib. The script is as follows: from numpy import * import matplotlib.pyplot as plt from pylab import * conf_arr = [[33,2,0,0,0,0,0,0,0,1,3], [3,31,0,0,0,0,0,0,0,0,...
How to plot confusion matrix with string axis rather than integer in python
I am following a previous thread on how to plot confusion matrix in Matplotlib. The script is as follows: from numpy import * import matplotlib.pyplot as plt from pylab import * conf_arr = [[33,2,0,0,0,0,0,0,0,1,3], [3,31,0,0,0,0,0,0,0,0,0], [0,4,41,0,0,0,0,0,0,0,1], [0,1,0,30,0,6,0,0,0,0,1], [0,0,0,0,38,10,0,0,0,0,0]...
[ "Here's what I'm guessing you want:\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nconf_arr = [[33,2,0,0,0,0,0,0,0,1,3], \n [3,31,0,0,0,0,0,0,0,0,0], \n [0,4,41,0,0,0,0,0,0,0,1], \n [0,1,0,30,0,6,0,0,0,0,1], \n [0,0,0,0,38,10,0,0,0,0,0], \n [0,0,0,3,...
[ 65, 31, 14, 4, 3, 1, 0 ]
[]
[]
[ "confusion_matrix", "matplotlib", "python" ]
stackoverflow_0005821125_confusion_matrix_matplotlib_python.txt
Q: Using python Requests with javascript pages I am trying to use the Requests framework with python (http://docs.python-requests.org/en/latest/) but the page I am trying to get to uses javascript to fetch the info that I want. I have tried to search on the web for a solution but the fact that I am searching with th...
Using python Requests with javascript pages
I am trying to use the Requests framework with python (http://docs.python-requests.org/en/latest/) but the page I am trying to get to uses javascript to fetch the info that I want. I have tried to search on the web for a solution but the fact that I am searching with the keyword javascript most of the stuff I am getti...
[ "Good news: there is now a requests module that supports javascript: https://pypi.org/project/requests-html/\nfrom requests_html import HTMLSession\n\nsession = HTMLSession()\n\nr = session.get('http://www.yourjspage.com')\n\nr.html.render() # this call executes the js in the page\n\nAs a bonus this wraps Beautif...
[ 98, 47, 34, 0, 0 ]
[ "its a wrapper around pyppeteer or smth? :( i thought its something different\n @property\n async def browser(self):\n if not hasattr(self, \"_browser\"):\n self._browser = await pyppeteer.launch(ignoreHTTPSErrors=not(self.verify), headless=True, args=self.__browser_args)\n\n return s...
[ -1 ]
[ "python", "python_requests", "web_scraping" ]
stackoverflow_0026393231_python_python_requests_web_scraping.txt
Q: django-cors-headers not work django-cors-headers not work INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis', 'corsheaders', 're...
django-cors-headers not work
django-cors-headers not work INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis', 'corsheaders', 'rest_framework', 'world', 'u...
[ "I was having this same issue and everything seemed to be in the right place. Then I figured out that I had started the server before adding 'corsheaders.middleware.CorsMiddleware', to the MIDDLEWARE_CLASSES. After making the correction, it was still not working. After trying a bunch of stuff, I opened it in anothe...
[ 27, 23, 20, 12, 11, 7, 6, 4, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ "This worked for me: \npython -m pip install django-cors-headers\n\nMIDDLEWARE = [ \n ...\n 'corsheaders.middleware.CorsMiddleware',\n 'django.middleware.common.CommonMiddleware',\n ...\n]\n\nINSTALLED_APPS = [\n ...\n 'corsheaders',\n ...\n]\n\n`ALLOWED_HOSTS = ['*']`\n\n`CORS_ORIGIN_ALLOW_AL...
[ -2, -2 ]
[ "django", "django_cors_headers", "python" ]
stackoverflow_0028046422_django_django_cors_headers_python.txt
Q: use a relative path in requirements.txt to install a tar.gz file with pip We're using a requirements.txt file to store all the external modules needed. Every module but one is gathered from internet. The other one is stored on a folder under the one holding the requirements.txt file. BTW, this module can be easily...
use a relative path in requirements.txt to install a tar.gz file with pip
We're using a requirements.txt file to store all the external modules needed. Every module but one is gathered from internet. The other one is stored on a folder under the one holding the requirements.txt file. BTW, this module can be easily installed with pip install I've tried using this: file:folder/module or this...
[ "In the current version of pip (1.2.1) the way relative paths in a requirements file are interpreted is ambiguous and semi-broken. There is an open issue on the pip repository which explains the various problems and ambiguities in greater detail:\nhttps://github.com/pypa/pip/issues/328\nLong story short the current...
[ 54, 19, 4, 2, 0, 0 ]
[]
[]
[ "pip", "python" ]
stackoverflow_0009809557_pip_python.txt
Q: python trying to generate all possible combinations of an array given two arrays I'm trying to get all the different combinations of the arrays with no repeats of sequences and without using itertools. My problem comes when I try to combine a 2 dimensional array with a 1 dimensional array. given arrays [1,...
python trying to generate all possible combinations of an array
given two arrays I'm trying to get all the different combinations of the arrays with no repeats of sequences and without using itertools. My problem comes when I try to combine a 2 dimensional array with a 1 dimensional array. given arrays [1,2],[1,3],[1,4],[2,3],[2,4] and [1,2,3,4] I want it to yield [1,2,3],...
[ "change_array = [1,2],[1,3],[1,4],[2,3],[2,4]\nbase_array = [1,2,3,4]\n\ndef candidate_generation2(change_array, base_array):\n for array in change_array:\n for value in base_array[base_array.index(array[-1])+1:]:\n yield array+[value]\n\nfor value in candidate_generation2(change_array, base_ar...
[ 0, 0 ]
[]
[]
[ "arrays", "list", "python" ]
stackoverflow_0074152611_arrays_list_python.txt
Q: How would I deal with an attribute error with mediapipe solutions? I get an attribute error if I use the function: def faceDetection(): if results.detections: for detection in results.detection: print(id, detection) AttributeError: type object 'SolutionOutputs' has no attribute 'detections' is ...
How would I deal with an attribute error with mediapipe solutions?
I get an attribute error if I use the function: def faceDetection(): if results.detections: for detection in results.detection: print(id, detection) AttributeError: type object 'SolutionOutputs' has no attribute 'detections' is the error I get if I try running, specifically it calls it on the resul...
[ "This error depends on the Python version you are using. You need to use the version minimum Python 3.9 but most probably you are using Python 3.6.\nIt would be better to create an environment with conda by specifying Python version and install mediapipe in there and try to run your code again. The error will disap...
[ 0, 0 ]
[]
[]
[ "mediapipe", "python" ]
stackoverflow_0074141367_mediapipe_python.txt
Q: Python - Time Convert from UTC to CEST I have following part of script: time = datetime.strptime(msg['timestamp'].split('.')[0],'%Y-%m-%dT%H:%M:%S') msg['timestamp'] is string. I would like to converted this time to CEST. Do you have any ideas? Best Regards A: Finally I use this time = datetime.strptime(msg['t...
Python - Time Convert from UTC to CEST
I have following part of script: time = datetime.strptime(msg['timestamp'].split('.')[0],'%Y-%m-%dT%H:%M:%S') msg['timestamp'] is string. I would like to converted this time to CEST. Do you have any ideas? Best Regards
[ "Finally I use this\ntime = datetime.strptime(msg['timestamp'].split('.')[0],'%Y-%m-%dT%H:%M:%S') timestamp = time+ timedelta(hours=2)\n" ]
[ 0 ]
[]
[]
[ "python", "time" ]
stackoverflow_0074152299_python_time.txt
Q: Merging results from model.predict() with original pandas DataFrame? I am trying to merge the results of a predict method back with the original data in a pandas.DataFrame object. from sklearn.datasets import load_iris from sklearn.cross_validation import train_test_split from sklearn.tree import DecisionTreeClass...
Merging results from model.predict() with original pandas DataFrame?
I am trying to merge the results of a predict method back with the original data in a pandas.DataFrame object. from sklearn.datasets import load_iris from sklearn.cross_validation import train_test_split from sklearn.tree import DecisionTreeClassifier import pandas as pd import numpy as np data = load_iris() # bear w...
[ "your y_hats length will only be the length on the test data (20%) because you predicted on X_test. Once your model is validated and you're happy with the test predictions (by examining the accuracy of your model on the X_test predictions compared to the X_test true values), you should rerun the predict on the full...
[ 37, 4, 2, 1, 0, 0, 0, 0, 0 ]
[ "you can also use\ny_hats = model.predict(X)\n\ndf['y_hats'] = y_hats.reset_index()['name of the target column']\n\n" ]
[ -3 ]
[ "pandas", "python", "scikit_learn" ]
stackoverflow_0040729162_pandas_python_scikit_learn.txt
Q: How to call a python function from views.py in html template I'm beginner with Django Framework and I need to finish a project. Right now I'm stuck on something. Please, someone help me. I'm redering a template "borrow.html". In html code I want to call a function from views.py. I tried like this: This is views.py...
How to call a python function from views.py in html template
I'm beginner with Django Framework and I need to finish a project. Right now I'm stuck on something. Please, someone help me. I'm redering a template "borrow.html". In html code I want to call a function from views.py. I tried like this: This is views.py: def borrowBook(request): return render(request,'app_system_b...
[ "Created a file output_QRscan with the following entries: aaa,eee.\nThe database looks like this:\n\nWhen the borrowBook view is called, the file is read. The data is converted to an array and returned to the view. Next, the database is fetched based on this array and displayed on the page.\nviews.py\ndef write_rea...
[ 0 ]
[]
[]
[ "django", "html", "python", "web" ]
stackoverflow_0074075229_django_html_python_web.txt
Q: Pandas dataframe with datetime column names behaves unexpected in QTableModel I am trying to automate processing of old Excel files and import to database. Using pandas.read_excel() works well for some files, but for others there are some problems. I tried to produce a MWE (below), but it doesn't behave exactly th...
Pandas dataframe with datetime column names behaves unexpected in QTableModel
I am trying to automate processing of old Excel files and import to database. Using pandas.read_excel() works well for some files, but for others there are some problems. I tried to produce a MWE (below), but it doesn't behave exactly the same as pandas.read_excel() because manually creating a dataframe appears to work...
[ "Oopsie. The problem was not actually with the datetime.\nAfter extensive review, I finally found a df.append(columndata) which is what caused the data to misalign (why doesn't this throw an error when the length of data is mismatch to row length?). After replacing it with df[\"newcolname\"] = columndata the code w...
[ 0 ]
[]
[]
[ "pandas", "pyside6", "python", "qtablewidget" ]
stackoverflow_0074152822_pandas_pyside6_python_qtablewidget.txt
Q: How can I fill empty DataFrame based on conditions? I have following dataframe called condition: [0] [1] [2] [3] 1 0 0 1 0 2 0 1 0 0 3 0 0 0 1 4 0 0 0 1 For easier reproduction: import numpy as np import pandas as pd n=...
How can I fill empty DataFrame based on conditions?
I have following dataframe called condition: [0] [1] [2] [3] 1 0 0 1 0 2 0 1 0 0 3 0 0 0 1 4 0 0 0 1 For easier reproduction: import numpy as np import pandas as pd n=4 t=3 condition = pd.DataFrame([[0,0,1,0], [0,1,0,0], ...
[ "I am not sure if this is what you want, but based on your desired output you can do this with only masking operations (which is more efficient than looping over the rows anyway). Your code could look like this:\nis_one = condition.astype(bool)\nis_after_one = (condition.cumsum(axis=1) - condition).astype(bool)\n\n...
[ 1 ]
[]
[]
[ "dataframe", "if_statement", "loops", "pandas", "python" ]
stackoverflow_0074143913_dataframe_if_statement_loops_pandas_python.txt
Q: Pyplot live updating bar chart I will be collecting data in real time from an Arduino and am trying to find a way to show updates in this data on a pyplot bar chart as it comes in. The sample code below is a simplified version of what I'd like to achieve, but the FuncAnimation method is too slow or, at least, I'm...
Pyplot live updating bar chart
I will be collecting data in real time from an Arduino and am trying to find a way to show updates in this data on a pyplot bar chart as it comes in. The sample code below is a simplified version of what I'd like to achieve, but the FuncAnimation method is too slow or, at least, I'm not utilizing it correctly. I'd rea...
[ "With the help of chrslg I was able to get this to work exactly how I wanted. The fact that the bars[].set_height call was using 'frame' from FuncAnimation as an index slipped past me. What I really wanted was to use the index from my for loop as the index of bars[].set_height and set frames in FuncAnimation to 1. ...
[ 2 ]
[]
[]
[ "matplotlib", "python", "tkinter" ]
stackoverflow_0074145596_matplotlib_python_tkinter.txt
Q: Python Package which is installed via SSH gets removed when azure app restarts I have uploaded Django app on azure server web app using Zip Deploy with FTP. After deploying it gives error that "sndlibrary not found" so i need to go to ssh and install it manually by using command apt update && apt-get -y install li...
Python Package which is installed via SSH gets removed when azure app restarts
I have uploaded Django app on azure server web app using Zip Deploy with FTP. After deploying it gives error that "sndlibrary not found" so i need to go to ssh and install it manually by using command apt update && apt-get -y install libsndfile1-dev.So The problem is that whenever the app(container) gets restarted it a...
[ "Every time you restart the container, if the image is rebuilt, the packages are installed from your requirements.txt file. What you have to do is simply adding it to your requirements.txt file. You can do that either manually, or with the command pip freeze.\nIf you're using docker the command is\ndocker exec <con...
[ 0, 0 ]
[]
[]
[ "azure", "azure_web_app_service", "django", "python" ]
stackoverflow_0074137290_azure_azure_web_app_service_django_python.txt
Q: How to calculate width of tree recursively? I have a tree with data structure: root: { children:[ {children: [ {children:[]} ]}, {children: []} ] } Here is example of tree where the result should be 4(maximum width) R / | \ ...
How to calculate width of tree recursively?
I have a tree with data structure: root: { children:[ {children: [ {children:[]} ]}, {children: []} ] } Here is example of tree where the result should be 4(maximum width) R / | \ A B X / \ / \ C D...
[ "To do this with recursion, you can make a helper function that returns the size of the current level and then the sums of sizes of children at each level as a sequence. Take the maximum of sizes from the sequence for output:\nfrom itertools import zip_longest\n\ndef max_tree_width(tree):\n def widths(tree):\n ...
[ 1, 1 ]
[]
[]
[ "python", "recursion" ]
stackoverflow_0074149319_python_recursion.txt
Q: selenium remote webdriver: session times out after 5 minutes I have tried using following commands to start hub and node: NODE: java -jar selenium-server.jar -role node -hub http://xx.xx.xx.xx:xxxx -browserTimeout=9000 -timeout=9000 HUB: java -jar selenium-server.jar -role hub -timeout=9000 -browserTimeout=9000 -D...
selenium remote webdriver: session times out after 5 minutes
I have tried using following commands to start hub and node: NODE: java -jar selenium-server.jar -role node -hub http://xx.xx.xx.xx:xxxx -browserTimeout=9000 -timeout=9000 HUB: java -jar selenium-server.jar -role hub -timeout=9000 -browserTimeout=9000 -Dwebdriver.server.session.timeout=9000 But my browser driver on nod...
[ "to fix this issue you need to use this parameter on run NODE:\n--session-timeout 500000\n\nmore information in documentation: https://www.selenium.dev/documentation/grid/configuration/cli_options/\nin docker-composer this issue is solved like this:\n ChromeService:\n image: selenium/node-chrome:4.5.0\n shm_s...
[ 0 ]
[]
[]
[ "python", "selenium_grid", "selenium_webdriver" ]
stackoverflow_0031284754_python_selenium_grid_selenium_webdriver.txt
Q: Finding variable names for a function from a dictionary list I have a dictionary that I would like to reference all of the values with a list inside the dictionary import pandas as pd data= [["john","","","","","","","","","","","",""]] df= pd.DataFrame(data,columns=['firstName', 'lastName', 'state', 'Communicat...
Finding variable names for a function from a dictionary list
I have a dictionary that I would like to reference all of the values with a list inside the dictionary import pandas as pd data= [["john","","","","","","","","","","","",""]] df= pd.DataFrame(data,columns=['firstName', 'lastName', 'state', 'Communication_Language__c', 'country', 'company', 'email', 'industry', 'Syst...
[ "Using apply function\nCode\ndf2 = df.apply(lambda column: column.str.capitalize() if \"capitalize\" in parsing[column.name] else column)\n\nExplanation\nUsed apply to process each column of Dataframe (e.g. axis = 0 by default)\n\n\"capitalize\" in parsing[column.name] True when either\n\nparsing[column.name] equal...
[ 1 ]
[]
[]
[ "dictionary", "pandas", "python" ]
stackoverflow_0074142359_dictionary_pandas_python.txt
Q: Trying to get highcharts waterfall chart working using justpy, getting "Unexpected text after end of JSON value" I'm trying to get highcharts waterfall chart working using justpy, getting "Unexpected text after end of JSON value". Can anyone spot the error in the below that would be causing an html error? Some cha...
Trying to get highcharts waterfall chart working using justpy, getting "Unexpected text after end of JSON value"
I'm trying to get highcharts waterfall chart working using justpy, getting "Unexpected text after end of JSON value". Can anyone spot the error in the below that would be causing an html error? Some character is somewhere that it shouldn't be? I don't have a good eye for HTML. I am using a justpy app in python to run t...
[ "It seems you have a mistake in your series configuration. Try the following code:\n{\n chart: {\n type: 'waterfall'\n },\n\n title: {\n text: 'Highcharts Waterfall'\n },\n\n xAxis: {\n type: 'category'\n },\n\n yAxis: {\n title: {\n text: 'USD'\n }\n },\n\n legend: {\n enabled: fals...
[ 0 ]
[]
[]
[ "highcharts", "python" ]
stackoverflow_0074153065_highcharts_python.txt
Q: Python pandas pass avarieble from inner loop to outer loop I have a python code as below but I cant pass the variable of inner loop to outer loop. Every time the inner loop breaks, the value of variable "x" reset to initial value. import pandas as pd import csv user_list = pd.read_csv(r'C:\Users\Administrator\Des...
Python pandas pass avarieble from inner loop to outer loop
I have a python code as below but I cant pass the variable of inner loop to outer loop. Every time the inner loop breaks, the value of variable "x" reset to initial value. import pandas as pd import csv user_list = pd.read_csv(r'C:\Users\Administrator\Desktop\user_list.csv') domain_list = pd.read_csv(r'C:\Users\Admini...
[ "This is the correct behaviour, since once you go back to outer loop again, the inner loop starts from the begging.\nYou can do something like this, use another variable z and use it.\nz=0\nfor y in user_list.index:\n print(user_list.iloc[y,0])\n\n for x in domain_list.index:\n if len(domain_list)==z:\n break\n...
[ 1 ]
[]
[]
[ "dataframe", "for_loop", "pandas", "python", "selenium" ]
stackoverflow_0074152036_dataframe_for_loop_pandas_python_selenium.txt
Q: In SQLAlchemy, is there a way to eager-load multiple aliased selectables of the same class using one query? I have an SQLAlchemy mapped class MyClass, and two aliases for it. I can eager-load a relationship MyClass.relationship on each alias separately using selectinload() like so: alias_1, alias_2 = aliased(MyCla...
In SQLAlchemy, is there a way to eager-load multiple aliased selectables of the same class using one query?
I have an SQLAlchemy mapped class MyClass, and two aliases for it. I can eager-load a relationship MyClass.relationship on each alias separately using selectinload() like so: alias_1, alias_2 = aliased(MyClass), aliased(MyClass) q = session.query(alias_1, alias_2).options( selectinload(alias_1.relationship), se...
[ "So, this is exactly the same issue we had. This docs explains how to do it.\nYou need to add selectin_polymorphic. For anyone else if you are using with_polymorphic in your select then remove it.\nfrom sqlalchemy.orm import selectin_polymorphic\n\nquery = session.query(MyClass).options(\n selectin_polymorphic(M...
[ 1 ]
[]
[]
[ "python", "sql", "sqlalchemy" ]
stackoverflow_0064450609_python_sql_sqlalchemy.txt
Q: Python dictionary no duplicate names def sort_dictionary(dict: dict) -> dict: return {k: sorted(v) for k, v in dict.items()} def create_dictionary_with_hobbies(data: str) -> dict: """Create dictionary about hobbies and their hobbyists ie. {hobby1: [name1, name2, ...], hobby2: [...]}.""" result = {} ...
Python dictionary no duplicate names
def sort_dictionary(dict: dict) -> dict: return {k: sorted(v) for k, v in dict.items()} def create_dictionary_with_hobbies(data: str) -> dict: """Create dictionary about hobbies and their hobbyists ie. {hobby1: [name1, name2, ...], hobby2: [...]}.""" result = {} for line in data.split('\n'): n...
[ "Adding the items to a dict with set values will remove duplicates. You can then convert the sets to lists and sort them.\nhobbies_dict = {}\nfor item in sample_data.split(): \n v, k = item.split(':')\n if k not in hobbies_dict:\n hobbies_dict[k] = set([v])\n else:\n hobbies_dict[k].add(v)\n...
[ 0, 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074153057_dictionary_python.txt
Q: Radicale config: File contains no section headers I am not very familiar with Linux / Debian but still trying to install radicale on my Raspberry Pi. The installation worked without problems but when I try to start the radicale service with sudo systemctl start radicale and connect to the web interface all I get i...
Radicale config: File contains no section headers
I am not very familiar with Linux / Debian but still trying to install radicale on my Raspberry Pi. The installation worked without problems but when I try to start the radicale service with sudo systemctl start radicale and connect to the web interface all I get is: "A server error occurred. Please contact the admini...
[ "Would help if your cure was listed.\nI've just worked through the same and found the guide https://www.atlantic.net/dedicated-server-hosting/how-to-install-radicale-calendar-caldav-and-carddav-on-ubuntu-20-04/\nI was using advised filesystem_locking = true but this is an unknown configuration option error\non comm...
[ 1 ]
[]
[]
[ "config", "python", "radicale" ]
stackoverflow_0072669413_config_python_radicale.txt
Q: Pytest-mock: chain mocking between modules I am actuually writting unittests on a project. While I am writting test functions, I am used to mock some function. Recently, I am trying to mock a function that should write into a file. Problem: This funct Like below: # file A.py def write_to_file(message, file="test.t...
Pytest-mock: chain mocking between modules
I am actuually writting unittests on a project. While I am writting test functions, I am used to mock some function. Recently, I am trying to mock a function that should write into a file. Problem: This funct Like below: # file A.py def write_to_file(message, file="test.txt"): with open(file, "w") as fh: fh...
[ "The general rule is to \"mock where it's used, not where it's defined\", see https://docs.python.org/3/library/unittest.mock.html#where-to-patch.\nNow, if you want to mock write_to_file or test, which is used in module B.py, you just do:\ndef test_with_mock(mocker):\n mocker.patch('B.write_to_file') # or mocke...
[ 0, 0 ]
[]
[]
[ "pytest", "pytest_mock", "python" ]
stackoverflow_0074152513_pytest_pytest_mock_python.txt
Q: pandas dictionary to json append to file I'm trying to write dictionaries with 3 items each into a json file which i'll ultimately be using with pandas. Each dictionary looks something like this: xyz_dictionary = {'x': 1, 'y': 2, 'z':3} I am doing the following to make it into a string and then add it to a .json...
pandas dictionary to json append to file
I'm trying to write dictionaries with 3 items each into a json file which i'll ultimately be using with pandas. Each dictionary looks something like this: xyz_dictionary = {'x': 1, 'y': 2, 'z':3} I am doing the following to make it into a string and then add it to a .json file: with open('jsonfile.json', 'a') as json...
[ "edit: I would suggest you create an array of json objects\nimport json\n\n{ 'xyz_data': \n[{\n \"x\": -0.03564453125,\n \"y\": -0.00830078125,\n \"z\": 1.0244140625\n},\n{\n \"x\": -0.03564453125,\n \"y\": -0.00830078125,\n \"z\": 1.0244140625\n}, ...\n]}\n\nUse append to add to the dic \noutfile...
[ 1, 0, 0 ]
[]
[]
[ "json", "pandas", "python" ]
stackoverflow_0054120733_json_pandas_python.txt
Q: Why i can’t login using my login template (Django) I am using a login template to log in to staff and non-staff members but the login page only allows the staff members or you can say superusers to login in which also logs me into the admin page, but I want to log in into the web app that I am using, not the admin...
Why i can’t login using my login template (Django)
I am using a login template to log in to staff and non-staff members but the login page only allows the staff members or you can say superusers to login in which also logs me into the admin page, but I want to log in into the web app that I am using, not the admin page be it staff or non-staff for logging in. Is there ...
[ "In manager.py file in the create_user function i forgot to add is_active=True,\ndef create_user(\n self, email, first_name, last_name, roll_no, password, department=None\n ):\n if not email:\n raise ValueError(\"User requires an Email\")\n if not first_name:\n raise Va...
[ 0 ]
[]
[]
[ "django", "django_forms", "django_templates", "python" ]
stackoverflow_0074152698_django_django_forms_django_templates_python.txt
Q: Pandas to_sql fails on duplicate primary key I'd like to append to an existing table, using pandas df.to_sql() function. I set if_exists='append', but my table has primary keys. I'd like to do the equivalent of insert ignore when trying to append to the existing table, so I would avoid a duplicate entry error. ...
Pandas to_sql fails on duplicate primary key
I'd like to append to an existing table, using pandas df.to_sql() function. I set if_exists='append', but my table has primary keys. I'd like to do the equivalent of insert ignore when trying to append to the existing table, so I would avoid a duplicate entry error. Is this possible with pandas, or do I need to writ...
[ "There is unfortunately no option to specify \"INSERT IGNORE\". This is how I got around that limitation to insert rows into that database that were not duplicates (dataframe name is df)\nfor i in range(len(df)):\n try:\n df.iloc[i:i+1].to_sql(name=\"Table_Name\",if_exists='append',con = Engine)\n exce...
[ 33, 13, 6, 5, 3, 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "mysql", "pandas", "python" ]
stackoverflow_0030337394_mysql_pandas_python.txt
Q: Multiple same name dictionaries in a list with each instance in the list having different dictionary contents First off: I don't really know how to correctly phrase this question, the idea is as follows: I have a standard dictionary that I want to check values in, with different objects using that dictionary to ch...
Multiple same name dictionaries in a list with each instance in the list having different dictionary contents
First off: I don't really know how to correctly phrase this question, the idea is as follows: I have a standard dictionary that I want to check values in, with different objects using that dictionary to check items to. Now if I'm working in a specific object and append data to the dictionary of that object, the data ge...
[ "The problem you faced here happens because dictionaries in Python are shared by reference but not by value. So every time you use one and the same dictionary for your operations. If you want to make sure that every time you get separate dictionary use copy() function. It will create a separate copy of the dictiona...
[ 1, 1 ]
[]
[]
[ "class", "dictionary", "oop", "python" ]
stackoverflow_0074152957_class_dictionary_oop_python.txt
Q: How to add a counter to pandas duplicated index? I want to transform duplicated values of index adding a counter like -01, -02, -0n, etc. for every duplicated item, skipping unduplicated indices. That is to transform index values from these: one one two three three four to these: one-01 one-02 two three-01 three-...
How to add a counter to pandas duplicated index?
I want to transform duplicated values of index adding a counter like -01, -02, -0n, etc. for every duplicated item, skipping unduplicated indices. That is to transform index values from these: one one two three three four to these: one-01 one-02 two three-01 three-02 four What approach can I resort to?
[ "Use GroupBy.cumcount for counter and assign only duplicated values by Index.duplicated with Series.where:\ndf = pd.DataFrame({'a': range(6)},\n index=['one', 'one', 'two', 'three', 'three', 'four'])\n\n\ndf.index += (df.groupby(level=0).cumcount().add(1).astype(str).str.zfill(2).radd('-')\n ...
[ 1, 0 ]
[]
[]
[ "indexing", "pandas", "python" ]
stackoverflow_0074153526_indexing_pandas_python.txt
Q: how to predict with pretrained model in pytorch i am trying to translate this https://github.com/piiswrong/deep3d/blob/master/deep3d.ipynb in pytorch import os import numpy as np import cv2 import torch from PIL import Image from images2gif import writeGif net = torch.jit.load("deep3d_v1.0_640x360_cpu.pt") net.ev...
how to predict with pretrained model in pytorch
i am trying to translate this https://github.com/piiswrong/deep3d/blob/master/deep3d.ipynb in pytorch import os import numpy as np import cv2 import torch from PIL import Image from images2gif import writeGif net = torch.jit.load("deep3d_v1.0_640x360_cpu.pt") net.eval() shape = (384, 160) img = cv2.imread('demo.jpg')...
[ "I would stick with net(test_iter) to predict and just use\nY = net(torch.from_numpy(test_iter))\n\nas this converts the numpy.ndarray to a Tensor, see here\nAlso similar questions: Similar Questions 1\n" ]
[ 0 ]
[]
[]
[ "numpy", "opencv", "python", "python_imaging_library", "pytorch" ]
stackoverflow_0074151744_numpy_opencv_python_python_imaging_library_pytorch.txt
Q: how to parse windows inf files for python? please help me. example inf file : ;============================================================================= ; ; Copyright (c) Intel Corporation (2002). ; ; INTEL MAKES NO WARRANTY OF ANY KIND REGARDING THE CODE. THIS CODE IS ; LICENSED ON AN "AS IS" BASIS AND INTE...
how to parse windows inf files for python?
please help me. example inf file : ;============================================================================= ; ; Copyright (c) Intel Corporation (2002). ; ; INTEL MAKES NO WARRANTY OF ANY KIND REGARDING THE CODE. THIS CODE IS ; LICENSED ON AN "AS IS" BASIS AND INTEL WILL NOT PROVIDE ANY SUPPORT, ; ASSISTANCE, IN...
[ "You may try the built-in ConfigParser\nhttp://docs.python.org/library/configparser.html\nAs well as ConfigObj\nhttp://code.google.com/p/configobj/\nBoth claim to be able to handle Windows INI files.\n", "Both configparser and configobj do not support parsing of INF files out of the box.\n\nin case of configparse...
[ 10, 0 ]
[]
[]
[ "drivers", "file", "parsing", "python", "windows" ]
stackoverflow_0000927279_drivers_file_parsing_python_windows.txt
Q: Docker image build error (python setup.py error) I have a problem building a docker image for my python server. when running: docker image build -t server:latest . I get the following error: => ERROR [4/6] RUN pip3 install -r requirements.txt ...
Docker image build error (python setup.py error)
I have a problem building a docker image for my python server. when running: docker image build -t server:latest . I get the following error: => ERROR [4/6] RUN pip3 install -r requirements.txt ...
[ "This can be very frustrating when you see your docker build is ending up in an error time and time over. Something you can try in future;\n\nCreate the Dockerfile with upto whatever the point giving an error (Say minimal os image)\nRun it in interactive mode with docker run -it <IMAGE_NAME>\nTry to install whateve...
[ 2 ]
[]
[]
[ "docker", "python" ]
stackoverflow_0074152681_docker_python.txt
Q: How to merge two 2D arrays with conditions of columns values I'm trying to merge two 2D NumPy arrays with a specific condition. Let's say we have: A=[[100.121,200.129,1,2,3], [105.343,203.347,2,2,1], [107.426,201.657,1,3,1], [100.121,300.010,1,1,1]] and B=[[107.426,201,675,80], [100.121,200.129,70], ...
How to merge two 2D arrays with conditions of columns values
I'm trying to merge two 2D NumPy arrays with a specific condition. Let's say we have: A=[[100.121,200.129,1,2,3], [105.343,203.347,2,2,1], [107.426,201.657,1,3,1], [100.121,300.010,1,1,1]] and B=[[107.426,201,675,80], [100.121,200.129,70], [100.121,300.010,90]] I want to obtain: C=[[100.121,200.129,1,...
[ "You can try this\nA=[[100,200,1,2,3],\n [105,203,2,2,1],\n [107,201,1,3,1]]\nB=[[107,201,80],\n [100,200,70],\n [105,203,50]]\n\ntemp_B = list(zip(*B))\nd_B = dict(zip(temp_B[0], temp_B[2]))\nA = [i + [d_B.get(i[0],0)] for i in A]\n# [[100, 200, 1, 2, 3, 70], [105, 203, 2, 2, 1, 50], [107, 201, 1, 3, 1, 80...
[ 0 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0074153399_arrays_numpy_python.txt
Q: Solving ODEs python with non-independent funcitons python I'm trying to plot a multi-equation ODE from this paper and I'm having trouble figuring out how to express the dependencies between the functions. I.e, in 3.1, it uses both z1 and z2. Aswell as using its own precious state x. I've checked the Scipy document...
Solving ODEs python with non-independent funcitons python
I'm trying to plot a multi-equation ODE from this paper and I'm having trouble figuring out how to express the dependencies between the functions. I.e, in 3.1, it uses both z1 and z2. Aswell as using its own precious state x. I've checked the Scipy documentation but they don't seem to express the functionality that I'm...
[ "You have to implement a system ODE function\ndef sys(t,u):\n x,y,z1,z2 = u\n v1 = z1/(p1*z2)-1\n v2 = 1-y/p6\n return p0*v1, p2*(x/p3-1)+p4*v1, p7*z1*v2, (p7-p5*z2/z1)*z2*v2\n\n#integrate to jump\nsol1 = solve_ivp(sys,(t0,td),u0,**options)\n# implement the jump\nx,y,z1,z2 = sol1.y[:,-1]\nfac = (2-λ)/(2...
[ 1, 1 ]
[]
[]
[ "math", "numpy", "ode", "python", "scipy" ]
stackoverflow_0074151300_math_numpy_ode_python_scipy.txt
Q: get execution time of bubble sort I'm trying to print the execution time of a bubble sort, but it keep asking an Integer "TypeError: an integer is required (got type NoneType)" import time def bubbleSort(array): # loop to access each array element for i in range(len(array)): # loop to compare arr...
get execution time of bubble sort
I'm trying to print the execution time of a bubble sort, but it keep asking an Integer "TypeError: an integer is required (got type NoneType)" import time def bubbleSort(array): # loop to access each array element for i in range(len(array)): # loop to compare array elements for j in range(0, ...
[ "Your program does not work the way you think it works:\nWhat you seem to be trying, is to make get_time() wait until bubbleSort() is finished. Hence the time.sleep() call inside of it.\nWhat actually happens is, the innermost function bubbleSort() gets called first, and its return value - None gets passed into the...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074153562_python.txt
Q: Sorting a pysimplegui table Is there a way with pysimplegui to sort a table by columns? I looked around on github for some examples but couldn't find anything. I found this example that creates a table from a csv file: #!/usr/bin/env python import PySimpleGUI as sg import csv # Show CSV data in Table sg.theme('Da...
Sorting a pysimplegui table
Is there a way with pysimplegui to sort a table by columns? I looked around on github for some examples but couldn't find anything. I found this example that creates a table from a csv file: #!/usr/bin/env python import PySimpleGUI as sg import csv # Show CSV data in Table sg.theme('Dark Red') def table_example(): ...
[ "There's a demo program and an eCookbook page specifically to demonstrate how to sort by columns.\n\n\nThe eCookbook (Trinket) link is here:\nhttps://pysimplegui.trinket.io/demo-programs#/tables/table-element-getting-click-events\nThis is the program I start with anytime I'm writing a PySimpleGUI program that's goi...
[ 0 ]
[]
[]
[ "pysimplegui", "python", "python_3.x" ]
stackoverflow_0069013174_pysimplegui_python_python_3.x.txt
Q: Accuracy while learning MNIST database is very low (0.2) I am developing my ANN from scratch which is supposed to classify MNIST database of handwritten digits (0-9). My feed-forward fully connected ANN has to be composed of: One input layer, with 28x28 = 784 nodes (that is, features of each image) One hidden lay...
Accuracy while learning MNIST database is very low (0.2)
I am developing my ANN from scratch which is supposed to classify MNIST database of handwritten digits (0-9). My feed-forward fully connected ANN has to be composed of: One input layer, with 28x28 = 784 nodes (that is, features of each image) One hidden layer, with any number of neurons (shallow network) One output la...
[ "Two points I observed:\n\nYou are not using mini batches during training. In every step you feed the entire dataset through the network. This is certainly not advisable for anything but simple convex problems. Use mini-batching instead, i.e. chop your dataset into small batches of, say, 32 images and perform updat...
[ 2, 2, 0 ]
[]
[]
[ "machine_learning", "mnist", "neural_network", "python" ]
stackoverflow_0074016277_machine_learning_mnist_neural_network_python.txt
Q: how to fix "Operation not permitted" when i use launchctl in macos catalina I'm setting up a launchctl server to run a python file regularly. So I write a.plist file , auto.sh file and it works well. However, after I installed Macos Catalina, it failed. I write "ls -l" in auto.sh to check file permission, log s...
how to fix "Operation not permitted" when i use launchctl in macos catalina
I'm setting up a launchctl server to run a python file regularly. So I write a.plist file , auto.sh file and it works well. However, after I installed Macos Catalina, it failed. I write "ls -l" in auto.sh to check file permission, log shows that: ls: .: Operation not permitted python3: can't open file 'auto.py': [Er...
[ "Finally figure it out...\nIt's a problem related to Catalina new permission system, the /bin/bash need to have the [full disk access].\n\n", "I think the problem you have is not with Python, but with the file permissions on auto.py or the path leading up to it. What user account is used to run the script? Does t...
[ 28, 1, 0, 0, 0 ]
[]
[]
[ "macos", "python", "sh" ]
stackoverflow_0058442951_macos_python_sh.txt
Q: python remove unknown text inside specific mark I have this text text = "{\g1}Hello world!{\i6}" I want to remove the curly brackets and the text inside them without knowing what is inside the curly brackets, I know how to remove a specific text by using .replace("Hello", "Hi") (sorry for my English) A: You can ...
python remove unknown text inside specific mark
I have this text text = "{\g1}Hello world!{\i6}" I want to remove the curly brackets and the text inside them without knowing what is inside the curly brackets, I know how to remove a specific text by using .replace("Hello", "Hi") (sorry for my English)
[ "You can use regular expressions to find & replace a particular pattern of characters.\nIn this case, a suitable regex pattern would be {\\\\.{2}}.\n\n{ matches a \"{\" character\n\\\\ matches a \"\\\" character\n. matches any character except line breaks\n{2} match exactly 2 of the preceding token (. in this case)...
[ 2 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074153655_python_python_3.x.txt
Q: Measuring Function runtime with waiting function Someone gave me this code for a timing measurement decorator for functions and it works perfectly fine: from functools import wraps from time import time def timing(f): @wraps(f) def wrap(*args, **kw): ts = time() result = f(*args, **kw) ...
Measuring Function runtime with waiting function
Someone gave me this code for a timing measurement decorator for functions and it works perfectly fine: from functools import wraps from time import time def timing(f): @wraps(f) def wrap(*args, **kw): ts = time() result = f(*args, **kw) te = time() print(f'func:{f.__name__} arg...
[ "You may want to define an inner function which is called only after the user has closed the window, and decorate that one:\ndef outer_func(arg):\n @timing\n def inner_func(arg):\n #do the actual stuff\n #wait for the user to close the window\n inner_func(arg)\n\n" ]
[ 1 ]
[]
[]
[ "python", "python_3.x", "runtime", "wait" ]
stackoverflow_0074151564_python_python_3.x_runtime_wait.txt
Q: Python list.index throws exception when index not found Why does list.index throw an exception, instead of using an arbitrary value (for example, -1)? What's the idea behind this? To me it looks cleaner to deal with special values, rather than exceptions. EDIT: I didn't realize -1 is a potentially valid value. Nev...
Python list.index throws exception when index not found
Why does list.index throw an exception, instead of using an arbitrary value (for example, -1)? What's the idea behind this? To me it looks cleaner to deal with special values, rather than exceptions. EDIT: I didn't realize -1 is a potentially valid value. Nevertheless, why not something else? How about a value of None?...
[ "Because -1 is itself a valid index. It could use a different value, such as None, but that wouldn't be useful, which -1 can be in other situations (thus str.find()), and would amount simply to error-checking, which is exactly what exceptions are for.\n", "Well, the special value would actually have to be None, b...
[ 18, 17, 9, 3, 3, 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "indexing", "list", "python" ]
stackoverflow_0000674229_indexing_list_python.txt
Q: How to write a string and dictionary value to a Python log file I tried this, but it does not seem like you can log a string together with a variable. How can I write a string and dictionary value to a Python log file? import logging logging.basicConfig(level=logging.DEBUG, filemode='w', format='%(asctime)s - %(le...
How to write a string and dictionary value to a Python log file
I tried this, but it does not seem like you can log a string together with a variable. How can I write a string and dictionary value to a Python log file? import logging logging.basicConfig(level=logging.DEBUG, filemode='w', format='%(asctime)s - %(levelname)s - %(message)s (Line: %(lineno)d)', filename='testlog.log') ...
[ "Have a look at: https://docs.python.org/3/library/logging.html#logging.debug\nYou have two options:\n\nYou can pass a dictionary of 'extra' values as well as the main string. You will then need a custom log formatter to do something with the extra keys, as I think by default they will not be output. e.g.:\nlogger....
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074153731_python_python_3.x.txt
Q: Unzipping data files on install of python project I have a python project which contains some largish data files as part of the distribution. I would like to distribute these data files in zip/gzip form and then have them unpacked on install. I'm using poetry to manage the project dependencies and publish to the r...
Unzipping data files on install of python project
I have a python project which contains some largish data files as part of the distribution. I would like to distribute these data files in zip/gzip form and then have them unpacked on install. I'm using poetry to manage the project dependencies and publish to the repository, so I assume I need to hook into the generate...
[ "The generated setup.py just exists for historical reasons, when pip wasn't able to understand PEP-518. It is not used anymore by any up-to-date tool and will be removed in the future.\nThere is no such thing like post-installation tasks in poetry and probably never will be.\nThe recommended way of doing it, is to ...
[ 1 ]
[]
[]
[ "python", "python_packaging", "python_poetry", "setuptools" ]
stackoverflow_0074153803_python_python_packaging_python_poetry_setuptools.txt
Q: Customize legend labels in Geopandas I would like to customize the labels on the geopandas plot legend. fig, ax = plt.subplots(figsize = (8,5)) gdf.plot(column = "WF_CEREAL", ax = ax, legend=True, categorical=True, cmap='YlOrBr',legend_kwds = {"loc":"lower right"}, figsize =(10,6)) Adding "labels" in legend_kwds...
Customize legend labels in Geopandas
I would like to customize the labels on the geopandas plot legend. fig, ax = plt.subplots(figsize = (8,5)) gdf.plot(column = "WF_CEREAL", ax = ax, legend=True, categorical=True, cmap='YlOrBr',legend_kwds = {"loc":"lower right"}, figsize =(10,6)) Adding "labels" in legend_kwds does not help. I tried to add labels wi...
[ "Since the question does not have reproducible code and data to work on. I will use the best possible approach to give a demo code that the general readers can follow and some of it may answer the question.\nThe code I provide below can run without the need of external data. Comments are inserted in various places ...
[ 1, 0 ]
[]
[]
[ "geopandas", "legend", "matplotlib", "python" ]
stackoverflow_0074143732_geopandas_legend_matplotlib_python.txt
Q: Reading files from G Drive from python I have a GCP project and there is a Jupiter notebook which is to read files from G Drive. def search_file(request = None): try: service = build('drive', 'v3', credentials=creds) # Call the Drive v3 API results = service.files().list( p...
Reading files from G Drive from python
I have a GCP project and there is a Jupiter notebook which is to read files from G Drive. def search_file(request = None): try: service = build('drive', 'v3', credentials=creds) # Call the Drive v3 API results = service.files().list( pageSize=1, fields="nextPageToken, files(id, ...
[ "Can you try running the query in the following format?\nshared_drive_id = \"\" # you need to specify specific id of drive folder provided in url of that folder such as https://drive.google.com/drive/folders/<shared_drive_id>\n \nquery_file = \"mimeType='application/vnd.google-apps.document' and trashed=false\"\ns...
[ 0 ]
[]
[]
[ "gdrive", "google_cloud_platform", "python" ]
stackoverflow_0074153389_gdrive_google_cloud_platform_python.txt
Q: python script that runs inside a docker image, doesn't use the usual PYTHONPATH I'm creating a docker image using the following Dockerfile: FROM python:3.7 RUN apt-get update && pip install sagemaker boto3 numpy sagemaker-training # Copies the training code inside the container COPY cv.py /opt/ml/code/train.py CO...
python script that runs inside a docker image, doesn't use the usual PYTHONPATH
I'm creating a docker image using the following Dockerfile: FROM python:3.7 RUN apt-get update && pip install sagemaker boto3 numpy sagemaker-training # Copies the training code inside the container COPY cv.py /opt/ml/code/train.py COPY scikit_learn_iris.py /opt/ml/code/scikit_learn_iris.py # Defines train.py as scri...
[ "I don't see any base image in the Dockerfile, it is possible that came from a base image if there was any. And I don't know if this helps, but this is the ```prinenv`` output from my training image. And I didn't have to set PYTHONPATH and it's working without issue.\nSAGEMAKER_SUBMIT_DIRECTORY=/opt/ml/code\nOLDPWD...
[ 0 ]
[]
[]
[ "amazon_sagemaker", "docker", "pip", "python" ]
stackoverflow_0073592771_amazon_sagemaker_docker_pip_python.txt
Q: Roman to Integer python I am trying to solve this python problem with python3, my code looks like this. class Solution: def romanToInt(self, s: str) -> int: # Define integer value to each roman rom_val = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} ...
Roman to Integer python
I am trying to solve this python problem with python3, my code looks like this. class Solution: def romanToInt(self, s: str) -> int: # Define integer value to each roman rom_val = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} # A list of integer values ...
[ "Here is a different approach, 5 lines:\nd = {'M':1000, 'D':500, 'C':100, 'L':50, 'X':10, 'V':5, 'I':1}\n\ndef romanToInt(self, s):\n res, p = 0, 'I'\n for c in s[::-1]:\n res, p = res - d[c] if d[c] < d[p] else res + d[c], c\n return res\n\nBasically, going backward, adding each letter to result un...
[ 4, 3, 0, 0 ]
[ "Here, for example, I pass 'II' to your function than values becomes [1,1]. Now using enumerate you will have (1,1) as i,j in your second iteration which is causing the index error. Then you can solve this easily.\n" ]
[ -1 ]
[ "python", "python_3.x" ]
stackoverflow_0061719161_python_python_3.x.txt
Q: How would you go about making this loop? A standard science experiment is to drop a ball and see how high it bounces. Once the “bounciness” of the ball has been determined, the ratio gives a bounciness index. For example, if a ball dropped from a height of 10 meters bounces 6 meters high, the index is 0.6 and the ...
How would you go about making this loop?
A standard science experiment is to drop a ball and see how high it bounces. Once the “bounciness” of the ball has been determined, the ratio gives a bounciness index. For example, if a ball dropped from a height of 10 meters bounces 6 meters high, the index is 0.6 and the total distance traveled by the ball is 16 mete...
[ "This is a classic recursion process.\nThere are three approaches that one might take:\n\nrecursive method. (needs end condition)\nwhile loop. (needs end condition)\nfor loop. (finishes at the end of the loop)\n\nUsing method 3 from the above this works:\ndef Bounce_Calculator(initial_height:float, bouncyness:float...
[ 1 ]
[]
[]
[ "loops", "python" ]
stackoverflow_0074152934_loops_python.txt
Q: Failed to load c-extensions in a shiv package I maintain a project which I bundle into a shiv package and distribute at work. I've included all necessary package dependencies into the shiv package, and this includes numpy and PIL. It is safe to assume everyone is using Windows and python 3.6+. It seems that the C-...
Failed to load c-extensions in a shiv package
I maintain a project which I bundle into a shiv package and distribute at work. I've included all necessary package dependencies into the shiv package, and this includes numpy and PIL. It is safe to assume everyone is using Windows and python 3.6+. It seems that the C-extensions for numpy and PIL do not come along with...
[ "At long last I've found the cause to my issue. I am using Anaconda to manage my python environments and when creating the shiv package \"path_to_site-packages\" folder was the one that Anaconda creates. I can not explain exactly why this was the issue, but my assumption is that Anaconda manages where the C-librari...
[ 0 ]
[]
[]
[ "python", "python_c_api" ]
stackoverflow_0073449828_python_python_c_api.txt
Q: How to compile Python APSW with local build os SQLite I'm developing an application and I would like to compile SQLite with some personalized flags and use this build of SQLite with APSW! To be more specific, I would like to use the options in the Recommended Compile-time Options section of SQLite Compile-time Opt...
How to compile Python APSW with local build os SQLite
I'm developing an application and I would like to compile SQLite with some personalized flags and use this build of SQLite with APSW! To be more specific, I would like to use the options in the Recommended Compile-time Options section of SQLite Compile-time Options Docs (https://www.sqlite.org/compile.html). I'm using ...
[ "You do not need to deal with APSW. The official SQLite binary release can be dropped in place of module included with Python. So you compile SQLite, replace the library that came with Python, and use the stock Python bindings (import sqlite3). I checked it on Windows, but, I suppose, it should work on Linux as wel...
[ 0 ]
[]
[]
[ "apsw", "c++", "gcc", "python", "sqlite" ]
stackoverflow_0074153961_apsw_c++_gcc_python_sqlite.txt
Q: django.db.utils.OperationalError: table "blog_post" already exists I'm creating a blog using Django and anytime I run manage.py migrate, I get the error below: (venv) (C:\Users\KOLAPO\Anaconda3) C:\Programming\Websites\shelteratyourcrossroads\shelteratyourcrossroads>manage.py migrate Operations to perform: Apply...
django.db.utils.OperationalError: table "blog_post" already exists
I'm creating a blog using Django and anytime I run manage.py migrate, I get the error below: (venv) (C:\Users\KOLAPO\Anaconda3) C:\Programming\Websites\shelteratyourcrossroads\shelteratyourcrossroads>manage.py migrate Operations to perform: Apply all migrations: admin, auth, blog, contenttypes, sessions, sites, taggi...
[ "Maybe faking the initial migration of blog app will help you. Try the following.\n\n./manage.py migrate --fake blog 0001_initial\n \n\n", "Django 3.2\nThe following worked for me:\ndelete all the migration files, including the initial migration. Then perform:\npython manage.py makemigrations\npython manage.py m...
[ 3, 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0047285154_django_python.txt
Q: Any idea on how the event loop works in Pysimplegui? Can't figure out disabling buttons based on other inputs So I am having many issues with Pysimplegui's event loops, I'm trying to disable a button based on the lack of input in another part of the code (in this case it's the lack of selection of at least one che...
Any idea on how the event loop works in Pysimplegui? Can't figure out disabling buttons based on other inputs
So I am having many issues with Pysimplegui's event loops, I'm trying to disable a button based on the lack of input in another part of the code (in this case it's the lack of selection of at least one checkbox if the radio button above is pressed [but I should apply the same logic if a folder is not selected]). I trie...
[ "You need .Get() in window_2['-OutputCSV-'].Get() and window_2['-OutputJSON-'].Get() to check if elements are selected.\nif not window_2['-OutputCSV-'].Get() and not window_2['-OutputJSON-'].Get():\n window_2['-Submit-'].update(disabled=True)\n sg.popup('Select an output', keep_on_top=True)\n\nYou would need ...
[ 1, 0 ]
[]
[]
[ "pysimplegui", "python", "user_interface" ]
stackoverflow_0074152616_pysimplegui_python_user_interface.txt
Q: why it will show AttributeError: module 'self' has no attribute 'driver' I want to fill the credit card in check out, but I can not find that self.driver.switch_to.frame() self.driver.switch_to.frame("number7fe57559-0283-43ef-90c4-484c5c17c4f1").click``` it show ```File "C:\Users\harry\PycharmProjects\pythonProj...
why it will show AttributeError: module 'self' has no attribute 'driver'
I want to fill the credit card in check out, but I can not find that self.driver.switch_to.frame() self.driver.switch_to.frame("number7fe57559-0283-43ef-90c4-484c5c17c4f1").click``` it show ```File "C:\Users\harry\PycharmProjects\pythonProject\main.py", line 34, in <module> self.driver.switch_to.frame() Attribute...
[ "You can use self only inside of a python class. Try without it.\n" ]
[ 0 ]
[]
[]
[ "python", "selenium", "selenium_webdriver" ]
stackoverflow_0074153967_python_selenium_selenium_webdriver.txt
Q: Copying python scripts into docker container in sagemaker I have been frustrated by this copy error while trying to copy a python script to docker container. I am doing this in AWS Sagemaker. Anyone can suggest why this error happens. The train_sm.py code I am trying to copy is inside the src folder. The dockerfil...
Copying python scripts into docker container in sagemaker
I have been frustrated by this copy error while trying to copy a python script to docker container. I am doing this in AWS Sagemaker. Anyone can suggest why this error happens. The train_sm.py code I am trying to copy is inside the src folder. The dockerfile is inside the docker folder. What is the build context here? ...
[ "Suggestion to structure your file structure as follows;\nProject\n -Dockerfile\n -src\n -a.py\n -b.py\n -c.py\n -packages\nsagemaker_script.py\nbuild_push_script.sh\nData\n -train\n -test\n -validate\n\nThen you can run from the Project with a command like docker ... Dockerfile\nand inside the Dockerfile ...
[ 0 ]
[]
[]
[ "amazon_sagemaker", "docker", "jupyter", "python" ]
stackoverflow_0072580651_amazon_sagemaker_docker_jupyter_python.txt
Q: From text doc to JSON with python Suppose I have multiple txt files that look like this (indentation is 4 spaces): key1=value1 key2 key2_1=value2_1 key2_2 key2_2_1=value2_2_1 key2_3=value2_3 key3=value3 How do I convert one (or all) of them into this format: { 'key1':'value1', 'key2': { ...
From text doc to JSON with python
Suppose I have multiple txt files that look like this (indentation is 4 spaces): key1=value1 key2 key2_1=value2_1 key2_2 key2_2_1=value2_2_1 key2_3=value2_3 key3=value3 How do I convert one (or all) of them into this format: { 'key1':'value1', 'key2': { 'key2_1':'value2_1', 'key2_2': ...
[ "You could try something like below:\n# helper method to convert equals sign to indentation for easier parsing\ndef convertIndentation(inputString):\n indentCount = 0\n indentVal = \" \"\n for position, eachLine in enumerate(inputString):\n if \"=\" not in eachLine:\n continue\n ...
[ 1 ]
[]
[]
[ "automation", "dictionary", "json", "python", "txt" ]
stackoverflow_0074152428_automation_dictionary_json_python_txt.txt