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,133,259
4,093,019
Corrupted display from QPixmap.fromImage
<p>When running the following code, I find that the displayed image is corrupt - consistently on Windows, intermittently on macOS.</p> <pre class="lang-py prettyprint-override"><code>from PyQt6.QtCore import Qt from PyQt6.QtGui import QImage, QPixmap from PyQt6.QtWidgets import QWidget, QApplication, QLabel, QVBoxLayou...
<python><pyqt><pyqt6>
2024-10-28 11:51:45
0
1,039
radarhere
79,133,141
4,878,478
Encoding/Decoding in Spring Boot
<p>I have a Spring Boot application (A1), and I need to invoke another application (A2) via Rest API. A1 is written in Java + Spring Boot while A2 is written in python and tornado. A1 is trying to invoke /Get that is exposed by A2. The /Get url is something like: <code>https:123.456:123/something?industry=Test Data O&a...
<python><java><spring-boot><microservices><tornado>
2024-10-28 11:19:08
1
328
Rahul
79,132,931
22,963,183
ConnectionError when initializing BM25Assembler in DB-GPT
<p>I'm trying to set up <a href="https://github.com/eosphoros-ai/DB-GPT/blob/main/examples/rag/bm25_retriever_example.py" rel="nofollow noreferrer">a simple example</a> in <a href="https://github.com/eosphoros-ai/DB-GPT?tab=readme-ov-file" rel="nofollow noreferrer">DB-GPT</a> which uses Elasticsearch as the vector stor...
<python><docker><elasticsearch><large-language-model><ollama>
2024-10-28 10:16:23
1
515
happy
79,132,812
6,930,340
Find intersection of dates in grouped polars dataframe
<p>Consider the following <code>pl.DataFrame</code>:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl df = pl.from_repr(&quot;&quot;&quot; ┌────────┬────────────┐ │ symbol ┆ date │ │ --- ┆ --- │ │ str ┆ str │ ╞════════╪════════════╡ │ AAPL ┆ 2023-01-01 │ │ AAPL ┆ 2...
<python><dataframe><python-polars>
2024-10-28 09:38:11
1
5,167
Andi
79,132,760
11,155,419
Can't decode event data in Cloud Run Function with a Firestore trigger
<p>I have deployed a 2nd Gen Cloud Run Function with a Firestore trigger, on the <code>google.cloud.datastore.entity.v1.written</code> event. I have used the sample code shown in <a href="https://cloud.google.com/firestore/docs/extend-with-functions-2nd-gen#functions_cloudevent_firebase_firestore-python" rel="nofollow ...
<python><google-cloud-firestore><google-cloud-functions><google-cloud-run>
2024-10-28 09:26:14
0
843
Tokyo
79,132,717
12,284,585
Why do i get a `'PosixPath' object has no attribute 'walk'` exception?
<p>Why do i get a <code>'PosixPath' object has no attribute 'walk'</code> exception?</p> <pre class="lang-py prettyprint-override"><code>from pathlib import Path p = Path() for dirpath, dirnames, filenames in p.walk(): print(dirpath, dirnames, filenames) </code></pre>
<python><path><os.walk>
2024-10-28 09:09:42
1
1,333
tturbo
79,132,658
18,054,760
SIGBUS error when trying to use python jaydeebe api
<p>I have written a small function that creates jdbc connection in python using <a href="https://pypi.org/project/JayDeBeApi/#install" rel="nofollow noreferrer">jaydeebe</a> api/module/library. I have tested it on my personal laptop which is a windows env and it created the connection object successfully. When I moved...
<python><java><postgresql><jdbc>
2024-10-28 08:53:11
1
315
Abhinav
79,132,609
465,159
How to add types to pandas *DataFrames*?
<p>Pandas dataframes are useful, but they are fundamentally untyped. With this I don't mean the raw types of the columns, but the structure of the dataframe itself.</p> <p>For example, when you do <code>df : pd.Dataframe = pd.read_csv(...)</code>, you don't know which columns the dataframe contains, nor what their type...
<python><pandas><dataframe>
2024-10-28 08:37:58
0
5,474
Ant
79,132,604
7,510,661
aiohttp adds ~100 seconds latency?
<p>I am sending a basic post request from a client to a server. The logs on my server show that the response took 9.41 seconds, but the logs on the client show that it took ~100 seconds.</p> <p>Here is my code</p> <pre class="lang-py prettyprint-override"><code>logger.info(&quot;Uploading %s messages to backend.&quot;,...
<python><aiohttp>
2024-10-28 08:37:13
0
1,429
Vahe Tshitoyan
79,132,558
6,667,035
Video Frame-by-Frame Deraining with MFDNet in Python
<p>As <a href="https://codereview.stackexchange.com/q/294178/231235">this CodeReview question</a> mentioned, I am trying to modify the code to process frame-by-frame rain streaks removal in a video. FFmpeg package is used in this code.</p> <pre class="lang-py prettyprint-override"><code>import argparse import os import...
<python><video><ffmpeg><pytorch><out-of-memory>
2024-10-28 08:22:51
1
559
JimmyHu
79,132,363
16,171,413
Why does my Blog API CustomUser have an error when sending request for a CustomUser detail?
<p>I have two Blog API's in Django Rest Framework. One uses Django's default User model whilst the other uses a CustomUser. Authentication works well in both cases. I have similar serializers, viewsets and routers all configured. The endpoints that returns a collection of posts and users works well as well as the endpo...
<python><django><django-rest-framework><django-rest-viewsets><django-custom-user>
2024-10-28 07:12:34
1
5,413
Uchenna Adubasim
79,132,337
1,942,868
Copying database and authentication fails?
<p>I have django project which has database on aws <code>RDS</code>.</p> <p>I can login django account correctly with this database.</p> <p>Now I copied the database with command.</p> <pre><code>PGPASSWORD=XXXXXX createdb -U dbuser -h kkk.cgrxw5ome4nb.ap-northeast-1.rds.amazonaws.com -p 5432 -T old_db new_db </code></...
<python><django><postgresql>
2024-10-28 07:01:19
1
12,599
whitebear
79,132,052
2,289,030
Is there a way to find undecorated classes/functions in a Python module?
<p>I'm trying to write a tool which will help me find implementation bugs in a large existing python code base that makes heavy use of decorators.</p> <p>Lets say I have a file, <code>rules.py</code>:</p> <pre class="lang-py prettyprint-override"><code>manager = RuleManager() @manager.register class A: pass class...
<python><abstract-syntax-tree><python-decorators>
2024-10-28 04:24:28
2
968
ijustlovemath
79,132,015
3,169,868
browser_cookie3.BrowserCookieError: Unable to get key for cookie decryption
<p>While using <code>browser_cookie3</code> <a href="https://pypi.org/project/browser-cookie3/" rel="nofollow noreferrer">python package</a>, the following:</p> <pre><code>my_domain = 'www.xxx.com' browser_cookie3.chrome(domain_name=my_domain) </code></pre> <p>generates the following error message:</p> <pre><code>Trace...
<python><google-chrome><cookies>
2024-10-28 03:56:02
2
1,432
S_S
79,131,911
284,932
How to replace the deprecated 'conversational' pipeline in Hugging Face Transformers?
<p>I'm working on a chatbot using Hugging Face's Transformers library. I was previously using the conversational pipeline, but it seems that it has been deprecated. Here is the code I was using:</p> <pre><code># Initialize the conversational pipeline conversation = pipeline(&quot;conversational&quot;, model=model, toke...
<python><huggingface-transformers><large-language-model>
2024-10-28 02:28:48
2
474
celsowm
79,131,807
605,794
Python static property autocomplete list not working in PyCharm
<p>I'm using PyCharm Community Edition 2024.2.4. Autocomplete function lists appear correctly except in the case where I have a static property returning an object instance.</p> <p>The static property syntax comes from this post: <a href="https://stackoverflow.com/questions/1697501/staticmethod-with-property">@staticm...
<python><pycharm><code-completion>
2024-10-28 00:55:21
1
1,635
greenback
79,131,544
3,990,451
How to reach inner button inside a inner open shadow root with selenium
<p>a webpage has this HTML</p> <pre><code>&lt;custom-tag1 class data-component-key=&quot;...&quot; ...&gt; #shadow-root (open) &lt;div class=&quot;...&quot;&gt; &lt;custom-tag2 ...&gt; #shadow-root (open) &lt;button class=&quot;button-download&quot; style=&quot;background: transparent; border: 0;&quot;...
<python><selenium-webdriver>
2024-10-27 21:38:31
1
982
MMM
79,131,531
5,378,816
how to avoid deadlock in process.wait
<p>I'm looking for a way how to avoid or break the deadlock the <a href="https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.subprocess.Process" rel="nofollow noreferrer">docs</a> warn about. Here is the warning:</p> <blockquote> <p>This method [process.wait] can deadlock when using stdout=PIPE or stderr=...
<python><python-asyncio>
2024-10-27 21:26:52
0
17,998
VPfB
79,131,319
529,103
How do you remove a python venv from vscode?
<p>I've added several custom virtual environments to <code>vscode</code>, so that when I use the command palette I can select from a variety of builtin ones, as well as my own.</p> <p>I'd like to remove some of these, but I can't figure out where vscode stores these. I don't have a settings.json in my workspace, but i...
<python><vscode-python>
2024-10-27 19:19:24
1
792
Zachary Turner
79,131,144
1,574,054
Matplotlib pgf export: supylabel misaligned
<p>I am trying to add a <code>supylabel</code> to two subplots in matplotlib and export the result as a <code>.pgf</code>. However, the <code>supylabel</code> is clearly not centered.</p> <p>This is the python code:</p> <pre><code>fig, axes = pyplot.subplots( 2, 1, figsize=(3, 3), squeeze=True, shar...
<python><matplotlib><pgf>
2024-10-27 17:31:34
0
4,589
HerpDerpington
79,130,996
5,786,649
Programmatically change components of pytorch Model?
<p>I am training a model in pytorch and would like to be able to programmatically change some components of the model architecture to check which works best without any if-blocks in the <code>forward()</code>. Consider a toy example:</p> <pre class="lang-py prettyprint-override"><code>import torch class Model(torch.nn...
<python><pytorch>
2024-10-27 16:25:12
1
543
Lukas
79,130,980
7,123,797
How do the copy and deepcopy functions work for a bytearray argument?
<p>The <a href="https://docs.python.org/3/library/copy.html" rel="nofollow noreferrer">docs</a> say:</p> <blockquote> <p>The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances)</p> </blockquote> <p>It seems that the <code>...
<python><copy><deep-copy>
2024-10-27 16:16:09
1
355
Rodvi
79,130,588
18,385,480
Geometric visulalization of Cosine Similarity
<p>I have calculated the cosine similarity between two documents in a very basic way by using TF-IDF vectorization in Python. But I want to visualize the documents as a vectorized graph in a 3D space. Like this:</p> <p><a href="https://i.sstatic.net/pBFMUIOf.png" rel="nofollow noreferrer"><img src="https://i.sstatic.ne...
<python><nlp><tf-idf><cosine-similarity><tfidfvectorizer>
2024-10-27 12:32:32
1
723
bsraskr
79,130,497
6,197,439
Creating a custom diagonal line QBrush tiled pattern in PyQt5?
<p>So, at first I wanted to use a gradient background to emphasize certain cells / items in my QTableView, but as it can be seen in <a href="https://stackoverflow.com/questions/79129869/stretchable-qlineargradient-as-backgroundrole-for-resizeable-qtableview-cells-in">Stretchable QLinearGradient as BackgroundRole for re...
<python><pyqt5><qt5>
2024-10-27 11:47:17
1
5,938
sdbbs
79,130,437
7,945,506
How can I implement parallel threads with a GUI?
<p>With python, I want to run a slideshow (tkinter) and - in parallel - open a video feed. If there is a &quot;thumbs up&quot; gesture detected, the slideshow and the video feed should close.</p> <p>My current implementation:</p> <p><strong>main.py</strong></p> <pre><code>import threading import time from slideshow imp...
<python><opencv><user-interface><tkinter><python-multithreading>
2024-10-27 11:09:06
0
613
Julian
79,130,355
1,306,892
Issues with LaTeX Formatting in Matplotlib
<p>I'm trying to display LaTeX formulas using Matplotlib in Python. I have two pieces of code, one of which works correctly, while the other raises a <code>ValueError</code>.</p> <p>Here’s the code that works:</p> <pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt # Set the LaTeX formula f...
<python><matplotlib><latex>
2024-10-27 10:25:03
0
1,801
Mark
79,130,350
3,686,187
PIP installing lowest possible version of dependency without explanation
<p>AFAIK, pip's default behavior is to install latest released versions of subdependencies, which satisfy all requirements. However, I'm observing quite the opposite behavior when trying to install my project afresh.</p> <p>Here's my requirements.txt (it does beg for some stricter version specification, I know):</p> <p...
<python><pip><pypi>
2024-10-27 10:22:40
0
389
Roman
79,130,216
1,487,336
How to plot Pandas Series having zero values and DateTimeIndex properly?
<p>I have a Pandas Series having many zero values and DateTimeIndex. I want to plot them only with some zero values and handle datetime spacing proper.</p> <p>For example, the series is as follows. The simple plot shows too many zeros. I only want to show a few zeros before and after the non-zero values. And at the sam...
<python><pandas><plot>
2024-10-27 08:58:58
2
809
Lei Hao
79,130,143
1,606,657
Python retrieve Google Keep data of personal account
<p>I'd like to build an app that interacts with my Google keep data (edit, add, delete). I have created a new Google Cloud project and enabled the Google Keep API as well as created a new service account for accessing the API.</p> <p>I've created credentials for the service account and downloaded them. I have created t...
<python><google-keep-api>
2024-10-27 08:11:14
1
6,352
wasp256
79,130,069
671,013
"json_schema_extra" and Pylance/Pyright issues
<p>I need to add metadata to fields of a <code>pydantic</code> model in a way that I could change the metadata. I ended up with the following solution:</p> <pre class="lang-py prettyprint-override"><code>class Foo(BaseModel): a: str = Field( meta_field=(&quot;some extra data a&quot;), # pyright: ignore ...
<python><python-typing><pydantic><pyright>
2024-10-27 07:09:38
1
13,161
Dror
79,129,869
6,197,439
Stretchable QLinearGradient as BackgroundRole for resizeable QTableView cells in PyQt5?
<p>Consider this example, where I want to apply a &quot;vertical&quot; background to all cells in the third column of the table:</p> <pre class="lang-py prettyprint-override"><code>import sys from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtCore import (Qt, QPointF) from PyQt5.QtGui import (QColor, QGradient, QL...
<python><pyqt5><qt5>
2024-10-27 03:50:50
1
5,938
sdbbs
79,129,809
9,632,470
Use Beautiful Soup to count Title/Links
<p>I am attempting to write a code that keeps track of the text for the links in the left handed gray box on <a href="https://www.mountainproject.com/area/109928429/aasgard-sentinel" rel="nofollow noreferrer">this</a> webpage. In this case the code should return</p> <p>Valykrie, The<br /> Acid Baby</p> <p>Here is the c...
<python><web-scraping><beautifulsoup>
2024-10-27 02:29:40
4
441
Prince M
79,129,734
11,501,160
Manipulate rotation of image using im2pdf. Parameter doesn't work as expected?
<p>I am trying to take images and convert them to PDFs, however, when an image has a rotation value in its exif data, then my pdf also has a rotation value on the converted pdf. Instead of having the rotation value on the pdf page, i want the image to be rotated as it is meant to be viewed based on the image's exif, an...
<python><pdf><img2pdf>
2024-10-27 00:59:33
1
305
Zain Khaishagi
79,129,491
4,701,426
Writing interdependent if else statements?
<p>Is there any advantage to one of these over the other? Also, is there any better code than these to achieve the goal? My intuition is that in number 2, since it has already checked for x or y, the check for y is more efficient?</p> <ol> <li> <pre><code>if x or y: do some stuff if y: do some OTHER stuff </cod...
<python>
2024-10-26 21:26:56
2
2,151
Saeed
79,129,467
203,204
How to create Python `datetime` in a specific timezone?
<p>Input:</p> <pre><code>import pytz from datetime import datetime as dt targettz = pytz.timezone('America/New_York') d1 = dt(2024, 1, 1, 7, 40, 0, tzinfo=targettz) d1.isoformat() </code></pre> <p>Output:</p> <pre><code>'2024-01-01T07:40:00-04:56' </code></pre> <p>Why <code>'-04:56'</code> but not <code>'-04:00'</code>...
<python><python-3.x><python-datetime>
2024-10-26 21:09:56
1
12,842
Anthony
79,129,317
4,752,874
Python How to Select to List All DataFrame Rows where Column has a NaN Entry
<p>I have a DataFrame (20k rows) with 2 columns I would like to update if the first column (latitude) row entry is NaN. I wanted to use the code below as it might be a fast way of doing it, but I'm not sure how to update this line <code>msk = [isinstance(row, float) for row in df['latitude'].tolist()]</code> to get the...
<python><dataframe><for-loop>
2024-10-26 19:21:28
1
349
CGarden
79,129,205
16,869,946
Applying scipy.minimize to Pandas dataframe with parameters
<p>I have a function defined by f(x_0, x_1) = a(x_1 - x_0^2)^2 + (b - x_0)^2, where a and b are some parameters:</p> <pre><code>def f(x): return a*(x[1]-x[0]**2)**2+(b-x[0])**2 </code></pre> <p>where <code>x=np.array([x_0,x_1])</code> is a numpy array. Then the gradient and the Hessian of f are both easy to find and ...
<python><pandas><numpy><scipy><scipy-optimize-minimize>
2024-10-26 18:22:53
1
592
Ishigami
79,129,144
12,415,855
Can't install shazamio on MacOs?
<p>I try to install the python shazamio package using the following command</p> <pre><code>pip install shazamio </code></pre> <p>Generally the solution works fine on my windows computer but on Mac I get this error when trying to install the package -</p> <pre><code> Preparing metadata (pyproject.toml) ... error erro...
<python><rust><shazam>
2024-10-26 17:48:45
1
1,515
Rapid1898
79,128,856
1,880,405
Building a statically-linked pysqlite3 library
<p>I am trying to compile and import SQLite3 into Python3 by following <a href="https://github.com/coleifer/pysqlite3?tab=readme-ov-file#building-a-statically-linked-library" rel="nofollow noreferrer">Building a statically-linked library</a>, however I can't get it to work. I have compiled from source, copied .c and .h...
<python><macos>
2024-10-26 15:25:00
1
432
estranged
79,128,840
53,468
How to define the method signature in a subclass
<p>I'm implementing a repository pattern as an excercise on typing.</p> <p>I have a couple of unrelated SQLAlchemy models:</p> <pre><code>class Base(MappedAsDataclass, DeclarativeBase): id: Mapped[primary_key] = mapped_column(init=False) default_string = Annotated[str, mapped_column(String(100))] class User(Base)...
<python><python-typing><abc>
2024-10-26 15:19:28
1
3,680
tutuca
79,128,726
5,928,577
Segmentation Fault when Running pip install with Pyenv on macOS M1
<p>I’m encountering a segmentation fault while trying to install Python packages with pip inside a pyenv-managed environment on my macOS M1 system.</p> <p>Steps I Followed:</p> <p><code>brew install pyenv</code></p> <p><code>pyenv install 3.10.0</code></p> <p><code>pyenv global 3.10.0</code></p> <p><code>pip install tr...
<python><macos><installation><pip>
2024-10-26 14:19:01
3
2,740
Divyesh Savaliya
79,128,612
8,519,830
Pandas precision not working for last dataframe column
<p>I have a issue with pandas dataframe print not printing the last column with the requested precision. How to fix?</p> <p>Here is the short code snippet of the printout:</p> <pre><code>print(dfy) print(dfy.dtypes) with pd.option_context('display.precision', 0): print(dfy) </code></pre> <p>The printout from the co...
<python><pandas><dataframe>
2024-10-26 13:08:30
1
585
monok
79,128,153
9,686,427
Visual Studio Code displaying "..." instead of the output in .iypnb files
<p>When running code in cells of a <code>.iypnb</code> file in VisualStudioCode I often encounter the issue of VSC not showing any output, but rather just three gray dots:</p> <p><a href="https://i.sstatic.net/wjhIsWIY.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/wjhIsWIY.png" alt="enter image descrip...
<python><visual-studio-code><jupyter-notebook><output>
2024-10-26 08:55:08
0
484
Sam
79,128,076
1,802,693
Calling async code from syncronous function in Python
<p>This problem is probably not complicated, but I'm new to async library and I just can't figure this out.</p> <p>Let's say I have a synchronous function from which I want to call an async function without transforming the synchronous function into an asynchronous one. The synchronous function needs to wait for the as...
<python><asynchronous><python-asyncio>
2024-10-26 08:06:34
2
1,729
elaspog
79,127,868
1,880,405
How do I instruct Python to use my own compiled SQLite3?
<p>I have compiled my own version of SQLite3 <a href="https://www.sqlite.org/download.html" rel="nofollow noreferrer">amalgamation tarball from the download</a> page and would like to include that into my Python3 script on MacOs. Is there a way to do that via <code>import sqlite3</code>? As in, is it possible to instru...
<python><macos><sqlite3-python>
2024-10-26 05:15:42
1
432
estranged
79,127,802
3,657,298
Extracting a PDF Page With pypdf Consistently Creates PDF Without Any Pages
<p>I am trying to programmatically split a PDF containing multiple articles into a PDF for each article. The read and page extraction appears to work, the file is created, but is only 311 bytes of what appears to contain PDF header information without any PDF pages, according to Adobe Reader.</p> <p>I created a new on...
<python><python-3.x><pypdf>
2024-10-26 04:02:14
1
498
user3657298
79,127,665
354,051
Multithreaded list comprehension in python is not faster compare to non threaded version
<pre class="lang-py prettyprint-override"><code>from concurrent.futures import ThreadPoolExecutor words = [...] # List of ~100 words dictionary = { # ~20K items 'word1': 0.12, 'word2': 0.32, 'word3': 0.24, # more words... } def get_word_frequency(word): return (word, dictionary[word]) if word in ...
<python><list-comprehension><python-multithreading>
2024-10-26 01:45:52
2
947
Prashant
79,127,647
894,067
Tensorflow Docker Not Using GPU
<p>I'm trying to get Tensorflow working on my Ubuntu 24.04.1 with a GPU.</p> <p>According to <a href="https://www.tensorflow.org/install/docker" rel="noreferrer">this page</a>:</p> <blockquote> <p>Docker is the easiest way to run TensorFlow on a GPU since the host machine only requires the NVIDIA® driver</p> </blockquo...
<python><docker><tensorflow><gpu>
2024-10-26 01:23:52
1
20,944
Charlie Fish
79,127,603
3,334,721
Dealing with confidential modules in a Python code: are conditional imports possible?
<p>Let say I have a Python code with a <code>src</code> source folder. Inside this folder is a subfolder <code>confidential</code> (typically a git submodule) that is confidential and only selected users of the code can access.</p> <p>I am trying to find a robust way to deal with this confidential part of the code. I w...
<python><import><conditional-statements>
2024-10-26 00:26:30
0
403
Alain
79,127,575
3,182,021
AttributeError in Python when running on a web server
<p>I have code that works pretty well from command line, but when launching by Apache web server via PHP, and Racket subprocess, I get this error in the server logs:</p> <pre><code>(Traceback (most recent call last): File &quot;/opt/homebrew/var/www/drive/cut_1D.py&quot;, line 59, in &lt;module&gt; from_VTK = fb....
<python>
2024-10-25 23:55:29
1
419
Damien Mattei
79,127,523
7,323,888
Singleton different behavior when using class and dict to store the instance
<p>Why do these two base classes result in the child objects having different behavior?</p> <pre><code>class Base: _instance: &quot;Base&quot; = None def __new__(cls) -&gt; &quot;Base&quot;: if cls._instance is None: cls._instance = super().__new__(cls) return cls._instance class ...
<python><singleton>
2024-10-25 23:03:18
1
3,841
Victor Wong
79,127,484
11,959,501
What does QuantizeWrapperV2 actually do?
<p>So I am training this <code>small CNN model which has few Conv2D layers and some MaxPool2D, Activations, Dense</code>, basically the basic layers that <code>Tensorflow</code> provides.</p> <p>I want it to <code>run on an embedded system</code> which doesn't have lots of space, and cannot make floating point calculat...
<python><tensorflow><keras><quantization-aware-training><tfmot>
2024-10-25 22:36:50
1
577
Jhon Margalit
79,127,377
2,275,171
Using the name of a column as a parameter in Pyspark SQL query
<p>On a particular DataFrame I have a SQL query that I want to use twice, once to generate daily results and once to get monthly results. I can't just roll up the daily information because I have non-additive metrics like averages, distinct counts, etc.</p> <pre><code>SOURCE_BASIC_METRICS = &quot;&quot;&quot; select c...
<python><pyspark><apache-spark-sql>
2024-10-25 21:37:09
1
680
mateoc15
79,127,307
4,048,657
PyTorch how to use the gradient of an intermediate variable in the computation graph of a later variable
<pre class="lang-py prettyprint-override"><code>point_2 = torch.tensor([0.2, 0.8], device=device, requires_grad=True) p = torch.cat((point_2, torch.tensor([0], device=device)), 0) x_verts = torch.tensor([0.0, 1.0, 0.0], device=device, requires_grad=True) y_verts = torch.tensor([0.0, 0.0, 1.0], device=device, requires_...
<python><pytorch>
2024-10-25 21:02:55
1
1,239
Cedric Martens
79,127,256
1,380,269
Why my async function seems not to run asynchronously?
<p>I want to (quickly) scan my LAN to find a host listening to a certain TCP port, e.g. 2442 (JS8Call network API, if anyone's interested).</p> <p>I copied program structure from a tutorial explaining asynchronous execution in python with the help of <code>asyncio</code> package. The program kind of works, but the indi...
<python><python-asyncio>
2024-10-25 20:32:53
0
854
Jindrich Vavruska
79,126,930
11,277,108
Generic TypeVar solution for class that produces another class that contains the original class
<p>I'm trying to come up with a generic <code>TypeVar</code> solution to avoid having to create an ever expanding <code>Union</code>type annotation. Here's a somewhat contrived MRE of what I have currently:</p> <pre><code>from __future__ import annotations from typing import Union class CreatedDetails: def __init_...
<python>
2024-10-25 18:27:44
1
1,121
Jossy
79,126,854
11,609,834
How to hint argument to a function as dictionary with parent class in Python
<p>I would like to hint a function as a mapping between instances of a class or its children and a value. <code>takes_mapping</code> below is an example. However, I am getting a static typing error when I use the following:</p> <pre class="lang-py prettyprint-override"><code>from collections.abc import Mapping class P...
<python><python-typing>
2024-10-25 18:03:09
1
1,013
philosofool
79,126,749
11,092,636
How to change "Recommended environment" in Visual Studio Code
<p>In Visual Studio Code, whenever I'm prompted to choose an environment, there is a &quot;recommended&quot; one or &quot;favourite&quot; one. But it's not the one I would like to see there (I would like another virtual environment* to get there).</p> <p>E.g.: <a href="https://i.sstatic.net/82mWjPWT.png" rel="nofollow ...
<python><visual-studio-code><virtualenv>
2024-10-25 17:28:03
1
720
FluidMechanics Potential Flows
79,126,618
1,306,892
Formatting Nested Square Roots in SymPy
<p>I'm working with <code>sympy</code> to obtain symbolic solutions of equation. This is my code:</p> <pre class="lang-py prettyprint-override"><code>import sympy as sp # Define the symbolic variable x = sp.symbols('x') # Define f(x) f = ((x**2 - 2)**2 - 2)**2 - 2 # Solve the equation f(x) = 0 solutions = sp.solve(f...
<python><sympy><symbolic-math>
2024-10-25 16:46:02
2
1,801
Mark
79,126,521
7,426,792
polars: `json_path_match` on `pl.element()` in `list.eval()` context
<p>I'm trying to perform a JSON path match for each element (string) in a list. I'm observing the following behavior:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl data = [ '{&quot;text&quot;:&quot;asdf&quot;,&quot;entityList&quot;:[{&quot;mybool&quot;:true,&quot;id&quot;:1},{&quot;mybool&...
<python><json><dataframe><python-polars><jsonpath>
2024-10-25 16:18:18
1
427
Moritz Wilksch
79,126,460
10,083,382
Using fine tuned flux-dev model from Replicate platform locally?
<p>I've fine tuned flux-dev model using Replicate platform. I've downloaded the weights after the training process but I do not want to generate images on web interface. Instead I want to use my local resources to generate images. Currently, I generate images locally using baseline flux-dev model.</p> <p>After download...
<python><large-language-model><replicate>
2024-10-25 16:02:01
1
394
Lopez
79,126,368
10,658,339
How to create a plotly graph in Power BI
<p>I'm using the Python visual tool for Power BI and I would like to create a plotly graph, like in <a href="https://www.youtube.com/watch?v=uLikWluqg54" rel="nofollow noreferrer">this video</a> I'm able to create plots with seaborn and matplotlib, but when I try plotly it gives the error: <a href="https://i.sstatic.ne...
<python><powerbi><plotly>
2024-10-25 15:35:15
2
527
JCV
79,126,319
8,458,083
How to constrain a generic type with an alias derived from a union type in Python
<p>quick summary: I want the function <code>combine</code> to take two arguments with the same type. It is the generic type T. And T is one element certain union type <code>possibleTypeForCombine = int | str.</code> I want to constraint by possibleTypeForCombine not the type it include because the definition of ...
<python><generics><python-typing><mypy>
2024-10-25 15:18:24
4
2,017
Pierre-olivier Gendraud
79,126,257
1,012,952
Accessing query results from DBT in python script
<p>I am doing a bunch of programmatic running of dbt models from a python script. Part of this is the need to access the results of a simple query to determine what to do next. The <code>dbtRunnerResult</code> object never seems to have the query results, no matter whether I run a model or an operation. So so far I've ...
<python><dbt>
2024-10-25 14:59:14
2
4,080
Killerpixler
79,126,205
13,147,413
How to split a pyspark dataframe taking a portion of data for each different id
<p>I'm working with a pyspark dataframe (in Python) containing time series data. Data got a structure like this:</p> <pre><code>event_time variable value step ID 1456942945 var_a 123.4 1 id_1 1456931076 var_b 857.01 1 id_1 1456932268 var_b 871.74 1 id_1 1456940055 var_b 992.3...
<python><pyspark>
2024-10-25 14:48:35
1
881
Alessandro Togni
79,126,171
274,460
ContextVar set and reset in the same function fails - created in a different context
<p>I have this function:</p> <pre><code>async_session = contextvars.ContextVar(&quot;async_session&quot;) async def get_async_session() -&gt; AsyncGenerator[AsyncSession, None]: async with async_session_maker() as session: try: _token = async_session.set(session) yield session ...
<python><python-3.x><fastapi><python-contextvars>
2024-10-25 14:39:50
2
8,161
Tom
79,126,092
999,162
Django ModelForm doesn't update instance but fails with IntegrityError
<p>I'm having some really weird issue with a <code>ModelForm</code>. Instead of saving the instance, it attempts to create the instance with the same primary key.</p> <pre><code>class Upload(models.Model): file = models.FileField(upload_to=get_foundry_upload_name, null=False, blank=False) filename = models.Char...
<python><django><django-forms><modelform>
2024-10-25 14:19:16
1
5,274
kontur
79,126,042
14,643,631
How to efficiently remove overlapping circles from the dataset
<p>I have a dataset of about 20,000 records that represent global cities of population &gt; 20,000. I have estimated radius which more or less describes the size of the city. It's not exactly accurate but for my purposes it will be enough.</p> <p>that I'm loading it into my Panda dataframe object. Below is the sample</...
<python><pandas><dataframe><algorithm><gis>
2024-10-25 14:03:01
3
308
Sebastian Meckovski
79,125,968
18,769,241
How to check whether audio bytes contain empty noise or actual voice/signal?
<p>I use my microphone to get sound as follows:</p> <pre><code>FRAMES_PER_BUFFER = 1024 FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE = 48000 RECORD_SECONDS = 2 import pyaudio audio = pyaudio.PyAudio() stream = audio.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=Tr...
<python><audio><pyaudio>
2024-10-25 13:43:47
0
571
Sam
79,125,851
14,120,387
Python Kubernetes MutatingWebhook Not Adding Labels
<p>I have created a Kubernetes MutatingWebhook using a Docker image I built from Python. The purpose of the webhook is to add labels to any Pod that is launched. All Kubernetes resources are running fine, however, when new Pods are launched they do not get the expected labels from the MutatingWebhook.</p> <p>I get th...
<python><kubernetes>
2024-10-25 13:11:01
1
418
Brian G
79,125,836
13,981,672
Using linux's perf tool with Python virtual environnent
<p>Assume the following setup:</p> <pre class="lang-bash prettyprint-override"><code>source -- &quot;&lt;some_python_venv_directory&gt;/bin/activate&quot; perf record -- python3 test.py </code></pre> <p>The <code>python3</code> binary is expected to be the one in <code>${VIRTUAL_ENV}/bin</code>. But due to <code>perf</...
<python><virtualenv><perf>
2024-10-25 13:07:50
0
675
Etienne M
79,125,784
8,458,083
How to efficiently use generics in Python to type-hint a function with two arguments of the same type (either int or str)?
<p>I have a function that takes two arguments of the same type, which could be either int or str. My initial implementation without generics looks like this: python</p> <pre><code>def combine1(a: int | str, b: int | str) -&gt; int | str: match a: case int(): match b: case int(): ...
<python><generics><python-typing><mypy>
2024-10-25 12:55:03
2
2,017
Pierre-olivier Gendraud
79,125,764
6,930,340
Find intersection of columns from different polars dataframes
<p>I have a variable number of <code>pl.DataFrame</code>s which share some columns (e.g. <code>symbol</code> and <code>date</code>). Each <code>pl.DataFrame</code> has a number of additional columns, which are not important for the actual task.</p> <p>The <code>symbol</code> columns do have exactly the same content (th...
<python><dataframe><python-polars>
2024-10-25 12:51:39
2
5,167
Andi
79,125,755
8,044,858
numpy's kronecker product outputs non-zero angles outside valid complex-valued blocks
<p>It seems <code>numpy.kron</code> outputs unexpected non-zero angles when applied to a complex-valued matrix, that is non-zero angles outside of the blocks reproducing the input complex-valued matrix. Here is the code generating toy inputs, real and complex:</p> <pre><code>import numpy as np import seaborn as sns imp...
<python><numpy><complex-numbers><kronecker-product>
2024-10-25 12:48:53
0
1,079
Blupon
79,125,629
5,678,653
Keeping SciPy Voronoi Iteration Bounded
<p>I'm looking at various means of balancing points in a given space, and voronoi iteration / relaxation (aka Lloyds algorithm) has been beckoning me.</p> <p>However, when using SciPy Voronoi, the points seem to be leaking out of the boundary, and spreading into the known universe, which doesn't work for me at all!</p>...
<python><scipy><voronoi><relaxer>
2024-10-25 12:15:12
1
2,248
Konchog
79,125,570
10,061,888
Debounced Completer autoselects highlighted option when I stop arrowing through results?
<p>I'm trying to create a debounced Typeahead widget that populates with data from my database. When I try to down arrow through the query results, the highlighted result autoselects when I stop pressing the down arrow key.</p> <p>I looked at the docs for the <a href="https://doc.qt.io/qtforpython-5/PySide2/QtWidgets/Q...
<python><pyqt5>
2024-10-25 11:59:07
1
359
J.spenc
79,125,477
8,914,303
Nested Pydantic Models and Generics
<p>I am trying to reduce some code duplication by using generic types in python. With this minimal example</p> <pre><code>from typing import Generic, TypeVar from pydantic import BaseModel T = TypeVar(&quot;T&quot;) class Foo(BaseModel, Generic[T]): a: T Bar = list[Foo[T]] class Baz(BaseModel, Generic[T]): ...
<python><generics><python-typing><pydantic>
2024-10-25 11:31:59
1
1,699
CodeZero
79,125,266
626,804
Pandas HTML generation, reproducible output
<p>I am writing a Pandas dataframe as HTML using this code</p> <pre><code>import pandas as pd df = pd.DataFrame({ &quot;a&quot;: [1] }) print(df.style.to_html()) </code></pre> <p>I ran it once and it produced this output</p> <pre><code>&lt;style type=&quot;text/css&quot;&gt; &lt;/style&gt; &lt;table id=&quot;T_f9297&qu...
<python><html><pandas><deterministic>
2024-10-25 10:22:23
1
1,602
Ed Avis
79,125,214
4,119,911
Sending an array from jQuery to a Django view
<p>I am making a very small application to learn Django. I am send a nested array from jQuery and trying to loop it in my Django view.</p> <p>The jQuery code is as follows:</p> <pre><code>$(document).on('click','#exModel',function () { const sending = []; $(&quot;table tr&quot;).each(function () { ...
<python><jquery><django><django-views>
2024-10-25 10:09:47
2
360
fcreav
79,124,974
2,265,812
How to type hint a method returning a list of generic dataclass instances?
<p>I was wondering if it was possible to get a Union return type for <code>get_bars</code> in this scenario using <code>pyright</code>:</p> <pre><code>from dataclasses import dataclass @dataclass class Bar[T]: a: T @dataclass class Foo: bars: list[Bar] def get_bars(self): return self.bars </code...
<python><generics><python-typing><pyright>
2024-10-25 08:56:39
0
1,043
Orelus
79,124,776
1,406,168
CBS Authentication Expired - Azure Service bus
<p>I am trying to add a simple message to a service bus locally. I have a c# project locally too in Visual Studio that works towards same ressource with no problems.</p> <p>But in Visual Studio Code with Phython I cannot get it working:</p> <p>First I login to azure with azd login successfully.</p> <p>I have following ...
<python><azure><azureservicebus><azure-managed-identity>
2024-10-25 07:59:07
1
5,363
Thomas Segato
79,124,373
511,302
How to print errors like python does by default?
<p>Considering the following errornous function:</p> <pre><code>def inner(): raise Exception(&quot;message&quot;) </code></pre> <p>If I run the function I get an error like:</p> <pre><code>Traceback (most recent call last): File &quot;/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/pydevconsole.py...
<python><exception><python-logging>
2024-10-25 05:34:16
1
9,627
paul23
79,124,311
8,621,823
How does pytest install pytest and _pytest into site-packages
<p>Within site-packages, there are <code>pytest</code> and <code>_pytest</code> folders. Most of the core code is in _pytest.</p> <p>When looking at pyproject.toml, I could not find how does setuptools know to install <code>pytest</code> and <code>_pytest</code>.</p> <p>I thought is it due to the existence of <code>__i...
<python><pytest><setuptools><pyproject.toml>
2024-10-25 04:58:50
1
517
Han Qi
79,124,260
2,962,555
ModuleNotFoundError: No module named 'x' where x is a module suppose to be a shared lib
<p>I have a project with three modules - one, two and three. one and two are stand-alone services and three is the common lib that will be used by one and two. When I tried to run <code>docker-compose up --build</code> at the root folder, both the module one and two containers failed to start with error log</p> <pre><c...
<python><docker><docker-compose><dockerfile>
2024-10-25 04:20:32
0
1,729
Laodao
79,124,203
9,547,278
Algorithm to indent and de-indent lines
<p>I have a long document with text like this:</p> <pre><code>paragraph = ''' • Mobilising independently with a 4-wheel walker • Gait: Good quality with good cadence, good step length, and adequate foot clearance • Lower limb examination: - Tone: Normal bilaterally - No clonus in either leg - Passive dorsiflexion: Poss...
<python><string>
2024-10-25 03:41:46
1
474
Legion
79,123,919
825,227
Pandas bar plot with multiple alpha values
<p>I am trying to create a bar plot with <code>alpha</code> transparency values for different time series.</p> <p>I thought the code below would give me that, as I've seen elsewhere lists can be passed via the <code>alpha</code> <code>kwarg</code>, but I get an error (included below). What am I missing?</p> <p>Code:</p...
<python><pandas><matplotlib>
2024-10-25 00:07:37
2
1,702
Chris
79,123,731
856,804
Why does asizeof() claim that Python instance of protobuf message takes so much memory?
<p>I'm investigating a memory issue related to protobuf message in Python.</p> <p>Here is the simple protobuf message:</p> <pre class="lang-protobuf prettyprint-override"><code>syntax=&quot;proto3&quot;; message LiveAgentMessage { string text = 1; } </code></pre> <p>So it gets compiled to a class in python with proto...
<python><memory><reflection><protocol-buffers>
2024-10-24 22:02:22
1
9,110
zyxue
79,123,539
54,873
How can I eliminate the pandas complaint about using aggfunc=np.sum in pivot_tables?
<p>I recently upgraded my <code>pandas</code> from v1.x to v2.x. However, code that does reasonable things with pivot tables generates an obnoxious set of future warnings.</p> <pre><code>(Pdb) df = pd.DataFrame([[&quot;a&quot;, 1], [&quot;a&quot;, 2], [&quot;b&quot;, 3]], columns=[&quot;col1&quot;, &quot;col2&quot;]) ...
<python><pandas>
2024-10-24 20:33:53
2
10,076
YGA
79,123,534
11,374,051
Playwright manual download with default file names
<p>I use Playwright to partially automate my tasks but sometimes I need to navigate manually to get to the info I require. As such, I need to download files manually as well, but there doesn't seem to be a way to save those files as their default names.</p> <p>I know if the download is started from the script, I might ...
<python><playwright><playwright-python>
2024-10-24 20:32:35
2
574
weasel
79,123,529
986,612
Revert back the behavior of loading dlls to before python 3.8 and the new add_dll_directory()
<p>The python <a href="https://docs.python.org/3.8/library/os.html#os.add_dll_directory" rel="nofollow noreferrer">doc</a> explains the breaking change:</p> <blockquote> <p>New in version 3.8: Previous versions of CPython would resolve DLLs using the default behavior for the current process. This led to inconsistencies...
<python>
2024-10-24 20:30:07
1
779
Zohar Levi
79,123,446
8,512,262
Is there a better way to combine two DataFrames from two SQL queries into a single DataFrame?
<p>Currently I'm querying two separate tables in a SQL database - one from which I get &quot;data&quot; from <code>my_table</code> and the other from which I get &quot;units&quot; from a <code>config</code> table. The <strong>units</strong> correspond 1:1 with the values in the <strong>data</strong>, i.e., each column ...
<python><sql><pandas>
2024-10-24 19:54:20
1
7,190
JRiggles
79,123,367
1,886,904
LangChain ReAct agent not performing multiple cycles
<p>I am struggling with getting my ReAct agent in LangChain to do any more than one cycle. It will select tools, and run them, but it won't ever decide that it needs to run any again. Very occasionally some combination of prompts will result in multiple cycles, but it is never repeatable.</p> <p>It is important to note...
<python><ollama><langgraph><langchain-agents>
2024-10-24 19:12:24
0
682
egeorge
79,123,306
8,595,535
Filter pandas dataframe between dates located in another dataframe
<p>Suppose I have two pandas dataframes: A first dataframe with some data (reflected in columns Col1 and Col2 in example below) across both Code and Time. A second dataframe detailing a set of date bounds. The idea is to exclude any rows (in <code>df_table</code>) that have a date that falls between any bounds (in <cod...
<python><pandas>
2024-10-24 18:50:49
2
309
CTXR
79,123,305
12,115,498
Numpy array does not correctly update in Gaussian elimination program
<p>I am trying to write a function <code>gaussian_elim</code> which takes in an n x n numpy array A and an n x 1 numpy array b and performs Gaussian elimination on the augmented matrix [A|b]. It should return an n x (n+1) matrix of the form M = [U|c], where U is an n x n upper triangular matrix. However, when I test my...
<python><arrays><numpy><matrix><linear-algebra>
2024-10-24 18:50:43
1
783
Leonidas
79,122,914
2,205,380
Zip input and output without wildcards, using absolute paths
<p>Very similar to <a href="https://stackoverflow.com/questions/69137857/snakemake-coupling-inputs-and-outputs-without-shared-wildcards">Coupling inputs and outputs without shared wildcards</a>, I have assembled a user-specified list of inputs and outputs that are paired:</p> <pre><code>inputs = [&quot;/path/to/input1&...
<python><snakemake>
2024-10-24 16:42:07
1
2,388
Rboreal_Frippery
79,122,892
6,216,530
Check when vectors are uploaded to Pinecone namespace
<p>I have a pinecone index set up and I am using Langchain to upload my prepared Documents to a certain namespace. My problem is that, I am returning the PineconeVectorStore and passing that as a parameter to another class; however, Pinecone takes a few seconds to completely be done with all the vector uploading. Is th...
<python><openai-api><langchain><pinecone>
2024-10-24 16:33:30
0
867
H.Sdq
79,122,632
850,271
Recursive nested string formatting
<p>I want to take something like the following:</p> <pre><code>print('{test_{test2}}'.format(test2='test2', test_test2='test3')) </code></pre> <p>and produce:</p> <pre><code>test3 </code></pre> <p>But I get the error:</p> <pre><code>ValueError: unexpected '{' in field name </code></pre> <p>How can I do this?</p>
<python><string>
2024-10-24 15:21:34
1
6,004
John Roberts
79,122,605
20,920,790
Why pandas.merge_asof working with error in my case?
<p>I'm trying to merge 2 tables with pandas.merge_asof.</p> <p>First table administrators_system_with_schemes_sort:</p> <div class="s-table-container"><table class="s-table"> <thead> <tr> <th style="text-align: right;">salon_id</th> <th style="text-align: right;">staff_id</th> <th style="text-align: left;">date</th> </...
<python><pandas><dataframe>
2024-10-24 15:13:48
1
402
John Doe
79,122,259
2,401,856
Python - flask app doesn't serve images used in react app
<p>I have a react project that is hosted in flask app.</p> <p>This is the project folders:</p> <pre><code>/simzol/ └── backend/ ├── app.py └── build/ ├── index.html ├── images/ ├── static/ │ ├── css/ │ └── js/ └── other_files... </code></pre> <blockquote> <p>P...
<python><reactjs><flask>
2024-10-24 13:54:26
1
620
user2401856
79,121,793
4,819,195
Requests per second(RPS) not going above certain number with Hana database and Locust
<p>I wanted to perform some load testing on Hana database. For this I decided to use Locust and I referenced the implementation given in this link for another database: <a href="https://community.cratedb.com/t/load-testing-cratedb-using-locust/1686" rel="nofollow noreferrer">https://community.cratedb.com/t/load-testing...
<python><load-testing><hana><locust>
2024-10-24 12:02:30
0
399
A Beginner