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,663,680 | 2025-6-12 | https://stackoverflow.com/questions/79663680/plotting-the-components-of-a-general-solution-returned-by-sympy | I have written the following code that returns a solution. import sympy as sym import numpy as np z = sym.Symbol('z') e = sym.Symbol('e') f = sym.Function('f') edo = sym.diff(f(z), z , 2) + e * f(z) soln = sym.dsolve(edo, f(z)) print(soln.rhs) the above code returns: C1*exp(-z*sqrt(-e)) + C2*exp(z*sqrt(-e)) I want to... | What you are looking for is the args attribute of a Sympy's symbolic expression. For example: print(soln.rhs.args[0]) # C1*exp(-z*sqrt(-e)) print(soln.rhs.args[1]) # C2*exp(z*sqrt(-e)) You might also want to insert appropriate values for the integrations constants by using the subs method: C1, C2 = symbols("C1, C2") s... | 1 | 2 |
79,663,153 | 2025-6-12 | https://stackoverflow.com/questions/79663153/correct-way-to-embed-and-bundle-python-in-c-to-avoid-modulenotfounderror-enc | I am trying to embed Python inside my C++ DLL. The idea is that the DLL, once distributed, should be sufficient and not rely on other installations and downloads. Interestingly, the below "sort of" works, only in my solution directory, since that is where my vcpkg_installed is. How can I make my DLL not be required to ... | CPython needs its standard library to exist at the PYTHONHOME directory, (which you can override in the config). If you need a standalone python interpreter to just parse python syntax (for game scripting) then you can use other implementations of python like RustPython or IronPython or JYThon or pocketpy, but you won'... | 1 | 2 |
79,663,207 | 2025-6-12 | https://stackoverflow.com/questions/79663207/matplotlib-slider-not-working-when-plot-is-updated-in-separate-function | I am using matplotlib's Slider to do a simple dynamic plot of a sine curve. I want to change the frequency using a slider. The code looks like this: import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import Slider x = np.linspace(400, 800, 400) fig, ax = plt.subplots() fig.subplots_adjust(bottom... | In the redraw() function: def redraw(): lambda_plot.set_ydata(np.sin(mod * x * 2 * np.pi / 500)) You're using the variable mod, but this mod is not defined in the local scope of redraw(), nor is it properly declared as global or passed as an argument. So Python looks for it in the outer scope and finds the mod = 1. yo... | 2 | 2 |
79,664,893 | 2025-6-13 | https://stackoverflow.com/questions/79664893/average-distance-of-any-point-of-a-disk-to-its-boundary | I was wondering what was the average distance "d" of any point in a ball to its boundary (not specifically the closest point). I made a simple monte carlo computation using Muller's method to get a uniform distribution - see linked answer : Python Uniform distribution of points on 4 dimensional sphere : def sample_with... | The error you are doing is to compute the average distance between a point within the disk and a point within the border. This is not what the article describes. The article describe the average distance between a point within a disk and the intersection of the border for a direction This may seem to be the same. Since... | 2 | 1 |
79,664,331 | 2025-6-13 | https://stackoverflow.com/questions/79664331/why-does-numpy-assign-different-string-dtypes-when-mixing-types-in-np-array | I'm trying to understand how NumPy determines the dtype when creating an array with mixed types. I noticed that the inferred dtype for strings can vary significantly depending on the order and type of elements in the list. print(np.array([1.0, True, 'is'])) # Output: array(['1.0', 'True', 'is'], dtype='<U32') print(np.... | Looking at your array contents and the NumPy type promotion rules, I guess the following applies: For some purposes NumPy will promote almost any other datatype to strings. This applies to array creation or concatenation. This leaves us with the question about the string lengths. For the complete array, we need to ch... | 2 | 1 |
79,664,217 | 2025-6-13 | https://stackoverflow.com/questions/79664217/arbitrary-stencil-slicing-in-numpy | Is there a simple syntax for creating references to an arbitrary number of neighbouring array elements in numpy? The syntax is relatively straightforward when the number of neighbours is hard-coded. A stencil width of three for example is import numpy as np x = np.arange(8) # Hard-coded stencil width of 3 x_neighbours ... | I'd recommend using sliding_window_view. Change: nStencil = 3 x_neighbours = ( x[indexStart:indexStop] for indexStart, indexStop in zip( (None, *range(1,nStencil)), (*range(1-nStencil,0), None), ) ) To: nStencil = 3 sliding_view = sliding_window_view(x, nStencil) x_neighbours = tuple(sliding_view[:, i] for i in range(... | 1 | 3 |
79,667,364 | 2025-6-16 | https://stackoverflow.com/questions/79667364/how-to-create-different-type-for-class-variable-and-instance-variable | I want to explain to Pyright that my variables in class and instance have different types. I managed to overload __get__ method to achieve this, but now Pyright complains about initialization of instances (see last line): Literal[1] is not assignable to Field[int] My code: import typing as ty from dataclasses import da... | You want to have a data-descriptor, such it needs a __set__ method. You will get an error depending on the signature of __set__, you want it to accept your generic. A working example could look like this, the instance value will be stored on the objects _field attribute, see the __set_name__ magic, you could of course ... | 1 | 0 |
79,667,071 | 2025-6-16 | https://stackoverflow.com/questions/79667071/why-numpy-fabs-is-much-slower-than-abs | This Python 3.12.7 script with Numpy 2.2.4: import numpy as np, timeit as ti a = np.random.rand(1000).astype(np.float32) print(f'Minimum, median and maximum execution time in us:') for fun in ('np.fabs(a)', 'np.abs(a)'): t = 10**6 * np.array(ti.repeat(stmt=fun, setup=fun, globals=globals(), number=1, repeat=999)) print... | fabs always calls the C math library function of the same name (or in this case, the fabsf type variation). Therefore the operation cannot be inlined or vectorized. I have verified this by injecting a custom version using LD_PRELOAD. I've checked the source code of glibc (which just calls __builtin_fabsf(x)) and looked... | 2 | 4 |
79,666,955 | 2025-6-16 | https://stackoverflow.com/questions/79666955/how-to-access-code-in-different-files-inside-the-main-app | I have a rather large app.py file, so I'd like to take a nav panel out and store it in a separate file. I'm not sure how to access code from a different file and include it in the main app. The app.py file: import page from shiny import reactive, render, req, ui from shiny.express import input, ui with ui.navset_hidden... | You can wrap the other_page nav panel into a function and use this function inside the main app. However, doing this results in an empty additional nav panel and you need to apply express.expressify. This is because otherwise only the return value of the nav function is shown (None), where we instead want to display th... | 1 | 1 |
79,669,389 | 2025-6-17 | https://stackoverflow.com/questions/79669389/pandas-subtract-one-dataframe-from-another-if-match | I have a pandas dataframe that has information about total attendance for schools grouped by School, District, Program, Grade, and Month #. The data looks like the following (df): School District Program Grade Month Count 123 456 A 9-12 10 100 123 456 B 9-12 10 95 321 654 A 9-12 10 23 321 456 A 7-8 10 40 Some of the c... | A possible solution: cols = ['School', 'District', 'Program', 'Grade', 'Month'] df1.set_index(cols).sub(df2.set_index(cols), fill_value=0).reset_index() First, it defines the list cols with the columns used to match records (School, District, Program, Grade, and Month). Then, it sets these columns as the index for bot... | 1 | 3 |
79,669,116 | 2025-6-17 | https://stackoverflow.com/questions/79669116/creating-a-character-grid-from-a-table-output-is-inverted | I was given a problem that takes in a table of information (grid coordinates and characters) and asked to place them into a table to make a message. I've spent time working on some Python to work it out but my answer is coming out upside down and I can't figure out why. import requests from bs4 import BeautifulSoup web... | The likely cause of the upside-down output is how you are indexing grid[int(y)]. In typical grid representations for display: grid[0] often represents the top row. grid[len(grid)-1] often represents the bottom row. However, if your data's y-coordinates are such that y=0 is the bottom of your intended image (like a ... | 1 | 0 |
79,668,894 | 2025-6-17 | https://stackoverflow.com/questions/79668894/plotly-express-line-plots-number-of-datapoint-insted-of-actual-data | Plotly express line plots number of data points instead of actual data on the y axis. Now whats confusing me is that it only does this on one machine, its works perfectly fine on 3 others. I made sure python and the packages i use are of the same version. I tried changing the data type to int and float, which only does... | The symptom you’re seeing is exactly the bug that crept into Plotly v6.0.0: in Jupyter the first release of 6.x sometimes mistakes a perfectly-normal numeric series for “categorical” and silently switches the underlying trace to the default aggregation “count”. Instead of plotting the values it therefore shows how many... | 1 | 1 |
79,670,825 | 2025-6-18 | https://stackoverflow.com/questions/79670825/index-array-using-boolean-mask-with-a-broadcasted-dimension | I have two arrays a1 and a2 of shape M1xM2x...xMPx3 and N1xN2x...xNQx3, and a mask m (boolean array) of shape M1xM2x...xMPxN1xN2x...xNQ (you can assume that a1 and a2 are at least 2D). import numpy as np np.random.seed(0) a1 = np.random.rand(4, 5, 3) a2 = np.random.rand(6, 3) m = np.random.rand(4, 5, 6) >= 0.7 I would... | A possible solution: idx = np.where(m) P = len(a1.shape) - 1 Q = len(a2.shape) - 1 a1_idx = idx[:P] a2_idx = idx[P:P+Q] b1 = a1[a1_idx] if P > 0 else np.tile(a1, (np.sum(m), 1)) b2 = a2[a2_idx] if Q > 0 else np.tile(a2, (np.sum(m), 1)) This solution begins by using np.where(m) to obtain a tuple of index arrays corresp... | 1 | 1 |
79,670,289 | 2025-6-18 | https://stackoverflow.com/questions/79670289/type-hinting-a-dynamic-asymmetric-class-property | I'm currently working on removing all the type errors from my Python project in VS Code. Assume you have a Python class that has an asymmetric property. It takes any kind of iterable and converts it into a custom list subclass with additional methods. class ObservableList(list): """list with events for change, insert, ... | You can use the Any-Trick, see my answer on how the four different cases work, but in short, if you type it as: from typing import Any, reveal_type class ObservableList(list): """list with events for change, insert, remove, ...""" def foo(self) -> str: ... class MyFrame: my_list: ObservableList | Any MyFrame().my_list ... | 1 | 2 |
79,673,580 | 2025-6-20 | https://stackoverflow.com/questions/79673580/why-do-i-get-a-division-by-zero-error-when-plotting-inverse-function-on-secondar | I get a division by zero error when I run the following python script. import matplotlib.pyplot as plt fig, ax = plt.subplots(figsize=(10, 10)) freq = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 1.8, 2.0] amp = [0.0, 0.0, 0.0, 0.0, 0.0, 0.012, 0.031, 0.074, 0.082, 0.084, 0.080, 0.078, 0.... | I think it is just a "feature" of the secondary axis. In the third example in the docs here, they explicitly have a check to avoid divide by zero warnings: fig, ax = plt.subplots(layout='constrained') x = np.arange(0.02, 1, 0.02) np.random.seed(19680801) y = np.random.randn(len(x)) ** 2 ax.loglog(x, y) ax.set_xlabel('f... | 1 | 1 |
79,673,208 | 2025-6-20 | https://stackoverflow.com/questions/79673208/dynamically-added-class-attributes-with-getter-setter-methods-in-a-loop-in-pytho | I'm trying to dynamically assign class attributes to an existing custom class. These attributes have individual getter and setter methods defined in a loop across all attributes to be created and are assigned with setattr() within the loop. Please see code below. If I use setattr(), the newly created attributes point t... | You create different getters and setters at each iteration but they all use the attr variable from the outer scope; this means that when you access a getter/setter then it uses the current value of the attr variable, which will be the final value from the loop. You need to have attr in a different scope for each getter... | 1 | 2 |
79,674,833 | 2025-6-22 | https://stackoverflow.com/questions/79674833/scipy-optimizewarning-covariance-of-the-parameters-could-not-be-estimated-when | I'm trying to plot some data with a non-linear fit using the function: kB and Bv being a constant while J'' is the independent variable and T is a parameter. I tried to do this in Python: #Constants kb = 1.380649e-23 B = 0.3808 #Fit function def func(J, T): return (B*(2*J+1) / kb*T * np.exp(-B*J*(J+1)/kb*T)) popt, pco... | Why? You have three problems in your model: Priority of operations are not respected, as pointed by @jared, you must add parenthesis around the term kb * T; Target dataset is normalized to unity where it is its area which is unitary (it is a distribution). therefore such normalization prevents the model to converge. A... | 5 | 4 |
79,675,821 | 2025-6-23 | https://stackoverflow.com/questions/79675821/force-python-sqlite3-to-report-non-existing-columns-in-where-clause | This is my code: import sqlite3 conn = sqlite3.connect(':memory:') cursor = conn.cursor() cursor.execute(''' CREATE TABLE schools ( county TEXT, statustype TEXT ) ''') cursor.execute(''' INSERT INTO schools VALUES ('some_county', 'some_status') ''') cursor.execute(''' SELECT COUNT(*) FROM schools WHERE county = 'Alpine... | SQLite has a quirk when it comes to delimiting identifiers. In ANSI SQL double quoting an column name does what you expect i.e. delimits the column name. However in SQLite you get the following behaviour (from the docs) ... in an effort to be compatible with MySQL 3.x (which was one of the most widely used RDBMSes whe... | 1 | 1 |
79,675,526 | 2025-6-23 | https://stackoverflow.com/questions/79675526/how-to-edit-an-element-inside-of-a-tkinter-grid | I'm working on a project to design a chessboard. I have successfully created the board. My goal is to edit the board. My original idea is to use buttons with the Tkinter grid to make the moves work. I decided to make the board using: window = tk.Tk() # Creating the GUI and Display window.geometry("800x500") window.mins... | To change the color of the checkerboard squares, one can make use of modulo 2. Here's a simple example showcasing that: from tkinter import tk COLOR_1 = "white" COLOR_2 = "green" for row in range(8): # 8 Rows along for column in range(8): #8 Columns down if ((row % 2) + column) % 2: color = COLOR_1 else: color = COLOR_... | 2 | 2 |
79,677,119 | 2025-6-24 | https://stackoverflow.com/questions/79677119/type-hinting-callable-with-positional-keyword-only-arguments-without-typing-prot | I'm wondering if it is possible to type-hint a Callable with positional- / keyword-only argument without using typing.Protocol. For example in this snippet - how would I type-hint x correctly so that add is assignable to it: from typing import Callable def add(arg: int, /, *, other: str) -> str: return f"{arg}{other}" ... | In short no. A combination is (currently) not possible, as keyword only parameters are not possible with Callable, as it describes positional-only parameters - you need a Protocol for more specific typing. To quote the specs: Parameters specified using Callable are assumed to be positional-only. The Callable form prov... | 3 | 1 |
79,676,972 | 2025-6-24 | https://stackoverflow.com/questions/79676972/python-while-loop-is-executed-but-then-it-fails-to-execute-an-if-statement-afte | I am working on a simple 2 player dice rolling game and have found a problem that i haven't been able to fix, after a While loop, it refuses to execute an if statement def Main(): global player1_score, player2_score rounds_input = int(input('How many rounds do you want?: ')) i = rounds_input n = 0 while n < i: gameFunc... | In your code in the logic of the final if statement in the Main() function: if player1_score > player1_score: This line always set to False because you're comparing player1_score to itself, not to player2_score. Just like this one: elif player1_score < player1_score: It should be something like this: if player1_score... | 1 | 2 |
79,678,764 | 2025-6-25 | https://stackoverflow.com/questions/79678764/how-can-i-vectorize-a-function-that-returns-eigenvalues-and-eigenvectors-of-a-ma | I'm working with a function in Python that constructs a 4×4 matrix based on inputs (x1, y1, x2, y2), and computes its eigenvalues and eigenvectors using np.linalg.eigh. Here is a simplified version of my code: import numpy as np def f(kx, ky): return kx + 1j * ky def fs(kx, ky): return np.conj(f(kx, ky)) def eig(x1, y1... | It is a bit of stacking, but you can create a matrix that is your batch size times 4x4 and pass it to np.linalg.eigh. Also note the slight optimization avoiding multiple evaluations of f(x, y) and fs(x, y). def eig_vectorized(x1_array, y1_array, x2_array, y2_array): a = 10 x_array = x1_array + x2_array y_array = y1_arr... | 1 | 1 |
79,680,007 | 2025-6-26 | https://stackoverflow.com/questions/79680007/is-this-a-bug-in-numpy-histogram-function | This Python 3.12.7 script with numpy 2.2.4: import numpy as np a = np.random.randint(0, 256, (500, 500)).astype(np.uint8) counts, bins = np.histogram(a, range(0, 255, 25)) print(np.column_stack((counts, bins[:-1], bins[1:]))) counts, bins = np.histogram(a, range(0, 257, 16)) print(np.column_stack((counts, bins[:-1], bi... | I think the docs explain pretty well what's happening, but are spread out in two different places. First, the range range(0, 255, 25) is supplying the bins parameter, not the range parameter. Secondly, the Notes section states: All but the last (righthand-most) bin is half-open. In other words, if bins is: [1, 2, 3, 4... | 2 | 3 |
79,680,409 | 2025-6-26 | https://stackoverflow.com/questions/79680409/cant-get-frequency-data-right-for-seaborn-histogram | I have a list containing thousands of survey answers ranging from 'A' to 'I', with the addition of None for blanks: Raw data list example: [None, 'A', 'G', None, None, 'I', 'B', ...<snip>... , 'C'] I would like to produce a Seaborn histogram showing the frequency of each response (in alphabetical order), something sim... | Since you have pre-aggregated data, you should use a barplot, not a histplot that is designed to perform the aggregation. For the alphabetical order, use sort_index: df = (pd.DataFrame.from_dict(Counter(values), orient='index') .sort_index().reset_index() ) df.columns = ['Choice', 'Frequency'] sns.barplot(data=df, x='C... | 2 | 0 |
79,680,212 | 2025-6-26 | https://stackoverflow.com/questions/79680212/using-python-pptx-how-can-i-display-the-in-my-chart-data | I would like to create a chart on a powerpoint slide with pourcent datas , python doesn't let my directly put the % symbol on my data so i had to only put the datas , but i want to show the % symbol on the chart and also on the axes So heres my code : if slide: for shape in slide.shapes: if shape.shape_type == MSO_SHA... | You have to divide by 100 in-place. Percentage formatting expects decimal values normalized to 0.0..1.0 as 0..100%. for moisSingleDate in moisDate: # Divide values by 100 to correctly format as percentages percentage_values = [value / 100 for value in result[moisSingleDate]] chart_data.add_series(str(moisSingleDate), v... | 1 | 2 |
79,681,704 | 2025-6-27 | https://stackoverflow.com/questions/79681704/i-have-an-np-array-of-a-number-single-entry-lists-and-i-want-to-add-1-to-each-si | I have created the following array, called X: array([[6.575], [6.421], [7.185], [6.998], [6.43 ], [6.012], [6.172], [5.631], [6.004], [6.377], [6.03 ]]) and I would like to create array([[6.575, 1], [6.421, 1], [7.185, 1], [6.998, 1], [6.43, 1], [6.012, 1], [6.172, 1], [5.631, 1], [6.004, 1], [6.377, 1], [6.03, 1]]) ... | Do not use list comprehensions/loops to work with numpy arrays. You should combine expand the scalar with broadcast_to and combine it to X with hstack: out = np.hstack([X, np.broadcast_to(1, X.shape)]) Output: array([[6.575, 1. ], [6.421, 1. ], [7.185, 1. ], [6.998, 1. ], [6.43 , 1. ], [6.012, 1. ], [6.172, 1. ], [5.6... | 4 | 4 |
79,682,876 | 2025-6-28 | https://stackoverflow.com/questions/79682876/how-to-create-same-ticks-and-labels-on-both-axes | I have to create a plot on which ticks and labels are specifically defined; an example of reproducible plot is given below: import matplotlib.pyplot as plt import seaborn as sns plt.style.use('seaborn-v0_8') fig, ax = plt.subplots(figsize=(4, 4)) ticks = [0.00, 0.25, 0.50, 0.75, 1.00] ax.set_xticks(ticks) ax.set_xtickl... | You can use a function. import matplotlib.pyplot as plt plt.style.use('seaborn-v0_8') def set_ticks_and_labels(ax, t, **kwargs): ax.set_xticks(t) ax.set_xticklabels(t, **kwargs) ax.set_yticks(t) ax.set_yticklabels(t, **kwargs) fig, ax = plt.subplots(figsize=(4, 4)) ticks = [0.00, 0.25, 0.50, 0.75, 1.00] set_ticks_and_l... | 1 | 1 |
79,684,430 | 2025-6-30 | https://stackoverflow.com/questions/79684430/why-does-isort-order-the-imports-differently-when-renaming-a-directory-from-te | In the example below, everything is already processed using isort . (version 6.0.1): tree . . ├── a │ └── test │ ├── __init__.py │ └── test_integration.py └── b └── tests ├── __init__.py └── test_integration.py cat ./a/test/test_integration.py from test.asdasd import hello import numpy as np if np.random.random() < ... | The module name test clashes with the standard library module test. isort will, by default, order with the following priorities ('FUTURE', 'STDLIB', 'THIRDPARTY', 'FIRSTPARTY', 'LOCALFOLDER') As test is within isort's list of known standard library names, it get's prioritised in the ordering, whereas tests doesn't. Yo... | 1 | 2 |
79,684,326 | 2025-6-30 | https://stackoverflow.com/questions/79684326/embedding-python-in-multi-threaded-c-environment | python 3.13.5 windows 10 msvc This is how initialize python in main. #include <iostream> #include <taskflow/taskflow.hpp> // Taskflow is header-only #define PY_SSIZE_T_CLEAN #include <Python.h> int main(int argc, char* argv[]) { wchar_t pythonHome[] = L".venv"; Py_SetPythonHome(pythonHome); Py_Initialize(); PyEval_In... | that's because each time you acquire the gil you must release it, the main thread starts by acquiring the GIL once so you must reset the initial GIL count in the main thread by calling PyEval_SaveThread in the main thread. Py_InitializeEx(); PyThreadState* tstate = PyEval_SaveThread(); // release the initial GIL // bef... | 2 | 3 |
79,685,618 | 2025-7-1 | https://stackoverflow.com/questions/79685618/checking-for-missing-signatures-in-uploaded-pdf-using-python | I am new to Python and I want to check whether the uploaded PDF file contains all the required signatures. If any are missing, it should return "Signature missing." I’ve tried reading the file, but I’m not sure how to implement this check. try: images = convert_from_path(pdf_path, dpi=200) print(f"[DEBUG] PDF has {len(... | As you already have your signature boxes cropped from the image, it boils down do checking for any content. Here are two variants, which can do the job. Both assume the cropped_image to be a PIL.Image. The first method checks for whiteness of the box. You can adapt the white_threshold for pixels considered to be white.... | 1 | 2 |
79,687,250 | 2025-7-2 | https://stackoverflow.com/questions/79687250/import-module-error-in-pythons-google-generative-ai | from google.generativeai import error in the above import of the google's generative ai of the python module is not working as expected the error module is not found but in the below import, the error module is working prefect in my previous verison of my code, i want to know, is that deprecated or else me using wrongl... | google.generativeai = Old deprecated SDK google.genai = New unified SDK https://ai.google.dev/gemini-api/docs/migrate pip uninstall google-generativeai Then pip install google-genai You can check available modules like so. from google import genai print("Available in main genai module:") print([item for item in dir(g... | 1 | 1 |
79,687,024 | 2025-7-2 | https://stackoverflow.com/questions/79687024/neural-network-built-from-scratch-using-numpy-isnt-learning | I'm building a neural network from scratch using only Python and numpy, It's meant for classifying the MNIST data set, I got everything to work but the network isn't really learning, at epoch 0 it's accuracy is about 12% after 20 epochs, it increases to 14% but then gradually drops to back to around 12% after 40 epochs... | dW*/db* just have the wrong axes. Because of that the two bias gradients end up with the wrong shape and your updates trash the weights every step, so the net hovers at chance (≈ 10 %). m = x.shape[0] # samples in a batch # ---------- forward ---------- Z1 = x @ W1 + b1 # (m,784)·(784,10) = (m,10) A1 = np.maximum(Z1, 0... | 2 | 4 |
79,688,514 | 2025-7-3 | https://stackoverflow.com/questions/79688514/why-are-type-checkers-fine-with-covariant-method-parameters-when-they-are-in-a-u | Method parameters should be contravariant, hence defining a covariant generic should raise a type error. However when using a covariant generic in a union pyright, mypy and pyre-check all do not report an error on the following code: from typing import TypeVar, Generic, Any T_co = TypeVar("T_co", covariant=True) class ... | It appears to be a missing feature. In Mypy's case, there's a comment about this: elif isinstance(arg_type, TypeVarType): # Refuse covariant parameter type variables # TODO: check recursively for inner type variables if ( arg_type.variance == COVARIANT and defn.name not in ("__init__", "__new__", "__post_init__") and ... | 2 | 3 |
79,688,933 | 2025-7-3 | https://stackoverflow.com/questions/79688933/how-can-i-create-a-column-that-is-the-result-of-replacing-values-in-two-or-more | Consider the dataframe df: import pandas as pd df = pd.DataFrame({'Event1': ['Music', 'Something else 1', 'Theatre', 'Comedy'], 'Event2': ['Something else 2', 'Ballet', 'Something else 3', 'Something else 4'], 'Cost': [10000, 5000, 15000, 2000]}) print(df) Event1 Event2 Cost 0 Music Something else 2 10000 1 Something e... | You can combine map and fillna: df['Event'] = df['Event1'].map(dict1).fillna(df['Event2'].map(dict2)) Output: Event1 Event2 Cost Event 0 Music Something else 2 10000 M 1 Something else 1 Ballet 5000 B 2 Theatre Something else 3 15000 T 3 Comedy Something else 4 2000 C If you imagine a more complex input with an arbi... | 1 | 2 |
79,690,330 | 2025-7-4 | https://stackoverflow.com/questions/79690330/how-to-have-a-line-break-in-the-math-mode-text-in-plotly | Suppose you would like to have a line break in the math mode text in plotly. The following solutions have been tried, but none of them is working in different reasons: import plotly.graph_objects as go fig = go.Figure() fig.add_trace(go.Box(y=[10, 14])) fig.update_layout(xaxis_title="$\alpha \\ \beta$") # causes to_ima... | You seem to be struggling, by trial and error, with 3 (at least) problems (and it is hard to debug when you have found the correct way for one of the problem, but won't even know it unless you solve both in the same trial) 1. Escaping Firstly, how to escape things. That is a pure python problem. You need to pass a stri... | 2 | 1 |
79,689,943 | 2025-7-4 | https://stackoverflow.com/questions/79689943/compute-group-wise-residual-for-polars-data-frame | I am in a situation where I have a data frame with X and X values as well as two groups GROUP1 and GROUP2. Looping over both of the groups, I want to fit a linear model against the X and Y data and the subtract the fit from the true data to get a residual. I'm currently implementing this in the following way: import po... | You can use a Struct to send multiple columns to .map_batches() def subtract_linear_best_fit(s: pl.Series) -> pl.Series: x, y = s.struct.unnest() a, b = np.polyfit(x, y, 1) return y - (a * x + b) df.with_columns( pl.struct("X", "Y").map_batches(subtract_linear_best_fit) .over("GROUP1", "GROUP2") .alias("residual") ) s... | 1 | 2 |
79,689,724 | 2025-7-4 | https://stackoverflow.com/questions/79689724/how-can-i-change-the-background-color-of-an-action-button | I have a Shiny for Python app with some buttons. I want to change the color of a button. How can I do this? from shiny.express import ui with ui.layout_columns(): ui.input_action_button("red_button", "Make this button red!") ui.input_action_button("blue_button", "Make this button blue!") | You can pass a style attribute and set the background-color: from shiny.express import ui with ui.layout_columns(): ui.input_action_button( "red_button", "Make this button red!", style = "background-color: red;" ) ui.input_action_button( "blue_button", "Make this button blue!", style = "background-color: lightblue;" ) ... | 3 | 2 |
79,690,793 | 2025-7-5 | https://stackoverflow.com/questions/79690793/pip-install-using-a-separate-build-machine | I have two same-architecture Linux boxes running identical versions of pypy, installed via pyenv. Consider one a "production" machine and one a "build" machine, such that the production machine cannot easily collect and configure all required build dependencies for modern source packages. I need to install a package on... | I would do pretty much what @phd suggested in the comments. Instead of trying to install directly on your production machine, you can download and build everything on your build machine, then move the ready files over. Here’s how: On your build machine, use pip to download the package and all its dependencies: python ... | 1 | 3 |
79,691,774 | 2025-7-6 | https://stackoverflow.com/questions/79691774/efficient-way-creating-a-dict-of-dict-from-a-pandas-dataframe | I have a pandas dataframe of the following structure: d = {'I': ['A', 'B', 'C', 'D'], 'X': [ 1, 0, 3, 1], 'Y': [0, 1, 2, 1], 'Z': [1, 0, 0, 0], 'W': [3, 2, 0, 0]} df = pd.DataFrame(data=d, columns=['I','X', 'Y', 'Z', 'W']) df.set_index('I', inplace=True, drop=True) I need to create a dict of dict to get data of all ex... | You can do this by combining df.iterrows() with a dictionary comprehension. Although iterrows() is not truly vectorized, it's still reasonably efficient for this kind of task and cleaner than using manual nested loops. For example, you could write: edge_dictionary = { node: {attribute: {weight} for attribute, weight in... | 3 | 2 |
79,692,462 | 2025-7-7 | https://stackoverflow.com/questions/79692462/fastmcp-client-timing-out-while-initializing-the-session | I am running a simple FastMCP server locally via the following server side code: from mcp.server.fastmcp import FastMCP server = FastMCP( name="Example-FastMCP", streamable_http_path="/mcp", # ← default but shown for clarity # json_response=True, # stateless_http=True ) @server.tool() def add(x: int, y: int) -> int: re... | On my computer it hangs on session.initialize(). It works when I use async with to create session async with ClientSession( read_stream=read_stream, write_stream=write_stream, read_timeout_seconds=timedelta(seconds=100), ) as session: init_result = await session.initialize() # ... rest ... But I don't know how to writ... | 2 | 0 |
79,692,191 | 2025-7-7 | https://stackoverflow.com/questions/79692191/in-python-how-to-find-difference-between-a-specific-column-in-one-dataframe-and | I have two datasets/dataframes df1 and df2, I want to generate df3 by finding the difference between numeric columns of df2 and df1's column_X. #### copy and paste below to generate df1 and df2 import pandas as pd from random import uniform import numpy as np # generation of df1 data = np.random.uniform(15,40, size=(60... | Copy and then broadcast-subtract: import pandas as pd import numpy as np np.random.seed(0) a, b = ab = np.random.uniform(low=15, high=40, size=(2, 60)) df1 = pd.DataFrame({ 'column_A': a, 'column_B': b, 'column_X': ab.mean(axis=0), }) df2 = pd.DataFrame( data=np.random.uniform(low=10.5, high=32.8, size=(60, 30)), colum... | 1 | 2 |
79,695,414 | 2025-7-9 | https://stackoverflow.com/questions/79695414/how-to-get-mutual-followers-mutual-friend-for-users-django | How do I get mutual followers (friends of friends) with request.user to be displayed for each users posts, I was able to display the count for mutual followers for each users posts on newsfeed. How can I get it done? What I tried: I was able to do this but I do not think it is the best way because when I use slice to s... | As I see it, you are already calculating the mutual follower count, but what you want is to display the actual mutualal follower objects for each post. The reason your original approach with annotate and prefetch_related isnt working is because while annotate is good for counts, it doesn’t fetch related objects. Meanwh... | 1 | 1 |
79,695,252 | 2025-7-9 | https://stackoverflow.com/questions/79695252/position-an-axis-at-a-point-location | I have a plot with a line graph. I need to place a new axis at a point/coordinate and plot a pie chart on the new axis so the pie is centered on the point. import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(6, 3)) ax.set_xlim(0,16) ax.set_ylim(8,12) #Plot a sine wave x ... | You could use the inset_axes method, (based on the last option from this answer) e.g., import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(6, 3)) ax.set_xlim(0,16) ax.set_ylim(8,12) #Plot a sine wave x = np.arange(0, 5*np.pi, 0.1) y = np.sin(x)+10 ax.plot(x, y, color="bl... | 3 | 4 |
79,696,762 | 2025-7-10 | https://stackoverflow.com/questions/79696762/seaborn-histogram-to-plot-survey-answer-frequency-by-gender | I have some survey question answers (letters A, B, C) I'd like to plot in a Seaborn histogram, with the frequency of each response letter grouped by gender. import pandas as pd answers = ['A', 'B', 'A', 'B', 'A', 'A', 'B', 'B', 'B', 'A', 'C', 'B', 'A', 'C'] genders = ['M', 'M', 'F', 'M', 'F', 'M', 'F', 'M', 'M', 'F', '... | You can use a simple countplot: import seaborn as sns sns.countplot(df, x='Answer', hue='Gender') Output: Another option, without seaborn, would be to crosstab, then plot.bar: pd.crosstab(df['Answer'], df['Gender']).plot.bar() Output: Which allows you to easily stack: pd.crosstab(df['Answer'], df['Gender']).plot.ba... | 1 | 1 |
79,699,679 | 2025-7-13 | https://stackoverflow.com/questions/79699679/identifying-outliers-from-opencv-contours-based-on-curvature | I'm processing a photo of the Earth from the Moon, as seen here. What I want to do is get the contour points that correspond to the edge of the Earth that is not in shadow. (e.g., the areas that should form an ellipsoid). I want the physical points on the edge of globe itself, and I'm trying to avoid using Gaussian bl... | RANSAC would be overkill (but good to know about if you don't know) I would suggest RANSAC, as I almost always do when you have a regression whose problem is not accuracy of the data, but numerous outliers. Even more when it is a linear regression (theoretically RANSAC works with any regression. But in practice, there ... | 2 | 3 |
79,700,418 | 2025-7-14 | https://stackoverflow.com/questions/79700418/sympy-mod-on-formulas-with-custom-functions | I would like to define custom sympy functions which cannot be directly evaluated, but which I do want to be able to compute some things about. For example, modular remainders. Here's my code attempt: from sympy import Function class Foo(Function): @classmethod def eval(cls, n): pass def __mod__(self, modulus: int) -> i... | SymPy's symbolic Mod expression type looks for a method called _eval_Mod. You don't need to define __mod__ because Expr.__mod__ already returns Mod(self, other) and Mod will look for the _eval_Mod method: In [2]: from sympy import Function ...: ...: class Foo(Function): ...: @classmethod ...: def eval(cls, n): ...: pas... | 1 | 3 |
79,700,637 | 2025-7-14 | https://stackoverflow.com/questions/79700637/python3-dictionary-being-modified-at-another-thread-does-not-show-changes-after | Python version: (3.9, but the same result with python 3.12) The goal was that another thread modified a dictionary and those modifications to be available at the original thread. import multiprocessing as mp import sys def my_func(result: dict): print(f'variable address at worker: {hex(id(result))}', file=sys.stderr) r... | You are using multiprocessing.Process. That is not a thread, that is a new process. It will inherit the whole address space of the parent process, but then work on its own copy. You will have to use threading.Thread if you want a thread. from threading import Thread def modify_dict(): result['test'] = 'test' print('Res... | 2 | 6 |
79,700,454 | 2025-7-14 | https://stackoverflow.com/questions/79700454/why-does-the-driver-open-two-tabs-by-one-click | I am trying to reach pages by hrefs nested to web elements. But the driver gives me two identical tabs when it click() on the href. It turns out that three tabs are open at the same time. Duplicate pages confuse further work with html. How can I get only one new tab by click? Python 3.11, PyCharm chrome_options = Optio... | The link is opened twice: • the normal <a> fires and Chrome opens a new tab • a JS listener on the same element calls window.open() and opens it again. WebDriver only replicates what the page tells the browser to do, so you have to avoid the click or neutralise the handler. from selenium import webdriver from selenium.... | 3 | 5 |
79,702,280 | 2025-7-15 | https://stackoverflow.com/questions/79702280/is-it-right-to-raise-an-error-in-except-block-in-python | I often see code like this: try: some_operation() except Exception: logger.error("An error occurred while running the operation") raise Exception("A custom message") Please ignore using the general Exception in this example, I know it's a bad practice. You can think of any other more specific subclasses of Exception. ... | This general pattern is an accepted practice. It allows a more meaningful message to be written for the user of the code as well as logging a more meaningful message for the developer. From the docs: The most common pattern for handling Exception is to print or log the exception and then re-raise it (allowing a caller... | 1 | 2 |
79,701,884 | 2025-7-15 | https://stackoverflow.com/questions/79701884/indicating-which-column-wins-in-a-df-min-call | I want to find the minimum value per row and create a new column indicating which of those columns has the lowest number. Unfortunately, it seems like pandas isn't immediately able to help in this regard. My research has led to the min() function, which does find the lowest for each row (when axis=1), but there's no fu... | A possible solution, which uses idxmin: initialDf.assign(min = initialDf.idxmin(axis=1)) Output: Value 1 Value 2 Value 3 min A 6.53 11.47 92.08 Value 1 B 9.11 8.15 12.49 Value 2 | 2 | 3 |
79,701,508 | 2025-7-15 | https://stackoverflow.com/questions/79701508/cache-updates-in-chatbot-when-adding-new-documents | I'm building a chatbot to answer legal-related questions. I'm facing an issue with caching questions and responses — the goal is to retrieve an answer when someone asks a similar question that's already been saved. However, when I add new documents to the chatbot, the previously cached questions don't include informati... | Here is a very naive approach to such a scenario. Our assumptions are: Your vector store initially contains N documents and any queries to which relevant context exists is cached. When the vector store is updated (i.e count of documents change) you want the cached items to be updated. from langchain_core.caches imp... | 2 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.