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
79,533,019
2,038,383
Get name of executed .pex file?
<p>Consider this script <code>/tmp/test.py</code>:</p> <pre class="lang-py prettyprint-override"><code>import os import sys print(__file__) print(os.path.dirname(os.path.realpath(__file__))) print(sys.argv) </code></pre> <p>bundled like this with <code>pex</code>:</p> <pre><code>python -m pex --exe test.py -o test.pex ...
<python><pex>
2025-03-25 08:08:12
1
8,760
spinkus
79,532,844
9,359,102
Create a Class object using the username from incoming data
<p>Python newbie here:</p> <p>I have a</p> <pre><code>class ExampleState: ... </code></pre> <p>My purpose is to create a class object unique to every user. I get the username from my client flutter app in django.</p> <p>So, instead of</p> <pre><code>state = ExampleState() </code></pre> <p>it should be</p> <pre><cod...
<python>
2025-03-25 06:38:47
1
489
Earthling
79,532,659
5,483,765
FastAPI openapi_examples not working with Query() although it works with Body(). How can I make it work with Query()?
<p>I am using <code>fastapi==0.115.12</code> and I have the following code:</p> <pre class="lang-py prettyprint-override"><code>from fastapi import FastAPI, Body, Query from pydantic import BaseModel app = FastAPI() class GetFrameworksRequest(BaseModel): devtype: str languages: Optional[list[str]] | None = No...
<python><fastapi><openapi><swagger-ui>
2025-03-25 03:59:13
0
1,035
Hassan
79,532,585
9,986,939
SQLAlchemy Count returns NoneType
<p>I'm working on a FastAPI project and I'm using SQLAlchemy to map the data to the API. I swear this problem started randomly as I've reverted back to my MVP code (bookmarked so I can always roll back to working code), and it still doesn't work.</p> <p>My situation is this, I'm trying to query the database to get the ...
<python><sqlalchemy><databricks><databricks-sql>
2025-03-25 02:37:31
1
407
Robert Riley
79,532,447
889,053
Does the oracle driver for python really require libraries from the native client?
<p>I am writing some Python code and pulling in the</p> <pre class="lang-yaml prettyprint-override"><code>cx-oracle = &quot;^8.3.0&quot; </code></pre> <p>library with poetry. However, in order to make this work I actually have to initialize it with a directory where it can find the native libraries. Specifically, <a hr...
<python><oracle-database><python-poetry>
2025-03-25 00:35:40
1
5,751
Christian Bongiorno
79,532,425
11,231,350
Applying a 2D deformation field to an image
<p>I am trying to deform an image using the following vector field.</p> <p>I have tried to use the response in <a href="https://stackoverflow.com/a/58727841/11231350">this post</a>. However, all of my attempts have been unsuccessful till now.</p> <p>The deformation field is generated using the following code:</p> <pre>...
<python><opencv><image-processing><graphics><computer-vision>
2025-03-25 00:16:47
0
369
alpha027
79,532,418
1,445,660
sqlalchemy - clear list and add item - null violation for foreign key
<p>I try to clear a list and add an item to it. I get <code>IntegrityError('(psycopg2.errors.NotNullViolation) null value in column &quot;game_id&quot; of relation &quot;player&quot; violates not-null co...2, null).\n')</code></p> <pre><code>class Game(Base): __tablename__ = &quot;game&quot; game_id: int = Colu...
<python><postgresql><sqlalchemy>
2025-03-25 00:10:12
0
1,396
Rony Tesler
79,532,286
14,471,263
Array time complexity when modifying elements in Python
<p>I was reading a bit on DS/A and found this cheat sheet on Leet Code..</p> <p>Add or remove element from arbitrary index: O(n) Access or modify element at arbitrary index: O(1)</p> <p>Intuitively I would think they would both be O(n). Why is one O(1) and the other O(n)?</p> <p>Why is adding or removing an element lin...
<python><time-complexity>
2025-03-24 22:21:40
1
301
rarara
79,532,275
2,112,406
Why does torch import complain about numpy version
<p>I created a virtual environment on MacOS and installed pytorch with pip:</p> <pre><code>python -m env torch-env source torch-env/bin/activate pip install torch torchvision torchaudio </code></pre> <p>Launching python and importing torch fails, however:</p> <pre><code>Python 3.11.2 (main, Mar 5 2023, 23:08:47) [Clan...
<python><python-3.x><numpy><pytorch>
2025-03-24 22:13:30
0
3,203
sodiumnitrate
79,532,148
3,625,865
Slack bolt python use metadata when using blocks in say() function
<p>I have this block of code which is responsible for selecting the namespace:</p> <pre class="lang-py prettyprint-override"><code>@app.command(&quot;/enable_worker&quot;) def enable_worker(ack, body, say): ack() blocks = [ { &quot;type&quot;: &quot;section&quot;, &...
<python><slack><slack-api><slack-bolt>
2025-03-24 21:04:01
0
2,743
Yashar
79,531,906
3,732,793
select value does fail in cosmo db
<p>new to cosmoDB tried this and it worked fine</p> <pre><code>cosmos_db = cosmos_client.create_database_if_not_exists(&quot;Test_DB&quot;) container = cosmos_db.create_container_if_not_exists(&quot;test_data&quot;, PartitionKey(path='/id', kind='Hash')) container.create_item({&quot;id&quot;: &quot;1&quot;, &quot;valu...
<python><azure-cosmosdb>
2025-03-24 18:47:24
1
1,990
user3732793
79,531,838
6,936,582
Create a graph using the edge attribute as node
<p>I have a directed graph where the edges have the attribute <code>edge_id</code>. I want to create a new graph using the <code>edge_id</code> as nodes.</p> <p>I think there should be some more straightforward method than this?</p> <pre><code>import networkx as nx import matplotlib.pyplot as plt edges = [(&quot;A&quo...
<python><networkx>
2025-03-24 18:12:22
1
2,220
Bera
79,531,810
3,575,623
'numpy.float64' object has no attribute 'numerator' for statistics.stdev()
<p>I have this function to calculate Cohen's D for some csv files</p> <pre><code>import statistics import numpy as np def cohen_d(a,b): float_a = [] float_b = [] for x in a: try: float_a.append(float(x)) except ValueError: return &quot;NAN&quot; for y in b: ...
<python><numpy>
2025-03-24 17:58:33
1
507
Whitehot
79,531,796
2,266,881
Polars Dataframe from nested dictionaries as columns
<p>I have a dictionary of nested columns with the index as key in each one. When i try to convert it to a polars dataframe, it fetches the column names and the values right, but each column has just one element that's the dictionary of the column elements, without &quot;expanding&quot; it into a series.</p> <p>An examp...
<python><dataframe><python-polars><polars>
2025-03-24 17:51:43
1
1,594
Ghost
79,531,667
2,526,586
Best practice for sharing resource in a Python module?
<p>Consider a Python3.1X project like this:</p> <pre><code>├─ my_module_1 │ ├─ a.py │ └─ b.py ├─ my_module_2 │ ├─ c.py │ └─ d.py └─ main.py </code></pre> <p><code>main.py</code> would import <code>my_module_1</code> and <code>my_module_2</code>. <code>main.py</code> would provision/initialise resources such as data...
<python><python-3.x><logging><dependency-injection>
2025-03-24 16:53:29
0
1,342
user2526586
79,531,664
16,383,578
What is the fastest way to generate alternating boolean sequences in NumPy?
<p>I want to create a 1D array of length n, every element in the array can be either 0 or 1. Now I want the array to contain alternating runs of 0s and 1s, every full run has the same length as every other run. Every run of 1s is followed by a run of 0s of the same length and vice versa, the gaps are periodic.</p> <p>F...
<python><arrays><numpy>
2025-03-24 16:52:22
3
3,930
Ξένη Γήινος
79,531,519
6,362,595
Installing `stringcase` under python `3.13.2` fails while it works on `python 3.12.9`
<p>I am trying to install the (seemingly abandoned) <code>stringcase</code> <a href="https://github.com/okunishinishi/python-stringcase/tree/master" rel="nofollow noreferrer">python package</a> with a <code>python3.13.2</code> build on ubuntu in a <code>venv</code> like so::</p> <pre><code> python3.13 -m venv venv ...
<python><pip>
2025-03-24 15:43:54
1
921
fgoudra
79,531,474
842,693
in Altair, can I assign fixed colour indices to data values?
<p>I have data in pandas dataframes, where I make plots of several subsets of the data, using Altair. In all the plots, colours are taken from some categorical column. To make the charts easy to read, I want each category to have the same colour in all the charts, even if the category selection differs between charts. ...
<python><altair>
2025-03-24 15:28:49
1
1,623
Michal Kaut
79,531,444
8,746,228
Find the value that is different when a row is marked "left_only" or "right_only" when comparing Pandas DataFrames
<p>There are two dataframes: <code>current</code> and <code>base</code>. <code>current</code> is an incremental update to <code>base</code>.</p> <p>Whenever there is an update made to <code>current</code>, we want to run checks to see if it adheres to rules. If it does, <code>current</code> becomes <code>base</code>.</...
<python><pandas><dataframe>
2025-03-24 15:15:42
1
1,513
adarsh
79,531,412
305,883
AWS - put data on S3 results in TimeOutError
<p>I am creating a dataset on AWS S3, for their Opendata program.</p> <p>I am fetching audio files, which are already stored on S3. I then segment them into smaller audio chunks, and putting those on S3 again. The problem occurs when I need to PUT (if I comment out, it won't give error).</p> <p>The S3 bucket is in US-r...
<python><amazon-web-services><amazon-s3><timeout><put>
2025-03-24 15:01:36
1
1,739
user305883
79,531,319
16,383,578
How to use Numba Cuda without Conda?
<p>I don't use Conda. I have downloaded and installed cuda_12.8.1_572.61_windows.exe from the <a href="https://developer.nvidia.com/cuda-downloads?target_os=Windows&amp;target_arch=x86_64&amp;target_version=11&amp;target_type=exe_local" rel="nofollow noreferrer">official link</a>. I have installed numba 0.61.0, numba-c...
<python><cuda><numba>
2025-03-24 14:22:14
1
3,930
Ξένη Γήινος
79,531,119
2,412,837
I2C Slave respond to registry read on Raspberry Pi with Python using pigpio package
<p>I need to respond to a specific registry read over I2C on an RPi.</p> <p>Currently, following the usual instructions for the pigpio package here: <a href="https://abyz.me.uk/rpi/pigpio/python.html#bsc_xfer" rel="nofollow noreferrer">https://abyz.me.uk/rpi/pigpio/python.html#bsc_xfer</a> i can see the reads to the de...
<python><raspberry-pi><i2c>
2025-03-24 12:48:07
0
346
tobynew
79,531,055
607,407
Can I get different boto3 instances to share their connection pool to the same host?
<p>I have code that creates few S3 objects but for many access keys. It does so in parallel, but within the same python process.</p> <p>Each of the boto3 instances has its own connection pool, which can linger even when it is not used. What happens, on occassion, is that the whole thing crashes with some variant of thi...
<python><boto3>
2025-03-24 12:23:56
0
53,877
Tomáš Zato
79,531,015
2,266,881
Bad request version/syntax/type when executing POST request to flask
<p>Good Morning,</p> <p>I'm trying to set up a local flask app running for testing some python code, i used to do it the same way a lot (with the same python script) without any issues, but now i'm getting random 'bad request version/type/syntax&quot; errors and a lot of random bytes text errors.</p> <p>To set the app ...
<python><flask>
2025-03-24 12:04:59
0
1,594
Ghost
79,530,884
6,601,575
Unable to start a pyFlink job from savepoint
<p>I'm using Flink 1.20.0, and try to submit a pyFlink job and start it from aan existed savepoint, I execute in command line:</p> <pre><code>flink run --fromSavepoint s3a://.../1a4e1e73910e5d953183b8eb1cd6eb84/chk-1 -py flink_job.py -pyFiles requirements.txt --table my_table --bucket my_bucket --secret my_secret </cod...
<python><apache-flink><flink-streaming><flink-sql><pyflink>
2025-03-24 11:02:14
1
834
Rinze
79,530,877
8,040,369
Importing NeuralProphet throwing ModuleNotFoundError: No module named 'importlib_resources'
<p>I have installed the latest version of &quot;NeuralProphet&quot;, and when I try to import it, getting the below error with <strong>importlib_resources</strong></p> <p>Tried installing the package separately using <strong>pip install importlib-resources</strong>, but still the same issue persists. Below is the error...
<python><prophet>
2025-03-24 10:58:30
0
787
SM079
79,530,829
1,306,892
Issues with Recursive Digraph Construction and Missing Loops in Python Code
<p>I'm trying to write code to recursively generate directed graphs as described in the following process:</p> <ul> <li>For <code>G_1</code>, we start with a single vertex with a self-loop.</li> <li>For <code>G_2</code>, we take two copies of <code>G_1</code>, add a new vertex, and connect them with new edges.</li> <li...
<python><networkx><graph-theory>
2025-03-24 10:33:42
1
1,801
Mark
79,530,791
4,473,615
Move files from one S3 to another using Boto3 in Python from multiple sub bucket levels
<p>I have below code to move the file from one S3 bucket to another which works perfectly. The catch here is while copying the files it copies the S3 bucket as well, instead I wanted to copy only the file from the bucket.</p> <p><code>Source bucket - bucket-source/Source-First/</code> --&gt; This file has multiple .xls...
<python><amazon-s3><boto3>
2025-03-24 10:18:52
0
5,241
Jim Macaulay
79,530,763
12,870,651
Python in VS Code - Change the default directory of python shell
<p>I am working on a ETL code template using VS Code which has the building blocks for most of the ETL workflows my team uses.</p> <p>Idea is that folks will <code>git clone</code> the repo and use this as a base for building ETLs rather than writing all the code from scratch.</p> <pre><code>root/ └── src/ ├── pyth...
<python><visual-studio-code>
2025-03-24 10:05:43
0
439
excelman
79,530,541
11,159,734
Cursor IDE overwrite TAB complete without disabling it in python
<p>I'm using cursor for a while not and I generally like it but it's incredible annoying when programming in python. The image below shows a simple example. My cursor is in line 22 and I just want to insert a TAB space since I do not want to autocomplete the suggestion in line 21. However as far as I know it's impossib...
<python><cursor-ide>
2025-03-24 08:29:17
0
1,025
Daniel
79,530,318
1,145,011
python script to check if the downloaded file from URL is corrupted or not
<p>I have a request to download files from URL and store in local system. Files are of different format like pdf, ppt, doc, docx, zip, jpg, iso etc. After downloading the files, is there a way to check if downloaded files are corrupted or not. Most of options suggested to use Checksum approach, but I do not have checks...
<python><python-requests>
2025-03-24 06:35:21
2
1,551
user166013
79,530,149
1,481,689
Problem if two inherited __init_subclass__s have the same argument name
<p>I'm trying to use two classes, <code>A</code> and <code>B</code>, as mixing classes of <code>AB</code>. They both have <code>__init_subclass__</code> methods. The problem is that both <code>__init__sublass__</code> methods have the same argument <code>msg</code>. Therefore I've used an adaptor class <code>B_</code> ...
<python>
2025-03-24 04:52:49
1
1,040
Howard Lovatt
79,530,146
4,126,111
Autogen: How to get a simple csv from the search instead of using
<p>I am trying to get data from the web. Unfortunately, I get this error. I suppose that it identifies a big file using a search and then tries to have a conversation about that entire file. Is there any way to navigate him to download the file, check the headers, and then process it? <a href="https://i.sstatic.net/oJ8...
<python><csv><web-scraping><large-language-model><ms-autogen>
2025-03-24 04:50:19
0
1,189
Karel Macek
79,530,047
10,321,138
Incorrect argument error when trying to enqueue a task within a firebase function
<p>I have a firebase function that attempts to enqueue a task with some data. Every time I call it I get the following two errors from the cloud run logs:</p> <blockquote> <p>requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: <a href="https://cloudtasks.googleapis.com/v2/projects/PROJECT_ID/locations...
<python><firebase><google-cloud-functions>
2025-03-24 02:54:01
1
1,896
yambo
79,530,017
1,445,660
return header without quotes in aws lambda + remove header if empty
<p>I'm trying to return a header from a lambda, it's returned as <code>&quot;&lt;https://example.com/ab?offset=0&amp;limit=0&gt;; rel=\&quot;next\&quot;&quot;</code> instead of <code>&lt;https://example.com/ab?offset=0&amp;limit=0&gt;; rel=&quot;next&quot;</code>.</p> <p>And also when I don't return the header, I still...
<python><aws-lambda><aws-cdk>
2025-03-24 02:18:02
0
1,396
Rony Tesler
79,529,986
234,118
No local python in Conda venv
<p>I am using a M2 Macbook Pro. conda 24.9.2. Python 3.12. Why the command &quot;python&quot; is not &quot;localized&quot;?</p> <pre><code>conda create -n f5-tts python=3.10 conda activate f5-tts which pip =&gt; /opt/anaconda3/envs/f5-tts/bin/pip which python =&gt; python: aliased to /usr/local/bin/python3 which py...
<python><conda><python-venv>
2025-03-24 01:28:23
0
5,540
Dustin Sun
79,529,951
1,788,496
Python: Get the Source State in Twain
<p>I have a python script where I am using Twain to interact with my scanner. First I initialize my source:</p> <pre><code>scanner = sm.OpenSource() </code></pre> <p>set a few capabilities then request to acquire an image:</p> <pre><code>scanner.RequestAcquire(0, 1) </code></pre> <p>I then try to transfer an image:</p>...
<python><twain>
2025-03-24 00:52:31
0
1,447
mgrenier
79,529,708
2,023,370
How to avoid a Torch error with Open WebUI/Ollama
<p>I'd like to get Open WebUI working with Ollama on Ubuntu 24.10, but installing it using pip and venv leads me to a <code>torch</code> error.</p> <p>Firstly, Ollama (0.6.2) is working: I can type <code>/path/to/ollama list</code> and see the 3 models I've been working with.</p> <p>Next, I follow the guidance in the e...
<python><pip><torch><python-venv><ollama>
2025-03-23 21:15:29
1
11,288
user2023370
79,529,322
1,236,840
Do subset-sum instances inherently require large integers to force exponential difficulty?
<p>I'm developing custom subset-sum algorithms and have encountered a puzzling issue: <strong>it seems difficult to generate truly &quot;hard&quot; subset-sum instances (i.e., forcing exponential computational effort) without using very large integers (e.g., greater than about 2^22).</strong></p> <p>I'd specifically li...
<python><algorithm><optimization><subset-sum>
2025-03-23 17:05:03
2
1,010
Naseiva Juman
79,529,320
10,918,680
PIL.UnidentifiedImageError for some image URL, but not others
<p>I'm trying to open an image at a URL using Pillow, but it only works for some URL. In my code below, URL1 works but not URL2.</p> <pre><code>import requests from PIL import Image url1 = &quot;https://picsum.photos/200&quot; # url2 = &quot;https://www.electrical-forensics.com/MajorAppliances/GE/Small/GE_2018_Stackab...
<python><image><python-requests><python-imaging-library>
2025-03-23 17:02:52
0
425
user173729
79,529,216
3,783,002
Cannot load an EF Core db context wrapper in Python using Python.NET
<p>Crossposting from <a href="https://github.com/pythonnet/pythonnet/discussions/2567" rel="nofollow noreferrer">here</a></p> <p>I have a class called <code>ModelSetWrapper</code> which wraps model sets from an EfCore DbContext (Jet, specifically) and returns a dictionary containing the model set information. Here's wh...
<python><c#><entity-framework-core><python.net><jet-ef-provider>
2025-03-23 15:47:52
0
6,067
user32882
79,529,060
3,815,773
ssh not accepting access with keygen keys
<p>I have a Desktop plus NAS setup, and did save backups via ssh. It has worked for years, but then the NAS crashed and was replaced. Both desktop and NAS are now regular computers running Linux Mint LMDE6. But now something is wrong in the SSH workings.</p> <p>My backup program (<a href="https://sourceforge.net/projec...
<python><ssh>
2025-03-23 14:03:22
2
505
ullix
79,528,990
14,351,788
Segmentation Fault during open() of JSON file in Python 3.8
<p>I am encounting a segmentation fault in my Python application, which utilizes MQTT to send requests to a service. The service then writes the response into a JSON file, which the application subsequently reads to retrieve the results.</p> <p>The problem manifests as a segmentation fault when the application attempts...
<python><python-3.x><segmentation-fault>
2025-03-23 13:06:50
1
437
Carlos
79,528,948
11,062,613
How to efficiently use NumPy's StringDType for string operations (e.g., joining strings)?
<p>I'm trying to perform string operations with NumPy's StringDType. As an example, I've attempted to join strings with a separator row-wise. In the past, NumPy's string operations were somewhat slower compared to Python list comprehensions, and I was hoping that with the introduction of NumPy's StringDType (which supp...
<python><string><numpy>
2025-03-23 12:29:48
0
423
Olibarer
79,528,403
4,609,089
unsloth save_pretrained_merged function issue
<p>I tried to save the model with the below code but failed. Planning to use <code>unsloth/Llama-3.2-11B-Vision-Instruct</code> as a base model to fine-tune a new model.</p> <pre><code>!pip install unsloth model, tokenizer = FastVisionModel.from_pretrained( &quot;unsloth/Llama-3.2-11B-Vision-Instruct&quot;, loa...
<python><model><fine-tuning>
2025-03-23 03:23:36
1
833
John
79,528,380
1,394,353
Is it possible to turn off printing the id (hex address) globally for Python objects?
<p>When you don't provide a <code>__repr__</code> or <code>__str__</code> method on a custom class, you just get a classname and the Python address of the object (or, to be more specific, what <code>id(self)</code> would return.</p> <p>This is fine most of the time. And it is very helpful when you are debugging some c...
<python><debugging><logging><repr>
2025-03-23 02:42:03
4
12,224
JL Peyret
79,528,264
9,560,245
How to sanitize indentation in the lists in a generated Markdown document?
<p>In my Python application I need to render to HTML a Markdown document generated by third-party software. The document contains long lists that contain non-standard and incompatible formatting (especially, blank lines between the elements of the same bulleted list). Additionally, the software does not comply with the...
<python><markdown>
2025-03-22 23:32:45
1
596
Andrei Vukolov
79,528,196
2,196,069
How do I call a recursion method for this minimal coin change problem?
<blockquote> <p>given coins <code>[10, 5, 1]</code> cents, find the minimum number of each coin to total <code>18</code> cents. A solution is supposed to return the coin collection <code>[10, 5, 1, 1, 1]</code>.</p> </blockquote> <p>I can't get it to move past the first coin, <code>10</code>, in the collection. It's su...
<python><algorithm><recursion><coin-change>
2025-03-22 22:06:07
4
3,174
haltersweb
79,528,081
1,267,833
Installing cmdstanpy fast on Google Colab
<p>After finding out that I would need to reinstall certain Python packages in Google Colab every time I refresh a runtime, I quickly lost interest in trying to use Google Colab to run <code>stan</code> code. In particular, the last step in installing <code>cmdstanpy</code></p> <pre><code>!pip install cmdstanpy import ...
<python><google-colaboratory><stan>
2025-03-22 20:32:32
1
2,157
Taylor
79,528,064
10,321,138
How to await within a Firebase Cloud Function in Python
<p>Can Firebase functions be marked as <code>async</code>?</p> <p>For example:</p> <pre><code>async def async_function() -&gt; str: print(&quot;async function starting&quot;) await asyncio.sleep(1) print (&quot;async function finished&quot;) return &quot;finished&quot; @https_fn.on_request() async def ...
<python><firebase><google-cloud-functions>
2025-03-22 20:15:31
1
1,896
yambo
79,528,000
511,081
Resolving Cyclic Import in Custom Type System for Expression Evaluator
<p>I'm building a custom expression evaluator that handles operations like max(date_1, date_2) + 90 using type-specific classes. The initial implementation worked when all classes were in a single file, but splitting them into separate modules caused cyclic imports.</p> <p><strong>Working Single-File Version</strong></...
<python>
2025-03-22 19:28:11
0
361
amu61
79,527,893
7,741,377
Django models migration gets generated after managed set to False
<p>In my django project, I have 2 databases, and I'm trying to achieve a cross database foreign key relationship. the models Form, FormSubmission, CmsEvent are in a postgres database and the models CmsEventOrder, CmsEventPayment are in another postgres database.</p> <p>When I makemigrations, the migrations is created f...
<python><django><postgresql><multi-database>
2025-03-22 18:09:41
1
838
Abhishek AN
79,527,704
6,683,176
Why is RUN pip install from Github not working in my Dockerfile?
<p>RUN pip install git+https://${GITHUB_TOKEN}@github.com//packages.git#egg=mypackage&amp;subdirectory=mypackage is not working in my Dockerfile</p> <p>This is my Dockerfile</p> <pre><code>FROM python:3.9-slim COPY . /app WORKDIR /app RUN apt-get update &amp;&amp; apt-get install -y git &amp;&amp; rm -rf /var/lib/ap...
<python><pip><dockerfile><google-cloud-build>
2025-03-22 16:02:48
0
339
pablowilks2
79,527,670
1,261,153
How to specify actual class in Pydantic member
<p>I'd like to serialize and deserialize an object holding a polymorphic member.</p> <p>If the class was polymorphic, I would use a correct concrete type with <code>TypeAdapter</code>. The question is, how to do the same when a member is polymorphic. Here's a minimal example of what I mean:</p> <pre class="lang-py pret...
<python><pydantic>
2025-03-22 15:36:24
2
8,144
Adam Ryczkowski
79,527,532
16,383,578
Why is the continued fraction expansion of arctangent combined with half-angle formula not working with Machin-like series?
<p>Sorry for the long title. I don't know if this is more of a math problem or programming problem, but I think my math is extremely rusty and I am better at programming.</p> <p>So I have this <a href="https://en.wikipedia.org/wiki/Continued_fraction" rel="nofollow noreferrer">continued fraction</a> expansion of arctan...
<python><algorithm><math><pi>
2025-03-22 13:38:07
2
3,930
Ξένη Γήινος
79,527,471
777,384
matplotlib candlestick chart and multiple subplots
<p>I need candlestick chart in one subplot and another subplot which share Y axe with candlestick chart.<br> I have following code drawing subplots:</p> <pre><code>df = get_current_data(limit=150) df_asks, df_bids = get_order_book_data(bookStep=&quot;step0&quot;,limit=150) fig, ((ax1, ax2),(ax3,ax4)) = plt.subplots(2,2...
<python><matplotlib><candlestick-chart>
2025-03-22 12:53:53
2
360
asat
79,527,456
16,798,185
IPython installation: "error: externally-managed-environment"
<p>I need to install <a href="https://en.wikipedia.org/wiki/IPython" rel="nofollow noreferrer">IPython</a> on Mac. My current Python interpreter version is:</p> <pre class="lang-none prettyprint-override"><code>python3 --version </code></pre> <p>Output:</p> <pre class="lang-none prettyprint-override"><code>Python 3.12....
<python><pip>
2025-03-22 12:43:12
1
377
user16798185
79,527,384
2,375,154
Wagtail one-to-one object hierarchy with enum type field
<p>I have a wagtail site and I want to create an object hierarchy in a one-to-one matter, but with multiple options. Basically, I want that the database setup look slike this:</p> <pre><code>CREATE TABLE products ( id PRIMARY KEY, product_type VARCHAR(10) CHECK (product_type IN ('BOOK', 'SHIRT', ...)), prod...
<python><django><django-models><wagtail>
2025-03-22 11:44:51
1
976
Alexander Köb
79,527,375
5,674,660
Flask Integration with Mpesa Express STK results in Wrong credentials
<p>I am still testing my code under sandbox, therefore, I believe giving the consumer key and consumer secret for my application is not a security issue, because I can always delete and change. The main problem is that the STK Push results in the error: <code>'errorCode': '500.001.1001', 'errorMessage': 'Wrong credenti...
<python><flask><integration><mpesa>
2025-03-22 11:35:21
0
1,012
chibole
79,527,321
891,440
uv run fails with "failed to spawn"
<p>I have a module with a pretty regular layout, a <code>main</code> function in a <code>sacrypt</code> directory inside a <code>__init__.py</code> file. Then, pyproject.toml looks like this;</p> <pre class="lang-ini prettyprint-override"><code>[project] name = &quot;sacrypt&quot; version = &quot;0.1.0&quot; descriptio...
<python><pyproject.toml><uv>
2025-03-22 10:55:44
2
23,619
jjmerelo
79,527,090
22,213,065
Convert multiple-page PDF files to PNG quickly
<p>I have a folder containing <strong>600 PDF files</strong>, and each PDF has <strong>20 pages</strong>. I need to convert each page into a <strong>high-quality PNG</strong> as quickly as possible.</p> <p>I wrote the following script for this task:</p> <pre><code>import os import multiprocessing import fitz # PyMuPDF...
<python><pdf><parallel-processing><multiprocessing><pymupdf>
2025-03-22 07:34:01
3
781
Pubg Mobile
79,527,000
1,145,011
download large file from URL using python
<p>I have a task to download around 16K+ ( max size is of 1GB) files from given URL to location. Files are of different format like pdf, ppt, doc, docx, zip, jpg, iso etc. So had written below piece of code which</p> <ol> <li>downloads file some times and some times only 26KB file only will be downloaded.</li> <li>Also...
<python><python-requests><shutil>
2025-03-22 05:41:03
3
1,551
user166013
79,526,957
2,541,276
Error to find module debugpy when debugging Python
<p>This is my neovim config for dap. This is specifically python config. When I tried to debug a python file I get below error. JS/Java/scala and go are all working fine. Only python dap is giving error.</p> <p>This is the <a href="https://jumpshare.com/s/jKy2WY6kqAfqDgQawL7q" rel="nofollow noreferrer">screen recording...
<python><neovim>
2025-03-22 04:50:54
0
10,555
user51
79,526,834
2,315,319
For a custom Mapping class that returns self as iterator, list() returns empty. How do I fix it?
<p>The following is a simplified version of what I am trying to do (the actual implementation has a number of nuances):</p> <pre class="lang-py prettyprint-override"><code>from __future__ import annotations from collections.abc import MutableMapping class SideDict(MutableMapping, dict): &quot;&quot;&quot; The...
<python><iterator><iteration>
2025-03-22 01:39:30
2
313
fishfin
79,526,636
15,046,415
Why doesn't len(obj) go through __getattribute__, and how can I override this behavior?
<p>I've noticed that calling <code>obj.__len__()</code> explicitly goes through <code>obj.__getattribute__(&quot;__len__&quot;)</code>, but calling <code>len(obj)</code> does not. A quick search suggests that built - in functions like <code>len()</code>, <code>dir()</code>, and <code>repr()</code> optimize their calls ...
<python>
2025-03-21 21:58:24
0
454
Ziv Sion
79,526,624
4,696,802
Is Python supposed to be this slow when importing?
<p>My understanding is that imports can be slow when you import the first time, and then they should be cached for subsequent imports. However that's not what I'm experiencing. And I really don't think I'm doing something wrong like having the wrong settings because I remember this same thing happening when I tried usi...
<python><import>
2025-03-21 21:44:24
1
16,228
Zebrafish
79,526,621
889,053
I am unable to load ed25519 private key in PEM format in Python
<p>I ripped code straight off of the jwt documentation website as I try to implement JWT. Their example works fine. However, when I try it with an ssh-keygen file, in PKCS8 format, it doesn't work:</p> <pre class="lang-py prettyprint-override"><code>import jwt private_key = &quot;-----BEGIN PRIVATE KEY-----\nMC4CAQAwBQ...
<python><jwt>
2025-03-21 21:40:55
0
5,751
Christian Bongiorno
79,526,487
835,073
How to create global variables dynamically from base class defined in a separate file?
<p>My real scenario needs to create global variables dynamically from within a function defined in a library so it can be reused for many projects. The function can be either a method in a base class or a global function.</p> <p>For the sake of simplicity, consider the following a trivial example. I know the global var...
<python>
2025-03-21 19:55:32
1
880
D G
79,526,468
2,396,539
Why we say dequeue in python is threadsafe when GIL already restricts running one thread at a time
<p>From what I have been reading Python has GIL that ensures only one thread can run the python code. So I am slightly confused when we say collections.dequeue is thread-safe. If only one thread is run at a time wouldn't objects be in a consistent state already?</p> <p>It would be great if someone can give an example o...
<python><multithreading><gil>
2025-03-21 19:42:34
2
69,441
Aniket Thakur
79,526,465
3,763,493
Is there a way to remove stack traces in python log handlers using filters or some other mechanism when calling Logger.exception()?
<p>I know the subject sounds counter-intuitive but bear with me.</p> <p>My goal is to have two rotating file log handlers, mostly for logger.exception() calls, one that includes stack traces and one that doesn't. I find that error conditions can sometimes cause the logs to fill with stack traces, making them difficult ...
<python><python-logging>
2025-03-21 19:40:46
2
544
DaveB
79,526,348
5,053,483
matplotlib - Unable to update plot with button widget
<p>The code below draws a button and an axes object in which it's meant to print out the number of times the button has been pressed. However, it never updates the axes with the number of presses.</p> <pre><code>from matplotlib import pyplot as plt from matplotlib.widgets import Button fig, ax = plt.subplots(figsize=(...
<python><matplotlib><matplotlib-widget>
2025-03-21 18:34:26
1
482
BGreen
79,526,325
10,658,339
How to identify duplicate datetime entries from a .csv file where pandas does not consider time down to the second?
<p>I am working with a pandas DataFrame where one of the columns contains datetime values, and I need to identify duplicate entries in the &quot;Data&quot; column. The datetime values include both the date and the exact time (hours, minutes, and seconds). However, I noticed an issue when I read the data from a .csv fil...
<python><pandas><date><datetime>
2025-03-21 18:21:56
1
527
JCV
79,526,231
10,034,073
How to omit exc_info from logs when using coloredlogs in Python?
<p>See <a href="https://stackoverflow.com/questions/6177520/python-logging-exc-info-only-for-file-handler">this question</a> about sending <code>exc_info</code> to a log file but not to the console using Python's <code>logging</code> module.</p> <p>I want the exact same behavior, except that I'm using <a href="https://...
<python><logging><python-logging>
2025-03-21 17:38:40
0
444
kviLL
79,526,166
3,245,254
In Folium can I specify multiple timestamps for a given feature
<p>I have a set of geometric features that I want to animate (change colors) using Folium.</p> <p>I know how to do it (see MWE below), but it seems I need to copy the feature data for each time, only changing the properties (time and color). While this works, it has lots of redundant data, resulting in a large HTML fil...
<python><animation><timestamp><folium>
2025-03-21 17:12:20
0
645
Didac Busquets
79,526,103
3,621,143
Converting RSA generated "modulus" (n) to base64 string
<p>I have a &quot;modulus&quot; as a long string of numbers that is obtained from doing the following:</p> <pre><code>private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048) modulus = private_key.private_numbers().public_numbers.n </code></pre> <p>which gives me this (modulus = )</p> <pre><code>264...
<python><openssl><cryptography>
2025-03-21 16:42:00
2
1,175
jewettg
79,526,074
2,487,835
Ollama model keep in memory and prevent unloading between requests (keep_alive?)
<p>No matter what I do from the terminal or in code, the agent requests to Ollama models take 15–25 seconds each time on my local M2 MacBook Pro.</p> <p>I am pretty sure this is not a hardware issue because the model is lightning fast when used from the terminal.</p> <p>I am using Python's module to load <code>gemma3.4...
<python><large-language-model><ollama>
2025-03-21 16:29:37
1
3,020
Lex Podgorny
79,525,834
9,962,007
How to compile FlashAttention wheels faster?
<p>Currently the compilation of the Python wheel for the FlashAttention 2 (<code>Dao-AILab/flash-attention</code>) Python package takes several <em>hours</em>, as reported by multiple users on GitHub (see e.g. <a href="https://github.com/Dao-AILab/flash-attention/issues/1038" rel="nofollow noreferrer">this issue</a>). ...
<python><build><python-wheel><flash-attn>
2025-03-21 15:00:54
1
7,211
mirekphd
79,525,541
11,863,823
Nullable ints and pandera unit testing
<p>First of all, I'm using <code>pandera==0.23.1</code> on Python 3.12.9.</p> <p>I have been following the examples of the <code>pandera</code> doc, in particular the ones from the <a href="https://pandera.readthedocs.io/en/stable/data_synthesis_strategies.html" rel="nofollow noreferrer">Data Synthesis Strategies</a> s...
<python><pandas><unit-testing><pandera>
2025-03-21 13:03:19
0
628
globglogabgalab
79,525,493
9,381,985
vscode python debugger hangs for ever
<p>Recently my VSCode is out of work. When I choose <code>Python Debugger: Debug Python File</code> from the upper-right drop-down menu, the TERMINAL panel will show the command line of starting Python debugger like:</p> <p><code>cd /Users/me/Projects/kiwi ; /usr/bin/env /Users/me/miniconda3/bin/python /Users/me/.vscod...
<python><visual-studio-code><debugpy>
2025-03-21 12:48:58
1
575
Cuteufo
79,525,445
4,473,615
Sub Folders of S3 bucket - Bucket name must match the regex "^[a-zA-Z0-9.\-_]
<p>I have below code to get the list of objects in the bucket, but it does not work for the sub folders of the S3.</p> <pre><code>import boto3 bucket_from = &quot;BucketSource&quot; s3 = boto3.resource('s3') src = s3.Bucket(bucket_from) for archive in src.objects.all(): print(archive.key) </code></pre> <p>While u...
<python><amazon-web-services><amazon-s3><boto3>
2025-03-21 12:33:01
2
5,241
Jim Macaulay
79,525,439
5,457,202
Changes to table with python-docx not persistent in Python 3.11
<p>I'm using python-docx (v1.1.2) and Python 3.11.3 to work on a tool to fix a bunch of Word documents automatically. I've been able to update fonts, titles, texts, headers and footers and tables (their borders).</p> <p>However, some tables, and I haven't found the pattern of why this happens, are not updated. This is ...
<python><xml><ms-word><python-docx>
2025-03-21 12:30:52
1
436
J. Maria
79,525,409
1,194,864
Create a zip file that contains only files and not a folder/directory
<p>I would like to create a function that lists the items of a directory and adds just the files in a <code>zip</code> folder (without having any folder inside the <code>zip</code>). So my directory looks like as follows:</p> <pre><code>student_path student_1: file1.txt file2.txt file.html student_...
<python><path><directory><zip>
2025-03-21 12:17:42
1
5,452
Jose Ramon
79,525,357
1,548,830
Deadlock in Multiprocessing Queue
<p>I am developing a program to simulate a P2P network using the <code>multiprocessing</code> package. Specifically, I have created a <code>Node</code> class that inherits from <code>multiprocessing.Process</code> and contains all the basic functionalities, while the <code>SpecializedNode</code> class implements specif...
<python><multiprocessing><queue>
2025-03-21 11:53:32
1
529
Mattia Campana
79,525,356
11,850,171
ValueError: could not convert string to float: '76.4984018.904527.000':geopandas
<p>I am working with geospatial data and attempting to apply machine learning for prediction. Here’s how I read my data:</p> <pre><code>import geopandas as gpd import fiona from fiona.drvsupport import supported_drivers supported_drivers['CSV'] = 'csv' all_data = gpd.read_file('book3.csv')[['Name','description', 'geome...
<python><pandas><dataframe><geopandas>
2025-03-21 11:51:48
0
321
TinaTz
79,525,238
4,537,160
Have different Black settings for submodules in main repo
<p>I'm cloning a repo which contains 2 submodules cloned in the <code>subs/</code> folder, so the structure is like:</p> <pre class="lang-none prettyprint-override"><code>main_repo/ -- subs/ ---- sub_01 ---- sub_02 </code></pre> <p>I would want each of them to have different settings, for example line length for the Bl...
<python><visual-studio-code>
2025-03-21 10:51:31
1
1,630
Carlo
79,525,092
6,378,557
Using Python's match/case statement to check for a list of a given type
<p>I'm trying to use a match/case instruction to process things differently based on type:</p> <p>Code looks like:</p> <pre><code>def checkArg(arg: str | list[str]) -&gt; str: match arg: case str(): return 'str' case list(): return 'list(str)' case _: retu...
<python><structural-pattern-matching>
2025-03-21 09:52:40
1
9,122
xenoid
79,525,083
10,727,331
How to remove padding coming from tick labels from other subplots
<p>I have created a set of heatmaps in a 6x3 subplot grid.</p> <p><a href="https://i.sstatic.net/AGrElD8J.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/AGrElD8J.png" alt="Heatmaps status quo" /></a></p> <p>As you can see, I added a shared color bar in the last row that spans over all columns (I used a ...
<python><matplotlib><seaborn>
2025-03-21 09:49:15
3
392
Mayor Mayer
79,525,077
11,803,687
FastAPI/Starlette's Request object is empty when used in a normal function
<p>When I use <code>request</code> inside a FastAPI route, the <code>request</code> is filled with the proper headers, such as:</p> <pre><code>request.headers.get('X-Forwarded-For') </code></pre> <p>However, when I use the <code>request</code> object inside a function, which isn't a route, all the values are empty. I g...
<python><fastapi><starlette>
2025-03-21 09:48:34
1
1,649
c8999c 3f964f64
79,524,765
2,148,718
Set initial value of a Pydantic 2 field using validator
<p>Say I have the following Pydantic 2.10.6 model, where <code>x</code> is dynamically calculated from another field, <code>y</code>:</p> <pre class="lang-py prettyprint-override"><code>from pydantic import BaseModel, Field, field_validator, ValidationInfo class Foo(BaseModel): x: int = Field(init=False) y: in...
<python><pydantic><pydantic-v2>
2025-03-21 07:17:13
1
20,337
Migwell
79,524,654
271,789
SQLAlchemy Mapped field not correctly type-checked
<p>With this code:</p> <pre class="lang-py prettyprint-override"><code>from typing import Protocol from sqlalchemy import Integer from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column class SpamProt(Protocol): id: int class Base(DeclarativeBase): pass class SpamModel(Base): id: Mapped[int] ...
<python><sqlalchemy><python-typing><mypy>
2025-03-21 06:06:36
1
2,066
zefciu
79,524,602
2,700,041
How to efficiently apply batched edge/node modifications across multiple graph copies using precomputed data?
<p>I'm working on a task where I need to apply custom modifications to many independent copies of the same base graph. For each instance, I want to:</p> <ul> <li>Start from the same base graph</li> <li>Remove one or more edges</li> <li>Insert intermediate nodes</li> <li>Add new edges with custom weights</li> </ul> <p>I...
<python><numpy><graph><networkx>
2025-03-21 05:22:11
1
1,427
hanugm
79,524,581
10,191,971
What is the good practice to add many similar methods to a class in Python?
<p>Let's say I have a class like this.</p> <pre><code>from scipy import interpolate import numpy as np class Bar: def __init__(self,data): self.data = data def mean(self): return self.data.mean(axis=0) def sd(self): return self.data.std(axis=0) bar = Bar(np.random.rand(10...
<python><class><oop><decorator>
2025-03-21 05:05:17
2
1,622
C.K.
79,524,515
1,491,229
Huge time difference when reading a file inside class
<p>Any suggestions where this huge time difference results from when reading the same large text file by the same loop from inside a class in Python.</p> <pre><code>import timeit fn = &quot;some-large-file.txt&quot; pos = 2434735976 class TestCase: def __init__(self, filename): self.filename = filename ...
<python><text-files><readline><file-read><timeit>
2025-03-21 03:48:07
3
709
user1491229
79,524,210
13,282,329
How to correctly read and process Kinesis Video Streams fragments?
<p>I am working on processing real-time audio from Amazon Connect by retrieving fragments from Kinesis Video Streams and saving them to S3. However, the MKV file I export to S3 is not playable and seems to be corrupted.</p> <pre><code>import boto3 import os s3_bucket = 'BUCKET_NAME' def lambda_handler(event, context):...
<python><amazon-web-services><amazon-kinesis><amazon-connect><amazon-kinesis-video-streams>
2025-03-20 22:34:57
0
703
Marcellin Khoury
79,524,167
5,956,725
How to Align Row and Column Labels of Plotly Subplot Grid in Python Dash Application
<p>I'm trying to create a Dash application that displays a grid of subplots to visualize the pairwise comparison of the columns of a dataframe. To the top and left of each grid row and column will be the corresponding variables. The variable names can be quite long though, so it's easy to misalign them. I've tried, sta...
<python><plotly><visualization><plotly-dash>
2025-03-20 22:02:10
0
332
The_Questioner
79,524,154
5,561,649
How to achieve a dynamic, non-square drawing area in matplotlib 3D plots?
<p>I've noticed, from what I can tell, that matplotlib 3D plots are restricted to a square drawing area. For example, when plotting a surface and zooming in, instead of the surface filling the entire window, it remains confined to a square region fitted inside the window, with blank borders: <a href="https://i.sstatic....
<python><matplotlib>
2025-03-20 21:54:28
1
550
LoneCodeRanger
79,524,079
3,482,266
What type of dependency management does `pip` do?
<p>In <a href="https://python-programs.com/differences-conda-vs-pip/" rel="nofollow noreferrer">this link</a>, one can read:</p> <blockquote> <p>Pip installs dependencies using a recursive serial loop. Pip does not check to see if all of the dependencies of all packages are met at the same time.</p> <p>If the packages ...
<python><pip>
2025-03-20 21:07:35
0
1,608
An old man in the sea.
79,524,069
9,464,295
Urwid ListBox size to space available instead of constant
<p>My program is split into 4 sections. One section is a constant-size section of various widgets, and the other 3 are list boxes.</p> <p><a href="https://i.sstatic.net/v8McH03o.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/v8McH03o.png" alt="Minimal example" /></a></p> <p>If I set <code>rows</code> to...
<python><layout><urwid>
2025-03-20 20:59:04
0
775
Doot
79,524,057
4,913,660
Replace values in series with first regex group if found, if not leave nan
<p>Say I have a dataframe such as</p> <pre><code>df = pd.DataFrame(data = {'col1': [1,np.nan, '&gt;3', 'NA'], 'col2':[&quot;3.&quot;,&quot;&lt;5.0&quot;,np.nan, 'NA']}) </code></pre> <pre><code>out: col1 col2 0 1 3. 1 NaN &lt;5.0 2 &gt;3 NaN 3 NA NA </code></pre> <p>What I would like is to strip stuf...
<python><pandas><regex>
2025-03-20 20:53:06
4
414
user37292
79,523,961
1,892,584
How does one get pypi package metadata for an uninstalled package - preferably in JSON?
<p><code>pip show</code> doesn't work for packages that aren't installed and does not output in JSON. Is there a way to make it do so?</p> <pre><code>pip show django WARNING: Package(s) not found: django </code></pre> <p>Is there any way of getting package metadata from the command line? Besides writing a scraper f...
<python><pip><pypi>
2025-03-20 19:51:51
1
1,947
Att Righ