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: solve it but still having error somewhere A cashier distributes change using the maximum number of five-dollar bills, followed by one-dollar bills. Write a single statement that assigns num_ones with the number of distributed one-dollar bills given amount_to_change. Hint: Use %. Sample output with input: 19 Change...
solve it but still having error somewhere
A cashier distributes change using the maximum number of five-dollar bills, followed by one-dollar bills. Write a single statement that assigns num_ones with the number of distributed one-dollar bills given amount_to_change. Hint: Use %. Sample output with input: 19 Change for $ 19 3 five dollar bill(s) and 4 one dolla...
[ "You may not use a hard-coded 19 , but rather amount_to_change, both 5 and 1 dollar bills\namount_to_change = int(input(\"Enter an amount\"))\n\nnum_fives = amount_to_change // 5\nnum_ones = amount_to_change % 5\n\nprint('Change for $', amount_to_change)\nprint(num_fives, 'five dollar bill(s) and', num_ones, 'one d...
[ 2, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0068246572_python_python_3.x.txt
Q: "TypeError: () takes 1 positional argument but 2 were given" using reduce() I want to return sum of square of numbers passed in list. from functools import reduce def square_sum(numbers): return reduce(lambda x: x ** 2, numbers) print(square_sum([1, 2, 2])) However i am getting the error: TypeError: <lambda...
"TypeError: () takes 1 positional argument but 2 were given" using reduce()
I want to return sum of square of numbers passed in list. from functools import reduce def square_sum(numbers): return reduce(lambda x: x ** 2, numbers) print(square_sum([1, 2, 2])) However i am getting the error: TypeError: <lambda>() takes 1 positional argument but 2 were given. I couldn't understand reason be...
[ "Here's how you might define sum if it didn't exist:\nfrom functools import reduce\n\ndef sum(it):\n return reduce(lambda acc, val: acc + val, it)\n\nOr:\nfrom functools import reduce\nimport operator\n\ndef sum(it):\n return reduce(operator.add, it)\n\nfunctools.reduce reduces the values produced by an itera...
[ 0, 0 ]
[]
[]
[ "lambda", "python" ]
stackoverflow_0073577319_lambda_python.txt
Q: How to debug my Python program, which sums positive numbers based on their evenness I'm trying to write program that asking the user for positive numbers, if it is an odd number, the software sums all of the odd digits in the number, same for even numbers. After that the software asking non stop for numbers and do...
How to debug my Python program, which sums positive numbers based on their evenness
I'm trying to write program that asking the user for positive numbers, if it is an odd number, the software sums all of the odd digits in the number, same for even numbers. After that the software asking non stop for numbers and does the same thing as before, till the user type 0/negative number. After that the softwar...
[ "Bug:\nif user enter a negative number it will continue the loop and print the last entered number\nbecause the program doesn't check for negative numbers\nFix:\nI have added a condition if N <= 0:\nreturn maX\nthis will return the last entered positive number\nBug:\nsum_Digits(num)\nI have removed this line becaus...
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074321983_python_python_3.x.txt
Q: Django Python rest framework, No 'Access-Control-Allow-Origin' header is present on the requested resource in chrome, works in firefox I have researched and read quite a few Stackoverflow posts on the same issue. None have resolved my issue. My problem is that I am getting the "...No 'Access-Control-Allow-Origin'...
Django Python rest framework, No 'Access-Control-Allow-Origin' header is present on the requested resource in chrome, works in firefox
I have researched and read quite a few Stackoverflow posts on the same issue. None have resolved my issue. My problem is that I am getting the "...No 'Access-Control-Allow-Origin' header is present on the requested resource..." error in my console. I am using: Chrome Version 57.0.2987.133 Firefox Version 52.0.2 Python...
[ "Install the cors-headers package with\npip install django-cors-headers\n\nAdds to your installed apps\nINSTALLED_APPS = [\n ...\n 'corsheaders',\n ...\n]\n\nAdd on your MIDDLEWARE \nremember to add as being the first in the list\nMIDDLEWARE = [ \n 'corsheaders.middleware.CorsMiddleware',\n 'django....
[ 88, 54, 7, 2, 1, 1, 0, 0, 0, 0 ]
[ "see if your url is correct.\nFor me it works by doing following things:\n\ninstall django cors headers package\n# django-cors-headers\nAdd CORS_ORIGIN_ALLOW_ALL = True in settings.py\nAdd this two line in start at MIDDLEWARE tag\ncorsheaders.middleware.CorsMiddleware\ndjango.middleware.common.CommonMiddleware\nadd...
[ -1, -1, -3 ]
[ "django", "django_cors_headers", "django_rest_framework", "google_chrome", "python" ]
stackoverflow_0043357687_django_django_cors_headers_django_rest_framework_google_chrome_python.txt
Q: Integration with different methods How can i define my variable method in my function so that my integrate function can calculate the same integral via a chosen method ? Maybe i have to define an alias for the different functions? import argparse def dummy_function(x_value): return 4/(1+x_value**2) def int...
Integration with different methods
How can i define my variable method in my function so that my integrate function can calculate the same integral via a chosen method ? Maybe i have to define an alias for the different functions? import argparse def dummy_function(x_value): return 4/(1+x_value**2) def integrate(method,function,integration_range...
[ "Something like this should work:\ndef integrate(method,function,integration_range,n_slices): \n methods = {\n 'riemann': riemann,\n 'trapezoid': trapezoid,\n 'simpson': simpson\n } \n return methods[method](function, integration_range, n_slices)\n\n\nYou could simplify this quite ...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074450360_python.txt
Q: Type annotation in a filter() function over a custom generator could you help me understand why I am getting the TypeError: 'type' object is not subscriptable error with the code below? Maybe I'm getting this wrong, but as I understood the Color type annotation in the filter() function is saying that the function ...
Type annotation in a filter() function over a custom generator
could you help me understand why I am getting the TypeError: 'type' object is not subscriptable error with the code below? Maybe I'm getting this wrong, but as I understood the Color type annotation in the filter() function is saying that the function will result in an Iterable of Color , which is exactly what I want....
[ "The issue is that generics aren't a language-level addition, but a library one. Specifying the generic type parameters actually employs the same [] operator you use for item access in collections, except it is defined on the metaclass. For this reason the generics syntax originally only worked with specific classe...
[ 1 ]
[]
[]
[ "generator", "iterator", "python", "types" ]
stackoverflow_0074450786_generator_iterator_python_types.txt
Q: How can I plot this piecewise function in python? Piecewise function I don't know how to plot it A: Try to use matplotlib's pyplot package. It has very user-friendly functions for plotting. This is my approach to plotting this piecewise function: import matplotlib.pyplot as plt import numpy as np # boundaries x...
How can I plot this piecewise function in python?
Piecewise function I don't know how to plot it
[ "Try to use matplotlib's pyplot package. It has very user-friendly functions for plotting. This is my approach to plotting this piecewise function:\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# boundaries\nxmin = -3\nxmax = 3\n\nN = 1001 # resolution of points between [xmin, xmax]\n\n# create x axis and...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074448891_python.txt
Q: Counts of integers seen in file aren't being updated I made a little script that is supposed to iterate over a text file and read the numbers. Once a number is read, another variable which measures the frequency of each number is supposed to get updated so that the frequency of the number increases by 1. I've test...
Counts of integers seen in file aren't being updated
I made a little script that is supposed to iterate over a text file and read the numbers. Once a number is read, another variable which measures the frequency of each number is supposed to get updated so that the frequency of the number increases by 1. I've tested every part of this program on its own and they work, ho...
[ "readline returns a string. Even if this string only contains digits, it is not equal to a number like 0. And the string actually also contains a newline character.\nYou need to convert the string to an integer. This will raise an exception if the line does not contain just an integer (plus optional surrounding whi...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074451049_python.txt
Q: User is not authenticated in Django? It shows errors I am creating a website so I finshed register page in login page, every details are correct but that is showing please verify your details I mean the else part also I put in a print statement after username and password same details are printing when I typed but...
User is not authenticated in Django? It shows errors
I am creating a website so I finshed register page in login page, every details are correct but that is showing please verify your details I mean the else part also I put in a print statement after username and password same details are printing when I typed but not access login. views.py def sign_in(request): ...
[ "authenticate() also requires request as an argument so it should be:\nuser = authenticate(request,username=username,password=password)\n\nYour view for registering users should be like this:\ndef register(request):\nif request.method == \"POST\":\n username=request.POST['username']\n password=request.POST['p...
[ 3, 1 ]
[]
[]
[ "django", "django_models", "django_urls", "django_views", "python" ]
stackoverflow_0074449864_django_django_models_django_urls_django_views_python.txt
Q: Merging 2 dataframe using update index but after running below code, index column is missing from dataframe1 I've a 2 dataframe for which I want to update dataframe1 specific column "var1" with dataframe2 column "var1" based on unique column "respid". This is just an example : There are more column in df1 along w...
Merging 2 dataframe using update index but after running below code, index column is missing from dataframe1
I've a 2 dataframe for which I want to update dataframe1 specific column "var1" with dataframe2 column "var1" based on unique column "respid". This is just an example : There are more column in df1 along with above shown example. However dataframe2 is the same as shown. I've used below code for same and its working ...
[ "Try this way\ndf = pd.merge(df1,df2,on = ['respid'],how ='inner')\ndfs = pd.merge(df,df1,on = ['respid'],how ='outer')\n\ndfs =dfs.drop(columns=['var1_x','var1'])\ndfs = dfs.fillna('')\ndfs.columns = ['respid', 'var1']\n\nwhich gives\n respid var1\n0 27217 screened\n1 27211 screened\n2 27214 scree...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074450791_pandas_python.txt
Q: stuff inside frame in .grid() method doesn't seem to wanna work trying to use the .grid method to make a school assignment and stuff i try to have under a frame seems to ignore the frame's position, is there a way to have it stay inside the frame? or in summary can stuff be put inside frames and be placed alongsid...
stuff inside frame in .grid() method doesn't seem to wanna work
trying to use the .grid method to make a school assignment and stuff i try to have under a frame seems to ignore the frame's position, is there a way to have it stay inside the frame? or in summary can stuff be put inside frames and be placed alongside the frame? used code: from tkinter import * import random as rn hl...
[ "This what is my bot had said :)) lol\nfrom tkinter import *\nimport random as rn\n#This is fucking BUG\nhlavni=Tk()\nhlavni.geometry('500x400')\nhrac_f=Frame(hlavni,width=100,height=100,bg=\"red\")\nhrac_f.grid(row=0,column=1,padx=20,pady=20)\ntest1=Label(hrac_f,text=\"why\").grid(row=0,column=0,padx=20,pady=20)\n...
[ 1 ]
[]
[]
[ "python", "python_3.x", "tkinter" ]
stackoverflow_0074450953_python_python_3.x_tkinter.txt
Q: rename AWS glue output file as .json/.parquet I have below code which writes data into AWS s3 location using Glue job, but at the end it is saving in part file, but my requirement is to save filename as filename.json or filename.parquet s3_loc = "s3a://s3_location/path" ##this is the default part of the glue scr...
rename AWS glue output file as .json/.parquet
I have below code which writes data into AWS s3 location using Glue job, but at the end it is saving in part file, but my requirement is to save filename as filename.json or filename.parquet s3_loc = "s3a://s3_location/path" ##this is the default part of the glue script job = Job(glueContext) job.init(args['JOB_NAME'...
[ "This is unfortunately not possible. Glue is using Spark under the hood which assigns those names to your files.\nThe only thing you can do is to rename the files after writing.\n", "So as direct saving file with extension like .json / .parquet is not possible in Glue job hence I tried renaming file name and belo...
[ 0, 0 ]
[]
[]
[ "aws_glue", "file_format", "python" ]
stackoverflow_0074448371_aws_glue_file_format_python.txt
Q: DEPRECATION Error : 'wheel' package is not installed We are getting following deprecation error while trying to deploy python code. We are using python 3.7.12. We have tried to install wheel package as the part of deployment with no luck. Do we need to mention any specific version of wheel -- Would you be able to ...
DEPRECATION Error : 'wheel' package is not installed
We are getting following deprecation error while trying to deploy python code. We are using python 3.7.12. We have tried to install wheel package as the part of deployment with no luck. Do we need to mention any specific version of wheel -- Would you be able to put some lights? 2022-11-14T19:34:39.7229174Z ##[error]Bas...
[ "We have added a flag --use-pep517 with the installation command which solved the issue with version. So final script to run requirement.txt where we keep all our packages is provided below.\npip install -r requirements.txt --use-pep517\n\n" ]
[ 1 ]
[]
[]
[ "deprecation_warning", "python", "python_3.7", "python_wheel" ]
stackoverflow_0074436681_deprecation_warning_python_python_3.7_python_wheel.txt
Q: I want to make 10/2 an int not a float 10/2 is 5 but pyhton says its 5.0 I want it to be 5 while making 11/2 5.5 which still makes it a float so basically thing that wouldnt be a float should be int but things like 4.3 should stay a float ` user_input = 10 prime_verification = user_input / 2 if isinstance(prime_...
I want to make 10/2 an int not a float
10/2 is 5 but pyhton says its 5.0 I want it to be 5 while making 11/2 5.5 which still makes it a float so basically thing that wouldnt be a float should be int but things like 4.3 should stay a float ` user_input = 10 prime_verification = user_input / 2 if isinstance(prime_verification, int): print(user_input) ...
[ "The previous comment is correct using // will give an int\nnumber = 10 // 2\nprint(number)\nprint(isinstance(number, int))\n\nOutput:\n5\nTrue\n\n", "You don't want to use / or //. If you want to know if n is divisible by 2, 3, etc, use % to check the remainder:\nuser_input = 10\n\nprime_verification = user_inpu...
[ 0, 0 ]
[ "Use the // Operator. This coverts your variable into an int\nuser_input = 10\nprime_verification = user_input // 2\n\nif isinstance(prime_verification, int):\n print(user_input)\n\n", "The // operator performs division and converts to integer. Try this:\nuser_input = 11\ndivisor = 2\n\nprime_verification = us...
[ -1, -1 ]
[ "division", "python" ]
stackoverflow_0074450891_division_python.txt
Q: Looping through json.loads(response.text) with Python i'm learning and would appreciate any help in this code. The issue is trying to print the values in the data that are contained in one line of the JSON using Python. import json import requests data = json.loads(response.text) print(len(data)) #showing correc...
Looping through json.loads(response.text) with Python
i'm learning and would appreciate any help in this code. The issue is trying to print the values in the data that are contained in one line of the JSON using Python. import json import requests data = json.loads(response.text) print(len(data)) #showing correct value #where i'm going wrong below obviously this will p...
[ "Presuming data is a list of dictionaries, where each dictionary contains a full_name key:\nfor item in data:\n print(item['full_name'])\n\nThis code sample from your post makes no sense:\nfor item in data:\nprint(data[0]['full_name'])\nprint(data[1]['full_name'])\n\nFirstly it's a syntax error because there is ...
[ 0, 0 ]
[]
[]
[ "arrays", "json", "python" ]
stackoverflow_0074451180_arrays_json_python.txt
Q: How to keep a cumulative count of changes across row elements, ignoring NaNs, and creating a separate column with the results I have a data frame that looks like this: Identification Date (day/month/year) X Y 123 01/01/2022 NaN abc 123 02/01/2022 200 acb 123 03/01/2022 200 ary 124 01/01/2022 200 abc 124 02/0...
How to keep a cumulative count of changes across row elements, ignoring NaNs, and creating a separate column with the results
I have a data frame that looks like this: Identification Date (day/month/year) X Y 123 01/01/2022 NaN abc 123 02/01/2022 200 acb 123 03/01/2022 200 ary 124 01/01/2022 200 abc 124 02/01/2022 NaN abc 124 03/01/2022 NaN NaN I am trying to create two separate 'change' columns, one for x and y separate...
[ "You can use a classical comparison with the next item (obtained with groupby.shift) combined with a groupby.cumsum, however a NaN compared with another NaN yields False. To overcome this, we can first fillna with an object that is not part of the dataset. Here I chose object, it could be -1 if your data is strictl...
[ 3 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074450526_pandas_python.txt
Q: Rearranging a list to get the 2nd column entries as rows I have a list associated to strings as follows; A string1^description1`string2^description2`string3^description3 B string4^description4 C string1^description1`string5^description5`string3^description3 D . E string6^description6`string1^description1...
Rearranging a list to get the 2nd column entries as rows
I have a list associated to strings as follows; A string1^description1`string2^description2`string3^description3 B string4^description4 C string1^description1`string5^description5`string3^description3 D . E string6^description6`string1^description1 F string7^description7 G string1^description1`string4^des...
[ "from collections import defaultdict\ndata = '''A string1^description1`string2^description2`string3^description3\nB string4^description4\nC string1^description1`string5^description5`string3^description3\nD .\nE string6^description6`string1^description1\nF string7^description7\nG string1^description1`s...
[ 2, 2, 1 ]
[]
[]
[ "awk", "perl", "python", "r" ]
stackoverflow_0074449796_awk_perl_python_r.txt
Q: Converting a list of triplets (row, column, value) to matrix as pandas df My question is similar to this one, but still different. I have a list of triplets like the following, representing rows and columns of a matrix with their cell value: a = [("g1","g2",7),("g1","g3",5)] The matrix is symmetrical, so the ele...
Converting a list of triplets (row, column, value) to matrix as pandas df
My question is similar to this one, but still different. I have a list of triplets like the following, representing rows and columns of a matrix with their cell value: a = [("g1","g2",7),("g1","g3",5)] The matrix is symmetrical, so the elements can be provided in any order - meaning that ("g1","g2",7) would imply ("g...
[ "Maybe not the most elegant of all solution, but it does the job.\nFor your list, identify all the \"tags\" you have (e.g., g1,g2,....gn).\nimport numpy as np\nimport pandas as pd\na = ((\"g1\",\"g2\",7),(\"g1\",\"g3\",5))\ntags = []\nfor t1, t2, _ in a:\n tags += [t1, t2]\ntags = index = columns = sorted(list(...
[ 0, 0 ]
[]
[]
[ "arrays", "pandas", "python", "sparse_matrix" ]
stackoverflow_0074449630_arrays_pandas_python_sparse_matrix.txt
Q: Pandas regex : Split String column into multiple integer columns I'm completely new to regex and i'm facing this challenge that is taking me hours to solve. I have the following dataframe with a string column "Dimensions": df Dimensions 0 "Width:2 cm" 1 "Diameter: 1....
Pandas regex : Split String column into multiple integer columns
I'm completely new to regex and i'm facing this challenge that is taking me hours to solve. I have the following dataframe with a string column "Dimensions": df Dimensions 0 "Width:2 cm" 1 "Diameter: 1.2 cm, Height: 10 cm" 2 "Diameter: 3.4cm, Volume: 10cm" I'm loo...
[ "Try:\nx = df[\"Dimensions\"].str.extractall(r'([^\\s\"]+)\\s*:\\s*(\\d+\\.?\\d*)').droplevel(1)\nx = x.pivot(columns=0, values=1)\nx.columns.name = None\nprint(x)\n\nPrints:\n Diameter Height Volume Width\n0 NaN NaN NaN 2\n1 1.2 10 NaN NaN\n2 3.4 NaN 10 NaN\n\n" ]
[ 4 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074451234_pandas_python.txt
Q: Cloud Run: Why does python flask return 400 Bad request? But locally everything is fine I have a simple flask application. And I need to run it on Cloud Run with enabled option "Manage authorized users with Cloud IAM." app.py from flask import Flask api_app = Flask(__name__) endpoints.py from app import api_app ...
Cloud Run: Why does python flask return 400 Bad request? But locally everything is fine
I have a simple flask application. And I need to run it on Cloud Run with enabled option "Manage authorized users with Cloud IAM." app.py from flask import Flask api_app = Flask(__name__) endpoints.py from app import api_app @api_app.route("/create", methods=["POST"]) def api_create(): # logic main.py from app ...
[ "So I did some testing, and the only thing I did was remove the port binding from the Dockerfile CMD exec gunicorn and from the main.py. Note that the dundermain thingy is not needed as gunicorn takes care of that.\nAfter that it worked as expected.\nNote that I did not set it up as a private endpoint as I was to l...
[ 1 ]
[]
[]
[ "flask", "google_cloud_platform", "google_cloud_run", "python" ]
stackoverflow_0074450399_flask_google_cloud_platform_google_cloud_run_python.txt
Q: How to allow dropdowns in the sidebar navigation TOC of the Furo Sphinx theme? I want to allow users to have dropdown menus (with a little arrow) in the TOC tree that is in the navigation sidebar in the Furo theme. I saw that some themes like book-theme allow for this by specifying a theme option, but I am current...
How to allow dropdowns in the sidebar navigation TOC of the Furo Sphinx theme?
I want to allow users to have dropdown menus (with a little arrow) in the TOC tree that is in the navigation sidebar in the Furo theme. I saw that some themes like book-theme allow for this by specifying a theme option, but I am currently puzzled as to how this can be done for the Furo theme. I tried looking into wheth...
[ "I ran into the same issue with adding a dropdown in the sidebar using furo. Here is what I did:\nI added the following extensions in my conf.py:\nmyst_enable_extensions = [\n\"html_image\",\n\"html_admonition\",\n\"colon_fence\",\n\"sphinx.ext.autodoc\",\n\"sphinx.ext.extlinks\",\n\"sphinx.ext.intersphinx\",\n\"sp...
[ 0 ]
[]
[]
[ "python", "python_sphinx" ]
stackoverflow_0074242882_python_python_sphinx.txt
Q: Python Error: "The JSON object must be str, bytes or bytearray, not NoneType" I am trying to translate a .srt subtitle file with python and googleTranslate module. I can't because I get this error: TypeError: the JSON object must be str, bytes or bytearray, not NoneType This is my code: from googletrans import Tra...
Python Error: "The JSON object must be str, bytes or bytearray, not NoneType"
I am trying to translate a .srt subtitle file with python and googleTranslate module. I can't because I get this error: TypeError: the JSON object must be str, bytes or bytearray, not NoneType This is my code: from googletrans import Translator import glob import subprocess import os import json f = open('/Users/agus...
[ "There's nothing wrong with your code. It's an issue with the googletrans Python package. You can check more about this issue: https://github.com/ssut/py-googletrans/issues/354\ngoogletrans package was updated almost 2 years ago. I would suggest you to use some other translation package that's up to date with lates...
[ 0 ]
[]
[]
[ "google_translate", "google_translation_api", "json", "python" ]
stackoverflow_0074451160_google_translate_google_translation_api_json_python.txt
Q: Count how many times an ip has accessed a url I can print the ip and url from a massive log file, but I need to list how many times an ip has visited that url. I have done some research about throwing the log in a database, but I specifically need to do all of this in Python. any help is very appreciated. My Code ...
Count how many times an ip has accessed a url
I can print the ip and url from a massive log file, but I need to list how many times an ip has visited that url. I have done some research about throwing the log in a database, but I specifically need to do all of this in Python. any help is very appreciated. My Code so far: #!/usr/bin/python3 count = 0 log = open("ac...
[ "I hope I've understood your question right:\ntext = \"\"\"\\\n66.177.237.17 - - [18/Oct/2020:03:06:07 -0400] \"GET /webcam/1/latest.jpeg HTTP/2.0\" 304 0 \"-\" \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36\" \"-\"\n158.136.64.65 - - [18/Oct/202...
[ 0, 0 ]
[]
[]
[ "parsing", "python", "ubuntu" ]
stackoverflow_0074451296_parsing_python_ubuntu.txt
Q: modify a text file with values from a dictionary I have a text file as follows: myfile.txt [items] colors = red, purple, orange, blue [eat] food = burgers, pizza, hotdogs [furry] animals = birds, dogs, cats I have a dictionary: my_dict = {'colors':'green, black','animals':'donkey, tigers'} I want to open the fi...
modify a text file with values from a dictionary
I have a text file as follows: myfile.txt [items] colors = red, purple, orange, blue [eat] food = burgers, pizza, hotdogs [furry] animals = birds, dogs, cats I have a dictionary: my_dict = {'colors':'green, black','animals':'donkey, tigers'} I want to open the file myfile.txt and search for the keys inside the file ...
[ "There's no need to create a dictionary from the file. Just replace the lines that match what's in your new dictionary.\nmy_dict = {'colors': 'green, black', 'animals': 'donkey, tigers'}\n\nwith open('myfile.txt', 'r') as file:\n filedata = file.read()\n\n# Now split the rows on newline\nlines = filedata.split('...
[ 2 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074451368_python_python_3.x.txt
Q: How to detect method overloading in subclasses in python? I have a class that is a super-class to many other classes. I would like to know (in the __init__() of my super-class) if the subclass has overridden a specific method. I tried to accomplish this with a class method, but the results were wrong: class Super:...
How to detect method overloading in subclasses in python?
I have a class that is a super-class to many other classes. I would like to know (in the __init__() of my super-class) if the subclass has overridden a specific method. I tried to accomplish this with a class method, but the results were wrong: class Super: def __init__(self): if self.method == Super.method: ...
[ "If you want to check for an overridden instance method in Python 3, you can do this using the type of self:\nclass Base:\n def __init__(self):\n if type(self).method == Base.method:\n print('same')\n else:\n print('different')\n\n def method(self):\n print('Hello fr...
[ 18, 17, 16, 8, 4, 3, 2, 2, 0, 0 ]
[]
[]
[ "abstract_class", "class", "overriding", "python" ]
stackoverflow_0009436681_abstract_class_class_overriding_python.txt
Q: Is there a way to find and modify the color of a point in a .ply file using python? i'm trying to modify the color of a set of points in a .ply file using python, can u know some method to do it? Thank you I have searched some examples on internet but i haven't found anything A: There is a Python module https://...
Is there a way to find and modify the color of a point in a .ply file using python?
i'm trying to modify the color of a set of points in a .ply file using python, can u know some method to do it? Thank you I have searched some examples on internet but i haven't found anything
[ "There is a Python module https://github.com/dranjan/python-plyfile https://pypi.org/project/plyfile/#files which you can install using\npip install plyfile \n\nBelow a Python script demonstrating how to change the color of a face:\nfrom plyfile import PlyData, PlyElement\nplydata = PlyData.read('tet.ply')\n# or\n#...
[ 0, 0 ]
[]
[]
[ "pcl", "ply_file_format", "point_cloud_library", "python" ]
stackoverflow_0073659218_pcl_ply_file_format_point_cloud_library_python.txt
Q: Python : Calculating probability of a dice throw function Hello this is a question I have been tasked with. .......................................................................................................... You are at the bottom of a staircase with a die. With each throw of the die, you either move down on...
Python : Calculating probability of a dice throw function
Hello this is a question I have been tasked with. .......................................................................................................... You are at the bottom of a staircase with a die. With each throw of the die, you either move down one step (if you get a 1 or 2 on the dice) or move up one step (i...
[]
[]
[ "You could assign T to 1000 by an input function and it would then loop for a certain amount of throws.\n" ]
[ -1 ]
[ "dice", "probability", "python" ]
stackoverflow_0074450731_dice_probability_python.txt
Q: Python: Find and increment a number in a string I can't find a solution to this, so I'm asking here. I have a string that consists of several lines and in the string I want to increase exactly one number by one. For example: [CENTER] [FONT=Courier New][COLOR=#00ffff][B][U][SIZE=4]{title}[/SIZE][/U][/B][/COLOR][/FO...
Python: Find and increment a number in a string
I can't find a solution to this, so I'm asking here. I have a string that consists of several lines and in the string I want to increase exactly one number by one. For example: [CENTER] [FONT=Courier New][COLOR=#00ffff][B][U][SIZE=4]{title}[/SIZE][/U][/B][/COLOR][/FONT] [IMG]{cover}[/IMG] [IMG]IMAGE[/IMG][/CENTER] [...
[ "Assuming the number you want to change is always after a given pattern, e.g. \"Episodes: [/B]\", you can use this code:\ndef increment_episode_num(request_string, episode_pattern=\"Episodes: [/B]\"):\n idx = req_str.find(episode_pattern) + len(episode_pattern)\n episode_count = int(request_string[idx:idx+2])...
[ 0, 0 ]
[]
[]
[ "find", "increment", "python", "string" ]
stackoverflow_0074450539_find_increment_python_string.txt
Q: Drag and drop oval on canvas using Tkinter I am working on a python program for moving two circles on a canvas with the mousepointer. I have figured out how to attach the motion to the circles, but when I drag it with the mousebutton the circles goes in a weird direction. Their motions should also be separate but ...
Drag and drop oval on canvas using Tkinter
I am working on a python program for moving two circles on a canvas with the mousepointer. I have figured out how to attach the motion to the circles, but when I drag it with the mousebutton the circles goes in a weird direction. Their motions should also be separate but now they are entangled. I have tried to use the ...
[ "self.canvas1.move requires a distance, but you're passing a pixel address.\nOne solution is to remember the previous pixel location, then in your move function you need to calculate how many pixels the cursor has moved and pass that to self.canvas1.move.\nThe other problem is that you are explicitly moving all of ...
[ 2 ]
[]
[]
[ "canvas", "geometry", "python", "tkinter" ]
stackoverflow_0074451318_canvas_geometry_python_tkinter.txt
Q: Python excel dataset transformation I am reading excel data columns Item, Month and value Items = pd.read_excel('items_dataset.xlsx') Item Date value All items 2021-04 100 All items 2021-05 100.2 All items 2021-06 99.7 Apples 2021-04 100 Apples 2021-05 100.1 Apples 2021-06 10...
Python excel dataset transformation
I am reading excel data columns Item, Month and value Items = pd.read_excel('items_dataset.xlsx') Item Date value All items 2021-04 100 All items 2021-05 100.2 All items 2021-06 99.7 Apples 2021-04 100 Apples 2021-05 100.1 Apples 2021-06 100.3 I am trying to switch columns and ro...
[ "Try:\ndf = df.pivot(\n index=\"Date\", columns=\"Item\", values=\"Index value (April 2021 = 100)\"\n).reset_index()\ndf.columns.name, df.index.name = None, None\n\nprint(df)\n\nPrints:\n Date All items Apples Baked beans\n0 2021-04 100.0 100.0 100.0\n1 2021-05 100.2 100.1 1...
[ 1 ]
[]
[]
[ "dataframe", "lambda", "pandas", "python", "python_3.x" ]
stackoverflow_0074451420_dataframe_lambda_pandas_python_python_3.x.txt
Q: how can I get data in table format from pyodbc I'm getting data from snowflake ODBC connection in python through below code - It gives me the data but its not in table format with column head. How can I get it in table format with column head import pyodbc import sys con = pyodbc.connect('DSN=Snowflake Conn') con...
how can I get data in table format from pyodbc
I'm getting data from snowflake ODBC connection in python through below code - It gives me the data but its not in table format with column head. How can I get it in table format with column head import pyodbc import sys con = pyodbc.connect('DSN=Snowflake Conn') con.setencoding(encoding='utf-8') con.setdecoding(pyodb...
[ "If you're open to viewing the data in a csv, then you can use the following after your \"cs.execute(query)\" line:\nimport os\nimport csv\n\n# create a new csv file\nfilename = 'results'\nwith open(f'{filename}.csv', 'w', newline='', encoding='utf-8') as csvfile:\n writer = csv.writer(csvfile)\n # write column h...
[ 0 ]
[]
[]
[ "pyodbc", "python" ]
stackoverflow_0074291984_pyodbc_python.txt
Q: Start interactive SSH session from Python script I'd like to start an interactive SSH terminal from a Python script without using modules like pexpect or paramiko - I want to stick with what CentOS pre-installed Python provides me (to ease compatibility and deployment issues). I can run commands fine using the sub...
Start interactive SSH session from Python script
I'd like to start an interactive SSH terminal from a Python script without using modules like pexpect or paramiko - I want to stick with what CentOS pre-installed Python provides me (to ease compatibility and deployment issues). I can run commands fine using the subprocess module, but cannot get an interactive terminal...
[ "I get an interactive terminal if I use os.system('ssh [...]')\n", "For clarity and simplicity for future visitors of this thread, here is an example using the OP's subproccess.popen() solution.\ntry:\n print(\"Starting SSH connection...\")\n ssh_cmd = 'ssh -vvv -i your_ssh_key -o BatchMode=yes -p 22 user...
[ 10, 0 ]
[ "You could use pexpext if you want to mix interaction with automatic response\nhttp://www.noah.org/wiki/Pexpect\n" ]
[ -1 ]
[ "python", "ssh" ]
stackoverflow_0003692387_python_ssh.txt
Q: How to do KMeans clustering with timeseries as a feature Lets say I have the following dataframe, with continuous data at fixed intervals (so am not sure the tslearn KMeans clustering package is useful for this) date value 2022-09-06 01:40:50.999059 0.2732 2022-09-05 19:55:0...
How to do KMeans clustering with timeseries as a feature
Lets say I have the following dataframe, with continuous data at fixed intervals (so am not sure the tslearn KMeans clustering package is useful for this) date value 2022-09-06 01:40:50.999059 0.2732 2022-09-05 19:55:02.242936 0.9771 . . . I am trying to use the K means...
[ "One solution is to convert your datetime to UTC timestamp. Which is basically the number of seconds passed since Jan 1st 1970 (https://en.wikipedia.org/wiki/Unix_time). This way your data will be shaped as integers.\nYou can do it like this:\ndf[\"stamp\"] = df[\"date\"].values.astype(np.int64) // 10 ** 9\n\nThe o...
[ 0 ]
[]
[]
[ "cluster_analysis", "k_means", "python", "scikit_learn", "sklearn_pandas" ]
stackoverflow_0074451328_cluster_analysis_k_means_python_scikit_learn_sklearn_pandas.txt
Q: improperly configured at /18/delete, Django views issue I have searched through the other questions similar to my own problem and have come to no solution so im hoping someone can help me figure out where i went wrong. I'm trying to implement a delete post option in my blog program but it is throwing the following...
improperly configured at /18/delete, Django views issue
I have searched through the other questions similar to my own problem and have come to no solution so im hoping someone can help me figure out where i went wrong. I'm trying to implement a delete post option in my blog program but it is throwing the following error once you click the 'delete' button: ImproperlyConfigur...
[ "I think it should be model not form_class so:\nclass Deletepost(LoginRequiredMixin, DeleteView):\n model = Post\n success_url = reverse_lazy('blog:home')\n template_name = 'templates/post.html'\n\n def test_func(self):\n post = self.get_object()\n if self.request.user == post.author:\n ...
[ 3, 2, 2 ]
[]
[]
[ "django", "django_forms", "django_queryset", "django_urls", "python" ]
stackoverflow_0074451207_django_django_forms_django_queryset_django_urls_python.txt
Q: Pyodbc doesn't drop connection once script closes I use PYODBC to connect to database ( its rare kind of database ) but Pyodbc doesn't drop connection even when I close it explicity cnxn.close() is there any issue in pyodbc or is there any better way of closing the connection I tried to use different methods on d...
Pyodbc doesn't drop connection once script closes
I use PYODBC to connect to database ( its rare kind of database ) but Pyodbc doesn't drop connection even when I close it explicity cnxn.close() is there any issue in pyodbc or is there any better way of closing the connection I tried to use different methods on database side as well did it on scripting but it didn't ...
[ "Did you close the cursor first?\ncursor.close()\ncnxn.close()\n\n" ]
[ 0 ]
[]
[]
[ "pyodbc", "python" ]
stackoverflow_0074282862_pyodbc_python.txt
Q: Is a python socket connection safe? I have built a python script that uses python socket to build a connection between my python application and my python server. I have encrypted the data sent between the two systems. I was wondering if I should think of any other things related to security against hackers. Can t...
Is a python socket connection safe?
I have built a python script that uses python socket to build a connection between my python application and my python server. I have encrypted the data sent between the two systems. I was wondering if I should think of any other things related to security against hackers. Can they do something that could possibly stea...
[ "If the data is encrypted using a good decryption (AES for example) and the decryption is key is send safely your data is safe. The only other thing I can think about is adding a password or another authentication before accepting data sent to you via socket.\nEdit: If you keep the connection open, it's always a go...
[ 1, 1 ]
[]
[]
[ "networking", "python", "python_3.x", "python_sockets", "sockets" ]
stackoverflow_0074451481_networking_python_python_3.x_python_sockets_sockets.txt
Q: Why does my use of "isin" to filter my data frame's rows by column based on values in a list result in a blank data frame? I'm trying to build a function that takes specific movie genres linked to a moiveId stored as a list and returns other movies that share one or more of those genres. I can create the list and ...
Why does my use of "isin" to filter my data frame's rows by column based on values in a list result in a blank data frame?
I'm trying to build a function that takes specific movie genres linked to a moiveId stored as a list and returns other movies that share one or more of those genres. I can create the list and have confirmed it is a list, but when I use "isin" to use this as a filter, I get a blank dataframe. First I remove the "|" deli...
[ "You can use set intersection to test if two lists overlap. Use apply() to check this for every row.\ngenre_set = set(y.genres[0])\n\na = inner_join_movies_ratings[inner_join_movies_ratings['genres'].apply(lambda g: len(genre_set.intersection(g)) > 0)]\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "indexing", "list", "pandas", "python" ]
stackoverflow_0074451332_dataframe_indexing_list_pandas_python.txt
Q: How can I ignore empty groups? Pretty straightforward regex, I am trying to extract IP from logs. But group(1) is empty, which is given. Is there a better way to approach this problem? sourceip_regex_extract = re.compile(r"{}".format(sourceip_syslog_regex)) sourceip_extract = sourceip_regex_extract.search(message)...
How can I ignore empty groups?
Pretty straightforward regex, I am trying to extract IP from logs. But group(1) is empty, which is given. Is there a better way to approach this problem? sourceip_regex_extract = re.compile(r"{}".format(sourceip_syslog_regex)) sourceip_extract = sourceip_regex_extract.search(message) sourceip_txt = sourceip_extract.gr...
[ "First of all, when you search for a match with a regex, make sure you actually get a match and only then access the first group value.\nNext, r\"{}\".format(sourceip_syslog_regex) makes no sense, it is the same as sourceip_syslog_regex.\nTo fix the current issue, you can use a (?:from |inside:) alternation to matc...
[ 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074451605_python_regex.txt
Q: Training custom SpaCy NER model gives training error I want to train my own custom NER with SpaCy for recogrnizing addresses. This is my data: training_data = [('send to: Aargauerstrasse 8005', {'entities': [(9, 28, 'ADDRESS')]}), ('send to: Abeggweg 8057', {'entities': [(9, 21, 'ADDRESS')]}), ...
Training custom SpaCy NER model gives training error
I want to train my own custom NER with SpaCy for recogrnizing addresses. This is my data: training_data = [('send to: Aargauerstrasse 8005', {'entities': [(9, 28, 'ADDRESS')]}), ('send to: Abeggweg 8057', {'entities': [(9, 21, 'ADDRESS')]}), ('send to: Abendweg 8038', {'entities': [(9,...
[ "nlp.update([example], drop=0.2, sgd=optimizer, losses=losses)\n" ]
[ 0 ]
[]
[]
[ "nlp", "python", "spacy" ]
stackoverflow_0066807713_nlp_python_spacy.txt
Q: Ursina Engine: Black screen flickers when I use `mouse.locked`, what is that? I want to make a 1st person game and the whole problem started by making an accessible inventory. Whenever I used mouse.locked (no matter if i do mouse.locked = True or mouse.locked = False) (it basically makes possible to move the curso...
Ursina Engine: Black screen flickers when I use `mouse.locked`, what is that?
I want to make a 1st person game and the whole problem started by making an accessible inventory. Whenever I used mouse.locked (no matter if i do mouse.locked = True or mouse.locked = False) (it basically makes possible to move the cursor around the screen, not to look around), black screen started flickering over the ...
[ "Maybe it's a bit late, but...\nI had the problem too. For me it solved the problem by closing all other apps (also background). If MS Teams was opened it flickered. Ursina wasn't the reason.\n" ]
[ 1 ]
[]
[]
[ "game_development", "panda3d", "python", "ursina" ]
stackoverflow_0074173852_game_development_panda3d_python_ursina.txt
Q: Escaping XML Characters using Python Polars I'm working with Polars to build out XML from a table and I want to Escape XML characters. However, I'm running into issues when I try and do this. The first thing I did was try the following: import polars as pl from xml.sax.saxutils import escape table_raw = pl.read_s...
Escaping XML Characters using Python Polars
I'm working with Polars to build out XML from a table and I want to Escape XML characters. However, I'm running into issues when I try and do this. The first thing I did was try the following: import polars as pl from xml.sax.saxutils import escape table_raw = pl.read_sql("""SELECT * FROM mytable""", engine).lazy() t...
[ "Figured out a way to handle this. You can use a custom function like the following:\nimport polars as pl\nfrom xml.sax.saxutils import escape\n\ntable_raw = pl.read_sql(\"\"\"SELECT * FROM mytable\"\"\", engine).lazy()\n\ntable = table_raw.select([\n pl.concat_str([\n pl.lit('''<wd:Overall_XML_Tag>''').alias...
[ 0 ]
[]
[]
[ "python", "python_polars", "xml" ]
stackoverflow_0074450483_python_python_polars_xml.txt
Q: BeautifulSoup cannot parse through html tag marked with =$0 "=$0" indicates the tag as the last selected Dom node, which means that all that html is added later via javascript which makes the tag look empty when parsing through it with beautiful soup. This is the website I am referring to, and I want to get the sr...
BeautifulSoup cannot parse through html tag marked with =$0
"=$0" indicates the tag as the last selected Dom node, which means that all that html is added later via javascript which makes the tag look empty when parsing through it with beautiful soup. This is the website I am referring to, and I want to get the src from the video tag from <div class = "jw-wrapper jw-reset"> =$0...
[ "You can't extract the src URL directly using BeautifulSoup because it's not in the HTML code returned with requests. So, you need to parse the HTML and Javascript before using it with BeautifulSoup. You can find Javascript parsing packages with simple Google search.\nHowever, I would suggest to use Selenium instea...
[ 1 ]
[]
[]
[ "beautifulsoup", "html", "javascript", "python", "web_scraping" ]
stackoverflow_0074451579_beautifulsoup_html_javascript_python_web_scraping.txt
Q: Return certain character or word followed or proceeded by space- Regex Python Try to select only the size of clothes using regex expression So I am new to Python and I trying to select rows find these sizes but gets confused with other words. I using regex expression but failed to obtain the desired result. Code: ...
Return certain character or word followed or proceeded by space- Regex Python
Try to select only the size of clothes using regex expression So I am new to Python and I trying to select rows find these sizes but gets confused with other words. I using regex expression but failed to obtain the desired result. Code: df = pd.DataFrame({"description":["Silver","Red","GOLD","Black Leather","S","L","S"...
[ "I think you need to use\nimport pandas as pd\ndf = pd.DataFrame({\"description\":[\"Silver\",\"Red\",\"GOLD\",\"Black Leather\",\"S\",\"L\",\"S\",\"XL\",\"XXL\",\"Noir Matt\",\" 150x160L\",\"140M\"]})\ndf['description'][df['description'].str.match(r'^(?:S|M|X*L)$')].unique()\n# => array(['S', 'L', 'XL', 'XXL'], dt...
[ 1 ]
[]
[]
[ "dataframe", "findall", "python", "python_re", "regex" ]
stackoverflow_0074450626_dataframe_findall_python_python_re_regex.txt
Q: How to check if random generated number forms a couple in a list of lists PYTHON I have 4 lists of couples of numbers and a list that contains all the 4 lists. I need to create a list with 4 numbers in total, in which only one couple is from the list_couples and the rest are randomly generated (for example:[1,21,...
How to check if random generated number forms a couple in a list of lists PYTHON
I have 4 lists of couples of numbers and a list that contains all the 4 lists. I need to create a list with 4 numbers in total, in which only one couple is from the list_couples and the rest are randomly generated (for example:[1,21,5,6]). Does anyone have an idea how to make a condition of checking whether the rest o...
[ "You could check to see if your random couple is in list_couple and loop until it isn't\nimport random\n\nlist1=[1,21]\nlist2=[1,31]\nlist3=[2,12]\nlist4=[2,22]\nlist5=[10,20]\nlist_couples = [list1,list2,list3,list4]\n\nrand_couple = [random.randint(1,99), random.randint(1,99)]\n#Loop until rand_couple isn't in li...
[ 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074451663_list_python.txt
Q: I have a 3d list of strings and numbers. I need to calculate the sum of each string and then percent in python I have a 3d list, of strings and numbers. I need to calculate the sum of each color. Plus, what percentage each item contributes to that total color. This is what I currently have. from collections import...
I have a 3d list of strings and numbers. I need to calculate the sum of each string and then percent in python
I have a 3d list, of strings and numbers. I need to calculate the sum of each color. Plus, what percentage each item contributes to that total color. This is what I currently have. from collections import defaultdict d = defaultdict(int) dc = defaultdict(int) l = [('red', 'apple', 7), ('red', 'car', 4), ('red', 'sho...
[ "You need to iterate one more times on dc and use value of d base color_key.\nfrom collections import defaultdict\n\nd = defaultdict(int)\ndc = defaultdict(int) \n\nl = [('red', 'apple', 0), ('red', 'car', 0), ('red', 'shoe', 0), ('blue', 'candy', 4), ('blue', 'bike', 5), ('green', 'melon', 2)]\n\nfor color, name, ...
[ 1 ]
[]
[]
[ "dictionary", "list", "percentage", "python", "sum" ]
stackoverflow_0074451657_dictionary_list_percentage_python_sum.txt
Q: Pandas: cannot safely convert passed user dtype of int32 for float64 I am stumped by a problem with loading my data into a Pandas dataframe using read_table(). The error says TypeError: Cannot cast array from dtype('float64') to dtype('int32') according to the rule 'safe' and ValueError: cannot safely convert pass...
Pandas: cannot safely convert passed user dtype of int32 for float64
I am stumped by a problem with loading my data into a Pandas dataframe using read_table(). The error says TypeError: Cannot cast array from dtype('float64') to dtype('int32') according to the rule 'safe' and ValueError: cannot safely convert passed user dtype of int32 for float64 dtyped data in column 2 test.py: import...
[ "The problem was that I was using spaces as the delimiter and that the csv had trailing spaces. Removing the trailing spaces solved the issue.\nTo trim all of the trailing spaces on every line of every file in a directory, I ran this command: find . -name \"*.csv\" | xargs sed -i 's/[ \\t]*$//'\n", "Column 2 inc...
[ 3, 0 ]
[]
[]
[ "dataframe", "numpy", "pandas", "python", "validation" ]
stackoverflow_0051214020_dataframe_numpy_pandas_python_validation.txt
Q: Pandas DateTime String/List I need to convert a list of strings to date time objects, particularly with Pandas. I really hope this doesn't get flagged as a duplicate because I have seen similar questions, but none have answered my question I have tried this and I was expecting a value like 'Hello World' to return ...
Pandas DateTime String/List
I need to convert a list of strings to date time objects, particularly with Pandas. I really hope this doesn't get flagged as a duplicate because I have seen similar questions, but none have answered my question I have tried this and I was expecting a value like 'Hello World' to return as NaT, but the only one that doe...
[ "Just by getting rid of the yearfirst and format arguments I get the output:\n0 2020-11-14\n1 2020-11-14\n2 2020-11-14\n3 NaT\n4 2020-11-14\ndtype: datetime64[ns]\n\n" ]
[ 0 ]
[]
[]
[ "datetime", "pandas", "python", "python_3.x", "string_to_datetime" ]
stackoverflow_0074451679_datetime_pandas_python_python_3.x_string_to_datetime.txt
Q: Can't delete role even though bot has admin permissions? I clearly have the permissions to delete the role, but I still get the error: await test_role.delete() raise Forbidden(response, data) discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions checking bot permissions gives me eve...
Can't delete role even though bot has admin permissions?
I clearly have the permissions to delete the role, but I still get the error: await test_role.delete() raise Forbidden(response, data) discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions checking bot permissions gives me every role as true (which it should bc it's an admin), but just t...
[ "Make sure the bot is above the role you're trying to delete.\nEX:\nOwner\nCo-Owner\n**test-role**\n**The Bots Role**\n\n^^^ The Bot role would need to be placed above the test-role.\nI believe it's a Discord Hierarchy issue\n" ]
[ 1 ]
[]
[]
[ "discord", "discord.py", "python" ]
stackoverflow_0074438351_discord_discord.py_python.txt
Q: StaleElementReferenceException in for loop with Python & Selenium I am trying to scrape newspaper articles from Le Monde's website, and have written a small simple script to do so. It has worked quite well so far but for some obscure reason, its recent runs have all brought me to a StaleElementReferenceException e...
StaleElementReferenceException in for loop with Python & Selenium
I am trying to scrape newspaper articles from Le Monde's website, and have written a small simple script to do so. It has worked quite well so far but for some obscure reason, its recent runs have all brought me to a StaleElementReferenceException error, without me being exactly able to pinpoint why. This is my code: f...
[ "Well, I think I have found a way myself. In case that can help anyone in the same situation in the future, I did this and it seems to be working just fine now.\nfor n in range(2, nb_pages+2): #+1 is because range does not include the last element / until excludes\n #collecting everything\n titles = b...
[ 0 ]
[]
[]
[ "exception", "python", "selenium", "web_scraping" ]
stackoverflow_0074447063_exception_python_selenium_web_scraping.txt
Q: Split variables into groups, each constrained to hold a specific number of variables, while optimizing group sums towards specific values I have a number of variables each assigned an integer value. I need to split these variables in three groups with a predefined number of variables going into each group while op...
Split variables into groups, each constrained to hold a specific number of variables, while optimizing group sums towards specific values
I have a number of variables each assigned an integer value. I need to split these variables in three groups with a predefined number of variables going into each group while optimizing towards predefined sums of the values in each group. Each group sum should be as close as possible to the predefined value, but can be...
[ "This seems to be a fairly standard \"assignment\" problem.\nLet z_ij be a set of binary variable representing if object i is assigned to group j.\nYour objective then is to minimise the absolute value of deviations of the group-sums from their target values - working example code below:\nfrom pulp import LpMaximiz...
[ 0 ]
[]
[]
[ "mathematical_optimization", "modeling", "pulp", "python" ]
stackoverflow_0074451706_mathematical_optimization_modeling_pulp_python.txt
Q: how to choose a chosen quantity and random order from a dictionary how to get only a certain number of question and not all? and randomly, i tried but im stuck import random score = 0 questions = [ { 'question': "first question", 'answer': ["dea", "hay"] }, { 'question': "second question", 'answer': ["deo", "h...
how to choose a chosen quantity and random order from a dictionary
how to get only a certain number of question and not all? and randomly, i tried but im stuck import random score = 0 questions = [ { 'question': "first question", 'answer': ["dea", "hay"] }, { 'question': "second question", 'answer': ["deo", "hoy"] }, { 'question': "third question", 'answer': ["dei", "hey"] }, ]...
[ "Instead of\nfor j in questions: preguntas = j.get(\"question\") print(preguntas)\n\ntry\nN = 2 # your target number of questions\nfor j in random.choices(questions, k = N): preguntas = j.get(\"question\") print(preguntas)\n\n" ]
[ 0 ]
[]
[]
[ "for_loop", "python", "range" ]
stackoverflow_0074451871_for_loop_python_range.txt
Q: Reshaping a dataframe every nth column I have two datasets. After merging them horzontally, and sorting the columns with the following code, I get the dataset below: df= X Y 5.2 6.5 3.3 7.6 df_year= X Y 2014 2014 2015 2015 df_all_cols = pd.concat([df, df_year], axis = 1) sorted_columns = sorted(df_all_cols...
Reshaping a dataframe every nth column
I have two datasets. After merging them horzontally, and sorting the columns with the following code, I get the dataset below: df= X Y 5.2 6.5 3.3 7.6 df_year= X Y 2014 2014 2015 2015 df_all_cols = pd.concat([df, df_year], axis = 1) sorted_columns = sorted(df_all_cols.columns) df_all_cols_so...
[ "One approach could be as follows:\n\nApply df.stack to both dfs before feeding them to pd.concat. The result at this stage being:\n\n 0 1\n0 X 5.2 2014\n Y 6.5 2014\n1 X 3.3 2015\n Y 7.6 2015\n\n\nNext, use df.sort_index to sort on the original column names (i.e. \"X, Y\", now appearing as inde...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python", "reshape", "stack" ]
stackoverflow_0074451730_dataframe_pandas_python_reshape_stack.txt
Q: How do I convert an absolute Posix path to a Windows path in Python's pathlib I'm running Python 3.9 on Windows. I have an absolute Posix path, such as: '/c/Program Files/clang-format' I happened to have obtained this by running os.system('which clang-format'), but no matter. I want to convert this to a Windows pa...
How do I convert an absolute Posix path to a Windows path in Python's pathlib
I'm running Python 3.9 on Windows. I have an absolute Posix path, such as: '/c/Program Files/clang-format' I happened to have obtained this by running os.system('which clang-format'), but no matter. I want to convert this to a Windows path so that I can call os.system(path_to_exe). I don't know why it's giving me Posix...
[ "You can get the Windows NT format path using the os.path module, and you can isolate the drive by using the os.path.splitdrive function. This only gets you halfway there; you still have to lop off the posix base /c/ and reconstruct the path.\nI've used posixpath to deal with the posix structure returned in mingw.\...
[ 0 ]
[]
[]
[ "pathlib", "python" ]
stackoverflow_0074440621_pathlib_python.txt
Q: Is there a better way to declare a numpy matrix where each element [i][j] is the result of an operation between A[i] and A[j], where A is an arange? Basically, what I need to do is this: I have a value "n" and two different arrays "x" and "y" of arbitrary values (x,y = [a, b, c, ...]) With n, I create an arange "...
Is there a better way to declare a numpy matrix where each element [i][j] is the result of an operation between A[i] and A[j], where A is an arange?
Basically, what I need to do is this: I have a value "n" and two different arrays "x" and "y" of arbitrary values (x,y = [a, b, c, ...]) With n, I create an arange "A" like this: [n, n-1, n-2, ..., 0] I create a 2d array "B" of size n+1×n+1 where each element B[i][j] = np.sum(np.power(x,(A[i]+A[j]))) I create a 1d arr...
[ "I would say:\nx = np.array(x)\nA = np.array(A)\n\nB = (x**(A[:,None]+A)[..., None]).sum(-1)\n\ny = np.array(y)\n\nC = (x**A[:, None]*y).sum(-1)\n\nOutput:\n# B\narray([[5, 3],\n [3, 3]])\n\n# C\narray([ 7, 10])\n\nother example\nn = 1\nA = np.arange(n,-1,-1)\nx = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])\ny = np...
[ 0 ]
[]
[]
[ "2d", "arrays", "matrix", "numpy", "python" ]
stackoverflow_0074451757_2d_arrays_matrix_numpy_python.txt
Q: how to make a matrix in python? Hello everyone I want to make a matrix that looks like the image, what I did first was to create a matrix of zeros and then with a for I made the diagonal of the matrix but now I need to make the diagonals that are above and below the -2 but in those there is not a single value, tho...
how to make a matrix in python?
Hello everyone I want to make a matrix that looks like the image, what I did first was to create a matrix of zeros and then with a for I made the diagonal of the matrix but now I need to make the diagonals that are above and below the -2 but in those there is not a single value, those have zeros and ones so I am not ve...
[ "You've got several choices....\n\nYou could \"hand jam\" the whole thing in by just typing the rows. (You probably already know this.)\nD = [[-2, 1, 0, ...],\n[...]]\n\nYou can make a smaller matrix that represents what you have in the red-dashed box (the sub-matrix) and just replace values in D by over-writing t...
[ 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074451647_python_python_3.x.txt
Q: Do double quotes (") act like field delimiters or as an escape character, or both in CSV files? I've read that the delimiter of a CSV is the comma (,) and the escape character is the double quotes ("). What I don't understand is why or how double quotes (") are used to also preserve spaces in field values...What ...
Do double quotes (") act like field delimiters or as an escape character, or both in CSV files?
I've read that the delimiter of a CSV is the comma (,) and the escape character is the double quotes ("). What I don't understand is why or how double quotes (") are used to also preserve spaces in field values...What I mean is this claim: "CSV files use double-quote marks to delimit field values that have spaces, so ...
[ "Consider what happens when you want a string with a comma as a field in your row. You would need some sort of way to let the csv parser that this is not a parsing comma, but it is a 'data comma', so you need to denote it in some sort of special form. usually this is done by enclosing the field with a comma in doub...
[ 0 ]
[]
[]
[ "csv", "parsing", "python" ]
stackoverflow_0074451038_csv_parsing_python.txt
Q: Get Calendar by name from Outlook using Powershell script I used a powershell script (found it in the Google)to get the calendar from exchange outlook and called the script in python.[] But somehow I'm not able to get the calendar that I want, I'm just getting the default calendar every time I run the code. I tire...
Get Calendar by name from Outlook using Powershell script
I used a powershell script (found it in the Google)to get the calendar from exchange outlook and called the script in python.[] But somehow I'm not able to get the calendar that I want, I'm just getting the default calendar every time I run the code. I tired this solution from the internet and add it to my powershell s...
[ "I am not a PowerShell guru, but the Outlook object model is common for all programming languages, so you may understand the required sequence or property and method calls in the following VBA macro:\nSub ListAllSharedCalendars()\n Dim olPane As NavigationPane\n Dim olMod As CalendarModule\n Dim olGrp As N...
[ 0 ]
[]
[]
[ "calendar", "office_automation", "outlook", "powershell", "python" ]
stackoverflow_0074451760_calendar_office_automation_outlook_powershell_python.txt
Q: Displaying Special Characters Using Unicode I want to know how to type a special character "Cherry" like the fruit. I got the Unicode string and attempted to display it, but for some reason it sees the 2 within \u1F352 as part of the string and not the Unicode sequence, so it displays something completely differen...
Displaying Special Characters Using Unicode
I want to know how to type a special character "Cherry" like the fruit. I got the Unicode string and attempted to display it, but for some reason it sees the 2 within \u1F352 as part of the string and not the Unicode sequence, so it displays something completely different: ἵ2. import sys print('\u1F352')
[ "Using the unicode escape:\n>>> print(\"\\U0001F352\")\n\n\nUsing the unicode name:\n>>> print(\"\\N{cherries}\")\n\n\nUsing the codepoint:\n>>> print(chr(0x1f352))\n\n\n" ]
[ 3 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0074451967_python_unicode.txt
Q: Is there a proper way to subclass Tensorflow's Dataset? I was looking at different ways that one can do custom Tensorflow datasets, and I was used to looking at PyTorch's datasets, but when I went to look at Tensorflow's datasets, I saw this example: class ArtificialDataset(tf.data.Dataset): def _generator(num_s...
Is there a proper way to subclass Tensorflow's Dataset?
I was looking at different ways that one can do custom Tensorflow datasets, and I was used to looking at PyTorch's datasets, but when I went to look at Tensorflow's datasets, I saw this example: class ArtificialDataset(tf.data.Dataset): def _generator(num_samples): # Opening the file time.sleep(0.03) for...
[ "Question 1\nThat example is just encapsulating a dataset with a generator in a class. It is inheriting from tf.data.Dataset because from_generator() returns a tf.data.Dataset -based object. However, no methods of tf.data.Dataset are used as seen in the example. Thus, answer to question 1: yes, it can be called str...
[ 0 ]
[]
[]
[ "python", "tensorflow" ]
stackoverflow_0072323238_python_tensorflow.txt
Q: Apache Airflow cannot execute any DAG - why? I'm trying to execute some airflow DAGs on localhost but non works. I get always the same error: [2022-11-15, 20:18:35 CET] {taskinstance.py:1383} INFO - Executing <Task(BashOperator): get_datetime> on 2022-11-15 19:18:29.749895+00:00 [2022-11-15, 20:18:35 CET] {standar...
Apache Airflow cannot execute any DAG - why?
I'm trying to execute some airflow DAGs on localhost but non works. I get always the same error: [2022-11-15, 20:18:35 CET] {taskinstance.py:1383} INFO - Executing <Task(BashOperator): get_datetime> on 2022-11-15 19:18:29.749895+00:00 [2022-11-15, 20:18:35 CET] {standard_task_runner.py:55} INFO - Started process 8406 t...
[ "It seems like you have a distributed Airflow executor (Celery or Kubernetes), and your dag folder is only mounted to the scheduler process, but not the workers. Airflow scheduler and workers runs the dag script for each operation on the task, so in your case, the workers doesn't find the dag script and it fail.\nI...
[ 0 ]
[]
[]
[ "airflow", "directed_acyclic_graphs", "python" ]
stackoverflow_0074451128_airflow_directed_acyclic_graphs_python.txt
Q: AttributeError: Can't pickle local object I'm working on a machine learning university project and I need to save an "agent" (an object) containing some complex stuff that allows me to do other stuff ahahah...I'm using pickle but unfortunately there is an error....AttributeError: Can't pickle local object 'constan...
AttributeError: Can't pickle local object
I'm working on a machine learning university project and I need to save an "agent" (an object) containing some complex stuff that allows me to do other stuff ahahah...I'm using pickle but unfortunately there is an error....AttributeError: Can't pickle local object 'constant_fn.<locals>.func' this is a piece of my code:...
[ "Check this:\nfrom finrl.agents.stablebaselines3.models import DRLAgent\nimport pickle\nimport os\n\nif os.path.isfile(\"./filename_pi.obj\"):\n print(\"-FILE FOUND-\")\n file_pi = open('filename_pi.obj', 'rb')\n trained_a2c = pickle.load(file_pi)\n file_pi.close()\nelse:\n print(\"-FILE NOT FOUND-\"...
[ 0 ]
[]
[]
[ "finrl", "pickle", "python" ]
stackoverflow_0074452018_finrl_pickle_python.txt
Q: Python: Separate text file data into tuples? I'm currently working on trying to separate values inside of a .txt file into tuples. This is so that, later on, I want to create a simple database using these tuples to look up the data. Here is my current code: with open("data.txt") as load_file: data = [tuple(lin...
Python: Separate text file data into tuples?
I'm currently working on trying to separate values inside of a .txt file into tuples. This is so that, later on, I want to create a simple database using these tuples to look up the data. Here is my current code: with open("data.txt") as load_file: data = [tuple(line.split()) for line in load_file] c = 0 pts = [] ...
[ "Try to use csv module with custom delimiter=:\nimport csv\n\nwith open(\"your_file.txt\", \"r\") as f_in:\n reader = csv.reader(f_in, delimiter=\"|\")\n\n for a, b, c, d in reader:\n print([a, int(b), c, d])\n\nPrints:\n['John', 43, '123 Apple street', '514 428-3452']\n['Katya', 26, '49 Queen Mary Roa...
[ 1, 1 ]
[]
[]
[ "database", "python", "tuples", "txt" ]
stackoverflow_0074452083_database_python_tuples_txt.txt
Q: reshape not require to display mnist images? If I want to display one image from mnist dataset, I need to reshape it from (1,28,28) to (28,28) using the following code: import tensorflow as tf import matplotlib.pyplot as plt mnist = tf.keras.datasets.mnist (x_train, y_train), (x_test, y_test) = mnist.load_data()...
reshape not require to display mnist images?
If I want to display one image from mnist dataset, I need to reshape it from (1,28,28) to (28,28) using the following code: import tensorflow as tf import matplotlib.pyplot as plt mnist = tf.keras.datasets.mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train, x_test = x_train / 255.0, x_test / 255.0...
[ "You wouldn't need reshape in the first one either if you selected the first image using x_train[0]. Accessing a specific index of the array removes the first element of the shape.\nSo if you have a numpy array of shape (100, 28, 28), and access x_train[0], you will get a shape of (28, 28). But if you access it as ...
[ 1 ]
[]
[]
[ "matplotlib", "mnist", "python", "reshape", "tensorflow" ]
stackoverflow_0074451766_matplotlib_mnist_python_reshape_tensorflow.txt
Q: Selecting columns from pandas MultiIndex I have DataFrame with MultiIndex columns that looks like this: # sample data col = pd.MultiIndex.from_arrays([['one', 'one', 'one', 'two', 'two', 'two'], ['a', 'b', 'c', 'a', 'b', 'c']]) data = pd.DataFrame(np.random.randn(4, 6), columns=col)...
Selecting columns from pandas MultiIndex
I have DataFrame with MultiIndex columns that looks like this: # sample data col = pd.MultiIndex.from_arrays([['one', 'one', 'one', 'two', 'two', 'two'], ['a', 'b', 'c', 'a', 'b', 'c']]) data = pd.DataFrame(np.random.randn(4, 6), columns=col) data What is the proper, simple way of sele...
[ "The most straightforward way is with .loc:\n>>> data.loc[:, (['one', 'two'], ['a', 'b'])]\n\n\n one two \n a b a b\n0 0.4 -0.6 -0.7 0.9\n1 0.1 0.4 0.5 -0.3\n2 0.7 -1.6 0.7 -0.8\n3 -0.9 2.6 1.9 0.6\n\nRemember that [] and () have special meaning when dealing with a MultiIndex obje...
[ 39, 28, 19, 17, 14, 11, 3, 1, 0, 0, 0, 0, 0 ]
[]
[]
[ "hierarchical", "multi_index", "pandas", "python" ]
stackoverflow_0018470323_hierarchical_multi_index_pandas_python.txt
Q: Struggling with simple loops //I started learning python 2 weeks ago and right now stack with this problem for a few days. I need somobody to give me a hint or something close to solution. Thank you.Here is my code. from math import sqrt # Write your solution here number = int(input("Please type in a number:")) w...
Struggling with simple loops
//I started learning python 2 weeks ago and right now stack with this problem for a few days. I need somobody to give me a hint or something close to solution. Thank you.Here is my code. from math import sqrt # Write your solution here number = int(input("Please type in a number:")) while True: if number > 0: ...
[ "the first break statement always breaks out of the loop, so you never reach the second (and third if). you may want to indent it to be part of the if statements' bodies:\nfrom math import sqrt\n\n# Write your solution here\nnumber = int(input(\"Please type in a number:\"))\nwhile True:\n if number > 0:\n ...
[ 2 ]
[]
[]
[ "loops", "python", "validation" ]
stackoverflow_0074452189_loops_python_validation.txt
Q: How can I convert this text file into a python dictionay? So I have this text file (1, 15), 'indice3 = [4, 5, 6]' (7, 1), "indice1 = {3: 'A B C'}" (11, 7), "indice4 = '(1, 2)'" (11, 17), 'typage = mode de déclaration des types de variable' (23, 5), "indice5 = '(3, 4)'" (25, 1), '27 * 37 = 999' As you can see, the...
How can I convert this text file into a python dictionay?
So I have this text file (1, 15), 'indice3 = [4, 5, 6]' (7, 1), "indice1 = {3: 'A B C'}" (11, 7), "indice4 = '(1, 2)'" (11, 17), 'typage = mode de déclaration des types de variable' (23, 5), "indice5 = '(3, 4)'" (25, 1), '27 * 37 = 999' As you can see, there's at first coordinates and then a text. Here's an example of...
[ "Try to use ast.literal_eval:\nfrom ast import literal_eval\n\n\nout = []\nwith open(\"your_file.txt\", \"r\") as f_in:\n for line in map(str.strip, f_in):\n if line == \"\":\n continue\n out.append(literal_eval(f\"[{line}]\"))\n\nprint(dict(out))\n\nPrints:\n{\n (1, 15): \"indice3 = ...
[ 3, 1 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0074452036_dictionary_list_python.txt
Q: Connecting to Bigquery by Python: ProjectId and DatasetId must be non-empty I wrote the below script to connect Big Query to Python by SDK as below: from google.cloud import bigquery client=bigquery.Client(project='My First Project') sql="select * from austin_311.311_service_requests" query_job=client.query(sql) ...
Connecting to Bigquery by Python: ProjectId and DatasetId must be non-empty
I wrote the below script to connect Big Query to Python by SDK as below: from google.cloud import bigquery client=bigquery.Client(project='My First Project') sql="select * from austin_311.311_service_requests" query_job=client.query(sql) I face the below error: BadRequest: 400 POST https://bigquery.googleapis.com/big...
[ "In my case, I solved the problem by offering credentials for the google BigQuery Client.\nCheck codes below.\n# https://googleapis.dev/python/google-api-core/latest/auth.html\nfrom google.oauth2 import service_account\n\njson_account_info = #{service_account_info}\ncredentials = service_account.Credentials.from_se...
[ 0, 0 ]
[]
[]
[ "connection", "google_cloud_platform", "python" ]
stackoverflow_0072823768_connection_google_cloud_platform_python.txt
Q: How to use Loop inside Function corectly i want use loop correctly inside function This is my code : def test(): for i in range(1,10): return i def check(): print(test()) check() output is 1 i want to full iteration output : 1 ,2,4....10 A: When you return inside a function, it immediately term...
How to use Loop inside Function corectly
i want use loop correctly inside function This is my code : def test(): for i in range(1,10): return i def check(): print(test()) check() output is 1 i want to full iteration output : 1 ,2,4....10
[ "When you return inside a function, it immediately terminates the function and returns the specified value. This means that it goes into the for loop and returns 1, then stops running. One way to get around this is to use the yield keyword instead of return.\ndef test():\n for i in range(1, 10):\n yield i...
[ 1, 0 ]
[ "If you want to return all the values in the range you can do something like this:\ndef test():\n return [i for i in range(1,10)]\n\n\ndef check():\n print(test())\ncheck()\n\n" ]
[ -2 ]
[ "list", "python" ]
stackoverflow_0074452150_list_python.txt
Q: loop attribute cannot be acessed in non-async contexts with discord.py When I try to run this code ` import json import os import random from pprint import pprint import aiohttp import discord import requests from discord.ext import commands from dotenv import load_dotenv from mojang import api # Functions # Se...
loop attribute cannot be acessed in non-async contexts with discord.py
When I try to run this code ` import json import os import random from pprint import pprint import aiohttp import discord import requests from discord.ext import commands from dotenv import load_dotenv from mojang import api # Functions # Sends a Get request to a given url def get_info(call): r = requests.get(ca...
[ "Your Bot variable is called bot, but you're using client in your wait_for statement.\nYou've got both a discord.Client (\"client\") and a commands.Bot (\"bot\") instance. This doesn't make a whole lot of sense. If you only need Client features then use Client, if you want Bot features then use Bot. You can't use b...
[ 1, 0 ]
[]
[]
[ "discord.py", "python" ]
stackoverflow_0074451216_discord.py_python.txt
Q: Image Convolution with callback function in python I want to loop over the pixels of a binary image in python and set the value of a pixel depending on a surrounding neighborhood of pixels. Similar to convolution but I want create a method that sets the value of the center pixel using a custom function rather than...
Image Convolution with callback function in python
I want to loop over the pixels of a binary image in python and set the value of a pixel depending on a surrounding neighborhood of pixels. Similar to convolution but I want create a method that sets the value of the center pixel using a custom function rather than normal convolution that sets the center pixel to the ar...
[ "Here's an idea: assign each pixel an array with its neighborhood and then simply apply your custom function to the extended image. It'll be fast BUT will consume more memory ( times more memory; if your B.shape is (3, 3) then you'll need 9 times more memory). Try this:\nimport numpy as np\n\ndef convolve2(func):\n...
[ 0 ]
[]
[]
[ "convolution", "image_processing", "numpy", "numpy_ndarray", "python" ]
stackoverflow_0073854250_convolution_image_processing_numpy_numpy_ndarray_python.txt
Q: Is it possible to include .html tags in a realhttp setContent statment? I am doing a Packet Tracer project with an SCB acting as a server and sending .html files to a browser. One of these pages needs to display dynamic text based on some of my python variables, as well as have a hard coded link to another page. S...
Is it possible to include .html tags in a realhttp setContent statment?
I am doing a Packet Tracer project with an SCB acting as a server and sending .html files to a browser. One of these pages needs to display dynamic text based on some of my python variables, as well as have a hard coded link to another page. Should look like this The first two lines of dynamic text can be passed using ...
[ "The solution is to use the setContentType command to send the data as html code, rather than palin text. This allows the html to recognize tags, and the link inside the tag displays correctly.\nThe line 'reply.setContentType(\"text/html\")' should go before reply.setContent\nlink_message = 'Click <a href=\"http:/...
[ 0 ]
[]
[]
[ "html", "python", "server" ]
stackoverflow_0074439938_html_python_server.txt
Q: Take user input from Python to SQL query I am creating a store front page where the user will be able to search for items inside of an SQL data base. I am having issues with the python logic where I am trying to use the WHERE logic to find what the user hass entered. Here is my code: username = input("Enter your u...
Take user input from Python to SQL query
I am creating a store front page where the user will be able to search for items inside of an SQL data base. I am having issues with the python logic where I am trying to use the WHERE logic to find what the user hass entered. Here is my code: username = input("Enter your username >>> ") password = input("Enter your pa...
[ "cursor.execute as you are using it accepts two parameters, sql and parameters. I believe, according to sqlite docs and sqlite parameter reference, that you should define your string sql with sql = \"SELECT * FROM item_in_stock WHERE item_name = ?\" and pass parameters into cursor.execute in a tuple.\nAll in all, y...
[ 0 ]
[]
[]
[ "python", "sql" ]
stackoverflow_0074452290_python_sql.txt
Q: Tkinter use of function and class so this is my class which is Login_Window class Login_Window: def __init__(self, window): self.window = window self.window.rowconfigure(0, weight=1) self.window.columnconfigure(0, weight=1) self.window.state('zoomed') self.window.resizab...
Tkinter use of function and class
so this is my class which is Login_Window class Login_Window: def __init__(self, window): self.window = window self.window.rowconfigure(0, weight=1) self.window.columnconfigure(0, weight=1) self.window.state('zoomed') self.window.resizable(0, 0) self.window.title('Log...
[ "You should make the function a proper method (indent it to the same level of __init__ and include the self parameter). You can then call it with self inside the class, and with the instance outside of the class\nclass Login_Window:\n def __init__(self, window):\n ...\n for frame in (LoginPage, Reg...
[ 1 ]
[]
[]
[ "class", "function", "python", "tkinter", "window" ]
stackoverflow_0074451962_class_function_python_tkinter_window.txt
Q: TooManyRedirects: Exceeded 30 redirects can somenone give me a hint how to fix the error - TooManyRedirects: Exceeded 30 redirects.? import requests from bs4 import BeautifulSoup baseurl = 'https://www.roco.cc/' headers = { 'UserAgent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome...
TooManyRedirects: Exceeded 30 redirects
can somenone give me a hint how to fix the error - TooManyRedirects: Exceeded 30 redirects.? import requests from bs4 import BeautifulSoup baseurl = 'https://www.roco.cc/' headers = { 'UserAgent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36' } productlinks ...
[ "import requests\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nimport xlsxwriter\n\nbaseurl = 'https://www.roco.cc/'\n\nheaders = {\n 'Accept-Encoding': 'gzip, deflate, sdch',\n 'Accept-Language': 'en-US,en;q=0.8',\n 'Upgrade-Insecure-Requests': '1',\n 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_6...
[ 0 ]
[]
[]
[ "error_handling", "python", "web_scraping" ]
stackoverflow_0074439527_error_handling_python_web_scraping.txt
Q: Turning a list into a frequency dictionary I am currently attempting to turn a list into a frequency dictionary. I am reading a file, separating the file into each individual words on a line and attempting to turn each word into its own frequency dictionary in order to find how many times it occurs. I was wonderin...
Turning a list into a frequency dictionary
I am currently attempting to turn a list into a frequency dictionary. I am reading a file, separating the file into each individual words on a line and attempting to turn each word into its own frequency dictionary in order to find how many times it occurs. I was wondering how I would accomplish this. This is what I cu...
[ "The Counter class was designed for exactly this task.\nfrom collections import Counter\nwith open(file, 'r', encoding='utf-8') as fp:\n counts = Counter(fp.read().split())\n\nNow you can print counts and use its methods to get the most common words.\n", "If you are doing this for learning purposes (i.e. want ...
[ 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074452169_python.txt
Q: My script is reading my JSON file as empty when it's not? Here is my config file: { "credentials": { "server": "0.1.2.3,6666", "database": "db", "username": "user", "password": "password" } } Here is my python script in a separate file: import pandas as pd import datatest as dt import datetim...
My script is reading my JSON file as empty when it's not?
Here is my config file: { "credentials": { "server": "0.1.2.3,6666", "database": "db", "username": "user", "password": "password" } } Here is my python script in a separate file: import pandas as pd import datatest as dt import datetime import json import pyodbc with open(r"path_to_config.json",...
[ "Once you've read run readlines, the stream has finished and is now empty!\nIf you need the lines for something, then you should load the json separately, for instance (without indentation):\ndf = json.load(open(r\"path_to_config.json\", 'r')) # No indentation, outside the \"with\"\n\nand if you don't need the lin...
[ 0, 0, 0 ]
[]
[]
[ "json", "python" ]
stackoverflow_0074452418_json_python.txt
Q: How can i add a column to a dataframe based on a conditional of another dataframe that has a different length, but shared column data I have two dataframes of different lengths and different columns, but a shared column with the same identifying data. They look like this observations DF: index scientific_name pa...
How can i add a column to a dataframe based on a conditional of another dataframe that has a different length, but shared column data
I have two dataframes of different lengths and different columns, but a shared column with the same identifying data. They look like this observations DF: index scientific_name park_name observations 0 name1 park1 10 1 name2 park2 12 species DF: index scientific_name common_names category 0 name1...
[ "If you only wanted to add the \"category\" column from species to observations based on the shared column \"scientific_name\", this should work.\nobservations = pd.merge(observations, species[['scientific_name', 'category']])\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074452228_dataframe_pandas_python.txt
Q: Hide windows powershell when an application run I have coded an application in python using the pygame library. Everything work, but when I run the application, it also opens the shell. Is there a way to hide the shell? I have tried to mute the pygame 'welcome message', thinking that was it that opened the shell ...
Hide windows powershell when an application run
I have coded an application in python using the pygame library. Everything work, but when I run the application, it also opens the shell. Is there a way to hide the shell? I have tried to mute the pygame 'welcome message', thinking that was it that opened the shell when I run the application(don't pay attention to the...
[ "Run the application using pythonw instead of python. pythonw is the exact same Python interpreter, but it's marked as a Windows GUI application, so it doesn't require a connection to a console.\n" ]
[ 1 ]
[]
[]
[ "console_application", "pygame", "python", "windows" ]
stackoverflow_0074452462_console_application_pygame_python_windows.txt
Q: Can't Login on Twitch with Selenium I have a problem to login on twitch with selenium. After the bot has entered the credentials (I also tried to enter them manually) the error message appears: "Something went wrong. Please try again." And it won't let me in. Any suggestions? from selenium import webdriver from se...
Can't Login on Twitch with Selenium
I have a problem to login on twitch with selenium. After the bot has entered the credentials (I also tried to enter them manually) the error message appears: "Something went wrong. Please try again." And it won't let me in. Any suggestions? from selenium import webdriver from selenium.webdriver.common.by import By impo...
[ "To fix this issue \"Something went wrong. Please try again.\" you can use your own chrome profile, but it's better to create a new one to work with selenium, since the main profile will load all installed extensions that may not work with selenium.\nHow to create a new profile you can see here: How to open a Chrom...
[ 1, 0, 0, 0 ]
[]
[]
[ "automation", "python", "python_3.x", "selenium", "undetected_chromedriver" ]
stackoverflow_0073927843_automation_python_python_3.x_selenium_undetected_chromedriver.txt
Q: How to return to earlier (if statement) loop in python I would like to write a simple function (I'm beginner), in my script, to check and test user's API KEY from VirusTotal. That's my idea: Firstly, I would like to check if user type his API KEY in code or field is empty. Secondly, I would like to check if API KE...
How to return to earlier (if statement) loop in python
I would like to write a simple function (I'm beginner), in my script, to check and test user's API KEY from VirusTotal. That's my idea: Firstly, I would like to check if user type his API KEY in code or field is empty. Secondly, I would like to check if API KEY is correct. I had no idea how to check it the easiest way,...
[ "I think you want to achieve this:\nimport requests\nimport json\n\ndef auth_vt_apikey():\n \"\"\"This function test VirusTotal's Api Key\"\"\"\n url = 'https://www.virustotal.com/vtapi/v2/url/report'\n api_key = ''\n msg = \"Please enter your VirusTotal's API Key: \"\n\n while api_key == '':\n ...
[ 1, 1, 1 ]
[]
[]
[ "api", "if_statement", "python" ]
stackoverflow_0074452388_api_if_statement_python.txt
Q: How to detect gRPC server is down from gRPC AIO python client I've been facing this issue where I have a gRPC AIO python client sending bunch of configuration changes to the gRPC server, though it's a bi-directional RPC, client is not expecting any message from gRPC server. So whenever there is a configuration cha...
How to detect gRPC server is down from gRPC AIO python client
I've been facing this issue where I have a gRPC AIO python client sending bunch of configuration changes to the gRPC server, though it's a bi-directional RPC, client is not expecting any message from gRPC server. So whenever there is a configuration change the client sends gRPC message containing the configuration. It ...
[ "I was able to solve it using channel.get_state(). Below is the code snippet\nif queue.empty():\n if channel.get_state() != grpc.ChannelConnectivity.READY:\n break\n time.sleep(5)\n\n" ]
[ 0 ]
[]
[]
[ "grpc", "grpc_python", "python" ]
stackoverflow_0074447288_grpc_grpc_python_python.txt
Q: What is the simplest way in Python to plot a line profile of an image for a specific value of y, specifying the start and end point of the line? I have an image of the moon like this: moon picture from normal camera lens I want to plot the intensity profile along a line for a fixed value on the y axis, that runs a...
What is the simplest way in Python to plot a line profile of an image for a specific value of y, specifying the start and end point of the line?
I have an image of the moon like this: moon picture from normal camera lens I want to plot the intensity profile along a line for a fixed value on the y axis, that runs along the image like this: image above with line across a fixed y coordinate I want to be able to specify the start and end point of the coordinate by ...
[ "You can use \"hyperspy\" package to easily do this. Probably there are more straightforward (commonly used packages) that do the same. I am not an expert but the following will surely work.\nimport hyperspy.api as hs\n\nFirst, load the image\ns = hs.load(\"spam.jpg\")\n\nThen plot it.\ns.plot()\n\n#Then define the...
[ 0 ]
[]
[]
[ "image_processing", "matplotlib", "python", "scikit_image" ]
stackoverflow_0073039063_image_processing_matplotlib_python_scikit_image.txt
Q: Get rolling average without every timestamp I have data about how many messages each account sends aggregated to an hourly level. For each row, I would like to add a column with the sum of the previous 7 days messages. I know I can groupby account and date and aggregate the number of messages to the daily level, b...
Get rolling average without every timestamp
I have data about how many messages each account sends aggregated to an hourly level. For each row, I would like to add a column with the sum of the previous 7 days messages. I know I can groupby account and date and aggregate the number of messages to the daily level, but I'm having a hard time calculating the rolling...
[ "I hope I've understood your question right:\ndf[\"Date\"] = pd.to_datetime(df[\"Date\"])\ndf[\"Messages_tmp\"] = df.groupby([\"Account\", \"Date\"])[\"Messages\"].transform(\n \"sum\"\n)\n\ndf[\"Rolling Previous 7 Day Average\"] = (\n df.set_index(\"Date\")\n .groupby(\"Account\")[\"Messages_tmp\"]\n ....
[ 1 ]
[]
[]
[ "group_by", "pandas", "pandas_rolling", "python" ]
stackoverflow_0074452104_group_by_pandas_pandas_rolling_python.txt
Q: Tweepy find spaces by user ID Is there a way to search for a spaces by user id? I tried different values in the query but it didn't work. client = tweepy.Client(bearer_token=BEARER_TOKEN, consumer_key=CONSUMER_KEY, consumer_secret=CONSUMER_SECRET, ...
Tweepy find spaces by user ID
Is there a way to search for a spaces by user id? I tried different values in the query but it didn't work. client = tweepy.Client(bearer_token=BEARER_TOKEN, consumer_key=CONSUMER_KEY, consumer_secret=CONSUMER_SECRET, access_token=ACCESS_TOKE...
[ "You seem to be looking for the get_spaces method.\nspaces = client.get_spaces(user_ids=\"ID_NUMBER\")\n\n" ]
[ 0 ]
[]
[]
[ "python", "tweepy" ]
stackoverflow_0074445884_python_tweepy.txt
Q: "Wrapping around a matrix" to get the neighbors of a cell in a 2D array in Python Currently I am needing to grab all 8 neighbor cells of each cell in a 2D array/matrix Now, as you may know, cells at the begginings and ends of a matrix only have either 3 or 5 neighbor cells. However, I want to register cells from t...
"Wrapping around a matrix" to get the neighbors of a cell in a 2D array in Python
Currently I am needing to grab all 8 neighbor cells of each cell in a 2D array/matrix Now, as you may know, cells at the begginings and ends of a matrix only have either 3 or 5 neighbor cells. However, I want to register cells from the first and last rows and columns of the matrix as neighbors of the last and first row...
[ "It actually takes a relatively minor modification to your code to make this work. You're talking about a modulo operation, so that's what we use:\ndef getNeighbours(matrix):\n h , w = len(matrix), len(matrix[0])\n\n def idx_gen(y, x , w, h):\n v = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1),(1, -1)...
[ 1 ]
[]
[]
[ "cell", "matrix", "python" ]
stackoverflow_0074452472_cell_matrix_python.txt
Q: How to append string in the middle of a pre-existing csv line? I am fairly new to working with python and finally encountered a problem I cannot circumvent. I will make this fairly simple. I have a csv file with many lines that looks like this once I create a list variable: ['1\t10000\t11000\tabcdef\t1\t+\t10000\t...
How to append string in the middle of a pre-existing csv line?
I am fairly new to working with python and finally encountered a problem I cannot circumvent. I will make this fairly simple. I have a csv file with many lines that looks like this once I create a list variable: ['1\t10000\t11000\tabcdef\t1\t+\t10000\t11000\t"0,0,0"\t1\t1000\t0\n'] I want to add 2 new string variables...
[ "append() is for adding an element to a list. To add to a string, use += on the variable that contains the string, which is line[0].\nline[0] += f'\\t{str1}\\t{str2}'\n\nThat said, it's strange that you have the entire line as a single element of the list, rather than parsing the CSV row into a list of fields, usin...
[ 0, 0 ]
[]
[]
[ "append", "list", "python", "string" ]
stackoverflow_0074452463_append_list_python_string.txt
Q: Python: BST removal function deleting multiple nodes and reattaching duplicates I have 2 functions to remove nodes from a binary search tree. The first is to remove the root of the tree, and the second is to remove any other node in the tree. The issue is when testing after the 3rd iteration, things start to get w...
Python: BST removal function deleting multiple nodes and reattaching duplicates
I have 2 functions to remove nodes from a binary search tree. The first is to remove the root of the tree, and the second is to remove any other node in the tree. The issue is when testing after the 3rd iteration, things start to get wonky. Line for DEL: 45 deletes nodes 45, 30, 20, and the line for DEL: 40 does not de...
[ "Some of the issues are:\n\nIn the \"easy\" cases you are assuming that the last descent came by choosing the right child, as you set pn.right to something, but it might well be that you came via the left child, and then you should set pn.left.\n\npar_tree is not initialised to the correct node. To be consistent, i...
[ 1 ]
[]
[]
[ "binary_search_tree", "data_structures", "python" ]
stackoverflow_0074451672_binary_search_tree_data_structures_python.txt
Q: how to convert text file to mp3 using audiosegment in python so i have file text contains with binary number 1 and 0. i want to make the text file to mp3 file and i found pydub. but i got error: [Errno 22] Invalid argument: 'F:\KULIAH\SEMESTER8\SKRIPSI\MusicLockApp\txt\done.txt' i just trying to open my file and...
how to convert text file to mp3 using audiosegment in python
so i have file text contains with binary number 1 and 0. i want to make the text file to mp3 file and i found pydub. but i got error: [Errno 22] Invalid argument: 'F:\KULIAH\SEMESTER8\SKRIPSI\MusicLockApp\txt\done.txt' i just trying to open my file and try the pydub. can someone fix my code? def readbinaryfinal(): ...
[ "Looks like those slashes need escaping...\n'F:\\\\KULIAH\\\\SEMESTER8\\\\SKRIPSI\\\\MusicLockApp\\\\txt\\\\done.txt'\n(Or change them to forward slashes, / if python in windows copes with that?)\n" ]
[ 0 ]
[]
[]
[ "binary", "mp3", "pydub", "python", "text_files" ]
stackoverflow_0074452505_binary_mp3_pydub_python_text_files.txt
Q: Why this code is wrong? It provides the wrong answer def reversed_list(lst1, lst2): for index in range(len(lst1)): if lst1[index] != lst2[len(lst2) - 1- index]: return False else: return True It should copmare first element of the lst1 and the last element of lst2. When I run with next coma...
Why this code is wrong? It provides the wrong answer
def reversed_list(lst1, lst2): for index in range(len(lst1)): if lst1[index] != lst2[len(lst2) - 1- index]: return False else: return True It should copmare first element of the lst1 and the last element of lst2. When I run with next comands: print(reversed_list([1, 2, 3], [3, 2, 1])) print(reve...
[ "return immediately stops execution of the function, so your function only tests whether the first element of lst1 is equal to the last element of lst2. This is the correct thing to do if they don't match, but if they do match, you should continue your comparison.\n", "def reversed_list(lst1, lst2):\n for inde...
[ 1, 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074452586_python_python_3.x.txt
Q: Mariadb in Docker: MariaDB Connector/Python requires MariaDB Connector/C >= 3.2.4, found version 3.1.16 I try the following Dockerfile: # syntax=docker/dockerfile:1 FROM python:3.11-slim-bullseye EXPOSE 80 WORKDIR /app RUN apt-get update && apt-get install -y RUN apt install gcc libmariadb3 libmariadb-dev libmaria...
Mariadb in Docker: MariaDB Connector/Python requires MariaDB Connector/C >= 3.2.4, found version 3.1.16
I try the following Dockerfile: # syntax=docker/dockerfile:1 FROM python:3.11-slim-bullseye EXPOSE 80 WORKDIR /app RUN apt-get update && apt-get install -y RUN apt install gcc libmariadb3 libmariadb-dev libmariadb-dev-compat -y RUN pip install --upgrade pip RUN pip install Flask Flask-SQLAlchemy flask-marshmallow marsh...
[ "Pulling the latest MariaDB Connector/C from MariaDB managed to install with the latests python mariadb:\nFROM python:3.11-slim-bullseye\nEXPOSE 80\nWORKDIR /app\nRUN apt-get update && apt-get install -y gcc wget\nRUN wget https://dlm.mariadb.com/2678574/Connectors/c/connector-c-3.3.3/mariadb-connector-c-3.3.3-debi...
[ 0 ]
[]
[]
[ "docker", "mariadb", "python" ]
stackoverflow_0074429209_docker_mariadb_python.txt
Q: Create a voice channel only to view but not to join I want to create a statistics bot. If the channel is not yet created, it should be created automatically under a certain category. However, I want to set the permission so that nobody can connect, talk, create a video, or use the activity. How can I make it so t...
Create a voice channel only to view but not to join
I want to create a statistics bot. If the channel is not yet created, it should be created automatically under a certain category. However, I want to set the permission so that nobody can connect, talk, create a video, or use the activity. How can I make it so that everyone can see this channel, but no one can use it?...
[ "You can do this through discord overwrites:\nperms = channel.overwrites_for(ctx.guild.default_role)\nperms.connect = False\nawait channel.set_permissions(ctx.guild.default_role, overwrite=perms)\n\nThe code gets the channel's existing permissions, sets the connect permission to false and then applies to the defaul...
[ 2 ]
[]
[]
[ "discord", "discord.py", "python" ]
stackoverflow_0074452606_discord_discord.py_python.txt
Q: How to load list columns into a dataframe? I try to load "columns" from a python list object into a dataframe. This is my list object: list = type(api_response.results) -> <class 'list'> These are the values from the list object (I think this is a json structur): {'results': [{'data': [{'interval': '2022-11-11T10...
How to load list columns into a dataframe?
I try to load "columns" from a python list object into a dataframe. This is my list object: list = type(api_response.results) -> <class 'list'> These are the values from the list object (I think this is a json structur): {'results': [{'data': [{'interval': '2022-11-11T10:00:00.000Z/2022-11-11T10:30:00.000Z', ...
[ "you can use:\ndef get_metric(x):\n check=0\n vals=[]\n for i in range(0,len(x)):\n if len(x)==1:\n check=1\n for j in range(0,len(x) + check):\n print(i,j)\n vals.append(x[i]['data'][0]['metrics'][j]['metric'])\n return vals\n\ndef get_count(x):\n vals=...
[ 0 ]
[]
[]
[ "apache_spark", "json", "list", "python" ]
stackoverflow_0074432757_apache_spark_json_list_python.txt
Q: Iterate through the columns of a dataframe in Python and show value counts for the categorical variavles I'm new to Python and programming, so this is no doubt a newbie question. I want to show the value counts for each unique value of each categorical variable in a data frame, but what I've written isn't working...
Iterate through the columns of a dataframe in Python and show value counts for the categorical variavles
I'm new to Python and programming, so this is no doubt a newbie question. I want to show the value counts for each unique value of each categorical variable in a data frame, but what I've written isn't working. I'm trying to avoid writing separate lines for each individual column if I can help it. # Column Non-Nu...
[ "this works for me\nfor i in creditData.columns:\n if creditData[i].dtype != 'int64':\n print(creditData[i].value_counts())\n\n" ]
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0069586963_pandas_python.txt
Q: how to create a grouped bar chart in streamlit how to create grouped bar chart in Streamlit I have tried st.altair(chart) method to get the answer but still it shows the stacked bar chart instead of grouped bar chart A: You should be able to create the bar chart with Altair and then just pass it to Streamlit: ch...
how to create a grouped bar chart in streamlit
how to create grouped bar chart in Streamlit I have tried st.altair(chart) method to get the answer but still it shows the stacked bar chart instead of grouped bar chart
[ "You should be able to create the bar chart with Altair and then just pass it to Streamlit:\nchart = alt.Chart(prediction_table2, title='Simulated (attainable) and predicted yield ').mark_bar(\n opacity=1,\n ).encode(\n column = alt.Column('date:O', spacing = 5, header = alt.Header(labelOrient = \"bottom\"...
[ 0 ]
[]
[]
[ "python", "streamlit" ]
stackoverflow_0074442954_python_streamlit.txt
Q: Query for list of attribute instead of tuples in SQLAlchemy I'm querying for the ids of a model, and get a list of (int,) tuples back instead of a list of ids. Is there a way to query for the attribute directly? result = session.query(MyModel.id).all() I realize it's possible to do results = [r for (r,) in resul...
Query for list of attribute instead of tuples in SQLAlchemy
I'm querying for the ids of a model, and get a list of (int,) tuples back instead of a list of ids. Is there a way to query for the attribute directly? result = session.query(MyModel.id).all() I realize it's possible to do results = [r for (r,) in results] Is it possible for the query to return that form directly, i...
[ "When passing in ORM-instrumented descriptors such as a column, each result is a named tuple, even for just one column. You could use the column name in a list comprehension to 'flatten' the list (you can drop the .all() call, iteration retrieves the objects too):\nresult = [r.id for r in session.query(MyModel.id)]...
[ 62, 12, 0, 0 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0048466959_python_sqlalchemy.txt
Q: Shannon Entropy coding I am trying to write a Shannon entropy code and test it. Although testing with "aaaaa" should give me 0.0. it gives me -0.0 is there anyway to fix that? [CODE] A: Since -0.0 == 0.0 is true, what you have is mathematically correct. If you find the output unaesthetic, the fix is simple. Don...
Shannon Entropy coding
I am trying to write a Shannon entropy code and test it. Although testing with "aaaaa" should give me 0.0. it gives me -0.0 is there anyway to fix that? [CODE]
[ "Since -0.0 == 0.0 is true, what you have is mathematically correct. If you find the output unaesthetic, the fix is simple. Don't multiply by -1. Take the absolute value instead:\nfrom collections import Counter\nimport math\n\ndef entropy(string):\n counts = Counter(string)\n rel_freq = ((i/len(string)) for ...
[ 1 ]
[]
[]
[ "entropy", "function", "python" ]
stackoverflow_0074451861_entropy_function_python.txt
Q: Anaconda-Navigator.app missing after installation on M1 macOS Monterey I installed Anaconda, but it did not include the GUI app, Anaconda-Navigator app in the Applications folder. What do I need to do to get the GUI app? Details: Computer: 2021 14-inch MacBook Pro, M1 Max OS: macOS Monterey 12.5 A month ago, I had...
Anaconda-Navigator.app missing after installation on M1 macOS Monterey
I installed Anaconda, but it did not include the GUI app, Anaconda-Navigator app in the Applications folder. What do I need to do to get the GUI app? Details: Computer: 2021 14-inch MacBook Pro, M1 Max OS: macOS Monterey 12.5 A month ago, I had the full Intel version of Anaconda, including Anaconda-Navigator, running f...
[ "I'm struggling with these issues now. Still doesn't seem to be documented and Anaconda.com's list of included packages for the ARM installer threw me off by listing \"anaconda-navigator\" as included \"In Installer\".. https://docs.anaconda.com/anaconda/packages/py3.9_osx-arm64/\nWhat you need to do is, after run...
[ 3, 3, 1, 1 ]
[]
[]
[ "anaconda3", "python" ]
stackoverflow_0073188906_anaconda3_python.txt
Q: How to modify the number of the rows in .csv file and plot them I read .csv file using this command df = pd.read_csv('filename.csv', nrows=200) I set the number of rows to 200. So it will only get the data for 200 rows. (200 rows x 1 column) data 1 4.33 2 6.98 . . 200 100.896 I want to plot thes...
How to modify the number of the rows in .csv file and plot them
I read .csv file using this command df = pd.read_csv('filename.csv', nrows=200) I set the number of rows to 200. So it will only get the data for 200 rows. (200 rows x 1 column) data 1 4.33 2 6.98 . . 200 100.896 I want to plot these data however I would like to divide the number of rows by 50. (ther...
[ "Just divide the index by 50.\nHere an example :\nimport pandas as pd\nimport random\n\ndata = pd.DataFrame({'col1' : random.sample(range(300), 200)}, index = range(1,201))\ndata.index = data.index / 50\n\ndata\n\n\n\n\n\n\ncol1\n\n\n\n\n0.02\n196\n\n\n0.04\n198\n\n\n0.06\n278\n\n\n0.08\n209\n\n\n0.10\n36\n\n\n...\...
[ 0 ]
[]
[]
[ "matplotlib", "pandas", "python", "python_3.x" ]
stackoverflow_0074452709_matplotlib_pandas_python_python_3.x.txt
Q: validation_split in python keras I have a project in python, the goal is to build a model to predict an image of a cat or a dog. My training set has a size of 24977 images, i want to use 10% of that using validation_split in keras. However, when i run this code: model.fit(x_2, y, epochs = 5, validation_split = 0.1...
validation_split in python keras
I have a project in python, the goal is to build a model to predict an image of a cat or a dog. My training set has a size of 24977 images, i want to use 10% of that using validation_split in keras. However, when i run this code: model.fit(x_2, y, epochs = 5, validation_split = 0.1) this process only took 703 out of 2...
[ "You actually do already what you want.\nYour batch_size is None which defaults to 32.\n22480/32 = ceil(702.5) = 703\n" ]
[ 0 ]
[]
[]
[ "conv_neural_network", "keras", "python", "training_data" ]
stackoverflow_0074452423_conv_neural_network_keras_python_training_data.txt
Q: Execute js function in HTML page scraped by python to get json data I have a website with products https://www.svenssons.se/varumarken/swedese/lamino-fatolj-och-fotpall-lackad-bokfarskinn/?variantId=514023-01 When I inspect the html page I see they have all info in json format in script tag under window.INITIAL_DA...
Execute js function in HTML page scraped by python to get json data
I have a website with products https://www.svenssons.se/varumarken/swedese/lamino-fatolj-och-fotpall-lackad-bokfarskinn/?variantId=514023-01 When I inspect the html page I see they have all info in json format in script tag under window.INITIAL_DATA = JSON.parse('{"pa...') I tried to scrape the html with requests and ...
[ "Try:\nimport re\nimport js2py\nimport requests\n\n\nurl = \"https://www.svenssons.se/varumarken/swedese/lamino-fatolj-och-fotpall-lackad-bokfarskinn/?variantId=514023-01\"\n\nhtml_doc = requests.get(url).text\ndata = re.search(r\"window\\.INITIAL_DATA = (.*)\", html_doc)\ndata = js2py.eval_js(data.group(1))\n\npri...
[ 0 ]
[]
[]
[ "js2py", "json", "python", "python_requests", "screen_scraping" ]
stackoverflow_0074452728_js2py_json_python_python_requests_screen_scraping.txt