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,447,569 | 2025-2-18 | https://stackoverflow.com/questions/79447569/keyerror-version-issue-with-pip-installing-catboost-on-python-3-13-1 | I am working on this ml project and I need to install catboost and xgboost using pip. the xgboost got installed successfully but catboost keeps giving the same error: (venv) D:\ML bootcamp\mlproject>pip install catboost Collecting catboost Using cached catboost-1.2.7.tar.gz (71.5 MB) Installing build dependencies ... d... | According to the catboost installation docs CatBoost Python package supports only CPython Python implementation with versions < 3.13. Version 3.13.x support is in progress. Source: https://catboost.ai/docs/en/concepts/python-installation There is also an open issue for this on their github repo: https://github.com/ca... | 1 | 4 |
79,482,145 | 2025-3-3 | https://stackoverflow.com/questions/79482145/extreme-value-analysis-and-quantile-estimation-using-log-pearson-type-3-pearson | I am trying to estimate quantiles for some snow data using the log pearson type 3 distribution in Python and comparing with R. I do this by reading in the data, log transforming it, fitting Pearson type 3, estimating quantiles, then transforming back from log space. In python: import numpy as np import matplotlib.pyplo... | Okey to my understanding basically, The main difference between the Python and R results stems from the estimation methods used: Python's scipy.stats uses Maximum Likelihood Estimation (MLE) by default. R's lmom package uses L-moments estimation. These methods can produce different parameter estimates, especially for s... | 1 | 1 |
79,480,260 | 2025-3-3 | https://stackoverflow.com/questions/79480260/ta-lib-is-not-properly-detecting-engulfing-candle | As you see in the attached image, there was a Bearish Engulfing candle on December 18. But when I see the same data and engulfing value, it shows something else, in fact 0. Below is the function computing, detecting engulfing candle pattern: def detect_engulfing_pattern(tsla_df): df = tsla_df.rename(columns={"Open": "... | It’s not an engulfing pattern because it only compares one bar to the next, not across multiple bars. I highlighted the part that I think you missed: | 1 | 1 |
79,482,283 | 2025-3-3 | https://stackoverflow.com/questions/79482283/presidio-with-langchain-experimental-does-not-detect-polish-names | I am using presidio/langchain_experimental to anonymize text in Polish, but it does not detect names (e.g., "Jan Kowalski"). Here is my code: from presidio_anonymizer import PresidioAnonymizer from presidio_reversible_anonymizer import PresidioReversibleAnonymizer config = { "nlp_engine_name": "spacy", "models": [{"lan... | After some test I was able to find the solution: config = { "nlp_engine_name": "spacy", "models": [{"lang_code": 'pl', "model_name": "pl_core_news_lg"}], } spacy_recognizer = SpacyRecognizer( supported_language="pl", supported_entities=["persName"] ) anonymizer.add_recognizer(spacy_recognizer) anonymizer_tool = Presidi... | 4 | -2 |
79,469,513 | 2025-2-26 | https://stackoverflow.com/questions/79469513/how-read-a-file-from-a-pod-in-azure-kubernetes-service-aks-in-a-pythonic-way | I have a requirement to read a file which is located inside a particular folder in a pod in AKS. My manual flow would be to: exec into the pod with kubectl. cd to the directory where the file is located. cat the file to see it's contents. I want to automate all this purely using python. I am able to do it with subpro... | To read a file which is located inside a particular folder in a pod in AKS via Python script, follow the below steps Assuming you have a valid aks cluster up and running, deploy a pod with your desired file. For example - apiVersion: v1 kind: Pod metadata: name: my-pod labels: app: my-app spec: containers: - name: my-c... | 1 | 2 |
79,475,225 | 2025-2-28 | https://stackoverflow.com/questions/79475225/azure-documen-intelligence-python-sdk-doesnt-separate-pages | When trying to extract content from a MS Word .docx file using Azure Document Intelligence, I expected the returned response to contain a page element for each page in the document and for each of those page elements to contain multiple lines in line with the documentation. Instead, I always receive as a single page wi... | As you have shown in your Actual output, all the 66 characters in your document are considered as one page. This is the expected behavior. As mentioned in the Docs on how the page units are computed: 3,000 characters are considered as one page unit in Word Document. File format Computed page unit Total pages Wor... | 2 | 1 |
79,481,379 | 2025-3-3 | https://stackoverflow.com/questions/79481379/hollowing-out-a-patch-anticlipping-a-patch-in-matplotlib-python | I want to draw a patch in Matplotlib constructed by hollowing it out with another patch, in a way such that the hollowed out part is completely transparent. For example, lets say I wanted to draw an ellipse hollowed out by another. I could do the following: import matplotlib.pyplot as plt from matplotlib.patches import... | Approach for ellipses The following is a simple approach that works for the ellipse example (and, generally, for symmetric objects): import matplotlib.pyplot as plt from matplotlib.patches import Ellipse, Rectangle, PathPatch from matplotlib.path import Path from matplotlib.transforms import Affine2D ellipse_1 = Ellips... | 2 | 4 |
79,480,032 | 2025-3-3 | https://stackoverflow.com/questions/79480032/in-numpy-find-a-percentile-in-2d-with-some-condition | I have this kind of array a = np.array([[-999, 9, 7, 3], [2, 1, -999, 1], [1, 5, 4, 6], [0, 6, -999, 9], [1, -999, -999, 6], [8, 4, 4, 8]]) I want to get 40% percentile of each row in that array where it is not equal -999 If I use np.percentile(a, 40, axis=1) I will get array([ 3.8, 1. , 4.2, 1.2, -799. , 4.8]) which ... | You can replace the -999s with NaNs and use nanpercentile. import numpy as np a = np.array([[-999, 9, 7, 3], [2, 1, -999, 1], [1, 5, 4, 6], [0, 6, -999, 9], [1, -999, -999, 6], [8, 4, 4, 8]], dtype=np.float64) a[a == -999] = np.nan np.nanpercentile(a, 40, axis=-1, keepdims=True) # array([[6.2], # [1. ], # [4.2], # [4.8... | 1 | 3 |
79,480,952 | 2025-3-3 | https://stackoverflow.com/questions/79480952/drawing-line-between-hand-landmarks | here is my code that draws landmarks on hand using mediapipe import cv2 import time import mediapipe as mp mp_holistic = mp.solutions.holistic holistic_model = mp_holistic.Holistic( min_detection_confidence=0.5, min_tracking_confidence=0.5 ) # Initializing the drawing utils for drawing the facial landmarks on image mp_... | You're using the built-in Mediapipe function draw_landmarks to handle all the drawings. This function takes an image, a normalized landmark list, and connections as inputs. However, the NormalizedLandmarkList type in Mediapipe doesn’t support merging multiple landmark lists, making it difficult to pass landmarks for bo... | 1 | 3 |
79,475,324 | 2025-2-28 | https://stackoverflow.com/questions/79475324/fitting-a-function-to-exponentially-decreasing-numbers-ensuring-equal-weight-fo | So this question is based on a biochemical experiment. For those who know a bit about biochemistry it is an enzyme kinetics experiment. I have a dilution series of an activator (a or x) and am measuring the enzyme velocity (y). The fitting equation (mmat) is derived from a biological model. The challenge I'm facing is ... | Okay, so it seems like I solved my problem and if at some point someone is searching for something similar, here is the answer: Scipy's curve_fit function, which uses least-squares fitting, aims to minimize the sum of the squared differences between the calculated and observed y-data. The equation for this is: sum(((f(... | 2 | 2 |
79,481,870 | 2025-3-3 | https://stackoverflow.com/questions/79481870/how-do-you-unwrap-a-python-property-to-get-attributes-from-the-getter | From "outside", how can I access attributes in a property's getter function whether by unwrapping it or some other way? In a python property, its __get__ function seems to be a wrapper of a wrapper of a wrapper ... Using inspect.unwrap on the __get__ function returns another wrapper, not the getter. In fact, what unwra... | ap.__class__.aprop.__get__ is a method of ap.__class__.aprop, so when you access the __get__ attribute of ap.__class__.aprop you invoke the MethodType descriptor, which stores the object that the method is bound to as the __self__ attribute. In this case, the object it's bound to is ap.__class__.aprop, a property descr... | 2 | 1 |
79,482,105 | 2025-3-3 | https://stackoverflow.com/questions/79482105/pyserial-asyncio-client-server-in-python-3-8-not-communicating-immediately | I'm learning python and asyncio and after having success with asyncio for a TCP client/server I took my first stab at creating a serial client/server using pyserial-asyncio running in bash on a Raspberry Pi 5 using Python 3.8 (I cannot change version). Here is the server: import asyncio import serial_asyncio class UART... | The problem here is that input is a blocking call. We all know that input doesn't return until the user types some text and hits the enter key. We also know that it's not an async function, therefore it doesn't use the event loop. So it can't run other Tasks while it's waiting for the user to type something. All the as... | 1 | 1 |
79,482,376 | 2025-3-3 | https://stackoverflow.com/questions/79482376/pandas-dropping-first-group-of-values | I want to drop the first group of rows based on a column's value. Here is an example of a table stage h1 h2 h3 0 4 55 55 0 5 66 44 0 4 66 33 1 3 33 55 0 5 44 33 Get the column stage, get all the first group of rows that start with 0, and drop the rows in the table. The table will look like this: st... | df.iloc[df['stage'].diff().idxmax():] First, find the first transition from 0 to 1 is by computing the difference between consecutive values in the stage column (using diff). Then use idxmax to locate the index where the first transition occurs. NB: In case, there are transitions that differ more than 1 unit, then use... | 1 | 4 |
79,480,120 | 2025-3-3 | https://stackoverflow.com/questions/79480120/why-result-of-scaling-each-column-always-equal-to-zero | I am using minmaxscaler trying to scaling each column. The scaled result for each column is always all zero. For example , below the values of df_test_1 after finishing scaling is all zero. But even with all values of zero, using inverse_transferm from this values of zero can still revert back to original values. But w... | According to MinMaxScaler DOC: X : array-like of shape (n_samples, n_features) The data used to compute the per-feature minimum and maximum used for later scaling along the features axis. When you reshape your data here: df_test_1.loc[:,df_test.columns[1]].values.reshape(1,-1) you get 1 row data with 4 columns in yo... | 1 | 1 |
79,481,158 | 2025-3-3 | https://stackoverflow.com/questions/79481158/keep-rows-where-a-field-of-a-liststruct-column-contains-a-message | Say I have the following data: import duckdb rel = duckdb.sql(""" FROM VALUES ([{'a': 'foo', 'b': 'bta'}]), ([]), ([{'a': 'jun', 'b': 'jul'}, {'a':'nov', 'b': 'obt'}]) df(my_col) SELECT * """) which looks like this: ┌──────────────────────────────────────────────┐ │ my_col │ │ struct(a varchar, b varchar)[] │ ├───────... | Maybe list_sum() the bools or list_bool_or()? https://duckdb.org/docs/stable/sql/functions/list.html#list_-rewrite-functions duckdb.sql(""" FROM VALUES ([{'a': 'foo', 'b': 'bta'}]), ([]), ([{'a': 'jun', 'b': 'jul'}, {'a':'nov', 'b': 'obt'}]) df(my_col) SELECT * WHERE list_bool_or(['bt' in s.b for s in my_col]) """) ... | 2 | 1 |
79,481,132 | 2025-3-3 | https://stackoverflow.com/questions/79481132/aligning-grid-columns-between-parent-and-container-frames-using-tkinter | Using Python and tkinter I have created a dummy app with a scrollable frame. There are two column headings in a container frame. The container frame also contains a canvas. Inside the canvas is an inner frame with two columns of scrollable content. Problem: the column headings do not align with the columns, presumably ... | It is because the innerframe does not have the same width of the canvas (which is the sum of the widths of the two labels at the top). You need to: set highlightthickness=0 in tk.Canvas(...) set the width of innerframe to the same as scrollcanvas (in callback of <Configure> event on scrollcanvas) add uniform=... to ou... | 2 | 2 |
79,480,437 | 2025-3-3 | https://stackoverflow.com/questions/79480437/find-column-name-with-highest-value | On the Pandas dataframe below I use max to find the maximum value: df["Max"] = df[['Day 1','Day 2','Day 4']].max(axis=1) Car Day 1 Day 2 Day 4 Max Car1 4 7 3 7 car2 8 2 1 8 What do I do to find when is the maximum value instead of the value itself as the table example below? Car Day 1 Day 2 Day 4 When ... | Yes, you can achieve this in Pandas using .idxmax(axis=1), which returns the column name where the maximum value occurs. Documentation - pandas.DataFrame.idxmax import pandas as pd data = { 'Car': ['Car1', 'Car2'], 'Day 1': [4, 8], 'Day 2': [7, 2], 'Day 4': [3, 1] } df = pd.DataFrame(data) df.set_index('Car', inplace=T... | 1 | 1 |
79,480,218 | 2025-3-3 | https://stackoverflow.com/questions/79480218/python-package-installation-fails-getting-requirements-to-build-wheel-did-not | In my python projects I create a list of required packages by pip freeze > requirements.txt it automatically list the packages with version. But after a while when I reinstall the package or trying to run other people project I have to install the dependencis with pip install -r requirements.txt. In this process some o... | Your Python version is 3.13 and it is not compatible with pillow 10.3.0. Pillow 10.3.0 supports Python 3.8 - 3.12. There are no wheels for Python 3.13. So why did pip install pillow work? Installing a package without specifying a version usually attempts to install the latest release. So pip install pillow will give yo... | 1 | 2 |
79,479,347 | 2025-3-2 | https://stackoverflow.com/questions/79479347/is-it-possible-to-increase-the-space-between-trace-lines-that-are-overlapping-on | I have been searching for this solution in the official site of Plotly, Plotly forum and this forum for 3 days, and did not find it. I tried these following quetsions: How to avoid overlapping text in a plotly scatter plot? Make X axis wider and Y axis narrower in plotly For example, here is the image: You can see t... | One way to deal with data adjacencies like this is to make the y-axis logarithmic, which sometimes solves the problem, but in your case the effect is limited. My suggestion is to create a subplot with three groups of numbers. Besides, minimise the gaps between the graphs to make them appear as one graph. The key to set... | 2 | 1 |
79,479,725 | 2025-3-2 | https://stackoverflow.com/questions/79479725/specify-model-related-fields-for-selection-with-only-function | Is it possible specify related model fields for selection with only() function in query? In this example I got KeyError: 'provider__description' from typing import Optional, List from tortoise import fields from models import BaseModel class Token(BaseModel): id = fields.CharField(primary_key=True, max_length=128) user... | Found solve in tortoise-orm docs on Github. For prefetch only certain fields need to use tortoise.query_utils.Prefetch object. query = Token.all().prefetch_related( Prefetch("provider", queryset=Provider.all().only("id", "description")), ) | 1 | 2 |
79,479,213 | 2025-3-2 | https://stackoverflow.com/questions/79479213/how-to-efficiently-exclude-already-assigned-objects-in-a-django-queryset | I am working on a Django project where I need to filter objects based on their status while excluding those that are already assigned in another model. I have two models: CartObject – Stores all objects. OnGoingProcess – Tracks objects that are currently assigned. Each OnGoingProcess entry has a OneToOneField relatio... | Your query: available_objects = ( CartObject.objects.filter(status='pending') .exclude(id__in=assigned_objects) .order_by('-id') ) will use a subquery, so run as: AND id NOT IN (SELECT associated_object FROM useradmin_ongoingprocess) You can inspect it with: print(available_objects.query) But on databases like MySQL,... | 4 | 5 |
79,475,986 | 2025-2-28 | https://stackoverflow.com/questions/79475986/pipeline-futurewarning-this-pipeline-instance-is-not-fitted-yet | I am working on a fairly simple machine learning problem in the form of a practicum. I am using the following code to preprocess the data: from preprocess.date_converter import DateConverter from sklearn.pipeline import Pipeline from preprocess.nan_fixer import CustomImputer import pandas as pd from preprocess.encoding... | The two issues are separate. The warning that the pipeline is not fitted is because of how pipelines report themselves as fitted: they just check whether their last (non-passthrough) step is fitted (source code). So your custom scaler isn't reported as having been fit. check_is_fitted looks for attributes with trailing... | 1 | 3 |
79,475,881 | 2025-2-28 | https://stackoverflow.com/questions/79475881/how-to-correctly-pair-elements-from-two-xcom-lists-in-airflow-triggerdagrunopera | I am using Apache Airflow and trying to trigger multiple DAGs from within another DAG using TriggerDagRunOperator.expand(). I have two lists being returned from an upstream task via XCom: confs → A list of dictionaries containing conf parameters. dags_to_trigger → A list of DAG IDs to be triggered. Each list contains 5... | Don't know your Airflow version but hope this helps. You can use execute() method instead of partial() + expand(). Here is an example: from datetime import datetime from typing import Any from airflow import DAG from airflow.models import BaseOperator from airflow.operators.empty import EmptyOperator from airflow.opera... | 1 | 2 |
79,478,331 | 2025-3-1 | https://stackoverflow.com/questions/79478331/what-does-matrixtrue-false-do-in-numpy | For example, I have matrix=np.array([[1,2],[3,4]]). When I use boolean filtration in Numpy like: matrix[[True,False]], I understand how's it works - I'll get the first row. But when I use something like: matrix[True, False] , I get empty parentheses. I guess, in this case boolean values means which dimension I want to ... | This is a very weird case. It is in fact tested, but I don't think the behavior is documented anywhere. If you index an array with any number of True scalars, the result is equivalent to arr[np.newaxis]: it contains all the original array's data, but with an extra length-1 axis at the start of its shape. If you index a... | 4 | 5 |
79,477,947 | 2025-3-1 | https://stackoverflow.com/questions/79477947/removing-list-duplicates-given-indices-symmetry-in-python | In python, given a list mylist of lists el of integers, I would like to remove duplicates that are equivalent under specific permutations of the indices. The question is more general but I have in mind "decorated" McKay graphs where each node is given an integer defining el whose sum is equal to a certain number. Gener... | It will probably be better to add "seen" cases to a set, and then continue to check if new elements have already been "seen", rather than comparing every element to every other element in the list iteratively (an operation with O(n^2) time complexity). Hopefully I understand what you're trying to accomplish, but here's... | 1 | 1 |
79,477,752 | 2025-3-1 | https://stackoverflow.com/questions/79477752/subclass-that-throws-custom-error-if-modified | What's the best way in python to create a subclass of an existing class, in such a way that a custom error is raised whenever you attempt to modify the object? The code below shows what I want. class ImmutableModifyError(Exception): pass class ImmutableList(list): def __init__(self, err = "", *argv): self.err = err sup... | There are plenty of more scalable and less error-prone way to achieve this is to dynamically block all mutating methods. Using Setattr to indentify all mutating methods dynamically and override them [Best Method to implement - Pycon 2017] class ImmutableModifyError(Exception): pass class ImmutableList(list): def __init... | 1 | 2 |
79,475,564 | 2025-2-28 | https://stackoverflow.com/questions/79475564/powershell-and-cmd-combining-command-line-filepath-arguments-to-python | I was making user-entered variable configurable via command line parameters & ran into this weird behaviour: PS D:> python -c "import sys; print(sys.argv)" -imgs ".\Test V4\Rilsa\" -nl 34 ['-c', '-imgs', '.\\Test V4\\Rilsa" -nl 34'] PS D:> python -c "import sys; print(sys.argv)" -imgs ".\TestV4\Rilsa\" -nl 34 ['-c', '-... | You're seeing a bug in Windows PowerShell (the legacy, ships-with-Windows, Windows-only edition of PowerShell whose latest and last version is 5.1), which has since been fixed in PowerShell (Core) 7, as detailed in this answer. In short, as you've since discovered yourself, the problem occurs when you pass arguments ... | 1 | 2 |
79,474,319 | 2025-2-28 | https://stackoverflow.com/questions/79474319/how-to-conditinonally-choose-which-column-to-backfill-over-in-polars | I need to backfill a column in a python polars dataframe over one of three possible columns, based on which one matches the non-null cell in the column to be backfilled. My dataframe looks something like this: ┌─────┬─────┬─────┬─────────┐ │ id1 ┆ id2 ┆ id3 ┆ call_id │ │ --- ┆ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ i64 ┆ i64 ... | Assuming that your dataframe is in a variable called df and your backfill value is always the same (which is the case in your example) df.with_columns( call_id=pl.coalesce( pl.when( (pl.col("^id.*$") == pl.col("call_id")).backward_fill().over("^id.*$") ) .then("^id.*$") ) ) # shape: (10, 4) # ┌─────┬─────┬─────┬───────... | 1 | 2 |
79,477,010 | 2025-3-1 | https://stackoverflow.com/questions/79477010/find-the-equation-of-a-line-with-sympy-y-mxb | So I'm brushing up on my algebra and trying to learn sympy at the same time. Following an algebra tutorial on youtube, I'm at this point: I can't quite figure out how to isolate y What I've tried: p1 = sym.Point(-1, 1) m = -2 eq = sym.Line(p1, slope=m).equation() eq returns: 2x + y + 1 eq1 = sym.Eq(eq, 0) eq1 Gives ... | I believe that the code below gives what you want. I believe solve wasn't working for you because you needed to define x, y as symbols. Then you can use the solution to create your equation using Eq. Note that the solution is a list. Hope this helps. import sympy as sym from sympy.solvers import solve p1 = sym.Point(-1... | 1 | 3 |
79,476,892 | 2025-2-28 | https://stackoverflow.com/questions/79476892/pandas-groupby-make-all-elements-0-if-first-element-is-1 | I have the following df: | day | first mover | | -------- | -------------- | | 1 | 1 | | 2 | 1 | | 3 | 0 | | 4 | 0 | | 5 | 0 | | 6 | 1 | | 7 | 0 | | 8 | 1 | i want to group this Data frame in the order bottom to top with a frequency of 4 rows. Furthermore if first row of group is 1 make all other entries 0. Desired ou... | I would use for-loop for this for name, group in df.groupby(...): this way I could use if/else to run or skip some code. To get first element in group: (I don't know why but .first() doesn't work as I expected - it asks for some offset) first_value = group.iloc[0]['first mover'] To get indexes of other rows (except f... | 1 | 0 |
79,476,789 | 2025-2-28 | https://stackoverflow.com/questions/79476789/how-to-get-the-dot-product-of-inner-dims-in-numpy-array | I would like to compute the dot product (matmul) of the inner dimension of two 3D arrays. In the following example, I have an array of 10 2x3 matrixes (X) and an array of 8 1x3 matrixes. The result Z should be a 10 element array of an 8 x 2 matrix (you might also think of this as an 10 x 8 array of 2-d vectors.) X = np... | Einsum You could use einsum np.einsum('ijk,lmk->ilj', X, Y) It produces an array whose shape is 3 axis axis 0 (i) the size of first axis of X (here 10) axis 1 (l) size of first axis of Y (here 8) axis 2 (j) second axis of X (2) m is just ignored (size 1) and k (3rd axis of both), since it is repeated is used to sum p... | 3 | 2 |
79,475,699 | 2025-2-28 | https://stackoverflow.com/questions/79475699/django-pagination-for-inline-models | I realize this is probably a beginner level error, but I'm out of ideas. I need to add pagination to Inline model for admin page. I'm using Django 1.8.4 ( yup, I know it's really old ) and python 3.6.15. Inside admin.py: class ArticleInline(GrappelliSortableHiddenMixin, admin.TabularInline): model = ArticleSection.arti... | This is due to compatibility issues between older versions of Python and Django when handling function signatures.. for example, related_lookup_fields is Deprecated in Django Admin such that the part related_lookup_fields = { 'fk': ['article'], } should be replaced by autocomplete_fields = ["article"] or just remove ... | 1 | 1 |
79,474,870 | 2025-2-28 | https://stackoverflow.com/questions/79474870/is-there-any-benefit-of-choosing-to-formulate-constraints-in-a-way-or-another-in | I have an MINLP problem and let's say the continuous variable Q can only be 0 when the binary variable z is 0. Two ways to formulate this would be: m.Equation(Q*(1-z) == 0) (1) or m.Equation(Q < z*10000) (2) whereby 10000 would be the upper bound to the continuous variable Q. Does (1) or (2) have any benefits over the ... | Q(1-z) = 0 is non-linear and non-convex while Q <= 10000z is linear (and convex). The last one is much better as long as the big-M constant is small. If you can't reduce the size of the big-M constant, consider using indicator constraints (using suitable modeling tools and solvers). | 1 | 2 |
79,475,812 | 2025-2-28 | https://stackoverflow.com/questions/79475812/python-cyrillic-string-encoding | I try to convert cyrillic string to readable format. I have the similar code for php and it work fine. But python was harder. import re from sys import getdefaultencoding def decodeString(matches): return chr(int(matches.group(0).lstrip('\\'), 8)) my_string = r'\320\222\321\213\320\263\321\200\321\203\320\267\320\272\3... | If you are able to get around using r'' then using b'' should work: def decode_utf8(byte_string: bytes) -> str: return byte_string.decode('utf-8') # Example usage byte_string = b'\320\222\321\203\320\263\321\200\321\203\320\267\320\272\320\260 \320\267\320\260\321\217\320\262\320\276\320\272' print(decode_utf8(byte_str... | 1 | 2 |
79,474,514 | 2025-2-28 | https://stackoverflow.com/questions/79474514/how-to-remove-xarray-plot-bad-value-edge-colour | I know set_bad can colour the pixel into a specific colour but in my example I only want to have edge colour for blue and grey pixels with values and not the bad pixels (red) import matplotlib.pyplot as plt import xarray as xr import numpy as np from matplotlib import colors fig, ax = plt.subplots(1, 1, figsize=(12, 8)... | Update: I was premature in my original answer (see below), and you can actually pass a list of edge colours (see pcolormesh) that can be used for each "box" within the plot. So, you could use: import xarray as xr import numpy as np from matplotlib import pyplot as plt from matplotlib import colors fig, ax = plt.subplot... | 1 | 3 |
79,475,051 | 2025-2-28 | https://stackoverflow.com/questions/79475051/whats-the-difference-between-uv-lock-upgrade-and-uv-sync | Being a total newbie in the python ecosystem, I'm discovering uv and was wondering if there was a difference between the following commands : uv lock --upgrade and uv sync If there's any, what are the exact usage for each of them ? | uv lock commands are all about managing the uv.lock file (or creating it). But what they NOT do: upgrading the actual package versions in your environment! The uv lock --upgrade command updates the lock file (uv.lock) by allowing package upgrades, even if they were previously pinned. But still it is a managing command ... | 1 | 2 |
79,474,435 | 2025-2-28 | https://stackoverflow.com/questions/79474435/assertequal-tests-ok-when-numpy-ndarray-vs-str-is-that-expected-or-what-have-i | My unittest returns ok, but when running my code in production, I found that my value is 'wrapped' with square brackets. Further investigation shows that, it lies under the df.loc[].values . I am expecting a single str value. Using the sample by cs95 and doing some slight modification, I am able to reproduce it to illu... | Yes, I believe that is expected behavior. From the documentation, unittest.TestCase.assertEqual(a, b) checks that a == b. If you run >>> if np.array([['3']]) == '3': ... print("Here") Here It indeed prints "Here". This is because of the way broadcasting works in numpy. When comparing an array against a string, like in... | 3 | 2 |
79,473,651 | 2025-2-27 | https://stackoverflow.com/questions/79473651/how-to-normalise-a-two-dimensional-array | I am given a two-dimensional array. Each element represents the x,y coordinates of a trapezium. I do not want negative values so I need to adjust the minimum x value to zero and I want to adjust the minimum y value to zero. I can do this (see below), but in a very long winded way. Is there a more elegant way to normali... | You can use .min(0) to get the minimum for each of x and y individually and then subtract that from the entire array. pa -= pa.min(0) | 1 | 2 |
79,473,874 | 2025-2-27 | https://stackoverflow.com/questions/79473874/how-to-group-by-on-multiple-columns-and-retain-the-original-index-in-a-pandas-da | I need to group by multiple columns on a dataframe and calculate the rolling mean in the group. But the original index needs to be preserved. Simple python code below : data = {'values': [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15], 'type':['A','B','A','B','A','B','A','B','A','B','A','B','A','B','A'], 'type2':['C','D','C','D'... | You should use droplevel: cols = ['type', 'type2'] df['mean'] = (df.groupby(cols)['values'] .rolling(window=3).mean() .droplevel(cols) ) Output: values type type2 mean 0 1 A C NaN 1 2 B D NaN 2 3 A C NaN 3 4 B D NaN 4 5 A C 3.0 5 6 B D 4.0 6 7 A C 5.0 7 8 B D 6.0 8 9 A C 7.0 9 10 B D 8.0 10 11 A C 9.0 11 12 B D 10.0 ... | 2 | 2 |
79,470,854 | 2025-2-26 | https://stackoverflow.com/questions/79470854/supply-extra-parameter-as-function-argument-for-scipy-optimize-curve-fit | I am defining a piecewise function for some data, def fit_jt(x, e1, e2, n1, E1, E2, N1, N2): a = 1.3 return np.piecewise(x, [x <= a, x > a], [ lambda x: 1 / e1 + (1 - np.float128(np.exp(-e2 * x / n1))) / e2, lambda x: 1 / E1 + (1 - np.float128(np.exp(-E2 * x / N1))) / E2 + x / N2 ]) which is called in main as: popt_j... | Use a factory function that returns a fit_it function with the desired value of a "baked in" via a closure: def make_fit_it(a): def fit_jt(x, e1, e2, n1, E1, E2, N1, N2): return np.piecewise(x, [x <= a, x > a], [ lambda x: 1 / e1 + (1 - np.float128(np.exp(-e2 * x / n1))) / e2, lambda x: 1 / E1 + (1 - np.float128(np.exp... | 1 | 2 |
79,473,568 | 2025-2-27 | https://stackoverflow.com/questions/79473568/np-where-with-a-in-type-condition | Given a numpy array arr = np.array([1, 2, 3, 4, 5]) I need to construct a binary mask according to a (arbitrary, potentially long) list of values, i.e. given values = np.array([2, 4, 5]) mask should be mask = np.array([False, True, False, True, True]) So I want to avoid condition = (arr==2) or (arr==4) or (arr==5) m... | In [64]: arr = np.array([1, 2, 3, 4, 5]) ...: values = np.array([2, 4, 5]) While isin is easy to use, it isn't the only option: In [66]: np.isin(arr, values) Out[66]: array([False, True, False, True, True]) We could compare the whole arrays: In [67]: values[:,None]==arr Out[67]: array([[False, True, False, False, Fal... | 3 | 3 |
79,473,015 | 2025-2-27 | https://stackoverflow.com/questions/79473015/how-to-gracefully-stop-an-asyncio-server-in-python-3-8 | As part of learning python and asyncio I have a simple TCP client/server architecture using asyncio (I have reasons why I need to use that) where I want the server to completely exit when it receives the string 'quit' from the client. The server, stored in asyncio_server.py, looks like this: import socket import asynci... | You can use an asyncio.Event to set when the QUIT message arrives. Then have asyncio wait for the either server_forever() or the Event to complete first. Once the Event is set, call the .close() method and stop the server. In the code below I assigned the server to an attribute. import socket import asyncio class Serve... | 1 | 2 |
79,473,192 | 2025-2-27 | https://stackoverflow.com/questions/79473192/disagreement-between-scipy-quaternion-and-wolfram | I'm calculating rotation quaternions from Euler angles in Python using SciPy and trying to validate against an external source (Wolfram Alpha). This Scipy code gives me one answer: from scipy.spatial.transform import Rotation as R rot = R.from_euler('xyz', [30,45,60], degrees=1) quat = rot.as_quat() print(quat[3], quat... | Indeed, when you switch from small "xyz", which denotes extrinsic rotations, to capital "XYZ", which denotes intrinsic rotations in from_euler(), the results will match those of WolframAlpha: from scipy.spatial.transform import Rotation import numpy as np np.set_printoptions(precision=3) rot = Rotation.from_euler("XYZ"... | 1 | 4 |
79,473,140 | 2025-2-27 | https://stackoverflow.com/questions/79473140/add-edges-to-colorbar-in-seaborn-heatmap | I have the following heatmap: import seaborn as sns import matplotlib.pyplot as plt import numpy as np # Create a sample heatmap data = np.random.rand(10, 12) ax = sns.heatmap(data) plt.show() How can I add a black edge to the colormap? Is there any way to do this without needing to use subplots? | Looks like seaborn turns the edges off by default. Here's an approach to get a reference to the colorbar Axes, and then re-apply the edge: ax = sns.heatmap(data) cax = ax.figure.get_children()[-1] cax.spines['outline'].set_linewidth(0.5) # adjust as desired Output: | 1 | 2 |
79,473,353 | 2025-2-27 | https://stackoverflow.com/questions/79473353/valueerror-too-many-values-to-unpack-python-when-creating-dictionary-from-a-str | I am trying to create a dictionary from a string. In this case I have posted my sample code (sorry its not that clean, just hardcoded values), the first str1 works fine and is able generate a corresponding dictionary by splitting correctly ; and associating key value at = sign. However, the second string (str5) is not ... | In split function you can pass additional parameter like maxsplit=1, so that it will split only based on first occurence of delimiter. i.e.g pair.split("=", 1) for pair in str5.split(";"): key, value = pair.split("=", 1) dictionary[key] = value | 1 | 2 |
79,472,659 | 2025-2-27 | https://stackoverflow.com/questions/79472659/boolean-indexing-in-numpy-arrays | I was learning boolean indexing in numpy and came across this. How is the indexing below not producing a Index Error as for axis 0 as there are only two blocks? x = np.arange(30).reshape(2, 3, 5) x array([[[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14]], [[15, 16, 17, 18, 19], [20, 21, 22, 23, 24], [25, 26, 2... | You are performing boolean array indexing, which is fine. You would have an indexing error with: # first dimension second dimension x[[True, True, False], [False, True, True]] # IndexError: boolean index did not match indexed array along dimension 0; # dimension is 2 but corresponding boolean dimension is 3 However, i... | 2 | 3 |
79,472,665 | 2025-2-27 | https://stackoverflow.com/questions/79472665/how-to-access-a-dictionary-key-storing-a-list-in-a-list-of-lists-and-dictionarie | I have the following list: plates = [[], [], [{'plate ID': '193a', 'ra': 98.0, 'dec': 11.0, 'sources': [[3352102441297986560, 99.28418829069784, 11.821604434173034], [3352465726807951744, 100.86164898224092, 12.756149587760696]]}], [{'plate ID': '194b', 'ra': 98.0, 'dec': 11.0, 'sources': [[3352102441297986560, 99.2841... | There is absolutely no need for pandas here. You're just using it as an expensive and slow container. Just loop over the lists and dictionaries, in pure python: matched_plates = [] matches_sources_ra = [] matches_sources_dec = [] for lst in plates: for dic in lst: if 'sources' in dic: print(dic['plate ID']) matched_pla... | 3 | 4 |
79,470,526 | 2025-2-26 | https://stackoverflow.com/questions/79470526/grouped-rolling-mean-in-polars | Similar question is asked here However it didn't seem to work in my case. I have a dataframe with 3 columns, date, groups, prob. What I want is to create a 3 day rolling mean of the prob column values grouped by groups and date. However following the above linked answer I got all nulls returned. import polars as pl fro... | Overall Problem. You group not only by group but also by date. This effectively performs the rolling operation separately for each group and date (i.e. separately for each row). Explanation of 1st attempt. As the groups are defined by the group and date columns, each group consists of a single row. This is lower than m... | 4 | 5 |
79,471,079 | 2025-2-26 | https://stackoverflow.com/questions/79471079/how-to-handle-malformed-api-request-in-flask | There is quite an old game (that no longer works) that has to make some API calls in order to be playable. I am creating a Flask mock server to handle those requests, however it turned out that the requests are not compliant with HTTP standard and are malformed. For example: Get /config.php http/1.1 to which flask rep... | Flask uses Werkzeug which in turn uses Python's http.server to parse HTTP requests. So the error is actually thrown by Python's http.server.BaseHTTPRequestHandler @ Line 311. Only way to get around this error is by monkey patching certain methods. If you let me know the version number of Werkzeug that you're running, I... | 1 | 2 |
79,470,828 | 2025-2-26 | https://stackoverflow.com/questions/79470828/nodriver-cannot-start-headless-mode | I found Nodriver, which is the successor Undetected-Chromedriver. I am trying to run in headless mode but am having problems. import nodriver as uc async def main(): browser = await uc.start(headless=True) page = await browser.get('https://bot.sannysoft.com/') if __name__ == '__main__': uc.loop().run_until_complete(mai... | The issue was created on the repo link This was suggested: browser_args.append(f"--headless=new") | 1 | 1 |
79,469,254 | 2025-2-26 | https://stackoverflow.com/questions/79469254/calculating-the-curvature-of-a-discrete-function-in-3d-space | I have a set of points representing a curve in 3D space. The goal is to detect the point with the maximum curvature. When looking on the curvature page on Wikipedia, I find the curvature can be found as the magnitude of the acceleration of the parametric function. My idea of solving the solution is to interpolate a B-s... | Fundamentally, each successive three points must lie on their own circle and the local radius of curvature (reciprocal of the “curvature”) is just the radius of that circle. Take points i-1, i, i+1 and form successive tangent vectors tA and tB. Three points must lie in a unique plane, unless they are collinear. Within ... | 4 | 3 |
79,469,894 | 2025-2-26 | https://stackoverflow.com/questions/79469894/polars-cum-sum-to-create-a-set-and-not-actually-sum | I'd like to use a function like cumsum, but that would create a set of all values contained in the column up to the point, and not to sum them df = pl.DataFrame({"a": [1, 2, 3, 4]}) df["a"].cum_sum() shape: (4,) Series: 'a' [i64] [ 1 3 6 10 ] but I'd like to have something like df["a"].cum_sum() shape: (4,) Series: 'a... | This can be achieved using pl.Expr.cumulative_eval together with pl.Expr.unique and pl.Expr.implode as follows. df.with_columns( res=pl.col("a").cumulative_eval(pl.element().unique().implode()) ) shape: (4, 2) ┌─────┬─────────────┐ │ a ┆ res │ │ --- ┆ --- │ │ i64 ┆ list[i64] │ ╞═════╪═════════════╡ │ 1 ┆ [1] │ │ 2 ┆ [... | 2 | 3 |
79,469,073 | 2025-2-26 | https://stackoverflow.com/questions/79469073/how-to-group-data-using-pandas-by-an-array-column | I have a data frame collected from a CSV in the following format: Book Name,Languages "Book 1","['Portuguese','English']" "Book 2","['English','Japanese']" "Book 3","[Spanish','Italian','English']" ... I was able to convert the string array representation on the column Languages to a python array using transform, but ... | You can do this by iterating through the DataFrame and updating a dictionary dynamically. import pandas as pd import ast data = { "Book Name": ["Book 1", "Book 2", "Book 3"], "Languages": ["['Portuguese','English']", "['English','Japanese']", "['Spanish','Italian','English']"] } df = pd.DataFrame(data) df["Languages"] ... | 2 | 0 |
79,470,214 | 2025-2-26 | https://stackoverflow.com/questions/79470214/add-space-between-xlabels-in-matplotlib | I have the following issue: I need to create a graph showing the results of an experiment I did in the lab recently. Unfortunately, two of these values are very close together due to an error (which must be considered). When I create the graph, these two values are so close to each other that they are basically unreada... | First, I'd suggest using the Axes interface instead of the pyplot interface. You could manually move the 0.217 label to the left (inspired by this answer): import matplotlib.pyplot as plt from matplotlib.transforms import ScaledTranslation import numpy as np x = [0.4139, 0.2192, 0.2170, 0.1124, 0.0570, 0.0289, 0.0144] ... | 2 | 1 |
79,469,400 | 2025-2-26 | https://stackoverflow.com/questions/79469400/python-numpy-how-to-split-a-matrix-into-4-not-equal-matrixes | from sympy import * import numpy as np # Python 3.13.2 u1 = Symbol("u1") u2 = Symbol("u2") q3 = Symbol("q3") u4 = Symbol("u4") q5 = Symbol("q5") disp_vector = np.array([u1, u2, q3, u4, q5]) stiffness_matrix = np.array([[1, 0, 0, -1, 0], [0, 0.12, 0.6, 0, 0.6], [0, 0.6, 4, 0, 2], [-1, 0, 0, 1, 0], [0, 0.6, 2, 0, 4]]) fo... | You need to divide your stiffness matrix into four submatrices based on the degrees of freedom you want to r and c. So to retain the first 3 rows/columns and condense the last 2 krr: The top left block krc: The top right block kcr: The bottom left block kcc: The bottom right block The code n_retain = 3 n_condense = 2 ... | 2 | 2 |
79,469,031 | 2025-2-26 | https://stackoverflow.com/questions/79469031/does-clickhouse-connect-get-client-return-a-new-client-instance-every-time | As the question mentions, does clickhouse_connect.get_client in the python client return a new client instance every time it is called? I can't seem to find if it is explicitly mentioned as such in the documentation, but it seems implied. I'm a little confused because of the name get_client (instead of say create_clien... | Yes. You can find this in init.py from clickhouse_connect.driver import create_client, create_async_client driver_name = 'clickhousedb' get_client = create_client get_async_client = create_async_client Permalink to the line of importance. | 2 | 2 |
79,465,328 | 2025-2-25 | https://stackoverflow.com/questions/79465328/arrays-of-size-0-in-numpy | I need to work with arrays that can have zeros in their shapes. However, I am encountering an issue. Here's an example: import numpy as np arr = np.array([[]]) assert arr.shape == (1,0) arr.reshape((1,0)) # No problem (nothing changes) arr.reshape((-1,0)) # ValueError: cannot reshape array of size 0 into shape (0) I a... | If you read the documentation: One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions. As furas says, it can't automatically calculate the remaining dimension because of undefined division by 0. Any number times 0 is 0. arr.reshape((1,0)) # Works arr.r... | 10 | 11 |
79,467,944 | 2025-2-25 | https://stackoverflow.com/questions/79467944/comparing-dataframes | The goal is to compare two pandas dataframes considering a margin of error. To reproduce the issue: Importing pandas import pandas as pd Case one - same data dataframes df1 = pd.DataFrame({"A": [1,1,1], "B": [2,2,2], "C": [3,3,3]}) df2 = pd.DataFrame({"A": [1,1,1], "B": [2,2,2], "C": [3,3,3]}) print(df1.compare(df2, r... | Depending on your ultimate goal, assert_frame_equal with the atol parameter may work. from pandas.testing import assert_frame_equal # specify dtypes for the reproducible example # otherwise assert_frame_equal flags different dtypes (int vs. float) df1 = pd.DataFrame({"A": [1,1,1], "B": [2,2,2], "C": [3,3,3]}, dtype=flo... | 2 | 2 |
79,467,071 | 2025-2-25 | https://stackoverflow.com/questions/79467071/adjacency-matrix-not-square-error-from-square-dataframe-with-networkx | I have code that aims to generate a graph from an adjacency matrix from a table correlating workers with their manager. The source is a table with two columns (Worker, manager). It still works perfectly from a small mock data set, but fails unexpectedly with the real data: import pandas as pd import networkx as nx # Re... | In: am = pd.DataFrame(0, columns=df["Worker"], index=df["Worker"]) # This way, it is impossible that the dataframe is not square, your DataFrame is indeed square, but when you later assign values in the loop, if you have a manager that is not in "Worker", this will create a new row: am.at[row["manager"], row["Worker"]... | 2 | 1 |
79,465,562 | 2025-2-25 | https://stackoverflow.com/questions/79465562/pybind11-multiple-definition-of-pyinit-module-name | Solved! - Please check the answer. I wrote a library where headers and python bindings are auto-generated. For example dummy_bind.cpp for dummy_message.h and each _bind.cpp file has PYBIND11_MODULE call in it for their specific class. There are dozens of other _bind.cpp files for other headers. What should be the modul... | I've actually solved this by generating proxy functions in _bind.cpp files. For instance, in message1_bind.cpp I've defined a function void init_message1(pyinit11::module& m) and then in main_bind.cpp I call them all inside PYBIND11_MODULE(protocol_name, m) so I only have only one PYBIND11_MODULE() call. Here's a minim... | 2 | 3 |
79,489,702 | 2025-3-6 | https://stackoverflow.com/questions/79489702/is-there-a-numpy-method-or-function-to-split-an-array-of-uint64-into-two-arrays | Say I have an array as follows: arr = np.asarray([1, 2, 3, 4294967296, 100], dtype=np.uint64) I now want two arrays, one array with the lower 32 bits of every element, and one with the upper 32 bits of every element, preferably by using views and minimizing copies, to get something like this: upper = np.array([0, 0, 0... | You can use structured arrays to split uint64 into two uint32 views without copying: # Create a structured view of the array (assuming little-endian system) view = arr.view(dtype=np.dtype([('lower', np.uint32), ('upper', np.uint32)])) # Extract views lower = view['lower'] upper = view['upper'] This creates memory view... | 5 | 10 |
79,488,683 | 2025-3-6 | https://stackoverflow.com/questions/79488683/how-to-avoid-object-has-no-attribute-isalive-error-while-debugging-in-intell | I am writing a simple project in python. My version of python is: 3.13.1 . I am using IntelliJ and Python plugin with version: 241.18034.62. I would like to debug my project but when I try to debug I am getting many errors: AttributeError: '_MainThread' object has no attribute 'isAlive'. Did you mean: 'is_alive'? bigg... | Path in error message may suggest that it is mistake in plugin, not in your code. It looks like code for Python2 which has function isAlive(). At this moment you may try to fix it. Open C:\Users\mylogin\AppData\Roaming\JetBrains\IntelliJIdea2024.1\plugins\python\helpers\pydev\_pydev_bundle\pydev_is_thread_alive.py and... | 3 | 2 |
79,497,967 | 2025-3-10 | https://stackoverflow.com/questions/79497967/is-there-a-callable-for-generating-ids-with-pytest-fixtureparam-the-same | I'm using parametrized fixtures but I don't find the way ids are generated practical. I'd like to fall back on the way it's generated when using pytest.mark.parametrize. I've seen that it's possible to provide a callable as the ids keyword argument in pytest.fixture (and it works), but I was wondering if there was alre... | The change you observe in test ids generation isn't due to the use of parametrized fixtures, but to the way pytest generates these ids depending on the parameters types: Numbers, strings, booleans and None will have their usual string representation used in the test ID. For other objects, pytest will make a string bas... | 2 | 1 |
79,483,002 | 2025-3-4 | https://stackoverflow.com/questions/79483002/numpy-ndarray-object-has-no-attribute-groupby | I am trying to apply target encoding to categorical features using the category_encoders.TargetEncoder in Python. However, I keep getting the following error: AttributeError: 'numpy.ndarray' object has no attribute 'groupby' from category_encoders import TargetEncoder from sklearn.model_selection import train_test_spl... | This is interesting. I can reproduce your error. It is related to the dtype. To solve the issue you need to force a conversion using its list values and set the name and index explicitly. y_train = pd.Series(y_train.tolist(), name='loan_status', index=y_train.index) This will convert your initial dtype of CategoricalDt... | 1 | 2 |
79,496,308 | 2025-3-9 | https://stackoverflow.com/questions/79496308/how-can-i-handle-initial-settings-with-pydantic-settings | I have an app that is largely configured by environment variables. I use Pydantic Settings to define the settings available, and validate them. I have an initial set of settings, and the regular app settings. The initial settings are ones that should not fail validation, and contain essential settings for starting the ... | The simplest solution is to use two different .env files: one for InitialSettings and one for Settings: # initial.env SENTRY_DSN=... # settings.env # your other `Settings` envs here without `SENTRY_DSN` class InitialSettings(BaseSettings): model_config = SettingsConfigDict( env_file="initial.env", env_file_encoding="... | 1 | 1 |
79,495,237 | 2025-3-9 | https://stackoverflow.com/questions/79495237/cumulative-elementwise-sum-by-python-polars | I have a weight vector: weight_vec = pl.Series("weights", [0.125, 0.0625, 0.03125]) And also a DataFrame containing up to m variables. For simplicity, we will only have two varaibles: df = pl.DataFrame( { "row_index": [0, 1, 2, 3, 4], "var1": [1, 2, 3, 4, 5], "var2": [6, 7, 8, 9, 10], } ) The size (number of observat... | Here is a solution that uses rolling. import numpy as np weight_vec_len: int = weight_vec.len() period = f"{weight_vec_len}i" df.rolling("row_index", period=period, offset=f"-1i").agg( pl.col(r"^var\d$") .extend_constant(np.nan, weight_vec_len - pl.len()) .dot(weight_vec) .fill_nan(None) .name.keep() ) shape: (5, 3) ┌... | 1 | 2 |
79,490,519 | 2025-3-6 | https://stackoverflow.com/questions/79490519/raising-error-in-function-task-parallelized-with-ray | Starting to try to use Ray to parallelize a number of task-parallel jobs. I.e. each task takes in an object from a data frame, and then returns a list. Within the function, there is a check for a property of the object though, and if that property if fulfilled I want the task to be canceled gracefully. (I know one coul... | reproducible One way to reproduce the effect with toy data would be to take sha1(i) as i ranges from zero to thirty-five thousand. Mask off some low order bits, and if result is "small" report error, else success. Using modulo on that can also be convenient. When I run it across all cores Ray reattempts failed tasks... | 2 | 0 |
79,497,191 | 2025-3-10 | https://stackoverflow.com/questions/79497191/when-using-mysql-connector-aio-how-do-we-enable-connection-pooling-assuming-it | I am trying to port my old mysql connector code to use the asyncio libraries provided by MySQL. When I tried to run it, it said it didn't recognize the pool_name and pool_size. It didn't explicitly state in the documentation that pooling is not supported. AIOMysql does support pooling. But I was also thinking, if I am ... | First, as regards to whether mysql.connector.aio supports connection pooling or not, the following is a portion of that package's connect function (Python 3.12.2): async def connect(*args: Any, **kwargs: Any) -> MySQLConnectionAbstract: """Creates or gets a MySQL connection object. In its simpliest form, `connect()` wi... | 1 | 1 |
79,499,236 | 2025-3-10 | https://stackoverflow.com/questions/79499236/deviation-in-solutions-differential-equations-using-odeint-vs-runge-kutta-4th | I am modelling a Coupled Spring-Mass-System: Two objects with masses m1 and m2, and are coupled through springs with spring constants k1 and k2, with damping d1 and d2. Method 1: taking a cookbook-script using ODEINT to solve the differential equations. # Use ODEINT to solve the differential equations defined by the ve... | As @lastchance first observed in the comments, your RK4 is not correct as it doesn't apply the method to all the four equations at the same time. I also don't understand the rationale behind the two velocity_solution equations. Here's RK4 method applied to the system of four equations. For pedagogical reasons I add it ... | 1 | 1 |
79,498,911 | 2025-3-10 | https://stackoverflow.com/questions/79498911/why-does-jaxs-grad-not-always-print-inside-the-cost-function | I am new to JAX and trying to use it with PennyLane and optax to optimize a simple quantum circuit. However, I noticed that my print statement inside the cost function does not execute in every iteration. Specifically, it prints only once at the beginning and then stops appearing. The quantum circuit itself does not ma... | When working with JAX it is important to understand the difference between "trace time" and "runtime". For JIT compilation JAX does an abstract evaluation of the function when it is called first. This is used to "trace" the computational graph of the function and then create a fully compiled replacement, which is cache... | 1 | 2 |
79,489,878 | 2025-3-6 | https://stackoverflow.com/questions/79489878/my-modal-doesnt-appear-after-an-action-in-streamlit | I have this Streamlit app: import streamlit as st st.title("Simulator") tab_names = ["tab1", "tab2"] tab1, tab2= st.tabs(tab_names) @st.dialog("Edit your relationships") def edit_relationships(result): edit_options = tuple(result) selection = st.selectbox( "Select an entity relationship", edit_options ) st.write(f"This... | It seems you need st.fragment: When a user interacts with an input widget created inside a fragment, Streamlit only reruns the fragment instead of the full app. If run_every is set, Streamlit will also rerun the fragment at the specified interval while the session is active, even if the user is not interacting with yo... | 1 | 3 |
79,499,242 | 2025-3-10 | https://stackoverflow.com/questions/79499242/how-to-check-if-a-library-is-installed-at-runtime-in-python | I want to check whether a library is installed and can be imported dynamically at runtime within an if statement to handle it properly. I've tried the following code: try: import foo print("Foo installed") except ImportError: print("Foo not installed") It works as intended but does not seem like the most elegant metho... | Use importlib.util for a clean check. import importlib.util if importlib.util.find_spec("library_name") is not None: print("Installed") | 1 | 1 |
79,499,303 | 2025-3-10 | https://stackoverflow.com/questions/79499303/confusion-on-re-assigning-pandas-columns-after-modification-with-apply | Let us assume we have this dataframe: df = pd.DataFrame.from_dict({1:{"a": 10, "b":20, "c":30}, 2:{"a":100, "b":200, "c":300}}, orient="index") Further, let us assume I want to apply a function to each row that adds 1 to the values in columns a and b def add(x): return x["a"] +1, x["b"] +1 Now, if I use the apply func... | This is your original DataFrame: a b c 1 10 20 30 2 100 200 300 Now, look at the output of df[['a', 'b']].apply(add, axis=1): df[['a', 'b']].apply(add, axis=1) 1 (11, 101) 2 (21, 201) dtype: object This creates a Series of tuples, which means you have two items (11, 101) and (21, 201), and those are objects (tuples)... | 1 | 3 |
79,496,846 | 2025-3-10 | https://stackoverflow.com/questions/79496846/how-to-use-pytest-mark-parametrize-and-include-an-item-for-the-default-mock-b | I am creating a parameterized Mock PyTest to test API behaviors. I am trying to simplify the test code by testing the instance modified behavior, e.g. throw and exception, and the default behavior, i.e. load JSON from file vs. calling REST API. I do not know how to add an array entry to represent the "default" mock beh... | As a workaround, you could deal with any api-related case inside the function, where the api is known. For this single-use, I would use None to trigger the default case @pytest.mark.parametrize( ("get_nearby_sensors_mock", "get_nearby_sensors_errors"), [ # [...] (None, {}), ], ) async def test_validate_coordinates( has... | 2 | 0 |
79,498,590 | 2025-3-10 | https://stackoverflow.com/questions/79498590/is-there-a-way-to-vertically-merge-two-polars-lazyframes-in-python | I want to vertically merge two polars.LazyFrames in order to avoid collecting both LazyFrames beforehand, which is computationally expensive. I have tried extend(), concat(), and vstack() but none of them are implemented for LazyFrames. Maybe I am missing the point about LazyFrames by trying to perform this operation, ... | pl.concat can be used with LazyFrames: >>> lf = pl.LazyFrame({"x": [1, 2]}) >>> pl.concat([lf, lf]).collect() shape: (4, 1) ┌─────┐ │ x │ │ --- │ │ i64 │ ╞═════╡ │ 1 │ │ 2 │ │ 1 │ │ 2 │ └─────┘ | 2 | 8 |
79,497,914 | 2025-3-10 | https://stackoverflow.com/questions/79497914/how-do-conditional-expressions-group-from-right-to-left | I checked python operator precedence (This one grammar is more detailed and more appropriate for the actual Python implementation) Operators in the same box group left to right (except for exponentiation and conditional expressions, which group from right to left). ** Exponentiation [5] if – else Conditional expressio... | a if b else c if d else e means a if b else (c if d else e) and not (a if b else c) if d else e | 1 | 2 |
79,497,724 | 2025-3-10 | https://stackoverflow.com/questions/79497724/index-pandas-with-multiple-boolean-arrays | Using numpy, one can subset an array with one boolean array per dimension like: In [10]: aa = np.array(range(9)).reshape(-1, 3) In [11]: aa Out[11]: array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) In [12]: conditions = (np.array([True, True, False]), np.array([True, False, True])) In [13]: aa[np.ix_(*conditions)] Out[13]: arr... | You should be able to directly use boolean indexing with iloc (or loc): df = pd.DataFrame(aa) out = df.iloc[conditions] Note that conditions should be a tuple of arrays/lists/iterables, if not you should convert it: out = df.iloc[tuple(conditions)] Output: 0 2 0 0 2 1 3 5 | 2 | 3 |
79,497,570 | 2025-3-10 | https://stackoverflow.com/questions/79497570/mean-value-with-special-dependency | I have a DataFrame that looks something like this: C1 C2 10 10 20 10 30 16 5 23 6 23 8 10 4 10 2 10 I would like to calculate the mean value in column C1 depending on the values in column C2. The mean value is to be calculated over all values in column C1 until the value in column C2 changes aga... | Use GroupBy.mean by consecutive values created by compared Series.shifted values with Series.cumsum, last remove first level and get original order of columns by DataFrame.reindex: out =(df.groupby([df['C2'].ne(df['C2'].shift()).cumsum(),'C2'],sort=False)['C1'] .mean() .droplevel(0) .reset_index() .reindex(df.columns, ... | 1 | 2 |
79,496,711 | 2025-3-9 | https://stackoverflow.com/questions/79496711/opencv-understanding-the-filterbyarea-parameter-used-in-simpleblobdetector | I am trying to detect a large stain using OpenCV's SimpleBlobDetector following this SO answer. Here is the input image: I first tried working with params.filterByArea = False, which allowed to detect the large black stain: However, smaller spots also ended up being detected. I therefore toggled params.filterByArea =... | opencv maxArea param has 5000 as default value. Increasing it could detect blobs bigger than that import cv2 import numpy as np def show_keypoints(im, keypoints): im_key = cv2.drawKeypoints(im, keypoints, np.array([]), (0, 0, 255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS) cv2.imshow("Keypoints", im_key) cv2.waitKey(... | 2 | 4 |
79,496,136 | 2025-3-9 | https://stackoverflow.com/questions/79496136/plotting-vertical-lines-on-pandas-line-plot-with-multiindex-x-axis | I have a dataframe whose index is a multiindex where axes[0] is the date, and axis[1] is the rank. Rank starts with 1 and ends at 100, but there can be a variable number of ranks in between as below. Here are the ranks dx = pd.DataFrame({ "date": [ pd.to_datetime('2025-02-24'), pd.to_datetime('2025-02-24'), pd.to_datet... | With a categorical axis, plt will use an integer index "under the hood". Here, since you are using a lineplot, it tries to come up with a reasonable step: dx.plot(ax=axes[0]) axes[0].get_xticks() # array([-2., 0., 2., 4., 6., 8., 10., 12.]) With a barplot, you would get the more logical: dx.plot.bar(ax=axes[0]) axes[0... | 1 | 1 |
79,487,849 | 2025-3-5 | https://stackoverflow.com/questions/79487849/expanding-numpy-based-code-that-detect-the-frequency-of-the-consecutive-number-t | This stackoverflow answer provides a simple way (below) to find the frequency and indices of consecutive repeated numbers. This solution is much faster than loop-based code (see the original post above). boundaries = np.where(np.diff(aa) != 0)[0] + 1 #group boundaries get_idx_freqs = lambda i, d: (np.concatenate(([0], ... | A possible solution (on my computer, it runs instantaneously): # data = np.load('tmp2.npz') # tmp2 = data['arr_0'] def get_freqs(aa): boundaries = np.where(np.diff(aa) != 0)[0] + 1 edges = np.r_[0, boundaries, len(aa)] group_lengths = np.diff(edges) valid = group_lengths >= 2 idx = np.concatenate(([0], boundaries))[val... | 2 | 2 |
79,496,092 | 2025-3-9 | https://stackoverflow.com/questions/79496092/pythons-predicate-composition | I would like to implement something similar to this OCaml in Python: let example = fun v opt_n -> let fltr = fun i -> i mod 2 = 0 in let fltr = match opt_n with | None -> fltr | Some n -> fun i -> (i mod n = 0 && fltr n) in fltr v This is easily composable/extendable, I can add as many predicates as I want at runtime.... | When you write fltr = lambda i: fltr(i) and i % opt_n == 0 fltr remains a free variable inside the lambda expression, and will be looked up when the function is called; it's not bound to the old definition of fltr in place when you evaluate the lambda expression. You need some way to do early binding; one option is to... | 1 | 3 |
79,496,102 | 2025-3-9 | https://stackoverflow.com/questions/79496102/sqlalchemy-use-in-to-select-pairwise-correspondence | Consider the following DB: from sqlalchemy import String, select, create_engine from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, Session class Base(DeclarativeBase): pass class User(Base): __tablename__ = "user_account" name: Mapped[str] = mapped_column(String(30)) surname: Mapped[str] = mapped_column... | You need to use more explicit OR Boolean condition sqlalchemy.or_(conditions) ensures that each (name, surname) pair is checked explicitly. from sqlalchemy import or_ with Session(engine) as session: stmt = select(User).where( or_(*[(User.name == name) & (User.surname == surname) for name, surname in users]) ) print(se... | 1 | 4 |
79,495,685 | 2025-3-9 | https://stackoverflow.com/questions/79495685/gpg-import-keys-is-not-working-in-python-virtual-environment | I'm running this piece of code to encrypt a file using PGP public key. import gnupg def pgp_encrypt(pub_file, out_file): gpg = gnupg.GPG() with open(pub_file, 'rb') as pgp_pub_key: public_key_data = pgp_pub_key.read() # import_keys_file() is NOT used as the key # eventually will come from user-input import_result = gpg... | How did you create the virtual environment? Did you activate it once it is created? Sometimes, we can miss activating the environment and installing the necessary dependencies on it. I personally use uv for creating and managing virtual environments: $ uv venv $ source .venv/bin/activate $ (venv) pip install python-gnu... | 1 | 2 |
79,495,573 | 2025-3-9 | https://stackoverflow.com/questions/79495573/how-to-change-the-bluetooth-name-of-the-raspberry-pico-2w | Currently, I want to change the Name of the Pico 2W device displayed on the nRF Connect app. I am using Micro Pico in VsCode. I tried many things but the Name is always "N/A". import bluetooth from time import sleep bluetooth.BLE().active(True) ble = bluetooth.BLE() device_name = 'PicoW_Device' advertising_data = b'\x0... | The problem is how you constructed the advertising_data. Try this device_name = 'PicoW_Device' advertising_data = bytearray() advertising_data += b'\x02\x01\x06' # Flags advertising_data += bytearray([1 + len(device_name), 0x09]) # Name length and Complete Local Name AD type advertising_data += device_name.encode('utf-... | 1 | 1 |
79,495,506 | 2025-3-9 | https://stackoverflow.com/questions/79495506/how-can-users-modify-cart-prices-using-burp-suite-and-why-is-this-a-security-ri | I recently discovered a serious security issue in Django e-commerce websites where users can modify product prices before adding items to the cart. Many developers allow users to send price data from the frontend, which can be easily tampered with using Burp Suite or browser developer tools. Example of the Issue: Cons... | What are the best practices to prevent this? You don't need the price, the view should add the product_id to the cart, and perhaps a quantity, but adding something to the cart has no price involved. It even makes it more complicated to later apply discounts, since the price is determined per product. Should e-commer... | 2 | 2 |
79,495,020 | 2025-3-8 | https://stackoverflow.com/questions/79495020/how-do-i-get-past-this-error-in-installing-pyautogui-as-a-third-party-module-in | I am on the final chapter of Automate the Boring Stuff with Python- Chapter 20 begins by installing and importing pyautogui, and I have been unable to accomplish this. I HAVE been able to install the module on my Mac I have NOT been able to add this as a Third Party Module in Mu Editor. Here is the error I get when I t... | Reasons According to the docs Mu Editor supports only versions from 3.5 to 3.8. That is issue exists since 2021 and hasn't been resolved since. You might have a newer version installed, but the Mu Editor has its own environment with its own Python interpreter. I've just successfully installed pyautogui on python3.7, ... | 1 | 1 |
79,492,385 | 2025-3-7 | https://stackoverflow.com/questions/79492385/asyncio-pass-context-or-contextvar-to-add-done-callback | I am learning asyncio callbacks. My task is- I have a message dict, message codes are keys, message texts are values. In coro main I have to create a number of asynchronous tasks (in my case 3 tasks), each task wraps a coro which prints one message. Also I have to add a callback to each task. Callback must print a code... | No tricks are needed, just specify the context. async def main(): tasks = [] for code in msg_dict: ctx = copy_context() # note: import copy_context from contexvars task = asyncio.create_task(print_msg(code), context=ctx) task.add_done_callback(callback_code, context=ctx) tasks.append(task) await asyncio.gather(*tasks) | 1 | 0 |
79,494,971 | 2025-3-8 | https://stackoverflow.com/questions/79494971/issue-with-transparency-mask-in-moviepy-v2-works-in-v1 | I'm facing an issue while migrating from MoviePy v1 to MoviePy v2. In v1, I could apply a transparency mask to an ImageClip, making certain areas of the clip transparent. However, in MoviePy v2, the same approach doesn't seem to work. Expected Behavior The ImageClip should become transparent in areas defined by the mas... | Turns out it works when I use RGBA image instead of greyscale image for the mask. Even though MoviePy docs explicitly mention that mask should always be greyscale image, but it seems to work with RGBA images only. | 2 | 2 |
79,492,814 | 2025-3-7 | https://stackoverflow.com/questions/79492814/failed-to-parse-the-total-results-from-a-webpage-of-which-my-existing-script-ca | I've created a script that issues a POST HTTP request with the appropriate parameters to fetch the town, continent, country, and inner_link from this webpage. The script can parse 69 containers, but there are 162 items in total. How can I fetch the rest? import requests link = 'https://wenomad.so/elasticsearch/search' ... | You need to replicate the requests to the /elasticsearch/search endpoint which requires three params x, y and z. These params are generated through a cryptographic encryption in the encode3 function of run.js First install PyCryptodome: pip install pycryptodome Then you can use this script to get all (162) results: fr... | 1 | 4 |
79,494,272 | 2025-3-8 | https://stackoverflow.com/questions/79494272/pass-value-from-one-django-template-to-other | I want to build a Django template hierarchy like so: root.html |_ root-dashboard.html |_ root-regular.html root.html shall have an if statement: {% if style == "dashboard" %} {# render some elements in a certain way #} {% else %} {# render those elements in a different way #} {% endif %} And root-dashboard.html and ... | Define a {% block … %} template tag [Django-doc] instead. In root.html, you don't use an if, but: {% block render_item %} {# render those elements in a different way #} {% endblock %} then in your root-dashboard.html, you use: # root-dashboard.html {% extend 'root.html' %} {% block render_item %} {# render some elemen... | 1 | 1 |
79,492,317 | 2025-3-7 | https://stackoverflow.com/questions/79492317/fill-gaps-in-time-series-data-in-a-polars-lazy-dataframe | I am in a situation where I have some time series data, potentially looking like this: { "t": [1, 2, 5, 6, 7], "y": [1, 1, 1, 1, 1], } As you can see, the time stamp jumps from 2 to 5. For my analysis, I would like to fill in zeros for the time stamps 3, and 4. In reality, I might have multiple gaps with varying lengt... | I think your approach is sensible, there's just no need for an intermediate collect: lf.join( lf.select(pl.int_range(pl.col.t.first(), pl.col.t.last()+1)), on="t", how="right" ) .fill_null(0) An alternate approach that might be a bit more efficient is to use an asof-join with no tolerance: lf.select(pl.int_range(pl.co... | 2 | 3 |
79,494,025 | 2025-3-8 | https://stackoverflow.com/questions/79494025/after-scraping-data-from-website-and-converting-csv-excel-dont-show-rows-excep | url ="https://www.dsebd.org/top_20_share.php" r =requests.get(url) soup = BeautifulSoup(r.text,"lxml") table = soup.find("table",class_="table table-bordered background-white shares-table") top = table.find_all("th") header = [] for x in top: ele = x.text header.append(ele) df = pd.DataFrame(columns= header) print(df) ... | The script itself works and CSV can be easily imported into Excel. Alternatively, export the data directly .to_excel('your_excle_file.xlsx') and open it in Excel. Since you are already operating with pandas, just use pandas.read_html which BeautifulSoup uses in the background to scrape the tables. import pandas as pd ... | 1 | 2 |
79,491,259 | 2025-3-7 | https://stackoverflow.com/questions/79491259/why-is-a-line-read-from-a-file-not-to-its-hardcoded-string-despite-being-prin | I'm reading lines from a file and trying to match them with regex, but it's failing despite the regex matcher looking right. When comparing the line to what it should be as a string declaration, python is saying that they are not equal. It's looking like this is being caused by a non utf-8 encoding on my file but not s... | The pattern of nulls in the output says that this file is encoded in big-endian UTF-16. Open it with encoding='utf-16be'. You might also want to figure out why Maven is producing output in UTF-16. | 2 | 6 |
79,485,215 | 2025-3-5 | https://stackoverflow.com/questions/79485215/sir-parameter-estimation-with-gradient-descent-and-autograd | I am trying to apply a very simple parameter estimation of a SIR model using a gradient descent algorithm. I am using the package autograd since the audience (this is for a sort of workshop for undergraduate students) only knows numpy and I don't want to jump to JAX or any other ML framework (yet). import autograd impo... | This is a modified version of your code that seems to work import autograd import autograd.numpy as np import matplotlib.pyplot as plt from autograd.scipy.integrate import odeint from autograd.builtins import tuple from autograd import grad, jacobian def sir(y, t, beta, gamma): S, I, R = y dS_dt = - beta * S * I dI_dt ... | 2 | 1 |
79,492,863 | 2025-3-7 | https://stackoverflow.com/questions/79492863/barplot-coloring-using-seaborn-color-palette | I have the following code fragment: import seaborn import matplotlib.pyplot as plt plt.bar(df['Col1'], df['Col2'], width = 0.97, color=seaborn.color_palette("coolwarm", df['Col1'].shape[0], 0.999)) Now, my bars are colored in the blue-red spectrum (as given by the parameter coolwarm). How can I change the distribution... | There's no built in way to do this using seaborn or the matplotlib colormaps, but here's a solution that seems to do the trick import seaborn as sns import matplotlib.pyplot as plt import pandas as pd import numpy as np ## function that generates a color palette def gen_palette(n_left, n_right, cmap_name="coolwarm", de... | 1 | 3 |
79,492,887 | 2025-3-7 | https://stackoverflow.com/questions/79492887/request-method-post-equaling-true-in-next-function-causing-it-to-run-prematur | so i am running this code def login_or_join(request): if request.method == "POST": option = request.POST.get("option") print('post request recieved') if option == "1": return login_screen(request) if option == '2': return in_game(request) return render(request,"login_or_join.html") and def login_screen() looks like th... | I guess the problem is that you are calling login_screen with request as parameter. But that variable is the parameter received on login_or_join so is the POST request with the option, neither a GET nor a POST with the username and password. I think in this case you can just name the url and do: if option == "1": retur... | 2 | 2 |
79,492,367 | 2025-3-7 | https://stackoverflow.com/questions/79492367/can-airflow-task-dependencies-be-re-used | I have a series of airflow DAGs which re-use some of the task dependencies. For example DAG 1: T1 >> T2 DAG 2: T1 >> T2 >> T3 DAG 3: T1 >> T2 >> T3 >> [T4, T5, T6] >> T7 I would like to store the dependencies from DAG 1 (which in this model, are being used by every other DAG) and re-use them when declaring the depende... | If tasks t1 and t2 are always the same tasks, you can generate these tasks + dependencies outside the DAG. To add additional tasks/dependencies following t2, you need a reference to that object to configure the additional dependencies. For example: def generate_t1_t2() -> BaseOperator: """Generates tasks + dependencies... | 1 | 1 |
79,491,894 | 2025-3-7 | https://stackoverflow.com/questions/79491894/vespa-indexing-anomaly-on-exact-indexed-field-with-diacritical-variants-and-no | I’m using the Vespa Python client (pyvespa 0.54.0) to query a Vespa index, and I’m running into an issue where Vespa doesn't find a document it has just returned in a previous query. I have this field in my toponym schema, indexed with match { exact }: field name_strict type string { indexing: attribute | summary match... | You're in luck, this is a case-folding problem that's been fixed recently. I could reproduce your problem on vespa 8.485.42 but it works as expected in 8.492.15. | 2 | 6 |
79,492,024 | 2025-3-7 | https://stackoverflow.com/questions/79492024/the-server-responded-with-a-status-of-500-internal-server-error-and-valueerror | I am trying to make dashboard in flask by connecting it with SQL server and getting these errors. I confirm there are no null values and I checked by removing the column as well from query but still not working. Code is - import pandas as pd import pyodbc from flask import Flask, render_template, jsonify app = Flask(__... | Add this line so that if there are NaT values in the 'TicketDate' column, it converts to None rather than throwing an error. df['TicketDate'] = df['TicketDate'].fillna(pd.NaT).apply( lambda x: x.strftime('%Y-%m-%d') if pd.notna(x) else None ) | 1 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.