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
62,691,279
2020-7-2
https://stackoverflow.com/questions/62691279/how-to-disable-tokenizers-parallelism-true-false-warning
I use pytorch to train huggingface-transformers model, but every epoch, always output the warning: The current process just got forked. Disabling parallelism to avoid deadlocks... To disable this warning, please explicitly set TOKENIZERS_PARALLELISM=(true | false) How to disable this warning?
Set the environment variable to the string "false" either by TOKENIZERS_PARALLELISM=false in your shell or by: import os os.environ["TOKENIZERS_PARALLELISM"] = "false" in the Python script
73
103
62,701,493
2020-7-2
https://stackoverflow.com/questions/62701493/3d-gridded-data-interpolation-in-julia
I'm strugling to convert some MATLAB code into Julia. I have some 3D gridded data (temperature that varies bi-dimensionally and over time) and want to change from a (x,y,t) mesh to a more loose (xi,yi,ti) mesh. In MATLAB it would be a simple interp(x,y,t,T,xi,yi,ti). I tried using Interpolations, Dierckx, but both seem...
What led you to believe that Interpolations.jl works only for two-dimensional data? julia> a = rand(1:100, 10, 10, 10); julia> using Interpolations julia> itp = interpolate(a, BSpline(Linear())); julia> v = itp(1.4, 2.3, 3.7) 55.24
7
9
62,696,796
2020-7-2
https://stackoverflow.com/questions/62696796/singledispatchmethod-and-class-method-decorators-in-python-3-8
I am trying to use one of the new capabilities of python 3.8 (currently using 3.8.3). Following the documentation I tried the example provided in the docs: from functools import singledispatchmethod class Negator: @singledispatchmethod @classmethod def neg(cls, arg): raise NotImplementedError("Cannot negate a") @neg.re...
This seems to be a bug in the functools library documented in this issue.
9
6
62,690,377
2020-7-2
https://stackoverflow.com/questions/62690377/tensorflow-compatibility-with-keras
I am using Python 3.6 and Tensorflow 2.0, and have some Keras codes: import keras from keras.models import Sequential from keras.layers import Dense model = Sequential() model.add(Dense(1)) model.compile(optimizer='adam',loss='mean_squared_error',metrics=['accuracy']) When I run this code, I got the following error: ...
The problem is that the latest keras version (2.4.x) is just a wrapper on top of tf.keras, which I do not think is that you want, and this is why it requires specifically TensorFlow 2.2 or newer. What you can do is install Keras 2.3.1, which supports TensorFlow 2.x and 1.x, and is the latest real releases of Keras. You...
12
16
62,691,561
2020-7-2
https://stackoverflow.com/questions/62691561/how-to-apply-different-border-widths-for-subregions-in-python-geopandas-chorople
I am making choropleth maps with geopandas. I want to draw maps with two layers of borders: thinner ones for national states (geopandas default), and thicker ones for various economic communities. Is this doable in geopandas? Here is an example: import geopandas as gpd import numpy as np import matplotlib.pyplot as plt...
Specify the background plot as an axis and use it within the second plot, plotting only EAC countries. To have only outlines, you need facecolor='none'. ax = africa.plot(column="pop_est") africa.loc[africa['EAC'] == 1].plot(ax=ax, facecolor='none', edgecolor='red', linewidth=2) If you want a boundary only around thos...
8
10
62,678,411
2020-7-1
https://stackoverflow.com/questions/62678411/how-to-plot-a-paired-histogram-using-seaborn
I would like to make a paired histogram like the one shown here using the seaborn distplot. This kind of plot can also be referred to as the back-to-back histogram shown here, or a bihistogram inverted/mirrored along the x-axis as discussed here. Here is my code: import numpy as np import matplotlib.pyplot as plt impor...
Here is a possible approach using seaborn's displots. Seaborn doesn't return the created graphical elements, but the ax can be interrogated. To make sure the ax only contains the elements you want upside down, those elements can be drawn first. Then, all the patches (the rectangular bars) and the lines (the curve for t...
7
7
62,684,213
2020-7-1
https://stackoverflow.com/questions/62684213/asyncio-task-was-destroyed-but-it-is-pending
I am working a sample program that reads from a datasource (csv or rdbms) in chunks, makes some transformation and sends it via socket to a server. But because the csv is very large, for testing purpose I want to break the reading after few chunks. Unfortunately something goes wrong and I do not know what and how to fi...
Many async resources, such as generators, need to be cleaned up with the help of an event loop. When an async for loop stops iterating an async generator via break, the generator is cleaned up by the garbage collector only. This means the task is pending (waits for the event loop) but gets destroyed (by the garbage col...
7
7
62,683,076
2020-7-1
https://stackoverflow.com/questions/62683076/is-there-a-way-to-do-conditionals-inside-python-3-for-loops
Coming from primarily coding in Java and wanted to know if Python could use conditionals and different kinds of incrementing inside its for loops like Java and C can. Sorry if this seems like a simple question. i.e.: boolean flag = True for(int i = 1; i < 20 && flag; i *= 2) { //Code in here }
Not directly. A for loop iterates over a pre-generated sequence, rather than generating the sequence itself. The naive translation would probably look something like flag = True i = 1 while i < 20: if not flag: break ... if some_condition: flag = False i *= 2 However, your code probably could execute the break stateme...
15
22
62,682,024
2020-7-1
https://stackoverflow.com/questions/62682024/how-to-apply-pandas-map-where-the-function-takes-more-than-1-argument
Suppose I have a dataframe containing a column of probability. Now I create a map function which returns 1 if the probability is greater than a threshold value, otherwise returns 0. Now the catch is that I want to specify the threshold by giving it as an argument to the function, and then mapping it on the pandas dataf...
We can use Dataframe.applymap df2 = df.applymap(lambda x: partition(x, threshold=0.5)) Or if only one column: df['probability']=df['probability'].apply(lambda x: partition(x, threshold=0.5)) but it is not neccesary here. You can do: df2 = df.ge(threshold).astype(int) I recommend you see it
9
9
62,681,223
2020-7-1
https://stackoverflow.com/questions/62681223/pycall-cant-find-scipy-in-julia
I'm currently rewriting a bunch of matlab code into julia. These codes envolves a lot of math and, particularly, interpolation functions for a 3D mesh. It is easy to deal with this in matlab: all I need to do is to use interp3 function. Once I coundn't find any simple way to do similar in Julia, I'm trying to use some ...
Install scipy with Conda - Julia's interface to Python's packages. using Conda Conda.add("scipy") now pyimport("scipy") will work like charm. Note that with a custom Python installation various things can happen (and you are left on your own with managing that), hence I recommend you to use Python built-into Julia. Th...
7
6
62,671,883
2020-7-1
https://stackoverflow.com/questions/62671883/discordbot-using-threading-raise-runtimeerror-set-wakeup-fd-only-works-in-main
I am using the threading module to host a web server and a Discord bot at the same time. Everything runs fine on Windows but as soon as I load it onto my Linux server I get the following error: Starting Bot Exception in thread Bot: Traceback (most recent call last): File "/usr/lib/python3.8/asyncio/unix_events.py", lin...
I'd suggest you to use client.start() in async coroutine instead of client.run() in separate thread. More detailed example here
7
1
62,671,692
2020-7-1
https://stackoverflow.com/questions/62671692/how-to-unpack-a-single-variable-tuple-in-python3
I have a tuple- ('name@mail.com',). I want to unpack it to get 'name@mail.com'. How can I do so? I am new to Python so please excuse.
tu = ('name@mail.com',) str = tu[0] print(str) #will return 'name@mail.com' A tuple is a sequence type, which means the elements can be accessed by their indices.
14
4
62,668,987
2020-7-1
https://stackoverflow.com/questions/62668987/does-python-3-gzip-closes-the-fileobj
The gzip docs for Python 3 states that Calling a GzipFile object’s close() method does not close fileobj, since you might wish to append more material after the compressed data Does this mean that the gzip file handler f_in is not closed if we do the following import gzip import shutil with gzip.open('/home/joe/file....
The warning about fileobj not being closed only applies when you open the file, and pass it to the GzipFile via the fileobj= parameter. When you pass only a filename, GzipFile "owns" the file handle and will also close it.
7
8
62,630,875
2020-6-29
https://stackoverflow.com/questions/62630875/how-to-change-the-plot-order-of-the-categorical-x-axis
I got a dataframe which looks like below: df: Time of Day Season value Day Shoulder 30.581606 Day Summer 25.865560 Day Winter 42.644530 Evening Shoulder 39.954759 Evening Summer 32.053458 Evening Winter 53.678297 Morning Shoulder 32.171245 Morning Summer 25.070815 Morning Winter 42.876667 Night Shoulder 22.082042 Night...
Use pandas.Categorical to set the categorical order of 'Time of Day' in the df. Tested in python 3.11, pandas 1.5.3, matplotlib 3.7.1, seaborn 0.12.2 import pandas as pd import matplotlib.pyplot as plt import seaborn as sns data = {'Time of Day': ['Day', 'Day', 'Day', 'Evening', 'Evening', 'Evening', 'Morning', 'Morn...
8
16
62,604,916
2020-6-27
https://stackoverflow.com/questions/62604916/how-to-build-an-sdist-with-pip
I'm in the process of converting my projects to use flit as their build backend using pyroject.toml as defined in PEP517. I still have some projects that will continue to use setuptools as their build backend. Some projects may not be PEP 517 compliant and will use the legacy setup.py build system. I'm using the latest...
The Python Packaging Guide recommends building packages using the new build library maintained by the same Python Packaging Authority that maintains pip. https://github.com/pypa/build python -m build . --sdist
13
6
62,662,564
2020-6-30
https://stackoverflow.com/questions/62662564/how-do-i-clear-the-cache-from-cached-property-decorator
I have an function called "value" that makes heavy calculation... The result of the function is always the same if the dataset is not changed for the identifier. Once the dataset is changed for some identifier, I want to clear the cache, and let the function calculate it again. You can better understand me by looking a...
As you can read in the CPython source, the value for a cached_property in Python 3.8 is stored in an instance variable of the same name. This is not documented, so it may be an implementation detail that you should not rely upon. But if you just want to get it done without regards to compatibility, you can remove the c...
30
26
62,618,680
2020-6-28
https://stackoverflow.com/questions/62618680/overwrite-an-excel-sheet-with-pandas-dataframe-without-affecting-other-sheets
I want to overwrite an existing sheet in an excel file with Pandas dataframe but don't want any changes in other sheets of the same file. How this can be achieved. I tried below code but instead of overwriting, it is appending the data in 'Sheet2'. import pandas as pd from openpyxl import load_workbook book = load_work...
I didn't find any other option other than this, this would be a quick solution for you. I believe still there's no direct way to do this, correct me if I'm wrong. That's the reason we need to play with these logical ways. import pandas as pd def write_excel(filename,sheetname,dataframe): with pd.ExcelWriter(filename, e...
16
25
62,584,640
2020-6-25
https://stackoverflow.com/questions/62584640/suggested-way-to-run-multiple-sql-statements-in-python
What would be the suggested way to run something like the following in python: self.cursor.execute('SET FOREIGN_KEY_CHECKS=0; DROP TABLE IF EXISTS %s; SET FOREIGN_KEY_CHECKS=1' % (table_name,)) For example, should this be three separate self.cursor.execute(...) statements? Is there a specific method that should be use...
I would create a stored procedure: DROP PROCEDURE IF EXISTS CopyTable; DELIMITER $$ CREATE PROCEDURE CopyTable(IN _mytable VARCHAR(64), _table_name VARCHAR(64)) BEGIN SET FOREIGN_KEY_CHECKS=0; SET @stmt = CONCAT('DROP TABLE IF EXISTS ',_table_name); PREPARE stmt1 FROM @stmt; EXECUTE stmt1; SET FOREIGN_KEY_CHECKS=1; SET...
39
13
62,603,598
2020-6-26
https://stackoverflow.com/questions/62603598/enforcing-units-on-numbers-using-python-type-hints
Is there a way to use Python type hints as units? The type hint docs show some examples that suggest it might be possible using NewType, but also those examples show that addition of two values of the same "new type" do not give a result of the "new type" but rather the base type. Is there a way to enrich the type defi...
You can do this by creating a type stub file, which defines the acceptable types for the __add__/__radd__ methods (which define the + operator) and __sub__/__rsub__ methods (which define the - operator). There are many more similar methods for other operators of course, but for the sake of brevity this example only use...
14
6
62,584,184
2020-6-25
https://stackoverflow.com/questions/62584184/understanding-the-shape-of-spectrograms-and-n-mels
I am going through these two librosa docs: melspectrogram and stft. I am working on datasets of audio of variable lengths, but I don't quite get the shapes. For example: (waveform, sample_rate) = librosa.load('audio_file') spectrogram = librosa.feature.melspectrogram(y=waveform, sr=sample_rate) dur = librosa.get_durati...
The essential parameter to understanding the output dimensions of spectrograms is not necessarily the length of the used FFT (n_fft), but the distance between consecutive FFTs, i.e., the hop_length. When computing an STFT, you compute the FFT for a number of short segments. These segments have the length n_fft. Usually...
7
15
62,569,594
2020-6-25
https://stackoverflow.com/questions/62569594/request-header-field-access-control-allow-origin-is-not-allowed-by-access-contr
I created an API endpoint using Google Cloud Functions and am trying to call it from a JS fetch function. I am running into errors that I am pretty sure are related to either CORS or the output format, but I'm not really sure what is going on. A few other SO questions are similar, and helped me realize I needed to remo...
Drop the part of your frontend code that adds a Access-Control-Allow-Origin header. Never add Access-Control-Allow-Origin as a request header in your frontend code. The only effect that’ll ever have is a negative one: it’ll cause browsers to do CORS preflight OPTIONS requests even in cases when the actual (GET, POST, e...
17
38
62,555,987
2020-6-24
https://stackoverflow.com/questions/62555987/lightgbm-ranking-example
Can anyone share a minimal example with data for how to train a ranking model with lightgbm? Preferably with the Scikit-Lean api? What I am struggling with is how to pass the label data. My data are page impressions and look like this: X: user1, feature1, ... user2, feature1, ... y: user1, page1, 10 impressions user1, ...
Here is how I used LightGBM LambdaRank. First we import some libraries and define our dataset import numpy as np import pandas as pd import lightgbm df = pd.DataFrame({ "query_id":[i for i in range(100) for j in range(10)], "var1":np.random.random(size=(1000,)), "var2":np.random.random(size=(1000,)), "var3":np.random.r...
9
14
62,658,215
2020-6-30
https://stackoverflow.com/questions/62658215/convergencewarning-lbfgs-failed-to-converge-status-1-stop-total-no-of-iter
I have a dataset consisting of both numeric and categorical data and I want to predict adverse outcomes for patients based on their medical characteristics. I defined a prediction pipeline for my dataset like so: X = dataset.drop(columns=['target']) y = dataset['target'] # define categorical and numeric transformers nu...
The warning means what it mainly says: Suggestions to try to make the solver (the algorithm) converges. lbfgs stand for: "Limited-memory Broyden–Fletcher–Goldfarb–Shanno Algorithm". It is one of the solvers' algorithms provided by Scikit-Learn Library. The term limited-memory simply means it stores only a few vectors ...
128
192
62,658,237
2020-6-30
https://stackoverflow.com/questions/62658237/it-seems-that-the-version-of-the-libffi-library-seen-at-runtime-is-different-fro
This traceback mess up all my program and I still cant fix it I have tried all methods and it didn't help! Here's the problem: ffi_prep_closure(): bad user_data (it seems that the version of the libffi library seen at runtime is different from the 'ffi.h' file seen at compile-time)
It is cffi python package issue. Try to download the source package tar.gz from https://pypi.org/project/cffi/#files and install it manually using: python setup.py install
17
1
62,629,644
2020-6-29
https://stackoverflow.com/questions/62629644/what-the-difference-between-att-mask-and-key-padding-mask-in-multiheadattnetion
What the difference between att_mask and key_padding_mask in MultiHeadAttnetion of pytorch: key_padding_mask – if provided, specified padding elements in the key will be ignored by the attention. When given a binary mask and a value is True, the corresponding value on the attention layer will be ignored. When given a ...
The key_padding_mask is used to mask out positions that are padding, i.e., after the end of the input sequence. This is always specific to the input batch and depends on how long are the sequence in the batch compared to the longest one. It is a 2D tensor of shape batch size × input length. On the other hand, attn_mask...
22
30
62,599,950
2020-6-26
https://stackoverflow.com/questions/62599950/is-storing-data-in-thread-local-storage-in-a-django-application-safe-in-cases
I have seen at many places that using thread local storage to store any data in Django application is not a good practice. But this is the only way I could store my request object. I need to store it because my application has a complex structure. And I can't keep on passing the request object at each function call or ...
Yes, using thread-local storage in Django is safe. Django uses one thread to handle each request. Django also uses thread-local data itself, for instance for storing the currently activated locale. While appservers such as Gunicorn and uwsgi can be configured to utilize multiple threads, each request will still be hand...
7
18
62,580,240
2020-6-25
https://stackoverflow.com/questions/62580240/django-cannot-import-name-config-from-decouple
I'm trying to run this project locally but when i try manage.py makemigrations i keep getting the following error: ImportError: cannot import name 'config' from 'decouple' Here are my steps: Clone the repository from github Create a virtual environment Install the dependencies I made some research but i found nothin...
You might have decouple installed in additional to python-decouple (two different packages). If that is the case simply uninstall decouple pip uninstall decouple And ensure you have python-decouple installed pip install python-decouple
46
181
62,636,860
2020-6-29
https://stackoverflow.com/questions/62636860/why-do-nan-values-make-min-and-max-sensitive-to-order
> import numpy as np > min(50, np.NaN) 50 > min(np.NaN, 50) nan (Same behaviour occurs with max) I know that I can avoid this behaviour by using numpy.nanmin. But what causes the change when the order is reversed? Is min sensitive to input order?
Is min sensitive to input order? Yes. https://docs.python.org/3/library/functions.html#min "If multiple items are minimal, the function returns the first one encountered." The documentation does not specify exactly how "minimal" is defined in the face of items that don't have a consistent order, but it's likely that ...
19
15
62,584,959
2020-6-25
https://stackoverflow.com/questions/62584959/python-mariadb-pip-install-failed-missing-mariadb-config
I am using Linux Ubuntu 18.04 and python 3. I am trying to build a connection between a maria-db and my python scripts. Therefore I have to install the mariadb package. I have already installed: sudo apt install mariadb-server But when i try: pip install mariadb I get following error: Collecting mariadb Using cached ...
To install mariadb python module, you have to install a recent version of MariaDB Connector/C, minimum required version is 3.1.5, afaik Ubuntu 18.04 has 3.0.3. An actual version of Connector/C for bionic is available on the MariaDB Connector/C Download Page. If you want to install it in a special directory, make sure t...
8
7
62,660,347
2020-6-30
https://stackoverflow.com/questions/62660347/airflow-send-email-with-aws-ses
Trying to send an email from apache airflow using AWS Simple Email Service (SES), and it's returning errors that are not helping me solve the problem. I believe it's a configuration issue within SES, but I'm not sure what to change. General info: New SES instance, verified email. Airflow 1.10.10 running on Ubuntu 18.0...
Not sure about the others but we just ran into this error today: ERROR - (554, b'Transaction failed: Unsupported encoding us_ascii.') This is the default value in the class's __init__ method, which isn't valid: https://github.com/apache/airflow/blob/1.10.10/airflow/operators/email_operator.py#L63 You can fix it by pas...
10
11
62,576,326
2020-6-25
https://stackoverflow.com/questions/62576326/python3-process-and-display-webcam-stream-at-the-webcams-fps
How can I read a camera and display the images at the cameras frame rate? I want to continuously read images from my webcam, (do some fast preprocessing) and then display the image in a window. This should run at the frame rate, that my webcam provides (29 fps). It seems like the OpenCV GUI and Tkinter GUI is too slow,...
On this answer I share some considerations on camera FPS VS display FPS and some code examples that demonstrates: The basics on FPS calculation; How to increase the display FPS from 29 fps to 300+ fps; How to use threading and queue efficiently to capture at the closest maximum fps supported by the camera; For anyone...
10
15
62,610,782
2020-6-27
https://stackoverflow.com/questions/62610782/fishers-linear-discriminant-in-python
I have the fisher's linear discriminant that i need to use it to reduce my examples A and B that are high dimensional matrices to simply 2D, that is exactly like LDA, each example has classes A and B, therefore if i was to have a third example they also have classes A and B, fourth, fifth and n examples would always ha...
Before answering your question, I will first touch the basic difference between PCA and (F)LDA. In PCA you don't know anything about underlying classes, but you assume that the information about classes separability lies in the variance of data. So you rotate your original axes (sometimes it is called projecting all th...
13
12
62,658,540
2020-6-30
https://stackoverflow.com/questions/62658540/how-to-combine-a-custom-protocol-with-the-callable-protocol
I have a decorator that takes a function and returns the same function with some added attributes: import functools from typing import * def decorator(func: Callable) -> Callable: func.attr1 = "spam" func.attr2 = "eggs" return func How do I type hint the return value of decorator? I want the type hint to convey two pi...
One can parameterise a Protocol by a Callable: from typing import Callable, TypeVar, Protocol C = TypeVar('C', bound=Callable) # placeholder for any Callable class CallableObj(Protocol[C]): # Protocol is parameterised by Callable C ... attr1: str attr2: str __call__: C # ... which defines the signature of the protocol ...
17
11
62,622,704
2020-6-28
https://stackoverflow.com/questions/62622704/attributeerror-module-tensorflow-has-no-attribute-compat-when-loading-tf-co
I can see that this question has been asked before here tensorflow-has-no-attribute-compat but the answer given was to Microsoft Visual C++ 2015-2019 Redistributable (x64) It did not work for the previous member it has not worked for me either. I have visual studio 2019 installed. I downloaded it anyways and ran a rep...
This is usually caused by the broken TensorFlow-estimator module. simply do a pip install tensorflow-estimator==2.1.*
16
16
62,559,540
2020-6-24
https://stackoverflow.com/questions/62559540/how-can-i-set-up-a-pusher-server-with-flask
I am trying to setup a simple flask server: import envkey import pysher from flask import Flask # from predictor import PythonPredictor app = Flask(__name__) pusher = pysher.Pusher(envkey.get('PUSHER_KEY')) def my_func(*args, **kwargs): print("processing Args:", args) print("processing Kwargs:", kwargs) # We can't subs...
Specifying my Pusher cluster during initalization helped me get rid of that issue: pusher = pysher.Pusher( key=envkey.get('PUSHER_KEY'), # Or however you get the key cluster="eu", # Add cluster! )
9
3
62,666,926
2020-6-30
https://stackoverflow.com/questions/62666926/str-function-of-class-ported-from-rust-to-python-using-pyo3-doesnt-get-used
I am using the pyo3 rust crate (version 0.11.1) in order to port rust code, into cpython (version 3.8.2) code. I have created a class called my_class and defined the following functions: new, __str__, and __repr__. TL;DR: The __str__ function exists on a class ported from rust using the pyo3 crate, but doesn't get pri...
I'm pretty sure this is because you need to implement these methods through the PyObjectProtocol trait. Many Python __magic__ methods correspond to C-level function pointer slots in a type object's memory layout. A type implemented in C needs to provide a function pointer in the slot, and Python will automatically gene...
11
12
62,643,102
2020-6-29
https://stackoverflow.com/questions/62643102/creating-a-dsl-expressions-parser-rules-engine
I'm building an app which has a feature for embedding expressions/rules in a config yaml file. So for example user can reference a variable defined in yaml file like ${variables.name == 'John'} or ${is_equal(variables.name, 'John')}. I can probably get by with simple expressions but I want to support complex rules/expr...
I don't know if you use Golang or not, but if you use it, I recommend this https://github.com/antonmedv/expr. I have used it for parsing bot strategy that (stock options bot). This is from my test unit: func TestPattern(t *testing.T) { a := "pattern('asdas asd 12dasd') && lastdigit(23asd) < sma(50) && sma(14) > sma(12)...
10
3
62,572,389
2020-6-25
https://stackoverflow.com/questions/62572389/django-drf-yasg-how-to-add-description-to-tags
Swagger documentation says you can do that: https://swagger.io/docs/specification/grouping-operations-with-tags/ But unfortunately drf-yasg not implementing this feature: https://github.com/axnsan12/drf-yasg/issues/454 It is said, that I can add custom generator class, but it is a very general answer. Now I see that dr...
Unfortunately, this is a current issue with drf-yasg. To actually achieve this, you need to create your own schema generator class: from drf_yasg.generators import OpenAPISchemaGenerator class CustomOpenAPISchemaGenerator(OpenAPISchemaGenerator): def get_schema(self, request=None, public=False): """Generate a :class:`....
11
5
62,624,980
2020-6-28
https://stackoverflow.com/questions/62624980/vscode-python-pandas-dataframe-intellisense-doesnt-show-attributes-method
After importing Pandas, when creating a pandas dataframe, Intellisense doesn't show the available attributes/methods of the created object.(Image 2, where I try to use the .head() function). It detects the module pd(pandas) methods without any problem (see Image 1). I don't have this problem when running a Jupyter Note...
The detection isn't working because IntelliSense has a hard time with pandas (and pandas.read_csv() especially). It works in Jupyter because it's accessing the live data while IntelliSense has to infer everything from the source code statically. I would advise trying out Pylance as it's the new language server from Mic...
11
9
62,654,908
2020-6-30
https://stackoverflow.com/questions/62654908/layer-is-not-connected-no-input-to-return-error-while-trying-to-get-intermedi
I'm trying to access predictions of intermediate layers of a model during training using custom callback. Following stripped down version of the actual code demonstrates the issue. import tensorflow as tf import numpy as np class Model(tf.keras.Model): def __init__(self, input_shape=None, name="cus_model", **kwargs): s...
I also cannot get the self.layers[0].input because of the same error, but maybe u can directly call function defined in Model like this: class Model(tf.keras.Model): def __init__(self, input_shape=None, name="cus_model", **kwargs): super(Model, self).__init__(name=name, **kwargs) if not input_shape: input_shape = (10,)...
8
2
62,667,158
2020-6-30
https://stackoverflow.com/questions/62667158/how-do-i-increase-the-line-thickness-for-sns-lineplot
I have a few seaborn lineplots and I can't figure out how to increase the width of my lines. Here is my code #graph 1 sns.lineplot(x="date", y="nps", data=df_nps, ax=ax1, label="NPS", color='#0550D0') sns.lineplot(x="date", y="ema28", data=df_nps, ax=ax1, label="EMA28", color='#7DF8F3') sns.lineplot(x="date", y="ema7",...
As you can see from seaborn.lineplot documentation, the function accepts matplotlib.axes.Axes.plot() arguments, which means you can pass the same arguments you can to matplotlib function in this documentation. If you want to simply adjust the width of your lineplots I find this the easiest: pass an argument linewidth =...
34
50
62,658,112
2020-6-30
https://stackoverflow.com/questions/62658112/how-to-download-all-the-python-packages-mentioned-in-the-requirement-txt-to-a-fo
I want to download all the python packages mentioned in the requirement.txt to a folder in Linux. I don't want to install them. I just need to download them. python version is 3.6 list of packages in the requirement.txt aiodns==0.3.2 aiohttp==1.1.5 amqp==1.4.7 anyjson==0.3.3 astroid==1.3.2 asyncio==3.4.3 asyncio-redis=...
The documentation gives what you want : pip download pip download does the same resolution and downloading as pip install, but instead of installing the dependencies, it collects the downloaded distributions into the directory provided source So you may try these option with pip download : pip download -r requirement...
8
5
62,658,847
2020-6-30
https://stackoverflow.com/questions/62658847/issue-with-using-snowflake-connector-python-with-python-3-x
I've spent half a day trying to figure it out on my own but now I've run out of ideas and googling requests. So basically what I want is to connect to our Snowflake database using snowflake-connector-python package. I was able to install the package just fine (together with all the related packages that were installed ...
AttributeError: module 'snowflake' has no attribute 'connector' Your test code is likely in a file named snowflake.py which is causing a conflict in the import (it is ending up importing itself). Rename the file to some other name and it should allow you to import the right module and run the connector functions.
13
16
62,649,745
2020-6-30
https://stackoverflow.com/questions/62649745/is-it-possible-to-change-font-sizes-according-to-node-sizes
According to NetworkX, draw_networkx(G, pos=None, arrows=True, with_labels=True, **kwds), node_size can be scalar or array but font_size needs to be integer. How can I change the font size to be bigger if the nodes are big? In fact, is it possible to change font sizes according to node sizes?
There isn't really a way of passing an array of font sizes. Both nx.draw and draw_networkx_labels only accept integers as font sizes for all labels. You'll have to loop over the nodes and add the text via matplotlib specifying some size. Here's an example, scaling proportionally to the node degree: from matplotlib.pypl...
10
20
62,620,268
2020-6-28
https://stackoverflow.com/questions/62620268/display-gpu-usage-while-code-is-running-in-colab
I have a program running on Google Colab in which I need to monitor GPU usage while it is running. I am aware that usually you would use nvidia-smi in a command line to display GPU usage, but since Colab only allows one cell to run at once at any one time, this isn't an option. Currently, I am using GPUtil and monitori...
Used wandb to log system metrics: !pip install wandb import wandb wandb.init() Which outputs a URL in which you can view various graphs of different system metrics.
21
23
62,652,159
2020-6-30
https://stackoverflow.com/questions/62652159/how-to-get-dynamodb-to-only-return-certain-columns
Hello, I have a simple dynamodb table here filled with placeholder values. How would i go about retrieving only sort_number, current_balance and side with a query/scan? I'm using python and boto3, however, just stating what to configure for each of the expressions and parameters is also enough.
Within the Boto3 SDK you can use: get_item if you're trying to retrieve a specific value query, if you're trying to get values from a single partition (the hash key). scan if you're trying to retrieve values from across multiple parititions. Each of these have a parameter named ProjectionExpression, using this parame...
8
9
62,649,203
2020-6-30
https://stackoverflow.com/questions/62649203/how-did-python-implement-type-free-variables-from-a-statically-typed-language
I know most of python is implemented in C. I was wondering that how does python work under the hood(in terms of its implementation in C) when it comes to determining what type of variable it is in this case lets say x = 5 now if the check the type of x it will say class int but how is that implemented in C? What checks...
This is a huge subject. The below document will give you more understanding. https://intopythoncom.files.wordpress.com/2017/04/internalsofcpython3-6-1.pdf Like you said a simple example for integer types To hold an integer type object, there is structure defined in C as said below typedef struct { PyObject_HEAD long ob...
10
6
62,646,573
2020-6-29
https://stackoverflow.com/questions/62646573/np-uint16-isnt-the-same-as-np-uint16
I'm attempting to map numpy dtypes to associated values using a dictionary lookup. I observe the following counterintuitive behavior: dtype = np.uint16 x = np.array([0, 1, 2], dtype=dtype) assert x.dtype == dtype d = {np.uint8: 8, np.uint16: 16, np.uint32: 32, np.float32: 32} print(dtype in d) # prints True print(x.dty...
Dtypes don't work like they look at first glance. np.uint16 isn't a dtype object. It's just convertible to one. np.uint16 is a type object representing the type of array scalars of uint16 dtype. x.dtype is an actual dtype object, and dtype objects implement == in a weird way that's non-transitive and inconsistent with ...
7
10
62,641,627
2020-6-29
https://stackoverflow.com/questions/62641627/how-to-tell-pip-that-a-packageopencv-has-been-compiled-from-source
Because of some specific requirements I needed to compile a package (opencv with cuda support) from source. After successfull compilation my python-environment is able to import opencv without a problem: $ python Python 3.7.7 (default, Mar 10 2020, 15:16:38) [GCC 7.5.0] on linux Type "help", "copyright", "credits" or "...
After you compile opencv, you can install the package with pip or python setup.py install. I would recommend building a Python wheel for opencv+cuda, and then installing that wheel. Having a wheel will make installing easier if you ever need to reinstall or make a new environment. The general steps are: Compile opencv...
10
2
62,641,506
2020-6-29
https://stackoverflow.com/questions/62641506/in-numpy-how-to-compare-all-values-in-an-axis
For a numpy array, how can I change the value only if all elements along an axis are equal to another array? For example... array = np.array([[1, 0, 1], [0, 0, 1], [1, 1, 0], [0, 0, 0], [1, 0, 1]]) I want to replace all [1, 0, 1] with [1, 1, 1]... so that array becomes array([[1, 1, 1], [0, 0, 1], [1, 1, 0], [0, 0, 0]...
Try with: array[(array == [1, 0, 1]).all(axis=1)] = [1, 1, 1]
7
11
62,641,851
2020-6-29
https://stackoverflow.com/questions/62641851/how-to-make-two-lists-out-of-two-elements-tuples-that-are-stored-in-a-list-of-li
I have a list which contains many lists and in those there 4 tuples. my_list = [[(12, 1), (10, 3), (4, 0), (2, 0)], [(110, 1), (34, 2), (12, 1), (55, 3)]] I want them in two separate lists like: my_list2 = [12,10,4,2,110,34,12,55] my_list3 = [1,3,0,0,1,2,1,3] my attempt was using the map function for this. my_list2 ,...
Your approach is quite close, but you need to flatten first: from itertools import chain my_list = [[(12, 1), (10, 3), (4, 0), (2, 0)], [(110, 1), (34, 2), (12, 1), (55, 3)]] my_list2 , my_list3 = map(list,zip(*chain.from_iterable(my_list))) my_list2 # [12, 10, 4, 2, 110, 34, 12, 55] my_list3 # [1, 3, 0, 0, 1, 2, 1, 3]...
9
10
62,639,387
2020-6-29
https://stackoverflow.com/questions/62639387/python-expand-list-of-strings-by-adding-n-elements-for-each-original-element
I have the following list of strings: l1 = ['one','two','three'] I want to obtain a list that has, say, these same elements repeated n times. If n=3 I'd get: l2 = ['one','one','one','two','two','two','three','three','three'] What I am trying is this: l2 = [3*i for i in l1] But what I obtain is this: l2 = ['oneoneone...
l2 = [j for i in l1 for j in 3*[i]] This gives: ['one', 'one', 'one', 'two', 'two', 'two', 'three', 'three', 'three'] This is equivalent to: l2 = [] for i in l1: for j in 3*[i]: l2.append(j) Note that 3*[i] creates a list with 3 repeated elements (e.g. ['one', one', 'one'])
9
14
62,620,539
2020-6-28
https://stackoverflow.com/questions/62620539/how-to-append-a-total-row-to-pandas-dataframe-with-multiindex
Suppose you have a simple pandas dataframe with a MultiIndex: df = pd.DataFrame(1, index=pd.MultiIndex.from_tuples([('one', 'elem1'), ('one', 'elem2'), ('two', 'elem1'), ('two', 'elem2')]), columns=['col1', 'col2']) Printed as a table: col1 col2 one elem1 1 1 elem2 1 1 two elem1 1 1 elem2 1 1 Question: How do you ad...
The solution You have to remove the index of df.sum() and just use the values: df.loc['Total', :] = df.sum().values Output: col1 col2 one elem1 1.0 1.0 elem2 1.0 1.0 two elem1 1.0 1.0 elem2 1.0 1.0 Total 4.0 4.0 Why was the second attempt wrong? The second attempt was almost correct. But df.sum() has the Index(['co...
8
10
62,578,276
2020-6-25
https://stackoverflow.com/questions/62578276/error-no-matching-distribution-found-for-wheel-dash-bootstrap-components
I am trying to install packages in an offline manner. However, when I downloaded all packages and tried to install these packages on another computer, some error has emerged as shown in the following figure. This seems like it is failed to install the "dash-bootstrap-components" package. How can I solve it? By the way,...
I have solved this problem by manually download the "wheel" package from the internet and put it into the folder.
10
13
62,614,078
2020-6-27
https://stackoverflow.com/questions/62614078/why-does-mutating-a-list-in-a-tuple-raise-an-exception-but-mutate-it-anyway
I am not sure I quite understand what's happening in the below mini snippet (on Py v3.6.7). It would be great if someone can explain to me as to how can we mutate the list successfully even though there's an error thrown by Python. I know that we can mutate a list and update it, but what’s with the error? Like I was un...
My gut feeling is that the line x[0] += [3, 4] first modifies the list itself so [1, 2] becomes [1, 2, 3, 4], then it tries to adjust the content of the tuple which throws a TypeError, but the tuple always points towards the same list so its content (in terms of pointers) is not modified while the object pointed at is ...
15
9
62,611,167
2020-6-27
https://stackoverflow.com/questions/62611167/plotly-round-hover-decimals-in-charts
How do you round numbers for display in a plotly graph? I included an MRE below. Essentially I wanted rounded numbers to appear when the user hovers over the bar. import plotly.express as px import pandas as pd df = pd.DataFrame({'num': [1, 2, 3], 'sqrt': pd.Series([1, 2, 3]) ** 0.5}) fig = px.bar(df, x='num', y='sqrt'...
You can do it two ways like this: METHOD-1: Using pd.series.round function. import plotly.express as px import pandas as pd df = pd.DataFrame({'num': [1, 2, 3], 'sqrt': (pd.Series([1, 2, 3]) ** 0.5).round(2)}) fig = px.bar(df, x='num', y='sqrt', title='Square root') fig.show() METHOD-2: Using python builtin round func...
10
13
62,604,893
2020-6-27
https://stackoverflow.com/questions/62604893/what-is-right-extension-for-plotly-in-jupyterlab
Plotly is not working in Jupyterlab. I assume that there is a conflict in required extensions but I'm not sure. On checking troubleshooting on Plotly https://plotly.com/python/troubleshooting/ , they advise to remove extensions and install them again. But I found that there is additional extension that came with Jupyte...
Enter 'jupyter labextension list' in a terminal or command to run the environment status. The example below shows my environment information with 'jupyter lab' running successfully. xxxxx-no-iMac:~ xxxxx$ jupyter labextension list JupyterLab v2.1.5 Known labextensions: app dir: /Library/Frameworks/Python.framework/Vers...
13
2
62,606,345
2020-6-27
https://stackoverflow.com/questions/62606345/tensorflow-2-2-0-error-predictions-must-be-0-condition-x-y-did-not-hold
I get the following error message when working on a named-entity-recognition task: tensorflow.python.framework.errors_impl.InvalidArgumentError: assertion failed: [predictions must be >= 0] [Condition x >= y did not hold element-wise:] [x (bidirectional_lstm_model/time_distributed/Reshape_1:0) = ] [[[-0.100267865 -0.10...
you are missing the last layer activation: decoder_dense = layers.TimeDistributed(layers.Dense(number_of_tags, name='decoder_dense'))(encoder_bidirectional_rnn) You should specify that you want a softmax, leaving the activation as default is actually a linear activation, meaning that you can have any value, therefore ...
11
12
62,573,039
2020-6-25
https://stackoverflow.com/questions/62573039/prevent-changing-indentation-from-tabs-to-spaces
I have VSCode installed and python 3.6.8 I use tabs for my indentation. But when ever I save the file, all the tabs are being converted to spaces. This might be because of the formatter I use, i.e. Black. How do I prevent the formatter from doing that(Do all your formatting except inter-changing indents with spaces)? T...
Assuming you don't have VS Code set up to insert space into tabs, then Black will very likely replace them with spaces as that's the norm in the Python community and Black takes a very opinionated view on how to format Python code. You could try another formatter like yapf or autopep8 to see if they will leave physical...
9
0
62,599,036
2020-6-26
https://stackoverflow.com/questions/62599036/python-requests-is-slow-and-takes-very-long-to-complete-http-or-https-request
When requesting a web resource or website or web service with the requests library, the request takes a long time to complete. The code looks similar to the following: import requests requests.get("https://www.example.com/") This request takes over 2 minutes (exactly 2 minutes 10 seconds) to complete! Why is it so slo...
There can be multiple possible solutions to this problem. There are a multitude of answers on StackOverflow for any of these, so I will try to combine them all to save you the hassle of searching for them. In my search I have uncovered the following layers to this: First, try logging For many problems, activating loggi...
59
165
62,597,959
2020-6-26
https://stackoverflow.com/questions/62597959/seaborn-violinplot-transparency
I would like to have increasingly transparent violins in a seaborn.violinplot. I tried the following: import seaborn as sns tips = sns.load_dataset("tips") ax = sns.violinplot(x="day", y="total_bill", data=tips, color='r', alpha=[0.8, 0.6, 0.4, 0.2]) Which does not result in the desired output:
Found this thread looking to change alpha values in general for violin plots, it seems you need to access matplotlib.PolyColections from your ax to even be able to set the alpha values, but since you need to access them anyways, you might as well set alpha values individually (at least in your case since you want indiv...
17
19
62,589,193
2020-6-26
https://stackoverflow.com/questions/62589193/how-to-get-class-diagram-from-python-source-code
I try to get a class diagram from Python source code in Client folder with pyreverse but it requires __init__.py (venv) C:\Users\User\Desktop\project> pyreverse Client parsing Client\__init__.py... Failed to import module Client\__init__.py with error: No module named Client\__init__.py. I don't find any solution for ...
Thanks to @Anwarvic and @bruno, I came up with the solution for this. Firstly, create empty __init__.py file inside Client folder: (venv) C:\Users\User\Desktop\project\Client> type NUL > __init__.py Then go to the parent folder of the Client folder where I want to get the class diagram: (venv) C:\Users\User\Desktop\pr...
9
10
62,586,878
2020-6-26
https://stackoverflow.com/questions/62586878/why-does-the-pip-requirements-file-contain-file-instead-of-version-number
I created the requirements.txt with pip freeze > requirements.txt. Some modules show the @file..... instead of the version #. What does it mean and why it show? Conda: 4.8.3 Here is the result of requirements.txt. e.g. astroid, flask-admin, matplotlib shows "@ file" below astroid @ file:///opt/concourse/worker/volumes/...
This is a special syntax (supported since pip 19.1) to install packages from VCS repositories : package_name @ git+https://githost/<repo>.git@<commit_id> See https://pip.readthedocs.io/en/stable/reference/pip_install/#requirement-specifiers and https://www.python.org/dev/peps/pep-0440/#direct-references
12
7
62,578,492
2020-6-25
https://stackoverflow.com/questions/62578492/what-is-the-time-complexity-of-checking-membership-in-dict-items
What is the time complexity of checking membership in dict.items()? According to the documentation: Keys views are set-like since their entries are unique and hashable. If all values are hashable, so that (key, value) pairs are unique and hashable, then the items view is also set-like. (Values views are not treated as...
Lookup in an instance of dict_items is an O(1) operation (though one with an arbitrarily large constant, related to the complexity of comparing values.) dictitems_contains doesn't simply try to hash the tuple and look it up in a set-like collection of key/value pairs. (Note: all of the following links are just to diff...
20
11
62,585,395
2020-6-25
https://stackoverflow.com/questions/62585395/not-able-to-install-jaxlib
I am trying to install jaxlib on my windows 10 by the following command which I found on the documentation.. pip install jaxlib It shows the following error Collecting jaxlib Could not find a version that satisfies the requirement jaxlib (from versions: None) No matching distribution found for jaxlib
Jaxlib is not supported on windows you can see it here.. https://github.com/google/jax/issues/438
15
10
62,564,117
2020-6-24
https://stackoverflow.com/questions/62564117/why-sorted-in-python-didnt-accept-positional-arguments
a=[1,2,3,4] def func(x): return x**x b=sorted(a,func) this line always gives a error-> TypeError: sorted expected 1 argument, got 2 in fact the syntax of sorted is sorted(iterable,key,reverse), in which key and reverse are optional, so according to this, second parameter i pass must go with key. and when i def my ow...
In addition to @user4815162342's answer, From the documentation, sorted(iterable, *, key=None, reverse=False) Notice the * between iterable and key parameter. That is the python syntax for specifying that every parameter after * must be specified as keyword arguments. So your custom function should be defined as the f...
7
8
62,561,254
2020-6-24
https://stackoverflow.com/questions/62561254/print-in-scientific-format-with-powers-of-ten-being-only-multiples-of-3
I haven't found a way to only get exponents which are multiples of 3, when displaying numbers in the scientific format. Neither did I succeed writing a simple custom formatting function. Here is a quick example: Normal behaviour using scientific notation with pythons .format(): numbers = [1.2e-2, 1.3e-3, 1.5e5, 1.6e6] ...
Well, it depends on if you want the output format to always adjust to the nearest power of 3, or if you want it to adjust to the nearest lower power of 3. Basically it comes to: how you handle 1.50E+05? Should it be 150.00E+03 or 0.15E+06? Case 1: nearest lower power of 3 from math import log10,floor numbers = [1.2e-2,...
8
6
62,554,840
2020-6-24
https://stackoverflow.com/questions/62554840/how-to-change-only-the-maximum-value-of-a-group-in-pandas-dataframe
I have following dataset Item Count A 60 A 20 A 21 B 33 B 33 B 32 Code to reproduce: import pandas as pd df = pd.DataFrame([ ['A', 60], ['A', 20], ['A', 21], ['B', 33], ['B', 33], ['B', 32], ], columns=['Item', 'Count']) Suppose I have to Change only the maximum value of each group of "Item" column by adding 1. the o...
Use idxmax: idx = df.groupby("Item")["Count"].idxmax() df["New_Count"] = df["Count"] df.loc[idx, "New_Count"] += 1 This will only increment the first occurrence of th maximum in each group. If you want to increment all the maximum values in the case of a tie, you can use transform instead. Just replace the first line ...
18
12
62,554,991
2020-6-24
https://stackoverflow.com/questions/62554991/how-do-i-install-python-on-alpine-linux
How do I install python3 and python3-pip on an alpine based image (without using a python image)? $ apk add --update python3.8 python3-pip ERROR: unsatisfiable constraints: python3-pip (missing): required by: world[python3-pip] python3.8 (missing): required by: world[python3.8]
This is what I use in a Dockerfile for an alpine image: # Install python/pip ENV PYTHONUNBUFFERED=1 RUN apk add --update --no-cache python3 && ln -sf python3 /usr/bin/python RUN python3 -m ensurepip RUN pip3 install --no-cache --upgrade pip setuptools
181
263
62,549,990
2020-6-24
https://stackoverflow.com/questions/62549990/what-does-next-and-iter-do-in-pytorchs-dataloader
I have the following code: import torch import numpy as np import pandas as pd from torch.utils.data import TensorDataset, DataLoader # Load dataset df = pd.read_csv(r'../iris.csv') # Extract features and target data = df.drop('target',axis=1).values labels = df['target'].values # Create tensor dataset iris = TensorDat...
These are built-in functions of python, they are used for working with iterables. Basically iter() calls the __iter__() method on the iris_loader which returns an iterator. next() then calls the __next__() method on that iterator to get the first iteration. Running next() again will get the second item of the iterator,...
38
43
62,547,848
2020-6-24
https://stackoverflow.com/questions/62547848/should-isinstance-check-against-typing-or-collections-abc
Both typing and collections.abc includes similar type such as Mapping, Sequence, etc. Based on the python documentation, it seems that collections.abc is preferred for type checking: This module provides abstract base classes that can be used to test whether a class provides a particular interface; for example, whethe...
Many of the typing generic classes are just aliases to the abc ones. Just as an example from the docs, Hashable: class typing.Hashable An alias to collections.abc.Hashable Also, isinstance(abc.Hashable, typing.Hashable) isinstance(typing.Hashable, abc.Hashable) are both True, making it clear they are equivalent in t...
12
4
62,510,114
2020-6-22
https://stackoverflow.com/questions/62510114/converting-from-py-to-ipynb
I wrote a juypter notebook that has been converted to .py somehow. I would like it back in the original format. Does anyone know how to do that? There is a previous stack overflow question about this, but the solution doesn't work for me. Converting to (not from) ipython Notebook format
The question was edited so this isn't as direct of an answer as it once was. Nevertheless, if you accidentally changed the extension of your Python notebook from .ipynb to .py as the OP did when originally asking the question, this is the answer for you. Just rename it changing the extension e.g. for linux/macos mv <fi...
57
12
62,423,613
2020-6-17
https://stackoverflow.com/questions/62423613/installing-aws-cli-v2-through-pip-on-windows
Is it possible to install AWS CLI v2 through PIP on Windows? In the instructions the recommended way to install is via MSI, but I want to use PIP. What if I install CLI like given on Github in a Linux way: python -m pip install awscli Will it install v1 or v2 by default?
pip install awscliv2 This single command should help you install AWS CLI v2
12
2
62,473,806
2020-6-19
https://stackoverflow.com/questions/62473806/how-to-cache-a-variable-with-flask
I am building a web form using Flask and would like the user to be able to enter multiple entries, and give them the opportunity to regret an entry with an undo button, before sending the data to the database. I am trying to use Flask-Caching but have not managed to set it up properly. I have followed The Flask Mega-Tu...
You first statement makes me wonder if you are really looking for caching. It seems you are looking for session data storage. Some possibilities... 1. Session Data Storage Client-Side: Store session client data as cookies using built-in Flask session objects. From docs: This can be any small, basic information about t...
7
11
62,489,359
2020-6-20
https://stackoverflow.com/questions/62489359/why-does-pandas-use-nan-from-numpy-instead-of-its-own-null-value
This is somewhat of a broad topic, but I will try to pare it to some specific questions. In starting to answer questions on SO, I have found myself sometimes running into a silly error like this when making toy data: In[0]: import pandas as pd df = pd.DataFrame({"values":[1,2,3,4,5,6,7,8,9]}) df[df < 5] = np.nan Out[0]...
A main dependency of pandas is numpy, in other words, pandas is built on-top of numpy. Because pandas inherits and uses many of the numpy methods, it makes sense to keep things consistent, that is, missing numeric data are represented with np.NaN. (This choice to build upon numpy has consequences for other things too. ...
9
8
62,527,331
2020-6-23
https://stackoverflow.com/questions/62527331/what-does-hexdigest-do-in-python
We need such a code for hashing: from hashlib import sha256 Hash = sha256(b"hello").hexdigest() #Hash = '2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824' hexdigest seems to be doing the main thing, because without it we will get the following result: Hash = sha256(b"hello") #Hash = <sha256 HASH object...
The actual digest is a really big number. It is conventionally represented as a sequence of hex digits, as we humans aren't very good at dealing with numbers with more than a handful of digits (and hex has the advantage that it reveals some types of binary patterns really well; for example, you'd be hard pressed to rea...
12
16
62,419,767
2020-6-17
https://stackoverflow.com/questions/62419767/how-to-reload-python-package-after-pip-install-in-visual-studio-code
I wonder how to reload Python package after pip install in Visual Studio Code? pip install package-A pip list package-A does not exist Restart 'Visual Studio Code' Is the only way to restart?
The best answer I've found is to use Developer: Reload Window in the command palette like @rioV8 suggested. You can either use the command palette or you can change the key mappings as described here. There's already a Ctrl + R key mapping for reloading the window, but it's got a 'when' condition attached to it so I ch...
16
17
62,523,166
2020-6-22
https://stackoverflow.com/questions/62523166/how-can-i-generate-an-azure-blob-sas-url-in-python
I am trying to generate blob SAS URLs on the fly using the azure-storage-blob package. This solution only works if you have the now-deprecated azure-storage package, which cannot be installed anymore. I need a way to mimic the behaviour of BlockBlobService.generate_blob_shared_access_signature to generate a blob SAS UR...
Take a look to the following code: from datetime import datetime, timedelta from azure.storage.blob import BlobClient, generate_blob_sas, BlobSasPermissions account_name = 'STORAGE_ACCOUNT_NAME' account_key = 'STORAGE_ACCOUNT_ACCESS_KEY' container_name = 'CONTAINER_NAME' blob_name = 'IMAGE_PATH/IMAGE_NAME' def get_blob...
10
21
62,488,423
2020-6-20
https://stackoverflow.com/questions/62488423/brokenprocesspool-while-running-code-in-jupyter-notebook
I am learning about multiprocessing in python. I have the following code snippet: import time import concurrent.futures def wait(seconds): print(f'Waiting {seconds} seconds...') time.sleep(seconds) return f'Done' if __name__ == "__main__": with concurrent.futures.ProcessPoolExecutor() as executor: p = executor.submit(w...
I got it to work! I saved the wait function in a separate python file called wait.py and imported it in jupyter notebook. wait.py: import time def wait(seconds): print(f'Waiting {seconds} seconds...') time.sleep(seconds) return f'Done' ipynb file: import concurrent.futures import wait #import the wait file if __name__...
15
13
62,469,881
2020-6-19
https://stackoverflow.com/questions/62469881/how-to-convert-docx-to-pdf-on-mac-os-with-python
I've looked up several SO and other web pages but I haven't found anything that works. The script I wrote, opens a docx, changes some words and then saves it in a certain folder as a docx. However, I want it to save it as a pdf but I don't know how to. This is an example of the code I'm working with: # Opening the orig...
you can use docx2pdf by making the changes first and then coverting. Use pip to install on mac (I am guessing you already have it but it is still good to include). pip install docx2pdf Once docx2pdf is installed, you can your docx file in inputfile and put an empty .pdf file in outputfile. from docx2pdf import convert...
8
8
62,511,086
2020-6-22
https://stackoverflow.com/questions/62511086/how-to-document-kwargs-according-to-numpy-style-docstring
So, I've found posts related to other styles and I am aware of this NumPy page about the documentation but I am confused. I didn't understand how to add each kwargs to the parameters section of a method. This is from the given web page: def foo(var1, var2, *args, long_var_name='hi', **kwargs): r"""Summarize the functio...
Summary The **kwargs are not typically listed in the function, but instead the final destination of the **kwargs is mentioned. For example: **kwargs Instructions on how to decorate your plots. The keyword arguments are passed to `matplotlib.axes.Axes.plot()` If there are multiple possible targets, they are all listed...
11
11
62,493,718
2020-6-21
https://stackoverflow.com/questions/62493718/how-asyncio-sleep-isnt-blocking-thread
I'm reading 'Fluent Python' by 'Luciano Ramalho' over and over, but I couldn't understand asyncio.sleep's behavior inside asyncio. Book says at one part: Never use time.sleep in asyncio coroutines unless you want to block the main thread, therefore freezing the event loop and probably the whole application as well. (....
The function asyncio.sleep simply registers a future to be called in x seconds while time.sleep suspends the execution for x seconds. You can test how both behave with this small example and see how asyncio.sleep(1) doesn't actually give you any clue on how long it will "sleep" because it's not what it really does: imp...
10
10
62,453,756
2020-6-18
https://stackoverflow.com/questions/62453756/how-to-move-jupyter-notebook-cells-up-down-using-keyboard-shortcut
Anyone knows keyboard shortcut to move cells up or down in Jupyter notebook? Cannot find the shortcut, any clues?
Further to honeybadger's response, you can see when you open up the Edit Command Mode shortcuts dialog box that there are no shortcuts defined for moving a cell up and down, by default: I simply typed in my preferred combination Ctrl-Shift-Down and Ctrl-Shift-Up in the 'add shortcut' field, and pressed Enter. This is ...
39
8
62,528,272
2020-6-23
https://stackoverflow.com/questions/62528272/what-does-asyncio-create-task-do
What does asyncio.create_task() do? A bit of code that confuses me is this: import asyncio async def counter_loop(x, n): for i in range(1, n + 1): print(f"Counter {x}: {i}") await asyncio.sleep(0.5) return f"Finished {x} in {n}" async def main(): slow_task = asyncio.create_task(counter_loop("Slow", 4)) fast_coro = coun...
What does asyncio.create_task() do? It submits the coroutine to run "in the background", i.e. concurrently with the current task and all other tasks, switching between them at await points. It returns an awaitable handle called a "task" which you can also use to cancel the execution of the coroutine. It's one of the ...
131
157
62,532,559
2020-6-23
https://stackoverflow.com/questions/62532559/list-of-object-attributes-in-pydantic-model
I use Fast API to create a web service. There are following sqlAlchemy models: class User(Base): __tablename__ = 'user' account_name = Column(String, primary_key=True, index=True, unique=True) email = Column(String, unique=True, index=True, nullable=False) roles = relationship("UserRole", back_populates="users", lazy=F...
If you are okay with handling the how to "get user from api" problem statement by modifying the fastapi path definition, see below. Can you change the response model used by the fastapi path definition in order to handle the desired output format? Example pydantic response model definition: class UserResponse(BaseModel...
9
6
62,444,612
2020-6-18
https://stackoverflow.com/questions/62444612/should-i-list-class-methods-in-the-class-docstring
I am a bit confused by the PEP257 standard for documenting classes. It says, "The docstring for a class should summarize its behavior and list the public methods and instance variables" But it also says that all functions should have dosctrings (which, of course, I want, so that help() works). But this seems to involve...
Yes just drop the methods section from the class docstring. I've never ever seen something like that used.(It is used in few places in the standard library.) The class docstring needs to just describe the class and the docstring of individual methods then handle describing themselves. Also the wording in the PEP to me ...
8
9
62,456,558
2020-6-18
https://stackoverflow.com/questions/62456558/is-one-hot-encoding-required-for-using-pytorchs-cross-entropy-loss-function
For example, if I want to solve the MNIST classification problem, we have 10 output classes. With PyTorch, I would like to use the torch.nn.CrossEntropyLoss function. Do I have to format the targets so that they are one-hot encoded or can I simply use their class labels that come with the dataset?
nn.CrossEntropyLoss expects integer labels. What it does internally is that it doesn't end up one-hot encoding the class label at all, but uses the label to index into the output probability vector to calculate the loss should you decide to use this class as the final label. This small but important detail makes comput...
19
27
62,543,342
2020-6-23
https://stackoverflow.com/questions/62543342/gunicorn-gevent-workers-vs-uvicorn-asgi
I'm currently developing a service in Django which makes use of a slow external API (takes about 10s to get a response), which means the connections to my server are kept open waiting for the external API to respond, and occupying worker time/resources. I know I can use gunicorn's thread or gevent workers to add concur...
Gunicorn has a pre-fork worker model A pre-fork worker model basically means a master creates forks which handle each request. A fork is a completely separate *nix process (Source). Uvicorn is a ASGI server running uvloop Python async needs a event loop for it to use it's async features. And uvloop is an alternative to...
40
18
62,468,402
2020-6-19
https://stackoverflow.com/questions/62468402/query-parameters-from-pydantic-model
Is there a way to convert a pydantic model to query parameters in fastapi? Some of my endpoints pass parameters via the body, but some others pass them directly in the query. All this endpoints share the same data model, for example: class Model(BaseModel): x: str y: str I would like to avoid duplicating my definiti...
The documentation gives a shortcut to avoid this kind of repetitions. In this case, it would give: from fastapi import Depends @app.post("/test-query-params") def test_query(model: Model = Depends()): pass This will allow you to request /test-query-params?x=1&y=2 and will also produce the correct OpenAPI description f...
38
45
62,461,847
2020-6-19
https://stackoverflow.com/questions/62461847/django-insert-or-update-record
the insert works but multiple data enters, when two data are inserted when I try to update, it does not update the record I just want that when the data is already have record in the database, just update. if not, it will insert def GroupOfProduct(request): global productOrderList relatedid_id = request.POST.get("relat...
Please use update_or_create method. This method if a data is exist then updated the details else newly inserted. Reference: https://www.kite.com/python/docs/django.db.models.QuerySet.update_or_create https://djangosnippets.org/snippets/1114/ def GroupOfProduct(request): group_id = request.POST.get('group') groups = Pro...
10
8
62,494,622
2020-6-21
https://stackoverflow.com/questions/62494622/python-how-to-remove-default-options-on-typer-cli
I made a simple CLI using Typer and Pillow to change image opacity and this program only have one option: opacity. But when I run python opacity.py --help it gives me the two typerCLI options: Options: --install-completion [bash|zsh|fish|powershell|pwsh] Install completion for the specified shell. --show-completion [ba...
I met the same problem today, i couldn't find anything except this question so dived in the source to find how Typer automatically adds this line in app, so i found this, when Typer initialiazing itself it automatically sets add_completion to True class Typer: def __init__(add_completion: bool = True) So when you init...
12
17
62,436,302
2020-6-17
https://stackoverflow.com/questions/62436302/extract-target-from-tensorflow-prefetchdataset
I am still learning tensorflow and keras, and I suspect this question has a very easy answer I'm just missing due to lack of familiarity. I have a PrefetchDataset object: > print(tf_test) $ <PrefetchDataset shapes: ((None, 99), (None,)), types: (tf.float32, tf.int64)> ...made up of features and a target. I can iterate...
You can convert it to a list with list(ds) and then recompile it as a normal Dataset with tf.data.Dataset.from_tensor_slices(list(ds)). From there your nightmare begins again but at least it's a nightmare that other people have had before. Note that for more complex datasets (e.g. nested dictionaries) you will need mor...
34
15
62,436,243
2020-6-17
https://stackoverflow.com/questions/62436243/attributeerror-smote-object-has-no-attribute-validate-data
I'm resampling my data (multiclass) by using SMOTE. sm = SMOTE(random_state=1) X_res, Y_res = sm.fit_resample(X_train, Y_train) However, I'm getting this attribute error. Can anyone help?
Short answer You need to upgrade scikit-learn to version 0.23.1. Long answer The newest version 0.7.0 of imbalanced-learn seems to have an undocumented dependency on scikit-learn v0.23.1. It would give you AttributeError: 'SMOTE' object has no attribute '_validate_data' if your scikit-learnis 0.22 or below. If you are ...
18
20
62,442,212
2020-6-18
https://stackoverflow.com/questions/62442212/aws-elastic-beanstalk-container-commands-failing
I've been having a hard time trying to get a successful deployment of my Django Web App to AWS' Elastic Beanstalk. I am able to deploy my app from the EB CLI on my local machine with no problem at all until I add a list of container_commands config file inside a .ebextensions folder. Here are the contents of my config ...
Finally got to the bottom of it all, after deep-diving through the AWS docs and forums... Essentially, there were a lot of changes that came along with Beanstalk moving from Amazon Linux to Amazon Linux 2. A lot of these changes are vaguely mentioned here. One major difference for the Python platform as mentioned in th...
20
32
62,457,956
2020-6-18
https://stackoverflow.com/questions/62457956/decorators-on-python-abstractmethods
I have an abstract base class in Python which defines an abstract method. I want to decorate it with a timer function such that every class extending and implementing this base class is timed and doesn't need to be manually annotated. Here's what I have import functools import time import abc class Test(metaclass=abc.A...
Use __init_subclass__ to apply the timer decorator for you. (timer, by the way, doesn't need to be defined in the class; it's more general than that.) __init_subclass__ is also a more appropriate place to determine if apply is callable. import abc import functools import time def timer(func): @functools.wraps(func) def...
9
7
62,495,112
2020-6-21
https://stackoverflow.com/questions/62495112/aligning-and-cropping-same-scene-images
Hello I have different images taken using exposure bracketing (same scene different exposures), I need to align the images and crop each one of them in order for them to be matching exactly. (since there was camera shake when these images were taken) I don't want to merge them, i just want to cut, rotate, or scale ..et...
On this answer I describe an approach to achieve Image Alignment which consists on using the euclidean model to transform image 1 (on the left) and image 3 (on the right) according to image 2, the center image. However, I would like to quickly point out that the images shared are very challenging: not only there's a ...
9
12
62,545,411
2020-6-23
https://stackoverflow.com/questions/62545411/how-to-create-a-title-with-a-newline-for-a-chart-in-plotly
I need to create a plot on plotly with a newline. Preferably the text on the top is larger than the second line, but not necessary. fig.update_layout( title=go.layout.Title( text=title, xref="paper", x=0.5, ), For the title I have tried title = "Hello \n World" title = "Hello" + "\n" + "World" title = "$Hello \\ World...
You can add a <br> tag to the title and it will be interpreted as an HTML line break. This is supported by this doc. You can see the result in the following example: from dash import Dash import dash_core_components as dcc import dash_html_components as html external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLw...
11
34
62,543,302
2020-6-23
https://stackoverflow.com/questions/62543302/python-pylintraising-format-tuple-exception-arguments-suggest-string-formattin
With a simple custom exception class defined as: class MyError(Exception): pass And this call: foo = 'Some more info' raise MyError("%s: there was an error", foo) pylint gives: Exception arguments suggest string formatting might be intended pylint(raising-format-tuple) What does this message mean?
Any one of these fixes the message, depending on your version of Python. foo = 'Some more info' raise MyError("%s: there was an error" % foo ) raise MyError("{}: there was an error".format(foo)) raise MyError(f"{foo}: there was an error") The message is triggered when pylint sees the %s tag in the string with no follo...
9
19
62,502,668
2020-6-21
https://stackoverflow.com/questions/62502668/can-flake8-fix-my-python-whitespace-problems
I just learned about flake8, which calls itself "Flake8: Your Tool For Style Guide Enforcement." While flake8 will find many Python whitespace errors and enforce PEP8, it does not appear to have an option to automatically fix problematic python code. autopep8 does appear to have this option (called --in-place), but fla...
no, flake8 is a linter only -- that is, it only checks your code. (technically, flake8 doesn't even check your code -- it is just a framework for other linters to plug into and provides inclusion / exclusion / etc. on top of other tools) if you want something which fixes your code, you'll want a code formatter to do co...
21
29
62,539,255
2020-6-23
https://stackoverflow.com/questions/62539255/grouping-two-numpy-arrays-to-a-dict-of-lists
I have two large NumPy arrays each with shape of (519990,) that look something like this: Order = array([0, 0, 0, 5, 6, 10, 14, 14, 14, 23, 23, 39]) Letters = array([A, B, C, D, E, F, G, H, I, J, K, L]) As you can see the first array is always in ascending and a positive number. I would like to group everything within...
We could leverage the fact that Order is sorted, to simply slice Letters after getting the intervaled-indices, like so - def numpy_slice(Order, Letters): Order = np.asarray(Order) Letters = np.asarray(Letters) idx = np.flatnonzero(np.r_[True,Order[:-1]!=Order[1:],True]) return {Order[i]:Letters[i:j] for (i,j) in zip(id...
9
8