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
76,150,890
3,515,174
Python variadic generics accepting class
<p><a href="https://docs.python.org/3/library/typing.html#typing.Type" rel="nofollow noreferrer">a variable annotated with Type[C] may accept values that are classes themselves</a></p> <p>How do you do this with <a href="https://peps.python.org/pep-0646/#type-variable-tuples" rel="nofollow noreferrer">TypeVarTuples (PE...
<python><generics><python-typing>
2023-05-01 23:55:55
1
4,502
Mardoxx
76,150,870
4,158,016
How to get key value fashion json output while scraping using python selenium
<p>My data is like this, repeated for different companies likewise</p> <pre class="lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt;&lt;/head&gt; &lt;body&gt; &lt;script type=&quot;text/javascript&quot;&gt;&lt;/script&gt; &lt;div class=&quot;result-container...
<python><selenium-webdriver><web-scraping>
2023-05-01 23:51:15
1
450
itsavy
76,150,862
6,321,559
Profiling Server Side vs Client Side Psycopg2 Cursor
<p>I'm profiling code to see the difference between bulk load from a Postgres DB source or stream from the source. The design for bulk is <code>psycopg2</code> with a client side cursor. The design I'm testing for stream is a server side cursor with an <code>itersize</code> of 20,000. The test table has ~600,000 rows.<...
<python><postgresql><psycopg2>
2023-05-01 23:50:03
0
2,046
it's-yer-boy-chet
76,150,855
8,276,973
How to get correct path for Sphinx autodoc with os.path
<p>I just built Sphinx for the first time and generated all of the skeleton files. Next I want to add another path with Python files for autodoc to analyze. <code>sphinx.ext.autodoc</code> is in conf.py as an extension.</p> <p>My Sphinx install is in: <code>/home/mbcn/Software_Projects/Sphinx</code>.<br /> The other ...
<python><python-3.x><python-sphinx><autodoc>
2023-05-01 23:48:34
0
2,353
RTC222
76,150,773
2,687,317
pandas pivot table aggregating over 2 diff columns and 2 functions: sum and mean
<p>I have data of the form</p> <pre><code> Date_Time LF Name Count pwr TS 0 2022-08-03 00:00:02 2885184100 OpenP1 1 0.302229 1 1 2022-08-03 00:00:02 2885184100 Net3 1 4.790000 3 2 2022-08-03 00:00:02 2885184100 OpenP1 1 0.000000 1 3 2022-08-03 00:00:02 28851...
<python><pandas><pivot-table>
2023-05-01 23:20:07
1
533
earnric
76,150,759
12,022,239
FastAPI - Struggling to use dependency injection to inject a service class into an endpoint
<p>I have an AI related FastAPI application, and I have the business logic nicely separated into multiple services. I want to use inject these services into my application so I can use them, but I can't get it to work. These are the services I have:</p> <p>aws_rekognition_service.py</p> <pre><code>from io import BytesI...
<python><fastapi>
2023-05-01 23:16:08
0
831
Stefan Jaspers
76,150,615
8,667,016
Adding items from one list to another list of lists
<p>Suppose I have the following lists:</p> <pre class="lang-py prettyprint-override"><code>list_1 = [[1,2],[3,4],[5,6],[7,8]] list_2 = [11,12,13,14] </code></pre> <p>How can I add items from the second list to each of the items from the first one?</p> <p>Stated clearly, this is the result I'm looking for:</p> <pre clas...
<python><list><iterable><unpack><iterable-unpacking>
2023-05-01 22:37:29
4
1,291
Felipe D.
76,150,614
3,380,902
Nested struct type not supported pyspark error
<p>I am attempting to apply a function to a pyspark DataFrame and save the API response to a new column and then parse using <code>json_normalize</code>. This works fine in pandas, however, I run into an exception with <code>pyspark</code>.</p> <pre><code>import pyspark.pandas as ps import pandas as pd import requests ...
<python><pandas><pyspark>
2023-05-01 22:37:29
0
2,022
kms
76,150,515
18,551,983
filter pandas dataframe by inserting zeros based on another data farme index
<p>is there anyway to filter the first dataframe based on the index of second dataframe and generate the output dataframe? In first datafarme, we filterout the rows whose index are present in second dataframe and need to insert whole 0 zero in place of index value of second dataframe.</p> <p>first dataframe</p> <pre><c...
<python><python-3.x><pandas><dataframe><dictionary>
2023-05-01 22:14:23
1
343
Noorulain Islam
76,150,479
5,022,913
Expose Grafana from Docker behind Nginx
<h2>Background</h2> <p>My app stack uses several Docker containers managed by <code>docker compose</code>:</p> <ul> <li>PostgreSQL at port 5433</li> <li>FastAPI (Python) backend at port 8000</li> <li>NodeJS frontend at port 8090 and exposed to 80 (via Nginx, see further)</li> <li>pgAdmin at port 5050</li> <li>Prometheu...
<python><docker><nginx><docker-compose><grafana>
2023-05-01 22:07:42
1
584
s0mbre
76,150,400
16,527,596
Print out 2 graphs in python
<p>Im a beginner when it comes to python OOP so i ask for some help regarding some small stuff.</p> <p>Firstly before we are required to print out the results we are asked to calculate different stuff for example one of them is from Class BSC the value of Snr_BSC(Its just formulas)</p> <p>What i dont understand though ...
<python>
2023-05-01 21:52:40
0
385
Severjan Lici
76,150,363
13,142,245
Executing asyncio method from a synchronous method / blocking until complete in Python
<p>I really don't want to update my large code base such that <code>async</code> and <code>await</code> are used in every method dependent on an asynchronous function or method. But this seems impossible.</p> <p>From what I can tell, there is no convenient way to</p> <ol> <li>Define two asynchronous functions</li> <li>...
<python><python-asyncio>
2023-05-01 21:45:16
1
1,238
jbuddy_13
76,150,266
2,219,369
plot timestamps and index in the same plot
<p>Hi I'm trying to figure out if you can plot dates on one axis and corresponding integer indices on another axis in the same subplot with matplotlib, for example just the price with dates on one axes and price and corresponding integers indices (to the dates, in the example idx = np.arange(len(aapl))) . Here is an ex...
<python><matplotlib><timestamp><indices>
2023-05-01 21:24:44
1
14,049
jonas
76,150,083
13,142,245
asyncio.wait in OOP design
<p>I have an application where my operations are network bound so I would like to execute these data pulls asynchronously.</p> <p>I make multiple data pulls to AWS, which is in the <code>pull</code> method. In the <code>runApplication</code> method, I use <code>asyncio.wait</code> for each of the two tasks.</p> <pre cl...
<python><python-asyncio>
2023-05-01 20:48:35
0
1,238
jbuddy_13
76,150,016
929,732
Need to install some MariaDB/Mysql tools for Python Mysql and having issues with dependancies
<h2>Here is the version I'm running.</h2> <pre><code>mysqld Ver 10.5.15-MariaDB-1:10.5.15+maria~focal-log for debian-linux-gnu on x86_64 (mariadb.org binary distribution) </code></pre> <p>-- Attempting to install</p> <pre><code>sudo apt-get install libmariadbclient-dev </code></pre> <p>And ending up with</p> <pre><cod...
<python><mariadb>
2023-05-01 20:36:05
0
1,489
BostonAreaHuman
76,149,748
5,942,100
Round to nearest even value based on row by row conditions using Pandas
<p>I would like to round EACH VALUE to the nearest even number, with this logic: Any value less than or = to 0.69, round down to 0</p> <pre><code>**Data** Location range type Q1 28 Q2 28 Q3 28 Q4 28 rounded_sum NY low re AA 1.14 0 0 0 2 NY ...
<python><pandas><numpy>
2023-05-01 19:44:44
2
4,428
Lynn
76,149,718
18,551,983
filter pandas dataframe based on another data farme index
<p>is there anyway to filter the first dataframe based on the index of second dataframe and generate the output dataframe? In first datafarme, we filterout the rows whose index are present in second dataframe. first dataframe</p> <pre><code> C1 C2 C3 C4 A 1 1 1 1 B 1 1 1 1 C 0 ...
<python><python-3.x><pandas><dataframe>
2023-05-01 19:40:31
1
343
Noorulain Islam
76,149,632
9,937,874
Polars specify dtypes fails
<p>I am trying to optimize the memory used when reading in a csv file into a polars dataframe as part of a pipeline. I have a large number of columns and I know ahead of time that 2 columns need to be objects, 2 columns need to be int64, and the rest can be uint8. I use the following bit of code to generate the list of...
<python><python-3.x><python-polars>
2023-05-01 19:26:35
1
644
magladde
76,149,628
9,626,922
'>=' not supported between instances of 'int' and 'str' when using env.step from gym
<p>I have the following code that I keep getting an error saying <code>'&gt;=' not supported between instances of 'int' and 'str'</code> coming from env.step() from gym. It seems to be the <code>terminated</code> value that is causing the error but I can not see where from:</p> <pre><code>%matplotlib notebook import gy...
<python><machine-learning><artificial-intelligence><reinforcement-learning><openai-gym>
2023-05-01 19:26:20
2
617
Jm3s
76,149,608
1,874,170
Using email.message to parse an HTTP POST request?
<p>With the deprecation of the standard <code>cgi</code> library in favor of <a href="https://peps.python.org/pep-3333/" rel="nofollow noreferrer">WSGI</a> starting in Python 3.11, the documentation <a href="https://docs.python.org/3.11/library/cgi.html" rel="nofollow noreferrer">alleges</a>:</p> <blockquote> <p>The <c...
<python><parsing><http-post><wsgi><python-3.11>
2023-05-01 19:23:18
1
1,117
JamesTheAwesomeDude
76,149,466
2,236,231
Prevent TimeoutError from asyncio in Python
<p>I am building a test suite for my Telegram Bot. There is a long-running task which may take +10mins. However, after ~15s I receive a <code>asyncio.exceptions.TimeoutError</code></p> <p>This is a simplified code:</p> <pre class="lang-py prettyprint-override"><code>from tgintegration import BotController from tgintegr...
<python><python-asyncio><pyrogram>
2023-05-01 19:01:12
1
1,099
Geiser
76,149,446
6,676,101
In python, how can we ignore case-sensitivity in dictionary keys when printing the dictionary to string, printing to console, or printing to file?
<p>In python, how do you <em><strong>pretty print</strong></em> a dictionary such that dictionary keys are <strong>not</strong>-case sensitive?</p> <p>For example, <code>Apple</code> with a big letter <code>A</code> and <code>apple</code> with a small letter <code>a</code> will be near each-other.</p> <p>The results sh...
<python><python-3.x><dictionary><pretty-print>
2023-05-01 18:58:50
2
4,700
Toothpick Anemone
76,149,427
4,372,237
Vector autoregressive models with custom lags
<p>I am trying to apply vector autoregression to my data using statsmodels package. This package has a lot of tools for univariate time-series modeling, including <code>statsmodels.tsa.ar_model.AutoReg()</code> method that accepts a list of custom lags. For a vector autoregression, the function <code>statsmodels.tsa.ve...
<python><statsmodels><vector-auto-regression>
2023-05-01 18:55:31
0
3,470
Mikhail Genkin
76,149,423
5,942,100
Tricky conditional transform values per row based on logic of another column using Pandas
<p>I would like to round EACH VALUE to the nearest even # so that our row sum doesn't exceed or go below the 'rounded_sum' column value for that row. If we exceed or go below, compensate for the difference by subtracting or adding the difference to one of the values. Making sure no negative values.</p> <p><strong>Data<...
<python><pandas><numpy>
2023-05-01 18:55:05
1
4,428
Lynn
76,149,381
113,538
Why can't libclang find a function argument declaration?
<p>I'm writing a tool to find the dependencies of a C function. For example in the tcpdump project there is a function in print-ppp.c</p> <p><code>static void ppp_hdlc(netdissect_options *ndo, const u_char *p, int length)</code></p> <p>netdissect_options is defined in the netdissect.h header.</p> <p>I'm trying to use l...
<python><parsing><clang><abstract-syntax-tree>
2023-05-01 18:47:31
1
895
Brian
76,149,371
5,370,631
Explode 2 columns into multiple columns in pyspark dataframe
<p>I have the following PySpark dataframe:</p> <pre><code>+--------------------------------+-------+------------------------------------+-----------+------------------+------------------+ |id |order |cart |item |sub |rank | ...
<python><apache-spark><pyspark><apache-spark-sql>
2023-05-01 18:45:50
1
1,572
Shibu
76,149,284
11,391,711
how to use every even column for the corresponding odd column and create a new data frame - Python
<p>I read a huge Excel file where each even column (e.g., 0,2) is the number of days, and the next column is a location. Each location has a different length. As a small example, here's a sample data frame.</p> <pre><code>import pandas as pd import numpy as np from datetime import datetime, timedelta data = { 'Un...
<python><pandas><dataframe>
2023-05-01 18:31:20
2
488
whitepanda
76,149,118
10,573,543
Why the registeration.html form is not rendering in DJANGO?
<p>New to DJANGO.</p> <p>I am having trouble with rendering my <code>registeration.html</code> page.</p> <p>This is my project structure</p> <pre><code>auth_test | |-urls.py |-settings.py big_app | |-admin.py |-forms.py |-models.py |-urls.py |-views.py templates media static </code><...
<python><django><django-views>
2023-05-01 18:06:19
1
1,166
Danish Xavier
76,149,068
19,325,656
Factory boy connect models to existing users
<p>Im populating my database with dummy data, I have separate Profile, User, Picture model. How can connect them to use same users?</p> <pre><code>class UserFactory(DjangoModelFactory): class Meta: model = User email = factory.Faker('email') first_name = factory.Faker('first_name') birthday = ...
<python><django><django-rest-framework><faker><factory-boy>
2023-05-01 17:57:14
1
471
rafaelHTML
76,149,018
2,112,406
How to filter a list of objects based on an attribute in parallel, using Pool
<p>Given a list of objects, I want to be able to reduce that list based on the attributes of the objects. Suppose I have the following class:</p> <pre><code>class TestClass: def __init__(self, x, y): self.x = x self.y = y </code></pre> <p>and a list of objects from that class:</p> <pre><code>N = 10 ...
<python><oop><parallel-processing><python-multiprocessing>
2023-05-01 17:49:59
1
3,203
sodiumnitrate
76,148,989
5,942,100
Sort within categories in a specific transformation using Pandas
<p>I have a dataset where I would like to sort my data within categories in a specific way.</p> <p><strong>Data</strong></p> <pre><code>Location range type Q1 27 Q2 27 Q3 27 Q4 27 NY low re AA 5 0 7 0 NY low re BB 0 0 0 0 NY low re...
<python><pandas><numpy>
2023-05-01 17:44:54
2
4,428
Lynn
76,148,945
5,583,772
How can I select rows with repeating values
<p>Is there a way to filter for rows in polars dataframe that allows for repeated values (this would be useful I think in block bootstrapping). What I have in mind is an example dataframe:</p> <pre><code>df = pl.DataFrame({ 'x':[0,1,2,3,4,5], 'y':[10,11,12,13,14,15], 'z':[0,0,1,1,2,2] }) </code></pre> <p>G...
<python><dataframe><python-polars>
2023-05-01 17:37:55
2
556
Paul Fleming
76,148,912
3,204,250
Pandas pivot_table with columns as horizon
<p>I have a dataframe like so:</p> <pre><code>first_dt dt val 2023-01-01 2023-01-02 1 2023-01-01 2023-01-02 1 2023-01-01 2023-01-03 1 ... 2023-01-02 2023-01-03 1 2023-01-02 2023-01-04 1 </code></pre> <p>You should note that <code>dt</code> is never less than <code>first_dt</code>. I would l...
<python><pandas><pivot-table>
2023-05-01 17:31:50
1
20,030
cdeterman
76,148,657
1,893,164
How can I convert an Excel spreadsheet to HTML with Python?
<p>I have several .xlsx Excel spreadsheets that I'd like to convert to an HTML web format by using a Python script. How can I do this?</p>
<python><pandas><excel>
2023-05-01 16:53:03
1
13,197
Al Sweigart
76,148,588
1,115,833
solr distance search with proximity
<p>I am trying to do some filtering of results using proximity search and I am finding it difficult to construct the correct query for this.</p> <p>So, in my index I have the following entry:</p> <pre><code> { &quot;aff&quot;:&quot;lg electronics&quot;, &quot;shortuuid&quot;:&quot;sddsd3ww&quot;, ...
<python><elasticsearch><solr><lucene>
2023-05-01 16:41:14
1
7,096
JohnJ
76,148,493
2,386,605
BioGPT causal language model with unexpected error
<p>I am trying to use a Causal Language Model from BioGPT. However, I got a strange error.</p> <p>Here are my steps:</p> <p>First, I installed <code>transformers</code> and <code>sacremoses</code>:</p> <pre><code>!pip install transformers sacremoses -q </code></pre> <p>Then I executed the following code:</p> <pre><code...
<python><pytorch><huggingface-transformers><large-language-model>
2023-05-01 16:24:49
1
879
tobias
76,148,492
10,620,003
Normalize the data and inverse_transform value error
<p>I have a prediction model and I have to normalize my label, since the loss exploded without normalization. But the problem is that, I use MinMaxScaler to normalize the data_train which is with size (2,10) and my predicted values size is (2,5). So when I want to use <code>inverse_transform</code>, I got</p> <pre><cod...
<python><machine-learning><scikit-learn>
2023-05-01 16:24:29
1
730
Sadcow
76,148,307
8,112,003
Executing docker exec concurrently
<p>Actually the docker python sdk is working fine: <a href="https://docker-py.readthedocs.io/en/stable/client.html" rel="nofollow noreferrer">https://docker-py.readthedocs.io/en/stable/client.html</a></p> <p>But I tried to perform docker exec with asyncio package simultaneously. It seems not to be possible? How could j...
<python><docker><python-asyncio><python-docker>
2023-05-01 15:55:05
1
752
Nikolai Ehrhardt
76,148,267
2,593,480
OpenAI API "AuthenticationError No API key provided" when switching to internalConsole in VS Code launch.json
<p>I'm using the OpenAI API in a Python script and have set the OPENAI_API_KEY as an environment variable in my system, which works fine when running the script in the integrated terminal. What I have used to set the key. <a href="https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety" rel="nofol...
<python><visual-studio-code><vscode-debugger><openai-api>
2023-05-01 15:49:36
1
581
Yam Shargil
76,148,251
499,721
Is there a way to change gunicorn log level at runtime?
<p>I have a <a href="https://fastapi.tiangolo.com/" rel="nofollow noreferrer">FastApi</a> service running on <a href="https://gunicorn.org/" rel="nofollow noreferrer">Gunicorn</a> server in a K8s pod. Is there a way to change the log levels / settings at runtime, without restarting the server?</p>
<python><gunicorn>
2023-05-01 15:48:03
1
11,117
bavaza
76,148,181
10,901,843
How do I get Python Timedelta to rollover to the next day when calculating time elapsed?
<p>I have a function that takes in the hour and minute of two programs and returns the elapsed time. It works well when the end_time isn't the next day. If it's the next day, I get a negative number. What's the best way to resolve this?</p> <pre><code>def elapsed_time_seconds(hour_start,hour_end,minute_start,minute_end...
<python><pandas><datetime><timedelta>
2023-05-01 15:36:58
2
407
AI92
76,148,115
8,849,071
Mypy failing when you type hint with a more general type
<p>I was writing some code and I found the following behaviour in mypy:</p> <pre class="lang-py prettyprint-override"><code>from typing import Dict, TypedDict class SomeDictionary(TypedDict): key: str def function() -&gt; Dict: some_dictionary: SomeDictionary = {&quot;key&quot;: &quot;value&quot;} retur...
<python><mypy>
2023-05-01 15:25:40
0
2,163
Antonio Gamiz Delgado
76,148,104
1,205,281
How do I get the current gcloud configuration user/service account's id token in python
<p>I'm using gcloud configurations to handle my CLI access. (switching between them with <code>gcloud config configurations activate &lt;env_name&gt;</code>). I'm NOT using <code>GOOGLE_APPLICATION_CREDENTIALS</code> env var at all as I want to be able to switch between configurations/projects/accounts.</p> <p>It works...
<python><google-cloud-platform><google-cloud-functions>
2023-05-01 15:24:29
3
646
David Avikasis
76,147,945
1,912,104
How to concatenate string columns that contain NaN values?
<p>I have a data that looks like this:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy as np mydict = { 'col1' : ['a', 'b', 'c'], 'col2' : ['d', np.NaN, 'e'], 'col3' : ['f', 'g', 'h'] } mydf = pd.DataFrame(mydict) </code></pre> <p>I want to concatenate these string col...
<python><pandas><dataframe><numpy>
2023-05-01 15:02:15
2
851
NonSleeper
76,147,864
11,462,274
Reducing the number of ticklabels on x axis of the graph while keeping the curve with all the dataframe lines
<p>At the end of the question, there is an example of a CSV file with data starting from records on April 17, 2023 to April 30, 2023 in the &quot;open_local_data&quot; column.</p> <p>Well, note that that when trying to generate the graph points, they are reset to 1970 due to the formatting of the date and time column. ...
<python><pandas><matplotlib>
2023-05-01 14:51:28
1
2,222
Digital Farmer
76,147,835
20,285,962
How to change theme in JupyterLab Desktop
<p>I've installed the JupyterLab Desktop application found here:</p> <p><a href="https://github.com/jupyterlab/jupyterlab-desktop" rel="nofollow noreferrer">jupyterlab-desktop</a></p> <p>and wanted to change the theme noticing only two options Jupyter Dark and Light. So naturally with the extensions setting I've tried ...
<python><jupyter-notebook><themes><jupyter><jupyter-lab>
2023-05-01 14:46:52
0
319
Shane Gervais
76,147,662
2,071,807
Pydantic Custom Data Types can't be optional in FastAPI route
<p>Following the Pydantic <a href="https://docs.pydantic.dev/latest/usage/types/#custom-data-types" rel="nofollow noreferrer">custom data types</a> instructions, I've created a type which attempts to get strings from a single comma-separated string like:</p> <pre><code>&quot;foo,bar,baz&quot; -&gt; [&quot;foo&quot;, &q...
<python><fastapi><optional-parameters>
2023-05-01 14:19:27
1
79,775
LondonRob
76,147,208
1,739,325
How to post second question via POST call to hugginface chat?
<p>So this code works pretty good I get first desired output to the <a href="https://huggingface.co/chat/conversation/" rel="nofollow noreferrer">https://huggingface.co/chat/conversation/</a>:</p> <pre><code>from requests.sessions import Session from json import loads prompt = &quot;Explain first condition in english?...
<python><post><request><huggingface>
2023-05-01 13:10:35
0
5,851
Rocketq
76,147,137
14,900,791
Python constant uuid token in class (property does not work)
<p>I need a class that remembers its constant token (uuid). When I use the property decorator as <a href="https://stackoverflow.com/a/45068730/14900791">described here</a>, <strong>the <code>property</code> will prevent the <code>uuid</code> function from changing, but not the value</strong>:</p> <pre class="lang-py pr...
<python><properties><constants>
2023-05-01 13:02:28
1
1,171
Jurakin
76,147,033
14,442,010
Method Not Allowed (submit form with jQuery in Django)
<p>I want to submit my &quot;contact us&quot; form on my Django website with jQuery.</p> <p>I'm working on development server.</p> <p>The error I receive in the browser and Django shell is:</p> <pre><code>Method Not Allowed (POST): / Method Not Allowed: / [01/May/2023 17:08:34] &quot;POST / HTTP/1.1&quot; 405 0 </code>...
<python><jquery><django>
2023-05-01 12:45:09
1
359
Omid Shojaee
76,146,972
6,687,699
Heroku deployment failed yet the build has passed
<p>I am facing this error on Heroku but I don't know the issue :</p> <pre><code>Traceback (most recent call last): File &quot;/app/manage.py&quot;, line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause o...
<python><django>
2023-05-01 12:33:06
0
4,030
Lutaaya Huzaifah Idris
76,146,824
19,325,656
Improve performance of qs with multiple filters and exclude statements
<p>I'm writing an app that has &quot;social media capabilities&quot;. You can block someone you can wave to someone etc...</p> <p>I have <code>get_queryset</code> for getting all users you didn't see on the app or blocked them with multiple exclude and filter statements that look like this.</p> <pre class="lang-py pret...
<python><django><django-models><django-rest-framework><django-queryset>
2023-05-01 12:11:57
1
471
rafaelHTML
76,146,799
4,755,229
Group consecutive True in 1-D numpy array
<p>Suppose we have a boolean array <code>x=np.array([True, True, False, True, False])</code>. There are two consecutive group of <code>True</code>. What I want is to create a list of boolean arrays <code>l</code> where each array in <code>l</code> contains exactly one set of consecutive <code>True</code>. For instance,...
<python><numpy>
2023-05-01 12:07:16
3
498
Hojin Cho
76,146,740
15,966,103
Django inheriting from base.html not displaying content on child page
<p>I have a <code>base.html</code> file:</p> <pre><code> {% load static %} {% load custom_tags %} &lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;script src=&quot;https://code.jquery.com/jquery-3.6.0.min.js&quot;&gt;&lt;/script&gt; {% comment %} &lt;script type=&quot...
<python><django><django-templates>
2023-05-01 11:57:43
1
918
jahantaila
76,146,571
6,550,449
How to make Celery I/O bound tasks execute concurrently?
<p>The only thing my Celery task is doing is making an API request and sending the response back to <code>Redis</code> queue. What I'd like to achieve is to utilize as many resources as possible by executing tasks in a coroutine-like fashion. This way every time a coroutine hits <code>requests.post()</code> the context...
<python><asynchronous><celery><gevent><greenlets>
2023-05-01 11:31:29
1
927
Taras Mykhalchuk
76,146,556
15,656,276
How to build CNN in Pytorch for RGB images?
<p>I am building a CNN in Pytorch. Below is the code I would use for grayscale input images:</p> <pre class="lang-py prettyprint-override"><code>import torch.nn as nn import torch.nn.functional as F class Net(nn.Module): def __init__(self): super(Net, self).__init__() # 1x1x28x28 to 32x1x28x28 self.conv1...
<python><pytorch><conv-neural-network>
2023-05-01 11:29:36
1
520
chai
76,146,386
15,803,668
Installing langchain and kor in PyCharm failling due to failed building wheel for greenlet
<p>I want to use <code>kor</code> and <code>langchain</code> in <code>PyCharm</code>. I import the packages using:</p> <pre><code># kor from kor.extraction import create_extraction_chain from kor.nodes import Object, Text, Number # LangChain Models from langchain.chat_models import ChatOpenAI from langchain.llms impor...
<python><pip><pycharm>
2023-05-01 10:59:17
1
453
Mazze
76,146,250
16,250,404
Calculate required start date for work order excluding weekends to reach shipping date
<p>Suppose there is an order which we have to ship on 28/04/2023 12:00 PM and to finish that order we need 11d:03h:36m:10s time. Find datetime when we should start working on that order.</p> <p>Conditions:</p> <ol> <li>Planned start date should not fall in Friday 22:00 PM to Sunday 22:00 PM.</li> <li>Also exclude Frida...
<python><datetime><timedelta>
2023-05-01 10:34:20
2
933
Hemal Patel
76,146,187
1,330,734
Unpacking a list of tuples of func, *args, **kwargs / command design pattern
<p>I have a routine that will take a list of tuples in the form:</p> <pre><code>(function, [optional] arguments, [optional] keyword arguments) </code></pre> <p>as part of a Command design pattern implementation.</p> <pre><code>ORG1_PROCESS = [(add_header_row, df, COLUMN_LABELS['ORG1']), (func_1, {'abc' ...
<python><syntax-error><iterable-unpacking>
2023-05-01 10:19:36
1
490
user1330734
76,146,181
992,687
How do I fix misquoted CSV files to allow parsing them with the csv module?
<p>I'd like the below code to avoid splitting within double quotes, but it does:</p> <pre><code>import csv from io import StringIO contents = &quot;&quot;&quot; gene &quot;Tagln2&quot;; note &quot;putative; transgelin 2 (MGD|MGI:1312985 GB|BC049861, evidence: BLASTN, 99%, match=1379)&quot;; product &quot;transgelin-2&...
<python><csv>
2023-05-01 10:18:53
2
32,459
The Unfun Cat
76,146,072
11,644,523
Dynamic pivot or lateral flatten in Snowflake / Snowpark to columns
<p>Given this sample table in Snowflake:</p> <pre><code>CREATE OR REPLACE TABLE vnt (src variant) AS SELECT parse_json(column1) as src FROM values ('{&quot;a&quot;: 1,&quot;b&quot;: 2,&quot;c&quot;: 3}'), ('{&quot;a&quot;: 1,&quot;b&quot;: 2,&quot;c&quot;: 3,&quot;d&quot;: 4}'); select * from vnt; </code></pre> <p>I w...
<python><snowflake-cloud-data-platform>
2023-05-01 10:01:10
1
735
Dametime
76,146,041
12,535,999
Scaling Matplotlib Colorbar
<p>I do many scatterplots (x vs. y) with a colormap to visualize a third variable (z). Since I do this for many z-variables, this has to work without manual intervention. Now the problem is, that some z-variables have only some very high values, so that the scaling of the colormap ist not useful (see figure).</p> <p>Ho...
<python><matplotlib><plot><colormap>
2023-05-01 09:56:39
0
315
Scrabyard
76,145,777
1,581,090
How to fix "pywinauto" not starting a windows application?
<p>I am trying to use python 3.10.11 on windows 10 to start a windows application. The command I am using is</p> <pre><code>from pywinauto.application import Application path = r&quot;C:\Program Files (x86)\Main_App\SafetyToolbox\ConfigurationRegister.exe&quot; app = Application(backend='uia').connect(path=path, timeou...
<python><windows><pywinauto>
2023-05-01 09:01:58
1
45,023
Alex
76,145,761
461,499
Use poetry to create binary distributable with pyinstaller on 'package'?
<p>I think I'm missing something simple</p> <p>I have a python poetry application:</p> <pre><code>name = &quot;my-first-api&quot; version = &quot;0.1.0&quot; description = &quot;&quot; readme = &quot;README.md&quot; packages = [{include = &quot;application&quot;}] [tool.poetry.scripts] start = &quot;main:start&quot; ...
<python><package><executable><python-poetry>
2023-05-01 08:58:48
4
20,319
Rob Audenaerde
76,145,647
11,241,501
enhance Tabula for accurate text with layout extraction
<p>I extracted all the text from pdf using tabula and it is great but as my pdf has border less tables and in some rows only single column is present with width of 3 columns, tabula put all text into single column.</p> <p>let me explain via some example. I highlighted the line in image using blue arrow. If I remove thi...
<python><pdf><pdfbox><tabula>
2023-05-01 08:34:03
0
312
Sybghatallah Marwat
76,145,539
8,621,405
How to prevent overlapping of subplots in Plotly using `make_subplots`
<p>I am creating a dashboard to visualize data using the Plotly and Dash packages in Python.</p> <p>I use the <code>prepare_plot_data</code> and <code>prepare_data_trend</code> functions to prepare the data for plotting.</p> <p>I am trying to create two subplots in one figure using <code>make_subplots</code> to set up ...
<python><python-3.x><plotly-dash><heatmap><plotly>
2023-05-01 08:10:16
1
325
CYC
76,145,466
11,162,983
How to compute Euler angles from Quaternion form?
<p>I am trying to use the Quaternion form instead of rotation matrices.</p> <p>I already trained my model, but when I need to test the model, I must compute Euler angles from the Quaternion form as this person did with <a href="https://github.com/papagina/RotationContinuity/blob/758b0ce551c06372cab7022d4c0bdf331c89c696...
<python><quaternions><euler-angles>
2023-05-01 07:54:21
0
987
Redhwan
76,145,455
2,186,349
Python AzureAppConfiguration SDK and Azure CLI SDK refuse to authenticate
<p>So I'm having all sorts of problems trying to authenticate a Python environment. My ultimate goal here is to use the Azure AppConfiguration SDK to read values from an AppConfig service in Azure. But right now I'm failing at the very first hurdle.</p> <p>FYI I'm running all of this on a Windows 11 machine using VS Co...
<python><azure><azure-cli><azure-app-configuration>
2023-05-01 07:52:22
1
401
Martin Hatch
76,145,394
2,707,342
Run Commands From Frontend Client in a Kubernetes Pod Using Python Kubernetes Client
<p>I am trying to build a Linux Playground using Django, Django Channels, Docker, and Kubernetes. Technically, how this would work is a user will head to the terminal route where a terminal-like interface will be displayed and they will be able to run Linux commands and interact with it just like they are interacting w...
<python><linux><docker><kubernetes><terminal>
2023-05-01 07:37:06
1
571
Harith
76,145,334
11,649,567
Error while trying to call np.ravel_multi_index function in python to convert subscripts to linear Indices for Three-Dimensional Array
<p>I am trying to use the np.ravel_multi_index function in order to convert y,x matrix subscripts to a linear index. Both y and x are ndarrays of shape/dimension (240,1236,4). Basically the line of code which I used is as follow:</p> <pre><code>lin_indices = np.ravel_multi_index((y, x), dims=x.shape) </code></pre> <p>...
<python><python-3.x><numpy>
2023-05-01 07:24:13
1
400
mashtock
76,145,123
832,230
Vectorize iterative Python loop: c[i] = a[i] + b[i] * c[i-1]
<p>I have an iterative Python function:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd def calculate_result(foo: pd.Series, bar: pd.Series, baz: pd.Series) -&gt; pd.Series: result = pd.Series(index=foo.index, dtype=float) result.iloc[0] = foo.iloc[0] for i in range(1, len(foo)): ...
<python><pandas><numpy><vectorization>
2023-05-01 06:34:20
1
64,534
Asclepius
76,144,837
20,122,390
How to create multiple records in a firebase realtime path?
<p>I am using a firebase real time database for a web application that I have written in python. One of my endpoints has the function that the client can load a csv file and subsequently each row of the csv will be converted to a record (node) in a specific path in the database (I simply read the csv and convert it to ...
<python><database><firebase><firebase-realtime-database><fastapi>
2023-05-01 05:08:17
1
988
Diego L
76,144,789
17,347,824
Postgresql in Python - Joining tables on a matching variable that is not showing as matching
<p>I have two tables in a database, 1 is a table of NFL teams (teams) and the other is a table of NFL games (games). The games table has the full team name of the home team (team_home) and the away team (team_away), the teams table has the full team name (team_name) and the team id (team_id) such as SF for San Fransisc...
<python><postgresql>
2023-05-01 04:53:21
0
409
data_life
76,144,756
2,987,552
ModuleNotFoundError: No module named '_ctypes' trying buildozer android debug
<p>I have setup WSL on my Windows 10 machine. I am trying to</p> <pre><code>buildozer android debug </code></pre> <p>on the ubunutu VM started on my Windows 10 machine so that I can convert my python application(s) to android apk(s) as documented in numerous articles. However I am getting stuck at</p> <pre><code>Module...
<python><android>
2023-05-01 04:42:54
0
598
Sameer Mahajan
76,144,724
15,233,108
error with ffmpeg converting images to video
<p>I have this code that I am using to convert multiple images in different folders into videos. this is the code i have:</p> <pre><code>counter = 0 list_of_videos = os.listdir('./Pending/') # obtain list of completed videos and strip extensions completed_mp4s = os.listdir('./outputvideos/') completed_mp4s = [x[:len(...
<python><python-3.x><image><video><ffmpeg>
2023-05-01 04:28:57
0
582
Megan Darcy
76,144,722
2,987,552
APK generated by github python to android action crashing
<p>I created apk using python to android action on github for my repo <a href="https://github.com/sameermahajan/Paadas" rel="nofollow noreferrer">https://github.com/sameermahajan/Paadas</a> (you can check my workflow yml as well as buildozer spec there). The apk is generated correctly without any error however when I d...
<python><android><github><github-actions>
2023-05-01 04:28:51
1
598
Sameer Mahajan
76,144,700
3,186,922
Scope of function parameter python
<p>I have this code snippet</p> <pre><code>def fun(i = []): print(&quot;i is&quot;, i) i.append(1) for k in range(5): print(&quot;k is&quot;, k) fun() </code></pre> <p>And its output</p> <pre><code>k is 0 i is [] k is 1 i is [1] k is 2 i is [1, 1] k is 3 i is [1, 1, 1] k is 4 i is [1, 1, 1, 1] </co...
<python><function><for-loop><default-value>
2023-05-01 04:17:31
1
6,332
Hari Krishnan
76,144,698
1,369,110
Ordinal logistic regression prediction and accuracy using statsmodels
<p>I am trying to do a ordinal logistic regression analysis using statsmodels. However, the predictions I'm getting are vastly different from that I get when using SciKit-Learn <code>LogisticRegression</code>.</p> <p>I'm using a dataset similar to the following. The aim is to predict the <code>quality</code> (on a scal...
<python><machine-learning><logistic-regression><prediction><statsmodels>
2023-05-01 04:16:03
1
650
AntikM
76,144,690
5,947,182
How do you scrape HTML content of a scrolled down page to the nth post on TikTok with Python Playwright?
<p><strong>I want to scroll down to let's say at least until 72 posts is visible on a TikTok user page</strong> such as <a href="https://www.tiktok.com/@thebeatles" rel="nofollow noreferrer">thebeatles page</a> <strong>and then save the HTML content</strong>. This page currently has 73 posts. I aimed to achieve the scr...
<python><scrollview><playwright><tiktok>
2023-05-01 04:12:25
2
388
Andrea
76,144,420
4,038,547
Problem using JPype on Mac OS X: I try to start the JVM but I get a DLL not found, but it is there
<p>My Python code is:</p> <pre class="lang-py prettyprint-override"><code>import jpype jvm_path = &quot;/Library/Java/JavaVirtualMachines/microsoft-11.jdk/Contents/Home/lib/jli/libjli.dylib&quot; jpype.startJVM( jvm_path, classpath=['~/org.alloytools.alloy.dist.jar'], ) </code></pre> <p>I get the following er...
<python><java><interop><alloy><jpype>
2023-05-01 02:17:18
1
425
Rodrigo Stv
76,144,372
4,873,538
Dynamic argument parser for python
<p>I am building a small wrapper which can accept a python command infer args and their associated values on the fly. I want something like and arg parser but the catch is that I do not know the arguments in advance. For example, I can get as input:</p> <pre><code>python some_script.py --arg1 val1 --arg2 val2 --arg3 va...
<python><argparse>
2023-05-01 01:53:09
2
521
saurbh
76,144,256
6,131,504
How to use parameterized fixtures in parameterized tests?
<p>I have some code that tests the values of a <code>Thing</code> object.</p> <pre class="lang-py prettyprint-override"><code>import pytest class Thing: def __init__(self, val) -&gt; None: self.val = val print(f&quot;Made a thing with val {val}&quot;, end=&quot; &quot;) @pytest.fixture(scope=&qu...
<python><pytest>
2023-05-01 00:59:23
1
318
Zeke Marffy
76,144,252
10,918,680
Saving a Plotly figure as an PNG image in a zip file is very slow
<p>I need to save a Plotly figure as an image in a zip file. I also need to store some texts that my program generates as a text file in the zip file. This is my attempt:</p> <pre><code>import io import zipfile import plotly.express as px import kaleido #write texts to stringIO s = io.StringIO() texts = ['foo','bar'] ...
<python><plotly>
2023-05-01 00:57:11
1
425
user173729
76,144,023
4,100,282
Elegantly include dynamically generated code in Python package
<p>I am writing a python package <code>foolib</code> which defines a class <code>foolib.Foo</code>. Creating a brand-new <code>Foo</code> object reads a <code>data_in</code> parameter and then performs an expensive numerical minimization, <strong>unless the results of this minimization are also specified in the instant...
<python><python-import><python-packaging>
2023-04-30 23:34:23
0
305
Mathieu
76,143,962
1,820,715
Calculating world coordinates of a pixel from a camera picture
<p>Sorry for this question. I know there are many <a href="https://stackoverflow.com/questions/30073616/calculating-world-coordinates-from-camera-coordinates">similar questions</a> but I really know nothing about math that involves this case (I'm not a 3D programmer) and those answers are very obscure to me, so I can't...
<python><3d><transformation><computational-geometry><raytracing>
2023-04-30 23:13:03
0
2,215
Magno C
76,143,920
13,330,700
Kubernetes health check always fails for django application
<p>I'm kinda new to kubernetes and I'm trying to figure out how to configure my health check. When I configure my <code>livenessProbe</code> it always returns a 400, but when I remove the probe, exec into the pod, and run <code>curl 127.0.0.1/health</code> I get <code>{&quot;status&quot;: &quot;ok&quot;}</code>.</p> <p...
<python><django><docker><kubernetes>
2023-04-30 22:57:54
1
499
mike_gundy123
76,143,836
15,966,103
Django block content not working properly
<p>I have a <code>base.html</code> file with the following code:</p> <pre><code>{% load static %} {% load custom_tags %} &lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;body&gt; &lt;style&gt; html { scroll-behavior: smooth; } *, ...
<javascript><python><html><css><django>
2023-04-30 22:30:37
1
918
jahantaila
76,143,807
5,065,546
Struggling to install pandas_datareader with conda install
<p>I'm trying to install pandas_datareader through conda install but having no luck. Each time I get the error message:</p> <pre><code>ERROR conda.core.link:_execute_actions(337): An error occurred while installing package 'conda-forge::charset-normalizer-2.1.1-pyhd8ed1ab_0'. CondaError: Cannot link a source that does ...
<python><anaconda>
2023-04-30 22:21:04
1
362
Euan Ritchie
76,143,799
733,002
talib.PLUS_DM - shouldn't the return value be bounded by [0, 100]?
<p>Why does this example return values out of the range [0, 100] for PLUS_DM, and why is it sensitive to scaling the values? I would assume with the ratio that changes of magnitude would cancel out.</p> <pre><code>import numpy as np import talib highs= np.array([39050.0, 39050.0, 39100.0, 39100.0, 39050.0, 39061.0, 39...
<python><ta-lib>
2023-04-30 22:17:22
1
1,031
Joe
76,143,677
1,930,402
How to do an efficient partial string match in Pandas?
<p>I have a dataframe of around 50k strings containing some variations of city names like these.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: right;">city</th> <th style="text-align: right;">variation</th> </tr> </thead> <tbody> <tr> <td style="text-align: right;">new ...
<python><pandas><optimization><lookup>
2023-04-30 21:39:08
1
1,509
pnv
76,143,613
11,135,962
Trying to add a pydantic model to a set gives unhashable error
<p>I have the following code</p> <pre><code>from pydantic import BaseModel class User(BaseModel): id: int name = &quot;Jane Doe&quot; def add_user(user: User): a = set() a.add(user) return a add_user(User(id=1)) </code></pre> <p>When I run this, I get the following error:</p> <pre><code>TypeEr...
<python><python-3.x><pydantic>
2023-04-30 21:24:33
2
3,620
some_programmer
76,143,494
14,529,779
Issue with a function that calculates the sum of positive elements after a negative element
<p>I am working on a Python function that takes an array as input and returns the maximum sum of positive elements that come right after a negative element:</p> <pre class="lang-py prettyprint-override"><code>def some(arr): som = 0 startSum = False ta = [] for i in range(len(arr)): if arr[i] &lt...
<python>
2023-04-30 20:53:38
1
9,636
TAHER El Mehdi
76,143,398
1,485,877
Pickle ignores __getstate__ on frozen dataclasses with slots
<p>You are supposed to be able to override how <code>pickle</code> pickles an object with <code>__getstate__</code> and <code>__setstate__</code>. However, these methods are ignored when a dataclass specifies both <code>frozen=True</code> and <code>slots=True</code>.</p> <pre class="lang-py prettyprint-override"><code>...
<python><pickle><python-dataclasses>
2023-04-30 20:30:45
1
9,852
drhagen
76,143,253
18,758,062
Running command with paramiko PTY gives error: write() argument must be str, not bytes
<p>I'm using <code>paramiko</code> to connect to the remote machine via SSH where a bash command is ran and the stdout output needs to be read line by line as they are sent.</p> <p>This is what I have so far. <code>get_pty=True</code> needs to be set.</p> <pre><code>import paramiko import sys ssh = paramiko.SSHClient(...
<python><python-3.x><ssh><paramiko><pty>
2023-04-30 19:55:53
1
1,623
gameveloster
76,143,042
2,097
Is there an interface to access pyproject.toml from Python?
<p>Is there an interface to access the information in pyproject.toml from Python?</p> <p>In particular, I'd like to access the dependencies. It doesn't seem hard to do</p> <pre class="lang-py prettyprint-override"><code>toml.load(&quot;pyproject.toml&quot;)['project']['dependencies'] </code></pre> <p>and then parse tha...
<python><python-importlib><toml><pyproject.toml>
2023-04-30 19:04:44
2
2,416
BlackShift
76,142,930
4,907,339
Why does pip not install the .whl version of a package on alpine base?
<p>While trying to roll a docker-in-docker image, I'm running up against an issue where certain python modules are not being installed by their pre-compiled <code>.whl</code> variants, instead they are trying to be source compiled. In this particular case it's Pandas and consequently NumPy:</p> <pre><code>FROM docker:...
<python>
2023-04-30 18:37:32
1
492
Jason
76,142,861
10,024,860
Behavior of Tensorflow's GradientTape when target is not a scalar
<p>Can somebody explain to me the shape and value of Tensorflow's <code>GradientTape</code> output when <code>target</code> is not a scalar value? For example, I had the following code:</p> <pre><code>import tensorflow as tf a = tf.Variable([[-1.], [0.], [1.]]) b = tf.Variable([[1.,2.,3.],[4.,5.,6.]]) with tf.Gradient...
<python><tensorflow><gradienttape>
2023-04-30 18:21:46
1
491
Joe C.
76,142,805
726,730
Python QTreeWidget const columns
<p>Is there any way to have a QTreeWidget with horizontal scroll bar but to have some specific columns (for example the first and the second) be const as the user scrolls horizontally?</p> <p>As for now there is no need to do something like that, but just in case is this possible? If yes how?</p>
<python><pyqt5><qtreewidget><qscrollarea><qscrollbar>
2023-04-30 18:07:57
0
2,427
Chris P
76,142,599
9,983,652
how to clear memory of global variables?
<p>I am using global variables to save big dataframe which is read from a file, so when it is read the first time executing callback, it is saved at a global variable. so when calling next time callback, I don't need to read it from an extenal file again, I just use it from global variable. Overtime, the dash app becom...
<python><plotly-dash>
2023-04-30 17:23:28
0
4,338
roudan
76,142,445
4,075,912
Converting pandas datetime to sparse datetime fails
<p>I'm trying to convert several columns in a pd.DataFrame from dense to sparse. The following MRE (dense integer to sparse integer) works:</p> <pre><code>&gt;&gt;&gt; dense = pd.DataFrame({&quot;A&quot;: [1, 0, 0, 1]}) &gt;&gt;&gt; dtype = pd.SparseDtype(int, fill_value=0) &gt;&gt;&gt; sparse = dense.astype(dtype) &gt...
<python><pandas><sparse-matrix>
2023-04-30 16:52:44
1
439
David Johnson