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
βŒ€
78,802,454
9,381,966
Static Files Not Loading in Production in Django-React application
<p>I'm running a Django application in a Docker container, and I'm having trouble serving static files in production. Everything works fine locally, but when I deploy to production, the static files don't load, and I get 404 errors.</p> <p>Here are the relevant parts of my setup:</p> <p><strong>Django <code>settings.py...
<python><reactjs><django><nginx><amazon-ecs>
2024-07-27 21:03:48
2
1,590
Lucas
78,802,361
827,927
How to generate permutations with constraints
<p>I want to generate all possible lists of [&quot;x&quot;,&quot;y&quot;,&quot;z&quot;,1,2,3] that are ordered in ascending order. &quot;x&quot;, &quot;y&quot; and &quot;z&quot; can be any real numbers and so their order can be arbitrary. However, as 1&lt;2&lt;3, 1 must be before 2 and 2 must be before 3. So, for examp...
<python><algorithm><permutation><python-itertools>
2024-07-27 20:09:59
3
37,410
Erel Segal-Halevi
78,802,205
5,506,167
pycharm debugger too slow on every "step over"
<p>I am using pycharm to debug a django web app. When I click &quot;step over&quot; to direct debugger to the next line, around 50-100 background jobs launches in pycharm (as shown in the image which is taken from status bar of PyCharm) and it takes a few second(!) for the debugger to settle and show new values and be ...
<python><debugging><pycharm>
2024-07-27 18:48:56
0
1,962
Saleh
78,802,160
1,794,549
Create a PyObject with a pointer to a C function
<p>Let's say I have this Python function:</p> <pre><code>def foo(bar): bar() </code></pre> <p>And this C function</p> <pre><code>void bar() { } </code></pre> <p>How can I create a PyObject with Python C API that holds a pointer to bar function so I can call the Python function. Something like this</p> <pre><code>Py...
<python><cpython><python-c-api>
2024-07-27 18:26:50
1
1,099
Marko Devcic
78,801,991
11,099,842
How to access a nested dictionary with a tuple
<p>I have a nested dictionary that I want to access via a tuple. How to do that?</p> <pre><code> my_dict = { &quot;1&quot;: { &quot;a&quot;: &quot;hi&quot;, &quot;b&quot;: &quot;bye&quot; }, &quot;2&quot;: { &quot;a&quot;: { &quot;i&quot;: &quot;howdy&quot;}} } # Way 1: Works my_...
<python>
2024-07-27 16:59:45
1
891
Al-Baraa El-Hag
78,801,910
18,125,313
Why is it slower when storing the result of numpy.astype in a variable?
<p>The following two functions logically do the same thing, but <code>func2</code>, which stores the result in a temporary variable, is slower.</p> <pre class="lang-py prettyprint-override"><code>def func1(a): return a.astype(np.float64) / 255.0 def func2(a): t = a.astype(np.float64) return t / 255.0 </co...
<python><numpy><performance>
2024-07-27 16:26:51
2
3,446
ken
78,801,590
1,136,895
Tensorflow consumes both GPU and CPU Memory
<p>I have TensorFlow set up with GPU enabled on Debian. Upon using <code>tensorflow.keras.models.load_model</code> to load a model, I noticed that it utilizesoth GPU memory and CPU memory (the system's RAM). I'm curious to know if it's typical for TensorFlow to use some of my system's RAM in addition to GPU memory.</p...
<python><tensorflow><keras><tensorflow2.0><tensorflow-serving>
2024-07-27 14:04:48
0
1,351
Masoud
78,801,434
11,354,959
Test python application and SQL scripts
<p>I am creating application with Flask and I am using SQLAclhemy with it.</p> <p>I am currently writing some unit/integration test and I was wondering what is the best practise when it comes to add data to my inmemory db in python? Should I execute SQL scripts before I run my tests in a file? Should I execute SQL duri...
<python><sql><flask><pytest>
2024-07-27 12:48:46
1
370
El Pandario
78,801,372
169,992
Huggingface Mistral-Nemo-Instruct-2407 python script for text generation just hanging on Mac M3?
<p>I installed pytorch, transformers, and python-dotenv to run this script:</p> <pre><code>from transformers import pipeline from dotenv import load_dotenv import torch import os import json # from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline load_dotenv() device = &quot;cuda&quot; if torch.cuda...
<python><pytorch><nlp><huggingface-transformers><text-generation>
2024-07-27 12:24:40
0
80,366
Lance Pollard
78,801,248
6,556,388
pyspark .display() works but .collect(), .distinct() and show() don't
<p>I'm working with a pyspark dataframe in Azure Databricks and I'm trying to count how many unique (distinct) values a particular column has.</p> <blockquote> <p>Cluster: 14.3 LTS (includes Apache Spark 3.5.0, Scala 2.12) pandas 1.5.3 pyspark 3.3.0</p> </blockquote> <p>I can .display...
<python><apache-spark><pyspark><databricks>
2024-07-27 11:28:44
0
864
Diego Rodrigues
78,800,937
1,188,943
Change Enter line break character with shift+enter line break in Python
<p>How can I replace newline characters (\n) with a Shift+Enter equivalent in Python to maintain paragraph structure when working with text data? Are there any specific libraries or techniques to achieve this?</p> <p>I want to fill the textarea with selenium.</p>
<python><selenium-webdriver>
2024-07-27 08:51:40
2
1,035
Mahdi
78,800,904
6,223,275
Preview Version 5.0 interactive window hangs in Visual Studio Professional 2022 (64-bit) (Python)
<ul> <li><p>I am running the Python Development Workload on Microsoft Visual Studio Professional 2022 (64-bit) - Preview Version 17.11.0 Preview 5.0.</p> </li> <li><p>I am following the Python in Visual Studio tutorial <a href="https://learn.microsoft.com/en-us/visualstudio/python/tutorial-working-with-python-in-visual...
<python><visual-studio>
2024-07-27 08:31:24
1
1,366
Joe
78,800,844
6,243,129
Paddle OCR not able to extract single digits from image
<p>I am doing an image OCR using Paddle OCR. Below is the sample code I am using:</p> <pre><code>from paddleocr import PaddleOCR import os image_file = &quot;3_496.png&quot; ocr = PaddleOCR(use_gpu=True) image_path = os.path.join(os.getcwd(), image_file) result = ocr.ocr(image_path, cls=True) if None not in result: ...
<python><ocr><paddle-paddle><paddleocr><paddle>
2024-07-27 07:57:08
2
7,576
S Andrew
78,800,797
2,268,543
How to view the final prompt in a MultiQueryRetriever pipeline using LangChain?
<p>I am currently working on a project using the LangChain library where I want to retrieve relevant documents from a vector database and then generate answers based on these documents using the Ollama LLM.</p> <p>Below is my current implementation:</p> <pre class="lang-py prettyprint-override"><code>import logging lo...
<python><langchain><large-language-model><ollama>
2024-07-27 07:28:04
1
2,519
Rasik
78,800,653
1,188,943
Remove common company name suffixes in Python using regex
<p>I'm struggling to remove suffixes from some company names. The expected result is like below:</p> <p>Original Names:</p> <pre><code>Apple Inc. Sony Corporation Fiat Chrysler Automobiles S.p.A. Samsung Electronics Co., Ltd. </code></pre> <p>Cleared Names:</p> <pre><code>Apple Sony Fiat Chrysler Automobiles Samsung El...
<python><regex><string>
2024-07-27 06:10:57
3
1,035
Mahdi
78,800,160
3,486,684
How to annotate type of an `OrderedDict` that is initialized with literals?
<p>Suppose I have the following:</p> <pre class="lang-py prettyprint-override"><code>from collections import OrderedDict from dataclasses import dataclass @dataclass class HelloWorld: x: OrderedDict[str, int] a = OrderedDict([(&quot;a&quot;, 0), (&quot;c&quot;, 2), (&quot;b&quot;, 1)]) HelloWorld(a) &lt;--- # t...
<python><python-typing><ordereddictionary><pyright>
2024-07-26 23:31:04
2
4,654
bzm3r
78,800,053
197,738
Python, pandas parse number and string from string
<p>In Python, I want to parse a string and return the numeric portion (may or may not have decimal point) as a float and return the suffix as a string. Examples are:</p> <ul> <li><p>7.1inch -&gt; 7.1, inch</p> </li> <li><p>7.1” -&gt; 7.1, β€œ</p> </li> <li><p>7in -&gt; 7.0, in</p> </li> <li><p>-10dB -&gt; -10.0, dB</p> <...
<python><pandas><string><floating-point>
2024-07-26 22:19:19
3
421
tosa
78,799,762
6,626,632
Overlay a polar matplotlib axis over a geopandas map
<p>I would like to overlay a polar axis over a map of a GeoPandas GeoDataFrame centered at a specific point. The ultimate goal is for the plot on the polar axis to be exactly centered at the point. I have found a way to do this but it is hacky and I wonder if there is a better way.</p> <p>The problem is that the center...
<python><matplotlib><geopandas><polar-coordinates>
2024-07-26 20:13:06
2
462
sdg
78,799,730
1,892,433
Open with Python an R data.table saved as metadata in a Parquet file
<p>With R, I created a Parquet file containing a <code>data.table</code> as main data, and another <code>data.table</code> as metadata.</p> <pre><code>library(data.table) library(arrow) dt = data.table(x = c(1, 2, 3), y = c(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;)) dt2 = data.table(a = 22222, b = 45555) attr(dt, &...
<python><r><parquet><pyarrow><apache-arrow>
2024-07-26 20:00:40
1
1,552
julien.leroux5
78,799,483
7,706,098
Can not iterate "cbar" or "cmins" in multiple violinplot in a single plot
<p>I am trying to change colors of each violinplot in multiple plots in a single plot. I can change colors of the <em>bodies</em>, but I can not change the colors for <em>cbars</em>, <em>cmins</em>, <em>cmaxes</em>. How do I do this?</p> <pre><code>import matplotlib.pyplot as plt mock_data= [ [0,1,2,3,4,5,6...
<python><matplotlib>
2024-07-26 18:24:50
1
301
Redshoe
78,799,460
674,039
Why does re._compile exist?
<p>Here is <a href="https://github.com/python/cpython/blob/v3.12.4/Lib/re/__init__.py#L226" rel="nofollow noreferrer"><code>re.compile</code></a>:</p> <pre><code>&gt;&gt;&gt; import re, inspect &gt;&gt;&gt; print(inspect.getsource(re.compile)) def compile(pattern, flags=0): &quot;Compile a regular expression patter...
<python><python-re>
2024-07-26 18:14:29
0
367,866
wim
78,799,407
22,886,184
JavascriptException Stale element not found after (multiple) redirects
<p>I'm building a SeleniumBase scraper that takes a set of tasks and performs them on a website. After performing some actions on the site the script calls <code>driver.execute_script(&quot;return window.variable;&quot;)</code>. This works fine on all domains I've scraped even with any redirects after clicks.</p> <p>To...
<python><selenium-webdriver><seleniumbase>
2024-07-26 17:58:06
0
537
Victor
78,799,303
10,181,236
read messages from public telegram channel using telethon
<p>I am using Telethon to automate some stuff from Telegram channels. I have already obtained my API key, hash, and token and I can start a new session using Telethon.</p> <p>The problem is that when a new message arrives from some selected channels, I want to print the text but the code I wrote does not seem to work a...
<python><telegram><telethon>
2024-07-26 17:25:03
1
512
JayJona
78,799,154
10,335,909
How to filter Pandas Dataframe to integer values?
<p>I have a dataframe column with string values. I want to filter to the rows that have integer. I can do the below to find if it's numeric, but this would return floats as well.</p> <pre><code>result = pd.to_numeric(df['col1'], errors='coerce').notnull() </code></pre> <p>'1' should be returned</p> <p>'1.1' should not ...
<python><pandas>
2024-07-26 16:40:20
4
1,098
Melissa Guo
78,798,926
276,193
Calling module from jupyter notebook inside of poetry project reults in 'No module named' error
<p>I'm working on a module with poetry with a directory structure like</p> <pre><code>./ /my_module (module files) /tests test_thing.py /jupyter demo.ipynb </code></pre> <p>In the test files and jupyter notebooks there is import code like</p> <pre><code>from my_module import thingy, other_thi...
<python><pytest><jupyter><python-poetry>
2024-07-26 15:40:17
1
16,283
learnvst
78,798,871
8,438,604
Using pymongo installed via virtualenv and Ansible returns an error
<p>Since it's good practice to install pip modules in virtual environment, I have the following task in place:</p> <pre><code>- name: Install python packages ansible.builtin.pip: name: - pymongo virtualenv: /home/user/.venv </code></pre> <p>However, the taks that supposed to use pymongo returns an error...
<python><python-3.x><ansible><virtualenv>
2024-07-26 15:25:38
1
391
matteo-g
78,798,654
5,786,649
Python: trying to access instance attributes in self.__setattr__
<p>I was trying to create a <code>dataclass</code> with shorter aliases for longer fields. Since I wanted to be able to add new fields (with long and short names) without having to write a <code>@property</code> decorated &quot;getter&quot; and a <code>@short_name.setter</code> decorated &quot;setter&quot;, I decided t...
<python><properties><python-dataclasses><setattr>
2024-07-26 14:40:03
1
543
Lukas
78,798,620
7,919,597
Why does my Pydantic model contain an extra attribute when popupated from an object with extra=ignore?
<p>The title says it all:</p> <p>Why does my Pydantic model contain an extra attribute when popupated from an object with extra=ignore?</p> <pre><code>from pydantic import BaseModel, ConfigDict # pydantic 2.4.2 class Test(BaseModel): a: int model_config = ConfigDict(extra='ignore', ...
<python><pydantic><pydantic-v2>
2024-07-26 14:31:01
1
7,233
Joe
78,798,569
20,920,790
How to add trigger for run dag into another dag (with decorators) in Airflow?
<p>I got 2 dags in same dags folder:</p> <ol> <li>dag_update_database (dag_update_database.py)</li> <li>dag_add_client_loyalty (dag_updade_clients_loyalty.py)</li> </ol> <p>I can run dag_add_client_loyalty with this code, but I get error:</p> <pre><code>[2024-07-29, 14:34:15 MSK] {task_command.py:423} INFO - Running &...
<python><airflow>
2024-07-26 14:21:20
2
402
John Doe
78,798,406
16,883,182
What's the simplest way to annotate a function/method parameter to accept an overlapping Union of types?
<p>In all my functions that allow an overlapping union of types, I already have special handling that checks all parameters to ensure that there are no types which don't support operations with each other.</p> <p>In my specific use-case, I'm writing functions that accept any of <code>int</code>, <code>float</code>, <co...
<python><generics><python-typing>
2024-07-26 13:45:19
0
315
I Like Python
78,798,373
850,781
Numpy 2 has a separate float64(nan) - how to get rid of it?
<p>It appears that Numpy 2 introduced its own separate <code>float64(nan)</code> - different from <code>np.nan</code>. Now regression tests fail because while</p> <pre><code>&gt;&gt;&gt; np.nan is np.nan True </code></pre> <p>we now have</p> <pre><code>&gt;&gt;&gt; np.nan is np.float64(&quot;nan&quot;) False </code></p...
<python><numpy><nan>
2024-07-26 13:38:26
1
60,468
sds
78,798,250
3,070,421
Plotly updatemenus - Only update specific parameters
<p>I'm looking for a way to have two updatemenu buttons on a plotly figure. One changes the data and the y-axis title and one switches from linear to log scale. Broadly the code below works but I lose something depending on which method I use.</p> <p>If the <code>buttons</code> method is <code>update</code> then when...
<python><plotly>
2024-07-26 13:14:34
1
2,179
Sobigen
78,798,106
12,057,138
AWS Lambda python log file is not created
<p>I have a Python AWS lambda with a logger that generates two different log files:</p> <pre><code>LOG = f&quot;/tmp/{uuid.uuid1()}_log.log&quot; SLOW_LOG = f&quot;/tmp/{uuid.uuid1()}_slow.log&quot; logging.basicConfig(level=logging.INFO, format=&quot;%(levelname)s - %(message)s&quot;, ...
<python><logging><aws-lambda>
2024-07-26 12:40:09
0
688
PloniStacker
78,797,584
12,350,600
Python nested dictionary to Tree
<p>I am trying to display my nested dictionary as a Tree.</p> <pre><code>data = {&quot;L1&quot; : {&quot;sub L1&quot; : &quot;sub sub L1&quot;}, &quot;L2&quot; : &quot;sub L2&quot;, &quot;L3&quot; : {&quot;sub L3&quot; : {&quot;sub ...
<python><dictionary><plot><tree>
2024-07-26 10:38:50
2
394
Kruti Deepan Panda
78,797,526
2,485,799
Is using a Pandas Dataframe as a read-only table scalable in a Flask App?
<p>I'm developing a small website in Flask that relies on data from a CSV file to output data to a table on the frontend using JQuery.</p> <p>The user would select an ID from a drop-down on the front-end, then a function would run on the back-end where the ID would be used as a filter on the table to return data. The d...
<python><pandas><flask><scalability>
2024-07-26 10:29:24
3
6,883
GreenGodot
78,797,499
24,191,255
Cubic spline interpolation in Python - why is it not working?
<p>I would like to apply a 2nd order low-pass Butterworth filter on my data, and then use cubic spline interpolation for resampling at every 1 meter in Python.</p> <p>I tried to prevent having non-finite values but I still receive the following ValueError:</p> <pre class="lang-none prettyprint-override"><code>cs_v = Cu...
<python><interpolation><spline><butterworth>
2024-07-26 10:23:50
1
606
MΓ‘rton HorvΓ‘th
78,797,378
19,520,266
Dynamic numbers of datasets with facebook Hydra
<p>I am currently working on a data science project where I can use different datasets, but on top of that I can use some of them in a dynamic manner (e.g I only use dataset1, or dataset1+dataset2, or dataset2+dataset3 etc).</p> <p>Currently, I have one yaml file for each of these datasets (containing the necessary inf...
<python><fb-hydra>
2024-07-26 09:57:06
1
303
Lelouch
78,797,187
188,331
BertTokenizer vocab_size remains unchanged after adding tokens
<p>I am using HuggingFace <code>BertTokenizer</code> and adding some tokens to it. Here are the codes:</p> <pre><code>from transformers import BertTokenizer tokenizer = BertTokenizer.from_pretrained('fnlp/bart-base-chinese') print(tokenizer) </code></pre> <p>which outputs:</p> <pre><code>BertTokenizer(name_or_path='fn...
<python><huggingface-transformers><huggingface><huggingface-tokenizers>
2024-07-26 09:14:28
1
54,395
Raptor
78,797,161
18,769,241
Can I copy paste Python 2.7 packages from lib/site-packages from Windows to Ubuntu?
<p>I am moving to Ubuntu 22.04 from Windows 10 and I was wondering if I could skip installing again all the packages I did on my Windows 10 machine on Python 2.7. Is it possible to save the package folders and paste them into the Python installation folder in Ubuntu?</p>
<python><windows><ubuntu><site-packages>
2024-07-26 09:08:21
1
571
Sam
78,797,159
5,423,259
Polygons elongation ratio calculation with geopandas - problem with creating a geodataframe with results
<p>I have a polygon shapefile (actually, there are 170 such files) and want to calculate the elongation ratio for each polygon. The elongation ratio is the ratio of the short to the long side of the minimum rotated rectangle around the polygon. I have the following script which works well up to the point I want to crea...
<python><geopandas><shapely>
2024-07-26 09:07:26
1
358
ABC
78,797,091
9,640,238
Replace img tag with in-line SVG with BeautifulSoup
<p>I have an HTML file produced by pandoc, where SVG illustrations have been embedded. The SVG content is encoded in base64 and included in the <code>src</code> attribute of <code>img</code> elements. It looks like this:</p> <pre class="lang-html prettyprint-override"><code>&lt;figure&gt; &lt;img role=&quot;img&quo...
<python><html><svg><beautifulsoup>
2024-07-26 08:48:04
1
2,690
mrgou
78,796,974
5,629,527
SHAP values for linear model different from those calculated manually
<p>I train a linear model to predict house price, and then I compare the Shapley values calculation manually vs the values returned by the <code>SHAP</code> library and they are slightly different.</p> <p>My understanding is that for linear models the Shapley value is given by:</p> <pre><code>coeff * features for obs -...
<python><machine-learning><shap><xai>
2024-07-26 08:22:09
1
1,134
Sole Galli
78,796,866
21,049,944
Polars - when/then conditions from dict
<p>I would like to have a function that accept list of conditions as parameter and filter given dataframe by all of them. Pseudocode should look like this:</p> <pre><code>def Filter(df, conditions = [&quot;a&quot;,&quot;b&quot;]): conditions_dict = { &quot;a&quot;: pl.col(&quot;x&quot;) &lt; 5, &qu...
<python><dataframe><python-polars>
2024-07-26 07:58:37
1
388
Galedon
78,796,805
3,083,195
avg() over a whole dataframe causing different output
<p>I see that <code>dataframe.agg(avg(Col)</code> works fine, but when i calculate avg() over a window over whole column(not using any partition), i see different results based on which column i use with orderBy.</p> <p>Sample code:</p> <pre><code>from pyspark.sql import SparkSession spark = SparkSession.builder.appNam...
<python><dataframe><apache-spark><pyspark><rdd>
2024-07-26 07:39:05
1
1,707
anurag86
78,796,733
6,999,569
Python WFDB library has no attribute ann2rr
<p>I am trying to extract RR interval data from ecg annotation files from physionet by using the <code>ann2rr</code> function according to documentation:</p> <pre class="lang-py prettyprint-override"><code>from IPython.display import display import matplotlib.pyplot as plt %matplotlib inline import numpy as np import o...
<python><python-import>
2024-07-26 07:20:31
1
846
Manfred Weis
78,796,237
5,595,678
django OAuth Toolkit not getting redirect URI
<p>I am using Django OAuth toolkit and using the following code for OAuth implementation</p> <pre><code>import requests from django.http import JsonResponse from django.shortcuts import redirect, render from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required...
<python><django><session><django-oauth><django-oauth-toolkit>
2024-07-26 04:41:20
1
1,765
Johnny
78,796,192
1,935,424
tkinter: what is the difference between transient() and wm_transient()?
<p>Using tkinter in Python. Created a dialog box from tk.Toplevel()</p> <p>After reading various posts and docs:</p> <pre><code> self.resizable(width=False, height=False) self.wm_transient(self._mainwin) self.transient(self._mainwin) self.wait_visibility() self.grab_set() self.update_idletasks() ...
<python><tkinter>
2024-07-26 04:09:36
1
899
JohnA
78,796,065
457,030
How to embed Python to .Net?
<p>I tried to embed Python to .Net using pythonnet based on the docs <a href="https://pythonnet.github.io/pythonnet/dotnet.html" rel="nofollow noreferrer">here</a> and <a href="https://github.com/pythonnet/pythonnet#embedding-python-in-net" rel="nofollow noreferrer">here</a>.</p> <p>Here are my code</p> <pre><code>Runt...
<python><c#><.net><python.net>
2024-07-26 02:49:15
1
4,315
Syaiful Nizam Yahya
78,795,944
1,471,980
how do you merge values in rows, replace nan values in pandas
<p>I am doing some manipulation on a data frame:</p> <pre><code>df Node Interface Speed carrier 1-May 9-May 2-Jun 21-Jun Server1 internet1 10 ATT 20 30 50 90 Server1 wan3.0 20 Comcast NaN NaN NaN 100 Server1 ...
<python><pandas>
2024-07-26 01:39:04
1
10,714
user1471980
78,795,749
880,783
How can I invert `dataclass.astuple`?
<p>I am trying to construct a hierarchy of <code>dataclass</code>es from a tuple, like so:</p> <pre class="lang-py prettyprint-override"><code>from dataclasses import astuple, dataclass @dataclass class Child: name: str @dataclass class Parent: child: Child # this is what I want p = Parent(Child(&quot;Tim&qu...
<python><python-dataclasses>
2024-07-25 23:29:40
2
6,279
bers
78,795,740
3,284,297
Sort Pandas dataframe by Sub Total and count
<p>I have a very large dataset called bin_df.</p> <p>Using pandas and the following code I've assigned sub-total &quot;Total&quot; to each group:</p> <pre><code> bin_df = df[df[&quot;category&quot;].isin(model.BINARY_CATEGORY_VALUES)] bin_category_mime_type_count_df = ( bin_df.groupby([&quot...
<python><pandas><group-by>
2024-07-25 23:24:55
2
423
Charlotte
78,795,739
8,037,521
Speed up / parallelize multivariate_normal.pdf
<p>I have multiple Nx3 points, and I sequentially generate a new value for each from its corresponding multivariate Gaussian, each with 1x3 mean and 3x3 cov. So, together, I have arrays: Nx3 array of points, Nx3 array of means and Nx3x3 array of covs.</p> <p>I only see how to do it with the classic for-loop:</p> <pre>...
<python><numpy>
2024-07-25 23:24:51
1
1,277
Valeria
78,795,722
2,136,286
gcloud mistakes event trigger for storage trigger
<p>There's a cloud function in Python that processes some data when a file is uploaded to firebase's bucket:</p> <pre><code>@storage_fn.on_object_finalized(bucket = &quot;my-bucket&quot;, timeout_sec = timeout_sec, memory = memory, cpu = cpu, region='us-central1') def validate_file_upload(event: storage_fn.CloudEvent[s...
<python><firebase><google-cloud-functions><google-cloud-storage><gcloud>
2024-07-25 23:16:48
1
676
the.Legend
78,795,712
395,857
How to find all occurrences of a substring in a string while ignoring some characters in Python?
<p>I'd like to find all occurrences of a substring while ignoring some characters. How can I do it in Python?</p> <p>Example:</p> <pre class="lang-py prettyprint-override"><code>long_string = 'this is a t`es&quot;t. Does the test work?' small_string = &quot;test&quot; chars_to_ignore = ['&quot;', '`'] print(find_occurr...
<python><string><python-re>
2024-07-25 23:12:50
2
84,585
Franck Dernoncourt
78,795,641
579,204
How to find rows with value on either side of a given value?
<p>Python, Pandas, I have a dataframe containing datetimes and values.</p> <pre class="lang-py prettyprint-override"><code># Create an empty DataFrame with 'timestamp' and 'value' columns df = pd.DataFrame(columns=['timestamp', 'value']) df.set_index('timestamp', inplace=True) </code></pre> <p>I append data to that fra...
<python><pandas><search><interpolation>
2024-07-25 22:36:15
3
411
Dave
78,795,606
2,655,092
FFprobe not reflecting MP4 dimension edits
<p>I'm trying to edit MP4 width &amp; height without scaling.</p> <p>I'm doing that by editing <code>tkhd</code> &amp; <code>stsd</code> boxes of the MP4 header.</p> <ul> <li><code>exiftool</code> will show the new width &amp; height but <code>ffprobe</code> will <strong>not</strong>.</li> </ul> <p>Before editing:</p> ...
<python><video><mp4><ffprobe><exiftool>
2024-07-25 22:17:20
1
3,085
James W.
78,795,597
54,873
How do I copy an individual Cell's conditional formatting using Openpyxl?
<p>I'm trying to move one set of Excel cells to another location in a workbook using python's <code>openpyxl</code>, offset by some columns. The source sheet has some cells that use conditional formatting.</p> <p>In good news, <code>move_range</code> does much of the work. But I cannot for the life of me figure out how...
<python><openpyxl>
2024-07-25 22:11:10
1
10,076
YGA
78,795,514
382,982
Unable to use implicit IAM/role-based auth when using Boto3 inside Docker on EC2
<p>I've run into a frustrating edge case that I'm now having to either introduce custom logic to work around or solve properly.</p> <p>I'm running a Django application inside a Docker container on EC2. I'm using an IAM role attached to the instance to grant it access to a particular S3 bucket and set of actions. This i...
<python><amazon-web-services><docker><amazon-ec2><boto3>
2024-07-25 21:34:36
2
10,529
pdoherty926
78,795,407
7,385,563
load a model from checkpoint folder in pyTorch
<p>I am trying to load a model from a certain checkpoint and use it for inference. The checkpoint folder looks like this. How do I load the model in torch from this folder. The <a href="https://pytorch.org/tutorials/recipes/recipes/saving_and_loading_a_general_checkpoint.html" rel="nofollow noreferrer">resources</a> I ...
<python><pytorch><checkpointing>
2024-07-25 20:57:29
1
691
afsara_ben
78,795,318
8,379,035
How to Use a Single INSERT INTO Statement for Multiple Rows in Python?
<p>I’m currently working on a Discord Python bot where I loop through a list of <a href="https://discordpy.readthedocs.io/en/latest/api.html?highlight=forumtag#discord.ForumTag" rel="nofollow noreferrer">ForumTags</a> and generate an <code>INSERT INTO</code> SQL statement for each object to insert data into a MySQL dat...
<python><sql><mysql><sql-insert>
2024-07-25 20:28:15
1
891
Razzer
78,795,251
496,289
How to capture call inside a with block?
<p>I have some code with a testcase for it. It works fine.</p> <pre><code>import pysftp from unittest import mock remote_file_name = 'remote_file_name' local_path = 'local/path/to/file' def open_sftp_connection(hostname): return pysftp.Connection(hostname, username='usr', password='pswd') def sftp_upload_try(loc...
<python><mocking><pytest><pytest-mock>
2024-07-25 20:04:15
0
17,945
Kashyap
78,795,087
4,306,274
How to remove the large left and right paddings due to "lines+markers" lines?
<p>How to remove the large left and right paddings due to &quot;lines+markers&quot; lines?</p> <pre><code>import numpy as np import pandas as pd import plotly.graph_objects as go count = 100 df = pd.DataFrame( { &quot;A&quot;: np.random.randint(10, 20, size=(count)), &quot;B&quot;: np.random.randi...
<python><plotly>
2024-07-25 19:16:12
1
1,503
chaosink
78,795,062
9,438,845
Can't connect to MongoDB server with Tableau or Python but can with Compass on Windows 10
<p>It was extremely easy accessing MongoDB server by pasting conn string into MongoDB Compass on Windows 10 but when it comes to Python or Tableau it returns errors</p> <p>For Python its either timout or:</p> <pre><code>Configuration Error: The DNS query name does not exist: _mongodb._tcp.mac88stage.sui9p.mongodb.net. ...
<python><mongodb><tableau-desktop><mongodb-biconnector>
2024-07-25 19:09:17
1
309
Alexander Ka
78,794,702
11,878,472
Read multiple files parallel into separate dataframe in Pyspark
<p>I am trying to read large txt files into dataframe. Each file is 10-15 GB in size,</p> <p>as the IO is taking long time. I want to read multiple file in parallel and get them in separate dataframe.</p> <p>I tried below code</p> <pre><code>from multiprocessing.pool import ThreadPool def read_file(file_path): retu...
<python><pyspark><databricks>
2024-07-25 17:26:59
0
411
Tejas
78,794,664
3,490,622
Scipy minimization problem - x never changes
<p>I am trying to solve the following problem: I have a sample of stores selected by geography, and I'd like to select 20% of the sample in such a way that the fraction of sales per geography for the selection mimics that of the overall sales distribution by geography. I tried several iterations of the code below, but...
<python><scipy><scipy-optimize>
2024-07-25 17:17:38
0
1,011
user3490622
78,794,566
864,245
Iterate over list of strings to retrieve groups of strings
<p>Given the following list:</p> <pre class="lang-py prettyprint-override"><code>inp = [&quot;arg1:&quot;, &quot;list&quot;, &quot;of&quot;, &quot;args&quot;, &quot;arg2:&quot;, &quot;other&quot;, &quot;list&quot;] </code></pre> <p>How can I develop a dictionary like this?</p> <pre class="lang-py prettyprint-override">...
<python><python-3.x>
2024-07-25 16:48:11
7
1,316
turbonerd
78,794,511
1,273,987
How can I set a python f-string format programmatically?
<p>I would like to set the formatting of a large integer in an fstring programmatically. Specifically, I have an integer that can span several orders of magnitude and I'd like to print it using the underscore &quot;_&quot; delimiter, e.g.</p> <pre class="lang-py prettyprint-override"><code>num = 123456789 print(f&quot;...
<python><f-string>
2024-07-25 16:36:41
2
2,105
Ziofil
78,794,242
610,569
How to convert JSONL to parquet efficiently?
<p>Given a jsonl file like this:</p> <pre><code>{&quot;abc1&quot;: &quot;hello world&quot;, &quot;foo2&quot;: &quot;foo bar&quot;} {&quot;foo2&quot;: &quot;bar bar blah&quot;, &quot;foo3&quot;: &quot;blah foo&quot;} </code></pre> <p>I could convert it to a dataframe like this:</p> <pre class="lang-py prettyprint-overr...
<python><pandas><parquet><jsonlines>
2024-07-25 15:31:39
3
123,325
alvas
78,794,183
5,661,667
scipy.special.eval_hermite with complex argument
<p>Does the scipy.special eval_hermite function only support real arguments? From the documentation (<a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.eval_hermite.html" rel="nofollow noreferrer">https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.eval_hermite.html</a>), I assum...
<python><scipy><polynomials>
2024-07-25 15:19:25
1
1,321
Wolpertinger
78,794,103
5,110,551
Mocking or monkey patching a slow loading resource that loads on import
<p>I have 1 file which loads a particular resource ( from a file ) that takes a while to load.</p> <p>I have a function in <strong>another</strong> file which uses that resource by importing it first. When that resource is first imported, it loads and takes a bit.</p> <p>However, when I'm testing that function that req...
<python><testing><mocking><pytest><monkeypatching>
2024-07-25 15:04:28
1
309
Sam
78,793,963
1,256,041
Different Python versions for different Bazel targets?
<p>I have many <code>py_library</code>, <code>py_binary</code> and <code>py_test</code> targets.</p> <p>Some of these must run against <code>3.9.16</code> (constraint outside of my control) and others use <code>3.10.6</code> (in order to get more recent features).</p> <p>In my <code>WORKSPACE</code>, I specify my toolc...
<python><bazel><bazel-python>
2024-07-25 14:37:50
1
37,819
sdgfsdh
78,793,821
14,463,396
Creating/Updating an excel file with slicers from python
<p>I have some python code which creates a few pandas data frames which I need to put into a spreadsheet, with different data on multiple sheets and with slicers for easy filtering. This then gets sent out so others can easily see/filter the data. Currently, I manually copy and paste the updated tables into a templat...
<python><excel><openpyxl><pywin32><xlsxwriter>
2024-07-25 14:12:01
1
3,395
Emi OB
78,793,812
3,636,909
How can I apply a transformation only once in open3D
<p>I want to apply a simple rotation to my 3D model, say 10Β° pitch, with respect to the recent rotation only once but the model keeps rotating indefinitely. I tried using rotation matrix in a transformation but I get the same issue.</p> <p>Here is an example code:</p> <pre><code>from colorama import init import numpy a...
<python><open3d>
2024-07-25 14:09:37
2
2,334
Ja_cpp
78,793,802
4,505,998
Detect precision loss in numpy floats
<p>If the difference between two numbers is too large, the smallest number will be &quot;lost&quot;. Does this raise any flag that I can check?</p> <p>In float32, the significant has 24 binary digits, therefore if the difference between numbers is greater than 10^7.2, the smaller number will be lost. Obviously, I could...
<python><numpy><floating-point><precision>
2024-07-25 14:07:18
1
813
David DavΓ³
78,793,796
5,507,132
Leave one out encoding on test set with transform
<p><strong>Context</strong>: When preprocessing a data set using sklearn, you use <code>fit_transform</code> on the <strong>training</strong> set and <code>transform</code> on the <strong>test</strong> set, to avoid data leakage. Using leave one out (LOO) encoding, you need the target variable value to calculate the en...
<python><machine-learning><scikit-learn><encoding>
2024-07-25 14:05:44
1
333
Jelle
78,793,568
1,471,980
how do you pick the max value of each row of certain columns in pandas
<p>I have this data frame:</p> <p>df</p> <pre><code>Node Interface Speed Band_In carrier 1-Jun 10-Jun Server1 wan1 100 80 ATT 80 30 Server1 wan2 100 60 Sprint 60 30 Server1 wan3 100 96 Verizon ...
<python><pandas>
2024-07-25 13:22:53
1
10,714
user1471980
78,793,443
2,207,840
Convert '3' to numpy.dtypes.Int64DType
<p>I have strings containing str representations of numpy values. I also have a list of the original dtypes, such as numpy.dtypes.Int64DType. I do not know all possible dtypes in advance. I can for the life of me not figure out how to convert the string back to a scalar of the correct dtype.</p> <pre class="lang-py pre...
<python><numpy>
2024-07-25 12:56:23
1
3,513
Eike P.
78,793,368
100,129
How do I find the smallest circle that can enclose a polygon?
<p>Using python, how do I find the smallest circle that can enclose a polygon?</p> <p>A polygon is defined as a set of coordinates that map the vertices inside a 2D plane.</p> <p><strong>Guidelines</strong>:</p> <p><strong>Input</strong>: A list of tuples representing the coordinates of the polygon’s vertices. For exa...
<python><algorithm><computational-geometry>
2024-07-25 12:41:37
4
1,805
makeyourownmaker
78,793,248
12,990,915
How to remove large space between rows in matplotlib plot?
<p>Code:</p> <pre><code>fig, axes = plt.subplots(2, 6) for row in axes: for ax in row: ## Set limits ax.set_xlim(-1, 1) ax.set_ylim(-1, 1) ## Set aspect ratio ax.axis('scaled') ## Plot plt.tight_layout(pad=0.5) plt.show() </code></pre> <p>Output: <a href="https://i.sstatic...
<python><matplotlib>
2024-07-25 12:15:23
2
383
user572780
78,793,132
241,552
Python: init exception from another (like raise ... from but with no raise)
<p>I am working on a piece of FastAPI app code that (already) has some exception handling, where handlers receive exceptions as function arguments, some exceptions are converted into other exceptions and then are passed on to other handler functions. My task is to log them, and I would like to be able to keep all the s...
<python><exception>
2024-07-25 11:51:00
1
9,790
Ibolit
78,793,130
4,599,564
How to check if one wallet address have already called a method on an EVM contract (PYTHON)
<h2>Introduction</h2> <p>I have a list of wallets and I want to ensure that a contract function is called only once. To achieve this, I iterate through the wallets, check if each wallet has already called that function, and if not, I proceed to call it. <em>(I'm testing on Linea and Base blockchains buy I'm looking for...
<python><ethereum><web3py>
2024-07-25 11:50:17
1
1,251
Juan Antonio TubΓ­o
78,792,953
6,714,667
from redis.commands.search.field import TagField, TextField, VectorField ModuleNotFoundError: No module named 'redis.commands' ERROR
<p>from redis.commands.search.field import TagField, TextField, VectorField ModuleNotFoundError: No module named 'redis.commands'</p> <p>i have the above - and am using redis 3.5.3 how can i recitfy this?</p>
<python><redis>
2024-07-25 11:02:26
1
999
Maths12
78,792,885
380,111
How do i shift the axis of a chart in plotly
<p>I'm trying to make this ridgeplot chart in plotly and its mostly working ok, but for some reason the top trace is getting cut off and i can't figure out how to move the trace down a bit. I can do it manually by dragging the axis</p> <p>the code i have</p> <pre><code>for i, time_unit in enumerate(time_units): fig...
<python><plotly>
2024-07-25 10:48:15
2
1,565
Nathaniel Saxe
78,792,882
100,129
How do I add 'week of year' and 'day of year' columns to a python datatable?
<p>There is currently (version 1.1.0) no python <code>datatable.time.week()</code> or <code>datatable.time.day_of_year()</code> functions.</p> <p>Here is some example data:</p> <pre><code>from datetime import date import datatable as dt DT = dt.Frame({&quot;Date&quot;: [&quot;2021-05-24&quot;, &quot;2021-06-26&quot;,...
<python><datetime><python-datetime><py-datatable>
2024-07-25 10:47:59
1
1,805
makeyourownmaker
78,792,758
11,357,695
Uninstall package with non-python files that weren't in distribution
<p>I have a python app that has been deposited on pypi as described <a href="https://packaging.python.org/en/latest/tutorials/packaging-projects/" rel="nofollow noreferrer">here</a>. The app runs an external software (<a href="https://blast.ncbi.nlm.nih.gov/doc/blast-help/downloadblastdata.html" rel="nofollow noreferr...
<python><package><delete-file><pypi><pyproject.toml>
2024-07-25 10:19:00
1
756
Tim Kirkwood
78,792,498
11,748,924
Remove blank area of matplotlib between distance of zero for multivariate time series
<p>I have two time series:</p> <ol> <li>First row is prediction</li> <li>second row is ground truth</li> </ol> <p><a href="https://i.sstatic.net/ZPbUCKmS.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/ZPbUCKmS.png" alt="enter image description here" /></a></p> <p>I want remove this red area, where it sh...
<python><matplotlib>
2024-07-25 09:22:16
1
1,252
Muhammad Ikhwan Perwira
78,792,386
6,936,582
Get cumulative weight of edges without repeating already traversed paths
<p>I have a water pipe network where each node is a house and each edge is a pipe connecting houses. The edges have a water volume as an attribute.</p> <p>I want to calculate the total volume reaching node 13.</p> <p>It should sum to <code>5+2+1+6+0+3+14+4+12+5+8+10+6+9=85</code></p> <p><a href="https://i.sstatic.net/p...
<python><networkx>
2024-07-25 09:01:57
1
2,220
Bera
78,792,381
5,595,678
Enable wildcard redirect_uri and disable code verification
<p>I am using Django OAuth toolkit in a intentionally vulnerable application. I am painting a scenario in which for example I there is a client application with <code>redirect_uri</code> <code>abc.com</code>. I want to show to the user that in OAuth 2.0 if the <code>redirect_uri</code> is not specifically well taken ca...
<python><oauth-2.0><oauth><access-token><django-authentication>
2024-07-25 09:00:37
0
1,765
Johnny
78,792,353
7,112,039
Celery class based tasks found in the worker, but gets NotRegistered when consumed
<p>I am configuring Celery like that</p> <pre class="lang-py prettyprint-override"><code>from celery import Celery from settings.config import settings celery_app = Celery( broker=settings.RABBITMQ_URL, backend=&quot;rpc://&quot;, ) celery_app.config_from_object(settings.CELERY_SETTINGS_MODULE) celery_app.au...
<python><celery>
2024-07-25 08:54:25
1
303
ow-me
78,792,196
4,701,852
Overpass API & Road Lanes
<p>I've written a script in Python that, given a lat/long, generates a geojson with the roads edges, pedestrian crosses and lanes. It looks like this:</p> <pre><code>def fetch_intersection_data(lat, lon, radius: int = 20): &quot;&quot;&quot; Fetch intersection data from OpenStreetMap using Overpass API and conv...
<python><gis><openstreetmap><overpass-api>
2024-07-25 08:20:15
1
361
Paulo Henrique PH
78,792,162
1,082,349
Multi-level rolling average with missing values
<p>I have data on frequencies (<code>N</code>), for combinations of [from, to, subset], and the month. Importantly, when N=0, the row is missing.</p> <pre><code> N from to subset month 1996-01-01 8.956799 1 2 0 1996-0...
<python><pandas><python-datetime>
2024-07-25 08:12:47
1
16,698
FooBar
78,792,124
10,855,529
Cast columns that might not exist in Polars
<p>I want to cast a column to another type, but there is a possibility that the column does not exist in the df.</p> <pre class="lang-py prettyprint-override"><code>import polars as pl import polars.selectors as cs # Sample DataFrame data = { &quot;viewCount&quot;: [100, 200, 300], &quot;likeCount&quot;: [10, ...
<python><python-polars>
2024-07-25 08:04:58
1
3,833
apostofes
78,791,781
511,302
How to encode unicode to bytes, so that the original string can be retrieved? in python 3.11
<p>In python 3.11 we can encode a string like:</p> <p>string.encode('ascii', 'backslashreplace')</p> <p>Which works neatly for say: <code>hellΓΆ</code> =&gt; <code>hell\\xf6</code></p> <p>However when I insert <code>hellΓΆ w\\xf6rld</code> I get <code>hell\\xf6 w\\xf6rld</code> (notice the second one has an literal part ...
<python><character-encoding>
2024-07-25 06:38:00
1
9,627
paul23
78,791,738
630,971
MultiLabelBinarizer: inverse_transform How can get a list of labels sorted according to their probability?
<p>I am doing a multi label classification and I use MultiLabelBinarizer to translate the list of labels into Zeros and Ones.</p> <p>I could get the Labels using inverse_transform which is super. However, in a case where I want to rank the class based on their probability, i.e the higher the probability, the better the...
<python><sorting><scikit-learn><classification><multilabel-classification>
2024-07-25 06:26:08
1
472
sveer
78,791,669
8,621,823
How does python's open() read mode and read binary mode deal with null bytes and f.seek?
<p>I did 2 experiments</p> <ol> <li>rb mode</li> <li>r mode</li> </ol> <pre><code>with open(&quot;small_file.txt&quot;, &quot;w&quot;) as f: f.seek(2) f.write(&quot;Content&quot;) with open(&quot;small_file.txt&quot;, &quot;rb&quot;) as f: content = f.read() print(f&quot;START|{content}|END&quot;) </co...
<python><io>
2024-07-25 06:05:18
0
517
Han Qi
78,791,591
2,181,188
Need help to extract this XML node - Excel connection strings in Python
<p>I have a Python program opening up Excel (XLSX) files, and trying to find the <code>&lt;connection&gt;</code> node.</p> <p>This is the full XML from the <code>connections.xml</code> file.</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;yes&quot;?&gt; &lt;connections x...
<python><excel><xml>
2024-07-25 05:29:04
3
4,945
Fandango68
78,791,013
3,120,501
Jax jitting of kd-tree code taking an intractably long amount of time
<p>I've written myself into a corner with the following situation:</p> <ul> <li>I'm running an optimiser which requires smooth gradients to work, and I'm using Jax for automatic differentiation. Since this code is Jax jitted, this means that anything connected to it has to be Jax jit traceable.</li> <li>I need to inter...
<python><scipy><jit><jax><kdtree>
2024-07-25 00:03:02
1
528
LordCat
78,790,887
3,754,125
Python multiprocessing.connection.Connection not behaving according to specifications
<p>According to python specifications, <code>recv()</code> method of python <code>Connection</code>, (returned from <code>multiprocessing.Pipe()</code>, throws an <code>EOFError</code> when pipe is empty and the other end of the pipe is closed. (Here is the reference: <a href="https://docs.python.org/3.9/library/multip...
<python><python-3.x>
2024-07-24 22:53:41
1
1,121
milaniez
78,790,767
5,013,066
Poetry unable to find installation candidates for a private package, but only on a GitLab runner
<p>I am having a very bad case of &quot;works on my machine&quot; today. I am using a private GitLab repository and a package from a private package registry on the same GitLab instance.</p> <p>On my machine, I have configured the package source with a personal access token.</p> <p>This is my pyproject.toml. (I have ob...
<python><python-poetry>
2024-07-24 22:06:11
1
839
Eleanor Holley
78,790,660
6,440,589
Does it make sense to use Python's multiprocessing module when deploying code on Azure?
<p>Our team has deployed a Python script on <strong>Azure Machine Learning</strong> (AML) to process files stored on an Azure storage account.</p> <p>Our pipeline consists of a <strong><a href="https://learn.microsoft.com/en-us/azure/data-factory/control-flow-for-each-activity" rel="nofollow noreferrer">ForEach</a></st...
<python><azure><parallel-processing><multiprocessing><vcpu>
2024-07-24 21:31:53
0
4,770
Sheldon