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,514,489
4,451,315
normalise a list column in DuckDB SQL
<p>Say I have:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl df = pl.DataFrame({'a':[1,1,2], 'b': [4,5,6]}).with_columns(c=pl.concat_list('a', 'b')) print(df) </code></pre> <pre><code>shape: (3, 3) ┌─────┬─────┬───────────┐ │ a ┆ b ┆ c │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ li...
<python><duckdb>
2025-03-17 11:50:27
1
11,062
ignoring_gravity
79,514,484
4,373,898
Why does Spark raises an IOException while running a aggregation on a streaming dataframe in Dataproc 2.2
<p>I try to migrate a job that is running on Dataproc 2.1 images (Spark 3.3, Python 3.10) to Dataproc 2.2 images (Spark 3.5, Python 3.11). However I encounter an error on one of my queries. After further investigation, I am able to reproduce the issue with this minimal example:</p> <pre class="lang-py prettyprint-overr...
<python><apache-spark><pyspark><google-cloud-dataproc>
2025-03-17 11:48:10
0
3,169
AlexisBRENON
79,514,242
19,386,576
Why isn’t my cookie being set on a POST redirect in FastAPI with sqladmin custom authentication?
<p>I’m building an admin panel with FastAPI using sqladmin, and I’ve implemented a custom authentication backend by extending sqladmin’s AuthenticationBackend. In my login method, when a POST request is made to /admin/login, I validate the credentials, create a JWT token with the claim is_admin=True, and then set this ...
<python><fastapi><setcookie><response.redirect><http-status-code-303>
2025-03-17 10:02:09
0
608
federikowsky
79,513,794
3,813,371
How to print colored or bold text in Python Visual Studio 2022 CLI app
<p>I have tried <code>colorama</code>, <code>termcolor</code> and <code>printy</code>.<br /> When I run the application in debug method, the text isn't formatted.</p> <p>This wasn't the case, when I built a C# Console application in VS.</p> <p>Here is the code using <code>printy</code>.</p> <pre><code>from printy impor...
<python><windows><visual-studio-2022><colorama><termcolor>
2025-03-17 06:42:23
2
2,345
sukesh
79,513,685
3,241,701
Is It Reasonable to Simplify Product Variant Design Using Notes Instead of Complex Relations?
<p>I'm building an application where product variants are intended to be handled as <strong>physical products already prepared and listed manually</strong>. Instead of using a conventional approach with complex relations between Product, Option, OptionValue, and SKUValue tables, I'm trying to simplify the design.</p> <...
<python><django><database><backend><product-variations>
2025-03-17 05:22:47
2
810
Solanoize
79,513,473
20,167,855
I’m trying to export data to a CSV file with semicolon separator ";"
<p>While using Scrapy, I’m trying to export data to a CSV file, and it’s working. However, the separator used is a comma (&quot;,&quot;), but I need it to be a semicolon (&quot;;&quot;) instead.</p> <p>I’m currently running the command:</p> <p><code>scrapy runspider Intro_Scrapy.py -o video.csv</code></p> <p>How can I ...
<python><csv><scrapy>
2025-03-17 01:11:19
0
351
Francisco Augusto Varela Aguir
79,513,387
2,250,791
How to specify generic python signature to return type, as well as use type in function
<p>I'm trying to write a function which takes a class as an argument, returns an instance of that class wrapped in another type, and uses the type of the class for casting internally, it works with a simple type like str, but not an actual class.</p> <p>I've reduced this code to the point that it's a bit silly to be us...
<python><generics><python-typing>
2025-03-16 23:39:58
1
2,075
Camden Narzt
79,513,337
13,392,257
pyyaml resolver: 'type' object is not iterable
<p>I am trying to resolve environment variables in yaml config</p> <p>For example, I want to convert</p> <pre><code>car: name: ${CAR_NAME} is_new: true </code></pre> <p>to</p> <pre><code>car: name: BMW is_new: true </code></pre> <p>My code</p> <pre><code># base_model.py import yaml import os import re from py...
<python><pyyaml>
2025-03-16 22:42:48
1
1,708
mascai
79,513,292
15,412,256
Jupyter Notebook DataFrame Render Steadily Increasing memory usage
<p>Generate any considerably large dataset:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import polars as pl from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split X, y = make_classification( n_samples=3_000_000, n_features=100, n_i...
<python><pandas><jupyter-notebook><jupyter><python-polars>
2025-03-16 21:58:43
0
649
Kevin Li
79,513,211
12,415,855
Selenium selecting element by value not possible
<p>i try to select an element using selenium with the following code:</p> <pre><code>from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import...
<python><selenium-webdriver>
2025-03-16 20:37:50
2
1,515
Rapid1898
79,513,209
1,506,763
python base64 string - how to decode first 8 bytes
<p>I'm having some problems decoding what should be simple data.</p> <p>I have a base64 string that represents a <code>np.int64</code> followed by an array of <code>np.float64</code>. The size of the array is defined by the first <code>np.int64</code>. This pattern is then repeated for multiple arrays. So in order to d...
<python><numpy><binary><base64><decode>
2025-03-16 20:35:57
1
676
jpmorr
79,513,093
2,057,516
How do I get VSCode Intellisense to work with my python class factory method?
<p>I have a python class factory method that I use to create a commonly implemented derived class of <code>django.tests.TestCase</code> and <code>django.tests.TransactionTestCase</code>:</p> <pre><code>from typing import Type from django.test import TestCase, TransactionTestCase def test_case_class_factory(base_class...
<python><visual-studio-code><intellisense><syntax-highlighting>
2025-03-16 19:13:43
1
1,225
hepcat72
79,512,994
11,850,322
Python - XYZ plot coloring cluster region
<p>Current this is my code for XY axis:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt def plot_with_tricontourf_customized(dfs, figures_organizer, figsize_setting, list_points_mean, list_points_type, x_col, y_col, color_col, titles, marker_type='o', apply_limits=False, x_limits=None, y_limits=None)...
<python><pandas><matplotlib><plotly><matplotlib-3d>
2025-03-16 17:56:00
0
1,093
PTQuoc
79,512,868
3,972,291
how to read excel merged cell properties value using python?
<p>I need to read data from an Excel file. The first cell contains the property name, and the second cell contains the property value. However, some of the property names in the first column are merged across two or more columns, and the corresponding values are in the next cell. For example, the property name &quot;Re...
<python><excel><pandas><openpyxl>
2025-03-16 16:29:17
1
5,095
Enamul Haque
79,512,785
20,167,855
Using Scrapy I get LookupError: unknown encoding: 'b'utf8''
<p>Im learning how to use Scrapy but when I try to export to csv I get a LookupError: unknown encoding: 'b'utf8''</p> <p>I made an example with Stack Overflow (only for learning) and tried to scrap first page of questions and then export to csv. But I get an empty CSV and the error on my terminal is:</p> <pre><code>20...
<python><web-scraping><scrapy>
2025-03-16 15:27:39
1
351
Francisco Augusto Varela Aguir
79,512,639
16,383,578
How to get specified number of decimal places of any fraction?
<p>So I can generate many <code>tuple</code>s like this:</p> <pre><code>(6015504051858104552483737987336109006898859464105582953839088630205514475818894141520359143448645806366622936410501476141546103947240895433054187160410825235031716410117287037442733992678958104128126276826863059645074167781437712189490501580284070...
<python><algorithm><math><fractions><integer-division>
2025-03-16 13:47:27
2
3,930
Ξένη Γήινος
79,512,493
22,213,065
How to Freeze a Flourish Studio Bar Chart Race Every 0.01s for High-Quality PDF Capture?
<p>I created the following Flourish Studio bar chart race as an example for this topic:<br /> <a href="https://flo.uri.sh/visualisation/19321054/embed" rel="nofollow noreferrer">https://flo.uri.sh/visualisation/19321054/embed</a></p> <p>Now, I want to capture a sequence of PDF prints from this bar chart race, recording...
<javascript><python><pdf><browser-automation><screen-recording>
2025-03-16 11:26:14
1
781
Pubg Mobile
79,511,967
15,587,184
Azure AI Search - Tag Scoring profile on azureopenai extra_body
<p>I created an index on Azure AI Search and connected it to Azure OpenAI using the extra_body. It works perfectly. However, I created a default scoring profile for my index, which boosts documents containing the string &quot;zinc&quot; in the VITAMINS field by a factor of 10.</p> <p>Since doing this, I can no longer r...
<python><azure><azure-openai><azure-ai-search>
2025-03-16 00:36:05
1
809
R_Student
79,511,907
16,383,578
Why my function that converts a string of digits to a list of bytes doesn't work?
<p>I have written a simple function that converts a string consisting of only digits (<code>'0123456789'</code>) to a list of bytes. More specifically it finds the longest possible sequences of digits that when converted to an integer is less than 256.</p> <p>For example, given the decimal digits in order, the output s...
<python>
2025-03-15 22:52:47
3
3,930
Ξένη Γήινος
79,511,457
23,512,643
Generate a random matrix in Python which satisfies a condition
<p>I manually define the following 16 matrices in Python :</p> <pre><code>matrices = { &quot;Simulation 1&quot;: [ [1, 1, 1, 1, 1, 2], [1, 1, 1, 1, 2, 2], [1, 1, 1, 2, 2, 2], [1, 1, 1, 2, 3, 2], [1, 1, 1, 1, 3, 3], [1, 1, 1, 1, 3, 3] ], &quot;Simulation 2...
<python><matrix><graph><tree>
2025-03-15 16:49:24
1
6,799
stats_noob
79,511,416
1,234,721
Multiple different attachments using Gmail API in Django
<p>How do I account for sending multiple (or no) attachments (via <code>request.FILES</code>) in Django using the Gmail API, so I can store the legacy message ID (ie &quot;FBf…MiD&quot;) for future retrieval to reply in the same thread/thread_ID? I am switching from the SMTP (to be fully deprecated by Google) by Djang...
<python><python-3.x><django><gmail-api><mime-types>
2025-03-15 16:15:28
4
19,295
chris Frisina
79,511,352
16,236,118
How can I change the success url of allauth AddEmailForm?
<p>I have a UserDetail page that includes several forms.</p> <pre><code>from allauth.account.forms import ChangePasswordForm, AddEmailForm User = get_user_model() class UserDetailView(LoginRequiredMixin, DetailView): model = User slug_field = &quot;username&quot; slug_url_kwarg = &quot;username&quot; ...
<python><django><django-forms><django-allauth>
2025-03-15 15:34:12
1
1,636
JAdel
79,511,254
7,886,968
Can I specify the replacement character in str([value], encoding='utf-8', errors='replace')
<p>Is it possible to specify the replacement character used by <code>str(xxx,encoding='utf-8', errors='replace')</code> to be something other than the diamond-question-mark character (�)?</p> <p>I am attempting to fix up a GPS data filtering routine in Python for my GoPiGo robot.</p> <p>The GPS module I am using return...
<python><string><utf-8>
2025-03-15 14:11:10
1
643
Jim JR Harris
79,511,208
6,035,977
Why does SymPy incorrectly evaluate inequalities for infinite symbols?
<p>I'm using SymPy to handle symbolic mathematics involving possibly infinite values. I need to define a symbol <code>y&gt;=0</code> and <code>y&lt;=sympy.inf</code> and tried the following but the behaviour is not as I would expect it:</p> <pre class="lang-py prettyprint-override"><code>import sympy y = sympy.symbols...
<python><sympy><symbols>
2025-03-15 13:31:36
1
333
Corram
79,511,189
12,323,013
matplotlib waterfall plot with surfaces shows black artifacts on border of plot
<p>I have a script to write a heatmap (or contour map) inside an arbitrary closed shape. A bounding box of grid points is created and a mask is used to clip any points outside of the shape. However, if I want to create a stacked plot of these maps (to show changes along a fourth dimension), the grid points are painted ...
<python><numpy><matplotlib>
2025-03-15 13:20:17
1
349
noobquestionsonly
79,511,188
3,815,773
Gauss Fitting data with scipy and getting strange answers on Fit Quality
<p>I have Gamma-Spectra and I am doing Gauss fit to the peaks using Python with scipy. Works well, but trying to get a number on fit quality (for the intent on some automation) returns very odd numbers.</p> <p>The scipy command is:</p> <pre><code>response = scipy.optimize.curve_fit(gauss, e, c, param0, full_output=True...
<python><scipy><statistics><curve-fitting>
2025-03-15 13:20:10
1
505
ullix
79,511,155
7,456,793
How to generate requirements (conda / pip) restricted to a given project, from a larger environment?
<p>so, I am not a pro-developer and my practices are a quite sub-optimal. I have developed a project (mainly python), which requires a bunch of dependencies. My way is generally to install the dependencies using conda, then pip if not in conda.</p> <p>The project is nearly ready to be shared. But my conda environment i...
<python><pip><conda><requirements>
2025-03-15 13:03:13
0
313
Megamini
79,510,955
3,368,111
Failing to initialise a new USGS API instance
<p>I have an account on the USGS and when I try to create an API instance using this code</p> <pre><code>from landsatxplore.api import API import os # Your USGS credentials username = '&lt;username&gt;' password = '&lt;password&gt;' # Initialize a new API instance api = API(username, password) # Perform a request r...
<python><geospatial>
2025-03-15 10:23:00
1
443
Federico
79,510,868
595,305
How can I test that a method of a class was passed as a parameter to a mocked method
<p>Say I have classes like this:</p> <pre><code>class MyTask(QtCore.QObject): def do(self): ... class Manager(QtCore.QObject): def __init__(self): super().__init__() self.worker_executor = concurrent.futures.ThreadPoolExecutor() def run_task(self): self.worker_executor.subm...
<python><pytest>
2025-03-15 09:08:18
1
16,076
mike rodent
79,510,817
1,232,660
Algorithm to select multiple non-overlapping subsequences of given sequence
<p>You have been given the input data (a sequence of items), for example:</p> <pre><code>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] </code></pre> <p>and your task is to randomly select M non-overlapping samples (subsequences) of the same size N.</p> <p>For example, if the task was to select 3 samples of si...
<python><algorithm><subsequence>
2025-03-15 08:27:56
2
3,558
Jeyekomon
79,510,643
18,333,498
How to Detect Thick Lines as Single Lines Using Hough Transform in OpenCV
<p>I'm using OpenCV's <code>HoughLinesP</code> function to detect straight lines in an image. When the image contains thin lines, the detection works perfectly. However, when the image contains thick lines, the algorithm detects them as two parallel lines instead of a single line.</p> <p>Here's my current code:</p> <pr...
<python><opencv><contour><hough-transform><canny-operator>
2025-03-15 04:54:16
1
572
Kuldeep J
79,510,222
89,931
Get Python string value as printed by "print()"
<p>Suppose I have a string as follows (after parsing some stdout):</p> <pre><code>&gt;&gt;&gt; mystr '--More-- \r \rSerial-Number: 12345' </code></pre> <p>I notice that print() function automatically processes the <code>\r</code> characters, essentially getting rid of the entire &quot;--More--&quot; part, like ...
<python>
2025-03-14 21:05:37
4
1,133
Dmitry Perets
79,510,104
21,896,093
How to get a discrete colour bar for plotly Scatter plot?
<p>I have defined a list of 5 colours, which I use to colour the markers in the <code>go.Scatter</code> plot below.</p> <p>I want the colour bar (legend) to show these <em>discrete</em> values, but the resulting colour bar stays white. See the white/empty bar titled &quot;outputs&quot; in the image.</p> <p><a href="htt...
<python><plotly><legend><colorbar>
2025-03-14 19:52:49
1
5,252
MuhammedYunus
79,510,075
4,515,940
python script causing error - NameError: name 'Python' is not defined
<p>I'm running a simple Streamlit + Ollama + Python to run an AI chatbot.</p> <p>After asking the chat, it's causing this error:</p> <pre><code>[ERROR] Failed with error: Traceback (most recent call last): File &quot;/usr/local/lib/python3.10/site-packages/pandasai/pipelines/chat/code_execution.py&quot;, line 87, in ...
<python><docker><ollama>
2025-03-14 19:31:40
0
1,835
anderlaini
79,510,017
18,385,480
How can I deploy and run a Flask web application using heavy NLP libraries (pandas, numpy, sklearn) on a SiteGround shared hosting plan?
<p>I have a Flask-based web application that performs NLP tasks using libraries like pandas, numpy, sklearn, and nltk. I've tried deploying it to my current hosting (SiteGround shared hosting plan), but encountered multiple issues, such as:</p> <p>Installation issues (pyahocorasick and other dependency errors). Resourc...
<python><flask><nlp>
2025-03-14 19:03:16
0
723
bsraskr
79,509,775
4,819,195
How to get route of request from connexion.AsyncApp in python?
<p>I have an <code>connexion.AsyncApp</code> in python. A snippet of the code looks like this:</p> <pre><code>app = AsyncApp(__name__) app.add_api(&quot;openapi.yaml&quot;, arguments={&quot;title&quot;: &quot;Async APP API&quot;}) if __name__ == &quot;__main__&quot;: uvicorn.run(app, host=&quot;127.0.0.1&quot;, p...
<python><connexion>
2025-03-14 17:06:55
0
399
A Beginner
79,509,728
6,695,793
Polars group_by + describe: return all columns as single dataframe
<p>I'm slowly migrating to polars from pandas and I have found that in some cases the polars syntax is tricky.</p> <p>I'm seeking help to do a <a href="https://docs.pola.rs/api/python/stable/reference/dataframe/api/polars.DataFrame.group_by.html" rel="nofollow noreferrer"><code>group_by</code></a> followed by a <a href...
<python><pandas><dataframe><python-polars>
2025-03-14 16:44:35
1
4,073
jcaliz
79,509,661
8,830,612
Azure AI ML - can't build local Docker container
<p>I want to build <strong>local Docker container</strong> with and Azure CLI &amp; Azure SDKv2, which afterwards I want to <strong>replicate in Azure ML</strong>. My objective is to have a container which can run YOLO models.</p> <p>With the following script you can replicate the error:</p> <pre class="lang-none prett...
<python><azure><docker><azure-machine-learning-service>
2025-03-14 16:19:57
0
518
default_settings
79,509,632
19,802,442
Shortest way to broadcast 1d array to specific dimension in NumPy
<p>I often find myself to broadcast 1d arrays into a specific dimension <code>dim_a</code> given a total number of dimension <code>dim_total</code>. What I mean is the following:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np a = np.arange(10) dim_a = 2 dim_total = 4 shape = tuple([-1 if idx =...
<python><arrays><numpy><array-broadcasting>
2025-03-14 16:09:34
2
1,941
Axel Donath
79,509,624
4,451,315
Python overload doesn't match `Any` case
<p>I've written this code:</p> <pre class="lang-py prettyprint-override"><code>from typing import overload, TYPE_CHECKING, Protocol, Any import pyarrow as pa # type: ignore[import-not-found] class PyArrowArray(Protocol): @property def buffers(self) -&gt; Any: ... @overload def func(a: PyArrowArray) -&gt; in...
<python><python-typing><mypy>
2025-03-14 16:06:37
1
11,062
ignoring_gravity
79,509,621
764,365
How do I pass in arguments when initializing an event handler with win32com.client.WithEvents in python
<p>I am trying to use win32com.client.WithEvents and I'd like to be able to pass values to the initialization method. However, the input for the event handler is the class, not an instance of the class:</p> <pre><code>import win32com.client #For my application this is what defines &quot;document&quot; labchart = win32...
<python><pywin32>
2025-03-14 16:04:38
0
3,304
Jimbo
79,509,594
990,549
Can a Python value be annotated with its type without assigning it to a variable?
<p>I'm working with a Pandas DataFrame where the index is guaranteed to be the first day of a year. I want to change the index to be the year itself. The code is straightforward enough, and runs fine:</p> <pre><code>import pandas as pd df = pd.DataFrame(data={ 'col1': [1, 2, 3], 'col2': ['a', 'b', 'c'], }, ind...
<python><pandas><python-typing>
2025-03-14 15:55:22
0
1,050
Shay Guy
79,509,565
9,951,273
Creating a dummy Pydantic model generator
<p>I want to create a method on a base Pydantic model to instantiate child models with dummy data.</p> <pre><code>from __future__ import annotations from pydantic import BaseModel class BaseModelWrapper(BaseModel): @classmethod def make_dummy(cls) -&gt; BaseModelWrapper: for name, field in cls.model_f...
<python><pydantic>
2025-03-14 15:47:31
2
1,777
Matt
79,509,548
5,403,466
Logistic curve produced by curve_fit is a straight line
<p>I'm trying to produce a Sigmoid/Logistic curve from some input data. I borrowed code from <a href="https://stackoverflow.com/questions/55725139/fit-sigmoid-function-s-shape-curve-to-data-using-python">this post</a> and <a href="https://stackoverflow.com/questions/48506782/scipy-curve-fit-how-to-plot-the-fitted-curve...
<python><matplotlib><scipy>
2025-03-14 15:39:57
3
1,456
Tyler Shellberg
79,509,402
59,587
Python environment error, "TypeError: Choicelist and default value do not have a common dtype"
<p>I have two python environments - one online through a class, and the other on my own computer.</p> <p>The following code works on the online environment, but gives an error on my local environment. Does anyone know what this error means, and have any suggestions for fixing my environment, or fixing my code? The onli...
<python><numpy>
2025-03-14 14:46:28
1
5,875
Sophia
79,509,349
2,573,061
Correctly invoke TorchEval AUC calculation for two tensors
<p>I am new to torcheval and trying to measure the AUC of my binary classifier (<a href="https://pytorch.org/torcheval/main/generated/torcheval.metrics.AUC.html" rel="nofollow noreferrer">doc</a>).</p> <p>I notice that while classifier accuracy is decent, the AUC metric evaluates to below 0.5, which is incorrect (given...
<python><pytorch><auc>
2025-03-14 14:26:43
1
19,153
C8H10N4O2
79,509,277
6,329,284
Is an instance of my Pydantic model also in my Enum?
<p>In my situation I get a response from an API which follows the structure of MyGenericModel. After I parse the response using MyGenericModel, I want to check if it belongs to my set defined in MyEnum. If it does I want to continue with it, if not.. then we proceed further.</p> <ul> <li><p>When I call <code>MyGenericM...
<python><enums><pydantic>
2025-03-14 13:55:51
1
1,340
zwep
79,509,243
5,404,647
How to Use Template in Langchain to Insert Results from Chain for Further Reasoning?
<p>I'm working with Langchain and OpenAI to develop a conversational AI. I've integrated multiple tools into the chain and am using a template to structure the conversation. However, I'm stuck on how to use the results from the chain (<code>chain.invoke(...)</code>) in the template to allow the agent to continue reason...
<python><artificial-intelligence><chatbot><langchain><large-language-model>
2025-03-14 13:42:12
1
622
Norhther
79,509,031
1,518,100
python multiprocess sharing value with Value not working as documented
<p>I'm learning sharing variables in multiprocess. The official <a href="https://docs.python.org/3/library/multiprocessing.html#synchronization-between-processes" rel="nofollow noreferrer">doc</a> says</p> <blockquote> <p>Data can be stored in a shared memory map using Value...</p> </blockquote> <p>and the example work...
<python><multiprocessing>
2025-03-14 12:07:19
1
4,435
Lei Yang
79,508,526
3,420,345
How to specify a nightly Pytorch version in environment.yml
<p>Consider the following environment.yml file:</p> <pre><code>channels: - nvidia - defaults - conda-forge dependencies: - bottleneck&gt;=1.3.6 - catboost&gt;=0.24.4 ... - pip: - xgboost==2.1.4 ... </code></pre> <p>How do I add the following pip command to the yml file without disrupting the curre...
<python><pytorch><pip><conda>
2025-03-14 08:46:31
1
343
Martin
79,508,495
2,780,906
How do I create a multi-index dataframe from tuples/lists
<p>I want to create (for example) a small multi-index dataframe with 3 level index and one column of values. There will only be a handful of rows.</p> <div class="s-table-container"><table class="s-table"> <thead> <tr> <th></th> <th></th> <th></th> <th>Value</th> </tr> </thead> <tbody> <tr> <td><strong>Category</stron...
<python><pandas><dataframe><multi-index>
2025-03-14 08:35:14
1
397
Tim
79,508,467
6,702,598
Prevent pytest instantiating parent test class
<p>I'm using the Template Method Pattern for my test cases, i.e. they have the following structure:</p> <pre class="lang-none prettyprint-override"><code>Parent(unittest.TestCase) | |---- Child1 |---- Child2 |---- Child3 </code></pre> <p>Test cases are defined in the parent. Each child implements a certain diff...
<python><pytest>
2025-03-14 08:20:34
1
3,673
DarkTrick
79,508,420
4,436,517
Expanding polars dataframe with cartesian product of two columns
<p>The code below shows a solution I have found in order to expand a dataframe to include the cartesian product of columns <code>A</code> and <code>B</code>, filling in the other columns with <code>null</code> values. I'm wondering if there is a better and more efficient way of solving this?</p> <pre class="lang-py pre...
<python><python-polars>
2025-03-14 07:53:07
2
1,159
rindis
79,508,413
7,766,024
How to bypass "Too many open files" error when using Playwright?
<p>I'm using Playwright to crawl websites. I have a scraping function that uses Playwright, and implemented a Python object that uses this function to crawl websites in a bread-first search manner.</p> <p>Below is the scraping function:</p> <pre class="lang-py prettyprint-override"><code>import logging from collections...
<python><concurrency><playwright><playwright-python>
2025-03-14 07:48:28
1
3,460
Sean
79,508,044
7,282,437
Asynchronously running a function in the background while sending results in Python
<p>I have a Python script which I would like to a) Continuously listen for requests from an API, and b) Run an expensive algorithm continuously in the background. The results from the algorithm are saved locally to a file (<code>results.json</code>), and if the API requests the result, I would like to load current resu...
<python><asynchronous><concurrency><python-asyncio>
2025-03-14 02:44:55
1
389
Adam
79,507,953
5,049,813
What type hint should I use for an object that can be iterated through multiple times?
<p>Sometimes I have a function that takes a parameter, and I need to be able to loop through that parameter multiple times. For example:</p> <pre class="lang-py prettyprint-override"><code>def loop_twice(param: MultiIterable): for thing in param: print(thing) for thing in param: print(f&quot;{t...
<python><python-typing>
2025-03-14 00:55:56
3
5,220
Pro Q
79,507,943
10,862,918
Pythonic Doxygen function signature rendering
<p>given the python function:</p> <pre class="lang-py prettyprint-override"><code> @staticmethod def check_for_conflicting_method( this_scope: Scope, target_scope: Scope, new_function: Asts.FunctionPrototypeAst, conflict_type: FunctionConflictCheckType)\ -&gt; Optional[Asts.Fu...
<python><doxygen>
2025-03-14 00:47:39
0
491
SamG101
79,507,897
235,218
Use a python regex expression to replace spaces between words in string1 with underscore, and add string2 at the end of string1
<p>I want to use a Python <em>regex</em> replacement operation to change prospective file names such as</p> <p><code>Using 3 Buttons in PyQt5 DialogButtonBox</code> into</p> <p><code>Using_3_Buttons_in_PyQt5_DialogButtonBox_aaa.pdf</code></p> <p>If I only wanted to replace the spaces with &quot;_&quot;, the replacement...
<python><regex>
2025-03-14 00:00:36
1
767
Marc B. Hankin
79,507,891
147,530
Understanding state management in Python ProcessPoolExecutor
<p>What I want to do: I have CPU intensive computation that I want to offload to a worker process so as not to block my main server.</p> <p>Without ProcessPoolExecutor my code looks like this:</p> <pre><code>my_model = model_init() def handler(args): return my_model.process(args) </code></pre> <p>How do I utilize ...
<python>
2025-03-13 23:55:55
1
20,700
morpheus
79,507,886
10,083,382
MacOS - Pty Host Disconnected VS Code
<p>I am using VSCode to execute Python Code inline. The execution seems to work fine if I execute line by line or couple of lines of code. Once I execute multiple code blocks the terminal gets unresponsive and then disconnects with error <code>pty host disconnected</code></p> <p>There is an <a href="https://stackoverfl...
<python><macos><visual-studio-code><execution>
2025-03-13 23:46:07
1
394
Lopez
79,507,737
785,494
How to exit a Python Win32 GUI program on Ctrl-C from invoking console
<p>I have a simple Python Win32 program that works well when run under <code>pythonw</code> from a command prompt. When I run it under <code>python</code>, it keeps running in the foreground of the command prompt and can e.g. print to STDOUT, which is very useful for debugging. However, it ignores Ctrl-C. I would li...
<python><user-interface><winapi><python-multithreading><pywin32>
2025-03-13 22:06:12
0
9,357
SRobertJames
79,507,720
16,383,578
How to improve the approximation of π using Machin-like formulas?
<p>I want to compute π using <a href="https://en.wikipedia.org/wiki/Machin-like_formula" rel="nofollow noreferrer">Machin-like formulae</a>, I use <a href="https://en.wikipedia.org/wiki/Arctangent_series#Accelerated_series" rel="nofollow noreferrer">Newton's accelerated series</a> to make the approximation converge fas...
<python><math><pi><taylor-series>
2025-03-13 21:57:48
1
3,930
Ξένη Γήινος
79,507,694
14,351,026
Unpredictable behaviour when reading from stdin in python daemon thread
<p>The <a href="https://docs.python.org/3/library/threading.html" rel="nofollow noreferrer">python documentation</a> says of daemon threads:</p> <blockquote> <p>A thread can be flagged as a “daemon thread”. The significance of this flag is that the entire Python program exits when only daemon threads are left.</p> </bl...
<python><linux><multithreading><python-multithreading><cpython>
2025-03-13 21:43:46
0
406
pjones123
79,507,557
4,474,230
How to send Slack api request to websocket without Bolt or other SDK?
<p>I have the code below. It connects correctly to Slack, and authenticate correctly.</p> <p>I want to sent a conversations.list request to list the channels. How can I do that without using Bolt or some other SDK? The system where this runs is locked down, so I'm not getting to install anything further than websockets...
<python><websocket><slack-api>
2025-03-13 20:27:58
2
11,112
Jeffrey
79,507,355
8,006,721
How to compare two list of objects using the object's equal method in Python
<p>I have a class that comes with a <code>.equals()</code> method. I'd like to compare two unordered lists of these objects to see if they are <em><strong>not</strong></em> equal.</p> <p>My current approach is to loop through list 1, then loop through list 2.</p> <pre><code>def objectListsNotEqual(list_1, list_2): ...
<python><python-3.x><list><compare>
2025-03-13 18:48:12
2
332
sushi
79,507,238
250,003
ModuleNotFoundError: No module named 'LibraryExplorer'
<p>I am a newbie on python and cannot figure out how to solve this error.</p> <p>This is the structure of my project: <a href="https://i.sstatic.net/Alne7J8J.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Alne7J8J.png" alt="my project struct" /></a></p> <p>and this is part of my code inside explorer.py<...
<python>
2025-03-13 17:48:36
1
715
Salvatore Di Fazio
79,507,207
13,132,728
Create an N length list by uniformly (in frequency) selecting items from a separate list in python
<h2>SETUP</h2> <p>I have a list <code>days</code> and a value <code>N</code></p> <pre><code>days = ['Monday','Tuesday','Wednesday','Thursday','Friday'] N = 52 </code></pre> <h2>WHAT I AM TRYING TO DO</h2> <p>I am trying to create a list <code>selections</code> with length <code>N</code> where I <em>uniformly in frequen...
<python><list><random>
2025-03-13 17:32:28
5
1,645
bismo
79,506,916
620,679
Sum of products of columns in polars
<p>I have a dataset, part of which looks like this:</p> <div class="s-table-container"><table class="s-table"> <thead> <tr> <th>customer</th> <th>product</th> <th style="text-align: right;">price</th> <th style="text-align: right;">quantity</th> <th>sale_time</th> </tr> </thead> <tbody> <tr> <td>C060235</td> <td>P0204<...
<python><dataframe><python-polars>
2025-03-13 15:28:55
3
4,041
Scott Deerwester
79,506,903
1,708,779
Cannot submit login form with Selenium (Python) using Headless Remote Driver
<p>I am trying to login to a website using Selenium. The relevant form HTML is as follows:</p> <pre class="lang-html prettyprint-override"><code>&lt;form class=&quot;ActionEmittingForm form-wrapper decorate-required&quot; method=&quot;post&quot; novalidate=&quot;&quot; data-rf-form-name=&quot;LoginPageForm_SignInForm&q...
<python><html><selenium-webdriver>
2025-03-13 15:25:13
3
1,690
GNUser
79,506,811
14,132
What could cause strange delays while sending delays from a python aiohttp server?
<p>We have a service with this architecture:</p> <ul> <li>HTTPS requests come into an A10 load balancer that does L4 load balancing</li> <li>Behind it are 2 backend servers with Apache running that terminate the TLS connection</li> <li>In Apache there is a <code>ProxyPass</code> rule that talks to a http service on loc...
<python><apache><debugging><gunicorn><latency>
2025-03-13 14:52:03
1
12,742
moritz
79,506,603
940,490
Check units of pandas DateTime index with pandera
<p>I am new to <code>pandera</code> and am still learning how it works. What is the easiest way to check that the <code>datetime</code> units of an index are in nanoseconds and not milliseconds?</p> <p>In a perfect world, I am looking for compact declarations of this check inside of the class-based API definitions. If ...
<python><pandera>
2025-03-13 13:30:49
1
1,615
J.K.
79,506,581
114,904
How can I use ruff rules to enforce a particular import style
<p>I changed my code base to always import the python <code>datetime</code> module like this:</p> <pre><code>import datetime as dt </code></pre> <p>instead of using</p> <pre><code>import datetime </code></pre> <p>or</p> <pre><code>from datetime import datetime </code></pre> <p>And we had both those in the codebase! It'...
<python><ruff>
2025-03-13 13:22:39
1
4,348
MichielB
79,506,558
2,801,669
Values differ on multiple reads from parquet files using polars read_parquet but not with pandas read_parquet by workstation
<p>I read data from the same parquet files multiple times using polars (polars rust engine and pyarrow) and using pandas pyarrow backend (not fastparquet as it was very slow), see below code.</p> <p>All the parquetfiles contain a column called &quot;backscat&quot; where every element is a list of 1.5 Million floating ...
<python><parquet><python-polars><polars>
2025-03-13 13:12:18
0
1,080
newandlost
79,506,519
616,460
How do I prevent shelve module from appending ".db" to filename?
<p>Python: 3.12.2, OS: MacOS 13.6.6</p> <p>When I specify a filename to <code>shelve.open</code>, it appends <code>.db</code> to the filename:</p> <pre class="lang-none prettyprint-override"><code>% ls % python Python 3.12.2 (main, Feb 6 2024, 20:19:44) [Clang 15.0.0 (clang-1500.1.0.2.5)] on darwin Type &quot;help&qu...
<python><python-3.x><shelve>
2025-03-13 12:54:13
1
40,602
Jason C
79,506,513
4,720,025
Efficient (and Safe) Way of Accessing Larger-than-Memory Datasets in Parallel
<p>I am trying to use <code>polars~=1.24.0</code> on Python 3.13 to process larger-than-memory sized datasets. Specifically, I am loading many (i.e., 35 of them) <code>parquet</code> files via the <code>polars.scan_parquet('base-name-*.parquet')</code> API to create the <code>LazyFrame</code>.</p> <p>In my use case, I ...
<python><python-polars><polars>
2025-03-13 12:48:48
1
1,303
Arda Aytekin
79,506,510
4,960,855
How to offset by 1 year the values of a date column using ORM?
<p>I have an <a href="https://docs.sqlalchemy.org/en/20/orm/declarative_mixins.html" rel="nofollow noreferrer">sqlalchemy ORM</a> for a Postgres table:</p> <pre class="lang-py prettyprint-override"><code>class Item(Base, BoilerPlateMixinBase): id = Column(Integer, primary_key=True) date = Column(Date) value...
<python><postgresql><sqlalchemy><dateadd>
2025-03-13 12:48:02
2
7,228
EliadL
79,506,286
2,604,247
How can I run a uv pytest tool with proper dependencies and module paths?
<h4>Directory Structure</h4> <pre class="lang-none prettyprint-override"><code>project-root/ ├── src/ │ ├── file1.py │ ├── file2.py └── tests/ │ ├── test_file1.py │ ├── test_file2.py ├── requirements.txt ├── pyproject.toml </code></pre> <p>So basically, under the project root, I have the source codes as <code>src/*.py<...
<python><testing><pytest><tdd><uv>
2025-03-13 11:18:17
2
1,720
Della
79,506,238
379,859
Polars upsampling with grouping does not behave as expected
<p>Here is the data</p> <pre class="lang-py prettyprint-override"><code>import polars as pl from datetime import datetime df = pl.DataFrame( { &quot;time&quot;: [ datetime(2021, 2, 1), datetime(2021, 4, 2), datetime(2021, 5, 4), datetime(2021, 6, 6), ...
<python><python-polars>
2025-03-13 10:58:19
1
1,257
JohnRos
79,506,182
5,576,083
python gdal.warp doesn't properly crop raster over shapefile polygons
<p><a href="https://i.sstatic.net/TM0yw0AJ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/TM0yw0AJ.png" alt="enter image description here" /></a></p> <p>I used this script to crop a raster using a polygon shapefile with python gdal.Warp, but it seems it leaves many pixels with value = 1 outside the crop...
<python><gdal>
2025-03-13 10:37:15
1
301
ilFonta
79,505,837
2,420,452
How to make an easily instantiable derivative attribute-only protocol class?
<p>I have a <code>Protocol</code> subclass that defines objects with attributes from an external library:</p> <pre><code>class P(Protocol): val: int </code></pre> <p>For testing purposes, I want to turn this protocol class into something I can instantiate easily. However, when I try to turn it into a dataclass, an ...
<python><python-typing><python-dataclasses>
2025-03-13 08:39:21
1
498
Jan Šimbera
79,505,800
3,999,951
Pandas - Unable to set Index to one of the columns
<p>A data frame is created and its index set to be one of the columns:</p> <pre><code>import pandas as pd ducks_of_destiny = { &quot;duck_ids&quot;: [2381, 2914, 3022, 3090], &quot;titles&quot;: [&quot;Viscount Wigeon&quot;, &quot;Sir Pintail the 4th&quot;, &quot;Lady Tufted&quot;, &quot;The Rig...
<python><pandas><dataframe>
2025-03-13 08:24:00
0
467
acolls_badger
79,505,516
22,213,065
Improve This APNG Webpage Recorder to Capture Smooth 30+ FPS Video
<p>I have written a Python script using Playwright to record a high-quality APNG video of a webpage. The script captures frames at 100 FPS and saves them as an animated PNG. I use it to record bar chart race animations from Flourish Studio, such as this one:<br /> <a href="https://public.flourish.studio/visualisation/2...
<python><python-3.x><playwright><screen-recording><apng>
2025-03-13 05:58:58
0
781
Pubg Mobile
79,505,390
2,130,515
How to grant a lambda function access to call routes in an API gateway
<p>Scenario: I create 4 different lambda functions using docker images. Each function is created froma separate image. Each function contains different FAST API routes for a different service.</p> <p>I create an API Gateway and invoke the 4 different lambda functions with proxy integration. For each, I create a resourc...
<python><aws-lambda><aws-api-gateway><amazon-iam>
2025-03-13 04:06:04
0
1,790
LearnToGrow
79,505,317
368,907
Write CSV file with data in new row in python
<p>I using python locust to do load test and my questions is i try to write csv file with email address as new row but it is separated the email charaters with ',' with each chracter like below:</p> <pre><code>z,b,r,X,S,F,i,E,p,H,1,@,g,m,a,i,l,.,c,o,m I,q,O,2,i,t,a,Q,w,m,2,@,g,m,a,i,l,.,c,o,m 5,w,J,b,1,v,Y,X,f,H,3,@,g,...
<python><python-3.x><locust>
2025-03-13 03:00:29
1
2,802
Ivan
79,505,315
20,706,987
Terminal stops launching after downgrading Python version
<p>I recently upgraded my Ubuntu through it's upgrade suggestion from <code>22.04</code> to <code>24.04</code>. when I try <code>python --version</code> I see <code>3.12.x</code>. But this caused my <code>cqlsh</code> command doesn't work, cause it needs a lower Python version.</p> <p>So I decided to install <code>Pyt...
<python><ubuntu><downgrade>
2025-03-13 02:59:33
1
756
best_of_man
79,505,258
243,031
PyMongo - Group by year based on subdocument date
<p>I have a MongoDB document like:</p> <pre><code>[ { _id: ObjectId('67cfd69ba3e561d35ee57f51'), created_at: ISODate('2025-03-11T06:22:19.044Z'), conversation: [ { id: '67cfd6c1a3e561d35ee57f53', feedback: { liked: false, disliked: true, copied: true, ...
<python><mongodb><aggregation-framework><pymongo><pipeline>
2025-03-13 02:15:22
1
21,411
NPatel
79,505,129
16,723,655
TypeError: Could not convert OscarOscarMichaelJimDwightCreed to numeric
<p>I am following the code (chapter_08_reshaping_and_pivoting) from following website.</p> <p><a href="https://github.com/paskhaver/pandas-in-action" rel="nofollow noreferrer">https://github.com/paskhaver/pandas-in-action</a></p> <pre><code>import pandas as pd pd.read_csv('sales_by_employee.csv').head() </code></pre> <...
<python><pandas><pivot-table>
2025-03-13 00:08:12
0
403
MCPMH
79,505,126
9,133,950
Convert the values in a SQL array by SELECTing from another table?
<p>I have a table &quot;Data&quot; containing arrays of FOOs, and a separate table &quot;Lookup&quot; where I can find the BAR for each FOO. I want to write a SQL query which returns the Data table, but with arrays of the BARs that correspond to the FOOs in the original.</p> <p>I appreicate it may be an awkward table s...
<python><sql><python-polars>
2025-03-13 00:07:38
1
375
DarthVlader
79,504,418
7,256,443
How to check if `pyright: ignore` comments are still required?
<p>I have recently switched from using <code>mypy</code> to <code>pyright</code> for static type checking. <code>mypy</code> has a useful feature whereby it can be configured to warn you if it detects comments instructing it to ignore certain errors which would not actually be raised (described here: <a href="https://s...
<python><python-typing><pyright>
2025-03-12 17:27:13
1
1,033
Ben Jeffrey
79,504,328
1,584,736
Confused about setting environment variables from Python script
<p>The problem is that I'm not able to fetch the variable I set in any way.</p> <p>I used</p> <pre><code> for var in vars: os.putenv(str(f&quot;${var}&quot;), local_config[var]) print(f&quot;{var} has been set&quot;) </code></pre> <p>I've also tried to use <code>os.environ[var]</code> but the result ...
<python><python-3.x>
2025-03-12 16:52:26
1
1,280
ngw
79,504,309
11,062,613
Create a uniform dataset in Polars with cross joins
<p>I am working with Polars and need to ensure that my dataset contains all possible combinations of unique values in certain index columns. If a combination is missing in the original data, it should be filled with null.</p> <p>Currently, I use the following approach with sequential cross joins:</p> <pre><code>def ens...
<python><dataframe><python-polars><polars>
2025-03-12 16:46:33
2
423
Olibarer
79,504,248
4,183,498
Heroku installs extra Python package
<p>I have a Python/Django app which uses <code>Pipfile</code> and <code>Pipfile.lock</code> running on Heroku-22 stack with <a href="https://devcenter.heroku.com/articles/buildpacks#classic-buildpacks" rel="nofollow noreferrer">classic buildpacks</a>.</p> <p><code>requirements.txt</code> is not part of the code base, t...
<python><django><heroku><psycopg2><pgbouncer>
2025-03-12 16:25:52
0
10,009
Dušan Maďar
79,504,247
1,412,564
How to find server_version in psycopg3?
<p>I have this test in Django <a href="https://stackoverflow.com/questions/47232413/how-to-find-postgres-version-from-django">[1]</a> which is using psycopg2:</p> <pre class="lang-py prettyprint-override"><code>from django.db import connection def test_postgresql_version(self): postgresql_version = connection.curs...
<python><django><postgresql><psycopg2><psycopg3>
2025-03-12 16:25:10
3
3,361
Uri
79,504,009
33,886
Detect coordinate precision in polars floats?
<p>I have some coordinate data; some of it high precision, some of it low precision thanks to multiple data sources and other operational realities. I want to have a column that indicates the relative precision of the coordinates. So far, what I want is to essentially count digits after the decimal; in my case more dig...
<python><python-3.x><coordinates><python-polars><polars>
2025-03-12 15:09:30
1
1,012
Kyle
79,503,984
13,812,982
Determining which row causes IntegrityError exception when using cursor.executemany() to insert data
<p>I am inserting a few thousand rows into a table with a UNIQUE constraint, using <code>cursor.executemany()</code>. On some occasions the data may have a duplicate which violates the constraint, and <code>sqlite</code> throws an <code>IntegrityError</code> exception.</p> <p>Is there any way to determine which row cau...
<python><sqlite>
2025-03-12 15:02:51
0
4,331
DS_London
79,503,943
9,669,142
PyCharm Cannot start the IDE
<p>I always used Spyder for my Python scripts, but I switcheed to PyCharm now and installed on my PC (version 2024.3.4). I made some Python scripts earlier in Spyder and committed those to a repo on GitLab. Now I want to clone this repo in PyCharm, but I get the following error:</p> <p><a href="https://i.sstatic.net/x7...
<python><pycharm>
2025-03-12 14:44:05
1
567
Fish1996
79,503,865
9,967,780
numpy timedelta highest unit without loss of information
<p>I have several numpy timedelta values. I want to convert them to the a format that is better to read for humans without losing information.<br /> Let's say I have <code>td = np.timedelta64(10800000000001, 'ns')</code>. Then I can only have it in <code>ns</code> because if I convert it to <code>ms</code>or higher it ...
<python><numpy><timedelta>
2025-03-12 14:11:02
2
374
AkariYukari
79,503,813
13,258,554
MSIX Packaging Tool - Failing Installation
<p>I am trying to create a Windows app from the following simple Python code.</p> <pre><code>from qtpy.QtWidgets import QApplication, QLabel from qtpy.QtCore import Qt if __name__ == &quot;__main__&quot;: # Create the application instance app = QApplication([]) # Create a fullscreen label label = QLab...
<python><uwp><packaging><msix>
2025-03-12 13:54:49
1
393
Mark wijkhuizen
79,503,514
7,134,737
How can I reuse the same virtualenv in a different project?
<p>I have created a project folder with a <code>pyproject.toml</code>, but I want to use the same virtualenv created in the ProjectA in ProjectB, how can I do that ?</p> <p>Whenever I use the poetry env use /full/path/python.exe, it basically creates another venv for me which I want to avoid.</p>
<python><virtualenv><python-poetry>
2025-03-12 11:58:17
1
3,312
ng.newbie
79,503,401
7,462,275
How to generate efficiently a full panda data frame from another data frame with missing values?
<p>Considering the following data frame : <code>df1 = pd.DataFrame({'col1':[1,4,5,7],'col2':[10,20,30,2]})</code>, some values are missing in <code>col1</code> to have a full series from 1 to 7.</p> <p>So, a second data frame <code>df2</code> is created with the full series in <code>col1</code> : <code>df2 = pd.DataFra...
<python><pandas><dataframe>
2025-03-12 11:10:00
0
2,515
Stef1611