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,085,020
1,839,674
Packaging with pyproject.toml that will include other multi level directories
<p>I have spent two full days trying to figure this out with no success. I have a python project that I want to package. That is the easy part. The part I can't figure out is how to copy other multilevel folders into the package.</p> <p>I am trying to get the <em>myproj</em> as a package with the <em>dosomething.py</em...
<python><setuptools><python-packaging><pyproject.toml>
2024-03-01 00:37:50
1
620
lr100
78,084,959
6,943,622
Count Unguarded Cells in the Grid (recursion)
<p>it's a semi-popular leetcode question. And I know there are a lot of solutions online, but I am practicing by solving all these problems myself to really master recursion. I am wondering what's wrong with my current approach; I keep maxing out the call stack. I would appreciate feedback! Here's the question:</p> <p>...
<python><algorithm><recursion><depth-first-search>
2024-03-01 00:08:32
2
339
Duck Dodgers
78,084,852
4,979,733
How to handle Path objects when dumping to YAML
<p>I have an object that contains PoxisPath() as data members. How do I write this out as a YAML file? I currently do:</p> <pre><code>safe_dump_all(data, f_out, indent=2, default_flow_style=False) </code></pre> <p>but I'm getting an error that it doesn't know how to reprsent Path objects.</p> <pre><code>Type: &lt;class...
<python><yaml>
2024-02-29 23:31:30
1
3,491
user4979733
78,084,790
2,635,863
split data frame index by separator and convert into columns in pandas
<pre><code>df = pd.DataFrame({'x':[1,2,3,4]}) df.index = ['A:100','B:103','C:105','D:108'] </code></pre> <p>I'm trying to split the index at <code>:</code> and convert the output into columns <code>y</code> and <code>z</code>:</p> <pre><code>x y z 1 A 100 2 B 103 3 C 105 4 D 108 </code></pre> <p>I t...
<python><pandas>
2024-02-29 23:11:08
2
10,765
HappyPy
78,084,763
1,447,953
Collect common groups on non-index column across two dataframes
<p>Here are two dataframes grouped how I want them:</p> <pre><code>last5s = pd.Timestamp.now().replace(microsecond=0) - pd.Timedelta('5s') dates = pd.date_range(last5s, periods = 5, freq='s') N=10 data1 = np.random.randint(0,10,N) data2 = np.random.randint(0,10,N) df1 = pd.DataFrame({'timestamp': np.random.choice(dat...
<python><pandas><dataframe><group-by>
2024-02-29 23:00:38
2
2,974
Ben Farmer
78,084,675
3,834,841
Python class method type overloading returns invalid type according to Pylint
<p>I've written a function that returns a <code>dict</code> from a config, and am trying to type it so that based on the key, the correct value type is returned (a <code>list</code> of an aliased <code>TypedDict</code>). I tried to achieve this with method overloading, but am receiving a Pylint error when trying to use...
<python><python-3.x><pylint>
2024-02-29 22:39:29
0
3,875
awarrier99
78,084,659
12,027,869
Two Plots in One Figure using seaborn
<p>I am trying to plot two plots in one figure: a histogram and a line plot based on the same x axis tick labels from the histogram.</p> <p>The histogram is just the frequency by <code>state</code> and <code>group</code>.</p> <p>The line plot is the <code>target</code> by <code>state</code>.</p> <p>I want the legends ...
<python><seaborn>
2024-02-29 22:35:07
0
737
shsh
78,084,456
15,963,311
How to maintain "pydantic style" errors for validations outside of pydantic?
<p>We are using fastapi and pydantic to excellent effect. However, there are some validations that we perform that can not (<a href="https://github.com/pydantic/pydantic/issues/1227#issuecomment-585723753" rel="nofollow noreferrer">should not?</a>) be done in a pydantic validator. (Mostly database/world-state kinds of ...
<python><fastapi><pydantic>
2024-02-29 21:50:05
1
394
Luke Nelson
78,084,311
14,055,985
How do I port python2 code using RSA.importKey().decrypt() to python3?
<p>We have a legacy python2 application that uses an RSA private key to decrypt a base64-encoded file. How do we port this to python3?</p> <h2>Python2.7 code, this does work:</h2> <pre class="lang-py prettyprint-override"><code> def _unlock_keys(self, passphrase): #get user priv key passphrase and perform u...
<python><python-3.x><python-2.7><cryptography><public-key-encryption>
2024-02-29 21:17:10
1
1,981
KJ7LNW
78,084,169
23,260,297
Power Automate Desktop '[Errno 2] No such file or directory when running powershell script
<p>I am trying to use power automate desktop to run a python script. Since power automate desktop does not have an action to run a python3 script (only python 2), I have to use the run powershell script action instead. I am passing the path to my python interpreter and the absolute path to my python script. However, wh...
<python><powershell><power-automate-desktop>
2024-02-29 20:42:41
1
2,185
iBeMeltin
78,084,157
1,134,337
FastAPI and Pydantic - ignore but warn when extra elements are provided to a router input Model
<p>This is the code I wrote</p> <pre><code>from typing import Any from fastapi import APIRouter from pydantic import BaseModel, ConfigDict, ValidationError class State(BaseModel): mode: str | None = None alarm: int = 0 class StateLoose(State): model_config = ConfigDict(extra='allow') class StateExact...
<python><fastapi><pydantic><python-3.11>
2024-02-29 20:41:00
1
766
Bertone
78,084,123
2,137,570
python - URL listener for request submission
<p>What in python can do this? Listener?? not sure what to use</p> <p>I'm trying to figure out how to do the following:</p> <ul> <li>Website1: Generates a code and loads website2 URL :<a href="https://website2.com/?code=123423439934&amp;state=619" rel="nofollow noreferrer">https://website2.com/?code=123423439934&amp;st...
<python>
2024-02-29 20:33:05
1
5,998
Lacer
78,083,956
4,815,601
How to use balanced sampler for torch Dataset/Dataloader
<p>My simplified Dataset looks like:</p> <pre><code>class MyDataset(Dataset): def __init__(self) -&gt; None: super().__init__() self.images: torch.Tensor[n, w, h, c] # n images in memmory - specific use case self.labels: torch.Tensor[n, w, h, c] # n images in memmory - specific use case ...
<python><pytorch><dataset><sampling><dataloader>
2024-02-29 19:56:22
1
1,042
Mateusz Konopelski
78,083,860
11,812,216
Why does this python decorator refuse to set the setter?
<p>This is my code:</p> <pre><code>class Property: def __init__(self, fget, fset): self.fget = fget self.fset = fset def __get__(self, obj, objtype=None): return self.fget(obj) def __set__(self, obj, value): self.fset(obj, value) class X: def __init__(self, val): ...
<python><python-decorators><python-descriptors>
2024-02-29 19:37:03
0
424
forstack overflowizi
78,083,607
1,743,843
TypeError with Datetimes in SQLModel
<p>I'm working with SQLModel ORM framework in a Python application and encountering a TypeError related to datetime objects when trying to insert new records into a PostgreSQL database.</p> <pre><code>from datetime import datetime, timezone import uuid from sqlmodel import Field, SQLModel, Relationship, UniqueConstrain...
<python><sqlmodel>
2024-02-29 18:39:26
1
34,339
softshipper
78,083,513
14,293,020
Python np.nansum() arrays but not return 0 when summing two nans
<p><strong>Context:</strong> I have a 3D numpy array (3,10,10): <code>arr</code>. I have a list gathering indices of the 0th dimension of <code>arr</code>: <code>grouped_indices</code>. I want to calculate the sum of these grouped indices of <code>arr</code>, and store them in a host array: <code>host_arr</code>.</p> <...
<python><numpy><sum><nan>
2024-02-29 18:16:02
1
721
Nihilum
78,083,235
1,711,271
Add a constant to an existing column
<p>Dataframe:</p> <pre><code>rng = np.random.default_rng(42) df = pl.DataFrame( { &quot;nrs&quot;: [1, 2, 3, None, 5], &quot;names&quot;: [&quot;foo&quot;, &quot;ham&quot;, &quot;spam&quot;, &quot;egg&quot;, None], &quot;random&quot;: rng.random(5), &quot;A&quot;: [True, True, False...
<python><python-polars>
2024-02-29 17:17:37
1
5,726
DeltaIV
78,083,169
3,225,420
Send GSD Command in JSON to Zebra Printer
<p>Trying to send commands (not labels) to Zebra printers using Python.</p> <p>On page 574 of the <a href="https://support.zebra.com/cpws/docs/zpl/zpl-zbi2-pm-en.pdf" rel="nofollow noreferrer">documentation</a> it shows: <a href="https://i.sstatic.net/tDWui.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net...
<python><json><python-3.x><zpl><zpl-ii>
2024-02-29 17:03:39
1
1,689
Python_Learner
78,083,042
520,556
No module named 'matplotlib.typing'
<p>I am receiving an error message: <code>ModuleNotFoundError: No module named 'matplotlib.typing'</code> with this bit of code:</p> <pre><code>from plotnine import * (ggplot(the, aes(x='Trial', y='Weights', colour='Cues')) + geom_line() + scale_colour_manual(values=['#1f78b4','#b2df8a','#fb9a99','#e31a1c','#a...
<python><matplotlib><plotnine>
2024-02-29 16:45:48
2
1,598
striatum
78,082,815
7,479,217
Python requests returns 503 status code as response when sending a file through POST request
<p>So I am using python requests to send a post request to another server (both servers are internal to the company). It worked some weeks ago, but I tried today and it has suddenly stopped working.</p> <p>I can use postman to send the same request and the server responds with 201. I can perform a get request from my p...
<python><python-3.x><django><flask><python-requests>
2024-02-29 16:08:03
0
352
Mazhar Ali
78,082,467
13,088,678
repartition vs coalesce performance on smaller partition
<p>I'm reading input data from s3, writing the result data back to s3.</p> <ul> <li>Input data volume (from delta table): 5TB</li> <li>Result data volume : ~5GB</li> </ul> <p>I used different options during write as below:</p> <ul> <li>Spark default behaviour (multiple files) : 6hr</li> <li>repartition(11) : completed ...
<python><scala><apache-spark>
2024-02-29 15:12:22
0
407
Matthew
78,082,446
12,415,855
Python DeepTranslator and GoogleTranslator not working with text?
<p>I try to translate a text using the following code -</p> <pre><code># -*- coding: utf-8 -*- text = &quot;&quot;&quot; ดำเนินธุรกิจทางด้าน ผลิต ถุงพลาสติก ถุงบรรจุอาหาร พร้อมด้วย ถุงพิมพ์สอดสี ระบบกราเวียร์ อันทันสมัย นอกจากนี้ยัง ผลิตถุงขยะ, แผ่นพลาสติก Green House ที่มีลูกค้าทั้งในและต่างประเทศ ตลอดระยะเวลา 40 กว่า...
<python><google-translator-toolkit>
2024-02-29 15:09:11
1
1,515
Rapid1898
78,082,220
8,436,290
Cron job in python every x hours - 1 minute
<p>I would like to create a cron job that triggers at 23h59, then 3h59, 7h59, 11h59...</p> <p>My solution</p> <pre><code>scheduler.add_job( func=myfunc, trigger=&quot;cron&quot;, day='*', hour=&quot;*/4&quot;, minute=59, second=0, ) </code></pre> <p>works but triggers every time one hour too lat...
<python><cron>
2024-02-29 14:33:32
2
467
Nicolas REY
78,082,169
3,923,576
numpy.intersect1d does not work on dictionary.keys()
<p>I tried to use numpy's <code>intersect1d</code> to compare the keys in two dictionaries. However, this always returns an intersection of zero, for some reason related to dictionary keys being objects. I want to know why this behavior is desireable in any way.</p> <pre><code>d1 = {'a':1, 'b':2} d2 = {'b':2, 'c':3} np...
<python><numpy><dictionary><set>
2024-02-29 14:24:34
2
569
Vira
78,081,978
1,181,452
Sqlite - How to efficiently insert or update millions of rows?
<p>I have thousands of text files consisting of an item and the supplier code that are in the following format:</p> <pre><code>item_name,supplier_code </code></pre> <p>So for example:</p> <pre><code>Potatoes,10294 Rope,49013 Beans,23958 Soap,12495 </code></pre> <p>I want to add them to a single table in sqlite with jus...
<python><database><sqlite><transactions>
2024-02-29 13:55:54
1
3,296
M9A
78,081,891
1,914,781
Why is Feb 29 reported as invalid date?
<pre><code>import datetime tstr = &quot;02-29 13:34:57.041&quot; dt = datetime.datetime.strptime(tstr, '%m-%d %H:%M:%S.%f') </code></pre> <p>My script reports such an error:</p> <pre class="lang-none prettyprint-override"><code> File &quot;/usr/lib/python3.11/_strptime.py&quot;, line 579, in _strptime_datetime re...
<python><datetime>
2024-02-29 13:42:24
1
9,011
lucky1928
78,081,853
1,661,267
Reading a multi-part 7z file using Python is failing due to memory issues
<p>I am using a loop to read multi-archive 7z files with this code.</p> <pre><code>import py7zr import multivolumefile zip_path = f&quot;{ARCHIVE_PATH}/test.7z&quot; with multivolumefile.open(zip_path, mode='rb') as multizip_handler: with py7zr.SevenZipFile(multizip_handler, 'r', password=PASSWORD, filters=filter...
<python><7zip><py7zr>
2024-02-29 13:36:29
1
1,252
mountrix
78,081,625
632,472
How to dynamically get a property?
<p>I have this python code:</p> <pre><code>class MyObject: def __init__(self): self._obj1 = &quot;obj1&quot; self._obj2 = &quot;obj2&quot; @property def obj1(self): return self._obj1 @property def obj2(self): return self._obj2 def get_property(obj, chose): if ch...
<python>
2024-02-29 12:59:08
1
12,804
Rodrigo
78,081,432
10,164,750
Handling a dynamic sql query in Psycopg2 with multiple WHERE condition
<p>I want to execute a sql query dynamically with multiple <code>WHERE</code> conditions. the query is as below</p> <pre><code>query = &quot;&quot;&quot;SELECT * FROM UBO_EXCEPTION WHERE reg_nb = %s AND return_date = %s::date AND data_type = %s ORDER BY db_timestamp LIMIT 1&quot;&quot;&quot; </code></pre> <p>The me...
<python><postgresql><psycopg2>
2024-02-29 12:30:18
0
331
SDS
78,081,304
11,067,209
Issue with Padding Mask in PyTorch Transformer Encoder
<p>I'm encountering an issue with the padding mask in PyTorch's Transformer Encoder. I'm trying to ensure that the values in the padded sequences do not affect the output of the model. However, even after setting the padded values to zeros in the input sequence, I'm still observing differences in the output.</p> <p>Her...
<python><pytorch><transformer-model>
2024-02-29 12:08:16
2
665
Angelo
78,081,023
1,095,967
Creating dataframe from dictionary with multiple dtypes set for columns
<p>I would like to create a pandas dataframe from a dictionary but set multiple dtypes on selected columns at creation. EDIT - should have made this clear - I have already created the dictionary and have passed it in as col_dets in this example.</p> <pre><code>df = pd.DataFrame(col_dets, index=[0]).astype(dict.fromkeys...
<python><pandas><dataframe><dictionary><dtype>
2024-02-29 11:26:40
1
661
MaxRussell
78,080,790
12,013,353
Solving implicit equation with scipy.optimize.fsolve
<p>I came to ask this question from <a href="https://stackoverflow.com/questions/64400639/solve-an-implicit-equation-python">the very similar one</a> where I &quot;learned&quot; how to employ fsolve to solve for solving implicit equations.<br /> My equation is defined by this function:</p> <pre><code>def fn4(Fs): r...
<python><scipy><fsolve>
2024-02-29 10:51:23
1
364
Sjotroll
78,080,761
9,322,863
Confusing finite difference results with numpy and scipy sparse for simple ODE
<p>I'm having trouble getting the solution to a simple ODE using finite difference. The equation I'm trying to solve is more complicated, but even for a sin function I'm getting different results with <code>scipy.sparse</code> and <code>numpy.linalg</code>. Neither is particularly close to the real solution, even for 2...
<python><numpy><scipy><sparse-matrix><differential-equations>
2024-02-29 10:47:38
1
323
TIF
78,080,591
1,714,692
Python get_type_hints not returning parent's annotations of child dataclass
<p>I want to get all fields of a inherited dataclass:</p> <pre><code>from dataclasses import dataclass, fields from typing import get_type_hints @dataclass class A: a: int = 0 @dataclass class B(A): b: int = 0 a = A(a=4) b = B(a=4, b=5) print(a.__annotations__) print(b.__annotations__) </code></pre> <p>As alrea...
<python><python-typing><python-dataclasses>
2024-02-29 10:24:00
1
9,606
roschach
78,080,499
13,520,223
Fetching API tokens does not work with requests-oauthlib (but without)
<p>I try to get a token from an API using <code>requests-oauthlib</code>. This is the essential part of my code:</p> <pre><code>from flask import Flask, request, redirect from requests_oauthlib import OAuth2Session # setting constants … app = Flask(__name__) app.config[&quot;SECRET_KEY&quot;] = SECRET_KEY @app.rout...
<python><flask><oauth-2.0><requests-oauthlib>
2024-02-29 10:10:59
1
693
Ralf Zosel
78,080,376
11,322,034
How to check whether a specific opc ua node already exists with asyncua?
<p>How to check with <a href="https://github.com/FreeOpcUa/opcua-asyncio" rel="nofollow noreferrer">asyncua</a> (python) whether a node with a specific name exists already on the server?</p> <p>If it exists it should be used if it doesn't exist then the node should be created.</p> <p><strong>Use case:</strong> The opcu...
<python><opc-ua>
2024-02-29 09:54:29
1
441
Samuel
78,080,336
23,461,455
Why is there implemented a default blank row when writing csv from python linked list?
<p>I have an example of writing a csv from a <code>python</code> linked list:</p> <pre><code>import csv # field names fields = ['Name', 'Branch', 'Year', 'CGPA'] # data rows of csv file rows = [ ['Nikhil', 'COE', '2', '9.0'], ['Sanchit', 'COE', '2', '9.1'], ['Aditya', 'IT', '2', '9.3'], ['Sagar',...
<python><excel><csv><export-to-csv>
2024-02-29 09:48:52
1
1,284
Bending Rodriguez
78,080,284
2,546,099
Test for missing import with pytest
<p>In the <code>__init__.py</code>-file of my project I have the following code, for retrieving the current version of the program from the <code>pyproject.toml</code>-file:</p> <pre><code>from typing import Any from importlib import metadata try: import tomllib with open(&quot;pyproject.toml&quot;, &quot;rb&...
<python><pytest>
2024-02-29 09:41:59
3
4,156
arc_lupus
78,080,274
2,352,158
Using python interpreter explicitely does not ignore shebang
<p>I have read <a href="https://stackoverflow.com/questions/64120768/does-shebang-overwrite-the-python-interpreter-path">Does shebang overwrite the python interpreter path</a>, and it seems the given answer does not apply to me.</p> <p>Some context: I am on Windows using <code>C:\Program Files\Git\bin\bash.exe</code> a...
<python><python-3.x><shebang>
2024-02-29 09:40:02
2
4,695
coincoin
78,080,209
17,797,258
ModuleNotFoundError in Python AzureFunction App for custom package
<p>I developing a <code>Python</code> <code>Azure Function</code> app and I use a <code>Custom Package</code> for this project. because of the custom package I build and install all dependencies in my <code>CI/CD</code> pipeline before making <code>zip</code> file and deploying it on <code>Azure</code> based on this <a...
<python><azure><azure-devops><azure-functions>
2024-02-29 09:29:26
2
440
Milad Karimifard
78,080,159
7,541,530
How to type-annotate a polars DataFrame created from an arrow Table?
<p>In python, I'm trying to create a polars DataFrame from a pyarrow table, like so:</p> <pre class="lang-py prettyprint-override"><code>import pyarrow as pa import polars as pl table = pa.table( { &quot;a&quot;: [1, 2, 3], &quot;b&quot;: [4, 5, 6], } ) df = pl.from_arrow(table) </code></pre> ...
<python><python-polars>
2024-02-29 09:22:45
1
321
Taeke
78,080,061
12,314,521
What is an efficient way for merge list of same key dictionaries which value is tensor [Pytorch]
<p>Is there any way more efficient than this way?</p> <pre><code>mention_inputs = defaultdict(list) for idx in mention_indices: mention_input, _ = ... for key,value in mention_input.items(): # value is a tensor has shape (dim,) mention_inputs[key].append(value) ...
<python><pytorch><tensor>
2024-02-29 09:02:36
1
351
jupyter
78,079,908
1,743,843
AttributeError: 'async_generator' object has no attribute 'post'
<p>I'm writing pytest tests for my FastAPI async project. Tests causes error :</p> <pre><code>test_main.py::test_create_user FAILED [100%] test_main.py:32 (test_create_user) client = &lt;async_generator object client at 0x106585fc0&gt; generate_random_phone_number = &lt;function gener...
<python><fastapi>
2024-02-29 08:35:29
1
34,339
softshipper
78,079,857
1,645,154
Apache Arrow with Apache Spark - UnsupportedOperationException: sun.misc.Unsafe or java.nio.DirectByteBuffer not available
<p>I am trying to integrate Apache Arrow with Apache Spark in a PySpark application, but I am encountering an issue related to <code>sun.misc.Unsafe</code> or <code>java.nio.DirectByteBuffer</code> during the execution.</p> <pre><code>import os import pandas as pd from pyspark.sql import SparkSession extra_java_option...
<python><apache-spark><pyspark><pyarrow>
2024-02-29 08:25:19
2
1,179
Midhun Pottammal
78,079,717
10,721,627
Polars - AttributeError: 'ArrowExtensionArray' object has no attribute 'to_pydatetime'
<p>I am trying to push dates to the SQLite database using Polars' <code>write_database</code> method:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl from datetime import date import sqlite3 dates_dt = [date(2000, 1, 1), date(2000, 1, 2), date(2000, 1, 3)] df = pl.DataFrame({&quot;date&quot;: d...
<python><pandas><python-polars>
2024-02-29 07:59:51
1
2,482
Péter Szilvási
78,079,454
14,466,860
How to register .otf font in reportlab python
<p>I am working on <code>reportlab</code> in python and want to use <code>Avenir</code> font I have this font of <code>OTF</code> type and There is class <code>TTFont</code> in reportlab but i want to use .otf font how to use it</p> <pre class="lang-py prettyprint-override"><code>pdfmetrics.registerFont(TTFont(&quot;Av...
<python><pdf><fonts><reportlab>
2024-02-29 07:10:58
0
7,847
Munsif Ali
78,079,168
2,804,197
How can I make my D-Bus service exit automatically when idle?
<p>I have a D-Bus service written in Python with GDBus (using bindings provided by <a href="https://gnome.pages.gitlab.gnome.org/pygobject/" rel="nofollow noreferrer">PyGObject</a>).</p> <p>Since it's written in Python and has a few dependencies, that service has a relatively big memory footprint (about 30MiB). It's on...
<python><service><systemd><dbus><gdbus>
2024-02-29 06:04:17
1
402
user2804197
78,078,945
12,314,521
Is it efficient to pass model into a custom dataset to run model inference during training for sampling strategy?
<p>I'm trying to design a training flow for sampling samples during training.</p> <p>My data look like this:</p> <pre><code>defaultdict(list, {'C1629836-28004480': [0, 5, 6, 12, 17, 19, 28], 'C0021846-28004480': [1, 7, 15], 'C0162832-28004480': [2, 9], 'C0025929-28004480': [3, 10, 30]...
<python><pytorch><dataset><sampling>
2024-02-29 04:57:29
1
351
jupyter
78,078,821
7,644,846
pyautogui is not finding the image on my screen while using the `locateCenterOnScreen` command
<p>So, I'm playing with <code>pyautogui</code> automation python library and trying to find the axis (x, y) of a picture on my screen.</p> <p>Following the <a href="https://pyautogui.readthedocs.io/en/latest/quickstart.html" rel="nofollow noreferrer">official documentation</a>, we have the following command, which supp...
<python><macos><automation><ui-automation><pyautogui>
2024-02-29 04:13:04
1
2,226
Victor Cordeiro Costa
78,078,811
6,997,665
Gradients for selection from array operation in PyTorch
<p>This is a followup question from <a href="https://stackoverflow.com/q/78072628/6997665">here</a>. I have obtained a tensor, say, <code>d</code> with gradients. Now I have another tensor array, say <code>e</code> from which I need to pick the first <code>d</code> elements. MWE below.</p> <pre><code>import torch a = ...
<python><python-3.x><machine-learning><deep-learning><pytorch>
2024-02-29 04:07:18
2
3,502
learner
78,078,717
22,371,917
html and js not working the same with flask
<p>i have a folder which contains server.py a templates folder with index.html and a js folder with script.js server.py:</p> <pre class="lang-py prettyprint-override"><code>from flask import Flask, render_template import random app = Flask(__name__) @app.route('/') def home(): return render_template('index.html')...
<javascript><python><html><flask>
2024-02-29 03:29:37
1
347
Caiden
78,078,676
2,201,789
How to properly setup ALLOWED_HOST to allow other machines in the network access the server
<p>Django server in machine TestPC-A, at 192.25.56.120</p> <p>I want it accessible from the computer in the same network 192.25.56.xxx.</p> <p>what I have configured</p> <p><strong>1. settings.py</strong></p> <pre class="lang-py prettyprint-override"><code> ALLOWED_HOSTS = [&quot;127.0.0.1&quot;, &quot;localhost&quot;,...
<python><django>
2024-02-29 03:13:36
2
1,201
user2201789
78,078,327
951,739
python re.split gives different results depending on char group order
<pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; import re &gt;&gt;&gt; s = &quot;i'm happy 7 times&quot; &gt;&gt;&gt; re.split(r' ',s) [&quot;i'm&quot;, 'happy', '7', 'times'] &gt;&gt;&gt; re.split(r&quot;[, -]&quot;,s) [&quot;i'm&quot;, 'happy', '7', 'times'] &gt;&gt;&gt; re.split(r&quot;[, -:]&quot;,s) [...
<python><regex>
2024-02-29 00:45:15
1
769
knowingpark
78,078,290
3,543,200
botocore >= 1.28.0 slower in multithread application
<p>The official Boto3 docs recommends creating a new resource per thread: <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/guide/resources.html#multithreading-or-multiprocessing-with-resources" rel="nofollow noreferrer">https://boto3.amazonaws.com/v1/documentation/api/latest/guide/resources.html#multith...
<python><amazon-web-services><amazon-s3><boto><botocore>
2024-02-29 00:30:11
1
997
gmoss
78,077,986
358,680
Vectorized version of `__contains__` (contained in) in pandas/numpy
<p>Consider:</p> <pre class="lang-py prettyprint-override"><code>a = pd.DataFrame([[&quot;x&quot;, &quot;y&quot;, &quot;z&quot;], [&quot;y&quot;, &quot;x&quot;, &quot;z&quot;]]) valid = (&quot;x&quot;, &quot;y&quot;) print(a in valid) # Doesn't work </code></pre> <p>I want the output to be:</p> <pre><code> 0 ...
<python><pandas><numpy>
2024-02-28 22:37:04
1
1,323
Luis
78,077,924
2,893,712
Pandas First Value That Doesnt Return KeyError
<p>I have a dataframe that has <em>either</em> column <code>A</code> or <code>B</code></p> <p>I was hoping for a syntax that uses the <code>or</code> operator to have a stntax like:</p> <pre><code>Value = df.at['Total','A'] or df.at['Total','B'] </code></pre> <p>but I still receive a <code>KeyError</code> exception. Is...
<python><pandas><dataframe><keyerror>
2024-02-28 22:19:17
3
8,806
Bijan
78,077,883
22,407,544
'ProgrammingError: cannot cast type bigint to uuid' in Django
<p>I've been moving development of my website over to using Docker. I replaced sqlite as my database with postgresql then ran the command <code>docker-compose exec web python manage.py migrate</code> in my Docker environment and it produced the following error:</p> <pre><code> File &quot;/usr/local/lib/python3.11/site-...
<python><sql><django><postgresql><sqlite>
2024-02-28 22:07:48
1
359
tthheemmaannii
78,077,822
7,124,155
Databricks spark submit - getting error with --py-files
<p>In Databricks workflows, I submit a spark job (Type = &quot;Spark Submit&quot;), and a bunch of parameters, starting with --py-files. The appl_src.zip contains application code and common functions.</p> <pre><code>&quot;--py-files&quot;, &quot;s3://some_path/appl_src.zip&quot;, &quot;s3://some_path/main.py&quot;, </...
<python><apache-spark><databricks>
2024-02-28 21:52:35
0
1,329
Chuck
78,077,509
53,491
Using aiohttp with requests_aws4auth
<p>I've asked a previous version of this, but I've progressed much since then.</p> <p>I've been told that I need to get the authorization headers from AWS4auth and add them as headers into the aiohttp session calls. I'm not sure how to do that.</p> <p>Currently I have:</p> <pre><code> self.aws4auth = AWS4Auth(access...
<python><python-asyncio><aiohttp>
2024-02-28 20:49:15
1
12,317
Brian Postow
78,077,448
4,706,711
TLS version mismach between curl and server. How I can accept multiple tls versions?
<p>I made the following servers:</p> <pre><code>import socket import threading import queue import time import ssl import multiprocessing class SocketServer: &quot;&quot;&quot; Basic Socket Server in python &quot;&quot;&quot; def __init__(self,host,port,max_threads): print(&quot;Create Ser...
<python><ssl><multiprocessing>
2024-02-28 20:38:28
1
10,444
Dimitrios Desyllas
78,077,410
23,260,297
Styling negative numbers in pandas
<p>I have a dataframe that I am exporting to Excel. I would also like to style it before the export.</p> <p>I have this code which changes the background color and text color and works fine, but I would like to add to it:</p> <pre><code>df.style.set_properties(**{'background-color': 'black', ...
<python><pandas><excel><dataframe><pandas-styles>
2024-02-28 20:31:47
2
2,185
iBeMeltin
78,077,316
2,414,957
Exception: Not found: 'python/cv2/py.typed' ERROR: Failed building wheel for opencv-python in Anaconda Python 3.6
<p>I am following the env setup in CenterPose repo. However, opencv-python doesn't get installed.</p> <p><code>(CenterPose) mona@ada:/data/CenterPose/data$ pip install opencv-python</code></p> <p>I get this error:</p> <pre><code> -- Installing: /tmp/pip-install-wjrf6kvm/opencv-python_e5e6222fa4024d2d8f3e1d1c3bd5fb1f/_...
<python><opencv><cmake><anaconda><conda>
2024-02-28 20:11:21
1
38,867
Mona Jalal
78,077,096
8,272,788
Subset list of text and matching embeddings using set() and np.unique() gives different length results
<p>I have a list of strings, as well as an array containing the dense embeddings generated from those strings (generated using <code>SentenceTransformer(&quot;all-mpnet-base-V2&quot;)</code>). In my analysis I notice that a number of the strings are repeated text. I want to run my analysis on unique values. Because ge...
<python><numpy><sentence-transformers>
2024-02-28 19:24:18
1
1,261
MorrisseyJ
78,077,069
2,079,306
Python - Read specific sheet of XLSM book that contains 7 sheets with macros and formulas. Find string in cell, replace string. Write back to XLSM
<p>Issue: Pandas to_excel writing as .xslx instead of .xlsm. Need to maintain macros in books.</p> <p>I have about 3000 xlsm files that are moderately complex with a few macros. There are about 7 sheets per book. I need to find a string(s) in a static column on a specific sheet and replace that string in all books.</p>...
<python><pandas><excel>
2024-02-28 19:17:09
2
1,123
john stamos
78,077,010
12,569,441
Optimizing the rational quadratic kernel function
<p>Given the following functions, what are some optimizations that can be done to speed up computations?</p> <p>Yes, I tried using ChatGPT and Bard, the reason I'm mentioning this is that there's a &quot;caveat&quot; to their solutions, <code>np.nan if (index - i) &lt; 0 else price_feed[index - i]</code> has to hold. S...
<python><numpy><performance><optimization><vectorization>
2024-02-28 19:03:21
1
403
Corfucinas
78,076,936
13,775,706
Single QPushButton Object on multiple frames
<p>I have an application that I'm writing that will have different layers for different purposes. Some layers will have functionality that differs from other layers, but some functionality will remain the same for all layers. As a user switches between the layers, I want to avoid having to have the user switch back to ...
<python><user-interface><pyqt6>
2024-02-28 18:47:21
0
304
Michael
78,076,624
225,020
How do I define a classmethod dunder?
<p>I have a class <code>percent</code> that I'd like to be able to define <code>__rsub__</code> for the class and not instances. For instance using this class:</p> <pre><code>class percent: def __init__(self, value: int) -&gt; None: self.value = value @classmethod def __rsub__(cls, value: int) -&g...
<python><python-3.x>
2024-02-28 17:48:44
0
27,595
Jab
78,076,401
13,339,621
Uninstall uv Python package installer
<p>I recently installed <a href="https://github.com/astral-sh/uv" rel="nofollow noreferrer">uv</a> on Linux using the command line provided in the documentation:</p> <pre class="lang-bash prettyprint-override"><code>curl -LsSf https://astral.sh/uv/install.sh | sh </code></pre> <p>It created an executable in <code>/home...
<python><linux><python-packaging><uv>
2024-02-28 17:12:25
2
1,549
matleg
78,076,355
1,773,592
TypeError when using regex to change column names in polars
<p>I have a df:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl df = pl.DataFrame({ &quot;A&quot;: [0], &quot;B&quot;: [1], '{&quot;C_C&quot;, &quot;1&quot;}': [2], '{&quot;D_D&quot;, &quot;6&quot;}': [3], }) </code></pre> <p>I want to change the column names so that if they hav...
<python><regex><dataframe><python-polars>
2024-02-28 17:04:46
1
3,391
schoon
78,076,346
16,383,578
how to download file using subprocess and update QProgressBar in PyQt6
<p>I am writing a program to download a bunch of files, the program is very long, I download the files by calling <a href="https://github.com/aria2/aria2/releases/tag/release-1.37.0" rel="nofollow noreferrer">aria2c.exe</a> via subprocess, and I have encountered a problem.</p> <p>Specifically, when using aria2c + subpr...
<python><subprocess><qthread><pyqt6>
2024-02-28 17:03:51
1
3,930
Ξένη Γήινος
78,076,321
11,431,332
Inner Join Database Table with Excel file by query in python
<p>I need to perform an inner join between a table in Amazon Redshift and an Excel table. The database table is quite large, and I only need to extract the IDs that are in Excel file, which contains a substantial list of IDs (approximately 30,000).</p> <p>I attempted to include the Excel table directly into the execute...
<python><sql><pandas><excel><amazon-redshift>
2024-02-28 17:00:40
1
331
Yasmine
78,076,178
225,020
How do I type hint a return type of one function based init if init is overloaded
<p>I have a class that accepts either ints or floats in it's init but all must be int or float so i am using <code>typing.overload</code> to achieve that and I want to be able to type hint the return of a function based on the given values.</p> <pre><code>class Vector3: @overload def __init__(self, x: int, y: i...
<python><python-typing>
2024-02-28 16:37:44
1
27,595
Jab
78,076,083
2,423,851
Error when running python machine learning model
<p>I am trying to follow tutorial video and run <a href="https://colab.research.google.com/github/camenduru/PanoHead-colab/blob/main/PanoHead_custom_colab.ipynb#scrollTo=v9wpwlGfiX2e" rel="nofollow noreferrer">this notebook</a> on google colab.</p> <p>After running second block of code, the following error is produced:...
<python><numpy><machine-learning>
2024-02-28 16:26:07
1
776
Petar Ivcec
78,076,046
7,270,723
Why str("").strip() in (".32") is True in Python?
<p>I've developed a habit of searching within collections to verify the existence of elements as part of my conditions. Recently, I encountered a test case that necessitated this approach, but I found myself unable to provide a clear explanation for the observed behavior or outcome.</p> <p>Why <code>str(&quot;&quot;).s...
<python><python-3.x><list>
2024-02-28 16:22:24
1
351
Jesse
78,075,946
4,692,610
Is there a way in Python to translate a hexidecimal representation of a fixed point number to the decimal representation of a fixed point number?
<p>I am aware of <a href="https://pypi.org/project/numfi/" rel="nofollow noreferrer">numfi</a>, which allows me to represent a decimal fixed point as a hexidecimal. For example:</p> <pre><code>import numfi y = numfi(0.5378, 1, 32, 30) y.hex array(['226B50B1'], dtype='&lt;U8') </code></pre> <p>However, lets say I only ...
<python><decimal><fixed-point><bit-representation>
2024-02-28 16:10:12
0
323
MW2023
78,075,943
8,648,710
Multi-node/host training with the sharding API
<p>I wanted to do multi-node training with jax. For context, I'm on TPUs (I have 2x <code>v3-8</code> nodes).</p> <p>The <a href="https://jax.readthedocs.io/en/latest/multi_process.html#initializing-the-cluster" rel="nofollow noreferrer">docs</a> suggests using <code>distributed.initialize()</code> along with <code>xma...
<python><python-3.x><jax>
2024-02-28 16:09:57
0
1,257
neel g
78,075,813
9,284,651
Python- Iterate over data frame in pandas and replace value that does not contains string from list
<p>My DF looks like below</p> <pre><code>x date_from cleaned_date 1 21 JUNE 23.59 2024-06-23 2 18TH JUN 23:59 2024-06-18 3 01TH JULY (23.59 HRS) 2024-07-01 4 28th June 2023 2023-06-28 5 5TH MAY 2023 2023-05-05 6 JUNE 27, 2023 2023-06-27 </code></pre> <p>I wr...
<python><pandas><dataframe><for-loop>
2024-02-28 15:48:40
2
403
Tmiskiewicz
78,075,720
10,721,627
Polars throw OperationalError when trying to write dataframe to a sqlite3 database
<pre class="lang-py prettyprint-override"><code>import polars as pl import sqlite3 conn = sqlite3.connect(&quot;test.db&quot;) df = pl.DataFrame({&quot;col1&quot;: [1, 2, 3]}) </code></pre> <p>According to the documentation of <a href="https://docs.pola.rs/py-polars/html/reference/api/polars.DataFrame.write_database.h...
<python><sqlite><python-polars>
2024-02-28 15:37:56
2
2,482
Péter Szilvási
78,075,639
12,415,855
Selenium can't input a text in a field on the website
<p>I tried to put a string in a txt-field on the following site with the following code:</p> <pre><code>import time from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service from selenium.webdriver.support.ui import WebDriverWait from sele...
<python><selenium-webdriver>
2024-02-28 15:25:51
3
1,515
Rapid1898
78,075,463
395,457
FB Hydra extending configurations
<p>I'm trying to use Facebook's Hydra package to configure a project. In the example below, I've tried to keep names as generic as possible. Suppose that there are multiple model architecture types (e.g. different types of segmentation task) that the user can load. The main application loads the appropriate model using...
<python><fb-hydra><omegaconf>
2024-02-28 15:00:56
1
2,917
Josh
78,075,375
13,812,982
Calculate row-by-row changes on a DataFrame where row data is a vector
<p>As an example:</p> <pre><code>import pandas as pd a = pd.Series([[1,2,3],[4,5,6],[7,8,9]]) a 0 [1, 2, 3] 1 [4, 5, 6] 2 [7, 8, 9] dtype: object </code></pre> <p>I am looking for the percentage change for each row to the row below, eg the result:</p> <pre><code>0 [-0.75, ...
<python><dataframe>
2024-02-28 14:49:40
2
4,331
DS_London
78,075,240
2,353,911
Python timedelta: microseconds vs milliseconds confusion
<p>I have what appears to be a very silly question.</p> <p>My impression is that the <code>timedelta.microseconds</code> attribute really returns milliseconds (at least in Python 3.10).</p> <p>Running the following code:</p> <pre><code>import sys from datetime import datetime, timedelta from time import sleep print(sy...
<python><python-3.x><datetime><timedelta>
2024-02-28 14:31:00
1
48,632
Mena
78,075,159
2,469,032
Concatenate values in a column by group as a list and assigning it to a variable in a pandas dataframe
<p>I have the following dataframe:</p> <pre><code>game = pd.DataFrame({ 'team': ['A', 'A', 'B', 'B', 'C', 'C', 'C'], 'members': [1, 2, 3, 4, 5, 6, 7] }) game </code></pre> <pre><code> team members 0 A 1 1 A 2 2 B 3 3 B 4 4 C 5 5 C 6 6 C 7 <...
<python><pandas>
2024-02-28 14:21:49
2
1,037
PingPong
78,075,152
3,836,815
Preserve line wrapping in ruamel.yaml
<p>Is there a way to preserve line wrapping with <code>ruamel.yaml</code>? The closest I have found is to use the <code>width</code> property but that doesn't quite do it.</p> <p><a href="https://stackoverflow.com/questions/42170709/prevent-long-lines-getting-wrapped-in-ruamel-yaml">Prevent long lines getting wrapped i...
<python><yaml><ruamel.yaml>
2024-02-28 14:20:40
2
22,535
crdavis
78,075,088
3,042,018
Get CodeSpaces VS Code to apply correct indentation
<p>I have checked every setting I can think of, but I must be missing something, as when I hit <kbd>Enter</kbd>, I get a 2-space indent, not a 4-space indent when trying to write Python in Visual Studio Code in <a href="https://github.com/features/codespaces" rel="nofollow noreferrer">GitHub Codespaces</a>.</p> <p>This...
<python><visual-studio-code><indentation><github-codespaces>
2024-02-28 14:11:04
0
3,842
Robin Andrews
78,075,052
4,119,262
Attempt to split word if uppercase (without enumerate, function or regex) leads to errors (e.g. not enough value to unpack)
<p>I am trying to learn python. In this context I need to split a word when encountering an upper case, convert it as a lower case and then insert a &quot;_&quot;.</p> <p>I have seen various quite complex answer <a href="https://stackoverflow.com/questions/63715861/insert-space-if-uppercase-letter-is-preceded-and-follo...
<python>
2024-02-28 14:04:46
1
447
Elvino Michel
78,074,899
13,181,599
OutOfMemoryError: CUDA out of memory. Both in local machine and google colab
<p>I am trying to use stable diffusion xl model to generate images. But after installing and painfully matching version of python, pytorch, diffusers, cuda versions I got this error:</p> <p><code>OutOfMemoryError: CUDA out of memory. Tried to allocate 1024.00 MiB. GPU 0 has a total capacty of 14.75 GiB of which 857.06 ...
<python><pytorch><google-colaboratory><stable-diffusion>
2024-02-28 13:41:01
1
301
Mahammad Yusifov
78,074,843
307,297
Jython: syntax check available?
<p>I am using Jython for a simple Python script task inside a Java app.</p> <pre class="lang-java prettyprint-override"><code>Properties ps = new Properties(); ps.put (&quot;python.console.encoding&quot;, &quot;UTF-8&quot;); ps.put (&quot;python.import.site&quot;, &quot;false&quot;); PythonInterpreter.initialize (Syste...
<python><java><jython>
2024-02-28 13:33:00
0
12,695
chris01
78,074,725
22,221,987
How to typehint dataclass field in function signature
<p>I've a frozen dataclass with some constants and function, which accept any constant from this class as it's argument.<br /> How can I typehint this mechanic? I need to tell user that function waits for any field's value from this specific dataclass.<br /> It should looks like this:</p> <pre><code>from dataclasses im...
<python><python-typing><python-dataclasses>
2024-02-28 13:16:09
2
309
Mika
78,074,666
10,764,260
Depth calculation for 3D-2D projections with different intrinsics and extrinsic matrices
<p>I have an ikea manual and the 3D parts in the assembled state. For each step in the ikea manual I have calculated intrinsic and extrinsic matrices to project the part onto the manual. Currently the intrinsic is different for each part and it is my understanding that this is unavoidable as the manual steps are drawn ...
<python><graphics><3d><computer-vision>
2024-02-28 13:07:21
0
308
Leon0402
78,074,623
4,354,477
"The truth value of an array with more than one element is ambiguous" when trying to train a new JAX+Equinox model a second time
<p><strong>TL;DR</strong>: I create a new instance of my <code>equinox.Module</code> model and fit it using Optax. Everything works fine. When I create a <em>new</em> instance of the same model and try to fit it from scratch, using the same code, same initial values, same everything, I get:</p> <pre><code>ValueError: T...
<python><machine-learning><neural-network><jax>
2024-02-28 13:01:01
1
45,042
ForceBru
78,074,445
16,511,234
Scatter plot on Plotly map but with search bar
<p>I use Plotly to create scatter plots on maps. Like this for example:</p> <pre><code>import plotly.express as px import geopandas as gpd geo_df = gpd.read_file(gpd.datasets.get_path('naturalearth_cities')) px.set_mapbox_access_token(open(&quot;.mapbox_token&quot;).read()) fig = px.scatter_mapbox(geo_df, ...
<python><plotly>
2024-02-28 12:34:53
0
351
Gobrel
78,074,401
820,410
Removing dense grid lines from CAPCHA & convert into clear image
<p>I want to extract the text from this image. I'm a newbie in opencv. I've tried various opencv codes across various questions, but none is working for me.</p> <p>How can I extract text from this? Or maybe remove grid lines &amp; that circular bulge in the middle so that image is straightened &amp; then I can extract ...
<python><opencv><ocr><captcha><text-recognition>
2024-02-28 12:29:28
1
16,203
Pankaj Singhal
78,074,286
316,723
Handling unregistered Celery tasks during continuous deployment
<p>I have a setup of multiple Celery workers on different machines. The tasks can get added at any time with a continous deployment process. So, at any point different workers may have different sets of tasks, even though they are on the same task queue.</p> <p>So, the following state is possible:</p> <ul> <li>tasks on...
<python><celery>
2024-02-28 12:10:40
0
4,106
naktinis
78,074,124
19,356,117
How to read zarr files correctly from minio?
<p>I want to read a big <code>zarr</code> file from my minio(s3) server,however,after I changed three methods,they are all crashed:</p> <pre><code>import hydrodata.configs.config as conf # Method 1 # https://pastebin.com/vkM1M3VV zarr_path = await conf.FS.open_async('s3://datasets-origin/usgs_streamflow_nldas_hourly.z...
<python><asynchronous><amazon-s3><bigdata><minio>
2024-02-28 11:44:35
1
1,115
forestbat
78,074,062
7,819,329
Deal with "non-stable" entries in a noisy signal
<p>I have a signal in which I want to identify &quot;outliers&quot;, actually corresponding to samples for which the signal is not sufficiently stable.</p> <p>I have implemented this:</p> <pre><code>def count_outliers(series, window_size=5, stability_threshold=0.1): rolling_min = series.rolling(window=window_size, ...
<python><filter><time-series><signal-processing>
2024-02-28 11:32:05
0
1,161
MysteryGuy
78,074,032
22,221,987
PyCharm Google-docstring russian language parsing problems
<p>I've a docstring in some function. This is a google-styled docstring. My PyCharm has enabled default syntax checking.<br /> For some reasons I got a PEP hint, that the first letter in a sentence should be capitalised. But, here is the tricky part. This hint occured under the Arg name.<br /> Here is the screenshot, w...
<python><python-3.x><pycharm><docstring><pep>
2024-02-28 11:25:02
1
309
Mika
78,073,757
14,565,295
Create class attribute derived from base class's class attribute
<p>I have a base class with a class attribute in Python:</p> <pre><code>class BaseClass(): TENANT_VARIABLES = # Some kind of dictionary </code></pre> <p>then I have some classes that inherit from that class:</p> <pre><code>class A(BaseClass): pass </code></pre> <p>and finally I have the lower-level class in the...
<python>
2024-02-28 10:38:54
1
349
rodvictor
78,073,490
12,878,983
Precise transliteration of Chinese words in Python
<p>I have this two words in Chinese:</p> <pre><code>l1 = '陕西省' l2 = '山西省' </code></pre> <p>and their transiliterations are 'Shaanxi Sheng' and 'Shanxi Sheng'. I'm using the python unidecode package</p> <pre><code>import unidecode print(unidecode.unidecode(l1), unidecode.unidecode(l2)) </code></pre> <p>but it gives ...
<python>
2024-02-28 09:57:29
1
573
marco
78,073,485
10,816,027
/usr/bin/python3: No module named colab_kernel_launcher
<p>I need python==3.7 and am working on Google Colab. The list of commands to downgrade the Python version are as follows:</p> <pre><code>!python --version !sudo apt-get install python3.7 !sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.7 1 </code></pre> <p>It seems to work:</p> <pre><code...
<python><google-cloud-colab-enterprise>
2024-02-28 09:56:38
0
1,057
Om Rastogi