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: Make Python dataclass iterable? I have a dataclass and I want to iterate over in in a loop to spit out each of the values. I'm able to write a very short __iter__() within it easy enough, but is that what I should be doing? I don't see anything in the documentation about an 'iterable' parameter or anything, but I ...
Make Python dataclass iterable?
I have a dataclass and I want to iterate over in in a loop to spit out each of the values. I'm able to write a very short __iter__() within it easy enough, but is that what I should be doing? I don't see anything in the documentation about an 'iterable' parameter or anything, but I just feel like there ought to be... H...
[ "The simplest approach is probably to make a iteratively extract the fields following the guidance in the dataclasses.astuple function for creating a shallow copy, just omitting the call to tuple (to leave it a generator expression, which is a legal iterator for __iter__ to return:\ndef __iter__(self):\n return ...
[ 3, 2 ]
[]
[]
[ "python", "python_dataclasses" ]
stackoverflow_0074393947_python_python_dataclasses.txt
Q: Permission denied path python Help needed. I am trying to save a file with python but this error appears. [Errno 13] Permission denied : "C:\Users\33769\Desktop\Reviewin" Firstly, I don't understand why it adds anti-slashes to the path ! Here is my code : file_path = r'C:\Users\33769\Desktop\Reviewin' with open(fi...
Permission denied path python
Help needed. I am trying to save a file with python but this error appears. [Errno 13] Permission denied : "C:\Users\33769\Desktop\Reviewin" Firstly, I don't understand why it adds anti-slashes to the path ! Here is my code : file_path = r'C:\Users\33769\Desktop\Reviewin' with open(file_path) as f: f.write(file) D...
[ "Open with write:\nwith open(file_path, \"w\") as f:\n ...\n\nRegarding the path, use os.path to define the path. For example:\nimport os\n\nfile_name = \"Reviewin\"\ncurrent_working_directory = os.getcwd()\nfile_path = os.path.join(directory, filename)\n\nThis makes path definition OS-independent (Linux, Windows...
[ 0, 0 ]
[ "Try specifying the file extension.\nfile_path = r'C:\\Users\\33769\\Desktop\\Reviewin.fileextentionhere'#ex png, gif\nwith open(file_path) as f: \n f.write(file) \n\n", "The built-in open() function can not save images, But you can easily do this task w...
[ -1, -1 ]
[ "operating_system", "python" ]
stackoverflow_0074385973_operating_system_python.txt
Q: Iterating for multiple conditions using itemgetter()/ Counter? I am new to Python. I have a CSV file that I am parsing and am looking to return information that meets two conditions. The data contains complaints about consumer financial products and services. 16 columns are within the file and I am looking to meet...
Iterating for multiple conditions using itemgetter()/ Counter?
I am new to Python. I have a CSV file that I am parsing and am looking to return information that meets two conditions. The data contains complaints about consumer financial products and services. 16 columns are within the file and I am looking to meet conditions for two of them, ['Product'] and ['Timely Response]. I a...
[ " c = Counter(map(itemgetter(15), reader))\n\nYou are reading all (remaining) elements from reader, but you want to read only from the current row.\nYou can solve this with itemgetter;\nc = Counter()\nfor row in reader:\n if row[1] == 'Credit reporting, credit repair services, or other personal consumer repor...
[ 0 ]
[]
[]
[ "csv", "python", "python_3.x" ]
stackoverflow_0074393910_csv_python_python_3.x.txt
Q: error building docker image 'executor failed running [/bin/sh -c apt-get -y update]' I'm trying to build a docker image but it throws an error and I can't seem to figure out why. It is stuck at RUN apt-get -y update with the following error messages: 4.436 E: Release file for http://security.debian.org/debian-secu...
error building docker image 'executor failed running [/bin/sh -c apt-get -y update]'
I'm trying to build a docker image but it throws an error and I can't seem to figure out why. It is stuck at RUN apt-get -y update with the following error messages: 4.436 E: Release file for http://security.debian.org/debian-security/dists/buster/updates/InRelease is not valid yet (invalid for another 2d 16h 26min 22s...
[ "In my case, docker was still using the cached RUN apt update && apt upgrade command, thus not updating the package sources.\nThe solution was to build the docker image once with the --no-cache flag:\ndocker build --no-cache .\n\n", "It's answered here https://askubuntu.com/questions/1059217/getting-release-is-no...
[ 5, 4, 3, 1, 0, 0 ]
[]
[]
[ "docker", "python" ]
stackoverflow_0066008106_docker_python.txt
Q: Robot framework running Library command before Suite Setup? I've got a Suite Setup command that i would like to call before the Library command but RobotFramework seems to be calling the Library command before the Suite setup. I need it to be in chronological order because suite setup pulls down the libraries that...
Robot framework running Library command before Suite Setup?
I've got a Suite Setup command that i would like to call before the Library command but RobotFramework seems to be calling the Library command before the Suite setup. I need it to be in chronological order because suite setup pulls down the libraries that the Library command is calling. I've got an extract from the rob...
[ "Robotframework first loads the Library and Resources, and only the executes the Suite Setup.\nThere is nothing you can do about this.\nWhat you can do, is to call the library import inside a step. Here is my example:\n***Settings***\n Library Hello.py # keep this import for RIDE to know keywords documentatio...
[ 0 ]
[]
[]
[ "python", "robotframework" ]
stackoverflow_0074391554_python_robotframework.txt
Q: Returning Array in Snowflake Stored procedure I have a stored procedure with return type as variant in snowflake. SP is written in JavaScript. Basically we are maintaining a array in SP and adding results and info just to maintain logs. The SP works fine when called from snowflake worksheets(UI) and returning [ ...
Returning Array in Snowflake Stored procedure
I have a stored procedure with return type as variant in snowflake. SP is written in JavaScript. Basically we are maintaining a array in SP and adding results and info just to maintain logs. The SP works fine when called from snowflake worksheets(UI) and returning [ "Using LOY DATABASE", "Using STAGE SCHEMA", "RU...
[ "Seems like the issue is still the case. I solved this issue by using ast.literal_eval() function as follows;\ndf[\"column1\"] = df[\"column1\"].apply(lambda x: ast.literal_eval(x))\n\n" ]
[ 0 ]
[]
[]
[ "python", "snowflake_cloud_data_platform", "snowflake_connector" ]
stackoverflow_0072285177_python_snowflake_cloud_data_platform_snowflake_connector.txt
Q: Python oracledb continous query notification not sending messages from database I've been trying to use Continuous Query Notification (CQN) in python script to get notification from database about changes that were made to a specific table. I have followed tutorial from this link here https://python-oracledb.read...
Python oracledb continous query notification not sending messages from database
I've been trying to use Continuous Query Notification (CQN) in python script to get notification from database about changes that were made to a specific table. I have followed tutorial from this link here https://python-oracledb.readthedocs.io/en/latest/user_guide/cqn.html Connection to oracle database was successful...
[ "Please take a look at the requirements for CQN in the documentation. Note in particular the fact that the database needs to connect back to the application. If this cannot be done no notifications will take place even though the registration is successful with the database. With Oracle Database 19.4 a new mode was...
[ 1 ]
[]
[]
[ "continuous_query_notification", "oracle", "python", "python_oracledb", "query_notifications" ]
stackoverflow_0074393496_continuous_query_notification_oracle_python_python_oracledb_query_notifications.txt
Q: How to solve "python pip install sslkeylog" error: Microsoft Visual C++ 14.0 or greater is required I try to install sslkeylog module however got the error as follows. I installed visual studio "Microsoft C++ Build Tools" as suggested in the error message however couldn't solved the problem. I will appreciate if y...
How to solve "python pip install sslkeylog" error: Microsoft Visual C++ 14.0 or greater is required
I try to install sslkeylog module however got the error as follows. I installed visual studio "Microsoft C++ Build Tools" as suggested in the error message however couldn't solved the problem. I will appreciate if you can guide me how to solve this problem. pip install sslkeylog Collecting sslkeylog Using cached ssl...
[ "You need to install Visual Studio Build Tools for C++\ndownload link here\npage link here\nThis will download the installer, open it and select Community on the Available tab. Then select Desktop Development with C++ and install that\n\niirc that should solve your issue ツ\n" ]
[ 1 ]
[]
[]
[ "pip", "python" ]
stackoverflow_0074393847_pip_python.txt
Q: Why does sampling the DataFrame of my entire dataset have better results in a prediction model than sampling my training set? Let's say I have a dataframe, called original_df, of 20,000 rows. I split the first 18,000 rows to be used as my training set and the last 2,000 rows to be used as my testing set. When I us...
Why does sampling the DataFrame of my entire dataset have better results in a prediction model than sampling my training set?
Let's say I have a dataframe, called original_df, of 20,000 rows. I split the first 18,000 rows to be used as my training set and the last 2,000 rows to be used as my testing set. When I use the sample function on the original_df before splitting and run a classifier model on the training set, it produces reasonable pr...
[ "Is your initial dataset sorted by label? If so, in the second case your training set might be only one label (negative) and your classifier learns to just always predict that label.\n", "It's because I had to reset_index() the training set after sampling. If the row with index training_length is shuffled to be t...
[ 0, 0 ]
[]
[]
[ "classification", "dataframe", "machine_learning", "pandas", "python" ]
stackoverflow_0074384011_classification_dataframe_machine_learning_pandas_python.txt
Q: code hangs when running interactive shell using paramiko I have written below code to run 3 command in remote server interactively But when I checked 3rd command never executed and code stuck here is my code def execute(): ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())...
code hangs when running interactive shell using paramiko
I have written below code to run 3 command in remote server interactively But when I checked 3rd command never executed and code stuck here is my code def execute(): ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect('ipaddress', username='user', password='pw') ...
[ "The code has following 2 errors:\n\nThe call to channel.recv is blocking, you should first check if channel has any data to be read or not using channel.recv_ready() \nAlso don't use buff.endswith(\"test >\") as a condition.As\nthe file_name might not always be at the last in buff. \n\nChange the while block to f...
[ 1, 0 ]
[]
[]
[ "paramiko", "python" ]
stackoverflow_0040252264_paramiko_python.txt
Q: What is the purpose of the "master" parameter in the tkinter Variable class/subclasses? I've been looking for some more detailed information regarding the Variable subclasses in tkinter, namely BooleanVar, DoubleVar, IntVar, and StringVar. I'm hoping someone with broader knowledge can point me in the right directi...
What is the purpose of the "master" parameter in the tkinter Variable class/subclasses?
I've been looking for some more detailed information regarding the Variable subclasses in tkinter, namely BooleanVar, DoubleVar, IntVar, and StringVar. I'm hoping someone with broader knowledge can point me in the right direction. Given the constructor: tkinter.Variable(master=None, value=None, name=None) I'm curious w...
[ "When you create an instance of Tk, you are doing more than just creating a widget. For each instance, you are also creating an embedded Tcl interpreter. This tcl interpreter is where all of the widgets and variables and image objects exist. The objects within this interpreter are only available to that interpreter...
[ 2 ]
[]
[]
[ "python", "tkinter", "variables" ]
stackoverflow_0074393442_python_tkinter_variables.txt
Q: Using itertools.product repeat multiple times I am trying to generate a list of unique lists each 5 elements long, the order is not important but there can't be any repeated elements. The first 3 elements needs to be from [1,2,3,4] and elements 4 and 5 from [5,6,7,8]. for example [1,2,3,7,8] is valid but [1,2,2,7,...
Using itertools.product repeat multiple times
I am trying to generate a list of unique lists each 5 elements long, the order is not important but there can't be any repeated elements. The first 3 elements needs to be from [1,2,3,4] and elements 4 and 5 from [5,6,7,8]. for example [1,2,3,7,8] is valid but [1,2,2,7,8] is not nor is [1,2,7,8,9] The below code works b...
[ "I would instead use itertools.combinations in combination with itertools.product:\nfrom itertools import chain, combinations, product\n\nresult = list(\n map(\n list,\n map(\n chain.from_iterable,\n product(\n combinations([1, 2, 3, 4], 3),\n com...
[ 1 ]
[ "the repeat is going to repeat the result two times, in case anyone is wondering about it .\nthe product takes 1 parameter, the second is optional\nfor more details :\nhttps://blog.teclado.com/python-itertools-part-1-product/\n" ]
[ -2 ]
[ "product", "python", "python_itertools" ]
stackoverflow_0071319927_product_python_python_itertools.txt
Q: How to read a file with special characters present in its path? What is done when encountered with special letters in file path, when trying to access it? To open a file, we need the specific path to the location where it lies. But in cases where the file path itself contains some special characters, like t, just ...
How to read a file with special characters present in its path?
What is done when encountered with special letters in file path, when trying to access it? To open a file, we need the specific path to the location where it lies. But in cases where the file path itself contains some special characters, like t, just after \, it shows error: OSError: [Errno 22] Invalid argument: 'tech\...
[ "Use a raw string, by putting r immediately before the string.\nf = open(r'tech\\tech_part.txt', 'r')\n\nThis forces Python to not apply the usual rules of backslash escapes, and so it treats \\t as simply \"backslash followed by t\", instead of \"tab\".\n", "You can use raw strings r'tech\\tech_part.txt' to igno...
[ 1, 1 ]
[]
[]
[ "compiler_errors", "path", "python" ]
stackoverflow_0074394150_compiler_errors_path_python.txt
Q: subprocess seems not working in pyinstaller exe file My program in tkinter is working well when I am running it using PyCharm, when I am creating .exe file using pyinstaller,pyinstaller -i"icon.ico" -w -F script.pyI have no errors. I am pasting script.exe in same folder as my script.py, and after running it I thi...
subprocess seems not working in pyinstaller exe file
My program in tkinter is working well when I am running it using PyCharm, when I am creating .exe file using pyinstaller,pyinstaller -i"icon.ico" -w -F script.pyI have no errors. I am pasting script.exe in same folder as my script.py, and after running it I think in step where subprocess is, it is not answering, becau...
[ "You can compile your code in -w mode or --windowed, but then you have to assign stdin and stderr as well. \nSo change:\ns = subprocess.Popen([EXE,files,'command'],shell=True, stdout=subprocess.PIPE)\n\nto:\ns = subprocess.Popen([EXE,files,'command'],shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin...
[ 13, 3, 2, 0, 0 ]
[]
[]
[ "python", "subprocess", "tkinter" ]
stackoverflow_0050463238_python_subprocess_tkinter.txt
Q: Firebase Admin SDK - Verify ID exists As part of our current API calls we receive the user's firebase installation ID. e.g. ezOi0OrW6UQAuyf9m0MeRq Is it possible to verify the ID actually exists via the Firebase Admin SDK in Python? Tried some of the functions regarding users in the SDK docs and kept getting user ...
Firebase Admin SDK - Verify ID exists
As part of our current API calls we receive the user's firebase installation ID. e.g. ezOi0OrW6UQAuyf9m0MeRq Is it possible to verify the ID actually exists via the Firebase Admin SDK in Python? Tried some of the functions regarding users in the SDK docs and kept getting user ID not found. I may be trying it in the wro...
[ "decoded_token = auth.verify_id_token(id_token)\nuid = decoded_token['uid']\nReference link: https://firebase.google.com/docs/auth/admin/verify-id-tokens#python\n" ]
[ 0 ]
[]
[]
[ "firebase", "python" ]
stackoverflow_0074392161_firebase_python.txt
Q: Python Can not parse website Human problem but open in website i try to parse website but there is error You need to enable support for <a href="https://yandex.ru/support/common/browsers-settings/browsers-java-js-settings.html">js</a> in your browser to visit this site I try this code import requests from bs4 impo...
Python Can not parse website Human problem but open in website
i try to parse website but there is error You need to enable support for <a href="https://yandex.ru/support/common/browsers-settings/browsers-java-js-settings.html">js</a> in your browser to visit this site I try this code import requests from bs4 import BeautifulSoup URL = "https://siteurl" headers={'User-Agent': 'Mo...
[ "The website asks for the enabled JavaScript. BeatifulSoup does not mimick a full-fledged web-browser, so it lacks JavaScript functionality. You can try using Selenium + BeatifulSoup together since Selenium behaves as a full fledged browser.\n" ]
[ 0 ]
[ "import requests\nfrom bs4 import BeautifulSoup\n\nURL = \"https://siteurl\"\npage = requests.get(URL)\n\nsoup = BeautifulSoup(page.text, \"html.parser\")\nprint(soup)\n\n" ]
[ -2 ]
[ "list", "parsing", "python", "python_3.x" ]
stackoverflow_0074394132_list_parsing_python_python_3.x.txt
Q: Get the size of an image using the Docker SDK for Python How do I get the size of a docker image using the Docker SDK for Python? import docker client = docker.from_env() some_image : docker.models.images.Image = client.images.list()[0] # size of some_image? As specified here, the regular docker API has some diff...
Get the size of an image using the Docker SDK for Python
How do I get the size of a docker image using the Docker SDK for Python? import docker client = docker.from_env() some_image : docker.models.images.Image = client.images.list()[0] # size of some_image? As specified here, the regular docker API has some differences when getting the size from a registry or locally. I'll...
[ "The size is listed in \"attrs\" json of the image.\nimport docker\nclient = docker.from_env()\nsome_image : docker.models.images.Image = client.images.list()[0]\nsome_image.attrs['Size'] # size in Bytes. \n\n" ]
[ 1 ]
[]
[]
[ "docker", "python" ]
stackoverflow_0074394237_docker_python.txt
Q: Python: Change key name in a list of dictionaries What is a pythonic way to remap each dictionary key in a list of dictionaries to different key names? The new name must be a concatenation between the existing key and the value of a list (value of list+"-"+ key), for the same index. E.g, List of dictionaries: [[{'...
Python: Change key name in a list of dictionaries
What is a pythonic way to remap each dictionary key in a list of dictionaries to different key names? The new name must be a concatenation between the existing key and the value of a list (value of list+"-"+ key), for the same index. E.g, List of dictionaries: [[{'Capture & Acquis.': '','Storage & Accounting': 'X','Tra...
[ "Try:\nlst_a = [\n [\n {\n \"Capture & Acquis.\": \"\",\n \"Storage & Accounting\": \"X\",\n \"Transformation\": \"\",\n }\n ],\n [{\"Process\": \"Acquisition\", \"Report\": \"Final\"}],\n [{\"Responsible\": \"APE\", \"Department\": \"ACC\"}],\n]\n\nlst_b =...
[ 1 ]
[]
[]
[ "dictionary", "list", "python", "python_3.x" ]
stackoverflow_0074394241_dictionary_list_python_python_3.x.txt
Q: Filter the logged in Users groups in before saving Django Hi upon registering a new user all the groups are listed for the user to select from the drop down. I am trying to filter this to only the groups that the logged in user is part of. views.py from .forms import UserRegisterForm @login_required(lo...
Filter the logged in Users groups in before saving Django
Hi upon registering a new user all the groups are listed for the user to select from the drop down. I am trying to filter this to only the groups that the logged in user is part of. views.py from .forms import UserRegisterForm @login_required(login_url='login') def addUser(request): ...
[ "you can try this\n\nforms.py\nclass UserRegisterForm(UserCreationForm):\n group = forms.ModelChoiceField(queryset=Group.objects.all(), required=True)\n def __init__(self,*args,**kwargs):\n # you can pass user id or \n #what ever you need to filter groups\n ...
[ 0 ]
[]
[]
[ "django", "python", "user_registration", "usergroups" ]
stackoverflow_0074394103_django_python_user_registration_usergroups.txt
Q: Why am I getting an incorrect payment total via Stripe in Python? I'm trying to make a payment through the ecommerce website I created. The payment successfully went through but the total amount charged is different than what I wanted to charge. For example, I want to charge $29.19 but I get charged $2,918.90. I k...
Why am I getting an incorrect payment total via Stripe in Python?
I'm trying to make a payment through the ecommerce website I created. The payment successfully went through but the total amount charged is different than what I wanted to charge. For example, I want to charge $29.19 but I get charged $2,918.90. I know it has something to do with the decimal places, but I seem to have ...
[ "If you look at the PaymentIntent object in the Stripe documentation you can see that the amount parameter accepts the price in the smallest currency unit.\n\nAmount intended to be collected by this PaymentIntent. A positive\ninteger representing how much to charge in the smallest currency unit\n(e.g., 100 cents to...
[ 2 ]
[]
[]
[ "python", "stripe_payments" ]
stackoverflow_0074394200_python_stripe_payments.txt
Q: Python Selenium (Getting Values from specific table) Image of the table I want to use So I wanted to get a specific value of the table, from a particular row and column, but there's no <table> in the inspect sheet, and I can't seem to find a way to retrieve my required result. My requirement is: Checking how many ...
Python Selenium (Getting Values from specific table)
Image of the table I want to use So I wanted to get a specific value of the table, from a particular row and column, but there's no <table> in the inspect sheet, and I can't seem to find a way to retrieve my required result. My requirement is: Checking how many users are there and how many are enabled/disabled The XPAT...
[ "Is this what you expect?\n# Needed libs\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\n# We create the driver\ndriver = webdriver.Chrome()\ndriver.maximize_win...
[ 1 ]
[]
[]
[ "python", "selenium", "selenium_webdriver" ]
stackoverflow_0074389823_python_selenium_selenium_webdriver.txt
Q: comparing two delta tables and replacing values in databricks I Have 2 delta tables: table1 has 10 columns (a,b,c,d,e,f,g,h,i,j) and table 2 has 8 columns (c,d,e,f,g,h,i,j) i want to compare both tables with respect to column c and fecth all the values to table 1 if it matches. and if column e has value 'closed'...
comparing two delta tables and replacing values in databricks
I Have 2 delta tables: table1 has 10 columns (a,b,c,d,e,f,g,h,i,j) and table 2 has 8 columns (c,d,e,f,g,h,i,j) i want to compare both tables with respect to column c and fecth all the values to table 1 if it matches. and if column e has value 'closed' in table 2 then table 1 column b should be replaced with 'OK' need...
[ "The following snippet should do that for you:\nfrom pyspark.sql.functions import when, col, lit\n\ndf_1 = spark.createDataFrame([(412, \"NOT_OKAY\", 123, None, None, None, None, None, None, None)], \"a: int, b: string, c: int, d: string, e: string, f: string, g: string, h: string, i: string, j: string\")\ndf_2 = s...
[ 0 ]
[]
[]
[ "pyspark", "python" ]
stackoverflow_0074393561_pyspark_python.txt
Q: Close PyWebView Window with HTML Button click Info in advance: There is a similar question dealing with the same issue. However, this one doesn't work for me (or I just don't know enough to include it properly). I have only recently started working with pywebview. The goal: I want to close the window / end the pro...
Close PyWebView Window with HTML Button click
Info in advance: There is a similar question dealing with the same issue. However, this one doesn't work for me (or I just don't know enough to include it properly). I have only recently started working with pywebview. The goal: I want to close the window / end the programme with a link (or button) in HTML. The problem...
[ "In the meantime I have found a solution that closes the window and exits the program. However, I get an error, unfortunately I do not know why.\n\nThe HTML / JS code is correct so far and needs no adjustment.\n\nIn the Python script, only def destroy(self) must be specified instead of def destroy(window).\n\nPrett...
[ 0, 0 ]
[]
[]
[ "html", "javascript", "python", "pywebview" ]
stackoverflow_0067208598_html_javascript_python_pywebview.txt
Q: How to convenient comment out if condition statement in Python? I am Python beginner, sometimes I would like to test my code without if condition statement like below picture Since Python determines the level of code by indentation, I had to resize the indentation after commenting out the if statement. And when I...
How to convenient comment out if condition statement in Python?
I am Python beginner, sometimes I would like to test my code without if condition statement like below picture Since Python determines the level of code by indentation, I had to resize the indentation after commenting out the if statement. And when I test passed, I have to resize the indentation to origin indentation ...
[ "You can remove spaces with SHIFT TAB\n" ]
[ 0 ]
[]
[]
[ "comments", "if_statement", "python" ]
stackoverflow_0074393755_comments_if_statement_python.txt
Q: How to fix an error about PATH when installing tensorflow on windows? I tried to install tensorflow, but I got the following error: My Command: pip install tensorflow The Error I got: ERROR: Could not install packages due to an OSError: [Errno 2] No such file or directory: 'C:\\Users\\sipha\\AppData\\Local\\Packa...
How to fix an error about PATH when installing tensorflow on windows?
I tried to install tensorflow, but I got the following error: My Command: pip install tensorflow The Error I got: ERROR: Could not install packages due to an OSError: [Errno 2] No such file or directory: 'C:\\Users\\sipha\\AppData\\Local\\Packages\\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0 \\LocalCache\\local...
[ "It seems like Long Path is disabled on your PC.\nDo the following to enable it, and then try to install Tensorflow.\n\nPress the Windows key + R key.\nType regedit and press enter.\nNavigate to the following location Computer\\HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\FileSystem in the registry edito...
[ 0 ]
[]
[]
[ "pip", "python", "tensorflow", "tensorflow2.0" ]
stackoverflow_0074371935_pip_python_tensorflow_tensorflow2.0.txt
Q: How to get value off JSON in Robot framework I have for example a log that will change each time it is run an example is below. I will like to take one of the value(id) lets say as a variable and log only the id to console or use that value somewhere else. [ { "@type": "type", "href": [ { ...
How to get value off JSON in Robot framework
I have for example a log that will change each time it is run an example is below. I will like to take one of the value(id) lets say as a variable and log only the id to console or use that value somewhere else. [ { "@type": "type", "href": [ { "@url": "url1", "@method": "get" }, ...
[ "You can see here that the JSON you are getting is in list format. Which means that to get a value from the JSON, you'll first need to read the JSON object in, then get the dictionary out of the list and only then access the key value you'd need to extract.\nRobot Framework supports using Python statements with Eva...
[ 0 ]
[]
[]
[ "automated_tests", "logging", "python", "robotframework" ]
stackoverflow_0074353852_automated_tests_logging_python_robotframework.txt
Q: Convert PNG to ZPL and print I'm trying to convert an image to ZPl and then print the label to a 6.5*4cm label on a TLP 2844 zebra printer on Python. My main problems are: 1.Converting the image 2.Printing from python to the zebra queue (I've honestly tried all the obvious printing packages like zebra0.5/ win32 p...
Convert PNG to ZPL and print
I'm trying to convert an image to ZPl and then print the label to a 6.5*4cm label on a TLP 2844 zebra printer on Python. My main problems are: 1.Converting the image 2.Printing from python to the zebra queue (I've honestly tried all the obvious printing packages like zebra0.5/ win32 print/ ZPL...) Any help would be ap...
[ "I had the same issue some weeks ago. I made a python script specifically for this printer, with some fields available. I commented (#) what does not involve your need, but left it in as you may find it helpful.\nI also recommend that you set your printer to the EPL2 driver, and 5cm/s print speed. With this script ...
[ 1, 0, 0 ]
[]
[]
[ "printing", "python", "windows", "zpl" ]
stackoverflow_0058123763_printing_python_windows_zpl.txt
Q: How to make buttons not dissapear while defining clear.canvas So esentially for this presentation I have to make a game and on the next to last GUI I have 4 buttons, once clicking one of them its supposed delete EVERYTHING but when doing def clear_command(): canvas.delete("all") It shows only the "Mulitplikas...
How to make buttons not dissapear while defining clear.canvas
So esentially for this presentation I have to make a game and on the next to last GUI I have 4 buttons, once clicking one of them its supposed delete EVERYTHING but when doing def clear_command(): canvas.delete("all") It shows only the "Mulitplikasjon" button and not the other ones. Im inexperienced in coding and ...
[ "According to your code, when pressing one of the buttons, it goes to the same function where the buttons are defined, so they are constantly being generated.\nI give you two ways to do that, it is really the same function written in different ways, but depending on what you need, you may find one or the other usef...
[ 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074393185_python_tkinter.txt
Q: Cannot turn response.text into a dictionary in Python I am using the Python request module and having trouble converting my response.text into a Python dictionary. def my_function(): url = API_URI["test"] headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} r = requests.post(url, ...
Cannot turn response.text into a dictionary in Python
I am using the Python request module and having trouble converting my response.text into a Python dictionary. def my_function(): url = API_URI["test"] headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} r = requests.post(url, data=json.dumps(api), headers=headers) print(r.text) ...
[ "As the error points out, the data should be decoded using utf-8-sig instead of the default utf-8 decoding.\nsomething like this:\ndecoded_data = r.text.encode().decode('utf-8-sig')\nreturn json.loads(decoded_data)\n\nwould probably work to load this data into a dictionary.\nEdit:\nSetting\nr.encoding = 'utf-8-sig'...
[ 2 ]
[]
[]
[ "python", "python_requests" ]
stackoverflow_0074394391_python_python_requests.txt
Q: Webdriver ( Selenium ) Cannot find the element ` import requests from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By from time import sleep imp...
Webdriver ( Selenium ) Cannot find the element
` import requests from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By from time import sleep import os login_page = "https://fap.fpt.edu.vn/Defaul...
[ "Google login page opens in a new window. So you need to switch to this window before interacting with it. So you need to use this code (the first and the last lines are from your code and between is the part you need to add):\nlogin1 = driver.find_element(\"xpath\",\"//div[@class='abcRioButtonContentWrapper']\").c...
[ 1, 0 ]
[]
[]
[ "python", "selenium", "selenium_chromedriver", "selenium_webdriver", "web_crawler" ]
stackoverflow_0074389314_python_selenium_selenium_chromedriver_selenium_webdriver_web_crawler.txt
Q: matching filename of an image with filename in pandas dataframe to copy matched images into a dest folder Can anyone help me with this: I am facing an issue while trying to copy the matched images based on the filename in the Pandas dataframe with the actual image filename in a folder into a destination folder. s...
matching filename of an image with filename in pandas dataframe to copy matched images into a dest folder
Can anyone help me with this: I am facing an issue while trying to copy the matched images based on the filename in the Pandas dataframe with the actual image filename in a folder into a destination folder. shutil.copy is throwing a error: [Errno 2] No such file or directory: '20161207-112141-0.jpg? for name in os.l...
[ " for name in src_dir: #glob.glob('Weed-4class-37/*.jpg')\n for i in range(len(df_filenames)): #df.Filename.tolist()\n if name.endswith(df_filenames[i]):\n shutil.copy(name, destination)\n\nThis piece of code was working but it is comparing the filename with all the filenames be...
[ 0 ]
[]
[]
[ "pandas", "python", "python_3.x" ]
stackoverflow_0074383851_pandas_python_python_3.x.txt
Q: Python Shape Printing Hi everyone, I have an assignment to acquire this shape in Python. I am a beginner, I tried to use nested loops to create this shape but I couldn't. Could someone help? Thanks a lot. (I couldn't copy the output exactly I'm sorry) I used nested for loops, if and else statements in various way...
Python Shape Printing
Hi everyone, I have an assignment to acquire this shape in Python. I am a beginner, I tried to use nested loops to create this shape but I couldn't. Could someone help? Thanks a lot. (I couldn't copy the output exactly I'm sorry) I used nested for loops, if and else statements in various ways (for example, I've tried ...
[ "This could be one way of solving it:\n\nif we define n as the sample input, the shape can be divided into 3 steps of length (n//2) each.\nInitialization: print('#'*n)\nStep 1: for i in range(n//2): print('*'+' '*(n-2)+'*')\nStep 2a: create a print_list: print_list = [k*' ' + '*'+ (n-2-2*k)*' ' + '*' + k*' ' for ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074394265_python.txt
Q: Python: if condition before reading a right or wrong input data type or to avoid `ValueError` I have the following code. It reads inputs of 2 integers and prints the sum of them. It also tries to check if the user fails to provide the correct inputs, i.e. if by mistake the user inputs string or float, the code wil...
Python: if condition before reading a right or wrong input data type or to avoid `ValueError`
I have the following code. It reads inputs of 2 integers and prints the sum of them. It also tries to check if the user fails to provide the correct inputs, i.e. if by mistake the user inputs string or float, the code will produce an error message and ask the user to enter new inputs again. I1, I2 = map(int, input('Ent...
[ "The map function has the syntax: map(fun, iter)\nSo as you wrote it, it already performs a check on the input data type.\nHowever, if you want to keep the code structure, you pass a lambda function that does nothing. For example:\nI1, I2 = map(lambda x : x, input('Enter 2 numbers\\n').split())\n\nprint('Numbers en...
[ 0, 0, 0, 0 ]
[]
[]
[ "if_statement", "input", "python", "python_3.x" ]
stackoverflow_0074393912_if_statement_input_python_python_3.x.txt
Q: Symbol not found: error while using ibm_db library in Python I am using Monterey MacOS and Python 3.10. While running this sample code: from ibm_db import connect from ibm_db import fetch_assoc from ibm_db import tables connection = connect('DATABASE=<DATABASE>;' 'HOSTNAME=<HOSTNAME>;' ...
Symbol not found: error while using ibm_db library in Python
I am using Monterey MacOS and Python 3.10. While running this sample code: from ibm_db import connect from ibm_db import fetch_assoc from ibm_db import tables connection = connect('DATABASE=<DATABASE>;' 'HOSTNAME=<HOSTNAME>;' 'PORT=<PORT>;' 'PROTOCOL=<PR...
[ "Please use the python ibm_db issues website at https://github.com/ibmdb/python-ibmdb/issues , becuse that is the ticketing site for issues with python ibm_db.\nSearch for Monterey and/or \"symbol not found\" and study the workarounds in the various hits,\nAt the present time, it appears that MachOs v12.1 and high...
[ 2, 0 ]
[]
[]
[ "db2", "gcc", "python" ]
stackoverflow_0074117514_db2_gcc_python.txt
Q: Python Playwright make code reload page after timeout until it finds the object I want the code to reload the page if it doesn't find the desired object (e.g. a button) after a given timeout time. The code should reload the page until it finds the object and then continue. Is there any way to do it in python playw...
Python Playwright make code reload page after timeout until it finds the object
I want the code to reload the page if it doesn't find the desired object (e.g. a button) after a given timeout time. The code should reload the page until it finds the object and then continue. Is there any way to do it in python playwright? I've read the documentation, but I didn't find anything, any help is appreciat...
[ "You can define your own function like this one:\ndef my_own_wait_for_selector(page, selector, time_out):\n try:\n page.wait_for_selector(selector, timeout=time_out)\n return True\n except:\n return False\n\nThat function will wait for a selector and if given some time (miliseconds) the e...
[ 0 ]
[]
[]
[ "automation", "playwright", "python" ]
stackoverflow_0074391065_automation_playwright_python.txt
Q: how compare two text file in python and delete duplicate? I am new in python. I have two text file contains list of url. I want to compare text1 file with text2 file and remove text2 matching url from text1 file. my text file look like this: text2 https://www.basketbal.vlaanderen/clubs/detail/bbc-wervik https://ww...
how compare two text file in python and delete duplicate?
I am new in python. I have two text file contains list of url. I want to compare text1 file with text2 file and remove text2 matching url from text1 file. my text file look like this: text2 https://www.basketbal.vlaanderen/clubs/detail/bbc-wervik https://www.basketbal.vlaanderen/clubs/detail/bbc-alsemberg https://www.b...
[ "If the order of the files doesn't matter, you can do this:\nwith open(\"file1.txt\") as f1:\n set1 = set(f1.readlines())\nwith open(\"file2.txt\") as f2:\n set2 = set(f2.readlines())\n\nnondups = set1 - set2\n\nwith open(\"file1.txt\", \"w\") as out:\n out.writelines(nondups)\n\nThis converts the contents...
[ 2, 1 ]
[]
[]
[ "python", "python_re" ]
stackoverflow_0068383996_python_python_re.txt
Q: Open Jupyter notebook without render images and without popolating dataframes - safe mode loading preventing out of memory state Under Windows 10 I have a Jupyter notebook that I am not able anymore to open because the browser reaches the "out of memory" state. The system resources tool confirms this: reaching 85%...
Open Jupyter notebook without render images and without popolating dataframes - safe mode loading preventing out of memory state
Under Windows 10 I have a Jupyter notebook that I am not able anymore to open because the browser reaches the "out of memory" state. The system resources tool confirms this: reaching 85% of used RAM the process is stopped. The last time I used the notebook there were a lot of rendered charts and some heavy dataframe po...
[ "You can copy your notebook to a new file and then clean the output from that. The clean version should then allow you to open it and access your code easily if indeed the output stored was the problem. (The copying is important because you don't want to clobber your original .ipynb file containing the intact outpu...
[ 2 ]
[]
[]
[ "jupyter", "out_of_memory", "python", "safe_mode" ]
stackoverflow_0074389001_jupyter_out_of_memory_python_safe_mode.txt
Q: Override JSONSerializer on django rest framework I'm trying to apply this fix on my django rest framework Adding root element to json response (django-rest-framework) But I'm not sure how to override the json serializer on django rest framework, any help would be great. The end result would be to have the root nod...
Override JSONSerializer on django rest framework
I'm trying to apply this fix on my django rest framework Adding root element to json response (django-rest-framework) But I'm not sure how to override the json serializer on django rest framework, any help would be great. The end result would be to have the root node name on the Json, because right now it's just an arr...
[ "I think you have your answer there in the post you've given.\nYou need to define custom JSON renderer\nfrom rest_framework.renderers import JSONRenderer\n\nclass EmberJSONRenderer(JSONRenderer):\n\n def render(self, data, accepted_media_type=None, renderer_context=None):\n data = {'element': data}\n ...
[ 22, 0 ]
[]
[]
[ "django", "django_rest_framework", "python" ]
stackoverflow_0020424521_django_django_rest_framework_python.txt
Q: from: command not found I'm trying to make my own python pack using setuptools, setup.py file and installing it directly from github repository. The package is sucessfully installed but when I call the command an error arises: line 1: from: command not found. somehow the binary file were not interpreted properly...
from: command not found
I'm trying to make my own python pack using setuptools, setup.py file and installing it directly from github repository. The package is sucessfully installed but when I call the command an error arises: line 1: from: command not found. somehow the binary file were not interpreted properly. I'm using anaconda but have...
[ "you need to start the python interpreter first in the command window, so just type python and then try your command.\n" ]
[ 0 ]
[]
[]
[ "conda", "pip", "python" ]
stackoverflow_0074394437_conda_pip_python.txt
Q: Fine control over the font size in Seaborn plots I'm currently trying to use Seaborn to create plots for my academic papers. The plots look great and easy to generate, but one problem that I'm having some trouble with is having the fine control on the font size in the plots. My font size in my paper is 9pt and I ...
Fine control over the font size in Seaborn plots
I'm currently trying to use Seaborn to create plots for my academic papers. The plots look great and easy to generate, but one problem that I'm having some trouble with is having the fine control on the font size in the plots. My font size in my paper is 9pt and I would like to make sure the font size in my plots are ...
[ "You are right. This is a badly documented issue. But you can change the font size parameter (by opposition to font scale) directly after building the plot. Check the following example:\nimport seaborn as sns\nimport matplotlib.pyplot as plt\ntips = sns.load_dataset(\"tips\")\n\nb = sns.boxplot(x=tips[\"total_bill\...
[ 109, 41, 0 ]
[]
[]
[ "matplotlib", "plot", "python", "seaborn" ]
stackoverflow_0036220829_matplotlib_plot_python_seaborn.txt
Q: Selenium Window Scroll to Bottom question Hello I am trying to use selenium to scrape the title for this page. https://sondors.com/collections/foldable-ebikes It seems that the elements have to wait me to scroll down the page to show up. So I use : driver.execute_script("window.scrollTo(0,document.body.scrollHeigh...
Selenium Window Scroll to Bottom question
Hello I am trying to use selenium to scrape the title for this page. https://sondors.com/collections/foldable-ebikes It seems that the elements have to wait me to scroll down the page to show up. So I use : driver.execute_script("window.scrollTo(0,document.body.scrollHeight);") before i call driver.find_elements(By......
[ "Try this:\n# Needed libs\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n# Set up Chrome driver\noptions=webdriver.ChromeOptions()\noptions.add_argument('--headle...
[ 1 ]
[]
[]
[ "google_colaboratory", "python", "selenium", "web_scraping" ]
stackoverflow_0074394328_google_colaboratory_python_selenium_web_scraping.txt
Q: sympy produces non-orthogonal column space When calculating the column space of a matrix with irrational numbers (e.g., sqrt(3)), sympy.columnspace() produces two vectors that are not orthogonal (e.g., V_1^TV_2 != 0). Given the matrix A: A = Matrix([[1.25000000000000, 0.25*sqrt(3), 0.500000000000000, 0, 1.25000000...
sympy produces non-orthogonal column space
When calculating the column space of a matrix with irrational numbers (e.g., sqrt(3)), sympy.columnspace() produces two vectors that are not orthogonal (e.g., V_1^TV_2 != 0). Given the matrix A: A = Matrix([[1.25000000000000, 0.25*sqrt(3), 0.500000000000000, 0, 1.25000000000000, -0.25*sqrt(3)], [0.25*sqrt(3), 0.750000...
[ "The vectors that comprise the column space are not necessarily orthogonal. In the above example, the column space is simply the first two columns of the matrix.\nTo orthogonalize, use the Gram-Schmidt process:\nV = GramSchmidt(A.columnspace(),True)\n\nwhere the optional argument True corresponds to normalizing the...
[ 3 ]
[]
[]
[ "linear_algebra", "python", "sympy" ]
stackoverflow_0074393864_linear_algebra_python_sympy.txt
Q: Read and concat multiple excel files based on a specific column path = '/Desktop/somefolder' for filename in os.listdir(path): with open(path+filename) as f: - read the 3-4 excel files and attach the path - be able to concat them based on a specific column filename gives me the name of the f...
Read and concat multiple excel files based on a specific column
path = '/Desktop/somefolder' for filename in os.listdir(path): with open(path+filename) as f: - read the 3-4 excel files and attach the path - be able to concat them based on a specific column filename gives me the name of the file I have in the directory. My idea was to concat the filename with...
[ "Read the data into data frames\ndf1 = pd.read_excel('file1.xlsx')\ndf2 = pd.read_excel('file2.xlsx') \n\nCreate filtered data frames\ndf1Filtered = df1[df1[\"YourColumnName\"].(\"YourColumnValues\")\ndf2Filtered = df2[df2[\"YourColumnName\"].(\"YourColumnValues\")\n\nConcat the filtered data frames\nNewDF = pd.con...
[ 1, 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074394405_pandas_python.txt
Q: I keep having this error with nested for loops n = int(input("Insérer entier inférieur à 100")) prime = [] if 100 >= n > 1 : for number in range(2, n+1): for div in range(number, 2): if number % div == 0 : prime.append(number) i want it to, if it's prime, add...
I keep having this error with nested for loops
n = int(input("Insérer entier inférieur à 100")) prime = [] if 100 >= n > 1 : for number in range(2, n+1): for div in range(number, 2): if number % div == 0 : prime.append(number) i want it to, if it's prime, add itself in the prime list ig ? please help me im str...
[ "First of all, you have the condition for inner loop, it should be range(2, number) instead of range(number, 2).\nFurthermore, you are not checking the number for prime correctly. Currently, if it checks whether 24 is prime or not, then, it will add 2, 3, 4, 6, 8 and 12 to the list - which is wrong.\nTo check wheth...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074394460_python.txt
Q: Time difference between two Python datetime objects in fractional seconds I am looking for an easy/Pythonic way to get the elapsed time difference (in fractional seconds) between two Python datetime objects. In the example below, I can see the delta.seconds and delta.microseconds attributes but am not sure what th...
Time difference between two Python datetime objects in fractional seconds
I am looking for an easy/Pythonic way to get the elapsed time difference (in fractional seconds) between two Python datetime objects. In the example below, I can see the delta.seconds and delta.microseconds attributes but am not sure what they actually contain and how they relate to the value returned by total_seconds(...
[ "total_seconds() is the entire delta time span expressed in seconds.\nNot sure what seconds represents in this case, you subtracted a time farther in the future (ctime) from mtime. Typically you would do the opposite.\nmicroseconds makes sense, as neither of your time variables contained microseconds.\nmake a prog...
[ 0, 0, 0, 0 ]
[]
[]
[ "python", "python_datetime", "timedelta" ]
stackoverflow_0074394434_python_python_datetime_timedelta.txt
Q: Odoo model operation throws "expected singleton" exception I want to perform an invoice operation with two records at the same time and I get this error. How do I solve it? ValueError: Expected singleton: account.invoice(481, 482) A: you can solve this by starting your code like this: def function(self): fo...
Odoo model operation throws "expected singleton" exception
I want to perform an invoice operation with two records at the same time and I get this error. How do I solve it? ValueError: Expected singleton: account.invoice(481, 482)
[ "you can solve this by starting your code like this:\ndef function(self):\n for invoice in self:\n # logic per invoice here\n\n" ]
[ 0 ]
[]
[]
[ "odoo", "python" ]
stackoverflow_0074394622_odoo_python.txt
Q: The correct way to create a new instance using pythoncom and force early binding Spent a little too much time trying to figure it out by myself... I'm working with a FEA app called Simcenter Femap. In my program I need to create N new instances of it after I get some data from base instance for some asyncio fun. C...
The correct way to create a new instance using pythoncom and force early binding
Spent a little too much time trying to figure it out by myself... I'm working with a FEA app called Simcenter Femap. In my program I need to create N new instances of it after I get some data from base instance for some asyncio fun. Can't even start on the asyncio part because I can't force early binding on new instanc...
[ "I recommend using pythoncom.New(...) instead of .connect(...).\n" ]
[ 0 ]
[]
[]
[ "comtypes", "python", "pythoncom" ]
stackoverflow_0073408878_comtypes_python_pythoncom.txt
Q: Just trying to make a simple calculator, but it keeps saying "Invalid Syntax: Perhaps you forgot a comma" operation = str(input("Operation (type which operation you would like): ")) if operation == "division": number1 = float(input("1st Number? ")) number2 = float(input("2nd Number? ")) quotient = numb...
Just trying to make a simple calculator, but it keeps saying "Invalid Syntax: Perhaps you forgot a comma"
operation = str(input("Operation (type which operation you would like): ")) if operation == "division": number1 = float(input("1st Number? ")) number2 = float(input("2nd Number? ")) quotient = number1 / number2 print(str(number1) + " / " + str(number2) " = " + str(division)) elif operation == "multiplic...
[ "As others have pointed out, you're missing a + sign in your if block. I'm putting the fix here for readability\nif operation == \"division\":\n number1 = float(input(\"1st Number? \"))\n number2 = float(input(\"2nd Number? \"))\n quotient = number1 / number2\n # the issue is here ----------------------...
[ 0, 0 ]
[]
[]
[ "python", "syntax_error" ]
stackoverflow_0074394621_python_syntax_error.txt
Q: Python, largest odd integer I am new to coding and have been learning a few days now. I wrote this program in Python while following along in some MIT OpenCourseware lectures and a few books. Are there anyways to more easily express the program? Finger exercise: Write a program that asks the user to input 10 inte...
Python, largest odd integer
I am new to coding and have been learning a few days now. I wrote this program in Python while following along in some MIT OpenCourseware lectures and a few books. Are there anyways to more easily express the program? Finger exercise: Write a program that asks the user to input 10 integers, and then prints the largest...
[ "A more compact form would be:\nfrom __future__ import print_function\ntry: # Python 2\n raw_input\nexcept NameError: # Python 3 compatibility\n raw_input = input\n\nlargest = None\n\nfor i in range(1, 11):\n number = int(raw_input('Enter integer #%d: ' % i))\n if number % 2 != 0 and (not largest or n...
[ 7, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ "This code should work work as well. Syntax tested for python 2.7\n def tenX(): #define function\n ten = [] #empty list for user input\n odds = [] #empty list for odd numbers only\n counter = 10\n ui = 0\n while counter > 0 :\n ui = raw_input('Enter a number: ')\n ten.append(int(ui)) #...
[ -1 ]
[ "python" ]
stackoverflow_0027005437_python.txt
Q: Are there like "asyncio.gather()" to run multiple threads or processes together in Python? There are 2 sets of code below to run multiple threads or multiple processes. Multiple threads: from threading import Thread import queue def test1(num1, num2, q): q.put(num1 + num2) def test2(num1, num2, q): q.put...
Are there like "asyncio.gather()" to run multiple threads or processes together in Python?
There are 2 sets of code below to run multiple threads or multiple processes. Multiple threads: from threading import Thread import queue def test1(num1, num2, q): q.put(num1 + num2) def test2(num1, num2, q): q.put(num1 + num2) queue1 = queue.Queue() queue2 = queue.Queue() thread1 = Thread(target=test1, arg...
[ "That's why the concurrent.futures module exists.\nimport concurrent.futures\nimport time\nimport asyncio\n\ndef print_hi():\n time.sleep(2)\n print(\"hi\")\n return 1\n\nasync def print_hi_async():\n await asyncio.sleep(2)\n print(\"hi\")\n return 1\n\nif __name__ == \"__main__\":\n loop = asy...
[ 0 ]
[]
[]
[ "gather", "python", "python_3.x", "python_multiprocessing", "python_multithreading" ]
stackoverflow_0074384557_gather_python_python_3.x_python_multiprocessing_python_multithreading.txt
Q: Not able to efficiently split two list having multiple spaces and commas using regex python I have 2 lists shown below which I am trying to split, however the regex expression used in the code is not efficiently splitting the list. Input List: Newlist1 = [['66021 4668873364_166638418 3,9202-DC,669251 ...
Not able to efficiently split two list having multiple spaces and commas using regex python
I have 2 lists shown below which I am trying to split, however the regex expression used in the code is not efficiently splitting the list. Input List: Newlist1 = [['66021 4668873364_166638418 3,9202-DC,669251 GEORGIA KS 16.0 55 7 0 1 11/03/22 00:00 11/04/22 23:58...
[ "Does this do what you're looking for?\nimport re\n\n\nNewlist1 = [['66021 4668873364_166638418 3,9202-DC,669251 GEORGIA KS 16.0 55 7 0 1 11/03/22 00:00 11/04/22 23:58 11/03/22 00:01 11/18/22 23:59 11/03/22 09:21 11/03/22 09:21 00:00 00:00 ...
[ 0 ]
[]
[]
[ "list", "python", "regex", "split" ]
stackoverflow_0074393063_list_python_regex_split.txt
Q: Pandas dataframe has zero elements after using dropna() My dataframe has zero elements after I use dropna() on a 2-dimensional array: data = pd.read_excel('/file.xlsx', sheet_name='Sheet1', engine='openpyxl').iloc[0:, 0:].astype(float).dropna().values.flatten() data array([], dtype=float64) However dropna() wor...
Pandas dataframe has zero elements after using dropna()
My dataframe has zero elements after I use dropna() on a 2-dimensional array: data = pd.read_excel('/file.xlsx', sheet_name='Sheet1', engine='openpyxl').iloc[0:, 0:].astype(float).dropna().values.flatten() data array([], dtype=float64) However dropna() works perfectly fine on a 1-dimensional array and the NaNs get c...
[ "By default the .dropna() removes the entire selected axis, speaking of axis, the default axis is also set to be rows. Maybe that's not what you want?\nIf you then in each rows have a NaN value, then all of the rows is going to be droped.\nTo fix this you can specify it like this\n.dropna(axis=1)\n\n", "The dropn...
[ 1, 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074394767_pandas_python.txt
Q: Pop an object from a class list I have 2 classes. AlchemicalStorage class is used to store the AlchemicalElement objects. class AlchemicalElement: def __init__(self, name: str): self.name = name def __repr__(self): return f'<AE: {self.name}>' class AlchemicalStorage: def __init__(se...
Pop an object from a class list
I have 2 classes. AlchemicalStorage class is used to store the AlchemicalElement objects. class AlchemicalElement: def __init__(self, name: str): self.name = name def __repr__(self): return f'<AE: {self.name}>' class AlchemicalStorage: def __init__(self): self.storage_list = [] ...
[ "You can just iterate through your storage list backwards and return the first instance, if it exists:\ndef pop(self, element_name: str) -> AlchemicalElement | None:\n for element in reversed(self.storage_list):\n if element.name == element_name:\n self.storage_list.remove(element)\n ...
[ 1, 0 ]
[]
[]
[ "class", "list", "oop", "python" ]
stackoverflow_0074392253_class_list_oop_python.txt
Q: Regex pattern to match multiple characters and split I haven't used regex much and was having issues trying to split out 3 specific pieces of info in a long list of text I need to parse. note = "**Jane Greiz** `#1`: Should be open here .\n**Thomas Fitzpatrick** `#90`: Anim: Can we start the movement.\n**Anthony Sm...
Regex pattern to match multiple characters and split
I haven't used regex much and was having issues trying to split out 3 specific pieces of info in a long list of text I need to parse. note = "**Jane Greiz** `#1`: Should be open here .\n**Thomas Fitzpatrick** `#90`: Anim: Can we start the movement.\n**Anthony Smith** `#91`: Her left shoulder.\nhttps://google.com" pat...
[ "Don't use alternatives. Put the name and number patterns after each other in a single alternative, and add another group for the match up to the next **.\nnote = \"**Jane Greiz** `#1`: Should be open here .\\n**Thomas Fitzpatrick** `#90`: Anim: Can we start the movement.\\n**Anthony Smith** `#91`: Her left shoulde...
[ 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074394808_python_regex.txt
Q: How to mark an email as read using O365 in python The goal of this project is to look through a mailbox and detach attachments based on subject, sender, has attachments and is read. For this to work, each email that is found must be set to read which it is being processed. I am using the O365 library from python t...
How to mark an email as read using O365 in python
The goal of this project is to look through a mailbox and detach attachments based on subject, sender, has attachments and is read. For this to work, each email that is found must be set to read which it is being processed. I am using the O365 library from python to access the mailbox and search the mailbox and this wo...
[ "This is most probably an issue caused by improper API permissions on the registered app on the Azure Portal. Ensure that the app you have registered has 'Mail.ReadWrite' permission enabled since 'mark_as_read' is essentially a Write activity. See below:\nAzure App Permissions\nI had the same issue and this solved ...
[ 0 ]
[]
[]
[ "azure", "microsoft_graph_api", "python", "python_o365" ]
stackoverflow_0074142687_azure_microsoft_graph_api_python_python_o365.txt
Q: ChromeDriver "cannot create default profile directory" I am using selenium with python, and I'm trying to use some arguments for starting the chromedriver. from selenium import webdriver from selenium.webdriver.chrome.options import Options as ChromeOptions def buildDriver(): options = ChromeOptions() opt...
ChromeDriver "cannot create default profile directory"
I am using selenium with python, and I'm trying to use some arguments for starting the chromedriver. from selenium import webdriver from selenium.webdriver.chrome.options import Options as ChromeOptions def buildDriver(): options = ChromeOptions() options.add_argument('--profile-directory="Default"') optio...
[ "Turns out you cannot use quotes when adding an argument.\noptions.add_argument('--profile-directory=Default')\noptions.add_argument('--user-data-dir=C:/Temp/ChromeProfile')\n\nNotice that it's --profile-directory=Default instead of --profile-directory=\"Default\"\nThis is what fixed the issue for me.\n", "option...
[ 19, 1 ]
[]
[]
[ "automation", "python", "selenium", "selenium_chromedriver" ]
stackoverflow_0036434415_automation_python_selenium_selenium_chromedriver.txt
Q: Modify the code to loop over another dataset I am using haversine_distance function to calculate distance between coordinates in a dataset to a specific coordinate. [start_lat, start_lon = 40.6976637, -74.1197643] def haversine_distance(lat1, lon1, lat2, lon2): r = 6371 phi1 = np.radians(lat1) phi2 = np...
Modify the code to loop over another dataset
I am using haversine_distance function to calculate distance between coordinates in a dataset to a specific coordinate. [start_lat, start_lon = 40.6976637, -74.1197643] def haversine_distance(lat1, lon1, lat2, lon2): r = 6371 phi1 = np.radians(lat1) phi2 = np.radians(lat2) delta_phi = np.radians(lat2-lat1...
[ "The beauty of Python is that you can use the same code to do different things.\nTo consider different [start_lat, start_lon] values for every column in your data, you can use the same code that you have now. All you need to do is to define start_lat and start_lon as arrays:\n# --------------------- Array Initiali...
[ 0 ]
[]
[]
[ "dataframe", "loops", "python" ]
stackoverflow_0074394824_dataframe_loops_python.txt
Q: Avoid models replication between app and DB I have an application with a DB. I'm using SQLAlchemy as the orm. I have drawn "on paper" my diagram with attributes and relationships between classes of my application. Now I want to code this diagram in classes of my apps with attributes, methods and relationships. Bu...
Avoid models replication between app and DB
I have an application with a DB. I'm using SQLAlchemy as the orm. I have drawn "on paper" my diagram with attributes and relationships between classes of my application. Now I want to code this diagram in classes of my apps with attributes, methods and relationships. But I also want that these are reflected into the ...
[ "The reason is arguable mostly historic. FastAPI uses Pydantic models for defining API schemata. SQLAlchemy is a DB abstraction and ORM. The latter is also much older. They serve distinct purposes. Just because you need an ORM for example, does not mean you are interested in writing a web API.\nIt just so happened ...
[ 0 ]
[]
[]
[ "postgresql", "pydantic", "python", "sqlalchemy" ]
stackoverflow_0074388030_postgresql_pydantic_python_sqlalchemy.txt
Q: CS50 dna.py compare STR counts with database So I got this far: names[] - is a dict with CSV data str[] - column names from CSV - to access STR names sequence[] - dna sequence from TXT checked_seq[] - list with STR counts from sequence I now got stuck on the final task: Need to compare the STR counts against ea...
CS50 dna.py compare STR counts with database
So I got this far: names[] - is a dict with CSV data str[] - column names from CSV - to access STR names sequence[] - dna sequence from TXT checked_seq[] - list with STR counts from sequence I now got stuck on the final task: Need to compare the STR counts against each person`s data from CSV Output the match Here`s...
[ "Slept on it and found the solution that works.\nProblem solved!\n" ]
[ 0 ]
[]
[]
[ "cs50", "python" ]
stackoverflow_0074381478_cs50_python.txt
Q: How to create bigrams of categorical column into separate columns? So I would like to take every row and split it into bigrams to be used as columns in order to encode the original string column. I have a dataset like this one: A blue red black I want my result to look like this: A bl lu ue re ed la ac ck b...
How to create bigrams of categorical column into separate columns?
So I would like to take every row and split it into bigrams to be used as columns in order to encode the original string column. I have a dataset like this one: A blue red black I want my result to look like this: A bl lu ue re ed la ac ck blue 1 1 1 0 0 0 0 0 red 0 0 0 1 1 0 0 0 black 1 0 0...
[ "Here's a way to do:\n# sample data\nf = pd.DataFrame({'A': ['blue', 'red', 'black']})\n\ndef bigram(s, n=2):\n return [s[i:i+n] for i in range(0, len(s), 1) if len(s[i:i+2]) == n]\n\n# using pandas \nf['bgm'] = f['A'].apply(bigram)\nf = f.explode('bgm').reset_index(drop=True)\nf = pd.crosstab(f['A'], f['bgm'])....
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074394849_python.txt
Q: i can't figure out how to use the discord.Member.remove_roles I want to remove the roles of those who send messages less than 20 characters, but I can't figure out how to use the discord.Member.remove_roles part I get this error TypeError: Member.remove_roles() missing 1 required positional argument: 'self' @Bot.e...
i can't figure out how to use the discord.Member.remove_roles
I want to remove the roles of those who send messages less than 20 characters, but I can't figure out how to use the discord.Member.remove_roles part I get this error TypeError: Member.remove_roles() missing 1 required positional argument: 'self' @Bot.event async def on_message(message): if len(message.content) < 2...
[ "Here's a little something that might help you.\n@bot.command()\nasync def example(ctx, member: discord.Member):\n role = discord.utils.get(ctx.guild.roles, name=\"Role\")\n await member.remove_roles(role)\n\nRemoves a role when the command is ran\n" ]
[ 0 ]
[]
[]
[ "discord", "discord.py", "python" ]
stackoverflow_0074256374_discord_discord.py_python.txt
Q: Checking multiple conditions for a "password" I'm trying to write code that can check if an input contains; At least 8 letters, whereas at least 1 of those is a number (0-9) Contains an upper and lower case character I keep getting stuck in a "inputs password, returns true, and input password again, exit" single...
Checking multiple conditions for a "password"
I'm trying to write code that can check if an input contains; At least 8 letters, whereas at least 1 of those is a number (0-9) Contains an upper and lower case character I keep getting stuck in a "inputs password, returns true, and input password again, exit" single loop.. Fairly new at programming, doing my first s...
[ "for ele in password:\n if ele.isupper and ele.islower and ele.isdigit and len(password) > 7:\n return \"True\"\n else:\n return \"False\"\n\nThis code has several problems.\nFirst, you're referring to the ele.isupper function, but because you don't have parentheses (), you're not calling the fu...
[ 2, 1, 1, 1, 1 ]
[ "for ele in password will iterate through the characters in the user's input.\nyour if statement doesnt make sense. ele.isupper and ele.islower will never be true at the same time.\nif statement needs work. make booleans for each condition you want to validate and set them to true individually is you see the requ...
[ -1 ]
[ "python" ]
stackoverflow_0074394498_python.txt
Q: Finding the summation of values from two pandas dataframe column I have a pandas dataframe like below import pandas as pd data = [[5, 10], [4, 20], [15, 30], [20, 15], [12, 14], [5, 5]] df = pd.DataFrame(data, columns=['x', 'y']) I am trying to attain the value of this expression. I havnt got an idea how to muti...
Finding the summation of values from two pandas dataframe column
I have a pandas dataframe like below import pandas as pd data = [[5, 10], [4, 20], [15, 30], [20, 15], [12, 14], [5, 5]] df = pd.DataFrame(data, columns=['x', 'y']) I am trying to attain the value of this expression. I havnt got an idea how to mutiply first value in a column with 2nd value in another column like in t...
[ "You can use pandas.DataFrame.shift(). You can one times compute shift(-1) and use it for 'x' and 'y'.\n>>> df_tmp = df.shift(-1)\n>>> (df['x']*df_tmp['y'] - df_tmp['x']*df['y']).sum() * 0.5\n-202.5\n\n# Explanation\n>>> df[['x+1', 'y+1']] = df.shift(-1)\n>>> df\n x y x+1 y+1\n0 5 10 4.0 20.0 # x*(y+...
[ 1, 1, 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074394821_pandas_python.txt
Q: AttributeError: 'Group' object has no attribute 'collide' Pygame I'm creating a basic simulation in pygame and my object (an amoeba represented by a green square on the screen) has two methods. My update method is running fine, but the collide method is giving my an attribute error. By the way, since I have added ...
AttributeError: 'Group' object has no attribute 'collide' Pygame
I'm creating a basic simulation in pygame and my object (an amoeba represented by a green square on the screen) has two methods. My update method is running fine, but the collide method is giving my an attribute error. By the way, since I have added many amoebae to the screen, I apply the methods to my amoebas group. i...
[ "pygame.sprite.Group.draw() and pygame.sprite.Group.update() are methods which are provided by pygame.sprite.Group.\nThe latter delegates to the update method of the contained pygame.sprite.Sprites — you have to implement the method. See pygame.sprite.Group.update():\n\nCalls the update() method on all Sprites in t...
[ 2 ]
[]
[]
[ "attributeerror", "group", "oop", "pygame", "python" ]
stackoverflow_0074395025_attributeerror_group_oop_pygame_python.txt
Q: newff and train functions of python's neurolab is giving inconsistent results for same code and input While the input is the same and the code is the same, I get two different results when run multiple time. There are only two unique outputs though. I do not know what part of the code is randomized and I'm having ...
newff and train functions of python's neurolab is giving inconsistent results for same code and input
While the input is the same and the code is the same, I get two different results when run multiple time. There are only two unique outputs though. I do not know what part of the code is randomized and I'm having a hard time figuring out where the error is. Is this a known bug in neurolab by any chance? I've attached t...
[ "Neural network training is not deterministic. It starts from random initialization of weights and perform (greedy in nature) optimziation process. You cannot expect the exact same results, unless you fix all random number generators used in nn training.\n", "You can fix it using in the beginning of the code\nnum...
[ 0, 0 ]
[]
[]
[ "gradient_descent", "machine_learning", "python" ]
stackoverflow_0036971678_gradient_descent_machine_learning_python.txt
Q: Scan of data of a specific column in DynamoDB table - Reserved Keyword I am trying to scan all the items of a specific column from a dynamodb table: I only want to get the data from the data column. I am not interesting in the seqno and payload column. I am using this code right now import boto3 dynamodb = boto3...
Scan of data of a specific column in DynamoDB table - Reserved Keyword
I am trying to scan all the items of a specific column from a dynamodb table: I only want to get the data from the data column. I am not interesting in the seqno and payload column. I am using this code right now import boto3 dynamodb = boto3.resource('dynamodb') table = dynamodb.Table('TablaLoraPF') response = tabl...
[ "Sometimes there is a need for everyone to use DynamoDB's reserved keyword names on their attribute names. In such cases, they can utilize the expression attribute names to map the reserved keyword name with another alternative name.\nYou can use the expression attribute names in your code as like below:\n...\nresp...
[ 0 ]
[]
[]
[ "amazon_dynamodb", "amazon_web_services", "aws_lambda", "python" ]
stackoverflow_0074392742_amazon_dynamodb_amazon_web_services_aws_lambda_python.txt
Q: Multiprocessing with Python from a text file I'm trying to extract the data for given set of PMID from a text file, how can I speed up the process, Can someone help with how to implement multiprocessing, thanks. import pandas as pd import os os.environ['NCBI_API_KEY'] = "" import metapub with open("pmid.txt", "r"...
Multiprocessing with Python from a text file
I'm trying to extract the data for given set of PMID from a text file, how can I speed up the process, Can someone help with how to implement multiprocessing, thanks. import pandas as pd import os os.environ['NCBI_API_KEY'] = "" import metapub with open("pmid.txt", "r") as file: pmid = file.read().splitlines() d...
[ "I got a bit carried away with this and ended up writing code to use a ThreadPool as this will be network bound so having multiple processes isn't going to help.\nI've tried to put some comments and docstrings in, but it might be a bit fancier code than your question suggests you're used to. Responses from PubMed ...
[ 0 ]
[]
[]
[ "dask", "multiprocessing", "ncbi", "python" ]
stackoverflow_0074389540_dask_multiprocessing_ncbi_python.txt
Q: Python class attributeError, even though I have that attribute I'm making some code with pygame and for some twisted, wicked reason I get an attributeError when obviosly I have that atrribute. What is even more interesting that I only get error at the second if statement. If I comment it out I get no errors. It is...
Python class attributeError, even though I have that attribute
I'm making some code with pygame and for some twisted, wicked reason I get an attributeError when obviosly I have that atrribute. What is even more interesting that I only get error at the second if statement. If I comment it out I get no errors. It is very annoying. Somebody please help me out! The vector() object I u...
[ "Attributes in Python are created dynamically when __init__ gives them a value, not statically at compile time. You are calling the player_surf method before you define self.vel but try to use self.vel in the body of player_surf. If you rearrange the order of the lines in __init__ so that you define vel before (ind...
[ 0 ]
[]
[]
[ "attributeerror", "python" ]
stackoverflow_0074394435_attributeerror_python.txt
Q: Comparing 2 values from the same line and looping to the next for all line in file main code: fgcuWins = 0 fgcuLoses = 0 ties = 0 file = open("2022_sport.txt", "r") for lines in file: if char[1] == char[3]: ties += 1 lines += 1 elif char[1] > char[3]: fgcuWins += 1 lines += ...
Comparing 2 values from the same line and looping to the next for all line in file
main code: fgcuWins = 0 fgcuLoses = 0 ties = 0 file = open("2022_sport.txt", "r") for lines in file: if char[1] == char[3]: ties += 1 lines += 1 elif char[1] > char[3]: fgcuWins += 1 lines += 1 else: fgcuLoses += 1 lines += 1 print(fgcuWins) print(fgcuLoses) ...
[ "Read each line of file, split line on '-', compare left int to right int and increment applicable win, loss, tie count.\nwins = 0\nlosses = 0\nties = 0\n\nwith open('2022_sport.txt', 'r') as f:\n for line in f:\n line = line.strip().split('-')\n if line[0] > line[1]:\n wins += 1\n ...
[ 1 ]
[]
[]
[ "compare", "python", "text" ]
stackoverflow_0074395015_compare_python_text.txt
Q: How to follow someone on Twitter using tweepy/Python? I'm trying to create a Twitter bot using tweepy that will search, like and retweet any status update containing the words "Retweet to enter", and I was successful. However, I would also like the script to follow the person that created the composition (I'm crea...
How to follow someone on Twitter using tweepy/Python?
I'm trying to create a Twitter bot using tweepy that will search, like and retweet any status update containing the words "Retweet to enter", and I was successful. However, I would also like the script to follow the person that created the composition (I'm creating this script to try and win contests, and you often nee...
[ "The comments from Alan on the question are indeed correct, api.search returns retweets as well as original tweets. At the moment, for retweets, your code will follow the retweeting account. Here are a couple of ways you can handle this:\nFilter out retweets\nWhile you could get all tweets and then filter the resul...
[ 1, 0 ]
[]
[]
[ "python", "python_3.x", "tweepy" ]
stackoverflow_0058844898_python_python_3.x_tweepy.txt
Q: Using Multiple Unique rows to create different Excel Workbooks from Python Hoping to use Python to use multiple combine multiple values in a single column into its own workbook - basically, grouping a few unique values together. Input: data = {'Name': ['Tom', 'nick', 'nick', 'jack'], 'Age': [20, 21, 19, 18...
Using Multiple Unique rows to create different Excel Workbooks from Python
Hoping to use Python to use multiple combine multiple values in a single column into its own workbook - basically, grouping a few unique values together. Input: data = {'Name': ['Tom', 'nick', 'nick', 'jack'], 'Age': [20, 21, 19, 18]} Goal Output: Edited slightly: I would like this to result in 2 new workbook...
[ "Here's a way to do using for loop with pandas:\nwith pd.ExcelWriter('output.xlsx') as writer: \n for name in data['Name'].unique():\n df = data[data['Name'] == name]\n df.to_excel(writer, sheet_name=name)\n\nThis outputs a output.xlsx file having three sheets.\nTo output to three different files,...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074395038_dataframe_pandas_python.txt
Q: Assign a session variable in Jinja2 / flask in front end html page Hello I have a problem with a select/option html where you can select the page number, so page 1 of 100, 2 of 200 etc... and then goes to page 1, 2, 3 ... Everything works in the following code apart from the fact that inside the select button, aft...
Assign a session variable in Jinja2 / flask in front end html page
Hello I have a problem with a select/option html where you can select the page number, so page 1 of 100, 2 of 200 etc... and then goes to page 1, 2, 3 ... Everything works in the following code apart from the fact that inside the select button, after clicking on the page you want to go, after refreshing the page, it go...
[ "In general, you cannot assign to an object atribute using set, neither using obj['attr'] or obj.attr syntax (see the documentation). However, you can enable the expression-statement extension and then set the attribute using dict update like this:\n{% do session.update({'page': page}) %}\n\nBut as already stated i...
[ 1, 0 ]
[]
[]
[ "flask", "jinja2", "python" ]
stackoverflow_0055965795_flask_jinja2_python.txt
Q: Python: merge Nested Dictionary into one JSON How to merge strings from the yield generator of JSON into one JSON? I have got Nested Dictionary by yield generator, and I aim to have one JSON file. I have the output of these correct strings of nested dictionary. {"domain.com": {"Chrome": "19362.344607264396"}} {"do...
Python: merge Nested Dictionary into one JSON
How to merge strings from the yield generator of JSON into one JSON? I have got Nested Dictionary by yield generator, and I aim to have one JSON file. I have the output of these correct strings of nested dictionary. {"domain.com": {"Chrome": "19362.344607264396"}} {"domain.com": {"ChromeMobile": "7177.498437391487"}} {...
[ "Something like this\nimport json\n\n\nDATA = [\n {\"domain.com\": {\"Chrome\": \"19362.344607264396\"}},\n {\"domain.com\": {\"ChromeMobile\": \"7177.498437391487\"}},\n {\"another.com\": {\"MobileSafari\": \"6237.433155080214\"}},\n {\"another.com\": {\"Safari\": \"5895.409403430795\"}}\n]\n\n\ndef yi...
[ 0 ]
[]
[]
[ "json", "python" ]
stackoverflow_0074394959_json_python.txt
Q: Does fsspec support virtual filesystems such as pyfileysystem One of pyfilesystem's main feature is virtual filesystems. E.g. home_fs = open_fs('~/') projects_fs = home_fs.opendir('/projects') I think that is a great feature and was hoping that fsspec has something similar. But I couldn't find an example and I'm ...
Does fsspec support virtual filesystems such as pyfileysystem
One of pyfilesystem's main feature is virtual filesystems. E.g. home_fs = open_fs('~/') projects_fs = home_fs.opendir('/projects') I think that is a great feature and was hoping that fsspec has something similar. But I couldn't find an example and I'm not able to get it working.
[ "You might want DirFileSystem, invoked like\nfs = fsspec.implementations.dirfs.DirFileSystem(\n \"<root path>\", fs=fsspec.filesystem(\"file\")\n)\n\nYou can apply this to any filesystem, not only local. root_path needs to be a string that, when you affix further path parts to it, makes a complete path the targe...
[ 0 ]
[]
[]
[ "fsspec", "pyfilesystem", "python" ]
stackoverflow_0074387348_fsspec_pyfilesystem_python.txt
Q: Pandas transform list values and their column names I have a pandas dataframe with 1 row and values in columns by separated by categories car > audi > a4 car > bmw > 3er moto > bmw > gs [item1, item2, item3] [item1, item4, item5] [item6] and I would like to create structure something like this: item category 1...
Pandas transform list values and their column names
I have a pandas dataframe with 1 row and values in columns by separated by categories car > audi > a4 car > bmw > 3er moto > bmw > gs [item1, item2, item3] [item1, item4, item5] [item6] and I would like to create structure something like this: item category 1 category 2 category 3 item 1 car audi a4...
[ "You can use:\n(df.set_axis(df.columns.str.split('\\s*>\\s*', expand=True), axis=1)\n .loc[0].explode()\n .reset_index(name='item')\n .rename(columns=lambda x: x.replace('level_', 'category'))\n)\n\nOutput:\n category0 category1 category2 item\n0 car audi a4 item1\n1 car audi ...
[ 2, 1 ]
[ "You can use the explode function that is a pandas built-in.\nDocumentation\n" ]
[ -1 ]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074389607_dataframe_pandas_python.txt
Q: extract a class from beatiful soup I Have a HTML script that after extraction looks something like this: class="a-toaster Toaster_toaster__bTabZ"> </div> </div> </div> <script id="__NEXT_DATA__" type="application/json"> {"props":{"pageProps": {"type":"Job","sid":"a84cacbbcb07ec55cdbfd5fbe3d9f252d7f9c...
extract a class from beatiful soup
I Have a HTML script that after extraction looks something like this: class="a-toaster Toaster_toaster__bTabZ"> </div> </div> </div> <script id="__NEXT_DATA__" type="application/json"> {"props":{"pageProps": {"type":"Job","sid":"a84cacbbcb07ec55cdbfd5fbe3d9f252d7f9cdd0","loggedIn":false,"userId":null,"ava...
[ "Try:\nimport json\nfrom bs4 import BeautifulSoup\n\nhtml_doc = \"\"\"\\\n<div class=\"a-toaster Toaster_toaster__bTabZ\">\n </div>\n </div>\n </div>\n <script id=\"__NEXT_DATA__\" type=\"application/json\">\n {\"props\":{\"pageProps\": {\"type\":\"Job\",\"sid\":\"a84cacbbcb07ec55cdbfd5fbe3d9f252d7f9cdd0\"...
[ 1 ]
[]
[]
[ "beautifulsoup", "html", "python", "web_scraping" ]
stackoverflow_0074395218_beautifulsoup_html_python_web_scraping.txt
Q: My android app made with kivy is crashing I created an app using kivy that works very well on pc, but after converting it into an apk file, it didn't work on my android device, the app was designed using kivy with all referenced file inside the same directory, when i was creating the apk file using google colab i...
My android app made with kivy is crashing
I created an app using kivy that works very well on pc, but after converting it into an apk file, it didn't work on my android device, the app was designed using kivy with all referenced file inside the same directory, when i was creating the apk file using google colab i upload all files independently because i don't...
[ "Make sure that following line of buildozer.spec is uncommented and have following extensions:\nsource.include_exts = py,png,jpg,kv,atlas,md\n" ]
[ 0 ]
[]
[]
[ "apk", "crash", "kivy", "logcat", "python" ]
stackoverflow_0074392419_apk_crash_kivy_logcat_python.txt
Q: django custom admin login page I have a custom auth mechanism for users and I want to use the same for django admin. All works fine for authenticated users but if an unauthenticated user opens the url /admin he is redirected to /admin/login with the std. login page for admin. I want to redirect to auth/sign-in or ...
django custom admin login page
I have a custom auth mechanism for users and I want to use the same for django admin. All works fine for authenticated users but if an unauthenticated user opens the url /admin he is redirected to /admin/login with the std. login page for admin. I want to redirect to auth/sign-in or block the page. urlpatterns = [ ...
[ "The urlpatterns are searched in order, using the first match, rather than overwitten by later patterns, so you might have better luck with:\nurlpatterns = [\n path('admin/login', SignInView.as_view(), name='admin/login'),\n path('admin/', admin.site.urls),\n ...\n\nDocu for the URL dispatcher for referenc...
[ 2 ]
[]
[]
[ "django", "django_urls", "python" ]
stackoverflow_0074392774_django_django_urls_python.txt
Q: How can I convert this [['1 0'], ['2 0'], ['3 1 2']] into an adjacency list in python I have a list of the lists that contain strings, like so : [['1 0'], ['2 0'], ['3 1 2']] How can I convert it to an adjacency list in Python please like this: (all ints) { 1: 0, 2:0, 3: 1,2 } My attempts so far have got...
How can I convert this [['1 0'], ['2 0'], ['3 1 2']] into an adjacency list in python
I have a list of the lists that contain strings, like so : [['1 0'], ['2 0'], ['3 1 2']] How can I convert it to an adjacency list in Python please like this: (all ints) { 1: 0, 2:0, 3: 1,2 } My attempts so far have gotten me to this: newlist = [] for word in linelist: word = word.split(",") newlist.a...
[ "You can convert it to a dict with something like this:\nadj_dict = {}\nfor inner_list in outer_list:\n values = [int(x) for x in inner_list[0].split()]\n adj_dict[values[0]] = values[1:]\n\n", "It kind of depends on the data types you want for the values in the dictionary, but this should get you most of t...
[ 1, 0, 0 ]
[]
[]
[ "adjacency_matrix", "dictionary", "graph", "python" ]
stackoverflow_0074395195_adjacency_matrix_dictionary_graph_python.txt
Q: How do I create a number of sympy symbols from a list? I have a list in the following form: ['C_k', 'c_f', 'm_1', 'T_1', 'T_m'] I wanna creat a sympy symbol for every "variable" in this list, which is possible with the following function: a,k,m_n=symbols('a k m_n') How would this work? The end goal is to do (Guass...
How do I create a number of sympy symbols from a list?
I have a list in the following form: ['C_k', 'c_f', 'm_1', 'T_1', 'T_m'] I wanna creat a sympy symbol for every "variable" in this list, which is possible with the following function: a,k,m_n=symbols('a k m_n') How would this work? The end goal is to do (Guassian-)error propagation, which requires me to evaluate a deri...
[ "Use the symbols function, like this:\ntokens = ['C_k', 'c_f', 'm_1', 'T_1', 'T_m']\nsymb = symbols(\" \".join(tokens))\nprint(symb)\n# out: (C_k, c_f, m_1, T_1, T_m)\n\n" ]
[ 0 ]
[]
[]
[ "data_science", "latex", "python", "sympy" ]
stackoverflow_0074395200_data_science_latex_python_sympy.txt
Q: Using Python to parse plain-text messages that use '/' and '//' as delimiters I am working on the way to transform or parse elements of a plain-text file that contains multiple records that look like the following: US/CIV/JOHN SMITH/-/-/Z/-/2018-03-25/BLUE/ 159/AZ/AUDI/2015// US/CTR/BILL STONE/5/TEXT/G/AU24/2021-0...
Using Python to parse plain-text messages that use '/' and '//' as delimiters
I am working on the way to transform or parse elements of a plain-text file that contains multiple records that look like the following: US/CIV/JOHN SMITH/-/-/Z/-/2018-03-25/BLUE/ 159/AZ/AUDI/2015// US/CTR/BILL STONE/5/TEXT/G/AU24/2021-06-18/ GREEN/174/CO/BENZ/2019// These records separate elements using a forward-slas...
[ "If you want to just get it into a list of lists so that it could populate a table or something of the like you could do something like the following:\nparsed = [x.split('/') for x in data.split('//')]\n", "You don't really specify what format you would like the output to be in, but here's some python code to get...
[ 0, 0 ]
[]
[]
[ "json", "parsing", "python" ]
stackoverflow_0074395149_json_parsing_python.txt
Q: vectorized computation of many matrix exponentials I have many 2-by-2 matrices, A, A.shape == (2, 2, 7324), and I have to compute the matrix exponential of all of those. Unfortunately, scipy.linalg.expm only accepts one matrix at a time such that I'd have to loop over the computations, import numpy import scipy.li...
vectorized computation of many matrix exponentials
I have many 2-by-2 matrices, A, A.shape == (2, 2, 7324), and I have to compute the matrix exponential of all of those. Unfortunately, scipy.linalg.expm only accepts one matrix at a time such that I'd have to loop over the computations, import numpy import scipy.linalg numpy.random.seed(0) A = numpy.random.rand(2, 2, 7...
[ "As of SciPy release 1.9.0 (released in July 28, 22), you can pass scipy.linalg.expm an array where the last two dimensions are square—that is, an array with shape (..., n, n)—and it will compute the matrix exponential\nin a vectorized fashion.\nThe documentation is here.\n", "From glancing over the code, https:/...
[ 1, 0, 0 ]
[]
[]
[ "python", "scipy" ]
stackoverflow_0060031702_python_scipy.txt
Q: local variable 'issue' referenced before assignment My main function for record in event["Records"]: payload = json.loads(record["body"]) if payload["action"] != "Create": continue issue_id = payload["documentId"]["id"] issue = client.get_issue(issue_id) data_i...
local variable 'issue' referenced before assignment
My main function for record in event["Records"]: payload = json.loads(record["body"]) if payload["action"] != "Create": continue issue_id = payload["documentId"]["id"] issue = client.get_issue(issue_id) data_id, main_id = parse_issue(client, issue) Error: local v...
[ "It should be ok just to define your variable at the higher scope so that all the functions can see it. Everything in python is based on how much it's indented. So if you put down a variable at the same indent level as the for loop and the call to the function, it will store the value outside of the for loop and be...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074395293_python.txt
Q: how to make list comparable with other lists i have this code: import csv from collections import Counter with open('C:\\Users\\ntonto\\Documents\\Currencies\\BTC-USD.csv', encoding='utf-8=sig') as csvfile: r = csv.DictReader(csvfile) count = 0 fsa = [] for row in r: count = count + 1 ...
how to make list comparable with other lists
i have this code: import csv from collections import Counter with open('C:\\Users\\ntonto\\Documents\\Currencies\\BTC-USD.csv', encoding='utf-8=sig') as csvfile: r = csv.DictReader(csvfile) count = 0 fsa = [] for row in r: count = count + 1 fsa.append(row['Open']) if count > 10:...
[ "Change\nfor members, count, in counter.items():\n print(list(members), count)\n\nto\nfor members, count, in counter.items():\n print([*members, count])\n\nThis will spread the tuple into the first list elements, and then use count as the next element.\n" ]
[ 1 ]
[]
[]
[ "compare", "list", "python" ]
stackoverflow_0074395329_compare_list_python.txt
Q: How to map header with data from ReadAllFromText/ReadFromText in Dataflow I would like to read a csv file in streaming Dataflow job and map each row into dict {"column1": "value"1} and upload it into BQ. As an entry point I am using ReadAllFromText so it returns just row by row, where first row is a header. How ca...
How to map header with data from ReadAllFromText/ReadFromText in Dataflow
I would like to read a csv file in streaming Dataflow job and map each row into dict {"column1": "value"1} and upload it into BQ. As an entry point I am using ReadAllFromText so it returns just row by row, where first row is a header. How can I map row[0] (header) to all next rows? I seems like a very basic task but I ...
[ "I share with you a class I written to read a CSV file in Beam in a Dict :\nimport codecs\nfrom _csv import QUOTE_ALL\nfrom typing import Iterable, Dict\n\nimport apache_beam as beam\nfrom apache_beam import PCollection\nfrom apache_beam.io import fileio\nfrom apache_beam.io.filesystem import CompressionTypes\nfrom...
[ 1, 1 ]
[]
[]
[ "apache_beam", "apache_beam_io", "google_bigquery", "google_cloud_dataflow", "python" ]
stackoverflow_0074387360_apache_beam_apache_beam_io_google_bigquery_google_cloud_dataflow_python.txt
Q: Why does the NoReverseMatch error pop up when trying to paginate my django website? I have a list of data from my models that I would like to paginate as it looks flooded on one singular page and it generally takes a longer time for the page to load. However, when I tried to use a paginating method, it doesn't see...
Why does the NoReverseMatch error pop up when trying to paginate my django website?
I have a list of data from my models that I would like to paginate as it looks flooded on one singular page and it generally takes a longer time for the page to load. However, when I tried to use a paginating method, it doesn't seem to work in my code. What I've already done for my code is: .../clubs/views.py class Clu...
[ "You are passing the next page number/prev page number as part of the {% url %} function which creates the path, however your URLS.py isn't expecting it as part of the URL path. eg, you don't have a urlpattern for listview/12/.\nFor a list view, by default next and prev pages numbers gets passed as part of the quer...
[ 0 ]
[]
[]
[ "django", "html", "python" ]
stackoverflow_0074390926_django_html_python.txt
Q: Conda: packages are already installed by pip but not shown in conda list I use pip install packages in a conda environment. pip install pygame Requirement already satisfied: pygame in ./anaconda3/lib/python3.6/site-packages (1.9.4) where the current directory is /Users/aptx4869. However, when I type conda list, t...
Conda: packages are already installed by pip but not shown in conda list
I use pip install packages in a conda environment. pip install pygame Requirement already satisfied: pygame in ./anaconda3/lib/python3.6/site-packages (1.9.4) where the current directory is /Users/aptx4869. However, when I type conda list, there is nothing in the current environment. What's wrong with it? Here's the d...
[ "The reason is simply because I didn't install python and pip in the dl environment, and conda implicitly uses python and pip in the root environment as I command pip install ...\n", "I guess that you installed the pygame package into the root environment when you run pip install pygame the first time. So make su...
[ 2, 0, 0, 0 ]
[]
[]
[ "conda", "pip", "python" ]
stackoverflow_0051710290_conda_pip_python.txt
Q: Create a dataframe with columns and their unique values in pandas I have tried looking for a way to create a dataframe of columns and their unique values. I know this has less use cases but would be a great way to get an initial idea of unique values. It would look something like this.... State County City Color...
Create a dataframe with columns and their unique values in pandas
I have tried looking for a way to create a dataframe of columns and their unique values. I know this has less use cases but would be a great way to get an initial idea of unique values. It would look something like this.... State County City Colorado Denver Denver Colorado El Paso Colorado Springs Colorado ...
[ "I would use mask and a lambda\ndf.mask(cond=df.apply(lambda x : x.duplicated(keep='first')), other='')\n\n State County City\n0 Colorado Denver Denver\n1 El Paso Colorado Springs\n2 Larimar Fort Collins\n3 Loveland\n\n", "R...
[ 2, 1, 0 ]
[]
[]
[ "pandas", "python", "unique" ]
stackoverflow_0074395260_pandas_python_unique.txt
Q: Selecting from dropdown menu with Playwright in Python using attributes With Playwright in Python I am trying to select from a variation dropdown on an Amazon product page -> https://www.amazon.de//dp/B08XWKDGL7 \<select name="dropdown_selected_size_name" autocomplete="off" data-a-touch-header="Größe" id="native_d...
Selecting from dropdown menu with Playwright in Python using attributes
With Playwright in Python I am trying to select from a variation dropdown on an Amazon product page -> https://www.amazon.de//dp/B08XWKDGL7 \<select name="dropdown_selected_size_name" autocomplete="off" data-a-touch-header="Größe" id="native_dropdown_selected_size_name" tabindex="0" data-action="a-dropdown-select" clas...
[ "In playwright, there are three alternatives to select dropdown element\n1. select by label\n\n2. select by index\n\n3. select by value\n\nYou can select dropdown element by visible text(label) or by value instead and select dropdow element by attribute is not supported in playwright even not in Selenium too.\nEx...
[ 1 ]
[]
[]
[ "playwright", "python", "web_scraping" ]
stackoverflow_0074394422_playwright_python_web_scraping.txt
Q: Unable to concatenate strings using + operator in python I have written the below python program. var = '28' express = "r'\b" + var + "\b'" print(express) I expected to get r'\b28\b' but I am getting r'28'. I don't understand why. Can someone please help me with it? Besides var is supposed to be a user input so I...
Unable to concatenate strings using + operator in python
I have written the below python program. var = '28' express = "r'\b" + var + "\b'" print(express) I expected to get r'\b28\b' but I am getting r'28'. I don't understand why. Can someone please help me with it? Besides var is supposed to be a user input so I need to know some way to print express correctly.
[ "\\b is the escape sequence for backspace. If you want literal \\b in your result, use a raw string to prevent the escape sequence from being processed.\nvar = '28'\nexpress = r\"r'\\b\" + var + r\"\\b'\"\nprint(express)\n\n" ]
[ 1 ]
[]
[]
[ "python", "string", "string_concatenation" ]
stackoverflow_0074395459_python_string_string_concatenation.txt
Q: how can I copy the bytes from numpy.save to stdout? I have some python that needs to send a pickled numpy array to stdout. If I try to numpy.save(sys.stdout.buffer, data, allow_pickle=False) I get the following error Traceback (most recent call last): File "/home/thoth/work/TandbergLabs/2022/iot-rendezvous/pic...
how can I copy the bytes from numpy.save to stdout?
I have some python that needs to send a pickled numpy array to stdout. If I try to numpy.save(sys.stdout.buffer, data, allow_pickle=False) I get the following error Traceback (most recent call last): File "/home/thoth/work/TandbergLabs/2022/iot-rendezvous/picture-server/src/main/resources/com/ericsson/duluthMadScie...
[ "you can write to io.BytesIO buffer then write it to stdout or even transfer it over network.\nimport numpy as np\nimport io\nimport sys\nbuffer = io.BytesIO()\narr = np.array([1, 2, 3])\nnp.save(buffer, arr, allow_pickle=False)\nbytes_value = buffer.getvalue()\nprint(bytes_value)\nsys.stdout.buffer.write(bytes_val...
[ 2, 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074395303_numpy_python.txt
Q: Python: AttributeError: 'Series' object has no attribute 'isdir' I am getting the error AttributeError: 'Series' object has no attribute 'isdir' I am trying to loop through my test directory and check if values in my dataframe exist in there and label it with a column named status. pl_dest is a dataframe like so: ...
Python: AttributeError: 'Series' object has no attribute 'isdir'
I am getting the error AttributeError: 'Series' object has no attribute 'isdir' I am trying to loop through my test directory and check if values in my dataframe exist in there and label it with a column named status. pl_dest is a dataframe like so: test = (r'O:\Stack\Over\Flow') for idx in pl_dest.iterrows(): ...
[ "pl_dest['Folder_Name_to_create'] is a pandas.Series object and doesn't have a isdir method.\nInstead of iterating the rows, you could use .apply to apply a function to each value in the column. The resulting Series would be True/False for existence. You could modify that to \"exists\" and \"\" later if you'd like....
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074395529_python.txt
Q: problem with iterating over non existing indexes python I have extracted data from woocommerce webshop with api. Part of the top structure is like this: {'id': 12345, 'attributes': [{'id': 1, 'name': 'kleur', 'position': 0, 'visible': True, 'variation': False, 'options': ['blauw...
problem with iterating over non existing indexes python
I have extracted data from woocommerce webshop with api. Part of the top structure is like this: {'id': 12345, 'attributes': [{'id': 1, 'name': 'kleur', 'position': 0, 'visible': True, 'variation': False, 'options': ['blauw']}, {'id': 2, 'name': 'maat', 'position'...
[ "Loop through the attributes until you find the one you want, and use its name.\nall_webshop_skus = [] \nfor item in all_data:\n for attr in item['attributes']:\n if attr['id'] == 2:\n name = attr['name']\n break\n else: # default if not found\n name = ''\n\n product =...
[ 1 ]
[]
[]
[ "loops", "python", "woocommerce_rest_api" ]
stackoverflow_0074395589_loops_python_woocommerce_rest_api.txt
Q: How to set custom error messages for argparse python module I want to change default message for errors caused by typing wrong argument value or typing argument without any value. I have code test.py: import argparse parser = argparse.ArgumentParser() parser.add_argument('-n', '--number', ...
How to set custom error messages for argparse python module
I want to change default message for errors caused by typing wrong argument value or typing argument without any value. I have code test.py: import argparse parser = argparse.ArgumentParser() parser.add_argument('-n', '--number', type=int, help='Specify a n...
[ "To do what you want, you can override the error method of the ArgumentParser class, you can see the argparse source code at https://github.com/python/cpython/blob/3.10/Lib/argparse.py\n#instead of doing this\nparser = argparser.ArgumentParser()\n\n#do this\n\nclass CustomArgumentParser(argparse.ArgumentParser)\n ...
[ 1 ]
[]
[]
[ "argparse", "error_handling", "python" ]
stackoverflow_0071363516_argparse_error_handling_python.txt
Q: ValueError: x and y must have same first dimension, but have different shapes I am currently trying to fit some measurement data into three polynomial functions of the degrees 1, 2, and 3. My code is as follows: ylist = [81, 50, 35, 27, 26, 60, 106, 189, 318, 520] y = np.array(ylist) t = np.linspace(-0.9,0.9,10) ...
ValueError: x and y must have same first dimension, but have different shapes
I am currently trying to fit some measurement data into three polynomial functions of the degrees 1, 2, and 3. My code is as follows: ylist = [81, 50, 35, 27, 26, 60, 106, 189, 318, 520] y = np.array(ylist) t = np.linspace(-0.9,0.9,10) p1 = np.polyfit(t,y,1) p2 = np.polyfit(t,y,2) p3 = np.polyfit(t,y,3) pp1 = np.poly...
[ "pp1 is a poly1d object. So, you need to call it for each of your t values to get the corresponding values of the fit. Something like\nfit_vals = [pp1(curr_t) for curr_t in t]\nplt.plot(t, fit_vals)\n\nShould work\n" ]
[ 0 ]
[]
[]
[ "model_fitting", "polynomials", "python", "valueerror" ]
stackoverflow_0074395434_model_fitting_polynomials_python_valueerror.txt
Q: Merge with multiple columns and refill NAN values in Python I have df1 that looks like this: STATE YEAR EVENT_TYPE DAMAGE ALABAMA 1962 Tornado 27 ALABAMA 1962 Flood 7 ALABAMA 1963 Thunderstorm 12 ... and df2 that looks like this: STATE ...
Merge with multiple columns and refill NAN values in Python
I have df1 that looks like this: STATE YEAR EVENT_TYPE DAMAGE ALABAMA 1962 Tornado 27 ALABAMA 1962 Flood 7 ALABAMA 1963 Thunderstorm 12 ... and df2 that looks like this: STATE YEAR TORNADO THUNDERSTORM FLOOD ALABAMA ...
[ "Concat two dataframes.\npd.concat([df1, df2], axis=0)\n\nConcat two dataframes and replace nan with 0, or whatever value you desire.\npd.concat([df1, df2], axis=0).df.fillna(0)\n\n", "merge the pivoted df1:\ncols = ['STATE', 'YEAR']\n\nout = df2[cols].merge(df1.pivot(index=cols, columns='EVENT_TYPE', values='DAM...
[ 1, 0, 0 ]
[]
[]
[ "merge", "pandas", "python", "replace" ]
stackoverflow_0074395626_merge_pandas_python_replace.txt
Q: How to call a function within another function when they both have different number of parameters? I have written this function: def sort2(self, start, end): if (start == None or start == end or start == end.next): return # split list and partition recurse pivot_prev = self.paritionLast(start,...
How to call a function within another function when they both have different number of parameters?
I have written this function: def sort2(self, start, end): if (start == None or start == end or start == end.next): return # split list and partition recurse pivot_prev = self.paritionLast(start, end) self.sort(start, pivot_prev) if (pivot_prev != None and pivot_prev == start): sel...
[ "You can certainly define that function as a local function inside the method that has the signature that is needed. The local function will then not take a self parameter:\ndef sort(self):\n\n def sort2(start, end):\n if (start == None or start == end or start == end.next):\n return\n \n ...
[ 0 ]
[]
[]
[ "function", "python", "quicksort", "recursion", "self" ]
stackoverflow_0074395184_function_python_quicksort_recursion_self.txt
Q: Game repeating output several times I'm making a small scrambled word game and am trying to implement a 'rescramble' feature. So far, if the user chooses to rescramble the word, I call the game function and place in the same input that was originally provided. The second iteration of the function will scramble the...
Game repeating output several times
I'm making a small scrambled word game and am trying to implement a 'rescramble' feature. So far, if the user chooses to rescramble the word, I call the game function and place in the same input that was originally provided. The second iteration of the function will scramble the word into a unique form and the game con...
[ "This does your looping correctly.\ndef game(n,d):\n while True:\n scrambled = shuffler(n)\n guess = input(f\"{scrambled} 're' to rescramble: \")\n if guess != 're':\n break\n if guess == n:\n print(\"Correct\")\n else:\n print(\"Incorrect\")\n print(n,\":...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074395742_python.txt
Q: After conda update, python kernel crashes when matplotlib is used I have create this simple env with conda: conda create -n test python=3.8.5 pandas scipy numpy matplotlib seaborn jupyterlab The following code in jupyter lab crashes the kernel : import matplotlib.pyplot as plt plt.subplot() I don't face the pro...
After conda update, python kernel crashes when matplotlib is used
I have create this simple env with conda: conda create -n test python=3.8.5 pandas scipy numpy matplotlib seaborn jupyterlab The following code in jupyter lab crashes the kernel : import matplotlib.pyplot as plt plt.subplot() I don't face the problem on Linux. The problem is when I try on Windows 10. There are no er...
[ "Update 2021-11-06\n\nThe default pkgs/main channel for conda has reverted to using freetype 2.10.4 for Windows, per main / packages / freetype.\nIf you are still experiencing the issue, use conda list freetype to check the version: freetype != 2.11.0\n\nIf it is 2.11.0, then change the version per the solution, or...
[ 71, 2, 2, 0 ]
[]
[]
[ "conda", "freetype", "matplotlib", "python", "windows" ]
stackoverflow_0069786885_conda_freetype_matplotlib_python_windows.txt
Q: How do I change position in loop once the loop is completed? finalList = [] list = [] c = 0 d = 0 for item in house_numbers: list.append(item) finalList.append(list) list = [] while population[c] != d: finalList[0].append(age[d]) d += 1 I am appending 2 different lists to make a 2d list. house...
How do I change position in loop once the loop is completed?
finalList = [] list = [] c = 0 d = 0 for item in house_numbers: list.append(item) finalList.append(list) list = [] while population[c] != d: finalList[0].append(age[d]) d += 1 I am appending 2 different lists to make a 2d list. house_numbers is a list that has the house numbers. example: Enter the ...
[ "Use a single loop that loops over the house_numbers and population lists together. Then use a nested loop that gets all the ages for that house.\nfinal_list = []\nfor house, num_people in zip(house_numbers, population):\n row = [house]\n for p in range(1, num_people+1):\n age = int(input(f'Enter the a...
[ 2 ]
[]
[]
[ "list", "loops", "position", "python", "while_loop" ]
stackoverflow_0074395689_list_loops_position_python_while_loop.txt