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,265,244
4,434,140
Can I run a python static binary without root privilege in a docker container?
<p>I have the following <code>Dockerfile</code>:</p> <pre><code>FROM cgr.dev/chainguard/wolfi-base as builder ENV PATH=/venv/bin:$PATH COPY . /code/app RUN apk add --no-cache python-3.11 git wget jq build-base posix-libc-utils \ &amp;&amp; python3 -m venv /venv WORKDIR /tmp RUN wget $(wget -qO- https://api.githu...
<python><docker><wolfi><chainguard>
2024-04-03 04:36:00
1
1,331
Laurent Michel
78,265,205
11,922,567
Decode URL strings with Pydantic
<p>I am using <code>Pydantic</code> to validate and type an incoming <code>S3 Event</code> in an <code>AWS Lambda</code> function.</p> <p>The event looks like this (only including relevant bits):</p> <pre class="lang-json prettyprint-override"><code>{ &quot;Records&quot;: [ { &quot;s3&quot;: { &quot...
<python><urllib><pydantic><urldecode>
2024-04-03 04:22:17
1
1,822
Wesley Cheek
78,265,179
6,757,815
filtering in folium based on two column values
<p>I aim to utilize <code>ipywidgets</code> <strong>dropdowns</strong> and <code>Folium</code> to filter and visualize geodataframes. As an example, let's consider a geodataframe sourced from Natural Earth vectors, containing columns such as 'continent' and 'name'.</p> <p>My objective is to create a user interface wher...
<python><folium>
2024-04-03 04:14:53
1
517
gis.rajan
78,265,109
10,378,232
The difference of placing signal.signal before or after child process is created and started?
<p>I'm encountering an odd problem when using the <code>signal</code> module to manage process behavior.</p> <p>I want to send a <code>SIGTERM</code> signal from <code>b.py</code> after <code>a.py</code> is running to terminate the main and child processes in <code>a.py</code>.</p> <p>Now I find when <code>signal.signa...
<python><signals>
2024-04-03 03:50:22
1
412
Runstone
78,265,106
1,989,579
How to Convert u-law 8000 Hz Audio Files to OPUS in Python
<p>I'm working on a Python project where I need to convert audio files from μ-law format with an 8000 Hz sampling rate to OPUS format. The challenge is to keep the original channels separated in the conversion process. Despite several attempts with different methods and libraries, I haven't succeeded yet. I'm looking f...
<python><ffmpeg><opus><mu-law>
2024-04-03 03:49:23
1
3,512
user60108
78,265,101
6,388,372
Missing Few days data historical : Yahoo Finance API Python yahoo_fin
<p>I am fetching historical data of forex pair from yahoo finance, and I am experiencing missing data of few days. Then I tried smaller version of code and I face same issue. Please help</p> <pre><code>stock_symbol = 'USDCHF=X' #fine the timeframe start_date = '2024-04-02' end_date = '2024-04-03' # Fetch the data stoc...
<python><yahoo-finance><forex>
2024-04-03 03:48:18
0
602
KMittal
78,265,092
464,277
Error when plotting confidence intervals with NeuralProphet
<p>I'm following the tutorial on quantile regression in <a href="https://neuralprophet.com/tutorials/tutorial08.html" rel="nofollow noreferrer">NeuralProphet</a>, but there is an issue when plotting the forecast.</p> <pre><code>confidence_lv = 0.9 quantile_list = [round(((1 - confidence_lv) / 2), 2), round((confidence_...
<python><deep-learning><neural-network><time-series>
2024-04-03 03:44:15
1
10,181
zzzbbx
78,265,014
202,335
nslookup error when I use scrapy, I can access the site with a browser
<pre><code>import scrapy class CninfoSpider(scrapy.Spider): name = 'cninfo_spider' start_urls = ['https://www.cninfo.com.cn/new/commonUrl/pageOfSearch?url=disclosure/list/search'] def parse(self, response): # Extract the table rows rows = response.xpath('//table[@id=&quot;notice-table&quot...
<python><scrapy><dns>
2024-04-03 03:09:22
0
25,444
Steven
78,264,876
5,863,348
why python list doesn't implement __copy__ and __deepcopy__
<p>Unlike Python's array, which implements <code>__copy__</code> and <code>__deepcopy__</code> so that the copy module can use it, Python's list does not implement <code>__copy__</code> and <code>__deepcopy__</code>. (although there is a copy method) Instead, the logic related to list copy is implemented in the copy fu...
<python>
2024-04-03 02:15:20
1
513
YouHoGeon
78,264,848
1,610,864
How to get the full Sales by Product/Service Detail Report using QuickBooks API?
<p>I have the below Python code trying to get <code>Sales by Product/Service Detail</code> Report data.</p> <p>Under the documentation: <a href="https://developer.intuit.com/app/developer/qbo/docs/api/accounting/report-entities/SalesByProduct" rel="nofollow noreferrer">https://developer.intuit.com/app/developer/qbo/doc...
<python><quickbooks><quickbooks-online>
2024-04-03 02:03:33
0
5,784
mongotop
78,264,508
4,447,761
Fastest way to extract moving dynamic crop from video using ffmpeg
<p>I'm working on an AI project that involves object detection and action recognition on roughly 30 minute videos.</p> <p>My pipeline is the following:</p> <ul> <li>determine crops using object detection model</li> <li>extract crops using Python and write them to disk as individual images for each frame.</li> <li>use a...
<python><opencv><image-processing><ffmpeg><video-processing>
2024-04-02 23:41:18
2
3,016
NateW
78,264,493
388,640
How to summarize counts by date and item as the column header with Pandas DataFrame
<p>Given the following DataFrame in Pandas:</p> <pre><code>import pandas as pd df = pd.DataFrame( { &quot;Date&quot;: [ pd.Timestamp(&quot;2000-01-02&quot;), pd.Timestamp(&quot;2000-01-02&quot;), pd.Timestamp(&quot;2000-01-05&quot;), pd.Timestamp(&quot;2000...
<python><pandas><dataframe>
2024-04-02 23:37:09
2
2,215
Niner
78,264,432
6,202,327
Cuda error when trying to setup a project using pytorch
<p>I was trying to follow the instructions of an <a href="https://github.com/Pointcept/SegmentAnything3D" rel="nofollow noreferrer">opensource repo</a> for segmentation. At some point I ran <code>python setup.py install</code> and got this error.</p> <pre><code>!! self.initialize_options() running bdist_egg running e...
<python><deep-learning><pytorch>
2024-04-02 23:12:47
0
9,951
Makogan
78,264,382
5,404,647
Weight and shape different than the number of channels in input
<p>I'm trying to fine-tunning the VAE of <a href="https://huggingface.co/CompVis/stable-diffusion-v1-4/tree/main/vae" rel="nofollow noreferrer">SD 1.4</a></p> <p>I'm in a multi gpu environment, and I'm using <code>accelerate</code> library for handling that. This is my code summarized:</p> <pre><code>import os import t...
<python><pytorch><huggingface>
2024-04-02 22:54:13
2
622
Norhther
78,264,232
1,231,450
Calculate the standard deviation of a distribution
<p>Let's say, we have tick data like the following</p> <pre><code>,timestamp,close,security_code,volume,bid_volume,ask_volume 2024-04-02 01:00:00.128123+00:00,2024-04-02 01:00:00.128123+00:00,18465.5,NQ,1,0,1 2024-04-02 01:00:00.128123+00:00,2024-04-02 01:00:00.128123+00:00,18465.5,NQ,1,0,1 2024-04-02 01:00:03.782064+0...
<python><pandas>
2024-04-02 21:56:45
1
43,253
Jan
78,263,388
11,360,093
Autograd returning None
<p>I am trying to create a Contractive Autoencoder, and I read in a couple of papers that the main idea is to use the norm of the Jacobian of the encoder's output with respect to its inputs.</p> <p>In other words, I'm trying to obtain the gradients of the encoder's output while using the original input.</p> <p>So far, ...
<python><machine-learning><pytorch><autoencoder>
2024-04-02 18:36:19
0
472
Sanzor
78,263,371
13,592,012
How to generate point cloud using depth image in drake simulation
<p>I'm currently working on setting up a simulation environment using Drake in Python. My goal is to load various objects into the scene and generate a point cloud from a depth camera. While I've successfully set up the environment and managed to obtain the depth map, I'm struggling with generating a point cloud using ...
<python><point-clouds><robotics><drake><depth-camera>
2024-04-02 18:32:54
1
967
Karan Owalekar
78,263,337
7,619,353
C# Program cannot ReadKey when Python is running it as a subprocess
<p>I have a C# app that runs perfectly fine when executing it through a command line terminal or manually executing it. When using a python script to run the C# app, the program spits out the following error:</p> <pre><code>Unhandled Exception: System.InvalidOperationException: Cannot read keys when either application ...
<python><c#><subprocess>
2024-04-02 18:25:44
1
1,840
tyleax
78,263,331
3,700,524
Python module with name __main__.py doesn't run while imported
<p>Somebody asked me a question and I honestly didn't try it before, So it was interesting to know what exactly happens when we name a module <code>__main__.py</code>. So I named a module <code>__main__.py</code>, imported it in another file with name <code>test.py</code>. Surprisingly when I tried to run <code>test.py...
<python><python-module>
2024-04-02 18:23:52
2
3,421
Mohsen_Fatemi
78,263,178
17,174,267
tkinter export Undo Stack
<p>As far as I understood the undo feature in tkinter's Text class is implemented via a stack saving the insertions/deletions. (<a href="https://tkdocs.com/shipman/text-undo-stack.html" rel="nofollow noreferrer">tkdocs</a>) How can I export this stack so that I can import it the next time the program is launches? (I'm ...
<python><tkinter>
2024-04-02 17:51:53
1
431
pqzpkaot
78,263,052
11,233,365
Write a setup.cfg installation key to install dependencies from other installation keys
<p><strong>The Problem:</strong></p> <p>I'm writing a <code>setup.cfg</code> file for a Python package that requires different sets of dependencies depending on what it's used for. For development purposes, I want to add a key to the <code>[options.extras_require]</code> table of the <code>setup.cfg</code> file that in...
<python><configuration>
2024-04-02 17:21:45
1
301
TheEponymousProgrammer
78,263,034
3,151,415
Langchain: Dynamically route logic based on input
<p>I am trying to dynamically bind two chains. It works when the question is about 'langchain' but fails with below error if otherwise.</p> <p>Individually the RAG chain works fine.</p> <pre><code>classification_chain = ( PromptTemplate.from_template( &quot;&quot;&quot;Given the user question below, classif...
<python><artificial-intelligence><langchain>
2024-04-02 17:17:37
1
6,248
garg10may
78,262,838
16,912,844
Python Logging Color Output In Terminal Without ANSI Escape Code In File
<p>this is more of a 2 part question regarding logging and terminal output.</p> <ol> <li>How, if possible to log color output in terminal with color, but don't have them display the ANSI escape code when redirecting (<code>&gt;</code>), or output to log file? I try not to use any external library with this if possible....
<python><python-logging>
2024-04-02 16:41:24
1
317
YTKme
78,262,772
1,391,441
Remove bottom edge on marplotlib bar plot
<p>I need to generate a <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.bar.html" rel="nofollow noreferrer">bar plot </a> but without the bottom edge. Here's an example output and code:</p> <p><a href="https://i.sstatic.net/NraKy.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/NraKy....
<python><matplotlib><bar-chart>
2024-04-02 16:28:02
3
42,941
Gabriel
78,262,738
540,725
Why does Pandas loc with multiindex return a matrix with single row
<p>This question is similar to <a href="https://stackoverflow.com/questions/20383647/pandas-selecting-by-label-sometimes-return-series-sometimes-returns-dataframe">Pandas selecting by label sometimes return Series, sometimes returns DataFrame</a>, however I didn't find a solution there. I have 2 dataframes read from CS...
<python><pandas><dataframe><multi-index><pandas-loc>
2024-04-02 16:23:55
0
1,857
N4ppeL
78,262,629
234,146
Why is libopenblas from numpy so big?
<p>We are deploying an open source application based on numpy that includes libopenblas.{cryptic string}.gfortran-win32.dll. It is part of the Python numpy package. This dll is over 27MB in size. I'm curious why it is so big and where I can find the source for it to see for myself.</p> <p>Ultimately I'd like to see ...
<python><numpy><blas>
2024-04-02 16:06:45
1
1,358
Max Yaffe
78,262,552
1,467,533
How to get `GenericAlias` super types in python?
<p>Say I have a class defined as follows:</p> <pre class="lang-py prettyprint-override"><code>class MyList(list[int]): ... </code></pre> <p>I'm looking for a method that will return <code>list[int]</code> when I give it <code>MyList</code>, e.g.:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; inspect....
<python><python-typing>
2024-04-02 15:52:06
1
1,855
mattg
78,262,522
11,049,863
not all arguments converted during string formatting when trying to execute mssql stored procedure from django
<p>My procedure consists of inserting the data into a table in the database from REST API.<br/> p1,p2,p3 are the parameters coming from the user interface<br/> P1,P2,P3 are my stored procedure's parameters.<br/> Here is my code <br/></p> <pre><code>def test(request): if request.method == &quot;POST&quot;: w...
<python><sql-server><django>
2024-04-02 15:45:27
1
385
leauradmin
78,262,486
20,920,790
How to make method for pandas.to_sql for making update operation?
<p>I got some tables in database, which must be updated. How to perform this with table.to_sql for Postgresql, v.16.2? Run .to_sql with if_exists='replace' will not works, cause this table related to another.</p> <p>I now that I can make custom method for this, but I can't find working code or good explanation hot to d...
<python><pandas><postgresql><sqlalchemy>
2024-04-02 15:39:42
0
402
John Doe
78,262,455
2,168,359
Accessing Images in media/ folder In Django, as public url
<p>I can access the image on the local machine as <a href="http://127.0.0.1:8000/media/taj.jpg" rel="nofollow noreferrer">http://127.0.0.1:8000/media/taj.jpg</a> in the browser.</p> <p>How can I access the same image publicly in the browser? Like url: <a href="http://49.128.160.80:8000/media/taj.jpg" rel="nofollow nore...
<python><django><media>
2024-04-02 15:33:40
0
399
Nands
78,262,292
12,545,041
Error loading Hugging Face model: SafeTensorsInfo.__init__() got an unexpected keyword argument 'sharded'
<p>I have been using Hugging Face transformers <a href="https://huggingface.co/TheBloke/Llama-2-7B-Chat-AWQ" rel="nofollow noreferrer">quantized Llama2 model</a>. Suddenly, code I was able to run earlier today is throwing an error when I try to load the model.</p> <p>This code is straight from the docs:</p> <pre class=...
<python><nlp><huggingface-transformers><huggingface><llama>
2024-04-02 15:10:17
1
23,071
SamR
78,262,179
9,652,160
How to pick timestamps from ndarray if time() is bigger than 5:00
<p>I have an ndarray of timestamps. I need to pick timestamps if they represent a time after 5:00.</p> <p>The sample code is:</p> <pre><code>import numpy as np from datetime import datetime arr = np.array([1672713000, 1672716600, 1672720200, 1672723800, 1672727400, 1672731000]) threshold_time = datetime.strptime('5:00...
<python><numpy><numpy-ndarray>
2024-04-02 14:52:46
2
505
chm
78,262,116
764,592
How to elegantly handle optional arguments when all optional arguments are explicitly defined but is called with dict unpack which key may not exist?
<p>My question is about Pythonic way of defining the function elegantly when all optional keyword arguments are defined explicitly, but function call arguments to be unpack dynamically from a dictionary <code>**</code>.</p> <p>Example: I want my function to be defined as follows (or equivalent):</p> <pre><code>def say(...
<python>
2024-04-02 14:43:37
0
11,858
Yeo
78,262,071
11,618,586
Getting into poetry shell environment and calling jupyter-notebook via a batchfile
<p>Im using poetry shell and I want to create a bactch file that will goto the folder that has the python environment and execute jupyter-notebook command to bring up my jupyter notebook.</p> <p>The actions I execute as follows:</p> <ol> <li>CD to the folder the with environment</li> <li>Poetry shell</li> <li>Jupyter-n...
<python><batch-file><virtualenv><python-poetry>
2024-04-02 14:37:39
0
1,264
thentangler
78,261,993
7,800,760
Python Wordcloud: Help getting (near) what designers ask for
<p>I am generating a wordcloud from a term-frequency dictionary and got this: <a href="https://i.sstatic.net/REArx.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/REArx.png" alt="Wordcloud of people mentioned on a given day" /></a></p> <p>by using the following wordcloud parameters:</p> <pre><code>wordcl...
<python><word-cloud>
2024-04-02 14:25:29
1
1,231
Robert Alexander
78,261,825
7,194,474
PuLP: Constrain the number of distinct people that can work on a task
<p>I have a LP/IP problem that I'm trying to solve using PuLP. It is the division of work amongst employees. The thing that I can't figure out is how to limit the engine to only plan 1 employee on an action. In reality the problem has significantly more constraints, but I tried to minimise the problem as much as possib...
<python><pulp><integer-programming>
2024-04-02 13:54:32
2
1,897
Paul
78,261,786
1,668,622
How to conditionally clear script output after execution?
<p>I want to build/provide a wrapper for scripts with output necessary only while the script is being executed, but which should conditionally be cleaned up after script execution.</p> <p>E.g. (only an example, I'm not talking about Docker)</p> <pre><code>docker build &lt;ARGS&gt; </code></pre> <p>can be quite verbose ...
<python><bash><terminal>
2024-04-02 13:47:34
0
9,958
frans
78,261,772
13,184,183
How to prevent consequences of code execution in try block if exception is raised?
<p>I want to prevent execution on <code>try</code> block if it raises an <code>Exception</code> of any kind. Example:</p> <pre class="lang-py prettyprint-override"><code>a = 1 try: a += 1 raise ValueError except: pass print(a) </code></pre> <p>After that <code>a</code> would be equal to 2. I want it to rema...
<python><exception><try-catch>
2024-04-02 13:45:39
1
956
Nourless
78,261,716
2,546,099
Usage of torchaudio.transforms.MelSpectrogram for tensor residing on GPU
<p>I want to calculate a MelSpectrogram using torchaudio on a GPU. For testing, I wrote the following code:</p> <pre><code>from typing import Optional import torch import torchaudio import numpy as np from tests.__init__ import ( __target_clock__ as TARGET_CLOCK, __number_of_test_data_vals__ as NUMBER_OF_TES...
<python><pytorch><torchaudio>
2024-04-02 13:36:30
1
4,156
arc_lupus
78,261,632
14,045,537
Folium Custom legend compatibility issue with Fullscreen plugin
<p>I'm using the code from <a href="https://github.com/python-visualization/folium/issues/528#issuecomment-421445303" rel="nofollow noreferrer"><code>How can I add a legend to a folium map?</code></a> to create a custom draggable legend.</p> <p><a href="https://i.sstatic.net/E6v6q.png" rel="nofollow noreferrer"><img sr...
<python><html><css><folium><folium-plugins>
2024-04-02 13:24:46
1
3,025
Ailurophile
78,261,613
14,824,108
OpenAI Fine-tuning API error: "ImportError: cannot import name 'FineTune'"
<p>I'm having an issue with the OpenAI Fine-tuning API, getting the same error message after having tried several versions:</p> <p><code>ImportError: cannot import name 'FineTune' from 'openai.cli'</code></p> <p>Which is related to the following imports:</p> <pre><code>from openai import FineTune as FineTune from opena...
<python><openai-api><fine-tuning>
2024-04-02 13:21:21
1
676
James Arten
78,261,368
1,714,692
filter result of groupby with pd.Series of boolean
<p>Consider having two dataframes having the same column <code>a</code>. However in the first dataframe column <code>a</code> has unique values, whereas in the second one it does not although the possible values of column are the same in both dataframes and both of them are sorted on <code>a</code>.</p> <pre><code>df =...
<python><pandas><dataframe><filter><group-by>
2024-04-02 12:40:12
1
9,606
roschach
78,261,324
20,920,790
Geting UnicodeDecodeError in then run read_sql_query for PostgreSQL
<p>I make database by this code:</p> <pre><code>CREATE DATABASE &quot;new_db&quot; WITH OWNER &quot;postgres&quot; ENCODING 'UTF8' LC_COLLATE = 'en_US.UTF-8' LC_CTYPE = 'en_US.UTF-8' TEMPLATE template0; </code></pre> <p>Successfully added table:</p> <pre><code>CREATE TABLE public.rounds ( rounds_id bigint NOT NULL...
<python><pandas><postgresql><sqlalchemy>
2024-04-02 12:32:47
1
402
John Doe
78,261,311
3,240,681
py is not linked with latest python version
<p>Regarding the <a href="https://stackoverflow.com/a/50896577/3240681">answer</a> <code>py</code> by default, i.e. without options, should use latest Python installed on system. But for some reason I have the following on my Windows 11:</p> <pre><code>$ py --version Python 3.8.10 $ python3 --version Python 3.12.2 </c...
<python><python-3.x><windows>
2024-04-02 12:30:09
1
5,172
αλεχολυτ
78,261,229
9,212,050
Cannot run Matlab SDK module for Python inside Docker, but no issues locally
<p>I need to run a Matlab script inside Python. To achieve that, first I installed Matlab Compiler Runtime (MCR) using <a href="https://fr.mathworks.com/products/compiler/matlab-runtime.html" rel="nofollow noreferrer">this</a> documentation. Then, I used <a href="https://mathworks.com/help/compiler/package-matlab-stand...
<python><docker><matlab><sdk><matlab-compiler>
2024-04-02 12:14:04
1
1,404
Sayyor Y
78,261,001
2,526,586
Different types of Integer division in Python
<p>In terms of the resulting value (ignoring the resulting data type), are the following the same in Python if <code>x</code> and <code>y</code> are both numbers?</p> <pre><code>int(x / y) </code></pre> <pre><code>x // y </code></pre> <p>If so, which is better to use in real application? And why?</p> <p>P.S. Are there ...
<python><integer-division>
2024-04-02 11:35:28
1
1,342
user2526586
78,260,947
1,473,517
How to parallelize/speed up embarrassingly parallel numba code?
<p>I have the following code:</p> <pre><code>@nb.njit(cache=True) def find_two_largest(arr): # Initialize the first and second largest elements if arr[0] &gt;= arr[1]: largest = arr[0] second_largest = arr[1] else: largest = arr[1] second_largest = arr[0] # Iterate throu...
<python><performance><numba>
2024-04-02 11:25:33
1
21,513
Simd
78,260,939
348,168
Make a pcap file in python with two udp packets with different timestamps
<p>I have a piece of code for making pcap files taken from here: <a href="https://www.codeproject.com/tips/612847/generate-a-quick-and-easy-custom-pcap-file-using-p" rel="nofollow noreferrer">https://www.codeproject.com/tips/612847/generate-a-quick-and-easy-custom-pcap-file-using-p</a></p> <pre><code>port = 9600 #Cust...
<python><pcap>
2024-04-02 11:23:42
1
4,378
Vinod
78,260,872
14,298,525
OpenTelemetry on Gunicorn and Falcon not showing spans properly
<p>I have an application running with a combination of Falcon and Gunicorn. I am trying to use OpenTelemetry to instrument it and send traces to Jaeger.</p> <p>The following is my code:</p> <p>pyproject.toml:</p> <pre><code>opentelemetry-distro = {extras = [&quot;otlp&quot;], version = &quot;0.44b0&quot; } opentelemetr...
<python><gunicorn><open-telemetry><otel><falcon>
2024-04-02 11:13:25
2
341
mifol68042
78,260,854
7,246,472
Python - custom type annotations for tree nodes and branches
<p>I have a class representation of a ternary tree, where every node has three child nodes, which are generated via different &quot;branches&quot;, which are actually generating functions for the child nodes. The class has methods which need to process the nodes and branches, and I would like to create the correct type...
<python><python-typing>
2024-04-02 11:10:45
1
595
srm
78,260,613
188,331
After creating a Custom Tokenizer using HF Tokenizers library, how to create a model that fits the Tokenizer?
<p>I followed <a href="https://huggingface.co/learn/nlp-course/chapter6/8?fw=pt" rel="nofollow noreferrer">this tutorial</a> to create a custom Tokenizer based on <code>SentencePieceBPE</code> class, with a custom pre-tokenizer class. The newly trained Tokenizer was successfully trained with a dataset and saved on the ...
<python><huggingface-transformers><huggingface-tokenizers>
2024-04-02 10:28:20
1
54,395
Raptor
78,260,588
4,320,131
Deploying Django App onto Elastic Beanstalk (mysqlclient issue)
<p>Having a bit of a mare trying to deploy my <strong>Django app</strong> to <strong>Elasticbeanstalk AWS</strong></p> <p>I'm getting issues related to the installation of mysql. See log files:</p> <pre><code>---------------------------------------- /var/log/eb-engine.log ---------------------------------------- ×...
<python><amazon-web-services><amazon-elastic-beanstalk><libmysqlclient>
2024-04-02 10:23:27
0
1,807
William Baker Morrison
78,260,507
367,079
How to provide type hints in Python to accepts graphs with certain connections
<p>I'm working on an application, which can boil down to traversing different graphs. I have a set of shared function that require that graph adheres to certain &quot;shape&quot; (i.e. has expected transitions between vertices). I want to somehow express it using type hints. Here is the simplest example of a graph:</p>...
<python><mypy><python-typing><duck-typing>
2024-04-02 10:08:41
0
605
Filip
78,260,392
5,349,916
How to overload functions to handle Any-arguments?
<p>I have a function whose return type is sensitive to multiple arguments: If a given predicate is strong enough to provide a type constraint, the input values are similarly constrained (<code>T | None -&gt; T</code> or <code>T -&gt; R where R &lt;: T</code>). This is straightforward to type-hint if all types are known...
<python><python-typing>
2024-04-02 09:48:54
1
53,360
MisterMiyagi
78,260,387
1,581,090
How to bind a socket to a multicast UDP port on Windows-10 with python?
<p>This is a python-related programming question that maybe cannot be answered at all. Maybe there is no solution.</p> <p>But here is the setup: I am using Windows-10 on a hp laptop and a device in a local network sends out UDP packages for destination <code>239.0.0.4</code> and port <code>45004</code> (As can be confi...
<python><websocket><windows-10>
2024-04-02 09:48:30
2
45,023
Alex
78,260,375
2,351,983
AzureOpenAI returning openai.NotFoundError
<p>I am trying to create embeddings as described here: <a href="https://github.com/MicrosoftDocs/azure-docs/blob/main/articles/ai-services/openai/how-to/embeddings.md" rel="nofollow noreferrer">https://github.com/MicrosoftDocs/azure-docs/blob/main/articles/ai-services/openai/how-to/embeddings.md</a></p> <p>So this:</p>...
<python><azure><openai-api><azure-openai>
2024-04-02 09:46:36
1
356
luanpo1234
78,260,128
5,022,847
Django-cte gives: 'QuerySet' object has no attribute 'with_cte'
<p>I have records in below format:</p> <pre><code>| id | name | created | ----------------------------------------------- |1 | A |2024-04-10T02:49:47.327583-07:00| |2 | A |2024-04-01T02:49:47.327583-07:00| |3 | A |2024-03-01T02:49:47.327583-07:00| |4 | A |2024-02-01T02:49...
<python><django><common-table-expression><django-orm><django-annotate>
2024-04-02 09:04:36
2
1,430
TechSavy
78,260,093
984,621
Python - No module named 'psycopg2' even though it is installed
<p>I have installed the <code>psycopg2</code> for PSQL on OSX (<code>Requirement already satisfied: psycopg2 in ./venv/lib/python3.12/site-packages (2.9.9)</code>). When I run <code>pip list</code>, I get the following:</p> <pre><code>Package Version ---------- ------- pip 24.0 psycopg2 2.9.9 setuptools 69....
<python><python-3.x><macos><pip>
2024-04-02 08:57:39
0
48,763
user984621
78,259,971
5,379,182
Celery - cannot stop test worker within shutdown timeout
<p>When my celery worker is ready I register a custom timer</p> <pre><code>@worker_ready.connect def worker_ready_handler(sender: Consumer, **kwargs): logger.info(f&quot;Worker process ready: {sender.pid}&quot;) timer: Timer = sender.timer timer.call_repeatedly( 60, do_something, () ) </code></p...
<python><pytest><celery>
2024-04-02 08:36:11
0
3,003
tenticon
78,259,837
15,648,070
Speech to text pipelining
<p>Quit new to using models, i'm trying to use <a href="https://huggingface.co/ivrit-ai/whisper-large-v2-tuned" rel="nofollow noreferrer">ivrit-ai/whisper-large-v2-tuned model</a></p> <p>with a 'long-form' of audio file like they advice here <a href="https://huggingface.co/ivrit-ai/whisper-large-v2-tuned#long-form-tran...
<python><pipeline><huggingface-transformers>
2024-04-02 08:10:26
1
636
Eyal Solomon
78,259,726
22,414,610
How to get closest geo points in Elasticsearch with Python (Flask)
<p>I am following the <a href="https://www.elastic.co/search-labs/tutorials/search-tutorial/full-text-search" rel="nofollow noreferrer">official tutorial</a> of Elasticsearch using Python with Flask. I implemented the full text matching search, but I wanted to extend the functionality to find nearest locations. I found...
<python><elasticsearch><flask><geolocation>
2024-04-02 07:52:36
1
424
Mr. Terminix
78,259,423
988,279
Find substring with same start and end characters
<p>I've to detect a substring which starts and ends with the same characters.</p> <pre><code>import re text = &quot;/image/123.__W500__.png&quot; print(re.findall('__.*?__', text)) -&gt; ['__W500__'] </code></pre> <p>How can I get rid of the search pattern?</p> <p>-&gt; ['W500']</p> <p>Thanks.</p>
<python><python-3.x>
2024-04-02 06:44:20
3
522
saromba
78,259,328
4,399,016
Downloading an Excel file from an URL using Python
<p>The URL for Excel file is this: <a href="https://www.gso.gov.vn/wp-content/uploads/2024/03/IIP-ENG.xlsx" rel="nofollow noreferrer">https://www.gso.gov.vn/wp-content/uploads/2024/03/IIP-ENG.xlsx</a></p> <p>I have this code:</p> <pre><code>from datetime import datetime, timedelta url = 'https://www.gso.gov.vn/wp-cont...
<python><web-scraping><python-requests><openpyxl>
2024-04-02 06:24:40
3
680
prashanth manohar
78,258,962
132,438
I have exported an HLL sketch from Snowflake, how can I estimate its count?
<p>Snowflake exports its HLL sketches in dense and sparse format, depending on the size of the sketch:</p> <ul> <li><a href="https://docs.snowflake.com/en/user-guide/querying-approximate-cardinality#dense-format" rel="nofollow noreferrer">https://docs.snowflake.com/en/user-guide/querying-approximate-cardinality#dense-f...
<python><snowflake-cloud-data-platform><hyperloglog>
2024-04-02 04:32:48
1
59,753
Felipe Hoffa
78,258,960
1,362,485
Does pyodbc support multiprocessing?
<p>The intent of the code below is to perform several database updates in parallel using pyodbc and mysql. Question: are the connections opened independently and in parallel? Will this code work or I need to take a different approach? I tried to investigate pyodbc and multithreading and didn't find much.</p> <pre><code...
<python><python-multiprocessing><python-multithreading><pyodbc>
2024-04-02 04:32:18
1
1,207
ps0604
78,258,943
16,525,263
How to read the configuration from one python file in another python file
<p>I have a .py file as below:</p> <pre><code>dict_nova = { &quot;export_nova_rosterlight&quot;:{ &quot;metadata_resource_id&quot;: &quot;export_nova_rosterlight&quot;, &quot;metadata_product_version&quot; : &quot;1.0&quot;, &quot;List_Fields&quot;: [ &quot;data_export&quot;, &quot;userI...
<python><pyspark>
2024-04-02 04:26:57
1
434
user175025
78,258,602
1,413,856
Python - Understanding TKInter Frames
<p>I’m trying to understand how the Notebook and Frames work in Python.</p> <p>As far as I understand, if I want a tabbed interface, I create a Notebook widget and add Frame widgets. Here is a simple working sample:</p> <pre class="lang-py prettyprint-override"><code>import tkinter from tkinter import ttk # Main Win...
<python><tkinter>
2024-04-02 01:57:19
1
16,921
Manngo
78,258,461
264,755
Rolling count/tally between a list of values in a creative way
<p>I have 2 DataFrames. The first is has a List of Dicts of values. The second has no data, but has a list of columns that are integers.</p> <pre><code>data1 = [{'Start': 51, 'End': 55},{'Start':24, 'End':37},{'Start':89,'End':122},{'Start':44, 'End':31}, {'Start':77, 'End':50}, {'Start':10, 'End':9}] dfm1 = pd.DataFra...
<python><pandas><dataframe><rolling-computation>
2024-04-02 00:49:34
1
1,705
jasonmclose
78,258,396
3,118,190
How to compile a pydantic BaseModel using mypyc?
<p>In an environment where we have installed:</p> <pre><code>pip install -U pydantic mypy </code></pre> <p>Given the example <code>test_basemodel.py</code>:</p> <pre><code>from pydantic import BaseModel class A(BaseModel): pass </code></pre> <p>We run the command: <code> mypyc test_basemodel.py</code> and see:</p...
<python><mypy><pydantic><pydantic-v2><mypyc>
2024-04-02 00:23:42
1
648
GDub
78,258,291
214,526
Does accessing a class variable by class in instance methods cause problems?
<p>I have seen multiple posts on this - some are quite old and some are not so old. So, I thought of asking the question again as pylint issues warnings on some of the accepted answers from previous posts like <a href="https://stackoverflow.com/a/70422556/214526">https://stackoverflow.com/a/70422556/214526</a></p> <pre...
<python><python-3.x>
2024-04-01 23:38:42
1
911
soumeng78
78,257,914
2,279,796
Showing a string variable in pyspark sql
<p>How to use spark sql to get a variable. I have a table called</p> <pre><code>delta.`first/merchant/loaddate=04-02-2024` </code></pre> <p>and the last part of my table is the latest data .</p> <p>I want to somehow get the latest data and put it in the spark. So it will always load the latest.</p> <p>So I did the foll...
<python><sql><pyspark>
2024-04-01 21:34:40
1
549
Fernando Martinez
78,257,849
4,535,717
SqlAlchemy bindparam fails on mssql (but works on mysql)
<p>I am having trouble making the following work on an azure db, while it works on mysql db. Explanation why this is happening and help with resolving it would be appreciated.</p> <pre><code> with engine.begin() as conn: print(f&quot;Running with {engine.name=}&quot;) sql_q = text(&quot;S...
<python><sql-server><sqlalchemy><azure-sql-database>
2024-04-01 21:16:07
1
941
dgeorgiev
78,257,767
4,447,853
Save an Arrow Dataset or Pandas DataFrame as .bin and .idx files
<p>I'm working with Hugging Face's <code>datasets</code> library to load a DataFrame using the <code>from_pandas()</code> method and save it as a Hugging Face dataset using <code>save_to_disk()</code>. The saved dataset consists of a folder with files <code>data-00000-of-00001.arrow</code>, <code>dataset_info.json</cod...
<python><pandas><artificial-intelligence><pyarrow><binning>
2024-04-01 20:56:35
0
527
chriscrutt
78,257,700
9,343,043
Add gridlines and y=x line to seaborn lmplot
<p>I have the following code below to plot a regression plot with respect to categorical variables. The variable of interest in this question is &quot;<code>Site</code>&quot;.</p> <pre><code>children_with_PNC_plot_site = sns.lmplot(x=&quot;Z Score, Post Central WM Right for All Patients vs. All Controls, Ages 6-18&quot...
<python><matplotlib><seaborn><regression><lmplot>
2024-04-01 20:42:23
2
871
florence-y
78,257,695
20,999,380
break out of while loop if a certain time passes or any key is pressed (record keypress)
<p>I need a piece of code that waits for a user input OR an elapsed time. If a user presses any key, it records the key pressed and uses that as a variable in the next function before breaking the while loop. If 3 seconds have elapsed and they have not pressed anything, I need it to activate a different function and th...
<python>
2024-04-01 20:41:28
1
345
grace.cutler
78,257,537
557,576
Catch "request body too large" error in python on azure functions
<p>Azure storage queue has a message size limit of 64KB. I want to catch this error when it occurs in azure functions. For that I use the following code:</p> <pre class="lang-py prettyprint-override"><code>@app.blob_trigger(arg_name='inputFile', path=&quot;blob&quot;, connection='queue_con_str') @app....
<python><azure><error-handling><azure-functions><azure-storage-queues>
2024-04-01 20:02:30
0
832
Shishir Pandey
78,257,311
16,845
Type annotations: pathlib.Path vs importlib.resources.abc.Traversable
<p>When loading file resources that are bundled inside my distribution package, I use <code>importlib.resources.files</code>. When loading files from disk, I use <code>pathlib.Path</code>.</p> <p>Sometimes I want to write a function that will take either:</p> <pre><code>from importlib.resources.abc import Traversable f...
<python><python-typing>
2024-04-01 19:11:46
2
1,216
Charles Nicholson
78,257,277
5,837,992
How do I Dump MySql Tables One At a Time Using Python
<p>I am using MySQL 5.6.21 on a Windows server and need to migrate from one machine to another. Been trying to use the MySQL Workbench Export Tables and I keep getting an error 22 on write at some point during the export process.</p> <p>I am using Jupyter for simplicity.</p> <p>I want to try to dump each table individ...
<python><mysql><database-backups>
2024-04-01 19:02:33
1
1,980
Stumbling Through Data Science
78,257,262
6,328,506
How to Identify Numbers from WAV Files for Comparison?
<p>I have an HTTP request that returns an audio file where Google's voice speaks a sequence of 6 numbers in Portuguese, ranging from 0 to 9, separated by silence. I have saved WAV files in my development environment with the audio of each of the possible numbers. Now, I want to extract a segment of raw data from each o...
<python><python-3.x><audio>
2024-04-01 18:58:21
0
416
Kafka4PresidentNow
78,257,192
2,910,704
Python Django ModelViewSet implementation with SAML ACS
<p>In the current system with the legacy IAM, we have implemented a class inherited from <code>ModelViewSet</code> with login and logout functions. In the legacy IAM, it is not compulsory to obtain <code>name_id</code> and <code>session_index</code> to logout. Therefore, we can bypass <code>acs</code> (a.k.a. assertion...
<python><django><saml><django-saml2-auth>
2024-04-01 18:41:43
1
708
chesschi
78,257,175
2,791,346
Preprocess image for better barcode read results
<p>I am trying to read barcodes from images. Unfortunately, sometimes images are of low quality. I tried to preprocess the image so that the <code>Pyzbar</code> library would return better results.</p> <p>I try with</p> <p>resizing</p> <pre><code>def resize(_image, _scalar): x, y = _image.size return _image.res...
<python><opencv><image-processing><barcode><pyzbar>
2024-04-01 18:35:35
0
8,760
Marko Zadravec
78,256,967
2,074,830
How to compare each element of tensor and record result
<p>I'm trying to check each element of a tensor to determine if it is closer to one of points I specify and then associate this element to this point somehow. The data is like a table, axes X and Y are image pixel coordinates and values are depth values in millimeters (the depth_data variable).</p> <p>My implementation...
<python><pytorch>
2024-04-01 17:44:38
0
334
Zmur
78,256,905
3,078,502
Do Python packages have to be built in the same environment as the project (source) files?
<p>I am working through the official <a href="https://packaging.python.org/en/latest/tutorials/packaging-projects/" rel="nofollow noreferrer">Python Packaging Tutorial</a>. I use <code>conda</code> environments, but the question should be the same for <code>venv</code> virtual environments.</p> <p>The tutorial presents...
<python><dependencies><packaging>
2024-04-01 17:30:24
2
609
Lee Hachadoorian
78,256,836
7,796,833
SQLAlchemy: Automatically update Column on Update
<p>TL;DR: SQLAlchemy <code>Column(server_onupdate=text('now()')</code> does not trigger update.</p> <p>I am defining a simple SQLAlchemy class:</p> <pre class="lang-py prettyprint-override"><code>class Task(Base): __tablename__ = &quot;tasks&quot; id = Column(Integer, primary_key=True, index=True, nullable=Fal...
<python><postgresql><sqlalchemy>
2024-04-01 17:16:16
0
618
Carol Eisen
78,256,679
6,242,883
Why does Python's multiprocess use all cores if I am telling it not to?
<p>I am running a script that includes</p> <pre><code>import multiprocess as mp def sample(): # ... do things... return x num_cores = 50 num_samples = 1000 with mp.Pool(num_cores) as p: samples = p.starmap(self, [() for i in range(num_samples)]) </code></pre> <p>There are 128 cores in my server. However, ev...
<python><python-3.x><multiprocessing><python-multiprocessing>
2024-04-01 16:45:02
1
1,176
Tendero
78,256,629
4,218,883
Apply style on different columns from different rules through a for loop
<p>I try to highlight different columns from a DataFrame with different lists of words as references. If I chain the <code>apply</code> to the Styler object, it works, but if I <em>apply</em> successively the <code>apply</code> through a for loop, it highlights both columns with the last list of words.</p> <pre class="...
<python><pandas>
2024-04-01 16:35:50
2
1,812
Marc
78,256,497
254,172
Using already deployed Snowflake UDF from snowpark
<p>So I have a prebuilt and predeployed set of Python UDFs that I would like to use from within a snowpark program. I defined the UDFs in SQL:</p> <pre><code>CREATE OR REPLACE FUNCTION dg_utility__field_contains_phone_number(str string, pre_clean boolean) RETURNS BOOLEAN LANGUAGE PYTHON RUNTIME_VERSION = 3.8 HANDLER =...
<python><snowflake-cloud-data-platform><user-defined-functions>
2024-04-01 16:04:49
1
595
Brutus35
78,256,362
6,011,193
When run onnx with CUDAExecutionProvider, it raise "FAIL : Failed to load library libonnxruntime_providers_cuda.so with error"
<pre><code>2024-04-01 23:16:16.891282913 [E:onnxruntime:Default, provider_bridge_ort.cc:1480 TryGetProviderInfo_CUDA] /onnxruntime_src/onnxruntime/core/session/provider_bridge_ort.cc:1193 onnxruntime::Provider&amp; onnxruntime::ProviderLibrary::Get() [ONNXRuntimeError] : 1 : FAIL : Failed to load library libonnxruntime...
<python><linux><artificial-intelligence><onnx><onnxruntime>
2024-04-01 15:33:51
1
4,195
chikadance
78,256,329
5,722,359
What is the correct syntax for a Python function/method argument when it has more than one possible type hints?
<pre><code>import os def scan(path) -&gt; os.DirEntry : return os.scandir(path) </code></pre> <p>What is the correct type hint for the <code>path</code> argument of this function?</p> <p>According to <a href="https://docs.python.org/3/library/os.html#os.scandir" rel="nofollow noreferrer">documentation</a>:</p> <blo...
<python><python-typing>
2024-04-01 15:28:43
3
8,499
Sun Bear
78,256,223
116,906
How, in Python 3, can I have a client open a socket to a server, send 1 line of JSON-encoded data, read 1 line JSON-encoded data back, and continue?
<p>I have the following code for a server listening on a port:</p> <pre><code> def handle_oracle_query(self, sock, address): sockIn = sock.makefile('rb') sockOut = sock.makefile('wb') line = sockIn.readline() submitted_data = json.loads(line) self.get_thread_specific_storage()...
<python><json><python-3.x><sockets>
2024-04-01 15:06:20
2
6,021
Christos Hayward
78,256,159
7,906,796
How can I make CTRL+C interrupt the script without closing Selenium WebDriver?
<p>My Python script uses Selenium to automate a browser on Windows. I want to be able to interrupt the script by pressing <kbd>CTRL</kbd>+<kbd>C</kbd>. But even if I catch the exception, the WebDriver terminates on the interrupt:</p> <pre class="lang-py prettyprint-override"><code>from selenium import webdriver driver...
<python><windows><selenium-webdriver><keyboardinterrupt>
2024-04-01 14:53:41
2
629
ryyyn
78,256,137
20,793,070
Keep websocket alive
<p>I have a websocket subscription watcher:</p> <pre><code>async def run(): start = get_start_status() ### ON/OFF while start == 1: live = True while live == True: try: async with websockets.connect(WEBSOCKET_URL, timeout=15...
<python><python-3.x><websocket>
2024-04-01 14:49:02
0
433
Jahspear
78,255,992
4,976,543
PyTorch Geometric SAGEConv - Expected scalar type Long, but found Float?
<p>I am trying to implement graph neural networks from the torch_geometric library of model types. I am receiving an error: &quot;RuntimeError: expected scalar type Long but found Float&quot; in this line of the SAGEConv module:</p> <pre><code>&quot;(My Path)\Python310\lib\site-packages\torch_geometric\nn\dense\linear...
<python><types><pytorch><pytorch-geometric>
2024-04-01 14:18:15
1
712
Branden Keck
78,254,765
6,751,456
Django custom user admin not reflected in admin site
<p>I am new to django and going through legacy django project where Custom user admin is configured with following:</p> <pre><code>app1/admin.py </code></pre> <pre><code>from .models import User @admin.register(User) class UserAdmin(DjangoUserAdmin): &quot;&quot;&quot;Define admin model for custom User model with ...
<python><django><django-custom-user>
2024-04-01 09:56:25
1
4,161
Azima
78,254,529
17,556,733
How to setup datadog alerts without time intervals
<p>I want to create a datadog alert when a specific phrase is found in my logs, however when I create a monitor with the specific query I need, I must specify over what time period I want the query evaluated (which causes one notification when the log is spotted, and another notification when the interval elapses witho...
<python><amazon-web-services><logging><slack><datadog>
2024-04-01 08:59:17
1
495
TheMemeMachine
78,254,501
9,112,151
How to disable application/json in Swagger UI autodocs of a FastAPI application?
<p>My API can return <strong>only</strong> a file:</p> <pre class="lang-py prettyprint-override"><code> @router.get( &quot;/partners/{partner_id}/rsr-requests/{rsr_request_id}/{document_path}&quot;, responses={200: {&quot;content&quot;: {&quot;application/octet-stream&quot;: {}}, &quot;description&qu...
<python><swagger><fastapi><swagger-ui><media-type>
2024-04-01 08:53:06
2
1,019
Альберт Александров
78,254,479
589,352
Running 10,000 SELECT queries against SQLite takes hours
<p>I am using Python and the <code>sqlite3</code> lib to run around 10,000 SELECT queries against a single table. Running it locally on my not-high-spec-but-not-ancient laptop this is taking six or seven hours to complete. I created a composite index on the fields but that didn't make any difference. Here's the table a...
<python><sql><sqlite>
2024-04-01 08:48:23
2
1,937
jaybee
78,254,396
2,856,552
How do I choose individual colors for contours in matplotlib
<p>In my short python code below I am plotting risk levels based on values in a csv file and using a shapefile. The code works, but I would like to select specific individual colors for each level, namely green, yellow, orange and red. Currently it works if I put &quot;Blues&quot;, or &quot;Reds&quot; as in the attache...
<python><matplotlib>
2024-04-01 08:30:06
1
1,594
Zilore Mumba
78,254,332
1,238,967
In python how to share a large data structure across modules (no copies)
<p>I am working on a prject where I use a Pandas dataframe, rather large, and I need to let several functions access it. So far I have used a single python script, where I create the dataframe as global to the script, and then define the various functions, which read and write from/to it. So far, so good.</p> <p>Now, t...
<python><pandas><module><global-variables>
2024-04-01 08:12:42
1
1,234
Fabio
78,254,013
3,118,602
How to use SpaCy NER?
<p>I am working on a mini-project to cluster similar sentences together. Before I can achieve that, I have to perform pre-processing to the extremely dirty data (these data are all user inputs, free text).</p> <p>One of the pre-processing step that I thought of is to identify each sentence and classify it with a catego...
<python><nlp><spacy><named-entity-recognition>
2024-04-01 06:41:32
1
593
user3118602