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
⌀
77,867,313
3,353,525
Python Requests lib - How to get IP address of connected host after getting the response?
<p>I'm trying to understand how I could access information about host that the request connected to. I have situation when behind a hostname, there is a multiple IP addresses that you can connect to, so for example <code>x.com</code> can route me to <code>1.2.3.4</code> or <code>2.3.4.5</code>. I need that information ...
<python><python-3.x><python-requests><urllib>
2024-01-23 15:10:07
0
474
drajvver
77,867,075
42,126
Python cProfile module throws exception in Lambda
<p>I'm trying to profile the execution of a function within my Lambda handler:</p> <pre><code>import cProfile import time def myfunc(reps, sleeptime): for x in range(reps): print(f&quot;rep {x}&quot;) time.sleep(sleeptime) def lambda_handler(event, context): x = 3 y = 0.25 cPro...
<python><amazon-web-services><aws-lambda>
2024-01-23 14:35:36
1
39,699
kdgregory
77,866,966
1,562,335
Implement a round robin tournament without playing twice with the same partner
<p>I want to organize a badminton tournament in double teams, where no one plays twice with the same partner, using python. I created a graph using nx.Graph and implemented a function to get the list of unplayed partners for each round (each player keeps track of already played partners). But unfortunately, after a few...
<python><graph><round-robin><tournament>
2024-01-23 14:17:49
0
588
AwaX
77,866,590
17,194,313
How do you create and update an iceberg table via Polars or PyArrow?
<p>So far I've been happy with using parquet as the data format to persist my data, but I'm being encouraged to try iceberg as an alternative approach.</p> <p>Keen to give it a go, but not sure how to start.</p> <p>let's say I have a <code>polars</code> dataframe in Python:</p> <pre class="lang-py prettyprint-override"...
<python><dataframe><python-polars><pyarrow><apache-iceberg>
2024-01-23 13:14:07
2
3,075
MYK
77,866,553
13,158,157
Write selected columns from pandas to excel with xlsxwriter efficiently
<p>I’m trying to write some of the columns of a pandas dataframe to an Excel file, but it’s taking too long. I’m currently using xlsxwriter to write all of the data to the file, which is much faster. How can I write only some of the columns to the file without sacrificing performance?</p> <p>My code for writing selecte...
<python><pandas><xlsxwriter>
2024-01-23 13:08:10
1
525
euh
77,866,543
8,971,668
create pydantic computed field with invalid syntax name
<p>I have to model a pydantic class from a JSON object which contains some invalid syntax keys.</p> <p>As an example:</p> <pre class="lang-py prettyprint-override"><code>example = { &quot;$type&quot;: &quot;Menu&quot;, &quot;name&quot;: &quot;lunch&quot;, &quot;children&quot;: [ {&quot;$type&quot;: ...
<python><pydantic><pydantic-v2>
2024-01-23 13:06:19
2
542
ndricca
77,866,436
159,695
How to use numba with readonly dict as input?
<p>I tried <code>typed.Dict.empty(types.uint8[:], types.int32)</code>, but it is not working.</p> <pre><code>import struct import scipy as sp import numpy as np import numba as nb #@nb.njit(parallel=True) def process_uids(uid, data, XYtoBCID ): indices = np.where(data == uid) uid_row = np.zeros(data.size, dtyp...
<python><dictionary><numba>
2024-01-23 12:49:26
1
2,072
Galaxy
77,866,435
590,335
vscode supports python scripts that can be run interactively - is there an option to have a section that runs only in interactive mode?
<p>vscode supports python scripts that can be run interactively - is there an option to have a section that runs only in interactive mode?</p> <p>that is, this snippet should be run as a notebook cell in interactive mode, but not when running as script</p> <p>a possible option would by a flag like the <strong>name</str...
<python><visual-studio-code><jupyter-notebook>
2024-01-23 12:49:08
0
8,467
Ophir Yoktan
77,866,356
3,512,538
building and installing extensions during pip install -e
<p>I have a <code>setup.py</code> with a CMake extension:</p> <pre class="lang-py prettyprint-override"><code>from setuptools.command.build_ext import build_ext class CmakeExtension(build_ext): ... if __name__ == &quot;__main__&quot;: setup( ... cmdclass={ &quot;build_ext&quot;: ...
<python><cmake><pip>
2024-01-23 12:39:23
0
12,897
CIsForCookies
77,866,250
470,994
See the raw IMAP commands when using imaplib or imap_tools
<p>I am writing a Python 3 script to handle IMAP mailboxes, and I am having some problems with the server. When I connect to it &quot;by hand&quot; and try to send raw IMAP commands, the server is unresponsive, and yet when I run the script it does what it does correctly.</p> <p>Anyway, in order to find out what's happ...
<python><python-3.x><imaplib><imap-tools>
2024-01-23 12:22:50
1
1,716
PaulJ
77,865,821
11,861,874
Insert PNG Image to Reportlab PDF using Python
<p>I have tried and gone through multiple topic on a similar questions, I am not able to export image to pdf, is there any way to debug to understand what's going on. When i use below function for simpler example it works fine, however, I can't share other image for which it doesn't work, I would like to know how can...
<python><io><reportlab>
2024-01-23 11:06:15
1
645
Add
77,865,780
23,179,206
Merging of PySimpleGUI EXE (PyInstaller) icons on the taskbar
<p>Windows 10<br /> Python 3.10.2<br /> PySimpleGUI 4.60.5<br /> pyinstaller 3.6.0</p> <p>Any PySimpleGUI EXEs generated using pyinstaller share the same icon on the taskbar when using PySimpleGUI 4.60.5 (the most recent version). But this issue does not occur with PySimpleGUI 4.57.0 (though it does also happen with th...
<python><pyinstaller><pysimplegui>
2024-01-23 11:00:14
0
910
Lee-xp
77,865,727
6,197,439
How to run bash shell echo in subprocess.run?
<p>On a Raspbian Stretch Linux, this <code>echo</code> command runs fine in the <code>bash</code> shell:</p> <pre class="lang-none prettyprint-override"><code>$ echo -n -e &quot;Hello World\n&quot; Hello World </code></pre> <p>Now, I want to execute this same command via Python 3's <code>subprocess.run</code>, passed a...
<python><subprocess>
2024-01-23 10:54:29
1
5,938
sdbbs
77,865,518
4,277,485
Reading partitioned multi-schema parquet files from S3 using Polars
<p>Having 1000+ s3 file in partitioned path, want to read all the files. using Polars because it is fast when compared to Pandas <br></p> <blockquote> <p>s3://bucket_name/rs_tables/name='part1'/key='abc'/date=''/part1_0000.parquet</p> </blockquote> <p>Scanning these files using Polars <br></p> <pre><code> source = &...
<python><dataframe><amazon-s3><partitioning><python-polars>
2024-01-23 10:18:23
1
438
Kavya shree
77,865,181
1,341,024
.relationship(…, cascade="all") does not delete children when multiple parents "bulk" deleted using session.execute(delete(Parent))
<p>I worte some code in Python for managing some database stuff. All I want to do, is to delete all parents of a 1-to-many relationsship , which should automatically delete all children. Here is my example code:</p> <pre><code>from sqlalchemy import create_engine, Column, Integer, String, ForeignKey from sqlalchemy.orm...
<python><sqlite><sqlalchemy><cascading-deletes>
2024-01-23 09:24:39
1
344
CodeCannibal
77,865,010
3,751,263
Run Python script in each subfolder automatically
<p>I have this file structure:</p> <ol> <li><p>Main Folder: <code>W001-W100</code>.</p> <ul> <li><p>Subfolder: <code>W001</code></p> <ul> <li>Around 500 DICOM files (I am working with CT data).</li> </ul> </li> <li><p>Subfolder: <code>W002</code></p> <ul> <li>Around 500 DICOM files (I am working with CT data).</li> </u...
<python><automation><subdirectory>
2024-01-23 08:50:46
1
2,800
antecessor
77,864,935
11,922,765
Python Seaborn Heatmap Turnoff main plot keep the cbar
<p>I am drawing a sub-plot figures with each sub-plot is a heatmap. I turned off all cbars. Now I will plot cbar separately. While doing so, I am getting main plot. I don't want it. I want to turn if off.</p> <p>My code:</p> <pre><code>df1 = Datetime 2022-08-04 15:06:00 53.4 57.8 2022-08-04 15:07:00 ...
<python><pandas><numpy><seaborn><heatmap>
2024-01-23 08:39:26
0
4,702
Mainland
77,864,794
4,784,914
How to get the project `config/` directory from inside an installed Python package?
<p>I have a Python database interface package, which requires configured credentials to work. I would like to tuck those away in a config file, that's not committed to the interface repository. So I have the following structure in mind:</p> <pre><code>my_project/ |- config/ | |- database.json |- main.py ...
<python><package><config>
2024-01-23 08:10:22
1
1,123
Roberto
77,864,704
4,281,353
Annotated Transformer - Why x + DropOut(Sublayer(LayerNorm(x)))?
<p>Please clarify if the <a href="https://nlp.seas.harvard.edu/annotated-transformer/#encoder-and-decoder-stacks" rel="nofollow noreferrer">Annotated Transformer</a> Encoder LayerNorm implementation is correct.</p> <p><a href="https://i.sstatic.net/8rLZkm.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/8...
<python><pytorch><transformer-model><encoder>
2024-01-23 07:49:43
1
22,964
mon
77,864,142
3,295,036
Pass SocketIO server instance to FastAPI routers as dependency
<p>I'm using <code>python-socketio</code> and trying to pass the server instance to my app routers as dependency:</p> <p><code>main.py</code> file:</p> <pre><code>import socketio import uvicorn from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from src.api.rest.api_v1.route_builder import b...
<python><fastapi>
2024-01-23 05:29:54
1
1,111
maudev
77,864,134
2,142,728
Pip dependency resolution algorithm (in editable installs)
<p>There are different and unclear explanations everywhere. I've checked the contents of wheels and sdists. I've learned about <code>setup.py</code>, <code>setup.cfg</code>, <code>pyproject.toml</code>, <code>dist-info</code> (and its <code>METADATA</code> file), about the <code>PKG-INFO</code> file, and I cannot conci...
<python><pip><setuptools><python-poetry><transitive-dependency>
2024-01-23 05:27:06
0
3,774
caeus
77,864,062
2,805,482
Streamlit display generated images with download button in form
<p>Hi I have a usecase where I have a streamlit form where I let user to upload images and based on the input images I generate multiple images. I write these images to tmp directory and wants to show it on the page along with a download button.</p> <p>Now my challenge is when I call <code>show_image()</code> after <co...
<python><streamlit>
2024-01-23 05:02:45
0
1,677
Explorer
77,864,039
17,610,082
How to avoid LOGENTRIES_TOKEN spam logs in django?
<p>When i run the <code>python manage.py &lt;somecmd&gt;</code>, i'm getting the below error:</p> <pre class="lang-bash prettyprint-override"><code>It appears the LOGENTRIES_TOKEN parameter you entered is incorrect! </code></pre> <p>How can i disable this log, this log spamming across the access log.</p> <p>I've tried ...
<python><python-3.x><django><debugging><logging>
2024-01-23 04:54:17
1
1,253
DilLip_Chowdary
77,863,948
12,352,239
load numpy array into pyspark
<p>I have an input json file where each row is an ID and a corresponding numpy array stored in base64. How can I load this file into pyspark?</p> <p>I have tried creating a udf to do this:</p> <pre><code>from pyspark.sql.functions import udf from pyspark.sql.types import ArrayType, DoubleType import base64 def decode...
<python><apache-spark><pyspark>
2024-01-23 04:07:47
2
480
219CID
77,863,752
920,599
Jupyter Notebook reports syntax error on code that isn't present
<p>Has anybody ever seen a Jupyter notebook give an error referring to code that is not actually present in the notebook?</p> <p>Notice that in the image below, the Syntax error refers to line 6 and the text <code>return amounts: {result}&quot;)</code></p> <p>This code does not appear in this block (or any other block ...
<python><jupyter-notebook>
2024-01-23 02:40:24
1
6,694
Zack
77,863,395
3,042,018
Python Turtle Graphics in GitHub Codespace
<p>Is it possible to run Python Turtle Graphics from Github Codespace? I tried and got</p> <pre><code>File &quot;/usr/local/python/3.10.13/lib/python3.10/tkinter/__init__.py&quot;, line 2299, in __init__ self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use) _tkinter....
<python><tkinter><python-turtle><github-codespaces>
2024-01-22 23:58:34
0
3,842
Robin Andrews
77,863,391
253,039
Reparenting the resources of a class to another class
<p>Suppose I have a python object <code>A</code> with field <code>field</code>. <code>A.field</code> is very expensive. Suppose a highly nested dict. At some point, after doing all necessary work with the <code>A</code> instance, I call <code>A.getB()</code>, which hands me a new kind of object <code>B</code>. The func...
<python><memory>
2024-01-22 23:57:00
1
402
Evan
77,863,269
7,563,454
Making threads in a pool notice changes to global variables
<p>I'm running into an interesting circumstance with pools which I don't fully understand. I was aware that if you edit any variable or object from a thread, changes will not be applied to the main thread and only exist in the isolated reality of that worker thread. Now however I'm noticing that threads in a pool don't...
<python><python-3.x><multithreading><threadpool>
2024-01-22 23:12:43
1
1,161
MirceaKitsune
77,863,214
9,983,652
Reconcile channels with varying data acquisition frequencies
<p>My dataframe has 8 columns for 4 different <em>data</em> recorded as a function of <em>depth</em>. However, each channel came with a different acquisition frequency. I would like to reconcile all these 4 data using a common depth interval.</p> <p>Interpolation with Scipy looked complex, so is there any easier method...
<python><pandas><interpolation><reindex>
2024-01-22 22:51:34
1
4,338
roudan
77,863,213
3,289,890
Addressing column header misalignment when using termcolor with pandas
<p>I'm currently facing a challenge while attempting to apply color to a single column in a Pandas DataFrame. I have this code snippet that accomplishes the task, but it introduces some side effects that are proving challenging to resolve.</p> <pre><code>import pandas as pd from termcolor import colored # Sample DataF...
<python><pandas><termcolor>
2024-01-22 22:51:12
1
1,008
Boris L.
77,863,198
558,639
pip fails: _in_process.py missing (but _in_process.pyc is present)
<p>TL;DR: What do I need to do in order to install the python <code>spidev</code> on my single-board linux machine?</p> <p>On a semi-custom Linux system:</p> <pre><code># uname -a Linux sama7 5.15.32-linux4microchip-2022.04 #1 Thu Jun 9 10:03:39 CEST 2022 armv7l GNU/Linux </code></pre> <p>I'm trying to <code>pip instal...
<python><linux><pip>
2024-01-22 22:45:15
0
35,607
fearless_fool
77,862,780
23,260,297
Read csv converts numeric column to data type string instead of float
<p>I am reading data from 2 files with similar formats using pandas. Both files contain the same column with all numeric values (positive and negative). One file reads the data in as floats and the other file reads the data in as strings. I need to format both columns with this line of code:</p> <pre><code>df['MTMValue...
<python><pandas>
2024-01-22 21:09:41
1
2,185
iBeMeltin
77,862,775
1,838,233
Pandas 2.2: FutureWarning: Resampling with a PeriodIndex is deprecated
<p>The pandas version 2.2 raises a warning when using this code:</p> <pre><code>import pandas as pd df = pd.DataFrame.from_dict({&quot;something&quot;: {pd.Period(&quot;2022&quot;, &quot;Y-DEC&quot;): 2.5}}) # FutureWarning: Resampling with a PeriodIndex is deprecated. # Cast index to DatetimeIndex before resampling i...
<python><pandas><pandas-resample>
2024-01-22 21:08:30
1
3,618
Arigion
77,862,704
14,890,683
Condense Pydantic Validators into Class Annotations
<p>Looking to create a datastructure in Python that condenses Pydantic's validators into oneline arguments:</p> <p>ie. from this</p> <pre class="lang-py prettyprint-override"><code>from pydantic import BaseModel, validator class MyClass(BaseModel): a: str b: str c: str @validator('b') def cal...
<python><pydantic>
2024-01-22 20:56:28
1
345
Oliver
77,862,678
3,456,812
simple python beginner chatgpt bot program bombs on compatibility issues, cannot find workaround
<p>I am trying to learn both Python and simple ChatGPT api programming. The code I came up with was suggested by gpt itself, and in researching the problem I'm having, every code example I can find on the web is basically doing the same thing as the code I'm trying (below).</p> <p>I started with a &quot;pip3 install op...
<python><openai-api><chatgpt-api>
2024-01-22 20:49:24
2
1,305
markaaronky
77,862,611
9,017,311
Quarto Unable to Render Python
<p>I <strong>cannot</strong> render Quarto documents that contain <code>Python</code> code chunks.</p> <p>I <strong>can</strong> successfully render Quarto documents that contain <code>R</code> code chunks.</p> <h1>Error message</h1> <p>The error message I receive is:</p> <pre><code>==&gt; quarto preview example.Qmd --...
<python><r><quarto><windows-11>
2024-01-22 20:36:28
1
712
Christian Million
77,862,210
23,190,147
What does [Errno 2] mean in python?
<p>I was playing around with python, and I was trying to open a file. I accidentally made a typo, and got the expected error:</p> <p>FileNotFoundError: [Errno 2] No such file or directory: 'tlesting.py'</p> <p>It was supposed to be <code>testing.py</code> if you are wondering.</p> <p>Of course, I expected the error, bu...
<python><file>
2024-01-22 19:09:18
2
450
5rod
77,862,188
4,049,444
Pygame font render missing baseline information, can not blit text properly
<p>In Pygame when rendering text with <code>render()</code> a surface is generated containing the text rendered. The size of the surface (<code>get_rect()</code>) has various heights based on the text itself. There is also the line height you can get with <code>get_linesize()</code>. Based just on these information the...
<python><fonts><pygame>
2024-01-22 19:05:45
1
315
geer
77,862,174
5,683,778
Quarto output executable RMD/QMD file with text includes
<p>I'm using quarto (v1.4) to put together an assignments for my a course, giving them the option to use either Python (.ipynb) or R (.rmd) to complete it. I'm giving them a template to get started, and having them edit some existing code.</p> <p>I have some generic preamble &amp; question text that I want to be unifo...
<python><r><r-markdown><quarto>
2024-01-22 19:03:49
0
1,230
June Skeeter
77,862,114
17,683,683
SSL certificate problem: unable to get local issuer certificate: zscaler
<p>Im trying to create docker image using dockerfile as it uses python, and it was throwing error while installing <code>RUN poetry install --no-root</code>. After digging deep it is throwing <code>SSL certificate problem: unable to get local issuer certificate</code> error as my system has Zscaler installed by my IT t...
<python><docker><python-poetry><zscaler>
2024-01-22 18:53:22
0
357
Rashmi Balkur
77,862,060
12,125,777
Django how to update existing database rows using pandas df.to_sql
<p>My goal is every day to update my <code>database lines by uploading a file containing the 7 past days data</code>.</p> <p>So, I have to read the file with pandas and load it into my <code>django database</code>. And most of time, the <code>dataframe</code> will have <code>lines already present in the database</code>...
<python><django><pandas><postgresql><django-models>
2024-01-22 18:40:37
1
542
aba2s
77,861,942
6,136,013
VSCode/Pylance converts network drive to UNC path
<p>I have a python file on a network drive (X:\foo.py). If I click on a python function defined in the same file and press F12 (go to definition), VSCode opens a <em>new window</em> where the file name is \\some.unc.path\foo.py This behavior is recent but downgrading VSCode to an older version didn't help. Is there a s...
<python><visual-studio-code><pylance>
2024-01-22 18:20:03
2
681
BlindDriver
77,861,879
1,493,192
RuntimeError: Sizes of tensors must match except in dimension 1. Expected size 78 but got size 102 for tensor number 1 in the list
<p>I am trying to try the example of this library <a href="https://github.com/openclimatefix/graph_weather?tab=readme-ov-file" rel="nofollow noreferrer">graph_weather</a></p> <pre><code>import torch from graph_weather import GraphWeatherForecaster from graph_weather.models.losses import NormalizedMSELoss lat_lons = []...
<python><pytorch>
2024-01-22 18:09:37
1
8,048
Gianni Spear
77,861,790
1,473,517
How to find an optimal circular area with regions missing
<p>I have an n by n matrix of integers and I want to find the circular area, with origin at the top left corner, with maximum sum. What makes this optimization problem more difficult is that I am allowed to miss out up to a fixed number of regions. A region is defined to be a consecutive block of rows. Let us call the ...
<python><algorithm><performance><optimization>
2024-01-22 17:54:26
1
21,513
Simd
77,861,764
15,341,457
Python Tkinter - Passing controllers as arguments of a tkinter frame
<p>I've got a main class called <em>App</em> that invokes 4 controllers. The method <em>start_from_home_page()</em> creates an object of type <em>HomePage</em> and I want this object to have access to all 4 controllers which I will pass as arguments. Here's the method:</p> <pre><code> def start_from_home_page(self, ...
<python><class><tkinter><arguments><parameter-passing>
2024-01-22 17:50:23
1
332
Rodolfo
77,861,682
18,476,381
Sqlalchemy - How to use joinedload while doing a groupby function
<p>I am trying join a load (vendor) to my main object (service_order) while also running a sum function and groupby. Below is the code I am trying to run.</p> <pre><code>async def search_service_orders( session: AsyncSession, service_order_number: str = None, source_service_order_number: str = None, lim...
<python><oracle-database><sqlalchemy>
2024-01-22 17:35:05
1
609
Masterstack8080
77,861,653
2,855,226
Does invoking a system call like statfs with Python subprocess use less overhead than invoking a C utility like df?
<p>Unix-based system. I'm trying to use as little overhead as possible right now in the code I'm working on (it's in a resource constrained space). In this particular code, we are gathering some basic disk usage stats. One suggestion was to replace a call to <code>df</code> with <code>statfs</code> since <code>df</code...
<python><unix><diskspace><overhead>
2024-01-22 17:31:13
1
506
Ryan Schuster
77,861,644
12,389,536
raise ValueError if None as value in dict __setitem__
<p>Is it possible to raise a ValueError if a new value in dict is a None? Is it possible without creating a new class based on <code>dict</code> and overloading <code>__setitem__</code> or checking each value before setting?</p> <pre class="lang-py prettyprint-override"><code>d = dict() d[&quot;va1&quot;] = None # sho...
<python><dictionary><collections>
2024-01-22 17:29:28
1
339
matt91t
77,861,609
13,147,413
Group by + rolling mean in Polars
<p>I need to translate this piece of pandas code:</p> <pre><code>df.groupby(groupby_col)[[A_col, B_col]].rolling(window=window, on=B_col, closed = 'left').agg(some_function) </code></pre> <p>to polars.</p> <p><em>A_col</em> features Int64 dtype, <em>B_col</em> datetime (ns).</p> <p>I came up with the following formulat...
<python><dataframe><python-polars>
2024-01-22 17:21:50
1
881
Alessandro Togni
77,861,518
955,273
polars: compute row-wise quantile over DataFrame
<p>I have some polars DataFrames over which I want to compute some row-wise statistics.</p> <p>For some there is a <code>.list.func</code> function which exists (eg <a href="https://docs.pola.rs/py-polars/html/reference/expressions/api/polars.Expr.list.mean.html" rel="nofollow noreferrer"><code>list.mean</code></a>), h...
<python><python-polars>
2024-01-22 17:04:17
1
28,956
Steve Lorimer
77,861,436
19,694,624
Can't edit an embed on callback function
<p>I am having troubles with editing a message with an embed. I want to replace the embed with another embed that is being created in a callback function <em>button click</em> (which executes on the button click). On the screenshots below you can see my problem. When I execute <em>/test</em> command, bot sends the firs...
<python><discord><discord.py><pycord>
2024-01-22 16:49:08
1
303
syrok
77,861,424
2,249,815
Python 3.X random.choice for object array with sub array?
<p>Provided the object array:</p> <pre><code>textures = [ { &quot;id&quot;: 1, &quot;name&quot;: &quot;cement&quot;, &quot;apply_to&quot;: [&quot;wall&quot;, &quot;basement&quot;], }, { &quot;id&quot;: 2, &quot;name&quot;: &quot;fabric&quot;, &quot;apply_to&qu...
<python><python-3.x>
2024-01-22 16:46:44
2
4,653
Jebathon
77,861,286
4,752,738
Does poetry/pip "compile" code when installing local package?
<p>I'm using poetry for my project (mono repo) structure. I have a lot of local packages that I want to &quot;install&quot;:</p> <pre><code>[tool.poetry.dependencies] &lt;my-local-lib&gt; = {path = &quot;../&lt;my-local-lib&gt;&quot;, develop = true} </code></pre> <p>Does it matter if I do <code>develop = true</code> o...
<python><pip><python-poetry>
2024-01-22 16:19:26
2
943
idan ahal
77,861,284
18,758,062
Regex/algorithm in Python to extract comments from class attributes
<p>Given the code for a class definition, I am trying to extract all attributes and their comments (<code>&quot;&quot;</code> empty string if no comments).</p> <pre class="lang-py prettyprint-override"><code>class Player(Schema): score = fields.Float() &quot;&quot;&quot; Total points from killing zombies an...
<python><python-3.x><regex><algorithm><parsing>
2024-01-22 16:19:12
2
1,623
gameveloster
77,861,151
21,185,825
Python - azure-devops - AssignedTo field is missing
<p>I wrote a python function retrieving the results from an <strong>ADO query</strong></p> <pre><code>def get_query_results(connection, project_name,query_id): ''' Gets the result of a query in ADO ''' results = [] try: wit_client = connection.clients.get_work_item_tracking_client() result =...
<python><azure-devops><ado>
2024-01-22 15:59:37
1
511
pf12345678910
77,861,129
9,786,534
Get the number of elements returned by a CDSView in Bokeh
<p>Given the following MRE, is it possible to access or print the number of elements resulting from the application of the <code>CDSView</code> filter on the <code>ColumnDataSource</code> in Bokeh? In this simple case, I'd like to get the information that 3 rows are returned and, if possible, access the index of <code>...
<python><bokeh>
2024-01-22 15:55:05
0
324
e5k
77,861,106
4,597,780
FastAPI depdendency factory
<p>I want to charge some credits for API usage and came up with following dependency</p> <pre><code>def charge_call(cost: int): async def _charge_call( wallet=Depends(get_wallet), ): await wallet.charge(cost) return _charge_call @router.post( &quot;/some-call&quot;, dependencies=[...
<python><dependency-injection><fastapi>
2024-01-22 15:50:07
1
1,914
Max
77,861,097
11,932,905
Pyspark one-hot encoding with grouping same id
<p>Is there a way to perform OHE in Spark and 'flatten' dataset so that each Id has only one row?</p> <p>For example if input is like this:</p> <pre><code>+---+--------+ | id|category| +---+--------+ | 0| a| | 1| b| | 2| c| | 1| a| | 2| a| | 0| c| +---+--------+ </code></pre> <...
<python><pyspark><one-hot-encoding>
2024-01-22 15:49:10
2
608
Alex_Y
77,861,071
12,696,223
Flax JIT error for inherited nn.Module class methods
<p>Based on <a href="https://github.com/google/jax/discussions/10598#discussioncomment-2700317" rel="nofollow noreferrer">this answer</a> I am trying to make a class jit compatible by creating a pytree node, but I get:</p> <pre><code>TypeError: Cannot interpret value of type &lt;class '__main__.TestModel'&gt; as an abs...
<python><jax><flax>
2024-01-22 15:45:39
0
990
Momo
77,860,523
8,283,557
Can't check client certs in CherryPy (mTLS)
<p>Is mTLS possible on CherryPy 18.9 / Python 3.12 ?</p> <p>The server is providing a valid certificate fine and clients are able to validate and connect to it via https without issue.</p> <p>However, for this particular project, I need to be able to authenticate client certs, so am wondering if it's implemented or a k...
<python><windows><ssl><cherrypy><mtls>
2024-01-22 14:21:22
0
323
Crapicus
77,860,272
1,249,481
Proper way to pass a pointer to numpy's structured array from Python to C
<p>I want to pass a pointer to numpy's structured array from Python to C. In Python I have:</p> <pre><code>import numpy as np import ctypes as ct so_file = 'test.so' my_functions = ct.CDLL(so_file) nobs = 3 intype = np.dtype([('nobs', np.intc), ('vals', np.double, (nobs, ))]) indata = np.empty(0, dtype=intype) new_e...
<python><c><numpy><ctypes>
2024-01-22 13:38:02
2
4,663
danas.zuokas
77,860,036
1,232,660
Why reading a compressed TAR file in reverse order is 100x slower?
<p>First, let's generate a compressed <code>tar</code> archive:</p> <pre class="lang-py prettyprint-override"><code>from io import BytesIO from tarfile import TarInfo import tarfile with tarfile.open('foo.tgz', mode='w:gz') as archive: for file_name in range(1000): file_info = TarInfo(str(file_name)) ...
<python><performance><tar>
2024-01-22 12:58:58
1
3,558
Jeyekomon
77,860,023
1,227,922
Dynamically add field to a Django Modelform
<p>I have read all previous posts regarding this, but none of the solutions work for me, maybe its because Django has changed something? I want to add fields dynamically to my modelform that is rendered in the django admin, in the future it will be based of fetching some information from the backend to populate the fie...
<python><django>
2024-01-22 12:55:12
0
1,489
Andreas
77,859,895
11,001,493
Why am I getting different hash for duplicated files?
<p>I need to check for duplicated and corrupted files in a folder with literally millions of files.</p> <p>First, I was trying this way:</p> <pre><code>hash_files = pd.DataFrame({&quot;Path&quot;:[], &quot;Hash&quot;:[]}) rootdir = &quot;//?/Z:/&quot; error_files = [] for root, subdir, file...
<python><hash><md5><hashlib>
2024-01-22 12:37:36
1
702
user026
77,859,861
1,840,524
What is the difference between xarray.open_mfdataset(parallel=True) and xarray.concat when using dask arrays?
<p>I'm working with a classic data processing workflow using python, i.e. loading a large number of files, pre-processing them, concatenating them and applying a few reductions.</p> <p>At the moment, I'm using a two-stage workflow with dask:</p> <ol> <li>I create a dask <code>Bag</code> to load and preprocess all the i...
<python><dask><python-xarray>
2024-01-22 12:30:45
1
1,529
Remy F
77,859,647
136,285
Python and support for EUC-KR
<p>I am trying to play with string encoding in python 3.10, in particular to demonstrate the <a href="https://archives.miloush.net/michkap/archive/2005/09/17/469941.html" rel="nofollow noreferrer">yen/won/backslash</a> encoding issue.</p> <p>So the <a href="https://stackoverflow.com/questions/56819615/are-there-correct...
<python><character-encoding><iconv>
2024-01-22 11:49:54
1
12,719
malat
77,859,478
4,255,096
ParseException when reading table in Spark fails
<p>I'm trying to read a table in spark using a string path but I get the following error:</p> <pre><code>spark.read.format(&quot;delta&quot;).table(path) Possibly unquoted identifier spark-warehouse detected. Please consider quoting it with back-quotes as `spark-warehouse`(line 1, pos 5) </code></pre> <p>The table tha...
<python><apache-spark><pyspark><delta-lake>
2024-01-22 11:22:45
0
375
Geosphere
77,859,473
525,865
Selenium use chrome on Colab got unexpectedly exited - how to fix this?
<p>i am trying to get data form a page</p> <p>see url = &quot;https://clutch.co/il/it-services&quot;</p> <p>The website i am trying to scrap from has some sort of anti-bot protection with CloudFlare or similar services, hence the scrapper need to use selenium with a headless browser like Headless Chrome or PhantomJS. S...
<python><selenium-webdriver><web-scraping><google-colaboratory>
2024-01-22 11:21:59
0
1,223
zero
77,859,431
1,922,302
How to get the index of function parameter list comprehension
<p>Gurobipy can apparently read the index of a list comprehension formulated within the parentheses of a function. How does this work? Shouldn't this formulation pass a generator object to the function? How do you read the index from that?</p> <pre><code> md = gp.Model() md.addConstrs(True for i in [1,2,5,3]) ...
<python><list-comprehension><generator><gurobi>
2024-01-22 11:14:46
1
953
johk95
77,859,418
7,662,164
Custom JVP and VJP for higher order functions in JAX
<p>I find custom automatic differentiation capabilities (JVP, VJP) very useful in JAX, but am having a hard time applying it to higher order functions. A minimal example of this sort is as follows: given a higher order function:</p> <pre><code>def parent_func(x): def child_func(y): return x**2 * y retur...
<python><function><higher-order-functions><jax><autodiff>
2024-01-22 11:12:44
1
335
Jingyang Wang
77,859,333
189,247
How to fit text labels on Seaborn log-log scatterplots?
<p>My question is how to adjust a Seaborn log-log scatterplot to fit text labels? MWE:</p> <pre><code>mport seaborn as sns mport seaborn.objects as so f = sns.load_dataset(&quot;penguins&quot;).sample(frac = 0.1) f['island'] = 'long names here' Arbitrary tweak distributions f['bill_length_mm'] = df['bill_length_mm'].a...
<python><plot><seaborn><scatter-plot><loglog>
2024-01-22 10:58:45
0
20,695
Gaslight Deceive Subvert
77,859,251
6,017,833
How do specify a only finite number of Hypothesis examples
<p>I am using Hypothesis to unit test my package. There are some functions in my package that I only want to run a few examples over for testing. I do not want Hypothesis to generate examples for me.</p> <p>If I do the following:</p> <pre class="lang-py prettyprint-override"><code>@example(s=&quot;hello world&quot;) @e...
<python><testing><pytest><python-hypothesis>
2024-01-22 10:45:10
1
1,945
Harry Stuart
77,859,194
3,719,961
Capturing arguments passed to a constructor using class based decorator without breaking inheritance
<p>Running the code below raises the following exception:</p> <pre><code>ERROR! Traceback (most recent call last): File &quot;&lt;string&gt;&quot;, line 22, in &lt;module&gt; TypeError: MyDecorator.__init__() takes 2 positional arguments but 4 were given &gt; </code></pre> <p>When an object derived from class Subcla...
<python><python-3.x><inheritance><python-decorators>
2024-01-22 10:34:52
1
373
epi.log
77,859,076
9,488,023
Creating a colormap in Python with a specific transition between two regions
<p>I am trying to create a colormap in Python for coloring a map of the world. As such, I want there to be a distinct difference in color between ocean and land, and I am trying to create a colormap for this, but I and stuck on how to make the transition between the two work correctly.</p> <p>My code is something like...
<python><plot><colors><colormap>
2024-01-22 10:18:04
1
423
Marcus K.
77,857,999
1,578,364
Debian packaged python does not latest scikit-learn
<p>My python program depends on scikit-learn - when I run this on ubuntu I get an an error</p> <pre><code>sklearn/base.py:299: UserWarning: Trying to unpickle estimator MultinomialNB from version 1.3.0 when using version 1.2.1 </code></pre> <p>I then reinstalled the package with</p> <pre><code>pip3 install scikit-learn...
<python><scikit-learn><raspberry-pi><debian>
2024-01-22 06:31:21
0
327
anish
77,857,733
1,266,109
Unable to get contour when bounding boxes are not overlapping
<p>I have some sprite sheets. In some cases, the bounding boxes of the sprites are overlapping, even though the sprites themselves are not overlapping:</p> <p><a href="https://i.sstatic.net/qabZQ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/qabZQ.png" alt="Overlapping bounding boxes" /></a></p> <p>In ...
<python><opencv><computer-vision><sprite><image-segmentation>
2024-01-22 05:07:13
1
21,085
Rahul Iyer
77,857,652
3,667,693
How to resolve pylance "Series[Unknown]" error for dataframe using applymap
<p>I've been running into the following pylance error.</p> <pre><code>Object of type &quot;Series[Unknown]&quot; is not callable </code></pre> <p>Sample code to recreate error:</p> <pre><code>import pandas as pd df = pd.DataFrame({'col1': ['a', 'b', 'c'], 'col2': ['c', 'd', 'e']}) df.applymap(lambda x: 'c' in x) # &lt;...
<python><pandas><pylance>
2024-01-22 04:39:31
1
405
John Jam
77,857,590
1,900,384
Limited decoration margin in "constrained" layout?
<p>I want to understand the decoration space limits of the <a href="https://matplotlib.org/stable/users/explain/axes/constrainedlayout_guide.html" rel="nofollow noreferrer">&quot;constrained&quot; layout engine</a> of Matplotlib. In my use case, I have to add a lot of decoration (such as different axes ticks and labels...
<python><matplotlib><layout><axis><decoration>
2024-01-22 04:07:40
3
2,201
matheburg
77,857,589
87,240
Avoid jagged edges when filling in quadrilateral using OpenCV
<p>I'm trying to fill in an area identified by a quadrilateral on an image, but keep getting jagged lines after performing the filling (doesn't seem to matter whether I'm filling using an image or just all plain black). I thought it was due to anti-aliasing so am using <code>lineType=cv2.LINE_AA</code> but I can still ...
<python><numpy><opencv><image-processing>
2024-01-22 04:07:32
1
3,165
krasnaya
77,857,466
5,960,363
With Langchain, how can I change the OpenAI API key at runtime?
<h3>Context</h3> <p>I'm working with Langchain Expression Language (LCEL) in Python.</p> <p>I'm using the <code>ChatOpenAI</code> class (<a href="https://github.com/langchain-ai/langchain/blob/master/libs/community/langchain_community/chat_models/openai.py#L150" rel="nofollow noreferrer">source code</a>) within a FastA...
<python><fastapi><openai-api><langchain><py-langchain>
2024-01-22 03:02:39
1
852
FlightPlan
77,857,275
4,580,217
Return Self of different generic
<p>In Python typings, am I able to express something like</p> <pre class="lang-py prettyprint-override"><code>A = TypeVar('A') B = TypeVar('B') class Foo(Generic[A]): def map(self, f: Callable[[A], B]) -&gt; Self[B]: fields = dataclasses.fields(type(self)) # do some transformations... mappe...
<python><python-typing>
2024-01-22 01:42:16
1
872
Aly
77,857,199
14,740,191
comparing sets to multiple sets within a loop
<p>Is it possible to compare a set to multiple sets with a for loop? I am trying to see if there is match when comparing against multiple sets. I want to create a function that will allow any number of sets to compare.</p> <pre><code>ex1 = {'a','b','c'} ex2 = {'a','b','c','d'} ex3 = {'a','b','c','d','e'} list_of_sets...
<python><python-3.x>
2024-01-22 01:08:47
1
441
kjay
77,857,096
5,269,749
How to show the results and confidence interval values together?
<p>I have two <code>10x10</code> matrices. One of them is for main results and the other one is for confidence interval (CI) of the corresponding element in the main results matrix.</p> <p>I am wondering how I can show both of them</p> <p><img src="https://latex.codecogs.com/svg.image?&amp;space;results%5Cpm&amp;space;...
<python><numpy><matplotlib><seaborn>
2024-01-22 00:14:44
1
1,264
Alex
77,857,091
1,914,781
convert string to datetime works on linux but fail on windows
<p>Below code works fine on ubuntu but fail on win10.</p> <pre><code>import datetime def main(): s1 = &quot;Sat Jan 20 08:13:13 CST 2024&quot; dt = datetime.datetime.strptime(s1, '%a %b %d %H:%M:%S %Z %Y') print(dt) main() </code></pre> <p>from ubuntu:</p> <pre><code>2024-01-20 08:13:13 </code></pre> <p>B...
<python>
2024-01-22 00:10:58
0
9,011
lucky1928
77,857,073
11,621,983
Cannot redirect crontab output to file
<p>I am on a raspberry pi 5 model B rev 1.0, and am trying to redirect the contents of this simple python program to a file:</p> <pre class="lang-py prettyprint-override"><code>import time import sys while True: time.sleep(1) sys.stdout.write(&quot;out\n&quot;) sys.stderr.write(&quot;err\n&quot;) </code></...
<python><python-3.x><cron><raspberry-pi>
2024-01-22 00:01:45
1
382
unfestive chicken
77,856,978
2,125,671
How to keep constant the memory used by SQLAlchemy
<p>I have this Python script :</p> <pre><code>from typing import Any, Tuple import sys def find_memory_usage(insertion: bool): from sqlalchemy import create_engine, select, String from sqlalchemy.orm import MappedAsDataclass, DeclarativeBase, declared_attr from sqlalchemy.orm import Mapped, mapped_column ...
<python><memory-management><sqlalchemy>
2024-01-21 23:18:10
1
27,618
Philippe
77,856,969
1,873,897
AzureDefaultCredentials fail with Authorization Code: None
<p>Tried <a href="https://stackoverflow.com/questions/75110869/how-to-check-which-credential-azure-python-sdk-class-defaultazurecredential-is-u">this</a> question. I'm running this code locally in Visual Studio Code, and am logged in using <code>az login</code>. I've also tried <code>aad_credentials = AzureCliCredentia...
<python><microsoft-entra-id><azure-python-sdk>
2024-01-21 23:12:57
1
1,159
MikeF
77,856,952
525,865
Running a script in Google Colab - throws back no results
<p>I have issues running a tiny scraper in Google Colab. While we are able to run the code on Google Colab Notebooks, the real issue is that the clutch-page, we are trying to scrape is using CloudFlare, which can detect Selenium. There is a work-around now (see below)</p> <p>So far so good: with the little code below w...
<python><pandas><web-scraping><beautifulsoup>
2024-01-21 23:06:42
1
1,223
zero
77,856,609
447,860
Avoid circular imports with generic types in python
<p>Often circular imports stemming from type checking can be avoided by skipping runtime imports based on <code>typing.TYPE_CHECKING</code></p> <p>However, it appears that generic types require evaluation at runtime, for example, the follow code does not run in 3.11.</p> <p>Note that this is different from non-generic ...
<python><python-3.x><types><circular-dependency>
2024-01-21 20:54:11
0
1,958
Lucas
77,856,584
959,306
Scikit-Learn's `_openmp_effective_n_threads()` returns 1, causing HistGradientBoostingRegressor to run on only 1 core
<p>the title pretty much says it all. I am troubleshooting why sklearn model is only running on 1 cpu core, when usually it will run on as many cores as I have available. I found behind the scenes it is setting the <code>n_threads</code> attribute with this convenience method from Scikit-Learn: <code>_openmp_effective_...
<python><multithreading><scikit-learn><cpu>
2024-01-21 20:47:41
0
18,324
jeffery_the_wind
77,856,369
1,245,659
Dag error asking for Task Group that is not asked for
<p>I'm experienced in Airflow 1.10.14. I'm now trying to learn Airflow 2, and am having difficulty running DAGs from one to the next. I'm hoping someone can look and tell me what I'm doing wrong.</p> <p><strong>Here's my DAG</strong></p> <pre><code>@dag( &quot;FILE_DB_PRODUCT_TABLES&quot;, schedule_interval='...
<python><airflow><directed-acyclic-graphs>
2024-01-21 19:37:15
1
305
arcee123
77,856,367
525,865
BeautifulSoup - parsing on the clutch.co site and adding the rules and regulations of the robot
<p>I want to use <code>Python</code> with <code>BeautifulSoup</code> to scrape information from the Clutch.co website.</p> <p>I want to collect data from companies that are listed at clutch.co :: lets take for example the it agencies from israel that are visible on clutch.co:</p> <p><a href="https://clutch.co/il/agenc...
<python><pandas><web-scraping><beautifulsoup><python-requests>
2024-01-21 19:36:51
1
1,223
zero
77,856,238
2,847,689
Passing a prompt via python to llama.cpp
<p>I have written the following code:</p> <pre><code>import subprocess import os import mysql.connector from dotenv import load_dotenv def run_llama_cpp(prompt): # Specify the absolute path of the executable and current directory executable_path = 'D:\\Code\\llama_cpp\\w64devkit\\w64devkit.exe' current_di...
<python><llama>
2024-01-21 19:00:05
1
5,261
Carol.Kar
77,856,221
12,167,598
python peewee upsert only dictionary specified fields
<p>I am new to peewee (<code>v3.17</code>) - using with sqlite(<code>v3.40</code>), trying to write a function that updates or inserts a data to my user table, This is the model class</p> <pre class="lang-py prettyprint-override"><code>class MyUser(Model): id = AutoField() user_mail = TextField(unique=True) ...
<python><sqlite><peewee>
2024-01-21 18:55:20
1
1,473
Akshay Chandran
77,856,187
1,020,139
How can I add scopes to `security.HTTPBearer[]` for a route using FastAPI?
<p>How can I add scopes to <code>security.HTTPBearer[]</code> for the <code>GET /v1/health</code> route using FastAPI?</p> <p>I have checked the docs for <code>HTTPBearer</code>, but it doesn't seem to support any way of adding scopes.</p> <p>I would like <code>security.HTTPBearer[]</code> to be equal to e.g. <code>[&q...
<python><fastapi>
2024-01-21 18:50:03
0
14,560
Shuzheng
77,855,843
9,016,861
Python/Bash: comparing local and remote docker images sha256 hashes
<p>The main goal: I have a very size-limited server and I can't afford docker pull of new image version while old layers are on server, so when new image is available, I remove the local one. But I don't want to do it when image wasn't updated as it takes several minutes to pull. I am trying to write a script that will...
<python><bash><docker><docker-pull>
2024-01-21 17:14:11
1
709
Jedi Knight
77,855,805
4,770,853
Multiprocessing in python won't keep log of errors in log file
<p>I've implemented multiprocessing in a data analysis I'm running but sometimes there are errors and instead of having the entire que get killed I wanted them to just be ignored so I implemeneted a try statement. But new errors keep cropping up, is there a more exhaustive list of erros I can include in the except sta...
<python><error-handling><multiprocessing><python-multiprocessing>
2024-01-21 17:03:57
1
584
Angus Campbell
77,855,764
7,225,482
How to send empty arguments in a parametrized pytest test?
<p>I am using Pytest. I have a function with several arguments and I am using a parametrized test to check different combinations of those arguments. But I would like to be able to not have all arguments in all test cases. Is there a way that I can indicate in the tuples where I define the test cases that some argument...
<python><testing><pytest>
2024-01-21 16:55:25
3
746
Alvaro Aguilar
77,855,742
1,145,744
How to convert safetensors model to onnx model?
<p>I want to convert a <code>model.safetensors</code> to ONNX, unfortunately I haven't found enough information about the procedure. The documentation of <code>safetensors</code> package isn't enough and actually is not clear even how to get the original (pytorch in my case) model, since when I try something as</p> <pr...
<python><pytorch><onnx><huggingface><safe-tensors>
2024-01-21 16:47:45
1
12,435
AndreaF
77,855,706
10,200,497
How can I merge two dataframes based on range of dates?
<p>I have two DataFrames: <code>df1</code> and <code>df2</code></p> <pre><code>import pandas as pd df1 = pd.DataFrame( { 'a': ['2024-01-01 04:00:00', '2023-02-02 20:00:00'], 'id':['a_1', 'a_2'] } ) df2 = pd.DataFrame( { 'a': [ '2024-01-01 4:00:00', '2024-01-01 05:00:0...
<python><pandas><dataframe>
2024-01-21 16:37:32
4
2,679
AmirX