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,204,868
21,420,742
Finding differences in values with strings in Python
<p>I am trying to create a new column that will describe when someone is a manager or a stand in while a manager is away.</p> <p>DF</p> <pre><code> ID Name Emp_Level 101 Adam Emp 102 Betty Mgr 103 Chris(Stand in) Mgr 104 Dave ...
<python><python-3.x><pandas><dataframe><numpy>
2023-05-08 22:53:27
3
473
Coding_Nubie
76,204,704
13,119,730
FastAPI get exception stacktrace
<p>I have a problem with my Exception handler in my FastAPI app. Here's my current code:</p> <pre><code>@app.exception_handler(Exception) async def server_error(request: Request, error: Exception): logger.error(f&quot;Internal server error: {error} \n{traceback.format_exc()}&quot;) return JSONResponse( ...
<python><exception><logging><fastapi><stack-trace>
2023-05-08 22:15:07
0
387
Jakub Zilinek
76,204,675
8,849,755
Changing colorbar title angle in plotly
<p>Consider the following code taken from <a href="https://plotly.com/python/heatmaps/" rel="nofollow noreferrer">the documentation</a></p> <pre class="lang-py prettyprint-override"><code>import plotly.express as px data=[[1, 25, 30, 50, 1], [20, 1, 60, 80, 30], [30, 60, 1, 5, 20]] fig = px.imshow(data, ...
<python><plotly>
2023-05-08 22:08:37
1
3,245
user171780
76,204,615
11,141,816
Python md5 same image files with different md5
<p>From <a href="https://stackoverflow.com/questions/16874598/how-do-i-calculate-the-md5-checksum-of-a-file-in-python">How do I calculate the MD5 checksum of a file in Python?</a> , I wrote a script to remove the duplicate files in the folder <code>dst_dir</code> with md5. However, for many files(.jpg and .mp4), the md...
<python><md5><hashlib>
2023-05-08 21:55:04
0
593
ShoutOutAndCalculate
76,204,576
15,569,921
Filtering on the positive values in scatterplot
<p>Imagine a nested dictionary, where the first level is the dates, and the second level dictionary has the number as keys and the value corresponding to that number as values. I want to do a scatterplot on the positive <strong>values</strong> of each date without losing the dates as the x-axis. What I mean is that if ...
<python><dictionary><matplotlib><filter>
2023-05-08 21:48:22
4
390
statwoman
76,204,504
5,424,117
Django Custom API Endpoint with two parameters
<p>I want to build a fairly simple API endpoint in a Django app I inherited.</p> <p>I'm new to python and Django</p> <p>The app uses views.py with classes that extend ModelViewSet.</p> <p>It also uses a urls.py with entries like this:</p> <pre class="lang-py prettyprint-override"><code>router.register('agent_licenses',...
<python><django><django-rest-framework><django-views>
2023-05-08 21:33:01
2
2,474
jb62
76,204,225
17,101,330
Python Kivy cannot use Video Player ffpyplayer ignored
<p>I am building my first app with kivy but cannot make the VideoPlayer work.</p> <p>There is a error-message stating: <strong>Provider: ffpyplayer(['video_ffmpeg'] ignored)</strong> which seems to be the problem.</p> <p>I have already installed ffpyplayer (aswell as Pillow) using pip install.</p> <p>When I type:</p> <...
<python><kivy><video-player>
2023-05-08 20:40:31
1
530
jamesB
76,204,154
1,123,336
Passing keyword arguments to NumPy __array__ functions
<p>In the past, a few questions have asked for help when getting the following exception:</p> <pre><code>TypeError: __array__() takes 1 positional argument but 2 were given </code></pre> <p>These have usually been in the context of using another package, in which the <code>__array__</code> function has been defined wit...
<python><numpy><numpy-ndarray>
2023-05-08 20:28:10
2
582
Ray Osborn
76,204,004
5,507,389
Unpacking dictionary in for loop with indeces
<p>I have the following code which iterate over a dictionary to unpack its values:</p> <pre><code>my_dict = {&quot;brand&quot;: &quot;A&quot;, &quot;product&quot;: [&quot;X&quot;, &quot;Y&quot;, &quot;Z&quot;], &quot;color&quot;: [&quot;red&quot;, &quot;green&quot;, &quot;blue&quot;]} def my_fnc(product, index): ...
<python><loops><dictionary>
2023-05-08 20:02:57
2
679
glpsx
76,203,943
13,741,789
Running a dash app from multidirectory structure
<p>I seem to have trouble running dash/(probably also flask?) apps from a multiple directory structure with python.</p> <p>Basically I have a large dash app I'm writing which would be annoying to maintain if everything was in one giant &quot;app.py&quot; file. I'd like to have a few folders to organize types of visuali...
<python><flask><plotly-dash>
2023-05-08 19:53:40
1
312
psychicesp
76,203,925
3,413,699
Custom Logging Module not working in Python
<p>I want to use same logging mechanism in all python scripts. Developed a class below class:</p> <p>File Name: ms_logging.py</p> <pre><code>import logging class ms_logging: @staticmethod def logging(): logging.basicConfig( level=logging.DEBUG, format='%(asct...
<python><logging><python-logging>
2023-05-08 19:49:53
1
478
Milon Sarker
76,203,884
8,032,148
Inconsistent Flask request behavior
<p>I have a simple flask app that receives an encoded json file in a url, prints it out and imports it in to a dictionary object my_dict:</p> <pre><code>from flask import request import json @app.route('/test', methods=['POST', 'GET']) def test: rqa = request.args.get('data', '') print(rqa) my_dict = json.loads(...
<python><flask><aws-lambda>
2023-05-08 19:42:32
1
314
FarNorth
76,203,575
14,676,485
How to extract first value from each array-like element in column?
<p>I have a column with single elements as well as array-like elements but I don't think it looks like an array:</p> <p><a href="https://i.sstatic.net/fxcse.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/fxcse.png" alt="enter image description here" /></a></p> <p>I need to extract first value from this ...
<python><pandas>
2023-05-08 18:57:45
0
911
mustafa00
76,203,482
21,420,742
Creating a column that indicates when a change in values happens by ID
<p>I know this is simple but I am having a little trouble trying to see when someone switche s roles. df</p> <pre><code> ID Date Job 101 05/2022 Sales 101 06/2022 Sales 102 12/2021 Tech 102 1/2022 Tech 102 2/2022 Finance 103 4/2022 HR 103 ...
<python><python-3.x><pandas><dataframe><group-by>
2023-05-08 18:45:39
4
473
Coding_Nubie
76,203,454
653,379
Correctly sort RSS items by time
<p>I'm getting RSS items from different RSS channels. And I'd like to sort them correctly by time and take into account the time zone, from the latests to the oldests. So far, I have the following code:</p> <pre><code>import feedparser import dateutil.parser rss_channels = [ &quot;https://www.novinky.cz/rss&quot;,...
<python><time><timezone><rss><feedparser>
2023-05-08 18:42:25
1
3,742
xralf
76,203,356
17,243,835
Plotly - Use custom Font
<p>I am trying to use a custom installed font in Plotly, specifically Plotly Express, however my fonts do not seem to be recognized by Plotly.</p> <p>My font is being recognized by Tkinter:</p> <pre><code>from tkinter import Tk, font root = Tk() print(font.families()) </code></pre> <p>Output:</p> <pre><code> ('System',...
<python><fonts><plotly>
2023-05-08 18:28:13
0
355
drew wood
76,203,330
181,098
Backslash gets stripped from string when trying to insert into mysql column using python
<p>As per title, when I try to insert a string containing backslashes they get removed. Say I have the following statement:</p> <p>filename=&quot;D:\myfiles\log files\2022-12-05 11-33-31.dat&quot;</p> <p>then I insert it into my MySQL table with the following:</p> <pre><code> sql=&quot;INSERT INTO df_log (log_fi...
<python><mysql>
2023-05-08 18:24:08
0
3,367
Hein du Plessis
76,203,293
183,315
Presenting an unnamed query_string parameter in OpenAPI docs using FastAPI
<p>I'm building a Python 3.10.9 FastAPI application. On my, HTTP GET single resource API endpoints, I'm accepting multiple query string elements, like this small sample:</p> <pre><code>amount__gt=1000&amp;start_date__lt=2023-05-10 </code></pre> <p>To get a query_string placeholder on the OpenAPI docs created by FastAPI...
<python><fastapi><query-string>
2023-05-08 18:20:38
1
1,935
writes_on
76,203,192
7,097,192
Stop a list in Python being shared between function invocations when multiprocessing
<p>I'm passing a function into a queue for parallel processing via <code>multiprocessing</code>, and that function takes 2 lists as inputs. I'm doing this in a loop 6 times, where each time I append the loops counter to the end of the list (see output section below). I would have expected each list to be a unique loc...
<python><list><multiprocessing><queue><python-multiprocessing>
2023-05-08 18:06:35
0
781
Shahad
76,203,141
5,959,685
Pandas rowwise partial matching with any item from a list
<p>I am trying to do a rowwise partial match in pandas dataframe so that if any of the terms from a list matches any word from a column. For example, I have a dataframe df_x</p> <pre><code> name terms_list 0 acupuncturist [acupuncturist, acupuncture] 1 seafood restaurant [...
<python><pandas><dataframe>
2023-05-08 17:59:27
4
423
Dutt
76,203,128
14,963,549
How to translate a query executed by a cursor in a pandas data frame? (Databricks)
<p>I've got a script that executes a query by a cursor in SQL (this is the only way to make a query in that Data base). I've to analyse its data, unfortunately it's so hard to make it with a cursor, I've tried to translate it into a pandas data frame but I've couldn't. The script is as follow:</p> <pre><code>from datab...
<python><sql><pandas><dataframe><databricks>
2023-05-08 17:57:52
1
419
Xkid
76,202,975
1,187,968
GLIBC_2.28 not found in Docker image amazonlinux
<p>I am using docker image <code>amazonlinux</code> to build my aws-lambdas in Python. Now, I'm getting the following build error.</p> <pre><code>/lib64/libc.so.6: version `GLIBC_2.28' not found </code></pre> <p>It was triggered by the Python <code>cryptography</code> package. I can do version locking <code>cryptograph...
<python><linux><amazon-web-services><docker>
2023-05-08 17:36:29
0
8,146
user1187968
76,202,829
4,879,688
Why there is no speed benefit of in-place multiplication when returning a numpy array?
<p>I have defined two functions as a minimal working example.</p> <pre><code>In [2]: A = np.random.random(10_000_000) In [3]: def f(): ...: return A.copy() * np.pi ...: In [4]: def g(): ...: B = A.copy() ...: B *= np.pi ...: return B </code></pre> <p>Both of them return the same result...
<python><numpy><performance><optimization><augmented-assignment>
2023-05-08 17:15:04
1
2,742
abukaj
76,202,643
14,790,056
Total time elapsed between the first fund addition and fund withdrawal
<p>I have the following dataframe:a positive value of LIQUIDITY_adj means fund addition and negative implies withdrawal. I want to compute time elapsed between the first liquidity addition until the whole funds are withdrawn.</p> <pre><code> BLOCK_TIMESTAMP NF_TOKEN_ID LIQUIDITY_adj LIQUIDITY_cumsum 0 2021-05-04...
<python><pandas><dataframe>
2023-05-08 16:49:12
1
654
Olive
76,202,551
11,475,651
Converting a JSON to a Pandas data frame in Python: why is it not working?
<p>I am trying to get a very straightforward bit of information from an API released by NREL (the National Renewable Energy Lab in the US):</p> <p><a href="https://developer.nrel.gov/docs/transportation/alt-fuel-stations-v1/all/" rel="nofollow noreferrer">https://developer.nrel.gov/docs/transportation/alt-fuel-stations...
<python>
2023-05-08 16:38:12
2
317
Abed
76,202,535
9,328,846
How to replace character in the index column of a Pandas Dataframe
<p>I have the following code piece:</p> <pre><code>d = {'col1': [0, 1, 2, 3], 'col2': [&quot;AAAD&quot;, &quot;BBC&quot;, &quot;KLMA&quot;, &quot;ABC&quot;]} df = pd.DataFrame(data=d) df </code></pre> <p>Output:</p> <pre><code> col1 col2 0 0 AAAD 1 1 BBC 2 2 KLMA 3 3 ABC </code></p...
<python><python-3.x><pandas><dataframe>
2023-05-08 16:35:18
1
2,201
edn
76,202,510
9,430,855
dictionary to "long" dataframe
<p>Is it possible to take a dictionary and transform it into a &quot;long&quot; dataframe in polars? basically have input that looks like</p> <pre><code>input_ = {&quot;a&quot;: 1, &quot;b&quot;: 2, &quot;c&quot;: 3} </code></pre> <p>and I want output like</p> <pre><code>┌───────┬───────┐ │ col_0 ┆ col_1 │ │ --- ┆ --...
<python><dataframe><python-polars>
2023-05-08 16:32:08
2
3,736
dave-edison
76,202,488
11,246,056
"MockerFixture" has no attribute "assert_called_once" [attr-defined]
<p>In <code>module.py</code>, I have:</p> <pre class="lang-py prettyprint-override"><code>def func(x: int) -&gt; str | None: if x &gt; 9: return &quot;OK&quot; return None def main(x: int) -&gt; str | None: return func(x) </code></pre> <p>In <code>test_module.py</code>, I have:</p> <pre class="lan...
<python><pytest><mypy><python-typing><pytest-mock>
2023-05-08 16:28:51
1
13,680
Laurent
76,202,360
10,133,797
Why is complex conjugation so slow?
<p>It's on par with complex multiplication, which boggles my mind:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np def op0(x): return np.conj(x) def op1(x0, x1): return x0 * x1 def op2(x0, x1): x0[:] = x1 for N in (50, 500, 5000): print(f&quot;\nshape = ({N}, {N})&quot...
<python><numpy><performance>
2023-05-08 16:09:18
3
19,954
OverLordGoldDragon
76,202,346
3,453,901
Recommended approach for retrieving rotating RDS credentials stored in Secrets Manager for python web app?
<p>I have a <code>flask</code> app running on <code>ECS</code> with <code>EC2 instance type</code> that accesses a <code>RDS</code> database. I'm storing the database credentials in <code>Secrets Manager</code>. I'd like to enable the built-in rotation provided by <code>Secrets Manager</code>, but I'm unsure about the ...
<python><amazon-web-services><flask><aws-secrets-manager>
2023-05-08 16:07:11
2
2,274
Alex F
76,202,342
13,488,243
works in postman but python request failing error":"Invalid access token
<p>scratching my head around this simple code giving error 401:invalid access token. could it be due to some endpoint security software tampering the request? code is actually generated by postman, believe no issue with it!</p> <pre><code> import requests url = &quot;&lt;url&gt;&quot; payload = {} head...
<python><client>
2023-05-08 16:07:00
2
459
uman dev
76,202,255
2,451,520
How can I reenable the warning about unsupported Python version by VS Code debugger
<p>I'm using Visual Studio Code 1.78.0 and version v2023.8.0 of the Python extension on Windows 10. When I tried to debug an old project requiring Python 2.7.13 (provided by a virtual environment), I got a warning saying <em>The debugger in the python extension no longer supports python version minor than 3.7</em>. I s...
<python><visual-studio-code><debugging><windows-10>
2023-05-08 15:56:51
1
353
maf
76,202,002
3,136,710
turtle.TurtleGraphicsError: bad color sequence
<p>I'm getting a colorfill error for my Python turtle graphics code, but I don't understand why. The method <code>t.fillcolor()</code> should accept 3 values as the r,g,b values for the fillcolor of a turtle shape, where <code>t</code> is a turtle. However, any three values in the method produce an error.</p> <p>This i...
<python><turtle-graphics><python-turtle>
2023-05-08 15:23:00
1
652
Spellbinder2050
76,201,908
1,082,349
Serializing, compressing and writing large object to file in one go takes too much memory
<p>I have a list of very large objects <code>objects</code>, that I want to compress and save to the hard drive.</p> <p>My current approach is</p> <pre><code>import brotli import dill # serialize list of objects objects_serialized = dill.dumps(objects, pickle.HIGHEST_PROTOCOL) # compress serialized string objects_seria...
<python><dill><brotli>
2023-05-08 15:09:45
1
16,698
FooBar
76,201,871
14,468,588
How to speed up implementation of my Code executing a complex formula in python
<p>I have implemented a complex problem in python. In fact, My code does not have any error. Here is my code (if it seems too long, you can skip it. in last part of question, I have mentioned a short part in my code that I think it makes the simulation time-consuming):</p> <pre><code>from random import uniform import n...
<python><runtime><genetic-algorithm>
2023-05-08 15:06:25
0
352
mohammad rezza
76,201,836
11,278,478
list S3 files in Pyspark
<p>I am new to Pyspark and trying to use spark.read method to read S3 files in dataframe. I was able to successfully read one file from S3. Now I need to iterate and read all the files in a bucket.</p> <p>My question is how to iterate and get all the files one by one.</p> <p>I used to do this in in Python using boto3, ...
<python><apache-spark><amazon-s3><pyspark><boto3>
2023-05-08 15:02:37
4
434
PythonDeveloper
76,201,745
7,053,813
How do I use a protocol for an attribute that shows up after running a method?
<p>I am working on a package that intimately uses scikit-learn objects. I wanted to use a protocol to identify the interface for certain aspects of sklearn functionality. One example is that an object when the <code>fit</code> method is run gains an attribute called <code>feature_names_in_</code>. However, it does not ...
<python><python-typing>
2023-05-08 14:51:33
1
759
Collin Cunningham
76,201,672
15,001,463
Single SciPy CSR Matrix from Large Dask Array
<p>I have a sparse dask array with 200k rows and 150k columns. I want to convert this sparse dask array into a <strong>single</strong> scipy sparse CSR matrix for use with collaborative filtering models from the <a href="https://github.com/benfred/implicit" rel="nofollow noreferrer">implicit</a> library. How can I do t...
<python><dask><sparse-matrix>
2023-05-08 14:42:20
1
714
Jared
76,201,572
16,383,578
How to deal with overlapping IP ranges in Python?
<p>I have downloaded the raw text file of IPFire location database from <a href="https://git.ipfire.org/?p=location/location-database.git;a=tree" rel="nofollow noreferrer">here</a>, I tried to convert the data to a sqlite3 database and I succeeded in doing so.</p> <p>However there are lots of overlapping IP ranges, and...
<python><python-3.x><algorithm>
2023-05-08 14:30:30
1
3,930
Ξένη Γήινος
76,201,512
3,729,714
Python - Variable won't print? (Trying to get variable outside of while/if, etc.)
<p>I have this code:</p> <pre><code>global dir_name dir_name = '' def generateDirectoryName(newpath, x=0): while True: dir_name = (newpath + ('_' + str(x) if x != 0 else '')).strip() if not os.path.exists(dir_name): os.mkdir(dir_name) #1 #print(dir_name) ...
<python>
2023-05-08 14:22:25
1
1,735
JM1
76,201,369
1,624,552
How can I get the commit where the head is pointing to?
<p>My Git HEAD is pointing to a commit that is not the last one committed so I would like to get that commit. Is it possible through the GitLab API? If so how can I do it from Python or a curl command?</p> <p>In case GitLab does not provide any mechanism to do so, how can I do it using a Git command from Python?</p>
<python><git><gitlab><gitlab-api>
2023-05-08 14:05:34
0
10,752
Willy
76,201,333
5,002,658
How can time spent in asynchronous generators be measured?
<p>I want to measure a time spent by generator (time blocking main loop).</p> <p>Lets say that I have two following generators:</p> <pre><code>async def run(): for i in range(5): await asyncio.sleep(0.2) yield i return async def walk(): for i in range(5): time.sleep(0.3) yie...
<python><python-3.x><python-asyncio><generator>
2023-05-08 13:59:54
2
340
Artur Laskowski
76,201,183
4,495,790
How to forecast with FB's Prophet with one common model for multiple users' time series data?
<p>I have the following (Pandas) data frame with daily records of purchase amounts (<code>y</code>) of different users (<code>user_id)</code> with other independent features (<code>v1, v2</code>) like this:</p> <pre><code>ds user_id v1 v2 y 2013-01-01 00:00:00 user00 6 100 8 2013-01-01 00...
<python><forecasting><facebook-prophet>
2023-05-08 13:41:06
0
459
Fredrik
76,201,055
610,569
How to skip bad lines when loading csv/tsv file in HuggingFace dataset? ParserError: Error tokenizing data
<p>Sometimes the default csv engine setup in the Python and/or pandas environment raises errors on bad line, e.g.</p> <pre><code>dataset = load_dataset(&quot;alvations/aymara-english&quot;) </code></pre> <p>[out]:</p> <pre><code>--------------------------------------------------------------------------- ParserError ...
<python><pandas><csv><huggingface-datasets>
2023-05-08 13:25:19
1
123,325
alvas
76,200,996
2,606,240
Pylance showing error for @classmethod which works during execution
<p>The following code works exactly as expected:</p> <pre><code>from abc import ABCMeta from typing import Dict, Any class Singleton(ABCMeta): __instances: Dict[Any, Any] = {} def __call__(cls, *args: Any, **kwargs: Any) -&gt; Any: if cls not in cls.__instances: cls.__instances[cls] = supe...
<python><pylance>
2023-05-08 13:18:17
1
681
user2606240
76,200,793
13,002,906
Unable to redirect non-www to www in django Nginx project on Digital Ocean
<p>Hello I would be grateful if someone could please help with the following Nginx configuration:</p> <p>/etc/nginx/sites-available/example</p> <pre><code>server { server_name *.example.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/admin/pyapps...
<python><django><ubuntu><nginx><digital-ocean>
2023-05-08 12:52:20
2
389
pH4nT0M
76,200,786
10,489,887
How to place images on top of each other in Python?
<p>I'm currently working on a project to save the image parts and for one part I need to combine them together and have the effect of full sweater feel.Most things work except masking. I'm creating the API basically to have combined view as image</p> <pre class="lang-py prettyprint-override"><code>from rembg import rem...
<python><image-processing><python-imaging-library>
2023-05-08 12:51:23
1
2,184
mrconcerned
76,200,707
2,835,640
Use numpy.vectorize on array of arrays
<p>How do I apply numpy.vectorize in order to have it act on an array of arrays where each array is an input to the function? For instance underneath, I am looking for the returns values to be the list [4,90]:</p> <pre><code>import numpy as np import operator import functools vidx = np.vectorize(operator.index) functo...
<python><arrays><numpy><vectorization><array-broadcasting>
2023-05-08 12:40:47
1
2,526
crogg01
76,200,674
13,102,609
How to use argument with dash in name in ffmpeg-python?
<p>Following is a simple ffmpeg command line for encoding an input video into a AV1 output with CRF 30:</p> <pre><code>ffmpeg -i input.mkv -c:v libsvtav1 -crf 30 output.mkv </code></pre> <p>Converting that command line into the syntax of <a href="https://github.com/kkroening/ffmpeg-python" rel="nofollow noreferrer">ffm...
<python><ffmpeg><video-encoding><ffmpeg-python>
2023-05-08 12:37:24
1
663
orderlyfashion
76,200,579
3,674,674
AWS Cloud Development Kit (CDK) No Container Instances were found in your cluster
<p>I want to deploy fastapi application as a service using AWS Elastic Container Service of type EC2. While deploying application, it is raising error <em><strong>No Container Instances were found in your cluster</strong></em>. Here is code for Cloud Development Kit using Python.</p> <pre><code>from pathlib import Path...
<python><amazon-web-services><aws-cdk>
2023-05-08 12:24:28
1
1,612
c__c
76,200,535
21,346,793
How to call an a callbacks when I take an a type of autorization?
<p>I have got a project, which have an autorization by vk and google. I need to call funcitions like vk_callback or google_callback when i make autorization by this types. Hoe can i do it? views.py:</p> <pre><code>def home(request): return HttpResponse('Home Page') def vk_callback(request): user_info_getter =...
<python><django>
2023-05-08 12:18:10
0
400
Ubuty_programmist_7
76,200,452
7,979,645
Error while iterating over dataframe column's entries: "AttributeError: 'Series' object has no attribute 'iteritems'"
<p>Using pandas version 2, I get an error when calling <code>iteritems</code>.</p> <pre class="lang-py prettyprint-override"><code>for event_id, region in column.iteritems(): pass </code></pre> <p>The following error message appears:</p> <pre><code>Traceback (most recent call last): File &quot;/home/analyst/an...
<python><pandas><dataframe><series><iteritems>
2023-05-08 12:07:34
1
319
jordimaggi
76,200,377
3,521,180
Why my unit test coverage is at the lower side?
<p>I have written a small class and function and unit test case for them.</p> <p>from flask_restful import Resource</p> <pre><code>class Calculator: def __init__(self, a, b ): self.a = a self.b = b def add(self): return self.a + self.b class CalcResource(Resource): def get(self): ...
<python><python-3.x><pytest><coverage.py>
2023-05-08 11:57:22
0
1,150
user3521180
76,200,256
4,336,593
Vectoring the FOR loop while computing rows of Dataframe
<p>Following is the sample dataframe:</p> <pre><code>df = pd.DataFrame({ 'time': pd.date_range(start='2023-03-15 00:00:00', periods=15, freq='1min'), 'binary': [0,0,0,0,1,0,0,0,0,1,1,1,1,1,0], 'nonbinary': np.random.randint(1, 10, 15) }) </code></pre> <p>My task is:</p> <p>To find the presence of <code>1s</...
<python><pandas><dataframe><vectorization>
2023-05-08 11:42:21
1
858
santobedi
76,200,044
1,624,552
How to check if a release exists on a GitLab repo
<p>I have a repo in GitLab and now I need to check if a release based on a tag exists using Python.</p> <p>I have tried below Python code but I always get the response &quot;301 Moved Permanently&quot; independently if release exsits or not.</p> <p>I am using Http Client instead of requests as I do not want to depend o...
<python><git><gitlab><gitlab-api><http.client>
2023-05-08 11:13:51
1
10,752
Willy
76,199,893
13,236,421
How can I use sklearn's Binarizer in a Pipeline with muliple, custom thresholds?
<p>Say I have a dataset with several features that I would like to binarize. Each feature has its own (manual) threshold. I have tried this:</p> <pre><code>import pandas as pd from sklearn.pipeline import Pipeline from sklearn.compose import ColumnTransformer from sklearn.preprocessing import Binarizer X = pd.DataFram...
<python><scikit-learn>
2023-05-08 10:57:49
1
365
Larsq
76,199,745
1,711,271
What is the best way to iterate over rows of a pandas dataframe whose elements are arrays of different length?
<p>I have a weird dataframe, where each row contains numpy arrays of different length from row to row. Below an example (actual df has more columns and waaaay more rows):</p> <pre><code>import pandas as pd import numpy as np import random import string def create_funny_string(): adjectives = [&quot;brilliant&quot;...
<python><arrays><pandas><numpy><iteration>
2023-05-08 10:37:23
0
5,726
DeltaIV
76,199,739
3,946,307
Deploy a flask selenium restful app in production
<p>I am trying to deploy a <code>Flask REST app</code> that primarily does two tasks:</p> <ol> <li>Normal CRUD Operations</li> <li>Using Python <code>selenium</code> to scrape web pages and fetch appropriate results (it opens up Chrome and does the ask)</li> </ol> <p>Can someone suggest to me the best way to deploy suc...
<python><flask><selenium-webdriver>
2023-05-08 10:36:52
1
797
Navitas28
76,199,659
5,371,102
How access form data as dict in streamlit app
<p>I want to be able to access the form data of a streamlit form as a collected dictonary object on the form. I know I can put it into seperate variables, but my code will be much nicer and easier to generalize if I can access it directly on the form object and it seems strange if it is not posible.</p> <pre><code>form...
<python><streamlit>
2023-05-08 10:24:53
1
1,989
Peter Mølgaard Pallesen
76,199,653
13,314,132
ValueError: `run` not supported when there is not exactly one input key, got ['question', 'documents']
<p>Getting the error while trying to run a langchain code.</p> <pre><code>ValueError: `run` not supported when there is not exactly one input key, got ['question', 'documents']. Traceback: File &quot;c:\users\aviparna.biswas\appdata\local\programs\python\python37\lib\site-packages\streamlit\runtime\scriptrunner\script_...
<python><langchain>
2023-05-08 10:24:17
2
655
Daremitsu
76,199,569
7,775,166
Python import function/class using full path or base path
<p>What is recommended when importing something from a subpackage?</p> <p>Option A:</p> <pre><code>from sklearn.model_selection import train_test_split from sklearn import preprocessing train_test_split() preprocessing() </code></pre> <p>Option B:</p> <pre><code>import sklearn sklearn.model_selection.train_test_split...
<python><import>
2023-05-08 10:13:13
3
732
girdeux
76,199,563
5,672,673
TypeError: Input 'y' of 'Sub' Op has type float32 that does not match type uint8 of argument 'x'
<p>I'm working on a GAN with generator and discriminator.</p> <pre><code>@tf.function def train_step(input_image, target, step): with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape: gen_output = generator(input_image, training=True) disc_real_output = discriminator([input_image, target], train...
<python><tensorflow><typeerror><generative-adversarial-network>
2023-05-08 10:12:43
1
1,177
Linh Chi Nguyen
76,199,404
10,966,677
Django admin showing a white box instead of toggle theme icon
<p>As I open Django admin page, a wide white box appears instead of the theme icon (using Django 4.2.1).</p> <p><a href="https://i.sstatic.net/dXqnL.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/dXqnL.png" alt="admin page as appears on production" /></a></p> <p>While testing on Docker container, everyt...
<python><django>
2023-05-08 09:51:19
15
459
Domenico Spidy Tamburro
76,199,337
610,569
How to add new language to NLLB tokenizer in Huggingface?
<p>No Language Left Behind (NLLB) is the machine translation model available on <a href="https://huggingface.co/facebook/nllb-200-distilled-600M" rel="nofollow noreferrer">https://huggingface.co/facebook/nllb-200-distilled-600M</a></p> <p>It supports a list of languages but to add a new language in the tokenizer, the f...
<python><nlp><huggingface-tokenizers><machine-translation>
2023-05-08 09:42:27
2
123,325
alvas
76,199,262
6,495,199
Send BackgroundTask out of controller
<p>The documentation explains how to send background tasks from controllers, like</p> <pre><code>@app.get(&quot;/mypath&quot;) async def send_notification(email: str, background_tasks: BackgroundTasks): pass </code></pre> <p>I wonder if there's a way to emit a background task out of controller scope (I mean, witho...
<python><python-3.x><fastapi><starlette>
2023-05-08 09:33:23
1
354
Carlos Rojas
76,199,165
1,826,066
Overlay average of data in Plotly plot inside a Streamlit app
<p>In this simplified <code>streamlit</code> app, I am using `plotly, to plot some dummy data:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd import plotly.express as px import streamlit as st n = 100 df1 = pd.DataFrame({&quot;x&quot;: np.arange(n), &quot;y&quot;: np.random....
<python><plotly><streamlit>
2023-05-08 09:19:32
0
1,351
Thomas
76,199,139
7,822,387
how to call a databricks notebook from an external python notebook
<p>I want to create a python notebook on my desktop that pass an input to another notebook in databricks, and then return the output of the databricks notebook. For example, my local python file will pass a string into a databricks notebook, which will reverse the string and then output the result back to my local pyth...
<python><rest><azure-databricks>
2023-05-08 09:15:54
1
311
J. Doe
76,198,778
343,159
Retrieving the context (sentences) from Pinecone
<p>I am building an open book abstractive QA model using Pinecone and Sentence Transformers, but I am having trouble later recalling the sentences that produced the matching vectors.</p> <p>I thought I could store this context as metadata, like this:</p> <pre><code>with open(&quot;content.processed.json&quot;, &quot;r&...
<python><huggingface-transformers><sentence-transformers><vector-database>
2023-05-08 08:30:22
0
12,750
serlingpa
76,198,488
17,980,931
Why is numpy.add.at slower than simple grouping and summation?
<p>I am improving the implementation of my kmeans algorithm and currently have the following ndarrays:</p> <ol> <li>Dataset <code>X</code> with shape <code>(n_samples, n_features)</code> and dtype <code>np.float64</code></li> <li>Labels <code>y</code> with shape <code>(n_samples,)</code> and dtpye <code>np.int64</code>...
<python><numpy><sum>
2023-05-08 07:51:48
1
7,781
Mechanic Pig
76,198,429
7,128,910
Enfore app-check for firebase functions in python
<p>I am trying to enforce firebase app-check for my android app. Specifically, I want to restrict access to my firebase cloud functions written in python. I found instructions on how to <a href="https://firebase.google.com/docs/app-check/cloud-functions?authuser=0" rel="noreferrer">do this on node.js</a> based firebase...
<python><firebase><firebase-app-check>
2023-05-08 07:43:35
2
1,261
Nik
76,198,291
5,072,705
Missing custom headers in Google Cloud Storage
<ol> <li>I've created Standard Storaget Type bucket in my GCS console with public access restriction</li> <li>I've put a little file inside this bucket and add custom metadata (&quot;name&quot;:&quot;jack&quot;) using GUI</li> <li>I've created simple Python script for downloading this file:</li> </ol> <p>from pathlib i...
<python><google-cloud-storage>
2023-05-08 07:18:42
1
1,213
Евгений Кравцов
76,198,210
11,801,298
How to have a smooth transition in an animation
<p>I want to create animation using matplotlib.</p> <p>But there is one problem related to the beauty of visualization. The next value appears abruptly after the previous one. There is no smooth transition. Such animation is good for own use, but it does not look good in a public demonstration.</p> <p>Example from offi...
<python><matplotlib><matplotlib-animation>
2023-05-08 07:08:09
0
877
Igor K.
76,198,051
610,569
How to add new tokens to an existing Huggingface tokenizer?
<h1>How to add new tokens to an existing Huggingface AutoTokenizer?</h1> <p>Canonically, there's this tutorial from Huggingface <a href="https://huggingface.co/learn/nlp-course/chapter6/2" rel="noreferrer">https://huggingface.co/learn/nlp-course/chapter6/2</a> but it ends on the note of &quot;quirks when using existing...
<python><nlp><huggingface-transformers><huggingface-tokenizers><large-language-model>
2023-05-08 06:41:32
1
123,325
alvas
76,197,932
13,403,510
Handling time stamps on a time series data and make prediction
<p>So I have a data which looks like below;</p> <pre><code>import pandas as pd data = {'Date': ['16-08-2021', '16-08-2021', '17-08-2021', '18-08-2021', '19-08-2021'], 'Reason no': ['R13', 'R2', 'R5', 'R2', 'R3'], 'Minutes': [115, 625, 625, 1364, 1440], 'Issues': ['Not meeting the hourly target ...
<python><pandas><datetime><deep-learning><lstm>
2023-05-08 06:15:42
0
1,066
def __init__
76,197,920
5,834,711
How to sum the values of multiple rows, group by id and keep the rows of all unique ids with pandas in python?
<p>I have a file with the following columns: 'id','H1','H2','H3','H4','H5','H6','H7','H8','H9','H10','H11','H12','H13','H14','H15','H16','H17','H18','H19','H20','H21','H22','H23','H24'</p> <p>see an example: <a href="https://i.sstatic.net/74NOd.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/74NOd.png" a...
<python><pandas><group-by><sum>
2023-05-08 06:14:07
2
345
Nat
76,197,800
7,921,635
filter list of dictionary based on two values
<p>I have dictionary:</p> <p><code>[{&quot;score&quot;:-10, &quot;name&quot;: &quot;Tom&quot;, &quot;etc&quot;: 1}, {&quot;score&quot;:-20, &quot;name&quot;: &quot;Tom&quot;, &quot;etc&quot;: 2} {&quot;score&quot;:-110, &quot;name&quot;: &quot;Jerry&quot;, &quot;etc&quot;: 3}, {&quot;score&quot;:-210, &quot;name&quot;:...
<python>
2023-05-08 05:43:31
1
427
Nir Vana
76,197,715
6,005,206
Pandas rolling max by skipping NaN
<p>Trying to get the rolling max in presence of NaN's. For some reason, not getting the expected output. Any thoughts!</p> <pre><code># Import library import pandas as pd # Data x = pd.Series([1,2,np.nan,4,np.nan]) # Get rolling max out = x.rolling(window=2).max() print(out) print() # Get rolling max out = x.rollin...
<python><pandas><max><rolling-computation><skip>
2023-05-08 05:23:16
2
1,893
Nilesh Ingle
76,197,453
3,713,835
How to pick value from list if gap(diff) is larger than a define number
<p><code>a = [44, 52, 59, 62, 174, 175, 178, 288, 292, 404, 408, 518, 521, 633, 637, 747, 751, 863, 867, 977, 980, 987]</code></p> <p>For example, on above list, if the gap is 100, then first 3 items should be filter out.</p> <p>final result should be:</p> <p><code>b = [62, 174, 288, 404, 518, 633, 747, 863, 977]</code...
<python>
2023-05-08 04:04:29
2
424
Niuya
76,197,265
21,107,707
Why is squaring a number slower than multiplying itself by itself?
<p>I was curious and decided to run this code in python:</p> <pre class="lang-py prettyprint-override"><code>import time def timeit(function): strt = time.time() for _ in range(100_000_000): function() end = time.time() print(end-strt) @timeit def function1(): return 1 * 1 @timeit def fun...
<python>
2023-05-08 03:04:46
1
801
vs07
76,197,241
10,452,700
Debugging RandomForestRegressor() producing mainly constant forecast results over time-series data
<p>Let's say I have <a href="https://drive.google.com/file/d/18PGLNnOI44LVFignYriBWQFW9WBkTX5c/view?usp=share_link" rel="nofollow noreferrer">dataset</a> contains a timestamp (<em>non-standard</em> timestamp column without datetime format) as a single feature and <code>count</code> as Label/target to predict within the...
<python><machine-learning><scikit-learn><time-series><random-forest>
2023-05-08 02:56:12
2
2,056
Mario
76,197,174
5,601,663
AWS Elastic Beanstalk: can't install mysqlclient
<p>I am going through the <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-rds.html" rel="nofollow noreferrer">adding database</a> to elastic beanstalk python documentation but following the steps leads to the following error</p> <pre><code>2023/05/07 14:06:36.847596 [ERROR] An error...
<python><mysql><amazon-web-services><amazon-ec2><amazon-elastic-beanstalk>
2023-05-08 02:29:44
2
1,732
A. Patrik
76,196,843
10,610,620
1B pseudo-random boolean permutations of vector set N by M
<p>Let's say we have a set of pseudo-random boolean/binary vectors of length N, and each vector is length M.</p> <p>e.g. {[0,1,0,1], [0,0,0,1]}</p> <p>We need one billion unique vectors.</p> <p><strong>Now, the question is, what is the fastest way to do this?</strong>? <em>(also please keep in mind we need to keep the ...
<python><performance><optimization><random><mathematical-optimization>
2023-05-08 00:29:33
2
446
Yume
76,196,828
2,081,511
"NameError: global name 'open' is not defined" Error in __init__.py File
<p>I'm trying to modify an existing Python script even though I'm very inexperience in Python.</p> <p>The script is a <code>__init__.py</code> file and is a Plex Plugin for a custom Agent.</p> <p>The exiting relevant section of code looks like:</p> <pre><code>class CustomAgent(Agent.Movies): def update(self, metada...
<python><python-3.x>
2023-05-08 00:22:49
1
1,486
GFL
76,196,817
20,122,390
How can I filter by date range in mongo db with python?
<p>I have a mongodb database for a python and fastapi web application. The data stored in the collection has the following structure:</p> <pre><code>[ { &quot;_id&quot;: &quot;6457dc8740f35d494c0c76a4&quot;, &quot;operator&quot;: &quot;example&quot;, &quot;department&quot;: &quot;deparment_example&quot;, ...
<python><mongodb><date><mongodb-query><fastapi>
2023-05-08 00:16:58
0
988
Diego L
76,196,816
104,950
Peculiar behavior with Python metaclasses
<p>I'm working on a coding puzzle shown <a href="https://www.codewars.com/kata/54bebed0d5b56c5b2600027f/train/python" rel="nofollow noreferrer">here</a>. My solution is shown and I've included the test cases which pass on my local computer but fail when submitted. It appears as though none of the instrumentation for ...
<python><metaclass>
2023-05-08 00:16:55
1
38,691
Amir Afghani
76,196,742
3,728,184
Can I leave out the `with` statement when opening a file with no pointer?
<p>In Python, it is recommended to use <code>with</code> when opening files, e.g.:</p> <pre><code>with open('x.json') as f: data = json.load(f) </code></pre> <p>But is it okay to shorten it as follows?</p> <pre><code>data = json.load(open('x.json')) </code></pre> <p>The <code>with</code> statement makes sure that the...
<python>
2023-05-07 23:47:20
1
2,005
Markus
76,196,612
11,235,680
Deploy HuggingFace models to AWS: configuration file needed on local machine
<p>I'm trying to deploy this model to AWS through Sagemaker: <a href="https://huggingface.co/mosaicml/mpt-7b-chat" rel="nofollow noreferrer">https://huggingface.co/mosaicml/mpt-7b-chat</a></p> <p>I generated the code from the same page which is as follow:</p> <pre><code>from sagemaker.huggingface import HuggingFaceMode...
<python><amazon-web-services><amazon-sagemaker><huggingface-transformers>
2023-05-07 22:58:11
1
316
Bouji
76,196,491
14,729,820
How to avoid skipping double quotation when save in Json line?
<p>I have file in <code>jsonl </code>format as shown below :</p> <p><code>input.jsonl</code></p> <pre><code>{&quot;file_name&quot;: &quot;input_image.jpg&quot;, &quot;text&quot;: &quot;II. Firtos. Jelige: \&quot;Vándor daruid V betűje szállt.\&quot;&quot;} </code></pre> <p>I am reading this file using pandas :</p> <pre...
<python><json><pandas>
2023-05-07 22:11:16
0
366
Mohammed
76,196,094
6,223,346
How to parse a CSV file that does not have a separator in Python?
<p>My CSV files after decryption are not having any separator and all the data is within quotes.</p> <p>Sample CSV file data:</p> <pre><code>&quot;text&quot;&quot;1&quot;&quot;0.2&quot;&quot;true&quot; &quot;text&quot;&quot;1&quot;&quot;0.2&quot;&quot;true&quot; </code></pre>
<python><csv><parsing>
2023-05-07 20:18:44
4
613
Harish
76,196,068
8,849,755
How to use plotly.express.imshow facet_row argument?
<p>Consider the following code:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy as np import plotly.express as px # Create the index for the data frame x = np.linspace(-1,1, 6) y = np.linspace(-1,1,6) n_channel = [1, 2, 3, 4] xx, yy = np.meshgrid(x, y) zzz = np.random.randn(len(y...
<python><plotly>
2023-05-07 20:12:24
1
3,245
user171780
76,195,989
10,122,822
opencv2 stitching images together failed
<p>I want to stitch together a bunch of images with OpenCV2 with python. Since it is very time consuming to stitch together 30+ images I modified my code to just stitch together 2 images and after that stitch together the next image with the previous stitched image.</p> <p>But when running the code even at the first st...
<python><opencv><imutils>
2023-05-07 19:53:36
0
748
sirzento
76,195,972
9,218,849
aspect sentiment analysis using Hugging face
<p>I am new to transformers models and trying to extract aspect and sentiment for a sentence but having issues</p> <pre><code>from transformers import AutoTokenizer, AutoModelForSequenceClassification model_name = &quot;yangheng/deberta-v3-base-absa-v1.1&quot; tokenizer = AutoTokenizer.from_pretrained(model_name) mode...
<python><nlp><huggingface-transformers><sentiment-analysis>
2023-05-07 19:50:01
1
572
Dexter1611
76,195,686
7,643,958
How to declare a range in the datetime while creating a column in SQLalchemy?
<p>I have a table named &quot;Employee&quot;, where I have a requirement to <strong>set the column value of &quot;hire date&quot; to a datetime object in the format of 'YYYY-MM-DD HH:MM:SS', with a range from 01-01-2020 00:00:00 to today</strong>. I did the following:</p> <pre><code>class Employee(db.Model): id = db....
<python><sqlite><datetime><sqlalchemy><flask-sqlalchemy>
2023-05-07 18:40:44
1
1,179
Proteeti Prova
76,195,685
11,913,986
How to replicate value based on distinct column values from a different df pyspark
<p>I have a df like:</p> <pre><code>df1 = AA BB CC DD 1 X Y Z 2 M N O 3 P Q R </code></pre> <p>I have another df like:</p> <pre><code>df2 = BB CC DD G K O H L P I M Q </code></pre> <p>I want to copy all the columns and rows of df2 for every distinct value of 'AA' column of df1 and ge...
<python><pandas><dataframe><apache-spark><pyspark>
2023-05-07 18:40:33
1
739
Strayhorn
76,195,648
5,766,416
Efficient way to divide a pandas col by a groupby df
<p>Easier to explain with an example, say I have an example dataframe here with <code>year</code>, <code>cc_rating</code> and <code>number_x</code>.</p> <pre><code>df = pd.DataFrame({&quot;year&quot;:{&quot;0&quot;:2005,&quot;1&quot;:2005,&quot;2&quot;:2005,&quot;3&quot;:2006,&quot;4&quot;:2006,&quot;5&quot;:2006,&quot...
<python><pandas><dataframe>
2023-05-07 18:32:27
1
2,572
Wboy
76,195,623
230,468
"Show hover" fails inside function arguments (vscode python intellisense)
<p>I'm working in python using vscode.<br /> My current vscode setup shows very nice, useful information when my cursor is on a function and I trigger <code>editor.action.showHover</code> (for me this is mapped to <code>Shift+Tab</code>). However, when I'm inside the function arguments and I hit <code>Shift+Tab</code>...
<python><visual-studio-code><intellisense>
2023-05-07 18:27:09
0
18,777
DilithiumMatrix
76,195,514
15,755,176
Detect original color regardless of light/scanning conditions
<p>I have the following color palette, which consists of eight RGB colors that are quite distinct from one another:</p> <pre><code>color_palette = [ (255, 255, 255), # White (0, 0, 0), # Black (0, 255, 255), # Cyan (255, 0, 255), # Magenta (255, 255, 0), # Yellow (0, 0, 255), # Blue (255, 0,...
<python><opencv><computer-vision>
2023-05-07 18:05:09
0
376
mangotango
76,195,463
13,231,537
Shorthand index to get a cycle of a numpy array
<p>I want to index all elements in a numpy array and also include the first index at the end. So if I have the array <code>[2, 4, 6]</code> , I want to index the array such that the result is <code>[2, 4, 6, 2]</code>.</p> <pre><code>import numpy as np a = np.asarray([2,4,6]) # One solution is cycle = np.append(a, a[...
<python><numpy>
2023-05-07 17:56:13
1
858
nikost
76,195,422
7,685,367
In Python with Tinkter, how can I use a grid to display a PandasTable instead of pack?
<p>I am researching how to use Tkinter ( CustomTkinter ) and I would like to display a pandastable using the Tkinter GRID layout, instead of the PACK layout. The code below will show the table but it is taking up the entire frame.</p> <p>The entire project is very large and complex but here is the relevant code:</p> <p...
<python><pandas><tkinter><layout><pandastable>
2023-05-07 17:47:46
1
1,057
vscoder
76,195,331
76,701
Plotly: Make a plot that doesn't change proportions when zoomed in
<p>I'm making a custom plot using Plotly for representing a <a href="https://math.stackexchange.com/questions/4693604/succinct-represention-of-a-condensed-complete-directed-graph">condensed complete directed graph</a>. I've worked hard to get the shapes right and it's still a work-in-progress. However, I noticed a prob...
<python><plot><plotly><drawing><graph-theory>
2023-05-07 17:24:11
1
89,497
Ram Rachum