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
βŒ€
79,023,397
13,392,257
TypeError: Object of type Project is not JSON serializable
<p>My code:</p> <p>main.py</p> <pre><code>from . import models, schemas from .database import SessionLocal, engine models.Base.metadata.create_all(bind=engine) app = FastAPI() # Dependency def get_db(): db = SessionLocal() try: yield db finally: db.close() @app.get(&quot;/projects/&quot;...
<python><fastapi>
2024-09-25 14:20:21
2
1,708
mascai
79,023,187
9,779,026
Enumerating all possible lists (of any length) of non-negative integers
<p>I would like to generate/enumerate all possible lists of non-negative integers such that the algorithm will generate lists like the following at some point</p> <pre class="lang-py prettyprint-override"><code>[1] [24542,0] [245,904609,848,24128,350,999] </code></pre> <p>In other words, for all possible non-negative i...
<python><list><enumeration>
2024-09-25 13:33:22
2
1,437
2080
79,023,175
1,949,081
Pandas write parquet files to S3 has partition limit of 1024
<p>I have a pandas dataframe which I am writing to S3 using Pyarrow engine. I have the data to be partitioned by Pyarrow engine throw error that more than 1024 partitions can not be written. Is there a way to overcome this limitation?</p> <pre><code>df.to_parquet(s3_output_path, compression='snappy', ...
<python><python-3.x><pandas><parquet><pyarrow>
2024-09-25 13:30:21
1
5,528
slysid
79,022,883
7,953,924
Mutate a column in Ibis when column name has spaces
<p>Given a dataframe that has a column with a space:</p> <pre><code>ibis.memtable({ 'colname with space': ['a', 'b', 'c'] }) </code></pre> <p>I want to mutate this column. How do I reference it in the <code>.mutate</code> method? One way is <code>table['colname with space']</code>, however I consider this at best a...
<python><ibis>
2024-09-25 12:23:54
1
1,381
Liudvikas Akelis
79,022,862
1,854,182
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa0 in position ???: invalid start byte
<p>I am working with byte strings that include non-ASCII characters, specifically Hebrew text, and I encountered a UnicodeDecodeError when trying to decode the byte string to UTF-8. Here's the problematic code:</p> <pre><code>t = b'\xd7\x91\xd7\x9c\xd7\xa9\xd7\x95\xd7\xa0\xd7\x99\xd7\xaa:\xa0 ' print(t.decode('utf8')) ...
<python><unicode><utf-8><byte><decoding>
2024-09-25 12:19:45
1
888
Ofer Rahat
79,022,782
4,751,700
Return all rows that have at least one null in one of the columns using Polars
<p>I need all the rows that have null in one of the predefined columns. I basically need <a href="https://stackoverflow.com/questions/78983868/keep-only-rows-that-have-at-least-one-null">this</a> but i have one more requirement that I cant seem to figure out. Not every column needs to be checked.</p> <p>I have a functi...
<python><dataframe><null><python-polars>
2024-09-25 12:04:47
2
391
fanta fles
79,022,742
6,054,066
How to trigger `tenacity` retry without raising exception?
<p>How can I trigger a retry within python tenacity library without raising an exception?</p> <p>The reason I want this is that while debugging at every raise of an error, the debugger stops. (This can be switched off by unticking <code>User Uncaught Exceptions</code> (in VSCode), but that means the debugger doesn't st...
<python><exception><tenacity>
2024-09-25 11:54:54
1
450
semyd
79,022,388
2,071,807
Factory Boy instance with start date before end date using SelfAttribute and Faker
<p>Similar to <a href="https://stackoverflow.com/questions/35508293/faker-having-end-date-greater-than-start-date">this question about Laravel</a> I'm hoping to create a FactoryBoy instance with start date before end date like this:</p> <pre class="lang-py prettyprint-override"><code> from dataclasses import dataclass...
<python><faker><factory-boy>
2024-09-25 10:32:18
1
79,775
LondonRob
79,022,245
2,537,394
OpenCV doesn't read images from some directories
<p>I'm trying to read a 16-bit grayscale PNG with OpenCV. This image is stored on a network share. When I try to load the image with <code>cv.imread()</code> nothing is returned:</p> <pre class="lang-py prettyprint-override"><code>import cv2 as cv print(img_paths[0]) print(type(img_paths[0])) print(img_paths[0].exists(...
<python><opencv><unicode><path>
2024-09-25 09:57:49
2
731
YPOC
79,021,917
9,542,989
Deploying Python-based Chat Bots for MS Teams
<p>I am trying to deploy a simple Microsoft Teams using one of the provided samples, but I cannot seem to get it running.</p> <p>Here are the steps that I followed:</p> <ol> <li>Cloned the the BotBuilder-Samples repository and navigated to the <a href="https://github.com/microsoft/BotBuilder-Samples/tree/main/samples/p...
<python><bots><botframework><microsoft-teams>
2024-09-25 08:51:39
2
2,115
Minura Punchihewa
79,021,750
12,556,481
find_elements only gets the first element when using Selenium
<p>I have a Python program that uses undetected Chromedriver to scrape product data from Walmart. The following is a simplified version of my code, but it only gets the first element. Can someone show me where the issue is?</p> <pre><code>import time from selenium.webdriver.support import expected_conditions as EC from...
<python><python-3.x><selenium-webdriver>
2024-09-25 08:10:56
0
309
dfcsdf
79,021,726
4,718,423
Increase Python REST requests efficiency
<p>Before, I used SQL joins to get data, and 10.000 lines would take fraction of a second.</p> <pre><code>select name, profession.expertise, resonsible.name, building.locker from technicians join profession on technicin.profession = profession.id join responsible on techician.responsible = responsi...
<python><rest><python-requests>
2024-09-25 08:04:18
1
1,446
hewi
79,021,676
3,581,875
Copy AWS S3 Bucket Between Accounts Cross-Region
<p>We need to copy the contents of a bucket to a new account in a different AWS region.</p> <p>The bucket contains Β±200K objects, most of which are archived (Glacier), and a large portion of them are quite big (&gt;10GB).</p> <p>At first we tried the following:</p> <ol> <li>Batch script to restore all the objects.</li>...
<python><amazon-web-services><amazon-s3>
2024-09-25 07:50:38
1
1,152
giladrv
79,021,659
14,998,459
Extend LabelEncoder classes
<p>I have a <code>LabelEncoder</code> with 500 classes.</p> <p>To store and load it, I used pickle:</p> <pre><code>with open('../data/label_encoder_v500.pkl', 'rb') as file: label_encoder = pickle.load(file) </code></pre> <p>I want to add 24 new classes to this encoder, keeping existing labels unchanged.</p> <pre><...
<python><scikit-learn><label-encoding>
2024-09-25 07:46:37
3
716
TkrA
79,021,428
1,330,984
UI grid alignment suddenly changes during subprocess run
<p>My UI looks like this:</p> <p><a href="https://i.sstatic.net/j3IOMPFd.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/j3IOMPFd.png" alt="enter image description here" /></a></p> <p>As soon as I hit the &quot;Start&quot; button to run the subprocess, my UI alignment goes wrong; the 2 buttons take up th...
<python><tkinter>
2024-09-25 06:39:42
1
16,376
Tom
79,021,346
2,084,314
Mocking a nested function call with pytest
<p>If I have a function, A1, that is being tested, and that function imports and calls function B1, which itself calls B2 from the same file, how do I mock function B2?</p> <p>If I mock with <code>mocker.patch('B.B2', return_value=return_value)</code>, the mocked function doesn't get called. If I mock with 'A.B2', 'A....
<python><pytest>
2024-09-25 06:13:21
1
442
Beez
79,020,997
169,252
Installing module with pip fails, is it possible to edit the versions?
<p>I am trying to install pywallet</p> <p><code>pip install pywallet</code></p> <p>This fails at some point:</p> <pre><code> Downloading protobuf-3.0.0a3.tar.gz (88 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error Γ— python setup.py egg_info did not run successfully. β”‚ exit code:...
<python><pip><module>
2024-09-25 02:59:23
1
6,390
unsafe_where_true
79,020,834
6,601,575
How to set a daily task in an hourly DAG in Airflow?
<p>I have an hourly scheduled DAG in Airflow, the Graph may look like this:</p> <pre><code>A &gt;&gt; B &gt;&gt; C </code></pre> <p>The task <code>A</code> and <code>B</code> need to be executed every hour, but task C just needs to be executed once each day. Can I achieve this in Airflow?</p>
<python><airflow><airflow-2.x>
2024-09-25 01:16:56
1
834
Rinze
79,020,773
687,112
Alternative to setting self.__class__ to something else?
<p>What's the right way to add a method to any member of a set of sibling instances (i.e. each instance's class inherits from a common base class)?</p> <p>The siblings come from <code>fsspec</code> and are out of my control, but it's like this.</p> <pre class="lang-py prettyprint-override"><code>class Base: def ope...
<python>
2024-09-25 00:33:31
1
1,165
Ian
79,020,533
1,496,743
Using multiple client certificates with Python and Selenium
<p>I’m working on a web-scrape project using Python and Selenium with a Chrome driver, which requires client certificates to access pages. I have 2 scenarios it must handle:</p> <ol> <li>Different certificates allow access to different URLs (e.g. Certificate A accesses URLs 1, 2 and 3, and Certificate B accesses URLs ...
<python><google-chrome><selenium-webdriver>
2024-09-24 22:14:57
1
706
VBStarr
79,020,484
6,253,337
Topic modelling many documents with low memory overhead
<p>I've been working on a topic modelling project using <a href="https://maartengr.github.io/BERTopic/index.html" rel="nofollow noreferrer">BERTopic</a> 0.16.3, and the preliminary results were promising. However, as the project progressed and the requirements became apparent, I ran into a specific issue with scalabili...
<python><cluster-analysis><topic-modeling>
2024-09-24 21:57:32
1
1,053
Bbrk24
79,020,422
3,837,778
How to run pytorch inside docker containers on two GCP VM?
<p>I have two GCP VM. on two vms, I run docker container.</p> <p>I run <code>docker run --gpus all -it --rm --entrypoint /bin/bash -p 8000:8000 -p 7860:7860 -p 29500:29500 lf</code></p> <p>I am trying <a href="https://github.com/hiyouga/LLaMA-Factory" rel="nofollow noreferrer">llama-factory</a>.</p> <p>In one container...
<python><docker><pytorch>
2024-09-24 21:31:29
2
9,056
BAE
79,020,378
8,605,685
Do I need to use timezones with timedelta and datetime.now?
<p>If I only use <a href="https://docs.python.org/3/library/datetime.html#datetime.datetime.now" rel="nofollow noreferrer"><code>datetime.now()</code></a> with <a href="https://docs.python.org/3/library/datetime.html#datetime.timedelta" rel="nofollow noreferrer"><code>timedelta</code></a> to calculate deltas, is it saf...
<python><datetime><time><timezone><timedelta>
2024-09-24 21:13:16
2
12,587
Salvatore
79,020,365
5,036,928
Numerical method used by sympy nsolve
<p>How does <code>sympy</code>'s <code>nsolve</code> do what it does?</p>
<python><sympy>
2024-09-24 21:08:45
1
1,195
Sterling Butters
79,020,257
12,076,197
JSON to Pandas Dataframe with null values and missing columns
<p>I am working with a JSON file that is designed as such:</p> <pre><code>f = {'results': [{'tables': [{'rows': [{'column1': 'dog', 'column2': 'blue', 'column3': 'sad'}, { 'column2': 'red', 'column3': 'happy'}, {'c...
<python><json><pandas><dataframe>
2024-09-24 20:25:33
1
641
dmd7
79,020,232
1,735,686
Assign multi-index variable values based on the number of elements in a dataframe that match a selection criteria
<p>I have a large csv dataset the looks like the following:</p> <pre><code>id,x,y,z 34295,695.117,74.0177,70.6486 20915,800.784,98.5225,19.3014 30369,870.428,98.742,23.9953 48151,547.681,53.055,174.176 34026,1231.02,73.7678,203.404 34797,782.725,73.9831,218.592 15598,983.502,82.9373,314.081 34076,614.738,86.3301,171.31...
<python><pandas><dictionary>
2024-09-24 20:18:47
2
6,167
Troy Rockwood
79,020,229
855,395
Creating a default value recursively given a type (types.GenericAlias)
<p>Given a type <code>t</code> (originally comes from function annotations), I need to create a default value of that type. Normally, <code>t()</code> will do just that and work for many types, including basic types such as <code>bool</code> or <code>int</code>. However, <code>tuple[bool, int]()</code> returns an empty...
<python><python-typing>
2024-09-24 20:17:05
1
4,507
Eran Zimmerman Gonen
79,020,226
485,337
How to use a generic function defined in Python?
<p>I have a class and a corresponding factory function that holds some state in a closure (<code>event_bus</code>):</p> <pre class="lang-py prettyprint-override"><code>from typing import TypeVar, Generic, Callable, Any class EventBus: def subscribe(self): print(&quot;Subscribed&quot;) def publish(sel...
<python><generics><python-typing>
2024-09-24 20:16:48
0
30,760
Adam Arold
79,020,191
3,182,496
uwsgi module not found after Python upgrade
<p>I have a Flask/UWSGI application running on my home server. A recent Ubuntu upgrade deleted Python 3.10 and installed Python 3.12 instead. I've made a new venv and installed the application, but it no longer runs. In the UWSGI log it says:</p> <pre><code>ModuleNotFoundError: No module named 'wsgi' </code></pre> <p>M...
<python><flask><uwsgi><wsgi>
2024-09-24 20:06:27
1
1,278
jon_two
79,020,189
4,751,598
Pydantic model for representing datetime as date and time
<p>I have created a Pydantic model for datetime that will handle parsing a JSON object that looks like <code>{ &quot;date&quot;: &quot;2021-07-01&quot;, &quot;time&quot;: &quot;12:36:23&quot; }</code> into <code>datetime(2021, 7, 1, 12, 36, 23)</code>. It also generates the correct JSON Schema for the model.</p> <pre><...
<python><pydantic>
2024-09-24 20:06:20
1
1,016
Matthew Jones
79,020,155
20,591,261
How to Apply LabelEncoder to a Polars DataFrame Column?
<p>I'm trying to use scikit-learn's <code>LabelEncoder</code> with a Polars DataFrame to encode a categorical column. I am using the following code.</p> <pre class="lang-py prettyprint-override"><code>import polars as pl from sklearn.preprocessing import LabelEncoder df = pl.DataFrame({ &quot;Color&quot; : [&quot...
<python><dataframe><scikit-learn><python-polars><label-encoding>
2024-09-24 19:51:17
3
1,195
Simon
79,020,129
2,276,054
CP-SAT | OR-Tools: Get existing variable by name?
<p>Is it possible to get an existing variable by its name? Something like:</p> <pre><code>model = CpModel() model.new_bool_var(&quot;mySuperBoolVar&quot;) # ...many lines later... bv = model.get_bool_var_by_name(&quot;mySuperBoolVar&quot;) </code></pre> <p>Obviously, <code>get_bool_var_by_name()</code> doesn't exist....
<python><or-tools><cp-sat>
2024-09-24 19:41:01
1
681
Leszek Pachura
79,019,920
1,559,401
How to generate multiple lists/vectors (same length) that are unique or partially unique?
<p>I have created the following function that can generate a list of 0s and 1s (basically a bitstring) using randomization.</p> <pre><code>import numpy as np def generate_genome(length: int, max_individuals: int = 0) -&gt; Genome: bits = None if max_individuals &gt; 0: num_individuals = np.random.randi...
<python><algorithm><random>
2024-09-24 18:29:22
1
9,862
rbaleksandar
79,019,861
2,381,348
pandas search across multiple columns return one column if matches
<p><strong>Example data:</strong></p> <pre><code>df1 = pd.DataFrame({ 'a': [1, 6, 3, 9], 'b': ['A', 'B', 'C', 'D'], 'c': [10, 20, 30, 40], 'd': [100, 200, 300, 400] }) df2 = pd.DataFrame({ 'm': [1, 5, 3, 7], 'n': [2, 6, 8, 4], 'o': [9, 10, 11, 12] }) </code></pre> <p><strong>Requirement:</s...
<python><pandas><dataframe>
2024-09-24 18:12:20
1
3,551
RatDon
79,019,852
2,772,805
jQuery in display function of a Python notebook
<p>Is there a way to run jQuery in a display function called in a Python notebook ? I am looking to be able to organize (sort) some div produced and displayed in a notebook.</p> <p>The static js+html version works. Not from a notebook.</p> <pre><code>import matplotlib.pyplot as plt import numpy as np from IPython.displ...
<python><jquery><jupyter-notebook><ipywidgets>
2024-09-24 18:09:32
1
429
PBrockmann
79,019,834
1,227,860
Realtime Plot Using Plotly In a Single Figure Object
<p>I wrote the following code (minimally working example) that uses <code>plotly</code> to show candlestick charts in real-time.</p> <p>It works great.</p> <p>However, the only issue I have is that every time I receive new data there will be a new plotly figure and over time I will end up having many opened figures, wh...
<python><plotly><real-time-data>
2024-09-24 18:03:17
0
2,367
shashashamti2008
79,019,774
15,835,974
How can I delete a specific record from my AWS Glue table?
<p>How can I delete a specific record from my AWS Glue table using Python? My table is linked to an S3 bucket that contains multiple files.</p> <p>So far, the only method I've found to delete a row/record is by deleting the file in the bucket, either using <a href="https://boto3.amazonaws.com/v1/documentation/api/lates...
<python><amazon-web-services><amazon-s3><aws-glue>
2024-09-24 17:46:27
0
597
jeremie bergeron
79,019,656
4,505,998
Hashed cross-product transformation in PyTorch
<p>I want to implement a hashed cross product transformation like the one Keras uses:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; layer = keras.layers.HashedCrossing(num_bins=5, output_mode='one_hot') &gt;&gt;&gt; feat1 = np.array([1, 5, 2, 1, 4]) &gt;&gt;&gt; feat2 = np.array([2, 9, 42, 37, 8]) &g...
<python><numpy><tensorflow><keras><pytorch>
2024-09-24 17:01:20
1
813
David DavΓ³
79,019,523
8,067,642
Is typing.assert_never() removed by command line option -O, similar to assert statement?
<p>In Python, <code>assert</code> statement produces no code if command line optimization options <code>-O</code> or <code>-OO</code> are passed. Does it happen for <code>typing.assert_never()</code>? Is it safe to declare runtime assertions that will not be optimized out?</p> <p>Consider the case</p> <pre class="lang-...
<python><python-typing>
2024-09-24 16:23:29
1
338
makukha
79,019,407
9,251,158
Direct import fails but "from ... import ..." succeeds
<p>I have a Python module called <code>my_module.py</code> in a folder <code>~/my_module</code>. I want to call this module from a Python interpreter and I don't know its directory. I run:</p> <pre><code>import os os.chdir(os.path.expanduser(&quot;~/my_module&quot;)) import my_module </code></pre> <p>and it fails. But...
<python><import><module><syntax>
2024-09-24 15:49:01
1
4,642
ginjaemocoes
79,019,358
2,381,348
Converting pandas dataframe to wiki markup table
<p>I'm automating some data processing and creating jira tickets out of it. Pandas does have <code>to_html</code> or <code>to_csv</code> or even <code>to_markdown</code>. But jira supports only wiki markup for creating a table.</p> <p>e.g.</p> <pre><code>&lt;!-- wiki markup --&gt; ||header1||header2||header3||\r\n|cell...
<python><pandas><dataframe><wiki-markup>
2024-09-24 15:34:39
2
3,551
RatDon
79,019,170
17,160,160
Calculate hours in period. DST aware
<p>I want to calculate a DST aware figure for the total hours in a period localized for Europe/London.</p> <p>Given the start time, I need to generate the end time and then calculate the hours in period.</p> <p>For example:<br /> <strong>MONTHLY PERIOD</strong></p> <pre><code># define start s = pd.to_datetime('2023-03-...
<python><pandas>
2024-09-24 14:47:53
1
609
r0bt
79,019,034
5,558,497
snakemake - specifying memory in resources directive vs. command-line call for individual rule
<p>memory requirements can be defined per rule in the <code>resources</code> directive</p> <pre><code>rule spades: input: rules.aRule.output output: &quot;{sample}/spades/contigs.fasta&quot; resources: mem_mb = 112000 shell: &quot;spades {input} {output}&quot; </code></pr...
<python><snakemake><hpc>
2024-09-24 14:16:31
1
2,249
BCArg
79,019,014
4,575,197
column is not accessible using groupby and apply(lambda)
<p>I'm encountering a <code>KeyError</code> when trying to use the <code>.apply()</code> method on a pandas DataFrame after performing a <code>groupby</code>. The goal is to calculate the weighted average baced on the Industry_adjusted_return column. The error indicates that the <code>'Industry_adjusted_return'</code> ...
<python><pandas><group-by><keyerror>
2024-09-24 14:12:28
1
10,490
Mostafa Bouzari
79,018,901
1,559,401
How to pass item from list that is being sorted to lambda that is used as the key function used for the sorting?
<p>I have a function that evaluates some parameters of the first argument it receives (here <code>item</code>):</p> <pre class="lang-py prettyprint-override"><code>def item_fitness( item, fitness_criterion1, fitness_criterion2 ) -&gt; int: ... return val </code></pre> <p>It does not matter what ...
<python><sorting><lambda>
2024-09-24 13:47:29
2
9,862
rbaleksandar
79,018,581
5,269,892
Python set does not remove duplicate NaNs
<p>Applying <code>set()</code> to a list containing multiple NaN values usually removes duplicate NaN entries.</p> <p><strong>Example</strong>:</p> <pre><code>set([np.nan, 5, np.nan, 17, 5, np.nan, 23]) </code></pre> <p>yields:</p> <pre><code>{5, 17, nan, 23} </code></pre> <p>However, I now have a list originating from...
<python><pandas><set><nan>
2024-09-24 12:19:48
2
1,314
silence_of_the_lambdas
79,018,577
4,729,764
Can't rollback an async session if error in db.commit()
<p>When an error is thrown during <code>await db.commit()</code> call, I am not able to rollback the session due to MissingGreenlet spawn.</p> <p><strong>DB</strong></p> <pre class="lang-py prettyprint-override"><code>async def get_db(self) -&gt; AsyncIterator[AsyncSession]: session = self.scoped_session() try:...
<python><sqlalchemy><fastapi><asyncpg>
2024-09-24 12:18:29
1
3,114
GRS
79,018,410
6,293,886
How to concatenate nested items in dictionary?
<p>I have a nested dictionary and I want to concatenate the items of the nested dictionaries:</p> <pre><code>import random nested_dict = { k: { 'val0': random.sample(range(100), 2), 'val1': random.sample(range(100), 2), } for k in 'abcd' } </code></pre> <p>I can make it with a double-loop li...
<python><dictionary>
2024-09-24 11:34:00
2
1,386
itamar kanter
79,018,294
2,528,453
Custom newline chracter in python socketserver.StreamRequestHandler
<p>I'm implementing a socket server for python. Ideally I would use a <a href="https://docs.python.org/3/library/socketserver.html#socketserver.TCPServer" rel="nofollow noreferrer"><code>socketserver.TCPServer</code></a> in combination with the<code>readline</code>-functionality of <a href="https://docs.python.org/3/li...
<python><sockets><tcp><stream><tcpserver>
2024-09-24 11:02:38
1
1,061
obachtos
79,017,998
2,989,330
Parameterized Enums in Python
<p>In Python, I want to have an enum-like data structure that can be used like the <a href="https://doc.rust-lang.org/book/ch06-01-defining-an-enum.html#the-option-enum-and-its-advantages-over-null-values" rel="nofollow noreferrer"><code>Option</code> enum in Rust</a>: the enum has parameterized member, and an unparame...
<python><enums>
2024-09-24 09:46:34
2
3,203
Green 绿色
79,017,954
10,679,609
Inverse of cumsum for multi-dimensional array in python
<p>I would like to know how to perform the inverse operation of cumulative sum on a multi-dimensional array in Python.</p> <p>For example, we can get cumulative array <code>P</code> of a given 2D array <code>T</code> by</p> <pre><code>import numpy as np T = np.array([[1,3,2],[5,5,6],[1,8,3]]) P = np.cumsum(np.cumsum(T,...
<python><arrays><numpy><cumsum>
2024-09-24 09:38:49
3
694
Sakurai.JJ
79,017,946
10,855,529
"{}" breaking the json_decode()
<p>I want to make the string of empty dictionary to be a struct, but <code>json_decode</code> fails as there are some rows with strings of empty dictionary in a df</p> <pre class="lang-py prettyprint-override"><code>import polars as pl df = pl.DataFrame({ &quot;meta_data&quot;: [&quot;{}&quot;] }) df.with_columns(...
<python><json><dataframe><python-polars>
2024-09-24 09:37:38
2
3,833
apostofes
79,017,811
1,064,416
How to connect custom storage to django
<p>I am writing a custom storage module to use a remote seafile-server as storage for a django (django-cms) installation.</p> <p>File <code>seafile.py</code> is located in the project-folder:</p> <p><a href="https://i.sstatic.net/8EB8gdTK.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/8EB8gdTK.jpg" alt=...
<python><django><storage>
2024-09-24 09:05:24
1
1,021
Rockbot
79,017,748
17,082,611
Circular Import Issue with FastAPI and Pydantic Models
<p>I'm developing an application using FastAPI and Pydantic, and I'm encountering a circular import issue when trying to define my data models.</p> <p>Here are the relevant files:</p> <h3><strong>src/schemas/user.py</strong></h3> <pre class="lang-py prettyprint-override"><code>from typing import List from pydantic impo...
<python><fastapi><importerror><circular-dependency>
2024-09-24 08:49:56
2
481
tail
79,017,560
3,361,462
Free CPU RAM while using tensorflow
<p>At first I am sorry for this question - I know python well, but I have never worked with ML frameworks. In addition it's very hard to create full example of the problem, because I cannot setup GPU on my machine and modyfying the code on the production machine is very hard.</p> <p>Coming to the problem, on the produc...
<python><tensorflow><keras><memory-management><gpu>
2024-09-24 07:57:30
0
7,278
kosciej16
79,017,399
14,720,215
Download large file from s3 using aioboto3 and aiofiles is really slow
<p>I have high-load system, where many users could upload large files (+1gb). After uploading, sometimes, I need to download them from S3 to calculate some meta information. Currently I'm using this code to do this (look at <code>fetch_file</code>):</p> <pre class="lang-py prettyprint-override"><code>def _get_file_exte...
<python><python-3.x><amazon-s3><aiobotocore>
2024-09-24 07:16:45
1
1,338
Kirill Ilichev
79,017,291
11,770,390
How to update and extend dataframe1 with values from dataframe2
<p>I have a dataframe <code>df_old</code> that I want to update with new values from <code>df_new</code>. The dataframes have exactly the same structure, each has records with a first column 'DateTime' that serves as the key column. The result should be a dataframe that is basically a concatenation of <code>df_old</cod...
<python><pandas><dataframe>
2024-09-24 06:43:56
2
5,344
glades
79,017,285
6,689,867
How to remove the @-expressions in a booktabs table created by pylatex?
<p>This code:</p> <pre><code>from pylatex import ( Tabular, ) # make tabular doc = Tabular('lcc', booktabs=True) doc.add_row('A','B','C') doc.add_hline() doc.add_row((1, 2, 3)) doc.generate_tex(&quot;my_table&quot;) </code></pre> <p>produces <code>my_table.tex</code>:</p> <pre><code>\begin{tabular}{@{}lcc@{}}% \...
<python><latex><pylatex>
2024-09-24 06:41:29
1
305
CarLaTeX
79,017,280
4,784,914
Use setup.py / pyproject.toml to compile a library also in editable install
<p>I am setting up a Python package with <code>setuptools</code>, together with <code>pyproject.toml</code>. The Python code is dependent on a C library that needs to be compiled and installed alongside the code (it's a <code>make</code> project).</p> <p>I have put something together that works for a <code>pip install ...
<python><setuptools><setup.py><software-distribution>
2024-09-24 06:40:03
1
1,123
Roberto
79,016,972
1,145,760
Killable socket in python
<p>My goal is to emit an interface to listen on a socket forever ... until someone up the decision chain decides it's enough.</p> <p>This is my implementation, it does not work. Mixing threads, sockets, object lifetime, default params and a language I do not speak too well is confusing.</p> <p>I tested individually dif...
<python><multithreading><sockets>
2024-09-24 04:35:33
1
9,246
Vorac
79,016,874
3,853,711
undefined reference to `Py_DecodeLocale'
<p>I'm embedding Python into a C++ project with example code from <a href="https://docs.python.org/3/extending/embedding.html#very-high-level-embedding" rel="nofollow noreferrer">https://docs.python.org/3/extending/embedding.html#very-high-level-embedding</a>:</p> <p><code>CMakeLists.txt</code>:</p> <pre><code>cmake_mi...
<python><c++><cmake>
2024-09-24 03:32:04
1
5,555
Rahn
79,016,563
289,784
QWebEngineView renders bokeh vizualisation with largish data (~18000 points) slowly
<p>I'm trying to include a Bokeh based visualisation canvas in a Qt application written in Python (using <code>PySide6</code>). So I create the visualisation, save it in an HTML file, and read it in a <code>QWebEngineView</code> widget. It renders fine, but is extremely sluggish to interact with it; e.g. try selectin...
<python><bokeh><pyside6><qwebengineview>
2024-09-23 23:46:24
0
4,704
suvayu
79,016,312
9,235,106
CMake unable to find Python3 in Windows with Miniconda installed
<p>I'm trying to build a project using CMake on Windows, but I'm encountering an error where CMake can't find Python3. I have Miniconda installed on my system.</p> <pre><code>CMake Error at C:/Program Files/Microsoft Visual Studio/2022/Community/Common7/IDE/CommonExtensions/Microsoft/CMake/CMake/share/cmake-3.29/Module...
<python><windows><cmake>
2024-09-23 21:15:05
0
577
Jiawei Lu
79,016,282
2,904,786
How to filter out elements with No Value for certain field
<p>I have a list of Events in Python. The problem I have is that a lot of events don't contain an <code>event_data['pick']['blurb']</code>. How do I create a filtered list with just the events that have this data?</p> <p>The current code shows an error:</p> <pre class="lang-none prettyprint-override"><code> if event...
<python>
2024-09-23 20:59:04
1
421
user237462
79,016,139
9,112,151
How to drop discriminator value from loc in validation error?
<p>I use Pydantic v2. For now I'd like to remove discriminator value from <code>loc</code> or validation error. Please take a look at the code below:</p> <pre><code>from pprint import pprint from typing import Literal, Union, Annotated, Any from pydantic import BaseModel, Field, RootModel, ValidationError from pydanti...
<python><pydantic-v2>
2024-09-23 20:07:37
1
1,019
ΠΠ»ΡŒΠ±Π΅Ρ€Ρ‚ АлСксандров
79,016,125
2,079,111
How to turn off cell spacing in a Word document using python docx? (or any other package)
<p>I have an input word document that has some tables with cell spacing set to 0.02&quot;. I’d like to turn off that cell spacing (or set it to 0) with the code below that uses the python-docx package. However, when I run the code on the input word file and open the output file, the cell spacing is still turned on and ...
<python><openxml><python-docx>
2024-09-23 20:00:17
1
828
Semihcan Doken
79,016,099
3,456,812
Beginner python tensorflow/keras woes... packages not recognized
<p>I am new to python programming and as a means of learning am taking on some fun AI challenges. Not ashamed to admit I've let GPT help me by asking it to assemble some starter code that I can dissect, learn from, and then add to once I understand the basics.</p> <p>In trying to put together a simple convolutional neu...
<python><tensorflow>
2024-09-23 19:53:23
0
1,305
markaaronky
79,015,946
4,511,243
Webpage for adding and removing emails from a text file
<p>I have a very simple webpage which is just going to read a text file listing email addresses and write them into a table. Next to each row there is a delete button to delete that specific email from the list. There is also a button to save the data in the table to a file.</p> <p>I cannot get it to work so I can add ...
<python><html><flask>
2024-09-23 18:55:01
0
681
Frank
79,015,728
4,048,657
Why am I getting "RuntimeError: Trying to backward through the graph a second time"?
<p>My code:</p> <pre class="lang-py prettyprint-override"><code>import torch import random image_width, image_height = 128, 128 def apply_ellipse_mask(img, pos, axes): r = torch.arange(image_height)[:, None] c = torch.arange(image_width)[None, :] val_array = ((c - pos[0]) ** 2) / axes[0] ** 2 + ((r - pos...
<python><pytorch>
2024-09-23 17:37:09
1
1,239
Cedric Martens
79,015,645
4,621,247
How to run Selenium as the user, and not root?
<p>I'm running a Python script with Selenium to authenticate to a service that opens an app via deep linking.</p> <p>The script runs remotely with SSH using sudo, but since Selenium is running as sudo, the deep link fails to open the app. Without sudo, it works fine, but I need the script to run with sudo.</p> <p>Is th...
<python><selenium-webdriver><selenium-chromedriver><sudo>
2024-09-23 17:12:12
2
1,070
Gilbert Williams
79,015,487
1,405,689
Normalization in pandas via function
<p>I have this dataframe:</p> <pre><code> age 0 48 1 7 2 62 3 48 4 51 </code></pre> <p>This code:</p> <pre><code>import pandas as pd import numpy as np def normalizar(x): # Convert x to a numpy array to allow for vectorized operations. x = np.array(x) # Calculate the minimum and maximum values of x....
<python><pandas><numpy>
2024-09-23 16:21:30
1
2,548
Another.Chemist
79,015,439
1,394,353
How do I fill_null on a struct column?
<p>I am trying to compare two dataframes via <code>dfcompare = (df0 == df1)</code> and nulls are never considered identical (unlike <code>join</code> there is no option to allow nulls to match).</p> <p>My approach with other fields is to fill them in with an &quot;empty value&quot; appropriate to their datatype. What ...
<python><python-polars>
2024-09-23 16:06:34
2
12,224
JL Peyret
79,015,399
14,517,452
QState.assignProperty not working in PySide
<p>I saw <a href="https://stackoverflow.com/questions/67717693/qtreewidget-how-to-change-sizehint-dynamically?rq=3">this example</a> using QState, which seems to work with PyQt5. However on trying to use PySide for this, I get this error;</p> <pre><code>Traceback (most recent call last): File &quot;.../qstate-error...
<python><pyqt5><pyside2><pyside6>
2024-09-23 15:55:26
1
748
Edward Spencer
79,015,315
1,406,168
Python script to access Azure Service Bus with Managed identity
<p>I want to send a message to a servicebus from Visual Studio Code, in a simple python script. I want to access the service bus using a managed identity (in this case my own user). From visual studio it would be fairly simple using the authentication part in options.</p> <p>As I understand it in Visual Studio Code you...
<python><azure><visual-studio-code><azureservicebus>
2024-09-23 15:35:46
1
5,363
Thomas Segato
79,015,194
18,769,241
How to define variables in case they their values change through a thread?
<p>I have <code>main.py</code> which looks like the following:</p> <pre><code>... val1, val2 = None, None ... thread1 = threading.Thread(func1, ) thread1.start() while condition: continue else: thread1.join() #check the values of val1 and val2 after the thread had changed them if val1!= None and...
<python>
2024-09-23 15:00:01
1
571
Sam
79,015,156
9,357,484
Python not recognized in laptop although it is installed
<p>The python I have in my laptop did not compile any code. The error said <a href="https://i.sstatic.net/JpddmPH2.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/JpddmPH2.png" alt="enter image description here" /></a></p> <p>I checked the environment variables (path) and the list is as follows</p> <p><a...
<python><python-3.x><environment-variables>
2024-09-23 14:51:46
1
3,446
Encipher
79,015,092
7,972,989
Reverse categories order in hovermode on Plotly
<p>I have a Plotly stacked barplot with specific categories order. On the plot, the categories stack from bottom to top as wanted : bronze, silver, gold.</p> <p>However, it stacks on the reversed order on the hovermode : gold, silver and bronze (from bottom to top as well)</p> <p>Is there any way to correct the order i...
<python><plotly>
2024-09-23 14:37:22
0
2,505
gdevaux
79,015,047
1,841,839
Ollama multimodal - Gemma not seeing image
<p>This sample <a href="https://github.com/ollama/ollama-python/blob/main/examples/multimodal/main.py" rel="nofollow noreferrer">multimodal/main.py</a> appears to show Ollama</p> <p>I am trying to do the same with an image loaded from my machine. I am using the gemma2:27b model. The model is working with chat so that...
<python><ollama><gemma>
2024-09-23 14:26:39
1
118,263
Linda Lawton - DaImTo
79,014,973
432,354
SQL Widgets in Databricks Interactive Serverless Compute Clusters Not Working
<p>I have the following code in a Notebook that creates a widget with three options.</p> <pre class="lang-sql prettyprint-override"><code>create widget dropdown environment default 'int' choices select * from (values ('int'), ('stage'), ('prod')); </code></pre> <p>This runs perfectly fine on a personal all purpose comp...
<python><databricks><azure-databricks><serverless><databricks-sql>
2024-09-23 14:07:06
1
7,329
pvorb
79,014,886
12,550,791
Mocking a class in Python, works in namespace package, but doesn't for regular package
<h1>Context</h1> <p>I'm writing unit tests for my application.</p> <p>I have a module in <code>configuration/connections.py</code> with configuration (usually defined by environment variables):</p> <pre class="lang-py prettyprint-override"><code>from typing import Literal from pydantic_settings import BaseSettings cl...
<python><unit-testing><mocking><pytest>
2024-09-23 13:45:27
1
391
Marco Bresson
79,014,457
12,544,460
Cannot install auto-sklearn Ubuntu 24.04 via conda or pip
<p>I have an issue when installing this library on both Windows and Ubuntu 24.04, and this is Ubuntu. I try other library like TPOT, even successful but still cannot import.</p> <p>with pip: error:</p> <pre><code> File &quot;&lt;string&gt;&quot;, line 293, in setup_package ModuleNotFoundError: No module na...
<python><pip><conda><automl>
2024-09-23 11:44:19
1
362
Tom Tom
79,014,228
1,348,691
ValueError: The model did not return a loss from the inputs, but `model` exists in `train_datasets column_names`
<p>A complete error is:</p> <pre><code>ValueError: The model did not return a loss from the inputs, only the following keys: logits. For reference, the inputs it received are input_ids,attention_mask. </code></pre> <p>However, <code>dataset</code> contains <code>label</code> and <code>train_dataset</code> in the argume...
<python><huggingface-transformers>
2024-09-23 10:30:35
1
4,869
Tiina
79,014,027
11,729,033
How can one have PEP-342 style coroutines where suspending execution and moving to the other context looks like a function call on both ends?
<p>Python generators allow program flow to jump back and forth between two different places, with messages being passed between using <code>.send</code> and <code>yield</code> as per <a href="https://peps.python.org/pep-0342/" rel="nofollow noreferrer">PEP-342</a>. For example:</p> <pre><code>def coroutine(lst): x ...
<python><generator>
2024-09-23 09:35:13
1
314
J E K
79,014,004
2,955,827
How to fill blank cells created by join but keep original null in pandas
<p>I have two dataframe, one is daily and one is quarterly</p> <pre class="lang-py prettyprint-override"><code>idx = pd.date_range(&quot;2023-03-31&quot;, periods=100, freq=&quot;D&quot;) idx_q = idx.to_series().resample(&quot;QE&quot;).last() df1 = pd.DataFrame({&quot;A&quot;: [1, &quot;a&quot;, None], &quot;B&quot;: ...
<python><pandas><dataframe>
2024-09-23 09:30:03
1
3,295
PaleNeutron
79,013,903
1,138,523
How to debug a specific method in VS Code (not main) using python
<p>I have a method <code>cli</code> in <code>mymodule</code> which is the entrypoint for my programm. <code>cli</code> takes several keyword arguments. The module <code>mymodule</code> does <strong>not</strong> contain something like</p> <pre><code>if __name__ == &quot;__main__&quot;: cli(...) </code></pre> <p>How ...
<python><visual-studio-code><debugging>
2024-09-23 09:00:16
1
27,285
Raphael Roth
79,013,736
7,959,614
Fill numpy array to the right based on previous column
<p>I have the following states and transition matrix</p> <pre><code>import numpy as np n_states = 3 states = np.arange(n_states) T = np.array([ [0.5, 0.5, 0], [0.5, 0, 0.5], [0, 0, 1] ]) </code></pre> <p>I would like to simulate <code>n_sims</code> paths where each path consist of <code>n_steps</code>....
<python><numpy>
2024-09-23 08:09:22
1
406
HJA24
79,013,584
855,217
How do I format numbers with leading zeros efficiently in Python?
<p>I have a set of floats in my script, and I'd like to print them from a method with a set number of leading zeros, and decimal points so that (for example): 0.0000 becomes 000.0000 12.1246 becomes 012.1245 etc.</p> <p>I've tried using rjust and an f-string eg.</p> <pre><code>fX = str(str(x)).rjust(4,'0') # and str(f'...
<python><string><formatting>
2024-09-23 07:28:49
2
1,622
Pete855217
79,013,549
4,332,274
How to divide large numbers by small numbers without rounding in Python
<p>Using Python 3, I want to calculate <code>18446744073709550592 / 65536</code>. In Python I get the output:</p> <pre><code>281474976710656 </code></pre> <p>But the actual result is:</p> <pre><code>281474976710655.984375 </code></pre> <p>It is automatically rounded? Is there any way to calculate it accurately?</p> <p>...
<python><python-3.x><integer><largenumber>
2024-09-23 07:19:56
4
307
QChΓ­ Nguyα»…n
79,013,441
4,489,082
pandas.Period for a custom time period
<p>I want to create <code>pandas.Period</code> for a custom time period, for example for a duration <code>starting_time = pd.Timestamp('2024-01-01 09:15:00')</code> and <code>ending_time = pd.Timestamp('2024-01-05 08:17:00')</code>.</p> <p>One way to achieving this is by first getting the <code>pandas.Timedelta</code...
<python><pandas><datetime>
2024-09-23 06:44:08
2
793
pkj
79,013,239
13,447,006
Preventing date conversion in Excel with xlwings
<p>the problem is as the title states. I have a column <code>AX</code> filled with values. The name of the column is &quot;Remarks&quot; and it will contain remarks but some of those remarks are dates and some are full blown notes like &quot;Person A owes Person B X amount.&quot;</p> <p>The problem I'm currently facing...
<python><excel><xlwings>
2024-09-23 05:14:20
2
565
AlphabetsAlphabets
79,013,151
2,058,333
FastAPI VSCode debug in new alpine docker container
<p>I had to update the base image for my python backend from the now deprecated <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" rel="nofollow noreferrer">FastAPI</a> image to a newer Alpine version. Dockerfile below... However, now I can not get VSCode debugger back up because:</p> <pre><code>cd /...
<python><docker><visual-studio-code><docker-compose><fastapi>
2024-09-23 04:24:36
0
5,698
El Dude
79,012,993
7,428,676
Unable to get LinkedIn API statistics - 500 response
<p>I initially get a list of campaign_ids from the LinkedIn account</p> <pre><code>headers = { 'Authorization': f'Bearer {ACCESS_TOKEN}', 'Content-Type': 'application/json' } campaigns_url = f'https://api.linkedin.com/v2/adCampaignsV2?q=search&amp;search.account.values[0]=urn:li:sponsoredAccount:XYZ1234' resp...
<python><python-requests><linkedin-api>
2024-09-23 02:36:46
0
564
IronMaiden
79,012,832
1,601,580
multiprocess.pool.RemoteTraceback and TypeError: Couldn't cast array of type string to null when loading Hugging Face dataset
<p>I’m encountering an error while trying to load and process the GAIR/MathPile dataset using the Hugging Face datasets library. The error seems to occur during type casting in pyarrow within a multiprocessing environment. Below is the code I’m using</p> <pre class="lang-py prettyprint-override"><code>from datasets imp...
<python><python-multiprocessing><huggingface-datasets>
2024-09-23 00:17:04
2
6,126
Charlie Parker
79,012,782
615,525
Need Help Appending Separate Lines of Text Retrieved From Image in Python
<p>I am writing a Program that used Microsoft Computer Vision to read text from images. The line of text is then stored in a string to be used later.</p> <p>I have accomplished that part of my project, which works fine if my image only has a single line of text.</p> <p>However SOMETIMES the text on the image is in mult...
<python><ocr><azure-cognitive-services>
2024-09-22 23:26:18
1
353
user615525
79,012,771
11,249,937
PyTorch model performance drop depending on test dataset batch size on MPS
<p>I have model that uses LSTM and full connected layer</p> <pre><code>Model( (lstm): LSTM(3, 32, num_layers=3, batch_first=True, dropout=0.7) (dense): Linear(in_features=32, out_features=2, bias=True) ) </code></pre> <p>I am training and testing my model using MPS on Apple M2 chip</p> <p>For loss function...
<python><pytorch><apple-silicon>
2024-09-22 23:12:19
0
345
wybot
79,012,503
4,321,525
How to Properly Track Gradients with MyGrad When Using Scipy's RectBivariateSpline for Interpolation?
<p>I'm working on a project where I need to interpolate enthalpy values using <code>scipy.interpolate.RectBivariateSpline</code> and then perform automatic differentiation using <code>mygrad</code>. However, I'm encountering an issue where the gradient is not tracked at all across the interpolation. Here is a simplifie...
<python><numpy><scipy><automatic-differentiation>
2024-09-22 20:00:39
1
405
Andreas Schuldei
79,012,349
595,305
Yield depth on a depth-first non-recursive tree walker?
<p>I'm trying to find a non-recursive &quot;powerful/versatile&quot; tree walker algorithm, ultimately yielding not just the node but the depth of the node, its parent and its sibling index, and able to use a breadth-first search (BFS) or depth-first search (DFS).</p> <p>It is possible to combine depth-first and bread-...
<python><tree><depth-first-search><breadth-first-search>
2024-09-22 18:49:10
2
16,076
mike rodent
79,012,310
11,626,909
dataframe from BeautifulSoup object
<p>I want to create a dataframe from a BeautifulSoup Object -</p> <pre><code>import pandas as pd from requests import get from bs4 import BeautifulSoup import re # Fetch the web page url = 'https://carbondale.craigslist.org/search/apa#search=1~gallery~0~0' response = get(url) # link exlcudes posts with no picures page...
<python><beautifulsoup>
2024-09-22 18:26:38
1
401
Sharif
79,012,165
4,710,409
Google generative ai: gemini not working on android: 403 error
<p>I send my text to &quot;google gemini&quot; using this code in python:</p> <pre><code>import google.generativeai as genai # Create your views here. # add here to your generated API key genai.configure(api_key=&quot;*****&quot;) def ask_question(request): if request.method == &quot;POST&quot;: text = re...
<python><google-gemini><google-generativeai>
2024-09-22 17:07:04
1
575
Mohammed Baashar
79,011,995
2,382,483
Way to perform a numpy "argany" or "argfirst"?
<p>I'd like to reduce a multidimensional array along one axis by finding the <em>first</em> value in the other dims that is truthy/matches some condition, or a default value if no matching elements can be found. So far I'm trying to do this for a 3D array with some simple looping as follows:</p> <pre><code>def first(ar...
<python><numpy>
2024-09-22 15:34:31
2
3,557
Rob Allsopp