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,320,052
1,770,604
Providing dynamically created pydantic model as type annotation to function without mypy errors
<p>I am using a pluggable architecture which registers pydantic models with a central registry on startup.</p> <p>These models are then added to an existing model as a <code>Union</code> field dynamically.</p> <p>This resulting class is then used by a framework we use (dagster) to provide yaml configuration in a UI.</p...
<python><mypy><dagster>
2024-04-13 08:52:24
0
691
Martin O Leary
78,320,047
3,383,640
Stalling of Multiprocessing in Python
<p>I experience a strange behavior of the multiprocessing module. Can anyone explain what is going on here?</p> <p>The following MWE stalls (runs forever without error):</p> <pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python3 import multiprocessing import numpy as np from skimage import io from skl...
<python><scikit-learn><multiprocessing><python-multiprocessing>
2024-04-13 08:50:05
1
5,078
Suuuehgi
78,319,882
11,770,390
How to resample a dataframe to stretch from start to enddate in intervals (containing 0 for not available values)
<p>I have the following setup:</p> <p>I have sparse information about queries hitting my endpoint at certain timepoints in a csv file. I parse this csv file with dates according to <code>date_format='ISO8601'</code> in the index column. Now what I want to do is this: I want to count the queries in certain intervals and...
<python><pandas><reindex><pandas-resample>
2024-04-13 07:44:26
1
5,344
glades
78,319,798
8,748,098
error: 'tf.TensorListSetItem' op is neither a custom op nor a flex op while trying to quantize a model
<p>I am trying to learn about quantization so was playing with a github repo trying to quantize it into int8 format. I have used the following code to quantize the model.</p> <pre><code>modelClass = DTLN_model() modelClass.build_DTLN_model(norm_stft=False) modelClass.model.load_weights(model_path) # tf.saved_model.sav...
<python><tensorflow><machine-learning><quantization><quantization-aware-training>
2024-04-13 07:02:24
0
327
Niaz Palak
78,319,719
2,962,794
How can I make datetime objects for the year 10,000 and beyond?
<p>In Python 3.10.12 (or 3.x), how do I make datetime objects for dates in the year 10,000 and beyond? I get a ValueError when I try:</p> <pre><code>ValueError: year 10000 is out of range </code></pre> <p>Is there some reason this error exists? I mean, does our actual calendar not support the year 10,000, or something?...
<python><python-3.x><datetime>
2024-04-13 06:24:24
1
4,809
Brōtsyorfuzthrāx
78,319,661
1,413,856
Python Module Help DocStrings - Exclucing extra documentation
<p>I have written a simple module (<code>testmodule</code>) which imports some other modules. When I import it and type:</p> <pre class="lang-py prettyprint-override"><code>help(testmodule) </code></pre> <p>I get all of the help from the imported modules as well.</p> <p>Is there a way of excluding the extra help?</p> <...
<python><module><docstring>
2024-04-13 05:54:00
0
16,921
Manngo
78,319,625
11,922,237
Snowflake `Table`s vs Snowflake `DataFrame`s in Snowpark
<p>Two things I've come across while trying to learn Snowflake Snowpark is that they mention both <code>Table</code>s and <code>DataFrame</code>s.</p> <p>The docs say that you can load an existing table from Snowflake database after creating a session:</p> <pre class="lang-py prettyprint-override"><code>connection_para...
<python><database><snowflake-cloud-data-platform>
2024-04-13 05:31:27
1
1,966
Bex T.
78,319,326
2,007,222
How numpy.linalg.norm works
<p>I am trying to understand how these numbers calculated:</p> <pre><code>&gt;&gt;&gt; np.linalg.norm([1,2,3,4,5],0) 5.0 &gt;&gt;&gt; np.linalg.norm([1,2,3,4,5],1) 15.0 &gt;&gt;&gt; np.linalg.norm([1,2,3,4,5],2) 7.416198487095663 &gt;&gt;&gt; np.linalg.norm([1,2,3,4,5],3) 6.082201995573399 &gt;&gt;&gt; np.linalg.norm([...
<python><numpy>
2024-04-13 01:40:26
1
1,949
Digerkam
78,319,072
842,476
Best way to go through two pandas dfs and using the data in an external function in python
<p>I have two pandas dfs one contains a list of workers and the other contains a list of tasks. I plan to assign the tasks to the workers. Each task requires a certain number of workers and the way I am doing it right now is by going through the tasks df and stop at each row and go through the workers df and keep assig...
<python><pandas><dataframe>
2024-04-12 23:02:57
1
302
Ayham
78,319,019
20,302,906
How to test external fetch API function with connectionerror exception Django
<p>My code snippet fetches data from an external API. It works fine and I tested the results when I don't have any issues with the connection. However, I'm interested on testing my <code>try</code> <code>except</code> block that handles any connection problem during the function execution. I'm using python 'requests' l...
<python><django><exception>
2024-04-12 22:41:41
0
367
wavesinaroom
78,318,955
4,307,142
Corrected Cramer's V results in division by zero when n = r
<p>I recently found <a href="https://stackoverflow.com/a/39266194">this answer</a> which provides the code of an unbiased version of Cramer's V for computing the correlation of two categorical variables:</p> <pre><code>import scipy.stats as ss def cramers_corrected_stat(confusion_matrix): &quot;&quot;&quot; calcul...
<python><pandas><correlation><categorical-data>
2024-04-12 22:20:57
1
1,167
Gabriel Rebello
78,318,744
984,621
How to properly set access to uploaded files to DigitalOcean Spaces cloud storage?
<p>I am uploading files through Python scripts to DigitalOcean Spaces (AWS S3-Compatible Object Storage).</p> <p>Uploading files is working well; the part I am not so sure about is how to properly access those files. I had to set <code>IMAGES_STORE_S3_ACL = 'public-read'</code></p> <p>so I am able to display the image ...
<python><amazon-web-services><amazon-s3><digital-ocean><digital-ocean-spaces>
2024-04-12 21:13:07
1
48,763
user984621
78,318,626
1,275,942
Python logging: check if a log will print before doing f-string?
<p>Suppose I have code I want to be able to run in production or verbose mode. In verbose, I want to print debug information that will slow the program down:</p> <pre class="lang-py prettyprint-override"><code>import logging import time import sys logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) root = loggi...
<python><lazy-evaluation><python-logging><f-string>
2024-04-12 20:41:02
0
899
Kaia
78,318,586
2,301,970
Propagating true entries along axis in an array
<p>I have to perform the operation below many times. Using numpy functions instead of loops I usually get a very good performance but I have not been able to replicate this for higher dimensional arrays. Any suggestion or alternative would be most welcome:</p> <p>I have a boolean array and I would like to propagate the...
<python><numpy><convolution><array-broadcasting>
2024-04-12 20:31:06
3
693
Delosari
78,318,544
8,849,755
plotly animation disable auto play
<p>Is it possible to disable the auto play when saving an animated plot created with plotly?</p> <pre class="lang-py prettyprint-override"><code>import plotly.express as px df = px.data.gapminder() px.scatter(df, x=&quot;gdpPercap&quot;, y=&quot;lifeExp&quot;, animation_frame=&quot;year&quot;, animation_group=&quot;cou...
<python><plotly>
2024-04-12 20:18:28
1
3,245
user171780
78,318,498
1,909,378
gdal: build from source with python bindings in docker container
<p>I’m struggling with building a gdal feature branch from source. My environment is docker with an ubuntu base image.</p> <p>It builds fine, but invoking <code>gdal2tiles.py</code> throws the notorious</p> <p><code>ModuleNotFoundError: No module named 'osgeo'</code></p> <p>These are my build steps in my docker contain...
<python><docker><ubuntu><cmake><gdal>
2024-04-12 20:01:09
1
5,347
creimers
78,318,497
7,941,944
Incorrect Placement visited node set in Graph traversal DFS
<p>I am having trouble understanding why placing <code>visited.append((i,j))</code> in the else case gives me the right output, while keeping it as shown below gives the incorrect output. I tried to debug with a simpler example [[0,1], [1,1]] But I am not able to figure out why keeping it outside the else gives wrong r...
<python><data-structures><depth-first-search>
2024-04-12 20:01:07
1
333
Vijeth Kashyap
78,318,447
2,054,629
Can I know synchronously if an AsyncIterator is at its end?
<p>I have an async iterator. <em>While</em> iterating over its element, I would like to know if I am reading the last element. Is this possible?</p> <pre class="lang-py prettyprint-override"><code>async def start_stream(): idx = 0 while idx &lt; 100: yield idx idx += 1 await asyncio.slee...
<python><iterator><python-asyncio>
2024-04-12 19:46:22
0
10,562
Guig
78,318,223
4,398,966
change KeyboardInterrupt to 'enter'
<p>I have the following code:</p> <pre><code>import time def run_indefinitely(): while True: # code to run indefinitely goes here print(&quot;Running indefinitely...&quot;) time.sleep(1) try: # Run the code indefinitely until Enter key is pressed run_indefinitely() ...
<python><keyboard-events>
2024-04-12 18:49:37
3
15,782
DCR
78,318,186
193,128
How can I make the background of this Python/Tk Treeview table all dark?
<p>I'm preparing to write a user interface for a REST interface and I've never used Python/Tk before. I've written a program which shows files in the current folder for now while I figure out the look of the UI. Unfortunately I've got stuck trying to make the whole window Dark. I have white patches showing around th...
<python><tkinter><tk-toolkit>
2024-04-12 18:42:45
0
32,596
Benj
78,318,135
610,569
How to save the LLM2Vec model as a HuggingFace PreTrainedModel object?
<p>Typically, we should be able to save a merged base + PEFT model, like this:</p> <pre class="lang-py prettyprint-override"><code>import torch from transformers import AutoTokenizer, AutoModel, AutoConfig from peft import PeftModel # Loading base MNTP model, along with custom code that enables bidirectional connecti...
<python><huggingface-transformers><large-language-model><mistral-7b>
2024-04-12 18:32:25
1
123,325
alvas
78,317,989
14,501,168
Is it possible to fine-tune a pretrained word embedding model like vec2word?
<p>I'm working on semantic matching in my search engine system. I saw that word embedding can be used for this task. However, my dataset is very limited and small, so I don't think that training a word embedding model such as word2vec from scratch will yield good results. As such, I decided to fine-tune a pre-trained m...
<python><nlp><artificial-intelligence><word2vec><word-embedding>
2024-04-12 17:57:56
2
323
th3plus
78,317,726
10,410,934
Issue with calling parent method of Python subclass?
<pre><code>import abc class Parent(abc.ABC): def is_valid(self, thing): return thing is not None class Child(Parent): def is_valid(self, thing): return super(Parent, self).is_valid(thing) and thing &gt; 5 a = Child() print(a.is_valid(6)) </code></pre> <p>this gives AttributeError: 'super' object h...
<python><inheritance>
2024-04-12 16:50:27
1
396
Stevie
78,317,566
3,981,447
How to insert a specific variable into the log formatter, avoiding the usual extra parameter?
<p>How to drag any parameter into logging.Formatter? Imagine that you have several threads that execute some code, and each of them writes logs. This includes calling the code of important third-party libraries, the files of which only contain import logging.. I'd like to have some way to say &quot;all log messages in ...
<python><logging><python-logging>
2024-04-12 16:18:43
0
370
Vlad Kisly
78,317,267
451,460
unknown file type '.pxd' when installing my package
<p>I'm trying to install a package that I'm maintaining (pygtftk). I'm using the latest version and would like to go on with the development but I'm not able to install it under Python 3.10.14 due to some error with a pxd file (I'm clearly not expert in cython but I will work on it...). When running:</p> <pre><code> g...
<python><cython><setup.py>
2024-04-12 15:25:03
1
804
dputhier
78,317,220
1,324,631
How to apply type annotations to variables in a tuple assignment statement?
<p>How should one annotate the types of variables assigned to in a tuple assignment?</p> <p>As a minimal example:</p> <pre><code>def foo() -&gt; Tuple[Any, Any]: return &quot;x&quot;, 2 a, b = foo() </code></pre> <p>In context, I'm able to provide tighter type bounds on <code>a</code> and <code>b</code> than are aut...
<python><python-3.x><python-typing>
2024-04-12 15:16:03
0
4,212
AJMansfield
78,316,928
3,585,575
gh has different output when captured with Python subprocess.run
<p>Within Python, I am trying to capture the full <code>stderr</code> output produced from the shell command:</p> <pre><code>$ gh repo fork --remote ! knoepfel/larvecutils already exists ✓ Using existing remote origin </code></pre> <p>The python code looks like:</p> <pre class="lang-py prettyprint-override"><code>impor...
<python><github-cli>
2024-04-12 14:28:17
2
1,710
Kyle Knoepfel
78,316,919
6,213,343
Polars: Replace parts of dataframe with other parts of dataframe
<p>I'm looking for an efficient way to copy / replace parts of a dataframe with other parts of the same dataframe in Polars.</p> <p>For instance, in the following minimal example dataframe</p> <pre class="lang-py prettyprint-override"><code>pl.DataFrame({ &quot;year&quot;: [2020,2021,2020,2021], &quot;district_id&q...
<python><dataframe><python-polars>
2024-04-12 14:27:17
4
626
Christoph Pahmeyer
78,316,856
3,611,164
Dynamically create and display ipywidgets, failing in databricks notebook
<p>Goal: An array of ipywidgets, that can be extended through a button-click on the UI.</p> <pre class="lang-py prettyprint-override"><code>import ipywidgets as widgets from IPython.display import display # Keeps track of default and dynamically added widgets widgets_list = [widgets.Text(value='Give me')] w_out_widge...
<python><jupyter-notebook><databricks><ipywidgets><databricks-notebook>
2024-04-12 14:14:21
1
366
Fabitosh
78,316,845
1,726,805
Counting number of unique values in groups
<p>I have data where for multiple years, observations <em>i</em> are categorized in <em>cat</em>. An observation <em>i</em> can be in multiple categories in any year, but is unique across years. I am trying to count unique values for <em>i</em> by <em>year</em>, by <em>cat</em>, and by <em>year</em> and <em>cat</em>.</...
<python><pandas><group-by>
2024-04-12 14:11:33
1
609
Matthijs
78,316,719
1,029,902
Algolia search function returns only first 20 results
<p>I have this Python function to return all verified venues using algolia</p> <pre><code>def get_all_venues(): try: page = 0 hits_per_page = 1000 # Increase this value while True: result = index.search(&quot;&quot;, { &quot;filters&quot;: &quot;is_verified=1&quo...
<python><search><filtering><algolia>
2024-04-12 13:52:00
0
557
Tendekai Muchenje
78,316,559
451,460
Get a "clang: error: no such file or directory" when building my Python package
<p>I'm trying to install a package that I'm maintaining (<a href="https://github.com/dputhier/pygtftk" rel="nofollow noreferrer">pygtftk</a>). I'm using the latest version and would like to go on with the development that I let few months ago (to prepare python 3.10 and 3.11 version). but I'm not able anymore to instal...
<python><gcc><compilation><package><clang>
2024-04-12 13:23:45
0
804
dputhier
78,316,555
4,971,866
FastAPI Depends(func) returns a dataclass but the typing is not right
<p>I created a dependency function to verify token in the header and return info from the token.</p> <pre class="lang-py prettyprint-override"><code>async def require_auth(res:Response, cred: HTTPAuthorizationCredentials = Depends(HTTPBearer(auto_error=True))): try: # 3rd-party service verify the token and ...
<python><fastapi><python-typing>
2024-04-12 13:23:07
1
2,687
CSSer
78,316,548
937,440
Problems debugging using the Visual Studio Code command line debugger
<p>I am fairly new to VS Code (IDE) and Python (I have plenty of experience with Visual Studio and C#). I have written the following Hello World type program (test.py) using VS Code:</p> <pre><code>import sys def main(): print(sys.argv) print(sys.argv[1]) print(sys.argv[2]) print(&quot;hello world&quo...
<python><python-3.x><visual-studio-code>
2024-04-12 13:22:14
1
15,967
w0051977
78,315,964
1,194,864
Loading pre-trained weights properly in Pytorch
<p>I would like to perform transfer learning by loading a pretrained vision transformer model, modify its last layer and training it with my own data.</p> <p>Hence, I am loading my dataset perform the typical transformation similar to the ImageNet, then, load the model, disable the grad from all its layer remove the la...
<python><pytorch><transformer-model><transfer-learning>
2024-04-12 11:27:08
1
5,452
Jose Ramon
78,315,840
13,849,446
Unable to find category and price for tickets in requests
<p>I have been lurking through the site: <a href="https://www.ticketcorner.ch" rel="nofollow noreferrer">https://www.ticketcorner.ch</a> for three days, but I am unable to find some ticket data in requests. The purpose is to make a script that takes event url and gives a list of available tickets. Now, I am getting som...
<python><web-scraping><python-requests>
2024-04-12 11:03:20
1
1,146
farhan jatt
78,315,717
5,868,293
Creating new column in pandas based on list of tuples
<p>I have the following :</p> <pre><code>import pandas as pd ls = [(1,2,10,20,5), (3,4,30,40,10), (5,6,50,60,20)] df_ = pd.DataFrame({'col1': [1.1, 3.5, 5.4, 4.1], 'col2': [11, 35, 44, 41]}) </code></pre> <p>I would like to create a new column in <code>df_</code> which will be created accordin...
<python><pandas>
2024-04-12 10:40:41
2
4,512
quant
78,315,681
268,581
bokeh vbar_stack: positive values on positive side, negative values on negative side
<h1>Example program</h1> <pre class="lang-py prettyprint-override"><code>import bokeh.colors import pandas as pd from bokeh.plotting import figure, show import bokeh.models import bokeh.palettes import bokeh.transform data = { 'date': ['2024-04-15', '2024-04-16', '2024-04-17' ], 'Bill': [1, 1, -1], 'Note'...
<python><bokeh>
2024-04-12 10:33:00
1
9,709
dharmatech
78,315,676
5,896,319
How to run a command at the same time with the running the application in Flask?
<p>I have a script as a flask command and I want to run it when the system starts until the system ends. It should be a thread basically. I already created the command and it is working fine. How can I run it at the same time with the system? flask_commands.py:</p> <pre><code>@click.command() def file_watcher() -&gt; N...
<python><python-3.x><flask><watchdog>
2024-04-12 10:31:49
1
680
edche
78,315,455
1,123,501
FastAPI error when using Annotated in Class dependencies
<p>FastAPI added support for Annotated (and started recommending it) in version 0.95.0.</p> <p>Additionally, FastAPI has a very powerful but intuitive Dependency Injection system (<a href="https://fastapi.tiangolo.com/tutorial/dependencies/" rel="nofollow noreferrer">documentation</a>). Moreover, FastAPI support <a hr...
<python><fastapi>
2024-04-12 09:50:25
1
20,150
Georgios
78,315,374
12,304,000
ValueError: You have to specify pixel_values
<p>Is it possible to generate an image using the CLIP model without giving a reference image? I tried to follow the documentation and came up with this:</p> <pre><code>import torch from transformers import CLIPProcessor, CLIPModel from PIL import Image # Load CLIP model and processor model = CLIPModel.from_pretrained(...
<python><pytorch><huggingface-transformers><generative-programming>
2024-04-12 09:36:02
1
3,522
x89
78,315,360
143,091
Docker API build does not reuse layers from cache
<p>I have a Dockerfile, and when I run <code>docker build</code> from the command line it reuses unchanged layers as expected. However, when I start the build using the Python API, it always rebuilds all steps. Any idea what the problem could be? My code looks like this:</p> <pre><code>import docker with contextlib.cl...
<python><docker><docker-api>
2024-04-12 09:32:44
1
10,310
jdm
78,315,239
906,598
Replace rows with nearest time using pyspark
<p>I have a dataframe in PySpark:</p> <pre><code>id time replace 3241 2024-01-31 false 4344 2019-09-01 true 5775 2022-02-01 false 5394 2018-06-16 true 7645 2023-03-11 false </code></pre> <p>I want to find rows where <code>replace == true</code> and replace the time column with the nearest time...
<python><apache-spark><pyspark><apache-spark-sql>
2024-04-12 09:11:04
1
1,119
upabove
78,315,143
6,667,035
Python UDP server start failed with error code WinError 10045 in Windows
<p>I am trying to build Python UDP server using the following code.</p> <pre class="lang-py prettyprint-override"><code> import socket if __name__ == '__main__': bind_ip = &quot;0.0.0.0&quot; bind_port = 30335 server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP, Server setting server.b...
<python><windows><network-programming><udp>
2024-04-12 08:50:16
1
559
JimmyHu
78,315,073
5,330,527
Conditional filling of autocomplete dropdown in Django backend with admin_auto_filters
<p>My <code>models.py</code>:</p> <pre><code>from smart_selects.db_fields import ChainedForeignKey class Funder(models.Model): name = models.CharField(max_length=200) scheme = models.ManyToManyField('Scheme', blank=True, related_name='funders') class Scheme(models.Model): name = models.CharField(max_lengt...
<python><django><django-filter>
2024-04-12 08:36:48
0
786
HBMCS
78,315,067
8,962,929
flask celery throw error "urls must start with a leading slash"
<p>I'm trying to implement the <strong>celery</strong> using <strong>flask</strong> and when i run this command <code>celery -A src.celery_worker.celery_app worker --loglevel=debug</code> to start the celery worker, it throwing error:</p> <blockquote> <p>Couldn't import 'src.celery_worker.celery_app': urls must start w...
<python><flask><celery><flask-restx>
2024-04-12 08:35:58
2
830
fudu
78,315,011
984,621
Running a script with only the libraries defined in virtual environment (venv)
<p>I worked for some time on a script and now I would like to create a virtualenv for it, create <code>requirements.txt</code>, so when I deploy the script to the server, all the necessary libraries would be installed from the <code>requirements.txt</code> file and I would not need to install one library after another....
<python><virtualenv>
2024-04-12 08:22:06
1
48,763
user984621
78,314,982
188,331
Assertion `srcIndex < srcSelectDimSize` failed on GPU for the `train()` function of HuggingFace `Seq2SeqTrainer`
<p>I use the HuggingFace Transformer framework's <code>Seq2SeqTrainer</code> to fine-tune a pre-trained model. The codes run perfectly on the CPU but are unable to run on GPU (NVIDIA GeForce 4090). The following error occurs:</p> <blockquote> <p>Assertion <code>srcIndex &lt; srcSelectDimSize</code> failed</p> </blockqu...
<python><huggingface-transformers>
2024-04-12 08:14:33
0
54,395
Raptor
78,314,847
8,781,465
How to resolve AttributeError and BadRequestError in Python using LangChain and AzureOpenAI?
<p>I'm working on integrating <code>LangChain</code> with <code>AzureOpenAI</code> in Python and encountering a couple of issues. I've recently updated from a deprecated method to a new class implementation, but now I'm stuck with some errors I don't fully understand. Here's the relevant part of my code:</p> <pre><code...
<python><langchain><py-langchain><azure-openai><gpt-4>
2024-04-12 07:41:01
0
1,815
DataJanitor
78,314,803
10,979,307
Manim set_opacity doesn't work in the expected manner
<p>When running the following code and generating the output animation, I expect the orange graph to slightly fade to opacity of 0.3. Unfortunately it does not work as expected. The area under the plot becomes colored which is not what I want. I have attached an image of the final output to the bottom of the question. ...
<python><manim>
2024-04-12 07:33:13
1
761
Amirreza A.
78,314,735
4,673,585
Csv files getting uploaded to local drive rather than storage account using python function app
<p>I have an azure function app in python with a blob trigger. It will trigger a function when a db file is uploaded in the following path in my storage account:</p> <pre><code>abc360/sqlite_db_file/{name}.db </code></pre> <p>The function will read data from db file and write data in csv and upload it back to a folder ...
<python><azure-functions><azure-blob-storage><azure-python-sdk>
2024-04-12 07:15:04
1
337
Rahul Sharma
78,314,579
1,020,139
Why can't I use AnyStr as a return type in Python 3.12 with Pyright?
<p>Consider the following code:</p> <pre><code>def get_secret(self, name: str, **kwargs: Any) -&gt; AnyStr: kwargs[&quot;SecretId&quot;] = name result = self.client.get_secret_value(**kwargs) return result[&quot;SecretBinary&quot;] if &quot;SecretBinary&quot; in result else result[&quot;SecretString&quot;] </c...
<python><mypy><python-typing><pyright>
2024-04-12 06:39:38
0
14,560
Shuzheng
78,314,515
10,200,497
What is the best way to slice a dataframe including the the first instance of a mask?
<p>This is my DataFrame:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame( { 'a': [np.nan, np.nan, np.nan, 20, 12, 42, 33, 32, 31], 'b': [np.nan, np.nan, np.nan, np.nan, 2333, np.nan, np.nan, 12323, np.nan] } ) </code></pre> <p>Mask is:</p> <pre><code>mask = ( (df.a.no...
<python><pandas><dataframe>
2024-04-12 06:24:34
2
2,679
AmirX
78,314,371
268,581
U.S. Treasury Securities : how to calculate net issuance
<h1>Treasury Security Auction Data</h1> <p>Each row represents a treasury auction:</p> <pre class="lang-none prettyprint-override"><code>&gt;&gt;&gt; df[(df['issue_date'] &gt;= '2024-03-01') &amp; (df['issue_date'] &lt;= '2024-03-20')][['issue_date', 'maturity_date', 'security_type', 'total_accepted']] issue_dat...
<python><pandas>
2024-04-12 05:40:58
1
9,709
dharmatech
78,314,350
10,429,573
idenitfy rowTag elements from a huge xml
<p>I have a huge XML file of 20k lines, before I process the data, I need to convert the data to a CSV file using Databricks (Python / Spark). In this huge XML file, how to list all the '<strong>rowTag</strong>' elements? Is there a way to find out??</p> <p>Mean while I tried below:</p> <p>For a simple xml, i can use b...
<python><xml><apache-spark><pyspark>
2024-04-12 05:33:55
0
613
RK.
78,314,340
4,732,111
Initialising a polars dataframe with 15 million records freezes the machine
<p>I'm using Psycopg3 connector to fetch records from AWS RDS Posgres Database and i'm initialising Polars dataframe using the code below:</p> <pre><code>rds_conn = psycopg.connect( host=config.RDS_HOST_NAME, dbname=config.RDS_DB_NAME, user=config.RDS_DB_USER, password=config.RDS_DB_PASS...
<python><pandas><dataframe><psycopg2><python-polars>
2024-04-12 05:31:54
1
363
Balaji Venkatachalam
78,314,205
1,214,800
Consuming an iterable/list/generator of dynamically loaded pytest fixtures
<p>I'm trying to create a dynamic fixture loader for pytest that does some work after the value is yielded to the test. In the beginning, I didn't need to do anything that complicated, so I just returned the fixture once it was ready:</p> <pre class="lang-py prettyprint-override"><code>from pathlib import Path import s...
<python><python-3.x><pytest><generator><pytest-fixtures>
2024-04-12 04:47:22
1
73,674
brandonscript
78,314,174
1,091,386
Assigning default values to class objects when member functions don't exist
<p>I realized I had oversimplified <a href="https://stackoverflow.com/q/78314000/1091386">my earlier question</a> while trying to make it easily reproducible.</p> <p>What I want is to run a member function on that input value and assign the result to an attribute, but if the input value didn't have that function, to gi...
<python><initialization><attributeerror>
2024-04-12 04:31:51
1
4,894
icedwater
78,314,079
12,714,507
Streaming audio over websockets and process it with ffmpeg, Invalid frame size error
<p>I am building an application in Python that processes audio data on a streaming connection with WebSockets. To work with it, I need to process it with ffmpeg on the server before passing it to some ML algorithms.</p> <p>I have the following ffmpeg code setup to process each byte sequence that comes over WebSockets:<...
<python><ffmpeg><subprocess><ffmpeg-python>
2024-04-12 03:51:26
1
349
Nimrod Sadeh
78,314,000
1,091,386
Specify default attribute value in Python class
<p>I would like to construct a class where an initial attribute depends on the result of an external function and gives a default value otherwise. E.g., <code>Puzzle</code> has a default score of the length of the string used to initialize it, but if no string is provided, its score is -1.</p> <pre class="lang-py prett...
<python><initialization>
2024-04-12 03:24:11
2
4,894
icedwater
78,313,962
1,355,120
Does shap's gradientexplainer take in a tensorflow function or a model?
<p>I'm using tensorflow 2 trying to call the gradientexplainer. I'm looking at the docs and it states the following:</p> <p><code>Note that for TensowFlow 2 you must pass a tensorflow function, not a tuple of input/output tensors</code></p> <p>However it seems that you need to pass in your model directly, you can't pas...
<python><tensorflow><shap><gradientexplainer>
2024-04-12 03:04:41
0
3,389
Kevin
78,313,930
419,115
Generic type-hinting for kwargs
<p>I'm trying to wrap the signal class of <a href="https://blinker.readthedocs.io/en/stable/" rel="nofollow noreferrer">blinker</a> with one that enforces typing so that the arguments to <code>send</code> and <code>connect</code> get type-checked for each specific signal.</p> <p>eg if I have a signal <code>user_update<...
<python><generics><mypy><python-typing>
2024-04-12 02:48:04
3
894
Michoel
78,313,709
8,325,579
Good "hash_func" for unhashable items in streamlit's st.cache_resource - mainly dataframes?
<p>Streamlit's st.cache_resource decorator is key to speeding up streamlit apps.</p> <p>In functions like:</p> <pre class="lang-py prettyprint-override"><code>@st.cache_resource def slow_function(inputA, input_b): ... return something </code></pre> <p>it can speed up the code through memoization.</p> <p>However,...
<python><hash><streamlit><python-polars><memoization>
2024-04-12 01:25:36
1
1,048
Myccha
78,313,700
825,227
Create a dataframe from numpy array and parameters
<p>Running Elastic Net simulations by varying a couple parameters and looking to save output coefficients to a dataframe for potential review later.</p> <p>Ultimately looking to save off a dataframe with two parameter identifier columns (ie, 'alpha', 'l1_ratio') and a number of other columns for the resulting coefficie...
<python><pandas>
2024-04-12 01:23:39
1
1,702
Chris
78,313,631
903,188
How do I run a shell script that requires the host Python environment from a script running in a virtual Python environment?
<p>I have a Python 3.9 script running in a virtual environment. The host environment is set up with Python 3.6 and many installed packages. I need to be able to run a shell script that only functions properly if it's run in the host environment.</p> <p>It's not possible for me to make the 3.9 virtual environment work f...
<python><python-venv>
2024-04-12 00:48:59
1
940
Craig
78,313,618
10,184,158
CSV file shows empty line or patial of content
<p>I wrote a python file to collect some server certificate info and save in a csv file. Everything works fine except the display when open the csv file.<a href="https://i.sstatic.net/zruNb.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/zruNb.jpg" alt="enter image description here" /></a></p> <p>As you ...
<python><excel><csv>
2024-04-12 00:42:16
1
463
chun xu
78,313,614
11,394,520
AlloyDB: Batch Import of CSV Files from GCS Bucket using python
<p>We need to design a process that efficiently imports large CSV files that are created by upstream processes on a regular base into AlloyDB. We'd like to use python for this task. What is the best practice in this case?</p> <p><strong>Some considerations:</strong></p> <ul> <li>SQL's INSERT statement is way less perfo...
<python><postgresql><google-cloud-platform><google-alloydb>
2024-04-12 00:38:47
1
560
Thomas W.
78,313,586
9,655,481
Python library: optionally support numpy types without depending on numpy
<h2>Context</h2> <p>We develop a Python library that contains a function expecting a numlike parameter. We specify this in our signature and make use of python type hints:</p> <pre class="lang-py prettyprint-override"><code>def cool(value: float | int | List[float | int]) </code></pre> <h2>🏳 Problem &amp; Goal</h2> <...
<python><numpy>
2024-04-12 00:26:27
1
1,157
Splines
78,313,334
195,540
Python opentelemetry wsgi usage with gunicorn / Application Insights
<p>I have the below setup working perfectly in development mode in my django application, so when I run <code>python manage.py runsslserver</code> the application reports perfectly to Application Insights.</p> <pre><code>from azure.monitor.opentelemetry import configure_azure_monitor from django.conf import settings a...
<python><django><azure-application-insights><wsgi><open-telemetry>
2024-04-11 22:34:19
1
1,787
scoopseven
78,313,298
13,395,230
Formula for the Nth bit_count (or population count) of size M
<p>I am interested in finding a simple formula for determining the nth time a particular bit_count occurs in the sequence of natural numbers. Specifically, what is the relationship between <code>K</code> and <code>N</code> in the table below. So, for example, what is the <code>N</code> of the <code>K=123456789123456789...
<python><algorithm><math><combinatorics><counting>
2024-04-11 22:23:44
4
3,328
Bobby Ocean
78,313,277
903,188
How can I run a Python program in the global Python environment from one in a virtual Python environment?
<p>I am writing and running Python programs on a machine that I don't have much control over. The global environment has Python 3.6 installed along with dozens of packages. There are many scripts available to me in that environment that I need to be able to run.</p> <p>I run most of the scripts I develop in a Python 3....
<python><python-venv>
2024-04-11 22:16:30
1
940
Craig
78,313,232
22,407,544
How to generate file in MEDIA_ROOT in Django?
<p>In my view I have a function that generates a file but does not return anything. I want the file to be generated in a specific folder in <code>MEDIA_ROOT</code> and saved in my models but I'm not sure how exactly to go about doing it. Here is the relevant section of my view:</p> <p><code>writer = get_writer(output_f...
<python><django>
2024-04-11 22:00:48
1
359
tthheemmaannii
78,313,091
4,549,682
Bug in polars 0.20 but not in 0.19 - any way to get around it?
<p>I found there seems to be a bug in the latest polars versions (0.20.19) that wasn't present in 0.19. With code like:</p> <pre><code>df.group_by(&quot;SomeDate&quot;) .agg( pl.col(col) .filter( pl.col(col).is_between( pl.quantile(col, 0.005), pl.quantile(col, 0.995) ...
<python><python-polars>
2024-04-11 21:26:56
0
16,136
wordsforthewise
78,313,084
23,260,297
Replace existing column with merged column and rename
<p>I am merging two dataframes. The first dataframe looks like this:</p> <pre><code>A B C D party1 asset1 product1 Buy party1 asset1 product2 Sell party2 asset2 product1 Buy party2 asset2 product2 Sell </code></pre> <p>The second dataframe looks like this:</p> <pre><code>A...
<python><pandas>
2024-04-11 21:22:27
1
2,185
iBeMeltin
78,312,935
13,354,617
Merging a python package into one script file
<p>I'm trying to merge all the files of a python package scripts+binaries into one script. I found this repo that does that: <a href="https://github.com/pagekite/PyBreeder" rel="nofollow noreferrer">https://github.com/pagekite/PyBreeder</a></p> <p>but it's an old repo and was written originally for python2, I found a P...
<python><python-import><python-packaging>
2024-04-11 20:40:31
0
369
Mhmd Admn
78,312,866
1,711,271
remove all whitespaces from the headers of a polars dataframe
<p>I'm reading some csv files where the column headers are pretty annoying: they contain whitespaces, tabs, etc.</p> <pre><code>A B C D E CD E 300 0 0 0 CD E 1071 0 0 0 K E 390 0 0 0 </code></pre> <p>I want to read the file, then remove all whitespaces and/or tabs from the colum...
<python><rename><python-polars>
2024-04-11 20:19:56
2
5,726
DeltaIV
78,312,841
1,609,514
Is there a simple analytical solution to this two-variable ODE? (using Sympy)
<p>I have a relatively simple but non-linear set of differential equations in two variables:</p> <ol> <li>dx[1]/dt = (u[1] - u[3]) / A</li> <li>dx[2]/dt = u[1] * u[2] - u[3] * x[2] / (x[1] * A)</li> </ol> <p>I thought this might have an analytical solution so I tried solving it in Sympy following <a href="https://s...
<python><sympy><ode><symbolic-math><integral>
2024-04-11 20:13:45
1
11,755
Bill
78,312,723
354,051
conversion from YUV to RGB color
<p>I'm trying to convert <a href="https://github.com/FFmpeg/FFmpeg/blob/7e59c4f90885a9ffffb0a3f1d385b4eae3530529/libavfilter/avf_showspectrum.c#L191" rel="nofollow noreferrer">FFMPEG's Intensity</a> color map from yuv format to rgb. It should give you colors as shown in the color bar in the image. You can generate a sp...
<python><ffmpeg><colors><yuv><color-conversion>
2024-04-11 19:41:10
1
947
Prashant
78,312,648
6,495,189
Python inheritance with @dataclasses.dataclass and annotations
<p>I am very confused by the following code:</p> <pre><code>import dataclasses @dataclasses.dataclass() class Base(): x: int = 100 @dataclasses.dataclass() class Derived(Base): x: int = 200 @dataclasses.dataclass() class DerivedRaw(Base): x = 300 base = Base() derived = Derived() derived_raw = DerivedRaw() ...
<python><inheritance><python-typing><python-dataclasses>
2024-04-11 19:24:40
1
443
Tony Bruguier
78,312,551
21,935,028
Decrypt a Java encrypted file in Python
<p>I use the following to encrypt a file in Java:</p> <pre><code> public static byte[] hexStringToByteArray(String s) { int len = s.length(); byte[] data = new byte[len / 2]; for (int i = 0; i &lt; len; i += 2) { data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) &lt;&lt; 4)...
<python><java><python-cryptography><javax.crypto>
2024-04-11 19:01:22
1
419
Pro West
78,312,534
12,556,481
Impossible to grab an href link using requests or Selenium
<p>My goal is to extract all the href links from this page and find the .pdf links. I tried using the requests library and Selenium, but neither of them could extract it.</p> <p>How can I solve this problem? Thank you.</p> <p>Ex: This contain a .pdf file link</p> <p><a href="https://i.sstatic.net/tmrDY.png" rel="nofoll...
<python><selenium-webdriver><python-requests><selenium-chromedriver>
2024-04-11 18:58:34
2
309
dfcsdf
78,312,517
18,100,562
How to implement EventDispatcher in Kivy?
<p>Good Day, Friends!</p> <p>The Kivy documentation is a bit unclear about the usage of EventDispatcher and I was not able to implement it.</p> <p>Simple description: When entering a screen, in on_enter() method, an object Task() is created and it will execute a threaded function. This function will emit (publish) a me...
<python><events><design-patterns><kivy>
2024-04-11 18:53:42
1
507
mister_kanister
78,312,502
15,524,510
pyGad RAM usage
<p>I am using pygad for a neural network and I am wondering why its using RAM after each generation? The issue is that I leave it to run and then as it starts to use more and more RAM, then RAM usage spikes suddenly and causes a craash.</p> <p>Here is my code to reproduce:</p> <pre><code>import pygad import pygad.keras...
<python><tensorflow><keras><pygad>
2024-04-11 18:49:46
1
363
helloimgeorgia
78,312,416
740,067
Why pyodbc connection.close hangs for 10 minute after timeout error on Azure-sql-database?
<p>I'm executing the following code. The code intentionally contains a query that takes longer than the <code>query timeout</code>.</p> <pre class="lang-py prettyprint-override"><code>import pyodbc TIMEOUT_SEC = 1 QUERY_DELAY_SEC = TIMEOUT_SEC + 1 DSN = &quot;..&quot; QUERY = f&quot;WAITFOR DELAY '00:00:{QUERY_DELAY_S...
<python><azure-sql-database><pyodbc><wait><freeze>
2024-04-11 18:32:07
1
5,669
xliiv
78,312,309
23,260,297
create new dataframe after performing calculations from groupby
<p>I have a dataframe that looks like this:</p> <pre><code>ID TradeDate party Deal Asset Start Expire Fixed Quantity MTM Float 1 04/11/2024 party1 Sell HO 01/01/2024 02/01/2024 10.00 1000 2500.00 10.00 1 04/11/2024 party1 Sell HO 01/01/2024 02/01/2024 10....
<python><pandas>
2024-04-11 18:10:30
1
2,185
iBeMeltin
78,312,262
14,179,793
AWS Lambda with Docker Image: Runtime.InvalidEntrypoint
<p>I have a Dockerfile that uses a base image from a third party that uses <code>FROM rockylinux:8</code> as its base image and the repo currently produces an image that is used in ECS. I am trying to make this container runnable on AWS lambda environment while also maintaining the ECS image functionality.</p> <p>Revie...
<python><amazon-web-services><docker><aws-lambda>
2024-04-11 18:01:44
0
898
Cogito Ergo Sum
78,312,157
984,003
Get image from data looking like \x00\x00\x87
<p>How do I create/get/open the image from a URL request when the response looks like this:</p> <pre class="lang-none prettyprint-override"><code>\x00\x00\x00 ftypavif\x00\x00\x00\ ... \x87&quot;y~\x13 $%\\\xad ... xb5\xa07tR\x80 </code></pre> <p>Much longer, of course.</p> <p>An example of such a URL is <a href="https...
<python><python-2.7><python-imaging-library>
2024-04-11 17:39:05
2
29,851
user984003
78,312,145
1,046,013
Loop in a Django template simple_tag returning a dictionary
<p>When using a simple template tag that returns a dictionary:</p> <pre><code>@register.simple_tag def get_types(): return { &quot;item1&quot;: &quot;Foo&quot;, &quot;item2&quot;: &quot;Bar&quot;, } </code></pre> <p>This doesn't print any column:</p> <pre><code>{% for type in get_types.values %}...
<python><django><django-templates><django-template-filters>
2024-04-11 17:37:26
1
3,866
NaturalBornCamper
78,312,080
158,466
SQL Server Table-Valued Parameter and Python
<p>I am writing a simple ETL. The source is a spreadsheet. The destination is a SQL Server table. The data are integers and strings. I would like to pass all of the data at once to SQL Server through a stored procedure rather than a row at a time. I learned about table-valued parameters, and created a type and a stored...
<python><sql-server><stored-procedures><table-valued-parameters>
2024-04-11 17:25:59
0
1,791
Daniel 'Dang' Griffith
78,312,055
5,790,653
How to write to different files based on value of list of dicts and concat the for loop and three list of dicts
<p>First of all, I'm sorry if the question is too long. I tried to include the least data, but that was I could add.</p> <p>These are the lists I have:</p> <pre class="lang-py prettyprint-override"><code>products_income = [ {'client_group': 'A', 'count': 2, 'product': 'A', 'monthly_income': 370}, {'client_group...
<python>
2024-04-11 17:19:58
4
4,175
Saeed
78,311,944
4,342,353
How to manage that escapes for the double quotes `'\"'` inside the 'user content' for training datasets will not be removed?
<h2>1. Objective</h2> <p>The objective is to ensure the training data keeps the needed format for a model training.</p> <p>Using the <a href="https://huggingface.co/docs/trl/sft_trainer" rel="nofollow noreferrer"><code>SFTTrainer</code></a> model training. The <a href="https://huggingface.co/docs/trl/sft_trainer" rel="...
<python><huggingface-datasets>
2024-04-11 16:57:15
1
471
Thomas Suedbroecker
78,311,930
3,621,575
How can I create a list based on values from all columns?
<p>I would like to create lists, such as in <code>df2</code>, from data such as in <code>df1</code>. Most of the help I read online is about the opposite, how to dissect lists. In the end, I would like this list to be accessible as a new column in the original <code>df1</code>.</p> <pre class="lang-py prettyprint-ove...
<python><pandas>
2024-04-11 16:54:25
2
581
windyvation
78,311,910
7,800,760
Unable to locally save some models locally with SentenceTransformers
<p>Tried many times to have SentenceTransformers and having stripped down my code to the following:</p> <pre><code>from sentence_transformers import SentenceTransformer modelPath = &quot;/Users/bob/.cache&quot; model = SentenceTransformer(&quot;Salesforce/SFR-Embedding-Mistral&quot;) model.save(modelPath) </code></pre>...
<python><nlp><huggingface-transformers><large-language-model><sentence-transformers>
2024-04-11 16:50:18
0
1,231
Robert Alexander
78,311,650
2,675,981
Jira Python get description from SUB-Task
<p>I am trying to get the description from a subtask in Jira. I am able to get all the information from the main task: summary, status, description, subtasks, etc... but when I pull data for a specific subtask, I am missing the description field.</p> <pre><code>ticket_data = jira.issue(&quot;PROJ-12345&quot;) for subta...
<python><jira>
2024-04-11 15:58:17
3
885
Apolymoxic
78,311,523
2,153,235
Invoke nonexistent __new__ method for abstract class: What happens?
<p>I was trying to decipher the following code, executed in a Conda environment for Python 3.9:</p> <pre><code>from datetime import datetime, timezone # &lt;...snip...&gt; current_file_start_time = datetime.now(timezone.utc) </code></pre> <p><a href="https://github.com/python/cpython/blob/3.9/Lib/datetime.py" rel="nofo...
<python>
2024-04-11 15:36:16
1
1,265
user2153235
78,311,513
2,715,191
Train neural network for Absolute function with minimum Layers
<p>I'm trying to train neural network to learn y = |x| function. As we know the absolute function has 2 different lines connecting with each other at point zero. So I'm trying to have following Sequential model:</p> <p>Hidden Layer: 2 Dense Layer (activation relu) Output Layer: 1 Dense Layer</p> <p>after training the m...
<python><tensorflow><machine-learning><keras><deep-learning>
2024-04-11 15:34:01
2
1,741
onik
78,311,464
5,330,527
Use autocomplete drop-down filters in Django Admin back-end for normal fields (not ManyToMany or ForeignKey)
<p>Is it possible to use an autocomplete filter <code>class</code> to be used in the <code>list_filter</code> for normal fields (i.e. not foreign keys or other relations)?</p> <p>For example, for this model:</p> <pre><code>class Project(models.Model): project_number = models.DecimalField(max_digits=15, decimal_pla...
<python><django><django-admin-filters>
2024-04-11 15:25:08
0
786
HBMCS
78,311,389
610,569
Why would `eval('dict('+s+')')` work but not `literal_eval('dict('+s+')')`?
<p>I could do this with <code>eval()</code>:</p> <pre><code>&gt;&gt;&gt; s = 'hello=True,world=&quot;foobar&quot;' &gt;&gt;&gt; eval('dict('+s+')') {'hello': True, 'world': 'foobar'} </code></pre> <p>but with <code>literal_eval()</code>:</p> <pre><code>&gt;&gt;&gt; from ast import literal_eval &gt;&gt;&gt; literal_eval...
<python><variables><eval><abstract-syntax-tree>
2024-04-11 15:13:48
1
123,325
alvas
78,311,338
2,263,683
GCP Spanner can't set DatabaseDialect while creating a database
<p>I have Python method to create a database in GCP's Spanner which in I want to set the database dialect to PostgreSql:</p> <pre><code>from google.cloud import spanner from google.cloud.spanner_admin_database_v1.types import spanner_database_admin, DatabaseDialect def create_database(instance_id, database_id, extra_s...
<python><google-cloud-platform><google-cloud-spanner>
2024-04-11 15:06:00
1
15,775
Ghasem
78,311,325
9,173,710
Detecting center and radius of craters in microscopy images
<p>I want to find the center and the radius of crater-like features in microscopy images using Python.</p> <p>I have images like this, they are numpy arrays representing the height map of a surface.<br /> <a href="https://i.sstatic.net/deGSv.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/deGSv.png" alt=...
<python><image-processing><feature-detection>
2024-04-11 15:03:30
2
1,215
Raphael