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,349,681
13,849,446
Extract chat id from https://web.telegram.org/z/ using selenium
<p>I want to extract the chat-id from telegram web version <strong>z</strong>. I have done it on the telegram web version <strong>k</strong> but, it is not present in the <strong>z</strong> version. I looked every where but could not find any element containing chat-id. I know I can get the chat-id from url after openi...
<python><selenium><selenium-webdriver><telegram>
2023-02-05 02:04:06
1
1,146
farhan jatt
75,349,639
3,019,570
Indirect inheritance in Python through decorators
<p>I want to define a decorator (let's name it subcollection) that behaves like this:</p> <pre class="lang-py prettyprint-override"><code>class ParentClass: name = None def __init__(self, name=None): self.name = name @subcollection class ChildClass: def greet(self): print(f...
<python><class><inheritance><python-decorators>
2023-02-05 01:52:46
0
1,977
Mahdi Jadaliha
75,349,592
3,788
Format HTML output of a Pandas dataframe based on row and column?
<p>I have the following code which outputs an HTML table:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame({ 'Color': ['Red', 'Red', 'Yellow', 'Yellow'], 'Fruit': ['Apple', 'Strawberry', 'Banana', 'Peach'], 'Weight': [5, 3, 8, 6] }) df = pd.pivot(df, index='Color',...
<python><pandas><dataframe>
2023-02-05 01:39:46
1
19,469
poundifdef
75,349,515
3,247,006
"on_session" vs "off_session" in Stripe
<p>I can set <code>on_session</code> and <code>off_session</code> for <a href="https://stripe.com/docs/api/checkout/sessions/create#create_checkout_session-payment_intent_data-setup_future_usage" rel="nofollow noreferrer">payment_intent_data.setup_future_usage</a> and <a href="https://stripe.com/docs/api/checkout/sessi...
<python><stripe-payments><payment><checkout><python-stripe-api>
2023-02-05 01:16:28
3
42,516
Super Kai - Kazuya Ito
75,349,427
7,583,953
Is there a difference between math.inf and cmath.inf in Python?
<p>Is there any difference between the infinities returned by the <code>math</code> module and <code>cmath</code> module?</p> <p>Does the complex infinity have an imaginary component of 0?</p>
<python><python-3.x><complex-numbers><infinity><python-cmath>
2023-02-05 00:54:45
1
9,733
Alec
75,349,313
5,051,937
Mock loading a dataframe during testing the function
<p>I am fairy new to unit testing in Python and have been using pytest. I have been using fixtures for some unit tests but there is a simple function (see below) that I want to test which has me baffled.</p> <p>It simply reads parquet file from s3 and as there are duplicate rows in the source data it dedupes on a given...
<python><unit-testing><mocking><pytest>
2023-02-05 00:23:31
0
323
pmanDS
75,349,191
2,713,263
How do I cimport scipy.spatial.ckdtree?
<p>I am rewriting some of my code using Cython, and want to type a <code>ckdtree</code> variable. I am currently doing</p> <pre><code>cimport scipy.spatial.ckdtree as ckdtree cdef tuple remove_labels(double[:, :] x_train, double[:, :] y_train): cdef ckdtree.KDTree tree // ... tree = ckdtree.KDTree(x_rest_...
<python><scipy><cython>
2023-02-04 23:52:54
0
1,276
Rahul
75,349,029
1,960,266
how to interpret this MNIST tensor?
<p>I have found a code that converts the data from the MNIST dataset into tensors. The code is the following:</p> <pre><code>import torch import torchvision import matplotlib.pyplot as plt batch_size_test=1000 test_loader=torch.utils.data.DataLoader( torchvision.datasets.MNIST('/files/',train=False,download=True,...
<python><tensorflow><mnist>
2023-02-04 23:18:43
1
3,477
Little
75,349,004
14,924,173
can not understand labeled concept in loc indexer in pandas
<p>I have a question and want to get an understanding of it, so the question is in pandas we have two indexers (loc, iloc) that we can use to select specific columns and rows, and the <em><strong>loc is labeled based on data selecting method which means that we have to pass the name of the row or column which we want t...
<python><python-3.x><pandas><dataframe><logic>
2023-02-04 23:13:28
1
496
Mohammad Al Jadallah
75,348,861
2,713,263
How can I speed up a loop that queries a kd-tree?
<p>The following section of my code is taking ages to run (it's the only loop in the function, so it's the most likely culprit):</p> <pre><code>tree = KDTree(x_rest) for i in range(len(x_lost)): _, idx = tree.query([x_lost[i]], k=int(np.sqrt(len(x_rest))), p=1) y_lost[i] = mode(y_rest[idx][0])[0][0] </code></pr...
<python><python-3.x><numpy>
2023-02-04 22:43:47
1
1,276
Rahul
75,348,803
19,051,091
How to make adaptive Threshold at part on image in Opencv python?
<p>Maybe my question is strange something but I need to make an adaptive Threshold on part of the image that the user selects with his mouse and that's my code</p> <pre><code>import cv2 img = cv2.imread(&quot;test.png&quot;) # img2 = cv2.imread(&quot;flower.jpg&quot;) # variables ix = -1 iy = -1 drawing = False def ...
<python><opencv>
2023-02-04 22:32:15
1
307
Emad Younan
75,348,791
257,924
seek(0) versus flush() on tempfile.NamedTemporaryFile before calling subprocess.run on a generated script
<p>Below is a example script to generate a Bash script into a temporary file, execute it, allow stdout and stderr to be emitted to the stdout of the calling script, and automatically delete the file.</p> <p>When I set <code>use_fix = True</code> as stated below, and set <code>use_seek</code> to either <code>True</code>...
<python><temporary-files>
2023-02-04 22:30:03
1
2,960
bgoodr
75,348,648
12,870,750
QtWidgets.QGraphicsLineItem issue when setting viewport to QOpenGLWidget()
<p><strong>Situation</strong></p> <p>I have a PyQt5 app that shows lines, text and circles, it shows them correctly but the text rendering is a bit slow. I have a custom class for <code>QGrapichsView</code> that implement all this.</p> <p><strong>problem</strong></p> <p>When I set in the properties of the gv the follow...
<python><pyqt5><pyopengl>
2023-02-04 21:58:12
1
640
MBV
75,348,588
16,665,831
Parse values from JSON body
<p>I have the attached following actions parameter part of my JSON data.</p> <pre><code>'actions': [{'action_type': 'onsite_conversion.post_save', 'value': '1'}, {'action_type': 'link_click', 'value': '2'}, {'action_type': 'post', 'value': '3'}, {'action_type': 'post_reaction', 'value': '4'}, {'action_type': 'v...
<python><json><pandas><parsing><jsonparser>
2023-02-04 21:45:34
3
309
Ugur Selim Ozen
75,348,491
9,773,920
How to extract username and password form secrets manager to use in psycopg2 connect
<p>My secrets manager is throwing secrets in the below format:</p> <pre><code>{&quot;username&quot;:&quot;uname&quot;,&quot;password&quot;:&quot;mypassword&quot;} </code></pre> <p>I want to extract username as password to use in psycopg2 connection string but it's not working. below is my code:</p> <pre><code>username ...
<python><amazon-web-services><aws-lambda><psycopg2><aws-secrets-manager>
2023-02-04 21:24:01
0
1,619
Rick
75,348,436
1,559,030
Get an evenly distributed subset of combinations without repetition
<p>I'm trying to get a subset of combinations such that every option is used the same amount of times, <em>or close to it</em>, from the total set of combinations without repetition. For example, I have 8 options (let's say A-H) and I need combinations of 4 letters where order doesn't matter. That would give me 70 poss...
<python><statistics><combinations>
2023-02-04 21:15:13
2
678
Marty
75,348,406
9,317,361
How to use fakebrowser driver and control it through Selenium Python
<p><strong>Summery of the question</strong><br /> The question is about how I can incorporate javascript modules in python. I need to operate the <a href="https://www.npmjs.com/package/fakebrowser" rel="nofollow noreferrer">fakebrowser's driver</a> in python the same way it does in javascript so it can keep all the man...
<javascript><python><selenium><selenium-webdriver>
2023-02-04 21:09:51
1
374
Speci
75,348,329
6,202,327
Numpy accurately computing the inverse of a matrix?
<p>I am trying to compute the eigen values of a matrix built by a matrix product M^{-1}K.</p> <p>I know M and K, I have initialized them properly. I thus try to compute the inverse of M:</p> <pre class="lang-py prettyprint-override"><code>M_inv = np.linalg.inv(M) with np.printoptions(threshold=np.inf, precision=10, sup...
<python><arrays><math><matrix><eigenvalue>
2023-02-04 20:57:18
1
9,951
Makogan
75,348,321
817,659
redis.client import string_keys_to_dict, dict_merge
<p>I have tried using this from both python 3.6 and 3.9 but get the same error:</p> <pre><code>pip install serialized-redis-interface Collecting serialized-redis-interface Using cached serialized_redis_interface-0.3.1-py3-none-any.whl (7.8 kB) Requirement already satisfied: redis&gt;3 in /home/idf/anaconda3/envs/work...
<python><redis><anaconda><redisclient>
2023-02-04 20:56:06
0
7,836
Ivan
75,348,247
443,626
Python - program crashes every 60 seconds making new requests in a while loop
<p>I have a script running every 60 seconds making a request using rest API:</p> <pre><code> def get_conn(): try: ms = datetime.now() - timedelta(days=xxx) current_time = time.mktime(ms.timetuple()) ms = datetime.now() current_time2 = time.mktime(ms.timetuple()) ...
<python>
2023-02-04 20:44:56
1
2,543
redoc01
75,348,156
1,533,576
Scale matplotlib text artist to fill rectangle patch bounding box
<p>Given a rectangle patch and text artist in matplotlib, is it possible to scale the text such that it fills the rectangle as best as possible without overfilling on either dimension?</p> <p>e.g.</p> <pre><code>import matplotlib as mpl import matplotlib.pyplot as plt f, ax = plt.subplots() ax.set(xlim=(0, 6), ylim=(0...
<python><matplotlib>
2023-02-04 20:26:15
1
49,310
mwaskom
75,348,116
1,584,906
gRPC becomes very slow all of a sudden
<p>I use gRPC for Python RPC on the same machine. It has been working great till yesterday. Then, all of a sudden, it started being very slow. The <code>helloworld</code> example now takes about 78s to complete. I tested it on three computers on the same network, all Ubuntu 18.04, with the same results. At home, the sa...
<python><grpc><grpc-python>
2023-02-04 20:19:43
0
1,465
Wolfy
75,347,974
5,151,909
mypy: Untyped decorator makes function "main" untyped for FastAPI routes
<p>Consider the following:</p> <pre class="lang-py prettyprint-override"><code>@app.post(&quot;/&quot;) def main(body: RequestBody) -&gt; dict[str, object]: pass </code></pre> <p>I'm getting the following error:</p> <blockquote> <p>Untyped decorator makes function &quot;main&quot; untyped [misc]mypy(error)</p> </b...
<python><fastapi><mypy>
2023-02-04 19:56:29
0
4,011
galah92
75,347,830
562,769
(Why) is there a performance benefit of using list.clear?
<p>I've recently noticed that the built-in <a href="https://docs.python.org/3/tutorial/datastructures.html" rel="nofollow noreferrer">list has a <code>list.clear()</code> method</a>. So far, when I wanted to ensure a list is empty, I just create a new list: <code>l = []</code>.</p> <p>I was curious if it makes a differ...
<python><cpython><python-3.11>
2023-02-04 19:35:30
1
138,373
Martin Thoma
75,347,762
12,574,341
Is using getters for read-only access pointless in Python?
<p>A method to achieve read-only access is to create a <code>getter</code> with no <code>setter</code>. This is the implementation in Python.</p> <pre class="lang-py prettyprint-override"><code>class Inventory: _items: list[Item] @property def items(self) -&gt; list[Item]: return self._items </code...
<python><oop>
2023-02-04 19:23:10
1
1,459
Michael Moreno
75,347,753
17,696,880
Replace ")" by ") " if the parenthesis is followed by a letter or a number using regex
<pre class="lang-py prettyprint-override"><code>import re input_text = &quot;((PL_ADVB)dentro ). ((PL_ADVB)ñu)((PL_ADVB) 9u)&quot; input_text = re.sub(r&quot;\s*\)&quot;, &quot;)&quot;, input_text) print(repr(input_text)) </code></pre> <p>How do I make if the closing parenthesis <code>)</code> is in front of a let...
<python><python-3.x><regex><string><regexp-replace>
2023-02-04 19:21:58
3
875
Matt095
75,347,524
9,213,682
How to convert string to key value in python
<p>I have a Django Application and want to convert a value from a string field which is comma separated to a key vaule pair and add it to a json data block.</p> <pre><code>class MyClass1(models.Model): keywords = models.TextField(_('Keywords'), null=True, blank=True) </code></pre> <p>Example of list:</p> <pre><code>blu...
<python><arrays><django-models><key-value>
2023-02-04 18:51:07
1
549
sokolata
75,347,457
12,941,578
Python asyncio, possible to run a secondary event loop?
<p>Is there a way to create a secondary asyncio loop(or prioritize an await) that when awaited does not pass control back to the main event loop buts awaits for those 'sub' functions? IE</p> <pre><code>import asyncio async def priority1(): print(&quot;p1 before sleep&quot;) await asyncio.sleep(11) print(&qu...
<python><python-3.x><asynchronous><python-asyncio>
2023-02-04 18:40:59
1
452
Pearl
75,347,443
13,571,242
Error with `python3.10` when running `apt install software-properties-common` when building dockerfile
<p>Currently my dockerfile is just:</p> <pre><code>FROM ubuntu:latest RUN apt-get update RUN apt install software-properties-common -y </code></pre> <p>However when building the dockerfile and running the step <code>apt install software-properties-common -y</code> the following error is in the messages:</p> <pre><code>...
<python><linux><docker><ubuntu><apt>
2023-02-04 18:38:33
2
407
James Chong
75,347,375
17,696,880
Set a regex pattern to condition placing or removing spaces before or after a ) according to the characters that are before or after
<pre class="lang-py prettyprint-override"><code>import re input_text = &quot;((NOUN) ) ) de el auto rojizo, algo) ) )\n Luego ((PL_ADVB)dentro ((NOUN)de baúl ))abajo.) ).&quot; input_text = input_text.replace(&quot; )&quot;, &quot;) &quot;) print(repr(input_text)) </code></pre> <p>Simply using the <code>.replace(&...
<python><regex>
2023-02-04 18:27:15
2
875
Matt095
75,347,354
19,363,912
Convert tuple with quotes to csv like string
<p>How to convert tuple</p> <pre><code>text = ('John', '&quot;n&quot;', '&quot;ABC 123\nDEF, 456GH\nijKl&quot;\r\n', '&quot;Johny\nIs\nHere&quot;') </code></pre> <p>to csv format</p> <pre><code>out = '&quot;John&quot;, &quot;&quot;&quot;n&quot;&quot;&quot;, &quot;&quot;&quot;ABC 123\\nDEF, 456\\nijKL\\r\\n&quot;&quot;&...
<python><csv><export-to-csv><quotes>
2023-02-04 18:23:46
1
447
aeiou
75,347,314
65,886
How to run python flet scripts on repl.it
<p>I'm trying to run a python flet script on repl.it. Here's what I did:</p> <ol> <li>created a new repl, for a python script; repl.it creates a main.py file</li> <li>from the Packages tool I imported flet</li> <li>I wrote this code into main.py:</li> </ol> <pre><code>import flet as ft def main(page:ft.Page): page.a...
<python><replit><flet>
2023-02-04 18:18:11
1
5,407
Al C
75,347,301
1,418,618
Using map to convert pandas dataframe to list
<p>I am using <code>map</code> to convert some columns in a dataframe to <code>list</code> of <code>dicts</code>. Here is a MWE illustrating my question.</p> <pre><code>import pandas as pd df = pd.DataFrame() df['Col1'] = [197, 1600, 1200] df['Col2'] = [297, 2600, 2200] df['Col1_a'] = [198, 1599, 1199] df['Col2...
<python><pandas><debugging>
2023-02-04 18:16:27
1
1,593
honeybadger
75,347,177
4,100,282
Spinning globe GIF with cartopy
<p>I'm failing to find the most efficient way to generate a simple animation of a spinning globe with a filled contour using cartopy. The following code yields a static gif, probably because the figure is not redrawing itself? Is there a way for the animation function to just change the geographic projection, without c...
<python><cartopy><matplotlib-animation>
2023-02-04 17:57:17
1
305
Mathieu
75,346,979
19,916,174
Is using else faster than returning value right away?
<p>Which of the following is faster?</p> <p>1.</p> <pre><code>def is_even(num: int): if num%2==0: return True else: return False </code></pre> <ol start="2"> <li></li> </ol> <pre><code>def is_even(num: int): if num%2==0: return True return False </code></pre> <p>Regardless of whi...
<python><performance><if-statement><optimization><return>
2023-02-04 17:27:06
1
344
Jason Grace
75,346,978
15,724,084
python tkinter wait until entry box widget has an input by user ONLY after then continue
<p>I have a code snippet which runs perfectly. In some cases, I need user input, but there are also cases where user input is not necessary and code functions without it perfectly. So, in that cases I create with conditional a flow where <code>entry box</code> widget is created and destroyed after value is <code>get()<...
<python><tkinter><tkinter-entry>
2023-02-04 17:27:04
1
741
xlmaster
75,346,930
6,367,971
Creating dataframe from XML file with non-unique tags
<p>I have a directory of XML files, and I need to extract 4 values from each file and store to a dataframe/CSV.</p> <p>The problem is some of the data I need to extract uses redundant tags (e.g., <code>&lt;PathName&gt;</code>) so I'm not sure of the best way to do this. I could specify the exact line # to extract, beca...
<python><pandas><xml><beautifulsoup>
2023-02-04 17:22:32
3
978
user53526356
75,346,830
10,558,697
Reuse file handle in python ThreadPoolExecutor
<p>The background to my question is the following: I have a search index implemented in whoosh, and I want to get the rankings for a batch of queries. I want to speed this up by handling multiple queries at a time, using <code>ThreadPoolExecutor.map</code>.</p> <p>In whoosh you have a <code>Searcher</code> object, whic...
<python><multithreading><concurrency><whoosh>
2023-02-04 17:06:53
0
324
Josef
75,346,782
1,572,146
Type check that a module has specific functions?
<p>How do I check if a module implements specific functions in Python?</p> <p>Say I have two modules, both implement two functions: <code>f</code> and <code>g</code>; with equal arity. However, in <code>mod0</code> <code>g</code> returns a <code>float</code> and in <code>mod1</code> <code>g</code> returns an <code>int<...
<python><protocols><python-typing>
2023-02-04 16:59:18
1
1,930
Samuel Marks
75,346,686
15,549,110
Find line number of replaced key value
<p>How do I get the line number of replaced key value? currently functions are different for it, how do i combine it to have line number at the time of replacing the string.</p> <pre><code>filedata= is a path of file. In which i need to replace strings. old_new_dict = {'hi':'bye','old':'new'} def replace_oc(file): ...
<python><python-3.x><dictionary><for-loop><replace>
2023-02-04 16:46:58
1
379
pkk
75,346,623
5,422,354
How to customize polynomial print in Numpy?
<p>I have polynomials which coefficients are computed using numerical integration methods. Mathematically, I use the Gram-Schmidt algorithm to produce orthogonal polynomials from a given probability distribution function, which involves integrals in the associated Hilbert space. Hence, they are sometimes approximated a...
<python><numpy>
2023-02-04 16:40:21
1
1,161
Michael Baudin
75,346,434
7,267,141
Automatic attribute copying from member class to parent class at class definition using ABC's __init_subclass__ in Python
<p>I have this code:</p> <pre><code>from abc import ABC class ConfigProto(ABC): def __init__(self, config_dict): self._config_dict = config_dict def parse(self, cfg_store: dict) -&gt; None: # do something with the config dict and the cfg_store and setup attributes ... class Configur...
<python><subclassing><abc>
2023-02-04 16:11:45
0
603
Adam Bajger
75,346,397
3,397,007
Can annotations be used to narrow types in Python
<p>I think in reality I'm going to use a different design, where <code>_attrib</code> is set in the construct and can therefore not be <code>None</code>, however I'm fascinated to see if there's a way to make MyPy happy with this approach. I have a situation where an attribute (in this instance <code>_attrib</code>) is...
<python><types><mypy>
2023-02-04 16:06:19
1
389
Richard Vodden
75,346,270
1,039,860
Add menu to libreoffice that persists app restarts via a script
<p>I'd like to run one script once that adds a menu that persists through <code>LibreOffice</code> restarts.</p> <p>I understand how to add a menu to <code>LibreOffice</code> <a href="https://stackoverflow.com/questions/75331489/how-to-run-libreoffice-python-script-using-scriptforge?noredirect=1#comment132933276_753314...
<python><libreoffice>
2023-02-04 15:45:10
1
1,116
jordanthompson
75,346,172
1,506,850
rolling unique value count in pandas across multiple columns
<p>there are several answers around rolling count in pandas <a href="https://stackoverflow.com/questions/65072737/rolling-unique-value-count-in-pandas">Rolling unique value count in pandas</a> <a href="https://stackoverflow.com/questions/46470743/how-to-efficiently-compute-a-rolling-unique-count-in-a-pandas-time-series...
<python><pandas><unique><rolling-computation>
2023-02-04 15:30:47
2
5,397
00__00__00
75,346,138
5,221,435
Python Flask - volumes don't work after dockerizing
<p>I'm trying to dockerize a Python-Flask application, using also volumes in order to have a live update when I change the code, but volumes don't work and I have to stop the containers and open run it again. That is the code that I try to change (main.py):</p> <pre><code>from flask import Flask import pandas as pd imp...
<python><docker><flask><docker-volume>
2023-02-04 15:25:48
1
1,585
Giacomo Brunetta
75,346,115
6,337,701
Unable to capture class with Brackets
<p>I'm using the following code in Python to capture certain text values from a webpage.</p> <pre><code>from bs4 import BeautifulSoup import requests url=&quot;https://example.com/page1.html&quot; response=requests.get(url) soup=BeautifulSoup(response.content,'html5lib') spans=soup.find_all('a',&quot;menu-tags&quot;) f...
<python><beautifulsoup>
2023-02-04 15:22:10
1
941
Aquaholic
75,346,073
4,418,481
Dash dropdown wont reset values once x clicked
<p>I created 2 Dash dropdowns where one dropdown (the lower) is based on the selection in the first dropdown (the upper)</p> <p><a href="https://i.sstatic.net/HSfCp.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/HSfCp.png" alt="enter image description here" /></a></p> <p>The selection and everything wor...
<python><plotly-dash>
2023-02-04 15:17:34
1
1,859
Ben
75,346,044
4,307,872
How to extract only a Rect object in PyMuPDF
<p>I tried the solution from this thread here:</p> <p><a href="https://stackoverflow.com/questions/72916381/read-specific-region-from-pdf">Read specific region from PDF</a></p> <p>Sadly the following example from the thread by user Zach Young doesn't work for me.</p> <pre><code>import os.path import fitz from fitz imp...
<python><extract><text-extraction><pymupdf>
2023-02-04 15:13:53
1
925
von spotz
75,345,963
51,167
Make BeautifulSoup recognize word breaks caused by HTML <li> elements
<p>BeautifulSoup4 does not recognize that it should would break between <code>&lt;li&gt;</code> elements when extracting text:</p> <p>Demo program:</p> <pre><code>#!/usr/bin/env python3 HTML=&quot;&quot;&quot; &lt;html&gt; &lt;body&gt; &lt;ul&gt; &lt;li&gt;First Element&lt;/li&gt;&lt;li&gt;Second element&lt;/li&gt; &...
<python><beautifulsoup>
2023-02-04 15:02:01
1
30,023
vy32
75,345,951
7,179,538
jupyter notebook python compatibility
<p>I am totally new to Python/Jupyter notebook.</p> <p>Using Windows 11. I installed latest version python <code>Python 3.11.1</code>. Also latest Anaconda - <code>conda 22.9.0</code>.</p> <p>My jupyter notebook (installed by anaconda) does not start from command line:</p> <blockquote> <p>jupyter notebook Traceback (mo...
<python><jupyter-notebook><anaconda>
2023-02-04 14:59:29
0
2,005
Sam-T
75,345,929
14,190,526
python patch. get Mock rather than MagicMock (with autospec)
<p>How I can get <code>Mock</code> object as patch result rather than <code>MagicMock</code> in this short sample?</p> <pre><code>from unittest.mock import patch, Mock class X: x=1 with patch.object(X, 'x', autospec=True) as my_mock: print(type(my_mock)) # NonCallableMagicMock, but need just a Mock/NonCall...
<python><python-unittest>
2023-02-04 14:56:10
0
1,100
salius
75,345,866
1,942,868
Object update by PATCH for Django REST Framework
<p>I am using <code>viewsets.ModelViewSet</code></p> <pre><code>from rest_framework import viewsets class ProjectViewSet(viewsets.ModelViewSet): serializer_class = s.ProjectSerializer queryset = m.Project.objects.all() def patch(self,request,*args,**kwargs): instance = self.get_object() ser...
<python><django><django-rest-framework>
2023-02-04 14:48:14
1
12,599
whitebear
75,345,862
15,673,832
How to use tuples as slice start:end values
<p>I need to slice array with arbitrary dimensions by two tuples. I can use slicing, such as <code>a[1:3, 4:6]</code>. But what do i do if 1,3 and 4,6 are tuples?</p> <p>While <code>a[(1, 3)]</code> works, I tried <code>a[(1, 3), (4, 6)]</code> and it didn't work, I think it ignores (4, 6). And I couldn't figure out ho...
<python><arrays><numpy><slice><dimensions>
2023-02-04 14:47:41
1
678
Ford F150 Gaming
75,345,674
11,436,357
Why playwright miss pattern url?
<p>I need to handle request with certain url and im trying to do it like this:</p> <pre class="lang-py prettyprint-override"><code>await page.route(&quot;**/api/common/v1/play?**&quot;, handle_data_route) </code></pre> <p>But it also handles a url like this: <code>api/common/v1/play_random?</code></p>
<python><playwright><playwright-python>
2023-02-04 14:17:25
1
976
kshnkvn
75,345,565
10,971,593
does read method of io.BytesIO returns copy of underlying bytes data?
<p>I am aware that <code>io.BytesIO()</code> returns a binary stream object which uses in-memory buffer. but also provides <code>getbuffer()</code> which provides a readable and writable view (<code>memoryview</code> obj) over the contents of the buffer without copying them.</p> <pre class="lang-py prettyprint-override...
<python><buffer><bytesio><memoryview>
2023-02-04 13:55:50
1
417
Scarface
75,345,521
9,773,920
Get filename from S3 bucket path
<p>I am getting the last modified file from S3 bucket using the below code:</p> <pre><code>import boto3 import urllib.parse import json import botocore.session as bc import time from time import mktime from datetime import datetime print('Loading function') def lambda_handler(event, context): s3_client = bot...
<python><amazon-web-services><amazon-s3><aws-lambda>
2023-02-04 13:49:57
1
1,619
Rick
75,345,190
323,631
pytest overrides existing warning filters
<p>It seems that ignoring warnings using <code>warnings.filterwarnings</code> is not respected by <code>pytest</code>. For example:</p> <pre><code>$ cat test.py import warnings warnings.filterwarnings('ignore', category=UserWarning) def test_warnings_filter(): warnings.warn(&quot;This is a warning&quot;, categor...
<python><pytest><warnings>
2023-02-04 12:47:38
2
2,581
Tom Aldcroft
75,345,086
6,630,397
Pandas DataFrame.to_sql() doesn't work anymore with an sqlalchemy 2.0.1 engine.connect() as a context manager and doesn't throw any error
<p>This code with <a href="https://pandas.pydata.org/docs/reference/index.html" rel="nofollow noreferrer">pandas</a> <code>1.5.3</code> and <a href="https://www.sqlalchemy.org/" rel="nofollow noreferrer">sqlalchemy</a> <code>2.0.1</code> is not working anymore and surprisingly, it doesn't raises any error, the code pas...
<python><pandas><sqlalchemy><psycopg2><contextmanager>
2023-02-04 12:27:23
3
8,371
swiss_knight
75,344,761
13,962,514
Why is Python not found by VS Code but found in the VS Code integrated terminal?
<p>I was trying learning about logging in python for the first time today. I discovered when i tried running my code from VS Code, I received this error message</p> <p><code>/bin/sh: 1: python: not found</code> however when I run the code directly from my terminal, I get the expected result. I need help to figure out t...
<python><visual-studio-code>
2023-02-04 11:26:42
3
311
Oluwasube
75,344,756
5,231,001
Python class function return super()
<p>So I was messing around with a readonly-modifyable class pattern which is pretty common in <code>java</code>. It involves creating a base class containig readonly properties, and extending that class for a modifyable version. Usually there is a function <code>readonly()</code> or something simular to revert a modify...
<python><python-3.x><design-patterns><super><readonly>
2023-02-04 11:26:19
1
1,922
n247s
75,344,613
13,285,583
How to get 1280x1280 from 3840x2160 output stream without scaling?
<p>My goal is to get 1280x1280 frame from nvarguscamerasrc. The problem is that <code>nvarguscamerasrc</code> scaled the 3840x2160 frame to 1280x720. The consequence is that the bottom of the frame is always black.</p> <p>JetsonCamera.py</p> <pre><code>def gstreamer_pipeline( # Issue: the sensor format used by Ras...
<python><opencv><gstreamer><nvidia-jetson>
2023-02-04 10:58:32
0
2,173
Jason Rich Darmawan
75,344,574
2,700,593
How to prevent Pandas to_dict() from converting timestamps to string?
<p>I have a dataframe with a <em>date</em> field which appear to be represented as unix timestamps. When i call <code>df.to_dict()</code> on it the dates are getting converted to a string like this <strong>yyyy-mm-dd</strong> .... how can I prevent this from happening?</p> <p>I'm using the code to return a JSON in my F...
<python><pandas><dataframe>
2023-02-04 10:53:09
1
3,203
rex
75,344,201
9,788,162
FastAPI Vercel deployment not starting app
<p>I can't get the API to run on Vercel, running locally works just fine.</p> <p>Since it's also my first time using Vercel, I can't seem to find logs. The build logs work fine (it's telling me 6 static pages, 0 of the rest), but when I go to the deployment page it serves me a <code>404</code> (not coming from my API)....
<python><deployment><fastapi><vercel><uvicorn>
2023-02-04 09:41:14
2
432
Dominic
75,344,021
3,682,549
How to access an object created inside a function outside
<p>I have the following function:</p> <pre><code>from __future__ import print_function, division from future.utils import iteritems from builtins import range, input # Note: you may need to update your version of future # sudo pip install -U future import numpy as np import matplotlib.pyplot as plt #from kmeans import...
<python><function>
2023-02-04 09:05:23
1
1,121
Nishant
75,343,916
2,706,344
Print full pandas index in Jupyter Notebook
<p>I have a pandas index with 380 elements and want to print the full index in Jupyter Notebook. I googled already but everything I've found did not help. For example this does not work:</p> <pre><code>with pd.option_context('display.max_rows', None, 'display.max_columns', None): print(my_index) </code></pre> <p>Ne...
<python><pandas><indexing><printing>
2023-02-04 08:42:23
2
4,346
principal-ideal-domain
75,343,872
6,468,436
No autocompletion for other python class in PyCharm
<p>I am a beginner with Python, in this loop i trying to use the methods of the variable &quot;data_point&quot; Behind the variable &quot;data_point&quot; is a simple getter and setter class, nevertheless in the autocompletion of PyCharm it shows me only 2 methods instead of all. What do I have to do to see all methods...
<python><autocomplete><pycharm>
2023-02-04 08:32:54
1
325
User1751
75,343,494
6,357,916
Empty `request.user.username` while handling a GET request created
<p>I was trying out logging all URLs accessed by user along with user id and date time when it was accessed using django middleware as explained <a href="https://stackoverflow.com/questions/67081706/django-middleware-to-log-every-time-a-user-hits-a-page">here</a>.</p> <p>For some URLs it was not logging user id. I chec...
<python><django><django-rest-framework><django-views>
2023-02-04 06:58:44
1
3,029
MsA
75,343,091
12,331,179
Json Creation using dataframe
<p>We are using below dataframe to create json file</p> <p>Input file</p> <pre><code>import pandas as pd import numpy as np a1=[&quot;DA_STinf&quot;,&quot;DA_Stinf_NA&quot;,&quot;DA_Stinf_city&quot;,&quot;DA_Stinf_NA_ID&quot;,&quot;DA_Stinf_NA_ID_GRANT&quot;,&quot;DA_country&quot;] a2=[&quot;data.studentinfo&quot;,&quo...
<python><json><pandas><for-loop><pyspark>
2023-02-04 05:05:44
1
386
Amol
75,342,979
9,206,667
Correctly Using Qmark (or Named) Style for SQL Queries
<p>I've got a a database filled with lots of data. Let's make it simple and say the schema looks like this:</p> <pre><code>CREATE TABLE foo ( col1 CHAR(25) PRIMARY KEY, col2 CHAR(2) NOT NULL, col3 CHAR(1) NOT NULL CONSTRAINT c_col2 (col2 = 'an' OR col2 = 'bx' OR col2 = 'zz') CONSTRAINT c_col3...
<python><python-3.x><sqlite>
2023-02-04 04:36:56
1
1,283
Lance E.T. Compte
75,342,909
6,653,602
UsePythonVersion@0 sets wrong Python versions in Azure Pipelines
<p>I added Python 3.9 to self hosted Agent toolcache successfully as shown in docs (<a href="https://learn.microsoft.com/en-us/azure/devops/pipelines/tasks/reference/use-python-version-v0?view=azure-pipelines&amp;viewFallbackFrom=azure-devops" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/azure/devops/pip...
<python><azure><azure-devops><azure-pipelines>
2023-02-04 04:14:42
0
3,918
Alex T
75,342,857
4,883,320
three dots aka ellipsis in import statement before package name
<p>I would like to know the purpose of a three-dots symbol aka ellipsis put before the package name in an import statement.</p> <p>Examples:</p> <p><a href="https://github.com/scikit-learn/scikit-learn/blob/b22f7fa552c03aa7f6b9b4d661470d0173f8db5d/sklearn/metrics/_plot/det_curve.py" rel="nofollow noreferrer">sklearn/me...
<python>
2023-02-04 04:00:25
1
1,293
KiriSakow
75,342,640
13,775,586
Python recv() doesn't wait for client response
<p>I'm trying to set up a communication via socket between a PHP page (client) and a Python script (server). The PHP page has a button that, when clicked, sends &quot;next&quot; to the server. This part works but the problem happens when I refresh the page. In this situation I'm not writing anything to the server, yet,...
<python><php><sockets><websocket>
2023-02-04 02:50:46
1
663
Raphaël Goisque
75,342,402
19,716,381
Load images into tensorflow from a single directory, with classes specified in a csv file
<p>Let's say I have a single directory <code>data</code>, which has pictures of both cats and dogs and a separate csv file <code>labels.csv</code>, which has the names of the files in the directory and it's labels. How can I load this image dataset into tensorflow?</p> <p>csv:</p> <pre><code>| filename | label | |___...
<python><tensorflow><keras>
2023-02-04 01:23:07
1
484
berinaniesh
75,342,312
20,959,773
Find pattern of elements between multiple lists
<p>Take these lists:</p> <pre><code>[545, 766, 1015] [546, 1325, 2188, 5013] [364, 374, 379, 384, 385, 386, 468, 496, 497, 547] </code></pre> <p>My actual pattern is just finding numbers that are ascending by one, only one from each list <code>(For this example, would be 545, 546 and 547).</code> After actually finding...
<python><list><math><logic><pattern-matching>
2023-02-04 00:54:46
2
347
RifloSnake
75,342,160
12,470,058
Partition of a list of integers into K sublists with equal sum
<p>Similar questions are <a href="https://stackoverflow.com/questions/27322804/partition-of-a-set-into-k-disjoint-subsets-with-equal-sum">1</a> and <a href="https://stackoverflow.com/questions/47557812/partition-a-set-into-k-subsets-with-equal-sum">2</a> but the answers didn't help. Assume we have a list of integers. W...
<python><python-3.x><algorithm><combinations>
2023-02-04 00:14:57
2
368
Bsh
75,341,949
14,790,056
groupby and apply multiple conditions
<p>This is a bit complicated but I will try to explain as best as I can.</p> <p>i have the following dataframe.</p> <pre><code> transaction_hash block_timestamp from_address to_address value data token_address 1 0x00685b3aecf64de61bca7a7c7068c17879bb2a2f3ebfe65d4b9421b40ac63952 2023-01-02 03:12:59+00:...
<python><pandas><dataframe>
2023-02-03 23:28:58
1
654
Olive
75,341,900
1,438,082
Query Nested JSON Data
<p>I am trying to query using the code below to get the value etoday but it does not return a result.</p> <pre><code> Result = json.loads(json_string) # Next Line works perfect print(&quot;The value of msg&quot;, &quot;msg&quot;, &quot;is: &quot;, Result[&quot;msg&quot;]) #Next Line does not (I have a few variat...
<python><json><dictionary>
2023-02-03 23:17:41
2
2,778
user1438082
75,341,867
1,475,962
Regex question to have substring match given strings
<p>I want regex to combine</p> <pre><code>&quot;.*SimpleTaskv9MoreDetails.*&quot; </code></pre> <p>or</p> <pre><code>&quot;.*SimpleTaskv10MoreDetails.*&quot; </code></pre> <p>How can I create regex to match both of them? I know that below one matches v8 and v9</p> <pre><code>&quot;.*SimpleTaskv[89]MoreDetails.*&quot; <...
<python><regex>
2023-02-03 23:11:39
2
5,048
raju
75,341,854
728,438
How to zip a list with a list of tuples?
<p>Say I have the following lists:</p> <pre><code>list_a = [1, 4, 7] list_b = [(2, 3), (5, 6), (8, 9)] </code></pre> <p>How do I combine them so that it becomes</p> <pre><code>[(1, 2, 3), (4, 5, 6), (7, 8, 9)] </code></pre>
<python><list>
2023-02-03 23:09:40
2
399
Ian Low
75,341,818
11,649,973
Correct way to add image related info wagtail
<p>I am setting up a simple site with the main purpose of having galleries of images. Using collections to group images and display them on a specific page is how I set it up first. However I am not sure what the recommended way is to add a description.</p> <p>My options I have tried are:</p> <ul> <li><a href="https://...
<python><django><wagtail>
2023-02-03 23:02:01
1
425
GreatGaja
75,341,446
10,007,302
Error trying to use a prepared statement in mysql.connector to updae a database
<p>I'm fairly new to databases/python and i've read that you're supposed to use prepared statements instead of string formatting</p> <p>I had</p> <pre><code>conn = mysql.connector.connect(user=user, password=pw, host=host, database=db) cursor = conn.cursor(prepared=True) cursor.execute(f&quot;DESCRIBE {table_name}&quo...
<python><mysql><mysql-connector>
2023-02-03 22:05:25
0
1,281
novawaly
75,341,427
1,932,930
Enum for bitwise operations with user readable strings table
<p>I am looking for an efficient and maintainable way to create a table in Python that can be used to look up user readable strings for enumeration values.</p> <p>Constraints:</p> <ul> <li>I want it to work with an enumeration that supports bitwise operations. For example: passing in a value of enumeration values that ...
<python><enums><bitmask>
2023-02-03 22:02:10
1
768
tdemay
75,341,411
214,526
pathlib relative path issue for upper/parent level directories
<p>I'm facing an issue while trying to get relative path to a parent level directory using pathlib but os.path works. How to satisfy the requirement using pathlib APIs?</p> <pre><code>In [1]: import os In [2]: p1 = &quot;/a/b/c&quot; In [3]: p2 = &quot;/a/b/c/d/e&quot; In [4]: os.path.relpath(p1, p2) Out[4]: '../..'...
<python><python-3.x>
2023-02-03 22:00:15
0
911
soumeng78
75,341,338
7,045,589
Python Requests: why do I get the error "get() takes 2 positional arguments but 3 were given" when I only have two arguments?
<p>I'm trying to implement error-handling of 504 responses for my Requests statement when I query an API. I read through <a href="https://stackoverflow.com/questions/23267409/how-to-implement-retry-mechanism-into-python-requests-library">this question</a>, and am attempting to implement the solution given in the most-...
<python><python-requests><http-status-code-504>
2023-02-03 21:49:27
2
309
the_meter413
75,341,308
4,668,368
How to remove json element with empty quotes?
<p>In the <code>python3</code> code below I read all the <code>objects</code> in the <code>json</code> then loop through the <code>elements</code> in the <code>json</code>. If I only search for the <code>id is not None</code> that element and the null value are removed. However when I add the <code>or</code> statement ...
<python><json>
2023-02-03 21:45:17
1
3,022
justaguy
75,341,301
7,841,330
Python - Resolve response Remote URL link with actual page
<p>I am trying to get the actual page URL using the remote URL from JSON response. Below is the remote URL I get in an JSON API response.</p> <pre><code>https://somesite.com/mainlink/1eb-68a8-40be-a3-5679e/utilities/927-40-b958-3b5?pagePath=teststaff </code></pre> <p>when I click the link, it resolves to actual page wh...
<python><python-3.x><python-requests>
2023-02-03 21:44:41
1
669
Joe_12345
75,341,277
2,519,150
Python get datetime intervals of x minutes between two datetime objects
<p>How can I get the list of intervals (as 2-tuples) of <code>x</code> minutes between to datetimes? It should be easy but even <code>pandas.date_range()</code> returns exacts intervals, dropping end time. For example:</p> <p>In:</p> <pre><code>from = '2023-01-05 16:01:58' to = '2023-01-05 17:30:15' x = 30 </code>...
<python><pandas><datetime>
2023-02-03 21:41:17
1
487
Stefano Lazzaro
75,341,238
17,696,880
Prevent a regex with capturing groups from acting on matches of a string that re preceded by a specific word and at the same time succeeded by another
<pre class="lang-py prettyprint-override"><code>import re input_text = &quot;((PL_ADVB)alrededor ((NOUN)(del auto rojizo, dentro de algo grande y completamente veloz)). Luego dentro del baúl rápidamente abajo de una caja por sobre ello vimos una caña.&quot; #example input place_reference = r&quot;(?i:[\w,;.]\s*)+?&qu...
<python><python-3.x><regex><string><regex-group>
2023-02-03 21:35:36
0
875
Matt095
75,341,236
6,918,112
How to run Netflix movies on Raspberry PIs using Docker container with Python and Selenium headless?
<p>I have a Raspberry PI and Docker containers in it.</p> <p>One of the containers (Python + Selenium script) is supposed to access Netflix headless and run a movie.</p> <p>It works fine in my Windows PC using Chrome (non-headless) or Firefox driver (headless and non-headless).</p> <p>Then, because it works on Firefox ...
<python><selenium><raspberry-pi><headless><netflix>
2023-02-03 21:35:27
0
640
Jeff Santos
75,341,170
1,848,244
Pandas Hierarchical MultiIndex: Concise way to use values from other levels in a row calc
<p>Probably easiest to demonstrate in code.</p> <p>Basically I have:</p> <ul> <li>A hierarchical dataframe. Something similar to:</li> </ul> <pre><code>level1 level2 root child1 10 10 child2 20 20 child3 30 30 child4 40 40 root2 child1 100 100 ...
<python><pandas>
2023-02-03 21:26:06
0
437
user1848244
75,341,070
4,792,865
Qt QProgressBar not updating regularly when text is not visible
<p>I have a QProgressBar that is set to not display text. It appears that this causes the progress bar to not update regularly, but only after some chunks (roughly 5-10%).</p> <p>The following minimum Python example shows a window with two progress bars which get updated in sync. The one not displaying text is lagging ...
<python><qt><pyqt5>
2023-02-03 21:12:26
1
735
Andre
75,340,998
9,328,993
cannot import name 'compute_pycoco_metrics' from 'keras_cv.metrics.coco'
<p>i install keras_cv on macbook M1:</p> <pre><code>pip install keras_cv </code></pre> <p>and run this code</p> <pre><code>import keras_cv </code></pre> <p>and get this error:</p> <pre><code>Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; File &quot;/opt/homebrew/lib/pyt...
<python><keras-cv>
2023-02-03 21:01:36
2
2,630
Sajjad Aemmi
75,340,900
21,116,910
Fast data transfer between a python program (server) and a Java program (client) on the same singleboard Linux computer (Raspberry Pi 3)
<p>I know relativ good java and created a videogame using it for raspberry pi. The game must be controlled via an USB joystick. I searched and found many variant to read joystick data, but it seems that the best way is to use evdev written on python. How can I transfer data from a python script to a Java application? T...
<python><java><linux><raspberry-pi><gamepad>
2023-02-03 20:48:06
1
333
Alexander Gorodilov
75,340,879
7,157,059
Multi-Thread Binary Tree Search Algorithm
<p>I find implementing a multi-threaded binary tree search algorithm in Python can be challenging because it requires proper synchronization and management of multiple threads accessing shared data structures.</p> <p>One approach, I think is to achieve this would be to use a thread-safe queue data structure to distribu...
<python><multithreading><binary>
2023-02-03 20:44:20
2
749
Acerace.py
75,340,743
2,690,257
How to use a variable dynamically from an imported module in python 3.8
<p>I currently have the following file load.py which contains:</p> <pre><code>readText1 = &quot;test1&quot; name1 = &quot;test1&quot; readText1 = &quot;test2&quot; name1 = &quot;test2&quot; </code></pre> <p>Please note that the number will change frequently. Sometimes there might be 2, sometimes 20 etc.</p> <p>I need...
<python>
2023-02-03 20:30:17
3
3,353
FabricioG
75,340,739
10,976,654
Python locally installed package, module not defined
<p>I have a local package set up like this:</p> <pre><code>D:. | .gitignore | LICENSE | pyproject.toml | README.md | requirements.txt +---.venv | | ... +---mypackage | | __init__.py | +---moduleA | | | module_a_src.py | | | module_a_helpers.py | +---tools | | ...
<python><package>
2023-02-03 20:29:55
0
3,476
a11
75,340,659
7,042,778
Easy code adding additional information into the dataframe
<p>Is there another way to add the information to the datafame, an easier way?</p> <p>I have a dataframe which looks like the following:</p> <pre><code> Product Price 2023-01-03 Apple 2.00 2023-01-04 Apple 2.10 2023-01-05 Apple 1.90 2023-01-03 Banana 1.10 2023-01-04 Banana 1.15 ...
<python><dataframe>
2023-02-03 20:19:01
2
1,511
MCM
75,340,441
19,366,064
Traverse Tree and finding all possible path to target
<p>Original Question: Given the root of a binary tree and an integer targetSum, return <em>the number of paths where the sum of the values along the path equals</em> targetSum. The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes)....
<python><binary-tree><tree-traversal>
2023-02-03 19:53:22
1
544
Michael Xia
75,340,307
9,542,989
"Unable to connect: Adaptive Server is unavailable or does not exist" in SQL Server Docker Image
<p>I am trying to connect to a Docker container running SQL Server using <code>pymssql</code> and I am getting the following error,</p> <pre><code>Can't connect to db: (20009, b'DB-Lib error message 20009, severity 9: Unable to connect: Adaptive Server is unavailable or does not exist (localhost) Net-Lib error during C...
<python><sql-server><docker><pymssql><mindsdb>
2023-02-03 19:36:18
1
2,115
Minura Punchihewa