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,615,858
11,244,938
Async changing of global variables safe ? (Python)
<p>I've been researching when I work in ASGI environments (single-threaded) whether it is safe to mutate singletons or global variables. I thought initially that it would be safe, but AI tells me it's not safe and I'm having a tough time believing it because I cannot reproduce it. Look at this code here.</p> <pre><code...
<python><asynchronous><concurrency><thread-safety><python-asyncio>
2025-05-10 19:43:09
2
301
Božidar Vulićević
79,615,849
20,895,654
Python pickled object equality guarantees
<p>I am wondering if, and if so which guarantees there are about the pickle module when using pickle.dump[s].</p> <p>Specifically for my problem I am pickling list[T] where T can be <code>bool</code>, <code>int</code>, <code>decimal</code>, <code>time</code>, <code>date</code>, <code>datetime</code>, <code>timedelta</c...
<python><pickle><equality>
2025-05-10 19:27:02
1
346
JoniKauf
79,615,828
14,425,501
Why shap's explainer.model.predict() and model.predict don't match?
<p>I have a machine learning model and I calculated SHAP on it using following code:</p> <pre><code>import shap background = shap.kmeans(X_dev, k=100) explainer = shap.TreeExplainer(model, feature_perturbation=&quot;interventional&quot;, model_output='probability', data=background.data) shap_values = explainer.shap_v...
<python><machine-learning><xgboost><shap>
2025-05-10 19:07:02
1
1,933
Adarsh Wase
79,615,747
3,163,618
Is polars bracket indexing to select a column discouraged?
<p>Some stuff online like <a href="https://stackoverflow.com/questions/74841242/selecting-with-indexing-is-an-anti-pattern-in-polars-how-to-parse-and-transform">Selecting with Indexing is an anti-pattern in Polars: How to parse and transform (select/filter?) a CSV that seems to require so?</a> suggests using indexing l...
<python><select><indexing><python-polars>
2025-05-10 17:31:12
1
11,524
qwr
79,615,662
5,958,323
How to replace *all* occurrences of a string in Python, and why `str.replace` misses consecutive overlapping matches?
<p>I want to replace all patterns <code>0</code> in a string by <code>00</code> in Python. For example, turning:</p> <p><code>'28 5A 31 34 0 0 0 F0'</code></p> <p>into</p> <p><code>'28 5A 31 34 00 00 00 F0'</code>.</p> <p>I tried with <code>str.replace()</code>, but for some reason it misses some &quot;overlapping&quot...
<python><string><replace>
2025-05-10 15:46:02
1
9,379
Zorglub29
79,615,493
7,921,684
InfluxDB 2.0 Client Stops Writing After Few Hours (Notifications Still Received, Container Restart Fixes Temporarily)
<p>I’m using InfluxDB 2.0 in Docker along with a custom notification receiver (influx-adapter-api container) that writes to InfluxDB using the Python influxdb-client in synchronous mode.</p> <ul> <li>The setup works fine for a few hours, but then:</li> <li>Notifications are still received correctly</li> <li>Writes to I...
<python><docker><influxdb><influxdb-python>
2025-05-10 12:53:38
1
586
Gray
79,615,255
6,067,741
Azure python sdk resourcegraph no skip_token
<p>no matter what i try skip_token is None. my code:</p> <pre><code>from azure.identity import DefaultAzureCredential from azure.mgmt.resourcegraph import ResourceGraphClient from azure.mgmt.resourcegraph.models import QueryRequest, QueryRequestOptions credential = DefaultAzureCredential() client = ResourceGraphClient...
<python><azure><pagination><azure-resource-graph>
2025-05-10 07:18:10
1
71,429
4c74356b41
79,615,098
3,810,748
Is there simpler way to get all nested text inside of ElementTree?
<p>I am currently using the <a href="https://docs.python.org/3/library/xml.etree.elementtree.html" rel="nofollow noreferrer"><code>xml.etree</code></a> Python library to parse HTML.</p> <p>After finding a target DOM element, I am attempting to extract its text. Unfortunately, it seems that the <code>.text</code> attrib...
<python><xpath>
2025-05-10 02:57:34
2
6,155
AlanSTACK
79,615,081
1,686,522
Disable FreeCAD recomputes from the Python console (not the mouse)
<p>In FreeCAD, if I right-mouse-click on my document in the model tree, I have the option to &quot;Skip recomputes&quot;. This action does not generate Python code in the console. How can I do this programmatically? I'd like to turn off recomputes while my script is running but then leave them enabled after the script ...
<python><freecad>
2025-05-10 02:20:40
0
473
durette
79,614,986
1,126,944
Is "type" a keyword
<p>When I read the Python C API Reference Manual, it points to below from <a href="https://docs.python.org/3/c-api/type.html#c.PyType_Type" rel="nofollow noreferrer">https://docs.python.org/3/c-api/type.html#c.PyType_Type</a></p> <blockquote> <p>type PyTypeObject</p> <p>Part of the Limited API (as an opaque struct).</p...
<python><c>
2025-05-09 23:26:06
2
1,330
IcyBrk
79,614,976
6,141,238
Does file_obj.close() nicely close file objects in other modules that have been set equal to file_obj?
<p>I have a file <code>main_file.py</code> that creates a global variable <code>file_obj</code> by opening a text file and imports a module <code>imported_module.py</code> which has functions that write to this file and therefore also has a global variable <code>file_obj</code> which I set equal to <code>file_obj</code...
<python><module><global-variables><text-files>
2025-05-09 23:15:49
1
427
SapereAude
79,614,935
4,704,065
Comapre two DF with different lengths based on same column name
<p>I have 2 Dataframe of different lengths (number of rows and columns are different )but having some same column names I want to filter out rows of DF1 where column value of Dataframe 1 is present in column value of Dataframe 2</p> <p><strong>eg: DF1:</strong></p> <p><a href="https://i.sstatic.net/gYjJNgwI.png" rel="n...
<python><pandas><dataframe>
2025-05-09 22:14:27
2
321
Kapil
79,614,850
20,591,261
How to replace string values in a strict way in Polars?
<p>I'm working with a Polars DataFrame that contains a column with string values. I aim to replace specific values in this column using the <code>str.replace_many()</code> method.</p> <p>My dataframe:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl df = (pl.DataFrame({&quot;Products&quot;: [&quo...
<python><python-polars>
2025-05-09 20:48:08
1
1,195
Simon
79,614,691
9,008,261
Why are the subplots in the subfigures getting smaller?
<p>I am using gridspec within a subfigure. For some reason matshow plots are getting smaller and smaller.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt mask = np.array([ [ 1, 0, 1, 0, 1], [ 1, 1, 1, 1, 1], [ 0, 0, 0, 0, 0], [ 1, 1, 1, 1, 1], [ 1, 1, 1, 1, 0] ...
<python><matplotlib>
2025-05-09 18:30:10
1
305
Todd Sierens
79,614,585
1,015,761
Python Asyncio: How to ensure async jobs are executed sequentially from requests
<p>I have a Django endpoint which needs to do some work when called (writing to a file), however, I would like the work to be done synchronised with any other calls to the same endpoint at the time. Such that, if the endpoint is called 10 times within the same moment, it will write to the file 10 times but one at a tim...
<python><python-asyncio>
2025-05-09 17:10:18
1
3,876
Goulash
79,614,495
1,547,004
How to share configuration for custom PyPI indexes?
<p>Is there a way to include configuration with a python package source so that it is able to properly resolve dependencies from private registries using a standard build/install chain?</p> <p>For example, I have a python package with dependencies on several python packages that are each published to different private ...
<python><pip><gitlab><pypi>
2025-05-09 16:02:23
1
37,968
Brendan Abel
79,614,459
8,521,346
Install Latest Compatible Package Pip
<p>Say I have a client on <code>Django==4.0.0</code> and I run <code>pip install djangorestframework</code> how do I prevent Pip from upgrading django to v5 along with installing drf?</p> <p>I know I can manually specify the version number for the package, but is there a built in way to just install the latest version ...
<python><pip>
2025-05-09 15:42:15
1
2,198
Bigbob556677
79,614,419
382,784
How do you use certificates and certificate chain with Flask SocketIO?
<p>I need to use SocketIO from flask_socketio with certificate, secret key, and certification chain. How do I do that? Here is my code so far:</p> <pre class="lang-py prettyprint-override"><code>from gevent import monkey monkey.patch_all() import ssl from engineio.async_drivers import gevent # noqa: I201, F401 from ...
<python><flask><socket.io><certificate>
2025-05-09 15:14:31
1
2,997
wedesoft
79,614,228
5,938,276
Comparison of Frequencies array to FFT indexes
<p>I have 10 channels with each channel corresponding to a frequency:</p> <pre><code>Ch Freq (Khz) 01 155.00 02 165.00 03 175.00 04 185.00 05 195.00 06 205.00 07 215.00 08 225.00 09 235.00 10 245.00 </code></pre> <p>Each channel is actually 10 Khz wide, so anything between 150-160 Khz is on channel 01, 160-1...
<python><arrays>
2025-05-09 13:26:26
1
2,456
Al Grant
79,614,223
2,954,288
Deviation between `/usr/bin/time` command and Python self measurement of running time
<p>The trivial Python script, t.py</p> <pre class="lang-py prettyprint-override"><code>import psutil, time startSecs = psutil.Process().create_time() print(&quot;startup took %.3fs&quot; % (time.time() - startSecs)) </code></pre> <p>when run as <code>/usr/bin/time -f 'wall=%e' python3 t.py</code>, results in the foll...
<python><psutil>
2025-05-09 13:23:28
1
5,257
Harald
79,614,175
3,888,116
Open Word document as "Read Only" with API doesn't work
<p>I'm using Python to open a Word file using the win32 API. When &quot;RO=False&quot;, it opens the Word file and the user can edit it. When the user opens the file using Word's built-in feature &quot;Open as Read-Only&quot;, the titlebar indicates &quot;Read-Only&quot; and the ribbon's buttons are grayed. The behavio...
<python><ms-word><pywin32>
2025-05-09 13:01:53
0
753
DaveG
79,614,127
2,336,887
PySide6.QtWidgets.QWidget crashes on super().__init__()
<p>The following code crashes and I don't understand why.</p> <pre class="lang-python prettyprint-override"><code>from PySide6 import QtWidgets class MockParent(QtWidgets.QWidget): def __init__(self, /): try: super().__init__() except Exception as e: print(e) if __name__ ==...
<python><pyside6>
2025-05-09 12:37:22
0
1,181
BaldDude
79,614,094
12,439,683
How to check if an object is a method_descriptor
<p>Given an object, how can I make a check if it is a <code>method_descriptor</code>?</p> <pre class="lang-py prettyprint-override"><code>is_method_descriptor = isinstance(obj, method_descriptor) # does not work </code></pre> <p>The problem: <code>method_descriptor</code> is a builtin but not an accessible variable. I ...
<python><python-descriptors><python-builtins>
2025-05-09 12:17:46
1
5,101
Daraan
79,614,070
4,240,413
Why is the upload of files to GCP Vertex AI RAG corpora so slow?
<p>I am experimenting with RAG on GCP/Vertex AI, and tried to create some simple example.</p> <p>Here's what I came up with, creating small dummy files locally and then uploading them one by one to a newly-minted RAG corpus:</p> <pre class="lang-py prettyprint-override"><code>import vertexai from vertexai import rag fr...
<python><google-cloud-vertex-ai><rag>
2025-05-09 11:58:20
0
6,039
Davide Fiocco
79,614,033
1,077,695
What explains pattern matching in Python not matching for 0.0, but matching for float()?
<p>I would like to understand how pattern matching works in Python.</p> <p>I know that I can match a value like so:</p> <pre><code>&gt;&gt;&gt; t = 12.0 &gt;&gt;&gt; match t: ... case 13.0: ... print(&quot;13&quot;) ... case 12.0: ... print(&quot;12&quot;) ... 12 </code></pre> <p>But I notice that when I us...
<python><structural-pattern-matching>
2025-05-09 11:27:59
1
2,680
mvallebr
79,613,929
416,983
Steal the GIL after fork()'ing
<p>I'm writing a C++ python module, the module needs to fork() a child process and call some python functions in the child process. The child process has only one thread.</p> <p>I cannot acquire the GIL before calling fork() because doing so will result in a deadlock.</p> <p>If the GIL isn't acquired, after fork(), the...
<python><fork><gil>
2025-05-09 10:28:24
0
1,106
user416983
79,613,844
1,413,856
TKInter widget not appearing on form
<p>I’m having trouble working out why a widget doesn’t appear on my tkinter form.</p> <p>Here is what I’m doint:</p> <ul> <li>Create a form</li> <li>Create a widget (a label) with the form as the master.</li> <li>Create a <code>Notebook</code> and <code>Frame</code> and add them to the form.</li> <li>Create additional ...
<python><tkinter>
2025-05-09 09:32:25
1
16,921
Manngo
79,613,763
3,087,409
Access variables available in plotly's default hovertemplate
<p>I'm trying to change the hovertemplate on a stacked bar chart with plotly, but I'm struggling to access the same variables that plotly does by default. Here's the MWE I'm working with</p> <pre><code>import plotly.express as px import pandas as pd df = pd.DataFrame({ 'value': [3,4,5,6,7,8], 'category': ['Cat...
<python><plotly>
2025-05-09 08:35:33
0
2,811
thosphor
79,613,514
754,136
Progress bar with multiple stats printed in new lines
<pre class="lang-py prettyprint-override"><code>import numpy as np from tqdm import tqdm import time tot_steps = 100 pbar = tqdm(total=tot_steps) for i in range(tot_steps): time.sleep(0.1) x, y, z, k = np.random.rand(4) pbar.update(1) pbar.set_description( f&quot;error[{x:.3f}] _ &quot; f&quot;sa...
<python><tqdm>
2025-05-09 05:11:08
2
5,474
Simon
79,613,461
2,085,438
How to make sure the browser can interpret a url through dcc.Location
<p>I am passing a string to the <code>pathname</code> property of a <code>dcc.Location</code> component in a callback function of my dash app.</p> <p>The string is structured like <code>path?query1=test</code>.</p> <p>When it actually runs, the <code>?</code> gets url encoded automatically and the browser does not inte...
<python><url><plotly-dash>
2025-05-09 03:52:30
1
2,663
Chapo
79,613,434
1,023,928
Polars pl.read_csv_batched -> batch_size is not respected at all
<p>Using the <code>pl.read_csv_batched()</code> with <code>batch_size=n</code>, batches are read without any regard to <code>batch_size</code> whatsoever. I use polars version 1.29.0.</p> <p>What's up with that. Can I use polars to import a large csv file without going the manual route? Why does <code>batch_size</code>...
<python><python-polars>
2025-05-09 02:59:50
1
7,316
Matt
79,613,425
3,026,965
Get "Media created" timestamp with python for .mp4 and .m4a video, audio files (no EXIF)
<p>Trying to get &quot;<strong>Media created</strong>&quot; timestamp and insert as the &quot;<strong>Last modified date</strong>&quot; with python for .mp4 and .m4a video, audio files (no EXIF). The &quot;Media created&quot; timestamp shows up and correctly in Windows with right click file inspection, but I can not ge...
<python><windows><mp4><datecreated>
2025-05-09 02:48:38
2
727
user3026965
79,613,159
1,394,590
Can a decorator be used to define type hints for the decorated function?
<p>Given a decorator that injects an argument into the decorated function like the following dumb example:</p> <pre class="lang-py prettyprint-override"><code>from typing import Callable import time def pass_timestamp(fn: Callable[[float], None]) -&gt; Callable[[], None]: def wrapper(): fn(time.time()) r...
<python><python-typing>
2025-05-08 21:01:19
1
15,387
bgusach
79,613,135
9,250,059
Can't connect to PostgreSQL, from Google Cloud Run to Google Cloud SQL
<p>Sup?</p> <p>I want to connect to my <strong>PostgreSQL</strong> database on <strong>Cloud SQL</strong> from <strong>Cloud Run</strong>, and whatever I do, I get errors. The most annoying one is the <strong>&quot;connection refused&quot;</strong> error. I have tried anything you can imagine: <strong>&quot;SQL client ...
<python><postgresql><sqlalchemy><google-cloud-sql><google-cloud-run>
2025-05-08 20:35:53
1
470
Armin Fisher
79,613,107
7,124,155
PySpark UDF mapping is returning empty columns
<p>Given a dataframe, I want to apply a mapping with UDF but getting empty columns.</p> <pre><code>data = [(1, 3), (2, 3), (3, 5), (4, 10), (5, 20)] df = spark.createDataFrame(data, [&quot;int_1&quot;, &quot;int_2&quot;]) df.show() +-----+-----+ |int_1|int_2| +-----+-----+ | 1| 3| | 2| 3| | 3| ...
<python><apache-spark><pyspark><databricks>
2025-05-08 20:15:56
1
1,329
Chuck
79,612,995
700,070
Parse specific key from JSON, and extract if field matches
<p>I am trying to parse this JSON file with the following declaration:</p> <pre class="lang-json prettyprint-override"><code>{ &quot;results&quot;: [ { &quot;vulnerabilities&quot;: [ { &quot;status&quot;: &quot;fixed in 1.3.1&quot;, &quot;s...
<python><json>
2025-05-08 18:52:19
3
2,680
Jshee
79,612,836
3,333,319
Pass Literal[...] where Type[T] is expected
<p>I have a Python function that accepts as parameters some raw <code>bytes</code> data (representing a JSON object) and a class, and it returns an instance of the class populated with values from the raw data. The function signature is as follows.</p> <pre class="lang-py prettyprint-override"><code>from typing import ...
<python><python-typing><pyright>
2025-05-08 16:46:56
0
973
Sirion
79,612,757
5,102,811
Scipy's WrappedCauchy function wrong?
<p>I'd like someone to check my understanding on the wrapped cauchy function in Scipy... From Wikipedia &quot;a wrapped Cauchy distribution is a wrapped probability distribution that results from the &quot;wrapping&quot; of the Cauchy distribution around the unit circle.&quot; It's similar to the Von Mises distribution...
<python><scipy><statistics>
2025-05-08 15:44:48
1
405
RedM
79,612,729
6,133,833
Training and validation losses do not reduce when fine-tuning ViTPose from huggingface
<p>I am trying to fine-tune a transformer/encoder based pose estimation model available here at: <a href="https://huggingface.co/docs/transformers/en/model_doc/vitpose" rel="nofollow noreferrer">https://huggingface.co/docs/transformers/en/model_doc/vitpose</a></p> <p>When passing &quot;labels&quot; attribute to the for...
<python><machine-learning><pytorch><huggingface-transformers><transformer-model>
2025-05-08 15:28:54
0
341
Soham Bhaumik
79,612,706
3,163,618
How do I keep both columns as the result of a Polars join with left_on and right_on?
<p>How do I keep both columns as the result of a Polars join with <code>left_on</code> and <code>right_on</code>, like in SQL?</p> <pre><code>df1 = pl.DataFrame({&quot;a&quot;: [&quot;x&quot;,&quot;y&quot;,&quot;z&quot;], &quot;lk&quot;: [1,2,3]}) df2 = pl.DataFrame({&quot;b&quot;: [&quot;x&quot;,&quot;y&quot;,&quot;z&...
<python><join><python-polars>
2025-05-08 15:19:13
1
11,524
qwr
79,612,705
662,285
Error: Operation returned an invalid status 'Bad Request' on client.complete
<p>I am using below code to get data from &quot;Mistral-Nemo&quot; model hosted as SaaS in Azure AI Foundry. It gives me below error:</p> <pre><code>Error: Operation returned an invalid status 'Bad Request' Traceback (most recent call last): File &quot;c:\Users\guptswapmax\TestFalcon\TestFalcon.py&quot;, line 32, in ...
<python><azure><model><azure-machine-learning-service><azure-ai-foundry>
2025-05-08 15:18:26
1
4,564
Bokambo
79,612,668
3,163,618
Concatenate two Polars string columns or a fixed string to a column
<p>How do I concatenate two string columns horizontally or append a fixed string to a column?</p>
<python><python-polars><string-concatenation>
2025-05-08 14:55:14
1
11,524
qwr
79,612,625
1,391,441
Underlining fails in matplotlib
<p>My <code>matplotlib.__version__</code> is <code>3.10.1</code>. I'm trying to underline some text and can not get it to work. As far as I can tell, Latex is installed and accessible in my system:</p> <pre><code>import subprocess result = subprocess.run( [&quot;pdflatex&quot;, &quot;--version&quot;], check=Tr...
<python><matplotlib>
2025-05-08 14:33:15
1
42,941
Gabriel
79,612,553
11,770,390
avoid building .egg-info files in read-only docker mount for local dependencies (uv sync)
<p>I'm trying to use uv sync from within docker with this command:</p> <p><em>Dockerfile</em></p> <pre><code>RUN --mount=type=cache,target=/root/.cache/uv \ --mount=type=bind,source=uv.lock,target=uv.lock \ --mount=type=bind,source=pyproject.toml,target=pyproject.toml \ --mount=type=bind,source=packages,tar...
<python><docker><uv>
2025-05-08 13:56:47
0
5,344
glades
79,612,454
167,745
VS Code debugger launch intermittently stops working and then does work again (Python debug)
<p>I have a Python script which works on the command line. It also does work via VS Code's debug launch ... sometimes.</p> <p>At first I thought it was to do with a bad <code>launch.json</code>, in particular related to how I was inject Env variables using</p> <pre><code>//&quot;envFile&quot;: &quot;${workspaceFolder}/...
<python><visual-studio-code><environment-variables><vscode-debugger>
2025-05-08 13:08:31
0
18,462
Stewart
79,612,414
8,365,731
Shared memory leaks in Python 3
<p>I experience problems with SharedMemory() in Python 3.12.0, it is not properly released. I use below context manager to handle share memory segments:</p> <pre><code>@contextmanager def managed_shm(name=None, size=0, create=False): shm = None try: shm = SharedMemory(create=create, name=name, size=siz...
<python><shared-memory>
2025-05-08 12:49:27
1
563
Jacek BΕ‚ocki
79,612,338
2,494,865
How to build an exact MPFR number using gmpy2?
<p>I believe that the result of any MPFR computation, whatever rounding mode or precision has been selected to obtain it, is (the memory representation of) an exact binary number, of the form <code>m*2^e</code>, where <code>m</code> is an integer mantissa and <code>e</code> is a (possibly negative) integer exponent. Co...
<python><mpfr><gmpy>
2025-05-08 12:05:52
1
848
Taar
79,612,271
4,066,646
Reading Outlook mail in Python or Powershell
<p>I have been trying to read the content of mails in Outlook from both Python and Powershell, but for every version of code I have tried, I can't access the properties I want.</p> <p>I can get the com-objects and I can access the subject from each. But I need to get the body and receivers. In Powershell the properties...
<python><powershell><email><outlook>
2025-05-08 11:32:20
1
357
Smorkster
79,612,149
1,826,066
Turn polars dataframe into nested dictionary
<p>I have a <code>polars</code> dataframe like such:</p> <pre><code>print( pl.DataFrame( { &quot;file&quot;: [&quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;B&quot;, &quot;B&quot;, &quot;B&quot;], &quot;user&quot;: [&quot;u1&quot;, &quot;u2&quot;, &quot;u3&quot;, &quot;u1&quot;, ...
<python><python-polars>
2025-05-08 10:12:39
2
1,351
Thomas
79,612,007
3,099,733
undefined reference to `Py_Initialize' when build a simple demo.c on a Linux conda environment
<p>I am testing of running a Python thread in a c program with a simple example like the below</p> <pre class="lang-py prettyprint-override"><code># demo.py import time for i in range(1, 101): print(i) time.sleep(0.1) </code></pre> <pre class="lang-c prettyprint-override"><code>// demo.c #include &lt;Python.h&...
<python><gcc><anaconda><conda>
2025-05-08 08:43:16
1
1,959
link89
79,611,923
1,019,109
Mixin for making third-party Django model fields typed
<p>Given the problem that not all libraries add type annotations, I am trying to build a mixin that would allow me to add type hints easily. Without that, the type-checker infers the type of the model instance field as that of the underlying built-in field’s value (e.g., str, int, date, etc.) that the custom field is b...
<python><django><python-typing><django-model-field>
2025-05-08 07:40:24
1
576
interDist
79,611,859
10,395,747
get processid of a function in python
<p>I have two functions in my python script</p> <pre><code> def func1(): #This does some processing and returns xyz informaiton return &quot;...&quot; def func2(): #This also does some other kind of prcessing and returns some info return &quot;#...#&quot; </code></pre> <p>More details on th...
<python><python-3.x><pyspark>
2025-05-08 07:01:10
1
758
Aviator
79,611,667
334,719
How do I handle SIGTERM inside python async methods?
<p>Based on <a href="https://gist.github.com/nvgoldin/30cea3c04ee0796ebd0489aa62bcf00a" rel="nofollow noreferrer">this code</a>, I'm trying to catch SIGINT and SIGTERM. It works perfectly for SIGINT: I see it enter the signal handler, then my tasks do their cleanup before the whole program exits. On SIGTERM, though, th...
<python><python-3.x><python-asyncio>
2025-05-08 03:07:59
2
2,265
Auspex
79,611,663
7,709
Automating a podman-based CI workflow using python
<p>I want to write a python3 script that will set up a pristine system (e.g: &quot;fedora:42&quot;), copy a local clone of a git repository, and run its tests. For continuous integration. I really would prefer to avoid Dockerfiles. A similar code in perl is <a href="https://github.com/thewml/website-meta-language/blob/...
<python><linux><docker><fedora><podman>
2025-05-08 03:04:52
1
4,510
Shlomi Fish
79,611,647
1,023,928
Polars for Python, can I read parquet files with hive_partitioning when the directory structure and files have been manually written?
<p>I manually created directory structures and wrote parquet files rather than used the <code>partition_by</code> parameter in the <code>write_parquet()</code> function of the python polars library because</p> <ul> <li>I want full control over the parquet file naming</li> <li>I want to handle what to do in the event of...
<python><parquet><python-polars><polars>
2025-05-08 02:34:09
1
7,316
Matt
79,611,625
5,082,463
Qt Creator Color Scheme for Python
<p>I'm trying Qt Creator with a Python project.</p> <p>Compared to Sublime Text it seems Qt Creator Color Scheme is less &quot;fancy&quot;.</p> <p>Below, the 1st is what I see on Qt Creator and the 2nd what I see on SublimeText:</p> <p><a href="https://i.sstatic.net/mSJAPeDs.png" rel="nofollow noreferrer"><img src="htt...
<python><qt-creator>
2025-05-08 01:57:37
0
6,367
KcFnMi
79,611,596
4,581,085
Qiskit v2.0.0 Statevector probabilities_dict throws TypeError: unsupported operand type(s) for -: 'int' and 'qiskit.circuit.Qubit'
<p>It’s my first week coding in Qiskit, so I’m using the latest version v2.0.0, but there seems to be a big overhaul, so I’m struggling with reading the docs and even going to the source code, and Copilot AIs are starting to loop into dead ends with their solutions.</p> <p>I’m implementing the <strong>Quantum Excess Ev...
<python><qiskit>
2025-05-08 01:21:12
1
985
Alex F
79,611,525
3,325,942
How to use a class property as a decorator in Python?
<p>I'm trying to make a RateLimiter class in Python that can be instantiated as a class property in other classes, and then applied to functions to be rate limited as a decorator. Here's the RateLimiter:</p> <pre class="lang-py prettyprint-override"><code>import time from functools import wraps from threading import Lo...
<python>
2025-05-07 23:38:25
2
842
ROODAY
79,611,317
476,298
Why does the command source not work on Windows - cannot activate venv?
<p>I try to setup a virtual environment for a <em>Python</em> project, and the command <code>source</code> doesn't work:</p> <pre class="lang-none prettyprint-override"><code>C:\Users&gt;source MyEnv 'source' is not recognized as an internal or external command, operable program or batch file. </code></pre> <p>I could ...
<python><powershell><batch-file><virtualenv>
2025-05-07 19:44:44
1
2,107
Darkhydro
79,611,225
3,163,618
Polars check if column is unique
<p>There are multiple ways to check if a column in polars is unique, i.e. it can be used as a key. For example</p> <pre><code>df.[&quot;a&quot;].is_unique().all() </code></pre> <p>(<a href="https://stackoverflow.com/questions/74841242/selecting-with-indexing-is-an-anti-pattern-in-polars-how-to-parse-and-transform">Sele...
<python><dataframe><unique><python-polars>
2025-05-07 18:36:32
1
11,524
qwr
79,611,220
1,328,439
"ModuleNotFoundError: No module named 'ESMF'" when importing xesmf installed via conda
<p>I have tried to install xESMF module developed by pangeo-data collective into my conda environment with</p> <pre class="lang-bash prettyprint-override"><code>conda install -c conda-forge --override-channels xesmf </code></pre> <p>however when I try to import xesmf I get the following error:</p> <pre><code>import xes...
<python><conda><xesmf>
2025-05-07 18:34:31
1
17,323
Dima Chubarov
79,611,005
3,758,232
pyproject.toml: specify dynamic parameters for C extension
<p>I'm updating a Python package that contains some C extensions.</p> <p>In a previous version I had all parameters set up in the setuptools <code>setup()</code> function, and now I am porting that setup into a new version that uses <code>pyproject.toml</code> with setuptools as a build back end.</p> <p>The relevant sn...
<python><python-c-api><pyproject.toml>
2025-05-07 16:16:28
0
928
user3758232
79,610,948
2,886,640
How to modify the metadata creation date of a file through Python?
<p>I have a lot of photos with wrong dates in metadata. When I upload them to a web service like Amazon Photos for example, they are disorganized due to that.</p> <p>So I am doing a Python 3 script in Linux to modify the dates of the photos, but not all dates are changing.</p> <p>For example, when examining the date of...
<python><python-3.x><metadata>
2025-05-07 15:50:04
0
10,269
forvas
79,610,656
3,760,519
What is the purpose of the output parameter in the server function of a shiny app?
<p>In R, the output is used to render outputs by assigning the result of a render function to some element of the output object. It does not seem to work this way in python.</p> <p>Some example python code:</p> <pre><code>def server(input: Inputs, output: Outputs, session: Session) -&gt; None: @render.plot def ...
<python><py-shiny>
2025-05-07 13:32:14
0
2,406
Chechy Levas
79,610,592
3,584,765
Utilizing cocoapi for evaluation in python produces print results in console
<p>I am using the Coco eval script for my project. I have modified the demo provided <a href="https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoEvalDemo.ipynb" rel="nofollow noreferrer">here</a>. The commands I use are basically those:</p> <pre><code>cocoGt = COCO(gt_json) cocoDt = cocoGt.loadRes(resul...
<python>
2025-05-07 13:00:11
0
5,743
Eypros
79,610,568
17,889,492
Store numpy array in pandas dataframe
<p>I want to store a numpy array in pandas cell.</p> <p>This does not work:</p> <pre><code>import numpy as np import pandas as pd bnd1 = np.random.rand(74,8) bnd2 = np.random.rand(74,8) df = pd.DataFrame(columns = [&quot;val&quot;, &quot;unit&quot;]) df.loc[&quot;bnd&quot;] = [bnd1, &quot;N/A&quot;] df.loc[&quot;bnd&q...
<python><pandas><numpy>
2025-05-07 12:49:15
2
526
R Walser
79,610,495
21,446,483
Spark memory error in thread spark-listener-group-eventLog
<p>I have a pyspark application which is using Graphframes to compute connected components on a DataFrame. The edges DataFrame I generate has 2.7M records. When I run the code it is slow, but slowly works through the required transformations and joins prior to the use of Graphframes. However, when calling the <code>con...
<python><apache-spark><pyspark><google-cloud-dataproc><graphframes>
2025-05-07 12:16:28
1
332
Jesus Diaz Rivero
79,610,462
13,392,257
Eliminate spaces in raw SQL in python script
<p>I am creating a sql-view with help of sqlalchemy, my code:</p> <pre><code>from sqlalchemy.sql import text from app.core.config import settings # CREATE VIEWS all_recent_tasks = text( f&quot;CREATE OR REPLACE VIEW all_recent_tasks AS \ SELECT COUNT(*) FROM tasks WHERE creation_time &gt;= NOW() - INTERVA...
<python><sql><sqlalchemy>
2025-05-07 12:00:28
4
1,708
mascai
79,610,450
538,256
subtract parabolic average from image (vignette removal)
<p>I have to process the images I acquire with the microscope with a vertical binning, to obtain the distances between the dark/bright regions. Images are like this: <a href="https://i.sstatic.net/3Tw6IilD.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/3Tw6IilD.png" alt="starting image" /></a></p> <p>I ...
<python><image-processing><signal-processing>
2025-05-07 11:49:55
1
4,004
alessandro
79,610,431
7,093,241
Failed import in jupyter notebook venv kernel in VS Code but successful import in terminal also in VS Code
<p>I was trying to go over this <a href="https://pgmpy.org/exact_infer/causal.html" rel="nofollow noreferrer">pgymy tutorial</a> and I ran into an issue with the package. I am running this on a Jupyter notebook on VS Code on Windows.</p> <pre><code>from pgmpy.models import DiscreteBayesianNetwork </code></pre> <p>Howev...
<python><visual-studio-code><jupyter-notebook><google-drive-shared-drive><venv>
2025-05-07 11:35:52
0
1,794
heretoinfinity
79,610,339
9,488,023
How to get the same shading and colors with Lightsource in Python on two different images
<p>I have two different images of maps that are located next to each other, and I want to shade them with the same method so that they fit seamlessly together with regards to shading and color. However, when I use LightSource in Python, they have different shadings despite using the same inputs. My code looks like this...
<python><image><matplotlib><shading>
2025-05-07 10:36:33
0
423
Marcus K.
79,610,246
2,250,791
Type-hinting a function to Initialize a class with provided parameter
<p>The following code which is just the extracted problematic part of a non-useless method, really makes pyright mad, how can I fix that?</p> <pre class="lang-py prettyprint-override"><code>from typing import Type, Optional def mymethod[T](inp:str, out:Type[T]) -&gt; Optional[T]: return out(inp) </code></pre> <p>P...
<python><python-typing><pyright>
2025-05-07 09:52:00
1
2,075
Camden Narzt
79,610,192
1,473,517
How to profile code where the time is spent in imap_unordered?
<p>This code (it will only work in Linux) makes a 100MB numpy array and then runs <code>imap_unordered</code> where it in fact does no computation.</p> <p>It runs slowly and consistently. It outputs a <code>.</code> each time the square function is called and each takes roughly the same amount of time. How can I profi...
<python><python-multiprocessing>
2025-05-07 09:27:14
1
21,513
Simd
79,610,172
2,526,586
Python Flask to log in different locations
<p>I have a Python Flask app that does <strong>3 things</strong> in one app:</p> <ul> <li>Serve as traditional monolithic web app with HTML, JS and CSS</li> <li>Serve RESTful API endpoints</li> <li>Run scheduled jobs using APScheduler</li> </ul> <p>I have two separate blueprints for serving as traditional web app and A...
<python><flask><logging><apscheduler>
2025-05-07 09:14:58
1
1,342
user2526586
79,609,861
1,219,158
Azure Container Apps Jobs with Event Hubs integration is looping endlessly, even though there is no new events
<p>I am using Azure Container Apps Jobs with an event driven trigger through Azure Event Hubs with <code>blobMetadata</code> as the check point strategy. The job gets triggered as it should, the check point store gets updated by the job, as it should. The problem is that the jobs get triggered immediately after finishi...
<python><azure><azure-eventhub><keda><azure-container-app-jobs>
2025-05-07 05:50:50
2
1,961
Ganhammar
79,609,673
3,834,639
Worker was sent code 139! running Gunicorn + Chroma
<p>I have a Flask app that uses Gunicorn/Nginx + ChromaDB v1.0.8. I've had no issues with its functionality till today when I restarted the service, to which I would receive</p> <pre><code>May 06 19:33:34 cluster gunicorn[6804]: 2025-05-06 19:33:34.413 | INFO | app:insert:79 - insert: querying chroma for nearest em...
<python><flask><nginx><gunicorn><chromadb>
2025-05-07 01:09:21
0
1,078
idris
79,609,620
18,002,913
Can we make future predictions using Orange Tool (time series forecasting)?
<p>I've been working on time series forecasting using models like LSTM, ARIMA, and Prophet. Recently, I came across Orange Tool, which seems very user-friendly and powerful for visual, low-code machine learning workflows. However, I couldn't find much documentation on how to perform future predictions with Orange β€” esp...
<python><time-series><orange>
2025-05-06 23:20:37
0
1,298
NewPartizal
79,609,493
13,112,929
Launch Celery Task from Database Object Method
<p>In Miguel Grinberg's <a href="https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world" rel="nofollow noreferrer">Flask Mega-Tutorial</a>, <a href="https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-xxii-background-jobs" rel="nofollow noreferrer">chapter 22</a>, he creates a gen...
<python><flask><celery><rq>
2025-05-06 21:12:44
1
477
setty
79,609,474
11,515,528
polars - no attribute 'extract_many'
<p>Trying this in Polars 0.20.23 but getting any error.</p> <pre><code>import polars as pl # Sample data data = { &quot;text&quot;: [ &quot;Year: 2020, Month: January&quot;, &quot;Year: 2021, Month: February&quot;, &quot;Year: 2022, Month: March&quot;, &quot;Year: 2023, Month: April...
<python><dataframe><python-polars>
2025-05-06 20:54:59
1
1,865
Cam
79,609,420
5,908,253
Using a Polars series as input for Scikit Learn TfidfVectorizer
<p>We are looking into adding polars support to string_grouper (<a href="https://github.com/Bergvca/string_grouper" rel="nofollow noreferrer">https://github.com/Bergvca/string_grouper</a>). To make this work, as a first step we should be able to run a TfIdfVectorizor on a Polars series. On the polars website it seems t...
<python><python-polars>
2025-05-06 20:10:01
0
337
Chris van den Berg
79,609,395
11,515,528
Polars extract_all get the last item
<p>so this works in polars</p> <pre><code>path = ['some text 2020', '2021 text 2020', 'etxt 2022', '2023 text 2022'] names = [&quot;Alice&quot;, &quot;Bob&quot;, &quot;Charlie&quot;, &quot;David&quot;] df = pl.DataFrame({ &quot;path&quot;: path, &quot;name&quot;: names }) df year = ['2019', '2020', '2021', '...
<python><python-polars>
2025-05-06 19:49:37
0
1,865
Cam
79,609,252
4,175,822
How can I define a protocol for a class that contains a protocol field and use a dataclass implementer?
<p>I want to do this:</p> <pre><code>import typing import dataclasses class ConfigProtocol(typing.Protocol): a: str @dataclasses.dataclass class Config: a: str class HasConfigProtocol(typing.Protocol): config: ConfigProtocol @dataclasses.dataclass class HasConfig: config: Config def accepts_hascon...
<python><python-dataclasses>
2025-05-06 18:01:40
1
2,821
spacether
79,609,220
1,635,909
Documenting a script step by step with Sphinx
<p>I am documenting a python library with Sphinx.</p> <p>I have a couple of example scripts which I'd like to document in a narrative way, something like this:</p> <pre><code>#: Import necessary package and define :meth:`make_grid` import numpy as np def make_grid(a,b): &quot;&quot;&quot; Make a grid for const...
<python><python-sphinx>
2025-05-06 17:40:43
4
2,234
Joce
79,609,199
14,586,554
Numerically stable noncentral chi-squared distribution in torch?
<p>I need numerically stable non-central chi2 distribution in torch.</p>
<python><pytorch><statistics><numerical-methods>
2025-05-06 17:29:47
1
620
Kemsikov
79,608,877
8,458,083
Nixpacks build hangs when venv directory exists in Python project
<p>I'm using Nixpacks to build a Docker image from a Python project. The build works fine when my project directory does not contain a local virtual environment. However, if I create a virtual environment (e.g., with <code>python -m venv venv</code>), the build hangs indefinitely at the <code>Building Nixpacks image......
<python><nixpacks>
2025-05-06 13:59:31
0
2,017
Pierre-olivier Gendraud
79,608,752
29,295,031
How to add space between Bubbles and increase thier size
<p>I have a bubble chart developed using plotly library and here’s the data :</p> <pre><code>import plotly.express as px import pandas as pd data = { &quot;lib_acte&quot;:[&quot;test 98lop1&quot;, &quot;test9665 opp1&quot;, &quot;test QSDFR1&quot;, &quot;test ABBE1&quot;, &quot;testtest21&quot;,&quot;test23&quot;]...
<python><pandas><plotly>
2025-05-06 12:53:00
1
401
user29295031
79,608,713
2,026,659
Getting 'Could not install packages due to an OSError' when installing Python packages in GitLab pipeline
<p>I'm trying to install a few pip packages in a GitLab pipeline job in order to run a Python script. The image used to run the pipeline job is a custom Python image using Python version 3.12 and with Ubuntu 25.04 and is set to a non-root user python. When the pipeline job runs I have a command to active the Python vir...
<python><python-3.x><gitlab-ci>
2025-05-06 12:28:14
1
2,641
mdailey77
79,608,662
13,806,869
How can I upgrade Pandas via pip?
<p>I currently have Pandas 1.4.2 installed. I want to update to the latest version, so I entered this into the command prompt:</p> <blockquote> <p>pip install -U pandas</p> </blockquote> <p>However, it just returns this message:</p> <blockquote> <p>Requirement already satisfied: pandas in c:\users\my_username\appdata\l...
<python><pandas><pip>
2025-05-06 12:01:35
2
521
SRJCoding
79,608,369
4,865,723
Bars not fitting to X-axis ticks in a Seaborn distplot
<p>I do generate that figure with <code>seaborn.distplot()</code>. My problem is that the ticks on the X-axis do not fit to the bars, in all cases. I would expect a relationship between bars and ticks like you can see at 11 and 15.</p> <p><a href="https://i.sstatic.net/BOCA6W8z.png" rel="nofollow noreferrer"><img src="...
<python><pandas><seaborn>
2025-05-06 09:17:48
2
12,450
buhtz
79,608,254
2,037,570
Installing python3.10 on debian:stretch-slim image?
<p>I have an docker file where the base image is set to debian:stretch-slim. The default version of python3 is python3.5 in this image.</p> <p>FROM debian:stretch-slim as base-os</p> <p>.... ....</p> <pre><code>RUN python3 -V RUN which python3 </code></pre> <p>Output is:</p> <pre><code>#35 [linux/amd64 base-os 14/18] R...
<python><docker><dockerfile><debian>
2025-05-06 08:11:00
0
3,645
Hemant Bhargava
79,608,184
11,769,133
Wrong column assignment with np.genfromtxt if passed column order is not the same as in file
<p>This problem appeared in some larger code but I will give simple example:</p> <pre class="lang-py prettyprint-override"><code>from io import StringIO import numpy as np example_data = &quot;A B\na b\na b&quot; data1 = np.genfromtxt(StringIO(example_data), usecols=[&quot;A&quot;, &quot;B&quot;], names=True, dtype=N...
<python><numpy><genfromtxt>
2025-05-06 07:24:24
2
1,142
Milos Stojanovic
79,608,124
1,713,297
Multiple time series chart in altair with selectable time series
<p>I want to make a chart in altair with the following properties:</p> <ul> <li>It shows multiple time series</li> <li>I can select which time series are displayed by clicking on the legend</li> <li>If a series is unselected in the legend, then it is not displayed in the plot</li> <li>If a series is unselected in the l...
<python><pandas><altair>
2025-05-06 06:45:22
1
662
Flounderer
79,607,892
9,630,700
How can I save the list of packages used after running "uv run --with REQUIRED_PACKAGE MYSCRIPT.py"?
<p>Say I have a script MYSCRIPT.py that imports REQUIRED_PACKAGE. REQUIRED_PACKAGE itself could have other dependencies. How can I save the details of the packages downloaded (e.g. into a lock file) when I run <code>uv run --with REQUIRED_PACKAGE MYSCRIPT.py</code>?</p> <p>For a specific example, if I save the followin...
<python><uv>
2025-05-06 02:36:20
1
328
chuaxr
79,607,851
1,276,664
get global variable with dashes in jinja2
<p>is there a way to render the variable <code>b-c</code> (456) by changing only <code>template</code> variable in the following code?</p> <pre class="lang-python prettyprint-override"><code>import jinja2 environment = jinja2.Environment() data = {'a':123, 'b-c':456} template = &quot;hello {{ b-c }}&quot; result = e...
<python><jinja2>
2025-05-06 01:46:57
2
28,952
daggett
79,607,760
9,759,947
Wrong color space of infered image in Unity
<p>I'm having a hard time infering an image from a camera in Unity to an ONNX using a render Texture. I realized that the output from the ONNX inferenced with Barracuda is significantly different from the output I get when I infer the same image (after capturing) in python to the same ONNX.</p> <p>The goal is to only u...
<python><c#><image><unity-game-engine><colors>
2025-05-05 23:19:19
0
320
Schelmuffsky
79,607,611
8,788,960
More efficient way to compute elementwise gradients (Jacobian) in PyTorch while preserving create_graph
<p>I’m currently using PyTorch’s <code>torch.autograd.functional.jacobian</code> to compute per-sample, <em>elementwise</em> gradients of a scalar-valued model output w.r.t. its inputs. I need to keep <code>create_graph=True</code> because I want the resulting Jacobian entries to themselves require gradients (for furth...
<python><pytorch><gradient><autograd>
2025-05-05 20:50:42
1
1,171
hans
79,607,596
2,391,712
Dataclass/attrs based orm models and their relationships
<p>I am building a small python application to learn Domain-Driven-Design (DDD) approaches. Therefore I am using a dataclass/attrs class as my domain model and also use this class to imperatively model my orm instances. However I encounter a bug when I try to insert a class containing foreign keys:</p> <pre><code>sqlal...
<python><sqlalchemy><domain-driven-design><python-dataclasses><python-attrs>
2025-05-05 20:28:45
2
2,515
5th
79,607,554
1,361,752
Does hvplot lazily load data from xarray objects?
<p>Suppose I open an xarray dataset <code>ds</code> using <code>xarray.open_dataset</code> that contains a 3d array called <code>cube</code> with dimension coordinates x, y, and z. Usually just opening the dataset doesn't load all the data into memory, its lazily retrieved as needed.</p> <p>Now suppose I do this:</p> <...
<python><python-xarray><hvplot>
2025-05-05 19:53:06
0
4,167
Caleb
79,607,498
3,486,773
Why does my python function not properly cast the dates despite recognizing the format?
<p>I am attempting to dynamically cast various date formats that come across as a string column but are actually dates. I've gotten pretty far, and this code can correctly identify the dates from the string, but the fields 'Date2' and 'Date3' always return as null values. I can't understand why that is, or how to cor...
<python><dataframe><apache-spark>
2025-05-05 19:08:22
1
1,278
user3486773
79,607,384
659,389
Azure - Python client for listing key vaults
<p>I found <a href="https://learn.microsoft.com/en-us/python/api/overview/azure/key-vault?view=azure-python" rel="nofollow noreferrer">4 python libraries</a> for working with key vaults:</p> <ul> <li>admin</li> <li>keys</li> <li>certs</li> <li>secrets</li> </ul> <p>but I am missing an API in python to list all vaults. ...
<python><azure><azure-keyvault><azure-python-sdk>
2025-05-05 17:32:40
1
1,333
koleS