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
71,516,584
2022-3-17
https://stackoverflow.com/questions/71516584/padding-scipy-affine-transform-output-to-show-non-overlapping-regions-of-transfo
I have source (src) image(s) I wish to align to a destination (dst) image using an Affine Transformation whilst retaining the full extent of both images during alignment (even the non-overlapping areas). I am already able to calculate the Affine Transformation rotation and offset matrix, which I feed to scipy.ndimage.i...
Working code below in case anyone else has this need of scipy's affine transformations: def affine_test(angle=0, translate=(0, 0), shape=(200, 100), buffered_shape=(300, 200), nblob=50): # Maxiumum translation allowed is half difference between shape and buffered_shape np.random.seed(42) # Generate a buffered_shape-siz...
7
2
71,514,124
2022-3-17
https://stackoverflow.com/questions/71514124/find-near-duplicate-and-faked-images
I am using Perceptual hashing technique to find near-duplicate and exact-duplicate images. The code is working perfectly for finding exact-duplicate images. However, finding near-duplicate and slightly modified images seems to be difficult. As the difference score between their hashing is generally similar to the hashi...
Here's a quantitative method to determine duplicate and near-duplicate images using the sentence-transformers library which provides an easy way to compute dense vector representations for images. We can use the OpenAI Contrastive Language-Image Pre-Training (CLIP) Model which is a neural network already trained on a v...
23
41
71,544,953
2022-3-20
https://stackoverflow.com/questions/71544953/unreadable-jupyter-lab-notebook-after-upgrading-pandas-capture-validation-error
I was recently using Jupyter lab and decided to update my pandas version from 1.2 to the latest (1.4). So I ran 'conda update pandas' which seemed to work fine. However when I then launched Jupyter lab in the usual way 'jupyter lab' and tried to open the workbook I had just been working on I got the below error: Unrea...
It turns out that a recent update to jupyter_server>=1.15.0 broke compatibility with nbformat<5.2.0, but did not update the conda recipe correctly per this Github pull request. It is possible that while updating pandas, you may have inadvertently also updated jupyterlab and/or jupyter_server. While we wait for the buil...
12
10
71,574,168
2022-3-22
https://stackoverflow.com/questions/71574168/how-to-plot-confusion-matrix-without-color-coding
Of all the answers I see on stackoverflow, such as 1, 2 and 3 are color-coded. In my case, I wouldn´t like it to be colored, especially since my dataset is largely imbalanced, minority classes are always shown in light color. I would instead, prefer it display the number of actual/predicted in each cell. Currently, I u...
Use seaborn.heatmap with a grayscale colormap and set vmin=0, vmax=0: import seaborn as sns sns.heatmap(cm, fmt='d', annot=True, square=True, cmap='gray_r', vmin=0, vmax=0, # set all to white linewidths=0.5, linecolor='k', # draw black grid lines cbar=False) # disable colorbar # re-enable outer spines sns.despine(left=...
6
6
71,577,514
2022-3-22
https://stackoverflow.com/questions/71577514/valueerror-per-column-arrays-must-each-be-1-dimensional-when-trying-to-create-a
I'm trying to create a very simple Pandas DataFrame from a dictionary. The dictionary has 3 items, and the DataFrame as well. They are: a list with the 'shape' (3,) a list/np.array (in different attempts) with the shape(3, 3) a constant of 100 (same value to the whole column) Here is the code that succeeds and displ...
If you look closer at the error message and quick look at the source code here: elif isinstance(val, np.ndarray) and val.ndim > 1: raise ValueError("Per-column arrays must each be 1-dimensional") You will find that if the dictionay value is a numpy array and has more than one dimension as your example, it throws an e...
15
15
71,574,873
2022-3-22
https://stackoverflow.com/questions/71574873/assign-one-column-value-to-another-column-based-on-condition-in-pandas
I want to how we can assign one column value to another column if it has null or 0 value I have a dataframe like this: id column1 column2 5263 5400 5400 4354 6567 Null 5656 5456 5456 5565 6768 3489 4500 3490 Null The Expected Output is id column1 column2 5263 5400 5400 4354 6567 6567 5656 5456 5456 5565 6768 3489 4500...
Based on the answers to this similar question, you can do the following: Using np.where: df['column2'] = np.where((df['column2'] == 'Null') | (df['column2'] == 0), df['column1'], df['column2']) Instead, using only pandas and Python: df['column2'][(df['column2'] == 0) | (df['column2'] == 'Null')] = df['column1']
7
10
71,576,361
2022-3-22
https://stackoverflow.com/questions/71576361/mypy-error-expected-type-in-class-pattern-found-any
Want to add MyPy checker to my html scraper. I manage to fix all errors except this one Expected type in class pattern. Source code: from bs4 import BeautifulSoup from bs4.element import Tag, NavigableString soup = BeautifulSoup(""" <!DOCTYPE html> <html> <body> EXTRA TEXT <p> first <b>paragraph</b> <br> <br> second pa...
You can use TYPE_CHECKING to load classes that have the typing from typing import TYPE_CHECKING if TYPE_CHECKING: class NavigableString: ... class Tag: children: list[NavigableString | Tag] name: str class BeautifulSoup: def __init__(self, markup: str, features: str | None) -> None: ... def select_one(self, text: str) ...
5
1
71,567,315
2022-3-22
https://stackoverflow.com/questions/71567315/how-to-get-the-ssim-comparison-score-between-two-images
I am trying to calculate the SSIM between corresponding images. For example, an image called 106.tif in the ground truth directory corresponds to a 'fake' generated image 106.jpg in the fake directory. The ground truth directory absolute pathway is /home/pr/pm/zh_pix2pix/datasets/mousebrain/test/B The fake directory ab...
Here's a working example to compare one image to another. You can expand it to compare multiple at once. Two test input images with slight differences: Results Highlighted differences Similarity score Image similarity 0.9639027981846681 Difference masks Code from skimage.metrics import structural_similarity im...
8
17
71,565,413
2022-3-21
https://stackoverflow.com/questions/71565413/adding-a-dictionary-to-a-row-in-a-pandas-dataframe-using-concat-in-pandas-1-4
After updating to pandas 1.4, I now receive the following warning when using frame.append to append a dictionary to a Pandas DataFrame. FutureWarning: The frame.append method is deprecated and will be removed from pandas in a future version. Use pandas.concat instead. Below is the code. This still works, though I woul...
Use loc to assign a single row value: report.loc[len(report)] = {"period":period, "symbol":symbol, "start_date":start_date, "start_price":start_price, "start_market_cap":start_market_cap, "end_date":end_date, "end_price":end_price, "end_market_cap":end_market_cap, "return":return_ }
9
3
71,564,200
2022-3-21
https://stackoverflow.com/questions/71564200/python-how-to-revert-the-pattern-of-a-list-rearrangement
So I am rearranging a list based on an index pattern and would like to find a way to calculate the pattern I need to revert the list back to its original order. for my example I am using a list of 5 items as I can work out the pattern needed to revert the list back to its original state. However this isn't so easy when...
This is commonly called "argsort". But since you're using 1-based indexing, you're off-by-one. You can get it with numpy: >>> pattern [2, 5, 1, 3, 4] >>> import numpy as np >>> np.argsort(pattern) + 1 array([3, 1, 4, 5, 2]) Without numpy: >>> [1 + i for i in sorted(range(len(pattern)), key=pattern.__getitem__)] [3, 1,...
6
2
71,546,900
2022-3-20
https://stackoverflow.com/questions/71546900/weird-glibc-2-17-conflict-when-trying-to-conda-install-tensorflow-1-4-1
I'm trying to create a new conda enviornment with tensorflow (GPU), version 1.4.1 with the following command conda create -n parsim_1.4.1 python=3 tensorflow-gpu=1.4.1. However, it prints a weird conflict: $ conda create -n parsim_1.4.1 python=3 tensorflow-gpu=1.4.1 Collecting package metadata (current_repodata.json): ...
Conda's error reporting isn't always helpful. Mamba is sometimes better, and in this particular case it gives: Looking for: ['python=3', 'tensorflow-gpu=1.4.1'] conda-forge/linux-64 Using cache conda-forge/noarch Using cache pkgs/main/linux-64 No change pkgs/main/noarch No change pkgs/r/linux-64 No change pkgs/r/noarch...
5
7
71,540,449
2022-3-19
https://stackoverflow.com/questions/71540449/aws-lambda-to-rds-postgresql
Hello fellow AWS contributors, I’m currently working on a project to set up an example of connecting a Lambda function to our PostgreSQL database hosted on RDS. I tested my Python + SQL code locally (in VS code and DBeaver) and it works perfectly fine with including only basic credentials(host, dbname, username passwor...
Following the directions at the link below to build a specific psycopg2 package and also verifying the VPC subnets and security groups were configured correctly solved this issue for me. I built a package for PostgreSQL 10.20 using psycopg2 v2.9.3 for Python 3.7.10 running on an Amazon Linux 2 AMI instance. The only ch...
5
2
71,546,126
2022-3-20
https://stackoverflow.com/questions/71546126/python-pydantic-error-typeerror-init-takes-exactly-1-positional-argument
i am currenty working on a python fastapi project for university. Every time i run my authorization dependencies i get the following error: ERROR: Exception in ASGI application Traceback (most recent call last): File "C:\Python39\lib\site-packages\uvicorn\protocols\http\h11_impl.py", line 366, in run_asgi result = awai...
You have to give Pydantic which key you are providing a value for: token_data = schemas.TokenData(username=username) Otherwise Pydantic has no idea that the variable username from the parent scope should be assigned to the username property in the schema.
11
20
71,545,135
2022-3-20
https://stackoverflow.com/questions/71545135/how-to-append-rows-with-concat-to-a-pandas-dataframe
I have defined an empty data frame with: insert_row = { "Date": dtStr, "Index": IndexVal, "Change": IndexChnge, } data = { "Date": [], "Index": [], "Change": [], } df = pd.DataFrame(data) df = df.append(insert_row, ignore_index=True) df.to_csv(r"C:\Result.csv", index=False) driver.close() But I get the below deprecati...
Create a dataframe then concat: insert_row = { "Date": '2022-03-20', "Index": 1, "Change": -2, } df = pd.concat([df, pd.DataFrame([insert_row])]) print(df) # Output Date Index Change 0 2022-03-20 1.0 -2.0
5
11
71,544,103
2022-3-20
https://stackoverflow.com/questions/71544103/how-can-we-store-a-json-credential-to-env-variable-in-python
{ "type": "service_account", "project_id": "project_id", "private_key_id": "private_key_id", "private_key": "-----BEGIN PRIVATE KEY-----\n", "client_email": "email", "client_id": "id", "auth_uri": "uri_auth", "token_uri": "token_urin", "auth_provider_x509_cert_url": "auth_provider_x509_cert_url", "client_x509_cert_url"...
Assuming your JSON file is creds.json creds.json { "type": "service_account", "project_id": "project_id", "private_key_id": "private_key_id", "private_key": "-----BEGIN PRIVATE KEY-----\n", "client_email": "email", "client_id": "id", "auth_uri": "uri_auth", "token_uri": "token_urin", "auth_provider_x509_cert_url": "aut...
8
6
71,510,217
2022-3-17
https://stackoverflow.com/questions/71510217/how-to-invalidate-a-view-cache-using-django-cacheops
I have a view and I cached it in views.py using django-cacheops (https://github.com/Suor/django-cacheops): @cached_view(timeout=60*15) @csrf_exempt def order(request, usr): ... The regex for order view in urls.py: url(r'^order/(?P<usr>\D+)$', views.order, name='ord') # Example Url: http://127.0.0.1:8000/order/demo (de...
Since you used a named group usr in your regex, Django passes it as a keyword argument: url(r'^order/(?P<usr>\D+)$', views.order, name='ord') But you are trying to invalidate the cache with a positional argument: order.invalidate("http://127.0.0.1:8000/order/demo", "demo") Instead, invalidate it with the correspondin...
6
4
71,529,767
2022-3-18
https://stackoverflow.com/questions/71529767/django-core-exceptions-improperlyconfigured-cannot-import-apps-accounts-ch
This is how it is structured The code inside apps.py of accounts folder file is from django.apps import AppConfig class AccountsConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = "apps.accounts" The code inside Settings is INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', '...
The solution was quite counterintuitive. You have to delete the class AccountsConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = "accounts" from apps.py\accounts\apps\mysite. Then run python manage.py makemigrations and 2 new models 'UserPersona' and 'UserProfile' are created. the output in...
22
2
71,535,170
2022-3-19
https://stackoverflow.com/questions/71535170/how-to-add-elements-of-a-list-to-elements-of-a-row-in-pandas-database
i have this database called db in pandas index win loss moneywin moneyloss player1 5 1 300 100 player2 10 5 650 150 player3 17 6 1100 1050 player11 1010 105 10650 10150 player23 1017 106 101100 101050 and i want to add the elements of list1 to the elements of db list1 = [[player1,105,101,10300,10100],[player3,17,6,11...
Solution 1: Create a dataframe from list1 then concat it with the given dataframe then group by index and aggregate the remaining columns using sum df1 = pd.DataFrame(list1, columns=df.columns) df_out = pd.concat([df, df1]).groupby('index', sort=False).sum() Solution 2: Create a dataframe from list1 then add it with t...
7
2
71,531,909
2022-3-18
https://stackoverflow.com/questions/71531909/declare-variable-type-inside-function
I am defining a function that gets pdf in bytes, so I wrote: def documents_extractos(pdf_bytes: bytes): pass When I call the function and unfortunately pass a wrong type, instead of bytes let's say an int, why I don't get an error? I have read the documentation regarding typing but I don't get it. Why is the purpose o...
Type hints are ignored at runtime. At the top of the page, the documentation that you've linked contains a note that states (emphasis mine): The Python runtime does not enforce function and variable type annotations. They can be used by third party tools such as type checkers, IDEs, linters, etc. The purpose of type ...
5
3
71,515,439
2022-3-17
https://stackoverflow.com/questions/71515439/equivalent-to-torch-rfft-in-newest-pytorch-version
I want to estimate the fourier transform for a given image of size BxCxWxH In previous torch version the following did the job: fft_im = torch.rfft(img, signal_ndim=2, onesided=False) and the output was of size: BxCxWxHx2 However, with the new version of rfft : fft_im = torch.fft.rfft2(img, dim=2, norm=None) I do no...
A few issues The dim argument you provided is an invalid type, it should be a tuple of two numbers or should be omitted. Really PyTorch should raise an exception. I would argue that the fact this ran without exception is a bug in PyTorch (I opened a ticket stating as much). PyTorch now supports complex tensor types, s...
6
7
71,511,514
2022-3-17
https://stackoverflow.com/questions/71511514/textmate-latex-compilation-pb-with-python-version-after-macos-update-monterey
I use textmate for make pdf file in latex. After the update of macOS Monterey version 12.3, the minimal version of python (/usr/bin/python) has disappeared : the compilation don't work now. I try to change in the textmate's files /usr/bin/python by /usr/bin/python3 (I have only this python folder) but that always don't...
The LaTeX-Bundle of TextMate was not updated in time for the release of MacOS 12.3. You can fix it as follows: Download and install Python 3 (https://www.python.org/downloads/) /usr/bin/python3 -m pip install pyobjc --user cd ~/Library/Application\ Support/TextMate/Managed/Bundles/LaTeX.tmbundle/Support/bin Change “py...
6
7
71,522,731
2022-3-18
https://stackoverflow.com/questions/71522731/unable-to-activate-virtual-environment-in-python
I am on Windows 10, Python 3.10.2. Here are the commands that I ran to create the virtual environment: Here are my versions for packages: virtualenv==16.7.5 virtualenvwrapper-win==1.2.6 I installed the virtual environment. D:\voice-cloning\real-time-voice-cloning>python -m pip install virtualenv WARNING: Ignoring in...
Using python 3.10.2 and virtualenv 16.7.5 gives me the same error. Looks like virtualenv 16.7.5 is too old for 3.10.2. Upgrade you package with this command and everything will work out. pip install --upgrade virtualenv
5
11
71,523,205
2022-3-18
https://stackoverflow.com/questions/71523205/how-to-install-multiple-versions-of-python-in-windows
Up until recently I have only worked with one version of Python and used virtual environments every now and then. Now, I am working with some libraries that require older version of Python. So, I am very confused. Could anyone please clear up some of my confusion? How do I install multiple Python versions? I initiall...
Your questions depend a bit on "all the other software". For example, as @leiyang indicated, the answer will be different if you use conda vs just pip on vanilla CPython (the standard Windows Python). I'm also going to assume you're actually on Windows, because on Linux I would recommend looking at pyenv. There is a py...
8
6
71,513,504
2022-3-17
https://stackoverflow.com/questions/71513504/upgrade-python-in-a-virtual-environment-with-m-venv-upgrade
I have multiple python versions managed by pyenv. I want to upgrade one of my virtual environments from 3.7.13 to 3.10.3 with the ‘—upgrade’ option as: >deactivate >pyenv local 3.10.3 >python3 -m venv --upgrade .venv >. .venv/bin/activate > python -V Python 3.7.13 I expect the '—upgrade' would change the python versio...
If you read the official documentation of the venv module, then the description of the --upgrade option is very specific: "... assuming Python has been upgraded in-place." I think this implies that it has to be the same Python installation that you originally created the virtual environment with, for the --upgrade flag...
5
3
71,518,406
2022-3-17
https://stackoverflow.com/questions/71518406/how-to-bypass-cloudflare-browser-checking-selenium-python
I am trying to access a site using selenium Python. But the site is checking and checking continuously by cloudflare. No other page is coming. Check the screenshot here. I have tried undetected chrome but it is not working at all.
By undetected chrome do you mean undetected chromedriver?: Anyways, undetected-chromedriver works for me: Undetected chromedriver Github: https://github.com/ultrafunkamsterdam/undetected-chromedriver pip install undetected-chromedriver Code that gets a cloudflare protected site: import undetected_chromedriver as uc dr...
10
9
71,510,827
2022-3-17
https://stackoverflow.com/questions/71510827/numba-when-to-use-nopython-true
I have the following setup: import numpy as np import matplotlib.pyplot as plt import timeit import numba @numba.jit(nopython=True, cache=True) def f(x): summ = 0 for i in x: summ += i return summ @numba.jit(nopython=True) def g21(N, locs): rvs = np.random.normal(loc=locs, scale=locs, size=N) res = f(rvs) return res @...
in this case, what is the use of using nopython=True, if a function with nopython=False achieves same speed? in which specific case is nopython=True better than nopython=False? The documentation states: Numba has two compilation modes: nopython mode and object mode. The former produces much faster code, but has li...
5
7
71,517,750
2022-3-17
https://stackoverflow.com/questions/71517750/how-to-replace-pandas-append-with-concat
Can you help me replace append with concat in this code? saida = pd.DataFrame() for x, y in lCodigos.items(): try: df = consulta_bc(x) logging.info(f'Indice {y} lido com sucesso.') except Exception as err: logging.error(err) logging.warning('Rotina Indice falhou!') exit() df['nome'] = y saida = saida.append(df) print(s...
Just save the "dataframe parts" using a list and use pd.concat on that list of dataframes at the end: saida = list() # Now use a list for x, y in lCodigos.items(): # ... your original code saida.append(df) saida = pd.concat(saida) # You can now create the dataframe
5
1
71,516,511
2022-3-17
https://stackoverflow.com/questions/71516511/python-api-request-to-gitlab-unexpectedly-returns-empty-result
import requests response = requests.get("https://gitlab.com/api/v4/users/ahmed_sh/projects") print(response.status_code) # 200 print(response.text) # [] print(response.json()) # [] I'm trying to get a list of my GitLab repo projects using python API, but the outputs are nothing! Although, when I use the browser, I got...
This is because you don't have any public projects in your user namespace. If you want to see your private projects in your namespace, you'll need to authenticate with the API by passing a personal access token in the PRIVATE-TOKEN header. Note, this also won't show projects you work on in other namespaces. headers = {...
5
5
71,504,533
2022-3-16
https://stackoverflow.com/questions/71504533/pip-install-from-github-broken-after-github-keys-policy-update
I would normally install a Python repository from Github using (for example): pip install git+git://github.com/Artory/drf-hal-json@master And concordantly, my "requirements.txt" would have git+git://github.com/Artory/drf-hal-json@master in it somewhere. This failed today. The full traceback is below, but the relevant ...
In the URL you give to pip, the git+git says to access a Git repository (the first git) over the unauthenticated git protocol (the second git). Assuming you want to continue to use anonymous access here, you can simply rewrite the command to use git+https instead, which access a Git repository over the secure HTTPS pro...
5
7
71,501,140
2022-3-16
https://stackoverflow.com/questions/71501140/type-hinting-for-scipy-sparse-matrices
How do you type hint scipy sparse matrices, such as CSR, CSC, LIL etc.? Below is what I have been doing, but it doesn't feel right: def foo(mat: scipy.sparse.csr.csr_matrix): # Do whatever What do we do if our function can accept multiple types of scipy sparse matrices (i.e any of them)?
All of csr, csc, lil are types of scipy.sparse.base.spmatrix: from scipy import sparse c1 = sparse.lil.lil_matrix c2 = sparse.csr.csr_matrix c3 = sparse.csc.csc_matrix print(c1.__bases__[0]) print(c2.__base__.__base__.__base__) print(c3.__base__.__base__.__base__) Output: <class 'scipy.sparse.base.spmatrix'> <class 's...
6
4
71,500,106
2022-3-16
https://stackoverflow.com/questions/71500106/how-to-implement-t-sne-in-tensorflow
I am trying to implement a t-SNE visualization in tensorflow for an image classification task. What I mainly found on the net have all been implemented in Pytorch. See here. Here is my general code for training purposes which works completely fine, just want to add t-SNE visualization to it: import pandas as pd import ...
You could try something like the following: Train your model import tensorflow as tf import pathlib dataset_url = "https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz" data_dir = tf.keras.utils.get_file('flower_photos', origin=dataset_url, untar=True) data_dir = pathlib.Path(data_dir...
5
7
71,500,756
2022-3-16
https://stackoverflow.com/questions/71500756/what-is-pythons-namespace-object
I know what namespaces are. But when running import argparse parser = argparse.ArgumentParser() parser.add_argument('bar') parser.parse_args(['XXX']) # outputs: Namespace(bar='XXX') What kind of object is Namespace(bar='XXX')? I find this totally confusing. Reading the argparse docs, it says "Most ArgumentParser actio...
Samwise's answer is very good, but let me answer the other part of the question. Or how can I introspect it? Being able to introspect objects is a valuable skill in any language, so let's approach this as though Namespace is a completely unknown type. >>> obj = parser.parse_args(['XXX']) # outputs: Namespace(bar='XXX...
15
15
71,499,349
2022-3-16
https://stackoverflow.com/questions/71499349/type-hinting-for-array-like
What would be the correct type hint for a function that accepts an one dimensional array-like object? More specifically, my function uses np.percentile and I would like to 'match' np.percentile's flexibility in terms of the kind of array it accepts (List, pandas Series, numpy array, etc.). Below illustrates what I'm lo...
Use numpy.typing.ArrayLike: from numpy.typing import ArrayLike def foo(arr: ArrayLike) -> float: p = np.percentile(arr, 50) return p
6
13
71,497,906
2022-3-16
https://stackoverflow.com/questions/71497906/python-sum-values-in-a-list-if-they-share-the-first-word
I have a list as follows, flat_list = ['hello,5', 'mellow,4', 'mellow,2', 'yellow,2', 'yellow,7', 'hello,7', 'mellow,7', 'hello,7'] I would like to get the sum of the values if they share the same word, so the output should be, desired output: l = [('hello',19), ('yellow', 9), ('mellow',13)] so far, I have tried the ...
Here is a variant for accomplishing your goal using defaultdict: from collections import defaultdict t = ['hello,5', 'mellow,4', 'mellow,2', 'yellow,2', 'yellow,7', 'hello,7', 'mellow,7', 'hello,7'] count = defaultdict(int) for name_number in t: name, number = name_number.split(",") count[name] += int(number) You coul...
5
9
71,496,253
2022-3-16
https://stackoverflow.com/questions/71496253/pandas-color-cell-based-on-value-of-other-column
I would like to color in red cells of a DataFrame on one column, based on the value of another column. Here is an example: df = pd.DataFrame([ { 'color_A_in_red': True , 'A': 1 }, { 'color_A_in_red': False , 'A': 2 }, { 'color_A_in_red': True , 'A': 2 }, ]) should give: I know how to color a cell of a df in red but o...
Use custom function for DataFrame of styles is most flexible solution here: def highlight(x): c = f"background-color:red" #condition m = x["color_A_in_red"] # DataFrame of styles df1 = pd.DataFrame('', index=x.index, columns=x.columns) # set columns by condition df1.loc[m, 'A'] = c return df1 df.style.apply(highlight, ...
5
5
71,491,107
2022-3-16
https://stackoverflow.com/questions/71491107/formatting-guidelines-for-type-aliases
What would be the correct way to format the name of a type alias—intended to be local to its module—according to the PEP8 style guide? # mymodule.py from typing import TypeAlias mytype: TypeAlias = int def f() -> mytype: return mytype() def g() -> mytype: return mytype() Should mytype be formatted in CapWords because ...
The PEP Style Guide does not have any explicit guidance on how to format TypeAliases. The guide does contain some rules on type variables, but that's not quite what you're asking for. The next best resource I could find was Google's Python Style Guide, which does happen to contain some guidance on how to name TypeAlia...
9
7
71,429,711
2022-3-10
https://stackoverflow.com/questions/71429711/how-to-run-a-docker-container-with-specific-gpus-using-docker-sdk-for-python
In the command line I am used to run/create containers with specific GPUs using the --gpus argument: docker run -it --gpus '"device=0,2"' ubuntu nvidia-smi The Docker SDK for Python documentation was not very helpful and I could not find a good explanation on how to do the same with the python SDK. Is there a way to do...
This is how you can run/create docker containers with specific GPUs using the Docker SDK for Python: client.containers.run('ubuntu', "nvidia-smi", device_requests=[ docker.types.DeviceRequest(device_ids=['0','2'], capabilities=[['gpu']])]) This way you can also use other GPU resource options specified here: https://do...
10
15
71,467,630
2022-3-14
https://stackoverflow.com/questions/71467630/fastapi-issues-with-mongodb-typeerror-objectid-object-is-not-iterable
I am having some issues inserting into MongoDB via FastAPI. The below code works as expected. Notice how the response variable has not been used in response_to_mongo(). The model is an sklearn ElasticNet model. app = FastAPI() def response_to_mongo(r: dict): client = pymongo.MongoClient("mongodb://mongo:27017") db = cl...
As per the documentation: When a document is inserted a special key, "_id", is automatically added if the document doesn’t already contain an "_id" key. The value of "_id" must be unique across the collection. insert_one() returns an instance of InsertOneResult. For more information on "_id", see the documentation on ...
7
15
71,416,383
2022-3-9
https://stackoverflow.com/questions/71416383/python-asyncio-cancelling-a-to-thread-task-wont-stop-the-thread
With the following snippet, I can't figure why the infiniteTask is not cancelled (it keeps spamming "I'm still standing") In debug mode, I can see that the Task stored in unfinished is indeed marked as Cancelled but obiously the thread is not cancelled / killed. Why is the thread not killed when the wrapping task is ca...
Cause If we check the definition of asyncio.to_thread(): # python310/Lib/asyncio/threads.py # ... async def to_thread(func, /, *args, **kwargs): """Asynchronously run function *func* in a separate thread. Any *args and **kwargs supplied for this function are directly passed to *func*. Also, the current :class:`contextv...
5
10
71,443,345
2022-3-11
https://stackoverflow.com/questions/71443345/gevent-cant-be-installed-on-m1-mac-using-poetry
I tried to install many dependencies for a virtual environment using poetry. When it gets to gevent (20.9.0) it gets the following import error: ImportError: dlopen(/private/var/folders/21/wxg5bdsj1w3f3j_9sl_pktbw0000gn/T/pip-build-env-50mwte36/overlay/lib/python3.8/site-packages/_cffi_backend.cpython-38-darwin.so, 0x0...
I've have this problem with other libraries also and this solution worked some times: arch -arm64 <poetry or pip> install <lib to istall> Using arch -arm64 allowed me to install the rigt wheel for the M1 processor
5
7
71,486,019
2022-3-15
https://stackoverflow.com/questions/71486019/how-to-drop-row-in-polars-python
How to add new feature like length of data frame & Drop rows value using indexing. I want to a add a new column where I can count the no-of rows available in a data frame, & using indexing drop rows value. for i in range(len(df)): if (df['col1'][i] == df['col2'][i]) and (df['col4'][i] == df['col3'][i]): pass elif (df['...
Polars doesn't allow much mutation and favors pure data handling. Meaning that you create a new DataFrame instead of modifying an existing one. So it helps to think of the data you want to keep instead of the row you want to remove. Below I have written an example that keeps all data except for the 2nd row. Note that t...
13
18
71,470,614
2022-3-14
https://stackoverflow.com/questions/71470614/make-pathlib-glob-and-pathlib-rglob-case-insensitive-for-platform-agnostic-a
I am using pathlib.glob() and pathlib.rglob() to matching files from a directory and its subdirectories, respectively. Target files both are both lower case .txt and upper case .TXT files. According file paths were read from the filesystem as follows: import pathlib directory = pathlib.Path() files_to_create = ['a.txt'...
What about something like: suffix = '*.[tT][xX][tT]' files = [fp.relative_to(directory) for fp in directory.glob(suffix)] It is not so generalizable for a "case-insensitive glob", but it works well for limited and specific use-case like your glob of a specific extension.
8
6
71,475,054
2022-3-14
https://stackoverflow.com/questions/71475054/structured-bindings-in-python
C++17 introduced the new structured bindings syntax: std::pair<int, int> p = {1, 2}; auto [a, b] = p; Is there something similar in python3? I was thinking of using the "splat" operator to bind class variables to a list, which can be unpacked and assigned to multiple variables like such: class pair: def __init__(self,...
Yes, you can use __iter__ method since iterators can be unpacked too: class pair: def __init__(self, first, second): self.first = first self.second = second def __iter__(self): # Use tuple's iterator since it is the closest to our use case. return iter((self.first, self.second)) p = pair(1, 2) a, b = p print(a, b) # Pr...
4
6
71,467,768
2022-3-14
https://stackoverflow.com/questions/71467768/programmatically-schedule-an-aws-lambda-for-one-time-execution
I have two AWS-Lamdbda functions and I want Lambda A to determine a certain point in time like the 4. May 2022 10:00. Then I want Lambda B to be scheduled to run at this specific point in time. I'm probably able to achieve this by programmatically creating a AWS eventbrigde rule with Lambda A and use the cron pattern t...
[Edit Nov 2022]: EventBridge Scheduler The new EventBridge Scheduler supports one-time schedules for events. The event will be invoked on the date and time you pass as the schedule expression: at(yyyy-mm-ddThh:mm:ss) in the boto3 EventScheduler client's create_schedule API. Here are a few more options to schedule a La...
5
10
71,435,874
2022-3-11
https://stackoverflow.com/questions/71435874/pip-these-packages-do-not-match-the-hashes-from-the-requirements-file
When I tried to install libraries using pip install, sometimes this error message come up. ERROR: THESE PACKAGES DO NOT MATCH THE HASHES FROM THE REQUIREMENTS FILE. If you have updated the package versions, please update the hashes. Otherwise, examine the package contents carefully; someone may have tampered with them....
So I had the same issue, tried deleting the pip cache file and using the "--no-cache-dir" argument. None of those worked. I then came across a post that said they were experiencing this error because of a networking issue. So I switched off my VPN and everything worked perfectly! Not sure why this works, but it got the...
12
9
71,432,620
2022-3-11
https://stackoverflow.com/questions/71432620/os-path-getsize-slow-on-network-drive-python-windows
I have a program that iterates over several thousand PNG files on an SMB shared network drive (a 2TB Samsung 970 Evo+) and adds up their individual file sizes. Unfortunately, it is very slow. After profiling the code, it turns out 90% of the execution time is spent on one function: filesize += os.path.getsize(png) wher...
I don't know why getsize() is as slow as it is over the network, however to speed it up you could try calling it concurrently: import os from multiprocessing.pool import ThreadPool def get_total_filesize_concurrently(paths): total = 0 with ThreadPool(10) as pool: for size in pool.imap_unordered(lambda path: os.path.get...
6
3
71,470,236
2022-3-14
https://stackoverflow.com/questions/71470236/post-request-response-422-error-detail-loc-body-msg-value-is-n
My POST request continues to fail with 422 response, even though valid JSON is being sent. I am trying to create a web app that receives an uploaded text file with various genetic markers and sends it to the tensorflow model to make a cancer survival prediction. The link to the github project can be found here. Here is...
In Python requests, when sending JSON data using the json parameter, you need to pass a dict object (e.g., json={"RPPA_HSPA1A":30,"RPPA_XIAP":-0.902044768}), which requests will automatically encode into JSON and set the Content-Type header to application/json. In your case, however, as you are using to_json() method, ...
10
10
71,460,894
2022-3-13
https://stackoverflow.com/questions/71460894/bayesianoptimization-fails-due-to-float-error
I want to optimize my HPO of my lightgbm model. I used a Bayesian Optimization process to do so. Sadly my algorithm fails to converge. MRE import warnings import pandas as pd import time import numpy as np warnings.filterwarnings("ignore") import lightgbm as lgb from bayes_opt import BayesianOptimization import sklearn...
This is related to a change in scipy 1.8.0, One should use -np.squeeze(res.fun) instead of -res.fun[0] https://github.com/fmfn/BayesianOptimization/issues/300 The comments in the bug report indicate reverting to scipy 1.7.0 fixes this, UPDATED: It seems the fix has been merged in the BayesianOptimization package, but t...
4
7
71,453,291
2022-3-12
https://stackoverflow.com/questions/71453291/difference-between-argparse-namespace-and-types-simplenamespace
It seems they both behave exactly the same – both are like dicts but with . literal to access an item, however none of it is even a subclass of another from argparse import Namespace from types import SimpleNamespace issubclass(Namespace, SimpleNamespace) # False issubclass(SimpleNamespace, Namespace) # False So, are ...
There once was a proposal to have the argparse inherit. That said, just use the types one if you are using a new enough Python; that's what it is there for.
6
5
71,412,499
2022-3-9
https://stackoverflow.com/questions/71412499/how-to-prevent-keras-from-computing-metrics-during-training
I'm using Tensorflow/Keras 2.4.1 and I have a (unsupervised) custom metric that takes several of my model inputs as parameters such as: model = build_model() # returns a tf.keras.Model object my_metric = custom_metric(model.output, model.input[0], model.input[1]) model.add_metric(my_metric) [...] model.fit([...]) # tra...
I think that the simplest solution to compute a metric only on the validation is using a custom callback. here we define our dummy callback: class MyCustomMetricCallback(tf.keras.callbacks.Callback): def __init__(self, train=None, validation=None): super(MyCustomMetricCallback, self).__init__() self.train = train self....
8
3
71,423,641
2022-3-10
https://stackoverflow.com/questions/71423641/create-complex-object-in-python-based-on-property-names-in-dot-notation
I am trying to create a complex object based on metadata I have. It is an array of attributes which I am iterating and trying to create a dict. For example below is the array: [ "itemUniqueId", "itemDescription", "manufacturerInfo[0].manufacturer.value", "manufacturerInfo[0].manufacturerPartNumber", "attributes.noun.va...
There's a similar question at Convert Dot notation string into nested Python object with Dictionaries and arrays where the accepted answer works for this question, but has unused code paths (e.g. isInArray) and caters to unconventional conversions expected by that question: ❓ "arrOne[0]": "1,2,3" → "arrOne": ["1", "2"...
4
2
71,446,065
2022-3-12
https://stackoverflow.com/questions/71446065/how-to-output-shap-values-in-probability-and-make-force-plot-from-binary-classif
I need to plot how each feature impacts the predicted probability for each sample from my LightGBM binary classifier. So I need to output Shap values in probability, instead of normal Shap values. It does not appear to have any options to output in term of probability. The example code below is what I use to generate d...
TL;DR: You can achieve plotting results in probability space with link="logit" in the force_plot method: import pandas as pd import numpy as np import shap import lightgbm as lgbm from sklearn.model_selection import train_test_split from sklearn.datasets import load_breast_cancer from scipy.special import expit shap.in...
7
10
71,486,742
2022-3-15
https://stackoverflow.com/questions/71486742/dask-dataframe-to-parquet-fails-on-read-repartition-write-operation
I have the following workflow. def read_file(path, indx): df = pd.read_parquet(path) df.index = [indx] * len(df) return df files_list = get_all_files() # list of 10k parquet files, each about 1MB df = dask.dataframe.from_delayed([dask.delayed(read_file)(x, indx) for (indx, x) in enumerate(files_list)]) df.divisions = l...
Use dask.dataframe.read_parquet or other dask I/O implementations, not dask.delayed wrapping pandas I/O operations, whenever possible. Giving dask direct access to the file object or filepath allows the scheduler to quickly assess the steps in the job and accurately estimate the job size & requirements without executin...
4
5
71,439,124
2022-3-11
https://stackoverflow.com/questions/71439124/google-protobuf-message-decodeerror-error-parsing-message-with-type-tensorflow
I was training the model and saved it, now I am trying to load but unable to do. I have seen in previous post as well, but some reference links are not working or some things I tried, still not able to solve the problem. Code snippet: #load model with tf.io.gfile.GFile(args.model, "rb") as f: graph_def = tf.compat.v1.G...
BG: I was getting errors while testing the code. In my case, it was solved with the help of freeze.py and a few modifications in the training file. And I found some other useful links while searching query. Link 1 Link 2
6
2
71,479,069
2022-3-15
https://stackoverflow.com/questions/71479069/exec-python-executable-file-not-found-in-path
since the last update to Mac OS Monterey 12.3 I get the following error message when compiling my Arduino sketch: exec: "python": executable file not found in $PATH Unfortunately, I have not yet been able to find out how to solve this problem. I would be very grateful for ideas and suggestions.
Problem In MacOS 12.3 Apple removed python2.7 (python) from MacOS. Solution What I did to solve this is link python3 to python, I wouldn't recommend it because it's sus, I would recommend you wait until Arduino IDE fixes this issue in a later build. For the time being, you could try their Web IDE: Arduino Editor Howeve...
6
16
71,483,248
2022-3-15
https://stackoverflow.com/questions/71483248/comment-color-based-on-keyword-in-pycharm
PyCharm has a feature that colors your comments yellow if they include TODO or FIXME keywords. What is the way to add more keywords to the list and change the colors based on the keyword? Example:
In PyCharm: Press CTRL+ALT+S or navigate to Preferences/Settings Search TODO or go to Editor/TODO Add a pattern using the + button. For example, the pattern for ERROR keyword would be \berror\b.*. It can also be any other regex pattern. \b - word boundaries; .* - zero or more characters. Unselect Use color scheme TODO...
6
9
71,425,861
2022-3-10
https://stackoverflow.com/questions/71425861/connecting-to-user-dbus-as-root
If we open a python interpreter normally and enter the following: import dbus bus = dbus.SessionBus() bus.list_names() We see all the services on the user's session dbus. Now suppose we wanted to do some root-only things in the same script to determine information to pass through dbus, so we run the interpreter with s...
I have little knowledge about DBus, but that question got me curious. TL;DR: Use dbus.bus.BusConnection with the socket address for the target user and seteuid for gaining access. First question: What socket does DBus connect to for the session bus? $ cat list_bus.py import dbus print(dbus.SessionBus().list_names()) $ ...
4
9
71,489,011
2022-3-15
https://stackoverflow.com/questions/71489011/attributeerror-dataframe-object-has-no-attribute-to-sparse
sdf = df.to_sparse() has been deprecated. What's the updated way to convert to a sparse DataFrame?
These are the updated sparse conversions in pandas 1.0.0+. How to convert dense to sparse Use DataFrame.astype() with the appropriate SparseDtype() (e.g., int): >>> df = pd.DataFrame({'A': [1, 0, 0, 0, 1, 0]}) >>> df.dtypes # A int64 # dtype: object >>> sdf = df.astype(pd.SparseDtype(int, fill_value=0)) >>> sdf.dtypes...
4
10
71,418,682
2022-3-10
https://stackoverflow.com/questions/71418682/skip-first-line-in-import-statement-using-gc-open-by-url-from-gspread-i-e-add
What is the equivalent of header=0 in pandas, which recognises the first line as a heading in gspread? pandas import statement (correct) import pandas as pd # gcp / google sheets URL df_URL = "https://docs.google.com/spreadsheets/d/1wKtvNfWSjPNC1fNmTfUHm7sXiaPyOZMchjzQBt1y_f8/edit?usp=sharing" raw_dataset = pd.read_csv...
Looking at the API documentation, you probably want to use: df = pd.DataFrame(g_sheets.get_worksheet(0).get_all_records(head=1)) The .get_all_records method returns a dictionary of with the column headers as the keys and a list of column values as the dictionary values. The argument head=<int> determines which row to ...
6
2
71,489,687
2022-3-15
https://stackoverflow.com/questions/71489687/pypi-the-name-is-too-similar-to-an-existing-project
When uploading to PyPI there is an error: $ twine upload -r test dist/examplepkg-1.0.tar.gz Uploading distributions to https://test.pypi.org/legacy/ Uploading examplepkg-1.0.tar.gz Error during upload. Retry with the --verbose option for more details. HTTPError: 400 Bad Request from https://test.pypi.org/legacy/ The na...
There is no direct way of knowing which exact package causes the name conflict, but here are some tips that may help you further in your search. First of all, you can find the source code of pypi (called warehouse) at https://github.com/pypa/warehouse/. Using the error message you gave, you can find that the failing ch...
4
10
71,486,255
2022-3-15
https://stackoverflow.com/questions/71486255/how-can-i-make-python-re-work-like-grep-for-repeating-groups
I have the following string: seq = 'MNRYLNRQRLYNMYRNKYRGVMEPMSRMTMDFQGRYMDSQGRMVDPRYYDHYGRMHDYDRYYGRSMFNQGHSMDSQRYGGWMDNPERYMDMSGYQMDMQGRWMDAQGRYNNPFSQMWHSRQGH' also saved in a file called seq.dat. If I use the following grep command grep '\([MF]D.\{4,6\}\)\{3,10\}' seq.dat I get the following matching string: MDNPER...
There is a fundamental difference between POSIX ("text-directed") and NFA ("regex-directed") engines. POSIX engines (grep here uses a POSIX BRE regex flavor, it is the flavor used by default) will parse the input text applying the regex to it and return the longest match possible. NFA engine (Python re engine is an NFA...
6
5
71,454,563
2022-3-13
https://stackoverflow.com/questions/71454563/visual-studio-code-intellisense-not-working-on-ssh-server-even-though-its-ins
So for some reason my intellisense is not working. I tried the solutions suggested here Visual Studio Code: Intellisense not working. The solution that seems to help most people is adding "python.autoComplete.extraPaths": [ "${workspaceFolder}/customModule" ], didn't work. Also VS Code says it doesn't recognize python....
the first solutions are kind of obvious, but ill add them anyway, Removing reinstalling it both locally and remotely Make sure VS code is updated to its last version In settings.json, set a language server in "python.languageServer". The Language Server includes: Jedi(build-in Python extension ), Microsoft, Pylance, s...
6
8
71,482,512
2022-3-15
https://stackoverflow.com/questions/71482512/selenium-executable-path-has-been-deprecated
When running my code I get the below error string, <string>:36: DeprecationWarning: executable_path has been deprecated, please pass in a Service object What could possibly be the issue? Below is the Selenium setup, options = webdriver.ChromeOptions() prefs = {"download.default_directory" : wd} options.add_experimenta...
This error message DeprecationWarning: executable_path has been deprecated, please pass in a Service object means that the key executable_path will be deprecated in the upcoming releases. Once the key executable_path is deprecated you have to use an instance of the Service() class as follows: from selenium import web...
4
4
71,452,013
2022-3-12
https://stackoverflow.com/questions/71452013/does-python-not-reuse-memory-here-what-does-tracemallocs-output-mean
I create a list of a million int objects, then replace each with its negated value. tracemalloc reports 28 MB extra memory (28 bytes per new int object). Why? Does Python not reuse the memory of the garbage-collected int objects for the new ones? Or am I misinterpreting the tracemalloc results? Why does it say those nu...
Short Answer tracemalloc was started too late to track the inital block of memory, so it didn't realize it was a reuse. In the example you gave, you free 27999860 bytes and allocate 27999860 bytes, but tracemalloc can't 'see' the free. Consider the following, slightly modified example: import tracemalloc tracemalloc.st...
6
9
71,471,449
2022-3-14
https://stackoverflow.com/questions/71471449/using-scikit-learn-preprocesser-to-select-subset-of-rows-in-pandas-dataframe
Is there a scikit-learn preprocesser I can use or implement to select a subset of rows from a pandas dataframe? I would prefer a preprocesser to do this since I want to build a pipeline with this as a step.
You can use a FunctionTransformer to do that. To a FunctionTransformer, you can pass any Callable that exposes the same interface as standard scikitlearn transform calls have. In code import pandas as pd from sklearn.preprocessing import FunctionTransformer class RowSelector: def __init__(self, rows:list[int]): self._r...
6
5
71,425,968
2022-3-10
https://stackoverflow.com/questions/71425968/remove-horizontal-lines-with-open-cv
I am trying to remove horizontal lines from my daughter's drawings, but can't get it quite right. The approach I am following is creating a mask with horizontal lines (https://stackoverflow.com/a/57410471/1873521) and then removing that mask from the original (https://docs.opencv.org/3.3.1/df/d3d/tutorial_py_inpainting...
So, I saw that working on the drawing separated from the paper would lead to a better result. I used MORPH_CLOSE to work on the paper and MORPH_OPEN for the lines in the inner part. I hope your daughter likes it :) img = cv2.imread(r'E:\Downloads\i0RDA.jpg') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Remove horizon...
12
14
71,462,024
2022-3-14
https://stackoverflow.com/questions/71462024/how-to-handle-chromium-microphone-permission-pop-ups-in-playwright
What I'm trying to do Test a website that requires microphone access with playwright The problem Pop-up in question comes up and seems to ignore supposedly granted permissions. Permission can be given manually, but this seems against the spirit of automation. What I tried with sync_playwright() as p: browser = p.chrom...
You're missing some command line flags that tell chrome to simulate having a microphone. Give this sample a shot. from playwright.sync_api import sync_playwright def run(playwright): chromium = playwright.chromium browser = chromium.launch(headless=False, args=['--use-fake-device-for-media-stream', '--use-fake-ui-for-m...
6
6
71,423,949
2022-3-10
https://stackoverflow.com/questions/71423949/azure-pipelines-proper-way-to-use-poetry
what would be a recommended way to install your Python's package dependencies with poetry for Azure Pipelines? I see people only downloading poetry through pip which is a big no-no. - script: | python -m pip install -U pip pip install poetry poetry install displayName: Install dependencies I can use curl to download p...
Consulted this issue with a collegue. He recommended doing separate step to add Poetry to the PATH. - task: UsePythonVersion@0 inputs: versionSpec: '3.8' displayName: 'Use Python 3.8' - script: | curl -sSL https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py | python - export PATH=$PATH:$HOME/.p...
7
9
71,460,471
2022-3-13
https://stackoverflow.com/questions/71460471/improve-quality-of-extracted-image-in-opencv
#Segmenting the red pointer img = cv2.imread('flatmap.jpg') hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) lower_red = np.array([140, 110, 0]) upper_red = np.array([255, 255 , 255]) # Threshold with inRange() get only specific colors mask_red = cv2.inRange(hsv, lower_red, upper_red) # Perform bitwise operation with the mas...
I've looked at the channels in HSL/HSV space. The arrows are the only stuff in the picture that has any saturation. That would be one required (but insufficient) aspect to get a lock on the desired arrow. I've picked those pixels and they appear to have a bit more than 50% saturation, so I'll use a lower bound of 25% (...
5
0
71,464,757
2022-3-14
https://stackoverflow.com/questions/71464757/what-does-sa-relationship-kwargs-lazy-selectin-means-on-sqlmodel-with-f
I'm trying to use SQLModel with Fastapi, and on the way I found this example for implementing entities relationships, and I would like to know what does sa_relationship_kwargs={"lazy": "selectin"} means and what does it do? class UserBase(SQLModel): first_name: str last_name: str email: EmailStr = Field(nullable=True, ...
It chooses the relationship loading technique that SQLAlchemy should use. The loading of relationships falls into three categories; lazy loading, eager loading, and no loading. Lazy loading refers to objects are returned from a query without the related objects loaded at first. When the given collection or reference i...
5
11
71,460,911
2022-3-13
https://stackoverflow.com/questions/71460911/moving-python-venv-to-another-machine-without-internet
I am trying to deploy a Python project to a machine with no internet. Because it has no internet, I cannot pip install any packages with a requirements.txt file. I am wondering if it is possible to move my existing environment with all installed packages into another machine with all packages pre-installed. I can also ...
On you local machine (adapt the instructions if you are on Windows) Create your requirements.txt file (venv) [...]$ mkdir pkgs (venv) [...]$ cd pkgs (venv) [...]$ pip freeze > requirements.txt (venv) [...]$ pip download -r requirements.txt Download pip archive from here Copy pkgs folder to the remote machine On ...
4
12
71,456,305
2022-3-13
https://stackoverflow.com/questions/71456305/is-there-a-way-to-replace-the-end-of-a-string-starting-at-a-given-substring
I have the string banana | 10 and want to replace everything from | to the end of the string with 9. The output I want would be banana | 9. How could I achieve this? I've looked into .replace(), .split() and converting the string into a list of characters, and looping over them until I find the bit that should be repl...
I suggest you use re module(regex module): import re myString = "banana | 10" re.sub(r"\|.+", r"| 9", myString) Output banana | 9
4
5
71,455,443
2022-3-13
https://stackoverflow.com/questions/71455443/python-convert-json-to-table-structure
I have a JSON with the following structure below into a list in a python variable. I'd like to extract this JSON value as a table. My question is, how can I extract it from the list and how can I change it into a table? Once I have converted it, I will insert the output into a Postgres table. JSON structure [' { "_id":...
Use the code below. I have used PrettyTable module for printing in a table like structure. Use this - https://www.geeksforgeeks.org/how-to-make-a-table-in-python/ for table procedure. Also, all the headers and values will be stored in headers and values variable. import json from prettytable import PrettyTable value = ...
4
6
71,453,766
2022-3-13
https://stackoverflow.com/questions/71453766/how-to-take-a-screenshot-from-part-of-screen-with-mss-python
I have a simple code here: import mss with mss.mss() as sct: filename = sct.shot(output="result.png") result.png But I want to take a part of screen like this: Thanks for help!
As explained on https://python-mss.readthedocs.io/examples.html, something like this should work: with mss.mss() as sct: # The screen part to capture monitor = {"top": 160, "left": 160, "width": 160, "height": 135} output = "sct-{top}x{left}_{width}x{height}.png".format(**monitor) # Grab the data sct_img = sct.grab(mon...
7
6
71,444,328
2022-3-11
https://stackoverflow.com/questions/71444328/can-i-initialize-a-pydantic-model-using-the-unaliased-attribute-name
I'm working with an API where the schema for creating a group is effectively: class Group(BaseModel): identifier: str I was hoping I could do this instead: class Group(BaseModel): groupname: str = Field(..., alias='identifier') But with that configuration it's not possible to set the attribute value using the name gr...
Maybe you are looking for the allow_population_by_field_name config option: whether an aliased field may be populated by its name as given by the model attribute, as well as the alias (default: False) from pydantic import BaseModel, Field class Group(BaseModel): groupname: str = Field(..., alias='identifier') class C...
5
7
71,445,570
2022-3-11
https://stackoverflow.com/questions/71445570/running-pre-commit-python-package-in-windows-gives-executablenotfounderror-exec
I am working on a project where pre-commit==2.15.0 was added to the python requirements file. I installed the requirements. Now when I try to do a git commit I get the following error: An unexpected error has occurred: ExecutableNotFoundError: Executable `/bin/sh` not found Check the log at C:\Users\username\.cache\pre...
your previous git hook is using a non-portable shebang (#!/bin/sh) (in your case this file will be located at .git/hooks/pre-commit.legacy -- originally .git/hooks/pre-commit) if you adjust the tool to use #!/usr/bin/env sh then pre-commit will be able to run it (even on windows) alternatively, if you don't want to use...
5
10
71,441,761
2022-3-11
https://stackoverflow.com/questions/71441761/how-to-use-match-case-with-a-class-type
I want to use match to determine an action to perform based on a class type. I cannot seem to figure out how to do it. I know their are other ways of achieving this, I would just like to know can it be done this way. I am not looking for workarounds of which there are many. class aaa(): pass class bbb(): pass def f1(t...
Try using typ() instead of typ in the match line: class aaa(): pass class bbb(): pass def f1(typ): if typ is aaa: print("aaa") elif typ is bbb: print("bbb") else: print("???") def f2(typ): match typ(): case aaa(): print("aaa") case bbb(): print("bbb") case _: print("???") f1(aaa) f1(bbb) f2(aaa) f2(bbb) Output: aaa b...
18
7
71,439,161
2022-3-11
https://stackoverflow.com/questions/71439161/how-to-generate-twitter-api-access-token-and-secret-with-read-write-permission
I just created twitter api with elevated access but I can't generate access token with write permission. I need this permission to update my twitter name.
App settings -> User authentication Settings -> Edit. Enable OAuth 1.0A -> App permissions Read and Write Callback URL can be set to something like http://localhost if you are not going to implement sign-in for other users Website URL set to something valid like your blog ideally, or use http://example.com if you must...
7
19
71,437,278
2022-3-11
https://stackoverflow.com/questions/71437278/after-changing-python-version-3-6-to-3-10-i-got-cannot-import-name-callable-fr
File "C:\Users\Codertjay\PycharmProjects\Teems_App_Kid\teems_app_kid\__init__.py", line 5, in <module> from .celery import app as celery_app File "C:\Users\Codertjay\PycharmProjects\Teems_App_Kid\teems_app_kid\celery.py", line 3, in <module> from celery import Celery File "C:\Users\Codertjay\PycharmProjects\brownie\Te...
The offending line has been removed from Celery nearly 6 years ago. You should update the celery package to a recent version.
5
8
71,433,507
2022-3-11
https://stackoverflow.com/questions/71433507/pytorch-python-distributed-multiprocessing-gather-concatenate-tensor-arrays-of
If you have tensor arrays of different lengths across several gpu ranks, the default all_gather method does not work as it requires the lengths to be same. For example, if you have: if gpu == 0: q = torch.tensor([1.5, 2.3], device=torch.device(gpu)) else: q = torch.tensor([5.3], device=torch.device(gpu)) If I need to ...
As it is not directly possible to gather using built in methods, we need to write custom function with the following steps: Use dist.all_gather to get sizes of all arrays. Find the max size. Pad local array to max size using zeros/constants. Use dist.all_gather to get all padded arrays. Unpad the added zeros/constants...
4
6
71,431,565
2022-3-10
https://stackoverflow.com/questions/71431565/syntax-for-returning-the-entire-list-when-using-the-minus-sign
Python lists have nifty indexing/slicing capabilities. Here are several examples: x = "123456" x[:-3] '123' x[:-1] '12345' # -1 slices off last element x[:-0] # -0 slices off .. everything .. this is what i'd like to fix '' I would like to slice off a variable number of elements d: x[:-d] But if d were 0 we get a muc...
You could use None, which is the default for missing start/stop/step values: x[:-d or None]
5
6
71,416,149
2022-3-9
https://stackoverflow.com/questions/71416149/modifying-the-signature-and-defaults-of-a-python-function-the-hack-way
I'm trying to understand the python data model better and ran into something odd. def foo(a, b = 2): return a / b assert foo(20) == 10.0 # note: for sanity purposes, should also change signature, but not needed for effect foo.__defaults__ = (10,) assert foo(20) == 2.0 foo.__defaults__ = () foo.__kwdefaults__ = {'b': 10...
Purpose of __signature__ Your issue is, that you think that you change a function's signature by setting foo.__signature__. However, this is not what's happening. It is equally useless to set it to foo.signature or foo.any_other_name. You just set a signature object to the respective property of the function, which cha...
7
6
71,424,233
2022-3-10
https://stackoverflow.com/questions/71424233/how-do-i-list-my-scheduled-queries-via-the-python-google-client-api
I have set up my service account and I can run queries on bigQuery using client.query(). I could just write all my scheduled queries into this new client.query() format but I already have many scheduled queries so I was wondering if there is a way I can get/list the scheduled queries and then use that information to ru...
Yes, you can use the APIs. When you don't know which one to use, I have a tip. Use the command proposed by @Yev bq ls --transfer_config --transfer_location=US --format=prettyjson But log the API calls. for that use the --apilog <logfile name> parameter like that bq --apilog ./log ls --transfer_config --transfer_locatio...
6
6
71,424,546
2022-3-10
https://stackoverflow.com/questions/71424546/combine-2-kde-functions-in-one-plot-in-seaborn
I have the following code for plotting the histogram and the kde-functions (Kernel density estimation) of a training and validation dataset: #Plot histograms import matplotlib.pyplot as plt import matplotlib import seaborn as sns displot_dataTrain=sns.displot(data_train, bins='auto', kde=True) displot_dataTrain._legend...
sns.displot() returns a FacetGrid. That doesn't work as input for ax.plot(). Also, displot_dataTest.kde.pdf is never valid. However, you can write sns.kdeplot(data=data_train, ax=ax[0]) to create a kdeplot inside the first subplot. See the docs; note the optional parameters cut= and clip= that can be used to adjust the...
4
7
71,416,368
2022-3-9
https://stackoverflow.com/questions/71416368/display-an-image-with-transparency-and-no-background-or-window-in-python
I'm trying to display an image on the screen, without any window/application popping up/containing it. I'm pretty close with TKinter, but the method for removing the background color of the canvas is hacky and has some undesired effects. import tkinter as tk import ctypes user32 = ctypes.windll.user32 screen_size = use...
Thanks to the suggestion from Kartikeya, I was able to solve my own question. Using PyQt5, this code will display an image with transparency and no border or background at all import sys from PyQt5.QtCore import Qt from PyQt5.QtGui import QPixmap from PyQt5.QtWidgets import QMainWindow, QApplication, QLabel app = QAppl...
6
6
71,413,808
2022-3-9
https://stackoverflow.com/questions/71413808/understanding-xarray-apply-ufunc
I have an xarray with multiple time dimensions slow_time, fast_time a dimension representing different objects object and a dimension reflecting the position of each object at each point in time coords. The goal is now to apply a rotation using scipy.spatial.transform.Rotation to each position in this array, for every ...
Reference First off, a helpful reference would be this documentation page on unvectorized ufunc Solution As I understand your question you want to apply a rotation to the position vector of each object at every time. The way you have set up your data already puts the coordinates as the final dimension of the array. Tra...
6
5
71,420,828
2022-3-10
https://stackoverflow.com/questions/71420828/custom-python-module-in-azure-databricks-with-spark-dbutils-dependencies
I recently swicthed on the preview feature "files in repos" on Azure Databricks, so that I could move a lot of my general functions from notebooks to modules and get rid of the overhead from running a lot of notebooks for a single job. However, several of my functions rely directly on dbutils or spark/pyspark functions...
The documentation for Databricks Connect shows the example how it could be achieved. That example has SparkSession as an explicit parameter, but it could be modified to avoid that completely, with something like this: def get_dbutils(): from pyspark.sql import SparkSession spark = SparkSession.getActiveSession() if spa...
6
11
71,420,605
2022-3-10
https://stackoverflow.com/questions/71420605/is-there-a-numpy-magic-avoiding-these-loops
I would like to avoid for loops in this code snippet: import numpy as np N = 4 a = np.random.randint(0, 256, size=(N, N, 3)) m = np.random.randint(0, 2, size=(N, N)) for i, d0 in enumerate(a): for j, d1 in enumerate(d0): if m[i, j]: d1[2] = 42 This is a simplified example where a is an N x N RGB image and m is a N x N...
You can index the last axis and set the elements selected by a boolean mask import numpy as np N = 4 a = np.random.randint(0, 256, size=(N, N, 3)) m = np.random.randint(0, 2, size=(N, N)) a[...,2][m.astype('bool')] = 42 a Output (for a random example of a) array([[[ 9, 13, 4], [15, 0, 42], [11, 12, 9], [13, 0, 42]], [...
4
4
71,420,362
2022-3-10
https://stackoverflow.com/questions/71420362/django4-0-importerror-cannot-import-name-ugettext-lazy-from-django-utils-tra
I use translation in my Django apps. Since I installed Django version 4, when I try to import ugettexget_lazy as shown in the code below from django.utils.translation import ugettexget_lazy as _ I get the following error: ImportError: cannot import name 'ugettext_lazy' from 'django.utils.translation'
It was removed from Django 4, use this instead from django.utils.translation import gettext_lazy as _
8
17
71,416,759
2022-3-9
https://stackoverflow.com/questions/71416759/i-want-to-run-a-python-script-on-a-server-24-7
I am making a program that simulates a stock market for a virtual currency. I have not tried anything yet, but I want a Python script to run 24/7 online for a long period of time. The python script should be something like this: import time import random while True: number = random.randint(0,5) print(number) time.sleep...
If you really want to just simulate it and there is only one user. You can just return a random number each time the user make a query. It’s irrelevant how often they query it. You can put this up locally or on heroic free plan. But the fact that the user is querying every 2 seconds means lots of requests and so you ma...
5
1
71,410,741
2022-3-9
https://stackoverflow.com/questions/71410741/pip-uninstall-gdal-gives-attributeerror-pathmetadata-object-has-no-attribute
I'm trying to pip install geopandas as a fresh installation, so I want to remove existing packages like GDAL and fiona. I've already managed to pip uninstall fiona, but when I try to uninstall or reinstall GDAL it gives the following error message: (base) C:\usr>pip install C:/usr/Anaconda3/Lib/site-packages/GDAL-3.4.1...
I just came across this question after getting the same error. Coincidentally I had just upgraded pip (I was getting tired of the yellow warnings). All I had was to down grade my pip pip install pip==21.3.1 --user
8
8
71,413,435
2022-3-9
https://stackoverflow.com/questions/71413435/why-does-floatinf-floatinf-return-true-but-floatinf-floatinf
Why does this happen in Python? float('inf') == float('inf') returns True, float('inf') + float('inf') == float('inf') returns True, float('inf') * float('inf') == float('inf') returns True, float('inf') - float('inf') == float('inf') returns False, float('inf') / float('inf') == float('inf') returns False. My best g...
Before the comparison of float('inf') - float('inf') == float('inf') can be made, the result of float('inf') - float('inf') will be calculated. That result is NaN. It is NaN because the amounts of infinity may differ. It's explained on the Stack Overflow sister site Math.SE, known as the Hilbert hotel paradox: From ...
4
8
71,409,353
2022-3-9
https://stackoverflow.com/questions/71409353/finding-the-position-of-noun-and-verb-in-a-sentence-python
Is there a way to find the position of the words with pos-tag 'NN' and 'VB' in a sentence in Python? example of a sentences in a csv file: "Man walks into a bar." "Cop shoots his gun." "Kid drives into a ditch"
You can find positions for certein PoS tags on a text using some of the existing NLP frameworks such us Spacy or NLTK. Once you process the text you can iterate for each token and check if the pos tag is what you are looking for, then get the start/end position of that token in your text. Spacy Using spacy, the code to...
6
7
71,404,046
2022-3-9
https://stackoverflow.com/questions/71404046/is-object-object-guaranteed-to-be-false
Suppose I create two instances of class object. Are these two instances guaranteed to be not equal to each other? In other words, is object() == object() guaranteed to be False, or is it implementation-dependent? I understand that object() is object() is guaranteed to be False, but here I am asking about object() == ob...
Yes it is guaranteed that object() == object() is False because it is documented that "by default, object implements __eq__() by using is".
5
10
71,328,869
2022-3-2
https://stackoverflow.com/questions/71328869/what-is-gettext-lazy-on-django-for
I have read on the documentation of Django about gettext_lazy, but there is no clear definition for me about this exact function, and I want to remove it. I found this implementation: from django.utils.translation import gettext_lazy as _ and it is used on a django model field in this way: email = models.EmailField(_(...
Its used for translation for creating translation files like this: # app/locale/cs/LC_MESSAGES/django.po #: templates/app/index.html:3 msgid "email address" msgstr "emailová adresa" Then it can be rendered in template as translated text. Nothing will happen if you remove it and don't want to use multilingualism.
10
19
71,380,919
2022-3-7
https://stackoverflow.com/questions/71380919/polars-return-dataframe-with-all-unique-values-of-n-columns
I have a dataframe that has many rows per combination of the 'PROGRAM', 'VERSION', and 'RELEASE_DATE' columns. I want to get a dataframe with all of the combinations of just those three columns. Would this be a job for groupby or distinct?
Since you are not aggregating anything, use unique df.select('PROGRAM','VERSION','RELEASE_DATE').unique()
6
5
71,325,155
2022-3-2
https://stackoverflow.com/questions/71325155/convert-images-to-pdf-using-img2pdf-package-in-python
I am trying to convert images in folder named Final to one pdf This is my try to achieve the task import os import img2pdf with open("Stickers.pdf","wb") as f: #print(os.listdir("./Final")) f.write(img2pdf.convert([x for x in os.listdir("./Final") if x.endswith(".png")])) But I got an error message like that (any idea...
The error message is cryptic largely because img2pdf bends over backwards to be so versatile about what you can pass to the convert function: a file path (as a string or path object), an open file object, raw image data, multiples of any of those, or a list of any of those. If given a string, it first treats it as a fi...
4
5
71,400,057
2022-3-8
https://stackoverflow.com/questions/71400057/parse-list-of-pydantic-classes-from-list-of-strings
I'd like to parse a Polygon with a list of Points out of the following data: {"points": ["0|0", "1|0", "1|1"]} I naively thought I could do something like this: from pydantic import BaseModel, validator class Point(BaseModel): x: int y: int @validator("x", "y", pre=True) def get_coords(cls, value, values): x, y = valu...
In Pydantic v2.0 it is possible to directly create custom conversions from arbitrary data to a BaseModel. This allows to define the conversion once for the specific BaseModel to automatically make containing classes support the conversion. The trick is to use a @model_validator(mode="before") to parse input before crea...
5
5
71,320,201
2022-3-2
https://stackoverflow.com/questions/71320201/how-to-fix-random-seed-for-bertopic
I'd like to fix the random seed from BERTopic library to get reproducible results. Looking at the code of BERTopic I see it uses numpy. Will using np.random.seed(123) be enough? or do I also need to other libraries as random or pytorch as in this question.
You can fix the random_state variable using UMAP, but you have to also send the other default parameters to the UMAP constructor or the model will break. What this looks like in practice is: umap = UMAP(n_neighbors=15, n_components=5, min_dist=0.0, metric='cosine', low_memory=False, random_state=1337) model = BERTopic(...
7
5
71,344,134
2022-3-3
https://stackoverflow.com/questions/71344134/how-to-list-files-from-a-s3-bucket-folder-using-python
I tried to list all files in a bucket. Here is my code import boto3 s3 = boto3.resource('s3') my_bucket = s3.Bucket('my_project') for my_bucket_object in my_bucket.objects.all(): print(my_bucket_object.key) it works. I get all files' names. However, when I tried to do the same thing on a folder, the code raise an erro...
You can't indicate a prefix/folder in the Bucket constructor. Instead use the client-level API and call list_objects_v2 something like this: import boto3 client = boto3.client('s3') response = client.list_objects_v2( Bucket='my_bucket', Prefix='data/') for content in response.get('Contents', []): print(content['Key']) ...
11
19