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
75,513,028
1,200,914
Running Selenium Chrome with extension - Chrome not reachable
<p>I'm developing an app with selenium on an ubuntu EC2 instance. Therefore, there are no displays.</p> <p>To start Selenium I use xvbf. This is what I used to install xvbf and selenium:</p> <pre><code>sudo apt-get -y update sudo apt-get install -y unzip xvfb libxi6 libgconf-2-4 default-jdk xdg-utils sudo snap install ...
<python><selenium-webdriver><google-chrome-extension><selenium-chromedriver>
2023-02-20 18:39:29
1
3,052
Learning from masters
75,513,023
271,388
Why don't callable attributes of a class become methods?
<p>Consider the following snippet.</p> <pre class="lang-py prettyprint-override"><code>import types def deff(s): print(f&quot;deff called, {s=}&quot;) lam = lambda s: print(f&quot;lam called, {s=}&quot;) class Clbl: def __call__(s): print(f&quot;__call__ called, {s=}&quot;) clbl = Clbl() print(type...
<python><methods><language-lawyer>
2023-02-20 18:38:53
1
1,808
CrabMan
75,512,982
3,057,865
Automatically switch Python gettext strings with their translations from a .po file
<p>I have a Python/Django code base in which strings are encapsulated in gettext calls. For legacy reasons, the strings in the Python files have been written in French and the English translations are inside a .po file.</p> <p>I now wish to make sure the Python files are in English, strings included. I would like to au...
<python><gettext>
2023-02-20 18:35:04
1
313
user3057865
75,512,978
1,549,736
Why is conda-build falsely reporting that numpy is not a build requirement?
<p>In response to this command:</p> <p><code>conda build --python=3.9 --numpy=1.23 -c dbanas -c defaults -c conda-forge conda.recipe/pyibis-ami/</code></p> <p>I'm getting the following error:</p> <p><code>ValueError: numpy x.x specified, but numpy not in build requirements.</code></p> <p>Here's my <code>meta.yaml</code...
<python><numpy><conda-build>
2023-02-20 18:34:30
0
2,018
David Banas
75,512,976
7,692,855
Converting a list of strings into part of a f string in Python
<p>I have a list of error messages:</p> <pre><code>errors = [ &quot;this is an error&quot;, &quot;this is another error&quot;, ] </code></pre> <p>I am then sending this as an email using Amazon SES:</p> <pre><code>ses_client.send_email( Destination={ &quot;ToAddresses&quot;: [ ...
<python><f-string>
2023-02-20 18:34:30
2
1,472
user7692855
75,512,629
11,782,590
Why tuples with the same elements declared in different way results in several memory addresses instead of one?
<p>I am learning about memory management in python. Recently I was exploring differences in memory addresses in mutable and immutable objects. At first I came to the conclusion that the same objects that are also immutable result in only one memory address for optimization purposes. And mutable objects always receive n...
<python><memory><tuples><cpython>
2023-02-20 17:50:45
1
585
Peksio
75,512,598
131,693
Reading a cell value as a str in openpyxl
<p>I want to read a numeric cell value as a str rather than a float, but as far as I can see the API doesn't allow for this, is there something I'm missing?</p> <p>The reason for this is the cell value is currency based, and as such I want to convert use it as a decimal not a float.</p> <p>Alternatively, is there a way...
<python><openpyxl>
2023-02-20 17:47:11
1
2,301
Kingamajick
75,512,556
1,874,170
pythonic way to decorate a generator at run-time?
<p>I have the following code:</p> <pre class="lang-py prettyprint-override"><code>def assertfilter(iterator, predicate): # TODO support send() for result in iterator: if not predicate(result): raise AssertionError(&quot;predicate failed in assertfilter()&quot;) yield result </code></...
<python><design-patterns><iterator>
2023-02-20 17:42:34
1
1,117
JamesTheAwesomeDude
75,512,552
848,746
matching two csv columns (fuzzy?) and extracting row information
<p>I have two csv files with some 1k entries each like so:</p> <pre><code>#1.csv Org,Address,Phone George, 121 faraday street, 837-837 Newton, 837 Bohr Street, 8327-837 ... </code></pre> <pre><code>#2.csv Org,location,course George William, Paris, Engineering P Newton, London, Arts ... </code></pre> <p>Essentially, col...
<python><bash><csv>
2023-02-20 17:42:04
1
5,913
AJW
75,512,527
20,967,663
python click: determine whether argument comes from default or from user
<p>How to tell whether an argument in click is coming from the user or is the default value?</p> <p>For example:</p> <pre><code>import click @click.command() @click.option('--value', default=1, help='a value.') def hello(value): print(value) if __name__ == &quot;__main__&quot;: hello() </code></pre> <p>Now if...
<python><python-click>
2023-02-20 17:39:12
1
303
Osman Mamun
75,512,427
7,568,316
How to find a list of structured records in a router log with Python
<p>We receive daily some dumps from our routers. This has been configured by the vendor of the routers. Now I would like to find the real records in these logs and put them in tables.</p> <p>Here is a sample of such a dump file.</p> <pre><code>PZMO120# PZMO120# show interface description ...
<python>
2023-02-20 17:27:33
1
755
Harry Leboeuf
75,512,328
9,773,920
Redshift COPY command failing - Lambda
<p>I have a scenario where I get the last modified file from a specific S3 folder and there by I want to COPY the csv data into a redshift table. Below is the code:</p> <pre><code>def lambda_handler(event, context): s3_client = boto3.client(&quot;s3&quot;) list_of_s3_objs = s3_client.list_objects_v2(Bucket...
<python><amazon-web-services><amazon-s3><aws-lambda><amazon-redshift>
2023-02-20 17:15:04
2
1,619
Rick
75,512,324
14,167,364
tkinter window not working properly with askDirectory
<p>I am trying to have the askDirectory open a floder which the user selects. Once they select this, some other functions will run that will take some time. Instead of putting that here, I added a sleep function to represent this. While this is running, I need another window to show that something is running in the bac...
<python><tkinter>
2023-02-20 17:14:46
1
580
Justin Oberle
75,512,306
14,088,584
Make a dataframe from list of variables which are lists
<p>I have a list of variables in which each variable is a list. And I want to use that list to form a dataframe.</p> <pre><code>A=[1,2] B=[4,3] C=[A,B] </code></pre> <p>I want to create the dataframe using the list C that looks like this:</p> <pre><code>A B 1 4 2 3 </code></pre> <p>I tried doing it like this</p> <pre><...
<python><pandas><dataframe>
2023-02-20 17:12:07
2
422
SHIVANSHU SAHOO
75,512,205
14,327,939
Unexpected behaviour of pandas.MultiIndex.set_levels
<p>I have noticed an unexpected result when resetting the level values in a <code>pandas.MultiIndex</code>. The minimal working example I have found to reproduce the problem is as follows:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd numbers = np.arange(11).astype(str) col...
<python><pandas>
2023-02-20 17:01:04
1
578
Alperino
75,512,042
3,810,748
What do the indices mean for the input/output in PyTorch's documentation?
<p>I was reading the <a href="https://pytorch.org/docs/stable/generated/torch.nn.Conv2d.html" rel="nofollow noreferrer">documentation</a> for PyTorch's <code>Conv2d</code> layer when I encountered this:</p> <p><a href="https://i.sstatic.net/AMy49m.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/AMy49m.pn...
<python><pytorch>
2023-02-20 16:47:39
1
6,155
AlanSTACK
75,512,032
1,788,771
How to hook up DRF ModelViewset to the app's root
<p>I have a small django app with a single ViewSet that extends DRF's ModelViewSet. I've tried attaching it to the app's root url like so</p> <pre class="lang-py prettyprint-override"><code>urlpatterns = [ path(r&quot;&quot;, NotificationViewSet.as_view(), name=&quot;company&quot;), ] </code></pre> <p>But this is c...
<python><django><routes><django-rest-framework>
2023-02-20 16:46:27
1
4,107
kaan_atakan
75,511,991
10,574,250
Run a notebook from different directory in another notebook in Jupyter Lab Domino
<p>I am trying to run <code>notebook_torun.ipynb</code> in <code>test_notebook.ipynb</code> within Jupyter Lab Domino from a different directory but have failed. The structure looks as such:</p> <pre><code>root -&gt; mnt -&gt; test_notebook.ipynb </code></pre> <p>and I want to run</p> <pre><code>root -&gt; repos -&gt;...
<python><jupyter-notebook><jupyter-lab><ibm-domino>
2023-02-20 16:42:13
1
1,555
geds133
75,511,978
9,484,595
Debugging python–cpp bindings
<p>I have written a C++-library with bindings for python. My python code (a jupyer notebook) calling the library makes crashes. The problem lies within the library. I would like to debug this (using lldb, at best from within vs code). So far, I've tried to call the library from a python file <code>test.py</code>, issue...
<python><c++><debugging><binding><lldb>
2023-02-20 16:40:13
0
893
Bubaya
75,511,919
1,572,146
Escape Python to `json[]` for `COPY FROM` PostgreSQL insertion?
<p>How do I correctly escape for <code>json[]</code> column insertion?</p> <p>Currently I get this error, [<a href="https://gist.github.com/SamuelMarks/fec744a620e2abd0257671aa6f2a96b4" rel="nofollow noreferrer">run script with more debugging</a>]:</p> <pre><code>COPY &quot;my_table&quot; (&quot;json_arr_col&quot;, &qu...
<python><postgresql><escaping><psycopg2><postgresql-json>
2023-02-20 16:33:47
1
1,930
Samuel Marks
75,511,829
451,878
Call a viewset in another viewset with POST method
<p>I want to call a function of a viewset in another viewset, with POST method. I don't known how to do that :(, I've this error &quot;GET method not allowed&quot; :</p> <p>url from initial AccessViewset :</p> <pre><code>access_level_add = accesslevel.AccessViewSet.as_view({&quot;post&quot;: &quot;add&quot;}) </code><...
<python><django><django-rest-framework><django-viewsets>
2023-02-20 16:25:28
0
1,481
James
75,511,700
7,776,781
Generic type inside recursive type not passing mypy check
<p>I have a slightly complicated type situation where the minimum reproducible version I could come up with looks like this:</p> <pre><code>from __future__ import annotations from typing import TypeVar T = TypeVar(&quot;T&quot;) class MyClass(list[T]): def method(self, num: int) -&gt; MyClass[MyRecursiveType]: ...
<python><python-3.x><type-hinting><mypy>
2023-02-20 16:13:03
0
619
Fredrik Nilsson
75,511,601
18,326,398
Nested Serializer Not Working in django rest framework. How can I fix it?
<p>Can you tell me where is the actual problem? My goal is to build up an API that will show how many courses an instructor offers.</p> <p><em><strong>models.py:</strong></em></p> <pre><code>class Instructor(models.Model): name = models.CharField(max_length=40) email = models.CharField(max_length=250) class C...
<python><django><django-models><django-rest-framework><django-serializer>
2023-02-20 16:04:15
1
421
Mossaddak
75,511,572
5,931,672
Add column of value_counts based on multiple columns
<p>So basically this questios in equal to either <a href="https://stackoverflow.com/questions/17709270/create-column-of-value-counts-in-pandas-dataframe">17709270</a> or <a href="https://stackoverflow.com/questions/29791785/python-pandas-add-a-column-to-my-dataframe-that-counts-a-variable">29791785</a>, with the differ...
<python><pandas>
2023-02-20 16:02:05
3
4,192
J Agustin Barrachina
75,511,545
7,530,975
Is there a way to animate a graph using matplotlib which incorporates blitting and has an advancing xaxis showing a window of time
<p>This post replaces a prior ill-formed and hurried post. I have been doing research on blitting with matplotlib. Earlier I posted a lengthy description with complicated code which, of course, invoked no response. I have reworked the question and code to provide a simple and hopefully clear picture of what I am seekin...
<python><matplotlib>
2023-02-20 15:59:38
1
341
GAF
75,511,524
20,392
nginx+uwsgi stops responding after auto reload
<p>I have a docker container based off Alpine 3.16 It runs nginx/uwsgi with supervisord for a django based app.</p> <p>This Dockerfile has been pretty much the same for several years now. Auto reload worked fine.</p> <p>Suddenly today after the container rebuilt, auto-reload fails in a strange way - it get hung up for ...
<python><django><nginx><uwsgi><supervisord>
2023-02-20 15:58:01
1
6,975
rep_movsd
75,511,490
5,197,329
How to parametrize a parametrized function in pytest?
<p>I have the following pytest function, where GAMES_AVAILABLE is a dynamic list of different games that I want my code to test.</p> <pre><code>@pytest.mark.parametrize(&quot;game_ref&quot;, GAMES_AVAILABLE) def test_all_games(game_ref): game_components = build_game_components(game_ref) available_players = dete...
<python><unit-testing><pytest>
2023-02-20 15:55:00
1
546
Tue
75,511,482
1,328,658
Data import, analysis and exporting a JSON file by using python
<p>I downloaded a JSON file by using the services offered by <a href="https://www.api-football.com/" rel="nofollow noreferrer">API-Football</a> using python and its package <em>requests</em>. I wrote down the following code to download the JSON file from the web:</p> <pre><code>import requests as requests # URL url = ...
<python><json><dataframe><parsing><python-requests>
2023-02-20 15:54:11
1
603
QuantumGorilla
75,511,420
10,673,107
Python - Build YAML file using .env file
<p>I am having a problem with python. In my project, I have the following .env file:</p> <pre><code>APP_NAME=laravel-api APP_ENV=dev APP_KEY= APP_DEBUG=true APP_URL=http://localhost APP_HOST=laravel-api APP_PORT=9000 WEB_PORT=8000 LOG_CHANNEL=stack DB_CONNECTION=pgsql DB_HOST=database DB_PORT=5432 DB_DATABASE=larave...
<python>
2023-02-20 15:48:54
1
994
A. Vreeswijk
75,511,410
374,458
Wrong image size when using Matplotlib savefig
<p>I use <code>savefig</code> from Matplotlib to get an Image from a figure, and this image is modified with PIL after that. I also want to remove every padding.</p> <p>My problem is that the final size of the image is smaller than expected. For example:</p> <ul> <li>Size = (8, 10)</li> <li>DPI = 300</li> <li>We expect...
<python><matplotlib><python-imaging-library><savefig>
2023-02-20 15:47:32
1
1,870
Nicolas
75,511,246
659,117
How can I use the python compile function on an empty string?
<p>I have a piece of code that calculates the sum of a number of variables. For example, with 3 variables (<code>A = 1</code>, <code>B = 2</code>, <code>C = 3</code>) it outputs the sum <code>X = 6</code>. The way the code is implemented this is set up as a list with two strings:</p> <pre><code>Y = [['X', 'A+B+C']] </c...
<python><compilation><eval>
2023-02-20 15:33:34
1
1,445
point618
75,511,007
18,366,396
How to convert date in python
<p>Iam using fullcalendar <a href="https://fullcalendar.io/" rel="nofollow noreferrer">fullcalendar</a></p> <p>From my web template iam getting 2 dates in django a <code>startdate</code> and an <code>enddate</code></p> <p>Getting my startdate:</p> <pre><code>start = request.GET.get('start', None) </code></pre> <p>I nee...
<python><django>
2023-02-20 15:10:44
2
841
saro
75,510,939
13,158,157
pandas conditional merge on multiple columns
<p>I have two dataframes of structured similar to:</p> <pre><code>conditions = pd.DataFrame({ 'keywords_0':[&quot;a&quot;, &quot;c&quot;, &quot;e&quot;], 'keywords_1':[&quot;b&quot;, &quot;d&quot;, &quot;f&quot;], 'keywords_2':[&quot;00&quot;, &quot;01&quot;, &quot;02&quot;], 'price': [1, 2 ,3] }) targ...
<python><pandas><merge>
2023-02-20 15:04:52
4
525
euh
75,510,934
16,363,897
Get first and nth non-blank value per row
<p>I have the following input dataframe:</p> <pre><code> 0 1 2 3 4 date 2007-02-15 NaN -0.88 0.80 NaN 0.5 2007-02-16 0.5 -0.84 NaN 0.29 NaN 2007-02-19 NaN -0.84 0.79 0.29 NaN 2007-02-20 0.5 0.50 0.67 0.20 0.5 </code></pre> <p>I need to get...
<python><pandas>
2023-02-20 15:04:24
2
842
younggotti
75,510,849
2,516,697
How to add two separated (not connected) flows in sankey diagram with python/matplotlib?
<p>I would like to create sankey diagram showing two seprated flows? Flow named <code>L</code> and <code>P</code>. Like one image below (It's only example image for tests). <a href="https://i.sstatic.net/GrzdR.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/GrzdR.png" alt="enter image description here" /...
<python><matplotlib><sankey-diagram>
2023-02-20 14:57:07
2
757
s.paszko
75,510,837
9,490,769
Upsample pandas data right index inclusive
<p>I have the following data which I want to resample (upsample) into sometimes 30 minute intervals, sometimes 15 minute intervals, sometime 5 minute intervals</p> <pre class="lang-py prettyprint-override"><code> TIME VALUE 0 2023-01-02 01:00:00 94.73 1 2023-01-02 02:00:00 ...
<python><pandas>
2023-02-20 14:56:22
1
3,345
oskros
75,510,621
17,530,552
How to change or multiply the xticks by a factor in plt.acorr (matplotlib)
<p>I am plotting the autocorrelation function via <code>plt.acorr</code> of a time-series called <code>data</code>. The sampling rate of the recorded time-series is 2.16 seconds or 0.4629 Hz.</p> <p><strong>Problem:</strong> <code>plt.acorr</code> spaces the lags’ xticks in accordance to the sampling point sequence, me...
<python><matplotlib>
2023-02-20 14:35:34
1
415
Philipp
75,510,487
13,518,907
Huggingface Trainer(): K-Fold Cross Validation
<p>I am following this <a href="https://towardsdatascience.com/fine-tuning-pretrained-nlp-models-with-huggingfaces-trainer-6326a4456e7b" rel="noreferrer">tutorial</a> from TowardsDataScience for text classification using Huggingface Trainer. To get a more robust model I want to do a K-Fold Cross Validation, but I am no...
<python><cross-validation><huggingface-transformers><bert-language-model><k-fold>
2023-02-20 14:25:54
2
565
Maxl Gemeinderat
75,510,407
656,912
Why does Jupyter Lab install fail without Rust?
<p>I'm using MBA M2 macOS 13.2.1, and installing Jupyter Lab using pip worked last night:</p> <pre class="lang-none prettyprint-override"><code>pip install jupyterlab </code></pre> <p>Then I did a clean maintenance reinstall (<code>pip freeze | xargs pip uninstall -y -q &amp;&amp; pip install -U -r .requirements.txt &a...
<python><pip><jupyter-lab>
2023-02-20 14:19:11
0
49,146
orome
75,510,181
10,045,805
Python - How to modify existing drop-down list in a document using Google Docs API?
<p>I have a Google Docs document stored in a Google Drive folder.</p> <p>This document contains new features from Google Docs like the drop-down list.</p> <blockquote> <p><a href="https://i.sstatic.net/aOKDv.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/aOKDv.png" alt="enter image description here" /><...
<python><google-apps-script><google-docs><google-docs-api>
2023-02-20 13:59:27
1
380
cuzureau
75,510,147
4,105,440
Find all specified periods that fit into a certain date range
<p>Suppose I have a certain defined range of dates, e.g. <code>2022-12-25</code> to <code>2023-02-05</code>. I want to find all <strong>fully closed</strong> periods (specified by the user) that fit into this date range. For example, if the user specifies <code>months</code> and <code>decades</code>, the method should ...
<python><pandas><datetime><period>
2023-02-20 13:56:31
1
673
Droid
75,510,062
51,816
How to find best fit line using PCA in Python?
<p>I have this code that does it using SVD. But I want to know how to do the same using PCA. Online all I can find is that they are related, etc, but not sure how they are related and how they are different in code, doing the exact same thing.</p> <p>I just want to see how PCA does this differently than SVD.</p> <pre><...
<python><numpy><math><pca><svd>
2023-02-20 13:48:11
2
333,709
Joan Venge
75,509,964
1,356,710
Python mysql.connector multithreading issues
<p>I am getting errors while using an object with a mysql connection in a multithreaded context. The error I get is <code>MySQL Connection not available</code> and I am almost sure is because of the multithread, but I don't know what would be the best way to overcome this.</p> <p>I've made an example code that creates ...
<python><mysql-python>
2023-02-20 13:38:31
1
2,055
Raul Luna
75,509,891
241,552
FastAPI: get data into view even though data is invalid
<p>In our app there is a view that accepts an instance of a model as an argument, and if the request data misses some fields, the view does not get called, eg:</p> <pre class="lang-py prettyprint-override"><code>class Item(BaseModel): id: int price: float is_offer: bool | None = False @app.post(&quot;/&quo...
<python><fastapi><pydantic><starlette>
2023-02-20 13:31:27
1
9,790
Ibolit
75,509,818
3,059,024
Python mock return a list of preset values in sequence and then switch to one value thereafter
<p>How would I make my mock return False twice and then any additional call to return True. Here's what I have so far:</p> <pre><code>def test_moc(self): class A: def __init__(self): self.value = False def getValue(self): return self.value m = mock.Mock(A) m.getVa...
<python><unit-testing><mocking>
2023-02-20 13:25:27
1
7,759
CiaranWelsh
75,509,802
1,102,514
Test email does not arrive in mail.outbox when sent by Django-RQ worker
<p>I've set up a test within <code>Django</code> that sends an email, in the background, using <code>Django-RQ</code>.</p> <p>I call the code that enqueues the <code>send_email</code> task, then, I get the <code>django-rq</code> worker, and call .work(), with <code>burst=True</code>.</p> <p>In my console, I can see the...
<python><django><python-rq><django-rq><rq>
2023-02-20 13:23:58
0
1,401
Scratcha
75,509,777
1,150,448
aiohttp returns empty cookie after using google identity services
<p>I migrated Google Sign-In JavaScript platform library to Google Identity Services. After successful login in Safari macOS, my <code>aiohttp</code> server sets cookie <code>myid=10</code> that is used by the server. Unfortunately when I read cookie <code>request.cookie.get('myid')</code>, it returns <code>None</code>...
<python><google-apps-script><cookies><aiohttp>
2023-02-20 13:21:00
1
3,599
vvkatwss vvkatwss
75,509,674
12,858,691
Keras Tuner how to do basic grid search
<p><a href="https://keras.io/api/keras_tuner/tuners/" rel="nofollow noreferrer">Keras Tuner</a> offers several tuning strategies in the form of tuner classes. I fail to find an implementation for the most basic tuning strategy, which is a grid search. Did I oversee it? If not, is there a way to force the strategy on on...
<python><tensorflow><hyperparameters><keras-tuner>
2023-02-20 13:11:35
1
611
Viktor
75,509,641
7,692,855
Permissions [Errno 13] error running Python in Docker with AWS Lambda
<p>I have a simple python script in lambda_handler.py:</p> <pre><code>def handler(event, context): print(&quot;success&quot;) return &quot;Success&quot; </code></pre> <p>and I am packaging it in Docker to run on AWS Lambda.</p> <p>The Dockerfile is:</p> <pre><code>FROM public.ecr.aws/lambda/python:3.9 COPY lam...
<python><docker><lambda>
2023-02-20 13:08:08
2
1,472
user7692855
75,509,544
2,122,773
Reconstruct audio from cepstrum
<p>I am trying a simple task &gt; calculate the cepstrum of a small audio sample, lift it and do the inverse process to build the audio file back. I obviously made a mistake as it does not work well</p> <pre><code>import numpy as np from scipy.signal import lfilter import soundfile as sf import librosa import IPython.d...
<python><signal-processing>
2023-02-20 12:56:46
1
313
pm200107
75,509,486
7,905,329
How to read multiple CSV files from Google in Jyputer Notebook and traverse each file
<p>I have 45 files in my Google Shared Drive. I need to load them in Jyputer Notebook. Each files are data for each month for the last 3 years.</p> <p>I need result for each file. How do I do this Pandas?</p> <p>The operations are as follows:</p> <ol> <li>Read all 45 files</li> <li>Get Sum(col 1), Sum(col 2), Sum(Col 3...
<python><python-3.x><pandas><group-by><google-drive-shared-drive>
2023-02-20 12:49:55
1
364
anagha s
75,509,457
5,318,634
Store an array, or a list, of fixed length as a class attribute using slots in python
<p>I have an object that represents a <code>User</code> and a variable measured 20 times. The object will be something like this:</p> <pre class="lang-py prettyprint-override"><code>class User: user_id: str measures: List[float] #this is a list(or an array) of size 20 </code></pre> <p>Given that I have many us...
<python><python-dataclasses><slots>
2023-02-20 12:46:26
1
3,564
Pablo
75,509,397
8,580,652
What is the proper way for including a file under root directory when using pyscript with pyodide-worker option?
<p>I am trying out pyscript as one of the ways to share interactive dashboards with others. I have been able to get &quot;hello world&quot; to work. In my example, which is a quite common situation, I need to visualize a dataset, preferably embedded in the .html or a zipped folder that the receiver can just <strong>ope...
<python><visualization><panel><pyscript>
2023-02-20 12:39:42
1
398
John
75,509,372
355,232
Why is this a "hacky" way to import sys?
<p>I'm no expert in Python, but I'm managing an AWS-CDK repository which has this import along with the following comment in most subfolder classes.</p> <pre><code># Hacky way to get our utils - due to the way folder structure is right now import sys sys.path.append(&quot;..&quot;) [...] </code></pre> <p>The folder st...
<python><python-import>
2023-02-20 12:37:43
1
5,426
sbrattla
75,509,253
1,356,710
Value of module variable is restarted after initialization in python
<p>I am trying to create a global variable in python, but it seems that I don't understand well the concept. I have created a <code>my_connection</code> vairable in a module called <code>mysql_example</code> and then I have initialized it inside the <code>MysqlExample</code> class, but after that, the value is cleared....
<python>
2023-02-20 12:24:02
2
2,055
Raul Luna
75,509,146
4,915,288
combine serializer choicefield and serializermethodfield
<p>I have class Person with qualification field.</p> <p>class</p> <pre><code> QUALIFICATION_CHIOCES = [('mt', 'Matriculation'), ('pr', 'pre_university'), ('gd', 'graduate'), ('pg', 'post_graduate'), ('ot', 'other')] class Person(models.Model): name = models.CharField(max_length=255) qualificati...
<python><django><django-rest-framework><django-serializer>
2023-02-20 12:14:41
1
954
Lohith
75,509,107
5,452,001
How to get the location of a timestamp index? `data.columns.get_loc` seems to fail
<p>I'm iterating over a dataframe and I need to stop the iteration by the last Nth row.</p> <p><code>data.index[n]</code> works for getting the index but I'm having trouble to get its integer-location when the index is a datetime. It works with other indexes though.</p> <pre><code>&gt; n = -5 &gt; data.index[n] Timest...
<python><python-3.x><pandas><dataframe>
2023-02-20 12:11:03
1
595
42piratas
75,508,842
3,614,197
Generating number Sequence Python
<p>I want to generate a number sequence that repeats 2 consective numbers twice then skips a number and repeats the sequence wihin the range specified.</p> <p>such as</p> <p>0,0,1,1,3,3,4,4,6,6,7,7 and so forth.</p> <p>what I have so far</p> <pre><code>numrange = 10 numsequence = [i for i in range(numrange) for _ in r...
<python><range><sequence>
2023-02-20 11:43:42
3
636
Spooked
75,508,779
1,497,139
How do i add a class to a SchemaDefinition in LinkML?
<p>The diagrams in <a href="https://linkml.io/linkml-model/docs/SchemaDefinition/" rel="nofollow noreferrer">https://linkml.io/linkml-model/docs/SchemaDefinition/</a> and <a href="https://linkml.io/linkml-model/docs/ClassDefinition/" rel="nofollow noreferrer">https://linkml.io/linkml-model/docs/ClassDefinition/</a> sho...
<python><linkml>
2023-02-20 11:37:51
2
15,707
Wolfgang Fahl
75,508,668
6,887,010
Socket.io cross origin is not working while same origin is
<p>I know there are quite a lot of questions on this and I've read many of them. But still not working and it looks like it should, because there is no visible issue. I have working application on <code>https://mylocalhostdomain.com</code>. There is UI layer and API layer. API is requested via REST or listened via sock...
<javascript><python><sockets><socket.io><python-socketio>
2023-02-20 11:26:22
0
1,018
Honza
75,508,626
5,468,258
Pandas updating a subset of rows multiple times leads to an unexpected result
<p>I have one dataframe which requires multiple updates to one column using different subsets of rows per update. Each update corresponds to a set of rows which have a certain value for column A, where the B column should be given the values of the B column from another dataframe. A simple example is presented below, w...
<python><pandas><dataframe>
2023-02-20 11:21:55
1
346
René Steeman
75,508,503
667,726
Can we get the signature or arguments of a celery task on `task_prerun`
<p>My plan is to log all celery task requests with the arguments they receive s I'm using the following</p> <pre><code>@task_prerun.connect() def log_celery_args(task, **kwargs): logger.info(f&quot;{task.name} {kwargs['kwargs']}&quot;, extra=kwargs['kwargs']) </code></pre> <p>The problem is this solution doesn't wo...
<python><logging><celery><celery-task><python-logging>
2023-02-20 11:11:29
1
7,091
Dany Y
75,508,283
2,095,383
Dump NumPy Array to YAML as regular list
<p>When using PyYAML to save a NumPy array in a YAML file, it by default adds a whole lot of metadata such that it can restore the actual array when loading the file. Example:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import yaml a = np.array([1, 2, 3]) print(yaml.dump(a)) </code></pre> <...
<python><numpy><yaml><pyyaml>
2023-02-20 10:49:43
1
5,085
luator
75,508,055
11,024,270
Select Python interpreter for VSCode project with activation in .bashrc
<p>I have several conda Python environments. In Visual Studio Code, for a project, I select the Pyhton interpreter I want to use. If I close and reopen VSCode, the previously selected interpreter is automatically used. However, this does not work if I activate a conda Python environments in my .bashrc file (<code>mamba...
<python><visual-studio-code><conda><virtual-environment><mamba>
2023-02-20 10:27:12
0
432
TVG
75,508,050
8,618,242
How to ensure file has been written to disk before reading it
<p>I want to read a <code>plan.txt</code> file generated by the <a href="https://www.fast-downward.org/" rel="nofollow noreferrer">fast-downward</a> planner, to do so I'm using <code>subprocess</code> as follows:</p> <pre class="lang-py prettyprint-override"><code>import subprocess search_options = &quot;lama-first&qu...
<python><subprocess><read-write>
2023-02-20 10:27:06
1
4,115
Bilal
75,507,893
11,809,811
get hourly finance info with yahoo finance -> hourly numbers not available anymore?
<p>I am trying to get hourly stock data from yahoo finance, the code is simple:</p> <pre><code>import yfinance as yf from datetime import datetime, date tickerData = yf.Ticker('AAPL') today = tickerData.history(start = datetime.combine(date.today(), datetime.min.time()), period = '1h') print(today) </code></pre> <p>I ...
<python><yahoo-finance>
2023-02-20 10:11:43
0
830
Another_coder
75,507,530
9,827,719
Python Matplotlib Bar Chart set "top, right, bottom (x-axis), left (y-axis)" colors
<p>I have successfully created a bar chart using Python and Matplotlib. I have managed to give the bars a background color and the values a color. I have also managed to x and y tick labels color (category labels color).</p> <p>The next thing I want to do are the following four changes:</p> <ul> <li>Set color of the &q...
<python><matplotlib>
2023-02-20 09:37:49
0
1,400
Europa
75,507,449
16,933,406
using a varible in "urllib.request.urlopen" throws an error
<p>I want to get data from NCBI website using python3. When I use</p> <pre><code>fp = urllib.request.urlopen(&quot;https://www.ncbi.nlm.nih.gov/gene/?term=50964&quot;) mybytes = fp.read() mystr = mybytes.decode(&quot;utf8&quot;) fp.close() print(mystr) #### executes without any error </code></pre> <p>but when I pa...
<python><url><urllib><urllib3>
2023-02-20 09:29:54
2
617
shivam
75,507,292
1,668,622
How to correctly declare/use a TypeVar when a function needs to access a common member (get error: has no attribute...)?
<p>I'm trying to provide type hints for a function that returns an instance of a class provided as an argument and also <em>accesses</em> an element of this class. For example:</p> <pre class="lang-py prettyprint-override"><code>import re from dataclasses import dataclass from typing import ClassVar, Type, TypeVar @da...
<python><mypy><python-typing>
2023-02-20 09:15:33
0
9,958
frans
75,507,273
11,436,357
How to use multiple conditions in one locator?
<p>One of several buttons may appear on the page, I have to wait for the first one and perform the action, with Selenium I did it this way:</p> <pre class="lang-py prettyprint-override"><code>element = WebDriverWait(driver, 20).until( lambda driver: \ driver.find_element(By.NAME, &quot;Confirm&quot;) or \ ...
<python><playwright>
2023-02-20 09:13:22
1
976
kshnkvn
75,507,240
159,072
How can I load a local library in Brython?
<p><em><strong>plot.html</strong></em></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt; &lt;link href=&quot;https://fonts.googleapis.com/css2?family=Open+Sans...
<python><flask><brython>
2023-02-20 09:10:10
1
17,446
user366312
75,507,181
10,498,616
iGraph installation on Mac: cairo dependency
<p>I am using Mac. I installed igraph in Python with <code>pip install igraph</code> and it was working well, except for plotting the graphs.</p> <p>I searched online and I installed cairo with <code>brew install cairo</code>. Ever since, I am getting the following error anytime I simply import igraph:</p> <pre><code>O...
<python><igraph><cairo>
2023-02-20 09:03:41
0
305
Vitomir
75,507,176
1,952,636
How send result from db_pipe to exec_in_db?
<p>I have one DB connection and many сoroutines to request data. I make the minimal concept, and need help with correct understanding the way of realization.</p> <pre><code>import asyncio db_queeu = asyncio.Queue() async def db_pipe(): while True: data = await db_queeu.get() print(&quot;DB got&quo...
<python><python-asyncio>
2023-02-20 09:03:20
1
605
Gulaev Valentin
75,506,653
17,561,414
Compare two df column names and select columns in common
<p>Im trying to append the <code>dictionary_of_columns</code> with the columns that two df has in common.</p> <p>my Code:</p> <pre><code>list_of_columns = [] for column in dfUpdates.schema: list_of_columns.append(column.jsonValue()[&quot;name&quot;].upper()) dictionary_of_columns = {} dictionary_of_columns['BK_COL...
<python><dataframe><multiple-columns>
2023-02-20 08:02:58
1
735
Greencolor
75,506,603
221,270
How to combine two columns if one is empty
<p>I have a table:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>A</th> <th>B</th> <th>C</th> </tr> </thead> <tbody> <tr> <td>x</td> <td>1</td> <td>NA</td> </tr> <tr> <td>y</td> <td>NA</td> <td>4</td> </tr> <tr> <td>z</td> <td>2</td> <td>NA</td> </tr> <tr> <td>p</td> <td>NA</td> <td>5</td...
<python><pandas>
2023-02-20 07:56:37
4
2,520
honeymoon
75,506,574
7,104,332
Poetry install error while running it on github workflow
<p>Encountering an error message while installing dependencies using Poetry with GitHub Actions. It works fine when I install it locally. However, it gives out the runtime error of ['Key &quot;files&quot; does not exist.'] missing when Action runs on GitHub for the line [Install dependencies].</p> <p>Poetry Lock file U...
<python><django><github-actions><python-poetry>
2023-02-20 07:52:56
0
474
Rohit Sthapit
75,506,435
6,108,107
Boolean mask unexpected behavior when applying style
<p>I am processing data where values may be of the format '&lt;x' I want to return 'x/2'. So &lt;5 would be returned as '2.5'. I have columns of mixed numbers and text. The problem is that I want to style the values that have been changed. Dummy data and code:</p> <pre><code>dummy={'Location': {0: 'Perth', 1: 'Perth...
<python><pandas><numpy>
2023-02-20 07:36:58
1
578
flashliquid
75,506,319
14,862,885
How do I keep the imshow() window responsive even if frame processing takes several seconds?
<p>I want to implement <a href="https://github.com/MayankSingal/PyTorch-Image-Dehazing" rel="nofollow noreferrer">this</a> library with video dehazing ability. I have only CPU, but I expect the result will be good without GPU,because video output of DCP,or any other dehaze algorithm works good.</p> <p>So I developed th...
<python><opencv><user-interface>
2023-02-20 07:23:06
1
3,266
redoc
75,506,085
18,268,798
How to do DependsOn in aws-cdk-python
<p>I'm trying to create a documentDB along with db-instance. Both functions are in the same stack class, But when i try to run the code, the instance and db cluster start creating parallel and throws an error that cluster_name not found for instance creation.</p> <p>I want to know is there any method like dependsOn in ...
<python><devops><aws-cdk><aws-documentdb>
2023-02-20 06:53:39
2
333
Muhammad_Bilal
75,505,907
13,178,155
How to render HTML in PyQt5 window?
<p>I'm new to using PyQt5 to create GUIs and I think I need a hand.</p> <p>I'm trying to just create a simple window that renders a simple html file. However, when I use the code below the window renders, but the central widget/entire window is empty. Have I missed a step that allows the HTML to show?</p> <p>Using the ...
<python><html><pyqt5><qtwebengine><qwebengineview>
2023-02-20 06:28:16
2
417
Jaimee-lee Lincoln
75,505,892
11,693,768
Merge a dictionary of dataframes and create a new column called source to show where it came from, also merge duplicates
<p>I have the following dictionary of dataframe, the actual one is much bigger</p> <pre><code>data = { 'src1': pd.DataFrame({ 'x1': ['SNN', 'YH', 'CDD', 'ONT', 'ONT'], 'x2': ['AAGH', 'KSD', 'CHH', '002274', '301002'] }), 'src2': pd.DataFrame({ 'x1': ['HA', 'TRA', 'GHJ', 'AH', 'ONT'],...
<python><pandas><dataframe><dictionary>
2023-02-20 06:25:37
1
5,234
anarchy
75,505,537
3,198,568
Monkey patching class functions and properties with an existing instance in Jupyter
<p>When I'm prototyping a new project on Jupyter, I sometimes find that I want to add/delete methods to an instance. For example:</p> <pre><code>class A(object): def __init__(self): # some time-consuming function def keep_this_fxn(self): return 'hi' a = A() ## but now I want to make A -&gt; A_new...
<python>
2023-02-20 05:22:47
0
2,253
irene
75,505,511
1,769,197
Python: how do i find the next business day for different countries
<p>In python, I have a a set of dates for different countries. How do i find their next business date if the date given is a holiday for that country, given that different countries have different holiday calendars.</p> <p><a href="https://i.sstatic.net/TIAuc.png" rel="nofollow noreferrer"><img src="https://i.sstatic.n...
<python><time>
2023-02-20 05:18:22
1
2,253
user1769197
75,505,496
2,469,032
Compute weighted average for a list of variables in Pandas
<p>Given a data frame, I would like to write a function to calculate the weighted average by group for a given set of columns.</p> <p>For example, I have a data frame</p> <pre><code>mydf = pd.DataFrame({ 'group' : np.array(['A', 'B', 'C', 'D', 'E']*20), 'weight' : np.array(list(range(1,6))*20), 'x1' : np.random.uniform...
<python><pandas><aggregate><weighted-average>
2023-02-20 05:14:44
1
1,037
PingPong
75,505,217
7,458,826
Unable to run pytorch using gpu (Windows 10)
<p>I have a RTX 3070 on my computer, installed pytorch for gpu and all its dependencies using <code>conda</code>, and still when I try</p> <pre><code> import torch torch.cuda.is_available() </code></pre> <p>I always get <code>False</code>. How to solve it?</p> <p>Here is my <code>conda list</code></p> <pre><code>#...
<python><pytorch><anaconda>
2023-02-20 04:14:54
1
636
donut
75,505,163
17,779,615
What are the important information needed to know from /proc/PID/status file?
<p>I am new to linux. I would like to know what are the important information that I need to know when reading /proc/PID/status file?</p> <pre><code>Name: python Umask: 0002 State: t (tracing stop) Tgid: 6279 Ngid: 0 Pid: 6279 PPid: 5563 TracerPid: 1297870 Uid: 1000 1000 1000 1000 Gid: 1000...
<python><linux><freeze><strace>
2023-02-20 04:00:26
0
539
Susan
75,504,836
5,089,311
Tkinter very slow to initialize on Python 3.10.10
<p>I have 3 machines, all run Windows 10.</p> <ol> <li>First has PyPy 7.3.9 (Python 3.9.10)</li> <li>Second pure vanilla Python 3.9.1 downloaded from python.org and installed manually</li> <li>Third has Python 3.10.10 installed via <code>winget</code></li> </ol> <p>I mostly develop on 1st PC and everything was fine, un...
<python><tkinter>
2023-02-20 02:44:14
1
408
Noob
75,504,828
9,443,671
Iteratively filtering pandas rows based on different inputs?
<p>I'm trying to filter out a pandas data-frame based on some a variable list <code>task_ids</code> that exist in the df.</p> <p>for example if <code>task_ids = [1,5,7]</code> then I'd want the following functionality:</p> <pre><code>df[(df.task_id = 1) &amp; (df.task_id = 5) &amp; (df.task_id = 7)] </code></pre> <p>Ho...
<python><pandas><dataframe>
2023-02-20 02:43:17
1
687
skidjoe
75,504,771
20,898,396
How is Numba faster than NumPy for matrix multiplication with integers?
<p>I was comparing parallel matrix multiplication with numba and matrix multiplication with numpy when I noticed that numpy isn't as fast with integers (int32).</p> <pre><code>import numpy as np from numba import njit, prange @njit() def matrix_multiplication(A, B): m, n = A.shape _, p = B.shape C = np.zeros((m,...
<python><numpy>
2023-02-20 02:31:09
1
927
BPDev
75,504,662
654,019
Can I use pivotal table to create a heatmap table in pandas
<p>I have this data frame and the result dataframe:</p> <pre><code>df= pd.DataFrame( { &quot;I&quot;: [&quot;I1&quot;, &quot;I2&quot;, &quot;I3&quot;, &quot;I4&quot;, &quot;I5&quot;, &quot;I6&quot;, &quot;I7&quot;], &quot;A&quot;: [1, 1, 0, 0, 0, 0, 0], &quot;B&quot;: [0,...
<python><pandas><dataframe><pivot-table>
2023-02-20 02:06:48
1
18,400
mans
75,504,389
1,185,242
How do I find the smallest surrounding rectangle of a set of 2D points in Shapely?
<p>How do I find the msmallest surrounding rectangle (which is possibly rotated) of a set of 2D points in Shapely?</p>
<python><shapely>
2023-02-20 00:50:56
1
26,004
nickponline
75,504,188
9,749,124
How to read emails with Python and Gmail API
<p>I want to get unread emails from my inbox with python code. I set up google developer account, I made an app (I set it to DESKTOP) and I downloaded credentials.</p> <pre><code>{&quot;installed&quot;:{&quot;client_id&quot;:&quot;xxx&quot;, &quot;project_id&quot;:&quot;xxx&quot;, &quot;auth...
<python><gmail><gmail-api>
2023-02-19 23:47:41
1
3,923
taga
75,504,084
5,131,437
Select multiple indices in an axis of pytorch tensor
<p>My actual problem is in a higher dimension, but I am posting it in a smaller dimension to make it easy to visualize.</p> <p>I have a tensor of shape (2,3,4): <code>x = torch.randn(2, 3, 4)</code></p> <pre><code>tensor([[[-0.9118, 1.4676, -0.4684, -0.6343], [ 1.5649, 1.0218, -1.3703, 1.8961], [ 0...
<python><multidimensional-array><pytorch><tensor>
2023-02-19 23:22:36
1
594
psuresh
75,503,943
10,858,691
Removing rows with dates within 4 or less days of each other Pandas Dataframe
<p>I want to remove rows if Date is 4 or less days within consecutive row Data value. We want to keep the first row, and remove the other rows.</p> <p>So below, 2018-02-20 is within 4 days of 2018-02-16 so we keep 2-16 but remove 2-20. The tricky part is going to be we have to now adjust for the removal of 2-20 and no...
<python><pandas>
2023-02-19 22:50:40
1
614
MasayoMusic
75,503,925
5,904,928
How to extract incomplete Python objects from string
<p>I am attempting to extract valid Python-parsable objects, such as dictionaries and lists, from strings. For example, from the string <code>&quot;[{'a' : 1, 'b' : 2}]&quot;</code>, the script will extract <code>[{'a' : 1, 'b' : 2}]</code> since the <code>{}</code> and <code>[]</code> denote completed Python objects.<...
<python><regex><list><dictionary><parsing>
2023-02-19 22:47:25
1
12,755
Aaditya Ura
75,503,797
4,492,738
Python: Searching for date using regular expression
<p>I am searching for date information, in the format of 01-JAN-2023 in a extracted text, and the following regular expression didn't work. Can \b and \Y be used this way?</p> <pre><code>import re rext = 'This is the testing text with 01-Jan-2023' match = re.search(r&quot;\d\b\Y&quot;, rext) print(match) </code></pr...
<python><regex>
2023-02-19 22:15:22
2
883
TTZ
75,503,759
19,916,174
Time Complexity of this program solving the coin change problem
<p>I have created a program shown below, and I am confused as to how to figure out its time complexity. Is it O(n<sup>target/min(coins)</sup>) because a for loop is created each time the function is called, and the function is called <code>target/min(coins)</code> times?</p> <p>The program solves the coin change proble...
<python><loops><recursion><iteration><time-complexity>
2023-02-19 22:06:11
1
344
Jason Grace
75,503,580
12,860,924
Image classification Using CNN
<p>I am working on breast cancer classification. I found this online code to train my pre-processed outputs on it. The results was awful but I didn't understand the code, I want to train my own model but I don't how to replace my own code with this one.</p> <p>Any help would be appreciated.</p> <pre><code>in_model = tf...
<python><tensorflow><keras><conv-neural-network><image-classification>
2023-02-19 21:27:25
2
685
Eda
75,503,493
654,019
how to merge two data frame so I can get same columns and rows merged
<p>I have the following sample data frames and want to merge them to get the result. I tried outer join, but the result was not what I wanted.</p> <pre><code>df1 = pd.DataFrame( { &quot;I&quot;: [&quot;I1&quot;,&quot;I2&quot;, &quot;I3&quot;, &quot;I4&quot;], &quot;A&quot;: [&quot;A0&quot;, &quot;A1...
<python><pandas><dataframe>
2023-02-19 21:14:04
2
18,400
mans
75,503,179
5,318,986
Web scraping ignore "Next" or ">" when hidden (Selenium, Python)
<p>I am using Selenium for Python to scrape a site with multiple pages. To get to the next page, I use <code>driver.find_element(By.XPATH, xpath)</code>. However, The xpath text changes. So, instead, I want to use other attributes.</p> <p>I tried to find by class, using &quot;page-link&quot;: <code>driver.find_element(...
<python><selenium-webdriver><web-scraping>
2023-02-19 20:20:26
2
2,767
Martien Lubberink