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: Replace a value found in a Df with a value found in a Dictionary I am having troubles writing an operation that replaces values found in a df with values that are found in a dictionary. Here's what I have: import pandas as pd d=[['English','Alabama','bob','smith']] df=pd.DataFrame(d,columns=["lang",'state','first...
Replace a value found in a Df with a value found in a Dictionary
I am having troubles writing an operation that replaces values found in a df with values that are found in a dictionary. Here's what I have: import pandas as pd d=[['English','Alabama','bob','smith']] df=pd.DataFrame(d,columns=["lang",'state','first','last']) filename='temp' error_dict={} error_dict[filename]={} rep...
[ "Loop through the dict and replace each column one at a time:\nfor colname, value in replace_dict.items():\n df[colname] = df[colname].map(value)\n\nEDIT full answer:\nimport pandas as pd\n\nd=[['English','Alabama','bob','smith']]\ndf=pd.DataFrame(d,columns=[\"lang\",'state','first','last'])\n\nreplace_dict={\"s...
[ 0 ]
[]
[]
[ "dictionary", "pandas", "python" ]
stackoverflow_0074309206_dictionary_pandas_python.txt
Q: Django 'x' object has no attribute 'get_form' I have a generic DetailView and I'm trying to do a form for the comment of an user after I display the details of the model but I keep getting the error 'ProductFeedbackView' object has no attribute 'get_form'. I don't know if the templates have any problem because th...
Django 'x' object has no attribute 'get_form'
I have a generic DetailView and I'm trying to do a form for the comment of an user after I display the details of the model but I keep getting the error 'ProductFeedbackView' object has no attribute 'get_form'. I don't know if the templates have any problem because the error is in the view when I try to get the form i...
[ "You need to inherit the form view mixing like so:\nfrom django.views.generic.edit import FormMixin\n\nclass ProductFeedbackView(DetailView, FormMixin):\n ...\n\nAs per django classy class based views guide:\nhttps://ccbv.co.uk/projects/Django/4.1/django.views.generic.edit/FormView/\nHowever, mixing a detail vie...
[ 0 ]
[]
[]
[ "django", "django_views", "python" ]
stackoverflow_0074309121_django_django_views_python.txt
Q: How to create a loop for a search query using set coordinates from a data frame, while creating a new data frame for each search result? I a really new to programming and can't seem to find a way to create a loop that matches what I am looking for. [] conv_stores1 = yelp_api.search_query(categories= 'convenience s...
How to create a loop for a search query using set coordinates from a data frame, while creating a new data frame for each search result?
I a really new to programming and can't seem to find a way to create a loop that matches what I am looking for. [] conv_stores1 = yelp_api.search_query(categories= 'convenience stores', latitude=30.62779075491679, longitude=-96.33484825223623, limit=50) this is the code I am trying to loop over. conv_stores1 = yelp_api...
[ "If I understand you correctly, to put it simply, you need something like the following;\nAssuming your dataframe is called \"df\":\nfor i in range(df.shape[0]):\n conv_stores = yelp_api.search_query(categories= 'convenience stores', df['latitude'].iloc[i], df['longitude'].iloc[i], limit=50)\n print (conv_sto...
[ 0 ]
[]
[]
[ "api", "dataframe", "loops", "python" ]
stackoverflow_0074309117_api_dataframe_loops_python.txt
Q: python regex to catch text between innermost brackets I need a regex that extracts text between a starting and an ending char (open and close bracket in my example) if and only if such text is made up of a specified number of words. I'm using this regex (really simple) that works in this case. re.findall("(?<=\()...
python regex to catch text between innermost brackets
I need a regex that extracts text between a starting and an ending char (open and close bracket in my example) if and only if such text is made up of a specified number of words. I'm using this regex (really simple) that works in this case. re.findall("(?<=\()(.*?)(?=\))", "bla bla (bla bla) bla bla") actual output: ...
[ "If you want to match 2 words that do not contain chars ( and ) between (...) you can use a capture group to get the inner value:\n\\((\\s*[^\\s()]+\\s+[^\\s()]+\\s*)\\)\n\nThe pattern matches:\n\n\\( Match (\n( Capture group 1\n\n\\s* Match optional leading whitespace chars\n[^\\s()]+ Match 1+ non whitespace char...
[ 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074306897_python_regex.txt
Q: How does one run Great Expectations from Docker using a Dockerfile to build the image I am pretty new to Great Expectations (GX) and very new to Docker, and now I am trying to combine the two. I can get a Docker image to build just fine, but when I try to run a container, it fails. I can get my GX Checkpoint to ru...
How does one run Great Expectations from Docker using a Dockerfile to build the image
I am pretty new to Great Expectations (GX) and very new to Docker, and now I am trying to combine the two. I can get a Docker image to build just fine, but when I try to run a container, it fails. I can get my GX Checkpoint to run from both the GX CLI, as well as from a Python file. I have tried to run a docker image u...
[ "If you want to use the image based on python:3.8-slim it looks like what you need is a Docker volume to mount your local version of the great_expectations directory to the container. You can do that by adding -v /usr/app/great_expectations:<your_local_great_expectations_folder> to your docker run command.\n", "I...
[ 0, 0 ]
[]
[]
[ "docker", "dockerfile", "great_expectations", "python", "python_docker" ]
stackoverflow_0074306129_docker_dockerfile_great_expectations_python_python_docker.txt
Q: Problem with python web-scraping when reading a URL using "get" function I have trouble using the "get" function to read the URL taken from cell A1 in the excel file "tennis3.xlsx". I have tried different solutions and I have no idea how to get it to read it and use it to get a webpage response. The problem probab...
Problem with python web-scraping when reading a URL using "get" function
I have trouble using the "get" function to read the URL taken from cell A1 in the excel file "tennis3.xlsx". I have tried different solutions and I have no idea how to get it to read it and use it to get a webpage response. The problem probably starts at at 'sheet["A1"].value'. I have applied this program through visua...
[ "You need to save the changes you made:\nimport requests\nfrom bs4 import BeautifulSoup\nfrom openpyxl import load_workbook\n\nfilename = r\"tennis3.xlsx\"\n\nworkbook = load_workbook(filename=filename)\nsheet= workbook['Sheet1']\nurlcell = sheet[\"A1\"].value\nprint(urlcell)\n\nresponse = requests.get(urlcell)\nwe...
[ 1 ]
[]
[]
[ "python", "web_scraping" ]
stackoverflow_0074309231_python_web_scraping.txt
Q: Use Python (PyAutoGUI) Automation in Windows Server I'm using Python 3.9 and PyAutoGUI to automate some processes in a program. This automation must run on a Windows Server I'm using object recognition, with, buttons, text boxes, mouse and keyboard functions. This automation must run in the Windows Task Scheduler,...
Use Python (PyAutoGUI) Automation in Windows Server
I'm using Python 3.9 and PyAutoGUI to automate some processes in a program. This automation must run on a Windows Server I'm using object recognition, with, buttons, text boxes, mouse and keyboard functions. This automation must run in the Windows Task Scheduler, with elevated privileges and only when the user is logge...
[ "First, you need to troubleshoot/add more info\nwhen running thru the task scheduler, does it run at all?\nif it does run(but not properly), then it's likely an issue with permissions\n" ]
[ 0 ]
[]
[]
[ "opencv", "pyautogui", "python", "rpa", "windows_server" ]
stackoverflow_0074304258_opencv_pyautogui_python_rpa_windows_server.txt
Q: Python Click - variable options. Using context inside decorator Here is a code sample: import click import functools features = { "feature1": { "option11", "option77" }, "feature2": { "option33", "option44" }, } def wrapper(f, opt): @click.option(f"--{opt}") ...
Python Click - variable options. Using context inside decorator
Here is a code sample: import click import functools features = { "feature1": { "option11", "option77" }, "feature2": { "option33", "option44" }, } def wrapper(f, opt): @click.option(f"--{opt}") @functools.wraps(f) def inner(*args, **kwargs): return ...
[ "Okay, I figured the way I was trying to do it was impossible. If the context doens't exist - it doesn't exist. No way around that.\nHere is my solution for dynamic options:\n\nfeatures = {\n \"feature1\": {\n \"option1\": {\"type\": bool, \"help\": \"Option 1 help\"},\n \"option2\": {\"type\": int...
[ 0 ]
[]
[]
[ "python", "python_click" ]
stackoverflow_0074297486_python_python_click.txt
Q: Error when trying to simulate a Lorenz Attractor I got this from a YouTube video: The only issue is, when I run the code a window pops up and then instantly closes, then it displays a message in the terminal saying: Process finished with exit code 0. Can someone help? This was taken from a video by QuantativeBytes...
Error when trying to simulate a Lorenz Attractor
I got this from a YouTube video: The only issue is, when I run the code a window pops up and then instantly closes, then it displays a message in the terminal saying: Process finished with exit code 0. Can someone help? This was taken from a video by QuantativeBytes, search up QuantativeBytes on YouTube. Code: impo...
[ "It is a matter of Indentation. Also on_init should return True:\nclass Application:\n # [...]\n\n def on_init(self):\n # [...]\n\n # Configure the attractor\n self.attractors = LAttractor()\n\n return True\n\n # [...]\n\n def on_execute(self):\n if self.on_init() == F...
[ 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0066893197_pygame_python.txt
Q: Dataframe query rows where date column are the same as name column I have a dataframe looking like this: user user 2022-08-01 Andy 2022-08-04 Mary 2022-08-05 Marc 2022-08-01 Frank Now I want to pick up that rows where Andy an Frank are Users at the same date. The date is the unknown part. It can be many more...
Dataframe query rows where date column are the same as name column
I have a dataframe looking like this: user user 2022-08-01 Andy 2022-08-04 Mary 2022-08-05 Marc 2022-08-01 Frank Now I want to pick up that rows where Andy an Frank are Users at the same date. The date is the unknown part. It can be many more rows and many more dates where that two users are both in t...
[ "df = pd.DataFrame({'date':['2022-08-01','2022-08-04','2022-08-05','2022-08-01'],\n 'user':['Andy','Mary','Marc','Frank']})\n\nYou can do a groupby date and join the user names as a string (sorted by their names, thus there won't be any error.)\ndf_grouped = df.groupby('date').user.apply(lambda x:...
[ 1, 0 ]
[]
[]
[ "dataframe", "python" ]
stackoverflow_0074308962_dataframe_python.txt
Q: why Object is not callable at the second time of execution? I am trying to use run the following code. The code generates output for the first time, however during the 2nd execution returns an error -- TypeError: 'YahooSecurity' object is not callable I am not sure why this is happening. I am using the following p...
why Object is not callable at the second time of execution?
I am trying to use run the following code. The code generates output for the first time, however during the 2nd execution returns an error -- TypeError: 'YahooSecurity' object is not callable I am not sure why this is happening. I am using the following python package https://pypi.org/project/pypf/ My code is - import ...
[ "because YahooSecurity = YahooSecurity(i, True, True, '1d',1) replaces the object with the result of calling the object (or, more likely, the class). So, the second time you use it, it's not a class anymore. Just make it somethin like yahoo_security = YahooSecurity(i, True, True, '1d',1)\n" ]
[ 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074309445_python_python_3.x.txt
Q: How to use Selenium in Python to update multiple page elements without refreshing the DOM to avoid StaleElementReferenceException? I have a school website html page that is used for publishing homework that looks something like this: When you click on each lesson, a javascript div element pops up where you write ...
How to use Selenium in Python to update multiple page elements without refreshing the DOM to avoid StaleElementReferenceException?
I have a school website html page that is used for publishing homework that looks something like this: When you click on each lesson, a javascript div element pops up where you write in the homework and submit via a button. I wanted to automate populating the entire table. The problem is that after each homework entry...
[ "Every time selenium finds an element it creates an identifier for it. So when you submit something on that page, the page reloads and all the elements become new for selenium (they have now other identifiers).\nTo resolve the problem you need to find all the elements again after submit.\nSo first of all you need t...
[ 0 ]
[]
[]
[ "dom", "python", "selenium", "staledataexception", "staleelementreferenceexception" ]
stackoverflow_0074308957_dom_python_selenium_staledataexception_staleelementreferenceexception.txt
Q: Set the values of rows from one dataframe based on the rows of another dataframe I made a mock-up example to illustrate my problem, naturally, what I am working with is something way more complex. Reading the example will make everything easier to understand but my goal is to use the row reference values of one da...
Set the values of rows from one dataframe based on the rows of another dataframe
I made a mock-up example to illustrate my problem, naturally, what I am working with is something way more complex. Reading the example will make everything easier to understand but my goal is to use the row reference values of one dataframe to set the values of a new column of another dataframe. That, taking my exampl...
[ "You can use map for this.\ndf1['z'] = df1['x1'].map(df2.set_index('x2')['y2'])\n\n x1 y1 z\n0 0.0 0.000000 0.00\n1 0.0 0.071429 0.00\n2 0.0 0.142857 0.00\n3 3.0 0.214286 0.25\n4 3.0 0.285714 0.25\n5 3.0 0.357143 0.25\n6 6.0 0.428571 0.50\n7 6.0 0.500000 0.50\...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074309427_dataframe_pandas_python.txt
Q: Getting error: jinja2.exceptions.TemplateSyntaxError: expected token 'end of print statement', got '=' i am trying to set select field choices using jinja in html but getting error. can someone help me with the mistake i am making in writing {{ seat_form.seat.choices = Available_seat_lst }} line of code. Error is ...
Getting error: jinja2.exceptions.TemplateSyntaxError: expected token 'end of print statement', got '='
i am trying to set select field choices using jinja in html but getting error. can someone help me with the mistake i am making in writing {{ seat_form.seat.choices = Available_seat_lst }} line of code. Error is showing on the same line. tried {% seat_form.seat.choices = Available_seat_lst %} and {%set seat_form.seat.c...
[ "Set the value before you call seat_form.seat() and don't use {{ }}. It's for printing values. Use {% %} instead.\nThis should work:\n<br>\n{{ seat_form.seat.label() }}\n{% set seat_form.seat.choices = Available_seat_lst %}\n{{ seat_form.seat(class=\"form-select\") }}\n<br><br>\n\n" ]
[ 0 ]
[]
[]
[ "flask", "jinja2", "python", "rendering", "select" ]
stackoverflow_0074308143_flask_jinja2_python_rendering_select.txt
Q: How can I make pyautogui wait for an image to appear, and then after it appears and an action is completed, wait for the next image to appear I've been using pyautogui to automate some browser stuff like so: time.sleep(1) locationscs = pyautogui.locateOnScreen('scs.PNG', confidence=.8) pyau...
How can I make pyautogui wait for an image to appear, and then after it appears and an action is completed, wait for the next image to appear
I've been using pyautogui to automate some browser stuff like so: time.sleep(1) locationscs = pyautogui.locateOnScreen('scs.PNG', confidence=.8) pyautogui.click(locationscs) time.sleep(1) This is not ideal because sometimes, the page doesn't load in time and I don't make the click. I've...
[ "import pyautogui\nimport time\n\n#for first image\n\nwhile True:\n time.sleep(1) #prevents lag and waits for new image\n image1 = pyautogui.locateOnScreen('ii.PNG', confidence=.7)#first image location\n if image1: #if the image is found\n print('found image clicking...')\n pyautogui.click(im...
[ 0 ]
[]
[]
[ "pyautogui", "python", "python_3.x" ]
stackoverflow_0074289379_pyautogui_python_python_3.x.txt
Q: REACT + DJANGO - CORS Errors After Login - CORS header ‘Access-Control-Allow-Origin’ missing We have a React + Django application on GCP App Engine instances and we are facing a CORS error when fetching data through our REST API. We have already installed and configured the CORS package for the Django Rest Framewo...
REACT + DJANGO - CORS Errors After Login - CORS header ‘Access-Control-Allow-Origin’ missing
We have a React + Django application on GCP App Engine instances and we are facing a CORS error when fetching data through our REST API. We have already installed and configured the CORS package for the Django Rest Framework in our django application: ` ALLOWED_HOSTS = [ 'xxxxxxxxxxxx.appspot.com', 'yyyyyyyyyy...
[ "After some debugging, we realized that the CORS error was actually masking another issue, related with the size of the cookies, that exceeded the allowed limit of the server.\nThe only way to view this error was to go to the network tab and preview the response data in Firefox, in Edge the response was empty, and ...
[ 0 ]
[]
[]
[ "django", "django_rest_framework", "python", "reactjs" ]
stackoverflow_0074299335_django_django_rest_framework_python_reactjs.txt
Q: How to interpret color intensity in displot? I am new to seaborn, and I was going through documentation and examples. I have attached the plot below. How can we interpret the color intensity in this plot? A: We will not be able to really understand what those bluish colours mean unless there is a scale or a guid...
How to interpret color intensity in displot?
I am new to seaborn, and I was going through documentation and examples. I have attached the plot below. How can we interpret the color intensity in this plot?
[ "We will not be able to really understand what those bluish colours mean unless there is a scale or a guide which represents the mapping of colors to some attributes of the data.\nThus, the best way to do this would be to add a cbar=True argument in sns.displot, along with the title of the colorbar to make sure the...
[ 1 ]
[]
[]
[ "displot", "matplotlib", "python", "seaborn" ]
stackoverflow_0074306976_displot_matplotlib_python_seaborn.txt
Q: Python is not printing List functions I wrote this code while i was in my university class. However, when i go to run the program nothing is printing into the console. def create_list(): return ["Playstation", "Xbox", "Steam", "iOS", "Googleplay"] def get_info(my_list): return (my_list[0], my_list[-2], le...
Python is not printing List functions
I wrote this code while i was in my university class. However, when i go to run the program nothing is printing into the console. def create_list(): return ["Playstation", "Xbox", "Steam", "iOS", "Googleplay"] def get_info(my_list): return (my_list[0], my_list[-2], len(my_list)) def get_partial(my_list): ...
[ "You need to remove the '()' from the if statement, and make \"main\" lowercase, like below:\nif __name__ == \"__main__\":\n" ]
[ 0 ]
[]
[]
[ "append", "function", "list", "python" ]
stackoverflow_0074309470_append_function_list_python.txt
Q: pyautogui.locateCenterOnScreen() is getting incorrect coordinates when looking for the Spotify pause button Trying to locate the Spotify pause button on my screen using pyautogui just to develop my python knowledge. I run the script below and a screenshot of the pause button is saved, but the mouse moves to the bo...
pyautogui.locateCenterOnScreen() is getting incorrect coordinates when looking for the Spotify pause button
Trying to locate the Spotify pause button on my screen using pyautogui just to develop my python knowledge. I run the script below and a screenshot of the pause button is saved, but the mouse moves to the bottom right of the screen, miles away from where the button is. import pyautogui input("Move to target button") ...
[ "import pyautogui\nimport time\nwhile True:\n time.sleep(1) #prevents lag and waits for new image\n spotify = pyautogui.locateOnScreen('spotify.PNG', confidence=.7,grayscale=False) #image location\n if spotify: #if the image is found\n print('found image clicking...')\n pyautogui.click(spotif...
[ 0 ]
[]
[]
[ "opencv", "pyautogui", "python", "python_3.x" ]
stackoverflow_0074256634_opencv_pyautogui_python_python_3.x.txt
Q: Selected column in a pandas dataframe to newline delimited json df = pd.DataFrame({"id":[123,465,978,505,567], "feature":[1.1,1.2,1.2,6.7,8.9]}) I try to only save a json file just for the id column. However, it seems that there is no column selection in the to_json function. My ideal result is like {"id":123} {"i...
Selected column in a pandas dataframe to newline delimited json
df = pd.DataFrame({"id":[123,465,978,505,567], "feature":[1.1,1.2,1.2,6.7,8.9]}) I try to only save a json file just for the id column. However, it seems that there is no column selection in the to_json function. My ideal result is like {"id":123} {"id":465} {"id":978} {"id":505} {"id":567} I've tried method 1: df.to...
[ "Try to use df[[\"id\"]]:\ndf[[\"id\"]].to_json(\"temp.json\", orient=\"records\", lines=True)\n\nsaves temp.json:\n{\"id\":123}\n{\"id\":465}\n{\"id\":978}\n{\"id\":505}\n{\"id\":567}\n\n" ]
[ 1 ]
[]
[]
[ "json", "python" ]
stackoverflow_0074309526_json_python.txt
Q: socket tcp package no delay I want to send two packages one by one: conn.send('package_1') conn.send('package_2') The question is it will be assembled in one package, because the interval of these to package is small. I don't want this to happen. So I found s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1),...
socket tcp package no delay
I want to send two packages one by one: conn.send('package_1') conn.send('package_2') The question is it will be assembled in one package, because the interval of these to package is small. I don't want this to happen. So I found s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1), but it still doesn't work. In cl...
[ "That's how TCP works. TCP is not a message protocol. If you want a message protocol, you have to implement (or choose) one.\n" ]
[ 0 ]
[]
[]
[ "python", "sockets", "tcp" ]
stackoverflow_0074303916_python_sockets_tcp.txt
Q: Selecting similar options from two different div-class dropdowns using Selenium WebDriver (Python) Im working on a project that involves submitting an online form. Currently I have no issues logging into the website, and accessing the form, however, there are two drop down menus in the form which my code condition...
Selecting similar options from two different div-class dropdowns using Selenium WebDriver (Python)
Im working on a project that involves submitting an online form. Currently I have no issues logging into the website, and accessing the form, however, there are two drop down menus in the form which my code conditionally struggles to fill out. One is asking for the state of a home address, and the second is asking for ...
[ "If two elements have the same locators you can use indexes to tell selenium with which one of them you want to work.\nFor the second dropdown's option you can use (By.XPATH, \"(//*[text() ='California'])[2]\")\n" ]
[ 0 ]
[]
[]
[ "drop_down_menu", "python", "selenium", "selenium_chromedriver", "webforms" ]
stackoverflow_0074308852_drop_down_menu_python_selenium_selenium_chromedriver_webforms.txt
Q: Splitting files from a single folder to multiple sub folders in specific ratio using Python I have bulk files in a directory. I need to split (divide) them into three folders randomly in the ratio 66:17:17. I normally do this manually but takes a lot of time. ie Source(directory): 100 files Destination(directory) ...
Splitting files from a single folder to multiple sub folders in specific ratio using Python
I have bulk files in a directory. I need to split (divide) them into three folders randomly in the ratio 66:17:17. I normally do this manually but takes a lot of time. ie Source(directory): 100 files Destination(directory) with Sub directories: Training:66 files(random) Validation:17 files(random) Testing...
[ "Not that pretty, but it should work\nimport os\nimport random\nimport shutil\n\n\nclass Target:\n def __init__(self, target_path: str, ratio: int, number_of_source_files: int):\n self._target_path = target_path\n self._max = int(number_of_source_files / 100 * ratio)\n self._counter = 0\n\n ...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074103233_python.txt
Q: What is the best way to return a variable or call a function to maximize code reuse? I was wondering if i could get some input from some season python exports, i have a couple questions I am extracting data from an api request and calculating the total vulnerabilities, what is the best way i can return this data ...
What is the best way to return a variable or call a function to maximize code reuse?
I was wondering if i could get some input from some season python exports, i have a couple questions I am extracting data from an api request and calculating the total vulnerabilities, what is the best way i can return this data so that i can call it in another function what is the way i can add up all the vulnerabil...
[ "If you have a lot of parameters to pass, consider using a dict to combine them. Then you can just return the dict and pass it along to the next function that needs that data. Another approach would be to create a class and either access the variables directly or have helper functions that do so. The latter is a ...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074309591_python.txt
Q: Using Python to fill in a web text box with an If Statement Hello everyone I am new to Python and I wanted to see if someone can help. I am trying to automate text input on a website. I am trying to run a code that says if the input box is empty to type 4.00 if not to press the down key. An image is provided to he...
Using Python to fill in a web text box with an If Statement
Hello everyone I am new to Python and I wanted to see if someone can help. I am trying to automate text input on a website. I am trying to run a code that says if the input box is empty to type 4.00 if not to press the down key. An image is provided to help understand the issue. from selenium import webdriver from sele...
[ "You're checking for a space character in the if statement.\nReplace\nif send_click = \" \":\nwith\nif send_click == \"\":\n", "As it's said if send_click = \" \" needs to be replaced by if send_click = \"\"\nAnd, maybe it's a copy-paste error but there is a mistake with the identation (that's how Python understa...
[ 0, 0 ]
[]
[]
[ "pyautogui", "python", "selenium" ]
stackoverflow_0074308593_pyautogui_python_selenium.txt
Q: python/django create a text file and make user download it does anyone know if there is a way to create a text file who can be downloaded by an user of my django site ? Can someone help me or send me tutorials to show me how to do it ? Thanks A: Donsimething like this: from django.http import HttpResponse def d...
python/django create a text file and make user download it
does anyone know if there is a way to create a text file who can be downloaded by an user of my django site ? Can someone help me or send me tutorials to show me how to do it ? Thanks
[ "Donsimething like this:\nfrom django.http import HttpResponse\n\ndef download_view(request):\n \n file_data = your_textfile \n response = HttpResponse(file_data, content_type='application/text charset=utf-8')\n response['Content-Disposition'] = 'attachment; filename=\"testfile.txt\"'\n return response\n\...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074305864_django_python.txt
Q: I need help changing the color of text in python Hey I need help with coloring the text in a program I am making. It is a password program and I am trying to make the denied and granted red and green when they appear. Here is the program so far: password = {"joseph":"jesus"} print ("Welcome") username = input("Pl...
I need help changing the color of text in python
Hey I need help with coloring the text in a program I am making. It is a password program and I am trying to make the denied and granted red and green when they appear. Here is the program so far: password = {"joseph":"jesus"} print ("Welcome") username = input("Please enter your username: ") if username in password: ...
[ "Python's standard input and output, as used by the input and print functions, is just plain text. It can output to an Unix terminal or Windows console, to a window in your IDE, or to a text file. And plain text doesn't have colors.\nHowever, almost all modern-day terminals and consoles do have ways to do things li...
[ 2, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0029597333_python.txt
Q: Python code isnt producing output, please advice on why I have an assignment to write code to print a number in words. I'm new to coding, so please do not judge my code... . so ive written the code am fairly certain it should work, but it isnt producing an output. there's no syntax error apparently either. Please ...
Python code isnt producing output, please advice on why
I have an assignment to write code to print a number in words. I'm new to coding, so please do not judge my code... . so ive written the code am fairly certain it should work, but it isnt producing an output. there's no syntax error apparently either. Please advice. If theres a better code please let me know as well bu...
[ "The reason for the infinite loop that is preventing your output from displaying, is that on the very last loop iteration, the following line will set y to 0:\ny=n//10**(x-1)\n\nAnd since right after that you have the following:\nif y==0:\n continue\n\nThat means your code will infinitely loop on the last loop i...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0074309695_python.txt
Q: How to find Bragg reflexes fast with numpy? For x-ray diffraction one needs to find the solutions to the so called Laue-Equation G_hkl - k_in + |k_in|*(sin(theta) cos(phi) , sin(theta) sin(phi) , cos(theta))=0 where G_hkl is a given 3 dimensional vector, k_in can be chosen as (0,0,1) and theta and phi are free par...
How to find Bragg reflexes fast with numpy?
For x-ray diffraction one needs to find the solutions to the so called Laue-Equation G_hkl - k_in + |k_in|*(sin(theta) cos(phi) , sin(theta) sin(phi) , cos(theta))=0 where G_hkl is a given 3 dimensional vector, k_in can be chosen as (0,0,1) and theta and phi are free parameters to fulfill the equation. In a typical exp...
[ "There's a dependency as Ghkl is being updated at each iteration and re-used at the next. The corresponding closed form might be difficult to trace out. So, I would focus on improving the performance on the rest of the code inside that innermost loop.\nNow, there we are calculating norm_vec, which I think could be ...
[ 3, 0 ]
[]
[]
[ "numpy", "performance", "python", "scientific_computing" ]
stackoverflow_0039726139_numpy_performance_python_scientific_computing.txt
Q: How do i randomize my answers, so that it syncs with the if else i am trying to built a little game with random. In this game you have the choice to answer a question with "a1" and "a2" for "Answer 1" and "Answer 2". At the End it should print, if you chose the right Answer. To make it a little more dynamic i want...
How do i randomize my answers, so that it syncs with the if else
i am trying to built a little game with random. In this game you have the choice to answer a question with "a1" and "a2" for "Answer 1" and "Answer 2". At the End it should print, if you chose the right Answer. To make it a little more dynamic i want that the Option for "a1" and "a2" is not always the same. Like the An...
[ "\nYou don't don't need to from random import randint because already you import random library.\n\nif op1 == \"a1\", op2 == \"a2\", else: op1 will be \"a2\" and you need to add op2 = \"a1\".Because of you have 2 options in list.\n\n\nAnd your code will be like this :\nimport random\n\nlist = [\"a1\", \"a2\"]\nop1 ...
[ 0, 0 ]
[]
[]
[ "python", "random" ]
stackoverflow_0074309587_python_random.txt
Q: loop through folders and copy similar folders with python how can i loop through folders and copy out subfolders with the same name from every folder and save it in a unique folder with the name. so A in test 1 and in test 2 should be copied to a folder called A and loop through doing the same for the rest i was a...
loop through folders and copy similar folders
with python how can i loop through folders and copy out subfolders with the same name from every folder and save it in a unique folder with the name. so A in test 1 and in test 2 should be copied to a folder called A and loop through doing the same for the rest i was able to loop through the main dir and got the dir(te...
[ "Are you looking for something like this?\nimport os, shutil;\n\ndirectory = \"/home/.../test1\";\ndest_dir = \"/home/.../test2\";\n\nfilelist = [];\n\nfor root, dirs, files in os.walk(directory):\n for file in files:\n filelist.append(os.path.join(root,file));\n\nfor subFile in filelist:\n shutil.copy...
[ 1 ]
[]
[]
[ "loops", "operating_system", "python" ]
stackoverflow_0074309628_loops_operating_system_python.txt
Q: Sending outlook mail to multiple users with different email content using python I have tried to automate the outlook mail to multiple recipient with different content, but I keep getting this below error. Error: The above exception was the direct cause of the following exception: Traceback (most recent call last...
Sending outlook mail to multiple users with different email content using python
I have tried to automate the outlook mail to multiple recipient with different content, but I keep getting this below error. Error: The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Pritch\Desktop\email.py", line 19, in <module> print(df['Name'...
[ "The code for sending emails looks good. I don't see anything strange there.\nThe To property of the MailItem class accepts a semicolon-delimited string list of display names for the To recipients for the Outlook item. Make sure that the string is well formatted with a proper encoding.\n" ]
[ 0 ]
[]
[]
[ "email", "office_automation", "outlook", "python", "win32com" ]
stackoverflow_0074306273_email_office_automation_outlook_python_win32com.txt
Q: Won't go back to Stage 0, goes to the next stage instead In this code, the main issue is that if "Full.PNG" is detected, it is supposed to do a few actions and then reset back to Stage 0. However, instead, it does the actions but then goes onto the next Stage. An example of what I mean is that on Stage 3, it detec...
Won't go back to Stage 0, goes to the next stage instead
In this code, the main issue is that if "Full.PNG" is detected, it is supposed to do a few actions and then reset back to Stage 0. However, instead, it does the actions but then goes onto the next Stage. An example of what I mean is that on Stage 3, it detects "Full.PNG" and activates CheckForFull(), causing Stage 3 to...
[ "assign the variable Stage on top of the script:\nimport pyautogui, pydirectinput, random, time, keyboard, ait\n\nStage = 0 # Starting stage, stage for reset.\n\ndef CheckForFull():\n\nIf this does not work, please reply to this answer and send me your error code\n" ]
[ 0 ]
[]
[]
[ "if_statement", "python", "while_loop" ]
stackoverflow_0074309795_if_statement_python_while_loop.txt
Q: Python using basicConfig method to log to console and file I don't know why this code prints to the screen, but not to the file? File "example1.log" is created, but nothing is written there. #!/usr/bin/env python3 import logging logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(me...
Python using basicConfig method to log to console and file
I don't know why this code prints to the screen, but not to the file? File "example1.log" is created, but nothing is written there. #!/usr/bin/env python3 import logging logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(message)s', handlers=[logging.FileHandler("exa...
[ "Try this working fine(tested in python 2.7) for both console and file \n# set up logging to file\nlogging.basicConfig(\n filename='log_file_name.log',\n level=logging.INFO, \n format= '[%(asctime)s] {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s',\n datefmt='%H:%M:%S'\n )\n\n# set up logging...
[ 65, 30, 12, 11, 1, 1 ]
[]
[]
[ "console", "file", "logging", "python", "screen" ]
stackoverflow_0013479295_console_file_logging_python_screen.txt
Q: How to sort sub-items in a list by ascending order to display them in a tuples Lets say I have exactly this list : ["('Jeff', 8)", "('Louis', 9)","('Deandre', 5)"] I want to be able to display in the console exactly this : ('Deandre',5) ('Jeff',8) ('Louis',9) So that the 2nd element of the tuples are in ascending ...
How to sort sub-items in a list by ascending order to display them in a tuples
Lets say I have exactly this list : ["('Jeff', 8)", "('Louis', 9)","('Deandre', 5)"] I want to be able to display in the console exactly this : ('Deandre',5) ('Jeff',8) ('Louis',9) So that the 2nd element of the tuples are in ascending order (5,8,9...) I tried with something like this : sorted(mylist, key=lambda x: x[1...
[ "First parse the strings to tuples using ast.literal_eval, then sort:\nfrom ast import literal_eval\n\nlst = [\"('Jeff', 8)\", \"('Louis', 9)\", \"('Deandre', 5)\"]\n\nout = sorted(map(literal_eval, lst), key=lambda x: x[1])\nprint(*out)\n\nPrints:\n('Deandre', 5) ('Jeff', 8) ('Louis', 9)\n\n" ]
[ 1 ]
[]
[]
[ "lambda", "list", "python", "sorting", "tuples" ]
stackoverflow_0074309820_lambda_list_python_sorting_tuples.txt
Q: Python - Pandas - Fill/Append a Multi-Index DataFrame inside a loop Because I am unable to provide a first draft of code, I would rather describe it in the best possible way: I would like to know how can I create a MultiIndex DataFrame, then fill it inside a loop (where data discovery happens), knowing at each ite...
Python - Pandas - Fill/Append a Multi-Index DataFrame inside a loop
Because I am unable to provide a first draft of code, I would rather describe it in the best possible way: I would like to know how can I create a MultiIndex DataFrame, then fill it inside a loop (where data discovery happens), knowing at each iteration, the Index Levels that should be assign to the Series considered. ...
[ "A possible solution goes like this:\nfilelist_unsorted=glob.glob(r\"*/filen*\", recursive=True)\nfor i, file in enumerate(filelist_unsorted):\n df=pd.read_csv(file)\n #some modifications\n df.drop(columns=['b','c'],inplace=True)\n #optional: add a new column that will serve as an index\n df['new']=r...
[ 0 ]
[]
[]
[ "append", "fill", "for_loop", "multi_index", "python" ]
stackoverflow_0047801393_append_fill_for_loop_multi_index_python.txt
Q: plot multivariate function based on max I would like to create a multivariate function that takes the max value of 2 functions and then to plot it. However by using the max function there is an error when applying the function on the meshgrid. I have tried this on other multivariate function without the max functi...
plot multivariate function based on max
I would like to create a multivariate function that takes the max value of 2 functions and then to plot it. However by using the max function there is an error when applying the function on the meshgrid. I have tried this on other multivariate function without the max function and it worked. import numpy as np import p...
[ "The np.sin and np.cos functions work with arrays and the max function would produce an ambiguous answer (do you want the maximum of both functions or a comparison - numpy doesn't know). I recommend doing the built-in math.sin, math.cos on each of the values in the arrays and compare to get the desired max value .\...
[ 0, 0 ]
[]
[]
[ "arrays", "boolean", "max", "python" ]
stackoverflow_0074304554_arrays_boolean_max_python.txt
Q: Overlay Two Plots in Plotly Using seaborn I can combine two plots with the code below. # LINE PLOT r_30 = r[r['ID']==30] #choosing person 30 g = sns.FacetGrid(r_30, col="VISIT", sharex=False, sharey=False,aspect=2,col_wrap=2,legend_out=True) # 2 columns, legend is outside of plot g.map(sns.lineplot, "DATE_TIME",...
Overlay Two Plots in Plotly
Using seaborn I can combine two plots with the code below. # LINE PLOT r_30 = r[r['ID']==30] #choosing person 30 g = sns.FacetGrid(r_30, col="VISIT", sharex=False, sharey=False,aspect=2,col_wrap=2,legend_out=True) # 2 columns, legend is outside of plot g.map(sns.lineplot, "DATE_TIME", "SBP",color='red',label='SBP',st...
[ "You're off to a good start with subplots, but using Plotly express is a faster option that gets you the same result.\nAlso, please remember to always provide sample data. For now, I created a sample dataset.\nimport pandas as pd\nimport numpy as np\nimport random\n\ndf = pd.DataFrame({'DATE_TIME':pd.date_range('20...
[ 1 ]
[]
[]
[ "plotly", "plotly_dash", "python" ]
stackoverflow_0074303566_plotly_plotly_dash_python.txt
Q: Can't upload to PyPi with Twine I'm trying to upload a python package to PyPi, using the following commands: pip install -e . python setup.py bdist_wheel --universal twine upload --repository-url https://upload.pypi.org/legacy/ dist/* I get this error: HTTPError: 403 Client Error: Invalid or non-existent authent...
Can't upload to PyPi with Twine
I'm trying to upload a python package to PyPi, using the following commands: pip install -e . python setup.py bdist_wheel --universal twine upload --repository-url https://upload.pypi.org/legacy/ dist/* I get this error: HTTPError: 403 Client Error: Invalid or non-existent authentication information. for url: https:/...
[ "EDIT: if you're using Windows, check my other suggestion\nIt looks like some sort of error with the account I was using. The following steps fixed it for me:\n\nCreate a new account\nUpload the package with the new account with twine upload dist/*\nAdd the previous account (that you originally wanted to upload wit...
[ 12, 12, 7, 6, 5, 2, 2, 1, 1, 1, 0, 0 ]
[ "I upload a project but when i viewed on pypi site, it wasn missing readme.md file. I wasn't knowing how to update so i deleted the project, accept some warnings though.\nLastly, I added readme.md file and tried to upload project again but I got this error. So, i headed to pypi site and completely deleted the last ...
[ -1 ]
[ "pypi", "python", "twine" ]
stackoverflow_0046606692_pypi_python_twine.txt
Q: How can I adjust sound on a youtube video [selenium Python] the below is an example of controlling the play button. but how do i control the volume bar? my usual methods dont work. this is what i have now. my usual methods of trying to hit the element is not working. from selenium import webdriver from selenium.we...
How can I adjust sound on a youtube video [selenium Python]
the below is an example of controlling the play button. but how do i control the volume bar? my usual methods dont work. this is what i have now. my usual methods of trying to hit the element is not working. from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys i...
[ "(1) For volume up/down, you can try ARROW_UP and ARROW_DOWN:\nplayer.send_keys(Keys.ARROW_DOWN) \n\n(2) For volume un-mute, you can try send_keys(\"m\"):\nplayer.send_keys(\"m\")\n\nPS: Code below is untested but you could try it for clicking the volume icon. The icon is called Mute (m) but I don't know if it will...
[ 0, 0 ]
[]
[]
[ "automation", "python", "selenium", "video" ]
stackoverflow_0074291098_automation_python_selenium_video.txt
Q: Iterate in a dictionary inside a list of json and get a dataframe I have a file with this structure (it comes from a json): lista = [{'document': {'amount': 20, 'name': 'Peter', 'city': 'Madrid'}, 'highlights': [], 'text_match': 100}, {'document': {'amount': 15, 'name': 'Angel', 'city': 'Barcelona...
Iterate in a dictionary inside a list of json and get a dataframe
I have a file with this structure (it comes from a json): lista = [{'document': {'amount': 20, 'name': 'Peter', 'city': 'Madrid'}, 'highlights': [], 'text_match': 100}, {'document': {'amount': 15, 'name': 'Angel', 'city': 'Barcelona'}, 'highlights': [], 'text_match': 100}, {'document': {'amount': ...
[ "Just edit the for - loop to append not the whole p but p['document']:\nres = []\nfor p in lista:\n res.append(p['document'])\ndf = pd.DataFrame(res)\n\nHope that helped\n" ]
[ 1 ]
[ "Try:\ndf = pd.DataFrame([d[\"document\"] for d in lista])\nprint(df)\n\nPrints:\n amount name city\n0 20 Peter Madrid\n1 15 Angel Barcelona\n2 10 Louis London\n\n" ]
[ -1 ]
[ "json", "loops", "python" ]
stackoverflow_0074309863_json_loops_python.txt
Q: discord.py getting custome server username I started programming my discord bot, it's a default roulette bot, but I asked myself how I could get the server-wide username? message.author returns the real username, but I want the Server-Username A: I believe you are looking for Member.nick, or in your case message...
discord.py getting custome server username
I started programming my discord bot, it's a default roulette bot, but I asked myself how I could get the server-wide username? message.author returns the real username, but I want the Server-Username
[ "I believe you are looking for Member.nick, or in your case message.author.nick\n" ]
[ 0 ]
[]
[]
[ "discord.py", "python" ]
stackoverflow_0074309887_discord.py_python.txt
Q: completely remove rows that contain ID associate with more than one industry I've seen a lot of post on removing duplicates but those don't apply to my case. The idea is I only care about whether the dataset contain IDs associate with more than one industries, if an ID has more than one industry, completely remove...
completely remove rows that contain ID associate with more than one industry
I've seen a lot of post on removing duplicates but those don't apply to my case. The idea is I only care about whether the dataset contain IDs associate with more than one industries, if an ID has more than one industry, completely remove that ID and rows associate with it from the dataset. Can this be done with SQL? P...
[ "You can do:\ndelete from t\nwhere id in (\n select id from t group by id having count(distinct industry) > 1\n)\n\nSee fiddle.\n", "This will select only the rows you are looking for:\nselect *\nfrom data\nwhere ID in (\n select ID \n from data \n group by ID\n having count(distinct Industry) <= 1\n...
[ 0, 0 ]
[]
[]
[ "duplicates", "python", "snowflake_cloud_data_platform", "sql" ]
stackoverflow_0074309755_duplicates_python_snowflake_cloud_data_platform_sql.txt
Q: pandas - creating new rows of combination with value of 0 I have a pandas dataframe like user_id music_id has_rating A a 1 B b 1 and I would like to automatically add new rows for each of user_id & music_id for those users haven't rated, like user_id music_id has_rating A a 1 A b 0 B a 0 B b 1 for each o...
pandas - creating new rows of combination with value of 0
I have a pandas dataframe like user_id music_id has_rating A a 1 B b 1 and I would like to automatically add new rows for each of user_id & music_id for those users haven't rated, like user_id music_id has_rating A a 1 A b 0 B a 0 B b 1 for each of user_id and music_id combination pairs ...
[ "You can use a temporary reshape with pivot_table and fill_value=0 to fill the missing values with 0:\n(df.pivot_table(index='user_id', columns='music_id',\n values='has_rating', fill_value=0)\n .stack().reset_index(name='has_rating')\n )\n\nOutput:\n user_id music_id has_rating\n0 A ...
[ 1, 0 ]
[]
[]
[ "dataframe", "matrix", "pandas", "python", "sparse_matrix" ]
stackoverflow_0074309879_dataframe_matrix_pandas_python_sparse_matrix.txt
Q: Django ManyToMany field object automatically pre-fills I have an PaypalOrder model that is created when someone orders from a website, and it has a ManyToManyField that connects it to multiple OrderItems. Whenever I create a PaypalOrder, it automatically lists every OrderItem that exists in the django admin panel....
Django ManyToMany field object automatically pre-fills
I have an PaypalOrder model that is created when someone orders from a website, and it has a ManyToManyField that connects it to multiple OrderItems. Whenever I create a PaypalOrder, it automatically lists every OrderItem that exists in the django admin panel. How do I only list the objects that I set it to connect to?...
[ "I believe that you are being tricked by the Front end; look again; even when the Django admin displays all the items, only those related to PayPal orders are highlighted.\n" ]
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0070809989_django_python.txt
Q: Python 3.9 Selenium click () does not work (Vimeo) I tried to click the button through selenium, but the website's HTML code seems like it blocks users to do that. (I am new to python and stuffs so not sure what it is.) import selenium from selenium import webdriver from selenium.webdriver.common.keys import Keys ...
Python 3.9 Selenium click () does not work (Vimeo)
I tried to click the button through selenium, but the website's HTML code seems like it blocks users to do that. (I am new to python and stuffs so not sure what it is.) import selenium from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from seleniu...
[ "I think you are trying this:\n# Needed libs\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\n# We create the driver\ndriver = webdriver.Chrome()\n\n# We maximize...
[ 1 ]
[]
[]
[ "html", "python", "selenium", "xpath" ]
stackoverflow_0074309730_html_python_selenium_xpath.txt
Q: Using pd.wide_to_long and having the sep= be parenthesis, getting empty dataframe with the column names only I am trying to do pd.wide_to_long and I want to separate based off of what is inside a parenthesis. I looked up the pandas manual here and the closes example is below. I changed the column names to match so...
Using pd.wide_to_long and having the sep= be parenthesis, getting empty dataframe with the column names only
I am trying to do pd.wide_to_long and I want to separate based off of what is inside a parenthesis. I looked up the pandas manual here and the closes example is below. I changed the column names to match something to what I have. np.random.seed(0) df = pd.DataFrame({'A(weekly_2010)': np.random.rand(3), ...
[ "Try this, remove the trailing close parenthesis and separate on open parenthesis:\ndf.columns = df.columns.str.replace(')','', regex=False)\npd.wide_to_long(df, stubnames=['A', 'B'], i=['id'], j='year', sep='(', suffix='\\w+')\n\nOutput:\n X A B\nid year ...
[ 1, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074309458_dataframe_pandas_python.txt
Q: Disable pure function assumption in dask distributed The Dask distributed library documentation says: By default, distributed assumes that all functions are pure. [...] The scheduler avoids redundant computations. If the result is already in memory from a previous call then that old result will be used rather tha...
Disable pure function assumption in dask distributed
The Dask distributed library documentation says: By default, distributed assumes that all functions are pure. [...] The scheduler avoids redundant computations. If the result is already in memory from a previous call then that old result will be used rather than recomputing it. When benchmarking function runtimes, th...
[ "After some digging in the source code of distributed, I believe I have found an answer myself. Although someone might correct me if I didn't come to the right conclusion.\nShort answer\nIt is not possible to globally disable disable the purity assumption in distributed.\nHowever, for dask collection it is possible...
[ 0 ]
[]
[]
[ "dask", "dask_distributed", "python" ]
stackoverflow_0074281672_dask_dask_distributed_python.txt
Q: Pytrends ResponseErrore code 429 for a search list of many words I am trying to get google search volume index using Pytrends. However, when I use a large set of words, I get the following error: TooManyRequestsError: The request failed: Google returned a response with code 429 There are similar posts on this iss...
Pytrends ResponseErrore code 429 for a search list of many words
I am trying to get google search volume index using Pytrends. However, when I use a large set of words, I get the following error: TooManyRequestsError: The request failed: Google returned a response with code 429 There are similar posts on this issue (for example here). However, none of the solutions in this step wor...
[ "Here's how you would do 5 at a time. The key is to run your loop in increments of 5, not increments of 1.\ndef get_trends(terms):\n trends = scrape_google(terms[0:5])\n for i in range(5,len(terms),5):\n trends = pd.concat([trends, scrape_google(terms[i:i+5])], axis=1)\n return trends\n\n" ]
[ 0 ]
[]
[]
[ "google_search", "google_trends", "python" ]
stackoverflow_0074308869_google_search_google_trends_python.txt
Q: how to check if timer is expired in python? I am having some questions related to python timer. Hope someone can give some suggestions on that. :) I would like when the timer is expired after 20sec, then it printout a string and exit(2), I look into some example hence, I have written the first example below, the p...
how to check if timer is expired in python?
I am having some questions related to python timer. Hope someone can give some suggestions on that. :) I would like when the timer is expired after 20sec, then it printout a string and exit(2), I look into some example hence, I have written the first example below, the problem for that is after timeout, event I have wr...
[ "It's happening because Thread's run method ignores SystemExit. From threading documentation\n\nIf the run() method raises an exception, threading.excepthook() is called to handle it. By default, threading.excepthook() ignores silently SystemExit.\n\nYou want to exit 2 when the application_timeout function returns....
[ 1, 1, 0 ]
[]
[]
[ "python", "time", "timer" ]
stackoverflow_0074310008_python_time_timer.txt
Q: Unable to loop through Nested Loop (Python) I am attempting to do a nested loop in order to find the mean-squared for a variety of different sized distributions. I keep getting an error that reads: "ValueError: could not broadcast input array from shape (0,) into shape (1000,)". I am a beginner coder so I know thi...
Unable to loop through Nested Loop (Python)
I am attempting to do a nested loop in order to find the mean-squared for a variety of different sized distributions. I keep getting an error that reads: "ValueError: could not broadcast input array from shape (0,) into shape (1000,)". I am a beginner coder so I know this may be trivial for some... My code: #%% Initial...
[ "What steps did you take to debug this? Any? or did you just throw your hands up in despair, not understanding that the error means?\nDid you examine the problem line? Test pieces in it?\nx_step[:,m] = np.cumsum(2*(rand(int(step_variation[n]))<.5)-1) \n\nThe first value of step_variation is 0 (from linspace). ra...
[ 0 ]
[]
[]
[ "loops", "nested", "numpy", "python" ]
stackoverflow_0074309303_loops_nested_numpy_python.txt
Q: replacing/re-assign pandas value with new value I wanted to re-assign/replace my new value, from my current 20000123 19850123 19880112 19951201 19850123 20190821 20000512 19850111 19670133 19850123 As you can see there is data with 19670133 (YYYYMMDD), which means that date is not exist since there is no month wi...
replacing/re-assign pandas value with new value
I wanted to re-assign/replace my new value, from my current 20000123 19850123 19880112 19951201 19850123 20190821 20000512 19850111 19670133 19850123 As you can see there is data with 19670133 (YYYYMMDD), which means that date is not exist since there is no month with 33 days in it.So I wanted to re assign it to the e...
[ "Probably not efficient on a large dataset but can be done using pendulum.parse()\nimport pendulum\n\n\ndef parse_dates(x: str) -> pendulum:\n i = 0\n while ValueError:\n try:\n return pendulum.parse(str(int(x) - i)).date()\n except ValueError:\n i += 1\n\n\ndf[\"date\"] = ...
[ 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074309815_pandas_python.txt
Q: Python Heapq Priority Queue returning values in the wrong order after removing/updating values I'm trying to implement a priority queue in Python using heapq as a base. It works fine when inputting values directly, and then popping them, but when values are updated or removed in between, the values begin to pop in...
Python Heapq Priority Queue returning values in the wrong order after removing/updating values
I'm trying to implement a priority queue in Python using heapq as a base. It works fine when inputting values directly, and then popping them, but when values are updated or removed in between, the values begin to pop in the wrong order. Since changing values directly (I have already tested this) does not maintain the ...
[ "By emptying elements (lists) that are in the heap, the heap property can be violated. Such emptied element becomes smaller than their parent -- violating the minheap (heapq) property, and this will negatively affect the behavior of future operations on the heap, bringing more inconsistency.\nYou could solve this b...
[ 1, 0 ]
[]
[]
[ "heap", "python" ]
stackoverflow_0074309570_heap_python.txt
Q: Why does asyncio.sleep alllow for the task to not be immediately cancelled? import asyncio async def cancel_me(): print('cancel_me(): before sleep') try: # Wait for 1 hour await asyncio.sleep(3600) except asyncio.CancelledError: print('cancel_me(): cancel sleep') raise...
Why does asyncio.sleep alllow for the task to not be immediately cancelled?
import asyncio async def cancel_me(): print('cancel_me(): before sleep') try: # Wait for 1 hour await asyncio.sleep(3600) except asyncio.CancelledError: print('cancel_me(): cancel sleep') raise finally: print('cancel_me(): after sleep') async def main(): # ...
[ "With the await asyncio.sleep(1) commented out, you cancel the task before it even starts running, so it just doesn't run.\n" ]
[ 2 ]
[]
[]
[ "python", "python_asyncio" ]
stackoverflow_0074307478_python_python_asyncio.txt
Q: Python Connection to Postgres over SSH- Incorrect port? I am trying to connect to a postgres database over an ssh server. On postico, it works, and looks something like this: When I copy the url from postico, it looks like this: postgresql+ssh://ubuntu@example-ec2-host.com/exampleusername:examplePassword@example-...
Python Connection to Postgres over SSH- Incorrect port?
I am trying to connect to a postgres database over an ssh server. On postico, it works, and looks something like this: When I copy the url from postico, it looks like this: postgresql+ssh://ubuntu@example-ec2-host.com/exampleusername:examplePassword@example-rds-host.com/exampledb However, when I try to implement it i...
[ "I have to connect to localhost, since this is a port forward.\n" ]
[ 0 ]
[]
[]
[ "postgresql", "psycopg2", "python", "ssh" ]
stackoverflow_0074102186_postgresql_psycopg2_python_ssh.txt
Q: Removing leap day from leap years in xarray dataset I have Netcdf file loaded in an xarray dataset and I want to make daily climatologies without the leap day that is, without 29th Feb included in it. I'm trying the Dataset.drop method by the syntax is not so intuitive for me. Here is the Dataset print(ds) >><xarr...
Removing leap day from leap years in xarray dataset
I have Netcdf file loaded in an xarray dataset and I want to make daily climatologies without the leap day that is, without 29th Feb included in it. I'm trying the Dataset.drop method by the syntax is not so intuitive for me. Here is the Dataset print(ds) >><xarray.Dataset> Dimensions: (lat: 1, lev: 1, lon: 720,...
[ "The right way to use drop() here would be:\nds_N_R.drop([np.datetime64('2000-02-29')], dim='time')\nBut I think this could actually be more cleanly done with an indexing operation, e.g.,\nds_N_R.sel(time=~((ds_N_R.time.dt.month == 2) & (ds_N_R.time.dt.day == 29)))\n", "You can convert your calendar to a non_leap...
[ 7, 0 ]
[]
[]
[ "python", "python_xarray" ]
stackoverflow_0053376113_python_python_xarray.txt
Q: Why is my function returning input1 and input2 as strings? I'm trying to create an addition function def addition(): int(input1) int(input2) mysum = input1 + input2 print(mysum) input1: str = input("Enter integer #1 \n ") input2: str = input("Enter integ...
Why is my function returning input1 and input2 as strings? I'm trying to create an addition function
def addition(): int(input1) int(input2) mysum = input1 + input2 print(mysum) input1: str = input("Enter integer #1 \n ") input2: str = input("Enter integer #2 \n ") addition() I tried to convert the inputs to ints so that I could add them together but...
[ "Change your function to this\ndef addition():\n mysum = int(input1) + int(input2)\n print(mysum)\n\n", "The function should look like this:\ndef addition(number1, number2):\n print(int(number1) + int(number2))\n\ninput1 = input(\"Enter integer #1 \\n \")\ninput2 = input(\"Enter integer #2 \\n \")\n...
[ 0, 0, 0 ]
[]
[]
[ "math", "python", "python_3.x", "return", "sum" ]
stackoverflow_0074310176_math_python_python_3.x_return_sum.txt
Q: python - join all threads after start_new_thread When using the thread library, Is there a way to join all threads that were created by start_new_threads ? for example: try: import thread except ImportError: import _thread as thread #Py3K changed it. for url in url_ip_hash.keys(): thread.start_n...
python - join all threads after start_new_thread
When using the thread library, Is there a way to join all threads that were created by start_new_threads ? for example: try: import thread except ImportError: import _thread as thread #Py3K changed it. for url in url_ip_hash.keys(): thread.start_new_thread(check_url, (url,)) How can join all threads...
[ "Is there a reason you're using thread instead of the recommended Threading module? If not, you should rather use the threading.Thread objects which have a join method:\nfrom threading import Thread\n\n\ndef check_url(url):\n # some code\n\nthreads = []\nfor url in url_ip_hash.keys():\n t = Thread(target=chec...
[ 25, 0, 0 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0019558401_multithreading_python.txt
Q: Asyncio : how to run one task in another one concurrently? I have two functions, both are async and they run outside a function thanks to asyncio However, the second function is inside the first one, and it's blocking the execution of the first : (note that this needs to be compatible with most used Python version...
Asyncio : how to run one task in another one concurrently?
I have two functions, both are async and they run outside a function thanks to asyncio However, the second function is inside the first one, and it's blocking the execution of the first : (note that this needs to be compatible with most used Python versions, from 3.8 to latest one) async def func_2(): # basically doe...
[ "To do what you want, convert func_2 into a task. Then loop inside func_1 until func_2 is finished. The two tasks will play together, giving an appearance of concurrency.\nI replaced your func_2 with a simple asyncio.sleep. I used the print function for the status messages instead of stdout.write. I print the f...
[ 1 ]
[]
[]
[ "asynchronous", "concurrency", "python", "python_asyncio" ]
stackoverflow_0074308650_asynchronous_concurrency_python_python_asyncio.txt
Q: Type hints without value assignment in Python I was under the impression that typing module in Python is mostly for increasing code readability and for code documentation purposes. After playing around with it and reading about the module, I've managed to confuse myself with it. Code below works even though those ...
Type hints without value assignment in Python
I was under the impression that typing module in Python is mostly for increasing code readability and for code documentation purposes. After playing around with it and reading about the module, I've managed to confuse myself with it. Code below works even though those two variables are not initialized (as you would nor...
[ "It is fairly straightforward, when you consider the namespaces involved. This is hinted at by the fact that you get a NameError, when you actually try and do anything with test_var, such as passing it to a function (like print). It tells you that the name you used is not known to the interpreter.\nWhat does variab...
[ 4, 1 ]
[]
[]
[ "annotations", "python", "python_typing", "type_hinting" ]
stackoverflow_0074308012_annotations_python_python_typing_type_hinting.txt
Q: MIgrating data from Datastore to a csv file with Dataflow in Python I would like to write a pipeline to migrate some data from datastore and export it into a csv. For that reason I was thinking about doing: read from datastore convert entities into a python dictionary (not sure about the correctness) write to big...
MIgrating data from Datastore to a csv file with Dataflow in Python
I would like to write a pipeline to migrate some data from datastore and export it into a csv. For that reason I was thinking about doing: read from datastore convert entities into a python dictionary (not sure about the correctness) write to big query export from big query into csv I wrote this code but I'm not sure...
[ "If you want a CSV you should write to Cloud Storage. There is no need to use BigQuery.\nUse a PTransform to convert your DataStore retrieved data, consider using a python library like csv to properly escape quotes (any string data may contain comma's that will mess up your CSV file).\n", "No need to Dataflow in ...
[ 0, 0 ]
[]
[]
[ "apache_beam", "google_cloud_dataflow", "python" ]
stackoverflow_0074307396_apache_beam_google_cloud_dataflow_python.txt
Q: Sql Server SET TRANSACTION ISOLATION LEVEL READ COMMITTED does not appear to work with pyodbc Short Summary I am running multiple sql queries (each committed separately) within one session via pyodbc. In a few queries we call SET TRANSACTION ISOLATION LEVEL SNAPSHOT;, begin a transaction, do some work, commit the ...
Sql Server SET TRANSACTION ISOLATION LEVEL READ COMMITTED does not appear to work with pyodbc
Short Summary I am running multiple sql queries (each committed separately) within one session via pyodbc. In a few queries we call SET TRANSACTION ISOLATION LEVEL SNAPSHOT;, begin a transaction, do some work, commit the transaction and then call SET TRANSACTION ISOLATION LEVEL READ COMMITTED; But even though we have s...
[ "Somehow your code is failing to commit or rollback your SNAPSHOT transaction, so your BEGIN TRANSACTION is actually a nested transaction. See this repro:\nif @@trancount > 0 rollback\ndrop table if exists #already_populated_temp_table\ngo\nSET TRANSACTION ISOLATION LEVEL snapshot;\nbegin transaction\n\nselect * i...
[ 0, 0 ]
[]
[]
[ "isolation_level", "pyodbc", "python", "sql_server", "transaction_isolation" ]
stackoverflow_0074278290_isolation_level_pyodbc_python_sql_server_transaction_isolation.txt
Q: Get keys of dictionary based on rules given a dictionary dictionary = {'Animal 1': {'Dog': 'Yes', 'Cat': 'No', 'Color': 'Black'}, 'Animal 2': {'Dog': 'Yes', 'Cat': 'No', 'Color': 'Brown'}, 'Animal 3': {'Dog': 'No', 'Cat': 'Yes', 'Color': 'Grey'}} How do I select the Animals that are do...
Get keys of dictionary based on rules
given a dictionary dictionary = {'Animal 1': {'Dog': 'Yes', 'Cat': 'No', 'Color': 'Black'}, 'Animal 2': {'Dog': 'Yes', 'Cat': 'No', 'Color': 'Brown'}, 'Animal 3': {'Dog': 'No', 'Cat': 'Yes', 'Color': 'Grey'}} How do I select the Animals that are dogs? expected output ['Animal 1','Animal 2']...
[ "You can use list comprehension:\ndictionary = {\n \"Animal 1\": {\"Dog\": \"Yes\", \"Cat\": \"No\", \"Color\": \"Black\"},\n \"Animal 2\": {\"Dog\": \"Yes\", \"Cat\": \"No\", \"Color\": \"Brown\"},\n \"Animal 3\": {\"Dog\": \"No\", \"Cat\": \"Yes\", \"Color\": \"Grey\"},\n}\n\nout = [k for k, d in diction...
[ 3, 1 ]
[]
[]
[ "dictionary", "pandas", "python" ]
stackoverflow_0074310338_dictionary_pandas_python.txt
Q: Update columns based on multiple complex conditions in Pandas For the DataFrame df below df = pd.DataFrame([('Tesla','Model3', '-', 'Tesla'), ('Tesla', 'ModelS', '-', 'Tesla_MD3'), ('Tesla', 'ModelX', '-', 'Tesla_MD3'), ('Tesla', 'ModelY', '-', 'Tesla'), ...
Update columns based on multiple complex conditions in Pandas
For the DataFrame df below df = pd.DataFrame([('Tesla','Model3', '-', 'Tesla'), ('Tesla', 'ModelS', '-', 'Tesla_MD3'), ('Tesla', 'ModelX', '-', 'Tesla_MD3'), ('Tesla', 'ModelY', '-', 'Tesla'), ('Jeep', 'Wrangler','Grouped','Jeep'), ...
[ "Try:\ndf.loc[df.Status == \"Grouped\", \"Type\"] = (\n df[df.Status == \"Grouped\"]\n .groupby(\"Make\")[\"Type\"]\n .transform(\n lambda x: x.name + \"_MD3\" if x.str.endswith(\"_MD3\").any() else x.name\n )\n)\n\nprint(df)\n\nPrints:\n Make Model Status Type\n0 Tesla Model3 ...
[ -1 ]
[]
[]
[ "dataframe", "group_by", "pandas", "python" ]
stackoverflow_0074310378_dataframe_group_by_pandas_python.txt
Q: Trying to take a screenshot, convert to grayscale, then get the average pixel value I apologize but I'm completely new to python.. I'm trying to take a screenshot of the main monitor, then convert to grayscale, then find the average of the grayscale pixel values - I will want this to loop with a defined sleep peri...
Trying to take a screenshot, convert to grayscale, then get the average pixel value
I apologize but I'm completely new to python.. I'm trying to take a screenshot of the main monitor, then convert to grayscale, then find the average of the grayscale pixel values - I will want this to loop with a defined sleep period as well between loops. I've been trying to read a number of articles with example code...
[ "You only define functions in your program, but never actually call them.\nAdd a new, unindented line at the bottom of your second program to actually call main() like this:\ndef main():\n while True:\n ...\n ... your code\n ...\n\nmain()\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074297528_python.txt
Q: Does struct.pack and encode Produce The Same Byte-String? Python I got quite confused about the difference between struct.pack() and encode. To my understanding, the output of both struct.pack() and encode is byte-string. And that struct.pack() is used to convert numbers into bytes, while encode is used to convert...
Does struct.pack and encode Produce The Same Byte-String? Python
I got quite confused about the difference between struct.pack() and encode. To my understanding, the output of both struct.pack() and encode is byte-string. And that struct.pack() is used to convert numbers into bytes, while encode is used to convert string into bytes. Is my understanding right? Then what if when you s...
[ "If you were given an object of class 'bytes', such as b'\\xc3\\xa9', you wouldn't know what it represented, whether that be a number or a string or something else, without any additional information.\nYou could decode it using utf-8\n>>> b'\\xc3\\xa9'.decode('utf-8')\n'é'\n\nYou could also decode it using utf-16 a...
[ 0 ]
[]
[]
[ "binary_data", "byte", "encode", "python", "struct" ]
stackoverflow_0065721229_binary_data_byte_encode_python_struct.txt
Q: Apply map on pandas column only if the key exisits I am trying to this in python df_svn_subset['job_title_name'] = df_svn_subset['job_title_name'].map(alias_job_titles) I noticed that when I am checking the existence of null values in the job_title_name column that it goes up after applying the latter above. Ther...
Apply map on pandas column only if the key exisits
I am trying to this in python df_svn_subset['job_title_name'] = df_svn_subset['job_title_name'].map(alias_job_titles) I noticed that when I am checking the existence of null values in the job_title_name column that it goes up after applying the latter above. Therefore, how can I apply the latter above only if the key ...
[ "update with the job_title_name, when map returns null using fillna\ndf_svn_subset['job_title_name'] = (df_svn_subset['job_title_name'].map(alias_job_titles)\n .fillna(df_svn_subset['job_title_name']))\n\n" ]
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074310497_pandas_python.txt
Q: About accesing depth images using Python OpenCV I have a array called depth_msg which has a lot of numbers that represents the depth values of a image. When I convert them in cv2 message format, I get this depth image, And the actual image is , How can I get the depth value of the red and yellow bell peppers wit...
About accesing depth images using Python OpenCV
I have a array called depth_msg which has a lot of numbers that represents the depth values of a image. When I convert them in cv2 message format, I get this depth image, And the actual image is , How can I get the depth value of the red and yellow bell peppers with the help of the depth image? My code is, import cv2...
[ "In order to get the depth value for the red and yellow peeprs in thei mage, you will first have to segment the blobs for the two peppers fro mthe image. Once you have the segmented mask, you can simply obtain through slicing.\nFor segmentation, you can either manually segment out the peppers or using a image segme...
[ 0 ]
[]
[]
[ "opencv", "python", "realsense", "robotics", "ros" ]
stackoverflow_0074301643_opencv_python_realsense_robotics_ros.txt
Q: Training ANN using Tensorflow. How to validate the training to avoid overfitting? To avoid overfitting it's necessary, after the X steps, to hold the training and validate its result. If the curve (iterations x loss) for validation crosses the curve (iterations x loss) for training I need to stop the train. How ca...
Training ANN using Tensorflow. How to validate the training to avoid overfitting?
To avoid overfitting it's necessary, after the X steps, to hold the training and validate its result. If the curve (iterations x loss) for validation crosses the curve (iterations x loss) for training I need to stop the train. How can I validate the training result to avoid overfitting? def train(self, dataset): nu...
[ "you can use the keras callback early stopping, documentation is [here.][1] set the callback as suggested below:\nes=tf.keras.callbacks.EarlyStopping( monitor='val_loss', min_delta=0, patience=3,\n verbose=1, mode='auto', baseline=None, restore_best_weights=True)\n\nin model.fit set callbacks=[es]\n\nEarly...
[ 0 ]
[]
[]
[ "custom_training", "overfitting_underfitting", "python", "tensorflow", "validation" ]
stackoverflow_0074303796_custom_training_overfitting_underfitting_python_tensorflow_validation.txt
Q: How do I share screens on 2 devices on a different network in Python? I have a script that allows me to share screens on the same network in python but I want to be able to do it from different networks. Can somebody show me how? My code for receiver.py is: from vidstream import StreamingServer import threading re...
How do I share screens on 2 devices on a different network in Python?
I have a script that allows me to share screens on the same network in python but I want to be able to do it from different networks. Can somebody show me how? My code for receiver.py is: from vidstream import StreamingServer import threading receiver = StreamingServer('127.0.0.1', 9999) t = threading.Thread(target=rec...
[ "You would need to change the IP address from the loopback address to your IP on the local network, and then forward those ports in the router.\nSince 192.168.x.x (class C IP address) is often used by home networks, we will take the following example IP, but you could find this out through ifconfig on linux, or ipc...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074310483_python.txt
Q: ValueError: Missing column provided to 'parse_dates': 'date' Why is it not working? import pandas as pd import numpy as np from statsmodels.graphics.tsaplots import plot_acf, plot_pacf from statsmodels.tsa.statespace.varmax import VARMAX from statsmodels.tsa.api import VAR from statsmodels.tsa.stattools import gra...
ValueError: Missing column provided to 'parse_dates': 'date' Why is it not working?
import pandas as pd import numpy as np from statsmodels.graphics.tsaplots import plot_acf, plot_pacf from statsmodels.tsa.statespace.varmax import VARMAX from statsmodels.tsa.api import VAR from statsmodels.tsa.stattools import grangercausalitytests, adfuller from tqdm import tqdm_notebook from itertools import product...
[ "You want 'Date', not 'date'. Maybe.\nIf my wild guess was incorrect, you can get further by breaking down the problem a bit. Might I suggest:\n\nFirst, be clear exactly where the error comes from. I am guessing pd.read_excel() is throwing a ValueError exception?\nTry reading the data without the parse_dates a...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074310519_pandas_python.txt
Q: Pytest No Module named 'api' I am trying to run a pytest and i am getting this error, i have tried a couple of things but i could not fix it. Could anyone give me a hand i am quite new to Python. I have no idea what else i should do. A: I found the solution for me problem. I have added on my interpreter the pa...
Pytest No Module named 'api'
I am trying to run a pytest and i am getting this error, i have tried a couple of things but i could not fix it. Could anyone give me a hand i am quite new to Python. I have no idea what else i should do.
[ "I found the solution for me problem.\n\nI have added on my interpreter the path for my project root;\nSet the variable PYTHONPATH pointing to my project;\n\nTa-dah! it worked.\nThen I just fixed all the references of the imports based on my API.coro...\n" ]
[ 0 ]
[]
[]
[ "pytest", "python" ]
stackoverflow_0074307485_pytest_python.txt
Q: Pythonic way to cycle through purely side-effect-based comprehension What is the most pythonic way to execute a full generator comprehension where you don't care about the return values and instead the operations are purely side-effect-based? An example would be splitting a list based on a predicate value as discu...
Pythonic way to cycle through purely side-effect-based comprehension
What is the most pythonic way to execute a full generator comprehension where you don't care about the return values and instead the operations are purely side-effect-based? An example would be splitting a list based on a predicate value as discussed here. It's natural to think of writing a generator comprehension spl...
[ "You do so by not using a generator expression.\nJust write a proper loop:\nfor v in split_me:\n if v:\n a.append(v)\n else:\n b.append(v)\n\nor perhaps:\nfor v in split_me:\n target = a if v else b\n target.append(v)\n\nUsing a generator expression here is pointless if you are going to ex...
[ 6, 5, 3, 3, 0, 0 ]
[]
[]
[ "generator", "list_comprehension", "python" ]
stackoverflow_0032307105_generator_list_comprehension_python.txt
Q: How do I print a list of strings in Python? I'm learning Python at the moment and I'm resolving easy problems to get the feeling of it. I'm trying to read a text file and print the maze that is inside of it: ########## ##---##--# #--------# #---###--# #--------# ##-------# ########## For now I have the following:...
How do I print a list of strings in Python?
I'm learning Python at the moment and I'm resolving easy problems to get the feeling of it. I'm trying to read a text file and print the maze that is inside of it: ########## ##---##--# #--------# #---###--# #--------# ##-------# ########## For now I have the following: file = open("maze.txt", "r") maze = file.readlin...
[ "You are on the right track. In the second for loop you have the line i, so you should do range(len(maze[i])) in order to do print(maze[i][j].\n", "Thanks to some of the comments I was able to come to a solution\nInstead of having\nfor i in range(len(maze)):\n for j in range(len()):\n print(maze[i][j])\...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074310558_python.txt
Q: Extract first fields from struct columns into a dictionary I need to create a dictionary from Spark dataframe's schema of type pyspark.sql.types.StructType. The code needs to go through entire StructType, find only those StructField elements which are of type StructType and, when extracting into dictionary, use th...
Extract first fields from struct columns into a dictionary
I need to create a dictionary from Spark dataframe's schema of type pyspark.sql.types.StructType. The code needs to go through entire StructType, find only those StructField elements which are of type StructType and, when extracting into dictionary, use the name of parent StructField as key while value would be name of...
[ "You can use a dictionary comprehension navigating through the schema.\n{x.name: x.dataType[0].name for x in df.schema if x.dataType.typeName() == 'struct'}\n\n\nTest #1\ndf = spark.createDataFrame([], 'field_1 int, field_2 int, field_3 struct<date:date,timestamp:timestamp>, field_4 int')\n\ndf.printSchema()\n# roo...
[ 2 ]
[]
[]
[ "dictionary", "field", "pyspark", "python", "struct" ]
stackoverflow_0074310543_dictionary_field_pyspark_python_struct.txt
Q: Remove the row from dataframe if the column(position) contains a value from list Here is the sample dataframe which has three column and a list My goal is to delete rows if column [position] contains the value from list. Lets say if list has a value sales then our code should find and delete row even if it is bet...
Remove the row from dataframe if the column(position) contains a value from list
Here is the sample dataframe which has three column and a list My goal is to delete rows if column [position] contains the value from list. Lets say if list has a value sales then our code should find and delete row even if it is between the string of columns position I have tired fuzzy matching but it didn't help me ...
[ "This is one way you could do it. The assumption is that the words are case insensitive. Which means that sales in the elimination_list will eliminate positions that contain the words Sales or sales or SALES etc\nIn the example below, I have chosen to eliminate the words sales and marketing.\nThe strings in the pos...
[ 0 ]
[]
[]
[ "data_cleaning", "dataframe", "fuzzy_logic", "python", "regex" ]
stackoverflow_0074272143_data_cleaning_dataframe_fuzzy_logic_python_regex.txt
Q: I want Selenium python to refresh the page if a certain text is visible in an xpath and to not refresh if another text appears in the xpath Here is the HTML I'm working with: <div class="comProductTile__soldOut add8top">Sold Out</div> I am locating the text in the xpath using the following: x = wd.find_element_by...
I want Selenium python to refresh the page if a certain text is visible in an xpath and to not refresh if another text appears in the xpath
Here is the HTML I'm working with: <div class="comProductTile__soldOut add8top">Sold Out</div> I am locating the text in the xpath using the following: x = wd.find_element_by_xpath('//*[@id="collectionApp"]/div/div/div[10]/a/div[4]/div[3]/div').text It returns "Sold Out". When that happens I want to refresh the page...
[ "It could be done using while loop:\nwhile True:\n x = wd.find_element_by_xpath('//*[@id=\"collectionApp\"]/div/div/div[10]/a/div[4]/div[3]/div').text\n if x == \"Sold out\":\n wd.refresh()\n time.sleep(2)\n elif x == \"In Stock\":\n break\n\n" ]
[ 0 ]
[]
[]
[ "find", "python", "selenium", "text", "xpath" ]
stackoverflow_0074310784_find_python_selenium_text_xpath.txt
Q: Updating A List Word Counter I'm creating a program that counts letters. I created two dictionaries that both have the same word and, because they are the same exact word, both have the same counter. I want to know how to merge the two dictionaries so that it updates the counters as well, but I consistently receiv...
Updating A List Word Counter
I'm creating a program that counts letters. I created two dictionaries that both have the same word and, because they are the same exact word, both have the same counter. I want to know how to merge the two dictionaries so that it updates the counters as well, but I consistently receive the result "NONE." word = 'he' w...
[ "To merge counters dictionaries d1 and d2:\nd = d1.copy()\n\nfor k, count in d2:\n if k not in d:\n d[k] = 0\n d[k] += count\n\n\nAlternatively:\nd = defaultdict(d1, int)\n\nfor k, count in d2:\n d[k] += count\n\n", "You can concatenate strings and use a single dictionary:\nword1 = 'he'\nword2 = '...
[ 0, 0 ]
[]
[]
[ "counter", "dictionary", "merge", "python", "python_3.x" ]
stackoverflow_0074310846_counter_dictionary_merge_python_python_3.x.txt
Q: How can I limit text score with $gt operator in MongoDB? I want to limit text scores using the $gt operator. Using the find function, I can sort the text scores according to the text similarity status from largest to smallest. I can get the cursor with the highest score by putting a limit of 1 on the rank. deneme...
How can I limit text score with $gt operator in MongoDB?
I want to limit text scores using the $gt operator. Using the find function, I can sort the text scores according to the text similarity status from largest to smallest. I can get the cursor with the highest score by putting a limit of 1 on the rank. deneme = user.find( { '$text': { '$search': "dogan can" } }, ...
[ "I think what you're requesting is documented here. In short - you will need to use the aggregation framework so that you can have 3 stages to accomplish each of the following:\n\nPerform the initial $text searching in a $match stage\nPersist the text score as part of the document via an $addFields stage\nUse an ad...
[ 0 ]
[]
[]
[ "anaconda", "jupyter_notebook", "mongodb", "nosql", "python" ]
stackoverflow_0074308200_anaconda_jupyter_notebook_mongodb_nosql_python.txt
Q: How to tell my script to process ONE particular image-file extension using PIL in Python? EDIT: I changed the title of this question because I realize I simply need to tell the following code to only process PNG image files and nothing else. I found a few solutions but they don't work. Allow me to explain: I'm hav...
How to tell my script to process ONE particular image-file extension using PIL in Python?
EDIT: I changed the title of this question because I realize I simply need to tell the following code to only process PNG image files and nothing else. I found a few solutions but they don't work. Allow me to explain: I'm having trouble when using this code I found on another author's question here. In brief, I'm tryin...
[ "You just need to glob:\nimport glob\n\nfor file in glob.glob('/path/to/images/*.png'):\n print(file\n\n" ]
[ 0 ]
[]
[]
[ "crop", "image", "jupyter_notebook", "python" ]
stackoverflow_0074302247_crop_image_jupyter_notebook_python.txt
Q: Using seaborn kdeplot by group. The equivalent of df.hist(by=‘col1’ ,column=‘col2’) trying to plot density with kdeplot. However, I can not get it to work exactly how I would like. data = customers groupby gender if I code customers.hist(by ='gender', column='total_trans_ct', figsize = [10,6]);``` I get a histog...
Using seaborn kdeplot by group. The equivalent of df.hist(by=‘col1’ ,column=‘col2’)
trying to plot density with kdeplot. However, I can not get it to work exactly how I would like. data = customers groupby gender if I code customers.hist(by ='gender', column='total_trans_ct', figsize = [10,6]);``` I get a histogram divided for M and F clients in the dataset. However, I want a density plot so I crea...
[]
[]
[ "I got it! I was really close. If anyone needs a code like this\nplot = sns.FacetGrid(customers, col='gender', hue=\"attrition_flag\", height=10, aspect=1)\nplot = plot.map(sns.kdeplot,\"total_trans_ct\", fill=True, common_norm=False, alpha=0.4)\n" ]
[ -1 ]
[ "kdeplot", "python", "seaborn" ]
stackoverflow_0074310844_kdeplot_python_seaborn.txt
Q: Adding cells and setting their format at the same time with batchUpdate and appendCells using python and spreadsheets api I would like to populate a sheet with values and some formatting. From what I've read I found out that batchUpdate and appendCells should do the work. Unfortunately I've encountered an error wh...
Adding cells and setting their format at the same time with batchUpdate and appendCells using python and spreadsheets api
I would like to populate a sheet with values and some formatting. From what I've read I found out that batchUpdate and appendCells should do the work. Unfortunately I've encountered an error which I'm not able to fix. Here's my code: sheet_values = [] for row in ws: row_data = {'values': []} for cell in row: ...
[ "I believe your goal is as follows.\n\nYou want to insert a new sheet and also want to put userEnteredValue and userEnteredFormat with one API call using \"Method: spreadsheets.batchUpdate\" of Sheets API.\n\nModification points:\n\naddSheet and appendCells are required to use separate requests in requests.\nIn you...
[ 1 ]
[]
[]
[ "google_sheets", "google_sheets_api", "python" ]
stackoverflow_0074310879_google_sheets_google_sheets_api_python.txt
Q: How to switch position of two items in a Python list? I haven’t been able to find a good solution for this problem on the net (probably because switch, position, list and Python are all such overloaded words). It’s rather simple – I have this list: ['title', 'email', 'password2', 'password1', 'first_name', 'last_n...
How to switch position of two items in a Python list?
I haven’t been able to find a good solution for this problem on the net (probably because switch, position, list and Python are all such overloaded words). It’s rather simple – I have this list: ['title', 'email', 'password2', 'password1', 'first_name', 'last_name', 'next', 'newsletter'] I’d like to switch position of...
[ "i = ['title', 'email', 'password2', 'password1', 'first_name', \n 'last_name', 'next', 'newsletter']\na, b = i.index('password2'), i.index('password1')\ni[b], i[a] = i[a], i[b]\n\n", "The simple Python swap looks like this:\nfoo[i], foo[j] = foo[j], foo[i]\n\nNow all you need to do is figure what i is, and t...
[ 463, 205, 18, 8, 1, 0 ]
[ "you can use for example:\n>>> test_list = ['title', 'email', 'password2', 'password1', 'first_name',\n 'last_name', 'next', 'newsletter']\n>>> reorder_func = lambda x: x.insert(x.index('password2'), x.pop(x.index('password2')+1))\n>>> reorder_func(test_list)\n>>> test_list\n... ['title', 'email', ...
[ -1, -1 ]
[ "list", "python" ]
stackoverflow_0002493920_list_python.txt
Q: Pandas - Compute z-score for all columns I have a dataframe containing a single column of IDs and all other columns are numerical values for which I want to compute z-scores. Here's a subsection of it: ID Age BMI Risk Factor PT 6 48 19.3 4 PT 8 43 20.9 NaN PT 2 39 18.1 3 PT...
Pandas - Compute z-score for all columns
I have a dataframe containing a single column of IDs and all other columns are numerical values for which I want to compute z-scores. Here's a subsection of it: ID Age BMI Risk Factor PT 6 48 19.3 4 PT 8 43 20.9 NaN PT 2 39 18.1 3 PT 9 41 19.5 NaN Some of my columns c...
[ "Using Scipy's zscore function:\ndf = pd.DataFrame(np.random.randint(100, 200, size=(5, 3)), columns=['A', 'B', 'C'])\ndf\n\n| | A | B | C |\n|---:|----:|----:|----:|\n| 0 | 163 | 163 | 159 |\n| 1 | 120 | 153 | 181 |\n| 2 | 130 | 199 | 108 |\n| 3 | 108 | 188 | 157 |\n| 4 | 109 | 171 | 119 |\n\nfrom sc...
[ 98, 92, 28, 7, 7, 4, 1, 1, 0 ]
[]
[]
[ "dataframe", "indexing", "pandas", "python", "statistics" ]
stackoverflow_0024761998_dataframe_indexing_pandas_python_statistics.txt
Q: how to set the selection shadow for delegate cell in a tableview? here is a tableview designed with delegate. I've set the selectionMode as selectRows. When I click on a row, only the central column cell with pure text shows the selection shadow while the first and last column realised by drawPixmap,drawText don't...
how to set the selection shadow for delegate cell in a tableview?
here is a tableview designed with delegate. I've set the selectionMode as selectRows. When I click on a row, only the central column cell with pure text shows the selection shadow while the first and last column realised by drawPixmap,drawText don't. The central is also realised by QTextDocument with code like doc.doc...
[ "Try calling the superclass method first in your item delegates paint method, then make the adjustments that you want to make.\nfor example:\n def paint(self, painter, option, index):\n super().paint(painter, option, index)\n if index.column() == 0:\n painter.save()\n painter....
[ 1 ]
[]
[]
[ "pyqt", "pyqt5", "python", "python_3.x", "qt" ]
stackoverflow_0074301710_pyqt_pyqt5_python_python_3.x_qt.txt
Q: Project Euler Project 67 - Python Note: I have bad English, please don't judge me on it :) Problems: projecteuler.net/problem=18 projecteuler.net/problem=67 I am doing the Project Euler #67 in Python. My program, which worked for Project 18, does not work for Project 67. Code (excludes the opening of the file and...
Project Euler Project 67 - Python
Note: I have bad English, please don't judge me on it :) Problems: projecteuler.net/problem=18 projecteuler.net/problem=67 I am doing the Project Euler #67 in Python. My program, which worked for Project 18, does not work for Project 67. Code (excludes the opening of the file and the processing of information): for i ...
[ "This approach is logically flawed. When you're in row 1, you don't have enough information to know whether moving right or left will lead you to the largest sum, not with only a 2-row lookahead. You would need to look all the way to the bottom to ensure getting the best path.\nAs others have suggested, start at ...
[ 1, 0, 0 ]
[]
[]
[ "python", "python_2.7" ]
stackoverflow_0043076039_python_python_2.7.txt
Q: Adding items to Python 2d list I have a empty 2d list which i dont know the length of or no of rows. Animals has some number of items passed from function call. In function startDocumentary_day(), For every function call, I have to append this each incoming animal list as each row in documentary list. Eg:Animals ...
Adding items to Python 2d list
I have a empty 2d list which i dont know the length of or no of rows. Animals has some number of items passed from function call. In function startDocumentary_day(), For every function call, I have to append this each incoming animal list as each row in documentary list. Eg:Animals can have ['cow','tiger'], sometimes...
[ "You need to loop over the documentary list, and append to each element.\ndef add(documentary, animals):\n for d in documentary:\n d.append(animals)\n\n" ]
[ 1 ]
[]
[]
[ "list", "python", "python_3.x" ]
stackoverflow_0074310938_list_python_python_3.x.txt
Q: How to append multiple occurrences of a letter from a string? I am trying to append multiple occurrences of a string into a list as so: index('Mississippi', 's') [2,3,5,6] s is found at index 2,3,5 and 6. It's a very simple code, yet I'm not sure why mine isn't working ? Python def index(w,l): wo=[] for ...
How to append multiple occurrences of a letter from a string?
I am trying to append multiple occurrences of a string into a list as so: index('Mississippi', 's') [2,3,5,6] s is found at index 2,3,5 and 6. It's a very simple code, yet I'm not sure why mine isn't working ? Python def index(w,l): wo=[] for i in range(len(w)): if w[i] == l: wor= w.find(l...
[ "w.find() always returns the index of the first match, so you can't use it when there are duplicates. Append the current index of the iteration, which is i. So change mo.append(wor) to mo.append(i).\nThe whole thing can be done in a single list comprehension.\ndef index(w, l):\n return [i for i, c in enumerate(w...
[ 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074310956_python.txt
Q: Check if S3 bucket name begins with word? I'm trying to write a python Lambda to check for an S3 bucket in an account. The issue is that the naming of this bucket changes from account to account, with the same phrase in the beginning but randomized letters at the ending. example: bucketname-bucketregion-jdkaieldja...
Check if S3 bucket name begins with word?
I'm trying to write a python Lambda to check for an S3 bucket in an account. The issue is that the naming of this bucket changes from account to account, with the same phrase in the beginning but randomized letters at the ending. example: bucketname-bucketregion-jdkaieldjadksl with the name of the bucket, which is alw...
[ "You can list the bucket names and check if the name prefix matches.\ns3 = boto3.resource('s3')\nfor bucket in s3.buckets.all():\n if bucket.name.startswith('bucketname-bucketregion-'):\n print(bucket.name)\n\n" ]
[ 1 ]
[]
[]
[ "amazon_s3", "amazon_web_services", "aws_lambda", "python" ]
stackoverflow_0074310360_amazon_s3_amazon_web_services_aws_lambda_python.txt
Q: Overwrite an Excel file in Google Drive using Python I have a loop which runs through a list of files then uploads them a Google Drive folder. There is a client_secrets.json file in the folder on my computer. I am able to create new files in the Google Drive folder but I wish to overwrite the existing files, witho...
Overwrite an Excel file in Google Drive using Python
I have a loop which runs through a list of files then uploads them a Google Drive folder. There is a client_secrets.json file in the folder on my computer. I am able to create new files in the Google Drive folder but I wish to overwrite the existing files, without changing the Google Drive file IDs. Is this possible to...
[ "I believe your goal is as follows.\n\nYou want to update the existing XLSX file with a new XLSX file on Google Drive.\nYou want to achieve this using pydrive for python.\n\nIssue and workaround:\nWhen I saw the document of pydrive, I couldn't find the method for updating the file content while the file metadata ca...
[ 2, 1, 1 ]
[]
[]
[ "google_drive_api", "google_oauth", "pydrive", "python" ]
stackoverflow_0074308764_google_drive_api_google_oauth_pydrive_python.txt
Q: Dict or WeakKeyDictionary with identity equality -- wrap unhashable objects to check identity I want to use some objects as keys for some dict, which are either unhashable, or hashable but I want to overwrite their __eq__/__hash__ with the default object.__eq__/object.__hash__, i.e. namely a == b iff a is b. (Thes...
Dict or WeakKeyDictionary with identity equality -- wrap unhashable objects to check identity
I want to use some objects as keys for some dict, which are either unhashable, or hashable but I want to overwrite their __eq__/__hash__ with the default object.__eq__/object.__hash__, i.e. namely a == b iff a is b. (These objects could e.g. be numpy.ndarray, torch.Tensor, or other things, but I want to ask in general ...
[ "It's probably not too difficult to create a wrapper class using __getattr__, though it might be more robust to create your own mapping class like the following (untested):\nimport collections.abc\nimport weakref\n\nclass WeakKeyIdMap(collections.abc.MutableMapping):\n \"\"\"Like weakref.WeakKeyDictionary except...
[ 0 ]
[]
[]
[ "python", "weak_references" ]
stackoverflow_0064946558_python_weak_references.txt
Q: How to efficiently iterate over a pandas dataframe dynamically looking to its rows I have thousands of csv files. Each file has something about 1k lines in the following structure Hour Val1 Val2 9:00 2 3 9:05 1 4 9:10 5 6 9:15 4 8 9:20 6 4 What I need is: verify if Val2 in row x is bigger th...
How to efficiently iterate over a pandas dataframe dynamically looking to its rows
I have thousands of csv files. Each file has something about 1k lines in the following structure Hour Val1 Val2 9:00 2 3 9:05 1 4 9:10 5 6 9:15 4 8 9:20 6 4 What I need is: verify if Val2 in row x is bigger then Val1 in row x-1 and row x+1 A basic output for this problem is: Hour Cond 9:00 False ...
[ "Iterate the list of dfs and compute cond as follows. dont iterate the df rows please. Its the anticlimax\ndf =df.assign(cond=(df['Val2'].gt(df['Val1'].shift()))&(df['Val2'].gt(df['Val1'].shift(-1))))\n\n" ]
[ 3 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074311031_dataframe_pandas_python.txt
Q: How to install pandas in Termux? I am trying to install pandas in Termux and it showing: File "setup.py", line 18, in import numpy ModuleNotFoundError: No module named 'numpy' But it's already installed. See the error here: https://pastebin.com/KdunjhRp My android details : kernal --> Linux ...
How to install pandas in Termux?
I am trying to install pandas in Termux and it showing: File "setup.py", line 18, in import numpy ModuleNotFoundError: No module named 'numpy' But it's already installed. See the error here: https://pastebin.com/KdunjhRp My android details : kernal --> Linux architecture --> aarch64 P...
[ "Following the tuto (https://wiki.termux.com/wiki/Python) to install Numpy, I installed successully Pandas (I had the same error before) :\nStep by step, I did :\n\nRemove all packages\n$ pip freeze > unins && pip uninstall -y -r unins && rm unins\n\nFind the path of the cache for pip...\n$ pip cache dir\n\n... and...
[ 2, 0 ]
[]
[]
[ "pandas", "python", "termux" ]
stackoverflow_0069141395_pandas_python_termux.txt
Q: Saving bot generated text to an external file I just started learning and using Python today and I am working on a discord bot that allows for custom user queries. In this current iteration, the user can specify how many dice and how many sides are rolled. The bot then displays the results in Discord. I am wanting...
Saving bot generated text to an external file
I just started learning and using Python today and I am working on a discord bot that allows for custom user queries. In this current iteration, the user can specify how many dice and how many sides are rolled. The bot then displays the results in Discord. I am wanting to save these results in an external log file for ...
[ "f.write('Dice results:\\n') - see you only write to the log the string 'Dice results:\\n' and nothing else. You can add what you want by this pattern f'Dice results: {dice}\\n'\nOn a side note, you don't want to do it this way but rather use the logging library and log to a file. Similar to this:\nSomewhere in the...
[ 0, 0 ]
[]
[]
[ "discord.py", "python" ]
stackoverflow_0074311130_discord.py_python.txt
Q: Is it possible for Django to sum lengths of a non-numeric field? I have learned we can sum all(or filtered) columns like price from this question. ItemPrice.objects.aggregate(Sum('price')) But is it possible for Django to sum non-numeric field's length, such as CharField or JSONField? A pseudocode is like followi...
Is it possible for Django to sum lengths of a non-numeric field?
I have learned we can sum all(or filtered) columns like price from this question. ItemPrice.objects.aggregate(Sum('price')) But is it possible for Django to sum non-numeric field's length, such as CharField or JSONField? A pseudocode is like following. User.objects.aggregate(Sum(len('username')))
[ "from django.db.models.functions import Length\nfrom django.db.models import Sum\nUser.objects.annotate(l=Length(\"username\")).aggregate(Sum(\"l\"))\n\n", "you can try use\nfrom django.db.models.functions import Length User.objects.aggregate(Sum(Length('username')))\n", "For a JSONFied, we can use Count to sum...
[ 3, 0, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0074285676_django_django_models_python.txt
Q: I am trying to do a one to one match between two csv files. the name I type I want python to search the other csv file and spit out the matching name So this is my code I am running: import pandas as pd import os os.chdir("/Users/oliviaunokesan/") #df=[df1, df2] #idx=df['NAME']== 'Claustrum' #print(df[idx]) #de...
I am trying to do a one to one match between two csv files. the name I type I want python to search the other csv file and spit out the matching name
So this is my code I am running: import pandas as pd import os os.chdir("/Users/oliviaunokesan/") #df=[df1, df2] #idx=df['NAME']== 'Claustrum' #print(df[idx]) #define query def query(list_of_dfs, column, key): output= [] for df in list_of_dfs: row= df[df[column]==key] output.append(row) ...
[ "You evaluated df[\"NAME\"] == \"Claustrum\" and were unhappy with the result:\nThe trouble is that df is a list rather than a DataFrame.\nWhen you assigned df = [df1, df2]\nwhat you were looking for is\ndf = pd.concat([df1, df2])\n\nhttps://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html\n" ]
[ 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074311196_list_python.txt
Q: Why am I getting NotImplementedError with async and await on Windows? I have this code: import os import time import asyncio async def run_command(*args): """ Example from: http://asyncio.readthedocs.io/en/latest/subprocess.html """ # Create subprocess process = await asyncio.create_su...
Why am I getting NotImplementedError with async and await on Windows?
I have this code: import os import time import asyncio async def run_command(*args): """ Example from: http://asyncio.readthedocs.io/en/latest/subprocess.html """ # Create subprocess process = await asyncio.create_subprocess_exec( *args, # stdout must a pipe to be accessibl...
[ "Different event loops are implemented differently. Some of them have restrictions (sometimes OS-related). By default, Windows uses SelectorEventLoop and as you can see in doc:\n\nSelectorEventLoop has the following limitations:\n\nSelectSelector is used to wait on socket events: it supports sockets and is limited ...
[ 23, 5, 0 ]
[]
[]
[ "python", "python_asyncio" ]
stackoverflow_0044633458_python_python_asyncio.txt
Q: python: TypeError: 'coroutine' object is not subscriptable i keep getting an exception in this function when it trys to subscript the json object from the anticaptcha function, but all the other functions seem to be working fine 'email':email, 'username': username, 'password': passwd, 'invite': None, 'captcha_key'...
python: TypeError: 'coroutine' object is not subscriptable
i keep getting an exception in this function when it trys to subscript the json object from the anticaptcha function, but all the other functions seem to be working fine 'email':email, 'username': username, 'password': passwd, 'invite': None, 'captcha_key': await anticaptcha.solve(session, 'register')['solution']['gRec...
[ "await anticaptcha.solve(session, 'register')['solution']['gRecaptchaResponse']\n\nmeans\nawait (anticaptcha.solve(session, 'register')['solution']['gRecaptchaResponse'])\n\nbut you want\n(await anticaptcha.solve(session, 'register'))['solution']['gRecaptchaResponse']\n\nIf the other similar thing, task_id = await ...
[ 18 ]
[ "An alternative to the accepted method is one line longer, but adds a bit of clarity.\nx = await anticaptcha.solve(session, 'register') # first do the await\nx = x['solution']['gRecaptchaResponse'] # then get the dict values\n\nThis above clearly shows what happens. When i first came across the same,...
[ -1 ]
[ "python", "python_asyncio" ]
stackoverflow_0051459793_python_python_asyncio.txt
Q: How can I read numbers as integers while also reading in names as strings from a data file? Here's the code I wrote to put the names and numbers into a file: def main(): num_players = int(input("How many players are there?")) golf = open("golf.txt", 'w') for i in range(num_players): player_name...
How can I read numbers as integers while also reading in names as strings from a data file?
Here's the code I wrote to put the names and numbers into a file: def main(): num_players = int(input("How many players are there?")) golf = open("golf.txt", 'w') for i in range(num_players): player_name = str(input("What is the player's name?")) player_score = int(input("What is their golf ...
[ "Minimal changes to OP code, with comments:\nwith open(\"golf.txt\") as golf: # make sure the file gets closed using with\n large = 0 # start small with largest\n small = 300 # start large with smallest\n\n # only one pass to read the file\n # compute small and large at the same time\n while name...
[ 2, 0, 0 ]
[]
[]
[ "data_files", "python" ]
stackoverflow_0074310760_data_files_python.txt
Q: ModuleNotFoundError: No Module Named openai import requests from bs4 import BeautifulSoup import openai #write each line of nuclear.txt to a list with open('nuclear.txt', 'r') as f: lines = f.readlines() #remove the newline character from each line lines = [line.rstrip() for line in lines] #gather the text...
ModuleNotFoundError: No Module Named openai
import requests from bs4 import BeautifulSoup import openai #write each line of nuclear.txt to a list with open('nuclear.txt', 'r') as f: lines = f.readlines() #remove the newline character from each line lines = [line.rstrip() for line in lines] #gather the text from each website and add it to a new txt file f...
[ "Try using pip3 install openai, as it installs openai for python3, not python2 (if you have it installed). If you only have python3, pip and pip3 are basically the same thing (I think).\n" ]
[ 2 ]
[ "Follow the steps below to install the openai package for the current interpreter\n\nrun the following code\nimport sys\nprint(sys.executable)\n\n\nget the current interpreter path\n\n\nCopy the path and install openai using the following command in the terminal\nC:\\WorkSpace\\pytest10\\.venv\\Scripts\\python.exe ...
[ -1 ]
[ "interpreter", "python", "visual_studio_code" ]
stackoverflow_0074311275_interpreter_python_visual_studio_code.txt