QuestionId
int64
74.8M
79.8M
UserId
int64
56
29.4M
QuestionTitle
stringlengths
15
150
QuestionBody
stringlengths
40
40.3k
Tags
stringlengths
8
101
CreationDate
stringdate
2022-12-10 09:42:47
2025-11-01 19:08:18
AnswerCount
int64
0
44
UserExpertiseLevel
int64
301
888k
UserDisplayName
stringlengths
3
30
βŒ€
78,849,095
8,372,455
How to fix "Please use 'min' instead of 'T'"
<p>How can I fix the warning:</p> <pre><code>FutureWarning: 'T' is deprecated and will be removed in a future version. Please use 'min' instead of 'T'. if median_diff &gt; pd.Timedelta(freq): </code></pre> <p>In the method below it comes up every time I run it but I am not using a <code>T</code> in my code that I can...
<python><pandas><dataframe><timedelta><deprecation-warning>
2024-08-08 14:52:05
0
3,564
bbartling
78,848,723
162,684
Non-nullable field in schema does not prevent null values in corresponding table column
<p>I have read the <a href="https://arrow.apache.org/docs/python/generated/pyarrow.field.html" rel="nofollow noreferrer">documentation</a> of the <code>field()</code> method, and as far as I understand I can say that a field does not allow NULL values by specifying <code>nullable=False</code>. So, I have tried this exa...
<python><pyarrow><apache-arrow>
2024-08-08 13:29:18
0
13,583
MarcoS
78,848,610
4,494,505
Why the Langchain placeholder is not being called?
<p>My goal is to insert the <code>language</code> placeholder into the invoke method but currently the response is always in english. I follow this tutorial -&gt; <a href="https://python.langchain.com/v0.2/docs/tutorials/chatbot/" rel="nofollow noreferrer">https://python.langchain.com/v0.2/docs/tutorials/chatbot/</a></...
<python><py-langchain>
2024-08-08 13:09:42
1
1,628
airsoftFreak
78,848,572
7,920,004
Python doesn't see added module to the same dir
<p>I added to my <code>utils</code> dir a new file that contains <code>dict</code> variable which I want to import into another file.</p> <p><code>mapping.py</code></p> <pre><code>config = [ { &quot;filter_column&quot;: &quot;SHOW_NAME&quot;, &quot;horizons&quot;: [ 3, 4, ...
<python><airflow><mwaa>
2024-08-08 13:02:20
1
1,509
marcin2x4
78,848,438
9,047,420
Python operator overloading - chaining '>' does not work as expected
<p>I'm trying to make a class that can keep track of basic join operations between instances of that class. See the minimum reproducible example below</p> <pre class="lang-py prettyprint-override"><code>from __future__ import annotations from typing import Literal class Block(): jointype_lookup = {'both': '&gt;'...
<python><operator-overloading>
2024-08-08 12:31:32
2
510
arneyjfs
78,848,271
13,000,229
How can I get each page of "Page Break Preview" in Excel using Python?
<h2>Problem</h2> <p>I'm trying to get each page of &quot;Page Break Preview&quot;. Precisely speaking, I need to know which cells Page 1 contains, which cells Page 2 contains and so on.</p> <p>Could you teach me how to realize this functionality in Python 3.12? I tried <code>openpyxl</code>, but other libraries are wel...
<python><excel><openpyxl>
2024-08-08 11:53:29
2
1,883
dmjy
78,848,034
1,172,907
Call a fixture with arguments
<p>I've read the pytest fixture parametrization <a href="https://docs.pytest.org/en/6.2.x/fixture.html#parametrizing-fixtures" rel="nofollow noreferrer">documentation</a> but struggle on the most simple task now.</p> <p>How can I have <code>f</code> and <code>f1</code> returned <code>as_file</code>?</p> <pre class="lan...
<python><pytest><pytest-fixtures>
2024-08-08 11:03:37
2
605
jjk
78,848,020
143,556
Invalid content type. image_url is only supported by certain models
<p>That's my Python request:</p> <pre><code>def analyze_screenshot_base64(encoded_image): headers = { &quot;Content-Type&quot;: &quot;application/json&quot;, &quot;Authorization&quot;: f&quot;Bearer {openai.api_key}&quot; } payload = { &quot;model&quot;: &quot;gpt-4o-mini&quot;, ...
<python><openai-api><chatgpt-api>
2024-08-08 11:00:34
2
1,331
Ploetzeneder
78,847,998
4,809,603
List to DataFrame with row and column headers
<p>I need to convert a list (including headers) to a Dataframe.</p> <p>If I do it directly using <code>pl.DataFrame(list)</code>, the headers are created and everything is kept as a string. Moreover, the table is transposed, such that the first element in the list becomes the first column in the dataframe.</p> <p><stro...
<python><python-polars>
2024-08-08 10:54:18
3
415
Rhys
78,847,944
3,220,554
Using XLSXWRITER in Python: How insert 27 digit number in cell and display it as text not as scientific number
<p>I'm writing an Excel using XLSXWRITER package in Python. Formats are applied to cells and this all works, except for one cell when the value assigned is a 27 digit text string (extracted from some source).</p> <p>I've read <a href="https://stackoverflow.com/questions/29727612/how-to-apply-format-as-text-and-accounti...
<python><xlsxwriter>
2024-08-08 10:39:58
2
2,744
phunsoft
78,847,819
607,846
Add two numpy arrays with an offset
<p>Lets say I have two arrays:</p> <pre><code>a = numpy.array([1,2,3,4,5]) b = numpy.array([10,11,12]) </code></pre> <p>I wish to add these arrays together, but I wish to start at index 3 in the first array, to produce:</p> <pre><code>numpy.array([1,2,3,14,16,12]). </code></pre> <p>So I'm basically adding an extra 0 to...
<python><numpy>
2024-08-08 10:14:45
3
13,283
Baz
78,847,702
10,780,974
Setting the legend on top of the lines connecting mark_inset plot
<p>I'm using <code>InsetPosition</code> and <code>mark_inset</code> to make a subplot so that I have the lines connecting them. However, I can't get the lines to be on top of the legend in the first plot. Any thoughts on how I can fix this?</p> <p>I'd also like to get the tick markers on top of the line plots if I can...
<python><matplotlib><subplot><insets>
2024-08-08 09:51:15
1
374
Steven Thomas
78,847,208
22,400,527
What is the better way to create multiple user types in Django? abstract classes or proxy models?
<p>I want to create multiple user types in Django. The user types are 'Admin', 'Company' and 'Individual'. Should I use abstract models or proxy models for this requirement.</p> <p>I have already done this using proxy models. How would it be done using abstract models instead? Is any one of them better than the other? ...
<python><django><django-models>
2024-08-08 08:04:20
2
329
Ashutosh Chapagain
78,847,160
2,545,523
Combine several affine transformations get from OpenCV estimateAffinePartial2D
<p>I use OpenCV on Android. I use the <code>goodFeaturesToTrack</code> method to find features in a video frame. Then I take the next video frame and find those features in it using <code>calcOpticalFlowPyrLK</code> and estimate the needed transformation using <code>estimateAffinePartial2D</code>. Up to here everything...
<python><numpy><opencv><computer-vision><linear-algebra>
2024-08-08 07:55:49
1
1,691
cliffroot
78,847,145
7,164,358
PySeriel - Accept (write) confirmation prompt from network sensor
<p>I'm working on collecting a few common configuration steps for jumping network sensors via the console port. Most of what I'll tried is working great, however I have noticed that if I send a command that requires user confirmation my write statment isn't working as intended.</p> <p>As you can see from this putty exa...
<python><serial-port><pyserial>
2024-08-08 07:52:11
0
1,013
Petter Γ–stergren
78,846,882
10,426,490
Gemini Status 429 no matter what
<p>I'm unsure of why on earth my Google Gemini requests are returning status 429 resource exhausted. It definitely isn't because my resource is exhausted! This exact code worked a couple weeks ago...ugh.</p> <p><strong>Specs</strong>:</p> <ul> <li>I have a paid account <ul> <li><a href="https://i.sstatic.net/82vE7YAT.p...
<python><google-gemini><http-status-code-429>
2024-08-08 06:48:08
0
2,046
ericOnline
78,846,694
4,277,485
Generate single dataframe using 2 dataframe with different number of rows, combining the columns
<p>we have 2 dataframes with different number of columns and rows. Want to combine both to a single dataframe in *<strong>python 3.7</strong></p> <p>Df1:</p> <div class="s-table-container"><table class="s-table"> <thead> <tr> <th style="text-align: left;">c1</th> <th style="text-align: center;">c2</th> <th style="text-...
<python><pandas><dataframe><concatenation>
2024-08-08 05:53:30
0
438
Kavya shree
78,846,556
2,728,148
Algorithm for a substring prefix matching a regular expression (in python)
<p>I am writing a parser in Python which operates on a stream. The stream may be unbounded, so I cannot keep it all in memory. As a convenience, I would like to offer a regular expression matcher which matches part of the stream. I believe that means that I need to come up with a regular expression that matches any ...
<python><regex><algorithm>
2024-08-08 04:44:26
1
11,113
Cort Ammon
78,846,426
5,091,720
Pandas parquet file pyarrow.lib.ArrowMemoryError: malloc of size 106255424 failed
<p>I am trying to run a python script in cPanel terminal. I am getting an error as the script tries to open the parquet file that is a 46.65 MB size. This worked on my home computer.</p> <pre><code>df = pd.read_parquet(file_path + 'CA_s.parquet') </code></pre> <p>The error message</p> <pre><code>Traceback (most recent ...
<python><pandas><cpanel><parquet><pyarrow>
2024-08-08 03:33:36
0
2,363
Shane S
78,846,318
5,567,893
How can I change the values in the tensor using dictionary?
<p>when I have a tensor and dictionary as below, how can I map the dictionary to the tensor?<br /> For example,</p> <pre class="lang-py prettyprint-override"><code>Dict = {1: 'A', 2: 'B', 3: 'C'} ex = torch.tensor([[1,2,3],[3,2,1]]) # Expected result #tensor([[A, B, C], # [C, B, A]]) </code></pre> <p>I tried t...
<python><dictionary><pytorch>
2024-08-08 02:30:15
2
466
Ssong
78,846,281
395,857
How can I write a POST request for Azure OpenAI that uses structured output?
<p>I want to write a POST request for Azure OpenAI that uses structured output.</p> <p><a href="https://azure.microsoft.com/en-us/blog/announcing-a-new-openai-feature-for-developers-on-azure/" rel="nofollow noreferrer">https://azure.microsoft.com/en-us/blog/announcing-a-new-openai-feature-for-developers-on-azure/</a> s...
<python><azure><http-post><azure-openai>
2024-08-08 02:04:46
2
84,585
Franck Dernoncourt
78,846,128
7,290,845
DLT - how to get pipeline_id and update_id?
<p>I need to insert pipeline_id and update_id in my Delta Live Table (DLT), the point being to know which pipeline created which row. How can I obtain this information?</p> <p>I know you can get job_id and run_id from widgets but I don't know if these are the same things as pipeline_id and update_id.</p> <p>I have a so...
<python><apache-spark><databricks><azure-databricks><delta-live-tables>
2024-08-08 00:27:26
1
1,689
Zeruno
78,846,004
395,857
How can I use structured_output with Azure OpenAI with the openai Python library?
<p>I want to use structured output with Azure OpenAI.</p> <p>I tried the following code, based on the code given in <a href="https://openai.com/index/introducing-structured-outputs-in-the-api/" rel="nofollow noreferrer">https://openai.com/index/introducing-structured-outputs-in-the-api/</a>:</p> <pre><code>from pydanti...
<python><nlp><azure-openai><gpt-4>
2024-08-07 23:14:19
2
84,585
Franck Dernoncourt
78,845,983
315,734
From Python code, how can I simulate a storage event to a Google Eventarc topic?
<p>Setup:</p> <ol> <li>Deploy a google cloud run service that simply logs exactly its POST payload</li> <li>Create an eventarc that triggers when an object is finalized in a storage bucket that calls that cloud run service endpoint</li> </ol> <p>That all works normally. Now, I know of two options to simulate an event (...
<python><google-cloud-run><event-arc>
2024-08-07 23:03:20
1
7,079
mentics
78,845,958
1,631,414
How to prompt for multiple exclusive groups of arguments from python command line
<p>So I'm trying to parse the command line for 2 groups of mutually exclusive arguments.</p> <ol> <li>The user can specify a file</li> <li>The user can specify a server along with a view</li> </ol> <p>I'm looking at the argparse.add_mutually_exclusive_group function. However, it doesn't seem like it will do what I nee...
<python><argparse>
2024-08-07 22:52:31
1
6,100
Classified
78,845,949
1,329,652
How to define a typing special form for use with static type checking?
<p>I would like to create a typing special form that takes a non-type, say integer, as an argument, similar to the 2nd argument of <code>typing.Annotated</code>.</p> <p>For example, I'd like <code>foo[5]</code> to be the same type annotation as <code>Annotated[int, 5]</code>.</p> <p>There are many ways that don't fail ...
<python><python-typing>
2024-08-07 22:48:10
1
99,011
Kuba hasn't forgotten Monica
78,845,943
1,404,208
Why is graph in Networkx pointing arrows in the wrong direction?
<p>I have a pandas data frame with two columns: source and sink. In a simplified form, there are just 5 users (source column) that can owe money to any other user (sink column). I thought the following code would show the plot of user 1 owing to user 3 (yes arrow is correct, good), user 2 to 4 (good), 3 to 5 (good), 4 ...
<python><graph><networkx><permutation>
2024-08-07 22:46:05
1
455
alexey
78,845,851
1,394,336
Quickly training multiple small neural networks
<p>I want to train multiple models on the same training data (just different initializations). Each model has exactly the same architecture. Crucially, the models are extremely small, so having them all in memory at the same time won't be a problem. How can I make this as efficient as possible?</p> <p>I read that cuda ...
<python><performance><pytorch><neural-network>
2024-08-07 22:09:07
2
2,057
Christopher
78,845,737
14,684,366
Convert XML file into dictionary, with ElementTree
<p>I have an XML configuration file used by legacy software, which I cannot change or format. The goal is to use Python 3.9 and transform the XML file into a dictionary, using only <code>xml.etree.ElementTree</code> library.</p> <p>I was originally looking at this <a href="https://stackoverflow.com/a/68082847/14684366"...
<python><xml><dictionary>
2024-08-07 21:27:05
1
591
Floren
78,845,456
8,382,067
Trying to update column in GridDB but can't figure out why it is not updating
<p>Im trying to update data in a GridDB container using the Python client. Ive set up my environment and written the following code to perform the update. The update operation does not seem to be working as the data stays the same.</p> <p>Any ideas on what I may have done wrong here? Here is the documentation I was rea...
<python><sql><griddb>
2024-08-07 19:54:16
0
2,099
Josh Adams
78,845,450
9,935,280
ImportError: cannot import name 'RSAAlgorithm' from 'jwt.algorithms'
<p>The <code>RSAAlgorithm</code> PyJWT algorithm method fails to import, but I do have the <code>PyJWT</code> installed.</p> <p>Error:</p> <pre><code>ImportError: cannot import name 'RSAAlgorithm' from 'jwt.algorithms' </code></pre> <p>I checked if the package is available by running this command:</p> <pre class="lang-...
<python><django><algorithm><jwt>
2024-08-07 19:53:10
1
524
Jonny
78,845,357
3,486,684
Python + Polars: how can I convert the values of a column with type `enum` into their integer ("physical") representation?
<p>The polars <a href="https://docs.pola.rs/user-guide/concepts/data-types/categoricals/#enum-type" rel="nofollow noreferrer">user guide</a> suggests that enums have a physical, integer representation.</p> <p>Is it possible to access the integers associated with an enum value? For example, is there a nicer way to get t...
<python><python-polars>
2024-08-07 19:21:14
2
4,654
bzm3r
78,845,316
19,838,445
How to configure Python ssl server ciphers to match client's
<p>I'm trying to run this simple socket ssl server in python</p> <pre class="lang-py prettyprint-override"><code>import socket, ssl context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) bindsocket = socket.socket() bindsocket.bind((&quot;&quot;, 443)) bindsocket.listen(5) while True: newsocket, fromaddr...
<python><ssl><curl><https><ssl-certificate>
2024-08-07 19:04:32
0
720
GopherM
78,845,297
3,486,684
How do define custom auto-imports for Pylance/Visual Studio Code?
<p>When I type out something like <code>np.</code> I think this triggers Visual Studio Code + Pylance's (not sure) auto-import completion by suggesting that <code>import numpy as np</code> might be relevant.</p> <p>I would like to create similar custom auto-import/complete associations. For example: between <code>pl</c...
<python><visual-studio-code><pylance>
2024-08-07 18:58:21
2
4,654
bzm3r
78,845,218
2,006,674
FastAPI TestClient not starting lifetime in test
<p>Example code:</p> <pre><code>import os import asyncio from contextlib import asynccontextmanager from fastapi import FastAPI, Request @asynccontextmanager async def lifespan(app: FastAPI): print(f'Lifetime ON {os.getpid()=}') app.state.global_rw = 0 _ = asyncio.create_task(infinite_1(app.state), name='...
<python><asynchronous><pytest><python-asyncio><fastapi>
2024-08-07 18:36:28
2
7,392
WebOrCode
78,845,156
1,028,270
Ruamel thinks this list is a multi-document file
<p>This is my valid YAML file:</p> <pre class="lang-yaml prettyprint-override"><code># my_yaml.yaml - aaa: zzzzz bbbb: 'lksdjflksjdflksdj' xxxx: qqqq: - sldflsdkjflks fffff: [] - aaa: zzzzz bbbb: 'lksdjflksjdflksdj' xxxx: qqqq: - sldflsdkjflks fffff: [] - aaa: zzzzz bbbb: 'lksdjflksj...
<python><ruamel.yaml>
2024-08-07 18:16:02
1
32,280
red888
78,845,128
7,084,129
pytest-randomly gives the same "random" result for every test
<p>I'm trying to figure out how to use <code>pytest-randomly</code> properly, but the problem is I always get the same set of random numbers for every test. All I did was install <code>pytest-randomly</code> (3.15.0) and run tests normally.</p> <p>Here's an example code:</p> <pre><code>import random def generate_ran...
<python><pytest>
2024-08-07 18:06:14
1
401
Duje
78,844,952
3,412,205
How to type hint the Apache Beam default DoFn.TimestampParam
<p>I'm struggling to annotate an extra parameter of a DoFn <code>process</code> method, specifically <a href="https://beam.apache.org/releases/pydoc/current/apache_beam.transforms.core.html#apache_beam.transforms.core.DoFn.process" rel="nofollow noreferrer">a timestamp parameter</a>.</p> <p>Minimal example:</p> <pre><c...
<python><apache-beam><python-typing><mypy>
2024-08-07 17:12:56
1
1,465
user3412205
78,844,871
17,220,672
Locking resource in FastAPI - using a multiprocessing Worker
<p>I would like to make an <code>FastAPI</code> service with one <code>/get</code> endpoint which will return a ML-model inference result. It is pretty easy to implement that, but the catch is I periodically need to update the model with a newer version (trough request on another server with models, but that is beside ...
<python><python-asyncio><fastapi><python-multiprocessing>
2024-08-07 16:51:14
1
419
mehekek
78,844,612
7,447,542
Outlook using python win32com reading only email till a specific date and nothing after that
<p>Below is my Python code using win32com to read emails from a particular folder.</p> <pre><code> from logging import root import os import win32com.client from datetime import datetime, timedelta import zipfile date_format = &quot;%m/%d/%Y %H:%M&quot; def recursively_find_folder(folder, target_name): if folder....
<python><python-3.x><outlook><win32com>
2024-08-07 15:47:21
2
424
Nikhil Ravindran
78,844,458
4,321,525
How to Optimize Grid Lines and Support Points for Piecewise Linear Interpolation?
<p>I am working on a piecewise linear interpolation problem in Python where I optimize the placement of support points (in x- and y-direction) to fit some data. The 1D version of my code works as expected, distributing the support points nicely to fit the data, especially placing more support points in areas with small...
<python><optimization>
2024-08-07 15:12:35
1
405
Andreas Schuldei
78,844,342
1,176,573
Sort only few columns in pandas dataframe by month and year
<p>How do I sort the only the <code>month year</code> columns in below dataframe? These columns could differ for different stock.</p> <div class="s-table-container"><table class="s-table"> <thead> <tr> <th></th> <th>Quarterly Results</th> <th>Stockname</th> <th>Mar 2021</th> <th>Jun 2021</th> <th>Sep 2021</th> <th>Dec...
<python><pandas>
2024-08-07 14:49:08
2
1,536
RSW
78,844,205
22,963,183
How to develop a Generalized RAG Pipeline for Text, Images, and Structured Data
<p>I'm trying to find a general solution for RAG to solve problems involving both text, images, chart, tables,.., they are in many different formats such as <strong>.docx</strong>, <strong>.xlsx</strong>, <strong>.pdf</strong>.</p> <p><strong>The requirement for the answer:</strong></p> <ul> <li>Some answers are just i...
<python><langchain><large-language-model><python-embedding><rag>
2024-08-07 14:22:48
1
515
happy
78,844,160
15,547,292
Getting a flat view of a nested list
<p>In Python, is it possible to get a flat view of a list of lists that dynamically adapts to changes to the original, nested list?</p> <p><strong>To be clear, I am not looking for a static snapshot, but for a view that reflects changes.</strong></p> <p>Further, the sub-lists should not be restricted to a primitive typ...
<python><list><flatten>
2024-08-07 14:12:41
3
2,520
mara004
78,843,966
4,232,472
Kafka broker does not receive message from python producer
<p>Hello i use the following configuration for Kafka using docker compose</p> <p><strong>compose_kafka.yml</strong></p> <pre><code>version: '3' services: zookeeper: image: wurstmeister/zookeeper container_name: zookeeper ports: - &quot;2181:2181&quot; environment: ZOO_MY_ID: 1 kafka: ...
<python><apache-kafka><apache-zookeeper>
2024-08-07 13:28:01
1
1,650
Erik hoeven
78,843,838
315,427
CFMessagePortSendRequest FAILED(-1)
<p>I'm using <code>PyQT6</code> on MacOS and <code>exec()</code> to open dialog</p> <pre><code>if dialog.exec() == QDialog.DialogCode.Accepted: print(&quot;Adding...&quot;) else: print(&quot;Adding cancelled&quot;) </code></pre> <p>The reason for exec is to block the execution until I get result from the dialog...
<python><macos><pyqt><pyqt6>
2024-08-07 12:59:23
0
29,709
Pablo
78,843,741
2,051,572
Error Using Ollama Docker Image with LangChain to Perform LLaMA Model Inference
<p>I'm trying to use the official Ollama Docker image to run a Python script that performs inference using the <code>llama3.1</code> model from Ollama with LangChain. My script performs some operations on a Pandas DataFrame and then uses the LLaMA model to answer questions based on the DataFrame's content.</p> <p>I am ...
<python><docker><containers><langchain><ollama>
2024-08-07 12:37:08
0
2,512
Ohm
78,843,713
2,521,423
PySide6 GUI displays differently on different computers
<p>I have a GUI application built in PySide6. Mostly it works fine, but a specific part of it displays differently on different machines: specifically, the text color is white on one machine, but black (as it should be) on every other machine I have tested on. Comparison below:</p> <p>Working: <a href="https://i.sstati...
<python><pyside6>
2024-08-07 12:31:17
0
1,488
KBriggs
78,843,705
1,876,739
Replace pandas DataFrame column values with dict values looked up by separate column
<p>Given a pandas <code>DataFrame</code> containing <code>nan</code>:</p> <pre><code>import numpy as np import pandas as pd bad_df = pd.DataFrame({'foo': [np.nan, 1.0, 2.0], 'bar': ['a', 'b', 'c']}) </code></pre> <p>And also given a dictionary with lookup keys that may exist in the <code>bar</code> column:</p> <pre><c...
<python><pandas>
2024-08-07 12:29:18
1
17,975
RamΓ³n J Romero y Vigil
78,843,541
3,402,703
hide firefox downloads window (or contain to one desktop)
<p>I don't even know if the name of that is &quot;window&quot;: it's not in the DOM, but in the browser, and Firefox opens it everytime a download is completed. I can be accessed with <code>Ctrl+Shift+y</code> if I do it manually.</p> <p>I'm downloading some pdfs with python and selenium. I set all options for download...
<python><selenium-webdriver><firefox><selenium-firefoxdriver>
2024-08-07 11:56:33
1
6,507
PavoDive
78,843,458
3,070,181
Ignore specific string in flake8 warning when using icecream
<p>I use <a href="https://github.com/gruns/icecream" rel="nofollow noreferrer">icecream</a> to support my debugging and a large project I use the <a href="https://github.com/gruns/icecream#import-tricks" rel="nofollow noreferrer">install method</a> to make it available in all files.</p> <p>Unfortunately, flake8, report...
<python><flake8>
2024-08-07 11:35:35
2
3,841
Psionman
78,843,191
1,016,428
NumPy on small arrays: elementary arithmetic operations performances
<p>I am not 100% positive that this question has a solution besides &quot;that's the overhead, live with it&quot;, but you never know.</p> <p>I have a very simple set of elementary mathematical operations done on rather small 1D NumPy arrays (6 to 10 elements). The arrays' <code>dtype</code> is <code>np.float32</code>,...
<python><arrays><numpy><performance><f2py>
2024-08-07 10:30:33
2
1,449
Infinity77
78,843,073
6,477,565
OSError: Bad file descriptor
<p>I'm trying to run celery beat worker and a normal celery worker as docker containers. I have my tasks in flask application.</p> <p>The normal celery worker is working fine but getting following error in <strong>beat worker</strong></p> <pre><code>[2024-08-07 09:57:24,692: INFO/MainProcess] mingle: searching for neig...
<python><flask><celery><python-importlib><kombu>
2024-08-07 10:06:03
1
815
Albin Antony
78,842,962
7,920,004
Airflow DAG throws GlueJobOperator is not JSON serializable
<p>Below Airflow task throws an <strong>error</strong>:</p> <pre><code>[2024-08-07T09:05:00.142+0000] {{xcom.py:664}} ERROR - Object of type GlueJobOperator is not JSON serializable. If you are using pickle instead of JSON for XCom, then you need to enable pickle support for XCom in your airflow config or make sure to ...
<python><amazon-web-services><airflow><mwaa>
2024-08-07 09:46:23
1
1,509
marcin2x4
78,842,905
3,885,696
Standardization of a 1d vector in torch
<p>I am working with torch dataset of 1d signals, and would like to standardize the vectors to mean 0, std 1 before further processing the data. If I would have dealt with an image, I could use torchvision.transforms:</p> <pre class="lang-py prettyprint-override"><code> import torchvision.transforms as transforms ...
<python><torch>
2024-08-07 09:36:11
1
1,954
Nir
78,842,887
12,397,370
Map RGB colors from a heatmap back to their original scale values
<p>I have the following heatmap</p> <p><a href="https://i.sstatic.net/bZejlPlU.webp" rel="nofollow noreferrer"><img src="https://i.sstatic.net/bZejlPlU.webp" alt="heatmap" /></a></p> <p>and all I know is that the mapping between the colors and the original values is as follows: -100 is blue, 0 is black, and +10 is red....
<python><matplotlib><colors>
2024-08-07 09:31:51
0
485
Gabriel Cia
78,842,630
13,840,270
Add column by accessing item in Array based on ID without SQL expression
<p>I have the following data in a dataframe <code>df</code>:</p> <pre class="lang-json prettyprint-override"><code>{ &quot;data&quot;:[ { &quot;id&quot;:&quot;a&quot;, &quot;val&quot;:1 }, { &quot;id&quot;:&quot;b&quot;, &quot;val&quot;:2 ...
<python><apache-spark><pyspark>
2024-08-07 08:35:02
2
3,215
DuesserBaest
78,842,605
7,395,592
16-byte offset in MPEG-4 video export from DICOM file
<p><strong>Short version</strong>: Where is the 16-byte offset coming from when exporting an MPEG-4 video stream from a DICOM file with <a href="https://pydicom.github.io/" rel="nofollow noreferrer"><code>Pydicom</code></a> via the following code? (And, bonus question, is it always a 16-byte offset?)</p> <pre class="la...
<python><dicom><pydicom>
2024-08-07 08:29:45
1
6,750
simon
78,842,466
6,930,340
Split a polars DataFrame into multiple chunks with groupby
<p>Consider the following <code>pl.DataFrame</code>s:</p> <pre><code>import datetime import polars as pl df_orig = pl.DataFrame( { &quot;symbol&quot;: [*[&quot;A&quot;] * 10, *[&quot;B&quot;] * 8], &quot;date&quot;: [ *pl.datetime_range( start=datetime.date(2024, 1, 1),...
<python><python-polars>
2024-08-07 07:52:59
2
5,167
Andi
78,842,293
298,847
Python @overload using union types causes overlapped function signature errors
<p>I would like to write the following overloaded Python function:</p> <pre class="lang-py prettyprint-override"><code>from typing import Any, TypeVar, overload _T1 = TypeVar('_T1') _T2 = TypeVar('_T2') _T3 = TypeVar('_T3') @overload def parse_as(ty: type[_T1] | type[_T2], s: bytes) -&gt; _T1 | _T2: ... @overl...
<python><python-typing><mypy>
2024-08-07 07:16:38
0
9,059
tibbe
78,842,246
1,008,698
python socket recv timeout while Wireshark shows received UDP packet (windows)
<p>I have the following diagram:</p> <blockquote> <p>Send: <strong>client</strong> --(tx_socket)--&gt; <strong>server</strong></p> <p>Reply: <strong>server</strong> -- (rx_socket) --&gt; <strong>client</strong></p> </blockquote> <pre><code>def connect(self) -&gt; None: self.tx_socket = socket.socket(socket.AF_INE...
<python><sockets>
2024-08-07 07:01:07
1
2,660
Tran Ngu Dang
78,842,133
5,109,026
"gcloud storage cp t.txt gs://my.bucket.name/" gives error: ModuleNotFoundError: No module named 'google.auth'
<p>I'm trying to upload a file to a bucket using:</p> <pre><code>gcloud storage cp t.txt gs://my.bucket.name/ </code></pre> <p>But there's an error:</p> <pre><code>Copying file://t.txt to gs://adhoc.textra.me/t.txt Traceback (most recent call last): File &quot;&lt;string&gt;&quot;, line 1, in &lt;module&gt; File &q...
<python><google-cloud-platform><gcloud>
2024-08-07 06:34:43
1
971
Theo Lassonder
78,841,959
1,447,953
Iterate over dependent iterators together
<p>So here is my scenario:</p> <pre><code>def gen1(a): for item in a: yield item ...
<python><python-itertools>
2024-08-07 05:39:12
0
2,974
Ben Farmer
78,841,908
1,870,400
Why python wiremock doesnt respect precision and returns numbers as string?
<p>I am trying basic mock example on decimals using wiremock and I couldn't get it to work. And I dont see any example online either. Below is the response section of my json file</p> <pre><code> &quot;response&quot;: { &quot;status&quot;: 200, &quot;jsonBody&quot;: { &quot;weekly_rate&quot;: &quot;{{r...
<python><wiremock>
2024-08-07 05:13:57
1
6,414
user1870400
78,841,671
3,624,000
Fetch Nth Keys from a Struct in Python
<p>Here is my json which has nested structs or list in it. I want to extract all the nth key from the JSON after parsing through all of them. I am doing this in python and able to crack it through re-cursive method but would help to solve through iterative method. Any help here in python is really appreciatable!</p> <p...
<python><arrays><json>
2024-08-07 02:59:20
1
311
user3624000
78,841,576
10,737,147
strange matplotlib limits when aspect ratio is fixed
<p>Im facing a strange behaviour from matplotlib when equal aspect ratio is preserved. For starters, this is the minimum code sample to show this behaviour. First with the correct behaviour and second with the crooked behaviour</p> <pre><code>import matplotlib.pyplot as plt import numpy as np # Generate some random da...
<python><matplotlib><aspect-ratio>
2024-08-07 01:57:32
1
437
XYZ
78,841,431
1,103,734
Correctly reimplementing `defaultdict`
<p>I want to re-implement <code>defaultdict</code> myself. In principle, this feels like a really simple question, and one I might give as a &quot;homework assignment&quot;, but the more I dug in, the more complicated it got. My first attempt looked something like this</p> <pre class="lang-py prettyprint-override"><cod...
<python><dictionary><defaultdict>
2024-08-07 00:23:56
1
4,846
ollien
78,841,378
16,171,413
A more elegant approach to writing Django’s unit tests
<p>I am currently writing tests using Django’s unit tests (based on Python standard library module: unittest). I have written this test for my Contact model which passes:</p> <pre><code>class ContactTestCase(TestCase): def setUp(self): &quot;&quot;&quot;Create model objects.&quot;&quot;&quot; Contac...
<python><django><python-unittest><django-testing><django-unittest>
2024-08-06 23:47:35
1
5,413
Uchenna Adubasim
78,841,259
825,227
Two sided seaborn barplot not referencing proper y-values
<p>Trying to make a two-sided barplot using Seaborn in Python and it doesn't appear to be using the proper levels for one side of the plot.</p> <p>Data looks like this:</p> <pre><code> Time Symbol Position Operation Side Price Size 0 2023-07-25 15:09:12.249964 MCDU3 0 0 1 0.7595 -2 1 2023...
<python><seaborn>
2024-08-06 22:44:02
1
1,702
Chris
78,841,211
2,697,895
How to get the dimensions of a toga.Canvas() in Python?
<p>In a Python BeeWare project, I want to use toga.Canvas to draw some horizontal rectangles, but I don't know from where to get the Canvas width. I can't find any documentation for the toga.Canvas() dimensions on the internet...</p> <pre><code> def redraw_canvas(self): x = 4; y = 4; for i in range(7): ...
<python><beeware><toga>
2024-08-06 22:22:37
1
3,182
Marus Gradinaru
78,841,091
12,919,727
Option to try flexible install first when using ```conda install -c conda-forge PACKAGE_NAME```
<p>I am working from an AWS SageMaker Notebook Instance. For installation of most packages for my project, conda fails to install using frozen install:</p> <pre><code>conda install -c conda-forge geopandas Collecting package metadata (current_repodata.json): done Solving environment: failed with initial frozen solve. R...
<python><conda><amazon-sagemaker>
2024-08-06 21:35:33
0
491
McM
78,841,040
6,357,916
ModuleNotFoundError: No module named 'yolov7'
<p>I am trying out code in <a href="https://github.com/NirAharon/BoT-SORT" rel="nofollow noreferrer">this repository</a>. I run one of the command given in their readme page, but I am getting ModuleNotFoundError:</p> <pre><code>/workspace/BoTSORT$ python3 tools/mc_demo_yolov7.py --weights pretrained/mot17_sbs_S50.pth -...
<python><python-3.x><pip><python-packaging><yolov7>
2024-08-06 21:18:40
0
3,029
MsA
78,841,010
20,591,261
Format datetime in polars
<p>I have a polars dataframe that contains a <code>datetime</code> column. I want to convert this column to strings in the format <code>%Y%m</code>. For example, all dates in January 2024 should be converted to <code>&quot;202401&quot;</code>.</p> <pre class="lang-py prettyprint-override"><code>from datetime import dat...
<python><datetime><python-polars><strftime>
2024-08-06 21:09:10
2
1,195
Simon
78,840,951
17,800,932
Abstracting a real hardware and simulated device with the same interface in Python
<p>I am looking for a more idiomatic or concise OOP pattern to implement the equivalent of the following.</p> <h4>Interface and implementations</h4> <pre class="lang-py prettyprint-override"><code>from abc import ABC, abstractmethod from typing import override class Device: &quot;&quot;&quot;Main interface that hi...
<python><oop><design-patterns><state-pattern><proxy-pattern>
2024-08-06 20:43:40
1
908
bmitc
78,840,589
235,472
How to spilt a Python class in multiple files in different subdirectories?
<p>I can split a class definition in multiple files only if these are located in the same directory:</p> <pre><code># entrypoint.py class C(object): from ImplFile import OtherMethod def __init__(self): self.a = 1 # ImplFile.py def OtherMethod(self): print(&quot;a = &quot;, self.a) </code></pre>...
<python><subdirectory>
2024-08-06 18:41:38
1
13,528
Pietro
78,840,534
5,568,409
How to understand a strange command linked to Delaunay and Line2D?
<p>I was intrigued by a command line that I don't understand, given in the answer of the (already old) post <a href="https://stackoverflow.com/questions/29807551/how-to-change-matplotlib-line-color-in-scipy-spatial-delaunay-plot-2d">HERE</a>.</p> <p>So, I tried to investigate and made the following program:</p> <pre><c...
<python><matplotlib><delaunay>
2024-08-06 18:23:57
1
1,216
Andrew
78,840,528
9,890,009
How to optimize method with multiple query calls?
<p>I have an event system in my app. Every time a user deletes/updates/creates and object a new event is created in the database with the info of the object and the type of event it is. My Event model looks something like this:</p> <pre><code>class Event(models.Model): uuid = models.UUIDField(primary_key=True, defa...
<python><django><django-orm>
2024-08-06 18:21:22
1
792
Paul Miranda
78,840,402
186,099
How to infer the type of the first element in an iterable?
<p><strong>How to infer the type of the first element in an iterable in MyPy/Pyright?</strong></p> <p>Is there any way to annotate the code below to a bit more narrow scoped? Meaning that I want the type checker to assume that the function below returns an object of the type that is contained in the iterable or list.</...
<python><python-typing><mypy><pyright>
2024-08-06 17:44:24
2
9,511
Vlad
78,840,242
8,436,290
How to return used context to answer using Langchain in Python
<p>I have built a RAG system like this:</p> <pre><code>loader = PyPDFLoader(pdf_file_name) raw_documents = loader.load() text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200) documents = text_splitter.split_documents(raw_documents) print(documents[-1]) Document( metadata={'source': '/A...
<python><langchain><large-language-model>
2024-08-06 16:57:27
1
467
Nicolas REY
78,840,095
2,827,582
Datetime doesn't seem to be converting
<p>I am trying to cast from a 'created_at' value in UTC to a value in Eastern Time. But after converting the time using astimezone, the time is the same and raises the assert error that the two times are identical. I tried making the datetime aware by doing <code>f_time.replace(tzinfo=pytz.utc)</code> although I am not...
<python><datetime><strptime><pytz>
2024-08-06 16:22:59
1
1,542
Steve Scott
78,839,970
305,597
How can I add several help arguments using argparse, which don't require adding any required arguments?
<p>I'm using <code>ArgumentParser</code> to document the usage of a complicated program. Since the program has several long lists of capabilities, it requires several <code>--help</code> arguments.</p> <p>My current <code>ArgumentParser</code> looks like this.</p> <pre><code>parser = ArgumentParser(description = 'Compl...
<python><arguments><argparse>
2024-08-06 15:50:26
2
9,705
MartΓ­n Fixman
78,839,834
3,070,181
python extension not loading in vscode
<p>I have seen <a href="https://stackoverflow.com/questions/74466183/why-is-my-python-extension-not-loading-in-vscode-microsoft">this question</a> and <a href="https://stackoverflow.com/questions/72791043/how-would-i-fix-the-issue-of-the-python-extension-loading-and-extension-activati">this one</a></p> <p>Neither help ...
<python><visual-studio-code>
2024-08-06 15:14:02
1
3,841
Psionman
78,839,662
1,391,441
emcee refuses to properly explore function
<p>I have a 1D function that looks like this:</p> <p><a href="https://i.sstatic.net/EyatUXZP.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/EyatUXZP.png" alt="function to be fitted" /></a></p> <p>i.e. a pronounced drop towards a stable value around 0. The function is written as:</p> <pre><code>((1. / np...
<python><optimization><bayesian><emcee>
2024-08-06 14:40:54
1
42,941
Gabriel
78,839,616
2,197,296
Tensorrt installation issues in WSL
<p>I'm trying to get tensorrt working with Tensorflow 2.17, yet after trying all of the official and unofficial instructions several times I still can't get it to work and I'm at the edge of sanity. I've have installed CUDA 12.5 (as that's reported as the last version supported by tensorrt)</p> <pre><code>$ sudo apt-ge...
<python><tensorflow><ubuntu-22.04><tensorrt>
2024-08-06 14:30:20
0
1,266
Nicolas
78,839,580
1,576,804
Removing ```json and ``` from Markdown
<p>I have a result object from the code:</p> <pre><code>for fragment_string in fragment_strings: prompt = generate_prompt(fragment_string) messages = [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt}] result = chat_completion(messages) # Post-process the response to remove the &quo...
<python><json><markdown>
2024-08-06 14:22:45
1
4,234
vkaul11
78,839,568
17,311,709
Tableau data source not updating through hyper API
<p>I have a workbook containing one data source being an extract file, I'm trying to update this file through hyper API, this is how my code looks like :</p> <pre><code>with server.auth.sign_in(tableau_auth): # Get the project ID all_projects, pagination_item = server.projects.get() project_id =...
<python><tableau-api><tableau-cloud>
2024-08-06 14:21:21
0
635
Rafik Bouloudene
78,839,513
6,620,090
python import issue with similar directory structure
<p>I have the below directory structure:</p> <pre><code>project_root_dir β”œβ”€β”€ a β”‚Β Β  └── b β”‚Β Β  β”œβ”€β”€ __init__.py β”‚Β Β  └── test_cases.py └── subdir └── a └── b └── __init__.py </code></pre> <p>My <code>PYTHONPATH</code> env is set as below:</p> <pre><code>export PYTHONPATH=&lt;workspace_path&g...
<python><python-3.x><import>
2024-08-06 14:08:51
3
1,292
Rachit Tayal
78,839,482
5,568,409
Is it possible to plot a Voronoi tessellation directly from a previous Delaunay triangulation?
<p>I have a small Python code plotting a small Delaunay triangulation:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from scipy.spatial import Delaunay points = np.array([[0, 0], [1, 0], [0.5, 0.5], [1 , 0.5]]) tri = Delaunay(points) fi...
<python><python-3.x><matplotlib><voronoi><delaunay>
2024-08-06 14:03:10
1
1,216
Andrew
78,839,425
10,518,698
How to convert PPTX to PDF on a Non-Windows machine
<p>I'm sure many have come across this question, but I couldn't find any solutions for non-windows machines.</p> <p>I need to prepare a Python script that can run on Linux (multiple versions) as well as On Windows machines. The script should read a PPT file, and convert it into a PDF, then convert the PDF into images. ...
<python><python-pptx>
2024-08-06 13:51:28
1
513
JSVJ
78,839,378
16,591,917
Can you use python xlwings library to trigger VBA code
<p>I have a use case where I want to automate and interface an Excel model from The workflow would be something like:</p> <ol> <li>Transfer data from Python to Excel</li> <li>Execute macro to run model model to convergence (about 45secs)</li> <li>Wait for macro to a cell statues indicating completion.</li> <li>Collec...
<python><excel><xlwings>
2024-08-06 13:41:15
1
319
JacquesStrydom
78,839,329
34,509
Wheels created by "pip freeze" and "pip wheel" not usable with --no-index and --find-links?
<p>I created wheels from an existing venv, that resulted in, among others, the following wheel. The wheel was created within <code>docker</code>, with a Python version of 3.9 (the smallest possible versions were chosen to provide maximal compatibility)</p> <pre><code>wheels/codechecker-6.23.1-cp39-cp39-linux_x86_64.whl...
<python><linux><pip><python-wheel>
2024-08-06 13:33:36
1
509,594
Johannes Schaub - litb
78,839,287
3,494,328
f2py in numpy 2.0.1 does not expose variables the way numpy 1.26 did. How can I access Fortran variables in Python?
<p>I used to run a collection of Fortran 95 subroutines from Python by compiling it via f2py. In the Fortran source I have a module with my global variables:</p> <pre><code> MODULE GEOPLOT_GLOBALS IMPLICIT NONE INTEGER, PARAMETER :: N_MAX = 16 INTEGER, PARAMETER :: I_MAX = 18 INTEGER, PARAMETER ::...
<python><numpy><f2py>
2024-08-06 13:27:19
2
714
Peter KΓ€mpf
78,839,246
5,029,509
PyTorch and Opacus for Differential Privacy
<p>When testing an example code from the <strong>TensorFlow</strong> website using <strong>Jupyter Notebook</strong>, which is available <a href="https://www.tensorflow.org/responsible_ai/privacy/tutorials/classification_privacy" rel="nofollow noreferrer">here</a>, I encountered an error. You can find my SO question ab...
<python><tensorflow><machine-learning><pytorch><pysyft>
2024-08-06 13:17:08
1
726
Questioner
78,839,105
736,662
JSONPath extracting
<p>I have used an online helper, <a href="https://jsonpath.com/" rel="nofollow noreferrer">https://jsonpath.com/</a> to find a working jsonpath to extract a value from the attacehd json structure. The expressionis as follows:</p> <pre><code>$.activations[0].bidReference </code></pre> <p>How can I translate this into &q...
<python><json>
2024-08-06 12:47:03
2
1,003
Magnus Jensen
78,839,103
18,091,040
How to return plain text or JSON depending on condition?
<p>Is there a way to do something like this using FastAPI:</p> <pre class="lang-py prettyprint-override"><code>@app.post(&quot;/instance/new&quot;, tags=[&quot;instance&quot;]) async def MyFunction(condition): if condition: response = {&quot;key&quot;: &quot;value&quot;} return response else: ...
<python><fastapi>
2024-08-06 12:46:41
1
640
brenodacosta
78,839,092
11,357,695
Defining fixtures with variable import paths
<p>I am testing functions from different modules that use an imported helper function from <code>helpers.py</code>. I am monkeypatching this helper function in each module function's test (please see below). I would like to put <code>setup_do_thing()</code> and <code>mock_do_thing()</code> in a <code>conftest.py</cod...
<python><pytest><monkeypatching><pytest-fixtures>
2024-08-06 12:43:26
1
756
Tim Kirkwood
78,839,067
11,159,734
Azure SAS token does not expire even though expiry is specified
<p>I created a SAS token using the following python function:</p> <pre class="lang-py prettyprint-override"><code>from datetime import datetime, timedelta from azure.storage.blob import BlobServiceClient, BlobSasPermissions, generate_blob_sas def generate_sas_token(connection_string: str, container_name: str, blob_na...
<python><azure><azure-blob-storage>
2024-08-06 12:36:15
1
1,025
Daniel
78,839,059
3,183,808
Efficient sky searches with HEALPix-alchemy
<p>I am trying to implement a cone search for a catalog with the HEALPix-alchemy package. I have the following models set up, based on the examples here: <a href="https://arxiv.org/pdf/2112.06947" rel="nofollow noreferrer">https://arxiv.org/pdf/2112.06947</a></p> <pre><code>class Field(Base): &quot;&quot;&quot; ...
<python><sqlalchemy><orm><healpy><object-relational-model>
2024-08-06 12:34:32
0
435
jm22b
78,838,965
9,715,816
pip >24.0 causes Expected matching RIGHT_PARENTHESIS for LEFT_PARENTHESIS, after version specifier kubernetes (>=9.0.0a1.0) ; extra == 'all_extras'
<p>I am trying to install <code>prefect[kubernetes,azure]==1.4.0</code> using <code>pip</code>.</p> <p>It get installed successfully with <code>pip&lt;=24.0</code>.</p> <p>However with any <code>pip&gt;24.0</code> the installation fails. For example:</p> <pre><code># in a venv pip install pip==24.2 # released on 2024-0...
<python><pip>
2024-08-06 12:10:57
2
2,019
Charalamm
78,838,932
9,640,238
Fill NA in pandas column with new UUID
<p>My dataframe includes a column with UUID's. Some values may be missing, and I need to fill them with a new UUID.</p> <p>Of course, if I do:</p> <pre class="lang-py prettyprint-override"><code>df[&quot;B&quot;].fillna(str(uuid.uuid4())) </code></pre> <p>all missing entries will be filled with the same value, which is...
<python><pandas>
2024-08-06 12:03:08
2
2,690
mrgou