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,767,645
10,737,147
Matplotlib event handling within a class
<p>Could someone please shed some light on this?</p> <p>This code is supposed to print out the event details on a mouse button press. If I connect the <code>button_press_event</code> slot to <code>on_button_press</code> (outside the class), the code works as expected. If I instead use the class method <code>self.on_but...
<python><matplotlib><events>
2024-01-05 23:19:22
1
437
XYZ
77,767,585
247,542
How to add organization access to Google Drive folder?
<p>How do you programmatically grant access to everyone in an organization to a shared folder on Google Drive using the v3 Drive Python API?</p> <p><a href="https://developers.google.com/drive/api/guides/manage-shareddrives" rel="nofollow noreferrer">These docs</a> clearly explain how to grant access to a specific user...
<python><google-drive-api><google-drive-shared-drive>
2024-01-05 23:00:51
1
65,489
Cerin
77,767,517
3,671,543
Combine rows and columns to create a 2x2 table for Fisher's exact test
<p>I need to perform a test of independence on the following crosstab <code>ct</code> using python:</p> <p><a href="https://i.sstatic.net/YPr8A.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/YPr8A.png" alt="enter image description here" /></a></p> <p>Since there are some values less than 5, I cannot per...
<python><scipy><statistics><data-analysis>
2024-01-05 22:36:27
2
689
Oussema Chaabouni
77,767,450
2,893,712
APScheduler Runs Job Twice
<p>I have an APScheduler job that I want to run on Friday's at 8:05am with a jitter of 15minutes. Here is my code:</p> <pre><code>from apscheduler.schedulers.background import BackgroundScheduler sched = BackgroundScheduler() def WOL(): requests.get(&quot;https://example.com/WOL&quot;) sched.add_job(WOL, 'cron', ...
<python><cron><apscheduler>
2024-01-05 22:13:59
0
8,806
Bijan
77,767,405
10,200,497
Creating a new column when values in another column is not duplicate
<p>This is my DataFrame:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame( { 'a': [98, 97, 100, 101, 103, 110, 108, 109, 130, 135], 'b': [3, 3, 3, 3, 3, 3, 3, 3, 3, 3], 'c': [np.nan, np.nan, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 3.0, 3.0], 'd': [92, 92, 92, 92, 92, 92, 92...
<python><pandas><dataframe>
2024-01-05 22:00:40
2
2,679
AmirX
77,767,299
21,420,742
Getting the names separated into own columns in python
<p>I have a dataset that I need to separate the names into <code>first name</code> <code>middle name</code> and <code>last name</code> issue I am having is on some occasions people have two last/middle names or spaces creating lager names. This is a sample of what I have:</p> <pre><code>name John Smith Jack A Doe Ja...
<python><python-3.x><pandas><dataframe>
2024-01-05 21:28:53
4
473
Coding_Nubie
77,767,278
15,412,256
Complex One-Hot Encoding Dummies Generation From Lists
<p>I have a pandas DataFrame like this:</p> <pre class="lang-py prettyprint-override"><code> username Category 0 user1 [&quot;stackoverflow&quot;, &quot;cross_validted&quot;] 1 user2 [] 2 user3 [&quot;stackoverflow&quot;] </code></pre> <p>I want to generate the binary dummy columns for eac...
<python><pandas><encoding><aggregation-framework>
2024-01-05 21:22:24
0
649
Kevin Li
77,767,224
12,553,730
Do I use the `--hyp` for training YOLO-v5 model with Albumentations?
<p>I have integrated various <em>Albumentations</em> into my YOLO-v5 model by modifying the <code>augmentations.py</code> file. In the <em>Albumentations</em> class, I have included a list of transformations.</p> <p>Here is my code in the Albumentations class(<code>/utils/augmentations.py</code>):</p> <pre><code>class ...
<python><python-3.x><yolo><yolov5>
2024-01-05 21:07:19
1
309
nikhil int
77,767,157
4,343,563
Python Create new row for each value within lists in two columns?
<p>I am trying to compare the values of a list within two columns so I would like to create a separate row for each list index in that column where the row name contains the index of the list. My dataframe looks like:</p> <pre><code> File Color File Value True Value 1 blue ['123',...
<python><pandas>
2024-01-05 20:49:55
2
700
mjoy
77,767,005
6,395,618
Tensorflow Out Of Range while saving weights
<p>I am getting <code>OutOfRangeError</code> when I am trying to save weights and don't necessarily know why. The model seems to be of the size <strong>674.82 MB</strong> and I have <strong>1 TB</strong> hard-disk size on my instance. So, I can't figure why I am getting this error. Below is my model and code to save we...
<python><tensorflow><keras><deep-learning>
2024-01-05 20:18:10
0
2,606
Krishnang K Dalal
77,766,938
836,941
is it possible to build a tree form expanded Airflow DAG tasks? (dynamic task mapping over dynamic task mapping output)
<p>I want to generate dynamic tasks from the dynamic task output. Each mapped task returns a list, and I'd like to create a separate mapped task for each of the element of the list so the process will look like this: <a href="https://i.sstatic.net/qApiz.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/qAp...
<python><airflow><airflow-2.x>
2024-01-05 20:01:15
1
8,862
zacheusz
77,766,843
2,142,728
Coroutines started with asyncio.create_task not running when followed by time.sleep - Why?
<p>I'm facing an issue with coroutines in Python's asyncio module. I've noticed that coroutines started with asyncio.create_task seem to not run as expected when I introduce a time.sleep immediately after starting them. I'm puzzled by this behavior and would appreciate some insights into why this might be happening.</p...
<python><python-asyncio>
2024-01-05 19:40:20
1
3,774
caeus
77,766,721
8,040,369
DataFrame: Convert the columns in a df to list of row in Python dataframe
<p>I have a pandas dataframe like below</p> <pre><code>id name value1 value2 value3 Type ======================================================= 1 AAA 1.0 1.5 1.8 NEW 2 BBB 2.0 2.3 2.5 NEW 3 CCC 3.0 3.6 3.7 NEW </code><...
<python><pandas><dataframe>
2024-01-05 19:11:10
4
787
SM079
77,766,597
8,040,369
DataFrame: Transform a DF rows into a key with list of value pairs in Python
<p>I have a pandas dataframe like below</p> <pre><code>id name value1 value2 value3 ======================================================= 1 AAA 1.0 1.5 1.8 2 BBB 2.0 2.3 2.5 3 CCC 3.0 3.6 3.7 </code></pre> <p>I have convert the above df...
<python><pandas>
2024-01-05 18:41:51
1
787
SM079
77,766,570
696,206
What is the proper Pythonic Approach to Collection.forEach?
<p>I inevitably end up writing a lot of functions that look something along the lines of</p> <pre class="lang-py prettyprint-override"><code>def forEach(function: typing.Callable, collection: typing.Iterable) -&gt; typing.NoReturn: for item in collection: function(item) </code></pre> <p>Just about every lan...
<python><list>
2024-01-05 18:36:05
1
715
Tubbs
77,766,567
2,437,443
SQLAlchemy / Python - SSL errors: "decryption failed or bad record mac" | "EOF detected"
<p>I have a Flask Python application where I'm using the multiprocessing library to execute a function in parallel with the main thread. The purpose of the function is to upload files to OneDrive. The function also needs to read and write from my DB.</p> <p>My app uses a PostgreSQL database and SQLAlchemy. In order to ...
<python><flask><sqlalchemy><python-multiprocessing><psycopg2>
2024-01-05 18:35:12
1
2,297
user2437443
77,766,301
1,441,053
Polars DataFrame enum and categorical type memory usage
<p>When I call <code>df.estimated_size()</code> on a <code>Categorical</code> or <code>Enum</code> column, it appears to have the same memory footprint as an <code>int32</code> of the same length, even though there are only four members in the category.</p> <p>Is this memory size accurate? <code>shrink_to_fit()</code> ...
<python><python-polars>
2024-01-05 17:37:46
1
802
user1441053
77,766,233
2,381,348
python subprocess.run with awk failing
<p><strong>My function:</strong></p> <pre><code>def run(cmd = &quot;&quot;): sp = subprocess.run(shlex.split(cmd), shell = False, capture_output = True) pprint(sp) print(sp.stdout.decode(&quot;utf-8&quot;, 'ignore')) </code></pre> <p>This function was working normally. Then I suddenly came across <code>awk<...
<python><awk><subprocess>
2024-01-05 17:23:19
0
3,551
RatDon
77,766,180
2,379,009
Adding scatter animations across frames in plotly
<p>I want to add scatter points over an animation i am doing w/ px.imshow:</p> <pre><code># video is a [n_frames, height, width, 3] array fig = px.imshow(video, animation_frame=0, binary_string=True, height=height) for i in range(video .shape[0]): str_plot = go.Scatter(x=[kp1[0, i], kp2[0, i]], y=[kp1[1, i], kp2[1,...
<python><animation><plotly><plotly-express>
2024-01-05 17:14:27
0
2,173
DankMasterDan
77,766,158
17,176,270
Cannot render a value to html from FastAPI JSONResponse with HTMX
<p>I'm making a concept of a client for API service running FastAPI. I need Fast API to serve API and HTML by different endpoints.</p> <p>My FastAPI code:</p> <pre><code>from fastapi import FastAPI, Request from fastapi.responses import HTMLResponse, JSONResponse from fastapi.templating import Jinja2Templates app = Fa...
<python><jinja2><fastapi><htmx>
2024-01-05 17:10:06
1
780
Vitalii Mytenko
77,766,049
893,254
Clarification of the parameter "alpha"
<p>The Pandas <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.ewm.html" rel="nofollow noreferrer"><code>ewm</code></a> function (Exponentially Weighted Moving Average/Stddev/etc.) takes a parameter <code>alpha</code>.</p> <p>If I understand the intent correctly, this parameter <code>alpha</code> ...
<python><pandas>
2024-01-05 16:48:16
1
18,579
user2138149
77,766,048
1,473,517
Getting a very simple stablebaselines3 example to work
<p>I tried to model the simplest coin flipping game where you have to predict if it is going to be a head. Sadly it won't run, given me:</p> <pre><code>Using cpu device Traceback (most recent call last): File &quot;/home/user/python/simplegame.py&quot;, line 40, in &lt;module&gt; model.learn(total_timesteps=100...
<python><machine-learning><reinforcement-learning><openai-gym><stable-baselines>
2024-01-05 16:47:55
2
21,513
Simd
77,765,955
3,159,288
VSCode - Renaming Symbol Skips Test Files in Python Project
<p>In my Python project, when I use VSCode to <a href="https://code.visualstudio.com/docs/editor/refactoring#_rename-symbol" rel="nofollow noreferrer">rename a symbol</a> the change is not propagated to &quot;test files&quot;. More specifically, if a <code>.py</code> file lives in a directory named <code>test</code> or...
<python><visual-studio-code>
2024-01-05 16:28:54
0
852
rmorshea
77,765,919
519,422
Pandas dataframe: writing specific values to a file with specific formatting?
<p>I want to update external files. I want to do this by writing new data from Pandas dataframes to the files in a particular format.</p> <p>Here is an example of the first two blocks of data in a file (what I want my new data from the dataframes to look like when I write the data to the files). &quot;<code>identifie...
<python><python-3.x><regex><dataframe><file-io>
2024-01-05 16:21:27
1
897
Ant
77,765,887
13,496,839
convert *.py to *.Pyd and getting a no module error in import?
<p>I have a Cython file (main_file_001.pyx) located at d:/exe_project/all_files/python_files/. I am attempting to compile this Cython file into a Python extension module and import it into another program. However, I'm encountering difficulties in the import process.</p> <pre><code>try: from setuptools import setup...
<python><python-3.x><cython><cythonize>
2024-01-05 16:15:45
0
686
Bala
77,765,806
11,431,171
FastAPI Application Deployment on Azure App Service: 503 Service Unavailable Error
<p><strong>Issue Summary:</strong> I am experiencing a 503 Service Unavailable error when deploying a FastAPI application on Azure App Service (Linux). The application runs fine locally but encounters issues when deployed to Azure.</p> <p><strong>Environment:</strong></p> <p>FastAPI version: 0.108.0 Gunicorn version: 2...
<python><azure><azure-web-app-service><fastapi>
2024-01-05 15:58:59
1
501
fortanu82
77,765,751
7,766,158
Handling asyncronous function in a loop
<p>I have the following code :</p> <pre><code>async def async_function(): await some_function() # TODO : Doesn't work def sync_function(): for i in range (100): async_function() </code></pre> <p>In the past I had no loop in <code>sync_function</code>, so I managed to call <code>async_function</code> u...
<python><python-asyncio>
2024-01-05 15:49:18
1
1,931
Nakeuh
77,765,572
15,991,297
Check if Value Greater than Previous Row by Group
<p>With the dataframe below I want to compare the values in Val1 with the value in the preceding row by group. I then want to create a new column containing the word &quot;Abv&quot; if the value is greater than the preceding row and &quot;Blw&quot; if the value is lower than the predecing row. If the values are equal t...
<python><pandas><numpy>
2024-01-05 15:16:57
1
500
James
77,765,509
2,102,025
Pandas dataframe: find closest time before timestamp
<p>I have two Pandas dataframes with &quot;datetime&quot; column.</p> <p>For the <code>df</code> dataframe I would like to add a column with the seconds-difference with the nearest <code>dflogdf[&quot;datetime&quot;]</code> BEFORE the <code>df[&quot;datetime&quot;]</code>. This means I cannot use <code>merge_asof direc...
<python><pandas>
2024-01-05 15:05:22
1
579
Scripter
77,765,417
14,839,602
Write text to a text file in RTL format
<p>I have an array of text, I want to write it to a .txt file from right to left since it is in Arabic or Kurdish. How can I do that using python?</p> <p><strong>Method to write to a file:</strong></p> <pre><code>with open(current_extracted_text_output_path, 'w', encoding='utf-8') as text_file: for line in extracte...
<python><text-files><right-to-left>
2024-01-05 14:51:06
1
434
Hama Sabah
77,765,355
18,206,974
How to use FastAPI's lifespan to manage connection pool creation and relase?
<p>I want to use FastAPIs <code>lifespan</code> to create redis connection pool.</p> <p>Currently my implementation looks like that:</p> <ol> <li>My APIs has the following dependencies</li> </ol> <pre class="lang-py prettyprint-override"><code>@router.post(&quot;/items&quot;) async def post_items(r: RedisDependency): ....
<python><fastapi>
2024-01-05 14:39:41
1
336
Vladyslav Chaikovskyi
77,765,298
12,390,973
how to compare variables in PYOMO?
<p>I have a dummy energy dispatch code which I have created just to learn about how to <strong>compare variables</strong> in <strong>PYOMO</strong> and also how to use <strong>Binary variable</strong> in <strong>PYOMO</strong>.</p> <pre><code>from pyomo.environ import * import random import pandas as pd import numpy as...
<python><binary><pyomo>
2024-01-05 14:30:06
1
845
Vesper
77,765,233
1,900,317
Accessing Flask application context within python-socketio Client()'s event handler
<p>I am trying to access Flask application context inside the <code>python-socketio</code>'s event handler <code>on_tick()</code>, and I am presented with error -</p> <pre><code>(...) File &quot;H:\Python\autotrader2\venv\lib\site-packages\werkzeug\local.py&quot;, line 316, in __get__ obj = instance._get_current_o...
<python><flask><flask-socketio><python-socketio>
2024-01-05 14:19:41
1
505
Adi
77,765,210
10,362,396
Django Migrations Not Using Configured Database Connection
<p>I am using supabase postgresql along with django. By default it uses the public schema, but now I want to link the user_id field in model to auth.users.id where auth is the schema, users is the table name and id is the UUID field</p> <p>Models definition here</p> <pre><code># auth/models.py class SupabaseUser(models...
<python><django><orm>
2024-01-05 14:16:27
1
2,057
tbhaxor
77,765,051
1,391,441
What is the proper replacement for scipy.interpolate.interp1d?
<p>The class <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp1d.html" rel="noreferrer">scipy.interpolate.interp1d</a> has a message that reads:</p> <blockquote> <p>Legacy</p> <p>This class is considered legacy and will no longer receive updates. This could also mean it will be remo...
<python><python-3.x><scipy><interpolation>
2024-01-05 13:52:37
1
42,941
Gabriel
77,764,890
17,580,381
sigwait not behaving as expected
<p><strong>Unix only</strong></p> <pre><code>from threading import Thread from signal import signal, alarm, sigwait, SIGALRM class Check(Thread): def __init__(self): super().__init__() signal(SIGALRM, Check.handler) @staticmethod def handler(*_): print(&quot;Hello&quot;) def ...
<python><signals>
2024-01-05 13:26:16
2
28,997
Ramrab
77,764,754
8,865,579
Gunicorn over Flask sending Parallel requests to same route
<p>I am running a Flask application (fewer users, organization level). I have a high-end machine, with 72 cores and 515703MB RAM.</p> <p>I am currently running my application as (no nginx):</p> <pre><code>gunicorn --workers=10 --threads=12 -b 0.0.0.0:5000 &quot;run:app&quot; --access-logfile user_activity_logs/user_act...
<python><flask><promise><gunicorn><htop>
2024-01-05 12:58:45
0
2,277
DARK_C0D3R
77,764,734
17,721,722
Better way to insert a very large data into PostgreSQL tables
<p>What is the better way to insert a very large data into PostgreSQL Table?<br /> OS: Ubuntu 22.04 LTS<br /> DB: PostgreSQL 14<br /> Framework: Python 3.11 Django</p> <p>For now I am using insert into statement of 100,000 rows at a time. It is taking 2 Minutes for the whole process of inserting average of 1,000,000 ro...
<python><django><postgresql>
2024-01-05 12:54:13
1
501
Purushottam Nawale
77,764,710
4,504,711
How to set multiple values in a Pandas dataframe at once?
<p>I have a large dataframe and a list of many locations I need to set to a certain value. Currently I'm iterating over the locations to set the values one by one:</p> <pre><code>import pandas as pd import numpy as np #large dataframe column_names = np.array(range(100)) np.random.shuffle(column_names) row_names = np....
<python><pandas>
2024-01-05 12:48:43
2
2,842
Botond
77,764,700
497,132
Very slow list_objects_v2 in minio
<p>I'm using latest minio in docker on two servers. One is in my local network, another one is on a remote server. Configuration is default, volume is located on an HDD, not SSD.</p> <p>Bucket contains around 400k objects, ~70 GB.</p> <p>I have the following code (with the latest boto3):</p> <pre><code> paginato...
<python><amazon-web-services><amazon-s3><boto3><minio>
2024-01-05 12:47:03
1
16,835
artem
77,764,671
13,854,431
Retrieve data from interactive brokers from inside a docker container
<p>I have a docker container and a script with the following code:</p> <pre><code> import backtrader as bt import pandas as pd class MyStrategy(bt.Strategy): def __init__(self): print('initializing strategy') def next(self): print('next') def st...
<python><docker><network-programming><port>
2024-01-05 12:41:06
1
457
Herwini
77,764,495
5,799,799
How to resolve Quarto version upgrade breaking panel-tabset and pandas.to_html() interaction (1.2->1.3)
<p>Rendering the below code chunk with Quarto cli version 1.2 generates 3 tabs labeled a, b and c with a nicely rendered table in each tab. However when I upgrade to version 1.3 all the tables appear in tab a.</p> <p>Is there a way I should be using panel-tabset differently in version 1.3? Or if this was hacky and neve...
<python><markdown><quarto>
2024-01-05 12:09:53
1
435
DataJack
77,764,228
425,678
Pandas/SciPy - High Commit Memory Usage - Windows
<p><em>Update: After posting this question I discovered the same issue was occurring with SciPy. I have updated the title so others may discover this post. I have left the original question unchanged. A solution is provided below.</em></p> <p>Original Question:</p> <p>Is there a way to reduce the commit memory usage of...
<python><pandas><windows>
2024-01-05 11:24:37
1
810
user425678
77,763,904
3,809,375
"RuntimeError: Event loop is closed" when using unit IsolatedAsyncioTestCase to test fastapi routes
<p>Consider this mcve:</p> <p><strong>requirements.txt:</strong></p> <pre><code>fastapi httpx motor pydantic[email] python-bsonjs uvicorn==0.24.0 </code></pre> <p><strong>main.py:</strong></p> <pre><code>import asyncio import unittest from typing import Optional import motor.motor_asyncio from bson import ObjectId fro...
<python><python-3.x><unit-testing><asynchronous><fastapi>
2024-01-05 10:23:46
2
9,975
BPL
77,763,824
1,059,860
Tokensize a string in python
<p>This is what I'm trying to do:</p> <pre><code>from typer import Option, Typer, echo app = Typer(name=&quot;testapp&quot;) @app.command(&quot;run&quot;, help=&quot;Run a command in my special environment&quot;) def run( command: str, ) -&gt; None: print (command) </code></pre> <p>When running this testapp usi...
<python><typer>
2024-01-05 10:08:42
1
2,258
tandem
77,763,574
17,525,745
httpstat pip installed but not working as a command httpstat
<p>I'm trying to use the Python library &quot;<a href="https://pypi.org/project/httpstat/" rel="nofollow noreferrer">httpstat</a>&quot;.</p> <p><a href="https://i.sstatic.net/S6HT4.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/S6HT4.png" alt="enter image description here" /></a></p> <p>As is mentioned ...
<python><pip>
2024-01-05 09:19:12
1
476
UNRIVALLEDKING
77,763,387
1,922,291
Missing module error when installing lmdb (windows)
<p>I am trying to install wikipedia2vec on windows. I am running &quot;pip install wikipedia2vec&quot;</p> <p>It throws an error: Building py-lmdb from source on Windows requires the &quot;patch-ng&quot; python module while collecting lmdb (Full stack trace below)</p> <p>I have already ran &quot;pip install patch-ng&qu...
<python><pip>
2024-01-05 08:40:19
1
428
QuarterlyQuotaOfQuotes
77,763,369
7,133,942
How to align two plots in Matplotlib
<p>I have the following matplotlib code</p> <pre><code>import matplotlib.pyplot as plt import numpy as np # Time of day values time_of_day = [ &quot;00:00&quot;, &quot;01:00&quot;, &quot;02:00&quot;, &quot;03:00&quot;, &quot;04:00&quot;, &quot;05:00&quot;, &quot;06:00&quot;, &quot;07:00&quot;, &quot;08:00&quot;, ...
<python><matplotlib>
2024-01-05 08:36:49
1
902
PeterBe
77,763,199
4,892,210
Not able to get live streaming from DJI Tello on ubuntu 22
<p>I am trying to do live video streaming using DJI Tello drone, initially i was able to run same code on windows machine but when i tried on Ubuntu 22 i am not able to get any opencv popup for live streaming.</p> <p>Here is the output of code :</p> <pre><code>base) nirbhay@nirbhay:~/Desktop/Tello_code$ python LiveStre...
<python><video-streaming><dji-sdk>
2024-01-05 07:59:17
0
321
NIrbhay Mathur
77,763,138
7,113,481
pymongo insert all data in string format
<p>I am importing csv using pymongo then inserting it into mongodb but due to some reason all field is in format of string where i was expecting double. Below is python code .</p> <pre><code>def saveToMongo(): print(&quot;inside saveToMongo&quot;) collection = mydb['country'] header = ['country_id','country_name','zon...
<python><python-3.x><mongodb><csv><pymongo>
2024-01-05 07:47:38
2
1,426
gaurav singh
77,762,764
12,935,622
How to remove a portion from a 3d plane?
<p>I'm plotting in matplotlib. I want to remove a circle on the planes where they intersect with the catenoid surfaces. It's ok to have the intersection hard coded, as long as it looks fine visually.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # Parametric ...
<python><matplotlib><3d><geometry><visualization>
2024-01-05 06:04:35
1
1,191
guckmalmensch
77,762,538
224,511
Python unittests: how to get an AsyncMock to block until a certain point
<p>I have some async Python code I want to test, which include something like</p> <pre><code>async def task(self): while True: await self.thing.change() ... self.run_callbacks() </code></pre> <p>In my test file, I'm starting the task in the setUp() function like so:</p> <pre><code>def setUp(...
<python><asynchronous><python-asyncio><python-unittest><python-unittest.mock>
2024-01-05 04:35:50
1
3,859
askvictor
77,762,482
13,645,093
how to iterate through the dataset from hugging face?
<p>I have a dataset saved in a local drive, and i can load and convert this dataset to json or csv format and saved it to my local drive. I want to know , if there is a way i can stream this data and iterate through item. how can i iterate through ds? I can save it as a csv and process data row by row. or can i stream ...
<python><huggingface-datasets>
2024-01-05 04:19:51
1
689
ozil
77,762,467
9,008,162
How to fix ArgumentError: List argument must consist only of tuples or dictionaries?
<p>This is my method:</p> <pre><code>def print_relative_strength_by_ticker(self, tickers): # print relative strength tickers_list = tickers.split(&quot; &quot;) if len(tickers_list) == 1: query = &quot;SELECT ticker, rs FROM companyinfo WHERE ticker = %s&quot; params = [tickers_list[0]] # Wrap ...
<python><mysql><sqlalchemy>
2024-01-05 04:11:20
1
775
saga
77,762,392
8,076,158
How do I set environment variables in Code Cells in Scientific Mode?
<p>Pycharm is not reflecting the environment variable I set in a code cell. The following code runs in Pycharm (hitting play on the entire script):</p> <pre><code>#%% &lt;- Scientific Mode: on import os from pathlib import Path CACHE_DIR = Path(&quot;/home/me/numba_cache&quot;) CACHE_DIR.touch(exist_ok=True) os.envir...
<python><pycharm><numba>
2024-01-05 03:42:29
0
1,063
GlaceCelery
77,762,324
4,582,026
How to detect only yellow objects in an image with Python OpenCV?
<p>I am attempting to detect only yellow objects in a screenshot i've taken and i'm using the following code in Python.</p> <pre><code>import cv2 import numpy as np img=cv2.imread('screenshot.png') #B, G, R boundaries yellow = ([0, 200, 200], [60, 255, 255]) for (lower, upper) in boundaries: lower = np.array(low...
<python><opencv><image-processing><computer-vision>
2024-01-05 03:12:35
1
549
Vik
77,762,317
23,190,147
Python google search not returning expected output
<p>I'm trying to do a google search using python, it's basically web scraping. I'm searching using a specific phrase, and I'm expecting a detailed output. I also would like to avoid using other web scraping modules, such as <code>bs4</code> (BeautifulSoup4) or <code>urllib</code>.</p> <p>I'm using the <code>googlesearc...
<python><web-scraping><google-search>
2024-01-05 03:10:44
1
450
5rod
77,762,241
1,101,750
How do you use Python's string interning?
<p>I was curious about the performance benefits on dictionary lookups when using Python's <code>sys.intern</code>. As a toy example to measure that, I implemented the following code snippets:</p> <p>Without interning:</p> <pre class="lang-py prettyprint-override"><code>import random from uuid import uuid4 keys = [str(...
<python><string><string-interning>
2024-01-05 02:40:17
2
475
Sergi
77,761,900
1,285,061
Python find min and max in realtime stream without full array
<p>I have a continuous stream of values coming in, many millions of records. I need to find the minimum and maximum in that has arrived so far in real-time as numbers keep coming in. The whole data array is not available. Data arrived is not stored. Min max range is also unknown.</p> <p>I tried something like this, but...
<python><numpy><scipy><signal-processing>
2024-01-05 00:25:56
3
3,201
Majoris
77,761,818
214,526
resolving sys.path in test
<p>My code structure is following:</p> <pre><code>&lt;root&gt; +-- src | +- module1.py | | | +- module2.py | | | + __init__.py | +-- test +- test1 | +- test1.py | | | + __init__.py | +- test2.py | +- __init__.py </code></pre> <p><code>test/__init__.p...
<python><python-3.x><pytest>
2024-01-04 23:56:48
1
911
soumeng78
77,761,606
788,775
How to use pylint with optional objects
<p>I have a class:</p> <pre><code>class MyClass: LOOKUP: Optional[Dict] = None # it is supposed to be a # dictionary, but each derived class # will prepare own version. It has to be done later. # None value indicates that initialization is not done yet. ...
<python><pylint>
2024-01-04 22:46:18
1
2,817
lesnik
77,761,566
23,190,147
Python google search "advanced" argument unexpected
<p>I'm trying to perform a google search using python, using the <code>googlesearch</code> python module. I don't just want urls to be outputted, I also want a description of the information in the url, basically web scraping.</p> <p>Here's the code that includes the advanced argument:</p> <pre><code>from googlesearch ...
<python><web-scraping><google-search>
2024-01-04 22:33:55
1
450
5rod
77,761,520
8,284,452
How to replace part of a Timestamp using .where()?
<p>I have a dataframe that contains a few timestamps. I am trying to find certain timestamps that don't meet a condition and compute their new timestamp value based on pieces from both another timestamp and the current timestamp being tested.</p> <pre><code>df = pd.DataFrame(data={'col1': [pd.Timestamp(2021, 1, 1, 12),...
<python><pandas><dataframe><timestamp><series>
2024-01-04 22:20:57
1
686
MKF
77,761,282
214,296
Python socket transmitting on correct interface but with wrong source address
<p>I have a multicast system with multiple network interfaces. Packets transmitted using the socket I created are being sent out the correct interface, but the packet's source address is incorrect. The source address should match the interface that was used to transmit the packet over an isolated network, but it's us...
<python><sockets><ip-address><multicast><transmission>
2024-01-04 21:24:17
2
14,392
Jim Fell
77,761,161
1,601,831
SQLAlchemy string relationships cause 'undefined name' complaints by flake8 and mypy
<pre><code># order.py class Order(Base): __tablename__ = &quot;Order&quot; id: Mapped[int] = mapped_column(primary_key=True) items: Mapped[List[&quot;Item&quot;]] = relationship(back_populates=&quot;order&quot;) # item.py class Item(Base): __tablename__ = &quot;Item&quot; id: Mapped[int] = mapped...
<python><sqlalchemy><relationship><mypy><flake8>
2024-01-04 20:56:12
1
417
dam
77,761,069
5,287,011
Dictionary where values can be either a list or a list of lists
<p>I am trying to plot the result of truck routing optimization using networkx library. First I must prepare the data and I am stuck.</p> <p>Here is small example of the initial data:</p> <pre><code>Vehicle Route 0 V0 [0,3](V0) 1 V0 [3,0](V0) 2 V1 [0,3](V1) 3 V1 [0,8](V1) 4 ...
<python><list><dictionary><nested-lists>
2024-01-04 20:33:30
3
3,209
Toly
77,760,902
929,382
Fix for "TypeError: cannot pickle 'weakref' object" when using Python Multiprocessing in a Class
<p>I am currently working on a Python FastAPI application that spawns busy loops in parallel threads using the multiprocessing library. When I first started building the application, I created the threads during start-up in the main.py file. This worked great and I could spawn all the threads I needed with no issues.</...
<python><class><multiprocessing><fastapi>
2024-01-04 19:55:23
1
593
utdream
77,760,717
1,546,990
Mocking signals function in unit test
<p>I'm using Django version 4.2.6.</p> <p>I have a file, <code>signals.py</code>, that includes a pre-save handler for my entity:</p> <pre><code>def do_stuff(sender, instance, **kwargs): ... stuff... pre_save.connect(do_stuff, sender=MyEntity) </code></pre> <p>... so that when an instance of <code>MyEntity</code> ...
<python><django>
2024-01-04 19:19:40
1
2,069
GarlicBread
77,760,651
5,924,264
How to converge derived classes when the overrode methods are defined the same way but base class is different
<p>I have the following design pattern:</p> <pre><code>class Base: # definition omitted class Derived(Base): # definition omitted </code></pre> <pre><code>class Mock1(Base): def __init__(self, input, args): self._input = input super(Mock1, self).__init__(args) # my_func is defined in Base so we're ove...
<python><design-patterns>
2024-01-04 19:08:19
1
2,502
roulette01
77,760,478
1,471,980
how do you style data frame and write to excel in pandas
<p>I need to change the background's color of the dataframe headers to orange:</p> <p>My <code>df</code> looks like this:</p> <pre><code>Campus Server Port AZ server12 Eth1 AZ1 server12 Eth2 AZ2 server23 Gi2 NV Server34 Eth2 </code></pre> <p>I tried this:</p> <pre><code>df1=df....
<python><pandas><excel><dataframe><pandas-styles>
2024-01-04 18:34:22
1
10,714
user1471980
77,760,449
10,750,537
pcolormesh() different behavior when using OO vs state machine interfaces
<p>I need to use the <a href="https://stackoverflow.com/a/14261698/10750537">OO interface</a> of matplotlib (3.1.2) to draw some pictures in Python, but I get unpleasant results when calling pcolormesh(). The issue disappears when using the state-machine interface. However, as far as I understand, I cannot use the latt...
<python><matplotlib>
2024-01-04 18:27:00
0
381
JtTest
77,760,239
12,352,239
Unable to import module 'index': No module named 'awswrangler'
<p>I am deploying a Python lambda to integrate with an open search endpoint. I am following this <a href="https://docs.aws.amazon.com/solutions/latest/constructs/aws-lambda-opensearch.html" rel="nofollow noreferrer">CDK example</a>.</p> <p>I have a directory containing my lambda handler as well as a <code>requirements....
<python><amazon-web-services><aws-lambda>
2024-01-04 17:45:16
1
480
219CID
77,760,238
2,725,810
Intermittently slow CPU performance in AWS Lambda
<p>Consider the following AWS Lambda function:</p> <pre class="lang-py prettyprint-override"><code>import time import pickle import gc def ms_now(): return int(time.time_ns() / 1000000) class Timer(): def __init__(self): self.start = ms_now() def stop(self): return ms_now() - self.start ...
<python><amazon-web-services><performance><aws-lambda>
2024-01-04 17:45:13
0
8,211
AlwaysLearning
77,760,171
4,343,563
Check if values in list in different dataframe columns match?
<p>I am trying to check each value in a list in two separate columns. My dataframe looks like:</p> <pre><code> attribute value1 value2 Address ['a','b','c'] ['a','b','c'] Count ['1', 2, 3] ['1','2','3'] Color ['bl','cr','r'] ['bl','rd','gr'] </code></pre> <p>I want a ...
<python><pandas>
2024-01-04 17:33:55
1
700
mjoy
77,760,041
3,002,584
Creating numpy ndarray gives error buffer is too small for requested array - but it isn't
<ul> <li><sub>[Searched for duplicates but couldn't find any referring to this simple issue on Windows, so that's a self-answer]</sub></li> </ul> <p>I'm trying to create a simple 1D numpy <code>ndarray</code>, but gets an error:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; np.ndarray(shape=(3,), buf...
<python><windows><numpy>
2024-01-04 17:10:03
1
10,690
OfirD
77,759,931
6,603,473
Title color for figure (not axes) in Matplotlib
<p><strong>Edit:</strong> <em>Solution below, original question misses a bit of key information</em></p> <p>I am having difficulties changing the title color for my figure in Matplotlib.</p> <p>I have a figure containing subplots:</p> <pre><code>import matplotlib as mpl import matplotlib.pyplot as plt fig, ax = plt.s...
<python><matplotlib>
2024-01-04 16:54:10
2
322
georussell
77,759,902
19,130,803
check value in column is list type
<p>I have a dataframe with 2 columns <code>field</code> and <code>value</code>. I am performing some checks on each field's value. For <code>field a</code> I need to check its corresponding value is always <code>list</code> type and storing its result in <code>status</code> column</p> <p>Below is code:</p> <pre><code>i...
<python><pandas><dataframe>
2024-01-04 16:49:53
2
962
winter
77,759,855
3,767,239
Type checking an optional attribute whose value is related to that of another attribute
<p>I have a function which computes a <code>Result</code> and this computation can either be <code>success</code>ful or not. In case it was successful, some <code>data</code> that summarizes the result of the computation will be returned as well. In case it was unsuccessful, this data will be <code>None</code>. Now the...
<python><mypy><python-typing>
2024-01-04 16:40:30
1
36,629
a_guest
77,759,545
9,366,726
I get a Max retries exceeded (_ssl.c:2427) error when trying to inject with LlamaIndex data in a pinecone DB
<p>I get a Max retries exceeded with url:</p> <pre><code>(Caused by SSLError(SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:2427)'))) </code></pre> <p>When trying to inject data in pinecone DB When trying to inject data with LlamaIndex into a Pinecone DB i get the following error:</p> <pre><code> Lla...
<python><llama-index><pinecone>
2024-01-04 15:52:07
1
476
Alex Ricciardi
77,759,542
9,318,323
SqlAlchemy why does engine create more connection than "permitted"
<p><strong>Situation</strong></p> <p>I am migrating some code from pyodbc to SqlAlchemy. I noticed that during some tests I get more active connections than previously. Old pyodbc code keeps at 2 connections at most while the new SqlAlchemy reaches 7.</p> <p>To check connections I just run a query from the db using SSM...
<python><sql-server><sqlalchemy>
2024-01-04 15:51:41
1
354
Vitamin C
77,759,524
17,597,213
A more efficient regular expression for extracting astrological house data?
<p>I wrote a script to extract astrological house data from a birth chart PDF. I am wondering if there is a more efficient regular expression I could be using.</p> <p><strong>Current pattern:</strong></p> <pre class="lang-py prettyprint-override"><code>house_pattern = r'([A-Z]{2}|[A-Z][a-z]+\.|[0-9]|[0-9]{2})\s+([a-z])...
<python><regex>
2024-01-04 15:49:21
2
617
Jordan
77,759,361
16,503,741
Pydantic refusing a model that clearly has an annotation
<p>I have a clearly annotated pydantic model:</p> <pre><code>class CurrencyCode(TripleApiModel, RootModel[str]): &quot;&quot;&quot;3-character ISO-4217 currency code&quot;&quot;&quot; root: Annotated[ str, Field( &quot;USD&quot;, description=&quot;3-character ISO-4217 cu...
<python><pydantic>
2024-01-04 15:23:29
0
339
Jelkimantis
77,759,260
2,923,617
Django AppRegistryNotReady when running Unittests from vscode
<p>My UnitTest test cases in a Django project run fine when running them directly from the Django utility (<code>python manage.py test</code>). However, when trying to run them from VSCode's test explorer, I get <code>django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.</code>. I found several similar qu...
<python><django><visual-studio-code>
2024-01-04 15:08:00
1
486
NiH
77,759,146
5,798,201
Issue installing openai in Colab
<p>Hi after the chrismas break I have problems installing openai in Google Colab</p> <p>I'm doing this. Which worked util mid december 2023:</p> <pre><code>!pip install --upgrade pip !pip install --upgrade --quiet openai import openai </code></pre> <p>Now I get this error:</p> <pre><code>ImportError ...
<python><google-colaboratory><openai-api>
2024-01-04 14:49:11
3
1,812
Tobi
77,759,057
2,932,907
PyEZ - Getting RpcTimeoutError after succesful commit even though timeout value is set to a high value
<p>I've got a Python (3.10) script using the PyEZ library to connect to Junos devices and commit various display set commands. Although both these steps are successful, when having committed the candidate configuration I get an RpcTimeoutError no matter what timeout value I set for the Device class and inside the commi...
<python><pyez>
2024-01-04 14:36:01
1
503
Beeelze
77,758,924
3,405,291
matplotlib figures are empty
<p>I run this Python code: <a href="https://github.com/calculix/beso" rel="nofollow noreferrer">https://github.com/calculix/beso</a></p> <h2>Config</h2> <p>The <code>beso_conf.py</code> file is modified. These variables:</p> <pre class="lang-py prettyprint-override"><code>path_calculix = &quot;C:\\Users\\m3\\Downloads\...
<python><matplotlib>
2024-01-04 14:14:56
1
8,185
Megidd
77,758,901
8,384,910
Multispectral image to RGB in Python
<p>I would like to convert a multispectral image to RGB. After parsing said image, its an ndarray of shape <code>(w, h, c)</code>. where c is the hundred-or-so wavelengths which were measured. Null measurements are -999, not 0.</p> <p>For a single pixel, it is easy to use the <a href="https://www.colour-science.org/" r...
<python><colors>
2024-01-04 14:11:58
1
9,414
Richie Bendall
77,758,714
393,010
How to type annotate converting envvar to integer?
<p>How would I get mypy to accept this code?</p> <pre><code>try: DEBUG = int(os.getenv(&quot;DEBUG&quot;)) &gt; 0 except ValueError: DEBUG = False </code></pre> <p>Current diagnostic is <code>mypy: Argument 1 to &quot;int&quot; has incompatible type &quot;str | None&quot;; expected &quot;str | Buffer | Supports...
<python><mypy>
2024-01-04 13:39:38
1
5,626
Moberg
77,758,645
10,847,096
Get accelerate package to log test results with huggingface Trainer
<p>I am fine-tuning a T5 model on a specific dataset and my code looks like this:</p> <pre class="lang-py prettyprint-override"><code>accelerator = Accelerator(log_with='wandb') tokenizer = T5Tokenizer.from_pretrained('t5-base') model = T5ForConditionalGeneration.from_pretrained('t5-base') accelerator.init_trackers( p...
<python><huggingface><wandb><accelerate>
2024-01-04 13:28:04
1
993
Ofek Glick
77,758,605
5,220,257
Get full text from a LayoutLM
<p>I am using LayoutLM to read receipts and get text from the invoices. I am using this model from HuggingFace &quot;philschmid/lilt-en-funsd&quot;. Given below is the code snippet:</p> <pre><code>def run_inference(image_path, model=model, processor=processor, output_image=True): # Load image from the path imag...
<python><deep-learning><ocr><huggingface-transformers><text-extraction>
2024-01-04 13:23:11
1
1,490
Asim
77,758,565
3,387,716
How to iterate over the remaining items in a dict while looping through that dict?
<p>Is there a cleaner way to iterate over the follow-up keys of a dict when iterating over a dict?</p> <pre class="lang-py prettyprint-override"><code>d = { &quot;a&quot;: 1, &quot;b&quot;: 2, &quot;c&quot;: 3 } k = list(d.keys()) for i in range(len(k)): print(k[i] + &quot;:&quot;) for j in range(i+1, len(k))...
<python><loops><dictionary>
2024-01-04 13:17:52
4
17,608
Fravadona
77,758,563
9,112,151
Rotate the array to the right by k steps
<p>Given an integer array nums, rotate the array to the right by k steps, where k is non-negative.</p> <p>Example:</p> <p>Input: nums = [1,2,3,4,5,6,7], k = 3</p> <p>Output: [5,6,7,1,2,3,4]</p> <p>Explanation:</p> <p>rotate 1 steps to the right: [7,1,2,3,4,5,6]</p> <p>rotate 2 steps to the right: [6,7,1,2,3,4,5]</p> <p...
<python>
2024-01-04 13:17:29
2
1,019
Альберт Александров
77,758,436
12,319,746
Autogen response in a variable
<pre><code>import autogen from nicegui import ui, context from uuid import uuid4 # AutoGen Configuration config_list = [ { 'model': 'gpt-4', 'api_key': '' } ] llm_config = { 'seed': 42, 'config_list': config_list, 'temperature': 0.2 } # Initialize AutoGen Agents assistant = autoge...
<python><artificial-intelligence><large-language-model><ms-autogen>
2024-01-04 12:55:32
1
2,247
Abhishek Rai
77,758,337
2,123,706
PerformanceWarning: DataFrame is highly fragmented when creating new columns
<p>I have a 1m row df with one column that is always 5000 characters, A-Z0-9</p> <p>I parse the long column into 972 columns using :</p> <pre><code>def parse_long_string(df): df['a001'] = df['long_string'].str[0:2] df['a002'] = df['long_string'].str[2:4] df['a003'] = df['long_string'].str[4:13] df['a004...
<python><dataframe><calculated-columns>
2024-01-04 12:37:42
1
3,810
frank
77,758,277
13,518,907
CMAKE in requirements.txt file: Install llama-cpp-python for Mac
<p>I have put my application into a Docker and therefore I have created a requirements.txt file. Now I need to install <code>llama-cpp-python</code> for Mac, as I am loading my LLM with from langchain.llms import LlamaCpp.</p> <p>My installation command specifically for Mac is:</p> <p><code>&quot;CMAKE_ARGS=&quot;-DLLA...
<python><macos><llama-cpp-python><llamacpp>
2024-01-04 12:28:49
2
565
Maxl Gemeinderat
77,758,047
10,128,276
Encountering ImportError with tesserocr: Symbol not found in flat namespace '__ZN9tesseract11TessBaseAPID1Ev'
<p>I'm attempting to use tesserocr in my Python project, but when I try to import it, I'm getting <code>[No module named 'tesserocr']</code>, I run into an ImportError. The error message points to a missing symbol related to the Tesseract library. Here is the full error message:</p> <p><div class="snippet" data-lang="j...
<python><macos><tesseract><importerror>
2024-01-04 11:43:51
1
617
Jim Khan
77,757,962
13,094,333
Understanding Python async await coroutines (blocking loop example)
<p>I am trying to understand the coroutines. I know that they are using single thread and <code>await</code> keyword means &quot;give back control to other running coroutines and give them a chance to run&quot;.</p> <p>I have the following example:</p> <pre class="lang-py prettyprint-override"><code>import asyncio impo...
<python><async-await><python-asyncio>
2024-01-04 11:30:23
2
412
Jack Scandall
77,757,929
1,095,967
"Go to Definition" not working in VS Code with Robot Framework Language Server
<p>When I use the context menu on a keyword in a file and select &quot;Go to Definition&quot; I'm always getting a pop-up for No Definition Found.</p> <p>I've got the Robot Framework Language Server extension installed. Python (3.11) and Pylance.</p> <p>I've tried disabling/reenabling extensions and restarting code and...
<python><visual-studio-code><robotframework>
2024-01-04 11:24:15
1
661
MaxRussell
77,757,731
1,119,391
uscxml (statecharts) and Python
<p>Are there any examples of <code>uscxml</code> (statechart) code using the Python bindings?</p> <p>E.g. I'm having the following problem. Running <code>uscxml-browser -v &lt;scxml-chart-file&gt;</code> works (showing me it's going through the transitions) but how do I run this as Python code.</p>
<python><statechart>
2024-01-04 10:54:55
0
335
stustd
77,757,473
4,393,414
Prevent "smem" command to use terminal width, Need to use custom width
<p>I want <code>smem</code> to capture whole output i.e. command name should fully capture agnostic of terminal width.</p> <p>I see <code>-a</code> option is there but its tied up with current terminal width.</p> <p>I want to use custom width, for that I tried below thing to set <code>env={'COLUMNS':'512'}</code> in <c...
<python><linux><subprocess>
2024-01-04 10:19:02
1
745
Sanket