QuestionId
int64
74.8M
79.8M
UserId
int64
56
29.4M
QuestionTitle
stringlengths
15
150
QuestionBody
stringlengths
40
40.3k
Tags
stringlengths
8
101
CreationDate
stringdate
2022-12-10 09:42:47
2025-11-01 19:08:18
AnswerCount
int64
0
44
UserExpertiseLevel
int64
301
888k
UserDisplayName
stringlengths
3
30
⌀
77,431,873
16,707,518
Averaging values in another dataframe prior to a date in first dataframe
<p>This I admit is pretty specific example. I have a two dataframes: the first has a date and group:</p> <pre><code>Date Group 06/11/2023 A 05/11/2023 B 04/11/2023 A 03/11/2023 A 02/11/2023 B </code></pre> <p>The second has dates, groups and values:</p> <pre><code>Date ...
<python><pandas>
2023-11-06 14:26:47
3
341
Richard Dixon
77,431,536
3,595,907
Zenoh subscriber not picking up payload
<p>Win 10 x64, Python 3.10</p> <p>I'm working from <a href="https://zenoh.io/docs/getting-started/first-app/" rel="nofollow noreferrer">Your first Zenoh app</a></p> <p>The publisher code,</p> <pre><code># z_sensor.py import zenoh, random, time random.seed() def read_temp(): return random.randint(15, 30) if __na...
<python><zenoh>
2023-11-06 13:44:31
1
3,687
DrBwts
77,431,491
11,189,280
TypeError: path should be path-like or io.BytesIO, not <class 'shiny.reactive._reactives.Value'>
<p>I am creating a simple shiny app for a dog breed classifier. The user would be able to upload a picture of a dog, and then have the shiny app display the predicted breed.</p> <p>A simplified version of the app code is as follows:</p> <pre><code>from shiny import App, Inputs, Outputs, Session, reactive, render, ui im...
<python><py-shiny>
2023-11-06 13:35:28
3
465
Dieu94
77,431,444
4,628,557
pandas dataframe returning max value for a date when index isn't unique
<p>I've got a pretty simple dataframe and I want the max row for every date.</p> <pre><code> all_data = pd.DataFrame([{'Date': pd.to_datetime('1/1/2022'), 'Name': 'John', 'Score': 92}, {'Date': pd.to_datetime('1/1/2022'), 'Name': 'Mike', 'Score': 87}, {'Date': pd.to_dat...
<python><pandas>
2023-11-06 13:27:39
1
1,463
frankd
77,431,234
1,864,294
Lowest common ancestor for multiple vertices in networkx
<p>How can I compute the lowest common ancestor (LCA) for a directed graph in <code>networkx</code> for a subset of vertices?</p> <p>For example, for the graph</p> <pre><code>G = nx.DiGraph() G.add_edges_from([(1, 2), (1, 3), (3, 4), (3, 5)]) </code></pre> <p>vertex <code>3</code> is the LCA for the vertex <code>{4, 5}...
<python><networkx><lowest-common-ancestor>
2023-11-06 12:53:28
1
20,605
Michael Dorner
77,431,211
212,063
How to define constant values of Python types defined in C++ extension with Py_LIMITED_API?
<p>I want to use <code>Py_LIMITED_API</code>. Thus, instead of defining my Python type statically, I define it dynamically, with specs and slots as follows.</p> <pre><code>struct MyType { PyObject_HEAD }; static void MyType_dealloc( MyType * self ) { PyObject_DEL( self ); } static PyObject * MyType_new( PyTypeObject ...
<python><c++><c><python-c-api>
2023-11-06 12:49:17
1
37,637
Didier Trosset
77,431,210
7,929,036
Implementing IS-A cardinality in Flask SQLAlchemy and Marshamllow schemas
<p>Say I have a table called <code>User</code> which holds general information for all the users registered in the system:</p> <pre><code>class User(db.Model): __tablename__ = 'User' id = db.Column(db.Integer, primary_key=True) role = db.Column(db.String(20), nullable=False) email = db.Column(db.String...
<python><sqlalchemy><flask-sqlalchemy>
2023-11-06 12:49:17
1
1,189
Dimitar
77,431,083
511,436
How to add attributes to decorated functions when combining decorators?
<p>Two function decorators are defined. The target is to detect if 0, 1, or 2 decorators are applied to a function.</p> <p>Why does the below code return &quot;False&quot; for the 2nd decorator?</p> <pre><code>def decorator1(f): def wrapped(*args, **kwargs): f(*args, **kwargs) wrapped.dec1 = True r...
<python><python-3.x><python-decorators>
2023-11-06 12:26:12
2
1,844
Davy
77,431,020
3,322,273
Parse "multipart/form-data" payload while preserving order of parts in Python
<p>I am building an HTTP server that accepts multiple input images, while images can be input as image files or as buffers.</p> <p>For example, a request command may look as follows:</p> <pre><code>$ curl -F image_file=@/path/to/image1.jpg \ -F image_file=@/path/to/image2.png \ -F image_buffer=/path/to/im...
<python><post><multipart>
2023-11-06 12:15:27
1
12,360
SomethingSomething
77,430,937
12,242,085
How to divide Data Frame on 2 separated datasets 70%/30% based on unique combinations of values from 2 columns in Python Pandas?
<p>I have Data Frame in Python Pandas like below:</p> <p><strong>Input data:</strong></p> <pre><code>df = pd.DataFrame({ 'id' : [999, 999, 999, 185, 185, 185, 44, 44, 44], 'target' : [1, 1, 1, 0, 0, 0, 1, 1, 1], 'event': ['2023-01-01', '2023-01-02', '2023-02-03', '2023-01-01', '2023-01-02', '2023-01-03', '2...
<python><pandas><dataframe>
2023-11-06 12:01:24
2
2,350
dingaro
77,430,840
22,466,650
How to identify duplicated values over multiple unsorted columns?
<p>Sorry for the title but to explain my problem, I made a small dataframe that look like my real dataset :</p> <pre><code>df = pd.DataFrame({'user': ['u1', 'u2', 'u3', 'u4', 'u5'], 'date': ['1. August 2023', '5. January 2023', '2. May 2023', '13. July 2023', '1. January 2023'], 'task1': ['A', 'D', 'G', 'B', ...
<python><pandas>
2023-11-06 11:44:03
1
1,085
VERBOSE
77,430,797
7,648,650
Permission denied error when pasting multiple images to pptx in a loop
<p>I am pasting a bunch of images (50+) into an existing PowerPoint File, slide by slide. After a quite randomly number of slides (usually between 10-20) I get an permission Error:</p> <blockquote> <p>PermissionError: [Errno 13] Permission denied: 'C:/Users/PowerPointFileName.pptx'</p> </blockquote> <p>My Code looks so...
<python><image><powerpoint><python-pptx>
2023-11-06 11:37:38
0
1,248
Quastiat
77,430,781
5,561,472
How can I enable retries for google cloud function?
<p>I created google cloud function:</p> <pre><code>@scheduler_fn.on_schedule( schedule=&quot;00 06 1 * *&quot;, ) def getRates(event: scheduler_fn.ScheduledEvent) -&gt; None: asyncio.run(getRatesAsync()) </code></pre> <p>How can I enable retry for this function?</p> <p>According to <a href="https://firebase.goo...
<python><google-cloud-functions>
2023-11-06 11:35:07
1
6,639
Andrey
77,430,743
22,538,132
Extract multiple roi's from np array using indices ranges without loops
<p>I have a numpy array of shape 640 x 480: <code>np.ones((640, 480))</code>, and I have a min, max ranges for the rows, columns:</p> <pre><code>u_min=[497, 157, 493, 137, 567] v_min=[ 36, 46, 208, 412, 418] u_max=[502, 162, 498, 142, 572] v_max=[41, 51 213, 417, 423] </code></pre> <p>I have tried:</p> <pre class="l...
<python><arrays><numpy><slice>
2023-11-06 11:29:01
2
304
bhomaidan90
77,430,493
1,447,207
Why does numpy transpose the result in some cases when indexing with a boolean mask
<p>I have some trouble understanding the behaviour of numpy when indexing a multi-dimensional array (d &gt;= 3) with a boolean mask along one dimension.</p> <p>The following example makes sense to me:</p> <pre><code>&gt; x = np.zeros((2, 2, 3)) &gt; mask = np.ones(3, dtype=bool) &gt; print(x[:,:,:].shape) (2, 2, 3) &...
<python><numpy>
2023-11-06 10:48:45
0
803
Tor
77,430,283
2,146,803
How to make annotations static without removing using pypdf2
<p>I have so many annotations in my pdf, which is all editable and I would like to convert it non editable, I couldn't figure out how to make it static, I used below code but it completely removed the annotations.</p> <pre><code>import PyPDF2 with open('drawing.pdf', 'rb') as pdf_obj: pdf = PyPDF2.PdfReader(pdf_ob...
<python><pypdf>
2023-11-06 10:13:21
0
4,029
Prabhakaran
77,430,110
19,500,571
Rounding float to a base gives too many decimals
<p>I want to round a number to a given base. Take the following example, where I want to round to the nearest 0.01:</p> <pre><code>number = 12.123123123 base = 0.01 base * round(number/base) </code></pre> <p>I expect the result <code>12.12</code>, but I get <code>12.120000000000001</code>. Why is that? Do I need to pro...
<python>
2023-11-06 09:46:16
2
469
TylerD
77,429,562
1,000,378
Leetcode answer print and answer not matching in Python
<p>I'm trying out leetcode for the first time <a href="https://leetcode.com/explore/featured/card/top-interview-questions-easy/92/array/727/" rel="nofollow noreferrer">here</a></p> <p>I don't understand what I'm supposed to do. If I run the code locally (sanity check really), everything works as expected. If I <code>pr...
<python>
2023-11-06 07:56:01
1
5,516
François Constant
77,429,272
5,132,860
Setting File Size Limits with Signed URLs in Google Cloud Storage v4
<p>I'm trying to upload a file to Google Cloud Storage using a signed URL and I want to restrict the file size during upload. Previously, with signed URL version 2, I could set the <code>conditions</code> parameter to enforce size restrictions, but when attempting to do the same using version 4, I receive an error stat...
<python><google-cloud-storage>
2023-11-06 07:03:24
1
3,104
Nori
77,429,177
480,118
pandas: group or pivot table by a column horizonally rather than vertically
<p>I have got data that looks like this</p> <pre><code>data = [['01/01/2000', 'aaa', 101, 102], ['01/02/2000', 'aaa', 201, 202], ['01/01/2000', 'bbb', 301, 302], ['01/02/2000', 'bbb', 401, 402],] df = pd.DataFrame(data, columns=['date', 'id', 'val1', 'val2']) df date id val1 val...
<python><pandas><numpy>
2023-11-06 06:42:31
3
6,184
mike01010
77,428,855
3,685,918
How do I customize xtick to include full date for first tick in matplotlib
<p>I am using matplotlib to draw a plot chart as shown below. The x-axis is dates. I would like to display daily data in yyyy-mm-dd format as m in monthly units. And I want the first date of each year to be displayed as yy.m, not m. The first date of the year may not be January. Depending on the data, it could be Febru...
<python><matplotlib>
2023-11-06 05:07:57
1
427
user3685918
77,428,847
4,898,202
Is there a way to use a conditional kernel in openCV that only changes pixels on an image if the condition is true?
<p>I want to use a kernel that performs a pixel operation based on a <em>conditional expression</em>.</p> <p>Let's say I have this grayscale image (6x6 resolution):</p> <p><a href="https://i.sstatic.net/lpbS7.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/lpbS7.png" alt="enter image description here" />...
<python><opencv><computer-vision><blur><gaussianblur>
2023-11-06 05:05:36
2
1,784
skeetastax
77,428,810
12,242,085
How to convert values like Decimal('0.303440') in list to float in Python Pandas?
<p>I have list in Python like below:</p> <pre><code> my_list = [[Decimal('0.303440'), 0.0, 2.0, 8.0, 1.0], [109.0, 10.0, 0.0, 0.0, 3.0], [52.0, 5.0, 99.0, 0.0, Decimal('0.445378')]] </code></pre> <ul> <li><p>As you can se most of values is float, but some values are like: <code>Decimal('0.303440')</code></p> </li>...
<python><pandas><list><decimal>
2023-11-06 04:54:09
1
2,350
dingaro
77,428,642
12,242,085
How to divide Data Frame on 2 separated datasets 70%/30% of unique ids taking all rows for each id in Python Pandas?
<p>I have Data Frame in Python Pandas like below:</p> <p><strong>Input data:</strong></p> <pre><code>df = pd.DataFrame({ 'id' : [999, 999, 999, 185, 185, 185, 44, 44, 44], 'target' : [1, 1, 1, 0, 0, 0, 1, 1, 1], 'event_date': ['2023-01-01', '2023-01-02', '2023-01-03', '2023-01-01', '2023-01-02', '2023-01-03...
<python><pandas><dataset>
2023-11-06 03:50:50
1
2,350
dingaro
77,428,515
369,792
Micropython remove cr/lf on pico w
<p>I'm pretty new to python and don't have a handle on the string functions yet. I want to have a simple TCP server I can enter commands into and have the network part working, but I can't figure out something simple like removing the CR/LF at the end :)</p> <p>Here's my simple code:</p> <pre class="lang-py prettyprin...
<python><micropython>
2023-11-06 02:58:40
1
29,301
Jason Goemaat
77,428,290
1,056,563
How to specify the timezone in a python timestamp literal?
<p>The following works:</p> <pre><code> datetime.strptime(&quot;2023-11-15 01:02:03.123456&quot;, &quot;%Y-%m-%d %H:%M:%S.%f&quot;)) </code></pre> <blockquote> <p>Out[11]: datetime.datetime(2023, 11, 15, 1, 2, 3, 123456)</p> </blockquote> <p>But the following fails:</p> <pre><code> datetime.strptime(&quot;2023-11-15 01...
<python><timestamp>
2023-11-06 01:22:13
1
63,891
WestCoastProjects
77,428,218
116
Creating a protobuf factory for a dynamically generated message?
<p>Based on <a href="https://stackoverflow.com/questions/27654594/dynamically-create-a-new-protobuf-message">Dynamically create a new protobuf message</a>, I have this Python code which dynamically generates a protobuf containing two ints and a string. (Context: a dynamic data server will transfer query results via pr...
<python><protocol-buffers>
2023-11-06 00:56:21
1
305,996
Mark Harrison
77,428,177
5,032,387
Why do I need an __init__.py file to run pytest
<p>My <code>conftest.py</code> file imports a function from a local module that's used when creating fixtures:</p> <pre><code>from config import dummy_func </code></pre> <p>I then use these fixtures in conjunction with a Hypothesis strategy.</p> <p>The code hierarchy:</p> <pre><code>- src -config.py - tests -conft...
<python><pytest>
2023-11-06 00:35:23
0
3,080
matsuo_basho
77,428,104
12,242,085
How to create new rows in Data Frame based on values in 2 columns managing also values in another columns in Python Pandas?
<p>I have Data Frame in Python Pandas like below:</p> <p><strong>Input data: (columns survey and event are object date type)</strong></p> <pre><code>data = [ (1, 2, 1, 0.33, '2023-10-10', '2023-09-25', 1, 20, 11), (1, 2, 1, 0.33, '2023-10-10', '2023-10-04', 0, 10, 10), (1, 5, 0, 0.58, '2023-05-05', '2023-05...
<python><pandas><dataframe><date>
2023-11-05 23:59:04
3
2,350
dingaro
77,427,892
1,914,781
Customize plotly legend lines to square
<p>I would like to change legend symbol from line to square. example code as below:</p> <pre><code>import pandas as pd import plotly.express as px import plotly.graph_objects as go def save_fig(fig,pngname): fig.write_image(pngname,format=&quot;png&quot;,width=600,height=400, scale=1) print(&quot;[[%s]]&quot;%...
<python><plotly>
2023-11-05 22:27:33
1
9,011
lucky1928
77,427,770
1,773,169
Longest Stable Subsequence - Recover solution from memo table
<p>I am working on a DP problem to find longest stable subsequence, and I'm currently stuck with recovering the solution.</p> <p>Here is the problem statement</p> <p><a href="https://i.sstatic.net/gIPzE.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/gIPzE.png" alt="enter image description here" /></a></...
<python><dynamic-programming><memoization>
2023-11-05 21:41:29
0
377
stack underflow
77,427,754
534,617
python decrement and possible deletion in one statement
<p>In python, I wonder if there is a combined statement for the following</p> <pre><code># dct = defaultdict(int) dct[k] -= 1 if dct[k] == 0: del dct[k] </code></pre> <p>Or any arbitrary lower bound, if below, delete the element.</p>
<python><python-3.x>
2023-11-05 21:36:03
2
10,925
Qiang Li
77,427,592
15,531,189
kafka-python not receiving message on consumer side
<p>I have my kafka running on my docker. When I create a topic from CLI and start producer and consumer on CLI then kafka is able to transfer messages. but when I do same thing with python, then I don't receive any message on consumer side.</p> <p>My docker-compose file looks like</p> <pre><code>version: '3' services: ...
<python><apache-kafka><kafka-consumer-api><kafka-python>
2023-11-05 20:38:04
0
343
SHIVAM SINGH
77,427,567
14,358,734
Why am I getting TypeError: readlinestest() missing 1 required positional argument: 'input'
<p>Here's the code</p> <pre><code>def readlinestest(input): return len(input) if __name__ == '__main__': argtest = [&quot;&quot;, &quot;/n /n&quot;, &quot;/n /n /n&quot;] with concurrent.futures.ThreadPoolExecutor() as e: results = list(e.map(readlinestest(), argtest)) for x in results: ...
<python>
2023-11-05 20:30:41
0
781
m. lekk
77,427,370
14,072,498
How to update nested object in delta-rs
<p>Given the below code, I'm able to update root-level fields as e.g. &quot;age&quot;. But how to update fields inside <code>my_struct</code>?</p> <p>The attempt with <code>struct(&quot;a&quot;: &quot;1&quot;, &quot;b&quot;: &quot;2&quot;)</code> gives</p> <blockquote> <p>DeltaTable error: This feature is not implement...
<python><delta-lake><delta-rs>
2023-11-05 19:34:20
1
11,484
Roar S.
77,427,359
2,869,180
deep equality vs shallow equality in python?
<p>I read somewhere that the shallow equality for reference type like tuples, lists and strings referes to comparing them to see if they are the same.</p> <p>For strings and lists the axiom is correct. But for tuple, it is wrong:</p> <pre><code>t1 = (1, 2) t2 = (1, 2) print(t1 is t2) print(t1 == t2) </code></pre> <p>th...
<python>
2023-11-05 19:31:29
0
1,060
bib
77,427,358
19,694,624
PyCharm doesn't list Python 3.12 interpreter
<p>On my Pop OS system the base Python interpreter is 3.10, and I installed Python 3.12, it works perfectly fine:</p> <p><a href="https://i.sstatic.net/aVFR3.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/aVFR3.png" alt="img1" /></a></p> <p>With 3.12 I can create virtual environment, run Python files, s...
<python><python-3.x><pycharm><jetbrains-ide><pythoninterpreter>
2023-11-05 19:31:21
1
303
syrok
77,427,221
16,707,518
Converting existence of any text in a pandas column to a number value
<p>I can't seem to find this specific question but hopefully it's an easy one. I have a pandas dataframe with a column with mixed numbers and text. I just want to convert any text instances in that column to the value 999. e.g. for column B, I'd like to perform this operation on, so:</p> <pre><code>A B 1 1 2 5 3 FD...
<python><pandas>
2023-11-05 18:45:12
2
341
Richard Dixon
77,427,019
5,551,539
Python script to generate letter does not read .csv well
<p>Maybe you can help me troubleshoot. I am running this code to read a <code>.csv</code> file and us a sample <code>.txt</code> letter to generate a <code>.txt</code> file for each row of the <code>.csv</code> file. I name each file after the <code>Institution</code> column of the <code>.csv</code> file.</p> <pre><cod...
<python><csv><txt>
2023-11-05 17:44:22
1
301
Weierstraß Ramirez
77,426,587
3,622,727
Ignoring all default arguments python / parse_args
<p>All arguments to a python script are unknown. I am using this to parse them:</p> <pre><code>parser = argparse.ArgumentParser() parsed, unknown = parser.parse_known_args() for arg in unknown: if arg.startswith((&quot;-&quot;)): parser.add_argument(arg.split(' ')[0]) args = parser.p...
<python><argparse>
2023-11-05 15:46:08
0
353
Døner M.
77,426,566
10,940,989
concurrent.futures.Executor.map: calculate function inputs lazily
<p>I have some code similar to the following:</p> <pre><code>def worker(l:list): ... really_big_list = [......] with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor: # Start the load operations and mark each future with its URL future = {executor.submit(worker, l[i:i+100]) for i in range(0, ...
<python><multiprocessing>
2023-11-05 15:38:51
1
380
Anthony Poole
77,426,429
5,352,674
Form not valid after setting QuerySet of field in __init__
<p>A new <code>Workorder</code> is created by visiting the <code>Building</code> page and creating a Work Order. This in turn displays the <code>WorkOrderForm</code> on a new page. When viewing this form, I want to display only the equipment associated to a building, not all of the equipment.</p> <p>I have tried overri...
<python><django><django-forms>
2023-11-05 14:58:15
1
319
Declan Morgan
77,426,399
11,395,264
Why is Python leaving non-existent files in my package?
<p>For whatever reason, when I install my package <code>pie</code> with <code>pip install --break-system-packages --user git+https://github.com/zurgeg/pie.git@ed00801</code>, it fails due to a mysterious phantom file:</p> <pre class="lang-none prettyprint-override"><code>Traceback (most recent call last): File &quot;...
<python><pip>
2023-11-05 14:49:40
1
544
zurgeg
77,426,326
893,254
Numpy power with array as exponent
<p>I have a Python code containing the following lines:</p> <pre><code># Poisson model lambda_param = 3.0 x_model = numpy.linspace(0, 10, num=11, dtype=int) y_model = numpy.zeros(10) index = 0 for x in x_model: y_model[index] = numpy.power(lambda_param, x) / math.factorial(x) * numpy.exp(-lambda_param) index...
<python><numpy><factorial><poisson>
2023-11-05 14:33:51
2
18,579
user2138149
77,425,978
15,001,463
D-dimensional multi-index sums
<p>I understand how a summation in 1, 2, and 3 dimensions could be defined by using 1, 2, and 3 <code>for</code> loops respectively, but how could you make a general function that sums over a multi-index like the one defined below?</p> <p><a href="https://i.sstatic.net/1DZuj.png" rel="nofollow noreferrer"><img src="htt...
<python><sum>
2023-11-05 12:53:56
2
714
Jared
77,425,962
9,835,872
How to compose functions through purely using Python's standard library?
<p>Python's standard library is vast, and my intuition tells that there must be a way in it to accomplish this, but I just can't figure it out. This is purely for curiosity and learning purposes:</p> <p>I have two simple functions:</p> <pre class="lang-py prettyprint-override"><code>def increment(x): return x + 1 ...
<python><functional-programming><standard-library><language-features><function-composition>
2023-11-05 12:48:12
3
24,819
ruohola
77,425,931
14,923,149
How to Parse Hierarchical Data and Format it into a TSV File in Python?
<p>I have a dataset with hierarchical information and KO numbers, and I'm looking to format this data into a TSV (Tab-Separated Values) file in Python, where the first column contains KO numbers, the second column contains descriptions, and the third column contains a hierarchy based on the nearest 'A' section in the i...
<python><for-loop><while-loop>
2023-11-05 12:34:18
1
504
Umar
77,425,921
2,804,160
Scientific notation in list form in Python
<p>I have a list <code>A</code>. I want to convert the elements of this list to scientific notation. I present the current and expected output.</p> <pre><code>A = [0.000129,0.000148] A_scientific = [f'{num:.2e}' for num in A] print(A_scientific) </code></pre> <p>The current output is</p> <pre><code>['1.29e-04', '1.48e-...
<python><list><scientific-notation>
2023-11-05 12:32:00
1
930
Wiz123
77,425,826
9,398,584
create a directory name from a string in python
<p>What's the most idiomatic, clean way to convert a descriptive string to a portable directory name?</p> <p>Something like <code>description.replace(&quot; &quot;, &quot;_&quot;)</code> but that also removes / replaces punctuations and other whitespaces, and maybe other edge cases I haven't thought about.</p> <p>The m...
<python><filesystems>
2023-11-05 12:05:00
4
431
Just Me
77,425,791
17,795,398
Kivy `Logger` treats Python exception as warning in `PYTHON` mode
<p>I'm using this basic configuration for logging a Kivy app:</p> <pre><code>import logging logging.basicConfig( filename = &quot;log.log&quot;, filemode = &quot;w&quot;, encoding = &quot;utf-8&quot;, force = True, level = logging.INFO, format = &quot;%(asctime)s %(levelname) -8s %(message)s&quo...
<python><logging><kivy>
2023-11-05 11:50:57
0
472
Abel Gutiérrez
77,425,781
12,214,867
`[0, 267, 270, 468]` describes a bbox, how do I get it from `[266.67, 0.0, 201.69, 269.58]`?
<p>i got a set of modified annotations for a bunch of coco images. for example, <code>[0, 267, 270, 468]</code> and <code>[254, 250, 458, 454]</code> are 2 pieces from the set, describing two bboxes for the following image. (named 000000173350.jpg in the original dataset)</p> <p><a href="https://i.sstatic.net/dgxnX.png...
<python><computer-vision><bounding-box>
2023-11-05 11:49:41
2
1,097
JJJohn
77,425,750
14,271,847
RuntimeError: Number of consecutive failures exceeded the limit of 3 during Keras Tuner search
<p>I'm encountering a <code>RuntimeError</code> when using Keras Tuner to search for the best hyperparameters for my image segmentation model. The error indicates that the number of consecutive failures has exceeded the limit of 3. Below is the full error message:</p> <pre><code>Exception has occurred: RuntimeError Num...
<python><tensorflow><keras><image-segmentation><keras-tuner>
2023-11-05 11:38:40
0
429
sysOut
77,425,682
4,832,499
What is the point of usedforsecurity?
<p>The parameter <code>usedforsecurity</code> was added to every hash function in hashlib in Python 3.9.</p> <blockquote> <p>Changed in version 3.9: All hashlib constructors take a keyword-only argument usedforsecurity with default value True. A false value allows the use of insecure and blocked hashing algorithms in r...
<python><python-3.x><security><hash>
2023-11-05 11:14:07
2
21,560
Passer By
77,425,573
330,457
How can I randomize existing byte array?
<p>I create an array of bytes.</p> <pre class="lang-py prettyprint-override"><code>array = bytearray(random.randint(1, 8192)) # Now, how can I randomize array's elements? </code></pre> <p>Now how can I randomize each elements of the <code>array</code>?</p> <p>Just like,</p> <pre class="lang-java prettyprint-override">...
<python><random>
2023-11-05 10:34:08
3
22,366
Jin Kwon
77,425,492
16,611,809
How can I get the number of Apple Silicon performance cores in Python?
<p>I want to determine the number of performance cores in a Python script (it's actually going to be a Python app frozen with PyInstaller, if that makes a difference).</p> <p>There are some ways to get the number of CPUs/cores like <code>os.cpu_count()</code>, <code>multiprocessing.cpu_count()</code> or <code>psutil.cp...
<python><cpu><apple-silicon><sysctl>
2023-11-05 10:05:44
0
627
gernophil
77,425,450
21,401,783
What does datetime.now().strftime("%j") do?
<p>To get the current year using the datetime module, you can use <code>datetime.now().strftime(&quot;%Y&quot;)</code>, which returns <code>2023</code> as expected.</p> <p>However, I found that another argument, <code>%j</code> can be passed instead of <code>%Y</code>. Doing this returns <code>309</code>.</p> <p>What d...
<python><datetime>
2023-11-05 09:49:35
1
1,364
Dinux
77,425,362
2,642,351
What is the default timed out time for Popen.communicate?
<p>In Python I am using subprocess to call a long running command and <code>proc.communicate()</code> so as to be able to log/print the output in realtime as shown <a href="https://docs.python.org/3/library/subprocess.html#subprocess.Popen.communicate" rel="nofollow noreferrer">here</a>.</p> <p>However, I am getting a ...
<python><subprocess><popen>
2023-11-05 09:19:16
0
5,918
Temp O'rary
77,425,335
17,795,398
How to set python gettext translations to source language
<p>I have this piece of code for translations:</p> <pre><code>translations = gettext.translation( locale_language, localedir=&quot;gui/locale&quot;, languages=[locale_language] ) translations.install() </code></pre> <p>Where <code>locale_language</code> can be <code>&quot;en&quot;</code> (source language (<...
<python><gettext>
2023-11-05 09:08:53
1
472
Abel Gutiérrez
77,425,239
5,821,028
cuml K-means clustering slower when multiple instances are running
<p>I am having a performance problem when running multiple cuml.cluster.KMeans.fit_predict() concurrently on a single machine. There is enough memory on both the GPU and the host. When run in isolation, the function (max_silhouette_score) call takes approximately 1 second. However, when I run the 2x functions concurren...
<python><k-means><cuml>
2023-11-05 08:34:02
0
1,125
Jihyun
77,425,149
14,459,677
Summing up in pandas based on Column conditions
<p>I have a dataframe (df1) which looks like this:</p> <pre><code>Date Name Category # 01/01/01 Vegetables A 15 01/01/01 Fruits A 10 01/01/01 Meat B 35 01/02/01 Vegetables A ...
<python><pandas><group-by><sum>
2023-11-05 07:57:20
4
433
kiwi_kimchi
77,425,084
8,950,733
Why AutoKey soft faster than bare Python script?
<p>I just have moved to <strong>Ubuntu 22.04.3 LTS</strong> from <strong>Windows</strong>, where I was active user of the <strong>AutoHotKey</strong>.</p> <p>So, I have created <strong>.py</strong> script file with the following code:</p> <p><a href="https://i.sstatic.net/OhLqL.png" rel="nofollow noreferrer"><img src="...
<python><ubuntu><keyboard-shortcuts><autokey>
2023-11-05 07:28:55
0
516
Mikhail
77,425,036
13,566,519
How can I determine the number of Python packages available for a specific package name in Python?
<p>Python packages vary in terms of their compatibility with different Python versions and platforms. For example, in the case of &quot;cffi&quot; equals 1.16.0 version packages on PyPI, you can find approximately 51 distinct packages tailored for various Python versions and platforms such as Windows, macOS, and Linux....
<python><python-3.x><pip><pypi><python-wheel>
2023-11-05 07:08:48
1
317
GreenMan
77,424,814
22,860,226
AWS SQS FIFO in Python - deleted messages are available even after correct VisbilityTimeout
<p>I created an FIFO queue. I send 10 msgs, receive them and delete them. But they are still available in queue and received again. I receive 10 msgs initially, then 5 , then 2 and then 0. &quot;delete_message&quot; response was also 200.</p> <p>Code :</p> <pre><code>import json import os import uuid import boto3 from...
<python><amazon-web-services><amazon-sqs>
2023-11-05 05:27:37
1
411
JTX
77,424,793
18,756,733
Multiprocessing Function Runs Forever
<p>I have a list of URLs : daily_article_urls. For each URL I want to run the following webscraping code:</p> <pre><code>daily_data=[] def scrape_article(i,article_url): try: article_html=requests.get(article_url).content article_soup=BeautifulSoup(article_html, 'html.parser') article_id=ar...
<python><beautifulsoup><multiprocessing>
2023-11-05 05:16:05
1
426
beridzeg45
77,424,774
10,200,497
Finding the last row that meets conditions of a mask
<p>This is my dataframe:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({'a': [20, 21, 333, 444], 'b': [20, 20, 20, 20]}) </code></pre> <p>I want to create column <code>c</code> by using this mask:</p> <pre class="lang-py prettyprint-override"><code>mask = (df.a &gt;= df.b) </code></pre> <p>And I...
<python><pandas><indexing><conditional-statements><duplicates>
2023-11-05 05:11:20
4
2,679
AmirX
77,424,767
992,421
RDD creating adjacency list
<p>I am trying to create adj list with input</p> <pre><code>RDD=[&quot;2\t{'3': 1}&quot;, &quot;3\t{'2': 2}&quot;, &quot;4\t{'1': 1, '2': 1}&quot;, &quot;5\t{'4': 3, '2': 1, '6': 1}&quot;, &quot;6\t{'2': 1, '5': 2}&quot;, &quot;7\t{'2': 1, '5': 1}&quot;, &quot;8\t{'2': 1, '5': 1}&quot;, ...
<python><list><apache-spark><pyspark>
2023-11-05 05:07:09
1
850
Ram
77,424,645
5,246,226
Building PyTorch as a submodule of larger project with Bazel results in invalid file paths
<p>I have a project I need to build using Bazel, and I need the PyTorch libraries for C++. After a lot of trial and error, I've resorted to including PyTorch's source as a submodule. This is because I need to edit the BUILD files and need to specify the dependencies again, since Bazel doesn't read external dependency W...
<python><build><bazel>
2023-11-05 03:52:56
0
759
Victor M
77,424,632
130,208
How to mock.patch a class method which is a generator/has yield
<p>How to patch a generator class method. For e.g. in class below, how would we patch get_changed_diff_patch method?</p> <pre><code>class PassiveJsonMixin(JsonMixin): &quot;&quot;&quot; passive items that do not have id/key &quot;&quot;&quot; def __init__(self, *args, **kwargs): JsonMixin.__ini...
<python><generator><patch><yield><python-unittest.mock>
2023-11-05 03:40:59
1
2,065
Kabira K
77,424,417
8,593,689
sqlite3 error "ValueError: parameters are of unsupported type"
<p>I have an sqlite3 table that I created like this:</p> <pre class="lang-sql prettyprint-override"><code>CREATE TABLE packages ( id INTEGER PRIMARY KEY, name TEXT UNIQUE NOT NULL, description TEXT, price DECIMAL(5,2), enabled INTEGER DEFAULT 1 ); </code></pre> <p>I am trying to query the table as b...
<python><flask><sqlite3-python>
2023-11-05 01:28:07
1
5,032
Shane Bishop
77,424,238
359,219
Fixing my Python package and module structure so it works with pytest and VS Code
<p>I have this directory structure:</p> <pre class="lang-none prettyprint-override"><code>memsim/ __init__.py utils.py tests/ __init__.py utils_test.py </code></pre> <p>In utils.py:</p> <pre><code>def flatten_free_segments(free_segments): </code></pre> <p>In utils_test.py:</p> <pre><code>from util...
<python>
2023-11-04 23:50:22
0
11,040
pitosalas
77,424,233
15,456,681
How to wrap an external function in numba such that the resulting function is cacheable?
<p>I would like to wrap an external function with numba, but require that the resulting function is able to be cached with <code>njit(cache=True)</code> like I can do with the numba implementation (I'm just using <code>dgesv</code> as an example):</p> <pre class="lang-py prettyprint-override"><code>import numba as nb i...
<python><numba>
2023-11-04 23:47:11
1
3,592
Nin17
77,424,156
414,104
logger not logging info but only logging error though every setting in logging flow is correct?
<p>I'm trying to log in python but I'm not seeing logs for anything lower than error. I've checked every part of the logging flow, from logger to to appropriate level, handlers, filters at logger and handler level.</p> <p>I don't have small reproducible answer since it works as expected when I pare it down, but screens...
<python><logging>
2023-11-04 23:16:28
1
3,595
canyon289
77,424,139
3,949,631
Indexing numpy array with an array of indices
<p>I have 2 <code>numpy</code> arrays: <code>X</code> with shape <code>(..., 12, 3)</code> and <code>Y</code> with shape <code>(..., 12)</code>, where the <code>...</code> is the same in both cases. I get an array of indices using:</p> <pre><code>idx = np.argmin(Y, axis=-1) </code></pre> <p>which afterwards I want to u...
<python><numpy>
2023-11-04 23:11:04
1
497
John
77,424,126
22,466,650
How to shift the values of a list to the left as much as possible?
<p>Let's consider these two lists :</p> <pre><code>list1 = ['N/A', 'a', 'b', 'c'] list2 = [None, None, 'd', None, 'e'] </code></pre> <p>1-) I need to shift their items to the left as long as there is a target value at the beginning but 2-) we should ignore the eventual targets that can be in the middle and finally 3-) ...
<python><list>
2023-11-04 23:03:31
2
1,085
VERBOSE
77,423,938
3,498,864
Order elements in a matrix based on another matrix
<p>I'd like to order an arbitrary number of elements into an arbitrarily shaped matrix (<code>matrix_a</code>) based on values in a binary matrix (<code>element_map</code>) that describes attributes of the elements. <code>matrix_b</code> defines which <code>elements</code> can be adjacent to each other in <code>matrix_...
<python><optimization><sparse-matrix><linear-programming><integer-programming>
2023-11-04 21:49:47
1
3,719
Ryan
77,423,868
1,734,357
Failing to use bound_contextvars with complex logger configuration because of missing structlog.contextvars.merge_contextvars processor
<p>This</p> <pre><code>import structlog from structlog.contextvars import bound_contextvars if __name__==&quot;__main__&quot;: log = structlog.getLogger(__name__) with bound_contextvars(frame_id=&quot;ADA&quot;, command_id=&quot;123&quot;): log.info(&quot;rabo&quot;) </code></pre> <p>logs <code>2023-11-...
<python><logging><structlog>
2023-11-04 21:22:06
1
1,493
WurmD
77,423,844
5,594,008
Wagtail CheckConstraint, column live does not exists
<p>I have such model</p> <pre><code>from wagtail.models import Page class Article(Page): price = PositiveIntegerField( null=True, blank=True, ) class Meta: constraints = [ CheckConstraint(check=Q(price__gte=100) &amp; Q(live=True), name=&quot;min price for publishe...
<python><django><wagtail>
2023-11-04 21:12:58
1
2,352
Headmaster
77,423,773
15,433,308
Reusing Spark SQL code in an on demand web service
<p>I have a process written in pyspark that runs some complex logic on large batches of data and is run periodically. There is also high demand to enable users to run the logic on demand on small subsets of data according to a query and get results fast. It would be really expensive and hard to maintain another copy of...
<python><apache-spark><pyspark><apache-spark-sql>
2023-11-04 20:47:50
0
492
krezno
77,423,724
2,809,176
Langchain custom agent promt for ollama mistral 7b-instruct does not call a tool, gives dirrectly a wrong final answer
<p>I followed this langchain custom agent <a href="https://python.langchain.com/docs/modules/agents/how_to/custom_llm_agent" rel="nofollow noreferrer">guide</a> but with local <code>ollama mistral:7b-instruct</code> model. <strong>The problem is that model hallucinates observations and gives a wrong final answer on the...
<python><langchain><large-language-model>
2023-11-04 20:33:47
0
1,335
user2809176
77,423,657
21,305,238
Constructing large character ranges with pyparsing.srange is extremely slow
<p>I have some of these constructions in my code:</p> <pre class="lang-py prettyprint-override"><code>from pyparsing import Char, srange _non_ascii = Char(srange('[\x80-\U0010FFFF]')) </code></pre> <p>The generation of the ranges is extremely slow, taking 6-8 seconds (<a href="https://meta.stackexchange.com/a/19514">h...
<python><performance><pyparsing>
2023-11-04 20:09:40
1
12,143
InSync
77,423,567
7,133,942
How to create multiple combined csv files out of a multi-dimensional numpy arrays
<p>I have 8 numpy arrays of the dimensionalty (number_of_buildings, number_of_weeks) which in my example is (2, 20). They look like that:</p> <pre><code>import numpy as np result_multiple_buildings_simulationObjective_costs_Euro_OPT = np.array([ [181.1, 172.59, 170.02, 173.83, 181.21, 160.95, 182.24, 186.1, 168.4,...
<python><arrays><numpy><csv>
2023-11-04 19:41:35
1
902
PeterBe
77,423,535
4,515,341
Fill pandas column forward iteratively, but without using iteration?
<p>I have a pandas data frame with a column where a condition is met based on other elements in the data frame (not shown). Additionally, I have a column that extends the validness one row further with the following rule:</p> <p><strong>If a valid row is followed directly by ExtendsValid, that row is also valid, even ...
<python><pandas><dataframe><fillna>
2023-11-04 19:30:16
2
332
DISC-O
77,423,000
893,254
Does Python support an optimization using the Levenberg Marquardt algorithm for general optimization problems?
<p>It is a while since I have tackled any non-linear function fitting (optimization) problems. Previously I have been familiar with them in the context of C++ or C libraries. The algorithm which I am most familiar with is the Levenberg Marquardt algorithm, which is a damped gradient descent algorithm. It typically prov...
<python><optimization><scipy><levenberg-marquardt>
2023-11-04 16:56:32
1
18,579
user2138149
77,422,945
5,330,527
No module found [my_app] with Apache and mod_wsgi
<p>This is my directory structure, in <code>/var/www</code>:</p> <pre><code>team_django --team_db ---- __init__.py -----settings.py -----wsgi.py </code></pre> <p>My wsgi.py:</p> <pre><code>import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'team_db.settings') ...
<python><django><mod-wsgi><django-wsgi>
2023-11-04 16:41:04
1
786
HBMCS
77,422,926
8,519,830
Sum of numpy array based on elements in another numpy array?
<p>I have 2 arrays:</p> <pre><code>arr1 =np.array([10, 20, 15, 0, 45, 100]) arr2 =np.array([0, 3, 1, 6, 0, 0]) </code></pre> <p>I want to get the sum of those elements from arr1 whose corresponding entries in arr2 are 0. The sum would be 10+45+100=155 in the example. How can I achieve this easily?</p>
<python><numpy>
2023-11-04 16:35:42
1
585
monok
77,422,820
18,445,352
Postgres query hung when I ran a simple select query
<p>I'm using pandas <code>read_sql()</code> method to read tables from my PostgreSQL database. The query is as simple as <code>SELECT * FROM my_table</code>. Yesterday, one of those queries failed, and I had to restart the Jupyter notebook after two or three minutes. Initially, I believed the issue was specific to the ...
<python><sql><pandas><postgresql>
2023-11-04 16:07:35
1
346
Babak
77,422,605
14,939,441
Program for an upright and inverted triangle pattern with one For loop and if-else statement
<p>I am new to Python and wanted to create a program which prints this star pattern using one <code>for</code> loop and an if-else statement:</p> <pre><code>* ** *** **** ***** **** *** ** * </code></pre> <p>What I've done so far:</p> <pre><code>stars = &quot;*&quot; for i in range (0,10): if i &lt;5: print...
<python>
2023-11-04 15:14:43
2
329
Thandi
77,422,491
8,937,353
Change pixels of a 2 bit image; How can I extend 3-color palette image to have a 4th palette entry?
<p>I have a 2-bit image, which has pixels as 0,1 and 2. Where 0 is the background and 1 and 2 are labels. I want to create one more label by changing some pixels to 3. I tried imageJ fill with a colour picker, but it's only letting me choose from existing labels. I tried using Python as well as Matlab but everything is...
<python><opencv><image-processing><python-imaging-library>
2023-11-04 14:46:10
0
302
A.k.
77,422,410
3,231,250
manipulate the element before finding sum of higher elements in the row
<p>I have asked about finding sum of higher elements in the row/column and got really good <a href="https://stackoverflow.com/questions/77418144/for-each-element-of-2d-array-sum-higher-elements-in-the-row-and-column">answer</a>. However this approach does not allow me to manipulate current element.</p> <p>My input data...
<python><pandas><numpy><matrix><scipy>
2023-11-04 14:23:06
1
1,120
Yasir
77,422,093
10,940,989
Measure total memory usage of python process that processing pool
<p>I'm running a python script that uses concurrent.futures.processPool. I would like to get an idea of what the <em>peak</em> memory usage is including all the child processes.</p> <p>There are obviously many linux tools for measuring memory usage, but I'd like to know if there's anything that correctly compacts child...
<python><linux><multiprocessing>
2023-11-04 12:56:23
1
380
Anthony Poole
77,422,013
1,668,622
How to get rid of 'incompatible type "Callable[[NamedArg(int, 'val')], ..'?
<p>I'm trying to forward and/or store <code>Callable</code>s while providing as much type hinting as possible. Currently I'm struggling with a <code>mypy</code> error that seems simple, but I somehow cannot solve it. Imagine this little snippet containing a collection of <code>Callable</code>s:</p> <pre><code>from coll...
<python><python-3.x><mypy><python-typing><keyword-argument>
2023-11-04 12:37:05
1
9,958
frans
77,421,996
16,383,578
Efficient way to implement Minimax AI for Tic Tac Toe orders 3, 4, 5?
<p>I want to create an artificial intelligence that plays Tic Tac Toe better than any human.</p> <p>I have already written a completely working GUI Tic Tac Toe game with AI players, but all those AI players are bad. So I have created another AI using <a href="https://stackoverflow.com/questions/77417037/why-does-utiliz...
<python><algorithm><tic-tac-toe>
2023-11-04 12:30:05
2
3,930
Ξένη Γήινος
77,421,991
9,565,342
GStreamer: properly send EOS event on ctrl+c
<p>I can successfully record video from videotestsrc via the following command:</p> <pre><code>gst-launch-1.0 -e videotestsrc ! videoconvert ! x264enc ! mp4mux ! filesink location=output.mp4 </code></pre> <p>When I run the command above and press ctrl+c, I get a playable <code>output.mp4</code> file.</p> <p>I want to r...
<python><gstreamer>
2023-11-04 12:28:13
1
1,156
NShiny
77,421,972
4,948,889
Finding ord of a red heart giving errors Python
<p>I am trying to print the ord of a red heart in Python.<br /> I have checked <a href="https://stackoverflow.com/questions/64161291/how-to-print-red-heart-in-python-3">How to print red heart in python 3</a> but it is not related to ord function.</p> <p>When I tried <code>print(ord(❤️))</code> I have received the foll...
<python><unicode>
2023-11-04 12:21:06
1
7,303
Jaffer Wilson
77,421,613
16,108,271
Cannot run python Flask app cPanel using PhusionPassenger
<p>I am unable to run my flask app in cpanel</p> <p>My <code>passenger_wsgi.py</code> is</p> <pre class="lang-py prettyprint-override"><code>import os import sys from app import app application = app sys.path.insert(0, os.path.dirname(__file__)) </code></pre> <p>and my <code>app.py</code> is</p> <pre class="lang-py...
<python><flask><cpanel><passenger>
2023-11-04 10:21:28
0
551
Timsib Adnap
77,421,350
1,709,475
sql query in python script not returning list of database tables
<p>I have the following code that is aimed to return, from the local system, the databases,the version of PostgreSQL, the size of the databases, the tables in each database (not beginning with pg_) and write all this data to a .csv file. Environment: PostgreSQl: v14.6, Python: v3.11, O/S: Win10</p> <pre><code>#-------...
<python><sql><database><postgresql>
2023-11-04 08:54:20
1
326
Tommy Gibbons
77,421,184
12,930,735
Rolling mean with most updated record from another column
<p>I have a dataframe with two datetime columns, one for the execution date (&quot;execution_time&quot;) and another for predictions (&quot;valid_time&quot;). For each row, valid_time &lt;= execution_time. And for each valid_time I may have several execution_times.</p> <p>What I want to compute is a rolling mean by eac...
<python><group-by><python-polars><rolling-computation>
2023-11-04 07:53:14
2
679
SergioGM
77,421,115
4,281,353
Python Ray - explanation of await queue.get_async(block=True, timeout=None)
<p><a href="https://docs.ray.io/en/latest/ray-core/api/doc/ray.util.queue.Queue.get_async.html#ray.util.queue.Queue.get_async" rel="nofollow noreferrer">Ray.util.queue.Queue.get_async</a> has <code>block</code> argument. Why async method blocks as async means return without blocking, in my understanding.</p> <p>Looked ...
<python><asynchronous><ray>
2023-11-04 07:24:03
1
22,964
mon
77,421,053
20,088,885
Blank Page After Odoo Login
<p>Why do I get blank page after Odoo Login? It was working yesterday but when I tried to open right now, I only get empty page. At first, I thought it was just my directory or the <code>odoo.conf</code> is not properly configured.</p> <p><a href="https://i.sstatic.net/PR3gl.png" rel="nofollow noreferrer"><img src="htt...
<python><odoo>
2023-11-04 06:59:02
1
785
Stykgwar
77,421,030
6,660,373
How to generate the UML diagram from the python code
<p>I have this code <a href="https://github.com/ninjakx/Low-Level-Design/tree/main/LLD(Python)/ShoppingCart" rel="nofollow noreferrer">repo</a></p> <p>I created manual UML which look like this: <a href="https://i.sstatic.net/h8DHw.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/h8DHw.png" alt="enter imag...
<python><uml><class-diagram><pyreverse>
2023-11-04 06:50:29
1
13,379
Pygirl