QuestionId
int64
74.8M
79.8M
UserId
int64
56
29.4M
QuestionTitle
stringlengths
15
150
QuestionBody
stringlengths
40
40.3k
Tags
stringlengths
8
101
CreationDate
stringdate
2022-12-10 09:42:47
2025-11-01 19:08:18
AnswerCount
int64
0
44
UserExpertiseLevel
int64
301
888k
UserDisplayName
stringlengths
3
30
76,297,183
2,768,296
How to write Django query expression to convert unix time to datetime?
<p>I am writing a function to generate a report from a Django database. My production database is PostgreSQL but my test database is SQLite, so I need to support both.</p> <p>I need to compare two times, but one is stored in the database as a unix time stamp, and the other is a datetime object. I do not have the freedo...
<python><django><sqlite>
2023-05-20 20:15:09
1
651
Steven Gillies
76,297,160
12,282,349
FastAPI middleware session custom var not updating
<p>In my FastApi application I am trying to set SessionMiddleWare cookie called &quot;lang&quot;:</p> <pre><code>@app.get(&quot;/language&quot;) async def language(request: Request, lang: str = None): if lang == 'en': request.session[&quot;lang&quot;] = 'en' elif lang == 'lt': request.session[&...
<python><fastapi>
2023-05-20 20:08:47
0
513
Tomas Am
76,297,001
17,638,206
Finding a string between two substrings in arabic
<p>I have a string</p> <pre><code>string = &quot;الطالب يذهب الي الممدرسة&quot; </code></pre> <p>I want to extract <code>يذهب</code> I have tried the following code:</p> <pre><code>import re res = re.search('الي(.*)الطالب', string) print(res.group(1)) </code></pre> <p>But this doesn't work.</p>
<python><string>
2023-05-20 19:27:06
1
375
AAA
76,296,957
11,748,924
How to implement WSGI while using multiprocessing in flask?
<p>Suppose I have video process handler in a function, I want implement true parallel processing using <code>multiprocessing</code> module instead of <code>threading</code>.</p> <p>So my code looks like this in general:</p> <pre><code>def start_subprocess(pid, progress_dict): ''' Suppose this is video processing st...
<python><flask><deployment><multiprocessing><wsgi>
2023-05-20 19:13:13
1
1,252
Muhammad Ikhwan Perwira
76,296,840
583,464
apply map to tf dataset
<pre><code>import numpy as np import tensorflow as tf def scale(X, dtype='float32'): a=-1 b=1 xmin = tf.cast(tf.math.reduce_min(X), dtype=dtype) xmax = tf.cast(tf.math.reduce_max(X), dtype=dtype) X = (X - xmin) / (xmax - xmin) scaled = X * (b - a) + a return scaled, xmin, xmax a = np.rand...
<python><tensorflow><tensorflow2.0>
2023-05-20 18:43:50
1
5,751
George
76,296,672
19,318,120
django crontab schedule not being executed
<p>Trying to run django crontab in docker-compose when running the command manually using <code>python manage.py crontab run some-hash</code>, it works <br> otherwite it's never executed, here's my compose</p> <pre><code>version: '3.8' services: django: build: . container_name: django co...
<python><django><cron>
2023-05-20 18:03:19
1
484
mohamed naser
76,296,608
187,519
Installing vpython on replit
<p>I go to packages and I search for vpython and I click install. It notifies that &quot;vpython is installed&quot; but it does not show up as installed.</p>
<python><vpython>
2023-05-20 17:48:52
0
3,704
Hassan Voyeau
76,296,353
5,838,180
How to subsample a pandas df so that its variable distribution fits another distribution?
<p>I am having 2 astronomical data tables, <code>df_jpas</code> and <code>df_gaia</code>. They are catalogues of galaxies containing among others the red-shifts <code>z</code> of the galaxies. I can plot the distribution of the redshifts of the 2 catalogs and it looks like this:</p> <p><a href="https://i.sstatic.net/NJ...
<python><pandas><histogram><distribution><astropy>
2023-05-20 16:54:56
1
2,072
NeStack
76,296,292
12,004,339
Postgres NOW() returns incorrect time when called inside asyncio task
<p>My code runs once an hour and logs the time correctly, but for some reason postgres HOW() returns the wrong time.</p> <p>The code looks something like this:</p> <pre class="lang-py prettyprint-override"><code>async def run(): await before_startup() # ... async def before_startup() -&gt; None: loop = asy...
<python><postgresql><python-asyncio>
2023-05-20 16:41:15
1
308
kinton
76,296,219
10,266,059
Why is the python docstring for `os.CLD_CONTINUED` the same as `int().__doc__`?
<p>I am getting familiar with Python and I thought I would do a dir() walk and examine the doc strings.</p> <p>I started with the &quot;os&quot; module.</p> <p>Why is the python docstring for <code>os.CLD_CONTINUED</code> the same as <code>int().__doc__</code>?</p> <p>I first noticed that <code>CLD_CONTINUED</code> had...
<python><docstring>
2023-05-20 16:26:35
1
1,676
Aleksey Tsalolikhin
76,296,055
12,065,403
How to avoid Tkinter slowing down as number of shapes increases?
<p>I have a python project with tkinter. On this project I draw small squares over time. I noticed tkinter is slowing down as the number of square increases.</p> <p>Here is a simple example that draws 200 red squares on each iteration:</p> <pre><code>import tkinter as tk import random import time WIDTH = 900 CELL_SIZE...
<python><tkinter>
2023-05-20 15:45:16
3
1,288
Vince M
76,295,882
1,485,872
How to pass a user defined argument to setuptools in order to set a flag that changes compilation macro
<p>I have some large setup.py file that compiles several CUDA files, something like (VERY INCOMPETE, I can provide more info if its relevant):</p> <pre><code>gpuUtils_ext = Extension( &quot;_gpuUtils&quot;, sources=include_headers( [ &quot;gpuUtils.cu&quot;, &quot;python/utilitie...
<python><setuptools><setup.py>
2023-05-20 15:04:03
1
35,659
Ander Biguri
76,295,586
616,507
Converting element types of python lists in Jinja2 templates
<p>I have a list of values, in string format (because that's what they're read in as from the CSV source):</p> <pre><code>[ '12.2', '14.5', '13.8', '17.3', '14.9' ] </code></pre> <p>In my Jinja2 template, I would like to do the functional equivalent of:</p> <pre><code>The average is: {{list|average}} </code></pre> <p>T...
<python><jinja2>
2023-05-20 13:53:52
1
727
John
76,295,226
350,143
remove horizontal black line in a grayscale image
<p>I have this image that has a continuous black horizontal line, and I need to remove it as a first step in enhancing it. is there a way to remove it using imageJ/Fiji or python, such as a library or a plug in?</p> <p>I understand the concept of using a mask of this horizontal line and using it to merge median filtere...
<python><image-processing><grayscale><imagej><fiji>
2023-05-20 12:27:08
1
931
Atheer
76,295,048
5,431,734
pandas qcut with NaNs
<p>I am trying to assign the elements of the rows of a dataframe into quartiles. The rows however could have NaNs only, for example:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'A': [np.nan, 20, 30, 40], 'B': [np.nan, np.nan, 31, 41], 'C': [np.nan, 22,...
<python><pandas>
2023-05-20 11:45:21
1
3,725
Aenaon
76,294,949
20,266,647
Error "value of key _fn0 is None" during data ingest
<p>I got this mistake in MLRun, during ingest values to the FeatureSet:</p> <pre><code>&gt; 2023-05-20 13:11:40,669 [info] loaded project my-project7xx from ./ and saved in MLRun DB &gt; 2023-05-20 13:11:53,640 [error] For {'_1': 374, '_2': 886, '_3': 989, '_4': 191, '_5': 49, '_6': 658, '_7': 994, '_8': 857, '_9': 217...
<python><mlops><feature-store><mlrun>
2023-05-20 11:21:42
1
1,390
JIST
76,294,697
7,987,455
Why does requests_html return an empty list, although the selector or XPATH are correct?
<p>I am trying to scrape data from AliExpress using requests_html and CSS selectors, but it always returns an empty list. Can you please help?</p> <p>The code I used:</p> <pre><code>import time from requests_html import HTMLSession url = 'https://www.aliexpress.com/w/wholesale-test.html?catId=0&amp;initiative_id=SB_...
<python><web-scraping><python-requests><css-selectors><python-requests-html>
2023-05-20 10:24:03
2
315
Ahmad Abdelbaset
76,294,683
4,105,440
Cannot use Dask to merge many CSV files (while Pandas works just fine)
<p>My use case is quite simple: read about 70k small CSV-gzipped files and merge them into a single zipped parquet file with a common index. Every file weights about 3KB zipped, 9KB extracted. All the files zipped together are about 200MB in size.</p> <p>The serial version looks like</p> <pre class="lang-py prettyprint...
<python><pandas><dask>
2023-05-20 10:22:35
1
673
Droid
76,294,611
17,082,611
Pasting a working code into a for loop suddenly won't work anymore
<p>This is the code I wrote:</p> <pre><code>raw = read_bdf(path='data_original/', subject='s01.bdf') raw.resample(sfreq=128, verbose=False) indices = get_indices_where_video_start(raw) index = indices[1] # 29948 eeg = ['Fp1', 'Fp2'] raw.pick_channels(eeg) raw = crop(raw, index) # &lt;&lt; works for index=29948 </...
<python><loops>
2023-05-20 10:04:14
2
481
tail
76,294,480
4,776,689
Basic inheritance not works while using dependency_injector library DeclarativeContainer in Python. Why?
<p>It is known the Python have ability to create child classes and add methods into them. However when I inherit class from DeclarativeContainer it fails and I cannot understand why. This code works fine if I inherit from different classes. Please help to understand why inheritance not works as I expect in this case.</...
<python><inheritance><dependency-injection>
2023-05-20 09:37:04
1
2,990
P_M
76,294,376
4,623,227
How can I type hint enum values in python, bounded to some protocol
<p>I'm trying to type hint enum values, so that each value is bounded to some protocol. The desired typing error is a warning on enum creation, not on calling.</p> <p>Minimum working example:</p> <pre class="lang-py prettyprint-override"><code>from __future__ import annotations import typing as t from enum import Enum ...
<python><enums><mypy>
2023-05-20 09:09:41
1
870
Susensio
76,294,111
1,603,480
Using pytest to test logged messages and avoid displaying logged messages on the console
<p>I want to test messages logged by some functions (<code>logging</code> modules) using the <code>caplog</code> fixtures.</p> <p>However, for some strange reasons, these logged messages keep on displaying on the console (even if explicitely set <code>log-cli</code> to False or with a higher level).</p> <p>Here is a so...
<python><pytest><python-logging><caplog>
2023-05-20 07:59:04
1
13,204
Jean-Francois T.
76,294,003
1,065,489
Convert MNIST dataFrame row of 1-D(784) Column to 2D(28x28) using pandas dataframe
<p>I am reading MNIST like image from a CVS of 784 columns, where each row represents an image. My model needs X_train input in form of 28x28 instead of 784 columns. Since I am new to Pandas and Dataframe, not sure I to do it. It would be really helpful if somebody can help change the shape of the input from 784 colums...
<python><pandas><dataframe><numpy>
2023-05-20 07:24:31
2
5,512
me_digvijay
76,293,833
8,277,802
Catastrophic backtracking issue while parsing partial/incomplete json
<p>I have a very complex rexeg meant to parse a fixed schema json. I know we are not supposed to parse jsons via regex but I am dealing with terabyte size json and am trying to implement a parallel json reader which identifies the target records in a buffer mode. i.e I take a a random chunk and find the matching record...
<python><json><regex>
2023-05-20 06:34:52
0
488
Siddharth Chabra
76,293,648
264,136
where is the collection name specified
<pre class="lang-python prettyprint-override"><code>app=Flask(__name__) CORS(app) app.config[&quot;MONGODB_SETTINGS&quot;] = [ { &quot;db&quot;: &quot;UPTeam&quot;, &quot;host&quot;: &quot;10.64.127.94&quot;, &quot;port&quot;: 27017, &quot;alias&quot;: &quot;default&quot;, } ] db...
<python><mongodb><mongoengine><flask-mongoengine>
2023-05-20 05:24:37
1
5,538
Akshay J
76,293,542
13,738,079
TypeError: GAN.training_step() missing 1 required positional argument: 'optimizer_idx'
<p>When I start training my GAN model:</p> <pre><code>trainer = pl.Trainer(max_epochs=20, devices=AVAIL_GPUS, accelerator='gpu') trainer.fit(GAN(), MNISTDataModule()) </code></pre> <p>I get this error: <code>TypeError: GAN.training_step() missing 1 required positional argument: 'optimizer_idx'</code></p> <p>I do have a...
<python><pytorch><generative-adversarial-network><pytorch-lightning>
2023-05-20 04:35:09
1
1,170
Jpark9061
76,293,258
489,088
Given a Numpy array, how to calculate the percentile of each of the array elements?
<p>I have an array like this:</p> <pre><code>import numpy as np arrx = np.array([0, 5, 10]) print(np.percentile(arrx, 100)) </code></pre> <p>Which returns a single scalar: the element that more closely matches the percentile I specified as a second argument. In this case, <code>10</code>.</p> <p>I would like however t...
<python><arrays><numpy><numpy-ndarray>
2023-05-20 02:00:28
1
6,306
Edy Bourne
76,293,219
5,656,793
How to build a python extension with C++ and include .so files in wheel
<p>I can't find any instructions on how you would put shared libraries used by python bindings generated with something like pybind11 into a wheel so that the end user does not have to also use an other package manager like apt to install the .so files gnerated in a project. As an example, if my C++ project builds lib...
<python><c++><pybind11>
2023-05-20 01:37:30
0
395
tenspd137
76,293,190
5,336,013
Python Pandas: how to subtract value of column A in the last row of each group from column B of certain rows in the group in reverse order
<p>To clarify, the 'group' in the title is not a result of pd.groupby. Instead, I meant it as rows that share the same values of certain columns. In my case it would be account and security_id.</p> <p>I am trying to calculate profits&amp;loss by account and position from trade data on a First-in, first-out (FIFO). Ther...
<python><pandas><dataframe><data-cleaning>
2023-05-20 01:18:36
1
1,127
Bowen Liu
76,293,167
9,571,463
Reading stdout and stderr as it Arrives Using Asyncio
<p>I have code that schedules two tasks (both simple python scripts) and runs them. However, I want to read the stdout/stderr as they are written via the task. Currently, my code is only returning them after the subprocess finishes. Note, I am using Python 3.9.13.</p> <p>Below are the two simple scripts which just prin...
<python><async-await><python-asyncio>
2023-05-20 01:03:12
0
1,767
Coldchain9
76,292,849
5,527,752
Databricks dbutils.fs.mv can not find unzipped file in BDFS
<p>I'm trying to follow a <a href="https://learn.microsoft.com/en-us/azure/databricks/files/unzip-files" rel="nofollow noreferrer">Microsoft Tutorial</a> on how to import a zipped file, unzip it, and then load the files contents into a data frame using databricks.</p> <p>First part of the tutorial goes fairly well, it'...
<python><bash><databricks><azure-databricks>
2023-05-19 22:55:17
1
1,531
Randall
76,292,635
21,305,238
Descriptor's __set__ not invoked
<p>I have a <code>innerclass</code> decorator/descriptor that is supposed to pass the outer instance to the inner callable as the first argument:</p> <pre class="lang-py prettyprint-override"><code>from functools import partial class innerclass: def __init__(self, cls): self.cls = cls def __get__(self, obj, ...
<python><python-decorators><inner-classes><python-descriptors>
2023-05-19 21:58:51
3
12,143
InSync
76,292,529
6,379,197
Doing T-test across two data sets to validate null hypothesis
<p>I need to T-Test to check whether the Sentiment feature has a significant role in identifying gender from text. I have computed the TF-IDF feature and got <code>author_post_new</code>. I have applied the Sentiment feature on the dataset and got <code>X_pac</code> from the dataset. Now I want to determine whether the...
<python><t-test><hypothesis-test><statistical-test>
2023-05-19 21:33:26
0
2,230
Sultan Ahmed
76,292,501
1,986,643
Query existing Pinecone index without re-loading the context data
<p>I'm learning Langchain and vector databases.</p> <p>Following the original documentation I can read some docs, update the database and then make a query.</p> <p><a href="https://python.langchain.com/en/harrison-docs-refactor-3-24/modules/indexes/vectorstores/examples/pinecone.html" rel="noreferrer">https://python.la...
<python><langchain>
2023-05-19 21:25:37
1
962
Francisco Ghelfi
76,292,432
2,317,670
How to have a python script restart itself in a screen session?
<p>I have a long running python script that runs on a remote machine. I'd like to have it check if it is running in a screen session and restart itself in an attached one if not. That way I will still see the output if I am watching it, but it will continue to run if I get disconnected. So far I've tried several var...
<python><linux><ssh><gnu-screen>
2023-05-19 21:07:56
1
369
carmiac
76,292,368
3,507,825
How to force indent of python LXML xml element nests when writing iteratively?
<p>I am using LXML to write an xml file that is a dump of a database. Given the size of the data, I must write the xml file iteratively. When dumping the etree to a file, I run out of memory on a server with 32GB of ram.</p> <p>I have written code that iteratively writes the xml via methods on this page <a href="https:...
<python><xml><iteration><lxml>
2023-05-19 20:54:04
1
451
user3507825
76,292,042
3,007,075
Multiprogress bars in Pycharm's console
<p>I've wanted to post this code here so I and others can use it in the future, and it works nicely on vscode. But I would also like it to work properly on PyCharm's Run console, if there is any way to do it.</p> <p>I'm basically spawning several tasks I want to be run in parallel. For the purpose of the example, the w...
<python><python-3.x><pycharm><python-multiprocessing><tqdm>
2023-05-19 19:46:13
0
1,166
Mefitico
76,292,039
1,391,683
GitHub Actions: Installing NumPy before other dependencies
<p>I have a workflow on GitHub that is performing unit tests with <code>pytest</code>.</p> <p>One of the dependencies in <code>requirements.txt</code> requires <code>NumPy</code> to be already present, since it is using <code>numpy.distutils</code> in its <code>setup.py</code> to install some Fortran extensions. I ther...
<python><numpy><github-actions><workflow>
2023-05-19 19:45:48
0
805
Sebastian
76,292,008
10,606,962
Why can I instantiate classes with abstract methods in Python?
<p>I noticed that a class with an <code>abstractmethod</code> can still be instantiated if it does not inherit from <code>ABC</code>. This seems to be in contrast with the <a href="https://docs.python.org/3/library/abc.html#abc.abstractmethod" rel="nofollow noreferrer">documentation</a>:</p> <blockquote> <p>Using this ...
<python><python-3.x><abstract-class><abstract>
2023-05-19 19:40:07
1
7,133
CallMeStag
76,292,003
1,006,183
When using uvicorn with gunicorn, why attach logs to the error logger?
<p>When running Gunicorn <a href="https://www.uvicorn.org/deployment/#gunicorn" rel="nofollow noreferrer">as a process manager</a> for Uvicorn the access logs, exceptions, etc are not displayed in the Gunicorn logs by default.</p> <p>The solutions I found in several places suggest variations of the following:</p> <pre ...
<python><flask><fastapi><gunicorn><uvicorn>
2023-05-19 19:39:36
1
11,485
Matt Sanders
76,291,943
445,810
Create a Python string from a native pointer without char buffer copy
<p>Is it possible?</p> <p>I'd like to have a lot of strings stored in a PyTorch/NumPy tensor (e.g. in fixed-size UTF-32 4-byte character) - could even be mmap'd from disk, and then to manipulate them with Python3 string APIs.</p> <p>For maximum elegance, savings of Python objects, manual arena-like memory management (a...
<python><python-3.x><string><cpython>
2023-05-19 19:25:31
0
1,164
Vadim Kantorov
76,291,845
2,697,895
How can I do an unbuffered disk read in Python?
<p>I need to read a sector from the physical disk, but without using the system cache.</p> <p>I tried this:</p> <pre><code>import os disk_path = &quot;/dev/sdc&quot; try: disk_fd = os.open(disk_path, os.O_RDONLY | os.O_DIRECT) os.lseek(disk_fd, 12345 * 4096, os.SEEK_SET) buffer = os.read(disk_fd, 4096) f...
<python><linux><disk-io>
2023-05-19 19:06:30
1
3,182
Marus Gradinaru
76,291,806
14,954,262
Django How to get value of CheckboxSelectMultiple in Javascript in Template
<p>I have a <code>CheckboxSelectMultiple</code> in a Django form like this :</p> <p><strong>forms.py</strong></p> <pre class="lang-py prettyprint-override"><code>LIST= [ ('Oranges', 'Oranges'), ('Cantaloupes', 'Cantaloupes') ] testrever = forms.MultipleChoiceField(required=False,widget=forms.widgets.CheckboxSelect...
<javascript><python><django><django-forms>
2023-05-19 18:58:14
2
399
Nico44044
76,291,801
1,566,682
Great Expectations using schema name in query for Redshift
<p>I'm having an issue where when great expectations builds a query string to a <code>table_asset</code> it doesn't use the schema name.</p> <pre><code>import great_expectations as gx from sqlalchemy_extras.sqlalchemy_utils import get_credentials, get_connection_string # this is a set of calls to our teams functions, ...
<python><amazon-redshift><great-expectations>
2023-05-19 18:57:19
1
798
Bill
76,291,756
127,251
Read Excel file that contains Tab Characters into Pandas Dataframe
<p>I have excel files that have tab characters and newlines in the Description column.</p> <p>I am loading the files into Pandas data frames.</p> <p>My goal is to replace all sequences of special characters with a single semicolon and space, then write the data out again as CSV files.</p> <p>The generated CSV files are...
<python><pandas><excel>
2023-05-19 18:49:14
0
5,593
Paul Chernoch
76,291,627
5,057,022
Adding columns with a Map Function Pandas
<p>I have a function that takes in a series and returns a dataframe, as so:</p> <pre><code>def check_streak(x): streak = x.to_frame(name = x.name) streak[f'start_of_streak'] = streak[x.name].ne(streak[x.name].shift()) streak[f'{x.name}_streak_count'] = streak['start_of_streak'].cumsum() ...
<python><pandas>
2023-05-19 18:24:59
1
383
jolene
76,291,432
4,977,957
How to Import all Methods Under Umbrella Alias in Python
<p>I have a <code>services</code> folder which has an <code>__init__.py</code>.</p> <p>It has an <code>__all__</code> method like below:</p> <pre><code>__all__ = [ &quot;get_customer_from_foo_api&quot;, &quot;get_store_from_foo_api&quot;, &quot;get_something_else_from_foo_api&quot; </code></pre> <p>I then i...
<python><fastapi>
2023-05-19 17:52:36
0
12,814
VSO
76,291,327
8,921,867
Adding langchain library via poetry add not working
<p>I'm on poetry <code>1.5.0</code>, python version <code>3.11</code>, trying to add langchain to my poetry project. However, when running <code>poetry add langchain</code>, I'm getting the error</p> <pre><code>Using version ^0.0.174 for langchain Updating dependencies Resolving dependencies... file could not be open...
<python><python-poetry>
2023-05-19 17:34:12
3
2,172
emilaz
76,291,270
4,439,019
Incrementing ISO date by 5 days
<p>I am working with a date format that looks like this:</p> <pre><code>2023-04-25T16:00:00+00:00 </code></pre> <p>I want to add 5 days to the <code>current_date</code> and return the same format as above</p> <p>I tried this:</p> <pre><code>from datetime import datetime, timedelta today = datetime.now() iso_date = tod...
<python><datetime>
2023-05-19 17:23:18
2
3,831
JD2775
76,291,190
9,730,862
Easiest way to override PosixPath in hydra
<p>Consider the following yaml file for hydra config:</p> <pre class="lang-yaml prettyprint-override"><code>a: b: !!python/object/apply:pathlib.PosixPath - /my/path/to/dir </code></pre> <p>How would I override <code>a.b</code> so that is stays <code>PosixPath</code> after providing a new path?</p> <p>Running<...
<python><fb-hydra><omegaconf>
2023-05-19 17:11:40
1
2,061
Proko
76,291,171
9,308,052
How to secure my Google Cloud Function (gen 2, pythong 3.11) for access only through my web app and iOS app?
<p>I have a python function running on Google Cloud (gen 2). I'm calling the function from my iOS app (using URLSession on Swift) and web app (using axios on JavaScript) as a regular REST API. Initially, I had trouble accessing it so I set the flag <code>--allow-unauthenticated</code> when deploying using gcloud CLI. N...
<python><swift><authentication><google-cloud-platform><google-cloud-functions>
2023-05-19 17:08:29
1
1,848
Mohammed Imthathullah
76,290,938
4,020,435
How to document private attributes of a Python class in Sphinx
<p>I'd like to add descriptions of private attributes of a Python class to the Sphinx doc string of that class for code readability, but I'd like the auto generated doc to not show those attributes. Can I do this?</p> <p>For example, if I have a class &amp; doc string like this:</p> <pre><code>class Foo: ''' My class d...
<python><python-sphinx><docstring>
2023-05-19 16:31:51
1
678
Fijoy Vadakkumpadan
76,290,827
1,971,246
Grouping and Summing Multiple Columns in Pandas
<p>I have a large dataset that is similar in structure to this:</p> <p><a href="https://i.sstatic.net/rJ2Yp.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/rJ2Yp.png" alt="enter image description here" /></a></p> <p>I am trying to get an ouput that groups and sums by customer and metal like this:</p> <p>...
<python><pandas><dataframe><group-by>
2023-05-19 16:16:05
0
415
William
76,290,771
9,687,872
Results not reproducible between runs despite seeds being set
<p>How is it possible, that running the same Python program twice with the exact same seeds and static data input produces different results? Calling the below function in a Jupyter Notebook yields the same results, however, when I restart the kernel, the results are different. The same applies when I run the code from...
<python><random><scikit-learn><random-seed>
2023-05-19 16:05:24
1
587
Dreana
76,290,745
1,471,980
how do you extract data from nested json file and create a data frame in python
<p>I have this nested json data:</p> <pre><code> { &quot;result&quot;: [ { &quot;deviceid&quot;: 33, &quot;devicename&quot;: &quot;server101&quot;, &quot;objectName&quot;: &quot;CPU&quot;, &quot;data&quot;: [ { &quot;value&quot;:0.59, &quot;rvalue&quot;:null }, { &...
<python><json><dataframe>
2023-05-19 16:01:46
5
10,714
user1471980
76,290,724
10,967,961
Nice plot of network divided into communities
<p>I have a graph of cities divided into communities with modularity for different years. Each community assignment of nodes lies in a separate dataset according to the year (e.g.community2000 for year 2000 and so on). The graph G contains nodes as follows:</p> <pre><code>{'Node': {0: 'albany', 1: 'almaty', 2: 'amsterd...
<python><plot><networkx><modularity>
2023-05-19 15:59:33
2
653
Lusian
76,290,678
1,142,881
How to automatically delegate unimplemented methods to a different class?
<p>I have a <code>class A</code> which implements method <code>x()</code> and <code>y()</code> but I also have a <code>class B</code> which implements method <code>z()</code>. Assuming there is a base <code>AbstractA</code> class. how can I detect any calls on <code>class A</code> which aren't implemented e.g. <code>z(...
<python>
2023-05-19 15:54:41
1
14,469
SkyWalker
76,290,671
11,666,502
how to do an operation on variable in flask app
<p>I have the following flask code:</p> <pre><code> def save_data(input_data): df = pd.DataFrame([input_data]) df.to_csv('out.csv') app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def index(): if request.method == 'POST': input_message = request.form['user_input'] input_tim...
<python><pandas><flask>
2023-05-19 15:53:43
0
1,689
connor449
76,290,619
12,309,386
Python memory behavior when nested dict retained/referenced but outer dict deleted and garbage collected
<p>I am trying to understand memory usage in Python in the context of nested dicts. I have the following dict:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; outer = { ... 'name': 'John Smith', ... 'books': [ ... {'name': 'The Goal', 'author': 'Goldratt'}, ... {'name': 'The Sou...
<python><memory>
2023-05-19 15:46:19
1
927
teejay
76,290,353
2,595,216
Pass python function as callback to C library
<p>I have C DLL library and I try add python interface to it. Here is header file:</p> <pre class="lang-c prettyprint-override"><code>typedef struct { unsigned int keyIdx : 8; // index of the G key or mouse button, for example, 6 for G6 or Button 6 unsigned int keyDown : 1; // key u...
<python><c><dll><ctypes>
2023-05-19 15:12:52
0
553
emcek
76,290,318
713,200
how to get data from json using python?
<p>So basically I have following json response from which I'm trying to get 1 piece of data in a for loop Here is the json response</p> <pre><code>{ &quot;RecommendSoftwareImageTypeDTOList&quot;: { &quot;id&quot;: &quot;imageReferenceType&quot;, &quot;items&quot;: [ { &q...
<python><json><python-3.x><list><dictionary>
2023-05-19 15:08:11
1
950
mac
76,290,315
5,748,138
Python script not running due to missing shareplum module but only on SQL Server Agent
<p>When I run the python script it executes without error.</p> <p>When I attempt to run it using SQL Server Agent I receive an error.</p> <p>The error is as follows...</p> <p>The error information returned by PowerShell is: ' File &quot;PYTHON FILE LOCATION AND FILENAME&quot;, line 1, in from shareplum import Si...
<python><sql><sql-server><shareplum>
2023-05-19 15:07:20
2
342
Will
76,290,269
15,637,940
Type hinting for objects in instance of child class of UserList
<p>Working with <code>Python 3.11.1</code> and <code>Pycharm 2023.1.2</code></p> <p>I wrote custom class <code>MyList</code> for storing lists using <code>collections.UserList</code>. And one more class <code>ListOfUsers</code> which inheriting of <code>MyList</code>.</p> <pre><code>from collections import UserList c...
<python><pycharm><type-hinting>
2023-05-19 15:01:33
1
412
555Russich
76,290,128
7,745,011
Is it possible to make different versions of the same pydantic basemodel?
<p><strong>Explanation of the title:</strong></p> <p>Suppose we have the following setup of pydantic models:</p> <pre><code>class ParametersA(BaseModel): param_a: str = Field( default=..., allow_mutation=False, exclude=False, description=&quot;some description.&quot;, extra={...
<python><pydantic>
2023-05-19 14:42:11
2
2,980
Roland Deschain
76,290,095
361,089
Multi-line JSON containing variables
<p>I have a python script which I am using to generate pull requests (PR). Since the PR data is large, I am trying to use <code>&quot;&quot;&quot;</code> but the issue is that the variables within the <code>&quot;&quot;&quot;</code> are not working correctly. I have searched many links especially <a href="https://stack...
<python><json>
2023-05-19 14:38:11
1
8,167
Technext
76,289,804
4,212,430
DockerFile CMD won't run Python script
<p>I have been successful building an image for a simple python script that is part of the working directory as follows:</p> <p><a href="https://i.sstatic.net/ymfVf.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/ymfVf.png" alt="enter image description here" /></a></p> <p>My <code>DockerFile</code> looks...
<python><docker><dockerfile>
2023-05-19 13:58:51
1
780
Balajee Addanki
76,289,707
5,379,182
mypy via pre-commit - Duplicate module name 'package.module.py' (and 'package\module.py')
<p>I have the following repo-structure</p> <pre><code>my-repo/ .github/ linters/ .mypy.ini .pre-commit-config.yaml mypackage/ __init__.py main.py subpackage/ __init__.py foo.py tests/ conftest.py </code></pre> <p>When I run mypy...
<python><mypy><pre-commit><pre-commit.com>
2023-05-19 13:46:52
1
3,003
tenticon
76,289,672
15,863,624
How can I visualise contents of nested dictionary in python before knowing what's inside?
<p>I'm working with data packed into nested dictionary with structure that might look like this:</p> <pre><code>outer_dict | key1 | | key11 | | | key111: value | | | key112: value | | key12: value | | key13:value | key2 | | key21: value | | key22 | | | key221: value | | | key222 | | | | key2221: value | key3 | key4 ......
<python><dataformat>
2023-05-19 13:43:01
0
453
stats_b
76,289,538
7,752,049
scaling stores duplicate data on db in Flask
<p>I am using Flask-APScheduler on my program and it works correctly but when I scale my app it stores duplicate data on database. How can I resolve this problem? I am new in Python.</p> <pre><code>scheduler = APScheduler() scheduler.init_app(app) @scheduler.task('cron', id='store-users', hour='*') def store(): # st...
<python><flask><apscheduler>
2023-05-19 13:27:14
0
2,479
parastoo
76,289,457
14,950,385
TypeError: must be real number, not c_ulonglong
<p>I'm trying to control my laptop fan speed using WMI in python. The <a href="https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/setspeed-method-in-class-cim-fan" rel="nofollow noreferrer">documentation</a> says the input is uint64:</p> <blockquote> <pre><code>uint32 SetSpeed( [in] uint64 DesiredSpeed ); ...
<python><wmi><ctypes><win32com>
2023-05-19 13:18:25
2
2,695
Ali Ent
76,289,435
800,735
In gRPC Python, do keepalives need to acquire the GIL?
<p>In gRPC Python, are the keepalives pings(<a href="https://github.com/grpc/grpc/blob/master/doc/keepalive.md" rel="nofollow noreferrer">https://github.com/grpc/grpc/blob/master/doc/keepalive.md</a>) executed by a Python thread or by some other mechanism (C thread)? If the GIL was unavailable (for example, due to Pybi...
<python><grpc><pybind11><grpc-python><gil>
2023-05-19 13:16:03
1
965
cozos
76,289,401
2,065,691
When do I need np.frompyfunc?
<p>Please, consider the following code below:</p> <pre><code>import numpy as np def one_plus_square(x): return 1+x**2 one_plus_square_vectorized = np.frompyfunc(one_plus_square,1,1) if __name__==&quot;__main__&quot;: A = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], np.float16) #Both codes below present...
<python><python-3.x><numpy><numpy-ndarray>
2023-05-19 13:11:33
1
3,249
DanielTheRocketMan
76,289,322
3,781,009
Selecting python interpreter in VSCode
<p>I am using VSCode with ArcGIS Pro 3.0 in a virtual environment. Until yesterday, everything worked just fine. After updating to Pro 3.0, I was still able to use open a script and then have it run in the terminal window.</p> <p>Previously, I was able to select a line from the script, run it, and then it would open th...
<python><visual-studio-code>
2023-05-19 13:00:52
3
1,269
user44796
76,289,313
8,832,641
Excel and Pandas - column should be read as string instead of double/float/int
<p>I have an excel file with column like below.</p> <pre><code>A &lt;NA&gt; &lt;NA&gt; 11234 11222 11456 </code></pre> <p>The numbers in above column are stored as text in excel.</p> <p>When reading this excel to pandas dataframe, the above column gets converted to gets converted to double automatically based on the d...
<python><pandas><excel>
2023-05-19 12:59:49
0
1,117
Padfoot123
76,288,966
1,803,007
Sending control characters to LCD over serial
<p>I have code that I used to write to an LCD screen in <code>Python 2</code>, it worked fine. I could control things like cursor, colour, brightness, display the text I need and update it. I've since converted my code to <code>python 3</code> and that has broken things, the screen has the correct text but a lot of gib...
<python><python-3.x><serial-port><lcd>
2023-05-19 12:14:48
1
6,024
Paul
76,288,935
2,577,122
Mouse hover on plotly graph doesn't show any content when the content is large and doesn't fit in the screen
<p>Below is my input data (this is ONLY a simpler sample of the actual data, the actuall data is much BIG)</p> <pre><code>LOG_NAME,DATETIME,LOG_CONTENT Server1.log,2023-03-19T06:39:52,Server1 Log Line1 Server1.log,2023-03-19T06:47:20,Server1 Log Line2 Server1.log,2023-03-19T07:45:15,Server1 Log Line3 Server1.log,2023-0...
<python><python-3.x><charts><plotly>
2023-05-19 12:10:39
0
307
Swap
76,288,642
1,118,630
remove the sparse text from the edge of an image
<p>I have a scanned image which has some text (the two <code>B</code>s) from the edge (left or right side of the image) I'd like to remove.</p> <p><a href="https://i.sstatic.net/b3ZOM.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/b3ZOM.jpg" alt="scanned image" /></a> Below is the code I have tried:</p>...
<python><opencv><image-processing>
2023-05-19 11:31:27
1
1,030
jonah_w
76,288,496
2,749,397
suptitle and title are still misaligned, coordinates conversion notwithstanding
<p>What is my misunderstanding?</p> <p>I know that something is wrong not only because of the misalignment, but also because <code>x</code> doesn't change when I, e.g., use <code>ax.set_ylabel('x\ny\nz')</code>: <code>x</code> always equals <code>0.5125</code> aka 41/80.</p> <pre><code>import matplotlib.pyplot as plt ...
<python><matplotlib>
2023-05-19 11:11:10
1
25,436
gboffi
76,288,488
19,480,934
Error when using Streamlit and Langchain to build an online AutoGPT app
<p>I get this error when trying to use LangChain with Streamlit to build an online AutoGPT app.</p> <pre><code>input to Terminal: streamlit run /Users/*username*/opt/anaconda3/lib/python3.9/site-packages/ipykernel_launcher.py returns: Traceback (most recent call last): File &quot;/Users/*username*/.pyenv/versions/...
<python><streamlit><chatgpt-api><langchain><autogpt>
2023-05-19 11:09:57
1
539
Lakeside52
76,288,443
5,183,473
Scipy least_square with jacobian
<p>I am trying to replicate a camera calibration optimization using scipy.</p> <p>The algorithm work fine without jacobian (the optimization converges towards optimal results). Yet, when adding the jacobian function, the least-square function barely iterates and stops without converging.</p> <pre class="lang-py prettyp...
<python><scipy><camera-calibration>
2023-05-19 11:02:25
1
372
AlixL
76,288,409
4,575,197
How to allow (accept) multiple Date formats?
<p>I have some Date formats that i can accept <strong>YYYYMMDDHHMMSS</strong> or <strong>YYYYMMDDHHMM</strong> or <strong>YYYYMMDDHH</strong> or <strong>YYYYMMDD</strong>. I want to check if the Date is in these formats, otherwise print an Error message or catch some error. I tried the achieving this using RegEx. It go...
<python><oop><datetime-format><python-datetime><gdelt>
2023-05-19 10:58:49
1
10,490
Mostafa Bouzari
76,288,357
19,995,658
How to find visual similarities between String in python
<p>I'm currently using Pytesseract to read image and extract usernames from it</p> <p>Then I need to compare this string with a list of String I have (containing every possible username)</p> <p>My problem is that sometime tesseract reads the word wrong, (example, poce instead of pocc) because e and c look similar</p> <...
<python><python-3.x>
2023-05-19 10:51:54
0
968
Sparkling Marcel
76,287,971
5,947,182
csv.DictReader prints out only obj
<p>For some reason the following code <strong>only prints out <code>&lt;csv.DictReader object at 0x7f2ee79531c0&gt;</code></strong>. This is what states on the Python official website but for some reason it doesn't work here, neither with data = <code>csv.DictReader(file)</code> nor data = <code>csv.DictReader(file, ...
<python><csv><dictionary>
2023-05-19 09:56:50
1
388
Andrea
76,287,668
15,520,615
Reading / Extracting Data from Databricks Database (hive_metastore ) with PySpark
<p>I am trying to read in data from Databricks Hive_Metastore with PySpark. In screenshot below, I am trying to read in the table called 'trips' which is located in the database <code>nyctaxi</code>.</p> <p>Typically if this table was located on a AzureSQL server I was use code like the following:</p> <pre><code>df = s...
<python><pyspark><apache-spark-sql><azure-databricks>
2023-05-19 09:16:29
2
3,011
Patterson
76,287,574
11,452,928
Are python lists created in a function memorized on the stack memory? Is it safe to return them?
<p>I'm working in Python. I have the following function:</p> <pre><code>def f(list_value: list): a = numpy.zeros(5) b = numpy.zeros(4) list_value.append(a) list_value.append(b) </code></pre> <p>and I use it as follows:</p> <pre><code>list_value[] f(list_value) a = list_value[0] b = list_value[1] </code>...
<python><numpy>
2023-05-19 09:03:11
1
753
fabianod
76,287,474
4,913,254
Identify columns with identical values and iterate over a column saving changes in the original table
<p>I have a data frame like this</p> <pre><code> Chr Start Ref Alt Revel_Score RefSeq CHR BP SNP P 21 9 133710834 A C 0.429 NM_005157.6 9 133710834 1 0.571001 22 9 133710834 A G 0.424 NM_005157.6 9 133710834 1 0.576001 23 9 133710834 A T 0.432 NM_005157.6 9 13371083...
<python><pandas>
2023-05-19 08:49:05
1
1,393
Manolo Dominguez Becerra
76,287,447
4,718,423
patch method that uses external library method calls
<p>The foo class links the external library to an atribute so I can use self.external_class.externalClassMethod. But to do testing, I need to patch out this method call so I can continue testing the rest of the method. I have tried everything in the @patch decorator, nothing worked :(</p> <pre><code>import os from uni...
<python><unit-testing><mocking>
2023-05-19 08:46:20
1
1,446
hewi
76,287,249
713,200
How to delete a item in list based on partial search string in python?
<p>I have a list of elements lets say</p> <pre><code>images = ['fcs-apple-5.5.4','gcs-banana-0.6.4','tf-2', 'mvc-grape-3.4.2'] </code></pre> <p>basically I want to delete the item that has a sub-string <code>grape</code>, so I will pass grape as <code>input</code> and look for the item matching <code>grape</code>. so ...
<python><python-3.x><string><list><for-loop>
2023-05-19 08:17:02
2
950
mac
76,286,927
14,994,712
Python hash() function not distributing uniformly?
<p>I am experiencing an odd behavior with python's built-in <code>hash()</code> function. I am writing hashes of strings (which come from various language/text datasets) into 900 different files, according to the first three digits of their hash values. Now I noticed that all files up to 921 tend to have very similar s...
<python><hash><dataset><hashtable><hashcode>
2023-05-19 07:31:29
1
473
joinijo
76,286,340
3,878,377
All the values of column are float but the column data type is object
<p>I have a dataframe which has no NAN (or any sort of missing values) and all the values in a column are numerics. When I check data type of each row for that column I get float but the data type of the overall column is object.</p> <p>I have looked at other similar problems but did not get any clear answer.</p> <p>Pr...
<python><pandas><types>
2023-05-19 05:56:36
2
1,013
user59419
76,286,283
11,741,232
Poetry using wrong Python version and wrong virtual environment
<p>I am on Windows. I have made a virtual environment with Python 3.9.0 called venv in my current directory. I have activated it. If I run python --version I get 3.9.0:</p> <p><a href="https://i.sstatic.net/4JbXO.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/4JbXO.png" alt="enter image description here...
<python><virtualenv><python-poetry>
2023-05-19 05:44:23
0
694
kevinlinxc
76,286,212
7,213,452
Pyrogram: Get detailed Chat media permissions (Can send stickers, Can send videos)
<p>Telegram client has rich Chat media permissions (Can send stickers, Can send videos, etc). How can I check if stickers, images or videos can be sent in chat using Pyrogram?</p>
<python><telegram><pyrogram>
2023-05-19 05:27:02
1
321
Serhiy Pustovit
76,286,097
5,302,323
Yfinance API for FX rates no longer working on Python
<p>I have a simple line of code that seems to no longer be working with the yfinance API.</p> <p>I am 99% sure that this used to work. Could you please tell me why it does not work anymore?</p> <pre><code>import yfinance as yf import pandas as pd # define GBP as the base currency base_currency = 'GBP' # create a list...
<python><yfinance>
2023-05-19 04:56:02
1
365
Cla Rosie
76,286,028
5,695,336
How to cancel all tasks in a TaskGroup
<pre><code>import asyncio import random task_group: asyncio.TaskGroup | None = None async def coro1(): while True: await asyncio.sleep(1) print(&quot;coro1&quot;) async def coro2(): while True: await asyncio.sleep(1) if random.random() &lt; 0.1: print(&quot;dead&qu...
<python><python-asyncio>
2023-05-19 04:35:59
3
2,017
Jeffrey Chen
76,285,998
1,354,514
This code always predicts a "period" as the next text sequence
<p>I am trying to learn how to use the transformers library to make predictions on the next word given a sentence. My code always predicts a &quot;period&quot; as the next token. Can someone help me see what I am doing wrong?</p> <pre><code>import torch from transformers import DistilBertTokenizer, DistilBertForMaske...
<python><machine-learning><nlp><huggingface-transformers><distilbert>
2023-05-19 04:25:54
2
1,923
steve landiss
76,285,982
3,198,281
TFLite could not broadcast input array from shape (96,96) into shape (96,96,1)
<p>I have built a tensorflow lite model using 3 sets of 96x96px grayscale jpgs using Google's Teachable Machine, then exported the model in tflite format. When I attempt to run a prediction on a new 96x96px grayscale image I get the error:</p> <blockquote> <p>ValueError: could not broadcast input array from shape (96,9...
<python><tensor><tensorflow-lite><tflite><teachable-machine>
2023-05-19 04:23:01
0
1,910
UltrasoundJelly
76,285,838
1,243,255
bs4 won't find urls on ercot.com site
<p>I need to extract all url from the Elements which you can see by right clicking on chrome and doing inspect.</p> <pre><code>url = fr'https://www.ercot.com/mp/data-products/data-product-details?id=NP6-788-CD' </code></pre> <p>The url displayed on the right is seen when you do inspect on zip on left in following image...
<python><web-scraping><beautifulsoup><python-3.8>
2023-05-19 03:35:27
1
4,837
Zanam
76,285,824
10,532,894
HTTPX RESPX Pytest TypeError: Invalid type for url. Expected str or httpx.URL, got <class 'tuple'>:
<p>I have a function in my Python class that works fine when I use it in my other <code>.py</code> file.</p> <pre><code>@exception_handler def get_all_workspaces(self) -&gt; Union[WorkspacesModel, GSResponse]: Client = self.http_client responses = Client.get(f&quot;workspaces&quot;) if responses.status_code...
<python><pytest><httpx>
2023-05-19 03:31:50
1
461
krishna lodha
76,285,818
7,408,143
How to encode a solidity struct in python?
<p>I have in solidity:</p> <pre><code>struct MyStruct { string data; address issuer; } function getHash(MyStruct calldata myStruct) public pure returns (bytes32) { return keccak256(abi.encode(myStruct)); } </code></pre> <p>and in python:</p> <pre><code>from eth_utils import keccak from eth_abi import encod...
<python><encoding><solidity>
2023-05-19 03:29:57
1
1,075
J3STER
76,285,715
1,232,087
Delete multiple assets of Microsoft Purview using REST API
<p>We did a <code>Purview Scan</code> of an <code>Azure SQL Database</code>. Now many of the SQL tables have been dropped from the database. But those assets (tables in Purview) are still in <code>Purview</code>. We want to delete those assets using a <code>REST API</code>.</p> <p>Using <a href="https://github.com/wjoh...
<python><azure-rest-api><azure-purview><apache-atlas>
2023-05-19 02:54:00
1
24,239
nam