QuestionId
int64
74.8M
79.8M
UserId
int64
56
29.4M
QuestionTitle
stringlengths
15
150
QuestionBody
stringlengths
40
40.3k
Tags
stringlengths
8
101
CreationDate
stringdate
2022-12-10 09:42:47
2025-11-01 19:08:18
AnswerCount
int64
0
44
UserExpertiseLevel
int64
301
888k
UserDisplayName
stringlengths
3
30
⌀
77,889,046
13,086,128
polars.read_csv vs polars.read_csv_batched vs polars.scan_csv?
<p>What is the difference between <code>polars.read_csv</code> vs <code>polars.read_csv_batched</code> vs <code>polars.scan_csv</code> ?</p> <p><code>polars.read_csv</code> looks equivalent to <code>pandas.read_csv</code> as they have the same name.</p> <p>Which one to use in which scenario and how they are similar/dif...
<python><python-polars>
2024-01-26 21:20:47
2
30,560
Talha Tayyab
77,888,975
2,465,039
Pydantic serialization of containers of mixed types
<p>Can Pydantic v2 handle containers of mixed types? For example, how would serialization take place in a class defined as follows:</p> <pre><code>class Foo(BaseModel): foo_list: list </code></pre> <p>If the code above is not the recommended way of doing things, what is the recommended way of defining lists that may ...
<python><pydantic><pydantic-v2>
2024-01-26 21:03:06
1
977
user2465039
77,888,944
1,471,980
how do you pull Aruba reports using API calls via Python
<p>I need to login to aruba appliance and get report data using the following api at aruba-airwave endpoint.</p> <p>I have this code so far:</p> <pre><code>import xml.etree.ElementTree as ET # libxml2 and libxslt import requests # HTTP requests import csv import sys # -------------------------------...
<python><aruba>
2024-01-26 20:56:45
1
10,714
user1471980
77,888,886
525,865
running bs4 scraper needs to be redefined to enrich the dataset - some issues
<p>got a bs4 scraper that works with selenium - see far below:</p> <p>well - it works fine so far:</p> <p>see far below my approach to fetch some data form <strong>the given page</strong>: clutch.co/il/it-services</p> <p>To enrich the scraped data, with additional information, i tried to modify the scraping-logic to ...
<python><selenium-webdriver><web-scraping><beautifulsoup>
2024-01-26 20:40:18
2
1,223
zero
77,888,783
7,225,482
Adding values in two array with overlapping dimensions (outer join)
<p>I have two xarrays with values along the same dimension. Some of the points overlap and some points along that dimension are only in the first or the second array. I would like to get a third array that adds the values and assumes 0 for missing values. I think this would be a sum of the two arrays along the dimensio...
<python><python-xarray>
2024-01-26 20:16:14
0
746
Alvaro Aguilar
77,888,735
5,420,229
Insert many-to-many relationship objects using SQLModel when one side of the relationship already exists in the database
<p>I am trying to insert records in a database using SQLModel where the data looks like the following. A House object, which has a color and many locations. Locations will also be associated with many houses. The input is:</p> <pre><code>[ { &quot;color&quot;: &quot;red&quot;, &quot;locations&quot;:...
<python><sql><sqlalchemy><fastapi><sqlmodel>
2024-01-26 20:02:50
1
485
Hannon Queiroz
77,888,477
1,769,327
PyQt6: QThread: Destroyed while thread is still running
<p>Consider the following class that implements QThread:</p> <pre><code>from PyQt6.QtCore import QThread from stream_consumer.streaming_worker import StreamingWorker class GuiStreamerController: def __init__(self, callback_function) -&gt; None: &quot;&quot;&quot;Initialize the class Args...
<python><pyqt><pyqt6>
2024-01-26 18:59:17
1
631
HapiDaze
77,888,418
6,471,140
CUDA path in Sagemaker instances to solve NameError: name '_C' is not defined with GroundingDINO
<p>I'm trying to install and use <a href="https://github.com/IDEA-Research/GroundingDINO" rel="nofollow noreferrer">grounding dino</a> in a Sagemaker instance (with GPU) but i got the error:</p> <pre><code>NameError: name '_C' is not defined </code></pre> <p>I found out the reason is because the variable CUDA_HOME is n...
<python><machine-learning><cuda><amazon-sagemaker>
2024-01-26 18:45:06
2
3,554
Luis Leal
77,888,183
11,170,350
How to find the indexes of stimulated regions in 1D signal python
<p>I have a 1D signal, where some part is at baseline and some at higher amplitude because of stimulus. I want to separate the stimulated segments. Here is the image of attached signal <a href="https://i.sstatic.net/6Qi9j.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/6Qi9j.png" alt="enter image descrip...
<python><signal-processing>
2024-01-26 17:58:47
1
2,979
Talha Anwar
77,887,846
880,874
How can I get my python script to ignore specific characters in my csv file?
<p>I have data in a csv file that contains car loan data.</p> <p>The columns are the car make and model, the total cost, and the APR.</p> <p>So I am using pyPlot and Python to make Pie charts for each make...the pie chart will contain the models for each car manufacturer where the size of the pie section will be determ...
<python><pandas><regex>
2024-01-26 16:53:20
1
7,206
SkyeBoniwell
77,887,703
274,579
How to convert a big bytes object to a list of 32-bit integer values?
<p>I have a <code>bytes</code> object with a length <code>n</code> in bytes that is a multiple of 4. I want to convert it to a list of <code>n/4</code> 32-bit integer values.</p> <p>What is an efficient way to do that?</p> <p>For example, convert <code>x</code> to <code>y</code>:</p> <pre><code>x = b'\x01\x02\x03\x04\x...
<python><python-3.x><type-conversion>
2024-01-26 16:31:00
5
8,231
ysap
77,887,623
5,838,180
How to make a figure with scatter plots on the sky as subplots?
<p>I am trying to make a figure with 4 subplots (in 2 columns and 2 rows). Each of them should contain a healpy projscatter subplot or a scatter plot on the sky of another kind. But I see no easy way provided by healpy to do this. Can someone provide a useful code? thx</p>
<python><matplotlib><plot><healpy>
2024-01-26 16:18:08
1
2,072
NeStack
77,887,573
11,402,025
How to auto populate the address in json
<p>This is the json object I have</p> <pre><code>[ { &quot;person&quot;: &quot;abc&quot;, &quot;city&quot;: &quot;united states&quot;, &quot;facebooklink&quot;: &quot;link&quot;, &quot;united states&quot;: [ { &quot;person&quot;: &quot;cdf&quot;, &quot;city&quot;: &quot;ohio&quot...
<python><json><python-3.x><recursion><iteration>
2024-01-26 16:11:53
1
1,712
Tanu
77,887,500
5,790,653
python unable to exit if the first for loop iteration matches
<p>This is <code>file.json</code>:</p> <pre class="lang-json prettyprint-override"><code>[ { &quot;id&quot;: 5, &quot;name&quot;: &quot;Jennifer&quot;, &quot;counts&quot;: 10, &quot;available_days&quot;: [&quot;Sunday&quot;, &quot;Monday&quot;, &quot;Wednesday&quot;], &quot;last_update&quot;: &quo...
<python>
2024-01-26 16:00:24
2
4,175
Saeed
77,887,308
6,486,583
Exception on update() after calling init() for the second time on the same tracker instance
<p>Consider the following code:</p> <pre><code>import cv2 window_name = &quot;Object Tracking&quot; source = cv2.VideoCapture(&quot;.tmp/2024-01-24 22-53-46.mp4&quot;) tracker = cv2.TrackerKCF_create() selectedROI = None while True: ret, frame = source.read() if not ret: print(&quot;Error: Could not...
<python><opencv><computer-vision><object-tracking>
2024-01-26 15:29:49
0
3,415
spirit
77,887,292
13,154,227
Python Django: make strftime return german language, not english
<p>In my Django project, I'm using strftime, specifically <code>%b</code> to get the abbreviated month name. Those names are returned in english. My settings contain the following:</p> <pre><code>LANGUAGE_CODE = 'de' # also tried 'de_DE' USE_I18N = True USE_TZ = True </code></pre> <p>Why does strftime still return engl...
<python><django><strftime>
2024-01-26 15:27:38
2
609
R-obert
77,887,248
4,527,628
Pydantic union discriminator based on field on parent model
<p>I have model like this:</p> <pre><code>class Foo(BaseModel): protocol: str protocol_params: Union[ProtocolOneParam, ProtocolTwoParam] </code></pre> <p><code>ProtocolOneParam</code> and <code>ProtocolTwoParam</code> have no same field with distinguishable value so I can use them as <code>Discriminator</code> ...
<python><python-3.x><pydantic><pydantic-v2>
2024-01-26 15:20:23
2
1,225
M.Armoun
77,887,232
3,747,486
Cannot explode a nested JSON within spark dataframe
<p>I am new to Spark. I am trying to flatten a dataframe but failed to do so with &quot;explode&quot;.</p> <p>The original dataframe schema is like below:</p> <pre><code>ID|ApprovalJSON 1|[{&quot;ApproverType&quot;:&quot;1st Line Manager&quot;,&quot;Status&quot;:&quot;Approved&quot;},{&quot;ApproverType&quot;:&quot;2nd...
<python><json><pyspark>
2024-01-26 15:18:31
1
326
Mark
77,886,972
5,709,240
How to vlookup within a single dataframe?
<p>From the following dataframe (<code>df</code>):</p> <pre><code>|------------+--------------------+-------------| | child_code | child_name | parent_code | |------------+--------------------+-------------| | 900 | World | 0 | | 920 | South-Eastern Asia | 900 | | ...
<python><pandas><dataframe>
2024-01-26 14:34:18
1
933
crocefisso
77,886,724
5,594,008
Call async function from sync inside async FastAPI application
<p>Not sure, that this is possible, but still</p> <p>I have default async FastAPI application, where I have sync function</p> <pre><code>@classmethod def make_values( cls, records: list, symbol: str = None, ) -&gt; list: values = [] for record in records: new_row = SomePydanticMo...
<python><asynchronous><async-await><python-asyncio><fastapi>
2024-01-26 13:50:40
2
2,352
Headmaster
77,886,606
929,122
Executing same operator in cloud composer as multiple tasks
<p>I have a PythonOperator in Airflow that gets executed using Cloud Composer:</p> <pre class="lang-py prettyprint-override"><code>with DAG( dag_id = config['dag_id'], schedule_interval = config['schedule_interval'], default_args = default_args ) as dag: generate_data_task = PythonOperator( ...
<python><google-cloud-platform><airflow><google-cloud-composer-2>
2024-01-26 13:30:47
1
437
drake10k
77,886,416
3,526,758
Altair plot in streamlit: How to add a legend?
<p>I'm using streamlit and need altair to plot (because of available interpolation options).</p> <p>Given this simple code:</p> <pre class="lang-py prettyprint-override"><code>import streamlit as st import altair as alt import pandas as pd data = pd.DataFrame({&quot;x&quot;: [0, 1, 2, 3], &quot;y&quot;: [0, 10, 15, 20...
<python><streamlit><altair>
2024-01-26 12:56:34
1
545
amw
77,886,346
2,148,416
Raising an exception in a custom ufunc in a NumPy ndarray subclass
<p>I'm implementing a NumPy ndarray subclass with a custom <code>equal()</code> universal function.</p> <p>This is a distilled example where the custom <code>equal()</code> ufunc just calls the original:</p> <pre><code>class MyArray(np.ndarray): def __new__(cls, data): return np.array(data).view(MyArray) ...
<python><numpy><numpy-ufunc>
2024-01-26 12:46:29
0
3,437
aerobiomat
77,886,336
8,000,016
How to set Nginx reverse proxy for local Docker Django
<p>I'm developing a docker project with <code>nginx</code> and <code>django</code> services. I've <code>django.conf.template</code> parameterised to pass environment variables dynamically depends on environment.</p> <p>django.conf:</p> <pre><code>upstream django_app { server ${DJANGO_PRIVATE_IP}:${DJANGO_PORT}; } s...
<python><django><docker><nginx>
2024-01-26 12:44:54
2
1,264
Alberto Sanmartin Martinez
77,886,215
10,232,932
Create random datetime column with condition to another datetime column pandas
<p>I have a pandas dataframe df_sample:</p> <pre><code>columnA columnB A AA A AB B BA B BB B BC </code></pre> <p>And I am already creating a random column with some date objects in it:</p> <pre><code>df_sample['contract_starts'] = np.random.choice(pd.date_range('2024-01-01', '202...
<python><pandas><dataframe><datetime>
2024-01-26 12:21:40
2
6,338
PV8
77,886,202
5,108,333
Parallel processing in python and need for if __name__ == '__main__'
<p>I've been battling the <strong>need for parallel processing</strong> in my application. I have relatively good understanding that GIL prevents concurrent processing in a single interpreter, and that there can only be one interpreter per process. At least until <a href="https://peps.python.org/pep-0554/" rel="nofollo...
<python><multiprocessing><subprocess><gil>
2024-01-26 12:19:04
2
1,291
A. Vieira
77,886,168
815,859
Python OpenCV threading with tkinter
<p>I have a small python opencv code to predict age and gender. I also have a GUI tkinter library to print the age on a separate window.</p> <pre class="lang-py prettyprint-override"><code>import cv2 import math import time import argparse import requests import tkinter as tk import threading window = tk.Tk() def ...
<python><multithreading><opencv><tkinter><python-multithreading>
2024-01-26 12:14:43
0
795
Monty Swanson
77,886,120
7,695,845
How to ignore ruff errors in jupyter notebook in VSCode?
<p>I am using ruff to lint and format my Python code in Visual Studio Code. I also work often with jupyter notebooks inside VSCode. When I do that I get some ruff linting errors that don't really make sense in a notebook such as <code>Module level import not at top of cell</code>:</p> <p><a href="https://i.sstatic.net/...
<python><visual-studio-code><jupyter-notebook><ruff>
2024-01-26 12:06:19
1
1,420
Shai Avr
77,886,066
13,839,945
Plotly colormaps in Matplotlib
<p>I really like the <a href="https://plotly.com/python/builtin-colorscales/" rel="nofollow noreferrer">additional colormaps</a> like 'dense' or 'ice' from plotly. Nevertheless, I am currently using matplotlib for most of my plots.</p> <p>Is there a way to use a pyplot colormap in matplotlib plots?</p> <p>When I take t...
<python><matplotlib>
2024-01-26 11:57:34
1
341
JD.
77,886,057
7,662,164
Unexpected behavior of JAX `vmap` for multiple arguments
<p>I have found that <code>vmap</code> in JAX does not behave as expected when applied to multiple arguments. For example, consider the function below:</p> <pre><code>def f1(x, y, z): f = x[:, None, None] * z[None, None, :] + y[None, :, None] return f </code></pre> <p>For <code>x = jnp.arange(7), y = jnp.arange...
<python><arrays><vectorization><jax>
2024-01-26 11:56:13
1
335
Jingyang Wang
77,885,918
6,494,707
Why finetuning MLP model on a small dataset, still keeps the test accuracy same as pre-trained weights?
<p>I have designed a simple MLP model trained on 6k data samples.</p> <pre><code>class MLP(nn.Module): def __init__(self,input_dim=92, hidden_dim = 150, num_classes=2): super().__init__() self.input_dim = input_dim self.num_classes = num_classes self.hidden_dim = hidden_dim #...
<python><machine-learning><deep-learning><pytorch><neural-network>
2024-01-26 11:32:05
1
2,236
S.EB
77,885,815
5,547,553
How to get string match starting position in str.contains() on polars?
<p>I know I can use str.contains() to check if a string is contained in a column, like:</p> <pre><code>import polars as pl df = pl.DataFrame({&quot;a&quot;: [&quot;my name is Bob&quot;,&quot;my little pony, my little pony&quot;]}) (df.with_columns(bbb = pl.col('a').str.slice(1,10000).str.contains(pl.col('a').str.slice(...
<python><regex><dataframe><python-polars>
2024-01-26 11:15:33
1
1,174
lmocsi
77,885,792
7,133,942
How to change the order of bars in a matplotlib barchart
<p>I have the following code</p> <pre><code>import matplotlib.pyplot as plt from datetime import datetime co2_prices = [100, 60] electricity_prices = [-2.6, 157] co2_timestamps = [&quot;March 2023&quot;, &quot;February 2024&quot;] electricity_timestamps = [&quot;24.09.2023 14:00&quot;, &quot;24.09.2023 19:00&quot;] ...
<python><matplotlib>
2024-01-26 11:11:30
1
902
PeterBe
77,885,787
9,132,526
Resume from checkpoint with Accelerator causes loss to increase
<p>I've been working on a project to attempt to finetune Stable Diffusion and introduce layout conditioning. I'm using all the components of Stable diffusion from the huggingface stable diffusion pipeline as frozen and only the Unet and my custom model called LayoutEmbeddeder for the conditioning are not frozen.</p> <p...
<python><huggingface><stable-diffusion><accelerate>
2024-01-26 11:10:59
1
355
Suemayah Eldursi
77,885,674
1,581,090
How can I find the best possible shift to correlate two data sets in NumPy?
<p>In Python, I have a two-dimensional data set consisting of the two lists, <code>x1</code> and <code>y1</code>. I also have another set, <code>x2</code> and <code>y2</code>, defined as follows:</p> <pre><code>import random import numpy as np import matplotlib.pyplot as plt # Define the real shift shift = 50.5 # Flu...
<python><numpy><correlation>
2024-01-26 10:51:24
1
45,023
Alex
77,885,605
8,003
Toggling character format with PyQt6
<p>I'm writing a custom word processor as a hobby project. I'm using Python and PyQt6.</p> <p>I wrote the following. The intent is that if I select some text and apply Bold formatting (for example, by hitting &quot;ctrl-b&quot;), it will toggle the formatting. Specifically, it should remove the bold formatting if all o...
<python><pyqt6>
2024-01-26 10:36:48
1
11,687
Ovid
77,885,145
5,170,442
How can I suppress ruff linting on a block of code
<p>I would like to disable/suppress the ruff linter (or certain linting rules) on a block of code. I know that I can do this for single lines (by using <code># noqa: &lt;rule_code&gt;</code> at the end of the line) or for entire files/folder (<code>#ruff: noqa &lt;rule_code&gt;</code> at the top of the file).</p> <p>Ho...
<python><lint><ruff>
2024-01-26 09:08:08
2
653
db_
77,885,120
16,383,578
How to open $MFT in Python?
<p>I need to open <code>&quot;//?/D:/$MFT&quot;</code> in binary read mode to parse its contents, I need the raw binary data from Master File Table to resolve <em><strong>File Record Segments</strong></em> from <code>&quot;D:/System Volume Information/Chkdsk/Chkdsk%y%m%d%H%M%S.log&quot;</code>.</p> <p>Long story short ...
<python><ntfs><ntfs-mft>
2024-01-26 09:03:15
0
3,930
Ξένη Γήινος
77,885,055
7,325,581
use AdaptiveAvgPool2d for CNN in pytorch
<p>I try to train a CNN with different size images but it throws an error <code>ValueError: expected sequence of length 1200 at dim 2 (got 1069)</code> when I convert them to tensor.</p> <p>I think it is because of the different size images. But I don't want to resize the images. How can I use AdaptiveAvgPool2d?</p> <p...
<python><pytorch><conv-neural-network>
2024-01-26 08:47:14
1
1,063
just_code_dog
77,885,015
5,056,347
Convert string to boolean using database expression in Django (for generated field)
<p>I have the following models code:</p> <pre class="lang-py prettyprint-override"><code>class Product(models.Model): ... barcode_data = models.CharField( max_length=255, blank=True, default=&quot;&quot;, ) @property def is_scannable(self): if self.barcode_data: ...
<python><django><django-models>
2024-01-26 08:40:32
1
8,874
darkhorse
77,884,899
10,452,700
What is difference between aggregation and resampling over historical data within pandas data frame?
<p>I'm experimenting with the characterization of data over time. Let's say I have the following time data:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd import scipy.signal as signal import matplotlib.pyplot as plt # Function to generate triangular wave def generate_triang...
<python><pandas><time-series><aggregate><downsampling>
2024-01-26 08:17:20
0
2,056
Mario
77,884,695
2,465,039
How can I replicate Pydantic v1 behaviour of json_encoders in pydantic v2?
<p>The latest versions of Pydantic v2 have resurrected the configuration option of <code>json_encoders</code> (see <a href="https://docs.pydantic.dev/latest/api/config/#pydantic.config.ConfigDict.json_encoders" rel="nofollow noreferrer">https://docs.pydantic.dev/latest/api/config/#pydantic.config.ConfigDict.json_encode...
<python><pydantic>
2024-01-26 07:32:03
1
977
user2465039
77,884,413
8,047,378
When I convert a PyTorch model to onnx, I get many files, why?
<p>when I convert a torch model to onnx, I get many files like you can see in the images below:</p> <p><a href="https://i.sstatic.net/jO4m3.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/jO4m3.png" alt="enter image description here" /></a></p> <p><a href="https://i.sstatic.net/WYFks.png" rel="nofollow n...
<python><pytorch><onnx>
2024-01-26 06:01:53
1
939
Frank.Fan
77,884,368
6,766,408
Unable to get XPath as values and location is changing
<p>I have one application under test. I want to test the numbers and verify with expected values using robot framework. As values and location is changing after importing one file it is hard to get the xpaths. I tried with all the xpaths like with Selectors Hub OR normal chrome xpath. How to get these values as it is c...
<python><selenium-webdriver><xpath><robotframework><automation-testing>
2024-01-26 05:42:17
2
312
ADS KUL
77,884,311
3,220,135
Python winrt how to get notification listener permission?
<p>How is it possible to get needed permission for a notification listener from winrt in python? The following code immediately returns &quot;denied&quot; without any sort of windows prompt showing up:</p> <pre class="lang-py prettyprint-override"><code>import asyncio import winrt.windows.ui.notifications.management as...
<python><notifications><windows-runtime>
2024-01-26 05:18:26
1
11,165
Aaron
77,884,246
11,480,383
How to read openapi json schema and extract API information using python
<p>I have a openapi json schema file. Using Python, I want to read that json file and extract all the APIs defined in it (including API definition, request headers, request body etc...) and execute all those APIs in a loop. API execution part I can handle but what I want to know is there any standard python library to ...
<python><openapi>
2024-01-26 04:50:00
1
700
Prabodha
77,884,044
2,624,770
python csvwriter gives "BrokenPipeError" when used in pipe
<p>Here's an example of what I'm seeing:</p> <pre><code>❯ cat /tmp/test.py #!/usr/bin/env python3 import csv with open(&quot;/dev/stdout&quot;, &quot;w&quot;) as f: csvwriter = csv.writer(f) csvwriter.writerows((_,) for _ in range(10000)) </code></pre> <p>This runs just fine when redirected to a file or to se...
<python><python-3.x>
2024-01-26 03:21:39
1
2,293
keithpjolley
77,884,005
522,815
Python ModuleNotFoundError only in command line execution not in IDE
<p>I see a <code>ModuleNotFoundError</code> error when running a simple program.</p> <p>The project is created using Poetry, and the setup is as shown in the screenshot.</p> <p><a href="https://i.sstatic.net/V5KS2.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/V5KS2.png" alt="enter image description her...
<python><python-import><python-module><modulenotfounderror>
2024-01-26 03:05:20
2
1,823
techjourneyman
77,883,926
50,385
How to make `import` and `from import` diverge in Python?
<p>Say I have the following consecutive lines in a python code base:</p> <pre><code>from foo import BAR # succeeds log.info(f&quot;{dir(BAR)=}&quot;) # succeeds import foo.BAR # succeeds log.info(f&quot;{dir(foo.BAR)=}&quot;) # fails, AttributeError no field BAR in module foo </code></pre> <p...
<python><python-import><attributeerror>
2024-01-26 02:30:52
2
22,294
Joseph Garvin
77,883,758
1,401,560
Why this exception using Paramiko?
<p>I'm trying to teach myself Python to connect to an SFTP server. I tried out this sample code from <a href="https://pythoneo.com/how-do-i-change-directories-using-paramiko/" rel="nofollow noreferrer">How do I change directories using Paramiko?</a>.</p> <pre class="lang-py prettyprint-override"><code>import paramiko ...
<python><python-3.x><paramiko>
2024-01-26 01:22:35
1
17,176
Chris F
77,883,755
1,297,248
Logging causing OSError and .nfs files
<p>I have this logger.py file:</p> <pre><code>import logging from logging.handlers import TimedRotatingFileHandler FORMAT = '%(asctime)s %(message)s' log = logging.getLogger(__name__) log.setLevel(logging.INFO) handler = TimedRotatingFileHandler('/mnt/NFS-drive/debug.log', when='midnight', backupCount=7) handler.setFo...
<python><nfs>
2024-01-26 01:21:21
1
6,409
Batman
77,883,709
4,770,412
How to resolve python path error while trying to write to a file from different sub directory
<p>In my Python project, my logger script is supposed to create a log file in the logs dir, my logger class is present in src/logger.py and logs/ and src are at the same level. when the logger tries to create a log file it tries to find log/ in src/ dir and errors out</p> <p>project structure</p> <pre><code>. ├── READM...
<python>
2024-01-26 00:57:26
1
413
Aamir Shaikh
77,883,624
687,739
Filter a pandas DataFrame by a dict
<p>Assume I have a DataFrame like this:</p> <pre><code> Num1 Num2 1 1 0 2 3 2 3 5 4 4 7 6 5 9 8 </code></pre> <p>And I have a dictionary like this:</p> <pre><code>d = { &quot;Num1&quot;: 2, &quot;Num2&quot;: 5 } </code></pre> <p>I want to retu...
<python><pandas>
2024-01-26 00:26:23
3
15,646
Jason Strimpel
77,883,535
1,519,058
Order dataframe by conditions combining many columns
<p>I have two advanced sorting scenarios.</p> <p>They are independent cases so I have listed below a sample with expected results.</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd a={ &quot;ip&quot;:['10.10.11.30','10.10.11.30','10.10.11.30', '10.2.2.10', '10.10.2.1', '10.2.2.2'], &quot;path...
<python><python-3.x><pandas><dataframe><sorting>
2024-01-25 23:47:17
2
4,963
Enissay
77,883,462
687,739
Get minimum unique tuple pair from list of tuples
<p>Consider the following list of tuples:</p> <pre><code>transactions = [ ('GBP.USD', '2022-04-29'), ('SNOW', '2022-04-26'), ('SHOP', '2022-04-21'), ('GBP.USD', '2022-04-27'), ('MSFT', '2022-04-11'), ('MSFT', '2022-04-21'), ('SHOP', '2022-04-25') ] </code></pre> <p>I can get the tuple with t...
<python><tuples>
2024-01-25 23:21:45
6
15,646
Jason Strimpel
77,883,300
1,519,417
Full page screenshot with Selenium Chrome driver in Python
<p>AI insists that for Selenium 4 or later to take the full page screenshot with <code>webdriver.Chrome()</code>, you can use the 'full' argument in <code>driver.get_screenshot_as_file(&quot;screenshot.png&quot;, full=True)</code>. However, I get error message</p> <blockquote> <p>TypeError: WebDriver.get_screenshot_as_...
<python><selenium-webdriver><selenium-chromedriver>
2024-01-25 22:33:02
1
668
Vladimir
77,883,267
2,299,939
Updating MP3 metadata with Python and music-tag
<p>I'm trying to use a Python 3 script to edit the metadata of MP3 (and other) files using music-tag (0.4.3) but with mixed success. I say &quot;mixed&quot; because it works for some fields and not for others.</p> <p>I'm wondering if it's related to how I'm using the names of the fields (capitalisation etc.) or the for...
<python><metadata><mp3><vlc>
2024-01-25 22:24:35
1
479
Ratler
77,883,241
1,701,812
Get specific form of range in Python 3
<p>When getting <code>range(1,100)</code> I get:</p> <pre><code>[ 1, 2, 3, 4, 5 ... 99 ] </code></pre> <p>I need something like zip of this range:</p> <pre><code>[ 50, 49, 51, 48, 52, 47, 53 ... 99 ] </code></pre> <p>How to get it?</p> <hr /> <p><strong>Background</strong>: It is all about Bitcoin puzzle 66.</p> <p>Fir...
<python><python-3.x><range>
2024-01-25 22:13:14
5
752
pbies
77,883,215
11,278,478
Get column number for Python Melt function
<p>I need to unpivot a pandas dataframe. I am using pd.melt() function for this. It is working as expected, now I need to add an additional column &quot;column_number&quot; in my output. Example below:</p> <pre><code>name age gender id a 18 m 1 b 20 f 2 </code></pre> <p>Current Output:</p> <pre><...
<python><python-3.x><pandas><dataframe><pandas-melt>
2024-01-25 22:11:54
5
434
PythonDeveloper
77,883,150
3,666,302
Add default values to decorated function and update type signature
<p>I'd like to create decorator which adds default values to function arguments, but preserves the argument names and types of the function signature.</p> <pre class="lang-py prettyprint-override"><code>from typing import Callable def optional[**P](f: Callable[P, None]) -&gt; Callable[P, None]: def wrapper(*args: ...
<python><decorator><typing>
2024-01-25 21:55:22
1
2,950
TomTom
77,883,056
2,512,455
Restrict Flake8 for older Python version
<p>Is there a way how to use flake8 from python 3.11, but restrict it to follow rules of python 3.9?</p> <p>e.g. for mypy, I can add <code>--python-version=X.Y</code></p> <blockquote> <p>This flag will make mypy type check your code as if it were run under Python version X.Y. Without this option, mypy will default to u...
<python><flake8>
2024-01-25 21:31:26
1
365
Michal Vašut
77,883,025
9,698,518
How to read in an environment variable for Jinja2 so that it can be interpolated in an if condition?
<p>I try to wrap-around my head on how to skip certain parts of code based on an environment variable when using a <code>Jinja2</code> template to generate a file with a <code>YAML</code> document. I did some research online, asked ChatGPT, but I did not find any answer that helped me.</p> <p>So I made this minimal exa...
<python><jinja2>
2024-01-25 21:24:22
1
672
mgross
77,882,964
23,260,297
Grouping data and calculating totals for new column
<p>I have a dataframe which contains data to be used in calculations. I have to group rows based on 3 columns and then calculate the totals and plug the totals into a formula.</p> <p>formula = -(totalvalue - totalFP)/ totalquantity where totalvalue is the sum of quantity column totalvalue is the sum of the value column...
<python><pandas>
2024-01-25 21:11:54
1
2,185
iBeMeltin
77,882,942
15,296,744
What is wrong with the function below for calculating simple moving average?
<p>I have written the function below in order to find the <a href="https://en.wikipedia.org/wiki/Moving_average#Simple_moving_average" rel="nofollow noreferrer">SMA</a> of a csv file according to the desired SMA formula, However, something is wrong with my formula which I can't figure it out.</p> <pre><code>def SMA_cal...
<python><numpy><moving-average>
2024-01-25 21:06:05
2
391
Dorrin Samadian
77,882,712
8,942,319
Why does TypedDict alt syntax work for illegal names?
<pre><code>from typing import TypedDict, Optional # This will work Overview = TypedDict('Overview', {'detail.id': Optional[str]}) # This will throw an error # SyntaxError: illegal target for annotation class Overview(TypedDict): 'detail.id': Optional[str] </code></pre> <p>This is on Python 3.8.9</p> <p>Is there a...
<python><python-3.x>
2024-01-25 20:17:10
0
913
sam
77,882,606
159,072
Why am I getting different autocorrelation results from different libraries?
<ol> <li>Why am I getting different autocorrelation results from different libraries?</li> <li>Which one is correct?</li> </ol> <pre><code>import numpy as np from scipy import signal # Given data data = np.array([1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 3.33]) # Compute the autocorrelation using scipy's correlate function au...
<python><pandas><statsmodels><autocorrelation>
2024-01-25 19:55:18
3
17,446
user366312
77,882,500
11,885,185
Regex for phone numbers
<p>I want to catch the phone number from a text using regex.</p> <p>Examples:</p> <p>I have this regex which finds the phone number very well: <code>^((\(?\+45\)?)?)(\s?\d{2}\s?\d{2}\s?\d{2}\s?\d{2})$</code></p> <p>and it catches all the numbers below well.</p> <p>But I cannot catch the &quot;tel.&quot;, &quot;tlf&quot...
<python><regex><regex-group>
2024-01-25 19:34:12
2
612
Oliver
77,882,402
2,657,986
Are hashmaps typically implemented with an array of keys?
<p>Many languages that include hashmaps in the standard library or as builtins, allow the programmer to iterate over the hashmap. For example, in python:</p> <pre><code>d = {&quot;US&quot;: &quot;English&quot;, &quot;Spain&quot;: &quot;Spanish&quot;, &quot;France&quot;: &quot;French&quot;, &quot;Canada&quot;: &quot;Eng...
<python><c++><rust><hashmap><iterator>
2024-01-25 19:13:04
1
939
Isaac D. Cohen
77,882,386
11,092,636
Unexpected Sheet Renaming in OpenPyXL When Only Case Changes
<p>I'm using OpenPyXL in Python to manipulate Excel workbooks. I encountered an unexpected behavior when renaming a sheet. <strong>If I change the name of a sheet to a name that only differs in letter case from its previous name, OpenPyXL appends a '1' to the new name</strong>.</p> <p>Here is a Minimal Reproducible Exa...
<python><openpyxl>
2024-01-25 19:08:06
1
720
FluidMechanics Potential Flows
77,882,308
1,316,702
azura databricks custom function not working (python)
<p>In databricks/python I am trying to create a custom function and I'm receiving an error.</p> <p>here is the function I am trying to create:</p> <pre><code>from pyspark.sql.functions import col, substr def CreateBloombergSymbol(pctym): digitMonth = pctym[6:2:1] match digitMonth: case &quot;01&qu...
<python><match><databricks>
2024-01-25 18:52:16
1
1,277
solarissf
77,882,297
1,028,270
How does class polymorphism work with pydantic models?
<p>I have two classes that inherit from the same parent:</p> <pre><code>class ChildOne(BaseSettings): model_config = SettingsConfigDict( extra=&quot;allow&quot;, ) ... class ChildTwo(BaseSettings): model_config = SettingsConfigDict( extra=&quot;forbid&quot;, ) ... </code></pre> ...
<python><python-typing><pydantic>
2024-01-25 18:49:34
1
32,280
red888
77,882,214
1,949,081
Airflow DAG - Not able to parse {{ ds }}
<p>I have an Airflow DAG and I use {{ ds }} to get the logical date. As per Airflow documentation template {{ ds }} return logical date in format YYYY-MM-DD in string format. So I am using following code to manipulate the dates</p> <pre><code>(datetime.strptime('{{ dag_run.logical_date|ds }}', '%Y-%m-%d') - timedelta(...
<python><airflow-2.x><mwaa>
2024-01-25 18:31:49
1
5,528
slysid
77,882,019
19,198,552
How can I switch to the tkinter text widget shortcuts defined in the TCL documentation when working under Win11?
<p>As I found in the <a href="https://tcl.tk/man/tcl8.5/TkCmd/text.htm" rel="nofollow noreferrer">TCL-documentation</a> Control-a is a shortcut for moving the cursor to the beginning of the line (which works at Linux). But when I use this shortcut at Windows11 it selects all the text in the text widget. There are many ...
<python><tkinter><keyboard-shortcuts><text-widget>
2024-01-25 17:55:29
1
729
Matthias Schweikart
77,881,945
23,002,898
In Django, when i compare two Html texts, how to remove the blank rows with the aim of making the comparison positive despite the blank lines?
<p>I'm comparing two texts with Django. Precisely, i am comparing two HTML codes using Json and <a href="https://docs.python.org/3/library/difflib.html" rel="nofollow noreferrer">difflib</a> module. The two files compared are: <code>user_input.html</code> and <code>source_compare.html</code>,they are compared with the...
<python><python-3.x><django><django-rest-framework><django-views>
2024-01-25 17:42:38
1
307
Nodigap
77,881,821
639,676
How is it possible that jax vmap returns not iterable?
<pre><code>import jax import pgx from jax import vmap, jit import jax.numpy as jnp env = pgx.make(&quot;tic_tac_toe&quot;) key = jax.random.PRNGKey(42) states = jax.jit(vmap(env.init))(jax.random.split(key, 4)) type(states) </code></pre> <p><code>states</code> has a type <code>pgx.tic_tac_toe.State</code>. I was expe...
<python><jax>
2024-01-25 17:18:31
1
4,143
Oleg Dats
77,881,795
23,260,297
list comprehension return a single value instead of a list
<p>I have a column in a dataframe that consists of tuples shaped like this:</p> <pre><code>Prices (0, 30.00) (0, 20.00) (0, 33.00) (-12.00, 0) (-13.00, 0) (0,0) </code></pre> <p>I need to grab the non-zero values from each of the tuples if it exists and replace the tuple as a float in the column.</p> <p>I used list com...
<python><pandas>
2024-01-25 17:15:13
3
2,185
iBeMeltin
77,881,766
3,419,895
is numba a good choice to create program that reads from peripherial and calls python wrapped C code?
<p>first of all I have never used numba, so my questions can have basic answers</p> <p>I would like to write program that reads from peripheral device and processes data in real-time, problem is not in amount of data rather will numba address this quiestions or should I use good old C++/Rust:</p> <ol> <li>I will call p...
<python><performance><numba>
2024-01-25 17:10:30
0
564
quester
77,881,712
8,942,319
TypedDict, illegal target for annotation when using attribute of another TypedDict in definition
<p>I have 2 TypedDicts and in the latter I want to use an attribute of the former in the definition.</p> <pre><code>class Detail(TypedDict): id: Optional[str] to_date: Optional[str] from_date: Optional[str] class Overview(TypedDict): id: Optional[str] 'Detail.to_date': Optional[str] </code></pr...
<python>
2024-01-25 17:01:24
1
913
sam
77,881,635
7,554,826
logging training and validation loss per epoch using huggingface trainer in pytorch to assess bias-variance tradeoff
<p>I'm fine-tuning a transformer model for text classification in Pytorch using huggingface Trainer. I would like to log both the training and the validation loss for each epoch of training. This is so that I can assess when the model starts to overfit to the training data (i.e. the point at which training loss keeps d...
<python><pytorch><loss><huggingface-trainer>
2024-01-25 16:48:10
1
570
Des Grieux
77,881,453
217,332
Interactions between asyncio, pytest, and SQLAlchemy
<p>I have a Python 3.8 program which runs a coroutine that loops infinitely, scheduling other coroutines in the background via <code>create_task</code> but not awaiting them. These coroutines use SQLAlchemy's <code>AsyncEngine</code> to write some data to a database. If an exception is raised, the handler cancels the l...
<python><async-await><sqlalchemy><pytest><python-asyncio>
2024-01-25 16:19:36
1
83,780
danben
77,881,432
5,998,186
End a nested loop in Python
<p>We want make a package of goal kilos of chocolate. We have small bars (1 kilo each) and big bars (5 kilos each). Return the number of small bars to use, assuming we always use big bars before small bars. Return -1 if it can't be done.</p> <pre><code>def make_chocolate(small, big, goal): for i in range(1,big+1): ...
<python><function><loops>
2024-01-25 16:16:20
2
343
Hadsga
77,881,025
10,145,953
Detect presence of a signature opencv
<p>I have an image of a form which contains signatures and I need an automated method of determining if a signature is present in the image. I do not need to match the signature, I just need a basic Boolean response of &quot;yes there is a signature in this image&quot; or &quot;there is no signature in this image.&quot...
<python><opencv><image-processing><object-detection>
2024-01-25 15:14:33
0
883
carousallie
77,880,853
3,952,274
SQLAlchemy: IntegrityError on cascade delete for children with siblings
<p>I have the following ORM (shortend excerpt):</p> <pre><code>class Base(DeclarativeBase): pass class Resource: resource_id: Mapped[UUID] = mapped_column( Uuid, default=uuid.uuid4, primary_key=True, index=True, ) created: Mapped[datetime] = mapped_column(DateTime, serve...
<python><sqlalchemy><orm>
2024-01-25 14:46:00
1
644
thomas
77,880,761
20,591,261
SQLAlchemy CASE Function Issue
<p>I have been trying a lot to understand the issue with my code, but I keep struggling with a the CASE function. I can't see any typo, so any advice would be really appreciated.</p> <p>I want to do the following:</p> <pre><code>jan_case = case([ (and_(logweb_cold.c.FECHA &gt;= '2023-01-01 00:00:00', logweb_cold.c....
<python><sqlalchemy>
2024-01-25 14:34:55
0
1,195
Simon
77,880,757
13,147,413
Polars filter dataframe with multiple conditions
<p>I've got this pandas code:</p> <pre class="lang-py prettyprint-override"><code>df['date_col'] = pd.to_datetime(df['date_col'], format='%Y-%m-%d') row['date_col'] = pd.to_datetime(row['date_col'], format='%Y-%m-%d') df = df[(df['groupby_col'] == row['groupby_col']) &amp; (row['date_col'] - df['date_col'] &l...
<python><dataframe><python-polars>
2024-01-25 14:34:19
2
881
Alessandro Togni
77,880,613
8,919,749
How to construct an axis resulting from a subtraction of two values with matplotlib?
<p>From a json file, I retrieve two dates from two distinct fields: <code>endDate</code> and <code>startDate</code>.</p> <p>I would like to plot on the <code>y</code> axis the difference between these two dates based on another value contained in the json file.</p> <p>With <code>matplotlib</code> is it possible to calc...
<python><date><matplotlib>
2024-01-25 14:12:19
0
380
Mamaf
77,880,604
859,227
Changing legend format for float numbers
<p>The following sample code from <a href="https://windrose.readthedocs.io/en/latest/usage.html" rel="nofollow noreferrer">Windrose</a> ax plot creates a legend which I want to control the number of decimal and fraction digits considering that data are shown in float.</p> <pre><code>from windrose import WindroseAxes fr...
<python><matplotlib><windrose>
2024-01-25 14:10:57
1
25,175
mahmood
77,880,562
5,056,347
How to convert calculated properties (that involve calling other methods) into Django generated fields?
<p>Let's say I have this following model:</p> <pre class="lang-py prettyprint-override"><code>class Product(models.Model): price = models.DecimalField( max_digits=19, decimal_places=4, validators=[MinValueValidator(0)], blank=False, null=False, ) expiry_date = models....
<python><django><django-models>
2024-01-25 14:02:55
2
8,874
darkhorse
77,880,524
7,437,143
How to safely verify a file contains valid Python syntax in java?
<h2>Question</h2> <p>After automatically modifying some Python comments in Java, I would like to verify the file still contains valid Python syntax, how can I do that from Java, without actually running some Python code using an interpreter? (To be explicit: I am looking for a java-only solution, not a solution that ca...
<python><java><syntax-checking>
2024-01-25 13:57:59
2
2,887
a.t.
77,880,286
3,647,782
Is the order of importing tensorflow and torch relevant?
<p>I am using a PyTorch model to run inference on an image, using a standard CNN model.</p> <p>I have noticed that the order in which I import the <code>tensorflow</code> and the <code>torch</code> packages has an effect on the time the inference is taking.</p> <p>When importing <code>tensorflow</code> first, the infer...
<python><tensorflow><pytorch>
2024-01-25 13:20:56
1
659
FabianTe
77,879,969
610,569
Is there a way to save a pre-compiled AutoTokenizer?
<p>Sometimes, we'll have to do something like this to extend a pre-trained tokenizer:</p> <pre><code>from transformers import AutoTokenizer from datasets import load_dataset ds_de = load_dataset(&quot;mc4&quot;, 'de') ds_fr = load_dataset(&quot;mc4&quot;, 'fr') de_tokenizer = tokenizer.train_new_from_iterator( ...
<python><nlp><tokenize><huggingface><huggingface-tokenizers>
2024-01-25 12:26:05
1
123,325
alvas
77,879,888
991,077
Explain Dask-cuDF behavior
<p>I try to read and process the 8gb csv file using <code>cudf</code>. Reading all file at once doesn't fit neither into GPU memory nor into my RAM. That's why I use the <code>dask_cudf</code> library. Here is the code:</p> <pre><code>import dask_cudf as dcf import dask.dataframe as dd exceptions = [&quot;a&quot;, &qu...
<python><dask><chunking><rapids><cudf>
2024-01-25 12:13:44
1
734
shda
77,879,635
610,569
How to reset parameters from AutoModelForSequenceClassification?
<p>Currently to reinitialize a model for <code>AutoModelForSequenceClassification</code>, we can do this:</p> <pre><code>from transformers import AutoModel, AutoConfig, AutoModelForSequenceClassification m = &quot;moussaKam/frugalscore_tiny_bert-base_bert-score&quot; config = AutoConfig.from_pretrained(m) model_from_s...
<python><machine-learning><huggingface-transformers><text-classification><safe-tensors>
2024-01-25 11:34:07
1
123,325
alvas
77,878,932
2,469,032
Specifying a suffixing function in feature_names_out argument of the functiontransformer function in scikit-learn
<p>I want to transform a series of variables 'x1', 'x2' with a squared function using FunctionTransformer and rename the feature names with a suffix 's2_'. For example, 'x1' would become 's2_x1' in the transformed data set. I have the following code:</p> <pre><code>import pandas as pd from sklearn.preprocessing import ...
<python><scikit-learn>
2024-01-25 09:47:55
1
1,037
PingPong
77,878,923
15,915,737
Use the number of active worker as a variable in a function
<p>I'm using <code>ThreadPoolExecutor</code> to create multiple worker in order to download simultaneously multiple table from database with an API. The API limitation is 200 request per minute (<code>rate_limit=60/200</code>), and as I'm trying to download 5 table i use 5 worker (<code>num_worker=5 </code>). Then my t...
<python><function><threadpoolexecutor>
2024-01-25 09:45:54
0
418
user15915737
77,878,907
19,694,624
Discord stops responding on reaction after second iteration
<p>I have a problem with my discord bot. It stops working when I click on second iteration specifically, and it does nothing when I click on any other iteration. It's supposed to call check() function when I click a reaction.</p> <pre><code>import asyncio from discord.ui import Button, View import discord from discord....
<python><python-3.x><discord><discord.py><pycord>
2024-01-25 09:44:36
1
303
syrok
77,878,901
583,464
image reconstruction from predicted array - padding same shows grid tiles in reconstructed image
<p>I have two images, <code>E1</code> and <code>E3</code>, and I am training a CNN model.</p> <p>In order to train the model, I use <code>E1</code> as train and <code>E3</code> as y_train.</p> <p>I extract tiles from these images in order to train the model on tiles.</p> <p>The model, does not have an activation layer,...
<python><tensorflow><machine-learning><image-processing><deep-learning>
2024-01-25 09:43:55
1
5,751
George
77,878,893
9,187,682
python selenium capture requests headers and responses [2024]
<p>I have been using selenium-wire to intercept and work with requests and responses headers, but now in 2024 selenium-wire is no longer maintained so I wonder what would be the alternative from now on.</p> <p>At some point in time selenium maintainers mentioned that this isn't the option for the core library so obviou...
<python><selenium-webdriver><seleniumwire>
2024-01-25 09:42:28
0
345
James Windshield
77,878,768
2,560,685
exec in comand line after a pip install on windows
<p>Hy, I'm on windows, and a python beginner. I do a</p> <pre><code> pip install someInternalTool </code></pre> <p>in order to install some internal tool .</p> <p>issue is, when I do</p> <pre><code>cmd&gt; someInternalTool </code></pre> <p>I have the message &quot;someInternalTool is not recognized as an internal or ex...
<python><windows><pip>
2024-01-25 09:23:39
0
5,182
sab
77,878,728
6,212,718
Polars dataframe: overlapping groups
<p>I am currently converting code from pandas to polars as I really like the api. This question is a more generally question to a previous question of mine (see <a href="https://stackoverflow.com/questions/77868799/polars-dataframe-add-columns-conditional-on-other-column-yielding-different-len">here</a>)</p> <p>I have ...
<python><dataframe><python-polars>
2024-01-25 09:15:53
3
1,489
FredMaster