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,594,143
2025-4-26
https://stackoverflow.com/questions/79594143/how-do-i-add-a-type-hint-for-a-writeablebuffer-parameter
I'm trying to add a parameter type to the readinto() method declared in a custom class that derives from RawIOBase, like this: from io import RawIOBase class Reader(RawIOBase): def readinto(self, buf: bytearray) -> int: pass # actual implementation omitted But pyright complains: io.py:6:9 - error: Method "readinto" ov...
You need to use the same type definition as your base. You can use the same type alias here by importing it from _typeshed package, provided you put it under a TYPE_CHECKING guard: from io import RawIOBase from typing import TYPE_CHECKING if TYPE_CHECKING: from _typeshed import MaybeNone, WriteableBuffer class Reader(R...
2
2
79,594,086
2025-4-26
https://stackoverflow.com/questions/79594086/using-classmethods-class-objects-and-generics-together-with-mypy
I use the following code to create subclasses of class G and pass them the type of model they should produce. from typing import TypeVar, Type class A: @classmethod def model_validate(cls): print('Done') T = TypeVar('T', bound=A) class G[T]: def __init__(self, model: Type[T]): self.model = model def func(self) -> None:...
You are mixing up two type variables. T = TypeVar... defines a typevar with bound, then G[T] completely disregards that, creates a new typevar (with no bound) and uses it. Either use old-style generics (playground): from typing import Generic, TypeVar class A: @classmethod def model_validate(cls) -> None: print('Done')...
1
1
79,593,724
2025-4-26
https://stackoverflow.com/questions/79593724/cant-tell-the-difference-between-two-python-n-queens-solutions
Reading up on backtracking led me to a page on geeksforgeeks.org about solutions to the n-queens problem. The first solution is introduced as the "naive approach" that generates all possible permutations and is the least efficient at O(n! * n). The second solution is "Instead of generating all possible permutations, we...
The difference is in the diagonal checks. The second, efficient version will know for a given square with O(1) time complexity whether it sits on any of the occupied diagonals. For this it makes use of the diag1 and diag2 lists, which have flags for each of the diagonals whether they are occupied or not. The less effic...
1
1
79,593,938
2025-4-26
https://stackoverflow.com/questions/79593938/while-testing-airflow-task-with-pytest-i-got-an-error
While testing airflow with pytest, i got an Error. # tests/conftest.py import datetime import pytest from airflow.models import DAG @pytest.fixture def test_dag(): return DAG( "test_dag", default_args={ "owner": "airflow", "start_date": datetime.datetime(2025, 4, 5), "end_date": datetime.datetime(2025, 4, 6) }, schedul...
The error occurs because your SampleDAG operator is failing during execution, which causes subsequent runs to fail due to the task's "failed" state. Let's fix this step by step: Key Issues in Your Code: Attribute Mismatch: You're using self.start_date and self.end_date in execute() but these attributes don't exist (yo...
1
2
79,593,773
2025-4-26
https://stackoverflow.com/questions/79593773/httpsconnectionpool-error-selenium-while-paste-3000-ids-from-column-in-a-csv-fi
I am using selenium to automate a downloading of a report. for that i need to paste around 3000 ids in a loop for ids around 300 000 into a input field of a webpage and click download button and wait around 40 secs to report to download. And after that click clear button to clear the input field and paste another 3000 ...
you're trying to paste 3000 IDs quickly into an input box using Selenium, but it hangs or throws HttpsConnectionPool errors (timeouts after 120 sec) only when IDs are many (like 3000), but works fine for small numbers (like 200). This is very common because: send_keys is very slow for huge text.The browser lags when pa...
1
1
79,593,216
2025-4-25
https://stackoverflow.com/questions/79593216/using-tkinter-colorchooser-erases-button-image-and-disables-button
I am making a simple Python GUI to allow the user to choose a color using Tkinter colorchooser. The user will click a button to open the colorchooser, and I'd like that button to have an image instead of text. However, after you use the colorchooser, the image is deleted from the button and the button is disabled. Any ...
The key fix is simply adding self. to store the PhotoImage as an instance variable instead of a local variable. The full code is provided below: import tkinter as tk from tkinter import colorchooser class MainGUI(tk.Tk): def __init__(self): super().__init__() addImage = r'add.png' self.addPhoto = tk.PhotoImage(file=add...
1
3
79,592,885
2025-4-25
https://stackoverflow.com/questions/79592885/fully-hide-margins-on-maps-added-to-streamlit
I want my leafmap map to occupy ALL the backgroud or main, without any margin or something to move it up, down, left or right. However, I still have margins at the top and bottom. Also, if I increase the height this creates a Y offset and I don't want that either but a static window fitted to the main or background spa...
Top margin is created by st.markdown() :) If I use st.html() (without unsafe_allow_html=True,) instead of st.markdown() then top margin disappears. (It seems st.html() was added in version 1.33.0 in Apr 2024 - so it may not be used in older tutorials) As for bottom margin - it needs height: 100vh (as suggested @Camilla...
1
1
79,592,530
2025-4-25
https://stackoverflow.com/questions/79592530/tkinter-listbox-has-a-shadow-selection-beside-the-proper-selection-how-to-syn
I built and populated a tkinter.Listbox. Now I have events that will select the item at index index. Like so: listbox.selection_clear(0, tk.END) listbox.select_set(index) And it works in that the entry with index index is in fact selected. However, when using 'tab' keys to move to other widgets that also have the powe...
That "shadow" designates the active item in the listbox. Think of it like a cursor in a text widget. You can set it with the activate method. If you want to hide it altogether you can set activestyle='none'. Or, you can set it when you set the selection: ... lb = tk.Listbox(...) ... lb.selection_set(4,6) lb.activate(4)...
1
3
79,591,814
2025-4-25
https://stackoverflow.com/questions/79591814/why-does-python-disallow-chaining-descriptors-classmethod-and-property-sin
(I know that there are similar questions already answered, but my question focuses more on the reason behind the solution instead of the solution itself). I have been in need of something like a "class property" in Python, and I have searched through existing questions. Some answers provide a workaround, but I cannot u...
Class property was deprecated in Python 3.11 (with link to the original issues) because it was found to be impossible for a chain of @classmethod and @property-decorated attribute to be seen by inspection code as an instance of property. If you need a class property to work on an instance then a custom classproperty is...
3
4
79,592,059
2025-4-25
https://stackoverflow.com/questions/79592059/why-use-super-to-call-functions
I am currently down the rabbit hole trying to understand metaclasses and as such went back to refresh my understanding of super() and type. While refreshing I came across a geeksforgeeks super() article and it had a rather weird example. here is the example class Animals: # Initializing constructor def __init__(self): ...
Yes. In this case, since neither the overloading __init__ nor isMammal do anything (besides calling their parent implementations), they could just be omitted for the same result: class Dogs(Animals): pass Here the parent methods would simply be inherited and do exactly the same thing. But if you want to use the parent...
1
4
79,590,117
2025-4-24
https://stackoverflow.com/questions/79590117/dtypewarning-columns-have-mixed-types-error-in-pandas-when-loading-csv
When loading a csv file in pandas I've encountered the bellow error message: DtypeWarning: Columns have mixed types. Specify dtype option on import or set low_memory=False Reading online I found few solutions. One, to set low_memory=False, but I understand that this is not a good practice and it doesn't really resolve...
if not x checks if x is an empty string. if it is empty it returns '', which is an empty string without any content. def convert_dtype(x): if not x: return '' try: return str(x) tries to convert and return x as a string. try: return str(x) if converting and returning x as a string doesn't work, it returns ''. excep...
1
3
79,591,853
2025-4-25
https://stackoverflow.com/questions/79591853/z-score-on-scipy
I need to find out the Zscore pertaining to 1 specific point, that is, for 1 value of X using Scipy. Below is the manual code: data = [25, 37, 15, 36, 92, 28, 33, 40] mean = sum(data)/len(data) summation = 0 for i in range(0, len(data)): summation += (data[i]-mean)**2 std = ((1/len(data))*summation))**(1/2) Z = (x-mean...
This solution might be suitable for you. This solution might be better than others. from scipy import stats import numpy as np data = [25, 37, 15, 36, 92, 28, 33, 40] x = 40 # Please assign a specific value mean = np.mean(data) std = np.std(data, ddof=0) Z = (x - mean) / std print(Z) You might like this method also (s...
2
2
79,591,383
2025-4-24
https://stackoverflow.com/questions/79591383/pandas-fill-in-missing-values-with-an-empty-numpy-array
I have a Pandas Dataframe that I derive from a process like this: df1 = pd.DataFrame({'c1':['A','B','C','D','E'],'c2':[1,2,3,4,5]}) df2 = pd.DataFrame({'c1':['A','B','C'],'c2':[1,2,3],'c3': [np.array((1,2,3,4,5,6)),np.array((6,7,8,9,10,11)),np.full((6,),np.nan)]}) df3 = df1.merge(df2,how='left',on=['c1','c2']) This lo...
A possible solution: # the array with the 6 nan values arr_nan = np.full( df3['c3'].map( lambda x: np.size(x) if isinstance(x, np.ndarray) else 0).max(), np.nan) df3.assign(c3 = df3['c3'].map( lambda y: arr_nan if not isinstance(y, np.ndarray) else y)) This solution first determines the length of the arrays in c3, and...
2
1
79,590,866
2025-4-24
https://stackoverflow.com/questions/79590866/how-to-make-a-reactive-event-silent-for-a-specific-function
I have the app at the bottom. Now, I have this preset field where I can select from 3 options (+ the option changed). What I want to be able to set the input_option with the preset field. But I also want to be able to change it manually. If I change the input_option manually the preset field should switch to changed. T...
Require (req()) input.input_option() != input.input_preset() for doing the update on the preset input: from shiny import App, ui, reactive, req app_ui = ui.page_fillable( ui.layout_sidebar( ui.sidebar( ui.input_select("input_preset", "input_preset", choices=["A", "B", "C", "changed"]), ui.input_text("input_option", "in...
2
1
79,591,058
2025-4-24
https://stackoverflow.com/questions/79591058/does-this-leapfrog-method-work-for-the-3-body-problem
I have been trying to make a leapfrog integration to document the variation of the hamiltonian over time for the 3BP, but I never really grasped how to implement it using the normal half-step method so I tried using a variation but I'm not sure if it's correct. This is the functions I'm using where the variables p, v, ...
Corrected implementation import numpy as np from numpy.linalg import norm from copy import deepcopy def H(p, v, m): # hamiltonian function # sum of kinetic energy for all bodies T = sum([m[i] * norm(v[i])**2 / 2 for i in range(3)]) # sum of potential energy between all unique pairs V = -sum([m[i] * m[j] / norm(p[i] - p...
1
1
79,590,908
2025-4-24
https://stackoverflow.com/questions/79590908/alternative-to-looping-over-one-numpy-axis
I have two numpy arrays a and b such that a.shape[:-1] and b.shape are broadcastable. With this constraint only, I want to calculate an array c according to the following: c = numpy.empty(numpy.broadcast_shapes(a.shape[:-1],b.shape),a.dtype) for i in range(a.shape[-1]): c[...,i] = a[...,i] * b The above code certainly...
Use np.newaxis with ... to add a new axis after your last axis. c = a * b[..., np.newaxis] Which is the same as c = a * b[np.newaxis, :] You don't need to allocate space for c in advance btw.
2
3
79,589,564
2025-4-23
https://stackoverflow.com/questions/79589564/is-it-possible-to-limit-attributes-in-a-python-sub-class-using-slots
One use of __slots__ in Python is to disallow new attributes: class Thing: __slots__ = 'a', 'b' thing = Thing() thing.c = 'hello' # error However, this doesn’t work if a class inherits from another slotless class: class Whatever: pass class Thing(Whatever): __slots__ = 'a', 'b' thing = Thing() thing.c = 'hello' # ok ...
If you are willing to use a metaclass, you can prevent this. Simply insert an empty sequence for '__slots__' in the namespace returned by __prepare__ this is a hook that prepares the namespace that will be used for the class, it defaults to a normal dict(), and we can just force the subclass to have an empty (not unspe...
2
1
79,590,476
2025-4-24
https://stackoverflow.com/questions/79590476/darts-and-lightgbm-original-column-names-cannot-be-retrieved-for-feature-import
Problem I am running a LightGBMModel via Darts with some (future) covariates. I want to understand the relevance of the different (lagged) features. In particular, I would like to retrieve the feature importance for the lagged target variable as well as for the covariates using the original column names from the Darts ...
The features that go into the models are available in model.lagged_feature_names. One of the authors addressed feature importances in Issue#1826, doing mostly what you've done, but they also referenced that along with a note about the feature names in Issue#2125.
2
0
79,590,120
2025-4-24
https://stackoverflow.com/questions/79590120/mypy-complains-about-missing-return-when-the-function-implicitly-returns-none
So, my question is regarding a code that looks like this: def f(condition: bool) -> int | None: if condition: return 1 def g(condition: bool) -> int | None: if condition: return return 1 This is clearly valid python code, the idea is that the function will try to do something, if it succeeds it will return the result,...
Provide an explicit return statement when the if statement does not match in the first function and explicitly return None in the second function: def f(condition: bool) -> int | None: if condition: return 1 return None def g(condition: bool) -> int | None: if condition: return None return 1 fiddle If you want to sil...
2
4
79,590,095
2025-4-24
https://stackoverflow.com/questions/79590095/find-points-in-curve
Can you share some ideas of how to find curve points (orange color marked places) like shown in picture: I've tried this code: result = [] for i in range(len(df)): if i == 0 or df['y'].iloc[i] != df['y'].iloc[i - 1]: result.append(df.iloc[i]) continue if i < len(df) - 1 and df['y'].iloc[i] != df['y'].iloc[i + 1]: resu...
Here is the full code: import numpy as np import matplotlib.pyplot as plt from scipy.signal import argrelextrema time = np.arange(0, 2200, 100) values = np.array([ -0.1, 0, 0.13, 0.27, 0.27, 0.4, 0.27, 0.27, 0.13, 0.13, 0.01, 0.01, -0.13, -0.13, -0.27, -0.4, -0.4, -0.27, -0.13, -0.13, 0, 0 ]) x = np.arange(0, 2200, 1) ...
2
2
79,588,998
2025-4-23
https://stackoverflow.com/questions/79588998/how-to-prevent-error-on-shutdown-with-logging-handler-qobject
In order to show logging messages in a PyQt GUI, I'm using a custom logging handler that sends the logRecord as a pyqtSignal. This handler inherits from both QObject and logging.Handler. This works as it should but on shutdown there's this error: File "C:\Program Files\Python313\Lib\logging\__init__.py", line 2242, i...
This may be caused by the multiple inheritance. I coincidentally just learned that PyQt6 works differently than PyQt5, affecting the way attributes that exist on the Qt side may be accessed. Since by default the flushOnClose attribute does not exist (it's only created for some subclasses, such as MemoryHandler), getatt...
2
0
79,587,363
2025-4-22
https://stackoverflow.com/questions/79587363/format-np-float64-without-leading-digits
I need to format np.float64 floating values without leading digits before the dot, for example -2.40366982307 as -.240366982307E+01, in python. This is to allow me to write in RINEX 3.03 the values with 4X, 4D19.12 formats. I have tried f"{x:.12E}" but it always has a leading 1 for numbers greater than 1. I have also t...
I would go for something custom designed from scratch. I agree, however, I did not think about all the marginal cases that can occur. # Format a floating-point number to RINEX format def format_rinex(value): if not np.isfinite(value): return f"{value}" sign = '-' if value < 0 else ' ' abs_value = np.abs(value) exponent...
1
2
79,589,020
2025-4-23
https://stackoverflow.com/questions/79589020/switching-to-iframe-with-rotating-id-selenium
I am trying to access the login iframe from https://www.steelmarketupdate.com/. Previously I was able to access this via XPATH client.switch_to.frame(client.find_element(By.XPATH, "/html/body/div[6]/div/iframe")) However this is no longer working. I found the length of all iframe elements to be 6, and I am unable to a...
Try this: # This relative XPath expression locates the <iframe> element which contains value piano in the ID attribute By.XPATH, "//iframe[contains(@id,'piano')]" or this: # This is an XPath expression which locates the 3rd <iframe> element from top of the DOM By.XPATH, "(//iframe)[3]" Full line of code: client.switc...
2
1
79,588,678
2025-4-23
https://stackoverflow.com/questions/79588678/optimum-selection-mechanism-when-choosing-relevant-rows-from-a-dataframe
I have a large Excel spreadsheet. I'm only interested in certain columns. Furthermore, I'm only interested in rows where specific columns meet certain criteria. The following works: import pandas as pd import warnings # this suppresses the openpyxl warning that we're seeing warnings.filterwarnings("ignore", category=Us...
You can certainly chain all your commands to avoid using intermediate variables, and combine all filters into a single expression (for example defining the condition in a col:regex dictionary and using loc with numpy.logical_and.reduce): conditions = {'A': r'\bFOO\b', 'B': r'\bBAR\b'} (pd.read_excel(XL, sheet_name=SHEE...
1
2
79,588,208
2025-4-23
https://stackoverflow.com/questions/79588208/why-does-strftimey-not-yield-a-4-digit-year-for-dates-1000-ad-in-python
I am puzzled by an inconsistency when calling .strftime() for dates which are pre-1000 AD, using Python's datetime module. Take the following example: import datetime old_date = datetime.date(year=33, month=3, day=28) # 28th March 33AD old_date.isoformat() >>> "0033-03-28" # Fine! old_date.strftime("%Y-%m-%d") >>> "33-...
This is caused by the implementation of .strftime() in the C library in Linux omitting any leading zeros from %Y and %G. The related issue in CPython's issue tracker is here. Thanks to jonrsharpe's comment for the answer, and highlighting this section of the documentation: "The full set of format codes supported varie...
7
1
79,587,390
2025-4-22
https://stackoverflow.com/questions/79587390/plt-contour-plots-series-of-lines-instead-of-a-contour-line
I aim to plot a contour plot of flux, but instead of closed contour curves, plt.contour() returns a series of lines with the same height. Psi is defined as a np.array and has a 320 by 200 shape. fig, ax = plt.subplots() r_end = grid_start[0] + grid_step[0] * grid_size[0] z_end = grid_start[1] + grid_step[1] * grid_size...
I think that your original data is a different size: maybe 3200 by 20, not 320 by 200. (You should check). The datafile does have 320 rows of 200 columns, but I suspect that is an artefact: maybe they were simply limited by line length. If I reshaped to 3200 by 20 then this is what I get: import numpy as np import ma...
1
1
79,586,803
2025-4-22
https://stackoverflow.com/questions/79586803/how-can-i-view-the-xpath-of-a-selected-element
I'm checking for a user on a web interface and clicking an edit button in the corresponding table, but the button and table itself are identical and therefore not uniquely identifiable. I can find the text in the table, so my approach was to grab the xpath where that's found, and derive the button's xpath from that. Th...
You can nest element with text in [] to search its parent tr and later you can search label in this parent. '//tr[td[contains(text(), "SeleniumTest")]]//label' You may also use following-sibling::td to search next td '//td[contains(text(), "SeleniumTest")]/following-sibling::td/label' Full working code with example...
2
2
79,587,773
2025-4-23
https://stackoverflow.com/questions/79587773/python-file-behaviour-different-when-run-from-different-ides
A colleague and I were reviewing some student submissions. He likes using IDLE, while I use PyCharm. The student developed their code in PyCharm. A simplified example of the students work is: file = open('test_file.txt','w') file.write('This is a test file.') print('Completed') exit() The student has made an error in ...
IDLE leaves the interpreter running after executing the code. You can go back to the Shell and inspect variables, for example. If you exit idle or restart the shell (Ctrl-F6) the interpreter exits (or restarts) and the file will be flushed and closed. Without restarting the shell, the file will still be open and cached...
1
2
79,587,407
2025-4-22
https://stackoverflow.com/questions/79587407/read-data-from-sheet1-and-output-filtered-data-on-sheet2
Is it possible? Or it seems that each sheet is a separate environment? CONTEXT: A clean way to read 200 rows of data (and 30+ columns) is using something like df=xl("A:BS", headers=True) So a user wants a filtered view of my data on sheet2. e.g., df[df['project'] =='bench'] (and despite that one can use Excel filter bu...
You can do something like import pandas as pd df = Excel("Data!A:AD", headers=True) filtered_df = df[df['project'] == 'bench'] filtered_df
1
2
79,586,324
2025-4-22
https://stackoverflow.com/questions/79586324/star-center-of-a-star-convex-shape
I'm working with 2D shapes represented by their boundary contours (as ordered x,y coordinates), and I want to check if a shape is star-convex. If it is, I'd like to find a star center — i.e., a point from which the entire shape is visible (meaning: every line segment to every boundary point lies entirely within the sha...
I think you can do this by linear-programming. Every CONVEX corner of your figure will give you a triangular wedge in which any solution must lie. In this wedge the X,Y point which is hopefully the centre must differ from the corner node by a combination of positive multiples of the two side vectors. i.e. or You the...
1
2
79,587,273
2025-4-22
https://stackoverflow.com/questions/79587273/tkinter-cant-delete-something-from-a-canvas-on-ubuntu
I created a programm on python to read serial data from an arduino and show it on a tkinter window. I made a Thread to read the from the arduino and the tkinter programm. My Programm runs perfectly on windows but the problem is that i want to use it on my ubuntu laptop and there it doesn't work. It works ok but there a...
The problem probably isn’t with your delete_Text() function itself, but more with how you're using threads with tkinter. In tkinter, you can’t call methods like canvas.delete, canvas.create_text, label.config, and so on, from a thread other than the main thread. I had a similar issue myself — everything worked fine on ...
1
2
79,586,415
2025-4-22
https://stackoverflow.com/questions/79586415/udf-returning-ljava-lang-object
I have a PySpark UDF which when I try to apply to each row for one of the df columns and get a new column, I get a [Ljava.lang.Object;@7e44638d (different value after the @ for each row) Please see the udf below: def getLocCoordinates(property_address): url = "https://maps.googleapis.com/maps/api/geocode/json" querystr...
I think that you're seeing the [Ljava.lang.Object;@... output because your UDF is returning a Python tuple ((lat, lng)), and PySpark doesn't know how to serialize that into a DataFrame column unless you explicitly define a return schema that Spark understands. You should return a StructType with fields for lat and lng....
1
2
79,585,895
2025-4-22
https://stackoverflow.com/questions/79585895/can-i-get-pycharm-to-accept-a-python-interpreter-not-named-python
My project has an executable called powerscript.exe, which is a Python interpreter that does and knows some extra things. This is out of my control, I can not change this. From the command line I can use this as a drop-in replacement for the Python interpreter. In PyCharm I cannot. Adding this thing as a Python interpr...
Since it's apparent that PyCharm validates only the name of the executable, you can make a copy of the wrapper executable powerscript.exe and rename the copy to python.exe as an interpreter for PyCharm.
1
2
79,605,626
2025-5-4
https://stackoverflow.com/questions/79605626/flask-cant-see-html-file
Based on the data given here : https://www.kaggle.com/code/bhavikjikadara/loan-status-prediction-decisiontreeclassifier/input i want to make flask based ML model prediction for loan status, here is my html code and screenshot <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Prediction of Loan Statu...
The reason why you get a 404 Not Found error on the / page is simply that you didn't register any handler for this route. If you try to access /prediction you should find your page. Another point is that your HTML template (by default) must be in the templates directory. So to fix your application you should have somet...
1
2
79,607,676
2025-5-5
https://stackoverflow.com/questions/79607676/making-solveset-solutions-rational-in-sympy
I'm trying to solve a cubic with a parameter r, for x. The cubic is the awful expression poly = b*(-(10 + x)*b - 10*b) - ((8/3) + x)*((10+x)*(1+x) - 10) where b = sp.sqrt((8/3)*(1 - a)) which factors out to x^3 + (41/3)x^2 + (8/3)(a + 10)x + (160/3)(a - 1). SymPy's solveset() gives a solution, but it is really long m...
If you import S and use S(8)/3 instead of 8/3 you will get fractions instead of floats...but it will still be complicated. You can also use cse to give a symbolically simpler substituted expression: ...your code >>> from sympy import cse >>> cse(solve(polyeq,x)) [(x0, 8*a + 817/9), (x1, (-556*a + sqrt(-4*x0**3 + (70450...
1
1
79,607,320
2025-5-5
https://stackoverflow.com/questions/79607320/i-cant-see-the-custom-button-i-created-in-the-header-of-the-list-in-my-module-i
I've created a module in odoo18 and in that I created a xml called product_views. It has a list in it. I added a button in the header of the list but I can't see it. Here is my xml file: <?xml version="1.0" encoding="utf-8"?> <odoo> <record id="view_product_list" model="ir.ui.view"> <field name='name'>"electronic.produ...
Actually, your code works, the button does appear. I assume that, you didn't know that in Odoo, for general, buttons that used in the tree/list view don't always show, they only appear when any data is selected. So, if I don't select any data, you can see on the picture below, the "import" button of yours will disappe...
1
1
79,606,481
2025-5-5
https://stackoverflow.com/questions/79606481/how-to-add-editable-text-layer-to-a-photoshop-psd-file-using-python
I have a very simple use case where I need to pack a PNG file and a text layer into a PSD file and save it. That's it. I have tried psd-tools for it and so far it works in principle. The problem is that the text layer that it creates is not editable. The text layer itself is added as an image (transparent background) s...
I think the perfect answer to this Question is the description from OP mentioned alternative editors. My boldening for emphasis https://docs.krita.org/en/general_concepts/file_formats/file_psd.html .psd, unlike actual interchange formats like *.pdf, *.tiff, *.exr, *.ora and *.svg doesn’t have an official spec online. ...
1
1
79,607,412
2025-5-5
https://stackoverflow.com/questions/79607412/how-can-i-provide-type-hints-while-destructuring-my-class
I would like to create a class that looks something like ConfigAndPath: import pathlib from typing import TypeVar, Generic from dataclasses import dataclass, astuple class ConfigBase: pass T = TypeVar("T", bound=ConfigBase) @dataclass class ConfigAndPath(Generic[T]): path: pathlib.Path config: T I often have a list of...
You can destructure a dataclass using a match block (requires python ≥ 3.10). It is more verbose, but type checkers understand it. For example, using mypy: @dataclass class Foo(Generic[T]): x: int y: T foo = Foo[float](1, 2.0) match foo: # NB. this case means must be an object, and have an attribute x and attribute y, ...
1
0
79,607,498
2025-5-5
https://stackoverflow.com/questions/79607498/why-does-my-python-function-not-properly-cast-the-dates-despite-recognizing-the
I am attempting to dynamically cast various date formats that come across as a string column but are actually dates. I've gotten pretty far, and this code can correctly identify the dates from the string, but the fields 'Date2' and 'Date3' always return as null values. I can't understand why that is, or how to correct ...
The issue is that while your convert_value function correctly identifies the date format using Python’s datetime.strptime...PySpark’s cast(DateType()) doesn't support this format unless it matches Spark's expected patterns (usually 'yyyy-MM-dd'). As a result, Date2 and Date3 return null because their formats (e.g. '01-...
3
5
79,600,488
2025-4-30
https://stackoverflow.com/questions/79600488/square-api-for-invoice-attachments-received-multiple-request-parts-please-only
The new square api versions 42+ have breaking changes. Im trying to upgrade to ver v42, and I am testing in a local dev environment. I keep getting the following error: *** square.core.api_error.ApiError: status_code: 400, body: {'errors': [{'category': 'INVALID_REQUEST_ERROR', 'code': 'INVALID_CONTENT_TYPE', 'detail':...
Docs should read something like this: Uploads a file and attaches it to an invoice. This endpoint accepts HTTP multipart/form-data file uploads with a JSON request part and a image_file part. The image_file part must INCLUDE a readable stream in the form of a file (or bytes) [supported formats: GIF, JPEG, PNG, TIFF, BM...
2
0
79,606,838
2025-5-5
https://stackoverflow.com/questions/79606838/qlistwidget-drag-and-drop-configuration-when-to-use-the-mode-instead-of-the-dra
I'm learning how to setup drag and drop in the view-model framework description at Qt site. When applied to convenience views (QListWidget, QTableWidget, QTreeWidget), the documentation uses either (in original C++ version): listWidget->setDragEnabled(true); listWidget->viewport()->setAcceptDrops(true); or: listWidget...
We can look at the source of the getter and setter of dragDropMode property: void QAbstractItemView::setDragDropMode(DragDropMode behavior) { Q_D(QAbstractItemView); d->dragDropMode = behavior; setDragEnabled(behavior == DragOnly || behavior == DragDrop || behavior == InternalMove); setAcceptDrops(behavior == DropOnly ...
2
5
79,606,651
2025-5-5
https://stackoverflow.com/questions/79606651/how-can-i-use-a-wx-filedialog-to-select-a-file-which-is-locked-by-another-proces
I'm trying to use the wx.FileDialog class to select the name of a file. I don't want to open it. This is a minimal example of what I'm trying to do: import wx if __name__ == '__main__': app = wx.App(redirect=False) frame = wx.Frame(None) frame.Show() dlg = wx.FileDialog(parent=frame, style=wx.FD_OPEN|wx.FD_FILE_MUST_EX...
Unfortunately it looks like this is currently impossible because wxWidgets doesn't set FOS_SHAREAWARE flag and so doesn't customize the default handling of locked files — which is to do what you see. It should be relatively straightforward to implement support for this in wxWidgets itself and, as it's an open source li...
1
2
79,606,665
2025-5-5
https://stackoverflow.com/questions/79606665/extract-header-from-the-first-commented-line-in-numpy-via-numpy-genfromtxt
My environment: OS: Windows 11 Python version: 3.13.2 NumPy version: 2.1.3 According to NumPy Fundementals guide describing how to use numpy.genfromtxt function: The optional argument comments is used to define a character string that marks the beginning of a comment. By default, genfromtxt assumes comments='#'. The ...
Thanks to what @mehdi-sahraei suggested, I changed the dtype to None and this permitted to parse other rows (any row after the header line) correctly. Finally, it seems that there is no bug about how the header line is treated but rather a lack of clarity in the documentation. As indicated in my original post, the docu...
4
0
79,606,785
2025-5-5
https://stackoverflow.com/questions/79606785/select-a-range-of-data-based-on-a-selected-value-using-pandas
I have a dataframe, I need to select a range of data based on a month value, but the result expected is always showing six rows where the month selected appears in the filtered data , here's the code : import pandas as pd data = { "function": ["test1","test2","test3","test4","test5","test6","test7","test8","test9","tes...
If there is default index is possible select by DataFrame.loc: selected_month_idx = df[df["month"] == selected_month].index[0] start = np.clip(selected_month_idx, 0, len(df) - 6) six_month_window = df.loc[start : start + 5] print(six_month_window) If always match value in condition, get position of first True by np.ar...
3
1
79,606,560
2025-5-5
https://stackoverflow.com/questions/79606560/which-class-accurately-represents-a-websocket-connection
I have come across multiple ways to describe a websocket connection object while using the websockets library in python but can't seem to understand which way to go. In the documentation, the code to start a server is very simple. import asyncio from websockets.asyncio.server import serve async def hello(websocket): na...
No need to apologize — your question is valid, and it’s clear you’re trying to understand how the websockets library works. That’s awesome! So, here’s what’s going on: When you define async def hello(websocket), the websocket parameter is the connection object to the client. Specifically, if you’re using websockets.asy...
1
1
79,606,646
2025-5-5
https://stackoverflow.com/questions/79606646/using-logical-operators-in-pytest-expected-results
I'm trying to develop pytest for a project, and while I'm not the most familiar with pytest I feel like I have a fairly basic understanding. In this particular case I am testing some code that does route optimization and I wish to implement a bunch of different tests to ensure that the code performs as it should. To he...
I suggest going with this approach: instead of overriding the __eq__ method in your dataclass, it’s better to create a separate comparison function where you can pass in custom check rules for each field. This is especially helpful when different test scenarios require different validation logic — like in one case, you...
1
1
79,604,901
2025-5-3
https://stackoverflow.com/questions/79604901/surrounding-whitespace-separated-urls-with-quotes-using-sed
Problem I was trying to get sed command to do the same thing I could do with Python regex flavour, but I encountered some problems Python regex example: (tested it on regex101 and it was working fine) find: (https.*?) replace: "\1" Unsuccessful code: sed 's/\(https.*?\)[:space:]/\"\1\"/g' .\elenco.txt elenco.txt file...
Ahoy! Its pretty trivial to do something like this in Perl. I donno 200mb these days seems pretty small. You can even do this with Windows Subsystems for Linux or WSL. Install WSL, run bash from a command prompt, then sudo apt install perl. I use WSL from the command line in Windows all the time. Its very small and inc...
2
2
79,606,201
2025-5-5
https://stackoverflow.com/questions/79606201/how-to-update-a-leaf-variable-in-pytorch
I am trying to implement simple gradient descent to find the root of a quadratic equation using PyTorch. I'm doing this to get a better sense of how the autograd function works but it's not going very well. Let's say that I want to find the roots of y = 3x^2 + 4x + 9 as a random example. Below was my first attempt to r...
In-place operations like x -= ... can break the computation graph if the tensor is a leaf tensor that requires gradients, and the operation is not inside a torch.no_grad() context. This causes a version mismatch error during .backward() if you try to reuse the computation graph or modify variables that are part of it. ...
1
3
79,604,883
2025-5-3
https://stackoverflow.com/questions/79604883/is-there-anything-i-need-to-do-to-make-session-data-persistent-across-routes-in
I am working with a Flask project with React as front-end. I just completed the authentication work. When i tried to access the user_id which i stored in session as 'user_data' from another route via an 'axios' request, I wasn't able to access it as it said 'No data found in session'. I have encountered some like these...
You should familiarize yourself with the Same Site Policy. This is likely responsible for rejecting session data in the backend. You can either use a proxy in the background or use third-party cookies. You define a proxy in the package.json file when using "Create React App". This forwards requests to the frontend serv...
2
0
79,605,214
2025-5-4
https://stackoverflow.com/questions/79605214/frida-how-to-send-byte-array-from-javascript-to-python
I have a Frida JS script inside a Python session, and I'm trying to pass an array of bytes (from a Bitmap image) from the JavaScript environment back to the Python environment. Here is my attempt: import frida import sys import os JS_SCRIPT = ''' setTimeout(function () {{ Java.perform(function () {{ // declare dependen...
Frida provides out of the box only methods for sending native byte arrays, thus raw data stored in ArrayBuffer or data at a certain NativePointer. Sending Java byte arrays in an efficient way requires a bit more work as you first have o convert the byte[] into a form that can b serialized by send(). The most simplest a...
1
1
79,605,465
2025-5-4
https://stackoverflow.com/questions/79605465/no-module-named-pip-in-venv-but-pip-installed
I work in WSL Ubuntu. After instalation python3.13 dependencies from my previous projects stopped working. Venv with python 3.12 stopped activate in vscode interface. ErrorMessage: An Invalid Python interpreter is selected, please try changing it to enable features such as IntelliSense, linting, and debugging. See out...
I ran into the exact same problem after installing Python 3.13 on WSL. Suddenly, all my existing virtual environments (created with Python 3.12) broke in VSCode. I was getting the "Invalid Python interpreter" error, Pylance couldn't resolve any imports, and pip appeared to be missing—even though I could see it in the v...
4
3
79,604,226
2025-5-2
https://stackoverflow.com/questions/79604226/performance-of-list-extend-slice-vs-islice
It seems that even when islice would theoretically be better, in practice, it is slower than just using slice. So I am a bit puzzled by the difference in performance between the usage of slice and islice here: from time import perf_counter from itertools import islice from random import choices from string import ascii...
The additional iteration layer of islice is far more costly than the string slices. Allocation optimization by length hint is insignificant, at least on the three systems where I tried this. With the string slices, the extend method iterates directly over the string (slice). With islice, it instead iterates over the is...
5
1
79,604,815
2025-5-3
https://stackoverflow.com/questions/79604815/creating-a-list-of-integer-lists-that-have-a-fixed-length-and-contain-integers-t
I am trying to write some code that will generate all lists of a fixed length that have the property that the next integer in each list will either be same or an increment of the previous integer. All lists should start with 0. I can write code that does this for size 4 BUT it uses 3 nested loops. If I want to continue...
I am providing you several solutions. I think you may like one. First: from itertools import product def generate_sequences(n, x=0): if n == 0: return [] deltas = product([0, 1], repeat=n-1) sequences = [] for delta_seq in deltas: sequence = [x] current = x for delta in delta_seq: current += delta sequence.append(curre...
2
2
79,603,414
2025-5-2
https://stackoverflow.com/questions/79603414/unexpected-keyword-in-createsuperuser-django
I am working with BaseAbstractUser and AbstractUser, and I have a problem with a required field. models.py from django.db import models from django.conf import settings from django.contrib.auth.models import User, AbstractBaseUser, BaseUserManager from django.utils.timezone import timedelta, now from django.core.except...
Add a role='admin' parameter to the create_superuser(..) method, we can add an extra check that it is indeed admin: class CustomUserManager(BaseUserManager): def create_user(self, email, password=None, role="customer", **kwargs): if not email: raise ValueError("Users must have an email address") user = self.model(email...
1
2
79,604,283
2025-5-3
https://stackoverflow.com/questions/79604283/palindromes-and-string-slicing-performance
There are a lot of ways to check if string is a palindrome. Plenty of them listed here This question is not about "how" but rather about performance. I was assuing that is_palindrome should be twice faster than is_palindrome0 because it does len/2 iterations in the worst case. However, in reality, is_palindrome takes m...
is_palindrome0 (the fast one) s[::-1] uses C-level optimizations under the hood (it's implemented in highly efficient C code in CPython). String comparisons (==) are also optimized for short-circuiting; they stop early if a mismatch is found. The entire operation is happening in compiled code with no explicit Python lo...
3
8
79,604,132
2025-5-2
https://stackoverflow.com/questions/79604132/pil-image-by-writing-a-matplotlib-figure-to-bytesio-buffer-not-working
A function I am working on takes a dictionary with some data, plots based on the data to axes of a noninteractive matplotlib figure (so without showing it) and renders that figure to an PIL image that is saved to the dictionary. The updated dictionary is returned. That returned dictionary is converted to a pandas.DataF...
It gives error ValueError: I/O operation on closed file. because open() is "lazy" and it doesn't load it at once but when you try to use image - but you try to display it after leaving with io.BytesIO() as buffer: and buffer is already closed and it can't read from buffer. You may use .load() to force it to load image:...
1
1
79,604,183
2025-5-2
https://stackoverflow.com/questions/79604183/pandas-time-series-dataframe-take-random-samples-by-group-date-ignore-missing
I have a time series dataframe, I would like to take x random samples from column "temperature" from each day. I am able to do this with: daily_groups = df.groupby([pd.Grouper(key='time', freq='D')])['temperature'].apply(lambda x: x.sample(10)) This works if there are at least x samples for each day. If there are not ...
If you want to randomly sample values from the "temperature" column for each day, up to 10 values per day, but also want to handle days with fewer than 10 entries, here's my suggestion on how to do it. This code checks how many rows there are per day — if there are fewer than 10, it just takes as many as possible. If t...
2
1
79,604,129
2025-5-2
https://stackoverflow.com/questions/79604129/how-can-i-annotate-a-function-that-takes-a-union-and-returns-one-of-the-types-i
Suppose I want to annotate this function: def add_one(value): match value: case int(): return value + 1 case str(): return value + " and one more" case _: raise TypeError() I want to tell the type checker "This function can be called with an int (or subclass) or a str (or subclass). In the former case it returns an in...
One solution I can think of is to mix attempts 2, 3 and 4: (playgrounds: Mypy, Pyright) @overload def add_one[T: (str, int, bytes)](value: T) -> T: ... @overload def add_one[T: str | int | bytes](value: T) -> T: ... def add_one(value: str | int | bytes) -> str | int | bytes: ... class S(StrEnum): A = '' class I(IntEnu...
2
2
79,604,001
2025-5-2
https://stackoverflow.com/questions/79604001/pandas-memory-issue-when-apply-list-to-groupby
I am doing the below but getting memory issues. make frame data = {'link': [1,2,3,4,5,6,7], 'code': ['xx', 'xx', 'xy', '', 'aa', 'ab', 'aa'], 'Name': ['Tom', 'Tom', 'Tom', 'Tom', 'nick', 'nick', 'nick'], 'Age': [20,20,20,20, 21, 21, 21]} # Create DataFrame df = pd.DataFrame(data) print(df) output link code Name Age 0...
Your method is inefficient as it explodes then drops the duplicates. Ensure to drop the duplicates first then merge: d = df.mask(df.eq(''))[['code', 'Name', 'Age']].drop_duplicates() df.merge(d, how = 'outer', on = ['Name', 'Age']).dropna(subset='code_y') link code_x Name Age code_y 0 1 xx Tom 20 xx 1 1 xx Tom 20 xy 3 ...
1
1
79,603,555
2025-5-2
https://stackoverflow.com/questions/79603555/how-to-set-a-fixed-random-state-in-randomizedsearchcv
I'm using RandomizedSearchCV with RandomForestClassifier in scikit-learn. I want to make sure my results are reproducible across runs. Where should I set the random_state—in the classifier, in RandomizedSearchCV, or both? Example code: from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection imp...
You can perform a simple test using as a starter code given in the RandomizedSearchCV examples. In the code, a random_state is set both, in the classifier, as well as in the RandomizedSearchCV. Writing a loop with let's say 50 iterations and printing outcomes, that is .best_params_ will show the following: setting ran...
2
2
79,603,499
2025-5-2
https://stackoverflow.com/questions/79603499/training-a-custom-tokenizer-with-huggingface-gives-weird-token-splits-at-inferen
So I trained a tokenizer from scratch using Huggingface’s tokenizers library (not AutoTokenizer.from_pretrained, but actually trained a new one). Seemed to go fine, no errors. But when I try to use it during inference, it splits words in weird places. even pretty common ones like “awesome” or “terrible” end up getting ...
Yeah, this actually comes up a lot when training a tokeniser from scratch. Just because a word shows up in your training data doesn’t mean it will end up in the vocab. It depends on how the tokeniser is building things. Even if “awesome” appears a bunch of times, it might not make it into the vocab as a full word. Word...
1
1
79,602,017
2025-5-1
https://stackoverflow.com/questions/79602017/correct-type-annotations-for-generator-function-that-yields-slices-of-the-given
I'm using Python 3.13 and have this function: def chunk(data, chunk_size: int): yield from (data[i : i + chunk_size] for i in range(0, len(data), chunk_size)) I want to give it type annotations to indicate that it can work with bytes, bytearray, or a general collections.abc.Sequence of any kind, and have the return ty...
You can define a Protocol that defines the behaviour when the object is sliced and then use that as the bound for your generic argument: from collections.abc import Generator, Sized from typing import Protocol, Self class Sliceable(Sized, Protocol): def __getitem__(self: Self, key: slice, /) -> Self: ... def chunk[T: S...
3
5
79,601,482
2025-5-1
https://stackoverflow.com/questions/79601482/2-laser-beams-number-of-intersections-in-a-mirror-problem
I've got an algorithmic problem that I've not been able to solve. Would appreciate any help with this The main problem: Two laser beams, blue and red color, are shot into a mirror and bounces around. Find the number of intersections between them. Example: red = [2, 7, 8, 15, 20] blue = [3, 4, 5, 7, 10, 16, 21] Should g...
The applicable technique is called a sweep line algorithm. Imagine a vertical line moving from left to right, and consider every "point of interest" at which you get new relevant information. You only need to process the situations at the points of interest, and there are relatively few of those. For your problem, the ...
3
4
79,603,404
2025-5-2
https://stackoverflow.com/questions/79603404/why-does-randomizedsearchcv-sometimes-return-worse-results-than-manual-tuning-in
I'm working on a classification problem using scikit-learn's RandomForestClassifier. I tried using RandomizedSearchCV for hyperparameter tuning, but the results were worse than when I manually set the parameters based on intuition and trial/error. Here's a simplified version of my code: from sklearn.ensemble import Ran...
RandomizedSearchCV can give worse results than manual tuning due to a few common reasons: Too few iterations – n_iter=10 may not explore enough parameter combinations. Poor parameter grid – Your grid might miss optimal values or be too coarse. Inconsistent random seeds – Different runs can yield different results if...
2
2
79,603,298
2025-5-2
https://stackoverflow.com/questions/79603298/what-is-the-oldest-leap-year-in-pandas
I'm working with a day of year column that ranges from 1 to 366 (to account for leap years). I need to convert this column into a date for a specific task and I would like to set it to a year that is very unlikely to appear in my time series. Is there a way to set it to the oldest leap year of pandas? import pandas as ...
The documentation for the pandas.Timestamp type says: Timestamp is the pandas equivalent of python’s Datetime and is interchangeable with it in most cases. So we can look up the Python documentation for datetime objects, where we find: Like a date object, datetime assumes the current Gregorian calendar extended in b...
2
8
79,602,340
2025-5-1
https://stackoverflow.com/questions/79602340/why-is-my-python-parser-method-returning-empty-strings
I am trying to write a simple parser method in Python. It takes in a filename pointing to a file of a certain format. An example of this format is below: File: .type = INFILE .fmt = CFP_INPUTFILE_FMT_2 Data: .cases .given = True .numCases = 2 .case .numlines = 2 .line .value = 3 .value = 3 .line .value = 3 .value = 3 ....
The issue is that: result = subprocess.run(['cat', 'temp.txt'], capture_output=True) returns a CompletedProcess[bytes], so result.stdout is a byte string, not a regular string. You can fix this by passing text=True: result = subprocess.run(['cat', 'temp.txt'], capture_output=True, text=True) I’d recommend avoiding su...
3
4
79,603,209
2025-5-2
https://stackoverflow.com/questions/79603209/privategpt-listing-ingested-document-filenames
I'm new to LLMs and need to extract the file names of files that have been already ingested into PrivateGPT that the system uses to answer questions. I can list the doc_ids using : from pgpt_python.client import PrivateGPTApi client = PrivateGPTApi(base_url="http://localhost:8001") # Health print(client.health.health(...
According to PrivateGPT API reference here (https://docs.privategpt.dev/api-reference/api-reference/ingestion/ingest-file), in addition to the doc_id property, which seems to be what you're getting, you should also be able to get the file's metadata in doc_metadata property, where the file name should be. Try running t...
1
2
79,602,749
2025-5-2
https://stackoverflow.com/questions/79602749/changing-the-page-numbering-index-in-reportlab
UPDATE: See second code block for the solution The question may seem simple but I haven't been able to find anything related to it: How to start the page numbering index at a given page? For example, let's consider a document composed of a front page, a table of content and then the document's content itself. How can...
ReportLab always uses physical page numbers, so to start numbering from a specific page (e.g., after the TOC), you need to manage it manually. Track your own logical_page_number, set a flag when the real content starts, and from that point on: Increment your counter on each page. Use it in the footer instead of canva...
2
1
79,601,938
2025-5-1
https://stackoverflow.com/questions/79601938/conda-installed-scipy-v1-15-2-does-not-contain-gaussian-function
Running Spyder 6.0.5 with Python version 3.11.11 and IPython 8.34.0. From within the Console window in Spyder I attempted to install Scipy with the following command: conda install -c conda-forge scipy=1.15.2 All seems to be ok, no error messages and a request to restart the kernel, which I do. However when I try to r...
Try from scipy.signal.windows import gaussian
1
1
79,601,812
2025-5-1
https://stackoverflow.com/questions/79601812/python-columns-must-be-same-length-as-key-when-splitting-a-column
I have two address columns and I want to extract the last word from the first column and the first word from the second column. In the provided example there aren't two words in column 'Address2', but I want to build the code in such a way that it will work regardless of how the dataset will look like. Sometimes the ad...
Using str.extract() might be better for several reasons: it handles all cases, offers precision with regular expressions, and eliminates the risk of value errors. import pandas as pd data = { 'Address1': ['3 Steel Street', '1 Arnprior Crescent', '40 Bargeddie Street Blackhill'], 'Address2': ['Saltmarket', 'Castlemilk E...
4
3
79,601,344
2025-5-1
https://stackoverflow.com/questions/79601344/how-to-get-the-key-and-values-from-a-dictionary-to-display-them-on-a-django-page
I want to build a page that has each author with their quote. I have tried, but everything i tried has failed. The function below is what causes me the issues. quotes = { "Arthur Ashe": "Start where you are, Use what you have, Do what you can.", "Steve Jobs": "Don’t watch the clock; do what it does. Keep going.", "Sam ...
You can pass the entire dictionary: def mypage(request): messages = [quotes[item] for item in quotes] authors = [item for item in quotes] return render(request, 'quotes/mypage.html', {'quotes': quotes}) and then in the template, enumerate over the .items() of the quotes, so: {% for author, quote in quotes.items %} {{au...
1
3
79,601,719
2025-5-1
https://stackoverflow.com/questions/79601719/attributeerror-messagebox-cant-take-multiple-functions
I tried to add multiple functions to a messagebox in my program: from Tkinter import * from Tkinter import messagebox as msgbox *some code...* input1 = msgbox.askyesno.showwarning('title', 'blahblahblah') if input1 == 1: input2 = msgbox.askyesno.showwarning('title', 'blahblahblah') if input2 == 1: function() But it sh...
I think, you're getting the error because askyesno is already a function inside tkinter.messagebox, not a module or object. So when you write msgbox.askyesno.showwarning(...), you're trying to access .showwarning on a function, which doesn't make sense—hence the AttributeError. You need to call either askyesno or showw...
1
1
79,601,644
2025-5-1
https://stackoverflow.com/questions/79601644/how-to-await-messages-and-not-affect-the-main-event-loop
I am writing a simple websocket script which registers & unregisters clients and then broadcasts random messages to them in a interval of 5s. This is the code: import asyncio, websockets, random, string import websockets.asyncio.server class web_socket(websockets.asyncio.server.ServerConnection): pass connections: set[...
In respond_to_messages, you're basically holding the lock forever. Inside the top-level loop you grab the lock and then start iterating through the connections; on each connection you await client.recv(), which blocks (holding the lock) until a new message arrives. You need to release the lock before you call .recv(). ...
1
1
79,600,873
2025-4-30
https://stackoverflow.com/questions/79600873/cant-align-rsa-encryption-in-python-and-kotlin
I would like to add RSA encryption in my server (Python FastAPI) and my Android app. But the encryption didn't work as the way I expected. I already have AES-GCM encryption/decryption working between my Python and Kotlin code. However, my RSA attempts in Python and Kotlin won't interoperate with each other. The Python ...
I've found that it's best to avoid defaults when writing cryptography code. The problem is that it's hard to know when you're getting defaults because there are no warnings. In this case, the OAEP scheme has a few parameters that you should always specify. These can be set on the Java/Kotlin side with the OAEPParameter...
1
1
79,600,626
2025-4-30
https://stackoverflow.com/questions/79600626/python-script-with-input-and-print-do-not-print-when-run-from-powershell-cla
This script in question runs as expected from powershell: # scripts.py x = input("type your input: ") print(f"your input is: {x}") But once you wrap it into a module: class CSV{ [string] $pythonScript CSV([string] $pythonPath){ $this.pythonScript = $pythonPath } [void] Run(){ python $this.pythonScript } } The interac...
Not sure if there will be an elegant way to provide input to your Python script in the same line from Python, however, here are some workarounds to your current issue. In both workarounds as you may note, the Run method output type has been changed from void to string[]. The first approach is what I'd personally use, i...
3
0
79,600,689
2025-4-30
https://stackoverflow.com/questions/79600689/numpy-concatenate-replacing-previous-data-in-array
I am trying to write code that produces a deck of cards. The deck is a 2D array that contains each card as an array. Each card array contains its card value as well as its suit, represented by the values 0 to 3. However, the code outputs this: [[ 1. 1.] ... [13. 1.] [ 1. 1.] ... [13. 1.] [ 1. 2.] ... [13. 2.] [ 1. 3.] ...
You have a classic NumPy issue — mutable arrays. The problem is that when you write a = suitsize, you're not creating a new copy of the array. You're just making a new reference to the same array in the computer's memory. So when you do a[:,1] = i, you're also modifying suitsize at the same time. You need to create an ...
1
2
79,600,512
2025-4-30
https://stackoverflow.com/questions/79600512/how-to-pickle-enum-with-values-of-type-functools-partial
Problem Suppose we have a python Enum where values are of type functools.partial. How to pickle and unpickle a member of that enum ? import pickle from enum import Enum from functools import partial def function_a(): pass class EnumOfPartials(Enum): FUNCTION_A = partial(function_a) if __name__ == "__main__": with open(...
The first answer is to pickle by name: from enum import Enum, pickle_by_enum_name class EnumDefs(Enum): __reduce_ex__ = pickle_by_enum_name The second answer is to use the new member class/decorator to avoid using partial, and to add __call__ so you can actually invoke the members: import pickle from enum import Enum,...
3
1
79,599,356
2025-4-30
https://stackoverflow.com/questions/79599356/how-can-i-stop-my-tkinter-hangman-game-accepting-a-correct-letter-more-than-once
I am making a python hangman game using tkinter. However, after guessing a correct letter, it continues to accept that letter but marking it as wrong. This is my guess function: def guess_letter(self, event=None): guess = self.entry.get().lower() self.entry.delete(0, tk.END) if not guess or len(guess) != 1 or not guess...
I have a fix. I have replaced: if not guess or len(guess) != 1 or not guess.isalpha(): return With: if not guess or len(guess) != 1 or not guess.isalpha() or guess in self.guessed_letters: return This checks if a letter has already been guessed, and doesn't take away lives if it has.
1
1
79,599,933
2025-4-30
https://stackoverflow.com/questions/79599933/change-color-of-tqdm-for-each-iteration
I'm using tqdm to track the progress of a task. For the fun of it, I want to change the color of the progress bar dynamically during each iteration. I know you can update the description of the bar using set_description(), but I haven’t found anything similar for changing the color of the progress bar. Is there a way t...
You can manually set the tqdm object's colour attribute: from tqdm import tqdm import time colors = iter(["red", "yellow", "green", "cyan", "blue"]) pbar = tqdm(range(5)) for i in pbar: pbar.colour = next(colors) time.sleep(0.5)
3
4
79,598,340
2025-4-29
https://stackoverflow.com/questions/79598340/efficiently-calculate-time-to-first-purchase-event-per-user-in-pandas-datafram
How can I compute time to first target event per user using Pandas efficiently (with edge cases)? I'm analyzing user behavior using a Pandas DataFrame that logs events on an app. Each row includes a user_id, event_type, and timestamp. I want to calculate the time (in seconds) from each user's first recorded event to th...
I grouped by user_id to get the first event timestamp, then did the same for 'purchase' events. Instead of subtracting the Series directly, I used pd.concat() to combine both into one DataFrame. Then I used .assign() with .dt.total_seconds() to calculate the difference. This gave me a clean DataFrame where I could see ...
1
1
79,599,624
2025-4-30
https://stackoverflow.com/questions/79599624/fastapi-application-with-nginx-staticfiles-not-working
I've a simple FastAPI project. It is running correctly in pycharm and in the docker container. When running via nginx, the StaticFiles are not delivered. Structure is like this: ├── app │ ├── main.py │ ├── static_stuff │ │ └── styles.css │ └── templates │ └── item.html ├── Dockerfile ├── requirements.txt main.py from ...
It seems like there is a bug in FastAPI with root_path parameter for mounted paths. If you specify root_path as a parameter of __init__ it expects additional my_app/ in path. So, your files are available on /my_app/my_app/static_stuff/ instead of /my_app/static_stuff/. Try specifying root_path as an argument of server ...
1
1
79,598,326
2025-4-29
https://stackoverflow.com/questions/79598326/im-trying-to-model-a-bolt-in-cadquery-python
I'm trying to build a CAD model of a bolt, but I can't figure out how to cut off the tops of the corners at the top of the head at a 45-degree angle. I want to get this result What did I do for this? At first I tried this: import cadquery as cq from math import sqrt, tan, radians head_diameter = 10.0 head_height = 5.0...
You can cut the upper edge by using a solid of revolution: create a triangle with the required angle and revolve it around the bolt axis to create the cutter. cutter = ( cq.Workplane("XZ") .workplane(offset=HEAD_HEIGHT) .move(r, 0) .lineTo(R*1.1, 0).lineTo(R*1.1, -cut_depth).lineTo(r, 0) .wire() .revolve() )
2
1
79,598,979
2025-4-29
https://stackoverflow.com/questions/79598979/how-could-i-self-eject-my-usb-drive-using-the-python-module-sub-process
I have a script for my USB that i need to use on multiple devices, and i want it to auto-eject, and using this method, as long as it has elevated privileges it runs, no issues, no errors, but i check the file explorer and the USB is still in there: p = Popen(["diskpart"], stdin=PIPE) p.stdin.write(b"select disk " + dr...
I believe the issue is that you are call it as a disk, not a volume. This code will fix your issue, but only works with elevated privileges: def eject_drive(drive_letter=input(): try: p = subprocess.Popen(["diskpart"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) # Prepare the disk...
2
2
79,599,115
2025-4-29
https://stackoverflow.com/questions/79599115/how-to-filter-all-columns-in-a-polars-dataframe-by-expression
I have this example Polars DataFrame: import polars as pl df = pl.DataFrame({ "id": [1, 2, 3, 4, 5], "variable1": [15, None, 5, 10, 20], "variable2": [40, 30, 50, 10, None], }) I'm trying to filter all columns of my dataframe using the method pl.all(), and I also tried using pl.any_horizontal() == Condition. However I...
You need to collapse the multiple-generated-expressions (imagine three matrices come out of that first pl.all(), one for each column) into a single column. You can do that with pl.all_horizontal(your, columns, here): >>> df.filter(pl.all_horizontal(pl.col('*').is_not_null())) shape: (3, 3) ┌─────┬───────────┬──────────...
2
1
79,598,793
2025-4-29
https://stackoverflow.com/questions/79598793/how-i-can-realtime-update-the-ui-when-i-receive-a-request-upon-fastapi
I have this simple script: import os import gradio as gr from fastapi import FastAPI, Request import uvicorn import threading from typing import List from datetime import datetime api = FastAPI() # Shared logs class Log(): def __init__(self): self._logs: List[str] = [] self.logstr="" def log_message(self,msg: str): tim...
Only method which works for me is def function(): return log.logstr Textbox(value=function, ..., every=1) It runs function every 1 second, and this function returns current content in log. Doc: Gradio Textbox Full code: import os import gradio as gr from fastapi import FastAPI, Request import uvicorn import threading...
1
1
79,598,423
2025-4-29
https://stackoverflow.com/questions/79598423/how-to-select-certain-rows-by-code-in-a-datagrid-table-in-python-shiny
I created a table ("DataGrid") using: ui.output_data_frame("grid") which I filled using @render.data_frame def grid(): df = ... return render.DataGrid(df, selection_mode="row") Now, I want to change the selection using codfe. Is this possible in Python's version of Shiny?
You can use update_cell_selection(): from shiny import ui, render, App, reactive import pandas as pd df = pd.DataFrame({"Row": ["Row Number 0", "Row Number 1", "Row Number 2"]}) app_ui = ui.page_fluid( ui.input_select( "rowSelection", "Which row shall be selected?", choices=["Choose", 0, 1, 2] ), ui.output_data_frame("...
1
1
79,598,174
2025-4-29
https://stackoverflow.com/questions/79598174/how-do-conditionally-apply-field-constraints-based-on-value-type-in-pydantic-v2
I have this pydantic model with a field, and this field could be either an int or a non numeric value like a str or list. from pydantic import BaseModel, Field class Foo(BaseModel): bar: str | list | int = Field('some string', ge=2) I want it to be that the constraint ge=2 is applied only if the value given to bar hap...
You can apply the validator to just the int value like so: from pydantic import BaseModel, Field from typing import Annotated class Foo(BaseModel): bar: str | list | Annotated[int, Field(ge=2)] foo_instance = Foo(bar="asdf") foo_instance = Foo(bar=4)
2
1
79,598,629
2025-4-29
https://stackoverflow.com/questions/79598629/double-bar-stacked-bar-plot-in-plotly-dash
I'm trying to create a double bar stacked bar chart using plotly. I found this code: from plotly import graph_objects as go data = { "original":[15, 23, 32, 10, 23], "model_1": [4, 8, 18, 6, 0], "model_2": [11, 18, 18, 0, 20], "labels": [ "feature", "question", "bug", "documentation", "maintenance" ] } fig = go.Figure(...
you can use dynamic stacking with calculated base values and consistent color coding, maintaining exactly 10 bars -5 categories × 2 sides- while supporting variable component combinations per bar. also chekc this out stacked + grouped bar chart from plotly import graph_objects as go data = { "left": [ {"original": 15, ...
3
2
79,598,228
2025-4-29
https://stackoverflow.com/questions/79598228/how-could-i-zoom-in-on-a-generated-mandelbrot-set-without-consuming-too-many-res
I am trying to make a Mandelbrot set display, with the following code: import numpy as np import matplotlib.pyplot as plt plt.rcParams['toolbar'] = 'None' def mandelbrot(c, max_iter): z = 0 for n in range(max_iter): if abs(z) > 2: return n z = z*z + c return max_iter def mandelbrot_set(xmin, xmax, ymin, ymax, width, he...
You're using Python code to handle single NumPy numbers. That's the worst way. Would already be about twice as fast if you used Python numbers instead, using .tolist(): r1 = np.linspace(xmin, xmax, width).tolist() r2 = np.linspace(ymin, ymax, height).tolist() But it's better to properly use NumPy, e.g., work on all p...
2
2
79,598,073
2025-4-29
https://stackoverflow.com/questions/79598073/tk-canvas-telepromter-text-transparency-problems
I have a fullscreen window with a fullscreen canvas. First I place a fullscreen background image in this canvas. canvas = tk.Canvas(window, bg="white", bd=0) canvas.pack(fill=tk.BOTH, expand=True) canvas.update() image = Image.open('bild.jpg') newimage = image.resize((canvas.winfo_width(),canvas.winfo_height()),Image.L...
You can use another Canvas widget as the telepromter with a cropped image from the background image that makes it looks like transparent, then scroll the text inside it: import tkinter as tk from PIL import Image, ImageTk, ImageGrab headline = 'Headline' with open(__file__) as f: fulltext = f.read() window = tk.Tk() wi...
1
1
79,598,239
2025-4-29
https://stackoverflow.com/questions/79598239/how-is-an-instance-attribute-of-the-same-type-as-the-instance-type-hinted
I am trying to assign a variable to an instance of a class such that the variable is of the same type. I want to use the instance itself in the construction of the variable. In order to be compatible with inheritance, I want to type hint it as Self rather than the class. The following works: class Foo: var: "Foo" def b...
PEP 673 (ref https://peps.python.org/pep-0673/) introduced typing.Self in Python 3.11 to let you write: from typing import Self class Foo: def clone(self) -> Self: … so that in subclasses clone() is recognized as returning the subclass type. But at the moment mypy only special‐cases Self in method signatures, not in a...
3
2
79,597,696
2025-4-29
https://stackoverflow.com/questions/79597696/how-to-decrypt-a-value-in-python-that-was-encrypted-using-php-openssl
I have a value that was encrypted using PHP openssl using cipher AES-CBC-256 but the passphrase for the final value was also encrypted using the same method. openssl_encrypt($key, $cipher, $passphrase, 0, $iv) I need to be able to unencrypt this data using Python but I'm running into block-size issues. Here's some of t...
I managed to figure out the PHP code that does the decryption: $localKey = base64_decode('Po0KPxyF'); $localIv = base64_decode('s8W+/a4jkp9mhO3NkCL7Yg=='); $encrypted_value = base64_decode('hl5n6Nq5QYtgKIyLEVCupA=='); $encrypted_key = base64_decode('MGRHRFlaMzhCR0lxb2VHS1JHQXcrWkV2bkJpNWFZb3cybW9iQW5KYTlOU0xKK1FHc2pPUW...
4
7
79,616,049
2025-5-11
https://stackoverflow.com/questions/79616049/streamlit-aggrid-multiselect-preview-values-were-undefinedundefined
I'm using streamlit-aggrid to display table. In the C column i use multiselect feature, select items and results are ok, but during selecting ,the preview values were undefined(undefined). I prefer to display the preview value like the result ex:Pink;Purple. I use followin python code in streamlit framwork. Select Ite...
import streamlit as st import pandas as pd from st_aggrid import AgGrid, GridOptionsBuilder, JsCode df = pd.DataFrame( "", index=range(5), columns=list("c"), ) df["c"]=[["Pink (#FFC0CB)","Purple (#A020F0)"], ["Purple (#A020F0)"], ["Blue (#0000FF)"], ["Green (#008000)"], ["Pink (#FFC0CB)"]] df["c"] = df["c"].astype("obj...
1
0
79,617,897
2025-5-12
https://stackoverflow.com/questions/79617897/how-can-i-efficiently-find-integer-solutions-x-%e2%89%a0-y-to-a-diophantine-equation-u
I'm trying to write a Python script to search for integer solutions (x, y) with x ≠ y to the following Diophantine equation: (y + n)^4 - y^4 = (x + k)^4 - x^4 Here: n and k are fixed small positive integers (like n = 1, k = 2), x and y range from 1 to a large number (e.g., 1 to 1,000,000), I only want solutions where ...
Efficient equivalent rhs and lhs are increasing with increasing x and y, so you can go through both in parallel, always advancing the smaller one: n = 1 k = 2 limit = 10**6 x = y = 1 while x < limit and y < limit: rhs = (x + k)**4 - x**4 lhs = (y + n)**4 - y**4 if lhs == rhs: if x != y: print(f"Match found: x = {x}, y ...
2
3
79,611,948
2025-5-8
https://stackoverflow.com/questions/79611948/imputing-and-adding-rows-to-dataframe-using-polars-expressions
I have a dataframe with incomplete values as below - in particular ages with corresponding years, and I would like to make it square (i.e., all three cust_id to have correctly imputed values for age in all three years, i.e. I want to turn this: df = pl.DataFrame({ "cust_id": [1, 2 ,2, 2, 3, 3], "year": [2000,1999,2000,...
Here is a possible approach # create all (year, cust_id) combinations index = df.select("year").unique().join(df.select("cust_id").unique(), how="cross") # compute the birth year of each customer as an expression birth_year = (pl.col("year") - pl.col("cust_age")).drop_nulls().first().over("cust_id") # use it to fill t...
2
3
79,617,786
2025-5-12
https://stackoverflow.com/questions/79617786/line-separator-python-r-n
We have an English-Latin dictionary in our hands, that is, a list of words in English and their translations into Latin (there may be several translations) in the form of a file with the following contents: apple - malum, pomum, popula fruit - baca, bacca, popum punishment - malum, multa It is necessary to write a scr...
The test itself is not OS-portable. It should use text=True in subprocess.run and the output will be the original text and not encoded to sys.stdout. Then .decode() won't be required in the student output as well: result = subprocess.run( ["python", os.path.join(SOLUTION_FOLDER_PATH, "task3.py"), test_input_file], std...
1
1
79,618,567
2025-5-12
https://stackoverflow.com/questions/79618567/how-to-cache-elements-to-increase-the-runtime-performance-with-lxml-pythin-libra
In the lxml.de website https://lxml.de/performance.html I see the following statement: A way to improve the normal attribute access time is static instantiation of the Python objects, thus trading memory for speed. Just create a cache dictionary and run: cache[root] = list(root.iter()) after parsing and: del cache[root...
Setting a variable like cache[root] = list(root.iter()) will effectively cache objects in memory as demonstrated by a simple test. The cache mechanism is very simple: the whole document tree is loaded in memory and elements can be obtained in different ways but point to the same memory address. Given an XML document, g...
2
1
79,608,752
2025-5-6
https://stackoverflow.com/questions/79608752/how-to-add-space-between-bubbles-and-increase-thier-size
I have a bubble chart developed using plotly library and here’s the data : import plotly.express as px import pandas as pd data = { "lib_acte":["test 98lop1", "test9665 opp1", "test QSDFR1", "test ABBE1", "testtest21","test23"], "x":[12.6, 10.8, -1, -15.2, -10.4, 1.6], "y":[15, 5, 44, -11, -35, -19], "circle_size":[375...
To change the size of your bubbles just do something like this: multiplier = 1.04 # made bigger by 4% df["circle_size"] = df["circle_size"]*multiplier But you still need to change the maximum size of the bubbles: Here i changed it to the biggest bubble size: biggest_bubble_size = max(df["circle_size"]) fig = px.scatt...
3
0
79,617,933
2025-5-12
https://stackoverflow.com/questions/79617933/multidimensional-coordinate-transform-with-xarray
How to convert multidimensional coordinate to standard coordinate in order to unify data when using xarray for nc data: import xarray as xr da = xr.DataArray( [[0, 1], [2, 3]], coords={ "lon": (["ny", "nx"], [[30, 40], [40, 50]]), "lat": (["ny", "nx"], [[10, 10], [20, 20]]), }, dims=["ny", "nx"], ) Expected conversion...
You can flatten the data into a list of points using xarray.DataArray.stack, extract unique coordinates and reassign values onto a regular grid using the unique coordinate values. import xarray as xr import numpy as np da = xr.DataArray( [[0, 1], [2, 3]], coords={ "lon": (["ny", "nx"], [[30, 40], [40, 50]]), "lat": (["...
2
1
79,618,357
2025-5-12
https://stackoverflow.com/questions/79618357/sqlalchemy-and-psycopg2-pandas-read-sql-query-dict-is-not-a-sequence-error-wi
Package Versions: SQLAlchemy 2.0.40 pandas 2.2.3 psycopg2-binary 2.9.10 I am trying to run a query using pandas' native param substitution, but I can't seem to get it to run without erroring. I tried simplifying the query to: select * FROM public.bq_results br WHERE cast("eventDate" as date) between TO_DATE('%test_st...
The documentation of read_sql_query says the following: params : list, tuple or mapping, optional, default: None List of parameters to pass to execute method. The syntax used to pass parameters is database driver dependent. Check your database driver documentation for which of the five syntax styles, described in PEP 2...
2
2