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,380,546
1,422,096
Zero pad a numpy n-dimensional array
<p>Not a duplicate of <a href="https://stackoverflow.com/questions/38191855/zero-pad-numpy-array">Zero pad numpy array</a> (that I posted 9 years ago, ouch!) because here it's about n-dimensional arrays.</p> <p><strong>How to zero pad a numpy n-dimensional array, if possible in one line?</strong></p> <p>Example:</p> <p...
<python><arrays><numpy>
2025-01-23 09:52:32
3
47,388
Basj
79,380,487
6,751,456
Celery: How to add a delay to a message sending to SQS
<p>I'm using Celery to consume messages from SQS queue.</p> <p>The queue is Standard type.</p> <p>There are cases [exceptions caught] when I explicitly re-enqueue tasks back to the queue.</p> <pre><code> def run(self): try: # some exceptions occurred ... ex...
<python><celery><amazon-sqs><django-celery><celery-task>
2025-01-23 09:31:47
0
4,161
Azima
79,380,222
17,721,722
How to immediately release memory after removing columns in PySpark?
<p>I want to remove specific columns from a DataFrame in PySpark and immediately release the memory occupied by these columns to optimize resource usage due to limited RAM. What is the best way to achieve this?</p> <p>Here are a few approaches I am considering:</p> <p>Note: df is already in-memory.</p> <p><strong>Appro...
<python><apache-spark><hadoop><pyspark><apache-spark-sql>
2025-01-23 07:48:22
0
501
Purushottam Nawale
79,379,899
5,273,594
Calling VerifyAddFixedPriceItem python Ebay sdk
<p>I am trying to call the VerifyAddItem endpoint with the following XML:</p> <pre><code>&lt;?xml version='1.0' encoding='utf-8'?&gt; &lt;VerifyAddFixedPriceItemRequest xmlns=&quot;urn:eb*y:apis:eBLBaseComponents&quot;&gt;&lt;RequesterCredentials&gt;&lt;eBayAuthToken&gt;v^1.1#i^1#r^1#I^3#p^3#f^0#t^Ul4xMF84Ojg0NUNBQzJCA...
<python><xml><ebay-sdk>
2025-01-23 05:07:43
0
2,073
Fredy
79,379,838
4,647,107
Binding Python process to specific cores (Linux) using mpirun
<p>I have a Python file bla.py:</p> <pre><code>import os from mpi4py import MPI import psutil comm = MPI.COMM_WORLD rank = comm.Get_rank() PID = os.getpid() cpu_affinity = psutil.Process().cpu_num() print(f'rank: {rank} has PID: {PID} with affinity {cpu_affinity}') </code></pre> <p>But when I execute it using <code>m...
<python><mpi><affinity>
2025-01-23 04:28:02
1
534
Pratyush Das
79,379,785
1,232,087
Pandas ValueError when using on_bad_lines
<p><strong>Question</strong>: What I may be doing wrong and how we can fix the following error?</p> <pre><code>import pandas as pd def handle_bad_line(bad_line: list[str]) -&gt; list[str] | None: # Do something with the bad line, e.g., print it or modify it print(&quot;Bad line:&quot;, bad_line) # Return a...
<python><python-3.x><pandas>
2025-01-23 03:49:22
1
24,239
nam
79,379,761
11,663,956
paramiko.transport hang after ssh.connect from jump server to target server
<p>I have to use a jump server to login to a restricted server. Below setup in my jump server:</p> <pre><code>PasswordAuthentication yes ChallengeResponseAuthentication yes UsePAM yes </code></pre> <p>Below is my code</p> <pre><code>import paramiko, traceback from getpass import getpass paramiko.common.logging.basicC...
<python><python-3.x><ssh><paramiko><jumphost>
2025-01-23 03:30:51
1
347
Ginger_Chacha
79,379,667
3,179,698
switch between different notebooks in the same environment(session) in colab
<p>I am currently working with colab.</p> <p>I think I have a demand to open different notebooks in the same session.</p> <p>I did some work in the ipynb1, which downloaded a lot of data, installed a lot of packages in the current session, and I want to continue my work on one of my another ipynb2, to try methods on th...
<python><session><google-colaboratory>
2025-01-23 02:26:06
1
1,504
cloudscomputes
79,379,608
4,839,713
No Module Named error when trying to run pybind11-stubgen
<p>I've been scratching my head (googling, chatgpt-ing) trying to figure out why I can't generate a pyi file for a pybind module with pybind11-stubgen. I did this about a year ago successfully but can't remember the specifics.</p> <p>I'm getting a &quot;No Module Named {my-pybind-module}&quot; error when I try running ...
<python><pybind11><stub>
2025-01-23 01:36:19
1
599
Andrew Voelkel
79,379,515
8,032,508
Create an (XML) file in working memory, rather than writing locally (Python)
<p><strong>tl;dr -</strong> In python, is there a way to write a file in memory and store it in a variable, rather than writing it locally to disk?</p> <p><strong>Use Case</strong></p> <p>I'm trying to generate an XML file using the <code>xml.etree.ElementTree</code> package. I've been able to create a local file with ...
<python><xml>
2025-01-23 00:06:48
0
752
Jwok
79,379,421
1,406,168
Azure function python app - getting nested environments variables
<p>I have an azure function app written in python that does not return environment variables from other sections than values.</p> <p>localsettings.json:</p> <pre><code>{ &quot;IsEncrypted&quot;: false, &quot;IBAN&quot;: { &quot;API_KEY&quot;: &quot;xx&quot;, &quot;CURRENCY&quot;: &quot;USD&quot; }, &qu...
<python><azure><azure-functions>
2025-01-22 23:01:22
1
5,363
Thomas Segato
79,379,418
11,441,069
Django Allauth's Google Login Redirect and Page Design
<p>Currently, on the login page, I have a button:</p> <pre><code>&lt;div class=&quot;d-grid gap-2&quot;&gt; &lt;a href=&quot;{% provider_login_url 'google' %}&quot; class=&quot;btn btn-danger&quot;&gt; &lt;i class=&quot;fab fa-google&quot;&gt;&lt;/i&gt; Sign in with Google &lt;/a&gt; &lt;/div&gt; </code...
<python><django><google-oauth><django-allauth>
2025-01-22 22:58:53
2
509
Krzysztof Krysztofczyk
79,379,407
1,938,096
Flask doesn't claim any port
<p>Been writing some code, used flask in debug mode to test html etc which worked fine on <a href="http://127.0.0.1:5000" rel="nofollow noreferrer">http://127.0.0.1:5000</a>. But I ran into in issue in the Python code that I couldn't get resolved with just print statements of what values some variables had. I really ne...
<python><flask>
2025-01-22 22:52:42
1
579
Gabrie
79,379,336
2,600,531
boto3 timestream queries very slow
<pre><code>import boto3 device_list = ['ARMS-GFY-D5', 'ARMS-GFY-D3'] client = boto3.client('timestream-query') for device_id in device_list: query = f&quot;&quot;&quot; SELECT time, charge, current, voltage, temperature FROM &quot;telemetryDatabase&quot;.&quot;telemetryTable&quot; WHERE device_id = ...
<python><boto3><amazon-timestream>
2025-01-22 22:06:06
0
944
davegravy
79,379,215
374,198
Response from AWS SQS Java SDK does not match Python SDK or CLI
<p>We are using Java to send/receive messages from SNS/SQS. When we publish the message, we are doing this:</p> <pre class="lang-java prettyprint-override"><code>final var req = PublishRequest.builder() .topicArn(topicArn) .message(payload) .subject(subject) .build(); final var response = snsClient.publ...
<python><amazon-web-services><amazon-sqs>
2025-01-22 21:06:27
1
28,017
Josh M.
79,378,915
595,305
Filter out unneeded lines in pytest stack traces?
<p>Pytest was installed by using <code>pip install pytest</code>.</p> <p>Pytest is being run <strong>at a command prompt</strong> (W10) not from inside an IDE. Typically:</p> <pre><code>&gt; pytest --random-order -k test_my_test_module </code></pre> <p>(NB <code>--random-order</code> comes from package <a href="https:/...
<python><pytest><stack-trace>
2025-01-22 18:50:24
1
16,076
mike rodent
79,378,886
5,989,199
Syntax highlighting for Jinja and AlpineJS
<pre><code>{# jinja-html #} {% extends &quot;base.html&quot; %} {% block content %} &lt;div class=&quot;min-h-screen bg-gray-100&quot; x-data=&quot;{ photos: [], selectedPhoto: null, previewUrl: null, uploadProgress: 0, question: '', // Added question field init() { // Store auth token...
<python><jinja2><alpine.js>
2025-01-22 18:33:40
0
2,481
Daryl Wong
79,378,822
5,402,618
MongoEngine library doesn't allow to use its BaseFields for persisting data
<p>I started to use <a href="https://docs.mongoengine.org/tutorial.html" rel="nofollow noreferrer">mongoengine</a> library in order to read and write data from Mongo DB.</p> <p>I found some strage behavior. The following class is defined in my codebase:</p> <pre><code>class CustomerRequest(BaseModel): type = fields....
<python><mongodb><mongoengine>
2025-01-22 18:07:44
1
15,182
CrazySynthax
79,378,667
8,605,685
How to redirect OpenCV backend error messages to my own logger
<p>When using OpenCV to enumerate cameras with:</p> <pre><code>def list_available_cameras(max_cameras=10): &quot;&quot;&quot;List all available camera indices.&quot;&quot;&quot; available_cameras = [] for index in range(max_cameras): logger.info(f&quot;Checking camera {index}...&quot;) cap =...
<python><opencv><logging>
2025-01-22 17:16:59
0
12,587
Salvatore
79,378,624
2,836,049
Error cannot import name 'Connectable' from 'sqlalchemy.engine.base' with pangres 4.1.2 and sqlalchemy 2.0.36
<p>When I try to run my Python 3.9 script, I get the following error:</p> <pre><code> File &quot;/usr/local/lib/python3.9/site-packages/pangres/__init__.py&quot;, line 1, in &lt;module&gt; from pangres.core import aupsert, upsert File &quot;/usr/local/lib/python3.9/site-packages/pangres/core.py&quot;, line 9, in &lt...
<python><sqlalchemy>
2025-01-22 17:03:35
1
1,461
John Langford
79,378,514
122,792
Force Altair chart to display years
<p>Using a data frame of dates and values starting from 1 Jan 2022:</p> <pre><code>import datetime as dt import altair as alt import polars as pl import numpy as np alt.renderers.enable(&quot;browser&quot;) dates = pl.date_range(dt.date(2022, 1, 1), dt.date(2025, 1, 22), &quot;1d&quot;, eager = True) values = np.rand...
<python><python-polars><altair>
2025-01-22 16:26:20
1
25,088
Thomas Browne
79,378,481
7,376,511
ipdb set_trace: retry block
<pre><code>import ipdb my_var = 1 try: assert my_var == 2 except AssertionError: ipdb.set_trace() raise </code></pre> <p>Is there an easy way to retry the failing block if the value of <code>my_var</code> is changed in the resulting ipdb console?</p>
<python><ipdb>
2025-01-22 16:13:17
0
797
Some Guy
79,378,440
16,389,095
How to change theme mode of a container and its children in Python Flet
<p>I'm trying to develop an app with multiple views. Each view should have a proper theme and theme mode. To solve this problem, I decided to deal with an easier one. I would like to set a page theme and theme mode, and add a container with a different theme mode or a different theme too. I found something similar into...
<python><flutter><flet>
2025-01-22 15:58:57
1
421
eljamba
79,378,313
3,554,721
Contravariance in Python protocols
<p>I have defined a simple protocol:</p> <pre><code>K = TypeVar('K', contravariant=True) V = TypeVar('V', contravariant=True) class Settable(Protocol[K,V]): def __setitem__(self, key: K, value: V) -&gt; None: ... </code></pre> <p>and a function that accepts an object that implements it</p> <pre><code>def h...
<python><python-typing><mypy><pyright>
2025-01-22 15:20:20
0
3,224
0x60
79,378,168
13,498,838
How to access and modify the original next_run_time of a paused Job in APScheduler?
<p>I am using Python 3.12 and APScheduler version 3.11.0.</p> <p>I have scheduled a job to run at a specific time. If the job needs to be paused before execution, I would like to adjust its next_run_time before resuming it. However, I am unsure how to access the <strong>originally set trigger time</strong> (the time sp...
<python><apscheduler>
2025-01-22 14:36:19
0
1,454
jda5
79,377,876
8,112,349
How can I convert this pandas.series result to integer?
<p>I've got a column <code>['Duration]</code> which is an <code>int</code> datatype. I'm now trying to find out the most occurencing <code>['Duration']</code> in a pandas dataframe.</p> <pre><code> duration = (inter['duration'].mode()) print(duration) </code></pre> <p>Result:</p> <pre><code> 0 94 Name: durati...
<python><pandas><dataframe><type-conversion>
2025-01-22 13:25:20
1
825
user234568
79,377,877
8,112,349
How to convert this pandas.series result to integer?
<p>I'm doing some questions and I'm stuck on this. So basically I've got a column ['Duration] which is an int datatype. I'm now trying to find out the most occurencing ['Duration'] in a pandas dataframe.</p> <pre><code> duration = (inter['duration'].mode()) print(duration) </code></pre> <p>Result:</p> <pre><code> ...
<python><pandas><dataframe><type-conversion>
2025-01-22 13:25:20
0
825
user234568
79,377,791
7,980,206
What are variables generated as "_1", "_2", "_3"... "_1i"...."_" when printing dir()?
<p>I am running Python with IPython. Out of nowhere the following variables are being created when I print <code>dir()</code>.</p> <p>Here are some of the variables with following code:</p> <pre class="lang-py prettyprint-override"><code>for i in dir(): if &quot;_&quot; in i: print(i) # Output: _ ...
<python><ipython>
2025-01-22 13:02:00
1
717
ggupta
79,377,681
876,832
Is it a bug to use subprocess.run() in a multithreaded script?
<p>I have a long build script which is a mix of &quot;real&quot; python code and lengthy <code>subprocess.run()</code> calls to things like <code>debootstrap</code>, <code>wget</code>, <code>apt-get</code> or <code>build.sh</code>.</p> <p>Everything is parallelized. One thread does <code>debootstrap</code> followed by ...
<python><multithreading>
2025-01-22 12:19:43
1
598
Fadeway
79,377,386
12,871,587
How to handle #DIV/0! errors with pl.read_excel() when using the calamine/fastexcel engine in Polars?
<p>I'm working with a messy Excel file and trying to read it using the <code>pl.read_excel()</code> method in Polars with the fastexcel or calamine engine. My goal is to load only 3 specific columns: &quot;<code>apple_column</code>&quot;, &quot;<code>banana_column</code>&quot;, and &quot;<code>kiwi_column</code>&quot;....
<python><python-polars>
2025-01-22 10:35:50
2
713
miroslaavi
79,377,336
2,915,050
Python unittest failing on function importing local file
<p>I have a Python package with a directory that looks like this:</p> <pre><code>-root | |-src | | | -app | | | |-__init__.py | |-__main__.py | |-file1.py | |-file2.py | |-tests | |-__init__.py |-test_function.py </code></pre> <p><code>file1.py</code> looks like this</p> <pre><code>from a...
<python><unit-testing><python-import>
2025-01-22 10:22:21
0
1,583
RoyalSwish
79,377,216
16,906,505
How to use sqlAlchemy events correctly with FastAPI
<p>I have a strange behavior that I do not understand really. I have a function to return a db session that knows a user email or throws 401 and a function that returns a db session without additional logic.</p> <p>I noticed that when a user is registered after someone logged in and used the db session with events, the...
<python><sqlalchemy><fastapi>
2025-01-22 09:48:54
0
500
RheinmetallSkorpion
79,377,019
11,663,956
"EOF in transport thread" when implementing challenge-response authentication with Python Paramiko
<p>I need to login to a Linux server and it has below configuration in <code>sshd_config</code>:</p> <pre><code>PasswordAuthentication yes ChallengeResponseAuthentication yes UsePAM yes </code></pre> <p>When I login through PuTTY, it firstly asked me to input the password, followed by the RSA token from an authentica...
<python><ssh><paramiko><challenge-response>
2025-01-22 08:43:06
1
347
Ginger_Chacha
79,376,992
719,001
vscode extension uses wrong python
<p>I am trying to use <code>sqlfluff</code> linter, which is a SQL formatter and linter. In settings.json I have, among others, this:</p> <pre><code> &quot;[sql]&quot;: { &quot;editor.defaultFormatter&quot;: &quot;dorzey.vscode-sqlfluff&quot; // Use SQLFluff formatter }, &quot;editor....
<python><visual-studio-code><vscode-python><sqlfluff>
2025-01-22 08:35:42
1
2,677
Nir
79,376,870
6,141,238
How can I remove the dotted border around the tab in focus in a multi-tabbed PyQt5 window?
<p>I have built a multi-tab window using PyQt5. Each tab has a thin dotted border when in focus:</p> <p><a href="https://i.sstatic.net/C4lBpkrk.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/C4lBpkrk.png" alt="enter image description here" /></a></p> <p>How do I remove this dotted border? (My operating...
<python><pyqt5><focus><border>
2025-01-22 07:47:17
1
427
SapereAude
79,376,281
3,004,257
Mod operator in Free Pascal gives a different result than expected
<p>The <code>mod</code> operator in Free Pascal does not produce the results I would expect.</p> <p>This can be demonstrated by the program below whose output does not agree with the result of the same calculation in Python (or Google).</p> <pre class="lang-pascal prettyprint-override"><code>program test(output); var ...
<python><freepascal>
2025-01-22 00:42:59
1
417
Mike T.
79,376,131
3,045,351
Using Python subprocess to resolve relative import error
<p>I have a situation where in a script I am having activate a virtualenv, then use subprocess to run a set of scripts in a package that live outside of the virtualenv like so:</p> <pre><code>#!/usr/local/lib/python3.10/virtual-environments/cogvideox/bin/python3.10 activate_this_file = &quot;/usr/local/lib/python3.10/...
<python><python-3.x><subprocess><virtualenv>
2025-01-21 22:49:45
0
4,190
gdogg371
79,376,031
5,013,066
'FileHandler' object has no attribute 'level'
<p>I am working on using the Python <code>logging</code> package. I am using Python 3.12.8 from <code>uv</code>.</p> <p>The <a href="https://docs.python.org/3/howto/logging.html" rel="nofollow noreferrer">documentation</a> gives the following code snippet as an example:</p> <pre class="lang-py prettyprint-override"><co...
<python><python-logging>
2025-01-21 21:50:22
0
839
Eleanor Holley
79,375,917
7,376,511
Python: convert back and forth between utf-8 and unicode_escape, preserving character
<pre><code>s = &quot;Hello隼&quot; s = s.encode(&quot;utf-8&quot;).decode(&quot;unicode_escape&quot;).encode(&quot;unicode_escape&quot;).decode(&quot;utf-8&quot;) print(s) </code></pre> <p>This returns <code>Hello\\xe9\\x9a\\xbc</code>. But why?!</p> <p>Yes, I know those escaped Unicode characters are equivalent to the ...
<python><unicode>
2025-01-21 20:55:01
1
797
Some Guy
79,375,876
5,856,587
Airflow task with parameter for task-generated mappings after a certain previous task
<p>I work with GCP Cloud Composer (Airflow), where I would like to list .csv files in a GCS storage bucket having a specific prefix and start an import into a GCP Cloud SQL instance for each of them. I would like to use <a href="https://airflow.apache.org/docs/apache-airflow/2.5.0/concepts/dynamic-task-mapping.html#" r...
<python><postgresql><google-cloud-storage><airflow><google-cloud-composer-2>
2025-01-21 20:35:31
0
555
Peter G. Horvath
79,375,816
6,005,699
Timestamps reset every 30 seconds when using distil-whisper with return_timestamps=True
<h2>Problem</h2> <p><a href="https://huggingface.co/distil-whisper/distil-large-v3#sequential-long-form" rel="nofollow noreferrer">distil-large-v3#sequential-long-form</a></p> <p>I'm using <code>distil-whisper</code> through the 🤗 Transformers pipeline for speech recognition. When setting <code>return_timestamps=True<...
<python><huggingface-transformers><transformer-model><openai-whisper>
2025-01-21 20:10:32
0
441
Martin Zhu
79,375,793
9,962,007
S3UploadFailedError due to MissingContentLength when calling PutObject in MLflow using MinIO
<p>When trying to save / upload a file using <code>mlflow.log_artifact()</code> to MinIO, our MLflow users are suddenly getting this error in previously working code, raised in <code>boto3</code> package (used by the <code>mlflow</code> package, and with S3-compatible local MinIO server acting as a data lake for our lo...
<python><amazon-s3><boto><minio><mlflow>
2025-01-21 20:02:05
2
7,211
mirekphd
79,375,777
19,672,778
Fourier Series Implementation cannot approximate batman shape
<p>I tried to implement a formula, from which a coefficients of Fourier Series could be calculated. (I used 3B1B's video about it: <a href="https://www.youtube.com/watch?v=r6sGWTCMz2k&amp;t=1284s" rel="nofollow noreferrer">Video</a>) and writing code for that, my first test subject was singular contour of batman logo, ...
<python><math>
2025-01-21 19:53:08
1
319
NikoMolecule
79,375,697
6,662,425
How to nest representer_mappings in ruamel.yaml?
<p>EDIT: made the question more concrete</p> <p>I want to have the concept of a learning task for optimizer benchmarking</p> <pre class="lang-py prettyprint-override"><code>@dataclass class LearningTask model: torch.nn.Module loss: torch.nn.Module data: lightning.LightningDataModule </code></pre> <p>Of cour...
<python><yaml><ruamel.yaml>
2025-01-21 19:13:19
1
1,373
Felix Benning
79,375,572
1,169,091
Why won't this Python module import into my code
<p>I have this entry point:</p> <pre><code># main.py from 022 import * print(&quot;Hello from main.py&quot;) </code></pre> <p>I have <code>022.py</code> also. It is:</p> <pre><code>print(&quot;Hello World&quot;) </code></pre> <p>When I run <code>main.py</code> I get this error:</p> <pre><code> File &quot;C:\Users\ni...
<python><python-import>
2025-01-21 18:31:45
1
4,741
nicomp
79,375,386
9,452,512
How to create a mesh from vertices and faces?
<p>I would like to use gmsh to create a mesh given the vertices and the faces (as they are usually stored in the .obj file format).</p> <p>How do I fill the following code?</p> <pre><code>import gmsh import numpy as np # Initialize Gmsh gmsh.initialize() vertices = np.array([ [-0.5, -0.5, -0.5], [0.5, -0.5, -...
<python><gmsh>
2025-01-21 17:28:17
1
1,473
Uwe.Schneider
79,375,287
997,633
GPU utilization almost always 0 during training Hugging Face Transformer
<p>I am fine-tuning a <a href="https://huggingface.co/naver-clova-ix/donut-base-finetuned-cord-v2" rel="nofollow noreferrer">Donut Cord-v2</a> model with my invoice data which is around 360 GB in size when preprocessed and saved on disk as a dataset. I am following <a href="https://github.com/philschmid/document-ai-tra...
<python><machine-learning><huggingface-transformers>
2025-01-21 17:09:03
1
2,511
astralmaster
79,375,135
3,336,423
Why does using `logging.Formatter` prevent widget from being deleted?
<p>Here is a MCVE, very simple piece of code creating a <code>QMainWindow</code>, with a central empty <code>QWidget</code>:</p> <pre><code>import sys from PyQt5.QtWidgets import QWidget class MyWidget(QWidget): &quot;&quot;&quot;QWidget based class to configure a Simulator object.&quot;&quot;&quot; def ...
<python><pyqt5><python-logging>
2025-01-21 16:13:14
1
21,904
jpo38
79,374,797
12,871,587
How to calculate horizontal median
<p>How to calculate horizontal median for numerical columns?</p> <pre><code>df = pl.DataFrame({&quot;ABC&quot;:[&quot;foo&quot;, &quot;bar&quot;, &quot;foo&quot;], &quot;A&quot;:[1,2,3], &quot;B&quot;:[2,1,None], &quot;C&quot;:[1,2,3]}) print(df) shape: (3, 4) ┌─────┬─────┬──────┬─────┐ │ ABC ┆ A ┆ B ┆ C │ │ --...
<python><python-polars>
2025-01-21 14:29:57
4
713
miroslaavi
79,374,674
5,618,856
pandas dataframe update with filter_func
<p>I have two dataframes with identical shape and want to update df1 with df2 if some conditions are met</p> <pre><code>import pandas as pd from typing import Any df1 = pd.DataFrame({&quot;A&quot;: [1, 2, 3], &quot;B&quot;: [4, 5, 6]}) print(df1, &quot;\n&quot;) df2 = pd.DataFrame({&quot;A&quot;: [7, 8, 9], &quot;B&q...
<python><pandas><dataframe>
2025-01-21 13:53:13
1
603
Fred
79,374,485
5,846,366
Override existing custom Django App template tags
<p>I have an application that uses Weblate to manage translations. I use <code>weblate/weblate</code> Docker image, with my own customizations built as a separate Python package extending this image and built on top of it. The problem is that in the Weblate HTML templates there is an <code>icon</code> template tag that...
<python><django><weblate>
2025-01-21 12:56:46
0
1,209
AlexNikolaev94
79,374,125
29,295,031
How to add custom buttons to update data in plotly grap
<p>I'm using Plotly in my Python project, and I came across a challenge, I don't know if I could do it with Plotly.</p> <p>Imagine this simple example:</p> <pre class="lang-py prettyprint-override"><code>import plotly.express as px df = px.data.gapminder().query(&quot;continent == 'Oceania'&quot;) fig = px.line(df, x=...
<python><plotly><plotly-dash><streamlit>
2025-01-21 11:00:24
0
401
user29295031
79,374,069
8,943,214
Error loading ASGI app. Could not import module "playground" - phidata
<p>I am following the guide from <a href="https://docs.phidata.com/agent-ui" rel="nofollow noreferrer">https://docs.phidata.com/agent-ui</a> to set up a UI for interacting with my agents. However, I am encountering the following error when trying to start a playground session with the phidata framework for an Agent UI ...
<python><phidata>
2025-01-21 10:40:13
1
3,817
laitifranz
79,374,057
9,749,124
Jupyter Notebook Kernel dies after trying to load libraries
<p>I have Macbook with M2 Chip. I have more than 700Gb free on my laptop. I want to load some hugging face models to my script.</p> <p>When ever I do this (this is the only lines of code):</p> <pre><code>from transformers import pipeline </code></pre> <p>The kernel dies:</p> <p><a href="https://i.sstatic.net/9VPgJxKN.p...
<python><jupyter-notebook><huggingface>
2025-01-21 10:34:22
0
3,923
taga
79,374,015
995,071
debug chalice Lambda Event Sources in vscode
<p>Chalice does not support debug mode with Lambda Event Sources. Functions based on event sources, such as on_sqs_message, are not even triggered locally when the Chalice app is launched. This limitation raises a critical question: how can developers effectively use debug tools, breakpoints, and other essential debugg...
<python><amazon-web-services><debugging><aws-lambda><chalice>
2025-01-21 10:20:52
1
701
negstek
79,373,980
5,462,743
Azure Machine Learning python SDK V2 download logs of steps of a job
<p>I wish to download all logs of a job. In the web interface, it is quite easy, but I want to create an automation around it and retrieve all the logs of a job that has multiple steps.</p> <pre class="lang-py prettyprint-override"><code>job = ml_client.jobs.get(name=&quot;my_job_name-08584641874851693546433866596CU116...
<python><azure><azure-machine-learning-service>
2025-01-21 10:14:09
2
1,033
BeGreen
79,373,960
12,466,687
How to use resolved output string from codechunk into markdown quarto?
<p>This can also be framed as &quot;How to view dynamic(names stored in variable) <code>html</code> files in <code>markdown</code> documents like <code>quarto</code> ?</p> <p>I have some <code>html plot</code> files with unique ids that I want to include in the notebook and names of those plots are in variables/paramet...
<python><html><iframe><jupyter-notebook><quarto>
2025-01-21 10:08:23
0
2,357
ViSa
79,373,843
2,881,414
How to generate a table of contents with meta data for a set of pages in mkdocs?
<p>I'm using mkdocs and mkdocs-material. I have a set of pages for which I want to generate a table of contents. Additionally, I want the table of contents to display a <strong>subset of the meta data</strong> provided by the pages indexed by the TOC. E.g.:</p> <pre><code>myproject/ |-- docs/ | |-- index.md &lt;- to ...
<python><mkdocs><mkdocs-material><mkdocs-macros>
2025-01-21 09:27:09
0
17,530
Bastian Venthur
79,373,468
2,243,490
flake8: ignore F841 unused variable for variable name _ex
<p>I have the following code and expecting flake8 not to raise any error as the variable name _ex starts with a underscore. But flake8 still gives me <code>F841 local variable '_ex' is assigned to but never used</code> error. How can I get rid of the error?</p> <pre><code>try: 1/0 except ZeroDivisionError as _ex: ...
<python><python-3.x><flake8>
2025-01-21 07:09:10
2
1,886
Dinesh
79,373,307
4,382,305
TypeError: 'Seq' object does not support item assignment
<p>I have a <code>Seq</code> object in Biopython (1.85), and I want to change its third element to <code>A</code>. When I run this code:</p> <pre><code>from Bio.Seq import Seq seq = Seq('CCGGGTTAACGTA') seq[2]= 'A' </code></pre> <p>I get this error:</p> <pre><code>TypeError: 'Seq' object does not support item assignmen...
<python><bioinformatics><biopython>
2025-01-21 05:40:48
3
2,091
Darwin
79,373,167
1,647,792
Python Postgres pull as byte object vs str
<p>I'm doing a basic Python Flask application with a Postgres database using psycopg2. I'm having trouble setting up the user registration password hash as it appears I'm working with a string vs byte type. Fundalmentally, I'll get this error when doing the password re-hash on the login (after registration and initial ...
<python><psycopg2><password-hash><python-3.11><postgresql-17>
2025-01-21 04:00:20
0
399
jazzmasterkc
79,373,155
8,098,068
Alembic keeps deleting and recreating Foreign Keys during autogenration
<p>After the autogenrated initial migration, when running another autogeneration all foreign keys are beeing dropped and recreated.</p> <p>Example Code from the migration script:</p> <pre><code>op.drop_constraint('fk_foo_bar_id_bar', 'foo', type_='foreignkey') op.create_foreign_key(op.f('fk_foo_bar_id_bar'), 'foo', 'ba...
<python><database><postgresql><alembic><timescaledb>
2025-01-21 03:49:55
1
364
tnfru
79,373,070
2,998,077
Requests and BeautifulSoup to get video length from YouTube
<p>In getting the video length from a YouTube url, Inspect from web browser shows there's a line:</p> <p><a href="https://i.sstatic.net/oZy2pGA4.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/oZy2pGA4.png" alt="enter image description here" /></a></p> <p>Then I use requests and BeautifulSoup to get it:<...
<python><web-scraping><beautifulsoup><request><youtube>
2025-01-21 02:47:34
4
9,496
Mark K
79,372,999
2,357,712
Please explain an unusual imported QIF library
<p>In this library on github, <code>https://github.com/giacomos/qifparse/blob/master/qifparse/parser.py</code> there is an import statement that I've never seen before.</p> <p><code> from qifparse.qif import</code></p> <p>I have tried all sorts of searches to find what this file source might be, but I'm stumped. Can ...
<python>
2025-01-21 01:28:01
0
1,617
Maxcot
79,372,940
1,046,184
How to get a list of models available in Ollama using Langchain
<p>I am trying to run a Python script that gets and prints a list of the models that are available to a running instance of Ollama. My code, based on code provided at <a href="https://medium.com/@garysvenson09/how-to-list-all-models-in-ollama-for-langchain-tutorial-786cb14298a8" rel="nofollow noreferrer">https://medium...
<python><artificial-intelligence><langchain>
2025-01-21 00:22:48
2
2,316
Factor Three
79,372,723
8,800,836
Sort columns of numpy unitary matrix such that highest element of each column is on the diagonal
<p>Take a unitary matrix <code>U</code>. I want to swap the columns such that the largest element of each column (in absolute value) is on the diagonal (modulo ties). What is the best way to do this in numpy?</p>
<python><numpy><sorting><numpy-ndarray>
2025-01-20 21:42:58
1
539
Ben
79,372,602
1,533,306
Pass parameters to custom transformer in sklearn
<p>I am trying to pass a parameter <code>DummyTransformer__feature_index_sec</code> to my sklearn custom transformer via a pipeline. It seems like I need to implement metadata routing in order to do this. However, I cannot successfully create a working dummy example:</p> <pre><code>from sklearn.base import BaseEstimat...
<python><scikit-learn><scikit-learn-pipeline>
2025-01-20 20:38:11
1
2,350
Jake Drew
79,372,577
673,600
Making long link clickable in Polars output
<p>I'm displaying a data frame in collab but finding that whilst the URL link is showing and being formatted, the underline and link don't go across the entire URL, which goes across a couple of lines, and when I click it, it goes to the truncated link.</p> <pre class="lang-py prettyprint-override"><code>result = { ...
<python><python-polars><polars>
2025-01-20 20:29:40
1
6,026
disruptive
79,372,227
14,454,397
Adjust the bars in the chart based on the subset condition
<p>I am facing an issue as shown in the image below, I am trying to generate the bar chart based on the treatments as a group, based on the drop-down, if I unselect a treatment the bar should disappear and show the bars of the remaining treatments, however when I unselect a treatment, there are gaps created. how to avo...
<python><python-3.x><streamlit>
2025-01-20 17:44:33
1
3,465
jkatam
79,372,210
20,302,906
Path.touch() patch assertion failed to find calls
<p>I'm creating files with <code>pathlib.Path.touch</code> with the following method that I'd like to assert in a unittest using <code>unitest.mock.patch</code> decorator:</p> <p><em>sessions.py</em></p> <pre><code>def generate_folders(paths: list): for p in paths: p.mkdir() Path(p / &quot;output&qu...
<python><mocking><python-unittest>
2025-01-20 17:38:03
1
367
wavesinaroom
79,372,122
22,538,132
How to check if a cuboid is inside camera frustum
<p>I want to check if an object (defined by four corners in 3D space) is inside the Field of View of a camera pose.</p> <p>I saw this <a href="https://math.stackexchange.com/questions/4144827/determine-if-a-point-is-in-a-cameras-field-of-view-3d">solution</a> and tried to implement it, but I missed something, can you p...
<python><math><graphics><3d><camera>
2025-01-20 17:04:31
2
304
bhomaidan90
79,372,057
2,256,085
aggregate 3D array using zone and time index arrays
<p>Using the small example below, I'm seeking to aggregate (sum) the values in the 3D <code>dat_arr</code> array using two other arrays to guide the grouping. The first index of <code>dat_arr</code> is related to time. The second and third indices are related to spatial (X, Y) locations. How can I sum values in <cod...
<python><numpy>
2025-01-20 16:43:19
1
469
user2256085
79,371,972
5,489,241
How to backfill jobs with different requirements to maximise CPU usage, with python joblib?
<p><strong>Here is the context to what I am trying to do:</strong></p> <ul> <li>I have several data blocks, that each consist of either 6 items or 24 items, and each item is analyzed separately. The analysis code is not mine. For reasons beyond my control, each item needs to be processed single-threaded.</li> <li>But I...
<python><joblib>
2025-01-20 16:13:15
0
413
cymon
79,371,835
4,873,946
pymatgen module not found in vscode
<p>I have installed pymatgen using the instructions on their website: <a href="https://pymatgen.org/installation.html" rel="nofollow noreferrer">https://pymatgen.org/installation.html</a></p> <p>Then I go to my vscode and in the terminal I activate the pymatgen conda environment with: <code>source activate pymatge</cod...
<python><pymatgen>
2025-01-20 15:32:35
0
454
lucian
79,371,747
16,527,170
Install Ta-Lib Library in Google Colab Current Latest: 3.11.11 in Jan-2025
<p>As 3.11.11 Python version rolled out in Jan-2025 in Google Colab Runtime, Ta-Lib Library stopped working.</p> <p>Earlier I used to install Ta-Lib as below in Colab:</p> <pre><code>url = 'https://anaconda.org/conda-forge/libta-lib/0.4.0/download/linux-64/libta-lib-0.4.0-h166bdaf_1.tar.bz2' !curl -L $url | tar xj -C /...
<python><google-colaboratory><ta-lib>
2025-01-20 15:09:36
2
1,077
Divyank
79,371,673
14,498,998
RUN pip install --no-cache-dir -r requirements.txt installing but no working with Docker
<p>I've trying to use docker for a couple of projects, one is a Django and another is a python telegram bot; But in both cases the problem is that no matter how I copy or install requirements.txt into the container, the libraries apparently get installed, but then all of a sudden I get errors like this in the main pyth...
<python><python-3.x><django><docker><pip>
2025-01-20 14:42:13
1
313
Alin
79,371,578
4,724,057
Sending multiple file uploads as input to Azure function app http trigger
<p>I am trying to send multiple file uploads to a function app (http trigger). The http trigger code is below,</p> <pre><code> app = func.FunctionApp(http_auth_level=func.AuthLevel.ADMIN) @app.route(route=&quot;test_http_trigger&quot;, auth_level=func.AuthLevel.ADMIN) def test_http_trigger(req: func.HttpRequ...
<python><azure><azure-functions><multipartform-data><azure-http-trigger>
2025-01-20 14:05:36
1
2,825
MenorcanOrange
79,371,534
10,722,752
Have only 2 classes but why am I getting ValueError: Target is multiclass but average = 'binary'. Please choose another average setting
<p>I am trying build an employee churn prediction model using <code>GridSearchCV</code> on <code>OneClassSVM</code>. My code is as below:</p> <pre class="lang-py prettyprint-override"><code>from sklearn.svm import OneClassSVM from sklearn.model_selection import GridSearchCV from sklearn.metrics import precision, recall...
<python><scikit-learn><svm><gridsearchcv>
2025-01-20 13:50:37
1
11,560
Karthik S
79,371,384
12,234,535
Cartopy doesn't render left and right longitude labes
<p>I'm using <code>cartopy</code> to draw a geomap. This is how I set up <code>graticule</code> rendering:</p> <pre class="lang-py prettyprint-override"><code> if graticule: gl = ax.gridlines( draw_labels=True, linewidth=0.8, color='gray', alpha=0.5, ...
<python><matplotlib><plot><latitude-longitude><cartopy>
2025-01-20 12:52:21
1
379
Outlaw
79,371,127
17,837,614
Module does not explicitly export attribute [attr-defined]
<p>In <code>bar.py</code> <code>foo</code> is imported</p> <pre class="lang-py prettyprint-override"><code># bar.py from path import foo </code></pre> <p>In my current file <code>bar</code> is imported and I use the <code>get_id</code> function of <code>foo</code>:</p> <pre class="lang-py prettyprint-override"><code>fr...
<python><python-typing><mypy>
2025-01-20 11:14:55
2
405
Sujay
79,371,056
3,336,423
Is it possible to make a pointer with bound parameter values?
<p>Consider this <code>ServicesManager</code> class that handles some services (basically, a function identified by a name):</p> <pre><code>class ServicesManager: def __init__(self): self.services = dict() def add_service(self,name,func): self.services[name] = func def call...
<python>
2025-01-20 10:55:37
1
21,904
jpo38
79,370,970
8,508,117
os.device_encoding changes when called from a subprocess, causing decoding error on Windows. How to force encoding in subprocess?
<p>I have the following Python 3.7 code in an imported package, not modifiable by myself, that reads and decodes the systems CCompiler name provided by disttools:</p> <h4>subproc.py</h4> <pre class="lang-py prettyprint-override"><code>import os import sys import locale import subprocess from distutils.ccompiler import ...
<python><python-3.x><unicode><encoding><subprocess>
2025-01-20 10:27:02
2
441
Energeneer
79,370,641
4,379,593
How to enforce ASCII-only identifiers in Python while allowing UTF-8 strings?
<p>I want to configure Python so that it raises an error when encountering non-ASCII characters in identifiers (e.g., variable names, function names) but still accepts UTF-8 encoded strings (e.g., &quot;Привет, мир!&quot;). For example:</p> <pre><code># This should raise an error def тест(): pass # This should wo...
<python><utf-8><ascii>
2025-01-20 08:09:05
3
373
Филя Усков
79,370,632
25,413,271
Asyncio future, running Future objects
<p>I have a code:</p> <pre><code>import asyncio as aio async def coro(future: aio.Future): print('Coro start') await aio.sleep(3) print('Coro finish') future.set_result('coro result') async def main(): future = aio.Future() aio.create_task(coro(future)) await future coro_result = fut...
<python><python-asyncio><coroutine>
2025-01-20 08:05:02
3
439
IzaeDA
79,370,497
17,837,614
Type annotate inside loop
<p>The mypy error is</p> <pre><code>Need type annotation for &quot;args&quot; [var-annotated] Need type annotation for &quot;kwargs&quot; [var-annotated] </code></pre> <p>and here is the piece of code</p> <pre><code>expected_args: Optional[Sequence[Tuple[Any, ...]]] expected_kwargs: Optional[Sequence[Dict[str, Any]]]...
<python><python-typing><mypy>
2025-01-20 06:58:18
1
405
Sujay
79,370,410
17,837,614
Invalid index type "str" for "dict[Literal[
<p>I created below types and used them to type annotate a dictionary.</p> <pre><code>objectNames = Literal[ 'TranslatableHtml', 'TranslatableUnicodeString', 'TranslatableSetOfUnicodeString', 'TranslatableSetOfNormalizedString', ] objectClasses = Union[ Type[objects.TranslatableHtml], Type[objec...
<python><python-typing><mypy>
2025-01-20 06:09:02
0
405
Sujay
79,370,096
9,801,811
How to efficiently compute spatial interpolation of a long time series data?
<p>I have a time series data with 260 time steps and 82k point observations at each time step. The points do not follow a regular gridded pattern, but the locations remain constant throughout the time series. What is the most effective way in Python to convert all time series data to a regular grid? Specifically, can w...
<python><spatial><spatial-interpolation>
2025-01-20 01:17:40
1
447
PPR
79,369,858
3,336,423
Why double `ctypes.POINTER` object works for `char***` while triple `ctypes.POINTER` would make more sense?
<p>I have a library <code>my_lib</code> with a C function that takes a <code>char***</code> parameter, a pointer to an array of <code>char*</code> that is allocated by the function. Here is a minimal reproducible example of such a function:</p> <pre><code>void getArrayOfStrings(char*** paramPtr) { (*paramPtr) = (ch...
<python><c><pointers><ctypes>
2025-01-19 22:12:25
1
21,904
jpo38
79,369,807
4,222,206
What component might emit 'Request max total header size exceeded'
<p>I am posting documents into <a href="https://docs.paperless-ngx.com/" rel="nofollow noreferrer">paperless-ngx</a> via REST api. For some pdf documents the API reliably responds with</p> <pre><code>{&quot;detail&quot;:&quot;Multipart form parse error - Request max total header size exceeded.&quot;} </code></pre> <p>I...
<python><django><gunicorn>
2025-01-19 21:37:52
1
9,930
queeg
79,369,752
179,014
How can I get the absolute path for a directory created with pyinfra?
<p>I created a new directory with pyinfra using the relative path <code>new_dir</code></p> <pre><code>from pyinfra.operations import files, server files.directory(&quot;new_dir&quot;) </code></pre> <p>Now I would like to get the absolute path of the new directory. I tried</p> <pre><code>result = server.shell(&quot;pwd...
<python><infrastructure-as-code><pyinfra>
2025-01-19 21:01:17
1
11,858
asmaier
79,369,679
8,035,772
Why is Dask slower than Pandas in computing the mean of a large dataset, and how can I improve performance?
<p>I am learning Dask to make my Python projects more efficient and scalable. To understand its performance better, I wrote a script comparing the computation time of Pandas and Dask when calculating the mean of a column in a large dataset. Here's my code:</p> <pre><code>import pandas as pd import dask.dataframe as dd ...
<python><pandas><numpy><dask>
2025-01-19 20:07:54
0
661
samman adhikari
79,369,662
506,825
How to set default datetime value with SQLAlchemy?
<p>I'm trying to set a default server value for a <code>created_at</code> column in a MySQL table with the SQLAlchemy library in Python 3.13. But, whenever I start up my Flask app and the table gets created, I run into an issue where the default value gets set to a string that reads <code>(now())</code> Inserting a row...
<python><flask><sqlalchemy><flask-sqlalchemy>
2025-01-19 19:54:20
1
4,830
Lance
79,369,611
18,100,562
Adding shaders to existing shapes, labels, drawables?
<p>Good day, friends! I would like to use existing drawable object like pyglet.shapes.Rectangle, pyglet.shapes.Line or pyglet.text.Label and add some shader effects like scaling over time, changing color over time.</p> <pre><code>class TestLabel(Label): def __init__(self): super().__init__( te...
<python><glsl><shader><pyglet>
2025-01-19 19:24:50
0
507
mister_kanister
79,369,363
5,678,653
SciPy minimise to find inverse function?
<p>I have a (non-invertible) function ak([u,v,w])</p> <p>This takes a point on the surface of the unit octahedron (p: such that |u|+|v|+|w| = 1) and returns a point on the surface of the unit sphere. The function isn't perfect but the intention is to keep the distance between points authalic.</p> <p>I was thinking of u...
<python><optimization><scipy><computational-geometry><inverse>
2025-01-19 16:53:14
2
2,248
Konchog
79,369,359
10,153,071
Problem in Backpropagation through a sample in Beta distribution in pytorch
<p>Say I have obtained some <strong>alphas</strong> and <strong>betas</strong> as parameters from a neural network, which will be parameters of the Beta distribution. Now, I sample from the Beta distribution and then calculate some loss and back-propagate via the samples obtained. Is it possible to do that? Given that ...
<python><pytorch><gradient-descent><autograd>
2025-01-19 16:52:41
1
536
Jimut123
79,369,295
2,074,831
Convert a PDF to a PNG with transparency
<p>My goal is to obtain a PNG file with a transparent background from a PDF file. The <code>convert</code> tool can do the job:</p> <pre class="lang-bash prettyprint-override"><code>$ convert test.pdf test.png $ file test.png test.png: PNG image data, 595 x 842, 8-bit gray+alpha, non-interlaced </code></pre> <p>But I...
<python><pdf><python-imaging-library><png><transparency>
2025-01-19 16:20:33
1
3,974
sevan
79,369,111
16,379,601
Numba - List() argument must be iterable
<p>I want to use numba to increase performance on a BLAST implementation. This is a very simple function to get all k-mers and their positions in a sequence</p> <pre><code>def preprocess_sequence(sequence, word_len): word_positions = dict() for i in range(0, len(sequence) - word_len + 1): word = sequen...
<python><numba>
2025-01-19 14:15:41
0
513
Marcel Lorenz
79,368,978
14,456,484
Handling indentation in multiline f-string with multiline string variables
<p>I know that we can use <code>textwrap.dedent()</code> to handle indentation of a multiline string. But if it is a multiline f-string which includes replacement of multiline string variable, it becomes a little complicated.</p> <p>The multiline strings in the following example are intentionally indented to simulate t...
<python>
2025-01-19 12:49:47
2
1,171
adamkwm
79,368,765
1,525,840
Can't create password containing parentheses in Azure CLI
<p>I'm setting up a SQL Server using CLI. It works as supposed to.</p> <pre><code>$Group = @(&quot;--resource-group&quot;, &quot;groupy&quot;) $Name = @(&quot;--name&quot;, &quot;servy&quot;) $User = @(&quot;--admin-user&quot;, &quot;BigCahoona&quot;) $Pass = @(&quot;--admin-password&quot;, &quot;Abcde12345#¤%&quot;...
<python><azure><azure-cli>
2025-01-19 10:16:02
1
40,130
Konrad Viltersten
79,368,487
219,153
How to get row numbers of maximum elements in a 2D Numpy array?
<p>I have a 2D array <code>a</code> given by:</p> <pre><code>a = np.array([[2, 3, 1, 9], [0, 5, 4, 7], [2, 4, 6, 8]]) [[2 3 1 9] [0 5 4 7] [2 4 6 8]] </code></pre> <p>I would like to get row numbers of maximum elements column-wise, i.e. given by <code>np.amax(a, axis=0)</code>, which in my example are <code>[0, 1, 2...
<python><arrays><numpy><numpy-ndarray>
2025-01-19 05:59:15
1
8,585
Paul Jurczak