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,409,587
2025-2-3
https://stackoverflow.com/questions/79409587/performance-impact-of-inheriting-from-many-classes
I am investigating the performance impact of a very broad inheritance setup. Start with 260 distinct attribute names, from a0 through z9. Create 260 classes with 1 uniquely-named attribute each. Create one class that inherits from those 260 classes. Create 130 classes with 2 uniquely-named attributes each. Create one ...
The slowdown will be weird and hard to fully predict, depending on subtle details of memory allocation and attribute access order. Worst-case, not only will you experience a linear slowdown, you'll slow down completely unrelated attribute accesses in unrelated code. CPython has a 4096-entry type attribute cache, and i...
2
3
79,407,233
2025-2-2
https://stackoverflow.com/questions/79407233/how-do-i-store-decimal-values-coming-from-sql-in-csv-file-with-python
I have a simple chatbot that generates SQL queries and uses them on a database. I want to store the output in a .csv file and then download that file. This is usually possible when I take my output from SQL (a list of dicts), create a pd.Dataframe after evaluating that output, and finally download it as a csv file usin...
pandas .read_sql_query() method can be used to directly create a DataFrame from an SQL query. Then the DataFrame can be written to a CSV file using the .to_csv() method. import pandas as pd import sqlalchemy as sa engine = sa.create_engine("postgresql://scott:tiger@192.168.0.199/test") sql = """\ SELECT 'widget' AS ite...
2
0
79,408,681
2025-2-3
https://stackoverflow.com/questions/79408681/perform-a-rolling-operation-on-indices-without-using-with-row-index
I have a DataFrame like this: import polars as pl df = pl.DataFrame({"x": [1.2, 1.3, 3.4, 3.5]}) df # shape: (3, 1) # ┌─────┐ # │ a │ # │ --- │ # │ f64 │ # ╞═════╡ # │ 1.2 │ # │ 1.3 │ # │ 3.4 │ # │ 3.5 │ # └─────┘ I would like to make a rolling aggregation using .rolling() so that each row uses a window [-2:1]: shape:...
Pure expressions approach (apparently slow) You can use concat_list with shift ( df .with_columns( y=pl.concat_list( pl.col('x').shift(x) for x in range(2,-2,-1) ) .list.drop_nulls() ) ) shape: (4, 2) ┌─────┬───────────────────┐ │ x ┆ y │ │ --- ┆ --- │ │ f64 ┆ list[f64] │ ╞═════╪═══════════════════╡ │ 1.2 ┆ [1.2, 1.3] ...
5
2
79,407,317
2025-2-2
https://stackoverflow.com/questions/79407317/how-to-create-possible-sets-of-n-numbers-from-m-sized-prime-number-list
Input: a list of m prime numbers (with possible repetition), and integers n and t. Output: all sets of n numbers, where each set is formed by partitioning the input into n parts, and taking the product of the primes in each part. We reject any set containing a number greater than t or any duplicate numbers. Thanks, @Da...
This may not be the ultimate most efficient solution, but there are at least two aspects where gains can be made: permutations of the same primes are a wasted effort. It will help to count how many you have of each prime (which will be its maximum exponent) and pre-calculate the partitions you can have of the availabl...
2
2
79,406,476
2025-2-2
https://stackoverflow.com/questions/79406476/why-doesnt-pagination-work-in-this-case-using-selenium
Most websites display data across multiple pages. This is done to improve user experience and reduce loading times. But when I wanted to automate the data extraction process using Selenium, I noticed that my script only retrieves information from page one and then stops. What am I doing wrong? from selenium.webdriver i...
Different websites often require bespoke strategies in order to scrape them with any level of success. This site is protected by Cloudflare. When Cloudflare detects too many automated invocations it will intervene and present a page that requires you to prove that you're not a robot. In this case, the number of pages t...
1
2
79,408,524
2025-2-3
https://stackoverflow.com/questions/79408524/writing-back-to-a-panda-groupby-group
Good morning all I am trying to process a lot of data, and I need to group data, look at the group, then set a value based on the other entries in the group, but I want to set the value in a column in the full dataset. What I can't figure out is how I can use the group to write back to the main dataframe. So as an exam...
A loop-less approach would be to compute a groupby.first after dropna, then to map the output: df['parents_in_group'] = df['class'].map( df.dropna(subset='child').groupby('class')['name'].first() ) # variant df['parents_in_group'] = df['class'].map( df['name'].where(df['child'].notna()).groupby(df['class']).first() ) ...
1
1
79,405,014
2025-2-1
https://stackoverflow.com/questions/79405014/how-put-an-algorithm-drafted-on-paper-into-a-working-c-code
I am trying to improve attack on PKZIP by minimizing workload and requirements, So PKZIP uses this: key0[i] = key0[i-1]>>8 ^ crctab[key0[i-1]&0xFF ^ plaintext[i]]; key1[i] = (key1[i-1] + (key0[i]&0xFF))* Const + 1; key2[i] = key2[i-1]>>8 ^ crctab[key2[i-1]&0xFF ^ (key1[i]>>24)]; to update its keystream or internal sta...
The problem isn't the code but the calculation itself as written on paper the algorithm states that you can find a unique y value from x value but that's not entirely correct because given x and the equation ((256*e) = ((x*x)-x) mod 65536) xor ((y*y)-y) mod 65536 ) and e they are 64 possible y values. That is when the ...
4
0
79,407,952
2025-2-3
https://stackoverflow.com/questions/79407952/find-the-index-of-the-current-df-value-in-another-series-and-add-to-a-column
I have a dataframe and a series, as follows: import pandas as pd from itertools import permutations df = pd.DataFrame({'a': [['a', 'b', 'c'], ['a', 'c', 'b'], ['c', 'a', 'b']]}) prob = list(permutations(['a', 'b', 'c'])) prob = [list(ele) for ele in prob] ps = pd.Series(prob) >>> df a 0 [a, b, c] 1 [a, c, b] 2 [c, a, b...
Use DataFrame.merge with DataFrame constructor: #if possible duplicates in ps remove them ps = ps.drop_duplicates() df = df.merge(pd.DataFrame({'idx': ps.index, 'a':ps.values}), on='a') print (df) a idx 0 [a, b, c] 0 1 [a, c, b] 1 2 [c, a, b] 4 Solution for oldier pandas versions - converting lists to tuples before me...
1
1
79,407,420
2025-2-2
https://stackoverflow.com/questions/79407420/why-doesnt-the-condition-of-my-while-loop-apply-to-my-print-statement
Only started learning Python a few days ago. I followed freecodecamp's while loop word guessing game tutorial and wanted to add the statement, "Wrong answer!" after every wrong guess. This was what I initially wrote: secret_word = "giraffe" guess = "" guess_count = 0 guess_limit = 3 out_of_guesses = False while guess !...
The while loop (it's not a function!) head is (here) independent from what you do in the loop's body. When the loop condition is true, the whole code in the body runs. If that code prints something unconditionally (i.e., without using an if to check whether it should print), then you get that output. After the body is ...
5
4
79,407,124
2025-2-2
https://stackoverflow.com/questions/79407124/python-3-13-1-breaks-indentation-when-pasting-code-in-terminal
Python 3.13.1 results in unexpected indentation errors when I copy and paste Python code into its windows terminal (as shown in the pic below). This did not happen in Python 3.12.x or earlier. In windows terminal open python 3.13.1, and 3.12.8 separately, and paste the below code for example def fun1(): if 5 > 3: retur...
Press F3 before pasting (new in Python 3.13). Press F3 again when done pasting. See What's New in Python 3.13: New Features - A better interactive interpreter.
2
3
79,405,614
2025-2-1
https://stackoverflow.com/questions/79405614/slicing-netcdf4-dataset-based-on-specific-time-interval-using-xarray
I have a netCDF4 dataset for the following datatime which is stored in _date_times variable:- <xarray.DataArray 'Time' (Time: 21)> Size: 168B array(['2025-01-30T00:00:00.000000000', '2025-01-30T06:00:00.000000000', '2025-01-30T12:00:00.000000000', '2025-01-30T18:00:00.000000000', '2025-01-31T00:00:00.000000000', '2025-...
You don't have to use a slice() to select the times, you can also specify a list or array of times. Here, I used Pandas date_range() for simplicity: import xarray as xr import pandas as pd import numpy as np ds = xr.open_dataset('202001.nc') times = pd.date_range(ds.time[0].values, ds.time[-1].values, freq='12h') dst =...
1
1
79,405,867
2025-2-1
https://stackoverflow.com/questions/79405867/change-value-in-ini-to-empty-using-python-configparser
I want to read the config file if the value is empty Example: To convert a video file to audio file # config.ini [settings] videofile = video.avi codesplit = -vn outputfile = audio.mp3 Output ['ffmpeg.exe', '-i', 'video.avi', '-vn', 'audio3.mp3'] If you make the value "codesplit" empty, the code will not work. exampl...
You can try using an if-else statement to check if there is a codesplit option passed from the config file or not. import subprocess import configparser config = configparser.ConfigParser(allow_no_value=True) config.read(r"config.ini") videofile = config.get("settings", "videofile") outputfile = config.get("settings", ...
1
1
79,405,672
2025-2-1
https://stackoverflow.com/questions/79405672/iterqueue-object-has-no-attribute-not-full
I have a class called "IterQueue which is an iter queue: IterQueue.py from multiprocessing import Process, Queue, Pool import queue class IterQueue(queue.Queue): def __init__(self): self.current = 0 self.end = 10000 def __iter__(self): self.current = 0 self.end = 10000 while True: yield self.get() def __next__(self): i...
You inherited from Queue and overrode __init__, but never called its __init__, so that was never run. That means that not_full was never assigned, thus the error. Unless you want to override its maxsize default argument of 0, you just need to change your __init__ to: def __init__(self): super().__init__() self.current ...
1
3
79,405,385
2025-2-1
https://stackoverflow.com/questions/79405385/why-is-my-code-rendering-curves-rotated-90-degrees
I'm trying to make a heating cable layout for floor heating and i got stuck with this problem. This i what i got from my code So i made a small program asking for width,lenght of the room and calculating the are in m2. And i need a graphical representation of how cable should be on the floor. This is my code for arch:...
I suspect you want to lay your cable like this. The end arcs are essentially the same (so don't keep re-calculating them). Just shift them up at each crossing and alternate left and right sides. import numpy as np import matplotlib.pyplot as plt width = 4 spacing = 0.25 N = 17 length = 4 total_length = 0 theta = np.li...
2
1
79,405,520
2025-2-1
https://stackoverflow.com/questions/79405520/md-simulation-using-velocity-verlet-in-python
I'm trying to implement a simple MD simulation in Python (I'm new to this),I'm using LJ potential and force equations along with Verlet method: def LJ_VF(r): #r = distance in Å #Returns V in (eV) and F in (eV/Å) V = 4 * epsilon * ( (sigma/r)**(12) - (sigma/r)**6 ) F = 24 * epsilon * ( 2 * ((sigma**12)/(r**(13))) - ( (s...
Your initial force F is negative. You assign that to P1, making it move down and -F (which is positive) to P2, so making P2 move up. That is contrary to the physics. You have just assigned F and -F to the wrong particles (F should go to the one with positive r). Switch them round, both where you update x_new, v_new and...
1
2
79,403,285
2025-1-31
https://stackoverflow.com/questions/79403285/how-to-force-sympy-to-simplify-expressions-that-contain-logarithms-inside-an-exp
Consider the following MWE: import sympy as sp a,b = sp.symbols("a b", positive=True, real=True) t = sp.symbols("t", real=True) s = sp.symbols("s") T = 1/(1+s*a)/(1+s*b) y = sp.inverse_laplace_transform(T,s,t) tmax = sp.solve(sp.diff(y,t),t)[0] ymax = y.subs(t,tmax) display(ymax.simplify()) This code gives the followi...
Notice the denominators in the arguments of the exponentials (which are different than you posted, but that is what I get): >>> from sympy import * ...your code... >>> e=ymax.atoms(exp);e [exp(-log((a/b)**(a*b))/(a**2 - a*b)), exp(-log((a/b)**(a*b))/(a*b - b**2))] If you assure SymPy that those are non-zero (and real)...
3
2
79,405,200
2025-2-1
https://stackoverflow.com/questions/79405200/using-named-columns-and-relative-row-numbers-with-pandas-3
I switched from NumPy arrays to Pandas DataFrames (dfs) many years ago because the latter has column names, which makes programming easier; is robust in order changes when reading data from a .json or .csv file. From time to time, I need the last row ([-1]) of some column col of some df1, and combine it with the last...
You can try to use the following snippet. df1.loc[df1.index[-1], 'col1'] = df2.loc[df2.index[-1], 'col1'] On my machine with pandas version 2.2.3, it gives no warnings.
1
1
79,404,040
2025-1-31
https://stackoverflow.com/questions/79404040/is-there-a-way-to-overlay-scatterplot-over-grouped-boxplots-so-they-arent-offse
I'm trying to get the scatter plots to lie ontop of their respective boxplots to act as outlier points. Since plotly's graph_object.box doesn't have a method of inputting precalculated outliers, I've been trying to do it this way. I don't want plotly to calculate the outliers for the purposes of the project. Is there a...
The desired output can be obtained by exiting box mode and making each label unique. This is because the x-axis of the box-and-whisker and scatter plots will be the same. import plotly.graph_objects as go def create_multiple_boxplots(summary_stats_list, labels, types, title="Multiple Boxplots"): fig = go.Figure() color...
1
1
79,404,376
2025-2-1
https://stackoverflow.com/questions/79404376/os-symlink-fails-when-directory-exists-and-when-directory-doesnt-exist
I have source and link paths. I'm trying to create a symlink, but must be misunderstanding how its used. Let's say source = '/var/source/things/' link = '/var/link/' When I use os.symlink(source, link) Initially I received an error FileNotFoundError: [Errno 129] EDC5129I No such file or directory.: '/var/source/things...
Can you remove "/" at the end under link and try once source = '/var/source/things/' link = '/var/link' apart from that, I don't see any issues in your code.
2
2
79,404,077
2025-1-31
https://stackoverflow.com/questions/79404077/how-to-fix-alignment-of-projection-from-x-y-z-coordinates-onto-xy-plane-in-mat
I was trying to make a 3D visualization of the joint probability mass function with the following code: import math import numpy as np import matplotlib.pyplot as plt def f(x, y): if(1 <= x + y and x + y <= 4): return (math.comb(3, x) * math.comb(2, y) * math.comb(3, 4 - x - y)) / math.comb(8, 4) else: return 0.0 x_dom...
Actually, they DO align with the integer grid, as you will see by rotating your plot a bit. It's just that the z axis doesn't naturally start from 0, which is where the end of your whatever-they-are are. Add the line ax.set_zlim( 0.0, 0.25 ) just before plt.show() and you will be good to go.
1
2
79,403,612
2025-1-31
https://stackoverflow.com/questions/79403612/calculate-the-count-of-distinct-values-appearing-in-multiple-tables
I have three pyspark dataframes in Databricks: raw_old, raw_new, and master_df. These are placeholders to work out the logic on a smaller scale (actual tables contain billions of rows of data). There is a column in all three called label. I want to calculate the number of labels that appear in: raw_old and raw_new (th...
You should use an inner join to get the elements in common between the datasets joined_data = raw_old.join( raw_new, on=raw_old["label"] == raw_new["label"], how="inner" ) and then you can collect the result back to Python, keeping all the heavy work in Spark print(joined_data.count()) When joining 3 dataframes, you ...
4
1
79,401,185
2025-1-30
https://stackoverflow.com/questions/79401185/overload-a-method-based-on-init-variables
How can I overload the get_data method below to return the correct type based on the init value of data_type instead of returning a union of both types? from typing import Literal DATA_TYPE = Literal["wood", "concrete"] class WoodData: ... class ConcreteData: ... class Foo: def __init__(self, data_type: DATA_TYPE) -> N...
Ok, for this solution, you annotate self with the generic type you want, both mypy and pyright give similar outputs for reveal_type (i.e., it works with the base class but not the subclass): from typing import Literal, overload, TypeVar class WoodData: ... class ConcreteData: ... class Foo[T:(Literal['wood'], Literal['...
4
3
79,400,487
2025-1-30
https://stackoverflow.com/questions/79400487/pyqt6-issue-in-fetching-geometry-of-the-window
I am currently learning the PyQt6 library and I want to get the geometry of the window. The issue is that the x and y positions are always 0 even after I changed the position of the window on the screen. OS: Ubuntu Python version: 3.9 import sys from PyQt6.QtWidgets import QApplication, QVBoxLayout, QPushButton, QWid...
why it doesn't work On Ubuntu, Wayland is used by default for regular user sessions. Wayland has certain limitations, including restricting access to low-level details like window position, which caused this issue. However, sudo runs the program with root privileges, which forces the system to use X11 (instead of Wayla...
3
2
79,402,794
2025-1-31
https://stackoverflow.com/questions/79402794/python-vectorized-minimization-of-a-multivariate-loss-function-without-jacobian
I have a loss function that needs to be minimized def loss(x: np.ndarray[float]) -> float My problem has nDim=10 dimensions. Loss function works for 1D arrays of shape (nDim,), and with 2D arrays of shape (nSample, nDim) for an arbitrary number of samples. Because of the nature of the implementation of the loss functi...
differential_evolution is a global optimizer that does not require gradients. It has a vectorized keyword to enable many function evaluations in a single call. Alternatively, you could write a function that takes the Jacobian with scipy.differentiate.jacobian, which calls the function at all required points at once, an...
1
2
79,402,532
2025-1-31
https://stackoverflow.com/questions/79402532/cropping-the-image-by-removing-the-white-spaces
I am trying to identify the empty spaces in the image and if there is no image, then I would like to crop it by eliminating the spaces. Just like in the images below. --> I would be grateful for your help. Thanks in advance! I was using the following code, but was not really working. import cv2 import numpy as np de...
Approach: threshold -> obtain mask use boundingRect() on the mask crop im = cv.imread("Cb768fyr.jpg") gray = cv.cvtColor(im, cv.COLOR_BGR2GRAY) th = 240 # 255 won't do, the image's background isn't perfectly white (th, mask) = cv.threshold(gray, th, 255, cv.THRESH_BINARY_INV) (x, y, w, h) = cv.boundingRect(mask) pad ...
2
3
79,402,275
2025-1-31
https://stackoverflow.com/questions/79402275/how-to-fix-inconsistent-method-resolution-order-when-deriving-from-ctypes-struct
Given the following Python code: import ctypes from collections.abc import Mapping class StructureMeta(type(ctypes.Structure), type(Mapping)): pass class Structure(ctypes.Structure, Mapping, metaclass=StructureMeta): pass struct = Structure() assert isinstance(struct, ctypes.Structure) assert isinstance(struct, Mapping...
As you can attest, there is no "error" in this code. Working with metaclasses is hard - and having to create a compatible metaclass in cases like this shows some of the side effects. The problem is most of what metaclasses do are things that take effect as the code is executed (i.e. in runtime) - while analysis tools l...
1
1
79,402,605
2025-1-31
https://stackoverflow.com/questions/79402605/can-storing-an-api-key-in-env-file-for-a-containerized-python-app-be-considered
The title is the question, can storing an API-key in .env file for a containerized Python app be considered safe? While writing, a Nginx/Docker set-up question came to mind as well, asked at the bottom. A little background, I've made a Python app that I want to deploy with Streamlit on a Linux-based server. All is hobb...
At the end of the day, your program is going to need to have this value, in a variable, in plain text. So the question is how many people do you want to be able to see it before then? There is a lot of "it depends" here. If your application is handling real-world money or particularly sensitive data, you might want (or...
2
1
79,402,318
2025-1-31
https://stackoverflow.com/questions/79402318/in-an-array-of-counters-that-reset-find-the-start-end-index-for-counter
Given an array that looks like this: values [0, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 6, 0, 0, 1, 2, 3] index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 If I search for index 3, I want to get the indexes of the start and end indexes for that counter, before it is reset again, which is 2 - 6. And for index 10, I want...
You can get the start/end coordinates of the non-null stretches with something like: idx = np.nonzero(values == 0)[0] start = idx+1 end = np.r_[idx[1:]-1, len(values)-1] m = start<end indices = np.c_[start, end][m] indices: array([[ 2, 6], [ 8, 13], [16, 18]]) Then get the position with searchsorted (assuming you onl...
4
3
79,402,325
2025-1-31
https://stackoverflow.com/questions/79402325/implement-a-knights-tour-algorithm-using-backtracking-in-python
I try to solve Knight tour problem with python and backtracking, but the code doesn't respond likely I want... This is my code in python: import random board = [ [0,0,0,0,0,0], [0,0,0,0,0,0], [0,0,0,0,0,0], [0,0,0,0,0,0], [0,0,0,0,0,0], [0,0,0,0,0,0] ] intialCell = [random.randint(0,5),random.randint(0,5)] path = [] de...
The problem is that your code can return False without undoing the latest update you made to path and board. To solve this, just remove the following lines: if not varbesideCells: return False If now that condition is true (i.e. varbesideCells is an empty list), then execution will continue as follows: it will not ma...
1
1
79,399,929
2025-1-30
https://stackoverflow.com/questions/79399929/how-to-sample-pandas-dataframe-using-a-normal-distribution-by-using-random-state
I am trying to write Pandas code that would allow me to sample DataFrame using a normal distribution. The most convinient way is to use random_state parameter of the sample method to draw random samples, but somehow employ numpy.random.Generator.normal to draw random samples using a normal (Gaussian) distribution. impo...
Passing a Generator to sample just changes the way the generator is initialized, it won't change the distribution that is used. Random sampling is uniform (choice is used internally [source]) and you can't change that directly with the random_state parameter. Also note that normal sampling doesn't really make sense for...
2
2
79,401,274
2025-1-30
https://stackoverflow.com/questions/79401274/extracting-text-from-wikisource-using-beautifulsoup-returns-empty-result
I'm trying to extract the text of a book from a Wikisource page using BeautifulSoup, but the result is always empty. The page I'm working on is Le Père Goriot by Balzac. Here's the code I'm using: import requests from bs4 import BeautifulSoup def extract_text(url): try: # Fetch the page content response = requests.get(...
To find the text section you are using the class mw-parser-output. But this class is present for two different div elements. And the first one with this class doesn't contain the texts. The find function returns the first element found. That is why you can't get the texts. The div with class prp-pages-output contains a...
1
2
79,401,374
2025-1-30
https://stackoverflow.com/questions/79401374/how-to-convert-multiple-video-files-in-a-specific-path-outputvideo-with-the-same
The following code to converts a one video from mp4 to avi using ffmpeg ffmpeg.exe -i "kingman.mp4" -c copy "kingman.avi" I need to convert multiple videos in a specific path. "outputvideo" with the same video name This is the my code that needs to be modified. from pathlib import Path import subprocess from glob impor...
Use ffmpeg.exe if you are using windows, else just ffmpeg will work in case of linux from pathlib import Path import subprocess import os from glob import glob input_folder = "video" output_folder = "outputvideo" abs_path = os.getcwd() all_files = glob(f'{abs_path}/{input_folder}/*.mp4') output_dir = os.path.join(abs_p...
1
1
79,401,430
2025-1-30
https://stackoverflow.com/questions/79401430/pyspark-jdbc-read-with-partitions
I'm reading data in pyspark from postgres using jdbc connection. The table being read is large, about 240 million rows. I'm attempting to read it into 16 partitions. The read is being performed like this. query = f""" (select receiptid, itemindex, barcode, productnumberraw, itemdescription, itemdescriptionraw, itemexte...
If you're seeing them duplicated in pg_stat_activity, some of them might show a leader_pid pointing at the pids of others, which means the query is being handled by multiple worker processes. Seeing your queries distributed between multiple workers is especially likely on partitioned tables. The fact that you specifica...
2
0
79,401,140
2025-1-30
https://stackoverflow.com/questions/79401140/representing-tridiagonal-matrix-using-numpy
I am trying to solve a mathematical problem related to matrices using numpy as shown below: I am really finding it hard to represent this kind matrix structure using numpy. I really donot want to type these values because I want to understand how this kind of structures are represented using python. Consider the empty...
The matrix has to be decomposed into several parts. First, the middle region forms a block diagonal matrix, where each block is a 4x4 Toeplitz matrix. # makes a shifted diagonal matrix def E(n, v, k): return v * np.eye(n, k=k) def toeplitz_block(n, v_list, k_list): return sum(E(n, v, k) for v, k in zip(v_list, k_list))...
1
2
79,400,679
2025-1-30
https://stackoverflow.com/questions/79400679/plotting-lambda-functions-in-python-and-mpmath-plot
I'm using the mpmath plot function (which simply uses pyplot, as far as I understood). Consider the following code: from math import cos, sin import mpmath as mp mp.plot([sin, cos], [0, 3]) # this is fine l = [sin, cos] mp.plot([lambda x: f(2*x) for f in l], [0, 3]) # this only plots sin(2x)! Is there anything I'm mis...
See the relevant documentation here. Here's a quick fix that does what you want. l = [sin, cos] mp.plot([lambda x, f=f: f(2*x) for f in l], [0, 3]) So, what's going on here? The key is that each lambda x: f(2*x) is equivalent to something of the form def func(x): return f(2*x) Importantly, the f within each lambda fu...
1
1
79,400,482
2025-1-30
https://stackoverflow.com/questions/79400482/map-each-element-of-torch-tensor-with-its-value-in-the-dict
Suppose i have a tensor t consisting only zeros and ones: t = torch.Tensor([1, 0, 0, 1]) And a dict with the weights: weights = {0: 0.1, 1: 0.9} I want to form a new tensor new_t, such that every element in tensor t is mapped to the corresponding value in the dict weights: new_t = torch.Tensor([0.9, 0.1, 0.1, 0.9]) Is ...
If you convert your weights dict into a tensor, you can index directly t = torch.tensor([1, 0, 0, 1]) weights = torch.tensor([0.1, 0.9]) new_t = weights[t] new_t >tensor([0.9000, 0.1000, 0.1000, 0.9000])
1
1
79,399,353
2025-1-30
https://stackoverflow.com/questions/79399353/insert-or-update-when-importing-from-json
My SQLAlchemy ORM model is populated by a JSON file that occasionally changes. The JSON file does not provide an integer primary key but has a unique alphanumeric ProductCode. My model: class ProductDescriptor(Base): __tablename__ = 'product_descriptor' id: Mapped[int] = mapped_column(primary_key=True, autoincrement=Tr...
SQLite lets us specify the matching columns for ON CONFLICT, like so: from sqlalchemy.dialects.sqlite import insert new_values = json.loads("""\ [ {"ProductCode": "code_1", "DisplayName": "display_1", "Description": "description_1"}, {"ProductCode": "code_2", "DisplayName": "display_2", "Description": "description_2"} ...
1
1
79,400,462
2025-1-30
https://stackoverflow.com/questions/79400462/django-managers-vs-proxy-models
I'm currently getting into proxy models and I actually cannot understand when we should give them respect. For me they look very similar to managers Is there some differences or we can implement the same things using proxy models and managers?
Django managers are classes that manage the database query operations on a particular model. Django model manager Proxy models allow you to create a new model that inherits from an existing model but does not create a new database table. proxy model Let me give you an example: class Book(models.Model): title = models.C...
2
2
79,400,269
2025-1-30
https://stackoverflow.com/questions/79400269/truth-value-for-expr-is-ambiguous-in-with-columns-ternary-expansion-on-dates
I'm trying to account for room usage only during business hours and abridge an event duration if it runs past the end of business hours. I have a dataframe like this: import polars as pl from datetime import datetime df = pl.DataFrame({ 'name': 'foo', 'start': datetime.fromisoformat('2025-01-01 08:00:00'), 'end': datet...
Short answer You use when/then/otherwise instead of if else df.with_columns( duration=pl.when(pl.col("end") <= pl.col("business_end")) .then(pl.col("end") - pl.col("start")) .otherwise(pl.col("business_end") - pl.col("start")) ) Background polars works with expressions inside contexts. What's that mean? Contexts are ...
3
6
79,399,683
2025-1-30
https://stackoverflow.com/questions/79399683/fastest-way-to-find-the-smallest-possible-sum-of-the-absolute-differences-of-pai
By grouping all the items within an array into pairs and getting their absolute differences, what is the minimum sum of their absolute differences? Example: [4, 1, 2, 3] should return 2 because |1 - 2| + |3 - 4| = 2 [1, 3, 3, 4, 5] should return 1 because |3 - 3| + |4 - 5| = 1 Getting the result for arrays with an eve...
Imagine you have sorted seven numbers A to G and you leave out A, thus calculating (C-B)+(E-D)+(G-F). That's adding or subtracting them like this: A B C D E F G - + - + - + (leaving out A) And this is how it looks in general, for leaving out each of the numbers: A B C D E F G - + - + - + (leaving out A) - + - + - + (l...
5
8
79,396,894
2025-1-29
https://stackoverflow.com/questions/79396894/doing-pywavelets-calculation-on-gpu
Currently working on a classifier using PyWavelets, here is my calculation block: class WaveletLayer(nn.Module): def __init__(self): super(WaveletLayer, self).__init__() def forward(self, x): def wavelet_transform(img): coeffs = pywt.dwt2(img.cpu().numpy(), "haar") LL, (LH, HL, HH) = coeffs return ( torch.from_numpy(LL...
Since you only seem to be interested in the Haar wavelet, you can pretty much implement it yourself: The high-frequency component of the Haar wavelet along each dimension can be written as a pairwise difference. The low-frequency component of the Haar wavelet along each dimension can be written as a pairwise sum. The...
2
4
79,398,404
2025-1-29
https://stackoverflow.com/questions/79398404/python-pandas-how-to-read-in-data-from-list-data-and-columns-separate-list
I'm running into a situation I don't know what to do: The data is a list, no index. Sample data: data = [ {'fields': ['2024-10-07T21:22:01', 'USER-A', 21, 0, 0, 21]}, {'fields': ['2024-10-07T21:18:28', 'USER-B', 20, 20, 0, 0, 0, 45]} ] The column header is in another: cols = ['Created On', 'Created By', 'Transaction C...
You could combine two DataFrame constructors: data = [{'fields': ['2024-10-07T21:22:01', 'USER-A', 21, 0, 0, 21]}, {'fields': ['2024-10-07T21:18:28', 'USER-B', 20, 20, 0, 0, 0, 45]}, ] out = pd.DataFrame(pd.DataFrame(data)['fields'].tolist()) Output: 0 1 2 3 4 5 6 7 0 2024-10-07T21:22:01 USER-A 21 0 0 21 NaN NaN 1 20...
1
3
79,398,865
2025-1-30
https://stackoverflow.com/questions/79398865/numpy-scipy-how-to-find-the-least-squares-solution-with-the-constraint-that-ax
I have a linear algebra problem that I can't find the correct function for; I need to find the vector x that satisfies Ax = b. Because A is non-square (there's 5 columns and something like 37 rows), np.linalg.solve(A,b) will not work - most search results I've seen have pointed me towards np.linalg.lstsq instead, or sc...
It doesn't sound like the least squares criterion is the important part; you just want a solution that is not too wasteful. In that case, as Nick pointed out, you could use linear programming to minimimize the total food required. (A common variant of this problem is to minimize the cost of the food consumed. You could...
3
7
79,395,723
2025-1-29
https://stackoverflow.com/questions/79395723/monte-carlo-simulation-in-rocketpy-flight-has-no-attribute-apogee
I am trying to model the trajectory of a rocket in RocketPy. I have successfully completed this, and now I am trying to look at the Monte Carlo simulations. However, I am encountering an error: AttributeError: 'Flight' object has no attribute 'apogee' I have tried to make the code as simple as I can. I have the Rocket...
Thanks for that Onuralp. That's a good insight. I did get some good results for all the following: stochastic_motor.visualize_attributes() print(stochastic_motor.total_impulse) stochastic_rocket.visualize_attributes() stochastic_flight.visualize_attributes() but something that stuck out to me as a potential problem wa...
2
1
79,396,950
2025-1-29
https://stackoverflow.com/questions/79396950/converting-a-pandas-dataframe-in-wide-format-to-long-format
I have a Pandas dataframe in wide format that looks like this: import pandas as pd df = pd.DataFrame({'Class_ID': {0: 432, 1: 493, 2: 32}, 'f_proba_1': {0: 3, 1: 8, 2: 6}, 'f_proba_2': {0: 4, 1: 9, 2: 9}, 'f_proba_3': {0: 2, 1: 4, 2: 1}, 'p_proba_1': {0: 3, 1: 82, 2: 36}, 'p_proba_2': {0: 2, 1: 92, 2: 96}, 'p_proba_3':...
You can use pd.wide_to_long for this: out = (pd.wide_to_long(df, stubnames=['f_proba', 'p_proba'], i=['Class_ID', 'Meeting_ID'], j='Student_ID', sep='_') .reset_index() ) Output: Class_ID Meeting_ID Student_ID f_proba p_proba 0 432 27 1 3 3 1 432 27 2 4 2 2 432 27 3 2 8 3 493 23 1 8 82 4 493 23 2 9 92 5 493 23 3 4 41...
2
5
79,397,830
2025-1-29
https://stackoverflow.com/questions/79397830/curve-fitting-a-non-linear-equation
I'm trying to fit my thermal conductivity into the Debye-Callaway equation. However, one of my parameters is coming back negative. I've tried different initial guesses. So I'm attaching a code with thermal conductivity data from literature and the values that they got to understand where my model is going wrong. What c...
Your tau_U_inv function forgot to take into account T. The corrected version should be this: def tau_U_inv(omega, B, T): return B * omega**2 * T * np.exp(-theta_D / (3 * T)) When I make this change the parameters show Fitted parameters: A = 1.935907419814169e-43, B = 9.770738747258265e-18 which appears to be much clo...
4
6
79,395,477
2025-1-29
https://stackoverflow.com/questions/79395477/how-to-save-a-dataset-in-multiple-shards-using-tf-data-dataset-save
How can I save a tf.data.Dataset in multiple shards using tf.data.Dataset.save()? I am reading in my dataset from CSV using tf.data.experimental.make_csv_dataset. The TF docs here are not very helpful. There is a shard_func argument, but the examples given aren't helpfull and its not clear how to map to an int in a det...
shard_func must return a scalar Tensor of type tf.int64 (not Python or NumPy integer). So you cannot just return np.int64(...) or do a Python‐level % on dictionary.You need to pick (or compute) tensor inside dataset element and return tf.cast(..., tf.int64). For example if your CSV has a column "c1" you could do: def s...
2
1
79,301,659
2024-12-22
https://stackoverflow.com/questions/79301659/assertionerror-detection-in-self-models-using-insightface-on-linux-docker-con
I’m developing a Python application that uses Flask, running in a Docker container on a Linux server with NGINX. The application works perfectly on my local machine, but when I deploy it on the server, I encounter the following error: ERROR:app:Exception: Traceback (most recent call last): File "/app/app.py", line 32,...
I met the same issue today with Ubuntu 22.04 + antelopev2 model. I changed the model to buffalo_l and the error is gone. # antelopev2 + Ubuntu 22.04: assert 'detection' in self.models app = FaceAnalysis(name='buffalo_l', providers=['CUDAExecutionProvider', 'CPUExecutionProvider']) app.prepare(ctx_id=0, det_size=(640, 6...
1
1
79,290,968
2024-12-18
https://stackoverflow.com/questions/79290968/super-object-has-no-attribute-sklearn-tags
I am encountering an AttributeError while fitting an XGBRegressor using RandomizedSearchCV from Scikit-learn. The error message states: 'super' object has no attribute '__sklearn_tags__'. This occurs when I invoke the fit method on the RandomizedSearchCV object. I suspect it could be related to compatibility issues be...
Scikit-learn version 1.6 modified the API around its "tags", and that's the cause of this error. XGBoost has made the necessary changes in PR11021, but at present that hasn't made it into a released version. You can either keep your sklearn version <1.6, or build XGBoost directly from github (or upgrade XGBoost, after ...
25
21
79,305,824
2024-12-24
https://stackoverflow.com/questions/79305824/efficiently-removing-a-single-page-from-a-large-multi-page-tiff-with-jpeg-compre
I am working with a large multi-page TIFF file that is JPEG-compressed, and I need to remove a single page from it. I am using the tifffile Python package to process the TIFF, and I already know which page I want to remove based on metadata tags associated with that page. My current approach is to read all pages, modif...
I've created a Python package to handle it. While it can be made more extensible, it efficiently solves the problem without loading all the image data into memory. Core Idea: The package works by: Reconstructing the IFD (Image File Directory) chain: It removes the IFD of concern while keeping references to the origina...
2
0
79,305,326
2024-12-24
https://stackoverflow.com/questions/79305326/how-to-make-pip-virtual-environments-truly-portable
I'm trying to install Open WebUI as a portable installation, where the base folder can be moved or renamed. However, I've encountered issues making the virtual environment truly portable. While installing, I've tried using dynamic paths, but somehow the paths get hardcoded during the installation process. When I try to...
so far the only workaround is to create offline portable project folder like this: In case of after moving or renaming when the project folder stops working, do the following: empty these folders: python, venv create backup for the following files and folders: telemetry_user_id, webui.db, vector_db, uploads setup.bat ...
1
0
79,305,588
2024-12-24
https://stackoverflow.com/questions/79305588/use-yolo-with-unbounded-input-exported-to-an-mlpackage-mlmodel-file
I want to create an .mlpackage or .mlmodel file which I can import in Xcode to do image segmentation. For this, I want to use the segmentation package within YOLO to check out if it fit my needs. The problem now is that this script creates an .mlpackage file which only accepts images with a fixed size (640x640): from u...
How to export YOLO segmentation model with flexible input sizes from ultralytics import YOLO import coremltools as ct # Export to torchscript first model = YOLO("yolov8n-seg.pt") model.export(format="torchscript") # Convert to CoreML with flexible input size input_shape = ct.Shape( shape=(1, 3, ct.RangeDim(lower_bound=...
2
1
79,306,155
2024-12-24
https://stackoverflow.com/questions/79306155/move-a-string-from-a-filename-to-the-end-of-the-filename-in-python
If I have documents labeled: 2023_FamilyDrama.pdf 2024_FamilyDrama.pdf 2022-beachpics.pdf 2020 Hello_world bring fame.pdf 2019-this-is-my_doc.pdf I would like them to be FamilyDrama_2023.pdf FamilyDrama_2024.pdf beachpics_2022.pdf Hello_world bring fame_2020.pdf this-is-my_doc_2019.pdf So far, I know how to remove a ...
This solution uses parse instead of regular expressions. from parse import parse fnames = [ "2023_FamilyDrama.pdf", "2024_FamilyDrama.pdf", "2022-beachpics.pdf" ] for file_name in fnames: year,sep,name,ext = parse("{:d}{}{:l}.{}", file_name) print(f"{name}_{year}.{ext}") # Output: # FamilyDrama_2023.pdf # FamilyDrama_2...
2
2
79,303,697
2024-12-23
https://stackoverflow.com/questions/79303697/snakemake-expand-a-string-saved-in-a-variable
My question is very simple, but I can't find how to do it in the Snakemake documentation. Let's say I have a very long string to expand, like : rule all: input: expand("sim_files/test_nGen{ngen}_N{N}_S{S}_NR{NR}_DG{DG}_SS{SS}/test_nGen{ngen}_N{N}_S{S}_NR{NR}_DG{DG}_SS{SS}.yaml", ngen=list_ngen, N=list_N, S=list_S, NR=l...
Use an f-string to format the string before expansion: prefix = "test_nGen{ngen}_N{N}_S{S}_NR{NR}_DG{DG}_SS{SS}" rule all: input: expand(f"sim_files/{prefix}/{prefix}.yaml",ngen=list_ngen, N=list_N, S=list_S, NR=list_NR, DG=list_DG, SS=list_SS)
2
1
79,305,237
2024-12-24
https://stackoverflow.com/questions/79305237/how-can-i-find-the-column-containing-the-third-nan-value-in-each-row-of-a-datafr
I have been given a problem to solve for my assignment. Here's the description for my problem: In the cell below, you have a DataFrame df that consists of 10 columns of floating-point numbers. Exactly 5 entries in each row are NaN values. For each row of the DataFrame, find the column which contains the third NaN value...
idxmax was a good approach, you can combine this with a mask that indicates the 3rd NaN, for this use cumsum: m = df.isna() out = (m & m.cumsum(axis=1).eq(3)).idxmax(axis=1) since idxmax always returns the first value if there are several maxes, this could be simplified to: out = df.isna().cumsum(axis=1).eq(3).idxmax(...
1
2
79,304,669
2024-12-24
https://stackoverflow.com/questions/79304669/when-yielding-anyof-events-is-it-safe-to-use-if-req-triggered-instead-of-if
There seems to be a quirky behaviour when working with requests without the with statement as a context manager, which causes resources to be locked up permanently if using the standard if req in res pattern and both conditions occur simulatenously as follows. req = resource.request() result = yield req | env.timeout(5...
You are correct. There seems to be a edge case where the request is triggered but not processed and expression req in results is false. However when the event is triggered, the resource is seized, which needs to be released. Also if a event has been triggered, the cancel does nothing. I looked that context manager for ...
2
2
79,300,265
2024-12-21
https://stackoverflow.com/questions/79300265/is-it-possible-to-type-annotate-python-function-parameter-used-as-typeddict-key
While working through code challenges I am trying to use type annotations for all function parameters/return types. I use mypy in strict mode with the goal of no errors. I've spent some time on this one and can't figure it out - example of problem: from typing import Literal, NotRequired, TypedDict class Movie(TypedDic...
You can use TypeVar to help mypy deduce the exact literal that is being used, and this can even be propagated to the output. That way mypy knows which keys are definitely present in the output dicts and which are not. Instead of: class MovieData(TypedDict): Awards: NotRequired[str] Runtime: NotRequired[str] You would ...
1
1
79,305,200
2024-12-24
https://stackoverflow.com/questions/79305200/static-typing-of-python-regular-expression-incompatible-type-str-expected
Just to be clear, this question has nothing to do with the regular expression itself and my code is perfectly running even though it is not passing mypy strict verification. Let's start from the basic, I have a class defined as follows: from __future__ import annotations import re from typing import AnyStr class MyClas...
AnyStr is a type variable, and type variables should either appear 2+ times in a function signature or 1+ time in the signature and 1 time in the enclosing class as a type variable. If you have neither of these situations, you'd be better off to use a union. See mypy Playground — comment by dROOOze
1
1
79,306,481
2024-12-24
https://stackoverflow.com/questions/79306481/how-can-i-save-a-figure-to-pdf-with-a-specific-page-size-and-padding
I have generated a matplotlib figure that I want to save to a PDF. So far, this is straightforward. import matplotlib.pyplot as plt x = [1, 2, 3, 4] y = [3, 5, 4, 7] plt.scatter(x, y) plt.savefig( "example.pdf", bbox_inches = "tight" ) plt.close() However, I would like the figure to appear in the middle of a standard ...
Another option is to use constrained layout and set a rectangle that you want the all the plot elements to be contained in. import matplotlib.pyplot as plt x = [1, 2, 3, 4] y = [3, 5, 4, 7] fig, ax = plt.subplots(figsize=(8.3, 11.7), layout='constrained') fig.get_layout_engine().set(rect=(0.15, 0.3, 0.7, 0.4)) # left, ...
5
2
79,302,863
2024-12-23
https://stackoverflow.com/questions/79302863/how-to-use-python-to-create-orc-file-compressed-with-zlib-compression-level-9
I want to create an ORC file compressed with ZLIB compression level 9. Thing is, when using pyarrow.orc, I can only choose between "Speed" and "Compression" mode, and can't control the compression level E.g. orc.write_table(table, '{0}_zlib.orc'.format(file_without_ext), compression='ZLIB', compression_strategy='COMPRE...
The Apache ORC library (which is used internally by other libraries for ORC support) doesn't allow to set the compression level freely (neither the C++ nor the Java implementation). The C++ library supports only CompressionStrategy_SPEED and CompressionStrategy_COMPRESSION (source): enum CompressionStrategy { Compressi...
1
2
79,304,262
2024-12-23
https://stackoverflow.com/questions/79304262/curve-on-top-of-heatmap-seaborn
I'm trying to reproduce this graph: Here's my code: #trials_per_sim_list = np.logspace(1, 6, 1000).astype(int) trials_per_sim_list = np.logspace(1, 5, 100).astype(int) trials_per_sim_list.sort() sharpe_ratio_theoretical = pd.Series({num_trials:get_expected_max_SR(num_trials, mean_SR = 0, std_SR = 1) for num_trials in ...
I replicate the visual effect below, using matplotlib: To speed things up I put values into a list rather than into a growing dataframe. To speed things up further, you could do one or a combination of: Compute the inner loop values in a single shot by adding an extra dimension to dist (i.e. this will dispense with t...
2
1
79,299,527
2024-12-21
https://stackoverflow.com/questions/79299527/why-numpy-array-so-slow-when-editing-the-data-inside
I wrote an algorithm that uses a long list. Since numpy.array should perform better in dealing with long data, I wrote another version using numpy.array. list version: import math def PrimeTable(n:int) -> list[int]: nb2m1 = n//2 - 1 l = [True]*nb2m1 for i in range(1,(math.isqrt(n)+1)//2): if l[i-1]: for j in range(i*3,...
Numpy is optimized for vectorized operations, where large chunks of data are processed in bulk. Instead of updating element-by-element(l[j] = False) we can use slicing to update a range of values at once. Also reducing the number of python loops should make the code more effective. I've further optimised the code by us...
2
1
79,304,226
2024-12-23
https://stackoverflow.com/questions/79304226/should-i-manually-patch-the-pandas-dataframe-query-vulnerability-or-wait-for-a
I'm currently addressing the Pandas DataFrame.query() Code Injection vulnerability, which allows arbitrary code execution if unsafe user input is processed by the .query() method. I understand this issue arises because the query() method can execute expressions within the context of the DataFrame, potentially leading t...
Should I wait for an official update to address this issue? Are there any best practices for monitoring when a fix becomes available? The 'vulnerability' in question strikes me as basically unfixable, so I would not expect a fix to become available. The method DataFrame.query() is designed to allow a user to run esse...
3
1
79,301,935
2024-12-23
https://stackoverflow.com/questions/79301935/how-to-solve-the-derivative-of-the-expression-with-respect-to-d
The integral is Where the variables follow the following distribution: Thus, the integral becomes: Now, my code in python is to integrate the expression with \(W_{1:3}\) being \(1,2,3\) respectively, \(r_1 = 0\), \(v\), which is the variance is \(1\), and the time constant \(tau\) being \(1\), I want to estimate roo...
I can't tell fully what's going on, but there seem to be some problems with the way the problem is stated, and I'm thinking that you need to straighten out the problem statement before seeking a solution. If I'm not mistaken, all the distributions involved are normal distributions, and you are marginalizing (integratin...
2
1
79,305,343
2024-12-24
https://stackoverflow.com/questions/79305343/how-to-move-x-axis-on-top-of-the-plot-in-plotnine
I am using plotnine with a date x-axis plot and want to put x-axis date values on top of the chart but couldn't find a way to do it. I have seen in ggplot it can be done using scale_x_discrete(position = "top") but with scale_x_datetime() I couldn't find any position parameter in plotnine. Below is the sample code: im...
Try this: # Create the line chart (ggplot(data, aes(x='date', y='value')) + geom_line() + labs(title='Line Chart with Dates on X-Axis', x='Date', y='Value') + theme_classic() + theme(axis_line_x=element_line(position=('axes', 1))) ) Here's the source code explanation/implementation for position=(axes, 1) for more clar...
2
1
79,304,899
2024-12-24
https://stackoverflow.com/questions/79304899/how-to-select-rows-that-display-some-type-of-pattern-in-python
I am looking to extract rows from my dataset based on a pattern like condition. The condition I'm looking for is finding periods in a battery's charging history where it discharged from 100-0% without charging in between. For example, in this dataset below I would be interested in a function that would only return time...
[Code updated according to comments] The idea I use is to keep only the rows with 0 and 100 and the final rows of interest will be the ones with 100 followed by 0. [after checking with .diff(1) that the values are monotonically decreasing] I also updated your example to include some more difficult cases like when it st...
1
1
79,302,825
2024-12-23
https://stackoverflow.com/questions/79302825/how-do-you-insert-a-map-reduce-into-a-polars-method-chain
I’m doing a bunch of filters and other transform applications including a group_by on a polars data frame, the objective being to count the number of html tags in a single column per date per publisher. Here is the code: 120 def contains_html3(mindate, parquet_file = default_file, fieldname = "text"): 121 """ checks if...
Is it not the same as aggregating the list of col() names at the same time? fieldnames = ["text1", "text2", "text3", "text4"] (df.group_by("publisher", "date") .agg(pl.col(fieldnames).str.contains_any(html_tags).sum()) .with_columns(sum = pl.sum_horizontal(fieldnames)) ) shape: (45, 7) ┌───────────┬────────────┬──────...
3
1
79,306,493
2024-12-24
https://stackoverflow.com/questions/79306493/unable-to-install-avatar2-on-windows
I'm trying to install the avatar2 package, but I'm encountering this error: posix_ipc_module.c(37): fatal error C1083: Non è possibile aprire il file inclusione: 'sys/time.h': No such file or directory I know that it is needed a unix system, bu the framework i'm trying to implement works with angr, which could work al...
Although not explicitly stated, this package doesn't seem to support Windows as can be seen in the installation instructions provided on their GitHub which uses POSIX style commands. One way you can use this package on Windows is to install Windows Subsystem for Linux (WSL) which provides a compatibility layer that let...
1
1
79,305,785
2024-12-24
https://stackoverflow.com/questions/79305785/how-does-numpy-solve-nth-5-and-higher-degree-polynomials
There is a function in NumPy that solves any polynomial with given coefficient (numpy.roots()). So how does NumPy solve it if there is no formula for 5th and higher degree polynomials? I know about Newton's method but I wonder how exactly NumPy applies it. I tried finding information about it in the NumPy documentation...
So, the answer is in numpy documentation. But since that was the opportunity for me to play with it, I put in an answer an experiment illustrating how it can be done. Let's say we want to solve zeros of X**5 - 7*X**4 + 15*X**3 - 5*X**2 - 16*X + 12 I obtained this polynomial by doing import sympy X=sympy.symbols("X") sy...
4
6
79,305,259
2024-12-24
https://stackoverflow.com/questions/79305259/cant-find-keyword-using-playwright-pyppeteer
When using all kinds of Python automation tools (such as Playwright and Pyppeteer), I can't seem to grab the "Continue with Google" button on https://dropbox.com/login. When I do this through the console like this: const element = [...document.querySelectorAll('span,button,div,a')].find(el => el.textContent.includes('D...
Apparently the structure generated for FireFox is different from the structure generated for other browsers. This worked on FireFox for me: document.querySelector(".L5Fo6c-bF1uUb").click() In FireFox the button has this structure: <div id="some_id_here" class="L5Fo6c-bF1uUb" tabindex="0"></div> and no inner text. Thi...
3
2
79,303,657
2024-12-23
https://stackoverflow.com/questions/79303657/why-is-byteslst-slower-than-bytearraylst
With lst = [0] * 10**6 I get times like these: 5.4 ± 0.4 ms bytearray(lst) 5.6 ± 0.4 ms bytes(bytearray(lst)) 13.1 ± 0.7 ms bytes(lst) Python: 3.13.0 (main, Nov 9 2024, 10:04:25) [GCC 14.2.1 20240910] namespace(name='cpython', cache_tag='cpython-313', version=sys.version_info(major=3, minor=13, micro=0, releaselevel='...
As pointed out by @Homer512 in the comments, bytearray and bytes are implemented quite differently in CPython. While bytearray was given a fast path for creation from list and tuple with GitHub issue #91149, bytes did not receive the same optimization. The said fast path for bytearray takes advantage of the PySequence_...
7
7
79,300,874
2024-12-22
https://stackoverflow.com/questions/79300874/datatables-instance-not-synced-with-dom-input-checkbox-status
I have a table my_tbl initialized with datatables2.1.8.js jQuery library: /* using python django template because table template is not in the same html file */ {% include 'my_tbl_template.html' %} let my_tbl=$('#my_tbl').DataTable({...}), each cell containing <input type="checkbox" value="some_value"> whether initial...
The problem was with DataTables initialization hierarchy in html page! my functions printCheckboxStatusDom(), printCheckboxStatusTbl() and $(document).ready(function(){...}) was stored in a javascript file my_scripts.js in a local dir, and the current page was like {% include 'my_tbl_template.html' %}; <script>let my_...
1
1
79,304,741
2024-12-24
https://stackoverflow.com/questions/79304741/how-should-i-convert-this-recursive-function-into-iteration
I have a recursive function in the following form: def f(): if cond1: ... f() elif cond2: ... I've "mechanically" converted it to an iterative function like this: def f(): while True: if cond1: ... elif cond2: ... break else: break I believe this conversion is valid, but is there a more elegant way to do it? For exam...
Since the loop effectively continues only when cond1 is met, you can make it the condition that the while loop runs on, and run the code specific to cond2 after the loop if it's met: def f(): while cond1: ... if cond2: ...
1
3
79,304,247
2024-12-23
https://stackoverflow.com/questions/79304247/polars-transform-meta-data-of-expressions
Is it possible in python polars to transform the root_names of expression meta data? E.g. if I have an expression like expr = pl.col("A").dot(pl.col("B")).alias("AdotB") to add suffixes to the root_names, e.g. transforming the expression to pl.col("A_suffix").dot(pl.col("B_suffix")).alias("AdotB_suffix") I know that ...
There is an example in the tests that does query plan node rewriting in Python with callbacks: https://github.com/pola-rs/polars/blob/main/py-polars/tests/unit/lazyframe/cuda/test_node_visitor.py But I can't see any equivalent API for rewriting expressions? Out of interest, there is .serialize() which can dump to JSO...
2
2
79,303,980
2024-12-23
https://stackoverflow.com/questions/79303980/can-you-override-the-default-formatter-for-f-strings
Reading through PEP 3101, it discusses how to subclass string.Formatter to define your own formats, but then you use it via myformatter.format(string). Is there a way to just make it work with f-strings? E.g. I'm looking to do something like f"height = {height:.2f}" but I want my own float formatter that handles certai...
As I mentioned in comments F-strings are actually processed at compile time, not runtime. you can't override the default f-string formatter is due to how Python implements f-strings at a fundamental level. For example if you run f"height = {height:.2f}" It effectively converts "height = {}".format(format(height, '.2f'...
1
1
79,295,206
2024-12-19
https://stackoverflow.com/questions/79295206/efficiently-draw-random-samples-without-replacement-from-an-array-in-python
I need to draw random samples without replacement from a 1D NumPy array. However, performance is critical since this operation will be repeated many times. Here’s the code I’m currently using: import numpy as np # Example array array = np.array([10, 20, 30, 40, 50]) # Number of samples to draw num_samples = 3 # Draw sa...
The code below generates random samples of a list without replacement in a vectorized manner. This solution is particularly useful when the number of simulations is large and the number of samples per simulation is low. import numpy as np def draw_random_samples(len_deck, n_simulations, n_cards): """ Draw random sample...
4
0
79,301,108
2024-12-22
https://stackoverflow.com/questions/79301108/googles-gemini-on-local-audio-files
Google has a page describing how to use one of their Gemini-1.5 models to transcribe audio. They include a sample script (see below). The script grabs the audio file from Google Storage via the Part.from_uri() command. I would, instead, like to use a local file. Setting the URI to "file:///..." does not work. How can I...
Although one might expect the following base-64 encoding and decoding to cancel, the following code appears to work. (The code is a slightly modified version from this page.) ... encoded_audio = base64.b64encode(open(audio_path, "rb").read()).decode("utf-8") mime_type = "audio/mpeg" audio_content = Part.from_data( data...
1
1
79,302,101
2024-12-23
https://stackoverflow.com/questions/79302101/calling-a-rust-function-that-calls-a-python-function-from-python-code
I’m new to pyo3, and I would like to achieve the following thing. My main code is in Python, but I would like to call a Rust function from this Python code. The trick is, the Rust function should be able to call a Python function provided as an argument. Let’s say that I have a Python function, that cannot be embedded ...
In my_rust_function(), take Bound<'_, PyAny> (or any variant, such as Borrowed<'_, '_, PyAny> or Py<PyAny>, but prefer Bound unless you have reasons not to), and use the call0() method on it to call it without arguments, or call1() to call it with positional arguments only, or call() to call it with both positional and...
2
2
79,302,073
2024-12-23
https://stackoverflow.com/questions/79302073/dealing-with-stopiteration-return-from-a-next-call-in-python
I'm using the below to skip a group of records when a certain condition is met: if (condition met): ... [next(it) for x in range(19)] Where it is an itertuples object created to speed up looping through a large dataframe (yes, the loop is necessary). it = df.itertuples() for row in it: ... What's the idiomatic way of...
So, in general, the solution to a potential exception being raised is to use exception handling. But in the case of next, you can simply use the second argument (which will make it return a default value in case the iterator is exhausted). But you shouldn't use a list comprehension like this anyway, so the most basic s...
1
2
79,294,881
2024-12-19
https://stackoverflow.com/questions/79294881/how-can-i-get-a-certain-number-of-evenly-spaced-points-along-the-octagon-perimet
I want to get the coordinates of a number of points that together form an octagon. For a circle this is done easily as follows: import numpy as np n = 100 x = np.cos(np.linspace(0, 2 * np.pi, n)) y = np.sin(np.linspace(0, 2 * np.pi, n)) coordinates = list(zip(x, y)) By changing n I can increase/decrease the "angularit...
Let's use some math. Each triangle in the polygon is isosceles. Assuming r the radius of the containing circle and a each side of the polygon we have: n_sides = 8 perimeter = n_sides * a a/2 = sin(pi/n_sides) / r # isosceles = 2 equal right triangles perimeter = n_sides * 2 * sin(pi/n_sides) / r r = perimeter/(2 * n_s...
5
4
79,300,458
2024-12-22
https://stackoverflow.com/questions/79300458/how-to-prevent-my-python-script-from-closing-immediately-after-running-on-window
I'm just starting out with Python on my Windows computer. I wrote a simple script to print "Hello, World!" like this: print("Hello, World!") When I double-click the .py file to run it, a command prompt window briefly appears and then closes right away. I can't see the "Hello, World!" message. How can I make the window...
you can use input function print("Hello, World!") input("Press Enter to exit...")
2
3
79,299,908
2024-12-21
https://stackoverflow.com/questions/79299908/select-rows-if-a-condition-is-met-in-any-two-columns
Please help me filter my dataframe for a condition, that should be fulfilled in any two columns. Imagine a list of students with grades in different sports. I want to filter the list so the new list passed_students shows only those who have scored a 4 or greater in at least two different sports. Students = { "Names": [...
drop the "Names", then compare to 4 with ge, sum to count the number of True per row and filter with boolean indexing: passed_Students = Students[Students.drop(columns=['Names']) .ge(4).sum(axis=1).ge(2)] Output: Names Football Basketball Volleyball Foosball 0 Tom 4 4 6 4 2 Sally 2 4 6 4 Intermediates: # Students.dr...
1
2
79,298,368
2024-12-20
https://stackoverflow.com/questions/79298368/inspect-all-probabilities-of-bertopic-model
Say I build a BERTopic model using from bertopic import BERTopic topic_model = BERTopic(n_gram_range=(1, 1), nr_topics=20) topics, probs = topic_model.fit_transform(docs) Inspecting probs gives me just a single value for each item in docs. probs array([0.51914467, 0. , 0. , ..., 1. , 1. , 1. ]) I would like the entir...
For individual topic probability across each document you need to add one more argument. topic_model = BERTopic(n_gram_range=(1, 1), nr_topics=20, calculate_probabilities=True) Note: This calculate_probabilities = True will only work if you are using HDBSCAN clustering embedding model. And Bertopic by default uses all...
1
1
79,299,276
2024-12-21
https://stackoverflow.com/questions/79299276/geopandas-is-missing-states-geojson-file
All, I got the following error when trying to import states.geojson file as described in this page https://www.twilio.com/en-us/blog/geospatial-analysis-python-geojson-geopandas-html. I think that this file is among the pre-installed files with the geopands. I am using geopandas version 0.14.4 import geopandas as gpd s...
The read_file method of geopandas expect a file adress as input as can be seen here in the documentation https://geopandas.org/en/stable/docs/reference/api/geopandas.read_file.html import geopandas as gpd gpd.read_file("./directory/fileName.json") it seems that the geojson that you are seeking is a geojson file for th...
1
2
79,298,447
2024-12-20
https://stackoverflow.com/questions/79298447/pytorch-scatter-max-for-sparse-tensors
I have the following PyTorch code value_tensor = torch.sparse_coo_tensor(indices=query_indices.t(), values=values, size=(num_lines, img_size, img_size)).to(device=device) value_tensor = value_tensor.to_dense() indices = torch.arange(0, img_size * img_size).repeat(len(lines)).to(device=device) line_tensor_flat = value_t...
You should be able to directly use scatter_max on the sparse tensor if you keep the indices that you pass to scatter_max also sparse (i.e, only the non-zero ones). Consider this example query_indices = torch.tensor([ [0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 1, 2], [0, 1, 0, 0, 1, 0] ]) values = torch.tensor([1, 2, 3, 4, 5, 6])...
2
1
79,298,424
2024-12-20
https://stackoverflow.com/questions/79298424/generating-binary-arrays-with-alternating-values-based-on-change-indices-in-nump
I have an array a of increasing indexes, e.g. [2 5 9 10], which indicates positions of value change. Assuming the output values are 0 and 1, I want to get array b: [0 0 1 1 1 0 0 0 0 1 0] Is there a NumPy magic to transform a into b?
One way among many others a=np.array([2,5,9,10]) x=np.zeros((a.max()+1,), dtype=np.uint8) x[a]=1 b=x.cumsum()%2 Some explanation (but I guess code, in this rare case, is its own explanation, since it is quite easy, once you see it) x (after x[a]=1) contains 1 at each given position in a. So x.cumsum() contains a value...
8
14
79,298,285
2024-12-20
https://stackoverflow.com/questions/79298285/calculate-percentage-of-flag-grouped-by-another-column
I have the following dataframe: Account ID Subscription type Cancellation flag 123 Basic 1 222 Basic 0 234 Hybrid 1 345 Hybrid 1 Now I would like to calculate the percentage of cancellations, but grouped by the subscription type. I would like to get it in a format so that I can easily create a bar chart...
Use a groupby.mean: out = df.groupby('Subscription type')['Cancellation flag'].mean().mul(100) Output: Subscription type Basic 50.0 Hybrid 100.0 Name: Cancellation flag, dtype: float64 Then plot.bar: out.plot.bar() Or directly with seaborn.barplot: import seaborn as sns sns.barplot(df, x='Subscription type', y='Can...
1
2
79,298,104
2024-12-20
https://stackoverflow.com/questions/79298104/sessionstore-object-has-no-attribute-get-session-cookie-age
I have a Django project, everything goes well, but when I tried to handle the expiration of the session I got confused In a test view print(request.session.get_session_cookie_age()) give me this error SessionStore' object has no attribute get_session_cookie_age According to the documentation it should returns the value...
That functionality is not in Django 2.0, see here.
1
1
79,298,219
2024-12-20
https://stackoverflow.com/questions/79298219/plotting-heatmap-with-gridlines-in-matplotlib-misses-gridlines
I am trying to plot a heatmap with gridlines. This is my code (adapted from this post): # Plot a heatmap with gridlines import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from functional import seq arr = np.random.randn(3, 20) plt.tight_layout() ax = plt.subplot(111) ax.imshow(...
I have no idea why this happens. Using the major grid instead fixes this issue: import numpy as np import pandas as pd import matplotlib.pyplot as plt arr = np.random.randn(3, 20) plt.tight_layout() ax = plt.subplot(111) ax.imshow(arr, cmap='viridis') xr = ax.get_xlim() yr = ax.get_ylim() ax.set_xticks(np.arange(max(xr...
1
1
79,297,339
2024-12-20
https://stackoverflow.com/questions/79297339/simple-1-d-dispersion-equation-numerical-solution
I am new to coding and trying to solve a simple 1D dispersion equation. The equation and boundary conditions: adC/dx = bd^2C/dx^2 x = hj, C = C0; x = - inf, C =0 The analytical solution is C = C0 * exp (a/b*(x-hj)) Here is the code I have : import numpy as np import matplotlib.pyplot as plt C0 = 3.5 # Concentration at ...
You have a number of errors. Your matrix coefficients are wrong - try discretising those first and second derivatives again carefully. Your boundary values are fixed (Dirichlet BC). So you only have N-1 varying nodes. So your matrix should be (N-1)x(N-1) not (N+1)x(N+1). The boundary conditions are effectively transfe...
1
0
79,297,758
2024-12-20
https://stackoverflow.com/questions/79297758/how-should-i-parse-times-in-the-japanese-30-hour-format-for-data-analysis
I'm considering a data analysis project involving information on Japanese TV broadcasts. The relevant data will include broadcast times, and some of those will be for programs that aired late at night. Late-night Japanese TV schedules follow a non-standard time format called the 30-hour system (brief English explanatio...
IIUC, you could use create a datetime with '00:00' as time and add the hours as timedelta: from datetime import date, time, datetime, timedelta from zoneinfo import ZoneInfo def process_30hour(d: date, t: str): h, m = map(int, t.split(':')) # assumes format 'HH:MM' for t return (datetime.combine(d, time(), ZoneInfo('Ja...
4
5
79,293,528
2024-12-19
https://stackoverflow.com/questions/79293528/how-to-replace-xml-node-value-in-python-without-changing-the-whole-file
Doing my first steps in python I try to parse and update a xml file. The xml is as follows: <?xml version="1.0" encoding="utf-8"?> <?xml-stylesheet href="util/style/aaaa-2-0.xsl" type="text/xsl"?> <!DOCTYPE eu:eu-backbone SYSTEM "../../util/dtd/eu-regional.dtd"[]> <test dtd-version="3.2" xmlns:test="http://www.ich.org/...
In addition to LMC’s answer a small modification. You can adjust the parser to keep comments and process instructions: (Update: add Doctype info to the xml string manually) from lxml import etree def replace_checksum(infile, new_value): parser = etree.XMLParser(remove_comments=False, remove_pis=False) root = etree.pars...
1
1
79,295,258
2024-12-19
https://stackoverflow.com/questions/79295258/ig-lightstreamer-server-always-sends-updates-every-second
I'm trying to connect to IG's lightstreamer server via python to obtain candle chart data. However, I always seem to get item updates every second even though I specify that I want it every minute or every hour. This is my code: from lightstreamer.client import * loggerProvider = ConsoleLoggerProvider(ConsoleLogLevel.W...
I believe that the label 1MINUTE in the item name indicates the duration of the time interval for the chart's candlestick aggregation; however, the updates are sent continuously. If you want to receive updates at a specific frequency, you could leverage the setRequestedMaxFrequency option of the Lightstreamer client li...
1
1
79,296,597
2024-12-20
https://stackoverflow.com/questions/79296597/rolling-window-selection-with-groupby-in-pandas
I have the following pandas dataframe: # Create the DataFrame df = pd.DataFrame({ 'id': [1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2], 'date': [1, 2, 3, 4, 5, 6, 7, 8, 5, 6, 7, 8, 9, 10, 11, 12], 'value': [11, 12, 13, 14, 15, 16, 17, 18, 21, 22, 23, 24, 25, 26, 27, 28] }) df id date value 0 1 1 11 1 1 2 12 2 1 3 13 ...
The exact expected logic is not fully clear, but assuming you want to loop over the groups/rolls, you could combine groupby.nth with sliding_window_view. By reusing the DataFrameGroupBy object, will only need to compute the groups once: import numpy as np from numpy.lib.stride_tricks import sliding_window_view as swv n...
2
2
79,293,060
2024-12-19
https://stackoverflow.com/questions/79293060/how-to-set-multiple-elements-conditionally-in-polars-similar-to-pandas
I am trying to set multiple elements in a Polars DataFrame based on a condition, similar to how it is done in Pandas. Here’s an example in Pandas: import pandas as pd df = pd.DataFrame(dict( A=[1, 2, 3, 4, 5], B=[0, 5, 9, 2, 10], )) df.loc[df['A'] < df['B'], 'A'] = [100, 210, 320] print(df) This updates column A where...
updated You can work around pl.Series.scatter() using pl.Expr.arg_true() or pl.arg_where(), although it would require accessing column as pl.Series: df.with_columns( df.get_column("A").scatter( # or df["A"].scatter df.select((pl.col.A < pl.col.B).arg_true()), # or df.select(pl.arg_where(pl.col.A < pl.col.B)), [100, 210...
1
1
79,295,605
2024-12-19
https://stackoverflow.com/questions/79295605/how-to-generate-an-integer-that-repeats-like-100100100-1-in-binary-with-time-com
I am making a function that takes length:int and distance:int as inputs, and output the largest integer that satisfies the following properties in its binary representation: It starts with 1, ends with 1 There are distance - 1 many 0 between each 1 Its length is strictly less than length It could be implemented as...
Doubling the number of 1-bits instead of adding them just one at a time: def repeatdigit(length:int, distance:int) -> int: def f(want): if want == 1: return 1 have = (want + 1) // 2 x = f(have) add = min(have, want - have) return x | (x << (add * distance)) ones = 1 + (length - 2) // distance return f(ones) My ones, w...
3
0
79,294,413
2024-12-19
https://stackoverflow.com/questions/79294413/second-independent-axis-in-altair
I would like to add a second (independent) x-axis to my figure, demonstrating a month for a given week. Here is my snippet: import pandas as pd import numpy as np from datetime import datetime, timedelta weeks = list(range(0, 54)) start_date = datetime(1979, 1, 1) week_dates = [start_date + timedelta(weeks=w) for w in ...
This can be done by using the timeUnit parameter of the x encoding along with the axis format and, optionally, labelExpr parameters. Also, Altair works best with long form data and can easily handle the aggregation for you, so I have updated the data generation with this in mind. If your real data is already in short f...
1
1
79,295,148
2024-12-19
https://stackoverflow.com/questions/79295148/how-do-i-type-hint-a-frame-object-in-python
I'm type hinting a large existing Python codebase, and in one part it sets a signal handler using signal.signal. The signal handler is a custom function defined in the codebase, so I need to type hint it myself. However, while I can guess based on the description of signal.signal that the first parameter is an integer,...
types.FrameType is what you are looking for.
1
2
79,294,628
2024-12-19
https://stackoverflow.com/questions/79294628/how-to-dynamically-adjust-colors-depending-on-the-dark-mode
The default header color for DataFrames (render.DataGrid(), render.DataTable()) is a very light grey (probably gainsboro). If I switch an app to dark mode using and DataFrame the header becomes unreadable. Is there any way to make a dict to tell shiny what color to use for the color gainsboro or for a specific object, ...
We can supply an id to the input_dark_mode(), say id="mode". And then we can define css dynamically depending on input.mode() (which is either "light" or "dark") for the required selectors. Below is an example for the card header. Express from shiny.express import input, render, ui with ui.layout_sidebar(): with ui.sid...
1
1
79,294,574
2024-12-19
https://stackoverflow.com/questions/79294574/in-pandas-how-to-reference-and-use-a-value-from-a-dictionary-based-on-column-an
I've data about how my times people are sick in certain locations (location A and B) at certain times (index of dates). I need to divide each value by the population in that location (column) AND at that time (index), which references a separate dictionary. Eg dataframe: import pandas as pd data = [{'A': 1, 'B': 3}, {'...
You can create a Series from your dictionary, then unstack to DataFrame, reindex/set_axis, perform your operation and join with add_suffix: def split(k): x, y = k.split('_') return (int(y), x) # ensure using NaNs for missing values, not strings df = df.replace('Unk', pd.NA).convert_dtypes() # reshape to match the origi...
2
3