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,703,727
2,894,535
Data class with argument optional only in init
<p>I have the following simple class in Python:</p> <pre><code>class Point: def __init__(x: int, y: int | None = None): self.x = x self.y = y if y is not None else x </code></pre> <p>How can the same thing be implemented using a <code>@dataclass</code>? The obvious would be to do the following:</p> ...
<python><python-3.x><python-dataclasses>
2025-07-16 16:20:04
2
3,116
Dominik Kaszewski
79,703,712
13,350,341
Validating ES query_string upfront, namely without connecting to an Elasticsearch server
<p>I am looking for a Python library (if any) that could help <strong>validate</strong> the <code>query_string</code> field of Elasticsearch queries<sup>1</sup> upfront, namely without connecting to an Elasticsearch server and without having to define any custom validation logic. <sup>1</sup>I mean queries of the kind<...
<python><elasticsearch><elasticsearch-dsl><elasticsearch-py>
2025-07-16 16:06:17
0
3,157
amiola
79,703,702
11,999,452
ModuleNotFoundError: No module named 'hidapi'
<p>I want to run the following code:</p> <pre><code>import hidapi # Find the device devices = hidapi.DeviceManager().devices() for device in devices: if device.vendor_id == 0x2341 and device.product_id == 0x0042: gamepad = device break # Read data from the device data = gamepad.read(64) print(data...
<python>
2025-07-16 15:57:21
2
400
Akut Luna
79,703,565
4,408,232
Anaconda install of geopy but module is not found
<p>I am trying to use geopy on my laptop running Ubuntu 24.04.2 LTS. Anaconda is installed and geopy is installed.</p> <pre><code>(base) igor@XPS-13:~$ conda list | grep geopy geopy 2.4.1 pyhd8ed1ab_2 conda-forge </code></pre> <p>and searchig for installation folder:</p> <pre><code>(...
<python><anaconda><geopy>
2025-07-16 14:16:00
1
301
IgorLopez
79,703,525
4,054,573
Reportlab canvas.DrawImage resizing not working
<p>I'd like to add a logo to to the canvas so that it repeats with each page of a report, but the problem is that the PNG image is quite large. I've tried resizing it inside the <code>canvas.DrawImage</code> command, but each time the image comes back in its original size.</p> <p>Here is what I am trying, but it has no...
<python><reportlab>
2025-07-16 13:56:03
1
1,179
vashts85
79,703,347
10,423,341
Unable to Load Extensions in nodriver Proxy Context
<p>I need to load user profile, extensions and proxy in a single page context. Looks like it is not possible to do so right now using nodriver, any help/suggestion would be appreciated. Thanks</p> <p>Right now the user profile gets loaded just fine, but no extension gets loaded within the proxy context.</p> <pre><code>...
<python><google-chrome><playwright-python><chrome-devtools-protocol><nodriver>
2025-07-16 11:37:10
0
309
Jawad Ahmad Khan
79,703,332
393,010
What is the difference between xpath() and findall()?
<p>Very often I see that calls to xpath could as well be replaced by calls to findall, when can this be done? What is the main differences between the two functions?</p> <ol> <li>The first argument to <code>path</code> findall is a <code>path</code>, while to xpath the first argument <code>_path</code> is an <code>xpat...
<python><lxml>
2025-07-16 11:24:59
2
5,626
Moberg
79,703,329
6,805,396
How to rotate a single label in a plotly treemap?
<p>Suppose we have a treemap like this:</p> <pre><code>import plotly.graph_objects as go fig = go.Figure(go.Treemap( parents=['', '', 'A', 'A', 'B'], labels=['A', 'B', 'a1', 'a2', 'b1'] )) fig.show() </code></pre> <p>And we need to rotate the <code>b1</code> label to 90 degrees. Is it possible to do in plotly...
<python><plotly><treemap>
2025-07-16 11:23:53
0
609
Vlad
79,703,196
1,926,221
Print only assert message in Python
<p>Is there any way print only assert message:</p> <p><code>assert 5==4, &quot;test&quot;</code></p> <p>will print:</p> <pre><code>Traceback (most recent call last): File &quot;C:\Users\user\temp\test.py&quot;, line 4, in &lt;module&gt; assert 5==4, &quot;test&quot; AssertionError [Finished in 221ms] </code></pre...
<python><python-3.x><assert><assertion>
2025-07-16 09:19:10
2
3,726
IGRACH
79,703,043
6,312,979
Best way to convert FastAPI/SQLmodel into Polars Dataframe?
<p>What is best way to convert a FastAPI query into a Polars (or pandas) dataframe.</p> <p>Co-pilot give this.</p> <pre><code>with Session(engine) as session: questions = session.exec(select(Questions)).all() questions_json = [q.dict() for q in questions] df = pl.DataFrame(questions_json) </code></pre> <p>Do ...
<python><pandas><fastapi><python-polars><sqlmodel>
2025-07-16 07:14:24
1
2,181
diogenes
79,702,999
14,250,641
Unsupervised Time Series Segmentation Without Predefined Number of Segments
<p>I'm working with time series data where I need to identify distinct segments without prior knowledge of how many segments exist. The data looks like:</p> <p><a href="https://i.sstatic.net/53jfNxpH.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/53jfNxpH.png" alt="sample data" /></a></p> <p>I've tried ...
<python><time-series><cluster-analysis>
2025-07-16 06:30:56
0
514
youtube
79,702,749
5,312,606
sphinxcontrib-bibtex and sphinx-multiversion
<p>I have a strange bug when building our documentation using sphinxcontrib-bibtex and sphinx-multiversion.</p> <p>In my <code>docs/source/conf.py</code> I have</p> <pre class="lang-py prettyprint-override"><code>from pathlib import Path extensions = [ &quot;sphinx_multiversion&quot;, &quot;sphinxcontrib.bibte...
<python><python-sphinx><bibtex>
2025-07-15 23:18:11
0
1,897
mcocdawc
79,702,696
967,621
Enable the strictest `ruff check` in GitHub Actions
<p>How do I enable the most stringent <code>ruff check</code> in GitHub Actions? I am looking for the equivalent of:</p> <pre><code>ruff check --select ALL </code></pre> <p>The docs (<a href="https://github.com/astral-sh/ruff-action?tab=readme-ov-file#specify-multiple-files" rel="nofollow noreferrer">astral-sh/ruff-act...
<python><github-actions><ruff>
2025-07-15 21:46:13
1
12,712
Timur Shtatland
79,702,608
2,711,059
Why is the condition in the Langraph not working
<p>I am trying to build a langraph and call the relevant node as per the condition. Here is my code:</p> <pre><code>class PersonDetails(TypedDict): name: str age: int # Nodes def greet(state: PersonDetails): print(f&quot;Hello, {state['name']}!&quot;) return state def check_age(state: PersonDetails): ...
<python><langchain><langgraph><google-generativeai>
2025-07-15 20:13:54
1
5,268
Lijin Durairaj
79,702,590
494,134
How to have separate logging for instances of a class
<p>I have a class that does some logging, and I want to be able to easily distinguish log messages that are from different instances of the class.</p> <p>So, I thought I would create a logger object in the class <code>__init__</code> method that has a unique identifier in the message formatter:</p> <pre><code>import lo...
<python><logging>
2025-07-15 19:53:14
1
33,765
John Gordon
79,702,441
7,253,674
Replace all non-empty strings in a column with a constant
<p>I have a data frame with a variety of string values. For a given column, if there is any string entered, I would like to replace it with the same value (say 'fruit').</p> <p>Example:</p> <pre class="lang-py prettyprint-override"><code>data = {'item_name': ['apple', 'banana', 'cherry', 'pineapple', 'apple pie', 'bana...
<python><pandas><string><replace>
2025-07-15 17:16:18
1
365
Liz
79,702,381
7,589,775
Ignore some default values in pydantic during JSON schema generation
<p>(At the time of writing, this is on pydantic version 2.11.7) I have the following MRE:</p> <pre class="lang-py prettyprint-override"><code>import json import time from pydantic import BaseModel, Field class SeededModel(BaseModel): seed: int = Field(default_factory=lambda _: int(time.time() * 1000)) sensible...
<python><pydantic-v2>
2025-07-15 16:29:25
1
4,336
Tristan F.-R.
79,702,280
6,041,915
Is it right to raise an error in except block in python?
<p>I often see code like this:</p> <pre><code>try: some_operation() except Exception: logger.error(&quot;An error occurred while running the operation&quot;) raise Exception(&quot;A custom message&quot;) </code></pre> <p>Please ignore using the general Exception in this example, I know it's a bad practice. ...
<python><exception><error-handling>
2025-07-15 15:09:54
1
702
Jakub MaΕ‚ecki
79,701,980
5,402,618
Pycharm fails to find package in the defined PYTHONPATH
<p>I have a Python monorepo. One of the services in this monorepo is &quot;poller-service&quot;. Its general structure is:</p> <pre><code> services/ └── poller-service/ β”œβ”€β”€ .venv/ | └─ ... β”œβ”€β”€ main.py β”œβ”€β”€ src/ | └─── mycompany/ | β”œβ”€β”€ __init__.py ...
<python><pycharm><pythonpath>
2025-07-15 11:18:15
0
15,182
CrazySynthax
79,701,884
11,405,174
Indicating which column wins in a df.min() call
<p>I want to find the minimum value per row and create a new column indicating which of those columns has the lowest number. Unfortunately, it seems like pandas isn't immediately able to help in this regard. My research has led to the <code>min()</code> function, which does find the lowest for each row (when axis=1), b...
<python><pandas><dataframe>
2025-07-15 10:06:52
1
464
Corsaka
79,701,849
13,682,559
How to type hint an attribute to be a dataclass?
<p>I want a class that encapsulates data with some meta information. The data changes during runtime. I want to safe it for evaluation. The class looks like this:</p> <pre class="lang-py prettyprint-override"><code>from dataclasses import dataclass, replace, _DataclassT @dataclass class Encapsulated[P: ???]: # &lt;- ...
<python><python-typing><python-dataclasses>
2025-07-15 09:36:29
1
1,108
Durtal
79,701,824
509,868
Does ArgumentParser support different arguments per file, ffmpeg style?
<p>I want my application to work on several files and have a different set of options for each input file:</p> <pre><code>python my.py -a file_a -b file_b --do-stuff=x file_c </code></pre> <p><code>ffmpeg</code> uses this idea for its command line arguments.</p> <p>I tried the following:</p> <pre><code>parser = argpars...
<python><command-line-arguments>
2025-07-15 09:22:38
2
28,630
anatolyg
79,701,742
20,895,654
Map one type to another and make type checker understand
<p>I have the following piece of code:</p> <pre><code>from typing import Any class RawA: pass class A: pass class RawB: pass class B: pass # Example of a kind of mapping (that doesn't work) mapping = { RawA: A, RawB: B } def unraw[TRaw: Any](obj: TRaw) -&gt; Any # -&gt; the unraw type ... </code><...
<python><python-typing>
2025-07-15 08:11:36
2
346
JoniKauf
79,701,584
5,567,893
How can I remove the brackets and parentheses at the end of words?
<p>My task is to parse the protein names by removing the brackets and parentheses in the row.<br /> In short, I want to retain the words in front of any parentheses and brackets.<br /> Note that I need to keep symbols in the main words like <code>H(+)/Cl(-) exchange transporter 6</code>.</p> <pre class="lang-py prettyp...
<python><pandas><regex>
2025-07-15 05:14:15
4
466
Ssong
79,701,463
17,246,545
Why nothing written in AWS Lambda logs?
<p>Originally some AWS Lambda(A) that i made was work well. But When I deploy new ECR Image and apply Lambda A, and then I invoke the lambda; Sometimes, nothing happen!</p> <p>So, I checked lambda logs every time when occured upper issue. and the logs like below:</p> <pre><code>2025-07-14T08:51:28.206+09:00 START Reque...
<python><amazon-web-services><aws-lambda><amazon-ecr>
2025-07-15 01:23:54
1
389
SecY
79,701,408
753,558
Python requests failed to verify certificate, while urllib3 and curl do it successfully
<p>Trying to done simple GET request. Site have self-signed certificate. I was export it using Firefox (downloaded chained certificates) as a &quot;pem&quot; file. Here versions of libraries:</p> <pre><code>[user@host]$ pip list | grep -E &quot;urllib3|requests&quot; requests 2.32.4 urllib3 ...
<python><python-3.x><ssl><python-requests>
2025-07-14 22:57:07
0
302
Renat Zaripov
79,701,380
7,121,783
Python: Running tests with all combinations of feature flags
<p>We have several modules that require mandatory feature / backout flags. These flags are defined at module level.</p> <p>module.py:</p> <pre><code>from enabled import is_enabled FLAGS = {flag : is_enabled(flag) for flag in (&quot;foo&quot;, &quot;bar&quot;)} if FLAGS.get(&quot;foo&quot;): def baz(): pri...
<python><testing><python-unittest>
2025-07-14 21:54:54
0
1,003
OM222O
79,701,195
2,153,235
Should plt.ion() eliminate the need for plt.show()?
<p>I was using <code>matplotlib</code>'s Tk back end on Spyder and never had to issue <code>plt.show()</code> (or more specifically, <code>plt.show(block=False)</code>). I now have to prepare for analysis work on a closed system where the only access to Python is via QGIS. From much Googling, my <em>impression</em> i...
<python><matplotlib>
2025-07-14 17:22:01
1
1,265
user2153235
79,701,140
3,892,866
pip install --no-index can't find setuptools
<p>I have a computer that for security reasons has no public network access. The system starts with all necessary public Python dependencies installed, I just need to add the latest version of my own python package and run. I'm trying to install my package from the .tar.gz file by pip3 --no-index; --no-index is needed ...
<python><pip>
2025-07-14 16:33:10
1
568
Bill Shubert
79,701,038
20,895,654
Make type checker understand that class and instance attributes share names but have diffent types dynamically
<p>I have a piece of code in Python that in essence looks and works the following way:</p> <pre class="lang-py prettyprint-override"><code>from typing import Any class Column: def __init__(self, s: str) -&gt; None: self.name = s def __repr__(self): return f'Column(name={self.name!r})' class M...
<python><python-typing><class-variables><pyright>
2025-07-14 14:41:54
1
346
JoniKauf
79,701,017
1,172,907
Mocking a class method attribute returns AttributeError
<p>How can I mock the value of <code>x</code> to &quot;bar&quot; instead of &quot;foo&quot;?</p> <pre class="lang-py prettyprint-override"><code>import pytest class Command(): def run(self): x = &quot;foo&quot; return x def test(mocker): mocker.patch(&quot;myapp.tests.test_mocker.Command.ru...
<python><pytest><pytest-mock>
2025-07-14 14:16:16
1
605
jjk
79,701,003
2,912,349
Generating blue noise with values sampled from a log normal distribution
<h1>Aim</h1> <p>I am trying to generate random signals with the following two properties:</p> <ol> <li><p>The values should be approximately log-normally distributed (any long-tailed distribution bounded form below with non-zero mode would do).</p> </li> <li><p>The power spectral density (PSD) of the signal should have...
<python><numpy><scipy><statistics><signal-processing>
2025-07-14 14:02:04
1
12,703
Paul Brodersen
79,700,885
14,380,704
Pandas Pivot_table KeyError when Key is Present
<p>I've run this code in an older version of Python, with success; however, we've recently switched to Python 3.9 and I'm getting a KeyError:'RegIndex' on a pivot step for a column that exists in the original dataframe...below is the code sample and dataframe sample.</p> <pre><code>myData=df[['ModelYear','RegIndex','Mo...
<python><pandas>
2025-07-14 12:32:36
1
307
2020db9
79,700,637
5,698,125
Python3 dictionary being modified at another thread does not show changes after those modifications at the original thread
<p>Python version: (3.9, but the same result with python 3.12)</p> <p>The goal was that another thread modified a dictionary and those modifications to be available at the original thread.</p> <pre class="lang-py prettyprint-override"><code>import multiprocessing as mp import sys def my_func(result: dict): print(f...
<python><multithreading>
2025-07-14 08:58:11
1
410
Francisco Javier Rojas
79,700,632
3,933,475
Python pickle scipy.interpolate.RBFInterpolator across operating systems (windows, mac)
<p>I have created an <code>RBFInterpolator</code> object from the package <code>scipy.interpolate</code> and I can easily pickle it and unpickle it using the <code>pickle</code> package along with binary read and write.</p> <p>However, when I create it under windows and try to use it on a mac (and vice versa), I get fo...
<python><windows><macos><scipy><pickle>
2025-07-14 08:55:24
0
394
Philip Harding
79,700,582
219,153
VS Code doesn't open Python virtual environment
<p>I'm using Python 3.13.5 with VS Code 1.102.0 on Ubuntu 24.04.2. With VS Code updates, there were often problems with opening <code>venv</code> environment, but usually reloading VS Code was sufficient to make it work. Not with the newest version. Here are the extensions I have installed:</p> <p><a href="https://i.ss...
<python><visual-studio-code><python-venv>
2025-07-14 08:07:59
0
8,585
Paul Jurczak
79,700,418
68,736
sympy mod on formulas with custom functions
<p>I would like to define custom <code>sympy</code> functions which cannot be directly evaluated, but which I do want to be able to compute some things about. For example, modular remainders. Here's my code attempt:</p> <pre class="lang-py prettyprint-override"><code>from sympy import Function class Foo(Function): @...
<python><sympy><symbolic-math><largenumber>
2025-07-14 03:43:50
1
6,427
sligocki
79,700,371
13,413,858
In-place, strictly In-place, and O(1) space algorithms
<p>How does one categorize an algorithm like this:</p> <pre class="lang-py prettyprint-override"><code>def foo(arr): # original_len = len(arr) tmp = [] while arr: tmp.append(arr.pop()) while tmp: arr.append(tmp.pop()) </code></pre> <p>The definitions get kinda of confusing because theore...
<python><space-complexity><in-place>
2025-07-14 01:59:39
1
494
Mathias Sven
79,700,110
503,456
scipy 1.16 bug, invalid matrices with incorrect indptr sizes
<p>I have just upgraded from 1.15 to 1.16, but rand across an issue with CSC matrices and multiplication.</p> <p>Demonstration of scipy sparse matrix multiply bug affecting CSC matrix indptr size.</p> <p>This script demonstrates a bug in scipy where the .multiply() operation on CSC matrices can produce invalid CSC matr...
<python><scipy>
2025-07-13 16:41:07
1
928
mattjvincent
79,700,040
626,063
Performing Union Operation using Inkscape Extension on 3 Groups But Weird Result
<p>I made an extension to perform union operation on each selected group, but I got a weird result.</p> <p>For example, there are three selected groups of rectangles:</p> <p><a href="https://i.sstatic.net/Z4iyiw8m.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Z4iyiw8m.jpg" alt="Example - Three Groups o...
<python><inkscape>
2025-07-13 14:49:12
1
469
Bayu
79,700,024
5,490,316
How to work with different python library with different interpreter
<p>I have some python interpreter installed in my computer:</p> <ul> <li>Python 3.13.5 (<em>Recommended</em>)</li> <li>Python 3.13.1 (<em>Global</em>)</li> <li>Python 3.12.10</li> <li>Python 3.12.3</li> <li>Python 3.11.9</li> </ul> <p>But some libraries can only work with one interpreter, for example if I import these ...
<python>
2025-07-13 14:25:49
2
387
louislugas
79,699,857
5,378,816
How to parametrize all async tests?
<p>I have many test functions, sync and async.</p> <p>I'm using <code>pytest-asyncio</code> in the &quot;auto&quot; mode, so it detects all async tests and I don't have to mark them as such.</p> <p>My problem is that I want to parametrize all my async tests. I want to run them twice, using two different task factories....
<python><pytest><pytest-asyncio>
2025-07-13 09:20:57
1
17,998
VPfB
79,699,841
7,456,317
VSCode devcontainer and UV
<p>I'm developing using VSCode's devcontainer, and I used pip with a <code>requirements.txt</code> file for a few years with no problems. Works like charm. I'd like to upgrade to using uv, but I'm encountering a problem. My <code>Dockerfile</code> has the following lines:</p> <pre class="lang-none prettyprint-override"...
<python><docker><vscode-devcontainer><uv>
2025-07-13 08:33:13
1
913
Gino
79,699,626
16,305,340
the virtual environment is using the global pip not the local one
<p>I am using Ubuntu 24.04 with Python 3.12 installed on it. I am jsut trying to use the command <code>pip install &lt;package_name&gt;</code> inside the virutal environment but for some reason it uses the global one.</p> <p>I first created a virtual environment using the command:</p> <pre><code>python3 -m venv .venv <...
<python><python-3.x><pip><virtualenv>
2025-07-12 22:25:52
1
1,893
abdo Salm
79,699,531
16,037,994
pybind11: Python callback executed in C++ with parameter modification
<p>I'm working on Python bindings of my C++ library (a mathematical optimization solver) and I'm stuck at a point where I create a Python callback <code>evaluate_constraints()</code> that takes two arguments, pass it to the C++ library and evaluate it with C++ arguments. The callback modifies its second parameter <code...
<python><c++><reference><pybind11>
2025-07-12 19:39:09
1
401
Charlie Vanaret - the Uno guy
79,699,115
28,004
Can't find PDF text
<p>I'm trying to come up with a nice feature for my work colleagues, that every day in the morning, we would get in Slack the menu of the day... inspired by <a href="https://github.com/lemedege/LunchBot/blob/main/run.py" rel="nofollow noreferrer">https://github.com/lemedege/LunchBot/blob/main/run.py</a></p> <p>But I'm ...
<python><pypdf>
2025-07-12 08:04:55
0
75,406
balexandre
79,699,094
11,071,831
Testing equality of lists which contain NaN
<p>I have a small class for which I am writing tests. The result for my function contains <code>nan</code> which causes my test to fail because <code>nan</code> is not equal to any other <code>nan</code>. How do I write a proper test for this?</p> <pre><code>from math import nan import unittest import pandas as pd cl...
<python><unit-testing>
2025-07-12 07:26:10
1
440
Charizard_knows_to_code
79,699,081
4,058,178
Not able to execute DAX on PowerBI in .Net through ADOMD Client
<p>I have the below python code which works perfectly on any Workspace by executing the DAX on powerbi Dataset, whereas i converted this in .Net, but its failing and giving Not Found error. Can someone please help here</p> <p>Python</p> <pre><code>import clr clr.AddReference(r&quot;C:\Program Files\Microsoft.NET\ADOMD....
<python><.net><powerbi><dax>
2025-07-12 07:08:15
0
404
Sam K
79,698,987
2,955,095
How can I execute a Python script in the REPL interpreter mode and get the exactly same output as if it was manually typed in? (Ubuntu, Python 3.12)
<p>The Python interpreter can be run either in script or interactive/REPL mode. I do have a Python script as text file but want to run it <em>as if</em> it was manually typed in in the interactive/REPL mode. I want to get the output (stdout) exactly as if this was done. To give an example, assume that I have the follow...
<python><linux><stdout><interactive><read-eval-print-loop>
2025-07-12 03:42:41
3
441
Thomas Weise
79,698,870
9,669,142
Convert FlightRadar altitude to WGS84 ellipsoid + elevation
<p>I have a CSV export from a flight from FlightRadar, where the altitude is included. I want to use this CSV with Cesium. Right now, the ground altitude in the file is always 0, which won't work properly with Cesium since then the altitude will be under the ground. Hence I need to take two things into account: the WGS...
<python><wgs84>
2025-07-11 21:57:05
1
567
Fish1996
79,698,757
4,996,797
Pytest fixture saved into a pickle
<p>I am working on a project where I am building on top of a solution of a very time-consuming problem. Instead of solving the very time consuming part many times, I only run the solver once, I save the solution with pickle, and then I reuse the pickle to test my features build on top of the solution.</p> <p>Here is a ...
<python><automated-tests><pytest>
2025-07-11 19:22:14
1
408
PaweΕ‚ WΓ³jcik
79,698,620
21,370,869
correct way to use the β€˜dragCallback’ parameter of the channelBox command?
<p>I have been at this for an hour, with various variations but have not had any success with it.</p> <p>Here is a very basic sample of one approach I tried:</p> <pre><code>def foo(dragControl, x, y, modifiers, *args): Β  Β print(&quot;--------------------------------- Β  Hello World ------------------------------------&...
<python><maya>
2025-07-11 16:33:46
0
1,757
Ralf_Reddings
79,698,441
6,838,716
Running Python functions from other files
<p>I have created a number of .py files containing functions. The files would be organized in a Project_Repertory as follows:</p> <p>Project_Repertory</p> <ul> <li>Load_Repertory <ul> <li>load_functions.py</li> <li>main.py</li> </ul> </li> <li>Automate_Repertory <ul> <li>main.py</li> </ul> </li> </ul> <p>In the Automat...
<python><import>
2025-07-11 13:57:38
1
1,486
YamiOmar88
79,698,380
3,336,423
PyQt vs PySide uic loader difference
<p>I'm migrating some code from PtQy5 to PySide6. I'm experiencing a significant behavioural difference when loading .ui files.</p> <p>The original PyQt5 code:</p> <pre><code>import sys import os from PyQt5.QtWidgets import QApplication from PyQt5.QtWidgets import QWidget, QMainWindow from PyQt5 import uic ui_content...
<python><pyqt5><qt-designer><pyside6>
2025-07-11 13:03:53
0
21,904
jpo38
79,698,070
2,311,202
Adding vertical lines to histogram plot
<p>I have the following code to plot a histogram in Python:</p> <p><code>fig.add_trace(go.Histogram(x = df[&quot;error&quot;], showlegend = False))</code></p> <p>This results into a histogram similar to:</p> <p><a href="https://i.sstatic.net/6bw54LBM.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/6bw54L...
<python><plotly><histogram>
2025-07-11 08:54:59
2
506
Pietair
79,697,826
3,577,105
Is there a way to tell if a function's return value is used?
<p>Is there a way to determine if the return value of a function is needed, from inside that function?</p> <p>Example:</p> <pre><code>drawPoint(1,2) </code></pre> <p>vs.</p> <pre><code>newPointId=drawPoint(1,2) </code></pre> <p>drawPoint makes an http request, so, the response from that request might be received from t...
<python>
2025-07-11 04:28:59
2
904
Tom Grundy
79,697,347
13,682,559
How to define a immutable ClassVar in a python protocol?
<p>I have an Enum and several classes using that Enum in an immutable class variable.</p> <pre class="lang-py prettyprint-override"><code>from typing import ClassVar, Protocol, Final, Literal from enum import Enum class MyEnum(Enum): A = 0 B = 1 class MyClass1: type: Final = MyEnum.A class MyClass2: ...
<python><protocols><python-typing><class-variables>
2025-07-10 16:29:34
1
1,108
Durtal
79,697,269
6,141,238
When reading a database table with polars, how do I avoid a SchemaError?
<p>I have a large <code>table_to_load</code> in a database file <code>my_database.db</code> that I am trying to read into a Python program as a <code>polars</code> DataFrame. Here is the code that does the reading:</p> <pre><code>import polars as pl conn = sqlite3.connect('my_database.db') df = pl.read_database(conne...
<python><dataframe><sqlite><python-polars><polars>
2025-07-10 15:10:29
2
427
SapereAude
79,697,190
5,058,384
ComfyUI error: Expected all tensors to be on the same device, but found at least two devices, cpu and cuda:0
<p>I am trying to train a LoRA in ComfyUI using the modified version of the example workflow for ComfyUI-FluxTrainer (<a href="https://github.com/kijai/ComfyUI-FluxTrainer/issues" rel="nofollow noreferrer">https://github.com/kijai/ComfyUI-FluxTrainer/issues</a>) I found on reddit here (<a href="https://www.reddit.com/r...
<python><pytorch>
2025-07-10 14:05:59
0
966
garrettlynchirl
79,696,741
2,311,202
Plot confusion matrix in black and white
<p>I currently have the following code:</p> <pre class="lang-py prettyprint-override"><code>disp = ConfusionMatrixDisplay(confusion_matrix=cm) disp.plot() plt.show() </code></pre> <p>This results into something like:</p> <p><a href="https://i.sstatic.net/JfXLXyc2.png" rel="nofollow noreferrer"><img src="https://i.sstat...
<python><scikit-learn><confusion-matrix>
2025-07-10 08:32:50
1
506
Pietair
79,696,290
1,713,450
A way to defer yielding a Request in scrapy?
<p>My scrapy logic is as follows:</p> <ol> <li>get all rows from <code>child_page_table</code> where <code>parent_page_id</code> is null</li> <li>for each row, if <code>parent_page_id</code> is (still) null, yield a <code>Request</code> with callback <code>scrape_page</code></li> <li><code>[scrape_page]</code> if this ...
<python><scrapy>
2025-07-09 21:43:11
0
1,513
user1713450
79,696,174
1,056,563
How to use mpld3.display() within ipython?
<p>I am running an example for <em>mplde3</em>: how to show it?</p> <pre class="lang-py prettyprint-override"><code>import mpld3 from mpld3 import plugins from mpld3.utils import get_id import numpy as np import collections import matplotlib.pyplot as plt mpld3.enable_notebook() N_paths = 5 N_steps = 100 x = np.linsp...
<python><mpld3>
2025-07-09 19:44:11
1
63,891
WestCoastProjects
79,696,142
2,250,791
How to use the type of another method's parameter as the type of my method's parameter?
<p>If I have something like this:</p> <pre><code>def _process(img: str | List[str] | ndarray[_AnyShape, dtype[Any]] | List[ndarray[_AnyShape, dtype[Any]]]) -&gt; None: … type TextInputs = ??? def process(img: TextInputs) -&gt; None: _process(img) </code></pre> <p>Where <code>_process</code> is defined in a 3rd...
<python><python-typing>
2025-07-09 19:09:22
0
2,075
Camden Narzt
79,696,122
14,305,251
UnicodeDecodeError when connecting to PostgreSQL using psycopg2, despite UTF-8 encoding everywhere
<p>I'm trying to connect to a local PostgreSQL database using psycopg2 in Python. Here's the code I'm using:</p> <pre><code>import psycopg2 params = { 'dbname': 'database_name', 'user': 'user_name', 'password': 'mypassword', 'host': 'localhost', } for k, v in params...
<python><django><database><postgresql>
2025-07-09 18:50:19
0
379
the star
79,696,110
1,747,834
Why is watchdog event-handler trying to open every new file?
<p>The simple directory-watching script is below:</p> <pre class="lang-py prettyprint-override"><code>import logging import sys import time from watchdog.events import FileSystemEventHandler from watchdog.observers import Observer class MyEventHandler(FileSystemEventHandler): def __init__(self, observer, log): ...
<python><python-watchdog><kqueue>
2025-07-09 18:39:23
0
4,246
Mikhail T.
79,696,095
14,944,414
Ordering points that roughly follow the contour of a line to form a polygon
<p>I have a list of points (x,y). A line is drawn somewhere 'inside' these points (within the area they form). I have been trying different algorithms for ordering these points to create a polygon, with these constraints:</p> <ol> <li>The polygon is not self-intersecting.</li> <li>The resulting polygon is not necessari...
<python><algorithm><polygon><concave>
2025-07-09 18:28:39
3
307
Leo
79,696,021
13,682,559
Pyright false positive when implementing a protocol
<p>This MRE illustrates my problem:</p> <pre class="lang-py prettyprint-override"><code>from dataclasses import dataclass from typing import Protocol class Child(Protocol): val: float class Parent(Protocol): sub: Child @dataclass class Child1(Child): val: float @dataclass class Parent1(Parent): sub...
<python><python-typing><mypy><pyright>
2025-07-09 17:27:51
1
1,108
Durtal
79,695,981
5,348,895
How to assign subgraph IDs based on weakly connected user pairs, but split when no shared connection exists
<p>I'm working with a dataset where I want to assign a sub_graph ID to user interactions. Each row in the data represents a directed edge between an actor_user_id and a related_user_id.</p> <p>I want to compute a sub_graph ID such that:</p> <p>Rows belong to the same sub_graph if they are connected (even indirectly) th...
<python><pandas><networkx>
2025-07-09 16:41:24
1
376
patrick
79,695,854
113,158
How do I "sign" a JWT using HMAC-SHA256 with a public key (RSA or EC) in order to trigger algorithm confusion?
<p>I am trying to understand exactly how exactly it is possible to trigger JWT algorithm confusion, as described in <a href="https://redfoxsec.com/blog/jwt-deep-dive-into-algorithm-confusion/" rel="nofollow noreferrer">https://redfoxsec.com/blog/jwt-deep-dive-into-algorithm-confusion/</a> - in section &quot;How does Al...
<python><jwt><jwcrypto>
2025-07-09 15:00:56
1
16,863
Jean Hominal
79,695,783
20,591,261
Ranking categories by count within groups in Polars
<p>I have a Polars DataFrame with months, categories, and IDs. I want to rank categories by their frequency within each month, then pivot the results to show which category held each rank position in each month.</p> <p>My dataframe:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl df = pl.DataFr...
<python><dataframe><pivot><python-polars>
2025-07-09 14:17:01
1
1,195
Simon
79,695,735
13,801,302
Dynamic and scalable MCP Server infrastructure in docker
<p>I have the following structure of my MCP Server projekt</p> <p><em>Folder structure</em></p> <pre><code>project-root/ β”‚ β”œβ”€β”€ prompts/ β”‚ β”œβ”€β”€ resources/ β”‚ β”œβ”€β”€ tools/ β”‚ └── add.py β”‚ β”œβ”€β”€ mcp_server.py β”‚ β””-- main.py </code></pre> <p><em>mcp_server.py</em></p> <pre class="lang-py prettyprint-override"><code>from fastm...
<python><docker><agent><model-context-protocol>
2025-07-09 13:45:34
1
621
Christian01
79,695,675
12,439,683
How to forcefully terminate a running Python test in VSCode
<p>Closely related to my question is <a href="https://stackoverflow.com/q/71803409/12439683">VSCode: how to interrupt a running Python test?</a>, however in my case the standard method of pressing the square in the <em>Test Results</em> tap does not work.</p> <p>What is different in my tests?</p> <p>I have code that vi...
<python><visual-studio-code><debugging><python-unittest><ray>
2025-07-09 13:08:26
1
5,101
Daraan
79,695,585
4,505,998
Matplotlib Engformatter base 2
<p>I am plotting some running time vs. data size. The x axis is logarithmic in base 2, but when I try to use <a href="https://matplotlib.org/stable/api/ticker_api.html#matplotlib.ticker.EngFormatter" rel="nofollow noreferrer">EngFormatter</a>, I get the values in base 10.</p> <p>Is it possible to get the values in base...
<python><matplotlib>
2025-07-09 12:06:15
1
813
David DavΓ³
79,695,557
6,930,340
How to resize/fit Altair chart in Quarto dashboard container?
<p>The Quarto <a href="https://quarto.org/docs/dashboards/data-display.html#plots" rel="nofollow noreferrer">docs</a> state that Altair charts resize themselves to fit their container within dashboards.</p> <p>My experience is that this is true for <code>alt.Chart()</code>, but not if I concatenate multiple charts via ...
<python><altair><quarto>
2025-07-09 11:40:12
0
5,167
Andi
79,695,544
922,712
Installing an older version of selenium with Python3 on Ubuntu with an externally-managed-environment
<p>I am on the following Ubuntu version on WSL</p> <pre><code>Distributor ID: Ubuntu Description: Ubuntu 24.04.2 LTS Release: 24.04 Codename: noble </code></pre> <p>I am running Python 3.12.3</p> <p>I need to install selenium 4.2.0 or 4.2.1</p> <p>I have admin rights on the machine</p> <p>When I try to ...
<python><python-3.x><ubuntu><selenium-webdriver><installation>
2025-07-09 11:33:31
1
14,081
user93353
79,695,261
2,083,756
Running MCP Server from py web view app on a diffreent thread after packaging
<p>I have Py Web View app and I need to run an MCP server in the backround. <br/> I am using MultiProcessing. <br/> In a python environment, everything works fine. <br/> I want it to package it as an exe, and I am using pyinstaller for that matter. <br/> The packaging process completes without error. <br/> My issue is ...
<python><pyinstaller><model-context-protocol>
2025-07-09 07:44:36
0
306
Moutabreath
79,695,252
6,936,582
Position an axis at a point location
<p>I have a plot with a line graph. I need to place a new axis at a point/coordinate and plot a pie chart on the new axis so the pie is centered on the point.</p> <pre><code>import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(6, 3)) ax.set_xlim(0,16) ax.set_ylim(8,12) #...
<python><matplotlib>
2025-07-09 07:36:47
1
2,220
Bera
79,695,194
2,081,568
Find field throwing error in Python Dataclass conversion
<p>I'm trying to convert a json array to a Python list of typed objects. It's data from Teltonika FOTA</p> <p>The call <code>result_list = fromlist(FotaDevice, intermediate_list)</code> is failing with the error message <strong>TypeError: strptime() argument 1 must be str, not None</strong></p> <p>imports are:</p> <pr...
<python><python-dataclasses><dataclass-wizard>
2025-07-09 06:50:40
1
1,111
Hecatonchires
79,695,154
13,825,658
Why does variance inference for type parameters include `__init__`?
<p>From the official <a href="https://typing.python.org/en/latest/spec/generics.html#variance-inference" rel="nofollow noreferrer">docs</a>:</p> <blockquote> <p>The introduction of explicit syntax for generic classes in Python 3.12 eliminates the need for variance to be specified for type parameters. Instead, type chec...
<python><generics><python-typing><covariance>
2025-07-09 06:22:01
1
1,368
Leonardus Chen
79,695,141
4,423,300
csv file wide to long. Float value gets truncated and getting integer for index column
<p>I have csv file with approx 40K rows and 1200 columns in wide format. with looks something like this:</p> <pre><code>| Millisec_diff | Value1 | Value2 | Value3 | | ------------- | ------ | ------ |------- | | 0 | 100 | 200 | 1.3 | | 0.005 | 101 | 20.1 | 1.3 | | 0.01 | 1...
<python><pandas><melt><pandas-melt>
2025-07-09 06:14:02
1
637
SheCodes
79,695,102
4,423,300
Pandas create date time column based on other column with relative milliseconds time
<p>My original data csv file columns looks like this:</p> <pre><code>| Millisec_diff | Value1 | Value2 | | ------------- | ------ | ------ | | 0 | 100 | 200 | | 0.005 | 101 | 20.1 | | 0.01 | 103 | 20.1 | | 0.015 | 104 | 24.1 | | 0.02 | 103 | 40.1 |...
<python><pandas><datetime><time-difference>
2025-07-09 05:11:53
1
637
SheCodes
79,694,783
7,453,703
Streamlit data_editor won't update data
<p>I am trying to have a data_editor in streamlit that can handle automatic changes from users. The idea, is that user will update a column value and automatically the change will be displayed triggering a calculation within the table. In my example, it should days to expire for a financial option. Pretty much like exc...
<python><streamlit>
2025-07-08 20:11:27
1
405
pbou
79,694,410
8,297,745
How to use Django Q objects with ~Q() inside annotate(filter=...) to exclude a value?
<p>I'm refactoring a legacy Django Job to use <code>annotate</code> with filtered <code>Count</code> aggregations instead of querying each record individually (avoiding the N+1 problem).</p> <p>I want to count the number of related <code>EventReport</code> objects per <code>Store</code>, excluding those where <code>sta...
<python><django><django-models><django-queryset><django-orm>
2025-07-08 14:30:37
1
849
Raul Chiarella
79,694,363
1,833,563
What are the benefits of using an annotated class vs. a dict[str, Any] in the declaration of an MCP tool?
<p>FastMCP's <a href="https://gofastmcp.com/servers/tools#return-values" rel="nofollow noreferrer">documentation</a> states that:</p> <blockquote> <p>When you add return type annotations, FastMCP automatically generates output schemas to validate the structured data and enables clients to deserialize results back to Py...
<python><pydantic><model-context-protocol>
2025-07-08 13:59:14
1
1,476
omer
79,694,308
7,408,848
extended mapfield results in error when updating a doc - mongoengine
<p>I am trying to write an enhanced field for mongoengine mapfield where it takes a defined enum and tracks the selection. Ideally, it locates and presents the enum when in python but saves the defined code when in mongodb. The code works well when saving the document initially but for some reason when I try to make mo...
<python><mongoengine>
2025-07-08 13:14:19
0
1,111
Hojo.Timberwolf
79,694,270
18,814,386
How can I exclude a column from a heatmap?
<p>I have a pivoted dataframe and want to plot a heatmap in Plotly. I have a total column, making it hard to use a color scale.</p> <pre><code>import numpy as np import pandas as pd import plotly.express as px city_origin = ['London', 'Tokio', 'Seoul', 'Paris', 'Tashkent', 'Washington', 'Moscow'] city_current = ['Lon...
<python><pandas><plotly><heatmap>
2025-07-08 12:50:38
2
394
Ranger
79,694,234
10,277,250
Does FastAPI still need Gunicorn?
<p>For a long time Gunicorn+Uvicorn was the default setup for running FastAPI in production. However, I recently came across a <a href="https://blueshoe.io/blog/fastapi-in-production/" rel="nofollow noreferrer">blog post</a> saying:</p> <blockquote> <p>In the meantime, this combination of Gunicorn and Uvicorn is no lon...
<python><fastapi><gunicorn><uvicorn><asgi>
2025-07-08 12:28:57
1
363
Abionics
79,694,189
4,404,699
matplotlib widget on jupyter notebook, dropdown menu working but not showing
<p>I wanted to test the code from <a href="https://stackoverflow.com/questions/61468175/dropdown-widget-python">this previous post</a> because I have a trouble to visualize my dropdown menu.</p> <p>I use pycharm, and add the code found in the answer of the post above in a Jupyter notebook. As you can see in the printsc...
<python><matplotlib><widget><jupyter><ipywidgets>
2025-07-08 11:54:13
0
1,457
tuttifolies
79,694,182
2,090,453
Memory Not Released After Each Request Despite Cleanup Attempts
<p>We're running a FastAPI service that fetches data from Trino, processes it using PyArrow and Polars, and uploads the result to AWS S3 in Parquet format. However, we're facing a persistent issue where memory is not released after each request, even after explicitly attempting cleanup.</p> <p>Architecture overview:</p...
<python><fastapi><python-polars><pyarrow>
2025-07-08 11:50:34
1
4,058
DonOfDen
79,694,305
7,282,437
Efficiently Computing Mean Pairwise Distances in an Array
<p>Suppose we have observations <span class="math-container">$\{y_i\}_{i=1}^{n}$</span>. I would like to compute the average pairwise distance defined by: <span class="math-container">$$ D = \frac{1}{n^2}\sum_{i=1}^{n}\sum_{j=1}^{n} |y_i - y_j| $$</span> This computation is done repeatedly in a loop, so optimizing it f...
<python><distance>
2025-07-08 11:38:07
1
389
Adam
79,693,791
9,257,294
Why is Dash ignoring the HOST environment variable?
<p>I have this minimal Dash app:</p> <pre><code>import os import dash from dash import html app = dash.Dash(__name__) app.layout = html.Div(&quot;Hello Dash!&quot;) print(f'{os.environ[&quot;HOST&quot;]=}') app.run() </code></pre> <p>The environment variable <code>HOST</code> is set to <code>0.0.0.0</code>. Accordi...
<python><docker><environment-variables><plotly-dash><jupyter-lab>
2025-07-08 07:01:31
1
1,129
mckbrd
79,693,681
14,271,017
In Python, How to run two statistical tests on all numeric columns
<p>I have a dataframe <code>df</code>, I want to do the following:</p> <ol> <li>run two stats tests on all the numeric columns (<code>column_1</code> to <code>column_84</code>) to compare if there is a statistical difference between Types <code>X</code>, <code>Y</code> and <code>Z</code></li> </ol> <ul> <li><p>The stat...
<python><pandas><numpy><scipy><scikits>
2025-07-08 05:02:35
1
319
RayX500
79,693,617
10,794,031
How to read [project.urls] metadata inside a project's entry point?
<p>Using <code>pyproject.toml</code> I wanted to read its <a href="https://packaging.python.org/en/latest/guides/writing-pyproject-toml/#urls" rel="nofollow noreferrer"><code>[project.urls]</code></a> from inside a script launched by one of the package's entry points. So using <a href="https://packaging.python.org/en/l...
<python><pyproject.toml>
2025-07-08 03:16:41
1
13,254
bad_coder
79,693,602
10,737,147
polar plot -- sin transformation
<p>I want to plot a very simple function that would look like a simple sinusoidal f(x) = r + n* sin(n*x) in a Cartesian coordinate plane.</p> <p>Given this, now I want to plot this in a polar plot -- ideally as a sin wave along a circular path.</p> <p>This is my code</p> <pre><code>import numpy as np import matplotlib....
<python><matplotlib><trigonometry>
2025-07-08 02:42:16
1
437
XYZ
79,693,413
430,766
Why is the fastest way to print a list of ints so unintuitive?
<p>I have a <code>list</code> of <code>int</code>s (<code>ints</code>) and I want to print each one in their own line as fast as possible.</p> <p>My first shot was this:</p> <pre><code>list(map(print,ints)) </code></pre> <p>and running it on 10<sup>7</sup> ints together with a function to read them from standard in thi...
<python><performance><optimization><language-implementation>
2025-07-07 21:02:47
2
35,164
bitmask
79,693,348
3,605,534
How to add an image to a page_navbar?
<p>I have a Shiny Python App in which I want to add an image as a logo on the menu's left hand side. I created my www folder and I saved the logo.png file there. I don't know why I cannot see the image when loading my Shiny App. I share the code as follows:</p> <pre><code>from shiny import App, ui app_ui = ui.page_nav...
<python><py-shiny>
2025-07-07 19:49:12
1
945
GSandro_Strongs
79,693,288
19,270,168
YouTube Videos.list API has drastic delays when called by requests.get
<pre class="lang-py prettyprint-override"><code>def validate_youtube_video(link:str, sessionid:str) -&gt; Tuple[bool, str]: # Returns (status, sanitized_link|error_message) import urllib.parse res = urllib.parse.urlparse(link) vidid = None if res.netloc == 'www.youtube.com' and res.path == '/watch': queri...
<python><youtube><youtube-api><youtube-data-api>
2025-07-07 18:34:29
1
1,196
openwld
79,693,271
1,520,228
How to point Conda at a specific, non-standard, pre-existing python installation
<p>I feel like I am asking for a hack, but I want to be sure before I look into other options.</p> <p>I am trying to use conda to build, repeatable environments on a given user's machine. For most uses everything works fine, however, when working with game engines or DCCs (digital content creation tools, maya, blender,...
<python><anaconda><conda>
2025-07-07 18:10:46
1
1,786
TheBeardedBerry
79,693,239
10,242,281
How can I call Python script on remote server with xp_cmdshell?
<p>Trying to call python script on <code>ServerB</code> from local server and getting this error like below, searched all about this error, figured out that it's about env variables, but not clear where in <code>xp_cmdshell</code> to change this setting. This is existing legacy process which uses <code>EXEC sp_executes...
<python><xp-cmdshell>
2025-07-07 17:44:17
0
504
Mich28
79,693,052
11,505,680
Windows CreateMutexW using Python not working
<p>I'm writing a Python application that connects to an external device. I want to enable the user to operate multiple devices simultaneously by running multiple instances of the application, but each device may only connect to one application instance. This calls for a mutex keyed to the device's serial number. With t...
<python><windows><mutex>
2025-07-07 15:02:55
1
645
Ilya