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:
how to generate new table from existing table by grouping them aggregated MODE values
I've a data frame in pandas, and I'm trying to generate a new table based on existing table by grouping them with their aggregated mode value.
df
country scores attempts
india 11 6
india 12 3
india 12 3
india 12 7
in... | how to generate new table from existing table by grouping them aggregated MODE values | I've a data frame in pandas, and I'm trying to generate a new table based on existing table by grouping them with their aggregated mode value.
df
country scores attempts
india 11 6
india 12 3
india 12 3
india 12 7
india 10 3
india 12 3
pakistan 10 4
Pakistan 14 4
pakistan 14 5
srilanka 23 5
srilanka ... | [
"Use GroupBy.size first and then get first modes by DataFrameGroupBy.idxmax for indice by maximal counts:\nprint (df)\n country scores attempts\n0 india 11 6\n1 india 12 3\n2 india 12 3\n3 india 12 7\n4 india 10 3\n5 ... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074364426_pandas_python.txt |
Q:
How to send an image to a flask server using Postman
I need to send an image file to a flask server using Postman.I did send it using a web browser and "render template".But when i tried the same program with postman it showed "method not allowed"
.
I also tried /upload, but it says "bad request"
A:
To make thi... | How to send an image to a flask server using Postman | I need to send an image file to a flask server using Postman.I did send it using a web browser and "render template".But when i tried the same program with postman it showed "method not allowed"
.
I also tried /upload, but it says "bad request"
| [
"To make this work you'll need this:\n\nadd upload in your URL in postman.\nadd header Content-Type multipart/form-dataitem\nenter file as key for row in form data where you choose your file. On the screenshots I see that it is empty.\n\n",
"to run your code on postman you need to do some changes\nin the header s... | [
8,
1,
0
] | [] | [] | [
"flask_restful",
"postman",
"python"
] | stackoverflow_0048607198_flask_restful_postman_python.txt |
Q:
Boxplot with different y-axes and different y-scales in seaborn
I am trying to create a boxplot with different y-axes and y-scales in seaborn but got stuck here.
In matplotlib I can use the following code to obtain my result:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# create random d... | Boxplot with different y-axes and different y-scales in seaborn | I am trying to create a boxplot with different y-axes and y-scales in seaborn but got stuck here.
In matplotlib I can use the following code to obtain my result:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# create random dataframe with different scales
df = pd.DataFrame(np.random.rand(30, ... | [
"I found a solution on my own:\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n\n# create random dataframe with different scales\ndf = pd.DataFrame(np.random.rand(30, 5), columns=['A', 'B', 'C', 'D', 'E'])\ndf['A'] *= 5\ndf['C'] *= 10\ndf['E'] *= 15\n\n# create bo... | [
3,
0
] | [] | [] | [
"python",
"seaborn"
] | stackoverflow_0062404884_python_seaborn.txt |
Q:
How to sort x, y in format/name "output_x:465_y:159.png" in the list
my purpose is to cut the original img in sticker size, and recognize img to text, find if is duplicate or print wrong
for now I can save img's name as their (x,y) in original pic, such as "output_x:465_y:159.png"
I can sort sort (x,y) in list
... | How to sort x, y in format/name "output_x:465_y:159.png" in the list | my purpose is to cut the original img in sticker size, and recognize img to text, find if is duplicate or print wrong
for now I can save img's name as their (x,y) in original pic, such as "output_x:465_y:159.png"
I can sort sort (x,y) in list
xy_list = []
tem_list_x_and_y = [ ]
if (x != 0) and (y != 0):
# I sa... | [
"list = [[45, 47], [150, 47], [255, 47], [360, 47], [465, 47], [570, 47], [45, 159], [150, 159], [255, 159], [360, 159], [465, 159], [570, 159], [45, 273], [150, 273], [255, 273], [360, 273], [465, 273], [570, 273], [45, 389], [150, 389], [255, 389], [360, 389], [465, 389], [570, 389], [45, 504], [150, 504], [255, ... | [
0
] | [] | [] | [
"list",
"numpy",
"python",
"python_3.x",
"sorting"
] | stackoverflow_0074372091_list_numpy_python_python_3.x_sorting.txt |
Q:
I have two same example from Python why one is one of them is having syntax error?
Example 1 - this code is in one line, once I run this code it shows error.
print('Hello world') ''
Example 2 - here I enter the apostrophe in next line and it is showing no error. Why?
print('Hello world')
''
Example 1 came as er... | I have two same example from Python why one is one of them is having syntax error? | Example 1 - this code is in one line, once I run this code it shows error.
print('Hello world') ''
Example 2 - here I enter the apostrophe in next line and it is showing no error. Why?
print('Hello world')
''
Example 1 came as error
Example 2 printed the code.
what is the logic behind it?
| [
"A statement is a single block of Python code which does a single 'thing'. Generally, it is a single line of code, but it may span multiple lines, if you use brackets or an intended block. In some cases, multiple statements can also go on the same line if you separate them with a semicolon.\nAn expression is a bloc... | [
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074371816_python_python_3.x.txt |
Q:
Plot x-axis with time in Plotly Python
Is there a way to plot in Python using Plotly an x-axis, so it can show time, day, and week in different levels like the image here?enter image description here
So x-axis should be like this: time (i.e. from 9am to 5pm), brackets showing the day (i.e time slots from 9am to 5p... | Plot x-axis with time in Plotly Python | Is there a way to plot in Python using Plotly an x-axis, so it can show time, day, and week in different levels like the image here?enter image description here
So x-axis should be like this: time (i.e. from 9am to 5pm), brackets showing the day (i.e time slots from 9am to 5pm is one day - Monday), day (i.e. Monday), b... | [
"Yes, you can!\nyou can do it like this:\nimport plotly.express as px\n\ndf = px.data.stocks(indexed=True)-1\nfig = px.bar(df, x=df.index, y=\"GOOG\")\nfig.show()\n\nFor more information: please check Plotly Documentation\n"
] | [
0
] | [] | [] | [
"python",
"visualization"
] | stackoverflow_0074372115_python_visualization.txt |
Q:
Setup.py not found, when installing package from GitHub
I am trying to install the gsv8_python3 package from Github (https://github.com/me-systeme/gsv8pypi_python3) to my python, but python gives me following error:
ERROR: gsv8pypi_python3 from git+https://github.com/me-systeme/gsv8pypi_python3.git#egg=gsv8pypi_py... | Setup.py not found, when installing package from GitHub | I am trying to install the gsv8_python3 package from Github (https://github.com/me-systeme/gsv8pypi_python3) to my python, but python gives me following error:
ERROR: gsv8pypi_python3 from git+https://github.com/me-systeme/gsv8pypi_python3.git#egg=gsv8pypi_python3 does not appear to be a Python project: neither 'setup.... | [
"gsv8_python3 is not a traditional python package, so you cannot install it through a package manager. Please clone the code and use/implement it in your project directly.\n"
] | [
0
] | [] | [] | [
"github",
"python"
] | stackoverflow_0074372135_github_python.txt |
Q:
python: read file continuously, even after it has been logrotated
I have a simple python script, where I read logfile continuosly (same as tail -f)
while True:
line = f.readline()
if line:
print line,
else:
time.sleep(0.1)
How can I make sure that I can still read the logfile, after it... | python: read file continuously, even after it has been logrotated | I have a simple python script, where I read logfile continuosly (same as tail -f)
while True:
line = f.readline()
if line:
print line,
else:
time.sleep(0.1)
How can I make sure that I can still read the logfile, after it has been rotated by logrotate?
i.e. I need to do the same what tail -F... | [
"As long as you only plan to do this on Unix, the most robust way is probably to check so that the open file still refers to the same i-node as the name, and reopen it when that is no longer the case. You can get the i-number of the file from os.stat and os.fstat, in the st_ino field.\nIt could look like this:\nimp... | [
20,
5,
3,
0,
0
] | [] | [] | [
"file",
"python"
] | stackoverflow_0025537237_file_python.txt |
Q:
"Typeerror int is not collable" from http requests.post()
I know this question has come up a lot, but I couldn't find any suitable solution for my problem.
from the library requests I try to use something like this:
response = requests.post(url, headers, data, proxies)
if response.status_code >= 300:
logging.... | "Typeerror int is not collable" from http requests.post() | I know this question has come up a lot, but I couldn't find any suitable solution for my problem.
from the library requests I try to use something like this:
response = requests.post(url, headers, data, proxies)
if response.status_code >= 300:
logging.ERROR(f"MY ERROR MESSAGE")
elif response.status_code < 300:
... | [
"Problem is not with requests, but how do you use logging. All-uppercase things in logging are constants, if you meant to use function use all-lowercase, that is replace\nlogging.ERROR(f\"MY ERROR MESSAGE\")\n\nusing\nlogging.error(f\"MY ERROR MESSAGE\")\n\nand\nlogging.INFO(f\"MY INFO MESSAGE\")\n\nusing\nlogging.... | [
3
] | [] | [] | [
"integer",
"python",
"python_3.9",
"python_requests"
] | stackoverflow_0074372129_integer_python_python_3.9_python_requests.txt |
Q:
How To Create a File Dialog Using Python
I started coding 3 days ago! So far it has been fun, but I have encoured my first road block.
I'm wanting to create a "FILE" button that performs all the same functions as it would in any other application: Open, Save, and Save as.
What I can do so far is click the file but... | How To Create a File Dialog Using Python | I started coding 3 days ago! So far it has been fun, but I have encoured my first road block.
I'm wanting to create a "FILE" button that performs all the same functions as it would in any other application: Open, Save, and Save as.
What I can do so far is click the file button to expose my three options.
from tkinter i... | [
"I think you might be looking for something like below:\n\nYou may be able to try something like below:\nimport tkinter as tk\nfrom tkinter import ttk\nfrom tkinter import filedialog as fd\nfrom tkinter.messagebox import showinfo\n\n# create the root window\nroot = tk.Tk()\nroot.title('Tkinter Dialog')\nroot.resiza... | [
1
] | [] | [] | [
"dialog",
"file",
"python",
"tk_toolkit",
"user_interface"
] | stackoverflow_0074366874_dialog_file_python_tk_toolkit_user_interface.txt |
Q:
Calling python script in makefile run in Cygwin results in No Such File or Directory
I am executing a Makefile in CYGWIN on Windows. The rule in the makefile calls a python script in another directory and passes arguments.
Here is the rule in the makefile:
$(OUTDIR)/toolchain:
$(NDK_PATH)/build/tools/make_sta... | Calling python script in makefile run in Cygwin results in No Such File or Directory | I am executing a Makefile in CYGWIN on Windows. The rule in the makefile calls a python script in another directory and passes arguments.
Here is the rule in the makefile:
$(OUTDIR)/toolchain:
$(NDK_PATH)/build/tools/make_standalone_toolchain.py \
--api=24 \
--arch=arm64 \
--install-... | [
"Try the conversion to cygwin path :\n$(OUTDIR)/toolchain:\n $$(cygpath $(NDK_PATH)/build/tools/make_standalone_toolchain.py) \\\n --api=24 \\\n --arch=arm64 \\\n --install-dir=$@ \\\n --verbose=2\n\n"
] | [
1
] | [] | [] | [
"cygwin",
"makefile",
"python"
] | stackoverflow_0074367638_cygwin_makefile_python.txt |
Q:
cloudscraper.exceptions.CloudflareChallengeError: Detected a Cloudflare version 2 challenge. Error when I used cloudscraper module with python
so I'm trying to bypass the cloudflare protection of a website to scrape some items from them but the Cloudscraper python module is not working.
Whenever I run it, I receiv... | cloudscraper.exceptions.CloudflareChallengeError: Detected a Cloudflare version 2 challenge. Error when I used cloudscraper module with python | so I'm trying to bypass the cloudflare protection of a website to scrape some items from them but the Cloudscraper python module is not working.
Whenever I run it, I receive this error:
cloudscraper.exceptions.CloudflareChallengeError: Detected a Cloudflare version 2 challenge, This feature is not available in the open... | [
"The cloudscraper library do not provide the bypass for cloudfare version 2 captcha in the free version.\nSo in order to scrape such sites, one of the alternatives is to use a third party captcha solver.\nCloud scraper currently supports the following provider:\n\n2captcha\nanticaptcha\nCapMonster Cloud\ndeathbycap... | [
2
] | [
"I encountered the same error when using scrapy + cloudscraper, but then I seted cookie_enable=true just fine:\nError\nTraceback (most recent call last):\ncloudscraper.exceptions.CloudflareChallengeError: Detected a Cloudflare version 2 Captcha challenge, This feature is not available in the opensource (free) versi... | [
-3
] | [
"beautifulsoup",
"cloudflare",
"python"
] | stackoverflow_0065733333_beautifulsoup_cloudflare_python.txt |
Q:
How to create a .exe of a python script
I've been trying to use pyinstaller, but it never creates it. There is always this error:
I've found that if I put this, it should work, but it doesn't. Does somebody know how to do it?
.\pyinstaller --onefile -w 'filename.py'
A:
Add Your pyinstaller directory PATH to en... | How to create a .exe of a python script | I've been trying to use pyinstaller, but it never creates it. There is always this error:
I've found that if I put this, it should work, but it doesn't. Does somebody know how to do it?
.\pyinstaller --onefile -w 'filename.py'
| [
"Add Your pyinstaller directory PATH to environment variable.\n",
"Search for 'Edit system environment variables' in control panel and add (C:\\Users\"Your username\"\\AppData\\Local\\Programs\\Python\\Python311\\Scripts) to PATH\n"
] | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074372065_python.txt |
Q:
Automatic deletion or expiration of GAE datastore entities
I'm building my first app with GAE to allow users to run elections, and I create an Election entity for each election.
To avoid storing too much data, I'd like to automatically delete an Election entity after a certain period of time -- say three months ... | Automatic deletion or expiration of GAE datastore entities | I'm building my first app with GAE to allow users to run elections, and I create an Election entity for each election.
To avoid storing too much data, I'd like to automatically delete an Election entity after a certain period of time -- say three months after the end of the election. Is it possible to do this automa... | [
"Assuming you have a DateProperty on the entities indicating when the election ended, you can have a cron job search for any older than 3 months every night and delete them.\n",
"You can use the app engine \"cron\" facility to run tasks periodically. Each task is basically a URL which gets called by the cronjob, ... | [
5,
4,
1,
1
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0005079885_google_app_engine_google_cloud_datastore_python.txt |
Q:
PyTorch 1.12 on Mac Monterey
I cannot use PyTorch 1.12.1 on macOS 12.6 Monterey with M1 chip.
Tried to install and run from Python 3.8, 3.9 and 3.10 with the same result.
I think that PyTorch was working before I updated macOS to Monterey. And the Rust bindings, tch-rs are still working.
Here is my install and the... | PyTorch 1.12 on Mac Monterey | I cannot use PyTorch 1.12.1 on macOS 12.6 Monterey with M1 chip.
Tried to install and run from Python 3.8, 3.9 and 3.10 with the same result.
I think that PyTorch was working before I updated macOS to Monterey. And the Rust bindings, tch-rs are still working.
Here is my install and the error messages I get when trying ... | [
"I recommend not touching your system python installations for your own projects, instead the recommended way is using conda (see here). The reason is that each conda environment encapsulates a whole separate python installation that does not interfere (and doesn't get interfered with) with any other programs. This... | [
1,
0
] | [] | [] | [
"apple_m1",
"homebrew",
"miniconda",
"python",
"pytorch"
] | stackoverflow_0073986257_apple_m1_homebrew_miniconda_python_pytorch.txt |
Q:
How to properly config a django application on cpanel
Before now, the main domain was serving a WordPress website but I needed to replace that with a new django application.
I was able to successfully deploy the Django application to cPanel, and the application was served on a subdomain without any problems. But w... | How to properly config a django application on cpanel | Before now, the main domain was serving a WordPress website but I needed to replace that with a new django application.
I was able to successfully deploy the Django application to cPanel, and the application was served on a subdomain without any problems. But when I edit the application url to point to the main domain,... | [
"I figured out that it was the wordpress installation that was interfering with the Django application, so I renamed the wordpress index.php file, and everything works now. This means that the problem is not with the Django configuration but with the fact that a WordPress website was running on that domain before.\... | [
0
] | [] | [] | [
"cpanel",
"deployment",
"django",
"python",
"wordpress"
] | stackoverflow_0074366525_cpanel_deployment_django_python_wordpress.txt |
Q:
Is there an html generator that will allow me to recreate the look from the Microsoft word or Excel
I need to generate nice-looking reports for my boss. I write program in python to generate reports but they are not looking too good, data is fine but I need to make them look better. I try to do it in HTML/CSS but ... | Is there an html generator that will allow me to recreate the look from the Microsoft word or Excel | I need to generate nice-looking reports for my boss. I write program in python to generate reports but they are not looking too good, data is fine but I need to make them look better. I try to do it in HTML/CSS but I am bad at the front end so I start looking for an automatic generator but I can't find it good enough. ... | [
"Create Your HTML Document\nUse one of the following two methods to create your new HTML document.\nMethod 1\n1- Start Microsoft Word.\n2- In the New Document task pane, click Blank Web Page under New.\n3- On the File menu, click Save.\nNOTE: The Save as type box defaults to Web Page (*.htm; *.html).\n4- In the Fil... | [
0
] | [] | [] | [
"css",
"excel",
"html",
"ms_word",
"python"
] | stackoverflow_0074372264_css_excel_html_ms_word_python.txt |
Q:
TypeError: unsupported operand type(s) for /: 'str' and 'str' with string concatenation
t_c = []
for i in range (10,41,5):
t_c.append(max("Time"+str(i)+"J") - min("Time"+str(i)+"J"))
Whenever I run this code, I get an error
"TypeError: unsupported operand type(s) for /: 'str' and 'str'"
Here, Time10J,Time15J,... | TypeError: unsupported operand type(s) for /: 'str' and 'str' with string concatenation | t_c = []
for i in range (10,41,5):
t_c.append(max("Time"+str(i)+"J") - min("Time"+str(i)+"J"))
Whenever I run this code, I get an error
"TypeError: unsupported operand type(s) for /: 'str' and 'str'"
Here, Time10J,Time15J,.....,Time40J are numpy data arrays
I tried
t_c = []
for i in range (10,41,5):
t_c.append... | [
"From MYousefi's comment:\nt_c = []\nfor i in range(10,41,5):\n t_c.append(max(eval(\"Time\"+str(i)+\"J\")) - min(eval(\"Time\"+str(i)+\"J\")))\n\nwill produce the result you're after.\nHowever, storing variables like this is maybe not best practice? When you create your series of arrays I think you would benefi... | [
0
] | [] | [] | [
"concatenation",
"operands",
"python",
"string",
"typeerror"
] | stackoverflow_0074372104_concatenation_operands_python_string_typeerror.txt |
Q:
Checking if variable exists in Namespace
I'm trying to use the output of my argparse (simple argparse with just 4 positional arguments that each kick of a function depending on the variable that is set to True)
Namespace(battery=False, cache=True, health=False, hotspare=False)
At the moment I'm trying to figure o... | Checking if variable exists in Namespace | I'm trying to use the output of my argparse (simple argparse with just 4 positional arguments that each kick of a function depending on the variable that is set to True)
Namespace(battery=False, cache=True, health=False, hotspare=False)
At the moment I'm trying to figure out how to best ask python to see when one of t... | [
"You can use hasattr(ns, \"battery\") (assume ns = Namespace(battery=False, cache=True, health=False, hotspare=False)).\nMuch cleaner than vars(ns).get(\"battery\") I would think.\n",
"Use vars() to convert your namespace to a dictionary, then use dict.get('your key') which will return your object if it exists, o... | [
4,
3,
2,
0
] | [] | [] | [
"argparse",
"namespaces",
"python"
] | stackoverflow_0030617742_argparse_namespaces_python.txt |
Q:
!_map1.empty() in function 'cv::remap'
I am trying to build this stereo vision obstacle distance detection system using a tutorial, but keep hitting a brick wall and could use some advice, please.
When running either disparity2depth or obstacle_avoidance files, I get the same xml file read errors and remap error a... | !_map1.empty() in function 'cv::remap' | I am trying to build this stereo vision obstacle distance detection system using a tutorial, but keep hitting a brick wall and could use some advice, please.
When running either disparity2depth or obstacle_avoidance files, I get the same xml file read errors and remap error at both rectification lines.
\[error:0@2.333... | [
"The issue was with the CWD.\nassert os.path.exists(\"data/stereo_rectify_maps.xml\"), os.getcwd()\nSolved the issue. At first the statement passed/returned nothing, which made me think the file might be corrupted. However, after reloading the IDE and running again, the statement returned the path it was looking fo... | [
0
] | [] | [] | [
"computer_vision",
"object_detection",
"opencv",
"python"
] | stackoverflow_0074258524_computer_vision_object_detection_opencv_python.txt |
Q:
How to keep missing item from being overwritten in JSON?
I have a file "stocks.json" that stores information about stock prices retrieved from an API. I wrote a Python function that takes in each symbol in the "stocks.json" file, adds each symbol to the API URL, and makes an API call with the URL. The function the... | How to keep missing item from being overwritten in JSON? | I have a file "stocks.json" that stores information about stock prices retrieved from an API. I wrote a Python function that takes in each symbol in the "stocks.json" file, adds each symbol to the API URL, and makes an API call with the URL. The function then takes whatever data is on the API and dumps it into the JSON... | [
"data (retrieved from the API based on stock_info):\n\nthose data are arrays of object (where stock is object)\n\nif i understand correctly this problem - that there isn't key - for identity, which stock is it?\nin this arrays of objects - was transformed into dictionary (where key = symbol):\n\nstocksWithoutKey = ... | [
1,
0
] | [] | [] | [
"api",
"dataframe",
"json",
"python"
] | stackoverflow_0074359171_api_dataframe_json_python.txt |
Q:
python json create list
Good afternoon.
I'm getting json from a provider, but for some reason it converts the data to a list format, not a dict
Provider return json
def bal(number, token):
headers = {
'Authorization': 'Bearer ' + token,
'Accept': 'application/json'
}
response = request... | python json create list | Good afternoon.
I'm getting json from a provider, but for some reason it converts the data to a list format, not a dict
Provider return json
def bal(number, token):
headers = {
'Authorization': 'Bearer ' + token,
'Accept': 'application/json'
}
response = requests.get('https://api.provider.c... | [
"Often you can guess the kind of response you will obtain by looking at the name of the endpoint.\nHere you hit the endpoint https://api.provider.com/idS.\nWith S at the end for plural.\nIn this case you're likely to expect a response with many items, returned as a JSON Array.\n"
] | [
0
] | [] | [] | [
"json",
"parsing",
"python"
] | stackoverflow_0074372270_json_parsing_python.txt |
Q:
Spark 3.2.2 Joining same dataframe multiple time does not drop column
We have some PySpark code that joins a table table_a, twice to another table table_b using the following code. After joining the table twice, we drop the key_hash column from the output DataFrame.
This code was working fine in spark version 3.0.... | Spark 3.2.2 Joining same dataframe multiple time does not drop column | We have some PySpark code that joins a table table_a, twice to another table table_b using the following code. After joining the table twice, we drop the key_hash column from the output DataFrame.
This code was working fine in spark version 3.0.1. Since upgrading to spark version 3.2.2, the behaviour has changed and du... | [
"Hi I also have an issue with this one, I don't know if its a bug or not but it seems not happening all time\nutilization_raw = time_lab.crossJoin(approved_listing)\nutilization_raw = utilization_raw\\\n.join(availability_series,\n ((utilization_raw.date_series == availability_series.availability_date)&\\\n ... | [
0
] | [] | [] | [
"apache_spark",
"pyspark",
"python"
] | stackoverflow_0073739687_apache_spark_pyspark_python.txt |
Q:
EasyAuth on Azure Function App errors out custom oidc provider
We have a Python Linux azure function that is connected to a custom oidc provider and azure ad to provide authentication to the HTTP triggered functions using Microsofts easyauth.
After the initial setup, the azure function was working and has been wor... | EasyAuth on Azure Function App errors out custom oidc provider | We have a Python Linux azure function that is connected to a custom oidc provider and azure ad to provide authentication to the HTTP triggered functions using Microsofts easyauth.
After the initial setup, the azure function was working and has been working for the last few months.
In the last 2 days, our application su... | [
"Could it be due to this: https://github.com/Azure/app-service-announcements/issues/404\n\nUse RSACNG when validating tokens to add PS256 support\n\nEDIT: Also experiencing this issue as of this morning. I'm currently trying to manually downgrade the version using this command az webapp auth update --name xxx --res... | [
1,
0,
0,
0
] | [] | [] | [
"azure",
"azure_functions",
"easy_auth",
"openid_connect",
"python"
] | stackoverflow_0074319419_azure_azure_functions_easy_auth_openid_connect_python.txt |
Q:
Python make chart from input list
I have this working function that takes 2 inputs as .csv files and shows chart of the data.
What I would like to do is to turn function input into list instead of 2 files.
This is the function:
def Graph(first_file,second_file):
fig = make_subplots(rows=1, cols=3)
list_o... | Python make chart from input list | I have this working function that takes 2 inputs as .csv files and shows chart of the data.
What I would like to do is to turn function input into list instead of 2 files.
This is the function:
def Graph(first_file,second_file):
fig = make_subplots(rows=1, cols=3)
list_of_atributes = ["Total", "Clean", "Dirty... | [
"If I understand correctly, you want your function to plot things based on a list of files, so from 1 to n files, not specifically 2.\nYou could try this :\ndef Graph(files):\n \n fig = make_subplots(rows=1, cols=len(files)+1)\n\n for file_idx in range(len(files)) :\n\n list_of_atributes = [\"Total\", ... | [
1,
0
] | [] | [] | [
"plotly",
"python"
] | stackoverflow_0074372320_plotly_python.txt |
Q:
Remove rows from table by using slice or pandas functions
I have csv file with data , but there rows i dont need. So task is remove rows from table.
For example:
0 A
1 B
2 C
3 D
4 E * to delete
5 F *
6 G *
7 H *
8 I
9 J
10 k
11 L
12 M *
13 N *
14 O *
15 P *
So i want remove last 4 rows for each 8 rows i... | Remove rows from table by using slice or pandas functions | I have csv file with data , but there rows i dont need. So task is remove rows from table.
For example:
0 A
1 B
2 C
3 D
4 E * to delete
5 F *
6 G *
7 H *
8 I
9 J
10 k
11 L
12 M *
13 N *
14 O *
15 P *
So i want remove last 4 rows for each 8 rows in table . In table 3089 rows
I try to slice table , but no good... | [
"Use numpy to craft a mask:\nimport numpy as np\n\nmask = (np.arange(len(df))%8//4) == 0\n\nout = df[mask]\n\nOther option:\nmask = np.arange(len(df))%8 < 4\n\nout = df[mask]\n\noutput:\n col\n0 A\n1 B\n2 C\n3 D\n8 I\n9 J\n10 k\n11 L\n\nHow it works\nWe first get the modulo 8 to get the posi... | [
2,
0
] | [] | [] | [
"pandas",
"python",
"slice"
] | stackoverflow_0074371986_pandas_python_slice.txt |
Q:
Is it the best way to create an array from a list of objects?
I have a list of objects stored in socialmedias variable. One parameter of SocialMedia class is called username. I want to create an array with all usernames from that list of objects socialmedias and I want to be sure I use the best way.
socialmedias =... | Is it the best way to create an array from a list of objects? | I have a list of objects stored in socialmedias variable. One parameter of SocialMedia class is called username. I want to create an array with all usernames from that list of objects socialmedias and I want to be sure I use the best way.
socialmedias = [obj1, obj2, obj3, ..., objN]
usernames = []
for sm in socialmedi... | [
"yes there is, you can use list comprehension like:\nusernames = [sm.username for sm in socialmedias]\n",
"You could do\nusernames = [sm.username for sm in socialmedias] \n\nFrom: Extract list of attributes from list of objects in python\n",
"By memory I would say by using list comprehension:\nsocialmedias = [o... | [
2,
0,
0,
0
] | [] | [] | [
"python",
"python_3.9",
"python_3.x"
] | stackoverflow_0074372036_python_python_3.9_python_3.x.txt |
Q:
collection.Mutablemapping Error in pyrebase Import
I have installed pyrebase library and tried importing it Like
import pyrebase
It gives following Error and i dont know how to fix it!
Traceback (most recent call last):
File "fire.py", line 1, in <module>
import pyrebase
File "env\lib\site-packages\pyreba... | collection.Mutablemapping Error in pyrebase Import | I have installed pyrebase library and tried importing it Like
import pyrebase
It gives following Error and i dont know how to fix it!
Traceback (most recent call last):
File "fire.py", line 1, in <module>
import pyrebase
File "env\lib\site-packages\pyrebase\__init__.py", line 1, in <module>
from .pyrebase ... | [
"This happens because pyrebase uses a deprecated collections module. Fixing this issue is possible but it leads to a chain of issues, I would recommend you to used pyrebase4 instead.\n"
] | [
0
] | [] | [] | [
"firebase",
"pyrebase",
"python"
] | stackoverflow_0072459623_firebase_pyrebase_python.txt |
Q:
Percentage Coverage in Python Pandas
If I have this value.counts() dataframe (already ascending) :
A 20
B 15
C 15
D 10
E 10
F 10
G 8
H 5
I 5
Then I want to get a first 70% for example, then what I get is
A
B
C
D
E
Do pandas have function for that ? I have tried with groupby but it does not work. Or should I c... | Percentage Coverage in Python Pandas | If I have this value.counts() dataframe (already ascending) :
A 20
B 15
C 15
D 10
E 10
F 10
G 8
H 5
I 5
Then I want to get a first 70% for example, then what I get is
A
B
C
D
E
Do pandas have function for that ? I have tried with groupby but it does not work. Or should I code manually like with for loop or somethi... | [
"Assuming X, Y the column names, you can compare the cumsum to be lower or equal (le) to 70, and slice with boolean indexing:\ndf.loc[df['Y'].cumsum().le(70), 'X']\n\nAlternative by position (first and second column):\ndf.loc[df.iloc[:, 1].cumsum().le(70), df.columns[0]]\n\noutput:\n0 A\n1 B\n2 C\n3 D\n... | [
2
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074372576_dataframe_pandas_python.txt |
Q:
Python: How to remove default options on Typer CLI?
I made a simple CLI using Typer and Pillow to change image opacity and this program only have one option: opacity.
But when I run python opacity.py --help it gives me the two typerCLI options:
Options:
--install-completion [bash|zsh|fish|powershell|pwsh]
... | Python: How to remove default options on Typer CLI? | I made a simple CLI using Typer and Pillow to change image opacity and this program only have one option: opacity.
But when I run python opacity.py --help it gives me the two typerCLI options:
Options:
--install-completion [bash|zsh|fish|powershell|pwsh]
Install completion for the sp... | [
"I met the same problem today, i couldn't find anything except this question so dived in the source to find how Typer automatically adds this line in app, so i found this, when Typer initialiazing itself it automatically sets add_completion to True\nclass Typer:\n def __init__(add_completion: bool = True)\n\nSo ... | [
15,
1
] | [] | [] | [
"python",
"python_imaging_library",
"typer"
] | stackoverflow_0062494622_python_python_imaging_library_typer.txt |
Q:
flask jsonify returns returns Decimal object as string instead of float
The jsonify function in flask seems to return strings for all Decimal values instead of floats. Is there a builtin way to go around this?
In the meantime, I've had to manually remap it, but would like to avoid this if possible
from decimal imp... | flask jsonify returns returns Decimal object as string instead of float | The jsonify function in flask seems to return strings for all Decimal values instead of floats. Is there a builtin way to go around this?
In the meantime, I've had to manually remap it, but would like to avoid this if possible
from decimal import Decimal
result = {
k: (float(v) if isinstance(v, Decimal) else v)
... | [
"I dont get this error, what exactly are you trying to return?\nfrom flask import jsonify\nfrom decimal import Decimal\nv = Decimal(0.1)\nreturn jsonify({\"0.1\": float(v)})\n\n-->\n{\n \"0.1\": 0.1\n}\n\nwithout conversion:\nv = Decimal(0.1)\nreturn jsonify({\"0.1\": v})\n\n{\n \"0.1\": 0.1000000000000000055... | [
0
] | [] | [] | [
"flask",
"json",
"python"
] | stackoverflow_0074341596_flask_json_python.txt |
Q:
Why is the global variable not showing the correct value
The code is creating a random number from a low value and a high value supplied by the user. Why, when printing the value of the comp_num inside the function it returns the correct value but when printing it at the end of the sequence it is 0.
import random ... | Why is the global variable not showing the correct value | The code is creating a random number from a low value and a high value supplied by the user. Why, when printing the value of the comp_num inside the function it returns the correct value but when printing it at the end of the sequence it is 0.
import random
comp_num = 0
def generateNumber():
comp_num = random.rand... | [
"You need to say inside the function that comp_num is a global variable:\nimport random \n\ncomp_num = 0\n\ndef generateNumber():\n global comp_num\n comp_num = random.randint(low_number,high_number)\n print(comp_num)\n\nlow_number = int(input(\"Please select the minimum number\"))\nhigh_number = int(input... | [
1,
0
] | [] | [] | [
"python",
"scope",
"variables"
] | stackoverflow_0074372458_python_scope_variables.txt |
Q:
How to get a TypedDict corresponding to a function signature?
Say I've got a function signature like this:
def any_foo(
bar: Bar,
with_baz: Optional[Baz] = None,
with_datetime: Optional[datetime] = None,
effective: Optional[bool] = False,
) -> Foo
I could of course just copy its declaration and fi... | How to get a TypedDict corresponding to a function signature? | Say I've got a function signature like this:
def any_foo(
bar: Bar,
with_baz: Optional[Baz] = None,
with_datetime: Optional[datetime] = None,
effective: Optional[bool] = False,
) -> Foo
I could of course just copy its declaration and fiddle with it enough to create the following TypedDict:
AnyFooParame... | [
"The result of any_foo.__annotations__ is exactly what you want. For example:\nfrom typing import Optional\ndef any_foo(\n req_int: int,\n opt_float: Optional[float] = None,\n opt_str: Optional[str] = None,\n opt_bool: Optional[bool] = False,\n) -> int:\n pass\n\nAnd with any_foo.__annotations__, you... | [
1
] | [] | [] | [
"python",
"python_3.x",
"typing"
] | stackoverflow_0063893783_python_python_3.x_typing.txt |
Q:
im trying to do a Typing bot with delay
Is my code correct? I just want to check. and is there a way that I can make it better.
import time
import random
string = "The quick brown fox jumps over the lazy dog"
def TypeDelay(string):
for i in range(len(string)):
delay = random.uniform(0,1.1)
ti... | im trying to do a Typing bot with delay | Is my code correct? I just want to check. and is there a way that I can make it better.
import time
import random
string = "The quick brown fox jumps over the lazy dog"
def TypeDelay(string):
for i in range(len(string)):
delay = random.uniform(0,1.1)
time.sleep(delay)
print(string[i], end=... | [
"You need to add the flush parameter to the print() function call to see the output immediately, otherwise the string will appear as a single blob of text.\nIn my code below I've added a generator to decouple the delay functionality from the print loop.\nimport random\nimport time\n\ndef characters_with_delay(str):... | [
1,
0
] | [] | [] | [
"python",
"python_3.10"
] | stackoverflow_0074372253_python_python_3.10.txt |
Q:
Need some debugging in my program: filling up SQL tables with data retrieved from a Python program
I am filling up SQL tables with data that I have retrieved from a Python program. I am using Visual Studio Code for the Python program and MySQL Workbench 8.0 for SQL. There are some errors in it that I cannot resolv... | Need some debugging in my program: filling up SQL tables with data retrieved from a Python program | I am filling up SQL tables with data that I have retrieved from a Python program. I am using Visual Studio Code for the Python program and MySQL Workbench 8.0 for SQL. There are some errors in it that I cannot resolve.
Here is my code:
from gettext import install #Importing PyMySQL... | [
"\"Duplicate entry '0' for key 'ref_info.PRIMARY'\" means that you try to insert a record in the ref_info table that already exists.\nA primary key is unique.\n"
] | [
0
] | [] | [] | [
"debugging",
"mysql",
"python"
] | stackoverflow_0074372581_debugging_mysql_python.txt |
Q:
How to solve array problem to check if element is greater, less than or equal its neighbor
I'm still learning more about programming and have a problem with my code.
I have an array
data = [5,4,4,4,4,3,3,8] the expected result should be P,n,n,n,n,n,v,p. but I'm getting this p,n,n,n,p,n,n,p
#data = [2,1,4,5,5,5,4] ... | How to solve array problem to check if element is greater, less than or equal its neighbor | I'm still learning more about programming and have a problem with my code.
I have an array
data = [5,4,4,4,4,3,3,8] the expected result should be P,n,n,n,n,n,v,p. but I'm getting this p,n,n,n,p,n,n,p
#data = [2,1,4,5,5,5,4] expected result p,v,n,n,n,p,v (my code works for this. but the code must be able to solve the t... | [
"Assuming:\n\nthat a peak is the last point of a stretch of identical values if it is strictly higher than the previous and next stretches (or of only one neighbor on the ends)\nthat is valley is the same for a strictly lower value compared to the neighbor(s)\nall other points being \"n\"\n\nYou can use itertools.g... | [
1
] | [] | [] | [
"algorithm",
"conditional_statements",
"python"
] | stackoverflow_0074371926_algorithm_conditional_statements_python.txt |
Q:
Convert string to Enum in Python
What's the correct way to convert a string to a corresponding instance of an Enum subclass? Seems like getattr(YourEnumType, str) does the job, but I'm not sure if it's safe enough.
As an example, suppose I have an enum like
class BuildType(Enum):
debug = 200
release = 400
... | Convert string to Enum in Python | What's the correct way to convert a string to a corresponding instance of an Enum subclass? Seems like getattr(YourEnumType, str) does the job, but I'm not sure if it's safe enough.
As an example, suppose I have an enum like
class BuildType(Enum):
debug = 200
release = 400
Given the string 'debug', how can I g... | [
"This functionality is already built in to Enum:\n>>> from enum import Enum\n>>> class Build(Enum):\n... debug = 200\n... build = 400\n... \n>>> Build['debug']\n<Build.debug: 200>\n\nThe member names are case sensitive, so if user-input is being converted you need to make sure case matches:\nan_enum = input('Wh... | [
465,
40,
13,
12,
2,
1,
1,
0
] | [
"I just want to notify this does not work in python 3.6\nclass MyEnum(Enum):\n a = 'aaa'\n b = 123\n\nprint(MyEnum('aaa'), MyEnum(123))\n\nYou will have to give the data as a tuple like this\nMyEnum(('aaa',))\n\nEDIT: \nThis turns out to be false. Credits to a commenter for pointing out my mistake\n"
] | [
-2
] | [
"enums",
"python",
"string",
"type_conversion"
] | stackoverflow_0041407414_enums_python_string_type_conversion.txt |
Q:
Get the missing column timestamps
I have a filtered time series dataframe. When I see the missing datetime columns, the figure obtained is as below:
df.datetime.diff().plot()
Here, I can manually see the missing datetime values as the spikes. Is there a way to get the start and stop of these datetime column, if f... | Get the missing column timestamps | I have a filtered time series dataframe. When I see the missing datetime columns, the figure obtained is as below:
df.datetime.diff().plot()
Here, I can manually see the missing datetime values as the spikes. Is there a way to get the start and stop of these datetime column, if for example they are missing for more t... | [
"You can use:\n# ensure datetime\ndf['datetime'] = pd.to_datetime(df['datetime'])\n\n# identify values above 1min\nm = df['datetime'].diff().gt('1min')\n\n# group the consecutive values above threshold\nout = (df.loc[m, 'datetime'].groupby((~m).cumsum())\n .agg(start='min', stop='max')\n .reset_inde... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python",
"time_series"
] | stackoverflow_0074371471_dataframe_pandas_python_time_series.txt |
Q:
How can I not using \n without separating the list in pandas dataframe?
I'm trying to use \n to add a new line in pandas dataframe
Here is the sample data to test:
df = pd.DataFrame({'KEY': [4507,211,5294,2233,2260],'NAME':['kim young','laa eudong','kill gil','lee suk','No hee'],'FIND_DATE':[20130518,20140626,2014... | How can I not using \n without separating the list in pandas dataframe? | I'm trying to use \n to add a new line in pandas dataframe
Here is the sample data to test:
df = pd.DataFrame({'KEY': [4507,211,5294,2233,2260],'NAME':['kim young','laa eudong','kill gil','lee suk','No hee'],'FIND_DATE':[20130518,20140626,20140215,20141121,20140910],'EVENT_DTL':['A','B','C','D','E']})
df.loc[:3,'EVENT... | [
"some kind of groupBy & agg might produce desired input. (i don't have test data format to try different combinations)\ndf.groupby('KEY').agg(lambda x: list(set(x))).reset_index()\n\nresult:\n KEY ... EVENT_DTL\n0 211 ... [1) 수사기록 상 주소 , 1. 변사자 정보 : laa eudong2014년06... | [
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074371969_pandas_python.txt |
Q:
Merging subsequent rows in a Dataframe in Python
I've got a Dataframe that looks like this :
cross entry cross exit Rate
Dates
2000-04-27 6.49223 6.6130
2000-06-06 6.63997 6.4920
2001-11-26 3.03064 3.1830
2001-12-04 2.99758 2.8000
... ...... | Merging subsequent rows in a Dataframe in Python | I've got a Dataframe that looks like this :
cross entry cross exit Rate
Dates
2000-04-27 6.49223 6.6130
2000-06-06 6.63997 6.4920
2001-11-26 3.03064 3.1830
2001-12-04 2.99758 2.8000
... ... ... ..
I am trying to get a DataFrame that merges su... | [
"It is possible to one-line it, but for the sake of comprehension I believe this would be my approach:\ndf = df.reset_index()\nentry_df = df.iloc[df.index[::2]].drop(columns='cross exit').rename(\n columns={'Date':'Entry Date',\n 'Rate':'Entry Rate'}).reset_index(drop=True)\nexit_df = df.iloc[df.inde... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074372603_dataframe_pandas_python_python_3.x.txt |
Q:
concatenation result add two lists
Create two lists by taking inputs from the user. First input is number of elements and second input is values in the list. Each list should only contain string as its member elements. Create a resultant list such that this list contains the concatenation result of elements of fir... | concatenation result add two lists | Create two lists by taking inputs from the user. First input is number of elements and second input is values in the list. Each list should only contain string as its member elements. Create a resultant list such that this list contains the concatenation result of elements of first list with each element of second list... | [
"print(list(map(''.join,zip(input('value: ')*int(input('number of elements: ')),input('value: ')*int(input('number of elements: '))))))\n\ncreates two lists\nconcatenates corresponding elements\nreturns one list\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074372424_python.txt |
Q:
Python: Assign missing value to rows in one column if any row is missing value in other columns
I have dataframe where column 'Score' is calculated from values in other columns. I would need to have missing value in Score column if any of other columns has missing value for that row.
df = pd.DataFrame({'Score': [7... | Python: Assign missing value to rows in one column if any row is missing value in other columns | I have dataframe where column 'Score' is calculated from values in other columns. I would need to have missing value in Score column if any of other columns has missing value for that row.
df = pd.DataFrame({'Score': [71, 63, 23],
'Factor_1': [nan, '15', '23'],
'Factor_2': ['12', n... | [
"Use DataFrame.filter for Factor column, test if missing values by DataFrame.isna for at least one value per row by DataFrame.any and set NaN by DataFrame.loc:\ndf.loc[df.filter(like='Factor').isna().any(axis=1), 'Score'] = np.nan\n\nOr use Series.mask:\ndf['Score'] = df['Score'].mask(df.filter(like='Factor').isna... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074372838_dataframe_pandas_python.txt |
Q:
Python Tkinter text insert from another module
I'm using python for my little project and for fun
I made my program one single file and it's kinda large and messy right now
so I decide try to devide several files and import it.
It's ok to work but the problem is I have no idea how to use text.insert func
gui_test.... | Python Tkinter text insert from another module | I'm using python for my little project and for fun
I made my program one single file and it's kinda large and messy right now
so I decide try to devide several files and import it.
It's ok to work but the problem is I have no idea how to use text.insert func
gui_test.py
from tkinter import *
import threading
from test ... | [
"You need to pass the Tk() object to the function if you want the function to be able to change anything in it:\ndef test_fun(widget):\n sec = 0\n while True:\n widget.txt.insert(END, f\"{sec}\\n\")\n widget.txt.update()\n sec += 1\n time.sleep(1)\n\nAnd then you need to make the T... | [
0
] | [] | [] | [
"python",
"tkinter",
"tkinter_text"
] | stackoverflow_0074351792_python_tkinter_tkinter_text.txt |
Q:
first order dynamic process using a pandas aggregate
I'd like to be able to create the following Data Frame in pandas
A
B
C
a1
b1
c1
a2
b2 = f(c1)
c2 = a2 + b2
a3
b3 = f(c2)
c3 = a3 + b3
Ahead of time I know the A column, b1 and c1 are initial conditions, and f is a known function. The ith row of column is b_... | first order dynamic process using a pandas aggregate | I'd like to be able to create the following Data Frame in pandas
A
B
C
a1
b1
c1
a2
b2 = f(c1)
c2 = a2 + b2
a3
b3 = f(c2)
c3 = a3 + b3
Ahead of time I know the A column, b1 and c1 are initial conditions, and f is a known function. The ith row of column is b_i = f(c_{i-1}) and c_i = a_i + b_i. All the a_i... | [
"import pandas as pd\nimport numpy as np\n\ndf = pd.DataFrame({'A': [1, 2, 3], 'B': [1, np.nan, np.nan], 'C': [1, np.nan, np.nan]})\n\nprint(df)\n\ndef my_func(x):\n df.loc[x.index, 'B'] = df.loc[x.index - 1, 'C'].values[0]\n df.loc[x.index, 'C'] = df.loc[x.index, 'A'].values[0] + df.loc[x.index, 'B'].values[... | [
0
] | [] | [] | [
"aggregate",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074351020_aggregate_dataframe_pandas_python.txt |
Q:
How to convert a 1 channel image into a 3 channel with opencv2?
I'm really stumped on this one. I have an image that was [BGR2GRAY]'d earlier in my code, and now I need to add colored circles and such to it. Of course this can't be done in a 1 channel matrix, and I can't seem to turn the damned thing back into 3.
... | How to convert a 1 channel image into a 3 channel with opencv2? | I'm really stumped on this one. I have an image that was [BGR2GRAY]'d earlier in my code, and now I need to add colored circles and such to it. Of course this can't be done in a 1 channel matrix, and I can't seem to turn the damned thing back into 3.
numpy.dstack() crashes everything
GRAY2BGR does not exist in opencv2
... | [
"It is the python equivalent:\n imgray is a numpy array containing 1-channel image.\nimg2 = cv2.merge((imgray,imgray,imgray))\n\n",
"Here's a way of doing that in Python:\nimg = cv2.imread(\"D:\\\\img.jpg\")\ngray = cv2.cvtColor(img, cv.CV_BGR2GRAY)\n\nimg2 = np.zeros_like(img)\nimg2[:,:,0] = gray\nimg2[:,:,1]... | [
23,
22,
4,
2,
0,
0,
0,
0
] | [] | [] | [
"arrays",
"opencv",
"python"
] | stackoverflow_0014786179_arrays_opencv_python.txt |
Q:
scrape multiple pages with python (real estate website)
I can't seem to scrape mutiple pages from a real estate website. I only seem to scrape the first page. Any help will be apreciated. The code below is what i gathered so far, i tried various solution in stackoverflow and i can't get it to work.
from bs4 import... | scrape multiple pages with python (real estate website) | I can't seem to scrape mutiple pages from a real estate website. I only seem to scrape the first page. Any help will be apreciated. The code below is what i gathered so far, i tried various solution in stackoverflow and i can't get it to work.
from bs4 import BeautifulSoup
import pandas as pd
import requests
import csv... | [
"Your problem is that your extract function takes a page which should be the number of the page. However, in for i in range(1, 10): you're passing an entire url as the parameter, instead of the page number.\nTo fix this, simply replace:\npage = 1\nfor i in range(1, 10):\n page = page+1\n webpage = f'https://w... | [
0
] | [] | [] | [
"pagination",
"python",
"scrape"
] | stackoverflow_0073929364_pagination_python_scrape.txt |
Q:
How to print a substring between two patterns if an offset is provided as an input
How can we print a substring that occurs between two patterns? We are also provided an offset of a character in the string as an input to choose which substring needs to be printed.
E.g.
string = '<p class="one">A quick brown fox</p... | How to print a substring between two patterns if an offset is provided as an input | How can we print a substring that occurs between two patterns? We are also provided an offset of a character in the string as an input to choose which substring needs to be printed.
E.g.
string = '<p class="one">A quick brown fox</p><p class="two">Jumps over</p>'
The substring that needs to be printed is between the p... | [
"The offset seems to be taken as a starting point for searching the nearest \"> to the left and </p> to the right.\n<p class=\"one\">A quick brown fox</p><p class=\"two\">Jumps over</p>\n ^ ^\n offset 20 offset 55\n\nIn oth... | [
1
] | [] | [] | [
"python",
"string"
] | stackoverflow_0074372836_python_string.txt |
Q:
Obtaining the image iterations before final image has been generated StableDiffusionPipeline.pretrained
I am currently using the diffusers StableDiffusionPipeline (from hugging face) to generate AI images with a discord bot which I use with my friends. I was wondering if it was possible to get a preview of the ima... | Obtaining the image iterations before final image has been generated StableDiffusionPipeline.pretrained | I am currently using the diffusers StableDiffusionPipeline (from hugging face) to generate AI images with a discord bot which I use with my friends. I was wondering if it was possible to get a preview of the image being generated before it is finished?
For example, if an image takes 20 seconds to generate, since it is ... | [
"You can use the callback argument of the stable diffusion pipeline to get the latent space representation of the image: link to documentation\nThe implementation shows how the latents are converted back to an image. We just have to copy that code and decode the latents.\nHere is a small example that saves the gene... | [
1
] | [] | [] | [
"huggingface",
"python",
"stable_diffusion",
"torch"
] | stackoverflow_0074369065_huggingface_python_stable_diffusion_torch.txt |
Q:
convert dataframe column values into list and make a new column from it which contains list of elements in pandas
I have these values in dataset in a pandas dataframe column
col1
0.74
0.77
0.72
0.65
0.24
0.07
0.21
0.05
0.09
I want to get a new column of six elements as list in new columns as rows (by shifting on... | convert dataframe column values into list and make a new column from it which contains list of elements in pandas | I have these values in dataset in a pandas dataframe column
col1
0.74
0.77
0.72
0.65
0.24
0.07
0.21
0.05
0.09
I want to get a new column of six elements as list in new columns as rows (by shifting one values at a time in list)
This is the col that I want to get.
col2
[0.74,0.77,0.72,0.65,0.24,0.07]
[0.77,0.72,0.65,0... | [
"Using the data you have given me i came up with this solution\nimport pandas as pd\nimport numpy as np\ndf = pd.DataFrame({'col1': [0.74,0.77,0.72,0.65,0.24,0.07,0.21,0.05,0.09]})\ndf[\"col2\"] = \"\"\nfor i in range(len(df)):\n lst = df[\"col1\"].iloc[i:i+6].to_list()\n length = len(lst)\n# Only if you need... | [
2,
1,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074372880_dataframe_pandas_python.txt |
Q:
Error installation custom django app package
I'm trying to install in a Django project my own package but when add the app to INSTALLED_APPS through the next error:
ModuleNotFoundError: No module named 'django_dashboards_app'
Code
pypi
Anybody could help me please ?
Thanks in advance.
A:
Solved by moving the f... | Error installation custom django app package | I'm trying to install in a Django project my own package but when add the app to INSTALLED_APPS through the next error:
ModuleNotFoundError: No module named 'django_dashboards_app'
Code
pypi
Anybody could help me please ?
Thanks in advance.
| [
"Solved by moving the files to a folder with the same name inside the package folder.\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074372287_django_python.txt |
Q:
python plot extend y-axis
How can I extend y-axis in the way that line in the top don't finish sharply with the end of graph. In this case would be fine to extend y-axis to 8 or even 9, note that I can't set limit to 8 because speed value will be always different. It's only about visual effect.
Second question, al... | python plot extend y-axis | How can I extend y-axis in the way that line in the top don't finish sharply with the end of graph. In this case would be fine to extend y-axis to 8 or even 9, note that I can't set limit to 8 because speed value will be always different. It's only about visual effect.
Second question, also estetic, graph start with do... | [
"Without seeing your code it is difficult to understand what you have already done and how your data is structured to create the graph, is it a pandas df? it is a list of values? Also what librarys are you using.\nAssuming you are using matplotlib this has already been answered here How to set the y-axis limit.\nGe... | [
1,
0
] | [] | [] | [
"plot",
"python"
] | stackoverflow_0074372665_plot_python.txt |
Q:
Pip not working on windows 10, freezes command promt
I recently installed Python for windows 10 and need to use pip command to install requests package.
However, whenever I try to use pip in cmd it just freezes my command prompt.
Using CTRL+C, CTRL+D or any command like that to cancel it does not work either, the ... | Pip not working on windows 10, freezes command promt | I recently installed Python for windows 10 and need to use pip command to install requests package.
However, whenever I try to use pip in cmd it just freezes my command prompt.
Using CTRL+C, CTRL+D or any command like that to cancel it does not work either, the prompt just freezes like its waiting for input or somethin... | [
"I had exactly the same problem here (Windows 10.0.10240). After typing just \"pip\" and hitting enter, nothing else happened on the console. This problem was affecting including other .exe compiled python related scripts like mezzanine-project.exe.\nThe antivirus AVAST was the culprit (in my case) !!!\nAfter disab... | [
15,
4,
1,
1,
1,
1,
0,
0
] | [
"If you have a certain network it can block pip for installation. For my case I used my own network without VPN.\n"
] | [
-1
] | [
"pip",
"python",
"windows"
] | stackoverflow_0033638395_pip_python_windows.txt |
Q:
Automatically Register Custom Models in Azure ML Studio Designer and Deploy Within Designer
I am currently trying out different architectures with Azure ML Ecosystem.
Currently, I am testing out Azure ML Studio Designer.
I want to create a complete End to End ML system, where I train several models and deploy the ... | Automatically Register Custom Models in Azure ML Studio Designer and Deploy Within Designer | I am currently trying out different architectures with Azure ML Ecosystem.
Currently, I am testing out Azure ML Studio Designer.
I want to create a complete End to End ML system, where I train several models and deploy the best.
The Pipeline Created:
In the Designer, is it possible to register a custom-trained model(i... | [
"First, we need to create the designer manually and assign the deployment manually for the first time. Input for the next iteration will be the web service input. For that we need to get the web service output to be attached with the evaluation model metrics. For the next time it will be running in repeated state.\... | [
1
] | [] | [] | [
"azure",
"azure_machine_learning_service",
"azure_ml_pipelines",
"mlops",
"python"
] | stackoverflow_0074341988_azure_azure_machine_learning_service_azure_ml_pipelines_mlops_python.txt |
Q:
Pyspark- how to check one data frame column contains string from another dataframe
For the two dataframes below, I'm trying to see if name1 in df1 contains name2 in df2. How to achieve this? I'm thinking of doing a join but there's no join key. Can I specify something like if name2 contains name1 then join them, a... | Pyspark- how to check one data frame column contains string from another dataframe | For the two dataframes below, I'm trying to see if name1 in df1 contains name2 in df2. How to achieve this? I'm thinking of doing a join but there's no join key. Can I specify something like if name2 contains name1 then join them, and result in the output below? Many thanks for your help
df1:
Name1 Colour
Lisa ('... | [
"Update\nAs @samkart mentioned, we can use direct .crossJoin(). Updated the solution with that.\n\nAs there is no common key to join, you may have to perform cross join and compare each value against the rest. This can be done by introducing a \"dummy_key\". Then just filter the rows by string contains():\ndf1 = sp... | [
1
] | [] | [] | [
"apache_spark",
"apache_spark_sql",
"dataframe",
"pyspark",
"python"
] | stackoverflow_0074372794_apache_spark_apache_spark_sql_dataframe_pyspark_python.txt |
Q:
simple dash app with table with histogram that updates with selected cell
I'm trying to create a dash app that updates a histogram depending on what cell is selected in the 'group' column.
I can get the table to display but having trouble with the histogram.
import dash
from dash import dcc
from dash import html
f... | simple dash app with table with histogram that updates with selected cell | I'm trying to create a dash app that updates a histogram depending on what cell is selected in the 'group' column.
I can get the table to display but having trouble with the histogram.
import dash
from dash import dcc
from dash import html
from dash.dependencies import Input, Output, State
import pandas as pd
import pl... | [
"When you use df_rand as a parameter to update_hist, you overwrite the df_rand defined outside the update_hist. To solve this problem, define new parameter, instead as follows:\nimport dash\nfrom dash import dcc\nfrom dash import html\nfrom dash.dependencies import Input, Output, State\nimport pandas as pd\nimport ... | [
2
] | [] | [] | [
"plotly",
"plotly_dash",
"python"
] | stackoverflow_0074369936_plotly_plotly_dash_python.txt |
Q:
How to implement stack with singly linked list in the given code format
'This code snippet has two types of insertion and deletion methods. I tried to fill the methods but i don't get the desired output. the print functions output is not as required. the output has to be 3 2 1 4 but instead i get 3 3 3 4. Please h... | How to implement stack with singly linked list in the given code format | 'This code snippet has two types of insertion and deletion methods. I tried to fill the methods but i don't get the desired output. the print functions output is not as required. the output has to be 3 2 1 4 but instead i get 3 3 3 4. Please help me to solve this'
"""Add a couple methods to our LinkedList class,
and us... | [
"Based on your output, it looks like the Stack never deletes the top value. It could either be your push algorithm, or another one inside it. Taking a look at 'delete_first()', it doesn't look like it actually removes it, just returns it. So you may be returning the first value (starting with '3'), but not actually... | [
0,
0
] | [] | [] | [
"linked_list",
"python",
"stack"
] | stackoverflow_0074371670_linked_list_python_stack.txt |
Q:
Remove the last character of each row in a text file
I have a text file that I need to read and perform an FFT onto.
Basically, the file reads something like this:
1458 1499 1232 1232 1888 ... 2022-09-11 09:32:51.076
1459 1323 1999 1323 1823 ... 2022-09-11 09:32:51.199
and so on. Each row has 200 columns, and I w... | Remove the last character of each row in a text file | I have a text file that I need to read and perform an FFT onto.
Basically, the file reads something like this:
1458 1499 1232 1232 1888 ... 2022-09-11 09:32:51.076
1459 1323 1999 1323 1823 ... 2022-09-11 09:32:51.199
and so on. Each row has 200 columns, and I want to basically read each row, up to each column while ig... | [
"You can use this:\narray = []\nwith open('file.txt','r') as tf:\n for lines in tf.readlines():\n array.append(' '.join(lines.split()[:-2]))\n\nprint(array)\n\nIf you want to append the list of integers from each of the lines:\narray = []\nwith open('file.txt','r') as tf:\n for lines in tf.readlines():\n ar... | [
5,
5,
1,
1
] | [] | [] | [
"filesystems",
"python"
] | stackoverflow_0074373193_filesystems_python.txt |
Q:
Can I use regular expressions in Django F() expressions?
I have a model:
class MyModel(models.Model):
long_name = models.CharField(unique=True, max_length=256)
important_A = models.CharField(unique=True, max_length=256)
important_B = models.CharField(unique=True, max_length=256)
MyModel.long_name cont... | Can I use regular expressions in Django F() expressions? | I have a model:
class MyModel(models.Model):
long_name = models.CharField(unique=True, max_length=256)
important_A = models.CharField(unique=True, max_length=256)
important_B = models.CharField(unique=True, max_length=256)
MyModel.long_name contains information, that I need to put in dedicated fields (imp... | [
"I'm surprised that updating 2M rows is \"too slow\", but you would definitely want to avoid creating two million objects at once, or doing 2M DB queries to update a single object. You might:\n\nEdit the model to create important_A and important_B fields with default values which cannot ever be valid in production.... | [
0
] | [] | [] | [
"django",
"postgresql",
"python",
"regex",
"sql"
] | stackoverflow_0074372798_django_postgresql_python_regex_sql.txt |
Q:
How to get plain text out of Wikipedia
I'd like to write a script that gets the Wikipedia description section only. That is, when I say
/wiki bla bla bla
it will go to the Wikipedia page for bla bla bla, get the following, and return it to the chatroom:
"Bla Bla Bla" is the name of a song
made by Gigi D'Agost... | How to get plain text out of Wikipedia | I'd like to write a script that gets the Wikipedia description section only. That is, when I say
/wiki bla bla bla
it will go to the Wikipedia page for bla bla bla, get the following, and return it to the chatroom:
"Bla Bla Bla" is the name of a song
made by Gigi D'Agostino. He described
this song as "a piece I ... | [
"Here are a few different possible approaches; use whichever works for you. All my code examples below use requests for HTTP requests to the API; you can install requests with pip install requests if you have Pip. They also all use the Mediawiki API, and two use the query endpoint; follow those links if you want do... | [
42,
24,
12,
7,
4,
2,
1,
1,
0,
0,
0,
0
] | [
"You can try the BeautifulSoup HTML parsing library for python,but you'll have to write a simple parser.\n",
"There is also the opportunity to consume Wikipedia pages through a wrapper API like JSONpedia, it works both live (ask for the current JSON representation of a Wiki page) and storage based (query multiple... | [
-1,
-1
] | [
"mediawiki",
"mediawiki_api",
"python",
"wikipedia",
"wikipedia_api"
] | stackoverflow_0004452102_mediawiki_mediawiki_api_python_wikipedia_wikipedia_api.txt |
Q:
How do add a carnival fair age sense in python only allowing 10 and above
age = input("How old are you? (10 and above) >>> ")
if age.lower() == 9 ≤ 100:
print("enter")
else:
print("sorry little man")
A:
age = input("How old are you? (10 and above) >>> ")
if 9 < int(age) <= 100:
print("enter")
els... | How do add a carnival fair age sense in python only allowing 10 and above | age = input("How old are you? (10 and above) >>> ")
if age.lower() == 9 ≤ 100:
print("enter")
else:
print("sorry little man")
| [
"age = input(\"How old are you? (10 and above) >>> \")\n\nif 9 < int(age) <= 100: \n print(\"enter\")\nelse: \n print(\"sorry little man\")\n\nOutput:\nHow old are you? (10 and above) > 10\nenter\n\n"
] | [
0
] | [] | [] | [
"input",
"python"
] | stackoverflow_0074373441_input_python.txt |
Q:
Python subprocess execution slower than main process
I have a Python method as shown below:
import gym
def run():
env = gym.make('Pendulum-v1')
env.reset()
action = [1.0]
for _ in range(1000):
env.step(action)
I use viztracer to profile this method in the main process and subprocess (by m... | Python subprocess execution slower than main process | I have a Python method as shown below:
import gym
def run():
env = gym.make('Pendulum-v1')
env.reset()
action = [1.0]
for _ in range(1000):
env.step(action)
I use viztracer to profile this method in the main process and subprocess (by multiprocessing.Process), respectively. It shows that the m... | [
"What is the cause of issue?\nyour CPU is triggering thermal throttling in the multiprocessing version, there's also memory and cache contention that will happen.\nHow to fix it?\nyou can't, even if you submerged the computer in liquid nitrogen.\nvendors are overspecing and pushing the numbers in single core perfor... | [
1
] | [] | [] | [
"multiprocessing",
"python"
] | stackoverflow_0074369071_multiprocessing_python.txt |
Q:
Python script in notepad++ for replace with a increment number
I try to do a python script in notepad++ to replace a simbol with the same symbol + increment number, like a list
# -*- coding: utf-8 -*-
import os
search_string = '▶️ '
final_str = '.-'
i = 0
for root, dirs, files in os.walk('C:\\temp\\prueba'): # ta... | Python script in notepad++ for replace with a increment number | I try to do a python script in notepad++ to replace a simbol with the same symbol + increment number, like a list
# -*- coding: utf-8 -*-
import os
search_string = '▶️ '
final_str = '.-'
i = 0
for root, dirs, files in os.walk('C:\\temp\\prueba'): # take care of double backslash like c:\\temp\\dir1\\
for file in fi... | [
"I have tried to modify your code as follow:\n# -*- coding: utf-8 -*-\nimport os\nsearch_string = '▶️ '\nfinal_str = '.-'\ni = 0\nfor root, dirs, files in os.walk('C:\\\\temp\\\\prueba'):\n for file in files:\n fname, ext = os.path.splitext(file)\n if ext == '.txt':\n i = 0\n ... | [
0
] | [] | [] | [
"python",
"replace"
] | stackoverflow_0074372842_python_replace.txt |
Q:
Convert string to dictionary with list of values
What is the best way to convert a string to dictionary with value of dictionary as a list
for example
str = "abc=1,abc=2,abc=3,xyz=5,xyz=6"
i need the output as:
d = {"abc":["1","2","3"],"xyz":["5","6"]}
I'm very new to python.
my code:
d = {k: [v] for k, v in map(l... | Convert string to dictionary with list of values | What is the best way to convert a string to dictionary with value of dictionary as a list
for example
str = "abc=1,abc=2,abc=3,xyz=5,xyz=6"
i need the output as:
d = {"abc":["1","2","3"],"xyz":["5","6"]}
I'm very new to python.
my code:
d = {k: [v] for k, v in map(lambda item: item.split('='), s.split(","))}
| [
"Here is the solution with dict.setdefault method.\n>>> help({}.setdefault)\nHelp on built-in function setdefault:\n\nsetdefault(key, default=None, /) method of builtins.dict instance\n Insert key with a value of default if key is not in the dictionary.\n\n Return the value for key if key is in the dictionary... | [
3,
0,
0
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0074373166_dictionary_list_python.txt |
Q:
Locust - How to pass new configuration through code to locust
I am trying to run locust as a library from python code and along with that I wanted to use locust-plugins library. The main problem I am facing is that I am not able to find how to pass additional command line arguments from code to locust ? locust-plu... | Locust - How to pass new configuration through code to locust | I am trying to run locust as a library from python code and along with that I wanted to use locust-plugins library. The main problem I am facing is that I am not able to find how to pass additional command line arguments from code to locust ? locust-plugins library is providing command line arguments like timescale and... | [
"I'm not sure anyone has done this before so it is kind of expected that you run in to some issues :)\nWhat I would try is parsing a \"fake\" command line, and passing it to the Environment constructor.\nYou'll need locust-plugins 2.6.12 or later (I renamed the add_arguments method just now)\nparser = locust.argume... | [
1
] | [] | [] | [
"load_testing",
"locust",
"python"
] | stackoverflow_0074370695_load_testing_locust_python.txt |
Q:
Does python logging incur a performance hit if you log below the set level?
I'm looking at optimising some code.
For example if I have set Python's log level to info and I write code e.g.
logger.debug(....)
Does Python know that I am set to info level and effectively throw the debug statement away?
Is there a way... | Does python logging incur a performance hit if you log below the set level? | I'm looking at optimising some code.
For example if I have set Python's log level to info and I write code e.g.
logger.debug(....)
Does Python know that I am set to info level and effectively throw the debug statement away?
Is there a way to determine which log level is set and I could test this before doing more cost... | [
"You can save yourself the hassle of formatting the string for logging as the logging module offers you some string formatting on its own.\nYou should also save yourself the hassle of checking the level manually. That is just what the library is for.\nThe docs have this nice graph to explain when and how expensive ... | [
2,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0058592292_python.txt |
Q:
How to LISTEN/GET for updated data to send to subscribed websocket clients using FastAPI
I can't find the exact guide of what I want to do, it's more of a structural and architectural issue:
Tooling:
Python 3.9
FastAPI
Uvicorn
Some scripts to monitor the folders
It'll run under docker when its done
The exact tas... | How to LISTEN/GET for updated data to send to subscribed websocket clients using FastAPI | I can't find the exact guide of what I want to do, it's more of a structural and architectural issue:
Tooling:
Python 3.9
FastAPI
Uvicorn
Some scripts to monitor the folders
It'll run under docker when its done
The exact task:
I want to build a web-app that lists the photos in a directory and shows them in a grid in ... | [
"Ok, unless anyone has any amazing ideas, the best solution is:\nConnect to REDIS, pull existing values at the time the client web socket connects.\nThe worker process(es) can push new values via REDIS.\nSince the connected client handler can use asyncio, they can subscribe to the pub/sun model.\nProblem solved, ye... | [
0
] | [] | [] | [
"fastapi",
"python",
"websocket"
] | stackoverflow_0074369127_fastapi_python_websocket.txt |
Q:
why does my dictionary get me "None" as value?
dic = {'A':'D','N':'Q','B':'E','O':'R','C':'F','P':'S','D':'G','Q':'T','E':'H','R':'U','F':'I','S':'V','G':'J','T':'W',
'H':'K','U':'X','I':'L','V':'Y','J':'M','W':'Z','K':'N','X':'A','L':'O','Y':'B','M':'P','Z':'C'}
user_input = input("Enter the word: ").up... | why does my dictionary get me "None" as value? | dic = {'A':'D','N':'Q','B':'E','O':'R','C':'F','P':'S','D':'G','Q':'T','E':'H','R':'U','F':'I','S':'V','G':'J','T':'W',
'H':'K','U':'X','I':'L','V':'Y','J':'M','W':'Z','K':'N','X':'A','L':'O','Y':'B','M':'P','Z':'C'}
user_input = input("Enter the word: ").upper()
Key=str(user_input)
print (dic.get(Key))
This... | [
"It looks like you are misunderstanding how a dictionary is working.\nIf I guess correctly, you would like to get DEFG when you enter ABCD.\nWhat you currently do works only for single letters (if you run dic.get('A') you will have 'D', but dic.get('ABC') will output None as 'ABC' is not a key).\nI believe what you... | [
3,
1
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074373377_dictionary_python.txt |
Q:
JSON data format write to InfluxDB error results in 204 response
I am requesting some data from the weather API and I am trying to save it to a influxdb database.
When I am trying to write the json data to the influx database I get a 204 response and no data are written to the database. The exact error from the d... | JSON data format write to InfluxDB error results in 204 response | I am requesting some data from the weather API and I am trying to save it to a influxdb database.
When I am trying to write the json data to the influx database I get a 204 response and no data are written to the database. The exact error from the docker logs is:
[httpd] 172.17.0.1 - root [17/Jun/2020:23:00:35 +0000] ... | [
"According to the documentation of the InfluxDBClient, the 204 response code is actually expected when writing data into the influx DB, see https://influxdb-python.readthedocs.io/en/latest/api-documentation.html#influxdb.InfluxDBClient.write \nPlease double check if there really is an issue with writing data into i... | [
0,
0
] | [] | [] | [
"influxdb",
"python"
] | stackoverflow_0062439771_influxdb_python.txt |
Q:
create environment from .yml file using pip
I have a file which has the environmental requirements in yml format. I want to read the file so as I can install the required dependencies using pip as we using txt file.
pip install -r requirement.txt
this what the yml file looks like after parsing uing pyaml.
{'name... | create environment from .yml file using pip | I have a file which has the environmental requirements in yml format. I want to read the file so as I can install the required dependencies using pip as we using txt file.
pip install -r requirement.txt
this what the yml file looks like after parsing uing pyaml.
{'name': 'tables-detr',
'channels': ['conda-forge', 'py... | [
"The yaml file is because you should install it with conda not with pip. If you want to install with pip you must filtere out name and channel from the yaml file and create a requirements txt with only dependencies and pip\n"
] | [
0
] | [] | [] | [
"anaconda",
"pip",
"python",
"virtualenv"
] | stackoverflow_0074373584_anaconda_pip_python_virtualenv.txt |
Q:
Double X Axis in Plotly plot for one line
I'm trying to create a plot in python using Plotly that allows me to add 2 x axis to a single plot. I just tried but every single tutorial and documentation add a second trace to the plot with y and x data, but if you do that it will generate a second line and I just want ... | Double X Axis in Plotly plot for one line | I'm trying to create a plot in python using Plotly that allows me to add 2 x axis to a single plot. I just tried but every single tutorial and documentation add a second trace to the plot with y and x data, but if you do that it will generate a second line and I just want a line that represents both axis. I mean de mai... | [
"As my experience, you can use x=[tuple(main_x),tuple(sub_x)] to set main xaxis and sub xaxis. Please refer below code:\nfig_1 = go.Figure(data=[\n go.Bar(x=[tuple(df['Season']), \n tuple(df['category_name'])],\n y=list(df['sale_dollars'])),\n ])\n\nAnd here is the result:\n... | [
1
] | [] | [] | [
"plotly",
"plotly_dash",
"plotly_python",
"python"
] | stackoverflow_0074372689_plotly_plotly_dash_plotly_python_python.txt |
Q:
How to add a request header at selenium-wire as passed argument?
What I need is to set header values defined outside def interceptor(request) function. How can I pass it?
def randomkeklul(main_arg):
return random.choice(['kek', 'lul']), random.choice(main_arg)
def interceptor(request):
request.headers['Ac... | How to add a request header at selenium-wire as passed argument? | What I need is to set header values defined outside def interceptor(request) function. How can I pass it?
def randomkeklul(main_arg):
return random.choice(['kek', 'lul']), random.choice(main_arg)
def interceptor(request):
request.headers['Accept-Encoding'] = value1
request.headers['Accept-Language'] = valu... | [
"I have the same issue. The only think that works fine for me is to get the parameters from some other function/file:\ndef interceptor(request):\n from custom_credentials import custom_credentials\n username, password = custom_credentials()\n \n auth_b = username + ':' + password\n \n auth = (\n ... | [
0
] | [] | [] | [
"python",
"python_3.x",
"seleniumwire"
] | stackoverflow_0072312662_python_python_3.x_seleniumwire.txt |
Q:
Python: animate FancyArrows with matplotlib.animation.FuncAnimation
I'm trying to get a Python script to visualize N arrows (which represent N phases in an electric machine).
I've got a kind of solution, but after running the code and the animation, Python crashes.
This is not a critical error, but could be in the... | Python: animate FancyArrows with matplotlib.animation.FuncAnimation | I'm trying to get a Python script to visualize N arrows (which represent N phases in an electric machine).
I've got a kind of solution, but after running the code and the animation, Python crashes.
This is not a critical error, but could be in the future. By the way, any suggestion about the code would be appreciated.
... | [
"After some scratching, I've get the correct answer.\nThe problem is appearing here:\ndef animate(t):\nax.patches.clear()\narrows=[( plt.arrow(0, 0,\n dx=(Iamp*np.cos(2*np.pi*f*t+phi)), dy=(Iamp*np.sin(2*np.pi*f*t+phi)), #what if I call buid_Fasor() here?\n head_widt... | [
0
] | [] | [] | [
"animation",
"matplotlib",
"patch",
"python"
] | stackoverflow_0074239686_animation_matplotlib_patch_python.txt |
Q:
Getting a dictionary from web-scrapping data sets
table = soup.find('table')
list_of_states = table.find_all('tr')
for state in list_of_states:
state_name = state.find('td')
if state_name is None:
continue
hours = state.find_all('td')[1].text
comparison_state = str(state_name.text.strip(... | Getting a dictionary from web-scrapping data sets | table = soup.find('table')
list_of_states = table.find_all('tr')
for state in list_of_states:
state_name = state.find('td')
if state_name is None:
continue
hours = state.find_all('td')[1].text
comparison_state = str(state_name.text.strip().lower())
sunlight = float(hours.split()[0])
dict... | [
"\ncomparison_state is the string of state names, but if you print that it prints all of them, not just one; same thing with the sunlight\n\nIs there one single cell with all the state names and another single cell with all the sunlight hours? Because otherwise that shouldn't be happening with the current code....(... | [
0
] | [] | [] | [
"beautifulsoup",
"code_formatting",
"python",
"web_scraping"
] | stackoverflow_0074354618_beautifulsoup_code_formatting_python_web_scraping.txt |
Q:
How to provide type annotations in case of circular dependency in different files in Python?
Please consider the following working code
from __future__ import annotations
class A(object):
def __init__(self, val: int):
self.val = val
@property
def b(self) -> B:
return B(self)
class B(... | How to provide type annotations in case of circular dependency in different files in Python? | Please consider the following working code
from __future__ import annotations
class A(object):
def __init__(self, val: int):
self.val = val
@property
def b(self) -> B:
return B(self)
class B(object):
def __init__(self, a: A):
self.a = a
a = A(val=1)
print(a.b.a.val)
Whic... | [
"Switching to module-only imports and forward-references should work as the documentation says.\nFirst have a directory structure similar to the following.\nfoo/\n __init__.py\n a.py\n b.py\n\na.py and b.py import each others module but not the class and __init__.py imports from a and b\n__init__.py\nfrom foo.a ... | [
0
] | [] | [] | [
"circular_dependency",
"forward_declaration",
"python",
"type_hinting"
] | stackoverflow_0074373368_circular_dependency_forward_declaration_python_type_hinting.txt |
Q:
Controlling the threshold in Logistic Regression in Scikit Learn
I am using the LogisticRegression() method in scikit-learn on a highly unbalanced data set. I have even turned the class_weight feature to auto.
I know that in Logistic Regression it should be possible to know what is the threshold value for a parti... | Controlling the threshold in Logistic Regression in Scikit Learn | I am using the LogisticRegression() method in scikit-learn on a highly unbalanced data set. I have even turned the class_weight feature to auto.
I know that in Logistic Regression it should be possible to know what is the threshold value for a particular pair of classes.
Is it possible to know what the threshold valu... | [
"There is a little trick that I use, instead of using model.predict(test_data) use model.predict_proba(test_data). Then use a range of values for thresholds to analyze the effects on the prediction;\npred_proba_df = pd.DataFrame(model.predict_proba(x_test))\nthreshold_list = [0.05,0.1,0.15,0.2,0.25,0.3,0.35,0.4,0.4... | [
35,
22,
21,
1
] | [] | [] | [
"classification",
"logistic_regression",
"machine_learning",
"python",
"scikit_learn"
] | stackoverflow_0028716241_classification_logistic_regression_machine_learning_python_scikit_learn.txt |
Q:
How to resolve python libraries dependencies when using pip
I have come across some nasty dependencies.
Looking around I found solutions like upgrade this, downgrade that...
Some solutions work for some but not for others.
Is there a more 'rounded' way to tackle this issue?
A:
First you need to understand that p... | How to resolve python libraries dependencies when using pip | I have come across some nasty dependencies.
Looking around I found solutions like upgrade this, downgrade that...
Some solutions work for some but not for others.
Is there a more 'rounded' way to tackle this issue?
| [
"First you need to understand that pip can resolve problems one at a time and when you put it in a corner, it can't go further.\nBut, if you give to pip the 'big problem' it has a nice way to try to resolve it. It may not always work, but for most cases it will.\nThe solutions you normally find out there are in som... | [
0,
0
] | [] | [] | [
"conflicting_libraries",
"pip",
"python"
] | stackoverflow_0074373058_conflicting_libraries_pip_python.txt |
Q:
Is there a way to directly upload a 'generated barcode' .png file onto azure blob storage?
I'm having issues with directly upload a generated barcode .png file of type 'code128' onto my azure-blob-storage account, without storing to any local storage on my azure function app.
I have had success directly uploading ... | Is there a way to directly upload a 'generated barcode' .png file onto azure blob storage? | I'm having issues with directly upload a generated barcode .png file of type 'code128' onto my azure-blob-storage account, without storing to any local storage on my azure function app.
I have had success directly uploading files like .txt, .csv, and .json where the contents of the file are just strings, however, when ... | [
"I tried in my environment and got below results:\nInitially, I tried with same code I got an similar error.\nConsole:\n\nI tried with below code and barcode uploaded successfully.\nCode:\nimport barcode\nfrom barcode.writer import ImageWriter\nfrom azure.storage.blob import BlobServiceClient\n\nbarcodeConte... | [
0
] | [] | [] | [
"azure_blob_storage",
"azure_functions",
"python"
] | stackoverflow_0074294565_azure_blob_storage_azure_functions_python.txt |
Q:
Can I use bag of words to find cosine similarity between vectors?
I have a Bag of Words dataset like this:
Item A B C D
abc 1 0 0 1
pqr 0 0 1 1
xyz 0 1 0 0
and so on.
Is there a way I can find the pairwise cosine similarity in this dataset?
What I see on scikit is - converting it to a tfidftransformer version... | Can I use bag of words to find cosine similarity between vectors? | I have a Bag of Words dataset like this:
Item A B C D
abc 1 0 0 1
pqr 0 0 1 1
xyz 0 1 0 0
and so on.
Is there a way I can find the pairwise cosine similarity in this dataset?
What I see on scikit is - converting it to a tfidftransformer version, and then finding cosine similarity.
The final aim is to compare the c... | [
"Some additional details can be added to the question to better present the question. For the given dataset, say the A, B, C, and D are the features, and you have 3 items 'abc', 'pqr', and 'xyz'. If you want to obtain a 3*3 matrix (len_items = 3) of pairwise similarity for each possible combination of items, then o... | [
0
] | [] | [] | [
"nlp",
"python",
"tf_idf"
] | stackoverflow_0067916065_nlp_python_tf_idf.txt |
Q:
TypeError: not all arguments converted during string formatting.(Armstrong number)
n=input("enter the number: ")
num=n
digit,sum=0,0
length=len(str(n))
for i in range(length):
digit=int(num%10)
num=num/10
sum+=pow(digit,length)
if sum==n:
print("armstrong")
else:
print("Not armstrong")
... | TypeError: not all arguments converted during string formatting.(Armstrong number) | n=input("enter the number: ")
num=n
digit,sum=0,0
length=len(str(n))
for i in range(length):
digit=int(num%10)
num=num/10
sum+=pow(digit,length)
if sum==n:
print("armstrong")
else:
print("Not armstrong")
when I run this code, it show error in line 6:
Traceback (most recent call last):
... | [
"You need to first convert the string into an integer before performing any mathematical operation.\nHere is the revised code.\nn=input(\"enter the number: \")\nnum=n\ndigit,sum=0,0\nlength=len(str(n))\nfor i in range(length):\n digit=int(num)%10\n num=int(num)/10\n sum+=pow(digit,length)\nif sum==n:\n ... | [
1
] | [] | [] | [
"python",
"typeerror"
] | stackoverflow_0074373706_python_typeerror.txt |
Q:
How to handle byte strings in Numba?
What is the proper way to handle byte strings (b'abc') with Numba? According to its documentation it handles Unicode strings similar to Python, with underlying memory representation compatible with Python (1,2,4 bytes with an apropriate tag withing the string object).
Numba has... | How to handle byte strings in Numba? | What is the proper way to handle byte strings (b'abc') with Numba? According to its documentation it handles Unicode strings similar to Python, with underlying memory representation compatible with Python (1,2,4 bytes with an apropriate tag withing the string object).
Numba has one string type: nb.types.unicode_type de... | [
"So far I managed to solve this issue with custom conversion code. It works with Python byte strings as well as Numpy byte string types (Sx):\n@nb.jit(nopython=True)\ndef btostr(x):\n return ''.join([chr(x[i]) for i in range(len(x))])\n\n# ...\nd[btostr(b'abc')] = 1\n\nI am not sure is this the most efficient wa... | [
0
] | [] | [] | [
"numba",
"python",
"python_3.x"
] | stackoverflow_0074373439_numba_python_python_3.x.txt |
Q:
How to remove zero values from arrays in dictionary
Suppose I have a dictionary containing 2d arrays:
dict = {
"a": np.array([[0, 2, 3], [4, 0, 6]]),
"b": np.array([[1, 0, 3], [4, 5, 0]]),
"c": np.array([[1, 2, 0], [0, 5, 6]])}
And I want to remove zero values from each array in that dictionary.
The o... | How to remove zero values from arrays in dictionary | Suppose I have a dictionary containing 2d arrays:
dict = {
"a": np.array([[0, 2, 3], [4, 0, 6]]),
"b": np.array([[1, 0, 3], [4, 5, 0]]),
"c": np.array([[1, 2, 0], [0, 5, 6]])}
And I want to remove zero values from each array in that dictionary.
The output I want to get should look like this:
dict = {
"... | [
"{k: v for k, v in d.items() if v}\n\nremoving False, [], None also\n"
] | [
1
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074373806_numpy_python.txt |
Q:
How to change a value inside a list which is a value for a key in a dictionary?
I try to change one value inside the list but all values change for all keys.
vertex_list = ['a','b']
distance_dict = dict.fromkeys(vertex_list, [10, 'None'])
distance_dict['a'][0] = 1
print(distance_dict)
output:
{'a': [1, 'None'], '... | How to change a value inside a list which is a value for a key in a dictionary? | I try to change one value inside the list but all values change for all keys.
vertex_list = ['a','b']
distance_dict = dict.fromkeys(vertex_list, [10, 'None'])
distance_dict['a'][0] = 1
print(distance_dict)
output:
{'a': [1, 'None'], 'b': [1, 'None']}
when I built the dictionary with traditional { } it works fine. I g... | [
"Quoting from the official documentation,\n\nfromkeys() is a class method that returns a new dictionary. value\ndefaults to None. All of the values refer to just a single instance,\nso it generally doesn’t make sense for value to be a mutable object\nsuch as an empty list. To get distinct values, use a dict\ncompre... | [
2,
1,
0
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0074373181_dictionary_list_python.txt |
Q:
while gets stuck in def function
My task is the following:
Given three integers. Determine how many of them are equal to each other. The program must print one of the numbers: 3 (if all are same), 2 (if two of them are equal to each other and the third one is different) or 0 (if all numbers are different).
I fig... | while gets stuck in def function | My task is the following:
Given three integers. Determine how many of them are equal to each other. The program must print one of the numbers: 3 (if all are same), 2 (if two of them are equal to each other and the third one is different) or 0 (if all numbers are different).
I figured I could do a def function to chec... | [
"If checker is not a valid int you'll reach the except block and call for another input, but you missed assigning that value back to checker:\ndef valuecheck(checker):\n loopx = True\n while loopx:\n try:\n #first it checks if the input is actually an integer\n checker = int(checker)\n loopx = F... | [
5,
0
] | [
"def valuecheck(value):\n if isinstance(value, int):\n return value\n else:\n while(True):\n value = input(\"Value isn't a valid input, try again: \")\n try:\n value = int(value)\n return val\n except:\n pass\n\n"
] | [
-1
] | [
"python",
"while_loop"
] | stackoverflow_0074373713_python_while_loop.txt |
Q:
TypeError: Cart() takes no arguments
This is views.py file from the cart section where I want to add product, remove product and show product details in the cart. Error is : Cart() takes no arguments.
from django.shortcuts import render, redirect, get_object_or_404
from django.views.decorators.http import require_... | TypeError: Cart() takes no arguments | This is views.py file from the cart section where I want to add product, remove product and show product details in the cart. Error is : Cart() takes no arguments.
from django.shortcuts import render, redirect, get_object_or_404
from django.views.decorators.http import require_POST
from ecommerce.models import Product
... | [
"I could see one mistake it should be __init__() method not __int__ method.\nThat's why Cart(request) gave that error as __init__() was not actually called.\n"
] | [
2
] | [] | [] | [
"django",
"django_forms",
"django_models",
"django_templates",
"python"
] | stackoverflow_0074372527_django_django_forms_django_models_django_templates_python.txt |
Q:
PermissionError: [Errno 13] Permission denied on macOS
I try to run the code below, but it's doesn't work
`
import cv2
from PIL import Image
import pytesseract
pytesseract.pytesseract.tesseract_cmd = r'/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/tesseract'
img = cv2.imread(r'/U... | PermissionError: [Errno 13] Permission denied on macOS | I try to run the code below, but it's doesn't work
`
import cv2
from PIL import Image
import pytesseract
pytesseract.pytesseract.tesseract_cmd = r'/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/tesseract'
img = cv2.imread(r'/Users/lhldanh/CompSci/Python/Coursera/TextDetection/sample.pn... | [
"pytesseract.pytesseract.tesseract_cmd should point to an executable if I remember correct, so maybe add /tesseract.exe to the path.\n"
] | [
0
] | [] | [] | [
"macos",
"permissionerror",
"python",
"tesseract"
] | stackoverflow_0074373370_macos_permissionerror_python_tesseract.txt |
Q:
how to read date and time on ecmwf file
I have global datasets in netcdf file. Time information on data file is:
<type 'netCDF4._netCDF4.Variable'>
int32 time(time)
units: hours since 1900-01-01 00:00:0.0
long_name: time
calendar: gregorian
unlimited dimensions: time
current shape = (5875,)
filling of... | how to read date and time on ecmwf file | I have global datasets in netcdf file. Time information on data file is:
<type 'netCDF4._netCDF4.Variable'>
int32 time(time)
units: hours since 1900-01-01 00:00:0.0
long_name: time
calendar: gregorian
unlimited dimensions: time
current shape = (5875,)
filling off
when I extracted time from file, I got thi... | [
"You could: \nfrom datetime import date, timedelta\n\nhours = [ 876600, 876624, 876648, 1017528, 1017552, 1017576]\nbase = date(1900, 1, 1)\nfor hour in hours:\n base + timedelta(hours=hour)\n\n2000-01-02\n2000-01-03\n2000-01-04\n2016-01-30\n2016-01-31\n2016-02-01\n\nUse datetime instead of date if you want... | [
4,
3,
1,
0
] | [] | [] | [
"data_analysis",
"datetime",
"pandas",
"python",
"time_series"
] | stackoverflow_0037854256_data_analysis_datetime_pandas_python_time_series.txt |
Q:
The dash is a invalid syntax in the import settings
I have a problem with launching the code, the problem was
"File C:\Users\User\Something\main.py
import color-utility
^
SyntaxError: invalid syntax'
Is there any fix for this?
A:
Well, you should use import color_utility instead of -.
| The dash is a invalid syntax in the import settings | I have a problem with launching the code, the problem was
"File C:\Users\User\Something\main.py
import color-utility
^
SyntaxError: invalid syntax'
Is there any fix for this?
| [
"Well, you should use import color_utility instead of -.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074373902_python.txt |
Q:
I'm trying to make function that grabs integers and combines them per continent and then prints it per year. I am struggling to make that work
I have a list of dictionaries shaped like this:
[{'country': 'Afghanistan', 'continent': 'Asia', '1990': 500, '1990_lower': 200, '1990_upper': 1000, '1991': 500, '1991_lowe... | I'm trying to make function that grabs integers and combines them per continent and then prints it per year. I am struggling to make that work | I have a list of dictionaries shaped like this:
[{'country': 'Afghanistan', 'continent': 'Asia', '1990': 500, '1990_lower': 200, '1990_upper': 1000, '1991': 500, '1991_lower': 200, '1991_upper': 1000, '1992': 500, '1992_lower': 200, '1992_upper': 1000, '1993': 1000, '1993_lower': 500, '1993_upper': 1100, '1994': 1000, ... | [
"The error you get arises because your keys (years) are strings in dataset, but you try to access dictionary through an int (years_cases[x] += dictionary[x]).\nHowever there is another problem in your script: you are assigning the same years_cases dictionary to each of your continents, which will not give the resul... | [
1,
0
] | [] | [] | [
"dataset",
"dictionary",
"list",
"nested",
"python"
] | stackoverflow_0074373523_dataset_dictionary_list_nested_python.txt |
Q:
How to make a phonebook directory in python uisng linkedlist
so im trying to make a phonebook directory in python using linked list but i dont know how to add the name and the number
As well as other functions
P.S my knowledge in python is not that solid and only a second year college
I need a help with this one
`... | How to make a phonebook directory in python uisng linkedlist | so im trying to make a phonebook directory in python using linked list but i dont know how to add the name and the number
As well as other functions
P.S my knowledge in python is not that solid and only a second year college
I need a help with this one
`
class Node:
def __init__(self, name=" ",number=None):
... | [
"Insert, view, update, and delete have already been implemented, just search for them on Google. You just need to implement the operations inside of a function. I have a sample code here for inserting a value, just for your information.\nname = input(\"Enter name:\")\nlist = []\ncontact = input(\"Enter new Contact:... | [
0
] | [] | [] | [
"class",
"directory",
"linked_list",
"list",
"python"
] | stackoverflow_0074305058_class_directory_linked_list_list_python.txt |
Q:
Provide object methods into the namespace of a python environment
I am trying to provide wrappers for short-cutting every-day commands. Python environments are very useful to do that.
Is it possible to provide all methods of an object to the local namespace within a new environment?
class my_object:
def method... | Provide object methods into the namespace of a python environment | I am trying to provide wrappers for short-cutting every-day commands. Python environments are very useful to do that.
Is it possible to provide all methods of an object to the local namespace within a new environment?
class my_object:
def method_a():
...
class my_environment:
...
def __enter__(self... | [
"It will be rather complex, and IMHO will not be worth it. The problem is that in Python, local variables are local to a function and not to a bloc. So what you are asking for would require that:\n\n__enter__ declares nonlocal variables for all of the methods from some_object and saves their previous value if any\n... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074373674_python.txt |
Q:
How to decode an UTF-8 encoded API response
When I send a request to an API:
import requests
url = 'website'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36'
}
response = requests.get(url.strip(), headers=headers, time... | How to decode an UTF-8 encoded API response | When I send a request to an API:
import requests
url = 'website'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36'
}
response = requests.get(url.strip(), headers=headers, timeout=10)
response.encoding = response.apparent_enc... | [
"In order to encode or decode from utf8 string you can use :\ns = \"test\"\nu = s.encode(\"utf8\")\ns = u.decode(\"utf8\")\n\nBut your problem is that your string is utf-8 encoded and escaped!\nSo you will need to un-escape it and then re-interpret it:\ns = response.text\nr = s.encode('raw_unicode_escape').decode('... | [
0
] | [] | [] | [
"encoding",
"python",
"utf_8"
] | stackoverflow_0074373845_encoding_python_utf_8.txt |
Q:
Count how often a Text is given in an txt File Python
how is it possible for me to count the word "OFFLINE" in the Following List with Python? The List is in a .txt File so i need to open that first i guess and then look after the specific word.
MPP MPP Fault MPP Fault MPP MPP MPP MPP MPP MPP MPP MPP MPP MPP MPP M... | Count how often a Text is given in an txt File Python | how is it possible for me to count the word "OFFLINE" in the Following List with Python? The List is in a .txt File so i need to open that first i guess and then look after the specific word.
MPP MPP Fault MPP Fault MPP MPP MPP MPP MPP MPP MPP MPP MPP MPP MPP MPP MPP MPP MPP MPP MPP MPP MPP MPP OFFLINE OFFLINE OFFLINE ... | [
"def word_count(str):\n return str.split().count(\"OFFLINE\")\n\nIf the goal is to count the number of OFFLINE occurences, you don't need a dict.\ndef word_count(str):\n counts = 0\n words = str.split()\n for word in words:\n if word == \"OFFLINE\":\n counts += 1\n return counts\n\n... | [
0,
0,
0,
0
] | [] | [] | [
"count",
"python"
] | stackoverflow_0074373103_count_python.txt |
Q:
Python how to decode code from GPS to NMEA?
I am trying to program a GPS (I have a GPS "here2" + CubeOrange + Raspberry PI 4 Model B).
From the circuit I get this result:
`b'3DA\x95F\xaa?p%b=,XIB\n'
3344470000000000000000cf19c93f0a
b'3DT\x00\x00\x00\x00\x00\n'
334441f959aa3f31895f3df15749420a
b'3DG\x00\x00\x00\x00... | Python how to decode code from GPS to NMEA? | I am trying to program a GPS (I have a GPS "here2" + CubeOrange + Raspberry PI 4 Model B).
From the circuit I get this result:
`b'3DA\x95F\xaa?p%b=,XIB\n'
3344470000000000000000cf19c93f0a
b'3DT\x00\x00\x00\x00\x00\n'
334441f959aa3f31895f3df15749420a
b'3DG\x00\x00\x00\x00\x00\x00\x00\x00\xcf\x19\xc9?\n'
3344540000000000... | [
"I guess the data is packed info byte-array to unpack data use the Python struct library\n>>> import struct\n>>> data = b'3DA\\x95F\\xaa?p%b=,XIB\\n'\n>>> struct.unpack(\"ffff\",data)\n(-3.902983930259824e-26, 2.372699393234608e+29, 2.6912996570899184e-12, 9.354554656484993e-33)\n>>>\n\n"
] | [
0
] | [] | [] | [
"gps",
"hex",
"python"
] | stackoverflow_0074373765_gps_hex_python.txt |
Q:
percentage difference of datetime object
I want to create a new column which contains the values of column diff(s) but in percentage.
Finish Time diff (s)
0 1900-01-01 00:42:43.500 0 days 00:00:00
1 1900-01-01 00:44:01.200 0 days 00:01:17
2 1900-01-01 00:44:06.500 0 days 00:01... | percentage difference of datetime object | I want to create a new column which contains the values of column diff(s) but in percentage.
Finish Time diff (s)
0 1900-01-01 00:42:43.500 0 days 00:00:00
1 1900-01-01 00:44:01.200 0 days 00:01:17
2 1900-01-01 00:44:06.500 0 days 00:01:23
3 1900-01-01 00:44:29.500 0 days 00:0... | [
"It depends how are defined percentages - if need divide by summed timedeltas:\ndf[\"diff(s)\"] = df[\"Finish Time\"] - df[\"Finish Time\"].min()\ndf[\"diff(%)\"] = (df[\"diff(s)\"] / df[\"diff(s)\"].sum()) * 100\nprint (df)\n Finish Time diff(s) diff(%)\n0 1900-01-01 00:42:43.500 ... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074374219_pandas_python.txt |
Q:
Creating a sub-set of data having only null values
I have a data as under in a pandas dataframe [Original shape of the data : 149347 rows and 2 columns]. Purpose includes a text/strings and employeeID includes floats.
Purpose : Text,Text,Text, ,Text,Text, , ,Text |
Employee : 1,2,3,4,5,6,7,8,9
I want to create a ... | Creating a sub-set of data having only null values | I have a data as under in a pandas dataframe [Original shape of the data : 149347 rows and 2 columns]. Purpose includes a text/strings and employeeID includes floats.
Purpose : Text,Text,Text, ,Text,Text, , ,Text |
Employee : 1,2,3,4,5,6,7,8,9
I want to create a subset of the data, having only blanks "purpose" and als... | [
"Try:\nprint(df[df.Purpose.eq(\"\")])\n\nPrints:\n Purpose Employee\n2 3\n4 5\n\n\ndf used:\n Purpose Employee\n0 Text 1\n1 Text 2\n2 3\n3 Text 4\n4 5\n\n",
"df :\n Purpose Employee\n0 Text 1\n1 Te... | [
1,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0068453246_dataframe_pandas_python.txt |
Q:
Seaborn graph where indices are on x-axis and DataFrame values are on y-axis
I am trying to plot a DataFrame and am unable to get exactly what I'm looking for. Here's an example:
import pandas as pd
import seaborn as sns
df = pd.DataFrame({'Jim': {'ball': 5, 'bat': 8}, 'Nancy': {'ball': 9, 'bat': 10}}).T
I would ... | Seaborn graph where indices are on x-axis and DataFrame values are on y-axis | I am trying to plot a DataFrame and am unable to get exactly what I'm looking for. Here's an example:
import pandas as pd
import seaborn as sns
df = pd.DataFrame({'Jim': {'ball': 5, 'bat': 8}, 'Nancy': {'ball': 9, 'bat': 10}}).T
I would like a graph where Jim and Nancy are on the x-axis and the y-axis is the values 1-... | [
"I think you're looking for this plot?\nsns.scatterplot(data=df)\n\n\n"
] | [
1
] | [] | [] | [
"python",
"seaborn"
] | stackoverflow_0074372962_python_seaborn.txt |
Q:
sqlalchemy lef join with order
I'm trying to make this SQL query in sqlalchemy:
SELECT t1.superior_id from "user" as t1
LEFT JOIN "user" as t2 ON t1.superior_id = t2.id
ORDER BY t2.first_name, t2.last_name;
Whole thing is - order users by the name of their superior.
But still getting many errors (depends on wha... | sqlalchemy lef join with order | I'm trying to make this SQL query in sqlalchemy:
SELECT t1.superior_id from "user" as t1
LEFT JOIN "user" as t2 ON t1.superior_id = t2.id
ORDER BY t2.first_name, t2.last_name;
Whole thing is - order users by the name of their superior.
But still getting many errors (depends on what i try at the moment). Totally don'... | [
"I use Oracle_11g\\instantclient_21_3 :\nhttps://docs.oracle.com/en/database/oracle/oracle-database/21/lacli/install-instant-client-using-zip.html\nAnd for the query itself :\n\nI would not use ; at the end of the query\nI would not use \" \" for the name of tables inside the query\n\nimport cx_Oracle\nfrom sqlalc... | [
0
] | [] | [] | [
"python",
"sql",
"sqlalchemy"
] | stackoverflow_0074373037_python_sql_sqlalchemy.txt |
Q:
how would i save specific part of JSON as a variale?
I'm using a an Api to get manga cover arts , and to do so I need to save part of the Json response as a variable.
import requests
import json
title = "prison-school"
base_url = "https://api.mangadex.org"
r = requests.get(
f"{base_url}/manga",
params={... | how would i save specific part of JSON as a variale? | I'm using a an Api to get manga cover arts , and to do so I need to save part of the Json response as a variable.
import requests
import json
title = "prison-school"
base_url = "https://api.mangadex.org"
r = requests.get(
f"{base_url}/manga",
params={"title": title}
)
lol = [manga["id"] for manga in r.json... | [
"Try running filename = lol2['filename']\nBy using json.dumps you're turning the dictionary back into a json string.\nTo keep the json format, keep it as a dictionary and access the keys:\nimport requests\nimport json\n\ntitle = \"prison-school\"\n\nbase_url = \"https://api.mangadex.org\"\n\nr = requests.get(\n ... | [
0,
0
] | [] | [] | [
"api",
"json",
"python",
"string",
"variables"
] | stackoverflow_0074371170_api_json_python_string_variables.txt |
Q:
Python: How can I round each value in a two-dimensional Pandas dataframe to N decimal places while preserving the overall sum?
Goal: round each individual value in the two-dimensional (2D) dataframe to N decimal places while preserving the overall sum of the dataframe (to N decimal places). For example, if the ove... | Python: How can I round each value in a two-dimensional Pandas dataframe to N decimal places while preserving the overall sum? | Goal: round each individual value in the two-dimensional (2D) dataframe to N decimal places while preserving the overall sum of the dataframe (to N decimal places). For example, if the overall table sum was 500.29239, then sum-safe rounding to 2 decimal places should result in an overall sum of 500.29. The pandas.DataF... | [
"My (OP) own current solution that I am looking to improve upon / simplify:\nimport pandas as pd\nimport iteround # For rounding values in a table without changing overall sum\nimport numpy as np\nimport itertools as it # A number of iterator building blocks\n\n\n#########################################\n# Creat... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"rounding"
] | stackoverflow_0074374334_dataframe_pandas_python_rounding.txt |
Q:
Count the maximum number of 0s between two 1s in list python
I want to count the 0s between two 1s from a list.
For example:
l = [0,1,0,0,0,0,1,1,1,0,0,1,0,1,1,0]
I want the output to be [4,2,1]. How can I do that in python?
A:
A slightly different way using itertools.groupby - using the fact that any entries be... | Count the maximum number of 0s between two 1s in list python | I want to count the 0s between two 1s from a list.
For example:
l = [0,1,0,0,0,0,1,1,1,0,0,1,0,1,1,0]
I want the output to be [4,2,1]. How can I do that in python?
| [
"A slightly different way using itertools.groupby - using the fact that any entries beyond the first and last 1 is irrelevant to us\nfrom itertools import groupby\n\nfirst_one = l.index(1) # index of the first \"1\"\nlast_one = len(l) - l[::-1].index(1) - 1 # index of the last \"1\"\nout = [len(list(g)) for k, g in... | [
1,
0,
0,
0,
0
] | [] | [] | [
"binary",
"list",
"python"
] | stackoverflow_0074371364_binary_list_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.