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,503,307
8,541,953
GCS function: missing 1 required positional argument: 'context'
<p>I have a large GCS function that used to work, and after updating it to include a minor change I am getting the following error:</p> <blockquote> <p>TypeError: gcs_trigger() missing 1 required positional argument: 'context'</p> </blockquote> <p>For context, my entry function does have context:</p> <pre><code>def gcs...
<python><google-cloud-platform><google-cloud-functions><google-cloud-storage>
2025-03-12 10:34:42
0
1,103
GCGM
79,503,227
266,375
In strawberry, how do I make a strawberry.input non-nullable but optional in an update mutation
<p>I have two fields in an input:</p> <pre class="lang-py prettyprint-override"><code>@strawberry.input class UserUpdateInput: name: str | None = strawberry.UNSET description: str | None = strawberry.UNSET </code></pre> <p><code>name</code> - in the backend database - is <strong>not nullable</strong>. <code>d...
<python><graphql><strawberry-graphql>
2025-03-12 10:03:45
2
3,662
Matthew Wilcoxson
79,503,147
13,672,396
Auto signing in docusign
<p>I have been trying to place signature image directly without having the user to sign it. I have used sign here tabs and added stamp tabs in it. But in the received document, it is still expecting the user to manually sign it.</p> <p>I have researched enough,I am not finding any resource which solves my problem.</p> ...
<python><docusignapi><docusign-sdk>
2025-03-12 09:32:31
1
347
srinivast6
79,502,861
354,051
Creating a masked image with smooth borders using opencv and numpy
<p><a href="https://i.sstatic.net/8MyDdHTK.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/8MyDdHTK.png" alt="smooth mask" /></a></p> <p>I'm trying to create a masked image (smooth rounded borders of 10x10 pixels) as shown here (created in photoshop) using opencv and numpy. Here is my code</p> <pre class...
<python><opencv><mask>
2025-03-12 07:14:49
1
947
Prashant
79,502,746
7,498,328
DeprecationWarning with groupby().apply(): How to properly exclude grouping column in pandas 2.2+
<p>I'm on Pandas <code>2.2.1</code> with Python <code>3.9.19</code> trying to sample 5 rows per group using <code>groupby().apply()</code>, but I keep getting this DeprecationWarning in pandas 2.2+:</p> <pre><code>DeprecationWarning: DataFrameGroupBy.apply operated on the grouping columns. This behavior is deprecated...
<python><pandas><group-by>
2025-03-12 05:59:57
1
2,618
user321627
79,502,550
1,708,779
Python-Selenium Remote Connection to Dockerized Selenium Server
<p>I'm trying to connect to a Dockerized version of Selenium on the same host within one Python script. This is running on a server, so this is necessarily headless.</p> <p>I'd like to use the Firefox driver. The Docker container seems to be created and runs fine, however I keep getting &quot;the connection reset by pe...
<python><docker><selenium-webdriver>
2025-03-12 03:01:55
1
1,690
GNUser
79,502,302
1,013,346
Serve NetCDF via WCS protocol with Python and MapServer
<p>I'd like to serve a NetCDF resource via WCS using MapServer Python bindings. I borrowed a mapfile form the MapServer test suite <a href="https://github.com/MapServer/MapServer/blob/main/msautotest/wxs/wcs_netcdf_input_output.map" rel="nofollow noreferrer">wcs_netcdf_input_output.map</a> for which I adapted the <code...
<python><netcdf><mapserver><wcs>
2025-03-11 23:02:51
0
1,367
epifanio
79,502,218
1,747,834
How to cast to long depending on Python version?
<p>I'm dealing with numbers, that may be too large for <code>int</code> as understood by Python-2.x, so my code's been casting them to <code>long</code>.</p> <p>In Python-3.x there is no such thing, and one is simply supposed to use <code>int</code>. However, the code needs to work with both Python-2 and 3 (for as long...
<python><python-2.x>
2025-03-11 21:51:12
1
4,246
Mikhail T.
79,502,038
6,467,736
Error trying to install Python 3.13 alongside existing Python 3.9 installation - Windows 10
<p>Windows 10 system. I have Python 3.9 installed in a user (non-admin) account. I'm trying to install Python 3.13 alongside 3.9. During install, I select 'Add python.exe to PATH' and select 'Customize installation', where all options are enabled on first screen except for 'for all users (requires admin privileges)'. O...
<python><python-3.x><registry>
2025-03-11 20:25:20
1
427
jub
79,502,011
940,490
Type coercion stops working after an invalid input in `pandera`
<p>I am new to <code>pandera</code> and really loving it. I encountered a peculiar behavior in one example <a href="https://pandera.readthedocs.io/en/stable/dataframe_models.html#basic-usage" rel="nofollow noreferrer">from the package's side</a>. I am using Python 3.9 and <code>pandera==0.22.1</code>. Copying the snipp...
<python><pandera>
2025-03-11 20:13:52
0
1,615
J.K.
79,501,940
8,188,120
PayFast signature (python): generated signature does not match submitted signature
<p>I am trying to submit a PayFast payment using the API tools, in python rather than php (the docs recommended approach).</p> <p>I am generating a signature like so:</p> <pre class="lang-py prettyprint-override"><code>import hashlib import urllib.parse def generate_signature(data: dict, passphrase: str) -&gt; str: ...
<python><hash><payment-gateway><urlencode><payfast>
2025-03-11 19:39:53
1
925
user8188120
79,501,764
676,001
Why is Poetry complaining that `name` isn't set in pyproject.toml?
<p>I set up a new Python Poetry project with <code>poetry init</code>. I'm not creating a package, so I added this to my <code>pyproject.toml</code>:</p> <pre class="lang-ini prettyprint-override"><code>[tool.poetry] package-mode = false </code></pre> <p>The <a href="https://python-poetry.org/docs/basic-usage/#operatin...
<python><python-poetry>
2025-03-11 18:22:39
1
11,028
bertday
79,501,731
20,591,261
Transforming polars Dataframe to Nested JSON Format
<p>I have a dataframe that contains a product name, question, and answers. I would like to process the dataframe and transform it into a JSON format. Each product should have nested sections for questions and answers.</p> <p>My dataframe:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl df = pl....
<python><python-polars>
2025-03-11 18:04:41
2
1,195
Simon
79,501,664
1,185,790
Palantir Foundry REST API endpoint for dataset queries?
<p>I would like to be able to query a dataset via Palantir Foundry's REST API, but keep getting a <code>404</code> response code. The <a href="https://www.palantir.com/docs/foundry/api/v2/general/overview/introduction/" rel="nofollow noreferrer">documentation</a> does not appear to have any information about how to do ...
<python><python-requests><palantir-foundry><palantir-foundry-api>
2025-03-11 17:41:38
1
723
baobobs
79,501,635
23,260,297
pyinstaller FileNotFoundError when compiling exe
<p>I am trying to compile an exe but It keeps failing with a FileNotFoundError:</p> <pre><code>Traceback (most recent call last): File &quot;C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python39_64\lib\runpy.py&quot;, line 197, in _run_module_as_main return _run_code(code, main_globals, None, File &quo...
<python><pyinstaller>
2025-03-11 17:32:52
0
2,185
iBeMeltin
79,501,620
2,015,882
Unable to load module when wheel installed in jupyter
<p>I have developed a python module with C++ and nanobind. I am using the stable ABI and compiling the wheel for python 3.12</p> <p>I am building a wheel using cibuildwheel <code>cibuildwheel --output-dir wheelhouse</code></p> <p>I have created a virtual environment and installed jupyter and ipykernel</p> <pre><code>py...
<python><jupyter><ipython><nanobind>
2025-03-11 17:26:48
0
1,757
jjcasmar
79,501,381
1,132,423
No module named 'matplotlib' in visual studio 2022 python project
<p>I am using Windows. I executed the below commands on the command prompt:</p> <pre><code>python -m pip install matplotlib. pip3 install matplotlib </code></pre> <p>But VS 2022 is not recognizing the matplotlib.</p> <p>Below is the code:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np xpoints = np....
<python><matplotlib><visual-studio-2022>
2025-03-11 15:57:09
0
1,806
Aditya Bokade
79,501,302
10,658,339
How to plot a processing message in power Bi visual
<p>I'm developing a visual using Python within Power BI, but due to the large dataset size, processing takes some time.</p> <p>How can I display a message or a loading symbol to inform users that the graph is temporarily blank because the Python script is still running? I attempted using the print statement within the ...
<python><matplotlib><powerbi><powerbi-custom-visuals>
2025-03-11 15:35:27
0
527
JCV
79,501,263
1,194,864
Calculate the gradient with respect to attention but also the FFN layers for a pre-trained LLMs
<p>I would like to return the gradient with respect to specific layers and the FFN layer in the Transformer architecture of pre-trained LLMs from the hugging-face model. Is that even possible?</p> <p>I am working with the code of this <a href="https://github.com/kristosh/xAI/blob/main/attn_vizualizations.py" rel="nofol...
<python><pytorch><nlp><large-language-model>
2025-03-11 15:21:57
0
5,452
Jose Ramon
79,501,206
3,873,799
Pyside6-designer: export Python code of custom (promoted) widget
<p>I've created the design for a widget in PySide6 GUI.<br /> This <code>MyCustomWidget</code> is defined in my main UI, which contains many other things.<br /> <em>Please consider that this custom widget can be quite complex and have many sub-widgets</em>, and I find it much more convenient to design it in the UI.</p>...
<python><qt><widget><pyside6><pyside6-gui>
2025-03-11 14:59:36
2
3,237
alelom
79,501,178
1,194,864
Store images instead of showing in a server
<p>I am running the code found on this <a href="https://captum.ai/tutorials/Llama2_LLM_Attribution" rel="nofollow noreferrer">site</a> in my server and I would like to store images instead of showing them since I have connected remotely with an ssh connection to my <code>server</code> via an <code>SSH</code> connection...
<python><nlp><large-language-model>
2025-03-11 14:50:31
1
5,452
Jose Ramon
79,501,083
8,296,096
What is the programming construct in Python of passing some arguments in front of a constructor call? How to interpret parameters passed to an object?
<p>In the below code line, if I am not mistaken, we are creating the object of the class <strong>layer.Dense</strong> from <strong>tensorflow.keras</strong> and then passing some arguments to the object in the parethesis. <code> x = layers.Dense(128 * 16 * 16)(inputs)</code>. What is this programming construct in Pytho...
<python><oop><keras><language-construct>
2025-03-11 14:22:29
1
434
Sushodhan V
79,500,975
633,439
Finding coprime numbers
<p>I have following snippet which finds numbers which are not coprime to 20. But, I want to achieve the opposite, i.e., printing the coprime numbers of 20. It should be achieved with something like <code>(((i%j)!==0) &amp; ((z%j)!==0))</code>. I am new to Python and hence not sure why this was not working. Can someone ...
<python>
2025-03-11 13:48:54
3
1,107
kzs
79,500,961
6,734,243
How to display a dash leaflet colorbar horizontally?
<p>I'm buiding an application in dash that contains a map. This map is build using the <a href="https://github.com/emilhe/dash-leaflet" rel="nofollow noreferrer">dash-leaflet</a> lib. I would like to have the colorbar displayed horizontally instead of vertically, is it possible and if yes what should I add to my code ?...
<python><plotly-dash><dash-leaflet>
2025-03-11 13:43:27
1
2,670
Pierrick Rambaud
79,500,932
1,826,066
Custom Python StrEnum auto() function that returns class name and variable
<p>I want to define column names for my data frame in a single file, using <code>dataclass</code> and <code>enum</code>.</p> <p>I have the current code with help of ChatGPT that does not achieve what I want, but might be a starting point</p> <pre class="lang-py prettyprint-override"><code> from enum import EnumMeta, St...
<python><enums>
2025-03-11 13:32:04
1
1,351
Thomas
79,500,909
16,383,578
What is the fastest way to generate all n-bit gray codes using NumPy?
<p>My goal is to create images using gray codes, an example would be this:</p> <p><a href="https://i.sstatic.net/ObiBx418.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/ObiBx418.png" alt="enter image description here" /></a></p> <p>It is all modulo 64 groups in gray codes in polar form.</p> <p>Now of co...
<python><arrays><numpy><gray-code>
2025-03-11 13:23:02
4
3,930
Ξένη Γήινος
79,500,858
10,452,700
Best Practices for Preserving Hashed Identifiers in Filenames After Character Sanitization for Accurate Merging
<p>We are working with a hashed identifier column (<code>vmid</code>) in a Pandas DataFrame, which has been sanitized to remove special characters due to CSV storage constraints. The sanitization function we used replaces disallowed characters with an underscore (<code>_</code>):</p> <pre class="lang-py prettyprint-ove...
<python><pandas><hash><cosine-similarity><html-escape-characters>
2025-03-11 13:05:50
0
2,056
Mario
79,500,760
3,133,018
Accessing a sibling inner class in initialiser
<p>Consider the following code, if you will:</p> <pre class="lang-py prettyprint-override"><code>class ParentService: BASE_DIR = '/some/path' class Results(str, Enum): RESULT1 = 'ResultOne.xlsx' RESULT2 = 'ResultTwo.pdf' def file_path(self) -&gt; str: return os.pat...
<python><python-class>
2025-03-11 12:33:16
0
496
zkvvoob
79,500,718
6,699,447
How to include first matching pattern as a column
<p>I have a dataframe <code>df</code>.</p> <pre><code>&gt;&gt;&gt; import polars as pl &gt;&gt;&gt; &gt;&gt;&gt; &gt;&gt;&gt; df = pl.DataFrame({&quot;col&quot;: [&quot;row1&quot;, &quot;row2&quot;, &quot;row3&quot;]}) &gt;&gt;&gt; df shape: (3, 1) ┌──────┐ │ col │ │ --- │ │ str │ ╞══════╡ │ row1 │ │ row2 │ │ row3...
<python><python-3.x><python-polars>
2025-03-11 12:18:24
2
25,841
user459872
79,500,374
17,500,571
Inconsistent API Data Size When Splitting a 4-Year Dataset into Various Time Chunks (Thingsbaord)
<p>I'm working with a 4-year dataset that I split into smaller time intervals (chunks) to send API requests to Thingsboard. I experimented with different chunk sizes—3 hours, 6 hours, 12 hours, and 24 hours. Since the overall time period remains the same (4 years), I expected the total amount of data retrieved to be co...
<python><fastapi><thingsboard>
2025-03-11 10:15:05
0
364
Foxbat
79,500,273
8,384,910
Python shelve downgrade to read-only mode
<p>If multiple executions are reading from the same shelve, I assume that they must open it in read-only mode so that there are no &quot;locked file&quot; errors.</p> <p>I'm using <code>shelve</code> as a cache, which is intended to be populated on the first run. When the code runs, it checks the integrity of the cache...
<python><shelve>
2025-03-11 09:48:07
1
9,414
Richie Bendall
79,500,233
14,855,041
How to resolve type checking error in Django when accessing Serializer.validated_data
<p>I'm encountering a type checking error in VSCode with Pylance (pyright) when accessing <code>serializer.validated_data[&quot;code&quot;]</code> in a Django project. The errors are:</p> <ul> <li><code>&quot;__getitem__&quot; method not defined on type &quot;empty&quot; Pylance</code></li> <li><code>Object of type &qu...
<python><django><python-typing><pylance><pyright>
2025-03-11 09:35:39
1
366
Farhad
79,500,016
2,604,247
What Are the Correct Versions of Tensorflow and Tensorflow Agents to Work with On Ubuntu 24.04?
<p>I remember having worked with tensorflow agents (for reinforcement learning) more than three years back, on an Ubuntu 18.04 machine. Of course, all the dependencies, including python versions have been upgraded since then, and it seems with a lot of breaking changes.</p> <p>So now that I need to build a custom <code...
<python><tensorflow><pip><dependency-management><tf-agent>
2025-03-11 08:05:46
1
1,720
Della
79,499,882
8,876,025
Claude Sonnet can call tool only once at a time
<p>I'm testing a function calling capability of Claude Sonnet 3.7, but it can only call the tool once before it responds to the client.</p> <p>Here is my code:</p> <pre><code>from llama_index.core.program.function_program import FunctionCallingProgram from llama_index.llms.anthropic import Anthropic from llama_index.co...
<python><llama-index><claude>
2025-03-11 06:55:40
1
2,033
Makoto Miyazaki
79,499,687
6,011,193
In vscode, how to disable debug error breakpoints
<p>When debug python, vscode always auto focus err line and popup err, but I hope disable the feature like intellij idea disable &quot;breakpoints &gt; error breakpoint&quot;</p> <p>When debug python, vscode always auto focus err line and popup err, but I hope disable the feature like intellij idea disable &quot;breakp...
<python><visual-studio-code><debugging>
2025-03-11 04:52:36
1
4,195
chikadance
79,499,568
4,570,628
Cython can't link external C++ library
<p>Part of a Python library I'm working on is written in Cython. I need to use the <a href="https://github.com/linbox-team/linbox/tree/master/linbox" rel="nofollow noreferrer">LinBox</a> C++ library (which depends on the <a href="https://github.com/linbox-team/givaro" rel="nofollow noreferrer">Givaro</a> library). Just...
<python><c++><compilation><cython>
2025-03-11 02:55:06
1
477
apizzimenti
79,499,322
8,357,735
YOLOv11 Model Converted to TFLite Not Producing Correct Output in TensorFlow
<p>I'm training an ALPR detection model using the dataset from <a href="https://universe.roboflow.com/alpr-12yby/alpr-transformed/" rel="nofollow noreferrer">Roboflow ALPR</a> with YOLOv11, converted to TFLite using:</p> <pre><code>import ultralytics as yolo !yolo detect export model=/content/runs/detect/yolov11_anpr/w...
<python><tensorflow><artificial-intelligence><data-science><yolo>
2025-03-10 22:54:14
1
320
farid
79,499,230
1,306,784
Circular Dependencies with Response Model
<p>I'm trying to leverage <a href="https://sqlmodel.tiangolo.com/tutorial/relationship-attributes/read-relationships/" rel="nofollow noreferrer">SQLModel &quot;Relationships&quot;</a> in a FastAPI app. Specifically, I want to break my model classes out into separate files.</p> <p>I found the official SQLModel documenta...
<python><fastapi><sqlmodel>
2025-03-10 21:46:00
1
4,801
Xedni
79,499,210
9,415,280
tensorflow dataset loop endless will model.predict
<p>I use this code to setup my dataset for trainning and predict:</p> <pre><code>train_dataset = train_dataset.batch(train_batch_sz) train_dataset = train_dataset.repeat().prefetch(5) test_dataset_sim = test_dataset test_dataset = test_dataset.batch(test_batch_sz) test_dataset = test_dataset.repeat().prefetch(5) </cod...
<python><tensorflow><dataset><tensorflow-datasets>
2025-03-10 21:38:06
1
451
Jonathan Roy
79,499,140
12,158,757
How to easily modify the number of neurons of a certain layer in a Tensorflow neural network?
<p>In <a href="/questions/tagged/tensorflow" class="s-tag post-tag" title="show questions tagged &#39;tensorflow&#39;" aria-label="show questions tagged &#39;tensorflow&#39;" rel="tag" aria-labelledby="tag-tensorflow-tooltip-container" data-tag-menu-origin="Unknown">tensorflow</a>, given a model <code>h = Model(input_l...
<python><tensorflow><keras><deep-learning>
2025-03-10 20:56:26
0
105,741
ThomasIsCoding
79,499,064
4,992,910
loading a dataset with datasets.load_dataset is hanging
<p>I'm trying to load some data using datasets.load_datasets. It runs correctly on a head node. The issue is happening on a slurm node. I'm using a conda env with datasets installed.</p> <p>When I run on head node with the conda env active, this command works:</p> <pre><code>python -c &quot;from datasets import load_da...
<python><dataset><torch>
2025-03-10 20:01:44
1
454
ate50eggs
79,499,056
11,063,709
How can I apply member functions of a list of objects across slices of a JAX array using vmap?
<p>I have a list of a objects, each of which has a function to be applied on a slice of a <code>jax.numpy.array</code>. There are <code>n</code> objects and <code>n</code> corresponding slices. How can I vectorise this using <code>vmap</code>?</p> <p>For example, for the following code snippet:</p> <pre><code>import ja...
<python><jax>
2025-03-10 19:58:21
1
1,442
Warm_Duscher
79,498,948
5,678,653
How can I derive names from numeric properties using numpy?
<p>My work is currently to do with functions and properties of the unit Octahedron. While it is not central to the question here, it may help with the context.</p> <p>A unit octahedron has side lengths of <code>√2</code>, and it's six vertices are at <code>(±1,0,0),(0,±1,0),(0,0,±1)</code></p> <p>As I am using this to ...
<python><numpy><computational-geometry>
2025-03-10 19:10:12
1
2,248
Konchog
79,498,680
72,437
Performing Collection Queries Within a Transaction: Python vs. Swift
<p>In Python, we can perform queries on collections within a transaction using the following code snippet:</p> <pre><code>def write_upload_success(filename: str, uid: str, doc_id: str) -&gt; DocumentReference: db = firestore.client() transaction = db.transaction() @firestore.transactional def transact...
<python><swift><firebase><google-cloud-firestore>
2025-03-10 17:08:57
1
42,256
Cheok Yan Cheng
79,498,670
7,959,614
Vectorize ordinal regression using numpy and scipy special
<p>I have a function that calculates the probability of belonging to category k ~ {1, 2, ..., K} based on <code>eta</code> and the cutoff points, <code>c</code> between the categories.</p> <pre><code>import numpy as np import scipy.special as ss def pmf(K: int, eta: np.ndarray, c: np.ndarray) -&gt; np.array: &quo...
<python><numpy><scipy>
2025-03-10 17:02:32
1
406
HJA24
79,498,634
3,336,423
Loading standard C++ library makes ctypesgen's Python binding crash if library is not loaded first
<p>I'm experiencing a wierd crash when trying to run a C++ library entry point from a Python script. I'm under Windows 10.</p> <p>I isolated this into a very simple example.</p> <p>Here is my C++ code:</p> <p><strong>sdetests_lib_bind_python.h:</strong></p> <pre><code>#pragma once #ifdef SDETESTS_LIB_BIND_PYTHON_EXPOR...
<python><c++><ctypes>
2025-03-10 16:50:57
1
21,904
jpo38
79,498,617
2,039,866
Error from Pycharm: Expected type 'SupportsIndex | slice', got 'str' instead
<p>My input file, infile is as follows:</p> <pre><code>NUMBER,SYMBOL 1,AAPL 2,MSFT 3,NVDA </code></pre> <p>Here is my code:</p> <pre><code>import csv infile = &quot;stock-symbols-nasdaq-SO.csv&quot; with open(infile, encoding='utf-8') as csvfile: reader = csv.DictReader(csvfile) # Read CSV as a dictionary fo...
<python><pycharm><python-typing>
2025-03-10 16:44:36
1
770
Charles Knell
79,498,527
1,670,583
Read text from file while keeping byte offset
<p>Using Python, I want to read text from a (utf-8 encoded) text file, but at the same time need to know the start and end position of each character in the file (in bytes). As there might be multi-byte characters, this isn't a 1:1 mapping.</p> <p>I can see that reading through the file character by character and keepi...
<python>
2025-03-10 15:52:04
1
375
incaseoftrouble
79,498,129
452,102
Should we close connections during program shutdown?
<p>We have long-lived connections that recreates itself when broken:</p> <pre><code>class RMQ(): def __init__(self): self.connection = ... def recreate(self): self.connection = ... def publish(self): &quot;&quot;&quot;All methods have retry logic to restore connection.&quot;&quot;&...
<python><rabbitmq><pika>
2025-03-10 13:23:54
1
22,154
Nishant
79,497,967
3,156,085
Is there a callable for generating ids with `pytest.fixture(param=...)` the same way it would be generated with `pytest.mark.parametrize()`?
<p>I'm using parametrized fixtures but I don't find the way ids are generated practical.</p> <p>I'd like to fall back on the way it's generated when using <code>pytest.mark.parametrize</code>.</p> <p>I've seen that it's possible to provide a callable as the <code>ids</code> keyword argument in <code>pytest.fixture</cod...
<python><pytest>
2025-03-10 12:14:58
1
15,848
vmonteco
79,497,914
21,294,350
How do conditional expressions group from right to left?
<p>I checked <a href="https://docs.python.org/3/reference/expressions.html#operator-precedence" rel="nofollow noreferrer">python operator precedence</a> (<a href="https://docs.python.org/3/reference/grammar.html" rel="nofollow noreferrer">This one grammar</a> is more detailed and more appropriate for the actual Python ...
<python><python-3.x><conditional-operator><operator-precedence>
2025-03-10 11:54:56
1
782
An5Drama
79,497,742
777,275
Python openpyxl issue when save xlsx file
<p>I'm using Walmart template file to upload bulk listings to their site. The template only allow 10.000 rows, so I have to split them into multiple files. The solution I'm using is to copy the original xlsx file and use new name for the file.</p> <p>Here's the code for copying file</p> <pre><code>newWMFile = 'c:\\User...
<python><openpyxl><xlsx>
2025-03-10 10:45:25
0
343
kenvu
79,497,737
16,611,809
Is a `ROUTEID` set by `Header add Set-Cookie`a locally stored cookie?
<p>I have an Apache2 server running as reverse proxy and behind this proxy there are multiple workers running a local shiny for python server. To always use the same worker for one session I use these code lines in my Apache2 config:</p> <pre><code>(...) Header add Set-Cookie &quot;ROUTEID=.%{BALANCER_WORKER_ROUTE}e; ...
<python><apache2><py-shiny>
2025-03-10 10:42:43
0
627
gernophil
79,497,724
8,771,082
Index Pandas with multiple boolean arrays
<p>Using numpy, one can subset an array with one boolean array per dimension like:</p> <pre><code>In [10]: aa = np.array(range(9)).reshape(-1, 3) In [11]: aa Out[11]: array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) In [12]: conditions = (np.array([True, True, False]), np.array([True, False, True])) In [13]: a...
<python><pandas>
2025-03-10 10:37:34
1
449
Anton
79,497,618
624,734
Send signal (SIGINT) to a C sub-process
<p>I use some Python bindings to a C++ based library which starts some processes.</p> <p>I have the problem that while the execution is within that code-path it does not &quot;feel&quot; a SIGINT, but as soon that context is finished, the Python process the SIGINT and use my defined handler. What is the proper procedur...
<python><signals>
2025-03-10 09:54:32
2
311
Adrian Sevcenco
79,497,511
2,487,988
Can't eliminate floating point errors with Decimal
<p>I'm using Decimal everywhere to try and get rid of floating point errors, but it's persisting.</p> <p>Here's my test code</p> <pre><code>from decimal import Decimal Demands = [9,12,8,11] fM = Decimal(10) alpha = Decimal(.01) fM = Decimal((1 - Decimal(alpha)) * fM + Decimal(alpha) * Demands[(1) % 4]) print(fM) <...
<python><floating-point><decimal>
2025-03-10 09:10:56
1
503
Jeff
79,497,191
242,042
When using mysql.connector.aio how do we enable connection pooling (assuming it is needed)?
<p>I am trying to port my old mysql connector code to use the <a href="https://dev.mysql.com/doc/connector-python/en/connector-python-asyncio.html" rel="nofollow noreferrer">asyncio libraries provided by MySQL</a>. When I tried to run it, it said it didn't recognize the <code>pool_name</code> and <code>pool_size</code...
<python><python-asyncio><mysql-connector>
2025-03-10 06:37:21
1
43,097
Archimedes Trajano
79,497,170
16,452,929
Generate 4 random numbers between -1.0 and 1.0 such their sum is 1 using python
<p>I am trying generate 4 random numbers between -1.0 and 1.0 such that their sum is 1 using python. I initially looked at the dirichlet function in numpy but that only works for positive numbers. One other way I can think of is:</p> <pre><code>def generate_random_numbers(): numbers = np.random.uniform(-1.0, 1.0, 3) ...
<python><numpy><random>
2025-03-10 06:24:36
4
517
CS1999
79,497,118
243,031
pydantic get field alias based on field value with python object
<p>I have pydantic model as below.</p> <pre><code>from typing import Annotated from bson import ObjectId from pydantic import Field from pydantic import EmailStr from pydantic import BaseModel from pydantic import BeforeValidator from pydantic import ConfigDict from pydantic import AwareDatetime from pydantic import f...
<python><serialization><deserialization><pydantic>
2025-03-10 05:53:10
0
21,411
NPatel
79,496,903
1,088,856
How to Call Python Code from Blazor WebApp
<p>I am trying to run a python script from a Blazor WebApp using pythonnet. The python script is located in the project but the PyModule.Import call to the script throws an error saying the module can't be found.</p> <pre><code>Runtime.PythonDLL = @&quot;C:\Users\homepc\AppData\Local\Programs\Python\Python312\python312...
<python><asp.net-core><blazor><python.net><blazor-webapp>
2025-03-10 02:44:56
1
963
physics90
79,496,846
7,238,426
How to use `@pytest.mark.parametrize` and include an item for the default mock behavior?
<p>I am creating a parameterized Mock PyTest to test API behaviors. I am trying to simplify the test code by testing the instance modified behavior, e.g. throw and exception, and the default behavior, i.e. load JSON from file vs. calling REST API.</p> <p>I do not know how to add an array entry to represent the &quot;de...
<python><mocking><pytest>
2025-03-10 01:27:22
1
623
PieterV
79,496,831
1,054,424
How to efficiently plot real-time rolling data with PyQtGraph
<p>What is an efficient method for plotting data with <code>pyqtgraph</code> for a rolling plot when samples arrive one at at time from an upstream process?</p> <p>Based on some experimentation, plotting each sample as it comes in is very slow. A workaround is to buffer the data prior to plotting.</p> <p>Below is some ...
<python><pyqt5><pyqtgraph>
2025-03-10 01:10:21
1
1,498
BigBrownBear00
79,496,750
3,696,153
Plugin - passing globals to a module
<p>I have Python Module system that I am trying to create.</p> <p>I have followed a previous example and it seems to work sell, except one thing.</p> <p>The basic 'manager' does the following:</p> <pre><code> NAME_PY='myplugin.py' def load_plugin( self, dirname ): filename = os.path.join( dirname, NAME_PY ) ...
<python><plugins><global>
2025-03-09 23:17:42
1
798
user3696153
79,496,711
6,440,589
OpenCV: understanding the filterByArea parameter used in SimpleBlobDetector
<p>I am trying to detect a large stain using OpenCV's <code>SimpleBlobDetector</code> following <a href="https://stackoverflow.com/a/54410195/6440589">this SO answer</a>.</p> <p>Here is the input image:</p> <p><a href="https://i.sstatic.net/nSs0aS1P.png?s=256" rel="nofollow noreferrer"><img src="https://i.sstatic.net/n...
<python><opencv><area>
2025-03-09 22:34:57
1
4,770
Sheldon
79,496,431
8,830,612
Azure ML - can't use the model path
<p>The ultimate goal - <strong>to publish my model to production</strong>. After a lot of iterations and not explicit errors I decided to do line by line check. I'm using <strong>Azure ML Notebooks</strong>.</p> <p>Everything is working until I try to deploy the model to an Endpoint. I concluded that the root cause lie...
<python><azure><azure-machine-learning-service><azureml-python-sdk>
2025-03-09 18:57:36
1
518
default_settings
79,496,388
242,042
How do I find classes that are decorated by a given decorator in Python?
<p>I am trying to do something like SpringBoot @Component scan to search for classes that are decorated with Temporal <code>@worfklow.defn</code> and <code>@activity.defn</code> so I can automatically register them to the worker without explicit plumbing.</p> <p>Do Python decorators provide a facility for a lookup like...
<python><python-decorators>
2025-03-09 18:22:54
1
43,097
Archimedes Trajano
79,496,351
2,057,516
How to include code-block headers in sticky-scrolling for python code?
<p>Is there a way to tell VS Code to include every code block header in the sticky scrolling feature when scrolling through python code? Currently, it only does class and method definitions. I'd like it to include loops, conditionals, try, etc blocks.</p> <p>For example, it would be nice to see everything between lin...
<python><visual-studio-code><scroll><settings><sticky>
2025-03-09 17:52:27
1
1,225
hepcat72
79,496,308
6,423,456
How can I handle initial settings with Pydantic Settings?
<p>I have an app that is largely configured by environment variables. I use Pydantic Settings to define the settings available, and validate them. I have an initial set of settings, and the regular app settings.</p> <p>The initial settings are ones that should not fail validation, and contain essential settings for sta...
<python><pydantic-v2><pydantic-settings>
2025-03-09 17:29:29
2
2,774
John
79,496,246
22,213,065
How to Capture a Sequence of High-Quality PDF Frames from a Website (Without Screen Recording)?
<p>In Firefox, I can take very high-quality screenshots of a webpage by using Ctrl + P and saving the page as a PDF. This method preserves the text, images, and code in excellent resolution.</p> <p>Now, I have created a movable bar chart race in Flourish Studio and want to convert it into a high-quality video. However,...
<python><firefox><playwright><screen-capture>
2025-03-09 15:52:02
1
781
Pubg Mobile
79,496,136
6,293,038
plotting vertical lines on pandas line plot with multiindex x axis
<p>I have a dataframe whose index is a multiindex where axes[0] is the date, and axis[1] is the rank. Rank starts with 1 and ends at 100, but there can be a variable number of ranks in between as below. Here are the ranks</p> <pre><code>dx = pd.DataFrame({ &quot;date&quot;: [ pd.to_datetime('2025-02-24'), p...
<python><pandas><dataframe><matplotlib><multi-index>
2025-03-09 15:24:22
1
1,105
dayum
79,496,120
2,572,994
Importing umap hangs and exits silently
<p>I am running some application code that relies on <code>umap</code>. However, when trying to import the module, it simply hangs and suddenly dies without any error message:</p> <pre class="lang-py prettyprint-override"><code>print(&quot;Importing umap&quot;) import umap print(&quot;Imported umap&quot;) # Never reach...
<python><umap>
2025-03-09 15:12:30
0
4,041
Ivaylo Toskov
79,496,102
1,719,931
SQLAlchemy use "IN" to select pairwise correspondence
<p>Consider the following DB:</p> <pre><code>from sqlalchemy import String, select, create_engine from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, Session class Base(DeclarativeBase): pass class User(Base): __tablename__ = &quot;user_account&quot; name: Mapped[str] = mapped_column(String...
<python><sqlite><select><sqlalchemy><sql-in>
2025-03-09 14:59:55
1
5,202
robertspierre
79,496,092
5,688,082
Python's predicate composition
<p>I would like to implement something similar to this OCaml in Python:</p> <pre class="lang-ml prettyprint-override"><code>let example = fun v opt_n -&gt; let fltr = fun i -&gt; i mod 2 = 0 in let fltr = match opt_n with | None -&gt; fltr | Some n -&gt; fun i -&gt; (i mod n = 0 &amp;&amp; flt...
<python><functional-programming><composition>
2025-03-09 14:55:27
1
1,668
Denis
79,495,685
605,156
gpg.import_keys() is not working in python virtual environment
<p>I'm running this piece of code to encrypt a file using PGP public key.</p> <pre><code>import gnupg def pgp_encrypt(pub_file, out_file): gpg = gnupg.GPG() with open(pub_file, 'rb') as pgp_pub_key: public_key_data = pgp_pub_key.read() # import_keys_file() is NOT used as the key # eventually...
<python><python-3.x><virtualenv><gnupg>
2025-03-09 09:23:34
1
2,261
MacUsers
79,495,237
15,412,256
Cumulative Elementwise Sum by Python Polars
<p>I have a weight vector:</p> <pre class="lang-py prettyprint-override"><code>weight_vec = pl.Series(&quot;weights&quot;, [0.125, 0.0625, 0.03125]) </code></pre> <p>And also a DataFrame containing up to <code>m</code> variables. For simplicity, we will only have two varaibles:</p> <pre class="lang-py prettyprint-overr...
<python><python-polars>
2025-03-09 00:33:44
2
649
Kevin Li
79,494,929
722,036
Can't get my Flask app to run as a bot in Azure Web App Services
<p>I'm working on a chat bot and I want to deploy it to Azure Web App Services. The bot receives HTTP requests from the messaging platform, and it also runs in a while loop checking something it's designed to notify about.</p> <p>The HTTP part is handled by Flask and it works fine. But I can't get the loop to work alon...
<python><python-3.x><azure><flask><azure-web-app-service>
2025-03-08 19:37:54
0
5,341
ᴍᴇʜᴏᴠ
79,494,797
4,703,291
How to deduplicate index of Dask dataframe?
<p>In the code provided below, I am trying to merge two Dask dataframes</p> <pre><code>def merge_with_aggregated_4(trans_ddf, agg_ddf): # First join condition: Adjust based on minutes trans_ddf[&quot;base_hour&quot;] = trans_ddf[&quot;column4&quot;].dt.floor(&quot;h&quot;) trans_ddf['adjusted_hour'] = tran...
<python><dask><dask-dataframe>
2025-03-08 17:51:10
0
463
Oleg
79,494,676
16,765,223
Run EXE software using App in Windows IIS
<p>I hosted my Django app on Windows IIS in Windows Server 2022 Standard</p> <p>But my application has a feature that opens software (.exe) and run specific user tasks provided in the request of the site.</p> <p>For example, a user provides some input from my site, and then it processes it with my app by opening softwa...
<python><django><iis><permissions><windows-server>
2025-03-08 16:26:27
1
823
MDEV
79,494,538
16,383,578
Fastest way to find all permutations of 0, 1 of width n without itertools in pure Python?
<p>What is an efficient way to get the same result as <code>list(product((0, 1), repeat=n))</code> without using itertools and any imports?</p> <p>For example, given n=3, the output be: <code>[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]</code> in exactly the same order.</p> <...
<python><algorithm><binary><permutation>
2025-03-08 14:43:31
3
3,930
Ξένη Γήινος
79,494,450
10,714,490
WHY is there a TabError in Python?
<p>I'm not asking WHAT is TabError nor HOW to fix TabError, I'm asking <strong>WHY</strong>.</p> <p>I completely understand a <code>TabError</code> means <code>inconsistent use of tabs and spaces in indentation</code> exactly as it prints. I mean, the Python Interpreter <em>should</em> be able to just simply convert ea...
<python>
2025-03-08 13:24:28
2
668
KumaTea
79,494,345
16,383,578
How to count the first N natural numbers in binary?
<p>This may seem trivial but I haven't found a good solution to the problem. I have even found this: <a href="https://stackoverflow.com/questions/12325868/generate-all-n-bit-binary-numbers-in-a-fastest-way-possible">generate all n bit binary numbers in a fastest way possible</a>. but I haven't found an exact duplicate....
<python><algorithm><binary>
2025-03-08 12:03:28
2
3,930
Ξένη Γήινος
79,494,272
2,315,319
Pass value from one Django template to other
<p>I want to build a Django template hierarchy like so:</p> <pre><code> root.html |_ root-dashboard.html |_ root-regular.html </code></pre> <p><code>root.html</code> shall have an <code>if</code> statement:</p> <pre><code>{% if style == &quot;dashboard&quot; %} {# render some elements in a certain way #} {% else...
<python><django><django-templates>
2025-03-08 11:02:39
1
313
fishfin
79,493,962
1,635,450
IPython.display does not show any image at all but <IPython.core.display.Image object>
<p>I am trying to show <code>LangChain</code> graph in my python module code. Not Jupiter notebook. However, the following code snippet:</p> <pre><code>from IPython.display import Image, display from langgraph.graph import StateGraph, MessagesState graph_builder = StateGraph(MessagesState) simple_graph = graph_builder....
<python><image><ipython><draw><python-3.12>
2025-03-08 05:58:07
1
4,280
khteh
79,493,688
2,687,317
3D scatter plot and projected KDE plots
<p>Can someone tell me why the xz projection in this code does not appear on the x-z plane?</p> <pre><code>import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import numpy as np from scipy.stats import kde # Sample data np.random.seed(42) x = np.random.randn(100) y = np.random.randn(100) z = np.ran...
<python><matplotlib><seaborn><plot3d>
2025-03-08 00:31:56
2
533
earnric
79,493,638
4,463,825
assigning data in a pythonic way
<p>Looking for suggestions on how to compress this code into a couple of lines. One line for assigning columns, and the other for data.</p> <pre><code>df_input = pd.DataFrame(columns=['supply_temp', 'liquid_mass_flow','air_inlet_temp']) flow = 60 inputs = np.array([45,flow*988/60000,35]) df_input['supply_temp'] = in...
<python><pandas><numpy>
2025-03-07 23:42:50
1
993
Jesh Kundem
79,493,514
10,083,382
Convert JSON object to Pandas DataFrame ensuring that Key is considered as column label
<p>I have a python script which needs to be executed by passing the input using command line. The command is as follows</p> <pre class="lang-bash prettyprint-override"><code>python script.py --input [{\\&quot;A\\&quot;:\\&quot;322|985\\&quot;,\\&quot;B\\&quot;:3}] </code></pre> <p>The idea is to convert the input to a ...
<python><json><pandas><dataframe>
2025-03-07 21:49:02
1
394
Lopez
79,493,454
2,893,712
SQLite cannot start a transaction within a transaction
<p>I have a script that utilizes the APScheduler module to run certain scripts at set intervals. These scripts are used for all kinds of purposes that make my life easier I also use a simple SQLite database to save the information and this is how I see if the data has changed, and if it has, it will send me a message u...
<python><sqlite><transactions><apscheduler>
2025-03-07 21:07:15
1
8,806
Bijan
79,493,181
568,352
I am trying to run uwsg-emporer vassal and it can't find my python
<p>When I create a uwsgi vassal ini file, the server throws this error when I hit the site:</p> <p>--- no python application found, check your startup logs for errors ---</p> <p>The virtualenv is correct and if I do python manage.py check I do not have errors and python manage.py runserver runs a dev version fine. I fi...
<python><django><uwsgi>
2025-03-07 18:23:26
0
1,817
bradrice
79,493,063
5,795,116
Post Request Not working for scraping a website
<p>Step 1: Send a GET request to fetch the page and extract hidden form values We'll first send a GET request to the page and extract necessary hidden form values like __VIEWSTATE, __VIEWSTATEGENERATOR, and __EVENTVALIDATION which are needed for subsequent POST requests.</p> <pre><code>import requests from bs4 import B...
<python><post><get>
2025-03-07 17:30:01
1
327
jatin rajani
79,493,017
274,579
How to make script-level variables private to the script
<p>Is it possible to declare a global variable that is invisible to the importing script?</p> <p>For example, in script <code>a.py</code> I have a variable <code>var_a</code> that is accessible to any function in <code>a.py</code>. However, in script <code>b.py</code> that imports <code>a.py</code>, I want <code>var_a<...
<python><python-3.x><scope><python-import>
2025-03-07 17:13:59
1
8,231
ysap
79,492,880
243,031
how to make all field optional with alias name?
<p>I am following <a href="https://stackoverflow.com/a/77851176/243031">https://stackoverflow.com/a/77851176/243031</a> to create my model optional.</p> <p>I created function to get base class annotations.</p> <pre><code>def get_annotations(main_cls): ret_val = main_cls.__annotations__ for base_cls in main_cls....
<python><mongodb><alias><pydantic>
2025-03-07 16:14:05
1
21,411
NPatel
79,492,823
1,999,585
AttributeError: The layer sequential has never been called and thus has no defined input.. Did you mean: 'inputs'?
<p>I am trying to write a Python class that applies the VGG-Face recognition algorithm. This class is written in the deepface.py file:</p> <pre><code>import cv2 import numpy as np from deepface import DeepFace from sklearn.metrics import classification_report from sklearn.model_selection import train_test_split from sk...
<python><keras>
2025-03-07 15:52:19
0
2,424
Bogdan Doicin
79,492,778
8,037,521
Apply VTK color series to render a point cloud
<p>I have managed to write this code containing a simple load button for laz/las file and the VTK rendering widget. It applies some automatic color scheme (which one?) to the point cloud based on the colors that I produce by normalizing intensity values to 0-1 range. Question: how to apply a VTK color series to it? I h...
<python><vtk><pyside2>
2025-03-07 15:33:25
0
1,277
Valeria
79,492,385
25,413,271
Asyncio: pass context or contextvar to add_done_callback
<p>I am learning asyncio callbacks. My task is- I have a message dict, message codes are keys, message texts are values. In coro <code>main</code> I have to create a number of asynchronous tasks (in my case 3 tasks), each task wraps a coro which prints one message. Also I have to add a callback to each task. Callback m...
<python><python-asyncio><asynccallback><python-contextvars>
2025-03-07 12:59:03
2
439
IzaeDA
79,492,367
15,560,990
Can Airflow task dependencies be re-used?
<p>I have a series of airflow DAGs which re-use some of the task dependencies. For example</p> <pre><code>DAG 1: T1 &gt;&gt; T2 DAG 2: T1 &gt;&gt; T2 &gt;&gt; T3 DAG 3: T1 &gt;&gt; T2 &gt;&gt; T3 &gt;&gt; [T4, T5, T6] &gt;&gt; T7 </code></pre> <p>I would like to store the dependencies from DAG 1 (which in this model,...
<python><airflow><directed-acyclic-graphs>
2025-03-07 12:51:54
1
460
Dasph
79,492,362
4,412,929
Applying a custom function to Xarray resample drops the dimension coordinates
<p>When using the <code>map</code> method to apply a custom function in Xarray resample, the dimension coordinates are lost, and the resulting Dataset has a sequence instead of the actual coordinate values.</p> <p>The following MWE will properly demonstrate the issue:</p> <pre><code>import numpy as np import pandas as ...
<python><python-xarray>
2025-03-07 12:48:37
0
363
RogUE
79,492,317
1,826,066
Fill gaps in time series data in a Polars Lazy- / Dataframe
<p>I am in a situation where I have some time series data, potentially looking like this:</p> <pre class="lang-py prettyprint-override"><code>{ &quot;t&quot;: [1, 2, 5, 6, 7], &quot;y&quot;: [1, 1, 1, 1, 1], } </code></pre> <p>As you can see, the time stamp jumps from <code>2</code> to <code>5</code>. For my an...
<python><dataframe><time-series><python-polars>
2025-03-07 12:25:16
1
1,351
Thomas
79,492,249
7,636,248
Why cannot build gem5 with a custom memory controller?
<p>I'm trying to integrate a custom memory controller in gem5 but when I try to build it returns me this error:</p> <pre><code>terminate called after throwing an instance of 'pybind11::error_already_set' what(): TypeError: module() takes at most 2 arguments (3 given) At: src/learning_gem5/my_mem_ctrl/DpiMemCtrl.py(...
<python><build><gem5>
2025-03-07 11:57:50
0
361
Vincy
79,491,978
8,621,823
Why inspect.getsource only works for functions and not classes in jupyter?
<pre><code>import inspect def method(): return &quot;Hello&quot; source_code = inspect.getsource(method) print(source_code) </code></pre> <p>works in both jupyter notebook and .py file</p> <pre><code>import inspect class MyClass: def method(self): return &quot;Hello&quot; source_code = inspect.ge...
<python><jupyter-notebook>
2025-03-07 10:27:46
0
517
Han Qi
79,491,666
368,907
Read file and insert into map
<p>I have been searching around the internet on how to read from file and insert it into map in Python? The file contains username, password.</p> <pre><code>def readFile(self): f = open(&quot;user.txt&quot;, &quot;r&quot;) for x in f: // Create a map insert into it print(x) </code></pre> <p>Plea...
<python><python-3.x>
2025-03-07 08:41:43
1
2,802
Ivan