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,434,549
1,940,534
trying to pull an value out of xml using xml.etree.ElementTree
<p>I have the following xml:</p> <pre><code>&lt;multi-routing-engine-results&gt; &lt;multi-routing-engine-item&gt; &lt;re-name&gt;node0&lt;/re-name&gt; &lt;source-resource-usage-pool-information&gt; &lt;resource-usage-entry style=&quot;all-pat-pool&quot;&gt; &lt;resource-...
<python><xml><elementtree>
2025-02-12 21:49:49
2
1,217
robm
79,434,486
1,324,631
How to apply regular expressions to practical non-text state machine logic?
<p>I'm trying to implement some logic within a system of microcontroller IRQs and event callbacks, that fundamentally require the use of a complex state machine in order to behave correctly.</p> <p>Regular expressions, as a concept, are a method of compactly and efficiently representing and reasoning about finite state...
<python><c><regex><interrupt><computation-theory>
2025-02-12 21:24:13
0
4,212
AJMansfield
79,434,379
2,978,125
How to distribute multiple variations of a package on PyPI?
<p>I have a Python package with two variations: a CPU-only, and a GPU-enabled build. I would like to distribute both versions on PyPI, where users could maybe do something like the following (it doesn't have to be this exact syntax, as long as its reasonably easy to work with for users, it's OK):</p> <p><code>pip insta...
<python><pip><pypi>
2025-02-12 20:32:55
0
484
user2978125
79,434,251
25,625,672
Split zip-nonzip submodules within one cx_freeze package
<p>I am (basically successfully) using cx_freeze to package a Python application that requires Pandas. Pandas is the only package I need that cannot go into cx_freeze's library zip. Specifically, I need to exclude this submodule:</p> <pre class="lang-ini prettyprint-override"><code>[tool.cxfreeze.build_exe] packages = ...
<python><cx-freeze><software-distribution>
2025-02-12 19:35:51
0
601
avigt
79,434,242
5,921,344
Merging Two DataFrames with Overlapping Components While Preserving Original Order
<p>I have two dataframes like below. Some of the <code>area1_name</code> and <code>area2_name</code> overlap, and I'm trying to combine the two area names into one long list.</p> <pre><code>df1 = pd.DataFrame({'area1_index': [0,1,2,3,4,5], 'area1_name': ['AL','AK','AZ','AR','CA','CO']}) df2 = pd.DataFrame({'area2_inde...
<python><pandas>
2025-02-12 19:33:07
3
375
Jen
79,434,176
7,897,042
Type hinting of subclass
<p>Given a subclass that overrides attributes and methods, is there a convention in Python related to type hinting explicit params (in the case you forgo using <code>*args</code> and/or <code>**kwargs</code>) and return types that are already type hinted in the base class? Meaning is there the expectation that subclass...
<python>
2025-02-12 19:02:41
1
384
mptrossbach
79,433,905
2,925,620
pyqtgraph: Show x axis labels in the form DD HH:MM:SS of data representing timedeltas with DateAxisItem
<p>I am trying to use pyqtgraphs <code>DateAxisItem</code> for relative times on the x axis, i.e., durations (which can be between a few hours and several days). I know I could simply use an ordinary <code>AxisItem</code> and show the durations of the type <code>datetime.timedelta</code> in seconds (see the MWE below)....
<python><python-datetime><timedelta><pyqtgraph>
2025-02-12 17:08:32
0
357
emma
79,433,640
28,904,207
Python: Deep Q Learning agent doesn't seem to learn
<p>I am using <strong>gymnasium</strong> and <strong>torch</strong>. I initially created a custom environment by following the <a href="https://gymnasium.farama.org/introduction/create_custom_env/" rel="nofollow noreferrer">official gymnasium's guide</a>: it shows you how to build a NxN <code>Box</code> where the agent...
<python><deep-learning><pytorch><agent><gymnasium>
2025-02-12 15:35:52
0
305
tommat208
79,433,460
865,169
Can I define a Pandas DataFrame GroupBy aggregation involving multiple columns?
<p>I have experimented and read the documentation for <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.aggregate.html" rel="nofollow noreferrer">DataFrameGroupBy.aggregate</a>, but it is not clear to me whether - and how I can define an aggregation that works on m...
<python><pandas><dataframe>
2025-02-12 14:36:53
1
1,372
Thomas Arildsen
79,433,458
6,681,932
lightgbm force variables to be in splits
<p>Im trying to find a way to train a lightgbm model forcing to have some features to be in the splits, i.e.: &quot;to be in the feature importance&quot;, then the predictions are afected by these variables.</p> <p>Here is an example of a the modeling code with an usless variable as it is constant, but the idea is that...
<python><machine-learning><lightgbm><ensemble-learning>
2025-02-12 14:36:26
1
478
PeCaDe
79,433,308
11,460,896
The thread running under multiprocessing.Process does not update its instance attributes
<p>I want to run several class instances in parallel and update the instance attributes using Redis. On each class instance, I run a thread in the background to listen to redis for changes. When I run <code>set value 9</code> in redis, the thread detects the change, but the self.value attribute is not updated.</p> <pre...
<python><multithreading><memory-management><parallel-processing><multiprocessing>
2025-02-12 13:50:27
1
307
birdalugur
79,433,213
2,920,612
Display icon in Status Bar and SysTray
<p>I'm creating an app in Python that should run in the background, executing tasks over a period of time.</p> <p>To help the user get the current version of the app and even to close it, I thought about placing an icon in SysTray (Windows/Linux) and in the Menu Bar (macOS).</p> <p>I even managed to make it display, bu...
<python>
2025-02-12 13:18:47
1
779
Tom
79,433,165
6,877,252
Gradient computation with PyTorch autograd with 1st and 2nd order derivatives does not work
<p>I am having a weird issue with PyTorch's autograd functionality when implementing a custom loss calculation on a second order differential equation. In the code below, predictions of the neural network are checked if they satisfy a second order differential equation. This works fine. However, when I want to calculat...
<python><math><pytorch><autograd>
2025-02-12 13:05:04
1
1,759
Wout Rombouts
79,433,136
902,769
Synapse notebook script runs fine but stops on time-out and stucks queued in pipelines
<p>I have a python script in a notebook that performs a parquet file schema correction. It is working fine, runs in less than 10 seconds, depending on the number of files to process. Not exactly fine, more on this later below.</p> <p>Now I need to run it in a pipeline that correct dataset schemas and then send the data...
<python><azure-synapse><spark-notebook><azure-synapse-pipeline>
2025-02-12 12:56:40
1
1,175
Ricker Silva
79,433,015
29,295,031
How to make streamlit session_state updated when I select a point on plotly_chart
<p>I have this use case where I have a plotlychart :</p> <pre><code>import streamlit as st import plotly.express as px if &quot;var&quot; not in st.session_state: st.session_state[&quot;var&quot;] = 0 col3,col4 = st.columns(2) def plot(): df = px.data.iris() fig = px.scatter( df, x=&quot;sepal_w...
<python><plotly><streamlit>
2025-02-12 12:18:44
0
401
user29295031
79,433,014
5,118,421
What is the difference between ConfigDict and dict?
<p>What is the difference between <code>ConfigDict</code> and <code>dict</code>?</p> <pre class="lang-py prettyprint-override"><code>ConfigDict: TypeAlias = dict[str, Union[str, list[str]]] </code></pre> <p>What are the advantages of using <code>ConfigDict</code>?</p> <p><a href="https://github.com/pytest-dev/pytest/pu...
<python><dictionary><pytest>
2025-02-12 12:18:34
1
1,407
Irina
79,432,925
2,176,819
Load UWP icon programmatically
<p>I'm writing a <a href="https://github.com/gridranger/progman.py" rel="nofollow noreferrer">Python-based launcher</a> that is automatically populated form Windows' Start menu. I plan to extend it to include UWP apps. Listing and launching them isn't hard, but accessing their icons seems to be tricky.</p> <p>As the ap...
<python><windows><uwp><icons>
2025-02-12 11:43:09
1
403
gridranger
79,432,856
884,463
When I create an array of Numpy floats, I get an array of Python floats
<p>The code:</p> <pre class="lang-py prettyprint-override"><code>import sys import numpy as np print(f&quot;We are using Python {sys.version}&quot;, file=sys.stderr) print(f&quot;We are using numpy version {np.__version__}&quot;, file=sys.stderr) # 2.2.1 def find_non_numpy_floats(x: any) -&gt; bool: if not (isin...
<python><numpy><type-conversion>
2025-02-12 11:17:16
2
15,375
David Tonhofer
79,432,808
1,150,683
Understanding Wikipedia titles batching API
<p>With the MediaWiki API we can <a href="https://www.mediawiki.org/w/api.php?action=help&amp;modules=query" rel="nofollow noreferrer">query</a> the Wikipedia API. One of the fields is <code>titles</code> where one <em>or more</em> titles can be queried at the same time. Batching them together is recommended in high lo...
<python><python-requests><wikipedia-api><mediawiki-api><batching>
2025-02-12 11:02:00
1
28,776
Bram Vanroy
79,432,772
16,906,505
sql alchemy constructor typesafety
<p>in order to have type safety in SQLAlchemy, do I need to define custom constructors for each model? With the current setup there is no type safety at all when creating an object</p> <pre><code>from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column class Base(DeclarativeBase): pass class User(Base)...
<python><sqlalchemy><python-typing>
2025-02-12 10:49:49
1
500
RheinmetallSkorpion
79,432,485
5,137,645
list the files in sagemaker estimator or processor
<p>Is there a way to have the sagemaker estimator or processor print out a list of files that it has in a certain directory without introducing custom scripts to them? Or if a custom script has to to be introduced how do I do it while still running the original transfer_learning.py script.</p>
<python><amazon-sagemaker>
2025-02-12 09:12:16
0
606
Nikita Belooussov
79,432,237
1,319,998
Can a KeyboardInterrupt be raised during the handling of a KeyboardInterrupt?
<p>If we have the following code:</p> <pre class="lang-py prettyprint-override"><code>try: long_running_thing() finally: # Some cleanup </code></pre> <p>And if we're just considering the <code>finally</code> block running because the user pressed CTRL+C and so KeyboardInterrupt was raised in <code>long_running_th...
<python><exception><signals>
2025-02-12 07:15:49
2
27,302
Michal Charemza
79,432,047
2,955,827
How to call helper functions from task.external_python in dag without set sys.path everytime?
<p>I have a helper function need to run in every task to init environment.</p> <p>The problem is, task can not access any variable out of it self's scope. So I have to add the same code to the beginning of every task, like:</p> <pre class="lang-py prettyprint-override"><code>@task.external_python( python=v_python_p...
<python><airflow>
2025-02-12 05:37:55
0
3,295
PaleNeutron
79,431,967
7,619,353
Python How to convert complex nested classes into dictionary
<p>I have a couple of classes instantiate basic types like str, int, float, list, dict's but also other classes that contains similar types. Essentially I have nested layers of objects. It is converted this way so data can be represented as objects and manipulated later. Once all the processing is done I want to export...
<python><python-3.x><dictionary><recursion>
2025-02-12 04:43:23
2
1,840
tyleax
79,431,910
1,084,875
Can't send a NumPy array larger than 2 GB with ZeroMQ
<p>I'm using the Python code shown below to serialize and send a NumPy array from the client to the server using ZeroMQ. I noticed that when the NumPy array is larger than 2 GB the client seems to stall when sending the array. For example, in the <code>client.py</code> code shown below, if you use <code>n = 17000</code...
<python><numpy><zeromq><pyzmq>
2025-02-12 03:59:27
1
9,246
wigging
79,431,607
2,077,386
Python type annotation for unique value representing 'not undefined'
<p>There is an idiom in Python to do something like,</p> <pre><code>UNDEFINED = object() def do_something(value=UNDEFINED): if value is UNDEFINED: do1() else if value is None: do2() else: do3() </code></pre> <p>The point being that <code>None</code> may be a valid value and <code>UN...
<python><python-typing><mypy>
2025-02-12 00:14:05
0
7,133
rrauenza
79,431,510
2,882,380
Python in Excel: How to print output dataframe to a tab
<p>I am experimenting on the new Python in Excel feature. I wrote the following lines in a cell.</p> <pre><code>import pandas as pd input_df = pd.DataFrame(xl(&quot;A6:ASH38&quot;, headers=True)) input_header = list(input_df.columns.values) label_col = input_header[:14] value_col = input_header[14:] output_df = input_d...
<python><excel>
2025-02-11 22:53:41
0
1,231
LaTeXFan
79,431,483
15,842
Polars selectors for columns that are Nested Types
<p>Some Polars operations, such as <code>.sort()</code> fail when passed a column with a Nested Type.</p> <p>This (sensible) choice about sort means I cannot use my usual sorting pattern of <code>df.sort(pl.all())</code>.</p> <pre class="lang-py prettyprint-override"><code>import polars as pl NESTED_TYPES = [ pl.Li...
<python><python-polars>
2025-02-11 22:38:45
1
21,402
Gregg Lind
79,431,447
4,913,592
Gradient Lost When Constructing a Matrix in Mitsuba 3
<p>I am trying to optimize the absolute scale of an area light in Mitsuba 3.</p> <p>I'm doing a simple toy example where I start with a scene like this:</p> <p><a href="https://i.sstatic.net/oXy670A4.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/oXy670A4.png" alt="enter image description here" /></a></...
<python><machine-learning><graphics><3d><mitsuba-renderer>
2025-02-11 22:10:15
1
351
Anson Savage
79,431,380
11,551,386
polars python - list version of search_sorted / filter and sort in one function
<p>I am trying to make a function that takes a <code>df</code> and filters and re-arranges rows where the elements of a specified column <code>c</code> are explicitly specified by a list <code>l</code>. The filtering aspect works as expected, but the sorting is not what I expect.</p> <p>The <code>search_sorted</code> m...
<python><python-polars>
2025-02-11 21:37:13
1
344
likethevegetable
79,431,296
265,521
Cross-platform command to activate venv
<p>Is there a way to activate a Python venv with one command that works on Windows and Unix?</p> <p>The standard commands are:</p> <ul> <li>Windows: <code>venv\Scripts\Activate.ps1</code></li> <li>Unix: <code>source venv/activate</code></li> </ul> <p>(There's a handy table of all the options <a href="https://docs.pytho...
<python><python-venv>
2025-02-11 20:59:00
0
98,971
Timmmm
79,431,220
782,392
Why does TextIOWrapper.seek() not use the buffer?
<p>I just noticed that whenever I use <code>seek()</code> on a <code>TextIOWrapper</code> object, the performance decreases noticeably.</p> <p>The following code opens a text file (should be of size between 10 and 50 MB) reads one line of code and then calls seek with a position before the last line. Then reads another...
<python><python-3.x>
2025-02-11 20:19:38
2
2,674
T3rm1
79,431,134
1,492,613
torch cannot add NamedTuple class to safe_globals
<p>I define some named tuple like this:</p> <pre><code>class checkpoint_t(NamedTuple): epoch: int model_state_dict: Dict[str, Any] optimizer_state_dict: Dict[str, Any] model_name: str | None = None </code></pre> <p>However I after save I cannot load this namedtuple via</p> <pre><code>import torch from ...
<python><pytorch>
2025-02-11 19:25:40
1
8,402
Wang
79,431,023
513,904
Tracing CustomMaskWarning to its source
<p>I am working with old TensorFlow (2.7) and Java Tensorflow but the answer may still help others tracing similar issues. My model produces the error when saved to the 2.7 save() format:</p> <pre><code>CustomMaskWarning: Custom mask layers require a config and must override get_config. When loading, the custom mask la...
<python><java><tensorflow>
2025-02-11 18:41:07
1
1,473
Eli S
79,430,893
20,302,906
How to assert an http.client.HTTPSConnection.request
<p>My code tries to make HTTP requests to Gitlab API to make different actions such as create projects, branches, milestones etc. I'm not using external modules like <a href="https://requests.readthedocs.io/en/latest/" rel="nofollow noreferrer">requests</a> because I want to keep my project free of dependencies and I h...
<python><http><mocking><python-unittest>
2025-02-11 17:43:45
2
367
wavesinaroom
79,430,769
696,264
Mysql 5.5..33 : (5010, "Authentication plugin 'mysql_old_password' couldn't be found in restricted_auth plugin list.")
<p>When I am trying to connect the MySQL db that hosted in remote via the python library MySQLdb, I am getting the following error.</p> <p><code>(5010, &quot;Authentication plugin 'mysql_old_password' couldn't be found in restricted_auth plugin list.&quot;)</code></p> <p><strong>Python Code</strong></p> <pre><code>impo...
<python><mysql><mysql-python>
2025-02-11 17:01:09
0
1,321
Madhan
79,430,731
12,115,498
Unable to launch Jupyter Notebook or update Anaconda
<p>I've been writing Python programs in Jupyter notebooks on my Windows 11 computer without any problems for the last few months, but today everything is suddenly not working: I tried to launch Jupyter Notebook from a <a href="https://medium.com/@msc.noguez/launch-jupyter-notebook-with-a-shortcut-windows-10-725e2b07b69...
<python><jupyter-notebook><anaconda><conda><spyder>
2025-02-11 16:45:43
0
783
Leonidas
79,430,573
8,188,435
How to make xarray.DataArray.to_zarr readable by napari?
<p>I have big TIFF-arrays that I want to save with xarray and view in napari. However, napari seems unable to read the zarr-format produced by xarray. Is there a way that I can specify the arguments of xarray.DataArray.to_zarr to make it readable by napari?</p> <p>I know that dask.array.to_zarr is an option but I would...
<python><python-3.x><python-xarray><zarr><python-napari>
2025-02-11 15:53:41
1
371
user8188435
79,430,458
11,402,025
Run sam applications using podman instead of docker on mac Ventura
<pre><code>podman version Client: Podman Engine Version: 5.3.2 API Version: 5.3.2 Go Version: go1.23.5 Built: Tue Jan 21 13:41:34 2025 OS/Arch: darwin/arm64 Server: Podman Engine Version: 5.3.2 API Version: 5.3.2 Go Version: go1.23.4 Built: Tue Jan 21 19:00:00 2025 OS/Arc...
<python><docker><podman><sam><podman-compose>
2025-02-11 15:16:14
0
1,712
Tanu
79,430,379
9,140
How can I get uv to Git pull dependencies on uv sync?
<p>In uv, I want to add a Git repository as a dependency which is easy in itself, but if we commit in the Git repository of the dependency, I want <code>uv sync</code> to do a Git pull for this Git repository. Basically, do a Git pull on the dependency Git repository and then apply the changed code for the dependency ...
<python><uv>
2025-02-11 14:47:44
1
5,498
EtienneT
79,430,288
2,951,942
install ansible in official jenkins docker container without rebuild?
<p>I've been setting up the official Jenkins docker container in my lab, and I'm installing Ansible (and also Python if possible) as plugins.</p> <p>I've installed the Ansible plugin and I need to setup/install the binary. I'm trying to utilise the functionality to &quot;Install plugin via script&quot; which I think bu...
<python><docker><jenkins><ansible><jenkins-plugins>
2025-02-11 14:18:24
2
571
Kareem
79,430,185
7,959,614
Generate all paths that consists of specified number of visits of nodes / edges
<p>In a graph/chain there are 3 different states: <code>ST</code>, <code>GRC_i</code> and <code>GRC_j</code>. The following edges between the states exists:</p> <pre><code>EDGES = [ # source, target, name ('ST', 'GRC_i', 'TDL_i'), ('ST', 'GRC_j', 'TDL_j'), ('GRC_i', 'GRC_j', 'RVL_j'), ('GRC_j...
<python><networkx><mixed-integer-programming>
2025-02-11 13:43:22
2
406
HJA24
79,429,531
14,282,714
Select the first and last row per group in Polars dataframe
<p>I'm trying to use <code>polars</code> dataframe where I would like to select the <code>first</code> and <code>last</code> row per group. Here is a simple example selecting the first row per group:</p> <pre><code>import polars as pl df = pl.DataFrame( { &quot;a&quot;: [1, 2, 2, 3, 4, 5], &quot;b&...
<python><dataframe><python-polars>
2025-02-11 09:57:15
3
42,724
Quinten
79,429,313
25,413,271
Python: Numpy shape typing
<p>I have a class with one method:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import numpy.typing as npt import pyvista as pv from typing import Tuple, TypeVar, Literal class SurfaceTriangleMesh: int_type = TypeVar(&quot;int_type&quot;, bound=int) flt_type = TypeVar(&quot;flt_...
<python><numpy><python-typing>
2025-02-11 08:28:13
0
439
IzaeDA
79,429,020
21,127,400
Is there a Python interpreter with type checking (with anottations) support
<p>I use <code>mypy</code> to check type related errors before running my code. It's really good, but it cannot check in runtime.</p> <p>But in some projects I use dynamic variables and mypy cannot check it.</p> <p>I know <code>pydantic</code>. But that is extra code.</p> <p>I need an interpreter to run same code, with...
<python><python-typing><mypy>
2025-02-11 06:06:04
0
402
0x01010
79,428,873
1,149,534
problems uploading a Kivy app to WebHostPython
<p>I'm a total newb with Python and Kivy. I like the way I can create and test a kivy app using VS. I have an account an account at WebHostPython and want to upload my simple kivy app (which runs in VS) to my account at WebHostPythonand run it from my browser. Has anyone done this? I'm having no luck.</p>
<python><kivy>
2025-02-11 04:08:24
1
507
bobonwhidbey
79,428,677
8,800,836
Batch make_smoothing_spline in scipy
<p>In <code>scipy</code>, the function <a href="https://docs.scipy.org/doc/scipy-1.15.1/reference/generated/scipy.interpolate.make_interp_spline.html#scipy.interpolate.make_interp_spline" rel="nofollow noreferrer"><code>scipy.interpolate.make_interp_spline()</code></a> can be batched since its <code>x</code> argument m...
<python><scipy><interpolation><spline>
2025-02-11 01:28:29
1
539
Ben
79,428,658
1,245,659
create a profile record when creating a user in Django
<p>I'm trying to solve this error:</p> <pre><code>TypeError: Profile.save() got an unexpected keyword argument 'force_insert' </code></pre> <p>signals.py</p> <pre><code>from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import User from .models import Pro...
<python><django>
2025-02-11 01:10:35
1
305
arcee123
79,428,655
26,428
Where in a MySQL statement can I use pyformat variables/parameters?
<p>Here's an example that doesn't work:</p> <pre class="lang-none prettyprint-override"><code>stmt = ''' SELECT `date_new`, `event` FROM `events` WHERE `date_new` &gt; TIMESTAMP(DATE_SUB(NOW(), INTERVAL %(days)s day)) ''' args = {'days': 30} c.execute(stmt, args) </code></pre> <p>which gives me an error: ...
<python><parameters><mysql-connector-python>
2025-02-11 01:08:51
0
363,512
Dennis Williamson
79,428,650
13,746,021
`map` causing infinite loop in Python 3
<p>I have the following code:</p> <pre><code>def my_zip(*iterables): iterators = tuple(map(iter, iterables)) while True: yield tuple(map(next, iterators)) </code></pre> <p>When <code>my_zip</code> is called, it just creates an infinite loop and never terminates. If I insert a print statement, it is reve...
<python><python-3.x><generator>
2025-02-11 01:05:49
2
361
Rusty
79,428,431
1,419,711
VSCode rename symbol ignores references in other files
<p>I have a class attribute <code>account_values</code> that occurs multiple times in class <code>MyClass</code>, all in the same the file <em>file1.py</em>. It is also referenced multiple times in <em>file2.py</em>. All the references in <em>file1.py</em> are in class method definitions and are of the form <code>self....
<python><visual-studio-code><refactoring>
2025-02-10 22:10:18
0
791
Llaves
79,428,043
1,247,136
Why `ast.Assign.targets` is a list?
<p><code>ast.Assign.targets</code> is a list</p> <pre class="lang-py prettyprint-override"><code>a, b = c, d </code></pre> <p>Yields following AST:</p> <pre class="lang-py prettyprint-override"><code>Assign( targets=[ Tuple( elts=[ Name(id='a', ctx=Store()), Name(id='b', ctx=Store())], ...
<python><python-ast>
2025-02-10 18:57:35
1
1,626
mr0re1
79,428,023
1,643,257
Can I use inline script dependencies to a `project.scripts` endpoint?
<p>I have a Python project that uses <code>uv</code> for building and running.</p> <p>Under <code>src/module/cli/my_script.py</code> I have a script like this:</p> <pre><code>#!/usr/bin/env -S uv run --script # /// script # requires-python = &quot;&gt;=3.12&quot; # dependencies = [ # &quot;numpy&quot;, # ] # /// i...
<python><uv>
2025-02-10 18:45:38
0
3,000
Zach Moshe
79,427,979
12,115,498
Importing one Google Colab notebook into another
<p>I am using Google Colab for the first time, and I am having trouble importing one Colab notebook into another. I have created two new notebooks in my Colab Notebooks folder titled <code>NB1.ipynb</code> and <code>NB2.ipynb</code>. I wish to import the latter from the former, i.e. I want to access all of the function...
<python><jupyter-notebook><google-colaboratory>
2025-02-10 18:24:45
3
783
Leonidas
79,427,974
1,473,517
Can `spawn` be made as memory efficient as `fork` with multiprocessing?
<p>I am on Linux and have working multiprocessing code that uses fork. Here is a MWE version:</p> <pre><code>from multiprocessing import Pool from time import perf_counter as now import numpy as np def make_func(): n = 20000 np.random.seed(6) start = now() M = np.random.rand(n, n) return lambda x,...
<python><multiprocessing>
2025-02-10 18:23:19
1
21,513
Simd
79,427,869
15,842
Default filter expression to "match anything"
<p>What kind of polars expression (<code>pl.Expr</code>) might be used in a filter context that will <em>match anything</em> including nulls?</p> <p>Use case: Type hinting and helper Functions that should return an <code>polars.Expr</code>.</p>
<python><python-polars>
2025-02-10 17:36:23
1
21,402
Gregg Lind
79,427,742
407,762
How do I add missing imports to a Python module using ast-grep?
<p>I have the following <a href="https://ast-grep.github.io/" rel="nofollow noreferrer"><code>ast-grep</code></a> rule to replace some http status integer literals in my code with constants</p> <pre><code>id: replace_http_status_with_constants language: python rule: all: - regex: &quot;^(200|201|204|302|400|401|4...
<python><ast-grep>
2025-02-10 16:45:27
1
3,138
armonge
79,427,599
1,914,781
Simplify replace statement with regex
<p>I would like to replace <code>[</code> with <code>{</code> and <code>]</code> with <code>}</code>, below code works but I wish to simplify it with one line (maybe regex?)</p> <pre><code>s = &quot;&quot;&quot; [[0,0],[0,1],[1,2],[2,1]] &quot;&quot;&quot; s = s.replace(&quot;[&quot;,&quot;{&quot;) s = s.replace(&quot...
<python>
2025-02-10 15:43:39
0
9,011
lucky1928
79,427,446
8,800,836
Interdependent bounds in scipy minimize
<p>Say I have a function <code>f(x,y,z)</code> I want to minimize using <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html" rel="nofollow noreferrer"><code>scipy.optimize.minimize</code></a>. I want to minimize it subject to the constraint <code>x &lt; y &lt; z</code>.</p> <p>I d...
<python><scipy><constraints><scipy-optimize-minimize><fitbounds>
2025-02-10 14:49:59
0
539
Ben
79,427,445
16,383,578
How to use Python to install fonts on Windows without reboot?
<p>I have seen some partial duplicates on the same topic, but all of those I have seen require a reboot for the installation to take effect.</p> <p>I am trying to download different fonts and install them in batch, double clicking the fonts one by one and clicking install works, but that is of course very slow.</p> <p>...
<python><windows><fonts>
2025-02-10 14:49:56
2
3,930
Ξένη Γήινος
79,427,260
1,957,820
python systemd timer every 2.5 hrs past the hour, but it runs every 2 hrs
<p>I am forced/bound to use python 2.7. I have created a systemd timer (and system.service of course) where the timer should run (24/7) every 2.5 hours past the hour. So starting at 00.00, 02:30, 05:00, 07.30, 10:00, etc). With the source below the timer runs, but (according to systemctl list-timers) it runs unfortunat...
<python><timer><systemd>
2025-02-10 13:45:13
1
438
ni_hao
79,427,227
8,189,936
Http-only cross-site cookie not being added to browser
<p>I am sending my <em>refresh</em> and <em>access</em> tokens as <em>http-only</em> cookies to the frontend of my Next.js application. When I log the response headers in the console of my frontend, I am able to get the cookies. However, they are not being added to the browser.</p> <p>My FastAPI CORS middleware looks l...
<python><reactjs><cookies><fastapi><cross-domain>
2025-02-10 13:33:51
2
1,631
David Essien
79,427,188
6,792,327
Firebase Cloud Functions Python - Loading service account path for different env
<p>I am attempting to deploy my Python Firebase Cloud Functions, but have not been able to do so because I'm using the same code base to deploy to different environment. I have set up different Firebase projects for <code>dev</code> and <code>prd</code>, and I would need to parse in the different <code>SERVICE_ACCOUNT_...
<python><firebase><google-cloud-functions>
2025-02-10 13:15:37
0
2,947
Koh
79,427,136
16,389,095
How to list all app/software/programs installed on Windows 11 using a Python script
<p>I develop a Python script to list all installed apps in my Windows 11 system. I would like to replicate the same results displayed in <em>Settings &gt; App &gt; Installed Apps</em>. Optionally, I would like to list apps installed not only for my user but in the entire system. Surfing the web, I found these four comm...
<python><windows><powershell><subprocess><system-administration>
2025-02-10 12:54:11
1
421
eljamba
79,427,039
13,219,123
Installing PySpark on Mac with pipenv
<p>I have a setup where I use pipenv for my virtual environments. I am using a MacBook.</p> <p>I have done the following:</p> <ul> <li>Installed openJDK 11 using brew</li> <li>Set paths in the <code>.zprofile</code> folder:</li> </ul> <pre><code>eval &quot;$(/opt/homebrew/bin/brew shellenv)&quot; export JAVA_HOME=&quot...
<python><macos><apache-spark><pyspark>
2025-02-10 12:15:33
1
353
andKaae
79,426,997
7,304,502
Issue with YAML formatting when modifying multiline fields in Python script
<p>I'm trying to write a Python script to read a YAML file, modify certain fields, and then rewrite it. However, I'm facing an issue with multiline fields. The original YAML file contains multiline strings, but after running my script, the formatting changes, and I see escaped characters instead of the expected format....
<python><yaml>
2025-02-10 11:56:27
1
669
delucaezequiel
79,426,847
5,722,359
How to express the dot product of 3 dimensions arrays with numpy?
<p>How do I do the following dot product in 3 dimensions with numpy?</p> <p><a href="https://i.sstatic.net/EfgTHtZP.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/EfgTHtZP.png" alt="enter image description here" /></a></p> <p>I tried:</p> <pre><code>x = np.array([[[-1, 2, -4]], [[-1, 2, -4]]]) W = np.ar...
<python><numpy>
2025-02-10 10:54:27
5
8,499
Sun Bear
79,426,845
15,485
In pandas, a groupby followed by boxplot gives KeyError: "None of [Index(['A', 1], dtype='object')] are in the [index]"
<p>This very simple script gives error <code>KeyError: &quot;None of [Index(['A', 1], dtype='object')] are in the [index]&quot;</code>:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt L1 = ['A','A','A','A','B','B','B','B'] L2 = [1,1,2,2,1,1,2,2] V = [9.8,9.9,10,10.1,19.8,19.9,20,20.1] df = pd.DataFra...
<python><pandas><group-by><boxplot>
2025-02-10 10:52:25
2
18,835
Alessandro Jacopson
79,426,669
9,827,719
Python create LimaCharlie Adapter of type "JSON > Events received throgh LimaCharlie webhooks" gives: Api failure (400): {'error': 'missing data'}
<p>I am trying to create a LimaCharlie Adapter of type &quot;JSON &gt; Events received throgh LimaCharlie webhooks&quot; with Python.</p> <p>This is my code:</p> <pre><code>import limacharlie # My variables lc_oid = &quot;123&quot; lc_api_key = &quot;456&quot; adapter_name = &quot;fw-cisco-meraki-tromso&quot; adapter_...
<python>
2025-02-10 09:53:51
0
1,400
Europa
79,426,664
6,230,282
`subprocess.run` invokes an executable (not script) using the python interpreter when it's not necessary
<p>Related: <a href="https://stackoverflow.com/q/78045053/6230282">After pakage a python to a exe with pyinstaller, why it can not run on a new computer?</a></p> <p>I'm packaging a command line application with a thin GUI wrapper written in Python using <code>pyinstaller</code>. I received feedback from user that it's ...
<python><subprocess><pyinstaller>
2025-02-10 09:51:13
1
1,641
DannyNiu
79,426,384
15,412,256
Docstring for Polars API register namespace
<p>An example Python Polars API UDF name registration:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl from pydantic import ValidationError, validate_call @pl.api.register_dataframe_namespace(&quot;test&quot;) class TestOps: def __init__(self, df: pl.DataFrame) -&gt; None: self._df...
<python><python-polars><docstring>
2025-02-10 07:47:20
0
649
Kevin Li
79,426,312
6,036,058
Should I generate an SBOM for a Python library with bounded version ranges?
<p>I'm maintaining a Python library and considering whether I should generate a Software Bill of Materials (SBOM) for it. However, my pyproject.toml defines dependencies using bounded version ranges (e.g., &gt;=1.0, &lt;=2.0), meaning that the exact versions used can vary depending on the environment.</p> <p>My main qu...
<python><dependencies><pyproject.toml><package-management><sbom>
2025-02-10 07:07:04
2
667
Florian Vuillemot
79,426,206
11,748,924
Understanding YOLOv11 Tensor Ouput Shape for Post-Processing
<p>I tried export YOLOv11 model to tensorflow, it said:</p> <pre><code>'yolo11n.pt' with input shape (1, 3, 640, 640) BCHW and output shape(s) (1, 84, 8400) (5.4 MB) </code></pre> <p>Now I have this model summary in Keras 3:</p> <pre><code>Model: &quot;functional_1&quot; ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━...
<python><numpy><tensorflow><yolo><ultralytics>
2025-02-10 06:12:00
1
1,252
Muhammad Ikhwan Perwira
79,426,130
6,702,598
How to create a class that runs business logic upon a query?
<p>I'd like to create a class/object that I can use for querying, that contains business logic.</p> <p>Constraints:</p> <ul> <li>Ideally that class/object is not the same one that is responsible for table creation.</li> <li>It's possible to use the class inside a query</li> <li>Alembic should not get confused.</li> <li...
<python><sqlalchemy><alembic>
2025-02-10 05:18:55
3
3,673
DarkTrick
79,426,062
6,162,679
`sklearn.metrics.r2_score` is giving wrong R2 value?
<p>I notice that <code>sklearn.metrics.r2_score</code> is giving wrong R2 value.</p> <pre><code>from sklearn.metrics import r2_score r2_score(y_true=[2,4,3,34,23], y_pred=[21,12,3,11,17]) # -0.17 r2_score(y_pred=[21,12,3,11,17], y_true=[2,4,3,34,23]) # -4.36 </code></pre> <p>However, the true R2 value should be 0....
<python><scikit-learn>
2025-02-10 04:12:06
1
922
Yang Yang
79,426,034
2,128,232
Why can't one change the size of a PyQt checkbox?
<p>The following code runs, but the checkbox is tiny (it should be large). Why doesn't this work as expected? (One can use styling to resize the text, but that's not what I'm trying to do here). I'll be grateful for any suggestions.</p> <pre class="lang-py prettyprint-override"><code>import sys from PyQt5.QtWidgets...
<python><checkbox><pyqt>
2025-02-10 03:28:19
1
566
Phillip M. Feldman
79,425,937
948,866
How do I modify a list value in a for loop
<p>In <a href="https://stackoverflow.com/questions/4081217/how-to-modify-list-entries-during-for-loop">How to modify list entries during for loop?</a>, the general recommendation is that it can be unsafe so don't do it unless you know it's safe. In comments under the first answer @martineau says:</p> <blockquote> <p>It...
<python><list><for-loop>
2025-02-10 01:25:15
2
3,967
Dave
79,425,910
6,395,555
Python Line profiler not working in VSCode
<p>I've installed line_profiler 4.1.3 from conda and I'm using a jupyter notebook in VSCode.</p> <p>When I run the following cells</p> <hr /> <pre><code>%load_ext line_profiler </code></pre> <hr /> <pre><code>def test_fn(): x = 2+2 return x </code></pre> <hr /> <pre><code>lprun -f test_fn test_fn() </code></pre...
<python><visual-studio-code><line-profiler>
2025-02-10 00:44:50
0
363
alessandro
79,425,829
5,231,665
emit Broadcast with flask_socketio
<p>I have a flask server running, and sockets are connection successfully. I want to run a service that monitors stuff on my server, such as GPU usage with <code>GPUMonitorService</code>, and the broadcast that data to all connected sockets. I make the GPU service, and pass in the socketio object. I have an <code>on....
<python><flask><flask-socketio>
2025-02-09 23:06:01
1
2,062
Barrard
79,425,585
3,213,204
Copy image to clipboard in python and Qt6 in linux
<h3>General overview</h3> <p>The goal is pretty simple :</p> <ol> <li>copy image in the clipboard</li> <li>using ideally no graphical library related solution, or if it’s necessary Qt</li> <li>Working on Unices or ideally a no OS-related solution</li> <li>With just python tools, no subprocess to call an external no pyt...
<python><clipboard><qt6>
2025-02-09 19:36:46
0
321
fauve
79,425,204
1,473,517
Why should I pass a function using initializer and can I use shared memory instead?
<p>Take this MWE:</p> <pre><code>from multiprocessing import Pool from time import perf_counter as now import numpy as np def make_func(): n = 20000 np.random.seed(7) M = np.random.rand(n, n) return lambda x, y: M[x, x] + M[y, y] class ParallelProcessor: def __init__(self): pass ...
<python><multiprocessing>
2025-02-09 16:01:43
2
21,513
Simd
79,425,183
405,017
Processing a list of zero or more checkboxes in FastHTML
<p>With <a href="https://www.fastht.ml/" rel="nofollow noreferrer">FastHTML</a> I'm writing a route to process a list of same-named checkboxes representing filenames in a <a href="https://picocss.com/docs/dropdown" rel="nofollow noreferrer">Pico CSS Dropdown</a> passed in a query string by HTMX:</p> <pre class="lang-py...
<python><htmx><starlette><fasthtml>
2025-02-09 15:49:48
1
304,256
Phrogz
79,425,037
11,635,654
orbax save/restore with 8 devices
<p>I have setup a snippet on Colab <a href="https://colab.research.google.com/drive/1clg6ZKorhfFQUuY44oYjyoW8rJ1FCe1B?usp=sharing" rel="nofollow noreferrer">here</a> with</p> <pre><code>jax.__version__ # 0.4.33 9Feb2025 orbax.checkpoint.__version__ # 0.6.4 9Feb2025 </code></pre> <p>It quite difficult t...
<python><jax><flax>
2025-02-09 14:12:29
0
402
Jean-Eric
79,425,025
893,254
Kafka Consumer group session timed out without a successful response from the group coordinator: revoking assignment and rejoining group
<p>The title had to be shortened a bit.</p> <p>The full error message is more like this:</p> <pre><code>Kafka Consumer group session timed out (in join-state steady) after X ms without a successful response from the group coordinator: revoking assignment and rejoining group </code></pre> <p>What causes this?</p> <h1>Co...
<python><apache-kafka>
2025-02-09 14:02:02
1
18,579
user2138149
79,424,951
11,439,134
Cursor not always updating in Tkinter
<p>I'm trying to change the cursor in my Tkinter app when the mouse moves. As a simplified example:</p> <pre><code>import tkinter as tk root = tk.Tk() root.geometry(&quot;500x200&quot;) frame2 = tk.Frame(root) frame = tk.Canvas(frame2) def on_mouse_motion(event): if event.x &gt; 200: frame2.config(cursor...
<python><tkinter>
2025-02-09 13:22:19
1
1,058
Andereoo
79,424,829
367,824
How to strip indents (not just lines) from inner Jinja2 blocks?
<p>Using Python’s Jinja, I’m concerned with both code readability and correct output. Here is my Jinja template:</p> <pre><code>M3U_TEMPLATE = jinja2.Template( textwrap.dedent(&quot;&quot;&quot;\ #EXTM3U {% for item in playlist %} #EXTALB:{{ item.strAlbum }} ({{ item.release }})...
<python><jinja2>
2025-02-09 11:35:21
4
330
avibrazil
79,424,554
9,495,110
How to draw straight lines from one edge of a blob to the other in opencv
<p>I have a blob of irregular shapes like this:</p> <p><a href="https://i.sstatic.net/B0Ujjszu.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/B0Ujjszu.png" alt="blob" /></a></p> <p>Now I want to draw lines from the outer edge to the inner edge of the blob like this:</p> <p><a href="https://i.sstatic.net...
<python><opencv><image-processing><computer-vision><geometry>
2025-02-09 07:41:20
1
1,027
let me down slowly
79,424,281
1,245,659
how to refer back to the model from utils.py in a Django object
<p>I'm trying to create a field in a django model, that forces a unique value in the model. I'm using utils.py to generate the value.</p> <p>The error I get is:</p> <pre><code>File &quot;/Users/evancutler/PycharmProjects/DjangoProject1/MCARS/utils.py&quot;, line 2, in &lt;module&gt; from MCARS.models import Profil...
<python><django>
2025-02-09 02:59:47
1
305
arcee123
79,423,875
6,151,828
Equivalent of Pythons selection by multiindex level (especially columns) in Julia
<p>My understanding is that DataFrames do not support MultiIndexing, which generally does not pose much problems, but translating some pythonic habits to Julia poses difficulties. I wonder how one could load and subselect features by columns, as in the example below.</p> <pre class="lang-py prettyprint-override"><code>...
<python><dataframe><julia><multi-index>
2025-02-08 20:31:54
1
803
Roger V.
79,423,661
1,574,054
Encrypt a file using a TPM with tpm2_pytss
<p>I am new to TPMs and want to construct a minimal example ecrypting and decrypting a file (here for simplicity represented just by a <code>bytes</code> object). It want everything to be non-persistent, so that the encryption/decryption only works until reboot. Furthermore, I don't want the symmetric encryption key (A...
<python><python-3.x><encryption><tpm><tpm-2.0>
2025-02-08 17:51:09
0
4,589
HerpDerpington
79,423,573
7,483,509
A parent class that allows dataclass style annotations that works with nested class hierarchy
<p>I would like to write a class that works similarly to <code>dataclass</code>, but would work with inheritance. It would also data to a dictionary rather than directly to the class.</p> <p>Currently I have something that work only with one subclass:</p> <pre class="lang-py prettyprint-override"><code>class Data: ...
<python><inheritance>
2025-02-08 16:52:10
0
1,109
Nick Skywalker
79,423,383
16,815,358
NumbaPerformanceWarning about contiguous arrays, although both arrays are already contiguous
<p>I am having a problem with removing this warning, before publishing a package on PyPI.</p> <p>As a summary, this is the function that I am using to speed up the <code>np.dot()</code> function:</p> <pre><code>@nb.jit(nb.float64[:,:](nb.float64[:,:], nb.float64[:,:]), nopython=True) def fastDot(X, Y): return np.do...
<python><numba><scientific-computing>
2025-02-08 14:47:07
1
2,784
Tino D
79,423,247
5,430,790
How to color excel cells with specific values in dataframe Python
<p>I created a code to insert my dataframe, called df3, into an excel file.</p> <p>My code is working fine, but now I'd like to change background cells color in all cells based on value</p> <p>I tried this solution, I don't get any errors but I also don't get any cells colored</p> <p>My code:</p> <pre><code>def cond_fo...
<python><excel><pandas>
2025-02-08 13:19:35
2
319
Marci
79,423,207
352,290
Close button not enabled while rendering an image using OpenCV
<p>I don't see the close button on a Mac machine, but this code works fine on a Windows machine while trying to render the image using OpenCV library on the <code>imshow</code> function.</p> <pre><code>def detect_objects_in_image(image_path: str): frame = cv2.imread(image_path) if frame is None: typer.e...
<python><macos><opencv>
2025-02-08 12:53:03
0
1,360
user352290
79,423,122
8,354,581
RuleBasedCollator rule ignored
<p>I'm trying to use the icu RuleBasedCollator in python. In my code I specify a rule wherby &quot;ä&quot; should sort before &quot;a&quot; as a secondary (accent) difference</p> <pre><code>from icu import RuleBasedCollator l=[&quot;a&quot;,&quot;ä&quot;] rbc = RuleBasedCollator('\n&amp;ä&lt;&lt;a') sorted(l, key=rbc....
<python><collation><icu>
2025-02-08 11:51:02
1
379
korppu73
79,422,511
15,547,292
python ctypes: reading a string array
<p>With python ctypes, how can I read a NUL-terminated array of NUL-terminated strings, e.g. ghostscript's <code>gs_error_names</code> ?</p> <p>I know how to get the first value:</p> <pre class="lang-py prettyprint-override"><code>from ctypes import * from ctypes.util import find_library gs = CDLL(find_library(&quot;g...
<python><ctypes>
2025-02-08 01:51:32
2
2,520
mara004
79,422,490
10,124,658
Python split() function :: Need to split "int_32\n' " so that I get int_32 alone
<p>Need to split &quot;int_32\n' &quot; so that I get int_32 alone.</p> <p>I tried</p> <pre><code>x = &quot;int_32\n' &quot; x.split(&quot;\n&quot;) </code></pre> <p>I also tried</p> <pre><code>x = &quot;int_32\n' &quot; x.splitlines() </code></pre> <p>Both do not yield the required output which is int_32</p> <p>Instea...
<python><arrays><string><split>
2025-02-08 01:28:14
3
707
Software Fan
79,422,452
3,251,645
Model returns NaNs when using ModernBERT instead of Roberta
<p>I'm trying to fine-tune ModernBERT for a classification task. For this I had some old code written using PyTorch that I've used to fine-tune BERT and recently Roberta with no issues. But when I switch out Roberta with ModernBERT, I suddenly get NaNs in my output tensor from the very first batch. This means my loss i...
<python><pytorch><fine-tuning>
2025-02-08 00:56:47
0
2,649
Amol Borkar
79,422,370
10,985,257
rich.Progress nested with correct time
<p>I try to implement a nested progress bar, which resets the inner.</p> <p>The following works for displaying the progress as I expected:</p> <pre class="lang-py prettyprint-override"><code>import time from rich.progress import Progress with Progress() as progress: task1 = progress.add_task(&quot;[red]Downloadin...
<python><progress-bar><rich>
2025-02-07 23:28:00
0
1,066
MaKaNu
79,422,227
2,955,541
Make PyFFTW Faster Than SciPy Convolve
<p>I have a simple function that performs a sliding dot product using an overlap-add convolution approach:</p> <pre><code>import numpy as np from scipy.signal import oaconvolve import pyfftw import os def scipy_sliding_dot(A, B): m = A.shape[0] n = B.shape[0] Ar = np.flipud(A) # Reverse/flip A AB = oa...
<python><numpy><scipy><fftw><pyfftw>
2025-02-07 21:47:49
0
6,989
slaw