QuestionId
int64
74.8M
79.8M
UserId
int64
56
29.4M
QuestionTitle
stringlengths
15
150
QuestionBody
stringlengths
40
40.3k
Tags
stringlengths
8
101
CreationDate
stringdate
2022-12-10 09:42:47
2025-11-01 19:08:18
AnswerCount
int64
0
44
UserExpertiseLevel
int64
301
888k
UserDisplayName
stringlengths
3
30
78,141,598
9,194,965
Plot regression line for dtype Period (Q_DEC) vs int column: python
<p>I am unable to plot a regression line for a simple dataframe that consists of a period formatted date column and a integer column. The sample dataframe may be created using below code:</p> <pre><code>df = pd.DataFrame({&quot;quarter&quot;: ['2017Q1', '2017Q2', '2017Q3', '2017Q4', '20...
<python><pandas><datetime><seaborn><regplot>
2024-03-11 15:01:12
0
1,030
veg2020
78,141,573
5,774,070
Integrating Frontend JavaScript Code with AES Encryption getting ValueError: Data must be padded to 16 byte boundary in CBC mode
<p>I'm currently working implementing AES encryption in the backend using Python, but I'm encountering some issues in ensuring compatibility between frontend and backedn. I need help in integrating the frontend JavaScript code to work with it.</p> <p>My backend Python code:</p> <pre class="lang-py prettyprint-override"...
<javascript><python><encryption><aes><cryptojs>
2024-03-11 14:58:00
1
1,777
Vishal Kharde
78,141,564
309,917
Corrupted ZipFile using file object
<p>I'm trying to create, using python, a zip file to be later used in a http response. To achieve this I'm using a <code>io.BytesIO()</code> as file object.</p> <p>The resulting zip file is somehow corrupted: some software like <code>unzip</code> don't like it while others like <code>zcat</code> do read contents.</p> <...
<python><zip>
2024-03-11 14:56:01
1
12,525
neurino
78,141,391
1,843,511
Best Practices for Modifying Nested Objects in Python
<p>I'm working on a Python project using Beanie ODM to interact with MongoDB, and I've come across a situation where I need to modify nested objects. Specifically, I'm dealing with a User object that contains a nested Job object (among other attributes). Here's a simplified version of the models I'm working with:</p> <...
<python><mongodb><object>
2024-03-11 14:30:07
1
5,005
Erik van de Ven
78,141,315
13,896,155
Visualizing Vector Embeddings Stored in ChromaDB
<p>I am currently working on a project where I am using ChromaDB to store vector embeddings generated from textual data. The vector embeddings are obtained using Langchain with OpenAI embeddings. However, I can't find a meaningful way to visualize these embeddings.</p> <p>Here is the relevant part of my code:</p> <pre>...
<python><visualization><large-language-model><chromadb><openaiembeddings>
2024-03-11 14:19:14
0
581
Anay
78,141,179
1,342,522
ML Algo for determining if a sentence is a question
<p>I have a form that user's are supposed to use to ask support questions. Instead we've noticed that alot of people are using it to submit feedback or statements to update parts of their record.</p> <p>I wanted to run through all records and separate out questions from feedback or statements (assume that feedback and...
<python><spacy><huggingface-transformers>
2024-03-11 13:57:10
1
1,385
JakeHova
78,141,113
6,435,921
Python - Read a table column on a specific page of a PDF on the browser as a NumPy Array
<h1>Task</h1> <p>On page 10 of <a href="https://cdn.who.int/media/docs/default-source/gho-documents/global-health-estimates/gpe_discussion_paper_series_paper31_2001_age_standardization_rates.pdf" rel="nofollow noreferrer">this</a> PDF there is Table 1. I would like to read the column &quot;WHO World Standard*&quot; as ...
<python><pdf><web-scraping>
2024-03-11 13:48:15
2
3,601
Euler_Salter
78,141,088
10,131,952
Unable to read Local language data from an Excel using csv
<p>I am giving data as &quot;यह एक नमूना संदेश है&quot; in a CSV file. I am reading the data inside the file using CSV Module in python. sample code:</p> <pre><code> csvFile = request.FILES.get('file') csv_copy = copy.deepcopy(csvFile) file_content = csv_copy.read() decoded_file = file_content.decode('utf-8').sp...
<python><django><csv><python-3.8>
2024-03-11 13:45:17
1
413
padmaja cherukuri
78,141,020
3,337,089
Make pytorch reserve certain amount of GPU memory upfront
<p>My code has two workflows that run sequentially. In the first workflow, it requires only about 8GB of GPU memory, but the second workflow takes about 22GB. Is it possible to reserve 22GB upfront (even while running the first workflow) even if it is not using all the memory at that time?</p> <p>I run my code on a sha...
<python><pytorch><shared-gpu-memory>
2024-03-11 13:36:19
0
7,307
Nagabhushan S N
78,140,988
3,433,875
Curved arrowstyle in matplotlib
<p>I am trying to replicate this: <a href="https://i.sstatic.net/yDnHp.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/yDnHp.png" alt="enter image description here" /></a></p> <p>And I have gotten quite far:</p> <pre><code>import matplotlib.pyplot as plt from matplotlib.lines import Line2D import numpy a...
<python><matplotlib>
2024-03-11 13:32:00
1
363
ruthpozuelo
78,140,865
9,488,023
Using SciPy ndimage.zoom on an array with nan values
<p>I am trying to use scipy.ndimage.zoom on an array that contains a significant amount of NaN values, and wanted to try to use different orders to see how the results varied, but for orders higher than 1 (linear), the entire zoomed array becomes filled with NaN values.</p> <p>Writing something like this:</p> <pre><cod...
<python><scipy><zooming><interpolation><nan>
2024-03-11 13:12:25
1
423
Marcus K.
78,140,560
6,884,119
AttributeError: 'NoneType' object has no attribute 'split' with Python Selenium in AWS Lambda
<p>I am trying to run a python script using Selenium in my AWS lambda but it's returning the below error:</p> <pre><code> File &quot;/var/lang/lib/python3.11/site-packages/webdriver_manager/core/driver.py&quot;, line 48, in get_driver_version_to_download return self.get_latest_release_version() ^^^^^^^^...
<python><python-3.x><selenium-webdriver><aws-lambda><aws-lambda-containers>
2024-03-11 12:17:51
0
2,243
Mervin Hemaraju
78,140,532
12,063,435
Plot array of Figures Mathplotlib
<p>I have a function that creates a figure and now I would like to call this function repeatedly inside a loop with different parameters, collect the figures and plot them. This is how I would do it in julia:</p> <pre><code>using Plots plots = Array{Plots.Plot{Plots.GRBackend},2}(undef, 3,3) for i in 1:3 for j in...
<python><matplotlib><julia>
2024-03-11 12:12:25
2
490
TheFibonacciEffect
78,140,395
694,162
Python function compatible with sync and async client
<p>I'm developing a library that should support sync and async users while minimizing code duplication inside the library. The ideal case would be implementing the library async (since the library does remote API calls) and adding support for sync with a wrapper or so. Consider the following function as part of the lib...
<python><asynchronous>
2024-03-11 11:47:29
1
5,188
sauerburger
78,140,362
2,409,793
VSCode not resolving installed python dependencies
<p>I have a <code>python</code> project for which I have activated a <code>virtualenv</code> and installed everything in <code>requirements.txt</code>.</p> <p>This has been done manually through</p> <pre class="lang-bash prettyprint-override"><code>python -m venv /path/to/new/virtual/environment </code></pre> <p>and</p...
<python><visual-studio-code><virtualenv><pylance>
2024-03-11 11:41:56
2
19,856
pkaramol
78,140,149
9,542,989
Check if Package Installation will Result in Dependency Conflicts in Python
<p>Before installing a package in my Python environment using <code>pip install &lt;some-package&gt;==&lt;version&gt;</code>, is it possible for me to check if doing so will cause a dependency conflict, given what has been installed in the environment already?</p> <p>I am looking for a script I can run before each inst...
<python><pip>
2024-03-11 11:05:39
1
2,115
Minura Punchihewa
78,140,123
6,197,439
Display/print column as hex in pandas?
<p>Let's say I have this data as a starting point:</p> <pre class="lang-python prettyprint-override"><code>import pandas as pd data = [ {&quot;colA&quot;: &quot;hello&quot;, &quot;colB&quot;: 22, &quot;colC&quot;: 3.0, &quot;colD&quot;: 123476}, {&quot;colA&quot;: &quot;there&quot;, &quot;colB&quot;: 122, &quot...
<python><pandas>
2024-03-11 11:02:18
1
5,938
sdbbs
78,140,052
3,676,262
Task Queue with cached libraries in Django
<p>I am creating a WEB interface for various Python scripts through Django.</p> <p>Example in calculation.py I would have :</p> <pre><code>import datetime def add_time(a, b): return = a + b + int(datetime.datetime.now()) </code></pre> <p>Usages :</p> <ul> <li>A user could say &quot;I want to run add from calculatio...
<python><django><python-import><task-queue>
2024-03-11 10:48:56
1
378
BleuBizarre
78,139,918
10,595,871
Flask API doesn't recognize folder input
<p>I'm working with flask on an app that receive an audio file and transcribe it. As long as I pass a single file everything is working fine, I'm now trying to adapt the code in order to pass a folder and start the jobs for every file in it, but for some reasons it is not working, as it only starts the job for the firs...
<javascript><python><html><flask>
2024-03-11 10:24:50
0
691
Federicofkt
78,139,910
9,751,001
How to identify feature names from indices in a decision tree using scikit-learn’s CountVectorizer?
<p>I have the following data for training a model to detect whether a sentence is about:</p> <ul> <li>a cat or dog</li> <li>NOT about a cat or dog</li> </ul> <p><a href="https://i.sstatic.net/gNnh6.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/gNnh6.png" alt="screenshot of data consisting of a text col...
<python><scikit-learn><nlp><decision-tree><countvectorizer>
2024-03-11 10:24:12
1
631
code_to_joy
78,139,855
10,715,700
Why do I get different embeddings when I perform batch encoding in huggingface MT5 model?
<p>I am trying to encode some text using HuggingFace's mt5-base model. I am using the model as shown below</p> <pre class="lang-py prettyprint-override"><code>from transformers import MT5EncoderModel, AutoTokenizer model = MT5EncoderModel.from_pretrained(&quot;google/mt5-base&quot;) tokenizer = AutoTokenizer.from_pret...
<python><machine-learning><pytorch><nlp><huggingface-transformers>
2024-03-11 10:14:53
2
430
BBloggsbott
78,139,574
7,116,108
FastAPI: return an appropriate error message and status for unhandled exceptions
<p>I would like my FastAPI app to always send detailed error messages in the response, even for unhandled exceptions.</p> <p>I have looked at the docs for this (<a href="https://fastapi.tiangolo.com/tutorial/handling-errors/" rel="nofollow noreferrer">https://fastapi.tiangolo.com/tutorial/handling-errors/</a>) but I'm ...
<python><fastapi>
2024-03-11 09:27:08
0
1,587
Dan
78,139,177
1,125,062
Backprop two networks with different loss without retain_graph=True?
<p>I have two networks in sequence that perform an expensive computation.</p> <p>The loss objective for both is the same, except for the second network's loss I want to apply a mask.</p> <p>How to achieve this without using retain_graph=True?</p> <pre><code># tenc - network1 # unet - network2 # the w...
<python><pytorch><autograd>
2024-03-11 08:09:23
2
4,641
Anonymous
78,139,097
447,537
How do I get column names of a model created in PyCaret
<p>I am trying to create a PyCaret Model</p> <pre><code># load dataset from pycaret.datasets import get_data insurance = get_data('insurance') # init environment from pycaret.regression import * r1 = setup(insurance, target = 'charges', session_id = 123, normalize = True, polynomial_features = T...
<python><machine-learning><regression><pycaret>
2024-03-11 07:54:33
1
3,510
Ajay Ohri
78,139,065
14,425,501
How to use batch prediction in Diffusers.StableDiffusionXLImg2ImgPipeline library
<p>I'm currently exploring the StableDiffusion Image to Image library within HuggingFace. My goal is to generate images similar to the ones I have stored in a folder. Currently, I'm using the following code snippet:</p> <pre><code>import torch from diffusers.utils import load_image from diffusers import StableDiffusion...
<python><pytorch><huggingface><stable-diffusion><diffusers>
2024-03-11 07:48:46
0
1,933
Adarsh Wase
78,138,546
1,676,448
How to stream tqdm text content to PySide2 GUI?
<p>I am using jMetalPy. It has a &quot;ProgressBarObserver&quot; that uses tqdm to show calculation progess</p> <p><a href="https://github.com/jMetal/jMetalPy/blob/main/jmetal/util/observer.py" rel="nofollow noreferrer">https://github.com/jMetal/jMetalPy/blob/main/jmetal/util/observer.py</a></p> <p>I have a PySide2 bas...
<python><user-interface><pyside2><tqdm><jmetalpy>
2024-03-11 05:22:26
1
307
idroid8
78,138,342
3,121,975
Sign hashed data with a PCKS12 certificate
<p>I need to send requests to a SOAP API, and as part of that process, I need to hash my XML request using SHA256 and then sign it with an RSA key (which I have in the form of a PCKS12 certificate). I've tried using the <code>Crypto</code> library like this:</p> <pre class="lang-py prettyprint-override"><code>from Cryp...
<python><cryptography><rsa><digital-signature>
2024-03-11 03:55:54
0
8,192
Woody1193
78,138,184
7,335,214
Unable to downgrade numpy for compatibility with librosa 0.8.1
<p>I need to use <code>librosa 0.8.1</code> for compatibility but cannot seem to downgrade it; or rather, I can downgrade it, but an incompatibility with the latest version of <code>numpy</code> followed by an inability to downgrade <code>numpy</code> is preventing me from using it.</p> <p>I first used <code>pip instal...
<python><numpy><pip><librosa>
2024-03-11 02:43:24
2
668
Dawn
78,138,125
11,037,602
How to see python logging output from child docker container (container started by another container)?
<p>I have an application that uses docker compose to start 3 containers. The logs for those 3 containers are outputted to <code>stdout</code> as expected. One of these containers is responsible for starting other containers, as they are needed. It uses <a href="https://docker-py.readthedocs.io/en/stable/" rel="nofollow...
<python><docker><docker-compose><python-logging><dockerpy>
2024-03-11 02:14:40
0
2,081
Justcurious
78,138,116
2,304,735
How can I fix python multiprocessing error?
<p>I am starting to learn about python multiprocessing. I am starting with this simple code. I am using Anaconda and the Spyder IDE to implement this code in. I am using Windows 10 Pro Operating System.</p> <pre><code>import time import multiprocessing start = time.perf_counter() def do_something(): print('Sleepi...
<python><python-3.x><python-multiprocessing>
2024-03-11 02:10:27
1
515
Mahmoud Abdel-Rahman
78,138,063
9,951,273
Dockerfile runs runs locally but fails on Google Cloud Run
<p>I have a Dockerfile, shown below:</p> <pre><code>FROM --platform=linux/amd64 prefecthq/prefect:2-python3.12 RUN apt-get update &amp;&amp; apt-get -y install libpq-dev gcc RUN pip install --upgrade pip RUN pip install pipenv ENV PREFECT_API_URL=&quot;foo&quot; ENV PREFECT_API_KEY=&quot;bar&quot; WORKDIR /app COPY...
<python><docker><google-cloud-run><prefect>
2024-03-11 01:45:38
1
1,777
Matt
78,138,032
7,160,815
What is the difference between skimage view_as_window and sklearn extract_patch_2d, in the context of extracting array of patches from an image?
<p>I have an array of 2D images; an array of [n x w x h], n being the number of images. I want to extract patches from each 2D image. A 2D image would not be divided equally by the patch size (meaning I should use padding). I do not want overlapping patches. I came across two functions in skimage and sklearn for this: ...
<python><image-processing><scikit-image>
2024-03-11 01:25:05
1
344
Savindi
78,137,961
1,079,065
Python read a csv file and map it to an object directly
<p>I am trying to parse some data for my project. I have following structure:</p> <pre><code>class Subject: #listing the fields only subject_name grade prof_name details (few more ) class Student: #listing the fields only name subjects = [] --------&gt; imp </code></pr...
<python><arrays><python-3.x><list><dictionary>
2024-03-11 00:47:19
0
2,245
user1079065
78,137,875
8,484,261
Add a column in a dataframe which takes the value of a column X if it is not blank , else it takes the value of column Y
<p>I have a dataframe with a column with data separated by delimiter <code>&quot;\&quot;</code>. There could be 1 or 2 delimiters and it varies by row. I was able to split the column into multiple columns as follows:</p> <pre><code>df[['Desc1','Desc2','Desc3']] = df['Descr'].str.split(&quot;\\&quot;, expand=True) </co...
<python><pandas>
2024-03-10 23:59:47
1
3,700
Alhpa Delta
78,137,739
1,960,266
Plotting of gradient descent curves by using Keras
<p>I have implemented the following code in Keras that uses the California housing dataset in an attempt to plot the values of theta 1 and theta 2, and how the chose of stochastic gradient descent, batch gradient or mini batch influences in the results:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt ...
<python><machine-learning><keras>
2024-03-10 22:46:54
1
3,477
Little
78,137,642
2,245,136
Cursor-based paging with a compound index in MongoDB and Python
<p>The Python application I'm implementing works with the MongoDB database. I use the <code>mongoengine</code> module to connect and fetch data in my scripts (<a href="https://docs.mongoengine.org/" rel="nofollow noreferrer">https://docs.mongoengine.org/</a>).</p> <p>My collection in the database has following structur...
<python><mongodb><mongoengine>
2024-03-10 22:03:17
0
372
VIPPER
78,137,516
1,309,300
Python - rdflib - json-ld - why does it not parse the nested triples
<p>I have the following code, parsing the JSON-ld file below. However, it only outputs the top-level triples and not the other, such as the <code>name</code> of the <code>WebPage</code></p> <pre class="lang-py prettyprint-override"><code>from rdflib import Dataset from rdflib.namespace import Namespace, NamespaceManage...
<python><json-ld><rdflib>
2024-03-10 21:15:35
1
328
Kaj Kandler
78,137,513
2,314,737
Pandas query doesn't work if column contains null values
<p>I have a Pandas dataframe containing null values and I want to filter it using <code>query</code></p> <pre><code>data = {'Title': ['Title1', 'Title2', 'Title3', 'Title4'], 'Subjects': ['Math; Science', 'English; Math', pd.NA, 'English']} df_test = pd.DataFrame(data) print(df_test) # Title Subject...
<python><pandas><dataframe>
2024-03-10 21:13:32
1
29,699
user2314737
78,137,505
5,431,734
float32 and precision points in numpy
<p>I am trying to understand presision points in python between <code>np.float32</code> and <code>np.float64</code>. For lower memory footprint I am leaning towards using float32 but I dont quite understand why sometimes a float turns into an iterger-like. For example:</p> <pre><code>x = np.array(12345678.1234) # this ...
<python><numpy>
2024-03-10 21:11:33
0
3,725
Aenaon
78,137,364
297,797
Rotate one axis in matplotlib
<p>I have some series x and y such that x+y ≤ 1. If I make a simple scatter plot it looks like this:</p> <p><a href="https://i.sstatic.net/VEGkY.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/VEGkY.png" alt="scatter plot" /></a></p> <p>I'd like to transform this plot so that the angle between the positi...
<python><matplotlib>
2024-03-10 20:19:23
2
2,689
Matthew Leingang
78,137,290
2,056,201
Cannot use relative folder structure in NPM packages.json
<p>Im using the example flask/react app from this github <a href="https://github.com/Faruqt/React-Flask" rel="nofollow noreferrer">https://github.com/Faruqt/React-Flask</a></p> <p>Problem is I have the <code>flask.exe</code> in <code>Project/venv/scripts</code> folder and the repository is in <code>Project/React-Flask-...
<javascript><python><reactjs><npm><python-venv>
2024-03-10 19:53:24
0
3,706
Mich
78,137,226
2,056,201
"env: ‘/bin/flask’: No such file or directory" when running "npm run start-backend"
<p>Im trying to find the most basic website template with Flask and React, Im using this repository and following installation instructions</p> <p><a href="https://github.com/Faruqt/React-Flask" rel="nofollow noreferrer">https://github.com/Faruqt/React-Flask</a></p> <p>Im using git Bash in Windows 10, and when running ...
<javascript><python><reactjs><windows><flask>
2024-03-10 19:32:01
1
3,706
Mich
78,137,158
2,514,157
Can Distilled Whisper Models be used as a Drop-In Replacement for OpenAI Whisper?
<p>I have a working video transcription pipeline working using a local OpenAI Whisper model. I would like to use the equivalent distilled model (&quot;distil-small.en&quot;), which is smaller and faster.</p> <pre class="lang-py prettyprint-override"><code>transcribe(self): file = &quot;/path/to/video&quot; mod...
<python><openai-api><openai-whisper>
2024-03-10 19:07:49
1
691
user2514157
78,137,038
889,675
Ensuring unique combination of many to many mapped entities in SqlAlchemy
<p>I have a following SqlAlchemy models with association table. They represent chat conversations. Each chat can have 0 - N users involved:</p> <pre><code>class Chat(BaseDbModel): __tablename__ = &quot;chats&quot; id = Column(Integer, primary_key=True) users = relationship(&quot;User&quot;, seconda...
<python><postgresql><sqlalchemy>
2024-03-10 18:30:48
1
876
Marian Galik
78,136,889
6,687,699
asyncpg.exceptions.AmbiguousParameterError: could not determine data type of parameter
<p>Am creating an endpoint to search in FastAPI, but am facing this error :</p> <pre><code>asyncpg.exceptions.AmbiguousParameterError: could not determine data type of parameter $2 </code></pre> <p>I have defined my sql query in queries.py :</p> <pre><code>GET_LOG_QUERY = &quot;&quot;&quot; SELECT * FROM activities WHE...
<python><sql><postgresql><fastapi>
2024-03-10 17:53:30
1
4,030
Lutaaya Huzaifah Idris
78,136,859
1,473,517
Find the optimal clipped circle
<p>Given a <code>NxN</code> integer lattice, I want to find the clipped circle which maximizes the sum of its interior lattice point values.</p> <p>Each lattice point <code>(i,j)</code> has a value <code>V(i,j)</code> and are stored in the following matrix <code>V</code>:</p> <pre><code> [[ 1, 1, -3, 0, 0, 3, ...
<python><algorithm><performance><optimization>
2024-03-10 17:45:45
3
21,513
Simd
78,136,787
3,017,869
While loop blocks when reading a buffer and writing to fifo
<p>I have a while loop that reads data from a buffer and writes it to a named pipe.</p> <p>The loop never executes, unless I add a small sleep interval inside the loop.</p> <p>This to me suggests there is a sync issue between reading data from the buffer and writing it to the pipe.</p> <p>If my hunch is correct, how do...
<python><picamera>
2024-03-10 17:22:45
0
573
user3017869
78,136,762
12,493,545
How to learn about print options keys from pycups?
<p>Via trial and error and looking into the ppd I wrote script below that allows you to print on different trays. I found the correct names for value and key of the job-options in the ppd.</p> <p>Just by looking into <code>conn.getPrinterAttributes(printer)['media-source-supported']</code> those options do not became c...
<python><cups><pycups>
2024-03-10 17:14:54
0
1,133
Natan
78,136,658
8,213,085
Jinj2 Extension - Skip clause if the variable is None
<h2>Intention</h2> <p>I'm trying to write a Jinja extension that emulates <a href="https://www.metabase.com/docs/latest/questions/native-editor/sql-parameters#optional-clauses" rel="nofollow noreferrer">Metabase's &quot;optional&quot; clauses</a>, where an expression between double square brackets <code>[[ ... ]]</code...
<python><jinja2>
2024-03-10 16:40:28
0
1,064
Bilbottom
78,136,298
12,178,630
Add external objects within matplotlib/plotly 3d plot
<p>I would like to know, how can I add or draw 3d model like for example those rectangular frames(gates), to a 3D plot in <code>matplotlib</code> or in <code>plotly</code>. I have searched for that quite for a long time, but I could not find a way that will allow me to do that. <a href="https://i.sstatic.net/Z0Qxp.jpg"...
<python><matplotlib><plotly>
2024-03-10 14:52:51
1
314
Josh
78,136,157
9,651,461
How do I create a keep_alive relationship between an object and the members of an aggregate return value in pybind11?
<p>I'm using pybind11 to generate Python mappings for a C++ library, and I'm using pybind11::keep_alive to manage the lifetime of C++ objects that are referenced by other objects. This works fine when the referrer is a direct return value, but I'm running into trouble when the referrer is part of an aggregate return va...
<python><c++><pybind11>
2024-03-10 14:06:41
1
1,194
Maks Verver
78,136,149
15,560,990
Cannot mutate a Python randomly generated list
<p>I'm just playing around with a local k8s cluster and created a simple app to containerize. I just want to print a reversed array. Disclaimer: I might be using the words &quot;lists&quot; and &quot;arrays&quot; interchangeably here :)</p> <p>So I defined two utility functions: one to generate lists with random int va...
<python><arrays>
2024-03-10 14:05:07
1
460
Dasph
78,135,769
893,254
Python jsons library and serializing a dataclass with optional None values
<p>I noticed some warning messages being printed by my Python code. These are coming from the <code>jsons</code> library when trying to perform serializing operations.</p> <pre><code>/home/user/project/.venv/lib/python3.11/site-packages/jsons/_common_impl.py:43: UserWarning: Failed to dump attribute &quot;None&quot; of...
<python><python-jsons>
2024-03-10 11:58:01
1
18,579
user2138149
78,135,624
12,314,521
Correct way to do multiprocessing with global variable in Python
<p>I'm working on large dataset, to make my function work I have to divide the dataset and do calculation by batch. Here is my code:</p> <pre><code>batch_size = 128 results = [] for i in range(0, len(queries), batch_size): result = linear_kernel(query[i:i+batch_size], dataset) results.append(result) </code></p...
<python><multiprocessing>
2024-03-10 11:08:15
1
351
jupyter
78,135,563
12,439,683
Why does overloading __new__ with singledispatchmethod not differentiate by type and always calls the initial method?
<p>I want my <code>__new__</code> method to behave differently in some cases and wanted to split it into overloaded functions with <a href="https://docs.python.org/3/library/functools.html#functools.singledispatchmethod" rel="nofollow noreferrer"><code>singledispatchmethod</code></a>.<br /> For other methods it works l...
<python><initialization><overloading><functools><single-dispatch>
2024-03-10 10:45:13
1
5,101
Daraan
78,135,417
7,323,032
Recursive Linked List Reversal Hangs with Print Statements
<p>I'm working on a Python program that reverses a linked list using recursion. I've implemented the reversal function and added print statements to help me understand the process. However, when I include certain print statements, the program hangs and doesn't complete. The reversal seems to work fine without those pri...
<python><recursion><linked-list>
2024-03-10 09:50:00
4
400
strboul
78,135,361
13,801,302
ValueError: 4.39.0.dev0 is not valid SemVer string
<p>I got the following error <code>ValueError: 4.39.0.dev0 is not valid SemVer string</code> in my code:</p> <pre class="lang-py prettyprint-override"><code>from GLiNER.gliner_ner import GlinerNER gli = GlinerNER() </code></pre> <p>Complete error message:</p> <pre class="lang-py prettyprint-override"><code>File ~/.../...
<python><pytorch><huggingface-transformers><large-language-model><huggingface>
2024-03-10 09:32:26
1
621
Christian01
78,135,082
6,515,755
How to connect aioboto3 with yandex s3
<p>I have yandex s3 storage <a href="https://cloud.yandex.ru/ru/docs/storage/s3/?from=int-console-help-center-or-nav" rel="nofollow noreferrer">https://cloud.yandex.ru/ru/docs/storage/s3/?from=int-console-help-center-or-nav</a> how to properly set up use of it with python aioboto3 lib</p>
<python><amazon-s3><yandex><aiobotocore>
2024-03-10 07:45:40
1
12,736
Ryabchenko Alexander
78,134,882
9,104,399
How to download structure (.cif) file from materialsproject.org using python
<p>I want to download cif file from <a href="https://next-gen.materialsproject.org" rel="nofollow noreferrer">https://next-gen.materialsproject.org</a> using python. I used the following code</p> <pre><code>from pymatgen.ext.matproj import MPRester # Initialize MPRester with your Materials Project API key mpr = MPRest...
<python>
2024-03-10 06:11:56
1
325
Alam
78,134,640
6,077,239
Polars: expanding window at fixed points
<p>I have a <code>Polars</code> dataframe with 3 columns - group, date, value. The goal is to calculate <code>cumsum(value)</code> for each expanding window ends at the first time point at each year for each <code>group</code>.</p> <p>For example, for the following sample dataframe:</p> <pre><code>import polars as pl ...
<python><python-polars>
2024-03-10 03:43:43
2
1,153
lebesgue
78,134,536
16,459,035
Function to search sequential values on a list
<p>I have the following list:</p> <pre><code>list = [ [2, 'A', '1'], [6, 'A', '2'], [6, 'S', '3'], [9, 'A', '4'], [6, 'A', '5'], [6, 'A', '6'], [6, 'S', '7'], [9, 'A', '8'], [9, 'A', '9'], [6, 'A', '10'], [10, 'S', '11'], [13, 'S', '12'], [13, 'S', '13'], [16, 'A', '14'] ] </co...
<python><list>
2024-03-10 02:36:03
1
671
OdiumPura
78,134,493
1,592,380
Zoom to KML layer with ipyleaflet
<p>I'm getting started with ipyleaflet with jupyter. I'd like to add a KML file layer to a basemap and zoom to that layer. The Kml is small, probably only a 10-50 acres. In qgis there is a zoom to layer function. Is there an easy way to do this.</p> <p>If not I plan on parsing the kml file for a point and setting that ...
<python><jupyter-notebook><ipyleaflet>
2024-03-10 01:59:47
1
36,885
user1592380
78,134,381
1,030,287
Does python shelve module allocate space in chunks of a certain size?
<p>I stored some pandas dataframes in a shelve and then stored the same dataframes but potentially containing a bit more data (maybe a few % more). The second shelve is about twice the size of the first one.</p> <p>Does the <code>shelve</code> module pre-allocate space in chunks by any chance? My first shelve is ~ 100M...
<python><python-3.x><shelve>
2024-03-10 00:33:49
0
12,343
s5s
78,134,317
1,592,380
Saving data from 1 cell to the next in Jupyter notebook
<p><a href="https://i.sstatic.net/h6T2n.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/h6T2n.png" alt="enter image description here" /></a></p> <p>I'm working in a Jupyter notebook. I want to open a kml file in 1 cell and do some analysis in the next. After selecting a file , the first cell has:</p> <pr...
<python><jupyter-notebook>
2024-03-10 00:01:23
1
36,885
user1592380
78,134,179
1,922,959
Python list index out of range error that is baffling me
<p>I'm trying to put together a flask app that works for a database as a final project for a class. I'm at the very end, and am encountering an error that baffles me. I'm pretty new to Python so my hope is that there is something very basic I'm missing here...</p> <p>Since it's flask, there are a bunch of <code>html<...
<python><sqlite><flask>
2024-03-09 22:45:27
1
1,299
jerH
78,133,939
12,425,893
Using PyMuPDF fitz to Swap the Overall Font in a Document
<p>I'm attempting to use fitz in a Python script to swap the font in a PDF document, and possibly change its size by an increment or ratio (in order to keep the elements to scale in respect to each other).</p> <p>Also, I suck at Python.</p> <p>Here's my attempt:</p> <pre><code>def change_font(input_pdf, output_pdf, new...
<python><pdf>
2024-03-09 21:03:53
0
301
GPWR
78,133,915
1,870,832
Why won't this duckdb query of s3/parquet data save 'EXPLAIN ANALYZE' profiling info?
<p>(UPDATED 3/10)</p> <p>Based on <a href="https://duckdb.org/dev/profiling" rel="nofollow noreferrer">this duckdb docs page on profiling</a>, I would have thought that my code snippet below should save a json file of profiling/timing stats to a <code>query_profile.json</code>, which I should be able to use to generate...
<python><amazon-web-services><amazon-s3><profiling><duckdb>
2024-03-09 20:55:26
1
9,136
Max Power
78,133,790
1,477,064
NiceGui: Multiline Button
<p>How can I make a multiline button in nicegui?</p> <p><a href="https://i.sstatic.net/FK2qY.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/FK2qY.png" alt="enter image description here" /></a></p> <p>Quasar example just uses a <code>&lt;br&gt;</code> tag, but it gets escaped by nicegui.</p>
<python><nicegui>
2024-03-09 20:16:47
2
4,849
xvan
78,133,787
13,815,493
Could not locate a bind configured on SQL expression or this Session
<p>I'm trying to use <code>Flask-SQLAlchemy</code> with multiple databases. And although I specify <code>bind_key</code> for the <code>Table</code> and it works fine for <code>Model</code> and the new session, <code>db.session.execute</code> doesn't look up the bind key on the metadata associated with the table and thr...
<python><sqlite><flask><sqlalchemy><flask-sqlalchemy>
2024-03-09 20:14:57
0
383
Andrew O.
78,133,591
2,518,602
Plotly Express Choropleth of Census Data Fails
<p>I am attempting to use <a href="https://plotly.com/python/plotly-express/" rel="nofollow noreferrer">Plotly Express</a> to create interactive choropleths of Census data which I retrieve using the <a href="https://github.com/censusdis/censusdis" rel="nofollow noreferrer">censusdis</a> package. This works for two of t...
<python><plotly><choropleth>
2024-03-09 19:11:19
1
2,023
Ari
78,133,261
2,386,605
Python package: `ImportError: cannot import name 'mod' from partially initialized module 'new_package' (most likely due to a circular import)
<p>I have a repo, which I would like to turn into a package</p> <pre><code>mypackage/ __init__.py multiplication.py mod/ __init__.py addition.py </code></pre> <p>The file <code>mod/addition.py</code> looks like</p> <pre><code>def add(a,b): return a+b </code></pre> <p>and the file <code>m...
<python>
2024-03-09 17:31:49
0
879
tobias
78,133,078
978,486
Run asyncio event loop embedded in thread
<p>I have a Qt application which uses pybind to embed python plugins providing some kind of handlers. From what I have read online gluing the event loops is nearly impossible. Now I wonder if it is possible to run an asyncio event loop in a c++ background thread and call gather in other threads (main or others, the scr...
<python><c++><qt><python-asyncio><pybind11>
2024-03-09 16:31:56
1
16,241
ManuelSchneid3r
78,132,998
22,208,056
convert file to dict where value is a code, e.g. PovScore(1,2)
<p>I have following data (7MB) and it's stored in transpostion.txt:</p> <pre><code>{'0x2df54c975eb48346': [PovScore(Cp(+57), BLACK), 5], ...} </code></pre> <p>I did try</p> <pre class="lang-py prettyprint-override"><code>with open(&quot;transposition.txt&quot;, &quot;r&quot;) as file: x = file.readline() transp...
<python>
2024-03-09 16:06:49
1
331
winapiadmin
78,132,993
7,338,672
Django ModuleNotFoundError on Heroku Release
<p>Similar to many previously stated issues yet unresolved in my case, I get a <code>ModuleNotFoundError</code> when deploying my Django project for release on Heroku, which works fine locally. I use <code>Django 4.0</code> and <code>Python 3.10.13</code>.</p> <p>Heroku release log:</p> <pre><code>Traceback (most recen...
<python><django><heroku>
2024-03-09 16:05:26
1
677
compmonks
78,132,778
5,267,751
Making an object's pretty-print representation different if it appears at top-level compared to nested
<p>In IPython, it is possible to make an object have a custom pretty-print representation as explained in <a href="https://stackoverflow.com/q/40193479/5267751">How to pretty print object representation in IPython</a> :</p> <pre class="lang-py prettyprint-override"><code>class MyObject: def _repr_pretty_(self, p, c...
<python><ipython>
2024-03-09 15:01:40
2
4,199
user202729
78,132,606
2,545,680
Why relative imports don't work without first importing package as a module
<p>I'm experiment with relative imports and have found very interesting case <a href="https://discuss.python.org/t/relative-imports/43183/2" rel="nofollow noreferrer">here</a>:</p> <pre><code>$ mkdir project $ cat &gt;&gt; project/one.py from . import two $ touch project/two.py $ python project/one.py Traceback (most ...
<python>
2024-03-09 14:01:33
1
106,269
Max Koretskyi
78,132,574
1,209,451
Tensorflow freeze shuffled dataset
<p>For training model I am using shuffled dataset which was created so:</p> <pre><code>train_dataset = train_dataset.shuffle(BUFFER_SIZE).batch(BATCH_SIZE).prefetch(tf.data.AUTOTUNE) </code></pre> <p>but after training I want to check the prediction results with some simple test function</p> <pre><code>def detect_wrong...
<python><tensorflow>
2024-03-09 13:51:34
1
3,220
Oleg
78,132,529
1,879,604
Python Metaclass: Create attributes for instance from the attribues for metaclass
<pre><code>class Meta(type): def __new__(cls, name, bases, attrs): # Generate a and b for the object based on x ? return super().__new__(cls, name, bases, attrs) class A(metaclass=Meta): def __init__(self, a, b): self.a = a self.b = b obj = A(x) </code></pre> <p>The <code>x</co...
<python><python-3.x>
2024-03-09 13:37:30
1
742
NEB
78,132,525
16,436,095
How to implement a cache in Python that efficiently supports both dictionary and heap operations?
<p>Is there a Python data structure that seamlessly combines a dictionary (with nested dictionaries or lists as values) and a heap, allowing sorting based on a specific value within the nested structures?</p> <pre class="lang-py prettyprint-override"><code>cache = {&quot;key1&quot;: {&quot;time&quot;: time1, &quot;info...
<python><caching><data-structures>
2024-03-09 13:37:13
1
370
maskalev
78,132,436
5,160,230
Pylance complaining on self.tr() method
<p>I'm developing an application with PySide6 6.6.2 and Python 3.11.8. Everything is working fine and mypy is happy. However, as I demonstrated on the following image, Pylance (on VSCode) keeps complaining that <code>self.tr()</code> cannot be accessed, though it actually should be acessible for any <code>QtCore.QObjec...
<python><qt><python-typing><pyside6><pyright>
2024-03-09 13:11:51
1
1,231
Heliton Martins
78,132,353
6,946,110
Pytest- How to remove created data after each test function
<p>I have a FastAPI + SQLAlchemy project and I'm using Pytest for writing unit tests for the APIs.</p> <p>In each test function, I create some data in some tables (user table, post table, comment table, etc) using SQLAlchemy. These created data in each test function will remain in the tables after test function finishe...
<python><sqlalchemy><pytest><fastapi>
2024-03-09 12:43:03
4
1,553
msln
78,132,293
6,087,589
Twitter user objects Python request
<p>I have the basic paid plan of Twitter. I am trying to obtain users information using this code:</p> <pre><code>import requests import json import config bearer_token = config.bearer_token url = &quot;https://api.twitter.com/2/users&quot; params = {'ids': '[4919451, 14151086]', 'user.fields':'name,descrip...
<python><twitter><python-requests>
2024-03-09 12:20:18
1
419
anitasp
78,131,942
7,207,987
Data structure - Shifting IDs to next dates in python
<p>I have a dataset where I have Date and ID.</p> <p><a href="https://i.sstatic.net/VJrhT.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/VJrhT.png" alt="enter image description here" /></a></p> <pre><code>Created the dataset using the following code import pandas as pd # Function to generate the speci...
<python><pandas><dataframe>
2024-03-09 10:08:19
2
623
NinjaR
78,131,920
4,643,584
how to send http 101 just with one CRLF
<p>There is an SSH client application that after requesting HTTP GET to an http server, should receive HTTP 101 switching protocol and a header for &quot;Protocol Version Exchange&quot;.</p> <p>The RFC 4253 -- section <a href="https://datatracker.ietf.org/doc/html/rfc4253#section-4.2" rel="nofollow noreferrer">4.2. Pro...
<python><python-3.x><ssh>
2024-03-09 09:59:15
1
24,534
Shakiba Moshiri
78,131,808
7,800,760
Checking if a docker compose service is reachable from another container
<p>I am writing a gunicorn/uvicorn/fastapi endpoint and want it to assess if a given port on another given container (using the compose service name) is reachable (and time it). For this example this service is called mematest and the container I want to check is memaapp.</p> <p>If I run a ping to memaapp from within m...
<python><docker>
2024-03-09 09:20:05
0
1,231
Robert Alexander
78,131,772
17,610,082
Getting NoSuchFile or Directory in subprocess
<p>I'm trying to run a CLI tool using <code>subprocess.run()</code>, but i'm getting irrelevant responses.</p> <p><strong>Folder structure</strong></p> <pre><code>script.py mytools |__tool_x |__tool_y </code></pre> <p><strong>Case:1</strong> Try to run the below command</p> <pre class="lang-py prettyprint-override">...
<python><python-3.x><shell><subprocess>
2024-03-09 09:00:28
0
1,253
DilLip_Chowdary
78,131,753
1,419,216
How to get parameters after hash mark # from a redirect URL in FastAPI?
<p>I am facing an issue while working with Redirect Url and getting the data from QueryParams in Python using FastApi. I am using Azure AD Authorization Grant Flow to log in, below is the code which generates the <code>RedirectResponse</code></p> <pre><code>@app.get(&quot;/auth/oauth/{provider_id}&quot;) async def oaut...
<python><http-redirect><azure-active-directory><fastapi><url-fragment>
2024-03-09 08:54:33
1
2,437
Shabir jan
78,131,711
5,790,653
How to round up integer number to multiple of 10
<p>I found how to round down or up a floating number to the next or previous integer number, but this is my issue:</p> <p>Suppose I have these numbers:</p> <pre class="lang-none prettyprint-override"><code>12 11 10 27 29 25 16 </code></pre> <p>I'm going to round up to the nearest 10. If number has 0 in the last digit, ...
<python>
2024-03-09 08:36:46
3
4,175
Saeed
78,131,645
9,112,151
How to run decorator at each request before wrapper?
<p>I'd like to run some code before a view even build dependencies (please note the comment marked with <code>===&gt;</code>):</p> <pre><code>from functools import wraps import uvicorn from fastapi import FastAPI, Depends app = FastAPI() def get_session(): print(&quot;get session&quot;) def transaction(): ...
<python><fastapi>
2024-03-09 08:09:50
0
1,019
Альберт Александров
78,131,641
15,491,774
Problem with python-keycloak package and FastApi
<p>I have a small application where i try to use Keycloak for authentication. If i use the endpoint /public to get the token of the test user and use that token wit Postman to send a request to /protected resource it wokrs.</p> <p>My issue is if i retrive the token from Keycloak over Postman with following call i can n...
<python><keycloak><fastapi>
2024-03-09 08:08:51
1
448
stylepatrick
78,131,589
2,386,930
Cassandra throws error('required argument is not an integer') when I set the consistency level to quorum
<p>Here is my table's definition.</p> <pre><code>CREATE TABLE chat_data.twitch_chat_by_broadcaster_and_timestamp ( broadcaster_id int, year_month int, timestamp bigint, message_id uuid, message text, PRIMARY KEY ((broadcaster_id, year_month), timestamp, message_id) ) WITH CLUSTERING ORDER BY (ti...
<python><cassandra>
2024-03-09 07:46:49
1
1,587
janovak
78,131,585
15,412,256
Polars Advanced Customized Expression Extension
<p>I want to construct a series of <strong>customized Polars Expression Extension</strong> following <a href="https://docs.pola.rs/py-polars/html/reference/api.html" rel="nofollow noreferrer">this tutorial</a>.</p> <p>This my attemp to create customized Polars Expressions:</p> <pre class="lang-py prettyprint-override">...
<python><python-polars>
2024-03-09 07:43:27
0
649
Kevin Li
78,131,353
10,431,634
what is a fast and simple way of packing signed values in 4 bits?
<p>I have a python list of integers, each being in the range [-8,7]. I want to pack these values into an array of bytes that i will send down a socket connection. Since these values can be represented by 4 bits in a two's complement representation, it should be possible to pack two such values in each byte. What is a g...
<python>
2024-03-09 05:39:55
1
909
astrophobia
78,131,338
2,411,377
How to set different filesystem for python os.path module?
<p>I'm developing a script that auto-deploys my Django project from my Windows machine to my local Raspberry server.</p> <p>Amongst the steps, there's a python script that has to be copyied to the server, and executed there. I execute it through an SSH call from <code>paramiko</code> module:</p> <pre><code>client.exec_...
<python><ssh><operating-system>
2024-03-09 05:30:09
1
353
Anderson Linhares
78,131,171
864,598
Python method chaining in functional programming style
<p>Below is Python code, where the <code>process_request_non_fp</code> method shows how to handle the problem with IF-ELSE condition (make-api -&gt; load-db -&gt; notify).</p> <p>I'm trying to get rid of IF-ELSE and chain in functional way with ERROR being handled in special method.</p> <p>Is there any helper from func...
<python><functional-programming><python-itertools><functools><toolz>
2024-03-09 03:42:09
3
1,014
M80
78,130,945
11,486,307
How to Prevent Gunicorn Workers/Threads from Blocking During External API Calls in Flask App
<p>I am developing a Flask application that makes external API calls and is served with Gunicorn configured to use multiple workers and threads. Despite this configuration, I observe that when one thread makes an API call, other workers and threads seem to wait for this call to complete before proceeding with their tas...
<python><multithreading><flask><gil>
2024-03-09 01:17:29
0
590
IdoS
78,130,876
22,437,734
ValueError with Scikit-Learn
<p><em>link to <a href="https://github.com/marsianjohncarter/StackOverflow--Sklearn_ValueError" rel="nofollow noreferrer">car data.csv</a></em></p> <p>My code:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import ...
<python><pandas><scikit-learn><model>
2024-03-09 00:42:16
2
473
Gleb
78,130,820
947,012
What instrumenting module name should I use with Opentelemetry tracer provider?
<p>The <a href="https://opentelemetry-python.readthedocs.io/en/latest/api/trace.html#opentelemetry.trace.TracerProvider" rel="nofollow noreferrer">documentation</a> suggests:</p> <blockquote> <p><code>instrumenting_module_name</code> (str) –<br /> The uniquely identifiable name for instrumentation scope, such as instru...
<python><open-telemetry><distributed-tracing>
2024-03-09 00:09:56
0
3,234
greatvovan
78,130,757
9,957,710
How to run IJulia using the PythonCall CondaPkg Python installation rather than PyCall.jl/Conda.jl
<p>It seems that PythonCall.jl and CondaPkg.jl are becoming increasingly useful packages. In particular CondaPkg provides tools for the management of Python's virtual environments via <code>CondaPkg.toml</code> which is very convenient due to its similarity to <code>Project.toml</code>.</p> <p>However, when using Jupyt...
<python><jupyter-notebook><julia><conda>
2024-03-08 23:46:01
1
42,537
Przemyslaw Szufel
78,130,748
3,460,486
Google Chat API get list of messages for a space
<p>I am trying to get <a href="https://developers.google.com/workspace/chat/list-messages" rel="nofollow noreferrer">this example</a> in Python working.</p> <pre><code>def get_msg(): creds = None if os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json', ['https://www.g...
<python><attributeerror><google-chat>
2024-03-08 23:44:42
1
493
user3460486