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
65,085,956
2020-12-1
https://stackoverflow.com/questions/65085956/pycharm-venv-failed-no-such-option-build-dir
I'm doing a fresh install on a new Windows 10 laptop. I installed Python 3.9 and PyCharm Community 2020.2, then started a new project. In the project settings, I created a new project interpreter in a venv, inside the /venv folder. Everything looks to get set up correctly, but I can't install anything to the project in...
PyCharm relies on --build-dir to install packages and the flag was removed in the latest pip 20.3. The fix for PyCharm is ready and will be released this week in 2020.3 release (and backported to 2020.2.5 and 2020.1.5). The workaround is to downgrade pip to the previous version - close PyCharm and run python -m pip ins...
49
61
65,098,912
2020-12-1
https://stackoverflow.com/questions/65098912/how-to-calculate-the-difference-between-rows-in-pyspark
This is my DataFrame in PySpark: utc_timestamp data feed 2015-10-13 11:00:00+00:00 1 A 2015-10-13 12:00:00+00:00 5 A 2015-10-13 13:00:00+00:00 6 A 2015-10-13 14:00:00+00:00 10 B 2015-10-13 15:00:00+00:00 11 B The values of data are cumulative. I want to get this result (differences between consecutive rows, grouped by...
You can use lag as a substitute for shift, and coalesce( , F.lit(0)) as a substitute for fill_value=0 from pyspark.sql.window import Window import pyspark.sql.functions as F window = Window.partitionBy("feed").orderBy("utc_timestamp") data = F.col("data") - F.coalesce(F.lag(F.col("data")).over(window), F.lit(0)) df.wit...
13
9
65,088,076
2020-12-1
https://stackoverflow.com/questions/65088076/how-to-find-the-current-project-id-of-the-deployed-python-function-in-google-clo
I have deployed a Python 3.7 function in Google Cloud. I need to get the project-id through code to find out where it is deployed. I write a small Python 3.7 script and test it through Google shell command line import urllib import urllib.request url="http://metadata.google.internal/computeMetadata/v1/project/project-i...
In the Python 3.7 runtime, you can get the project ID via an environment variable: import os project_id = os.environ['GCP_PROJECT'] In future runtimes, this environment variable will be unavailable, and you'll need to get the project ID from the metadata server: import urllib.request url = "http://metadata.google.inte...
11
17
65,097,687
2020-12-1
https://stackoverflow.com/questions/65097687/what-is-a-default-transaction-isolation-level-in-sqlalchemy-for-postgres
I use sqlalchemy for Postgres DB. engine = create_engine( "postgresql://postgres:postgres@localhost/test" ... Create engine without Postgres dialect(psycopg2, pg8000, or other). So my question: what is a default transaction isolation level? And what is a default Postgres dialect?
Per the docs, the default postgres driver used by SQLAlchemy is psycopg2. The default transaction isolation level is configured on the DB side, not by the client. Out-of-the-box, it is READ COMMITTED.
5
8
65,093,644
2020-12-1
https://stackoverflow.com/questions/65093644/pandas-group-by-one-column-and-aggregate-other-column-to-list
I have a dataframe that has multiple entries for users. These users can also be assigned to multiple ID's. I would like to group by the users and then store a list of these ID's in another column as shown below: I'd like to go from this: df1 = pd.DataFrame({'USER': ['BOB','STEVE','PAUL','KEITH','STEVE','STEVE','BOB'],'...
groupby + map u = df1.groupby("USER")["ID"].agg(list) df1["MULTI_IDS"] = df1["USER"].map(u[u.str.len().ge(2)]) USER ID MULTI_IDS 0 BOB 1 [1, 7] 1 STEVE 2 [2, 5, 6] 2 PAUL 3 NaN 3 KEITH 4 NaN 4 STEVE 5 [2, 5, 6] 5 STEVE 6 [2, 5, 6] 6 BOB 7 [1, 7]
10
10
65,046,975
2020-11-28
https://stackoverflow.com/questions/65046975/finding-relationships-between-values-based-on-their-name-in-python-with-panda
I want to make relationship between values by their Name based on below rules: 1- I have a CSV file (with more than 100000 rows) that consists of lots of values, I shared some examples as below: Name: A02-father A03-father A04-father A05-father A07-father A08-father A09-father A17-father A18-father A20-father A02-SA-A...
Start with import collections (will be needed soon). I assume that you have already read df and Fa DataFrames. The first part of my code is to create children Series (index - parent, value - child): isFather = df.Name.str.contains('-father', case=False) dfChildren = df[~isFather] key = []; val = [] for fath in df[isFat...
6
3
65,085,780
2020-12-1
https://stackoverflow.com/questions/65085780/what-is-difference-between-keras-backend-tensorflow-and-keras-from-tensorfl
I want to limit CPU cores and threads. So I found three ways to limit these. 1) "Keras backend + Tensorflow" from keras import backend as K import tensorflow as tf config = tf.ConfigProto(intra_op_parallelism_threads=2, \ inter_op_parallelism_threads=4, \ allow_soft_placement=True, \ device_count = {'CPU': 1}) session ...
Not exactly, it's not as simple as that. As per official documentation - intra_op_parallelism_threads - Certain operations like matrix multiplication and reductions can utilize parallel threads for speedups. A value of 0 means the system picks an appropriate number. Refer this inter_op_parallelism_threads - Determines ...
6
2
65,085,181
2020-12-1
https://stackoverflow.com/questions/65085181/adding-df-column-finding-matching-values-in-another-df-for-both-indexed-values-a
Simplified dfs: df = pd.DataFrame( { "ID": [6, 2, 4], "to ignore": ["foo", "whatever", "idk"], "value": ["A", "B", "A"], } ) df2 = pd.DataFrame( { "ID_number": [1, 2, 3, 4, 5, 6], "A": [0.91, 0.42, 0.85, 0.84, 0.81, 0.88], "B": [0.11, 0.22, 0.45, 0.38, 0.01, 0.18], } ) ID to ignore value 0 6 foo A 1 2 whatever B 2 4 id...
You can set ID_number as index in df2,then use pd.Index.get_indexer here. df2 = df2.set_index('ID_number') r = df2.index.get_indexer(df['ID']) c = df2.columns.get_indexer(df['value']) df['new_col'] = df2.values[r, c] df ID to ignore value new_col 0 6 foo A 0.88 1 2 whatever B 0.22 2 4 idk A 0.84 Timeits Benchmarked us...
9
4
65,084,389
2020-12-1
https://stackoverflow.com/questions/65084389/why-am-i-blocked-from-using-the-discord-api
Im coding a discord bot and I got this error randomly. From what I can interpret, I am temporarily blocked from discord.py api, but what does the "exceeding rate limits part mean?" discord.errors.HTTPException: 429 Too Many Requests (error code: 0): You are being blocked from accessing our API temporarily due to excee...
Exceeding the rate limit means that the discord API is explicitly telling you that you cannot read any more data from their API for a given amount of time. Looking at their rate limit docs, the rate limit varies depending on the endpoint you're talking to: The HTTP API implements a process for limiting and preventing ...
6
8
65,083,494
2020-12-1
https://stackoverflow.com/questions/65083494/unpack-python-tuple-with-s
I know the canonical way to unpack a tuple is like this a, b, c = (1, 2, 3) # or (a,b,c) = (1, 2, 3) but noticed that you can unpack a tuple like this [a, b, c] = (1, 2, 3) Does the second method incur any extra cost due to some sort of cast or list construction? Is there a way to inspect how the python interpreter i...
No, those are all exactly equivalent. One way to look at this empirically is to use the dis dissasembler: >>> import dis >>> dis.dis("a, b, c = (1, 2, 3)") 1 0 LOAD_CONST 0 ((1, 2, 3)) 2 UNPACK_SEQUENCE 3 4 STORE_NAME 0 (a) 6 STORE_NAME 1 (b) 8 STORE_NAME 2 (c) 10 LOAD_CONST 1 (None) 12 RETURN_VALUE >>> dis.dis("(a, b,...
14
18
65,051,581
2020-11-28
https://stackoverflow.com/questions/65051581/how-to-trigger-lifespan-startup-and-shutdown-while-testing-fastapi-app
Being very new to FastAPI I am strugling to test slightly more difficult code than I saw in the tutorial. I use fastapi_cache module and Redis like this: from fastapi import Depends, FastAPI, Query, Request from fastapi_cache.backends.redis import CACHE_KEY, RedisCacheBackend from fastapi_cache import caches, close_cac...
The point is that httpx does not implement lifespan protocol and trigger startup event handlers. For this, you need to use LifespanManager. Install: pip install asgi_lifespan The code would be like so: import pytest from asgi_lifespan import LifespanManager from httpx import AsyncClient from .main import app @pytest.ma...
5
10
65,076,264
2020-11-30
https://stackoverflow.com/questions/65076264/python-library-for-parsing-code-of-any-language-into-an-ast
I'm looking for a Python library for parsing code into its abstract syntax tree representation. There exists a built-in module, named ast, however, it is only designed for parsing Python code, to my understanding. I'm wondering if there is a similar Python library that suits the same purpose, but works with other progr...
In general, when you need to parse code written in a language, it’s almost always better to use that language instead. For parsing JavaScript from Python, you may want to check out this module, which can be installed using pip and should work well enough.
6
4
65,075,158
2020-11-30
https://stackoverflow.com/questions/65075158/converting-pil-image-to-skimage
I have 2 modules in my project: first works with image in bytes format, second requires skimage object. I need to combine them. I have this code: import io from PIL import Image import skimage.io area = (...) image = Image.open(io.BytesIO(image_bytes)) image = Image.crop(area) image = skimage.io.imread(image) But i ge...
Scikit-image works with images stored as Numpy arrays - same as OpenCV and wand. So, if you have a PIL Image, you can make a Numpy array for scikit-image like this: # Make Numpy array for scikit-image from "PIL Image" na = np.array(YourPILImage) Just in case you want to go the other way, and make a PIL Image from a Nu...
5
12
65,072,296
2020-11-30
https://stackoverflow.com/questions/65072296/django-execute-code-only-for-manage-py-runserver-not-for-migrate-help-e
We are using Django as backend for a website that provides various things, among others using a Neural Network using Tensorflow to answer to certain requests. For that, we created an AppConfig and added loading of this app config to the INSTALLED_APPS in Django's settings.py. This AppConfig then loads the Neural Networ...
I had a similar problem, solved it with checking argv. class SomeAppConfig(AppConfig): def ready(self, *args, **kwargs): is_manage_py = any(arg.casefold().endswith("manage.py") for arg in sys.argv) is_runserver = any(arg.casefold() == "runserver" for arg in sys.argv) if (is_manage_py and is_runserver) or (not is_manage...
6
8
65,071,206
2020-11-30
https://stackoverflow.com/questions/65071206/override-all-python-comparison-methods-in-one-declaration
Suppose you have a simple class like A below. The comparison methods are all virtually the same except for the comparison itself. Is there a shortcut around declaring the six methods in one method such that all comparisons are supported, something like B? I ask mainly because B seems more Pythonic to me and I am surpri...
The functools module provides the total_ordering decorator which is meant to provide all comparison methods, given that you provide at least one from __lt__(), __le__(), __gt__(), or __ge__(). See this answer from Martijn Pieters.
8
7
65,044,430
2020-11-27
https://stackoverflow.com/questions/65044430/plotly-create-a-scatter-with-categorical-x-axis-jitter-and-multi-level-axis
I would like to make a graph with a multi-level x axis like in the following picture: import plotly.graph_objects as go fig = go.Figure() fig.add_trace( go.Scatter( x = [df['x'], df['x1']], y = df['y'], mode='markers' ) ) But also I would like to put jitter on the x-axis like in the next picture: So far I can make e...
Firstly - thanks for the challenge! There aren't many challenging Plotly questions these days. The key elements to creating a scatter graph with jitter are: Using mode: 'box' - to create a box-plot, not a scatter plot. Setting 'boxpoints': 'all' - so all points are plotted. Using 'pointpos': 0 - to center the points o...
15
20
65,061,121
2020-11-29
https://stackoverflow.com/questions/65061121/git-repository-within-docker-python-image
I have a dockerfile, where my image is python:3.7-alpine. In my project, I use a git repository I need to download. Is there any way to do that ? My Dockerfile : FROM python:3.7-alpine ENV DOCKER_APP True COPY requirements.txt . RUN pip install -r requirements.txt COPY . app/ WORKDIR app/ ENTRYPOINT ["python3", "main.p...
add the following to your dockerfile RUN apk update RUN apk add git
8
13
65,059,995
2020-11-29
https://stackoverflow.com/questions/65059995/convert-pyspark-dataframe-into-list-of-python-dictionaries
Hi I'm new to pyspark and I'm trying to convert pyspark.sql.dataframe into list of dictionaries. Below is my dataframe, the type is <class 'pyspark.sql.dataframe.DataFrame'>: +------------------+----------+------------------------+ | title|imdb_score|Worldwide_Gross(dollars)| +------------------+----------+------------...
You can map each row into a dictionary and collect the results: df.rdd.map(lambda row: row.asDict()).collect()
8
9
65,041,691
2020-11-27
https://stackoverflow.com/questions/65041691/is-python-dictionary-async-safe
I have created a dictionary in my Python application where I save the data and I have two tasks that run concurrently and get data from external APIs. Once they get the data, they update the dictionary - each with a different key in the dictionary. I want to understand if the dictionary is async safe or do I need to pu...
I want to understand if the dictionary is async safe or do I need to put a lock when the dictionary is read/updated? Asyncio is based on cooperative multitasking, and can only switch tasks at an explicit await expression or at the async with and async for statements. Since update of a single dictionary can never invo...
17
27
65,023,526
2020-11-26
https://stackoverflow.com/questions/65023526/runtimeerror-the-size-of-tensor-a-4000-must-match-the-size-of-tensor-b-512
I'm trying to build a model for document classification. I'm using BERT with PyTorch. I got the bert model with below code. bert = AutoModel.from_pretrained('bert-base-uncased') This is the code for training. for epoch in range(epochs): print('\n Epoch {:} / {:}'.format(epoch + 1, epochs)) #train model train_loss, _ =...
The issue is regarding the BERT's limitation with the word count. I've passed the word count as 4000 where the maximum supported is 512(have to give up 2 more for '[cls]' & '[Sep]' at the beginning and the end of the string, so it is 510 only). Reduce the word count or use some other model for your promlem. something l...
9
20
65,031,973
2020-11-27
https://stackoverflow.com/questions/65031973/how-to-select-specific-data-variables-from-xarray-dataset
BACKGROUND I am trying to download GFS weather data netcdf4 files via xarray & OPeNDAP. Big thanks to Vorticity0123 for their prior post, which allowed me to get the bones of the python script sorted (as below). PROBLEM Thing is, the GFS dataset has 195 data variables, But I don't require the majority, I only need ten ...
You can use the dict-like syntax of xarray. variables = [ 'ugrd100m', 'vgrd100m', 'dswrfsfc', 'tcdcclm', 'tcdcblcll', 'tcdclcll', 'tcdcmcll', 'tcdchcll', 'tmp2m', 'gustsfc' ] dataset[variables] Gives you: <xarray.Dataset> Dimensions: (lat: 721, lon: 1440, time: 121) Coordinates: * time (time) datetime64[ns] 2020-11-24...
8
15
65,048,547
2020-11-28
https://stackoverflow.com/questions/65048547/how-to-get-number-of-days-between-two-dates-using-pandas
I'm trying to get number of days between two dates using below function df['date'] = pd.to_datetime(df.date) # Creating a function that returns the number of days def calculate_days(date): today = pd.Timestamp('today') return today - date # Apply the function to the column date df['days'] = df['date'].apply(lambda x: c...
For performance you can subtract values without apply for avoid loops use Series.rsub for subtract from rigth side: df['date'] = pd.to_datetime(df.date) df['days'] = df['date'].rsub(pd.Timestamp('today')).dt.days What working like: df['days'] = (pd.Timestamp('today') - df['date']).dt.days If want use your solution: d...
5
8
65,045,565
2020-11-28
https://stackoverflow.com/questions/65045565/why-is-random-shuffle-so-much-slower-than-using-sorted-function
When using pythons random.shuffle function, I noticed it went significantly faster to use sorted(l, key=lambda _: random.random()) than random.shuffle(l). As far as I understand, both ways produce completely random lists, so why does shuffle take so much longer? Below are the times using timeit module. from timeit impo...
On CPython (the reference interpreter) random.shuffle is implemented in Python (and implemented in terms of _randbelow, itself a Python wrapper around getrandbits, the C level function that ultimately implements it, and which can end up being called nearly twice as often as strictly necessary in an effort to ensure the...
6
5
65,044,048
2020-11-27
https://stackoverflow.com/questions/65044048/how-to-check-if-na-type-variable-is-na-or-not-from-a-pandas-dataframe-np-na
I have a dataframe with a column whose values look something like: YEAR_TORONTO 0 <NA> 1 2016 2 <NA> 3 1999 I need to check each element of this dataframe individually via a for loop for other reasons outside this segment of code, so I'm looking for solutions that comply with my implementation. Essentially the code I...
As sammywemmy said, pd.isna() should work. >>> d = pd.Series([1,2,pd.NA,3]) >>> d 0 1 1 2 2 <NA> 3 3 dtype: object >>> d.isna() 0 False 1 False 2 True 3 False dtype: bool
7
7
65,041,605
2020-11-27
https://stackoverflow.com/questions/65041605/why-does-python-detect-the-symbol-%c2%b2-as-a-digit
Can someone say if "²" is a symbol or a digit? (alt+1277, power of two) print("²".isdigit()) # True print("²".isnumeric()) # True Because Python says it's a digit, but it's not actually a digit. Am I wrong? Or it's a bug?
It is explicitly documented as a digit: str.isdigit() Return True if all characters in the string are digits and there is at least one character, False` otherwise. Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits. This covers digits which cannot be u...
12
17
65,034,771
2020-11-27
https://stackoverflow.com/questions/65034771/how-to-truncate-a-bert-tokenizer-in-transformers-library
I am using the Scibert pretrained model to get embeddings for various texts. The code is as follows: from transformers import * tokenizer = AutoTokenizer.from_pretrained('allenai/scibert_scivocab_uncased', model_max_length=512, truncation=True) model = AutoModel.from_pretrained('allenai/scibert_scivocab_uncased') I ha...
truncation is not a parameter of the class constructor (class reference), but a parameter of the __call__ method. Therefore you should use: tokenizer = AutoTokenizer.from_pretrained('allenai/scibert_scivocab_uncased', model_max_length=512) len(tokenizer(text, truncation=True).input_ids) Output: 512
9
19
65,021,157
2020-11-26
https://stackoverflow.com/questions/65021157/increase-pythons-stdout-buffer-size
Is there a way to increase the stdout buffer size from 8182 in Python or to delay the flush until I actually call flush? Things I've tried that don't work: I can get around this issue on Windows because I can access the buffer directly (e.g. see my answer to this post). But this doesn't work for Unix. I can increase t...
Found the answer, actually very simple: my_stdout = open( 1, "w", buffering = 100000 ) 1 is the fileno for stdout. sys.stdout = my_stdout can be used to make the change to the default print target. I've only tested this on Unix.
6
6
65,014,768
2020-11-26
https://stackoverflow.com/questions/65014768/cant-find-my-python-module-after-installing-on-github-actions
When I install my example module in the local environment, python is able to find it when the module is imported. Whereas, when executed by Github Actions, the workflow fails and the reported error is that my module (ci-test) is not installed. main.yaml: - name: Install ci-test package run: | python setup.py build pyt...
The issue is not related to github action. When looking to your repository, the repository is organized this way. ci-test/ |-- requirements.txt |-- setup.py |-- src/ | |-- ci_test/ | | |-- app.py | | |-- __init__.py | | |-- main.py |-- tests/ | |-- app_test.py | |-- __init__.py | |-- main_test.py And in your setup.py ...
9
6
65,024,477
2020-11-26
https://stackoverflow.com/questions/65024477/walrus-operator-in-list-comprehensions-python
When coding I really like to use list comprehensions to transform data and I try to avoid for loops. Now I discovered that the walrus operator can be really handy for this, but when I try to use it in my code it doesn't seem to work. I've got the following code and want to transform the strings containing data about th...
Since Walrus operator does not support values unpacking, the operation day,hour,mins,sec := i.split(':') is invalid. Walrus operator is recommended to be used mostly in logic comparison, especially when you need to reuse a variable in comparison. Therefore, I would argue that for this case, a simple datetime.strptime()...
23
30
65,018,676
2020-11-26
https://stackoverflow.com/questions/65018676/how-to-sum-even-and-odd-values-with-one-for-loop-and-no-if-condition
I am taking a programming class in college and one of the exercises in the problem sheet was to write this code: number = int(input()) x = 0 y = 0 for n in range(number): if n % 2 == 0: x += n else: y += n print(x) print(y) using only one "for" loop, and no "while" or "if". The purpose of the code is to find the sum ...
for n in range(number): x += (1 - n % 2) * n y += (n % 2) * n
24
13
65,014,519
2020-11-26
https://stackoverflow.com/questions/65014519/docker-log-dont-show-python-print-output
I have a Django Proj running in Docker Container My Debug=True but docker up logging doesn't show any print('xxxx') output. Is there a way to fix it? thanks!
After a long search I found this https://serverfault.com/a/940357 Add flush=True print(datetime.now(), flush=True) Or add PYTHONUNBUFFERED: 1 to docker-compose.yml which is added by PyCharm by default version: '3.6' services: test: .... environment: PYTHONUNBUFFERED: 1 # <--- ....
7
15
65,013,956
2020-11-25
https://stackoverflow.com/questions/65013956/a-function-like-index-get-loc-but-for-multiple-values
I have the following data frame: df = pd.DataFrame({'color': ['Yellow', 'Green', 'Red', 'Orange'], 'weight': [0.5, 4, 1, 10]}, index = ['Banana','Melon','Apple','Pumpkin']) which looks like this: Banana Yellow 0.5 Melon Green 4.0 Apple Red 1.0 Pumpkin Orange 10.0 What I'm trying to do is access the integer locations o...
Try with get_indexer which accept list like input df.index.get_indexer(['Apple','Pumpkin']) Out[104]: array([2, 3], dtype=int32)
6
11
65,012,603
2020-11-25
https://stackoverflow.com/questions/65012603/removing-rows-contains-non-english-words-in-pandas-dataframe
I have a pandas data frame that consists of 4 rows, the English rows contain news titles, some rows contain non-English words like this one **She’s the Hollywood Power Behind Those ...** I want to remove all rows like this one, so all rows that contain at least non-English characters in the Pandas data frame.
If using Python >= 3.7: df[df['col'].map(lambda x: x.isascii())] where col is your target column. Data: df = pd.DataFrame({ 'colA': ['**She’s the Hollywood Power Behind Those ...**', 'Hello, world!', 'Cainã', 'another value', 'test123*', 'âbc'] }) print(df.to_markdown()) | | colA | |---:|:--------------------...
6
9
65,011,428
2020-11-25
https://stackoverflow.com/questions/65011428/play-is-not-defined-pylance-reportundefinedvariable
I'm just starting to learn Python and am having trouble calling classes. I'm using Visual Studio Code. I've looked up the error but couldn't find anything helpful. All of my experience so far has been with Java and think I might be getting some stuff mixed up. Any help would be greatly appreciated! print("Lets play a g...
Python is executed top to bottom, so all your Classes and finctions should be defined before called (so placed on top). Also class Play: def __init__(player1, player2): self.player1 = player1 self.player2 = player2 you should define your attributes inside your class like this before anything else, self it refers to th...
8
10
65,011,159
2020-11-25
https://stackoverflow.com/questions/65011159/importerror-cannot-import-name-celery
I'm trying to learn Celery i'm using Django 2.0 and celery 5.0.2 and my os is Ubuntu. This is my structure My project structure is: celery/ manage.py celery/ __init__.py cerely_app.py settings.py urls.py wsgi.py apps/ main/ __init__.py admin.py apps.py models.py task.py views.py test.py My configuration for cerely_app...
Do not put same name of your package and system package as it creates confusion for python when you hit import statement. In your case you name your package celery which is also a name of original celery package. In short simply rename your celery folder to something else.
6
4
64,998,847
2020-11-25
https://stackoverflow.com/questions/64998847/only-remove-entirely-empty-rows-in-pandas
If I have this data frame: d = {'col1': [1, np.nan, np.nan], 'col2': [1, np.nan, 1]} df = pd.DataFrame(data=d) col1 col2 0 1.0 1.0 1 NaN NaN 2 NaN 1.0 and want to drop only rows that are empty to produce the following: d = {'col1': [1, np.nan], 'col2': [1, 1]} df = pd.DataFrame(data=d) col1 col2 0 1.0 1 1 NaN 1 What ...
Check the docs page df.dropna(how='all')
17
32
64,998,533
2020-11-25
https://stackoverflow.com/questions/64998533/how-to-import-a-class-from-another-file-in-python
Im new to python and have looked at various stack overflow posts. i feel like this should work but it doesnt. How do you import a class from another file in python? This folder structure src/example/ClassExample src/test/ClassExampleTest I have this class class ClassExample: def __init__(self): pass def helloWorld(sel...
If you're using Python 3, then imports are absolute by default. This means that import example will look for an absolute package named example, somewhere in the module search path. So instead, you probably want a relative import. This is useful when you want to import a module that is relative the module doing the impo...
7
9
64,998,199
2020-11-25
https://stackoverflow.com/questions/64998199/cannot-import-name-imaging-from-pil
I'm trying to run this code: import pyautogui import time from PIL import _imaging from PIL import Image import pytesseract time.sleep(5) captura = pyautogui.screenshot() codigo = captura.crop((872, 292, 983, 337)) codigo.save(r'C:\autobot_wwe_supercard\imagenes\codigo.png') time.sleep(2) pytesseract.pytesseract.tesser...
It appears as if a lot of PIL ImportErrors can simply be fixed by uninstalling and reinstalling Pillow again according to this source and your specific problem can be found here. Try these three commands: pip uninstall PIL pip uninstall Pillow pip install Pillow
8
13
64,974,078
2020-11-23
https://stackoverflow.com/questions/64974078/how-do-the-scoping-rules-work-with-classes
Consider the following snippet of python code: x = 1 class Foo: x = 2 def foo(): x = 3 class Foo: print(x) # prints 3 Foo.foo() As expected, this prints 3. But, if we add a single line to the above snippet, the behavior changes: x = 1 class Foo: x = 2 def foo(): x = 3 class Foo: x += 10 print(x) # prints 11 Foo.foo() ...
Class block scope is special. It is documented here: A class definition is an executable statement that may use and define names. These references follow the normal rules for name resolution with an exception that unbound local variables are looked up in the global namespace. The namespace of the class definition beco...
51
33
64,993,130
2020-11-24
https://stackoverflow.com/questions/64993130/how-to-get-hmm-working-with-real-valued-data-in-tensorflow
I'm working with a dataset that contains data from IoT devices and I have found that Hidden Markov Models work pretty well for my use case. As such, I'm trying to alter some code from a Tensorflow tutorial I've found here. The dataset contains real-values for the observed variable compared to the count data shown in th...
@mCoding's answer is right, in the example posted in by Tensorflow, you have a Hidden Markov model with a uniform zero distribution ([0.,0.,0.,0.]), a heavy diagonal transition matrix, and the emission probabilities are Poisson distributed. In order to adapt it to your "Normal" example, you only have to change those pr...
6
1
64,967,847
2020-11-23
https://stackoverflow.com/questions/64967847/pandas-representative-sampling-across-multiple-columns
I have a dataframe which represents a population, with each column denoting a different quality/ characteristic of that person. How can I get a sample of that dataframe/ population, which is representative of the population as a whole across all characteristics. Suppose I have a dataframe which represents a workforce o...
You create a combined feature column, weight that one and draw with it as weights: df["combined"] = list(zip(df["favourite_colour"], df["favourite_knight"], df["favourite_quality"])) combined_weight = df['combined'].value_counts(normalize=True) df['combined_weight'] = df['combined'].apply(lambda x: combined_weight[x]) ...
8
7
64,936,440
2020-11-20
https://stackoverflow.com/questions/64936440/python-uvicorn-the-term-uvicorn-is-not-recognized-as-the-name-of-a-cmdlet-f
Good evening, I am using python 3.9 and try to run a new FastAPI service on Windows 10 Pro based on the documentation on internet https://www.uvicorn.org/ i executed the following statements pip install uvicorn pip install uvicorn[standard] create the sample file app.py from fastapi import FastAPI app = FastAPI() @app...
Python installs it's scripts in the scripts folder at the following path: c:\users\username\appdata\roaming\python\python39\scripts Place that path in the system and user environment variable. This will solve the problem.
29
11
64,992,044
2020-11-24
https://stackoverflow.com/questions/64992044/pytest-mock-multiple-calls-of-same-method-with-different-side-effect
I have a unit test like so below: # utilities.py def get_side_effects(): def side_effect_func3(self): # Need the "self" to do some stuff at run time. return {"final":"some3"} def side_effect_func2(self): # Need the "self" to do some stuff at run time. return {"status":"some2"} def side_effect_func1(self): # Need the "s...
Your first attempt doesn't work because each mock just replaced the previous one (the outer two mocks don't do anything). Your second attempt doesn't work because side-effect is overloaded to serve a different purpose for iterables (docs): If side_effect is an iterable then each call to the mock will return the next v...
8
12
64,955,230
2020-11-22
https://stackoverflow.com/questions/64955230/how-can-i-check-by-type-if-an-object-is-instance-of-pytz-timezone
I want something like this: from datetime import datetime, timezone import pytz def convert_datetime_by_timezone(timestamp_dt, to_timezone): if isinstance(to_timezone, str): return timestamp_dt.astimezone(pytz.timezone(to_timezone)) elif isinstance(to_timezone, pytz.tzinfo.??????): return timestamp_dt.astimezone(to_tim...
isinstance(x, pytz.BaseTzInfo) works for both cases
9
15
64,950,340
2020-11-22
https://stackoverflow.com/questions/64950340/cv2-imshow-is-not-working-properly-in-pycharm-macos
Environment: interpreter: Python 3.9.0 OS: macOS Big Sur This simple code is running fine with no errors; however, no image is produced and nothing is displayed, and I'm forced to manually stop the code and interrupt it to exit, otherwise it just seems to run forever? This exact same code used to work fine on my wind...
With Ubuntu 18.04 and Anaconda environment I was getting the error with Pycharm as process finished with exit code 139 (interrupted by signal 11 sigsegv) Solved it by pip install opencv-python-headless in addition to pip install opencv-python
10
3
64,900,801
2020-11-18
https://stackoverflow.com/questions/64900801/implementing-knn-imputation-on-categorical-variables-in-an-sklearn-pipeline
I am implementing a pre-processing pipeline using sklearn's pipeline transformers. My pipeline includes sklearn's KNNImputer estimator that I want to use to impute categorical features in my dataset. (My question is similar to this thread but it doesn't contain the answer to my question: How to implement KNN to impute ...
I am afraid that this cannot work. If you one-hot encode your categorical data, your missing values will be encoded into a new binary variable and KNNImputer will fail to deal with them because: it works on each column at a time, not on the full set of one-hot encoded columns there won't any missing to be dealt with a...
12
24
64,902,852
2020-11-18
https://stackoverflow.com/questions/64902852/the-difference-between-opencv-python-and-opencv-contrib-python
I was looking at the Python Package Index (PyPi) and noticed 2 very similar packages: opencv-contrib-python and opencv-python and wondering what the difference was. I looked at them and they had the exact same description and version numbers.
As per PyPi documentation: There are four different packages (see options 1, 2, 3 and 4 below): Packages for standard desktop environments: Option 1 - Main modules package: pip install opencv-python Option 2 - Full package (contains both main modules and contrib/extra modules): pip install opencv-contrib-python (chec...
39
57
64,971,281
2020-11-23
https://stackoverflow.com/questions/64971281/airflow-webserver-gettins-valueerrorsamesite
I installed Airflow 1.10.12 using Anaconda in one of my environments. But when I tried to follow the Quick Start Guide (at https://airflow.apache.org/docs/stable/start.html) I got the following error after accessing http://localhost:8080/admin/ Traceback (most recent call last): File "/home/guilherme/anaconda3/envs/eng...
Bump werkzeug version to the following: pip install 'werkzeug<1.0.0' For Airflow >=2.0.0 change the config (airflow.cfg) [webserver] cookie_samesite to use Lax (https://github.com/apache/airflow/blob/2.0.1/UPDATING.md#the-default-value-for-webserver-cookie_samesite-has-been-changed-to-lax).
7
10
64,988,557
2020-11-24
https://stackoverflow.com/questions/64988557/how-to-run-a-coroutine-inside-a-context
In the Python docs about Context Vars a Context::run method is described to enable executing a callable inside a context so changes that the callable perform to the context are contained inside the copied Context. Though what if you need to execute a coroutine? What are you supposed to do in order to achieve the same b...
As I already pointed out here, context variables are natively supported by asyncio and are ready to be used without any extra configuration. It should be noted that: Сoroutines executed by the current task by means of await share the same context New spawned tasks by create_task are executed in the copy of parent task...
7
10
64,909,861
2020-11-19
https://stackoverflow.com/questions/64909861/how-to-return-401-from-aws-lambda-authorizer-without-raising-an-exception
I have a lambda authorizer that is written in Python. I know that with the following access policy I can return 200/403 : { "principalId": "yyyyyyyy", "policyDocument": { "Version": "2012-10-17", "Statement": [ { "Action": "execute-api:Invoke", "Effect": "Deny", "Resource": "*" } ] }, "context": { "stringKey": "value",...
It really is ugly, but that's the only way to truly signal a 401, which means "I can't find your Authorization header or cookie or nothing, you have to authenticate to do that". A 403 is an explicit 👎 saying "I know who you are, you're Forbidden from doing that". It's an odd, ternary response that API Gateway needs he...
14
12
64,908,080
2020-11-19
https://stackoverflow.com/questions/64908080/python-deepcopy-uses-more-memory-than-needed
Recently I came across strange memory usage while using copy.deepcopy. I have the following code example: import copy import gc import os import psutil from pympler.asizeof import asizeof from humanize import filesize class Foo(object): __slots__ = ["name", "foos", "bars"] def __init__(self, name): self.name = name sel...
Some of that is probably accounted for because deepcopy keeps a cache of all the objects it has visited to avoid getting stuck in an infinite loop (a set I'm pretty sure). For this sort of thing, you should probably write your own efficient copy function. deepcopy is written to be able to handle arbitrary inputs, not n...
6
7
64,894,694
2020-11-18
https://stackoverflow.com/questions/64894694/which-python-static-checker-can-catch-forgotten-await-problems
Code: from typing import AsyncIterable import asyncio async def agen() -> AsyncIterable[str]: print('agen start') yield '1' yield '2' async def agenmaker() -> AsyncIterable[str]: print('agenmaker start') return agen() async def amain(): print('amain') async for item in agen(): pass async for item in await agenmaker(): ...
MyPy is perfectly capable of finding this issue. The problem is that unannotated functions are not inspected. Annotate the offending function as -> None and it is correctly inspected and rejected. # annotated with return type async def amain() -> None: print('amain') async for item in agen(): pass async for item in awa...
6
5
64,994,872
2020-11-24
https://stackoverflow.com/questions/64994872/how-can-i-properly-run-2-threads-that-await-things-at-the-same-time
Basically, I have 2 threads, receive and send. I want to be able to type a message, and whenever I get a new message it just gets 'printed above the line I am typing in'. first what I thought would work, and you can just paste this it will run: import multiprocessing import time from reprint import output import time i...
Don't use the same socket for communicating with... itself. That may be possible to do, I'm not sure, but it certainly isn't normal. Instead make a socket pair, one for the sending thread, and one for the receiving thread, e.g. this works for me: import socket; import multiprocessing; def receiveThread(sock): while Tru...
7
8
64,973,695
2020-11-23
https://stackoverflow.com/questions/64973695/automatically-register-new-prefect-flows
Is there a mechanism to automatically register flows/new flows if a local agent is running, without having to manually run e.g. flow.register(...) on each one? In airflow, I believe they have a process that regularly scans for any files with dag in the name in the specified airflow home folder, then searches them for D...
Great question (and awesome username!) - in short, I suggest you are thinking too much in terms of Airflow. There are a few reasons this is not currently available in Prefect: explicit is better than implicit Prefect flows are not constrained to live in one place and are not constrained to have the same runtime enviro...
6
6
64,996,339
2020-11-24
https://stackoverflow.com/questions/64996339/get-cpu-and-gpu-temp-using-python-without-admin-access-windows
I posted this question, asking how to get the CPU and GPU temp on Windows 10: Get CPU and GPU Temp using Python Windows. For that question, I didn't include the restriction (at least when I first posted the answer, and for quite a bit after that) for no admin access. I then modified my question to invalidate answers th...
Problem An unprivileged user needs access to functionality only available by a privileged user in a secure manner. Solution Create an server-client interface where functionality is decoupled from the actual system as to prevent security issues (ie: don't just pipe commands or options directly from client for execution ...
6
2
64,910,582
2020-11-19
https://stackoverflow.com/questions/64910582/can-we-make-the-ml-model-pickle-file-more-robust-by-accepting-or-ignoring-n
I have trained a ML model, and stored it into a Pickle file. In my new script, I am reading new 'real world data', on which I want to do a prediction. However, I am struggling. I have a column (containing string values), like: Sex Male Female # This is just as example, in real it is having much more unique values No...
Yes, you can't include (update the model) a new category or feature into a dataset after the training part is done. OneHotEncoder might handle the problem of having new categories inside some feature in test data. It will take care of keep the columns consistent in your training and test data with respect to categorica...
7
7
64,995,369
2020-11-24
https://stackoverflow.com/questions/64995369/geopandas-warning-on-read-file
I'm getting the following warning reading a geojson with geopanda's read_file(): ...geodataframe.py:422: RuntimeWarning: Sequential read of iterator was interrupted. Resetting iterator. This can negatively impact the performance. for feature in features_lst: Here's the code sample I used: crime_gdf = gpd.read_file('da...
See my comment in Fiona's issue tracker: https://github.com/Toblerity/Fiona/issues/986 GDAL (the library Fiona uses to access the geodata) maintains an iterator over the features that are currently read. There a some operations that, for some drivers, can influence this iterator. Thus, after such operations we have to ...
10
11
64,927,909
2020-11-20
https://stackoverflow.com/questions/64927909/failed-to-read-descriptor-from-node-connection-a-device-attached-to-the-system
I got this while running the selenium webdriver script in python I also set the path in System Environment and also tried downloading the webdriver that matches with my chrome version. And also letest version also. But I still get this error: [8552:6856:1120/155118.770:ERROR:device_event_log_impl.cc(211)] [15:51:18.771...
After a week of finding an answer to my error, I ended up with a solution that you just need to install pywin32 library and it will not gives you an error open cmd and type pip install pywin32 and you are good to go.....!
46
10
64,901,945
2020-11-18
https://stackoverflow.com/questions/64901945/how-to-send-a-progress-of-operation-in-a-fastapi-app
I have deployed a fastapi endpoint, from fastapi import FastAPI, UploadFile from typing import List app = FastAPI() @app.post('/work/test') async def testing(files: List(UploadFile)): for i in files: ....... # do a lot of operations on each file # after than I am just writing that processed data into mysql database # c...
Below is solution which uses uniq identifiers and globally available dictionary which holds information about the jobs: NOTE: Code below is safe to use until you use dynamic keys values ( In sample uuid in use) and keep application within single process. To start the app create a file main.py Run uvicorn main:app --re...
24
10
64,983,112
2020-11-24
https://stackoverflow.com/questions/64983112/keras-vertical-ensemble-model-with-condition-in-between
I have trained two separate models ModelA: Checks if the input text is related to my work (Binary Classifier [related/not-related]) ModelB: Classifier of related texts (Classifier [good/normal/bad]). Only the related texts are relayed to this model from ModelA I want ModelC: Ensemble classifier that outputs [good/no...
Just define your own model. I'm surprised your other models are outputting strings instead of numbers, but without more info this is about all I can give you, so I will assume the output of model A is a string. import tensorflow as tf class ModelC(tf.keras.Model): def __init__(self, A, B): super(ModelC, self).__init__(...
7
2
64,993,222
2020-11-24
https://stackoverflow.com/questions/64993222/python-neat-not-learning-further-after-a-certain-point
It seems that my program is trying to learn until a certain point, and then it's satisfied and stops improving and changing at all. With my testing it usually goes to a value of -5 at most, and then it remains there no matter how long I keep it running. The result set does not change either. Just to keep track of it I ...
Sorry to tell you that this approach just isn't going to work. Remember that neural networks are typically built out of doing a matrix multiply and then max with 0 (this is called RELU), so basically linear at each layer with a cutoff (and no, picking a different activation like sigmoid is not going to help). You want ...
6
7
64,899,579
2020-11-18
https://stackoverflow.com/questions/64899579/how-to-debug-a-python-script-launched-by-a-third-party-app
I'm using Linux Eclipse (pydev) as IDE to develop python scripts that are launched by an application written in C++. I can debug the python script without problems in the IDE, but the environment is not real (the C++ program sends and receives messages through the stdin/stdout and it's a complex communication channel t...
After some research, this is the best option I have found. Without any other solution provided, I post it just in case anyone has the same problem. Python has an integrated debugger: pdb. It works as a module and it doesn't allow to use it if you don't have the window control (i.e. you launch the script). To solve this...
6
4
64,916,693
2020-11-19
https://stackoverflow.com/questions/64916693/jupyter-notebook-error-dyld-library-not-loaded-corefoundation-after-macos-big
After updating to macOS Big Sur I get the following error when I run jupyter notebook: dyld: Library not loaded: /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation Referenced from: /Library/Frameworks/Python.framework/Versions/3.6/Resources/Python.app/Contents/MacOS/Python Reason: image not f...
I had the same problem after i upgraded to macOS Big Sur. I updated my python version (3.6.4) to (3.9.0) and after that i just uninstalled the notebook and reinstalled it. Now it works.
9
3
64,952,027
2020-11-22
https://stackoverflow.com/questions/64952027/compute-l2-distance-with-numpy-using-matrix-multiplication
I'm trying to do it by myself the assignments from Stanford CS231n 2017 CNN course. I'm trying to compute L2 distance using only matrix multiplication and sum broadcasting with Numpy. L2 distance is: And I think I can do it if I use this formula: The following code shows three methods to compute L2 distance. If I com...
Here is how you can compute pairwise distances between rows of X and Y without creating any 3-dimensional matrices: def dist(X, Y): sx = np.sum(X**2, axis=1, keepdims=True) sy = np.sum(Y**2, axis=1, keepdims=True) return np.sqrt(-2 * X.dot(Y.T) + sx + sy.T)
10
13
64,994,341
2020-11-24
https://stackoverflow.com/questions/64994341/gauge-needle-for-plotly-indicator-graph
I currently have an indicator chart (gauge) from plotly where the value is shown by how far a dark blue center reaches. However, that looks a bit odd to me, so I would like to change it to have a needle/pointer from the center to the value, like a speedometer. Here is my current code: import plotly.graph_objects as go ...
My suggestion would be to add an arrow annotation that overlays the indicator chart. By setting the range of the chart to [-1,1] x [0,1] we are basically creating a new coordinate system that the arrow will be on, we can approximate where the arrow should go to in order to correspond to the value on your indicator char...
7
7
64,995,178
2020-11-24
https://stackoverflow.com/questions/64995178/decryption-failed-or-bad-record-mac-in-multiprocessing
I am trying to get all the PC cores to work simultaneously while filling a PostgreSQL database, I have edited the code to make a reproducible error of what I am getting Traceback (most recent call last): File "test2.py", line 50, in <module> download_all_sites(sites) File "test2.py", line 36, in download_all_sites pool...
Create a new postgres connection for each multiprocess. Libpq connections shouldn’t be used with forked processes (what multiprocessing is doing), it is mentioned in the second warning box at the postgres docs. import requests import multiprocessing import time import os import psycopg2 session = None def set_global_se...
8
9
64,987,304
2020-11-24
https://stackoverflow.com/questions/64987304/qtmediaplayer-wont-work-on-frameless-and-translucent-background-pyqt5
I am making a videoplayer with QMediaplayer but it wont work on frameless and translucent background window.I want to make a round corner windows so i need frameless and translucent window. Here is my code: from PyQt5.QtCore import Qt, QUrl from PyQt5.QtMultimedia import QMediaContent, QMediaPlayer from PyQt5.QtMultime...
Try it: import sys from PyQt5.QtCore import Qt, QUrl, QRectF from PyQt5.QtGui import QPainterPath, QRegion from PyQt5.QtMultimedia import QMediaContent, QMediaPlayer from PyQt5.QtMultimediaWidgets import QVideoWidget from PyQt5.QtWidgets import QApplication, QMainWindow, QFrame, QWidget, QHBoxLayout class Player(QMainW...
6
0
64,990,689
2020-11-24
https://stackoverflow.com/questions/64990689/control-the-power-of-a-usb-port-in-python
I was wondering if it could be possible to control the power of usb ports in Python, using vendor ids and product ids. It should be controlling powers instead of just enabling and disabling the ports. It would be appreciated if you could provide some examples.
Look into the subprocess module in the standard library: What commands you need will depend on the OS. Windows For windows you will want to look into devcon This has been answered in previous posts import subprocess # Fetches the list of all usb devices: result = subprocess.run(['devcon', 'hwids', '=usb'], capture_outp...
6
4
64,987,430
2020-11-24
https://stackoverflow.com/questions/64987430/what-exactly-does-the-forward-function-output-in-pytorch
This example is taken verbatim from the PyTorch Documentation. Now I do have some background on Deep Learning in general and know that it should be obvious that the forward call represents a forward pass, passing through different layers and finally reaching the end, with 10 outputs in this case, then you take the outp...
it seems to me by default the output of a PyTorch model's forward pass is logits As I can see from the forward pass, yes, your function is passing the raw output def forward(self, x): x = self.pool(F.relu(self.conv1(x))) x = self.pool(F.relu(self.conv2(x))) x = x.view(-1, 16 * 5 * 5) x = F.relu(self.fc1(x)) x = F.re...
12
11
64,943,693
2020-11-21
https://stackoverflow.com/questions/64943693/what-are-the-best-practices-for-structuring-a-fastapi-project
The problem that I want to solve related the project setup: Good names of directories so that their purpose is clear. Keeping all project files (including virtualenv) in one place, so I can easily copy, move, archive, remove the whole project, or estimate disk space usage. Creating multiple copies of some selected fil...
Harsha already mentioned my project generator but I think it can be helpful for future readers to explain the ideas behind of it. If you are going to serve your frontend something like yarn or npm. You should not worry about the structure between them. With something like axios or the Javascript's fetch you can easily ...
85
129
64,985,488
2020-11-24
https://stackoverflow.com/questions/64985488/how-do-you-list-local-profiles-with-boto3-from-aws-credentials-and-aws-c
I would like to list all of my local profiles using boto3, as I think boto3 is not picking up my credentials correctly. I have tried the following: import boto3 boto3.Session.available_profiles Which doesn't give me a list, but a property object.
You might want to use awscli instead of boto3 to list your profiles. aws configure list This should output something like this: Name Value Type Location ---- ----- ---- -------- profile <not set> None None access_key ****************ABCD config_file ~/.aws/config secret_key ****************ABCD config_file ~/.aws/con...
13
17
64,979,440
2020-11-24
https://stackoverflow.com/questions/64979440/in-python-is-it-possible-to-restrict-the-type-of-a-function-parameter-to-two-po
I try to restrict the 'parameter' type to be int or list like the function 'f' below. However, Pycharm does not show a warning at the line f("weewfwef") about wrong parameter type, which means this (parameter : [int, list]) is not correct. In Python, is it possible to restrict the type of a python function parameter to...
The term you're looking for is a union type. from typing import Union def f(parameter: Union[int, list]): ... Union is not limited to two types. If you ever have a value which is one of several known types, but you can't necessarily know which one, you can use Union[...] to encapsulate that information.
7
8
64,897,689
2020-11-18
https://stackoverflow.com/questions/64897689/how-to-have-pandas-perform-a-rolling-average-on-a-non-uniform-x-grid
I would like to perform a rolling average but with a window that only has a finite 'vision' in x. I would like something similar to what I have below, but I want a window range that based on the x value rather than position index. While doing this within pandas is preferred numpy/scipy equivalents are also OK import nu...
According to pandas documentation on rolling Size of the moving window. This is the number of observations used for calculating the statistic. Each window will be a fixed size. Therefore, maybe you need to fake a rolling operation with various window sizes like this test_df = pd.DataFrame({'x':np.linspace(1,10,10),'y...
7
3
64,973,215
2020-11-23
https://stackoverflow.com/questions/64973215/specifying-any-instance-of-class-foo-for-mock-assert-called-once-with
In assert_called_once_with, how can I specify a parameter is "any instance of class Foo"? For example: class Foo(): pass def f(x): pass def g(): f(Foo()) import __main__ from unittest import mock mock.ANY of course passes: with mock.patch.object(__main__, 'f') as mock_f: g() mock_f.assert_called_once_with(mock.ANY) a...
One simple solution is to do this in two steps: with mock.patch.object(__main__, 'f') as mock_f: g() mock_f.assert_called_once() self.assertIsInstance(mock_f.mock_calls[0].args[0], Foo) However, if you look at the implementation of ANY: class _ANY(object): "A helper object that compares equal to everything." def __eq...
7
6
64,968,646
2020-11-23
https://stackoverflow.com/questions/64968646/pandas-convert-integer-zeroes-and-ones-to-boolean
I have a dataframe that contains one hot encoded columns of 0s and 1s which is of dtype int32. a b h1 h2 h3 xy za 0 0 1 ab cd 1 0 0 pq rs 0 1 0 I want to convert the columns h1,h2 and h3 to boolean so here is what I did.. df[df.columns[2:]].astype(bool) But this changed all values of h1-h3 as TRUE. I also tried df[df...
You can select all columns by positions after first 2 with DataFrame.iloc, convert to boolean and assign back: df.iloc[:, 2:] = df.iloc[:, 2:].astype(bool) print (df) a b h1 h2 h3 0 xy za False False True 1 ab cd True False False 2 pq rs False True False Or create dictionary for convert columns names without first 2: ...
6
7
64,964,259
2020-11-23
https://stackoverflow.com/questions/64964259/retain-original-bar-order-in-plotly-python-when-also-passing-color
Using Plotly for a bar plot preserves the dataset's order when not using color: import pandas as pd import plotly.express as px df = pd.DataFrame({'val': [1, 2, 3], 'type': ['b', 'a', 'b']}, index=['obs1', 'obs2', 'obs3']) px.bar(df, 'val') But color reorders the data: px.bar(df, 'val', color='type') How can I pres...
You could use the category_orders parameter: import pandas as pd import plotly.express as px df = pd.DataFrame({'val': [1, 2, 3], 'type': ['b', 'a', 'b']}, index=['obs1', 'obs2', 'obs3']) fig = px.bar(df, 'val', color='type', category_orders={'index': df.index[::-1]}) fig.show() Output From the documentation: This p...
6
8
64,960,430
2020-11-22
https://stackoverflow.com/questions/64960430/python-requests-with-proxy-results-in-sslerror-wrong-version-number
I can't use the different proxy in Python. My code: import requests proxies = { "https":'https://154.16.202.22:3128', "http":'http://154.16.202.22:3128' } r=requests.get('https://httpbin.org/ip', proxies=proxies) print(r.json()) The error I'm getting is: . . . raise MaxRetryError(_pool, url, error or ResponseError(cau...
The proxy you use simply does not support proxying https:// URLs: $ https_proxy=http://154.16.202.22:3128 curl -v https://httpbin.org/ip * Trying 154.16.202.22... * TCP_NODELAY set * Connected to (nil) (154.16.202.22) port 3128 (#0) * Establish HTTP proxy tunnel to httpbin.org:443 > CONNECT httpbin.org:443 HTTP/1.1 > H...
14
9
64,954,213
2020-11-22
https://stackoverflow.com/questions/64954213/python-how-to-recieve-sigint-in-docker-to-stop-service
I'm writing a monitor service in Python that monitors another service and while the monitor & scheduling part works fine, I have a hard time figuring out how to do a proper shutdown of the service using a SIGINT signal send to the Docker container. Specifically, the service should catch the SIGINT from either a docker ...
Solution: The app must run as PID 1 inside docker to receive a SIGINT. To do so, one must use ENTRYPOINT instead of CMD. The fixed Dockerfile: FROM python:3.8-slim-buster COPY test/TestGS.py . ENTRYPOINT ["python", "TestGS.py"] Build the image: docker build . -t python-signals Run the image: docker run -it --rm --nam...
16
18
64,959,714
2020-11-22
https://stackoverflow.com/questions/64959714/await-vs-asyncio-run-in-python
In Python, what is the actual difference between awaiting a coroutine and using asyncio.run()? They both seem to run a coroutine, the only difference that I can see being that await can only be used in a coroutine.
That is the exact difference. There should be exactly one call to asyncio.run() in your code, which will block until all coroutines have finished. Inside any coroutine, you can use await to suspend the current function, and asyncio will resume the function at some future time. All of this happens inside the asyncio.run...
21
19
64,952,572
2020-11-22
https://stackoverflow.com/questions/64952572/output-directories-for-python-setup-py-sdist-bdist-wheel
When doing python setup.py sdist bdist_wheel it creates build, dist, packagename.egg-info directories. I'd like to have them out of the current folder. I tried: --dist-dir=../dist: works with sdist but packagename.egg-info is still there --bdist-dir=../dist: for example: python setup.py sdist bdist_wheel --dist-dir...
I tried some time again with -d, --dist-dir, --bdist-dir but I found no way to do it in one-line. I'm afraid the shortest we could find (on Windows) is: python setup.py sdist bdist_wheel rmdir /s /q packagename.egg-info build ..\dist move dist ..
11
0
64,943,656
2020-11-21
https://stackoverflow.com/questions/64943656/plot-3-graphs-2-on-top-and-one-on-bottom-axis-in-python
I am trying to plot 3 dendrograms, 2 on top and one on the bottom. But the only way I figured out in doing this: fig, axes = plt.subplots(2, 2, figsize=(22, 14)) dn1 = hc.dendrogram(wardLink, ax=axes[0, 0]) dn2 = hc.dendrogram(singleLink, ax=axes[0, 1]) dn3 = hc.dendrogram(completeLink, ax=axes[1, 0]) Gives me a fourt...
You can redivide the canvas area as you desire and use the 3rd argument to subplot to tell it which cell to plot to: plt.subplot(2, 2, 1) # divide as 2x2, plot top left plt.plt(...) plt.subplot(2, 2, 2) # divide as 2x2, plot top right plt.plt(...) plt.subplot(2, 1, 2) # divide as 2x1, plot bottom plt.plt(...) You can ...
7
10
64,940,181
2020-11-21
https://stackoverflow.com/questions/64940181/cannot-display-emojis-in-windows-powershell-or-wsl-linux-terminal-using-python
I am trying to print emojis in both Windows Powershell and WSL Linux Terminal using Python3. I have tried using unicode, CLDR names and also installed the emoji library. print("\U0001F44D") print(emoji.emojize(':thumbs_up:')) But in the terminal it is showing only a question mark within a box. No emoji is showing. Wha...
I don't think any of the Windows Shells has proper support for emoji/unicode characters, or it may not support emojis. If your using Windows, you may want to try Windows Terminal. It has complete Emoji support and should work with Powershell and WSL.
8
8
64,905,873
2020-11-19
https://stackoverflow.com/questions/64905873/sibling-package-import-and-mypy-has-no-attribute-error
I am trying to import a module from a sibling package in Python; following the instructions in this answer. My problem is that the import works... but mypy is saying that it's a bad import. I'm seeking to understand why mypy is reporting an error, and how to fix it. Directory structure/Code This is a module that I have...
Running mypy with the --namespace-packages flag made the check run without error, which pointed me to the actual problem: ./mypackage/mypackage/__init__.py did not exist, causing mypy to not pursue the import correctly. Python was working because in 3.3+, namespace packages are supported, but mypy requires a flag to ch...
8
7
64,935,522
2020-11-20
https://stackoverflow.com/questions/64935522/how-to-know-torch-version-that-installed-locally-in-your-device
I want to check torch version in my device using Jupyter Notebook. I'm used this import torch print(torch.__version__) but it didn't work and Jupyter notebook raised an error as below AttributeError Traceback (most recent call last) <ipython-input-8-beb55f24d5ec> in <module> 1 import torch ----> 2 print(torch.__versio...
I have tried to install new Pytorch version. But, it didn't work and then I deleted the Pytorch files manually suggested on my command line. Finally, I installed new Pytorch version using conda install pytorch torchvision torchaudio cudatoolkit=11.0 -c pytorch and everything works fine. This code works well after that...
6
6
64,938,027
2020-11-20
https://stackoverflow.com/questions/64938027/type-annotation-for-dict-arguments
Can I indicate a specific dictionary shape/form for an argument to a function in python? Like in typescript I'd indicate that the info argument should be an object with a string name and a number age: function parseInfo(info: {name: string, age: number}) { /* ... */ } Is there a way to do this with a python function t...
In Python 3.8+ you could use the alternative syntax to create a TypedDict: from typing import TypedDict Info = TypedDict('Info', {'name': str, 'age': int}) def parse_info(info: Info): pass From the documentation on TypedDict: TypedDict declares a dictionary type that expects all of its instances to have a certain set...
10
23
64,933,298
2020-11-20
https://stackoverflow.com/questions/64933298/why-should-we-use-in-def-init-self-n-none
Why should we use -> in def __init__(self, n) -> None:? I read the following excerpt from PEP 484, but I am unable to understand what it means. (Note that the return type of __init__ ought to be annotated with -> None. The reason for this is subtle. If __init__ assumed a return annotation of -> None, would that mean t...
The main reason is to allow static type checking. By default, mypy will ignore unannotated functions and methods. Consider the following definition: class Foo: def __init__(self): return 3 f = Foo() mypy, a static type analysis tool, sees nothing wrong with this by default: $ mypy tmp.py Success: no issues found in 1 ...
27
29
64,917,285
2020-11-19
https://stackoverflow.com/questions/64917285/difference-in-python-thread-join-between-python-3-7-and-3-8
I have a small Python program that behaves differently in Python 3.7 and Python 3.8. I'm struggling to understand why. The #threading changelog for Python 3.8 does not explain this. Here's the code: import time from threading import Event, Thread class StoppableWorker(Thread): def __init__(self): super(StoppableWorker,...
There is an undocumented change in the behavior of threading _shutdown() from Python version 3.7.3 to 3.7.4. Here's how I found it: To trace the issue, I first used the inspect package to find out who join()s the thread in the Python 3.7.3 runtime. I modified the join() function to get some output: ... def join(self, *...
7
6
64,919,868
2020-11-19
https://stackoverflow.com/questions/64919868/fastapi-module-app-routers-test-has-no-attribute-routes
I am trying to setup an app using FastAPI but keep getting this error which I can't make sense of. My main.py file is as follows: from fastapi import FastAPI from app.routers import test app = FastAPI() app.include_router(test, prefix="/api/v1/test") And in my routers/test.py file I have: from fastapi import APIRouter...
I think you want: app.include_router(test.router, prefix="/api/v1/test") rather than: app.include_router(test, prefix="/api/v1/test")
6
15
64,909,849
2020-11-19
https://stackoverflow.com/questions/64909849/syntax-error-with-flake8-and-pydantic-constrained-types-constrregex
I use in Python the package pydantic and the linker Flake8. I want to use constr from pydantic with a regular Experssion. Only certain Characters should be passed. (a-z, A-Z, 0-9 and _) The regular Experssion "^[a-zA-Z0-9_]*$" works, but flake8 shows me the following error: syntax error in forward annotation '^[a-zA-Z...
the error here comes from pyflakes which attempts to interpret type annotations as type annotations according to PEP 484 the annotations used by pydantic are incompatible with PEP 484 and result in that error. you can read more about this in this pyflakes issue I'd suggest either (1) finding a way to use pydantic which...
18
24
64,915,548
2020-11-19
https://stackoverflow.com/questions/64915548/python-sharedmemory-persistence-between-processes
Is there any way to make SharedMemory object created in Python persist between processes? If the following code is invoked in interactive python session: >>> from multiprocessing import shared_memory >>> shm = shared_memory.SharedMemory(name='test_smm', size=1000000, create=True) it creates a file in /dev/shm/ on a Li...
You can unregister a shared memory object from the resource cleanup process without unlinking it: $ python3 Python 3.8.6 (default, Sep 25 2020, 09:36:53) [GCC 10.2.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> from multiprocessing import shared_memory, resource_tracker >>> shm =...
8
10
64,908,770
2020-11-19
https://stackoverflow.com/questions/64908770/replace-values-in-pandas-dataframe-column-with-different-replacement-dict-based
I have a dataframe where I want to replace values in a column, but the dict describing the replacement is based on values in another column. A sample dataframe would look like this: Map me strings date 0 1 test1 2020-01-01 1 2 test2 2020-02-10 2 3 test3 2020-01-01 3 4 test2 2020-03-15 I have a dictionary that looks l...
Use DataFrame.join with MultiIndex Series created by DataFrame cosntructor and DataFrame.stack: df = df.join(pd.DataFrame(map_dict).stack().rename('new'), on=['Map me','date']) print (df) Map me strings date new 0 1 test1 2020-01-01 4 1 2 test2 2020-02-10 4 2 3 test3 2020-01-01 1 3 4 test2 2020-03-15 4
6
7
64,900,812
2020-11-18
https://stackoverflow.com/questions/64900812/how-to-use-sqlites-upsert-or-on-conflict-with-flask-sqlalchemy
I want to update my SQLite DB with data provided by an external API and I don't want to check every time for any conflicts by myself, instead, I want to take advantage of UPSERT statement. SQLAlchemy documentation for version 1.4 (still in beta but that's ok) shows that this is possible. But I don't know how to get thi...
I found the solution thanks to this gist (credits for droustchev) which I slightly edited. It's a bit messy but it works: from sqlalchemy.ext.compiler import compiles from sqlalchemy.sql import Insert @compiles(Insert, 'sqlite') def suffix_insert(insert, compiler, **kwargs): stmt = compiler.visit_insert(insert, **kwarg...
8
8
64,896,838
2020-11-18
https://stackoverflow.com/questions/64896838/how-do-i-avoid-type-errors-when-internal-function-returns-union-that-could-be
I've been running into a bit of weirdness with Unions (and Optionals, of course) in Python - namely it seems that the static type checker tests properties against all member of a union, and not a member of the union (i.e. it seems overly strict?). As an example, consider the following: import pandas as pd def test_dumm...
The underlying function should really be defined as an overload -- I'd suggest a patch to pandas probably Here's what the type looks like right now: def fillna( self: FrameOrSeries, value=None, method=None, axis=None, inplace: bool_t = False, limit=None, downcast=None, ) -> Optional[FrameOrSeries]: ... in reality, a ...
7
6
64,890,117
2020-11-18
https://stackoverflow.com/questions/64890117/what-is-the-best-way-to-generate-all-binary-strings-of-the-given-length-in-pytho
I'm now studying recursion and try to build some codes to generate all binary strings of the given length 'n'. I found a code to use for loop: n = 5 for i in range(2**n, 2**(n+1)): print(bin(i)[3:]) But is there any other way to solve this problem using recursion? Thank you!
It's hard to determine what way is "the best" ;) We have to add zero or one to current string and go to the next recursion level. Stop-condition is reaching of needed length (here n-1 because we have to provide leading one corresponding to your example) def genbin(n, bs = ''): if n-1: genbin(n-1, bs + '0') genbin(n-1, ...
10
5
64,795,367
2020-11-11
https://stackoverflow.com/questions/64795367/method-to-determine-lowest-required-versions-of-python-packages-for-a-project-pa
This question concerns any package, not just Python version itself. To give some context: we are planning to build an internal package at work, which naturally will have many dependencies. To give freedom for our developers and avoid messy version conflicts, I want to specify broader constraints for packages requiremen...
Installing a project using its "lower bounds" dependencies is useful to ensure that (a) you have those lower bounds specified properly and (b) the tests pass. This is a popular feature request for pip, and is being tracked in Add a resolver option to use the specified minimum version for a dependency #8085. The issue h...
10
4
64,872,401
2020-11-17
https://stackoverflow.com/questions/64872401/os-system-calls-run-like-serial-execution-multi-threads
My co-worker asked me why his code cannot run in concurrency in multi-threads. I discover the os.system function is acting weird unlike the other functions in multi-threads. I code a small demo to reproduce the problem. Appreciating somebody who can answer my question. Run like serial execution import os import time fr...
os.system is implemented by calling the standard C function system: This is implemented by calling the Standard C function system(), and has the same limitations. And according to the man page of the system function: Blocking SIGCHLD while waiting for the child to terminate prevents the application from catching the...
6
2
64,799,827
2020-11-12
https://stackoverflow.com/questions/64799827/python-json-dumps-outputs-all-my-data-into-one-line-but-i-want-to-have-a-new-l
I am working with Python and some json data. I am looping through my data (which are all dictionaries) and when I print the loop values to my console, I get 1 dictionary per line. However, when I do the same line of code with json.dumps() to convert my object into a string to be able to be output, I get multiple lines ...
You can newline after each f.write(json.dumps(value, sort_keys=True, indent=0)) like this - f.write('\n')
9
8
64,815,227
2020-11-13
https://stackoverflow.com/questions/64815227/attributeerror-module-seaborn-has-no-attribute-histplot
I'm trying to plot using sns.histplot on the Titanic Dataset in Kaggle's Jupyter Notebook. This is my code: sns.histplot(train, x = "Age", hue="Sex") But it's throwing me this error: --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-i...
If you have a standard python installation, update with pip: pip install -U seaborn If you are using an Anaconda distribution, at the anaconda prompt (base) environment, or activate the appropriate environment: # update all the packages in the environment conda update --all # or conda update seaborn See Anaconda: Man...
40
51
64,807,163
2020-11-12
https://stackoverflow.com/questions/64807163/importerror-cannot-import-name-from-partially-initialized-module-m
I'm upgrading an application from Django 1.11.25 (Python 2.6) to Django 3.1.3 (Python 3.8.5) and, when I run manage.py makemigrations, I receive this message: File "/home/eduardo/projdevs/upgrade-intra/corporate/models/section.py", line 9, in <module> from authentication.models import get_sentinel** ImportError: cannot...
You have a circular import. authentication/models imports corporate/models, which imports corporate/models/section, which imports authentication/models. You can't do that. Rewrite and/or rearrange your modules so that circular imports aren't needed. One strategy to do this is to organize your modules into a hierarchy, ...
151
65
64,809,370
2020-11-12
https://stackoverflow.com/questions/64809370/how-can-i-invert-a-melspectrogram-with-torchaudio-and-get-an-audio-waveform
I have a MelSpectrogram generated from: eval_seq_specgram = torchaudio.transforms.MelSpectrogram(sample_rate=sample_rate, n_fft=256)(eval_audio_data).transpose(1, 2) So eval_seq_specgram now has a size of torch.Size([1, 128, 499]), where 499 is the number of timesteps and 128 is the n_mels. I'm trying to invert it, so...
Just for history, full code: import torch import torchaudio import IPython waveform, sample_rate = torchaudio.load("wavs/LJ030-0196.wav", normalize=True) n_fft = 256 n_stft = int((n_fft//2) + 1) transofrm = torchaudio.transforms.MelSpectrogram(sample_rate, n_fft=n_fft) invers_transform = torchaudio.transforms.InverseMe...
15
5