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,041,623
7,505,256
How to check that a string is a string literal for mypy?
<p>With this code</p> <pre class="lang-py prettyprint-override"><code>import os from typing import Literal, get_args Markets = Literal[ &quot;BE&quot;, &quot;DE&quot;, &quot;DK&quot;, &quot;EE&quot;, &quot;ES&quot;, &quot;FI&quot;, &quot;FR&quot;, &quot;GB&quot;, &quot;IT&quot;, &quot;LT&quot;, &quot;LV&quot;, &qu...
<python><mypy><python-typing>
2023-01-07 15:44:59
2
316
Prokie
75,041,608
18,806,499
How to configure DB in a Flask app dynamicly?
<p>I'm working on app, where user have to enter database connection parametrs by hands</p> <p>So I've made an api here it is:</p> <pre><code>from flask_mysqldb import MySQL from flask import Flask, request import MySQLdb.cursors app = Flask(__name__) # /hello @app.route(&quot;/hello&quot;, methods=['GET']) def hello...
<python><mysql><flask>
2023-01-07 15:42:48
0
305
Diana
75,041,592
936,652
Oracle AdvancedQueuing: failing to broadcast (ORA-24033: no recipients for message, Python client)
<p>I am referring to the following project on GitHub: <a href="https://github.com/chris-ch/poc-oracle-aq/tree/v0.1" rel="nofollow noreferrer">poc-oracle-aq</a></p> <p>The code responsible for publishing messages is located in <em>scripts/publisher.py</em>:</p> <pre><code>def loop(connection, queue_high, queue_low, name...
<python><oracle19c><advanced-queuing>
2023-01-07 15:40:08
0
2,012
Christophe
75,041,364
13,994,829
Python-MultiProces in closure function
<p>The <strong>case1</strong> in <code>test.py</code> (as following code):</p> <p>I can get a expected result for variable &quot;<code>res</code>&quot;.</p> <p>(<code>res[-1]</code> is correct that i want)</p> <p><strong>test.py:</strong></p> <pre><code>from multiprocessing import Pool as ProcessPool skus = [i for i i...
<python><multiprocessing><closures><python-multiprocessing>
2023-01-07 15:06:09
1
545
Xiang
75,041,291
13,491,606
Seaborn manually set interval of x axis
<p>My data:</p> <pre class="lang-py prettyprint-override"><code>data = pd.DataFrame({'y': {0: 0.8285, 1: 0.869, 2: 0.8781, 3: 0.8806, 4: 0.8825, 5: 0.8831},'x': {0: 5764, 1: 22021, 2: 56906, 3: 114157, 4: 289474, 5: 4755584}}) </code></pre> <p>My current plot:</p> <pre class="lang-py prettyprint-override"><code>sns.set...
<python><matplotlib><seaborn>
2023-01-07 14:56:44
1
1,964
namespace-Pt
75,041,261
8,401,374
driver.switch_to.alert.text throws exepction: no such alerts but there is an alert
<p>I'm trying to open a <a href="https://drive.inditex.com/drfrcomr/login" rel="nofollow noreferrer">https://drive.inditex.com/drfrcomr/login</a> with Selenium.</p> <p>It opens a prompt with username and password fields, &amp; submit and cancel buttons. I am trying to close the prompt. It can be closed by clicking the ...
<python><selenium><selenium-webdriver><web-scraping><selenium-chromedriver>
2023-01-07 14:51:54
0
1,710
Shaida Muhammad
75,041,235
17,779,615
How to read specific n_rows and n_columns from parquet file?
<p>How can I read first row and specific columns 1,3,5 from the parquet file? Currently I use <code>pd.read_parquet(filename,columns=['first_col','third_col','fifth_col'])</code> to read only the columns that I want but I don't know how to read only first row while reading those specific column from parquet file.</p>
<python><parquet>
2023-01-07 14:48:38
1
539
Susan
75,041,218
5,370,631
Recognize date format and convert it
<p>Is there a way where to guess date format of a string and convert other dates to the same format as the given string (e.g. <code>YYYYMMDD</code>)?</p> <p>For example:</p> <pre class="lang-py prettyprint-override"><code># Recognize the format as YYYYMMDD date1 = '20221111' # Recognize the format as YYYY-MM-DD and co...
<python>
2023-01-07 14:46:28
3
1,572
Shibu
75,041,188
4,040,643
Exception in soundfile.py: io.UnsupportedOperation: seek
<p>I am currently going through this <a href="https://pytorch.org/tutorials/beginner/audio_preprocessing_tutorial.html" rel="nofollow noreferrer">jupiter notebook</a></p> <p>However when running this code block, I get the error below. Is there someone familiar with this problem and has an idea how to fix/resolve this? ...
<python><exception><audio>
2023-01-07 14:42:50
1
489
Imago
75,041,095
7,578,494
How to apply a custom function to xarray.DataArray.coarsen.reduce()?
<p>I have a (2x2) NumPy array:</p> <pre class="lang-py prettyprint-override"><code>ar = np.array([[2, 0],[3, 0]]) </code></pre> <p>and the same one in the form of xarray.DataArray:</p> <pre class="lang-py prettyprint-override"><code>da = xr.DataArray(ar, dims=['x', 'y'], coords=[[0, 1], [0, 1]]) </code></pre> <p>I am t...
<python><numpy><python-xarray>
2023-01-07 14:29:59
2
343
hlee
75,040,882
6,392,779
Split string with multiple possible delimiters to get substring
<p>I am trying to make a simple Discord bot to respond to some user input and having difficulty trying to parse the response for the info I need. I am trying to get their &quot;gamertag&quot;/username but the format is a little different sometimes.</p> <p>So, my idea was to make a list of delimiter words I am looking f...
<python>
2023-01-07 13:59:31
2
901
nick
75,040,793
17,779,615
How to erase memory while using watchdog in python
<p>I used watchdog to monitor file creating in a folder. Whenever a parquet file is created, watchdog will call python script to read the parquet file.</p> <p>When the watchdog program is first run, the memory usage is 90KB. After finished reading first parquet file, the memory usage is 100KB. I delete all the datafram...
<python><pandas><out-of-memory><watchdog>
2023-01-07 13:44:20
0
539
Susan
75,040,733
10,958,326
Is there a way to use StrEnum in earlier python versions?
<p>The enum package in python 3.11 has the StrEnum class. I consider it very convenient but cannot use it in python 3.10. What would be the easiest method to use this class anyway?</p>
<python><enums>
2023-01-07 13:35:37
3
390
algebruh
75,040,633
19,838,445
Why does function descriptor create new bound method each time
<p>Could you explain why new bound method is created each time when trying to access same method of the same class instance?</p> <pre class="lang-py prettyprint-override"><code>class MyClass: def my_method(self): print(f&quot;Called bounded to {self}&quot;) m_unbound = MyClass.my_method print(f&quot;{type...
<python><methods><class-method><python-descriptors><unbound>
2023-01-07 13:16:34
0
720
GopherM
75,040,613
13,910,839
Incorrect diagnostics in Nvim LSP (Python)
<p>I have installed lsp server for python and have def like this one:</p> <pre><code>def get_info_about_file(db: Session, name_of_file: str) -&gt; schema.File: return db.query(models.File).filter(models.File.name == name_of_file).first() </code></pre> <p>After that I got error:</p> <pre><code>Diagnostics: 1. Expres...
<python><neovim><liskov-substitution-principle>
2023-01-07 13:13:02
1
692
0xActor
75,040,459
1,362,055
Type conversion during function call in python
<p>In the example below I'm passing float value to a function accepting and int argument (using type hints). Looks like the value read into the function arg is a float nonetheless (was expecting int(11.2) * 10 = 110 instead of 112)</p> <p>Why is this the case?</p> <pre><code>def f(n:int): return n*10 l = [11.2, 2.2...
<python><function><parameter-passing>
2023-01-07 12:47:50
1
817
Nikhil
75,040,437
1,792,344
More Iterations Of Gauss-Seidel With Scipy Infinite Norm
<p>I have a python code to solve linear systems with Gauss-Seidel Method, using Numpy and Scipy. I'm implementing the code and an example from the book: <strong>'Numerical Analysis: Burden and Faires'</strong>. <em><strong>The problem is I obtain the exact solution but with more iterations: 10 iterations with 0.0000001...
<python><numpy><scipy>
2023-01-07 12:44:10
1
759
Tobal
75,040,352
16,142,496
I have this Dataframe, Using Transform Function how can I assign them index values as new row?
<p><a href="https://i.sstatic.net/fdIX6.png" rel="nofollow noreferrer">This is the Dataset, I want to add a column named Index which will start number for every person from 1</a></p> <p>This provides count, but I want to provide Index values for eg: 1,2,3 for one person, and new person comes again 1,2,3,4 etc.</p> <pre...
<python><pandas><dataframe><transform><analytics>
2023-01-07 12:33:00
2
351
Manas Jadhav
75,040,330
383,793
How can I define a TypeAlias for a nested Generic in Python?
<p>I currently have this code</p> <pre><code>T = TypeVar(&quot;T&quot;) Grid = Sequence[Sequence[T]] def columns(grid: Grid) -&gt; Iterable[list[T]]: return ([row[i] for row in grid] for i in range(len(grid[0]))) </code></pre> <p>But I think the <code>T</code> in the alias <code>Grid</code> is bound to a different...
<python><generics><python-typing><nested-generics>
2023-01-07 12:30:03
1
6,396
Chris Wesseling
75,040,164
18,948,596
Check if numpy's array_like is an empty array
<p>Suppose <code>a</code> is an <code>array_like</code> and we want to check if it is empty. Two possible ways to accomplish this are:</p> <pre class="lang-py prettyprint-override"><code>if not a: pass if numpy.array(a).size == 0: pass </code></pre> <p>The first solution would also evaluate to <code>True</code> ...
<python><arrays><numpy>
2023-01-07 12:02:51
1
413
Racid
75,040,072
1,636,973
linux: how to wait for a process and file at the same time?
<p>I am trying to build an event loop in python, mostly for educational purposes. I am not interested in solutions involving asyncio or similar because my goal is really to learn about the low-level linux APIs.</p> <p>For file-like objects (pipes, sockets, …) there are the select/poll/epoll system calls. In python, the...
<python><linux><asynchronous><select>
2023-01-07 11:47:49
1
2,494
tobib
75,040,059
8,849,755
Python print single byte as char
<p>I have a long array of bytes and I need to carefully inspect the values at each position. So I want to print it in two columns with byte number and byte value. How can this be done?</p> <p>Example:</p> <pre><code>bytes = b'hola\x00chau' print(bytes) for i,byte in enumerate(bytes): print(i,byte) </code></pre> <p...
<python><arrays><byte>
2023-01-07 11:45:56
2
3,245
user171780
75,040,048
859,141
Django. Access list index in child for loop
<p>How can I change the accessed index of an inner for loop list based on a counter from the outer loop? In normal python I would do something like</p> <pre><code>parent_list = ['One','Two','Three'] child_list = ['A','B','C'] for idx, item in enumerate(parent_list): for child_item in child_list[idx]: print...
<python><django><django-views><django-templates>
2023-01-07 11:44:40
2
1,184
Byte Insight
75,039,860
13,950,870
How to concat column Y to column X and replicate values Z in pandas dataframe?
<p>I have a pandas DataFrame with three columns:</p> <pre><code> X Y Z 0 1 4 True 1 2 5 True 2 3 6 False </code></pre> <p>How do I make it so that I have two columns <code>X</code> and <code>Z</code> with values:</p> <pre><code> X Z 0 1 True 1 2 True 2 3 False 3...
<python><pandas>
2023-01-07 11:12:45
4
672
RogerKint
75,039,721
3,287,355
Matplotlib add labels to individual stacks in a stacked chart for imbalanced dataset
<p>I am trying to plot a graph based on a huge imbalanced dataset using matplotlib and it looks something like</p> <p><a href="https://i.sstatic.net/9Gcad.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/9Gcad.png" alt="enter image description here" /></a></p> <p>I want to represent % values on each bar, ...
<python><matplotlib><plot><stacked-chart>
2023-01-07 10:51:15
0
1,346
moonwalker7
75,039,674
1,439,912
Python type hinting for generic container constructor
<p>What is the correct typing to use for the below marked in ???, where we cast a generic iterable data container type to an iterable container of different type?</p> <pre><code>def foo(itr:Iterable, cast_type:???) -&gt; ???: (For Py 3) # type: (Iterable[Any], ???) -&gt; ??? (For Py 2.7) return cast_type(it...
<python><python-typing>
2023-01-07 10:42:32
2
480
Pontus Hultkrantz
75,039,612
7,437,143
Typing: NameError: name 'function' is not defined
<p>While trying to specify the return type of a function that returns a list of functions, I am experiencing some difficulties. The typechecker retrurns:</p> <pre><code>Traceback (most recent call last): File &quot;/home/name/anaconda/envs/snncompare/lib/python3.10/runpy.py&quot;, line 196, in _run_module_as_main ...
<python><function><typing>
2023-01-07 10:31:37
1
2,887
a.t.
75,039,533
19,003,861
Cannot render model fields in forloop with annotate() and values() (Django)
<p>I am using <code>.values()</code> and <code>.annotate()</code>to sum up 2 models fields based on matching criteria.</p> <p>I wrapped this in a <code>forloop</code> in my template to iterate.</p> <p>Problem: I cannot call the model fields anymore. The forloop returns the venue_id instead of the name and the usual app...
<python><django><django-views><django-templates>
2023-01-07 10:17:06
1
415
PhilM
75,039,459
15,352,143
For categorical class RuntimeError: 0D or 1D target tensor expected, multi-target not supported
<p>I have 28 features and target variable is categorical (0-8) i.e. 9 target variable .</p> <p>Data sample:</p> <pre><code>X_train.shape,y_train.shape output --((640, 28), (640, 1)) X_train[0] output --array([0.4546875 , 0.63958333, 0.46875 , 0.62916667, 0.4859375 , 0.62916667, 0.5015625 , 0.64166667, 0.48593...
<python><deep-learning><pytorch><neural-network>
2023-01-07 10:03:18
1
313
k_p
75,039,222
11,082,866
Dynamic annotion in django queryset
<p>I have a Django queryset being created for a graph like the following:</p> <pre><code>obj = Allotment.objects .all() .values('dispatch_date') .annotate(transaction_no=Count('transaction_no')) .values('dispatch_date', 'transaction_no') </code></pre> <p>Now I am trying to pass all these values dynamica...
<python><django><django-rest-framework>
2023-01-07 09:16:34
1
2,506
Rahul Sharma
75,039,156
3,088,891
How can I rotate axis labels in a faceted seaborn.objects plot?
<p>I am working with the excellent <code>seaborn.objects</code> module in the most recent version of <strong>seaborn</strong>.</p> <p>I would like to produce a plot:</p> <ul> <li>With rotated x-axis labels</li> <li>With facets</li> </ul> <p>Rotating x-axis labels is not directly supported within <code>seaborn.objects</...
<python><matplotlib><seaborn><seaborn-objects>
2023-01-07 09:04:32
1
1,253
NickCHK
75,039,071
7,959,614
Turn table-element into Pandas DataFrame
<p>I would like to turn a table into a <code>pandas.DataFrame</code>.</p> <pre><code>URL = 'https://ladieseuropeantour.com/reports-page/?tourn=1202&amp;tclass=rnk&amp;report=tmscores~season=2015~params=P*4ESC04~#/profile' </code></pre> <p>The element in question is</p> <pre><code>from selenium import webdriver from sel...
<python><pandas><selenium>
2023-01-07 08:44:55
1
406
HJA24
75,038,677
8,049,220
Plotly Scatter3D plot with consistent gradient
<p>I'm trying to visualize temperature curves from different source in a 3D scatter plot. I have set <code>colorscale='Turbo'</code> so that hotter region will be read and colder region will be blue. But I cannot plot multiple scatter line with consistent color gradient. I understand the problem is occurring because I'...
<python><plot><plotly><scatter-plot>
2023-01-07 07:12:10
0
643
carl
75,038,622
2,773,461
Understanding Open Telemetry Integration to google cloud pub sub in python
<p>I am curious about how distributed tracing can be provided to a message from a publisher and how this is received in the subscriber part just to get the possibility to get track about what could be happening when things go wrong in the point the message is sent (publisher) and the message is received (subscriber). T...
<python><publish-subscribe><google-cloud-pubsub><open-telemetry>
2023-01-07 06:58:50
1
3,263
bgarcial
75,038,573
2,147,347
Modifying Pytorch Pretrained Model's Parameter in `forward()` Makes Training Slowing
<p>I have two parameters, A and B, that I need to put to replace all the weight of the pre-trained model. So I want to utilize the forward calculation of the pre-trained model but not the weight.</p> <p>I want to modify the weight of the model W = A + B, where A is a fixed tensor (not trainable), but B is a trainable p...
<python><pytorch>
2023-01-07 06:44:09
2
3,321
malioboro
75,038,239
15,893,581
can't install scikit-learn in python 3.10 for Windows 10?
<p>it's all about <strong>meson-python</strong>:</p> <blockquote> <p>Run-time dependency openblas found: NO</p> </blockquote> <blockquote> <p>....\scipy\meson.build:134:0: <strong>ERROR</strong>: Dependency &quot;OpenBLAS&quot; not found</p> <p>AttributeError: module 'mesonpy' has no attribute 'prepare_metadata_for_bui...
<python>
2023-01-07 05:08:53
2
645
JeeyCi
75,037,969
11,575,257
Vectorize Creating logical replacement along color channel
<p>I have an image with a subject and a mostly white background. I am trying to create an alpha mask around the subject. Due to image compression artifacts, the white background is not entirely made up of (255,255,255) values for rgb values. I am trying to convert values such as (252,253,252) to (255,255,255).</p> <p>M...
<python><numpy><alpha-transparency>
2023-01-07 03:41:23
2
1,055
theastronomist
75,037,933
103,252
Python/SqlAlchemy joining table to itself not generating expected query
<p>What I want to do seems like it should be straightforward. I want to join a table representing data collection stations to itself, in order to track previous iterations of stations deployed in the same location.</p> <p>In the code below, I have two classes: StationTable and StationTypeTable. The StationTable has t...
<python><sqlalchemy>
2023-01-07 03:28:35
1
1,932
Watusimoto
75,037,894
151,954
In python, how do you search for a tag value pair in a JSON file
<p>Im dealing with a large json file that has many boolean values, so I cant just search on the value alone. How can I extract the entire user information if one value is true?</p> <p>For example the json file has many lines that could read something like this:</p> <pre><code>[ 12, { &quot;name&quot;: ...
<python><json>
2023-01-07 03:19:03
2
2,780
Leroy Jenkins
75,037,853
12,060,596
Does Tweepy offer proxy support for Twitter API v2?
<p>I've looked through the <a href="https://docs.tweepy.org/en/stable/index.html" rel="nofollow noreferrer">documentation</a> but only found documentation indicating that Tweepy supports proxied requests through the v1 API. I have an essential developer account so I am limited to using the v2 API. As a workaround, I wr...
<python><twitter><python-requests><tweepy><twitter-api-v2>
2023-01-07 03:07:44
2
318
OTM
75,037,777
13,136,438
Google colab blocking requests.get, causing 403 error
<p>I'm trying to scrape web reviews from the appstore through rss and when I run my code on a local environment, it runs just fine and it gets all the requests 200 without issue. but if i run my code in google colab, it eventually fails after a while and google seems to block it, giving a 403 error.</p> <p>i've tried a...
<python><python-requests><google-colaboratory>
2023-01-07 02:46:51
1
378
Aeiddius
75,037,616
115,102
Convert ctypes object to numpy array
<p>I’m trying to write a ctypes structure so that it can be easily converted into a numpy array and used for assignments. Here is a simple example that shows the issue:</p> <pre><code>from ctypes import Structure, c_double import numpy as np class Vec3d: x = 1 y = 2 z = 3 def __array__(self, dtype): ...
<python><numpy>
2023-01-07 01:53:17
2
6,523
hanno
75,037,544
12,350,966
*** pyarrow.lib.ArrowInvalid: CSV parse error: Empty CSV file or block: cannot infer number of columns
<p>Trying the new pyarrow, this gives error:</p> <pre><code>data= pd.read_csv(path,sep='\t',engine=&quot;pyarrow&quot;) *** pyarrow.lib.ArrowInvalid: CSV parse error: Empty CSV file or block: cannot infer number of columns </code></pre> <p>But this works:</p> <pre><code>data= pd.read_csv(path,sep='\t') </code></pre>
<python><pandas><pyarrow>
2023-01-07 01:37:43
0
740
curious
75,037,364
954,835
Unable to access notion comments via API/python
<p>I'm trying to read the comments on a database entry in notion but I can't figure out how I need to make the request.</p> <pre><code>import requests _url = 'https://api.notion.com/v1/comments' _headers = {&quot;Authorization&quot;: _auth, &quot;Notion-Version&quot;: &quot;2021-08-16&quot;} _data = {'bloc...
<python><notion-api><notion>
2023-01-07 00:47:27
1
712
ninhenzo64
75,037,336
7,826,852
Changing value of a value in a dictionary within a list within a dictionary
<p>I have a json like:</p> <pre><code>pd = { &quot;RP&quot;: [ { &quot;Name&quot;: &quot;PD&quot;, &quot;Value&quot;: &quot;qwe&quot; }, { &quot;Name&quot;: &quot;qwe&quot;, &quot;Value&quot;: &quot;change&quot; } ], &quot;RFN&quot;: [ ...
<python>
2023-01-07 00:41:32
1
927
qwerty
75,037,330
4,348,534
requests.get() not completing with Tiktok user profile
<p>So, basically, it seems that <code>requests.get(url)</code> can't complete with Tiktok user profiles url:</p> <pre><code>import requests url = &quot;http://tiktok.com/@malopedia&quot; rep = requests.get(url) #&lt;= will never complete </code></pre> <p>As I don't get any error message, I have no idea what's going on....
<python><python-requests>
2023-01-07 00:40:13
1
4,297
François M.
75,037,252
11,614,319
socket.gaierror: [Errno 11001] getaddrinfo failed when sending gmail email via Python
<p>I'm on Windows and using Python 3.9.10 and I have trouble sending an email via google smtp.</p> <p>My code is :</p> <pre class="lang-py prettyprint-override"><code>import smtplib from email.mime.text import MIMEText def send_email(host, port, subject, msg, sender, recipients, password): msg = MIMEText(msg) ...
<python><smtp><gmail>
2023-01-07 00:20:53
1
362
gee3107
75,037,137
7,714,681
Is it possible to set generic legend next to four subplots matplotlib?
<p>I have the following code:</p> <pre><code>x1 = np.linspace(0, 5, 10) y1 = x1 + np.random.randn(10) y2 = x1 + np.random.randn(10) x2 = np.linspace(0, 5, 10) y3 = x2 + np.random.randn(10) y4 = x2 + np.random.randn(10) x3 = np.linspace(0, 5, 10) y5 = x3 + np.random.randn(10) y6 = x3 + np.random.randn(10) x4 = np.lin...
<python><matplotlib><legend><subplot>
2023-01-06 23:54:09
0
1,752
Emil
75,037,007
14,593,213
"ImportError: DLL load failed while importing cv2" but "Requirement already satisfied"
<p>I'm getting this error while trying to import the cv2 module on a anaconda virtual enviroment:</p> <pre><code>Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; File &quot;C:\anaconda3\envs\venv-1\lib\site-packages\cv2\__init__.py&quot;, line 181, in &lt;module&gt; b...
<python><opencv><anaconda>
2023-01-06 23:26:09
1
355
Davi A. Sampaio
75,036,877
8,971,218
Assign a value to a Pandas DataFrame column, based on multiple conditions, fastest ways?
<p>I am aware there are some other similar questions but I haven't found a <code>timeit</code> test with a fairly large dataset. I have a ~1.6M rows DF , and I want to use the fastest way to assign a column ['stag'] a 0-1 value depending on the index weekday and hour.</p> <p>Is there a faster approach I am missing ? su...
<python><pandas><timeit>
2023-01-06 23:00:56
0
955
Lorenzo Bassetti
75,036,861
8,795,358
How can I extract value of variable from script element in Scrapy
<p>I need to extract some data from a website, I found that all I need is exist in <code>&lt;script&gt;</code> element, So I extracted them with this command:</p> <pre><code>script = response.css('[id=&quot;server-side-container&quot;] script::text').get() </code></pre> <p>And this is the value of <code>script</code>:<...
<python><regex><web-scraping><xpath><scrapy>
2023-01-06 22:59:08
1
359
Tanhaeirad
75,036,841
4,437,631
unittest directory structure - cannot import src code
<p>I have the following folder structure in my project:</p> <pre><code>my-project src/ __init__.py script.py test/ __init__.py test_script.py </code></pre> <p>Ideally I want to have a separate folder where all the unit tests go. My <code>test_script.py</code> looks something like this:...
<python><python-3.x><python-unittest>
2023-01-06 22:55:58
1
714
ellen
75,036,613
9,352,077
Automatically use subclass type in method signature
<p>I have a parent class with many subclasses in Python 3. Currently, the hierarchy looks something like this:</p> <pre class="lang-py prettyprint-override"><code>class Parent: @classmethod def check(cls, obj: &quot;Parent&quot;): pass class Child1(Parent): def __init__(self, x): self.x...
<python><oop><casting><signature><type-safety>
2023-01-06 22:23:51
1
415
Mew
75,036,423
14,141,126
DataFrame returns Value Error after adding auto index
<p>This script needs to query the DC server for events. Since this is done live, each time the server is queried, it returns query results of varying lengths. The log file is long and messy, as most logs are. I need to filter only the event names and their codes and then create a DataFrame. Additionally, I need to add ...
<python><pandas>
2023-01-06 21:55:15
1
959
Robin Sage
75,036,412
4,714,742
No version is set for command pg_config
<p>I am attempting to install psycopg2 for use within a project. I am also using asdf in order to manage my python versions. I have tried doing this inside of a venv but I get the same error so to keep things simple let's just say I want to install it outside of a venv.</p> <pre><code>❯ cat .tool-versions nodejs 15.9.0...
<python><postgresql><homebrew><psycopg2><asdf>
2023-01-06 21:53:37
1
1,704
Jon McClung
75,036,296
3,654,588
Poetry/Meson: How to use meson as a build backend with Cython files to install a Python/Cython package
<p>I have a Python package that contains Cython code, similar to scikit-learn. I am trying to use poetry to do package management, but meson to handle the build process for Cython and possible c++ code. Before, when I was using the deprecated setuptools and distutils, I was able to do the following in scikit-learn:</p>...
<python><cython><python-poetry><meson-build>
2023-01-06 21:37:55
0
1,302
ajl123
75,036,272
8,749,168
Why are different objects created when using globals in a file vs importing them?
<p>Below is a simple code example that may help to explain my question.</p> <p><strong>file_1.py</strong></p> <pre><code>from functools import lru_cache from file_2 import add_stuff, add_stats @lru_cache() def add(x, y): return x + y if __name__ == &quot;__main__&quot;: add(1, 2) add(1, 2) add(3, 4...
<python>
2023-01-06 21:34:51
1
1,088
pythonweb
75,036,229
4,586,180
does pydev support python 3.5 Type Hints?
<p>I use eclipse/pydev.</p> <p>I recently learned about python 3.5 support for type hints <a href="https://medium.com/techtofreedom/8-levels-of-using-type-hints-in-python-a6717e28f8fd" rel="nofollow noreferrer">https://medium.com/techtofreedom/8-levels-of-using-type-hints-in-python-a6717e28f8fd</a></p> <p>I found <a hr...
<python><eclipse><pydev>
2023-01-06 21:28:52
1
968
AEDWIP
75,036,210
7,194,464
How to list all parquet files in s3 bucket folder via OPENROWSET (SQL Server)?
<p>I have a bucket (AWS) in a folder with 3 PARQUET files that are the same and have different names:</p> <p><img src="https://i.sstatic.net/8MFw4.png" alt="enter image description here" /></p> <p>I'm trying to create an EXTERNAL TABLE with the code below:</p> <pre><code>CREATE EXTERNAL TABLE tb_Test ( coluna_1 INT, co...
<python><sql-server><amazon-web-services><openrowset>
2023-01-06 21:26:33
2
405
Clayton A. Santos
75,036,001
2,876,994
Error: Got unexpected extra arguments when using Click library
<p>I'm trying to use the Click library in Python to create a command line interface, but I keep getting the following error when I try to run my script:</p> <pre><code>Error: Got unexpected extra arguments (hello hello1) </code></pre> <p>Here is my code:</p> <pre><code>import click @click.group(name='script') def cli(...
<python><command-line-interface><python-click>
2023-01-06 20:54:49
1
1,552
Shinomoto Asakura
75,035,999
2,186,567
Scrapy to parse multiple URLs into a single json
<p>Currently using scrapy with multiple URLs on the start_urls parameter which I load like this:</p> <pre><code> with open('urllist.txt') as f: start_urls = f.read().splitlines() </code></pre> <p>Then, I parse it the page with this code:</p> <pre><code> def parse(self, response): yield { '...
<python><json><scrapy>
2023-01-06 20:54:32
0
8,178
douglaslps
75,035,806
8,260,088
re.findall() function python
<p>Can you please help me to understand the following line of the code:</p> <pre><code>import re a= re.findall('[А-Яа-я-\s]+', string) </code></pre> <p>I am a bit confused with the pattern that has to be found in the string. Particularly, a string should start with <code>A</code> and end with any string in-between <co...
<python><python-re>
2023-01-06 20:30:13
1
875
Alberto Alvarez
75,035,589
2,026,010
Panda rename rows after grouping by columns
<p>I've recently started to play around with Pandas in order to manipulate some data and I am now trying to anonymize a few columns after a <code>groupBy</code> to find unique occurrences for persons.</p> <p>For example, suppose the following DF:</p> <pre><code> First Name Last Name DOB 0 Bob One ...
<python><pandas><group-by>
2023-01-06 20:02:09
2
3,947
Felipe Mosso
75,035,567
12,126,272
How can I read and filter many parquet files with different column names without spending many hours
<p>I have a lot of files on parquet, i need jut jo take 3 columns of this files. Some times one of this columns can have different names. I have this code but, this is spending more than 3 hours to run. This is not good. i'm using pyspark.</p> <pre><code>df_list = [] # I iterate all paths from a df which contains all f...
<python><for-loop><pyspark><parquet>
2023-01-06 19:59:11
1
467
Gizelly
75,035,337
7,209,497
How to ensure that .nonzero() returns one element tensor?
<p>[Edited to include the original source code]</p> <p>I try to run the code that I found here:<a href="https://colab.research.google.com/drive/1roZqqhsdpCXZr8kgV_Bx_ABVBPgea3lX?usp=sharing" rel="nofollow noreferrer">https://colab.research.google.com/drive/1roZqqhsdpCXZr8kgV_Bx_ABVBPgea3lX?usp=sharing</a> (linked from:...
<python><torch><stable-diffusion>
2023-01-06 19:28:44
1
314
Jan
75,035,171
5,495,385
Vectorizing a function for finding local minima and maxima in a 2D array with strict comparison
<p>I'm trying to improve the performance of a function that returns the local minima and maxima of an input 2D NumPy array. The function works as expected, but it is too slow for my use case. I'm wondering if it's possible to create a vectorized version of this function to improve its performance.</p> <p>Here is the fo...
<python><numpy><image-processing><vectorization><mathematical-morphology>
2023-01-06 19:07:06
1
997
Oliver
75,035,056
1,700,890
Microsecond do not work in Python logger format
<p>For some reason my Python logger does not want to recognize microseconds format.</p> <pre><code>import logging, io stream = io.StringIO() logger = logging.getLogger(&quot;TestLogger&quot;) logger.setLevel(logging.INFO) logger.propagate = False log_handler = logging.StreamHandler(stream) log_format = logging.Formatt...
<python><logging><time><format><python-logging>
2023-01-06 18:53:59
2
7,802
user1700890
75,035,018
1,818,713
Proper syntax for a pydeck PathLayer from a shapely geometry
<p>I see <a href="https://deckgl.readthedocs.io/en/latest/gallery/path_layer.html?highlight=pathlayer" rel="nofollow noreferrer">the example</a> of a PathLayer and it shows the input data is a list of lists within a regular pandas df, as opposed to a geopandas df.</p> <p>Let's say I'm coming from a GeoPandas df (let's ...
<python><deck.gl><pydeck>
2023-01-06 18:49:50
1
19,938
Dean MacGregor
75,034,877
2,425,753
Download AWS CloudWatch logs for a period
<p>I want to download all CloudWatch logs from AWS for:</p> <ul> <li>a spectific log group</li> <li>a specific time range</li> </ul> <p>My plan is fairly simple:</p> <ol> <li>Iterate over all logstreams for log group.</li> <li>For each log stream iterate over events and build a list of all log events.</li> </ol> <pre c...
<python><amazon-web-services><loops><amazon-cloudwatch><amazon-cloudwatchlogs>
2023-01-06 18:34:38
3
1,636
rfg
75,034,770
4,343,563
Create column of unique randomly generated letters to pandas dataframe?
<p>I have a dataframe where there is one column of random letters and numbers, then a column of how many random letters/numbers need to be added to random string in the first column. Like so but my dataframe is 3+ million rows:</p> <pre><code> id missing XK39J 4 NI94N 4 9IN3 5 MN83D 4 IUN2...
<python><pandas><list><sequence>
2023-01-06 18:23:12
1
700
mjoy
75,034,758
5,205,393
Delete all keys in Python dictionary greater than x in constant time
<p>If you have a dictionary:</p> <pre><code>d = {1: True, 2: False, 3: False, 4: True, 5: False, 6: True, 7: False, 8: False} </code></pre> <p>and you want all keys greater than 3 to be deleted so the dictionary becomes:</p> <pre><code>{1: True, 2: False, 3: False} </code></pre> <p>can you do this in constant time if t...
<python><algorithm><dictionary>
2023-01-06 18:22:08
2
301
Andrew
75,034,746
5,270,376
PIL image save causes FFMPEG to fail
<p>I have been attempting to convert some videos using FFMPEG with image2pipe using PIL. I have found that when the frame is particularly simple (such as all one colour), it causes FFMPEG to fail with the following message:</p> <pre><code>[image2pipe @ 000001785b599bc0] Could not find codec parameters for stream 0 (Vid...
<python><ffmpeg><python-imaging-library>
2023-01-06 18:20:45
0
520
Xorgon
75,034,658
9,742,558
Install Python3.8 on Ubuntu 22 server and got an error
<p>I have a Ubuntu 22.04 server and I need to install Python3.8 on it.</p> <p>Here is what I did:</p> <pre><code>sudo apt update sudo apt upgrade sudo apt install python3.8 -y </code></pre> <p>The last command gave me this error:</p> <pre><code>Reading package lists... Done Building dependency tree... Done Reading stat...
<python><linux><ubuntu>
2023-01-06 18:12:48
0
557
Philip Shangguan
75,034,644
5,437,090
if else statement for input arguments of a function in python
<p>I run my bash script <code>my_file.sh</code> in a python file as follows:</p> <pre><code>import subprocess def rest_api(): params = { 'query': 'indepedence day', 'formats': '[&quot;NEWSPAPER&quot;]', } subprocess.call(['bash', 'my_file.sh', f'...
<python><function><arguments><parameter-passing>
2023-01-06 18:11:30
2
1,621
farid
75,034,628
19,321,677
How to replace values by users correctly based on reference value?
<p>I have a dataframe where for each user I have always 2 pairs by goods_type and business KPI for EACH USER such as:</p> <pre><code>user | amount | goods_type | business 1 | $10 | used | cost 1 | $30 | used | revenue 1 | $15 | new | cost 1 | $50 | new | reven...
<python><pandas>
2023-01-06 18:09:10
1
365
titutubs
75,034,593
1,700,890
Cannot log to stream in Python
<p>I want to log to stream of io.StringIO, but end up with empty stream. Here is my code:</p> <pre><code>import logging, io log_handler = logging.StreamHandler(stream) log_format = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') log_handler.setFormatter(log_format) log_handler.setLevel(loggin...
<python><string><logging>
2023-01-06 18:06:48
1
7,802
user1700890
75,034,589
2,442,879
Variable in dictionary
<p>I want to replace <code>CHANGE</code> with the variable <code>zone_list</code>.</p> <pre class="lang-py prettyprint-override"><code>output_zones = {'CHANGE' : {}} </code></pre> <p>I would like to get:</p> <pre class="lang-py prettyprint-override"><code>{'zone_name': {... a set of dictionaries...}} </code></pre> <p>W...
<python>
2023-01-06 18:06:27
1
615
Rostyslav Malenko
75,034,523
1,473,517
How to average across two dataframes
<p>I have two dataframes:</p> <pre><code>{'id': {4: 1548638, 6: 1953603, 7: 1956216, 8: 1962245, 9: 1981386, 10: 1981773, 11: 2004787, 13: 2017418, 14: 2020989, 15: 2045043}, 'total': {4: 17, 6: 38, 7: 59, 8: 40, 9: 40, 10: 40, 11: 80, 13: 44, 14: 51, 15: 46}} {'id': {4: 1548638, 6: 1953603, 7: 1956216, 8: 1962245, 9: ...
<python><pandas>
2023-01-06 18:00:42
2
21,513
Simd
75,034,449
1,877,527
Aggregating multiple columns into one in Pandas quickly
<p>I have a DataFrame that is, ultimately, object IDs attached to individual X and Y coordinates, something like</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>X</th> <th>Y</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>0</td> <td>0</td> </tr> <tr> <td>1</td> <td>1</td> <td>3<...
<python><pandas><shapely>
2023-01-06 17:53:35
1
732
Philip Kahn
75,034,252
8,849,071
How to handle inheritance in mypy?
<p>I'm trying to add mypy to my Python project but I have found a roadblock. Let's say I have the following inheritance:</p> <pre class="lang-py prettyprint-override"><code>class BaseClass: base_attribute: str class A(BaseClass): attribute_for_class_A: str class B(BaseClass): attribute_for_class_B: str ...
<python><inheritance><mypy>
2023-01-06 17:33:39
1
2,163
Antonio Gamiz Delgado
75,034,239
9,820,773
Python boto3 how to parse role_arn from AWS_CONFIG_FILE?
<p>I have an AWS config file that my boto3 session has access to, via the AWS_CONFIG_FILE environment variable. The config file looks like this: (multi-account environment)</p> <pre><code>[profile profile1] credential_source Environment region=us-east-whatever role_arn=arn:aws:iam:&lt;ACCOUNT NUMBER 1&gt;:role/all-prof...
<python><amazon-web-services><boto3>
2023-01-06 17:32:07
2
323
Robert Campbell
75,033,658
11,925,464
count unique combination in one column using Groupby
<p>i have a dataframe which i'm trying to create new columns showing the occurrence of different combinations within different groups. Solutions I've found are all combinations of values across 2 or more columns instead of one. Therefore, is hoping somebody can help.</p> <p>sample df:</p> <pre> ╔════╦═════╗ ║ id ║ tag ...
<python><pandas><group-by>
2023-01-06 16:37:06
2
597
ManOnTheMoon
75,033,602
1,189,620
QSqlDatabase insert array of float using QSqlTableModel
<p>I am trying to insert an array into sql3 and retrieve it by first converting them into a BLOB, but its not inserting anything into the DB, code Below of a widget with QTableView using a pyqt model pattern</p> <pre><code>from PyQt6.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QLineEdit, QTableView, QMessageBox...
<python><python-3.x><pyqt6>
2023-01-06 16:32:57
1
3,636
ramon22
75,033,545
11,980,301
How to open a json.gz.part file using Python?
<p>I have lots of json.gz files in a directory and some them are json.gz.part. Supposedly, when saving them, some of the files were too large and they were splitted.</p> <p>I tried to open them as normally using:</p> <pre><code>with gzip.open(file, 'r') as fin: json_bytes = fin.read() json_str = json_byte...
<python><json><gzip>
2023-01-06 16:26:52
1
403
Marlon Teixeira
75,033,467
2,977,164
Solutions to 'make_dirs' problem in labelbox_json2yolo.py code
<p>I'd like to convert my label file in *json to YOLO * txt with to class ('bsb','wsb') using the <code>labelbox_json2yolo.py</code> (<a href="https://github.com/ultralytics/JSON2YOLO/blob/master/labelbox_json2yolo.py" rel="nofollow noreferrer">https://github.com/ultralytics/JSON2YOLO/blob/master/labelbox_json2yolo.py<...
<python><json><yolo><yolov5><yolov4>
2023-01-06 16:20:59
2
1,883
Leprechault
75,033,404
12,519,771
Timeout on task cancellation
<p>Consider this code:</p> <pre class="lang-py prettyprint-override"><code>import asyncio from async_timeout import timeout async def sleep_coroutine(sleep=10): while True: print(&quot;Coroutine running&quot;) try: await asyncio.sleep(10) except Exception: print(&qu...
<python><python-asyncio>
2023-01-06 16:15:27
0
957
RobBlanchard
75,033,370
15,445,589
Github Workflow / Action commit to repository returning 403
<p>I have a Github Workflow file where I bump the version of the python package (setup.py) and afterwards I want to push the changes to the repository the workflow runs in. But I get 403 no access granted back</p> <pre class="lang-yaml prettyprint-override"><code> build-package: permissions: contents: read ...
<python><git><github><github-actions>
2023-01-06 16:11:45
1
641
Kevin Rump
75,033,296
1,422,058
Consistent way of getting labels from plot, bar and other drawings with matplotlib
<p>With line plots, I can get all labels like this and build a legend:</p> <pre><code>p1 = ax1.plot(x, 'P1', data=df) p2 = ax1.plot(x, 'P2', data=df) p3 = ax1.plot(x, 'P3', data=df) p4 = ax1.plot(x, 'P4', data=df) p = p1+p2+p3+p4 labs = [l.get_label() for l in p] ax1.legend(p, labs, loc=0, frameon=False) </code></pre>...
<python><matplotlib>
2023-01-06 16:04:10
1
1,029
Joysn
75,033,149
4,796,942
Using python to connect or write a google apps script to a google sheet
<p>Is it true that it is not possible to directly connect a Google Apps Script (which uses JavaScript) to a Google Sheets spreadsheet using Python?</p> <p>I am asking this more as a design question: would it not be possible to keep a Google Apps Script in a file and simply use Python to connect it to a gsheets spreadsh...
<javascript><python><google-apps-script><design-patterns><pygsheets>
2023-01-06 15:51:05
2
1,587
user4933
75,033,112
19,003,861
Calculate sum of columns matching 2 criteria within a for loop
<p>Looking to calculate the sum of models objects macthing 2 requirements.</p> <p>As an example this is what the table would look like</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">User</th> <th style="text-align: center;">Venue</th> <th style="text-align: right;...
<python><django-models><django-views><django-templates>
2023-01-06 15:47:50
1
415
PhilM
75,033,069
1,667,018
Type hint for a dict that maps tuples containing classes to the corresponding instances
<p>I'm making a semi-singleton class <code>Foo</code> that can have (also semi-singleton) subclasses. The constructor takes one argument, let's call it a <code>slug</code>, and each (sub)class is supposed to have at most one instance for each value of <code>slug</code>.</p> <p>Let's say I have a subclass of <code>Foo</...
<python><mypy><python-typing>
2023-01-06 15:44:35
1
3,815
Vedran Šego
75,032,996
511,302
python subprocess behaviour changed between ubuntu 20 and 22?
<p>I upgraded my ubuntu installation to 22.04 from 18.04 yesterday. Now I notice that python virtual environment is no longer working as expect.</p> <p>I use python to run a lot of tools, and hence am highly dependent on subprocess library.</p> <p>However to my &quot;horror&quot; I notice that it changed quite a lot, ...
<python><ubuntu-22.04>
2023-01-06 15:37:59
0
9,627
paul23
75,032,936
662,285
Python Get complete string before last slash
<p>I want to get complete string path before last occurrence of slash (/)</p> <pre><code>String : /d/d1/Projects/Alpha/tests Output : /d/d1/Projects/Alpha </code></pre> <p>I am able to get the last part of string after last slash by doing</p> <pre><code>String.split('/')[-1] </code></pre> <p>But I want to get <code>&qu...
<python>
2023-01-06 15:33:04
3
4,564
Bokambo
75,032,742
4,822,772
SQL in python to include a where clause
<p>Here are the SQL code as string in python:</p> <pre><code>sql_code=&quot;&quot;&quot; SELECT VAR VAR2 FROM TABLE WHERE VAR in ('A','B') &quot;&quot;&quot; </code></pre> <p>And I would like to create a variable for the list of selection in the WHERE clause, this is what we can do:</p> <pre><code>sql_code_arg1=&qu...
<python><sql><python-3.x><prepared-statement>
2023-01-06 15:15:01
2
1,718
John Smith
75,032,730
11,092,636
sys.path.append which main.py will be imported
<p>If I have a project with two files <code>main.py</code> and <code>main2.py</code>. In <code>main2.py</code> I do <code>import sys; sys.path.append(path)</code>, and I do <code>import main</code>, which <code>main.py</code> will be imported? The one in my project or the one in <code>path</code> (the question poses it...
<python><sys>
2023-01-06 15:14:08
2
720
FluidMechanics Potential Flows
75,032,546
3,050,230
Github Actions not accessing download from Newspaper3k
<p>I've been trying to use Github Actions to run a python script. Everything seems to run fine, except a specific function that uses the Newspaper3k package. The article appears to download fine (article.html works ok), but Article.parse() does not work. This works fine on my local server, but not in Github. Is this re...
<python><python-3.x><github-actions><newspaper3k>
2023-01-06 14:56:35
0
387
Dave C
75,032,272
418,875
Debugging a C++ extension for Python from a Jupyter Notebook in Visual Studio Code
<p>I have a C++ extension for Python (produced using <code>pybind11</code>). Debugging this C++ extension from a Python script in Visual Studio Code can be achieved by adding the following configuration in the <code>launch.json</code> file:</p> <pre class="lang-json prettyprint-override"><code>{ &quot;version&quot;: ...
<python><visual-studio-code><jupyter-notebook><vscode-debugger><pybind11>
2023-01-06 14:32:40
1
1,200
A.L.
75,032,247
8,200,410
Add nan buffer to xarray dataset
<p>I have an xarray Dataset which will be acting as a mask to a different dataset. I'd like to create a buffer (of a configurable distance) from any nan values in the mask. I haven't seen anything that adds a buffer internally, instead of expanding the array size with padded values. Below is some reproducible code to s...
<python><python-xarray><resampling>
2023-01-06 14:30:59
1
441
JackLidge
75,032,181
1,562,489
Deprecating and Sunsetting endpoints in Django Rest Framework
<p>It's very hard to find documentation in Django Rest Framework for deprecation decorators. It seems the first few pages in google list Django's changelog and the various functionality they are deprecating, rather than how to deprecate endpoints in your own app.</p> <p>I have an API that I'm trying to develop inline w...
<python><django-rest-framework>
2023-01-06 14:25:34
1
1,198
David Sigley
75,032,145
2,876,994
How to pass an argument calling a function using ArgParse?
<p>I'm trying to call function_3 with an argument but i'm receiving a error unrecognized arguments. I'm calling this way: <code>python script.py --pass test</code></p> <pre><code>import argparse import sys def function_1(): print('Function 1') def function_2(): print('Function 2') def function_3(arg): pr...
<python><command-line-interface><argparse>
2023-01-06 14:22:15
2
1,552
Shinomoto Asakura