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,073,442
1,367,655
Custom return type for class function based on how it was initialized
<p>Is it possible or makes sense to <code>@overload</code> the return type <code>Hashable</code> of a <code>CLASS.function() -&gt; Hashable:</code> based on how the relevant <code>self.obj</code> was initialized?</p> <pre><code>from typing import Hashable, overload class CLASS: obj = None obj_type = Hashable ...
<python><python-typing><pyright>
2024-02-28 09:50:08
0
980
Radio Controlled
78,073,334
2,307,441
Create Mysql Storec Procedure via Python using Mysql Connector
<p>I Am builing a small application. where I Need to create MySQL Stored procedure via python using mysql Connector.</p> <p>I have tried following code. But getting an following error that</p> <blockquote> <p>&quot;Commands out of sync; you can't run this command now.&quot;</p> </blockquote> <p>I Am using MySQL Version...
<python><mysql><mysql-connector><mysql-5.7>
2024-02-28 09:31:02
2
1,075
Roshan
78,073,286
395,857
How can I have the value of a Gradio block be passed to a function's named parameter?
<p>Example:</p> <pre><code>import gradio as gr def dummy(a, b='Hello', c='!'): return '{0} {1} {2}'.format(b, a, c) with gr.Blocks() as demo: txt = gr.Textbox(value=&quot;test&quot;, label=&quot;Query&quot;, lines=1) txt2 = gr.Textbox(value=&quot;test2&quot;, label=&quot;Query2&quot;, lines=1) answer ...
<python><named-parameters><gradio>
2024-02-28 09:23:28
1
84,585
Franck Dernoncourt
78,073,185
1,734,545
TypeError: 'int' object is not iterable" and PCA Assertion Error in Python Clustering Function
<p>I'm working on a Python function (cluster_articles) to perform document clustering and return a dictionary of results. However, I'm encountering the following test errors:</p> <p>TypeError: 'int' object is not iterable (in test_number_of_observations_kmeans10 and possibly test_proper_dict_return) AssertionError: Ass...
<python><cluster-analysis><pickle><pca><doc2vec>
2024-02-28 09:07:31
0
473
Sushant Patekar
78,073,101
23,461,455
Delete all Occurences of a Substring in SQL-Statement in Python
<p>I have a file from a mariadb containing 3GBs of SQL-Statements. Problem is, that my SQLlite DB doesn't support the contained Key-Statements.</p> <p>Is there a way to edit the Strings containing the Statements that cuts out all substrings or statements that contain the word &quot;key&quot;?</p> <p>I tried the followi...
<python><sql><regex><mariadb><key>
2024-02-28 08:53:27
2
1,284
Bending Rodriguez
78,072,628
6,997,665
Pass gradients through min function in PyTorch
<p>I have a variable, say, <code>a</code> which has some gradient associated with it from some operations before. Then I have integers <code>b</code> and <code>c</code> which have no gradients. I want to compute the minimum of <code>a</code>, <code>b</code>, and <code>c</code>. MWE is as given below.</p> <pre><code>imp...
<python><python-3.x><machine-learning><deep-learning><pytorch>
2024-02-28 07:29:56
2
3,502
learner
78,072,506
263,409
Upsert table using PySpark in Azure Databricks
<p>I have a table in a SQL Server database</p> <pre><code>create table person (Name varchar(255), Surname varchar(255)) </code></pre> <p>And I am trying a simple upsert operation with PySpark:</p> <pre><code># Read data from the &quot;person&quot; table person_df = spark.read.jdbc(url=database_url, table=&quot;person&q...
<python><sql-server><pyspark><azure-databricks>
2024-02-28 07:05:03
2
639
fkucuk
78,072,303
20,075,659
Formating CSV to JSON Python (Nested Objects)
<p>I was trying to convert CSV to JSON Objects and I need to decode the nested objects. For example.</p> <pre><code>&quot;row_id&quot;,_emitted_at,_data rid_1,124,&quot;{&quot;&quot;property_id&quot;&quot;:&quot;&quot;xx&quot;&quot;,&quot;&quot;date&quot;&quot;:&quot;&quot;20220221&quot;&quot;,&quot;&quot;active1DayUs...
<python>
2024-02-28 06:20:23
4
396
Anon
78,072,112
1,788,205
How to run python code using Android kotlin code
<p>I am trying to read python code using android kotlin code .This is my python code</p> <pre><code>import json import pandas as pd from ultralytics import YOLO model = YOLO(&quot;file:///android_asset/YoloV8_model.pt&quot;) def detectOCR(imagePath): try: results = model(imagePath) df = pd.DataFram...
<python><android>
2024-02-28 05:29:49
1
331
MARSH
78,072,111
1,530,508
Unexpected `FrozenInstanceError` in unit test when using a frozen exception
<p>I have a unit test that I want to show failing as part of a bug report. It's important not only that the test fail with an error, but that the error message very clearly evidences the underlying bug. I do <strong>NOT</strong> want the test to pass.</p> <p>Here is a minimal example:</p> <pre><code>import unittest im...
<python><exception><immutability><python-unittest><python-attrs>
2024-02-28 05:29:21
1
14,373
ApproachingDarknessFish
78,072,040
1,734,545
Efficient Algorithm to Make Array Strictly Increasing with Segment Modifications
<p>I'm working on a problem where I need to calculate the minimum number of moves required to transform an array into a strictly increasing one. Moves involve selecting a segment of the array and increasing all of its elements by a positive integer.</p> <p>Problem Description:</p> <p>Given an array A of N positive int...
<python><arrays>
2024-02-28 05:04:13
1
473
Sushant Patekar
78,071,815
13,677,363
Design Add and Search Words Data Structure: Leetcode 211
<p>I am currently trying to solve the problem <a href="https://leetcode.com/problems/design-add-and-search-words-data-structure/description/?source=submission-noac" rel="nofollow noreferrer">Add and Search Words Data Structure</a> on leetcode. The question is as follows:</p> <blockquote> <p>Design a data structure that...
<python><dictionary><hashmap><trie>
2024-02-28 03:47:59
2
949
Kanchon Gharami
78,071,606
6,197,439
Why does modifying a Python list of dict in this loop, change dicts parameters after completion?
<p>I have a list of OrderedDict, which have <code>id</code> and <code>content</code> keys. I want to insert new such OrderedDicts in the list, depending on some condition which I need to find for each original item individually - in the below example simulated with <code>special_indices</code> - and therefore I need to...
<python><python-2.7>
2024-02-28 02:28:47
1
5,938
sdbbs
78,071,552
890,803
Writing to s3: expected string or bytes-like object
<p>I am getting the following error from the very last line of my script in AWS Lambda when trying to write a cav file to a bucket:</p> <pre><code>Response { &quot;errorMessage&quot;: &quot;expected string or bytes-like object, got 's3.Bucket'&quot;, &quot;errorType&quot;: &quot;TypeError&quot;, &quot;requestId&q...
<python><amazon-web-services>
2024-02-28 02:07:28
1
1,725
DataGuy
78,071,487
558,639
Python spidev xfer2 clarification
<p>I've not found good answer to the following, and the spidev documentation isn't much help:</p> <p>Assume I have a SPI device where you send two bytes plus a pad byte before reading back a four byte response. Here's what I want to send, and what I expect to receive:</p> <pre><code>byte 0 1 2 3...
<python><spidev>
2024-02-28 01:42:13
1
35,607
fearless_fool
78,071,482
3,609,976
Lists construction in Python Bytecode
<p>This python code:</p> <pre><code>import dis def f(): a=[1,2,3] dis.dis(f) </code></pre> <p>generates this output:</p> <pre><code> 2 0 RESUME 0 3 2 BUILD_LIST 0 4 LOAD_CONST 1 ((1, 2, 3)) 6 LIST_EXTEND ...
<python><bytecode><cpython>
2024-02-28 01:39:44
1
815
onlycparra
78,071,474
604,296
How can I augment class type definition in Python?
<p>I have a 3rd party class with the following code</p> <pre class="lang-py prettyprint-override"><code>class CBlockHeader(ImmutableSerializable): &quot;&quot;&quot;A block header&quot;&quot;&quot; __slots__ = ['nVersion', 'hashPrevBlock', 'hashMerkleRoot', 'nTime', 'nBits', 'nNonce'] def __init__(self, nV...
<python><python-typing>
2024-02-28 01:36:16
0
7,139
M.K. Safi
78,071,393
6,653,602
How to query LanceDB vector DB using Langchain api with filters?
<p>I am trying to use Langchain with LanceDB as vector database. Here is how I instatiate database:</p> <pre><code>db = lancedb.connect(&quot;./data/lancedb&quot;) table = db.create_table(&quot;my_docs&quot;, data=[ {&quot;vector&quot;: embeddings.embed_query(chunks[0].page_content), &quot;text&quot;: chunks[0].pa...
<python><langchain><vector-database>
2024-02-28 00:58:03
0
3,918
Alex T
78,071,316
1,030,287
matplotlib plot 3D scatter plot where one axis is time or date
<p>I'm having problems with plotting 3D data where one of the dimensions is a date. I am wondering how I can solve it because any solution I can come up with looks too complicated for such a common case problem.</p> <p>My solution is to drop the date dimension and replace it with an integer. I'd like to map this intege...
<python><matplotlib><plot>
2024-02-28 00:28:49
1
12,343
s5s
78,071,313
890,803
Copy and files between two different S3 buckets in different accounts
<p>I am trying to copy one file from one S3 bucket in my account to a different S3 bucket in another account of which I have assumed the role for.</p> <p>I am getting the following error:</p> <pre><code>&quot;errorMessage&quot;: &quot;An error occurred (403) when calling the HeadObject operation: Forbidden&quot; </code...
<python><amazon-web-services>
2024-02-28 00:28:00
1
1,725
DataGuy
78,071,185
2,142,728
Building docker python project that uses dbmate
<p>From what I've read, migrations can be run separately from the application (dbmate), or as part of the bootstrap of the application (Flyway in the JVM).</p> <p>I prefer the latter approach, yet most tools in python (and in general) use the former approach.</p> <p>My intention is to build a docker image that once run...
<python><docker><schema-migration>
2024-02-27 23:41:46
0
3,774
caeus
78,071,148
11,098,908
Matplotlib transformation from data coordinates to figure coordinates
<p>The following code came from the <a href="https://www.packtpub.com/en-au/product/matplotlib-30-cookbook-9781789135718?type=print&amp;gad_source=1&amp;gclid=CjwKCAiAlcyuBhBnEiwAOGZ2S5AG1tIdmdDusS18Q4CYS6Cv8c3TLClPdVPEMOz85nEEyw5kpOYxmRoCJLoQAvD_BwE" rel="nofollow noreferrer">Matplotlib 3.0 Cookbook</a></p> <pre><code...
<python><matplotlib>
2024-02-27 23:33:13
0
1,306
Nemo
78,071,104
3,237,438
EasyOCR segfault when used with Decord
<ul> <li>EasyOCR version: 1.7.1</li> <li>Decord version: 0.6.0</li> <li>Python version: 3.11.7</li> </ul> <p>Minimum reproducible example:</p> <pre><code>import decord import easyocr ocr = easyocr.Reader(['en']) </code></pre> <p><code>[1] 1106258 segmentation fault (core dumped) python</code></p> <p><a href="https...
<python><easyocr>
2024-02-27 23:20:45
1
4,856
hkchengrex
78,071,026
1,417,926
wxpython alpha colors overwrite previous drawing
<p>I create a new bitmap on each frame so that everything draws on a new canvas but apparently something else is going on, each frame seems to be drawing on top of the previous, is there something I have to modify in this code:</p> <pre><code>import wx class MyPanel(wx.Window): def __init__(self, parent, *args, **...
<python><wxpython><wxwidgets><repaint><paintevent>
2024-02-27 22:59:59
0
7,569
shuji
78,070,974
4,119,262
Splitting a word at the uppercase without using regex or a function leads to error cannot assign the expression or not enough value to unpack
<p>I am trying to learn python. In this context I need to split a word when encountering an upper case, convert it as a lower case and then insert a &quot;_&quot;.</p> <p>I have seen various quite complex answer <a href="https://stackoverflow.com/questions/63715861/insert-space-if-uppercase-letter-is-preceded-and-follo...
<python><loops><iteration><camelcasing>
2024-02-27 22:45:44
2
447
Elvino Michel
78,070,928
11,627,201
Allow Python to access the page that is displayed on Google Chrome?
<p>I heard the google terms of service does not allow automated scraping for the search results, and the API is pretty slow, so I thought I might try something like</p> <ol> <li>Manually enter a search item</li> <li>Have the Python script get all URLs from the google search page and analyze them, something like</li> </...
<python>
2024-02-27 22:32:13
1
798
qwerty_99
78,070,834
10,969,942
Implementing Rate Limiting in asyncio for Remote Calls with QPS Constraints
<p><strong>Note: The answer to <a href="https://stackoverflow.com/questions/38683243/asyncio-rate-limiting">Asyncio &amp; rate limiting</a> that uses sleep method is not what I want.</strong></p> <p>I'm working with an asynchronous function in Python that performs a remote call, which takes approximately 20 seconds to...
<python><python-asyncio>
2024-02-27 22:10:39
0
1,795
maplemaple
78,070,661
1,491,229
Visualize a vector of booleans as an image grid of symbols with different colors in python
<p>For teaching purposes in statistics and probability, I want to give a visual representation of various probabilities by an image grid with objects or symbols in different colors in a Jupyter notebook.</p> <p>For instance, by the following code an pixelwise random image is created.</p> <pre><code>import numpy as np f...
<python><jupyter-notebook><statistics><visualization><probability>
2024-02-27 21:27:34
1
709
user1491229
78,070,540
1,065,175
Numpy prints a vector of rows, where I expected a vector of vectors
<p>I have a 4x1 vector v, and I reshape it to 2x1x2, so to a vector of vectors, w.</p> <pre><code>v=np.array([[1],[2],[3],[4]]) print(v) w=np.reshape(v,(2,1,2)) print(w) </code></pre> <p>But it prints a vector of rows:</p> <pre><code>[[1] [2] [3] [4]] [[[1 2]] [[3 4]]] </code></pre> <p>I expected something like:<...
<python><numpy>
2024-02-27 20:58:50
0
2,331
ericj
78,070,504
832,560
"Upgrading" an SQLAlchemy object to a derived class
<p>Given these two models:</p> <pre><code>class Game(Base): __tablename__ = 'games' type = Column(String(11)) __mapper_args__ = { 'polymorphic_identity': 'game', 'polymorphic_on': type, } class HostedGame(Game): __tablename__ = 'hosted_games' name = Column(String, ForeignKey...
<python><sqlalchemy>
2024-02-27 20:51:17
0
830
Cerzi
78,070,484
4,119,262
Why is looping over a dictionary (made form a json) leading to an error?
<p>I am trying to learn python. In this context, I get a json, and get a specific value. However, I get the following error:</p> <blockquote> <p>string indices must be integers, not &quot;str&quot;.&quot;</p> </blockquote> <p>for my last line of code:</p> <pre><code>print(dollar[&quot;rate_float&quot;]) </code></pre> <...
<python><loops><dictionary>
2024-02-27 20:46:23
1
447
Elvino Michel
78,070,444
8,652,920
Is there a concise one liner to process and replace values in a dictionary? (using some form of dictionary comprehension)
<p>say you have a class like</p> <pre><code>class Foo: bar = {&quot;hello&quot;: 123, &quot;world&quot;: 456} </code></pre> <p>And I want to define <code>Foo.bar</code> such that for all the keys and values of <code>bar</code>, all even values are replaced with 0.</p> <p>Is there a clean way to do that in one line? T...
<python><dictionary>
2024-02-27 20:35:25
3
4,239
notacorn
78,070,439
1,030,287
matplotlib scatter plot with NaNs and a cmap colour matrix
<p>Hi I have a simple 3D scatter plot - a dataframe <code>bm</code> with columns and index as the <code>x</code> and <code>y</code> axes. When I plot it, I want to add a colour map - also simple and I've done it below.</p> <p>However, in my data <code>bm</code> I have some zeros which I do not want to plot - this is al...
<python><matplotlib><plot>
2024-02-27 20:34:41
2
12,343
s5s
78,070,421
7,422,287
How to get a QFormLayout() next to a GLViewWidget() in a QVBoxLayout()
<p>I am trying to get a QFormLayout() next to a GLViewWidget() in a QVBoxLayout() in QMainWindow() using the below code.</p> <p>However, I struggle to find out how to display both at once, I can only display one at a time.</p> <p>My aim is to have something like this:</p> <p><a href="https://i.sstatic.net/6qSV4.png" re...
<python><python-3.x><qwidget><pyqtgraph><pyqt6>
2024-02-27 20:30:44
0
727
New2coding
78,070,316
11,197,957
Does passing a string from Rust to Python like this cause memory leaks?
<p>I'm currently tinkering with interfacing between <strong>Python and Rust</strong> for a hobby. (Clearly I have too much time on my hands.) The problem I'm working on right now is passing <strong>large integers</strong> between the two languages.</p> <p>Passing large integers from Python to Rust was suprisingly strai...
<python><rust><memory-leaks><ffi>
2024-02-27 20:06:36
0
734
Tom Hosker
78,070,256
376,829
htmx: hx-target-error fails when hx-target defined (django python)
<p>I am using the htmx extension &quot;response-targets&quot; via &quot;hx-ext&quot; in a python django project.</p> <p><strong>The Problem</strong></p> <p>&quot;hx-target-error&quot; will not work when &quot;hx-target&quot; is also defined, but works when it is the only <em>target</em>.</p> <p><strong>Environment</str...
<python><django><htmx>
2024-02-27 19:56:29
1
12,696
David Manpearl
78,070,219
10,976,654
Some minor tick labels do not show on log axis
<p>I'm trying to customize major and minor tick labels on a log y axis where all labels are in <code>%g</code> format.</p> <p>When the minor 2s and 5s are labeled, and both major and minor grid lines are showing and the ticklabels show as expected.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt impor...
<python><python-3.x><matplotlib><logarithm><yticks>
2024-02-27 19:52:29
1
3,476
a11
78,070,176
10,462,461
Python returning 0's instead of value
<p>I'm working on a project where I need to convert SAS code to Python. I've gotten most of the script converted but I'm having an issue with the following SAS snippet:</p> <pre><code>if balloondt_i &lt;= intnx('month',datadt,1,'end') then prinamt = currbal; else do; do i = 1 to dpd_mult; if currbal &gt; 0 ...
<python><pandas><sas>
2024-02-27 19:44:03
1
340
gernworm
78,070,052
22,518,813
How to create an uninstaller for my python app?
<p>I'm currently developing a python application for windows and i want to share it to my friends. To do so, I converted my python files in to an executable using pyinstaller. I then created an installer and an updater which retrieves the files in a github repository, downloads them and unzips them to be used.</p> <p>I...
<python><windows><uninstallation>
2024-02-27 19:19:16
0
314
fastattack
78,069,994
6,458,245
What are user and global installations when in a conda environment?
<p>I am trying to update pip within my conda environment using pip install --upgrade pip. However, I am getting this warning message: &quot;Defaulting to user installation because normal site-packages is not writeable&quot;</p> <p>What does user and global refer to when I am already within a conda environment?</p>
<python><pip><anaconda>
2024-02-27 19:06:25
0
2,356
JobHunter69
78,069,925
1,867,985
Why does comparison between empty ndarrays and empty lists behave differently if done inside an f-string?
<p>I was messing around a bit with empty <code>ndarray</code>s and uncovered some unexpected behavior. Minimal working example:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np print(f&quot;{np.empty(0)} :: {type(np.empty(0))}&quot;) print(f&quot;{[]} :: {type([])}&quot;) print(f&quot;internal ...
<python><numpy><numpy-ndarray><f-string>
2024-02-27 18:53:20
1
325
realityChemist
78,069,777
7,418,125
Exporting Prometheus Alertmanager Alerts to CSV Using Python, Filtering by Specific Timestamps
<p>I'm working with a monitoring platform provisioned on AWS, utilising EKS, and configured with a Prometheus data source and Alertmanager. Currently, alerts triggered by Alertmanager are sent to a Slack channel. I have used Alertmanager API to fetch all the alerts triggered within a specific period of time.</p> <p>Bel...
<python><excel><amazon-web-services><prometheus><prometheus-alertmanager>
2024-02-27 18:27:09
1
504
Emmanuel Spencer Egbuniwe
78,069,591
16,525,263
How to read and execute hql file(hive query) and create pyspark dataframe
<p>I have a <code>.hql</code> file. I need to read and execute the query to create a dataframe from the query result. I have the below code</p> <pre><code>def read_and_exec_hql(hql_file_path): with open(hql_file_path, 'r') as f: hql_query = f.read().strip() queries = [q.strip() for q in hql_query.splitl...
<python><apache-spark><pyspark><hql>
2024-02-27 17:54:00
0
434
user175025
78,069,588
7,128,934
Implications of querying database before lambda_handler
<p>Here is the pseudo-code for what current lambda function looks like;</p> <pre class="lang-py prettyprint-override"><code>import pandas import pymysql def get_db_data(con_): query = &quot;SELECT * FROM mytable&quot; data = pandas.read_sql(query, con_) return data def lambda_handler(event, context): ...
<python><amazon-web-services><aws-lambda>
2024-02-27 17:53:18
1
32,598
d.b
78,069,220
16,759,116
What sorting algorithm is this? ("merge iterator with itself")
<p>As long as the list isn't sorted, keep replacing it with a merge of an iterator with itself. Is that (equivalent to) one of the commonly known sorting algorithms, just implemented weirdly, or is it something new?</p> <pre class="lang-py prettyprint-override"><code>from random import shuffle from heapq import merge f...
<python><algorithm><sorting><merge>
2024-02-27 16:53:39
3
10,901
no comment
78,069,167
4,439,019
Python: Opening specific file with latest timestamp in name
<p>I have set of JSON files in my directory that look like this:</p> <pre><code>P2096_20240221114151310.json QA558_20240223154745500.json QA558_20240223165244591.json </code></pre> <p>what I want to do is pass the string to the left of the underscore as an argument, and then open the json file with the latest timestamp...
<python><string>
2024-02-27 16:45:35
3
3,831
JD2775
78,068,883
2,726,900
Spark session with .master("yarn"): addFile(...) does not upload file to executor nodes
<p>I have a pyspark session (client mode, with <code>.master(&quot;yarn&quot;)</code>). I have a file that I need to upload to each Spark executor's file system.</p> <p>I've uploaded the file to HDFS, created a Spark session (to &quot;/tmp/dummy.txt&quot;), and tried to</p> <p>I'm creating a SparkSession,and call:</p> ...
<python><apache-spark><pyspark>
2024-02-27 15:58:54
0
3,669
Felix
78,068,806
14,230,633
Polars aggregate without a groupby
<p>Is there a way to call <code>.agg()</code> without grouping first? I want to perform standard aggregations but only want one row in the response, rather than separate rows for separate groups.</p> <p>I could do something like</p> <pre><code>df.with_columns(dummy_col=pl.lit(&quot;dummy_col&quot;)).group_by('dummy_col...
<python><dataframe><python-polars>
2024-02-27 15:45:49
2
567
dfried
78,068,464
14,833,503
Error: PyType_GetFlags when trying to use keras package
<p>I am using <code>library(keras)</code> and <code>library(tensorflow)</code> to estimate an LSTM model. When I try to run the code I am getting the following error message:</p> <p>MODULE: Removing module /shared/modulefiles-tools/python/miniconda-3.9 Error: PyType_GetFlags - /usr/lib64/libpython2.7.so.1.0: undefined ...
<python><r><tensorflow><keras>
2024-02-27 14:54:12
0
405
Joe94
78,068,423
14,034,263
When creating Zoom I am getting invalid access token error when my keys are valid
<pre><code>import requests import json API_KEY = 'API KEY' API_SEC = 'SECRET KEY' zoom_api_url = 'https://api.zoom.us/v2/users/me/meetings' meeting_details = { &quot;topic&quot;: &quot;The title of your Zoom meeting&quot;, &quot;type&quot;: 2, &quot;start_time&quot;: &quot;2024-02-27T10:00:00&quot;, ...
<python><django><django-views><zoom-sdk>
2024-02-27 14:46:55
0
359
Vishal Pandey
78,068,207
962,190
How to interrupt a sleeping python process
<p>I tried to write generic timeout-context-manager, and can't get it to work properly:</p> <pre class="lang-py prettyprint-override"><code>import signal import contextlib from threading import Thread from _thread import interrupt_main # 3.10 and up only import time class CustomInterrupt(Exception): SIG = 63 # ...
<python><multithreading><async-await><signals><interrupt>
2024-02-27 14:13:16
0
20,675
Arne
78,068,080
10,927,050
how to handle if root level keys if they are dynamic in pydantic
<pre><code>{ &quot;type&quot;: &quot;thirdparty&quot;, &quot;key&quot;: &quot;postgres&quot;, &quot;host&quot;: &quot;test&quot;, &quot;id&quot;: &quot;88c8fo90&quot; } </code></pre> <p>or</p> <pre><code>{ &quot;type&quot;: &quot;weburl&quot;, &quot;url&quot;: &quot;https://www.googl...
<python><pydantic>
2024-02-27 13:57:06
1
668
Prajna
78,068,060
2,646,505
`importlib.import_module` not finding module in working directory
<p>I would like to import from the current working directory. For example:</p> <pre class="lang-py prettyprint-override"><code>import os import pathlib import tempfile from importlib import import_module with tempfile.TemporaryDirectory() as temp_dir: tmp_dir = pathlib.Path(temp_dir) (tmp_dir / &quot;foo&quot;...
<python><python-importlib>
2024-02-27 13:53:41
1
6,043
Tom de Geus
78,067,992
682,661
reindex and group dataframe using the repeated ids
<p>I have the following dataframe:</p> <pre><code> doc_id term_candidate tfidf 0 1240600489869402113 space 0.057618 1 1240600489869402113 capacity 0.057618 2 1240600489869402113 idea 0.057618 3 1340608455992815617 priority 0.064477 4 1340608455992815617 typical date...
<python><pandas><dataframe>
2024-02-27 13:42:13
1
907
Omnia
78,067,953
8,050,183
How to extract Sign In methods from AuthBlockingEvent dataclass firebase cloud function
<p>I would like to extract the associated sign-in method used, like Google or email/password from the event.</p> <p>Given the Google Documentations here for <a href="https://firebase.google.com/docs/auth/extend-with-blocking-functions?gen=2nd#getting_user_and_context_information" rel="nofollow noreferrer">Getting user ...
<python><firebase-authentication><google-cloud-functions><google-cloud-identity>
2024-02-27 13:35:21
1
1,159
axelmukwena
78,067,735
273,593
statically inspect a python test suite
<p>I have a (unittest-based) test suite for my python project. Here I have my test classes, with my test methods, etc... In (some of my) tests I call a function to initialize the scenarios of the tests. Let's call this function <code>generate_scenario(...)</code>, and it has a bunch of parameters.</p> <p>I was wonderin...
<python><unit-testing><testing><python-unittest>
2024-02-27 12:55:55
1
1,703
Vito De Tullio
78,067,709
11,749,309
How to calculate a rolling statistic in Polars, looking back from the `end_date`?
<p>I would like to calculate a rolling <code>&quot;1m&quot;</code> statistic on a financial data time series. Given that there won't always be an equal number of rows, per month calculation, unless you have exactly enough data to divide into months, which is uncommon.</p> <p>I am trying to assign a column <code>window_...
<python><python-3.x><python-polars><date-arithmetic><rolling-computation>
2024-02-27 12:52:08
1
373
JJ Fantini
78,067,592
1,472,474
Is it possible to dummy/fake types with mypy for problematic imports?
<h2>Motivation:</h2> <p>I have to use external python library (&quot;SDK&quot;) which is just a directory of code (i.e. it's not a package and can't be &quot;installed&quot; in any meaninful way). So the only way to use it is to add it to system path (<code>sys.path</code> in python or <code>PYTHONPATH</code> in shell)...
<python><python-import><python-typing><mypy>
2024-02-27 12:33:12
0
5,587
Jan Spurny
78,067,569
9,189,389
Python - proper logging import to classes
<p>I struggle with proper imports of <code>logging</code> to classes. Generally, I would like to avoid showing debug messages in the console and saving several same messages in a log file. However, when running in J. notebook via imported classes, the second class in sequence starts to show debug messages in the consol...
<python><logging><python-logging>
2024-02-27 12:28:51
0
464
Luckasino
78,067,552
710,955
Error when benchmarking French datasets constituting the MTEB French leaderboard
<p>I want to evaluate some french embeddings models using MTEB Semantic Text Similarity (STS) task. To do this, I took inspiration from this code <a href="https://github.com/embeddings-benchmark/mteb/blob/main/scripts/run_mteb_french.py" rel="nofollow noreferrer">run_mteb_french.py</a></p> <pre><code> import logging ...
<python><huggingface-transformers><embedding>
2024-02-27 12:26:39
1
5,809
LeMoussel
78,067,449
243,467
Unable to forward HTTP to HTTPS with Gunicorn on Heroku
<p>I am running a Python app using Dash library on Heroku and trying to redirect any HTTP request to HTTPS, but I'm unable to get the setting right.</p> <p>In my Proc file I have:</p> <pre><code>web: gunicorn --config=gunicorn.conf.py app:server </code></pre> <p>And my config file:</p> <pre><code>forwarded_allow_ips = ...
<python><heroku><plotly-dash>
2024-02-27 12:10:58
0
659
benbyford
78,067,336
4,186,430
rebin an array in python to have at least N counts in each entry
<p>I have an array as:</p> <pre><code>A = [1,8,2,6,4,8,1,0,1,6,7,3,1,4,9,1,2,1,2,1,1,2] </code></pre> <p>and I'd like to rebin/group it into a smaller size array, which has at least a value of <code>10</code> in each entry, i.e.:</p> <pre><code>A_reb = [[1,8,2],[6,4],[8,1,0,1],[6,7],[3,1,4,9],[1,2,1,2,1,1,2]] A_reb = [...
<python><arrays><bin><group>
2024-02-27 11:48:48
1
641
urgeo
78,067,054
13,757,692
How to always place axis unit in specific tick label position in Matplotlib?
<p>There is a specific way of including units in graphs that I like: <a href="https://i.sstatic.net/541rp.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/541rp.png" alt="Image from wikipedia" /></a></p> <p>The image is from Wikipedia, from <a href="https://de.wikipedia.org/wiki/DIN_461" rel="nofollow nor...
<python><matplotlib>
2024-02-27 11:05:59
2
466
Alex V.
78,067,053
8,792,159
How to configure pyproject.toml for a pip package to enable one Python script to execute another via command line?
<p>I would like to create a pip package where one python script can execute the other script over the command line.</p> <p>Take this as an example:</p> <pre><code>my-package/ └── my-package ├── script.py └── tests.py </code></pre> <p>with <code>script.py</code>:</p> <pre class="lang-py prettyprint-override"><co...
<python><pip><command><pytest><pyproject.toml>
2024-02-27 11:05:54
0
1,317
Johannes Wiesner
78,066,983
7,724,187
Python Struct Assign Bitfield with typesafety
<p>Consider I have the following struct:</p> <pre class="lang-py prettyprint-override"><code>import ctypes class MyStruct(ctypes.BigEndianStructure): # ! These typehints are added so that the IDE recognizes the fields of the Structure field_size1: ctypes.c_uint8 field_size7: ctypes.c_uint8 field_size8:...
<python><ctypes>
2024-02-27 10:55:11
1
621
Adehad
78,066,450
3,809,691
Create a binary pytorch tensor with n% ones
<p>I want to create a binary tensor with 0 and 1s only, but the number of 1s should be n%.</p> <p>I am using this code, but it takes 7+ seconds and has 19926MB of memory.</p> <p>Is there any faster way to do that?</p> <pre><code>import torch import time start_time = time.time() def create_random_binary_tensor(shape, pe...
<python><pytorch><pytorch-geometric>
2024-02-27 09:33:32
1
3,065
Adnan Ali
78,066,329
13,919,925
from okta auth0 how can i increase the azure ad token validity?
<p>I'm using Okta as the identity provider for user management and have integrated Azure AD with Auth0 for authentication. However, when i retrieve user information after authentication using this API of auth0</p> <pre><code>url = 'https://' + AUTH0_DOMAIN + '/api/v2/users/' + user_id </code></pre> <p>I notice that the...
<python><azure-active-directory><auth0><okta>
2024-02-27 09:14:56
1
302
sandeepsinghnegi
78,066,319
2,826,018
VS Code in WSL2: Python extension doesn't find references, definitions or dependencies in code
<p>I am running a Python-Project in WSL2 using Visual Studio Code. The extensions I have installed are:</p> <ul> <li>isort</li> <li>Pylance</li> <li>Python</li> <li>Python Debugger</li> </ul> <p>all of them are specifically installed and enabled on WSL. I open VS-Code by starting a WSL shell, cd-ing to my directory and...
<python><visual-studio-code><windows-subsystem-for-linux>
2024-02-27 09:13:06
1
1,724
binaryBigInt
78,066,260
1,652,219
In python how do you get the "last" directory in a path string?
<p>I am working on a remote file system, where I don't have direct access to the files/directories, so I cannot check if a string represents a file or a directory.</p> <p>I have the following paths I need to handle, where I have to get a hold of the &quot;partition column&quot;:</p> <pre><code>path1 = &quot;/path/to/20...
<python><path><subdirectory>
2024-02-27 09:02:44
5
3,944
Esben Eickhardt
78,066,199
11,926,970
AWS Cost and Usage Report difference from AWS Billing Dashboard
<p>I have an activated AWS service called AWS Cost and Usage Report(CUR), which generates on an <code>Hourly</code> basis.</p> <p>The format of the CUR is in <code>parquet</code> format.</p> <p>I have a Python code that takes the <code>parquet</code> and reads it.</p> <p>The issue is that there is a difference in total...
<python><amazon-web-services><parquet><aws-cost-explorer>
2024-02-27 08:51:17
0
2,700
Not A Robot
78,066,157
3,111,290
ValueError: setting an array element with a sequence in Python numpy array
<p>I'm currently working on a project to build an AI chatbot using Python, and I'm encountering an error that I can't seem to resolve. When attempting to convert my training data into a numpy array, I'm getting the following error:</p> <pre><code>ValueError: setting an array element with a sequence. The requested array...
<python><arrays><numpy><tensorflow><valueerror>
2024-02-27 08:43:28
1
643
ghost21blade
78,065,964
9,394,465
Is it possible to load limited columns with pandas for processing but output with entire columns though
<p>I have been working with pandas to process very huge csv files lately, and the read_csv(..) itself is taking more time than the actual processing. I am not able to figure out if its possible to read only few columns from the csv for the task that I am doing so my read_csv would be faster? My task involve reading two...
<python><pandas>
2024-02-27 08:06:06
1
513
SpaceyBot
78,065,466
15,412,256
Polars groupby map UDF using multiple columns as parameter
<p>I have a numba UDF:</p> <pre class="lang-py prettyprint-override"><code>@numba.jit(nopython=True) def generate_sample_numba(cumulative_dollar_volume: np.ndarray, dollar_tau: Union[int, np.ndarray]) -&gt; np.ndarray: &quot;&quot;&quot; Generate the sample using numba for speed. &quot;&quot;&quot; ...
<python><pandas><numpy><numba><python-polars>
2024-02-27 06:15:38
2
649
Kevin Li
78,065,443
12,314,521
How to track the best metric score during training (Pytroch Lightning)
<p>I'm learning Pytorch Lightning.</p> <p>I want to track loss and performance metric scores of each epoch for saving best model or plot chart or get the highest performance but all I have is the the loss and performance score of a batch in the training_step method like this:</p> <pre><code> class Model(pl.LightningMod...
<python><pytorch><pytorch-lightning>
2024-02-27 06:07:36
0
351
jupyter
78,065,399
3,700,524
Select consecutive elements that satisfy a certain condition as separate arrays
<p>Given an array of values, I want to select multiple sequences of consecutive elements that satisfy a condition. The result should be one array for each sequence of elements.</p> <p>For example I have an array containing both negative and positive numbers. I need to select sequences of negative numbers, with each seq...
<python><arrays><numpy>
2024-02-27 05:52:32
4
3,421
Mohsen_Fatemi
78,065,151
758,982
Provide schema while reading avro files using pyspark
<p>I am trying to read avro files using pyspark. I want to provide my own schema while reading the file. Below is the sample code.</p> <pre><code>json_schema = &quot;&quot;&quot; { &quot;type&quot;: &quot;record&quot;, &quot;name&quot;: &quot;User&quot;, &quot;fields&quot;: [ { &quot;nam...
<python><apache-spark><pyspark><schema><avro>
2024-02-27 04:24:45
2
394
Harbeer Kadian
78,065,114
10,200,497
How can I conditionally change background color and font color of a cell when using Pandas to_excel?
<p>This is my DataFrame:</p> <pre><code>import numpy as np import pandas as pd df = pd.DataFrame( { 'a': [2, 2, 2, -4, np.nan, np.nan, 4, -3, 2, -2, -6], 'b': [2, 2, 2, 4, 4, 4, 4, 3, 2, 2, 6] } ) </code></pre> <p>I want to change background color and font color of cells only for column <code>...
<python><pandas>
2024-02-27 04:12:18
2
2,679
AmirX
78,065,058
2,955,541
Knapsack Problem: Find Top-K Lower Profit Solutions
<p>In the classic 0-1 knapsack problem, I am using the following (dynamic programming) algorithm to construct a &quot;dp table&quot;:</p> <pre><code>def knapsack(weights, values, capacity): n = len(weights) weights = np.concatenate(([0], weights)) # Prepend a zero values = np.concatenate(([0], values)) ...
<python><optimization><dynamic-programming><knapsack-problem>
2024-02-27 03:49:06
1
6,989
slaw
78,065,048
1,938,410
How to use Pillow to set RGB value of a PNG based on a binary mask
<p>I have an PNG image and a black-and-white mask. This post (<a href="https://note.nkmk.me/en/python-pillow-putalpha/" rel="nofollow noreferrer">https://note.nkmk.me/en/python-pillow-putalpha/</a>) demonstrated how to use <code>putalpha()</code> to send the alpha channel of the image so the masked out area becomes tra...
<python><image-processing><python-imaging-library><png>
2024-02-27 03:44:53
1
507
SamTest
78,065,046
12,545,137
How can I find all hex codes for a Unicode character?
<p>I have to find some special characters using a Python regular expression. For example, for the character 'à', I found some hex codes to build a regex pattern:</p> <pre><code>r'\x61\x300|\xe0|\x61\x300' </code></pre> <p>But I am afraid that I may miss some other hex codes. How can I find all possible hex codes for a ...
<python><regex><unicode><escaping><python-re>
2024-02-27 03:44:34
2
584
Dinh Quang Tuan
78,064,799
7,938,796
Python script works locally but not on AWS Lambda Container
<p>I'm trying to run a linear optimization problem using <code>scipy</code> within AWS Lambda. <code>scipy</code> is over the limit to be added as a layer, so I've created a container and deployed to AWS Lambda. I was able to run a script that imports and uses basic parts of <code>scipy</code>, so I know the process wo...
<python><amazon-web-services><docker><aws-lambda>
2024-02-27 02:04:24
0
767
CoolGuyHasChillDay
78,064,721
7,631,480
Why does my AWS Boto3 API request asking to create some Route53 records silently fail?
<p>I have some code that has always just worked. It uses the AWS API to request information about some ECS containers, then queries Route53 to get information about existing records, and then finally makes a Boto3 Route53 call to update a DNS zone to match the ECS information.</p> <p>This code has worked in the past, ...
<python><amazon-web-services><dns><boto3><route53>
2024-02-27 01:35:11
0
23,355
CryptoFool
78,064,599
890,803
copy one file from one S3 bucket to a key within another S3 bucket
<p>I am using boto3 and have two s3 buckets:</p> <pre><code>source s3 bucket: 'final-files' destination s3 bucket: 'exchange-files' prefix for destination s3 bucket: 'timed/0001' key: final_file[-1] #this is assigned earlier and is a file name </code></pre> <p>I need to copy a single file from the source bucket to a fo...
<python><amazon-web-services><amazon-s3>
2024-02-27 00:48:05
1
1,725
DataGuy
78,064,540
9,659,759
Unit testing flask errorhandler
<p>I am trying to unit test my Flask app's <a href="https://flask.palletsprojects.com/en/1.1.x/errorhandling/#registering" rel="nofollow noreferrer">errorhandler</a>, which looks something like this:</p> <pre class="lang-py prettyprint-override"><code> from http.client import INTERNAL_SERVER_ERROR bp = flask.Blueprint...
<python><unit-testing><flask>
2024-02-27 00:20:50
1
883
Jake
78,064,494
5,159,284
Importing file from another directory python
<p><strong>Disclaimer</strong>: I have tried adding my root of the project folder to the path and also followed <a href="https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time">this post</a> but still finding issues.</p> <p>My project structure is:</p> <pre><code>package_name - __init__.py...
<python>
2024-02-27 00:04:01
1
2,635
Prabhjot Singh Rai
78,064,460
2,307,570
Why does `__builtins__` not contain itself?
<p>The following code seems like a good way to get an overview of the builtin objects in Python.<br></p> <pre class="lang-py prettyprint-override"><code>dunder = [] # 8 lower_fun = [] # 41 lower_type = [] # 26 lower_sitebuiltins = [] # 6 upper_exception = [] # 50 upper_warning = [] # 11 upper_other = [] # 10 ...
<python><python-builtins>
2024-02-26 23:50:45
0
1,209
Watchduck
78,064,166
11,618,586
converting http directory listing into a dataframe and access path in each row
<p>I am able to access an http url and retrieve the directory listing. Then i go line by line and check if each url has a <code>.txt</code> extension and accessing it using <code>requests.content</code> and decode the txt file. However I want to be able to filter the listing based on the date. The directory listing is ...
<python><python-3.x><pandas><urllib>
2024-02-26 22:07:46
1
1,264
thentangler
78,064,126
903,521
Read and Write files using Threadpool
<p>I want to read large number of small files (1000s) from AWS S3 and write them as few big partitions (100s) in AWS S3. So, I group the files in a chunks based on their size and read/write the files in threads to parallelize the whole process.</p> <pre><code>Threadpool(10).starmap(read_write, file_dict) def read_writ...
<python><python-3.x>
2024-02-26 21:59:46
0
3,628
syv
78,064,016
746,100
how can i programmatically set a python breakpoint in visual studio code on Macos
<p>That is, in my Python3 code on MacOS, is there some Python command I can put in my code to cause a breakpoint in Visual Studio Code?</p> <p>I believe in Java they use &quot;debugger&quot; for this.</p>
<python><visual-studio-code>
2024-02-26 21:35:40
1
8,387
Doug Null
78,063,706
3,475,298
Pairs of ragged sequences as input for Tensorflow model
<p>I have a model that takes pairs of sequences. The sequences are of variable length.</p> <p>My model does this:</p> <ol> <li>embeds each item of both sequences</li> <li>sums embeddings of all items for each sequence</li> <li>calculates dot product of the sums</li> </ol> <p>This is the minimal code illustrating the id...
<python><tensorflow><ragged-tensors>
2024-02-26 20:32:46
0
743
Maxim Blumental
78,063,667
1,663,462
How to call python function with default values when they are using typer decorated functions
<p>I'm currently migrating some Python functions to be used with the Typer library for a CLI application. Previously, these functions worked well with default parameters, but I'm encountering issues when applying Typer's argument and option decorators, specifically when dealing with default parameter values. I am using...
<python><typer>
2024-02-26 20:24:29
1
34,785
Chris Stryczynski
78,063,556
6,641,693
How to Set a Custom Logger for the Requests Library in Python?
<p>I am trying to set a custom logger for the requests library in Python, but I am having trouble finding the correct way to do it. I have already created a custom logger and configured it with my desired settings, such as the log level, format, and file handler.</p> <p>no matter what i try the requests library default...
<python><logging><python-requests>
2024-02-26 19:57:45
1
1,656
Kaki Master Of Time
78,063,452
4,373,898
How to access index value in `pd.Series` aggregation or mapping?
<p>After a <code>groupby</code> operation, I have a DataFrame with a MultiIndex (say, level names are <code>i1</code>, <code>i2</code>).</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame( { &quot;i1&quot;: list(&quot;abcde&quot;), &quot;i2&quot;: range(10, 20...
<python><pandas><dataframe>
2024-02-26 19:35:16
1
3,169
AlexisBRENON
78,063,406
4,119,262
Why is my function always outputting "invalid" as a result?
<p>I am learning python. In this context, I do an exercise in which I need to perform a series of test on a string. If these checks are met, python should output &quot;Valid&quot;, if not &quot;Invalid&quot;.</p> <p>Here is my code, with the comments describing the goal of each functions:</p> <pre><code>import string ...
<python><function>
2024-02-26 19:24:30
1
447
Elvino Michel
78,063,283
6,779,049
How to use Numpy as Default for Code Generation In Sympy?
<p>I'm digging into SymPy's code generation capabilities and am struggling with a few basic things. Ironically, of all the languages that SymPy supports for code generation, the documentation for python code generation seems to be the most minimal/lacking. I would like to use <code>numpy as np</code> as the default for...
<python><sympy><code-generation>
2024-02-26 18:57:23
1
398
Nick-H
78,063,175
10,425,150
XML to DATAFRAME and back to XML in python
<p>I would to convert XML file into pandas dataframe.</p> <p>Afterwards I would like to convert the dataframe back to exactly the same XML.</p> <p><strong>[First step]</strong>: save the XLM file from string:</p> <pre><code> xml = '''&lt;system&gt; &lt;station id=&quot;1&quot; type=&quot;DeviceName Functional Te...
<python><pandas><xml><dataframe>
2024-02-26 18:35:43
1
1,051
Gооd_Mаn
78,063,035
2,075,630
How to use context managers with callback functions?
<p>How do you correctly use resources, when the resource is expected to be released asynchronously?</p> <p>Motivated by <code>tempfile.TemporaryDirectory</code> emitting a warning, when the temporary directory is cleaned up by the destructor rather than explicitly, and this leading to problems in <code>PYTHONSTARTUP</c...
<python><python-3.x><contextmanager><resource-management>
2024-02-26 18:09:37
0
4,456
kdb
78,062,935
2,148,414
Snowflake ARRAY column as input to Snowpark modeling.decomposition
<p>I have a Snowflake table with an ARRAY column containing custom embeddings (with array size&gt;1000). These arrays are sparse, and I would like to reduce their dimension with SVD (or one of the Snowpark <code>ml.modeling.decomposition</code> methods). A toy example of the dataframe would be:</p> <pre><code>df = sess...
<python><arrays><snowflake-cloud-data-platform><dimensionality-reduction>
2024-02-26 17:50:50
1
394
user2148414
78,062,820
1,014,217
TypeError: 'function' object is not iterable in flask with langchain
<h3>Description</h3> <p>I am creating a REST API with flask and using langchain and AzureOpenAI, however the llm.stream doesnt seam to work correctly based on my code.</p> <p>How can I stream AzureOPENAI responses using flask?</p> <h3>Example Code</h3> <pre class="lang-py prettyprint-override"><code>@app.route('/stream...
<python><flask><langchain>
2024-02-26 17:29:48
1
34,314
Luis Valencia
78,062,685
7,453,074
Issue in iterating over Python dictionaries with lists and sub-dictionaries
<p>I have a data structure I have read from a file which looks like below -</p> <pre><code>data = {&quot;test&quot;:['[{&quot;Day&quot;:&quot;Monday&quot;,&quot;Device&quot;:&quot;Android&quot;,&quot;Data&quot;:[1, 2, 3]}, {&quot;Day&quot;:&quot;Tuesday&quot;,&quot;Device&quot;:&quot;Iphone&quot;,&quot;Data&quot;:[10, ...
<python><dictionary><parsing>
2024-02-26 17:05:05
1
371
Nitron_707