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,744,982
7,226,192
How to get the current function name and file name and location (path) in python ? And how to get the calling function data as-well?
<p>I've been searching for some useful code examples on this subject for creating a simple logger for my program.</p> <p>Here are the things I've searched:</p> <ol> <li>Getting the current function info (name, arguments, file name and path)</li> <li>Getting the calling function into (name, file name and path, line numb...
<python><function><parameters><filenames><signature>
2024-07-13 21:04:18
2
506
JamesC
78,744,970
10,749,925
How do i get my Python .env credentials file into Ubuntu EC2?
<p>I have a .env file which my app.py file references, containing my AWS credentials. How do i get this into my AWS Ubuntu EC2 machine?</p> <p>I can't even upload it to GitHub.</p> <p>If there's any security issues with this, whats the simplest workaround strategy you use? Worst case i could hardcode it, but i don't th...
<python><amazon-web-services><ubuntu><amazon-s3><amazon-ec2>
2024-07-13 20:57:12
1
463
chai86
78,744,860
4,611,374
Using pandas.concat along Axis 1 returns a Concatenation along Axis 0
<p>I am trying to horizontally concatenate a pair of data frames with identical indices, but the result is always a vertical concatenation with NaN values inserted into every column.</p> <pre class="lang-py prettyprint-override"><code>dct_l = {'1':'a', '2':'b', '3':'c', '4':'d'} df_l = pd.DataFrame.from_dict(dct_l, ori...
<python><pandas><dataframe><concatenation>
2024-07-13 20:06:21
1
309
RedHand
78,744,758
3,347,814
How do I get Lead Info from Facebook API using Python?
<p>I want to get Leadinfo from my Lead ads using python and the facebook API.</p> <p>I have tried this:</p> <pre><code>import json from facebook_business.api import FacebookAdsApi from facebook_business.adobjects.adaccount import AdAccount from facebook_business.adobjects.leadgenform import LeadgenForm from facebook_bu...
<python><facebook-graph-api><facebook-python-business-sdk>
2024-07-13 19:12:10
1
1,143
user3347814
78,744,671
2,401,856
Creating a local proxy server in python
<p>I have two computers <code>computer 1</code> and <code>computer 2</code> on the same network. I'm trying to make <code>computer 1</code> act as a proxy server so when I send a request from <code>computer 2</code> using its ip address as a proxy, the request will pass through <code>computer 1</code>.</p> <p>After try...
<python><ssl><proxy>
2024-07-13 18:31:33
1
620
user2401856
78,744,539
11,420,295
Understanding sync_to_async method in Django?
<p>I have never worked with asyncio and/or asynchronous methods with django and am having a little difficulty understanding.</p> <p>I am trying to convert a synchronous utility function (create_email_record) into an asynchronous function inside of a form method.</p> <p>I will minimize some code for better understanding...
<python><django><asynchronous><django-forms><python-asyncio>
2024-07-13 17:36:41
0
415
master_j02
78,744,469
11,748,924
Numpy geta mask of false positives from the given two vectors of y_true and y_pred
<p>Given three classes (5,6,7) of two arrays:</p> <pre><code>y_true = np.array([5,6,7,5]) y_pred = np.array([5,7,7,5]) </code></pre> <p>Since second element is false, how to return one-hot encoded array of false positive array like this?</p> <pre><code>y_falsep_class5: [0,0,0,0] y_falsep_class6: [0,0,0,0] y_falsep_clas...
<python><numpy>
2024-07-13 16:58:17
2
1,252
Muhammad Ikhwan Perwira
78,744,437
6,173,214
Create an LSTM Model based on multiple arrays events of random numbers
<p>I need help on create a LSTM Model based on a complex structure of data.</p> <p>I have a multidimensional array. It is an array of over 4000 arrays, each one consists of six numbers (from 1 to 128). I have found a partial predction feature.</p> <p>Suppose I select a group of 70 arrays [0..69], and I want to predict ...
<python><multidimensional-array><lstm>
2024-07-13 16:39:37
1
393
Klode
78,744,422
11,032,590
Issues with Creating a Conda Environment from environment.yml
<p>I'm trying to create an environment from the environment.yml file I found <a href="https://github.com/liusiyan/UQnet/blob/master/environment.yml" rel="nofollow noreferrer">here</a>. I run the command:</p> <pre><code>conda env create -f environment.yml </code></pre> <p>While everything seems fine up to a certain poin...
<python><yaml>
2024-07-13 16:30:17
0
349
KΟŽΟƒΟ„Ξ±Ο‚ ΞšΞΏΟΞ΄Ξ±Ο‚
78,744,397
726,730
Connect a server peer (dynamic ip address) with browser peers javascript
<p>I want to make live ip video calls between a python pyqt5 user and a browser (html5).</p> <p>The javascript code i use for client is:</p> <pre class="lang-py prettyprint-override"><code>var port = 8080 var ip_address = &quot;192.168.1.10&quot; var main_pc = { &quot;name&quot;:&quot;&quot;, &quot;surname&quot...
<python><portforwarding><aiortc>
2024-07-13 16:16:05
1
2,427
Chris P
78,744,276
1,418,326
How to use DataFrameMapper to delete rows with a null value in a specific column?
<p>I am using <code>sklearn-pandas.DataFrameMapper</code> to preprocess my data. I don't want to impute for a specific column. I just want to drop the row if this column is <code>Null</code>. Is there a way to do that?</p>
<python><sklearn-pandas><sklearn2pmml>
2024-07-13 15:34:57
2
1,707
topcan5
78,744,194
818,209
Get aggregates for a dataframe with different combinations
<p>Total <code>pyspark</code> noob here. I have a dataframe similar to this:</p> <pre><code>df = spark.createDataFrame([ Row(ttype='C', amt='12.99', dt='2024/01/01'), Row(ttype='D', amt='21.99', dt='2024/02/15'), Row(ttype='C', amt='16.99', dt='2024/01/21'), ]) </code></pre> <p>I want to find the average <code>am...
<python><apache-spark><pyspark><group-by>
2024-07-13 14:57:53
1
4,414
mithun_daa
78,743,993
4,599,564
File "<frozen runpy>", ModuleNotFoundError: No module named 'pip' o Windows
<p>Original title was: <em>Can't install pip on Windows Server 2019 Standard using Windows embeddable package for Python 3.12.4</em> Edited to: <em>File &quot;&quot;, ModuleNotFoundError: No module named 'pip' o Windows</em> to help finding it.</p> <p>I'm using a Windows Server 2019 Standard with admin rights.</p> <p>I...
<python><windows><pip><windows-server-2019>
2024-07-13 13:43:16
2
1,251
Juan Antonio TubΓ­o
78,743,822
1,422,096
Split a video with ffmpeg, without reencoding, at timestamps given in a txt file
<p>Let's say we have a video <code>input.mp4</code>, and a file <code>split.csv</code> containing:</p> <pre><code>start;end;name 00:00:27.132;00:07:42.422;&quot;Part A.mp4&quot; 00:07:48.400;00:17:17.921;&quot;Part B.mp4&quot; </code></pre> <p>(or I could format the text file in any other format, but the timestamps mus...
<python><ffmpeg><split>
2024-07-13 12:22:26
1
47,388
Basj
78,743,607
13,727,105
Socket can't find AF_UNIX attribute
<p>I'm using an Arch <strong>Linux</strong> machine and trying to run the following code from a Python file.</p> <pre><code>import socket import sys if __name__ == &quot;__main__&quot;: print(sys.platform) server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) </code></pre> <p>and it keeps telling me ...
<python><linux><sockets>
2024-07-13 10:48:03
1
369
Praanto
78,743,539
2,783,767
how to open a pdf to specific page and zoom in python in mac-os
<p>I am trying to open a pdf in mac-os to specific page and zoom programatically. But I am unable to do so. Here is my code, can somebody please let me know what I need to change?</p> <pre><code>import subprocess import os import traceback def open_pdf_with_adobe(pdf_path, page_num, zoom): try: # Ensure th...
<python><macos><pdf><adobe>
2024-07-13 10:25:18
1
394
Granth
78,743,275
3,486,684
How do I pretty print the source code of functions contained in a class instance's attributes?
<p>I would like to use <a href="https://pypi.org/project/rich/" rel="nofollow noreferrer"><code>rich</code></a> to pretty print a Python class like so:</p> <pre class="lang-py prettyprint-override"><code>from dataclasses import dataclass import inspect from typing import Any, Callable from rich import print as rprint i...
<python><rich>
2024-07-13 08:24:49
1
4,654
bzm3r
78,743,265
10,186,547
Websocket from ESP32 to Python to slow
<p>I am working on a project where I have Python server that's connected to an esp32 cam (AI Thinker) via a websocket.</p> <p>The ESP32 cam constantly takes frames and sends them to the server, where they are being streamed to the user.</p> <p>Server code:</p> <pre><code>from fastapi import FastAPI, WebSocket from fast...
<python><c++><websocket><esp32>
2024-07-13 08:19:57
0
312
yardenK
78,743,228
14,194,418
SERVER TIMESTAMP for Realtime Database in Cloud Functions (Python)
<p>To get the SERVER TIMESTAMP for firestore, it is</p> <pre><code>from firebase_admin import firestore ... {&quot;createdAt&quot;: firestore.firestore.SERVER_TIMESTAMP} </code></pre> <p>but how to get the SERVER TIMESTAMP for Realtime Database?</p> <pre><code>from firebase_admin import db @https_fn.on_call() def f1(r...
<python><firebase><firebase-realtime-database><google-cloud-functions>
2024-07-13 07:58:29
0
2,551
Ibrahim Ali
78,743,190
43,118
How to type-hint Python function that takes tuple of type constructors?
<p>I can write a function like</p> <pre><code>async def par_all(fns: tuple[Awaitable[T], Awaitable[U]]) -&gt; tuple[T,U]: ... </code></pre> <p>But how do I extend this to take tuples of any size, without losing type info? (And ideally not <code>*fns</code>, but I'm fine if it needs to be that.)</p> <p>Tried something l...
<python><python-typing>
2024-07-13 07:36:51
0
16,578
xyzzyrz
78,743,031
3,486,684
Read-only class attributes that pass type checking, the modern way (3.11+)
<p>Relevant older questions:</p> <ul> <li><a href="https://stackoverflow.com/questions/76249636/class-properties-in-python-3-11">Class properties in Python 3.11+</a></li> <li><a href="https://stackoverflow.com/questions/76378373/what-are-some-similar-alternatives-to-using-classmethod-and-property-decorators">What are s...
<python><mypy><python-typing><pyright>
2024-07-13 06:14:47
1
4,654
bzm3r
78,742,511
4,119,292
Cumulative calculation across rows?
<p>Suppose I have a function:</p> <pre><code>def f(prev, curr): return prev * 2 + curr </code></pre> <p>(Just an example, could have been anything)</p> <p>And a Polars dataframe:</p> <pre><code>| some_col | other_col | |----------|-----------| | 7 | ... | 3 | | 9 | | 2 | </code></pre> <...
<python><python-polars>
2024-07-12 23:26:11
1
1,031
ldmat
78,742,490
14,649,310
How to stop Ollama model streaming
<p>So I have this class that streams the response form a model:</p> <pre><code>from langchain_community.llms.ollama import Ollama from app.config import ( LLM_MODEL_NAME, MAX_LLM_INPUT_LENGTH, MAX_LLM_INPUT_SENTENCES, LLAMA_BASE_URL, ) from app.utils.text_processing import TextProcessing from app.utils....
<python><websocket><fastapi><langchain><ollama>
2024-07-12 23:11:33
1
4,999
KZiovas
78,742,371
21,540,734
WebDriverWait is getting the title, but javascript, or something is changing the browser's title after the page has loaded
<p>I'm using selenium to rename and sort the medium to a folder based on the title of the page, but the page is still loading content in the background and the title of the page changes after firefox has finished downloading and displaying the content.</p> <p>Whenever I click on an episode of a docuseries that isn't th...
<python><selenium-webdriver><web-scraping><firefox><webdriverwait>
2024-07-12 22:14:18
1
425
phpjunkie
78,742,278
3,367,091
Built-in constants in Python not accessible via __builtins__ using dot syntax?
<p>Reading <a href="https://docs.python.org/3/library/constants.html" rel="nofollow noreferrer">Built-in Constants</a> one can see that for example <code>False</code> is a built-in constant.</p> <p>It is possible to retrieve it using:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; print(getattr(__buil...
<python>
2024-07-12 21:32:47
2
2,890
jensa
78,742,267
11,618,586
Getting hierachy from 2 columns that have parent child relationships
<p>I have a dataframe like so :</p> <pre><code>data = { 'Parent': [None, None, 'A', 'B', 'C', 'I', 'D', 'F', 'G', 'H', 'Z', 'Y', None,None,None,None, 'AA', 'BB', 'CC', 'EE', 'FF', None, None], 'Child': ['A', 'B', 'D', 'D', 'D', 'C', 'E', 'E', '...
<python><pandas><dataframe>
2024-07-12 21:28:43
2
1,264
thentangler
78,741,922
3,486,684
Attaching an "in-group index" to each row of sorted data with Polars
<p>Here's the solution I came up with for the problem:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl import numpy as np max_groups = 5 max_reps = 3 # print out all rows in our table, for the sake of convenience pl.Config.set_tbl_rows(max_groups * max_reps) num_groups = np.random.randint(3, ...
<python><dataframe><window-functions><python-polars>
2024-07-12 19:14:14
2
4,654
bzm3r
78,741,828
874,024
inverted rows,cols in cv.resize
<p>I don't understand why the np.shape passed to cv.resize needs me to swap the tuple elements:</p> <pre class="lang-py prettyprint-override"><code> # Our operations on the frame come here gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY) # Display the resulting frame cv.imshow('frame', gray) (rows, cols) = np.sh...
<python><opencv>
2024-07-12 18:43:08
0
60,094
CapelliC
78,741,811
11,318,930
Using rsync to insert a new subdirectory
<p>I have an existing remote file system like so:</p> <pre><code>β”œβ”€β”€ freshmeat β”‚Β Β  └── prime β”‚Β Β  β”œβ”€β”€ A β”‚Β Β  └── B </code></pre> <p>I want to insert an update from a local directory: freshmeat/prime/c/D So the end result would be:</p> <pre><code>β”œβ”€β”€ freshmeat β”‚Β Β  └── prime β”‚Β Β  β”œβ”€β”€ A β”‚Β Β  └── B | |__...
<python><rsync>
2024-07-12 18:36:29
1
1,287
MikeB2019x
78,741,573
353,337
Matplotlib axes caption with automatic wrapping
<p>In Matplotlib, I have two plots next to each other and I'd like to add a caption to each to them. I'd like the caption auto-wrapped to fit under the respective axes pair.</p> <p>I've tried</p> <pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt fig, axs = plt.subplots(nrows=1, ncols=2) ...
<python><matplotlib>
2024-07-12 17:17:28
1
59,565
Nico SchlΓΆmer
78,741,557
4,701,426
Panda's value_counts() method counting missing values inconsistently
<p>Please consider this simple dataframe:</p> <pre><code>df = pd.DataFrame({'x': [1, 2, 3, 4, 10]}, index = range(5)) df: x 0 1 1 2 2 3 3 4 4 10 </code></pre> <p>Some indices:</p> <pre><code>ff_idx = [1, 2] sd_idx= [3, 4] </code></pre> <p>One way of creating a new column by filtering df based on the abo...
<python><pandas><numpy>
2024-07-12 17:12:40
1
2,151
Saeed
78,741,526
6,023
How to detect that a built-in function has had its name imported over by another module
<h2>Backstory</h2> <p>A confession, I have used <code>import *</code> and felt the pain.</p> <p>Specifically I had <code>from pyspark.sql.functions import *</code> and then attempted to use a builtin function that had been overridden by that liberal import.</p> <p>Looking at how many same named functions exist in both,...
<python><python-import><built-in>
2024-07-12 17:03:54
1
1,340
Don Vince
78,741,441
2,071,807
Structural pattern matching binds already defined variables but treats instance attributes as literals: is this documented anywhere?
<p><a href="https://peps.python.org/pep-0636/#matching-specific-values" rel="nofollow noreferrer">PEP 636 - Structural Pattern Matching</a> discusses how pattern matching binds values to variables declared on the go:</p> <blockquote> <pre class="lang-py prettyprint-override"><code>match command.split(): case [&quot...
<python><match><structural-pattern-matching>
2024-07-12 16:38:03
1
79,775
LondonRob
78,741,393
16,527,170
AttributeError: 'Index' object has no attribute 'strftime'
<p>In DataFrame <code>df</code>, I am having index column as <code>Timestamp</code> in it some values are in format: <code>%Y-%m-%d %H:%M:%S.%f</code> and other values in format: <code>%Y-%m-%d %H:%M:%S</code> due to which I am facing issue in Sorting the index <code>df =df.sort_index()</code> as well and Data Fomat it...
<python><pandas><dataframe>
2024-07-12 16:24:04
1
1,077
Divyank
78,741,359
1,361,752
How to have a pip editable install not install dependencies that are already installed in editable mode
<p>I am often working on multiple python packages with interdependencies defined in pyproject.toml. I want them all installed in editable mode, which seems harder than it should be. What I want to do is to:</p> <ol> <li>Clone each package locally using git</li> <li>Install each package in editable mode with <code>pip i...
<python><pip><pyproject.toml>
2024-07-12 16:14:53
0
4,167
Caleb
78,741,275
2,153,235
Using something like MyDataFrame.print() instead of print(MyDataFrame)?
<p>When I run a script from the Spyder console using <code>runfile</code>, source file lines containing expressions (e.g., <code>&quot;HELLO&quot;</code>) don't print out to the console. I have to explicitly print, e.g., <code>print(&quot;HELLO&quot;)</code>.</p> <p>Is there a way to output the string representation o...
<python><pandas><dataframe>
2024-07-12 15:51:58
2
1,265
user2153235
78,741,237
14,179,793
boto3 copy using SourceClient and access keys results in "AccessDenied"
<p>I am trying to determine if using boto3 copy with a <code>SourceClient</code> will work for my current use case. The <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3/client/copy.html#copy" rel="nofollow noreferrer">documentation</a> mentions the <code>SourceClient</code> paramet...
<python><boto3>
2024-07-12 15:43:16
1
898
Cogito Ergo Sum
78,741,205
11,208,087
Unable to access FastApi app that is running as windows service created with pywin32
<p>i have a basic fastapi <code>main.py</code> as following:</p> <pre><code>from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware app = FastAPI() origins = [&quot;*&quot;] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=[&quot;*&...
<python><python-3.x><windows-services><fastapi><pywin32>
2024-07-12 15:36:59
1
801
Jaydeep
78,741,177
11,037,602
How to read environment variables with spiders deployed to scrapyd?
<h3>TL;DR:</h3> <p><code>load_env()</code> loads the env vars locally, but it doesn't when runs in scrapyd</p> <h3>Details</h3> <p>I have a scrapy project that needs to read some environment variables. These variables are found in the <code>.env</code> file and I use <a href="https://github.com/theskumar/python-dotenv"...
<python><scrapy><scrapyd><python-dotenv><scrapyd-deploy>
2024-07-12 15:30:08
1
2,081
Justcurious
78,741,144
5,983,080
Is there an exponentially weighted moving sum (ewms instead of ewma) function in polars
<p>Also here: <a href="https://github.com/pola-rs/polars/issues/17602" rel="nofollow noreferrer">https://github.com/pola-rs/polars/issues/17602</a></p> <p>In polars ewm_mean, the update is formulated as:</p> <pre><code>y = (1 - alpha) * y + alpha * x </code></pre> <p>I found that sometimes it is useful to use non-decay...
<python><python-polars>
2024-07-12 15:21:31
0
381
Celsius_Xu
78,741,064
7,580,944
weird shape when indexing a jax array
<p>I am experiencing a weird issue when indexing a Jax array using a list. If I place a debugger in the middle of my code, I have the following:</p> <p><a href="https://i.sstatic.net/IiaThfWk.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/IiaThfWk.png" alt="indexing inside the code" /></a></p> <p>This a...
<python><numpy><jax>
2024-07-12 15:01:07
1
359
Chutlhu
78,740,794
4,687,489
xml.etree.ElementTree. Element object has no attribute 'nsmap'
<p>I try to process xml data from the website <a href="https://www.marktstammdatenregister.de/MaStR/Datendownload" rel="nofollow noreferrer">https://www.marktstammdatenregister.de/MaStR/Datendownload</a> I downloaded some datasets for a certain technology for example Netzanschlusspunkte. First step would be to delete c...
<python><xml><filter><merge><grandchild>
2024-07-12 14:08:57
1
359
Mlle Blanche
78,740,790
8,037,521
Efficient way of finding nearest pixel
<p>I have array of floating points Nx2 which is representing the reprojected 3D -&gt; 2D coordinates in a 2D image. I need to find closest (integer) pixel. The naive solution is pretty simple:</p> <pre><code>import numpy as np # Original array of floating-point row and column values points = np.array([ [327.479103...
<python><numpy>
2024-07-12 14:08:25
0
1,277
Valeria
78,740,763
12,633,371
Is it possible to pause a python script that has already started running and check the value of a variable?
<p>Even though the title is self explanatory, I have a python script running for quite a few days and I want to know if there is a way to pause it and check the value of a variable.</p> <p>If I haven't already written code in the script for that purpose before running it, is it possible to check the value of this varia...
<python>
2024-07-12 14:03:25
1
603
exch_cmmnt_memb
78,740,675
8,580,574
How to programmatically generate some documentation from Python dictionary and insert it into .rst file using Sphinx
<p>I am writing a configuration tool that automates the deployment of some monitoring dashboards. Each dashboard has a written description that is available in the tool, and can be found in the deployed dashboard. But we also have some functional documentation that repeats this description so end-users can read it outs...
<python><python-sphinx>
2024-07-12 13:40:33
1
2,542
PEREZje
78,740,522
2,123,706
How to split single element of list and maintain order in list?
<p>I have a list:</p> <pre><code>ll=['the big grey fox','want to chase a squirell', 'because they are friends'] </code></pre> <p>I want to split the 2nd element, <code>ll[1]</code>, into <code>&quot;want to chase&quot;</code> and <code>&quot; a squirell&quot;</code>.</p> <p>I want to end up with:</p> <pre><code>['the b...
<python><list>
2024-07-12 13:08:20
1
3,810
frank
78,740,103
11,357,695
Test multiple functions raise the same error with pytest
<p>Is there a way to put multiple tests under one <code>pytest.raises</code> block? I'd like something similar to the below, but I would want to test that both functions raise the error (whereas I believe only one <code>ValueError</code> would need to be raised for <code>pytest</code> to be satisfied here).</p> <pre><...
<python><pytest>
2024-07-12 11:24:16
0
756
Tim Kirkwood
78,739,761
1,564,070
Visio Container FillForegnd not taking effect
<p>I'm controlling Visio from Python using win32com and with good results overall so far. After a recent update to my code, container header fills are no longer taking effect. The code I'm using:</p> <pre><code>class Container(Shape): Β  v_app: Application Β  def __init__(self, caption: str, items: list, header_fill: s...
<python><visio>
2024-07-12 10:04:43
1
401
WV_Mapper
78,739,630
1,232,660
LXML automatically converts Windows newlines
<p>I am trying to parse an XML string that contains Windows newlines (the CR, LF pair):</p> <pre class="lang-python prettyprint-override"><code>from lxml.etree import XML root = XML('&lt;root&gt;_\r\n_\n_&lt;/root&gt;') print( [ord(char) for char in root.text], ) </code></pre> <p>but the resulting text surprisingl...
<python><lxml>
2024-07-12 09:38:10
0
3,558
Jeyekomon
78,739,619
6,003,901
Best Practice for updating class attribute based on values
<p>I have to read set of csv files which have 5 columns like name, age, address, type and distance. As these column names are string and I want to iterate them in my pandas df. I have created a class that store name with a variable so that if a name change in these files, I just need to update this in one location and ...
<python><class><oop><metaprogramming>
2024-07-12 09:36:15
1
647
abby37
78,739,598
14,301,545
Python - RGBA image non-zero pixels extracting - numpy mask speed up
<p>I need to extract non-zero pixels from RGBA Image. Code below works, but because I need to deal with really huge images, some speed up will be salutary. Getting &quot;f_mask&quot; is the longest task. Is it possible to somehow make things work faster? How to delete rows with all zero values ([0, 0, 0, 0]) faster?</p...
<python><numpy><image>
2024-07-12 09:30:09
2
369
dany
78,739,573
1,335,492
Get object properties without including defaults
<p>This is almost what I want:</p> <pre><code>MyList = list(vars(MyObject).keys()) </code></pre> <p>But it gives me</p> <p><code>['__module__', '__dict__', '__weakref__', '__doc__']</code></p> <p>I want a list without those default properties.What's currently the best way of doing that?</p>
<python>
2024-07-12 09:25:32
0
2,697
david
78,739,565
12,439,683
How to use a constant object like a literal type-hint?
<p>I have a unique and constant object as a special value, which I would like to use for type-hints in different occasions.</p> <p>Lets assume I have a situation like this:</p> <pre class="lang-py prettyprint-override"><code>NO_RESULT = object() def foo() -&gt; Hashable | ???: try: result : Hashable = res() ...
<python><python-typing>
2024-07-12 09:24:05
1
5,101
Daraan
78,739,512
19,472,100
VSCode says 'Cannot access attribute "[attribute]" for class "FunctionType"' for Keras model even though it runs without error
<p>I'm trying to import a saved Keras model from disk:</p> <pre class="lang-py prettyprint-override"><code>from keras._tf_keras.keras.models import load_model model = load_model('data/model.keras') print(model.summary()) </code></pre> <p>(Note: <code>keras</code> is imported like this because everything other solution...
<python><tensorflow><visual-studio-code><keras><pyright>
2024-07-12 09:10:12
0
328
yees_7
78,739,444
815,170
Python pynput not working as expected on osx
<p>I'm trying to catch keystrokes in a python script, but it ONLY catches modifier keys (ctrl, cmd, alt) and not ordinary alphanumerical keys. Running on Mac Sonoma 14.1.1, Python 3.10.6.</p> <pre><code>from pynput.keyboard import Key, Listener def on_press(key): try: print(f'\nYou Entered {key.char}') ...
<python><pynput>
2024-07-12 08:58:09
0
1,336
Hampus Brynolf
78,739,349
710,955
Expand templates to text in wikipedia
<p>I have some custom wikitext(which also includes templates) and need to convert to text. To do this, I use <a href="https://bitbucket.org/wmj/wikiexpand/src/master/" rel="nofollow noreferrer">wikiexpand</a>.</p> <p>In the README file it is indicated:</p> <p><em>Modules written in Lua and executed using {{#invoke:}} a...
<python><wikipedia><wikitext>
2024-07-12 08:38:53
1
5,809
LeMoussel
78,739,294
13,562,186
Tkinter Plot becomes blurry when in a frame
<p><strong>TEST_PLOT.py</strong></p> <pre><code>[![import matplotlib.pyplot as plt import numpy as np from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import tkinter as tk class TestPlot: def __init__(self, master=None): self.master = master self.create_plot() def create_plot(se...
<python><matplotlib><tkinter><tkinter-canvas>
2024-07-12 08:26:34
0
927
Nick
78,739,236
3,909,896
How to configure pypi repo authentication for an Azure DevOps Artifact Feed in databricks.yml for Databricks Asset Bundles?
<p>I have a python_wheel_task in one of my asset bundle jobs which executes the whl file that is being built from my local repository from which I deploy the bundle. This process works fine in itself.</p> <p>However - <strong>I need to add a custom dependency whl file</strong> (another repo, packaged and published to m...
<python><databricks><databricks-asset-bundle>
2024-07-12 08:09:33
1
3,013
Cribber
78,738,969
1,371,481
pip installing packages via external tools
<p>I am trying to install an internal python package via</p> <pre class="lang-bash prettyprint-override"><code>pip install -r requirements.txt </code></pre> <h5>requirements.txt</h5> <pre class="lang-bash prettyprint-override"><code>black numpy scipy interpackage @ git+ssh://git@github.com/..... otherpackage @ git+ssh...
<python><git><pip><github-cli>
2024-07-12 06:49:10
0
1,254
DOOM
78,738,850
205,147
Convert trained and pickled sklearn ColumnTransformer from sklearn 1.1.2 to 1.5.1
<p>I have a Scikit Learn ColumnTransformer containing a number of other transformers (passthrough, a custom transformer and a OneHotEncoder) that has been &quot;trained&quot; (transformer.fit() has been run on data) and stored in a Pickle file, created with Scikit Learn 1.1.2.</p> <p>The OneHotEncoder seems to be the b...
<python><scikit-learn><migration><pickle>
2024-07-12 06:16:43
0
2,229
Hendrik Wiese
78,738,602
679,824
Handling diamond inheritance super class invocations in Python
<p>I have a class setup that looks like below</p> <pre class="lang-py prettyprint-override"><code>from abc import abstractmethod class Player: def __init__(self, name, age): self._player_name = name self._age = age @property def player_name(self): return self._player_name @pr...
<python><python-3.x><oop><diamond-problem>
2024-07-12 04:29:54
1
14,756
Krishnan Mahadevan
78,738,462
3,793,935
Regular expression to extract monetary values from an invoice text
<p>I have a regular expression: <code>\b[-+]?(?:\d{1,3}\.)(?:\d{3}\.)*(?:\d*)</code> (Python) that matches numeric values in strings like this:</p> <pre><code>Amount: 12.234.55222 EUR Some Text 123.222.22 maybe more text 1.245.455.2 22.34565 Could be at the beginning It could be at the end of a string 21.1 221. It coul...
<python><regex>
2024-07-12 03:28:14
2
499
user3793935
78,738,178
816,566
Why does shutil.copytree() and distutils.dir_util.copy_tree() copy the contents of a source directory, not the directory itself?
<p>I'm using On python 3.11 on Windows. I have a directory &quot;comfyui\js&quot; I want to copy the directory &quot;js&quot;, from&quot; comfyui&quot; to a destination &quot;T:\temp&quot; so that the result is &quot;T:\temp\js&quot;.</p> <p>I have found that both<code>distutils.dir_util.copy_tree(&quot;comfyui/js&quot...
<python><windows><path>
2024-07-12 00:59:14
0
1,641
Charlweed
78,738,067
1,806,566
In python, when raising an exception from an except block, is there a way to stop a traceback?
<p>This code:</p> <pre><code>def abc(): raise ValueError() def xyz(): try: raise TypeError() except TypeError: abc() xyz() </code></pre> <p>creates the following traceback:</p> <pre><code>Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 8, in xyz TypeError During ...
<python><try-except>
2024-07-11 23:50:44
1
1,241
user1806566
78,737,996
1,006,183
Set Pydantic BaseModel field type dynamically when instantiating an instance?
<p>With Pydantic is it possible to build a model where the type of one of its fields is set via an argument when creating an instance?</p> <p>For example:</p> <pre class="lang-py prettyprint-override"><code>class Animal(BaseModel): name: str class Dog(Animal): # more custom fields... class Cat(Animal): # ...
<python><fastapi><pydantic><pydantic-v2>
2024-07-11 23:11:04
1
11,485
Matt Sanders
78,737,947
5,615,873
Pyglet 'window.set_location()' method does not work properly
<p>A most weird problem has occurred to me a couple of days ago during my exploration of the pyglet package: While <em>window.set_location(x,y)</em>, window centering on the screen etc. were working fine, at a certain point when I wanted to center a pyglet window on the Windows screen as usual, the window was totallly...
<python><pyglet>
2024-07-11 22:51:16
1
3,537
Apostolos
78,737,927
801,902
Playing an audio file on server from Django
<p>I have a Raspberry Pi that I have hooked up to a door chime sensor, so it plays different sounds as people enter the building. Right now, I just made a short script to play those sounds from whatever is in a directory, and it works fine.</p> <p>I decided that it might be easier to upload sounds and organize their pl...
<python><django><raspberry-pi>
2024-07-11 22:42:37
1
1,452
PoDuck
78,737,908
3,272
Is it possible to get a dict of fields with FieldInfo from the Pydantic Dataclass?
<p>When creating classes by inheriting from BaseModel, I can use the model_fields property to get a dict of field names, and FieldInfo, but how can I do it if I use the Pydantic Dataclass decorator instead of BaseModel?</p> <p>When using <code>BaseModel</code> I can do this:</p> <pre><code>from pydantic import BaseMode...
<python><pydantic><pydantic-v2>
2024-07-11 22:33:14
1
971
Michal
78,737,894
1,806,566
In python, how do I evaluate a statement from a string and get the value if it's an expression?
<p>In python, I would like to take one statement (as a string) and execute it. If the statement is an expression, I'd like to get the value of the expression.</p> <p><code>eval()</code> doesn't handle statements, only expressions. <code>exec()</code> handles statements but doesn't give a way to retrieve a value if the...
<python><eval>
2024-07-11 22:26:42
1
1,241
user1806566
78,737,854
3,358,927
How to unpivot a Pandas dataframe on two ID fields with multiple sets of columns
<p>I have a pandas Dataframe that looks like this:</p> <div class="s-table-container"><table class="s-table"> <thead> <tr> <th>pid</th> <th>fid</th> <th>FirstReasonName</th> <th>FirstReasonValue</th> <th>SecondReasonName</th> <th>SecondReasonValue</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>'x'</td> <td>'a'</td> <t...
<python><pandas><pivot><unpivot>
2024-07-11 22:08:33
1
5,049
ddd
78,737,778
13,989,935
ImportError: DLL load failed while importing _rust: The specified procedure could not be found
<p>I have been trying to run a quick start <strong>flask app</strong> for the first time via <strong>PyCharm / VSCode</strong>. My pip is fully upgraded to the latest version, and I have installed requirements.txt in my venv, but when I try to run it, I see this error.</p> <pre><code>Traceback (most recent call last): ...
<python><flask><requirements.txt><python-cryptography>
2024-07-11 21:37:14
1
715
Abdul Ahad Akram
78,737,729
10,979,307
Make the contents of a table in the header and/or footer RTL using Python docx library
<p>I've got a word document that has an empty 1 by 3 table (or a table with any dimension for that matter) in the header. I want to be able to manipulate the cells of the table using python-docx library. The language of the document is Farsi and naturally all the text in Farsi must start from right to left. Here is how...
<python><ms-word><docx><python-docx>
2024-07-11 21:22:36
1
761
Amirreza A.
78,737,488
14,301,545
Python for loop numpy vectorization
<p>Do you have any suggestions how I can speed up the &quot;f_img_update&quot; function in the code below? I tried adding numba @jit decorator, but without luck. I guess that numpy vectorization might work, but I am not enough educated to make it work on my own :/</p> <p>Code:</p> <pre><code>import numpy as np import t...
<python><numpy><vectorization>
2024-07-11 20:03:45
1
369
dany
78,736,990
2,878,290
How to Looping the list of table contain business key pass to method to execute data process?
<p>We are doing the data validation to pass the source table for SQL view names like <code>TEST_SCH.VIEWNAME</code> and target datalake delta view for <code>schema.deltaview</code> to compare the column row count testing. So that we have to write many scripts to execute.</p> <p>I have common scripts in which I have to ...
<python><apache-spark><pyspark>
2024-07-11 17:39:49
0
382
Developer Rajinikanth
78,736,942
1,423,631
Is python gzip.open not fully implemented on Windows?
<p>At least on my system (Windows 11 Enterprise, Python 3.12.2), using <code>gzip.open(filename, 'wb')</code> to write a compressed file creates an empty .gz file, despite reporting having written data.</p> <p>Minimal example:</p> <pre><code>import os import gzip data = b'Lorem ipsum dolor sit amet, consectetur adipis...
<python><windows><gzip>
2024-07-11 17:27:59
0
483
Oded R.
78,736,839
5,881,326
How to convert variable length datetime column to datetime dtype in pandas dataframe
<p>I have a column of data that is formatted as <code>XXh:XXm:XXs</code> but the hours/minutes/seconds can be different lengths depending on their values</p> <p>Example: <code>123h:23m:1s</code> <code>1h:1m:1s</code> <code>12h:0m:14s</code></p> <p>How can I convert a column to datetime with these variable lengths.</p> ...
<python><pandas>
2024-07-11 17:01:47
0
587
Evan Brittain
78,736,780
8,605,685
What is the difference between installing a module with pip/setup.py vs adding it to PYTHONPATH?
<p>I have a custom Python module I want to use in another project. This module gets deployed to production as well. I have two options:</p> <ol> <li>Add a <code>setup.py</code> and install the module locally with <code>pip</code>.</li> <li>Add the location of the module to the <code>PYTHONPATH</code> environment variab...
<python><pip><python-module><python-packaging>
2024-07-11 16:46:47
1
12,587
Salvatore
78,736,775
13,187,876
Load a Registered Model in Azure ML Studio in an Interactive Notebook
<p>I'm using Azure Machine Learning Studio and I have an <code>sklearn mlflow</code> model stored in my default datastore (blob storage) which I have then registered as a model asset. How can I load this model inside an interactive notebook to perform some quick model inferencing and testing before deploying this as a ...
<python><azure><machine-learning><azure-machine-learning-service><mlflow>
2024-07-11 16:45:51
1
773
Matt_Haythornthwaite
78,736,687
251,420
How do I change the logging level for ibkr's ibapi?
<p>I am trying to get more detailed logging to the console. I have done it before and seen details like</p> <pre><code>4948305328 connState: None -&gt; 0 Connecting to 127.0.0.1:4001 w/ id:1 4948305328 connState: 0 -&gt; 1 </code></pre> <p>I can't seem to get it working now. I have even tried changing the client.py sou...
<python><ib-api>
2024-07-11 16:24:56
1
7,791
joels
78,736,538
9,357,484
Cannot use GPU, CuPy is not installed
<p>I have a GPU enabled machine.</p> <p>O.S: Ubuntu 20.04.6 LTS</p> <p>nvcc version: 12.2</p> <p>Nvidia Driver Version: 535.183.01</p> <p>Pytorch version 2.3.1+cu121</p> <p>spaCy version 3.7.5</p> <p>Python version 3.8.10</p> <p>Pipelines : en_core_web_sm (3.7.1)</p> <p>I am using a virtual environment.</p> <p>I receiv...
<python><pytorch><spacy><nvcc><cupy>
2024-07-11 15:49:51
1
3,446
Encipher
78,736,499
5,842,705
Why does multiple sequence of wildcard characters not work in re.search?
<p>I am trying to use re.search but with multiple wildcard characters and it does not work. Is there something else I have to do? Or is there a better method?</p> <pre><code>import re pattern = '2A-CS-*.GPM.DPR.V*' file = '/home/files/2A-CS-WFF.GPM.DPR.V9-20240130.20240707-S220512-E220609.058829.V07C.HDF5' print(re.sea...
<python><string><matching>
2024-07-11 15:41:06
1
407
Charanjit Pabla
78,736,498
20,122,390
Why can't I call Run from asyncio twice in the same function?
<p>I am using Celery to process background tasks in my application. Sometimes, I need to process asynchronous functions within those tasks, for which I use asyncio. And in this case, I also need to process an asynchronous function in a finally block. So my code is something like this:</p> <pre><code>@celery_app.task(na...
<python><celery><python-asyncio>
2024-07-11 15:40:36
0
988
Diego L
78,736,419
1,420,553
Tensorflow Understanding Conv2D
<p>Beginner using Tensorflow. Started reading the documentation and checking the examples provided in the website: <a href="https://www.tensorflow.org/api_docs/python/tf/keras/layers/Conv2D" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/keras/layers/Conv2D</a> <a href="https://www.tensorflow.o...
<python><tensorflow>
2024-07-11 15:20:22
1
369
gus
78,736,338
7,465,462
"Exception: Power BI report is not embedded" inside Azure Databricks
<p>We are trying to use the <code>powerbiclient</code> package inside an Azure Databricks notebook to get information on reports but we are getting the error <code>Exception: Power BI report is not embedded</code>. The same code works instead if we use it locally on Visual Studio Code.</p> <ul> <li>Azure Databricks clu...
<python><powerbi><databricks><azure-databricks>
2024-07-11 15:05:21
1
9,318
Ric S
78,736,182
865,169
How do I best send Pydantic model objects via put requests?
<p>I am quite new to Pydantic. I have noticed how it is often used in validating input to FastAPI.</p> <p>I have a project where I need to send something to another application's API endpoint and thought I would try structuring my data via a model class that inherits from Pydantic's <code>BaseModel</code>.</p> <p>I try...
<python><python-requests><pydantic>
2024-07-11 14:35:07
2
1,372
Thomas Arildsen
78,736,144
3,618,999
Debug flask docker container with breakpoints
<p>I am building my flask application on ubuntu image,</p> <p>below is snippet of my dockerfile</p> <pre><code>FROM ubuntu:24.04 # Install required packages and Python RUN apt-get update &amp;&amp; \ apt-get install -y python3 python3-pip python3-venv default-libmysqlclient-dev build-essential pkg-config curl &amp...
<python><docker><flask><debugging><containers>
2024-07-11 14:27:58
0
579
ratnesh
78,736,095
562,335
Archtecture/Design pattern for communication between asyncio and non-asyncio context
<p>I am writing a TCP-based client which do both req/rep pattern communication and push/pull pattern communication. I tried to employ <code>asyncio</code> and its transport/protocol structure to handle the low-level transport actions. But the APIs for others to use is not run in asyncio context. So I create the followi...
<python><design-patterns><python-asyncio>
2024-07-11 14:17:21
1
1,241
Holmes Conan
78,735,850
12,760,550
Why one of the label bars have their name omited in the graph displayed on Jupyter Notebook?
<p>I have the multiindex dataframe (example below but not complete) named &quot;pivot_dftable&quot; and the code below displaying the analysis I need for it.</p> <ul> <li><p>I would like to understand why in the graph displayed with the code provided, instead of one of the bar labels in the graph to be named &quot;Re-O...
<python><pandas><matplotlib><multi-index>
2024-07-11 13:31:36
0
619
Paulo Cortez
78,735,769
1,788,771
How to access a translation defined in the base model from views and the admin panel of a child model
<p>In a project I have inherited I have a few polymorphic models based on a common model. Something like:</p> <pre class="lang-py prettyprint-override"><code>from django.db import models from polymorphic.models import PolymorphicManager, PolymorphicModel class Product(PolymorphicModel): name=models.CharField(max_l...
<python><django><django-polymorphic><django-parler>
2024-07-11 13:16:01
1
4,107
kaan_atakan
78,735,697
19,648,465
How to Avoid Using --run-syncdb with python manage.py migrate
<p>I am working on a Django project that I cloned from GitHub. When I try to run python manage.py migrate, it fails and requires me to use --run-syncdb. However, I want to make it so that python manage.py migrate is sufficient without the need for --run-syncdb.</p> <p>I noticed that there is no migrations folder in my ...
<python><django><django-rest-framework><database-migration>
2024-07-11 13:01:15
0
705
coder
78,735,671
2,261,553
Parallel decorator on Numba routine featuring race condition
<p>I have the following routine aiming to calculate in parallel different SVD of random matrices:</p> <pre><code>import numpy as np from numba import jit,prange @jit(nopython=True,parallel=True) def svd_bn(aa,n): res=[] for k in prange(n): u,s,v=np.linalg.svd(aa[k],0) res.append( s ) ...
<python><numpy><numba>
2024-07-11 12:54:34
0
411
Zarathustra
78,735,592
6,930,340
How to compute a column in Polars using np.linspace
<p>Consider the following <code>pl.DataFrame</code>:</p> <pre><code>df = pl.DataFrame( data={ &quot;np_linspace_start&quot;: [0, 0, 0], &quot;np_linspace_stop&quot;: [8, 6, 7], &quot;np_linspace_num&quot;: [5, 4, 4] } ) shape: (3, 3) β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€...
<python><dataframe><python-polars>
2024-07-11 12:40:08
4
5,167
Andi
78,735,399
8,622,404
Handling 'Too Large for Available Bit Count' Error When Reading Part of an MP3 File in Python
<p>I am trying to read a specific part of an MP3 file, but I am encountering an error:</p> <pre><code>[src/libmpg123/layer3.c:INT123_do_layer3():1771] error: part2_3_length (1376) too large for available bit count (760) </code></pre> <p>The audio file can be accessed <em><strong><a href="https://drive.google.com/file/d...
<python><librosa><libsndfile>
2024-07-11 12:00:29
0
356
kingGarfield
78,735,104
2,859,449
Nested partitions of integers
<p>I want to create all nested partitions of an integer - with all possible permutations of numbers and brackets (nests) at all possible positions.</p> <p>For example, for n = 3, I would like to have</p> <pre><code>(3,) (1, 2) (1, 1, 1) (1, (1, 1)) (2, 1) ((1, 1), 1) </code></pre> <p>In general something like</p> <pre>...
<python><nested-lists><integer-partition>
2024-07-11 10:56:13
2
465
Jake B.
78,735,093
275,195
Is it possible to validate a pyrsistent data structure with jsonschema?
<p>I'm toying around with immutable data structures using the pyrsistent library in python. One of the nice things when representing data with generic data structures is the ability to check data with schemas. Here an example of an immutable data structure in pyrsistent:</p> <pre class="lang-py prettyprint-override"><c...
<python><pyrsistent>
2024-07-11 10:53:59
1
2,338
Pascal
78,734,820
10,739,750
How to attach a print format to attachments upon saving the Doctype in ERPNext?
<p>I have created a custom print format in ErpNext from the Quotation Doctype.</p> <p>It gets printed and I can download it as a PDF as well.</p> <p>Now what I want is that whenever I save the Quotation Doctype, the PDF of that print format is named <code>Scope of Work</code> to attach in the attachments of Quotations ...
<python><erpnext><frappe>
2024-07-11 09:56:14
1
1,235
Khayam Khan
78,734,801
2,132,593
Python Pandas monthly yoy% change when current month is partial
<p>I want to calculate yoy% change for month level data, taking into account that the last (current) period is partial.</p> <p>This has already been asked: <a href="https://stackoverflow.com/questions/47842534/resampling-and-calculating-year-over-year-with-partial-data">Resampling and calculating year over year with pa...
<python><pandas>
2024-07-11 09:51:14
1
1,964
Giacomo
78,734,626
4,689,521
Optimizing Parallel Execution of Sequential and Dependent I/O and CPU-bound Tasks in Python
<p>I have a simple processing pipeline that consists of just a couple of steps:</p> <pre><code>def run(): SIZE = 100 values = get &lt;SIZE&gt; entries from DB for v in values: # 1. Update Status for file in DB # 2. Then download file from BLOB storage # 3. Then generate thumbnail fo...
<python><multithreading><asynchronous>
2024-07-11 09:12:52
0
629
M4V3N
78,734,532
73,323
Make a word optional between a negative lookbehind and a target word
<p>This regex <code>(?&lt;!not)\s(hello\W*world)</code> will not match when <code>hello world</code> is preceded by <code>not</code> word.</p> <p>How do I make it not match too when there's a word in between: <code>not a hello world</code>?</p> <p>I'm trying this regex <code>(?&lt;!not)(?:\s+.*)?\s(hello\W*world)</code...
<python><regex>
2024-07-11 08:53:34
2
7,713
kyw
78,734,383
5,197,329
asyncio how to chain coroutines
<p>I have the following test code, where I am trying to chain together different coroutines. The idea is that I want to have one coroutine that downloads data, and as soon as data is downloaded I want to get the data into the second routine which then process the data. The code below works, whenever I skip the process_...
<python><python-3.x><python-asyncio>
2024-07-11 08:23:25
3
546
Tue