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
78,361,457
4,575,173
Python IMAP get all the messages from one conversation via latest message id
<p>I am using Python and imapib. I have a message id of a specific message. If that message is part of conversation (I think it's called thread, I am really unfamiliar with the standard) I need to get list of all previous messages in that conversation, preferably sorted by time. I can get raw email, thread topic and in...
<python><email><imap>
2024-04-21 11:57:19
1
374
ajaleksa
78,361,389
1,082,349
Pystata: run stata instances in parallel from python
<p>I'm using the pystata package that allows me to run stata code from python, and send data from python to stata and back.</p> <p>The way I understand this, is that there is a single stata instance that is running in the background. I want to bootstrap some code that wraps around the stata code, and I would like to ru...
<python><stata>
2024-04-21 11:33:58
1
16,698
FooBar
78,361,331
5,201,005
BLE: Measure Respiratory rate or breathing rate from bluetooth low energy Device
<p>I want a Bluetooth low energy device that measures Respiratory rate (Breathing rate) in breaths per minute. I don't see any Service or characteristic in Bluetooth SIG assigned numbers and no resources.</p> <p>Some article suggests to calculate it from heart rate monitor but I don't see anything that tells how to do ...
<python><android><ios><bluetooth><bluetooth-lowenergy>
2024-04-21 11:14:34
1
305
Sudhanshu
78,361,309
614,944
Load python data similar to json.loads
<p>I'm wondering if there's a way to import Python data, e.g</p> <pre><code>[{'test1': True, 'test2': [0, 1, 2], 'test3': None}] </code></pre> <p>I need to produce a large Python data dump, e.g 300MB. First thought is to import the data as a module, so I tried to add a heading and a trailing,</p> <pre><code># heading, ...
<python>
2024-04-21 11:09:26
0
23,701
daisy
78,361,283
6,430,403
run an async websocket loop in background of flask app
<p>I am trying to build an app which will connect to a websocket (for streaming data) and provide this data with rest API. I am using <code>Flask</code> for creating my API and <code>websockets</code> package for connecting to websocket server.</p> <p>This is my code so far:</p> <pre class="lang-py prettyprint-override...
<python><flask><asynchronous><websocket><python-asyncio>
2024-04-21 10:54:24
1
401
Rishabh Gupta
78,361,034
4,417,586
Django queryset filter on a ManyToMany with custom fields
<p>I have the following Django models <code>Block</code> and <code>CustomCondition</code> that are related to each other through a custom ManyToMany relationship which has customs fields and a custom DB table:</p> <pre class="lang-py prettyprint-override"><code>from django.db import models class CustomCondition(model...
<python><django><django-models>
2024-04-21 09:33:33
1
1,152
bolino
78,360,988
13,942,929
Cython : how can I import multiple class or object from a single .pyx file
<p>For simplicity, Imma give you guys my .pyx. I have a file called Geometry.pyx and in that file I have Segment, Angle and Circle classes.</p> <pre><code>cimport Geometry # Define Python classes cdef class Segment: def __cinit__(self, float length): self.c_segment = make_shared[_Segment](length) def ...
<python><c++><cython>
2024-04-21 09:18:10
1
3,779
Punreach Rany
78,360,900
1,413,856
Extending a line
<p>As far as I understand, you can use the <code>create_line()</code> method to create a path with multiple points. For example, you can write the following:</p> <pre class="lang-py prettyprint-override"><code>points = [(10,20), (30, 40), (50,60)] line = canvas.create_line(points) </code></pre> <p>The <code>create_line...
<python><tkinter><tkinter-canvas>
2024-04-21 08:35:47
1
16,921
Manngo
78,360,777
3,405,291
Compile TensorFlow while installing by Conda
<h1>Error due to AVX</h1> <p>I have run into this error when importing TensorFlow by a simple Python statement:</p> <pre><code>&gt;&gt;&gt; import tensorflow as tf Illegal instruction (core dumped) </code></pre> <p>The <code>lscpu</code> command confirms that CPU lacks AVX instruction set. It looks like the error is du...
<python><tensorflow><anaconda><conda>
2024-04-21 07:45:05
1
8,185
Megidd
78,360,693
3,882,290
Pip ERROR: No matching distribution found for python
<p>I'm tidying up a python project for public distribution.</p> <p>It uses a virtual environment and has a requirements.txt file containing all dependencies.</p> <p>I would like this environment to include a dependency on the specific version of python I built it with. I seem to remember that this is good practice.</p>...
<python><pip><virtualenv>
2024-04-21 07:09:01
1
365
ancient geek
78,360,369
195,562
The results of math.fsum is different from a simple loop sum in python
<p>I'd like to understand why the two methods of summing a list of floating point numbers differs by exactly 32.0?</p> <pre class="lang-py prettyprint-override"><code>import math nums = [26015151255025000.,26015151255025000.,26015151255025000.,26015151255025000.,26015151255025000.,26015151255025000.,26015151255025000....
<python><arrays><math><sum>
2024-04-21 04:11:42
3
1,313
Firestrand
78,360,190
11,951,910
How to add a title to a plot in ploty using a pandas histogram
<p>I am trying to add a title to my plot but it's not working.</p> <pre><code>data.hist(by=['ascites', 'sex', 'drug']) plt.title('Ascites Distribution') plt.xlabel('Age') plt.ylabel('Number of Patients') plt.show() </code></pre> <p>The title and xlabel are not showing.</p> <p><a href="https://i.sstatic.net/GI3An.png" r...
<python><matplotlib><plot>
2024-04-21 01:49:21
1
718
newdeveloper
78,360,154
826,112
Why is there a large difference between measured time and actual time?
<p>I am playing around with big lists to test a RPi cluster. I am building a list of character strings that I will eventually calculate hashes of to simulate cryptocurrency mining. The code is running on a Raspberry Pi 3B Rev 1.2.</p> <p>The code to build the list is:</p> <pre><code>from pympler import asizeof import...
<python>
2024-04-21 01:19:38
1
536
Andrew H
78,359,858
301,644
Why would a parquet file get larger when FIXED_LEN_BYTE_ARRAY data type is used for fixed length byte array column?
<p>When trying to store a dataset in a parquet file for uploading it to HuggingFace I've encountered a strange phenomenon: when storing 50-byte array as a column, the file size gets larger when <a href="https://parquet.apache.org/docs/file-format/types/" rel="nofollow noreferrer">type</a> <code>FIXED_LEN_BYTE_ARRAY</co...
<python><serialization><encoding><format><parquet>
2024-04-20 22:14:57
1
1,493
fiktor
78,359,764
2,058,333
FastAPI fails spinning up worker
<p>I am running FastAPI inside a docker container on my deployment VM. The image tests well on my develop OSX + Docker. Now, running it on the target machine it fails with the issue below.</p> <p>It says max workers is -1?</p> <pre><code>[2024-04-20 23:26:12 +0200] [165] [INFO] Starting gunicorn 22.0.0 [2024-04-20 23:2...
<python><linux><docker><fastapi><gunicorn>
2024-04-20 21:31:23
0
5,698
El Dude
78,359,535
5,424,117
FastAPI + Async DB calls + Async response to client
<p>I have code already for using FastAPI and making an async call to the database.</p> <p>Next I need to trigger an async call to the database (to create or update) and also trigger a response to the client calling my API in an async way, so that each process runs separately and does not wait for the other one to compl...
<python><asynchronous><fastapi>
2024-04-20 19:50:34
0
2,474
jb62
78,359,422
1,380,285
Trying to find pythonic way to partially fill numpy array
<p>I have a numpy array <code>psi</code> of shape (3,1000)</p> <pre><code>psi.__class__ Out[115]: numpy.ndarray psi.shape Out[116]: (3, 1000) </code></pre> <p>I want to partially fill <code>psi</code> with another array <code>b</code></p> <pre><code>b.__class__ Out[113]: numpy.ndarray b.shape Out[114]: (3, 500) </cod...
<python><arrays><numpy>
2024-04-20 19:09:04
1
6,713
bob.sacamento
78,359,397
279,097
Polars: zscore with grouping on multiple period
<p>what is the best way with polars to calculate the zscore on multiple fields and perioid with a grouping.<br /> I have the code below but checking if I can do something better:</p> <pre class="lang-py prettyprint-override"><code>window = &quot;30d&quot; # would like to do it on a list df = ( df.sort([&quot;date&q...
<python><python-polars>
2024-04-20 19:01:00
1
415
Mac Fly
78,359,302
1,560,241
module 'sys' has no attribute 'last_traceback'
<p>A bit confused by whether this is a standard attribute. The doc string says it does exist.</p> <pre><code>In [1]: import sys In [2]: sys.last_traceback --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Cell In[2], ...
<python><traceback>
2024-04-20 18:28:14
1
812
episodeyang
78,359,292
1,769,327
Calculating Exponential Moving Average (EMA) in Polars with ewm_mean or another method
<p>Please note, this is related to <a href="https://stackoverflow.com/questions/77160103/exponential-moving-average-ema-calculations-in-polars-dataframe">Exponential Moving Average (EMA) calculations in Polars dataframe</a> that I raised 7 months ago.</p> <p>Suppose I have the following values:</p> <pre><code>values = ...
<python><dataframe><python-polars>
2024-04-20 18:26:30
1
631
HapiDaze
78,359,182
5,287,011
Time series decomposition
<p>I have a time series that I want to decompose. Dataset (train - dataframe) example (stock price):</p> <pre class="lang-none prettyprint-override"><code> Date Close 7389 2014-12-24 104.589996 7390 2014-12-26 105.059998 7391 2014-12-29 105.330002 7392 2014-12-30 105.360001 7393 2014-12-31 ...
<python><pandas><time-series><decomposition>
2024-04-20 17:46:10
1
3,209
Toly
78,358,608
8,026,780
how to log request id in django middleware?
<p>I write some code as below,but it raise an exception</p> <p>here is request_id_middleware.py</p> <pre class="lang-py prettyprint-override"><code>import uuid from django.middleware.common import CommonMiddleware from taiji.logger import logger class RequestIDMiddleware(CommonMiddleware): # pass def process_...
<python><django>
2024-04-20 14:36:57
1
453
Cherrymelon
78,358,561
736,662
Correlating response into another function with another function in Python
<p>I have a working function that obtains a value, not defined elsewhere in my script</p> <pre><code>def get_requests(t, endpoint): response = requests.get(f'{base_url}{endpoint}', headers={&quot;Authorization&quot;: f'Bearer {t}', &quot;Content-Type&quot;: 'application/json'}) try: ...
<python>
2024-04-20 14:24:37
1
1,003
Magnus Jensen
78,358,388
11,092,636
Worksheet.row_dimensions type hinting does not work properly?
<p>Worksheet's <code>row_dimensions</code> raises a Warning when I put an integer in it (for the index of the row to change the height of) although it works (height is changed and script runs correctly).</p> <p>MRE:</p> <pre class="lang-py prettyprint-override"><code>import openpyxl from openpyxl.worksheet.worksheet im...
<python><openpyxl><python-typing>
2024-04-20 13:29:53
1
720
FluidMechanics Potential Flows
78,358,268
774,575
How to remove <indexing past lexsort depth may impact performance?">
<p>I've a dataframe with a non-unique MultiIndex:</p> <pre><code> A B L1 L2 7.0 7.0 -0.4 -0.1 8.0 5.0 -2.1 1.6 5.0 8.0 -1.8 -0.8 7.0 7.0 0.5 -1.2 NaN -1.1 -0.9 5.0 8.0 0.6 2.3 </code></pre> <p>I want to select some rows using a tuple of values:</p> <pre><code>data = df.loc[(7, 7), :] </...
<python><pandas><multi-index>
2024-04-20 12:49:22
1
7,768
mins
78,358,188
11,114,048
Why do PIL and plt.imshow display different images when using the same tensor in Python?
<p>I am trying to convert a PyTorch tensor to a PIL image and display it using both matplotlib.pyplot and PIL. However, I am noticing that the images displayed by plt.imshow and PIL's display() function look different from each other.</p> <p>imshow</p> <p><a href="https://i.sstatic.net/X0qrB.png" rel="nofollow noreferr...
<python><pytorch><python-imaging-library>
2024-04-20 12:23:38
1
322
Hjin
78,358,169
11,274,362
Best Algorithm for arrange members of set with the least proximity between the members of different sets in Python
<p>We have different sets. How to arrange different members next to each other in such a way that there is the least proximity between the members of the same set? And as much as possible none of the two members of the same set are next to each other? For example</p> <pre><code>s1 = [m1, m1, m1, m1, m1, m1, m1, m1, m1,...
<python><algorithm><sorting><math>
2024-04-20 12:18:17
1
977
rahnama7m
78,358,131
5,703,539
Cannot migrate Flask db : No such command 'db'
<p>I'm new on Flask, I've been setting up a first version of my flask app : <code>test-app</code>, with a mysql database. Now I want to alter and add some columns to some of my database table without erasing the existing data. I heard about Flask-migrate with Alembic as a solution of that problem. I've tried to setting...
<python><flask><flask-sqlalchemy><flask-migrate>
2024-04-20 12:08:13
2
1,665
kabrice
78,358,124
3,623,537
get true `__dict__` if `__dict__` was overridden
<p>Is it possible to get object's true <code>__dict__</code> if <code>__dict__</code> was overridden? Are there simpler solutions than the ones below?</p> <p>I came across this example where <code>__dict__</code> was overridden and got curious. I thought python is using <code>__dict__</code> to recognize object's attri...
<python><ctypes><magic-methods>
2024-04-20 12:06:36
1
469
FamousSnake
78,358,049
1,580,469
VS Code: How to debug a Python method in debug console
<p>I have started a Python script in VS Code's debugger and have hit a breakpoint. I can examine the state in Debug Console.</p> <p>Now I would like to call a method with parameters from within the Debug Console and follow (debug) it's execution.</p> <p><a href="https://i.sstatic.net/q8xLm.png" rel="nofollow noreferrer...
<python><visual-studio-code><debugging>
2024-04-20 11:42:09
3
396
Christian
78,357,988
661,716
numba jitclass with record type of string
<p>The v3 variable is string value. I could not run with below code which gives error.</p> <pre><code>import numpy as np import pandas as pd from numba.experimental import jitclass from numba import types import os os.environ['NUMBA_VERBOSE'] = '1' # ----- BEGINNING OF THE MODIFIED PART ----- # recordType = types.Rec...
<python><numba><jit>
2024-04-20 11:16:53
1
1,226
tompal18
78,357,908
17,973,259
Django Object id's passed to the template are not the same inside the view function
<p>When I am submitting the form, the question id's that are inside the view function do not match with the question id's from the request.POST.</p> <p>When submitting the from, the print statements from the view function below are:</p> <blockquote> <p>&lt;QueryDict: {'csrfmiddlewaretoken': ['token here'], 'question_15...
<python><html><django>
2024-04-20 10:45:15
1
878
Alex
78,357,791
4,196,578
How to apply `--break-system-packages` conditionally only when the system pip/python supports it?
<p>I am adapting my pip commands to newer versions of Ubuntu (that support PEP 668). Out of the options, the only one worked so far (in my specific use case) is to</p> <blockquote> <p>Use --break-system-packages at the end of pip</p> </blockquote> <p>as indicated in <a href="https://stackoverflow.com/a/76084249/4196578...
<python><pip>
2024-04-20 10:01:39
1
22,728
thor
78,357,735
5,473,482
How can I detect the two ellipses on a roulette wheel?
<p>I have the image below:</p> <p><a href="https://i.sstatic.net/33mvLm.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/33mvLm.png" alt="roulette" /></a></p> <p>How can I detect the two ellipses below:</p> <p><a href="https://i.sstatic.net/WqMoBm.png" rel="nofollow noreferrer"><img src="https://i.sstatic...
<python><opencv><computer-vision><object-detection><semantic-segmentation>
2024-04-20 09:41:49
1
1,047
Blind0ne
78,357,734
14,256,643
Django mysql icontains not working for small case
<p>When I type <code>Travel</code> exactly same as my database it's working but when type <code>travel</code> it's working even I tried icontains for ignore case sensitivity. my code:</p> <pre><code>similar_titles_query = Q(title__icontains=search_query) &amp; Q(parent_product__isnull=True, domain_name=domain_name,is_p...
<python><mysql><django>
2024-04-20 09:41:42
1
1,647
boyenec
78,357,541
926,918
Disable pyvis from opening elinks by default
<p>I work remotely on a Ubuntu system using a terminal and <code>vi</code> editor. I want to generate output using <code>pyvis</code> which I am able to do. However, running the code also creates a terrible side-effect of invoking a CLI browser (<code>elinks</code>) that keeps running in the background even if I exit a...
<python><pyvis>
2024-04-20 08:34:50
1
1,196
Quiescent
78,357,523
1,841,839
Path to pip broken - pip : The term 'pip' is not recognized as the name of a cmdlet,
<p>if i do this from terminal in PyCharm just try to install the package with pip.</p> <pre><code>(venv) PS C:\Development\Citizenship\video_auto_generator&gt; pip install python-dotenv </code></pre> <p>I get</p> <blockquote> <p>pip : The term 'pip' is not recognized as the name of a cmdlet...
<python><pip><pycharm>
2024-04-20 08:29:31
1
118,263
Linda Lawton - DaImTo
78,357,512
1,815,710
Setting AUTH_USER_MODEL for user app within a v1 folder
<p>My django project structure looks like this</p> <pre><code>/api manage.py poetry.lock /api /v1 __init__.py /users __init__.py models.py ... /properties __init__.py ... </code></pre> <p>I'm trying to set up a custom User model by setting <code>AUTH_...
<python><django><django-rest-framework>
2024-04-20 08:26:53
1
16,539
Liondancer
78,357,478
14,923,149
How to create a combined heatmap in Python using matplotlib with normalized data and original t-test values?
<p>I have a DataFrame containing multiple features along with their associated t-test results and p-values. I aim to generate a combined heatmap in Python using Seaborn. In this heatmap, one section should display the features with normalized data using z-scores (to ensure visibility of both high and low values), while...
<python><matplotlib>
2024-04-20 08:17:45
1
504
Umar
78,357,461
3,405,291
Mount Google Drive on Google Colab with write access
<p>How can I mount my Google Drive on Google Colab with <strong>write</strong> access?</p> <p>That's because I'm receiving an error when my AI model tries to update a file on Google Drive:</p> <pre><code>Traceback (most recent call last): File &quot;/content/Deep3DFaceRecon_pytorch/test.py&quot;, line 72, in &lt;modu...
<python><google-drive-api><google-colaboratory>
2024-04-20 08:11:45
1
8,185
Megidd
78,357,424
661,716
numba jitclass, dictionary of list variables
<p>I need to have dictionary of list variables for jitclass. Following gives me error.</p> <p>I tried 10 different ways, but did not work. All dictionary values have same length of list.</p> <pre><code>import numpy as np import pandas as pd from numba.experimental import jitclass from numba import types import os os.e...
<python><numba><jit>
2024-04-20 07:53:34
1
1,226
tompal18
78,357,326
7,743,427
Can any usage of the assignment operator technically be replaced with the walrus operator surrounded by parentheses?
<p>Say we have this assignment statement:</p> <pre><code>a = 5 </code></pre> <p>Even though it'd obviously be ugly to do this for no reason, we could technically accomplish the same thing with:</p> <pre><code>(a := 5) </code></pre> <p>This still assigns 5 to <code>a</code>, and the value that the walrus operator return...
<python><python-3.x><syntax><language-design><python-assignment-expression>
2024-04-20 07:14:48
1
561
Inertial Ignorance
78,357,130
736,662
Python getting value from JSON
<p>I have a response on a request returning this json</p> <pre><code>Response: [{&quot;hpsId&quot;:10032,&quot;powerPlant&quot;:{&quot;name&quot;:&quot;Svartisen&quot;,&quot;id&quot;:67302, .... </code></pre> <p>I get the hpsId by saying</p> <pre><code>corr_value = response.json()[0][&quot;hpsId&quot;] </code></pre> <...
<python>
2024-04-20 05:53:14
2
1,003
Magnus Jensen
78,357,085
3,920,548
Welford Variance Differs from Numpy Variance
<p>I want to use Welford's method to compute a running variance and mean. I came across <a href="https://pypi.org/project/welford/" rel="nofollow noreferrer">this</a> implementation of Welford's method in Python. However, when testing to double-check that it results in the same output as the standard Numpy implementati...
<python><numpy><statistics><numerical-methods>
2024-04-20 05:28:50
1
1,784
Robbie
78,356,981
12,714,507
Terminating threads in Python using threading.Event in a class
<p>I have a Python program that uses fairly long-lived synchronous calls so things are wrapped in threads. Here's a rough MVP:</p> <pre class="lang-py prettyprint-override"><code> class MyClass: processor = None def __init__(self): self.processor_active = threading.Event() self.processor_thread...
<python><python-multithreading>
2024-04-20 04:22:54
1
349
Nimrod Sadeh
78,356,841
4,618,639
Getting 404 on Openai Azure Endpoint
<p>Using the AzureOpenAi client, and getting a 404</p> <pre><code>AsyncAzureOpenAI( api_key=os.getenv(&quot;AZURE_OPENAI_API_KEY&quot;), api_version=&quot;2024-01-25-preview&quot;, azure_deployment=&quot;XXX-staging&quot;, azure_endpoint=os.getenv(&quot;...
<python><azure><openai-api>
2024-04-20 02:38:07
1
583
Randy Song
78,356,812
13,250,589
Error: User code failed to load. Cannot determine backend specification
<p>I am using the Python sdk for firebase functions.</p> <p>When I try to deploy functions by running the command <code>firebase deploy</code> I receive this Error</p> <blockquote> <p>Error: User code failed to load. Cannot determine backend specification</p> </blockquote> <p>I get the same error when running firebase ...
<python><firebase><google-cloud-functions><firebase-tools>
2024-04-20 02:17:31
0
885
Hammad Ahmed
78,356,723
6,443,336
How to set output print precision of Sympy on Jupyter Notebook
<p>Using <code>set_global_settings</code> I was able to print variables on jupyter-notebook using scientific notation:</p> <pre><code>import sympy as sy from sympy.printing.str import StrPrinter StrPrinter.set_global_settings(min=1, max=1) a=sy.Matrix([189.001234]) a </code></pre> <p>However, I still need to set precis...
<python><jupyter-notebook><sympy>
2024-04-20 01:26:14
1
1,403
Vitor Abella
78,356,713
3,821,009
Add row of totals for certain Polars columns (and null for others) without listing each column separately
<p>Say I have this dataframe:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl df = pl.DataFrame(dict( j=[2, 7, 1, 8], k=[False, True, True, False], l=['foo', 'bar', 'quux', 'bin'], u=[5.0, 8.0, 13.0, 21.0], )) print(df) </code></pre> <pre><code>shape: (4, 4) ┌─────┬───────┬──────┬────...
<python><dataframe><python-polars>
2024-04-20 01:16:55
1
4,641
levant pied
78,356,180
339,144
Python: What happens to signal handers when another signal is received
<pre><code>import time import signal global_thing = [] class Foreman: def __init__(self): signal.signal(signal.SIGUSR1, self.handle_sigusr1) def handle_sigusr1(self, sig, frame): global_thing.append(&quot;x&quot;) i_am_nr = len(global_thing) for i in range(4): p...
<python><signals>
2024-04-19 21:10:50
1
2,577
Klaas van Schelven
78,355,920
6,386,155
How do you count repeating entries in a column?
<p>I have a data frame like this:</p> <div class="s-table-container"><table class="s-table"> <thead> <tr> <th>Value</th> </tr> </thead> <tbody> <tr> <td>0</td> </tr> <tr> <td>0</td> </tr> <tr> <td>0</td> </tr> <tr> <td>1</td> </tr> <tr> <td>1</td> </tr> <tr> <td>0</td> </tr> <tr> <td>0</td> </tr> </tbody> </table></div...
<python><pandas><dataframe>
2024-04-19 19:51:48
1
885
user6386155
78,355,889
10,625,777
Dealing with I/O exceptions beyond OSError
<p>I have an endless program that needs to write to daily log files. Below is basically my Message class that opens a file at startup and closes/opens a new file daily. Now I'm testing for error handling, as the program should not die even if it can't write logs. For example, the file system fills up. Most normal I/O e...
<python><attributeerror><valueerror><oserror>
2024-04-19 19:44:11
0
495
Chris
78,355,856
16,717,009
Identify if there is a contiguous group of non-zeros in a list
<p>I have a list of integers. I want to know if the non-zero numbers form a <em>single</em> contiguous group. So for instance:</p> <pre><code>[0, 0, -1, 2, -3, 0] True [1, 2, 3, 0, 0, 0] True [1, 2, 3, 4, 5, 0] True [1, 1, 1, 1, 1, 1] True [0, 1, 0, 3, 3, 3] False [1, 2, 3, 0, 3, 0] False [0, 0, 0, 0, 0, 0] False </cod...
<python>
2024-04-19 19:34:26
3
343
MikeP
78,355,676
4,117,496
OSError: libtorch_cuda_cpp.so: cannot open shared object file: No such file or directory
<p>I needed to have Python <code>torchaudio</code> library installed for my application which is packaged into a Docker image.</p> <p>I am able to do this easily on my EC2 instance easily:</p> <pre><code>pip3 install torchaudio python3 Python 3.10.12 (main, Nov 20 2023, 15:14:05) [GCC 11.4.0] on linux Type &quot;help&q...
<python><python-3.x><docker><pytorch><torchaudio>
2024-04-19 18:47:00
1
3,648
Fisher Coder
78,355,442
719,812
Python json.dumps of a tuple with some UTF-8 characters, either fails or converts them. I want the encoded character retained as is
<p>On my server, a Python script gets data from a database as a tuple. Then the script converts the tuple to a string (using json.dumps()) to be passed to the JavaScript script in the user's browser.</p> <p>The data include German names such as Weidmüller. When the Python scrip gets that data, it returns it as Weidm\xf...
<python><json><python-2.7><utf-8>
2024-04-19 17:51:49
1
1,425
Davide Andrea
78,355,329
9,771,547
TypeError: ADAM.minimize() got an unexpected keyword argument 'initial_point'
<p>When I run the below code, it shows the below error. I tried with COBYLA and still same,</p> <pre><code> optimizer = ADAM(maxiter=100) new_params = optimizer.minimize(len(agent.params), objective, initial_point=agent.params) </code></pre> <p><a href="https://i.sstatic.net/BlyYt.png" rel="nofollow norefer...
<python><optimization><qiskit><adam>
2024-04-19 17:23:07
0
351
monir zaman
78,355,159
895,029
How to monkey patch `__init__` in a third party module?
<p>I'm trying to monkey patch the <code>__init__</code> method of a third party module (<a href="https://github.com/jborean93/smbprotocol/tree/master" rel="nofollow noreferrer">smbprotocol</a>).</p> <p>Specifically, the <code>SMBDirectoryIO#_init__</code> which inherits from <code>SMBRawIO#__init__</code> (<a href="htt...
<python><python-3.x><monkeypatching><smb>
2024-04-19 16:41:59
0
4,506
rwb
78,355,151
5,786,649
Combining paths from hydra configurations (varible interpolation)
<p>I am using hydra for configuration management.</p> <p>When my configuration files contain parts of paths (folder names, file names), what is the most convenient way to create a full path to a given file? As an example:</p> <p>I have a <code>config.yaml</code> that contains some folder names:</p> <pre class="lang-yam...
<python><fb-hydra>
2024-04-19 16:40:42
1
543
Lukas
78,355,086
1,231,450
Pandas rolling closest value
<p>Suppose we have the following dataframe:</p> <pre><code> timestamp open high low close delta atr last_index bearish bullish_turning_point 2 04-10-2024 01:54:44 18370.00 18377.75 18367.50 18376.00 32 0 1949 False True 5 04-10-2024 03:21:14...
<python><pandas>
2024-04-19 16:30:37
2
43,253
Jan
78,355,057
6,714,667
How can i iterate through this list and return a text if threshold not met?
<pre><code>scores = [0.9,0.8,0.3,0.4] new=[] for sc in scores: if sc &lt; 0.8: pass else: new.append(sc) print(new) </code></pre> <p>however i want to also include a response IF none of the scores are &gt;0.8 then print &quot;none of the scores in list had a score that met threshold&quot; how c...
<python><python-3.x>
2024-04-19 16:22:40
3
999
Maths12
78,354,977
1,104,581
Why can't I get PySpark to drop the right duplicate columns after a 'leftouter' join with a Dataframe that is itself the result of a join?
<p>I have the following input dataframes:</p> <pre class="lang-py prettyprint-override"><code>expected = spark.createDataFrame( # fmt: off data=[ {&quot;id&quot;: &quot;1&quot;, &quot;group&quot;: &quot;1&quot;, &quot;start&quot;: 1_000_000, &quot;stop&quot;: 1_001_200, &quot;info&quot;: &quot;info1&quo...
<python><apache-spark><join><pyspark>
2024-04-19 16:06:52
1
2,104
dr-igor
78,354,974
2,573,075
AWS DeepAR predict returns 400
<p>I'm trying to run a DeepAR to do some estimation for a series the next 15 records based on current and previous months.</p> <p>I follow the examples and I believe that everything is ok. Still I have a very cryptic error.</p> <p>I put here the code:</p> <pre><code>predictor = estimator.deploy( initial_instance_co...
<python><amazon-web-services><time-series><amazon-sagemaker><deepar>
2024-04-19 16:05:59
2
633
Claudiu
78,354,862
6,546,694
polars getting a StringCacheMismatchError even after using stringcache context manager
<p>Using polars throughout</p> <p>I want to use replace to kind of like labelencode my categorical columns. The problem is that my dataframe is made by concatenating other dataframes</p> <p>I can do the following:</p> <pre><code>df1 = pl.DataFrame( {'a':[1,2], 'b':['a','b']}, schema = {'a':pl.Float32, 'b'...
<python><dataframe><python-polars><categorical-data>
2024-04-19 15:44:15
2
5,871
figs_and_nuts
78,354,838
2,803,344
RuntimeError when using keras 3 with pytorch backend
<p>I am trying to reproduce the VAE model demonstrated in the document of Keras3: <a href="https://keras.io/examples/generative/vae/" rel="nofollow noreferrer">https://keras.io/examples/generative/vae/</a> and <a href="https://keras.io/guides/making_new_layers_and_models_via_subclassing/#putting-it-all-together-an-endt...
<python><machine-learning><keras><pytorch><neural-network>
2024-04-19 15:39:03
0
3,867
Belter
78,354,782
4,434,140
how to use returns.context.RequiresContext with async functions in python?
<p>I am very fond of the <a href="https://github.com/dry-python/returns" rel="nofollow noreferrer">returns</a> library in python, and I would like to use it more. I have a little issue right now. Currently, I have a function that uses a redis client and gets the value corresponding to a key, like so:</p> <pre class="la...
<python><functional-programming>
2024-04-19 15:28:13
2
1,331
Laurent Michel
78,354,689
8,618,987
Python script not returning results from MSSQL stored procedure, despite successful execution
<p>I'm encountering an issue with retrieving results from an MSSQL stored procedure using a Python script. Here's the problem:</p> <p>I have a stored procedure <code>getlive_value</code> in my MSSQL database <code>XStudio_Historian</code>. When I execute this stored procedure in SQL Server Management Studio using the q...
<python><sql-server><stored-procedures><pyodbc>
2024-04-19 15:11:56
0
549
Ranjit Singh Shekhawat
78,354,679
10,962,766
Problem decoding Google News URLS that contain consent information
<p>I have a particular problem decoding base64 Google News URLs in Python when they do not only contain a URL but also consent information.</p> <p>Based on the older issue <a href="https://stackoverflow.com/questions/51131834/decoding-encoded-google-news-urls">decoding Google news urls</a>, I wrote the following functi...
<python><base64><google-news>
2024-04-19 15:11:01
2
498
OnceUponATime
78,354,610
12,846,524
Customtkinter: Close the dropdown menu when the dropdown arrow is clicked again
<p>I have a piece CustomTkinter GUI that has several combobox dropdowns. I am having an issue with closing the popup when clicking the dropdown arrow for a second time. I have tried looking online for anybody having the same issue but I've not found much, and digging through the source code on GitHub didn't bring me an...
<python><oop><tkinter><dropdown><customtkinter>
2024-04-19 15:00:24
1
374
AlexP
78,354,489
2,604,247
Are Totally Different Python Scripts Running on the Same Host Influenced by the GIL?
<p>As the question says, if I run two different python scripts on two different terminals (Ubuntu 22.04) like</p> <pre><code>$ python3 script1.py $ python3 script2.py </code></pre> <p>does the global interpreter lock still prevent their concurrent execution? Or does the GIL only prevents thread pooling or process pool...
<python><multithreading><concurrency><gil>
2024-04-19 14:40:52
0
1,720
Della
78,354,467
1,356,926
Python and C++ long double give different results
<p>I'm trying to debug an inconsistency between a piece of C++ code and another piece of Python code which are returning different results.</p> <p>In general, I have always expected floating point operations between the two environments to yield equal results, assuming the initial floating point values are the same. Fo...
<python><c++><numpy><floating-point><precision>
2024-04-19 14:37:19
1
5,637
Svalorzen
78,354,338
11,468,323
No way to terminate python process; using trio, running as root, reading /proc/bus/input/devices
<p>I wanted to achieve some of the functionality that <code>keyboard</code> python package offers, but without threads, instead using trio.</p> <p>I created an async function that reads <code>/proc/bus/input/devices</code> to look for keyboards, then starts a task (in a nursery) for each keyboard found - basically it o...
<python><python-trio>
2024-04-19 14:17:03
1
325
Paweł Lis
78,354,236
7,615,872
Call an async function in Pydantic custom Validator
<p>I have 2 Paydantic models <code>Article</code> and <code>Author</code> defined as follow:</p> <pre><code>from pydantic import BaseModel from typing import List class Author(BaseModel): id: int first_name: str class Article(BaseModel): id: int name: str authors: List[Author] </code></pre> <p>Th...
<python><python-3.x><python-asyncio><pydantic>
2024-04-19 14:02:30
1
1,085
Mehdi Ben Hamida
78,354,145
4,791,408
Concatenate large matrices leads to memory error
<p>I have two large sparse matrices which I want to concatenate, I am using the following function.</p> <pre><code>all_data = sparse.vstack([train_data_pt_a, train_data_pt_b]) </code></pre> <p>I can load the two matrices without any issue, however, when the <code>vstack</code> happens, the memory usage spikes and the p...
<python><numpy><matrix><scipy><sparse-matrix>
2024-04-19 13:50:56
0
1,064
RUser4512
78,354,136
16,115,413
How to Send a Streaming Response via LlamaIndex to a FastAPI Endpoint?
<p>I need to send a streaming response using LlamaIndex to my FastAPI endpoint. Below is the code I've written so far:</p> <pre class="lang-py prettyprint-override"><code>@bot_router.post(&quot;/bot/pdf_convo&quot;) async def pdf_convo(query: QuestionInput): chat_engine = cache[&quot;chat_engine&quot;] user_que...
<python><nlp><openai-api><large-language-model><llama-index>
2024-04-19 13:49:16
1
549
Mubashir Ahmed Siddiqui
78,354,106
10,983,470
Surprising results comparing 2 pd.array
<p>Using <code>python</code> 3.10.13, <code>pandas</code> 2.2.0 with <code>numpy</code> 1.26.4, I expected to be able to use something like (as required by the ruff linter) :</p> <pre class="lang-py prettyprint-override"><code># this is False $ (pd.array([&quot;&quot;]) == pd.array([&quot;&quot;]))[0] is True False # ...
<python><python-3.x><pandas>
2024-04-19 13:45:26
1
1,783
cbo
78,353,981
827,927
Sequentially reading inputs of different types in Python
<p>My program gets as input an integer, then a string, then another integer, all in the same line of input. In C++, I can read them from the standard input in one line, as follows:</p> <pre><code>int a; string b; int c; cin &gt;&gt; a &gt;&gt; b &gt;&gt; c; </code></pre> <p>Moreover, I can easily read custom types like...
<python><input>
2024-04-19 13:23:38
1
37,410
Erel Segal-Halevi
78,353,844
8,119,069
Python module to get PDF text coordinates
<p>Is there a Python module that has the possibility of returning contents of a PDF file as a list of bounding boxes, with top and left coordinates and text value? Something like Firefox has would be ideal, this is what I mean. <a href="https://i.sstatic.net/b7FPb.jpg" rel="nofollow noreferrer"><img src="https://i.ssta...
<python><pdf><pypdf>
2024-04-19 13:01:51
0
501
DoctorEvil
78,353,817
8,040,369
Changing the structure of a DataFrame in Python from row level to column level
<p>I have a DataFrame like below</p> <pre><code>name Type value ================================== AAA 1 Increase AAA 2 Decrease AAA 3 Neutral </code></pre> <p>I would like to convert the structure of the DF to something like below</p> <pre><code>name Type1 Type2...
<python><pandas><dataframe>
2024-04-19 12:57:20
0
787
SM079
78,353,737
9,212,050
Continue TensorBoard Logging from a Previous Timestep When Resuming Training with Stable Baselines3
<p>I am working with a reinforcement learning model using Stable Baselines3, specifically a PPO model. I train my model for a certain number of timesteps, let's say 500, using the following code:</p> <pre><code>log_dir='./logging_directory/' model = PPO_model(&quot;MlpPolicy&quot;, env, verbose=1, tensorboard_log=log_d...
<python><reinforcement-learning><tensorboard><stable-baselines>
2024-04-19 12:41:27
0
1,404
Sayyor Y
78,353,691
5,743,955
Pyright with multiple venv (monorepo)
<p>Got an issue with pyright on a monorepo: it didn't recognize classes/functions imported from nearby projects/libraries (get a <code>reportMissingImports</code>).</p> <p>For instance, with this repo structure:</p> <pre><code>. ├── library |   └── src |    └── __init__.py ├── project1 |   └── src |   └── main.p...
<python><sublimetext><python-venv><pyright>
2024-04-19 12:34:50
1
334
Romain
78,353,074
8,840,275
PIL Image Crop and Resize Degrading Quality
<p>I am writing an image-processing script.</p> <ol> <li>Hits background removal API</li> <li>Detect item bounds in the image</li> <li>Crops image based on bounds co-ordinates and places it on a 1400 x 1000 canvas</li> <li>Save to PNG</li> </ol> <p>The image I got back from the background removal API is the perfect col...
<python><python-imaging-library>
2024-04-19 10:39:48
1
327
Piers Thomas
78,352,986
12,890,458
Salabim 3D animation example program is not running
<p>I am running the <a href="https://www.salabim.org/manual/3dAnimation.html#example" rel="nofollow noreferrer">example program</a>, see below, from the 3D animation page of the salabim website (salabim is a discrete event simulation package in Python)</p> <pre><code>import salabim as sim env = sim.Environment() env.b...
<python><event-simulation>
2024-04-19 10:22:46
1
460
Frank Tap
78,352,972
4,873,946
extracting blocks of data using numpy
<p>Here is a problem I am having:</p> <p>I want to plot some energy bands obtained with Quantum Espresso. The data comes in a file with two columns. The columns are separated by empty lines into blocks. Each block corresponds to a band.</p> <p>Here is an example of the first two blocks:</p> <pre><code> 0.0000 -44.2...
<python><numpy>
2024-04-19 10:19:55
3
454
lucian
78,352,905
621,591
Pydantic BaseModel validation order for Json vs str
<p>Can someone tell me why Pydantic is validating a field as a string even though the field type is <code>Json[Any] | str</code>? And is there a way to have it return a dict instead?</p> <pre class="lang-py prettyprint-override"><code>from typing import Any from pydantic import BaseModel, Json class FooStr(BaseModel...
<python><pydantic><pydantic-v2>
2024-04-19 10:06:15
1
4,621
Brendan Maguire
78,352,595
10,396,491
Angular transformation matrix for 6 DoF simulation using scipy.spatial.transform.Rotation
<p>I am writing a simulator for 6 DoF motion of a vehicle and need to transform the moments and angular velocities defined in the global coordinate system into the vehicle reference frame and back. Normally this is done using:</p> <p><a href="https://i.sstatic.net/4wcRI.png" rel="nofollow noreferrer"><img src="https://...
<python><scipy><simulation><physics><motion>
2024-04-19 09:11:29
1
457
Artur
78,352,556
1,654,955
milvus.py: pymilvus.exceptions.MilvusException: <MilvusException: (code=1, message=Field full_length is not in the hit entity)>
<p>I query a collection in a zilliz milvus db like this:</p> <pre><code>documents = vector_store.similarity_search_with_score(query) </code></pre> <p>The query is successful but in line 777 of milvus.py the value <code>result.full_length</code> is retrieved, which is not available:</p> <pre><code>for result in res[0]: ...
<python><langchain><milvus>
2024-04-19 09:02:53
3
312
Tilman Rossmy
78,352,361
2,411,320
Docker build stopped working after Ubuntu software update
<p>Docker build was ok, and the Python script (app) that was inside could be executed perfectly too. I hadn't touched the code for some months now, but I recently did a general, across-system software update in my Oracle VM VirtualBox Ubuntu 20.04.3 LTS x86_64. I thought this wouldn't affect my docker, since I had spec...
<python><linux><docker><tensorflow><ubuntu>
2024-04-19 08:31:31
1
73,655
gsamaras
78,352,244
4,847,250
How to put a dictionary into the clipboard to copy/paste it in another pyqt6 window?
<p>I would like to use the clipboard to pass a dict from a Qapplication to another.</p> <p>I can copy a text, but I don't understand how I can pass something else. I need to pass a dict instead of a text.</p> <p>Here is a minimal example where I can launch the software twice and copy the text to the other one:</p> <pre...
<python><clipboard><pyqt6>
2024-04-19 08:09:39
0
5,207
ymmx
78,352,141
3,070,181
Modifying an environment vairiable when running a Python subprocess
<p>I am attempting to run a Python subprocess in a different virtualenv from the default. I have based my solution on <a href="https://stackoverflow.com/a/4453495/3070181">this answer</a>. My script is</p> <pre><code>import os import subprocess from pathlib import Path from icecream import ic VIRTUAL_ENV = str(Path(Pa...
<python><subprocess>
2024-04-19 07:49:36
2
3,841
Psionman
78,352,063
6,376,297
python concurrent.futures.ProcessPoolExecutor causes BrokenProcessPool error when run in a Visual Studio Code notebook with Windows 10
<p>The example code in the <a href="https://docs.python.org/3/library/concurrent.futures.html#processpoolexecutor-example" rel="nofollow noreferrer">official doc</a> of <code>concurrent.futures.ProcessPoolExecutor()</code> :</p> <pre><code>import concurrent.futures import math PRIMES = [ 112272535095293, 11258...
<python><jupyter-notebook><parallel-processing>
2024-04-19 07:34:41
1
657
user6376297
78,352,004
2,473,382
Global fixture in pytest
<h1>Question</h1> <p>I want, with <em>as little boilerplate possible</em>, to mock one of my function.</p> <h1>Project Setup</h1> <p>In my (simplified) project, I have the following files/functions:</p> <ul> <li><code>utils.py</code>, with function <code>get_id(param1, param2)</code> (that is what I want to mock)</li> ...
<python><python-3.x><unit-testing><pytest><monkeypatching>
2024-04-19 07:24:54
1
3,081
Guillaume
78,351,990
11,082,237
Is there a way to safely import a Python module from untrusted user input?
<p>I want to dynamically import a module, based on untrusted user input, and be confident that the submodule that I will import comes from a specific trusted module directory.</p> <p>I intend to process user input in the following way :</p> <pre class="lang-py prettyprint-override"><code>import importlib submodule_name...
<python><input><python-import>
2024-04-19 07:22:23
1
863
Pierre couy
78,351,963
11,441,731
Why am I getting an error when backpropagating through a compiled PyTorch module multiple times?
<p>I'm working on a PyTorch project where I have a custom module called that applies axial rotatry position embeddings to tensors. I've implemented both a regular and a compiled version of this module using torch.compile. When I try to backpropagate through the compiled version multiple times, I encounter the followin...
<python><pytorch><autograd>
2024-04-19 07:16:17
1
471
Kinyugo
78,351,628
10,216,112
CMake error: Cannot find python executable
<p>I had a CMake file which searches for a python executable as</p> <pre><code>find_program(PYTHON python) if(NOT PYTHON) if(MSVC) set(PYTHON &quot;python3.12&quot;) else() message(FATAL_ERROR &quot;could not find python executable&quot;) endif() endif() get_filename_component(PYTHON_PATH &q...
<python><visual-studio><cmake>
2024-04-19 06:09:41
1
7,901
Himanshu Poddar
78,351,590
9,522,658
sqlalchemy-file package FileField is not allowing to give custom filename, automatically saves the file as unnamed
<p>I am using sqlalchemy-file package FileField to save files in local storage, it is being saved but not allowing to give custom filename, automatically saves the file as unnamed. I need to fix that.</p> <p>I am working on FastAPI project and using file variable as shown below to save files</p> <pre><code>from sqlalch...
<python><file><file-upload><sqlalchemy><fastapi>
2024-04-19 05:58:48
1
570
Avin Mathew
78,351,569
51,816
Aligning/syncing one audio file to another using Python
<p>I have 2 audio files recorded using laptop mic and one with external mic. Laptop mic recording starts after external mic. The time difference could be 2-60 seconds.</p> <p>So I wrote this code which is pretty accurate, but when I bring both audio tracks (one from the video that uses laptop mic) and the newly adjuste...
<python><audio><scipy><signal-processing><correlation>
2024-04-19 05:52:40
0
333,709
Joan Venge
78,351,491
16,723,655
How numpy array full show in jupyter notebook without wrapping?
<p>I already referred to <a href="https://stackoverflow.com/questions/55466277/how-to-print-the-full-numpy-array-without-wrapping-in-jupyter-notebook">'How to print the full NumPy array without wrapping (in Jupyter Notebook)'</a>.</p> <p>However, my array size is 256x256.</p> <p>Therefore, it is automatically wrapping ...
<python><numpy><jupyter-notebook>
2024-04-19 05:19:01
1
403
MCPMH
78,351,381
15,233,792
How to measure Flask API response time and record them in logs?
<p>I have a log system for my flask API</p> <pre class="lang-py prettyprint-override"><code>import logging def setup_logger(logp=None, debug=False): log_level = logging.DEBUG if debug else logging.INFO form = &quot;[%(asctime)s][%(name)s][%(levelname)s][%(filename)s] %(message)s&quot; datefmt = &quot;%Y-%m...
<python><flask><logging>
2024-04-19 04:40:42
1
2,713
stevezkw
78,351,374
2,444,008
Django " [ was not closed " error in url routing
<p>I'm new to python. Trying to understand and following the tutorials. One of the many tutorials that I follow, in django for url routing we are creating url.py and put our routing logic inside that file as below:</p> <pre><code>urlpatterns = [ path=(&quot;&quot;,views.index), path=(&quot;/index&quot;,views.in...
<python><django>
2024-04-19 04:34:39
1
1,093
ftdeveloper
78,351,077
20,122,390
Is asyncio in Python user-level threading model, cooperative scheduling?
<p>I have been working for a long time with asyncio in Python, however I would like to clarify some thoughts on how asyncio actually works. I will break down my thoughts so that I can give context and that you can correct me if I have any errors in the bases. I understand that Python programs are kernel-level threading...
<python><python-asyncio><python-multithreading>
2024-04-19 02:28:17
1
988
Diego L