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
77,821,648
2024-1-15
https://stackoverflow.com/questions/77821648/managing-allowed-hosts-in-django-for-kubernetes-health-check
I have a Django application running on Kubernetes, using an API for health checks. The issue I'm facing is that every time the IP associated with Django in Kubernetes changes, I have to manually update ALLOWED_HOSTS. django code: class HealthViewSet(ViewSet): @action(methods=['GET'], detail=False) def health(self, requ...
The ALLOWED_HOSTS setting checks the Host header sent on an HTTP request, so you can simply configure the headers sent by your liveliness probe: livenessProbe: httpGet: path: /health/ port: 8000 httpHeaders: - name: host value: your.hostname.here # Configure the appropriate host here initialDelaySeconds: 15 timeoutSeco...
6
5
77,794,024
2024-1-10
https://stackoverflow.com/questions/77794024/searching-existing-chromadb-database-using-cosine-similarity
I have a preexisting database with around 15 PDFs stored. I want to be able to search the database so that I'm getting the X most relevant results back given a certain threshold using cosine similarity. Currently, I've defined a collection using this code: chroma_client = chromadb.PersistentClient(path="TEST_EMBEDDINGS...
ChromaDB does have similarity search. The default is L2, but you can change it as documented here. collection = client.create_collection( name="collection_name", metadata={"hnsw:space": "cosine"} # l2 is the default )
3
3
77,790,973
2024-1-10
https://stackoverflow.com/questions/77790973/lengths-of-overlapping-time-ranges-listed-by-rows
I am using pandas version 1.0.5 The example dataframe below lists time intervals, recorded over three days, and I seek where some time intervals overlap every day. For example, one of the overlapping time across all the three dates (yellow highlighted) is 1:16 - 2:13. The other (blue highlighted) would be 18:45 - 19:0...
This solution uses: numpy, no uncommon Python modules, so using Python 1.0.5 you should, hopefully, be in the clear, no nested loops to care for speed issues with growing dataset, Method: Draw the landscape of overlaps Then select the overlaps corresponding to the number of documented days, Finally describe the over...
5
3
77,818,902
2024-1-15
https://stackoverflow.com/questions/77818902/how-to-make-connections-between-two-wells
I have a list of wells that stores two wells and the contents of these wells in the form [depth interval from, depth interval to, soil description] wells = [ [[0, -4, 'soil'], [-4, -8, 'clay'], [-8, -12, ' gravel'], [-12, -20, 'sand'], [-20, -24, 'basalts']], [[0, -4, 'soil'], [-4, -16, 'sand'], [-16, -20, 'galka'], [-...
All i had to do was compare all the layers from top to bottom and draw connections so that the deeper layers lay lower than the shallower ones wells = [ [ [24, 20, 'basalts'], [20, 12, 'sand'], [12, 8, 'graviy'], [8, 4, 'clay'], [4, 0, 'soil'] ], [ [36, 32, 'basalts'], [32, 20, 'galka'], [20, 16, 'sheben'], [16, 4, 'sa...
3
0
77,806,733
2024-1-12
https://stackoverflow.com/questions/77806733/download-oecd-api-data-using-python-and-sdmx
I'm trying to execute the following SDMX query using Python from the OECD's database. https://stats.oecd.org/restsdmx/sdmx.ashx/GetData/LAND_COVER_FUA/AUS+AUT.FOREST+GRSL+WETL+SHRUBL+SPARSE_VEGETATION+CROPL+URBAN+BARE+WATER.THOUSAND_SQKM+PCNT/all?startTime=1992&endTime=2019 I've looked around but can't get this to wor...
Using sdmx1: import sdmx OECD = sdmx.Client("OECD_JSON") key = dict( COU="AUS AUT".split(), FUA=[], VARIABLE="FOREST GRSL WETL SHRUBL SPARSE_VEGETATION CROPL URBAN BARE WATER".split(), MEAS="THOUSAND_SQKM PCNT".split(), ) # Assemble into a string key_str = ".".join("+".join(values) for values in key.values()) print(f"{...
3
2
77,815,914
2024-1-14
https://stackoverflow.com/questions/77815914/macos-sonoma-cron-job-doesnt-have-access-to-trash-even-though-it-has-full-sy
Edit: MacOS Sonoma Version 14.2.1 I am running a python script via crontab, and the script runs, but I get an error when trying to iterate the ~/.Trash directory: PermissionError: [Errno 1] Operation not permitted: '/Users/me/.Trash' I have enabled full disk access for: /usr/sbin/cron, /usr/bin/crontab, and terminal.ap...
I cross posted this issue in the apple developer forums: Here In one of the responses I was linked a really great thread that helps explain some of what is going on: Here Here's the snippet that's most applicable to the situation. Scripting MAC presents some serious challenges for scripting because scripts are run b...
4
1
77,823,058
2024-1-16
https://stackoverflow.com/questions/77823058/how-create-a-2-row-table-header-with-docutils
I wrote an extension for Sphinx to read code coverage files and present them as a table in a Sphinx generated HTML documentation. Currently the table has a single header row with e.g. 3 columns for statement related values and 4 columns for branch related data. I would like to create a 2 row table header, so multiple ...
The magic of multiple cells spanning rows or columns is done by morerows and morecols. In addition, merged cells need to be set as None. I found it by investigating the code for the table parser. Like always with Sphinx and docutils, such features are not documented (but isn't docutils and Sphinx meant to document code...
2
2
77,819,010
2024-1-15
https://stackoverflow.com/questions/77819010/how-to-find-the-points-of-intersection-between-a-circle-and-an-ellipsem
So I have been trying to solve a question lately, given an ellipse and a circle such that the center of the circle lies on the ellipse. We need to find the area between the two curves. As for inputs we have a,b (The axes of the ellipse). R(The radius of the circle) and Theta(The angle that the circles center makes with...
I think the easiest way to do this is simply by numerical integration. You can find the lower and upper curves for both circle and ellipse and hence the top and bottom parts of the area at any x value. You can also readily find the limits of integration. Note also that, for the purposes of finding the relevant area, yo...
3
2
77,826,724
2024-1-16
https://stackoverflow.com/questions/77826724/implementing-frustum-culling-in-python-ray-tracing-camera
I'm working on a ray tracing project in Python and have encountered a performance bottleneck. I believe implementing frustum culling in my Camera class could significantly improve rendering times. Camera: class Camera(): def __init__(self, look_from, look_at, screen_width = 400 ,screen_height = 300, field_of_view = 90....
You just need to modify the Camera class as following: class Camera(): def __init__(self, look_from, look_at, screen_width = 400 ,screen_height = 300, field_of_view = 90., aperture = 0., focal_distance = 1.): self.screen_width = screen_width self.screen_height = screen_height self.aspect_ratio = float(screen_width) / s...
2
6
77,817,356
2024-1-15
https://stackoverflow.com/questions/77817356/how-to-correctly-define-a-classmethod-that-accesses-a-value-of-a-mangled-child-a
In Python, how do I correctly define a classmethod of a parent class that references an attribute of a child class? from enum import Enum class LabelledEnum(Enum): @classmethod def list_labels(cls): return list(l for c, l in cls.__labels.items()) class Test(LabelledEnum): A = 1 B = 2 C = 3 __labels = { 1: "Label A", 2:...
Note: This answer was originally a comment to the question. I strongly advise taking a different approach, like: Ethan Furman's answer (author of Python's Enum) Or juanpa.arrivillaga's answer Python 3.11+ I do not suggest using private names. That being said, if for some reason you must use private names and you...
4
2
77,827,942
2024-1-16
https://stackoverflow.com/questions/77827942/connection-and-cursor-still-usable-outside-with-block
My system: Windows 10 x64 Python version 3.9.4 SQLite3 module integrated in the standard library A DB connection and a cursor are both considered resources, so that I can use a with clause. I know that if I open a resource in a with block, it will be automatically closed outside it (files work in this way). If these ...
The context manager does not close the connection on exit; it either commits the last transaction (if no exception was raised) or rolls it back. From the documentation: Note The context manager neither implicitly opens a new transaction nor closes the connection. If you need a closing context manager, consider using c...
2
1
77,827,341
2024-1-16
https://stackoverflow.com/questions/77827341/searching-a-list-of-lists-with-unique-keys
I have a list of track information from Spotify: track_list = [[track_id1, track_title1, track_popularity1],[track_id2, track_title2, track_popularity2] Each track_id is unique. Is there a way to find the entry that matches the track_id without iterating through the entire list every time? def find_track(track_id, trac...
The most efficient method for this purpose would be using a dictionary, where the keys are the track_ids and the values are the corresponding track information. This allows for constant-time lookups (O(1) complexity), which is significantly faster than iterating over the entire list (O(n) complexity). Here's an example...
2
4
77,825,686
2024-1-16
https://stackoverflow.com/questions/77825686/error-installing-faiss-cpu-no-module-named-swig
I'm trying to install faiss-cpu via pip (pip install faiss-cpu) and get the following error: × Building wheel for faiss-cpu (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [12 lines of output] running bdist_wheel running build running build_py running build_ext building 'faiss._swigfaiss' extension swigg...
faiss-cpu is not available in python-3.12. According to their page on pypi it's available from python-3.7 to python-3.11. You need to downgrade your python in order to install faiss-cpu in your system. Now you can either remove python-3.12 and install python-3.10 on your system. Or use conda to create a virtual env wit...
3
4
77,808,226
2024-1-12
https://stackoverflow.com/questions/77808226/pydantic-pass-the-entire-dataset-to-a-nested-field
I am using django, django-ninja framework to replace some of my apis ( written in drf, as it is becoming more like a boilerplate codebase ). Now while transforming some legacy api, I need to follow the old structure, so the client side doesn't face any issue. This is just the backstory. I have two separate models. clas...
Resolved the problem with the following code class AuthorSchema(ModelSchema): class Meta: model = Author exclude=["updated", "date_joined"] class BlogBaseSchema(ModelSchema): class Meta: model = Blog exclude = ["author", ] class BlogSchema(Schema): blog: BlogBaseSchema author: AuthorSchema @staticmethod def resolve_blo...
4
2
77,813,892
2024-1-14
https://stackoverflow.com/questions/77813892/what-is-the-minimal-gdscript-equivalent-of-python-websocket-client-code
I'm attempting to program a simple turn-based game in Godot which relies on a Python websocket server for rules and state updates. To that end, I'm trying to make a simple prototype where I can input text into a Godot client, send it to the websocket, and receive some data back - an 'echo' configuration. I have server ...
In Godot 4.2 WebSocketClient seems to not exist anymore, but in the editor I found the class WebSocketPeer with an example. I extended the example to show how to send a message to the socket server. extends Node # The URL we will connect to @export var websocket_url = "ws://localhost:8080" # Our WebSocketClient instanc...
2
1
77,824,830
2024-1-16
https://stackoverflow.com/questions/77824830/how-to-colour-the-outer-ring-like-a-doughnut-plot-in-a-radar-plot-according-to
I have data in this form : data = {'Letter': ['A', 'B', 'C', 'D', 'E'], 'Type': ['Apples', 'Apples', 'Oranges', 'Oranges', 'Bananas'], 'Value': [1, 2, 0, 5, 6]} df = pd.DataFrame(data) I want to combine a doughnut plot and a radar plot, where the outer ring will be coloured according to the column "Type". import numpy...
You could use Wedge: from matplotlib.patches import Wedge from matplotlib import colormaps ax = plt.gca() cmap = plt.cm.viridis.resampled(df['Type'].nunique()) # group consecutive types g = df['Type'].ne(df['Type'].shift()).cumsum() # set up colors per type colors = dict(zip(df['Type'].unique(), map(matplotlib.colors.t...
4
5
77,825,112
2024-1-16
https://stackoverflow.com/questions/77825112/filtering-data-based-on-boolean-columns-in-python
I have the following pandas dataframe and I would like a function that returns the ID's data with at least 1 True value in bool_1, 2 True values in bool_2 and 3 True values in bool_3 column, using the groupby function. index ID bool_1 bool_2 bool_3 0 7 True True True 1 7 False True True 2 7 False False True 3 8 True Tr...
You can specify number of Trues in dictionary, so possible compare by DataFrame.ge for greate or equal count of Trues by aggregate sum and filter original DataFrame by boolean indexing with Series.isin: d = {'bool_1':1, 'bool_2':2,'bool_3':3} ids = df.groupby('ID')[list(d.keys())].sum().ge(d).all(axis=1) print (ids) ID...
2
2
77,817,726
2024-1-15
https://stackoverflow.com/questions/77817726/python-access-modifiers-as-a-decorator
Is it possible to implement protected and private access modifiers for classes with decorators in python? How? The functionality should be like the code below: class A: def public_func(self): self.protected_func() # Runs without warning and error (Because is called in the owner class) self.private_func() # Runs without...
In the other answer of mine, in trying to determine whether a call is made from code defined in the same class as a protected method, I made use of the co_qualname attribute of a code object, which was only introduced in Python 3.11, making the solution incompatible with earlier Python versions. Moreover, using the ful...
4
6
77,824,075
2024-1-16
https://stackoverflow.com/questions/77824075/changing-values-of-a-column-in-a-data-frame
I have a data frame exemplified as data = [['A', 10, {'Cc', 'Dd'}], ['B', 15, {'Aa', 'Dd', 'Cc', 'Ee'}], ['C', 14, {'Dd', 'Ee', 'Aa'}],['D', 3, {'Bb'}],['E', 3,{'Dd', 'Cc'}]] df = pd.DataFrame(data, columns=['type', 'val', 'others']) I would like to perform some data processing on this dataset. For the 'type' column, ...
If I understand you correctly, you need to assign a numerical code to the column others - which contains sets of values. You can convert the column values to frozenset and then apply pd.Categorical to it: df["others_codes"] = pd.Categorical(df["others"].apply(frozenset)).codes print(df) Prints: type val others others...
2
1
77,823,443
2024-1-16
https://stackoverflow.com/questions/77823443/pd-io-formats-excel-excelformatter-header-style-none-not-working
I have used the following code to remove the default formating from the header in pandas. pd.io.formats.excel.ExcelFormatter.header_style = None It was working previously, but now I am getting following error. pd.io.formats.excel.ExcelFormatter.header_style = None ^^^^^^^^^^^^^^^^^^^ AttributeError: module 'pandas.io....
I tried on pandas <2 as well as pandas >2, it is working in both pandas versions. This should be the correct import: import pandas.io.formats.excel pandas.io.formats.excel.ExcelFormatter.header_style = None related git : https://github.com/pandas-dev/pandas/issues/19386#issuecomment-851653196
5
4
77,822,142
2024-1-15
https://stackoverflow.com/questions/77822142/polars-execute-many-operations-over-same-grouping
Showing a toy example with K=2 but the question is mostly relevant for high g cardinality and K>>1: df = pl.DataFrame(dict( g=[1, 2, 1, 2, 1, 2], v=[1, 2, 3, 4, 5, 6], )) K = 2 df.with_columns((col.v.shift(k+1).over('g').alias(f's{k}') for k in range(K))) ╭─────┬─────┬──────┬──────╮ │ g ┆ v ┆ s0 ┆ s1 │ │ i64 ┆ i64 ┆ i...
Polars caches window expressions. While you may not see this represented in the query plan, the over grouping is only done once. Still, your over query will not run as fast as your group_by query. This is because over has to add the results back into the original data frame. A fairer comparison would be the query below...
2
5
77,814,538
2024-1-14
https://stackoverflow.com/questions/77814538/cannot-import-publickey-from-solana-publickey
I'm developing a tracking script using Python and the Solana.py, installed via pip. The script uses websocket subscriptions to notify me when something happens on the Solana blockchain. My first approach was to watch a specific account: await websocket.account_subscribe(PublicKey('somekeyhere')) But when doing ... fro...
Based on their github, it looks like what you need is Pubkey, not Publickey, taken from solders rather than solana. Have you tried this instead? from solders.pubkey import Pubkey I haven't used their SDK before, so this might not solve your issue, but it was something I noted given your issue. Ref: solana.py Github
4
4
77,820,120
2024-1-15
https://stackoverflow.com/questions/77820120/numpy-filter-data-based-on-multiple-conditions
Here's my question: I'm trying to filter an image based on the values of two coordinates. I can do this easily with a for loop: import numpy as np import matplotlib.pyplot as plt x = np.linspace(-1, 1, 101) y = np.linspace(-1, 1, 51) X, Y = np.meshgrid(x, y) Z = np.exp(X**2 + Y**2) newZ = np.zeros(Z.shape) for i, y_i i...
Edit, you have to use numpy broadcasting: m = (y[:, None] > 0) | (x > 0) newZ = np.where(m, Z, 0) # OR m = (y[:, None] > 0) | (x > 0) newZ = np.zeros(Z.shape) newZ[m] = Z[m] Demo: x = np.linspace(-1, 1, 11) y = np.linspace(-1, 1, 6) Z = np.arange(len(y)*len(x)).reshape(len(y), len(x)) m = (y[:, None] > 0) | (x > 0) ne...
2
2
77,821,018
2024-1-15
https://stackoverflow.com/questions/77821018/stackable-traits-in-python
I am implementing a hierarchy of classes in Python. The common base class exposes a few methods like an interface, there are a few abstract classes that should not be instantiated directly and each of the concrete subclasses can mixin a few of the abstract classes and provide additional behaviour. For example, the foll...
Congratulations! You've discovered when not to use inheritance. Inheritance is a very specific tool in a programmer's toolbelt that solves a very specific problem, but there are lots of poor tutorials and poor instructors out there that try to hammer every nail in the software development world with subclasses. What yo...
2
3
77,820,136
2024-1-15
https://stackoverflow.com/questions/77820136/pandas-to-datetime-is-off-by-one-hour
I have some data recorded with timestamps using time.time(). I want to evaluate the data using pandas and convert the timestamps to datetime objects for better handling. However, when I try, all my timing data is off by one hour. This example reproduces the issue on my machine: import datetime as dt import pandas as pd...
You can use tz_convert to shift your datetime: >>> pd.to_datetime(timestamps, unit='s', utc=True).tz_convert('Europe/Paris') DatetimeIndex(['2024-01-15 00:00:00+01:00', '2024-01-15 01:00:00+01:00', '2024-01-15 02:00:00+01:00', '2024-01-15 03:00:00+01:00', '2024-01-15 04:00:00+01:00', '2024-01-15 05:00:00+01:00', '2024-...
3
2
77,817,609
2024-1-15
https://stackoverflow.com/questions/77817609/cloud-function-cant-call-postgresql-multiple-times-at-once-unless-test-queries
Edit: The answer to this was a bit complicated. The tl;dr is make sure you do Lazy Loading properly; many of the variables declared in the code below were declared and set globally, but your global variables should be set to None and only changed in your actual API call! I'm going bonkers. Here is my full main.py. It ...
Please see this other SO post for the proper detailed usage of the Cloud SQL Python Connector with Cloud Functions. The reason for the error here has to do with initializing the Connector as a global var outside of the Cloud Function request context. Cloud Functions only have access to compute and resources when reques...
2
3
77,819,377
2024-1-15
https://stackoverflow.com/questions/77819377/attributeerror-module-streamlit-has-no-attribute-chat-input
I'm trying to run a simple Streamlit app in my conda env. When I'm running the following app.py file: # Streamlit app import streamlit as st # prompt = st.chat_input("Say something") if prompt: st.write(f"User has sent the following prompt: {prompt}") It returns the following error when running streamlit run app.py: T...
Create a new virtual environment: python -m venv venv Activate the virtual environment : source venv/bin/activate Then install streamlit: pip install streamlit Then you can run your app: streamlit run app.py That way you can make sure that you are using the right version of streamlit. You can use conda to manage ma...
2
2
77,819,360
2024-1-15
https://stackoverflow.com/questions/77819360/python-pandas-select-rows-that-match-more-than-one-condition-on-group
Given the sample data: data = [['john', 'test_1', pd.NA], ['john', 'test_2', 'fail'], ['john', 'test_3', 'fail'], ['mary', 'test_1', pd.NA], ['mary', 'test_2', 'fail'], ['mary', 'test_3', pd.NA], ['nick', 'test_1', pd.NA], ['liam', 'test_1', pd.NA], ['liam', 'test_2', pd.NA], ['jane', 'test_1', pd.NA], ['jane', 'test_2...
Determine who failed the test with boolean indexing and drop them with another boolean indexing and isin: # identify which names failed "test_2" drop = df.loc[df['test'].eq('test_2') & df['result'].eq('fail'), 'name'].unique() # ['john', 'mary'] # select the other names out = df[~df['name'].isin(drop)] You code was in...
3
2
77,818,764
2024-1-15
https://stackoverflow.com/questions/77818764/how-can-i-select-all-dataframe-entries-between-two-times-when-the-time-is-a-ser
Here's some data: my_dataframe = pd.DataFrame({'time': ["2024-1-1 09:00:00", "2024-1-1 15:00:00", "2024-1-1 21:00:00", "2024-1-2 09:00:00", "2024-1-2 15:00:00", "2024-1-2 21:00:00"], 'assists': [5, 7, 7, 9, 12, 9], 'rebounds': [11, 8, 10, 6, 6, 5], 'blocks': [4, 7, 7, 6, 5, 8]}) I want to select all data between noon...
You could convert your Series (converted to_datetime) to a DatetimeIndex to use DatetimeIndex.indexer_between_time to get the positions of the matching rows, and iloc to select them: keep = (pd.DatetimeIndex(pd.to_datetime(my_dataframe['time'])) .indexer_between_time('12:00', '22:00') ) # array([1, 2, 4, 5]) out = my_d...
2
2
77,818,180
2024-1-15
https://stackoverflow.com/questions/77818180/is-it-pythonic-to-use-a-shallow-copy-to-update-an-objects-attribute
I found this code in the wild (simplified here), and I was wondering whether this is considered a good practice or not, that is, making a shallow copy (of an object's attribute in this case) for the sole purpose of updating the attribute (and reduce verbosity?). I ask because it is not the first time I see this kind of...
There is no copy of any kind, shallow or otherwise, made in your example. points = self.raw_points means points is self.raw_points. It makes the name points an additional reference to the same object that self.raw_points refers to, so that: points.append(Points(x,y)) is functionally equivalent to: self.raw_points.appe...
2
5
77,792,759
2024-1-10
https://stackoverflow.com/questions/77792759/how-to-rotatescale-pdf-pages-around-the-center-with-pypdf
I would like to rotate PDF pages around the center (other than just multiples of 90°) in a PDF document and optionally scale them to fit into the original page. Here on StackOverflow, I found a few similar questions, however, mostly about the outdated PyPDF2. And in the latest pypdf documentation, I could not find (or ...
It took me some time to figure out how to rotate a page around the center and scale it to fit the original page. Although, it just requires a matrix with the correct elements at the right place and some trigonometric functions, it was not too obvious for me. Hence, I post the script I ended up with for my own memories ...
2
1
77,813,766
2024-1-14
https://stackoverflow.com/questions/77813766/how-does-range-allocate-memory-in-python-3
I'm a beginner programmer, and I took a class in C and got (what I believe and hope to be) a really good understanding of how different functions and data types allocate memory differently. So, with that in mind, could someone explain how range() in Python uses memory, please? I know range() in Python 2 would create a ...
The Python 3 range() object does not allocate memory by creating it (other than the heap memory allocated by itself object, of course); it is a sequence object. All it contains is the start, stop and step values. It 'generates' numbers on demand, in this case, the 'demand' is the loop for n in range(6):. As you 'iterat...
5
2
77,790,822
2024-1-10
https://stackoverflow.com/questions/77790822/having-relevant-so-and-binaries-inside-the-venv
I installed OpenCV using Anaconda, with the following command. mamba create -n opencv -c conda-forge opencv matplotlib I know that the installation is fully functional because the below works: import cv2 c = cv2.imread("microphone.png") cv2.imwrite("microphone.jpg",c) import os os.getpid() # returns 13249 Now I try t...
You need pkg-config to also be in the env. The following should work: mamba create -n opencv -c conda-forge opencv matplotlib pkg-config mamba activate opencv g++ opencv_test.cpp `pkg-config --cflags --libs opencv4`
2
2
77,814,530
2024-1-14
https://stackoverflow.com/questions/77814530/is-there-a-way-to-get-hotspot-information-from-cur-file-using-pyqt
I am working on a PyQt application and one of the functions is to change the cursor style when user opens the app. It is easy to make this work, the only problem is the hotspot information is default to half of the image's width and height and there is not a certainty that all cursor image have their hotspot info just ...
When creating the cursor via QPixmap, any hotspot information in the file will be lost, since Qt will treat it as an ICO image (which has an almost identical format). The QCursor.hotSpot() method can only ever return the values you supply in the constructor - or a generic default calculated as roughly width [or height]...
2
3
77,815,755
2024-1-14
https://stackoverflow.com/questions/77815755/modifying-element-with-index-in-python
I am a beginner in Python. I am learning currently how to Modify an element with index MyCode: data = [4, 6, 8] for index, value in enumerate(data): data[index] = data[index] + 1 value = value * 2 print(data) print(value) Terminal Output: [5, 7, 9] 16 Terminal Output Expectation: [5, 7, 9] [8, 12, 16] Why didn’t I g...
If your list is empty you can't access it with an index. Use append method to add new elements: data = [4, 6, 8] empty_list = [] for index, value in enumerate(data): data[index] = data[index] + 1 value = value * 2 empty_list.append(value) print(data) print(empty_list) Output: [5, 7, 9] [8, 12, 16]
2
1
77,812,049
2024-1-13
https://stackoverflow.com/questions/77812049/openai-api-error-choice-object-has-no-attribute-text
I created a Python bot a few months ago, and it worked perfectly, but now, after the OpenAI SDK update, I have some problems with it. As I don't know Python very well, I need your help. This is the code: from openai import OpenAI import time import os import csv import logging # Your OpenAI API key api_key = "MY-API-KE...
You're trying to extract the response incorrectly. Change this... choices = response.choices chat_completion = choices[0] content = chat_completion.text # Wrong (this works with the Completions API) ...to this. choices = response.choices chat_completion = choices[0] content = chat_completion.message.content # Correct ...
2
3
77,813,986
2024-1-14
https://stackoverflow.com/questions/77813986/string-replace-replacing-all-occurences
I'm trying to make string.replace replace all words except ones starting with a certain character, e.g. ~, but if i have a word with only one letter, that letter gets deleted from the words i want to stay Code import re st1 = "dolphin fish ~shark eel octopus ~squid a" for i in re.findall(r"\b(?<!~)\w+", st1): st1 = st1...
I would actually suggest using a regex find all approach here: st1 = "dolphin fish ~shark eel octopus ~squid a" matches = re.findall(r'~\w+', st1) output = " ".join(matches) print(output) # ~shark ~squid
2
2
77,810,920
2024-1-13
https://stackoverflow.com/questions/77810920/how-to-find-pair-of-subarrays-with-maximal-sum
Given an array of integers, I can find the maximal subarray sum using Kadane's algorithm. In code this looks like: def kadane(arr, n): # initialize subarray_sum, max_subarray_sum and subarray_sum = 0 max_subarray_sum = np.int32(-2**31) # Just some initial value to check # for all negative values case finish = -1 # loca...
Kadane's algorithm is used to find the maximal subarray sum in an array of integers. However, to find the maximal pair of non-overlapping subarrays with maximal sum, a different approach is needed. One way to solve this is by using the concept of prefix and suffix sums. Here's a high-level overview of the algorithm: C...
2
2
77,812,803
2024-1-13
https://stackoverflow.com/questions/77812803/efficient-rendering-optimization-in-ray-tracing-avoiding-full-scene-rendering
I'm currently working on a ray tracing project using Python and have encountered performance issues with rendering the entire scene each time. I want to implement a more efficient rendering approach similar to how Unreal Engine handles it. Specifically, I'm looking for guidance on implementing the following optimizatio...
To 1: Frustum culling does not make sense in ray tracing. Frustum culling makes sense for rasterization. Rasterization is a top down approach: For instance you want to render cube. In rasterization you say in a top down approach - to render a cube I just must render it faces. To render a face (quad) of a cube you you j...
2
1
77,810,699
2024-1-13
https://stackoverflow.com/questions/77810699/can-numpy-replace-these-list-comprehensions-to-make-it-run-faster
Can this matrix math be done faster? I'm using Python to render 3D points in perspective. Speed is important, because it will translate directly to frame rate at some point down the line. I tried to use NumPy functions, but I couldn't clear out two pesky list comprehensions. 90% of my program's runtime is during the li...
An intial speedup can be made by using vectorization def render_all_verts(vert_array): """ :param vert_array: a 2-dimensional numpy array of float32 values and size 3 x n, formatted as follows, where each row represents one vertex's coordinates in world-space coordinates: [[vert_x_1, vert_y_1, vert_z_1], [vert_x_2, ve...
2
1
77,812,375
2024-1-13
https://stackoverflow.com/questions/77812375/pytorch-error-on-mps-apple-silicon-metal
When I use PyTorch on the CPU, it works fine. When I try to use the mps device it fails. I'm using miniconda for osx-arm64, and I've tried both python 3.8 and 3.11 and both the stable and nightly PyTorch installs. According to the website (https://pytorch.org/get-started/locally/) mps acceleration is available now with...
Jupyter was using the old kernel (the dev one) even though I switched interpreters. Restarting Jupyter with the new anaconda environment (python 3.8 and the release version of PyTorch) works.
2
1
77,811,790
2024-1-13
https://stackoverflow.com/questions/77811790/what-is-the-role-of-base-class-used-in-the-built-in-module-unittest-mock
While having deep dive into how the built-in unittest.mock was designed, I run into these lines in the official source code of mock.py: class Base(object): _mock_return_value = DEFAULT _mock_side_effect = None def __init__(self, /, *args, **kwargs): pass class NonCallableMock(Base): ... # and later in the init def _ini...
It's for multiple inheritance, which unittest.mock uses for classes like class MagicMock(MagicMixin, Mock):. Despite the name, super doesn't mean "call the superclass method". Instead, it finds the next method implementation in a type's method resolution order, which might not come from a parent of the current class wh...
2
3
77,811,473
2024-1-13
https://stackoverflow.com/questions/77811473/how-to-draw-a-arc-in-a-surface
i want to draw a semicircle inside a surface. So i thought to use pygame.draw.arc() but i cant figure out how to draw the arc inside of a surface i have seen the official_docs and am using math.radians() to convert degrees to radians but i cant see the arc. A circle is being drawn tho... import pygame import math pygam...
The position of the circle segment must of course be relative to the Surface on which the circle segment is drawn and not the absolute position on which the Surface is then placed on the screen: pygame.draw.arc(surf, (255, 255, 255), rect, math.radians(270), math.radians(90)) pygame.draw.arc(surf, (255, 255, 255), (0, ...
5
3
77,809,700
2024-1-12
https://stackoverflow.com/questions/77809700/should-name-mangling-be-used-in-classes-that-are-inherited-by-other-subclasses
I'm trying to create classes and subclasses in python with "protected" attributes using name mangling (__). However, when I try to extend the functionality of classes further with different subclasses, I get errors. So when is the appropriate time to use name mangling when the expectation is that both the parent class ...
The entire point of using double-underscore name-mangling is to prevent name collisions in subclasses. That's it. So this is precisely the behavior that is intended, what you have demonstrated is the canonical use case for double-underscore name mangling! Or to be a little more precise, it is to prevent accidental name...
2
4
77,808,706
2024-1-12
https://stackoverflow.com/questions/77808706/update-the-values-in-the-df-based-on-the-column-name
I have next pandas DataFrame: x_1 x_2 x_3 x_4 col_to_replace cor_factor 1 2 3 4 x_2 1 3 3 5 1 x_1 6 2 2 0 0 x_3 0 ... I want to update the column which name is saved in the col_to_replace with the value from cor_factor and save the result in the corresponded column and also in the car_factor column. Some (ugly) solut...
Use a pivot to correct the x_ values and an indexing lookup to correct the last column. Make sure to make a copy before modification since the values change: # perform indexing lookup # save the value for later idx, cols = pd.factorize(df['col_to_replace']) corr = df.reindex(cols, axis=1).to_numpy()[np.arange(len(df)),...
2
3
77,808,253
2024-1-12
https://stackoverflow.com/questions/77808253/how-to-replace-counter-to-use-numpy-code-only
I have this code: from collections import Counter import numpy as np def make_data(N): np.random.seed(40) g = np.random.randint(-3, 4, (N, N)) return g N = 100 g = make_data(N) n = g.shape[0] sum_dist = Counter() for i in range(n): for j in range(n): dist = i**2 + j**2 sum_dist[dist] += g[i, j] sorted_dists = sorted(su...
Can you just make sum_dist into an array, since you know its maximum index? sum_dist = np.zeros(2 * N * N, dtype=int) for i in range(n): for j in range(n): dist = i**2 + j**2 sum_dist[dist] += g[i, j] print(np.argmax(np.cumsum(sum_dist)))
6
5
77,808,235
2024-1-12
https://stackoverflow.com/questions/77808235/pandas-remove-characters-from-a-column-of-strings
I have a dataframe with a Date column consisting of stings in this format. I need to strip the end of the string so that I can convert to a datetime object. "20231101 05:00:00 America/New_York" "20231101 06:00:00 America/New_York" I have tried these approaches unsuccessfully. df['Date'] = df['Date'].replace('^.*\]\s*'...
If you want to remove a particular suffix, then I recommend str.removesuffix rather than str.strip. Notice that you sometimes write New_York with an underscore and sometimes NewYork without an underscore. If you ask to remove 'NewYork' then 'New_York' won't be removed. After the edit in your question, the suffixes all...
2
1
77,802,033
2024-1-11
https://stackoverflow.com/questions/77802033/c-program-and-subprocess
I wrote this simple C program to explain a more hard problem with the same characteristics. #include <stdio.h> int main(int argc, char *argv[]) { int n; while (1){ scanf("%d", &n); printf("%d\n", n); } return 0; } and it works as expected. I also wrote a subprocess script to interact with this program: from subprocess...
Change these: Send a separator between the numbers read by the C program. scanf(3) accepts any non-digit byte as separator. For easiest buffering, send a newline (e.g. .write(b'42\n')) from Python. Without a separator, scanf(3) will wait for more digits indefinitely. After each write (both in C and Python), flush the...
4
2
77,807,818
2024-1-12
https://stackoverflow.com/questions/77807818/trouble-updating-a-rectangle-using-a-custom-property-in-pygame
I am debugging one of my programs where I am trying to assign a custom variable to a rectangle to update it's position. Here is my code: import os ; os.environ['PYGAME_HIDE_SUPPORT_PROMPT']='False' import pygame, random pygame.init() display = pygame.display.set_mode((401, 401)) display.fill("white") ; pygame.display.f...
You have to redraw the scene. You have to redraw the rectangle after it has been changed. Clear the display and draw the rectangle in the application loop: while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() ; exit() elif event.type == pygame.MOUSEBUTTONDOWN: if square.contains(pyga...
2
1
77,806,510
2024-1-12
https://stackoverflow.com/questions/77806510/can-i-use-pydantic-to-deserialize-a-union-type-without-creating-another-basemod
I want to deserialize some data into a union type like so: from pydantic import BaseModel, Field from typing import Annotated, Union, Literal class Foo(BaseModel): type: Literal["foo"] = "foo" x: int class Bar(BaseModel): type: Literal["bar"] = "bar" x: float Baz = Annotated[Union[Foo, Bar], Field(discriminator="type")...
You can use pydantic.TypeAdapter from pydantic import TypeAdapter model = TypeAdapter(Baz).validate_python(d)
7
6
77,802,979
2024-1-11
https://stackoverflow.com/questions/77802979/how-to-draw-a-horizontal-line-at-y-0-in-an-altair-line-chart
I'm creating a line chart using Altair. I have a DataFrame where my y-values move up and down around 0, and I'd like to add a phat line to mark y=0. Sounds easy enough, so I tried this: # Add a horizontal line at y=0 to clearly distinguish between positive and negative values. y_zero = alt.Chart().mark_rule().encode( y...
Using alt.datum instead of alt.value will draw the line at the data value 0, instead at a pixel value of 0. You can read more and see examples in the docs here https://altair-viz.github.io/user_guide/encodings/index.html#datum-and-value
3
2
77,802,627
2024-1-11
https://stackoverflow.com/questions/77802627/is-it-really-good-idea-to-use-asyncio-with-files
I've been reading and watching videos a lot about asyncio in python, but there's something I can't wrap my head around. I understand that asyncio is great when dealing with databases or http requests, because database management systems and http servers can handle multiple rapid requests, but... How can it be good for ...
I'm trying to write data to file, but the server will surly receive bursts of requests. So in a way I don't know how to handle this situation, and I fear the corruption of data. Yes, corruption could happen from time to time especially if you use aiofiles. If I'm not wrong it uses threads to achieve this. I think you...
2
2
77,801,556
2024-1-11
https://stackoverflow.com/questions/77801556/how-can-i-create-a-list-of-range-of-numbers-as-a-column-of-dataframe
My DataFrame is: import pandas as pd df = pd.DataFrame( { 'a': [20, 100], 'b': [2, 3], 'dir': ['long', 'short'] } ) Expected output: Creating column x: a b dir x 0 20 2 long [22, 24, 26] 1 100 3 short [97, 94, 91] Steps: x is a list with length of 3. a is starting point of x and b is step that a increases/decreases ...
If you want a vectorial approach with numpy # create 1 for long, else -1 d = np.where(df['dir'].eq('long'), 1, -1)[:,None] # convert a and b to numpy as a column vector a = df['a'].to_numpy()[:,None] b = df['b'].to_numpy()[:,None] # combine N = 3 x = np.arange(1, N+1) df['x'] = list(a + d*b*x) Output: a b dir x 0 20 ...
3
2
77,800,927
2024-1-11
https://stackoverflow.com/questions/77800927/how-to-combine-fixture-with-parametrize
I have comfortably been using @pytest.mark.parametrize() in many tests now. I have not, however, succeeded in combining it with @pytest.fixture() and I cannot find a question answering this issue. This example applies @pytest.fixture() succesfully (copied from another question that I cannot find anymore): import pytest...
One method is request.getfixturevalue: import pytest @pytest.fixture() def dict_used_by_many_tests(): return { "name": "Dionysia", "age": 28, "location": "Athens", } @pytest.fixture() def dict_used_by_some_tests(): return { "name": "Medusa, maybe?", "age": 2 << 32, "location": "Underworld?", } @pytest.mark.parametrize(...
2
4
77,796,639
2024-1-10
https://stackoverflow.com/questions/77796639/combining-two-dataframes-in-which-the-order-of-entries-dont-match
I have 2 dataframes called df and df2 ,a small example of both are shown below. I want to join the two into a combined dataframe by matching the entries of the dataFrame by the 'formula' column df2 with the 'filename' column of df1 since the order of entries in the 2 dataFrames are not the same. An example of the final...
Create a temporary column in first dataframe df and use merge: out = df2.merge( df.assign(formula=df["filename"].str.split(".").str[0]), on="formula" ).drop(columns="filename") print(out) Prints: formula nsites number jml_bp_mult_atom_rad jml_hfus_add_bp 0 Fe12Co4BN 8 139 170.11 45.13 1 Fe15CoBN 8 139 172.43 47.23 2 ...
2
3
77,794,386
2024-1-10
https://stackoverflow.com/questions/77794386/compute-the-max-sum-circular-area
I have an n by n matrix of integers and I want to find the circular area, with origin at the top left corner, with maximum sum. Consider the following grid with a circle imposed on it. This is made with: import matplotlib.pyplot as plt from matplotlib.patches import Circle import numpy as np plt.yticks(np.arange(0, 10...
Same O(n^2 log n) method as others: accumulate weight sums by distance, then compute cumulative sums. But in pure python which should be trivial to translate to C++. Also PyPy may run surprisingly fast. from collections import Counter g = [[-3, 2, 2], [ 2, 0, 3], [-1, -2, 0]] n = 3 sum_dist = Counter() for i in range(n...
2
1
77,795,362
2024-1-10
https://stackoverflow.com/questions/77795362/how-to-migrate-from-typing-typealias-to-type-statements
I have created a type alias for defining member variables in a dataclass through type annotations: >>> from typing import TypeAlias >>> Number: TypeAlias = int | float >>> n, x = 1, 2.5 >>> isinstance(n, Number) True >>> isinstance(x, Number) True According to the docs, this syntax has been deprecated: Deprecated sin...
If you need to use isinstance with the new syntax, you need to access the type alias's value (and force its evaluation) explicitly, through the __value__ attribute: isinstance(n, Number.__value__) Of course, this will only work if the value of the alias is compatible with isinstance, which rules out stuff like NewType...
2
5
77,794,522
2024-1-10
https://stackoverflow.com/questions/77794522/how-to-reformat-a-big-csv-file-putting-a-newline-every-9-delimiter
I have a big csv file of data delimited by ";" stored in one only huge row. The first 9 fields separated by a semicolon are the columns name of the entire set. With Python, how could I reformat this csv file rewriting it and adding a newline every 9 fields for a correct import in Excel or Calc? Should I import csv or p...
Here's a quick regex hack that could do the job. This assumes that there are no quoted semicolons in the values: import re csv = "a;b;c;d;e;f;g;h;i;1;2;3;4;5;6;7;8;9;1;2;3;4;5;6;7;8;9;" wrapped = re.sub(r"((?:[^;]*;){9})", r"\1\n", csv) print(wrapped) This outputs: a;b;c;d;e;f;g;h;i; 1;2;3;4;5;6;7;8;9; 1;2;3;4;5;6;7;8...
2
2
77,792,596
2024-1-10
https://stackoverflow.com/questions/77792596/subsequent-if-statement-shorter-ways-to-assign-values-to-parameters-based-on-an
I want to create an array in which the values depends on one variables and two coefficients. The coefficient values depend on the variable value as well. A simple example: x_intervals = [2, 10] C1_values = [0.1, 0.5, -0.2] C2_values = [0.4,0.6, -0.8] Here I want C1 and C2: to be equal to the first array element if x<...
It would make a lot of sense to use numpy here. What you want is a searchsorted on x_intervals, then a vectorial operation: import numpy as np x_intervals = np.array([2, 10]) C1_values = np.array([0.1, 0.5, -0.2]) C2_values = np.array([0.4,0.6, -0.8]) x = [0.1,1,1.5,2.2,5,9,12,20,30,60,70,100] idx = np.searchsorted(x_i...
2
1
77,792,098
2024-1-10
https://stackoverflow.com/questions/77792098/average-day-of-a-month-on-minute-precision
I have data with datetime index using minute resolution. I want to see what is the average 'profile' of one day in a month using minute resolution. The dataset format is like this: Power 2019-01-01 11:43:01+02:00 9.223261 2019-01-01 11:44:01+02:00 14.304057 2019-01-01 11:45:01+02:00 28.678970 2019-01-01 11:46:01+02:00...
You should use resample with the desired frequency. If you want to plot an average day of the month, you can transform all days to the end of month (with pd.offsets.MonthEnd), then resample: (df_jul.set_axis(df_jul.index + pd.offsets.MonthEnd(0)) .resample('2min')['Power'].mean() .plot(marker='o') ) Or with a variant ...
2
4
77,790,923
2024-1-10
https://stackoverflow.com/questions/77790923/should-i-write-jupyter-server-or-jupyter-server-when-using-pip-install
When pip installing the jupyter server package, it seems that pip install jupyter_server and pip install jupyter-server do the same thing. Is that right? Why are the package names with underscore and hyphen both OK? The same goes to jupyter_client and jupyter-client.
Pip replaces underscore with dash by default, so you always install the same package (jupyter-server).
2
2
77,790,846
2024-1-10
https://stackoverflow.com/questions/77790846/finding-the-maximum-value-between-two-columns-where-one-of-them-is-shifted
My DataFrame is: import pandas as pd df = pd.DataFrame( { 'a': [20, 9, 31, 40], 'b': [1, 10, 17, 30], } ) Expected output: Creating column c a b c 0 20 1 20 1 9 10 20 2 31 17 17 3 40 30 31 Steps: c is the maximum value between df.b and df.a.shift(1).bfill(). My attempt: df['temp'] = df.a.shift(1).bfill() df['c'] = ...
If you don't want the temporary column, then you can replace values on the shifted column using where() in a one-liner. df['c'] = df['a'].shift(1).bfill().where(lambda x: x>df['b'], df['b']) This is similar to the combine() method posted in the other answer, but this one does a vectorized comparison while, combine() d...
2
1
77,790,217
2024-1-9
https://stackoverflow.com/questions/77790217/filter-for-specific-sequences-involving-multiple-columns-and-surrounding-rows
I have data that looks like this: It's standard financial price data (open, high, low, close). In addition, I run some calculations. 'major_check' occasionally returns 1 or 2 (which 'minor_check' will then also return). 'minor_check' also returns 1 or 2, but more frequently. the rest is filled with 0 or NaN. I'd like ...
As this answer by Timeless looked surprisingly complex, here is a quite simpler one. Method: Temporarily remove rows that are empty of test results (effectively skipping NaN and None), Search for patterns either with numpy.where and pandas.shift to check for patterns row-wise (faster), or preferrably with pandas.roll...
4
1
77,752,443
2024-1-3
https://stackoverflow.com/questions/77752443/abstractapp-call-missing-1-required-positional-argument-send-connexion
Recently upgraded from connexion version 2 to version 3. Based on official documents in https://connexion.readthedocs.io/en/latest/index.html major change in architecture happend. my problem: when using zappa to deploy python lambda function in aws, this general error Error: Warning! Status check on the deployed lambda...
Connexion 3 migrated from the WSGI to the ASGI interface, which does not seem to be supported by Zappa. You can either use an adapter middleware to run Connexion through WSGI (docs) or switch to a Zappa alternative like Magnum which supports ASGI.
3
1
77,781,734
2024-1-8
https://stackoverflow.com/questions/77781734/sagemaker-batch-transformer-with-my-own-pre-trained-model
I'm trying to run inference on demand for yolo-nas using sagemaker batch transformer. Using pre trained model with pre trained weights. But I am getting this error: python3: can't open file '//serve': [Errno 2] No such file or directory I have no idea what this '//serve' is. I have no ref or use of it at all, and can...
Sagemaker batch inference and endpoints work in same way. They are expecting web server with get[ping] and post[invocations] to start working. The thing is, when sagemaker runs, he is running a file named "serve" which was missing in my case. To be clear, as far as i understood. "my case" is when we dont use estimator ...
2
0
77,763,904
2024-1-5
https://stackoverflow.com/questions/77763904/runtimeerror-event-loop-is-closed-when-using-unit-isolatedasynciotestcase-to
Consider this mcve: requirements.txt: fastapi httpx motor pydantic[email] python-bsonjs uvicorn==0.24.0 main.py: import asyncio import unittest from typing import Optional import motor.motor_asyncio from bson import ObjectId from fastapi import APIRouter, Body, FastAPI, HTTPException, Request, status from fastapi.test...
From what I understand from your question, you are also facing issues while running FastAPI. To solve the unit test issue, try creating a test_app.py file in your directory and paste the following code: import asyncio import unittest from fastapi.testclient import TestClient from abhyas import app class TestAsync(unitt...
2
1
77,785,399
2024-1-9
https://stackoverflow.com/questions/77785399/show-a-wolfram-mathematica-plot-from-within-python
I need to show a plot created by the Wolfram Mathematica application used from within a Python script. So far I have written the following code, but I do not know how I should show the information stored in the wlplot variable. Is it even possible in Python? The plot.txt file contains the command I need. I checked that...
The working code follows. from PIL import Image png_export = wl.Export(path,wlplot,"PNG") session.evaluate(png_export) img = Image.open(path) img.show()
4
1
77,768,273
2024-1-6
https://stackoverflow.com/questions/77768273/instaloader-json-query-to-explore-tags-hashtag-404-not-found
I am constantly getting an error where when I try to scrape posts from a specific hashtag using instaloader, I am getting the error: JSON Query to explore/tags/hashtag/: 404 Not Found Here is my script: from itertools import islice import instaloader username = '' password = '' hashtag = 'food' L = instaloader.Instaloa...
Seems like instagram has temporarily blocked your ip Address due to the unusual activity you'd need to change your address or use a quality VPN.
3
-1
77,756,336
2024-1-4
https://stackoverflow.com/questions/77756336/better-way-to-access-a-nested-foreign-key-field-in-django
Consider the following models class A(models.Model): id field1 field2 class B(models.Model): id field3 field_a (foreign_key to Class A) class C(models.model): id field4 field5 field_b (foreign_key to Class B) @property def nested_field(self): return self.field_b.field_a Now here that property in class C, would trigger...
Turning my comments into an answer: select_related() is one of the go-to tools. As you noticed, the model instance needs to have been fetched by a queryset that has made the appropriate call to select_related(). queryset = C.objects.select_related('b__a') obj = queryset.first() print(obj.nested_field) # Shouldn't cost ...
2
1
77,789,573
2024-1-9
https://stackoverflow.com/questions/77789573/vscode-pytest-discovers-but-wont-run
In VScode, pytests are discovered. Using a conda env and it is the selected Python:Interpreter. However, when I try to run one or all the tests, it just says "Finished running tests!". Can't get into debug. Doesn't give green checkmark or red x's. If I run pytest in the terminal, it works just fine. I have reinstalled ...
having the following in my .vscode/setting.json fixed the problem: { "python.testing.pytestEnabled": true, "python.testing.unittestEnabled": false, "python.testing.pytestArgs": [ "${workspaceFolder}", "--rootdir=${workspaceFolder}" ], }
2
1
77,788,310
2024-1-9
https://stackoverflow.com/questions/77788310/vs-code-jupyter-notebook-output-cell-word-wrapping-not-working
I'm selecting text data from an SFrame and printing it. The text is really long, and the cell gets a horizontal scrollbar to view it. I would like to have it wrap to a newline and fit in my window, not to have a horizontal scrollbar. I tried enabling/disabling the vscode command View: Toggle Word Wrap, but that didn't ...
Unfortunately, VS Code doesn't currently support word wrap in the output or terminal windows. You can try to use textwrap package manually. Add the following codes to your script: import textwrap wrapped_text = textwrap.fill(text, width=80) #text is the object which you want to print print(wrapped_text)
6
2
77,785,036
2024-1-9
https://stackoverflow.com/questions/77785036/iteratively-convert-an-arbitrary-depth-list-to-a-dict
The input has a pattern, every element in the list is a dict and has a fixed keys [{'key': 'a', 'children': [{'key': 'a1', 'children': [{'key': 'a11', 'children': []}]}]}, {'key': 'b', 'children': [{'key': 'b1', 'children': [{'key': 'b11', 'children': []}]}]},] expected output {'a': {'a1': {'a11': ''}}, 'b': {'b1': {'...
You can perform a breadth-first traversal with a queue instead: from collections import deque from operator import itemgetter def convert_tree(lst): tree = {} queue = deque([(lst, tree)]) while queue: entries, branch = queue.popleft() for key, children in map(itemgetter('key', 'children'), entries): if children: queue....
2
1
77,789,971
2024-1-9
https://stackoverflow.com/questions/77789971/convert-dataframe-from-datetimens-to-datetimeus
I'm trying to convert a column of my pandas dataframe from datetime['ns'] to datetime['us']. I've tried using astype but the column type doesn't seem to change. I need the type of the column itself to update due to some downstream libraries checking for a specific column type. >> data[column].dtype.name 'datetime64[ns]...
I can reproduce, the behaviour you describe, in 1.5.3. So, you're most likely using a similar version or at least older than (2.0.0). Why ? Backwards incompatible API changes : In past versions, when constructing a Series or DataFrame and passing a datetime64 or timedelta64 dtype with unsupported resolution (i.e. anyt...
2
1
77,776,128
2024-1-8
https://stackoverflow.com/questions/77776128/adding-submenu-to-a-qcombobox
How can I go about creating sub-menus in a QComboBox? I am currently using the default layout offered by the widget but this creates a lengthy pull-down list as seen in the attached image.
QComboBox normally uses a QListView as its popup. While it is possible to change it to a QTreeView by calling setView(), its result is sometimes cumbersome and often requires further adjustments to make it usable. Most importantly, the view will not use furhter popups, which can become an issue if the whole structure r...
2
0
77,786,853
2024-1-9
https://stackoverflow.com/questions/77786853/how-to-print-timedelta-consistently-i-e-formatted
I have this code that prints the time difference in milliseconds. #!/usr/bin/python import datetime import sys date1= datetime.datetime.strptime('20231107-08:52:53.539', '%Y%m%d-%H:%M:%S.%f') date2= datetime.datetime.strptime('20231107-08:52:53.537', '%Y%m%d-%H:%M:%S.%f') diff = date1-date2 sys.stdout.write(str(diff) +...
You can define the following formatting function: def format_diff(diff): sign = '-' if diff < datetime.timedelta(0) else '' seconds = abs(diff.total_seconds()) return f'{sign}{seconds//60//60:02.0f}:{seconds//60%60:02.0f}:{seconds%60:06.03f}' #!/usr/bin/python import datetime import sys date1= datetime.datetime.strpti...
2
1
77,786,441
2024-1-9
https://stackoverflow.com/questions/77786441/using-pd-cut-with-duplicate-bins-and-labels
I'm using pd.cut with the keyword argument duplicates='drop'. However, this gives errors when you combine it with the keyword argument labels. The question is similar to this question, but that ignores the label part. Does not work: pd.cut(pd.Series([0, 1, 2, 3, 4, 5]), bins=[0, 1, 1, 2]) Works: pd.cut(pd.Series([0, 1,...
No, the cut documentation is pretty clear, it only concerns the bins: duplicates {default ‘raise’, ‘drop’}, optional If bin edges are not unique, raise ValueError or drop non-uniques. Also, in any case the labels must be one value less than the bins, so dropping the labels based on the bins would be ambiguous. This w...
2
2
77,785,794
2024-1-9
https://stackoverflow.com/questions/77785794/importerror-cannot-import-name-checkpoint-from-ray-air
I'm trying to follow this tutorial to tune hyperparameters in PyTorch using Ray, copy-pasted everything but I get the following error: ImportError: cannot import name 'Checkpoint' from 'ray.air' from this line of import: from ray.air import Checkpoint I installed ray using pip install -U "ray[tune]" as suggested on t...
Try to install older version 2.7.0: pip install ray[tune]==2.7.0 Update : For the newest version the Ray AIR session is replaced with a Ray Train context object. You can import Checkpoint using : from ray.train import Checkpoint You need to adjust your code as follow: from ray import air, train # Ray Train methods an...
2
5
77,780,873
2024-1-8
https://stackoverflow.com/questions/77780873/removing-certain-end-standing-values-from-list-in-python
Is there an elegant Pythonic way to perform something like rstrip() on a list? Imagine, I have different lists: l1 = ['A', 'D', 'D'] l2 = ['A', 'D'] l3 = ['D', 'A', 'D', 'D'] l4 = ['A', 'D', 'B', 'D'] I need a function that will remove all end-standing 'D' elements from a given list (but not those that come before or ...
def remove_end_elements(mylist, myelement): while myelement in mylist[-1:]: mylist.pop() return mylist
5
1
77,785,263
2024-1-9
https://stackoverflow.com/questions/77785263/deprecating-a-function-that-is-being-replaced-with-a-property
I am refactoring parts of an API and wish to add deprecation warnings to parts that will eventually be removed. However I have stumbled into an issue where I would like to replace a function call with a property sharing a name. Is there a hack where I can support both calling the .length as a property and as a function...
One workaround is to make the property return a proxy object of a subtype of the value to be returned. The proxy object can then produce the warning when called: import warnings def warning_property(message, warning_type=DeprecationWarning): class _property(property): def __get__(self, obj, obj_type=None): value = supe...
4
4
77,766,048
2024-1-5
https://stackoverflow.com/questions/77766048/getting-a-very-simple-stablebaselines3-example-to-work
I tried to model the simplest coin flipping game where you have to predict if it is going to be a head. Sadly it won't run, given me: Using cpu device Traceback (most recent call last): File "/home/user/python/simplegame.py", line 40, in <module> model.learn(total_timesteps=10000) File "/home/user/python/mypython3.10/l...
The gymnasium.Env class has the following signature which divers from the one by DummyVecEnv which takes no arguments. Env.reset(self, *, seed: int | None = None, options: dict[str, Any] | None = None) → tuple[ObsType, dict[str, Any]] in other words seed and options are keyword-only which your own reset function needs ...
2
1
77,767,421
2024-1-5
https://stackoverflow.com/questions/77767421/plot-an-bended-arrow-in-matploblib-with-gradient-color-from-head-to-tail
I am trying to plot an arrow in Matplotlib as shown in the following picture. The arrow's color changes gradually from black to blue from the tail to the head. I searched the existing answers, and I found a few relevant posts: Using Colormap with Annotate Arrow in Matplotlib, Matplotlib: How to get a colour-gradient as...
Plotting multiple overlapping arrows of different lengths and colors might work. You can adjust their length by changing the tail shrinking factors like this: import matplotlib.pyplot as plt import matplotlib.cm as cm from matplotlib.colors import LinearSegmentedColormap, ListedColormap import numpy as np def annotatio...
2
1
77,775,267
2024-1-7
https://stackoverflow.com/questions/77775267/combine-argparse-metavartypehelpformatter-argparse-argumentdefaultshelpformatte
I want to display default values, argument type, and big spacing for --help. But if I do import argparse class F(argparse.MetavarTypeHelpFormatter, argparse.ArgumentDefaultsHelpFormatter, lambda prog: argparse.HelpFormatter(prog, max_help_position = 52)): pass parser = argparse.ArgumentParser( prog = 'junk', formatter_...
Separating the lambda part works In [122]: class F(argparse.MetavarTypeHelpFormatter, argparse.ArgumentDefaultsHelpFormatter): pass ...: F1 = lambda prog: F(prog, max_help_position=52) ...: parser = argparse.ArgumentParser( ...: prog = 'junk', ...: formatter_class = F1) In [123]: parser.print_help() usage: junk [-h] op...
3
2
77,774,217
2024-1-7
https://stackoverflow.com/questions/77774217/how-to-extract-several-rotated-shapes-from-an-image
I had taken an online visual IQ test, in it a lot of questions are like the following: The addresses of the images are: [f"https://www.idrlabs.com/static/i/eysenck-iq/en/{i}.png" for i in range(1, 51)] In these images there are several shapes that are almost identical and of nearly the same size. Most of these shap...
This is my take on the problem. It basically involves working with the contour themselves, instead of the actual raster images. Use the Hu moments as shape descriptors, you can compute moments on the array of points directly. Get two vector/arrays: One "objective/reference" contour and compare it amongst the "target" c...
4
5
77,770,099
2024-1-6
https://stackoverflow.com/questions/77770099/pairwise-conditional-averages-in-pandas
Consider the following table. All are to be considered boolean except days_old and SKU which are to be considered integer pd.DataFrame({ 'SKU': [10,11,12,13,14,15], 'frozen':[1,0,1,1,1,0], 'vegetable':[1,1,0,1,1,0], 'microwaveable':[1,0,0,0,0,1], 'days_old':[21,9,11,2,6,14], }) I want a co-occurence table of counts th...
One option is to use dot: df2 = df[['frozen','vegetable','microwaveable']] df2.T.dot(df2.mul(df['days_old'],axis=0)).div(df2.T.dot(df2)).round(2) Output: frozen vegetable microwaveable frozen 10.00 9.67 21.0 vegetable 9.67 9.50 21.0 microwaveable 21.00 21.00 17.5
3
1
77,773,655
2024-1-7
https://stackoverflow.com/questions/77773655/prisoners-dilemma-strange-results
I tried to implement a prisoner's dilemma in Python, but my results, instead of showing that tit for tat is a better solution, it is showing that defecting is giving better results. Can someone look at my code, and tell me what I have done wrong here? import random from colorama import Fore, Style import numpy as np # ...
I think the problem lies in the setup of your tournament. It is set up in such a way that always_defect never has to play against always_defect. So a player of any type never plays against a player of the same type. It seems to be an advantage to be the only always_defect in the group. Modifying the lines for i in rang...
2
5
77,754,131
2024-1-3
https://stackoverflow.com/questions/77754131/macos-tkinter-app-terminating-invalid-parameter-not-satisfying-astring-ni
When im launching my app via CLI, it works without issue ./org_chart.app/Contents/MacOS/org_chart however when I launch via double click I met with the error *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid parameter not satisfying: aString != nil' I used py2app to b...
I suppose you use pyinstaller. It works for mac and it will compile an UNIX file. Just use pip install pyinstaller and after that in directory of your script pyinstaller -F main.py. Rename your file as main.py and it should compile one UNIX file. -F flag compiles it in one file. It works perfectly!
2
1
77,772,560
2024-1-7
https://stackoverflow.com/questions/77772560/merge-value-lists-of-two-dict-in-python
I have several dictionary with equal keys. The values of the key are list. Now I would merge the values lists like. Input, e.g.: dict_1 ={"a":["1"], "b":["3"]} dict_2 = {"a":["2"], "b":["3"]} Required output: new_dict = {'a':["1","2"], 'b':["3","3"]} What is the fastest, pythonic way to get this result? I found this,...
you can use defaultdict with extend like this: from collections import defaultdict new_dict = defaultdict(list) for d in [dict_1, dict_2]: for key, value in d.items(): new_dict[key].extend(value)
2
4
77,771,673
2024-1-7
https://stackoverflow.com/questions/77771673/merging-dataframe-columns-in-python
I have a special dataframe called df here is how it looks like RepID +Col01 +Col02 +Col03 -Col01 +Col04 +Col05 -Col03 -Col04 +Col06 -Col07 1 5 7 9 8 3 8 1 9 4 6 2 1 3 3 3 1 2 2 3 6 0 3 9 8 0 9 4 9 5 1 2 0 4 3 1 0 5 8 7 1 0 9 2 5 0 7 1 2 0 0 2 9 2 1 They are all positive numbers in the data but if you notice the column...
No need for groupby, just extract the + and - columns separately, subtract with fill_value=0, concat to the ID: out = pd.concat([df[['RepID']], df.filter(regex='^\+') .rename(columns=lambda x: x[1:]) .sub(df.filter(regex='^-') .rename(columns=lambda x: x[1:]), fill_value=0) ], axis=1) Output: RepID Col01 Col02 Col03 ...
4
2
77,766,228
2024-1-5
https://stackoverflow.com/questions/77766228/insert-a-column-with-a-conditional-function-into-a-dataframe
I want to calculate the difference between open and close price but taking to account if a trade is a Buy/Sell. I have the conditional function below; but l do not know how to insert a new column with the results into the original dataframe which has a list of trades and l am getting an error with this function. def pl...
I also found out that this solution also works: mt_trades["pl_gap"] = mt_trades.apply( lambda row: ( row["close_price"] - row["open_price"] if row["type"] == "BUY" else row["open_price"] - row["close_price"] ), axis=1, )
2
0
77,771,119
2024-1-6
https://stackoverflow.com/questions/77771119/gurobi-unsupported-operand-types-for-int-and-tupledict
I have this constraint with big-M parameter and an auxiliary binary variable w: for i in customers: for j in customers: if i != j: mdl.addConstr(y[j] + z[j] <= y[i] + z[i] - df.demand[j]*(x1[i,j] + x2[i,j]) + 100000 * (1 - w), name= 'C8') When I run the code, I got the following error: TypeError: unsupported operand t...
w is tupledict as it was defined using mdl.addVars. As w is a single variable you need to define it using mdl.addVar instead: w = mdl.addVar(0,1,vtype=GRB.BINARY, name='w')
2
4
77,769,625
2024-1-6
https://stackoverflow.com/questions/77769625/how-to-generate-a-standalone-swagger-ui-docs-page-for-each-endpoint-in-fastapi
Is there a way to generate each endpoint on its own page instead of generating the documentation for all of the endpoints on a single page like below: I would like to show, let's say, the GET endpoint for books on its own dedicated page without all the other endpoints. I want this because I am using an iframe tag to em...
You could achieve having separate Swagger UI (OpenAPI) autodocs generated by using Sub applications. In the following example, you could access the Swagger UI autodocs for the main API at http://127.0.0.1:8000/docs, and the docs for the sub API at http://127.0.0.1:8000/subapi/docs. Example from fastapi import FastAPI a...
2
1
77,766,938
2024-1-5
https://stackoverflow.com/questions/77766938/is-it-possible-to-build-a-tree-form-expanded-airflow-dag-tasks-dynamic-task-ma
I want to generate dynamic tasks from the dynamic task output. Each mapped task returns a list, and I'd like to create a separate mapped task for each of the element of the list so the process will look like this: Is it possible to expand on the output of the dynamically mapped task so it will result in a sequence of ...
You would need to add a task which collects and flattens the result of second. @task def first() -> list[str]: return ['1', '2'] @task def second(input: str) -> list[str]: return [f"{input}_{i}" for i in ['1', '2', '3']] @task def second_collect(input: list[list[str]]) -> list[str]: return list(chain.from_iterable(inpu...
2
4
77,756,723
2024-1-4
https://stackoverflow.com/questions/77756723/type-hints-for-class-decorator
I have a class decorator which removes one method and adds another to a class. How could I provide type hints for that? I've obviously tried to research this myself, to no avail. Most people claim this requires an intersection type. Is there any recommended solution? Something I'm missing? Example code: class MyProtoco...
There is no type annotation which can do what you want. Even with intersection types, there won't be a way to express the action of deleting an attribute - the best you can do is making an intersection with a type which overrides do_check with some kind of unusable descriptor. What you're asking for can be instead done...
2
2
77,767,405
2024-1-5
https://stackoverflow.com/questions/77767405/creating-a-new-column-when-values-in-another-column-is-not-duplicate
This is my DataFrame: import pandas as pd import numpy as np df = pd.DataFrame( { 'a': [98, 97, 100, 101, 103, 110, 108, 109, 130, 135], 'b': [3, 3, 3, 3, 3, 3, 3, 3, 3, 3], 'c': [np.nan, np.nan, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 3.0, 3.0], 'd': [92, 92, 92, 92, 92, 92, 92, 92, 92, 92], } ) And this is the expected output...
You can use duplicated, mask, grouby.ffill and fillna: # identify duplicated "c" m = df['c'].duplicated() # compute a-(2*b) # mask the duplicated "c" # ffill per group # replace NaN with "d" df['x'] = (df['a'].sub(df['b'] * 2) .mask(m) .groupby(df['c']).ffill() .fillna(df['d']) ) Variant to work by groups of successiv...
2
2
77,766,887
2024-1-5
https://stackoverflow.com/questions/77766887/merge-3-dataframes-with-different-timesteps-10min-and-15min-and-30min-using-pa
The goal is to merge three different dataframes having different timesteps (10min, 15min and 30min. The code must recognize what timestep to consider firstly and identify the next available next timestep. in This example 2019/04/02 10:40:00 does not exist in the dataframes dataset. Therefore the next timestep to consid...
# Convert Timestamp columns to datetime df1['Timestamp'] = pd.to_datetime(df1['Timestamp']) df2['Timestamp'] = pd.to_datetime(df2['Timestamp']) df3['Timestamp'] = pd.to_datetime(df3['Timestamp']) # Sort the DataFrames based on Timestamp df1 = df1.sort_values('Timestamp') df2 = df2.sort_values('Timestamp') df3 = df3.sor...
4
1
77,766,721
2024-1-5
https://stackoverflow.com/questions/77766721/dataframe-convert-the-columns-in-a-df-to-list-of-row-in-python-dataframe
I have a pandas dataframe like below id name value1 value2 value3 Type ======================================================= 1 AAA 1.0 1.5 1.8 NEW 2 BBB 2.0 2.3 2.5 NEW 3 CCC 3.0 3.6 3.7 NEW I have convert the above df into something like below so that i can join it to another df based on name (which will be unique ...
A possible solution, which first adds column value containing the list and then uses pivot: (df.assign(value=df.loc[:, 'value1':'value3'].apply(list, axis=1)) .pivot(index='Type', columns='name', values='value') .rename_axis(None, axis=1).reset_index()) Output: Type AAA BBB CCC 0 NEW [1.0, 1.5, 1.8] [2.0, 2.3, 2.5] [...
2
4
77,752,955
2024-1-3
https://stackoverflow.com/questions/77752955/dynamically-discounted-cumulative-sum-in-numpy
I have a frequently occurring problem where I have two arrays of the same length: one with values and one with dynamic decay factors; and wish to calculate a vector of the decayed cumulative sum at each position. Using a Python loop to express the desired recurrence we have the following: c = np.empty_like(x) c[0] = x[...
Mathematically speaking, this is a first-order non-homogeneous recurrence relation with variable coefficients. Please note that coefficients (in your case, values in d[1:]) must be different from 0. Here is a way to solve your recurrence relation using NumPy functions. Note that d[0] is supposed to be equal to 1 (your ...
3
1
77,765,051
2024-1-5
https://stackoverflow.com/questions/77765051/what-is-the-proper-replacement-for-scipy-interpolate-interp1d
The class scipy.interpolate.interp1d has a message that reads: Legacy This class is considered legacy and will no longer receive updates. This could also mean it will be removed in future SciPy versions. I'm not sure why this is marked for deprecation, but I use it heavily in my code to return an interpolating functi...
According to the documentation: interp1d is considered legacy API and is not recommended for use in new code. Consider using more specific interpolators instead. https://docs.scipy.org/doc/scipy/tutorial/interpolate/1D.html#legacy-interface-for-1-d-interpolation-interp1d it is asking to: Consider using more specific ...
6
1
77,764,733
2024-1-5
https://stackoverflow.com/questions/77764733/how-to-set-zorder-across-axis-in-matplotlib
I want to make a graph that contains bars, the value of the bars noted above them and a line on the secondary axis, but I can't configure the order of the elements the way I want where the bars would be the furthest element, followed by the line and then the texts, but so far I can only change the position of an entire...
Unfortunately respecting zorder across twinned axes is not possible. A workaround for annotations is to add them to the second axes, but using the data transform of the first. See the xycoords parameter added in the call to annotate here: import matplotlib.pyplot as plt years = [2019, 2020, 2021, 2022, 2023] values1 = ...
2
1
77,764,710
2024-1-5
https://stackoverflow.com/questions/77764710/how-to-set-multiple-values-in-a-pandas-dataframe-at-once
I have a large dataframe and a list of many locations I need to set to a certain value. Currently I'm iterating over the locations to set the values one by one: import pandas as pd import numpy as np #large dataframe column_names = np.array(range(100)) np.random.shuffle(column_names) row_names = np.array(range(100)) np...
You can access the underlying numpy array with .values and use the position indices after conversion: cols = pd.Series(range(df.shape[1]), index=df.columns) idx = pd.Series(range(df.shape[0]), index=df.index) df.values[idx.reindex(ix), cols.reindex(iy)] = 1 Minimal example: # input df = pd.DataFrame(index=['a', 'b', '...
2
2