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: In django I have created "tool" app, When I try to import tool to other file I got error "No module named 'tool' " please check the following image for reference from tool.models import loginauth Traceback (most recent call last): File "<string>", line 1, in <module> ModuleNotFoundError: No module named 'tool' ...
In django I have created "tool" app, When I try to import tool to other file I got error "No module named 'tool' "
please check the following image for reference from tool.models import loginauth Traceback (most recent call last): File "<string>", line 1, in <module> ModuleNotFoundError: No module named 'tool'
[ "As per my understanding you have created app inside the internal directory of project. Which shouldn't be soo. If you still want to go with the same structure as present please replace this line with the one causing error.\nfrom techticket.tool.models import loginauth\n\nPlease comment here If the issue still pers...
[ 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0074542778_django_django_models_python.txt
Q: Imputing nulls in a row with other row if one column is same I have a dataframe data = [[1000, 'x', 'A'], [2000,'y', 'A'], ['NaN','NaN', 'A'], ['NaN','NaN','B'], [1700,'z', 'B']] df = pd.DataFrame(data, columns=['Price', 'Attribute', 'Model' ]) df = df.replace('NaN',np.nan) Now i want to impute the nulls in such...
Imputing nulls in a row with other row if one column is same
I have a dataframe data = [[1000, 'x', 'A'], [2000,'y', 'A'], ['NaN','NaN', 'A'], ['NaN','NaN','B'], [1700,'z', 'B']] df = pd.DataFrame(data, columns=['Price', 'Attribute', 'Model' ]) df = df.replace('NaN',np.nan) Now i want to impute the nulls in such a way that if Model is same, copy the content of rows having leas...
[ "If there is multiple columns use DataFrame.fillna with minimal values per groups to new columns by GroupBy.transform:\ncols = ['Price','Col1']\ndf[cols] = df[cols].fillna(df.groupby('Model')[cols].transform('min'))\nprint(df)\n Price Attribute Model\n0 1000.0 x A\n1 2000.0 y A\n2 1000...
[ 1 ]
[]
[]
[ "dataframe", "group_by", "numpy", "pandas", "python" ]
stackoverflow_0074544028_dataframe_group_by_numpy_pandas_python.txt
Q: django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 13: 'endblock'. Did you forget to register or load this tag? I'm trying to create a user registration in Django, but I have an issue with the template: registrazione.html. My github repo: https://github.com/Pif50/MobFix registrazione.html {%...
django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 13: 'endblock'. Did you forget to register or load this tag?
I'm trying to create a user registration in Django, but I have an issue with the template: registrazione.html. My github repo: https://github.com/Pif50/MobFix registrazione.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% block head_title %} {{ block.super }} - Registrati sul Forum{% endblock head_title %...
[ "Try this way:\n{% extends 'base.html' %}\n{% load crispy_forms_tags %} \n{% block head_title %} \n{{ block.super }} - Registrati sul Forum\n{% endblock head_title %}\n{% block content %}\n<div class=\"row justify-content-center mt-4\">\n <div class=\"col-6 text-center\">\n <h2>Registrati sul Sito!</h2>\n <f...
[ 0, 0 ]
[]
[]
[ "django", "django_templates", "python", "templates" ]
stackoverflow_0074543753_django_django_templates_python_templates.txt
Q: Generate Sequence Number on similar values from dataframe column Trying to fetch a sequence number on similar group (Fuzzy) of values. Input data frame: KeyName KeyCompare Source PapasMrtemis PapasMrtemis S1 PapasMrtemis Pappas, Mrtemis S1 Pappas, Mrtemis PapasMrtemis ...
Generate Sequence Number on similar values from dataframe column
Trying to fetch a sequence number on similar group (Fuzzy) of values. Input data frame: KeyName KeyCompare Source PapasMrtemis PapasMrtemis S1 PapasMrtemis Pappas, Mrtemis S1 Pappas, Mrtemis PapasMrtemis S2 Pappas, Mrtemis Pappas, Mrtemis S2 Micheal M...
[ "Updated Answer\nthe Previous version will work if you sort the dataframe by doing df.sort_values(by='KeyName')\nPrevious version:\nLet's import the library difflib and calculate the matching ratio by using the function SequenceMatcher(a,b).ratio and increment keyId when that ratio is lower than 0.5:\nimport diffli...
[ 0, 0 ]
[]
[]
[ "databricks", "pyspark", "python" ]
stackoverflow_0074532732_databricks_pyspark_python.txt
Q: One or more errors occurred while loading the module 'aspose.word'(-1009) I'm trying to make an executable with pyinstaller but it's giving an error in a library I'm using called aspose.words this is the error that appears to me: if the image does not open: Traceback (most recent call last): File "<frozen impor...
One or more errors occurred while loading the module 'aspose.word'(-1009)
I'm trying to make an executable with pyinstaller but it's giving an error in a library I'm using called aspose.words this is the error that appears to me: if the image does not open: Traceback (most recent call last): File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._boots...
[ "Try to use --collect-all option instead of --collect-binaries and --collect-submodules ones: such approach helped me.\ni.e., try to use the following command:\npyinstaller --noconsole --onefile --collect-all \"aspose\" main.py --ico 3151580_game_maze_retro_icon.png\n\n" ]
[ 1 ]
[]
[]
[ "aspose.words", "pyinstaller", "python" ]
stackoverflow_0074477544_aspose.words_pyinstaller_python.txt
Q: Why do we need "try-finally" when using @contextmanager decorator? I wonder why we need to use a try-finally when using a the @contextmanager decorator. The provided example suggests: from contextlib import contextmanager @contextmanager def managed_resource(*args, **kwds): resource = acquire_resource(*args, ...
Why do we need "try-finally" when using @contextmanager decorator?
I wonder why we need to use a try-finally when using a the @contextmanager decorator. The provided example suggests: from contextlib import contextmanager @contextmanager def managed_resource(*args, **kwds): resource = acquire_resource(*args, **kwds) try: yield resource finally: release_res...
[ "Because a finally statement is guaranteed to run no matter what (except a power outage), before the code can terminate. So writing it like this guarantees that the resource is always released\n", "finally makes sure that the code under it is always executed even if there's an exception raised:\nfrom contextlib i...
[ 2, 2 ]
[]
[]
[ "contextmanager", "python", "python_3.x" ]
stackoverflow_0074543989_contextmanager_python_python_3.x.txt
Q: How to write unit test for this particular function in python? There's a function result = Downloader.downloadFiles(list_to_download, download_path, username, password) in the file downloadModule, which will return a boolean(True/False) to the 'result' variable. How to write a mock to this call such that result wi...
How to write unit test for this particular function in python?
There's a function result = Downloader.downloadFiles(list_to_download, download_path, username, password) in the file downloadModule, which will return a boolean(True/False) to the 'result' variable. How to write a mock to this call such that result will always return True. Tried the following way but got the following...
[ "Missing quotes\nI think you have only to add the quotes (') as delimiter for the patch parameter downloadModule.Downloader.downloadFiles.\nYour code becomes the following:\n@patch('downloadModule.Downloader.downloadFiles')\ndef test_download_files(self,mock_download_files):\n mock_download_files.return_valu...
[ 1 ]
[]
[]
[ "download", "mocking", "patch", "python", "unit_testing" ]
stackoverflow_0074537012_download_mocking_patch_python_unit_testing.txt
Q: Can I change value's decimal point seperately in pandas? I want each values of df have different decimal point like this year month day count 1234 5678 9101 mean 12.12 34.34 2.3456 std 12.12 3.456 7.789 I searched to find a way to change specific value's decimal point but couldn'...
Can I change value's decimal point seperately in pandas?
I want each values of df have different decimal point like this year month day count 1234 5678 9101 mean 12.12 34.34 2.3456 std 12.12 3.456 7.789 I searched to find a way to change specific value's decimal point but couldn't find the way. So this is what I've got year ...
[ "You can change displayning of floats:\npd.options.display.float_format = '{:,6f}'.format\n\n#if necessary convert to floats\ndf = df.astype(float)\n\nOr change format to 6 zeros:\ndf = df.astype(float).applymap('{:.6f}'.format)\n\n", "The format approach is correct, but I think what you are looking for is this:\...
[ 0, 0 ]
[]
[]
[ "dataframe", "decimal_point", "pandas", "python" ]
stackoverflow_0074543206_dataframe_decimal_point_pandas_python.txt
Q: Kubernetes Python API get all crs I want to use the Python Kubernetes Client to retrieve all CRs, because I want to delete them. The latter can easily be done with delete_namespaced_custom_object from the CustomObjectsApi. But first, I need a list containing all of them, so an equivalent to k get crd -A, which can...
Kubernetes Python API get all crs
I want to use the Python Kubernetes Client to retrieve all CRs, because I want to delete them. The latter can easily be done with delete_namespaced_custom_object from the CustomObjectsApi. But first, I need a list containing all of them, so an equivalent to k get crd -A, which cannot be found in the docu. Is there a tr...
[ "Use the API method: list_cluster_custom_object.\nThere are some concepts to clarify:\n\nk get crd is used to get all CRD resource objects, -A option is useless;\nSay, you have a custom resource type called application. kubectl get application -A gets all application(custom resource) objects in all namespaces;\nkub...
[ 1 ]
[]
[]
[ "kubernetes", "python" ]
stackoverflow_0074536173_kubernetes_python.txt
Q: How to list files in a directory in python? I am unable to list files in a directory with this code import os from os import listdir def fn(): # 1.Get file names from directory file_list=os.listdir(r"C:\Users\Jerry\Downloads\prank\prank") print (file_list) #2.To rename files fn() on running ...
How to list files in a directory in python?
I am unable to list files in a directory with this code import os from os import listdir def fn(): # 1.Get file names from directory file_list=os.listdir(r"C:\Users\Jerry\Downloads\prank\prank") print (file_list) #2.To rename files fn() on running the code it gives no output !
[ "The function call fn() was inside the function definition def fn(). You must call it outside by unindenting the last line of your code:\nimport os\ndef fn(): # 1.Get file names from directory\n file_list=os.listdir(r\"C:\\Users\")\n print (file_list)\n\n #2.To rename files\nfn()\n\n", "You should use...
[ 13, 0, 0 ]
[]
[]
[ "directory", "python", "python_2.7" ]
stackoverflow_0044494431_directory_python_python_2.7.txt
Q: Getting the file name of an ipython notebook For python files I can get the file name and use to as a prefix for the generated results using: prefix = os.path.splitext(os.path.basename(main.__file__))[0] But this fails for ipython notebooks with the following error: ---> 23 return os.path.splitext(os.path.bas...
Getting the file name of an ipython notebook
For python files I can get the file name and use to as a prefix for the generated results using: prefix = os.path.splitext(os.path.basename(main.__file__))[0] But this fails for ipython notebooks with the following error: ---> 23 return os.path.splitext(os.path.basename(main.__file__))[0] AttributeError: module '_...
[ "Someone already posted a workaround using JavaScript.\nYou can find the original question here: https://stackoverflow.com/a/44589075\n" ]
[ 0 ]
[]
[]
[ "ipython", "jupyter_notebook", "python" ]
stackoverflow_0074544081_ipython_jupyter_notebook_python.txt
Q: Getting a list of all subdirectories in the current directory Is there a way to return a list of all the subdirectories in the current directory in Python? I know you can do this with files, but I need to get the list of directories instead. A: Do you mean immediate subdirectories, or every directory right down ...
Getting a list of all subdirectories in the current directory
Is there a way to return a list of all the subdirectories in the current directory in Python? I know you can do this with files, but I need to get the list of directories instead.
[ "Do you mean immediate subdirectories, or every directory right down the tree? \nEither way, you could use os.walk to do this:\nos.walk(directory)\n\nwill yield a tuple for each subdirectory. Ths first entry in the 3-tuple is a directory name, so\n[x[0] for x in os.walk(directory)]\n\nshould give you all of the sub...
[ 872, 293, 261, 210, 71, 42, 31, 27, 24, 18, 13, 12, 11, 10, 9, 9, 8, 6, 5, 4, 4, 3, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 ]
[]
[]
[ "directory", "python", "subdirectory" ]
stackoverflow_0000973473_directory_python_subdirectory.txt
Q: Reverse only vowels in a string Given a string, I want to reverse only the vowels and leave the remaining string as it is. If input is fisherman output should be fashermin. I tried the following code: a=input() l=[] for i in a: if i in 'aeiou': l.append(i) siz=len(l)-1 for j in range(siz,-1,-1): fo...
Reverse only vowels in a string
Given a string, I want to reverse only the vowels and leave the remaining string as it is. If input is fisherman output should be fashermin. I tried the following code: a=input() l=[] for i in a: if i in 'aeiou': l.append(i) siz=len(l)-1 for j in range(siz,-1,-1): for k in a: if k in 'aeiou': ...
[ "You have few logical mistakes in the code.\n\nYou need to save the o/p of .replace function in another string\na= a.replace(k,'l')\n\n'l' is a string. I am sure it was list access that you were going for, so the correct syntax is: a= a.replace(k,l[j])\n\nWhen replacing if you use the same string(string 'a' in your...
[ 0, 0, 0, 0 ]
[]
[]
[ "list", "python", "python_3.x" ]
stackoverflow_0066688611_list_python_python_3.x.txt
Q: cvxpy returns problem unbounded status unexplicably I'm trying to solve an integer version of the blending problem. I want to maximize a linear objective and I have several linear constraints. The code is: # we'll need both cvxpy and numpy import cvxpy as cp import numpy as np N = 5 # the number of products M = ...
cvxpy returns problem unbounded status unexplicably
I'm trying to solve an integer version of the blending problem. I want to maximize a linear objective and I have several linear constraints. The code is: # we'll need both cvxpy and numpy import cvxpy as cp import numpy as np N = 5 # the number of products M = 5 # the number of materials # material availability of e...
[ "Thanks to Michal Adamaszek and AirSquid comments I figured a solution out.\nI don't understand yet why is this necessary but I added the restriction x >= 0 to explicitly force the solution to be non-negative. This is the code:\nimport cvxpy as cp\nimport numpy as np\n\nN = 5 # the number of products\nM = 5 # the ...
[ 0 ]
[]
[]
[ "cvxpy", "optimization", "python" ]
stackoverflow_0074530049_cvxpy_optimization_python.txt
Q: How to search inside an uploaded document? I'm trying to find a way to search inside the uploaded files. If a user uploads a pdf, CSV, word, etc... to the system, the user should be able to search inside the uploaded file with the keywords. Is there a way for that or a library? or maybe should I save the file as a...
How to search inside an uploaded document?
I'm trying to find a way to search inside the uploaded files. If a user uploads a pdf, CSV, word, etc... to the system, the user should be able to search inside the uploaded file with the keywords. Is there a way for that or a library? or maybe should I save the file as a text inside a model and search from that? I wil...
[ "Well If you save the file text in the db and then search it seems to be a practical idea.\nBut I feel there mi8 be decrease in performance.\nOr maybe you If you upload the file in S3 bucket and use the presigned url to generate the file from the db once uploaded and then perform search operation.\n" ]
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074533417_django_python.txt
Q: How to Scrape Multiple pages of one website with unchanging URL via Python? I have written following program to fetch data from all pages in this url, but its not working I don't wanna use selenium, I have used same type of program to fetch data from other url but not working for this site Please note than in thi...
How to Scrape Multiple pages of one website with unchanging URL via Python?
I have written following program to fetch data from all pages in this url, but its not working I don't wanna use selenium, I have used same type of program to fetch data from other url but not working for this site Please note than in this link pages are more than 10... #PROGRAM 1:- import requests from bs4 import Be...
[ "As explained in comments to your (now deleted) latest question, that page is optimally scraped with Selenium, to which you replied 'I don't know how to use Selenium'. It's really not difficult: here is one way of getting that data:\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Serv...
[ 0 ]
[]
[]
[ "beautifulsoup", "pandas", "python", "selenium", "web_scraping" ]
stackoverflow_0074529231_beautifulsoup_pandas_python_selenium_web_scraping.txt
Q: Pairwise rename columns for variable even number of dataframe columns Example dataframe: 0 1 0 1 3 1 2 4 Additional example dataframe: 0 1 2 3 0 1 3 5 7 1 2 4 6 8 Expected result after pairwise renaming columns of above dataframes: Item 1 ID Item 1 Title 0 1 3 1 ...
Pairwise rename columns for variable even number of dataframe columns
Example dataframe: 0 1 0 1 3 1 2 4 Additional example dataframe: 0 1 2 3 0 1 3 5 7 1 2 4 6 8 Expected result after pairwise renaming columns of above dataframes: Item 1 ID Item 1 Title 0 1 3 1 2 4 Item 1 ID Item 1 Title Item 2 ID Item 2 Title ...
[ "IIUC, you can use a simple list comprehension:\ndf.columns = [f'Item {i+1} {x}' for i in range(len(df.columns)//2)\n for x in ['ID', 'Title']]\n\noutput:\n Item 1 ID Item 1 Title Item 2 ID Item 2 Title\n0 1 3 5 7\n1 2 ...
[ 2, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0072215808_pandas_python.txt
Q: Moving all rows to a set of new columns in pandas Basically, I want to move the second row of my data frame to be the first elements of a new set of columns. I have a data frame, **Topics** **co-authors** Object Detection; Deep Learning; IOU Bandala, Argel A. Charact...
Moving all rows to a set of new columns in pandas
Basically, I want to move the second row of my data frame to be the first elements of a new set of columns. I have a data frame, **Topics** **co-authors** Object Detection; Deep Learning; IOU Bandala, Argel A. Character Recognition; Tesseract; Number Vicerra, Ryan ...
[ "The question is ambiguous, but assuming you want to perform one-hot encoding on the two columns:\nout = (df['Topics'].str.get_dummies(sep='; ')\n .join(df['co-authors'].str.get_dummies(sep='; '))\n )\n\nOutput:\n Beriberi Character Recognition Crops Deep Learning End Effectors IOU Malus Number...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074544216_dataframe_pandas_python.txt
Q: Error upgrading pip in virtualenv in Windows I'm creating a virtual environment as such: $ py -m venv venv Then activate it (I use Powershell): > venv/Scripts/activate Now I run: (venv) PS D:/...> pip install -U pip Requirement already satisfied: pip in d:\azure\app-registration\ms-identity-python-webapp\venv\li...
Error upgrading pip in virtualenv in Windows
I'm creating a virtual environment as such: $ py -m venv venv Then activate it (I use Powershell): > venv/Scripts/activate Now I run: (venv) PS D:/...> pip install -U pip Requirement already satisfied: pip in d:\azure\app-registration\ms-identity-python-webapp\venv\lib\site-packages (21.1.1) Collecting pip Download...
[ "It happening because your os didn't give the permission to create virtualenvironment.\nYou can solve it by opening powershell administrative then paste this\nSet-ExecutionPolicy unrestricted\n\nthen click enter\nafter that select Yes To All\nthen restart your ide\nit must be solve\n" ]
[ 0 ]
[]
[]
[ "pip", "powershell", "python" ]
stackoverflow_0074544287_pip_powershell_python.txt
Q: Can a lambda function call itself recursively in Python? A regular function can contain a call to itself in its definition, no problem. I can't figure out how to do it with a lambda function though for the simple reason that the lambda function has no name to refer back to. Is there a way to do it? How? A: Th...
Can a lambda function call itself recursively in Python?
A regular function can contain a call to itself in its definition, no problem. I can't figure out how to do it with a lambda function though for the simple reason that the lambda function has no name to refer back to. Is there a way to do it? How?
[ "The only way I can think of to do this amounts to giving the function a name:\nfact = lambda x: 1 if x == 0 else x * fact(x-1)\n\nor alternately, for earlier versions of python:\nfact = lambda x: x == 0 and 1 or x * fact(x-1)\n\nUpdate: using the ideas from the other answers, I was able to wedge the factorial func...
[ 87, 61, 34, 22, 12, 6, 5, 3, 3, 0, 0, 0 ]
[ "I know this is an old thread, but it ranks high on some google search results :). With the arrival of python 3.8 you can use the walrus operator to implement a Y-combinator with less syntax!\nfib = (lambda f: (rec := lambda args: f(rec, args)))\\\n (lambda f, n: n if n <= 1 else f(n-2) + f(n-1))\n\n", "As s...
[ -1, -1, -2, -3 ]
[ "lambda", "python", "recursion", "y_combinator" ]
stackoverflow_0000481692_lambda_python_recursion_y_combinator.txt
Q: Selenium - how to check that button is HIDDEN, without throwing error? (python) I'm trying to do the test to learn Allure, and to assure that the test is passed, the button has to be INVISIBLE. It first clicks 1st button to make 2nd button appear. Then click 2nd button - so same (2nd button disappears). Here it is...
Selenium - how to check that button is HIDDEN, without throwing error? (python)
I'm trying to do the test to learn Allure, and to assure that the test is passed, the button has to be INVISIBLE. It first clicks 1st button to make 2nd button appear. Then click 2nd button - so same (2nd button disappears). Here it is: http://the-internet.herokuapp.com/add_remove_elements/ My code would look like this...
[ "You can wrap the deleteCheck in a try block:\ntry:\n deleteCheck = browser.find_element(By.XPATH, \"/html/body/div[2]/div/div/div/button\")\n assert False\nexcept NoSuchElementException:\n assert True\n\n", "you can try this code to wait for that element in 15 second\nand if it does not appear then cont...
[ 1, 1, 1 ]
[]
[]
[ "findelement", "python", "selenium", "selenium_webdriver", "xpath" ]
stackoverflow_0074544092_findelement_python_selenium_selenium_webdriver_xpath.txt
Q: How to alter file type and then save to a new directory? I have been attempting to change all files in a folder of a certain type to another and then save them to another folder I have created. In my example the files are being changed from '.dna' files to '.fasta' files. I have successfully completed this via thi...
How to alter file type and then save to a new directory?
I have been attempting to change all files in a folder of a certain type to another and then save them to another folder I have created. In my example the files are being changed from '.dna' files to '.fasta' files. I have successfully completed this via this code: files = Path(directory).glob('*.dna') for file in file...
[ "Hi, You can use os lib to rename the file with the new extension (type)\nimport os\nmy_file = 'my_file.txt'\nbase = os.path.splitext(my_file)[0]\nos.rename(my_file, base + '.bin')\n\nAnd you can use shutil lib to move the file to a new directory.\nimport shutil\n\n# absolute path\nsrc_path = r\"E:\\pynative\\repor...
[ 0 ]
[]
[]
[ "biopython", "directory", "python" ]
stackoverflow_0074543872_biopython_directory_python.txt
Q: How can I check the extension of a file? I'm working on a certain program where I need to do different things depending on the extension of the file. Could I just use this? if m == *.mp3 ... elif m == *.flac ... A: Assuming m is a string, you can use endswith: if m.endswith('.mp3'): ... elif m.endswith('.f...
How can I check the extension of a file?
I'm working on a certain program where I need to do different things depending on the extension of the file. Could I just use this? if m == *.mp3 ... elif m == *.flac ...
[ "Assuming m is a string, you can use endswith:\nif m.endswith('.mp3'):\n...\nelif m.endswith('.flac'):\n...\n\nTo be case-insensitive, and to eliminate a potentially large else-if chain:\nm.lower().endswith(('.png', '.jpg', '.jpeg'))\n\n", "os.path provides many functions for manipulating paths/filenames. (docs)\...
[ 560, 70, 61, 20, 9, 9, 6, 5, 4, 2, 2, 1, 0, 0 ]
[]
[]
[ "file_extension", "python" ]
stackoverflow_0005899497_file_extension_python.txt
Q: How to convert local time array to UTC array? I have tried to combine timezonefinder and pytz like this: import numpy as np import pandas as pd from pytz import timezone from timezonefinder import TimezoneFinder tf = TimezoneFinder() def get_utc(local_time, lat, lon): """ returns a location's time zone o...
How to convert local time array to UTC array?
I have tried to combine timezonefinder and pytz like this: import numpy as np import pandas as pd from pytz import timezone from timezonefinder import TimezoneFinder tf = TimezoneFinder() def get_utc(local_time, lat, lon): """ returns a location's time zone offset from UTC in minutes. """ tz_target = ...
[ "Here's a modified version of your code, that handles the timezone not found problem. In that case, np.datetime64(\"NaT\") is returned, which allows you to keep the dtype of the result as np.datetime64.\nI also took the freedom to replace pytz and use native Python datetime instead of pandas.\nfrom datetime import ...
[ 1 ]
[]
[]
[ "arrays", "datetime", "numpy", "pandas", "python" ]
stackoverflow_0074544075_arrays_datetime_numpy_pandas_python.txt
Q: "Name or Service not known" while attaching to container I'm dockerizin a flask app and everything works till container creation after that there is an error "Name or Service not known" Dockerfile: FROM python:3.10.8 COPY requirements.txt . RUN pip install -r requirements.txt RUN python -c "import nltk; nltk.do...
"Name or Service not known" while attaching to container
I'm dockerizin a flask app and everything works till container creation after that there is an error "Name or Service not known" Dockerfile: FROM python:3.10.8 COPY requirements.txt . RUN pip install -r requirements.txt RUN python -c "import nltk; nltk.download('averaged_perceptron_tagger'); nltk.download('wordnet'...
[ "Found an answer with the help of @David Maze.\n--host= 0.0.0.0\n\nHad a space after \"host=\" which caused this issue.\nRemoval of the space got it running.\n" ]
[ 2 ]
[]
[]
[ "docker", "docker_compose", "flask", "nltk", "python" ]
stackoverflow_0074443865_docker_docker_compose_flask_nltk_python.txt
Q: How to interpret the values returned by numpy.correlate and numpy.corrcoef? I have two 1D arrays and I want to see their inter-relationships. What procedure should I use in numpy? I am using numpy.corrcoef(arrayA, arrayB) and numpy.correlate(arrayA, arrayB) and both are giving some results that I am not able to co...
How to interpret the values returned by numpy.correlate and numpy.corrcoef?
I have two 1D arrays and I want to see their inter-relationships. What procedure should I use in numpy? I am using numpy.corrcoef(arrayA, arrayB) and numpy.correlate(arrayA, arrayB) and both are giving some results that I am not able to comprehend or understand. Can somebody please shed light on how to understand and i...
[ "numpy.correlate simply returns the cross-correlation of two vectors. \nif you need to understand cross-correlation, then start with http://en.wikipedia.org/wiki/Cross-correlation.\nA good example might be seen by looking at the autocorrelation function (a vector cross-correlated with itself):\nimport numpy as np\n...
[ 19, 12, 8, 2, 0 ]
[]
[]
[ "correlation", "numpy", "python", "scipy" ]
stackoverflow_0013439718_correlation_numpy_python_scipy.txt
Q: Converting SQLite database column values to strings and concatenating I have a database with the following format. (1, 'Kristen', 'Klein', '2002-11-03', 'North Cynthiafurt', 'AZ', '50788') I am trying to strip away the first and last name values and pass them to a function to concatenate them as strings. "Kristen ...
Converting SQLite database column values to strings and concatenating
I have a database with the following format. (1, 'Kristen', 'Klein', '2002-11-03', 'North Cynthiafurt', 'AZ', '50788') I am trying to strip away the first and last name values and pass them to a function to concatenate them as strings. "Kristen Klein" in this case. I use a query such as: query_first = db.select([custom...
[ "This [('Kristen',), ('April',), ('Justin',)] - is a list of tuples. If you are confused by the trailing comma after string, because it is required to distinguish it as a tuple for single element tuple's.\nFind out the full info here in python wiki.\nI guess you were using sqlalchemy library to connect to the db. I...
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0069512537_python.txt
Q: Apply tf.keras model to tensor of variable shape I have a tf.keras model that takes as input a tensor of shape (batch_size, ) and outputs another tensor of the same shape. The result at index i does not depend on any of the inputs at index j != i. I would like to apply this model on tensors of any shape (dim1, dim...
Apply tf.keras model to tensor of variable shape
I have a tf.keras model that takes as input a tensor of shape (batch_size, ) and outputs another tensor of the same shape. The result at index i does not depend on any of the inputs at index j != i. I would like to apply this model on tensors of any shape (dim1, dim2, ..., dimn). In theory this should be possible, but ...
[ "In the end I solved it like this:\ndef apply_model(X: tf.Tensor, my_model: tf.keras.Model) -> tf.Tensor:\n \"\"\"\n Apply a tf.keras.Model to a tensor of unknown dimensions.\n\n Args:\n X (tf.Tensor): The tensor containing the input.\n my_model (tf.keras.Model): The model...
[ 0 ]
[]
[]
[ "python", "tensorflow", "tf.keras" ]
stackoverflow_0074522378_python_tensorflow_tf.keras.txt
Q: I need to add an if statement before conducting some calculations in python I have a list consisting of 4 attributes: subject, test, score, and result. I need to calculate the total score for each subject, by adding up the test scores for each subject. I currently have that. But I need to calculate the total test ...
I need to add an if statement before conducting some calculations in python
I have a list consisting of 4 attributes: subject, test, score, and result. I need to calculate the total score for each subject, by adding up the test scores for each subject. I currently have that. But I need to calculate the total test score of passed tests, and then divide that number by the total test score of all...
[ "You want to add to the total in dc only if the test is passed, so why not do that in the first place?\nfor sub, scr, completion, in zip(subject, score, result):\n points = float(scr)\n d[sub] += points\n if completion == \"pass\":\n dc[sub] += points\n\nNow, you have\nd = defaultdict(float, {'Math'...
[ 1, 1, 0 ]
[]
[]
[ "if_statement", "python" ]
stackoverflow_0074539951_if_statement_python.txt
Q: Create New True/False Pandas Dataframe Column based on conditions Year District Geometry TRUE/FALSE 1900 101 POLYGON ((-89.26355 41.32246, -89.26171 41.322... TRUE 1902 101 POLYGON ((-89.26355 41.33246, -89.26171 41.322... FALSE I have a dataframe with a large number of columns and rows (only a sample above) an...
Create New True/False Pandas Dataframe Column based on conditions
Year District Geometry TRUE/FALSE 1900 101 POLYGON ((-89.26355 41.32246, -89.26171 41.322... TRUE 1902 101 POLYGON ((-89.26355 41.33246, -89.26171 41.322... FALSE I have a dataframe with a large number of columns and rows (only a sample above) and I am trying to create a new column with a conditional resp...
[ "Depending on how your rows are actually organized, you could use eq together with a shift.\n(partial answer from here)\nFirst create the dummy dataframe:\nimport pandas as pd\n\ndata = {'Year':[1900,1901,1902],\n 'District':[101,101,101],\n 'Geometry':[\n 'POLYGON ((-89.26355 41.32246, -8...
[ 0 ]
[]
[]
[ "conditional_statements", "dataframe", "pandas", "python" ]
stackoverflow_0074543702_conditional_statements_dataframe_pandas_python.txt
Q: Scaling and data leakage on cross validation and test set I have more of a best practice question. I am scaling my data and I understand that I should fit_transform on my training set and transform on my test set because of potential data leakage. Now if I want to use both (5 fold) Cross validation on my training ...
Scaling and data leakage on cross validation and test set
I have more of a best practice question. I am scaling my data and I understand that I should fit_transform on my training set and transform on my test set because of potential data leakage. Now if I want to use both (5 fold) Cross validation on my training set but I use a holdout test set anyway is it necessary to scal...
[ "It's definitely best practice to include everything within your cross-validation loop to avoid data leakage. Any scaling should be done on the training set and then applied to the test set within each CV loop.\n" ]
[ 0 ]
[]
[]
[ "cross_validation", "machine_learning", "mlxtend", "python", "scikit_learn" ]
stackoverflow_0072808905_cross_validation_machine_learning_mlxtend_python_scikit_learn.txt
Q: Django form 2 not loading I am trying to build a inventory management project facing some difficulty, Looking for a solution. I have created a 2 form in django model and when I try to load form2 only form1 is loading for all the condition. I have tried to comment form1 and load only form2 with that I got the expe...
Django form 2 not loading
I am trying to build a inventory management project facing some difficulty, Looking for a solution. I have created a 2 form in django model and when I try to load form2 only form1 is loading for all the condition. I have tried to comment form1 and load only form2 with that I got the expected result but when I try to a...
[ "Instead of this:\n<a href=\"/QC_form\">Incoming Quality Check</a>\n<a href=\"/form\">Inventory Store Management</a>\n\nTry this:\n<a href=\"{% url 'QC_form' %}\">Incoming Quality Check</a>\n<a href=\"{% url 'form' %}\">Inventory Store Management</a>\n\nI think the problem is in view.\nSimply try this:\ndef Incomin...
[ 0 ]
[]
[]
[ "django", "django_forms", "django_models", "python" ]
stackoverflow_0074544009_django_django_forms_django_models_python.txt
Q: Matplotlib: Scale axis by multiplying with a constant Is there a quick way to scale axis in matplotlib? Say I want to plot import matplotlib.pyplot as plt c= [10,20 ,30 , 40] plt.plot(c) it will plot How can I scale x-axis quickly, say multiplying every value with 5? One way is creating an array for x axis: x = ...
Matplotlib: Scale axis by multiplying with a constant
Is there a quick way to scale axis in matplotlib? Say I want to plot import matplotlib.pyplot as plt c= [10,20 ,30 , 40] plt.plot(c) it will plot How can I scale x-axis quickly, say multiplying every value with 5? One way is creating an array for x axis: x = [i*5 for i in range(len(c))] plt.plot(x,c) I am wondering...
[ "Use a numpy.array instead of a list,\nc = np.array([10, 20, 30 ,40]) # or `c = np.arange(10, 50, 10)`\nplt.plot(c)\nx = 5*np.arange(c.size) # same as `5*np.arange(len(c))`\n\nThis gives:\n>>> print x\narray([ 0, 5, 10, 15])\n\n", "It's been a long time since this question is asked, but as I searched for that...
[ 1, 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0034080270_matplotlib_python.txt
Q: Django Login Required to view I am building a small application which needs user profiles, I've used the build in user system from Django. But I have a problem regarding that even if you are not logged in you can still view the profile also another thing is that each user should only see his profile not others I n...
Django Login Required to view
I am building a small application which needs user profiles, I've used the build in user system from Django. But I have a problem regarding that even if you are not logged in you can still view the profile also another thing is that each user should only see his profile not others I need some tips on this views.py cla...
[ "Since you are using the Class Based Generic View, you need to add decorator @login_required in your urls.py\n#urls.py\n\nfrom django.contrib.auth.decorators import login_required\nfrom app_name import views\n\nurl(r'^test/$', login_required(views.UserProfileDetailView.as_view()), name='test'),\n\n", "Have you ch...
[ 5, 0, 0 ]
[ "The below is what you should typically do\n@login_required\ndef my_view(request, uid):\n # uid = user id taken from profile url\n me = User.objects.get(pk=uid)\n if me != request.user:\n raise Http404\n\n" ]
[ -2 ]
[ "django", "python" ]
stackoverflow_0019216440_django_python.txt
Q: psycopg: Python.h: No such file or directory I'm compiling psycopg2 and get the following error: Python.h: No such file or directory How to compile it, Ubuntu12 x64. A: Python 2: sudo apt-get install python-dev Python 3: sudo apt-get install python3-dev A: This is a dependency issue. I resolved this issue on ...
psycopg: Python.h: No such file or directory
I'm compiling psycopg2 and get the following error: Python.h: No such file or directory How to compile it, Ubuntu12 x64.
[ "Python 2:\nsudo apt-get install python-dev\n\nPython 3:\nsudo apt-get install python3-dev\n\n", "This is a dependency issue.\nI resolved this issue on Ubuntu using apt-get. Substitute it with a package manager appropriate to your system.\nFor any current Python version:\nsudo apt-get install python-dev\n\nFor al...
[ 75, 30, 8, 2, 1, 1, 1 ]
[ "if none of the above-suggested answers is not working, try this it's worked for me.\nsudo apt-get install libpq-dev\n\n" ]
[ -1 ]
[ "psycopg2", "python" ]
stackoverflow_0019843945_psycopg2_python.txt
Q: How to convert path into json in python? I'm getting values in the below format /a/b/c/d="value1" /a/b/e/f="value2" I want these values in the below format. { "a": { "b": { { "c": { "d": "value1" } }, { ...
How to convert path into json in python?
I'm getting values in the below format /a/b/c/d="value1" /a/b/e/f="value2" I want these values in the below format. { "a": { "b": { { "c": { "d": "value1" } }, { "e" { "f": "value2" ...
[ "Feels a bit hacky, but if you want to go with the a[\"b\"][\"c\"][\"d\"] route, you could use collections.defaultdict to do it.\nfrom collections import defaultdict\n\ndef defaultdict_factory():\n return defaultdict(defaultdict)\n\na = defaultdict(defaultdict_factory)\n\na[\"b\"][\"c\"][\"d\"] = \"value1\"\n\n"...
[ 1, 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074544321_python_python_3.x.txt
Q: TypeError: must be str, not NoneType in bluetooth ` def arduino_connect(): global sock print("Cihazlar axtarılır....") nearby_devices = bluetooth.discover_devices() num = 0 for i in nearby_devices: num+=1 print(str(num)+":"+bluetooth.lookup_name(i)+" MAC: "+i) if i=="00:...
TypeError: must be str, not NoneType in bluetooth
` def arduino_connect(): global sock print("Cihazlar axtarılır....") nearby_devices = bluetooth.discover_devices() num = 0 for i in nearby_devices: num+=1 print(str(num)+":"+bluetooth.lookup_name(i)+" MAC: "+i) if i=="00:21:13:00:EF:19": selection = num-1 bd_a...
[ "When joining items using the + operator, they have to be of the same type.\nThat means that if bluetooth.lookup_name(i) returns a result which isn't a string (a NoneType in your case) than the concatenation fails.\nYou can use format string to print the result anyway -\nprint(f\"{}:{} MAC: {}\".format(num, bluetoo...
[ 0 ]
[]
[]
[ "non_type", "python", "typeerror" ]
stackoverflow_0074544740_non_type_python_typeerror.txt
Q: Error when transforming resultos to df from Bigquery This is the typical connection I have from my local device: from google.cloud import bigquery from google.oauth2 import service_account credentials_path = "credential path" credentials = service_account.Credentials.from_service_account_file(credentials_path) p...
Error when transforming resultos to df from Bigquery
This is the typical connection I have from my local device: from google.cloud import bigquery from google.oauth2 import service_account credentials_path = "credential path" credentials = service_account.Credentials.from_service_account_file(credentials_path) project_id = "project id" client = bigquery.Client(credenti...
[ "Use google-cloud-bigquery[pandas] as requirement instead of google-cloud-bigquery.\nFor installing it: pip install google-cloud-bigquery[pandas]\n" ]
[ 0 ]
[]
[]
[ "google_bigquery", "jupyter_notebook", "python" ]
stackoverflow_0074539669_google_bigquery_jupyter_notebook_python.txt
Q: Pushing QWidget Window to topmost in Python I'm new to Python and have mostly learnt C# in the past. I am creating a QWidget class: class Window(QWidget): def __init__(self, gif, width, height): super().__init__() self.setGeometry(400, 200, width, height) self.setWindowTitle("Python Ru...
Pushing QWidget Window to topmost in Python
I'm new to Python and have mostly learnt C# in the past. I am creating a QWidget class: class Window(QWidget): def __init__(self, gif, width, height): super().__init__() self.setGeometry(400, 200, width, height) self.setWindowTitle("Python Run GIF Images") self.setWindowIcon(QIcon('...
[ "Using setWindowFlag(Qt.WindowType.WindowStaysOnTopHint, True) seems to be working for me so far.\nExample:\nfrom PySide6.QtWidgets import *\nfrom PySide6.QtCore import *\nfrom PySide6.QtGui import *\n\n\nclass Window(QWidget):\n\n def __init__(self, parent=None):\n super().__init__(parent=parent)\n ...
[ 0 ]
[]
[]
[ "gif", "pyside6", "python", "qapplication", "qwidget" ]
stackoverflow_0074521530_gif_pyside6_python_qapplication_qwidget.txt
Q: make dict by averaging values in python keys = ['a', 'a' ,'a' ,'b' ,'b' ,'c'] values = [2, 4, 6, 6, 4 ,3] Here it is guaranteed that len(keys)==len(values). You can also assume that the keys are sorted. I would like to create a dictionary where the new values will be the average of the old values. If I do x = dic...
make dict by averaging values in python
keys = ['a', 'a' ,'a' ,'b' ,'b' ,'c'] values = [2, 4, 6, 6, 4 ,3] Here it is guaranteed that len(keys)==len(values). You can also assume that the keys are sorted. I would like to create a dictionary where the new values will be the average of the old values. If I do x = dict(zip(keys, values)) # {'a': 3, 'b': 4, 'c': ...
[ "I think the cleanest solution would be what you suggested - grouping it by key, summing and dividing with length. I guess dataframe based solution could be quicker, but I really don't think that's enough usecase to justify additional external libraries.\nfrom collections import defaultdict\n\nkeys = ['a', 'a' ,'a'...
[ 3, 3 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074544760_dictionary_python.txt
Q: Parsing JSON in AWS Lambda Python For a personal project I'm trying to write an AWS Lambda in Python3.9 that will delete a newly created user, if the creator is not myself. For this, the logs in CloudWatch Logs will trigger (via CloudTrail and EventBridge) my Lambda. Therefore, I will receive the JSON request as m...
Parsing JSON in AWS Lambda Python
For a personal project I'm trying to write an AWS Lambda in Python3.9 that will delete a newly created user, if the creator is not myself. For this, the logs in CloudWatch Logs will trigger (via CloudTrail and EventBridge) my Lambda. Therefore, I will receive the JSON request as my event in : def lambdaHandler(event, c...
[ "What you are printing is a python dict, it looks sort of like JSON but is not JSON, it is the representation of a python dict. That means it will have True / False instead of true / false, it will have ' instead of \", etc.\nYou could do print(json.dumps(event)) instead.\nAnyway, the actual problem is that invokin...
[ 1 ]
[]
[]
[ "amazon_cloudwatchlogs", "amazon_web_services", "aws_lambda", "json", "python" ]
stackoverflow_0074544747_amazon_cloudwatchlogs_amazon_web_services_aws_lambda_json_python.txt
Q: Using casefold() with dataframe Column Names and .contains method How do I look for instances in the dataframe where the 'Campaign' column contains b0. I would like to not alter the dataframe values but instead just view them as if they were lowercase. df.loc.str.casefold()[df['Campaign'].str.casefold().contains('...
Using casefold() with dataframe Column Names and .contains method
How do I look for instances in the dataframe where the 'Campaign' column contains b0. I would like to not alter the dataframe values but instead just view them as if they were lowercase. df.loc.str.casefold()[df['Campaign'].str.casefold().contains('b0')] I recently inquired about doing this in the instance of matching...
[ "Try with\ndf.loc[df['Campaign'].str.contains('b0',case=False)]\n\n", "Alternatively, if you want to create a subset of the dataframe:\ndf_subset = df[(df[('Campaign')].str.casefold().str.contains('b0', na=False))] \n" ]
[ 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0069833410_pandas_python.txt
Q: How to integrate and visualize 1d kde with scipy? I have a 1d array, and I have used scipy.stats.gaussian_kde to get the pdf. Now I want to compute the integral of each particular data point and my code is as below. Does this make sense? if not, what is the correct solution? Btw,how can I visualize the pdf and the...
How to integrate and visualize 1d kde with scipy?
I have a 1d array, and I have used scipy.stats.gaussian_kde to get the pdf. Now I want to compute the integral of each particular data point and my code is as below. Does this make sense? if not, what is the correct solution? Btw,how can I visualize the pdf and the integral function? Thanku X=np.array([0.21,0.21,0.21,...
[ "To plot the kde, you need to create a dense array of x-values. The integral at the given points can be plotted via a scatter plot.\nfrom matplotlib import pyplot as plt\nimport numpy as np\nimport scipy, scipy.stats\n\nX = np.array([0.21,0.21,0.21,0.28,0.30,0.30,0.24,0.22,0.19,0.20,0.18,0.23,0.20,0.12,0.14,0.13,0...
[ 0 ]
[]
[]
[ "math", "python", "scipy" ]
stackoverflow_0074541617_math_python_scipy.txt
Q: Python 3: CSV Module I am working with a simple csv file and want to know how to update the values contained in a specific cell on each row using data my script has generated. column1, column2, colum3, column4, bob, 20, blue, hammer jane, 30, red, pencil chris, 40, green, ruler Then: new_colour = [pink, yellow, b...
Python 3: CSV Module
I am working with a simple csv file and want to know how to update the values contained in a specific cell on each row using data my script has generated. column1, column2, colum3, column4, bob, 20, blue, hammer jane, 30, red, pencil chris, 40, green, ruler Then: new_colour = [pink, yellow, black] Is there a way to t...
[ "One (probably unoptimized) solution could be using the pandas module, as long as your CSV file is not too big:\nPATH_TO_CSV = <your_path>\nnew_colour = ['pink', 'yellow', 'black']\n\ndf = pd.read_csv(PATH_TO_CSV)\ndf['colum3'] = pd.Series(new_colour)\ndf.to_csv(PATH_TO_CSV)\n\n" ]
[ 2 ]
[]
[]
[ "csv", "python", "python_3.x" ]
stackoverflow_0074540287_csv_python_python_3.x.txt
Q: Iterate over a list of floats- python I'm trying to use Markov clustering (MCL) to cluster (6) data points, the matrix represents a similarity matrix between data points based on some criteria. my data: import warnings import math import random import pandas as pd import numpy as np import matplotlib.pyplot as plt...
Iterate over a list of floats- python
I'm trying to use Markov clustering (MCL) to cluster (6) data points, the matrix represents a similarity matrix between data points based on some criteria. my data: import warnings import math import random import pandas as pd import numpy as np import matplotlib.pyplot as plt from scipy.optimize import linear_sum_assi...
[ "You can not iterate over a list of floats (as the exception clearly says). Do that instead:\nfor i in range(15, 26):\n inflation = i/10\n # ... your code\n\n" ]
[ 0 ]
[]
[]
[ "cluster_analysis", "graph_theory", "pandas", "python" ]
stackoverflow_0074523622_cluster_analysis_graph_theory_pandas_python.txt
Q: ImportError: cannot import name language in Google Cloud Language API I am trying to use this sample code from the Google Natural Language API to get a sentiment score back. However, each time I run the code, I get an "ImportError: cannot import name language." error on the first line. I have pip installed the li...
ImportError: cannot import name language in Google Cloud Language API
I am trying to use this sample code from the Google Natural Language API to get a sentiment score back. However, each time I run the code, I get an "ImportError: cannot import name language." error on the first line. I have pip installed the library, tried uninstalling and reinstalling, made the credentials on the con...
[ "This seems to be a duplicate of this question:\nGoogle sentiment analysis - ImportError: cannot import name language\nFor me, wasn't enough to upgrade google-api-python-client and google-cloud\nInstead, what solved my problem was:\n!pip install google-cloud-language\n\nBesides, when you upgrade google api librarie...
[ 13, 2, 2, 2, 0 ]
[]
[]
[ "google_api", "google_cloud_functions", "google_cloud_platform", "google_natural_language", "python" ]
stackoverflow_0050072510_google_api_google_cloud_functions_google_cloud_platform_google_natural_language_python.txt
Q: ImportError: No module named mpl_toolkits with maptlotlib 1.3.0 and py2exe I can't figure out how to be able to package this via py2exe now: I am running the command: python setup2.py py2exe via python 2.7.5 and matplotlib 1.3.0 and py2exe 0.6.9 and 0.6.10dev This worked with matplotlib 1.2.x I have read http://w...
ImportError: No module named mpl_toolkits with maptlotlib 1.3.0 and py2exe
I can't figure out how to be able to package this via py2exe now: I am running the command: python setup2.py py2exe via python 2.7.5 and matplotlib 1.3.0 and py2exe 0.6.9 and 0.6.10dev This worked with matplotlib 1.2.x I have read http://www.py2exe.org/index.cgi/ExeWithEggs and tried to implement the suggestions for h...
[ "There is a quite simple workaround to this problem. Find the directory from which mpl_tools is imported and simply add an empty text file named __init__.py in that directory. py2exe will now find and include this module without any special imports needed in the setup file.\nYou can find the mpl_tools directory by ...
[ 25, 11, 3, 0, 0 ]
[]
[]
[ "matplotlib", "py2exe", "python", "python_import" ]
stackoverflow_0018596410_matplotlib_py2exe_python_python_import.txt
Q: How to enable Docker Build Context in azure machine learning studio? I'm trying to create an environment from a custom Dockerfile in the UI of Azure Machine Learning Studio. It previously used to work when I used the option: Create a new Docker context. I decided to do it through code and build the image on comput...
How to enable Docker Build Context in azure machine learning studio?
I'm trying to create an environment from a custom Dockerfile in the UI of Azure Machine Learning Studio. It previously used to work when I used the option: Create a new Docker context. I decided to do it through code and build the image on compute, meaning I used this line to set it: ws.update(image_build_compute = "my...
[ "Created compute cluster with some specifications and there is a possibility to update the version of the cluster and checkout the code block.\n\nworkspace.update(image_build_compute = \"Standard_DS12_v2\")\n\nWe can create the compute instance using the UI of the portal using the following steps using the docker.\...
[ 0 ]
[]
[]
[ "azure_machine_learning_service", "azure_machine_learning_studio", "azuremlsdk", "docker", "python" ]
stackoverflow_0074530536_azure_machine_learning_service_azure_machine_learning_studio_azuremlsdk_docker_python.txt
Q: Non useful tkinter window appears in spyder Question 1: I have a non useful window that appears when using tkinter in spyder. Any solution for this issue ? Question 2: Why there is a warning message on 'from tkinter import *' ? Code: from tkinter import * from tkinter.simpledialog import askstring from tkinter im...
Non useful tkinter window appears in spyder
Question 1: I have a non useful window that appears when using tkinter in spyder. Any solution for this issue ? Question 2: Why there is a warning message on 'from tkinter import *' ? Code: from tkinter import * from tkinter.simpledialog import askstring from tkinter import messagebox box = Tk() name = askstring('N...
[ "The \"non useful\" window is simply box.\nmessagebox will open a new window. So you can just remove box if you don't intend to use it further.\nIt's usually not recommended to import everything from a module because it could cause name conflicts with other modules or built-in function:\nimport tkinter as tk\nfrom ...
[ 1, 1 ]
[ "For the first question answer is that you don't need to create box because function askstring create frame on it's own. So if the whole program is just to ask for the name and to greet user, you are perfectly fine with just this piece of code:\nfrom tkinter import *\nfrom tkinter.simpledialog import askstring\nfro...
[ -1 ]
[ "python", "spyder", "tkinter" ]
stackoverflow_0074544778_python_spyder_tkinter.txt
Q: How would you go about finding longest string per row in a data frame? I am writing a piece of code which allows me to open a CSV file, remove nan rows and also find strings that are too long in the data frame. I want the program to say what row the length of data exceeds the 30-character limit and give you an opt...
How would you go about finding longest string per row in a data frame?
I am writing a piece of code which allows me to open a CSV file, remove nan rows and also find strings that are too long in the data frame. I want the program to say what row the length of data exceeds the 30-character limit and give you an option to exit or skip. I previously had it set up so it would go by columns in...
[ "I would recommend not to use a loop, but rather to vectorize.\nSo, you want to identify the strings longer than a threshold, except for excluded columns?\nAssuming this example:\n col1 col2 col3\n0 abc A this_is_excluded\n1 defghijkl BCDEF excluded\n2 ...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074544966_dataframe_pandas_python.txt
Q: PUTing files into S3 using Python requests I've got this URL that was generated using the generate_url(300, 'PUT', ...) method and I'm wanting to use the requests library to upload a file into it. This is the code I've been using: requests.put(url, data=content, headers={'Content-Type': content_type}), I've also t...
PUTing files into S3 using Python requests
I've got this URL that was generated using the generate_url(300, 'PUT', ...) method and I'm wanting to use the requests library to upload a file into it. This is the code I've been using: requests.put(url, data=content, headers={'Content-Type': content_type}), I've also tried some variations on this but the error I get...
[ "Using boto3, this is how to generate an upload url and to PUT some data in it:\nsession = boto3.Session(aws_access_key_id=\"XXX\", aws_secret_access_key=\"XXX\")\ns3client = session.client('s3')\nurl = s3client.generate_presigned_url('put_object', Params={'Bucket': 'mybucket', 'Key': 'mykey'})\n\nrequests.put(url,...
[ 1, 0, 0 ]
[]
[]
[ "amazon_s3", "boto", "python", "python_requests" ]
stackoverflow_0011580874_amazon_s3_boto_python_python_requests.txt
Q: How does sklearn.tree.DecisionTreeClassifier function predict_proba() work internally? I know how to use predict_proba() and the meaning of the output. Can anyone tell me how predict_proba() internally calculates the probability for decision tree? A: First You have to see this for basics of decision tree https:/...
How does sklearn.tree.DecisionTreeClassifier function predict_proba() work internally?
I know how to use predict_proba() and the meaning of the output. Can anyone tell me how predict_proba() internally calculates the probability for decision tree?
[ "First You have to see this for basics of decision tree https://www.youtube.com/watch?v=_L39rN6gz7Y and after that here is the link :https://www.youtube.com/watch?v=wpNl-JwwplA\nto see how these probabilities are calculated.\nHere for predict_proba() function just finds out the probability of occurrence of all the ...
[ 0 ]
[]
[]
[ "decisiontreeclassifier", "predict_proba", "python", "scikit_learn" ]
stackoverflow_0074544624_decisiontreeclassifier_predict_proba_python_scikit_learn.txt
Q: How can I convert Conll 2003 format to json format? I have a list of sentences with each word of a sentence being in a nested list. Such as: [['EU', 'rejects', 'German', 'call', 'to', 'boycott', 'British', 'lamb', '.'], ['Peter', 'Blackburn'], ['BRUSSELS', '1996-08-22']] And also another list where each word cr...
How can I convert Conll 2003 format to json format?
I have a list of sentences with each word of a sentence being in a nested list. Such as: [['EU', 'rejects', 'German', 'call', 'to', 'boycott', 'British', 'lamb', '.'], ['Peter', 'Blackburn'], ['BRUSSELS', '1996-08-22']] And also another list where each word creesponds to an entity tag. Such as: [['B-ORG', 'O', 'B-MI...
[ "You can convert the sentences to pandas Dataframe with there respective entity tags and join them. Here is an inspiration.\nYou can also look at this is your data is in usual CoNLL format\n" ]
[ 0 ]
[]
[]
[ "conll", "doccano", "json", "python" ]
stackoverflow_0065619397_conll_doccano_json_python.txt
Q: Why am I getting error message as "ModuleNotFoundError: No module named 'plotly.express" while it was working before? I'm having this bizarre experience; I'm re-running a code to plot a geographical graph using Plotly and use import plotly.express as px but it gives me the error message saying that "ModuleNotFound...
Why am I getting error message as "ModuleNotFoundError: No module named 'plotly.express" while it was working before?
I'm having this bizarre experience; I'm re-running a code to plot a geographical graph using Plotly and use import plotly.express as px but it gives me the error message saying that "ModuleNotFoundError: No module named 'plotly.express'". I can confirm that plotly is installed, and most importantly it was working until...
[ "Apparently, it turned out that upgrading plotly version solved the problem.\nTo upgrade plotly, I simply run the following codes to check the plotly version.\nimport plotly\nplotly.__version__\n\nThat gave me the output of version of plotly as '5.11.0'. Then I upgraded the plotly version to '5.11.0' by writing the...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074531412_python.txt
Q: Find consecutive series in list of tuples in python I am struggling with the following issue: I would like to write some small code to deisotope mass spec data. For this, I compare, if the difference between two signals is equal the mass of a proton devided by the charge state. So far, so easy. I am struggling now...
Find consecutive series in list of tuples in python
I am struggling with the following issue: I would like to write some small code to deisotope mass spec data. For this, I compare, if the difference between two signals is equal the mass of a proton devided by the charge state. So far, so easy. I am struggling now, to find series of more than two peaks. I broke down the...
[ "In graph theory your problem will be \"How to find all disconnected subgraph in a graph ?\".\nSo why not using a network analysis library such as networkx:\nimport networkx as nx\n# Your tuples become the edges of the graph.\nedge = [(1,2), (2,3), (4,5), (7,9), (8,10), (9,11)]\n\n# We create the graph\nG = nx.Grap...
[ 5, 2, 1, 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074534622_numpy_python.txt
Q: How can I add a certain cell to its respective column/row I have this Excel file that looks like this . For every name, I want to add for each group the respective cells. So I would expect a for loop that iterates by +4 rows to go through all the names. Here's what I've done so far: import openpyxl doc = openpyx...
How can I add a certain cell to its respective column/row
I have this Excel file that looks like this . For every name, I want to add for each group the respective cells. So I would expect a for loop that iterates by +4 rows to go through all the names. Here's what I've done so far: import openpyxl doc = openpyxl.load_workbook('World Cup Bet Tournament.xlsx') doc_activati...
[ "You just want to build your user's group from the values in the cell, then add that to the a group dictionary with the group name as the key e.g. GROUPA, GROUPB etc which is then added to the overall dictionary under the user's name.\nSee example code\nimport openpyxl\n\n\ndoc = openpyxl.load_workbook('World Cup B...
[ 0 ]
[]
[]
[ "dictionary", "excel", "list", "openpyxl", "python" ]
stackoverflow_0074519801_dictionary_excel_list_openpyxl_python.txt
Q: Python Sphinx autodoc and decorated members I am attempting to use Sphinx to document my Python class. I do so using autodoc: .. autoclass:: Bus :members: While it correctly fetches the docstrings for my methods, those that are decorated: @checkStale def open(self): """ Some docs. ...
Python Sphinx autodoc and decorated members
I am attempting to use Sphinx to document my Python class. I do so using autodoc: .. autoclass:: Bus :members: While it correctly fetches the docstrings for my methods, those that are decorated: @checkStale def open(self): """ Some docs. """ # Code with @checkStale being def...
[ "I had the same problem with the celery @task decorator.\nYou can also fix this in your case by adding the correct function signature to your rst file, like this:\n.. autoclass:: Bus\n :members:\n\n .. automethod:: open(self)\n .. automethod:: some_other_method(self, param1, param2)\n\nIt will still docume...
[ 15, 14, 3, 2, 2, 1, 0, 0, 0 ]
[]
[]
[ "autodoc", "decorator", "python", "python_sphinx" ]
stackoverflow_0003687046_autodoc_decorator_python_python_sphinx.txt
Q: how do I use *args when working with a string I tried to use the *args when working with a list of strings and the output remained a tuple. I'm trying ensure that all letters in the string are uppercase but I cant figure it out I tried tuple unpacking but it doesn't work on an indefinite number of objects A: *ar...
how do I use *args when working with a string
I tried to use the *args when working with a list of strings and the output remained a tuple. I'm trying ensure that all letters in the string are uppercase but I cant figure it out I tried tuple unpacking but it doesn't work on an indefinite number of objects
[ "*args is used to pass variable number of arguments to a function. Here's a reference article: https://www.geeksforgeeks.org/args-kwargs-python/\nAs far as working with a function that has a *args of strings, since *args groups its arguments into a tuple, you would need to access and operate on each string individu...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074533013_python.txt
Q: Python - Bland-Altman Plot with Text Customization I am trying to Create the Bland-Altman Plot with the text having on the left side of the plot instead of having it as the default configuration on the right hand side This is my code import pandas as pd df = pd.DataFrame({'A': [5, 5, 5, 6, 6, 7, 7, 7, 8, 8, 9, ...
Python - Bland-Altman Plot with Text Customization
I am trying to Create the Bland-Altman Plot with the text having on the left side of the plot instead of having it as the default configuration on the right hand side This is my code import pandas as pd df = pd.DataFrame({'A': [5, 5, 5, 6, 6, 7, 7, 7, 8, 8, 9, 10, 11, 13, 14, 14, 15, 18, 22, ...
[ "I don't know, but I can use pyplot so:\nmean_diff = (df.A-df.B).mean()\ndiff_range = (df.A-df.B).std()*1.96\n\nplt.figure(figsize = (9,6))\n\nplt.scatter(df.A, df.A-df.B, alpha=.5)\n\nplt.hlines(mean_diff, df.A.min()-2, df.A.max()+2, color=\"k\", linewidth=1)\nplt.text(\n df.A.min()-1, mean_diff+.05*diff_range,...
[ 0 ]
[]
[]
[ "matplotlib", "plot", "python", "python_3.x", "statsmodels" ]
stackoverflow_0074544603_matplotlib_plot_python_python_3.x_statsmodels.txt
Q: Is there a max size, max no. of columns, max rows? .. and, if so, what are those max limits of pandas? Sorry, this question seems elementary but I couldn't find an answer at pandas.pydata.org. A: The limit is your memory. ( but these limits are really large ) But when you want to display a DataFrame table in "Ju...
Is there a max size, max no. of columns, max rows?
.. and, if so, what are those max limits of pandas? Sorry, this question seems elementary but I couldn't find an answer at pandas.pydata.org.
[ "The limit is your memory. ( but these limits are really large )\nBut when you want to display a DataFrame table in \"Jupyter Notebook\", there is some predefined limits.\nFor example you can:\nprint (pd.options.display.max_columns) # <--- this will display your limit\npd.options.display.max_columns = 500 # this wi...
[ 31, 29 ]
[ "You can do that easily with .set_option() function.\npd.set_option('display.max_rows', 500) \n# Where 500 is the maximum number of rows that you want to show\n\n" ]
[ -1 ]
[ "pandas", "python" ]
stackoverflow_0015455722_pandas_python.txt
Q: x exceeds 10% of free system memory, even though plenty is available Every time i try to run model.predict() it throws an error if the picture is too large (which is fine) but the error says that tensorflow/core/framework/allocator.cc:101] Allocation of 3717120800 exceeds 10% of system memory Yeah it does, i have ...
x exceeds 10% of free system memory, even though plenty is available
Every time i try to run model.predict() it throws an error if the picture is too large (which is fine) but the error says that tensorflow/core/framework/allocator.cc:101] Allocation of 3717120800 exceeds 10% of system memory Yeah it does, i have 32GB, but why can't it use, say 20% or maybe 30% (btw, cuda is disabled fo...
[ "I was also having the same problem. I setup a swap memory in my linux. Then the problem was solved.\n" ]
[ 0 ]
[]
[]
[ "artificial_intelligence", "python", "reinforcement_learning", "tensorflow", "tf.keras" ]
stackoverflow_0072448084_artificial_intelligence_python_reinforcement_learning_tensorflow_tf.keras.txt
Q: NumPy one-liner equivalent to this loop, condition changes according to index In the code below I want to replace the loop in a compact NumPy one-liner equivalent. I think the code is self-explanatory but here is a short explanation: in the array of prediction, I one to threshold the prediction according to a thre...
NumPy one-liner equivalent to this loop, condition changes according to index
In the code below I want to replace the loop in a compact NumPy one-liner equivalent. I think the code is self-explanatory but here is a short explanation: in the array of prediction, I one to threshold the prediction according to a threshold specific to the prediction (i.e. if I predict 1 I compare it to th[1] and if ...
[ "If you make th a numpy array:\nth = np.array(th)\n\nz_pred = np.where(y_prob > th[y_pred], 0, y_pred)\n\nOr with in-line conversion to array:\nz_pred = np.where(y_prob > np.array(th)[y_pred], 0, y_pred)\n\nOutput: array([0, 2, 0, 1, 0, 0, 3])\nIntermediates:\nnp.array(th)\n# array([0. , 0.4, 0.7, 0.5])\n\nnp.array...
[ 1 ]
[]
[]
[ "numpy", "numpy_ndarray", "numpy_slicing", "python", "vectorization" ]
stackoverflow_0074545288_numpy_numpy_ndarray_numpy_slicing_python_vectorization.txt
Q: Extract labels from tflite model file I have a trained TF-Lite model (model.tflite) for image classification with several labels. The output of the model provides an array of probabilities, but I don't know the order to the labels. Can I extract the labels from the TF model? A: I think this might extract the met...
Extract labels from tflite model file
I have a trained TF-Lite model (model.tflite) for image classification with several labels. The output of the model provides an array of probabilities, but I don't know the order to the labels. Can I extract the labels from the TF model?
[ "I think this might extract the metadata\npip install tflite_support\nimport os\nfrom tflite_support import metadata as _metadata\nfrom tflite_support import metadata_schema_py_generated as _metadata_fb\nmodel_file = <model_path>\ndisplayer = _metadata.MetadataDisplayer.with_model_file(model_file)\nexport_json_file...
[ 0 ]
[]
[]
[ "python", "tensorflow", "tensorflow_lite" ]
stackoverflow_0074545345_python_tensorflow_tensorflow_lite.txt
Q: How run package Depix? I'm new to Python and I want to run the Duplex tool (https://github.com/beurtschipper/Depix ). But the test version does not start, when I type an in the command line: python depix.py -p images/testimages/testimage3_pixels.png -s images/searchimages/debruinseq_notepad_Windows10_closeAndSpace...
How run package Depix?
I'm new to Python and I want to run the Duplex tool (https://github.com/beurtschipper/Depix ). But the test version does not start, when I type an in the command line: python depix.py -p images/testimages/testimage3_pixels.png -s images/searchimages/debruinseq_notepad_Windows10_closeAndSpaced.png -o output.png an erro...
[ "I had the same error and it looks like it is a directory structure problem.\nYou can fix it by adding depixlib where you import the modules.\ndepixlib\\depix.py\nfrom depixlib import __version__\nfrom depixlib.functions import\nfrom depixlib.LoadedImage import LoadedImage\nfrom depixlib.Rectangle import Rectangle\...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0072105190_python.txt
Q: Mock patch path to function Is there a more easy way to get this path when mocking functions? @mock.patch('folder1.folder2.file.class.get_some_information', side_effect=mocked_information) I would like to have the path for the function get_some_information generated automatically. Thanks! A: Helper package to ge...
Mock patch path to function
Is there a more easy way to get this path when mocking functions? @mock.patch('folder1.folder2.file.class.get_some_information', side_effect=mocked_information) I would like to have the path for the function get_some_information generated automatically. Thanks!
[ "Helper package to generate paths for mocking: github.com/pksol/mock_autogen#generating-the-arrange-section\n", "If you have the function object get_some_information, you can generate the said path by joining with a dot the object's __module__ attribute, for package name and module name, and the __qualname__ attr...
[ 1, 0 ]
[]
[]
[ "mocking", "patch", "python" ]
stackoverflow_0074527960_mocking_patch_python.txt
Q: Git - Should Pipfile.lock be committed to version control? When two developers are working on a project with different operating systems, the Pipfile.lock is different (especially the part inside host-environment-markers). For PHP, most people recommend to commit composer.lock file. Do we have to do the same for P...
Git - Should Pipfile.lock be committed to version control?
When two developers are working on a project with different operating systems, the Pipfile.lock is different (especially the part inside host-environment-markers). For PHP, most people recommend to commit composer.lock file. Do we have to do the same for Python?
[ "Short - Yes!\nThe lock file tells pipenv exactly which version of each dependency needs to be installed. You will have consistency across all machines.\n// update: Same question on github\n", "NO, you should not commit Pipfile.lock because:\n\nIt will contain info on a specific build of each library. Those build...
[ 86, 0 ]
[]
[]
[ "pip", "pipenv", "python" ]
stackoverflow_0046278288_pip_pipenv_python.txt
Q: Layering (or nesting) multiple Bokeh transforms I need to dynamically layer (or "nest") multiple Bokeh transforms, most of which are CustomJSTransforms. Is there anyway to do that? Is there any way to use syntax like: Log10Transform(ThresholdTransform(column_name)) or LinearColorMapper(Log10Tranform(column_name)...
Layering (or nesting) multiple Bokeh transforms
I need to dynamically layer (or "nest") multiple Bokeh transforms, most of which are CustomJSTransforms. Is there anyway to do that? Is there any way to use syntax like: Log10Transform(ThresholdTransform(column_name)) or LinearColorMapper(Log10Tranform(column_name)) I'm currently using the {'field':column_name, 'tra...
[ "the composite_transform() calls transforms one by one:\nfrom inspect import Signature, Parameter\n\ndef composite_transform(*transforms):\n def trans_func():\n transforms = arguments\n res = x\n for transform in transforms.values():\n res = transform.compute(res)\n return ...
[ 1, 0, 0 ]
[]
[]
[ "bokeh", "data_visualization", "python" ]
stackoverflow_0048772907_bokeh_data_visualization_python.txt
Q: Django: 'Couldn't reconstruct field' on subclass of `OneToOneField` I've made a field Extends with this super short declaration: class Extends(models.OneToOneField): def __init__(self, to, **kwargs): super().__init__( to, on_delete=models.CASCADE, primary_key=True, ...
Django: 'Couldn't reconstruct field' on subclass of `OneToOneField`
I've made a field Extends with this super short declaration: class Extends(models.OneToOneField): def __init__(self, to, **kwargs): super().__init__( to, on_delete=models.CASCADE, primary_key=True, **kwargs ) However, if i use this as a field in a mod...
[ "Try it this way:\nclass Extends(models.OneToOneField):\n def __init__(self, *args, **kwargs):\n kwargs[\"on_delete\"] = models.CASCADE\n kwargs[\"primary_key\"] = True\n super().__init__(*args, **kwargs)\n\n" ]
[ 0 ]
[]
[]
[ "django", "python", "python_3.x" ]
stackoverflow_0074545019_django_python_python_3.x.txt
Q: finding a minimum value with all header values I am trying to find a minimum value in a dataframe with all column values. Sample data: **Fitness Value MSU Locations MSU Range** 1.180694 {17, 38, 15} 2.017782 1.202132 {10, 22, 39} 2.032507 1.179097 {10, 5, 38} 2.048932 ...
finding a minimum value with all header values
I am trying to find a minimum value in a dataframe with all column values. Sample data: **Fitness Value MSU Locations MSU Range** 1.180694 {17, 38, 15} 2.017782 1.202132 {10, 22, 39} 2.032507 1.179097 {10, 5, 38} 2.048932 1.175793 {27, 20, 36} 1.820395 1.18746...
[ "Use Series.idxmin for indices by minimal values, select row by DataFrame.loc for get row first minimal value in Fitness Value column:\ndf = df_2.loc[[df_2['Fitness Value'].idxmin()]]\nprint (df)\n Fitness Value MSU Locations MSU Range\n3 1.175793 {27,20,36} 1.820395\n\nIf need list without columns:\n...
[ 3, 3, 2 ]
[]
[]
[ "dataframe", "genetic_algorithm", "genetic_programming", "pandas", "python" ]
stackoverflow_0074545391_dataframe_genetic_algorithm_genetic_programming_pandas_python.txt
Q: Image processing with OpenCV- AttributeError: module 'cv2' has no attribute 'face' I try to run following "trying.py" but get above error. How to fix it? trying.py import cv2, os import numpy as np from PIL import Image # Create Local Binary Patterns Histograms for face recognization recognizer = cv2.face.LBPHFac...
Image processing with OpenCV- AttributeError: module 'cv2' has no attribute 'face'
I try to run following "trying.py" but get above error. How to fix it? trying.py import cv2, os import numpy as np from PIL import Image # Create Local Binary Patterns Histograms for face recognization recognizer = cv2.face.LBPHFaceRecognizer_create() # Using prebuilt frontal face training model, for face detection d...
[ "Most probably, you installed the wrong OpenCV version.\nImporting face will fail (I am using v4.6.0), since the module is not included in the \"normal\" install of OpenCv.\nTry running pip list and check for the OpenCv Version. My guess is, that you installed normal OpenCv that will give you an entry like:\nopencv...
[ 0, 0 ]
[]
[]
[ "image_processing", "opencv", "python", "video_processing" ]
stackoverflow_0074544839_image_processing_opencv_python_video_processing.txt
Q: Returning an average of integers only at the list where a string is searched inside a list of lists I'm a beginner with Python. Say I have a list of lists in python list1 = [['id1','Jane','Doe',100,75,100],['id2','John','Snow',90,87,92],['id3','Peter','Pan',79,81,83]] How can I search the list of lists for sa...
Returning an average of integers only at the list where a string is searched inside a list of lists
I'm a beginner with Python. Say I have a list of lists in python list1 = [['id1','Jane','Doe',100,75,100],['id2','John','Snow',90,87,92],['id3','Peter','Pan',79,81,83]] How can I search the list of lists for say 'id2' and print a list with only the integers in its list? This is what I tried import numbers ...
[ "This solution stops looping when index is found.\nReturns None if index has not been found.\nUses a list-comprehension to easily create a list.\nNo need to import Number just test if it's an integer.\nA small optimization consists to look for integers starting from the 2nd row (item[:1]) as we know that the first...
[ 1, 0, 0, 0, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074544254_list_python.txt
Q: Make option HTML tag set something in the url - Django I am trying to do something, but I don't know if it's acutally possible... Basically I'm trying to pass information in the url... (something like this) <form class="header__search" method="GET" action=""> <input name="q" placeholder="Browse Topics" /> </fo...
Make option HTML tag set something in the url - Django
I am trying to do something, but I don't know if it's acutally possible... Basically I'm trying to pass information in the url... (something like this) <form class="header__search" method="GET" action=""> <input name="q" placeholder="Browse Topics" /> </form> but instead of using a text input I would like the user...
[ "You can do this with javascript and onchange attribute:\n <div class=\"units-div\">\n <label for=\"units\">Units:</label>\n <select name=\"units\" id=\"units-selection\" onchange=\"window.location.href='?units='+units-selection.value+'&language='+language-selection.value\">\n <option value=\"metric\">M...
[ 0 ]
[]
[]
[ "django", "get", "input", "python", "url" ]
stackoverflow_0074545508_django_get_input_python_url.txt
Q: Python Match Case (Switch) Performance I was expecting the Python match/case to have equal time access to each case, but seems like I was wrong. Any good explanation why? Lets use the following example: def match_case(decimal): match decimal: case '0': return "000" case '1': return ...
Python Match Case (Switch) Performance
I was expecting the Python match/case to have equal time access to each case, but seems like I was wrong. Any good explanation why? Lets use the following example: def match_case(decimal): match decimal: case '0': return "000" case '1': return "001" case '2': return "010" ...
[ "PEP 622\nThe \"match\\case\" functionality is developed to replace the code like this:\ndef is_tuple(node):\nif isinstance(node, Node) and node.children == [LParen(), RParen()]:\n return True\nreturn (isinstance(node, Node)\n and len(node.children) == 3\n and isinstance(node.children[0], Leaf)\n ...
[ 6, 3, 3, 0 ]
[]
[]
[ "match", "python", "python_3.x", "switch_statement" ]
stackoverflow_0068476576_match_python_python_3.x_switch_statement.txt
Q: pyspark if statement optimization Hello guys I'm doing a dataframe filtering based on if condition but the problem that I must repeat the same code 3 times in every if condition and I don't want to do that. It's not optimized. Someone has any idea how to optimize that? here is the code exemple if sexe == "male": ...
pyspark if statement optimization
Hello guys I'm doing a dataframe filtering based on if condition but the problem that I must repeat the same code 3 times in every if condition and I don't want to do that. It's not optimized. Someone has any idea how to optimize that? here is the code exemple if sexe == "male": new_df = ( df.where(F.col("...
[ "One way is to build the filtering expression then use it to filter the dataframe:\nfilter_expr = ~F.col(\"column_flag\")\n\nif sexe == \"male\":\n filter_expr = filter_expr & F.col(\"sexe\") == 1\nelif sexe == \"female\":\n filter_expr = filter_expr & F.col(\"sexe\") == 2\n\nnew_df = df.filter(filter_expr).w...
[ 2 ]
[]
[]
[ "apache_spark", "apache_spark_sql", "dataframe", "pyspark", "python" ]
stackoverflow_0074545367_apache_spark_apache_spark_sql_dataframe_pyspark_python.txt
Q: How to convert result multidimentional list python to single list python I have result value of some training data like this [[ 0] [ 0] [ 0] [1049.3618 ] [1049.3618 ] [1049.3618 ] [1047.8524 ] [1034.0015 ] [1011.92944] [ 997.6305 ] [ 985.61743] [ 971.35583] [ 953.3492 ] [ 934.0...
How to convert result multidimentional list python to single list python
I have result value of some training data like this [[ 0] [ 0] [ 0] [1049.3618 ] [1049.3618 ] [1049.3618 ] [1047.8524 ] [1034.0015 ] [1011.92944] [ 997.6305 ] [ 985.61743] [ 971.35583] [ 953.3492 ] [ 934.00104] [ 912.93585] [ 886.3636 ] [ 857.08594] [ 832.37103] [ 803.3781 ] [...
[ "The array can be converted to list using tolist() which will result to list of lists e.g.:[[1,2,3], [2,3,4], [0]].\n[x for sub_list in <your_array>.tolist() for x in sub_list]\n\nThe array can also be flattened to a list using array.flatten(). More information can be found in the Numpy documentation\n<your_array>...
[ 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074545519_list_python.txt
Q: What parameter is missing from my function to extract a table from BigQuery to a GCS Bucket? I have written a function to extract a table from BigQuery to a GCS Bucket, but I believe that my function is missing a parameter, and I am unsure what I need to add. I have written the following function: def extract_tab...
What parameter is missing from my function to extract a table from BigQuery to a GCS Bucket?
I have written a function to extract a table from BigQuery to a GCS Bucket, but I believe that my function is missing a parameter, and I am unsure what I need to add. I have written the following function: def extract_table(client): bucket_name = "extract_mytable_{}".format(_millis()) storage_client = storage....
[ "I tested your function and no parameters are missing in the extract_table function :\ndef extract_table():\n bucket_name = \"bucket_name\"\n client = bigquery.Client()\n\n project = \"bigquery-public-data\"\n dataset_id = \"samples\"\n table_id = \"mytable\"\n\n destination_uri = \"gs://{}/{}\".f...
[ 0 ]
[]
[]
[ "airflow", "google_bigquery", "google_cloud_platform", "google_cloud_storage", "python" ]
stackoverflow_0074517166_airflow_google_bigquery_google_cloud_platform_google_cloud_storage_python.txt
Q: How to add string at the beginning of each row? I would like to add a string at the beginning of each row- either positive or negative - depending on the value in the columns: I keep getting ValueError, as per screenshot A: For a generic method to handle any number of columns, use pandas.from_dummies: cols = ['...
How to add string at the beginning of each row?
I would like to add a string at the beginning of each row- either positive or negative - depending on the value in the columns: I keep getting ValueError, as per screenshot
[ "For a generic method to handle any number of columns, use pandas.from_dummies:\ncols = ['positive', 'negative']\n\nuser_input_1.index = (pd.from_dummies(user_input_1[cols]).squeeze()\n +'_'+user_input_1.index\n )\n\nExample input:\n Score positive negative\nA 1 ...
[ 2, 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074545479_pandas_python.txt
Q: How to find specific regex in Python I want to make a data analyzing script and therefore I'm checking the cells of an excel sheet for occuring error codes. For each error code I iterate through my error code list and check for every single code if there is a regex match in that cell. Some codes have 4 digits and ...
How to find specific regex in Python
I want to make a data analyzing script and therefore I'm checking the cells of an excel sheet for occuring error codes. For each error code I iterate through my error code list and check for every single code if there is a regex match in that cell. Some codes have 4 digits and some have 6. The problem is now, for all t...
[ "The regex search method is being asked to look for 1234 in the string 123456, so it does find a match. But of course it also finds a match when you look for 123456. What you want is to find only the match on the whole of the error code.\nYou can do this by searching the string between word boundaries. A word bound...
[ 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074543782_python_regex.txt
Q: Python pandas.melt how to switch row values into column name? I am trying to use pandas.melt() or pandas.pivot() to convert rows from Column Food-Type into Column headings and Dates into row. Food-Type 2021 Oct-21 Nov-21 Banana 104 104.4 105.5 cereals 105.7 105.8 106.5 Rice 97.6 97.5 98.2...
Python pandas.melt how to switch row values into column name?
I am trying to use pandas.melt() or pandas.pivot() to convert rows from Column Food-Type into Column headings and Dates into row. Food-Type 2021 Oct-21 Nov-21 Banana 104 104.4 105.5 cereals 105.7 105.8 106.5 Rice 97.6 97.5 98.2 The end result should be like this. Banana cereals Ri...
[ "Use a transposition, after setting Food-Type as index:\nout = df.set_index('Food-Type').T\n\nOutput:\nFood-Type Banana cereals Rice\n2021 104.0 105.7 97.6\nOct-21 104.4 105.8 97.5\nNov-21 105.5 106.5 98.2\n\nAlternative:\nout = df.set_index('Food-Type').T.rename_axis(columns=None)\n...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python", "python_3.x" ]
stackoverflow_0074545651_dataframe_pandas_python_python_3.x.txt
Q: Printing Simple Pattern in Python I would like to print the following pattern in Python input: 5 output: 5 456 34567 2345678 123456789 I have used the following code but it is not showing the above pattern. Anyone help me on this topic, please? CODE: rows = int(input("Enter number of rows: ")) k = 0 co...
Printing Simple Pattern in Python
I would like to print the following pattern in Python input: 5 output: 5 456 34567 2345678 123456789 I have used the following code but it is not showing the above pattern. Anyone help me on this topic, please? CODE: rows = int(input("Enter number of rows: ")) k = 0 count=0 count1=0 for i in range(1, rows+...
[ "If I understand your question correctly, you just want a pattern starting from n and going to 1 in decreasing order left side, and starting from n and going to 2n-1 in increasing order right side\n def pattern(n):\n for i in range(n,0,-1):\n for j in range(1,i):\n print(\" \",end=...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074545433_python.txt
Q: Get a list of values from a list of enumerations Let us assume that we have an enum class: class MyEnum(Enum): foo = 1 bar = 2 How to get the list of values [1, 1, 2] from the above list of enumerations? mylist = [MyEnum.foo, MyEnum.foo, MyEnum.bar] I know it is possible to create a new list using list c...
Get a list of values from a list of enumerations
Let us assume that we have an enum class: class MyEnum(Enum): foo = 1 bar = 2 How to get the list of values [1, 1, 2] from the above list of enumerations? mylist = [MyEnum.foo, MyEnum.foo, MyEnum.bar] I know it is possible to create a new list using list comprehension, but I am wondering if there exists a mor...
[ "we can access name and value of an Enum class by .name, .value. So a simple list comprehension could solve your problem.\nclass MyEnum(Enum):\n foo = 1\n bar = 2\nmylist = [MyEnum.foo, MyEnum.foo, MyEnum.bar]\nmy_enum_val_list = [i.value for i in mylist]\n\nFurther, you can also use IntEnum to make it behave...
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074545435_python.txt
Q: Type-Hinting Child class returning self Is there any way to type an abstract parent class method such that the child class method is known to return itself, instead of the abstract parent. class Parent(ABC): @abstractmethod def method(self) -> [what to hint here]: pass class Child1(Parent) def...
Type-Hinting Child class returning self
Is there any way to type an abstract parent class method such that the child class method is known to return itself, instead of the abstract parent. class Parent(ABC): @abstractmethod def method(self) -> [what to hint here]: pass class Child1(Parent) def method(self): pass def other_me...
[ "So, the general approach is described in the docs here\nimport typing\nfrom abc import ABC, abstractmethod\n\nT = typing.TypeVar('T', bound='Parent') # use string\n\nclass Parent(ABC):\n @abstractmethod\n def method(self: T) -> T:\n ...\n\nclass Child1(Parent):\n def method(self: T) -> T:\n ...
[ 14, 0 ]
[]
[]
[ "abc", "abstract_class", "python", "type_hinting" ]
stackoverflow_0058986031_abc_abstract_class_python_type_hinting.txt
Q: Jupyter kernel is not linked to conda environment in Jupyter Lab I know similar questions have been asked before but previous answers do not help. The problem: Although, I installed a kernel from an active conda environment, the conda environment uses the wrong python interpreter. I tried the following: # 1. Activ...
Jupyter kernel is not linked to conda environment in Jupyter Lab
I know similar questions have been asked before but previous answers do not help. The problem: Although, I installed a kernel from an active conda environment, the conda environment uses the wrong python interpreter. I tried the following: # 1. Activate my conda environment snowflakes $ conda activate /opt/miniconda3/e...
[ "I found a solution:\n#1 install nb_conda_kernels in base environment and in conda environment of choice\n\n#2 Run the following code in the activated conda environment \n$ conda install --channel=conda-forge nb_conda_kernels\n\n#3 Open jupyter-lab\n$ jupyter-lab\n\nBefore I created Kernels that were still linked t...
[ 0 ]
[]
[]
[ "jupyter_lab", "jupyter_notebook", "python" ]
stackoverflow_0074537171_jupyter_lab_jupyter_notebook_python.txt
Q: Selenium screenshot of multiple elements Im using Python Selenium to scrape a website. At some point during the scrape i want to take a screenshot. I only 'roughly' want to take a screenshot covering specific WebElements. How do I take a screenshot of section containing multiple WebElements? A: To avoid an event...
Selenium screenshot of multiple elements
Im using Python Selenium to scrape a website. At some point during the scrape i want to take a screenshot. I only 'roughly' want to take a screenshot covering specific WebElements. How do I take a screenshot of section containing multiple WebElements?
[ "To avoid an eventual XY Problem, here is how you can screenshot any particular element you want, with Selenium (Python) - that element can be a div encompassing other elements:\n[...]\nurl = 'https://www.startech.com.bd/benq-gw2480-fhd-monitor'\nbrowser.get(url) \nbrowser.execute_script('window.scrollBy(0, 100);')...
[ 0 ]
[]
[]
[ "python", "selenium", "web_scraping" ]
stackoverflow_0074545135_python_selenium_web_scraping.txt
Q: For Every duplicated value in Id Column how can i append a string 'duplicated' with that value I have created a dataframe df=pd.DataFrame({'Weather':[32,45,12,18,19,27,39,11,22,42], 'Id':[1,2,3,4,5,1,6,7,8,2]}) df.head() You can see Id on index 5th and 9th are duplicated. So, I want to append string -...
For Every duplicated value in Id Column how can i append a string 'duplicated' with that value
I have created a dataframe df=pd.DataFrame({'Weather':[32,45,12,18,19,27,39,11,22,42], 'Id':[1,2,3,4,5,1,6,7,8,2]}) df.head() You can see Id on index 5th and 9th are duplicated. So, I want to append string --duplicated with Id on 5th and 9th index. df.loc[df['Id'].duplicated()] Output Weather Id 5 2...
[ "Do you want an aggregated DataFrame with modification of your previous output using assign?\n(df.loc[df['Id'].duplicated()]\n .assign(Id=lambda d: d['Id'].astype(str).add('--duplicated'))\n)\n\noutput:\n Weather Id\n5 27 1--duplicated\n9 42 2--duplicated\n\nOr, in place modification o...
[ 1, 1 ]
[]
[]
[ "dataframe", "pandas", "python", "python_3.x" ]
stackoverflow_0074545761_dataframe_pandas_python_python_3.x.txt
Q: Convert list of rows to list of columns Python Python. How can I convert list of lists to list of columns lists according to number of indexes in lists. But every time I can have different matrix(dimension), different number of row/list and different number of numbers in list For example from this list of lists: ...
Convert list of rows to list of columns Python
Python. How can I convert list of lists to list of columns lists according to number of indexes in lists. But every time I can have different matrix(dimension), different number of row/list and different number of numbers in list For example from this list of lists: x = [ [1, 0, 0, 0, 1, 0, 0], [0, 0, 2, 2, ...
[ "You can use zip to do this. By unpacking x into its sublists and passing it into zip, you can get the format you want:\nx = [\n [1, 0, 0, 0, 1, 0, 0],\n [0, 0, 2, 2, 0, 0, 0],\n [0, 1, 0, 0, 0, 2, 2]\n]\n\ny = list(zip(*x))\nprint(y)\n>>> [(1, 0, 0), (0, 0, 1), (0, 2, 0), (0, 2, 0), (1, 0, 0), (0, 0, 2), ...
[ 1, 1 ]
[]
[]
[ "indexing", "list", "nested", "nested_lists", "python" ]
stackoverflow_0074545631_indexing_list_nested_nested_lists_python.txt
Q: Multiprocessing for reading files (Python) I have a list of files (as classes, see the realisation below). class F: def __init__(self,path): self.path=path self. size=0 def calculate_size() with open(self.path,”rb”) as f: self.size=len(f.read()) I want to use the multiprocessing library to calcu...
Multiprocessing for reading files (Python)
I have a list of files (as classes, see the realisation below). class F: def __init__(self,path): self.path=path self. size=0 def calculate_size() with open(self.path,”rb”) as f: self.size=len(f.read()) I want to use the multiprocessing library to calculate file sizes parallel. I tried to do it with ...
[ "You can use python's threading library like the example below.\nfrom threading import Thread\n\nclass F:\n def __init__(self, path):\n self.path = path\n self.size = 0\n def calculate_size(self):\n print(\"calculation started\")\n with open(self.path, 'rb') as f:\n self...
[ 2 ]
[]
[]
[ "file", "multiprocessing", "python" ]
stackoverflow_0074545696_file_multiprocessing_python.txt
Q: Dash - Include custom html object I'm creating a Dash application in Python to showcase results of some Topic Analysis I performed. For topic analysis there is a nice visualisation tool called pyLDAvis. I used this tool, and saved its output as a html file named lda.html: # Visualisatie topic_data = pyLDAvis.gens...
Dash - Include custom html object
I'm creating a Dash application in Python to showcase results of some Topic Analysis I performed. For topic analysis there is a nice visualisation tool called pyLDAvis. I used this tool, and saved its output as a html file named lda.html: # Visualisatie topic_data = pyLDAvis.gensim.prepare(ldamodel, doc_term_matrix, d...
[ "You've written the file extension as .hmtl instead of .html. That is probably the cause of the first problem.\nUPDATE\nI noticed that you've put lda.html into the static folder. In Dash, assets folder is used to store external resources.\nhtml.Iframe(src='assets/lda.html')\n\nOr in a more pythonic way\nhtml.Ifram...
[ 1 ]
[]
[]
[ "html", "iframe", "plotly_dash", "python" ]
stackoverflow_0074534261_html_iframe_plotly_dash_python.txt
Q: How do you find all instances of ISBN number using Python Regex I would really appreciate some assistance... I'm trying to retrieve an ISBN number (13 digits) from pages, but the number set in so many different formats and that's why I can't retrieve all the different instances: ISBN-13: 978 1 4310 0862 9 ISBN: 97...
How do you find all instances of ISBN number using Python Regex
I would really appreciate some assistance... I'm trying to retrieve an ISBN number (13 digits) from pages, but the number set in so many different formats and that's why I can't retrieve all the different instances: ISBN-13: 978 1 4310 0862 9 ISBN: 9781431008629 ISBN9781431008629 ISBN 9-78-1431-008-629 ISBN: 9781431008...
[ "You can use\n(?i)ISBN(?:-13)?\\D*(\\d(?:\\W*\\d){12})\n\nSee the regex demo. Then, remove all non-digits from Group 1 value.\nRegex details:\n\n(?i) - case insensitive modifier, same as re.I\nISBN - an ISBN string\n(?:-13)? - an optional -13 string\n\\D* - zero or more non-digits\n(\\d(?:\\W*\\d){12}) - Group 1: a...
[ 4, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074545639_python_regex.txt
Q: Max no of 200 conversations exceeded error in PyRFC I am getting this error from the PyRFC library: Traceback (most recent call last): ... File "/.../sap_connection.py", line 486, in get_connection return Connection(**get_connection_dict(contact_host)) File "src/pyrfc/_pyrfc.pyx", line 182, in pyrfc._pyrfc...
Max no of 200 conversations exceeded error in PyRFC
I am getting this error from the PyRFC library: Traceback (most recent call last): ... File "/.../sap_connection.py", line 486, in get_connection return Connection(**get_connection_dict(contact_host)) File "src/pyrfc/_pyrfc.pyx", line 182, in pyrfc._pyrfc.Connection.__init__ File "src/pyrfc/_pyrfc.pyx", line ...
[ "There are SAP notes exists about this error. It says there is limit on server side and you need to limit your client. Note 316877 included server side parameter for increasing size.\nIt make sense to close connection. Because RFC working on TCP/IP level, it hasn't got auto close routine after response look like re...
[ 3, 2, 1 ]
[]
[]
[ "abap", "pyrfc", "python" ]
stackoverflow_0059178676_abap_pyrfc_python.txt
Q: Compare elements of two lists and calculate median value I have a list of keywords: list1 = ['key(1)', 'key(2)' ........, 'key(x)'] And another 2D list: list2 = [['key1','str(11)','value(11)'],['key1','str(12)','value(12)'].....,['key(1)','str(1n)','value(1n)'],['key2','str(21)','value(21)'],...,['key(2)','str(2n...
Compare elements of two lists and calculate median value
I have a list of keywords: list1 = ['key(1)', 'key(2)' ........, 'key(x)'] And another 2D list: list2 = [['key1','str(11)','value(11)'],['key1','str(12)','value(12)'].....,['key(1)','str(1n)','value(1n)'],['key2','str(21)','value(21)'],...,['key(2)','str(2n)','value(2n)'],........., ['key(n)','str(n1)','value(n1)'],.....
[ "median should receive an iterable containing all values for key, whereas you give it only one value.\nlist1 = [\"key(1)\", \"key(2)\"]\nlist2 = [\n [\"key(1)\", \"str(11)\", \"11\"],\n [\"key(1)\", \"str(12)\", \"12\"],\n [\"key(1)\", \"str(1n)\", \"19\"],\n [\"key(2)\", \"str(21)\", \"21\"],\n [\"k...
[ 0 ]
[]
[]
[ "list", "python", "python_3.x" ]
stackoverflow_0074545506_list_python_python_3.x.txt
Q: OperationalError:Connection to server at "IP_HERE", port 5432 failed:Connection timed out Is the server running on that host and accepting TCP/IP conc I have a python script, which I deployed on Azure Functions (HTTP Request). My python script contains a connection string to connect with DB using psycopg2, Everyth...
OperationalError:Connection to server at "IP_HERE", port 5432 failed:Connection timed out Is the server running on that host and accepting TCP/IP conc
I have a python script, which I deployed on Azure Functions (HTTP Request). My python script contains a connection string to connect with DB using psycopg2, Everything is working fine in my machine. But when I deployed it on Azure Functions it is showing ** OperationalError: connection to server at "20.231.229.175", po...
[ "\nAs far I know this is a firewall issue when I deployed a python function and tried to connect to the postgresqldb it gave me the following error\n\nSimilar to yours.\n\nNow I whitelisted Ip from the azure functions. These Ip address are of azure function they will be available under the networking tab just white...
[ 0 ]
[]
[]
[ "azure", "azure_functions", "database", "psycopg2", "python" ]
stackoverflow_0074521865_azure_azure_functions_database_psycopg2_python.txt
Q: Installed PyTorch with Anaconda, but cannot use PyTorch outside of the Anaconda Prompt I installed PyTorch by running the following command in the Anaconda Prompt: conda install pytorch torchvision torchaudio cpuonly -c pytorch This command is given by the official PyTorch installation page. I then tested a short...
Installed PyTorch with Anaconda, but cannot use PyTorch outside of the Anaconda Prompt
I installed PyTorch by running the following command in the Anaconda Prompt: conda install pytorch torchvision torchaudio cpuonly -c pytorch This command is given by the official PyTorch installation page. I then tested a short python script within the Anaconda prompt, and it worked. However, when I then open the Wind...
[ "I've had a lot of problems with Anaconda taking over as the \"main\" Python directory. Apparently this problem is wide spread (many programmers in a Discord channel I am in have the same problems). The answer lies in creating a virtual environment for Python and adding PyTorch it, adjusting your System Environment...
[ 0 ]
[]
[]
[ "anaconda", "anaconda3", "python", "pytorch" ]
stackoverflow_0074090912_anaconda_anaconda3_python_pytorch.txt
Q: Continuing script in selenium when element is not present on a page I am trying to get selenium set up to send out messages automatically and have not yet got around to check if the specific listing has already been sent a message. This causes selenium to give a NoSuchElementException because its looking for (By.X...
Continuing script in selenium when element is not present on a page
I am trying to get selenium set up to send out messages automatically and have not yet got around to check if the specific listing has already been sent a message. This causes selenium to give a NoSuchElementException because its looking for (By.XPATH, ('//span[contains(text(),"Message")]')) How can I have it skip thes...
[ "Instead of find_element you should use find_elements here.\nfind_elements returns a list of found matches. So, in case of match (such element exists) it will return non-empty list. It will be interpreted by Python as Boolean True. Otherwise, in case of no matches found the returned list is empty, it is interpreted...
[ 0 ]
[]
[]
[ "findelement", "python", "selenium", "selenium_webdriver" ]
stackoverflow_0074545769_findelement_python_selenium_selenium_webdriver.txt
Q: Using annotated field to order_by in Django So I have a queryset that has an annotated value that uses conditional expressions in it: def with_due_date(self: _QS): self.annotate( due_date=models.Case( *[ models.When( FKMODEL__field=fie...
Using annotated field to order_by in Django
So I have a queryset that has an annotated value that uses conditional expressions in it: def with_due_date(self: _QS): self.annotate( due_date=models.Case( *[ models.When( FKMODEL__field=field, then=models.F('create...
[ "QuerySet's are immutable, so you return the newly created one:\ndef with_due_date(self: _QS):\n return self.annotate(\n due_date=models.Case(\n *[\n models.When(\n FKMODEL__field=field,\n then=models.F('created_at') - timedelta(days=days),\n...
[ 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0074545796_django_django_models_python.txt
Q: Can't install Tensrflow I'm a beginner in Deep Learning and NLP stream. I was trying to install Tensorflow but it is giving me an error. Can anyone please help me how to solve this? This is the error I'm getting I was watchig an YouTube video for Toxic Comment Classification and thought should try that out for bet...
Can't install Tensrflow
I'm a beginner in Deep Learning and NLP stream. I was trying to install Tensorflow but it is giving me an error. Can anyone please help me how to solve this? This is the error I'm getting I was watchig an YouTube video for Toxic Comment Classification and thought should try that out for better practice. After creating ...
[ "Welcome to Stack Overflow!!\nHave you tried installing each package indivually?\nLike this\npip install tensorflow\npip install tensorflow-gpu\n\n\nAnd so on\n", "I ran your CLI commands from the picture separately as-well.\nThe error you are getting is from tensorflow-gpu command.\nI've found a link for you, fr...
[ 0, 0 ]
[]
[]
[ "deep_learning", "machine_learning", "nlp", "python", "tensorflow" ]
stackoverflow_0074536171_deep_learning_machine_learning_nlp_python_tensorflow.txt
Q: How to grab an output result from website using selenium So there is this code that i want to try. if a website exists it outputs available domain names. i used this website www.eurodns.com/whois-search/app-domain-name If the website does not exist, currently parked, or registered it says this. The code that i'm...
How to grab an output result from website using selenium
So there is this code that i want to try. if a website exists it outputs available domain names. i used this website www.eurodns.com/whois-search/app-domain-name If the website does not exist, currently parked, or registered it says this. The code that i'm thinking involves selenium and chrome driver input the text a...
[ "There is no need to use other libraries.\nRather than using XPATHs like that, because it may change the structure of the page. Always try to search for elements by ID, if it exists associated with that particular element (which by their nature should be unique on the page) or by class name (if it appears to be uni...
[ 0 ]
[]
[]
[ "jupyter_notebook", "python", "selenium" ]
stackoverflow_0074545280_jupyter_notebook_python_selenium.txt
Q: Capture all unique information by group I want to create a unique dataset of fruits. I don't know all the types (e.g. colour store, price) that could be under each fruit. For each type, there could also be duplicate rows. Is there a way to detect all possible duplicates and capture all unique informoation in a ful...
Capture all unique information by group
I want to create a unique dataset of fruits. I don't know all the types (e.g. colour store, price) that could be under each fruit. For each type, there could also be duplicate rows. Is there a way to detect all possible duplicates and capture all unique informoation in a fully generalisable way? type val de...
[ "First is created fruit column with val values if type is fruit, replace non matched values to NaNs and forward filling missing values, then pivoting by DataFrame.pivot_table with custom function for unique values without NaNs and then flatten MultiIndex:\nm = df['type'].eq('fruit')\n\ndf['fruit'] = df['val'].where...
[ 1 ]
[]
[]
[ "pandas", "python", "python_3.x" ]
stackoverflow_0074545745_pandas_python_python_3.x.txt
Q: How to plot a circle, that tilts according to a function? import numpy as np import matplotlib.pyplot as plt from io import BytesIO from PIL import Image r = 18 h = 1.7 num_of_steps = 1000 emp = 3 time = np.arange(0, 100, 0.4) phi = [] theta = [] Amp = np.pi/6 fphi = 4 ftheta = 9 pics = [] r1 = 16 for j in time:...
How to plot a circle, that tilts according to a function?
import numpy as np import matplotlib.pyplot as plt from io import BytesIO from PIL import Image r = 18 h = 1.7 num_of_steps = 1000 emp = 3 time = np.arange(0, 100, 0.4) phi = [] theta = [] Amp = np.pi/6 fphi = 4 ftheta = 9 pics = [] r1 = 16 for j in time: kampas = np.radians(2*np.pi*fphi*j) kitaskampas = Amp*...
[ "Use animation\nimport matplotlib.animation as animation\n\n# (...) your code\n\n# Your plot, but keeping the artist result\npltdata,=ax.plot(x, y, z)\n\ndef animate(i):\n theta = 0.524 + i*0.02\n x = r * np.cos(phi)\n y = r * np.sin(phi) * np.cos(theta) - h * np.sin(theta)\n z = r * np.sin(phi) * np.si...
[ 0 ]
[]
[]
[ "3d", "animation", "matplotlib", "numpy", "python" ]
stackoverflow_0074545546_3d_animation_matplotlib_numpy_python.txt
Q: compute engine's service account has insufficient scopes for cloud vision api I need to use Cloud Vision API in my python solution, I've been relying on an API key for a while now, but at the moment I'm trying to give my Compute Engine's default service account the scope needed to call Vision, with little luck so ...
compute engine's service account has insufficient scopes for cloud vision api
I need to use Cloud Vision API in my python solution, I've been relying on an API key for a while now, but at the moment I'm trying to give my Compute Engine's default service account the scope needed to call Vision, with little luck so far. I have enabled vision API in my project via cloud console, but I still get tha...
[ "Google Cloud APIs (Vision, Natural Language, Translation, etc) do not need any special permissions, you should just enable them in your project (going to the API Library tab in the Console) and create an API key or a Service account to access them.\nYour decision to move from API keys to Service Accounts is the co...
[ 2, 0 ]
[]
[]
[ "google_cloud_platform", "google_cloud_vision", "google_compute_engine", "python" ]
stackoverflow_0050646403_google_cloud_platform_google_cloud_vision_google_compute_engine_python.txt