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: TypeError: argument of type 'numpy.int64' is not iterable I am trying to combine these feature selection methods. But there's an error here "TypeError: argument of type 'numpy.int64' is not iterable". How to fix this? def get_true_false(selected_features, features): selected_t_f = [] for feature in featur...
TypeError: argument of type 'numpy.int64' is not iterable
I am trying to combine these feature selection methods. But there's an error here "TypeError: argument of type 'numpy.int64' is not iterable". How to fix this? def get_true_false(selected_features, features): selected_t_f = [] for feature in features: if feature in selected_features: select...
[ "For any reason your selected_features variable is an integer.\nAs mentioned in the error message its type is numpy.int64.\nSo you can't use feature in selected_features.\nBecause to be able to do that selected_features must be iterable, it must be a sequence e.g. a list.\n" ]
[ 0 ]
[]
[]
[ "dimensionality_reduction", "feature_selection", "python" ]
stackoverflow_0074385564_dimensionality_reduction_feature_selection_python.txt
Q: Pillow in Python won't let me open image ("exceeds limit") Just having some problems running a simulation on some weather data in Python. The data was supplied in a .tif format, so I used the following code to try to open the image to extract the data into a numpy array. from PIL import Image im = Image.open('jan...
Pillow in Python won't let me open image ("exceeds limit")
Just having some problems running a simulation on some weather data in Python. The data was supplied in a .tif format, so I used the following code to try to open the image to extract the data into a numpy array. from PIL import Image im = Image.open('jan.tif') But when I run this code I get the following error: PIL....
[ "Try\nPIL.Image.MAX_IMAGE_PIXELS = 933120000\n\nHow to find out such a thing?\nimport PIL\nprint(PIL.__file__) # prints, e. g., /usr/lib/python3/dist-packages/PIL/__init__.py\n\nThen\ncd /usr/lib/python3/dist-packages/PIL\ngrep -r -A 2 'exceeds limit' .\n\nprints\n./Image.py: \"Image size (%d pixels) ex...
[ 92, 59, 0 ]
[]
[]
[ "dataset", "image", "python" ]
stackoverflow_0051152059_dataset_image_python.txt
Q: Python - How to convert JSON File to Dataframe How can I convert a JSON File as such into a dataframe to do some transformations. For Example if the JSON file reads: {"FirstName":"John", "LastName":"Mark", "MiddleName":"Lewis", "username":"johnlewis2", "password":"2910"} How can I convert it to a table like...
Python - How to convert JSON File to Dataframe
How can I convert a JSON File as such into a dataframe to do some transformations. For Example if the JSON file reads: {"FirstName":"John", "LastName":"Mark", "MiddleName":"Lewis", "username":"johnlewis2", "password":"2910"} How can I convert it to a table like such Column -> FirstName | LastName | MiddleName | ...
[ "Creating dataframe from dictionary object.\nimport pandas as pd\ndata = [{'name': 'vikash', 'age': 27}, {'name': 'Satyam', 'age': 14}]\ndf = pd.DataFrame.from_dict(data, orient='columns')\n\ndf\nOut[4]:\n age name\n0 27 vikash\n1 14 Satyam\n\nIf you have nested columns then you first need to normalize the...
[ 76, 11, 4, 2, 1 ]
[]
[]
[ "dataframe", "json", "pandas", "python" ]
stackoverflow_0041168558_dataframe_json_pandas_python.txt
Q: Remove duplicate rows but with condition I have a data frame that looks something like: df = date col1 col2 col3 col4 ----------------------------------------- 2022/30/01 2 2 4 5 2022/30/01 2 2 4 5 2022/30/01 0 0 1 2 2022/30/01 0 ...
Remove duplicate rows but with condition
I have a data frame that looks something like: df = date col1 col2 col3 col4 ----------------------------------------- 2022/30/01 2 2 4 5 2022/30/01 2 2 4 5 2022/30/01 0 0 1 2 2022/30/01 0 0 1 2 2022/30/01 3 2 ...
[ "IIUC, this is a simple selection by boolean masks using duplicated to find the duplicated rows and ne+all to filter the 0 values:\n# is the row not a duplicate?\nmask1 = ~df.duplicated()\n# are col1 and col2 not both 0?\nmask2 = df[['col1', 'col2']].ne(0).all(axis=1)\n# then keep the data on either of the above co...
[ 5, 4, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0071111308_pandas_python.txt
Q: os.walk loop is not passing the readout of the last directory in the hierarchy to a list I'm using os.walk and os.path.splitext to generate two separate lists of folder names and file names (w/o extension) located in a given disk drive of a Windows 10 system. For this purpose I'm using the following loop: import o...
os.walk loop is not passing the readout of the last directory in the hierarchy to a list
I'm using os.walk and os.path.splitext to generate two separate lists of folder names and file names (w/o extension) located in a given disk drive of a Windows 10 system. For this purpose I'm using the following loop: import os output_files = [] output_dir = [] ex_dir = set(['dir1','dir2']) inc_ext = set(['ext1','ext...
[ "This is because you're pruning the directory list in-place with a if d not in ex_dir filter in your list comprehension.\nFrom the documentation of os.walk:\n\nWhen topdown is True, the caller can modify the dirnames list in-place\n(perhaps using del or slice assignment), and walk() will only recurse\ninto the subd...
[ 0 ]
[]
[]
[ "list", "os.path", "os.walk", "python", "python_3.x" ]
stackoverflow_0074385458_list_os.path_os.walk_python_python_3.x.txt
Q: Convert string values starting with a specific letter in a list to integer List Values 49 873 50 575 51 487 52 B000XPZCXW 53 B098LPQ5LM 54 B09W5S7GFK All the values starting with 'B' need to converted into 1 Output 49 873 50 575 51 487 52 ...
Convert string values starting with a specific letter in a list to integer
List Values 49 873 50 575 51 487 52 B000XPZCXW 53 B098LPQ5LM 54 B09W5S7GFK All the values starting with 'B' need to converted into 1 Output 49 873 50 575 51 487 52 1 53 1 54 1 I was hoping to use 'startswith' lamb...
[ "It looks like this is what you want.\n# -*- coding=utf-8 -*-\nlst = [\n (49, \"873\"),\n (50, \"575\"),\n (51, \"487\"),\n (52, \"B000XPZCXW\"),\n (53, \"B098LPQ5LM\"),\n (54, \"B09W5S7GFK\")\n]\nf = lambda x: 1 if x.startswith(\"B\") else x\nfor i in lst:\n print((i[0], f(i[1])))\n# Output\n#...
[ 0, 0 ]
[]
[]
[ "jupyter", "python" ]
stackoverflow_0074385548_jupyter_python.txt
Q: Overcome Performance warning in Pandas mydata = [{'ID' : '10', 'StartDate': '10/10/2016', 'EndDate': '15/10/2016'}, {'ID' : '20', 'StartDate': '10/10/2016', 'EndDate': '18/10/2016'}] df = pd.DataFrame(mydata) df['StartDate'] = pd.to_datetime(df['StartDate']).dt.date df['EndDate'] = pd.to_datetime(df['E...
Overcome Performance warning in Pandas
mydata = [{'ID' : '10', 'StartDate': '10/10/2016', 'EndDate': '15/10/2016'}, {'ID' : '20', 'StartDate': '10/10/2016', 'EndDate': '18/10/2016'}] df = pd.DataFrame(mydata) df['StartDate'] = pd.to_datetime(df['StartDate']).dt.date df['EndDate'] = pd.to_datetime(df['EndDate']).dt.date df = df.loc[df.index.repea...
[ "For vectorized solution need datetimes instead dates:\ndf['StartDate'] = pd.to_datetime(df['StartDate'], dayfirst=True)\ndf['EndDate'] = pd.to_datetime(df['EndDate'], dayfirst=True)\n\nIf there are times and need remove them use Series.dt.normalize instead dt.date:\ndf['StartDate'] = pd.to_datetime(df['StartDate']...
[ 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074385724_dataframe_pandas_python.txt
Q: Running PyOpenPose on Google Colab I'm trying to run PyOpenPose on Google Colab. It requires CUDA, this is how I did it. !wget https://developer.nvidia.com/compute/cuda/10.0/Prod/local_installers/cuda-repo-ubuntu1804-10-0-local-10.0.130-410.48_1.0-1_amd64 -O cuda-repo-ubuntu1804-10-0-local-10.0.130-410.48_1.0-1_am...
Running PyOpenPose on Google Colab
I'm trying to run PyOpenPose on Google Colab. It requires CUDA, this is how I did it. !wget https://developer.nvidia.com/compute/cuda/10.0/Prod/local_installers/cuda-repo-ubuntu1804-10-0-local-10.0.130-410.48_1.0-1_amd64 -O cuda-repo-ubuntu1804-10-0-local-10.0.130-410.48_1.0-1_amd64.deb !dpkg -i cuda-repo-ubuntu1804-10...
[ "here is how I managed to make Openpose work in my googlecolab:\nJust enter the following in one googlecolab cell and run it.\nimport os\nfrom os.path import exists, join, basename, splitext\n\ngit_repo_url = 'https://github.com/CMU-Perceptual-Computing-Lab/openpose.git'\nproject_name = splitext(basename(git_repo_u...
[ 0 ]
[]
[]
[ "c++", "cmake", "google_colaboratory", "openpose", "python" ]
stackoverflow_0053383267_c++_cmake_google_colaboratory_openpose_python.txt
Q: How to delete a panel from grafana dashboard using python requests? I am able to access dashboards using the following api call- url2 = server + "/api/dashboards/uid/" + uid #uid of dashboard r = requests.get(url=url2, headers=headers, verify=False) From this I can retrieve panel details in a particular dashboar...
How to delete a panel from grafana dashboard using python requests?
I am able to access dashboards using the following api call- url2 = server + "/api/dashboards/uid/" + uid #uid of dashboard r = requests.get(url=url2, headers=headers, verify=False) From this I can retrieve panel details in a particular dashboard. Is there any way I can delete a panel inside this dashboard with or wi...
[ "You cannot directly delete a panel inside a dashboard using the API.\nIt is possible to retrieve the dashboard JSON via the API (as you explained in your question), then programmatically edit that JSON in your python code so that the panel is removed, and then overwrite the dashboard using the API again.\n" ]
[ 0 ]
[]
[]
[ "grafana", "grafana_api", "python", "python_requests" ]
stackoverflow_0074376497_grafana_grafana_api_python_python_requests.txt
Q: how to assign to numpy array represented by iterator I have a number of numpy arrays a,b,c, ... which all should be trimmed according to a boolean mask array keep or re-arranged according to an index array indices. Doing this on an individual array works find via arr = arr[keep], but is tedious. Therefore, I want ...
how to assign to numpy array represented by iterator
I have a number of numpy arrays a,b,c, ... which all should be trimmed according to a boolean mask array keep or re-arranged according to an index array indices. Doing this on an individual array works find via arr = arr[keep], but is tedious. Therefore, I want to do this for all arrays via a loop, but the following fa...
[ "Based on this answer to a similar question, I have the following solution.\nlist = [a,b,c] # in practice, this could be many more numpy arrays\nfor i,arr in enumerate(list):\n list[i] = arr[keep] # assign the list element to the new array, the modification of the old one\na,b,c = list # u...
[ 0 ]
[]
[]
[ "arrays", "indexing", "list", "numpy", "python" ]
stackoverflow_0074381475_arrays_indexing_list_numpy_python.txt
Q: 'virtualenv' won't activate on Windows Essentially I cannot seem to activate my virtualenv environment which I create. I'm doing this inside of Windows PowerShell through using scripts\activate but I get an error message: "cannot be loaded because the execution of scripts is disabled on this system". Could this...
'virtualenv' won't activate on Windows
Essentially I cannot seem to activate my virtualenv environment which I create. I'm doing this inside of Windows PowerShell through using scripts\activate but I get an error message: "cannot be loaded because the execution of scripts is disabled on this system". Could this be because I don't carry administrator priv...
[ "According to Microsoft Tech Support it might be a problem with Execution Policy Settings. To fix it, you should try executing Set-ExecutionPolicy Unrestricted -Scope Process (as mentioned in the comment section by @wtsiamruk) in your PowerShell window. This would allow running virtualenv in the current PowerShell ...
[ 253, 53, 29, 20, 9, 7, 3, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "python", "virtualenv" ]
stackoverflow_0018713086_python_virtualenv.txt
Q: label = np.where(df['Sentimen']=='Positif','Negatif','Netral' ,1, 0,-1) y = label y[45:75] TypeError Traceback (most recent call last) Input In [32], in <cell line: 1>() ----> 1 label = np.where(df['Sentimen']=='Positif','Negatif','Netral' ,1, 0,-1) 2 y = label 3 y[45:75...
label = np.where(df['Sentimen']=='Positif','Negatif','Netral' ,1, 0,-1) y = label y[45:75]
TypeError Traceback (most recent call last) Input In [32], in <cell line: 1>() ----> 1 label = np.where(df['Sentimen']=='Positif','Negatif','Netral' ,1, 0,-1) 2 y = label 3 y[45:75] File <__array_function__ internals>:179, in where(*args, **kwargs) TypeError: where() takes ...
[ "According to the docs for np.where, it accepts either one argument, or three arguments. The first argument must be an array consisting of True or False (i.e. bool values). Optionally two additional arrays of the same shape/size can be passed.\nYou have passed np.where 6 arguments. The first is a conditional, df['S...
[ 1 ]
[]
[]
[ "jupyter", "jupyter_notebook", "python" ]
stackoverflow_0074385779_jupyter_jupyter_notebook_python.txt
Q: Real-time stdout read from subprocess works only when running from PyCharm and not Terminal What the application does: runs a subprocess and displays the stdout in real-time to a Tkinter textbox widget. This works perfectly when I run the application from PyCharm. When I run the application from terminal ./applica...
Real-time stdout read from subprocess works only when running from PyCharm and not Terminal
What the application does: runs a subprocess and displays the stdout in real-time to a Tkinter textbox widget. This works perfectly when I run the application from PyCharm. When I run the application from terminal ./application.py it doesn't display in real-time, but instead will display it all after the process has fi...
[ "I know this is an old thread, but still - \nI had the same issue as you did. I asked a question that seemed to help me get in the right direction as to working with real time output. My issue was I needed to differentiate output that resulted of a CR and simulate that behavior in my program. But then I encountered...
[ 0, 0 ]
[]
[]
[ "pycharm", "python", "python_3.x", "subprocess", "tkinter" ]
stackoverflow_0043637572_pycharm_python_python_3.x_subprocess_tkinter.txt
Q: Send Sms from odoo application to mobile number I have a problem with sending sms from odoo application to mobile number. here the console print the message but the message not sending in mobile number. Please help me how can I send message from button action in odoo. I added a button in form view and i need to se...
Send Sms from odoo application to mobile number
I have a problem with sending sms from odoo application to mobile number. here the console print the message but the message not sending in mobile number. Please help me how can I send message from button action in odoo. I added a button in form view and i need to send sms after clicking the button. I have declare a fu...
[ "The best thing you can do here is inherits the native sms module of odoo and modify it according to your needs, so you set up your API and so on. It has everything build already to send sms, batches and get error messages\nHave a look there : https://github.com/odoo/odoo/tree/14.0/addons/sms\nOr in your code ~/odo...
[ 0 ]
[]
[]
[ "odoo", "python" ]
stackoverflow_0074385875_odoo_python.txt
Q: Using FreeImage convert hdr to jpg How can I use ImageIO's FreeImage to convert and hdr to a jpeg image? I've written a function that takes and EXR and converts it to a jpg and the results looks like this: So I'm stumped on how to take an HDR and convert it to a jpg with similar results. I downloaded the HDR from...
Using FreeImage convert hdr to jpg
How can I use ImageIO's FreeImage to convert and hdr to a jpeg image? I've written a function that takes and EXR and converts it to a jpg and the results looks like this: So I'm stumped on how to take an HDR and convert it to a jpg with similar results. I downloaded the HDR from here for free: https://hdrihaven.com/hd...
[]
[]
[ "sudo apt-get install -y openimageio-tools\noiiotool probe.hdr -o probe.png\n# https://github.com/OpenImageIO/oiio/discussions/3579\n# https://launchpad.net/ubuntu/+source/openimageio\n\n" ]
[ -1 ]
[ "python", "python_imageio" ]
stackoverflow_0047725161_python_python_imageio.txt
Q: Combine similar DataFrame columns and stack values Currently, I have a dataframe that looks as such: abc def ghi abc def ghi 2 4 78 56 7 45 Is there a way to combine the columns that have the same name and create a new row for each set of values? Example: abc def ghi 2 4 78 56 7 45 A: You can use .groupby(...
Combine similar DataFrame columns and stack values
Currently, I have a dataframe that looks as such: abc def ghi abc def ghi 2 4 78 56 7 45 Is there a way to combine the columns that have the same name and create a new row for each set of values? Example: abc def ghi 2 4 78 56 7 45
[ "You can use .groupby(level=0, axis='columns') to assign a cumulative count and then perform a transformation based on that.\nimport pandas as pd\n\nnew_cols = pd.MultiIndex.from_arrays([df.columns, df.groupby(level=0, axis=1).cumcount()])\n\nout = df.set_axis(new_cols, axis=1).stack().reset_index(level=0, drop=Tru...
[ 5, 4, 1, 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0073170960_pandas_python.txt
Q: Django REST framework - Edit data if there is such a record, create - if not I'm new to DRF, writing an api for later use in Vue.js . Help me understand how to make it so that when adding a nomenclature, he checks if there is one, and if there is, he edits the quantity by adding to the previous quantity. I am also...
Django REST framework - Edit data if there is such a record, create - if not
I'm new to DRF, writing an api for later use in Vue.js . Help me understand how to make it so that when adding a nomenclature, he checks if there is one, and if there is, he edits the quantity by adding to the previous quantity. I am also interested in the question of how, when adding changes to the nomenclature, the n...
[ "you can use django get_or_create\nread more here\nfor example\nobj, created = Nomenclature.objects.get_or_create(\n nameNom='some name')\n\n" ]
[ 0 ]
[]
[]
[ "api", "django", "django_rest_framework", "python", "vue.js" ]
stackoverflow_0074385648_api_django_django_rest_framework_python_vue.js.txt
Q: TypeError: 'Image' object is not subscriptable (numpy image) I am getting the error TypeError: 'Image' object is not subscriptable My code is: def show_img(self,img): image = img print(image.shape) for i in range (len(image)): image= Image.fromarray(image[i].astype(np.uint8)...
TypeError: 'Image' object is not subscriptable (numpy image)
I am getting the error TypeError: 'Image' object is not subscriptable My code is: def show_img(self,img): image = img print(image.shape) for i in range (len(image)): image= Image.fromarray(image[i].astype(np.uint8)) image.show() Image.shape = (8, 1080, 1920, 3)
[ "Well, you modified the image.\nSo if image has shape (8,1080,1920,3), you set image=image[0] in the first iteration. So now image has shape (1080,1920,3). Then, in 2nd iteration, image=image[1] makes it shape (1920,3), then in 3rd iteration, image=image[2] makes it shape (3,), and then 4th iteration would fail any...
[ 1 ]
[]
[]
[ "numpy", "python", "python_imaging_library" ]
stackoverflow_0074386022_numpy_python_python_imaging_library.txt
Q: How do i filter by specific event for my graph plotting I have a CSV File with columns below: Time Event Speed 1/30/2022 17:23 Speeding 50 1/28/2022 18:22 Speeding 20 1/27/2022 22:00 Speeding 30 1/26/2022 23:23 Speeding 40 1/27/2022 22:00 Stopping 10 1/26/2022 23:23 Stopping 10 Issue: Currently my code wil...
How do i filter by specific event for my graph plotting
I have a CSV File with columns below: Time Event Speed 1/30/2022 17:23 Speeding 50 1/28/2022 18:22 Speeding 20 1/27/2022 22:00 Speeding 30 1/26/2022 23:23 Speeding 40 1/27/2022 22:00 Stopping 10 1/26/2022 23:23 Stopping 10 Issue: Currently my code will run and give me the average speed of every ev...
[ "Filter by Speeding then group by Time:\nevent_filter = df[\"Event\"] == \"Speeding\"\ngrouped_by_time = df[event_filter].groupby('Time')[['Speed']].mean()\n\nAnd it plots average speed of Speeding events (50, 20, 30, 40):\n\nThe whole code as below:\nimport pandas as pd\nfrom bokeh.plotting import figure, output_f...
[ 0 ]
[]
[]
[ "bokeh", "graph", "pandas", "plot", "python" ]
stackoverflow_0074385853_bokeh_graph_pandas_plot_python.txt
Q: How to deal with log output which contains progress bar? Context This question is not related to any particular programming language, but how stdout works when we write to a terminal vs when we write to a file. Anyways, to demonstrate, I'll have to pick a language, and I choose Python for the problem part. I've st...
How to deal with log output which contains progress bar?
Context This question is not related to any particular programming language, but how stdout works when we write to a terminal vs when we write to a file. Anyways, to demonstrate, I'll have to pick a language, and I choose Python for the problem part. I've stolen code below from this answer: Save this code as progress.p...
[ "I found an answer to my question.\nSo docker spits the log output in io.ReadCloser, that output can be written to a bytes.Buffer:\nvar stdout bytes.Buffer\nvar stderr bytes.Buffer\n\ncontainerLog := GetLogs(containerID)\nstdcopy.StdCopy(&stdout, &stderr, containerLog)\n\nHere is code for GetLogs anyway:\n// GetLog...
[ 0 ]
[]
[]
[ "docker", "go", "python", "stdout" ]
stackoverflow_0074375547_docker_go_python_stdout.txt
Q: assigned lambda as method: self not passed? I want to create a method in a class object (depending on some condition). This works when I create the lambda in the class (m2) and when I assign an existing method to a class attribute (m3), but NOT when I assign a lambda to a class attribute (m1). In that case the lam...
assigned lambda as method: self not passed?
I want to create a method in a class object (depending on some condition). This works when I create the lambda in the class (m2) and when I assign an existing method to a class attribute (m3), but NOT when I assign a lambda to a class attribute (m1). In that case the lambda does not get the self parameter. class c: ...
[ "A function needs to be bound to an instance for it to become a bound method of the instance and be passed with the instance as the first argument when called.\nYou can bind an unbound function to an instance with types.MethodType:\nfrom types import MethodType\n\nclass c:\n def __init__(self):\n self.m1 ...
[ 0 ]
[ "Replace\nself.m1 = lambda self: 1\n\nby\nself.m1 = lambda: 1\n\n" ]
[ -1 ]
[ "attributes", "lambda", "methods", "python", "python_3.x" ]
stackoverflow_0074385980_attributes_lambda_methods_python_python_3.x.txt
Q: Matplotlib: zorder in 3d projection not working I am drawing a 3d graph with matplotlib and trying to change the order of some scatters with the attribute "zorder". The object with the highest zorder should be placed on top, but it failed. Here is my code: import matplotlib.pyplot as plt import numpy as np fig = ...
Matplotlib: zorder in 3d projection not working
I am drawing a 3d graph with matplotlib and trying to change the order of some scatters with the attribute "zorder". The object with the highest zorder should be placed on top, but it failed. Here is my code: import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax = fig.add_subplot(projection= '3d') ...
[ "Interesting. I'm not sure why but zorder seems to behave properly when called with ax.plot rather than ax.scatter, as follows:\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfig = plt.figure()\nax = fig.add_subplot(projection= '3d')\n\ncoorx = [1,2,3,4]\ncoory = [1,1,1,1]\ncoorz = [1,1,1,1]\n\n\nax.plot(c...
[ 1 ]
[]
[]
[ "matplotlib", "python", "z_order" ]
stackoverflow_0074385967_matplotlib_python_z_order.txt
Q: Why is the following only scraping one page? How can I scrape the other pages as well? I am trying to scrape multiple pages, but the following code scrapes only one page. How can I scrape the other pages? import requests from bs4 import BeautifulSoup headers ={ 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win6...
Why is the following only scraping one page? How can I scrape the other pages as well?
I am trying to scrape multiple pages, but the following code scrapes only one page. How can I scrape the other pages? import requests from bs4 import BeautifulSoup headers ={ 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36' } for pag...
[ "Now using correct locator, I'm getting working output:\nCode:\nimport requests\nfrom bs4 import BeautifulSoup\nimport pandas as pd\n\n\nTitle = []\np = []\n\nheaders ={\n 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36'\n}\nfor pa...
[ 1, 0, 0, 0 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0068805102_beautifulsoup_python_web_scraping.txt
Q: Group by dataframe using python and pandas Lets say i have df like this ID name_x st string 1 xx us Being unacquainted with the chief raccoon was harming his prospects for promotion 2 xy us1 The overpass went under the highway and into a secret world 3 xz us He was 100% into fasting with her until he understoo...
Group by dataframe using python and pandas
Lets say i have df like this ID name_x st string 1 xx us Being unacquainted with the chief raccoon was harming his prospects for promotion 2 xy us1 The overpass went under the highway and into a secret world 3 xz us He was 100% into fasting with her until he understood that meant he couldn't eat 4 xu us2 ...
[ "I would first groupby() to concatenate the strings as you show and then use collections Counter and then most_common. Finally assign it back to the dataframe. I am using x.lower() because otherwise \"He\" and \"he\" will be considered a different word (but you can always remove it if this is intended):\noutput = d...
[ 2, 1 ]
[]
[]
[ "dataframe", "keyword", "numpy", "pandas", "python" ]
stackoverflow_0074385812_dataframe_keyword_numpy_pandas_python.txt
Q: Is there a way to use pandas.read_xml() with out a URI/URL for namespaces? In my XML file [studentinfo.xml] some tags have namespace prefixes, is there a way to loop through the xml file and parse tag content [all sibling and child tags] without defining the URI/URL for namespace? If you have another way of parsin...
Is there a way to use pandas.read_xml() with out a URI/URL for namespaces?
In my XML file [studentinfo.xml] some tags have namespace prefixes, is there a way to loop through the xml file and parse tag content [all sibling and child tags] without defining the URI/URL for namespace? If you have another way of parsing the xml file not using pandas I am open to any and all solutions. <?xml versio...
[ "You were about 90% there. I just fixed up a couple of things:\n\nall_items : to find StudentScreening instead of info\ninfo.find() statements : dealt with missing values\npd.concat() : instead of df1.append()\ncalled the function parse_xml at the end\n\n\n\nHere is the code:\nimport pandas as pd\nimport numpy as n...
[ 0, 0 ]
[]
[]
[ "beautifulsoup", "pandas", "parsing", "python", "xml" ]
stackoverflow_0074376254_beautifulsoup_pandas_parsing_python_xml.txt
Q: moving a crosshair in Games im trying to make an aim bot for personal fun use against friends not to ruin others experience and to see if I can make one I am relatively new to programming and cant get my cross hair to move. I have tried using pyautogui and pydirectinput and a few other things I can get it to work ...
moving a crosshair in Games
im trying to make an aim bot for personal fun use against friends not to ruin others experience and to see if I can make one I am relatively new to programming and cant get my cross hair to move. I have tried using pyautogui and pydirectinput and a few other things I can get it to work in a browser but when I get into ...
[ "Try change this code part:\nfrom shutil import move\nfrom time import sleep\nimport pyautogui \n\nwhile True: \n sleep(5) \n x, y = pyautogui.locateCenterOnScreen(\"ball.jpg\", confidence = 0.8) \n pyautogui.moveTo(10, 10, duration = 0.1) \n pyautogui.leftClick() \n break\n\n" ]
[ 0 ]
[]
[]
[ "mouse", "project", "python", "social_gaming" ]
stackoverflow_0074046554_mouse_project_python_social_gaming.txt
Q: PYPY venv pip ERROR: ModuleNotFoundError: No module named 'pip._vendor.six' I created venv according to pypy install site: System-Product-Name:~# virtualenv -p "/home/x/pypy3.8-v7.3.7-linux64/bin/pypy" ve created virtual environment PyPy3.8.12.final.0-64 in 102ms Success. Following step 2 (activation) worked as...
PYPY venv pip ERROR: ModuleNotFoundError: No module named 'pip._vendor.six'
I created venv according to pypy install site: System-Product-Name:~# virtualenv -p "/home/x/pypy3.8-v7.3.7-linux64/bin/pypy" ve created virtual environment PyPy3.8.12.final.0-64 in 102ms Success. Following step 2 (activation) worked as well... and using: $python opens pypy same as using ./pypy, which is as intende...
[ "Please use the venv module provided with python\npypy3 -m venv /tmp/venv\nsource /tmp/venv/bin/activate\n\nThe version of virtualenv provided with your linux distro does not know about pypy3.8, since pypy3.8 changed the file layout and that version of virtualenv shipped long before pypy3.8 was released.\n", "Got...
[ 1, 0, 0 ]
[]
[]
[ "installation", "pip", "pypy", "python", "web3py" ]
stackoverflow_0070101401_installation_pip_pypy_python_web3py.txt
Q: Get AuditLogs for specific groups to know the users have been added to those groups in the last month I am trying to obtain the logs of the past 30 days to know the users that have been added to given group. I'm using Python to report and modify different things and everything else has worked fine except this. The...
Get AuditLogs for specific groups to know the users have been added to those groups in the last month
I am trying to obtain the logs of the past 30 days to know the users that have been added to given group. I'm using Python to report and modify different things and everything else has worked fine except this. The first thing I tried was using the filter option as described here like this targetUrl = "https://graph.mic...
[ "When i tried to repo in our side , its working as expected ,\nAPI - https://graph.microsoft.com/v1.0/auditLogs/directoryAudits?$filter=activityDateTime gt 2022-10-10\n\nAs i can see the date you are written in query is 2022-10-08 , you can't query for more than 30 days , could you please try by changing the date t...
[ 1 ]
[]
[]
[ "api", "azure_active_directory", "msgraph", "python" ]
stackoverflow_0074378208_api_azure_active_directory_msgraph_python.txt
Q: How to ignore all values in list that are not numbers I need to get all values that are numbers from: lst = [7, 18, 3, 'a', True, (2,3)] So I need to get 7,8 and 3. How can I get that? I tried using function isnumeric and isdigit. It returns error -> AttributeError: 'int' object has no attribute 'isnumeric' A: ...
How to ignore all values in list that are not numbers
I need to get all values that are numbers from: lst = [7, 18, 3, 'a', True, (2,3)] So I need to get 7,8 and 3. How can I get that? I tried using function isnumeric and isdigit. It returns error -> AttributeError: 'int' object has no attribute 'isnumeric'
[ "You can try using type()\nlst = [7, 18, 3, 'a', True, (2,3)]\nnew_lst = [i for i in lst if type(i) in [int, float]]\n\n" ]
[ 1 ]
[ "Use list comprehension\nHere is a quick example\nlst = [7, 18, 3, 'a', True, (2,3)]\n[x for x in lst if isinstance(x, int)]\n\n==> [7, 18, 3, True]\n\n\"True\" gets in the way here cause\nint.__subclasses__()\n[<type 'bool'>]\n\nBut this is another question...\n" ]
[ -1 ]
[ "list", "python" ]
stackoverflow_0074386141_list_python.txt
Q: Adding values to an nxn numpy array from a pandas dataframe with the specific indices The problem is as follows. I have a pandas dataFrame looking something like row_idx clm_idx value 0 0 1 a1 1 0 2 b1 2 1 3 c1 3 2 3 ...
Adding values to an nxn numpy array from a pandas dataframe with the specific indices
The problem is as follows. I have a pandas dataFrame looking something like row_idx clm_idx value 0 0 1 a1 1 0 2 b1 2 1 3 c1 3 2 3 d1 This dataFrame can have up to m lines (probably quite a lot). Secondly I have a nxn ...
[ "example:\ndata = [[0, 1, 100], [0, 2, 200], [1, 3, 300], [2, 3, 400]]\ndf = pd.DataFrame(data, columns=['row_idx', 'clm_idx', 'value'])\n\ndf\n row_idx clm_idx value\n0 0 1 100\n1 0 2 200\n2 1 3 300\n3 2 3 400\n\n\na1 = np.arange(0, 16).reshape(4,4)\n\na1\...
[ 0, 0, 0 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074385991_numpy_pandas_python.txt
Q: ImportError: cannot import name 'MutableMapping' from 'collections' (/app/.heroku/python/lib/python3.10/collections/__init__.py) I'm trying to deploy my Flask app to a Heroku server, but I keep "Internal Server Error", and when I check the app error logs this is what I found: Extract of Heroku error logs: [...] 20...
ImportError: cannot import name 'MutableMapping' from 'collections' (/app/.heroku/python/lib/python3.10/collections/__init__.py)
I'm trying to deploy my Flask app to a Heroku server, but I keep "Internal Server Error", and when I check the app error logs this is what I found: Extract of Heroku error logs: [...] 2022-03-26T02:07:20.728861+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/flask/sessions.py", line 14, in <mod...
[ "These errors came from python 3.10 which is not stable yet, Heroku by default will use the latest python edition\nI suggest you should use 3.9. Add a \"runtime.txt\" in your code with body:\npython-3.9.6 # or version you are using\n\n", "For Python 3.10.6\n\nImportError: cannot import name 'MutableMapping' from ...
[ 0, 0 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0071625118_flask_python.txt
Q: How can I speed up my misplaced tiles heuristic for the 8 puzzle problem? My lists are always of length 8 (7 indices), and always contain numbers 0-8 I currently do this to find the sum of misplaced tiles: def misplacedTilesHeuristic(stateObj, goal): sum = 0 for elem in range(len(goal)): if goal[e...
How can I speed up my misplaced tiles heuristic for the 8 puzzle problem?
My lists are always of length 8 (7 indices), and always contain numbers 0-8 I currently do this to find the sum of misplaced tiles: def misplacedTilesHeuristic(stateObj, goal): sum = 0 for elem in range(len(goal)): if goal[elem] != stateObj[elem]: sum+=1 return sum How can I make this...
[ "as already mentioned, the one-liner is a good idea, for example like this :\ndef comp(stObj,goal):\n sum = 0\n for elem in range(len(goal)):\n if goal[elem] != stObj[elem]:sum +=1\n return sum\n\ndef prop1(stObj,goal):\n sum = 0\n for i,j in zip(stObj,goal):\n if i !=j:sum +=1\n ret...
[ 0, 0 ]
[]
[]
[ "heuristics", "python", "sliding_tile_puzzle" ]
stackoverflow_0071149288_heuristics_python_sliding_tile_puzzle.txt
Q: how pull beta data from yahoo.finance? beta values are calculated in yahoo.finance and thinking I can save time rather calculating through variance and etc. The beta chart can be seen under stock chart. I am able to extract close price an volume for the ticker using the code below: import yfinance as yf from yahoo...
how pull beta data from yahoo.finance?
beta values are calculated in yahoo.finance and thinking I can save time rather calculating through variance and etc. The beta chart can be seen under stock chart. I am able to extract close price an volume for the ticker using the code below: import yfinance as yf from yahoofinancials import YahooFinancials df = yf.do...
[ "you can do this in a batch, using concat instead of the soon-to-be deprecated append\n# import yfinance\nimport yfinance as yf\n\n# initialise with a df with the columns\ndf = pd.DataFrame(columns=['Stock','Beta','Marketcap'])\n\n# here, symbol_sgx is the list of symbols (tickers) you would like to retrieve data o...
[ 1, 0 ]
[]
[]
[ "python", "stock", "variance", "yahoo_finance", "yfinance" ]
stackoverflow_0069352860_python_stock_variance_yahoo_finance_yfinance.txt
Q: UnicodeEncodeError: 'utf-8' codec can't encode character '\ud83d' in position 388: surrogates not allowed When I try to use: df[df.columns.difference(['pos', 'neu', 'neg', 'new_description'])].to_csv('sentiment_data.csv') I get the error: UnicodeEncodeError: 'utf-8' codec can't encode character '\ud83d' in positi...
UnicodeEncodeError: 'utf-8' codec can't encode character '\ud83d' in position 388: surrogates not allowed
When I try to use: df[df.columns.difference(['pos', 'neu', 'neg', 'new_description'])].to_csv('sentiment_data.csv') I get the error: UnicodeEncodeError: 'utf-8' codec can't encode character '\ud83d' in position 388: surrogates not allowed I don't understand what this error means and how I can fix this error and expor...
[ "Emojis in Unicode lie outside the Basic Multilingual Pane, which means they have codepoints that won't fit in 16 bits. Surrogate pairs are a way to make these glyphs directly representable in UTF-16 as a pair of 16-bit codepoints.\nYou can force surrogate pairs to be resolved into the corresponding codepoint outsi...
[ 21, 0, 0 ]
[]
[]
[ "pandas", "python", "python_3.x" ]
stackoverflow_0054536539_pandas_python_python_3.x.txt
Q: Accessing UpdateLinks() in COM Object using Python I am working on automating an Excel file which is linked to certain .csv files. Those .csv files are created from a SAS Code which is run every Quarter. The files created are timestamped accordingly for example XYZ_201603.csv and XYZ_201606.csv and so on. I nee...
Accessing UpdateLinks() in COM Object using Python
I am working on automating an Excel file which is linked to certain .csv files. Those .csv files are created from a SAS Code which is run every Quarter. The files created are timestamped accordingly for example XYZ_201603.csv and XYZ_201606.csv and so on. I need to update the links on my Excel File so that it automa...
[ "If you review the Microsoft Documentation, it seems that the UpdateLink method can be called without any parameters. Therefore this program should work:\nimport win32com.client as win32\nxl_app = win32.gencache.EnsureDispatch(\"Excel.Application\")\nxl_app.Visible = True\nxl_app.DisplayAlerts = False\nwb = x...
[ 1, 0 ]
[]
[]
[ "csv", "excel", "python" ]
stackoverflow_0046434713_csv_excel_python.txt
Q: Is there a way to hint that an attribute can't be None in certain circumstances? I'm trying to avoid having a bunch of ifs or asserts in the code using this class. class TemplateRow(tp.NamedTuple): """Parsed template row, if not error.""" template: Template | None = None error: str | None = None ...
Is there a way to hint that an attribute can't be None in certain circumstances?
I'm trying to avoid having a bunch of ifs or asserts in the code using this class. class TemplateRow(tp.NamedTuple): """Parsed template row, if not error.""" template: Template | None = None error: str | None = None @property def valid(self) -> bool: """Determine if this row is valid. ...
[ "Instead of a TypeGuard, you could actually define two types - ValidTemplateRow and InvalidTemplateRow. Then, simply use isinstance to check for either.\n\nclass ValidTemplateRow(tp.NamedTuple):\n template: Template\n\n\nclass InvalidTemplateRow(tp.NamedTuple):\n error: str\n\n\ndef read_template(filename: st...
[ 2, 1 ]
[]
[]
[ "pydantic", "python", "python_typing" ]
stackoverflow_0074384403_pydantic_python_python_typing.txt
Q: Save failed in Google Colab I opened a number of tabs at the same time. I think that's why Google Colab was not able to support the heavy load. The message stated: Save failed This file could not be saved. Please use the File menu to download the .ipynb and upload the notebook to make a copy that includes your re...
Save failed in Google Colab
I opened a number of tabs at the same time. I think that's why Google Colab was not able to support the heavy load. The message stated: Save failed This file could not be saved. Please use the File menu to download the .ipynb and upload the notebook to make a copy that includes your recent changes. Is downloading the...
[ "It turned out to be a network issue. Output is heavy and colab is not able to save it is not able to make a handshake because internet speed is poor. So just switch the internet source and see it working.\n", "I had the same problem despite ''Runtime > Change runtime type' being already set 'None' beforehand. As...
[ 16, 2, 2, 1, 1, 0 ]
[]
[]
[ "google_colaboratory", "python" ]
stackoverflow_0060867546_google_colaboratory_python.txt
Q: Matplotlib add a default watermark I'm using matplotlib for work and company policy is to include a watermark on every plot we make. Is there a way to set matplotlib to do this by default? I'm currently passing each Axes object into a helper function which adds the watermark in the bottom left corner. import matpl...
Matplotlib add a default watermark
I'm using matplotlib for work and company policy is to include a watermark on every plot we make. Is there a way to set matplotlib to do this by default? I'm currently passing each Axes object into a helper function which adds the watermark in the bottom left corner. import matplotlib.pyplot as plt def add_watermark(a...
[ "You may easily subclass and monkey-patch the default axes. So create a file matplotlib_company.py like this\nimport matplotlib.axes\nfrom matplotlib.offsetbox import AnchoredText\n\nclass MyAxes(matplotlib.axes.Axes):\n def __init__(self, *args, **kwargs):\n\n super().__init__(*args, **kwargs)\n a...
[ 4, 1, 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0056981603_matplotlib_python.txt
Q: Get maximum value of each id in Pyspark I have data like this and I need output like this A: Groupby everything and find max value. Code below from pyspark.sql import Window df.withColumn('Value',max('Amount').over(Window.partitionBy())).show()
Get maximum value of each id in Pyspark
I have data like this and I need output like this
[ "Groupby everything and find max value. Code below\n from pyspark.sql import Window\n\ndf.withColumn('Value',max('Amount').over(Window.partitionBy())).show()\n\n" ]
[ 1 ]
[]
[]
[ "pyspark", "python" ]
stackoverflow_0074385432_pyspark_python.txt
Q: How to change a string name in a file when a hexadecimal numbers is split? I have a file named input.txt. name="XYZ_PP_0" number="0x12" bytesize="4" info="0x00000012" name="GK_LMP_2_0" number="0xA5" bytesize="8" info="0x00000000bbae321f" name="MP_LKO_1_0" number="0x356" bytesize="4" info="0x00000234" name="PNP_VXU...
How to change a string name in a file when a hexadecimal numbers is split?
I have a file named input.txt. name="XYZ_PP_0" number="0x12" bytesize="4" info="0x00000012" name="GK_LMP_2_0" number="0xA5" bytesize="8" info="0x00000000bbae321f" name="MP_LKO_1_0" number="0x356" bytesize="4" info="0x00000234" name="PNP_VXU_1_2_0" number="0x48A" bytesize="8" info="0x00000000a18c3ba3" name="AVU_W_2_3_1"...
[ "With your current code you just need to capture the name with the regex and add it to the output in the same way you handle nums:\nwith open(infile_path, \"r\") as infile, open(outfile_path, \"w\") as outfile:\n for s in infile:\n r = re.match('name=\"(.*)\" number=\"(.*)\" bytesize=\"(.*)\" info=\"(.*)\...
[ 1, 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074385525_python_python_3.x.txt
Q: Unable to covert Json to Dataframe Unable to covert Json to Dataframe, the following TypeError shows : The following data is created Test_data = {'archived': False, 'archived_at': None, 'associations': None, 'created_at': datetime.datetime(2020, 10, 30, 8, 3, 54, 190000, tzinfo=tzlocal()), 'id': '12345', 'pr...
Unable to covert Json to Dataframe
Unable to covert Json to Dataframe, the following TypeError shows : The following data is created Test_data = {'archived': False, 'archived_at': None, 'associations': None, 'created_at': datetime.datetime(2020, 10, 30, 8, 3, 54, 190000, tzinfo=tzlocal()), 'id': '12345', 'properties': {'createdate': '[![2020-10-30...
[ "can you try this:\ndf=pd.json_normalize(Test_data)\nprint(df)\n'''\n archived archived_at associations created_at id properties_with_history updated_at properties.createdate properties.email properties.firstname\n0 False None None 2020-10-30T08:03:54.1...
[ 2, 0 ]
[]
[]
[ "api", "dataframe", "json", "pandas", "python" ]
stackoverflow_0074385639_api_dataframe_json_pandas_python.txt
Q: Selecting jquery dropdown list using XPATH Actually I am doing tasks from https://demo.seleniumeasy.com/jquery-dropdown-search-demo.html. But I found a problem - I can't find any element on this page using XPATH. For example I want to find "Select Country" using driver.find_element and XPATH: from selenium import ...
Selecting jquery dropdown list using XPATH
Actually I am doing tasks from https://demo.seleniumeasy.com/jquery-dropdown-search-demo.html. But I found a problem - I can't find any element on this page using XPATH. For example I want to find "Select Country" using driver.find_element and XPATH: from selenium import webdriver from selenium.webdriver.common.by impo...
[ "There is a Select block here.\nYou need to utilize Selenium Select object for that.\nThis code is selecting Denmark:\nfrom selenium import webdriver\nfrom selenium.webdriver import ActionChains\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.chrome.options import Options\nfrom selen...
[ 1 ]
[]
[]
[ "html", "python", "selenium", "selenium_webdriver", "xpath" ]
stackoverflow_0074386371_html_python_selenium_selenium_webdriver_xpath.txt
Q: Pandas dataframe with hourly data: Calculating sums for specific times There is a dataframe with hourly data, e.g.: DATE TIME Amount 2022-11-07 21:00:00 10 2022-11-07 22:00:00 11 2022-11-08 07:00:00 10 2022-11-08 08:00:00 13 2022-11-08 ...
Pandas dataframe with hourly data: Calculating sums for specific times
There is a dataframe with hourly data, e.g.: DATE TIME Amount 2022-11-07 21:00:00 10 2022-11-07 22:00:00 11 2022-11-08 07:00:00 10 2022-11-08 08:00:00 13 2022-11-08 09:00:00 12 2022-11-08 10:00:00 11 2022-11-08 ...
[ "First set a DatetimeIndex in order to use DataFrame.between_time, then groupby DATE and aggregate by sum. Finally, get the last value of datetimes per day, in order to match the index of the original DataFrame:\ndf.index = pd.to_datetime(df['DATE'] + ' ' + df['TIME'])\n\ns = (df.between_time('7:00','12:00')\n ...
[ 3, 2 ]
[]
[]
[ "pandas", "python", "time_series" ]
stackoverflow_0074386350_pandas_python_time_series.txt
Q: how to use python to calculate resistance value bases on linear system? I have searched many guidance on how to compute my simular situation, I choose to use sympy, but I failed to get correct result. Bellow is my formula system to calculate my resistances R3 and R4: 1/r3 + 1/r4 = 1/r_ref Vneg * r3/(r3+r4) = Vbias...
how to use python to calculate resistance value bases on linear system?
I have searched many guidance on how to compute my simular situation, I choose to use sympy, but I failed to get correct result. Bellow is my formula system to calculate my resistances R3 and R4: 1/r3 + 1/r4 = 1/r_ref Vneg * r3/(r3+r4) = Vbias I further convert them to be: r4 = r3 * r_ref / (r3 - r_ref) r4 = (Vneg / V...
[ "Here I wrote your two initial equations. Note that it is always better to tell solve what to solve for.\nfrom sympy import *\n\nr3, r4 = symbols(\"r3, r4\")\nVbias = -717.39\nVneg = -5000\nr_ref = 43\n\neq1 = Eq(1/r3 + 1/r4, 1/r_ref)\neq2 = Eq(Vneg * r3/(r3+r4), Vbias)\n\nsol = solve([eq1, eq2], [r3, r4], dict=Tru...
[ 2 ]
[]
[]
[ "numpy", "python", "sympy" ]
stackoverflow_0074385936_numpy_python_sympy.txt
Q: How to get full response in MS LUIS? (Python) I want to program a chatbot with machine learning entities and subentities. With LUIS Recognizer I can access the entities but not the subentities. The subentities or also called children are available in the raw response but not in the Recognizer. -> how can I read ou...
How to get full response in MS LUIS? (Python)
I want to program a chatbot with machine learning entities and subentities. With LUIS Recognizer I can access the entities but not the subentities. The subentities or also called children are available in the raw response but not in the Recognizer. -> how can I read out these subentities? Somebody had already a similar...
[ "Solution:\nC:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python39_64\\Lib\\site-packages\\botbuilder\\ai\\luis\n-> by opening the folder where the botbuilder lib is stored, luis_recognizer.py can be opened\nFor me it looks like this\nenter image description here\nThere it can be seen which init paramet...
[ 0 ]
[]
[]
[ "azure_language_understanding", "botframework", "luis.ai", "python" ]
stackoverflow_0074383712_azure_language_understanding_botframework_luis.ai_python.txt
Q: Redirect print command in python script through tqdm.write() I'm using tqdm in Python to display console-progressbars in our scripts. However, I have to call functions which print messages to the console as well and which I can't change. In general, writing to the console while displaying progress bars in the cons...
Redirect print command in python script through tqdm.write()
I'm using tqdm in Python to display console-progressbars in our scripts. However, I have to call functions which print messages to the console as well and which I can't change. In general, writing to the console while displaying progress bars in the console messes up the display like so: from time import sleep from tqd...
[ "Redirecting sys.stdout is always tricky, and it becomes a nightmare when two applications are twiddling with it at the same time.\nHere the trick is that tqdm by default prints to sys.stderr, not sys.stdout. Normally, tqdm has an anti-mixup strategy for these two special channels, but since you are redirecting sys...
[ 36, 14, 13, 2, 0 ]
[]
[]
[ "python", "python_2.7", "tqdm" ]
stackoverflow_0036986929_python_python_2.7_tqdm.txt
Q: How to efficiently iterate to create a new dataframe from old dataframe with iterrows or itertuples everyone I have a dataframe with 2 million unique codes for students and two other columns: initial and final year. I need to create a new dataframe with only two columns (student cod and year), with one row for eac...
How to efficiently iterate to create a new dataframe from old dataframe with iterrows or itertuples
everyone I have a dataframe with 2 million unique codes for students and two other columns: initial and final year. I need to create a new dataframe with only two columns (student cod and year), with one row for each year the student remained studying. For instance, if student with code 1234567 studied from 2013 to 201...
[ "For improve performance use vectorized solution - Index.repeat with DataFrame.loc for new rows and for YEAR column add counter by GroupBy.cumcount:\ndif = df['YEAR_END'].sub(df['YEAR_INCLUSION']).add(1)\ndf = (df.loc[df.index.repeat(dif), ['COD','YEAR_INCLUSION']]\n .rename(columns={'YEAR_INCLUSION':'YEAR'}...
[ 1, 1 ]
[]
[]
[ "dataframe", "for_loop", "iteration", "pandas", "python" ]
stackoverflow_0074386524_dataframe_for_loop_iteration_pandas_python.txt
Q: Can anyone explain how to solve this problem A program that reads 3 numbers A, B and C and checks if each 3 numbers are greater than or equal to 20. Output should be single line containing a boolean. True should be printed if each number is greater than or equal to 20, Otherwise False should be printed. I have tri...
Can anyone explain how to solve this problem
A program that reads 3 numbers A, B and C and checks if each 3 numbers are greater than or equal to 20. Output should be single line containing a boolean. True should be printed if each number is greater than or equal to 20, Otherwise False should be printed. I have tried using "and" operator and got result. Are there ...
[ "You can use the all function with a generator expression that iterates over a range of 3 to test if each input value is greater than or equal to 20:\nprint(all(int(input()) >= 20 for _ in range(3)))\n\n", "This is another way:\nabc = all(a, b, c)\n\n", "Take the lowest thanks to the min() function.\nIf the low...
[ 3, 2, 1, 0 ]
[]
[]
[ "operators", "python", "python_3.x" ]
stackoverflow_0074386538_operators_python_python_3.x.txt
Q: Pytesseract result includes unexpected content "\n\x0c" I'm doing python OCR image to text, and compare if there is duplicate, I'm checking one by one so that I can locate easier pic link: https://imgur.com/a/0BGmtEV Main issue: from (original pic in pic link) I saved each of the result of image to text , ex: CAT4...
Pytesseract result includes unexpected content "\n\x0c"
I'm doing python OCR image to text, and compare if there is duplicate, I'm checking one by one so that I can locate easier pic link: https://imgur.com/a/0BGmtEV Main issue: from (original pic in pic link) I saved each of the result of image to text , ex: CAT4B5, CA7T4BB, CATAAF ... and I saved them in list, but when I ...
[ "Use the strip method to remove the unwanted characters from the string when assigning the string value to the text variable.\ntext = pytesseract.image_to_string(new_crop, lang='eng').strip()\n\nExample:\nt = ' \\n\\nCAT4B5\\n\\x0c'\nt.strip()\n# 'CAT4B5'\n\n" ]
[ 1 ]
[]
[]
[ "numpy", "python", "python_3.x" ]
stackoverflow_0074386329_numpy_python_python_3.x.txt
Q: y-axis range for plotting line of best fit is way too small I have x and y dataframes and when I plot a scatterplot I get a pretty good result as shown below: But when I fit the data into a regression model and plot the line of best fit, the line appears to have much higher values and it's squeezing the y-axis in...
y-axis range for plotting line of best fit is way too small
I have x and y dataframes and when I plot a scatterplot I get a pretty good result as shown below: But when I fit the data into a regression model and plot the line of best fit, the line appears to have much higher values and it's squeezing the y-axis into a clustered mess. How do I make the y-axis have a normal rang...
[ "Try to use this:\nplt.plot(x, model.predict(x))\n" ]
[ 0 ]
[]
[]
[ "matplotlib", "numpy", "pandas", "python", "regression" ]
stackoverflow_0074331420_matplotlib_numpy_pandas_python_regression.txt
Q: How can I ask for user input in Python? So to start coding I have to ask for a user input. They have to place 4 cards like so A-S,A-H,A-C,A-D Then I would create a list from their input. It should take the 2nd element then the 4th element from their input 4cards = input() List1 = [] List1.append(4cards[1], 4cards...
How can I ask for user input in Python?
So to start coding I have to ask for a user input. They have to place 4 cards like so A-S,A-H,A-C,A-D Then I would create a list from their input. It should take the 2nd element then the 4th element from their input 4cards = input() List1 = [] List1.append(4cards[1], 4cards[3]) List1pair = ', '.join(P2) print 'List1 c...
[ "You can't use number first 4cards. Use variable I.E _4cards\n_4cards = input()\nList1 = []\nList1.append(_4cards[1], _4cards[3])\nList1pair = ', '.join(P2)\nprint ('List1 cards: {0}.format(List1pair)')\n\n", "Hi The reson you are getting error because of the name of variable 4cards we cant use this as a variabl...
[ 0, 0, 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074386488_python_python_3.x.txt
Q: How to find the euclidean distance between X and each sublist of Z using python The points are x=[[0.5697071,0.447144773,0.45310486]] and z=[[0,0.47144773043356025,0],[0,0.47144773043356025,0.4531048568095023],[0.5697070991026062,0.47144773043356025,0.4531048568095023],[0,0,0]] I want a Python code to solve the ...
How to find the euclidean distance between X and each sublist of Z using python
The points are x=[[0.5697071,0.447144773,0.45310486]] and z=[[0,0.47144773043356025,0],[0,0.47144773043356025,0.4531048568095023],[0.5697070991026062,0.47144773043356025,0.4531048568095023],[0,0,0]] I want a Python code to solve the above problem, I tried using unpacking of lists but I am getting a lot of errors.
[ "Here's a way:\n(EDIT: On @Timus's advice - sum switched to math.fsum to reduce loss of precision)\nimport math\n\ndef distance(point1, point2):\n return math.sqrt(math.fsum((dim2-dim1)**2 for dim1, dim2 in zip(point1, point2)))\n\n\nx=[[0.5697071,0.447144773,0.45310486]]\nz=[[0,0.47144773043356025,0],[0,0.47144...
[ 0 ]
[]
[]
[ "euclidean_distance", "python" ]
stackoverflow_0074384907_euclidean_distance_python.txt
Q: Python-3 Tkinter checkbuttons in different classes activated together It happened with checkbuttons in different clases. It can be seen by running this code and clicking in any checkbutton: from tkinter import * import constant class Frame1(Frame): def __init__(self, parent): Frame.__init__(se...
Python-3 Tkinter checkbuttons in different classes activated together
It happened with checkbuttons in different clases. It can be seen by running this code and clicking in any checkbutton: from tkinter import * import constant class Frame1(Frame): def __init__(self, parent): Frame.__init__(self, parent, bg="lightgray") self.parent = parent se...
[ "I MUST add a variable to store the checkbutton data:\nBefore:\nself.cboton[row1]=Checkbutton(self, padx=7, relief=RIDGE,text=t, onvalue=1, offvalue=0)\n\nAfter:\nself.CheckVar[row1]=IntVar()\nself.cboton[row1]=Checkbutton(self, padx=7, relief=RIDGE, variable = self.CheckVar[row1], text=t, ...
[ 0 ]
[]
[]
[ "python", "tkinter", "tkinter.checkbutton" ]
stackoverflow_0074374288_python_tkinter_tkinter.checkbutton.txt
Q: libssl.so.3: cannot open shared object file: No such file or directory I have provisioned a vanila centos and then executed the following commands: conda create --name an-env python=3.9 conda activate an-env conda install -c conda-forge sentence-transformers I am trying to import a hugging face library: from sen...
libssl.so.3: cannot open shared object file: No such file or directory
I have provisioned a vanila centos and then executed the following commands: conda create --name an-env python=3.9 conda activate an-env conda install -c conda-forge sentence-transformers I am trying to import a hugging face library: from sentence_transformers import SentenceTransformer import os In a centos 8 machi...
[ "I got the idea from @CharlesDuffy as he mentioned You need to have the same version of OpenSSL installed that your software was compiled against \nI uninstalled the library using conda uninstall sentence-transformers. And then installed with pip install -U sentence-transformers.\nThis solves the issue.\n", "I ra...
[ 1, 1 ]
[]
[]
[ "centos8", "python", "python_3.x" ]
stackoverflow_0073430846_centos8_python_python_3.x.txt
Q: SQLAlchemy - Multithreading Best Practices - Packet sequence number wrong I'm tring to make a clean Flask App which use SQLAlchemy and Multi-Threading. I've read the doc : https://docs.sqlalchemy.org/en/14/orm/contextual.html#thread-local-scope but can't manage to make it work successfully. SQL Alchemy is initate ...
SQLAlchemy - Multithreading Best Practices - Packet sequence number wrong
I'm tring to make a clean Flask App which use SQLAlchemy and Multi-Threading. I've read the doc : https://docs.sqlalchemy.org/en/14/orm/contextual.html#thread-local-scope but can't manage to make it work successfully. SQL Alchemy is initate directly at the app init.py file with something like that : db = SQLAlchemy(app...
[ "Looks like maybe you are duplicating the scoped session already provided by flask sqlalchemy. You can probably use db.session directly. Although you have to clean it up yourself when the thread ends or at regular intervals with db.session.remove() because it isn't within a request like flask expects. Why are yo...
[ 0, 0 ]
[]
[]
[ "flask_sqlalchemy", "multithreading", "pymysql", "python", "sqlalchemy" ]
stackoverflow_0074379021_flask_sqlalchemy_multithreading_pymysql_python_sqlalchemy.txt
Q: Cast a dataframe to text following a hierarchical structure I am working in Jupyter Notebook and I have a dataframe like this df = pd.DataFrame({'Parent': ['Stay home', "Stay home","Stay home", 'Go outside', "Go outside"], 'Child' : ['Severe weather', "raining", "Windy", 'Sunny', "Good weather"], 'Child1': ['', "s...
Cast a dataframe to text following a hierarchical structure
I am working in Jupyter Notebook and I have a dataframe like this df = pd.DataFrame({'Parent': ['Stay home', "Stay home","Stay home", 'Go outside', "Go outside"], 'Child' : ['Severe weather', "raining", "Windy", 'Sunny', "Good weather"], 'Child1': ['', "some rain", "extreme windy", "very hot", ""]}) Parent C...
[ "Definitely not the most elegant way but I think it does the thing:\nall=[]\nfor i in df.index:\n for j,text in enumerate(df.iloc[i]):\n if j==0:\n all.append(f'{text}\\n')\n elif j==1:\n all.append(f'\\t{text}\\n')\n elif j==2:\n all.append(f'\\t\\t{text}\\n...
[ 1 ]
[]
[]
[ "dataframe", "hierarchical_data", "pandas", "python", "python_3.x" ]
stackoverflow_0074386647_dataframe_hierarchical_data_pandas_python_python_3.x.txt
Q: Odoo15 custom module creation I just created my new custom module, but I'd like to have the form view present in the module. I used the scaffold method to drag all the required files for the module, but when I try to affect the file view.xml so I can reflect the fields I already have included It gives me an error ...
Odoo15 custom module creation
I just created my new custom module, but I'd like to have the form view present in the module. I used the scaffold method to drag all the required files for the module, but when I try to affect the file view.xml so I can reflect the fields I already have included It gives me an error and I don't know how to solve it. T...
[ "Please try to read error (log)\nExternal ID not found in the system: secondmodule.model_secondmodule_secondmodule\nThat means : odoo can't find this id that exist in your code in action server in \"ref\" attribute .. so make sure you have a model with this name 'model_secondmodule_secondmodule' and it's file added...
[ 0 ]
[]
[]
[ "odoo_15", "python", "xml" ]
stackoverflow_0070987708_odoo_15_python_xml.txt
Q: Issue in web scraping using Selenium and driver.get() I am trying to scrape this url but the url I enter in the driver.get() gets changed when the program runs and chrome page is opened. What can be causing it to change? I want to open this link and get specific things but the url changes and it displays error bec...
Issue in web scraping using Selenium and driver.get()
I am trying to scrape this url but the url I enter in the driver.get() gets changed when the program runs and chrome page is opened. What can be causing it to change? I want to open this link and get specific things but the url changes and it displays error because this class doesnot exist on the changed url. Here's my...
[ "The URL is changed by the site. You can not change its behavior. It is redirecting users with new sessions to the search instead of the page of a hotel.\nAs a workaround I can suggest to click the hotel name in search:\ndriver.find_element(By.XPATH, '//div[text()=\"Hotel One Bahawalpur\"]').click\n\nput this line ...
[ 0 ]
[]
[]
[ "python", "selenium", "selenium_webdriver" ]
stackoverflow_0074386547_python_selenium_selenium_webdriver.txt
Q: PyCharm. Unexpected argument(s) Possible callees I write in PyCharm and get a bug (in line "func(dict_data)"): Unexpected argument(s) Possible callees: A.foo(dict_data: dict) A.bar(dict_data: dict). Is it a PyCharm bug or am I doing something wrong? PyCharm 2020.3 class A: def __init__(self): ...
PyCharm. Unexpected argument(s) Possible callees
I write in PyCharm and get a bug (in line "func(dict_data)"): Unexpected argument(s) Possible callees: A.foo(dict_data: dict) A.bar(dict_data: dict). Is it a PyCharm bug or am I doing something wrong? PyCharm 2020.3 class A: def __init__(self): self.functions = { "foo": self...
[ "func is actually a variable in your code, but you are calling it as a function which does not exist there, so PyCharm is guessing what function you might want to use instead which can accommodate dict_data as it's argument.\n1\nThis 'def function_name(arguments : datatype)' in the pic is how function is identified...
[ 1, 1, 0, 0 ]
[]
[]
[ "arguments", "pycharm", "python" ]
stackoverflow_0065372118_arguments_pycharm_python.txt
Q: Converting Time Format without using strptime I've been tasked with printing yesterday's, today's and tomorrow's date. The task itself is very simple, but i wanted to also change the way the date is displayed. I would like to display the date as day/month/year I've tried the ways proposed online but they don't wor...
Converting Time Format without using strptime
I've been tasked with printing yesterday's, today's and tomorrow's date. The task itself is very simple, but i wanted to also change the way the date is displayed. I would like to display the date as day/month/year I've tried the ways proposed online but they don't work for me, fex. strptime apparently cannot be an att...
[ "I'm not sure why you don't want to use strftime, but if you absolutely wanted a different way, try altering your last three lines to this:\nprint(f\"Yesterday : {yesterday.day}/{yesterday.month}/{yesterday.year}\")\nprint(f\"Today : {today.day}/{today.month}/{today.year}\")\nprint(f\"Tomorrow : {tomorrow.day}/{tom...
[ 2 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074386807_python_python_3.x.txt
Q: Inserting data into Popup with Django In my Django project, I want to have the institution selection selected from a list, for this I created a model for the institution name and I want the user to enter it as a pop-up window or a list selection for this: models.py class Institution(models.Model): institutionName ...
Inserting data into Popup with Django
In my Django project, I want to have the institution selection selected from a list, for this I created a model for the institution name and I want the user to enter it as a pop-up window or a list selection for this: models.py class Institution(models.Model): institutionName = models.CharField(max_length=200,null=True...
[ "Django provides the form field ModelChoiceField. When this field of a form is rendered, it will by default generate a <select> with <option> for each instance in a queryset.\nYou can either transform this using Javascript, or you can write (or look for) your own widget to use with this field, to generate the HTML ...
[ 0 ]
[]
[]
[ "django", "html", "javascript", "python" ]
stackoverflow_0074386222_django_html_javascript_python.txt
Q: How to limit strings in Pandas row by row using apply and lambda? I have the following dataframe: # initialize list of lists data = [['1', "Tag1, Tag323, Tag36"], ['2', "Tag11, Tag212"], ['4', "Tag1, Tag12, Tag3, Tag324"]] # Create the pandas DataFrame df = pd.DataFrame(data, columns = ['ID', 'Tag']) print(df) ...
How to limit strings in Pandas row by row using apply and lambda?
I have the following dataframe: # initialize list of lists data = [['1', "Tag1, Tag323, Tag36"], ['2', "Tag11, Tag212"], ['4', "Tag1, Tag12, Tag3, Tag324"]] # Create the pandas DataFrame df = pd.DataFrame(data, columns = ['ID', 'Tag']) print(df) ID Tag 1 Tag1, Tag323, Tag36 2 Tag11, Tag212 4 ...
[ "len_ = len('Tag1, Tag2, Tag3') \ndf['Tag'] = [x if len(x)<len_ else \"Tag1, Tag2 ..\" for x in df['Tag'] ]\n\nYou can choose your own length.\nOutput:\n ID Tag\n0 1 Tag1, Tag2 ..\n1 2 Tag1, Tag2\n2 4 Tag1, Tag2 ..\n\n", "The ol’ split and join Methods might just work here. I’ll write the whol...
[ 1, 1, 1, 1, 1 ]
[]
[]
[ "lambda", "pandas", "python", "string" ]
stackoverflow_0074386694_lambda_pandas_python_string.txt
Q: Python - Loop through a list of players and make them play a game So I'm trying to make a game in python where you register players at the start and then can play games of odd or even. I wanted a system where the game would loop over for each player and once ever player within the list has been gone through it ope...
Python - Loop through a list of players and make them play a game
So I'm trying to make a game in python where you register players at the start and then can play games of odd or even. I wanted a system where the game would loop over for each player and once ever player within the list has been gone through it opens the menu again. There is a list named players and the following code...
[ "So I ended up fixing it with some tweaking of the code, turns out I had forgotten to add a loop around where the next player would be asked the question so this is what I now have that is working.\nindex = 0\n for index in range(len(players)):\n print(\"Hey\", players[index], \"Odd (o) or Even (e)?\")\n ...
[ 0 ]
[]
[]
[ "loops", "python", "python_3.x" ]
stackoverflow_0074384176_loops_python_python_3.x.txt
Q: Python - Creating a pdf with tables and table titles I am trying to use Python to create multiple pdf files each containing 3 tables (each with text wrapping within the cells as well as a title at the top of the table). I am having difficulty finding the perfect library to use. The closest I have got is using the ...
Python - Creating a pdf with tables and table titles
I am trying to use Python to create multiple pdf files each containing 3 tables (each with text wrapping within the cells as well as a title at the top of the table). I am having difficulty finding the perfect library to use. The closest I have got is using the fpdf "multi_cell" function, and using a tutorial I got a s...
[ "def alarms_summary(self):\n PDF .set_font(\"Arial\", size=8, style=\"B\")\n PDF .cell(180, 4, 'ALARMS SUMMARY', 1, 0, 'L')\n PDF .Ln()\n alarms_summary_col_names = [\"Alarm Time\", \"Description\"]\n PDF .set_font(\"Arial\", size=6, style=\"B\")\n for col_name in range(Len(alarms_summary_col_name...
[ 1 ]
[]
[]
[ "fpdf", "pdf", "python", "python_3.x" ]
stackoverflow_0071253856_fpdf_pdf_python_python_3.x.txt
Q: Dash Plotly, unable to download the processed excel file on button click I'm trying to build small dash App that lets the user download an Excel that is generated through the following function: import base64 import io import dash from dash.dependencies import Input, Output, State from dash import dcc,html import ...
Dash Plotly, unable to download the processed excel file on button click
I'm trying to build small dash App that lets the user download an Excel that is generated through the following function: import base64 import io import dash from dash.dependencies import Input, Output, State from dash import dcc,html import plotly.express as px import pandas as pd app = dash.Dash() app = dash.Dash(pre...
[ "I think you're missing a callback, try adding the following:\n@app.callback(\n Output(\"download\", \"data\"),\n [Input(\"btn\", \"n_clicks\")],\n prevent_initial_call=True,\n)\ndef func(n_clicks):\n return dcc.send_data_frame(df2.to_csv, \"mydf.csv\")\n\n" ]
[ 2 ]
[]
[]
[ "html", "pandas", "plotly_dash", "python" ]
stackoverflow_0074387012_html_pandas_plotly_dash_python.txt
Q: Fill out the form and save it in db base I am working on a Django project and I want to fill out a form and save the data in the db database and then be able to show it on another page, I managed to create the form, following some tutorials, but it does not write me anything in the database. Here's how I currently...
Fill out the form and save it in db base
I am working on a Django project and I want to fill out a form and save the data in the db database and then be able to show it on another page, I managed to create the form, following some tutorials, but it does not write me anything in the database. Here's how I currently have things: forms.py from django import ...
[ "In forms.py:\nYou have imported wrong model name:\nchange this\nfrom .models import AusenciasForm\n\nTo this:\nfrom .models import AusenciasFormulario\n\nAnd in views.py file:\nYou have not added any orm query so that's why it is not saving in db.\nviews.py :\nDo this:\ndef index(request):\n ausencias_formulari...
[ 0 ]
[]
[]
[ "database", "django", "forms", "python" ]
stackoverflow_0074386850_database_django_forms_python.txt
Q: How to select specific csv files for specified date range from a folder in python? I have a folder (existing in the same directory as the python script) with a lot of csv files starting from 1st Jan to 31st Dec and I want to read only specific csv files within a certain date range from the folder into python and l...
How to select specific csv files for specified date range from a folder in python?
I have a folder (existing in the same directory as the python script) with a lot of csv files starting from 1st Jan to 31st Dec and I want to read only specific csv files within a certain date range from the folder into python and later appending the files into a list. The files are named as below and there are files f...
[ "I would have a different approach for more flexibility\nimport os\nfrom datetime import datetime\nfrom pprint import pprint\n\n\ndef quick_str_to_date(s: str) -> datetime:\n return datetime.strptime(s, \"%Y-%m-%d\")\n\n\ndef get_file_by_date_range(path: str, startdate: datetime or str, enddate: datetime or str)...
[ 1, 0 ]
[]
[]
[ "dataframe", "python", "regex" ]
stackoverflow_0074386583_dataframe_python_regex.txt
Q: negative lookbehind when filtering pandas columns Consider this simple example import pandas as pd df = pd.DataFrame({'good_one' : [1,2,3], 'bad_one' : [1,2,3]}) Out[7]: good_one bad_one 0 1 1 1 2 2 2 3 3 In this artificial example I would lik...
negative lookbehind when filtering pandas columns
Consider this simple example import pandas as pd df = pd.DataFrame({'good_one' : [1,2,3], 'bad_one' : [1,2,3]}) Out[7]: good_one bad_one 0 1 1 1 2 2 2 3 3 In this artificial example I would like to filter the columns that DO NOT start with bad. I c...
[ "Solution if need remove columns names starting by bad:\ndf = pd.DataFrame({'good_one' : [1,2,3],\n 'not_bad_one' : [1,2,3],\n 'bad_one' : [1,2,3]})\n\n\n#https://stackoverflow.com/a/5334825/2901002\ndf1 = df.filter(regex=r'^(?!bad).*$')\nprint (df1)\n good_one not_bad_one\n0 ...
[ 3 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074387130_pandas_python.txt
Q: Specify GOOGLE APPLICATION CREDENTIALS in Airflow So I am trying to orchestrate a workflow in Airflow. One task is to read GCP Cloud Storage, which needs me to specify the Google Application Credentials. I decided to create a new folder in the dag folder and put the JSON key. Then I specified this in the dag.py fi...
Specify GOOGLE APPLICATION CREDENTIALS in Airflow
So I am trying to orchestrate a workflow in Airflow. One task is to read GCP Cloud Storage, which needs me to specify the Google Application Credentials. I decided to create a new folder in the dag folder and put the JSON key. Then I specified this in the dag.py file; os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "dag...
[ "You can create a connection to Google Cloud from Airflow webserver admin menu. In this menu you can pass the Service Account key file path.\n\nIn this picture, the keyfile Path is /usr/local/airflow/dags/gcp.json.\nBeforehand you need to mount your key file as a volume in your Docker container with the previous pa...
[ 1, 0 ]
[]
[]
[ "airflow", "google_cloud_platform", "python" ]
stackoverflow_0074380932_airflow_google_cloud_platform_python.txt
Q: Can't install Noise module I was trying to install the Noise module (https://pypi.org/project/noise/) with PIP, but it showed me this... Collecting noise Using cached https://files.pythonhosted.org/packages/18/29/bb830ee6d934311e17a7a4fa1368faf3e73fbb09c0d80fc44e41828df177/noise-1.2.2.tar.gz Installing collected p...
Can't install Noise module
I was trying to install the Noise module (https://pypi.org/project/noise/) with PIP, but it showed me this... Collecting noise Using cached https://files.pythonhosted.org/packages/18/29/bb830ee6d934311e17a7a4fa1368faf3e73fbb09c0d80fc44e41828df177/noise-1.2.2.tar.gz Installing collected packages: noise Running setup.py ...
[ "Installing python libs that require c++ compilation on windows can be a pain. Fortunately, the community has a very helpful contributor from the University of California, Irvine, Chris Gohlke that hosts a number of pre-compiled wheels for windows. And lucky for us, noise is one of those pre-compiled wheels. Go ...
[ 9, 0 ]
[]
[]
[ "installation", "module", "noise", "pip", "python" ]
stackoverflow_0053365282_installation_module_noise_pip_python.txt
Q: PYTHON - grep command: wrong output, exit status 2 I trying to find a Pattern in specific large files (GB) in subfolders I am runnging Python code. tried.... FILE_PATH=/folder1/FILE.txt - OK, absolute path with open (FILE_PATH, "r") as FILE: for index, x in enumerate(FILE): if re.findall(".*TEXT.*", x): ...
PYTHON - grep command: wrong output, exit status 2
I trying to find a Pattern in specific large files (GB) in subfolders I am runnging Python code. tried.... FILE_PATH=/folder1/FILE.txt - OK, absolute path with open (FILE_PATH, "r") as FILE: for index, x in enumerate(FILE): if re.findall(".*TEXT.*", x): ...takes too much time... another way in Bash ...
[ "You could try to use os.popen(), which should mimic and return the result you see when using the bash command:\nimport os\nFILE_PATH = \"/folder1/FILE.txt\"\nresults = os.popen(f\"grep -a 'TEXT' {FILE_PATH}\").read()\nprint(results)\n\n" ]
[ 1 ]
[]
[]
[ "binary", "encode", "grep", "python", "subprocess" ]
stackoverflow_0074386989_binary_encode_grep_python_subprocess.txt
Q: Running a python script from a python script Imagine I have Python script, called 'script1.py', which simplies prints "Hello". I want to define a second script, 'script2.py' that runs 'script1.py'. 'script2.py' would return something like 'run('script1.py')'. In PowerShell, I then want to write something like pyth...
Running a python script from a python script
Imagine I have Python script, called 'script1.py', which simplies prints "Hello". I want to define a second script, 'script2.py' that runs 'script1.py'. 'script2.py' would return something like 'run('script1.py')'. In PowerShell, I then want to write something like python3 script2.py and return "Hello". Any easy way o...
[ "In script1.py:\nprint ('hello')\n\nin script2.py:\nimport script1\n\nRunning script2 yields:\nhello\n\n" ]
[ 1 ]
[]
[]
[ "powershell", "python", "python_3.x", "shell" ]
stackoverflow_0074387165_powershell_python_python_3.x_shell.txt
Q: Running output of Python in html in Djngo I am working on a django project. In the app's views.py I am having some outputs that I am storing in a dictionary. The views.py looks like this: from django.shortcuts import render def allblogs(request): a = request.GET['a'] b = request.GET['b'] return rende...
Running output of Python in html in Djngo
I am working on a django project. In the app's views.py I am having some outputs that I am storing in a dictionary. The views.py looks like this: from django.shortcuts import render def allblogs(request): a = request.GET['a'] b = request.GET['b'] return render(request, 'blog/allblogs.html', {'a': a, 'b':...
[ "{{a}} is used whenever we are showing something as a variable from views\n{% .. %} is used for conditional purposes like if we are writing for loops or if conditions or even inside some buttons we can use this as parameter to perform routing operations \n", "With that last error, you're mixing up tags {% somethi...
[ 1, 0, 0, 0 ]
[]
[]
[ "django", "html", "python", "python_3.x" ]
stackoverflow_0061726389_django_html_python_python_3.x.txt
Q: Find first and last element in each pandas DataFrame row given an order for that row I have a pandas DataFrame with values in columns A, B, C, and D and want to determine for every row the first and last non-zero column. BUT the order of the elements is not the same for all rows. It is determined by columns item_0...
Find first and last element in each pandas DataFrame row given an order for that row
I have a pandas DataFrame with values in columns A, B, C, and D and want to determine for every row the first and last non-zero column. BUT the order of the elements is not the same for all rows. It is determined by columns item_0, item_1 and item_2. While I can easily do this by applying a function to every row this b...
[ "Here is a fully vectorized numpy approach. It's not very complex but has quite a few steps so I also provided a commented version of the code:\ncols = ['A', 'B', 'C', 'D']\na = df[cols].to_numpy()\n\nidx = df.filter(like='item_').replace({k:v for v,k in enumerate(cols)}).to_numpy()\nb = a[np.arange(len(a))[:,None]...
[ 4, 1, 1, 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0072213691_pandas_python.txt
Q: how sum two tensors with difference shapes_pytorch I have two tensors with these shapes: a_tensor : torch.Size([64, 37]) b_tensor : torch.Size([64, 300]) how can I sum them (a_tensor+b_tensor ) and pad a_tensor with zeros to be size of [64,300]? For example, a_tensor is [[1 , 2 , 3],[3 , 2 , 1]] with shape of ([2...
how sum two tensors with difference shapes_pytorch
I have two tensors with these shapes: a_tensor : torch.Size([64, 37]) b_tensor : torch.Size([64, 300]) how can I sum them (a_tensor+b_tensor ) and pad a_tensor with zeros to be size of [64,300]? For example, a_tensor is [[1 , 2 , 3],[3 , 2 , 1]] with shape of ([2 , 3]) and b_ensor is [[10 , 20 , 30 , 40] , [40 , 30 , ...
[ "You can do so using nn.functional.pad:\n>>> a = torch.rand(64, 37)\n>>> b = torch.rand(64, 300)\n\nMeasure the padding amount:\n>>> r = b.size(-1) - a.size(-1)\n\nPad and sum:\n>>> tf.pad(a, (0,0,r,0)) + b\n\n" ]
[ 1 ]
[]
[]
[ "python", "pytorch" ]
stackoverflow_0074386760_python_pytorch.txt
Q: How to open a opj file in python? I am trying to open an opj (from Origin, the data visualization tool) in python but I haven't been able to find a way to know if it's even possible. I downloaded PyWavefront to give it a shot but it seems that it was directed to Blender files instead, which are also opj apparently...
How to open a opj file in python?
I am trying to open an opj (from Origin, the data visualization tool) in python but I haven't been able to find a way to know if it's even possible. I downloaded PyWavefront to give it a shot but it seems that it was directed to Blender files instead, which are also opj apparently.
[ "You can have a look at this project, although you have to compile the tool yourself.\n" ]
[ 0 ]
[]
[]
[ "data_visualization", "pandas", "python" ]
stackoverflow_0072633077_data_visualization_pandas_python.txt
Q: With clause does not work as expected in Oracle Database I'm using pypika to build some queries. It used to work great but I have an issue with subqueries on an oracle database. The query reads as follow fake_query = Query().from_(my_table).where(my_table.ID == "12345").select(my_table.ID) QN = AliasedQuery("fake...
With clause does not work as expected in Oracle Database
I'm using pypika to build some queries. It used to work great but I have an issue with subqueries on an oracle database. The query reads as follow fake_query = Query().from_(my_table).where(my_table.ID == "12345").select(my_table.ID) QN = AliasedQuery("fake_query_with") query = ( Query() .with_(fake_query, "f...
[ "I don't know Python nor Pypika, but - from Oracle's point of view - this is what's wrong here: usage of (evil!) double quotes.\nIn Oracle, by default, all \"identifiers\" (table names, column names, procedures, functions ...) are stored into the data dictionary in UPPERCASE. Then, you can reference them any way yo...
[ 1, 1 ]
[]
[]
[ "oracle", "pypika", "python", "sql" ]
stackoverflow_0074383037_oracle_pypika_python_sql.txt
Q: Dataflow: Stream pub/sub messages from different project I have a pub/sub topic in project A. I would now like to stream messages from that topic into a dataflow pipeline running in a different project B. I have followed the example at https://cloud.google.com/pubsub/docs/stream-messages-dataflow and everything wo...
Dataflow: Stream pub/sub messages from different project
I have a pub/sub topic in project A. I would now like to stream messages from that topic into a dataflow pipeline running in a different project B. I have followed the example at https://cloud.google.com/pubsub/docs/stream-messages-dataflow and everything works when the topic is in the same project as the dataflow pipe...
[ "You might need to create a subscription in the source project (A), so your dataflow job (in the project B) takes the messages from that subscription (from the project A).\nThen yoou find out a service account under which your dataflow job is runnig (in the project B). Presumably that service account is in the proj...
[ 1, 0 ]
[]
[]
[ "apache_beam", "google_cloud_dataflow", "google_cloud_platform", "publish_subscribe", "python" ]
stackoverflow_0074378534_apache_beam_google_cloud_dataflow_google_cloud_platform_publish_subscribe_python.txt
Q: IndexError: list index out of range in chained callback How the second dropdown list can automatically show value based on the first dropdown list? Only one value is available for the second dropdown list based on the selection in first dropdown list. Sample data: data = {'Product ID': {0: 'P1', 1: 'P2', 2: 'P3',...
IndexError: list index out of range in chained callback
How the second dropdown list can automatically show value based on the first dropdown list? Only one value is available for the second dropdown list based on the selection in first dropdown list. Sample data: data = {'Product ID': {0: 'P1', 1: 'P2', 2: 'P3', 3: 'P4', 4: 'P5', 5: 'P1', 6: 'P2', 7: 'P3', 8: 'P4', 9: 'P5...
[ "I think firstly you need to add options in your layout first and then use callback to return new options. Please refer below code:\nimport pandas as pd\nimport numpy as np\nimport plotly.express as px\nimport dash\nimport dash_html_components as html\nimport dash_core_components as dcc\nfrom dash.dependencies impo...
[ 0 ]
[]
[]
[ "plotly_dash", "python" ]
stackoverflow_0074385282_plotly_dash_python.txt
Q: Python text adventure: Consecutive if-query in while Loops I'm coding a text adventure in python. In general: I want people to be able to make mistakes for putting in the wrong answers. If they not write a valid answer like "1" or "2" they should get send back with a loop until they put in a viable answer without ...
Python text adventure: Consecutive if-query in while Loops
I'm coding a text adventure in python. In general: I want people to be able to make mistakes for putting in the wrong answers. If they not write a valid answer like "1" or "2" they should get send back with a loop until they put in a viable answer without breaking the whole code and to start all over again. As mentione...
[ "Here's an idea of how I'd structure your program and what things you should look at and learn to properly implement what you want to do.\nI'd recommend you use a state machine and putting all your logic into a dictionary (which later you could read from a json file, so you can create different adventures without h...
[ 0 ]
[]
[]
[ "adventure", "if_statement", "loops", "python", "while_loop" ]
stackoverflow_0074387217_adventure_if_statement_loops_python_while_loop.txt
Q: Keep unique values with only 1 instance I have the following dataset: Col_A Amounts 0 A 100 1 B 200 2 C 500 3 D 100 4 E 500 5 F 300 The output I am trying to achieve is to basically remove all values based on the "Amounts" column which have a duplicate value and to ...
Keep unique values with only 1 instance
I have the following dataset: Col_A Amounts 0 A 100 1 B 200 2 C 500 3 D 100 4 E 500 5 F 300 The output I am trying to achieve is to basically remove all values based on the "Amounts" column which have a duplicate value and to keep only the rows where there is one unique ...
[ "You are close, need keep=False for remove all duplicates per Amounts column:\nprint (df.drop_duplicates(subset=['Amounts'], keep=False))\n Col_A Amounts\n1 B 200\n5 F 300\n\n", "Less straight forward than the previous answer, but if you want to be able keep the rows that appear n times, you c...
[ 1, 0 ]
[]
[]
[ "duplicates", "pandas", "python", "unique" ]
stackoverflow_0074387257_duplicates_pandas_python_unique.txt
Q: Rotation matrix is changed with scipy.spatial.transform.Rotation I perform PCA on 3D images after semantic segmentation to define the orientation of objects and align them. It works fine, produced eigenvectors form a valid rotation matrix that aligns objects correctly But I would like to have rotation angles from ...
Rotation matrix is changed with scipy.spatial.transform.Rotation
I perform PCA on 3D images after semantic segmentation to define the orientation of objects and align them. It works fine, produced eigenvectors form a valid rotation matrix that aligns objects correctly But I would like to have rotation angles from the matrix. When I use scipy.spatial.transform.Rotation.from_matrix an...
[ "Solved!\nMy fault, the matrix contains reflection, so it is not a proper rotational matrix.\nhttps://github.com/scipy/scipy/issues/17324\n" ]
[ 0 ]
[]
[]
[ "3d", "matrix", "python", "rotation", "scipy" ]
stackoverflow_0074265765_3d_matrix_python_rotation_scipy.txt
Q: how to transform a loop for with if condition into comprehension dictionary I'm not at ease with comprehension dictionaries I would like to transform this loop into a dictionary comprehension. Thanks for your help dico={} for key in ['good','very good','bad','very bad','not good not bad']: if key in['good','very...
how to transform a loop for with if condition into comprehension dictionary
I'm not at ease with comprehension dictionaries I would like to transform this loop into a dictionary comprehension. Thanks for your help dico={} for key in ['good','very good','bad','very bad','not good not bad']: if key in['good','very good']: dico[key]='green' else: dico[key]='red' print(dico) Here is w...
[ "I think you you're looking to this\ndico = {key: ['red', 'green'] [key in ['good','very good']] for key in ['good','very good','bad','very bad','not good not bad']}\n\n", "Try this syntax\n{k:'green' if k in ['good','very good'] else 'red' for k in ['good','very good','bad','very bad','not good not bad']}\n\n" ]
[ 0, 0 ]
[]
[]
[ "dictionary_comprehension", "for_loop", "if_statement", "python" ]
stackoverflow_0074387376_dictionary_comprehension_for_loop_if_statement_python.txt
Q: Retrieve the 1st occurrence of a sub string in a list of strings I have a list that contains multiple strings as follows: ls= ['CN=text_1 ,CN =Users,OU=text_12,DC=eample,DC=com', 'CN=text_3433,CN=users,OU=text4,DC=example,DC=com'] Now I want to get a list that should contain only the 1st occurrence of CN=. So the...
Retrieve the 1st occurrence of a sub string in a list of strings
I have a list that contains multiple strings as follows: ls= ['CN=text_1 ,CN =Users,OU=text_12,DC=eample,DC=com', 'CN=text_3433,CN=users,OU=text4,DC=example,DC=com'] Now I want to get a list that should contain only the 1st occurrence of CN=. So the resultant list should look like: ls_f = ['text_1','text_3433'] I am ...
[ "You might want to split the string at , and then take the first part after CN= -\ncn = [i.split(',')[0][3:].strip() for i in ls if i.startswith('CN=')]\n\nHere we are checking if the string starts with CN=, if it does, split the string at , and then from the first part, extract the part after CN=\nOutput:\n['text_...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0074387435_python.txt
Q: Python memory model and pointers I'm learning Python and got confused about memory model of Python a variable contains the memory address of the object to which it refers This reads like Python variables are actually pointers, since they only directly contains memory address of the actual object instances. Then ...
Python memory model and pointers
I'm learning Python and got confused about memory model of Python a variable contains the memory address of the object to which it refers This reads like Python variables are actually pointers, since they only directly contains memory address of the actual object instances. Then what does Python do when I call a vari...
[ "To answer to your interrogation: \"why then a=100;b=a;a=101 doesn't change values of b\", I remind you that even in C, it would not be the case. The fact that a and b are pointers, and made equal, doesn't mean that changes to a impacts b. They are not alias. *a and *b may be, but not a and b.\nIn C, something quit...
[ 0 ]
[]
[]
[ "pointers", "python" ]
stackoverflow_0074386649_pointers_python.txt
Q: Select Column with multiple condition pandas Get column value with condition from another column. For example I have dataframe Package Drink Age Name Full Tea 50 Toni Half Tea 50 Stark Full Tea 20 Evan Half Tea 50 Christ Quarter Tea 61 Mark Quarter Tea ...
Select Column with multiple condition pandas
Get column value with condition from another column. For example I have dataframe Package Drink Age Name Full Tea 50 Toni Half Tea 50 Stark Full Tea 20 Evan Half Tea 50 Christ Quarter Tea 61 Mark Quarter Tea 18 Rufallo Then I want to get name only '''if...
[ "Use DataFrame.loc for select only column name with mask, for check membership use Series.isin:\nsubdf= df.loc[df[\"Package\"].isin([ 'Full','Half']) & (df['Age'] >= 50), 'Name']\nprint (subdf)\n0 Toni\n1 Stark\n3 Christ\nName: Name, dtype: object\n\nYour solution with multiple | for bitwise OR:\nsubdf=...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074387557_dataframe_pandas_python.txt
Q: torch Parameter grad return none I want to implement learned size quantization algorithm. And I create a quante Linear layer class QLinear(nn.Module): def __init__(self, input_dim, out_dim, bits=8): super(QLinear, self).__init__() # create a tensor requires_grad=True self.up = 2 ** bits...
torch Parameter grad return none
I want to implement learned size quantization algorithm. And I create a quante Linear layer class QLinear(nn.Module): def __init__(self, input_dim, out_dim, bits=8): super(QLinear, self).__init__() # create a tensor requires_grad=True self.up = 2 ** bits - 1 self.down = 0 sel...
[ "The issue is that you are passing dequant_weight through data attribute of your parameter which ends up not being registered by autograd. A simple alternative would be to handle weight as a nn.Parameter and apply a linear operator manually in the forward definition directly with the computed weight dequant_weight....
[ 1 ]
[]
[]
[ "deep_learning", "python", "pytorch", "quantization" ]
stackoverflow_0074387343_deep_learning_python_pytorch_quantization.txt
Q: importing json file from github into python. Getting Error: JSONDecodeError: Expecting value: line 7 column 1 (char 6) Here is my code: import re, json, requests url = 'https://github.com/caminofinancial/data-eng-take-home/blob/master/prequalresult.json' resp = requests.get(url) resp_parsed = re.sub(r'^jsonp\d+\...
importing json file from github into python. Getting Error: JSONDecodeError: Expecting value: line 7 column 1 (char 6)
Here is my code: import re, json, requests url = 'https://github.com/caminofinancial/data-eng-take-home/blob/master/prequalresult.json' resp = requests.get(url) resp_parsed = re.sub(r'^jsonp\d+\(|\)\s+$', '', resp.text) data = json.loads(resp_parsed) print(data) And I Got the error : JSONDecodeError: Expecting value...
[ "Use the raw GitHub URL when you need to access the file directly. You can get it by clicking the 'Raw' button on the page. \n url = 'https://raw.githubusercontent.com/caminofinancial/data-eng-take-home/master/prequalresult.json'\n resp = requests.get(url)\n data = json.loads(resp.text)\n print(data)\n\n", "fro...
[ 7, 0 ]
[]
[]
[ "json", "python", "sql" ]
stackoverflow_0060219180_json_python_sql.txt
Q: How to group unrelated exceptions together with ExceptionGroup I use try...except blocks as below for regular exception handling in Python. try: <do something> except: <handle the error> How can I use ExceptionGroup to propagate a group of unrelated exceptions together? A: try: #code) pass except (V...
How to group unrelated exceptions together with ExceptionGroup
I use try...except blocks as below for regular exception handling in Python. try: <do something> except: <handle the error> How can I use ExceptionGroup to propagate a group of unrelated exceptions together?
[ "try:\n #code)\n pass\nexcept (ValueError, ZeroDivisionError):\n #code\n pass \n\n" ]
[ 0 ]
[]
[]
[ "concurrency", "exception", "python", "try_except" ]
stackoverflow_0074387519_concurrency_exception_python_try_except.txt
Q: Data frame - adding index with count of values under each column df1 = pd.DataFrame({'Region': ['E', 'E', 'U', 'E'], 'Id': [1,None,None,None], 'Ids': [1,2,3,4]}) df2 = pd.DataFrame({'Region': ['E', 'U', 'U', 'E'], 'Id': [1,2,3,4], 'Ids': [1,2,3,4]}) x = df1.groupby(['Region']).count() y = df2.groupby(['Region']).c...
Data frame - adding index with count of values under each column
df1 = pd.DataFrame({'Region': ['E', 'E', 'U', 'E'], 'Id': [1,None,None,None], 'Ids': [1,2,3,4]}) df2 = pd.DataFrame({'Region': ['E', 'U', 'U', 'E'], 'Id': [1,2,3,4], 'Ids': [1,2,3,4]}) x = df1.groupby(['Region']).count() y = df2.groupby(['Region']).count() c = pd.concat([x['Id'], y['Id']], axis=1, keys=['Here', 'Ther...
[ "You can add it simply by defining it as the sum:\nc.loc['Total'] = c.sum()\n\nOutput:\n Here There\nRegion \nE 1.0 2.0\nU 0.0 2.0\nTotal 1.0 4.0\n\n", "c.loc['total'] = c.sum(axis=0)\n\nOutput:\n Here There\nRegion \nE 1 2\nU 0 2\ntotal 1 4\n\n...
[ 1, 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074387691_dataframe_pandas_python.txt
Q: twosum leetcode problem, why this solution doesn't work? "Index out of range" The problem give an array of integers 'nums' and an integer 'target', return indices of the two numbers such that they add up to target. Example: Input: nums = [2,7,11,15], target = 9 Output: [0,1] Explanation: Because nums[0] + nums[1] ...
twosum leetcode problem, why this solution doesn't work? "Index out of range"
The problem give an array of integers 'nums' and an integer 'target', return indices of the two numbers such that they add up to target. Example: Input: nums = [2,7,11,15], target = 9 Output: [0,1] Explanation: Because nums[0] + nums[1] == 9, we return [0, 1]. class Solution: def twoSum(self, nums: List[int], targ...
[ "When you do for x in nums you actually iterate over values, not indices, so then nums[x] is actually x[2], then x[7] - which is out of range of the list.\nTry for x in range(0, len(nums)) instead, same goes for y.\nOr, you can also keep iterating over values and just do if (x + y) == target.\n", "Not pretty but...
[ 0, 0 ]
[]
[]
[ "list", "python", "range" ]
stackoverflow_0074387351_list_python_range.txt
Q: iloc'ing one level of a multiindex I have multiindex dataframe, something like: df = pd.DataFrame(index = pd.MultiIndex.from_product([['mike', 'matt', 'dave', 'frank', 'larry'], range(10)])) df['foo']="bar" df.index.names=['people', 'socket'] What I'd like to do is iloc-slice all the rows associated with the firs...
iloc'ing one level of a multiindex
I have multiindex dataframe, something like: df = pd.DataFrame(index = pd.MultiIndex.from_product([['mike', 'matt', 'dave', 'frank', 'larry'], range(10)])) df['foo']="bar" df.index.names=['people', 'socket'] What I'd like to do is iloc-slice all the rows associated with the first three people in the index. IE: retrie...
[ "Here you go:\ndf = pd.DataFrame(index = pd.MultiIndex.from_product([['mike', 'matt', 'dave', 'frank', 'larry'], range(10)], names=['people', 'socket']))\ndf['foo']=\"bar\"\ndf.index.names=['people', 'socket']\n# get rows\nselect_rows = df.loc[['mike', 'matt', 'dave']]\n\nOutput:\npeople socket \nmike 0 ...
[ 2, 0, 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0056340906_pandas_python.txt
Q: Get data from qtablewidget in 2d array I have Qtablewidget and a PushButton. When a button pressed I want that data(flot number) in Qtablewidget exctracted/trandformed(dont know how to describe it) in 2d array and then pass to previously made function. I created a cycle: def DoSomething(self): for i in...
Get data from qtablewidget in 2d array
I have Qtablewidget and a PushButton. When a button pressed I want that data(flot number) in Qtablewidget exctracted/trandformed(dont know how to describe it) in 2d array and then pass to previously made function. I created a cycle: def DoSomething(self): for i in range(self.ui.Level_N.rowCount()): ...
[ "You should create the \"top level\" list outside of the main loop, and each \"row\" outside of the inner one.\nNote that you should always check that item() is valid before calling its methods, because unless the item value was edited by the user (or set in Designer) or explicitly set with setItem(), it will retur...
[ 0 ]
[]
[]
[ "pyqt5", "python" ]
stackoverflow_0074387509_pyqt5_python.txt
Q: What's the alternate of echo for windows cmd? I want to override the args of a model in the "comp1" folder by passing the parameters to the main file in the "component" folder and hence need some mechanism to pass the override args. I've run it before in wsl2 and it worked.I want it to work in windows cmd and henc...
What's the alternate of echo for windows cmd?
I want to override the args of a model in the "comp1" folder by passing the parameters to the main file in the "component" folder and hence need some mechanism to pass the override args. I've run it before in wsl2 and it worked.I want it to work in windows cmd and hence need some workaround or an alternate of echo to b...
[ "According to this answer, you shouldn't place space before and after = in the set command.\nIt would work if you rewrote the MLproject into this:\nname: KNN_main\nconda_env: conda.yml\n\nentry_points:\n main:\n parameters:\n hydra_options:\n description: Hydra values to override\n type: str\...
[ 0 ]
[]
[]
[ "devops", "hydra_core", "mlflow", "python", "windows" ]
stackoverflow_0074313881_devops_hydra_core_mlflow_python_windows.txt
Q: Waiting for elements to become interactible reliably I'm a noob and trying to automate some online form filling in a certain site. My problem is that some buttons need some time before clicking them, otherwise they don't work (but no error!, execution continues). My only solution so far is to add a time.sleep(6) b...
Waiting for elements to become interactible reliably
I'm a noob and trying to automate some online form filling in a certain site. My problem is that some buttons need some time before clicking them, otherwise they don't work (but no error!, execution continues). My only solution so far is to add a time.sleep(6) before these buttons but this is not ideal. I am trying to ...
[ "You definitely can reduce all your code to a single line of\ndef Send_Click_dk(bywhat,what): \n WebDriverWait(browser, 10).until(EC.element_to_be_clickable(browser.find_element(bywhat, what))).click()\n\nSend_Click_dk(By.NAME, \"mainpanel_parentSection_1b0a0b\")\n\nvisibility_of expected condition includes p...
[ 1 ]
[]
[]
[ "expected_condition", "python", "selenium", "selenium_webdriver", "webdriverwait" ]
stackoverflow_0074387734_expected_condition_python_selenium_selenium_webdriver_webdriverwait.txt
Q: Find groups with not not a number I have a dataframe containing some coded answers to a questionnaire. Each row is a respondent and each column is a question. Not every person responded to the same questions because of some skip logic in the questionnaire therefore I have a sparse dataframe cotaining NaN import pa...
Find groups with not not a number
I have a dataframe containing some coded answers to a questionnaire. Each row is a respondent and each column is a question. Not every person responded to the same questions because of some skip logic in the questionnaire therefore I have a sparse dataframe cotaining NaN import pandas as pd import numpy as np # create...
[ "If you like to keep the information, of which questions were answered by each person, one possible approach is to drop all columns (=questions) first that do not meet the criteria. In a second step you could store the questions that were answered in a separate result column and group it.\nimport pandas as pd\nimpo...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python", "python_itertools" ]
stackoverflow_0074385933_dataframe_pandas_python_python_itertools.txt
Q: calling a python module that reads a file so my program import a utils that reads a file in the same directory as the utils. However, this utils function can be called from different files from different directory. Project | |-module_1: |__ init __.py | file.py <--- calls util.load_file() |module_2: ...
calling a python module that reads a file
so my program import a utils that reads a file in the same directory as the utils. However, this utils function can be called from different files from different directory. Project | |-module_1: |__ init __.py | file.py <--- calls util.load_file() |module_2: | __ init __.py | utils.py <---- load...
[ "__file__ contains the path to the current file. Check it with print(__file__).\npathlib from Pythons standard library can be used to construct an absolute path to the data file.\nimport pathlib\n\nprint(pathlib.Path(__file__))\nprint(pathlib.Path(__file__).parent)\nprint(pathlib.Path(__file__).parent / 'file.txt')...
[ 0 ]
[]
[]
[ "package", "python" ]
stackoverflow_0074387243_package_python.txt
Q: RuntimeError: the layer has never been called and thus has no defined output shape. tensorflow I am trying to run the following code but it is throwing this error This code is taken from Kaggle site for a competition. from keras.applications.vgg16 import VGG16 as PTModel from keras.applications.inception_resnet_v2...
RuntimeError: the layer has never been called and thus has no defined output shape. tensorflow
I am trying to run the following code but it is throwing this error This code is taken from Kaggle site for a competition. from keras.applications.vgg16 import VGG16 as PTModel from keras.applications.inception_resnet_v2 import InceptionResNetV2 as PTModel from keras.applications.inception_v3 import InceptionV3 as PTMo...
[ "I have solved the problem, the problem was simple and something more I have taken the input shape as -> 224 , 224 , 3, you can take for your own choice.\nfrom keras.applications.vgg16 import VGG16 as PTModel\nfrom keras.applications.inception_resnet_v2 import InceptionResNetV2 as PTModel\nfrom keras.applications.i...
[ 0 ]
[]
[]
[ "keras", "python", "tensorflow" ]
stackoverflow_0074380383_keras_python_tensorflow.txt
Q: Upload File to OpenStack Using Python Swift Client Would someone have a complete example of how to upload a file to an OpenStack container using the Python Swift client: https://pypi.org/project/python-swiftclient/ Something that would include: Authenticate against the OpenStack instance Call the relevant functio...
Upload File to OpenStack Using Python Swift Client
Would someone have a complete example of how to upload a file to an OpenStack container using the Python Swift client: https://pypi.org/project/python-swiftclient/ Something that would include: Authenticate against the OpenStack instance Call the relevant function(s) to upload the file to an OpenStack container Thank...
[ "I was able to do it with the following piece of code\nfrom keystoneauth1 import session\nfrom keystoneauth1.identity import v3\nfrom swiftclient.client import Connection\n\n# Create a password auth plugin\nauth = v3.Password(\n auth_url='https://cloud.company.com:5000/v3/',\n username='myaccount',\n passw...
[ 0 ]
[]
[]
[ "openstack", "python", "swift", "upload" ]
stackoverflow_0074387034_openstack_python_swift_upload.txt
Q: trying to determine whether the first and last letters of a string are the same first and last () is used to call a function that determines whether the first and last letters of a string are the same def first_and_last(message): if message[0] == message[-1]: return True elif message[0] != message[...
trying to determine whether the first and last letters of a string are the same
first and last () is used to call a function that determines whether the first and last letters of a string are the same def first_and_last(message): if message[0] == message[-1]: return True elif message[0] != message[-1]: return False elif message == "": return False print(first...
[ "The issue is with the empty string input \"\", as python cannot find a 0th or -1st index of this, it throws an error before reaching the elif statement. If you check for an empty string first, then you will avoid this error:\ndef first_and_last(message):\n if message == \"\":\n return False\n elif mes...
[ 1 ]
[]
[]
[ "python", "string" ]
stackoverflow_0074387843_python_string.txt