QuestionId
int64
74.8M
79.8M
UserId
int64
56
29.4M
QuestionTitle
stringlengths
15
150
QuestionBody
stringlengths
40
40.3k
Tags
stringlengths
8
101
CreationDate
stringdate
2022-12-10 09:42:47
2025-11-01 19:08:18
AnswerCount
int64
0
44
UserExpertiseLevel
int64
301
888k
UserDisplayName
stringlengths
3
30
βŒ€
78,660,261
12,946,401
Appropriate applications for the as_strided function
<p>I am practicing on figuring out how to use the as_strided function in numpy. I began with the following example of my own where I generate 5 images of 3 x 3 where each image is full of 1s, the next full of 2s, and so on till 5. If I want convert the (5,3,3) volume to place all images into a single row, I can do the ...
<python><arrays><numpy><memory>
2024-06-24 01:33:52
3
939
Jeff Boker
78,660,242
18,346,591
How do I access FastAPI URL from my docker application?
<p>I have a front end react application hosted on a subdomain (<a href="http://www.admin.example.com" rel="nofollow noreferrer">www.admin.example.com</a>). I also have a backend application that uses FastAPI to communicate with the front-end react application. This backend application is deployed using docker. The fron...
<python><linux><docker><docker-compose><fastapi>
2024-06-24 01:23:28
1
662
Alexander Obidiegwu
78,660,203
9,582,542
Local Azure Function Deployment
<p>I am very green to Azure functions. But I have managed to deploy a function and have it run Successfully when the output is to be created to the current Directory. No issues up to here everything is fine.</p> <p>The next thing I like to do is save the output to a specific folder. This causes an Error. I will list er...
<python><azure-functions>
2024-06-24 00:56:07
1
690
Leo Torres
78,660,117
395,857
How can I export a tokenizer from Huggingface transformers to CoreML?
<p>I load a tokenizer and a Bert model from Huggingface transformers, and export the Bert model to CoreML:</p> <pre><code>from transformers import AutoTokenizer, AutoModelForTokenClassification import torch # Load the tokenizer tokenizer = AutoTokenizer.from_pretrained(&quot;huawei-noah/TinyBERT_General_4L_312D&quot;)...
<python><huggingface-transformers><coreml>
2024-06-23 23:59:46
1
84,585
Franck Dernoncourt
78,660,102
4,139,698
How to iterate through a python list to get each additional list element?
<p>I have a python list that I need to iterate through to get the additional consecutive element.</p> <p>I'm trying to make a string from every other consecutive element in my list named data</p> <p><code>data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, ...]</code></p> <p>I need to turn this into a string that reads ...
<python><loops>
2024-06-23 23:45:18
2
9,199
Charles Jr
78,659,905
893,254
Efficient (vectorized) method of converting a Pandas DataFrame categorical column back into original values
<p>After a quite lengthy series of operations on a Pandas DataFrame I find myself with a categorical type column.</p> <p>This has been created as a result of a <code>pandas.cut()</code> operation.</p> <p>I would like to convert the column back into &quot;values&quot; rather than the current categorical encoding.</p> <p...
<python><pandas>
2024-06-23 21:36:17
1
18,579
user2138149
78,659,844
50,385
async version of Context.run for context vars in python asyncio?
<p>Python has the <a href="https://docs.python.org/3/library/contextvars.html#contextvars.copy_context" rel="nofollow noreferrer"><code>contextvars.copy_context()</code></a> function which lets you store a copy of the current values of all the <code>ContextVars</code> that are currently active. Then later, you can run ...
<python><python-asyncio><python-contextvars>
2024-06-23 21:08:59
2
22,294
Joseph Garvin
78,659,781
3,486,684
If I already have an instance of a super class, how can I create an instance of a child class from it?
<p>How do I properly inherit <em>data</em> from an instantiation of a super class? For example, consider something I can get to work, but is confusing in its behaviour:</p> <pre class="lang-py prettyprint-override"><code>from dataclasses import dataclass from typing import Self @dataclass class SuperClass: hello: in...
<python><inheritance>
2024-06-23 20:39:54
3
4,654
bzm3r
78,659,682
7,713,770
How to add permissions in django admin panel for user?
<p>I have a django app. And I added in the admin panel of django the following permission:</p> <pre><code>Accounts | account | Can view account </code></pre> <p>And in the code of admin.py of the accounts app. I have added this:</p> <pre><code>from django.contrib.auth import get_user_model from django.contrib import ad...
<python><django><django-rest-framework>
2024-06-23 19:51:20
1
3,991
mightycode Newton
78,659,174
7,713,770
How to show permissions in django admin project?
<p>I have a django app. And I try in the admin panel of django restrict user permissions with the AUTHENTICATION AND AUTHORIZATION tab.</p> <p>But I noticed that something is missing in my existing django app on the AUTHENTICATION AND AUTHORIZATION tab.</p> <p>Because I installed a clean install from django. And the AU...
<python><django><django-rest-framework>
2024-06-23 15:56:06
1
3,991
mightycode Newton
78,659,070
3,616,293
How can I vectorize this linalg.lstq() operation?
<p>I am trying to implement a multi-frequency phase unwrapping algorithm using Python3 and NumPy. I have 7 single channel (gray scale) images of shape <code>(1080, 1920)</code>. After stacking them along the third axis I get <code>(1080, 1920, 7)</code>.</p> <p>I have shift-matrix <code>A</code> (which is fixed for all...
<python><numpy><least-squares><array-broadcasting>
2024-06-23 15:17:04
1
2,518
Arun
78,659,055
268,581
Package name with username
<p>Let's suppose there's a company <code>abc</code> that makes a library <code>abc</code>.</p> <p>I'd like to make a Python package that interfaces with <code>abc</code>.</p> <p>I could just call it <code>abc</code>. However, that seems selfish to take that name in case the company itself wants to publish a package usi...
<python><pypi>
2024-06-23 15:08:14
1
9,709
dharmatech
78,659,009
8,964,393
Get minimum through record iterations in pandas dataframe
<p>I have created the following pandas dataframe:</p> <pre><code>import pandas as pd import numpy as np ds = { 'trend' : [1,1,1,1,2,2,3,3,3,3,3,3,4,4,4,4,4], 'price' : [23,43,56,21,43,55,54,32,9,12,11,12,23,3,2,1,1]} df = pd.DataFrame(data=ds) </code></pre> <p>The dataframe looks as follows:</p> <pre><code>display(df...
<python><pandas><dataframe><function><group-by>
2024-06-23 14:50:24
1
1,762
Giampaolo Levorato
78,658,908
4,269,851
IDA Pro change color of variables in pseudocode
<p>Very basic Ida Pro plugin that changes color of <code>MyVar123</code> inside pseudocode window.</p> <p>Problem is this approach is limited to using <a href="https://hex-rays.com/products/ida/support/sdkdoc/group___s_c_o_l_o_r__.html" rel="nofollow noreferrer">ida_lines.SCOLOR_...</a> constants for color. How to defi...
<python><plugins><ida>
2024-06-23 14:11:05
2
829
Roman Toasov
78,658,742
694,716
langchain chat chain invoke does not return an object?
<p>I have a simple example about langchain runnables. From <a href="https://python.langchain.com/v0.1/docs/expression_language/interface/" rel="nofollow noreferrer">https://python.langchain.com/v0.1/docs/expression_language/interface/</a></p> <pre><code>from langchain_core.prompts import ChatPromptTemplate from langcha...
<python><py-langchain>
2024-06-23 12:55:39
2
6,935
barteloma
78,658,424
1,457,380
Matplotlib: set ticks and labels at regular intervals but starting at specific date
<p>I am trying to set the following dates (year only):</p> <p><strong>lab = [1969, 1973, 1977, 1981, 1985, 1989, 1993, 1997, 2001, 2005, 2009, 2013, 2017, 2021, 2025]</strong></p> <p>I tried with <code>dates.YearLocator(base=4)</code>, but didn't find a way to set the starting year. I get the labels starting in 1968 in...
<python><matplotlib>
2024-06-23 10:41:47
1
10,646
PatrickT
78,658,112
14,655,211
How do I repeat question in python if user enters wrong input?
<p>Ξ™ am asking user a series of questions in this loop and assigning each answer to a variable to be used later in my script.</p> <p>I'm also doing some error handling if the user doesn't enter an integer as response but not sure how to get it to repeat the relevant question if the user enters invalid input.</p> <pre><...
<python>
2024-06-23 08:10:15
0
471
DeirdreRodgers
78,658,075
7,339,624
Unexpected horizontal line in discrete inverse Fourier transform of Gaussian function with odd number of samples
<p>I'm implementing a discrete inverse Fourier transform in Python to approximate the inverse Fourier transform of a Gaussian function.</p> <p>While the output looks promising, I'm encountering an unexpected horizontal line when the number of samples <code>n</code> is an odd number.</p> <p>For <code>n = 1000</code> (ev...
<python><numpy><matplotlib><signal-processing><fft>
2024-06-23 07:52:03
0
4,337
Peyman
78,657,967
5,540,159
Signal processing Conv1D Keras
<p>I am learning Keras using signal classification where all values are binary (0 or 1). The input data is a vector of [,32] and the output is [,16]. I have a large dataset more then 400K samples.</p> <p>This is the dataset: <a href="https://www.dropbox.com/scl/fi/bx51lgwsd1pa7l2c4issb/NewNew.csv?rlkey=mpqdttoq74f9s1xl...
<python><keras><deep-learning><neural-network><conv-neural-network>
2024-06-23 06:55:37
0
962
stevGates
78,657,909
482,519
How to build external URL with parameters in flask/jinja2?
<p>Simple question, how can I build URL with parameters for external websites?</p> <p>Flask helper <code>url_for</code> is really handy to build internal links and I was wandering if it could also be used for external links, but it seems that this is not as simple as it sounds.</p> <pre class="lang-html prettyprint-ove...
<python><flask><jinja2>
2024-06-23 06:18:46
2
3,675
ernix
78,657,558
7,583,953
Does a recursive segment tree require more space than an iterative one?
<p>I'm learning the segment tree data structure.</p> <p>I have seen several iterative segment trees that use only 2n space. So I tried to use the same build method in a segment tree with recursive update and sumRange. Is this not allowed? Why can an iterative seg tree be stored in 2n but a recursive one needs 4n? Or do...
<python><algorithm><data-structures><segment-tree>
2024-06-23 01:08:15
1
9,733
Alec
78,657,517
6,147,374
Pushing dataframe to Azure SQL DB table with sqlalchemy
<p>I had a python script to push data frames to Azure SQL DB that was working fine. I now use a new computer and I had to update python and packages used such as sqlalchemy etc</p> <p>Now, the script is executing, but for the part that it pushes dataframe data to SQL tables it is extremely slow, I even tried pyspark an...
<python><sqlalchemy><azure-sql-database>
2024-06-23 00:35:19
1
4,319
Ibo
78,657,390
2,748,409
Accessing elements of an awkward array that are not a passed-in index
<p>I'm trying to access the elements of an awkward array that do <em>not</em> correspond to some particular set of indices. I have 3 events in total with one jet per event and some number of leptons. Each lepton has a particular flag associated with it. For each jet I keep track of the indices of the leptons in that je...
<python><awkward-array>
2024-06-22 23:02:58
2
440
Matt Bellis
78,657,336
12,091,935
Convex Function in CVXPy does not appear to be producing the optimal solution for a battery in an electircal system
<p>I am working on optimizing a battery system(1 MWh) that, in conjunction with solar power(200 kW nameplate capacity), aims to reduce electricity costs for a commercial building. For those unfamiliar with commercial electricity pricing, here's a brief overview: charges typically include energy charges (based on total ...
<python><mathematical-optimization><cvxpy><convex-optimization>
2024-06-22 22:30:22
1
435
Luis Enriquez-Contreras
78,657,208
811,299
Official Python documentation of os.symlink() function is lacking crucial information
<p>This is the header for the section on the os.symlink() function in <a href="https://docs.python.org/3.12/library/os.html#os.symlink" rel="nofollow noreferrer">official python 3.12 documentation</a>, which is the version of python I am running:</p> <pre><code>os.symlink(src, dst, target_is_directory=False, *, dir_fd=...
<python>
2024-06-22 21:09:12
1
4,909
Steve Cohen
78,657,042
1,534,504
How to show tickmarks when using whitegrid seaborn style
<p>I'm struggling to find how to <em>show</em> the tick marks on the x-axis when I enable the <code>whitegrid</code> seaborn style:</p> <pre class="lang-py prettyprint-override"><code>import datetime import itertools import random import pandas as pd import numpy as np import seaborn as sns from matplotlib import pypl...
<python><matplotlib><seaborn><bar-chart>
2024-06-22 19:47:05
0
1,003
Pablo
78,657,029
18,091,372
How can I add custom xtics for a python gnuplotlib plot?
<p>I want to add custom tick labels on the x-axis using the python gnuplotlib.</p> <p>I have tried (using jupyterlab):</p> <pre><code>import numpy as np import gnuplotlib as gp xtics_positions = [0, 2, 4, 6, 8] xtics_labels = [&quot;zero&quot;, &quot;two&quot;, &quot;four&quot;, &quot;six&quot;, &quot;eight&quot;] xti...
<python><gnuplot><jupyter-lab>
2024-06-22 19:41:10
1
796
Eric G
78,656,997
15,763,991
How to Localize Button Labels in discord.py Based on User Locale or Guild Settings?
<p>I am using <code>discord.py</code> to build a Discord bot that includes interactive views with buttons. Each button performs specific actions related to message embed manipulation. I want to localize the button labels so they are displayed in the user's locale or default to the guild's locale. Below is a simplified ...
<python><discord><discord.py>
2024-06-22 19:23:48
1
418
EntchenEric
78,656,978
296,239
Rank within group in Polars?
<p>I have a Polars dataframe like so:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl df = pl.from_repr(&quot;&quot;&quot; β”Œβ”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β” β”‚ c1 ┆ c2 ┆ c3 β”‚ β”‚ --- ┆ --- ┆ --- β”‚ β”‚ str ┆ str ┆ i64 β”‚ β•žβ•β•β•β•β•β•ͺ═════β•ͺ═════║ β”‚ a ┆ a ┆ 1 β”‚ β”‚ a ┆ a ┆ 1 β”‚ β”‚ a ┆ b ┆ 1 β”‚ β”‚ a ┆ c ...
<python><dataframe><window-functions><python-polars>
2024-06-22 19:12:34
1
4,540
ldrg
78,656,475
5,793,672
Using Python heapq.heapify(Array)
<p>I want to use <code>heapq.heapify(Arr)</code> but everytime i want a slice of array to be used without creating new memory allocation for the new array. I want the rest of the array to be as is. example: <code>heapq.heapify(arr[0:3])</code> and use rest of <code>arr[3::]</code> in some calculation and go on changing...
<python><heap>
2024-06-22 15:32:02
1
303
swifty
78,656,452
41,572
Python use wx.CallAfter into HttpServer
<p>I am using python 2.7 and <code>wxPython</code> 2.8. I created a simple desktop application from which the user can start an <code>HTTPServer</code> created from the one builtin in python itself. Server is created in this way:</p> <pre><code>class Services(Thread): def __init__(self): Thread.__init__(sel...
<python><wxpython>
2024-06-22 15:21:13
1
1,123
semantic-dev
78,656,297
17,889,328
Why does importing FastAPI TestClient into my PyCharm debugger session take 24 seconds?
<p>Using PyCharm Pro, importing FastAPI TestClient takes 2 seconds in run mode and 23 in debug. I don't know if this is PyCharm, FastAPI, Starlette, or basically where I start to reduce the time.</p> <p>Here is everything installed in the venv:</p> <pre><code>&gt; uv pip list Package Version -----------------...
<python><debugging><pycharm><fastapi><starlette>
2024-06-22 14:11:17
0
704
prosody
78,656,258
7,134,737
Why leave the variable at the end of the with statement?
<p>I am trying to make sense of the why you would just write a particular variable at the end of the <code>with</code> statement ?</p> <pre><code>from datetime import datetime, timedelta from airflow import DAG from airflow.operators.bash import BashOperator default_args = { 'owner': 'coder2j', 'retries': 5, ...
<python><airflow><contextmanager>
2024-06-22 13:51:59
1
3,312
ng.newbie
78,656,232
3,177,186
Visual Studio Code is adding 5 spaces of indentation for new lines despite all settings being for tabs
<p>I'm using Visual Studio Code with Python and every time I hit enter on a line of code, the next line is indented by 5 spaces. However:</p> <ul> <li>Detect Indentation is OFF</li> <li>Insert spaces when pressing tab is OFF</li> <li>Tab size is 4</li> </ul> <p>My settings per the UI are: <a href="https://i.sstatic.net...
<python><visual-studio-code>
2024-06-22 13:42:45
1
2,198
not_a_generic_user
78,656,159
7,123,797
Are these built-in types mutable or not?
<p>In Python some type is called mutable if it is possible to change the value of any object of this type (without changing the identity of the object).</p> <p>Which of the following built-in types are mutable, and which of them are immutable? And why?</p> <ul> <li>function (in particular, method)</li> <li>module (here...
<python>
2024-06-22 13:09:21
1
355
Rodvi
78,656,115
17,721,722
PostgreSQL Recursive Delete with Foreign Key Constraint
<p>In my PostgreSQL table, when I try to delete a record, I encounter the following error:</p> <pre><code>SQL Error [23503]: ERROR: update or delete on table &quot;parent_table&quot; violates foreign key constraint &quot;parent_table_header_ref_id_id_4fd15d08_fk&quot; on table &quot;child_table&quot; Detail: Key (id)...
<python><postgresql>
2024-06-22 12:59:38
2
501
Purushottam Nawale
78,655,764
914,641
What exactly does the parameter "real_field=True" in the sympy constructor of a quaternion mean?
<p>In the sympy documentation about quatenions <a href="https://docs.sympy.org/latest/modules/algebras.html#sympy.algebras.Quaternion" rel="nofollow noreferrer">https://docs.sympy.org/latest/modules/algebras.html#sympy.algebras.Quaternion</a> the quatenion constructor is defined as:</p> <p><em>class sympy.algebras.Quat...
<python><sympy>
2024-06-22 10:29:16
2
832
Klaus Rohe
78,655,628
7,339,624
Inverse Fourier Transform X-Axis Scaling
<p>I'm implementing a discrete inverse Fourier transform in Python to approximate the inverse Fourier transform of a Gaussian function.</p> <p><a href="https://i.sstatic.net/fcVR2S6t.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/fcVR2S6t.png" alt="enter image description here" /></a></p> <p>The input f...
<python><numpy><fft><continuous-fourier>
2024-06-22 09:31:49
1
4,337
Peyman
78,655,562
12,276,279
How to write a function to read csv files with different separators in pandas in Python?
<p>I have a bunch of CSV files for different years named my_file_2019, my_file_2020, my_file_2023 and so on. Some files have tab separator while others have semi-colon.</p> <p>I want to write a common function to extract data from all files.</p> <p>This was my initial function:</p> <pre><code>def get_data(year): ...
<python><python-3.x><pandas><dataframe><filter>
2024-06-22 08:58:43
1
1,810
hbstha123
78,655,289
21,376,217
How does Python's Binascii.a2b_base64 (base64.b64decode) work?
<p>I checked the source code in <a href="https://www.python.org/downloads/release/python-3124/" rel="nofollow noreferrer">Python</a> and implemented a function that is the same as the Python's <a href="https://docs.python.org/3/library/binascii.html#binascii.a2b_base64" rel="nofollow noreferrer">binascii.a2b_base64</a>...
<python><c++><c><base64>
2024-06-22 06:47:25
2
402
S-N
78,655,265
5,091,964
Unable to alter the text color within a QTableWidget
<p>I wrote a complex program that utilizes a PyQt6 table. I encountered an issue where I was unable to alter the font color within the table. To troubleshoot, I created a smaller program (see below) that generates a single-cell PyQt6 table containing the letter &quot;A&quot; in red font. However, upon executing the cod...
<python><pyqt5><pyqt6>
2024-06-22 06:31:40
1
307
Menachem
78,654,772
3,177,186
Python winreg is updating SOMETHING, but not the Windows registry
<p>I am using winreg to read, write, and change the Windows registry. My program flips a lot of different settings to fix things that annoy me about the windows defaults. When I run it, it seems to work. The changes even persist between Flask runs, even after restarting Windows Explorer, and the computer.</p> <p>But ev...
<python><windows><registry>
2024-06-21 23:44:14
1
2,198
not_a_generic_user
78,654,728
7,339,624
How to calculate continuous Fourier inverse numerically with numpy?
<p>I'm trying to implement a function that calculates the inverse Fourier transform of a continuous function <code>F(Ο‰)</code> to obtain <code>f(x)</code>.</p> <p>My input function is continuous (you can assume it is a lambda function) so I have to approximate it discretely using discrete sampling. Here's my current im...
<python><numpy><fft><continuous-fourier>
2024-06-21 23:18:18
1
4,337
Peyman
78,654,453
6,622,697
How to handle circular dependecy between two tables in SQLAlchemy
<p>I'm having a problem resolving a circular dependency between two tables. Have followed all the information I found, but it still doesn't quite work.</p> <p>My tables look like this</p> <pre><code> run calibration_metric -------------------------------------...
<python><sqlalchemy>
2024-06-21 21:11:45
2
1,348
Peter Kronenberg
78,654,348
922,533
How to enable python includes when EXECing from PHP
<p>I have a small python script for calculating the peaks of a PPG signal, as below.</p> <pre><code>#!/usr/bin/python import numpy as np from scipy.signal import find_peaks # Sample PPG signal ppg_signal = np.sin(2*np.pi*0.5*np.linspace(0, 10, 1000)) + np.random.rand(1000) * 0.2 # Find peaks with prominence of 0.1 an...
<python><php><python-3.x><scipy>
2024-06-21 20:31:02
0
2,156
Doug Wolfgram
78,654,305
1,202,417
Serving generated image from firebase
<p>I'm working on a simple web app, using firebase.</p> <p>Essentially I would like to make it so that whenever a user visits a page it will serve them an image with the text of the url:</p> <p>For example <code>mywebpage.com/happy_birthday/hannah.jpg</code>, would serve the user a simple image takes an image I have st...
<python><firebase><image><google-cloud-functions><python-imaging-library>
2024-06-21 20:15:11
1
411
Ben Fishbein
78,654,233
1,382,667
Selenium get element text after click event
<p>Most modern website have dynamic elements where a click event makes an AJAX call and replaces all or usually part of a webpage. The response can be tracked using the network tab in Developer tools</p> <p>How do you do this in Selenium?</p> <p>In python I thought about grabbing the element text again after the click...
<python><selenium-webdriver>
2024-06-21 19:52:53
0
333
Holly
78,654,158
4,522,501
Is it safe sharing Self-signed certificate to other persons?
<p>I have a python script that I will share with other persons to consume messages from a Kafka service, I dont have experience with security but I have a doubt before assume things. My kafka broker is hosted in DigitalOcean cloud, they provide few certificates and one of them is used to connect via SSL, this is a ca.c...
<python><ssl><apache-kafka><cloud><digital-ocean>
2024-06-21 19:27:42
1
1,188
Javier Salas
78,654,124
2,992,192
Convert a python non-tail recursive function adding sub-folders info to a loop
<p>I wrote a function to get the total size and total files/subdirs of the entire disk or specific folder. The recursive function was very simple:</p> <pre><code># Make the python dirSize function a non recursive one: from pathlib import Path obj = {} def dirSize(dir: Path, size = 0, files = 0, dirs = 0): for sub_...
<python><recursion>
2024-06-21 19:15:03
3
5,209
Marquinho Peli
78,654,028
3,995,256
WxPython Align text in TextCtrl Center Vertical
<p>I am trying to center the text inside a TextCtrl. Many solutions to other similar questions rely on using <code>ALIGN_CENTER_VERTICAL</code> however I cannot do this as I want my text box to be larger than the font height.</p> <p>This is what I am trying now:</p> <pre><code>self.name_tb = wx.TextCtrl(self.showing_pa...
<python><wxpython><wxwidgets>
2024-06-21 18:50:44
0
490
nyxaria
78,653,995
6,622,697
What are the pros and cons of the two different declaritive methods in SQLAlchemy 2.0
<p>This page, <a href="https://docs.sqlalchemy.org/en/20/orm/declarative_tables.html#declarative-table-with-mapped-column" rel="nofollow noreferrer">https://docs.sqlalchemy.org/en/20/orm/declarative_tables.html#declarative-table-with-mapped-column</a>, desribes two different ways of using Declarative Mapping</p> <p>Dec...
<python><sqlalchemy>
2024-06-21 18:41:35
1
1,348
Peter Kronenberg
78,653,824
20,591,261
Efficiently Marking Holidays in a Data Column
<p>I'm trying to add a column that indicates whether a date is a holiday or not. I found some code online, but I believe there's a more efficient way to do it, possibly using a polar method instead of map elements and lambda.</p> <p>Example code:</p> <pre><code>import polars as pl import holidays # Initialize the holi...
<python><dataframe><python-polars><python-holidays>
2024-06-21 17:53:39
2
1,195
Simon
78,653,796
955,558
TTL setting for Redis inside Connection String, is it possible?
<p>I am doing a maintenance on several Python applications, which use connections to Redis services. Due to an infrastructure need, I am reducing the number of variables we will have in the environment settings as much as possible for all applicaitons. Today, the application uses several parameters, for example:</p> <p...
<python><redis><connection-string>
2024-06-21 17:45:39
1
539
Gustavo GonΓ§alves
78,653,649
2,839,803
ModuleNotFoundError message using Python
<p>I'm trying to create an API using Python. In my app folder there are the folders: models, services, tests. In each folder (including app) there is an empty<code> __init__.py</code></p> <p>In my model folder there is Ad.py file.</p> <p>In my services folder there is an AdService.py file.</p> <p>This is part of the co...
<python><module><modulenotfounderror>
2024-06-21 17:02:25
0
582
itzick binder
78,653,638
18,476,381
SQLAlchemy Join statement introducing duplicates
<p>I have two tables <code>component</code> and <code>component_transform</code></p> <pre><code>class Component(BaseModel): __tablename__ = &quot;component&quot; component_id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) component_serial_number: Mapped[str] = mapped_column(String(250),...
<python><sql><sqlalchemy>
2024-06-21 17:00:51
1
609
Masterstack8080
78,653,631
3,821,009
Polars literal DuplicateError using when/then with selectors
<p>Say I have this:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl import polars.selectors as cs df = pl.from_repr(&quot;&quot;&quot; β”Œβ”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β” β”‚ j ┆ k ┆ l β”‚ β”‚ --- ┆ --- ┆ --- β”‚ β”‚ i64 ┆ i64 ┆ i64 β”‚ β•žβ•β•β•β•β•β•ͺ═════β•ͺ═════║ β”‚ 71 ┆ 79 ┆ 67 β”‚ β”‚ 26 ┆ 42 ┆ 55 β”‚ β”‚ 12 ┆ 43 ┆ 85 β”‚ ...
<python><dataframe><python-polars>
2024-06-21 16:58:02
1
4,641
levant pied
78,653,572
15,912,168
How to remove the line breaks that Visual Studio Code includes when saving the code
<p>How to remove the line breaks that's added in the formatting when saving the code in VSCode</p> <p>For example:</p> <p>If I have an expression with multiple validations:</p> <pre class="lang-py prettyprint-override"><code>if True == True or False == True or False == False: </code></pre> <p>It is being formatted as:<...
<python><visual-studio-code><pep8>
2024-06-21 16:42:14
2
305
WesleyAlmont
78,653,525
13,562,186
Python Module not Found after pip install in VSCode
<p>Installed a new fresh version of python and running into the following error in VS Code:</p> <p>Here are the steps I have taken:</p> <ol> <li>Create Virtual Environment and activate:</li> </ol> <p><a href="https://i.sstatic.net/TfowPYJj.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/TfowPYJj.png" alt...
<python><visual-studio-code><pip><modulenotfounderror>
2024-06-21 16:28:17
1
927
Nick
78,653,471
10,200,497
How can I form groups by a mask and N rows after that mask?
<p>My <strong>DataFrame</strong> is:</p> <pre><code>import pandas as pd df = pd.DataFrame( { 'a': [False, True, False, True, False, True, False, True, True, False, False], } ) </code></pre> <p><strong>Expected output</strong> is forming groups like this:</p> <pre><code> a 1 True 2 False 3 ...
<python><pandas><dataframe>
2024-06-21 16:16:23
6
2,679
AmirX
78,653,369
19,276,472
Scrapy + Playwright: calling a synchronous parse_single function from an async parse function
<p>I'm working with scrapy + Playwright.</p> <p>A simplified version of the spider I have currently:</p> <pre><code>class MySpider(CodeSpider): def start_requests(self): url = 'https://www.google.com/search?q=product+designer+nyc&amp;ibp=htl;jobs' yield Request(url, headers=headers, meta={ ...
<python><scrapy><python-asyncio>
2024-06-21 15:57:35
1
720
Allen Y
78,653,112
6,360,521
pybind11 cannot import simplest module
<p>I just started with pybind11 and I wanted to try the <a href="https://pybind11.readthedocs.io/en/stable/basics.html#creating-bindings-for-a-simple-function" rel="nofollow noreferrer">minimal example</a> they provide on their page.</p> <pre><code>#include &lt;pybind11/pybind11.h&gt; int add(int i, int j) { retur...
<python><c++><visual-studio-2022><pybind11><python-3.12>
2024-06-21 15:06:18
0
636
roi_saumon
78,653,069
11,769,133
LevelDB error: plyvel._plyvel.Error: NotFound: c:/tmp/testdb/LOCK: The system cannot find the path specified
<p>I followed <a href="https://stackoverflow.com/a/68862748/11769133">this</a> answer on how to install LevelDB on Windows. Everything went smoothly. The only thing I didn't know how to do (and if I had to it anyway) is step 1.2. Also I didn't do this part: <code>set PYTHONLIB=&lt;full path to plyvel&gt;</code>.</p> <p...
<python><leveldb>
2024-06-21 14:58:28
1
1,142
Milos Stojanovic
78,653,060
12,806,076
How to make a circle inside other circles white and fat?
<p>I have a problem, to change the color of a single circle in my plotly graph. I want to color the third ring white and make it fat and also the 7th ring, to show separate layers.</p> <p>I have tried a lot, like line_color and so on, but it did not affect the ring itself, but the piece of the cake.</p> <p>I will give ...
<python><plotly>
2024-06-21 14:56:39
0
516
LGe
78,652,999
10,785,003
Tortoise ORM: bulk_create update_fields vs on_conflict
<p>To perform upsert operations in Tortoise, we can use the <code>bulk_create</code> method. For this we should provide both <code>update_fields</code> and <code>on_conflict</code> params. Like this:</p> <pre><code>await Users.bulk_create(users_list, on_conflict=fields_list, update_fields=fields_list) </code></pre> <p>...
<python><sql><orm><tortoise-orm>
2024-06-21 14:45:04
0
1,169
Igor Alex
78,652,843
8,741,781
Why does csv.reader with TextIOWrapper include new line characters?
<p>I have two functions, one downloads individual csv files and the other downloads a zip with multiple csv files.</p> <p>The <code>download_and_process_csv</code> function works correctly with <code>response.iter_lines()</code> which seems to delete new line characters.</p> <blockquote> <p>'Chicken, water, cornmeal, s...
<python><django><csv>
2024-06-21 14:12:50
1
6,137
bdoubleu
78,652,758
597,742
Cryptic "OSError: [WinError 10106] The requested service provider could not be loaded or initialized" error from Python subprocess call
<p>When porting some subprocess execution code from Linux to Windows, the Windows version failed with a Python traceback in the executed subprocess that reported <code>OSError: [WinError 10106] The requested service provider could not be loaded or initialized</code></p> <p>None of the answers that came up in a Google s...
<python><subprocess>
2024-06-21 13:54:38
1
41,806
ncoghlan
78,652,649
3,848,833
Append an entry per view to the DEFAULT_FILTER_BACKENDS
<p>In a Django (and DRF) project with a large number of views we have set a list of filter backends in <code>settings.py</code>:</p> <pre><code>REST_FRAMEWORK = { &quot;DEFAULT_FILTER_BACKENDS&quot;: [ # filter backend classes ], # other settings } </code></pre> <p>Some of the view classes need addi...
<python><django><django-rest-framework><django-rest-framework-filters>
2024-06-21 13:34:44
1
12,082
cezar
78,652,436
16,527,170
Pandas Extract Sequence where prev value > current value
<p>Need to extract sequence of negative values where earlier negative value is smaller than current value and next value is smaller than current value</p> <pre><code>import pandas as pd # Create the DataFrame with the given values data = { 'Value': [0.3, 0.2, 0.1, -0.1, -0.2, -0.3, -0.4, -0.35, -0.25, 0.1, -0.15, ...
<python><pandas><dataframe>
2024-06-21 12:46:21
3
1,077
Divyank
78,652,281
13,663,100
Python Polars SQL Interface results in InvalidOperationError on multiple joins
<p>I am struggling to run a query that joins 3 tables together with the middle table joining the other two.</p> <ul> <li>Table A has a column &quot;a&quot;.</li> <li>Table B has columns &quot;a&quot; and &quot;b&quot;.</li> <li>Table C has columns &quot;b&quot; and &quot;c&quot;. (Only column &quot;b&quot; is required)...
<python><python-polars>
2024-06-21 12:11:47
0
1,365
Chris du Plessis
78,652,141
3,906,713
How to vectorize Scipy.integrate.quad()
<p>I have a 1D function <code>f(t)</code> defined on an interval <code>[t0, t1]</code>. I would like to obtain an integral of this function, uniformly sampled over the above interval with a timestep <code>delta_t</code>. The naive solution for this is to use <a href="https://docs.scipy.org/doc/scipy/reference/generated...
<python><performance><scipy><vectorization>
2024-06-21 11:37:43
1
908
Aleksejs Fomins
78,651,589
6,412,997
Converting np.random.logistic to scipy.stats.fisk
<p>I cannot figure out how to convert <code>np.random.logistic</code> to <code>scipy.stats.fisk</code>, here's my code:</p> <pre><code>import numpy as np import numpy.random as npr import scipy.stats as ss import matplotlib.pyplot as plt SEED = 1337 SIZE = 1_000_000 Generator = npr.default_rng(seed=SEED) PARAMS = { ...
<python><numpy><scipy><distribution>
2024-06-21 09:49:27
1
1,996
E.Z
78,651,547
10,889,650
Take value of nearest (L1) non-zero in three dimensional array
<p>I wish to fill all zero valued elements of a three-dimensional numpy array with the value of the &quot;nearest&quot; non-zero valued element (at the point of running the program.) I do not mind which is used when there are multiple with the same distance.</p> <p>I can demonstrate the desired result in 2D:</p> <p>in...
<python><numpy>
2024-06-21 09:40:25
0
1,176
Omroth
78,651,453
5,472,354
Matplotlib LaTeX preamble not correctly interpreted
<p>I was trying to use a custom LaTeX preamble with matplotlib, but it raises</p> <pre><code>ValueError: Key text.latex.preamble: Could not convert ['\\usepackage{siunitx}' ...] to str </code></pre> <p>For some reason, the <code>\</code> are converted into <code>\\</code>, but I don't understand why. I'm using Python v...
<python><string><matplotlib><latex>
2024-06-21 09:19:08
1
2,054
mapf
78,651,412
508,236
Cannot mock the method in dependency module correctly in Python
<p>Here is my project structure</p> <pre><code>|-- project |-- util.py |-- main.py |-- tests |-- test_main.py </code></pre> <p>In the <code>main.py</code> file I reference the function in <code>util.py</code></p> <pre class="lang-py prettyprint-override"><code>from util import rename def use_rename...
<python><testing><mocking>
2024-06-21 09:10:05
1
15,698
hh54188
78,651,332
3,575,623
Define input files for snakemake using glob
<p>I am building a snakemake pipeline for some bioinformatics analyses, and I'm a beginner with the tool. The end users will be mainly biologists with little to no IT training, so I'm trying to make it quite user-friendly, in particular not needing much information in the config file (a previous bioinformatician in the...
<python><glob><snakemake>
2024-06-21 08:52:35
1
507
Whitehot
78,651,311
2,928,970
Hydra sweep lower level parameters in config file
<p>In hydra experiment when I want to sweep over two parameters, why does</p> <pre><code>hydra: mode: MULTIRUN sweeper: params: seed: 'range(1000,1005)' data.index: 'range(0,10)' </code></pre> <p>work, but</p> <pre><code>hydra: mode: MULTIRUN sweeper: params: seed: 'range(100...
<python><fb-hydra>
2024-06-21 08:46:33
1
1,395
hovnatan
78,651,308
4,502,950
{'code': 500, 'message': 'Internal error encountered.', 'status': 'INTERNAL'}
<p>I have several projects in Google cloud that I am using to extract the data from Google Sheets using python. They run daily and refreshes the data in destination. Now this morning, one of the job failed and started throwing the error '<code>{'code': 500, 'message': 'Internal error encountered.', 'status': 'INTERNAL'...
<python><google-sheets><google-cloud-platform>
2024-06-21 08:45:40
0
693
hyeri
78,651,138
20,554,684
How can I parse a .ini file with this type of format?
<p>I would like to parse a generated .ini file containing some config parameters, but I am a little uncertain of the format used. I am not able to change the format of the generated .ini file. This is a snippet of what the format looks like:</p> <pre><code>[Sensors] Sensors = { ( [0]={ SensorTyp...
<python><parsing><ini>
2024-06-21 08:05:53
1
399
a_floating_point
78,651,007
5,251,061
mypy can't infer type of a dictionary value: What's a clean way to still use it as a function argument?
<p>I have a dictionary that I use as my &quot;config&quot;. I don't change values, so it could be immutable. I use its values as arguments for functions via key indexing, something like this:</p> <pre><code>from typing import Union my_config: dict[str, Union[int, float, str]] = { &quot;timeout&quot;: 60, &quot...
<python><mypy><python-typing>
2024-06-21 07:35:48
1
2,358
mc51
78,650,942
2,721,265
Make all if statements true in Jinja2 templates
<p>I am writing a Jinja2 template validator where I want to check all possibly needed variables. I already implemented my own Undefined class and can successfully detect missing variables, but obviously variables within if-statements are not found.</p> <p>I do not want to hardcode multiple if-else-cases, so I am wonder...
<python><jinja2>
2024-06-21 07:19:12
1
1,107
Charma
78,650,882
1,818,935
GridSearchCV runs smoothly when scoring='accuracy', but not when scoring=accuracy_score
<p>When I run the following piece of code in a Jupyter notebook inside Visual Studio Code, it runs smoothly.</p> <pre><code>from sklearn.datasets import load_iris from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import accuracy_score from sklearn.model_selection import GridSearchCV X, y = load_i...
<python><scikit-learn><gridsearchcv>
2024-06-21 07:04:53
0
6,053
Evan Aad
78,650,641
8,973,620
How do I redirect file writing location for a python package?
<p>I have a package that uses one temporary file, and this file is written and loaded using the package functions. The problem is that I am using this package with Azure Functions, and you are only allowed to write to a special location there. How can I force this package to write to this location? The path is defined ...
<python><file-writing>
2024-06-21 06:02:12
3
18,110
Mykola Zotko
78,650,620
11,098,908
Trying to understand pygame.key.get_pressed()
<p>I made the following toy code to understand what <code>pygame.key.get_pressed()</code> means</p> <pre><code>window = pygame.display.set_mode((500, 500)) run = True while run: for event in pygame.event.get(): if event.type == pygame.QUIT: run = False keys = pygame.key.get_pressed() ...
<python><pygame>
2024-06-21 05:55:45
2
1,306
Nemo
78,650,607
561,243
compare numpy array against list of values
<p>I would like to have your help about a problem I have with a numpy array.</p> <p>In my code I have a huge array made of integers, this is the result of a skimage labelling process.</p> <p>The idea is that I want to generate a boolean array with same shape as the input array containing a True value if the cell value ...
<python><numpy><scikit-image>
2024-06-21 05:51:06
1
367
toto
78,650,421
3,777,717
Get variable from identifier in a context
<p>Is it possible in Python to get some abstract representation of a variable, given <code>FrameInfo</code> and location (line number and offset) of its identifier occurrence?</p> <p>What I'd like to be able to do with it is change its value, find its definition site and all occurrences (which may form a proper subset ...
<python><abstract-syntax-tree><code-inspection>
2024-06-21 04:39:23
0
1,201
ByteEater
78,650,388
6,733,980
Not able to import functions from python file
<p>Folder structure:</p> <p><a href="https://i.sstatic.net/8iIs5KTK.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/8iIs5KTK.png" alt="enter image description here" /></a></p> <p>I have a master script which calls <code>requires.py</code> only. The <code>requires.py</code> file is responsible to call all...
<python><python-import>
2024-06-21 04:16:44
1
639
Coding4Life
78,650,371
8,474,894
Convert date column with DDMMMYYYY strings into YYYYMMDD string in Pandas
<p>Convert a date column loaded as strings into a pandas dataframe, in the format <code>DDMMMYYYY</code> (i.e. <code>%d%b%Y</code>) to the desired format of <code>YYYYMMDD</code> (i.e. <code>%Y%m%d</code>).</p> <p>Example: Convert <code>31Oct2023</code> to <code>20231031</code>.</p> <pre class="lang-none prettyprint-ov...
<python><pandas><datetime>
2024-06-21 04:09:38
1
7,403
CypherX
78,650,258
8,521,346
Strange Default Behavior For Python Dict Get Method
<p>We recieve API requests from two versions of embedded systems as follows.</p> <pre><code>data = {&quot;sender&quot;: &quot;555-555-5555&quot;} #new version data = {&quot;from&quot;: &quot;555-555-5555&quot;} #old version </code></pre> <p>To support backwards compatibility with older systems I wrote the code.</p> <p...
<python>
2024-06-21 02:59:36
1
2,198
Bigbob556677
78,650,222
13,086,128
ValueError: numpy.dtype size changed, may indicate binary incompatibility. Expected 96 from C header, got 88 from PyObject
<h2>MRE</h2> <pre><code>pip install pandas==2.1.1 numpy==2.0.0 </code></pre> <p><code>Python 3.10</code> on Google Colab</p> <p>Output</p> <pre><code>Collecting pandas==2.1.1 Downloading pandas-2.1.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (12.3 MB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 12....
<python><python-3.x><pandas><numpy><pip>
2024-06-21 02:43:35
1
30,560
Talha Tayyab
78,649,938
3,486,684
How do I print a python slice as a string separated by ":"?
<p>I have a <a href="https://docs.python.org/3/library/functions.html#slice" rel="nofollow noreferrer"><code>slice</code></a> object, and I'd like to print it out in the form of a string <code>start:stop:step</code>. How do I do so?</p>
<python><string><slice>
2024-06-20 23:38:44
2
4,654
bzm3r
78,649,880
1,711,271
Finding probabilities of each value in all categorical columns across a dataframe
<p>My question is nearly identical to <a href="https://stackoverflow.com/q/70811240">Finding frequency of each value in all categorical columns across a dataframe</a>, but I need the probabilities, instead of the frequencies. We can use the same example dataframe:</p> <pre><code>df = pd.DataFrame( {'sub_code': ['CS...
<python><pandas><categorical-data><pandas-melt>
2024-06-20 23:07:01
1
5,726
DeltaIV
78,649,615
6,622,697
Defined many-to-many with Association table in SQLAlchemy
<p>Updating with a more complete example</p> <p>I've seen many solutions, but I still can't get this to work. I have</p> <pre><code>class ModuleGroupMember(ModelBase): __tablename__ = 'module_group_member' pk = mapped_column(Integer, primary_key=True) module_pk = mapped_column(Integer, ForeignKey('module.pk...
<python><sqlalchemy>
2024-06-20 21:16:38
0
1,348
Peter Kronenberg
78,649,420
6,329,284
Vscode command to run selection in REPL and maintain focus in editor
<p>It seemed like a simple feature but I am unable figure it out.</p> <p>What I want:</p> <p>Work in the editor Execute a selection of lines in the native REPL Maintain focus on the editor from which I selected the lines of code</p> <p>What I have: python.execSelectionInTerminal: this sends commands to the terminal and...
<python><visual-studio-code>
2024-06-20 20:11:46
1
1,340
zwep
78,649,416
2,302,911
UNIX socket data exchange between client and server. Due to the message length, it stops
<p>I'm trying to set up a UNIX socket communication for exchanging floats between a client and a server. The following <a href="https://medium.com/python-pandemonium/python-socket-communication-e10b39225a4c" rel="nofollow noreferrer">tutorial</a> did help a lot and I realized a very simple client python code which sen...
<python><sockets><unix><server><client>
2024-06-20 20:10:46
0
348
Dave
78,649,311
14,498,998
How to add a Tabular Inline to Django's default user's page When The other model has a many to many relation with user model
<p>So I surfed the web for this problems solutions but I couldn't quite find the answer to this problem.</p> <p>Here are my models:</p> <pre><code>class Website(models.Model): url = models.URLField() users = models.ManyToManyField(User) def __str__(self) -&gt; str: return str(self.url) class Prof...
<python><django><many-to-many><admin><user-administration>
2024-06-20 19:36:41
0
313
Alin
78,649,170
297,780
Can’t Install the search-ads-360-python Library
<p>I'm trying to connect with the SearchAds 360 API via a Python script. I'm following their <a href="https://developers.google.com/search-ads/reporting/quickstart/quickstart-guide" rel="nofollow noreferrer">quickstart guide</a> and I’m having trouble installing the <a href="https://developers.google.com/search-ads/rep...
<python><pip>
2024-06-20 18:52:54
1
1,414
Lenwood
78,649,010
3,486,684
How to pass optimization options such as `read_only=True` to `pandas.read_excel` using `openpyxl` as the engine,?
<p>I want to use <a href="https://pandas.pydata.org/docs/reference/api/pandas.read_excel.html" rel="nofollow noreferrer"><code>pandas.read_excel</code></a> to read an Excel file with the option <code>engine=&quot;openpyxl&quot;</code>. However, I also want to pass additional <a href="https://openpyxl.readthedocs.io/en/...
<python><excel><pandas><openpyxl>
2024-06-20 18:05:23
1
4,654
bzm3r
78,648,906
10,470,575
Vectors in Redis Search index are corrupted even though index searches work correctly
<p>I have a redis cache using Redis Search and an HNSW index on a 512 element vector of float32 values.</p> <p>It is defined like this:</p> <pre class="lang-py prettyprint-override"><code>schema = ( VectorField( &quot;vector&quot;, &quot;HNSW&quot;, { &quot;TYPE&quot;: &quot;FLOA...
<python><redis>
2024-06-20 17:33:23
1
466
magnanimousllamacopter
78,648,876
13,088,678
Nested condition on simple data
<p>I have a dataframe having 3 columns, two boolean type and one column as string.</p> <pre><code>from pyspark.sql import SparkSession from pyspark.sql.types import StructType, StructField, BooleanType, StringType # Create a Spark session spark = SparkSession.builder \ .appName(&quot;Condition Test&quot;) \ .g...
<python><apache-spark><pyspark>
2024-06-20 17:22:19
1
407
Matthew
78,648,820
1,182,299
BeautifulSoup output not properly formatted
<p>I'm trying to webscrape some text from a website, the problem is its HTML formatting.</p> <pre><code> &lt;div class=&quot;coptic-text html&quot;&gt; &lt;div class=&quot;htmlvis&quot;&gt;&lt;t class=&quot;translation&quot; title=&quot;The book of the genealogy of Jesus Christ, the son of David, the...
<python><beautifulsoup><python-requests>
2024-06-20 17:05:39
1
1,791
bsteo