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,557,781
2025-4-6
https://stackoverflow.com/questions/79557781/error-using-cv2-in-python3-13-free-threading-mode
Without python3.13 free-threading, cv2 importing numpy is fine. But when python3.13 free-threading is turned on, when cv2 tries to import numpy, numpy gives this error: ImportError: Error importing numpy: you should not try to import numpy from its source directory; please exit the numpy source tree, and relaunch your ...
Starting with the 3.13 release, CPython has experimental support for a build of Python called free threading where the global interpreter lock (GIL) is disabled. [...] The free-threaded mode is experimental and work is ongoing to improve it: expect some bugs and a substantial single-threaded performance hit. (From: h...
1
1
79,556,592
2025-4-5
https://stackoverflow.com/questions/79556592/how-to-repeat-and-truncate-list-elements-to-a-fixed-length
I have data that looks like: lf = pl.LazyFrame( { "points": [ [ [1.0, 2.0], ], [ [3.0, 4.0], [5.0, 6.0], ], [ [7.0, 8.0], [9.0, 10.0], [11.0, 12.0], ], ], "other": ["foo", "bar", "baz"], }, schema={ "points": pl.List(pl.Array(pl.Float32, 2)), "other": pl.String, }, ) And I want to make all lists have the same number o...
The repr defaults for lists are quite small, so we will increase them for the example. pl.Config(fmt_table_cell_list_len=8, fmt_str_lengths=120) If you use pl.int_ranges() (plural) and modulo arithmetic, you can generate the indices. target_length = 5 lf.select(pl.int_ranges(target_length) % pl.col("points").list.len(...
2
2
79,553,519
2025-4-3
https://stackoverflow.com/questions/79553519/optimizing-k-ij-free-subgraph-detection-in-a-bounded-degree-graph
I am working with an undirected graph G where the maximum degree is bounded by a constant d. My goal is to check whether G contains a complete bipartite subgraph K_{i,j} as a subgraph, for small values of i, j (specifically, i, j < 8). I currently use the following brute-force approach to detect a K_{i,j} subgraph: nod...
I incorporated an idea from the comments. I’m iterating through the nodes and, for each node, only consider its neighbors to construct the subgraph K_ij. This reduces the complexity of generating all possible combinations, but it’s still exponential for graphs with a high degree. def is_k_ij_free(self, i: int, j: int) ...
3
2
79,557,806
2025-4-6
https://stackoverflow.com/questions/79557806/how-to-gracefully-ignore-non-matching-keyword-matching-arguments-in-python-datac
With normal classes you have **kwargs in the __init__ so non-matching keyword arguments can be ignored: class MyClass: def __init__(self, a, **kwargs): self.a=a my_class = MyClass(20, **{"kwarg1" : 1}) Is there an equivalent for @dataclass that can gracefully ignore non-matching keyword arguments without having to inc...
TL;DR No, it's impossible This scenario was even quoted in the original pep introducing dataclass. I think it's against the original assumptions around dataclass - which would be simplify semantics at the expense of making functionality less flexible. vide pep-0557 Sometimes the generated init method does not suffice....
2
1
79,553,451
2025-4-3
https://stackoverflow.com/questions/79553451/generating-a-discrete-polar-surface-map-in-cartesian-coordinates
I would like to generate a surface plot with discrete arc-shaped cells on a 2D cartesian plane. I am able to get decent results by plotting a 3D surface plot (using plot_surface) and viewing it from the top, but matplotlib can be a bit finicky with 3D, so I'd prefer to do it in 2D. I can also get similar results using ...
One solution could be to put together the plot from wedge patches. import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import Wedge from matplotlib.collections import PatchCollection r = np.linspace(2, 5, 25) theta = np.linspace(0, np.pi, 25) r_mid = 0.5 * (r[:-1] + r[1:]) theta_mid = 0.5 * (the...
2
2
79,557,330
2025-4-5
https://stackoverflow.com/questions/79557330/how-can-i-fix-a-problem-regarding-problem-regarding-l1dist-call
class L1Dist(Layer): def __init__(self, **kwargs): super().__init__() def call(self, input_embedding, validation_img): return tf.math.abs(input_embedding - validation_img) Signature of method 'L1Dist.call()' does not match signature of the base method in class'Layer' how can i fix this problem?
I found the solution : class L1Dist(Layer): def __init__(self, **kwargs): super(L1Dist, self).__init__(**kwargs) def call(self, inputs, *args, **kwargs): input_embedding, validation_embedding = inputs return tf.math.abs(input_embedding - validation_embedding) Instead of having input_embedding and validation_embedding ...
1
0
79,556,412
2025-4-5
https://stackoverflow.com/questions/79556412/polars-efficient-list-of-substrings-counting
I have a Polars dataframe corpus with one string column, and millions of rows. I also have a list of substrings substrings. I can take a substring and query in how many rows that substring appears with: corpus.select(pl.col('contents').str.contains(substrings[0]).sum()).item() This works well for one substring, but I ...
substrings = ["ab", "abc", "c"] df = pl.DataFrame({ "contents": ["abcMMmcICm", "ckIJCwjVab", "JTQHufYcpo", "SNoqabcpMY", "SYbEsasrzt"] }) .str.extract_many() has been the fastest way I've found to do this. df.with_columns( pl.col("contents").str.extract_many(substrings).alias("substring") ) shape: (5, 2) ┌───────────...
1
1
79,556,360
2025-4-4
https://stackoverflow.com/questions/79556360/pytest-fixture-is-changing-the-instance-returned-by-another-fixture
I'm very baffled and a little concerned to discover the following behaviour where I have two tests and two fixtures. import pytest @pytest.fixture def new_object(): return list() @pytest.fixture def a_string(new_object): # Change this instance of the object new_object.append(1) return "a string" def test_1(new_object):...
The fixture new_object is invoked for each test as you clearly stated from the documentation. The issue lies within your second fixture and the usage of the combination of both in your second test. As pytest allows you to use fixtures more than once per test without affecting each other by using cached returns. That me...
1
3
79,555,544
2025-4-4
https://stackoverflow.com/questions/79555544/matplotlib-animation-doesnt-clear-previous-frame-before-plotting-new-one
So, I'm trying to create an animated plot, but I want the previous frame to be cleared before a new one appears. What I keep getting is all frames at the same time or just a blank plot. fig, ax = plt.subplots() campo = ax.plot(x2[0], phiSol[0])[0] def init(): campo.set_data([],[]) return campo def update(frame): campo...
It's your slicing that's causing the problem. with :frame you're slicing up to frame instead of just grabbing the frame you want. You may have copied an example with a moving point that traces out a line . I just tried this, and it worked how you described. import numpy as np import matplotlib.pyplot as plt from matpl...
2
3
79,555,896
2025-4-4
https://stackoverflow.com/questions/79555896/python-script-locked-by-thread
I would like this Python 3.10 script (where the pynput code is partially based on this answer) to enter the while loop and at the same time monitor the keys pressed on the keyboard. When q is pressed, I would like it to end. (I do not know threads very well, but the while loop probably should run in the main thread and...
you are joining the listener thread, ie: waiting for it to exit. remove the while loop. the join is already waiting for the thread to exit. also from the docs Call pynput.keyboard.Listener.stop from anywhere, raise StopException or return False from a callback to stop the listener. you are waiting for the listener to...
1
1
79,555,775
2025-4-4
https://stackoverflow.com/questions/79555775/concatenate-rows-for-two-columns-in-panda-dataframe
I have the following dataframe: import pandas as pd d = {'Name': ['DataSource', 'DataSource'], 'DomainCode': ['Pr', 'Gov'], 'DomainName': ['Private', 'Government']} df = pd.DataFrame(data=d) So the dataframe is as follows: Name DomainCode DomainName 0 DataSource Pr Private 1 DataSource Gov Government I need to group...
Please use the following line: df_grouped = df.groupby("Name").agg(list).reset_index() When you run this line df_grouped = df.groupby("Name")["DomainCode"].apply(list).reset_index() It returns 1 instead of 2 because Pandas is storing the list as a single string ('[Pr, Gov]') rather than a true Python list. For conver...
1
1
79,553,686
2025-4-3
https://stackoverflow.com/questions/79553686/how-to-flatten-a-mapping-constructed-from-a-tagged-scalar-using-ruamel-yaml
My aim is to create a YAML loader that can construct mappings from tagged scalars. Here is a stripped-down version of the loader which constructs an object containing names from a scalar tagged !fullname. import ruamel.yaml class MyLoader(ruamel.yaml.YAML): def __init__(self, *args, **kwargs): super().__init__(*args, *...
The merge key language indepent type for YAML definition states: The “<<” merge key is used to indicate that all the keys of one or more specified maps should be inserted in to the current map. If the value associated with the key is a single mapping node, each of its key/value pairs is inserted into the current mapp...
1
1
79,550,367
2025-4-2
https://stackoverflow.com/questions/79550367/snakemake-in-cluster-different-ways
When running snakemake on a cluster, and if we don't have specific requirements for some rules about number of cores/memory, then what is the difference between : Using the classic way, i.e. calling snakemake on the login node, telling it that executor is slurm and that we want X jobs with X cores each, optionally wit...
With the second way, your whole workflow will have to wait in the queue before individual rule instances can start. With the first way the resource demand will be spread across the jobs that snakemake will submit, so each rule has a chance to start earlier than what you would have to wait in the second way. (I use a th...
1
1
79,554,176
2025-4-3
https://stackoverflow.com/questions/79554176/how-to-randomly-sample-n-ids-for-each-combination-of-group-id-and-date-in-a-pola
I am trying to randomly sample n IDs for each combination of group_id and date in a Polars DataFrame. However, I noticed that the sample function is producing the same set of IDs for each date no matter the group. Since I need to set a seed for replication purposes, I believe the issue is occurring because the same see...
If you need each group to be random but you also need to be able to set a seed to get predictable results then use numpy to generate random numbers and then choose your sample based on those like this. (Technically you could use base python to generate the random numbers but it's slower) First approach n_samples = 3 SE...
1
1
79,555,053
2025-4-4
https://stackoverflow.com/questions/79555053/group-by-and-apply-multiple-custom-functions-on-multiple-columns-in-python-panda
Consider the following dataframe example: id date hrz tenor 1 2 3 4 AAA 16/03/2010 2 6m 0.54 0.54 0.78 0.19 AAA 30/03/2010 2 6m 0.05 0.67 0.20 0.03 AAA 13/04/2010 2 6m 0.64 0.32 0.13 0.20 AAA 27/04/2010 2 6m 0.99 0.53 0.38 0.97 AAA 11/05/2010 2 6m 0.46 0.90 0.11 0.14 AAA 25/05/2010 2 6m 0.41 0.06 0.96 0.31 AAA 08/06/20...
Use GroupBy.agg with DataFrame.stack for reshape last level of MultiIndex in columns: cols = ['id','hrz', 'tenor'] out = (df.groupby(cols)[df.columns.difference(cols + ['date'], sort=False)] .agg([ks_test, cvm_test]) .rename_axis([None, 'test'], axis=1) .stack(future_stack=True) .reset_index()) print (out) id hrz tenor...
1
2
79,554,664
2025-4-4
https://stackoverflow.com/questions/79554664/colorbar-warning-with-pcolor-and-np-nan
I have an array with np.nan values which I want to plot using pcolor. In principle everything works, but I get a warning I cannot get rid of. Using plt.imshow does not give the warning, but I need to specify the x and y coordinates. MatplotlibDeprecationWarning: Getting the array from a PolyQuadMesh will return the fu...
This warning is due to a change in how the internal pcolor logic is structured (changenote here). It is triggered when the colorbar code internally calls get_array on the object returned by pcolor. You can silence the warning by explicitly re-passing your Z array to the set_array method: pc = plt.pcolor(Y,X,Z, cmap='vi...
1
2
79,553,855
2025-4-3
https://stackoverflow.com/questions/79553855/overlaping-subplots-vertically-stacked
While reading a paper for my thesis I encountered this graph (b): I've tried to recreate the second graph which is the one I would like to use for my results: import numpy as np import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec years = np.linspace(1300, 2000, 700) np.random.seed(42) delta_13C = ...
The main change you'll need to make is to make the background color of your Axes transparent and to use a negative hspace to force the graphs to overlap a bit more: plt.rcParams['axes.facecolor'] = 'none' # transparent Axes background gs = GridSpec(3, 1, height_ratios=[1, 1, 1], hspace=-.1) # negative hspace for overla...
2
2
79,551,690
2025-4-2
https://stackoverflow.com/questions/79551690/drawing-from-opencv-fillconvexpoly-does-not-match-the-input-polygon
I'm trying to follow the solution detailed at this question to prepare a dataset to train a CRNN for HTR (Handwritten Text Recognition). I'm using eScriptorium to adjust text segmentation and transcription, exporting in ALTO format (one XML with text region coordinates for each image) and parsing the ALTO XML to grab t...
You called cv.fillConvexPoly(). Your polygon is not convex. The algorithm assumed it to be convex and took some shortcuts to simplify the drawing code, so it came out wrong. Use cv.fillPoly() instead. That will draw non-convex polygons correctly. As you point out, the function signatures are not drop-in compatible. fil...
2
2
79,552,738
2025-4-3
https://stackoverflow.com/questions/79552738/create-a-legend-taking-into-account-both-the-size-and-color-of-a-scatter-plot
I am plotting a dataset using a scatter plot in Python, and I am encoding the data both in color and size. I'd like for the legend to represent this. I am aware of .legend_elements(prop='sizes') but I can have either colors or sizes but not both at the same time. I found a way of changing the marker color when using pr...
Using legend_elements, you can get the size and a colour-based legend elements separately, then set the colours of the former with the latter. E.g., import pandas as pd import numpy as np import matplotlib.pyplot as pl time = pd.DataFrame(np.random.rand(10)) intensity = pd.DataFrame(np.random.randint(1,5,10)) df = pd.c...
1
1
79,552,332
2025-4-3
https://stackoverflow.com/questions/79552332/unloading-kivy-builder-rules-more-than-once-in-order-to-re-import-gui-elements
I would like to import optional GUI elements defined in separate Mod1.py/Mod2.py/etc files and add/remove these dynamically from the main GUI. The separate files that define these optional GUI elements, contain kv strings. In my use case, these GUI elements can be unloaded/reloaded multiple times. I discovered that if ...
I think the importlib will not import a module if it has already been loaded. In that case, you can use importlib.reload(). Try modifying your MainWidget class to do that. Something like: class MainWidget(BoxLayout): def __init__(self): self.current_module1 = None self.current_module2 = None super(MainWidget, self).__i...
1
2
79,552,670
2025-4-3
https://stackoverflow.com/questions/79552670/convert-a-column-containing-a-single-value-to-row-in-python-pandas
Consider the following dataframe example: maturity_date simulation simulated_price realized_price 30/06/2010 1 0.539333333 0.611 30/06/2010 2 0.544 0.611 30/06/2010 3 0.789666667 0.611 30/06/2010 4 0.190333333 0.611 30/06/2010 5 0.413666667 0.611 Apart from setting aside the value of the last column and concatenating,...
Maybe easier is processing dictionary from last row, DataFrame.pop trick is for remove original column realized_price: d = df.iloc[-1].to_dict() d['simulated_price'] = d.pop('realized_price') d['simulation'] = 'realized_price' df.loc[len(df.pop('realized_price'))] = d Alternative: last = df.columns[-1] d = df.iloc[-1]...
1
2
79,552,639
2025-4-3
https://stackoverflow.com/questions/79552639/django-select2-autocomplete-how-to-pass-extra-parameter-argid-to-the-view
I'm using Django with django-autocomplete-light and Select2 to create an autocomplete field. The Select2 field is dynamically added to the page when another field is selected. It fetches data from a Django autocomplete view, and everything works fine. Now, I need to filter the queryset in my autocomplete view based on ...
Just pass them as query params /myautocomplete/class?title=title_1 and you can catch them in the class class ElementAutocomplete(LoginRequiredMixin, autocomplete.Select2QuerySetView): def get_queryset(self): title = self.request.GET.get("title") qs = MyModel.objects.all() if title is not None: qs.filter(title__icontain...
1
1
79,551,904
2025-4-3
https://stackoverflow.com/questions/79551904/how-to-preprocess-multivalue-attributes-in-a-dataframe
Description: Input is a CSV file CSV file contains columns of different data types: Ordinal Values, Nominal Values, Numerical Values and Multi Value For the multivalue columns. Minimum is 1, maximum is 5 values. The input is similar to this: Job Perks Insurance Benefits Online Courses; Certification Program...
You could combine str.get_dummies, add_prefix, and pd.concat with a generator: out = pd.concat( ( df[col].str.get_dummies(sep='; ').add_prefix(f'{col}_') for col in multivalueColumns ), axis=1, ) Output: Job Perks_Certification Programs Job Perks_Cross Training Job Perks_Leadership Development Programs Job Perks_Onli...
3
3
79,549,771
2025-4-2
https://stackoverflow.com/questions/79549771/efficiently-filter-list-of-permutations
I would like to efficiently generate a list of "valid" permutations from a given list. By way of simple example, suppose I would like to generate the permutations of [1,2,3] where 3 is in one of the first two positions. My return result would then be [[3,1,2], [3,2,1], [1,3,2],[2,3,1]] Currently, I can solve this probl...
You'll need a custom solution for that, covering all the types of constraints that you could have. In your examples I can see two types of constraints: A constraint whereby all values in a given set must occur in a certain range (start, end) The size of the produced partial permutations In Python you could think of a...
3
5
79,548,517
2025-4-1
https://stackoverflow.com/questions/79548517/how-to-use-redmon-for-generating-multiple-outputs-tspl-and-pdf
I have printer TSC TE 210. I created virtual printer on a RedMon port and installed TSC driver on it. I am able to generate printfile.prn file using redmon (redirecting output to python, that will edit the data and create .prn file), that has TSPL commands it it, e.g.: SIZE 97.6 mm, 50 mm GAP 3 mm, 0 mm DIRECTION 0,0 R...
This is a good question and from long discussions we get to the hub of an XY problem. Only one print type (text, vector or raster) at a time, can be one applications printout. In this case the desire is Textual TSPL (203 DPI: 1 mm = 8 dots) and vector PDF 1000 sub units = 1/72" (printer point). PDF is not a good source...
1
1
79,550,040
2025-4-2
https://stackoverflow.com/questions/79550040/why-is-jax-treating-floating-point-values-as-tracers-rather-than-concretizing-th
I am doing some physics simulations using jax, and this involves a function called the Hamiltonian defined as follows: # Constructing the Hamiltonian @partial(jit, static_argnames=['n', 'omega']) def hamiltonian(n: int, omega: float): """Construct the Hamiltonian for the system.""" H = omega * create(n) @ annhilate(n) ...
The fundamental issue is that you cannot differentiate with respect to a static variable, and if you try to do so you will get the error you observed. This is confusing me, because I no longer know what qualifies as static or dynamic variables anymore, from the definition that static variables does not change between ...
1
1
79,549,881
2025-4-2
https://stackoverflow.com/questions/79549881/how-to-resample-a-dataset-to-achieve-a-uniform-distribution
I have a dataset with a schema like: df = pl.DataFrame( { "target": [ [1.0, 1.0, 0.0], [1.0, 1.0, 0.1], [1.0, 1.0, 0.2], [1.0, 1.0, 0.8], [1.0, 1.0, 0.9], [1.0, 1.0, 1.0], ], "feature": ["a", "b", "c", "d", "e", "f"], }, schema={ "target": pl.Array(pl.Float32, 3), "feature": pl.String, }, ) If I make a histogram of th...
I don't think you can avoid those three steps for resampling (although depending on your use case you could try to transform the data instead) You can optimize that code a bit though, import polars as pl import numpy as np # Some random mocked data rng = np.random.default_rng() df = pl.DataFrame({'z': rng.lognormal(siz...
2
2
79,550,795
2025-4-2
https://stackoverflow.com/questions/79550795/python-dataframe-structure-breaks-when-appending-the-file
I am trying to get user inputs to create a file where users can store website, username, and password in table format whenever users hit a button. I made the function below, and it looks okay to me. However, when a user enters the second and third entries, the data frame structure is broken. Any idea why it happens? Yo...
The confusion is caused by writing the .CSV with a ; separator but ignoring this on reading. Use: else: data = pd.read_csv("MyPassword_test.txt") data = pd.concat([data, input_entries_df], ignore_index=True) print(data) data.to_csv("MyPassword_test.txt", index=False)
1
2
79,550,287
2025-4-2
https://stackoverflow.com/questions/79550287/python-descriptors-on-readonly-attributes
I want to refactor a big part of my code into a generic descriptor for read only attribute access. The following is an example of property based implementation class A: def __init__(self, n): self._n = n self._top = -1 @property def n(self): return self._n @property def top(self): return self._top def increase(self): s...
Instead of disallowing all modifications, simply check if the attribute exists on instance before creating it. If it already exists, raise the AttributeError. Otherwise, let the attribute be created. def __set__(self, instance, value): if self._name in instance.__dict__: raise AttributeError("Can't set attribute") inst...
1
2
79,550,276
2025-4-2
https://stackoverflow.com/questions/79550276/how-to-load-a-pdf-from-bytes-instead-of-file-in-pyside6
I'm trying to display a PDF I created (using fpdf2) in a Pyside6 app. There seems to be two roads there: I can use QWebEngineView with plugins enabled, in which I can inject the PDF raw bytes, which works. It is not ideal for me since there's a lot of UI involved ; I'd like something cleaner. Or I can use QPdfView. T...
You need to use a QBuffer (which inherits QIODevice) backed by a QByteArray containing the pdf bytes data. The buffer doesn't take ownership of the data, and the document doesn't take ownership of the buffer, so you need to ensure these objects are kept alive whilst the pdf is loading. A slot connected to the statusCha...
2
1
79,549,767
2025-4-2
https://stackoverflow.com/questions/79549767/create-a-new-file-moving-an-existing-file-out-of-the-way-if-needed
What is the best way to create a new file in Python, moving if needed an existing file with the same name to a different path? While you could do if os.path.exists(name_of_file): os.move(name_of_file, backup_name) f = open(name_of_file, "w") that has TOCTOU issues (e.g. multiple processes could try and create the file...
In a loop: Open the file exclusively (open(..., "x") or O_CREAT|O_EXCL). If that fails with FileExistsError (EEXIST), then atomically os.rename the existing file to something else. Try again. If that renaming fails with anything other than FileExistsError (ENOENT, meaning someone else removed or renamed the offending f...
2
3
79,548,581
2025-4-1
https://stackoverflow.com/questions/79548581/jwt-token-expiration-handling-causing-500-error-in-flask-jwt-extended-and-flask
Problem: I'm building a Flask backend using flask-restful, flask-jwt-extended, and PostgreSQL. When testing JWT token expiration via Postman, expired tokens consistently result in a 500 Internal Server Error instead of a 401 Unauthorized response. Desired Behavior: When a JWT token expires, my API should return a JSON ...
Figured out that I had to force handling JWT exceptions globally: Configured Flask and Flask-RESTful to propagate JWT exceptions correctly by adding the following code to init.py: app.config['PROPAGATE_EXCEPTIONS'] = True # Propagate exceptions to the client api.handle_errors = False # Disable Flask-RESTful This provi...
2
1
79,550,403
2025-4-2
https://stackoverflow.com/questions/79550403/get-a-row-subset-of-a-pandas-dataframe-based-on-conditions-with-query
I would like to gain a subset of a Pandas Dataframe based on query, if possible giving several conditions based on column values where only rows have to be selected until conditions appear for the first time. Probably this is nothing new. I do just not find the right answers from other posts. The example Dataframe: i...
You can use cummin to compute your second condition: df_GPS[df_GPS['__UTCs__'].ge(22960) & df_GPS['s01[m]'].lt(16).cummin()] Output: time __UTCs__ Altitude s01[m] s5.5[m] s10[m] 2 2024-06-21 06:22:40 22960 605.630573 1 2 0 3 2024-06-21 06:22:41 22961 605.476367 3 3 0 4 2024-06-21 06:22:42 22962 605.322161 2 1 1 5 202...
2
2
79,549,626
2025-4-2
https://stackoverflow.com/questions/79549626/why-does-sort-with-key-function-not-do-anything-while-sorted-is-working
I have a list of integers with duplicates and I need to sort it by the number of these duplicates. For example: input: n = [2, 4, 1, 2] output: n = [4, 1, 2, 2] I wrote some code and noticed, that sort() does not change the list. But if I try to use sorted() with the same key argument, then it works just fine. What is...
Unlike sorted, the list.sort method sorts a list in-place, during which time the list is in an interim state where there is no integrity to its internal data structure for the other methods to read from. Since a key function for the sort method is called during a sort, your calling the count method of the same list in ...
4
5
79,547,850
2025-4-1
https://stackoverflow.com/questions/79547850/why-is-the-bounding-box-not-aligned-to-the-square
import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import Rectangle def generate_square_image(size, square_size, noise_level=0.0): """ Generates an image with a white square in the center. Args: size (int): The size of the image (size x size). square_size (int): The size of the square. noise_lev...
Fixes: 1. Subtract 0.5 from x and y in Rectangle().Matplotlib positions pixels at the center of grid cells, but imshow() assumes pixel edges align exactly with grid lines. Adjusting by -0.5 shifts the bounding box to align properly. 2. origin='upper' ensures consistency with NumPy's top-left origin. 3. Hiding axis tick...
3
3
79,549,110
2025-4-1
https://stackoverflow.com/questions/79549110/huggingface-tokenizer-str-object-has-no-attribute-size
I am trying to extract the hidden states of a transformer model: from transformers import AutoModel import torch from transformers import AutoTokenizer model_ckpt = "distilbert-base-uncased" device = torch.device("cuda" if torch.cuda.is_available() else "cpu") tokenizer = AutoTokenizer.from_pretrained(model_ckpt) model...
The issue is happening when you're filtering the dictionary, extract_hidden_states in your extract_hidden_states() function. This dictionary includes keys like 'text' (which contains strings), the function may mistakenly try to .to(device) on a string, which I'm guessing is causing the error here. You can modify your f...
1
2
79,549,000
2025-4-1
https://stackoverflow.com/questions/79549000/pydantic-object-self-validation
I am trying to understand the way validation works in pydantic. I create a class and three objects: import pydantic class TestClass(pydantic.BaseModel): id: int = 'text' name: str obj0 = TestClass(id=1, name="test") obj1 = TestClass(name="test") obj2 = TestClass.model_construct(id=2) One may see that first object is t...
By default Pydantic does not re-validate instances, because it assumes they have been validated. This is configurable, the docs is here In your test program, all you need is to update the TestClass definition: class TestClass(pydantic.BaseModel, revalidate_instances='always'): ... (There is also another related option...
1
2
79,548,243
2025-4-1
https://stackoverflow.com/questions/79548243/how-to-do-a-groupby-on-a-cxvpy-variable-is-there-a-way-using-pandas
I would like to define a loss function for the CVXPy optimization that minimizes differences from the reference grouped target: import cvxpy as cp import pandas as pd # toy example for demonstration purpose target = pd.DataFrame(data={'a': ['X', 'X', 'Y', 'Z', 'Z'], 'b': [1]*5}) w = cp.Variable(target.shape[0]) beta = ...
Based on my understanding, your code calculates the sum of weighted values (w @ beta) grouped by the unique values in column "a". However, since Pandas cannot handle CVXPY variables, this approach results in errors. The hstack method, on the other hand, uses native CVXPY functions like cp.sum() and cp.hstack(), making ...
1
1
79,548,754
2025-4-1
https://stackoverflow.com/questions/79548754/reshape-4d-array-to-2d
I have the array import numpy as np a1 = [["a1", "a2"], ["a3", "a4"], ["a5", "a6"], ["a7", "a8"]] b1 = [["b1", "b2"], ["b3", "b4"], ["b5", "b6"], ["b7","b8"]] c1 = [["c1", "c2"], ["c3", "c4"], ["c5", "c6"], ["c7","c8"]] arr = np.array([a1, b1, c1]) #arr.shape #(3, 4, 2) Which I want to reshape to a 2D array: ["a1","b1...
What you want is to stack the arrays such that the final 2D shape is (8, 3), where each row contains the same index from each original array. So the key is to use np.array(arr).transpose(1, 2, 0).reshape(-1, 3). Code Example: import numpy as np a1 = [["a1", "a2"], ["a3", "a4"], ["a5", "a6"], ["a7", "a8"]] b1 = [["b1", ...
2
2
79,548,492
2025-4-1
https://stackoverflow.com/questions/79548492/cant-install-numpy-with-pypy-7-3-19
I'm trying to install numpy (2.2.3) with PyPy 7.3.19 (Python 3.11.11). I'm using PyPy in a .venv folder. While the venv is active, I've tried running these commands: python -m pip install numpy pip install numpy pypy -m pip install numpy First windows flagged the install as a virus: This was fixed by allowing the th...
There are wheels for the next NumPy version available on anacoda.org, you can use them with ` pip install -i https://pypi.anaconda.org/scientific-python-nightly-wheels/simple numpy
1
2
79,547,496
2025-4-1
https://stackoverflow.com/questions/79547496/use-greater-equal-less-comparison-result-as-dictionary-key
Is there a clean way to store the values comparison result as dictionary key, naming >, =, and < (not the str format, but the state of "greater" for example). Curious if this could be a way to replace wordy if a > b: print(f'{a} > {b}') elif a == b: print(f'{a} = {b}') else: print(f'{a} < {b}') with a dict d = { >: '{...
The operator module contains actual function objects for greater-than, less-than, equal, etc. import operator d = { operator.gt: '{a} > {b}', operator.eq: '{a} = {b}', operator.lt: '{a} < {b}', }
1
1
79,565,969
2025-4-10
https://stackoverflow.com/questions/79565969/importerror-when-importing-numpy-missing-libgfortran-5-dylib-on-macos-vs-code
I’m working on macOS Sequoia 15.4, using VS Code and Jupyter Notebooks with Conda environments. Everything worked fine until yesterday. Now, when I try to run any of my existing environments, importing NumPy or other scientific libraries results in the following ImportError related to libgfortran.5.dylib. ImportError: ...
As mentioned previously, this is similar to this question. MacOS Sequoia 15.4.1 update raises an error for duplicate R paths, which triggers the error you mentioned for typically 'old' environments. If you don't want to re-create an environment, you can try to install libgfortran5 package to its version which avoids th...
1
5
79,573,221
2025-4-14
https://stackoverflow.com/questions/79573221/keep-context-vars-values-between-fastapi-starlette-middlewares-depending-on-the
I am developing a FastAPI app, and my goal is to record some information in a Request scope and then reuse this information later in log records. My idea was to use context vars to store the "request context", use a middleware to manipulate the request and set the context var, and finally use a LogFilter to attach the ...
Currently dealing with a similar setup and I spent some time digging.. I'm not sure if this truly answers the why in your question but what I found is that if I use a custom middleware class without inheriting from BaseHTTPMiddleware (à la Pure ASGI Middleware) the context variables get propagated correctly to the uvic...
2
1
79,573,908
2025-4-14
https://stackoverflow.com/questions/79573908/openai-assistants-with-citations-like-42-source-and-citeturnxfiley
When streaming with OpenAI Assistants openai.beta.threads.messages.create( thread_id=thread_id, role="user", content=payload.question ) run = openai.beta.threads.runs.create( thread_id=thread_id, assistant_id=assistant_id, stream=True, tool_choice={"type": "file_search"}, ) streamed_text = "" for event in run: if event...
The approach I've used was to get the final message after streaming messages = openai.beta.threads.messages.list(thread_id=thread_id) and then apply the following regex def replace_placeholder(match): nonlocal citation_index citation_index += 1 return f"[{citation_index}]" pattern = r"(citeturn\d+file\d+|【\d+:\d+†....
1
1
79,572,368
2025-4-14
https://stackoverflow.com/questions/79572368/parsing-pydantic-dict-params
I have an endpoint that takes a Pydantic model, Foo, as a query parameter. from typing import Annotated import uvicorn from fastapi import FastAPI, Query from pydantic import BaseModel app = FastAPI() class Foo(BaseModel): bar: str baz: dict[str, str] @app.get("/") def root(foo: Annotated[Foo, Query()]): return foo if ...
It is indeed a complex subjects for which I see mainly 2 paths forward. Parse your dictionary from the query It is actually possible to get the dictionary back from the query parameters: from pydantic import BaseModel, Json class Foo(BaseModel): bar: str baz: Json When baz will receive the Json string, it will be pars...
1
3
79,571,481
2025-4-13
https://stackoverflow.com/questions/79571481/get-current-function-name
Executing vscode.executeDocumentSymbolProvider gives me all symbols in the file. Can I somehow get name of the function that the cursor is currently in?
If you only want the top-most outer function that the cursor is in, then the answer is fairly straightforward. If you wanted to consider multiple nested functions then it get much trickier. Scan through the symbols. finding the symbol range that contains the cursor: const symbols = await vscode.commands.executeCommand(...
1
1
79,573,420
2025-4-14
https://stackoverflow.com/questions/79573420/should-i-always-use-asyncio-lock-for-fairness
I have a Python service that uses Python's virtual threads (threading.Thread) to handle requests. There is a shared singleton functionality that all threads are trying to access, which is protected using threading.Lock. g_lock = threading.Lock() def my_threaded_functionality(): try: g_lock.acquire() # ... Do something ...
Python's virtual threads (threading.Thread) CPython threads are native threads, not virtual threads, the concept of virtual threads doesn't exist in CPython. asyncio's Lock is not thread-safe, you cannot use it for multithreaded synchronization, only threading.Lock is safe for multithreaded access. you can serialize ...
1
1
79,567,168
2025-4-10
https://stackoverflow.com/questions/79567168/how-can-i-get-llvm-loop-vectorization-debug-output-in-numba
I'm trying to view LLVM debug messages for loop vectorization using Numba and llvmlite. I want to see the loop vectorization "LV:" debug output (e.g., messages like LV: Checking a loop in ...) so I can analyze the vectorization decisions made by LLVM. https://numba.readthedocs.io/en/stable/user/faq.html#does-numba-vect...
On Linux, a workaround solution for tests is to use Numba 0.60.0. Indeed, it is based on LLVMlite v0.43.0 which is build with an LLVM version having assertions. On Linux, newer versions (e.g. Numba 0.61.2 and LLVMlite v0.44.0) do not embed an LLVM supporting assertions (apparently due to a code cleaning). Thus it must ...
1
2
79,573,449
2025-4-14
https://stackoverflow.com/questions/79573449/removing-elements-based-on-nested-dictionary-values
I have a complex nested dictionary structure and I need to remove elements based on the values in a nested dictionary. My dictionary looks like this: my_dict = { 'item1': {'name': 'Apple', 'price': 1.0, 'category': {'id': 1, 'name': 'Fruit'}}, 'item2': {'name': 'Banana', 'price': 0.5, 'category': {'id': 1, 'name': 'Fru...
As a dictionary comprehension A dictionary comprehension can be used to create dictionaries from arbitrary key and value expressions. new_dict2 = { key: value for key, value in my_dict.items() if value['category']['name'] == 'Fruit' } new_dict2 == new_dict # True Using filter() The filter() function is used to: Const...
7
6
79,574,127
2025-4-14
https://stackoverflow.com/questions/79574127/cannot-see-all-dense-layer-info-from-search-space-summary-when-using-rand
I am trying to use keras-tuner to tune hyperparameters, like !pip install keras-tuner --upgrade import keras_tuner as kt from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Flatten from tensorflow.keras.optimizers import Adam def build_model(hp): model = Sequential([ Flatten(input_...
Each hyperparameter must have a unique name. This is also listed in the docs. In your case, both layer units parameters are called units . You should rename them to something like units_1 and units_2, for example.
2
2
79,574,115
2025-4-14
https://stackoverflow.com/questions/79574115/why-wont-polars-when-and-then-run-in-jupyters-notebook
I'm trying to insert/make a new column with these attributes in lines of then("") but i get columnNotFoundError instead for the lines of .then(). But these does not exists yet, what is wrong with the code? df_2023 = df_2023.with_columns( pl.when(pl.col("Tillatt totalvekt opp til og med 3500").eq("X")) .then("Opp til o...
The then construct assumes strings are column names. I guess "Opp til og med 3500" is a literal value in your code and not a column name. Use pl.lit('....') to define a literal value explicitly, that way polars won't consider it as a column name. In your case, .then(pl.lit("Opp til og med 3500")) (same for other then)....
2
3
79,571,227
2025-4-13
https://stackoverflow.com/questions/79571227/difference-in-variable-values-in-jax-non-jit-runtime-and-jit-transformed-runtime
I have a deep learning mode which I am running in the jit transformed manner by: my_function_checked = checkify.checkify(model.apply) model_jitted = jax.jit(my_function_checked) err, pred = model_jitted({"params": params}, batch, training=training, rng=rng) err.throw() The code is compiling fine, but now I want to deb...
In general when comparing the same JAX operation with and without JIT, you should expect equivalence up to typical floating point rounding errors, but you should not expect bitwise equivalence, as the compiler may fuse operations in a way that leads to differing float error accumulation.
1
2
79,572,227
2025-4-14
https://stackoverflow.com/questions/79572227/how-to-annotate-a-pandas-index-of-datetime-date-values-using-pandera-and-mypy
I'm using Pandera to define a schema for a pandas DataFrame where the index represents calendar dates (without time). I want to type-annotate the index as holding datetime.date values. Here's what I tried: # mypy.ini [mypy] plugins = pandera.mypy # schema.py from datetime import date import pandera as pa from pandera....
TL;DR use Index[pa.engines.pandas_engine.Date] Pandera as of now does not support datetime.date series data type, but it has a semantic representation of a date type column for each library (pandas, polars, pyarrow etc). Date type for pandas.DataFrames is pa.engines.pandas_engine.Date , for the others you can see the A...
1
1
79,574,073
2025-4-14
https://stackoverflow.com/questions/79574073/how-to-find-full-delta-using-python-deepdiff
I wrote the following simple test: deeptest.py from deepdiff import DeepDiff, Delta dict1 = {'catalog': {'uuid': 'e95fb23c-57d2-495f-8ab5-2c6b3152bcee', 'metadata': {'title': 'Catalog', 'last-modified': '2025-04-10T16:00:34.033789-05:00', 'version': '1.0', 'oscal-version': '1.1.2'}, 'controls': [{'id': 'ac-1', 'title':...
A DeepDiff returns an object that has already calculated the difference of the 2 items. The format of the object is chosen by the view parameter. By default it uses view=’text’, but there is also tree view, which is more complicated and detailed, and pretty() method. You can read about it in the documentation But the t...
1
2
79,573,720
2025-4-14
https://stackoverflow.com/questions/79573720/is-there-a-way-to-automate-activating-the-virtualenv-in-powershell-in-windows
I know that to activate virtualenv it's just .venv/Scripts/activate.ps1 but I was wondering if there's a way of having powershell do it automatically? Existing ones just talk about activating it, but not how to have Powershell do it automatically virtualenv in PowerShell? How to activate virtualenv using PowerShell? ...
Add something like the following to your PowerShell $PROFILE file: $ExecutionContext.SessionState.InvokeCommand.LocationChangedAction = [Delegate]::Combine( $ExecutionContext.SessionState.InvokeCommand.LocationChangedAction, [EventHandler[System.Management.Automation.LocationChangedEventArgs]] { # Look for a virtual-en...
2
2
79,569,354
2025-4-11
https://stackoverflow.com/questions/79569354/for-multi-index-columns-in-pandas-dataframe-how-can-i-group-index-of-a-particul
I have a pandas dataframe which is basically a pivot table. df.plot(kind = "bar",stacked = True) results in following plot. The labels in x-axis are congested as shown. In Excel I can group the first index value for Scenarios pes, tes and des are clear and distinct as shown: How can I create similar labels in x-axis ...
I have been struggling a bit with finding a way to draw lines outside the plot area but found a creative solution in this previous thread: How to draw a line outside of an axis in matplotlib (in figure coordinates). Thanks to the author for the solution once again! My proposed solution for the problem is the following ...
1
3
79,574,000
2025-4-14
https://stackoverflow.com/questions/79574000/how-to-return-a-variable-from-a-tkinter-button-command-function
I am trying to make a button that increments a variable with Tkinter, but when I 'call' (I know it isn't really calling) a function with command, i can not use return variable, as there is nowhere to return the variable to. Are there alternative ways to do this? Here is my code: import tkinter as tk variable = 0 root =...
You don't need to return from the call-back, Instead, you can update the label directly and you used .push() but actually Tkinter widgets uses .grid() , .pack() or .place() to display them? here is the updated code: import tkinter as tk variable = 0 root = tk.Tk() label = tk.Label(root, text=f"Count: {variable}") label...
2
5
79,573,648
2025-4-14
https://stackoverflow.com/questions/79573648/why-do-model-evaluate-vs-manual-loss-computation-with-model-predict-in-tf-k
I use keras and tensorflow to train a 'simple' Multilayer Perceptron (MLP) for a regression task, where I use the mean-squared error (MSE) as loss-function. I denote my training data as x_train, y_train and my test data as x_test, y_test. I recognized the following: For A and B defined as follows: A = model.evaluate(x...
Keras operates on float32 datatypes, that's what you see when you use model.evaluate(). However, when you compute MSE using your custom function, you're computing them using float64 because your y is float64. You'll see same values if you cast y into float32, something like this: # out-of-sample eval_loss = model_MLP.e...
1
3
79,573,564
2025-4-14
https://stackoverflow.com/questions/79573564/group-by-column-in-polars-dataframe-inside-with-columns
I have the following dataframe: import polars as pl df = pl.DataFrame({ 'ID': [1, 1, 5, 5, 7, 7, 7], 'YEAR': [2025, 2025, 2023, 2024, 2020, 2021, 2021] }) shape: (7, 2) ┌─────┬──────┐ │ ID ┆ YEAR │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞═════╪══════╡ │ 1 ┆ 2025 │ │ 1 ┆ 2025 │ │ 5 ┆ 2023 │ │ 5 ┆ 2024 │ │ 7 ┆ 2020 │ │ 7 ┆ 2021 │ │...
You can use Expr.n_unique: out = df.with_columns( pl.col('YEAR').n_unique().over('ID').alias('UNIQUE_YEARS') ) Output: shape: (7, 3) ┌─────┬──────┬──────────────┐ │ ID ┆ YEAR ┆ UNIQUE_YEARS │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ u32 │ ╞═════╪══════╪══════════════╡ │ 1 ┆ 2025 ┆ 1 │ │ 1 ┆ 2025 ┆ 1 │ │ 5 ┆ 2023 ┆ 2 │ │ 5 ┆ ...
1
3
79,573,037
2025-4-14
https://stackoverflow.com/questions/79573037/how-to-specify-location-where-pandas-to-csv-file-is-stored-in-my-directory
So I do not know how to save the csv which this code creates to a specific folder in my directory. Any help would be appreciated! #Store rows which do not conform to the relationship in a new dataframe subset = df[df['check_total_relationship'] == False]` subset.to_csv('false_relationships.csv', index=False, header=Tru...
Just specify the folder in your directory. subset.to_csv('output_data/false_relationships.csv', index=False, header=True, encoding='utf-8') Or you can specify the absolute path subset.to_csv('/absolute-path/output_data/false_relationships.csv', index=False, header=True, encoding='utf-8') If you need to join paths you...
1
2
79,568,762
2025-4-11
https://stackoverflow.com/questions/79568762/i-keep-getting-this-error-cuda-available-runtimeerror-expected-all-tensors-to
I'm training a transformer model using RLlib's PPO algorithm, but I encounter a device mismatch error: RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu! Despite moving all model components to the GPU with to(self.device), the error persists. CUDA is available...
To resolve the device mismatch error, you should let RLlib and PyTorch manage device placement automatically. Layers are no longer explicity moved to to(self.device) during initialization Used dynamic device detection of the input self.device = input_dict["obs"].device Only inputs in the forward method and values_ou...
2
0
79,572,697
2025-4-14
https://stackoverflow.com/questions/79572697/produce-nice-barplots-with-python-in-pycharm
I'm working on a very basic barplot in Python where I need to plot a series of length occurrences showcasing how many times a specific one appears. I'm storing everything in an array, but when I attempt to plot I either get the y-scale wrong, or on the x-axis all the instances when instead they should be “added” on top...
Here is the code with changes: import matplotlib.pyplot as plt import seaborn as sns import pandas as pd l = [408, 321, 522, 942, 462, 564, 765, 747, 465, 957, 993, 1056, 690, 1554, 1209, 246, 462, 3705, 1554, 507, 681, 1173, 408, 330, 1317, 240, 576, 2301, 1911, 1677, 1014, 756, 918, 864, 528, 882, 1131, 1440, 1167, 1...
1
2
79,572,584
2025-4-14
https://stackoverflow.com/questions/79572584/do-i-need-a-local-install-of-firefox-if-using-firefox-driver-in-selenium
I'm using Librewolf as my personal browser, in my script I'm using Firefox driver, do I need to install Firefox in my machine in order for the driver to work "better"? I have a Python + Selenium app to get URL data from a website, it has 35 pages, the script worked for the first 2 pages, on the third gave me en error (...
You have asked two questions. Am answering the second one, which is about scraping 35 pages. Your selenium script needs to navigate to individual page and scrape the data. In the code below, I have used a while loop to click on the Next Page and scrape the data until the last page is reached. NOTE: Keep in mind that se...
1
1
79,569,153
2025-4-11
https://stackoverflow.com/questions/79569153/module-not-found-azure-data-when-deploying-azure-function-works-locally
I am building a python function. When I run it locally, everything works as expected. When I try to deploy it (using GitHub Actions), the deployment is successful, but the function can not be started, because it throws an error. As you can see in the following picture, the build process works fine and I can run the fun...
I got it to work on a FLEX Consumption plan. I deployed the exact same zip file (using azure cli) to two functions, one one FLEX and one on normal consumption plan. On the Consumption plan it still produces the original error, module not found, while on the flex plan it deploys successfully. must be a bug
1
0
79,572,155
2025-4-13
https://stackoverflow.com/questions/79572155/how-to-automatically-start-the-debugging-session-in-playwright
I want to automatically start the debugging session instead of having it starting as paused. I found out that adding this code makes it work but it feels hackish to me: context.add_init_script("setTimeout(window.__pw_resume, 500)") Without the setTimeout, it won't work. Am I doing anything wrong?
__pw_resume isn’t defined immediately, so a short delay is needed. As of now, there’s no official setting to start unpaused, so this workaround necessary.
1
2
79,568,397
2025-4-11
https://stackoverflow.com/questions/79568397/setting-a-predecessor-constraint-in-timefold-python
I am trying to implement a predecessor constraint similar to the Job Scheduling example given in java. But I struggle with the ordering constraint definition to consider predecessors. I have defined my time slots simply as ordered integers : @dataclass class Timeslot: slot : int And my operations as planning entities ...
Unique pairs are tricky. In this case, you probably want to avoid using them, and instead go for a standard join. Consider three operations: A, B, C. Unique pairs will give you A+B, A+C and B+C. It assumes that whatever is true for A+B, it is also true for B+A and therefore processing both would be redundant. But this ...
1
2
79,572,510
2025-4-14
https://stackoverflow.com/questions/79572510/shareplum-queries-do-not-support-datetime-variables
Shareplum is unable to retrieve entries from a Sharepoint list using DateTime variables (for example, to find entries that were modified after a certain date). Code: from requests_negotiate_sspi import HttpNegotiateAuth from shareplum import Site import datetime site = Site("sharepoint.com", version=Version.v2016, auth...
You can manually craft the CAML query XML, rather than using SharePlum’s dictionary-style shorthand. Here’s how to do it: from requests_negotiate_sspi import HttpNegotiateAuth from shareplum import Site from shareplum import Office365 from shareplum.site import Version import datetime # SharePoint credentials site_url ...
1
1
79,571,959
2025-4-13
https://stackoverflow.com/questions/79571959/efficient-rolling-non-equi-joins
Looking for the current most efficient approach in either R, python or c++ (with Rcpp). Taking an example with financial data, df time bid ask time_msc flags wdayLab wday rowid <POSc> <num> <num> <POSc> <int> <ord> <num> <int> 1: 2025-01-02 04:00:00 21036.48 21043.08 2025-01-02 04:00:00.888 134 Thu 5 1 2: 2025-01-02 04...
Here is a RCCP stack-based approach of the Previous Greater Element problem with O(n) time complexity. It is also described here or here. IDK how fast you want this to be, maybe Java is faster. You could also use OpenMP parallel processing for the for-loop. For 1 million rows it runs with a median of 19.1ms Code d <- d...
1
4
79,572,062
2025-4-13
https://stackoverflow.com/questions/79572062/django-duplication-of-html-on-page-load
I am using DJANGO to create a website, with minimal add ins. At this time, I have a page that duplicates itself on select change. Trying to change its' behavior only makes it worse, like if I change the swap to outer, then it duplicates outside of the element rather than in it. The environment: Windows 11 Pro x64 Visua...
The issue is that on select you're replacing the <form name="form-content" id="form-content" method="post"> with your entire page. What you actually want to do is replace the contents of the form with the contents of the newly generated form, and ignore the remainder of the page. Htmx has an attribute to achieve this, ...
2
0
79,571,645
2025-4-13
https://stackoverflow.com/questions/79571645/form-causes-an-unsupported-media-format-error
I'm working on a todo app for a class project and the /add_todo route returns a 415 error code whenever I try to add a todo. @app.route("/add-todo", methods=["GET", "POST"]) def add_todo(): title = request.get_json().get("title") db.session.add(Todo(title=title)) db.session.commit() return '', 204 <form action="/add-t...
The data you're sending is form-encoded (by the browser). You can retrieve it by using form instead of get_json: @app.route("/add-todo", methods=["POST"]) def add_todo(): title = request.form.get("title") # Here ---------^ db.session.add(Todo(title=title)) db.session.commit() return '', 204
2
3
79,571,144
2025-4-13
https://stackoverflow.com/questions/79571144/passing-two-named-pipes-as-input-to-ffmpeg-using-python
I have two av streams, one video and one audio, i'm trying to pipe both as inputs to ffmpeg os.mkfifo(VIDEO_PIPE_NAME) os.mkfifo(AUDIO_PIPE_NAME) ffmpeg_process = subprocess.Popen([ "ffmpeg", "-i", VIDEO_PIPE_NAME, "-i", AUDIO_PIPE_NAME, "-listen", "1", "-c:v", "copy", "-c:a", "copy", "-f", "mp4", "-movflags", "frag_ke...
I can confirm chrslg's comment under the OP. Placing each pipe's open() call in its own write thread should resolve your issue. I'm nearing to release a new version of ffmpegio to introduce this exact feature, and it works well.
2
1
79,571,506
2025-4-13
https://stackoverflow.com/questions/79571506/tkinter-canvas-rectangle-appears-with-incorrect-size-depending-on-row-column-h
I am writing a Python tkinter rectangle function: def Rectangle(row,col,color="#FFFFFF",outline="gray"): """ Fills a block with a color. Args: row - The row col - The column *color - The rectangle color *outline - The color of the outline """ global blockwidth, blockheight, canvas x, y, i = blockCoords(row,col) canvas....
You're currently treating the center point (x, y) as if it were the top-left and bottom-right corners. Instead of x//2 and x*2, calculate the corners based on width and height like this: canvas.create_rectangle(x - blockwidth // 2, y - blockheight // 2, x + blockwidth // 2, y + blockheight // 2, fill=color, outline=ou...
2
2
79,569,505
2025-4-11
https://stackoverflow.com/questions/79569505/load-deepseek-v3-model-from-local-repo
I want to run the DeepSeek-V3 model inference using the Hugging-Face Transformer library (>= v4.51.0). I read that you can do the following to do that (download the model and run it) from transformers import pipeline messages = [ {"role": "user", "content": "Who are you?"}, ] pipe = pipeline("text-generation", model="d...
Since you said you downloaded the model already from Huggingface, I assume you downloaded all of the related Huggingface files including the JSON files in the repo that describe the model for loading. In this case, the pipeline function can easily take a filesystem path in the model parameter instead of a model name. F...
2
2
79,571,067
2025-4-13
https://stackoverflow.com/questions/79571067/residual-analysis-for-simple-linear-regression-model
I'm trying to conduct the residual analysis for simple linear regression. I need to prove that the residuals follow an approximate Normal Distribution. The csv file I'm using has values for Percentage of marks in Grade 10 and the Salary the student makes. Once I run the below code, my plot looks like this: The plot in...
So, if I understand correctly, you are trying to get the residual part of a linear regression (so the error) on your training dataset, and check if the distribution of that residual part follows a normal law. But ppplot or qqplot need to know which law you want to compare your dataset against. As you probably understan...
5
3
79,571,051
2025-4-12
https://stackoverflow.com/questions/79571051/how-can-i-type-a-method-that-accepts-any-subclass-of-a-base-class
I'm having some trouble typing subclasses of a base class. I have a base class called Table, which defines shared behavior for all table subclasses. Then, I have a Database class that manages collections of these tables. The code below works fine at runtime. However, when I try to type the methods in the Database class...
As stated in the existing answer by @user2357112, you can't make this fully type safe: mapping from a name (string) to some sequence of instances can't be encoded in python's static type system, you can't map a name to a type. However, your filter method is probably the best possible approach. You didn't try to throw i...
1
2
79,571,010
2025-4-12
https://stackoverflow.com/questions/79571010/how-to-create-a-numpy-structured-array-with-different-field-values-using-full-li
I would like to create a NumPy structured array b with the same shape as a and (-1, 1) values, for example: import numpy as np Point = [('x', 'i4'), ('y', 'i4')] a = np.zeros((4, 4), dtype='u1') b = np.full_like(a, fill_value=(-1, 1), dtype=Point) # fails b = np.full_like(a, -1, dtype=Point) # works Using full_like() ...
Convert the fill value into an array with the Point dtype as well import numpy as np Point = [('x', 'i4'), ('y', 'i4')] a = np.zeros((4, 4), dtype='u1') b = np.full_like(a, fill_value=np.array((-1, 1), dtype=Point), dtype=Point) # works Alternatively, if you don't need a, just create the array directly with your desir...
2
5
79,570,284
2025-4-12
https://stackoverflow.com/questions/79570284/how-to-locate-and-overwrite-eip-in-a-buffer-overflow-lab-using-gdb-14-2
I have the following code as part of a buffer overflow CTF challenge: #define _GNU_SOURCE #include <stdio.h> #include <string.h> #include <unistd.h> int my_gets(char *buf) { int i = 0; char c; while (read(0, &c, 1) > 0 && c != '\n') { buf[i++] = c; } buf[i] = '\0'; return i; } int main() { int cookie; char buf[16]; pri...
Your main has non-standard stack layout and epilogue: 0x08049253 <+106>: pop %ecx 0x08049254 <+107>: pop %ebx 0x08049255 <+108>: pop %ebp 0x08049256 <+109>: lea -0x4(%ecx),%esp 0x08049259 <+112>: ret If you simply try to overflow the buffer until you overwrite the return address you overwrite the saved ecx as well wh...
1
1
79,569,269
2025-4-11
https://stackoverflow.com/questions/79569269/seeking-advice-on-efficient-pandas-operations-for-conditional-summing
I am a newbie to Python and pandas and would appreciate any help I can get. I have the below code and would like to know whether there is a more efficient way to write it to improve performance. I tried using cumsum but it does not give me the same output. Context: I need to calculate the total vesting_value_CAD for ea...
Here's one approach: cols = ['employeeID', 'groupName', 'vesting_year', 'agreementDate'] out = ( df.merge( df.groupby(cols)['vesting_value_CAD'].sum() .groupby(cols[:-1]).cumsum() .rename('total_vesting_value_CAD'), on=cols ) .assign( total_vesting_value_CAD=lambda x: x['total_vesting_value_CAD'] - x['vesting_value_CAD...
4
2
79,570,507
2025-4-12
https://stackoverflow.com/questions/79570507/selenium-doesnt-open-website-with-provided-url-url-is-valid
I try to open whois EURID website with no luck. Selenium opens browser (tried with Chrome and FF), but when I try to open particular URL (http://whois.eurid.eu/): nothing opens, I got blank page only. I have driver set by this function: def set_driver() -> WebDriver: service = Service() if cfg["browser"]["browser_name...
Cloudflare Protection or User Agent Detection or JavaScript might cause the issue. Please find below an enhanced solution for your consideration: from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by i...
1
2
79,568,828
2025-4-11
https://stackoverflow.com/questions/79568828/image-matching-fails-with-low-confidence-using-pyautogui-and-opencv
I'm working on automating GUI testing using OpenCV and PyAutoGui. I tried both pyautogui.locateOnScreen() and cv2.matchTemplate() to detect UI elements by matching a reference image inside a screen region. The reference image is visibly present inside the screenshot (confirmed manually), but both approaches either fail...
Here is your template overlaid side by side with the instance I think you want to locate. See how the image content is not the same size? That is the problem. That can't match. It has to be the same size/scale. Pick the template correctly. Then it will work.
2
1
79,570,437
2025-4-12
https://stackoverflow.com/questions/79570437/what-is-the-most-efficient-way-to-get-length-of-path-from-adjacency-matrix-using
The problem I am solving is optimizing a genetic algorithm for the Traveling Salesman Problem. Calculating the path takes the most time. Here is the current code I am working on: from itertools import pairwise import numpy as np from random import shuffle def get_path_len(adj_mat: np.ndarray, path: np.ndarray) -> float...
Here is an example of how to use Numba to do that efficiently: import numba as nb # Pre-compile the code for a int32/int64 adj_mat 2D array # and a int64 path 1D array @nb.njit(['(int32[:,:], int64[:])', '(int64[:,:], int64[:])']) def get_path_len(adj_mat, path): s = 0 for i in range(path.size-1): # Assume path contain...
3
3
79,570,508
2025-4-12
https://stackoverflow.com/questions/79570508/create-boolean-columns-from-string-column
I have column column1 of type string with values like "some1,some2,some3". I need to create boolean columns based on column1 like: some1, some2, some3. For example, I have the dataframe with one column column1: column1 | -------------------+ "some1,some2,some3"| "some2,some3" | "some1" | "some1,some3" | I need to get ...
You can use str.get_dummies + astype: df['column1'].str.get_dummies(sep=',').astype(bool) Output: some1 some2 some3 0 True True True 1 False True True 2 True False False 3 True False True Data used import pandas as pd data = {'column1': ["some1,some2,some3", "some2,some3", "some1", "some1,some3"]} df = pd.DataFrame(...
1
4
79,570,287
2025-4-12
https://stackoverflow.com/questions/79570287/python-3-concurrent-futures-get-thread-number-without-adding-a-function
Currently this code prints, MainThread done at sec 1 MainThread done at sec 1 MainThread done at sec 2 MainThread done at sec 1 MainThread done at sec 0 MainThread done at sec 3 MainThread done at sec 2 MainThread done at sec 5 MainThread done at sec 4 I need it to print MainThread 1 done at sec 1 MainThread 3 done at...
future doesn't know which thread ran the function, you need to store that yourself. you can wrap the functor in a wrapper that will return whatever you want from the executing thread. import concurrent.futures import threading import pdb import time import random from functools import wraps def wrap_function(func): @wr...
2
1
79,570,163
2025-4-12
https://stackoverflow.com/questions/79570163/why-do-these-nearly-identical-functions-perform-very-differently
I have written four functions that modify a square 2D array in place, it reflects half of the square array delimited by two sides that meet and the corresponding 45 degree diagonal, to the other half separated by the same diagonal. I have written a function for each of the four possible cases, to reflect product(('uppe...
this is a mixture of false sharing and memory bandwidth bottleneck, removing the parallelization by converting nb.prange -> range you get equal times for all 4 functions. the first one is writing a single row at a time, which is contiguous in memory, the second one is writing a column at a time. this column is not cont...
2
4
79,569,792
2025-4-11
https://stackoverflow.com/questions/79569792/pickle-works-but-fails-pytest
I've created a module persist containing a function obj_pickle which I'm using to pickle various objects in my project. It work fine but it's failing pytest, returning; > pickle.dump(obj, file_handle, protocol=protocol) E AttributeError: Can't pickle local object 'test_object.<locals>.TestObject' Running: python 3.12...
This doesn't really have anything to do with pytest. When you load an object from a pickle, the pickle machinery needs to know what the class of that object should be. But if you define a class inside a function, then every execution of that function generates a whole new class. pickle has no way to tell which version ...
1
2
79,568,766
2025-4-11
https://stackoverflow.com/questions/79568766/pyqt6-on-windows-qtquickcontrols2windowsstyleimplplugin-dll-the-specified-mod
i am trying to test some code using PyQt6. When I try to display en MenuBar in my main.qml, i have this error : QQmlApplicationEngine failed to load component file:///C:/Users/[blablabla]/GUIt/main.qml:11:9: Type Menu unavailable qrc:/qt-project.org/imports/QtQuick/Controls/Windows/Menu.qml:32:15: Type MenuItem unavail...
The last version of QtQuick.Controls which supports a natively rendered Windows MenuBar was version 1.4. Unfortunately, for your current code, QtQuick.Controls available with PyQt6 is version 2. In order to use QtQuick.Controls 1.4, you have to use PyQt5. Use PyQt5 instead of PyQt6 in main.py, backend.py, and CommitLis...
2
1
79,569,422
2025-4-11
https://stackoverflow.com/questions/79569422/how-to-check-range-of-versions
I have a build_requirments_file.py file, which builds a requirments.txt file for a given python program, but the thing is... It creates something like: huggingface_hub==currently installed version\ pynput==currently installed version\ module==current version But, how will I know in which "range" of versions will my co...
Unfortunately there is no nice and clean way to actually do this. Why is that the case? Very time a package gets an updated version, all that really means is that its source code is in some way different. The more utility of the package that you use the more potential sensitivity you may have to different versions of t...
2
3
79,568,360
2025-4-11
https://stackoverflow.com/questions/79568360/determine-position-of-an-inserted-string-within-another
Following this post I managed to put together a small function to place within a bigger text body (FASTA) shorter strings determined from another file based on some conditions (e.g. 100 events from a subset of only those 400-to-500 characters in length, and selected randomly). Now, I'm pretty fine with the result; howe...
Your current code has some issues: It inserts the 100 randomly selected strings all adjacent to eachother in the genome The 100 strings are concatenated with commas, which end up in the final gnome string So that would need to be fixed first before getting to the question of the positions where the insertions happe...
1
1
79,568,961
2025-4-11
https://stackoverflow.com/questions/79568961/why-does-this-fast-function-with-numba-jit-slow-down-if-i-jit-compile-another-fu
So I have this function: import numpy as np import numba as nb @nb.njit(cache=True, parallel=True, nogil=True) def triangle_half_UR_LL(size: int, swap: bool = False) -> tuple[np.ndarray, np.ndarray]: total = (size + 1) * size // 2 x_coords = np.full(total, 0, dtype=np.uint16) y_coords = np.full(total, 0, dtype=np.uint1...
TL;DR: This mainly comes from the system allocator which does not behave the same way regarding the current state of the memory (hard to predict). When the function is fast, there are no page faults, while when the function is slow, it seems there are a lot of page faults slowing down the master thread. Analysis When ...
3
8
79,569,325
2025-4-11
https://stackoverflow.com/questions/79569325/cannot-pickle-local-function-when-sending-callable-filter-objects-via-multiproce
Problem Description I'm developing a FilterBroker class that manages callable filters for subscriber processes. The broker receives functions wrapped in a Filter object via a message queue. However, I'm encountering a pickling error when trying to send a locally defined function: AttributeError: Can't get local object ...
you should use cloudpickle, you'll have to do the cloudpickle.dumps and cloudpickle.loads yourself. from threading import Thread from multiprocessing import Queue, Manager, Process from dataclasses import dataclass from typing import Optional import logging import inspect import cloudpickle @dataclass class Service: id...
2
1
79,569,500
2025-4-11
https://stackoverflow.com/questions/79569500/how-can-i-sort-order-of-index-based-on-my-preference-in-multi-index-pandas-dataf
I have a pandas dataframe df. It has multi-index with Gx.Region and Scenario_Model. The Scenario_Model index is ordered in alphabetical order des, pes, tes. When I plot it, it comes in the same order. However, I want to reorder it as pes, tes and des, and plot it accordingly. Is it possible to achieve it in Python pand...
A quick an easy approach, if you know the categories, would be to reindex: (df_sample.reindex(['pes', 'tes', 'des'], level=1) .plot(kind='bar', stacked=True) ) A more canonical (but more complex) approach would be to make the second level an ordered Categorical: order = pd.CategoricalDtype(['pes', 'tes', 'des'], order...
3
2
79,569,039
2025-4-11
https://stackoverflow.com/questions/79569039/python-is-installed-in-two-different-locations
I am trying to get the latest version of Python to run on my Linux Ubuntu 24.04 system, but the older version is still showing as current. There are two locations that Python is configured, '/usr/bin' and '/usr/local/bin'. How should I handle this to get the correct configuration on my system? I tried ~-> $ python --ve...
Simply put one Python path in front of the other, for example if you want /usr/local/bin to be found before /usr/bin, then do this: export PATH=/usr/local/bin:${PATH} in your shell. If you are satisfied with the result, put the above line in your ~/.bashrc.
1
1
79,568,585
2025-4-11
https://stackoverflow.com/questions/79568585/running-poetry-in-using-jenkins-dockerfile
I've got my dockerfile FROM git.corp.com:4567/some/python:3.11-slim RUN apt update; \ apt install pipx -y; \ pipx install poetry; \ pipx ensurepath; \ chmod a +rx /root/.local/bin/poetry; \ ln -s /root/.local/bin/poetry /usr/bin/poetry; \ and my jenkins stage stage('Test') { agent { dockerfile{ filename 'Dockerfile.bu...
Try to install Poetry to the path which will be available to all users instead of installing it to /root/.local ENV PIPX_HOME=/opt/pipx \ PIPX_BIN_DIR=/usr/local/bin RUN apt update && \ apt install pipx -y && \ pipx install poetry
1
3
79,568,097
2025-4-11
https://stackoverflow.com/questions/79568097/python-static-class-variable-in-nested-class
I have a nested class that uses static vars to have class wide parameters and accumulators. If I do it as a standalone class it works. If I do a nested class and inherit the standalone class, it works. But I can't get a nested class to have static class variables, the interpreter gets confused. What am I doing wrong? C...
You can use the classmethod decorator, which is more appropriate for this situation anyways: class C: class Nested: counter = 0 @classmethod def increment(cls) -> int: cls.counter += 1 return cls.counter print(C().Nested.increment()) # prints 1 If you are wondering why increment can't find Cl_static_parameter_nested i...
1
2
79,567,933
2025-4-11
https://stackoverflow.com/questions/79567933/using-a-class-property-as-an-iterable-produces-a-reassign-warning
I need to use an iterable and a loop variable as a class property. But the flake8 checker produces B2020 warning: easy.py:11:13: B020 Found for loop that reassigns the iterable it is iterating with each iterable value. If I use a variable for iterable there is OK. What is wrong? The warning example: #!/usr/bin/env pyt...
It's a known issue: https://github.com/PyCQA/flake8-bugbear/issues/248 Understandably flake8-bugbear developers are a bit unwilling to fix this as it's not very common to use an instance attribute as the loop variable. It's also not really needed. You can simply use a normal loop variable: class My_Template: def __init...
1
1
79,564,589
2025-4-9
https://stackoverflow.com/questions/79564589/how-to-find-all-grid-points-that-correspond-to-non-reduced-fractions-in-a-square
Given a positive integer N, we can label all grid points in the square N x N, starting at 1, the total number of grid points is N x N, and the grid points are list(itertools.product(range(1, N + 1), repeat=2)). Now, I want to find all tuples (x, y) that satisfies the condition x/y is a non-reduced fraction, the followi...
The algorithm of Weeble runs in O(n² m²) where m is the size of integers in bits (using a naive multiplication). Since we can assume the multiplication of numbers to be done in constant time (due to bounded native integers used by Numpy), this means O(n²) but with a significant hidden constant which should not be negle...
10
9
79,567,429
2025-4-10
https://stackoverflow.com/questions/79567429/duplicate-and-rename-columns-on-pandas-dataframe
I guess this must be rather simple, but I'm struggling to find the easy way of doing it. I have a pandas DataFrame with the columns A to D and need to copy some of the columns to new ones. The trick is that it not just involves renaming, I also need to duplicate the values to new columns as well. Here is an example of ...
IIUC, you can do this with this command, this is one of the reason I like to use the set_axis method in dataframes. table_name = 'table_1' df[list(mapping_dict[table_name].values())+['values']].set_axis(list(mapping_dict[table_name].keys())+['values'], axis=1) Output: id dt_start dt_end values 0 1 2025-10-01 2025-10-...
2
3
79,567,480
2025-4-10
https://stackoverflow.com/questions/79567480/how-to-select-from-xarray-dataset-without-hardcoding-the-name-of-the-dimension
When selecting data from an xarray.Dataset type, the examples they provide all include hardcoding the name of the dimension like so: ds = ds.sel(state_name='California') TLDR; How can you select from a dataset without hardcoding the dimension name? How would I achieve something like this since the below doesn't work? ...
This is a nice place to use Python dictionary unpacking. To get this: res = ds.sel(state_name='California') You can: dim_sel = {'state_name': 'California'} res = ds.sel(**dim_sel) And of course directly: res = ds(**{'state_name': 'California'}} Unpacking the dictionary with ** spreads the keys as argument names and ...
1
2
79,566,634
2025-4-10
https://stackoverflow.com/questions/79566634/how-to-make-same-sized-plots-with-sns-matplotlib
plt.figure(figure=(6,8)) sns.barplot(data=csat_korean,x='grade',y='percentage').set_title('Korean'); plt.show() sns.barplot(data=csat_math,x='grade',y='percentage').set_title('Math'); plt.show() sns.barplot(data=csat_english,x='grade',y='percentage').set_title('English'); plt.show() Hello, the above code is me trying ...
With seaborn's catplot(), you can generate a grid of bar plots, starting from a combined dataframe. The size of the subplots is set via the height= and aspect= parameters (width = height * aspect). By default, the x and y axis are shared between the subplots, so they look very similar. from matplotlib import pyplot as ...
1
1
79,566,761
2025-4-10
https://stackoverflow.com/questions/79566761/sort-a-polars-dataframe-based-on-an-external-list
Morning, I'm not sure if this can be achieved.. Let's say i have a polars dataframe with cols a, b (whatever). df = pl.DataFrame({"a":[1,2,3,4,5],"b":['x','y','z','p','f']}) And a list.. l = [1,3,5,2,4]; is it possible to sort the dataframe (using column "a") using the list l as the sorting order? Thanks in advance!
You can use an Enum to sort with a custom order, however as Enum only works with strings, you first need to temporarily convert to string: df.sort(by=pl.col('a').cast(pl.String).cast(pl.Enum(list(map(str, l))))) Output: ┌─────┬─────┐ │ a ┆ b │ │ --- ┆ --- │ │ i64 ┆ str │ ╞═════╪═════╡ │ 1 ┆ x │ │ 3 ┆ z │ │ 5 ┆ f │ │ 2...
2
2