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,427,635
3,926,543
custom SGD was not updating parameters
<p>I was learning pytorch from d2l website and writing a simple linear regression model. Here is my optimizer:</p> <pre><code>class SGD(): def __init__(self, params, lr): self.params = params self.lr = lr def step(self): for param in self.params: param -= self.lr * param.grad...
<python><deep-learning><pytorch>
2024-05-04 02:52:07
1
17,427
mt1022
78,427,494
480,118
Best way to split jagged array on first element and fill with other elements
<p>It's hard to describe this problem, but the code below should clarify. Basically i start with an array where first element is another array of N size. the rest of the array is a single element. I want to split the first element a for every partion, fill with the remainder of the array:</p> <pre><code>import pandas...
<python><pandas><numpy>
2024-05-04 01:02:34
1
6,184
mike01010
78,427,374
6,135,182
Wrap fortran with python using ctypes (just ctypes, no cython or f2py or similar) and turn it into a python package (for python>=3.12)
<p>I have looked at (and used as inspiration) the following SO threads and GitHub repositories:</p> <ul> <li><a href="https://stackoverflow.com/questions/15875533/using-python-ctypes-to-interface-fortran-with-python">Using python-ctypes to interface fortran with python</a></li> <li><a href="https://stackoverflow.com/qu...
<python><fortran><ctypes><python-packaging><meson-build>
2024-05-03 23:49:18
0
1,450
Zaus
78,427,086
825,227
Parse string with specific characters if they exist using regex
<p>I have text containing assorted transactions that I'm trying to parse using regex.</p> <p>Text looks like this:</p> <pre><code>JT Meta Platforms, Inc. - Class A Common Stock (META) [ST]S (partial) 02/08/2024 03/05/2024 $1,001 - $15,000 F S: New S O: Morgan Stanley - Select UMA Account # 1 JT Microsoft Corporation - ...
<python><regex>
2024-05-03 21:51:30
2
1,702
Chris
78,426,975
7,227,627
How to relate Matplotlib's fig.add_axes local coordinates with my coordinates?
<h1>Question</h1> <p>Motivated by this example form Matplotlib <a href="https://matplotlib.org/stable/gallery/subplots_axes_and_figures/axes_demo.html#sphx-glr-gallery-subplots-axes-and-figures-axes-demo-py" rel="nofollow noreferrer">here</a> I would like to make a similar one. I have run into following question: <stro...
<python><matplotlib>
2024-05-03 21:10:47
2
1,998
pyano
78,426,972
3,827,505
How to properly position child element to its parent?
<p>I was trying to get a better understanding of how kivy parent/child positioning works SPECIFICALLY with the FloatLayout because it allows to place elements based on window size and therefore super dynamic.</p> <p>This code below is simple. I'm just trying to get label to base ITS position from its parent position, a...
<python><android><kivy><kivy-language><kivymd>
2024-05-03 21:09:53
1
318
Omar Moodie
78,426,957
2,153,235
Use json_normalize with extraneous dictionary layer with single key?
<p>I have automated identification system (AIS) data as nested dictionaries in a pandas dataframe. Here is an example:</p> <pre><code>dfAIS Out[18]: Message ... MetaData 0 {'ShipStaticData': {'AisVersion': 1, 'CallSign.....
<python><json><pandas><dictionary><data-ingestion>
2024-05-03 21:05:45
2
1,265
user2153235
78,426,876
13,227,420
Accessing values in a dictionary with JMESPath in Python when the value is an integer (e.g.: 1)
<p>Using the dictionary:</p> <pre class="lang-py prettyprint-override"><code>d = {'1': 'a'} </code></pre> <p>How can I extract the value <code>a</code> using the JMESPath library in Python?</p> <p>The following attempts did not work:</p> <pre class="lang-py prettyprint-override"><code>import jmespath value = jmespath....
<python><jmespath>
2024-05-03 20:41:56
1
394
sierra_papa
78,426,875
15,020,312
Get one unique value in several lists in Python
<p>I have this data:</p> <pre><code>data = {23: ['WA', 'NV', 'AZ', 'OH'], 24: ['NV', 'OH'], 25: ['NV', 'OH']} </code></pre> <p>I'm trying to get one unique values from each keys list, like this:</p> <pre><code>{23: ['WA'], 24: ['NV'], 25: ['OH']} </code></pre> <p>But in my current code, it returns something different, ...
<python><list><dictionary>
2024-05-03 20:41:52
0
592
artiest
78,426,731
180,275
Why does a requests.get(...) call hang
<p>The following simple python script that uses <code>requests.get</code> to execute a GET request does not return on my computer:</p> <pre><code>import requests print(requests.get('https://api.openstreetmap.org/api/0.6/node/1894790125')) </code></pre> <p>However, I am able to get an &quot;instant&quot; response with t...
<python><http><connection><openstreetmap>
2024-05-03 20:00:08
0
40,876
René Nyffenegger
78,426,675
2,599,709
Mounting multiple Gradio apps with FastAPI
<p>Is it possible to mount multiple Gradio apps with FastAPI? I'd like to have two endpoints: localhost:8000 and localhost:8000/debug. The /debug endpoint would ultimately be a bit more complex and log more data. I thought I'd be able to do something like this:</p> <pre class="lang-py prettyprint-override"><code>from f...
<python><fastapi><gradio>
2024-05-03 19:44:39
0
4,338
Chrispresso
78,426,646
5,561,472
How to run LLM from transformers library under Windows without GPU?
<p>I have no GPU but I can run <code>openbuddy-llama3-8b-v21.1-8k</code> from <code>ollama</code>. It works with speed of ~1 t/s.</p> <p>But it doesn't work when I try the following code:</p> <pre><code>from transformers import ( AutoModelForCausalLM, AutoTokenizer, GenerationConfig, ) import torch new_mod...
<python><huggingface-transformers><large-language-model>
2024-05-03 19:35:04
1
6,639
Andrey
78,426,636
11,815,307
Cython: Protecting a cdef class if __init__ is not called
<p>I'm wrapping some Fortran/C codes with Cython. The <code>__init__</code> method of my <code>cdef class</code> allocates some memory in C. I believe that this memory allocation has to happen in the <code>__init__</code> method instead of the <code>__cinit__</code> method because the allocation depends on inputs to <c...
<python><c><cython>
2024-05-03 19:32:18
0
699
nicholaswogan
78,426,633
825,227
Conditional exception handling in Python
<p>I'm processing transactions from a list to make individual data items more easily accessible.</p> <p>I've set up the below code to process a list of transactions item by item with a <code>try-except</code> block to exclude problem transactions for the time being.</p> <p>A sample transaction might look like the below...
<python><conditional-statements><try-catch>
2024-05-03 19:31:12
1
1,702
Chris
78,426,546
13,578,682
Where did sys.modules go?
<pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; del sys.modules['sys'] &gt;&gt;&gt; import sys &gt;&gt;&gt; sys.modules Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; AttributeError: module 'sys' has no attribute 'modules' </code></pre> <p>Why does re-imported <code>sys</...
<python><python-internals><python-3.12>
2024-05-03 19:05:38
1
665
no step on snek
78,426,505
20,898,396
Match generic type: "Unbound" is not a class
<p>I am trying to tell whether a variable is of type T using the syntax</p> <pre class="lang-py prettyprint-override"><code>match variable: case ClassName(): </code></pre> <p>However, I get a <code>&quot;Unbound&quot; is not a class</code> error when using a generic. Why is T unbound?</p> <pre class="lang-py prettypr...
<python><python-typing>
2024-05-03 18:54:26
1
927
BPDev
78,426,478
465,183
Python's Selenium4 ChromeDriver crash when in non headless mode (works in headless mode): selenium.common.exceptions.SessionNotCreatedException
<p>I have a Python's Selenium4 with ChromeDriver script that refuse to start when in non headless mode:</p> <p>I have another scripts with the same imports, and the other ones don't crash.</p> <pre><code>Traceback (most recent call last): File &quot;/path/to/selenium_scraper.py&quot;, line 92, in &lt;module&gt; d...
<python><selenium-webdriver><selenium-chromedriver>
2024-05-03 18:47:13
1
187,771
Gilles Quénot
78,426,245
1,169,091
Package installed from test.pypi.org is not the same folder structure as was uploaded to the repository
<p>I created a package and uploaded it to test.pypi.org: <a href="https://test.pypi.org/project/name-generator-nicomp/0.0.2/" rel="nofollow noreferrer">https://test.pypi.org/project/name-generator-nicomp/0.0.2/</a></p> <p>The logic reads a text file that I want to include in the package. In my initial design I put the ...
<python><pypi><hatch>
2024-05-03 17:49:48
1
4,741
nicomp
78,426,163
9,191,338
How do python main process and forked process share gc information?
<p>From the post <a href="https://stackoverflow.com/a/53504673/9191338">https://stackoverflow.com/a/53504673/9191338</a> :</p> <blockquote> <p>spawn objects are cloned and each is finalised in each process</p> <p>fork/forkserver objects are shared and finalised in the main process</p> </blockquote> <p>This seems to be ...
<python><python-multiprocessing>
2024-05-03 17:30:25
2
2,492
youkaichao
78,426,073
10,240,072
Best way to avoid a loop
<p>I have 2 dataframes of number x and y of same length and an input number a. I would like to find the fastest way to calculate a third list z such as :</p> <ul> <li><code>z[0] = a</code></li> <li><code>z[i] = z[i-1]*(1+x[i]) + y[i]</code></li> </ul> <p>without using a loop like that :</p> <pre class="lang-py prettyp...
<python><pandas><dataframe><optimization>
2024-05-03 17:09:48
1
313
Fred Dujardin
78,426,050
4,212,158
How to index a numpy memmap without creating an in-memory copy?
<p>Which indexing operations on <code>numpy.memmap</code> arrays return an in-memory copy vs a view that is still backed by a file? The <a href="https://numpy.org/doc/stable/reference/generated/numpy.memmap.html#numpy.memmap" rel="nofollow noreferrer">documentation</a> doesn't explain which indexing operations are &quo...
<python><arrays><numpy><numpy-memmap><memmap>
2024-05-03 17:05:30
1
20,332
Ricardo Decal
78,425,933
3,070,181
How to get rid of a popup menu if opened by mistake on linux
<p>I have a Treeview with a bound context menu which appears when I right click on the mouse. Sometimes I right click by accident. How do I get rid of the context menu without adding an item to close it?</p> <pre><code>import tkinter as tk from tkinter import ttk MEMBER_COLUMNS = ( ('first_name', 'First name', 1...
<python><linux><tkinter>
2024-05-03 16:42:54
0
3,841
Psionman
78,425,804
11,318,930
polars: how to optimize sink_parquet
<p>I'm working on string manipulation in large files which is explained <a href="https://stackoverflow.com/questions/78202730/polars-efficient-way-to-apply-function-to-filter-column-of-strings">here</a>. Based on the recommendations I received, I am using <code>LazyFrame</code>s and the <code>sink_parquet</code> funct...
<python><python-3.x><rust><parquet><python-polars>
2024-05-03 16:13:07
0
1,287
MikeB2019x
78,425,471
13,132,640
Custom bin sizes on heatmap within seaborn pairgrid?
<p>I have a use-case where I will regularly receive data in the same format and awnt to quickly compare individual distributions of each variable as well as pairwise / bivariate distributions. I originally was using sns.pairplot out of box, but I realized the scatter plots are not great for my application: I sometimes ...
<python><matplotlib><seaborn>
2024-05-03 15:06:32
1
379
user13132640
78,425,430
2,703,209
How to kill a subprocess and all of its descendants on timeout in Python?
<p>I have a Python program which launches subprocesses like this:</p> <pre><code>subprocess.run(cmdline, shell=True) </code></pre> <p>A subprocess can be anything that can be executed from a shell: Python programs, binaries or scripts in any other language.</p> <p><code>cmdline</code> is something like <code>export PYT...
<python><linux><subprocess><freebsd>
2024-05-03 14:58:40
2
6,269
user149408
78,425,424
12,902,027
How can you specify python runtime version in vercel?
<p>I am trying to deploy a simple FastAPI app to vercel for the first time. Vercel.json is exactly below.</p> <pre class="lang-json prettyprint-override"><code>{ &quot;devCommand&quot;: &quot;uvicorn main:app --host 0.0.0.0 --port 3000&quot;, &quot;builds&quot;: [ { &quot;src&quot;: &quot;api/index.py&quo...
<python><fastapi><vercel>
2024-05-03 14:57:03
1
301
agongji
78,425,396
18,730,707
Can't find table position in image with opencv
<p>I want to process tabular data from images. To do this, we read the image with <code>opencv</code> and find where the table is by going through the following seven steps. In image number 7, we plan to crop based on the border. In the following example data, it works exactly what I want. This is because there is a bl...
<python><opencv>
2024-05-03 14:49:56
2
878
na_sacc
78,425,322
3,649,441
Pandas daily to weekly OHLC data resampling
<p>I'm resampling daily OHLC data fetched from Yahoo Finance to weekly with the following code:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import yfinance as yf ticker = yf.Ticker('AAPL') daily_data = ticker.history(start='2024-04-01', end='2024-05-03', interval='1d') weekly_data = daily_...
<python><python-3.x><pandas><yfinance>
2024-05-03 14:35:22
1
1,009
Chris
78,425,234
145,682
cannot fill curses window region with text - is this the design?
<p>Here is code to simply fill a terminal screen:</p> <pre class="lang-py prettyprint-override"><code>import curses def main(stdscr): max_y = curses.LINES max_x = curses.COLS rows = max_y - 1 cols = max_x - 3 total_chars1 = rows * cols stdscr.addstr(f'Screen: {max_y}x{max_x} = {max_x ...
<python><python-curses>
2024-05-03 14:21:07
0
11,985
deostroll
78,425,228
1,654,226
How do I type a method in base class that returns another class instance that is defined in child class?
<p>Imaging a base class <code>BaseA</code> with method <code>get_b</code> that returns an instance of class <code>B</code>. Class <code>B</code> is defined in both <code>BaseA</code> and another class <code>Child</code> that inherits from <code>BaseA</code>.</p> <pre class="lang-py prettyprint-override"><code>class Bas...
<python><python-typing><pyright>
2024-05-03 14:19:54
1
2,361
squgeim
78,425,091
1,951,507
Unexpected behavior with "only" restriction type in owlready2
<p>I don't understand the reasoning for model below in owlready2:</p> <pre><code>class Equipment(Thing): pass class Task(Thing): pass class EquipmentTask(Task): pass class task_executed_by_equipment(EquipmentTask &gt;&gt; Equipment, FunctionalProperty): pass class task_included_subtasks(Task &gt;&gt; Task): pass cla...
<python><owl><ontology>
2024-05-03 13:49:20
0
1,052
pfp.meijers
78,424,991
3,941,671
pyside6 QObject::killTimer message when running GUI in separate thread
<p>I want to set up a gui that runs in its own thread. Therefor I create my own class <code>MainWindow</code> as a subclass of <code>QMainWindow</code> and created a function <code>run()</code> that is executed in another thread (see code below).</p> <p>Now my problem: When I execute <code>run()</code> in a separate th...
<python><multithreading><pyqt><pyside6>
2024-05-03 13:28:42
0
471
paul_schaefer
78,424,943
821,832
Configure VS Code using settings.json to use ruff instead of pylint, pylance, etc
<p>I am looking to be able to set up <code>settings.json</code> used by VS Code so that I can use ruff instead of pylint, pylance, flake8 linting. I am hoping to get the rules into <code>settings.json</code> and not have external <code>.toml</code> files.</p> <p>Here is what my Python settings currently include:</p> <...
<python><visual-studio-code><ruff>
2024-05-03 13:19:32
1
614
Charles Plager
78,424,923
14,471,688
Faster way to access the value of a huge dictionary from a huge list of arrays in python
<p>I am curious whether I can access the value of a huge dictionary faster from a huge list of arrays.</p> <p>Here is a simple example:</p> <pre><code>import numpy as np my_list = [np.array([ 1, 2, 3, 4, 5, 6, 8, 9, 10]), np.array([ 1, 3, 5, 6, 7, 10]), np.array([ 1, 2, 3, 4, 6, 8, 9, 10]), np.array([ ...
<python><arrays><list><numpy>
2024-05-03 13:15:30
0
381
Erwin
78,424,901
15,341,457
Scrapy - Setting Feed Exporter Overwrite to True
<p>I developed a Scrapy spider and I want to execute it without using the command line. That's why I use <code>CrawlerProcess</code>. I also want the output to be saved to a json file. <strong>Feed exporters</strong> are perfect in my case and the only way I could get them to work is by updating the settings this way:<...
<python><scrapy><export>
2024-05-03 13:10:45
1
332
Rodolfo
78,424,869
1,492,956
Enable/Disable Logging block in Vector CANoe through COM
<p>I am trying to Enable/Disable the Logging Block using COM Objects in python. I could access the individual loggings from the collection, but cannot enable them programatically. I tried below way, the Application starts and starts measurement, but no log file is created.</p> <pre><code>app = client.dynamic.Dispatch('...
<python><win32com><canoe>
2024-05-03 13:03:01
1
902
lerner1225
78,424,819
1,511,294
Pandas setting frequency in a time series dataframe
<p>I have a data frame with monthly data and it looks like this.</p> <pre><code> metric date 2021-01-01 0.822201 2021-02-01 0.845884 2021-03-01 0.868405 2021-04-01 0.866245 2021-05-01 0.861446 2021-06-01 0.859356 2021-07-01 0.864788 2021-08-01 0.868941 2021-09-01 0.875224 2021-10-01 0.868509 20...
<python><pandas>
2024-05-03 12:52:22
1
1,665
Ayan Biswas
78,424,750
1,014,809
azure batch update only one property of a job
<p>I have some python code to create a job, and add some tasks. I want the job to <code>OnAllTasksComplete.terminate_job</code>, but I can't set this during job creation since then it will complete immediately before I have a chance to add tasks. So I do it after.</p> <p>Here my python code to update a job:</p> <pre><c...
<python><azure><azure-batch>
2024-05-03 12:40:44
1
827
ZirconCode
78,424,722
447,426
dpkt how check checksum of a given/ received package
<p>i have code that receives pcap packates as <code>bytes</code>. I decode the IP and UDP layer and later the proprietary app layer within (&quot;UMS&quot;).</p> <p>I would like to check the IP header checksum and the UDP checksum prior continuing. How to do this?</p> <p>Here is my current code:</p> <pre><code>import i...
<python><udp><ip><pcap><dpkt>
2024-05-03 12:34:10
1
13,125
dermoritz
78,424,685
6,435,921
Vectorising this function in python efficiently
<h1>Problem Description</h1> <p>I have written Python code to compute the following function, for fixed <code>y_i</code> and fixed <code>z_i</code>.</p> <p><a href="https://i.sstatic.net/AJzfMom8.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/AJzfMom8.png" alt="enter image description here" /></a></p> <...
<python><numpy><vectorization>
2024-05-03 12:27:10
1
3,601
Euler_Salter
78,424,654
13,561,669
how to access elements inside svg object with selenium
<p>I am trying to access speed data from <a href="https://www.openstreetbrowser.org/#map=16/53.3989/-3.0881&amp;basemap=osm-mapnik&amp;categories=car_maxspeed" rel="nofollow noreferrer">OpenStreetBrowser</a> with Selenium but I am unable to access SVG elements of the website.</p> <p>This is what I've tried so far</p> <...
<python><selenium-webdriver><web-scraping><openstreetmap>
2024-05-03 12:18:43
1
307
Satya Pamidi
78,424,583
9,536,103
Last value in precision_recall_curve for precision is 1 when it shouldn't be
<p>I am trying to use the <code>precision_recall_curve</code> in <code>sklearn</code>. However, I don't understand the output it is giving me and I think it looks wrong.</p> <pre><code>import numpy as np from sklearn import metrics y = np.array([0, 0, 1, 0]) pred = np.array([0.1, 0.2, 0.3, 0.4]) precision, recall, thre...
<python><scikit-learn>
2024-05-03 12:05:00
1
1,151
Daniel Wyatt
78,424,534
92,516
Terminate cleanly after an exact number of Task executions have occurred across multiple processes
<p>Following on from a previous question<a href="https://stackoverflow.com/q/78420717/92516,">1</a>, I want locust to terminate a run once I've performed an exact number of requests across multiple Users and processes. I can track the progress on a per-User basis, but I'm struggling to communicate that to locust in a c...
<python><locust>
2024-05-03 11:53:25
1
9,708
DaveR
78,424,517
4,564,080
What is wrong with my function overload with 8 different argument combinations?
<p>I am trying to override Pydantic's and SQLModel's <code>Field</code> function.</p> <p>I have 3 boolean arguments which indicate different combinations:</p> <ol> <li>If <code>is_table_field == True</code>, then return SQLModel's <code>FieldInfo</code>, else return Pydantic's <code>FieldInfo</code></li> <li>If <code>i...
<python><function><arguments><overloading>
2024-05-03 11:49:37
0
4,635
KOB
78,424,501
1,320,143
How can I implement multiple optional fields but with at least one of them mandatory in MyPy or Pydantic?
<p>I'm trying to write a minimal, custom, JSON:API 1.1 implementation using Python.</p> <p>For the top level, the RFC/doc says:</p> <p><a href="https://jsonapi.org/format/#document-top-level" rel="nofollow noreferrer">https://jsonapi.org/format/#document-top-level</a></p> <blockquote> <p>A document MUST contain at leas...
<python><mypy><pydantic><json-api>
2024-05-03 11:45:31
1
1,673
oblio
78,424,238
2,745,609
Python normalize a hierarchical tree into pandas dataframe
<p>I have the following dataframe which holds a tree-like structure. The hierarchy levels range from 2 to 4:</p> <pre class="lang-py prettyprint-override"><code>df = Hierarchy ID Value 0 1.0 T1 1 1.1 T2 2 1.1.1 T3 3 1.1.2 T4 4 1.2 T5 5 1.2.1 T6 6 ...
<python><pandas>
2024-05-03 10:50:59
2
474
Solijoli
78,424,042
315,168
A persistent hash of a Python function code for caching
<p>I am running data processing jobs that are - Inputs (Pandas Series) - Python function</p> <p>I'd like to make this so that if inputs (function arguments) and the function itself (function body and code) are the same, I do not run the calculation, but just cache the results on the disk.</p> <p>While function results ...
<python>
2024-05-03 10:12:14
1
84,872
Mikko Ohtamaa
78,424,000
17,741,484
Is a pandas.DataFrame still sorted after using the method `query`?
<p>I am working on a dataframe <code>df</code> in python. I need to query and sort the results multiple times, but on different columns:</p> <pre class="lang-py prettyprint-override"><code>for x in X: # query the dataframe and sort the result query_result = df.query(f&quot;column_name == '{x}'&quot;).sort_values(...
<python><pandas>
2024-05-03 10:04:30
1
357
27636
78,423,909
1,120,410
Fast way to iterate over an Arrow.Table with 30 million rows and 25 columns in Julia
<p>I saved a Python Pandas <code>DataFrame</code> of size (30M x 25) as an Apache Arrow table. Then, I'm reading that table in Julia as:</p> <pre><code>input_arrow = Arrow.Table(&quot;path/to/table.arrow&quot;) </code></pre> <p>My question is how can I iterate over the rows of <code>input_arrow</code> in an efficient w...
<python><pandas><julia><apache-arrow>
2024-05-03 09:47:54
1
2,985
Lay González
78,423,788
202,335
How can I get total assets with yfinance?
<p>I tried with the code below:</p> <pre><code>stock = yf.Ticker(ticker) info = stock.info totalShares = info.get('sharesOutstanding') totalAssets=info.get('totalAssets') </code></pre> <p>I can not get total assets.</p>
<python><yfinance>
2024-05-03 09:26:05
1
25,444
Steven
78,423,690
14,849,198
How to filter tensorflow tuple dataset?
<pre><code>import tensorflow as tf # Create dummy data image_data = [tf.constant([1]), tf.constant([2]), tf.constant([3])] caption_data = [tf.constant([10]), tf.constant([20]), tf.constant([30])] target_data = [tf.constant([100]), tf.constant([200]), tf.constant([300])] # Create a dataset from the dummy data dataset ...
<python><tensorflow>
2024-05-03 09:05:38
2
428
SoraHeart
78,423,575
10,273,940
How to prevent typehint errors for Pydantic datetime validation
<p>I am designing a Pydantic model that contains some datetime fields, like so:</p> <pre><code>from pydantic import BaseModel, Field from datetime import datetime class Event(BaseModel): start_date: datetime = Field(..., description=&quot;datetime in format YYYY-mm-ddTHH:MM:SS&quot;) end_date: datetime = Field...
<python><python-typing><pydantic>
2024-05-03 08:41:01
1
314
Harm van den Brand
78,423,528
18,878,905
Create an infinite callback loop in Dash
<p>I'm trying to create callback loop in dash. My idea was to have a button that reclicks on itself until we hit n_clicks = 10.</p> <pre><code>import time import dash import dash_bootstrap_components as dbc from dash import Dash, html, Input, Output app = Dash(__name__, external_stylesheets=[dbc.themes.BO...
<python><loops><callback><plotly-dash>
2024-05-03 08:33:03
2
389
david serero
78,423,469
13,238,846
Getting 400 when trying to download sharepoint file using python and 365 clinet
<p>I am trying to download sharepoint file using office 365 python clinet and user credentials. But I am getting following error when trying download. But I am able to list down the files without any issues. Here's my code.</p> <pre><code>from office365.runtime.auth.authentication_context import AuthenticationContext,U...
<python><sharepoint><office365api>
2024-05-03 08:20:23
1
427
Axen_Rangs
78,423,393
16,383,578
Problem with converting ADPCM to wav in Python
<p>I am trying to extract audio files from .fsb files used by Dragon Age: Origins. FSB means &quot; FMOD Sample Bank&quot; and the game uses FSB4. Because it is a proprietary format, Google is almost useless in finding relevant information about it, but I managed to find <a href="http://aezay.dk/aezay/fsbextractor/" re...
<python><audio><pcm><adpcm>
2024-05-03 08:01:20
1
3,930
Ξένη Γήινος
78,423,363
7,745,011
Force venv to create virtual environment in "bin" instead of "Scripts" folder
<p>According to the <a href="https://docs.blender.org/api/current/info_tips_and_tricks.html#bundled-python-extensions" rel="nofollow noreferrer">Blender docs</a> you can replace the python installation that comes with blender with your own:</p> <blockquote> <p>Copy or link the extensions into Blender’s Python subdirect...
<python><virtualenv><blender>
2024-05-03 07:54:07
1
2,980
Roland Deschain
78,423,352
2,487,835
SpaCy GPU memory utilization for NER training
<p>My training code:</p> <pre><code>spacy.require_gpu() nlp = spacy.blank('en') if 'ner' not in nlp.pipe_names: ner = nlp.add_pipe('ner') else: ner = nlp.get_pipe('ner') docs = load_data(ANNOTATED_DATA_FILENAME_BIN) train_data, test_data = split_data(docs, DATA_SPLIT) unique_labels = set(ent.label_ for doc i...
<python><gpu><spacy><named-entity-recognition><custom-training>
2024-05-03 07:52:34
1
3,020
Lex Podgorny
78,423,306
996,302
How to asynchronously run Matplolib server-side with a timeout? The process hangs randomly
<p>I'm trying to reproduce the ChatGPT code interpreter feature where a LLM create figures on demand by executing to code.</p> <p>Unfortunately Matplotlib hangs 20% of time, I have not managed to understand why.</p> <p>I would like the implementation:</p> <ul> <li>to be non-blocking for the rest of the server</li> <li>...
<python><matplotlib><asynchronous><process><event-loop>
2024-05-03 07:40:36
1
6,592
L. Sanna
78,423,305
1,559,401
Managing multiple OpenGL VBO and VAO instances in Python
<p>I need some help with the code found below, where I try to load an OBJ using Impasse (a fork of PyAssimp) that may contain multiple meshes. In order to do that and help myself with debugging I am storing all the data in a dictionary structure, which allows me to grab the vertex, color and face data in an easy way.</...
<python><opengl><pyopengl>
2024-05-03 07:40:33
1
9,862
rbaleksandar
78,423,080
2,355,176
Pyotp Microsoft Authenticator not displaying Logo after Scanning QR
<p>I am using Pyotp python package to generate OTP's using python, the generated QR is perfectly working fine, Microsoft authenticator can add the required information and code matches as expected the only problem I am facing is the added image is not displaying in logo, the logo always consists of character initials.<...
<python><python-3.x><authenticator><pyotp>
2024-05-03 06:47:38
0
2,760
Zain Ul Abidin
78,423,078
246,241
How do I keep a correct API spec when using a ModelSerializer?
<p>I'm using a <a href="https://docs.pydantic.dev/latest/concepts/serialization/#custom-serializers" rel="nofollow noreferrer">model serializer</a> to <a href="https://stackoverflow.com/questions/78421170/pydantic-how-do-i-represent-a-list-of-objects-as-dict-serialize-list-as-dict">serialize a list as a dictionary</a> ...
<python><fastapi><pydantic>
2024-05-03 06:47:27
0
11,661
tback
78,422,754
424,957
How to keep same size when save pictures in python matplotlib?
<p>I use code as below to plot graphs and save fig to png files, but all png files are not in the same size (width x height), how can I let all of them in the same size?</p> <pre><code>fig, ax = plt.subplots(nrows=1, ncols=1, figsize(20, 10)) fig.savefig('myImage.png', bbox_inches='tight', dpi=300) </code></pre> <p>The...
<python><matplotlib><image-scaling><image-size>
2024-05-03 05:00:15
0
2,509
mikezang
78,422,647
1,242,028
Sort a list of points in row major snake scan order
<p>I have a list of points that represent circles that have been detected in an image.</p> <pre><code>[(1600.0, 26.0), (1552.0, 30.0), (1504.0, 32.0), (1458.0, 34.0), (1408.0, 38.0), (1360.0, 40.0), (1038.0, 54.0), (1084.0, 52.0), (1128.0, 54.0), (1174.0, 50.0), (1216.0, 52.0), (1266.0, 46.0), (1310.0, 46.0), (1600.0, ...
<python><algorithm><sorting>
2024-05-03 04:07:56
2
2,359
noel
78,422,418
788,153
How to run Python files by clicking a link in another file?
<p>New to Streamlit and Flask. I am trying to create a simple page containing links. When these links are clicked, I want the connected files to run in the new window or tab. Here is my code that is trying to achieve this. But the new link does not show anything. Also, the port keeps on changing.</p> <p><code>main.py</...
<python><flask><streamlit>
2024-05-03 02:16:18
1
2,762
learner
78,422,323
825,227
How to match a string not surrounded by brackets and parenthesis using regex
<p>I have a collection of strings that take, for example, the following form:</p> <pre><code>(GOOGL) [ST]S (partial) 02/01/2024 03/01/2024 $1,001 - $15,000 (PHG) [ST]P 02/12/2024 03/01/2024 $1,001 - $15,000 (PFE) [ST] P 02/12/2024 03/01/2024 $1,001 - $15,000 (UL) [ST]S 02/12/2024 03/01/2024 $1,001 - $15,000 </cod...
<python><regex>
2024-05-03 01:24:33
3
1,702
Chris
78,422,215
7,065,886
model.fit not recognizing labels in tf.data.Dataset
<p>I am creating a dataset by generator like this</p> <pre class="lang-py prettyprint-override"><code>tfds = tf.data.Dataset.from_generator(streamFromFile, output_signature=tf.TensorSpec(shape=(240,120), dtype=tf.uint16)) </code></pre> <p>The model is an autoencoder that internally calculates the loss, so the training ...
<python><tensorflow><keras>
2024-05-03 00:29:27
0
905
TheClockTwister
78,422,200
5,105,207
GEKKO: Parameter estimation on a delayed system with known delay
<p>Here is a simple delayed system, or say a DDE</p> <p><a href="https://i.sstatic.net/FyfpFPeV.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/FyfpFPeV.png" alt="enter image description here" /></a></p> <p>I believe the parameter <code>k</code> can be estimated with direct collocation method when <code>...
<python><gekko>
2024-05-03 00:22:43
1
1,413
Page David
78,422,084
9,191,338
What is the lifecycle of a process in python multiprocessing?
<p>In normal Python code, I can understand the lifecycle of the process. e.g. when executing <code>python script.py</code>:</p> <ol> <li>shell receives the command <code>python script.py</code>, and os creates a new process to start executing <code>python</code> .</li> <li><code>python</code> executable sets up the int...
<python><multiprocessing><python-multiprocessing>
2024-05-02 23:20:01
1
2,492
youkaichao
78,421,758
6,606,057
How to Automatically Dummy Code High Cardinality Variables in Python
<p>I am working my way through the data engineer salary data set on Kaggle. The salary_currency column has the following value counts.</p> <pre><code>salary_currency USD 13695 GBP 558 EUR 406 INR 51 CAD 49 ... </code></pre> <p>16494 values total</p> <p>Is there a way to dummy code only for values that are a...
<python><one-hot-encoding><recode>
2024-05-02 21:08:47
1
485
Englishman Bob
78,421,709
6,606,057
Recode a Variable if it Does Not Fall into a Set Python
<p>I have a data set that looks like this. I would like to recode the values if they do not fall into a set.</p> <p>If my set = (Apple, Orange) I would like all other values to be 'x'.</p> <p>I have this column.</p> <pre><code> a 0 Apple 1 Apple 2 Pear 3 Banana 4 Apple 5 Orange </code></pre> <p>I would like to m...
<python><pandas>
2024-05-02 20:55:30
1
485
Englishman Bob
78,421,693
8,742,641
Calling a Python script inside a virtual environment from PowerShell without changing working directory
<p>I am trying to set up a <code>(1)Powershell script</code> that will activate a Python virtual environment with a <code>(2)Python .exe</code> file to call a <code>(3)Python script</code> that requires an <code>(4)SQL query</code>. I want the paths to be relative.</p> <p><a href="https://i.sstatic.net/nSqhpNOP.png" re...
<python><powershell>
2024-05-02 20:51:22
1
351
Frederi ROSE
78,421,600
5,472,006
Python code execution too slow due to bottleneck - seeking performance optimization
<p>I'm currently facing a performance issue with my Python code, specifically with the execution speed. I've identified a bottleneck in my code, and I'm seeking advice on how to optimize it for better performance.</p> <p>Here's a simplified version of the code:</p> <pre><code>import numpy as np def merge_arrays(arr: l...
<python><arrays><performance><recursion><array-merge>
2024-05-02 20:24:51
1
317
Nisu
78,421,521
825,227
Why does regex get tripped up on this
<p>Have the below set up to parse text to individual transactions:</p> <pre><code>transactions = rx.findall(r&quot;(\([A-Z][\s\S]*?\$.*\$[,\d]+)&quot;, text) </code></pre> <p>For the below sample text, I'd expect to return 6 transactions (one for each ticker represented--denoted initially by a &quot;([A-Z])&quot; patte...
<python><regex>
2024-05-02 20:05:05
0
1,702
Chris
78,421,427
14,471,688
Most efficient way to perform XOR operations between two matrices by using less memory
<p>I want to perform the XOR operations between two 2D numpy.ndarray by saving the memory usage. For each row of <strong>u_values</strong>, I want to perform the XOR operation to every row of <strong>v_values</strong> and so on. For example, if <strong>u_values</strong> has dimension <strong>(8,10)</strong> and <strong...
<python><numpy><bit-manipulation><numpy-ndarray><numba>
2024-05-02 19:45:05
1
381
Erwin
78,421,355
15,452,168
Efficiently Finding Nearest Locations from Large Datasets in Python
<p>I am working on a project where I need to find the three nearest geographical locations (from a dataset of 1,000 entries) for each entry in another large dataset consisting of 500,000 addresses. Each dataset includes latitude and longitude coordinates. I've been using Python with geopy and pandas, but due to the siz...
<python><pandas><geospatial><geopandas><geopy>
2024-05-02 19:26:21
1
570
sdave
78,421,334
1,451,346
Python can't see a new module in a directory it already imported from
<p>In this test, I create a new directory (deleting it if it already exists), add it to <code>sys.path</code>, add two simple Python files, and try to import them. I'm using Python 3.11.6 on Ubuntu 23.10.</p> <pre><code>import sys from pathlib import Path from shutil import rmtree d = Path('/tmp/fleen') try: rmtre...
<python><python-import><race-condition>
2024-05-02 19:22:50
2
3,525
Kodiologist
78,421,280
2,893,712
tzwhere returns empty even with forceTZ enabled
<p>I am using tzwhere module to get the timezone based on coordinates. I recently found I can set <code>forceTZ=True</code> but when I do this, it still does not return a timezone.</p> <p>My code is:</p> <pre><code>from tzwhere import tzwhere tz = tzwhere.tzwhere(forceTZ=True) tz.tzNameAt(18.45903590,-67.16367790) </co...
<python><timezone>
2024-05-02 19:10:22
1
8,806
Bijan
78,421,247
179,014
Why is do Pythons sum() and Pandas sum() yield different results
<p>Why do Pandas <code>sum()</code> and Pythons <code>sum()</code> on a list of floating point numbers yield slightly different results generating a difference when rounding the result</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; from decimal import Decimal &gt;&gt;&gt; numbers = [0.495,1.495,2.495,3.49...
<python><pandas><sum><floating-point><precision>
2024-05-02 19:04:24
1
11,858
asmaier
78,421,183
791,793
Trouble with prefilters in MongoDB Atlas and Langchain: 'Path needs to be indexed as token' error
<p>How do I use prefilters with langchain and mongodb atlas?</p> <p>Here's my example models:</p> <pre><code>class Question(Document): content = StringField(required=True) class ResponseFragment(Document): question = ReferenceField(Question, required=True) text = StringField(required=True) </code></pre> <p...
<python><mongodb><langchain><mongodb-atlas>
2024-05-02 18:51:31
1
721
user791793
78,421,170
246,241
Pydantic: How do I represent a list of objects as dict (serialize list as dict)
<p>In Pydantic I want to represent a list of items as a dictionary. In that dictionary I want the key to be the <code>id</code> of the Item to be the key of the dictionary. I read the documentation on <a href="https://docs.pydantic.dev/latest/concepts/serialization/#custom-serializers" rel="nofollow noreferrer">Seriali...
<python><pydantic>
2024-05-02 18:48:20
2
11,661
tback
78,421,046
5,960,363
Change Poetry Python version
<h2>Context</h2> <ul> <li>I want Poetry to use Python 3.12.x</li> <li>Poetry is installed globally, and I've set Pyenv to default to 3.12 globally on my machine</li> <li>I'm using VSCode</li> <li>In the terminal in my project, I've done <code>poetry env use 3.12</code>, and <code>poetry install</code> which successfull...
<python><visual-studio-code><environment><python-poetry><pyenv>
2024-05-02 18:22:34
1
852
FlightPlan
78,421,032
955,091
How to properly clean up non-serializable states associated with a Ray object?
<p>Suppose I have a Ray actor that can create a Ray object that associates with some non-serializable states. In the following example, the non-serializable state is a temporary directory.</p> <pre class="lang-py prettyprint-override"><code>class MyObject: pass _non_serializable_states = {} @ray.remote class MyCr...
<python><garbage-collection><distributed-computing><weak-references><ray>
2024-05-02 18:19:26
0
3,773
Yang Bo
78,420,943
480,118
python concurrent.futures.ThreadPool blocking
<p>I have the code below. read_sql is method on my DBReader class and it's using pd.read_sql. Im parallelizing sql selects to the Postgres sql table.</p> <pre><code>import pandas as pd def read_sql(self, sql, params = None): t1 = timeit.default_timer() with warnings.catch_warnings(): warnings.simplefilter(&q...
<python><pandas><postgresql><python-multiprocessing><python-multithreading>
2024-05-02 17:58:59
0
6,184
mike01010
78,420,729
9,877,065
PyQt5 is it possible to have ScrollArea to scroll while dragging widget inside it?
<p>I am trying to answer to <a href="https://stackoverflow.com/questions/78370120/how-to-drag-qlineedit-form-one-cell-of-qgridlayout-to-other-cell-in-pyqt/78415934#78415934">How to Drag QLineEdit form one cell of QGridLayout to other cell in pyqt?</a></p> <blockquote> <p>I have gridlayout with four cells (0,0),(0,1),(1...
<python><scroll><pyqt><pyqt5><qscrollarea>
2024-05-02 17:12:57
1
3,346
pippo1980
78,420,717
92,516
Assign globally-unique user_id to each created User in multi-process setup
<p>I'm attempting to distribute a list of pre-defined request payloads across all the <code>Users</code> which are spawned in my run. Conceptually I want to split my list of N requests across U Users, such that each request is only issued once to the server.</p> <p>For a single process I can achieve this by simply assi...
<python><locust>
2024-05-02 17:09:30
1
9,708
DaveR
78,420,696
15,452,168
How to efficiently send 500,000 requests to Woosmap API for geocoding using multiprocessing in Python?
<p>I need to geocode a large dataset using the Woosmap API. I have a DataFrame containing around 500,000 addresses that I need to geocode as quickly as possible. Currently, I'm using the requests library to send requests one by one, but it's taking a significant amount of time. I've heard about multiprocessing in Pytho...
<python><multithreading><asynchronous><multiprocessing><concurrent.futures>
2024-05-02 17:06:20
2
570
sdave
78,420,685
3,623,537
Why ctypes.CDLL is assuming long result type even though it's actually is long long?
<p>Consider python code below - it seems that calling .dll's function is assuming long time for some reason (system is windows x64 if it's important). Why it's doing this? Is there way to disable it? Will it get in the way in other cases, e.g. if I'm going to pass <code>long long</code> arguments or initialize structs ...
<python><dll><ctypes>
2024-05-02 17:04:19
1
469
FamousSnake
78,420,645
4,820,782
Worker failed to index functions with Azure Functions & FastAPI local using AsgiMiddleware
<p>Running into an error that has started after a reboot. I am testing using Azure Functions in conjunction with FastAPI based on: <a href="https://dev.to/manukanne/azure-functions-and-fastapi-14b6" rel="nofollow noreferrer">https://dev.to/manukanne/azure-functions-and-fastapi-14b6</a></p> <p>Code was operating and te...
<python><azure-functions><fastapi>
2024-05-02 16:55:44
1
439
Jabberwockey
78,420,559
9,795,817
Performing recursive feature elimination with multiple performance metrics
<p>I am trying to make a classifier as parsimonious as possible. To do this, I am recursively dropping features using cross validation.</p> <p>In the context of my model, precision is the most important metric. However, I would also like to see how other metrics evolve as less features are fed to the model.</p> <p>In p...
<python><machine-learning><scikit-learn>
2024-05-02 16:37:03
1
6,421
Arturo Sbr
78,420,462
20,212,483
Why is array slower to index than list?
<p><a href="https://docs.python.org/2/faq/programming.html#how-do-you-make-an-array-in-python" rel="nofollow noreferrer">Programming FAQ for Python2</a> and <a href="https://docs.python.org//3/faq/programming.html#how-do-you-make-an-array-in-python" rel="nofollow noreferrer">Programming FAQ for Python3</a>:</p> <blockq...
<python>
2024-05-02 16:16:44
0
505
shynur
78,420,436
18,878,905
Dash Reloading main.py on button click undesirable
<p>My worry here is performance and unnecessary reloading of main script in Dash. Here is my script. Please keep in mind that my &quot;fake_utils&quot; modules reads files and slow to load. Hence we want to load it once and for all.</p> <p>main.py</p> <pre><code>import dash_bootstrap_components as dbc from fake_utils ...
<python><performance><plotly-dash><reload>
2024-05-02 16:09:24
0
389
david serero
78,420,125
15,341,457
Python Relative and Absolute Imports not Working
<p>I have a file structure like this:</p> <pre><code>└── scraper ├── __init__.py └── converter ├── items.py ├──__init__.py └── spiders ├──__init__.py └──spider.py </code></pre> <p>I am in spider.py and I'm trying to import items.py, I'm doing it like this:</p> <pr...
<python><import><importerror><relative-import>
2024-05-02 15:12:47
2
332
Rodolfo
78,420,017
1,207,193
Apply a decorator over a method already decorated with @property in Python
<p>Why the code bellow doesn't work when the @property decorator is applied on the method already decorated with <code>@property</code>? (I am using Python 3.10.)</p> <pre><code># Define a decorator def my_decorator(func): def wrapper(*args, **kwargs): print(&quot;Decorator applied&quot;) return fun...
<python><python-decorators>
2024-05-02 14:56:14
1
7,852
imbr
78,419,990
6,546,694
Read the function definition of pipe in polars python
<p>The documentation of <a href="https://docs.pola.rs/py-polars/html/reference/dataframe/api/polars.DataFrame.pipe.html#polars.DataFrame.pipe" rel="nofollow noreferrer">pipe</a> in polars says :</p> <pre><code>DataFrame.pipe( function: Callable[Concatenate[DataFrame, P], T], *args: P.args, **kwargs: P.kwargs, ) → T </...
<python><python-typing><python-polars>
2024-05-02 14:52:43
1
5,871
figs_and_nuts
78,419,981
490,324
Getting "ValueError Encountered text corresponding to disallowed special token '<|endoftext|>'" while running CrewAI
<p>I am running CrewAI with the Ollama Phi3 model, which runs well as long as I am not asked to generate sample Python code. Things get complicated when the Developer Agent passes a response to the HumanProxy Agent. Crew never finishes the work and continuously produces the following output:</p> <blockquote> <p>2024-05...
<python><ollama>
2024-05-02 14:51:36
1
2,808
m1k3y3
78,419,925
6,714,667
cannot import punkt nltk
<p>Due to security settings at work i cannot simply do nltk.download('punkt')</p> <p>i therefore printed out the <code>nltk.data.path</code> and found where it's looking, then added the zip file into the location e.g it was looking at C:\Users\name\Anaconda3\envs\ml\nltk_data so i added the punkt.zip file in nltk_data....
<python><nltk>
2024-05-02 14:40:27
3
999
Maths12
78,419,842
3,277,064
Accessing a C++ static member variable of a class in Cython
<p>Consider how to access, in Cython, the following C++ static inline class member variable:</p> <pre class="lang-cpp prettyprint-override"><code>namespace my::name::space { class MyClass { public: static inline int LIFE { 42 }; }; } </code></pre> <p>A plausible <code>.pyx</code> file might be:</p> <pre><code>cdef ...
<python><c++><cython>
2024-05-02 14:27:32
1
1,904
Vercingatorix
78,419,734
10,830,699
How set an autoreload on my `socketio.ASGIapp` plugged on my FastAPI app?
<p>I have an app combining FastAPI and SocketIO ASGI. On code change, the FastAPI reloads but not the SocketIO one. Is there a way to tell SocketIO to reload on change without using <code>watchdog</code> ? By setting a flag or something very short to write than a watchdog command ?</p> <pre class="lang-py prettyprint-o...
<python><fastapi><python-socketio>
2024-05-02 14:09:02
0
599
Bravo2bad
78,419,733
9,230,073
Firebase Admin SDK: Authentication failed using Compute Engine authentication due to unavailable metadata server
<p>When I try to send a push notification with firebase admin sdk from my own Django server. I get this error: <code>Authentication failed using Compute Engine authentication due to unavailable metadata server.</code></p> <ul> <li>I created a Google service account from my firebase console.</li> <li>Generated a new pr...
<python><amazon-web-services><firebase-cloud-messaging><firebase-admin>
2024-05-02 14:08:40
0
347
Fravel
78,419,689
14,471,688
Faster way to perform XOR operations between two 2D numpy.ndarray with memory efficiency
<p>I want to perform the XOR operations between two 2D numpy.ndarray by saving the memory usage. For each row of <strong>u</strong>, I want to perform the XOR operation to every row of <strong>v</strong> and so on. For example, if u has dimension <strong>(8,10)</strong> and v has dimension <strong>(6,10)</strong>, the ...
<python><numpy><bit-manipulation><numba><bitwise-xor>
2024-05-02 14:01:36
0
381
Erwin