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
⌀
77,371,478
159,072
How can I convert a Union type into a tensor type?
<p>I want to convert a tab-delimited text into a 2D tensor object so that I can feed the data into a CNN.</p> <p>What is the proper way to do this?</p> <p>I wrote the following:</p> <pre><code>from typing import List, Union, cast import tensorflow as tf CellType = Union[str, float, int, bool] RowType = List[CellType] ...
<python><tensorflow><union-types>
2023-10-27 04:19:38
0
17,446
user366312
77,371,442
1,277,865
M1 MacBook can not execute python, after execute ln -s /usr/bin/python3 /usr/bin/local/python
<pre><code>luis@LuisdeMacBook-Pro ~ % python zsh: command not found: python luis@LuisdeMacBook-Pro ~ % ln -s /usr/bin/python3 /usr/local/bin/python ln: /usr/local/bin/python: Permission denied luis@LuisdeMacBook-Pro ~ % sudo ln -s /usr/bin/python3 /usr/local/bin/python luis@LuisdeMacBook-Pro ~ % python python: error: F...
<python><macos><ln>
2023-10-27 04:02:48
2
2,207
thecr0w
77,371,311
235,218
From inside a python function, use a var representing the func object, to get the func's parameters and the values supplied
<p>The first line of the code in the function, '<em>func</em>', below is a print statement. It prints/generates the following sort of cross between a tuple and a dictionary, (to the right of the first equals sign) containing all <em>func</em>’s parameters along with the <strong>default</strong> values for those paramet...
<python><attributes><inspect>
2023-10-27 03:04:49
1
767
Marc B. Hankin
77,371,281
1,715,544
Why does unittest's `mock.patch.start` re-run the function in which the patcher is started?
<p>Let's say we have two files:</p> <p><strong>to_patch.py</strong></p> <pre class="lang-py prettyprint-override"><code>from unittest.mock import patch def patch_a_function(): print(&quot;Patching!&quot;) patcher = patch(&quot;to_be_patched.function&quot;) patcher.start() print(&quot;Done patching!&quo...
<python><python-unittest><patch><monkeypatching><python-unittest.mock>
2023-10-27 02:53:10
2
1,410
AmagicalFishy
77,371,189
7,580,944
Using sklearn KMeans without fitting
<p>Similarly to the question in <a href="https://stackoverflow.com/questions/73909643/using-sklearn-kmeans-with-initial-centroids-without-fitting-model">here</a>, I want to cluster some data according to pre-computed centroids. Differently by that question, these centroids are are provided by other methods.</p> <p>I co...
<python><machine-learning><scikit-learn><k-means>
2023-10-27 02:16:08
1
359
Chutlhu
77,371,047
202,335
Import "flask" could not be resolvedPylancereportMissingImports)
<pre><code>from flask import Flask, request, jsonify app = Flask(__name__) @app.route('/process_user_input', methods=['POST']) def process_user_input(): # Retrieve user input from the request user_input = request.form.get('input') # Return a response response = {'processed_input': user_input} ret...
<python><visual-studio-code><flask>
2023-10-27 01:28:17
1
25,444
Steven
77,371,015
7,188,690
return a difference of nested dictionary in a new column of a dataframe
<p>I have a dataframe where I want to find the difference in the unique_users and total_sessions for the latest day(2023-09-06) and previous day(2023-09-07) for a specific hour 2 and 13 separately for each key 'jio' and 'other' and for a specific Exception. I need to consider the Exception and Hour and Date to calculat...
<python><pandas>
2023-10-27 01:16:48
1
494
sam
77,371,009
2,130,515
How to train doc2vec with pre-built vocab in gensim
<p>I have 1000 documents.</p> <p>For some purpose I need to keep specific words in the vocab. I tokenize the 1000 documents and I design a word_freq dict. e.g. {&quot;word1&quot;:100, &quot;word2&quot;: 2000, ...}</p> <p>Now I want to build a doc2vec model using this word_freq.</p> <pre><code>from gensim.models.doc2vec...
<python><nlp><gensim><word-embedding><doc2vec>
2023-10-27 01:15:12
0
1,790
LearnToGrow
77,370,889
6,471,140
Sagemaker-huggingface An error occurred (ValidationException) when calling the CreateModel operation: Requested image not found
<p>I'm trying to create an asyncronous sagemaker endpoint as shown here <a href="https://github.com/aws/amazon-sagemaker-examples/blob/main/async-inference/Async-Inference-Walkthrough.ipynb" rel="nofollow noreferrer">shown here</a> but using a huggingface model, so I need to use one of the huggingface images and for th...
<python><amazon-web-services><machine-learning><amazon-sagemaker><huggingface>
2023-10-27 00:22:15
1
3,554
Luis Leal
77,370,866
1,330,974
How to filter pandas dataframe using lambda function with regular expression to extract date
<p>Say I have a pandas dataframe like below (with millions of rows) -</p> <pre><code>data = {'s3_path': ['s3://mybucket/date=2023-10-26/f1.txt', 's3://mybucket/date=2023-10-25/f2.txt', 's3://mybucket/date=2023-10-24/f3.txt', 's3://mybucket/date=2023-10-23/f4.txt']} df = pd.DataFrame(data) </code></pre> <p>I want to fil...
<python><pandas>
2023-10-27 00:13:46
2
2,626
user1330974
77,370,814
12,172,744
Fastest way to extract raw Y' plane data from Y'Cb'Cr encoded video?
<p>I have a use-case where I'm extracting <code>I-Frames</code> from videos and turning them into <a href="https://en.wikipedia.org/wiki/Perceptual_hashing" rel="nofollow noreferrer">perceptual hashes</a> for later analysis.</p> <p>⠀</p> <p>I'm currently using <code>ffmpeg</code> to do this with a command akin to:</p> ...
<python><c++><ffmpeg><video-encoding><yuv>
2023-10-26 23:48:44
1
364
memeko
77,370,743
14,187,095
Kedro viz blank page
<p>I created a sample pipeline that works correctly with <code>kedro run</code>, however when I try to visualise it with <code>kedro viz</code> I'm getting basically a blank page, even though the terminal doesn't show a single error. The only detail I've found was in the inspection mode:</p> <p><a href="https://i.sstat...
<python><server><localhost><visualization><kedro>
2023-10-26 23:16:13
2
307
Fatafim
77,370,620
9,067,016
A DRY approach for multiple excepts
<p>Let's assume we have a following code:</p> <pre><code>try: whatever except ValueError: something1 except (IndexError, KeyError): something2 except KeyBoardInterrupt: something3 except Exception: something4 else: # no error something5 finally: finalize </code></pre> <p>So we have multiple...
<python><error-handling><dry>
2023-10-26 22:32:36
3
609
Vova
77,370,408
20,122,390
How does Celery Chord works in Python?
<p>I have the following piece of code:</p> <pre><code>def create_pipeline( real: DataFrame, forecast_name: str, energy_asset_id: int, family: str, forecast_range: date_range, methodologies: List[str], start_forecast: datetime, subfamily_x_forecast_id: int, uuid: str, subfamily_id...
<python><celery><celery-task>
2023-10-26 21:33:14
1
988
Diego L
77,370,398
652,528
Python decimal sum returning wrong value
<p>I'm using decimal module to avoid float rounding errors. In my case the values are money so I want two decimal places.</p> <p>To do that I do <code>decimal.getcontext().prec = 2</code> but then I get some surprising results which make me think I'm missing something. In this code the first assertion works, but the se...
<python><fixed-point>
2023-10-26 21:31:37
2
6,449
geckos
77,370,358
7,197,899
Python check if value in tuple fails with numpy array
<p>I've got a function that returns a tuple, and I need to check if a specific element is in the tuple. I don't know types of elements will be in the tuple, but I know that I want an exact match. For example, I want</p> <pre><code>1 in (1, [0, 6], 0) --&gt; True 1 in ([1], 0, 6]) --&gt; False </code></pre> <p>This shou...
<python><arrays><numpy><tuples>
2023-10-26 21:19:32
1
1,173
KindaTechy
77,370,195
6,523,485
Plotly Error: X-axis of scatter is grouping time series points erroneously
<h1>TL;DR</h1> <p>I am plotting time series data using a plotly scatter plot in a streamlit dashboard. The data is captured every second (actually down to microseconds) but the plot groups approximately every two minutes of data together.</p> <h2>Improper &quot;grouped every 2 minute&quot; output</h2> <p>Plotly express...
<python><scatter-plot><plotly><streamlit>
2023-10-26 20:42:03
0
1,089
Harry de winton
77,370,187
6,202,092
Problem with nested loops and if else statements in python, Jinja2
<p>The following code is doing what it is supposed to do, but I need it to return just one instance under each category; please see the output example below.</p> <pre><code>categories = [[1], [2], [3], [4], [5], [6], [7], ...
<python><django-templates><jinja2>
2023-10-26 20:41:01
2
503
Enrique Bruzual
77,370,130
8,508
Is there a way to have an Argparse argument imply multiple other options?
<p>I have 2 options, that can take various arguments. I want to have a special option that means &quot;both of those with specific standard data&quot;. This will be a different mode then the operation with no arguments.</p> <pre><code> parser.add_argument('--use-std-date', '-U', action='store_const', ...
<python><argparse>
2023-10-26 20:26:34
0
15,639
Matthew Scouten
77,370,098
12,436,050
Streamlit application too slow after each user selection
<p>I am new to streamlit. I am creating a webservice through reading a spreadsheet (~2 million rows).<br /> I created two drop down selection using columns &quot;PRODUCTID&quot;, &quot;PRODUCTNDC&quot; from the table. However when a user is selecting the identifier from the drop down, it is reading a dataframe again an...
<python><pandas><dataframe><streamlit>
2023-10-26 20:19:49
1
1,495
rshar
77,370,079
4,399,016
How to read a pandas date column as date type
<p>I have this code. I can download a spreadsheet and load a worksheet as a data frame. But the Date column is not getting converted as expected.</p> <pre><code>import requests import pandas as pd def get_BH_spreadsheet(URLS, SPREADSHEET_NAME): resp = requests.get(URLS) output = open(SPREADSHEET_NAME, 'wb') ...
<python><pandas><dataframe><datetime>
2023-10-26 20:16:57
2
680
prashanth manohar
77,370,040
6,818,619
Decode byte string to Cyrillic in Python
<p>I have a byte string like this, it should be <code>Сравнение</code> in Cyrillic characters:</p> <pre><code>a = b'&amp;#1057;&amp;#1088;&amp;#1072;&amp;#1074;&amp;#1085;&amp;#1077;&amp;#1085;&amp;#1080;&amp;#1077;' </code></pre> <p>Decoding it into UTF-8 doesn't help:</p> <pre><code>a = b'&amp;#1057;&amp;#1088;&amp;#...
<python><python-3.x><utf-8><decode>
2023-10-26 20:08:28
1
390
ans
77,369,986
1,338,449
Ansible collections, google.cloud.gcp_storage_object, increase timeout
<p>I am running a playbook that uses google.cloud.gcp_storage_object to upload a file to google cloud storage. Some times this module throws timeout exception. What I want, is to increase the timeout while calling this module but I couldn't figure out and understand why the module itself doesn't provide this parameter ...
<python><ansible><google-cloud-storage><ansible-galaxy>
2023-10-26 19:56:44
0
481
laxris
77,369,969
152,781
How to persist a dask dataframe loaded with dask.dataframe.from_delayed
<p>I have a large sharded dataset stored in a custom format that would benefit greatly from <code>dask.dataframe.from_delayed</code></p> <p>However, I'm seeing odd behavior when trying to persist the resulting dataframe:</p> <pre><code>def load(file): # Just an example...Actual loading code is more complex. return ...
<python><pandas><dask><dask-distributed>
2023-10-26 19:52:27
1
753
kjleftin
77,369,814
226,081
Python: type annotate a function return value that returns a class defined in that function
<p>I'm wondering what the proper way to type annotate a return value of a function or method where a class is defined inside of that function.</p> <p>For example:</p> <pre class="lang-py prettyprint-override"><code>from typing import List from dataclasses import dataclass def get_users() -&gt; List['ReturnUser']: ...
<python><python-typing>
2023-10-26 19:20:30
1
10,861
Joe Jasinski
77,369,793
10,426,490
How to show Azure Function with Python runtime as a failed run?
<p>Does an Azure Function run only show as &quot;failed&quot; if an unhandled exception occurs? If all exceptions are handled, will the Function run show as &quot;successful&quot; even though some part of it failed?</p> <p><strong>Example</strong>: If the below parsing logic fails, do I need to <code>raise</code> in th...
<python><azure><azure-functions>
2023-10-26 19:16:38
1
2,046
ericOnline
77,369,695
3,420,197
How can I get 1000 sample from each class of dataframe?
<p>I want to get sample of each class, for example, 1000 rows each class 1, 2, 3, 4 or fewer if there aren't enough rows.</p> <pre><code>import pandas as pd data = { 'Date': ['2023-10-20', '2023-10-21', '2023-10-22', '2023-10-23', '2023-10-24' ...], 'class': [4, 1, 1, 2, 3 ...], 'other_col1': [5, 6, 3, 1, ...
<python><pandas><dataframe>
2023-10-26 18:57:22
1
1,712
Anna Andreeva Rogotulka
77,369,612
11,092,636
Issue with .dt accessor even after confirming Timestamp datatype in pandas DataFrame
<p>I am encountering an AttributeError when trying to use the .dt accessor on a pandas Series, despite confirming that the Series contains only Timestamp objects. I've condensed my problem into a Minimal Reproducible Example (MRE) below:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd # Sample ...
<python><pandas><dataframe>
2023-10-26 18:43:47
1
720
FluidMechanics Potential Flows
77,369,454
1,902,616
pytube NameError: name 'YouTube' is not defined
<p>I had pytube working before and I've obviously messed something up, however at the moment I can't get pytube or pytube3 to work at the most basic level.</p> <p>When I run &quot;py&quot; to open Python, then I type in just:</p> <pre><code>import pytube i = &quot;https://www.youtube.com/watch?v=X&quot; yt = YouTube(i)...
<python><installation><pip><namespaces><pytube>
2023-10-26 18:14:46
0
1,025
azoundria
77,369,410
1,072,283
How to handle utf-8 non-breaking spaces in CSV
<p>In a Python script I am using <code>openpyxl</code> to read an XLSX file. I move some metadata around, and ultimately writing out a new CSV. When I open that CSV in Microsoft Excel, there are whitespaces in a certain metadata field that are being replaced with the following characters: <code>†¬</code>. Here is a bef...
<python><excel><csv><utf-8>
2023-10-26 18:06:09
1
661
dongle
77,369,379
11,716,727
Why do I face such error when I import data throught pandas?
<p>As a beginner, I am trying to import data with the name of (Facebook_Ads_2.csv) using pandas on jupyter notebook; the output must be as shown below.</p> <p><a href="https://i.sstatic.net/gsiAL.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/gsiAL.png" alt="enter image description here" /></a></p> <p>b...
<python><pandas><read-csv>
2023-10-26 17:59:45
1
709
SH_IQ
77,369,332
3,380,902
find the maximum Split of Positive Even integers given an array
<p>I am trying to solve LeetCode problem <a href="https://leetcode.com/problems/maximum-split-of-positive-even-integers/description/" rel="nofollow noreferrer">2178. Maximum Split of Positive Even Integers</a>:</p> <blockquote> <p>You are given an integer <code>finalSum</code>. Split it into a sum of a <strong>maximum<...
<python><algorithm>
2023-10-26 17:52:42
4
2,022
kms
77,369,029
469,476
parsing actual link from href using lxml
<p>Using jupyter notebook, python 3. I'm downloading some files from the web, much with them in bulk locally. The files are listed on a webpage, but they are in an href attribute. The code I found gives me the text, but not the actual link (even though my understanding is the code was supposed to get the link).</p> <p>...
<python><parsing><lxml>
2023-10-26 17:00:33
0
1,994
elbillaf
77,369,002
12,274,651
Python Gekko Differential Equation Solution wrt Distance, not Time
<p>I need to solve a differential equation for a plug flow chemical reactor with respect to distance, not time. Gekko uses <code>m.time</code> to define the time horizon and <code>y.dt()</code> to use <code>dy/dt</code> in equations. Is it possible to covert to <code>m.distance</code> and <code>y.dx()</code> instead to...
<python><ode><gekko>
2023-10-26 16:55:44
1
744
TexasEngineer
77,368,905
16,383,578
PyQt6 custom title bar causes window to move differently from the cursor
<p>This is about my GUI program that I have been working on for over 2 months.</p> <p><a href="https://i.sstatic.net/DLJfp.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/DLJfp.png" alt="enter image description here" /></a></p> <p>I have finally completed it and I have posted it on <a href="https://coder...
<python><pyqt><pyqt6>
2023-10-26 16:42:23
1
3,930
Ξένη Γήινος
77,368,904
7,318,120
Methods and attributes do not show when dot is pressed (intellisense)
<p>Yesterday I upgraded from <code>3.11</code> to python <code>3.12</code>. The editor that i use is <code>VScode</code>.</p> <p>When i use standard patterns with matplotlib (from the official docs), the intellisense does not recognise the types and therefore pressing the dot fails to expose the methods and attributes....
<python><matplotlib><visual-studio-code><pylance>
2023-10-26 16:42:14
1
6,075
darren
77,368,894
5,052,605
Python: PackageNotFoundError No package metadata was found for <myproject>
<p>I have an existing python project and trying to debug in via Microsoft Visual Studio Code.</p> <p>Therefore I have the following launch.json:</p> <pre><code>{ &quot;version&quot;: &quot;0.2.0&quot;, &quot;configurations&quot;: [ { &quot;name&quot;: &quot;Python: myproject&quot;, ...
<python><visual-studio-code><python-3.12>
2023-10-26 16:40:15
1
326
Airwave
77,368,828
2,687,317
Compute time diffs between each entry in one dataframe and all entries in another - pandas
<p>Again, I have 2 data frames consisting of times. I'd like to find the <strong>delta</strong> time between <strong>each</strong> df1 Stop Time and <strong>every</strong> df2 Start Time. If the Start Time in df2 is before the Stop Time in df1 I would want deltatime of 0. For instance:</p> <p>df1</p> <pre>Stop Time ...
<python><pandas>
2023-10-26 16:32:27
2
533
earnric
77,368,813
13,944,524
Why joinedload() is the better choice than selectinload() in many to one relationship in SQLAlchemy
<p>I know how <a href="https://docs.sqlalchemy.org/en/20/tutorial/orm_related_objects.html#selectin-load" rel="noreferrer"><code>selectinload()</code></a> and <a href="https://docs.sqlalchemy.org/en/20/tutorial/orm_related_objects.html#joined-load" rel="noreferrer"><code>joinedload()</code></a> work. And I also know wh...
<python><database><sqlalchemy><orm>
2023-10-26 16:31:02
1
17,004
S.B
77,368,601
5,344,058
Combination of @statsd.timed and @swag_from decorators causes FileNotFoundError
<p>I have a working Flask endpoint decorated with <code>flasgger.swag_from</code> decorator:</p> <pre class="lang-py prettyprint-override"><code>from flasgger import swag_from @app.route(&quot;/jobs&quot;, methods=[&quot;GET&quot;]) @swag_from('swagger/get_jobs.yml') def get_jobs(request_id): # ... </code></pre> <p...
<python><flask><datadog><flasgger>
2023-10-26 15:59:15
1
37,882
Tzach Zohar
77,368,577
21,612,376
Convert an .xlsb file to .xlsx
<p>Suppose I have <code>file.xlsb</code>. I would like to convert it to <code>file.xlsx</code> programmatically using R. How can I do this?</p> <p>I have tried using both <code>openxlsx::read.xlsx()</code> and <code>readxl::read_excel()</code> to read the files (to then later write to <code>.xlsx</code>), but both a...
<python><r>
2023-10-26 15:56:14
2
833
joshbrows
77,368,387
4,004,541
Understanding OpenCV projectPoints: reference points and origins
<p>I have been battling with projectPoints for days without understanding the basic reference point of the function. I find it hard to find the word coordinates and the reference points of all the inputs.</p> <p>Here a small example.</p> <pre><code> import numpy as np import cv2 as cv camera_matrix = np.arra...
<python><opencv><computer-vision><camera-calibration><camera-projection>
2023-10-26 15:29:56
1
360
Patrick Vibild
77,368,186
2,600,531
Python Multiprocessing - detect if PID is alive
<p>I need to detect if the PID of a grandchild process is alive. Because the multiprocessing.Process() object <a href="https://stackoverflow.com/questions/29007619/python-typeerror-pickling-an-authenticationstring-object-is-disallowed-for-sec">is non-pickleable (for security reasons)</a>, I can't pass it up the process...
<python><multiprocessing><pid>
2023-10-26 15:05:53
1
944
davegravy
77,368,184
850,781
Non-uniform domain moving average using sparse matrices
<p><a href="https://stackoverflow.com/q/75981262/850781">Moving average with non-uniform domain</a> works fine:</p> <pre><code>import numpy as np import pandas as pd import matplotlib.pyplot as plt def convolve(s, f): &quot;&quot;&quot;Compute the convolution of series S with a universal function F (see https:...
<python><numpy><sparse-matrix><convolution><rolling-computation>
2023-10-26 15:05:39
1
60,468
sds
77,368,089
6,524,169
SandBoxing Python : exec with __builtins__ set as None, Accessing a method on datetime leads to a KeyError exception
<p>I was trying to limit random code execution by doing the below in Py 3.11.4 on M1 chip -:</p> <pre class="lang-py prettyprint-override"><code>import datetime import io import traceback from contextlib import redirect_stderr, redirect_stdout from typing import Dict SAFE_BUILTINS = ['abs', 'all', 'any', 'chr', 'dict...
<python><python-3.x>
2023-10-26 14:52:51
1
2,580
Aditya
77,367,935
2,724,080
Celery Chains: Do chains work is there is a one to many relationship with the functions?
<p>Chain documentation: <a href="http://docs.celeryproject.org/en/latest/userguide/tasks.html#avoid-launching-synchronous-subtasks" rel="nofollow noreferrer">http://docs.celeryproject.org/en/latest/userguide/tasks.html#avoid-launching-synchronous-subtasks</a></p> <p>Example from another thread: <a href="https://stacko...
<python><celery>
2023-10-26 14:34:37
1
393
Chase Westlye
77,367,782
18,159,603
music21 seems to modify MIDI file when reading/rewritting it
<p>I've got a midi file from the <a href="https://magenta.tensorflow.org/datasets/groove" rel="nofollow noreferrer">Groove MIDI dataset</a>. Here is an example: <a href="https://drive.google.com/file/d/1xcWT8Uodgh1TG9QxZfMUYul1bUAu54C4/view?usp=drive_link" rel="nofollow noreferrer">groove/drummer1/eval_session/1_funk-g...
<python><midi><music21>
2023-10-26 14:15:35
0
1,036
leleogere
77,367,745
774,575
Numpy and linear algebra: How to code Axꞏy?
<p>I've some difficulty in matching what Numpy expects when performing the dot product and vector representation in linear algebra, in term of shapes.</p> <p>Let's say I've a matrix and two column vectors represented by Numpy arrays:</p> <pre><code>import numpy as np A = np.array([[1,2], [3,1], ...
<python><numpy><linear-algebra>
2023-10-26 14:10:12
1
7,768
mins
77,367,509
8,318,946
Django Rest Framework - allow other application to log in
<p>I want to share <code>api/user/profile</code> API endpoint with other developers so they can take user data and process it in their application. I am struggling with writing python script to succesfully log in to DRF because I am constantly getting <code>{&quot;errors&quot;: {&quot;detail&quot;: &quot;Authentication...
<python><django-rest-framework>
2023-10-26 13:40:00
0
917
Adrian
77,367,482
20,122,390
Why can some Celery workers stop without any evidence of failure?
<p>I have an event-driven architecture in a part of my application that is implemented in Celery workers. It is a training of machine learning models so the process is usually somewhat delayed (around 48 hours). So at a certain point, there is a communication between workers that invoke each other's tasks and do some t...
<python><kubernetes><microservices><celery>
2023-10-26 13:36:55
1
988
Diego L
77,367,468
6,494,707
Replacing the original pixel values with the predicted values by model: it returns True when comparing two tennsors?
<p>I have an original input value tensor <code>patches</code> to my model</p> <pre><code>patches.shape torch.Size([64, 1280, 10]) # batch: 64, number of patches: 1280, original pixel values of each patch: 10 </code></pre> <p>My model predicts the pixel values of specific patches that are masked and the indices of mask...
<python><python-3.x><deep-learning><pytorch><pytorch-lightning>
2023-10-26 13:34:44
2
2,236
S.EB
77,367,213
5,431,734
python multithreading. How to prevent multiple threads from running on the gpu
<p>I am using multithreading to read files and obtain some data and then I am processing those data with a gpu accelerated function. My system has only one gpu, hence I think, I should be allowing only one thread to run on my gpu at any given time.</p> <p>My program looks as follows</p> <pre><code>from multiprocessing....
<python><multithreading><multiprocessing>
2023-10-26 12:57:30
0
3,725
Aenaon
77,367,195
4,203,480
Simple flood fill algorithm in C to fill an array of integers
<p>After trying my luck at <a href="https://codereview.stackexchange.com/questions/287543/flood-fill-algorithm-in-fortran-90">implementing it in Fortran 90</a>, I turned to C. I'm not sure whether it's my <code>queue</code> implementation or the actual <code>flood fill algorithm</code> but it doesn't work as expected a...
<python><c><algorithm><queue><flood-fill>
2023-10-26 12:54:07
1
1,180
YeO
77,367,185
5,961,077
My headless browser works on its own, but fail when used as a FastAPI endpoint
<p>I coded a class to use as a headless browser for my FastAPI app. The problem is the class works just fine when I use it directly, but it fails when used in a FastAPI endpoint.</p> <p>Here's the class</p> <pre class="lang-py prettyprint-override"><code>from playwright.async_api import async_playwright import logging ...
<python><asynchronous><fastapi><playwright-python>
2023-10-26 12:52:13
1
1,411
Mehdi Zare
77,366,886
17,160,160
Create quarter: month dictionary in Python from varied arrays of quarters and months
<p><strong>Basic Problem</strong><br /> Given a list of quarters and a list of months:</p> <pre><code>quarters = ['Q1-21', 'Q2-21', 'Q3-21', 'Q4-21', 'Q1-22', 'Q2-22', 'Q3-22', 'Q4-22'] months = ['JAN-21', 'FEB-21', 'MAR-21', 'APR-21', 'MAY-21', 'JUN-21', 'JUL-21','AUG-21', 'SEP-21','OCT-21', 'NOV-21', 'DEC-21',...
<python>
2023-10-26 12:11:03
3
609
r0bt
77,366,713
9,525,238
PySide6 QPushButton with Icon in Center
<p>I'm trying to design a button that has a bigger icon, slightly above the center of the button, with some small text below it.</p> <p><a href="https://i.sstatic.net/qPlEd.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/qPlEd.png" alt="enter image description here" /></a></p> <p>Minimum example:</p> <pr...
<python><pyqt6><pyside6><qtstylesheets>
2023-10-26 11:44:03
0
413
Andrei M.
77,366,710
752,976
How can I get Python stacktraces to show up properly in Google Cloud Trace?
<p>I have a web service written in python, running on GKE. I've enabled opentelemetry instrumentation via FastAPI contrib package, OTel SDK and cloud trace exporter.</p> <p>I am able to send and view successful traces, but the exception information seems wrong. I am getting the correct message and <code>exception.type<...
<python><google-cloud-platform><fastapi><stack-trace><open-telemetry>
2023-10-26 11:43:35
0
39,520
Bartek Banachewicz
77,366,617
736,662
Using the "name" argument to group requests
<p>I have a working request like this:</p> <pre><code> resp = self.client.get(f'/api/loadValues?tsIds={load_ts_ids_in_function}&amp;resolution={resolution}' f'&amp;startUtc={set_from_date_load_values()}&amp;endUtc={set_to_date_load_values()}', headers={'X-API-KEY': ...
<python><locust>
2023-10-26 11:30:46
1
1,003
Magnus Jensen
77,366,382
21,049,944
polars dataFrame.sort() - large memory requirements
<p>When I call the <code>DataFrame.sort()</code> from the Python-polars library, the RAM jumps to more then double of its original values. This is of course a problem when dealing with large datasets (we are talking tens to hundereds of GB). Is there any workaround that (even in cost of performance) cost less RAM?</p> ...
<python><dataframe><sorting><ram><python-polars>
2023-10-26 10:56:10
1
388
Galedon
77,366,310
4,547,189
Connection in DaG - Using Connection() to connect to MsSQL Backend in Airflow
<p>We have our secrets stored in AWS Secrets manager. Hence I figured, let use Connection() to create connection to MsSQL and then use the Hook to execute SQL query.</p> <pre><code>c = Connection( conn_id=&quot;test_mssql_1&quot;, conn_type=&quot;mssql&quot;, description=&quot;connec...
<python><sql-server><airflow>
2023-10-26 10:45:55
1
648
tkansara
77,366,252
17,487,457
Why macOS is pointing to two versions of python 3?
<p>Good that MacBook now shipped without the dead <code>python2.7</code>.</p> <p>I have python 3 installed already:</p> <pre><code> % python -V Python 3.9.6 </code></pre> <p>However, I a create an isolated virtual environment, I get <code>Python 3.11</code> instead.</p> <pre><code>python -m venv venv </code></pre> <p>W...
<python><macos><macos-sonoma>
2023-10-26 10:37:02
2
305
Amina Umar
77,366,027
15,320,579
Create nested dictionary based on some custom rules
<p>I have a python dictionary as follows:</p> <pre><code>ip_dict = { &quot;img_folder/144-64ee3d9bb7-3.png&quot;: &quot;COMMERCIAL PROPERTY &quot;, &quot;img_folder/144-64ee3d9bb7-2.png&quot;: &quot;CBIC COMMERCIAL &quot;, &quot;img_folder/144-64ee3d9bb7-4.png&quot;: &quot;CBIC COMMERCIAL GENERAL&quot;, ...
<python><dictionary><nested><data-munging>
2023-10-26 10:05:29
2
787
spectre
77,366,022
2,724,299
How to get comments from a worksheet as a pandas dataframe after reading in with openpyxl and
<p>I can get the data from an Excel worksheet as a dataframe by using :</p> <pre><code>from openpyxl import load_workbook import pandas as pd wb = load_workbook(filename = 'test.xlsx',data_only=True) ws = wb[wb.sheetnames[1]] df = pd.DataFrame(ws.values) </code></pre> <p>But how do I get the comments from each cell in...
<python><pandas><excel><openpyxl>
2023-10-26 10:04:50
1
738
Frash
77,366,004
13,328,010
Snakemake workflow run with conda and singularity fails to find conda
<p>I am facing an issue when running snakemake with a container and conda. Let me explain better. I am developing a workflow (locally) in snakemake, where some rules use a conda env (defined in /envs/env.yaml) and other rules use wrappers (so they also are based on conda envs).</p> <p>An example here:</p> <pre><code>ru...
<python><docker><containers><conda><snakemake>
2023-10-26 10:02:47
0
2,424
DavideBrex
77,365,963
14,967,240
Why is 'plt.imshow' showing the original image when the actual values are changed?
<h2>What is the problem of this piece of code?</h2> <p>It modifies the values but when it wants to show me the actual modified image, it will show me the original image again. Am I doing something wrong?</p> <p>And let me explain this in images too:</p> <p>1- Original image:</p> <p><a href="https://i.sstatic.net/M1C8R....
<python><numpy><matplotlib><image-processing>
2023-10-26 09:57:51
1
615
Mahmood
77,365,901
1,794,714
How can I fix the async call to OpenAI embeddings from Databricks?
<p>I am attempting to use the OpenAI Python package to get some embeddings for text classification.</p> <p>The regular version currently works:</p> <pre><code>import openai from openai.embeddings_utils import get_embedding def add_embeddings(data:pd.DataFrame) -&gt; pd.DataFrame: data[&quot;embedding&quot;] = data['...
<python><asynchronous><databricks><openai-api>
2023-10-26 09:47:57
1
391
FitzKaos
77,365,862
13,146,029
UnboundLocalError: cannot access local variable 'Migrate' where it is not associated with a value - flask
<p>I'm trying to set up Flask Migrate to handle my migrations for my app. I use a factory to handle my set-up and when I try to run flask db init I get the following error:</p> <pre><code>Traceback (most recent call last): File &quot;/Users/grahammorby/Documents/GitHub/tagr-api/venv/bin/flask&quot;, line 8, in &lt;mo...
<python><flask>
2023-10-26 09:42:44
1
317
Graham Morby
77,365,790
14,243,731
Jinja2 Whitespace control on {% with %} tag not working as expected
<p>I am running into the issue that a <code>{% with %}</code> tag is adding an extra line to my jinja template although I set <code>trim_blocks=True</code> and <code>lstrip_blocks=True</code> in my <code>Environment(loader=loader, trim_blocks=True, lstrip_blocks=True)</code> class.</p> <p>Here is the code:</p> <p>ddl.j...
<python><flask><jinja2>
2023-10-26 09:33:20
1
328
Adventure-Knorrig
77,365,770
10,722,752
how to perform rolling mean using if condition in group by operation
<p>I am trying to add a code wherein, if the difference between current date and the minimum date of the id column is more than 3 months, the rolling mean should be for a 21 days window, else it should be for a 7 days window.</p> <p>Sample data:</p> <pre><code>import pandas as pd import numpy as np np.random.seed(0) dt...
<python><pandas><numpy>
2023-10-26 09:31:07
2
11,560
Karthik S
77,365,743
8,030,794
How do professional programs process huge amounts of data from websockets?
<p>I'm just learning Python. I would like to receive data from the exchange for all coins via a websocket. But the loop does not have time to process so much data and the queue gradually accumulates. I don’t understand how screener sites process so much in parallel and don’t slow down. Can you tell me please how this i...
<python><websocket><python-asyncio>
2023-10-26 09:28:36
0
465
Fresto
77,365,740
2,986,042
How to send logs back to tkinter GUI from Robot framework?
<p>I have created GUI using python Tkinter. After clicking <code>run button</code> in the GUI, It will send selected GUI variables (eg: text box values) to Robot framework. This is my design concept</p> <pre><code>Tkinter GUI ----&gt; Run.bat ---&gt; Execute Robot framework </code></pre> <p><strong>Run.bat</strong></p...
<python><tkinter><robotframework><python-multithreading>
2023-10-26 09:28:00
0
1,300
user2986042
77,365,516
21,185,825
Python - textual - question marks instead of borders in DOS prompt
<p>When I run this Python code in VS Code, it displays the borders fine.</p> <p>But in a Windows command-line (DOS prompt) I get question marks where borders should display.</p> <h3>Code</h3> <p>I use the code from Textual tutorial:</p> <pre><code>class Hello(Static): BORDER_TITLE = &quot;Hello Widget&quot; de...
<python><utf-8><windows-console><textual>
2023-10-26 08:54:45
0
511
pf12345678910
77,365,453
16,473,860
Error Installing Pytorch+cuda121 in Poetry Virtual Environment: Source (pytorch): Authorization error accessing https://download.pytorch.org/
<p>I am looking to use the yolov5 model and opencv in my project. I am currently using Poetry as the virtual environment for my project.</p> <p>In order to operate yolov5 with gpu rather than cpu, I am looking to install cuda. I am trying to download the Cuda 12.1 version from <a href="https://pytorch.org/" rel="nofoll...
<python><deep-learning><pytorch><yolo><python-poetry>
2023-10-26 08:46:20
1
747
Kevin Yang
77,365,408
8,905,583
Defining Correct DataType for Nested JSON in Flink's Elasticsearch Sink (Python)
<p>I am working with Apache Flink and attempting to sink documents into Elasticsearch using the built-in Elasticsearch Sink. I'm having difficulty defining the correct data type for the sink to accept my documents.</p> <p>My JSON documents look as follows:</p> <pre class="lang-json prettyprint-override"><code>{ bod...
<python><json><elasticsearch><apache-flink>
2023-10-26 08:39:37
1
838
thijsfranck
77,365,361
5,775,358
Move x-axis to data=0 but keep tick labels at the bottom
<p>I would like to move the line of the x-axis (with all the corresponding ticks) x=0. But the tick-labels should be positioned at the bottom of the figure, to prevent clutter in the graph.</p> <p><a href="https://stackoverflow.com/questions/56669981/show-axis-at-center-but-keep-labels-on-the-left/56670291#comment13638...
<python><numpy><matplotlib><xticks>
2023-10-26 08:33:20
1
2,406
3dSpatialUser
77,365,273
736,662
Aggregate Locust test results runtime
<p>I have two apparantly similar tests in Locust, but one of them writes every call two the <code>web-gui</code>, while the other one aggregates the calls. I want both tests to do as the latter aka aggregate.</p> <p><a href="https://i.sstatic.net/wJznX.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/wJzn...
<python><locust>
2023-10-26 08:20:56
1
1,003
Magnus Jensen
77,365,266
10,232,932
ModuleNotFoundError: No module named 'ruptures.datasets'
<p>Probably I am opening the 1.000.000 question to a modul not found error. But I installed <code>ruptures</code> with <code>pip install ruptures</code>, but somehow when I run my script I get the following error:</p> <pre><code>--------------------------------------------------------------------------- ModuleNotFoundE...
<python>
2023-10-26 08:20:00
0
6,338
PV8
77,365,178
12,176,803
Poetry cannot install custom script
<h1>Issue</h1> <p>Poetry does not install a custom script (for CLI app)</p> <h1>My setup</h1> <p>I have a very simple project on MacOS:</p> <pre><code>- .venv - pyproject.toml - main.py - src |... </code></pre> <p>Here is my <code>pyproject.toml</code></p> <pre><code>[tool.poetry] ... [tool.poetry.dependencies] ... ...
<python><python-poetry>
2023-10-26 08:06:32
2
366
HGLR
77,365,163
5,955,479
Airflow - import DAGs from multiple repositories
<p>We have deployed airflow using the official helm chart on kubernetes, we are using KubernetesExecutor and git-sync.</p> <p>I have no problems running DAGs from a single Gitlab repository, however how are you supposed to load DAGs from a different repository? I ran into this discussion - <a href="https://github.com/a...
<python><git><airflow>
2023-10-26 08:03:26
0
355
user430953
77,365,129
11,716,727
How can I get zeros or ones instead of True or false using pd.get_dummies?
<p>I am working as a beginner on the dataset of Titanic survivals, and I am trying to convert the <strong>Sex column</strong> into a single column with <strong>zeros</strong> and <strong>ones</strong> using <strong>get_dummies</strong>.</p> <pre><code> female male 0 True False 1 False True 2 True False ...
<python><pandas>
2023-10-26 07:58:38
1
709
SH_IQ
77,364,938
1,635,253
Forecasting with Prophet with "id" column on test test
<p>I'm building a forecasting model with Prophet in python. My train dataset consist on column <strong>&quot;Date&quot;, &quot;Var1&quot;, &quot;Var2&quot;, &quot;Y&quot;</strong>. And the test set consist of column <strong>&quot;id&quot;, &quot;Date&quot;, &quot;Var1&quot;, &quot;Var2&quot;</strong>. The &quot;id&quot...
<python><pandas><facebook-prophet>
2023-10-26 07:30:09
2
347
thenoirlatte
77,364,715
3,089,084
Installing python kats on macos m1
<p>I aim to use <a href="https://facebookresearch.github.io/Kats/" rel="nofollow noreferrer">python kats</a> library to do some time series analysis. I can not get it to install using python 3.11 on my Mac.</p> <p>Basic machine info: M1 Macbook Pro Python Version: 3.11</p> <p>The process for installation:</p> <pre><cod...
<python><pipenv>
2023-10-26 06:52:34
1
1,222
silverdagger
77,364,710
7,052,826
Plotly express inconsistent behavior with text size
<p>I am having trouble controlling text size within plotly.express figures.</p> <p>If I create some fake data like so, it appears to work.</p> <pre><code>df = pd.DataFrame({ &quot;x&quot;:['1','2','2','1','1','2','2','1'], 'y':[10,20,30,40,30,20,10,10], 'type':['a','a','b','b','a','a','b','b'], 'text'...
<python><plotly><plotly-express>
2023-10-26 06:51:45
0
4,155
Mitchell van Zuylen
77,364,550
6,323,020
AttributeError: module 'pkgutil' has no attribute 'ImpImporter'. Did you mean: 'zipimporter'?
<p>Earlier I installed some packages like <a href="https://en.wikipedia.org/wiki/Matplotlib" rel="noreferrer">Matplotlib</a>, <a href="https://en.wikipedia.org/wiki/NumPy" rel="noreferrer">NumPy</a>, pip (version 23.3.1), wheel (version 0.41.2), etc., and did some programming with those. I used the command <code>C:\Use...
<python><python-3.x><numpy><pip>
2023-10-26 06:22:24
9
2,687
sreeraj t
77,364,461
839,733
Find the length of the last word
<p>I'm working on the LeetCode <a href="https://leetcode.com/problems/length-of-last-word/description" rel="nofollow noreferrer">58. Length of Last Word</a>.</p> <blockquote> <p>Given a string s consisting of words and spaces, return the length of the last word in the string.</p> <p>A word is a maximal substring consis...
<python><python-itertools><python-operator>
2023-10-26 06:03:44
4
25,239
Abhijit Sarkar
77,364,235
4,451,521
How to efficiently select some data from a large trajectory set
<p><strong>The situation</strong></p> <p>I have one dataframe with one (well actually three but let's start with one) set of coordinates (X,Y) or <strong>trajectory</strong> (in two columns). For the sake to illustrate my point and to have some reproducible example let's use this code</p> <pre><code>import numpy as np ...
<python><pandas>
2023-10-26 05:05:34
2
10,576
KansaiRobot
77,364,184
1,068,378
AWS SAM Environment variable
<p>i was wondering if someone can help me here. I am devleoping a python SAM application in which i need to use environment variables. at the moment i am declaring my variables in template.yaml</p> <pre><code>Globals: Function: Timeout: 3 Environment: Variables: FMPREPKEY: &lt;myfmprepkey&gt; </...
<python><amazon-web-services><sam>
2023-10-26 04:47:55
1
319
user1068378
77,364,104
2,419,531
How to efficiently find pairs of nodes in a graph that when removed will cause the graph to split?
<p>Consider this simple biconnected graph (graph without <a href="https://networkx.org/documentation/stable/reference/algorithms/generated/networkx.algorithms.components.articulation_points.html" rel="nofollow noreferrer">articulation points</a>):</p> <pre class="lang-py prettyprint-override"><code>import networkx as n...
<python><python-3.x><graph><networkx><graph-theory>
2023-10-26 04:22:13
1
41,002
Saravana
77,364,093
7,144,427
TLSV1_ALERT_UNKNOWN_CA using self signed certificate and proxy.py?
<p>I'm trying to use a self signed certificate with <a href="https://github.com/abhinavsingh/proxy.py" rel="nofollow noreferrer">proxy.py</a> (v2.3.1). I found <a href="https://github.com/abhinavsingh/proxy.py/issues/1268" rel="nofollow noreferrer">this</a> issue but couldn't really find a solution there. My code is as...
<python><linux><ssl><openssl>
2023-10-26 04:19:32
0
1,636
wizzfizz94
77,364,000
18,649,992
Convert for loop to jax.lax.scan
<p>How does one convert the following (to accelerate compiling)? The <code>for</code> loop version works with <code>jax.jit</code>,</p> <pre><code>import functools import jax import jax.numpy as jnp @functools.partial(jax.jit, static_argnums=0) def func(n): p = 1 x = jnp.arange(8) y = jnp.zeros((n,)) ...
<python><index-error><jax>
2023-10-26 03:47:51
1
440
DavidJ
77,363,957
268,581
Using Grouper to group dataframe by various timeframes and charting
<p>Here's a Python program which does the following:</p> <ul> <li>Makes an API call to treasury.gov to retrieve data</li> <li>Stores the data in a Pandas dataframe</li> </ul> <pre><code>import requests import pandas as pd import matplotlib.pyplot as plt # ---------------------------------------------------------------...
<python><pandas><matplotlib>
2023-10-26 03:29:57
1
9,709
dharmatech
77,363,909
3,099,733
How to block execution until Jupyter widget's value has been changed?
<h2>Busy wait: NOT work</h2> <p>Given the following code:</p> <pre class="lang-py prettyprint-override"><code>from ipywidgets import IntsInput from IPython.display import display in_value = IntsInput(description=&quot;value&quot;) before = in_value.value print('before': before) display(in_value) while before == in_va...
<python><jupyter-notebook><ipywidgets>
2023-10-26 03:08:53
1
1,959
link89
77,363,673
3,162,975
Oauth 2.0 run flow for Youtube Data Api v3 not work - cache problem?
<p>I want to upload videos to youtube via command line (prompt) using the following code in python and the google api &quot;<strong>Youtube Data Api v3</strong>&quot;.</p> <p>When the code is executed for the first time, the <strong>Oauth 2.0 run flow</strong> start. A screen appears in the prompt asking for the <em>us...
<python><google-cloud-platform><oauth-2.0><youtube><youtube-data-api>
2023-10-26 01:41:47
1
3,599
Borja
77,363,596
327,694
How to get more word suggestions from Hunspell with pyhunspell
<p>I'm using hunspell with the pyhunspell wrapper. I'm calling:</p> <pre><code>hunspell.suggest(&quot;Yokk&quot;) </code></pre> <p>But this is returning only [&quot;Yolk&quot;, &quot;Yoke&quot;]. I saw that &quot;York&quot; is in the dictionary but is not being returned. Is there a way to return more than 2 suggestions...
<python><spell-checking><hunspell>
2023-10-26 01:06:20
1
5,610
Josep Valls
77,363,541
4,961,048
Python multiprocessor pool post-process
<p>I have a set of tasks to be executed (to the tune of millions) and I have to <code>POST</code> the result of each &quot;execution&quot;. The POST offers me a way to batch the results.</p> <p>I have the following skeleton :</p> <pre class="lang-py prettyprint-override"><code>def init_pool_processes(): global gath...
<python><multiprocessing>
2023-10-26 00:39:25
0
471
midi
77,363,447
395,857
Whenever I submit the first query, I always get an "error" with Gradio. But subsequent queries work fine. Why?
<p>I'm following the basic Gradio interface from the <a href="https://www.gradio.app/docs/interface" rel="nofollow noreferrer">Gradio documentation</a>:</p> <pre><code>import gradio as gr def greet(name): return &quot;Hello &quot; + name #+ &quot;!&quot; +a demo = gr.Interface(fn=greet, inputs=&quot;text&quot;, o...
<python><gradio>
2023-10-25 23:59:21
1
84,585
Franck Dernoncourt
77,363,429
1,524,372
Inconsistency in Enum with class mixing string formatting in Python 3.11
<p>I have been following the back and forth on Enum formatting in Python 3.11, see <a href="https://github.com/python/cpython/issues/100458" rel="nofollow noreferrer">https://github.com/python/cpython/issues/100458</a>.</p> <p>However I have a few mixins with classes that implement <code>__str__</code> and have been se...
<python><enums><python-3.11>
2023-10-25 23:53:08
1
311
Paul
77,363,316
268,581
How to resolve issues with a bar plot x-axis being overcrowded
<p>Here's a Python program which does the following:</p> <ul> <li>Makes an API call to treasury.gov to retrieve data</li> <li>Stores the data in a Pandas dataframe</li> <li>Plots the data as a bar chart</li> </ul> <pre><code>import requests import pandas as pd import matplotlib.pyplot as plt date = '1900-01-01' trans...
<python><pandas><matplotlib><time-series><bar-chart>
2023-10-25 23:08:15
1
9,709
dharmatech
77,363,105
1,514,682
How to visualize colmap export that contains Intrinsic and Extrinsic Camera Parameters using python
<p>I have a transforms.json file which contains Intrinsic and Extrinsic for 23 cameras. I would like to visualize those using Python, colmap, pycolmap and jupyternotebook. Below is a part of the .json file</p> <pre><code>{ &quot;w&quot;: 1920, &quot;h&quot;: 1080, &quot;fl_x&quot;: 1098.8550003271516, &quot;fl...
<python><camera-calibration><colmap>
2023-10-25 22:01:21
2
2,393
Khayam Gondal
77,363,017
8,279,172
python set element in dict by accessing non-existent element
<p>I want to add a new element to dictionary this way:</p> <pre class="lang-python3 prettyprint-override"><code>d[&quot;key1&quot;][&quot;key2&quot;][&quot;key3&quot;] = 10 </code></pre> <p>But I have to do it such way:</p> <pre class="lang-python3 prettyprint-override"><code>d[&quot;key1&quot;] = {} d[&quot;key1&quot;...
<python><dictionary>
2023-10-25 21:34:57
2
1,540
wowonline