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,011,972
1,938,026
How to solve a case of circular imports with referencing dataclasses and default_factory?
<p>I'm writing a Python package in which there are a lot of units (classes, functions...) that are referencing each other. I face problems with circular imports.</p> <p>How to solve something like that:</p> <p>a.py:</p> <pre><code>from dataclasses import dataclass, field from .b import B from .c import C @dataclass c...
<python><import><python-import><circular-dependency><circular-reference>
2024-09-22 15:23:03
0
318
Damian
79,011,931
4,690,023
Is discord.py on_message listener a privacy issue?
<p>While writing a bot with <code>discord.py</code> I realised that it would be extremely easy for a developer to log all messages that would pass through the listener <code>on_message</code>.</p> <p>A simple <code>logging</code> call in the listen such as:</p> <pre><code>@commands.Cog.listener() async def on_message(s...
<python><discord><discord.py>
2024-09-22 14:59:38
1
1,870
Luca
79,011,915
1,581,090
How to create smooth interpolations between two images with OpenCV?
<p>I have been trying to create smooth interpolated images between two images (they might be a bit rotated, translated and/or zoomed) and came up with this function</p> <pre><code>def interpolate_images(image1, image2, n_interpolations): # Convert to grayscale for feature detection gray1 = cv2.cvtColor(image1, ...
<python><opencv><computer-vision><feature-matching>
2024-09-22 14:52:40
0
45,023
Alex
79,011,854
1,593,077
Failure trying to pip install in Cygwin: "UserWarning: unprocessed git archival found (no export subst applied)"
<p>I'm trying to install some Python packages on Cygwin, on an X86_64 machine running Windows 10.</p> <p>I've just updated my Cygwin distribution, and installed python. Now, using pip, some packages install fine, like <code>argparse</code>, but some just don't. The errors seem to be:</p> <ul> <li><code>UserWarning: gi...
<python><pip><cygwin><package-management><git-archive>
2024-09-22 14:26:41
1
137,004
einpoklum
79,011,778
9,030,200
How to reply emails with original content preserved using smtplib and imaplib
<p>I want to use Python's smtplib and imaplib to implement reading emails (such as Gmail, Exchange) and replying to the original email. What I want to do is read an email, add a new message to the original email while preserving the original message, just like using Gmail's reply function. The new message might be in H...
<python><html><smtplib><imaplib><reply>
2024-09-22 13:53:03
0
567
黃郁暉
79,011,631
11,165,214
How to change the resolution of a OpenStreetMaps figure?
<p>For a little design project, I want to use some geo data from OpenStreetMaps.</p> <p>Let's use the data from the little german coast village of Greetsiel for illustration of the issue.</p> <p>I use the following code snippet:</p> <pre><code>import osmnx as ox import matplotlib.pyplot as plt place_name = &quot;Greet...
<python><matplotlib><openstreetmap><geopandas><osmnx>
2024-09-22 12:36:58
1
449
Lepakk
79,011,622
1,403,470
How to prevent Pelican from copying Markdown source files into output folder?
<p>I am converting my Jekyll blog to Pelican. The directory structure of the source <code>content</code> folder uses <code>YYYY/MM/DD/slug.md</code> to organize blog posts and stores static files in <code>files/YYYY/filename.ext</code>. Static pages are in <code>pages/filename.md</code>:</p> <pre><code>content |-- 2023...
<python><pelican>
2024-09-22 12:32:55
1
1,403
Greg Wilson
79,011,621
184,379
Sqlite gives a value which I cannot recreate
<p>Using django: here is some values and the query:</p> <pre><code> max_played, avg_days_last_played = get_next_song_priority_values() # Calculate time since played using raw SQL time_since_played_expr = RawSQL(&quot;(julianday('now') - julianday(main_song.played_at))&quot;, []) query = Song.objects ...
<python><django><sqlite>
2024-09-22 12:32:28
1
17,352
Tjorriemorrie
79,011,599
395,857
How to fix "Invalid value for purpose." error when using Azure OpenAI GPT 4o mini batch?
<p>I try to use Azure OpenAI GPT 4o mini batch. I first need to create the batch. I ran:</p> <pre><code>import os from openai import AzureOpenAI client = AzureOpenAI( api_key=&quot;[insert Azure OpenAI API key here]&quot;, api_version=&quot;2023-07-01-preview&quot;, azure_endpoint=&quot;https://[insert Azu...
<python><azure><batch-processing><azure-openai><gpt-4>
2024-09-22 12:13:19
1
84,585
Franck Dernoncourt
79,011,417
4,412,929
Null values in log file from Python logging module when used with Dask
<p>I have been trying to setup logging using the <em>logging</em> module in a Python script, and I have got it working properly. It can now log to both the console and a log file. But if fails when I setup a Dask cluster. The first log message is now replaced with invalid/null values in the log file, while the console ...
<python><character-encoding><dask><dask-distributed><python-logging>
2024-09-22 10:28:02
0
363
RogUE
79,011,352
3,357,352
determine which system modules were loaded
<p>I'm trying to determine which python system modules are loaded:</p> <pre class="lang-py prettyprint-override"><code>In [1]: import sys In [2]: l = sorted(list(sys.modules.keys())) In [3]: 'json' in l Out[3]: True </code></pre> <p>According to <a href="https://docs.python.org/3/library/sys.html#sys.modules" rel="nofo...
<python><module>
2024-09-22 09:59:00
1
7,270
OrenIshShalom
79,011,203
3,203,158
PySpark: Throwing error 'Column' object is not callable while using .count()
<p>I'm working with a PySpark DataFrame and trying to count the number of null values in each column. I tried the following expression:</p> <pre><code>[col(c).isNull().count() for c in df.columns] </code></pre> <p>throws error:</p> <pre><code>----&gt; 2 [col(c).isNull().count() for c in df.columns] TypeError: 'Column' ...
<python><dataframe><pyspark><apache-spark-sql>
2024-09-22 08:23:31
1
922
aroyc
79,011,125
4,555,765
Assignin lists as elements of CUDF DataFrame
<p>While using Pandas, I can add lists as elements without issues, as in</p> <pre><code>import pandas as pd A = {&quot;cls&quot;: &quot;A&quot;} B = {&quot;cls&quot;: &quot;B&quot;} C = {&quot;cls&quot;: [&quot;A&quot;, &quot;B&quot;]} df = pd.DataFrame([A,B,C]) type(df.iloc[2][&quot;cls&quot;]) # Returns `list` </...
<python><pandas><dataframe><cudf>
2024-09-22 07:47:06
1
1,211
Lin
79,010,931
8,741,108
How to trigger a POST request API to add a record in a SQLite database table using FastAPI and HTML forms using Jinja2?
<p>I am trying to submit a HTML form from the browser to create a new user in a SQLite database table. Clicking on the Submit button triggers a POST request using FastAPI and Sqlalchemy 2.0. The API works perfectly when executed from the Swagger UI. But it does not work when triggered from an actual HTML form, returnin...
<python><sqlite><sqlalchemy><jinja2><fastapi>
2024-09-22 05:23:58
1
1,723
Code_Sipra
79,010,838
4,555,765
Neo4j results to JSON in Python
<p>While python Neo4j library, with bolt driver, when executing queries by <code>session.run(query)</code> I receive a result object that can be manipulated perfectly. In the other hand Neo4j browser interface, when executing a query, in table tab, it returns a string formatted as a JSON.</p> <p>Is there any function ...
<python><neo4j><bolt>
2024-09-22 03:43:47
1
1,211
Lin
79,010,712
13,634,560
advanced multi conditional list comprehension
<p>I am new to Python and would like to assign a value based on mathematical operations, eg &quot;right&quot; if &gt;, &quot;left&quot; if &lt;, &quot;equal&quot; if ==, within a list comprehension.</p> <p>I have tried the below, but it throws an error. Can multiple conditions be specified in a single list comprehensio...
<python><pandas>
2024-09-22 01:34:30
2
341
plotmaster473
79,010,633
1,332,263
How to Change Multiple Values in a json file
<p>I want to change the values in a json file. The json file contents are commented out. I want to change the values individually with having to write to the file separately for each value.</p> <pre><code>import json &quot;&quot;&quot; { &quot;keys&quot;: { &quot;developer&quot;: {}, &quot;personal...
<python><json>
2024-09-21 23:53:40
1
417
bob_the_bob
79,010,629
22,407,544
Running `collecstatic` returns [Errno 13] Permission denied in docker compose
<p>I run my django app in Docker. I recently tried running <code>collecstatic</code> and instead was given this error code:</p> <pre><code>&gt;docker-compose exec web python manage.py collectstatic </code></pre> <pre><code>Traceback (most recent call last): File &quot;/code/manage.py&quot;, line 22, in &lt;module&gt;...
<python><django><docker><docker-compose>
2024-09-21 23:49:43
0
359
tthheemmaannii
79,010,413
6,136,013
Annotate a constructor that delegates to another function
<p>I have a Python library that encapsulates an external c++ library that exposes its objects via handles. I have a root class</p> <pre><code>class ABObj: def __init__(self, *args, **kwargs): if is_handle(args[0]): self.handle = args[0] else: self.handle = self._make_obj(*arg...
<python><python-typing>
2024-09-21 20:29:14
0
681
BlindDriver
79,010,412
20,591,261
Efficiently Applying Multiple Operations to a Polars DataFrame Using a Custom Function
<p>I'm working with a Polars DataFrame and trying to clean up a column by applying multiple string operations. The first operation I need to do is a <code>str.replace()</code> to fix some inconsistencies in the string, and then I want to extract several values into new columns.</p> <p>My current approach:</p> <pre><cod...
<python><python-polars>
2024-09-21 20:27:52
1
1,195
Simon
79,010,316
344,669
How do I map a column to create an autoincrement primary key?
<p>My SQLAlchemy 2.0 mapped column with an SQLite database is creating a primary key column due to which I'm not able to insert.</p> <p>Mode class:</p> <pre><code>import datetime from typing import Optional from sqlalchemy import String, TIMESTAMP, Integer from sqlalchemy import func from sqlalchemy.dialects import po...
<python><sql><sqlite><sqlalchemy><flask-sqlalchemy>
2024-09-21 19:24:54
1
19,251
sfgroups
79,010,261
1,255,630
Finding the leftover rows in pandas dataframes
<p>If I'm detecting Ys in particular columns using this:</p> <pre><code>thing1 = df[df['column1'] == 'Y'] thing2 = df[df['column2'] == 'Y'] thing3 = df[df['column3'] == 'Y'] thing4 = df[df['column4'] == 'Y'] </code></pre> <p>How can I get all the rows that don't have Y in one of those columns? I have tried somethin...
<python><pandas><dataframe>
2024-09-21 18:46:58
2
1,258
thoth
79,009,823
14,506,951
Is there a faster way to crawl a predefined list of URLs with scrapy when having to authenticate first?
<p>I have two scrapy Spiders:</p> <ul> <li>Spider 1 crawls a list of product links (~10000) and saves them to a <code>csv</code> file using a feed. It doesn't visit each of those links, only the categories (with multiple pages). This Spider rarely needs to run, so speed is not an issue here.</li> <li>Spider 2 visits ea...
<python><web-scraping><scrapy><web-crawler>
2024-09-21 14:55:26
1
2,623
LoahL
79,009,679
2,989,330
PyCharm warning: Type of 'field' is incompatible with 'A' when implementing property from protocol
<p>I want to define an interface for a data class, but leave open the way the data is stored. To this end, I define a protocol <code>A</code> for the interface and an implementation <code>B</code>:</p> <pre><code>class A(Protocol): @property def field(self): ... @field.setter def field(self, va...
<python><pycharm><python-typing>
2024-09-21 13:35:46
1
3,203
Green 绿色
79,009,651
3,572,505
python nested dict multikey method suggestion
<p>apparently, there is no built-in dict method (let's call it <code>.nestkey</code>) for dynamic key addressing in multi-nested dict structures. this can be demanding when dealing with complex dict structures,</p> <p>e.g., <code>dic_1.nestkey(list_of_keys_A) = value</code> instead of manually doing <code>dic_1[&quot;k...
<python><dictionary><dynamic><nested><multikey>
2024-09-21 13:19:12
1
903
José Crespo Barrios
79,009,647
8,964,393
How to calculate the Exponential Moving Average (EMA) through record iterations in pandas dataframe
<p>I have created a pandas dataframe as follows:</p> <pre><code>import pandas as pd import numpy as np ds = { 'trend' : [1,1,1,1,2,2,3,3,3,3,3,3,4,4,4,4,4], 'price' : [23,43,56,21,43,55,54,32,9,12,11,12,23,3,2,1,1]} df = pd.DataFrame(data=ds) </code></pre> <p>The dataframe looks as follows:</p> <p>display(df)</p>...
<python><pandas><dataframe><iterator><calculated-columns>
2024-09-21 13:16:15
1
1,762
Giampaolo Levorato
79,009,603
12,190,301
Process inside daemon immediately exits when using FIFO
<p>I have a setup that looks roughly like the following example:</p> <pre class="lang-py prettyprint-override"><code>from contextlib import contextmanager import subprocess import os from pathlib import Path import daemon @contextmanager def tmp_fifo(path: Path): try: os.mkfifo(path) file = os.op...
<python><mkfifo><python-daemon>
2024-09-21 12:49:49
1
2,109
Schottky
79,009,454
6,449,621
Convert a list of time string to unique string format
<p>I have a list of time string with different formats as shown</p> <pre><code>time = [&quot;1:5 am&quot;, &quot;1:35 am&quot;, &quot;8:1 am&quot;, &quot;9:14 am&quot;, &quot;14:23 pm&quot;, &quot;20:2 pm&quot;] dict = {'time': time} df = pd.DataFrame(dict) </code></pre> <p>and wanted to replace strings in list ...
<python><pandas><dataframe>
2024-09-21 11:36:14
4
465
anandyn02
79,009,352
15,260,108
how to configure nginx so that front end and backend works in AWS
<p>i am deploying my app on AWS instance. i have both frontend and backend as docker image. i want to use nginx. when i run this config, and go to AWS given public URL, then 502 is returned by nginx. /api /docs they are working but /admin / returning 502. here is my conf files:<br /> docker-compose.yml:</p> <pre><code>...
<python><django><docker><nginx><nuxt.js>
2024-09-21 10:36:31
1
400
Diyorbek
79,009,315
19,556,055
Multiplying a 2D array with a 3D array of vectors in Numpy
<p>I have a dxd matrix that I would like to multiply with a dx1xn matrix. The idea is to get back another dx1xn matrix, so I would essentially like to multiply each dxd matrix with each dx1 matrix n times along that third axis. I have no idea how to go about this though. I have tried <code>np.apply_along_axis</code> an...
<python><arrays><numpy>
2024-09-21 10:18:42
2
338
MKJ
79,009,151
769,677
What is the difference between python requests and cURL?
<p>I have the following situation. I send a request from 3 sources (postman, cURL and python requests library). For Postman and cURL I receive the same response but for <strong>python requests</strong> library I get a different response(other HTML source) and I don't understand the difference:</p> <p>In Postman I send ...
<python><http><curl><python-requests>
2024-09-21 08:48:43
1
1,660
Adrian B
79,009,052
8,086,892
run docker command within python subprocess within GitHub runner
<p>I am running functional tests as CI in my GitHub runner. To properly execute my tests, I am building a docker image and running it (a slightly modified mysql container). Because I am building the container from a Dockerfile (not only pulling it from a registry), I dont use GitHub <code>service</code> or <code>contai...
<python><docker><subprocess><github-actions><pytest>
2024-09-21 08:03:48
1
347
mouch
79,008,714
1,234,799
Django Filter __In Preserve Order
<p>This question is regarding Django filtering, with <code>__In</code> clause. Basically, I am trying to understand how to filter by providing <code>videos.filter(video__in = video_ids)</code> with string ids, so that each row that gets returned has the same order as the order of string ids in the list used for filteri...
<python><django><database><data-structures>
2024-09-21 03:32:22
3
4,214
Patt Mehta
79,008,560
238,671
Identify duplicated groups in pandas
<p>Assume I have the following data</p> <pre><code>df = pd.DataFrame({ 'task_id': [1, 1, 1, 1, 2, 2, 2, 2], 'job_id': [1, 1, 2, 2, 0, 0, 1, 1], 'filename': ['filename1', 'filename2', 'filename33', 'filename2342', 'filename1', 'filename2', 'filename33', 'filename5'] }) </code></pre> <pre><code> task_id jo...
<python><pandas>
2024-09-21 00:27:34
1
17,832
Ruggero Turra
79,008,480
1,658,617
Does Cython guarantee __dealloc__ order in __mro__?
<p>Does Cython respect the <code>__mro__</code> in case of <code>__dealloc__</code>?</p> <p>For example, in the case of inheritence:</p> <pre><code>cdef class A: def __dealloc__(self): # Deallocate cdef class B(A): def __dealloc__(self): # Deallocate some more </code></pre> <p>Is <code>B.__dealloc__</c...
<python><memory-management><cython>
2024-09-20 23:09:04
1
27,490
Bharel
79,008,391
1,713,850
Grabbing a specific url from a webpage with re and requests
<pre><code>import requests, re r = requests.get('example.com') p = re.compile('\d') print(p.match(str(r.text))) </code></pre> <p>This always prints None, even though r.text definitely contains numbers, but print(p.match('12345')) works. What do I need to do to r.text to make it readable by re.compile.match()? Casting...
<python><regex><python-requests><python-re>
2024-09-20 22:15:34
1
728
Red Dwarf
79,008,369
1,921,352
Rumble RSS feed - gives 403 when called with a python urllib.request
<p>The iine of code failing is</p> <pre><code> req = urllib.request.Request(url) </code></pre> <p>A rumble RSS feed address that works fine typed into a browser address line returns a '403 - authorisation will not help'.</p> <p>A youtube RSS feed address works fine, other RSS feed addresses work fine.</p> <p...
<python><rss><rumble-api>
2024-09-20 22:07:20
1
1,497
pperrin
79,008,316
1,422,096
Parameter encoded with encodeURIComponent, how to get it in a Python Bottle server?
<p>Let's say I send a request with JavaScript:</p> <pre class="lang-javascript prettyprint-override"><code>fetch(&quot;/query?q=&quot; + encodeURIComponent(&quot;c'est un château? Yes &amp; no!&quot;)); </code></pre> <p>to a Python Bottle server:</p> <pre class="lang-python prettyprint-override"><code>from bottle impor...
<javascript><python><bottle><encodeuricomponent>
2024-09-20 21:32:31
1
47,388
Basj
79,008,301
2,278,511
FLET: Matematical operation on value in Slider controls
<p>I have specific problem and i don't understand how to solve it :/</p> <p>Source: <a href="https://flet.dev/docs/controls/slider" rel="nofollow noreferrer">FLET Slider Example</a></p> <pre class="lang-py prettyprint-override"><code>import flet as ft def main(page): def slider_changed(e): t.value = f&quo...
<python><flutter><flet>
2024-09-20 21:23:03
1
408
lukassliacky
79,008,185
13,634,560
median() tries to change column to numeric
<p>I am using median() inside of an if-else list comprehension as such:</p> <pre><code>summary_frame = pd.DataFrame({ # ... &quot;50%&quot;: [df[col].median() if &quot;float&quot; or &quot;int&quot; or &quot;time&quot; in str(df[col].dtype) else df[col].mode() for col in df.columns] # ... }) </code></pre> <p>where if t...
<python><pandas><typeerror>
2024-09-20 20:32:28
1
341
plotmaster473
79,008,149
1,415,405
Implement a scipy Butterworth filter to operate on data contained in a sequence of numpy arrays
<p>I have seen code examples of how to use the scipy Butterworth filter to filter data stored in a numpy array.</p> <p>I need to do something slightly different. I want to process the data in blocks.</p> <p>As an example, if the total signal is 4096 samples long, I would like to process the first 1024 samples and outpu...
<python><numpy><filter><scipy><butterworth>
2024-09-20 20:18:14
1
498
Martin McBride
79,008,105
4,129,091
Passing an Enum as a tool to a client: "TypeError: Object of type ModelMetaclass is not JSON serializable"
<p>I'm attempting to call a tool in langchain.</p> <p>The function takes an <code>IntEnum</code> input. It rolls a dice and returns a random integer.</p> <pre class="lang-py prettyprint-override"><code>import random from enum import IntEnum from dotenv import load_dotenv from langchain.tools import Tool, tool from lan...
<python><pydantic><langchain><py-langchain>
2024-09-20 19:52:44
1
3,665
tsorn
79,008,061
4,298,208
Proper way to process larger-than-memory datasets in Polars
<p>I have begun to learn and implement Polars because of (1) the potential speed improvements and (2) for the promise of being able to process larger-than-memory datasets. However, I'm struggling to see how the second promise is actually delivered in specific scenarios that my use case requires.</p> <p>One specific exa...
<python><python-polars>
2024-09-20 19:35:00
1
2,630
aaronsteers
79,008,055
4,635,580
Difference in validation result using `jsonschema` and `check-jsonschema` in regard to a field with value of date-time
<p>Given <code>model_schema.json</code></p> <pre class="lang-json prettyprint-override"><code>{ &quot;properties&quot;: { &quot;dt&quot;: { &quot;format&quot;: &quot;date-time&quot;, &quot;title&quot;: &quot;Dt&quot;, &quot;type&quot;: &quot;string&quot; } }, &quot;required&quot;: [ ...
<python><jsonschema>
2024-09-20 19:32:48
2
739
Isaac To
79,007,935
307,149
PyQt QMessageBox is Blocking, or not?
<p>I have some operations that take place in the <strong>init</strong>() phase of my GUI. It looks for the presence of a file in a particular location and if it finds it, it will pop up a message box asking the user if they want to load the settings in that file. When I place that operation in the <strong>init</stron...
<python><qt><pyqt><pyside><qmessagebox>
2024-09-20 18:42:49
0
645
spickles
79,007,795
10,319,707
Pymssql: "DBPROCESS is dead or not enabled" error every time I run my sixth query, no matter how many times I rerun in one day
<h2>The Problem</h2> <p>I have an AWS Glue job that uses the <a href="https://aws.amazon.com/blogs/big-data/aws-glue-python-shell-now-supports-python-3-9-with-a-flexible-pre-loaded-environment-and-support-to-install-additional-libraries/" rel="nofollow noreferrer">standard set of analytics libraries</a> with Python She...
<python><sql-server><amazon-web-services><aws-glue><pymssql>
2024-09-20 17:47:23
1
1,746
J. Mini
79,007,782
2,287,458
Polars when().then(map_elements(function)) always calls function
<p>I have this code:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl def get_year(entry_id: str) -&gt; str: arr = entry_id.split('.') print(f'&gt; Function is called for {entry_id} &lt;') if arr[0] != 'DEBT': return None else: return int(arr[1]) df = pl.DataFram...
<python><performance><vectorization><python-polars>
2024-09-20 17:42:03
4
3,591
Phil-ZXX
79,007,637
6,431,715
python: ssl.wrap_socket - cert.pem vs. cert & key
<p>I'm running SFTP server with the following code:</p> <pre><code>httpd= HTTPServer (('10.0.0.10',4443), MyHandler) httpd.socket = ssl.wrap_socket (httpd.socket, keyfile='private.key', certfile='cert.pem', server_side=True) httpd.serve_forever () </code></pre> <p>It's working fine.</p>...
<python><ssl>
2024-09-20 16:52:59
0
635
Zvi Vered
79,007,518
9,392,446
Find duplicates from pandas column of nested lists within previous rows with multiple conditions
<p>I'm a little confused on how to code this.</p> <p>I have a dataset like this:</p> <pre><code>rules user_list event_time row_number rule1 123,244,344 2024-09-20 1 rule1 125,346,421 2024-09-19 2 rule1 125,343,431 2024-09-18 3 rule2 125,344,423 2024-09...
<python><pandas>
2024-09-20 16:13:54
1
693
max
79,007,387
3,258,380
Python 3 superclass instantiation via derived class's default constructor
<p>In this code:</p> <pre><code>class A(): def __init__(self, x): self.x = x def __str__(self): return self.x class B(A): def __str__(self): return super().__str__() b = B(&quot;Hi&quot;) print(b) </code></pre> <p>The output is: <code>Hi</code>.</p> <p>What is happening under the hood? How does t...
<python><python-3.x>
2024-09-20 15:23:32
2
698
Aroonalok
79,007,264
1,084,684
Upload large files (multipart) with md5 verification, using same code for both AWS S3 and Alibaba OSS?
<p>I'm hoping to upload (potentially) large files (up to 5 Gig) to both Amazon S3 and Alibaba OSS, with verification - preferably MD5 verification.</p> <p>My code currently looks like:</p> <pre><code>#!/usr/bin/env python3.10 &quot;&quot;&quot; This toy program is an exploration of how to do verified, multipart file u...
<python><amazon-web-services><amazon-s3><boto3><alibaba-cloud-oss>
2024-09-20 14:49:17
1
7,243
dstromberg
79,007,232
485,337
How to create a factory function that preserves generic type information in Python?
<p>I have the following function that returns a class with a generic type parameter:</p> <pre class="lang-py prettyprint-override"><code>T = TypeVar('T') def create_property(event_bus: EventBus): class Property(Generic[T]): def __init__(self, validator: Callable[[T], bool]): self._validator = v...
<python><generics><python-typing>
2024-09-20 14:38:10
1
30,760
Adam Arold
79,007,161
457,290
can columns be kept in ruamel.yaml?
<p>I'm reading a YAML file, manipulating it and dumping it again with <a href="https://pypi.org/project/ruamel.yaml/" rel="nofollow noreferrer"><code>ruamel.yaml</code></a>. I'd like to get it as much human readable as it was before. That requires some tables to be kept in columns.</p> <p>This is a short example of wha...
<python><ruamel.yaml>
2024-09-20 14:19:56
1
2,019
matiasg
79,007,120
2,130,515
How tox create a fresh environments
<p>Here is my workflow:</p> <p>I have a requirements.txt file that includes tox and many other packages.</p> <p>Run:</p> <pre><code> python3 -m venv global_env source global_env/bin/activate pip install -r requirements </code></pre> <p>I create a tox.ini as following and I call all the different env in the jenki...
<python><unit-testing><pytest><tox>
2024-09-20 14:10:14
1
1,790
LearnToGrow
79,007,107
4,352,047
Langchain FastEmbed with ChromaDB
<p>I'm trying to follow a simple example I found of using Langchain with FastEmbed and ChromaDB. I will eventually hook this up to an off-line model as well. I believe I have set up my python environment correctly and have the correct dependencies. Just am I doing something wrong with how I'm using the embeddings and t...
<python><py-langchain><chromadb>
2024-09-20 14:06:20
2
379
Deftness
79,006,887
1,117,028
Regular expression to match contents of double brackets containing other groups of double brackets
<p>I would like to clean-up raw data from a Wiktionary dump. Here are two usecases.</p> <p>Multilines:</p> <pre><code>[[Archivo:Diagrama bicicleta.svg|400px|miniaturadeimagen|'''Partes de una bicicleta:'''&lt;br&gt; [[asiento]] o [[sillín]], [[cuadro]]{{-sub|8}}, [[potencia]], [[puño]]{{-sub|4}}, [[cuerno]], [[manubrio...
<python><regex>
2024-09-20 13:07:49
1
7,220
Tiger-222
79,006,776
4,443,260
AssertionError when launching python via systemd
<p>I seem to be getting an AssertionError with my Python script, but only when I launch it through <code>systemd</code>. Otherwise, it works fine if launched manually from the command line. I thought perhaps it's a permissions thing, but it also runs fine being manually executed as root.</p> <p><a href="https://i.sstat...
<python><service><systemd><mavlink>
2024-09-20 12:37:39
1
923
Kris Rice
79,006,736
22,466,650
How to make a function accessible from both the object and the class itself?
<p>I have a simple class called <code>Storage</code> that has many methods and properties.</p> <p>For this question, I'm only interested in making <code>uniques</code> a classmethod and a property in the same time. I don't know if this is possible. I wonder if there is a dynamic processing : based on if <code>uniques</...
<python><class><oop>
2024-09-20 12:27:15
3
1,085
VERBOSE
79,006,642
6,930,340
Multiply elements of list column in polars dataframe with elements of regular python list
<p>I have a <code>pl.DataFrame</code> with a column comprising lists like this:</p> <pre><code>import polars as pl df = pl.DataFrame( { &quot;symbol&quot;: [&quot;A&quot;, &quot;A&quot;, &quot;B&quot;, &quot;B&quot;], &quot;roc&quot;: [[0.1, 0.2], [0.3, 0.4], [0.5, 0.6], [0.7, 0.8]], } ) shape...
<python><dataframe><list><python-polars>
2024-09-20 11:58:52
4
5,167
Andi
79,006,506
3,218,338
Google Cloud Speech-To-Text tagging requests for billing purposes
<p>I am looking to reduce the amount of hassle we get by managing multiple customers within the same app. Today we're using service account JSON files for authentication, one file for each customer. We do this to separate billing accordingly. This basically means that each customer is its own project within the Google ...
<python><google-cloud-platform><speech-recognition>
2024-09-20 11:15:55
0
682
user3218338
79,006,487
10,639,382
Plotly Chlorepath Map Subplot
<p>I have geopandas dataframe as show below. I want to create subplots where each subplot would have a map.</p> <p>I managed to do a Single plot using plotly express</p> <pre><code>p4 = px.choropleth(s_new_cp, geojson=s_new_cp.geometry, color = &quot;usage&quot;, locations = s_new_cp.index) p4.update_geos(fitbounds=&qu...
<python><plotly>
2024-09-20 11:10:08
0
3,878
imantha
79,006,427
3,976,229
SQLModel how to find foreign_key information while introspecting SQLModel classes?
<p>I am looping through my SQLModel classes, extracting the field info, and creating a .dbml format file from the details. This works great, except trying to find the foreign_key information in the fields. Here is an example of an SQLModel classes:</p> <pre><code> class Account(PostgresBase, table=True): __tablenam...
<python><sqlmodel>
2024-09-20 10:49:06
1
362
havoc1
79,006,254
7,499,018
FastHTML fail to load
<p>When loading the <a href="https://www.fastht.ml/" rel="nofollow noreferrer">fastHTML</a> demo example the browser page for <a href="http://0.0.0.0:5001" rel="nofollow noreferrer">http://0.0.0.0:5001</a> shows invalid address:</p> <p>This site can't be reached. ERR_ADDRESS_INVALID Site might be temporarily down...</p...
<python><fasthtml>
2024-09-20 09:53:33
2
487
Martin Cronje
79,006,122
8,790,507
Is there a way to test only a subset of unittests in a jupyter notebook?
<p>I followed the unittest example in this answere here: <a href="https://stackoverflow.com/a/48405555/8790507">https://stackoverflow.com/a/48405555/8790507</a></p> <p>I have two test classes in two cells, so something like:</p> <p>First cell:</p> <pre><code>class TestSuite1(unittest.TestCase): def test_in_suite1(s...
<python><unit-testing><jupyter-notebook><python-unittest>
2024-09-20 09:20:33
1
1,594
butterflyknife
79,006,060
9,973,879
Click a button to go to a URL in a Jupyter notebook
<p>I want to be able to open <code>http://example.com</code> when clicking on an <code>ipywidgets.Button</code> (ideally in the same tab).</p> <p>I tried</p> <pre class="lang-py prettyprint-override"><code>def on_click(btn): display(Javascript('window.open(&quot;http://example.com&quot;);')) </code></pre> <p>and</p> ...
<python><jupyter-notebook><jupyter-lab><ipywidgets>
2024-09-20 09:05:16
1
1,967
user209974
79,005,800
5,507,055
How to show enum keys in OpenAPI?
<p>I use <code>EnumInt</code> and want to show the enum keys at the OpenAPI docs.</p> <pre><code>from enum import IntFlag from pydantic import BaseModel class ResponseCode(IntFlag): request_failed: 1000 request_success: 1001 class Response(BaseModel): success: bool message: str code: ResponseCode...
<python><enums><fastapi><openapi>
2024-09-20 07:53:37
0
2,845
ikreb
79,005,484
2,192,824
How to dynamically create a protobuf object from string?
<p>I have a protobuf definition like below,</p> <pre><code>message MyProto { optional string ip = 1; optional int32 port = 2; optional Flags flags = 3; } message Flags { optional bool flag1 = 1; optional bool flag2 = 2; } </code></pre> <p>My goal is to create a MyProto object from the below string...
<python><protocol-buffers>
2024-09-20 06:26:10
0
417
Ames ISU
79,005,424
12,035,739
Why do I get a value error while creating a ragged array but only for a certain shape?
<pre class="lang-py prettyprint-override"><code>import numpy as np for h in range(10): try: array = np.array([np.zeros((h, 4)), np.zeros((3, h))], dtype=object) except ValueError: print(f'Value Error for h={h} only.') </code></pre> <p>In the above code, <code>ValueError</code> only happens for ...
<python><numpy>
2024-09-20 06:07:16
1
886
scribe
79,005,356
3,404,377
Can I load docutils nodes directly as an XML file?
<p>A <a href="https://docutils.sourceforge.io/docs/ref/doctree.html" rel="nofollow noreferrer">docutils document</a> is based on a hierarchy of nodes. They say throughout that the nodes are XML (or at least XML-like) and there are ways to dump documents and document fragments in XML format. They even produce a <a href=...
<python><xml><python-sphinx><docutils>
2024-09-20 05:36:18
1
1,131
ddulaney
79,005,148
1,530,967
What does `get_type_analyze_hook` return in a MyPy plugin that handles subtypes created by __class_getitem__ and recapitulate the __subclasshook__?
<p>(NB: repost of a question that was deemed not specific enough and then auto-deleted before I got a chance to revise it)</p> <p><strong>Background tl;dr</strong></p> <p>I contribute to a scientific worklow engine called <a href="https://pydra.readthedocs.io/en/latest/" rel="nofollow noreferrer">Pydra</a>, which utili...
<python><mypy>
2024-09-20 03:59:04
0
594
Tom Close
79,005,098
10,829,044
Modifying range in Traffic light Iconset in Openpyxl
<p>I have a sample data in excel like as below</p> <pre><code>cust_id,avg_purchase 1,0.2 2,0.5 3,100 4,9 5,1 6,31 7,9.5 8, &quot;No purchase&quot; 9, &quot;No purchase&quot; </code></pre> <p>I would like to do the below using Openpyxl</p> <p>a) Insert traffic light symbol for column B that is 'avg_purchse' based on the...
<python><excel><dataframe><openpyxl><conditional-formatting>
2024-09-20 03:34:02
0
7,793
The Great
79,005,032
4,875,641
How to have a pool of Python tasks wait for a wake up event
<p>I have created a pool of Python processes with the multiproccessing.pool function, any of which performs similar work. This is to have more work done simultaneously.</p> <p>I would like all of the tasks to wait on one event/signal/semafore or other object that has the tasks sleeping until signaled. They will perform...
<python><events><multiprocessing><wait><wakeup>
2024-09-20 02:44:39
1
377
Jay Mosk
79,005,011
4,451,521
Loading yaml config files twice
<p>I am following and analyzing a code from a course on ML deployment and I found something puzzling. (This question is not related to the ML part of the code)</p> <p>The ML pipeline uses some values that are in a config file. This config file is a yaml file.</p> <p>This yaml file is provided to the scripts that need i...
<python><config>
2024-09-20 02:32:09
1
10,576
KansaiRobot
79,004,901
4,577,467
How to pass byte buffer from C++ to Python using SWIG?
<p>I am using SWIG version 4.0.2 in a Windows Subsystem for Linux (WSL) Ubuntu distribution. The C++ class I want to wrap contains an array of bytes (i.e., each item in the array is of type <code>uint8_t</code> or <code>unsigned char</code>). The C++ class has a method whose output parameter is a double pointer, so t...
<python><c++><swig>
2024-09-20 01:13:37
1
927
Mike Finch
79,004,858
1,079,110
How can I wait for a threading event and socket pollin at the same time?
<p>I have a <code>select.poll()</code> object for incoming messages of a socket, and a <code>queue.Queue()</code> object that contains potential outgoing messages.</p> <p>While both objects separately support waiting for a timeout without spending CPU cycles, I need to wait on both at the same time and resume the threa...
<python><multithreading><sockets><unix>
2024-09-20 00:32:18
1
34,449
danijar
79,004,806
5,937,757
Streamlit (python) App button issue: Showing Previous Number After Button Click Instead of New Random Number
<p>I'm building a simple Streamlit app as a demonstration of a larger project I'm working on. The goal is to display a random number between 0-100 and let the user select whether they &quot;like&quot; the number or not. After the user clicks either &quot;Yes&quot; or &quot;No,&quot; the app should store the number and ...
<python><button><streamlit>
2024-09-19 23:53:29
1
423
mas
79,004,785
7,366,596
Merge intervals based on condition
<p>This is the classical approach to merge intervals:</p> <pre><code>def merge(intervals: List[List[int]]) -&gt; List[List[int]]: result = [] intervals.sort() prev_interval = intervals[0] for curr_interval in intervals[1:]: if prev_interval[1] &gt;= curr_interval[0]: # Check if they ov...
<python><algorithm><data-structures><intervals>
2024-09-19 23:32:56
1
402
bbasaran
79,004,666
12,299,000
Why does `ismethod` return False for a method when accessed via the class?
<p>Define a simple method:</p> <pre class="lang-py prettyprint-override"><code>class Foo: def bar(self): print('bar!') </code></pre> <p>Now use <code>inspect.ismethod</code>:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; from inspect import ismethod &gt;&gt;&gt; ismethod(Foo.bar) False </...
<python><python-inspect>
2024-09-19 22:29:11
1
51,583
kaya3
79,004,528
3,906,713
Does numpy implement indexed choice function
<p>Here is an indexed choice function</p> <pre><code>def np_ifelse( x: np.ndarray[float] | float, ind: bool | np.ndarray[bool], v1: float, v2: float ) -&gt; float | np.ndarray[float]: if isinstance(x, np.ndarray): y = np.full_like(x, v2) y[ind] = v1 return y else: ...
<python><numpy>
2024-09-19 21:33:41
1
908
Aleksejs Fomins
79,004,499
6,618,225
Get certain value from column with varying row index in Pandas
<p>I am using Pandas to process numerous Excel files and I need to extract certain values from columns. The position within the column (the row) may vary but the name of the column remains the same throughout the files as does the start of the desired value which always starts with 'K_'.</p> <p>The only way I can come ...
<python><pandas>
2024-09-19 21:20:02
1
357
Kai
79,004,263
5,867,094
Write pandas dataframe to excel consume too much memory
<p>I am using this code to write a dataframe into Excel file:</p> <pre class="lang-py prettyprint-override"><code>with pd.ExcelWriter(file_data, engine='xlsxwriter',engine_kwargs={&quot;options&quot;: {&quot;strings_to_formulas&quot;: False}}) as writer: df.to_excel(excel_writer=writer,sheet_name=&quot;data&quot;,i...
<python><excel><pandas><memory>
2024-09-19 20:04:13
1
891
Tiancheng Liu
79,004,136
2,962,555
Got "PydanticUserError" when import ChatGroq
<p>I have following packages installed</p> <pre><code>langchain_core==0.2.39 langchain==0.2.16 langchain-community==0.2.16 langchain_groq==0.1.10 langchain_openai==0.1.24 fastapi==0.114.2 redis pyyaml </code></pre> <p>However, when I try to</p> <pre><code>from langchain_groq import ChatGroq </code></pre> <p>I got error...
<python><langchain><groq><langchain-agents>
2024-09-19 19:22:22
3
1,729
Laodao
79,004,026
674,039
Why doesn't the future barry_as_FLUFL work in a .py file?
<p>There is a future statement which enables using the diamond operator <code>&lt;&gt;</code> instead of <code>!=</code> for equality comparisons.</p> <p>Here is a demonstration in a REPL:</p> <pre><code>&gt;&gt;&gt; from __future__ import barry_as_FLUFL &gt;&gt;&gt; print(1 &lt;&gt; 2) True &gt;&gt;&gt; 1 != 2 File ...
<python>
2024-09-19 18:47:05
0
367,866
wim
79,003,971
9,973,879
How can I plot an interactive matplotlib figure without the figure number in a Jupyter notebook?
<p>I am using matplotlib with the <code>%matplotlib widget</code> in a Jupyter lab notebook. When I display a figure, there is &quot;Figure 1&quot; displayed just above it. How can I get rid of it?</p> <p>I have found that <code>plt.figure(num='', frameon=False)</code> does show a figure without this prefix, however it...
<python><matplotlib><jupyter-notebook><jupyter-lab><matplotlib-widget>
2024-09-19 18:30:11
1
1,967
user209974
79,003,823
1,491,895
Is there any use for a top-level global variable declaration?
<p>In Python, the <code>global</code> declaration is used inside function definitions to specify that assigning the variable will create/update a global variable, rather than the default local variable.</p> <p>Python also allows the <code>global</code> statement outside of function definitions. This doesn't cause an er...
<python><global-variables>
2024-09-19 17:44:47
1
788,391
Barmar
79,003,679
22,407,544
How to change Root User to Custom User in Dockerfile
<p>I've been attempting to make all users in my Dockerfile to custom user as when running <code>collectstatic</code> in my Django app, I get a error message:</p> <pre><code> [Errno 13] Permission denied: /code/static/admin/js/vendor/select2/i18n/pl.6031b4f16452.js.gz' </code></pre> <p>I also want to do so for securit...
<python><django><docker>
2024-09-19 17:01:07
1
359
tthheemmaannii
79,003,623
11,770,390
Get icons from X apps that don't have _NET_WM_ICON property set
<p>I'm trying to extract the icon from an xwindow, namely the one from <code>Obsidian</code> which doesn't seem to have the <code>_NET_WM_ICON</code> property set. How can I still extract this icon information? Is there another way? I'm using python-xlib right now.</p>
<python><ubuntu><x11><xorg><window-managers>
2024-09-19 16:44:11
1
5,344
glades
79,003,530
1,872,357
Parse Base64 Email Attachment in Python
<p>I created an Agent to review emails I forward to it. Emails are sent by AWS SES, stored in S3, and pushed to an SQS queue, which I read in my Python server.</p> <p>**Unfortunately, I could not extract the base64 attachment from the email. While I manage to read the Sender, Recipient, and other metadata. In the end, ...
<python><email><base64><amazon-ses>
2024-09-19 16:15:40
0
768
ilbets
79,003,448
1,658,617
Py_INCREF in Cython accepts Python object but not pointer
<p>I have a small implementation of a linked list in Cython, and I wish to add a value to the list.</p> <p>For some reason, when I try to <code>Py_INCREF</code> (to make sure I keep a strong reference in each node), Cython does not accept a pointer to the Python object, but only the object itself:</p> <pre><code>ctyped...
<python><cython>
2024-09-19 15:54:07
1
27,490
Bharel
79,003,432
5,454
Why is mypy issuing import-not-found errors on every single import?
<p>I am writing a simple Python application using FastAPI. I am using pdm as my package manager which means I have a pyproject.toml file and a pdm.lock file. I also using pyenv to manage both versions of Python installed on my system as well as virtual environments. So in this case, I started off creating my project by...
<python><mypy><pyenv><pyenv-virtualenv>
2024-09-19 15:50:01
1
10,170
soapergem
79,003,375
10,962,766
API changes when using app_store_scraper in Python?
<p>Last summer, I created code for scraping Apple podcast reviews based on the official documentation provided for app-store-scraper:</p> <p><a href="https://pypi.org/project/app-store-scraper/" rel="nofollow noreferrer">https://pypi.org/project/app-store-scraper/</a></p> <p>Here is the relevant section from my longer ...
<python><pandas><app-store>
2024-09-19 15:38:14
0
498
OnceUponATime
79,003,290
3,259,222
How to align xarray dimensions without performing calculation?
<p>I have 2 DataArrays with partially overlapping dimensions. If I perform any calculation the dimensions of the result are auto aligned according to the exact matches between the overlapping dimensions.</p> <p>How can I achieve the same result without performing the redundant calculation below:<code>y_da.y * x_da.x/x_...
<python><python-xarray>
2024-09-19 15:16:59
1
431
Konstantin
79,003,259
11,370,582
Return an Error Message in Plotly Dash and place at the top of the page
<p>I have a fairly complex visualization tool I created in Plotly Dash, so I won't share the entire code, though what I am trying to do is return an error message using a try/except block.</p> <pre><code>except Exception as e: print(e) return html.Div([ html.B('THERE WAS AN ERROR...
<python><pandas><plotly><plotly-dash><dashboard>
2024-09-19 15:08:58
1
904
John Conor
79,003,145
12,730,406
Python - Parent and Child Class inheritance - attribute inheritance
<p>If I have this parent class to define a profile:</p> <pre><code>class Profile: # this is the class constructor def __init__(self, account_holder, account_type, value): self.account_holder = account_holder self.account_type = account_type self.value = value # some methods for ...
<python><oop>
2024-09-19 14:49:31
1
1,121
Beans On Toast
79,003,089
926,459
azure function .python_packages missing
<p>I have an azure function app to which I am trying to deploy some python code to via zip upload through the CLI. I can get a hello world application to run but I cannot add external libraries. I added a requirements.txt in my root folder but this is not being picked up.</p> <p>Many solutions and suggestions I found o...
<python><azure><pip><azure-functions>
2024-09-19 14:36:58
2
2,209
matteok
79,003,081
8,037,521
Faster voxelization with inverse indices
<p>I am using the following piece of code to get a <code>voxelized</code> point cloud <strong>with inverse indices</strong> so that I can compute the e.g. mask on the downsampled point cloud and then apply it on the original point cloud by getting the original points through inverse indices.</p> <pre><code>def voxelize...
<python>
2024-09-19 14:35:08
1
1,277
Valeria
79,003,055
13,469,674
Langgraph tools_condition prebuilt method routing to other nodes instead of END node
<p>I was building quite a simple graph using Langgraph. I decided the pre-built tools_condition function from langgraph. So I imported it and used it as follows:</p> <pre><code>graph_builder = StateGraph(State) graph_builder.add_node(&quot;chatbot&quot;, assistant) graph_builder.add_node(&quot;tools&quot;, lambda state...
<python><langchain><langgraph>
2024-09-19 14:31:08
2
955
DPM
79,003,021
17,721,722
How to Read Multiple CSV Files with Skipping Rows and Footer in PySpark Efficiently?
<p>I have several CSV files with an inconsistent number of data rows without a header row and I want to read these files into a single PySpark DataFrame. The structure of the CSV files is as follows:</p> <pre><code>data1,data2 data1,data2,data3 data1,data2,data3,data4,data5,data6 data1,data2,data3,data4...
<python><python-3.x><apache-spark><pyspark><apache-spark-sql>
2024-09-19 14:23:24
2
501
Purushottam Nawale
79,002,987
12,647,231
Vault does not return token renewed by script
<p>I write a script for renewing Hashicorp Vault tokens. But I faced an issue. When the token renewed automatically by the script Vault retuns n/a instead of token value so I cannot save it anywhere, to kubernetes secret, for example.</p> <p>Output looks like this:</p> <pre><code>--- ----- token ...
<python><python-3.x><kubernetes><hashicorp-vault><vault>
2024-09-19 14:14:37
1
1,677
poisoned_monkey
79,002,984
10,722,752
How to save all Plotly express graphs created using a for loop in a PDF?
<p>I am trying to save all the charts generated through a for loop in a SINGLE PDF file.</p> <p>My sample data:</p> <pre><code>import pandas as pd import numpy as np import plotly.io as pio import plotly.express as px import plotly.graph_objects as go np.random.seed(0) df = pd.DataFrame({'State' : np.repeat(['NY', 'TX...
<python><pandas><plotly><pypdf>
2024-09-19 14:14:29
1
11,560
Karthik S