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,719,585
10,633,596
How to read headers that are sent in the webhook URL request
<p>I'm trying to read the additional custom headers that were sent when I made the curl request using the webhook URL of a Slack channel but I cannot find a way to read the custom header or query parameters. May I know if there is any way to determine them?</p> <pre><code>from typing import Optional import slack_sdk im...
<python><slack-bolt>
2023-12-27 00:31:44
1
1,574
vinod827
77,719,512
12,719,086
How to send audio stream to an Icecast server in Python
<p>I am having some issues trying to properly send audio data from a file to an Icecast server in Python.</p> <p>Here is my class :</p> <pre><code>import requests from base64 import b64encode class IcecastClient: def __init__(self, host, port, mount, user, password, audio_info): self.host = host se...
<python><http><python-requests><icecast><icecast2>
2023-12-26 23:50:04
1
471
Polymood
77,719,408
15,494,335
How to make a python package's __init__.py file execute when debugging the __main__.py file?
<p>If I execute <code>python -m some_package</code> on the command line, with <code>some_package/__init__.py</code> containing <code>print(&quot;hello __init__.py&quot;)</code> and <code>some_package/__main__.py</code> containing <code>print(&quot;hello __main__.py&quot;)</code>, then both lines get printed, each once....
<python><vscode-debugger>
2023-12-26 23:02:35
2
707
mo FEAR
77,719,249
1,171,746
How to create a TypeGuard that mimics isinstance
<p>I have to check an object that may have been created by an API. When I try using <code>isinstance(obj, MyClass)</code> it get a <code>TypeError</code> if <code>obj</code> was created by the API.</p> <p>I wrote a custom function to handle this.</p> <pre class="lang-py prettyprint-override"><code>def is_instance(obj: ...
<python><python-typing><typeguards>
2023-12-26 22:01:51
1
327
Amour Spirit
77,719,065
1,874,170
Different repr for REPL?
<p>I want to present an alternative <code>repr</code> for an object <strong>iff</strong> it's being dumped into the REPL directly, not as part of a <code>Collection</code> and not as part of a different function call; this alternate representation contains a lot of very useful debugging information, but inherently brea...
<python><debugging>
2023-12-26 20:55:46
1
1,117
JamesTheAwesomeDude
77,718,512
893,254
Is there a way to prevent Visual Studio Code automatically hiding the "Add Code" and "Add Markdown" buttons when working with Jupyter Notebooks?
<p>When working with Jupyter Notebook files in VS Code, two buttons &quot;Add Code&quot; and &quot;Add Markdown&quot; appear below a Cell, when hovering over the location of the buttons.</p> <p>Is there any way to prevent them from being automatically hidden when not being hovered-over by the mouse?</p> <p>It seems lik...
<python><visual-studio-code><jupyter-notebook>
2023-12-26 17:53:14
1
18,579
user2138149
77,718,293
12,696,223
Why BLAS cblas_sgemm in C is slower than np.dot?
<p>I made a simple benchmark between Python NumPy and C OpenBLAS to multiply two 500x500 matrices. It seems that <code>np.dot</code> performs almost 9 times faster than <code>cblas_sgemm</code>. Is there anything I'm doing wrong?</p> <p>Results:</p> <ul> <li>Python: 0.001830 seconds</li> <li>C: 0.016374 seconds</li> </...
<python><c><numpy><blas>
2023-12-26 16:54:52
0
990
Momo
77,718,249
13,146,544
Deploying a Flask app on Vercel is showing 404 Not Found
<p>My project structure:</p> <pre><code>api | |--fsk.py (file) | |--static (folder) | | | |--css (folder containing css files) | | | |--scripts (folder containing js files) | |--templates (folder containing html files) | |--vercel.json (file) | |--requirements.txt (file) </code></pre>...
<python><html><flask><vercel>
2023-12-26 16:44:00
0
866
Samudra Ganguly
77,717,714
14,533,334
How to Set Event Reminders in Google Calendar for Multiple Users using Python API without Explicit Consent?
<p>I'm developing an application where I need to set event reminders in multiple users' Google Calendars without explicitly asking for their permission. When exploring the Google Calendar API in Python, I encountered limitations due to privacy and security restrictions.</p> <p>I'm seeking insights into whether it's pos...
<python><django><google-api><google-calendar-api>
2023-12-26 14:24:57
1
493
Fasil K
77,717,687
16,525,263
Create a new row based on other column values in pyspark dataframe
<p>I have a pyspark dataframe as below:</p> <pre><code>c1 c2 111 null null 222 333 444 null null </code></pre> <p>I need to have a final dataframe with an additional column like below</p> <pre><code>c1 c2 new_col 111 null 111 null 222 222 333 444 333 333 444 ...
<python><apache-spark><pyspark>
2023-12-26 14:15:53
4
434
user175025
77,717,398
3,372,061
Getting the path to the file located by FileSensor
<p>I am building a DAG that waits for filesystem changes then runs some analysis on newly appearing or modified files, for which I'm using a <code>FileSensor</code>. The path definition I'm monitoring contains both a jinja template and either a wildcard or a glob. When a file is found, I would like to provide its absol...
<python><airflow><parameter-passing><glob><file-watcher>
2023-12-26 13:01:01
1
24,239
Dev-iL
77,717,390
2,148,416
Inconsistent declaration of `ndarray.__array_ufunc__`
<p>While writing an ndarray subclass, Mypy flags a problem related to the declaration of the <code>method</code> argument in <code>__array_ufunc__</code>.</p> <p>The <a href="https://numpy.org/doc/stable/user/basics.subclassing.html#array-ufunc-for-ufuncs" rel="nofollow noreferrer"><code>__array_ufunc__</code> docs</a>...
<python><numpy><numpy-ufunc>
2023-12-26 12:59:21
0
3,437
aerobiomat
77,717,255
893,254
Python iterate between two datetime objects
<p>How can I iterate between two <code>datetime.date</code> objects in Python?</p> <p>For example, if I have two dates:</p> <pre><code>date1 = datetime.date(2024, 1, 10) date2 = datetime.date(2024, 1, 20) </code></pre> <p>and I want to do something like this:</p> <pre><code>while date1 &lt; date2: # do something ...
<python><date><datetime>
2023-12-26 12:34:05
2
18,579
user2138149
77,717,231
815,443
Why is __radd__ not called for the same class in Python?
<p>I thought returning <code>NotImplemented</code> from <code>__add__</code> will pass to <code>__radd__</code> under all circumstances, but apparently this is not true if it's the same class?</p> <pre><code>class A: def __add__(self, other): print(&quot;add&quot;) return NotImplemented def __r...
<python>
2023-12-26 12:26:39
1
12,817
Gere
77,717,029
1,469,954
Redisearch full text index not working with Python client
<p>I am trying to follow <a href="https://redis.io/docs/connect/clients/python/" rel="noreferrer">this</a> Redis documentation link to create a small DB of notable people searchable in real time (using Python client).</p> <p>I tried a similar code, but the final line, which queries by &quot;s&quot;, should return two d...
<python><redis><redis-py><redisearch>
2023-12-26 11:33:29
3
5,353
NedStarkOfWinterfell
77,716,952
1,473,517
How to stop dots being cut off at edge of grid
<p>I have a simple grid of dots which I make with:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt # Add blue dots for x in np.arange(0, 10, 1): for y in np.arange(0, 10, 1): plt.scatter(x, y, color='blue', s=20) # Adjust the size (s) as needed # Customize plot ax = plt.gca() ...
<python><matplotlib>
2023-12-26 11:13:27
1
21,513
Simd
77,716,847
3,563,894
Calculating power of (1-1/x)^y for very large x,y
<p>I am thinking about calculating $(1-1/x)^y$ for very large x,y numbers in python. One way todo so, it to use <code>exp(y*log1p(-1/x))</code>, but I am not sure about its accuracy.</p> <p>Are they any results on using such accuracy? e.g., bound the error of such result?</p> <p>I guess it better than using the approxi...
<python><numpy><floating-accuracy>
2023-12-26 10:42:16
1
367
user3563894
77,716,829
7,254,247
How do I deserialize a protobuf string in js sent from a python backend?
<p>I have a Flask server that sends a serialized protocol buffer message. I've de-serialized this message in a few environments successfully, including a C++ client. However, when I attempt to de-serialize my message in js, nothing works. I am using <a href="https://github.com/protobufjs" rel="nofollow noreferrer">prot...
<javascript><python><protocol-buffers>
2023-12-26 10:38:19
2
772
lee
77,716,718
1,668,622
Bug or wrong usage? Scrollbar broken for textual.Log when printing styled (coloured) lines
<p>I'm trying to render colored text inside a <code>textual.Log</code> widget using <code>rich.Style</code>, but somehow the scrollbar gets scrambled when applying a <code>Style</code> to the individual lines.</p> <p>Here is my code:</p> <pre class="lang-py prettyprint-override"><code>from textual import work from text...
<python><rich><python-textual>
2023-12-26 10:12:43
1
9,958
frans
77,716,670
972,733
Trouble Sending Messages to Numbers Outside Twilio Sandbox via WhatsApp API
<p>I'm integrating the Twilio WhatsApp API into a Flask application to send automated messages. While I can send messages to my own WhatsApp number that's subscribed to the sandbox with the <code>join &lt;given code&gt;</code> command, I'm unable to send messages to other numbers. The peculiar part is that there are no...
<python><twilio><whatsapi>
2023-12-26 10:02:37
1
318
Wardruna
77,716,293
6,494,707
There is no current wx.App object - creating one now
<p>I am trying to visualize my hypercube data using <code>spectral</code> package and I follow the commands in the <a href="https://www.spectralpython.net/graphics.html" rel="nofollow noreferrer">main page</a> of spectral by <code>ipython --pylab=wx</code> and then I loaded the data to view::</p> <pre><code>import spec...
<python><user-interface><wxpython><wxwidgets><spectral-python>
2023-12-26 08:16:19
0
2,236
S.EB
77,716,028
1,330,810
Inserting many rows in psycopg3
<p>I used to use <code>execute_values</code> in psycopg2 but it's gone in psycopg3. I tried following the advice in <a href="https://stackoverflow.com/questions/76713315/passing-nested-tuple-to-values-in-psycopg3">this</a> answer or this <a href="https://github.com/psycopg/psycopg/issues/114" rel="noreferrer">github po...
<python><postgresql><psycopg2><psycopg3>
2023-12-26 06:57:06
2
5,825
Idan
77,715,955
4,309,170
Best approach to find next True value from an index in a boolean array
<p>I have a boolean list like this:</p> <pre><code>test_dict = [False, False, True, False, False, True] </code></pre> <p>I need help with an algorithm that can find the next True value from a given position. Please note that the position is also obtained by iterating a list. Hence, please consider that loop as well whe...
<python><algorithm>
2023-12-26 06:33:22
2
628
Han
77,715,786
1,965,449
Numpy shape function
<pre><code> A = np.array([ [-1, 3], [3, 2] ], dtype=np.dtype(float)) b = np.array([7, 1], dtype=np.dtype(float)) print(f&quot;Shape of A: {A.shape}&quot;) print(f&quot;Shape of b: {b.shape}&quot;) </code></pre> <p>Gives the following output :</p> <pre><code>Shap...
<python><numpy><numpy-slicing>
2023-12-26 05:28:28
1
2,931
user1965449
77,715,073
22,466,650
How to select some values of a dataframe based on a list of coordinates?
<p>My inputs are a dataframe and a list of coodinates :</p> <pre><code>df = pd.DataFrame({ 'col1': ['A', 'B', 'C', 'A', 'G'], 'col2': ['B', 'E', 'F', 'F', 'H'], 'col3': ['C', 'D', 'E', 'A', 'I']}) coords = [(2, 0), (3, 2)] </code></pre> <pre><code>print(df) col1 col2 col3 0 A B C 1 B E D 2 C...
<python><pandas>
2023-12-25 22:03:06
2
1,085
VERBOSE
77,715,017
9,669,142
multiprocessing uses all cores for the same code
<p>I have a list of tuples which are used inside a loop to perform some calculations. The calculations can take some time, hence I want to try to divide the tasks over multiple processing cores (to speed things up). Something goes wrong here.</p> <p>First of all: I checked the performance of each of the cores when I ru...
<python><multiprocessing>
2023-12-25 21:29:41
1
567
Fish1996
77,715,012
7,961,594
Multiple CSS Providers in Python GTK3
<p>I've read lots of posts about using CSS in GTK3 in Python, but I never really seemed to find anything about changing styles programmatically. Usually there is one big triple-quoted string that has all of the CSS definitions in it. But what if I want to change a single style programmatically in the code? If I modify ...
<python><css><gtk3>
2023-12-25 21:26:53
1
1,095
Jeff H
77,714,986
4,706,711
Why running a container via docker sdk in python I get different output compared to the actual command line?
<p>In a shell session I have run:</p> <pre><code> docker run --rm --net host busybox /bin/sh -c &quot;ip route get 1 | sed -n 's/^.*src \([0-9.]*\) .*$/\1/p'&quot; </code></pre> <p>The output of the command is:</p> <pre><code>10.0.2.15 </code></pre> <p>But for a utility script that interfaces docker directly using pyth...
<python><docker>
2023-12-25 21:11:36
2
10,444
Dimitrios Desyllas
77,714,963
3,381,280
Python access property from parent class
<p>I am following <a href="https://edube.org/learn/pe-2/queue-aka-fifo-part-2-1" rel="nofollow noreferrer">this tutorial</a> on Python Institute.</p> <p>I have three classes as shown below. The parent class Queue has put and get functions. The <em>get</em> function raises a QueueError if the queue is empty. The child c...
<python>
2023-12-25 21:00:49
1
467
kobosh
77,714,962
11,038,635
What is the purpose of END_FINALLY bytecode in older Python versions?
<p>Consider the following code:</p> <pre class="lang-py prettyprint-override"><code>try: helloworld() except: failure() </code></pre> <p>and its disassembly (this is in Python 2.7):</p> <pre><code> 1 0 SETUP_EXCEPT 11 (to 14) 2 3 LOAD_NAME 0 (helloworld) ...
<python><python-2.7><bytecode><cpython>
2023-12-25 21:00:16
1
482
musava_ribica
77,714,951
5,287,011
Create a dictionary inside of FOR loop and the Create a data frame
<p>I have a list of lists</p> <pre><code>tours = [[0, 4], [0, 5], [0, 6], [1, 13], [2, 0], [3, 8], [4, 9], [5, 10], [6, 7], [7, 1], [8, 2], [9, 3], [10, 11], [11, 14], [12, 0], [13, 12], [14, 0]] </code></pre> <p>I also have a dataframe <code>df</code>:</p> <pre><code> Node X Y Demand Profit 1 2 5...
<python><pandas><dataframe><list>
2023-12-25 20:53:32
2
3,209
Toly
77,714,801
12,349,101
Tkinter - Scrolling notebook tabs without expanding the window width
<p>I'm trying to make a tkinter window with tabs, and a text widget for each tabs. I ended up using this <a href="https://stackoverflow.com/a/59803188/12349101">answer</a> as basis. Started with this:</p> <pre class="lang-py prettyprint-override"><code>import tkinter as tk from tkinter import ttk tab_count = 1 def cr...
<python><tkinter><text><tabs>
2023-12-25 19:44:41
0
553
secemp9
77,714,644
4,601,931
Sudden issue with Python installation via Homebrew
<p>I have Python 3.12 and virtualenv 20.25.0, both installed via Homebrew. The last time I used my computer, virtualenv was functioning properly. The very next time I try to use <code>virtualenv</code>, I am greeted with this error:</p> <pre><code>&gt; $ virtualenv --version Traceback (most recent call last): File ...
<python><virtualenv><homebrew>
2023-12-25 18:38:51
1
5,324
user4601931
77,714,538
19,366,064
How to reuse AsyncClient fixture
<p>Here is a simple code snippet to demonstrate the problem, it seems that the fixture client is not properly injected into the testing functions.</p> <pre><code>from contextlib import asynccontextmanager from fastapi import FastAPI import asyncio from httpx import AsyncClient import pytest @asynccontextmanager async ...
<python><fastapi><httpx>
2023-12-25 17:50:03
0
544
Michael Xia
77,714,536
7,136,640
JSON parsing error when loading Firebase service account from .env file in Python
<p>I'm encountering an issue with parsing a Firebase service account stored in a .env file using Python. Here's my approach:</p> <pre><code>import firebase_admin from firebase_admin import credentials from dotenv import load_dotenv import os, json load_dotenv() firebase_config = os.getenv(&quot;FIREBASE_CONFIG&quot;) ...
<python><python-3.x><firebase><firebase-authentication><python-dotenv>
2023-12-25 17:49:21
1
345
Huzaifa Zahoor
77,714,534
3,679,377
kbar keyboard shortcuts troubleshooting
<p>I am trying to create a component for plotly dash using react-kbar.</p> <p>I am able to run it without any issues for the most part. However, for some reason, the keyboard shortcuts defined for the actions are not working. The keyboard shortcut for kbar itself is working fine (ctlr + k, escape), but the action short...
<python><reactjs><plotly>
2023-12-25 17:48:34
1
1,921
najeem
77,714,443
12,058,407
calculate date and time difference between 2 dates (& time) using robot framework
<p>Need to calculate date and time difference between 2 dates (&amp; time). one will be input in the format of 'm/d/yy h:m:s' and other is current date and time. I see methods like &quot;Subtract Date From Date&quot; &amp; &quot;Subtract Time From Date&quot; in robot framework documentation. But both are not working as...
<javascript><python><selenium-webdriver><robotframework>
2023-12-25 17:14:29
4
307
Balaji211
77,714,338
15,893,581
why my Linear Least-Squares does not fit right the data-points
<p>I'm getting not very fitted 2D-plane with such a code:</p> <pre><code>import numpy as np from scipy import linalg as la from scipy.linalg import solve # data f1 = np.array([1., 1.5, 3.5, 4.]) f2 = np.array([3., 4., 7., 7.25]) # z = np.array([6., 6.5, 8., 9.]) A= X= np.array([f1, f2]).T b= y= np.array([0.5, 1., 1....
<python><scipy><least-squares><matrix-factorization>
2023-12-25 16:41:49
1
645
JeeyCi
77,714,037
7,862,953
python sort groupby data by key/function
<p>I would like to sort the data by the month however not alphabetically rather by the month order, i.e first the sales for January and then February etc, see the illustrated data I created</p> <pre><code>month=['January','February','March','April','January','February','March','April'] sales=[10,100,130,145,13409,670,5...
<python><pandas><sorting>
2023-12-25 14:50:36
3
537
zachi
77,713,818
2,952,838
pip/pipx installation and adding path
<p>I run <a href="https://en.wikipedia.org/wiki/Debian#Forks_and_derivatives" rel="nofollow noreferrer">Debian Stable</a> on my box, and I want to install the <a href="https://github.com/binance/binance-connector-python" rel="nofollow noreferrer">Binance connector</a> library to query <a href="https://en.wikipedia.org/...
<python><pip><debian><binance><pipx>
2023-12-25 13:27:08
1
1,543
larry77
77,713,438
5,594,008
Wagtail, can't add settings
<p>I'm trying to add custom settings to wagtail (version 4.0.4).</p> <p>Following the guide from the <a href="https://docs.wagtail.org/en/v4.0.4/reference/contrib/settings.html" rel="nofollow noreferrer">docs</a>, I added <code>wagtail.contrib.settings</code> to INSTALLED_APPS and added this to <em>models.py</em>:</p> ...
<python><django><wagtail><django-cms>
2023-12-25 11:07:27
1
2,352
Headmaster
77,713,384
12,285,101
nbdev_export ; pip install doesn't work on nbdev with windows
<p>I have downloaded nbdev based on [this tutorial][1] and [the help I got in this post][2]. Before I used nbdev on bash , but now unfortunately I have to work with windows. Now, I have two notebooks, and I want to import function from notebook1 to notebook2. In order to do this , when I used bash I run this command on...
<python><pip><windows-subsystem-for-linux><nbdev>
2023-12-25 10:43:39
1
1,592
Reut
77,713,103
20,176,161
Dataframe: Keep unique values in a list for each row
<p>I have a dataframe as follows:</p> <pre><code>Ville match Paris Talborjt,Talborjt,Ville Nouvelle Rome Hay Najah,Hay Najah,Najah </code></pre> <p>I would like to keep the unique values per row of the column match. The desired output is as follows:</p> <pre><code>Ville match cont...
<python><pandas><dataframe>
2023-12-25 09:07:06
1
419
bravopapa
77,713,072
1,985,409
How to accelerate assignment problem with ortools.linear_solver
<p>I am new to ortools.linear_solver, and built the follow code which assigns workers to tasks under the follow demands:</p> <ol> <li>I wish to find an assignment where the difference between worker with higher cost, and the one with lower cost is minimized.</li> <li>Each worker has one of the follow Ids (&quot;A&quot;...
<python><or-tools><cp-sat>
2023-12-25 08:57:30
1
671
audi02
77,712,635
8,509,235
How to disable border in subplot for a 3D plot in matplotlib
<p>I have the following code which produces two plots in matplotlib.</p> <p>However, each I'm unable to remove this border in the second subplot despite feeding all these arguments.</p> <p>How can I remove the black border around the second subplot (see attached image)</p> <pre class="lang-py prettyprint-override"><cod...
<python><numpy><matplotlib>
2023-12-25 05:59:48
1
666
Vivek Katial
77,712,413
90,506
Remove element from list if list of sub strings in list
<p>Fairly a newbie in Python3. Was wondering what the most efficient way is to accomplish this, i.e. if a directory listing contains a sub directory, then remove that item from the directory listing.</p> <pre><code>dirs = [ &quot;/mnt/user/dir1&quot;, &quot;/mnt/user/dir1/filea&quot;, &quot;/mnt/user/dir2&quot;, &quot;...
<python><python-3.x><python-3.8>
2023-12-25 03:45:07
1
1,581
farhany
77,712,392
21,305,238
Type alias for a union of two @runtime_checkable Protocols triggers mypy's "Cannot use parameterized generics in instance checks"
<p>Here's my code, simplified a lot (<a href="https://mypy-play.net/?flags=strict&amp;mypy=master&amp;python=3.12&amp;gist=02326c887487ca6c05e31867ddf66412" rel="nofollow noreferrer">playground</a>, <a href="https://mypy-play.net/?flags=strict&amp;mypy=master&amp;python=3.12&amp;gist=0b719a8f72ee21851b84492a81a78629" r...
<python><mypy><python-typing>
2023-12-25 03:34:26
1
12,143
InSync
77,712,334
8,497,844
Real size of directory with subdirectories and files on disk
<p>I need to create <code>img</code> container for archive some directories and files.</p> <p>For that I need to create it with <code>dd</code>. It's no problem but I can't create it 'cause I don't know real size of the some directories and files. As I understand <code>img</code> container don't support dynamic size.</...
<python>
2023-12-25 02:52:14
1
727
Pro
77,712,302
1,487,336
How to speed up `pandas.where`?
<p>I have two dataframes: <code>df1</code> with shape <code>(34, 1151649)</code>, <code>df2</code> with shape <code>(76, 3467)</code>. I would like to perform <code>pandas.where.groupby</code> operation on them. They are quite slow. I'm wondering is there's any way to speed up the code. A sample code is as follows.</p>...
<python><pandas>
2023-12-25 02:31:42
2
809
Lei Hao
77,712,087
6,467,736
Use python script to schedule several tasks in Windows Task Scheduler, then exit. Each task should generate Win toast notification. How to do?
<p>There is an online calendar of events. I will fetch the names, dates and times of these events. I then want to use python to pass these events to Windows Task Scheduler (running Win 10), then have the script exit. For each task, at the appropriate time, I want Task Scheduler to generate a Windows toast notification....
<python><toast><windows-task-scheduler>
2023-12-24 23:16:16
1
427
jub
77,711,996
453,673
How to display graphical information infinitely downward in Python?
<p>Example:<br /> <a href="https://i.sstatic.net/K4tUn.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/K4tUn.png" alt="enter image description here" /></a></p> <p>I need to display more rows like this (in the direction of the red arrow), with more of those squares. Along with the squares I could also use...
<python><matplotlib><pyqt>
2023-12-24 22:12:13
2
20,826
Nav
77,711,955
360,826
Pytorch parameters are not updating
<p>This seems to be a common question for folks who start using pytorch and I guess this one is my version of it.</p> <p>Is it clear to a more experienced pytorch user why my params are not updating as my code loops?</p> <pre><code>import torch import numpy as np np.random.seed(10) def optimize(final_shares: torch.T...
<python><pytorch>
2023-12-24 21:49:41
1
6,863
jason m
77,711,951
13,520,498
script using mediapipe breaks after making it executable with pyinstaller - FileNotFoundError: The path does not exist
<p>I made a desktop-application using <code>PyQT5</code> library. The main library that I am using is <code>opencv-python-headless</code>, <code>mediapipe</code> and <code>pyserial</code>. So, my python script does exactly what it should do and works perfectly. But after I make it executable with <code>pyinstaller</cod...
<python><pyinstaller><mediapipe>
2023-12-24 21:44:02
1
1,991
Musabbir Arrafi
77,711,768
5,675,229
No latest price for CCXT's fetch_ohlcv API
<p>I am using CCXT's fetch_ohlcv method to get the historical price of the coins. For a trading strategy I need to get the last N number timeframe of price records. Let's say if the timeframe is '15m' and N is 99, if the current time is 00:00, then I will need to extract the records starting from around 23:15 of the pr...
<python><cryptocurrency><ccxt>
2023-12-24 20:04:52
1
509
Wonderjimmy
77,711,708
11,009,696
Extracting text from a PDF - python
<p>I am new to Python and I am developing a program that takes a PDF file as input and converts it into text, I am using Python 3 and tried the PyPDF2 and PDFMiner.six packages.</p> <p>For the first PDF file it convert well and print it on console, but when I use another PDF file which contains some empty pages, it pri...
<python><pdf><pypdf><text-extraction><pdfminersix>
2023-12-24 19:41:30
0
1,800
Sana'a Al-ahdal
77,711,555
5,962,981
FASTapi doesn't handle Pydatnic validation error
<p>in FASTapi aplication I have a <code>model.py</code></p> <pre><code>class Testing(BaseModel): a: Optional[str] b: Optional[str] @root_validator(pre=True) def check_all_values(cls, values): if len(values) == 0: raise ValueError('Error...') return values <...
<python><fastapi><pydantic>
2023-12-24 18:35:51
1
923
filtertips
77,711,531
2,063,900
In odoo How to add search in Product Variants screen with a field in product template model
<p>I want to add a search in Product Variants list screen with a custom field, I am already added to the product.template model</p> <p>the field name is model_number and I added with this code</p> <pre><code>class ProductCoNew(models.Model): _inherit = 'product.template' model_number = fields.Char(string='Mode...
<python><odoo><odoo-16>
2023-12-24 18:28:19
1
361
ahmed mohamady
77,711,480
4,398,966
Python readline() bug, writes at eof
<p>In python3 it seems that there is a bug with the readline() method.</p> <p>I have a file txt.txt that contains two lines:</p> <pre><code>1234567890 abcdefghij </code></pre> <p>I then run the following code:</p> <pre><code>g = open(&quot;txt.txt&quot;,&quot;r+&quot;) g.write(&quot;xxx&quot;) g.flush() g.close() </cod...
<python><python-3.x><readline>
2023-12-24 18:10:39
1
15,782
DCR
77,711,443
1,473,517
How can I plot a ring shape instead of the whole circular part?
<p>This code plots a grid and then draws two circles of different sizes on it.</p> <pre><code>from math import sqrt # Calculate the center coordinates and add blue dots for x in np.arange(0.5, 10, 1): for y in np.arange(0.5, 10, 1): plt.scatter(x, y, color='blue', s=10) # Adjust the size (s) as needed ...
<python><matplotlib>
2023-12-24 17:58:38
1
21,513
Simd
77,711,415
10,922,372
FastAPI - Unable to test error responses with custom error handler
<p>In FastAPI 0.104.1, I have this custom error handler:</p> <p><em>main.py:</em></p> <pre><code>def create_app() -&gt; FastAPI: app = FastAPI() @app.exception_handler(Exception) async def api_exception_handler(request: Request, exc: Exception): if isinstance(exc, APIException): # APIException ins...
<python><pytest><fastapi>
2023-12-24 17:47:07
1
1,010
Gonzalo Dambra
77,711,328
15,835,974
How can I resolve circular references between two class in Python?
<p>I have 2 python class that depend on each other (a circular dependency)</p> <ol> <li>The class <code>FontFile</code> can contain multiple <code>FontFace</code> (1 to n).</li> <li>The class <code>FontFace</code> contain 1 <code>FontFile</code>.</li> </ol> <p>Should I refactor the code so there isn't a circular refere...
<python><circular-reference>
2023-12-24 17:13:09
1
597
jeremie bergeron
77,711,315
7,290,715
Pandas: get the difference from the previous row for a given column value
<p>I have a dataframe like below:</p> <pre><code>countryname yr US_Election_Year id_score Dem_Score Albania 1992 1990 0.688809 0.366570 Albania 1997 1996 0.024751 0.247750 Argentina 1995 1992 0.081818 ...
<python><pandas>
2023-12-24 17:07:33
3
1,259
pythondumb
77,711,295
12,035,877
Getting real time data for a set of symbols from BINANCE API
<p>I'm trying to retrieve the latest information about a set of Binance symbols every, say, 15 seconds, using the <code>binance-connector-python</code> library.</p> <p>For example: <code>pairs=['BTCUSDT','ETHUSDT',...]</code></p> <p>I can do it by using:</p> <pre><code>info=[spot_client.klines(pair, &quot;1s&quot;, lim...
<python><binance><cryptocurrency>
2023-12-24 17:00:32
0
547
José Chamorro
77,711,250
20,830,264
Deploying Django project in an Amazon EC2 Ubuntu instance
<p>I have developed a Django website and hosted the application in an Amazon EC2 instance. AMI name: ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-20231207 Instance type: t2.micro</p> <p>I run the project following these steps:</p> <ol> <li>SSH into the EC2 instance from my terminal.</li> <li>I locate into the ...
<python><django><amazon-web-services><amazon-ec2>
2023-12-24 16:42:15
3
315
Gregory
77,711,209
4,458,718
TextIOWrapper gzip buffer dropping records at the end even with flush
<p>I'm having an issue where writing to the gzip buffer drops records at the end.</p> <pre><code>print(f'Data has {len(data)} rows') try: with gzip.GzipFile(mode=&quot;w&quot;, fileobj=gz_buffer) as gz_file: writer = csv.DictWriter(TextIOWrapper(gz_file, &quot;utf8&quot;), fieldnames=data[0].ke...
<python><io><gzip>
2023-12-24 16:27:03
1
1,931
L Xandor
77,711,076
12,858,691
Print/log everything that pandas.testing.assert_frame_equal() finds
<p>Consider the following test. Its purpose is to detect - given a tolerance - any differences between two dataframes.</p> <pre><code>import pandas as pd def test_two_cubes_linewise() -&gt; None: df1 = pd.DataFrame({&quot;A&quot;: [1, 2, 3, 4, 5.0], &quot;B&quot;: [4, 5, 6, 7, 8.0001]}) df2 = pd.DataFrame({&qu...
<python><pandas>
2023-12-24 15:29:56
1
611
Viktor
77,711,045
353,497
LLM RAG with Agent
<p>I was trying the application code in the <a href="https://python.langchain.com/docs/use_cases/question_answering/conversational_retrieval_agents" rel="nofollow noreferrer">link</a>.</p> <p>I am using the following Llang Chain version</p> <p>langchain 0.0.327 langchain-community ...
<python><large-language-model>
2023-12-24 15:20:03
3
1,990
Ameya
77,710,890
1,064,197
Parse table of divs on a website. that doesn't follow standard th & tr format
<p>I am trying to parse the table of predictions here but <a href="https://theanalyst.com/na/2023/08/opta-football-predictions/" rel="nofollow noreferrer">https://theanalyst.com/na/2023/08/opta-football-predictions/</a></p> <p>However, I am struggling to parse the divs table. I find_all(&quot;tr&quot;) and getting th...
<python><selenium-webdriver><web-scraping><beautifulsoup>
2023-12-24 14:16:37
1
2,625
Michael WS
77,710,813
2,482,149
Psycopg3 - no pq wrapper available
<p>I am facing this error when I try to run psycopg3 on AWS Lambda.</p> <pre><code>[ERROR] Runtime.ImportModuleError: Unable to import module 'function': no pq wrapper available. Attempts made: - couldn't import psycopg 'c' implementation: No module named 'psycopg_c' - couldn't import psycopg 'binary' implementation: N...
<python><postgresql><aws-lambda><psycopg2><psycopg3>
2023-12-24 13:40:38
2
1,226
clattenburg cake
77,710,768
1,682,699
Getting constrained layout to work with nested subplots in Matplotlib
<p>I'm trying to create nested subplots in Matplotlib, where each plot is produced by a function that takes an <code>axis</code> object as an argument. Some of the plot functions can create subplots of their own.</p> <p>This simple example works:</p> <pre class="lang-py prettyprint-override"><code>def myplot(ax): g...
<python><matplotlib>
2023-12-24 13:24:03
0
507
roberto
77,710,609
85,837
Creating an SQLDatabase using schema file instead of URI
<p>Currently experimenting with the SQLDatabaseChain were the end result would be to generate the SQL statesmen, not running the query</p> <p>Is there a way to create SQLDatabase from schema file, hence avoiding giving the SQLDatabase actual connection to the database?</p> <p>Is it possible to not use the SQLDatabase...
<python><langchain><py-langchain>
2023-12-24 12:23:42
1
321
eLAN
77,710,362
1,028,679
Streaming results of a large db query in FastAPI takes too long
<p>We have a tiny FastAPI deployed in Fargate Cluster, and the task is set to use 16vCPU's and 32GB Ram.</p> <p>It queries data from Aurora, on a single table which has millions of records.</p> <p>This is the code:</p> <pre class="lang-py prettyprint-override"><code>@trade_router.get('/trades') def read_item(symbol: st...
<python><postgresql><amazon-web-services><fastapi><aws-fargate>
2023-12-24 10:48:40
0
5,571
rmcsharry
77,710,202
1,959,753
Does Python optimize key-value pairs with None values?
<p>Consider a dict with an int key and dict value, where the value features string keys and further dict values.</p> <p>Now consider these 2 representations of this dict:</p> <pre><code>&gt;&gt;&gt; a_it_1 { 1: {&quot;it&quot;: None, &quot;ndar&quot;: {1:1}, 2: {&quot;it&quot;: {2:8}, &quot;ndar&quot;: None} } &gt;&gt;...
<python><dictionary-comprehension>
2023-12-24 09:49:45
1
736
Jurgen Cuschieri
77,710,146
7,695,845
How to request the latest core OpenGL profile with GLFW?
<p>I am new to OpenGL and GLFW, and I wanted to make a little graphics engine in Python using the GLFW Python bindings and the <a href="https://moderngl.readthedocs.io/en/5.8.2/" rel="nofollow noreferrer">moderngl</a> library to get an OpenGL context. From the <a href="https://www.glfw.org/docs/3.3/window_guide.html#wi...
<python><opengl><glfw>
2023-12-24 09:21:22
1
1,420
Shai Avr
77,710,143
2,417,709
What is the best way to retrieve data each second from sqlite table (at the same time inserting the rows to the same table in other thread)
<p>I'm using sqlite database to store tick data in a table, at the same time I have a requirement to fetch the data each second from the table.</p> <p>I have written following sample code in python to test this.</p> <pre><code>def get_ltp(): query = &quot;&quot;&quot;select * from test order by rowid desc LIMIT 1&q...
<python><sqlite>
2023-12-24 09:20:51
0
311
Naga
77,710,089
17,596,179
login with superuser nog working in django admin panel
<p>So I built this custom auth model because I want to use the email instead of the username field which is default for django.</p> <pre><code>AUTH_USER_MODEL = 'customers.Customers' </code></pre> <p>This I have in my <code>settings.py</code></p> <pre><code>from django.utils import timezone from django.db import models...
<python><django><django-models><django-authentication><django-auth-models>
2023-12-24 08:49:47
1
437
david backx
77,710,075
23,106,915
libcairo-2.dll or libcairo library not found
<p>I created a tkinter project which shows user-data analysis using pygal graph plotter. The graph is using a library to render the png file called cairosvg. I am facing the following issue when running the code:</p> <pre><code>OSError: no library called &quot;cairo-2&quot; was found no library called &quot;cairo&quot;...
<python><python-3.x><cairo><pycairo><pygal>
2023-12-24 08:44:24
0
546
AshhadDevLab
77,709,826
2,568,647
Keras model suddenly started outputting Tensors. How to revert that?
<p>So I was learning DQNs trying to solve Cart Pole env:</p> <pre><code>import gymnasium as gym import numpy as np from rl.agents import DQNAgent from rl.memory import SequentialMemory from rl.policy import BoltzmannQPolicy from tensorflow.python.keras.layers import InputLayer, Dense from tensorflow.python.keras.models...
<python><tensorflow><keras><reinforcement-learning><dqn>
2023-12-24 06:10:49
1
1,117
sleexed
77,709,752
12,104,604
When using string shared memory in Python's multiprocessing alongside Kivy, it causes an error
<p>I have tried using <strong>shared memory for strings with the following simple Python code, and it works well</strong>.</p> <pre><code>from multiprocessing import Value, Array, Process, Lock def process1(array, lock): with lock: buffer_data = str(&quot;z1111&quot;).encode(&quot;utf-8&quot;) arr...
<python><multiprocessing><kivy><shared-memory>
2023-12-24 05:26:55
1
683
taichi
77,709,546
12,461,032
Pyspark RAM leakage
<p>My spark codes recently causes ram leakage. For instance, before running any script, when I run top, I can see 251 GB total memory and 230 GB free + used memory.</p> <p>When I run my spark job through <code>spark-submit</code>, regardless of whether the job is completed or not (ending with exception) the free + used...
<python><apache-spark><pyspark>
2023-12-24 02:43:10
1
472
m0ss
77,709,426
899,573
Media player error Exception occurred during processing of request
<p>I have a simple HTML media player like following,</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt; &lt;title&gt;Sample Media Player&lt...
<python><html><html5-video><media-player><video-codecs>
2023-12-24 00:51:09
0
12,959
Johnykutty
77,709,402
1,126,944
Does the "object" here refer to the object class
<p>I saw in the Python documentation for defining an emulating container type <a href="https://docs.python.org/3/reference/datamodel.html#emulating-container-types" rel="nofollow noreferrer">https://docs.python.org/3/reference/datamodel.html#emulating-container-types</a>, it states:</p> <blockquote> <p><strong>object.<...
<python><python-3.x><language-lawyer>
2023-12-24 00:34:03
2
1,330
IcyBrk
77,709,363
9,315,690
Why does having a `packages` property in pyproject.toml affect mypy's behaviour?
<p>I've been having the issue that Mypy suddenly no longer type checks the contents of my imports, even though they are in the same source tree. After bisecting the issue, I figured out that the cause was the addition of the <code>packages</code> line to my pyproject.toml file by a co-worker. He claims it must be there...
<python><mypy><python-poetry><pyproject.toml>
2023-12-24 00:03:25
0
3,887
Newbyte
77,709,350
3,761,310
How can I convert this Python code into a SQLAlchemy query?
<p>I'm building a data dashboard for a project where players field a certain position within a game. Players can also field multiple positions in a single game. The dashboard needs the following data:</p> <ul> <li>Each player in the Player table</li> <li>The number of games that player has appeared in, regardless of wh...
<python><sqlalchemy><subquery><querying>
2023-12-23 23:53:38
0
718
DukeSilver
77,709,215
2,671,049
ezdxf -- transform undefined EPSG 3395 latitude longitude decimal degrees coordinates to WCS coordinates to save revised DXF file
<p><strong>UPDATE 26 December 2023</strong></p> <p>The <code>DXF</code> file was created via the Export Project to DXF function in QGIS 3.34. Although the exported <code>DXF</code> was set to EPSG 3395, that designation is not set in the <code>dxf.coordinate_type</code>. The answer by mozman and the previously displaye...
<python><latitude-longitude><dxf><ezdxf>
2023-12-23 22:29:44
1
944
iembry
77,709,156
5,938,276
Check if float result is close to one of the expected values
<p>I have a function in Python makes a number of calculations and returns a float.</p> <p>I need to validate the float result is close (i.e. +/- 1) to one of 4 possible integers.</p> <p>For example the expected integers are 20, 50, 80, 100.</p> <p>If I have <code>result = 19.808954</code> if would pass the validation t...
<python><math>
2023-12-23 21:52:29
1
2,456
Al Grant
77,708,882
7,391,480
Change first and last elements of strings or lists inside a dataframe
<p>I have a dataframe like this:</p> <pre><code>data = { 'name': ['101 blueberry 2023', '102 big cat 2023', '103 small white dog 2023'], 'number': [116, 118, 119]} df = pd.DataFrame(data) df </code></pre> <p>output:</p> <pre><code> name number 0 101 blueberry 2023 116...
<python><pandas><dataframe><list>
2023-12-23 20:02:42
5
1,364
edge-case
77,708,843
6,357,916
Reading opencv yaml in python gives error "Input file is invalid in function 'open'"
<p>I have following test.yaml:</p> <pre><code>Camera.ColourOrder: &quot;RGB&quot; Camera.ColourDepth: &quot;UCHAR_8&quot; Camera.Spectrum: &quot;Visible_NearIR&quot; IMU.T_b_c1: !!opencv-matrix rows: 4 cols: 4 dt: f data: [0.999903, -0.0138036, -0.00208099, -0.0202141, 0.0137985, 0.999902, -0.00243...
<python><opencv><yaml>
2023-12-23 19:44:35
1
3,029
MsA
77,708,621
3,697,344
Unable to connect to postgres instance when flask app Dockerfile in different directory
<p>I have a project structure like this</p> <pre><code>project-root/ back/ Dockerfile docker-compose.yaml .env </code></pre> <p>Where <code>docker-compose.yaml</code> has</p> <pre><code>services: postgres: image: postgres:latest restart: always environment: POSTGRES_USER: ${POSTGR...
<python><postgresql><docker><flask><docker-compose>
2023-12-23 18:28:35
1
301
user3697344
77,708,557
2,205,916
Python Tensorflow.keras LSTM: TypeError: `generator` yielded an element of shape (36, 36, 147) where an element of shape (36, 147) was expected
<p>I've been struggling with the following code for some time now.</p> <p>Basically, I'm getting either of the following two errors, depending on my adjustments:</p> <p><code>TypeError: </code>generator<code> yielded an element of shape (36, 36, 147) where an element of shape (36, 147) was expected.</code></p> <p>and</...
<python><tensorflow><machine-learning><keras><deep-learning>
2023-12-23 18:05:26
0
3,476
user2205916
77,708,463
22,466,650
How to pick slices of groups and complete some if necessary?
<p>My input is a dataframe :</p> <pre><code>df = pd.DataFrame({'mycol': ['A', 'B', 'A', 'B', 'B', 'C', 'A', 'C', 'A', 'A']}) print(df) mycol 0 A 1 B 2 A 3 B 4 B 5 C 6 A 7 C 8 A 9 A </code></pre> <p><code>A</code> appear 5 times, <code>B</code> appear 3 times and <code>C</code...
<python><pandas>
2023-12-23 17:30:51
2
1,085
VERBOSE
77,708,267
1,874,170
Multiple byte "OUTPUT" arguments in SWIG?
<p>I've got a C library which has 3 functions (all arguments are fixed-length <code>uint8_t*</code>, with the length known at compile time):</p> <ul> <li>One which has 2 output parameters only</li> <li>One which has 1 input parameter and 2 output parameters</li> <li>One which has 2 input parameters and 1 output paramet...
<python><swig><swig-typemap>
2023-12-23 16:15:31
1
1,117
JamesTheAwesomeDude
77,708,266
1,473,517
Speed-up for finding an optimal partition line
<p>This coding question derived from this <a href="https://codegolf.stackexchange.com/questions/268581/finding-the-optimal-straight-line-boundary">question</a>.</p> <p>Consider an n by n grid of integers. The task is to draw a straight line across the grid so that the part that includes the top left corner sums to the ...
<python><algorithm><performance><optimization>
2023-12-23 16:15:30
2
21,513
Simd
77,708,146
5,540,159
My autoencoder was not learning to predict value [Updated]
<p>I am trying to work on building a variational autoencoder in Keras, with an input shape of X= (1,50) and Y= (1,20).</p> <p>I have uploaded the DataSet, <a href="https://www.dropbox.com/scl/fi/tp3dr1dxdml454zjuepin/DataSet.rar?rlkey=wazw1m29ck4400x6fg5aetl2z&amp;dl=0" rel="nofollow noreferrer">you can download it fro...
<python><keras><deep-learning><neural-network>
2023-12-23 15:33:28
1
962
stevGates
77,707,957
519,422
How to preserve whitespace in the "name" part of a name/value pair when importing JSON-formatted data (Python)?
<p>I have been asking for help in importing JSON-formatted data from URLs (I am a newbie as far as dealing with JSON) and received a great answer in response to <a href="https://stackoverflow.com/questions/77681060/how-to-get-json-formatted-data-from-a-website-into-a-dataframe-i-e-extract-va/77681349#77681349">this</a>...
<python><json><python-3.x><pandas><file-io>
2023-12-23 14:29:14
2
897
Ant
77,707,880
16,748,945
How to groupby a multiindex dataframe with different rules on different levels?
<p>If I have a dataframe like</p> <pre><code>In [58]: arrays = [ ....: [&quot;bar&quot;, &quot;bar&quot;, &quot;baz&quot;, &quot;baz&quot;, &quot;foo&quot;, &quot;foo&quot;, &quot;qux&quot;, &quot;qux&quot;], ....: [&quot;one1&quot;, &quot;one2&quot;, &quot;one1&quot;, &quot;one2&quot;, &quot;one1&quot;, ...
<python><dataframe><group-by>
2023-12-23 14:03:19
1
665
f1msch
77,707,742
893,254
How to perform insert statements with SQL Alchemy in a structured way?
<p>I do not know if the following is possible with SQL Alchemy and Python.</p> <p>My objective is to perform an insert statement in a more structured way, using some kind of object as a row.</p> <p>Some pseduocode might look like this:</p> <pre><code># SQL: # # create table test_table ( # id bigserial not null, # v...
<python><sqlalchemy>
2023-12-23 13:11:25
0
18,579
user2138149
77,707,689
1,283,836
python-docx: matching an lxml element using xpath
<p>I'm trying to access the underlying <code>lxml</code> data of a cell of a table in a docx file using <a href="https://pypi.org/project/python-docx/" rel="nofollow noreferrer">python-docx</a> library in order to change the <code>val</code> attribute of an element.</p> <pre><code>from docx import Document doc = Docum...
<python><xpath><lxml><python-docx>
2023-12-23 12:52:16
0
2,093
wiki
77,707,610
102,315
Collapse edges in NetworkX
<p>Is this really the best way to collapse edges in NetworkX?</p> <pre class="lang-py prettyprint-override"><code>n = list(G.neighbors(node)) new_weight = G[node][n[0]]['weight'] + G[node][n[1]]['weight'] G.add_edge(n[0], n[1], weight=new_weight) G.remove_edges_from(G[node]) G.remove_node(node) </code></pre> <p>It's ...
<python><networkx>
2023-12-23 12:20:38
1
4,061
Alper
77,707,524
1,473,517
How to remove redundancy when computing sums for many rings
<p>I have this code to compute the sum of the values in a matrix that are closer than some distance but further away than another. Here is the code with some example data:</p> <pre><code>square = [[ 3, 0, 1, 3, -1, 1, 1, 3, -2, -1], [ 3, -1, -1, 1, 0, -1, 2, 1, -2, 0], [ 2, 2, -2, 0, 1, -3, 0, -2, ...
<python><algorithm><optimization>
2023-12-23 11:50:58
3
21,513
Simd