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,692,222
2,404,988
Is it possible to change the return value of a function with pdb?
<p>Let's say I have the following code :</p> <pre class="lang-py prettyprint-override"><code>def returns_false(): breakpoint() return False assert(returns_false()) print(&quot;Hello world&quot;) </code></pre> <p>Is there a sequence of pdb commands that will print &quot;Hello world&quot; without triggering an Asser...
<python><pdb>
2024-07-01 12:25:55
5
8,056
C4stor
78,692,165
5,295,755
Send list of lists of floats in request body
<p>I have defined the following endpoint using FastAPI:</p> <pre><code>@app.post( &quot;/my_endpoint&quot;, ) async def my_endpoint( my_matrix: list[list[list[float]]], ): print(my_matrix) </code></pre> <p>However, I cannot manage to send a request using either the Swagger UI nor a Python requests request:<...
<python><python-requests><swagger><fastapi>
2024-07-01 12:13:53
1
849
Aloïs de La Comble
78,692,083
521,070
How to run an executable Python script packaged in a wheel?
<p>Suppose I've got a &quot;wheel&quot; file that contains executable python script <code>myscript.py</code> and a few python modules it imports.</p> <p>Now I want to run <code>myscript.py</code> on a host with python virtual environment &quot;xyz&quot;.<br /> So I install the &quot;wheel&quot; file in this virtual env...
<python><execution><python-wheel>
2024-07-01 11:55:53
0
42,246
Michael
78,691,957
487,993
Parse temperature string in pint
<p>I was trying to parse a string with a temperature and pint fails due to the non-multiplicative nature of the temperature. However, it seems the internal conversion should handle this:</p> <pre class="lang-py prettyprint-override"><code>from pint import Quantity Quantity(&quot;6degC&quot;) </code></pre> <p>Produces</...
<python><pint>
2024-07-01 11:28:21
1
801
JuanPi
78,691,826
1,789,718
chaquopy and android: interactive dialog
<p>I have been trying to implement this functionality for a while, but all my approaches failed.</p> <p>I would like to have some python code opening a dialog in the android app and wait for the user to click on the ok button (this is the first step I want to complete before I can create more complex YES/NO dialogs).</...
<python><java><chaquopy>
2024-07-01 10:58:53
1
1,360
Luca
78,691,625
14,084,653
From Excel to JSON convert an empty string to null using Python
<p>I'm reading an Excel sheet using the Pandas read_excel which gives me a dataframe, then I'm using df.to_json(...) to convert the dataframe into JSON string. However when there are no values in the Excel cell its coming as empty string &quot;&quot; in JSON. How can I ensure that JSON converts empty cells to null valu...
<python><pandas>
2024-07-01 10:18:27
2
779
samsal77
78,691,616
2,163,392
Cannot extract the penultimate layer output of a vision transformer with a Pytorch
<p>I have the following model that I tuned with my own dataset trained with DataParallel:</p> <pre><code>model = timm.create_model('vit_base_patch16_224', pretrained=False) model.head = nn.Sequential(nn.Linear(768, 512),nn.ReLU(),nn.BatchNorm1d(512),nn.Dropout(p=0.2),nn.Linear(512, 141)) checkpoint = torch.load('vit_b_...
<python><machine-learning><pytorch><vision-transformer>
2024-07-01 10:16:39
1
2,799
mad
78,691,574
18,769,241
Roboflow Vs. Darknet for generating weight file and creating the model
<p>I have a YoloV8 data file format that is an annotation of data (images) done manually. What is the most effective and straightforward way of generating a model and therefore yielding the weights file? is it using <code>darknet</code> through the command:</p> <pre><code>darknet.exe detector train data/obj.data yolo-o...
<python><machine-learning><yolo><yolov8><darknet>
2024-07-01 10:07:36
1
571
Sam
78,691,539
1,617,563
Prevent pdoc from leaking environment variables of pydantic-settings
<p>I use <code>pydantic-settings</code> to collect configuration parameters from a variety of sources (config.yaml, .env, environment variables, ...). The settings object is stored as a module variable in a similar fashion to how it is shown for FastAPI <a href="https://fastapi.tiangolo.com/advanced/settings/#create-th...
<python><pydantic><pdoc>
2024-07-01 10:00:00
1
2,313
aleneum
78,691,107
5,266,998
Regex to substitute the next two words after a matching point
<p>I'm writing a Regex to substitute the maximum of the next two words after the matching point.</p> <p>Expected prefixes: dr, doctor, pr, professor</p> <p><strong>Sample text:</strong></p> <blockquote> <p>Examination carried out in agreement with and in the presence of Dr John Doe (rhythmologist).</p> </blockquote> <p...
<python><python-3.x><regex>
2024-07-01 08:16:08
2
2,607
Januka samaranyake
78,691,025
6,618,289
Parsing .targets file with ElementTree does not find specified tag
<p>I am trying to use ElementTree to parse information out of a .targets file from a NuGet package. What I am trying to find is the tag <code>&lt;AdditionalIncludeDirectories&gt;</code>. I am using the following python code to try to get it:</p> <pre><code>import xml.etree.ElementTree as ET tree = ET.parse(targets_fi...
<python><xml><msbuild><elementtree>
2024-07-01 07:54:12
1
925
meetaig
78,690,334
16,405,935
How can I load copied Libraries to Anaconda packages
<p>Because the company does not allow Internet connection from the internal computer, so I installed the libraries from my personal laptop and copied them to the company computer, but I did not see it appear on Anaconda's Package list. In my case it is dash module.</p> <p><a href="https://i.sstatic.net/Hii6nUOy.png" re...
<python><anaconda><libraries>
2024-07-01 03:16:47
1
1,793
hoa tran
78,690,229
19,366,064
How to mock sqlalchemy's async session?
<p>Code snippet</p> <pre><code>from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine engine = create_async_engine(url=&quot;&quot;) session_maker = async_sessionmaker(engine) </code></pre> <p>How can I mock the session maker so that the following executes without any error:</p> <pre><code>async w...
<python><testing><sqlalchemy><pytest><python-unittest>
2024-07-01 02:02:45
2
544
Michael Xia
78,690,213
1,033,217
How to Enumerate Threads using CreateToolhelp32Snapshot and Python ctypes?
<p>This seems like it should print the thread ID of the first thread in the snapshot, but it always prints <code>0</code>. What is wrong with it?</p> <p>The following assumes that process ID <code>1234</code> is a real, running process.</p> <pre class="lang-py prettyprint-override"><code>import ctypes from ctypes impor...
<python><python-3.x><windows><ctypes><kernel32>
2024-07-01 01:46:18
1
795
Utkonos
78,690,204
6,407,935
How to Fix "TypeError: getattr(): attribute name must be string" when multiple optimizers are GridSearched for GaussianProcessRegressor?
<p>Here is my script to predict targets on the final date of a timeseries dataset. I am trying to incorporate a <code>GaussianProcessRegressor</code> model to find the best hyperparameters using <code>GridSearchCV</code>: (Note that some of the code including most of the constants used are not explicitly shown in here ...
<python><optimization><scikit-learn><kernel-density><gaussian-process>
2024-07-01 01:40:33
1
525
Rebel
78,690,101
3,163,618
Do PyPy int optimizations apply to classes subclassed from int?
<p>From what I recall, PyPy has special optimizations on built-in types like ints and lists, which is great because they are very common, and it would be wasteful to treat an int like any other object.</p> <p>If I subclass <code>int</code> specifically, for example</p> <pre><code>class bitset(int): def in_bit(self,...
<python><optimization><subclass><pypy>
2024-07-01 00:06:06
1
11,524
qwr
78,689,986
3,486,684
Pivoting and then unpivoting while maintaining the original data types in the dataframe, without any reparsing operations
<p>Consider the following example:</p> <pre class="lang-py prettyprint-override"><code>from enum import Enum import polars as pl from typing import NamedTuple Months = Enum( &quot;MONTHS&quot;, [ &quot;Jan&quot;, &quot;Feb&quot;, &quot;Mar&quot;, &quot;Apr&quot;, &quot;M...
<python><python-polars>
2024-06-30 22:48:59
0
4,654
bzm3r
78,689,924
5,570,089
Efficient Merge sort implementation in python
<pre><code>def merge(arr, l, m, r): merged_arr = [] i, j = 0, 0 while (i &lt; len(arr[l:m])) and (j &lt; len(arr[m:r+1])): if arr[l+i] &lt; arr[m+j]: merged_arr.append(arr[l+i]) i += 1 elif arr[l+i] &gt;= arr[m+j]: merged_arr.append(arr[m+j]) j...
<python><algorithm><sorting><data-structures>
2024-06-30 22:17:13
1
636
Gerry
78,689,912
3,486,684
Polars: "explode" an enum-valued series into two columns of enum index and enum value
<pre class="lang-py prettyprint-override"><code>import polars as pl dates = [&quot;2024 Jan&quot;, &quot;2024 Feb&quot;] DateEnum = pl.Enum(dates) </code></pre> <pre class="lang-py prettyprint-override"><code>date_table = pl.DataFrame( {&quot;date&quot;: pl.Series(raw_dates, dtype=DateEnum)} ) date_table.explode(&...
<python><enums><python-polars>
2024-06-30 22:09:56
1
4,654
bzm3r
78,689,910
13,395,230
Why is Numpy converting an "object"-"int" type to an "object"-"float" type?
<p>This could be a bug, or could be something I don't understand about when numpy decides to convert the types of the objects in an &quot;object&quot; array.</p> <pre><code>X = np.array([5888275684537373439, 1945629710750298993],dtype=object) + [1158941147679947299,0] Y = np.array([5888275684537373439, 1945629710750298...
<python><arrays><numpy>
2024-06-30 22:07:22
2
3,328
Bobby Ocean
78,689,873
6,286,900
How to fine-tune merlinite 7B model in Python
<p>I am new to LLM programming in Python and I am trying to fine-tune the <a href="https://huggingface.co/instructlab/merlinite-7b-lab" rel="nofollow noreferrer">instructlab/merlinite-7b-lab</a> model on my Mac M1. My goal is to teach this model to a new music composer <strong>Xenobi Amilen</strong> I have invented.</p...
<python><pytorch><huggingface-transformers><large-language-model><huggingface-tokenizers>
2024-06-30 21:37:14
0
1,179
Salvatore D'angelo
78,689,869
2,687,250
Ignore missing columns in pandas read_excel usecols
<p>Is there a way to get pandas to ignore missing columns in usecols when reading excel?</p> <p><a href="https://stackoverflow.com/questions/63002350/ignore-missing-columns-in-usecol-parameter">I know there is a similar solution for read_csv here</a></p> <p>But can’t find a solution for Excel.</p> <p>For example:</p> <...
<python><excel><pandas>
2024-06-30 21:35:20
2
538
Jack
78,689,833
9,547,007
TextTestRunner doesn't recognize modules when executing tests in a different project
<p>i am currently working on a project, where i need to run tests inside a different file structure like this:</p> <pre><code>/my_project ├── __init__.py ├── ...my python code /given_proj ├── __init__.py ├── /package │ ├── __init__.py │ └── main.py └── /tests └── test_main.py </code></pre> <h3>Current approach</h3> <...
<python><python-import><python-unittest>
2024-06-30 21:20:07
1
352
jonas
78,689,782
2,837,253
Can't delete attribute added by metaclass
<p>I've been playing around with Python metaclasses, and I have encountered a rather strange instance where I cannot delete an attribute added to a class object by a metaclass. Consider the following two classes:</p> <pre class="lang-py prettyprint-override"><code>class meta(type): def __new__(mcls, name, base...
<python><metaclass>
2024-06-30 20:57:48
1
4,778
MrAzzaman
78,689,770
1,285,061
Django django.contrib.messages add new constant messages.NOTICE
<p>How can I create a new constant to Django messages?</p> <p>I want to add a new constant <code>messages.NOTICE</code> in addition to the existing six constants. That I can use to display notices using Bootstrap CSS.</p> <pre><code># settings.py from django.contrib.messages import constants as messages MESSAGE_TAGS =...
<python><python-3.x><django><bootstrap-5><django-messages>
2024-06-30 20:52:56
1
3,201
Majoris
78,689,527
4,322
How to get Rich to print out final table without cutting off the bottom?
<p>I am using the &quot;Rich&quot; printing tool in Python. It's working great - but I have a problem. When I run it with more content than fits on the terminal window, it cuts everything off at the bottom (as expected). But when it finishes, I want to allow the entire table to print out. Here's a repro:</p> <pre class...
<python><rich>
2024-06-30 18:58:25
1
7,148
aronchick
78,689,486
25,874,132
how to calculate this integral using scipy/numpy?
<p>i have the folowing question <a href="https://i.sstatic.net/51XgyKMH.png" rel="nofollow noreferrer">enter image description here</a> it's written badly, but for those values of alpha and beta (0.32, 12) i need to find the minimal k at which the integral from -inf to inf of that expression is less than pi.</p> <p>but...
<python><numpy><scipy>
2024-06-30 18:39:02
2
314
Nate3384
78,689,397
893,254
How to configure VS Code pytest when Python code is not in top level directory?
<p>I started a project with what I would describe as a &quot;standard&quot; Python project structure, whereby my code is organized into a set of <em>packages</em> which all live in the top level directory. In addition to this, there is a <code>tests</code> directory which contains <code>.py</code> files with functions ...
<python><visual-studio-code><pytest>
2024-06-30 18:02:31
2
18,579
user2138149
78,689,389
6,843,153
Attempt to debug streamlit on VSC raises error
<p>I have the following <code>launch.json</code>:</p> <pre><code>{ // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 &quot;version&quot;: &quot;0.2.0&quot;, &quo...
<python><visual-studio-code><debugging><streamlit>
2024-06-30 17:58:34
1
5,505
HuLu ViCa
78,689,352
6,394,617
Why doesn't `randrange(start=100)` raise an error?
<p>In the <a href="https://docs.python.org/3/library/random.html#functions-for-integers" rel="nofollow noreferrer">docs</a> for <code>randrange()</code>, it states:</p> <blockquote> <p>Keyword arguments should not be used because they can be interpreted in unexpected ways. For example <code>randrange(start=100)</code> ...
<python><parameter-passing>
2024-06-30 17:44:16
1
913
Joe
78,689,274
1,795,245
Yfinance history returns different result each time
<p>I use Yfinance to download historical prices and have found that the function returns different result each time. Is it an error or am I doing something wrong?</p> <pre><code>import yfinance as yf msft = yf.Ticker('AAK.ST') data_1 = msft.history(period=&quot;max&quot;) data_2 = msft.history(period=&quot;max&quot;) <...
<python><yfinance>
2024-06-30 17:09:17
1
649
Jonas
78,689,258
1,521,512
Time Limit Exceed on a UVA problem using Python, is this code that inefficient?
<p>Just for fun, I'm trying to solve <a href="https://onlinejudge.org/index.php?option=com_onlinejudge&amp;Itemid=8&amp;category=24&amp;page=show_problem&amp;problem=2019" rel="nofollow noreferrer">UVA 11078 (Open Credit System)</a>. (Solutions can be checked on <a href="https://vjudge.net/problem/UVA-11078" rel="nofol...
<python><performance>
2024-06-30 17:03:15
1
427
dietervdf
78,689,216
1,089,239
BedrockEmbeddings - botocore.errorfactory.ModelTimeoutException
<p>I am trying to get vector embeddings on scale for documents.</p> <ul> <li>Importing, <code>from langchain_community.embeddings import BedrockEmbeddings</code> package.</li> <li>Using <code>embeddings = BedrockEmbeddings( credentials_profile_name=&quot;default&quot;, region_name=&quot;us-east-1&quot;, model_id=&quot;...
<python><langchain><retrieval-augmented-generation><amazon-bedrock>
2024-06-30 16:45:59
2
7,208
Benny
78,689,213
6,758,654
Polars cumulative count over sequential dates
<p>Here's some sample data</p> <pre class="lang-py prettyprint-override"><code>import polars as pl df = pl.DataFrame( { &quot;date&quot;: [ &quot;2024-08-01&quot;, &quot;2024-08-02&quot;, &quot;2024-08-03&quot;, &quot;2024-08-04&quot;, &quot;2024-...
<python><python-polars><cumulative-sum>
2024-06-30 16:45:38
1
3,643
Will Gordon
78,689,124
322,909
What is the correct maxmem parameter value in Python's hashlib.scrypt method?
<p>I am trying to use Python's <a href="https://docs.python.org/3/library/hashlib.html#hashlib.scrypt" rel="nofollow noreferrer"><code>hashlib.scrypt</code></a> to hash passwords. According to <a href="https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html" rel="nofollow noreferrer">OWASP</a> ...
<python><encryption><python-3.6><hashlib><scrypt>
2024-06-30 16:08:45
0
13,809
John
78,689,123
9,640,238
Value of nested dict remains unchanged in loop
<p>Consider the following:</p> <pre class="lang-py prettyprint-override"><code>template = {&quot;first&quot;: &quot;John&quot;, &quot;last&quot;: &quot;Doe&quot;, &quot;numbers&quot;: {&quot;age&quot;: 30}} people = [] for age in range(30, 41): new_dict = template.copy() new_dict[&quot;numbers&quot;][&quot;age&...
<python><dictionary><nested>
2024-06-30 16:08:45
0
2,690
mrgou
78,688,830
2,521,423
How to avoid import issues when Sphinx docs are generated from a different directory to parent app
<p>I want to autogenerate documentation for a python project. I managed to get a barebones pipeline working with sphinx, but the output is not very pretty and I would appreciate some guidance on how to make the output cleaner and the inputs more maintainable.</p> <p>My project is organized like so:</p> <pre><code>docs ...
<python><mocking><python-sphinx>
2024-06-30 14:11:20
0
1,488
KBriggs
78,688,698
631,619
Skipping playwright test gives pytest is not defined
<p>I can run my python playwright tests ok</p> <p>However I want to skip one</p> <p>I added <code>@pytest.mark.skip</code> but I get the error <code>'pytest' is not defined</code></p> <pre><code>import re from playwright.sync_api import Page, expect def test_has_title(page: Page): page.goto(&quot;https://b...
<python><pytest><playwright>
2024-06-30 13:19:16
1
97,135
Michael Durrant
78,688,583
898,042
venv is activated but pip installing still goes in default and python does not see the lib in sourcecode
<p>in vscode in terminal shell typing &quot;which python&quot; shows default path:</p> <pre><code>C:\Users\erjan\AppData\Local\Programs\Python\Python311\python.exe (my_venv) </code></pre> <p>but (my_venv) means my venv is active, I did <code>pip install transformers</code>, but the code below still shows error - can't ...
<python><pip><virtualenv><python-venv>
2024-06-30 12:30:08
0
24,573
ERJAN
78,688,455
498,584
Can one inherit a ModelSerializer and Merge Models
<p>I am trying to inherit djoser's UserCreatePasswordRetypeSerializer</p> <p>Djoser Modelserializer's model is User. The child Serializer that I am implementing represents a different model, Customer.</p> <p>So could one do:</p> <pre><code>class CustomerSerializer(UserCreatePasswordRetypeSerializer): class Meta: ...
<python><django><django-rest-framework><django-serializer><djoser>
2024-06-30 11:37:29
1
1,723
Evren Bingøl
78,688,424
13,977,239
algorithm to detect pools of 0s in a matrix
<p>I'm writing an algorithm that detects regions of contiguous empty cells that are completely surrounded (orthogonally) by filled cells and do not extend to the edge of the grid. Let's call such regions &quot;pools&quot;.</p> <p>As you can see in the below visualization, there are three pool cells – <code>(1, 1)</code...
<python><arrays><algorithm><matrix><multidimensional-array>
2024-06-30 11:22:58
1
575
chocojunkie
78,688,289
5,029,589
Retrive all records from elasticsearch
<p>I have an index on Elasticsearch that has more than 100K records.</p> <p>The format of the index data is:</p> <pre><code>{ &quot;_index&quot;: &quot;isp_names&quot;, &quot;_id&quot;: &quot;XX.XXX.XXX.X&quot;, &quot;_version&quot;: 1, &quot;_score&quot;: 1, &quot;_source&quot;: { &quot;XX.XXX.XXX.X&quot;: &quot;Some ...
<python><elasticsearch>
2024-06-30 10:22:07
1
2,174
arpit joshi
78,688,223
6,597,296
Communicating with a Kafka server from a Python app using the Twisted framework
<p>I have an app written using the Twisted framework, that communicates various data (mostly - log entries in JSON format) to a variety of logging servers using output plug-ins. I would like to make it able to send the data to a Kafka server, too - but I am hitting some kind of problem that I don't know how to solve.</...
<python><apache-kafka><twisted>
2024-06-30 09:51:32
1
578
bontchev
78,688,141
15,358,800
How to choose dataset_text_field in SFTTrainer hugging face for my LLM model
<p>Note: Newbie to LLM's</p> <h2>Background of my problem</h2> <p>I am trying to train a LLM using LLama3 on stackoverflow <code>c</code> langauge dataset.</p> <pre><code>LLm - meta-llama/Meta-Llama-3-8B Dataset - Mxode/StackOverflow-QA-C-Language-40k </code></pre> <p>My dataset structure looks like so</p> <pre><code>D...
<python><large-language-model><huggingface><huggingface-datasets>
2024-06-30 09:25:57
1
4,891
Bhargav
78,687,946
6,243,129
How to optimize PyTorch and Ultralytics Yolo code to utilize GPU?
<p>I am working on a project which involves object detection and tracking. For object detection I am using <code>yolov8</code> and for tracking, I am using <code>SORT</code> tracker. After running the below code, my GPU usage is always under 10% and CPU usage is always more than 40%. I have installed <code>cuda</code>,...
<python><machine-learning><pytorch><gpu><yolov8>
2024-06-30 07:43:52
2
7,576
S Andrew
78,687,879
10,855,529
Standard way to use a udf in polars
<pre><code>def udf(row): print(row) print(row[0]) print(row[1]) return row df = pl.DataFrame({'a': [1], 'b': [2]}) df = df.map_rows(udf) </code></pre> <p>gives output,</p> <pre><code>(1, 2) 1 2 </code></pre> <p>but I would like to use the <code>[]</code> notation, is there a specific reason that it com...
<python><python-polars>
2024-06-30 07:08:25
1
3,833
apostofes
78,687,580
395,857
"RuntimeError: BlobWriter not loaded" error when exporting a PyTorch model to CoreML. How to fix it?
<p>I get a &quot;RuntimeError: BlobWriter not loaded&quot; error when exporting a PyTorch model to CoreML. How to fix it?</p> <p>Same issue with Python 3.11 and Python 3.10. Same issue with torch 2.3.1 and 2.2.0. Tested on Windows 10.</p> <p>Export script:</p> <pre><code># -*- coding: utf-8 -*- &quot;&quot;&quot;Core M...
<python><pytorch><coreml><coremltools>
2024-06-30 03:30:14
1
84,585
Franck Dernoncourt
78,687,492
1,371,666
permanent virtual numpad in tkinter
<br> I am using Python 3.11.9 on windows OS.<br> I want to create button in tkinter which when pressed add text to entry i selected before clicking the button.<br> Here is my example code<br> <pre><code>from tkinter import * class Application(Frame): def __init__(self, master=None): Frame.__init__(self, mas...
<python><tkinter>
2024-06-30 02:07:01
1
481
user1371666
78,687,398
6,343,313
Regex does or does not give an error depending on which REPL is used
<p>Consider the following Python code using the regex library re</p> <pre><code>import re re.compile(rf&quot;{''.join(['{c}\\s*' for c in 'qqqq'])}&quot;) </code></pre> <p>I have run it in two different REPLs:</p> <p><a href="https://www.pythonmorsels.com/repl/" rel="nofollow noreferrer">https://www.pythonmorsels.com/r...
<python><regex><f-string>
2024-06-30 00:46:17
2
1,580
Mathew
78,687,328
395,857
"Failed to load _MLModelProxy: No module named 'coremltools.libcoremlpython'"when converting an ONNX model to CoreML with onnx-coreml lib. How to fix?
<p>I try to use the onnx-coreml lib to convert an ONNX model to CoreML:</p> <pre><code>import onnx from onnx_coreml import convert onnx_model = onnx.load('model.onnx') coreml_model = convert(onnx_model) coreml_model.save('model.mlmodel') </code></pre> <p>Error:</p> <pre><code>C:\code\export_model_to_coreml.py scikit-l...
<python><coreml><onnx><onnx-coreml>
2024-06-29 23:56:16
0
84,585
Franck Dernoncourt
78,687,274
446,943
Python problem showing image in label in secondary window
<p>This problem is one of many posted here where there's an error because the image created by PhotoImage doesn't exist. Consider this code:</p> <pre><code>from tkinter import * from PIL import ImageTk def show(): path = r'P:\Greece Slideshow\01001-MJR_20240511_5110080-Edit.jpg' pimg = ImageTk.PhotoImage(file=...
<python><tkinter><python-imaging-library><photoimage>
2024-06-29 23:06:27
1
3,740
Marc Rochkind
78,687,048
11,860,883
Count all unique triples
<p>Suppose that I have a pandas data frame A with columns called user_id and history where history is an array of ints. And the possible histories are bounded from above by 2000. I need to iterate through all rows of A, for each history b = [b1, b2, b3, ..., bn]. All bi's are unique(only appearing once in the array). I...
<python><pandas><algorithm><pytorch>
2024-06-29 20:58:46
3
361
Adam
78,686,937
15,547,292
Shorter way to define contextmanager by decorator?
<p>When creating a decorator using <code>@contextlib.contextmanager()</code>, we have to write</p> <pre class="lang-py prettyprint-override"><code>enter_action(...) try: yield ... finally: exit_action(...) </code></pre> <p>That is 3 lines just for the (rather unaesthetic) <code>try/yield/finally</code> construct...
<python><contextmanager>
2024-06-29 19:54:27
2
2,520
mara004
78,686,834
17,896,651
Add Payment Method on my SAAS using an API from local gateway
<p>I have a SAAS program on Django and Python, that manage Clients accounts (one or many).</p> <p>As for now, we handle all payment manually, adding a new client manually to reoccurring monthly payment 3'rd party system For a client with many accounts we have a payment calculator and we charge the amount manually. The ...
<python><django>
2024-06-29 18:59:29
0
356
Si si
78,686,779
1,114,105
Why does my code time out with ThreadPoolExecutor but not with normal Threads
<p>Trying to solve <a href="https://leetcode.com/problems/web-crawler-multithreaded/" rel="nofollow noreferrer">https://leetcode.com/problems/web-crawler-multithreaded/</a></p> <p>This code works (well at least for the toy test cases before eventually TLE'ing)</p> <pre><code>from collections import deque from urllib.pa...
<python><multithreading><queue><threadpoolexecutor>
2024-06-29 18:29:41
1
1,189
user1114
78,686,622
2,425,044
Install Artifact Registry Python package from Dockerfile with Cloud Build
<p>I have a python package located in my Artifact Registry repository.</p> <p>My Dataflow Flex Template is packaged within a Docker image with the following command:</p> <pre><code>gcloud builds submit --tag $CONTAINER_IMAGE . </code></pre> <p>Since developers are constantly changing the source code of the pipeline, th...
<python><dockerfile><google-cloud-dataflow><google-cloud-build><google-artifact-registry>
2024-06-29 17:01:59
2
2,038
Grégoire Borel
78,686,561
6,554,121
sqlite db not being created in RUN instruction during image build (python/pdm)
<p>What I'm trying to do is for a new sqlite db file to be created when spinning up a container. But the db files doesn't get created for some reason. When I run the file inside the container normally: <code>pdm run src/db_setup.py</code> it works fine and the file is created.</p> <p>So why doesn't the <code>RUN pdm ru...
<python><docker>
2024-06-29 16:33:06
0
12,739
A. L
78,686,504
13,566,716
422 Unprocessable Entity error when sending Form data to FastAPI backend using ReactJs and Fetch API in the frontend
<p>I keep getting the <code>422 Unprocessable Entity</code> error with the follwoing missing fields:</p> <pre><code>{&quot;detail&quot;:[{&quot;type&quot;:&quot;missing&quot;,&quot;loc&quot;:[&quot;body&quot;,&quot;username&quot;],&quot;msg&quot;:&quot;Field required&quot;,&quot;input&quot;:null},{&quot;type&quot;:&quo...
<javascript><python><reactjs><fastapi><http-status-code-422>
2024-06-29 16:03:34
1
369
3awny
78,686,477
9,554,640
ONNXRuntimeError with chromadb adding docs on MacOS
<p>I am trying to run Python script with Chroma db. Create collection, add some vectors and get. But getting an error.</p> <p>Script:</p> <pre class="lang-py prettyprint-override"><code>import chromadb client = chromadb.Client() collection = client.create_collection(name=&quot;example&quot;) collection.add( documen...
<python><chromadb>
2024-06-29 15:51:35
2
372
Dmitri Galkin
78,686,295
2,755,116
import python libraries in jinja2 templates
<p>I have this template:</p> <pre><code>% template.tmpl file: % set result = fractions.Fraction(a*d + b*c, b*d) %} The solution of ${{a}}/{{b}} + {{c}}/{{d}}$ is ${{a * d + b*c}}/{{b*d}} = {{result.numerator}}/{{result.denominator}}$ </code></pre> <p>which I invoke by</p> <pre><code>from jinja2 import Template import ...
<python><jinja2>
2024-06-29 14:45:24
1
1,607
somenxavier
78,686,253
16,778,949
Encountering ValueError upon joining two pandas dataframes on a datetime index column
<p>I have two tables which I need to join on a date column. I want to preserve all the dates in both tables, with the empty rows in each table just being filled with <code>NaN</code>s in the final combined array. I think an outer join is what I'm looking for. So I've written this code (with data_1 and data_2 acting as ...
<python><pandas><dataframe>
2024-06-29 14:27:24
1
534
phoney_badger
78,686,206
20,920,790
How to insert int128 data to Cickhouse with ClickHouseHook?
<p>I'm using ClickHouseHook for insert data to databse.</p> <pre><code>from airflow_clickhouse_plugin.hooks.clickhouse import ClickHouseHook ch_hook = ClickHouseHook(clickhouse_conn_id=connections_name) def update_replacingmergetree(ch_hook, table_name: str, df: pd.DataFrame): values = tuple(df.to_records(index=F...
<python><airflow><clickhouse>
2024-06-29 14:11:00
1
402
John Doe
78,686,130
6,058,203
scrapy selenium firefox - cant scrap urls from a page
<p>I am trying to get a list of urls from a website (perfectly permitted to scrape it). I am using firefox and whilst it seemed to work last month does not work this month and i am struggling to see where the error is.</p> <p>In the code below, the url_authority_list list is empty at the end.</p> <p>the output i get i...
<python><selenium-webdriver><firefox><scrapy>
2024-06-29 13:43:31
0
379
nevster
78,686,119
7,404,892
How To get consistent and expected json from Autogen?
<p>I'm using multi-agent autogen, where I have multiple critic agents who review writer agent's report. I need to get critic reviews in a specific JSON format, but I'm not getting a consistent and expected JSON as output. How can I get this?</p> <p>I tried configuring llm config with the below param, but no use.</p> <p...
<python><artificial-intelligence><ms-autogen>
2024-06-29 13:39:15
0
1,225
Nayana Madhu
78,686,046
6,621,137
pip dependencies from env yaml file missed during building docker container
<p>I have the following conda environment YAML file :</p> <pre><code>name: someapp channels: - conda-forge - defaults dependencies: - flask=2.2.2 - pandas=1.5.3 - pip=23.0.1 - python=3.11.3 - pip: - psycopg2-binary==2.9.9 - requests==2.32.3 prefix: /usr/local/anaconda3/envs/someapp </code></pr...
<python><docker><conda>
2024-06-29 13:02:16
1
452
TmSmth
78,685,937
937,440
Search for currency pairs
<p>I am trying to learn more about Python. I am trying to pull some data from Yahoo Finance. I have this code:</p> <pre><code>import yfinance as yf from statsmodels.tsa.vector_ar.vecm import coint_johansen symbols = ['AMZN', 'AAPL'] start = '2020-01-01' end = '2024-01-16' data = yf.download(symbols, start=start, end...
<python><python-3.x><yfinance>
2024-06-29 12:10:58
0
15,967
w0051977
78,685,901
10,855,529
ComputeError: dynamic pattern length in 'str.replace' expressions is not supported yet
<p>What is the polars expression way to achieve this,</p> <pre><code>df = pl.from_repr(&quot;&quot;&quot; ┌───────────────────────────────┬───────────────────────────┐ │ document_url ┆ matching_seed_url │ │ --- ┆ --- │ │ str ...
<python><regex><dataframe><python-polars>
2024-06-29 11:54:16
2
3,833
apostofes
78,685,861
2,748,928
Optimizing an LLM Using DPO: nan Loss Values During Evaluation
<p>I want to optimize an LLM based on DPO. When I tried to train and evaluate the model, but there are nan values in the evaluation results.</p> <blockquote> </blockquote> <pre><code>import torch from transformers import AutoModelForCausalLM, AutoTokenizer from datasets import Dataset from trl import DPOTrainer, DPOCon...
<python><huggingface-transformers><large-language-model><huggingface><huggingface-trainer>
2024-06-29 11:37:20
1
1,220
Refinath
78,685,748
893,254
FastAPI no module named "my module" - FastAPI cannot find my Python Package
<p>FastAPI cannot find my Python Package. It seems relatively obvious that this is an issue with Python paths and imports, however I do not know how to fix it.</p> <p>What surprised me is that this worked when using Flask instead of FastAPI. I converted a small application from Flask to FastAPI, and this is when the im...
<python><fastapi>
2024-06-29 10:46:00
1
18,579
user2138149
78,685,502
1,867,328
How to easily standardise pandas dataframe
<p>I have below pandas dataframe</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd dat = pd.DataFrame({'AA': [1, 2], 'BB': [3,4]}) </code></pre> <p>I am looking for a direct way to standardise each column like in <code>SAS</code> we have <a href="https://www.statology.org/sas-proc-stdize/" rel="no...
<python><pandas><dataframe>
2024-06-29 08:48:36
1
3,832
Bogaso
78,685,269
880,783
Is there a Numpy function to subset an array based on values (not indices) in a slice or range?
<p>I am trying to extract, from an array, all values within a certain <code>slice</code> (something like a <code>range</code>, but with optional <code>start</code>, <code>stop</code> and <code>step</code>). And in that, I want to benefit from the heavy optimizations that <code>range</code> objects employ for <code>rang...
<python><numpy><subset><slice>
2024-06-29 06:57:07
3
6,279
bers
78,685,004
3,486,684
Efficiently storing data that is not yet purely-columnar into the Arrow format
<p>I previously asked a question similar to this one (in that it uses the same example to illustrate the problem): <a href="https://stackoverflow.com/questions/78684997/efficiently-storing-data-that-is-not-quite-columnar-yet-into-a-duckdb-database?noredirect=1#comment138730725_78684997">Efficiently storing data that is...
<python><pyarrow><apache-arrow>
2024-06-29 03:39:33
1
4,654
bzm3r
78,684,997
3,486,684
Efficiently storing data that is partially columnar into a DuckDB database in a purely columnar form
<p>I have some partially columnar data like this:</p> <pre><code>&quot;hello&quot;, &quot;2024 JAN&quot;, &quot;2024 FEB&quot; &quot;a&quot;, 0, 1 </code></pre> <p>If it were purely columnar, it would look like:</p> <pre><code>&quot;hello&quot;, &quot;year&quot;, &quot;month&quot;, &quot;value&quot; &quot;a&quot;, 2024...
<python><postgresql><duckdb>
2024-06-29 03:31:12
2
4,654
bzm3r
78,684,807
908,313
or tools flexible job shop intervals with multiple machines and per machine availability per job
<p>I have been looking at OR-tools flexible job shop examples, specifically around machine jobs with per job durations. I see examples for this base problem problems but not for a way to specify specific times of day that particular jobs can be done on a machine.</p> <p>How would I approach implementing an additional c...
<python><or-tools><constraint-programming><cp-sat>
2024-06-29 00:22:45
0
1,130
Jarrod Sears
78,684,750
3,213,204
Key-value “sub-parameter” with Python’s argparse
<p>I want to make the <code>--new-entry</code> parameter be able to process a key-value sequence with space as statement separator.</p> <p>As example:</p> <pre class="lang-bash prettyprint-override"><code>script.py --new-entry name=&quot;The Republic&quot; author=&quot;Plato&quot; year=&quot;-400&quot; </code></pre> <p...
<python><parameter-passing><argparse><key-value>
2024-06-28 23:46:02
1
321
fauve
78,684,705
5,009,293
UnicodeDecodeError: 'charmap' codec can't decode byte 0x90
<p>So, yesterday I was having issues trying to define all columna via the data frame's to_sql method. For the most part, this works just fine.</p> <p>One file I was trying to process, however, is giving me an odd error. See below.</p> <p>When I run this :</p> <pre><code> data.to_sql ( name=f'tbl{table_name}...
<python><dataframe><sqlalchemy><anaconda>
2024-06-28 23:12:46
0
7,207
Doug Coats
78,684,619
2,153,235
"matplotlibrc" is read at the "startup" of what?
<p>According to <a href="https://matplotlib.org/stable/users/explain/customizing.html#customizing-with-matplotlibrc-files" rel="nofollow noreferrer">matplotlibrc documentation</a>, &quot;The <code>matplotlibrc</code> is read at startup to configure Matplotlib.&quot; It didn't say the startup of what. Can I assume that...
<python><matplotlib>
2024-06-28 22:28:35
1
1,265
user2153235
78,684,613
3,213,204
Match a patern with multiple entries in arbitrary order in Python with re
<p>I try to catch values entered in syntax like this one <code>name=&quot;Game Title&quot; authors=&quot;John Doe&quot; studios=&quot;Studio A,Studio B&quot; licence=ABC123 url=https://example.com command=&quot;start game&quot; type=action code=xyz78</code></p> <p>But <code>name</code>, <code>author</code>, <code>studi...
<python><regex><python-re>
2024-06-28 22:25:10
1
321
fauve
78,684,592
2,475,195
Pandas hybrid rolling mean
<p>I want to consider a window of size 3, in which I take the last value from the <code>b</code> column, and the other 2 values from the <code>a</code> column, like in this example:</p> <pre><code>df = pd.DataFrame.from_dict({'a':[1, 2, 3, 4, 5], 'b':[10, 20, 30, 40, 50]}) df['hybrid_mean_3'] = [10, 10.5, 11, 15, 19] #...
<python><pandas><dataframe><rolling-computation>
2024-06-28 22:16:00
1
4,355
Baron Yugovich
78,684,570
395,857
Is there any point in setting `fp16_full_eval=True` if training in `fp16`?
<p>I train a Huggingface model with <a href="https://huggingface.co/docs/transformers/main_classes/trainer#transformers.Seq2SeqTrainingArguments.fp16_opt_level" rel="nofollow noreferrer"><code>fp16=True</code></a>, e.g.:</p> <pre class="lang-py prettyprint-override"><code> training_args = TrainingArguments( outp...
<python><huggingface-transformers><half-precision-float>
2024-06-28 22:04:10
1
84,585
Franck Dernoncourt
78,684,472
4,591,810
How to convert a glb 3D design file to a step file in python?
<p>I have found several libraries, <a href="https://github.com/tpaviot/pythonocc-core" rel="nofollow noreferrer"><code>pythonOCC</code></a>, <a href="https://gitlab.com/dodgyville/pygltflib" rel="nofollow noreferrer"><code>pygltflib</code></a> which have data exchange functions. However, I cannot figure out how to conv...
<python><file-conversion><step>
2024-06-28 21:18:51
1
3,731
hazrmard
78,684,119
2,475,195
Pandas dataframe - keep values that are certain number of rows apart
<p>I have a column of 0s and 1s. I only want to keep 1s in the output column only if they end up being at least 4 rows apart. Note that simply doing <code>diff()</code> is not a solution, because this would eliminate too many <code>1</code>s. Here's an example:</p> <pre><code>df = pd.DataFrame.from_dict({'ix':list(rang...
<python><pandas><dataframe>
2024-06-28 19:11:30
3
4,355
Baron Yugovich
78,684,115
5,924,007
Python: Relative import with no known parent package
<p>I have an AWS Python lambda. The directory structure is as follows&quot;</p> <pre><code>src __init__.py main.py service.py </code></pre> <p>I am initiating a detabase connection in <code>__init__.py</code> file and then importing the connection variable in <code>main.py</code></p> <p><code>from . import ...
<python><python-3.x><aws-lambda><relative-import>
2024-06-28 19:10:16
1
4,391
Pritam Bohra
78,684,063
8,584,739
Python strptime not working when time zone is PST
<p>I have a python function to convert a given date time string to epoch time. It is working when the date time string has the time zone, say IST. I need to change the time zone to PST/PDT for obvious reasons, but it throws <code>ValueError: time data '01-06-2024 21:30 PDT' does not match format '%d-%m-%Y %H:%M %Z'</co...
<python><python-3.x>
2024-06-28 18:54:24
1
1,228
Vijesh
78,684,013
3,361,850
Minimize repetitions by removing all occurrences of one number
<p>I did a program in python3 which is correct, it gives the right results, but it has Time Complexity of O(n^2). I wanna improve the Time complexity of this program. When I run it on a platform <a href="https://concours.algorea.org/contents/4807-4802-1735320797656206224-103413922876285801-1426630568355953802/" rel="no...
<python><python-3.x><algorithm><time-complexity>
2024-06-28 18:35:05
2
1,063
Mourad BENKDOUR
78,683,994
12,466,687
How to add horizontal lines dynamically to a facet plot in plotly python?
<p>I am trying to add <code>upper</code> and <code>lower</code> limits <code>red dashed horizontal lines</code> to each <strong>facet Line plot</strong> based on respective column values but dashed lines are not formed at correct yaxis values of the facets.</p> <p>I have tried below code and made several attempts but i...
<python><plotly><python-polars><facet>
2024-06-28 18:28:53
1
2,357
ViSa
78,683,848
22,479,232
Attribute error : None type object in Linked List
<p>I tried to create a simple single-linked list as the following:</p> <pre class="lang-py prettyprint-override"><code>class node: def __init__(self, data=None): self.data = data self.next = None class linkedlist: def __init__(self): self.head = node() def append(self, data): ...
<python><data-structures><linked-list><nonetype>
2024-06-28 17:47:55
2
351
Epimu Salon
78,683,609
893,254
I want to write and deploy a single thread, single process Flask/Gunicorn application? How can I maintain persistent state?
<p>Please note that if you have seen a similar question from myself on <code>stackoverflow.com/beta/discussions</code> this question is intended to be focused with (hopefully) a specific answer, rather than a more open ended discussion with a range of possible answers.</p> <p>I am writing a Flask application which I in...
<python><flask>
2024-06-28 16:46:21
1
18,579
user2138149
78,683,536
7,886,968
How to find the location of a specific "include" library in Python?
<p>Within a particular Python program, how do I know what and where a particular included file is?</p> <p>For example: given <code>import EASY from easygopigo</code>, how do I find which one of many <code>easygopigo</code> libraries are being used?</p> <p>In other words, I'd like the Python equivalent of <code>which [c...
<linux><python><raspbian><debian-buster>
2024-06-28 16:03:08
1
643
Jim JR Harris
78,683,374
893,254
Due to the Python GIL, access to "most" variables is (usually said to be) thread safe. However access to global variables is not. What explains this?
<p>There are several questions on Stack Overflow which explain why access to global variables is not thread safe in Python, even with the presence of the Global Interpreter Lock.</p> <p>This reason for this is that the GIL only permits a single Python Interpreter instance to execute bytecode at any one time. However, s...
<python><multithreading>
2024-06-28 15:48:55
1
18,579
user2138149
78,683,270
1,304,376
How to watch recursion depth in vscode?
<p>I'm trying to convert a custom json-like response structure to json object. Since lists can contain dicts and vice versa, I'm calling them recursively as they appear. While the recursion is deep, I don't think it should have exceeded the recursion depth. So, I think I have a bug in the handling. Or maybe I'm misunde...
<python><visual-studio-code><recursion>
2024-06-28 15:23:55
0
1,676
Ching Liu
78,683,162
439,497
Why does sign of eigenvector flip for small covariance change?
<p>The 2 covariance matrices only differ by values at top-right and bottom-left. However, sign of principal component eigen vectors (right column) has flipped.</p> <pre><code>import numpy as np cov = np.array([[9369, 7060, 16469], [7060, 8127, 23034], [16469, 23034, 126402]]) eige...
<python><eigenvector>
2024-06-28 14:58:09
2
7,005
ManInMoon
78,683,099
1,726,633
Gradient flow in Pytorch for autocallable options
<p>I have the following code:</p> <pre><code>import numpy as np import torch from torch import autograd # Define the parameters with requires_grad=True r = torch.tensor(0.03, requires_grad=True) q = torch.tensor(0.02, requires_grad=True) v = torch.tensor(0.14, requires_grad=True) S = torch.tensor(1001.0, requires_grad...
<python><pytorch><quantitative-finance>
2024-06-28 14:44:03
1
368
user1726633
78,683,065
5,931,672
PIP downloading again package already installed
<p>I am trying to install <a href="https://github.com/timeseriesAI/tsai/" rel="nofollow noreferrer">tsai</a>. When doing so, PIP tries to download PyTorch:</p> <pre><code>Collecting torch&lt;1.14,&gt;=1.7.0 (from tsai==0.3.5) </code></pre> <p>However, I already have a version that matches 1.7 &lt; my version &lt; 1.14....
<python><pip>
2024-06-28 14:34:33
3
4,192
J Agustin Barrachina
78,683,048
2,645,548
How to authorize in python google cloud library with API-token
<p>How to authorize with API-token? My code</p> <pre class="lang-py prettyprint-override"><code>from google.auth.api_key import Credentials from google.cloud.storage import Client client = Client('my-project', Credentials('my-token')) blobs = client.list_blobs('my-bucket') for blob in blobs: print(blob.name) </cod...
<python><python-3.x><google-cloud-storage>
2024-06-28 14:30:04
1
611
jonsbox
78,682,971
1,003,288
Override return type hint of function from Python dependency
<p>I am using a dependency that has type hints but doesn't test them and some of them are just broken. For example:</p> <pre class="lang-py prettyprint-override"><code>def foo() -&gt; object: return {&quot;hello&quot;: &quot;world&quot;} </code></pre> <p>In my code I want to assign the output of that function to a ...
<python><python-typing>
2024-06-28 14:14:01
1
3,833
Jacob Tomlinson
78,682,936
7,056,539
SQLAlchemy async session requires refresh
<p>I'm new to SQLAlchemy in general, and even more to its asyncio mode. I'm creating an async session like so (demo/pseudo code):</p> <pre class="lang-py prettyprint-override"><code>async_scoped_session( async_sessionmaker( bind=create_async_engine( format_db_url(CONFIG) ) ), sco...
<python><sqlalchemy><python-asyncio>
2024-06-28 14:05:47
1
419
Nasa
78,682,716
13,537,183
Spark getItem shortcut
<p>I am doing the following in spark sql:</p> <pre class="lang-py prettyprint-override"><code>spark.sql(&quot;&quot;&quot; SELECT data.data.location.geometry.coordinates[0] FROM df&quot;&quot;&quot;) </code></pre> <p>This works fine, however I do not want to use raw SQL, I use datafr...
<python><apache-spark><pyspark><databricks>
2024-06-28 13:19:23
3
699
Pdeuxa
78,682,652
13,912,132
Python packages: Multiple subprojects
<p>I have this directory structure:</p> <pre><code>pyproject.toml proj1/ pyproject.toml MANIFEST.in proj1/ __init__.py proj2/ pyproject.toml MANIFEST.in proj2/ __init__.py </code></pre> <p>What I want to do is:</p> <ul> <li>The toplevel pyproject.toml is only there for e.g. formatting and including ...
<python><python-packaging><hatch>
2024-06-28 13:06:14
0
3,593
JCWasmx86
78,682,628
6,179,785
Reading Excel date columns as strings without time part
<p>I'm encountering an issue while reading date columns from an Excel file into a Pandas DataFrame. The date values in my Excel sheet are formatted as DD-MM-YYYY (e.g., 05-03-2024), but when I use pd.read_excel, Pandas interprets these values as datetime objects and appends 00:00:00, resulting in output like this:</p> ...
<python><pandas>
2024-06-28 13:03:29
1
340
Ash3060