QuestionId
int64
74.8M
79.8M
UserId
int64
56
29.4M
QuestionTitle
stringlengths
15
150
QuestionBody
stringlengths
40
40.3k
Tags
stringlengths
8
101
CreationDate
stringdate
2022-12-10 09:42:47
2025-11-01 19:08:18
AnswerCount
int64
0
44
UserExpertiseLevel
int64
301
888k
UserDisplayName
stringlengths
3
30
โŒ€
79,457,349
9,261,322
How to install gitpython in GitBash on Windows?
<p>I downloaded Python 3.13.2 zip archive (Windows embeddable package (64-bit)). It contains the following files:</p> <pre><code>_asyncio.pyd _bz2.pyd _ctypes.pyd _decimal.pyd _elementtree.pyd _hashlib.pyd _lzma.pyd _multiprocessing.pyd _overlapped.pyd _queue.pyd _socket.pyd _sqlite3.pyd _ssl.pyd _uuid.pyd _wmi.pyd _zo...
<python><git-bash>
2025-02-21 12:22:00
2
4,405
Alexey Starinsky
79,457,247
13,769,291
How to get rid of a level in pandas dataframe?
<p>I want to remove some data from a Pandas dataframe and make it over. I tried using the drop function but this didnt work. It is unclear to me whether the data is a row or level. The picture below will hopefully clarify the issue.</p> <p>Using pd.columns I got the following information about the dataframe:</p> <pre><...
<python><pandas>
2025-02-21 11:30:56
0
357
Alex
79,457,237
6,101,024
fit function stops after epoch 1
<p>I have implemented this function to fit the model</p> <pre><code>def fit_model(model, X_train_sequence_tensor,Y_train_sequence_tensor, epochs, val_set, time_windows, scaler): X_column_list = [item for item in val_set.columns.to_list() if item not in ['date', 'user', 'rank','rank_group', 'counts', 'target']]...
<python><machine-learning><deep-learning>
2025-02-21 11:26:50
2
697
Carlo Allocca
79,457,089
1,251,549
Return same class from its function in Python?
<p>I have written:</p> <pre><code>class MyClass: def myfucntion(self) -&gt; MyClass: &quot;&quot;&quot;&quot;&quot;&quot; </code></pre> <p>And IntelliJ IDEA tells me <code>Unresolved reference 'MyClass'</code> on function defintion.</p> <p>What is missed? How define function that returns class where it defi...
<python><python-typing>
2025-02-21 10:38:08
0
33,944
Cherry
79,457,083
1,422,096
UI element for an infinite scrolling image gallery for 100k images: which data structure?
<p>I'm making an (infinite) scrollable GUI that displays 100x100px thumbnails of possibly 100 000 image files (JPG), in Python <code>Tkinter</code>.</p> <p>The MCVE code below works:</p> <p><a href="https://i.sstatic.net/xJv7e2iI.png" rel="noreferrer"><img src="https://i.sstatic.net/xJv7e2iI.png" alt="enter image descr...
<python><image><tkinter><tkinter-canvas><tile>
2025-02-21 10:35:29
4
47,388
Basj
79,456,811
1,145,666
Google Vision AI does not include correct documentation
<p>I am using the following code to do OCR using Google Vision AI:</p> <pre><code>from google.cloud import vision client = vision.ImageAnnotatorClient() bindata = base64.b64decode(b64data) # b64data is a Base64 encoded image file image = vision.Image(content=bindata) results = client.text_detection(image=image) <...
<python><documentation><google-cloud-vision>
2025-02-21 09:00:01
1
33,757
Bart Friederichs
79,456,717
2,315,319
'pdm build' adds date to scm version number, TestPyPI rejects it
<p>My distribution project is managed with git, The last tag is <code>0.1.2.dev1</code>. I use PDM (<a href="https://pdm-project.org" rel="nofollow noreferrer">https://pdm-project.org</a>). The relevant snipped in <code>pyproject.toml</code> is:</p> <pre><code>[build-system] requires = [&quot;pdm-backend&quot;] build-b...
<python><pypi><python-pdm>
2025-02-21 08:18:48
0
313
fishfin
79,456,688
9,144,522
Spread out task evenly over a minute, some tasks will run multiple times and should have equal distance to each other
<p>I have a conifg file with a list of bash script that should run <code>times_per_min</code> amount of time(s) during 60 seconds.</p> <p><code>tasks.yaml</code>:</p> <pre><code>every_minute: - name: test0 path: test0.sh times_per_min: 3 - name: test1 path: test1.sh times_per_min: 2 </co...
<python>
2025-02-21 08:01:06
1
341
Jesper.Lindberg
79,456,596
17,173,476
How to instantiate a single element Array/List in Polars expressions efficiently?
<p>I need to convert each element in a polars df into the following structure:</p> <pre class="lang-json prettyprint-override"><code>{ &quot;value&quot;: &quot;A&quot;, &quot;lineItemName&quot;: &quot;value&quot;, &quot;dimensions&quot;: [ { &quot;itemCode&quot;: 1, &quot;dim...
<python><python-polars>
2025-02-21 07:20:26
1
487
Vinz
79,456,565
6,629,148
Trigger a DAG based on upstream DAG completion (unscheduled)
<p>I am trying to see if I can trigger a DAG (say B1) to run (daily) if an upstream DAG (say A1) complete's run. I am already aware about <a href="https://airflow.apache.org/docs/apache-airflow/stable/howto/operator/external_task_sensor.html#externaltasksensor" rel="nofollow noreferrer">ExternalTaskSensor</a>, but my l...
<python><airflow><airflow-2.x><astronomer>
2025-02-21 07:05:00
1
1,088
Anand Vidvat
79,456,467
11,422,407
Python request LM Studio Model failed but Curl successful
<p>I tried to request local model by using Python with below code,</p> <pre><code>import requests import json url = 'http://localhost:1234/v1/chat/completions' headers = { 'Content-Type': 'application/json' } data = { 'model': 'deepseek-r1-distill-qwen-7b', 'messages': [ {'role': 'system', 'conte...
<python><large-language-model><rag><lm-studio>
2025-02-21 06:06:22
1
1,576
leo0807
79,456,337
16,405,935
How to subtract data between columns that have same subfix
<p>I have a sample dataframe as below that has same subfix as <code>001, 002, 003</code>.</p> <pre><code>import pandas as pd import numpy as np branch_names = [f&quot;Branch_{i}&quot; for i in range(1, 11)] date_1 = '20241231' date_2 = '20250214' date_3 = '20250220' data = { 'Branch': branch_names, date_1 + '...
<python><pandas>
2025-02-21 04:09:17
1
1,793
hoa tran
79,456,253
1,252,307
Connection pool for beanie?
<p>I have the following function in my code:</p> <pre><code>async def context(client_id: str) database = f'db_{client_id}' await init_beanie( database=database, document_models=[ .. # quite a few models ], ) </code></pre> <p>Every time I fetch something from the database I...
<python><mongodb><beanie>
2025-02-21 02:40:21
1
9,915
kev
79,455,927
6,471,140
how to get the target generated query on a self-query retriever(langchain)
<p>I'm implementing a <a href="https://python.langchain.com/api_reference/langchain/retrievers/langchain.retrievers.self_query.base.SelfQueryRetriever.html" rel="nofollow noreferrer">self-query retriever</a> using langchain with OpenSearch as the target vectore store, so far everything is good but we need to capture t...
<python><nlp><artificial-intelligence><langchain>
2025-02-20 21:57:26
0
3,554
Luis Leal
79,455,807
182,781
Python Debugger not contributing to built-in Terminal's environment
<p>I'm unable to get the Python Debugger to contribute to the built-in Terminal's output. I learned about that feature in a screenshot here: <a href="https://github.com/microsoft/vscode-python-debugger/wiki/No%E2%80%90Config-Debugging" rel="nofollow noreferrer">https://github.com/microsoft/vscode-python-debugger/wiki/N...
<python><visual-studio-code>
2025-02-20 20:47:27
0
4,701
Marc Liyanage
79,455,749
3,732,793
Command not found when installing it with poetry
<p>python is 3.12.3 on linux and in pyproject.toml</p> <pre><code>[tool.poetry.dependencies] deptry = &quot;^0.18.0&quot; </code></pre> <p>and poetry reports</p> <pre><code>The following packages are already present in the pyproject.toml and will be skipped: - deptry </code></pre> <p>poetry install did run without a...
<python><python-poetry>
2025-02-20 20:18:50
2
1,990
user3732793
79,455,684
16,383,578
How can one scrape any table from Wikipedia in Python?
<p>I want to scrape tables from Wikipedia in Python. Wikipedia is a good source to get data from, but the data present is in HTML format which is extremely machine unfriendly and cannot be used directly. I want the data in JSON format.</p> <p>As an example, the following scrapes the primary table from here: <a href="ht...
<python><web-scraping><wikipedia>
2025-02-20 19:54:55
1
3,930
ฮžฮญฮฝฮท ฮ“ฮฎฮนฮฝฮฟฯ‚
79,455,667
3,936,496
mix two dataframes with every second row
<p>I have two dataframes that I want to mix togther first two of the second table go to the every second two of, so like this:</p> <pre><code>First table Second table column_1 column_1 1 5 2 6 3 7 4 ...
<python><pandas>
2025-02-20 19:44:57
4
401
pinq-
79,455,504
1,194,864
Load Phi 3 model extract attention layer and visualize it
<p>I would like to visualize the attention layer of a <code>Phi-3-medium-4k-instruct</code> (or mini) model downloaded from hugging-face. In particular, I am using the following <code>model, tokenizer</code>:</p> <pre><code>import torch from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline import pdb ...
<python><pytorch><huggingface-transformers><attention-model>
2025-02-20 18:25:48
1
5,452
Jose Ramon
79,455,366
10,034,073
Allow Enum Names as Valid Inputs with Pydantic's @validate_call
<p><a href="https://stackoverflow.com/questions/67911340/encode-pydantic-field-using-the-enum-name-instead-of-the-value">This question</a> asks about using the name of an enum when serializing a model. I want something like that except with the <code>@validate_call</code> decorator.</p> <p>Take this function <code>foo(...
<python><enums><pydantic>
2025-02-20 17:28:56
1
444
kviLL
79,455,179
18,476,381
Fetching an image and meta-deta from S3 and returning via API in a restful manner
<p>I have an API that takes a time range input and fetches and returns the image back to the client via an API. One addition that makes this a bit tricky is that I also want to return some meta-data in the same response, such as the actual time range of the file. I've read some previous threads about having two differe...
<python><rest><amazon-s3><bucket>
2025-02-20 16:26:47
0
609
Masterstack8080
79,455,175
16,383,578
Python lxml.html SyntaxError: invalid predicate with XPATH when using lxml find
<p>I am using CPython 3.12.6, lxml 5.3.1, Windows 11 Pro 23H2 x64.</p> <p>The following Python code raises an exception:</p> <pre><code>tree.find(&quot;.//table[contains(@class, 'wikitable')]//tr&quot;) </code></pre> <pre><code>SyntaxError: invalid predicate </code></pre> <p>Interestingly the following works:</p> <pre>...
<python><python-3.x><xpath><lxml>
2025-02-20 16:24:58
1
3,930
ฮžฮญฮฝฮท ฮ“ฮฎฮนฮฝฮฟฯ‚
79,455,091
940,490
Gracefully terminate `asyncio` program in Python with a full queue
<h2>The Problem</h2> <p>I have a simplified example of an asynchronous program (Python 3.9) that is not working when exceptions are raised in futures, and I am looking for ways to gracefully terminate it.</p> <p>In particular, when the number of failed requests exceeds the sum of the queue size and the number of worker...
<python><asynchronous><python-asyncio>
2025-02-20 15:55:11
2
1,615
J.K.
79,454,901
2,921,683
Monotonically increasing id order
<p>The spec of monotonically order id <a href="https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.functions.monotonically_increasing_id.html" rel="nofollow noreferrer">monotonically_increasing_id</a> says</p> <blockquote> <p>The generated ID is guaranteed to be monotonically increasin...
<python><dataframe><apache-spark><pyspark><apache-spark-sql>
2025-02-20 14:49:54
1
1,403
BelowZero
79,454,786
1,654,143
Detect highlighted text in .docx
<p>I'm trying to detect text that has a coloured background in a MS Word docx, to separate it from the &quot;normal&quot; text.</p> <pre><code>from docx import Document ... # Load the document doc = Document(docx_path) highlighted_text = [] normal_text = [] # Iterate through all paragraphs for para in doc.paragraphs: ...
<python><python-3.x><ms-word>
2025-02-20 14:08:31
3
7,007
Ghoul Fool
79,454,470
1,679,410
Integrate Superset with API using Shillelagh
<p>I am trying to connect my Superset deployment using docker, with JSON APIs. I have tried using it with <a href="https://github.com/betodealmeida/shillelagh/blob/main/ARCHITECTURE.rst" rel="nofollow noreferrer">Shillelagh</a> but i am getting following errors:</p> <p><a href="https://i.sstatic.net/BHFepEQz.png" rel="...
<python><apache-superset>
2025-02-20 12:13:41
1
2,618
Dakait
79,454,460
2,197,109
Yfinace - Getting Too Many Requests. Rate limited. Try after a while
<p>i am getting Too Many Requests. Rate limited. Try after a while.</p> <p>while trying</p> <pre><code>response = yfinance.Ticker(&quot;MSFT&quot;) </code></pre> <p>my traceback:</p> <pre class="lang-none prettyprint-override"><code>File &quot;/usr/local/lib/python3.13/site-packages/yfinance/scrapers/quote.py&quot;, li...
<python><yfinance>
2025-02-20 12:12:01
2
775
Kalyanakannan padivasu
79,454,335
3,808,018
Google Earth Engine: Exported NDVI Rasters are Empty Despite Correct Visualization
<p>I am using Google Earth Engine (GEE) to export monthly median NDVI rasters from the MODIS MOD13Q1 dataset, clipped to a specific fire polygon.</p> <h3><strong>Issue</strong></h3> <ul> <li>NDVI visualizes correctly in the GEE Console (with expected values).</li> <li>Exported GeoTIFFs are completely empty (NaN values)...
<javascript><python><google-earth-engine>
2025-02-20 11:26:24
0
4,132
Derek Corcoran
79,454,185
5,868,293
How to apply different model on different rows of a pandas dataframe?
<p>I have a pandas dataframe that looks like this:</p> <pre><code>import pandas as pd df = pd.DataFrame({'id': [1,2], 'var1': [5,6], 'var2': [20,60], 'var3': [8, -2], 'model_version': ['model_a', 'model_b']}) </code></pre> <p>I have 2 different models, saved in <code>pkl</code> files, which I load them like this:</p> <...
<python><pandas><scikit-learn>
2025-02-20 10:38:44
1
4,512
quant
79,454,104
166,442
Using match statement with a class in Python 3
<p>Can somebody explain why in the following code Two matches?</p> <pre><code>&gt;&gt;&gt; class One: ... pass ... &gt;&gt;&gt; class Two: ... pass ... &gt;&gt;&gt; a = One() &gt;&gt;&gt; &gt;&gt;&gt; match a.__class__: ... case Two: ... print(&quot;is two&quot;) ... is two &gt;&gt;&gt; </code></...
<python><python-3.x>
2025-02-20 10:14:04
2
6,244
knipknap
79,453,988
6,930,340
Applying numpy partition to a multi-dimensional array
<p>I need to find the <code>k</code> smallest element within a <code>np.array</code>. In a simple case you would probably use <code>np.partition</code>.</p> <pre><code>import numpy as np a = np.array([7, 4, 1, 0]) kth = 1 p = np.partition(a, kth) print(f&quot;Partitioned array: {p}&quot;) print(f&quot;kth's smallest e...
<python><numpy>
2025-02-20 09:39:08
1
5,167
Andi
79,453,780
13,560,598
detecting debug mode for python in visual studio
<p>Let's say I have a file called script.py which I am running under Visual Studio 2022 Community Edition. I am running script.py by right clicking on the window and choosing `Start with debugging' or 'Start without debugging'. I would like to detect which mode it is launched in from inside the script. For C++, the pr...
<python><visual-studio><debugging>
2025-02-20 08:27:34
0
593
NNN
79,453,775
447,426
handling large tgz with pcap in pyspark - ValueError: can not serialize object larger than 2G
<p>I have a pyspark based pipeline that uses spark.read.format(&quot;binaryFile&quot;) to decompress tgz files and handle the pcap file inside (exploding to packages etc). The code that handles the tar, pcap, and single packets is written as pure python and integrated as &quot;User Defined Function&quot;.</p> <p>This p...
<python><apache-spark><pyspark>
2025-02-20 08:24:29
0
13,125
dermoritz
79,453,757
671,013
Define a dynamic default value of an option based on another option when using Typer
<p>I have the following ~minimal code:</p> <pre class="lang-py prettyprint-override"><code>from typing import Annotated import typer def main( username: Annotated[ str, typer.Option(&quot;--username&quot;, &quot;-u&quot;, help=&quot;Short username&quot;, show_default=False), ], cluster_na...
<python><python-click><typer>
2025-02-20 08:15:47
0
13,161
Dror
79,453,711
2,695,990
How to configure python simple "logging" with different colors for different levels
<p>I have created simple python script:</p> <pre class="lang-py prettyprint-override"><code>import logging import sys if __name__ == &quot;__main__&quot;: logging.basicConfig(level=logging.DEBUG) print(&quot;This is a normal print statement&quot;, file=sys.stdout) logging.debug(&quot;debug message&quot;) ...
<python><logging><colors><log-level>
2025-02-20 07:57:12
1
3,174
fascynacja
79,453,625
143,091
Download data models while installing my python library
<p>Sometimes, a Python library depends on additional data, such as ML models. This could be a model from <code>transformers</code>, <code>spacy</code>, <code>nltk</code>and so on. Typically there is a command to download such a model:</p> <pre><code>python -m nltk.downloader stopwords </code></pre> <p>How can I have th...
<python><nltk><spacy><pyproject.toml><uv>
2025-02-20 07:21:18
1
10,310
jdm
79,453,531
4,131,060
Using a python library installed in virtual environment from script running in standalone application
<p>There is a python library that only wants to be installed in a virtual environment, but how to import the library into scripts running in my standalone application that does not run in a virtual environment?</p> <p>I'm writing a a Delphi/Lazarus application using the component Python4Delphi and Python4Lazarus to run...
<python><delphi><lazarus>
2025-02-20 06:33:11
1
400
Rimfire
79,453,312
13,869,231
How to find points that preserve given nearest neighbor distance?
<p>I have a set of two-dimensional points, <code>X</code> with dimension of <code>n by 2</code>, and nearest neighbor distance of <code>Dx (n by 1) </code> where <code>DX(i)</code> being the distance of <code>X(i)</code> to its nearest neighbor. I want to generate nontrivial Y with the constraint that <code>Dy=Dx</code...
<python><random>
2025-02-20 03:57:37
2
436
Zain
79,452,945
72,437
When using asyncio to make 4 requests to gemini-1.5-flash, it gives Error code: 429 - Resource has been exhausted, RESOURCE_EXHAUSTED
<p>I try to use <code>gemini-1.5-flash</code>, to process 4 chunk of text, using async way.</p> <pre><code>def generate_readable_transcript(transcript: str, model: str, converter: OpenCC) -&gt; str: readable_transcript = asyncio.run(_generate_readable_transcript( transcript = transcript, model = mod...
<python><google-gemini><google-generativeai>
2025-02-19 22:38:20
1
42,256
Cheok Yan Cheng
79,452,943
13,132,728
Pandas - How to backfill a main dataframe with values from another while prioritizing the main dataframe
<h1>SET UP MY PROBLEM</h1> <p>I have two pandas dataframes. First, I have <code>main</code>:</p> <pre><code>import pandas as pd import numpy as np main = pd.DataFrame({&quot;foo&quot;:{&quot;a&quot;:1.0,&quot;b&quot;:2.0,&quot;c&quot;:3.0,&quot;d&quot;:np.nan},&quot;bar&quot;:{&quot;a&quot;:&quot;a&quot;,&quot;b&quot;...
<python><pandas><dataframe><missing-data>
2025-02-19 22:37:04
0
1,645
bismo
79,452,925
605,006
Barebones Python Function App via IaC for Azure
<p>I need a bare minimum Bicep file to create an <strong>EMPTY</strong> Python 3.11 Function App in Azure via Infrastructure as Code (IaC). I do not want App Insights support. I should be able to deploy to a preexisting resource group named rg-py-func-tst via this one line command:</p> <pre class="lang-none prettyprint...
<python><azure-functions><azure-bicep><infrastructure-as-code>
2025-02-19 22:27:16
1
752
Shawn Eary
79,452,893
3,727,648
poetry-plugin-shell install hangs when installing ptyprocess
<p>Background: Switched from pip to poetry and I am trying to utilize an existing virtual environment by running poetry shell. I am currently on a Windows machine.</p> <p>When I try to install the poetry shell plugin using <code>poetry self add poetry-plugin-shell</code>, the installation hangs (i.e., does not proceed ...
<python><python-poetry>
2025-02-19 22:08:05
1
485
MatthewS
79,452,824
15,412,256
Python Polars Encoding Continous Variables from Breakpoints in another DataFrame
<p>The breakpoints data is the following:</p> <pre class="lang-py prettyprint-override"><code>breakpoints = pl.DataFrame( { &quot;features&quot;: [&quot;feature_0&quot;, &quot;feature_0&quot;, &quot;feature_1&quot;], &quot;breakpoints&quot;: [0.1, 0.5, 1], &quot;n_possible_bins&quot;: [3, 3,...
<python><python-polars>
2025-02-19 21:26:24
3
649
Kevin Li
79,452,813
10,006,235
How to apply a custom function across multiple columns
<p>How to extend this</p> <pre><code>df = df.select( pl.col(&quot;x1&quot;).map_batches(custom_function).alias(&quot;new_x1&quot;) ) </code></pre> <p>to something like</p> <pre><code>df = df.select( pl.col(&quot;x1&quot;,&quot;x2&quot;).map_batches(custom_function).alias(&quot;new_x1&quot;, &quot;new_x2&quot;) ) </...
<python><dataframe><python-polars>
2025-02-19 21:20:48
1
474
Nip
79,452,710
8,292,630
uv in PyCharm / handling local imports
<p>Issue: I've created project with uv as venv manager. To this venv I &quot;uv pip install .&quot; my local library caled commons. When testing in terminal all works well but PyCharm does not recognize common module (it is on a list of modules - &quot;uv pip list&quot;.</p> <p>Now, in terminal opened in PyCh I'm alrea...
<python><pycharm><uv><venv>
2025-02-19 20:29:28
0
315
Ranny
79,452,659
509,301
Is Fernet implementation threadsafe?
<p>I have the following code</p> <pre class="lang-py prettyprint-override"><code>from cryptography.fernet import Fernet encryption_key=&quot;....&quot; fernet_instance = Fernet(encryption_key) encoded_value = fernet_instance.encrypt(&quot;some text&quot;).decode() </code></pre> <p>Is <code>Fernet</code> implementation ...
<python><fernet>
2025-02-19 20:09:33
0
336
Dan Corneanu
79,452,414
7,976,097
Gio.Settings behaviour changing with environment
<p>I have a CMake project where I want to execute a Python script as part of the install target to automatically set a global keyboard shortcut for the target that gets installed.</p> <p>The script itself works when started from the terminal but when I add it to the install target like so</p> <pre class="lang-none pret...
<python><cmake><gnome><gio>
2025-02-19 18:29:57
1
436
Nummer_42O
79,452,360
11,515,528
Pandas list dates to datetime
<p>I am looking to convert a column with dates in a list [D, M, Y] to a datetime column. The below works but there must be a better way?</p> <pre><code>new_df = pd.DataFrame({'date_parts': [[29, 'August', 2024], [28, 'August', 2024], [27, 'August', 2024]]}) display(new_df) ## Make new columns with dates new_df = pd.co...
<python><pandas>
2025-02-19 18:03:57
2
1,865
Cam
79,452,212
1,506,763
Numba np.linalg.eigvalsh exception raised inconsistenlty
<p>I'm using <code>numba</code> to compile some expensive calcualtion for signifcant performance gains - this is wonderful! Recently I made a small change to the calcualtion to extract some additional values (eigenvalues), cleared the cache and started to test. Everything compiles without error and starts to run.</p> <...
<python><numpy><linear-algebra><numba><eigenvalue>
2025-02-19 17:06:18
0
676
jpmorr
79,452,027
5,098,711
How to connect from Python to Postgres DB deployed on Azure Container Apps?
<p>I am facing an issue connecting from python to postgres on Azure Container Apps (ACA).</p> <p>What do I need to modify to fix the connection issue?</p> <p>ACA deployment yaml definition:</p> <pre class="lang-yaml prettyprint-override"><code>properties: workloadProfileName: D16 configuration: activeRevisionsM...
<python><postgresql><docker><azure-container-apps>
2025-02-19 16:04:24
0
890
kanimbla
79,451,974
3,048,363
word/ sentence similarities
<p>I am trying to find if a given word/ set of words are similar to a definition.</p> <p>Example - Definition - &quot;vegetarian User&quot;</p> <p>Now, if I want to check a set of sentences like below</p> <pre><code>sentences = ['vegetarian User', 'user sometimes eats chicken', 'user is vegetari...
<python><python-3.x><nlp>
2025-02-19 15:47:45
1
1,091
A3006
79,451,916
11,571,390
How to Preserve Autocomplete for String Arguments While Avoiding Magic Strings in Code?
<p>I have a large codebase with hundreds of functions that take string arguments, and I want to reduce brittle use of hardcoded strings while preserving autocomplete for users.</p> <p><strong>The Problem</strong></p> <p>Right now, functions look like this:</p> <pre><code>def process_data(dataset: str = &quot;default_da...
<python><python-typing>
2025-02-19 15:29:39
0
595
Gary Frewin
79,451,761
113,586
Using pytest-twisted functions with pytest-asyncio fixtures
<p>I have code that uses Twisted so I've written a test function for it and decorated it with <code>@pytest_twisted.ensureDeferred</code>. The function awaits on some Deferreds. Then, I need to run some <code>aiohttp</code> website in it so I've written a fixture that uses the <code>pytest_aiohttp.plugin.aiohttp_client...
<python><pytest><python-asyncio><twisted><pytest-asyncio>
2025-02-19 14:41:02
2
25,704
wRAR
79,451,702
8,477,566
Python multiprocessing.Process hangs when large PyTorch tensors are initialised in both processes
<p>Why does the code shown below either finish normally or hang depending on which lines are commented/uncommented, as described in the table below?</p> <p>Summary of table: if I initialise sufficiently large tensors in both processes without using <code>&quot;spawn&quot;</code>, the program hangs. I can fix it by maki...
<python><pytorch><python-multiprocessing><freeze>
2025-02-19 14:27:04
1
1,950
Jake Levi
79,451,592
1,309,245
Airflow DAG gets stuck when filtering a Polars DataFrame
<p>I am dynamically generating Airflow DAGs based on data from a Polars DataFrame. The DAG definition includes filtering this DataFrame at DAG creation time and again inside a task when the DAG runs.</p> <p>However, when I run the dag and I attempt to filter the polars dataframe inside the dynamically generated DAG, th...
<python><airflow><python-polars><polars>
2025-02-19 13:56:58
1
1,407
elvainch
79,451,344
17,500,571
Handling Occasional 100 MB API Responses in FastAPI: Polars vs. NumPy/Pandas?
<p>I'm working on an asynchronous FastAPI project that fetches large datasets from an API. Currently, I process the JSON response using a list comprehension and NumPy to extract device IDs and names. For example:</p> <pre><code>response = await client.get(tenant_url, headers=headers, params=params) response.raise_for_s...
<python><dataframe><for-loop><fastapi><python-polars>
2025-02-19 12:34:13
1
364
Foxbat
79,451,332
13,559,669
Slow data download into Windows shared folder via Databricks using SMB
<p>I use Databricks (python) to download data from a public source directly into a Windows shared drive (NetApp folder) using SMB protocol, but it is downloading at 700 kbps on average, whereas when using Azure Data Factory (on the same Azure VNet) to do the same, it downloads at 5.5 mbps on average.</p> <p>Some additi...
<python><windows><databricks><azure-databricks><smb>
2025-02-19 12:32:07
1
436
el_pazzu
79,451,254
2,112,406
Github actions to test python scripts after creating and activating conda environment not working
<p>I have a repo where there are a bunch of python scripts, and there's a <code>environment.yml</code> file to create a conda environment with. I run tests by:</p> <pre><code>conda env create -f environment.yml conda activate env_name cd tests pytest </code></pre> <p>I want to automate this with github actions. I have ...
<python><github-actions><conda>
2025-02-19 12:05:25
1
3,203
sodiumnitrate
79,451,234
9,318,323
Self-signed certificate error when working with PreparedRequest and Session objects
<p>I have an app running on Azure that was not setup by me, I just need to use its API.</p> <p>If I use the code below, it works just fine.</p> <pre class="lang-py prettyprint-override"><code>import os import requests from msal import PublicClientApplication connection_data = { &quot;url&quot;: &quot;url&quot;, ...
<python><ssl><python-requests><ssl-certificate>
2025-02-19 11:56:59
0
354
Vitamin C
79,450,942
497,649
How to set height & width in pm4py's graph visualization?
<p>If I use the Python package <code>pm4py</code>, I get a nice graph visualization. However, the size is quite small in terms of height, and I want to change it. The code so far:</p> <pre><code>from pm4py.visualization.bpmn import visualizer as bpmn_visualizer parameters = bpmn_visualizer.Variants.CLASSIC.value.Param...
<python><package><rendering><process-mining>
2025-02-19 10:10:23
0
640
lambruscoAcido
79,450,855
7,227,146
multiprocess library barely works
<p>I'm using the <a href="https://pypi.org/project/multiprocess/" rel="nofollow noreferrer"><code>multiprocess</code></a> library to accelerate a CPU-bound task (a method inside a user-defined class).</p> <p>The function processes a page of a document, in my example a 500-page document takes around 20 seconds sequentia...
<python><multiprocessing><multiprocess><dill><pathos>
2025-02-19 09:45:42
0
679
zest16
79,450,852
571,033
Null-aware Evaluation flawed in Polars 1.22.0?
<p>I observed that the polars expression:</p> <pre><code>pl.DataFrame(data={}).select(a=pl.lit(None) | pl.lit(True)) </code></pre> <p>evaluates to True, but it should evaluate to None in my estimation, based on the concept of &quot;null aware evaluation&quot;.</p> <blockquote> <p>This concept ensures that if any part o...
<python><dataframe><python-polars><polars>
2025-02-19 09:45:38
1
1,527
Silverdust
79,450,810
1,635,450
Pandas groupby multiple columns, aggregate some columns, add a count column of each group
<p>The data I am working with:</p> <pre><code>data (140631115432592), ndim: 2, size: 3947910, shape: (232230, 17) VIN (1-10) object County object City object State ...
<python><pandas><group-by><aggregation>
2025-02-19 09:32:13
2
4,280
khteh
79,450,165
11,156,131
Sorting axis in pandas plot
<p>How can I sort the axis in descending order? I tried the following and it did not work:</p> <pre class="lang-py prettyprint-override"><code>from io import BytesIO from fpdf import FPDF import pandas as pd import matplotlib.pyplot as plt import io DATA = { 'x': ['val_1', 'val_2', 'val_3', 'val_4', 'val_5'], ...
<python><pandas><matplotlib><fpdf2>
2025-02-19 04:18:20
2
4,376
smpa01
79,450,153
5,118,421
How does this algo cuttree hackerrank work?
<p>Given a tree T with n nodes, how many subtrees (Tโ€™) of T have at most K edges connected to (T โ€“ Tโ€™)? <strong>Input Format</strong></p> <p>The first line contains two integers n and K followed by n-1 lines each containing two integers a &amp; b denoting that thereโ€™s an edge between a &amp; b.</p> <p><strong>Constrain...
<python><algorithm>
2025-02-19 04:07:13
1
1,407
Irina
79,450,048
10,902,944
Sending large Dask graphs causing major slowdown before computation
<p>I am encountering a warning from Dask where it takes a long time to start a computation (roughly around 5 minutes) because of my large task graphs. Here is the full warning:</p> <pre><code>UserWarning: Sending large graph of size 29.88 MiB. This may cause some slowdown. Consider loading the data with Dask directly ...
<python><python-xarray><google-earth-engine>
2025-02-19 02:25:48
0
397
Adriano Matos
79,449,962
17,296,506
Why is RStudio Data Viewer Wrong with Python pd.DF - Snowflake Query
<p>At loss why when I look at the data viewer in RStudio it looks like it does in the image below yet when I print the data frame it looks normal. Am I missing something? It works fine in Spyder</p> <h2>Sample Code</h2> <pre><code># pip install `snowflake-connector-python` and `pandas` if not already installed import s...
<python><snowflake-cloud-data-platform><rstudio>
2025-02-19 01:01:32
0
371
Eizy
79,449,933
10,576,557
Skip bad hosts and return good results on Fabric call
<p>I would like to send a remote command to multiple hosts using the Python Fabric library. The following code works as long as all hosts are available</p> <pre class="lang-none prettyprint-override"><code>#!/usr/bin/python3 import fabric group = fabric.ThreadingGroup('boss1', 'boss2') results = group.run('uname -a', ...
<python><fabric>
2025-02-19 00:35:05
1
569
shepster
79,449,698
1,492,613
how can I add new LD path in python?
<pre><code>import ctypes.util import importlib.util import os lib_dir=... # some local installed clibs os.environ[&quot;LD_LIBRARY_PATH&quot;] = lib_dir + &quot;:&quot; + os.environ.get(&quot;LD_LIBRARY_PATH&quot;, &quot;&quot;) os.environ[&quot;PATH&quot;] = lib_dir + &quot;:&quot; + os.environ.get(&quot;PATH&quot;, &...
<python><python-3.x>
2025-02-18 21:54:19
0
8,402
Wang
79,449,605
793,154
How to ask for parameter before installations with Poetry?
<p>My package's Python version depends on one of its dependencies'. Since it integrates with Databricks, the corresponding runtime environment (DBR) sets a dependency package <code>databricks-connect</code> which then fixes the Python version. That is to say:</p> <pre><code>DBR 13.3 -&gt; Python 3.10 DBR 14.3 -&gt; P...
<python><databricks><python-packaging><python-poetry><databricks-connect>
2025-02-18 20:59:44
0
2,349
Diego-MX
79,449,433
554,305
Installing/Compiling wxPython for Python 3.13t (free threaded)
<p>I want to use wxPython under free threaded Python 3.13. Currently, there is no wheel file available.</p> <p><strong>Problem 1</strong>: Pip will build from source but fail due to missing packages.</p> <p><strong>Solution 1</strong>: I installed <code>wheel, setuptools, six</code> - and all packages listed in <code>\...
<python><pip><build><wxpython>
2025-02-18 19:46:52
0
395
BeschBesch
79,449,424
11,156,131
FPDF2 separate styling in table
<p>Is it possible to separately style column headers and row values? I tried this but it generates same style for both. I am only keen on different font-size and font-color.</p> <pre><code>from fpdf import FPDF from fpdf.fonts import FontFace data = ( (&quot;First name&quot;, &quot;Last name&quot;, &quot;Age&quot...
<python><fpdf2>
2025-02-18 19:43:49
0
4,376
smpa01
79,449,407
14,122
Configuring a custom log handler to add kwargs from "extra" dict for captured logs in pytest
<p>I'm using structlog with keyword arguments to generate stdlib log events with the <code>extra</code> dict storing keyword arguments necessary to understand the context around the log message being printed.</p> <p>When my program is run under pytest, the log messages written directly to stdout honor the application's...
<python><logging><pytest>
2025-02-18 19:35:44
1
299,045
Charles Duffy
79,449,347
11,354,959
Exception when trying to launch django project debug in VS code
<p>Hi I have a django project (4.2.2) and when I start the project from the terminal inside VS Code using &quot;python3 manage.py runserver&quot; everything works perfectly. But I want to debug it so I created a launch.json file to start it as debug Here is what it contains:</p> <pre><code>{ // Use IntelliSense to ...
<python><django><visual-studio-code>
2025-02-18 19:11:45
2
370
El Pandario
79,449,287
1,534,017
Align grid and cells in heatmap
<p>I use <code>plotly</code>'s <code>graph_objects</code> to generate a <code>heatmap</code>. It all works well, however, I would like to shift the grid in such a way that its lines are aligned with the boundaries of the cells that contain the numbers; right now the grid lines point towards the center of the the cells....
<python><plotly><heatmap>
2025-02-18 18:33:18
0
26,249
Cleb
79,449,212
15,456,681
Numba promotes types differently to numpy
<p>When adding (or multiplying, dividing, subtracting etcโ€ฆ) a python float to a numpy array, in numpy the dtype of the array is preserved, whereas in numba the array is promoted to float64. How can I modify the overload of <code>ndarray.__add__</code> etcโ€ฆ to change the dtype of the python float to match that of the ar...
<python><numpy><numba>
2025-02-18 17:58:12
1
3,592
Nin17
79,449,175
1,084,684
wtforms: optional FieldList of IntegerField?
<p>I need an <em>optional</em> list of int's in a WTForms-validated Rest API.</p> <p>Right now this is the relevant part of my form:</p> <pre><code>from wtforms import IntegerField, FileField, StringField, FieldList from wtforms.validators import DataRequired, Optional, UUID class PublishForm(FlaskForm): # This va...
<python><wtforms>
2025-02-18 17:44:13
1
7,243
dstromberg
79,449,057
1,870,832
confused by silent truncation in polars type casting
<p>I encountered some confusing behavior with polars type-casting (silently truncating floats to ints without raising an error, even when explicitly specifying <code>strict=True</code>), so I headed over to the <a href="https://docs.pola.rs/user-guide/expressions/casting/" rel="nofollow noreferrer">documentation page o...
<python><dataframe><casting><python-polars>
2025-02-18 16:55:40
2
9,136
Max Power
79,448,931
1,838,076
How to dynamically pick the columns to show in dataframe with streamlit
<p>I am trying to pick the columns to show dynamically in a <code>streamlit</code> dataframe.</p> <p>Below is the code</p> <pre class="lang-py prettyprint-override"><code>#! /usr/bin/env python3 import streamlit as st import pandas as pd st.set_page_config(layout=&quot;wide&quot;) # Create a sample dataframe with 3 c...
<python><dataframe><streamlit>
2025-02-18 16:09:22
0
1,622
Krishna
79,448,844
11,470,719
Appropriate type-hints for Generic/Frozen Multivariate Distributions in scipy.stats
<p>I need to differentiate between 4 different sets of probability distributions from the <code>scipy.stats</code> module: generic univariate, frozen univariate, generic multivariate, &amp; frozen multivariate. Throughout the application, I would like to add type hints for these 4 sets.</p> <p>For the univariate cases,...
<python><python-typing><mypy><scipy.stats><probability-distribution>
2025-02-18 15:55:39
1
2,210
brentertainer
79,448,815
1,406,168
Default credentials with WorkspaceClient hosted in an Azure Web App with managed identity
<p>I have a fast API hosted in an azure web app. I am trying to get some data from DataBricks and return it from the FastAPI. This is my context:</p> <p>DbxContext.py:</p> <pre><code>import time import pandas as pd from databricks import sql from databricks.sdk import WorkspaceClient from pydantic import SecretStr # fr...
<python><azure-web-app-service><databricks><azure-databricks><azure-managed-identity>
2025-02-18 15:45:25
0
5,363
Thomas Segato
79,448,760
4,693,577
CuPy ROI Analysis significantly slower than NumPy version on RTX 4090
<p>I have two versions of an ROI analysis class - one using NumPy and one using CuPy. The CuPy version is running much slower despite using an RTX 4090. Both versions perform the same operations:</p> <pre><code># Standard library imports import json from typing import Any, Dict, List, Optional, Tuple, Union # Third-pa...
<python><pandas><numpy><cupy>
2025-02-18 15:20:24
0
368
Santi
79,448,675
7,347,925
How to speed up calibrating denoiser?
<p>I'm trying to calibrate the denoiser like this:</p> <pre><code>import numpy as np from skimage.restoration import ( calibrate_denoiser, denoise_tv_chambolle, denoise_invariant, ) # create random noisy data noisy = np.random.random ([1200, 1000])*100 noise_std = np.std(noisy) # set weights for calibrati...
<python><numpy><image-processing><scikit-image>
2025-02-18 14:53:59
0
1,039
zxdawn
79,448,571
14,084,653
Matplotlib show function is showing the plot window minmized after python input command
<p>Im seeing strange behavior to the matplotlib plot.show() function as result of the python input command as in the below code. If I take the input command the plot window will show up and centered to the sceen, however if I add it back the plot window will be minimized. Im sure this is related to focus but not sure ...
<python><python-3.x><visual-studio><matplotlib>
2025-02-18 14:20:37
1
779
samsal77
79,448,337
13,840,270
Using re.sub and replace with overall match
<p>I was just writing a program where I wanted to insert a newline after a specific pattern. The idea was to match the pattern and replace with the overall match (i.e. capture group <code>\0</code>) and <code>\n</code>.</p> <pre><code>s = &quot;abc&quot; insert_newline_pattern = re.compile(r&quot;b&quot;) re.sub(insert...
<python><regex><python-re>
2025-02-18 12:55:09
2
3,215
DuesserBaest
79,448,155
650,405
Python Squish wrapper that reports the original call location
<p>Just some background, so this doesn't end up being an XY Problem:</p> <p>The Squish library has some basic methods to do tests, <code>test.verify</code>, <code>test.compare</code>, etc.</p> <p>Because the screenshot functionality is not working in our configuration and in the pipeline I don't see stack traces (only ...
<python><python-3.8><squish>
2025-02-18 11:49:51
0
96,680
Karoly Horvath
79,448,057
7,465,516
How does "MaybeNone" (also known as "The Any Trick") work in Python type hints?
<p>In typestubs for the Python standard library I noticed a peculiar type called <a href="https://github.com/python/typeshed/blob/132456af62b1d15e966e490d9ba9235d2f6bbf2e/stdlib/_typeshed/__init__.pyi#L58" rel="nofollow noreferrer"><code>MaybeNone</code></a> pop up, usually in the form of <code>NormalType | MaybeNone</...
<python><python-typing><typeshed>
2025-02-18 11:17:38
2
2,196
julaine
79,447,986
6,113,142
How to run multiple browser-use agents in parallel?
<p>Currently I have this code</p> <pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python3 # -*- coding: utf-8 -*- &quot;&quot;&quot; :brief: Run multiple browser-use agents in parallel &quot;&quot;&quot; import asyncio import os from browser_use import Agent, Browser, BrowserConfig, Controller from brow...
<python><browser-automation><browser-use>
2025-02-18 10:54:24
1
350
Pratik K.
79,447,890
6,544,849
How can I seperate the fringes that have been calculated with findpeaks
<p>I would like to seperate the fringes (the red curved lines) that I have calculated with scipy findpeaks how can I achive it. I would like to seperate them and store in the text file.</p> <p><a href="https://i.sstatic.net/e47plvI4.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/e47plvI4.png" alt="enter...
<python><arrays><numpy><scipy>
2025-02-18 10:27:59
2
321
wosker4yan
79,447,749
7,996,523
Python trace module does not display calling relationships when running pytest
<p>I would like to track the functions invoked by pytest test cases. I use <a href="https://github.com/pydata/xarray/blob/main/xarray/tests/test_coding.py" rel="nofollow noreferrer">this test file in xarray</a> as an example. I use the following command to trace</p> <pre><code>python -m trace --trackcalls --module pyte...
<python><pytest><trace>
2025-02-18 09:33:52
1
901
Richard Hu
79,447,743
7,853,142
Representing Networkx graphs as strings in a consistent way
<p>I have multiple Networkx graphs (with node attributes), and I need to represent them as strings. There are several ways to do that, but I need to always get the same string for equal graphs (not isomorphic, by equal I mean that <a href="https://networkx.org/documentation/stable/reference/generated/networkx.utils.mis...
<python><serialization><networkx>
2025-02-18 09:32:46
1
902
ThePirate42
79,447,533
6,930,340
Passing a polars struct to a user-defined function using map_batches
<p>I need to pass a variable number of columns to a user-defined function. The <a href="https://docs.pola.rs/user-guide/expressions/user-defined-python-functions/#combining-multiple-column-values" rel="nofollow noreferrer">docs</a> mention to first create a <code>pl.struct</code> and subsequently let the function extra...
<python><python-polars>
2025-02-18 08:11:40
1
5,167
Andi
79,447,468
10,377,244
Can't read parquet file with polars while pyarrow can
<p>I am getting a <code>dtype</code> exception</p> <blockquote> <p>pyo3_runtime.PanicException: Arrow datatype Map(Field { name: &quot;key_value&quot;, dtype: LargeList(Field { name: &quot;key_value&quot;, dtype: Struct([Field { name: &quot;key&quot;, dtype: Utf8View, is_nullable: false, metadata: None }, Field { name:...
<python><parquet><python-polars><pyarrow><polars>
2025-02-18 07:44:03
0
1,127
MPA
79,447,425
7,106,508
what is best way to copy a class without using inheritance in Python
<p>I want a class 'child' to inherit all the properties of class 'parent' but this is going to be the exception rather than the rule. In more than 95% of the cases this is not going to happen, so what is the best way in Python to have a child class copy all of the attributes of the parent? Right now, I'm doing it thi...
<python>
2025-02-18 07:22:28
1
304
bobsmith76
79,447,219
169,165
SHAP plot with categorical columns
<p>Before one-hot encoding, the input data consists of 2 categorical columns (category1, category2). category1 is among A,B,C and category2 is among X,Y. After the one-hot encoding, the input data transforms to 5 columns(A,B,C,X,Y). The fit function works well.</p> <p>However, the problem lies on the output SHAP summar...
<python><xgboost><shap>
2025-02-18 05:31:15
0
2,969
Hyunjik Bae
79,447,153
20,762,114
Topological sort in Polars
<pre><code>df = pl.from_repr(''' shape: (6, 2) โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ A โ”† B โ”‚ โ”‚ --- โ”† --- โ”‚ โ”‚ i64 โ”† i64 โ”‚ โ•žโ•โ•โ•โ•โ•โ•โ•ชโ•โ•โ•โ•โ•โ•โ•ก โ”‚ 1 โ”† null โ”‚ โ”‚ 2 โ”† 1 โ”‚ โ”‚ 2 โ”† 2 โ”‚ โ”‚ null โ”† 3 โ”‚ โ”‚ 3 โ”† 4 โ”‚ โ”‚ 4 โ”† null โ”‚ โ”‚ 5 โ”† 5 โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”˜ ''') </code></pre> <p>I want to sort a dataframe such that multip...
<python><python-polars>
2025-02-18 04:45:54
1
317
T.H Rice
79,447,024
6,230,282
Why does Python regular expression give different result for the following 2 quantifiers?
<p>While investigating the semantic difference between quantifiers based on length and count, I noticed that Python 3 regular expression gave different result for the following 2 regular expressions (notice the quantifiers <code>+</code> and <code>*</code>:</p> <pre><code>Python 3.10.16 (main, Dec 7 2024, 13:31:33) [C...
<python><php><regex><pcre>
2025-02-18 03:00:49
1
1,641
DannyNiu
79,446,885
1,301,310
PyPi Server on windows: 503 Forbidden
<p>I have a windows server with pypiserver running as a schedule task and am accessing it via a reverse proxy.</p> <ul> <li>My pypi server is running as a scheduled task under user X.</li> <li>I have .htpasswd setup.</li> <li>The package directory and the pypi server config directory (.htpassed, start.bat, pypiserver.l...
<python><pypi>
2025-02-18 00:29:58
1
1,833
Gina Marano
79,446,809
1,532,454
transpose pitch down an octave?
<p>Using music21, how can I transpose a pitch down an octave?</p> <p>If I use <code>p.transpose(-12)</code>, flats get changed to sharps:</p> <pre><code>import music21 p = music21.pitch.Pitch('D-4') print(p.transpose(-12)) </code></pre> <p>output</p> <pre><code>C#3 </code></pre>
<python><music21><music-notation>
2025-02-17 23:21:03
1
3,389
Jeff Learman
79,446,667
2,648,504
Pandas - shifting columns to a specific column position
<p>I have a simple dataframe:</p> <pre><code>data = [[2025, 198237, 77, 18175], [202, 292827, 77, 292827]] </code></pre> <p>I only want the 1st and 4th columns and I don't want header or index labels:</p> <pre><code>df = pd.DataFrame(data).iloc[:,[0,3]] print(df.to_string(index=False, header=False)) </code></pr...
<python><pandas>
2025-02-17 21:52:51
1
881
yodish