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: SQLAlchemy create_engine connection string with Microsoft ODBC datasource User DSN Does anyone know how to pass connection string into create_engine function? I use Window and has a ODBC datasource with DSN that set up by IT department. My ODBC DSN connects to Postgres database. Does anyone know the library or con...
SQLAlchemy create_engine connection string with Microsoft ODBC datasource User DSN
Does anyone know how to pass connection string into create_engine function? I use Window and has a ODBC datasource with DSN that set up by IT department. My ODBC DSN connects to Postgres database. Does anyone know the library or connection string to make this to work? Note that I cannot ask them for the username and pa...
[ "The below worked for me:\nengine=create_engine(\"mssql+pyodbc://user:password@DSNSTRING\") \n\n", "Yes, you can use the winreg library.\nBelow is a function I adapted from Bart Jonk.\nOriginal answer and function: https://stackoverflow.com/a/66528870/11080806\nfrom winreg import (ConnectRegistry, HKEY_CURRENT_US...
[ 0, 0 ]
[]
[]
[ "connection_string", "odbc", "postgresql", "python", "sqlalchemy" ]
stackoverflow_0046259313_connection_string_odbc_postgresql_python_sqlalchemy.txt
Q: Unable to parse arguments in Flask Restful for GET request With reference to the below code, I am getting an error while parsing the parameters for a GET request in Flask Restful. from flask_restful import Resource, reqparse class View_Result(Resource): def get(self): parser = reqparse.RequestParser...
Unable to parse arguments in Flask Restful for GET request
With reference to the below code, I am getting an error while parsing the parameters for a GET request in Flask Restful. from flask_restful import Resource, reqparse class View_Result(Resource): def get(self): parser = reqparse.RequestParser() parser.add_argument('aid', type=str) print('H...
[ "First, you've defined a get method, but reqparse is designed to work with a JSON request body in a POST (or PUT) request. You would need:\nfrom flask import Flask\nfrom flask_restful import Resource, reqparse, Api\n\napp = Flask(__name__)\napi = Api(app)\n\nclass View_Result(Resource):\n\n def post(self):\n\n ...
[ 1 ]
[]
[]
[ "flask", "flask_restful", "python" ]
stackoverflow_0074366800_flask_flask_restful_python.txt
Q: python xmlrpc server Cannot receive any XMLRPC from other computers I wrote this server using xmlrpc in python I want to be albe to access this server from any computer but it throws error. And another thing is that how can I make sure that the my server can support more than 1 client at a time? from xmlrpc.server...
python xmlrpc server Cannot receive any XMLRPC from other computers
I wrote this server using xmlrpc in python I want to be albe to access this server from any computer but it throws error. And another thing is that how can I make sure that the my server can support more than 1 client at a time? from xmlrpc.server import SimpleXMLRPCServer from xmlrpc.server import SimpleXMLRPCRequestH...
[ "Have a look onto the doc.\nIt seems you are confusing the ports. Server port is 8000, but client tries to connect on port 3000. That won't match.\nAlso it is good practice to make use of with statements, like shown in the doc.\n" ]
[ 1 ]
[]
[]
[ "client", "python", "rpc", "server", "xml" ]
stackoverflow_0074367236_client_python_rpc_server_xml.txt
Q: Python program to make a list even odd parity Task: count the number of operations required to make an array's values alternate between even and odd. Given: items = [6, 5, 9, 7, 3] (Example test case) Operations we can do: make n number of operations: floor(item/2) My code def change(expected): return 1 if ...
Python program to make a list even odd parity
Task: count the number of operations required to make an array's values alternate between even and odd. Given: items = [6, 5, 9, 7, 3] (Example test case) Operations we can do: make n number of operations: floor(item/2) My code def change(expected): return 1 if (expected == 0) else 0 def getMinimumOperations(...
[ "This seems like more of a math/logic problem than a Python problem.\nTo make a list's elements alternate between odd and even, either all the elements at even indices should be even and the rest odd, or all the elements at even indices should be odd and the rest even.\nIt appears you're not looking to change the o...
[ 0, 0 ]
[]
[]
[ "data_structures", "list", "python" ]
stackoverflow_0074367322_data_structures_list_python.txt
Q: django-filter how to add attribute to html tag under form I'm using Django-filter,I tried to add attributes by using widget and attrs: filter.py: class MyFilter(django_filters.FilterSet): messageText = django_filters.CharFilter(widget=(attrs={'style':'width: 20px', 'class':'form-select form-select-sm'})) ...
django-filter how to add attribute to html tag under form
I'm using Django-filter,I tried to add attributes by using widget and attrs: filter.py: class MyFilter(django_filters.FilterSet): messageText = django_filters.CharFilter(widget=(attrs={'style':'width: 20px', 'class':'form-select form-select-sm'})) class Meta: model = Mymodel fields = ['messageT...
[ "The widget for a CharFilter is a TextInput [Django-doc]:\nfrom django.forms import TextInput\n\n\nclass MyFilter(django_filters.FilterSet):\n messageText = django_filters.CharFilter(\n widget=TextInput(\n attrs={'style': 'width: 20px', 'class': 'form-select form-select-sm'}\n )\n )\n...
[ 2 ]
[]
[]
[ "django", "django_filter", "python", "python_3.x" ]
stackoverflow_0074367709_django_django_filter_python_python_3.x.txt
Q: "ValueError: 'url(#color-1)' is not a recognized color." SVG in manimce I am trying to display an SVG in my scene. when running, I encounter this error ValueError: 'url(#color-1)' is not a recognized color. does anyone know what I could do to fix this? this is my code: from manim import * class myScene(Scene): ...
"ValueError: 'url(#color-1)' is not a recognized color." SVG in manimce
I am trying to display an SVG in my scene. when running, I encounter this error ValueError: 'url(#color-1)' is not a recognized color. does anyone know what I could do to fix this? this is my code: from manim import * class myScene(Scene): def construct(self): self.play(FadeIn(SVGMobject("silver.svg")))
[ "This just means the SVG has a gradient. Gradients don't work with animations like FadeIn() or DrawBorderThenFill().\nTo fix this:\n\nOpen the SVG file in Adobe Illustrator or such\nGet the start hex and end hex of the gradient with the angle\nGive static colors to all gradients\nReplicate that in Manim using color...
[ 0 ]
[]
[]
[ "manim", "python" ]
stackoverflow_0070913015_manim_python.txt
Q: time data '2020–04–29 00:00:00' does not match format '%Y-%m-%d %H:%M:%S' I am getting this error time data '2020–04–29 00:00:00' does not match format '%Y-%m-%d %H:%M:%S' input for start date is '2020–04–29' I am trying to srap tweets using twint and I am geting this error ` config = twint.Config() config.Pa...
time data '2020–04–29 00:00:00' does not match format '%Y-%m-%d %H:%M:%S'
I am getting this error time data '2020–04–29 00:00:00' does not match format '%Y-%m-%d %H:%M:%S' input for start date is '2020–04–29' I am trying to srap tweets using twint and I am geting this error ` config = twint.Config() config.Pandas = True payload = json.dumps(request.GET) payload = json.loads(pay...
[ "The – is not a hyphen (-), but an en dash [wiki] with codepoint 0x2013. You thus parse this with:\nstartDate = datetime.strptime(startDate, '%Y–%m–%d %H:%M:%S')\n" ]
[ 4 ]
[]
[]
[ "datetime", "django", "python" ]
stackoverflow_0074367831_datetime_django_python.txt
Q: RuntimeError: Failed to process string with tex because latex could not be found I was trying to render text with LaTeX in Matplotlib. There is a demo provided by Matplotlib at https://matplotlib.org/3.1.1/gallery/text_labels_and_annotations/tex_demo.html. However, when I ran this demo, I got this error saying "Ru...
RuntimeError: Failed to process string with tex because latex could not be found
I was trying to render text with LaTeX in Matplotlib. There is a demo provided by Matplotlib at https://matplotlib.org/3.1.1/gallery/text_labels_and_annotations/tex_demo.html. However, when I ran this demo, I got this error saying "RuntimeError: Failed to process string with tex because latex could not be found", but I...
[ "I managed to solve this issue by installing texlive and latex. In apt based Linux, this command installs texlive:\nsudo apt install texlive texlive-latex-extra texlive-fonts-recommended dvipng\n\nlatex can be easily installed via pip:\npip install latex\n\n", "When I tried to change the standard font for matplot...
[ 16, 16, 15, 9, 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0058121461_matplotlib_python.txt
Q: Python Multiprocessing read and write to large file I have a large file of 120GB consisting of strings line by line. I would like to loop the file line by line replacing all the German characters ß with characters s. I have a working code, but it is very slow, and in the future, I should be replacing more German c...
Python Multiprocessing read and write to large file
I have a large file of 120GB consisting of strings line by line. I would like to loop the file line by line replacing all the German characters ß with characters s. I have a working code, but it is very slow, and in the future, I should be replacing more German characters. So I have been trying to cut the file in 6 pie...
[ "For a multiprocessing solution to be more performant than the equivalent single-processing one, the worker function must be sufficiently CPU-intensive such that running the function in parallel saves enough time to compensate for the additional overhead that multiprocessing incurs.\nTo make the worker function suf...
[ 0 ]
[]
[]
[ "chunks", "file", "multiprocessing", "python", "python_3.x" ]
stackoverflow_0074354733_chunks_file_multiprocessing_python_python_3.x.txt
Q: Multiple functions in Plotly Dash app call back? I'm creating a fitness chart using Plotly Dash that allows a user to enter a weight, which saves the data to an excel file, and then the user can refresh the screen to update the graph. I've been able to do them seperately by only having one function under the app.c...
Multiple functions in Plotly Dash app call back?
I'm creating a fitness chart using Plotly Dash that allows a user to enter a weight, which saves the data to an excel file, and then the user can refresh the screen to update the graph. I've been able to do them seperately by only having one function under the app.callback section. How can I have both functions? I can ...
[ "The main issue you're having is the callback is being called at initial start of program, so to fix this pass in prevent_initial_callbacks=True into dash app instance.\nThen you need 2 separate inputs for each button and don't use an anchor for Refresh button it won't work.\nimport dash\nfrom dash import html, dcc...
[ 1 ]
[]
[]
[ "plotly_dash", "python" ]
stackoverflow_0074366054_plotly_dash_python.txt
Q: Selenium can't get this class I'm trying to get the button clicked but Selenium cant reach that class : access-grants__flows-area__create-button container key_cli_btn = self._get_xpath("//div[@class='/html/body/div/div/div[1]/div/div[3]/div/div[2]/div[2]/div[3]/div[4]/div'") print(key_cli_btn) This xpath is ...
Selenium can't get this class
I'm trying to get the button clicked but Selenium cant reach that class : access-grants__flows-area__create-button container key_cli_btn = self._get_xpath("//div[@class='/html/body/div/div/div[1]/div/div[3]/div/div[2]/div[2]/div[3]/div[4]/div'") print(key_cli_btn) This xpath is invalid : selenium.common.excep...
[ "I have no idea what self._get_xpath is, but generally something like this probably should work:\nkey_cli_btn = driver.find_element(By.XPATH, \"//div[@class='access-grants__flows-area__create-button container']\")\n\n" ]
[ 0 ]
[]
[]
[ "python", "selenium", "selenium_webdriver", "webdriver", "xpath" ]
stackoverflow_0074367860_python_selenium_selenium_webdriver_webdriver_xpath.txt
Q: Clear Subprocess.popen's output (so far) I want to run a binary with subprocess. The binary acts similarly (but is different from) bash's tail -f <file name> which prints certain number of lines from an existing continuous stream, while also printing any new outputs as they appear. I want to run the command with s...
Clear Subprocess.popen's output (so far)
I want to run a binary with subprocess. The binary acts similarly (but is different from) bash's tail -f <file name> which prints certain number of lines from an existing continuous stream, while also printing any new outputs as they appear. I want to run the command with subprocess.Popen(), clear stdout so far after a...
[ "You can do a non-blocking read on the stream to consume everything output so far. This is pretty easy on Unix-like systems that support os.set_blocking():\n# switch to non-blocking mode and read everything up to this point\nos.set_blocking(process.stdout.fileno(), False)\nprocess.stdout.read()\n# go back to blocki...
[ 1 ]
[]
[]
[ "python", "python_3.x", "stdout", "subprocess" ]
stackoverflow_0074366851_python_python_3.x_stdout_subprocess.txt
Q: How to force a rotating name with python's TimedRotatingFileHandler? I am trying to use TimedRotatingFileHandler to keep daily logs in separate log files. The rotation works perfectly as intended, but what I don't like how it does is the naming of the files. If I set a log file as my_log_file.log, this will be the...
How to force a rotating name with python's TimedRotatingFileHandler?
I am trying to use TimedRotatingFileHandler to keep daily logs in separate log files. The rotation works perfectly as intended, but what I don't like how it does is the naming of the files. If I set a log file as my_log_file.log, this will be the "today's" log file, and when it changes day at midnight it will be rename...
[ "I have created a class ParallelTimedRotatingFileHandler mainly aimed at allowing multiple processes writing in parallel to a log file.\nThe problems with parallel processes solved by this class, are:\n\nThe rollover moment when all processes are trying to copy or rename the same file at the same time, gives errors...
[ 6, 4, 3, 0, 0 ]
[]
[]
[ "filehandler", "logging", "python" ]
stackoverflow_0024649789_filehandler_logging_python.txt
Q: How to access the cx/cy coordinates of a circle from svg element on atptour.com I am working on a data science project for school and I want to get the ball coordinates from a page like this one: https://www.atptour.com/en/stats/second-screen/archive/2021/403/MS001 My goal is to get the serve placement for J.Sinne...
How to access the cx/cy coordinates of a circle from svg element on atptour.com
I am working on a data science project for school and I want to get the ball coordinates from a page like this one: https://www.atptour.com/en/stats/second-screen/archive/2021/403/MS001 My goal is to get the serve placement for J.Sinner and H.Hurkacz on both the deuce and add sides, for 1st and 2nd serves. Because of t...
[ "This Xpath will get all circle under #ball-plot\n//*[@id=\"ball-plots\"]/*[local-name()=\"circle\"]\n\n" ]
[ 0 ]
[]
[]
[ "python", "selenium", "svg", "web_scraping", "xpath" ]
stackoverflow_0074364303_python_selenium_svg_web_scraping_xpath.txt
Q: multiply .mhd images (image and mask) / python I want to multiply two images in .mhd format. (One is the medical image and the other is the desired mask) But no matter what I search, I can't find the right code. I would appreciate it if you could guide me, what should I do? A: You can use SimpleITK for this. Ins...
multiply .mhd images (image and mask) / python
I want to multiply two images in .mhd format. (One is the medical image and the other is the desired mask) But no matter what I search, I can't find the right code. I would appreciate it if you could guide me, what should I do?
[ "You can use SimpleITK for this.\nInstall:\n$ pip install SimpleITK\n\nSample code:\nimport SimpleITK as sitk\n\n# load data\nimg = sitk.ReadImage(\"image_file.mhd\")\nmask = sitk.ReadImage(\"mask.mhd\")\n\n# you can only multiply images with the same voxel type\nprint(\"Type (img) =\", img.GetPixelIDTypeAsString(...
[ 1 ]
[]
[]
[ "deep_learning", "medical_imaging", "python" ]
stackoverflow_0074334737_deep_learning_medical_imaging_python.txt
Q: How to change the url of an app in Django to custom url I have an app in my Django project that called Stressz. So the url of my app is: http://localhost:8000/stressz/ http://localhost:8000/stressz/siker http://localhost:8000/stressz/attitud How can I change the url without changing the name of the app from the a...
How to change the url of an app in Django to custom url
I have an app in my Django project that called Stressz. So the url of my app is: http://localhost:8000/stressz/ http://localhost:8000/stressz/siker http://localhost:8000/stressz/attitud How can I change the url without changing the name of the app from the above url to something like this: http://localhost:8000/mpa ht...
[ "Look into your root urls.py, which you can usually find in your project (not app) folder. There has to be a line similar to this:\nurlpatterns = [\n path('stressz', include('stressz.urls')),\n]\n\nIf you then change it to:\nurlpatterns = [\n path('mpa', include('stressz.urls')),\n]\n\nIt should work as you i...
[ 2, 0 ]
[]
[]
[ "django", "python", "url" ]
stackoverflow_0068571707_django_python_url.txt
Q: Pandas groupby day in range and category I have a dataframe in the following format and want to sum the weight column by category and by day (where day is in the start-end range) i.e. from this: batch category start_day end_day duration weight XX001 AAA 2022-01-06 2022-01-14 6 0.1250 XX002 BBB 2022-01-08 2022-0...
Pandas groupby day in range and category
I have a dataframe in the following format and want to sum the weight column by category and by day (where day is in the start-end range) i.e. from this: batch category start_day end_day duration weight XX001 AAA 2022-01-06 2022-01-14 6 0.1250 XX002 BBB 2022-01-08 2022-01-12 4 0.2500 XX003 AAA 2022-01-07 20...
[ "something like\ndf.groupby([\"category\",\"start_day\"]).sum()[\"weight\"]\n\ngroupby - groups in to sub dfs and you can actually iterate these with\n\nfor grouped_df, name in df.groupby([\"category\",\"start_day\"]):\n\n print(name)\n\n\n.sum() then sum the column\n\n[\"weight\"] select the weight column\n\n\n...
[ 0 ]
[]
[]
[ "group_by", "pandas", "python" ]
stackoverflow_0074368011_group_by_pandas_python.txt
Q: Importing Python variable into text case in Robot Framework I'm trying to use an global variable from python but i didn't find a way to use it in my custom keywork My helper.robot it's look like this: *** Settings *** Resource main.resource Library SeleniumLibrary Variables ...
Importing Python variable into text case in Robot Framework
I'm trying to use an global variable from python but i didn't find a way to use it in my custom keywork My helper.robot it's look like this: *** Settings *** Resource main.resource Library SeleniumLibrary Variables Login *** Variables *** ${email} *** Keywords *** Login ...
[ "You should create robot test/suite/global variable ${email} that is accessible from robot file.\nemail = fake.ascii_safe_email()\nBuiltIn().set_global_variable(\"${email}\", email)\n\n" ]
[ 1 ]
[]
[]
[ "python", "robotframework" ]
stackoverflow_0074349385_python_robotframework.txt
Q: Python dataframe: labelling (1-0) ) adjacent rows upon condition I have a column number containing number and NaN. I want to add a column label identifying by 1 and 0 the "zones" where we have a number: the zone includes adjacents (above and below) rows. The result should look like below: Number Label Nan 0...
Python dataframe: labelling (1-0) ) adjacent rows upon condition
I have a column number containing number and NaN. I want to add a column label identifying by 1 and 0 the "zones" where we have a number: the zone includes adjacents (above and below) rows. The result should look like below: Number Label Nan 0 Nan 1 4 1 Nan 1 Nan 0 Nan 0 Nan 1 8.9...
[ "Shift based method\n(Spoiler alert: it was my first answer, but not my best. This is not the fastest. See end of post for faster solution)\nAs long as your condition remains \"number on previous, current or next row\" (I mean, if you don't want to extend that to \"k previous rows or k next rows\") the shift method...
[ 1, 0 ]
[]
[]
[ "dataframe", "numpy", "pandas", "python" ]
stackoverflow_0074366772_dataframe_numpy_pandas_python.txt
Q: Do async responses get stored or processed immediately? Say I'm communicating with an API which, for any valid parameter, responds with a very long list. I want to extract the first element of this list for several parameters. My code looks like this (feedback welcome): import asyncio import aiohttp URL = 'https:...
Do async responses get stored or processed immediately?
Say I'm communicating with an API which, for any valid parameter, responds with a very long list. I want to extract the first element of this list for several parameters. My code looks like this (feedback welcome): import asyncio import aiohttp URL = 'https://api2.binance.com/api/v3/trades?symbol=' symbols = ['BTCUSD...
[ "Yes, all of the responses will be stored in all_trades, before being processed in the next lines. To avoid that, you can discard what you don't need before it is collected from all tasks. Approximately this way:\nasync def get_one_trade(session, symbol):\n x = await session.get(URL + symbol)\n return (await ...
[ 2 ]
[]
[]
[ "async_await", "asynchronous", "python", "python_asyncio" ]
stackoverflow_0074367629_async_await_asynchronous_python_python_asyncio.txt
Q: Is it possible to add raw bytes to a TarFile object in python 3? I'm creating a Python script that does a backup of various files, and data on my server. It looks something like this: #!/usr/bin/env python3 import subprocess import tarfile import os DIRS_TO_BACKUP = [] FILES_TO_BACKUP = [] backup_destination = "...
Is it possible to add raw bytes to a TarFile object in python 3?
I'm creating a Python script that does a backup of various files, and data on my server. It looks something like this: #!/usr/bin/env python3 import subprocess import tarfile import os DIRS_TO_BACKUP = [] FILES_TO_BACKUP = [] backup_destination = "/tmp/out.tar.gz" # Code that adds directories to DIRS_TO_BACKUP DIRS_...
[ "As you can see in the tarfile docs: https://docs.python.org/3/library/tarfile.html, you can add a file object to a tar using gettarinfo and addfile. Just convert your bytes to a file object using io.BytesIO.\n#!/usr/bin/env python3\n\nimport subprocess\nimport tarfile\nimport os\nimport io\n\nDIRS_TO_BACKUP = []\n...
[ 0, 0 ]
[]
[]
[ "python", "python_3.x", "tarfile" ]
stackoverflow_0064878940_python_python_3.x_tarfile.txt
Q: How to create a python class with a single use context If we look at python docs it states: Most context managers are written in a way that means they can only be used effectively in a with statement once. These single use context managers must be created afresh each time they’re used - attempting to use them a s...
How to create a python class with a single use context
If we look at python docs it states: Most context managers are written in a way that means they can only be used effectively in a with statement once. These single use context managers must be created afresh each time they’re used - attempting to use them a second time will trigger an exception or otherwise not work c...
[ "Here is a possible solution:\nfrom functools import wraps\n\n\nclass MultipleCallToCM(Exception):\n pass\n\n\ndef single_use(cls):\n if not (\"__enter__\" in vars(cls) and \"__exit__\" in vars(cls)):\n raise TypeError(f\"{cls} is not a Context Manager.\")\n\n org_new = cls.__new__\n @wraps(org_n...
[ 1, 0, 0 ]
[]
[]
[ "contextmanager", "python", "with_statement" ]
stackoverflow_0074364470_contextmanager_python_with_statement.txt
Q: How to find peaks in a noisy signal or estimate its number? I have a series of signals, sample data looks like this: We can see that there are 5 peaks there. I can assume that there won't be more than 1 pick every 10 samples, usually there is one pick every 20 to 40 samples. I was trying to fit a polynomial and t...
How to find peaks in a noisy signal or estimate its number?
I have a series of signals, sample data looks like this: We can see that there are 5 peaks there. I can assume that there won't be more than 1 pick every 10 samples, usually there is one pick every 20 to 40 samples. I was trying to fit a polynomial and then use scipy.signal.find_peaks and it kind of works but I have t...
[ "I would use find_peaks of scipy but filtering the signal with a moving average mean:\nimport numpy as np\nimport matplotlib.pyplot as plt\n\narr = np.array([254256., 254390., 251546., 250561., 250603., 250128., 251000.,\n 252612., 253552., 253776., 252843., 251800., 250808., 250569.,\n 249804., 247755., 247685...
[ 1, 0 ]
[]
[]
[ "algorithm", "max", "python", "signal_processing" ]
stackoverflow_0074364841_algorithm_max_python_signal_processing.txt
Q: N = 10, = 100, = 1000 in a range I have the the sum from (i = 1) to N is 1 + 2 + 3 + 4 ... + N I found this program to calculate the sum for i in range(1,100) num1, num2 = 1, 100 sum = int((num2*(num2+1)/2) - (num1*(num1+1)/2) + num1) print(sum) This works, but what if I want to know N = 10, or N = 100? A: Here...
N = 10, = 100, = 1000 in a range
I have the the sum from (i = 1) to N is 1 + 2 + 3 + 4 ... + N I found this program to calculate the sum for i in range(1,100) num1, num2 = 1, 100 sum = int((num2*(num2+1)/2) - (num1*(num1+1)/2) + num1) print(sum) This works, but what if I want to know N = 10, or N = 100?
[ "Here is a better way to do that:\ndef sum(n):\n return int(n * (n + 1) // 2)\n\nprint(sum(10))\nprint(sum(100))\n\n", "This program works by pairing the numbers together from the end to the beginning. For example, to find the sum of the list 1, 2, 3, 4, 5, 6, you can pair 1 and 6 to make 7, 2 and 5 to make 7,...
[ 1, 0, 0 ]
[]
[]
[ "for_loop", "math", "python" ]
stackoverflow_0074368007_for_loop_math_python.txt
Q: Sum() returns bad value when used in a list of numbers with many decimals a = [0.0021, 0.0087] s = sum(a) print(s) Outcome: 0.010799999999999999 When executing the program above, the result is complex and eronated. After performing multiple tests, including: a = 0.0021 b = 0.0087 The result is the same. I tried ...
Sum() returns bad value when used in a list of numbers with many decimals
a = [0.0021, 0.0087] s = sum(a) print(s) Outcome: 0.010799999999999999 When executing the program above, the result is complex and eronated. After performing multiple tests, including: a = 0.0021 b = 0.0087 The result is the same. I tried different combinations of numbers and it seems that only these 2 have such an o...
[ "I would say that this is floating point arithmetics error. Or I think there were some performance improvements done to math operations in Python which cause this, you can look more into it if you want by searching for PyNumber_Add and BINARY_ADD operation\n" ]
[ 0 ]
[]
[]
[ "function", "python", "sum" ]
stackoverflow_0074368010_function_python_sum.txt
Q: How to write speaker output to a file sounddevice Is there a way that I can use the python library sounddevice to write the output through my speakers to a file? For example if I were to play any sounds through my computer they would be written to a mp4/wav file. A: You can just specify the output device - for e...
How to write speaker output to a file sounddevice
Is there a way that I can use the python library sounddevice to write the output through my speakers to a file? For example if I were to play any sounds through my computer they would be written to a mp4/wav file.
[ "You can just specify the output device - for example:\nimport sounddevice as REC\nREC.default.device = 'Speakers (Realtek High Definition Audio), Windows DirectSound'\n\nTo get all the sound devices that sounddevice recognizes you can use this command in ur command line:\nthis: py -m sounddevice\nor this: pytho...
[ 2, 0 ]
[ "This is a solution: (See comments)\nimport sounddevice as sd\nfrom scipy.io.wavfile import write\n\nfs = 44100 # Sample rate\nseconds = 3 # Duration of recording\nsd.default.device = 'digital output' # Speakers full name here\n\nmyrecording = sd.rec(int(seconds * fs), samplerate=fs, channels=2)\nsd.wait() # Wa...
[ -1 ]
[ "audio", "audio_recording", "python", "python_3.x", "python_sounddevice" ]
stackoverflow_0062596168_audio_audio_recording_python_python_3.x_python_sounddevice.txt
Q: How to insert newlines on argparse help text? I'm using argparse in Python 2.7 for parsing input options. One of my options is a multiple choice. I want to make a list in its help text, e.g. from argparse import ArgumentParser parser = ArgumentParser(description='test') parser.add_argument('-g', choices=['a', 'b...
How to insert newlines on argparse help text?
I'm using argparse in Python 2.7 for parsing input options. One of my options is a multiple choice. I want to make a list in its help text, e.g. from argparse import ArgumentParser parser = ArgumentParser(description='test') parser.add_argument('-g', choices=['a', 'b', 'g', 'd', 'e'], default='a', help="Some opti...
[ "Try using RawTextHelpFormatter to preserve all of your formatting:\nfrom argparse import RawTextHelpFormatter\nparser = ArgumentParser(description='test', formatter_class=RawTextHelpFormatter)\n\nIt's similar to RawDescriptionHelpFormatter but instead of only applying to the description and epilog, RawTextHelpForm...
[ 533, 95, 41, 14, 10, 3, 3, 2, 1, 0, 0, 0, 0 ]
[]
[]
[ "argparse", "python" ]
stackoverflow_0003853722_argparse_python.txt
Q: Delete all lines that start with comments and print statements from Python file I want to delete all lines that start with comments and print statements from my file. This code works on lines that don't start with indents: with open("in.py", "r") as file_input: with open("out.py", "w") as file_output: ...
Delete all lines that start with comments and print statements from Python file
I want to delete all lines that start with comments and print statements from my file. This code works on lines that don't start with indents: with open("in.py", "r") as file_input: with open("out.py", "w") as file_output: for line in file_input: if line.startswith('#'): continu...
[ "This issue is that you're ignoring whitespace. All you need to do is run .lstrip() to get rid of leading whitespace. Just do this:\nwith open(\"in.py\", \"r\") as file_input:\n with open(\"out.py\", \"w\") as file_output:\n for line in file_input:\n stripped = line.lstrip()\n if str...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074368133_python.txt
Q: I am getting TLE in CSES Dice Combinations Question I am getting TLE error when I tried to submit my python code in CSES. It is the first problem of CSES Problem Set. Below is my Python code CODE: import sys,io,os input = io.BytesIO(os.read(0, \os.fstat(0).st_size)).readline n=int(input()) mod=1000000007 if(n>=1 a...
I am getting TLE in CSES Dice Combinations Question
I am getting TLE error when I tried to submit my python code in CSES. It is the first problem of CSES Problem Set. Below is my Python code CODE: import sys,io,os input = io.BytesIO(os.read(0, \os.fstat(0).st_size)).readline n=int(input()) mod=1000000007 if(n>=1 and n<7): print(2**(n-1)) else: dp=[0]*(n+1) ...
[ "Here are some optimizations you can do. dp[i] is already after modulo, so need not do\ndp[i]=(dp[i-1]%mod+dp[i-2]%mod+dp[i-3]%mod+dp[i-4]%mod+dp[i-5]%mod+dp[i-6]%mod) %mod\n\nBut Just:\ndp[i] = (dp[i-1] + dp[i-2] + dp[i-3] + dp[i-4] + dp[i-5] + dp[i-6])%mod\n\nyou can also get rid of the whole dp array. If your ob...
[ 0 ]
[]
[]
[ "dynamic_programming", "python" ]
stackoverflow_0074357062_dynamic_programming_python.txt
Q: Plotting 3d plot in python I am trying to plot a 3d plot in Python but not able to do as required. I am using each value of d and then for each value d I have 4 values of f_sample for which I am calculating FSPL. Later appending values in a single array I want to plot d, f_sample, and FSPL_remotes in a same 3d plo...
Plotting 3d plot in python
I am trying to plot a 3d plot in Python but not able to do as required. I am using each value of d and then for each value d I have 4 values of f_sample for which I am calculating FSPL. Later appending values in a single array I want to plot d, f_sample, and FSPL_remotes in a same 3d plot. Since d and f_sample have sam...
[ "just adding some boilerplate from matplotlib 3d surface\nimport math\nd =[23.1476,125.4207,146.0814,129.8549]\nf_sample = [902,904,906,908]\nFSPL_remotes = []\n\nfor i in d:\n for j in f_sample:\n FSPL = 32.44 + 20*math.log10(i) +20*math.log10(j)\n FSPL_remotes.append(FSPL)\n \nimport matpl...
[ 1 ]
[]
[]
[ "for_loop", "matplotlib", "plot", "python" ]
stackoverflow_0074368129_for_loop_matplotlib_plot_python.txt
Q: How to extrude along a spline in the gmsh python module? what is the syntax for it? I am working on a research project where I need to create meshes of fiber models to test some stuff later. For that, I'm trying to make an extrusion along a spline in gmsh python module and I don't what is the syntax for that to wr...
How to extrude along a spline in the gmsh python module? what is the syntax for it?
I am working on a research project where I need to create meshes of fiber models to test some stuff later. For that, I'm trying to make an extrusion along a spline in gmsh python module and I don't what is the syntax for that to write the code. Is it even possible to do that in the gmsh python module or only just in th...
[ "I am probably facing similiar issues with the python api of gmsh. Can you add some more details on the error-messanges? Can you export a geometry with the python-script and show the geometry in the gmsh-gui?\nI can create a 2d-mesh. But i am failing with the extrusion and the 3d-meshing.\nenter image description h...
[ 0 ]
[]
[]
[ "gmsh", "python" ]
stackoverflow_0073227237_gmsh_python.txt
Q: Read multiple csv files with Pandas and assign different names I am inside a directory with a series of .csv files that I would like to assign to their own variable. The idea is that I want to tidy up each dataframe on its own first within a loop, then concantenate everything at the end (my code non-"loopified" is...
Read multiple csv files with Pandas and assign different names
I am inside a directory with a series of .csv files that I would like to assign to their own variable. The idea is that I want to tidy up each dataframe on its own first within a loop, then concantenate everything at the end (my code non-"loopified" is a series of dropping, renaming, and group-by/pivot commands. I wrot...
[ "The error here happens because it's not legal for a variable name to start with a number. Your code would have worked otherwise.\nHowever, constructing variable names from strings is usually a bad idea. Use a dict instead:\ndfs = {}\nfor f in files:\n dfs[f] = pd.read_csv(f)\n\n" ]
[ 4 ]
[]
[]
[ "csv", "pandas", "python", "string", "string_formatting" ]
stackoverflow_0074368201_csv_pandas_python_string_string_formatting.txt
Q: Webscraping using python for a webpage having "Mehr Anseigen" i.e(eng: Show more) I have been trying to scrape a web page and get a few details into an excel or CSV. But unable to get everything since the page is having Mehr Anzeigen which is 'Show more' in German. URL: https://www.gelbeseiten.de/suche/architektur...
Webscraping using python for a webpage having "Mehr Anseigen" i.e(eng: Show more)
I have been trying to scrape a web page and get a few details into an excel or CSV. But unable to get everything since the page is having Mehr Anzeigen which is 'Show more' in German. URL: https://www.gelbeseiten.de/suche/architekturb%c3%bcros/aachen?umkreis=21000 From the above ``URL`` I would like to extract: <h2> ...
[ "I have a function (linkToSoup_selenium) that can click through the button a set number of times and then scrape the page\n# import pandas # for saving as table\n# from linkToSoup_selenium import * ## OR PASTE HERE\n\ncfList = (\n ['//div[@id=\"cmpbox\"]//span[@id=\"cmpbntyestxt\"]'] # \"Akzeptieren\" - for cook...
[ 0 ]
[]
[]
[ "html", "python", "web_scraping" ]
stackoverflow_0074350179_html_python_web_scraping.txt
Q: How do i convert duration column into hours and minutes? I'm currently sitting in Jupyter Notebook on a dataset that has a duration column that looks like this; I still feel like a newbie at programming at programming, so i'm not sure to convert this data so it can be visualized in graphs in jupyter. Right now it...
How do i convert duration column into hours and minutes?
I'm currently sitting in Jupyter Notebook on a dataset that has a duration column that looks like this; I still feel like a newbie at programming at programming, so i'm not sure to convert this data so it can be visualized in graphs in jupyter. Right now its just all strings in the column. Does anyone knows how i do t...
[ "Assuming each time in your data is a string and assuming the formats are all as shown then you could use a parser after a little massaging of the data:\nfrom dateutil import parser\n\ns = \"1 hour 35 mins\"\nprint(s)\n\ns = s.replace('min', 'minute')\ntime = parser.parse(s).time()\nprint(time)\n\nThis somewhat les...
[ 1, 0 ]
[]
[]
[ "jupyter", "jupyter_notebook", "python", "time" ]
stackoverflow_0074367390_jupyter_jupyter_notebook_python_time.txt
Q: I'm trying to make a code that when user press the button, it exports excel file I don't know why, but it says that i can't iterate thru db model class 'Claim'. Does anyone have idea how to fix it? Here is my code: @auth.route('/download') def excel_downlaod(): # Function is defined somewhere else data = d...
I'm trying to make a code that when user press the button, it exports excel file
I don't know why, but it says that i can't iterate thru db model class 'Claim'. Does anyone have idea how to fix it? Here is my code: @auth.route('/download') def excel_downlaod(): # Function is defined somewhere else data = db.session.query(Claim).all() # Convert result set to pandas date frame and add co...
[ "You can save the step of converting the results of the database query into a DataFrame by executing the query directly in pandas with read_sql.\nThe following example shows you how to generate the file and serve it with send_file.\nfrom flask import send_file\n\n# ...\n\n@auth.route('/download')\ndef excel_downloa...
[ 0 ]
[]
[]
[ "flask", "flask_sqlalchemy", "mysql", "pandas", "python" ]
stackoverflow_0074367585_flask_flask_sqlalchemy_mysql_pandas_python.txt
Q: Pivot dataframe into one level / rename df.pivot() output columns I have a dataframe, df_res with volumetric and mean and standard deviation jacobian values against ID strings (subjid), software type ran (pipeline), and anatomical region labels (label_id): df_res = subjid pipeline label_id volume_(...
Pivot dataframe into one level / rename df.pivot() output columns
I have a dataframe, df_res with volumetric and mean and standard deviation jacobian values against ID strings (subjid), software type ran (pipeline), and anatomical region labels (label_id): df_res = subjid pipeline label_id volume_(mm^3) mean_jacobian stdev_jacobian 0 100007_t0 Rigid ...
[ "Try:\ndf = df.pivot(index=[\"subjid\", \"pipeline\"], columns=[\"label_id\"])\ndf.columns = [f\"label{b}_{a}\" for a, b in df.columns]\n\nprint(df.reset_index())\n\nPrints:\n subjid pipeline label0_volume_(mm^3) label1_volume_(mm^3) label2_volume_(mm^3) label3_volume_(mm^3) label0_mean_jacobian label1_m...
[ 1, 1 ]
[]
[]
[ "dataframe", "group_by", "pandas", "pivot", "python" ]
stackoverflow_0074368083_dataframe_group_by_pandas_pivot_python.txt
Q: OpenCV: Why is one trackbar shorter than others? I have encountered a strange issue and would like someone to explain it to me, so I can avoid it in the future. When I place multiple trackbars (6 in my case) the last trackbar is much shorter. Here is the base code: import cv2 def nothing(arguments): pass cv2...
OpenCV: Why is one trackbar shorter than others?
I have encountered a strange issue and would like someone to explain it to me, so I can avoid it in the future. When I place multiple trackbars (6 in my case) the last trackbar is much shorter. Here is the base code: import cv2 def nothing(arguments): pass cv2.namedWindow('TrackBars') cv2.resizeWindow('TrackBars'...
[ "It's a bug in OpenCV that seems to have been lingering there for a while. After a few hours of digging (and uncovering few other issues in the code along the way), I think I've nabbed it and filed a bug report with proposed resolution. I'll be making a pull request in the near future, and hopefully this can be res...
[ 3 ]
[]
[]
[ "opencv", "python" ]
stackoverflow_0074358897_opencv_python.txt
Q: How do you remove words with 3 of the same letters in a row, such as abbbe or accce from a list in Python? I found a similar question for R but not for Python. Apologies if it does exist, but I cannot find it. I have a long list of words out of the dictionary. I'm just trying to get rid of all the words that hav...
How do you remove words with 3 of the same letters in a row, such as abbbe or accce from a list in Python?
I found a similar question for R but not for Python. Apologies if it does exist, but I cannot find it. I have a long list of words out of the dictionary. I'm just trying to get rid of all the words that have 3 of the same letters in a row. I used to program back in the day, and I probably would have gone in and itera...
[ "One option is to use re:\nimport re\n\nwords = [\"abbbe\", \"abcde\", \"accce\"]\n\noutput = [word for word in words if not re.search(r\"(.)\\1{2}\", word)]\nprint(output) # ['abcde']\n\nIn the regex, (.) captures a character and then \\1{2} checks whether the captured character is repeated twice afterwards.\n" ]
[ 2 ]
[]
[]
[ "iteration", "list", "python", "string" ]
stackoverflow_0074368185_iteration_list_python_string.txt
Q: ```while [List]: ``` vs ```while [List] is True```? What is the difference? while [List]: vs while [List] is True? What is the different? For example I am doing this problem (heap and priority queues) https://leetcode.com/problems/find-k-pairs-with-smallest-sums/ and here is a sample solution that I retrieved. I...
```while [List]: ``` vs ```while [List] is True```? What is the difference?
while [List]: vs while [List] is True? What is the different? For example I am doing this problem (heap and priority queues) https://leetcode.com/problems/find-k-pairs-with-smallest-sums/ and here is a sample solution that I retrieved. I do not understand this line while len(res) < k and heap:. Why do I need while he...
[ "There are a few different things necessary to fully understand the topic you're asking about.\nThe first is what do the is operator does. It checks for identity, that is, if A is B is true, then A and B must be two references to the same object.\nThe second is boolean contexts. When you use an expression in a if o...
[ 1, 0 ]
[]
[]
[ "python", "while_loop" ]
stackoverflow_0074342697_python_while_loop.txt
Q: GET data with Python from Dynamodb This is my code where i am trying to get the data from an existing table of dynamodb through python code. import boto3 import os os.environ['AWS_DEFAULT_REGION'] = 'us-east-1' _TableName_ = "TablaLoraPF" client = boto3.client('dynamodb') DB = boto3.resource('dynamodb') table =...
GET data with Python from Dynamodb
This is my code where i am trying to get the data from an existing table of dynamodb through python code. import boto3 import os os.environ['AWS_DEFAULT_REGION'] = 'us-east-1' _TableName_ = "TablaLoraPF" client = boto3.client('dynamodb') DB = boto3.resource('dynamodb') table = DB.Table(_TableName_) response = tab...
[ "To do this you need to specify ProjectionExpression.\nresponse = table.get_item(\n Key={\n 'seqno': \"65909\", 'data': \"11\"\n },\n ProjectionExpression = '#data', \n ExpressionAttributeNames = {\n '#d':'data'\n }\n)\n\nhttps://docs.aws.amazon.com/amazondynamodb/latest/APIReference/A...
[ 0 ]
[]
[]
[ "amazon_dynamodb", "amazon_web_services", "boto3", "get", "python" ]
stackoverflow_0074367305_amazon_dynamodb_amazon_web_services_boto3_get_python.txt
Q: Simple python equation I'm a new pyhton programmer, I'm writing a simple program that calculate what I have in my storage and what is remaining so let's assume that x = 1000 I want to deduct 200 items now and after a day I'll deduct 300 more the problem here that programme will deduct 200 out of the 1000 and deduc...
Simple python equation
I'm a new pyhton programmer, I'm writing a simple program that calculate what I have in my storage and what is remaining so let's assume that x = 1000 I want to deduct 200 items now and after a day I'll deduct 300 more the problem here that programme will deduct 200 out of the 1000 and deduct 300 out of the same 1000 n...
[ "You're never changing the origianl x variable\nYou need to take your input value minus x and feed it back into x\nI've added some extra bits for you, for validation under 0 etc.\nx = 1000\nwhile True:\n b = input(\"how many (x) you need:\")\n \n #make sure its a number\n is_valid_input = b.isnumeric()\...
[ 0, 0 ]
[]
[]
[ "integer", "python", "while_loop" ]
stackoverflow_0074368089_integer_python_while_loop.txt
Q: Python: Max recursion depth exceeded while calling a Python object I have looked at the other answers to this question from this website, but Im still stuck. After adding, setrecursion limit and stack_size, my screen just shows the starting board. I followed "Tech with Tim" step by step but I'm not fully getting t...
Python: Max recursion depth exceeded while calling a Python object
I have looked at the other answers to this question from this website, but Im still stuck. After adding, setrecursion limit and stack_size, my screen just shows the starting board. I followed "Tech with Tim" step by step but I'm not fully getting the answer. Now, I did notice that he was using PyCharm and I'm using VSC...
[ "Your position index variables x and y are mixed up in find_empty(): you check board[x][y] == 0, but it should be board[y][x] == 0 to be consistent with board[row][col] in solve(). I'd recommend using the same names for your position variables everywhere to avoid these kinds of mistakes.\nAs a side note, changing t...
[ 0 ]
[]
[]
[ "import", "methods", "object", "python", "recursion" ]
stackoverflow_0074367989_import_methods_object_python_recursion.txt
Q: Chrome page opened with selenium remains blank I am trying to save a screenshot of a webpage, to do so I am trying to use Selenium. The problem is that once the webpage is opened, it stays blank with "data:" in the URL. Here is my code: from selenium import webdriver options = webdriver.ChromeOptions() options.add...
Chrome page opened with selenium remains blank
I am trying to save a screenshot of a webpage, to do so I am trying to use Selenium. The problem is that once the webpage is opened, it stays blank with "data:" in the URL. Here is my code: from selenium import webdriver options = webdriver.ChromeOptions() options.add_experimental_option('useAutomationExtension', False...
[ "You need to update the value of the Key executable_path with the absolute path of the chromedriver binary and service_args as follows:\ndriver = webdriver.Chrome(options=options,executable_path=r'C:\\path\\to\\chromedriver.exe', service_args=[\"--log-path=C:\\\\path\\\\to\\\\mylog.log\"])\n\nYou can find a couple ...
[ 2, 2, 0 ]
[]
[]
[ "google_chrome", "python", "selenium", "webdriver" ]
stackoverflow_0059717738_google_chrome_python_selenium_webdriver.txt
Q: How to create lists by running functions in parallel in python I want to create two lists by running two functions (returning a value each for every run) in parallel. My code below works, but is still taking too much time. Is there a more efficient way to parallelize this code? import time from joblib import Paral...
How to create lists by running functions in parallel in python
I want to create two lists by running two functions (returning a value each for every run) in parallel. My code below works, but is still taking too much time. Is there a more efficient way to parallelize this code? import time from joblib import Parallel, delayed catchments = 50 #define number of catchments to plo...
[ "The way you've written your code, you're first running all your budx instances, waiting for them to complete, and only then running your budy instances. That is, you are sequentially running two sets of parallel tasks.\nHere's one possible way of doing that, noting that (a) I was not previously familiar with jobli...
[ 1 ]
[]
[]
[ "parallel_processing", "python" ]
stackoverflow_0074368210_parallel_processing_python.txt
Q: Python, PIP & Conda, install package in global env I'm using Python for some projects. I want run some .py program with task scheduler Windows. The task scheduler is using the Global environnement (from Python) by default (which is fine for me). I've tried to install packages in this Global environnement but there...
Python, PIP & Conda, install package in global env
I'm using Python for some projects. I want run some .py program with task scheduler Windows. The task scheduler is using the Global environnement (from Python) by default (which is fine for me). I've tried to install packages in this Global environnement but there are always installed in Conda active environnement. I'v...
[ "Ok I solved this issue by uninstalling pip in Conda then run powershell in admin to reinstall it in global environnement. It worked...\n" ]
[ 0 ]
[]
[]
[ "conda", "miniconda", "package", "pip", "python" ]
stackoverflow_0074368294_conda_miniconda_package_pip_python.txt
Q: Generating a random sparse matrix using a custom discrete distribution in SciPy I would like to generate a sparse matrix using a custom discrete distribution. E.g.: from scipy.sparse import random from scipy import stats xk = np.arange(7) pk = np.array([0.1, 0.2, 0.3, 0.1, 0.1, 0.1, 0.1]) custm = stats.rv_discret...
Generating a random sparse matrix using a custom discrete distribution in SciPy
I would like to generate a sparse matrix using a custom discrete distribution. E.g.: from scipy.sparse import random from scipy import stats xk = np.arange(7) pk = np.array([0.1, 0.2, 0.3, 0.1, 0.1, 0.1, 0.1]) custm = stats.rv_discrete(name='custm', values=(xk, pk)) rvs = custm.rvs dens = 0.5 S = random(1, 8, densit...
[ "The docs on rv_discrete.rvs() say this:\n\nsize\nDefining number of random variates (Default is 1). Note that size has to be given as keyword, not as positional argument.\n\nSource.\nHowever, scipy.sparse.random() passes the size as a positional argument:\nvals = data_rvs(k).astype(dtype, copy=False)\n\nTherefore,...
[ 3, 2 ]
[]
[]
[ "numpy", "python", "scipy", "sparse_matrix" ]
stackoverflow_0074353783_numpy_python_scipy_sparse_matrix.txt
Q: How to set up siblings? Hi I am a high school student who is new to coding with BeautifulSoup 4.9.0(?) using Python 3.10 and I was having trouble with siblings. I have been using an online resources to try and understand how siblings work and what each part does but when I run the code I run into errors and I am ...
How to set up siblings?
Hi I am a high school student who is new to coding with BeautifulSoup 4.9.0(?) using Python 3.10 and I was having trouble with siblings. I have been using an online resources to try and understand how siblings work and what each part does but when I run the code I run into errors and I am confused on how to fix it to ...
[ "The tag with the id=\"giftList\" is <table>, not <title>:\nimport requests\nfrom bs4 import BeautifulSoup\n\nr = requests.get(\"http://www.pythonscraping.com/pages/page3.html\")\nbs = BeautifulSoup(r.content, \"html.parser\")\n\nfor sibling in bs.find(\"table\", {\"id\": \"giftList\"}).tr.next_siblings:\n print...
[ 0 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0074363187_beautifulsoup_python.txt
Q: ImportError: No Module Named bs4 (BeautifulSoup) I'm working in Python and using Flask. When I run my main Python file on my computer, it works perfectly, but when I activate venv and run the Flask Python file in the terminal, it says that my main Python file has "No Module Named bs4." Any comments or advice is gr...
ImportError: No Module Named bs4 (BeautifulSoup)
I'm working in Python and using Flask. When I run my main Python file on my computer, it works perfectly, but when I activate venv and run the Flask Python file in the terminal, it says that my main Python file has "No Module Named bs4." Any comments or advice is greatly appreciated.
[ "Activate the virtualenv, and then install BeautifulSoup4:\n$ pip install BeautifulSoup4\n\nWhen you installed bs4 with easy_install, you installed it system-wide. So your system python can import it, but not your virtualenv python.\nIf you do not need bs4 to be installed in your system python path, uninstall it an...
[ 279, 63, 17, 14, 11, 8, 5, 5, 5, 4, 4, 3, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "beautifulsoup", "flask", "importerror", "python" ]
stackoverflow_0011783875_beautifulsoup_flask_importerror_python.txt
Q: ImportError: dlopen(...): Library not loaded: @rpath/_pywrap_tensorflow_internal.so I am a beginner at machine learning. I try to use LSTM algorism but when I write from keras.models import Sequential it shows error as below: ImportError: dlopen(/Users/wangzifan/opt/anaconda3/lib/python3.9/site-packages/tensorflow...
ImportError: dlopen(...): Library not loaded: @rpath/_pywrap_tensorflow_internal.so
I am a beginner at machine learning. I try to use LSTM algorism but when I write from keras.models import Sequential it shows error as below: ImportError: dlopen(/Users/wangzifan/opt/anaconda3/lib/python3.9/site-packages/tensorflow/python/_pywrap_tfe.so, 2): Library not loaded: @rpath/_pywrap_tensorflow_internal.so R...
[ "Problem solved. install tensorflow again with\nsudo pip3 install tensorflow\n\nand change the import to\nfrom tensorflow.python.keras.models import Sequential\n\n", "I solve this annoying issue with\npip3 install --upgrade tensorflow --user\n\nMy environment is\nPython 3.7.9\nconda 22.9.0\n\n" ]
[ 0, 0 ]
[]
[]
[ "keras", "lstm", "pip", "python", "tensorflow" ]
stackoverflow_0072937452_keras_lstm_pip_python_tensorflow.txt
Q: How to search for comments containing keyword in all Reddit using praw or similar? If I want to search on Reddit for comments containing a keyword, the website has an URL like this: https://www.reddit.com/search/?q=exampletest&include_over_18=1&type=comment and the search is very fast and immediately find results...
How to search for comments containing keyword in all Reddit using praw or similar?
If I want to search on Reddit for comments containing a keyword, the website has an URL like this: https://www.reddit.com/search/?q=exampletest&include_over_18=1&type=comment and the search is very fast and immediately find results, it's "native". If I try to do that with praw, with for example something like this: re...
[ "I fixed scraping results within the url:\nhttps://www.reddit.com/search/?q=exampletest&include\\_over\\_18=1&type=comment\n" ]
[ 0 ]
[]
[]
[ "api", "praw", "python", "reddit" ]
stackoverflow_0074361595_api_praw_python_reddit.txt
Q: Splitting a list into strings I have a variable that contains multiple lists. I'm trying to split the lists into strings so that I can add them to a csv file but I'm not sure how. This is what I have been trying to do. For some reason, integrating through the different lists (i.e. participants) doesn't seem to wor...
Splitting a list into strings
I have a variable that contains multiple lists. I'm trying to split the lists into strings so that I can add them to a csv file but I'm not sure how. This is what I have been trying to do. For some reason, integrating through the different lists (i.e. participants) doesn't seem to work properly. It only uses the last l...
[ "with open('results.csv', 'w') as f:\n f.write('\\n'.join(','.join(s) for s in [participant for participant in contest]))\n\n" ]
[ 0 ]
[]
[]
[ "csv", "list", "python", "string" ]
stackoverflow_0074368474_csv_list_python_string.txt
Q: Sign hash via AWS KMS eth account I need to sign a hash using my eth account, the private key to which is in AWS KMS. Initially I just needed to sign some data with an eth private key. I implemented it this way and it worked fine: from eth_account import Account from hexbytes import HexBytes KEY = 'ETH PRIVATE KE...
Sign hash via AWS KMS eth account
I need to sign a hash using my eth account, the private key to which is in AWS KMS. Initially I just needed to sign some data with an eth private key. I implemented it this way and it worked fine: from eth_account import Account from hexbytes import HexBytes KEY = 'ETH PRIVATE KEY' DATA = 'SOME DATA' account = Accoun...
[ "I studied the source code of the \"eth_account\" module and simply rewrote the signHash function (from the first piece of code) to work with aws kms.\nI took some of the code from here:\nhttps://github.com/ethereum/eth-account/blob/master/eth_account/account.py\nThe final solution looks like this:\nfrom hexbytes i...
[ 1 ]
[]
[]
[ "amazon_kms", "amazon_web_services", "cryptography", "ethereum", "python" ]
stackoverflow_0074366186_amazon_kms_amazon_web_services_cryptography_ethereum_python.txt
Q: How do I read a CSV directly into a pandas dataframe from a download link button? I'm trying to read the Train File directly into a pandas dataframe from the link address instead of downloading to my local computer then reading. The website is: https://datahack.analyticsvidhya.com/contest/practice-problem-loan-pre...
How do I read a CSV directly into a pandas dataframe from a download link button?
I'm trying to read the Train File directly into a pandas dataframe from the link address instead of downloading to my local computer then reading. The website is: https://datahack.analyticsvidhya.com/contest/practice-problem-loan-prediction-iii/download/#ProblemStatement The link address when you right click the Train ...
[ "You need supply your login credentials to the website. With requests you pass them in as arguments, as follows:\nresponse = requests.get(url, auth=HTTPBasicAuth(username, password))\n\nReplace username and password with your username and password. It will authenticate the request and return a response 200 or else ...
[ 0 ]
[]
[]
[ "csv", "data_science", "pandas", "python" ]
stackoverflow_0074368519_csv_data_science_pandas_python.txt
Q: replace empty space lines on a string column using Python i am reading an excel data where one of the columns has text based data. it basically some set of database qry's if i look at the dataframe: sel a ,b \n\n\n\n from database1\n\n\n where n=1 \n\n\n order by \n; \n\n\n \n is the new line character. Some...
replace empty space lines on a string column using Python
i am reading an excel data where one of the columns has text based data. it basically some set of database qry's if i look at the dataframe: sel a ,b \n\n\n\n from database1\n\n\n where n=1 \n\n\n order by \n; \n\n\n \n is the new line character. Some qry lengths are huge and with new line character in between it...
[ "Here's a quick and easy way to get rid of extraneous whitespace.\nIn [1]: s = \"\"\"sel\n ...:\n ...: col1 ,\n ...:\n ...:\n ...:\n ...: col2 from database\n ...:\n ...: order by 1;\"\"\"\n\nIn [2]: \" \".join(s.split())\nOut[2]: 'sel col1 , col2 from database order by 1;'\n\nNot...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074368557_python.txt
Q: AWS CLI Can List S3 Bucket But Access Denied For Python Lambda I've used terraform to setup infra for an s3 bucket and my containerised lambda. I want to trigger the lambda to list the items in my s3 bucket. When I run the aws cli it's fine: aws s3 ls returns 2022-11-08 23:04:19 bucket-name This is my lambda: im...
AWS CLI Can List S3 Bucket But Access Denied For Python Lambda
I've used terraform to setup infra for an s3 bucket and my containerised lambda. I want to trigger the lambda to list the items in my s3 bucket. When I run the aws cli it's fine: aws s3 ls returns 2022-11-08 23:04:19 bucket-name This is my lambda: import logging import boto3 LOGGER = logging.getLogger(__name__) LOGG...
[ "As far as I can tell, your Lambda function has the correct IAM role (the one indicated in your Terraform template) but that IAM role has no attached policies.\nYou need to attach the S3 policy, and any other IAM policies needed, to the IAM role. For example:\nresource \"aws_iam_role_policy_attachment\" \"lambda-at...
[ 3, 2 ]
[]
[]
[ "amazon_s3", "amazon_web_services", "aws_lambda", "python", "terraform" ]
stackoverflow_0074368366_amazon_s3_amazon_web_services_aws_lambda_python_terraform.txt
Q: Can you change font of labels in plotly sankey diagrams? I can't find a way to change the font size or colors of the labels (source and target names, not the title) in the Sankey diagram of plotly. Is this even possible? In the example below: change font size of fe "Steam 8 MW" import plotly.graph_objects as go f...
Can you change font of labels in plotly sankey diagrams?
I can't find a way to change the font size or colors of the labels (source and target names, not the title) in the Sankey diagram of plotly. Is this even possible? In the example below: change font size of fe "Steam 8 MW" import plotly.graph_objects as go fig = go.Figure(data=[go.Sankey( valueformat = ".0f", v...
[ "You can change the font and size of the title font and the label font and size in the following ways I have addressed the issue in question based on the example in the reference.\nA reference on font settings can be found here.\nimport plotly.graph_objects as go\n\nfig = go.Figure(data=[go.Sankey(\n node = dict...
[ 0 ]
[]
[]
[ "plotly", "plotly_python", "python", "sankey_diagram" ]
stackoverflow_0074367449_plotly_plotly_python_python_sankey_diagram.txt
Q: When using an ndarray to represent a matrix, how to modify a column based on the value of another column? Numpy's documentation suggests to use numpy arrays to represent matrices, so I'm looking at something like import numpy as np arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) to represent and I...
When using an ndarray to represent a matrix, how to modify a column based on the value of another column?
Numpy's documentation suggests to use numpy arrays to represent matrices, so I'm looking at something like import numpy as np arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) to represent and I just can't figure out from the documentation how I would update a column based on the value of another column....
[ "The specific task you're interested can be done as follows\narr[arr[:,1]>3,2] += 10\n\n" ]
[ 1 ]
[]
[]
[ "numpy_ndarray", "python" ]
stackoverflow_0074368753_numpy_ndarray_python.txt
Q: "ModuleNotFoundError: No module named 'kivymd'" in .spec file I already did pip install kivymd in my Python project. I also had the kivymd directory in my project. I'm working with a Mac. I created a spec file called "coinsnack4.spec" including the code below: from kivymd import hooks_path as kivymd_hooks_path Ho...
"ModuleNotFoundError: No module named 'kivymd'" in .spec file
I already did pip install kivymd in my Python project. I also had the kivymd directory in my project. I'm working with a Mac. I created a spec file called "coinsnack4.spec" including the code below: from kivymd import hooks_path as kivymd_hooks_path However, when I try to package my python project with the spec file ...
[ "Why are you facing this issue?\nThe reason behind this is the concept of virtual environments in python. Each virtual environment is independent of the other. You can use different virtual environments, activate and deactivate them as per your project's requirements.\nI would suggest you go through this doc once P...
[ 1, 0 ]
[]
[]
[ "kivy", "kivymd", "packaging", "pip", "python" ]
stackoverflow_0067856180_kivy_kivymd_packaging_pip_python.txt
Q: How to create single form to input orders with order table and order_item table that has foreign key from orders table? This is more of a conceptual question on how to format my page and forms for a customer ordering process with the way I structed my tables. To follow normalization standards, I separated order ta...
How to create single form to input orders with order table and order_item table that has foreign key from orders table?
This is more of a conceptual question on how to format my page and forms for a customer ordering process with the way I structed my tables. To follow normalization standards, I separated order table and order items table, with the order ID as a foreign key in the order items table. The orders table just takes the prima...
[ "not full answer but can use lastrowid method from cursor to get the id of the last row inserted into the db\n" ]
[ 0 ]
[]
[]
[ "flask", "html", "jinja2", "python" ]
stackoverflow_0074365419_flask_html_jinja2_python.txt
Q: Multiple Inheritance --> Fish.__init__() missing 2 required positional arguments I have been practicing multiple inheritance, the example can sound weird but this is what I have in mind... Here is a main class called Pet and that has two children Cat and Fish and, I wanted to mix the skills of the cat and the skil...
Multiple Inheritance --> Fish.__init__() missing 2 required positional arguments
I have been practicing multiple inheritance, the example can sound weird but this is what I have in mind... Here is a main class called Pet and that has two children Cat and Fish and, I wanted to mix the skills of the cat and the skills of the fish in another class but it seems not to work, some idea? class Pet: de...
[ "super() doesn't call the first parent class' method. It calls the next method in the MRO, or method resolution order (link is for Python 2.3, but the same algorithm is still used today).\nclass Pet:\n pass\n\nclass Cat(Pet):\n pass\n \nclass Fish(Pet):\n pass\n\nclass fishCat(Cat, Fish):\n pass\...
[ 1 ]
[]
[]
[ "inheritance", "multiple_inheritance", "oop", "python", "typeerror" ]
stackoverflow_0074368847_inheritance_multiple_inheritance_oop_python_typeerror.txt
Q: Classification NN stuck some point and changing initializers and optimizers doesn't really help in increasing accuracy I am trying to train a neural net to predict if if certain signal is PN, NN, NP or PP based on some values. Each sample in main dataset (before spliting it in training, valid and test datasets) ha...
Classification NN stuck some point and changing initializers and optimizers doesn't really help in increasing accuracy
I am trying to train a neural net to predict if if certain signal is PN, NN, NP or PP based on some values. Each sample in main dataset (before spliting it in training, valid and test datasets) has these values: df[['SIGNAL_CLASS1', 'SIGNAL_CLASS2', 'value1', 'value2[-2]', 'value2[-1]', 'value3[-2]', 'value3[-1]', 'val...
[ "Instead of using neural nets i'd recommend first creating clusters as features and then applying a traditional classification algorithm. After clustering you may even be able to just use a support vector machine classifier scikit-learn support vector machine\n" ]
[ 0 ]
[]
[]
[ "keras", "neural_network", "python", "tensorflow" ]
stackoverflow_0074368820_keras_neural_network_python_tensorflow.txt
Q: Formatting numbers one zero less with D3 (e.g. 15 -> 1.5) Plotly uses D3 for formatting ticks so, I want the ticks of a plot to have one zero less. My code: # Spatial axes dx, dz = 100, 100 x = np.arange(0, 60000, dx) z = np.arange(0, 30000, dz) [zz, xx]= np.meshgrid(z, x, indexing='ij') # Velocity model vel = 1...
Formatting numbers one zero less with D3 (e.g. 15 -> 1.5)
Plotly uses D3 for formatting ticks so, I want the ticks of a plot to have one zero less. My code: # Spatial axes dx, dz = 100, 100 x = np.arange(0, 60000, dx) z = np.arange(0, 30000, dz) [zz, xx]= np.meshgrid(z, x, indexing='ij') # Velocity model vel = 1000 + 0.032 * zz fig = px.imshow(vel, labels=dict(x="x[km]", y...
[ "Customization of the scale is made possible by setting the scale value and the numerical value or string for the scale.\nimport plotly.express as px\nimport numpy as np\n\n# Spatial axes\ndx, dz = 100, 100\nx = np.arange(0, 60000, dx)\nz = np.arange(0, 30000, dz)\n\n[zz, xx]= np.meshgrid(z, x, indexing='ij')\n\n# ...
[ 0 ]
[]
[]
[ "d3.js", "javascript", "plotly", "python" ]
stackoverflow_0074353749_d3.js_javascript_plotly_python.txt
Q: Why am I getting this error when I try to slice a Zarr array exactly the same way I would slice a Numpy array? I am using the following code to slice a Zarr array from disk: import zarr as zr db = zr.open('/content/drive/My Drive/Share/Daily Data/Database/dbz.zarr', mode='r') data = db[db[:,0]==20171003] Here is...
Why am I getting this error when I try to slice a Zarr array exactly the same way I would slice a Numpy array?
I am using the following code to slice a Zarr array from disk: import zarr as zr db = zr.open('/content/drive/My Drive/Share/Daily Data/Database/dbz.zarr', mode='r') data = db[db[:,0]==20171003] Here is the error: IndexError Traceback (most recent call last) <ipython-input-16-4ae364a8c3...
[ "I found the following page to be helpful: https://zarr.readthedocs.io/en/stable/api/core.html\nIn summary, using zarr_array.oindex([]) allows classic indexing/slicing.\n" ]
[ 0 ]
[]
[]
[ "numpy", "python", "zarr" ]
stackoverflow_0063819672_numpy_python_zarr.txt
Q: How to handle Mypy when many possible types but expecting a specific type? Say I have a generic function that can return a number of different types depending on what properties I select: def json_parser(json_data: Dict[str, Any], property_tree: List[str] ) -> Union[Dict[str, Any], List[str], str, ...
How to handle Mypy when many possible types but expecting a specific type?
Say I have a generic function that can return a number of different types depending on what properties I select: def json_parser(json_data: Dict[str, Any], property_tree: List[str] ) -> Union[Dict[str, Any], List[str], str, None]: .... I then call this generic function with specific properties that...
[ "You've got two options, depending on how careful you want to be.\nFirst, typing.cast is a function that takes a type and a value and... magically makes the value have that type. At runtime it's defined as\ndef cast(ty, value):\n return value\n\nbut type-checkers are instructed to treat it as some magic black box....
[ 1 ]
[]
[]
[ "mypy", "python" ]
stackoverflow_0074368353_mypy_python.txt
Q: pyodbc encrypt username and password I am using VSCode, pyodbc-4.0.34, Python 3.10.7. Code from here: import pyodbc import pandas as pd server = 'servername' database = 'AdventureWorks' username = 'yourusername' password = 'databasename' cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER='+server+';DATABASE='+...
pyodbc encrypt username and password
I am using VSCode, pyodbc-4.0.34, Python 3.10.7. Code from here: import pyodbc import pandas as pd server = 'servername' database = 'AdventureWorks' username = 'yourusername' password = 'databasename' cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ passwor...
[ "We can use command line argument to give the argument to python when you run the file in the cmd.\nFor example:\nimport sys\nserver = sys.argv[1]\ndatabase = sys.argv[2]\nusername = sys.argv[3]\npassword = sys.argv[4] \nprint(server+database+username+password)\n\n\nCorrespondingly, you can modify your code:\nimpor...
[ 0 ]
[]
[]
[ "pandas", "python", "visual_studio_code" ]
stackoverflow_0074360434_pandas_python_visual_studio_code.txt
Q: How to compute a rolling sum for a grouped DataFrame in Python I am trying to calculate a rolling sum by group as shown below. I tried the following: # Function john = pd.DataFrame({'name':'john', 'score':[0, 2, 1, 0, 0, 0, 0, 0, 0, 0], 'rolling_sum':[np.nan, np...
How to compute a rolling sum for a grouped DataFrame in Python
I am trying to calculate a rolling sum by group as shown below. I tried the following: # Function john = pd.DataFrame({'name':'john', 'score':[0, 2, 1, 0, 0, 0, 0, 0, 0, 0], 'rolling_sum':[np.nan, np.nan, np.nan, np.nan, np.nan, 3, 3, 1, 0, 0]}) ...
[ "Thanks to Naveed, I have resolved my issue. Naveed advised me to remove \"min_periods=1\" from the code. After removing this code, I wrote a function that returns a complete DataFrame (see the code below).\nWrite a function\n----------------\ndef calc_rolling_sum(df, window):\n \"\"\"\n Compute a 6-month rol...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074354077_pandas_python.txt
Q: How to redirect always to the same page in a Flask app I am running a Flask application and I want to implement a functionality that keeps a user in the same page until some process is completed, but if he leaves and come back the user will see the same page, also if he tries to return the page, he will be redirec...
How to redirect always to the same page in a Flask app
I am running a Flask application and I want to implement a functionality that keeps a user in the same page until some process is completed, but if he leaves and come back the user will see the same page, also if he tries to return the page, he will be redirected to the same page. He will be able to make another action...
[ "it is not flask issue, it is web app mechanism, you cannot stop user do everything in browser.\nyou can use session or db to store user state, and redirect / block requests what you want to\n" ]
[ 0 ]
[]
[]
[ "flask", "javascript", "python" ]
stackoverflow_0074368946_flask_javascript_python.txt
Q: Audio stream reading function getting stuck during multiprocessing Consider this python code: class Recorder: (...) def __init__(self): self.p = pyaudio.PyAudio() self.stream = self.p.open(format=FORMAT, channels=CHANNELS, rat...
Audio stream reading function getting stuck during multiprocessing
Consider this python code: class Recorder: (...) def __init__(self): self.p = pyaudio.PyAudio() self.stream = self.p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, ...
[ "Ok, so I got it working.\nThe answer is simple.\nWe are not supposed to use multiprocessing in this scenario, but Threading instead:\nimport threading\n\na = Recorder()\n\n\nthread1 = threading.Thread(target = a.listen)\nthread1.start()\n\nWith this, the code is now working as intended.\n" ]
[ 0 ]
[]
[]
[ "multiprocessing", "pyaudio", "python" ]
stackoverflow_0074368945_multiprocessing_pyaudio_python.txt
Q: How to make a question generator based on pdf files using Python I have many mathematics worksheets like this.(This is an image of a page of pdf) So I want to make a Python program to take questions from these worksheets randomly and save them to a pdf file. I can easily take out the whole text from pdf but I have...
How to make a question generator based on pdf files using Python
I have many mathematics worksheets like this.(This is an image of a page of pdf) So I want to make a Python program to take questions from these worksheets randomly and save them to a pdf file. I can easily take out the whole text from pdf but I have no idea how to distinguish the questions and the bigger problem is of...
[ "Maybe start with a sentence paraphraser coupled with machine learning model that takes symbolics to its written language form. Once you have that you can use a keyword frequency distribution to have it scrape the web. The returned average question now paraphrased and condensed to its general relative concept would...
[ 0, 0 ]
[]
[]
[ "pdf", "pdf_generation", "python", "python_3.x" ]
stackoverflow_0070046824_pdf_pdf_generation_python_python_3.x.txt
Q: equivalent code of 'open with' in python script import sys sys. argv[1] is the code equivalent of the above image. Please reply me A: You need to get the os which is in-built library to Python. Then you can use os.startfile(_filepath_) to open the file. A: finally i got the answer. yes it is right I wanted t...
equivalent code of 'open with' in python script
import sys sys. argv[1] is the code equivalent of the above image. Please reply me
[ "You need to get the os which is in-built library to Python. Then you can use\nos.startfile(_filepath_)\n\nto open the file.\n", "finally i got the answer. yes it is right I wanted to create a pdf reader application using python tkinter which i will use to open any pdf file. When i will click a pdf file it will s...
[ 0, 0 ]
[]
[]
[ "equivalent", "python", "tkinter" ]
stackoverflow_0074355848_equivalent_python_tkinter.txt
Q: Conditional downsampling over a data frame I am working on a data frame that looks like this: Id feat1 value c1 c22 51 c2 c12 83 c3 d31 42 c4 a19 110 c5 d44 56 . . . . . . . . . The value column has a range [40,240]. I want to downsample the dataframe s...
Conditional downsampling over a data frame
I am working on a data frame that looks like this: Id feat1 value c1 c22 51 c2 c12 83 c3 d31 42 c4 a19 110 c5 d44 56 . . . . . . . . . The value column has a range [40,240]. I want to downsample the dataframe such that I get 300 rows for each of the followin...
[ "You can create bins using pandas.cut(), then groupby bins to draw equal samples per bin\ndf['bin'] = pd.cut(df['value'], range(40, 250, 10))\nsampled_df = df.groupby('bin').apply(lambda x: x.sample(300)).reset_index(drop=True)\n\n" ]
[ 1 ]
[]
[]
[ "bin", "downsampling", "pandas", "python" ]
stackoverflow_0074368417_bin_downsampling_pandas_python.txt
Q: Python error: unpack requires a buffer of 4 bytes, when using PyMySQL, I am connecting a Python program in Visual Studio Code to a SQL databse stored in MySQL Workbench 8.0. I am using the PyMySQL connector to do this. However, I am running into an error with code that I have used from another question that I have...
Python error: unpack requires a buffer of 4 bytes, when using PyMySQL,
I am connecting a Python program in Visual Studio Code to a SQL databse stored in MySQL Workbench 8.0. I am using the PyMySQL connector to do this. However, I am running into an error with code that I have used from another question that I have posted. Here is the link and the code: How do I connect a Python program in...
[ "First of all, obviously you didn't copy the code in the answer correctly.\nYour code has the following errors (only from the picture, I don't know what your complete code looks like)\n\nThe port number is 3306. NOT 33060. Of course, if you make changes when you install the database, you need to change it to the po...
[ 0 ]
[]
[]
[ "error_handling", "mysql", "pymysql", "python" ]
stackoverflow_0074358734_error_handling_mysql_pymysql_python.txt
Q: How do we print a function's name along with the calling arguments? We want to print each function call along with the calling arguments. Consider the following recursive function decorated with a user-defined (custom-made) decorator named @traced: @traced def foo(a,b): if a == 0: return b return f...
How do we print a function's name along with the calling arguments?
We want to print each function call along with the calling arguments. Consider the following recursive function decorated with a user-defined (custom-made) decorator named @traced: @traced def foo(a,b): if a == 0: return b return foo(b=a-1,a=b-1) The desired output is something like this: foo(a=4, b=3)...
[ "You can replace\nprint(bsig)\n\nwith\nprint(self.__f.__name__ + \"(\" + \", \".join(f\"{key}={val}\" for key, val in bsig.arguments.items()) + \")\")\n\nHere\nself.__f.__name__\n\ngives the name of the calling function, and\nbsig.arguments\n\ngives a dictionary of the arguments, so with some simple formatting we c...
[ 0 ]
[]
[]
[ "python", "python_3.x", "python_decorators", "signature", "stack_trace" ]
stackoverflow_0074368772_python_python_3.x_python_decorators_signature_stack_trace.txt
Q: How do you exit this websocket and eventloop example? !/usr/bin/env python import asyncio import websockets buttcount=0 async def hello(websocket, path): global buttcount name = await websocket.recv() print(name) if name=="butt": buttcount += 1 if buttcount == 3: #Do somethin...
How do you exit this websocket and eventloop example?
!/usr/bin/env python import asyncio import websockets buttcount=0 async def hello(websocket, path): global buttcount name = await websocket.recv() print(name) if name=="butt": buttcount += 1 if buttcount == 3: #Do something really cool to gracefully exit without error messages ...
[ "I got it working with asyncio Future.\n#!/usr/bin/env python\n\nimport asyncio\nimport websockets\n\nthefuture= \"\"\nbuttcount= 0\n\nasync def echo(websocket):\n global buttcount\n global thefuture\n print(buttcount)\n name = await websocket.recv()\n if name == \"butt\":\n buttcount +=1\n ...
[ 0 ]
[]
[]
[ "async_await", "asynchronous", "python", "python_asyncio", "websocket" ]
stackoverflow_0074355877_async_await_asynchronous_python_python_asyncio_websocket.txt
Q: pandas: find the first friday following the first monday of the month currently trying to figure this out with code like this..but not quite yet able to get it: df[(df.index.day_of_week==0) & (df.index.day<15) & (df.shift(-4).index.day_of_week==4)] this is what the data looks like. (i've added the day_of_week co...
pandas: find the first friday following the first monday of the month
currently trying to figure this out with code like this..but not quite yet able to get it: df[(df.index.day_of_week==0) & (df.index.day<15) & (df.shift(-4).index.day_of_week==4)] this is what the data looks like. (i've added the day_of_week column for convenience). basically, i am trying to find the first day_of_we...
[ "You can group by [year, month, day_of_week] and do a cumcount to assign to each row the number of times its day_of_week has appeared in this month.\nThen, grab the rows corresponding to the first monday of the month using the filter day_of_week == 0 & cumcount == 0 and shift their index by 4 days to get the follow...
[ 1, 0 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074367620_numpy_pandas_python.txt
Q: Get duplicates between two lists I want to get the duplicates between two lists. Something like this: list1 = [1,2,3,4,5] list2 = [1,2,8,4,6] duplicates = getDuplicates(list1, list2) print(duplicates) # => = [1,2,4] I tried to search for an answer, but I only found how to remove the duplicates. A: You can us...
Get duplicates between two lists
I want to get the duplicates between two lists. Something like this: list1 = [1,2,3,4,5] list2 = [1,2,8,4,6] duplicates = getDuplicates(list1, list2) print(duplicates) # => = [1,2,4] I tried to search for an answer, but I only found how to remove the duplicates.
[ "You can use a set and the .intersection() method. Like this:\nlist1 = [1,2,3,4,5]\nlist2 = [1,2,8,4,6]\n\nduplicates = list(set(list1).intersection(list2))\nprint(duplicates) # => [1, 2, 4]\n\nI tested this against jsbueno's answer using timeit and found that my answer is significantly faster. For two lists of 5 ...
[ 1, 0, 0, 0 ]
[]
[]
[ "duplicates", "list", "python" ]
stackoverflow_0074365410_duplicates_list_python.txt
Q: How to search specific word in csv file with pandas df: first last email 0 Corey Schafer CoreMSchafer@gmail.com 1 Jane Doe JaneDoe@gmail.com 2 John Doe JohnDoe@gmail.com From a big CSV file, how can I find a specific word like John, without knowing on what col...
How to search specific word in csv file with pandas
df: first last email 0 Corey Schafer CoreMSchafer@gmail.com 1 Jane Doe JaneDoe@gmail.com 2 John Doe JohnDoe@gmail.com From a big CSV file, how can I find a specific word like John, without knowing on what column or row he is? If there are several names with John, c...
[ "That's the way to do i believe.\nimport pandas as pd\n\ndf = pd.read_csv('data.csv')\ndf[df['first'].str.contains('John')] # returns all rows where John in the column 'first'\ndf[df['first'].str.contains('John')].index.tolist() # get the index of the rows\n\nThe contains method is case sensitive, to make it case i...
[ 1, 0 ]
[]
[]
[ "csv", "pandas", "python" ]
stackoverflow_0074361684_csv_pandas_python.txt
Q: Adding a zero to a decimal for a string: 0.1 --> 0.10 0.2 --> 0.20 0.3 --> 0.30 0.35 --> 0.35 Example: print(str(round(variableB.count('X') /len(variableA), 2))) I tried print("%.2f" %str(round(variableB.count('X')/len(variableA),2))), but I got TypeError: must be real number, not str then I tried print ("%.2f" ...
Adding a zero to a decimal
for a string: 0.1 --> 0.10 0.2 --> 0.20 0.3 --> 0.30 0.35 --> 0.35 Example: print(str(round(variableB.count('X') /len(variableA), 2))) I tried print("%.2f" %str(round(variableB.count('X')/len(variableA),2))), but I got TypeError: must be real number, not str then I tried print ("%.2f" % int(str(round(variableB.count(...
[ "An f-string (added in Python 3.6) is a perfectly valid way to accomplish this.\n>>> num = 3.1\n>>> f\"{num:.2f}\"\n'3.10'\n\nUsing %:\n>>> \"%.2f\" % num\n'3.10'\n\nBoth specify two digits of precision when displaying a floating point number.\n", "You can just use the % for string interpolation. This will work i...
[ 3, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074369254_python.txt
Q: Python 3 + GTK 4 - Buttons with pictures and labels look weird I develop a simple app for Linux, Kamarada Firstboot (source on GitLab), using Python 3 and GTK, and I'm migrating from GTK 3 to GTK 4. In case you are curious, you can see it in action if you download the Linux Kamarada ISO image and boot it using e.g...
Python 3 + GTK 4 - Buttons with pictures and labels look weird
I develop a simple app for Linux, Kamarada Firstboot (source on GitLab), using Python 3 and GTK, and I'm migrating from GTK 3 to GTK 4. In case you are curious, you can see it in action if you download the Linux Kamarada ISO image and boot it using e.g. VirtualBox. The following screenshots are from the current version...
[ "Using the GTK Inspector on some GNOME core apps and studying their source codes, I found a solution.\nEach software listed in GNOME Software corresponds to a GsSummaryTile, which inherits from GsAppTile, whose parent is the GtkButton. So, we are seeing buttons here:\n\nThe GsSummaryTile uses a GtkGrid (not a GtkBo...
[ 0 ]
[]
[]
[ "gtk", "gtk4", "pygtk", "python", "python_3.x" ]
stackoverflow_0074311441_gtk_gtk4_pygtk_python_python_3.x.txt
Q: How do i send a non-recursive query to a dns server in dnspython/python in general? I can't seem to figure out how to do this or if it is even doable, any help would be appreciated. I have not tried much due to the lack of answers i can find on google. A: If not doing a recursive query it means you already know ...
How do i send a non-recursive query to a dns server in dnspython/python in general?
I can't seem to figure out how to do this or if it is even doable, any help would be appreciated. I have not tried much due to the lack of answers i can find on google.
[ "If not doing a recursive query it means you already know which nameservers to contact, and over UDP or TCP.\ndnspython provides the query module to do exactly that, as explained in documentation at https://dnspython.readthedocs.io/en/stable/query.html#udp\nQuick POC:\nIn [1]: import dns.message\n\nIn [2]: import d...
[ 0 ]
[]
[]
[ "dns", "dnspython", "python", "python_3.x" ]
stackoverflow_0074367240_dns_dnspython_python_python_3.x.txt
Q: Why using getters/setters in python I stumbled across the below example of using getters and setters in a different question Preferred way of defining properties in Python: property decorator or lambda? Since python has implicit getters and setters, I wonder what the reason is to define them explicitly as below. I...
Why using getters/setters in python
I stumbled across the below example of using getters and setters in a different question Preferred way of defining properties in Python: property decorator or lambda? Since python has implicit getters and setters, I wonder what the reason is to define them explicitly as below. Is there any advantage in those examples o...
[ "Normally you should just use attribute access. getters and setters are pointless if they are doing nothing more than adding overhead\nThe nice thing about the way Python ties getters and setters to properties, is that you can easily change an attribute into a property without having to go and refactor all the code...
[ 3, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0021471359_python.txt
Q: Remove group if contains record with status 300 I would like to group records by ID from df and delete group if any of records has STATUS = 300. import pandas as pd df1 = pd.DataFrame( { "ID": ["A0", "A0", "A0", "A1", "A1", "A1", "A2", "A2", "A2"], "STATUS": [100, 100, 300, 100, 100, 100, 300,...
Remove group if contains record with status 300
I would like to group records by ID from df and delete group if any of records has STATUS = 300. import pandas as pd df1 = pd.DataFrame( { "ID": ["A0", "A0", "A0", "A1", "A1", "A1", "A2", "A2", "A2"], "STATUS": [100, 100, 300, 100, 100, 100, 300, 100, 100], }, index=[0, 1, 2, 3, 4, 5, 6, 7...
[ "df1.groupby('ID').filter(lambda x: 300 not in x['STATUS'].to_list())\n\n", "An efficient method to match any value from a list (see OP's comment) is to use isin coupled with groupby+transform:\ndf1[~df1['STATUS'].isin([300, 500]).groupby(df1['ID']).transform('any')]\n\noutput:\n ID STATUS\n3 A1 100\n4 A...
[ 7, 4, 2, 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0070435297_pandas_python.txt
Q: Add method to initialized object (python) I want to add a method to an object that has already been instantiated. The object is an instance of type vaderSentiment.vaderSentiment.SentimentIntensityAnalyzer (Vader is a popular NLP model). In order to get the predicted negative tone of a text I need to do the followi...
Add method to initialized object (python)
I want to add a method to an object that has already been instantiated. The object is an instance of type vaderSentiment.vaderSentiment.SentimentIntensityAnalyzer (Vader is a popular NLP model). In order to get the predicted negative tone of a text I need to do the following: # Import model from vaderSentiment.vaderSen...
[ "If you want to activate __get__ protocol (if you don't know what it is, you probably do want it:), add the method to the class, not the instance.\nSentimentIntensityAnalyzer.predict_proba = predict_proba\n\nYou'll also need del vader.predict_proba if you're doing it all in one session, to remove the instance funct...
[ 1 ]
[]
[]
[ "extension_methods", "methods", "python" ]
stackoverflow_0074369289_extension_methods_methods_python.txt
Q: Bioreactor Simulation for Ethanol Production using GEKKO I am trying to simulate a DAE system that solves a fed-batch bioreactor problem for ethanol production using GEKKO. This is done so I can later optimize it more easily to maximize Ethanol production. It was previously solved in MATLAB and produced the resul...
Bioreactor Simulation for Ethanol Production using GEKKO
I am trying to simulate a DAE system that solves a fed-batch bioreactor problem for ethanol production using GEKKO. This is done so I can later optimize it more easily to maximize Ethanol production. It was previously solved in MATLAB and produced the results as shown in the following figures: , , , , My problem now ...
[ "Nice application! Here are some suggestions to improve the convergence.\n\nRemove the lower and upper bounds when simulating. This was causing the \"no solution found\" error.\n\nVl = m.Var(value=1000, name='Vl') # lb=-0.0, ub=0.75*V\nXt = m.Var(value=0.1, name='Xt') # lb=-0.0, ub=10\nXv = m.Var(value...
[ 3 ]
[]
[]
[ "gekko", "python", "simulation" ]
stackoverflow_0074362585_gekko_python_simulation.txt
Q: Trying to delete a string in a list, but python wont detect it, using a csv file I am trying to delete certain elements of the beginning of my list, but when I run my code python wont detect the elements. I am currently trying to delete/find a string. my_list = [time,open,high,low,close 1666627...
Trying to delete a string in a list, but python wont detect it, using a csv file
I am trying to delete certain elements of the beginning of my list, but when I run my code python wont detect the elements. I am currently trying to delete/find a string. my_list = [time,open,high,low,close 1666627200,1754.7,1756.1,1750.5,1753.5] for i in my_list: my_list.remove('open') ...
[ "The strings in your list need to be in quotes, otherwise Python will not know that they are strings. For example:\nmy_list = [\"time\",\"open\",\"high\",\"low\",\"close\", 1666627200,1754.7,1756.1,1750.5,1753.5]\n\nAs for using the .remove() method, you do not need to use a for loop since .remove() iterates for yo...
[ 0 ]
[]
[]
[ "csv", "del", "list", "python", "string" ]
stackoverflow_0074369343_csv_del_list_python_string.txt
Q: trigger python script through changes on azure is there a way to trigger a python script to run when a specific file in the remote repo is updated? Also, the python script will update another file in the repo. I am using Azure for my project I am thinking of using pipeline by creating a task to check if the file w...
trigger python script through changes on azure
is there a way to trigger a python script to run when a specific file in the remote repo is updated? Also, the python script will update another file in the repo. I am using Azure for my project I am thinking of using pipeline by creating a task to check if the file was updated using powershell then based on that the n...
[ "Let me write a demo for you (The below is a DevOps YAML pipeline, based on Azure Git Repository).\ntrigger:\n branches:\n include:\n - main\n paths:\n include:\n - monitor/monitored_file.txt\n\npool:\n vmImage: ubuntu-latest\n\nsteps:\n- checkout: self\n persistCredentials: true #This will generate...
[ 0 ]
[]
[]
[ "azure", "azure_pipelines", "powershell", "python", "task" ]
stackoverflow_0074367845_azure_azure_pipelines_powershell_python_task.txt
Q: Python kernel dies on Jupyter Notebook with tensorflow 2 I installed tensorflow 2 on my mac using conda according these instructions: conda create -n tf2 tensorflow Then I installed ipykernel to add this new environment to my jupyter notebook kernels as follows: conda activate tf2 conda install ipykernel python -...
Python kernel dies on Jupyter Notebook with tensorflow 2
I installed tensorflow 2 on my mac using conda according these instructions: conda create -n tf2 tensorflow Then I installed ipykernel to add this new environment to my jupyter notebook kernels as follows: conda activate tf2 conda install ipykernel python -m ipykernel install --user --name=tf2 That seemed to work wel...
[ "After trying different things I run jupyter notebook on debug mode by using the command:\njupyter notebook --debug\n\nThen after executing the commands on my notebook I got the error message:\n\nOMP: Error #15: Initializing libiomp5.dylib, but found libiomp5.dylib already initialized.\nOMP: Hint This means that mu...
[ 12, 2, 1, 1, 0, 0, 0, 0 ]
[]
[]
[ "conda", "jupyter_notebook", "python", "tensorflow" ]
stackoverflow_0059576397_conda_jupyter_notebook_python_tensorflow.txt
Q: Sum column data while merging zip_code polygons to MultiPolygons in geopandas I m working with python on a Jupyter notebook I have the following dataset: +-------+------------+----------+---------------------------------------------------+ | zip | population | area# | polygon ...
Sum column data while merging zip_code polygons to MultiPolygons in geopandas
I m working with python on a Jupyter notebook I have the following dataset: +-------+------------+----------+---------------------------------------------------+ | zip | population | area# | polygon | +-------+------------+----------+---------------------------...
[ "The geopandas spatial equivalent of a pandas .groupby().aggreagte() operation is dissolve. Take a look through the docs, they're really helpful.\nOne key argument to note is the aggfunc argument. From the docs:\n\nThe aggfunc = argument defaults to ‘first’ which means that the first row of attributes values found ...
[ 1 ]
[]
[]
[ "geopandas", "python", "shapely" ]
stackoverflow_0074369166_geopandas_python_shapely.txt
Q: Is it possible to have a tuple contain only one tuple without the comma? Can I have a tuple that contains just one tuple (without any additional commas) like the following: ((0,1)) I know that if I do the following, this works (kind of): final_tuple = () input_tuple = (0,1) final_tuple = ((input_tuple,)) print(st...
Is it possible to have a tuple contain only one tuple without the comma?
Can I have a tuple that contains just one tuple (without any additional commas) like the following: ((0,1)) I know that if I do the following, this works (kind of): final_tuple = () input_tuple = (0,1) final_tuple = ((input_tuple,)) print(str(final_tuple)) Output: ((0,1),)
[ "((0, 1),) may be what you want.\n" ]
[ 1 ]
[]
[]
[ "data_structures", "python", "tuples" ]
stackoverflow_0074369497_data_structures_python_tuples.txt
Q: Possible to make labels appear when hovering over a point in matplotlib in stem plot? I am new to matplotlib and I am looking to label stems in a stem plot with x,y co-od when mouse hovers over that point. When I searched everything was meant for scatter plot (Possible to make labels appear when hovering over a po...
Possible to make labels appear when hovering over a point in matplotlib in stem plot?
I am new to matplotlib and I am looking to label stems in a stem plot with x,y co-od when mouse hovers over that point. When I searched everything was meant for scatter plot (Possible to make labels appear when hovering over a point in matplotlib? present code is like this: def plot_matching(mzs,ints,matching,scan_num)...
[ "To make a hovering label, you need to hook up a function to handle motion_notify_events:\n plt.connect('motion_notify_event', some_function)\n\nBelow is some code showing one way to do it. The hovering label behavior is produced by \ncursor = FollowDotCursor(ax, x, y)\n\nwhere ax is the axis, x and y are lists ...
[ 10, 0 ]
[]
[]
[ "matplotlib", "mouseover", "python" ]
stackoverflow_0020637113_matplotlib_mouseover_python.txt
Q: Calculate percentage change between values of column in Pandas dataframe I have a dataframe with some price indices across 5 years, from 2017 to 2021. It looks like this: Country Industry Year Index US Agriculture 2017 83 US Agriculture 2018 97.2 US Agriculture 2019 100 US Agriculture 2020 112 US Agriculture...
Calculate percentage change between values of column in Pandas dataframe
I have a dataframe with some price indices across 5 years, from 2017 to 2021. It looks like this: Country Industry Year Index US Agriculture 2017 83 US Agriculture 2018 97.2 US Agriculture 2019 100 US Agriculture 2020 112 US Agriculture 2021 108 Japan Mining 2017 88 Japan Mining 2018 93 Japan Mini...
[ "pct_change is computing a change relative to the previous value (which is why 2017 is NaN), and this doesn't seem to be what you want. If you want to compute a percentage change relative to 2019, as 2019 is already normalized to 100, simply subtract 100:\ndf['Percentage_Change'] = df['Index'].sub(100)\n\noutput:\n...
[ 4, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0072444301_pandas_python.txt
Q: change python interpreter during runtime there are two python environment 3.6 and 3.8 in my program.I can not unified the environment because there are different sdk come from different vendor. what can I do call the two sdk at the same time. I have try to change the environment by source different shell scripts.i...
change python interpreter during runtime
there are two python environment 3.6 and 3.8 in my program.I can not unified the environment because there are different sdk come from different vendor. what can I do call the two sdk at the same time. I have try to change the environment by source different shell scripts.it can not work.
[ "I didn't come up with a nested way to change interpreter during runtime, before and after Googling. A naive way could be splitting your program into two parts, with each part requiring only one interpreter.\nThen you can write a bash script to run these two parts sequentially or in whatever way you wish.\nA possib...
[ 0 ]
[]
[]
[ "interpreter", "linux", "python", "sdk" ]
stackoverflow_0074369473_interpreter_linux_python_sdk.txt
Q: Run Scrapy from a script I'm trying to run my script without the command "scrapy crawl...", I'm following this documentation https://docs.scrapy.org/en/latest/topics/practices.html#run-scrapy-from-a-script, but my code is not working. Would appreciate the help! import scrapy from scrapy.crawler import CrawlerProce...
Run Scrapy from a script
I'm trying to run my script without the command "scrapy crawl...", I'm following this documentation https://docs.scrapy.org/en/latest/topics/practices.html#run-scrapy-from-a-script, but my code is not working. Would appreciate the help! import scrapy from scrapy.crawler import CrawlerProcess class misbeneficiosSpider(...
[ "It looks like with some minor error checking your code would work fine.\nBTW there are two span.price tags per product card and I wasn't sure which you wanted. So I think I just specified the first one.\nFor example:\nimport scrapy\nfrom scrapy.crawler import CrawlerProcess\n\nclass misbeneficiosSpider(scrapy.Spi...
[ 0 ]
[]
[]
[ "python", "scrapy", "screen_scraping" ]
stackoverflow_0074369073_python_scrapy_screen_scraping.txt
Q: Dealing with "cracks" in the unary_union of several imprecise Polygons? I used shapely.ops.unary_union on a number of 6-sided shapely.geometry.Polygons, and obtained the following shape A: Note how there are two "cracks" in the upper part. These are not intended, and are presumably caused by some floating-point e...
Dealing with "cracks" in the unary_union of several imprecise Polygons?
I used shapely.ops.unary_union on a number of 6-sided shapely.geometry.Polygons, and obtained the following shape A: Note how there are two "cracks" in the upper part. These are not intended, and are presumably caused by some floating-point edge cases. If you construct another shape B that sits inside of A, and if A h...
[ "You can fix this by buffering and un-buffering the shape.\nHere's an example of a polygon with a small crack:\nfrom shapely.geometry import Polygon\nbad_polygon = Polygon([[0, 0], [1, 0], [1, 0.4999], [0.5, 0.5], [1, 0.5001], [1, 1], [0, 1], [0, 0]])\n\n\nTo fix it, expand the shape slightly, and contract it the s...
[ 3 ]
[]
[]
[ "python", "shapely" ]
stackoverflow_0074369418_python_shapely.txt
Q: issue on pandas_ta adx indicator when i run this code it's obvious get this error s missing close value. df['ADX'] = ta.adx(df['High'], df['Low'],length = 14) df output: TypeError Traceback (most recent call last) <ipython-input-23-1031ca130ef0> in <module> ----> 1 df['ADX'] = ta....
issue on pandas_ta adx indicator
when i run this code it's obvious get this error s missing close value. df['ADX'] = ta.adx(df['High'], df['Low'],length = 14) df output: TypeError Traceback (most recent call last) <ipython-input-23-1031ca130ef0> in <module> ----> 1 df['ADX'] = ta.adx(df['High'], df['Low'],length = 14)...
[ "The ADX indicator generates three dataframe columns, which is why there is this exception.\nDo this like this:\na = ta.adx(df['High'], df['Low'], df['Close'], length = 14)\ndf = df.join(a)\ndf\n\nyou will get three columns with data\n\n(ADX_14 DMP_14 DMN_14)\n\nand you can remove unnecessary columns with t...
[ 1, 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0071711033_dataframe_pandas_python.txt
Q: Exception in thread django-main-thread Traceback I am getting this error while trying to run a Django project. This happened when I cloned the project and run it for this first time, I am running it using a virtual environment (env1) C:\Users\Chiam\Desktop\fyp\odyera>python manage.py runserver Watching for file ch...
Exception in thread django-main-thread Traceback
I am getting this error while trying to run a Django project. This happened when I cloned the project and run it for this first time, I am running it using a virtual environment (env1) C:\Users\Chiam\Desktop\fyp\odyera>python manage.py runserver Watching for file changes with StatReloader Performing system checks... E...
[ "You are missing a package named pyrebase and its references have been used in your project. Install this package by the following instructions:\npip install pyrebase\n\nor,\npip3 install pyrebase\n\n" ]
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074369519_django_python.txt
Q: How to run Django project in background Recent I am running Django project on terminal using this command: python manage.py runserver 0.0.0.0:80 But Server is stopped by closing terminal, So I need to run server in background. How can I solve this issue? A: You can use the nohup command, so your command runs wi...
How to run Django project in background
Recent I am running Django project on terminal using this command: python manage.py runserver 0.0.0.0:80 But Server is stopped by closing terminal, So I need to run server in background. How can I solve this issue?
[ "You can use the nohup command, so your command runs without the terminal and all the outputs from the program will go to the file nohup.out (in the same directory you ran the command).\nUse like so:\nnohup python manage.py runserver 0.0.0.0:80\n\n", "You can use screen to run a program in background.\nThis shoul...
[ 0, 0, 0, 0 ]
[]
[]
[ "django", "python", "server" ]
stackoverflow_0071853022_django_python_server.txt
Q: pandas describe() and drop index (flatten column names) I made a data frame and then calculated some summary stats with describe, however it still has nested index. How can I drop these? import pandas as pd import numpy as np df_rand = pd.DataFrame(np.random.randint(0, 100, size=(100, 4)), columns=list('ABCD')) df...
pandas describe() and drop index (flatten column names)
I made a data frame and then calculated some summary stats with describe, however it still has nested index. How can I drop these? import pandas as pd import numpy as np df_rand = pd.DataFrame(np.random.randint(0, 100, size=(100, 4)), columns=list('ABCD')) df_rand = pd.melt(df_rand, value_vars=list('ABCD')) df_rand_sum...
[ "df_rand_summary.droplevel(level=0, axis=1)\n\noutput:\n count mean std min 25% 50% 75% max\n0 100.0 50.01 27.402534 0.0 28.00 52.5 73.00 99.0\n1 100.0 49.85 29.836042 0.0 22.75 54.0 79.25 99.0\n2 100.0 46.57 30.491017 0.0 19.75 40.0 76.00 99.0\n3 100.0 53.27 28.3038...
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074369639_pandas_python.txt
Q: Finding 0 - (Python Testing) random.uniform(0,1) Double Precision Floating Point This has been making my head hurt. I have also seen a detailed post on stack overflow about this situation that is a few years old and I would like to highlight some of the flaws from the discussions. I will highlight them in the next...
Finding 0 - (Python Testing) random.uniform(0,1) Double Precision Floating Point
This has been making my head hurt. I have also seen a detailed post on stack overflow about this situation that is a few years old and I would like to highlight some of the flaws from the discussions. I will highlight them in the next section. But the problem is outlined below. I am trying to find out if the random.uni...
[ "Python does not have a formal specification, and the behavior of random.uniform is not well specified. Given a and b with a ≤ 0 < b, I expect random.uniform(a, b) should be able to return zero, based on my minimum quality expectations. And, since it supports inverted ranges, it should also be able to return zero w...
[ 2 ]
[]
[]
[ "ieee_754", "proof", "python", "random" ]
stackoverflow_0074368837_ieee_754_proof_python_random.txt
Q: Edit a button more than once on a Discord bot using Nextcord So, I'm using Nextcord to make a Discord bot. I have some buttons that I would like to edit the style more than once. At first, I tried with interaction.response.edit_message(), which works great once but the second time, it gives me this error: nextcord...
Edit a button more than once on a Discord bot using Nextcord
So, I'm using Nextcord to make a Discord bot. I have some buttons that I would like to edit the style more than once. At first, I tried with interaction.response.edit_message(), which works great once but the second time, it gives me this error: nextcord.errors.InteractionResponded: This interaction has already been re...
[ "When you pass the button argument into the code you can use the button.style attribute to change the button style. You can also use button.label to change what the text is on the label.\nExample which turns green and says Hi! when you click it:\nimport nextcord\nfrom nextcord.ext import commands\n\n\n# Define a si...
[ 0 ]
[]
[]
[ "discord", "discord.py", "nextcord", "python" ]
stackoverflow_0072471882_discord_discord.py_nextcord_python.txt