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,873,281
15,587,184
Creating and fixing PDF with margings, and text style in reportlab
<p>I'm having an issue creating a report using ReportLab in Python.</p> <p>I'm using a JSON file from an AWS S3 bucket. Here is a sample of the information:</p> <pre><code>from reportlab.lib.pagesizes import A1 from reportlab.pdfgen import canvas from reportlab.lib.units import cm company_info = [ {'title': '...
<python><pdf><reportlab>
2024-08-15 00:16:24
1
809
R_Student
78,873,223
5,082,048
Draw arrow from data coordinates to AnnotationBBox
<p>I have a figure with two axis, and an annotation box that sits below the top axis. I want an arrow that starts at the data point in the top axis and points to the top-center of the box (currently it points to 0,0, see picture below). How can I do this? <a href="https://i.sstatic.net/wjRKgfUY.png" rel="nofollow noref...
<python><matplotlib>
2024-08-14 23:41:57
1
3,950
Arco Bast
78,873,119
6,595,551
How to prevent ruff formatter from adding a newline after module-level docstring?
<p>I'm using <code>ruff</code> as a replacement to <code>black</code> formatter but I wanna keep the diff at minimum. I'm noticing that it automatically inserts a newline between the module-level docstring and the first import statement.</p> <p>For example, given this code:</p> <pre class="lang-py prettyprint-override"...
<python><python-black><ruff>
2024-08-14 22:41:01
1
1,647
Iman Shafiei
78,873,083
2,774,885
choosing the non-empty group when I have multiple regex matches in a python regex?
<p>I have a regex defined as such, it's two regular expressions separated by an OR - I want to find lines from a text file that match either of these regexes...</p> <pre><code>my_regex = re.compile(r'^\s+V.*CORE.*?: (\S+)|^\s+NP._VDDC_V: (\S+)') # ^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^ # ...
<python><regex>
2024-08-14 22:22:08
2
1,028
ljwobker
78,872,939
22,312,722
Homebrew Python not working after running conda deactivate
<p>I am having so much trouble with what I assume is a conflict between conda and homebrew. When I run my code with the line <code>print(sys.executable)</code>, this is the output:</p> <p><code>/Users/user/opt/anaconda3/bin/python</code></p> <p>Even though my interpreter in VSCode is set to this:</p> <p><code>/opt/home...
<python><conda>
2024-08-14 21:13:11
0
761
simey
78,872,884
8,062,181
Multi-index lookup between 2 dataframes
<p>I have 2 dataframes: one that acts as a lookup dataframe, and another that I insert values into where numerous rows match between them.</p> <p>The lookup dataframe looks like this:</p> <pre><code>data1 = { 'store': ['1', '1', '1', '1', '1', '1'], 'department': ['produce', 'produce', 'produce', 'bakery', 'mea...
<python><pandas><dataframe><indexing>
2024-08-14 20:51:08
1
411
Luxo_Jr
78,872,754
251,589
Onboarding a new codebase to mypy - silencing errors one-by-one
<p>I am currently converting an existing codebase to <code>mypy</code>.</p> <p>There are ~500 type errors. I am not familiar with the code so fixing all of the errors would be time consuming.</p> <p>I would like to:</p> <ol> <li>Run <code>mypy</code></li> <li>For each error listed, edit the code and add a <code># type...
<python><mypy>
2024-08-14 20:03:00
1
27,385
sixtyfootersdude
78,872,343
1,313,890
Efficient Merge Code in Pyspark / Databricks
<p>I have a library built out for handling MERGE statements on Databricks delta tables. The code for these statements is pretty straightforward and for almost every table resembles the following:</p> <pre><code>def execute_call_data_pipeline(self, df_mapped_data: DataFrame, call_data_type: str = 'columns:mapped'): ...
<python><pyspark><databricks><azure-databricks>
2024-08-14 17:52:00
1
547
Shane McGarry
78,872,318
11,106,572
pyinstaller creating a package more than a GB for a simple python script having import pandas, and some operations
<p>When I run pyinstaller for such a simple script <code>sam.py</code> as below, the package size is worth 1.6 GB...How do we justify sharing this big file to someone ? Is it normal ?</p> <pre><code>import pandas as pd d = pd.read_csv(&quot;~/a.csv&quot;) cols = ['a', 'b'] d[cols].to_csv(&quot;~/new.csv&quot;, index =...
<python><pandas><ubuntu><pyinstaller>
2024-08-14 17:46:18
1
318
cryptickey
78,872,300
893,254
How to convert mutiple level Pandas DataFrame column names into single level?
<p>There are other seemingly similar looking questions which already exist on this site, however all of them appear to be related to performing some form of melt operation, rather than a column renaming operation, which is what I ask about here.</p> <p>I have a Pandas DataFrame with multiple columns. The column names a...
<python><pandas><dataframe>
2024-08-14 17:41:54
1
18,579
user2138149
78,872,237
1,251,099
Protobuf (Python): read binary data file and assign the data to repeated object
<p>I have a protobuf file as below.</p> <pre><code>syntax = &quot;proto3&quot;; message Message { repeated bytes data = 1; } </code></pre> <p>This is the Python code.</p> <pre><code>import test_pb2 message = test_pb2.Message() with open(&quot;test.dat&quot;, mode='rb') as file: message.data.extend(file.read()) <...
<python><python-3.x><protocol-buffers>
2024-08-14 17:21:16
1
6,206
user180574
78,872,166
41,060
How do I stream a large BZ2 data file using Python requests stream=True/iter_content()?
<p>I have a large data file at <a href="https://dumps.wikimedia.org/other/pageview_complete/monthly/2024/2024-07/pageviews-202407-user.bz2" rel="nofollow noreferrer">https://dumps.wikimedia.org/other/pageview_complete/monthly/2024/2024-07/pageviews-202407-user.bz2</a> (3.3 GB).</p> <p>I'm trying to stream its contents ...
<python><http><python-requests><http-chunked>
2024-08-14 16:59:43
0
2,860
audiodude
78,872,103
868,574
python - How to get Unicode characters to display as boxes instead of accented letters - "x96\x88" and "x96\x80"
<p>I have a table that is returning the characters &quot;â\x96\x88&quot; and &quot;â\x96\x80&quot;</p> <p>These are displaying as &quot;â&quot; and &quot;â&quot;</p> <p>However, what I need is for them to display as &quot;█&quot; and &quot;▀&quot;.</p> <p>How do I handle this in Python so they display as I wish?</p> <p...
<python><unicode><character-encoding><non-ascii-characters>
2024-08-14 16:44:14
1
447
Lachlan Macnish
78,872,037
6,733,654
role_required decorator for FastAPI route
<p>Disclaimer and sorry words.. It's been quite a long time since I do not ask questions here and also I am a complete novice in FastAPI, so.. please do not judge too strong</p> <p>I am playing with FastAPI authorization and wondering how can I protected my routes from user who are authenticated but do not have permiss...
<python><authentication><fastapi><decorator><rbac>
2024-08-14 16:29:30
2
475
John
78,871,680
1,072,352
In NumPy arrays, is there a syntax to set a value in the last dimension based on the first dimension?
<p>I've Googled and asked ChatGPT and looked through NumPy docs and can't find any way to do this, so thought I'd ask here.</p> <p>Suppose I have a 4-dimensional array -- in this case, of shape (3, 2, 2, 2):</p> <pre><code>a = np.array([ [[[0, 0], [0, 0]], [[0, 0], [0, 0]]], [[[0, 0], [0, 0]], [[0, 0], [0...
<python><arrays><numpy><numpy-ndarray><array-broadcasting>
2024-08-14 15:08:03
1
1,375
crazygringo
78,871,472
2,889,521
CPython: Usage of `tp_finalize` in C-defined static types with no custom `tp_dealloc`
<p><a href="https://peps.python.org/pep-0442/" rel="nofollow noreferrer">PEP 442</a> introduced the <code>tp_finalize</code> callback to Python type definitions (as a one-to-one equivalent of Pythons classes' <code>__del__</code> function), and recommends using this for any non-trivial destruction.</p> <p>The <a href="...
<python><python-3.x><destructor><cpython><python-c-api>
2024-08-14 14:23:40
1
398
mont29
78,871,372
7,713,770
How to generate the confirm password reset view with Django?
<p>I have a Django Rest Framework api app. And I try to generate some functionaly for forgot password. At the moment there is an api call availeble for reset password. And a user gets an email with a reset email link.</p> <p>But the problem I am facing is that if the user triggers the reset email link that this results...
<python><django><django-rest-framework>
2024-08-14 14:01:42
0
3,991
mightycode Newton
78,871,370
3,512,538
pybind11 cross compilation can link against native python executable, can't install cross python
<p>Working on x64 ubuntu22.04 and on ubuntu23.10 with python3.10 and python3.11 on both.</p> <p>I can build my project natively for both python versions, controlling the python version using <code>PYBIND11_PYTHON_VERSION</code> - which then triggers <code>find_package(Python3 ${PYBIND11_PYTHON_VERSION} REQUIRED EXACT C...
<python><linux><cross-compiling><pybind11>
2024-08-14 14:01:32
0
12,897
CIsForCookies
78,871,265
8,605,348
Stripe Python AttributeError: 'coroutine' object has no attribute 'auto_paging_iter'
<p>An example in the Stripe Python library doesn't seem to work. The <a href="https://github.com/stripe/stripe-python/blob/master/README.md#async" rel="nofollow noreferrer">README</a> says:</p> <pre class="lang-py prettyprint-override"><code># .auto_paging_iter() implements both AsyncIterable and Iterable async for c i...
<python><python-3.x><asynchronous><stripe-payments><python-asyncio>
2024-08-14 13:40:17
1
1,294
ardaar
78,871,239
327,074
BleakScanner timeout with asyncio.wait_for when function has returned
<ul> <li>bleak version: 0.22.2</li> <li>Python version: 3.8.18</li> <li>Operating System: Linux</li> <li>BlueZ version (<code>bluetoothctl -v</code>) in case of Linux: 5.64</li> </ul> <h3>Description</h3> <p>I have a BleakScanner with a timeout. The timeout still occured after returning from the <code>asyncio.wait_for<...
<python><bluetooth-lowenergy><python-asyncio><python-bleak>
2024-08-14 13:34:20
1
13,115
icc97
78,871,211
881,712
Continuously iterate through a dict
<p>If we have a <code>dict</code> we can easily iterate through its values:</p> <pre><code>a = {'mon': 10, 'tue': 13, 'wed': 6, 'thu': 24, 'fri': 15} for v in a: print(v) </code></pre> <p>I also have a nested loop like this:</p> <pre><code>while True: # some conditions to break the outer loop for v in a: ...
<python><dictionary>
2024-08-14 13:28:24
3
5,355
Mark
78,871,193
66,191
Alembic (MySQL) - Always wants to drop/create indexes where index contains column that requires a size
<p>I have the following class..</p> <pre><code>class X( Base ): __tablename__ = &quot;X&quot; __table_args__ = ( Index( &quot;index1&quot;, &quot;downloaded&quot;, text( &quot;x_name( 255 )&quot; ) ), ) id: Mapped[ int ] = mapped_column( BIGINT( unsigned = True ), primary_key = Tru...
<python><mysql><sqlalchemy><alembic>
2024-08-14 13:24:27
1
2,975
ScaryAardvark
78,870,853
3,265,791
SQLAlchemy select with arrow ADBC driver
<p>I am trying to use SQLAlchemy queries with the <a href="https://arrow.apache.org/adbc/current/index.html" rel="nofollow noreferrer">ADBC</a> driver.</p> <p>The main issue is that I use a lot of sqlalchemy queries, i.e. <code>query = select(*cols)...</code> and I can't simply mix the two like in the following way, as...
<python><postgresql><sqlalchemy><apache-arrow>
2024-08-14 12:13:54
1
639
MMCM_
78,870,831
9,270,577
Best way to resolve conflicts between application packages
<p>I am developing a package that will be used by 3-party applications that I have no control over whatsoever.</p> <p>I am wondering what is the best way to solve conflicts between packages.</p> <p>For example:</p> <p>Lets say a 3-party app wants to use my package called <code>external-package</code>.</p> <pre><code>├─...
<python><python-3.x><pip>
2024-08-14 12:09:08
1
1,164
rook
78,870,803
5,084,560
DPY-3008: unsupported in-band notification with error number 2396
<p>I run a SQL query with a python script. i use python-oracledb library. same script works for other queries without error. i run query on Toad. there is no problem or error. i check the search engines for error message. i couldn't find a solution.</p> <p>any ideas?</p>
<python><oracle-database><python-oracledb>
2024-08-14 12:02:45
2
305
Atacan
78,870,739
1,930,508
Reuse inheritance tree of one out of multiple classes in Python
<p>I have 2 classes each implementing a specific behavior and using parent classes.</p> <p>Now I have a new class that needs to use either behavior but which one can only be determined during/after construction.</p> <p>That is currently being done by using multiple inheritance. However as the base classes were not writ...
<python><inheritance><overloading><multiple-inheritance><method-resolution-order>
2024-08-14 11:50:20
1
5,927
Flamefire
78,870,698
10,215,301
Is it necessary for torch_dtype when loading a model and the precision for trainable weights to be different? If so, why?
<p>According to <a href="https://github.com/huggingface/peft/issues/341#issuecomment-1884911753" rel="nofollow noreferrer">this comment</a> in the huggingface/peft package, if a model is loaded in fp16, the trainable weights must be cast to fp32. From this comment, I understand that generally, the <code>torch_dtype</co...
<python><pytorch><nlp><huggingface-transformers><large-language-model>
2024-08-14 11:39:28
0
3,723
Carlos Luis Rivera
78,870,533
5,457,202
Issues trying to load saved Keras U-Net model from h5 file
<p>I've been assigned a task in my company to try to hydrate a model that was trained for a previous project, and while I can load it again, I'm failing to try it and I don't know why.</p> <p>The model follows a U-Net architecture, and here's the output of the <code>summary()</code> method after calling <code>load_weig...
<python><tensorflow><keras><deep-learning><unet-neural-network>
2024-08-14 10:52:17
1
436
J. Maria
78,870,532
12,424,131
Python metaclass keyword arguments not getting used by subclass
<p>I am trying to write a metaclass to assist in serialization. The intention of the metaclass was to isolate the production code from the serialization mode (e.g. YAML or JSON) as much as possible. So, things could inherit from the class <code>Serializable</code>, and not have to worry (too much) about whether it was ...
<python><metaclass>
2024-08-14 10:52:13
1
466
Steven Dickinson
78,870,514
4,340,985
How to read a csv into pandas with missing columns in the header?
<p>I have a CSV file from a measurement device, that produces a bunch of values (Temperature, Rain and Wind) and gives some metadata for the device:</p> <pre><code>Station, Hillside ID, 12345 elevation, 54321 units, °C, mm, kph time, temp, prec, wind 2024-08-01 00:00, 18, 0, 5 2024-08-01 01:00, 18, 0, 2 2024-08-01 02:0...
<python><pandas><csv><multi-index>
2024-08-14 10:47:44
3
2,668
JC_CL
78,870,445
864,245
Class inheritance where the children are simple variable-only classes
<p>I am working with some YAML patches. These patches are a similar structure, but contain different values. The values are often difficult to remember, so I want to abstract them away into class instances that I can reference.</p> <p>Here is the approach I have taken so far:</p> <pre class="lang-py prettyprint-overrid...
<python><python-3.x>
2024-08-14 10:32:51
2
1,316
turbonerd
78,870,086
13,942,929
Cython : How can we add default value to fused_type parameter?
<p>I want my function that has a fused_type parameter to take a default value. I already added int as a part of my fused_type. But I keep getting an error.</p> <pre><code>ctypedef fused test_type: double int str MyObject </code></pre> <hr /> <pre><code>def test_point(self, a : test_type = 0): print...
<python><cython><cythonize>
2024-08-14 09:14:28
0
3,779
Punreach Rany
78,870,005
6,450,267
How to input multiple inputs in RunnableWithMessageHistory of LangChain?
<p>I would like to ask about LangChain for LLM in python.</p> <p>I need multiple inputs with chatting history to run the model, so I tried to use RunnableWithMessageHistory but got an error.</p> <blockquote> <p><strong>Error in RootListenersTracer.on_chain_end callback: KeyError('input')</strong></p> <p><strong>{'outpu...
<python><openai-api><langchain>
2024-08-14 08:59:49
0
340
Soonmyun Jang
78,869,764
2,612,235
Local Package Development with Poetry on Ubuntu 24.04?
<p>I'm working on a Python project that uses Poetry for dependency management. Recently, I found a bug in a third-party package, so I cloned its repository to work on it locally. My goal is to integrate this local version of the package into my project, but I've run into some issues.</p> <p>First, I attempted to manual...
<python><ubuntu><pip><python-poetry><pipx>
2024-08-14 08:03:52
1
29,646
nowox
78,869,763
10,855,529
Using starts_with for comparing a string to a list of strings in Polars
<p>Could I do a <code>starts_with</code> check for a string with a list of strings and return <code>True</code> if the string starts with <em>any</em> of the strings in the list.</p> <p>For now, I came up with the following.</p> <pre class="lang-py prettyprint-override"><code>df = pl.DataFrame({ 'a': ['https://abcd...
<python><python-polars>
2024-08-14 08:03:49
1
3,833
apostofes
78,869,587
11,046,379
Get boolean expression from hierarchical Pandas DataFrame
<p>The dataframe is given as :</p> <pre><code>df = pd.DataFrame( { &quot;id&quot;: [1, 2, 3, 4, 5, 6, 7, 8], &quot;parent_id&quot;: [0, 0, 1, 1, 2, 2, 4, 4], &quot;value&quot;: [a&gt;2, b&lt;4, d&gt;5, e&lt;3, h&gt;1, i&gt;10, f&gt;3, g&gt;2], } ) </code></pre> <p>I need get that string...
<python><pandas><dataframe>
2024-08-14 07:14:58
1
1,658
harp1814
78,869,394
11,895,964
Import Errors for Custom Django Apps in XBlock Development on OpenEdX Palm Version
<p>I’m having trouble importing custom Django apps in an Open edX XBlock. Even though the Django application is installed in the Open edX environment, I'm encountering errors.</p> <p>The <code>video_rating</code> custom Django application is installed and working perfectly in this environment.</p> <p><code>onlineofflin...
<python><django><openedx><edx><palm>
2024-08-14 06:17:42
1
414
Neeraj Kumar
78,869,326
11,678,700
Why is it that calling standard sum on a numpy array produces a different result than numpy.sum?
<p>Observe in the following code, creating an numpy array and calling the builtin python <code>sum</code> function produces different results than <code>numpy.sum</code></p> <p>How is numpy's sum function implemented? And why is the result different?</p> <pre><code>test = [.1]*10 test = [np.float64(x) for x in test] te...
<python><numpy><data-science>
2024-08-14 05:55:28
2
328
Liam385
78,869,236
6,101,419
Use Custom Manager to Filter on a Reverse Relation
<p>I have a set of users and a set of assignments each user submits.</p> <pre class="lang-py prettyprint-override"><code>class User(models.Model): name = models.CharField() class Assignment(models.Model): user = models.ForeignKey( &quot;User&quot;, related_name=&quot;assignments&quot; ) status = models...
<python><django>
2024-08-14 05:16:28
1
2,137
Enrico Borba
78,869,092
14,808,637
Visualization of Graphs Data
<p>I need to visualize graphs where each pair of nodes connected by a comma represents an edge, and the numeric value represents the intensity of that edge. For instance, ('A', 'B'): 0.71 means that node A is connected to node B with an edge intensity of 0.71. Now, I need to visualize these graphs in python. Here are t...
<python><python-3.x><matplotlib><graph>
2024-08-14 04:03:44
1
774
Ahmad
78,869,085
2,966,723
Using and changing a variable name for a value in a dict
<p>I've encountered a challenge in doing repeated simulations with a changing parameter value using Python. I'm looking for a clean way to change the parameter value.</p> <p>Reducing it to the simplest case, we can assume the parameter is showing up as the value for some specific keys in a dictionary, <code>D</code>, ...
<python><dictionary>
2024-08-14 04:01:35
1
24,012
Joel
78,868,737
11,233,365
How to relate new SQL table row to an existing row in a related SQL table without creating a duplicate new row
<p>I am trying to create two tables using SQLModel where a parent can have multiple children. The parents and their children will be found and registered to the database individually, so I need to somehow implement the ability to point already existing entries in the parent table to their children as they are found and...
<python><fastapi><sqlmodel>
2024-08-14 00:55:00
1
301
TheEponymousProgrammer
78,868,652
4,718,221
Inheriting from Python dataclass
<p>I started using data classes recently and am having some issues understanding how inheritance works. I can't understand the problem with too many variables being passed on. Am I using the super() method correctly here?</p> <p>Attaching code below:</p> <pre><code>from typing import Optional @dataclass class ZooAnima...
<python><inheritance><python-dataclasses>
2024-08-13 23:52:20
0
604
user4718221
78,868,598
169,252
Friend optimized some python code of mine, what is it really doing?
<p>A friend optimized some code I wrote. I was trying to make sense of it. Using some actual values it boils down to this:</p> <pre><code>from itertools import cycle list = sorted([8, 4, 6, 2]) c = cycle(list) u = [set(next(c) for _ in range(2)) for _ in range(6)] print(u) </code></pre> <p>This code prints <code>[{2,...
<python><cycle>
2024-08-13 23:22:52
0
6,390
unsafe_where_true
78,868,592
20,302,906
Sending different content to clients throug websocket connection
<p>I'm working on an online blackjack game to be implemented with python websockets. Player 1 and 2, both human, will interact with the server through two client instances I'm planning to make with <a href="https://textual.textualize.io" rel="nofollow noreferrer">textual</a> which make it an online terminal based game....
<python><websocket>
2024-08-13 23:17:09
1
367
wavesinaroom
78,868,372
738,811
Mocking a function import with from keyword
<p>There are three files, a file with a test and two simple modules:</p> <p><code>a.py</code>:</p> <pre><code>import b def bar(): b.foo() </code></pre> <p><code>b.py</code>:</p> <pre><code>def foo(): print(&quot;Hello from b.py&quot;) </code></pre> <p><code>test_a.py</code>:</p> <pre><code>from a import bar fr...
<python><unit-testing>
2024-08-13 21:31:59
1
15,721
scdmb
78,868,296
12,820,205
Icons not found by briefcase/android-emulator
<p>I am building an app for android and iOS using beeware. When running the android emulator through briefcase, my icons are not included. I get the warnings:</p> <pre><code>I/python.stdout: WARNING: Can't find icon view_white; falling back to default icon I/python.stdout: WARNING: Can't find icon add_white; falling ba...
<python><android-emulator><beeware>
2024-08-13 20:58:06
1
1,994
rjen
78,868,163
5,013,066
Does Poetry for Python use a nonstandard pyproject.toml? How?
<p>I am considering introducing my organization to Poetry for Python, and I came across this claim:</p> <blockquote> <p>Avoid using the Poetry tool for new projects. Poetry uses non-standard implementations of key features. For example, it does not use the standard format in pyproject.toml files, which may cause compat...
<python><python-poetry><pyproject.toml>
2024-08-13 20:12:08
1
839
Eleanor Holley
78,868,024
2,986,153
How to know when to use map_elements, map_batches, lambda, and struct when using UDFs?
<pre><code>import polars as pl import numpy as np df_sim = pl.DataFrame({ &quot;daily_n&quot;: [1000, 2000, 3000, 4000], &quot;prob&quot;: [.5, .5, .5, .6], &quot;size&quot;: 1 }) df_sim = df_sim.with_columns( pl.struct(&quot;daily_n&quot;, &quot;prob&quot;, &quot;size&quot;) .map_elements(lambda x: ...
<python><dataframe><python-polars>
2024-08-13 19:29:16
2
3,836
Joe
78,867,953
1,592,427
Psycopg hangs on connection
<p>Running the latest (3.2.1) version of th psycopg faced a problem that it hangs on getting connection from the pool to the postgres db. I saw that timeout there is 0.1 so it must raise an error but instead it just got stuck at that point. Are there any way to force it to raise an error if failed to connect?</p> <pre>...
<python><postgresql><sqlalchemy><psycopg2><psycopg3>
2024-08-13 19:05:41
0
414
Andrew
78,867,805
13,562,186
Struggling to get mathematical model to work
<p>I am trying to mimic a mathematical model based on the following model documentation.</p> <p>4.1.1.4 Exposure to Vapour: Evaporation</p> <p><a href="https://www.rivm.nl/bibliotheek/rapporten/2017-0197.pdf" rel="nofollow noreferrer">https://www.rivm.nl/bibliotheek/rapporten/2017-0197.pdf</a></p> <p><a href="https://i...
<python><math><differential-equations>
2024-08-13 18:16:23
1
927
Nick
78,867,587
835,730
Parse WhatsApp message read status
<p>My question is more about html layout and parsing dynamic of content.</p> <p>My task: parse contacts who read my particular message in the Group. I tried to see DOM structure for the DIV block that hold that contacts. But it's dynamic and list 20 items only. So when I scroll down it's updated.</p> <p>So what should ...
<python><c#><html><selenium-webdriver><html-parsing>
2024-08-13 17:22:12
1
393
Jeffrey Rasmussen
78,867,241
19,369,310
Applying function that takes a list as input and a list as output to a pandas dataframe
<p>I have defined the following function:</p> <pre><code>def my_function(inputList): intermediateList = [] outputList = [] S = 0 for x in inputList: S += x y = 6*x intermediateList.append(y) for elt in intermediateList: z = S / elt outputList.append(z) return outputList </code></pre> <p>...
<python><pandas><dataframe><group-by><apply>
2024-08-13 15:54:52
1
449
Apook
78,867,160
3,710,004
PyPDF2 stalling while parsing pdf for unknown reason
<p>I have a script in which I go through and parse a large collection of PDFs. I noticed that when I tried to parse a particular PDF, the script just stalls forever. But it doesn't throw up an error and as far as I can tell, the PDF is not corrupted. I can't tell what the issue is, but I can see that it happens on page...
<python><pypdf>
2024-08-13 15:38:17
1
686
user3710004
78,867,121
2,287,458
Fill several polars columns with a constant value
<p>I am working with the following code...</p> <pre class="lang-py prettyprint-override"><code>import polars as pl df = pl.DataFrame({ 'region': ['GB', 'FR', 'US'], 'qty': [3, 6, -8], 'price': [100, 102, 95], 'tenor': ['1Y', '6M', '2Y'], }) cols_to_set = ['price', 'tenor'] fill_val = '-' df...
<python><python-polars>
2024-08-13 15:30:39
2
3,591
Phil-ZXX
78,866,838
1,812,732
Create filter based on specific column
<p>How do I filter an 2D array based on a value in a column?</p> <p>I tried <code>arr[arr[2] &gt; 5]</code> but it fails</p> <pre><code>&gt;&gt;&gt; arr = np.arange(12).reshape((4,3)) &gt;&gt;&gt; print(arr) [[ 0 1 2] [ 3 4 5] [ 6 7 8] [ 9 10 11]] &gt;&gt;&gt; print(arr[arr[2] &gt; 5]) Traceback (most recent call...
<python><numpy>
2024-08-13 14:24:34
1
11,643
John Henckel
78,866,648
6,439,229
How to get 'underlying' key in shift combinations
<p>In order to implement customisable hotkeys in an application I'm looking for a way to capture and display key presses with modifiers.</p> <p>What I have now is this customised <code>QLineEdit</code>:</p> <pre><code>from PyQt6.QtWidgets import QApplication, QLineEdit from PyQt6.QtGui import QKeyEvent, QKeySequence fr...
<python><pyqt6><qkeyevent>
2024-08-13 13:41:48
0
1,016
mahkitah
78,866,546
436,315
PyInstaller causing a crash, PyCharm works a charm
<p>I have someone else's Python code that I am upgrading from 3.7 to 3.12 before changing database calls to API calls. The Python code is compiled using PyInstaller into an executable to be distributed as required.</p> <p>If I run the PyInstaller command, it compiles fine creating an executable and an &quot;_internal&q...
<python><pycharm><pyinstaller><executable>
2024-08-13 13:20:48
1
1,148
Jim Grant
78,866,437
1,975,199
"unpacking" binary into floating point
<p>I've got a data set that is in binary, and trying to convert it to decimal/float.</p> <p>For now, I am just using Python to get the understanding for now. Typically, I would achieve this in one of two ways. Either using Python's struct, or bit shifting and OR'ing.</p> <p>For instance, I have a two byte array of [67...
<python><bit-manipulation>
2024-08-13 12:57:36
1
432
jgauthier
78,866,416
10,527,135
Serving Static Files with Nginx and Django in Docker
<p>Despite seeing many similar issues in other threads, I've been unable to configure Nginx to serve static files from my Django project.</p> <p>Here are my two static variables in my <code>settings.py</code>:</p> <pre><code>STATIC_URL = '/static/' STATIC_ROOT='/opt/django/portfolio/collectstatic' </code></pre> <p>Here...
<python><django><docker><nginx>
2024-08-13 12:54:22
2
349
fjjones88
78,866,188
9,438,759
CTypes bitfield sets whole byte
<p>I have the following structure:</p> <pre><code>class KeyboardModifiers(Structure): _fields_ = [ ('left_control', c_bool, 1), ('right_control', c_bool, 1), ('left_shift', c_bool, 1), ('right_shift', c_bool, 1), ('left_alt', c_bool, 1), ('right_alt', c_bool, 1), ...
<python><ctypes><bit-fields>
2024-08-13 12:05:07
2
321
Slendi
78,865,964
6,400,277
RS485 communication between C++ and Python, message splitted and receive in multiple reception
<p><strong>Context</strong></p> <p>I am working on a personal project on which I have to connect a Python script (3.7) to a QML application (Qt 5.2, C++17), all running on a Linux RHEL8 distribution.</p> <p><strong>Hardware connections</strong></p> <p>I have two computers with 2 USB ports, and 2 homemade cables with US...
<python><c++><rs485>
2024-08-13 11:21:51
1
635
Mathieu Gauquelin
78,865,932
390,224
Get rotation angle from rotation vector over axis Y/Z
<p>For some of you this could be a really easy question, but I didn't find a solution or was too dumb to understand some of the math papers.</p> <p>I am currently working in Python but that shouldn't matter. What I want is to get the rotation angle of the unit vector representing the rotation, over a specific axis.</p>...
<python><math><vector><rotation>
2024-08-13 11:14:37
0
2,597
Nuker
78,865,667
7,695,845
How to draw a rectangle with one side in matplotlib?
<p>I want to draw a rectangle in matplotlib and I want only the top edge to show. I tried to draw a line on top of the rectangle to make it work, but I was not satisfied with the result. Here's my code:</p> <pre class="lang-python prettyprint-override"><code>import matplotlib.pyplot as plt from matplotlib.axes import A...
<python><matplotlib>
2024-08-13 10:12:58
2
1,420
Shai Avr
78,865,556
3,128,122
Only one FTP query to get directory files and metadata
<p>I'm working on a project that needs solid performance.</p> <p>I need to analyze the contents of an FTP folder (and its sub-folders) with a single FTP request (to avoid making a call per file, which I could do with <code>ftp_host.stat(file_path)</code>).</p> <p>For each folder, I need to retrieve :</p> <ul> <li>The f...
<python><ftp><ftputil>
2024-08-13 09:51:59
1
11,394
Samuel Dauzon
78,865,475
6,300,438
Python on Mac does not recognize venv executable
<p>I recently moved to Macbook to do programming. It has a really weird problem that I don't know where to start debugging. I already perform an exhautive search on Google but can't find a solution.</p> <p>Basically, I try to create a virtual environment <code>env</code> with<code>python3.10</code>, activate it and exp...
<python><macos>
2024-08-13 09:35:00
2
599
Luan Pham
78,865,470
11,046,379
Recursively traverse Pandas Dataframe
<p>There is Pandas dataframe</p> <pre><code> id parent_id result 1 0 True 2 0 False 3 1 True 4 1 False 5 2 True 6 2 False 7 4 True 8 4 True </code></pre> <p>How to recursively traverse t...
<python><pandas>
2024-08-13 09:34:09
2
1,658
harp1814
78,865,284
8,510,149
PySpark optimization mindset - loop over groups with joins and union
<p>I'm looping over groups in a PySpark dataframe and do one filter operation, several joins (depending on depth of group) and one union operation on each group. The individual groups are quite small, in my real-world use cases number of rows for each group ranges from 3-20. I have around 1500 groups to loop thru and i...
<python><pyspark><optimization><databricks>
2024-08-13 08:56:35
1
1,255
Henri
78,865,258
1,617,563
How to pass an untyped dictionary assigned to a variable to a method that expects a TypedDict without mypy complaining?
<p>I would like to pass a dictionary to a method <code>foo</code> that expects a <code>TypedDict</code> without explicitly mentioning the type. When I pass the dictionary directly to the method, everything is good. However, when I assign the dictionary to a variable <code>configs</code> first, mypy complains about inco...
<python><python-typing><mypy>
2024-08-13 08:50:15
2
2,313
aleneum
78,865,145
6,212,999
ltrace doesn't work for Python compiled with --enable-shared
<p>When I build Python 3.12.4 with <a href="https://docs.python.org/3/using/configure.html#cmdoption-enable-shared" rel="nofollow noreferrer">--enable-shared</a> option:</p> <blockquote> <p>Enable building a shared Python library: libpython (default is no).</p> </blockquote> <p>the only output I get from ltrace is:</p>...
<python><gcc><linker><shared-libraries><ltrace>
2024-08-13 08:19:00
1
405
Marcin Barczyński
78,865,114
6,597,296
Using Twisted to implement implicit FTPS server
<p>I am writing an FTP server using the Python framework Twisted. Twisted has its own plain FTP implementation - but it doesn't support FTPS. I've noticed that most clients connect and immediately issue an <code>AUTH TLS</code> command, requesting an encrypted FTPS connection. If the server responds that this command i...
<python><ftp><twisted><ftps>
2024-08-13 08:09:48
1
578
bontchev
78,865,047
6,234,139
KeyError when filtering time series on basis of datetimeindex in pandas
<p>I am trying to filter a time series on the basis of a datetimeindex in pandas, but get a KeyError. The example below for instance yields the error KeyError: '2021'. What causes this?</p> <pre><code>import pandas as pd data = {'date':['2021-11-1', '2021-12-1', '2022-01-1', '2022-02-1'], 'value':['hello', 'bon...
<python><pandas>
2024-08-13 07:51:51
0
701
koteletje
78,864,992
4,934,344
Quick search list of tuples
<p>I have a very long list of tuples, about 4000 entries. Data is not sorted. This is not the full code. It is a simplified example. Just looking for a way to speed this up if possible.</p> <pre><code>arr = [['863', '0.31', '0.00', '0.69'], ['621', '1.00', '0.00', '0.00'], ['834', '1.00', '0.00', '0.00']] </code></pre>...
<python><numpy><performance><loops>
2024-08-13 07:37:23
2
611
Rankinstudio
78,864,333
1,940,534
How do I use presence_of_element_located to click a checkbox
<p>I want to use a piece of code like this:</p> <pre><code>elementspan = WebDriverWait(driver, 10).until(EC.presence_of_element_located((&quot;xpath&quot;, '//span[text()=&quot;&quot; and @class=&quot;cb-i&quot;]'))) </code></pre> <p>the trick is the html I am presented is below I want to click the checkbox below,just ...
<python><selenium-webdriver><xpath><chrome-web-driver>
2024-08-13 03:58:55
1
1,217
robm
78,863,941
2,449,857
Parsing XML with lxml without unescaping characters
<p>Is there a way to read XML from a string with <code>lxml</code>, without converting escaped characters (<code>&amp;apos;</code> for <code>'</code>, <code>&amp;quot;</code> for <code>&quot;</code>, etc) back to their original form?</p> <p>For example,</p> <pre class="lang-py prettyprint-override"><code>from lxml impo...
<python><lxml>
2024-08-12 23:53:17
0
3,489
Jack Deeth
78,863,925
8,251,318
mock.patch object extending into non-decorated methods?
<p>I have the following code:</p> <pre><code>def get_mocked_contract_event(): event = {#stuff} return event @pytest.fixture(scope=&quot;function&quot;) def context(): yield #works as expected @mock.patch(&quot;ticketfactory.TicketFactory&quot;, autospec = True) def test_success_ticket(mock_ticket_factory...
<python><unit-testing><pytest>
2024-08-12 23:40:49
0
877
Matthew
78,863,704
15,231,102
Why will my python file run via a terminal command but not when I run the same command inside of a function in my Flutter macos app?
<p>I want to execute python code in my Flutter macos app to run a YOLO object detection model.</p> <p>I am using the <a href="https://pub.dev/packages?q=process_run" rel="nofollow noreferrer">https://pub.dev/packages?q=process_run</a> package to execute shell commands. The package works and will run a python file with ...
<python><flutter><pytorch><torch><yolo>
2024-08-12 21:47:11
1
597
greenzebra
78,863,647
695,984
Define default arguments using a dict
<p>I have an unusual situation where a dict of keyword-type argument defaults, <code>the_defaults</code>, is created before a function <code>my_function</code> is defined:</p> <pre><code>the_defaults = {'kwarg_a': 1, 'kwarg_b': 2} def my_function(my_args = the_defaults): print(my_args['kwarg_a']) print(my_args['kwa...
<python><function><dynamic>
2024-08-12 21:23:28
1
1,044
Christian Chapman
78,863,622
24,191,255
Extracting a curve and identifying coordinates from an image using OpenCV
<p>Currently I am particularly interested in pacing strategy optimization in different sports. As part of these kind of processes, I have to define certain courses concerning distance and changes in altitude along the course. I thought I could make this process easier by extracting the data I need from downloaded schem...
<python><opencv><image-processing><computer-vision><plot-parsing>
2024-08-12 21:14:20
2
606
Márton Horváth
78,863,608
1,786,016
Django 5 update_or_create reverse one to one field
<p>On Django 4.x</p> <p>Code is working as expected</p> <pre><code>from django.db import models class Project(models.Model): rough_data = models.OneToOneField( &quot;Data&quot;, related_name=&quot;rough_project&quot;, on_delete=models.SET_NULL, null=True, blank=True, ) ...
<python><django><django-models>
2024-08-12 21:09:14
1
7,822
Arti
78,863,540
3,949,008
Force PyArrow table write to ignore NULL type and use original schema type for a column
<p>I have this piece of code that appends two parts of the same data to a PyArrow table. The second write fails because the column gets assigned <code>null</code> type. I understand why it is doing that. Is there a way to force it to use the type in the table's schema, and not use the inferred one from the data in seco...
<python><pandas><pyarrow>
2024-08-12 20:45:38
1
10,535
Gopala
78,863,539
1,940,534
Python selenium webdriver.chrome issue
<p>I have a code using these libraries</p> <pre><code>from arcgis.gis import GIS from arcgis.geometry import Point, Polyline, Polygon import datetime import os from selenium import webdriver from selenium.webdriver.chrome.service import Service as ChromeService from selenium.webdriver.common.keys import Keys from webdr...
<python><selenium-webdriver><selenium-chromedriver>
2024-08-12 20:45:28
1
1,217
robm
78,863,526
6,622,697
Loading package from disk in Pycharm
<p>I am trying to load a package in Pycharm that I have on disk.</p> <p>Everythings works if I do this outside of Pycharm in a venv</p> <pre><code>pip install -e python/createInput </code></pre> <p>But using Pycharm's Install Package from Disk</p> <p><a href="https://i.sstatic.net/cKuzu1gY.png" rel="nofollow noreferrer...
<python><pip><pycharm>
2024-08-12 20:40:51
1
1,348
Peter Kronenberg
78,863,462
4,710,409
How to retrive ChoiceField value from a form?
<p>I want to get the selected choice from a <strong>ChoiceField</strong> in a view. When I submit the form, I process it in a view:</p> <p>views.py</p> <pre><code>def myFormSubmitView(request): ... if form.is_valid(): print(&quot;valid form&quot;) post = Post() post.title = ...
<python><django><forms><modelform>
2024-08-12 20:20:35
2
575
Mohammed Baashar
78,863,444
14,250,641
Efficiently fetch sequences for sliding window (large dataset)
<p>The dataset I have stored are just coordinates of DNA sequence.</p> <p>df:</p> <pre><code>chr start stop label chr1 9000 9100 1 chr1 8803 8903 1 chr1 8903 9000 0 </code></pre> <p>My goal is to expand the original dataset by creating a sliding window around each coordinate to ...
<python><pandas><dataframe><bigdata><bioinformatics>
2024-08-12 20:13:36
1
514
youtube
78,863,326
2,071,807
Structural pattern matching for checking if a list contains an element
<p>Boto3 lists buckets unhelpfully like this:</p> <pre class="lang-py prettyprint-override"><code>{'Buckets': [{'CreationDate': datetime.datetime(1, 1, 1, 0, 0, tzinfo=tzlocal()), 'Name': 'foo'}, {'CreationDate': datetime.datetime(1, 1, 1, 0, 0, tzinfo=tzlocal()), 'Name': 'bar'}...
<python><pattern-matching>
2024-08-12 19:33:31
1
79,775
LondonRob
78,863,319
12,694,438
ValueError: Namespace Atspi not available
<p>I'm trying to use pyatspi.</p> <p>I installed pygobject with <code>conda install conda-forge::pygobject</code>.</p> <p>Then I ran both <code>sudo apt-get install python3-at-spi</code> and <code>sudo apt-get -y install python3-pyatspi</code>, just in case.</p> <p>I'm using a conda environment, so I added a symlink t...
<python><pygobject>
2024-08-12 19:31:51
1
944
splaytreez
78,863,131
2,687,427
Why does the inclusion of an inner function that uses a local variable change order of locals
<p>The following prints <code>{'a': 'a', 'b': 'b'}</code>:</p> <pre class="lang-py prettyprint-override"><code>def foo(a: str = &quot;a&quot;, b: str = &quot;b&quot;) -&gt; None: print(locals()) foo() # Prints {'a': 'a', 'b': 'b'} </code></pre> <p>Which I'd expect as <code>locals</code> in Python 3.7+ <a href="htt...
<python><lambda><local-variables>
2024-08-12 18:32:35
0
3,472
Nelson Yeung
78,863,093
6,197,439
PyQt5 dynamically expand widget to two columns in QGridLayout?
<p>The example below, which I've modified from the answer in <a href="https://stackoverflow.com/questions/59429678/pyqt5-widget-in-grid-expansion">Pyqt5 widget in grid expansion</a>, starts like this:</p> <p><a href="https://i.sstatic.net/Kn61JhnG.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Kn61JhnG....
<python><pyqt5><qgridlayout>
2024-08-12 18:16:41
1
5,938
sdbbs
78,862,861
2,287,458
Expand/Unnest Polars struct into rows, not into columns
<p>I have this DataFrame</p> <pre class="lang-py prettyprint-override"><code>import polars as pl df = pl.DataFrame({ 'as_of': ['2024-08-01', '2024-08-02', '2024-08-03', '2024-08-04'], 'quantity': [{'A': 10, 'B': 5}, {'A': 11, 'B': 7}, {'A': 9, 'B': 4, 'C': -3}, {'A': 15, 'B': 3, 'C': -14, '...
<python><dataframe><python-polars><unpivot><unnest>
2024-08-12 17:17:30
2
3,591
Phil-ZXX
78,862,781
2,676,598
Improving low-light image capture using OpenCV
<p>We are using the following Python script combined with OpenCV to record video of salmon migration in order to estimate total fish passage,</p> <pre><code>import cv2 import numpy as np import time import datetime import pathlib import imutils import os import shutil import socket szPlacename = 'Yukon River' iCapture...
<python><opencv><webcam><video-capture><light>
2024-08-12 16:55:11
0
2,174
portsample
78,862,691
3,241,486
`mlflow.transformers.log_model()` does not finish
<h3>Problem</h3> <p>I want to use <code>mlflow.transformers.log_model()</code> to log a finetuned huggingface model.</p> <p><strong>However, when the <code>mlflow.transformers.log_model</code> method is running, it simply does not finish - runs forever - throws no errors.</strong></p> <p>I suspect my configuration is n...
<python><nlp><huggingface-transformers><mlflow><mlops>
2024-08-12 16:27:32
1
2,533
chamaoskurumi
78,862,684
6,778,374
Regular expression for letters within a Unicode range?
<p>I'm using the <code>re</code> module in Python. Let's say I want to find all Arabic letters in a string. Essentially I want to combine <code>\w</code> with <code>[\u0600-\u06FF]</code>.</p> <p>Is there a way of doing this? Specify both a character range and a class, where both must match?</p> <p>If not possible with...
<python><regex>
2024-08-12 16:26:25
2
675
NeatNit
78,862,640
20,898,396
Async wrapper - Pylance doesn't recognize that the function is now awaitable
<p>For convenience, I created a wrapper to run blocking code in a separate thread.</p> <pre class="lang-py prettyprint-override"><code>from functools import wraps import time import asyncio def async_wrapper(func): @wraps(func) async def wrapper(*args, **kwargs): print(&quot;wrapper&quot;) retu...
<python><python-asyncio><python-typing><pyright>
2024-08-12 16:15:06
1
927
BPDev
78,862,578
16,725,431
Pip breaks with AttributeError
<p>I am trying to install pillow, however this is what happened:</p> <pre><code>&gt; pip3 install pillow Traceback (most recent call last): File &quot;C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\runpy.py&quot;, line 197, in _run_module_as_main return _run_code(code, main_globals, None, File &quot;C...
<python><python-3.x><pip>
2024-08-12 15:56:28
0
444
Electron X
78,862,530
7,124,155
Why do I get error when importing Python module in Databricks?
<p>I'm trying to import a module using Python files in Databricks, but it's not a notebook and not Spark. Python version 3.10.12.</p> <p>In the Databricks workspace (Git repo, not user workspace), I define this in testmodule.py:</p> <pre><code>def sum_numbers(a, b): return a + b class Circle: def __init__(self...
<python><pyspark><module><databricks>
2024-08-12 15:44:55
0
1,329
Chuck
78,862,512
4,381,589
use xcom shared variable as key in BigQueryInsertJobOperator configuration
<p>I am having a case where I want to share a string to a BigQueryInsertJobOperator and use it as a key to take a given configuration. I try to do it as is:</p> <p>Inside dag definition I am using PythonOperator to push a variable to xcom:</p> <pre><code>def capture_mode(**context): trigger = context[&quot;dag_run&...
<python><google-bigquery><airflow><airflow-xcom>
2024-08-12 15:37:56
1
427
saadoune
78,862,511
810,815
Sums Package Failing to Tokenize in Python
<p>I am using the following code to summarize my text in Python. The code is being run in Jupyter Notebook. I have already install sumy using pip command.</p> <pre><code>pip install sumy nltk python -m nltk.downloader punkt </code></pre> <pre><code>from sumy.parsers.plaintext import PlaintextParser from sumy.nlp.tokeni...
<python><machine-learning>
2024-08-12 15:37:15
2
9,764
john doe
78,862,484
6,145,729
Remove Leading/Trialing spaces from header row in Excel using Python
<p>I'm using pandas to read an XLSB file into a data frame before using 'to_sql't to push it to my SQLite Database. Engine is using pyxlsb and not an issue.</p> <p>My issue is that my XLSB column headers (row 1) have a mixture of spaces before and after the column name. This means that the database also captures the er...
<python><pandas><dataframe><sqlite>
2024-08-12 15:31:34
1
575
Lee Murray
78,862,471
160,245
Extend TypedDict to save/retrieve as JSON to/from file
<p>I want to have simple data structure, and save it to disk as JSON, and later take the JSON and put back into the data structure.</p> <p>This is the error I get:</p> <blockquote> <p>AttributeError: 'dict' object has no attribute 'saveToFile'</p> </blockquote> <p>with the code below:</p> <pre><code>import json from ty...
<python><typeddict>
2024-08-12 15:27:46
2
18,467
NealWalters