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,253,276
10,132,474
how could I write a pytorch model in diamond inheritance way?
<p>I need to implement a complex model, and I better to use Diamond inheritance to satisfy different requirements, here is the toy code to show what I am trying to do:</p> <pre><code>import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.model_zoo as modelzoo import torch.distributed as d...
<python><inheritance><pytorch>
2024-12-05 03:00:17
1
1,147
coin cheung
79,253,234
1,492,613
how does the area interpolation for downsampling work when the scale factor is not integer?
<p>by definition area interpolation is just weighted by the pixel area.</p> <p>So I suppose if scale factor is 1.5, then output pixel 00 contain full pixel of 00, half of the 01 and 10, 1/4 of the 11. the weight will be in_pixel_area/(1.5)^2</p> <p>However, this does not seem to be the case:</p> <pre class="lang-py pre...
<python><pytorch><interpolation>
2024-12-05 02:19:16
1
8,402
Wang
79,253,146
1,487,336
What is the difference between `cached_property` and `field(init=False)` in Python dataclass?
<p>I have a dataset which needs to be loaded from database. I'm wondering what is the difference between the following two ways of handling it.</p> <pre><code>import pandas as pd from dataclasses import dataclass, field @dataclass class A: df: pd.DataFrame = field(init=False) def load_df(self): self....
<python><python-dataclasses>
2024-12-05 01:18:04
2
809
Lei Hao
79,252,985
11,197,957
Is there a sane way of writing an external Python library with mssparkutils calls?
<p>I have been tasked with clarifying and simplifying a pretty knotty codebase, which exists at present as a series of <strong>&quot;runbooks&quot;</strong> in <strong>Azure Synapse</strong>. As part of that process, I thought it would be good to put some of the more convoluted data analysis into <strong>an external Py...
<python><azure><python-import><azure-synapse>
2024-12-04 23:14:37
1
734
Tom Hosker
79,252,957
754,136
Bars almost disappear when I layer and facet charts
<pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd import altair as alt np.random.seed(0) model_keys = ['M1', 'M2'] data_keys = ['D1', 'D2'] scene_keys = ['S1', 'S2'] layer_keys = ['L1', 'L2'] ys = [] models = [] dataset = [] layers = [] scenes = [] for sc in scene_keys: for ...
<python><altair>
2024-12-04 22:58:13
1
5,474
Simon
79,252,863
1,473,517
Is it possible to speed up my set implementation?
<p>I am trying to make a fast and space efficient set implementation for 64 bit unsigned ints. I don't want to use set() as that converts everything into Python ints that use much more space than 8 bytes per int. Here is my effort:</p> <pre><code>import numpy as np from numba import njit class HashSet: def __ini...
<python><performance><numba>
2024-12-04 22:06:10
1
21,513
Simd
79,252,813
12,334,204
How to "inject" a local variable when importing a python module?
<p>Is it possible to declare a local variable <em>before</em> it's imported?</p> <p>For example to get this code to run as expected:</p> <pre class="lang-py prettyprint-override"><code># a.py # do magic here to make b.foo = &quot;bar&quot; import b b.printlocal() </code></pre> <pre class="lang-py prettyprint-override...
<python><python-3.x><databricks><python-unittest><python-unittest.mock>
2024-12-04 21:40:40
1
589
Brett S
79,252,785
9,492,730
Troubleshooting consuming python module in azure function
<p>I have the following code structure in my Python (3.12.3) application:</p> <pre><code>**ROOT** -- .venv -- azure_functions ---- function_app.py ---- host.json ---- local.settings.json ---- requirements.json -- src ---- __init__.py ---- main.py -- tests ---- test_action.py -- .gitignore -- requirements.txt -- setup.p...
<python><azure><azure-functions><python-module>
2024-12-04 21:29:04
1
4,783
dododo
79,252,670
13,413,858
How is memory handled for intermidiate values in Python?
<p>For example, if you need to construct a new object from 2 lists, it seems that it is irrelevant whether you concat them and then iterate, or you yield from one list and then the other, even though intuitively concat should allocate more memory for that temporary value.</p> <pre class="lang-py prettyprint-override"><...
<python><memory>
2024-12-04 20:40:26
1
494
Mathias Sven
79,252,655
2,326,896
Breakpoint in a callback function from iPyWidgets Jupiter Notebook not breaking in VsCode
<p>I created a Jupyter Notebook cell with this code</p> <pre><code>from ipywidgets import widgets def test_fun(button): for i in range(10): # breakpoint in this line print(i) # Button to split in 12 months test_button = widgets.Button(description=&quot;Click Me!&quot;) test_button.on_click(test_fun) displ...
<python><visual-studio-code><debugging><jupyter-notebook><ipywidgets>
2024-12-04 20:35:19
0
891
Fernando César
79,252,519
16,606,223
PyTorch > TorchScript tensor.view() alternative?
<p>I have the following code:</p> <pre class="lang-py prettyprint-override"><code>@torch.jit.script def my_function(t: torch.Tensor) -&gt; torch.Tensor: if t.dtype != torch.bfloat16: raise ValueError(&quot;Input tensor must be of dtype torch.bfloat16&quot;) int_type = torch.int16 t_bits = t.view(int...
<python><pytorch><torchscript>
2024-12-04 19:37:03
1
1,631
Yahor Barkouski
79,252,493
12,466,687
How to create geom_segment() plot on Date x-axis using plotnine in python?
<p>Not able to figure out how to use <code>geom_segment()</code> on <code>Date</code> <code>x-axis</code> in <code>python</code> by using <code>plotnine</code>. Have tried some code but getting error:</p> <pre><code>import pandas as pd from plotnine import ggplot, aes, geom_segment from datetime import date # this is ...
<python><ggplot2><plotnine><geom-segment>
2024-12-04 19:26:12
1
2,357
ViSa
79,252,320
5,763,413
Pip fails with ReadTimeoutError on internal Artfactory
<p>TLDR: Pip/mamba/conda keep failing with a timeout issue on arbitrary packages. <strong>Pip is set up to pull from an internal artifactory.</strong></p> <p>The contents of pip.conf</p> <pre class="lang-none prettyprint-override"><code>[global] index-url = https://user:password@artifactory.myURL.com/artifactory/api/py...
<python><pip><artifactory><connection-timeout><timeoutexception>
2024-12-04 18:16:16
1
2,125
blackbrandt
79,252,306
8,163,071
Testing passport.js login with selenium in CI fashion
<p>I have a set of existing selenium (Selenium Webdriver 4, python) tests for a website that will henceforth be authenticated with <a href="https://www.passportjs.org/packages/passport-google-oauth20/" rel="nofollow noreferrer">passsport.js google oauth2</a>. I want to continue automating the end-to-end workflow starti...
<python><authentication><selenium-webdriver><oauth-2.0><passport.js>
2024-12-04 18:11:03
0
3,719
C. Peck
79,252,301
1,390,272
Regex match only when there is no printable characters anywhere behind it
<p>As an example, I want to match the letter A, if there are 0 or more is white spaces behind it and no printable character, I want a solution that will broudly work in the default python java, golang, and other engines.</p> <p>Match this:</p> <pre><code> A </code></pre> <p>Not this:</p> <pre><code> x A </co...
<python><java><regex><go>
2024-12-04 18:09:01
1
1,673
Goku
79,252,297
46,521
Why does Pandas .floor() throw AmbiguousTimeError for this Timestamp that's already unambiguous?
<p>The following fails:</p> <pre><code>def round_in_tz(epoch_sec: int, tz_name: str, freq_spec: str): &quot;&quot;&quot;Round the given epoch timestamp to the nearest pandas time frequency spec in the given timezone.&quot;&quot;&quot; return pd.to_datetime(epoch_sec, unit='s', utc=True).tz_convert(tz_name).floor(fr...
<python><pandas><dst>
2024-12-04 18:07:53
1
6,651
tba
79,252,248
2,270,043
How to unit test AWS Glue scripts using pytest, Dynamic frames and Data frames?
<p>I want to unit test my AWS Glue scripts. I am using Python and Pyspark. I want to unit test functions that utilise Dynamic frames and Data frames. I don't need to interface with AWS or data on AWS. I want to essentially assert the content of the frames is correct for these small testable functions.</p> <p>I was hopi...
<python><pyspark><pytest><aws-glue>
2024-12-04 17:54:31
0
781
SamBrick
79,252,245
2,893,712
Pandas Filter and Sum but Apply to All Rows
<p>I have a dataframe that has user ID, code, and value.</p> <pre><code>user code value 0001 P 10 0001 P 20 0001 N 10 0002 N 40 0002 N 30 0003 P 10 </code></pre> <p>I am trying to add a new column that groups by User ID, filters for code = <c...
<python><pandas>
2024-12-04 17:53:18
2
8,806
Bijan
79,252,195
5,167,277
Vercel --prebuilt Issue with FastAPI and Github Actions
<p>I’m trying to deploy a FastAPI app using Github Actions to Vercel. I can successfully deploy it without using the <code>--prebuilt</code> tag. However, it seems to me that the <code>--prebuilt</code> tag prevents the whole source code to be shared/deployed to Vercel according to the docs <a href="https://vercel.com/...
<python><github-actions><fastapi><vercel>
2024-12-04 17:36:27
1
1,163
gmartinsnull
79,251,914
16,389,095
Convert list of integers into a specific string format
<p>I'm dealing with a list of integers that represent the pages in which a keyword was found. I would like to build block of code that converts this list into a string with a specific format that follow some simple rules. Single integers are converted into string. Consecutive integers are considered as intervals (left ...
<python><string><list><integer>
2024-12-04 16:04:06
2
421
eljamba
79,251,900
4,776,977
CUDA out of memory while using Llama3.1-8B for inference
<p>I have written a simple Python script that uses the HuggingFace <code>transformers</code> library along with <code>torch</code> to run <code>Llama3.1-8B-instruct</code> purely for inference, after feeding in some long-ish bits of text (about 10k-20k tokens). It runs fine on my laptop, which has a GPU with 12GB RAM, ...
<python><pytorch><huggingface-transformers><llama>
2024-12-04 16:00:36
0
1,768
Tom Wagstaff
79,251,882
18,206,974
What operations are thread-safe in Python?
<p>I am trying to understand why some particular code snippets behave thread-safe.</p> <p>There's a <a href="https://docs.python.org/3/faq/library.html#what-kinds-of-global-value-mutation-are-thread-safe" rel="nofollow noreferrer">Python's FAQ page</a> which says what mutations are considered thread safe (though I stil...
<python><thread-safety><gil>
2024-12-04 15:54:54
1
336
Vladyslav Chaikovskyi
79,251,873
1,592,427
Haystack 2 with Elasticsearch complex document
<p>I have Elasticsearch storage with a <code>movies</code> index which is populated with documents like that:</p> <pre class="lang-json prettyprint-override"><code>{ _id: ObjectId, title: &quot;Some film&quot;, actors: [ { _id: ObjectId, title: &quot;Actor A&quot; }, { _id: ObjectId, title: &quot;Actor B&quot; } ...
<python><elasticsearch><rag><haystack>
2024-12-04 15:53:06
1
414
Andrew
79,251,582
4,692,635
rise in jupyter truncates in height in fenced syntax highlight code
<p>I added the following code into a jupyter notebook cell:</p> <pre><code># this is just a demo # line 2 # line 3 # line 4 def fib(n): if n&lt;1: return 1 else: return fib(n-1)+fib(n-2) if __name__ == '__main__': print(fib(5)) </code></pre> <p>The code was rendered correctly:</p> <p><a ...
<python><jupyter-notebook><slider><jupyter><rise>
2024-12-04 14:32:09
0
567
oyster
79,251,417
3,414,663
In Polars, how can you update several columns simultaneously?
<p>Suppose we have a Polars frame something like this</p> <pre><code>lf = pl.LazyFrame([ pl.Series(&quot;a&quot;, ...), pl.Series(&quot;b&quot;, ...), pl.Series(&quot;c&quot;, ...), pl.Series(&quot;i&quot;, ...) ]) </code></pre> <p>and a function something like this</p> <pre><code>def update(a, b, c, i)...
<python><python-polars>
2024-12-04 13:49:42
1
589
user3414663
79,251,181
7,054,480
PyCharm typing warning inconsistency for abstract base classes
<p>In the following code, PyCharm is issuing a typing warning for <code>Base.foo</code> (&quot;Expected to return 'int', got no return&quot;) but not for <code>Base.bar</code>, which has exactly the same typing hint and return type:</p> <pre class="lang-py prettyprint-override"><code>import abc class Base(abc.ABC): ...
<python><pycharm><python-typing><abc>
2024-12-04 12:34:16
1
332
Fidel I. Schaposnik
79,250,910
4,738,644
Adjust images to screen size in tensorboard instead of maximizing
<p>I have a grid of images (2 rows x 4 columns) in Tensorboard. Each image is 640 x 480 and I have a sequence of those grids, representing the prediction changes in each epoch.</p> <p>My problem is that the image is either too small...</p> <p><a href="https://i.sstatic.net/nAWbOSPN.png" rel="nofollow noreferrer"><img s...
<python><pytorch><tensorboard>
2024-12-04 11:08:19
0
421
Diego Alejandro Gómez Pardo
79,250,681
1,826,241
Add custom overload to Python method with existing type hints
<p>Is it possible to extend existing type hints for a Python package <em>in my application code</em> (i.e., not touching the upstream type hints) by adding custom overload for a method? (See also <a href="https://github.com/dlukes/pandas-apply-set" rel="nofollow noreferrer">repo with minimal reproducible example</a>.)<...
<python><pandas><overloading><python-typing>
2024-12-04 10:05:50
1
1,873
dlukes
79,250,667
14,681,038
Refactoring marshmellow schema to pydantic 2
<p>I have been struggling to refactor this marshmellow schema to pydantic 2. Problem is with AttributeValue field. When I refactor this to pydantic, I always get strange errors regarding this field. This attribute field is dynamic that can accept many values as you can see it in <code>_get_field</code> function. I cann...
<python><refactoring><python-dataclasses><marshmallow><pydantic-v2>
2024-12-04 10:02:56
0
643
Sharmiko
79,250,415
19,500,571
Calculate relative difference of elements in a 1D numpy array
<p>Say I have a 1D numpy-array given by <code>np.array([1,2,3])</code>.</p> <p>Is there a built-in command for calculating the relative difference between each element and display it in a 2D-array? The result would then be given by</p> <p><code>np.array([[0,-50,-100*2/3], [100,0,-100*1/3], [200,50,0]])</code></p> <p>Al...
<python><numpy>
2024-12-04 08:44:20
1
469
TylerD
79,250,306
11,630,148
Can't get data from Companies House and HMRC API that have more than £2m in turnover data
<p>I've been dealing with this issue for a day now and have troubles getting company data from HMRC and Companies House API. I mainly need companies that have more than £1m turnover. I have set <code>MIN_TURNOVER = 1_000_000</code> in my code to filter out companies that have less than £1m turnover.</p> <p>This is my c...
<python><web-scraping>
2024-12-04 08:12:58
1
664
Vicente Antonio G. Reyes
79,250,200
6,862,601
Make ssh run a local script when invoked by subprocess.Popen
<p>I have this code that executes shell commands on remote hosts:</p> <pre><code>cmd_list = shlex.split(cmd) proc = subprocess.Popen(cmd_list, stdin=sys.stdin, stdout=subprocess.PIPE, stderr=subprocess.PIPE) </code></pre> <p>I am trying to run this command (based on this <a href="https://stackov...
<python><ssh>
2024-12-04 07:25:53
1
43,763
codeforester
79,250,060
7,364,894
Pymemcache OSError: [Errno 99] Cannot assign requested address
<p>Context:</p> <p>We have a django application running inside a container on our cloud instance. We recently started seeing errors when we try to access value from django cache in an api end point.</p> <pre><code>cache.get('key') </code></pre> <p>This api endpoint is very frequently accessed by our users.</p> <p>The f...
<python><django><network-programming><memcached><pymemcached>
2024-12-04 06:13:35
0
3,648
Thakur Karthik
79,249,502
298,511
No name 'Main' in module 'juliacall'
<p>I have an interesting problem where the line <code>from juliacall import Main as jl</code> shows an error in both Pylint and Pylance (VSCode). Is this just a linter issue and if so, can it be resolved (other than disabling)?</p> <pre><code>No name 'Main' in module 'juliacall' Pylint(E0611:no-name-in-module) &quot;Ma...
<python><julia><juliacall>
2024-12-03 23:49:04
1
2,918
Mike Lowery
79,249,475
405,017
In Dash can I update an output value but disable further updates from that change?
<p>I have two inputs, and an output. Both inputs, when changed, affect the output. When the user types a value in one input, I want the value in the other to be cleared...but to NOT invoke the follow-on callback that would update the output. Is this possible?</p> <pre class="lang-py prettyprint-override"><code>app.layo...
<python><plotly-dash><circular-dependency>
2024-12-03 23:34:30
0
304,256
Phrogz
79,249,439
6,929,343
Tkinter menu command, set string to None
<p>I have this code I'd like to condense if possible:</p> <pre class="lang-py prettyprint-override"><code>def ForgetPassword(): &quot;&quot;&quot; Clear sudo password for extreme caution &quot;&quot;&quot; global SUDO_PASSWORD SUDO_PASSWORD = None self.tools_menu.add_command(label=&quot;Forget sudo passwor...
<python><tkinter><variable-assignment>
2024-12-03 23:10:30
0
2,005
WinEunuuchs2Unix
79,248,888
363,028
How to embed python scripts into LibreOffice Calc (v.24.8.3.2)
<p>This is a repeat of <a href="https://stackoverflow.com/questions/70501673/how-to-embed-python-scripts-into-libreoffice-calc">How to embed python scripts into LibreOffice Calc</a> because <a href="https://stackoverflow.com/a/70510410">https://stackoverflow.com/a/70510410</a> does not work for me.</p> <p>Specifically ...
<python><libreoffice-calc>
2024-12-03 19:09:35
1
34,146
Ole Tange
79,248,883
3,652,584
Submit too many commands from different files as a single batch job
<p>I want to use bash to run a batch job on an HPC. The commands to be executed are saved to a text file. Previously, I used the following to run each line of the text file separately as a batch job.</p> <pre><code>File=Commands.txt head -n $SLURM_ARRAY_TASK_ID $File | tail -n 1 | bash </code></pre> <p>I need to extend...
<python><bash><slurm><hpc>
2024-12-03 19:06:42
0
537
Ahmed El-Gabbas
79,248,780
2,590,981
Python: Can one call of random.uniform (a,b) influence the outcome of a second call?
<p>I tripple-checked this: the call of the function earlier in my code has an influence on the outcome of a second call (with different variables involved) later on in my code. Random seed is not changed within. I'm puzzled.</p>
<python><random><seed>
2024-12-03 18:20:44
1
653
JohnDoe
79,248,710
2,475,195
Reshaping out tensor in pytorch produces weird behavior
<p>I was going through <a href="https://github.com/parrt/fundamentals-of-deep-learning/blob/main/notebooks/3.train-test-diabetes.ipynb" rel="nofollow noreferrer">https://github.com/parrt/fundamentals-of-deep-learning/blob/main/notebooks/3.train-test-diabetes.ipynb</a> as an exercise, but forgot to reshape y tensors in ...
<python><deep-learning><pytorch><neural-network><tensor>
2024-12-03 17:54:12
1
4,355
Baron Yugovich
79,248,600
1,114,872
an import that works on python, but not on jupyter lab
<p>I have installed a library (<a href="https://pypi.org/project/plot-likert/" rel="nofollow noreferrer">https://pypi.org/project/plot-likert/</a>) in a venv, but curiously it works on vanilla python and does not work on <code>jupyter lab</code></p> <p>On vanilla python:</p> <pre><code>(venv_jupyter) lucas@karaboudjan:...
<python><pip><jupyter-lab>
2024-12-03 17:15:29
0
1,512
josinalvo
79,248,554
885,486
Tensorflow - Time Series Tutorial - How Does Data Windowing Works?
<p>I am following the <a href="https://www.tensorflow.org/tutorials/structured_data/time_series#linear_model" rel="nofollow noreferrer">Time Series tutorial</a> from TensorFlow, which takes in weather data and predicts the future value of temperature.</p> <p>I have a hard time wrapping my head around how the Window Gen...
<python><tensorflow><neural-network>
2024-12-03 17:00:43
1
1,448
Erken
79,248,486
6,447,123
How to reverse the tokenizer.apply_chat_template()
<pre class="lang-py prettyprint-override"><code># Chat template example prompt = [ { &quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Random prompt.&quot;}, ] # Applying chat template prompt = tokenizer.apply_chat_template(chat) </code></pre> <p>Is there anyway to convert the prompr string back to t...
<python><huggingface-transformers>
2024-12-03 16:39:55
0
4,309
A.A
79,248,481
653,966
Finding Python Errors - Async function not Awaited
<p>I am using Python in Visual Studio 2022 - not Code, on Win11. I had a bug recently where an async function was not awaited. It occurred to me that it would be great to find these types of errors at design time, not run time.</p> <p>I have tried installing PyLint, but none of the PyLint options are available in the ...
<python><asynchronous><pylint>
2024-12-03 16:38:39
0
2,195
Steve Hibbert
79,248,406
2,617,144
Not JSON serializable when using SQLAlchemy
<p>Given the following code below</p> <pre><code>from sqlalchemy.orm import mapped_column, Mapped, DeclarativeBase, relationship from sqlalchemy import String, Integer, ForeignKey, Column class Base(DeclarativeBase): pass class CModel(Base) : __tablename__ = 'c' id: Mapped[int] = mapped_column(Integer, p...
<python><sqlalchemy>
2024-12-03 16:20:46
0
1,851
Mark Hill
79,248,350
1,473,320
Is it possible to install the Google Cloud CLI on alpine Linux Without it installing a bundled version of python?
<h2>Problem Background</h2> <p>I am building an Alpine Linux docker image to use as a (relatively) lightweight CI image. In this image, I need to have the Google Cloud <code>gcloud</code> CLI installed.</p> <p>I am installing Python from my <code>Dockerfile</code> like this:</p> <pre><code>RUN apk add python3 </code></...
<python><docker><gcloud><alpine-linux>
2024-12-03 16:06:17
1
472
kashev
79,248,235
4,653,423
Validate kubernetes memory & cpu resources input strings in python
<p>I am writing an API which takes inputs for kubernetes container resources. The API takes only the 4 values as string inputs and not the entire <code>resources</code> block.</p> <p>Examples:<br /> For memory inputs: <code>4Gi</code>, <code>8G</code>, <code>512M</code><br /> For cpu limits: <code>1</code>, <code>250...
<python><python-3.x><kubernetes>
2024-12-03 15:36:26
1
1,369
Mukund Jalan
79,248,152
1,818,122
AWS CDK and Multiple Chalice Apps with CDK-Chalice
<p>My goal is to create an infra stack and create a few lambdas using Chalice that would use the resources on that stack.</p> <p>There is a tutorial given on <a href="https://aws.amazon.com/blogs/developer/aws-chalice-adds-support-for-the-aws-cdk/" rel="nofollow noreferrer">https://aws.amazon.com/blogs/developer/aws-ch...
<python><amazon-web-services><aws-cdk><chalice>
2024-12-03 15:11:02
0
1,350
The_Cute_Hedgehog
79,248,001
13,392,257
object has no attribute '__fields_set__'. Did you mean: '__fields__'?
<p>I am using <code>pydantic-settings==2.4.0</code> and trying to configure my settings class with yaml file</p> <p>My code:</p> <pre><code>import os import yaml from pydantic.v1 import AnyHttpUrl, BaseSettings, EmailStr, validator, BaseModel, Field from typing import List, Optional, Union, Any from pathlib import Pa...
<python><pydantic>
2024-12-03 14:28:58
1
1,708
mascai
79,247,843
4,190,098
Cannot crop correctly with openCV in Python
<p>I want to crop the identity card off of this scan <a href="https://i.sstatic.net/QsYdqgRn.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/QsYdqgRn.png" alt="enter image description here" /></a> Mind, that there is a lot of white space under the id (until here)</p> <p>First, I preprocess the image:</p>...
<python><opencv><image-processing><computer-vision><crop>
2024-12-03 13:41:21
2
949
Selphiron
79,247,768
1,719,931
Define __dict__ in slotted dataclass
<p>Consider the following example:</p> <pre class="lang-py prettyprint-override"><code>from dataclasses import dataclass @dataclass(slots=True) class Circle: radius:int = 2 @property def myslots(self): return self.__slots__ @property def __dict__(self): return self.__slots__ c = ...
<python><python-dataclasses><slots>
2024-12-03 13:20:30
1
5,202
robertspierre
79,247,457
2,270,043
How to set ENV VARs that can be used during PyCharm local development in AWS Glue Interactive Session Magics
<p>I'm trying to make an ENV VAR available to use in an AWS Glue Interactive Session Magic. The ENV VAR would exist in a .env file. Essentially I want to do this:</p> <p><code>%extra_py_files { SOME_PATH_TO_S3_DEPENDENCIES }</code></p> <p>When the Interactive Session eventually kicks off it has no knowledge of the ENV ...
<python><jupyter-notebook><pycharm><aws-glue>
2024-12-03 11:46:51
0
781
SamBrick
79,247,386
3,324,294
HKDF function in Python and NodeJS give different results, why?
<p>While working on implementing encryption/decryption between a Python backend server and a NodeJS frontend, my decryption attempts on the frontend were failing. I noticed that HKDF result generated by <code>cryptography</code> library in Python and by <code>crypto</code> in NodeJS don't output the same results.</p> <...
<python><node.js><cryptography><hkdf>
2024-12-03 11:24:51
1
374
ZeroByter
79,247,378
3,264,895
twisted reactor not launching tasks on raspberry pi
<p>I don't know why this code works on my windows computer, but just blocks on my raspberry pi.</p> <pre><code>from twisted.internet import reactor, ssl, threads from autobahn.twisted.websocket import WebSocketClientFactory, WebSocketClientProtocol import queue from queue import Empty import threading import time conn...
<python><python-3.x><raspberry-pi><twisted>
2024-12-03 11:23:33
1
864
Spoutnik16
79,247,356
12,297,666
Why i got this error trying to import Parametric UMAP
<p>I am trying to use <a href="https://umap-learn.readthedocs.io/en/latest/transform_landmarked_pumap.html" rel="nofollow noreferrer">Parametric UMAP</a>, using this code:</p> <pre><code>from umap import ParametricUMAP p_embedder = ParametricUMAP() </code></pre> <p>And this error happens:</p> <pre><code>C:\Users\ldsp_\...
<python><umap>
2024-12-03 11:16:35
1
679
Murilo
79,247,309
244,297
How to clean up thread-local data after using ThreadPoolExecutor?
<p>I want to use <a href="https://docs.python.org/3/library/concurrent.futures.html#threadpoolexecutor" rel="nofollow noreferrer"><code>ThreadPoolExecutor</code></a> to parallelize some (legacy) code with database access. I would like to avoid creating a new database connection for each thread, so I use <a href="https:...
<python><multithreading><database-connection><threadpool><python-multithreading>
2024-12-03 11:01:23
2
151,764
Eugene Yarmash
79,247,299
726,730
What is the right way to close a pair of QThread/Process?
<p>In my main pyqt5 program i instantiate some classes.</p> <p>Each of this classes are born a QThread and a Process.</p> <p>I am having trouble closing all this pairs of QThreads/Processes.</p> <p>Here is what i do:</p> <p>main close event:</p> <pre class="lang-py prettyprint-override"><code> def closeEvent(self,ev...
<python><process><qthread><terminate>
2024-12-03 10:59:33
0
2,427
Chris P
79,247,249
11,571,390
Dynamic module aliasing in __init__.py works at runtime but is not recognized by Pylance in VSCode
<p>I’m trying to create a clean alias for a submodule in my Python package by dynamically importing it in <code>__init__.py</code> and exposing it as a different name. While this works perfectly at runtime, Pylance in VSCode does not recognize the alias, and I lose autocomplete and type checking.</p> <p>Here’s a minima...
<python><visual-studio-code><pylance>
2024-12-03 10:42:12
0
595
Gary Frewin
79,247,128
1,504,082
Pandas pyarrow types and sum aggfunc in pivot tables
<p>I stumbled over the issue that the summation aggfunc in pandas behaves not as expected when using <code>bool[pyarrow]</code> instead of <code>bool</code>.</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({'count': [False] * 12, 'index': [0, 1] * 6, 'cols': ['a', 'b', 'c'] * 4}) # count inde...
<python><pandas><pyarrow>
2024-12-03 10:08:46
0
4,475
maggie
79,247,116
19,576,917
Pyinstaller isn't properly converting a python script with alot of dependencies to an exe file
<p>I have written a python script that enables users to upload pdf files and ask questions about them. The script uses Gemini for smart responses and PyQt5 for the GUI. I am trying to convert this script into an executable file that is portable and can run on other windows devices. The script has the following imports:...
<python><python-3.x><pyinstaller><desktop-application><auto-py-to-exe>
2024-12-03 10:05:41
0
488
Chandler Bong
79,247,088
9,261,745
telegram bot to trigger share_to window with checkbox
<p>I am using python-telegram-bot module to create a InlineKeyboardButton called invite. I would like the user to click the invite button then a share_to window with checkbox showing up like this <a href="https://i.sstatic.net/yrCEOMI0.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/yrCEOMI0.png" alt="en...
<python><telegram-bot><python-telegram-bot>
2024-12-03 09:59:42
0
457
Youshikyou
79,246,860
14,333,315
common folder with template files for gitlab python projects
<p>I have a folder with word templates files which are common for several projects. If template was changed, i have to copy new file to all that projects in that directory.</p> <p>Is there a way to automate the procedure?</p> <p>I thought about creating a diff project &quot;word_templates&quot; and make changes in the ...
<python><git><gitlab>
2024-12-03 08:50:21
1
470
OcMaRUS
79,246,676
3,104,974
Plot contours from discrete data in matplotlib
<p>How do I make a <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.contourf.html" rel="nofollow noreferrer"><code>contourf</code></a> plot where the areas are supposed to be discrete (integer array instead of float)?</p> <p>The values should discretely mapped to color indices. Instead matplotlib ju...
<python><matplotlib><contourf>
2024-12-03 07:42:04
1
6,315
ascripter
79,245,922
21,935,028
How to get parameter name, type and default value of Oracle PLSQL function body?
<p>I have the following PLSQL code which I am processing with Antlr4 in Python. I ma having trouble extracting the function parameter name and related details.</p> <pre><code>CREATE OR REPLACE FUNCTION getcost ( p_prod_id IN VARCHAR2 , p_date IN DATE) RETURN number AS </code></pre> <p>The ParseTree output for this:<...
<python><antlr4>
2024-12-03 00:04:03
1
419
Pro West
79,245,905
11,061,827
Sagemaker's SklearnModel requirements.txt not getting installed
<p>This is my code:</p> <pre><code>from sagemaker.sklearn import SKLearnModel role = sagemaker.get_execution_role() model = SKLearnModel( model_data= f&quot;s3://{default_bucket}/{prefix}/model.tar.gz&quot;, role=role, entry_point=&quot;inference.py&quot;, framework_version=&quot;1.2-1&quot;, ...
<python><amazon-web-services><scikit-learn><amazon-sagemaker>
2024-12-02 23:51:31
1
631
Daniele Gentili
79,245,886
15,842
How can I efficiently scan multiple remote parquet files in parallel?
<p>Suppose I have <code>urls</code>, a list of <code>s3</code> Parquet urls (on S3).</p> <p>I observe that this <code>collect_all</code> runs in O(urls).</p> <p>Is there a better way to parallelize this task?</p> <pre class="lang-py prettyprint-override"><code>import polars as pl pl.collect_all(( pl.scan_parquet(ur...
<python><python-polars>
2024-12-02 23:37:46
1
21,402
Gregg Lind
79,245,770
472,610
Where is scipy.stats.dirichlet_multinomial.rvs?
<p>I wanted to draw samples from a <a href="https://en.wikipedia.org/wiki/Dirichlet-multinomial_distribution" rel="nofollow noreferrer">Dirichlet-multinomial</a> distribution using SciPy. Unfortunately it seems that <code>scipy.stats.dirichlet_multinomial</code> <a href="https://docs.scipy.org/doc/scipy/reference/gener...
<python><scipy><statistics>
2024-12-02 22:25:51
1
8,002
Jonathan H
79,245,689
1,843,101
How to Configure tufup URLs for new Updates and Fetching Metadata/Targets?
<p>I'm using the python <a href="https://github.com/dennisvang/tufup" rel="nofollow noreferrer">tufup library</a> to manage updates for my application, it seems that I need to specify two different URLs, but I'm struggling to understand from the <a href="https://github.com/dennisvang/tufup-example" rel="nofollow norefe...
<python><tkinter><updates><tuf><tufup>
2024-12-02 21:46:48
1
1,015
Michael Romrell
79,245,514
2,889,716
Error with Celery+S3 celery.exceptions.ImproperlyConfigured: Missing bucket name
<p>This is my script to have a celery on SQS and S3 as the result backend:</p> <pre class="lang-py prettyprint-override"><code>from celery import Celery from celery.backends.s3 import S3Backend # Set your SQS queue URL sqs_queue_url = 'https://sqs.eu-central-1.amazonaws.com/938891507445/test-sqs-queue' app = Celery...
<python><amazon-s3><celery><amazon-sqs>
2024-12-02 20:26:32
0
4,899
ehsan shirzadi
79,245,287
6,862,601
W0622: Redefining built-in 'help' (redefined-builtin)
<p>I have this method that causes a pylint issue:</p> <pre><code>def add_ssh_config_path(self, help=&quot;Enter ssh-config path for ssh connection to the host.&quot;, required=False, metavar=&quot;&lt;SSH_CONFIG_PATH&gt;&quot;): self._parser.add_argument(&quot;--ssh-c...
<python><pylint>
2024-12-02 19:07:44
1
43,763
codeforester
79,245,159
1,449,982
How to run Stable Diffusion 3.5 Large on 4090?
<p>I have 4090 and this code:</p> <pre><code>login(HF_TOKEN) self.pipe = StableDiffusion3Pipeline.from_pretrained(&quot;stabilityai/stable-diffusion-3.5-large&quot;, torch_dtype=torch.bfloat16) self.pipe = self.pipe.to(&quot;cuda&quot;) </code></pre> <p>This fails to load to vram due to oom. What is the correc...
<python><huggingface><stable-diffusion>
2024-12-02 18:19:09
1
8,652
Dima
79,245,038
3,723,031
Python typing error when incrementing a dict value: 'Unsupported operand types for + ("object" and "int")'
<p>I have this code:</p> <pre><code>result = {&quot;AAA&quot;: &quot;a&quot;, &quot;BBB&quot;: &quot;b&quot;, &quot;Count&quot;: 0} result[&quot;Count&quot;] += 1 </code></pre> <p>mypy generates this error message:</p> <pre class="lang-none prettyprint-override"><code>Unsupported operand types for + (&quot;object&quot;...
<python><python-typing><mypy>
2024-12-02 17:34:00
2
1,322
Steve
79,245,015
2,801,669
Pydantic objects as elements in a Polars dataframe get automatically converted to dicts (structs)?
<p>What puzzles me is that when running</p> <pre class="lang-py prettyprint-override"><code>class Cat(pydantic.BaseModel): name: str age: int cats = [Cat(name=&quot;a&quot;, age=1), Cat(name=&quot;b&quot;, age=2)] df = pl.DataFrame({&quot;cats&quot;: cats}) df = df.with_columns(pl.lit(0).alias(&quot;acq_num&qu...
<python><dataframe><python-polars><pydantic>
2024-12-02 17:22:51
1
1,080
newandlost
79,245,011
5,115,928
Cassandra Python driver custom retryPolicy doesn't catch ReadFailure
<p>I created a custom retryPolicy to implement backoff for my Keyspaces cluster.</p> <p>It works for read timeouts, I do have logs with <code>retry on_read_timeout</code>. But It doesn't retry on <code>ReadFailure</code>, and my understanding is that it should do it thanks to the <code>on_request_error</code> method. B...
<python><cassandra><amazon-keyspaces><datastax-python-driver>
2024-12-02 17:21:05
1
306
sechstein
79,244,988
1,430,607
Unable to integrate asyncio and scrapy
<p>I have this spider:</p> <pre class="lang-py prettyprint-override"><code>import logging from scrapy import Spider, Request, settings from dummy import settings from dummy.items import DummyItem LOGGER = logging.getLogger(__name__) class DummySpider(Spider): name = 'DummySpider' def start_requests(self)...
<python><scrapy><python-asyncio><twisted>
2024-12-02 17:13:55
2
31,741
Luis Sieira
79,244,802
19,916,174
pytest-django: Model class sites.models.Site doesn't declare an explicit app_label
<p>There have been lots of similar questions, but most of them are irrelevant to <code>pytest</code>. Running <code>manage.py runserver</code> works correctly for me, it only fails with pytest.</p> <p>When running <code>pytest --collectonly --verbose -n0</code>, <code>pytest</code> fails with the following error:</p> <...
<python><django><testing><pytest><pytest-django>
2024-12-02 16:17:06
1
344
Jason Grace
79,244,782
3,792,852
Why is this asynchronous event loop blocked?
<p>I have a python application that handles remote control of a drone. I mainly employ traditional multithreading, but I have to support asynchronous programming too since some third party libs insist on using it. Currently, I have the following situation:</p> <p>The current flying mission is temporarily halted, which ...
<python><python-asyncio>
2024-12-02 16:10:51
1
355
user3792852
79,244,745
2,473,382
Python layer in lambda via cdk
<p><strong>TL;DR</strong>: the requirements.txt file ends up the layer, not the actual modules.</p> <p>I have a very simple Lambda, created by the cdk.</p> <pre class="lang-py prettyprint-override"><code>from aws_cdk import aws_lambda_python_alpha as aws_lambda_python from aws_cdk import aws_iam, aws_lambda, Duration, ...
<python><aws-lambda><aws-cdk><aws-lambda-layers>
2024-12-02 15:59:03
0
3,081
Guillaume
79,244,724
18,744,117
Either incorrect spacing or incorrect size using matplotlib shared y axis and aspect equal
<p><strong>Context</strong></p> <p>I'm trying to display some timing data of differing algorithms which depend on some input size and another parameter. The goal is to have <code>n</code> plots showing the various algorithms and one summary plot.</p> <p>the algorithm plots have Parameter to Execution Time axes and diff...
<python><matplotlib><plot>
2024-12-02 15:52:44
0
683
Sam Coutteau
79,244,701
9,640,384
How to get name of the script used in a job on Cloudera ML platform
<p>I want to programmatically retrieve the name of the script used in the current job that runs a python script on the Cloudera ML platform.</p> <ul> <li><code>__file__</code> magic variable doesn't work as in the background our Cloudera runtime uses ipython to execute the script</li> <li>I could get the script associa...
<python><cloudera>
2024-12-02 15:45:20
2
3,263
Mischa Lisovyi
79,244,510
2,753,095
xfce4-terminal cannot be killed
<p>From a Python program, I start <code>xfce4-terminal</code> as a subprocess. When calling <code>.terminate()</code>, xfce4-terminal is still there. Not nice. So I tried to kill it more abruptly - surprisingly, the corresponding process with corresponding PID is not there anymore... Some ancient and dangerous black ma...
<python><bash><subprocess><kill><xfce>
2024-12-02 14:49:52
1
7,998
mguijarr
79,244,459
20,591,261
How to Use Aggregation Functions as an Index in a Polars DataFrame?
<p>I have a Polars DataFrame, and I want to create a summarized view where aggregated values (e.g., unique IDs, total sends) are displayed in a format that makes comparison across months easier. Here's an example of my dataset:</p> <p>My example dataframe:</p> <pre><code>import polars as pl df = pl.DataFrame({ &quo...
<python><python-polars>
2024-12-02 14:33:51
1
1,195
Simon
79,244,353
1,600,821
Syn dependency when trying to use maturin on a Mac
<p>I am trying to follow the <a href="https://www.maturin.rs/tutorial" rel="nofollow noreferrer">quickstart of maturin</a>. However, after creating a project and copying the <code>Cargo.toml</code> over I always get this issue when I run <code>cargo build</code>.</p> <pre><code>&gt; cargo build warning: unused manifest...
<python><rust><maturin>
2024-12-02 13:56:32
1
35,145
cantdutchthis
79,244,267
2,852,466
Python code to get all the subclass objects of a given base class and call the function defined in the base class
<h2>Edit:</h2> <p>The question has been closed as duplicate to the <a href="https://stackoverflow.com/questions/328851/printing-all-instances-of-a-class">Printing all instances of a class</a></p> <p>However, there is are two differences here.</p> <ol> <li>I want to create the object of all the subclass instances.</li> ...
<python><python-3.x>
2024-12-02 13:26:47
0
1,001
Ravi
79,244,260
11,023,821
Python behave: get list of selected features in before_all
<p>For a pre-processing (cross-cutting) task, I would like to obtain a list of all selected &quot;Features&quot; already in the before_all hook. However, I only get very basic data via the Context there, like &quot;Context.config&quot;. Where, as far as I can see, only an in-memory representation of the run configurati...
<python><bdd><python-behave>
2024-12-02 13:24:22
0
1,719
Ralf Ulrich
79,244,250
880,783
How can I convert a TypeVarTuple to a ParamSpec?
<p>(I am almost certain the wording of the question does not make sense, but I have yet to find a better one.)</p> <p>I have the following code that I want to type-check:</p> <pre class="lang-py prettyprint-override"><code>from collections.abc import Callable from typing import Generic, TypeVar, TypeVarTuple C = TypeV...
<python><python-typing><python-decorators>
2024-12-02 13:19:24
1
6,279
bers
79,244,109
1,542,011
Worker thread is started multiple times when running Dash App
<p>I'm trying to (a) have a worker thread that does some background work and (b) to monitor its progress using Dash. For some reason, when executing the code, the script is loaded twice, and two worker threads end up running. The code below reproduces the situation.</p> <pre><code>import threading import time from thre...
<python><multithreading><plotly-dash>
2024-12-02 12:35:32
1
1,490
Christian
79,243,949
8,000,016
Connection error from GCP Composer (Airflow) to GCP PubSub
<p>I'm trying to subscribe to a GCP PubSub to get the messages from GCP Composer but got the following error:</p> <pre><code>airflow.exceptions.AirflowException: The conn_id `google_cloud_default` isn't defined </code></pre> <p>My DAG code is the following:</p> <pre><code>subscribe_pubsub_task = PubSubPullSensor( tas...
<python><google-cloud-platform><airflow><google-cloud-pubsub>
2024-12-02 11:45:20
1
1,264
Alberto Sanmartin Martinez
79,243,808
5,350,089
Python Tkinter Grid Column width Not expanding need First row not Scorallable
<p>I have three column with scrollbar and it needs to be expand and it should be stretched the window size but i am unable to increase the column width according to the screen size and i need top first row should need to stable that is like heading. the code is below</p> <pre><code>import tkinter as tk from tkinter imp...
<python><tkinter><scrollbar><tkinter-canvas>
2024-12-02 11:04:22
1
445
Sathish
79,243,713
7,495,742
How to replace multiple special chars in a string
<p>I am trying to replace special characters in a string, but there are different occurences and differents characters. The actual code will only replace the first special character encountered, whereas i would like to replace all special characters in the string.</p> <p>Edit : All answers i get are specific to this st...
<python>
2024-12-02 10:36:04
2
357
Garbez François
79,243,572
189,777
Agent override given tool result
<p>I am writing following agent conversation:</p> <pre><code>from autogen import ConversableAgent from typing import Annotated from model_config import get_model_config llm_config = get_model_config('GPT-4o') # Define simple calculator functions def add_numbers( a: Annotated[int, &quot;First number&quot;], b: Ann...
<python><artificial-intelligence><ms-autogen>
2024-12-02 09:42:23
0
837
Ronen
79,243,356
240,566
How do I convert a csv file to an apache arrow ipc file with dictionary encoding
<p>I am trying to use pyarrow to convert a csv to an apache arrow ipc with dictionary encoding turned on. The following appears to convert the csv to an arrow ipc file:</p> <pre><code>file = &quot;./in.csv&quot; arrowFile = &quot;./out.arrow&quot; with pa.OSFile(arrowFile, 'wb') as arrow: with pa.csv.open_csv(...
<python><pyarrow><apache-arrow>
2024-12-02 08:13:55
1
10,496
Jay Askren
79,243,348
587,587
How to connect to an Oracle7 database
<p>I have an ancient Oracle7 database (version 7.3.4.5.0) that I need to extract some data from.</p> <p>I mainly work with Python, so naturally I started looking at <a href="https://pypi.org/project/oracledb/" rel="nofollow noreferrer">oracledb</a>. However, it looks like the oldest version of oracledb only supports Or...
<python><oracle-database><python-2.x><oracle7>
2024-12-02 08:09:53
1
492
Anton Lahti
79,243,106
931,625
How to extract the parent JSON property name using JSONPath?
<p>I would like to extract the <code>content_filter_results</code> property names that have been filtered, e.g., <code>foo</code> here:</p> <pre class="lang-json prettyprint-override"><code>{ &quot;choices&quot;: [ { &quot;content_filter_results&quot;: { &quot;foo&quot;: { &quot;filtered&q...
<python><json><jsonpath>
2024-12-02 06:17:08
1
4,120
Kel Solaar
79,243,015
4,515,046
Pythonanywhere and flask app requiring Playwright, does not install
<p>I have a Flask app that uses crawl4ai, which has a dependancy on Playwright, listed here, despite not directly interacting with the browser object, we still need to install Playwright:</p> <p><a href="https://crawl4ai.com/mkdocs/basic/installation/" rel="nofollow noreferrer">https://crawl4ai.com/mkdocs/basic/install...
<python><flask><pythonanywhere>
2024-12-02 05:22:02
0
3,546
yoyoma
79,242,541
13,175,203
In Polars, how do you create a group counter / group ID?
<p>How do you get a <code>group_id</code> column like this, grouping by columns <code>col1</code> and <code>col2</code> ?</p> <div class="s-table-container"><table class="s-table"> <thead> <tr> <th>col1</th> <th>col2</th> <th>group_id</th> </tr> </thead> <tbody> <tr> <td>A</td> <td>Z</td> <td>1</td> </tr> <tr> <td>A</t...
<python><dataframe><python-polars>
2024-12-01 21:44:44
2
491
Samuel Allain
79,242,476
3,431,557
Optimising requests in my Python code using asynchronicity
<p>I’m currently attempting to optimise a Python script I wrote that makes multiple HTTP requests using the <code>aiohttp</code> library. I want to take advantage of asynchronous programming in order to handle requests concurrently, without blocking the execution of the rest of the program. I have written the following...
<python><beautifulsoup><aiohttp>
2024-12-01 21:06:30
0
637
user119264
79,242,432
298,288
await asyncio.to_thread blocks complete event loop?
<p>I am trying to create a Python program that - when triggered via a websocket - does some blocking work in a thread. I would expect my program to be able to continue to react to the stop signal also received via websocket, but it does not.</p> <p>It works when I change from <code>result = await blocking</code> to <co...
<python><python-asyncio><python-multithreading>
2024-12-01 20:40:20
0
18,394
me.at.coding
79,242,365
14,230,633
Create custom mlflow PythonModel with `predict()` function that takes no arguments
<p>I'd like to create a custom mlflow <a href="https://mlflow.org/docs/latest/_modules/mlflow/pyfunc/model.html#PythonModel" rel="nofollow noreferrer">PythonModel</a> whose predict function does not take <em>any</em> arguments. It looks like <code>mlflow.pyfunc.load_model</code> (which I use to reover the custom moel) ...
<python><mlflow><mlops>
2024-12-01 19:45:03
0
567
dfried
79,242,289
7,373,353
Azure Container-App Post-Request with PDF-Upload returns "502 Bad Gateway", "507 Insufficient Storage" or "503 Service Unavailable"
<p>I have a Azure Container-App containing an Docker Image of an Fast-API application that is supposed to alter an uploaded PDF and return back the altered PDF. On my localhost the application runs fine, however after deployment the Post-Request leads to the above responses. It says: <code>upstream connect error or dis...
<python><azure><docker><fastapi><azure-container-apps>
2024-12-01 19:05:35
1
395
leabum