QuestionId
int64
74.8M
79.8M
UserId
int64
56
29.4M
QuestionTitle
stringlengths
15
150
QuestionBody
stringlengths
40
40.3k
Tags
stringlengths
8
101
CreationDate
stringdate
2022-12-10 09:42:47
2025-11-01 19:08:18
AnswerCount
int64
0
44
UserExpertiseLevel
int64
301
888k
UserDisplayName
stringlengths
3
30
75,711,746
12,767,247
How to call and pass information to a Python script in a Laravel 9 project?
<p>I have an HTML form in my Laravel 9 project saved to the browser's localStorage using JS (with jQuery). I also have a Python script that needs to take a CSV-formatted database, modify it based on the information from localStorage, and convert it to JSON. Lastly, I have a JavaScript file that takes the JSON and build...
<javascript><python><json><laravel><laravel-9>
2023-03-12 07:53:45
1
500
andreasv
75,711,452
258,662
appropriate method to read ungridded lat / long csv as raster in python?
<p>I have a csv file or data.frame of un-gridded latitude/longitude coordinates which I would like to coerce to a raster object in python (e.g. ideally using <code>rasterio</code>).</p> <p>While GDAL's 'xyz' driver only accepts gridded coordinates in a text file, spatial packages in R are happy to do this coercion from...
<python><geospatial><raster><spatial><rasterio>
2023-03-12 06:36:44
1
12,767
cboettig
75,711,311
10,284,437
python selenium chrome driver 111 path is not handled
<p>I have this code:</p> <pre><code>#!/usr/bin/env python import selenium from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.chrome.options import Options chrome_options = Options() import undetected_chromedriver as uc driver = uc.Chrome(executable_path='/usr/local/bin/c...
<python><selenium-webdriver><selenium-chromedriver>
2023-03-12 05:59:38
1
731
Mévatlavé Kraspek
75,711,289
11,099,842
How to convert pandas column to numeric if there are strings?
<p>I have a dataset that has numerical values, empty values and text values. I want to do the following in pandas:</p> <ol> <li>Numerical Values -&gt; Float</li> <li>Empty Values -&gt; N/A</li> <li>Text Values -&gt; N/A</li> </ol> <p>When I try to run <code>astype('float')</code>, I get an error:</p> <pre><code>import ...
<python><pandas>
2023-03-12 05:54:03
1
891
Al-Baraa El-Hag
75,711,286
2,218,086
Decimal numbers in Python are displayed as floats
<p>I have defined my variables as decimal but they are still output as float when I print them.</p> <p>My actual problem has complex calculations and I want to print the values to verify my results but I’m getting floats not decimals.<br> Does this simply not matter as the calculations will come out correctly?</p> <pre...
<python>
2023-03-12 05:52:23
1
411
David P
75,711,193
6,446,053
Running Selective Unit Tests in Jetbrains Idea or Pycharm
<p>I have a test suite with multiple test methods, but I want to run only a specific test method (i.e., test_one) using Jetbrains product (e.g., Pycharm, Idea). In this case, I try to avoid using the command line approach.</p> <p>How can I do that?</p> <p>The unit test is as below:</p> <pre><code>import unittest class...
<python><unit-testing>
2023-03-12 05:18:31
1
3,297
rpb
75,710,936
2,947,218
Match rule json with data json to find value in python3
<p><strong>PYTHON3</strong></p> <h2>Need to Find articleid by applying rules on data</h2> <p>Given a set of rules in JSON format, which includes article IDs and corresponding properties rules.</p> <p>Eg: <code>rules.json</code></p> <pre><code>{ &quot;rules&quot;: [ { &quot;articleId&quot;: &quot;art1&quot;,...
<python><json><python-3.x>
2023-03-12 03:39:39
1
606
Sudipta Dhara
75,710,928
7,932,972
How can I ensure every us state is accounted for in a pandas dataframe?
<p>Im very new to pandas</p> <p>I have a CSV that contains 43 states and a count of how many times something has happened in that state.</p> <pre><code>STATE,Count AL,1 AK,4 AZ,7 </code></pre> <p>My CSV does not contain every state, how can I ensure that every state is accounted for? If its not in the original datafram...
<python><pandas><dataframe>
2023-03-12 03:37:24
2
357
Joey Stout
75,710,514
384,936
cannot plot the predictions
<p>When i apply valid predictions, it errors out stating only IndexError: only integers, slices (<code>:</code>), ellipsis (<code>...</code>), numpy.newaxis (<code>None</code>) and integer or boolean arrays are valid indices</p> <p>How can i convert this to ensure i can plot the predictions?</p> <pre><code>import nump...
<python><machine-learning>
2023-03-12 01:02:31
0
1,465
junkone
75,710,491
12,389,536
Colorful notebook output with rich library
<p>May someone tell me how to set again that colorful output from jupyter notebook without using <code>rich.print</code>? I use VSCode. I've got this <em>feature</em> with kedro=0.18.4 and <em>lost</em> with kedro=0.18.5. <strong>Kedro</strong> requires <strong>rich</strong> as an dependency.</p> <p><a href="https://i....
<python><visual-studio-code><jupyter-notebook><kedro><rich>
2023-03-12 00:56:50
0
339
matt91t
75,710,267
525,865
working with BeautifulSoup - defining the entities for getting all the data of the target page - perhaps panda would solve this even better
<p>i am in the mid of a task with BeautifulSoup - the awesome python-library for all things scraping. what is aimed: i want to get the data out of this page: <a href="https://schulfinder.kultus-bw.de" rel="nofollow noreferrer">https://schulfinder.kultus-bw.de</a> note; its a public page for finding all schools in a c...
<python><pandas><csv><beautifulsoup>
2023-03-11 23:42:05
1
1,223
zero
75,710,142
1,506,589
Way around Pagination safeguards
<p>trying to scrape <a href="https://www.autoscout24.de/lst/bmw?atype=C&amp;cy=D&amp;desc=0&amp;ocs_listing=include&amp;sort=standard&amp;ustate=N%2CU" rel="nofollow noreferrer">this website</a> with python/selenium but they implemented a cunning way to stop scrapers - the pagination doesn't extend past 20 pages.</p> <...
<python><selenium-webdriver><web-scraping>
2023-03-11 23:12:12
1
593
Csongor
75,710,106
12,125,777
How to use a map function insted of a Loop Python
<p>I am working on django project. I would like to avoid use Loop because of a number of row in the file to upload.</p> <blockquote> <p>With a loop, I have this (it's nicely working with small files):</p> </blockquote> <pre><code>my_list = [] for ligne in my_json: network = Network( x1=ligne[&quot;x1&quot;]...
<python><django>
2023-03-11 23:00:39
1
542
aba2s
75,710,027
11,741,232
Sending an image with an ID across processes in Python, Windows
<p>I have a project with multiple Python processes on the same computer.</p> <p>Python process A is the central node, and it receives images and data from sensors.</p> <p>Python process A sends images to process B for image processing/feature detection, and process B sends back some information to process A. The system...
<python><shared-memory>
2023-03-11 22:42:25
1
694
kevinlinxc
75,709,969
15,724,084
python Scrapy framework adding to my code proxy
<p>I am trying new feature for myself as adding proxy port to my python scraper code.</p> <p>I took free proxy from this <a href="https://scrapingant.com/free-proxies/" rel="nofollow noreferrer">site</a>, and looked for an answer from <a href="https://stackoverflow.com/questions/4710483/scrapy-and-proxies">SO</a>. With...
<python><proxy><scrapy>
2023-03-11 22:30:58
1
741
xlmaster
75,709,963
1,647,792
CDKTF Iterator On AWS Resources
<p>I've gone through the source code of CDKTF TerraformIterator, and the AWS Subnets to try and find a way to iterate over Subnet when setting for_each. I'm not sure how to do this as the iterator requires a list of strings and I don't see anything that would return subnet ids from that class. Here is some Python pseud...
<python><amazon-web-services><terraform-cdk>
2023-03-11 22:30:04
1
399
jazzmasterkc
75,709,894
734,748
Display new chart or table in streamlit on demand
<p>All the tutorials online I found about streamlit is to create a fix type of table/chart, etc. I.e., the developer will write the code to display a table with the fixed query to extract the data.</p> <p>Imaging I have this use case:</p> <ol> <li>user type in something from the chat window: Show me the population grow...
<python><streamlit>
2023-03-11 22:17:13
1
3,367
drdot
75,709,741
10,870,383
Pydantic nested setting objects load env variables from file
<p>Using pydantic setting management, how can I load env variables on nested setting objects on a main settings class? In the code below, the <code>sub_field</code> env variable field doesn't get loaded. <code>field_one</code> and <code>field_two</code> load fine. How can I load an environment file so the values are pr...
<python><pydantic>
2023-03-11 21:47:08
2
541
stormakt
75,709,429
5,957
Django child model's Meta not available in a @classmethod
<p>I am trying to write a check for django abstract base model that verifies some facts about the inner <code>Meta</code> of a derived class. As per <a href="https://docs.djangoproject.com/en/4.1/topics/checks/#field-model-manager-and-database-checks" rel="nofollow noreferrer">documentation</a> the check is a <code>@cl...
<python><django><django-models>
2023-03-11 20:47:55
1
4,159
Kasprzol
75,709,404
2,479,786
python httpx use --compressed like curl
<p>How can I use httpx library to do something similar to</p> <pre><code>curl --compressed &quot;http://example.com&quot; </code></pre> <p>Meaning I want the library to check if server supports compression, if so send the right header and return the data to me as if it was not compressed?</p>
<python><httpx>
2023-03-11 20:43:24
2
2,931
Ehud Lev
75,709,399
7,747,759
What does it mean if -1 is returned for .get_device() for torch tensor?
<p>I am using pytorch geometric to train a graph neural network. The problem that led to this question is the following error:</p> <blockquote> <p>RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cpu and cuda:0! (when checking argument for argument mat1 in method wrapper_addm...
<python><pytorch><pytorch-geometric>
2023-03-11 20:42:02
2
511
Ralff
75,709,225
3,885,446
Yolo V8 on Raspberry Pi
<p>I am trying to localise my robot using a camera. After months trying to use classical computer vision to pinpoint landmarks in my garden I gave up and created a custom dataset and quickly trained a yolov8 nano model which was outstandingly effective. Now I have just got to work on speed. I ran the following code to ...
<python><raspberry-pi><yolo>
2023-03-11 20:07:59
2
575
Alan Johnstone
75,709,199
2,627,777
SimpleDirectoryReader cannot be downloaded via llama_index's download_loader
<p>I am using llama_index package to index some of our own documents and query them using GPT. It works fairly well with individual PDFs. However we have a large anout of PDFs which I would like to load in a single run as using its SimpleDirectoryReader. But I am getting the following error when the following commands ...
<python><gpt-3>
2023-03-11 20:04:05
2
1,724
Ishan Hettiarachchi
75,709,193
310,370
How to calculate image similarity of given 2 images by using open AI Clip model - which method / AI model is best for calculating image similarity?
<p>I have prepared a small example code but It is throwing error. Can't solve the problem because it is supposed to work.</p> <p>Also do you think are there any better approaches to calculate image similarity? I want to find similar cloth images. e.g. I will give an image of a coat and I want to find similar coats.</p>...
<python><huggingface-transformers><clip><huggingface>
2023-03-11 20:03:21
1
23,982
Furkan Gözükara
75,709,118
3,147,690
How are attribute names with underscore managed in Pydantic Models?
<p>Can anyone explain how Pydantic manages attribute names with an underscore?</p> <p>In Pydantic models, there is a weird behavior related to attribute naming when using the underscore. That behavior does not occur in python classes. The test results show some allegedly &quot;unexpected&quot; errors.</p> <p>The follow...
<python><pydantic>
2023-03-11 19:51:47
2
474
villamejia
75,707,839
4,321,525
Pandas read_csv() parse_dates does not limit itself to the specied column - how to fix?
<p>I want to read in different CSV files and while doing that, convert the time column to seconds since the epoch. However, the date_parser gets applied to more then the specified column, and my data is butchered.</p> <p>here is my code and some example data:</p> <pre><code>import pandas as pd TIME_STG = &quot;Datum ...
<python><pandas><datetime><timestamp>
2023-03-11 18:17:19
1
405
Andreas Schuldei
75,706,571
12,846,701
How to filter rows using custom function in pyarrow
<p>I've a parquet dataset that contains latitude and longitude values as separate columns. And I want to filter those rows that are inside a polygon, I'm able to do this in pandas dataframe but unable to do in pyarrow table.</p> <p>I'm using pyarrow to read the parquet files, as it's quite fast.</p> <p>Here's how I'm d...
<python><pandas><geolocation><pyarrow>
2023-03-11 17:07:16
1
356
cicada_
75,706,482
6,245,473
Select specific column in Python dictionary?
<p>I would like to select a specific field from a python dictionary. The following code produces a result of 152 lines, but I only want to select one line and output it as a dataframe.</p> <pre><code>import pandas as pd from yahooquery import Ticker AAPL = Ticker('AAPL') AAPL.earnings_trend </code></pre> <p>Code above...
<python><pandas><dataframe><dictionary><yfinance>
2023-03-11 16:51:12
2
311
HTMLHelpMe
75,706,131
17,378,883
How to split the list into sublists with length between 2 and 4?
<p>I want to write a function, which splits the list into sublists with length between 2 and 4, no more or less.</p> <p>For example this list <code>[&quot;a&quot;,&quot;a&quot;,&quot;a&quot;,&quot;a&quot;,&quot;a&quot;,&quot;a&quot;,&quot;a&quot;,&quot;a&quot;,&quot;a&quot;]</code> can turn into this <code>[[&quot;a&qu...
<python><python-3.x><list><function>
2023-03-11 15:57:28
3
397
gh1222
75,706,096
3,672,883
is "correct" or pythonic, this way of make getters or is better to use @property?
<p>I have a class where the attribute is a numpy array, and a lot of getters, for several slices of that array.</p> <p>The question is about what is a more pythonic way of doing this</p> <pre><code>def get_right_knee(self) -&gt; YoloV7PoseKeypoint: return self._get_x_y_conf(49) </code></pre> <p>or</p> <pre><code>@p...
<python><python-class>
2023-03-11 15:50:40
1
5,342
Tlaloc-ES
75,706,064
20,122,390
How to do web-scraping with python on pages with dynamic content?
<p>I'm trying to do web scraping on flight pages to compare prices for a specific month on the airlines, at the moment I have this:</p> <pre><code>from selenium import webdriver from selenium.webdriver.chrome.options import Options from bs4 import BeautifulSoup options = Options() options.add_argument('--headless') op...
<python><selenium-webdriver><web-scraping><beautifulsoup>
2023-03-11 15:44:56
0
988
Diego L
75,706,046
21,343,992
boto3 Multiple ways to wait for an instance to be ready, which is the correct one?
<p>I'm investigating a sporadic bug with <code>send_command()</code> and I think it might be related to the instance not being completely ready before sending the command.</p> <p>I was using this to wait for the instance:</p> <pre><code>instance.wait_until_running() </code></pre> <p>However I have also seen:</p> <pre><...
<python><amazon-web-services><amazon-ec2><boto3>
2023-03-11 15:41:11
1
491
rare77
75,706,032
10,735,076
Why is flask running on AWS Lambda corrupting GeoJSON files served using static folder?
<p>I am serving a simple folium map using the following flask app running as an AWS Lambda function:</p> <pre><code>from flask import Flask import serverless_wsgi from Map import fullscreen_map import logging logger = logging.getLogger() logger.setLevel(logging.INFO) app = Flask(__name__, static_folder=&...
<python><aws-lambda><folium>
2023-03-11 15:38:59
0
313
Anthony Townsend
75,705,912
4,989,403
Update a non trainable variable at the beginning of each epoch
<p>This question is similar to <a href="https://stackoverflow.com/questions/60102214/tensorflow-keras-modify-model-variable-from-callback">Tensorflow Keras modify model variable from callback</a>. I am unable to get the solution there to work (maybe there have been changes in TensorFlow 2.x since the solution was poste...
<python><tensorflow><keras>
2023-03-11 15:20:52
2
499
Anirban Mukherjee
75,705,893
384,936
How to broadcast operands with same shape?
<p>I get error when --&gt; 73 rmse = np.sqrt(np.mean(predictions - y_test)**2) 74 print(f&quot;RMSE: {rmse}&quot;) 75</p> <p>ValueError: operands could not be broadcast together with shapes (41,1) (101,1) How do i fix it?</p> <pre><code>import numpy as np import pandas as pd import matplotlib.pyplot as plt import tenso...
<python><machine-learning>
2023-03-11 15:17:59
1
1,465
junkone
75,705,845
13,460,543
Difference between ' and " in read_json?
<p>I have the following strings :</p> <pre class="lang-py prettyprint-override"><code>d1 = &quot;[{'col 1':'a','col 2':'b'}]&quot; d2 = '[{&quot;col 1&quot;:&quot;a&quot;,&quot;col 2&quot;:&quot;b&quot;}]' </code></pre> <p>These strings contains the same data.</p> <p>I only inverted the use of single and double quotes...
<python><json><pandas><dataframe>
2023-03-11 15:10:48
0
2,303
Laurent B.
75,705,324
7,848,740
Edit an Object of the PostgresSQL Database in Django from Celery Worker
<p>I'm trying to edit an object which is saved into my Postgress Database used by Django from a Celery Worker.</p> <p>The Worker is called when the signal <code>post_save</code> is called with</p> <pre><code>@receiver(post_save, sender=Task) def send_task_creation(sender, instance, created, raw, using, **kwargs): p...
<python><django><database><celery>
2023-03-11 13:39:11
1
1,679
NicoCaldo
75,705,280
2,312,666
Python - Assesing each line in a file against an IF
<p>The below works for a single ip or fqdn, but for a list of assets its failing and assigning them all as FQDNs.</p> <pre><code>#!/usr/bin/env python import argparse import ipaddress import re def parse_args(): # Assess arguments parser = argparse.ArgumentParser(description='do some sh*t') parser.add_arg...
<python><for-loop><if-statement>
2023-03-11 13:31:51
1
309
yeleek
75,705,140
2,889,970
How to properly manage Python application dependencies?
<h2>Problem</h2> <p>I have a Python application (not library) that i want to publish as a <code>pip</code> installable package. In order for the application to install and run predictably with <code>pip install</code> now, in a month or in 2 years i want to pin all dependencies, for example with <a href="https://github...
<python><pip><dependency-management><setup.py><pyproject.toml>
2023-03-11 13:08:24
2
2,564
timmwagener
75,705,043
13,944,524
Why some Django view classes had not been defined as abstract base class?
<p>I'm writing a small and lightweight Django-like back-end framework for myself just for experiment.</p> <p>If we look at <code>ProcessFormView</code> view(and some other views):</p> <pre class="lang-py prettyprint-override"><code>class ProcessFormView(View): def get(self, request, *args, **kwargs): return...
<python><python-3.x><django><django-views><abstract-class>
2023-03-11 12:49:16
1
17,004
S.B
75,704,833
14,853,907
Sizing the Python standard library
<p>I want to find out how many objects and methods there are in the standard library for a given Python 3.x installation, to compare to different languages. For this, I wrote a <code>script.py</code>.</p> <pre class="lang-py prettyprint-override"><code>from sys import stdlib_module_names from inspect import isclass fro...
<python><python-3.x>
2023-03-11 12:11:37
1
4,470
Donald Seinen
75,704,644
2,079,875
unable to install confluent-kafka python module on alpine 3.13.5
<p>I am trying to install <code>confluent-kafka</code> on a <code>alpine-3.13.5</code>. Basically i am trying the same in <code>docker in docker</code> - <a href="https://hub.docker.com/_/docker" rel="nofollow noreferrer">https://hub.docker.com/_/docker</a> as part of my <code>gitlab runner</code>.</p> <p>This is how m...
<python><docker><gitlab-ci-runner><alpine-linux>
2023-03-11 11:36:09
0
3,282
curiousguy
75,704,611
4,533,188
Getting the original name of an argument
<h1>Task</h1> <p>I would like to have a way to access the original name of a passed argument. I looked at the answers of</p> <ul> <li><a href="https://stackoverflow.com/questions/18425225/getting-the-name-of-a-variable-as-a-string">Getting the name of a variable as a string</a></li> <li><a href="https://stackoverflow.c...
<python>
2023-03-11 11:30:56
2
13,308
Make42
75,704,397
673,600
How to group data with color but still show a trendline for the entire dataset using Plotly Express?
<p>I'm getting a trend line, however the issue is that with color and a trendline (set to max of data points), I'm getting multiple lines. I only want one line on the entire data set. Here is my code:</p> <pre><code>fig = px.scatter(df, &quot;Date&quot;, y=&quot;Number&quot;, color=&quot;Technology&quot;, labels={ ...
<python><dataframe><plotly>
2023-03-11 10:51:52
1
6,026
disruptive
75,704,050
12,438,249
Process multiline JSON file without Commas at the end of new Record
<p>I have a multiline JSON File with no commas after a new record. I have tried to read it using both JSON and BSON libraries but it's not working. Below are the sample two records from the file.</p> <pre><code>{ &quot;_id&quot; : , &quot;form&quot; : , &quot;owner&quot; : , &quot;deleted&quot; : nu...
<python><json><python-3.x><mongodb>
2023-03-11 09:44:12
1
532
Abdul Haseeb
75,704,000
12,027,232
Correctly zipping two columns with different data types in cuDF
<p>I have the following DataFrame in cuDF:</p> <pre><code> Context Questions 0 Architecturally, the school has a Catholic cha... [To whom did the Virgin Mary allegedly appear ... 1 As at most other universities, Notre Da...
<python><rapids><cudf>
2023-03-11 09:35:15
1
410
JOKKINATOR
75,703,828
842,476
Problem with getting data from Yahoo finance with python
<p>I am trying to get data from Yahoo finance but keep getting the same error that says:</p> <pre><code>TypeError Traceback (most recent call last) &lt;ipython-input-23-3fd0d552ddbc&gt; in &lt;module&gt; 6 enddate = dt.datetime.now() 7 ----&gt; 8 data = web.get_data_yahoo(y_...
<python><yahoo-finance>
2023-03-11 09:03:01
0
302
Ayham
75,703,815
3,865,151
How to help Pylance understand dynamically added class properties
<p>I'm using code such as this to add properties dynamically to a class:</p> <pre class="lang-py prettyprint-override"><code>class A: def __init__(self, props) -&gt; None: for name in props: setattr(self.__class__, name, property(lambda _: 1)) </code></pre> <p>This will work as expected:</p> <pr...
<python><python-3.x><pylance>
2023-03-11 09:00:32
3
551
myke
75,703,773
8,618,242
ROS Service to Show Image
<p>I'm using <code>Ubuntu 20.04</code> and <code>ROS Noetic</code>, <code>OpenCV version 4.2.0.34</code> I'm creating a ros service to show an image:</p> <pre class="lang-py prettyprint-override"><code>#! /usr/bin/env python3 # -*- coding: utf-8 -*- import rospy import cv2 from img_reader.srv import ImgReader, ImgRead...
<python><opencv><ros>
2023-03-11 08:50:57
1
4,115
Bilal
75,703,668
7,421,447
Error when trying to use custom loss function in Pytorch binary classifier
<p>I am trying to create a binary classification pytorch model using a custom loss function with the help of this <a href="https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html" rel="nofollow noreferrer">tutorial</a>. The model works when using inbuilt loss functions such as <code>nn.CrossEntropyLoss()...
<python><machine-learning><pytorch>
2023-03-11 08:24:31
0
713
Alain Michael Janith Schroter
75,703,636
6,947,156
Running all cells again adding new rows instead of return new dataframe
<p>I am creating a class just like <code>lazypredict</code> library but with k fold support and return a data frame withh the mean score of every model every thing works and I can print dataframe but when I run again it add more rows to the old datafarme istead show the new dataframe I also try to use implace parameter...
<python><pandas><dataframe><visual-studio-code><jupyter-notebook>
2023-03-11 08:16:03
1
1,076
Burhan Khanzada
75,703,607
13,362,665
Segmenting multiple unfull ellipses from each other in an image
<p>I have an image of multiple not fully drawn ellipses, and I am trying to separate each one from the other to further calculate the diameter of each one, so in other words to get another 3 images containing each ellipse, I want to make the algorithm know which one is the outer circle, middle circle and inner one.</p>...
<python><image-processing><computer-vision><image-segmentation>
2023-03-11 08:09:34
1
593
Rami Janini
75,703,494
4,874,204
Python: Want to write zipfile.ZipFile object to disk as "foo.zip"
<p>It feels like I'm missing something obvious here.</p> <p>I have a zipfile.ZipFile object, which was created by writing files into it using io.BytesIO() called <code>buffer</code> as follows:</p> <pre><code>with zipfile.ZipFile(buffer, &quot;a&quot;) as zip: # write some things into the zip using zip.write() </co...
<python><io><zip>
2023-03-11 07:41:06
1
379
rorance_
75,703,265
10,625,950
Nothing happens after extracting .tar file in Python
<p>I downloaded the dataset from Yelp: <a href="https://www.yelp.com/dataset" rel="nofollow noreferrer">https://www.yelp.com/dataset</a> which is in .tar format.</p> <p>I tried the following in Python but nothing happened afterwards, am I doing anything wrong?</p> <pre><code>#import module import tarfile path = &quot;...
<python>
2023-03-11 06:42:20
0
684
Xin
75,702,975
21,343,992
AWS Boto3 send_command() always fails on Ubuntu "An error occurred (InvalidInstanceId) when calling the SendCommand operation"
<p>I'm using boto3 to create an EC2 instance and then <code>send_command()</code> to send Linux commands to execute. I created an IAM role and pass this to <code>create_instances()</code>.</p> <p>For the Amazon Linux AMI <code>ami-0329eac6c5240c99d</code> it works 99% of the time. For the Ubuntu 22.04 AMI <code>ami-0b8...
<python><amazon-web-services><amazon-ec2><boto3><aws-ssm>
2023-03-11 05:27:06
1
491
rare77
75,702,792
882,134
Error when attempting to run Google Colab Deforum Stable Diffusion with a local GPU -- ModuleNotFoundError: No module named 'helpers.save_images'
<p>I'm attempting to run Deforum in Google Colab (<a href="https://colab.research.google.com/github/deforum-art/deforum-stable-diffusion/blob/main/Deforum_Stable_Diffusion.ipynb" rel="nofollow noreferrer">https://colab.research.google.com/github/deforum-art/deforum-stable-diffusion/blob/main/Deforum_Stable_Diffusion.ip...
<python><google-colaboratory><stable-diffusion>
2023-03-11 04:32:44
0
309
user882134
75,702,735
8,194,364
How to handle multiple url calls using global driver with selenium web driver?
<p>I have a function that returns a webdriver as a singleton (only instantiate once AND global_driver is a global variable):</p> <pre><code>global_driver = None ... def getDriver(): global global_driver if not global_driver: options = Options() options.add_argument('--headless') global_d...
<python><selenium-webdriver>
2023-03-11 04:15:53
0
359
AJ Goudel
75,702,723
1,525,788
can't parse IP address from PDF file, no error, just empty
<p>I'm using Tika to parse IP addresses from a PDF file. Below is my code:</p> <pre><code>import tika from tika import parser import re # Press the green button in the gutter to run the script. if __name__ == '__main__': tika.initVM() # opening pdf file parsed_pdf = parser.from_file(&quot;static_hosts.pd...
<python><regex><pdf><tika-python>
2023-03-11 04:11:00
1
1,556
Huy Than
75,702,658
3,015,449
Numpy array copy slower than Python list copy
<p>I've seen several posts here about accessing individual items in numpy arrays and python lists via a for loop.</p> <p>My program is a little different. What I'm doing is copying a small array (or list) of about 10 elements and then using it. I'm doing this many times, so I want it to be fast. The application if y...
<python><list><numpy><performance>
2023-03-11 03:47:14
2
724
davo36
75,702,573
412,234
Pythonic way to check if x is a module
<p>This works for builtin types (str, list, int, etc) and for classes that are imported properly, but not module:</p> <pre><code>type(x) is module #NameError: name 'module' is not defined. </code></pre> <p>There are workarounds:</p> <pre><code>str(type(x)) == &quot;&lt;class 'module'&gt;&quot; type(x) is type(os) # Or ...
<python><syntax>
2023-03-11 03:17:51
1
3,589
Kevin Kostlan
75,702,555
9,542,989
DESCRIBE TABLE Equivalent for Apache Ignite
<p>I am looking to get the column names and the data types for my Apache Ignite tables. Is there a SQL query that can be used to accomplish this? Maybe an equivalent to the <code>DESCRIBE TABLE</code> command?</p> <p>If this is not possible using SQL, can it be done using the Python driver for Apache Ignite: <code>pyig...
<python><sql><apacheignite>
2023-03-11 03:08:26
1
2,115
Minura Punchihewa
75,702,521
5,617,608
Recognizing drop caps in PDF in python
<p>I'm currently using pymupdf to extract text blocks from a <a href="https://drive.google.com/file/d/1QgtIbxQusZGluMo-jir3HryKv5_VKJzj/view?usp=sharing" rel="nofollow noreferrer">file</a> in python.</p> <p><a href="https://i.sstatic.net/2RA37.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/2RA37.png" al...
<python><extract><pymupdf>
2023-03-11 03:00:24
1
1,759
Esraa Abdelmaksoud
75,702,242
5,212,614
How to make KMeans Clustering more Meaningful for Titanic Data?
<p>I'm running this code.</p> <pre><code>import pandas as pd titanic = pd.read_csv('titanic.csv') titanic.head() #Import required module from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.cluster import KMeans from sklearn.metrics import adjusted_rand_score documents = titanic['Name'] vectoriz...
<python><python-3.x><cluster-analysis><k-means>
2023-03-11 01:14:51
1
20,492
ASH
75,702,225
8,012,864
Python remove row from list of lists
<p>I have a list of lists that looks like this in Python...</p> <pre><code>[ [&quot;item 1&quot;, 'green', 'round', 'sold'], [&quot;item73&quot;, 'red', 'square', 'for sale'], ['item477', 'blue', 'rectangle', 'on hold'] ] </code></pre> <p>I have the name of the item <code>item73</code> generated...
<python>
2023-03-11 01:10:31
2
443
jsmitter3
75,702,101
3,886,898
Create a labeling project in Azure Machine Learning using python code
<p>The GUI in Azure Machine Learning for creating datasets is straight forward. But I have a hard time creating it through python code. I'm using the Python 3.8 Azure ML kernel. Here is the code I have but it's running into a bug and I'm not able to debug it.</p> <pre><code>from azureml.core import Workspace, Dataset f...
<python><azure><azure-functions><azure-machine-learning-service>
2023-03-11 00:37:23
2
1,108
Mohammad
75,702,065
7,267,480
h5py problem - driver lock request failed - how to fix? (under WSL Ubuntu)
<p>I am trying to use the h5py (<a href="https://pypi.org/project/h5py/" rel="nofollow noreferrer">https://pypi.org/project/h5py/</a>) package to handle the data of datasets in that format.</p> <p>I am using a side library to write datasets in that format, it uses the h5py.</p> <p>I got the following error when I tried...
<python><h5py><hdf>
2023-03-11 00:25:44
0
496
twistfire
75,701,995
5,323,311
Polars: Naming Dataframe Columns when using scan_csv on headerless CSVs
<p>It doesn't look like Polars' <code>scan_csv</code> supports user provided column names. This can make it a little awkward to work with headerless CSVs because you then have to either mutate your data for Polars or load with <code>read_csv</code> which has the <code>new_columns</code> argument (and while <code>new_co...
<python><dataframe><python-polars>
2023-03-11 00:06:21
1
895
Tshimanga
75,701,948
14,729,820
How to merge many data frames to only one
<p>I have directory that has many folders inside each folder has (<code>images folder &amp; labels text</code>) and I want to combine them to one dataframe file by concatnating folders name with images name to make them uinque names . The structuer of my directory like below :</p> <pre><code>$ tree . ├── sample │ ├-...
<python><json><pandas><dataframe><deep-learning>
2023-03-10 23:53:47
1
366
Mohammed
75,701,899
8,361,830
Cannot login with QRCode in TikTok using Selenium
<p>I have written a simple script to login in TikTok using qrcode, but when I scan it shows that URL is undefined:</p> <pre class="lang-py prettyprint-override"><code>from time import sleep from selenium import webdriver if __name__ == &quot;__main__&quot;: driver = webdriver.Chrome(driver_executable_path=&quot;pa...
<python><selenium-webdriver><selenium-chromedriver><tiktok>
2023-03-10 23:39:08
2
396
Dori
75,701,878
817,659
how to read a json web response representing a pandas dataframe
<p>I have a <code>json</code> response from a <code>FastAPI</code> <code>REST</code> <code>service</code> that is generated like this:</p> <pre><code>dfjson = df.to_json(orient='records', date_format='iso', indent=4) </code></pre> <p>and looks like this:</p> <pre><code>[ { &quot;Date&quot;:&quot;2017-12-01T...
<python><json><pandas><rest>
2023-03-10 23:34:38
1
7,836
Ivan
75,701,809
13,376,511
Why does set subtraction and .difference() run at different speeds
<p>To find the difference between two sets there is the <code>-</code> operator and <code>.difference()</code>. I'm using this code to time each of those:</p> <pre><code>import timeit print(timeit.timeit(''' a.difference({b}) ''', setup=''' a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} b = 3 ...
<python><set><cpython><pypy><timeit>
2023-03-10 23:20:21
1
11,160
Michael M.
75,701,791
7,133,942
How to use the current value of a variable in Python in another class without using arguments in the method
<p>I have the 2 python classes:</p> <p><strong>Test.py</strong></p> <pre><code>import Test2 variable1_Test = 1 #Call function from Test2 if __name__ == &quot;__main__&quot;: variable1_Test = 5 Test2.print_variables() </code></pre> <p><strong>Test2.py</strong></p> <pre><code>def print_variables (): import ...
<python>
2023-03-10 23:16:46
1
902
PeterBe
75,701,709
4,812,479
How do I align the display of non-aligning dataframe columns containing Arabic, Thai, CJK, etc Unicode characters?
<p>I have a dataframe containing some foreign Unicode characters, such as Arabic and Thai, that causes my dataframe's columns to be misaligned when viewed by a <code>print(df)</code> on the Terminal.</p> <p>I've tried <code>pd.set_option(&quot;display.unicode.east_asian_width&quot;, True)</code>, but it's only alignin...
<python><pandas><dataframe><unicode>
2023-03-10 23:00:27
0
316
Aeronautix
75,701,634
3,261,292
Pandas update field value with the output of another condition
<p>I have the following dataframe:</p> <p><a href="https://i.sstatic.net/4e389.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/4e389.png" alt="enter image description here" /></a></p> <p>What I want to achieve is, if id1 is not equal to id2, I want to update the y values (in <code>name</code> column) wit...
<python><pandas><dataframe><indexing><mask>
2023-03-10 22:47:01
1
5,527
Minions
75,701,576
6,676,101
How do we dispatch to different class methods based on the number of input arguments?
<p>We want to have a class with two methods of the same name, however:</p> <blockquote> <ol> <li>there exists a method which accepts exactly one argument.</li> <li>The other method accepts two or more arguments.</li> </ol> </blockquote> <p>Maybe, to implement multi-dispatching a person can download a third party librar...
<python><python-3.x><overloading><dispatch><overload-resolution>
2023-03-10 22:37:58
2
4,700
Toothpick Anemone
75,701,437
2,593,810
Why do we multiply learning rate by gradient accumulation steps in PyTorch?
<p>Loss functions in pytorch use &quot;mean&quot; reduction. So it means that the model gradient will have roughly the same magnitude given any batch size. It makes sense that you want to scale the learning rate up when you increase batch size because your gradient doesn't become bigger as you increase batch size.</p> ...
<python><deep-learning><pytorch><gradient-descent><learning-rate>
2023-03-10 22:15:02
1
4,257
offchan
75,701,348
6,676,101
What it the most pythonic way to call a super class `__getattr__` method?
<p>In the code below we attempt to overload the dot-operator.</p> <p>I am not sure how to call <code>__getattr__</code> from the super class inside of the <code>__getattr__</code> method defined inside of the sub-class.</p> <pre class="lang-python prettyprint-override"><code>class Floor: def __init__(this_floor, su...
<python><python-3.x><attributes><operator-overloading>
2023-03-10 21:59:40
1
4,700
Toothpick Anemone
75,701,313
726,730
python - pyinstaller hidden_import exe file then subprocess Popen the exe file
<p>is it possible in the .spec file to include as hidden_import an exe file, and then in then main py script use a command subprocess.Popen to run it?</p> <p>I am getting an error like:</p> <pre class="lang-py prettyprint-override"><code>Traceback (most recent call last): File &quot;running_example.py&quot;, line 40,...
<python><pyinstaller><popen>
2023-03-10 21:52:12
1
2,427
Chris P
75,701,278
12,106,577
Flask - Using javascript and url_for to replace html
<p>I am new to Flask (as well as whatever else is involved in what I'm trying to do, apparently) and I'm creating a small using M. Grinberg's Mega-Tutorial as reference (Flask==2.2.3, jQuery==3.6.4).</p> <p>I'm trying to incorporate a range html input element</p> <p><code>&lt;input id=&quot;slider&quot; type=&quot;rang...
<javascript><python><jquery><flask>
2023-03-10 21:47:01
1
399
John Karkas
75,701,273
1,473,517
Can callback show improved solutions with basinhopping without declaring a global variable?
<p>I am using <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.basinhopping.html" rel="nofollow noreferrer">basinhopping</a> from scipy and I would to see the progress that the optimizer is making. Currently I do:</p> <pre><code>def show_bh(a, b, c): global MIN if b &lt; MIN: ...
<python><scipy>
2023-03-10 21:46:00
2
21,513
Simd
75,701,272
3,047,531
In Python, does a function capture variables created after the function is defined?
<p>I am trying to better understand closures. Examples 1 - 3 make sense to me according to my understanding, but I think it must be incorrect since example 4 does not make sense to me.</p> <h1>Example 1</h1> <pre class="lang-py prettyprint-override"><code>def f(): print(x) x=1 f() # prints 1 </code></pre> <p>At the...
<python><closures>
2023-03-10 21:45:52
1
444
master_latch
75,701,262
346,977
Pandas dataframe: resampling time intervals and dividing values proportionally?
<p>I have the following pandas dataframe:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>index</th> <th>start_time</th> <th>end_time</th> <th>amount</th> </tr> </thead> <tbody> <tr> <td>foo</td> <td>2023-03-11 09:45:27</td> <td>2023-03-11 09:58:39</td> <td>48</td> </tr> <tr> <td>bar</td> <...
<python><pandas><group-by><resampling>
2023-03-10 21:43:30
1
12,635
PlankTon
75,701,258
1,663,762
Clone a Poetry project onto my PC and continue using Poetry
<p>It seems a simple question. I forked someone else's Github repository. This project is developed with and dependencies are managed by Poetry. The directory structure is there, pyproject.toml is there, poetry.lock is there.</p> <p>I have set up poetry on my local PC. And now what?</p> <p>I have gone through 473 tutor...
<python><github><python-poetry>
2023-03-10 21:43:09
1
353
Johannes Linkels
75,701,207
15,176,150
Which Design Pattern combines an Interface, a Factory, and Data?
<h3>Problem</h3> <p>I've tried reading <a href="https://python-patterns.guide/gang-of-four/composition-over-inheritance/#solution-2-the-bridge-pattern" rel="nofollow noreferrer">this resource</a> on the naming conventions for common Python design patterns, but I can't find a pattern that matches the class I'm creating....
<python><design-patterns><architecture><software-design>
2023-03-10 21:33:43
1
1,146
Connor
75,701,064
5,394,072
Why documentation etc. use @ in place of * for multiplication
<p>Why many documentations and blog posts use @ in place of * (multiplication operator) in python. <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.linprog.html#scipy.optimize.linprog" rel="nofollow noreferrer">Here</a> is an example. They use <code>C@x</code> instead of <code>c*x</code> (al...
<python><numpy>
2023-03-10 21:13:19
1
738
tjt
75,701,011
2,510,104
Python multiprocessing pipe max write size
<p>I am implementing a piece of code using multiprocessing package of Python running on Ubuntu. For more efficient communication between processes, I'm collecting data to be sent through multiprocessing.Pipe in an array and send the whole array once size goes beyond 1000 elements. I noticed there are occasional deadloc...
<python><multiprocessing><pipe><pickle>
2023-03-10 21:04:39
1
541
Amir
75,700,990
46,799
How can I print the value of a clicked point in altair_viz scatter plot?
<p>I have created a scatter plot from a dataframe. One of the columns contains large amounts of text, which isn't feasible to display in the hover bubble.</p> <p>I would like to be able to click on a point and the values in the corresponding row to be printed outside the scatter plot. I don't mind if it gets printed as...
<python><jupyter-notebook><altair><vega-lite>
2023-03-10 21:02:30
0
10,655
Shahbaz
75,700,946
2,580,302
Modify and re-queue a message using pika on python
<p>I'm using Pika/RabbitMQ lib for processing messages in a python 3.8 project. When processing the messages the function can fail due to several reasons. There are a few cases when the message can be recovered in part if modified. I'm currently creating a new message with the modified body and queuing it. This is not ...
<python><python-3.x><rabbitmq><pika>
2023-03-10 20:56:17
1
17,662
zetacu
75,700,807
633,318
Picking/filtering element from pandas table where data is between column header values
<p>I have some 2D data that has boundaries (<code>bins</code>) like this:</p> <pre class="lang-py prettyprint-override"><code>import numpy as npy # These are the boundaries of our wind speeds and directions speed_bins = npy.array([0.0, 0.5, 1.0, 2.0, 5.0, 10.0, 100.0]) dir_bins = npy.linspace(0,360,9) # Random LPF val...
<python><pandas><numpy><filter>
2023-03-10 20:37:15
1
15,194
jlconlin
75,700,499
13,742,058
How do WebDriverWait throw a NoSuchElementException if there is no element found?
<p>My code does not throw NoSuchElementException even if no element found using WebDriverWait ..</p> <pre><code>import time from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as ec from selenium.common.exceptions import NoSuchElementExce...
<python><selenium-webdriver><web-scraping><webdriverwait><nosuchelementexception>
2023-03-10 19:58:45
0
308
fardV
75,700,411
6,534,818
Python: str split on repeated instances in single string
<p>How can I split and remove repeated patterns from a string, such as?</p> <pre><code># sample s1 = '-c /home/test/pipeline/pipelines/myspace4/.cache/sometexthere/more --log /home/test1/pipeline2/pipelines1/myspace1/.cache/sometexthere/more --arg /home/test4/pipeline3/pipelines3/myspace3/.cache/sometexthere/more --new...
<python>
2023-03-10 19:46:30
1
1,859
John Stud
75,700,342
417,896
Python get microseconds from time stamp into uint64
<p>The purpose of this function is to get the microseconds from a numpy timestamp elapsed since the unix epoch.</p> <p>Would this conversion eventually overflow because the data type is restricted to an int64 instead of a uint64?</p> <pre><code>dt = np.datetime64('2023-01-01T00:00:00') timestamp_microsec = int((dt - np...
<python><numpy>
2023-03-10 19:36:58
0
17,480
BAR
75,700,322
1,028,133
When is d1==d2 not equivalent to d1.__eq__(d2)?
<p>According <a href="https://docs.python.org/3.8/reference/datamodel.html#basic-customization" rel="nofollow noreferrer">to the docs</a> (in Python 3.8):</p> <blockquote> <p>By default, <code>object</code> implements <code>__eq__()</code> by using <code>is</code>, returning <code>NotImplemented</code> in the case of a...
<python><python-3.x>
2023-03-10 19:32:53
3
744
the.real.gruycho
75,700,147
6,676,101
How do you unpack a nested iterator/iterable as an argument to a variadic function?
<p>Consider the following snippet of code written in Python-style syntax:</p> <pre class="lang-python prettyprint-override"><code>class k: def __init__(*args): self._args = args def mimethod(self, attrname:str): return type(self)(getattr(arg, attrname) for arg in self._args) </code></pre>...
<python><iterable>
2023-03-10 19:11:33
2
4,700
Toothpick Anemone
75,700,124
9,105,621
What does {method 'poll' of 'select.poll'...} mean in cprofile output?
<p>I have a flask app that I'm trying to profile (I'm new to this). When I ran it, I had this result:</p> <pre><code>3327 function calls (3247 primitive calls) in 7.350 seconds Ordered by: cumulative time ncalls tottime percall cumtime percall filename:lineno(function) 7/1 0.000 0.000 7.350 ...
<python><cprofile>
2023-03-10 19:09:19
1
556
Mike Mann
75,700,004
20,358
How to check in Python if the value in a key value pair of a dict is a list or a string
<p>I have an object like this</p> <pre><code>ds_obj = { &quot;Labels&quot; : [ { &quot;Label&quot; : &quot;pop&quot;, &quot;People&quot; : { &quot;Composer&quot; : &quot;John&quot; ...
<python><dictionary>
2023-03-10 18:55:42
2
14,834
user20358
75,699,994
20,266,647
Sklearn-classifier, issue with freez (pod pending in K8s)
<p>I got freez of Sklearn-classifier in MLRun (the job is still running after 5, 10, 20, ... minutes), see log output:</p> <pre><code>2023-02-21 13:50:15,853 [info] starting run training uid=e8e66defd91043dda62ae8b6795c74ea DB=http://mlrun-api:8080 2023-02-21 13:50:16,136 [info] Job is running in the background, pod: t...
<python><kubernetes><scikit-learn><classification><mlrun>
2023-03-10 18:54:03
1
1,390
JIST
75,699,951
4,348,400
Finding where Pandera schemas are different
<p>I have two Pandas data frames <code>df1</code> and <code>df2</code> which <em>should</em> have the same inferred Pandera schema. Unfortunately they do not because when I run <code>pa.infer_schema(df1) != pa.infer_schema(df2)</code> I get a return of <code>False</code>. The print out (which should be <code>__repr__</...
<python><pandas><validation><schema><pandera>
2023-03-10 18:49:16
1
1,394
Galen
75,699,877
6,676,101
What is an example of a class decorator which overrides `__getattribute__` or `__getattr__`?
<p>Suppose that we want to overload the dot-operator, also known as <code>__getattribute__</code></p> <pre class="lang-python prettyprint-override"><code>obj.insert() obj.__getattribute__(&quot;insert&quot;)() height = rectangle.height height = rectangle.__getattribute__(&quot;height&quot;) </code></pre> <p>Is th...
<python><python-3.x><attributes><operator-overloading>
2023-03-10 18:38:46
0
4,700
Toothpick Anemone
75,699,856
14,269,252
DuplicateWidgetID: There are multiple identical st.checkbox widgets with the same generated key
<p>I am building stream lit app, I defined two function, sidebar, tab, etc. output of first function is simply a data frame, and output of the second function is chart. I get the error as follows. The error seems to be because of the second function</p> <pre><code> def func(): option_1 = st.sidebar.checkbox('x1', v...
<python><streamlit>
2023-03-10 18:35:53
1
450
user14269252