content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: How to store a portion of a result in python? I have this code to get download links via libgen api. @app.route("/api/default") def titleSearch(): title = request.args.get('query') s = LibgenSearch() results = s.search_title(title) item_to_download = results[0] download_links = s.resolve_...
How to store a portion of a result in python?
I have this code to get download links via libgen api. @app.route("/api/default") def titleSearch(): title = request.args.get('query') s = LibgenSearch() results = s.search_title(title) item_to_download = results[0] download_links = s.resolve_download_links(item_to_download) return render_...
[ "In response, you have a dictionary which is key-value pairs.\nreading key value of a dictionary:\nmy_dict = {\n \"link_1\": \"example_1.com\",\n \"link_2\": \"example_2.com\" \n }\nfor key, value in my_dict.items():\n print(key, value)\n\noutput\nlink_1, example_1.com\nlink_2, example_2.com\n\nnow you ...
[ 0 ]
[]
[]
[ "flask", "html", "python" ]
stackoverflow_0074134140_flask_html_python.txt
Q: How to manually iterate a for loop in Python I got the following for loop with nested while loops: new_offset = 0 threshold = 600 limit = 20000 counter = 0 for query in all_queries: print('query: ', query) params = {"q": query, "license": "public", "imageType": "photo", "count": threshold} while ne...
How to manually iterate a for loop in Python
I got the following for loop with nested while loops: new_offset = 0 threshold = 600 limit = 20000 counter = 0 for query in all_queries: print('query: ', query) params = {"q": query, "license": "public", "imageType": "photo", "count": threshold} while new_offset <= threshold: print('Finding resu...
[ "I could probably recommend a better solution if I knew more about what you are trying to achieve, however, the example below should work the way you described. It skips to the next query once the length contentUrls reaches the limit.\nI should mention that this code doesn't change the limit or reset the contentUrl...
[ 0 ]
[]
[]
[ "for_loop", "python" ]
stackoverflow_0074134056_for_loop_python.txt
Q: Python integration within Stata I am trying to run the python urllib module from the python interface in Stata, but it sends me the following message error: Traceback (most recent call last): File "", line 1, in AttributeError: module 'urllib' has no attribute 'request' This happens when I run the script within t...
Python integration within Stata
I am trying to run the python urllib module from the python interface in Stata, but it sends me the following message error: Traceback (most recent call last): File "", line 1, in AttributeError: module 'urllib' has no attribute 'request' This happens when I run the script within the python interface in Stata. However...
[ "Agreeed with Nick ODell's comment: you should check your python path in Stata. and also you can change the path like this:\nset python_exec \"YOUR PATH FILE PATH\\python.exe\"\n\n" ]
[ 0 ]
[]
[]
[ "python", "stata", "urllib" ]
stackoverflow_0074132280_python_stata_urllib.txt
Q: How to round values created in dataframe column using lambda? I've used the following code in order to find the sum of a column's values and store it: FavCountSum=Merge3['Favorite_Count'].sum() and then I've used the following code in order to divide each number in the original column by the stored sum in order t...
How to round values created in dataframe column using lambda?
I've used the following code in order to find the sum of a column's values and store it: FavCountSum=Merge3['Favorite_Count'].sum() and then I've used the following code in order to divide each number in the original column by the stored sum in order to create a new column with the respective percentages and I'd like ...
[ "try it:\nMerge3.assign(Favorite_Color_Percent=lambda x: round(x.Favorite_Count/FavCountSum, 2))\n\n" ]
[ 1 ]
[]
[]
[ "computer_science", "data_science", "python" ]
stackoverflow_0074134237_computer_science_data_science_python.txt
Q: TypeError: sum() takes at most 2 arguments (3 given). Confused with my error? Not sure why I am receiving a TypeError: sum() takes at most 2 arguments (3 given). Is my code correct? Investigate the distribution of weight for different age groups. To start, partition the dataset into three DataFrames by filtering d...
TypeError: sum() takes at most 2 arguments (3 given). Confused with my error?
Not sure why I am receiving a TypeError: sum() takes at most 2 arguments (3 given). Is my code correct? Investigate the distribution of weight for different age groups. To start, partition the dataset into three DataFrames by filtering df and assign them to the following variables: df_20s: Only the rows where 'age' is ...
[ "Instead of sum(len(df_20s),len(df_30s),len(df_40s))), use:\nsum([len(df_20s),len(df_30s),len(df_40s))])\n\nYou can also improve your code to use a dictionary and loop:\nd = {'df_20s' : (df[df['age'] < 30]),\n 'df_30s' : (df[(df['age'] >= 30) & (df['age'] < 40)]),\n 'df_40s' : (df[df['age'] >= 40])\n }\n...
[ 0 ]
[]
[]
[ "dataframe", "error_handling", "pandas", "python" ]
stackoverflow_0074134262_dataframe_error_handling_pandas_python.txt
Q: How to match a group of words that appear consecutively in any order? Say I have a group (or set) of words: {foo, bar, baz}, and I want to match and extract the group. The words can be in any order, but they need to be next to each other. For example, hello foo bar baz wow yeah => foo bar baz hello bar foo baz wow...
How to match a group of words that appear consecutively in any order?
Say I have a group (or set) of words: {foo, bar, baz}, and I want to match and extract the group. The words can be in any order, but they need to be next to each other. For example, hello foo bar baz wow yeah => foo bar baz hello bar foo baz wow yeah => bar foo baz wow yeah hello baz bar foo hello => baz bar foo baz ye...
[ "If each word can only appear once (in the entire string), you may use:\n(?:\\b(foo|bar|baz)(?!.*\\b\\1\\b) ){3}\n\nDemo.\n\nIf words might repeat, I don't think you can get any shorter than something like this:*\n\\b(foo|bar|baz) (?!\\1)(foo|bar|baz) (?!\\1|\\2)(foo|bar|baz)\\b\n\nDemo.\nDetails:\n\n\\b - Word bou...
[ 3, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074134032_python_regex.txt
Q: Problem encountered in MMDetection. KeyError: 'mask_detectionDataset is not in the dataset registry' I tried to train my model with MMdetection, however, error like "KeyError: 'mask_detectionDataset is not in the dataset registry'" keep showing. I've added my dataset to init.py in \mmdetection\mmdet\datasets. And ...
Problem encountered in MMDetection. KeyError: 'mask_detectionDataset is not in the dataset registry'
I tried to train my model with MMdetection, however, error like "KeyError: 'mask_detectionDataset is not in the dataset registry'" keep showing. I've added my dataset to init.py in \mmdetection\mmdet\datasets. And use @DATASETS.register_module(), but problem doesn't solved. When I try to run init.py directly in \mmdete...
[ "maybe add a custom_imports key in your config?\ncustom_imports = dict(\n imports=['mmdet.datasets.mask_detectionDataset'],\n allow_failed_imports=False)\n\n" ]
[ 1 ]
[]
[]
[ "python", "pytorch" ]
stackoverflow_0070136275_python_pytorch.txt
Q: New object not added to queryset in Django Here is the model class Student(models.Model): """Student info""" id = models.CharField( max_length=7,primary_key=True) name = models.CharField(_('name'),max_length=8, default=""); # help_text will locate after the field address = models.CharField(_('addre...
New object not added to queryset in Django
Here is the model class Student(models.Model): """Student info""" id = models.CharField( max_length=7,primary_key=True) name = models.CharField(_('name'),max_length=8, default=""); # help_text will locate after the field address = models.CharField(_('address'),max_length=30,blank=True,default="") #bl...
[ "You are using a custom id field as model id and you put it as Char, so you should add this id also when you want to save an object\nBut it is not a good idea, if you want to use custom id use it in this way\nid = models.AutoField(primary_key=True)\n\n" ]
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074134213_django_python.txt
Q: Variable Is Printing Out as String If I run print(CURRENT_JSON) then it prints out ChunkName, ChunkId, m and LINE as string, rather than printing out their values. How to fix it? CURRENT_JSON = '{"ChunkName": "{ChunkName}", "ChunkData": {"ChunkId": "{ChunkId}", "MasterData": [{"Line": "{m}", "LData": "{LINE}"}]} }...
Variable Is Printing Out as String
If I run print(CURRENT_JSON) then it prints out ChunkName, ChunkId, m and LINE as string, rather than printing out their values. How to fix it? CURRENT_JSON = '{"ChunkName": "{ChunkName}", "ChunkData": {"ChunkId": "{ChunkId}", "MasterData": [{"Line": "{m}", "LData": "{LINE}"}]} }'
[ "You can't build JSON manually without considering escaping embedded control characters. For instance, what if one of these fields has a \" character? Better to build a python dictionary and then serialize it.\nimport json\n\nCURRENT_JSON = json.dumps({\"ChunkName\": ChunkName, \n \"ChunkData\": {\"ChunkId\": Ch...
[ 1 ]
[]
[]
[ "format", "json", "python", "string", "variables" ]
stackoverflow_0074134285_format_json_python_string_variables.txt
Q: Get functions from python generator I'm trying to learn more about generator functions in Python. To my knowledge, generator functions don't fully return until there are no more yield calls, so a stack frame exists in the generator returned by the function. Stack frames should have references to a callable functio...
Get functions from python generator
I'm trying to learn more about generator functions in Python. To my knowledge, generator functions don't fully return until there are no more yield calls, so a stack frame exists in the generator returned by the function. Stack frames should have references to a callable function, so my question is: how can I get that ...
[ "You can use the __name__ attribute to get the name of the original function then access it inside locals provided it's still in scope.\ndef test():\n for i in range(10):\n yield i\n\n\ngenerator = test()\nprint(list(generator)) \n# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n\n\nfunc_name = generator.__name__ \nnew_...
[ 1 ]
[]
[]
[ "cpython", "generator", "python", "stack_frame" ]
stackoverflow_0074133866_cpython_generator_python_stack_frame.txt
Q: comparing a dataframe column to the values found in another dataframe I have a dataframe 'df' where I would like to compare the list of column names to the values found under the dataframe titled 'set_cols' I have code that i previously used to compare a dictionary key to the df column name but i cant figure out h...
comparing a dataframe column to the values found in another dataframe
I have a dataframe 'df' where I would like to compare the list of column names to the values found under the dataframe titled 'set_cols' I have code that i previously used to compare a dictionary key to the df column name but i cant figure out how to make it work to compare a dataframe column heading values to another ...
[ "It looks like a very complicated way to do:\ndiff = df.columns.difference(set_cols['Numbers'])\n\nerrors= {}\nerrors[filename] = dict(enumerate({'column': c,\n 'message': f'{c} is an invalid column heading'}\n for c in diff))\n\nprint(errors)\n\nou...
[ 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074134174_dataframe_pandas_python.txt
Q: scipy minimize on function with multiple inputs, and optimize with multiple bounds I am trying to optimize a function with 2 inputs, each being a list of numbers. I created these similar but simpler version of the function: w1 = [1,2,3] w2 = [4,5,6] w = [w1,w2] def objective(x): a = x[0][0]**2+x[0][1]**2+x[...
scipy minimize on function with multiple inputs, and optimize with multiple bounds
I am trying to optimize a function with 2 inputs, each being a list of numbers. I created these similar but simpler version of the function: w1 = [1,2,3] w2 = [4,5,6] w = [w1,w2] def objective(x): a = x[0][0]**2+x[0][1]**2+x[0][2]**2+x[1][0]**2+x[1][1]**2+x[1][2]**2 return a bnds_1 = tuple((0.1, 1) for w in...
[ "minimize is designed to minimise functions of the form R^n --> R^1. The documentation for minimize states:\nfun: callable\n The objective function to be minimized.\n \n fun(x, *args) -> float\n\n where x is a 1-D array with shape (n,) \n\nThe x0 input should be a 1-D array - you are providing a 2-D array for...
[ 0, 0 ]
[]
[]
[ "constraints", "python", "scipy", "scipy_optimize", "scipy_optimize_minimize" ]
stackoverflow_0074133357_constraints_python_scipy_scipy_optimize_scipy_optimize_minimize.txt
Q: how to send mails in python using outlook web app I want to send mails to many people with python but without using smtp link like how this guy is doing : https://www.youtube.com/watch?v=r6I_YifPid4 can anyone tell how can I recieve this results or if anyone has same type of software as shown in the video tell tha...
how to send mails in python using outlook web app
I want to send mails to many people with python but without using smtp link like how this guy is doing : https://www.youtube.com/watch?v=r6I_YifPid4 can anyone tell how can I recieve this results or if anyone has same type of software as shown in the video tell that too please..
[ "you could use a library like redmail to send emails\nthis is an example of how to use it:\nfrom redmail import outlook\n\noutlook.username = YOUR_USERNAME\noutlook.password = YOUR PASSWORD\n\noutlook.send(receivers, subject, text, attachments)\n\nhope that helps.\n" ]
[ 1 ]
[]
[]
[ "python", "smtp" ]
stackoverflow_0074133169_python_smtp.txt
Q: input a integer X and tell if it is a prime input a integer X and tell if it is a prime. If it is a prime, output 'Y' If not, output 'N' and the smallest prime factor. Here is the program I have tried to write. X = int(input('enter a integer X:')) for i in range(2, X): if X % i == 0: print('Y') else: print('N') Bu...
input a integer X and tell if it is a prime
input a integer X and tell if it is a prime. If it is a prime, output 'Y' If not, output 'N' and the smallest prime factor. Here is the program I have tried to write. X = int(input('enter a integer X:')) for i in range(2, X): if X % i == 0: print('Y') else: print('N') But I would like to print just one time 'Y' or 'N'....
[ "Use any and := walrus operator along with generator like this\nThis will work for python >= 3.8.\nn = int(input(\"Enter a number : \"))\nj = 2\nif any(((k:=j) and (not n%j)) for j in range(2, int(n**0.5)+1)) :\n print(k)\nelse:\n print(\"prime\")\n\n", "You may want to use the Miller-Rabin primality test t...
[ 0, 0 ]
[]
[]
[ "input", "output", "python" ]
stackoverflow_0074134273_input_output_python.txt
Q: Binary variable in GEKKO optimization problem I have an optimization problem that has a condition such that if the variable value is greater than 0, a certain constraint applies. I tried to use m.if3 to generate a binary value that assumes the value of 1 if the variable value is greater than 0, but that did not wo...
Binary variable in GEKKO optimization problem
I have an optimization problem that has a condition such that if the variable value is greater than 0, a certain constraint applies. I tried to use m.if3 to generate a binary value that assumes the value of 1 if the variable value is greater than 0, but that did not work because the m.if3 condition applies for greater ...
[ "You can flip the variable's sign and flip the conditions to get your desired behaviour:\nIn a = m.if3(x,0,1) a = 0 if x < 0, and a = 1 if x >= 0.\nInstead you can do a = m.if3(-x,1,0). Here a = 1 if -x < 0 (equivalent to x > 0).\nUsing an if statement as in the second part of your question will not work because x ...
[ 1, 0 ]
[]
[]
[ "gekko", "optimization", "python" ]
stackoverflow_0074133047_gekko_optimization_python.txt
Q: AttributeError when using python-can (module 'can' has no attribute 'interface') I'm getting an error when running the following code: import can #importing CAN module import time bus1 = can.interface.Bus(bustype='vector', channel=0, bitrate=500000, app_name='python-can') bus2 = can.inter...
AttributeError when using python-can (module 'can' has no attribute 'interface')
I'm getting an error when running the following code: import can #importing CAN module import time bus1 = can.interface.Bus(bustype='vector', channel=0, bitrate=500000, app_name='python-can') bus2 = can.interface.Bus(bustype='vector', channel=1, bitrate=500000, app_nam...
[ "I was having this issue today while using python-can 3.3.3, and resolved it by updating to 3.3.4 which was released not that long ago.\nSince the package is still being worked on, it looks like they accidentally released a broken version with 3.3.3.\n", "In case that issue happens with pyinstaller 4.0 after the ...
[ 2, 0, 0 ]
[]
[]
[ "can_bus", "python" ]
stackoverflow_0064022196_can_bus_python.txt
Q: Redirect print and/or logging to Panel I have made a small application that uses a Rich to show a Live view in several Panels. Is there a way to put standard (or rich) print statements into a particular panel? Being able to show logging output in its own dedicated panel would also work. I feel like this would be a...
Redirect print and/or logging to Panel
I have made a small application that uses a Rich to show a Live view in several Panels. Is there a way to put standard (or rich) print statements into a particular panel? Being able to show logging output in its own dedicated panel would also work. I feel like this would be a very common use case but I haven't found an...
[ "I figure out how you can manage to that. First, we need to intercept the stdout process of Rich logger. We start with a class:\nfrom collections import deque\nclass Logger():\n _instance = None\n def __init__(self):\n self.messages = deque([\"sa\"])\n self.size = 10\n\n def __new__(class_, *...
[ 1, 1, 0, 0, 0 ]
[]
[]
[ "python", "rich" ]
stackoverflow_0071077706_python_rich.txt
Q: OLS Statsmodels formula: Returns an ValueError: zero-size array to reduction operation maximum which has no identity Hey I am doing multiple OLS regressions for some cross-sectional data iterating through the months. I encounter for the forth month a ValueError: zero-size array to reduction operation maximum which...
OLS Statsmodels formula: Returns an ValueError: zero-size array to reduction operation maximum which has no identity
Hey I am doing multiple OLS regressions for some cross-sectional data iterating through the months. I encounter for the forth month a ValueError: zero-size array to reduction operation maximum which has no identity. But I do not know why. The data has no NaNs, I have tested this with dropna since it was suggested in an...
[ "I was reluctant to use this approach but it works and I still get results even for those month where there is supposed to be a lack of data.\nI found the idea here Overcom ValueError for empty array\ntry: #Catches the upcoming Value Error\n results = smf.ols(formula = 'eTR_t1 ~ ESG_norm', data=df_month)...
[ 0 ]
[]
[]
[ "python", "regression", "statsmodels" ]
stackoverflow_0074036864_python_regression_statsmodels.txt
Q: Gekko discrete optimization indexing problem I have a question regarding this problem. I want to let model search for optimal value of loader, loader_size, truck, truck_size to solve two constraints of total cost and total duration. However, i faced with a problem regarding the cost. Since truck size and truck, lo...
Gekko discrete optimization indexing problem
I have a question regarding this problem. I want to let model search for optimal value of loader, loader_size, truck, truck_size to solve two constraints of total cost and total duration. However, i faced with a problem regarding the cost. Since truck size and truck, loader size and loader cost cost must be correlated....
[ "Use a cubic spline (cspline) to lookup the values of size and cost. They are interpolations between the points but exactly equal the size and cost at the integer values. Here is a script that solves successfully:\nimport numpy as np\nfrom gekko import GEKKO\nimport random\nm = GEKKO()\n\nTotal_Cost = m.Const(15000...
[ 0 ]
[]
[]
[ "discrete", "gekko", "optimization", "python" ]
stackoverflow_0074107619_discrete_gekko_optimization_python.txt
Q: How to record video rtsp and save video for 5 minutes using python and opencv How to record video rtsp and save video for 5 minutes using python and opencv i m using to record some of the code but for 5 minutes using clas and function video is very tuff to download for 5 minutes. A: You will need to import cv2. ...
How to record video rtsp and save video for 5 minutes using python and opencv
How to record video rtsp and save video for 5 minutes using python and opencv i m using to record some of the code but for 5 minutes using clas and function video is very tuff to download for 5 minutes.
[ "You will need to import cv2. You may need to execute pip install opencv-python to install the module for importation.\nimport cv2\nimport time\n\n# open video stream\ncap = cv2.VideoCapture('rtsp://127.0.0.1/stream')\n\n# set video resolution\ncap.set(3, 640)\ncap.set(4, 480)\n\n# set video codec\nfourcc = cv2.Vid...
[ 0 ]
[]
[]
[ "capture", "opencv", "python", "recording", "video" ]
stackoverflow_0074134718_capture_opencv_python_recording_video.txt
Q: pd.read_csv just not responding I am trying to load all the csv files of directory in list of dataframes in python. These are about 1000 files and 300kb each. I was able to read 5000 files of exactly same structure previously from another directory using this small code. However, now I am facing a weird problem. W...
pd.read_csv just not responding
I am trying to load all the csv files of directory in list of dataframes in python. These are about 1000 files and 300kb each. I was able to read 5000 files of exactly same structure previously from another directory using this small code. However, now I am facing a weird problem. When I run this, each time the script ...
[ "First, I would ensure that all data you are loading into a dataframe is needed (for example, can you only read in specific columns you need). If that isn't a solution, I would use the chunksize parameter and concatenate the results. Here is an example from Panda's docs 1:\nIn [216]: with pd.read_csv(\"tmp.csv\", s...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074132245_dataframe_pandas_python.txt
Q: How to match between row values serial name match 1 John 5,6,8 2 Steve 1,7 3 Kevin 4 4 Kevin 3 5 John 1,6,8 6 Johnn 1,5,8 7 Steves 2 8 John 1,5,6 Need to check and match the name of each row with the name of the row serial number mentioned in it's match column. Keep the serials matching else remove it. If...
How to match between row values
serial name match 1 John 5,6,8 2 Steve 1,7 3 Kevin 4 4 Kevin 3 5 John 1,6,8 6 Johnn 1,5,8 7 Steves 2 8 John 1,5,6 Need to check and match the name of each row with the name of the row serial number mentioned in it's match column. Keep the serials matching else remove it. If nothing is matching...
[ "Convert values of serial column to strings,then mapping aggregate sets to Series wth same size like original, split column match and get difference with intersection of sets, last sorting and join back to strings:\ns = df['serial'].astype(str)\nsets = df['name'].map(s.groupby(df['name']).agg(set))\nmatch = df['mat...
[ 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074134608_pandas_python.txt
Q: How to retain elements from pandas dict I have he below code like this which splits the address column and pops if length of add dict equal to 4 or 5(see code). import pandas as pd data = {'address': ["William J. Clare\\n290 Valley Dr.\\nCasper, WY 82604\\nUSA", "1180 Shelard Tower\\nMinneapol...
How to retain elements from pandas dict
I have he below code like this which splits the address column and pops if length of add dict equal to 4 or 5(see code). import pandas as pd data = {'address': ["William J. Clare\\n290 Valley Dr.\\nCasper, WY 82604\\nUSA", "1180 Shelard Tower\\nMinneapolis, MN 55426\\nUSA", "Wil...
[ "Instead of using pop(), it might work to use slicing, like target = target[-3:]. This tells it to take only the last three items in the list.\n", "Simple use slicing in a if-else condition\nCODE:\nimport pandas as pd\n\ndata = {'address': [\"William J. Clare\\\\n290 Valley Dr.\\\\nCasper, WY 82604\\\\nUSA\",\n ...
[ 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074134717_dataframe_pandas_python.txt
Q: env: python: No such file or directory when building app with Xcode When I build/run/archive my app in Xcode (on MacOS 12.3) I encounter this error: env: python: No such file or directory Command Ld failed with a nonzero exit code I think I might have changed something with regard to my python environment while w...
env: python: No such file or directory when building app with Xcode
When I build/run/archive my app in Xcode (on MacOS 12.3) I encounter this error: env: python: No such file or directory Command Ld failed with a nonzero exit code I think I might have changed something with regard to my python environment while working on a school project or messed something up there. However, I can n...
[ "Homebrew only installs the binary python3, just to be safe. Xcode is complaining about a lack of the binary python (note the lack of a 3!).\nYou have a couple of options:\n\nWhen installing python3, Homebrew also creates a libexec folder with unversioned symlinks, such as python (what you're missing). Note the Cav...
[ 64, 21, 16, 12, 5, 3, 2, 0 ]
[]
[]
[ "nativescript", "python", "xcode" ]
stackoverflow_0071468590_nativescript_python_xcode.txt
Q: Error: can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first I am trying to make a MLP classifier in PyTorch. The error is produced from the code in the final chunk. I'm not sure why numpy is even involved with this, can someone please point me in the right dire...
Error: can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first
I am trying to make a MLP classifier in PyTorch. The error is produced from the code in the final chunk. I'm not sure why numpy is even involved with this, can someone please point me in the right direction. device = torch.device("cuda" if torch.cuda.is_available() else "cpu") data = ImageFolder(data_dir, transform=tr...
[ "The plotting function you are using, plt.plot, works on numpy arrays and not on torch.tensors. Therefore, accHistory is being converted to numpy array and failed there.\nPlease see this answer for more details.\n" ]
[ 1 ]
[]
[]
[ "python", "pytorch" ]
stackoverflow_0074133657_python_pytorch.txt
Q: Update bubble plot using Arduino serial data Hi I'm new to this Site and appreciate your help. I have a variable resistor and it reads analog value and send to the python script. My objective is to plot this value using bubble plot which indicate the intensity by using radius of the circle. But I can not understan...
Update bubble plot using Arduino serial data
Hi I'm new to this Site and appreciate your help. I have a variable resistor and it reads analog value and send to the python script. My objective is to plot this value using bubble plot which indicate the intensity by using radius of the circle. But I can not understand to clear the figure and update it. Your help wil...
[ "The matplotlib.animation documentation has a good example to get you started (I added some comments below). This works much faster than manually drawing and clearing the plot. Please try adapting your code using this example:\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import Fu...
[ 0 ]
[]
[]
[ "matplotlib_animation", "plot", "python" ]
stackoverflow_0074134892_matplotlib_animation_plot_python.txt
Q: Adjusting plot.graph_objects.Sunburst colorbar Although I can create a colorbar for Sunburst, I fail to manipulate the fontsize, ntick, tickvals and other parameters in the colorbar. import plotly.graph_objects as go data = dict( labels=["Eve", "Cain", "Seth", "Enos", "Noam", "Abel", "Awan", "Enoch", "Azura"]...
Adjusting plot.graph_objects.Sunburst colorbar
Although I can create a colorbar for Sunburst, I fail to manipulate the fontsize, ntick, tickvals and other parameters in the colorbar. import plotly.graph_objects as go data = dict( labels=["Eve", "Cain", "Seth", "Enos", "Noam", "Abel", "Awan", "Enoch", "Azura"], parents=["", "Eve", "Eve", "Seth", "Seth", "Ev...
[ "You can continue with the same way with marker, have a look at the code below:\nimport plotly.graph_objects as go\n\ndata = dict(\n labels=[\"Eve\", \"Cain\", \"Seth\", \"Enos\", \"Noam\", \"Abel\", \"Awan\", \"Enoch\", \"Azura\"],\n parents=[\"\", \"Eve\", \"Eve\", \"Seth\", \"Seth\", \"Eve\", \"Eve\", \"A...
[ 1 ]
[]
[]
[ "plotly", "plotly_python", "python" ]
stackoverflow_0074134753_plotly_plotly_python_python.txt
Q: for loop starts over again I'm trying to load shapefiles with years from 1900-2014 into a dictionary in a for loop using geopandas. I did the same code already except with fiona which worked fine but I am finding at an individual level that the data is more useful for me in geopandas format. All I did was replace ...
for loop starts over again
I'm trying to load shapefiles with years from 1900-2014 into a dictionary in a for loop using geopandas. I did the same code already except with fiona which worked fine but I am finding at an individual level that the data is more useful for me in geopandas format. All I did was replace the fiona command with the gpd.r...
[ "Every time you move to the next file in the list you re-create your \"years\" variable and loop through it again. It sounds like you only want this to happen once(?). There is currently nothing in your code that relates the current file name to the current \"year\", so it will blindly loop through them all. It sou...
[ 0 ]
[]
[]
[ "dictionary", "for_loop", "geopandas", "python" ]
stackoverflow_0074134874_dictionary_for_loop_geopandas_python.txt
Q: No module named 'flask_restful' according to command prompt I am trying to learn the basics of apis and flask restful, and was trying to run the minimal api in the flask documentation. I installed flask and flask-restful into the scripts folder in the virtual environment using command prompt, and my ide picked up ...
No module named 'flask_restful' according to command prompt
I am trying to learn the basics of apis and flask restful, and was trying to run the minimal api in the flask documentation. I installed flask and flask-restful into the scripts folder in the virtual environment using command prompt, and my ide picked up that these modules are installed. However, having saved the scrip...
[ "Do you have flask-restful installed on your system? If not just use pip for installation, and type in your command prompt this command: pip install flask-restful\n" ]
[ 0 ]
[]
[]
[ "command_line_interface", "flask_restful", "python" ]
stackoverflow_0074135009_command_line_interface_flask_restful_python.txt
Q: Concatenating columns in pandas dataframe I have a dataset like below (see code): import pandas as pd data = {'id': ['001', '002', '003','004'], 'address': ["William J. Clare\\n290 Valley Dr.\\nCasper, WY 82604\\nUSA", "1180 Shelard Tower\\nMinneapolis, MN 55426\\nUSA", ...
Concatenating columns in pandas dataframe
I have a dataset like below (see code): import pandas as pd data = {'id': ['001', '002', '003','004'], 'address': ["William J. Clare\\n290 Valley Dr.\\nCasper, WY 82604\\nUSA", "1180 Shelard Tower\\nMinneapolis, MN 55426\\nUSA", "William N. Barnard\\n145 S. Durbin\\nCas...
[ "The following will do the work\ndf = df['address'].where(df[['locality', 'region', 'Zipcode', 'Country']].isnull().all(axis=1), df['address'] + '\\\\n' + df['locality'] + ', ' + df['region'] + ' ' + df['Zipcode'] + '\\\\n' + df['Country'])\n\n[Out]:\n\n0 William J. Clare\\n290 Valley Dr.\\nCasper, WY 8...\n1 ...
[ 0 ]
[]
[]
[ "concatenation", "dataframe", "if_statement", "pandas", "python" ]
stackoverflow_0074134911_concatenation_dataframe_if_statement_pandas_python.txt
Q: How to type hint dynamically created properties of a class def property_factory(n: int) -> property: getter = lambda self: return n return property(getter) class Foo: number: int = property_factory(1) The above code gives me the errror (line 6) Expression of type "property" cannot be assigned to dec...
How to type hint dynamically created properties of a class
def property_factory(n: int) -> property: getter = lambda self: return n return property(getter) class Foo: number: int = property_factory(1) The above code gives me the errror (line 6) Expression of type "property" cannot be assigned to declared type int How do I go about type hinting dynamically creat...
[ "One possible option is to use Protocol:\nfrom typing import Protocol, TypeVar, overload\n\n\nT_co = TypeVar('T_co', covariant=True)\n\n\nclass ReadonlyProperty(Protocol[T_co]):\n\n @overload\n def __get__(self, instance: None, owner) -> property: ...\n\n @overload\n def __get__(self, instance, owner) -...
[ 0 ]
[ "Just change the return type to int instead of property.\nBut I suggest you to follow the classic approach:\nclass Foo:\n def __init__(self) -> None:\n self._property_factory: int = 0\n self.property_factory = 1\n number: int = self.property_factory\n\n @property # getter\n def prope...
[ -1 ]
[ "python", "python_3.x" ]
stackoverflow_0074125481_python_python_3.x.txt
Q: Python Sanic ext 22.9.0 - Open API static YAML file loading I am using sanic/sanic-ext 22.9.0 , I need to load a static open api yaml or json file rather than autogenerate so that when I access it as <url>/docs, the static yaml file is loaded and UI display either Swagger or redoc version of UI with the API defi...
Python Sanic ext 22.9.0 - Open API static YAML file loading
I am using sanic/sanic-ext 22.9.0 , I need to load a static open api yaml or json file rather than autogenerate so that when I access it as <url>/docs, the static yaml file is loaded and UI display either Swagger or redoc version of UI with the API definition. Any suggestion on how to achieve this.
[ "You have a few options.\nOPTION 1\nLoad your custom OAS into Sanic, and server that.\n@app.before_server_start\nasync def load_oas(app: Sanic):\n custom_oas_dict = load_spec_from_yaml()\n app.ext.openapi.raw(custom_oas_dict)\n\nOPTION 2\nTurn off OAS and roll your own solution, including swagger/redoc, etc\n...
[ 1 ]
[]
[]
[ "openapi", "python", "sanic" ]
stackoverflow_0074129080_openapi_python_sanic.txt
Q: What is different between scipy.sparse.csr_matrix and scipy.sparse.lil_matrix What is different between scipy.sparse.csr_matrix and scipy.sparse.lil_matrix? These matrices represent sparse matrices, but I don't know what is different. Additionally, what is each advantage for using lil_matrix or csr_matrix? A: cs...
What is different between scipy.sparse.csr_matrix and scipy.sparse.lil_matrix
What is different between scipy.sparse.csr_matrix and scipy.sparse.lil_matrix? These matrices represent sparse matrices, but I don't know what is different. Additionally, what is each advantage for using lil_matrix or csr_matrix?
[ "csr_matrix is the Compressed Sparse Row matrix, while\ncsc_matrix is the Compressed Sparse Column matrix.\nSo if you know your data will be large and sparse row-wise, you'll likely want to use csr_matrix. If, instead your date is sparse column-wise, you'll want to use a csc_matrix.\nAs explained in this post, ther...
[ 0 ]
[]
[]
[ "python", "scipy" ]
stackoverflow_0069216623_python_scipy.txt
Q: anaconda activation bug on windows wsl2 I'm trying to activate anaconda on wsl2. anaconda version - Anaconda3-2021.05-Linux-x86_64 wsl distro - ubuntu 20.04.1 I'm getting this error on opening a new shell bash: eval: line 203: syntax error near unexpected token ('` Subsequent activation of other environments with ...
anaconda activation bug on windows wsl2
I'm trying to activate anaconda on wsl2. anaconda version - Anaconda3-2021.05-Linux-x86_64 wsl distro - ubuntu 20.04.1 I'm getting this error on opening a new shell bash: eval: line 203: syntax error near unexpected token ('` Subsequent activation of other environments with conda activate <envname> fails with a similar...
[ "wsl adds environment variables from windows itself.\nOne of the paths in the path environment variable was missing an apostrophes.\nThat was the cause.\n" ]
[ 0 ]
[]
[]
[ "activation", "anaconda", "python", "windows_subsystem_for_linux" ]
stackoverflow_0067950066_activation_anaconda_python_windows_subsystem_for_linux.txt
Q: Cannot save PySpark dataframe as a parquet file Complete Python newbie here. I am trying to save a PySpark dataframe as a parquet file, but it's giving me an error. I installed PySpark PySpark version is 3.3.0, Hadoop version 3.2.2, Java jdk1.8.0_351 on PC and created environment variables, as per https://phoenix...
Cannot save PySpark dataframe as a parquet file
Complete Python newbie here. I am trying to save a PySpark dataframe as a parquet file, but it's giving me an error. I installed PySpark PySpark version is 3.3.0, Hadoop version 3.2.2, Java jdk1.8.0_351 on PC and created environment variables, as per https://phoenixnap.com/kb/install-spark-on-windows-10. I am using Ju...
[ "May I know how and where you are running this code snippet ?\nIf you are running on your local machine, then you need to setup your HADOOP_HOME.\nyou can refer to the below docs which will give details around it.\nhttps://phoenixnap.com/kb/install-spark-on-windows-10\nSetting HADOOP_HOME on windows:\nhttps://brain...
[ 0 ]
[]
[]
[ "apache_spark", "parquet", "pyspark", "python" ]
stackoverflow_0074134851_apache_spark_parquet_pyspark_python.txt
Q: Python request.get() after few seconds I want to get html-text a few seconds after opening url. Here's the code: import requests url = "http://XXXXX…" html = request.get(url).text A: I want to get html-text few seconds after opening url. Well, the webpage HTML stays the same right after you "get" the url using ...
Python request.get() after few seconds
I want to get html-text a few seconds after opening url. Here's the code: import requests url = "http://XXXXX…" html = request.get(url).text
[ "\nI want to get html-text few seconds after opening url.\n\nWell, the webpage HTML stays the same right after you \"get\" the url using Requests, so there's no need to wait a few seconds as the HTML will not change.\nI assume the reason that you would like to wait is for the page to load all the relevant resources...
[ 5, 3, 1, 1 ]
[ "basically you can give a sleep to the request as a parameter as bellow:\nimport requests\nimport time\nurl = \"http://XXXXX…\"\nseconds = 5\nhtml = requests.get(url,time.sleep(seconds)).text #for example 5 seconds\n\n" ]
[ -2 ]
[ "python" ]
stackoverflow_0044014718_python.txt
Q: How do I connect Docker Airflow container to local machine, so that I can write/save files to local machine? I have a file called hello_world.py saved in my dag folder, that contains the following code. from airflow import DAG from airflow.operators.python import PythonOperator from datetime import datetime import...
How do I connect Docker Airflow container to local machine, so that I can write/save files to local machine?
I have a file called hello_world.py saved in my dag folder, that contains the following code. from airflow import DAG from airflow.operators.python import PythonOperator from datetime import datetime import os.path def helloWorld(): f= open("C:\\Users\\username\\test.txt","w+") f.write("hello world") f.clo...
[ "Your Airflow docker can not access the host machine unless you bind a volume that map between a folder in the host to a folder in the docker.\nIf you are using a docker-compose you can defined this volume where the dags/plugins and logs are defined\nvolumes:\n- ./dags:/opt/airflow/dags\n- ./logs:/opt/airflow/logs\...
[ 0 ]
[]
[]
[ "airflow", "docker", "python" ]
stackoverflow_0074133419_airflow_docker_python.txt
Q: How to give a condition that if difference between two hexadecimal no is 2 then concatenate two rows? I have a file which contain two columns, eg abc.txt 000000008b8c5200 af dg sd jh g1 43 66 23 67 000000008b8c5220 bc bi ub cb ue qi hd 16 72 0000000056fb2620 ad ag sj ha bn bc bh 53 69 00000000...
How to give a condition that if difference between two hexadecimal no is 2 then concatenate two rows?
I have a file which contain two columns, eg abc.txt 000000008b8c5200 af dg sd jh g1 43 66 23 67 000000008b8c5220 bc bi ub cb ue qi hd 16 72 0000000056fb2620 ad ag sj ha bn bc bh 53 69 0000000056fb2640 ak bh jg bf re 34 16 8g ff 0000000045ab4630 sg fj g3 6g dh w7 28 g7 dg 0000000045ab4...
[ "Here is how you could do it:\nwith open('input.txt', 'r') as f, open('output.txt', 'w') as g:\n out = []\n lines = [elem.strip().split() for elem in f] # lines will be list of lists, each list with 2 elements (-> 2 columns)\n for line_x, line_y in zip(lines[::2], lines[1::2]): # use zip and steps of 2 to ...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074134756_python.txt
Q: Is there a numpy function to compress a (k, m, n) matrix to a (k//2, m//2, n//2) matrix by summing neighbors? This can be accomplished with cube = ( cube[::2, ::2, ::2] + cube[1::2, ::2, ::2] + cube[::2, 1::2, ::2] + cube[1::2, 1::2, ::2] + cube[::2, ::2, 1::2] + cube[1::2, ::2, 1::2] +...
Is there a numpy function to compress a (k, m, n) matrix to a (k//2, m//2, n//2) matrix by summing neighbors?
This can be accomplished with cube = ( cube[::2, ::2, ::2] + cube[1::2, ::2, ::2] + cube[::2, 1::2, ::2] + cube[1::2, 1::2, ::2] + cube[::2, ::2, 1::2] + cube[1::2, ::2, 1::2] + cube[::2, 1::2, 1::2] + cube[1::2, 1::2, 1::2] ) But I'm wondering if there is a function to accomplish this ...
[ "This sounds like a classical strided-convolution pooling operation.\nYou can do this in many ways, but the most straightforward would probably be to use skimage's block_reduce functionality, as so -\nfrom skimage.measure import block_reduce\na = np.arange(6*8*4).reshape(6, 8, 4)\nreduced_a = block_reduce(a, block_...
[ 1, 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074130858_numpy_python.txt
Q: Creating a user file input that keeps asking if entered a wrong file name I had created a python program that asks a user to create a file (for simplicity this will just be a .txt file). The stipulation is that the file can only contain alphabets and an "_". No leading numbers and cannot contain special characters...
Creating a user file input that keeps asking if entered a wrong file name
I had created a python program that asks a user to create a file (for simplicity this will just be a .txt file). The stipulation is that the file can only contain alphabets and an "_". No leading numbers and cannot contain special characters and it must contain an "." somehow for an extension. In this program I did use...
[ "Put the 3 conditions you have in a while loop using if statements instead to check for all 3. Use continue to go the start of the while loop and ask for new input on invalid input. break out of the loop of if all checks are passed.\nimport re\n\npattern1 = re.compile('[ @ ! # $ % ^ & * ( ) < > ? / \\ | { } ~ : ]')...
[ 0 ]
[]
[]
[ "python", "regex", "writelines" ]
stackoverflow_0074134459_python_regex_writelines.txt
Q: How do I run a background task with sanic blueprint instance? I saw the docs and that caused some confusion for me. When working with blueprints, how do I schedule a background task inside my manager class or my service class for that matter. Any of the cases would work but I would prefer if I could schedule a bac...
How do I run a background task with sanic blueprint instance?
I saw the docs and that caused some confusion for me. When working with blueprints, how do I schedule a background task inside my manager class or my service class for that matter. Any of the cases would work but I would prefer if I could schedule a background task from the manager class. admin = Blueprint("admin", ver...
[ "It is unclear what you mean by \"manager\" class.\nIf you mean inside of your route on your admin blueprint, what I think you really want is this:\n@admin.route(\"admin/applications\", methods=[\"GET\"], name=\"get_apps\")\nasync def get_all_apps(request: Request):\n ...\n request.app.add_task(task_to_run_in...
[ 1 ]
[]
[]
[ "python", "sanic" ]
stackoverflow_0074134597_python_sanic.txt
Q: sqlalchemy random error Exception during reset or similar - no impact on functionality I have an application running and from time to time this stack trace shows in console. However the app continues to run smoothly. Anyway, I don't really like this kind of unpredictable behavior in the app. Can I avoid such error...
sqlalchemy random error Exception during reset or similar - no impact on functionality
I have an application running and from time to time this stack trace shows in console. However the app continues to run smoothly. Anyway, I don't really like this kind of unpredictable behavior in the app. Can I avoid such error messages? All queries are returned with correct data, updates work fine. No idea why this m...
[ "You actually do want these messages. They state that your parameter pool_pre_ping=True works as intended. It is in the nature of the thing that it is unpredictable behavior, as it is handling exactly those unpredictable moments.\nI guess you could just try wrap the thing so it does not pop up in your console:\ntry...
[ 0 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0069928081_python_sqlalchemy.txt
Q: VSCode "Open file in editor" hover not working in Python When I get a syntax error in Python I think VSCode is supposed to offer a mouse hover over the error message, which lets you Ctrl-click to go to the errored line in the editor. I'm not getting the hover on the final line in the traceback (but it works OK on ...
VSCode "Open file in editor" hover not working in Python
When I get a syntax error in Python I think VSCode is supposed to offer a mouse hover over the error message, which lets you Ctrl-click to go to the errored line in the editor. I'm not getting the hover on the final line in the traceback (but it works OK on earlier lines). I think it's some kind of configuration proble...
[ "UPDATE:\nThe problem is that there are spaces in your file path.\n\nTo fix it, change your folder name to make the file path recognizable. Generally, the file path should be in full English, with no spaces and no special symbols.\n\nHover over the file path to see the underscore including the line number. At this ...
[ 1 ]
[]
[]
[ "python", "syntax_error", "visual_studio_code" ]
stackoverflow_0074128021_python_syntax_error_visual_studio_code.txt
Q: How to find selector for this HTML snippet How to find selector from this? I want to click the button but unable to find selector.it will be a css selector or class selector. HTML <button data-bb-handler="confirm" type="button" class="btn btn-success">Continue and Logout Other User</button> A: You can try it but...
How to find selector for this HTML snippet
How to find selector from this? I want to click the button but unable to find selector.it will be a css selector or class selector. HTML <button data-bb-handler="confirm" type="button" class="btn btn-success">Continue and Logout Other User</button>
[ "You can try it\nbutton_Login = driver.find_element_by_css_selector(\"#button\").text(\"Continue and Logout Other User\")\n\n", "Make sure the button is visible when you try to click it.\nThe following selectors should work:\n.btn-succes \n//button[@class='btn btn-succes']\n\n", "You can use the following selec...
[ 0, 0, 0 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0074134728_python_selenium.txt
Q: Extract table from Powerpoint I am trying to extract table from a PPT using python-pptx, however, the I am not sure how do I that using shape.table. from pptx import Presentation prs = Presentation(path_to_presentation) # text_runs will be populated with a list of strings, # one for each text run in presentation t...
Extract table from Powerpoint
I am trying to extract table from a PPT using python-pptx, however, the I am not sure how do I that using shape.table. from pptx import Presentation prs = Presentation(path_to_presentation) # text_runs will be populated with a list of strings, # one for each text run in presentation text_runs = [] for slide in prs.slid...
[ "This appears to work for me.\n\nprs = Presentation((path_to_presentation))\n# text_runs will be populated with a list of strings,\n# one for each text run in presentation\ntext_runs = []\nfor slide in prs.slides:\n for shape in slide.shapes:\n if not shape.has_table:\n continue \n tb...
[ 5, 0 ]
[]
[]
[ "powerpoint", "python", "python_3.x", "python_pptx" ]
stackoverflow_0054419118_powerpoint_python_python_3.x_python_pptx.txt
Q: How can I find the first difference between two strings in Python? Let's say I have: a = 'abcde' b = 'ab34e' How can I get printed out that the difference in a is c,d and in b is 3,4? Also would it be possible to also the get the index of those? I know I should use difflib, but the furthest I've got is with this ...
How can I find the first difference between two strings in Python?
Let's say I have: a = 'abcde' b = 'ab34e' How can I get printed out that the difference in a is c,d and in b is 3,4? Also would it be possible to also the get the index of those? I know I should use difflib, but the furthest I've got is with this overly complex code from this website: https://towardsdatascience.com/si...
[ "Something like this?\na = \"abcde\"\nb = \"ab2de\"\n\nfor index, char in enumerate(a):\n if not b[index] == char:\n print(f\"First mismatch on index {index}: {char} is not {b[index]}\")\n\n\nWould print: First mismatch on index 2: c is not 2\nAnother possibility would be to create a list of 3-way-tuples,...
[ 2, 1, 1 ]
[]
[]
[ "difflib", "python" ]
stackoverflow_0074135109_difflib_python.txt
Q: Combine two columns into tuple in polars python API I have a polars dataframe that looks like: df = pl.DataFrame({"bid": [1, 2, 3], "fid": [4, 5, 6]}) I would like to combine the two columns row wise into a tuple so that the result looks like: pl.DataFrame({"bfid": [(1, 4), (2, 5), (3, 6)]}) I tried to do this: ...
Combine two columns into tuple in polars python API
I have a polars dataframe that looks like: df = pl.DataFrame({"bid": [1, 2, 3], "fid": [4, 5, 6]}) I would like to combine the two columns row wise into a tuple so that the result looks like: pl.DataFrame({"bfid": [(1, 4), (2, 5), (3, 6)]}) I tried to do this: df2.with_columns(pl.map(['bid', 'fid'], lambda x: (x[0], ...
[ "So to combine row-wise columns of a dataframe in polars is pretty straight forward since this kind of functionality is already built in.\ndf.select(pl.concat_list(pl.col([\"bid\", \"fid\"])).alias(\"bfid\"))\n\n\nshape: (3, 1)\n┌───────────┐\n│ bfid │\n│ --- │\n│ list[i64] │\n╞═══════════╡\n│ [1, 4] ...
[ 2 ]
[]
[]
[ "data_manipulation", "python", "python_polars" ]
stackoverflow_0074130719_data_manipulation_python_python_polars.txt
Q: Invoke Django Signal only if the record is newly created - Django I am using Django post_save signal, which will trigger whenever the new record is created. This signal is called every time a save action takes place. Even though it has the created boolean field, this function is executed all the time. The problem ...
Invoke Django Signal only if the record is newly created - Django
I am using Django post_save signal, which will trigger whenever the new record is created. This signal is called every time a save action takes place. Even though it has the created boolean field, this function is executed all the time. The problem here is, at each request I am updating the User table last_login and la...
[ "If you call save on an instance model there is really no way around not hooking into the signal.\nHowever if you were to change the way you update your user instance you could skip the signal.\nThis for instance won't trigger the post_save event\nUser.objects.filter(id=1).update(last_login=timestamp)\n\n", "Cons...
[ 0, 0, 0 ]
[]
[]
[ "django", "django_models", "django_signals", "python" ]
stackoverflow_0072487137_django_django_models_django_signals_python.txt
Q: Getting Error while importing functions from a file which takes runtime arguments I have a file Main.py which takea one runtime argument NoOftimes. Which I store in NoOftimes = sys.argv[1] I tried to run help.py for NoOftimes in a function of Main.py but getting error def RunScriptForTime(NoOftimes): for i in ...
Getting Error while importing functions from a file which takes runtime arguments
I have a file Main.py which takea one runtime argument NoOftimes. Which I store in NoOftimes = sys.argv[1] I tried to run help.py for NoOftimes in a function of Main.py but getting error def RunScriptForTime(NoOftimes): for i in range(NoOftimes): print("File is opened........") os.system('python hel...
[ "My Problem is solved now. It was because the Main.py was run every time the help.py was opened.\nUse\nif __name__ == \"__main__\":\n import sys\n NoOfTimes = sys.argv[1]\n RunScriptForTime(NoOfTimes)\n sys.exit()\n\nThe Main.py will run this block of code only if python script is directly run by user.\n" ]
[ 0 ]
[]
[]
[ "import", "python", "sys" ]
stackoverflow_0074135037_import_python_sys.txt
Q: How to view detailed data in Kusto, using the Python kusto SDK I have used the following packages import pandas as pd from azure.kusto.data import KustoClient, KustoConnectionStringBuilder from azure.kusto.data.exceptions import KustoServiceError from azure.kusto.data.helpers import dataframe_from_result_table I ...
How to view detailed data in Kusto, using the Python kusto SDK
I have used the following packages import pandas as pd from azure.kusto.data import KustoClient, KustoConnectionStringBuilder from azure.kusto.data.exceptions import KustoServiceError from azure.kusto.data.helpers import dataframe_from_result_table I would like to see the detailed output of the results, but I followed...
[ "You can play with the publicly available help cluster.\nPlease note that the connection requires an interactive login.\nA login window will pop when you execute the code.\nfrom azure.kusto.data import KustoClient, KustoConnectionStringBuilder\nfrom azure.kusto.data.helpers import dataframe_from_result_table\n\nclu...
[ 0 ]
[]
[]
[ "azure", "azure_data_explorer", "kql", "python" ]
stackoverflow_0074135101_azure_azure_data_explorer_kql_python.txt
Q: Count the range of each value in Python I have dataset of student's scores for each subject. StuID Subject Scores 1 Math 90 1 Geo 80 2 Math 70 2 Geo 60 3 Math 50 3 Geo 90 Now I want to count the range of scores for each subject like 0< x <=20, 2...
Count the range of each value in Python
I have dataset of student's scores for each subject. StuID Subject Scores 1 Math 90 1 Geo 80 2 Math 70 2 Geo 60 3 Math 50 3 Geo 90 Now I want to count the range of scores for each subject like 0< x <=20, 20< x <=30 and get a dataframe like this: Sub...
[ "Assuming a pandas DataFrame df:\nimport pandas as pd\n\nbins = list(range(0, 100+1, 20))\n# [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]\nlabels = [f'{a}-{b}' for a,b in zip(bins, bins[1:])]\n# ['0-10', '10-20', '20-30', '30-40', '40-50', '50-60', '60-70', '70-80', '80-90', '90-100']\n\nout = (pd.crosstab(df['Subj...
[ 3, 0 ]
[]
[]
[ "count", "dataframe", "python", "range" ]
stackoverflow_0074135208_count_dataframe_python_range.txt
Q: From SQL to Django without raw method I'm trying to convert SQL Query to Django. I'm new to Django and I find it hard to do simple things, here is the SQL query I'm trying to run with Django : SELECT * FROM balance_hold bh1 WHERE bh1.account_balance = X and bh1.hold_id in ( SELECT hold_id FROM balance...
From SQL to Django without raw method
I'm trying to convert SQL Query to Django. I'm new to Django and I find it hard to do simple things, here is the SQL query I'm trying to run with Django : SELECT * FROM balance_hold bh1 WHERE bh1.account_balance = X and bh1.hold_id in ( SELECT hold_id FROM balance_hold bh2 WHERE bh2.transaction_i...
[ "I don't think attempting to translate an sql query to django ORM is the right way to tackle your issue, regardless you'll need several tools to achieve this.\nOR and AND can be written with Q objects (https://docs.djangoproject.com/fr/4.1/ref/models/querysets/#operators-that-return-new-querysets).\nThe kind of sub...
[ 1 ]
[]
[]
[ "django", "python", "sql" ]
stackoverflow_0074125589_django_python_sql.txt
Q: The problem of merging dataframes with different rows When i have these 2 dataframes,, df1: df2: col1 col2 | col3 col4 1 2 | 0 0 3 4 | 0 0 | 0 0 I want to merge them into this form. col1 col2 col3 col4 1 2 0 0 3 4 0 0 0 0 If I use concat, t...
The problem of merging dataframes with different rows
When i have these 2 dataframes,, df1: df2: col1 col2 | col3 col4 1 2 | 0 0 3 4 | 0 0 | 0 0 I want to merge them into this form. col1 col2 col3 col4 1 2 0 0 3 4 0 0 0 0 If I use concat, this is what happens. concat([df1,df2],axis=1) col1 col2 co...
[ "The issue must be somewhere in your actual code, since this is what I get:\nfrom pandas import DataFrame, concat\n\ndf1 = DataFrame([\n {'col1': 1., 'col2': 2.},\n {'col1': 3., 'col2': 4.}\n])\n\ndf2 = DataFrame([\n {'col3': 5., 'col4': 6.},\n {'col3': 7., 'col4': 8.},\n {'col3': 9., 'col4': 0.}\n])...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074135375_dataframe_pandas_python.txt
Q: I cannot find a "button onclick" element using Selenium and Python I am automating a process using Selenium and python. Right now, I am trying to click on a button in a webpage (sorry I cannot share the link, since it requires credential to login), but there is no way my code can find this button element. I have t...
I cannot find a "button onclick" element using Selenium and Python
I am automating a process using Selenium and python. Right now, I am trying to click on a button in a webpage (sorry I cannot share the link, since it requires credential to login), but there is no way my code can find this button element. I have tried every selector (by id, css selector, xpath, etc.) and done a lot of...
[ "The element you trying to click is inside an iframe. So, you need to switch driver into the iframe content before accessing elements inside it.\nI can't give you a specific code solution since you didn't share a link to that page, even not all that HTML block. You can see solutions for similar questions here or e...
[ 1 ]
[]
[]
[ "iframe", "python", "selenium", "selenium_webdriver" ]
stackoverflow_0074132465_iframe_python_selenium_selenium_webdriver.txt
Q: How to match text in two different file and extract values So I have two files. One yaml file that contains tibetan words : its meaning. Another csv file that contains only word and it's POStag. As below: yaml file : ད་གདོད: ད་གཟོད་དང་དོན་འདྲ། ད་ཆུ: དངུལ་ཆུ་ཡི་མིང་གཞན། ད་ཕྲུག: དྭ་ཕྲུག་གི་འབྲི་ཚུལ་གཞན། ད་བེར: སྒྲིབ...
How to match text in two different file and extract values
So I have two files. One yaml file that contains tibetan words : its meaning. Another csv file that contains only word and it's POStag. As below: yaml file : ད་གདོད: ད་གཟོད་དང་དོན་འདྲ། ད་ཆུ: དངུལ་ཆུ་ཡི་མིང་གཞན། ད་ཕྲུག: དྭ་ཕྲུག་གི་འབྲི་ཚུལ་གཞན། ད་བེར: སྒྲིབ་བྱེད་དང་རླུང་འགོག་བྱེད་ཀྱི་གླེགས་བུ་ལེབ་མོའི་མིང་། ད་མེ་དུམ་མེ:...
[ "On a functional point of view, you have:\n\na dictionary, meaning here a key: value thing\na list of words to search in that dictionary, and that will produce a record\n\nIf everything can fit in memory, you can first read the yaml file to produce a Python dictionary, and then read the words file, one line at a ti...
[ 3, 2, 1 ]
[]
[]
[ "csv", "python", "python_3.x", "text_extraction", "yaml" ]
stackoverflow_0074135326_csv_python_python_3.x_text_extraction_yaml.txt
Q: AttributeError: 'tuple' object has no attribute 'end' in python Moviepy I am a beginner in python I had this error when I try to write multiple videos for the final video this is the code from moviepy.editor import * # getting video files video_1 = VideoFileClip(r"C:\Users\shakila\PycharmProjects\autovideomerger...
AttributeError: 'tuple' object has no attribute 'end' in python Moviepy
I am a beginner in python I had this error when I try to write multiple videos for the final video this is the code from moviepy.editor import * # getting video files video_1 = VideoFileClip(r"C:\Users\shakila\PycharmProjects\autovideomerger\data\samples\inputs\1.mp4").fx(vfx.fadein,3).fx(vfx.fadeout,3) video_2 = Vid...
[ "I fixed it!\nI'm trying to use .ts video files to merge the video, that's why that happens when I use only mp4 it works\n" ]
[ 0 ]
[]
[]
[ "moviepy", "python" ]
stackoverflow_0074119527_moviepy_python.txt
Q: Dataframe - Datetime, get cumulated sum of previous day I have a dataframe with the following columns: datetime: HH:MM:SS (not continuous, there are some missing days) date: ['datetime'].dt.date X = various values X_daily_cum = df.groupby(['date']).X.cumsum() So Xcum is the cumulated sum of X but grouped per day, ...
Dataframe - Datetime, get cumulated sum of previous day
I have a dataframe with the following columns: datetime: HH:MM:SS (not continuous, there are some missing days) date: ['datetime'].dt.date X = various values X_daily_cum = df.groupby(['date']).X.cumsum() So Xcum is the cumulated sum of X but grouped per day, it's reset every day. Code to reproduce: import pandas as pd...
[ "Use Series.duplicated with Series.mask for set missing values to all values without last per dates, then shifting values and forward filling missing values:\ndf['last_day_cum_value'] = (df['X_daily_cum'].mask(df['date'].duplicated(keep='last'))\n .shift()\n ...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074135554_dataframe_pandas_python.txt
Q: z3 python How select element in Array and store to file How create array of integer and show all array with this same element A = [0..4,0..4,0..4] i need print to screen each: [0,0,0,0] and [1,1,1,1] and .... [4,4,4,4] from z3 import * #A = [ Int('a%s' % i) for i in range(4) ] A = IntVector('a', 4...
z3 python How select element in Array and store to file
How create array of integer and show all array with this same element A = [0..4,0..4,0..4] i need print to screen each: [0,0,0,0] and [1,1,1,1] and .... [4,4,4,4] from z3 import * #A = [ Int('a%s' % i) for i in range(4) ] A = IntVector('a', 4) print( 'A = ', A ) i = Int('i'); j = Int('j') ...
[ "It isn't quite clear to me what you're trying to achieve. Do you want to generate all length-4 lists with same elements between 0 and 4? There could be many ways to encode that in z3; here's one approach:\nfrom z3 import *\n\nA = Ints('a b c d')\n\ns = Solver()\n\nfor a in A[1:]:\n s.add(A[0] == a)\n\ns.add(A[0] ...
[ 1 ]
[]
[]
[ "python", "z3", "z3py" ]
stackoverflow_0074130281_python_z3_z3py.txt
Q: Solana listen for new transactions on certain wallet (with Solana.py) I need to listen for new transactions(solana transfers) on a certain wallet, from python code from these transactions I need to take the sender's wallet and how many solans were transferred also i need to fetch transactions(solana transfers) fro...
Solana listen for new transactions on certain wallet (with Solana.py)
I need to listen for new transactions(solana transfers) on a certain wallet, from python code from these transactions I need to take the sender's wallet and how many solans were transferred also i need to fetch transactions(solana transfers) from certain wallet all this i need for implement payment by solana(in my rea...
[ "A possible solution would be to look at the most recent Block with a combination of getBlockHeight and getBlock and check for all the transactions in there.\nTo improve this, the script could only iterate over the block when detecting a change in getBalance on the Public Key of your wallet.\n\nI'm working on a min...
[ 1 ]
[]
[]
[ "payment", "python", "solana", "solana_py" ]
stackoverflow_0074020555_payment_python_solana_solana_py.txt
Q: How can I let my code send messages simultaneously? I'm trying to do UDP socket programming in Python, and I want both the client and the server to be able to send messages without the need to wait for the other party to send a message first. Here is my server code: import socket sock=socket.socket(socket.AF_INET...
How can I let my code send messages simultaneously?
I'm trying to do UDP socket programming in Python, and I want both the client and the server to be able to send messages without the need to wait for the other party to send a message first. Here is my server code: import socket sock=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) sock.bind(('127.0.0.1',12345)) while...
[ "You need to create two functions to handle listening and sending.\nThen you start them as threads so they run in parallel.\nEach function has its own loop. The receive thread waits for messages and the send thread waits for user input\ndef client_receive():\n while True:\n data,addr=client_socket.recvfrom(4096...
[ 0 ]
[]
[]
[ "python", "sockets", "udp" ]
stackoverflow_0074135163_python_sockets_udp.txt
Q: Evaluate multiple boolean columns I wonder if there is smart, pythonic way to evaluate multiple boolean columns in a dataframe at the same time. Based on the boolean mask of multiple columns (only one column per row contains a true), I want to assign a string value (in the following example, first_true, second_tru...
Evaluate multiple boolean columns
I wonder if there is smart, pythonic way to evaluate multiple boolean columns in a dataframe at the same time. Based on the boolean mask of multiple columns (only one column per row contains a true), I want to assign a string value (in the following example, first_true, second_true, or third_true - depending on which c...
[ "Use DataFrame.dot with mapping columns names:\ndf = df.dot(df.columns.map({'b1':'first_true',\n 'b2':'second_true',\n 'b3':'third_true'}))\nprint(df)\n0 first_true\n1 second_true\n2 third_true\ndtype: object\n\nIf need dynamic solution use inflect fo...
[ 1 ]
[]
[]
[ "boolean", "dataframe", "pandas", "python" ]
stackoverflow_0074135624_boolean_dataframe_pandas_python.txt
Q: Connect Celery to AWS SQS I have a problem connecting Celery to AWS SQS service. My arhitecture looks like this: First service is API that uses celery.send_task() methods, then I have 2 SQS queues, and after that I have two celery workers, and each worker(separate containers) takes elements from specific queue. Fo...
Connect Celery to AWS SQS
I have a problem connecting Celery to AWS SQS service. My arhitecture looks like this: First service is API that uses celery.send_task() methods, then I have 2 SQS queues, and after that I have two celery workers, and each worker(separate containers) takes elements from specific queue. For now everything is LOCAL excep...
[ "I found out that\nqueue_1': {\n 'url': <sqs url/queue_1>,\n 'access_key_id': ...,\n 'secret_access_key': ...,\n }\n...\n\ndoes not work for me. I wound up using this\nqueue_1': {\n 'url': get_aws_sqs(queue_name)\n ...
[ 0 ]
[]
[]
[ "amazon_sqs", "amazon_web_services", "celery", "kombu", "python" ]
stackoverflow_0074068093_amazon_sqs_amazon_web_services_celery_kombu_python.txt
Q: Pandas read_csv produces unexpected behavior, why? I've got a large tab-separated file and am trying to load it using import pandas as pd df = pd.read_csv(..., sep="\t") however, the process crashes with the error being pandas.errors.ParserError: Error tokenizing data. C error: Expected 8 fields in line 1743925,...
Pandas read_csv produces unexpected behavior, why?
I've got a large tab-separated file and am trying to load it using import pandas as pd df = pd.read_csv(..., sep="\t") however, the process crashes with the error being pandas.errors.ParserError: Error tokenizing data. C error: Expected 8 fields in line 1743925, saw 12 Nothing apparent wrong with that particular lin...
[ "Fixed the issue. Turns out the problem was a different quoting on csv export and read. The issue was solved by matching quoting on read_csv with quoting on the to_csv which created the loaded file. I assume some tabs and newlines were thought to be parts of string literals because of this, hence the assumption of ...
[ 0 ]
[]
[]
[ "csv", "pandas", "python" ]
stackoverflow_0074124140_csv_pandas_python.txt
Q: Calling Functions in an Executable from Python I need to create an executable with pyinstaller that contains many functions. How can I call these functions with arguments from Python? My current approach is to use conditionals based on optional arguments. For example (untested): #math_app.py import argparse parser...
Calling Functions in an Executable from Python
I need to create an executable with pyinstaller that contains many functions. How can I call these functions with arguments from Python? My current approach is to use conditionals based on optional arguments. For example (untested): #math_app.py import argparse parser = argparse.ArgumentParser() parser.add_argument("-a...
[]
[]
[ "Well,thats a job for the front end (GUI).You can spend a little time searching on the topic since you made a decision to make an executable.Since your project seems kinda small you can use a library like Tkinker(already available in python) or PyQt (for more advanced things) to make an interface so the user can pr...
[ -1 ]
[ "command_line", "exe", "pyinstaller", "python", "subprocess" ]
stackoverflow_0074135663_command_line_exe_pyinstaller_python_subprocess.txt
Q: Django getting error exceptions must derive from BaseException Info: I want to upload files using Uppy in frontend and django-tus as backend for file processing. I am getting error TypeError: exceptions must derive from BaseException. Traceback Internal Server Error: /tus/upload/6393bfe5-277e-4c68-b9af-c0394be796b...
Django getting error exceptions must derive from BaseException
Info: I want to upload files using Uppy in frontend and django-tus as backend for file processing. I am getting error TypeError: exceptions must derive from BaseException. Traceback Internal Server Error: /tus/upload/6393bfe5-277e-4c68-b9af-c0394be796b9 Traceback (most recent call last): File "/django_tus/tusfile.py"...
[ "EDIT: Our pull request has now fixed this error.\nThe django-tus attempts in case of 404 error raise in line 60 TusResponse which does not however inherit from exception.\nThis is an error of the library. It has not been updated in 2 years and according to the @torek BaseException inheritance was not previously en...
[ 1 ]
[]
[]
[ "django", "python", "python_3.x", "uppy" ]
stackoverflow_0073260707_django_python_python_3.x_uppy.txt
Q: Reading multiple images in python using only matplotlib and cv2 I want to read multiple images from a folder and display them in my jupyter notebook. to achieve this i need to use for loop in combination with matplotlib and cv2 packages. i have tried to read the images using matplotlib and cv2 but the code seems r...
Reading multiple images in python using only matplotlib and cv2
I want to read multiple images from a folder and display them in my jupyter notebook. to achieve this i need to use for loop in combination with matplotlib and cv2 packages. i have tried to read the images using matplotlib and cv2 but the code seems repetitive and i have had difficulty in making a simple and more short...
[ "you can use os library to get the all images in a folder.\nimport cv2\nfrom matplotlib import pyplot as plt\nimport os\n\n\ndef bike_images():\n ### creating a function to generate different bike images that a customer/ or a bike rider\n\n ## creating a figure object\n\n fig = plt.figure(figsize=(10, 7))\...
[ 0 ]
[]
[]
[ "image_processing", "matplotlib", "opencv", "python" ]
stackoverflow_0074135110_image_processing_matplotlib_opencv_python.txt
Q: Trouble in Clicking on Log in Google Button of Pop Up Menu Playwright Python I am having trouble shifting my cursor from back page to front page using python playwright. I already write a script for that which does not seems like work for me as mentioned in the documentation. I have also attached the script below ...
Trouble in Clicking on Log in Google Button of Pop Up Menu Playwright Python
I am having trouble shifting my cursor from back page to front page using python playwright. I already write a script for that which does not seems like work for me as mentioned in the documentation. I have also attached the script below for your ease. Kindly suggest me solution for how I can click on this pop up menu...
[ "Playwright has no method get_by_role.\nTry this:\npage.locator('link[name=\"Log in\"]').click()\n\nYou can give the locator method any CSS or Xpath expression.\n" ]
[ 1 ]
[]
[]
[ "automation", "browser", "playwright", "python", "selenium" ]
stackoverflow_0074134603_automation_browser_playwright_python_selenium.txt
Q: Replacing char to date I have a dataframe in which one column is of date format type but in some rows, it is written as just SUB instead of date format, how to change it to one particular date(Let us say all SUB be replaced with 28-09-2020) using python? A: You can use pd.to_datetime and convert error rows to Na...
Replacing char to date
I have a dataframe in which one column is of date format type but in some rows, it is written as just SUB instead of date format, how to change it to one particular date(Let us say all SUB be replaced with 28-09-2020) using python?
[ "You can use pd.to_datetime and convert error rows to NaT then fill those na values with some default values like this\nimport pandas as pd\ndf = pd.DataFrame({\"cola\": [\"10-10-2022\", \"11-11-2022\", \"sub\"]})\ndf[\"cola\"] = pd.to_datetime(df[\"cola\"], errors=\"coerce\").fillna(\"01-01-1976\") # use your def...
[ 0 ]
[]
[]
[ "excel", "python" ]
stackoverflow_0074135428_excel_python.txt
Q: Can R^2 Metric be used for rolling forecasts? I forecasted some pricing data and evaluated it using a few of the standard metrics (MSE,MAE,R^2). The forecasting was done using fbprophet and a rolling ARIMA forecast. The graph of the forecast is shown here: We can see that the rolling ARIMA follows the test data r...
Can R^2 Metric be used for rolling forecasts?
I forecasted some pricing data and evaluated it using a few of the standard metrics (MSE,MAE,R^2). The forecasting was done using fbprophet and a rolling ARIMA forecast. The graph of the forecast is shown here: We can see that the rolling ARIMA follows the test data really well (maybe too well? Overfitting?) whereas p...
[ "I think calculating the error metrics for both the train and test sets should give a better overview of what is happening\n" ]
[ 0 ]
[]
[]
[ "arima", "facebook_prophet", "forecasting", "metrics", "python" ]
stackoverflow_0071501984_arima_facebook_prophet_forecasting_metrics_python.txt
Q: Cannot import name 'CRS' from 'pyproj' for using the osmnx library I have used a fresh anaconda install to download and install all the required modules for osnmx library but I got the following error: A: I am the developer of OSMnx. There is a growing amount of misinformation and confusion in this thread, so I ...
Cannot import name 'CRS' from 'pyproj' for using the osmnx library
I have used a fresh anaconda install to download and install all the required modules for osnmx library but I got the following error:
[ "I am the developer of OSMnx. There is a growing amount of misinformation and confusion in this thread, so I will give you a definitive answer.\nJust follow the documented installation instructions to install the latest release of OSMnx:\nconda config --prepend channels conda-forge\nconda create -n ox --strict-chan...
[ 11, 6, 0, 0 ]
[]
[]
[ "anaconda", "data_science", "osmnx", "pyproj", "python" ]
stackoverflow_0059658167_anaconda_data_science_osmnx_pyproj_python.txt
Q: Calculating RMSE for Prophet Model in Python I'm new to learning python, and I'm creating a time series model which predicts total sales each month using the Prophet model. I am needing help getting the RMSE of my model! Thanks! from fbprophet import Prophet #Creating Dataframe# proph = train.groupby(['date_block_...
Calculating RMSE for Prophet Model in Python
I'm new to learning python, and I'm creating a time series model which predicts total sales each month using the Prophet model. I am needing help getting the RMSE of my model! Thanks! from fbprophet import Prophet #Creating Dataframe# proph = train.groupby(['date_block_num'])[ 'item_cnt_day'].sum() proph.index=pd.date_...
[ "I do not know if its still relevant. You will need to prepare a DataFrame that holds the actual values, lets call it df_actual. Then the following will calculate RMSE for you: \nse = np.square(forecast.loc[:, 'yhat'] - df_actual)\nmse = np.mean(se)\nrmse = np.sqrt(mse)\n\nHope this helps.\n", "You can also use c...
[ 1, 0 ]
[]
[]
[ "facebook_prophet", "forecast", "python", "statsmodels", "time_series" ]
stackoverflow_0051063282_facebook_prophet_forecast_python_statsmodels_time_series.txt
Q: Split a dataframe based on values in a column I want to split a dataframe into quartiles of a specific column. I have data from 800 companies. One row displays a specific score which ranges from 0 to 100. I want to split the dataframe in 4 groups (quartiles) with same size (Q1 to Q4, Q4 should contain the companie...
Split a dataframe based on values in a column
I want to split a dataframe into quartiles of a specific column. I have data from 800 companies. One row displays a specific score which ranges from 0 to 100. I want to split the dataframe in 4 groups (quartiles) with same size (Q1 to Q4, Q4 should contain the companies with the highest scores). So each group should co...
[ "Suppose your dataframe sorted by some values already.\nimport numpy as np\nimport pandas as pd\n\nwriter = pd.ExcelWriter('splited_df.xlsx', engine='xlsxwriter')\n\n# determine you want to divide into how many parts\nn_groups= 4\n\n# make the dataframe slicing list\nseparator= list(map(int, np.linspace(0,len(df1),...
[ 0, 0, 0, 0 ]
[]
[]
[ "dataset", "finance", "numpy", "pandas", "python" ]
stackoverflow_0074135490_dataset_finance_numpy_pandas_python.txt
Q: How to get weather data from site? I'm not able to get the Dew_Point and Wind Data from the site https://weather.gc.ca/city/pages/ab-52_metric_e.html import requests from lxml import html # Get the html page resp=requests.get("https://weather.gc.ca/city/pages/ab-52_metric_e.html") # Build h...
How to get weather data from site?
I'm not able to get the Dew_Point and Wind Data from the site https://weather.gc.ca/city/pages/ab-52_metric_e.html import requests from lxml import html # Get the html page resp=requests.get("https://weather.gc.ca/city/pages/ab-52_metric_e.html") # Build html tree html_tree=html.fromstri...
[ "The best approach is to use BeautifulSoup to parse the page.\nThis is what you want:\nimport requests\nfrom bs4 import BeautifulSoup\n\nresp = requests.get(\"https://weather.gc.ca/city/pages/ab-52_metric_e.html\").content\n\nsoup = BeautifulSoup(resp, \"html.parser\")\n\nall_dt = soup.find_all(\"dt\")\n\n#if you w...
[ 2, 0 ]
[]
[]
[ "html", "lxml", "python" ]
stackoverflow_0074048864_html_lxml_python.txt
Q: remove trailing zeros in float representation python Using the f-string floating formatting I get the following results: f"{1.34 :.2f}" # 1.34 f"{1.30 :.2f}" # 1.30 f"{1.00 :.2f}" # 1.00 What I want however is to remove all trailing zeros: f"{1.34 :.2f}" # 1.34 f"{1.30 :.2f}" # 1.3 f"{1.00 :.2f}" # 1 Using...
remove trailing zeros in float representation python
Using the f-string floating formatting I get the following results: f"{1.34 :.2f}" # 1.34 f"{1.30 :.2f}" # 1.30 f"{1.00 :.2f}" # 1.00 What I want however is to remove all trailing zeros: f"{1.34 :.2f}" # 1.34 f"{1.30 :.2f}" # 1.3 f"{1.00 :.2f}" # 1 Using complex functions I can strip zeros and possibly the deci...
[ "You can try this\nmy_float = 69.880\n\nresult = f'{str(my_float).rstrip(\"0\").rstrip(\".\") if \".\" in str(my_float) else my_float}'\n\nprint(result)\n\n" ]
[ 0 ]
[]
[]
[ "f_string", "formatting", "python" ]
stackoverflow_0074135533_f_string_formatting_python.txt
Q: Python logging exception I'm currently writing a wrapper class. I want to be able to log exceptions properly but allow calling methods to be aware of exceptions which occur. My class looks like this: import logging log = logging.getLogger('module') class MyAPIWrapper(library.APIClass): def __init__(self): ...
Python logging exception
I'm currently writing a wrapper class. I want to be able to log exceptions properly but allow calling methods to be aware of exceptions which occur. My class looks like this: import logging log = logging.getLogger('module') class MyAPIWrapper(library.APIClass): def __init__(self): self.log = logging.getL...
[ "There is nothing wrong with catching to log. However, I'd recommend:\n try:\n response = self.call_api_method()\n except APIException, e: # or 'as e' depending on your Python version\n self.log.exception('Oh noes!')\n raise #Throw exception again so calling code knows it happened\n e...
[ 37, 11, 2 ]
[]
[]
[ "design_patterns", "exception", "logging", "python" ]
stackoverflow_0007003034_design_patterns_exception_logging_python.txt
Q: Run a pytest test flow with differest starting data while running each test case basically if I have test cases written like class TestClass: data = "a" def test_1(self): TestClass.results = function1(TestClass.data) def test_2(self): function1(TestClass.results[1]) def test_3(self)...
Run a pytest test flow with differest starting data while running each test case
basically if I have test cases written like class TestClass: data = "a" def test_1(self): TestClass.results = function1(TestClass.data) def test_2(self): function1(TestClass.results[1]) def test_3(self): function1(TestClass.results[2]) def test_4(self): function1(Test...
[ "You can use @pytest.mark.parametrize in class level\n@pytest.mark.parametrize('data', ['a', 'b', 'c'])\nclass TestClass:\n\n def test_1(self, data):\n function1(data)\n\n def test_2(self, data):\n function1(data)\n\n def test_3(self, data):\n function1(data)\n\n def test_4(self, da...
[ 1 ]
[]
[]
[ "pytest", "python" ]
stackoverflow_0074135913_pytest_python.txt
Q: How to create a web-scraper to retrieve data from a given site I need to build a web scraper using BeautifulSoup to extract movie data such as url, movie name, introduction from imdb top 250 movies web page and write the extracted data into an excel file. A: import requests import lxml from bs4 import BeautifulS...
How to create a web-scraper to retrieve data from a given site
I need to build a web scraper using BeautifulSoup to extract movie data such as url, movie name, introduction from imdb top 250 movies web page and write the extracted data into an excel file.
[ "import requests\nimport lxml\nfrom bs4 import BeautifulSoup\nfrom xlwt import *\n\n#creating the worksheet table\nworkbook = Workbook(encoding = 'utf-8')\ntable = workbook.add_sheet('data')\ntable.write(0, 0, 'Number')\ntable.write(0, 1, 'movie_url')\ntable.write(0, 2, 'movie_name')\ntable.write(0, 3, 'movie_intro...
[ 1 ]
[]
[]
[ "python", "web_crawler", "web_scraping" ]
stackoverflow_0074135919_python_web_crawler_web_scraping.txt
Q: Using transform to filter dataframe based on groupby information I want to filter out id's that not appear 3 times in the dataset below. I thought of using groupby and transform('size'), but that doesn't work. Why? data = pd.DataFrame({'id':[0,0,0, 1,1,1, 2,2, 3,3,3, 4, 4], 'info':[23,22,12,12,14,23,...
Using transform to filter dataframe based on groupby information
I want to filter out id's that not appear 3 times in the dataset below. I thought of using groupby and transform('size'), but that doesn't work. Why? data = pd.DataFrame({'id':[0,0,0, 1,1,1, 2,2, 3,3,3, 4, 4], 'info':[23,22,12,12,14,23,11,2,98,76,46,341,12]}) data[data.groupby(['id']).transform('size')==...
[ "Specify column after groupby:\ndf = data[data.groupby(['id'])['id'].transform('size')==3]\n\nAlternative:\ndf = data[data['id'].map(data['id'].value_counts())==3]\n\n" ]
[ 3 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074135999_pandas_python.txt
Q: dropdown menu not auto populating find_element_by_xpath maybe a dumb question. I'm not getting in the dropdown menu find_element_by_xpath. Only getting find_element and find_elements. A: Your code snippet isn't enough in any way. With that in mind: Please be aware that the Xpath locator is very finnicky. It depe...
dropdown menu not auto populating find_element_by_xpath
maybe a dumb question. I'm not getting in the dropdown menu find_element_by_xpath. Only getting find_element and find_elements.
[ "Your code snippet isn't enough in any way.\nWith that in mind:\nPlease be aware that the Xpath locator is very finnicky.\nIt depends on the HTML you see and selenium loads a slightly different version of the HTML breaking the xpath.\n /html//div/div/div/div[1]/div/a/img\n\nIs unlikely to ever work, prone to breaki...
[ 0 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0074132873_python_selenium.txt
Q: Trying to get a value from a JSON in python I am trying to access a value in a json file using python. In the imgur link, the value I am trying to access is the "NUM" nested in "args". My main logic is reading in the JSON file, then using pandas to normalize the json.I have tried using .loc to try and find 'args' ...
Trying to get a value from a JSON in python
I am trying to access a value in a json file using python. In the imgur link, the value I am trying to access is the "NUM" nested in "args". My main logic is reading in the JSON file, then using pandas to normalize the json.I have tried using .loc to try and find 'args' but I need help with another way or option. [1]: ...
[ "This is how you can access value of NUM:\nimport json\n\nfile = open('data.json')\n\ndata = json.load(file)\n\nNUM = data[1][\"args\"][\"NUM\"]\n\n# NUM = 20.0\n\nfile.close()\n\n", "The JSON structure appears to be a list of dictionaries. Those dictionaries may or may not have a 'args' key. The value associated...
[ 0, 0 ]
[]
[]
[ "json", "python" ]
stackoverflow_0074135060_json_python.txt
Q: Scraping dynamic website with unchanging urls I need to scrape data of all dental clinis. What's the next step? Can someone help me out? I have now 2 options of code: 1, Here i don't know how to set 'for loop' for all pages url = "https://www.dent.cz/zubni-lekari" s = HTMLSession() r = s.get(url) r.html.render(sl...
Scraping dynamic website with unchanging urls
I need to scrape data of all dental clinis. What's the next step? Can someone help me out? I have now 2 options of code: 1, Here i don't know how to set 'for loop' for all pages url = "https://www.dent.cz/zubni-lekari" s = HTMLSession() r = s.get(url) r.html.render(sleep=1) for x in range(1, 31): clinic = r.html...
[ "You just need to change the page number. And extract the information from the json response\napi_url = \"https://is-api.dent.cz/api/v1/web/workplaces\"\n\npayload = {\n \"deleted\": False,\n \"filter\": \"accepts_new_patients=false\",\n \"fulltext\": \"\",\n \"page\": 1, # <--- you...
[ 1 ]
[]
[]
[ "api", "python", "web_scraping", "xpath" ]
stackoverflow_0074135622_api_python_web_scraping_xpath.txt
Q: (Python) calling mutiple my own functions, NameError not defined , on passing output between function I know this kind of the beginner mistake, but I'm not sure how to make change_db_data detect mycol issue on passing value mycol between function (ps. mycol means collection in MongoDB ) error : Traceback (most r...
(Python) calling mutiple my own functions, NameError not defined , on passing output between function
I know this kind of the beginner mistake, but I'm not sure how to make change_db_data detect mycol issue on passing value mycol between function (ps. mycol means collection in MongoDB ) error : Traceback (most recent call last): File "C:\Users\chuan\OneDrive\Desktop\10.20_connect_mongoD_(Query, Delete)\main.py", line...
[ "You're not passing 'mycol' into your change_db_data() function.\nchange_db_data(myquery_json, newvalues_json, one_or_many_bool, mycol)\n\ndef change_db_data(myquery_json, newvalues_json, one_or_many_bool, mycol):\n\n" ]
[ 0 ]
[]
[]
[ "mongodb", "python", "python_3.x" ]
stackoverflow_0074135982_mongodb_python_python_3.x.txt
Q: My selenium code throwing error while using opera browser for the first time I am using opera version=91.0.4516.16 and operadriver version = 105.0.5195.102. I'm unable to opera browser with the simplest code also which is: from selenium import webdriver from selenium.webdriver.opera.options import Options s = Opt...
My selenium code throwing error while using opera browser for the first time
I am using opera version=91.0.4516.16 and operadriver version = 105.0.5195.102. I'm unable to opera browser with the simplest code also which is: from selenium import webdriver from selenium.webdriver.opera.options import Options s = Options() s.binary_location = r'C:\Users\Admin\AppData\Local\Programs\Opera\launcher....
[ "Solution\nWith selenium==4.2.0\nYou can solve your issue.\nAlso one more thing, the reason why we can't use opera in our latest version of selenium is that opera don't follow the rules of w3 that's why it was removed by selenium\nfrom webdriver_manager.opera import OperaDriverManager\nfrom selenium import webdrive...
[ 1, 0 ]
[]
[]
[ "opera", "operadriver", "python", "selenium", "selenium_webdriver" ]
stackoverflow_0073772684_opera_operadriver_python_selenium_selenium_webdriver.txt
Q: String format with variable number of inserts I have a string that contains an arbitrary number of inserts in the form of variables names that will be in the global namespace. Please note the future tense - the variables do not yet exist at the moment when the formatted string is created. txt = "{x} --- {y}" # cou...
String format with variable number of inserts
I have a string that contains an arbitrary number of inserts in the form of variables names that will be in the global namespace. Please note the future tense - the variables do not yet exist at the moment when the formatted string is created. txt = "{x} --- {y}" # could very well be "{z} --- {x} --- {w}" x = "A" y = "...
[ "Two options that come to mind:\n\nBrute force f-string conversion, because every body loves eval:\n\ntxt = eval(f\"f'{txt}'\")\n\nor, a little more cryptic, and as kindall proposed:\n\nformat the complete available global namespace into your text by unpacking globals() into your string's format method.\n\ntxt.form...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074126484_python.txt
Q: How to get the mean and median of derived value I have a DataFrame of houses in different towns: data = [ ['Oxford', 2016, True], ['Oxford', 2016, True], ['Oxford', 2018, False], ['Cambridge', 2016, False], ['Cambridge', 2016, True], ['Brighton', 2019, True], ] df = pd.DataFrame(data, columns=['town', ...
How to get the mean and median of derived value
I have a DataFrame of houses in different towns: data = [ ['Oxford', 2016, True], ['Oxford', 2016, True], ['Oxford', 2018, False], ['Cambridge', 2016, False], ['Cambridge', 2016, True], ['Brighton', 2019, True], ] df = pd.DataFrame(data, columns=['town', 'year_built', 'is_detached']) I want to get the mean...
[ "Use value_counts to get the number of houses per town, and then agg with 'mean' and 'median':\ndf['town'].value_counts().agg(['mean', 'median'])\n\nOutput:\nmean 2.0\nmedian 2.0\nName: town, dtype: float64\n\n" ]
[ 2 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074136088_pandas_python.txt
Q: engine.runandWait() get stuck My script just stop and get stuck after engine.runandWait()... If someone has any idea of how to make it continue I would appreciate ! It seems that the answer isn't in the script itself because I tried scripts that are super simple... I also tried to uninstall and reinstall portaudio...
engine.runandWait() get stuck
My script just stop and get stuck after engine.runandWait()... If someone has any idea of how to make it continue I would appreciate ! It seems that the answer isn't in the script itself because I tried scripts that are super simple... I also tried to uninstall and reinstall portaudio, pyaudio and pyttsx3 Here is my sc...
[ "In the def talk section, you can remove the first line and in the while True statement, delete if run == False, and add a elif statement to the take command sections saying elif 'thank you' in command: exit(the name of your assistant). Try it\n", "Here is a short pyttsx testing program.\nSave it as 'pyttsx_test....
[ 0, 0, 0, 0 ]
[]
[]
[ "python", "python_3.x", "pyttsx3" ]
stackoverflow_0066075838_python_python_3.x_pyttsx3.txt
Q: ImportError: No module named 'settings' I have two versions of python installed 2.7 and 3.4 and created a virtualenv and assigned python34 to that new environment. When I activate that virtualenv and run python manage.py runserver then I get the following output. (casenv) C:\pyprojects\focus\site>python manage.py ...
ImportError: No module named 'settings'
I have two versions of python installed 2.7 and 3.4 and created a virtualenv and assigned python34 to that new environment. When I activate that virtualenv and run python manage.py runserver then I get the following output. (casenv) C:\pyprojects\focus\site>python manage.py runserver Traceback (most recent call last): ...
[ "try:\nfrom .settings import Hasher\n\n", "Go to your directory and select setting in the directory and open it with pycharm. When it open right click the tab and and click open in Terminal then run the code. It works\n" ]
[ 4, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0045522004_django_python.txt
Q: "RuntimeError: Working outside of application context" in Flask I am learning flask using this tutorial. When I try to execute db.create_all() in the interactive python environment in VS Code, I get Working outside of application context error. According to this solution, I have done everything correct. I am not a...
"RuntimeError: Working outside of application context" in Flask
I am learning flask using this tutorial. When I try to execute db.create_all() in the interactive python environment in VS Code, I get Working outside of application context error. According to this solution, I have done everything correct. I am not able to find the error in my code. Can someone please help me? Followi...
[ "In this case you need to push application context.\n# debug.py\nfrom flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\n# change sqlalchemy log level\nimport logging\nlogging.basicConfig()\nlogging.getLogger('sqlalchemy.engine').setLevel(logging.DEBUG)\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DAT...
[ 0 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0074135421_flask_python.txt
Q: Can't run command "pip install mariadb" This is what I get when I run the command pip install mariadb: Defaulting to user installation because normal site-packages is not writeable Collecting mariadb Using cached mariadb-1.1.4.zip (97 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-...
Can't run command "pip install mariadb"
This is what I get when I run the command pip install mariadb: Defaulting to user installation because normal site-packages is not writeable Collecting mariadb Using cached mariadb-1.1.4.zip (97 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not...
[ "Check the installed version of MariaDB Connector/C. Required version is > 3.2.4.\nmariadb_config --cc_version\nIf the installed version is too old, you have to upgrade Connector/C.\nFrom Installation FAQ:\nThe previously installed version of MariaDB Connector/C is too old and cannot be used for the MariaDB Connect...
[ 2, 0 ]
[]
[]
[ "mariadb", "pip", "python" ]
stackoverflow_0074131559_mariadb_pip_python.txt
Q: Suppress RasterIO Warning. Warning 1: TIFFReadDirectory I've been having problems with the error message Warning 1: TIFFReadDirectory:Sum of Photometric type-related color channels and ExtraSamples doesn't match SamplesPerPixel. Defining non-color channels as ExtraSamples. This error message occurs when I open a ....
Suppress RasterIO Warning. Warning 1: TIFFReadDirectory
I've been having problems with the error message Warning 1: TIFFReadDirectory:Sum of Photometric type-related color channels and ExtraSamples doesn't match SamplesPerPixel. Defining non-color channels as ExtraSamples. This error message occurs when I open a .tiff file with wrong tiff tags, in my case the tags: PHOTOME...
[ "Updated Answer\nAfter a lot of hunting around, and trying to use TIFFSetWarningHandler() as described here, it transpires that rasterio uses its own, built-in, stripped-down version of gdal - unless you build from source. That gives rise to the following.\nMethod 1\nTell rasterio's GDAL to quiet warnings:\n#!/usr/...
[ 2 ]
[]
[]
[ "python", "rasterio", "suppress_warnings", "tiff" ]
stackoverflow_0074089170_python_rasterio_suppress_warnings_tiff.txt
Q: Django: set default value for new model field which has unique=True There is a custom user model which inherits AbstractUser in Django. The model has username = None, below is the model: class User(AbstractUser): username = None email = models.EmailField(_("Email address"), unique=True) USERNAME_FIELD...
Django: set default value for new model field which has unique=True
There is a custom user model which inherits AbstractUser in Django. The model has username = None, below is the model: class User(AbstractUser): username = None email = models.EmailField(_("Email address"), unique=True) USERNAME_FIELD = "email" I want to remove username = None so that we can save username...
[ "You can use a custom migration. When creating your migration, provide a default value, then edit the generated migration with something like this:\nimport django.contrib.auth.models\nfrom django.db import migrations, models\nimport users.models\n\n\ndef forwards_func(apps, schema_editor):\n User = apps.get_mode...
[ 3, 1, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0074135368_django_django_models_python.txt
Q: Python combine/group by dictionaries in a list by a value in the dict I have this data : [ {'name': 'INV/2021/0913', 'invoice_date': datetime.date(2021, 3, 12), 'qty_total': 5.0}, {'name': 'INV/2021/0965', 'invoice_date': datetime.date(2021, 3, 14), 'qty_total': 6.0}, {'name': 'INV/2021/0966', 'invoi...
Python combine/group by dictionaries in a list by a value in the dict
I have this data : [ {'name': 'INV/2021/0913', 'invoice_date': datetime.date(2021, 3, 12), 'qty_total': 5.0}, {'name': 'INV/2021/0965', 'invoice_date': datetime.date(2021, 3, 14), 'qty_total': 6.0}, {'name': 'INV/2021/0966', 'invoice_date': datetime.date(2021, 3, 14), 'qty_total': 7.0}, {'name': 'INV...
[ "use itertools.groupby\nfrom datetime import datetime\nfrom itertools import groupby\n\nl = [\n {'name': 'INV/2021/0913', 'invoice_date': datetime(2021, 3, 12).date(), 'qty_total': 5.0}, \n {'name': 'INV/2021/0965', 'invoice_date': datetime(2021, 3, 14).date(), 'qty_total': 6.0}, \n {'name': 'INV/2021/0966...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074135916_python.txt
Q: Python: To combine lines of a text file and skip certain records I have an input file like below (please note that there may/may not be blank lines in the file 11111*Author Name 22222*Date 11111 01 Var-1 11111 02 Var-2 11111 02 Var-3 Rules to be used: If asterisk(*) is present at position # 6 of a record th...
Python: To combine lines of a text file and skip certain records
I have an input file like below (please note that there may/may not be blank lines in the file 11111*Author Name 22222*Date 11111 01 Var-1 11111 02 Var-2 11111 02 Var-3 Rules to be used: If asterisk(*) is present at position # 6 of a record then skip the record. First 6 bytes are sequence number which can be spa...
[ "Assuming you just want to print them one after another (they will still be on separate lines)\nwith open(\"D:/Desktop/Files/Myfile.txt\",\"r\") as file_in:\n for line in file_in:\n if line == \"\\n\": # skip empty lines\n continue \n if line[5] == \"*\": #skip if asterix at 6th position...
[ 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074131083_python.txt
Q: django form isn't inserting values from views.py file I'm trying to insert values into a Django Database using both HTML and a generated value from views.py This is my views.py def NewPassword(request): if request.method == "POST": if request.POST.get('app_name') and request.POST.get('url') and reque...
django form isn't inserting values from views.py file
I'm trying to insert values into a Django Database using both HTML and a generated value from views.py This is my views.py def NewPassword(request): if request.method == "POST": if request.POST.get('app_name') and request.POST.get('url') and request.POST.get('username') and request.POST.get('email') and ...
[ "Figured out the answer, it was registering as an empty form and views.py had\nform.category = request.POST.get('Category')\n\nwhen it should've had\nform.category = request.POST.get('category')\n\n" ]
[ 1 ]
[]
[]
[ "django", "django_forms", "django_models", "django_views", "python" ]
stackoverflow_0074134323_django_django_forms_django_models_django_views_python.txt
Q: Efficient way of concatenating and grouping pandas dataframes I have around 150 CSV files on the following format: Product Name Cost Manufacturer Country P_0 5 Pfizer Finland P_1 10 BioNTech Sweden P_2 12 Pfizer Denmark P_3 11 J&J Finland Each CSV represents daily data. So the file for the previous date woul...
Efficient way of concatenating and grouping pandas dataframes
I have around 150 CSV files on the following format: Product Name Cost Manufacturer Country P_0 5 Pfizer Finland P_1 10 BioNTech Sweden P_2 12 Pfizer Denmark P_3 11 J&J Finland Each CSV represents daily data. So the file for the previous date would look like: Product Name Cost Manufacturer Country...
[ "Fundamentally your reading approach is fine: as far as I know reading then concatenating the dataframes is the best approach. There are some marginal improvements you can get if you use the usecols and dtype parameters in read_csv but this is ever dependant on what your data looks like:\n\n\n\n\nMethod\nTime\nRela...
[ 0 ]
[]
[]
[ "csv", "pandas", "parallel_processing", "performance", "python" ]
stackoverflow_0074114771_csv_pandas_parallel_processing_performance_python.txt
Q: Typing an unimported module I have a Python package that has an optional [extras] dependency, yet I want to adhere to typing on all methods. The situation is that in my file, I have this class MyClass: def __init__(self, datastore: Datastore): # <- Datastore is azureml.core.Datastore ... def my_...
Typing an unimported module
I have a Python package that has an optional [extras] dependency, yet I want to adhere to typing on all methods. The situation is that in my file, I have this class MyClass: def __init__(self, datastore: Datastore): # <- Datastore is azureml.core.Datastore ... def my_func(self): from azureml....
[ "You can use TYPE_CHECKING:\n\nA special constant that is assumed to be True by 3rd party static type\ncheckers. It is False at runtime.\n\nIt is False at runtime: So it doesn't affect your module's behavior.\nfrom typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n from azureml.core import Datastore\n\n\nclass M...
[ 2, 1 ]
[]
[]
[ "annotations", "python", "python_typing", "type_hinting" ]
stackoverflow_0073383393_annotations_python_python_typing_type_hinting.txt
Q: Validating optional field in marshmallow I have a field in my model which is required in the resource body while creating the resource (POST) and is not passed in the request body(will be passed along with URL) while updating the resource (PUT). I have created my marshmallow model: class DummySchema(): field_1 ...
Validating optional field in marshmallow
I have a field in my model which is required in the resource body while creating the resource (POST) and is not passed in the request body(will be passed along with URL) while updating the resource (PUT). I have created my marshmallow model: class DummySchema(): field_1 = fields.Str(required=True) field_2 = field...
[ "I think I should've read the documentation thoroughly before :(\nI could set a field as partial, so when it'll do validation marshmallow would skip the field\ndata, errors = DummySchema().load({'field_2': 42}, partial=('field_1',))\n\nREF: https://marshmallow.readthedocs.io/en/2.x-line/quickstart.html#validation\n...
[ 3, 0 ]
[]
[]
[ "marshmallow", "python" ]
stackoverflow_0055795258_marshmallow_python.txt
Q: Python list of dictionaries from two lists I have tried to create list of dictionary. In order to map two lists in list of dictionaries. Where: k = ['00-00', '00-01', '00-02', '00-00', '00-01', '00-02'] a = [1.08, 2.89, 3.88, 4.44, 8.88, 9.99] The list of dictionaries must equal: [{'00-00':1.08, '00-01':2.89, '00...
Python list of dictionaries from two lists
I have tried to create list of dictionary. In order to map two lists in list of dictionaries. Where: k = ['00-00', '00-01', '00-02', '00-00', '00-01', '00-02'] a = [1.08, 2.89, 3.88, 4.44, 8.88, 9.99] The list of dictionaries must equal: [{'00-00':1.08, '00-01':2.89, '00-02':3.88}, {'00-00':4.44, '00-01':8.88, '00-02'...
[ "try:\n[dict(zip(k,a[0:3])),dict(zip(k,a[3:]))]\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074136327_python.txt
Q: How to extract only the desired text using for loop So I have list of Tibetan words with their POS tag as shown below: ད་གདོད DET ད་གཟོད PART ད་ཏྲིག NO_POS ད་དུང PART ད་དྲག NOUN How can I strip out these POS tags and output only the below: ད་གདོད ད་གཟོད ད་ཏྲིག ད་དུང ད་དྲག A: [x.split(" ")[0] for x in list_] ...
How to extract only the desired text using for loop
So I have list of Tibetan words with their POS tag as shown below: ད་གདོད DET ད་གཟོད PART ད་ཏྲིག NO_POS ད་དུང PART ད་དྲག NOUN How can I strip out these POS tags and output only the below: ད་གདོད ད་གཟོད ད་ཏྲིག ད་དུང ད་དྲག
[ "[x.split(\" \")[0] for x in list_]\n\nreturns\n['ད་གདོད', 'ད་གཟོད', 'ད་ཏྲིག', 'ད་དུང', 'ད་དྲག']\n\nif you want printing then this:\nfor x in list_:\n print(x.split(\" \")[0])\n\nprints out:\nད་གདོད\nད་གཟོད\nད་ཏྲིག\nད་དུང\nད་དྲག\n\n" ]
[ 2 ]
[]
[]
[ "for_loop", "loops", "nlp", "python", "python_3.x" ]
stackoverflow_0074136361_for_loop_loops_nlp_python_python_3.x.txt
Q: I do not see opengl triangle getting rendered in window when I lauch this pyQT6 App in python 3.10 I am trying to draw a triangle using pyGL6 and pyQT6. I could launch a window but then I could not render a triangle; instead, I just see a black screen. from PyQt6 import QtGui from PyQt6 import QtCore, QtWidgets fr...
I do not see opengl triangle getting rendered in window when I lauch this pyQT6 App in python 3.10
I am trying to draw a triangle using pyGL6 and pyQT6. I could launch a window but then I could not render a triangle; instead, I just see a black screen. from PyQt6 import QtGui from PyQt6 import QtCore, QtWidgets from PyQt6.QtOpenGLWidgets import QOpenGLWidget as OpenGLWidget import OpenGL.GL as gl # python wrapping ...
[ "from PyQt6 import QtGui\nfrom PyQt6 import QtCore, QtWidgets\nfrom PyQt6.QtOpenGLWidgets import QOpenGLWidget as OpenGLWidget\nimport OpenGL.GL as GL # python wrapping of OpenGL\nfrom OpenGL import GLU # OpenGL Utility Library, extends OpenGL functionality\nimport sys # we'll need this later to run our Qt appli...
[ 0 ]
[]
[]
[ "opengl", "pyqt", "pyqt6", "python" ]
stackoverflow_0073181133_opengl_pyqt_pyqt6_python.txt