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
75,593,863
2023-2-28
https://stackoverflow.com/questions/75593863/python-match-case-continue-to-match-next-case-even-matched
key: Literal['all', 'a', 'b'] = 'a' def do_a(): pass def do_b(): pass match key: case 'a': do_a() case 'b': do_b() case 'all': do_a() do_b() Is there any way to simplify the code so I can remove the case 'all'? Something like match key: case 'a' | 'all': do_a() case 'b' | 'all': do_b()
Example Setup: from typing import Literal key: Literal['all', 'a', 'b'] def do_a(): print('do_a') def do_b(): print('do_b') Solution I: You can just use if: if key in ('a', 'all'): do_a() if key in ('b', 'all'): do_b() Solution II: You could use a function mapper, like so: function_mapper = { 'all': (do_a, do_b), '...
3
2
75,587,316
2023-2-28
https://stackoverflow.com/questions/75587316/subtract-values-of-single-row-polars-frame-from-multiple-row-polars-frame
Lets say I have a polars dataframe like this in python newdata = pl.DataFrame({ 'A': [1, 2, 3, 4], 'B': [5, 6, 7, 8], 'C': [9, 10, 11, 12], 'D': [13, 14, 15, 16] }) And I want to subtract from every value in every column the corresponding value from another frame baseline = pl.DataFrame({ 'A': [1], 'B': [2], 'C': [3]...
Here loop by column names can be used: newdata.with_columns( [pl.col(c) - baseline[c] for c in newdata.columns] )
3
3
75,566,105
2023-2-25
https://stackoverflow.com/questions/75566105/authenticate-a-get-request-to-google-play-purchase-api-with-service-account-pyth
I need to verify purchases of my android App from my AWS lambda in python. I have seen many posts of how to do so and the documentation and here is the code I have written : url = f"{google_verify_purchase_endpoint}/{product_id}/tokens/{token}" response = requests.get(url=url) data = response.json() logging.info(f"Resp...
Pre-Requisites and Assumptions It looks like you have already set-up a service account but need a hand with obtaining a JSON Web Token (JWT) before going after the verify_purchase endpoint. Generating a JWT is documented here. You should read this to understand what the following code is doing. I note that you have a s...
5
2
75,563,361
2023-2-25
https://stackoverflow.com/questions/75563361/meaning-of-pop-style-stack-without-without-push-in-kivy
What does it mean when Kivy gives this warning message? What can cause it? [WARNING] [Label ] pop style stack without push
I don't see any documentation about this message specifically, but here's the relevant bit from the source code that handles BBCode-style text markup: def _pop_style(self, k): if k not in self._style_stack or len(self._style_stack[k]) == 0: Logger.warning('Label: pop style stack without push') return v = self._style_st...
3
3
75,584,837
2023-2-27
https://stackoverflow.com/questions/75584837/pass-returned-value-from-a-previous-python-operator-task-to-another-in-airflow
I am a new user to Apache Airflow. I am building a DAG like the following to schedule tasks: def add(): return 1 + 1 def multiply(a): return a * 999 dag_args = { 'owner': 'me', 'depends_on_past': False, 'start_date': datetime(2023, 2, 27), 'email': ['me@myhome.com'], 'email_on_failure': True, 'email_on_retry': True, 'r...
Your DAG can be simplified using taskflow API. It will handle the Xcom and simplify the code. import pendulum from airflow.decorators import dag, task @dag( schedule_interval=None, start_date=pendulum.datetime(2023, 1, 1, tz="UTC"), catchup=False, ) def taskflow_api_etl(): @task() def add(): return 1+1 @task() def mult...
3
3
75,583,768
2023-2-27
https://stackoverflow.com/questions/75583768/tell-pip-package-to-install-build-dependency-for-its-own-install-and-all-install
I am installing a package whose dependency needs to import numpy inside its setup.py. It also needs Cython to correctly build this dependency. This dependency is scikit-learn==0.21.2. Here is the setup.py of my own package called mypkgname: from setuptools import find_packages, setup import Cython # to check that Cytho...
For building packages pip uses build Isolation. I.e. it installs build dependencies into a separate virtual environment, build a package and remove the isolating venv. So build dependencies (in your case Cython and numpy) are removed along with the isolating venv. You can disable isolation but better and more correct w...
3
3
75,579,904
2023-2-27
https://stackoverflow.com/questions/75579904/mkdocs-with-auto-generated-references
I am building a TensorFlow model and have a ton of functions and modules that have proper docstrings. I installed mkdocs due to popular demand and the documentation does appear to be very easy to write. Nevertheless, I don't want to manually write up the entire API reference of all my modules inside this package. I am ...
The solution is described in this recipe for mkdocstrings: https://mkdocstrings.github.io/recipes/#automatic-code-reference-pages
3
4
75,581,571
2023-2-27
https://stackoverflow.com/questions/75581571/in-numpy-what-is-the-difference-between-calling-ma-masked-where-and-ma-masked-a
Calling masked_array (the class constructor) and the masked_where function both seem to do exactly the same thing, in terms of being able to construct a numpy masked array given the data and mask values. When would you use one or the other? >>> import numpy as np >>> import numpy.ma as MA >>> vals = np.array([0,1,2,3,4...
You comment: If I call them with inconsistently shaped value and masked arrays, I get the same error message in both cases. I don't think we can help you without more details on what's different. For example if I try the obvious inconsistency, that of length, I get different error messages: In [121]: np.ma.masked_arr...
3
2
75,572,878
2023-2-26
https://stackoverflow.com/questions/75572878/shading-regions-inside-an-mplfinance-chart
I am using matplotlib v 3.7.0, mplfinance version '0.12.9b7', and Python 3.10. I am trying to shade regions of a plot, and although my logic seems correct, the shaded areas are not being displayed on the plot. This is my code: import yfinance as yf import mplfinance as mpf import pandas as pd # Download the stock data ...
The problem is that, when show_nontrading=False (which is the default value when not specified) then the X-axis are not dates as you would expect. Thus the vertical lines and the fill_between that you are specifying by date are actually ending up way off the chart. The simplest solution is to set show_nontrading=True. ...
3
4
75,567,023
2023-2-25
https://stackoverflow.com/questions/75567023/descriptors-in-python-for-implementing-perls-tie-scalar-operation
I need some help with descriptors in python. I wrote an automatic translator from perl to python (Pythonizer) and I'm trying to implement tied scalars, which is basically an object that acts as a scalar, but has FETCH and STORE operations that are called appropriately. I'm using a dynamic class namespace 'main' to stor...
Ok - with your help, I was able to figure out how to do it. Basically I have to create a metaclass for my main, then use that class to store the initial object for tied scalars. Here is my updated code with changes marked # new: meta = type('mainmeta', (type,), { '__init__': lambda cls, name, bases, attrs: type.__init_...
5
1
75,570,820
2023-2-26
https://stackoverflow.com/questions/75570820/pynamodb-last-evaluated-key-always-return-null
I'm using Pynamodb for interacting with dynamodb. However, last_evaluated_key always returns null even if there are multiple items. When I run this query results = RecruiterProfileModel.profile_index.query( hash_key=UserEnum.RECRUITER, scan_index_forward=False, limit=1, ) If I try getting this value results.last_evalu...
The result returned by the query() is the ResultIterator object, which is an iterator. Its last_evaluated_key is the key of the last item you pulled from the iterator, not DynamoDB. Because your code have not yet asked to retrieve any items, the last_evaluated_key is not set. You need to process some or all of the item...
3
4
75,565,527
2023-2-25
https://stackoverflow.com/questions/75565527/how-to-efficiently-calculate-combinations-of-the-sum-of-two-lists-and-avoid-sel
I am not the best coder, but I am trying to figure out how to calculate the number of possible combinations and actually generate every combination, but with some rules. I have two sets of "things," primaries (P) and secondaries (S). In this case I have P = 16 and S = 7. So a valid combination needs at least one P valu...
Printing to a terminal is relatively slow. According to your rules, there will be 8,388,480 valid combinations. Writing the valid combinations to a file will be much faster than sending output to a terminal. Try this: from itertools import combinations from time import perf_counter OUTPUT_FILE = '/Volumes/G-Drive/combo...
3
1
75,556,221
2023-2-24
https://stackoverflow.com/questions/75556221/why-is-np-dot-so-much-faster-than-np-sum
Why is np.dot so much faster than np.sum? Following this answer we know that np.sum is slow and has faster alternatives. For example: In [20]: A = np.random.rand(1000) In [21]: B = np.random.rand(1000) In [22]: %timeit np.sum(A) 3.21 µs ± 270 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each) In [23]: %timeit...
This answer completes the good answer of @user2357112 by providing additional details. Both functions are optimized. That being said the pair-wise summation is generally a bit slower while providing generally a more accurate result. It is also sub-optimal yet though relatively good. OpenBLAS which is used by default on...
48
35
75,565,030
2023-2-25
https://stackoverflow.com/questions/75565030/does-python-allows-elif-statement-without-else-statement
While teaching python to a friend i tried this statement : val = "hi" if (val=="hello") or ("w" in val): print("hello") elif(val=="hi"): print("hi") And to my great surprise it worked. I always tought in Python you couldn't do an elif without else. Has it been always like that or the syntax has changed since a particu...
else is optional, and follows any number of elif statements. From the specification of version 1.6: if_stmt: "if" expression ":" suite ("elif" expression ":" suite)* ["else" ":" suite] The * in this syntax means zero or more elements, and [ and ] means an optional element. Python 1.6 was the first version released as ...
3
4
75,559,538
2023-2-24
https://stackoverflow.com/questions/75559538/third-clone-of-the-turtle
I made this program, when trying to make a chase game, but I stumbled along something really strange. I created a clone of the turtle, but at the middle of the map a third one appeared. Does anybody know what causes this? import turtle sc = turtle.Screen() t = turtle.Turtle() c = turtle.clone() c.penup t.penup c.goto(1...
Very good question. I'm able to reproduce the behavior: if you only make one turtle, print(len(turtle.turtles())) gives 1 as expected, but after cloning once, there's suddenly 3. Here's a minimal example: import turtle t = turtle.Turtle() print(len(turtle.turtles())) # => 1, no problem c = turtle.clone() print(len(turt...
3
3
75,553,212
2023-2-24
https://stackoverflow.com/questions/75553212/best-way-to-check-if-a-numpy-array-is-all-non-negative
This works, but not algorithmically optimal since I dont need the min value to be stored while the function is parsing the array: def is_non_negative(m): return np.min(m) >= 0 Edit: Depending on the data an optimal function could indeed save a lot because it will terminate at the first encounter of a negative value. I...
One pure-Numpy solution is to use a chunk based strategy: def is_non_negative(m): chunkSize = max(min(65536, m.size/8), 4096) # Auto-tunning for i in range(0, m.size, chunkSize): if np.min(m[i:i+chunkSize]) < 0: return False return True This solution is only efficient if the arrays are big, and chunks are big enough f...
3
2
75,561,461
2023-2-24
https://stackoverflow.com/questions/75561461/how-do-i-efficiently-perform-the-same-function-across-multiple-groups-of-columns
I am cleaning a csv for data analysis and I'm new to python, so I am trying my best to make this as straightforward as possible in case anyone wants to go back into this later. I want to perform a straightforward operation on four columns and add a new column with the result, then efficiently repeat that for 10 other s...
You can group columns by a suffix (here the first letter of column name) and compute your function: def difference(df): return df.iloc[:, :3].sum(numeric_only=True, axis=1) - (df.iloc[:, 3]) df1 = df.groupby(df.columns.str[0], axis=1).apply(difference).add_suffix('_diff') out = pd.concat([df, df1], axis=1) print(out) #...
3
2
75,559,543
2023-2-24
https://stackoverflow.com/questions/75559543/how-to-unpack-tuples-within-a-list-to-use-in-map
I'm just going to simplify my problem a bit. I have a function like this: def func(a,b): return a+b I also have a list of tuples which I would like to map to this function. num = [(0,4),(6,3),(2,2),(9,1)] I want to be able to map the tuples within the list like (a,b) to the function I provided. In javascript you coul...
map won't perform unpacking without writing a wrapper function to do that actual unpacking for you. That's why itertools.starmap exists: from itertools import starmap def func(a,b): return a+b num = [(0,4),(6,3),(2,2),(9,1)] for result in starmap(func, num): print(result) The name "starmap" is referring to the implici...
4
8
75,559,368
2023-2-24
https://stackoverflow.com/questions/75559368/getting-422-error-while-trying-to-use-coveralls-with-github-actions
I'm trying to set up Coveralls to work with GitHub Actions for a Python project, and although I've reviewed the documentation multiple times and followed all the instructions to the best of my understanding, I'm still facing the following error: Bad Response 422 {“message”: “Couldn’t find a repository matching this jo...
The documentation is not clear enough at this point: Name Requirement Description github-token required Must be in form github-token: ${{ secrets.GITHUB_TOKEN }}; Coveralls uses this token to verify the posted coverage data on the repo and create a new check based on the results. It is built into Github Action...
4
5
75,556,141
2023-2-24
https://stackoverflow.com/questions/75556141/error-modulenotfounderror-no-module-named-azure-keyvault-secrets-although-i-i
I have a Python script to retrieve username and password from Key Vault (Azure). 3 months ago it worked but now it gives me the error No module named 'azure.keyvault.secrets' when I run 'from azure.keyvault.secrets import SecretClient'. Why I get this error? It gives me error also if I try to run pip install azure!
Error ModuleNotFoundError: No module named 'azure.keyvault.secrets' although I installed the package: If you run pip install azure it won't work for azure.keyvaults module to be used in the code. You need to install or update with the latest version using pip command: pip install azure-keyvault-secrets //4.6.0 is the...
5
6
75,553,432
2023-2-24
https://stackoverflow.com/questions/75553432/cant-locate-popup-button-with-selenium
I have been trying to use selenium on a webpage but this popup is refraining me to do so. note that the popup is only shown when you are not signed in (means you have to run my code so that selenium opens up a new browser window for you which does not have any accounts) I want to click on the "Not Interested" button t...
The popup element is inside Shadow-root element you need to reach to shadow-root first then identify the button not interested shadowRoot= driver.execute_script('''return document.querySelector("div.airship-html-prompt-shadow").shadowRoot''') shadowRoot.find_element(By.CSS_SELECTOR,"button.airship-btn.airship-btn-deny"...
3
2
75,547,065
2023-2-23
https://stackoverflow.com/questions/75547065/how-to-check-if-feature-descriptors-and-matches-are-correct
I'm trying to find common over laps between two images and for this I am using a ORB feature detector and BEBLID feature descriptor. Using these features, find the homography between them and align the images. The function code is as follows: for pair in image_pairs: img1 = cv2.cvtColor(pair[0], cv2.COLOR_BGR2GRAY) img...
This thread and its two top answers are a useful resource for what you are doing: Detecting garbage homographies from findHomography in OpenCV? One of the things the selected answer suggests is to check the determinant of the homography matrix. Where negative determinants signals a "flipped image", while a very large o...
3
3
75,553,614
2023-2-24
https://stackoverflow.com/questions/75553614/tensorflow-the-channel-dimension-of-the-inputs-should-be-defined
I am new to Tensorflow, and am trying to train a specific deep learning neural network. I am using Tensorflow (2.11.0) to get a deep neural network model which is described below. The data which I use is also given below: Data: Here is some example data. For sake of ease we can consider 10 samples in data. Here, each s...
Define the input shape directly in the normalization layer (or add an Input layer), since it cannot be inferred directly: import numpy as np import tensorflow as tf x_train = np.random.rand(10, 128, 128, 1) normalizer = tf.keras.layers.Normalization(input_shape=[128, 128, 1], axis=-1) normalizer.adapt(x_train) def buil...
7
1
75,554,263
2023-2-24
https://stackoverflow.com/questions/75554263/beanie-exceptions-collectionwasnotinitialized-error
I'm new to the Beanie library which is an asynchronous Python object-document mapper (ODM) for MongoDB. Data models are based on Pydantic. I was trying this library with fastAPI framework, and made an ODM for some document, let's say it's name is SomeClass and then tried to insert some data in the db using this ODM. ...
As the error tells us, we should first Initialize the collection. We should initialize the collection via the init_beanie. I’ve used this function like this (in databse.py): from beanie import init_beanie import motor.motor_asyncio from someClass import SomeClassDao async def init_db(cls): MONGO_DB_DATABASE_NAME = "Som...
3
3
75,540,223
2023-2-23
https://stackoverflow.com/questions/75540223/how-to-sort-a-2d-numpy-object-array-based-on-a-list
I have a 2D numpy object array: aa = np.array([["aaa","05","1","a"], ["ccc","30","2","v"], ["ddd","50","2","v"], ["bbb","10","1","v"]]) and the following list: sample_ids = ["aaa", "bbb", "ccc", "ddd"] I would like to sort the numpy array based on the list so that I get the following: [["aaa","05","1","a"], ["bbb","1...
Here are a couple of possible solutions. Using numpy: subs = list(aa.T[0]) idxs = [subs.index(i) for i in sample_ids if i in subs] res = aa[idxs] # array([['aaa', '05', '1', 'a'], # ['bbb', '10', '1', 'v'], # ['ccc', '30', '2', 'v'], # ['ddd', '50', '2', 'v']], dtype='<U3') Using pandas: res = np.array(pd.DataFrame(aa...
3
2
75,550,639
2023-2-23
https://stackoverflow.com/questions/75550639/how-to-separate-strings-in-a-list-multiplied-by-a-number
I need to take a list, multiply every item by 4 and separate them by coma. My code is: conc = ['0.05 ml : 25 ml', '0.05 ml : 37.5 ml', '0.05 ml : 50 ml', '0.05 ml : 62.5 ml', '0.05 ml : 75 ml'] new_conc = [", ".join(i*4) for i in conc] print(new_conc) But when I run it, I get every SYMBOL separated by come. What I nee...
You can use a simple for loop. new_conc = [] for item in conc: new_conc.extend([item] * 4)
3
3
75,548,903
2023-2-23
https://stackoverflow.com/questions/75548903/how-to-make-snakemake-wildcard-work-for-empty-string
I expected Snakemake to allow wildcards to be empty strings, alas, this isn't the case. How can I make a wildcard accept an empty string?
Wildcards by default only match the regex .+ meaning everything but empty strings. This is unfortunately not documented beyond a Google group conversation. To make a wildcard accept empty strings, simply add a custom wildcard constraint wildcard_constraints: foo=".*", either within the scope of a rule or globally: # Op...
4
6
75,547,631
2023-2-23
https://stackoverflow.com/questions/75547631/overwrite-single-file-in-a-google-cloud-storage-bucket-via-python-code
I have a logs.txt file at certain location, in a Compute Engine VM Instance. I want to periodically backup (i.e. overwrite) logs.txt in a Google Cloud Storage bucket. Since logs.txt is the result of some preprocessing made inside a Python script, I want to also use that script to upload / copy that file, into the Googl...
It's because of if_generation_match As a special case, passing 0 as the value for if_generation_match makes the operation succeed only if there are no live versions of the blob. This is what is meant by the return message "At least one of the pre-conditions you specified did not hold." You should pass None or leave o...
7
8
75,545,370
2023-2-23
https://stackoverflow.com/questions/75545370/how-to-configure-the-entrypoint-cmd-for-docker-based-python3-lambda-functions
I switched from a zip-based deployment to a docker-based deployment of two lambda functions (which are used in an API Gateway). Both functions where in the same zip file and I want to have both functions in the same docker-based container (meaning I can't use the cmd setting in my Dockerfile (or to be precise need to o...
First, the container you deploy to AWS Lambda has to implement the Lambda Runtime Interface. AWS Lambda isn't a generic docker container runtime, it only supports running containers that implement a specific interface. The easiest way to ensure your container implements this interface is to base it on one of the AWS pr...
6
6
75,529,064
2023-2-22
https://stackoverflow.com/questions/75529064/how-to-load-multiple-partition-parquet-files-from-gcs-into-pandas-dataframe
I am trying to read multiple parquet files stored as partitions from google cloud storage and read them as 1 single pandas data frame. As an example, here is the folder structure at gs://path/to/storage/folder/ And inside each of the event_date=*, there are multiple parquet files So the directory structure is somethin...
Seems it is not possible for pandas to read multiple parquet files stored under a gcs path,There is a bug raised for this at github, which is still open further progress can be tracked there.
3
3
75,535,679
2023-2-22
https://stackoverflow.com/questions/75535679/implementation-of-adamw-is-deprecated-and-will-be-removed-in-a-future-version-u
How to fix this deprecated AdamW model? I tried to use the BERT model to perform a sentiment analysis on the hotel reviews, when I run this piece of code, it prompts the following warning. I am still studying the transformers and I don't want the code to be deprecated very soon. I searched on the web and I can't find t...
If you comment out both these lines: import torch_optimizer as optim from transformers import AdamW and then use: optimizer = torch.optim.AdamW(optimizer_grouped_parameters, lr=1e-5) does it work? If not, what is the error? To switch optimizer, put optim="adamw_torch" in your TrainingArguments (the default is "adamw...
5
5
75,537,816
2023-2-22
https://stackoverflow.com/questions/75537816/transform-a-dataframe-for-network-analysis-using-pandas
I have a data frame of online game matches including two specific columns: IDs of matches and IDs of players participated in a particular match. For instance: match_id player_id 0 1 0 2 0 3 0 4 0 5 1 6 1 1 1 7 1 8 1 2 Hence, player_id is a unique identificator of a player. Meanwhile, match...
I think you don't need networkx if you use permutations from itertools and pd.crosstab: from itertools import permutations pairs = (df.groupby('match_id')['player_id'] .apply(lambda x: list(permutations(x, r=2))) .explode()) adj = pd.crosstab(pairs.str[0], pairs.str[1], rownames=['Player 1'], colnames=['Player 2']) Ou...
3
2
75,537,221
2023-2-22
https://stackoverflow.com/questions/75537221/learning-python-regex-why-can-t-i-use-and-operator-in-if-statement
I’m trying to create a very basic mock password verification program to get more comfortable with meta characters. The program is supposed to take an input, use regex to verify it has at least one capital letter and at least one number, then return either “Password created” if it does, or “Wrong format” if it doesn’t. ...
Use re.search to find a match anywhere in the string. re.match will only return a match if the match starts from the beginning of the string. if re.search("[A-Z]", password) and re.search("[0-9]", password):
4
5
75,534,231
2023-2-22
https://stackoverflow.com/questions/75534231/how-can-i-connect-to-remote-database-using-psycopg3
I'm using Psycopg3 (not 2!) and I can't figure out how can I connect to a remote Postgres server psycopg.connect(connection_string) https://www.psycopg.org/psycopg3/docs/ Thanks!
Psycopg3 uses the postgresql connection string which can either be a string of keyword=value elements (separated by spaces) with psycopg.connect("host=your_server_hostname port=5432 dbname=your_db_name") as conn: or a URI with psycopg.connect("postgresql://user:user_password@db_server_hostname:5432") as conn: So, put...
4
10
75,528,960
2023-2-22
https://stackoverflow.com/questions/75528960/extracting-replies-from-yahoo-finance-forum
I am trying to scrape comments from the Yahoo Finance conversation page (e.g. TSLA) using Python Selenium. I would like to extract all comments together with their replies. As Yahoo Finance does not automatically show all the replies under each comment and have no unique identifier for individual comment, there are als...
If you'll inspect the network tab, you'll notice the API that the client communicates with to fetch the comments and related data. It required some data like spotId and uuid. I guess this is to identify the article. With this information, you can simply use BeautifulSoup and requests to make the process much more effic...
3
2
75,515,475
2023-2-21
https://stackoverflow.com/questions/75515475/unable-to-display-two-tables-side-by-side-inside-a-panel
Using Python (version: 3.10.6) and the Rich (version: 13.3.1) package, I'm attempting to display two tables side by side inside a panel, like this: from rich.panel import Panel from rich.table import Table from rich.console import Console console = Console() table1 = Table() table1.add_column("a") table1.add_column("b"...
I think if you want side-by-side tables inside your panel, you'll need to wrap them in a Columns: panel = Panel.fit( Columns([table1, table2]), title="My Panel", border_style="red", title_align="left", padding=(1, 2), ) console.print(panel) That results in: ╭─ My Panel ─────────────────────────────────────────────────...
3
5
75,471,704
2023-2-16
https://stackoverflow.com/questions/75471704/masking-a-polars-dataframe-for-complex-operations
If I have a polars Dataframe and want to perform masked operations, I currently see two options: # create data df = pl.DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]], schema = ['a', 'b']).lazy() # create a second dataframe for added fun df2 = pl.DataFrame([[8, 6, 7, 5], [15, 16, 17, 18]], schema=["b", "d"]).lazy() # define mas...
You can use a struct with an unnest Your dfs weren't consistent between being lazy and eager so I'm going to make them both lazy ( df .join(df2, on='b') .with_columns(pl.when(mask).then( pl.struct( pl.col("a").sin().alias("new_1"), pl.col("a").cos().alias("new_2"), (pl.col("a") / pl.col("b").cast(pl.Float64())) .alias(...
3
2
75,483,708
2023-2-17
https://stackoverflow.com/questions/75483708/replicate-pandas-ngroup-behaviour-in-polars
I am currently trying to replicate ngroup behaviour in polars to get consecutive group indexes (the dataframe will be grouped over two columns). For the R crowd, this would be achieved in the dplyr world with dplyr::group_indices or the newer dplyr::cur_group_id. As shown in the repro, I've tried couple avenues without...
We can use rank for this: (df.with_row_index() .with_columns( pl.first("index").over("id", "cat").rank("dense") - 1 ) ) shape: (8, 3) ┌───────┬─────┬─────┐ │ index ┆ id ┆ cat │ │ --- ┆ --- ┆ --- │ │ u32 ┆ str ┆ i64 │ ╞═══════╪═════╪═════╡ │ 0 ┆ a ┆ 1 │ │ 0 ┆ a ┆ 1 │ │ 1 ┆ a ┆ 2 │ │ 1 ┆ a ┆ 2 │ │ 2 ┆ b ┆ 1 │ │ 2 ┆ b ┆ ...
3
6
75,495,451
2023-2-18
https://stackoverflow.com/questions/75495451/how-to-combine-two-mypy-disable-error-code-err-comments
I put these on the top of a module: # mypy: disable-error-code=misc # mypy: disable-error-code=attr-defined but only the last line is honoured, the first one is ignored. The same with reversed order or with three lines. In each case all lines except the last one are ignored. I was also trying to aggregate it into one ...
Use both quotes and commas: # mypy: disable-error-code="misc,attr-defined" (Credit goes to STerliakov, who discovered this but did not post an answer.)
4
1
75,476,135
2023-2-16
https://stackoverflow.com/questions/75476135/how-can-i-fix-the-pathlib-package-is-an-obsolete-backport-of-a-standard-libra
I am using Python 3.9.16. When I try to build an application like so: (base) G:\>pyinstaller --onefile grp.py I get an error that says: The 'pathlib' package is an obsolete backport of a standard library package and is incompatible with PyInstaller. Please remove this package (located in C:\Users\alpha\anaconda3\lib\s...
If conda remove pathlib can't find the package, go to the lib folder and delete a folder called path-list-.....
4
4
75,523,498
2023-2-21
https://stackoverflow.com/questions/75523498/python-polars-how-to-get-the-row-count-of-a-lazyframe
The CSV file I have is 70 Gb in size. I want to load the DF and count the number of rows, in lazy mode. What's the best way to do so? As far as I can tell, there is no function like shape in lazy mode according to the documentation. I found this answer which provide a solution not based on Polars, but I wonder if it is...
For polars 0.20.5+ To get the row count using polars. First load it into a lazyframe... lzdf=pl.scan_csv("mybigfile.csv") Then count the rows and return the result lzdf.select(pl.len()).collect() If you just want a python scalar rather than a table as a result then just subset it lzdf.select(pl.len()).collect().item(...
17
26
75,476,288
2023-2-16
https://stackoverflow.com/questions/75476288/difference-between-2-polars-dataframes
What is the best way to find the differences between 2 Polars dataframes? The equals method tells me if there is a difference, I want to find where is the difference. Example: import polars as pl df1 = pl.DataFrame([ {'id': 1,'col1': ['a',None],'col2': ['x']}, {'id': 2,'col1': ['b'],'col2': ['y', None]}, {'id': 3,'col1...
Here's the filter approach ( df1.join(df2, on='id', suffix='_df2') .filter(pl.any_horizontal( pl.col(x).ne_missing(pl.col(f"{x}_df2")) for x in df1.columns if x!='id' )) ) If you wanted the bool column then you just change the filter to with_columns and add an alias. ( df1.join(df2, on='id', suffix='_df2') .with_colum...
3
4
75,458,300
2023-2-15
https://stackoverflow.com/questions/75458300/efficient-speaker-diarization
I am running a VM instance on google cloud. My goal is to apply speaker diarization to several .wav files stored on cloud buckets. I have tried the following alternatives with the subsequent problems: Speaker diarization on Google's API. This seems to go fast but the results make no sense at all. I've already seen sim...
In order to make this work quickly on a GPU (Google colab is used as an example): You need to first install pyannote: !pip install -qq https://github.com/pyannote/pyannote-audio/archive/refs/heads/develop.zip And then: from pyannote.audio import Pipeline import torch pipeline = Pipeline.from_pretrained( "pyannote/spea...
5
7
75,455,529
2023-2-15
https://stackoverflow.com/questions/75455529/specify-a-class-to-detect-using-yolov8-on-pre-trained-model
I'm new to YOLOv8, I just want the model to detect only some classes, not all the 80 classes the model trained on. How can I specify YOLOv8 model to detect only one class? For example only person. from ultralytics import YOLO model = YOLO('YOLOv8m.pt') I remember we can do this with YOLOv5, but I couldn't do same with...
Just specify classes in predict with the class IDs you want to predict from ultralytics.yolo.engine.model import YOLO model = YOLO("yolov8n.pt") model.predict(source="0", show=True, stream=True, classes=0) # [0, 3, 5] for multiple classes for i, (result) in enumerate(results): print('Do something with class 0')
4
6
75,464,271
2023-2-15
https://stackoverflow.com/questions/75464271/attributeerror-str-object-has-no-attribute-execute-on-connection
I have a problem with following code: from pandasql import sqldf import pandas as pd df = pd.DataFrame({'column1': [1, 2, 3], 'column2': [4, 5, 6]}) query = "SELECT * FROM df WHERE column1 > 1" new_dataframe = sqldf(query) print(new_dataframe) When I submit, I have this error: Traceback (most recent call last): File ~...
SQLAlchemy 2.0 (released 2023-01-26) requires that raw SQL queries be wrapped by sqlalchemy.text. The general solution for this error message is to pass the query text to sqlalchemy.text() from sqlalchemy import text ... query = text("SELECT * FROM some_table WHERE column1 > 1") However in this case the OP is using pa...
20
54
75,500,135
2023-2-19
https://stackoverflow.com/questions/75500135/how-can-i-add-my-own-id-instead-of-the-already-given-id-in-mongodb-in-python
I have a class model using Pydantics. I try to supply my own ID but it gives me two id fields in the MongoDB database. The one I gave it and the one it makes automatically. Here is the result of my post method: here is my class in models/articleModel.py: class ArticleModel(BaseModel): _id: int title: str body: str tag...
I had to change the articleModel to a dictionary and add a new key called _id. @router.post("/article/", status_code=status.HTTP_201_CREATED) def add_article(article: articleModel.ArticleModel): article.datetime = datetime.utcnow() article_new_id = article.dict() article_new_id['_id'] = article_new_id['id'] del article...
3
4
75,459,172
2023-2-15
https://stackoverflow.com/questions/75459172/loading-a-huggingface-model-on-multiple-gpus-using-model-parallelism-for-inferen
I have access to six 24GB GPUs. When I try to load some HuggingFace models, for example the following from transformers import AutoTokenizer, AutoModelForSeq2SeqLM tokenizer = AutoTokenizer.from_pretrained("google/ul2") model = AutoModelForSeq2SeqLM.from_pretrained("google/ul2") I get an out of memory error, as the mo...
When you load the model using from_pretrained(), you need to specify which device you want to load the model to. Thus, add the following argument, and the transformers library will take care of the rest: model = AutoModelForSeq2SeqLM.from_pretrained("google/ul2", device_map = 'auto') Passing "auto" here will automatica...
21
31
75,457,741
2023-2-15
https://stackoverflow.com/questions/75457741/dynamically-generating-marshmallow-schemas-for-sqlalchemy-fails-on-column-attrib
I am automatically deriving marshmallow schemas for SQLAlchemy objects using the approach described in How to dynamically generate marshmallow schemas for SQLAlchemy models. I am then decorating my model classes: @derive_schema class Foo(db.Model): id = db.Column(UUID(as_uuid=True), primary_key=True, server_default=sql...
This was a compatibility issue with SQLAlchemy 2.x. marshmallow-sqlalchemy 0.28 doesn't support SQLAlchemy 2.x but the "sqlalchemy<2.0" lock was only introduced in marshmallow-sqlalchemy 0.28.2 so before I released 0.28.2 people could end up with incompatible versions. marshmallow-sqlalchemy 0.29 supports SQLAlchemy ...
3
3
75,519,932
2023-2-21
https://stackoverflow.com/questions/75519932/azure-function-python-model-2-in-docker-container
I am failing to get a minimal working example running with the following setup: azure function in docker container python as language, specifically the "new Python programming model V2" I followed the instructions from here but added the V2 flag, specifically: # init directory func init --worker-runtime python --doc...
It seems there are ongoing changes on this. I was able to get it working by changing the environment variables in the auto generated dockerfile: # To enable ssh & remote debugging on app service change the base image to the one below # FROM mcr.microsoft.com/azure-functions/python:4-python3.10-appservice FROM mcr.micro...
6
8
75,511,558
2023-2-20
https://stackoverflow.com/questions/75511558/video-capture-from-webcam-only-works-when-debugging
SYSTEM AND INSTALL INFORMATION System Information OpenCV Version 4.7.0 Operating System: Windows 10.0.17763 (Pro - Version 21H2) CMake: 3.24.2 Python Version: 3.8.6 OpenCV version Installed from pip (but also built from source as part of diagnostics, reverted back to pip version as no change) Description of issue I a...
Usually this error occurred to me when some application like Antivirus interfering OpenCV, blocking it from accessing the camera. It might be the case that some antivirus software has tendency to block OpenCV when run in non debug mode. My current hypothesis is that in debug mode, the OpenCV libraries may be more trans...
4
1
75,525,029
2023-2-21
https://stackoverflow.com/questions/75525029/msno-matrix-shows-an-error-when-i-use-any-venv-using-pyenv
I tried many times installing several virtual environments using pyenv, but the system shows a error in missingno library. This is : msno.matrix(df) `ValueError Traceback (most recent call last) Cell In[17], line 1 ----> 1 msno.matrix(df) File c:\Users\sarud\.pyenv\venvs\ETLs\lib\site-packages\missingno\missingno.py:72...
I believe argument b has been renamed to visible. An earlier version: matplotlib/axes/_base.py A recent version: matplotlib/axes/_base.py
4
5
75,523,057
2023-2-21
https://stackoverflow.com/questions/75523057/how-is-the-yolov8-best-loss-model-selected-by-the-trainer-class
From the YOLOv8 documentation, it is not clear to me which loss metric the YOLOv8 trainer class uses in determining the best loss model that is saved in a training run. Is it based on the validation or training loss? Specifically, when I look at the outputs from a YOLOv8 training run, I do not see any metadata indicati...
In the save_model function you can see that it uses the maximum fitness to save the best model. The fitness is defined as the weighted combination of 4 metrics [P, R, mAP@0.5, mAP@0.5:0.95]. P and R are disregarded for some reason. mAP@0.5, mAP@0.5:0.95 are weighted 0.1 and 0.9 respectively. If fitness cannot be found,...
4
8
75,480,002
2023-2-17
https://stackoverflow.com/questions/75480002/in-pytorch-how-can-i-avoid-an-expensive-broadcast-when-adding-two-tensors-then
I have two 2-d tensors, which align via broadcasting, so if I add/subtract them, I incur a huge 3-d tensor. I don't really need that though, since I'll be performing a mean on one dimension. In this demo, I unsqueeze the tensors to show how they align, but they are 2-d otherwise. x = torch.tensor(...) # (batch , 1, B) ...
To save memory I recommend using torch.einsum: We can make use of the trigonometric identity cos(x-y) = cos(x)*cos(y) + sin(x)*sin(y) In this case we can apply einsum where the usual summing will be the averaging, and the + between the two produces will be another operation later, so in short xs, ys = torch.sin(x), to...
3
3
75,527,054
2023-2-21
https://stackoverflow.com/questions/75527054/python3-how-to-spawn-jobs-in-parallel
I am pretty new to multithreading and would like to explore. I have a json file, that provides some config. Based on this, i need to kick off some processing. Here is the config { "job1":{ "param1":"val1", "param2":"val2" }, "job2":{ "param3":"val3", "param4":"val4" } } and here is the python snippet config_file = ope...
You are looking for the multiprocessing module. Use a process pool to iterate over many jobs. Here is an example source file that runs correctly when executed as $ python spawn.py. Putting the main code within a def main(): function is nice but not critical. Protecting it with an "if name..." clause is quite important,...
3
1
75,525,312
2023-2-21
https://stackoverflow.com/questions/75525312/how-can-i-convert-a-polars-dataframe-to-a-python-list
I understand Polars Series can be exported to a Python list. However, is there any way I can convert a Polars Dataframe to a Python list? In addition, if there is a one single column in the Polars Dataframe, how can I convert that into a Polars Series? I tried to use the pandas commands but it didn't work. I also check...
How about the rows() method? df = pl.DataFrame( { "a": [1, 3, 5], "b": [2, 4, 6], } ) df.rows() [(1, 2), (3, 4), (5, 6)] df.rows(named=True) [{'a': 1, 'b': 2}, {'a': 3, 'b': 4}, {'a': 5, 'b': 6}] Alternatively, you could get all the DataFrame's columns using the get_columns() method, which would give you a list of S...
8
18
75,495,800
2023-2-18
https://stackoverflow.com/questions/75495800/error-unable-to-extract-uploader-id-youtube-discord-py
I have a very powerful bot in discord (discord.py, PYTHON) and it can play music in voice channels. It gets the music from youtube (youtube_dl). It worked perfectly before but now it doesn't want to work with any video. I tried updating youtube_dl but it still doesn't work I searched everywhere but I still can't find a...
This is a known issue, fixed in Master. For a temporary fix, python3 -m pip install --force-reinstall https://github.com/yt-dlp/yt-dlp/archive/master.tar.gz This installs tha master version. Run it through the command-line yt-dlp URL where URL is the URL of the video you want. See yt-dlp --help for all options. It sh...
93
117
75,523,569
2023-2-21
https://stackoverflow.com/questions/75523569/runtimeerror-a-sqlalchemy-instance-has-already-been-registered-on-this-flask
I am writing a test for my Flask app that uses Flask-SQLAlchemy. In models.py, I used db = SQLAlchemy(), and wrote a function to configure it with the app. But when I run my test, I get the error "RuntimeError: A 'SQLAlchemy' instance has already been registered on this Flask app". I'm not sure where the test file is c...
Flask-SQLAlchemy 3 raises an error for a common incorrect setup of the extension. You must only call db.init_app(app) once for a given pair of db and app instances. You defined db = SQLAlchemy() in models, then called init_app on it in create_app. You must use that db, not create another instance. You must not call db....
5
3
75,512,527
2023-2-20
https://stackoverflow.com/questions/75512527/python-click-determine-whether-argument-comes-from-default-or-from-user
How to tell whether an argument in click is coming from the user or is the default value? For example: import click @click.command() @click.option('--value', default=1, help='a value.') def hello(value): print(value) if __name__ == "__main__": hello() Now if I run python script.py --value 1, the value is now coming fr...
You can use Context.get_parameter_source to get what you want. This returns an enum of 4 possible values (or None if the value does not exist), you can then use them to decide what you want to do. COMMANDLINE - The value was provided by the command line args. ENVIRONMENT - The value was provided with an environment var...
6
7
75,521,662
2023-2-21
https://stackoverflow.com/questions/75521662/upsert-pandas-dataframe-into-snowflake-table
I'm upserting data in snowflake table by creating a Temp Table (from my dataframe) and then merging it to my Table. But is there a more efficient way of achieving it ? Like merging directly the dataframe on snowflake table without a temp Table ? Because I will do it on several tables having a few thousant rows. My Code...
Using snowflake.snowpark.Table.merge: Merges this Table with DataFrame source on the specified join expression and a list of matched or not-matched clauses, and returns a MergeResult, representing the number of rows inserted, updated and deleted by this merge action. Standalone sample(table target exists at Snowflake...
3
3
75,508,198
2023-2-20
https://stackoverflow.com/questions/75508198/python-multithreading-is-faster-than-sequential-code-why
In many stack overflow Q&A about python multi-threading, I read that python has GIL so multi-threading is slower than sequential code. But in my code it doesn't look like This is multi-threading code code updated 02-21-2023 import threading import time global_v = 0 thread_lock = threading.Lock() def thread_test(num): t...
It looks like it is caused by the way CPython treats globals. This sequential version is faster than your concurrent one using CPython 3.11 on my machine: def increment(): nomal_result = 0 for _ in range(5_000_000): nomal_result += 1 nomal_result = 0 start_time = time.perf_counter() increment() end_time = time.perf_cou...
3
2
75,516,448
2023-2-21
https://stackoverflow.com/questions/75516448/python-pandas-groupby-to-calculate-differences-in-months
A data frame below and I want to calculate the intervals of months under the names. Lines so far: import pandas as pd from io import StringIO import numpy as np csvfile = StringIO( """Name Year - Month Score Mike 2022-11 31 Mike 2022-11 136 Lilly 2022-11 23 Lilly 2022-10 44 Kate 2023-01 1393 Kate 2022-10 2360 Kate 2022...
You need to difference with next value instead of previous value. You can do so by setting -1 in diff(). ... df['Interval'] = df.groupby(['Name'])['Year - Month'].transform(lambda x: x.diff(-1)) / np.timedelta64(1, 'M') df['Interval'] = df['Interval'].fillna(0).round().astype(int) Result: Name Year - Month Score Inte...
3
4
75,512,363
2023-2-20
https://stackoverflow.com/questions/75512363/reasoning-behind-high-latency-when-using-python-ctypes-during-process-interrupts
While investigating a critical path in our python codebase, we found out that the behaviour of ctypes in terms of latencies is quite unpredictable. A bit more background of our application. We have bunch of processes where each of them communicate through shared memory. We leverage python library multiprocessing.RawVal...
There are multiple reason for a code to be slower sleeping. Here, the 4 main reasons are the frequency scaling, the TLB/cache misses and the branch misses. All of them are due to context switches mixed with a long period of CPU inactivity. The problem is independent of ctypes. Frequency scaling When a mainstream moder...
4
8
75,477,373
2023-2-16
https://stackoverflow.com/questions/75477373/sqlalchemy-is-slow-when-doing-query-the-first-time
I'm using Sqlalchemy(2.0.3) with python3.10 and after fresh container boot it takes ~2.2s to execute specific query, all consecutive calls of the same query take ~70ms to execute. I'm using PostgreSQL and it takes 40-70ms to execute raw query in DataGrip. Here is the code: self._Session = async_sessionmaker(self._engin...
After hours of googling I have found this post. In short, problem is related to lack of dependencies(in some alpine docker images) that are required by JIT that is used by Postgres. For details I really recommend to read post and real-life impact author provides. Actual solution for Sqlalchemy is to switch off JIT: eng...
4
8
75,504,389
2023-2-20
https://stackoverflow.com/questions/75504389/how-do-i-find-the-smallest-surrounding-rectangle-of-a-set-of-2d-points-in-shapel
How do I find the msmallest surrounding rectangle (which is possibly rotated) of a set of 2D points in Shapely?
To create the smallest surrounding rectangle in Shapely, first construct a MultiPoint from a sequence of points then use the minimum_rotated_rectangle property (which is in the BaseGeometry class). from shapely.geometry import MultiPoint, Polygon points = [(0, 0), (2, 2), (10, 4), (5, 5), (8, 8)] # create a minimum rot...
4
4
75,514,573
2023-2-20
https://stackoverflow.com/questions/75514573/where-can-i-find-python-requests-library-functions-kwargs-parameters-documente
For example, from https://docs.python-requests.org/en/latest/api/#requests.cookies.RequestsCookieJar.set: set(name, value, **kwargs) Dict-like set() that also supports optional domain and path args in order to resolve naming collisions from using one cookie jar over multiple domains. Where can I find information about...
In my experience reading the source code for many open source libraries solves this problem. For the example you posted the source code is the following: def set(self, name, value, **kwargs): """Dict-like set() that also supports optional domain and path args in order to resolve naming collisions from using one cookie ...
3
4
75,504,654
2023-2-20
https://stackoverflow.com/questions/75504654/is-there-a-way-in-numpy-to-merge-two-arrays-using-the-part-that-appears-first-a
I have two same length timeline-like series and I want to merge the parts that appear first while not overlapping. For Example: long = [0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,0,0,0,1,1,1,1,1,0] short = [0,0,0,1,1,1,1,0,1,1,1,1,1,1,0,0,0,1,1,1,0,0,1,1,1] wanted: result = [0,0,1,1,1,1,0,0,1,1,1,1,1,1,0,0,0,1,1,1,0,0,1,1,1] # ...
I do not think any pure-Numpy code can efficiently compute this. Thus, this is the perfect use-case for Numba or Cython. You can solve this using a few simple nested loops for loop that will be compiled to a very-fast native code: import numpy as np import numba as nb long = np.array([0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,0,...
4
1
75,512,205
2023-2-20
https://stackoverflow.com/questions/75512205/unexpected-behaviour-of-pandas-multiindex-set-levels
I have noticed an unexpected result when resetting the level values in a pandas.MultiIndex. The minimal working example I have found to reproduce the problem is as follows: import numpy as np import pandas as pd numbers = np.arange(11).astype(str) columns = pd.MultiIndex.from_product([['A'],numbers]) df = pd.DataFrame(...
It's a bit confusing but it's not a surprise and this is the expected behavior. I slightly modified your example: numbers = np.arange(11).astype(str) columns = pd.MultiIndex.from_product([['A'],numbers]) df = pd.DataFrame(columns.codes, index=['Lvl0', 'Lvl1'], columns=columns) print(df) # Output: A 0 1 2 3 4 5 6 7 8 9 ...
3
3
75,511,806
2023-2-20
https://stackoverflow.com/questions/75511806/running-c-program-on-heroku-no-such-file
I am trying to open a C program in a python script running on a Heroku dyno. The Python script works fine locally, but on the dyno it says that the executable cannot be found. The line to run the program in Python is: proc = subprocess.Popen(["./backend/test-print"], stdout=subprocess.PIPE, stderr=subprocess.PIPE), whe...
There are different user names u5587 vs u13747 in the output of ls and id. ~/backend $ ls -laq total 28 drwx------ 2 u5587 dyno 4096 Feb 20 16:16 . drwx------ 5 u5587 dyno 4096 Feb 20 17:08 .. -rw------- 1 u5587 dyno 520 Feb 20 16:16 server.py -rwx------ 1 u5587 dyno 16176 Feb 20 16:16 test-print ~/backend $ id uid=13...
3
2
75,497,496
2023-2-19
https://stackoverflow.com/questions/75497496/why-is-0-1-faster-than-false-true-for-this-sieve-in-pypy
Similar to why use True is slower than use 1 in Python3 but I'm using pypy3 and not using the sum function. def sieve_num(n): nums = [0] * n for i in range(2, n): if i * i >= n: break if nums[i] == 0: for j in range(i*i, n, i): nums[j] = 1 return [i for i in range(2, n) if nums[i] == 0] def sieve_bool(n): nums = [False...
The reason is that PyPy uses a special implementation for "list of ints that fit in 64 bits". It has got a few other special cases, like "list of floats", "list of strings that contain only ascii", etc. The goal is primarily to save memory: a list of 64-bit integers is stored just like an array.array('l') and not a lis...
6
7
75,504,084
2023-2-19
https://stackoverflow.com/questions/75504084/select-multiple-indices-in-an-axis-of-pytorch-tensor
My actual problem is in a higher dimension, but I am posting it in a smaller dimension to make it easy to visualize. I have a tensor of shape (2,3,4): x = torch.randn(2, 3, 4) tensor([[[-0.9118, 1.4676, -0.4684, -0.6343], [ 1.5649, 1.0218, -1.3703, 1.8961], [ 0.8652, 0.2491, -0.2556, 0.1311]], [[ 0.5289, -1.2723, 2.386...
In your case, this is quite straightforward. An easy way to navigate through two dimensions in parallel is to use a range on the first axis and your indexing tensor on the second: >>> x[range(len(indices)), indices] tensor([[-0.9118, 1.4676, -0.4684, -0.6343], [-1.8151, -0.4634, 1.6490, 0.6957]]) In more general case...
3
4
75,501,247
2023-2-19
https://stackoverflow.com/questions/75501247/plotting-a-3-dimensional-superball-shape
I'm trying to plot a 3D superball in python matplotlib, where a superball is defined as a general mathematical shape that can be used to describe rounded cubes using a shape parameter p, where for p = 1 the shape is equal to that of a sphere. This paper claims that the superball is defined by using modified spherical c...
When plotting a regular sphere, we transform positive and negative coordinates differently: Positives: x**0.5 Negatives: -1 * abs(x)**0.5 For the superball variants, apply the same logic using np.sign and np.abs: power = lambda base, exp: np.sign(base) * np.abs(base)**exp x = r * power(np.cos(u), 1/p) * power(np.sin(...
3
4
75,503,936
2023-2-19
https://stackoverflow.com/questions/75503936/or-condition-in-css-selector-with-selenium-python
I hope you're fine. I'm scraping the logos of some websites. I'm using the next code to localize them. I don't use a tag only the * because the class or attribute that contains the substring 'logo' there is not always in a <div> or <a> tags. driver.find_element(By.CSS_SELECTOR, "*[class*='logo']") I have obtained some...
You can use , to group multiple CSS selectors. driver.find_element(By.CSS_SELECTOR, "[class*='logo'], [id*='logo']")
3
4
75,501,133
2023-2-19
https://stackoverflow.com/questions/75501133/unsupported-interpolation-type-using-env-variables-in-hydra
What I'm trying to do: use environment variables in a Hydra config. I worked from the following links: OmegaConf: Environment variable interpolation and Hydra: Job Configuration. This is my config.yaml: hydra: job: env_copy: - EXPNAME # I also tried hydra:EXPNAME and EXPNAME, # which return None test: ${env:EXPNAME} T...
Try this (env was removed in a long time ago in favor of oc.env). test: ${oc.env:EXPNAME} I don't think the rest is needed if all you need is to access environment variables on your local machine.
5
5
75,495,212
2023-2-18
https://stackoverflow.com/questions/75495212/type-hinting-numpy-arrays-and-batches
I'm trying to create a few array types for a scientific python project. So far, I have created generic types for 1D, 2D and ND numpy arrays: from typing import Any, Generic, Protocol, Tuple, TypeVar import numpy as np from numpy.typing import _DType, _GenericAlias Vector = _GenericAlias(np.ndarray, (Tuple[int], _DType)...
You should not be using protected members (names starting with an underscore) from the outside. They are typically marked this way to indicated implementation details that may change in the future, which is exactly what happened here between versions of numpy. For example in 1.24 your import line from numpy.typing fail...
3
7
75,495,278
2023-2-18
https://stackoverflow.com/questions/75495278/how-to-prevent-vscode-from-reordering-python-imports-across-statements
This is the correct way to import Gtk3 into python: import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk, Gdk, GObject When I save such code in VSCode with "editor.formatOnSave": true, it gets reordered to: from gi.repository import Gtk, Gdk import gi gi.require_version('Gtk', '3.0') which makes G...
To prevent VSCode from reordering Python imports across statements, you can configure the editor to use a specific Python code formatter that maintains the order of the imports as they are in the original code. Here's how you can do it: Install the Python extension for VSCode if you haven't already done so. Install a ...
4
6
75,491,056
2023-2-18
https://stackoverflow.com/questions/75491056/how-does-sympy-handle-exponents-to-the-0-5-power
((gamma-(gamma**2-omega**2)**0.5)*(gamma+(gamma**2-omega**2)**0.5)).simplify() The output is: gamma^2 - (gamma^2 -omega^2)^{1.0} $ However, I expected the result to be omega^2. I know in the sympy docs, it warns about being careful with floating point numbers, but I was under the impression that integers and also frac...
SymPy considers that there is a distinction between exact and inexact numbers. In this context floats like 0.5 and 1.0 are considered to be inexact and therefore it is not clear that x**1.0 is really equal to x or equal to something slightly different like say x**1.00000000000000000000001. That is because floats usuall...
3
6
75,486,790
2023-2-17
https://stackoverflow.com/questions/75486790/sending-a-word-document-without-saving-it-on-the-flask-server
Good day. Today I'm trying to send a document generated on the server to the user on the click of a button using Flask. My task is this: Create a document (without saving it on the server). And send it to the user. However, using a java script, I track the button click on the form and use fetch to make a request to the...
You need to specify the mimetype, It tries to detect the mimetype from the filename but since we are not saving it we need to specify the mimetype. return send_file(f, mimetype='application/msword', as_attachment=True, download_name='output.doc')
3
4
75,488,271
2023-2-17
https://stackoverflow.com/questions/75488271/modulenotfounderror-no-module-named-app-lang-app-is-not-a-package
I have this file structure in my python project |__src |__main.py |__gen.py |__app |__ __init__.py |__ app.py |__ lang.py Intention I want to use the Language class from sibling module lang. So I tried with this import statement in app.py: from app.lang import Language Issue But when I run app.py I get a ModuleNotFou...
Because both app.py and lang.py are in the same directory try to import like this : from .lang import Language or you can use from app.lang import Language from another file located outside app folder
3
2
75,462,344
2023-2-15
https://stackoverflow.com/questions/75462344/make-pip-install-e-build-cython-extensions-with-pyproject-toml
With the move to the new pyproject.toml system, I was wondering whether there was a way to install packages in editable mode while compiling extensions (which pip install -e . does not do). So I want pip to: run the build_ext I configured for Cython and generate my .so files put them in the local folder do the rest of...
I created a module that looks like this: $ tree . . ├── pyproject.toml ├── setup.py └── test └── helloworld.pyx 1 directory, 3 files My pyproject.toml looks like: [build-system] requires = ["setuptools>=61.0", "numpy>=1.17", "cython>=0.18"] build-backend = "setuptools.build_meta" [tool.setuptools] py-modules = ["test"...
5
4
75,486,472
2023-2-17
https://stackoverflow.com/questions/75486472/flask-teardown-request-equivalent-in-fastapi
I am building a rest api with fastapi. I implemented the data layer separately from the fastapi application meaning I do not have direct access to the database session in my fastapi application. I have access to the storage object which have method like close_session which allow me to close the current session. Is ther...
We can do this by using dependency. credit to williamjemir: Click here to read the github discussion from fastapi import FastAPI, Depends from models import storage async def close_session() -> None: """Close current after every request.""" print('Closing current session') yield storage.close() print('db session closed...
3
3
75,480,406
2023-2-17
https://stackoverflow.com/questions/75480406/remembering-the-previous-conversation-of-a-chatbot
I have created a basic ChatBot using OpenAI with the following code: import openai openai.api_key = "sk-xxx" while True: prompt = input("User:") response = openai.Completion.create( model="text-davinci-003", prompt=prompt, max_tokens=50, temperature=0, ) print(response.choices[0].text) This is the input and output: A...
One possibility would be to store the inputs and outputs somewhere, and then include them in subsequent inputs. This is very rudimentary but you could do something like the following: inputs, outputs = [], [] while True: prompt = input("Enter input (or 'quit' to exit):") if prompt == 'quit': break if len(inputs) > 0: i...
3
3
75,479,046
2023-2-16
https://stackoverflow.com/questions/75479046/how-can-i-combine-a-scatter-plot-with-a-density-heatmap
I have a series of scatterplots (one example below), but I want to modify it so that the colors of the points in the plot become more red (or "hot") when they are clustered more closely with other points, while points that are spread out further are colored more blue (or "cold"). Is it possible to do this? Currently, ...
Using scipy.stats.gaussian_kde you can calculate the density and then use this to color the plot: import pandas as pd import plotly.express as px from scipy import stats df = pd.DataFrame({ 'x':[0,0,1,1,2,2,2.25,2.5,2.5,3,3,4,2,4,8,2,2.75,3.5,2.5], 'y':[0,2,3,2,1,2,2.75,2.5,3,3,4,1,5,4,8,4,2.75,1.5,3.25] }) kernel = st...
4
4
75,480,456
2023-2-17
https://stackoverflow.com/questions/75480456/detecting-handwritten-boxes-using-opencv
I have the following image: I want to extract the boxed diagrams as so: Here's what I've attempted: import cv2 import matplotlib.pyplot as plt # Load the image image = cv2.imread('diagram.jpg') # Convert to grayscale gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Apply thresholding to create a binary image _, thre...
We may replace morphological closing with dilate then erode, but filling the contours between the dilate and erode. For filling the gaps, the kernel size should be much larger than 5x5 (I used 51x51). Assuming the handwritten boxes are colored, we may convert from BGR to HSV, and apply the threshold on the saturation ...
5
3
75,472,350
2023-2-16
https://stackoverflow.com/questions/75472350/how-to-resolve-error-could-not-build-wheels-for-matplotlib-which-is-required
I am encountering the following error when attempting to install matplotlib in an alpine Docker image: error: Failed to download any of the following: ['http://www.qhull.org/download/qhull-2020-src-8.0.2.tgz']. Please download one of these urls and extract it into 'build/' at the top-level of the source repository. [e...
This solved my problem: pip install matplotlib==3.2.1
6
4
75,479,969
2023-2-17
https://stackoverflow.com/questions/75479969/how-to-get-all-data-when-show-more-button-clicked-with-scrapy-playwright
Currently, I've had trouble getting all data on this page: https://www.espn.com/nba/stats/player/_/season/2023/seasontype/2 so if scrape right now it only gets 50 of the data, this is not what I want, what I want is to scrape all data, to show all table data must have to click the "show more" button until there is no "...
Since your goal is to to continously find the same element until it no longer exists, you could handle all of the logic in the parse method itself. Their could be better ways to handle this, but this does provide the desired full table of results in the output. def start_requests(self): yield scrapy.Request( url='http...
3
3
75,480,225
2023-2-17
https://stackoverflow.com/questions/75480225/using-if-else-in-with-statement-in-python
I want to open a file that may be gzipped or not. To open the file, I use either with open(myfile, 'r') as f: some_func(f) # arbitrary function or import gzip with gzip.open(myfile, 'r') as f: some_func(f) I want to check if myfile has a gz extension or not, and then from there decide which with statement to use. Her...
if myfile_gzipped: f = gzip.open(myfile, 'rb') else: f = open(myfile, 'r') with f: some_func(f) The result of open and gzip.open is a context manager. with invokes the entry and exit methods on context managers. There is nothing special in calling those functions inside the with statement itself.
3
6
75,478,554
2023-2-16
https://stackoverflow.com/questions/75478554/fill-gaps-between-1s-in-pandas-dataframe-column-with-increment-values-that-rese
Apparently this is a more complicated problem than I thought. All I want to do is fill the zeros with ++1 increments until the next 1 My dataset is 1m+ rows, so I'm trying to vectorize this operation if possible. Here's a sample column: # Define the input dataframe df = pd.DataFrame({'col': [1, 0, 1, 0, 1, 1, 0, 0, 0, ...
Group by cumulative sums of column col and apply cumcount: df['col'] = df.groupby(df['col'].cumsum())['col'].cumcount() + 1 col 0 1 1 2 2 1 3 2 4 1 5 1 6 2 7 3 8 4 9 5 10 1 11 2 12 1 13 1 14 2
3
2
75,467,411
2023-2-16
https://stackoverflow.com/questions/75467411/conda-what-difference-does-it-make-if-we-set-pip-interop-enabled-true
There are many posts on this site which reference, typically in passing, the idea of setting pip_interop_enabled=True within some environment. This makes conda and pip3 somehow interact better, I am told. To be precise, people say conda will search PyPI for packages that don't exist in the main channels if this is true...
Not a PyPI Searching Feature First, let's clarify: Conda will not "search PyPI" - that is not what the pip_interop_enabled configuration option adds. Rather, it enables the solver to allow a package already installed with pip to satisfy a dependency requirement of a Conda package. Note that the option is about Pip inte...
4
7
75,478,267
2023-2-16
https://stackoverflow.com/questions/75478267/how-to-use-pandas-groupby-in-a-for-loop-futurewarning
I have the following pandas dataframe: d2 = {'col1': [0, 0, 1, 1, 2], 'col2': [10, 11, 12, 13, 14]} df2 = pd.DataFrame(data=d2) df2 Output: col1 col2 0 0 10 1 0 11 2 1 12 3 1 13 4 2 14 And I need to run the following: for i, g in df2.groupby(['col1']): col1_val = g["col1"].iloc[0] print(col1_val) The original code ...
This means that you should use a string instead of the list with a unique string: for i, g in df2.groupby('col1'): col1_val = g["col1"].iloc[0] print(col1_val) If you keep the original code, in the future i will have the value (0,)/(1,)/(2,) instead of 0/1/2
3
5
75,477,485
2023-2-16
https://stackoverflow.com/questions/75477485/how-do-i-type-hint-for-enums-in-python
I have a python function for which I want to use type hinting. There are two arguments. The first is any Enum class, the second optional arg is an element of that Enum. For example, say I have: class Foo(Enum): ALPHA = 1 BETA = 2 GAMMA = 3 The first arg would be, e.g. Foo, the second would be e.g. Foo.ALPHA What would...
Define a TypeVar with Enum as a bound, and then specify that your function takes the Type of that typevar and returns an instance of it: from enum import Enum from typing import Optional, Type, TypeVar _E = TypeVar('_E', bound=Enum) def switch( options: Type[_E], selected: Optional[_E] = None ) -> _E: ... Testing it i...
3
3
75,471,388
2023-2-16
https://stackoverflow.com/questions/75471388/sentry-rate-limit-errors-sent-to-prevent-depletion-of-error-quota
When an infrastructure incident happens, the application will start to generate thousands of occurrences of the same error. Is it possible to configure some kind of rate limiting or anything like that on the sentry client (or server) to avoid depleting the error quota? I'm using Python, Django and Celery mostly.
Yes, there are multiple solutions to this common problem. Sentry is an amazing tool, but when there's that annoying bug it can cause quite the issue. Sentry has great documentation that covers this problem. There are two solutions I see as a good use case for you: Rate limiting - This enables you to control the number...
3
3
75,471,318
2023-2-16
https://stackoverflow.com/questions/75471318/readonlyworksheet-object-has-no-attribute-defined-names
Whenever I try to read Excel using part=pd.read_excel(path,sheet_name = mto_sheet) I get this exception: <class 'Exception'> 'ReadOnlyWorksheet' object has no attribute 'defined_names' This is if I use Visual Studio Code and Python 3.11. However, I don't have this problem when using Anaconda. Any reason for that?
The error seems to be caused by the latest version of openpyxl. You can fix it by downgrading to a lower version pip install --force-reinstall -v "openpyxl==3.1.0"
25
49
75,468,967
2023-2-16
https://stackoverflow.com/questions/75468967/extracting-and-replacing-a-particular-string-from-a-sentence-in-python
Say I have a string, s1="Hey Siri open call up duty" and another string s2="call up duty". Now I know that "call up duty" should be replaced by "call of duty". Say s3="call of duty". So what I want to do is that from s1 delete s2 and place s3 in its location. I am not sure how this can be done. Can anyone please guide...
In python, Strings have a replace() method which you can easily use to replace the sub-string s2 with s3. s1 = "Hey Siri open call up duty" s2 = "call up duty" s3 = "call of duty" s1 = s1.replace(s2, s3) print(s1) This should do it for you. For more complex substitutions the re module can be of help.
3
3
75,454,731
2023-2-15
https://stackoverflow.com/questions/75454731/python-opc-ua-client-write-variable-using-browsename
I can't find the correct syntax for assigning a value to a variable using its BrowseName. I am testing with the 'flag1' boolean variable because it is easier to debug. But my goal is be able to write in all variables, including the arrays. If I try to use the index number it works fine. import pyOPCClient as opc client...
I see you use the pyOPCClient package. I´m not sure if this is maintaned anymore (Last Update: 2014-01-09 see here). You can switch to opcua-asyncio which can address nodes with the browse services like this: myvar = await client.nodes.root.get_child(["0:Objects",..., "4:flag1"]) And here is the complete example
3
3
75,454,425
2023-2-15
https://stackoverflow.com/questions/75454425/access-blocked-project-has-not-completed-the-google-verification-process
I am building a simple script which polls some data and then updates a spreadsheet that I am giving to my client. (It is a small project and I don't need anything fancy.) So I created a Google Cloud project, enabled the Sheets API, and got a credential for a Desktop app. When I try to run the quickstart sample, I get a...
You need to add the account as a test user under the OAuth consent screen: 1.) From the dashboard go to APIs & Services and click OAuth concent screen 2.) Under the Test users, click +Add Users. A menu will prompt on the right panel. 3.) Input the users email 4.) Reload the URL provided. Reference: https://www.youtu...
42
90
75,463,473
2023-2-15
https://stackoverflow.com/questions/75463473/why-are-the-balls-so-unstable
This is a physics simulation constraining balls in a circular area. I made the original code in Scratch and converted it to Python in Pygame. When I run the simulation, all the balls were shaking, compared to the original code. I constrained the velocity to be maximum 20, but it didn't help. I created substeps for each...
The angle of the trigonometric functions in the math module is measured in Radian, but not in Degrees. d should not be a global variable, you can just return the angle from pointat: def pointat(px,py): dx = px-x[i] dy = py-y[i] if dy == 0: if dx < 0: d = -math.pi/2 else: d = math.pi/2 else: if dy < 0: d = math.pi+math....
3
3
75,461,236
2023-2-15
https://stackoverflow.com/questions/75461236/dynamically-updating-type-hints-for-all-attributes-of-subclasses-in-pydantic
I am writing some library code where the purpose is to have a base data model that can be subclassed and used to implement data objects that correspond to the objects in a database. For this base model I am inheriting from pydantic.BaseModel. There is a bunch of stuff going on but for this example essentially what I ha...
Plugin required Not without a custom plugin I'm afraid (see e.g. Pydantic). You explicitly annotate the birth_date name within the class' scope to be of the type datetime, so the type checkers are correct to say that it does not support __neg__ (instance or not is irrelevant). Your metaclass magic will likely not be un...
4
4
75,458,034
2023-2-15
https://stackoverflow.com/questions/75458034/no-module-named-pil-after-installing-pillow-latest-version
I am installed pillow,following the documentation here, python3 -m pip install --upgrade pip python3 -m pip install --upgrade Pillow and import Image like this: from PIL import Image Even though I upgraded Pillow to 9.4.0, I am getting the following error in vscode No module named 'PIL' I am using Python 3.9.7. I a...
Add this code to your script. import sys print(sys.path) Ensure that your sys.path contains the path "$PROJECT/venv/lib/python3.9/site-packages" If it doesn't, your virtual environment is broken. Try this instead: Use this command to remove the current environment. rm -rf venv Create it again. python -m venv venv Ins...
5
1
75,387,339
2023-2-8
https://stackoverflow.com/questions/75387339/how-can-i-edit-modify-replace-text-in-an-existing-pdf-file
I am working on my final year project, so I working on a website where a user can come and read PDF. I am adding some features such as converting currency to their country currency. I am using flask and pymuPDF for my project and I don't know how I can modify the text at a pdf anyone can help me with this problem? I he...
Using the redaction facility of PyMuPDF is probably the adequate thing to do. The approach: Identify the location of the text to replace Erase the text and replace it using redactions Care must be taken to get hold of the original font, and whether or not the new text is longer / short than the original. import fitz ...
4
13
75,438,152
2023-2-13
https://stackoverflow.com/questions/75438152/how-to-convert-time-durations-to-numeric-in-polars
Is there any built-in function in polars or a better way to convert time durations to numeric by defining the time resolution (e.g.: days, hours, minutes)? import polars as pl df = pl.DataFrame({ "from": ["2023-01-01", "2023-01-02", "2023-01-03"], "to": ["2023-01-04", "2023-01-05", "2023-01-06"], }) My current approac...
The dt accessor lets you obtain individual components, is that what you're looking for? df.select( total_days = pl.col.time_diff.dt.total_days(), total_hours = pl.col.time_diff.dt.total_hours(), total_minutes = pl.col.time_diff.dt.total_minutes() ) shape: (3, 3) ┌────────────┬─────────────┬───────────────┐ │ total_day...
14
7