question_id
int64
59.5M
79.7M
creation_date
stringdate
2020-01-01 00:00:00
2025-07-15 00:00:00
link
stringlengths
60
163
question
stringlengths
53
28.9k
accepted_answer
stringlengths
26
29.3k
question_vote
int64
1
410
answer_vote
int64
-9
482
79,491,828
2025-3-7
https://stackoverflow.com/questions/79491828/run-a-simple-flask-web-socket-on-render
I'm new to Render , and I make a simple flask web socket I use these modules: ,flask_socketio ,flask ,gunicorn (to run my script on Render host) Here is my code for server side: from flask import Flask from flask_socketio import SocketIO , emit app = Flask("application") socket = SocketIO(app) @app.route("/") def home(...
The timeout with the second client is likely due to the fact that the default synchronous worker can only handle one request at a time. Switching to an asynchronous worker will allow multiple concurrent connections without timing out. Install eventlet: pip install eventlet Modify your Gunicorn command gunicorn -k event...
1
2
79,485,612
2025-3-5
https://stackoverflow.com/questions/79485612/adding-hours-to-a-polars-time-column-in-python
I have a table representing a schedule, i.e. it contains day (monday-sunday), start_time and end_time fields df = pl.DataFrame({ "day": ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"], "enabled": [True, True, True, True, True, False, False], "start_time": ["09:00", "09:00", "09:00", "09:0...
You are right, arithmetic operations between time and duration are not implemented. So we have to do some workaround. The most straightforward method is indeed to combine time with an arbitrary date to form a datetime object, do the math and then keep only the time part. We can avoid introducing a date by casting hours...
5
3
79,490,573
2025-3-6
https://stackoverflow.com/questions/79490573/field-validator-not-called-on-sqlmodel
I have a FastAPI setup of the form: class Foo(sqlmodel.SQLModel, table=True): id: typing.Optional[int] = sqlmodel.Field(primary_key=True) data: str @pydantic.field_validator("data", mode="before") def serialize_dict(cls, value): if isinstance(value, dict): return json.dumps(value) return value @app.post("/foos") def cr...
This is one of the oldest issues with SQLModel (see e.g. this github issue from 2022). Validators are not called on models with table=True.
1
2
79,489,653
2025-3-6
https://stackoverflow.com/questions/79489653/two-threads-using-same-socket-object-problem
I found this example of a simple Python chat implementation, in order to understand how sockets work: #server import socket, threading #Libraries import host = '127.0.0.1' #LocalHost port = 7976 #Choosing unreserved port server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #socket initialization server.bind((host...
A socket is fully bidirectional. It has separate buffers for sending and receiving. One thread can be reading from a socket while another thread is writing to the same socket, that is perfectly OK and does not require any coordination between the threads. Reading does not block writing, and vice versa. What is not OK, ...
1
3
79,490,365
2025-3-6
https://stackoverflow.com/questions/79490365/why-does-a-numpy-transpose-break-mediapipes-image-command
I would like to rotate an image in opencv before putting it into mediapipe. I took a transpose using numpy but, although the type is still numpy.uint8, mediapipe complains, import cv2 import numpy as np import mediapipe as mp image_file_name = "IMG_0237.JPG" cvImage = cv2.imread(image_file_name) cvImage = np.transpose(...
The issue here is that ndarray.transpose does not actually move anything in memory. It simply resets the strides so that accesses APPEAR to be using new locations. mediapipe, on the other hand, requires that the input array be physically contiguous in memory. Your array isn't. You can use np.ascontiguousarray to force ...
2
5
79,490,056
2025-3-6
https://stackoverflow.com/questions/79490056/compute-named-quantiles-in-pandas-using-groupby-aggregate
Among other descriptive statistics, I want to get some quantiles out of my pandas DataFrame. I can get the quantiles I want a couple of different ways, but I can't find the right way to do it with aggregate. I'd like to use aggregate because it'd be tidy and maybe computationally efficient to get all my stats in one go...
You could use a function factory to simplify the syntax: def quantile(q=0.5, **kwargs): def f(series): return series.quantile(q, **kwargs) return f df.groupby('dummy').agg( bell_med=('bell', 'median'), bell_mean=('bell', 'mean'), fish_med=('fish', 'median'), fish_mean=('fish', 'mean'), bell_q10=('bell', quantile(0.1)),...
3
3
79,484,655
2025-3-4
https://stackoverflow.com/questions/79484655/qiskit-attributeerror-parameterexpression-object-has-no-attribute-name-whe
I am trying to optimize a quantum circuit using scipy.optimize.minimize and Qiskit Runtime's Estimator, running on an IBM Quantum real device. However, I am encountering the following error: AttributeError: 'ParameterExpression' object has no attribute 'name' The error occurs inside the minimize function call, specifi...
It was a bug in the QPY serialization. qiskit 1.4.1 and qiskit 2.0.0 have fixes for it.
2
3
79,489,723
2025-3-6
https://stackoverflow.com/questions/79489723/why-is-this-python-code-not-running-faster-with-parallelization
This is a MWE of some code I'm writing to do some monte carlo exercises. I need to estimate models across draws and I'm parallelizing across models. In the MWE a "model" is just parametrized by a number of draws and a seed. I define the functions below. import time import pandas as pd import numpy as np import multipro...
Based on the comment by Nils Werner, I tried disabling multithreading in Numpy. And now I get the gains from parallelization. Interestingly, the serial version is also about twice as fast. import time import os os.environ['OMP_NUM_THREADS'] = '1' os.environ['MKL_NUM_THREADS'] = '1' os.environ['OPENBLAS_NUM_THREADS'] = ...
3
2
79,486,984
2025-3-5
https://stackoverflow.com/questions/79486984/get-an-array-containing-differences-between-two-numpy-arrays-with-some-members-t
I have two very large NumPy arrays containing coordinates [[x1,y1,z1],[x2,y2,z2]...] (~10^9 elements) The arrays are of different sizes, and there will be overlap between the coordinates. So [x1,y1,z1] may be in array1, but not in array2. I would like to quickly get all of the coordinates that are in one, and only one ...
For simple arrays there is setdiff1d() in numpy, however, this does not work for your arrays. If you would write your function from scratch, you could follow one of the following paths: Using list comprehension: def some_function_to_get_diff(array1, array2): unique1 = np.unique(array1, axis=0) # Get the unique coordina...
2
0
79,487,404
2025-3-5
https://stackoverflow.com/questions/79487404/how-to-parse-a-nested-structure-presented-as-a-flat-list
To easily understand my problem, below is a simplified version of some example input. ['foo', 1, 'a', 'foo', 2, 'foo', 1, 'b', 'foo', -1, 'foo', -1, "bar", 1, "c", "bar", 2, 'baz', 1, 'd', 'baz', -1, "bar", 3, "e", "bar", 4, 'qux', 1, 'stu', 1, 'f', 'stu', -1, 'qux', -1, 'bar', -1] (I used "stu" because I ran out of p...
A valid list following this grammar rule can be parsed recursively with a function which, given a valid index, tries to parse the tokens starting from the index as keys to a function followed by the argument position (with -1 ending the function call), or otherwise defaults to a scalar value. In addition to the parsed ...
5
1
79,487,786
2025-3-5
https://stackoverflow.com/questions/79487786/vs-code-comment-toggle-behaviour-unexpected-adds-and-removes-comments-does-not
I have tried looking this up but I only find answers related to getting the toggle command to work at all, not about the specific issue I have. I was previously using Notepad++. For Python, when I would toggle the comment of two lines simultaneously, I would get the following behaviour: # Line 1 Line 2 After toggle: L...
Shift+ Alt+ I then Ctrl + /. You can bind them using extension multi-command
1
2
79,485,958
2025-3-5
https://stackoverflow.com/questions/79485958/is-there-any-way-to-make-gekko-create-a-csv-file-thats-more-readable
The results.csv file is hard to read since the variables, intermediates etc. are shown in a format like "i1000" which probably means "intermediate number 1000". Is there any way to make the results show the proper symbols/characters that I used in the variable declaration? I've used the m.Array function to declare vari...
Use a list comprehension to define custom names for an array of variables. Here is an example: from gekko import GEKKO m = GEKKO(remote=False) # Create an array of variables #t = m.Array(m.Var,3,lb=-1000,ub=1000) t = [m.Var(lb=-1000,ub=1000,name=f'T{i+1}') for i in range(3)] # Create intermediate variables i1 = m.Inter...
3
2
79,486,991
2025-3-5
https://stackoverflow.com/questions/79486991/how-to-add-a-new-level-to-json-output-using-polars-in-python
I'm using Polars to process a DataFrame so I can save it as JSON. I know I can use the method .write_json(), however, I would like to add a new level to the JSON. My current approach: import polars as pl df = pl.DataFrame({ "id": [1, 2, 3, 4, 5], "variable1": [15, 25, 5, 10, 20], "variable2": [40, 30, 50, 10, 20], }) (...
The write_json() function always returns the data in a row-oriented format, in which the root element is a list, and each row contains a mapping of column_name -> row_value As a hacky workaround you could use write_ndjson() instead, given that its root element is a dictionary (for each line), but for that to match your...
1
3
79,486,908
2025-3-5
https://stackoverflow.com/questions/79486908/how-can-i-use-a-pyspark-udf-in-a-for-loop
I need a PySpark UDF with a for loop to create new columns but with conditions based on the iterator value. def test_map(col): if x == 1: if col < 0.55: return 1.2 else: return 0.99 elif x == 2: if col < 0.87: return 1.5 else: return 2.4 etc. test_map_udf = F.udf(test_map, IntegerType()) And then iterate: for x in ran...
You can pass x as arguments to udf. def test_map(x, col): ... test_map_udf = F.udf(test_map, IntegerType()) for x in range(1, 10): df = df.withColumn(f"new_value_{x}", test_map_udf(F.lit(x), F.col(f"old_value_{x}"))
1
3
79,482,885
2025-3-4
https://stackoverflow.com/questions/79482885/separable-convolutions-in-pytorch-i-e-2-1d-vector-tensor-traditional-convolu
I'm trying to implement an image filter in PyTorch that takes in two filters of shapes (1,3), (3,1) that build up a filter of (3,3). An example application of this is the Sobel filter or Gaussian blurring I have a NumPy implementation ready, but PyTorch has a different way of working with convolutions that makes it har...
Solution with conv2d You can make your life a lot easier by using conv2d rather than conv1d. Although we use conv2d below, this is still a 1-d convolution (or rather, two 1-d convolutions) effectively, since we apply a 1×n kernel. Thus, we still have all benefits of a separable convolution (in particular, 2·n rather th...
1
3
79,484,953
2025-3-4
https://stackoverflow.com/questions/79484953/identifying-and-removing-duplicate-columns-rows-in-sparse-binary-matrix-in-pytor
Let's suppose we have a binary matrix A with shape n x m, I want to identify rows that have duplicates in the matrix, i.e. there is another index on the same dimension with the same elements in the same positions. It's very important not to convert this matrix into a dense representation, since the real matrices I'm us...
Here is an implementation where the duplicate rows in a binary sparse matrix are identified. It returns a mask of the rows to keep from the sparse matrix, but can easily be adjusted to give e.g. indices of duplicate rows. It also handles cases where 3 or more rows are duplicates of each other and only keeps 1 row per g...
4
1
79,484,649
2025-3-4
https://stackoverflow.com/questions/79484649/python-regex-substitution-for-comma-match
For the input string as shown below, I am trying to substitute UK1/ after Street and every , and skip hyphen to create expected output shown below. Input = Street1-2,4,6,8-10 Expected output = StreetUK/1-2,UK/4,UK/6,UK/8-10 With the regex pattern I have trouble substitute for each captured group. How can I capture all ...
You can search using this regex: (Street|,)(?=\d) and replace with: \1UK/ RegEx Demo Code: import re input = 'Street1-2,4,6,8-10' print(re.sub(r'(Street|,)(?=\d)', r'\1UK/', input)) Output: StreetUK/1-2,UK/4,UK/6,UK/8-10 If you want to do these replacements only for input starting with Street then use: print(re.sub...
2
6
79,484,274
2025-3-4
https://stackoverflow.com/questions/79484274/how-to-prevent-the-formatting-of-any-linebreaks
Let's say I have a file like this: import pandas as pd df = pd.DataFrame( { "A": [" a: yu", "b: stuff ", "c: more_stuff"], "B": [4, 5, 6], "C": [7, 8, 9], } ) df["A"] = ( df["A"] .str.strip() .str.replace(":", "") .str[0] ) new_df = pd.melt( df, id_vars=["A"] ) print(new_df) If I then run ruff format --diff play_line_...
It seems there is no option available at the moment in ruff. See: ruff formatter: one call per line for chained method calls. Workaround: Seems like putting # fmt: skip next to the closing parentheses works as a quick hack. import pandas as pd df = pd.DataFrame( { "A": [" a: yu", "b: stuff ", "c: more_stuff"], "B": [4...
1
4
79,483,300
2025-3-4
https://stackoverflow.com/questions/79483300/unable-to-create-a-toggle-for-gridlines-on-matplotlib-python
I've been trying to make a toggle button to turn on and off the gridlines on my graph every time it's clicked. I understand how the toggle works as I was able to do it for some lines being animated onto my graph. I'm unsure if it's a problem with how MatplotLib sets axis and zorder etc. Or if it's to do with the fact i...
The issue is that instead of turning the grid off, you're only changing its color to black. Even though your background is black, the grid is still active, it’s just invisible. To disable the grid, call: ax.grid(False) and to enable, explicitly call: ax.grid(True, color='white', linestyle='--', linewidth=0.5) Example...
2
1
79,509,732
2025-3-14
https://stackoverflow.com/questions/79509732/how-to-add-a-case-sensitive-python-package-as-depencency
I need to add the package "modAL" (uppercase AL) as a dependency to a package. Since packages names are (seemingly) case insensitive in pyproject.toml, it falls back to "modal" which is another package. How can I add modAL and not modal as a dependency? I can install modAL separately (it works), but I want to add it as...
The comment by juanpa.arrivillega solves my problem: [...] python package names are case insensitive, and on pypi, the "modAL" package seems to be distributed as "modAL-python" – Commented 2025-03-14 at 16:56:12Z I just replaced "modAL" by "modAL-python" and it works as expected.
2
3
79,515,343
2025-3-17
https://stackoverflow.com/questions/79515343/how-to-compare-objects-based-on-their-superclass
How do I check for equality using super-class-level comparison? from dataclasses import dataclass @dataclass(order=True) class Base: foo: int @dataclass(order=True) class X(Base): x: str @dataclass(order=True) class Y(Base): y: float x = X(0, "x") y = Y(1, 1.0) How do I compare x and y on their Base attributes only? B...
Unlike C++, Java and certain OOP frameworks for C, in which classes and inheritances are implemented essentially as data structures that grow larger as classes are inherited, and bound methods, Python's objects can't be temporarily "cast" as one instance of their superclasses, where a superclass method can be called an...
1
2
79,501,764
2025-3-11
https://stackoverflow.com/questions/79501764/why-is-poetry-complaining-that-name-isnt-set-in-pyproject-toml
I set up a new Python Poetry project with poetry init. I'm not creating a package, so I added this to my pyproject.toml: [tool.poetry] package-mode = false The Operating Modes section of the Poetry documentation says that when operating in non-package mode, the name and version fields in pyproject.toml are optional, s...
This is a known issue: Poetry Issue 10032. More context is available in Issues 10031 and 10033. It does not matter if poetry.tools.package-mode = false, the project.name field is still required, because per the official standardized specification of the [project] table: A [project] table must include a name key. This...
1
4
79,515,104
2025-3-17
https://stackoverflow.com/questions/79515104/sliding-window-singular-value-decomposition
Throughout the question, I will use Python notation. Suppose I have a matrix A of shape (p, nb) and I create a sliding window, taking the submatrix of p rows and n columns Am = A[:, m : m + n]. Now I want to compute it singular value decomposition (SVD): U_m, S_m, Vh_m = svd(Am) = svd(A[:, m:m+n] and then go to the ne...
I'm going to assume square matrices, I leave the extension to non-square matrices to you (it may require further experimentation followed by a proof, but the general approach remains the same.) The comments by a user in the post you made in Mathematics stack exchange pretty much point you at the right answer. Lets call...
4
2
79,506,903
2025-3-13
https://stackoverflow.com/questions/79506903/cannot-submit-login-form-with-selenium-python-using-headless-remote-driver
I am trying to login to a website using Selenium. The relevant form HTML is as follows: <form class="ActionEmittingForm form-wrapper decorate-required" method="post" novalidate="" data-rf-form-name="LoginPageForm_SignInForm" data-rf-test-name="ActionEmittingForm"> <span data-rf-test-name="Text" class="field text Text r...
Try the below code. It is working in my machine with headless mode. I have used many chrome_options, to be honest I am not sure which one did the trick. I think it's adding user-agent. from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.chrome.options import Options from s...
1
1
79,515,806
2025-3-17
https://stackoverflow.com/questions/79515806/using-c-iris-or-iris-variants-to-decompose-c-free-while-ignoring-mimic-joints
I previously asked about modeling a 2-finger gripper as a 1-DOF system in Drake: How to make a gripper with two fingers (2DOF) have 1 DOF making one finger symmetric to the other. My gripper had two fingers (each with a prismatic joint) and I wanted to represent it as a 1-DOF system in Drake. The answer provided indica...
It is doable inside C-IRIS (well, not out-of-the-box). What C-IRIS does is that it certifies the following problem ∀s ∈ {s | C*s <= d}, ∃ a(s), b(s), such that the separating plane a(s) * x + b(s) = 0 separates the geometries A and B in the Cartesian space. Normally we search for the parameter C and d in the polytope ...
1
1
79,507,557
2025-3-13
https://stackoverflow.com/questions/79507557/how-to-send-slack-api-request-to-websocket-without-bolt-or-other-sdk
I have the code below. It connects correctly to Slack, and authenticate correctly. I want to sent a conversations.list request to list the channels. How can I do that without using Bolt or some other SDK? The system where this runs is locked down, so I'm not getting to install anything further than websockets. I think ...
You can’t get the channel list through the same WebSocket. Slack needs a normal HTTP request for conversations.list. Usually, you'd use WebSocket for real-time events, but you can open the socket and still use normal HTTP calls to list the channels. import requests import websocket import argparse def on_message(ws, m...
2
2
79,514,743
2025-3-17
https://stackoverflow.com/questions/79514743/cant-install-matplotlib-in-python-3-6
I've created a Python 3.6 environment in my WSL Ubuntu 22.04 operating system using virtualenv -p python3.6 <my_env>. I need to download some packages, particularly matplotlib, but I'm having some problems. When I run pip install matplotlib from terminal, it returns me ERROR: Command errored out with exit status 1, as ...
Here I am answering my own question. After trying everything you and the internet suggested, I gave up on using virtualenv. As Matt suggested in the comments, I downloaded miniconda and created an environment there. I was able to download all the packages and the code is running nicely. Thanks for your help.
2
0
79,509,565
2025-3-14
https://stackoverflow.com/questions/79509565/creating-a-dummy-pydantic-model-generator
I want to create a method on a base Pydantic model to instantiate child models with dummy data. from __future__ import annotations from pydantic import BaseModel class BaseModelWrapper(BaseModel): @classmethod def make_dummy(cls) -> BaseModelWrapper: for name, field in cls.model_fields.items(): if not field.is_required...
I ultimately used @kamilcuk's answer to create the following method from __future__ import annotations from pydantic import BaseModel from types import UnionType from typing import Any, Union, get_args, get_origin def is_union_type(t: type | UnionType) -> bool: return get_origin(t) in [Union, UnionType] class BaseModel...
2
0
79,515,678
2025-3-17
https://stackoverflow.com/questions/79515678/inspect-signature-on-class-methods
Can someone help me understand why the Signature.bind(...).arguments are different when I call directly for a class method vs. when used in a decorator? I have the decorator below. def decorator(func): @functools.wraps(func) def inner(*args, **kwargs): print(inspect.signature(func).bind(*args, **kwargs).arguments) retu...
The classmethod decorator changes the signature of a function. When classmethod is applied to a function that is stored on a class, it automatically fills the first parameter of the function as the class. This is much the same as how self parameter is filled as the object a method is called on. If you print out the two...
1
1
79,515,692
2025-3-17
https://stackoverflow.com/questions/79515692/how-to-reference-class-static-data-in-decorator-method
Is it possible to make the global variable handlers a static class variable? from typing import Callable, Self # dispatch table with name to method mapping handlers:dict[str, Callable[..., None]] = {} class Foo: # Mark method as a handler for a provided request name @staticmethod def handler(name: str) -> Callable[[Cal...
When handler is called, the name handlers will exist in the class statement's namespace, but not yet be bound as a class attribute (as you've noticed). It also is not part of any scope that handler will have access to, since the class statement does not define any scope. You can, however, inject a reference to the dict...
1
3
79,513,685
2025-3-17
https://stackoverflow.com/questions/79513685/is-it-reasonable-to-simplify-product-variant-design-using-notes-instead-of-compl
I'm building an application where product variants are intended to be handled as physical products already prepared and listed manually. Instead of using a conventional approach with complex relations between Product, Option, OptionValue, and SKUValue tables, I'm trying to simplify the design. 💡 ERD Design: +---------...
If the design fits your use-case, it is by definition not bad. Don't worry about best-practices if your current practice in actuality fulfills all your needs, doesn't expose you to any downsides, and is sufficiently performant. Current design For the note field: consider using JSONField (though note the database compat...
1
1
79,514,922
2025-3-17
https://stackoverflow.com/questions/79514922/most-performant-approach-to-find-closest-match-from-unordered-collection
I'm wondering what the best approach for finding the closest match to a given value from a collection of items is. The most important part is the lookup time relative to the input size, the data can be shuffled and moved around as much as needed, as long as the lookup is therefore faster. Here the initial script: MAX =...
With floats, the binary search scales like the best known. However it requires looking at locations in memory at some distance from each other. A B-tree also scales like O(log(n)), but by locating sets of decisions close to each other, it gets an order of magnitude constant improvement. The hash idea doesn't work becau...
5
1
79,510,719
2025-3-15
https://stackoverflow.com/questions/79510719/can-i-customize-compile-options-in-nuitka
Can I customize the compile options for GCC in Nuitka (e.g. -O2, -static)? Update: I read the user manual but found nothing. I also checked the command line options of nuitka and found --generate-c-only and --show-scons. Maybe these can help me build the executables, but I don't know how to complete the rest of the pro...
From the user manual: Providing extra Options to Nuitka C compilation Nuitka will apply values from the environment variables CCFLAGS, LDFLAGS during the compilation on top of what it determines to be necessary. Beware, of course, that this is only useful if you know what you are doing, so should this pose issues, rai...
2
1
79,513,766
2025-3-17
https://stackoverflow.com/questions/79513766/how-to-list-a-2d-array-in-a-tabular-form-along-with-two-1d-arrays-from-which-it
I'm trying to calculate a 2d variable z = x + y where x and y are 1d arrays of unequal dimensions (say, x- and y-coordinate points on a spatial grid). I'd like to display the result row-by-row in which the values of x and y are in the first two columns and the corresponding value of z calculated from these x and y valu...
Here is one way: import numpy as np import pandas as pd x = np.asarray([1, 2])[:, np.newaxis] y = np.asarray([3, 4, 5]) x, y = np.broadcast_arrays(x, y) z = x + y df = pd.DataFrame(zip(x.ravel(), y.ravel(), z.ravel()), columns=["x", "y", "z"]) print(df) # x y z # 0 1 3 4 # 1 1 4 5 # 2 1 5 6 # 3 2 3 5 # 4 2 4 6 # 5 2 5 ...
2
5
79,513,414
2025-3-17
https://stackoverflow.com/questions/79513414/how-to-specify-package-as-an-extra-in-poetry-pyproject-toml
I have a package with a pyproject.toml that has a core package & an optional GUI package with its own extra dependencies. This is the project structure: . └── my_project/ ├── src/ │ └── my_package/ │ ├── core/ │ │ └── __init__.py │ ├── gui/ │ │ └── __init__.py │ └── __init__.py ├── poetry.lock └── pyproject.toml PEP 7...
Extras don't work like that, they only apply to your packages dependencies. If you put the code in same package it will get bundled in when the package is built. Extras only apply to the dependencies of your package. In your case regardless of whether the user specifies [gui]or not they will get the gui code bundled in...
1
1
79,512,868
2025-3-16
https://stackoverflow.com/questions/79512868/how-to-read-excel-merged-cell-properties-value-using-python
I need to read data from an Excel file. The first cell contains the property name, and the second cell contains the property value. However, some of the property names in the first column are merged across two or more columns, and the corresponding values are in the next cell. For example, the property name "Ref" is in...
Just get the last cell in the range column number and add 1 as you have with the other fields. This code assumes the merge cells are row only. Also assumes the key name is cells is exactly the same as the name in the properties List import os import openpyxl def get_next_col(lc): # lc = Left cell in the merge range for...
1
1
79,513,050
2025-3-16
https://stackoverflow.com/questions/79513050/expand-and-then-sort-dataframe-based-on-the-value-order-in-the-first-row
Suppose I have a DataFrame with the following format of strings separated by commas: Index ColumnName 0 apple,peach,orange,pear, 1 orange, pear,apple 2 pear 3 peach,apple 4 orange The actual number of rows will be greater than 10,000. I want to expand the DataFrame and sort the DataFrame by row 0. My ...
Here is another way: s = df['columnName'].str.strip(',').str.split(', ?').explode() s.set_axis(pd.MultiIndex.from_frame(s.groupby(s).ngroup().reset_index())).unstack() Output: 0 0 1 2 3 index 0 apple orange peach pear 1 apple orange NaN pear 2 NaN NaN NaN pear 3 apple NaN peach NaN 4 NaN orange NaN NaN
2
1
79,512,639
2025-3-16
https://stackoverflow.com/questions/79512639/how-to-get-specified-number-of-decimal-places-of-any-fraction
So I can generate many tuples like this: (60155040518581045524837379873361090068988594641055829538390886302055144758188941415203591434486458063666229364105014761415461039472408954330541871604108252350317164101172870374427339926789581041281262768268630596450741677814377121894905015802840702115217387971343315603866730497...
Python has a built-in decimal.Decimal type and you can set the total number of places of precision for operations. I don't know if you would call this "using a library" because the Decimal type is just as fundamental to Python as the int type except implementing its math on CPUs that do not have decimal math capabiliti...
3
6
79,511,189
2025-3-15
https://stackoverflow.com/questions/79511189/matplotlib-waterfall-plot-with-surfaces-shows-black-artifacts-on-border-of-plot
I have a script to write a heatmap (or contour map) inside an arbitrary closed shape. A bounding box of grid points is created and a mask is used to clip any points outside of the shape. However, if I want to create a stacked plot of these maps (to show changes along a fourth dimension), the grid points are painted bla...
try channging: # Plot each heatmap slice as a surface surf = ax.plot_surface(xx, yy, z_surface, facecolors=facecolors_heatmap, linewidth=0, antialiased=False, shade=False, alpha=0.8, rstride=1, cstride=1) to: # Plot each heatmap slice as a surface surf = ax.plot_surface(np.where(mask, xx, np.nan), yy, z_surface, facec...
3
2
79,511,457
2025-3-15
https://stackoverflow.com/questions/79511457/generate-a-random-matrix-in-python-which-satisfies-a-condition
I manually define the following 16 matrices in Python : matrices = { "Simulation 1": [ [1, 1, 1, 1, 1, 2], [1, 1, 1, 1, 2, 2], [1, 1, 1, 2, 2, 2], [1, 1, 1, 2, 3, 2], [1, 1, 1, 1, 3, 3], [1, 1, 1, 1, 3, 3] ], "Simulation 2": [ [1, 1, 2, 2, 2, 2], [1, 1, 1, 2, 2, 2], [1, 1, 2, 2, 2, 2], [1, 1, 1, 2, 2, 2], [1, 1, 1, 2, ...
One way is to perform a random flood-fill out of the three initial coloured corners. Here is a possible implementation: import random def make_matrix(n): mat = [[0] * n for _ in range(n)] frontier = set() def place(row, col, color): mat[row][col] = color frontier.discard((row, col, 1)) frontier.discard((row, col, 2)) f...
1
3
79,510,817
2025-3-15
https://stackoverflow.com/questions/79510817/algorithm-to-select-multiple-non-overlapping-subsequences-of-given-sequence
You have been given the input data (a sequence of items), for example: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] and your task is to randomly select M non-overlapping samples (subsequences) of the same size N. For example, if the task was to select 3 samples of size 3, one of the solutions would be: [3, ...
import random seq = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] M = 3 N = 3 dividers = sorted(random.sample(range(len(seq) - M*N + M), M)) starts = [d + i*(N-1) for i, d in enumerate(dividers)] samples = [seq[start : start+N] for start in starts] print(samples) Example output (Attempt This Online!): [[3, 4...
4
5
79,511,188
2025-3-15
https://stackoverflow.com/questions/79511188/gauss-fitting-data-with-scipy-and-getting-strange-answers-on-fit-quality
I have Gamma-Spectra and I am doing Gauss fit to the peaks using Python with scipy. Works well, but trying to get a number on fit quality (for the intent on some automation) returns very odd numbers. The scipy command is: response = scipy.optimize.curve_fit(gauss, e, c, param0, full_output=True, absolute_sigma=True, me...
The formula you have is useful, but it is not a direct measure of the quality of the fit. It is related to "uncertainty" of the fit, and the condition number specifically is useful for diagnosing problems that may have occurred during fit. For instance, I've seen in other SO posts that `curve_fit` returns wild -looking...
2
5
79,508,238
2025-3-14
https://stackoverflow.com/questions/79508238/how-to-apply-a-global-rate-limit-for-all-routes-using-slowapi-and-fastapi
I want to configure rate limiting with SlowAPI (in-memory, without Redis Cache etc.), but I don't want to add the @limiter.limit() decorator seperately for every endpoint. So, something I don't want to do manually would be: @limiter.limit("5/minute") async def myendpoint(request: Request) pass So, essentially, I want ...
To apply a global (default) limit to all routes, you could use the SlowAPIMiddleware, as shown in the example below. The relevant documentation could be found here. Related answers could also be found here and here. Example from fastapi import FastAPI from slowapi import Limiter, _rate_limit_exceeded_handler from slowa...
1
3
79,510,643
2025-3-15
https://stackoverflow.com/questions/79510643/how-to-detect-thick-lines-as-single-lines-using-hough-transform-in-opencv
I'm using OpenCV's HoughLinesP function to detect straight lines in an image. When the image contains thin lines, the detection works perfectly. However, when the image contains thick lines, the algorithm detects them as two parallel lines instead of a single line. Here's my current code: import cv2 import numpy as np ...
You're looking to skeletonize the image - reduce the thickness of all features to 1 pixel. scikit-image.morphology has a neat method, skeletonize, just for this. import cv2 import numpy as np from skimage.morphology import skeletonize image_path = "thickLines.png" image = cv2.imread(image_path) # binarize image gray =...
1
3
79,509,466
2025-3-14
https://stackoverflow.com/questions/79509466/how-to-retrieve-singleton-model-instance-with-drf-without-having-to-provide-id
I have a django app, and I use django-solo for SingletonModel. I do have a singleton settings model: class GeneralSettings(SingletonModel): allow_signup = models.BooleanField(default=True) I want to create an API endpoint to be able to retrieve and update the settings. I currently use DRF. Using RetrieveModelMixin and...
You can use custom router to solve your problem. Below is an example of what this might look like: from rest_framework.routers import Route, SimpleRouter class SingletonRouter(SimpleRouter): routes = [ Route( url=r'^{prefix}{trailing_slash}$', mapping={ 'get': 'retrieve', 'put': 'update', }, name='{basename}-detail', d...
1
2
79,510,249
2025-3-14
https://stackoverflow.com/questions/79510249/custom-wraps-on-discord-command
I created a custom wraps like this def addLogger(fn): from functools import wraps @wraps(fn) async def add_logger(*args, **kwargs): print(f"addLogger: About to run {fn.__name__}") log = logger startTime = time.time() log.info('About to run %s' % fn.__name__) result = await fn(*args, **kwargs) log.info('Done running %s ...
You need to have @addLogger after the @bot.tree.command() line. So the correct code would be @bot.tree.command(name="list_cogs", description="list all cogs") @addLogger async def list_cogs(interaction): await interaction.response.send_message(f"{cogList}") Think of it like @addLogger changing the code of list_cogs() s...
1
3
79,509,624
2025-3-14
https://stackoverflow.com/questions/79509624/python-overload-doesnt-match-any-case
I've written this code: from typing import overload, TYPE_CHECKING, Protocol, Any import pyarrow as pa # type: ignore[import-not-found] class PyArrowArray(Protocol): @property def buffers(self) -> Any: ... @overload def func(a: PyArrowArray) -> int: ... @overload def func(a: str) -> str: ... @overload def func(a: Any) ...
I am confident to say that this is very likely not possible. The Any Type per PEP 484 matches everything, hence an Any input will match all overloads. What happens in such cases is defined here in the Mypy docs: [...] if multiple variants match due to an argument being of type Any, mypy will make the inferred type als...
2
3
79,509,728
2025-3-14
https://stackoverflow.com/questions/79509728/polars-group-by-describe-return-all-columns-as-single-dataframe
I'm slowly migrating to polars from pandas and I have found that in some cases the polars syntax is tricky. I'm seeking help to do a group_by followed by a describe using less (or more readable) code. See this example: from io import BytesIO import pandas as pd import polars as pl S = b'''group,value\n3,245\n3,28\n3,48...
You can write a quick function that returns a mapping of expressions that you can unpack right into your DataFrame.group_by(...).agg. This avoids any slow-ness of using map_groups and enables Polars to easily scan the query for any optimizations (provided you are working with a LazyFrame). from io import BytesIO import...
2
3
79,507,218
2025-3-13
https://stackoverflow.com/questions/79507218/why-text-alignment-is-not-performed-via-styles
I'm trying to organize text alignment in ttk.Label using style in order to reduce the amount of code: import tkinter as tk from tkinter import ttk from tkinter import font app = tk.Tk() width = 605 height = 200 x = int((app.winfo_screenwidth() / 2) - (width / 2)) y = int((app.winfo_screenheight() / 2) - (height / 2)) a...
According to the official documentation, justify is not supported in the style. I think the documentation you're using is incorrect. ---- TLabel styling options configurable with ttk::style are: -background color -compound compound -foreground color -font font
1
3
79,508,420
2025-3-14
https://stackoverflow.com/questions/79508420/expanding-polars-dataframe-with-cartesian-product-of-two-columns
The code below shows a solution I have found in order to expand a dataframe to include the cartesian product of columns A and B, filling in the other columns with null values. I'm wondering if there is a better and more efficient way of solving this? >>> df = pl.DataFrame({'A': [0, 1, 1], ... 'B': [1, 1, 2], ... 'C': [...
This is a requested feature (this is available in R or pandas's janitor as complete). An alternative approach mentioned in the feature request would be: (df.select(pl.col(['A', 'B']).unique().sort().implode()) .explode('A') .explode('B') .join(df, how='left', on=['A', 'B']) ) Which makes it easy to generalize to a gre...
5
4
79,508,139
2025-3-14
https://stackoverflow.com/questions/79508139/how-to-transfer-this-part-of-code-from-c-to-python-using-dataclass
I have this structure in C: MAX_NUMBER_OF_ITEMS = 9 typedef struct { uint64_t status; uint8_t serial_number_of_items [MAX_NUMBER_OF_ITEMS]; uint8_t version; } Items_Info_t; How can I convert it to Python, specifically the part: uint8_t number_of_items [MAX_NUMBER_OF_ITEMS] I try to do this way: class SensorInfo: stat...
Create a class to encapsulate Items_Info_t and manage its serialization/deserialization. The __init__ method initializes the object's attributes, after doing data validation to ensure that the input values are within the expected ranges. Added an endian parameter to both the serialize and deserialize methods. The defa...
2
2
79,507,207
2025-3-13
https://stackoverflow.com/questions/79507207/create-an-n-length-list-by-uniformly-in-frequency-selecting-items-from-a-separ
SETUP I have a list days and a value N days = ['Monday','Tuesday','Wednesday','Thursday','Friday'] N = 52 WHAT I AM TRYING TO DO I am trying to create a list selections with length N where I uniformly in frequency sample values from days (remainders are fine). I would like the order of this list to then be shuffled. E...
The code you have is correct. You are seeing expected noise around the mean. Note that for higher N, the relative noise decreases, as expected. For example, this is what you get for N = 10000000: Counter({'Tuesday': 2000695, 'Thursday': 2000615, 'Wednesday': 2000096, 'Monday': 1999526, 'Friday': 1999068}) If you need ...
2
5
79,505,837
2025-3-13
https://stackoverflow.com/questions/79505837/how-to-make-an-easily-instantiable-derivative-attribute-only-protocol-class
I have a Protocol subclass that defines objects with attributes from an external library: class P(Protocol): val: int For testing purposes, I want to turn this protocol class into something I can instantiate easily. However, when I try to turn it into a dataclass, an error pops up: import dataclasses from typing impor...
You are asking for a non-protocol class derived from the attributes in your protocol class. They are stored in the annotations, which are accessible as typing.get_type_hints(P). In my first try, I dynamically created that class with builtin type, passing it the protocol's type hints to define an equivalent non-protocol...
2
2
79,506,954
2025-3-13
https://stackoverflow.com/questions/79506954/passing-integers-to-fastapi-post-endpoint
I have two endpoints below, one that accepts two integers and another that accepts tow lists of integers. I also have two post requests that I am making using Python requests. The request for the list of ints endpoint works fine, but the one that just accepts the two ints does not. I know that if I pass the two ints in...
could you tell me why it doesn't work when passed as JSON? When you register a route with @app.post('/ints') def post_int(x: int, y: int): return x, y in FastApi, the route is analyzed and added in decorator (routing.py) add_api_route (routing.py) __init__ (routing.py) get_dependant (dependencies/utils.py) analyze_p...
2
1
79,506,519
2025-3-13
https://stackoverflow.com/questions/79506519/how-do-i-prevent-shelve-module-from-appending-db-to-filename
Python: 3.12.2, OS: MacOS 13.6.6 When I specify a filename to shelve.open, it appends .db to the filename: % ls % python Python 3.12.2 (main, Feb 6 2024, 20:19:44) [Clang 15.0.0 (clang-1500.1.0.2.5)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import shelve >>> with shelve.open(...
Why can't I open existing databases if I specify their ".db" extension? After scrying shelve source code it could be unveiled that shelve.open("myfile") does result in calling dbm.open(filename, 'c') After scrying dbm source code it could be unveiled that this does depend on dbm.whichdb, where following line could be...
1
2
79,507,131
2025-3-13
https://stackoverflow.com/questions/79507131/dataframe-fill-for-null-values-pandas
I encounter problems trying to fill all null values on a specific column of a data frame. Here is an example of dataframe and my expected outcome. Example data frame: Column_1 Column_2 F A None B None None G C None None None D H D I want to get the first value from the column 1 to all null value from column 2 Expected...
You can combine fillna on Column_2 and bfill on Column_1: df['Column_2'] = df['Column_2'].fillna(df['Column_1'].bfill()) Output: Column_1 Column_2 0 F A 1 NaN B 2 NaN G 3 G C 4 NaN H 5 NaN D 6 H D Intermediates: Column_1 Column_2 col1_bfill col2_fillna 0 F A F A 1 NaN B G B 2 NaN NaN G ------> G 3 G C G C 4 NaN NaN...
2
4
79,501,131
2025-3-11
https://stackoverflow.com/questions/79501131/does-nuitka-onefile-mode-displays-my-python-code-in-tracebacks
Here is an example code: while True: # here is a comment pass Here is my Python and Nuitka version: D:\test>py -m nuitka --version 2.6.8 Commercial: None Python: 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 22:45:29) [MSC v.1916 32 bit (Intel)] Flavor: CPython Official Executable: ~\AppData\Local\Programs\Python\Python38-...
In the Nuitka page you can read that Nuitka Standard The standard edition bundles your code, dependencies and data into a single executable if you want. It also does acceleration, just running faster in the same environment, and can produce extension modules as well. It is freely distributed under the Apache license. ...
1
2
79,506,581
2025-3-13
https://stackoverflow.com/questions/79506581/how-can-i-use-ruff-rules-to-enforce-a-particular-import-style
I changed my code base to always import the python datetime module like this: import datetime as dt instead of using import datetime or from datetime import datetime And we had both those in the codebase! It's confusing because you can't know at this point what datetime can do, if it is the module or the class. See ...
You should be able to lint code using from datetime import datetime syntax to suggest replacing it with import datetime as dt with the TOML configuration: [tool.ruff.lint] # Add the ICN rules to any others you have selected. select = ["E4", "E7", "E9", "F", "ICN"] [tool.ruff.lint.flake8-import-conventions] banned-from ...
1
2
79,506,301
2025-3-13
https://stackoverflow.com/questions/79506301/how-to-do-fitting-on-experimental-graph-and-theoretical-graph
I am currently fitting the experimental results and will later take the MSE to increase the accuracy, the accuracy between the data and theory. How do you make sure the fittings fit perfectly to each other? Can that be done? And how do you calculate the MSE? so this is my code import numpy as np import matplotlib.pypl...
Your experimental data has a negative offset in it (not centred on y=0). You should allow for that in your fitting function. Although the peaks are a good first indicator of period, the damped frequency will differ from the undamped one, so I would allow that to vary also. Your error estimation looks OK (if a little lo...
1
2
79,506,238
2025-3-13
https://stackoverflow.com/questions/79506238/polars-upsampling-with-grouping-does-not-behave-as-expected
Here is the data import polars as pl from datetime import datetime df = pl.DataFrame( { "time": [ datetime(2021, 2, 1), datetime(2021, 4, 2), datetime(2021, 5, 4), datetime(2021, 6, 6), datetime(2021, 6, 8), datetime(2021, 7, 10), datetime(2021, 8, 18), datetime(2021, 9, 20), ], "groups": ["A", "B", "A", "B","A","B","A...
It is due to the group columns resulting in null - which is a bug. https://github.com/pola-rs/polars/issues/15530 upsample itself is implemented as a datetime_range and join https://github.com/pola-rs/polars/blob/a4fbc9453cacb7e7e5cc476b30a98845aaa5f506/crates/polars-time/src/upsample.rs#L203 Which you could do man...
1
3
79,505,931
2025-3-13
https://stackoverflow.com/questions/79505931/why-can-i-read-a-file-with-pandas-but-not-with-polars
I have a CSV (or rather TSV) I got from stripping the header off a gVCF with bcftools view foo.g.vcf -H > foo.g.vcf.csv A head gives me this, so everything looks like expected so far chr1H 1 . T <*> 0 . END=1000 GT:GQ:MIN_DP:PL 0/0:1:0:0,0,0 chr1H 1001 . T <*> 0 . END=1707 GT:GQ:MIN_DP:PL 0/0:1:0:0,0,0 chr1H 1708 . C ...
Looks like you might have empty trailing spaces. Hence the error: Original error: remaining bytes non-empty Polars is stricter than pandas on file formatting. Pandas will infer formatting but Polars will not. You can use this command to remove empty lines and white spaces: sed -i '/^\s*$/d' foo.g.vcf.csv But I recomm...
1
2
79,505,258
2025-3-13
https://stackoverflow.com/questions/79505258/pymongo-group-by-year-based-on-subdocument-date
I have a MongoDB document like: [ { _id: ObjectId('67cfd69ba3e561d35ee57f51'), created_at: ISODate('2025-03-11T06:22:19.044Z'), conversation: [ { id: '67cfd6c1a3e561d35ee57f53', feedback: { liked: false, disliked: true, copied: true, created_at: ISODate('2025-03-11T06:27:48.634Z') } }, { id: '67cfd77fa3e561d35ee57f54',...
You need the $unwind stage to deconstruct the conversation array before grouping by conversation.feedback.created_at. Note that, in your sample data, there is possibly the conversation.feedback is null. Hence you should remove those unwinded document with conversation.feedback is null. For calculating the sum based ...
1
2
79,504,309
2025-3-12
https://stackoverflow.com/questions/79504309/create-a-uniform-dataset-in-polars-with-cross-joins
I am working with Polars and need to ensure that my dataset contains all possible combinations of unique values in certain index columns. If a combination is missing in the original data, it should be filled with null. Currently, I use the following approach with sequential cross joins: def ensure_uniform(df: pl.DataFr...
I think your approach is sensible, it can however be done lazily: from functools import reduce def ensure_uniform(df: pl.DataFrame, index_cols: Sequence[str]) -> pl.DataFrame: if len(index_cols) == 1: return df lf = df.lazy() uniques = [lf.select(col).unique(maintain_order=True) for col in index_cols] product = reduce(...
3
3
79,502,464
2025-3-12
https://stackoverflow.com/questions/79502464/fastest-way-to-find-indices-of-highest-value-in-a-matrix-iteratively-and-exclusi
I'm attempting to find the "best hits" in a similarity matrix (i.e. an mxn matrix where index along each axis corresponds to the ith position in vector m and the jth position in vector n). The simplest way to explain this is finding the indices of the highest values in a matrix iteratively, excluding previously selecte...
Here's a candidate using numpy only, about 100x faster on your small example: import numpy as np import pandas as pd import timeit sim = np.array([[1,5,6,2],[7,10,3,4],[1,5,3,7]]) def mine(sim): out = [] copy = sim.copy() MIN = np.iinfo(copy.dtype).min # or -np.inf if using floats... for _ in range(min(copy.shape)): ij...
3
3
79,503,619
2025-3-12
https://stackoverflow.com/questions/79503619/pandas-dataframe-add-columns-based-on-list-of-samples-and-column-headers
I want to add columns in my df with values based on the sample list in one column and the next column headers as sample numbers. In detail: based on the 11 column, I want to add 3 columns designed as 11_1, 11_2 and 11_3 with values according to the sample list in the 11 and then the same for 00. My tiny part of input d...
Another possible solution: df_matrix.assign( **{f"{k}_{i+1}": df_matrix.apply( lambda row: row[row[k][i]], axis=1) for k in ['11', '00'] for i in range(3)}) It uses a dictionary comprehension within assign, iterating over each key (e.g., '11') and list index (0-2), then generates columns like 11_1 by mapping the list'...
1
1
79,504,418
2025-3-12
https://stackoverflow.com/questions/79504418/how-to-check-if-pyright-ignore-comments-are-still-required
I have recently switched from using mypy to pyright for static type checking. mypy has a useful feature whereby it can be configured to warn you if it detects comments instructing it to ignore certain errors which would not actually be raised (described here: https://stackoverflow.com/a/65581907/7256443). Does anyone k...
Pyright has reportUnnecessaryTypeIgnoreComment, which flags unnecessary # type: ignore comments as errors. To enable this check, add the following to your pyrightconfig.json: { "reportUnnecessaryTypeIgnoreComment": "error" } Source: Pyright Documentation - Type Check Diagnostics Settings reportUnnecessaryTypeIgnoreCo...
1
3
79,501,731
2025-3-11
https://stackoverflow.com/questions/79501731/transforming-polars-dataframe-to-nested-json-format
I have a dataframe that contains a product name, question, and answers. I would like to process the dataframe and transform it into a JSON format. Each product should have nested sections for questions and answers. My dataframe: import polars as pl df = pl.DataFrame({ "Product": ["X", "X", "Y", "Y"], "Question": ["Q1",...
You could do some of the reshaping in Polars first. faq_list = ( df.group_by("product", maintain_order=True) .agg(faqs=pl.struct(pl.int_range(pl.len()).alias("id") + 1, pl.exclude("product"))) .with_row_index("id", offset=1) #.to_struct() #.to_list() ) shape: (2, 3) ┌─────┬─────────┬────────────────────────────────┐ │...
1
2
79,504,009
2025-3-12
https://stackoverflow.com/questions/79504009/detect-coordinate-precision-in-polars-floats
I have some coordinate data; some of it high precision, some of it low precision thanks to multiple data sources and other operational realities. I want to have a column that indicates the relative precision of the coordinates. So far, what I want is to essentially count digits after the decimal; in my case more digits...
You can extract the minor fields directly without the need for temp columns and unnesting. df.with_columns( pl.col("lat", "lng").cast(pl.String) .str.split_exact(".", 1) .struct.field("field_1") .str.len_chars() .name.suffix("_minor") ) shape: (4, 4) ┌───────────┬────────────┬───────────┬───────────┐ │ lat ┆ lng ┆ lat...
2
1
79,503,865
2025-3-12
https://stackoverflow.com/questions/79503865/numpy-timedelta-highest-unit-without-loss-of-information
I have several numpy timedelta values. I want to convert them to the a format that is better to read for humans without losing information. Let's say I have td = np.timedelta64(10800000000001, 'ns'). Then I can only have it in ns because if I convert it to msor higher it will lose information. If I have td = np.timedel...
If I understand the problem statement, you only want to express the time in terms of one unit: the largest that retains precision using only whole numbers. import numpy as np td = np.timedelta64(10800000000000, 'ns') units = ['h', 'm', 's', 'ms', 'ns'] # Convert to each of the desired units deltas = [td.astype(f'timede...
1
2
79,500,324
2025-3-11
https://stackoverflow.com/questions/79500324/how-can-i-pass-environment-variables-to-a-custom-training-script-in-amazon-sagem
I'm training a custom model using a script in Amazon SageMaker and launching the job with the Python SDK. I want to pass some environment variables (like API keys or config flags) to the training job so they’re accessible inside the script via os.environ. Here’s a simplified version of my code: from sagemaker.estimator...
Yes, your approach is correct. Using the environment parameter in the Estimator and accessing variables with os.environ.get() in your script is the standard way to pass environment variables in SageMaker. As @furas pointed out in their comment, os.environ.get() is the common approach in Python. That said, for handling ...
2
2
79,503,488
2025-3-12
https://stackoverflow.com/questions/79503488/sympy-i-cant-solve-an-equation-symbolically-it-keeps-trying-to-give-real-solu
import sympy as sym # Python 3.13 # Used variables in question x = sym.Symbol("x") I1 = sym.Symbol("I₁") L = sym.Symbol("L") pi = sym.Symbol("Π") v2 = sym.Symbol("v2") P = sym.Symbol("P") E = sym.Symbol("E") I = I1 * (1 - x/L) # For the part a of the question one in Assignment 3. question_part = "a" if question_part ==...
Don't declare a symbol called pi. You should use SymPy's sympy.pi if you mean the mathematical number pi. This is your equation as stated: In [42]: x, L, v2, E, I1, P, v2 = symbols('x, L, v2, E, I1, P, v2') In [43]: eq = Eq(Integral((P*(L - x)*(pi/(2*L))**2*cos((pi*x)/(2*L)) * v2)/(E*I1*(1 - x/L)), (x, 0, L ...: )), P*...
3
3
79,503,212
2025-3-12
https://stackoverflow.com/questions/79503212/fast-way-to-expand-split-list-into-index-list
Given an index split list T of length M + 1, where the first element is 0 and the last element is N, generate an array D of length N such that D[T[i]:T[i+1]] = i. For example, given T = [0, 2, 5, 7], then return D = [0, 0, 1, 1, 1, 2, 2]. I'm trying to avoid a for loop, but the best I can do is: def expand_split_list(s...
You could combine diff, arange, and repeat: n = np.diff(T) out = np.repeat(np.arange(len(n)), n) As a one-liner (python ≥3.8): out = np.repeat(np.arange(len(n:=np.diff(T))), n) Another option with assigning ones to an array of zeros, then cumsum: out = np.zeros(T[-1], dtype=int) out[T[1:-1]] = 1 out = np.cumsum(out) ...
6
7
79,503,035
2025-3-12
https://stackoverflow.com/questions/79503035/set-priority-on-queryset-in-django
this is my product and category model: class Category(models.Model): name = models.CharField(max_length=100) class Product(models.Model): ... category = models.ForeignKey(Category, related_name="products", on_delete=models.CASCADE) I want a list of all products with priority order. e.g. categories_ids = [3,5,1,4,2] ...
We can determine the priority based on the category, and a Case-When expression: from django.db.models import Case, Value, When category_ids = [3, 5, 1, 4, 2] Product.objects.filter( category_id__in=category_ids ).alias( priority=Case(*[When(category_id=k, then=Value(i)) for i, k in enumerate(category_ids)]) ).order_by...
1
4
79,500,030
2025-3-11
https://stackoverflow.com/questions/79500030/scipys-multivariate-earth-mover-distance-not-working-as-intended
I am using scipy's multivariate earth mover distance function wasserstein_distance_nd. I did a quick sanity check that confused me: Given that I draw two Gaussian multivariate samples from the same distribution, I should get an earth mover distance that is close to 0. However, I am getting something large (e.g., 12). W...
Your multivariate_normal example is in a 100-dimensional space. You can think of the reason you are getting large distances from an intuitive perspective: there is too much variety possible in a 100-dimensional space for the two samples to be very similar. Some more motivation: In high dimensional spaces, randomly dra...
1
2
79,501,591
2025-3-11
https://stackoverflow.com/questions/79501591/plotly-displaying-numerical-values-as-counts-instead-of-its-actual-values
I am trying to plot my pandas df data onto a plotly bar chart, but for some reason, instead of putting the numerical values on the chart, its just putting the order onto it. For example, I am trying to also follow along with the docs, but it also fails on the docs' example. The code: import plotly.express as px fig = p...
I tested this out, and this appears to be a bug that only appears when using plotly v6.0.0 in a jupyter notebook. For now, the issue can be worked around by downgrading the version inside the notebook: %pip install plotly==5.23.0 You'll notice that if you try to plot fig = px.bar(x=["a", "b", "c"], y=["1", "3", "2"]) y...
2
1
79,500,909
2025-3-11
https://stackoverflow.com/questions/79500909/what-is-the-fastest-way-to-generate-all-n-bit-gray-codes-using-numpy
My goal is to create images using gray codes, an example would be this: It is all modulo 64 groups in gray codes in polar form. Now of course I know of the simple mapping n ^ (n >> 1) from binary, but I had found more efficient ways to generate gray codes directly than using said mapping. But since binary codes are re...
This seems 3-4 times faster than your fastest gray_codes. Fills the array by reverse-copying blocks and setting streaks of 1s. def g(n): a = np.zeros((n, 2**n), dtype=bool) m, M = 1, 2 while n: a[n:, m:M] = a[n:, m-1::-1] n -= 1 a[n, m:M] = 1 m, M = M, 2*M return a.T Attempt This Online!
5
1
79,500,718
2025-3-11
https://stackoverflow.com/questions/79500718/how-to-include-first-matching-pattern-as-a-column
I have a dataframe df. >>> import polars as pl >>> >>> >>> df = pl.DataFrame({"col": ["row1", "row2", "row3"]}) >>> df shape: (3, 1) ┌──────┐ │ col │ │ --- │ │ str │ ╞══════╡ │ row1 │ │ row2 │ │ row3 │ └──────┘ Now I want to create a new column new. It should be the first matched pattern in the col. For example, For t...
You should modify your pattern to have a capturing group (...) and use Expr.str.extract: df.with_columns(new=pl.col('col').str.extract("(1|2)")) Output: ┌──────┬──────┐ │ col ┆ new │ │ --- ┆ --- │ │ str ┆ str │ ╞══════╪══════╡ │ row1 ┆ 1 │ │ row2 ┆ 2 │ │ row3 ┆ null │ └──────┴──────┘
3
1
79,499,646
2025-3-11
https://stackoverflow.com/questions/79499646/how-can-i-replace-multiple-items-in-a-string-using-a-dictionary-when-the-matched
Given this dictionary and input strings: d = { 'one': '1', 'two': '2', 'three': '3' } s1 = 'String containing <#one|> or <#two|> numbers. <#one|>, <#two|>, <#three|>' s2 = 'Only replace items which are anchored. <#one|> is replaced, but not this one.' How can I replace each occurrence of an anchored item <# |> using t...
The regular expression pattern should be <#(\w+)\|?>. The \|? part makes the trailing | optional because the quantifier ? (Zero or One) matches zero or one occurrence of the preceding element. I used the re.sub(pattern, repl, string) function for substituting substrings that match the pattern with a replacement functio...
2
4
79,523,584
2025-3-20
https://stackoverflow.com/questions/79523584/use-a-single-pyproject-toml-for-poetry-uv-dev-dependencies
I'm trying to let people on my project (including myself) migrate to uv while maintaining compatibility with people who still want to use poetry (including some of our builds). Now that poetry 2.0 has been released, and the more standard [project] fields are supported, this should be possible. It's working well in almo...
Until poetry adds support for PEP-735, you can (ab)use the project.optional-dependencies to achieve something similar: [project.optional-dependencies] dev = ["bandit ~= 1.8.3"] Since this is a standard table, it can be used by both poetry and uv: $ poetry sync --extras dev $ poetry sync --all-extras $ uv sync --extr...
2
4
79,532,232
2025-3-24
https://stackoverflow.com/questions/79532232/how-can-i-download-multiple-files-using-urllib2-in-a-single-http-request-instead
I am using tornado to host a server that serves as the backend for a client that needs to be running Jython 2.5.2 (thus urllib2). I have a function that downloads files, that up until now only downloaded text files. I need to add non-text files and download them quickly. To download text files in a timely fashion, I co...
Turns out you can just stick a b in front of each string to convert it to bytes and everything works great! class DownloadHandler(web.RequestHandler): def get(self): files_as_text = b"" for file in os.listdir("files"): files_as_text += file.encode("utf-8")+b"---title_split---"+open("files/"+file, "rb").read()+b"---file...
2
0
79,525,802
2025-3-21
https://stackoverflow.com/questions/79525802/plotly-bar-conditional-dual-axis-python
import plotly.graph_objects as go fig=go.Figure() cols=['NO2 mug/m^3','NO mug/m^3'] for idx,col in enumerate(cols): for df in [ag,snd]: fig.add_trace(go.Bar(x=df['Date'],y=df[col], name=f'{str(df.Municipality.unique()[0])} {col}')) #fig.add_trace(go.Bar(x=ag['Date'],y=ag['NO mug/m^3'])) fig.update_layout(barmode='group...
This is because you are using df_idx to offset the bars. df_idx will only be 0 or 1. When multiple data sets (traces) share a common x-axis (for vertical bars) or y-axis (for horizontal bars), the offsetgroup property allows you to align bars at the same position. Assigning the different offsetgroup value to these trac...
3
3
79,531,378
2025-3-24
https://stackoverflow.com/questions/79531378/dynamic-libraries-not-found-when-launching-a-python-script-using-slurm
I have difficulties setting my environment variables when launching a python script using Slurm. The following python script import petsc4py without error when launched from a shell session : from petsc4py import PETSc print("petsc4py imported successfully") However when I try to run it using srun with the following s...
This could be because liblapack is available as a operating system package on the node where the shell session is run and not available on the node on which the job runs. You might have to load the lapack module if one exists module load python/3.10.0 openmpi gcc openblas/latest lapack/latest slurm
2
1
79,528,159
2025-3-22
https://stackoverflow.com/questions/79528159/mandelbrot-set-coloring-error-around-period-2-bulb-not-colormap-related
I wrote some code to render the Mandelbrot set with continuous coloring, but the bulbs on the period-2 blub are not colored correctly. regions that should not escape are colored as though the escape after 100 iterations, which happens to be my iteration limit. What I tried 1. Increasing resolution and max iteration co...
The updating of the output and the mask inside the loop (iterations) is incorrect. We need to focus only on the points inside mask and escaped in current iteration. def mandelbrot(cmax, width, height, maxiter): real = np.linspace(-2, 0.5, width, dtype=np.float32) imag = np.linspace(0, cmax.imag, height // 2 + 1, dtype=...
2
3
79,530,792
2025-3-24
https://stackoverflow.com/questions/79530792/typeerror-in-fastapi-when-using-apiroute-with-a-router
I have a FastAPI backend and i'm trying to implement an APIRoute class to handle logic before and after the request (logging). # app.py from fastapi import FastAPI, APIRouter from backend.app.routers import questions API_VERSION = "v1" app = FastAPI(lifespan=lifespan) api_v1_router = APIRouter(prefix=f"/{API_VERSION}")...
The error was caused by defining the get_route_handler method of LoggingAPIRoute as a coroutine function (async). Removing async before the function definition solved it. class LoggingAPIRoute(APIRoute): @staticmethod async def access_log_req(request: Request) -> None: print("request...") @staticmethod async def access...
2
0
79,531,664
2025-3-24
https://stackoverflow.com/questions/79531664/what-is-the-fastest-way-to-generate-alternating-boolean-sequences-in-numpy
I want to create a 1D array of length n, every element in the array can be either 0 or 1. Now I want the array to contain alternating runs of 0s and 1s, every full run has the same length as every other run. Every run of 1s is followed by a run of 0s of the same length and vice versa, the gaps are periodic. For example...
Since you are certainly on Windows (which is not mentioned in this question and critical for performance) and you likely use PIP packages, your Numpy implementation has been compiled with MSVC which does not use SIMD units of CPU for many functions, including np.tile. This means your Numpy package it pretty inefficient...
2
2
79,531,851
2025-3-24
https://stackoverflow.com/questions/79531851/polars-fails-to-create-a-new-dataframe-using-with-columns-when-creating-new-co
I'm new to polars and encountering a confusing error. I'm trying to take several array columns and zip them into struct columns. When I try to do this with with_columns I encounter the error: ValueError: can only call `.item()` if the dataframe is of shape (1, 1), or if explicit row/col values are provided; frame has s...
Compute test_1 and test_2 as separate DataFrames. Use join to combine test_1 and test_2 with the original DataFrame. Avoid passing complete DataFrames to with_columns() import polars as pl df = pl.DataFrame( { "a": [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]], "b": [[1, 2, 3, 5], [1, 2, 3, 5], [1, 2, 3, 5]...
2
1
79,518,064
2025-3-18
https://stackoverflow.com/questions/79518064/how-to-create-google-doc-tabs-with-the-python-sdk
I’m trying to create a Tab in a google doc via the python SDK (as in the new(ish) side navigation/organizational tabs, not a tab character). I see how to read and update existing tabs, but don't see any mention of how to create a tab (or any callouts on that being a pending feature). Is it supported and just not well d...
It is not currently implemented. See this feature request, https://issuetracker.google.com/375867285.
1
2
79,530,667
2025-3-24
https://stackoverflow.com/questions/79530667/how-to-use-multiple-database-connections-in-django-testcase
I'm writing a testcase to reproduce deadlock in my service. After I use multiprocessing to create a two thread, I found they use the same database connection. So I can't reproduce the deadlock scenario in testcase. How do i resolve this issue? My code is as belows: @transaction.atomic() def process_1(): change = Change...
This is happening cause Django’s database connections are not automatically shared across processes when using multiprocessing (each process should create its own database connection). Just close the database connection before forking the new processes: from django.db import connection # Here your functions ... connect...
2
1
79,528,929
2025-3-23
https://stackoverflow.com/questions/79528929/why-does-sequentialfeatureselector-return-at-most-n-features-in-1-predictor
I have a training dataset with six features and I am using SequentialFeatureSelector to find an "optimal" subset of the features for a linear regression model. The following code returns three features, which I will call X1, X2, X3. sfs = SequentialFeatureSelector(LinearRegression(), n_features_to_select='auto', tol=0....
Check the source code, lines 240-46 inside the method fit(): if self.n_features_to_select == "auto": if self.tol is not None: # With auto feature selection, `n_features_to_select_` will be updated # to `support_.sum()` after features are selected. self.n_features_to_select_ = n_features - 1 else: self.n_features_to_sel...
2
3
79,531,065
2025-3-24
https://stackoverflow.com/questions/79531065/python-vectorized-mask-generation-numpy
I have an arbitrary Matrix M which is (N x A). I have a column vector V (N x 1) which has on each row the amount of entries I would like to keep from the original M <= A (starting from the leftmost) As an example, say I have the following V (for an arbitrary 5xA Matrix): [[1] [0] [4] [2] [3]] i.e. I want to keep the 1...
Just use broadcasting and numpy.arange: mask = V > np.arange(M.shape[1]) Or from A: A = 5 mask = V > np.arange(A) Output: array([[ True, False, False, False, False], [False, False, False, False, False], [ True, True, True, True, False], [ True, True, False, False, False], [ True, True, True, False, False]]) And if y...
2
1
79,530,635
2025-3-24
https://stackoverflow.com/questions/79530635/opencv-cv2-waitkey-cannot-detect-the-delete-key-what-should-i-do
I am using cv2.waitKey(1) & 0xFF to capture key events, but I found that it cannot correctly detect the Delete key. My current code is as follows: import cv2 while True: key = cv2.waitKey(1) if key != -1: # -1 : timeout/no key event print(f"Key pressed: {key}") if key == 127: print("Delete key detected!") break cv2.des...
Use waitKeyEx(). It'll give you every bit of information the operating system has to give. waitKey does not, it only gives you the lowest eight bits. On Windows, Del will cause waitKey to return 0, but waitKeyEx() will return 0x2e0000. waitKeyEx() will return other values on other systems. Never ever use that & 0xFF p...
3
2
79,523,536
2025-3-20
https://stackoverflow.com/questions/79523536/can-you-raise-an-airflowexception-without-dumping-the-entire-traceback-into-the
In Airflow, you're suppose to raise an AirflowException if you want a task to be marked as a failure. But the raised error doesn't seem to be caught in the top-level Airflow module, and so it results in the entire stacktrace being dumped into the logs. If you do your error handling properly, it should be possible to pr...
Yes, you can do it by using Python’s exception chaining syntax. Instead of writing: raise AirflowException("Your error message") you write: raise AirflowException("Your error message") from None This “from None” tells Python not to include the exception’s context (i.e. the chained traceback) in the logs. So, when you...
1
1
79,528,380
2025-3-23
https://stackoverflow.com/questions/79528380/is-it-possible-to-turn-off-printing-the-id-hex-address-globally-for-python-obj
When you don't provide a __repr__ or __str__ method on a custom class, you just get a classname and the Python address of the object (or, to be more specific, what id(self) would return. This is fine most of the time. And it is very helpful when you are debugging some code and you want to see if instances are/are not t...
As a workaround you can add your desired __repr__ to every user class that does not have a custom __repr__ defined anywhere in the MRO. This can be done automaticallly by replacing builtins.__build_class__, which implements the class statement, with a wrapper function that applies the patch to the class that the origin...
1
2
79,530,149
2025-3-24
https://stackoverflow.com/questions/79530149/problem-if-two-inherited-init-subclass-s-have-the-same-argument-name
I'm trying to use two classes, A and B, as mixing classes of AB. They both have __init_subclass__ methods. The problem is that both __init__sublass__ methods have the same argument msg. Therefore I've used an adaptor class B_ to rename B's argument msg_b. But I'm having trouble! The nearest I have got is: class A: def ...
Presumably you don't have the authorization to modify A or B, or you would've renamed the msg parameter in one of their __init_subclass__s already. One workaround then is to use an intermediary base class between A and B with an __init_subclass__ method that renames the argument msg_b to msg before passing the baton to...
1
1
79,529,322
2025-3-23
https://stackoverflow.com/questions/79529322/do-subset-sum-instances-inherently-require-large-integers-to-force-exponential-d
I'm developing custom subset-sum algorithms and have encountered a puzzling issue: it seems difficult to generate truly "hard" subset-sum instances (i.e., forcing exponential computational effort) without using very large integers (e.g., greater than about 2^22). I'd specifically like to know: Are there known construc...
We know subset-sum to be solvable in pseudopolynomial time. "Pseudopolynomial time" means the worst-case running time on large inputs is bounded by a polynomial in the input length and the largest numeric value in the input. Because a string of L bits can encode numbers of size O(2^L), pseudopolynomial time algorithms ...
4
8
79,526,922
2025-3-22
https://stackoverflow.com/questions/79526922/how-to-replicate-the-following-density-plot-in-python
Given the following setup, N_r = 21; N_theta = 18; N_phi= 36; r_index = N_r-1; [phi,theta,r_sphere] = np.meshgrid(np.linspace(0,2*np.pi,N_phi),np.linspace(0,np.pi,N_theta),np.linspace(a,b,N_r)); X = r_sphere[:,:,r_index] * np.sin(theta[:,:,r_index]) * np.cos(phi[:,:,r_index]); Y = r_sphere[:,:,r_index] * np.sin(theta[:...
Ah, so it's the same as with using scatter where we create a colormap out of the data and applying it. The only issue now is that the colorbar's min and max values aren't reflective of the of the data, as it's locked to 0 to 1. I'm guessing that's what the Normalize function does. Tried fiddling around with the inputs...
4
1
79,527,532
2025-3-22
https://stackoverflow.com/questions/79527532/why-is-the-continued-fraction-expansion-of-arctangent-combined-with-half-angle-f
Sorry for the long title. I don't know if this is more of a math problem or programming problem, but I think my math is extremely rusty and I am better at programming. So I have this continued fraction expansion of arctangent: I got it from Wikipedia I tried to find a simple algorithm to calculate it: And I did it, I...
The loss of precision is here: c = (x**2 + y**2) ** 0.5 a, b = c.as_integer_ratio() This code works with float type, which is the result of power calculation ** 0.5. As soon as you use float, you lose arbitrary precision. You might want to use the Decimal.sqrt method instead.
7
7
79,528,465
2025-3-23
https://stackoverflow.com/questions/79528465/find-element-by-key-in-json
I want to fetch an element under the key ID in my json list that looks like this: [{"ID": 0, "login": "admin", "password": "123", "email": "apple@gmail.com"}, {"ID": 1, "login": "admin2", "password": "1234", "email": "grape@gmail.com"}] The list is in the data.json file and it’s not assigned any variable. I have a 'che...
First, create and save a file "fetch_data.py" with the following code: import json def check_id(check): with open("data.json", "r") as file: data = json.load(file) # Read JSON list for item in data: if item.get("ID") == check: return True return False Create and save the main.py file: from fetch_data import check_id c...
2
1
79,528,010
2025-3-22
https://stackoverflow.com/questions/79528010/unexpected-behaviour-in-z3-when-working-with-exponentials
I have the following code in which I am trying to return the value of e^x using z3. However, this code is returning y = 0 import z3 x, y = z3.Real('x'), z3.Real('y') e = z3.RealVal(str(gmpy2.exp(gmpy2.mpfr(1)))) # or e^1, the Euler's number e print(e) s = z3.Solver() s.add(x == 1134585759063987950064875850350910837993/...
If you add: print(s.check()) you'll see that z3 prints: unknown This means that the solver wasn't able to come up with a model that is guaranteed to satisfy the constraints. (Exponentials are hard for SMT solvers: There are very good reasons for this, you can search stack-overflow for it.) So, the model you print is ...
1
1
79,526,468
2025-3-21
https://stackoverflow.com/questions/79526468/why-we-say-dequeue-in-python-is-threadsafe-when-gil-already-restricts-running-on
From what I have been reading Python has GIL that ensures only one thread can run the python code. So I am slightly confused when we say collections.dequeue is thread-safe. If only one thread is run at a time wouldn't objects be in a consistent state already? It would be great if someone can give an example of how a li...
The GIL doesn't prevent race conditions, it only protects python internals from corruption, you cannot have a dangling pointer or a use-after-free inside the python interpreter. the only way they were able to make a GIL-free interpreter in python3.13 is to put a lock (or more than one lock) in every object in python, i...
2
4