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,526,465 | 2025-3-21 | https://stackoverflow.com/questions/79526465/is-there-a-way-to-remove-stack-traces-in-python-log-handlers-using-filters-or-so | I know the subject sounds counter-intuitive but bear with me. My goal is to have two rotating file log handlers, mostly for logger.exception() calls, one that includes stack traces and one that doesn't. I find that error conditions can sometimes cause the logs to fill with stack traces, making them difficult to read/pa... | You can use a custom Formatter that removes the exception info necessary to the logging of the stack trace. See the source code of the format method of the Formatter. You can see that since record.exc_info, record.exc_text and record.stack_info are set to None, no stack trace can be shown. import logging logger = loggi... | 1 | 1 |
79,526,873 | 2025-3-22 | https://stackoverflow.com/questions/79526873/conda-environment-does-not-isolate-each-environment | I am trying to install some packages upon newly created conda environment. But weirdly it is already full of packages, which have been used in other previous conda environments. For example, I noticed var conda environment already share the packages with other environments although I never asked to - I used conda creat... | How about in your Python session you try to make visible all environment variables relevant for your Python sessions by: import os for name, value in os.environ.items(): print("{0}: {1}".format(name, value)) first? when I was working with HPC (high performance clusters), when Python was behaving strangely - like loadi... | 1 | 1 |
79,526,834 | 2025-3-22 | https://stackoverflow.com/questions/79526834/for-a-custom-mapping-class-that-returns-self-as-iterator-list-returns-empty | The following is a simplified version of what I am trying to do (the actual implementation has a number of nuances): from __future__ import annotations from collections.abc import MutableMapping class SideDict(MutableMapping, dict): """ The purpose of this special dict is to side-attach another dict. A key and its valu... | The problem is that your object is its own iterator. Most objects should not be their own iterator - it only makes sense to do that if the object's only job is to be an iterator, or if there's some other inherent reason you shouldn't be able to perform two independent loops over the same object. Most iterable objects s... | 1 | 4 |
79,526,348 | 2025-3-21 | https://stackoverflow.com/questions/79526348/matplotlib-unable-to-update-plot-with-button-widget | The code below draws a button and an axes object in which it's meant to print out the number of times the button has been pressed. However, it never updates the axes with the number of presses. from matplotlib import pyplot as plt from matplotlib.widgets import Button fig, ax = plt.subplots(figsize=(7,7)) ax.set_visibl... | change : def button_fx(self, event): ax_str.clear() self.N_presses += 1 text_out = "Pushed {} times".format(self.N_presses) ax_str.text(0.5, 0.5, text_out) print(text_out) to def button_fx(self, event): ax_str.clear() self.N_presses += 1 text_out = "Pushed {} times".format(self.N_presses) ax_str.text(0.5, 0.5, text_ou... | 2 | 1 |
79,526,398 | 2025-3-21 | https://stackoverflow.com/questions/79526398/pandas-group-by-without-performing-aggregation | I have a pandas dataframe as follows: Athlete ID City No. of Sport Fields 1231 LA 81 4231 NYC 80 2234 NJ 64 1223 SF 75 4531 LA 81 2345 NYC. 80 ... I want to print the City and No. of Sport Fields columns and group by City and sort by No. of Sport Fields. groupby() won't work here because I am no... | In your example, it seems that the No. of Sports Field remains the same for a given City. You can therefore use first() upon grouping by City, before sorting by No. of Sports Field : df.groupby('City').first().sort_values(by='No. of Sport Fields') This returns: Athlete ID No. of Sport Fields City NJ 2234 64 SF 1223 75... | 2 | 1 |
79,526,103 | 2025-3-21 | https://stackoverflow.com/questions/79526103/converting-rsa-generated-modulus-n-to-base64-string | I have a "modulus" as a long string of numbers that is obtained from doing the following: private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048) modulus = private_key.private_numbers().public_numbers.n which gives me this (modulus = ) 26430269838726291280672963883929276522234428127706081469034773... | Since you already have the modulus as a decimal number, you only have to convert it to a hexadecimal number (with int.to_bytes()) and then Base64url encode it (with base64.urlsafe_b64encode()). The Base64 padding can be removed with rstrip(), e.g.: import base64 n = 26430269838726291280672963883929276522234428127706081... | 1 | 3 |
79,525,857 | 2025-3-21 | https://stackoverflow.com/questions/79525857/offset-in-using-trapezoid-method-for-numerical-integration | I am using the trapezoidal method to integrate the squared modulus of this Gaussian function: In fact, the squared modulus of this function can be integrated analytically, resulting in: When I try to solve the integral both analytically and numerically, I get the following result (I simplify by setting ( t_0 = 0 ) an... | In fact, the squared modulus of this function can be integrated analytically, resulting in: It's that plus C. When you take the indefinite integral of this, you get that value, plus some arbitrary constant. If you want to use this indefinite integral / antiderivative to find the definite integral, you need to evaluat... | 2 | 3 |
79,519,529 | 2025-3-19 | https://stackoverflow.com/questions/79519529/how-to-run-julia-in-a-docker-container-in-linux-or-macos-e-g-for-running-wflow | Docker Container for Flask App with Julia-based Wflow: Package Not Found Error I want to make a docker container of my Flask App. I am running an open-source hydrological model called 'Wflow' (see github) inside my flask app. The Wflow runs with Julia command. Running Wflow inside Flask: julia_process = subprocess.Pope... | Create and save content of the Dockerfile. mkdir -p julia-wflow cd julia-wflow nano Dockerfile and enter and save this content in the Dockerfile: # Force Ubuntu x86-64 (amd64) even on Apple Silicon # The docker build and run commands contain enforcing information # of amd64 architecture # in ubuntu - you don't need to... | 2 | 3 |
79,524,581 | 2025-3-21 | https://stackoverflow.com/questions/79524581/what-is-the-good-practice-to-add-many-similar-methods-to-a-class-in-python | Let's say I have a class like this. from scipy import interpolate import numpy as np class Bar: def __init__(self,data): self.data = data def mean(self): return self.data.mean(axis=0) def sd(self): return self.data.std(axis=0) bar = Bar(np.random.rand(10,5)) print(bar.mean()) print(bar.sd()) The class Bar may have man... | One DRYer approach that avoids repeating method names for the sampled versions is to make the decorator a custom descriptor whose __get__ method returns an object that calls the decorated function when called, but also provides a sample method that calls the decorated function with the sampling logics around it: class ... | 2 | 1 |
79,524,534 | 2025-3-21 | https://stackoverflow.com/questions/79524534/typeerror-cannot-determine-truth-value-of-relational-when-entering-symbolic-val | I heard the issue comes when trying to compare symbolic values, for example if i enter e^(8*x) as the initial function in the code, so I've tried evalf() with the values to turn them into numeric, but they continue to be symbolic. What else could i do? import math import sympy as sp print("Fixed Point Method") funini =... | Sympy thinks that e is another variable. Try passing it exp(8*x) instead. Also, you have a couple of lines where you do something.evalf() but don't save it to a variable. Those lines aren't doing anything. | 1 | 1 |
79,523,479 | 2025-3-20 | https://stackoverflow.com/questions/79523479/python-class-that-does-integer-operations-mod-n | I am trying to create a Python class that does operations mod n. For example using mod 100: 11*11==21 66+39==5 1+2+3-30==73 2**10==24 This is how I am doing it: class ModInteger: def __init__(self, value, mod): self.mod = mod self.value = value % mod def __add__(self, other): return ModInteger((self.value + other.valu... | A more generic approach would be to build ModInteger with a metaclass that creates wrapper methods around relevant int methods. To allow compatibility with both int and ModInteger objects the wrapper methods should convert arguments of ModInteger objects into int objects before passing them to int methods, and convert ... | 2 | 1 |
79,524,057 | 2025-3-20 | https://stackoverflow.com/questions/79524057/replace-values-in-series-with-first-regex-group-if-found-if-not-leave-nan | Say I have a dataframe such as df = pd.DataFrame(data = {'col1': [1,np.nan, '>3', 'NA'], 'col2':["3.","<5.0",np.nan, 'NA']}) out: col1 col2 0 1 3. 1 NaN <5.0 2 >3 NaN 3 NA NA What I would like is to strip stuff like "<" or ">", and get to floats only out: col1 col2 0 1 3. 1 NaN 5.0 2 3 NaN 3 NaN NaN I thought about ... | This should work. Logic: First match, but do not include in the capture group \1, anything we do not want to keep at the beginning of the number with the negated character class [^...]. Python (re module flavor regex): pattern = "^[^\w+-\.]*([+-]?\d*\.?\d*)" replacement = \1 Regex Demo: https://regex101.com/r/Halz4X/2... | 6 | 3 |
79,523,736 | 2025-3-20 | https://stackoverflow.com/questions/79523736/return-value-of-np-polynomial-polynomial-fit-when-full-true | In the NumPy module, when you call np.polynomial.Polynomial.fit with full=True and you look at the residuals value that's returned you get an object of type array. If this value is always a single number, why is it returned as an array? | Because, what Polynomial.fit basically does, is calling lstsq. See an artificial example import numpy as np x=np.linspace(-1,1,11,1) # I choose this range because I am lazy: then I know that there is no conversion needed to get the returned coefficient y=12+x+3*x**2+0.5*x**3 np.polynomial.polynomial.Polynomial.fit(x,y,... | 2 | 2 |
79,523,249 | 2025-3-20 | https://stackoverflow.com/questions/79523249/multi-processing-copy-on-write-4-workers-but-only-double-the-size | I'm running an experiment on copy-on-write mechanism on Python Multiprocessing. I created a large file of 10GB and load the file into large_object in main. file_path = 'dummy_large_file.bin' try: large_object = load_large_object(file_path) print("File loaded successfully") except ValueError as e: print(e) except Except... | linux knows nothing about python or how big its objects are. the computer divides memory into pages, a memory page is a contiguous block of memory, linux uses 4KB memory pages on most systems, that's the "unit" of memory that could get duplicated with COW when you write to it, if you modify a single byte then the entir... | 1 | 2 |
79,522,011 | 2025-3-20 | https://stackoverflow.com/questions/79522011/python-pil-image-text-overlay-not-displayed-with-expected-color-on-white-backgro | Python PIL Image not working properly with overlay text image. I am trying to use FPDF image to convert an overlayed text png image to pdf file. However, the overlay text is not in expected colour (looks transparent) on a white background image. However, the same logic works in a zebra pattern background image. Source ... | The reason you are not seeing the text correctly on the RGBA is that you did not define the colors correctly. The text() method's parameter fill expects an integer-valued tuple, so (0,0,0,1) would result in a nearly transparent color (0=fully transparent, 255=fully opaque). Try again with font_color_bgra = (0,0,0,255) ... | 1 | 2 |
79,520,985 | 2025-3-19 | https://stackoverflow.com/questions/79520985/how-to-simplify-the-generation-process-of-these-boolean-images | I have written code that generates Thue-Morse sequence, its output is a NumPy 2D array containing only 0s and 1s, the height of the array is 2n and the width is n. More specifically, each intermediate result is kept as a column in the final output, with the elements repeated so that every column is of the same length. ... | Think in shaders. First, have a function that decides the bit in the sequence. @nb.njit def thue_morse(level: int, alpha: float) -> bool: assert level >= 0 assert 0 <= alpha < 1 value = False while level > 0: level -= 1 if alpha < 0.5: alpha *= 2 else: alpha = alpha * 2 - 1 value = not value return value You can test ... | 2 | 4 |
79,520,670 | 2025-3-19 | https://stackoverflow.com/questions/79520670/multithreading-python-jobs-to-shared-state | I think I'm lacking the understanding on multithreading in Python and the answers online are hurting my feeble brain. I want to use multithreading to write json data to a list as it works. I have the below, the some_function function is a function that takes a dictionary runs a different (basic) web scraper, that retur... | As been pointed out by Arthur Belanger your code is using multiprocessing and not multithreading. If you want to be using multithreading, then you can do so with minimal changes. Instead of: from multiprocessing import Pool Do either: from multiprocessing.dummy import Pool # multithreading or: from multiprocessing.po... | 1 | 1 |
79,521,498 | 2025-3-19 | https://stackoverflow.com/questions/79521498/how-does-a-palette-work-in-python-imaging-library | Suppose I have an RGB888 image (= 8 bit per color) in which the color of each pixel evenly encodes a (raw) data byte. Scheme: Channel red encodes Bit 7:6 (R: 0-63 = 0b00, 64-127 = 0b01, 128-191 = 0b10, 192-255 = 0b11) Channel green encodes Bit 5:3 (G: 0-31 = 0b000, 32-63 = 0b001, 64-95 = 0b010, 96-127 = 0b011, ...) Cha... | I think your question maybe means something different altogether. I think you want to convert ranges of numbers into small integers, i.e. 0-31 becomes 0, 32-63 becomes one. So you just need to shift your values to the right and you will lose the less significant bits. If your image is this: import numpy as np array([10... | 1 | 1 |
79,522,783 | 2025-3-20 | https://stackoverflow.com/questions/79522783/nonexistenttime-error-caused-by-pandas-timestamp-floor-with-localised-timestamp | I need to calculate the floor of a localized timestamp with daily resolution, but I get an exception when the daylight saving time starts. >>> pd.Timestamp('2024-09-08 12:00:00-0300', tz='America/Santiago').floor("D") NonExistentTimeError: 2024-09-08 00:00:00 I understand that midnight does not exist on that day, cloc... | By default a non-existent time will raise an error. There is an nonexistent option in Timestamp.floor to shift the time forward/backward: (pd.Timestamp('2024-09-08 12:00:00-0300', tz='America/Santiago') .floor('D', nonexistent='shift_backward') ) # Timestamp('2024-09-07 23:59:59-0400', tz='America/Santiago') (pd.Timest... | 2 | 2 |
79,521,805 | 2025-3-20 | https://stackoverflow.com/questions/79521805/shiftenter-inserts-extra-indents | I have a Python source file with some dummy code: a = 3 if a == 1: print("a = 1") elif a == 2: print("a = 2") else: print("Other") When I submit the code to terminal with shift+enter, I get the following error. It looks like VS Code changed the indentation of my code. The same code ran just fine with shift+enter on my... | bug: Python3.13 All functions fail to send: IndentationError: unexpected indent Use python 3.12 | 3 | 1 |
79,516,939 | 2025-3-18 | https://stackoverflow.com/questions/79516939/triton-strange-error-with-matrix-multiplication | I have 2 matrices P and V and when I take their dot product with triton I get results that are inconsistent with pytorch. The P and V matrices are as follows. P is basically the softmax which is why it is mostly 0s except the final column, the result of the dot product should be the final row of V. P = torch.zeros((32,... | The problem has been solved (thanks to dai on discord). The issue is input_precision is tf32 by default for dot product, which has 10bits mantissa - leading to trailing digit loss. The problem was very pronounced with V = torch.arange(4096, 4096 + 2048, device = 'cuda', dtype = torch.float32), where the output was [608... | 1 | 1 |
79,521,249 | 2025-3-19 | https://stackoverflow.com/questions/79521249/advice-on-using-wagtail-e-g-richtextfield-with-pylance-type-checking | Nearly all my Wagtail models files are full of errors according to Pylance and I'm not sure how to silence them without either adding # type: ignore to hundreds of lines or turning off Pylance rules that help catch genuine bugs. The errors often come from RichTextField properties on my models. Here is a simple example:... | You're hitting a deficiency in pylance: the heuristic doesn't apply in your case and causes troubles. I don't have anything powered by pylance available to investigate this, but you may try with a smaller snippet to check if pylance thinks that def __init__(*args, **kwargs) on a subclass means "use same arguments as pa... | 1 | 1 |
79,519,890 | 2025-3-19 | https://stackoverflow.com/questions/79519890/how-can-i-place-the-icon-after-the-text-of-a-qpushbutton-in-pyqt5 | How can I place the icon after the text of a QPushButton in PyQt5? The icon should not come before the text - it should come after or below the text. Currently it's looking like this: but it should be like this: Track ⨁ from PyQt5.QtWidgets import QApplication, QPushButton, QWidget, QVBoxLayout from PyQt5.QtGui import... | The simplest option is to change the direction of the button layout: btn_add_track.setLayoutDirection(Qt.LayoutDirection.RightToLeft) Unlike the other solution, this will maintain the appearance of the original button such as centering the icon text and text relative to the button (this can also be done with the other... | 1 | 1 |
79,518,603 | 2025-3-18 | https://stackoverflow.com/questions/79518603/how-to-populate-a-2-d-numpy-array-with-values-from-a-third-dimension | New Post: Processing satellite conjunctions with numpy efficiently Original Post: I have a numpy array of shape n x m x r, where the n axis represents an object, the m axis represents a timestep and the r axis represents a position vector in 3-d space. I have an array containing three (x, y and z position values) of m ... | "I'm struggling to find a way to do this efficiently - I can do it with bog standard python loops, but as I scale up the number of objects and timesteps this becomes massively inefficient." What you want to do makes no sense in numpy. Unless using an object dtype, there is no way to have anything else than numeric data... | 1 | 1 |
79,519,830 | 2025-3-19 | https://stackoverflow.com/questions/79519830/what-is-the-best-way-to-get-the-last-non-zero-value-in-a-window-of-n-rows | This is my dataframe: df = pd.DataFrame({ 'a': [0, 0, 1, -1, -1, 0, 0, 0, 0, 0, -1, 0, 0, 1, 0] }) Expected output is creating column b: a b 0 0 0 1 0 0 2 1 0 3 -1 1 4 -1 -1 5 0 -1 6 0 -1 7 0 -1 8 0 0 9 0 0 10 -1 0 11 0 -1 12 0 -1 13 1 -1 14 0 1 Logic: I explain the logic by some examples: I want to create column b ... | I don't think there is a much more straightforward approach. There is currently no rolling.last method. You could however simplify a bit your code: def last_nonzero(s): return 0 if (x:=s[s != 0]).empty else x.iloc[-1] df['b'] = (df['a'].shift(1, fill_value=0) .rolling(window=3, min_periods=1).apply(last_nonzero) .conve... | 3 | 4 |
79,519,395 | 2025-3-19 | https://stackoverflow.com/questions/79519395/how-to-skip-if-starts-with-but-match-other-strings | I want to match and substitute for strings as shown in the example below, but not for some strings which start with test or !!. I have used negative lookahead to skip matching unwanted strings but (Street|,)(?=\d) matching for Street & comma replacing group 1 with UK/ is not working as expected. import re input = [ 'St... | You could change the pattern to use 2 capture groups, and then use a callback with re.sub. The callback checks if there is a group 1 value. If there is, use it in the replacement, else use group 2 followed by UK/ ^((?:!!|test)\s.*)|(Street|,)(?=\d) The regex matches ^((?:!!|test)\s.*) Capture either !! or test at the... | 7 | 5 |
79,518,999 | 2025-3-19 | https://stackoverflow.com/questions/79518999/why-stdskipna-false-and-stdskipna-true-yield-different-results-even-when-the | I have a pandas Series s, and when I call s.std(skipna=True) and s.std(skipna=False) I get different results even when there are no NaN/null values in s, why? Did I misunderstand the skipna parameter? I'm using pandas 1.3.4 import pandas as pd s = pd.Series([10.0]*4800000, index=range(4800000), dtype="float32") # No Na... | This is an issue with the Bottleneck optional dependency, used to accelerate some NaN-related routines. I think the wrong result happens due to loss of precision while calculating the mean, since Bottleneck uses naive summation, while NumPy uses more accurate pairwise summation. You can disable Bottleneck with pd.set_o... | 3 | 3 |
79,516,763 | 2025-3-18 | https://stackoverflow.com/questions/79516763/method-decorators-which-tag-method-prevent-overwriting-by-other-decorators | I'm investigating the pattern whereby you have a method decorator which annotates the method in some way, and then once the class is defined it looks through its methods, finds the annotated methods, and registers or processes them in some way. e.g. def class_decorator(cls): for name, method in cls.__dict__.iteritems()... | Since a "tag" is always applied on a function object itself, it is always going to be susceptible to obstruction by an unaware wrapper function. To achieve a similar usage you can implement the behavior with a registry pattern instead by adding method names to a list with a method decorator so that the class decorator ... | 3 | 3 |
79,518,393 | 2025-3-18 | https://stackoverflow.com/questions/79518393/can-we-get-x21-instead-of-1-x2-with-sympy-latex-x21 | I need -x^{2}+1 rather than 1-x^{2} with sympy.latex(-x**2+1). from sympy import symbols, latex x = symbols('x') print(-x**2+1) print(latex(-x**2+1)) Output: 1 - x**2 1 - x^{2} Is it possible to change the default format? | As suggested in comments, you can use the order argument to change the result ordering! https://docs.sympy.org/latest/modules/printing.html#sympy.printing.latex.latex order: string, optional Any of the supported monomial orderings (currently 'lex', 'grlex', or 'grevlex'), 'old', and 'none'. This parameter does nothing... | 4 | 3 |
79,518,311 | 2025-3-18 | https://stackoverflow.com/questions/79518311/arrange-consecutive-zeros-in-panda-by-specific-rule | I have panda series as the following : 1 1 2 2 3 3 4 4 5 0 6 0 7 1 8 2 9 3 10 0 11 0 12 0 13 0 14 1 15 2 I have to arrange this in following format : 1 1 2 2 3 3 4 4 5 0 6 0 7 3 ---> 4-2+1 (previous non zero value - amount of previous zeroes + current value) 8 4 ---> 4-2+2 (previous non zero value - amount of previo... | Although this can only be done with Pandas in a rather convoluted way IMHO, here is a straightforward implementation using Numba (which should also be faster than all Pandas solutions): import numba as nb import numpy as np @nb.njit(['(int32[:],)', '(int64[:],)']) def compute(arr): res = np.empty(arr.size, dtype=arr.dt... | 4 | 3 |
79,517,885 | 2025-3-18 | https://stackoverflow.com/questions/79517885/how-to-scroll-and-click-load-more-results-using-selenium-in-python-booking-com | I’m new to web scraping with Selenium, and I’m trying to scrape property listings from Booking.com. My code (included below) successfully scrapes 25 results, but I suspect the issue is that more results are available if I scroll and click the "Load more results" button. I've tried using execute_script to scroll and fin... | I did a few changes to the code to make it work for your case: the first results are loaded automatically when the user scrolls so first we need to scroll to the bottom of the page a few times only then the "load more button" appears and we need to properly located it and click it I also closed the cookie banner as it... | 1 | 2 |
79,516,990 | 2025-3-18 | https://stackoverflow.com/questions/79516990/general-way-to-define-jax-functions-with-non-differentiable-arguments | For a particular JAX function func, one can define non-differentiable arguments by using the decorator @partial(jax.custom_jvp, nondiff_argnums=...). However, in order to make it work, one must also explicitly define the differentiation rules in a custom jvp function by using the decorator @func.defjvp. I'm wondering i... | In JAX's design, non-differentiated arguments are a property of the gradient transformation being used, not a property of the function being differentiated. custom_jvp is fundamentally about customizing the gradient behavior, and using it to mark non-differentiable arguments without actually customizing the gradient is... | 1 | 1 |
79,516,194 | 2025-3-18 | https://stackoverflow.com/questions/79516194/typing-a-generic-iterable | I'm creating a function that yields chunks of an iterable. How can I properly type this function so that the return value bar is of type list[int]. from typing import Any, Generator, Sequence def chunk[T: Any, S: Sequence[T]](sequence: S, size: int) -> Generator[S, None, None]: for i in range(0, len(sequence), size): y... | The Type Parameter Scopes section of PEP 695 – Type Parameter Syntax specifically points out that Python's typing system currently does not allow a non-concrete upper bound type, but that it may be allowed in a future extension: # The following generates no compiler error, but a type checker # should generate an error... | 2 | 1 |
79,533,867 | 2025-3-25 | https://stackoverflow.com/questions/79533867/how-to-display-both-application-json-and-application-octet-stream-content-types | I have an endpoint that can return JSON or a file (xlsx): class ReportItemSerializer(BaseModel): id: int werks: Annotated[WerkSerializerWithNetwork, Field(validation_alias="werk")] plu: Annotated[str, Field(description="Название PLU")] start_date: Annotated[date, None, Field(description="Дата начала периода в формате")... | Here is a working example, heavily based on this answer; hence, please have a look at that answer for more details. The example below will correctly display the example value/schema in Swagger UI autodocs, below the 200 response's description. Using the drop down menu, one could switch between the various media types—i... | 2 | 1 |
79,541,683 | 2025-3-28 | https://stackoverflow.com/questions/79541683/getting-infeasibility-while-solving-constraint-programming-for-shelf-space-alloc | I'm trying to allocate shelf space to items on planogram using constraint programming. It is a big problem and I'm trying to implement piece by piece. At first we're just trying to place items on shelf. The strategy is dividing whole planogram into multiple sections. For example if my planogram width is 10 cm with 3 sh... | Actually, due to the formulation of problem, the solver is always placing the item only on the edges, adding one more constraint helped to solve the issue: m.constraints.append(node_p_var_dict[p][(0, shelf)] + node_p_var_dict[p][((section_width*bay_count)-1, shelf)] <= 1) | 2 | 1 |
79,547,143 | 2025-3-31 | https://stackoverflow.com/questions/79547143/how-is-this-python-script-retrieving-youtube-urls-from-discogs | The purpose of the following code from here is to extract Youtube URLs from the Discogs API. It provides a JSON version of a list of releases on Discogs according to a particular search query, and an HTML example of this page would be: https://www.discogs.com/search/?sort=title%2Casc&format_exact=Vinyl&decade=1990&sty... | It looks like the original script does a two-level crawl of the API data. When it reads the initial URL, it gets JSON data like you show, which contains results and pagination as keys, but not videos. What it does with that data is read each value from results (a list), and find the sub-key resource_url for each result... | 2 | 1 |
79,539,046 | 2025-3-27 | https://stackoverflow.com/questions/79539046/how-to-use-jupyter-notebooks-or-ipython-for-development-without-polluting-the-ve | Best practice for Python is to use venv to isolate to the imports you really need. I use python -m venv. For development, it's very convenient to use IPython and notebooks for exploring code interactively. However, these need to be installed into the venv to be used. That defeats the purpose of the venv. I can make two... | I work on multiple projects most of which run in production, each with it's own dependencies. The practice which works for me is to create separate requirements.txt files: one for production environment, the other one contains additions used for development, and a small script that creates/u[dates 2 venvs at the same r... | 4 | 1 |
79,547,170 | 2025-3-31 | https://stackoverflow.com/questions/79547170/lxml-target-interface-splits-data-on-non-ascii-characters-how-can-i-get-the-w | Here's a file test.xml: <?xml version="1.0" encoding="UTF-8"?> <list> <entry>data</entry> <entry>Łódź</entry> <entry>data Łódź</entry> </list> and here's a simple python script to parse it into a list with lxml: from lxml import etree class ParseTarget: def __init__(self): self.entries = [] def start(self, tag, attrib... | You have to use the end handler to reset: Explanation of Steps With event based parsing, the parser may split the third <entry> (<entry>data Łódź</entry>) into multiple data() calls.: First: "data " (with a space at the end). Second: "Łódź". This is why we need to accumulate text correctly to "data Łódź". from lxml... | 2 | 4 |
79,536,730 | 2025-3-26 | https://stackoverflow.com/questions/79536730/mypy-complains-for-static-variable | mypy (v.1.15.0) complains with the following message Access to generic instance variables via class is ambiguous for the following code: from typing import Self class A: B: Self A.B = A() If I remove B: Self, then is says "type[A]" has no attribute "B". How make mypy happy? You can play with this here: mypy playground | In addition to InSync's solution, you can also do this: class A: B: 'A' A.B = A() Or better yet: from typing import ClassVar class A: B: ClassVar['A'] A.B = A() This is an example of a forward reference, and mypy handles those by putting the type name in quotes. Using ClassVar just tells the type checker to disallow ... | 1 | 3 |
79,544,423 | 2025-3-30 | https://stackoverflow.com/questions/79544423/fastest-way-to-search-5k-rows-inside-of-100m-row-pair-wise-dataframe | I am not sure title is well describing the problem but I will explain it step by step. I have a correlation matrix of genes (10k x 10k) I convert this correlation matrix to pairwise dataframe (upper triangle) (around 100m row) gene1 gene2 score Gene3450 Gene9123 0.999706 Gene5219 Gene9161 0.999691 Gene27 Gen... | Several optimisations can be applied to compute_per_complex_pr. First of all, pairwise_df.loc[candidate_indices] can be optimised by converting candidate_indices to a Numpy array and using iloc instead. Actually, sorted(candidate_indices) is also bit slow because it is a set of integer Python object and code operating ... | 3 | 4 |
79,547,082 | 2025-3-31 | https://stackoverflow.com/questions/79547082/extracting-images-from-a-pdf-using-pymupdf-gives-broken-output-images | The code I am using to extract the images is from PIL import Image def extract_images_from_pdfs(pdf_list): import fitz # PyMuPDF output_dir = "C:/path_to_image" os.makedirs(output_dir, exist_ok=True) for pdf_path in pdf_list: pdf_name = os.path.splitext(os.path.basename(pdf_path))[0] # Open the PDF pdf_document = fitz.... | The PDF has 78 very small pieces of imagery of which the "largest" is masking for O on the first page: 1 60 image 81 62 index 1 8 image no 271 0 151 151 1996B 40% And many are simply one single pixel. They can be in any order and the early ones of the 78 are generally parts of R: pdfimages -list chem.pdf page num ... | 1 | 1 |
79,545,895 | 2025-3-31 | https://stackoverflow.com/questions/79545895/image-upload-corruption-with-seaweedfs-s3-api | Problem Description I'm experiencing an issue where images uploaded through Django (using boto3) to SeaweedFS's S3 API are corrupted, while uploads through S3 Browser desktop app work correctly. The uploaded files are 55 bytes larger than the original and contain a Content-Encoding: aws-chunked header, making the image... | Follow answer in https://github.com/boto/boto3/issues/4435#issuecomment-2648819900 I added this lines on top of settings.py file and problem solved. import os os.environ["AWS_REQUEST_CHECKSUM_CALCULATION"] = "when_required" os.environ["AWS_RESPONSE_CHECKSUM_VALIDATION"] = "when_required" | 1 | 1 |
79,545,985 | 2025-3-31 | https://stackoverflow.com/questions/79545985/find-correct-root-of-parametrized-function-given-solution-for-one-set-of-paramet | Let's say I have a function foo(x, a, b) and I want to find a specific one of its (potentially multiple) roots x0, i.e. a value x0 such that foo(x0, a, b) == 0. I know that for (a, b) == (0, 0) the root I want is x0 == 0 and that the function changes continuously with a and b, so I can "follow" the root from (0, 0) to ... | Get rid of your @cache and @vectorize; neither is likely to help you for the following and they're just noise. (If they're needed for outer code, you haven't shown that outer code, so the point stands.) Do keep using Scipy's root-finding iteratively, but beyond that your procedure should look pretty different. I propos... | 2 | 0 |
79,546,711 | 2025-3-31 | https://stackoverflow.com/questions/79546711/python-asyncio-how-do-awaitables-interact-with-system-level-i-o-events-e-g | I’m learning asynchronous programming in Python using asyncio and want to understand how low-level awaitables work, particularly for system events like serial port communication. For example, libraries like pyserial-asyncio allow non-blocking reads from a serial port, but I’m unclear on the underlying mechanics. My Und... | In brief, asyncio rests on three pillars: coroutines, callback schedulers, and selectors. When you call socket.read() in synchronous code, you are telling the operating system to "wake up this thread when the operation completes (successfully or unsuccessfully)". Exactly one wait, interrupted only by signal handlers. B... | 1 | 4 |
79,546,910 | 2025-3-31 | https://stackoverflow.com/questions/79546910/typeerror-in-sfttrainer-initialization-unexpected-keyword-argument-tokenizer | Question: I am trying to fine-tune the Mistral-7B-Instruct-v0.1-GPTQ model using SFTTrainer from trl. However, when running my script in Google Colab, I encounter the following error: TypeError: SFTTrainer.__init__() got an unexpected keyword argument 'tokenizer' Here is the relevant portion of my code: import torch f... | In the 0.12.0 release it is explained that the tokenzier argument is now called the processing_class parameter. You should be able to run your code as before by replacing tokenizer with processing_class: trainer = SFTTrainer( model=model, train_dataset=data, peft_config=peft_config, args=training_arguments, processing_... | 3 | 4 |
79,540,700 | 2025-3-28 | https://stackoverflow.com/questions/79540700/is-it-possible-to-use-python-social-auths-emailauth-with-drf-social-oauth2-for | I have a facebook authentication in my project, and I've set up some pipelines. So It would be nice for non-social email registration to also utilize these pipelines. I tried adding EmailAuth to the authentication backends list, but I don't know what view to use now for registratioin. So, is it possible (or reasonable)... | You can integrate EmailAuth with drf-social-oauth2 by adding it to AUTHENTICATION_BACKENDS and using the same authentication pipelines. Since drf-social-oauth2 lacks a native email registration view, create a custom API endpoint that registers users manually and authenticates them via the email backend. Then, expose th... | 1 | 1 |
79,545,669 | 2025-3-31 | https://stackoverflow.com/questions/79545669/how-to-achieve-similar-desmos-visuals-in-manim | I am trying to graph this function in manim x^(2/3) + 0.9sqrt(3.5-x^2) * sin(πx*a) I wrote some simple code to graph it in an animation like style: from manim import * import numpy as np class HeartAnimation(Scene): def construct(self): axes = Axes( x_range=[-10, 10, 1], y_range=[-7, 7, 1], axis_config={"color": BLUE},... | for the sampling rate, you have to add a third element (which will be the step of your sampling). However it seems like you can't make it too low, so to work aroud this problem, you can just scale the whole thing to be bigger (on both x and y so that shape doesn't change (in the formulas: x->x/scale and y->y*scale) for... | 1 | 1 |
79,542,444 | 2025-3-28 | https://stackoverflow.com/questions/79542444/faster-moving-median-in-numpy | I am trying to calculate a moving median for around 10.000 signals that each are a list of length around 750. An example dataframe looks like this: num_indices = 2000 # Set number of indices # Generate lists of values (each a list of numbers from 0 to 1) column_data = [np.random.random(750).tolist() for _ in range(num_... | You don't mention having NaNs in your data, so I will assume you do not. In that case, I think this is the best SciPy has to offer: import numpy as np from scipy.ndimage import median_filter rng = np.random.default_rng(49825498549428354) data = rng.random(size=(2000, 750)) # 2000 signals, each of length 750 res = media... | 2 | 2 |
79,544,212 | 2025-3-30 | https://stackoverflow.com/questions/79544212/conditional-running-total-based-on-date-field-in-pandas | I have a dataframe with below data. DateTime Tag Qty 2025-01-01 13:00 1 270 2025-01-03 13:22 1 32 2025-01-10 12:33 2 44 2025-01-22 10:04 2 120 2025-01-29 09:30 3 182 2025-02-02 15:05 1 216 To be achieved: 2 new columns, first with cumulative sum of Qty until the DateTime on each row when Tag is not ... | You can use a condition and the methods mask and where to create both columns cond = df['Tag'].eq(2) df['RBQ'] = df['Qty'].mask(cond, 0).cumsum() df['RSQ'] = df['Qty'].where(cond, 0).cumsum() Another solution is to use the same condition and pivot the dataframe based on that. df2 = (df.join(df.assign(cols=df['Tag'].eq... | 2 | 2 |
79,544,697 | 2025-3-30 | https://stackoverflow.com/questions/79544697/how-to-extract-nested-json-using-json-normalize | I have a nested json, but I can't understand how to work with them. { "return": { "status_processing": "3", "status": "OK", "order": { "id": "872102042", "number": "123831", "date_order": "dd/mm/yyyy", "items": [ { "item": { "id_product": "684451795", "code": "VPOR", "description": "Product 1", "unit": "Un", "quantity"... | I don't know what exactly you expect in output but if you want every item in new row then you could use normal code with for-loop for this. order_list = { "return": { "status_processing": "3", "status": "OK", "order": { "id": "872102042", "number": "123831", "date_order": "dd/mm/yyyy", "itens": [ { "item": { "id_produc... | 1 | 0 |
79,542,528 | 2025-3-28 | https://stackoverflow.com/questions/79542528/how-to-strip-quotes-from-csv-table | I'm using the pandas library to convert CSVs to other data types. My CSV has the fields quoted, like this: "Version", "Date", "Code", "Description", "Tracking Number", "Author" "0.1", "22AUG2022", , "Initial Draft", "NR", "Sarah Marshall" "0.2", "23SEP2022", "D", "Update 1", "N-1234", "Bill Walter" "0.3", "09MAY2023", ... | The leading spaces in your input seem to be throwing Pandas off (and some other CSV processors I can think of). Try the skipinitialspace=True option to make Pandas ignore every space between a comma and a quote char: import pandas as pd df = pd.read_csv("input.csv", skipinitialspace=True) print(df) Version Date ... T... | 1 | 5 |
79,544,791 | 2025-3-30 | https://stackoverflow.com/questions/79544791/how-to-fix-signupview-is-missing-a-queryset | In my django web app i am trying to build a Newspaper app, in my homepage when i click on SIGN UP Button i get an error "ImproperlyConfigured at /accounts/signup/", I didnt figure out where is the problem. forms.py: from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser cl... | The culprit is a typo: from_class to form_class: from django.urls import reverse_lazy from django.views.generic import CreateView from .forms import CustomUserCreationForm class SignUpView(CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy('login') template_name = 'registration/signup.html' But... | 2 | 3 |
79,541,208 | 2025-3-28 | https://stackoverflow.com/questions/79541208/printing-numpy-matrices-horizontally-on-the-console | Numpy has many nice features for formatted output, but something I miss is the ability to print more than one array/matrix on the same line. What I mean is easiest to explain with an example. Given the following code: A = np.random.randint(10, size = (4, 4)) B = np.random.randint(10, size = (4, 4)) niceprint(A, "*", B,... | Don't write it yourself; use something common and off-the-shelf like Sympy. import numpy as np import sympy A = sympy.Matrix(np.random.randint(10, size=(4, 4))) B = sympy.Matrix(np.random.randint(10, size=(4, 4))) sympy.pretty_print( sympy.Eq( sympy.MatMul(A, B), A @ B, ) ) ⎡4 2 1 5⎤ ⎡3 0 7 7⎤ ⎡77 54 42 58 ⎤ ⎢ ⎥ ⎢ ⎥ ⎢... | 6 | 0 |
79,537,058 | 2025-3-26 | https://stackoverflow.com/questions/79537058/getting-authentication-failed-error-while-connecting-with-ms-fabric-data-warehou | First I ahve used Node.js and tedious but it didn't work becase tedious library can't connect to fabric dwh because fabric has a bit different security layers and protocols, that tedious so far do not have. Now I have used ODBC library but got Authentication Error Microsoft][ODBC Driver 17 for SQL Server][SQL Server]C... | Fixed by giving azure sql storage permission On Azure and app id read permission to the workspace of Fabric | 2 | 0 |
79,544,253 | 2025-3-30 | https://stackoverflow.com/questions/79544253/image-size-inconsistency-between-github-and-pypi-in-readme-md | I created some simple console games in Python(Oyna Project) and took screenshots of each game to showcase them in the README.md file. I wanted to display these images in a table format both on GitHub and on PyPI. On GitHub, everything looks fine — the images are well-aligned, and their sizes are consistent. But when I ... | You can solve this issue by resizing the images via usage of html table format since PyPi supports HTML in its Readme files, find a way to tweak the width and or the height, however monitor the aspect ratio of the image and perhaps focus only on the width of the image since most browser calculate other dimension for yo... | 1 | 2 |
79,536,716 | 2025-3-26 | https://stackoverflow.com/questions/79536716/expand-columns-of-structs-to-rows-in-polars | Say we have this dataframe: import polars as pl df = pl.DataFrame({'EU': {'size': 10, 'GDP': 80}, 'US': {'size': 100, 'GDP': 800}, 'AS': {'size': 80, 'GDP': 500}}) shape: (1, 3) ┌───────────┬───────────┬───────────┐ │ EU ┆ US ┆ AS │ │ --- ┆ --- ┆ --- │ │ struct[2] ┆ struct[2] ┆ struct[2] │ ╞═══════════╪═══════════╪════... | TL;DR Performance comparison at the end. Both @etrotta's method and @DeanMacGregor's adjustment perform well on a pl.lazyframe with small Structs (e.g., struct[2]) and columns N <= 15 (not collected). Other methods fail lazily. With bigger Structs and/or columns N > 15, both unpivot options below start to outperform. O... | 5 | 5 |
79,542,832 | 2025-3-29 | https://stackoverflow.com/questions/79542832/using-winrt-interface-in-python | ref: ISystemMediaTransportControlsInterop I compiled a dll about ISystemMediaTransportControlsInterop::GetForWindow. I use IDA to decompile it. Then I wrote the C-like code as Python. I believe that I was wrote them in a right way. But sadly, I met a pointer error. I know it's because SMTC_Interop_GetForWindow function... | The error suggests you're trying to write to memory that's not accessible. The main problem is in this line: SMTC_Interop_GetForWindow = ctypes.CFUNCTYPE(...)(ctypes.cast(smtc_interop.value, ctypes.POINTER(ctypes.c_int64)).contents.value + 48) Change it with vtable_ptr = ctypes.cast(smtc_interop.value, ctypes.POINTER(... | 1 | 2 |
79,542,469 | 2025-3-28 | https://stackoverflow.com/questions/79542469/python-valueerror-is-a-bad-directive-in-format-y-m-dxz | I'm attempting to parse HTML time strings in Python: from datetime import datetime input = "2025-03-24T07:01:53+00:00" output = datetime.strptime(input, "%Y-%m-%d%X%:z") print(output) Running this with Python 3.13 returns the following error: Traceback (most recent call last): File "/Users/dread_pirate_roberts/html_ti... | This is a known CPython bug. For now (3.13), %:z only works in .strftime(): >>> import datetime >>> d = datetime.datetime.now(tz = datetime.UTC) >>> d datetime.datetime(2025, 1, 1, 1, 1, 1, 111111, tzinfo=datetime.timezone.utc) >>> d.strftime('%z') '+0000' >>> d.strftime('%:z') '+00:00' It should also be noted that %z... | 3 | 5 |
79,542,324 | 2025-3-28 | https://stackoverflow.com/questions/79542324/constrain-llama3-2-vision-output-to-a-list-of-options | I have several images of animals in the same directory as the script. How can I modify the following script to process an image but force the output to only be a single selection from a list: from pathlib import Path import base64 import requests def encode_image_to_base64(image_path): """Convert an image file to base6... | Llama3.2-vision supports structured outputs, so you can specify the schema of the response you want, and the model should follow it. Your request should look like this: payload = { "model": "llama3.2-vision", "stream": False, "messages": [ { "role": "user", "content": ( "Classify this image into one of these exact cate... | 1 | 2 |
79,541,633 | 2025-3-28 | https://stackoverflow.com/questions/79541633/how-to-add-aliases-to-consecutive-occurrences-in-column | I want to add aliases to consecutive occurrences of the same gene name in column gene_id. If the gene_id value is unique, it should be unchanged. Here is my example input: df_genes_data = {'gene_id': ['g0', 'g1', 'g1', 'g2', 'g3', 'g4', 'g4', 'g4']} df_genes = pd.DataFrame.from_dict(df_genes_data) print(df_genes.to_str... | Use shift+ne+cumsum to group the consecutive values, then groupby.transform('size') to identify the groups of more than 2 values, and groupby.cumcount to increment the name: # Series as name for shorter reference s = df_genes['gene_id'] # group consecutive occurrences group = s.ne(s.shift()).cumsum() # form group and s... | 3 | 6 |
79,538,411 | 2025-3-27 | https://stackoverflow.com/questions/79538411/why-is-using-a-dictionary-slower-than-sorting-a-list-to-generate-frequency-array | I was doing this question on Codeforces (2057B - Gorilla and the Exam) where I had to use the frequencies of different numbers in a list. First I tried calculating it with a dictionary but I got TLE verdict (Time limit exceeded). After reading the editorial I implemented it by sorting the input list and then using comp... | Why is using a dictionary slower than sorting a list to generate frequency array? Apparently because one input is specially crafted to hack Python's dict implementation, so that building your dict doesn't take the expected linear time. It can take up to quadratic time, and likely they did that. See Python's TimeCompl... | 2 | 2 |
79,537,769 | 2025-3-27 | https://stackoverflow.com/questions/79537769/raising-a-float-near-1-to-an-infinite-power-in-python | 1.000000000000001 ** float('inf') == float('inf') while 1.0000000000000001 ** float('inf') == 1.0 What determines the exact threshold here? It seems to be an issue of float precision, where numbers below a certain threshold are considered the same as 1.0. Is there a way to get better precision in Python? | As others have said, this is due to IEEE754 floats not being able to represent your constants with the precision you're expecting. Python provides some useful tools that lets you see what's going on, specifically the math.nextafter method and and decimal module. The decimal module is useful to see the decimal expansion... | 2 | 2 |
79,540,471 | 2025-3-28 | https://stackoverflow.com/questions/79540471/filter-sequences-of-same-values-in-a-particular-column-of-polars-df-and-leave-on | I have a very large Polars LazyFrame (if collected it would be tens of millions records). I have information recorded for a specific piece of equipment taken every second and some location flag that is either 1 or 0. When I have sequences where the location flag is equal to 1, I need to filter out and only leave the la... | If I've interpreted correctly, for each equipment you want to keep only the first row of each continuous sequence of loc = 1. Fixing your solution In that case, the only changes you need to make to your solution are: Add the fill_value to pl.col(“time”).shift(1) to ensure that the first row with loc = 1 is always sele... | 1 | 2 |
79,540,754 | 2025-3-28 | https://stackoverflow.com/questions/79540754/coc-pyright-fail-to-report-reportattributeaccessissue-if-setattr-is-provided | from pydantic import BaseModel class User2(BaseModel): name:str age: int ''' def __setattr__(self, key, value): super().__setattr__(key, value) ''' user2 = User2(name="Alice", age=1) >>> user2.foo = 1 # Should report: Cannot assign to attribute "foo" for class "User2" \ Attribute "foo" is unknown if I uncomment the __... | The presence of __setattr__ does not report reportAttributeAccess issue for pyright as well as mypy. The trick is to not reveal that such a method exists. This can be done by defining it in an if not TYPE_CHECKING: block. Linters and checkers might mark the code there as unreachable which can be undesired, therefore yo... | 1 | 2 |
79,540,627 | 2025-3-28 | https://stackoverflow.com/questions/79540627/why-does-pathlib-path-glob-function-in-python3-13-return-map-object-instead-of-a | I was playing around with Path objects and found an interesting behaviour. When testing with python3.11, Path.glob returns a generator object. >>> from pathlib import Path >>> >>> cwd = Path.cwd() >>> cwd.glob("*") <generator object Path.glob at 0x100b5e680> >>> import sys;sys.version '3.11.6 (v3.11.6:8b6ee5ba3b, Oct 2... | pathlib.Path.glob learned a bunch of new things in Python 3.13, and I suspect the change in return value type from one generator type to another generator was part of that: Changed in version 3.13: The recurse_symlinks parameter was added. Changed in version 3.13: The pattern parameter accepts a path-like object. Chan... | 1 | 2 |
79,540,404 | 2025-3-28 | https://stackoverflow.com/questions/79540404/calculating-spo2-with-max30101-sensor-in-python-on-raspberry-pi-4 | I have recently purchased a MAX30101 breakout board / sensor and have been using it with a Raspberry Pi 4 and Python. I have been using the sparkfun-qwiic-max3010x library provided by Sparkfun to communicate with the sensor and collect data. The GitHub page for the Python sparkfun-qwiic-max3010x library includes an exa... | Calculating r the way you do is incorrect. By the very nature of red_ac its mean is almost zero (it is not exactly zero because of rounding errors). Same for ir_ic. Dividing two such values results in a huge meaningless error, precisely what you observe. Notice that in the Maxim paper you linked they do not divide aver... | 4 | 6 |
79,539,620 | 2025-3-27 | https://stackoverflow.com/questions/79539620/the-problem-of-reachability-in-a-directed-graph-but-all-predecessors-must-be-re | The problem It's similar to the problem of finding the minimal set of vertices in a directed graph from which all vertices can be reached, except that a node must have all its predecessors reached in order to be reached itself. More formally, let S be a set of nodes belonging to a directed graph G. A node n of G is sai... | This problem is NP hard. That can be seen by reducing the minimum feedback vertex set problem to your reachability problem. Start with any directed graph G. Construct a new graph H by adding a single vertex v with an edge connecting it to every vertex in G. Let S be any solution to your reachability problem on H. It is... | 2 | 4 |
79,540,025 | 2025-3-27 | https://stackoverflow.com/questions/79540025/how-to-materialize-polars-expression-into-series | Working with a single series instead of a dataframe, how can I materialize an expression on that series? For instance, when I run time = pl.Series([pl.datetime(2025, 3, 27)]) (time + pl.duration(minutes=5)).to_numpy() I get AttributeError Traceback (most recent call last) Cell In[46], line 2 1 time = pl.Series([pl.dat... | You need a "DataFrame" to run expressions. Your example is "wrong" because passing an Expr creates a Series with dtype object. pl.Series([pl.datetime(2025, 3, 27)]) # shape: (1,) # Series: '' [o][object] # [ # 2025-03-27 00:00:00.alias("datetime") # ] # pl.select() is shorthand for creating an empty frame. s = pl.sele... | 1 | 1 |
79,539,193 | 2025-3-27 | https://stackoverflow.com/questions/79539193/parsing-dates-from-strings-that-contain-unrelated-text-while-avoiding-parsing-in | What I want to Achieve My goal is to extract a date that has at least a day and a Month, but could also have a minute, hour, and year. I want to avoid the parser finding integers and thinking that implies a day of the current month. Furthermore, I also want the parser to find a date that is only a small part of a large... | Use from dateparser.search import search_dates Here's a quick function: from dateparser import parse from dateparser.search import search_dates def extract_date(text:str, exclusions:list=['now', 'today', 'tomorrow', 'yesterday', 'hour', 'minute', 'seconds', 'month', 'months','year', 'years'], required:list=['month', 'd... | 2 | 1 |
79,538,811 | 2025-3-27 | https://stackoverflow.com/questions/79538811/how-do-i-send-email-using-client-credentials-flow-such-that-senders-mail-is-inc | I created below app to send mail using Graph API I used Client Credential flow to send mail, but I keep getting 401 error. Is there anything that needs to be changed in the API permission on Azure or in the code? Is there a way I can send mail using delegated access without an interactive session? import requests impo... | The error usually occurs if you using ConfidentialClientApplication to send mail and granted delegated type API permission to the Microsoft Entra ID application. Hence to resolve the error, you need to grant application type API permission to the Microsoft Entra ID application. Refer this MsDoc Make sure to grant admi... | 1 | 1 |
79,538,656 | 2025-3-27 | https://stackoverflow.com/questions/79538656/python-asyncio-condition-why-deadlock-appears | I learn python asyncio and now struggling with Conditions. I wrote a simple code: import asyncio async def monitor(condition: asyncio.Condition): current_task_name = asyncio.current_task().get_name() print(f'Current task {current_task_name} started') async with condition: await condition.wait() print(f'Condition lock r... | In your original code, the setter task is started before the monitor tasks. When setter calls notify_all(), no monitor tasks are yet waiting so no tasks are notified. Later, the monitors reach condition.wait() but remain stuck because no further notifications are sent. When you reverse the order, starting monitor tasks... | 1 | 3 |
79,538,469 | 2025-3-27 | https://stackoverflow.com/questions/79538469/is-with-concurrent-futures-executor-blocking | Why when using separate with, the 2nd executor is blocked until all tasks from 1st executor is done when using a single compound with, the 2nd executor can proceed while the 1st executor is still working This is confusing because i thought executor.submit returns a future and does not block. It seems like the context... | When you use a concurrent.futures.Executor instance as a context manager (e.g. with ThreadPoolExecutor() as executor:), then when the block is exited there is an implicit call to executor.shutdown(wait=True). So when you have two with blocks that are not nested (i.e. they are coded one after the other), the second with... | 1 | 2 |
79,537,428 | 2025-3-26 | https://stackoverflow.com/questions/79537428/can-i-multiply-these-numpy-arrays-without-creating-an-intermediary-array | This script: import numpy as np a = np.linspace(-2.5, 2.5, 6, endpoint=True) b = np.vstack((a, a)).T c = np.array([2, 1]) print(b*c) produces: [[-5. -2.5] [-3. -1.5] [-1. -0.5] [ 1. 0.5] [ 3. 1.5] [ 5. 2.5]] which is my desired output. Can it be produced directly with from a and c? Trying a*c and c*a fails due to Val... | With the original (6,) and (2,) arrays, einsum may make the outer product more explicit: In [331]: a=np.linspace(-2.5, 2.5, 6, endpoint=True); c=np.array([1,2]) In [332]: np.einsum('i,j->ij',a,c) Out[332]: array([[-2.5, -5. ], [-1.5, -3. ], [-0.5, -1. ], [ 0.5, 1. ], [ 1.5, 3. ], [ 2.5, 5. ]]) np.outer(a,c) and np.mul... | 1 | 2 |
79,537,461 | 2025-3-26 | https://stackoverflow.com/questions/79537461/test-that-unittest-mock-was-called-with-some-specified-and-some-unspecified-argu | We can check if a unittest.mock.Mock has any call with some specified arguments. I now want to test that some of the arguments are correct, while I do not know about the other ones. Is there some intended way to do so? I could manually iterate over Mock.mock_calls, but is there a more compact way? import random from un... | You can assert the wildcard argument to be unittest.mock.ANY, which has its __eq__ method overridden to unconditionally return True so that the object is evaluated equal to anything: from unittest.mock import ANY def test_mymethod(): handler = mock.Mock() mymethod(5, handler) handler.assert_any_call(5, ANY) # passes D... | 2 | 1 |
79,537,356 | 2025-3-26 | https://stackoverflow.com/questions/79537356/pandas-group-by-maximum-row-for-a-subset | I have a dataframe with weekly product sales product_id week_number sales A1 1 1000 A1 2 2000 A1 3 3000 A2 1 8000 A2 2 4000 A2 3 2000 I want to add a column that identifies rows where the total sales were the highest for the given product: product_id week_number sales product_max A1 1 1000 FA... | Answer df['product_max'] = ( df.groupby('product_id')['sales'].transform('max') .eq(df['sales']) ) df product_id week_number sales product_max 0 A1 1 1000 False 1 A1 2 2000 False 2 A1 3 3000 True 3 A2 1 8000 True 4 A2 2 4000 False 5 A2 3 2000 False Example Code import pandas as pd data = {'product_id': ['A1', 'A1',... | 2 | 1 |
79,536,276 | 2025-3-26 | https://stackoverflow.com/questions/79536276/numpy-element-by-element-subtract | I have two numpy 'arrays': 1st is a 2D array with shape (N, 2) 2nd is a 3D "matrix" with shape (N, M, 2) where M can be different from 0 to N-1 Code example import numpy as np a = np.array([[1, 2], [3, 4]]) # (N=2,2) shape b = np.array([np.array([[1, 2]]), np.array([[1, 2], [3, 4]])], dtype=object) # (N=2,(1,2), 2) sha... | Another solution is using np.concatenate and np.split: import numpy as np a = np.array([[1, 2], [3, 4]]) b_list = [np.array([[1, 2]]), np.array([[1, 2], [3, 4]])] # Flatten `b` into a single array b_concat = np.concatenate(b_list, axis=0) a_repeat = np.repeat(a, [len(b) for b in b_list], axis=0) diff_flat = a_repeat - ... | 1 | 3 |
79,533,554 | 2025-3-25 | https://stackoverflow.com/questions/79533554/how-to-programmatically-get-a-list-of-all-first-level-keys-stored-in-a-namespace | In the process of developing a custom Jinja2 extension (a tag, not a filter), I am finding myself in the situation where I need to extract a list of first-level keys that refer to the runtime values saved in a namespace. Individual first-level values with known keys are easy to extract from the namespace with a simple ... | If you read the source code you'll find that the attributes of jinja2.utils.Namespace are stored in the __attrs attribute, a "private" variable prefixed with double underscores that is subject to name mangling, so you would have to access it with the _Namespace prefix instead. So to obtain a list of all first-level key... | 4 | 1 |
79,534,957 | 2025-3-25 | https://stackoverflow.com/questions/79534957/is-there-a-way-to-call-functions-in-functions-without-the-memory-inefficiencies | If I have a text-based game, and I transition through game states by calling a function corresponding to each game state like the following def go_to_lobby(gold_coins: int) -> None: """ The start of the adventure """ print_gold_amount(gold_coins) print("You are in the lobby of the dungeon. What do you do?") print("1. E... | Like @Joffan pointed out in the comment, you should convert your recursive program flow to an iterative one with an action loop where each action sets the next action to perform. Without rewriting your code, however, you can perform the conversion by applying to each action function a decorator that defers a call to th... | 2 | 1 |
79,532,996 | 2025-3-25 | https://stackoverflow.com/questions/79532996/scipy-minimize-throwing-bounds-error-when-constraint-is-added | I am trying to optimize a matrix given some bounds and constraints. When I run the minimize function with only the bounds everything works fine, but when adding the constraints I get the following error: Exception has occurred: IndexError SLSQP Error: the length of bounds is not compatible with that of x0. Below is a ... | The minimize() function generally assumes that when it evaluates f(x), then x is not modified. If you modify it, you may get strange behavior. This is a problem, because this modifies the argument passed to it: guess.shape = (int(np.sqrt(guess.size)), int(np.sqrt(guess.size))) This is why removing the constraint helps... | 1 | 2 |
79,534,739 | 2025-3-25 | https://stackoverflow.com/questions/79534739/is-there-a-way-to-individually-control-subplot-sizes-in-matplotlib | I need to combine imshow and regular line plots to create a figure. Unfortunately, the imshow plot area is smaller than the regular line plots, leading to something that looks like this: fig = plt.figure(figsize=(25, 9)) map_subplots = [ plt.subplot(2, 5, 1, projection=ccrs.PlateCarree()), plt.subplot(2, 5, 3, projecti... | This is what compressed layout is meant to handle (https://matplotlib.org/stable/users/explain/axes/constrainedlayout_guide.html#grids-of-fixed-aspect-ratio-axes-compressed-layout) Note that there is still blank space, but it is above and below the plots instead of between them. One fix for that is to either adjust the... | 1 | 2 |
79,555,858 | 2025-4-4 | https://stackoverflow.com/questions/79555858/how-to-programmatically-use-the-result-of-an-expression-as-argument-to-a-name-no | In the process of developing a custom Jinja2 extension that creates namespaces with dynamically evaluated names, I need to use the result of the evaluation of a template expression as argument to a Name node. The root of the issue is that the Name node's first argument must be of string type, while the result of parsin... | You're trying to dynamically create a variable whose name is only known at runtime, but as you already pointed out, the name of an assignment target is determined during compilation, so simply tinkering with the AST isn't going to help. As a workaround you can make the symbol mapping table available at runtime by embed... | 1 | 1 |
79,556,268 | 2025-4-4 | https://stackoverflow.com/questions/79556268/mcp-python-sdk-how-to-authorise-a-client-with-bearer-header-with-sse | I am building the MCP server application to connect some services to LLM . I use the MCP Python SDK https://github.com/modelcontextprotocol/python-sdk One of things i want to implement is authorisation of a user with the token. I see it must be possible somehow. Most of tutorials about MCP are related to STDIO kind of... | If someone is still looking for this. There is the solution. from mcp.server.fastmcp import FastMCP from fastapi import FastAPI, Request import subprocess import shlex # Global variable to keep a token a for a request auth_token = "" app = FastAPI() mcp = FastMCP("Server to manage a Linux instance") @app.middleware("ht... | 2 | 2 |
79,559,057 | 2025-4-7 | https://stackoverflow.com/questions/79559057/how-do-i-update-text-in-toga | I am trying to create a simple clock app, and for that, I am using time. I want to update the time label Imports import toga from toga.style import Pack from toga.style.pack import COLUMN, ROW import time code self.time_label=toga.Label("00:00:00",style=Pack(padding=10,font_size=50)) I directly call the update_time(... | If you only call the update method once, then of course it will only update once. To update it regularly, you'll need to run an async task. I think the startup method is called before the asyncio event loop is running, so instead you could override the on_running method, like this: async def on_running(self): while Tru... | 2 | 0 |
79,557,443 | 2025-4-5 | https://stackoverflow.com/questions/79557443/is-it-possible-to-mix-ctypes-structure-with-regular-python-fields | Just going the straight way like this, doesn't seem to work in python 3. import ctypes class cA(ctypes.Structure): _fields_ = [("a", ctypes.c_ubyte)] def __init__(self): super().__init__() self.c = 3 z = cA.from_buffer_copy(b'0') print (z) print (z.c) print (dir(z)) Traceback (most recent call last): File "polymorph.p... | .from_buffer_copy() doesn't call __init__. But use a normal constructor and it works, although I don't recommend this since a ctypes.Structure is meant to exactly wrap the fields of a C structure and represent its memory layout. How would additional Python fields be represented? Also note that the default constructor o... | 1 | 2 |
79,557,694 | 2025-4-6 | https://stackoverflow.com/questions/79557694/saving-statsmodel-to-adls-blob-storage | i currently have a model fit using statsmodel OLS formula and I am trying to save this model to ADLS blob storage. '/mnt/outputs/' is a mount point I have created and I am able to read and write other files from this directory. import statsmodels.formula.api as smf fit = smf.ols(formula=f"Pressure ~ {cat_vars_int} + Sp... | Default the mount point will be under dbfs context, whenever you reference files without spark you need prefix path with /dbfs. So, save the file giving path like below. path = f'/dbfs/mnt/outputs/Models/20240406_M2.pickle' fit.save(path) and whenever accessing via spark context give like below. spark.read.csv("dbfs:/... | 1 | 1 |
79,560,723 | 2025-4-7 | https://stackoverflow.com/questions/79560723/update-formulas-in-excel-using-python | I am trying to update formulas in an existing excel which has data and tables but I am failing to update the formulas so that they would update the data for example: Okay since I get some answers but not exactly what I'm trying to achieve I will try to get more context here: I am trying to make a unique list from a tab... | To add the UNIQUE function you need add it as a Array Formula. You could enter the formula to a single cell but if the unique values are more than one cell it will only show the first unique value. An Array allows every value to be assigned a cell and the range should be no bigger than the 'Names' range of the Table of... | 1 | 3 |
79,550,092 | 2025-4-2 | https://stackoverflow.com/questions/79550092/time-limit-exceeded-on-leetcode-128-even-for-optimal-time-complexity | I was attempting LeetCode question 128. Longest Consecutive Sequence: Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence. You must write an algorithm that runs in O(n) time. Example 1: Input: nums = [100,4,200,1,3,2] Output: 4 Explanation: The longest consecutive e... | Why does a O(nlogn) algorithm perform faster than O(n) in practice? Time complexity does not say anything about actual running times for concrete input sizes. It only says something about how running times will evolve asymptotically as the input size grows large. In general (unrelated to the actual code you presented... | 5 | 7 |
79,560,599 | 2025-4-7 | https://stackoverflow.com/questions/79560599/algorithm-for-detecting-full-loop-when-iterating-over-a-list | Assignment: Write a funcion cycle_sublist(lst, start, step) where: lst is a list start is number that satisfies: 0 <= start < len(lst) step is the amount we increase your index each iteration without using: slicing, importing, list comprehension, built-in functions like map and filter. The function works in this way... | This is my try based on your try. I got something like this: def cycle_sublist(lst,start,step): index = start length = len(lst) res = [] while index < length + start: res.append(lst[index % length]) index += step return res print(cycle_sublist([1], 0, 2)) # [1] print(cycle_sublist([6, 5, 4, 3], 0, 2)) # [6, 4] print(cy... | 5 | 5 |
79,558,410 | 2025-4-6 | https://stackoverflow.com/questions/79558410/how-to-prevent-ruff-from-formatting-arguments-of-a-function-into-separate-lines | I have a function like so: def get_foo(a: object, b: tuple, c: int,) -> dict: ..... When I do $ ruff format myfile.py, my function is changed to def get_foo( a: object, b: tuple, c: int, ) -> dict: .... How do I stop this behaviour? Update: @STerliakov I implemented your solution but received this warning. $ ruff for... | That happens due to the trailing comma in your arguments list. This behavior is intentional. You can disable it globally using skip-magic-trailing-comma. E.g. in pyproject.toml that would be [tool.ruff.format] skip-magic-trailing-comma = true Enabling this setting is incompatible with import sorter default configurati... | 1 | 3 |
79,555,255 | 2025-4-4 | https://stackoverflow.com/questions/79555255/numpy-strange-behaviour-of-setitem-of-array | Say we have an array: a = np.array([ [11, 12, 13], [21, 22, 23], [31, 32, 33], [41, 42, 43] ]) a[[1, 3], [0, 2]] = 0 So we want to set zeros to 0th and 2nd element at both 1st and 3rd rows. But what we get is: [[11 12 13] [ 0 22 23] [31 32 33] [41 42 0]] Why not: [[11 12 13] [ 0 22 0] [31 32 33] [0 42 0]] ? | In import numpy as np a = np.array([ [11, 12, 13], [21, 22, 23], [31, 32, 33], [41, 42, 43] ]) a[[1, 3], [0, 2]] = 0 a the last statement is equivalent to (edited) a[1, 0] = 0 a[3, 2] = 0 It gives the following: a = np.array([ [11, 12, 13], [21, 22, 23], [31, 32, 33], [41, 42, 43] ]) a[1, 0] = 0 a[3, 2] = 0 a # array... | 2 | 0 |
79,560,710 | 2025-4-7 | https://stackoverflow.com/questions/79560710/getting-an-error-attributeerror-module-tensorflow-python-distribute-input-lib | After running the code train(train_data, EPOCHS) I'm getting error "AttributeError: module 'tensorflow.python.distribute.input_lib' has no attribute 'DistributedDatasetInterface'" and after traching the error, it points at line 15--> of def train(data, EPOCHS): # Loop through epochs for epoch in range(1, EPOCHS+1): p... | Your error happens cuz there's mismatch between how you're trying to make prediction and what your dataset type allows. Tensorflow has changed some of its APIs across versions, please refer this this will help you to gain some knowledge about how actually perform distributed training Distributed training with TensorFlo... | 1 | 1 |
79,560,135 | 2025-4-7 | https://stackoverflow.com/questions/79560135/creating-new-rows-in-a-dataframe-based-on-previous-values | I have a dataframe that looks like this: test = pd.DataFrame( {'onset': [1,3,18,33,35,50], 'duration': [2,15,15,2,15,15], 'type': ['Instr', 'Remember', 'SocTestString', 'Rating', 'SelfTestString', 'XXX'] } ) I want to create a new dataframe such that when type contains "TestString", two new rows are created below tha... | You could use str.contains to identify the target rows, then Index.repeat to duplicate them, finally boolean indexing and groupby.cumcount to update the new rows: N = 3 # number of rows to create # identify target rows m = test['type'].str.contains('TestString') # repeat them out = test.loc[test.index.repeat(m.mul(N-1)... | 2 | 1 |
79,554,246 | 2025-4-4 | https://stackoverflow.com/questions/79554246/takeprofit-indie-displaying-labels-in-front-of-candlesticks | I'm working with the Indie library to create a candlestick pattern indicator, and I'm facing an issue with how labels are displayed on the chart. As you can see in the attached screenshot, the candlesticks are currently rendered on top of my pattern labels. What I need help with: Label Order: Is there a way to make t... | Now you can not change the z-index from the indicator code, but you can do it through the UI: Yes, you can adjust the transparency of labels in the same way as any other elements: color=indie.color.TEAL(alpha), for example: @plot.marker(color=color.GREEN(0.5), text='BE', style=plot.marker_style.LABEL, position=plo... | 4 | 2 |
79,559,256 | 2025-4-7 | https://stackoverflow.com/questions/79559256/django-queryset-annotate-sum-of-related-objects-of-related-objects | I have class Book(models.Model): title = models.CharField(max_length=32) class Table(models.Model): book = models.ForeignKey(Book, related_name='tables') class TableEntry(models.Model): table = models.ForeignKey(Table, related_name='entries') value = models.FloatField() and want a queryset of books that has annotated ... | You can annotate the prefetched Tables, like: from django.db.models import Prefetch, Sum Book.objects.prefetch_related( Prefetch('tables', Table.objects.annotate(sum=Sum('entries__value'))) ) If you then access a Book instance (named book for example), the book.tables.all() is a QuerySet of Tables with each an extra s... | 1 | 2 |
79,558,911 | 2025-4-7 | https://stackoverflow.com/questions/79558911/renaming-columns-names-in-polars | I want to change the column labels of a Polars DataFrame from ['#a', '#b', '#c', '#d'] to ['a', 'b', 'c', 'd'] | The following approach is most effective when renaming all columns that follow a consistent pattern, such as a common prefix or suffix. df.columns = [col.lstrip("#") for col in df.columns] Alternatively, the approach outlined below is most suitable when renaming specific columns or when no consistent pattern is presen... | 1 | 4 |
79,558,939 | 2025-4-7 | https://stackoverflow.com/questions/79558939/using-a-list-of-values-to-select-rows-from-polars-dataframe | I have a Polars DataFrame below: import polars as pl df = pl.DataFrame({"a":[1, 2, 3], "b":[4, 3, 2]}) >>> df a b i64 i64 1 4 2 3 3 2 I can subset based on a specific value: x = df[df["a"] == 3] >>> x a b i64 i64 3 2 But how can I subset based on a list of values? - something like this: list_of_values = [1, 3] y = df... | y = df.filter(pl.col("a").is_in(list_of_values)) Output: ┌─────┬─────┐ │ a ┆ b │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞═════╪═════╡ │ 1 ┆ 4 │ │ 3 ┆ 2 │ └─────┴─────┘ | 1 | 1 |
79,558,420 | 2025-4-6 | https://stackoverflow.com/questions/79558420/cookie-cannot-be-added-to-website-in-selenium | from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options import json import time service = Service(executable_path=f"chromedriver.exe", log_path=f"seleniumlog.txt") selenium_options = Options() selenium_options.add_argument("--disable-bli... | Your cookie won't add as it is expired. Update the time and it adds in fine: I used this: cookie = { 'domain': '.tiktok.com', 'expiry': 1744835794, # <-- updated here 'httpOnly': True, 'name': 'sessionid', 'path': '/', 'secure': True, 'value': 'abc123' } Cookies work on an epoch time. Which is number seconds since 1s... | 2 | 3 |
79,558,657 | 2025-4-6 | https://stackoverflow.com/questions/79558657/apply-1d-mask-on-numpy-3d-array | I have the following 3d-numpy.ndarray: import numpy as np X = np.array([ [[0.0, 0.4, 0.6, 0.0, 0.0], [0.6, 0.0, 0.0, 0.0, 0.0], [0.4, 0.0, 0.0, 0.0, 0.0], [0.0, 0.6, 0.0, 1.0, 0.0], [0.0, 0.0, 0.4, 0.0, 1.0]], [[0.1, 0.5, 0.4, 0.0, 0.0], [0.6, 0.0, 0.0, 0.0, 0.0], [0.2, 0.0, 0.0, 0.0, 0.0], [0.1, 0.6, 0.0, 1.0, 0.0], [... | Probably you can try X[:, ~idx,:][:,:, ~idx] or np.ix_ X[:, *np.ix_(~idx, ~idx)] which gives array([[[0. , 0.4, 0.6], [0.6, 0. , 0. ], [0.4, 0. , 0. ]], [[0.1, 0.5, 0.4], [0.6, 0. , 0. ], [0.2, 0. , 0. ]]]) | 2 | 2 |
79,558,025 | 2025-4-6 | https://stackoverflow.com/questions/79558025/efficient-and-readable-way-to-get-n-dimensional-index-array-in-c-order-using-num | When I need to generate an N-dimensional index array in C-order, I’ve tried a few different NumPy approaches. The fastest for larger arrays but less readable: np.stack(np.meshgrid(*[np.arange(i, dtype=dtype) for i in sizes], indexing="ij"), axis=-1).reshape(-1, len(sizes)) More readable with good performance: np.ascon... | Here is a (quite-naive) solution in Numba using multiple threads: import numba as nb @nb.njit( [ # Eagerly compiled for common types # Please add your type if it is missing '(int32[:,:], int32[:])', '(int64[:,:], int32[:])', '(float32[:,:], int32[:])', '(float64[:,:], int32[:])', ], parallel=True, cache=True ) def nb_k... | 4 | 5 |
79,557,758 | 2025-4-6 | https://stackoverflow.com/questions/79557758/how-can-i-implement-true-constants-in-python | I'm attempting to use real constants in Python—values which cannot be modified once defined. I realize Python has no native support for constants like certain other languages (e.g., final in Java or const in C++), but I want the most Pythonic or safest manner of achieving this behavior. class Constants: PI = 3.14159 G... | You're correct—Python natively supports neither true constants like C, C++, nor Java. There is no const keyword, and even the hack of creating variables in all caps (PI = 3.14) is completely dependent on developer discipline. Although workarounds such as metaclasses or special classes can be used to mimic immutability,... | 1 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.